mirror of
https://gitlab.com/mbugroup/lti-web-client.git
synced 2026-06-12 03:21:42 +00:00
Merge remote-tracking branch 'origin/development' into staging
This commit is contained in:
Generated
+6
-146
@@ -9,7 +9,6 @@
|
|||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@react-pdf/renderer": "^4.3.1",
|
"@react-pdf/renderer": "^4.3.1",
|
||||||
"@supabase/supabase-js": "^2.89.0",
|
|
||||||
"@tanstack/match-sorter-utils": "^8.19.4",
|
"@tanstack/match-sorter-utils": "^8.19.4",
|
||||||
"@tanstack/react-table": "^8.21.3",
|
"@tanstack/react-table": "^8.21.3",
|
||||||
"axios": "^1.12.2",
|
"axios": "^1.12.2",
|
||||||
@@ -3951,86 +3950,6 @@
|
|||||||
"integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",
|
"integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@supabase/auth-js": {
|
|
||||||
"version": "2.89.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.89.0.tgz",
|
|
||||||
"integrity": "sha512-wiWZdz8WMad8LQdJMWYDZ2SJtZP5MwMqzQq3ehtW2ngiI3UTgbKiFrvMUUS3KADiVlk4LiGfODB2mrYx7w2f8w==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"tslib": "2.8.1"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@supabase/functions-js": {
|
|
||||||
"version": "2.89.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@supabase/functions-js/-/functions-js-2.89.0.tgz",
|
|
||||||
"integrity": "sha512-XEueaC5gMe5NufNYfBh9kPwJlP5M2f+Ogr8rvhmRDAZNHgY6mI35RCkYDijd92pMcNM7g8pUUJov93UGUnqfyw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"tslib": "2.8.1"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@supabase/postgrest-js": {
|
|
||||||
"version": "2.89.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@supabase/postgrest-js/-/postgrest-js-2.89.0.tgz",
|
|
||||||
"integrity": "sha512-/b0fKrxV9i7RNOEXMno/I1862RsYhuUo+Q6m6z3ar1f4ulTMXnDfv0y4YYxK2POcgrOXQOgKYQx1eArybyNvtg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"tslib": "2.8.1"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@supabase/realtime-js": {
|
|
||||||
"version": "2.89.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@supabase/realtime-js/-/realtime-js-2.89.0.tgz",
|
|
||||||
"integrity": "sha512-aMOvfDb2a52u6PX6jrrjvACHXGV3zsOlWRzZsTIOAJa0hOVvRp01AwC1+nLTGUzxzezejrYeCX+KnnM1xHdl+w==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@types/phoenix": "^1.6.6",
|
|
||||||
"@types/ws": "^8.18.1",
|
|
||||||
"tslib": "2.8.1",
|
|
||||||
"ws": "^8.18.2"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@supabase/storage-js": {
|
|
||||||
"version": "2.89.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@supabase/storage-js/-/storage-js-2.89.0.tgz",
|
|
||||||
"integrity": "sha512-6zKcXofk/M/4Eato7iqpRh+B+vnxeiTumCIP+Tz26xEqIiywzD9JxHq+udRrDuv6hXE+pmetvJd8n5wcf4MFRQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"iceberg-js": "^0.8.1",
|
|
||||||
"tslib": "2.8.1"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@supabase/supabase-js": {
|
|
||||||
"version": "2.89.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@supabase/supabase-js/-/supabase-js-2.89.0.tgz",
|
|
||||||
"integrity": "sha512-KlaRwSfFA0fD73PYVMHj5/iXFtQGCcX7PSx0FdQwYEEw9b2wqM7GxadY+5YwcmuEhalmjFB/YvqaoNVF+sWUlg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@supabase/auth-js": "2.89.0",
|
|
||||||
"@supabase/functions-js": "2.89.0",
|
|
||||||
"@supabase/postgrest-js": "2.89.0",
|
|
||||||
"@supabase/realtime-js": "2.89.0",
|
|
||||||
"@supabase/storage-js": "2.89.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@swc/helpers": {
|
"node_modules/@swc/helpers": {
|
||||||
"version": "0.5.15",
|
"version": "0.5.15",
|
||||||
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.15.tgz",
|
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.15.tgz",
|
||||||
@@ -4471,6 +4390,7 @@
|
|||||||
"version": "20.19.23",
|
"version": "20.19.23",
|
||||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.23.tgz",
|
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.23.tgz",
|
||||||
"integrity": "sha512-yIdlVVVHXpmqRhtyovZAcSy0MiPcYWGkoO4CGe/+jpP0hmNuihm4XhHbADpK++MsiLHP5MVlv+bcgdF99kSiFQ==",
|
"integrity": "sha512-yIdlVVVHXpmqRhtyovZAcSy0MiPcYWGkoO4CGe/+jpP0hmNuihm4XhHbADpK++MsiLHP5MVlv+bcgdF99kSiFQ==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"undici-types": "~6.21.0"
|
"undici-types": "~6.21.0"
|
||||||
@@ -4488,12 +4408,6 @@
|
|||||||
"integrity": "sha512-dISoDXWWQwUquiKsyZ4Ng+HX2KsPL7LyHKHQwgGFEA3IaKac4Obd+h2a/a6waisAoepJlBcx9paWqjA8/HVjCw==",
|
"integrity": "sha512-dISoDXWWQwUquiKsyZ4Ng+HX2KsPL7LyHKHQwgGFEA3IaKac4Obd+h2a/a6waisAoepJlBcx9paWqjA8/HVjCw==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@types/phoenix": {
|
|
||||||
"version": "1.6.7",
|
|
||||||
"resolved": "https://registry.npmjs.org/@types/phoenix/-/phoenix-1.6.7.tgz",
|
|
||||||
"integrity": "sha512-oN9ive//QSBkf19rfDv45M7eZPi0eEXylht2OLEXicu5b4KoQ1OzXIw+xDSGWxSxe1JmepRR/ZH283vsu518/Q==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/@types/raf": {
|
"node_modules/@types/raf": {
|
||||||
"version": "3.4.3",
|
"version": "3.4.3",
|
||||||
"resolved": "https://registry.npmjs.org/@types/raf/-/raf-3.4.3.tgz",
|
"resolved": "https://registry.npmjs.org/@types/raf/-/raf-3.4.3.tgz",
|
||||||
@@ -4506,7 +4420,6 @@
|
|||||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.2.tgz",
|
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.2.tgz",
|
||||||
"integrity": "sha512-6mDvHUFSjyT2B2yeNx2nUgMxh9LtOWvkhIU3uePn2I2oyNymUAX1NIsdgviM4CH+JSrp2D2hsMvJOkxY+0wNRA==",
|
"integrity": "sha512-6mDvHUFSjyT2B2yeNx2nUgMxh9LtOWvkhIU3uePn2I2oyNymUAX1NIsdgviM4CH+JSrp2D2hsMvJOkxY+0wNRA==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"csstype": "^3.0.2"
|
"csstype": "^3.0.2"
|
||||||
}
|
}
|
||||||
@@ -4517,7 +4430,6 @@
|
|||||||
"integrity": "sha512-9KQPoO6mZCi7jcIStSnlOWn2nEF3mNmyr3rIAsGnAbQKYbRLyqmeSc39EVgtxXVia+LMT8j3knZLAZAh+xLmrw==",
|
"integrity": "sha512-9KQPoO6mZCi7jcIStSnlOWn2nEF3mNmyr3rIAsGnAbQKYbRLyqmeSc39EVgtxXVia+LMT8j3knZLAZAh+xLmrw==",
|
||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@types/react": "^19.2.0"
|
"@types/react": "^19.2.0"
|
||||||
}
|
}
|
||||||
@@ -4544,15 +4456,6 @@
|
|||||||
"integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==",
|
"integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@types/ws": {
|
|
||||||
"version": "8.18.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
|
|
||||||
"integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@types/node": "*"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@typescript-eslint/eslint-plugin": {
|
"node_modules/@typescript-eslint/eslint-plugin": {
|
||||||
"version": "8.46.2",
|
"version": "8.46.2",
|
||||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.46.2.tgz",
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.46.2.tgz",
|
||||||
@@ -4599,7 +4502,6 @@
|
|||||||
"integrity": "sha512-BnOroVl1SgrPLywqxyqdJ4l3S2MsKVLDVxZvjI1Eoe8ev2r3kGDo+PcMihNmDE+6/KjkTubSJnmqGZZjQSBq/g==",
|
"integrity": "sha512-BnOroVl1SgrPLywqxyqdJ4l3S2MsKVLDVxZvjI1Eoe8ev2r3kGDo+PcMihNmDE+6/KjkTubSJnmqGZZjQSBq/g==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@typescript-eslint/scope-manager": "8.46.2",
|
"@typescript-eslint/scope-manager": "8.46.2",
|
||||||
"@typescript-eslint/types": "8.46.2",
|
"@typescript-eslint/types": "8.46.2",
|
||||||
@@ -5123,7 +5025,6 @@
|
|||||||
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
|
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"bin": {
|
"bin": {
|
||||||
"acorn": "bin/acorn"
|
"acorn": "bin/acorn"
|
||||||
},
|
},
|
||||||
@@ -5829,8 +5730,7 @@
|
|||||||
"version": "3.1.3",
|
"version": "3.1.3",
|
||||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz",
|
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz",
|
||||||
"integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==",
|
"integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==",
|
||||||
"license": "MIT",
|
"license": "MIT"
|
||||||
"peer": true
|
|
||||||
},
|
},
|
||||||
"node_modules/d3-array": {
|
"node_modules/d3-array": {
|
||||||
"version": "3.2.4",
|
"version": "3.2.4",
|
||||||
@@ -6206,8 +6106,7 @@
|
|||||||
"version": "8.6.0",
|
"version": "8.6.0",
|
||||||
"resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.6.0.tgz",
|
"resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.6.0.tgz",
|
||||||
"integrity": "sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==",
|
"integrity": "sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==",
|
||||||
"license": "MIT",
|
"license": "MIT"
|
||||||
"peer": true
|
|
||||||
},
|
},
|
||||||
"node_modules/embla-carousel-react": {
|
"node_modules/embla-carousel-react": {
|
||||||
"version": "8.6.0",
|
"version": "8.6.0",
|
||||||
@@ -6468,7 +6367,6 @@
|
|||||||
"integrity": "sha512-t5aPOpmtJcZcz5UJyY2GbvpDlsK5E8JqRqoKtfiKE3cNh437KIqfJr3A3AKf5k64NPx6d0G3dno6XDY05PqPtw==",
|
"integrity": "sha512-t5aPOpmtJcZcz5UJyY2GbvpDlsK5E8JqRqoKtfiKE3cNh437KIqfJr3A3AKf5k64NPx6d0G3dno6XDY05PqPtw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@eslint-community/eslint-utils": "^4.8.0",
|
"@eslint-community/eslint-utils": "^4.8.0",
|
||||||
"@eslint-community/regexpp": "^4.12.1",
|
"@eslint-community/regexpp": "^4.12.1",
|
||||||
@@ -6642,7 +6540,6 @@
|
|||||||
"integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==",
|
"integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@rtsao/scc": "^1.1.0",
|
"@rtsao/scc": "^1.1.0",
|
||||||
"array-includes": "^3.1.9",
|
"array-includes": "^3.1.9",
|
||||||
@@ -7519,15 +7416,6 @@
|
|||||||
"integrity": "sha512-fXHXcGFTXOvZTSkPJuGOQf5Lv5T/R2itiiCVPg9LxAje5D00O0pP83yJShFq5V89Ly//Gt6acj7z8pbBr34stw==",
|
"integrity": "sha512-fXHXcGFTXOvZTSkPJuGOQf5Lv5T/R2itiiCVPg9LxAje5D00O0pP83yJShFq5V89Ly//Gt6acj7z8pbBr34stw==",
|
||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
"node_modules/iceberg-js": {
|
|
||||||
"version": "0.8.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/iceberg-js/-/iceberg-js-0.8.1.tgz",
|
|
||||||
"integrity": "sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/ignore": {
|
"node_modules/ignore": {
|
||||||
"version": "5.3.2",
|
"version": "5.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
|
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
|
||||||
@@ -8160,7 +8048,6 @@
|
|||||||
"resolved": "https://registry.npmjs.org/jspdf/-/jspdf-3.0.4.tgz",
|
"resolved": "https://registry.npmjs.org/jspdf/-/jspdf-3.0.4.tgz",
|
||||||
"integrity": "sha512-dc6oQ8y37rRcHn316s4ngz/nOjayLF/FFxBF4V9zamQKRqXxyiH1zagkCdktdWhtoQId5K20xt1lB90XzkB+hQ==",
|
"integrity": "sha512-dc6oQ8y37rRcHn316s4ngz/nOjayLF/FFxBF4V9zamQKRqXxyiH1zagkCdktdWhtoQId5K20xt1lB90XzkB+hQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@babel/runtime": "^7.28.4",
|
"@babel/runtime": "^7.28.4",
|
||||||
"fast-png": "^6.2.0",
|
"fast-png": "^6.2.0",
|
||||||
@@ -9380,7 +9267,6 @@
|
|||||||
"resolved": "https://registry.npmjs.org/react/-/react-19.2.3.tgz",
|
"resolved": "https://registry.npmjs.org/react/-/react-19.2.3.tgz",
|
||||||
"integrity": "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==",
|
"integrity": "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
@@ -9411,7 +9297,6 @@
|
|||||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.3.tgz",
|
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.3.tgz",
|
||||||
"integrity": "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg==",
|
"integrity": "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"scheduler": "^0.27.0"
|
"scheduler": "^0.27.0"
|
||||||
},
|
},
|
||||||
@@ -9479,8 +9364,7 @@
|
|||||||
"version": "16.13.1",
|
"version": "16.13.1",
|
||||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
|
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
|
||||||
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
|
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
|
||||||
"license": "MIT",
|
"license": "MIT"
|
||||||
"peer": true
|
|
||||||
},
|
},
|
||||||
"node_modules/react-number-format": {
|
"node_modules/react-number-format": {
|
||||||
"version": "5.4.4",
|
"version": "5.4.4",
|
||||||
@@ -9497,7 +9381,6 @@
|
|||||||
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz",
|
||||||
"integrity": "sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g==",
|
"integrity": "sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@types/use-sync-external-store": "^0.0.6",
|
"@types/use-sync-external-store": "^0.0.6",
|
||||||
"use-sync-external-store": "^1.4.0"
|
"use-sync-external-store": "^1.4.0"
|
||||||
@@ -9666,8 +9549,7 @@
|
|||||||
"version": "5.0.1",
|
"version": "5.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
|
||||||
"integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",
|
"integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",
|
||||||
"license": "MIT",
|
"license": "MIT"
|
||||||
"peer": true
|
|
||||||
},
|
},
|
||||||
"node_modules/redux-thunk": {
|
"node_modules/redux-thunk": {
|
||||||
"version": "3.1.0",
|
"version": "3.1.0",
|
||||||
@@ -10533,7 +10415,6 @@
|
|||||||
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=12"
|
"node": ">=12"
|
||||||
},
|
},
|
||||||
@@ -10701,7 +10582,6 @@
|
|||||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"peer": true,
|
|
||||||
"bin": {
|
"bin": {
|
||||||
"tsc": "bin/tsc",
|
"tsc": "bin/tsc",
|
||||||
"tsserver": "bin/tsserver"
|
"tsserver": "bin/tsserver"
|
||||||
@@ -10733,6 +10613,7 @@
|
|||||||
"version": "6.21.0",
|
"version": "6.21.0",
|
||||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
|
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
|
||||||
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
|
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/unicode-properties": {
|
"node_modules/unicode-properties": {
|
||||||
@@ -11064,27 +10945,6 @@
|
|||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/ws": {
|
|
||||||
"version": "8.18.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
|
|
||||||
"integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=10.0.0"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"bufferutil": "^4.0.1",
|
|
||||||
"utf-8-validate": ">=5.0.2"
|
|
||||||
},
|
|
||||||
"peerDependenciesMeta": {
|
|
||||||
"bufferutil": {
|
|
||||||
"optional": true
|
|
||||||
},
|
|
||||||
"utf-8-validate": {
|
|
||||||
"optional": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/xlsx": {
|
"node_modules/xlsx": {
|
||||||
"version": "0.20.3",
|
"version": "0.20.3",
|
||||||
"resolved": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
|
"resolved": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
|
||||||
|
|||||||
@@ -12,7 +12,6 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@react-pdf/renderer": "^4.3.1",
|
"@react-pdf/renderer": "^4.3.1",
|
||||||
"@supabase/supabase-js": "^2.89.0",
|
|
||||||
"@tanstack/match-sorter-utils": "^8.19.4",
|
"@tanstack/match-sorter-utils": "^8.19.4",
|
||||||
"@tanstack/react-table": "^8.21.3",
|
"@tanstack/react-table": "^8.21.3",
|
||||||
"axios": "^1.12.2",
|
"axios": "^1.12.2",
|
||||||
|
|||||||
@@ -7,26 +7,58 @@ import ClosingDetail from '@/components/pages/closing/ClosingDetail';
|
|||||||
|
|
||||||
import { ClosingApi } from '@/services/api/closing';
|
import { ClosingApi } from '@/services/api/closing';
|
||||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||||
|
import { FlockApi } from '@/services/api/master-data';
|
||||||
|
import { ProjectFlockApi } from '@/services/api/production/project-flock';
|
||||||
|
import { ProjectFlockKandangApi } from '@/services/api/production';
|
||||||
|
|
||||||
const ClosingDetailPage = () => {
|
const ClosingDetailPage = () => {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
|
|
||||||
const closingId = searchParams.get('closingId');
|
const closingId = searchParams.get('closingId');
|
||||||
|
const kandangId = searchParams.get('kandangId'); // project flock kandang ID
|
||||||
|
|
||||||
const { data: closing, isLoading: isLoadingClosing } = useSWR(
|
const { data: closing, isLoading: isLoadingClosing } = useSWR(
|
||||||
closingId,
|
closingId,
|
||||||
(id: number) => ClosingApi.getGeneralInfo(id)
|
(id: number) => ClosingApi.getGeneralInfo(id)
|
||||||
);
|
);
|
||||||
|
|
||||||
// const { data: salesData, isLoading: isLoadingSales } = useSWR(
|
// WORKAROUND - get flock data from closing ID
|
||||||
// closingId ? `sales-${closingId}` : null,
|
const { data: projectData, isLoading: isLoadingProject } = useSWR(
|
||||||
// () => ClosingApi.getPenjualan(Number(closingId))
|
`flock-${closingId}`,
|
||||||
// );
|
() => ProjectFlockApi.getSingle(Number(closingId))
|
||||||
|
);
|
||||||
|
// WORKAROUND - get kandang data from closing ID
|
||||||
|
const { data: kandangData, isLoading: isLoadingKandang } = useSWR(
|
||||||
|
kandangId ? `kandang-${closingId}-${kandangId}` : null,
|
||||||
|
() => ProjectFlockKandangApi.getSingle(Number(kandangId))
|
||||||
|
);
|
||||||
|
|
||||||
|
const { data: salesData, isLoading: isLoadingSales } = useSWR(
|
||||||
|
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(
|
const { data: hppEkspedisiData, isLoading: isLoadingHppEkspedisi } = useSWR(
|
||||||
closingId ? `hpp-ekspedisi-${closingId}` : null,
|
kandangId
|
||||||
() => ClosingApi.getHppEkspedisi(Number(closingId))
|
? `hpp-ekspedisi-${closingId}-${kandangId}`
|
||||||
|
: closingId
|
||||||
|
? `hpp-ekspedisi-${closingId}`
|
||||||
|
: null,
|
||||||
|
() =>
|
||||||
|
kandangId
|
||||||
|
? ClosingApi.getHppEkspedisiByKandang(
|
||||||
|
Number(closingId),
|
||||||
|
Number(kandangId)
|
||||||
|
)
|
||||||
|
: ClosingApi.getHppEkspedisi(Number(closingId))
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!closingId) {
|
if (!closingId) {
|
||||||
@@ -44,8 +76,12 @@ const ClosingDetailPage = () => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const isLoading = isLoadingClosing || isLoadingHppEkspedisi;
|
const isLoading =
|
||||||
// const isLoading = isLoadingClosing || isLoadingSales || isLoadingHppEkspedisi;
|
isLoadingClosing ||
|
||||||
|
isLoadingSales ||
|
||||||
|
isLoadingHppEkspedisi ||
|
||||||
|
isLoadingProject ||
|
||||||
|
isLoadingKandang;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className='w-full p-4 flex flex-row justify-center'>
|
<div className='w-full p-4 flex flex-row justify-center'>
|
||||||
@@ -55,12 +91,18 @@ const ClosingDetailPage = () => {
|
|||||||
<ClosingDetail
|
<ClosingDetail
|
||||||
id={Number(closingId)}
|
id={Number(closingId)}
|
||||||
initialValue={closing.data}
|
initialValue={closing.data}
|
||||||
// salesData={isResponseSuccess(salesData) ? salesData.data : undefined}
|
salesData={isResponseSuccess(salesData) ? salesData.data : undefined}
|
||||||
hppExpeditionData={
|
hppExpeditionData={
|
||||||
isResponseSuccess(hppEkspedisiData)
|
isResponseSuccess(hppEkspedisiData)
|
||||||
? hppEkspedisiData.data
|
? hppEkspedisiData.data
|
||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
|
projectData={
|
||||||
|
isResponseSuccess(projectData) ? projectData.data : undefined
|
||||||
|
}
|
||||||
|
kandangData={
|
||||||
|
isResponseSuccess(kandangData) ? kandangData.data : undefined
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { MasterConfigurationContent } from '@/figma-make/components/pages/master-data/configuration/MasterConfigurationContent';
|
||||||
|
|
||||||
|
const MasterConfigurationPage = () => {
|
||||||
|
return (
|
||||||
|
<section className='w-full'>
|
||||||
|
<MasterConfigurationContent />
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default MasterConfigurationPage;
|
||||||
@@ -37,7 +37,7 @@ const ExpenseRealization = () => {
|
|||||||
const isExpenseCanBeRealized =
|
const isExpenseCanBeRealized =
|
||||||
isResponseSuccess(expense) &&
|
isResponseSuccess(expense) &&
|
||||||
expense.data.latest_approval.action !== 'REJECTED' &&
|
expense.data.latest_approval.action !== 'REJECTED' &&
|
||||||
expense.data.latest_approval.step_number === 3;
|
expense.data.latest_approval.step_number === 4;
|
||||||
|
|
||||||
if (isResponseSuccess(expense) && !isExpenseCanBeRealized) {
|
if (isResponseSuccess(expense) && !isExpenseCanBeRealized) {
|
||||||
if (typeof window !== 'undefined') {
|
if (typeof window !== 'undefined') {
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import FinanceTabs from '@/components/pages/report/finance/FinanceTabs';
|
||||||
|
|
||||||
|
const Finance = () => {
|
||||||
|
return <FinanceTabs />;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Finance;
|
||||||
@@ -39,8 +39,8 @@ const FloatingActionsButton = ({
|
|||||||
// Jika tidak ada baris yang dipilih, jangan tampilkan FAB
|
// Jika tidak ada baris yang dipilih, jangan tampilkan FAB
|
||||||
const positionStyles =
|
const positionStyles =
|
||||||
selectedRowIds.length > 0
|
selectedRowIds.length > 0
|
||||||
? 'bottom-[10%] opacity-100'
|
? 'bottom-[5%] opacity-100'
|
||||||
: 'bottom-[-10%] opacity-0';
|
: 'bottom-[-5%] opacity-0';
|
||||||
|
|
||||||
// Helper untuk menentukan gaya warna tombol approval
|
// Helper untuk menentukan gaya warna tombol approval
|
||||||
const getApprovalColor = (action: 'APPROVED' | 'REJECTED') => {
|
const getApprovalColor = (action: 'APPROVED' | 'REJECTED') => {
|
||||||
@@ -60,7 +60,7 @@ const FloatingActionsButton = ({
|
|||||||
// Container utama FAB
|
// Container utama FAB
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
`absolute ${positionStyles} inset-x-1/2 -translate-x-1/2 z-50`,
|
`fixed ${positionStyles} inset-x-1/2 -translate-x-1/2 z-50`,
|
||||||
'mx-auto w-full max-w-sm sm:mx-0 bg-base-300 p-4 rounded-xl shadow-md transition-all duration-300 transform',
|
'mx-auto w-full max-w-sm sm:mx-0 bg-base-300 p-4 rounded-xl shadow-md transition-all duration-300 transform',
|
||||||
'bg-slate-950 backdrop-blur-md'
|
'bg-slate-950 backdrop-blur-md'
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import Alert from '@/components/Alert';
|
import Alert from '@/components/Alert';
|
||||||
import Button from '@/components/Button';
|
import Button from '@/components/Button';
|
||||||
import { Icon } from '@iconify/react';
|
import { Icon } from '@iconify/react';
|
||||||
|
import { useState } from 'react';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Alert Unique Error List
|
* Alert Unique Error List
|
||||||
@@ -14,8 +15,10 @@ const AlertErrorList = ({
|
|||||||
formErrorList: string[];
|
formErrorList: string[];
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
}) => {
|
}) => {
|
||||||
|
if (formErrorList.length === 0) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Alert color='error' className='flex flex-col gap-2 px-4 m-4'>
|
<Alert color='error' className='w-full flex flex-col gap-2 px-4 m-4'>
|
||||||
<div className='flex justify-between items-center gap-2 w-full'>
|
<div className='flex justify-between items-center gap-2 w-full'>
|
||||||
<div className='flex items-center gap-2'>
|
<div className='flex items-center gap-2'>
|
||||||
<Icon icon='material-symbols:error-outline' width={24} height={24} />
|
<Icon icon='material-symbols:error-outline' width={24} height={24} />
|
||||||
|
|||||||
@@ -19,12 +19,16 @@ import ClosingOverheadTabContent from '@/components/pages/closing/ClosingOverhea
|
|||||||
import ClosingFinanceTabContent from '@/components/pages/closing/ClosingFinanceTabContent';
|
import ClosingFinanceTabContent from '@/components/pages/closing/ClosingFinanceTabContent';
|
||||||
import SalesReportTable from '@/components/pages/closing/sale/SalesReportTable';
|
import SalesReportTable from '@/components/pages/closing/sale/SalesReportTable';
|
||||||
import HppExpeditionReportTable from './hpp-ekspedisi/HppExpeditionReportTable';
|
import HppExpeditionReportTable from './hpp-ekspedisi/HppExpeditionReportTable';
|
||||||
|
import ClosingKandangList from '@/components/pages/closing/ClosingKandangList';
|
||||||
|
import { ProjectFlock } from '@/types/api/production/project-flock';
|
||||||
|
import { ProjectFlockKandang } from '@/types/api/production/project-flock-kandang';
|
||||||
interface ClosingDetailProps {
|
interface ClosingDetailProps {
|
||||||
id: number;
|
id: number;
|
||||||
initialValue?: ClosingGeneralInformation;
|
initialValue?: ClosingGeneralInformation;
|
||||||
salesData?: BaseClosingSales;
|
salesData?: BaseClosingSales;
|
||||||
hppExpeditionData?: ClosingHppExpedition;
|
hppExpeditionData?: ClosingHppExpedition;
|
||||||
|
projectData?: ProjectFlock;
|
||||||
|
kandangData?: ProjectFlockKandang;
|
||||||
}
|
}
|
||||||
|
|
||||||
const ClosingDetail: React.FC<ClosingDetailProps> = ({
|
const ClosingDetail: React.FC<ClosingDetailProps> = ({
|
||||||
@@ -32,6 +36,8 @@ const ClosingDetail: React.FC<ClosingDetailProps> = ({
|
|||||||
initialValue,
|
initialValue,
|
||||||
salesData,
|
salesData,
|
||||||
hppExpeditionData,
|
hppExpeditionData,
|
||||||
|
projectData,
|
||||||
|
kandangData,
|
||||||
}) => {
|
}) => {
|
||||||
const [activeTab, setActiveTab] = useState<string>('sapronak');
|
const [activeTab, setActiveTab] = useState<string>('sapronak');
|
||||||
|
|
||||||
@@ -52,11 +58,11 @@ const ClosingDetail: React.FC<ClosingDetailProps> = ({
|
|||||||
/>
|
/>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
// {
|
{
|
||||||
// id: 'penjualan',
|
id: 'penjualan',
|
||||||
// label: 'Penjualan',
|
label: 'Penjualan',
|
||||||
// content: <SalesReportTable initialValues={salesData} />,
|
content: <SalesReportTable initialValues={salesData} />,
|
||||||
// },
|
},
|
||||||
{
|
{
|
||||||
id: 'overhead',
|
id: 'overhead',
|
||||||
label: 'Overhead',
|
label: 'Overhead',
|
||||||
@@ -87,7 +93,9 @@ const ClosingDetail: React.FC<ClosingDetailProps> = ({
|
|||||||
<section className='w-full max-w-7xl pb-16'>
|
<section className='w-full max-w-7xl pb-16'>
|
||||||
<header className='flex flex-col gap-4'>
|
<header className='flex flex-col gap-4'>
|
||||||
<Button
|
<Button
|
||||||
href='/closing'
|
href={
|
||||||
|
!kandangData ? '/closing' : `/closing/detail/?closingId=${id}`
|
||||||
|
}
|
||||||
variant='link'
|
variant='link'
|
||||||
className='w-fit p-0 text-primary'
|
className='w-fit p-0 text-primary'
|
||||||
>
|
>
|
||||||
@@ -98,7 +106,18 @@ const ClosingDetail: React.FC<ClosingDetailProps> = ({
|
|||||||
<h1 className='text-2xl font-bold text-center'>Detail Closing</h1>
|
<h1 className='text-2xl font-bold text-center'>Detail Closing</h1>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<ClosingGeneralInformationTable initialValue={initialValue} />
|
<ClosingGeneralInformationTable
|
||||||
|
initialValue={initialValue}
|
||||||
|
projectData={projectData}
|
||||||
|
kandangData={kandangData}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{!kandangData && (
|
||||||
|
<ClosingKandangList
|
||||||
|
initialValue={initialValue}
|
||||||
|
projectData={projectData}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
<Tabs
|
<Tabs
|
||||||
activeTabId={activeTab}
|
activeTabId={activeTab}
|
||||||
|
|||||||
@@ -1,12 +1,29 @@
|
|||||||
import { ClosingGeneralInformation } from '@/types/api/closing';
|
import { ClosingGeneralInformation } from '@/types/api/closing';
|
||||||
|
import { ProjectFlock } from '@/types/api/production/project-flock';
|
||||||
|
import { ProjectFlockKandang } from '@/types/api/production/project-flock-kandang';
|
||||||
|
import { useMemo } from 'react';
|
||||||
|
|
||||||
interface ClosingGeneralInformationProps {
|
interface ClosingGeneralInformationProps {
|
||||||
initialValue?: ClosingGeneralInformation;
|
initialValue?: ClosingGeneralInformation;
|
||||||
|
projectData?: ProjectFlock;
|
||||||
|
kandangData?: ProjectFlockKandang;
|
||||||
}
|
}
|
||||||
|
|
||||||
const ClosingGeneralInformationTable = ({
|
const ClosingGeneralInformationTable = ({
|
||||||
initialValue,
|
initialValue,
|
||||||
|
projectData,
|
||||||
|
kandangData,
|
||||||
}: ClosingGeneralInformationProps) => {
|
}: ClosingGeneralInformationProps) => {
|
||||||
|
const chickinPopulation = useMemo(() => {
|
||||||
|
if (kandangData) {
|
||||||
|
return kandangData?.chickins?.reduce(
|
||||||
|
(acc, chickin) => acc + chickin.usage_qty,
|
||||||
|
0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}, [kandangData]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className='w-full my-4 @container'>
|
<div className='w-full my-4 @container'>
|
||||||
<div className='flex flex-col @sm:flex-row gap-4'>
|
<div className='flex flex-col @sm:flex-row gap-4'>
|
||||||
@@ -17,7 +34,9 @@ const ClosingGeneralInformationTable = ({
|
|||||||
<tr>
|
<tr>
|
||||||
<td>Lokasi</td>
|
<td>Lokasi</td>
|
||||||
<td>:</td>
|
<td>:</td>
|
||||||
<td>{initialValue?.location_name}</td>
|
<td>
|
||||||
|
{initialValue?.location_name ?? projectData?.location?.name}
|
||||||
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<td>Periode</td>
|
<td>Periode</td>
|
||||||
@@ -27,12 +46,20 @@ const ClosingGeneralInformationTable = ({
|
|||||||
<tr>
|
<tr>
|
||||||
<td>Project Flock</td>
|
<td>Project Flock</td>
|
||||||
<td>:</td>
|
<td>:</td>
|
||||||
<td>{initialValue?.project_flock?.name}</td>
|
<td>
|
||||||
|
{initialValue?.project_flock?.name ??
|
||||||
|
projectData?.flock_name}
|
||||||
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<td>Populasi</td>
|
<td>Populasi</td>
|
||||||
<td>:</td>
|
<td>:</td>
|
||||||
<td>{initialValue?.population} Ekor</td>
|
<td>
|
||||||
|
{!kandangData
|
||||||
|
? (initialValue?.population ?? 0)
|
||||||
|
: (chickinPopulation ?? 0)}{' '}
|
||||||
|
Ekor
|
||||||
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<td>Jenis Project</td>
|
<td>Jenis Project</td>
|
||||||
@@ -40,9 +67,13 @@ const ClosingGeneralInformationTable = ({
|
|||||||
<td>{initialValue?.project_type}</td>
|
<td>{initialValue?.project_type}</td>
|
||||||
</tr>
|
</tr>
|
||||||
<tr className='table-row @sm:hidden'>
|
<tr className='table-row @sm:hidden'>
|
||||||
<td>Kandang Aktif</td>
|
<td>Kandang {!kandangData && 'Aktif'}</td>
|
||||||
<td>:</td>
|
<td>:</td>
|
||||||
<td>{initialValue?.active_house_count} Kandang</td>
|
<td>
|
||||||
|
{!kandangData
|
||||||
|
? `${initialValue?.active_house_count} Kandang`
|
||||||
|
: kandangData?.kandang?.name}
|
||||||
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
<tr className='table-row @sm:hidden'>
|
<tr className='table-row @sm:hidden'>
|
||||||
<td>Status Pembayaran Penjualan</td>
|
<td>Status Pembayaran Penjualan</td>
|
||||||
@@ -69,9 +100,13 @@ const ClosingGeneralInformationTable = ({
|
|||||||
<table className='table table-zebra table-sm'>
|
<table className='table table-zebra table-sm'>
|
||||||
<tbody>
|
<tbody>
|
||||||
<tr>
|
<tr>
|
||||||
<td>Kandang Aktif</td>
|
<td>Kandang {!kandangData && 'Aktif'}</td>
|
||||||
<td>:</td>
|
<td>:</td>
|
||||||
<td>{initialValue?.active_house_count} Kandang</td>
|
<td>
|
||||||
|
{!kandangData
|
||||||
|
? `${initialValue?.active_house_count} Kandang`
|
||||||
|
: kandangData?.kandang?.name}
|
||||||
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<td>Status Pembayaran Penjualan</td>
|
<td>Status Pembayaran Penjualan</td>
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import Button from '@/components/Button';
|
||||||
|
import { ClosingGeneralInformation } from '@/types/api/closing';
|
||||||
|
import { ProjectFlock } from '@/types/api/production/project-flock';
|
||||||
|
|
||||||
|
const ClosingKandangList = ({
|
||||||
|
initialValue,
|
||||||
|
projectData,
|
||||||
|
}: {
|
||||||
|
initialValue?: ClosingGeneralInformation;
|
||||||
|
projectData?: ProjectFlock;
|
||||||
|
}) => {
|
||||||
|
return (
|
||||||
|
<div className='w-full my-4 @container'>
|
||||||
|
<div className='flex flex-col @sm:flex-row gap-4'>
|
||||||
|
<div className='w-full'>
|
||||||
|
<div className='overflow-x-auto'>
|
||||||
|
<h1 className='font-bold my-4'>Kandang</h1>
|
||||||
|
<div className='flex flex-wrap gap-2 mb-4'>
|
||||||
|
{projectData?.kandangs?.map((kandang) => (
|
||||||
|
<Button
|
||||||
|
key={kandang.id}
|
||||||
|
variant='outline'
|
||||||
|
href={`/closing/detail/?closingId=${initialValue?.flock_id}&kandangId=${kandang.project_flock_kandang_id}`}
|
||||||
|
className='min-w-32'
|
||||||
|
>
|
||||||
|
{kandang.name}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ClosingKandangList;
|
||||||
@@ -14,6 +14,7 @@ import useSWR from 'swr';
|
|||||||
import { ClosingApi } from '@/services/api/closing';
|
import { ClosingApi } from '@/services/api/closing';
|
||||||
import { isResponseSuccess } from '@/lib/api-helper';
|
import { isResponseSuccess } from '@/lib/api-helper';
|
||||||
import { ClosingGeneralInformation } from '@/types/api/closing';
|
import { ClosingGeneralInformation } from '@/types/api/closing';
|
||||||
|
import { useSearchParams } from 'next/navigation';
|
||||||
|
|
||||||
interface ClosingSapronakCalculationTableProps {
|
interface ClosingSapronakCalculationTableProps {
|
||||||
projectFlockId: number;
|
projectFlockId: number;
|
||||||
@@ -24,9 +25,12 @@ const ClosingSapronakCalculationTable = ({
|
|||||||
projectFlockId,
|
projectFlockId,
|
||||||
closingGeneralInformation,
|
closingGeneralInformation,
|
||||||
}: ClosingSapronakCalculationTableProps) => {
|
}: ClosingSapronakCalculationTableProps) => {
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
const kandangId = searchParams.get('kandangId');
|
||||||
|
|
||||||
const { data: sapronakCalculation, isLoading } = useSWR(
|
const { data: sapronakCalculation, isLoading } = useSWR(
|
||||||
`/closing/sapronak-calculation/${projectFlockId}`,
|
`/closing/sapronak-calculation/${projectFlockId}${kandangId ? `/${kandangId}` : ''}`,
|
||||||
() => ClosingApi.getPerhitunganSapronak(projectFlockId),
|
() => ClosingApi.getPerhitunganSapronak(projectFlockId, Number(kandangId)),
|
||||||
{
|
{
|
||||||
keepPreviousData: true,
|
keepPreviousData: true,
|
||||||
}
|
}
|
||||||
@@ -57,11 +61,11 @@ const ClosingSapronakCalculationTable = ({
|
|||||||
cell: (props) =>
|
cell: (props) =>
|
||||||
props.row.original.qty_in
|
props.row.original.qty_in
|
||||||
? formatNumber(props.row.original.qty_in as number)
|
? formatNumber(props.row.original.qty_in as number)
|
||||||
: '-',
|
: '0',
|
||||||
footer: total
|
footer: total
|
||||||
? () => (
|
? () => (
|
||||||
<div className='font-semibold text-gray-900'>
|
<div className='font-semibold text-gray-900'>
|
||||||
{total?.qty_in ? formatNumber(total?.qty_in) : '-'}
|
{total?.qty_in ? formatNumber(total?.qty_in) : '0'}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
: '',
|
: '',
|
||||||
@@ -72,11 +76,11 @@ const ClosingSapronakCalculationTable = ({
|
|||||||
cell: (props) =>
|
cell: (props) =>
|
||||||
props.row.original.qty_out
|
props.row.original.qty_out
|
||||||
? formatNumber(props.row.original.qty_out as number)
|
? formatNumber(props.row.original.qty_out as number)
|
||||||
: '-',
|
: '0',
|
||||||
footer: total
|
footer: total
|
||||||
? () => (
|
? () => (
|
||||||
<div className='font-semibold text-gray-900'>
|
<div className='font-semibold text-gray-900'>
|
||||||
{total?.qty_out ? formatNumber(total?.qty_out) : '-'}
|
{total?.qty_out ? formatNumber(total?.qty_out) : '0'}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
: '',
|
: '',
|
||||||
@@ -87,11 +91,11 @@ const ClosingSapronakCalculationTable = ({
|
|||||||
cell: (props) =>
|
cell: (props) =>
|
||||||
props.row.original.qty_used
|
props.row.original.qty_used
|
||||||
? formatNumber(props.row.original.qty_used as number)
|
? formatNumber(props.row.original.qty_used as number)
|
||||||
: '-',
|
: '0',
|
||||||
footer: total
|
footer: total
|
||||||
? () => (
|
? () => (
|
||||||
<div className='font-semibold text-gray-900'>
|
<div className='font-semibold text-gray-900'>
|
||||||
{total?.qty_used ? formatNumber(total?.qty_used) : '-'}
|
{total?.qty_used ? formatNumber(total?.qty_used) : '0'}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
: '',
|
: '',
|
||||||
@@ -173,20 +177,12 @@ const ClosingSapronakCalculationTable = ({
|
|||||||
[sapronakCalculation]
|
[sapronakCalculation]
|
||||||
);
|
);
|
||||||
|
|
||||||
const pulletColumns = useMemo(
|
|
||||||
() =>
|
|
||||||
isResponseSuccess(sapronakCalculation)
|
|
||||||
? createColumns(sapronakCalculation.data?.pullet?.total)
|
|
||||||
: createColumns(),
|
|
||||||
[sapronakCalculation]
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className='flex flex-col gap-4'>
|
<div className='flex flex-col gap-4'>
|
||||||
{/* Table DOC jika kategori Project Flock Growing */}
|
{/* Table DOC jika kategori Project Flock Growing */}
|
||||||
<Card
|
<Card
|
||||||
title={
|
title={
|
||||||
closingGeneralInformation?.project_category === 'GROWING'
|
closingGeneralInformation?.project_type == 'GROWING'
|
||||||
? 'DOC'
|
? 'DOC'
|
||||||
: 'Pullet'
|
: 'Pullet'
|
||||||
}
|
}
|
||||||
@@ -200,20 +196,17 @@ const ClosingSapronakCalculationTable = ({
|
|||||||
<Table<RowSapronakCalculation>
|
<Table<RowSapronakCalculation>
|
||||||
data={
|
data={
|
||||||
isResponseSuccess(sapronakCalculation)
|
isResponseSuccess(sapronakCalculation)
|
||||||
? ((closingGeneralInformation?.project_category === 'GROWING'
|
? (sapronakCalculation.data?.doc?.rows ?? [])
|
||||||
? sapronakCalculation.data?.doc?.rows
|
|
||||||
: sapronakCalculation.data?.pullet?.rows) ?? [])
|
|
||||||
: []
|
: []
|
||||||
}
|
}
|
||||||
columns={
|
columns={docColumns}
|
||||||
closingGeneralInformation?.project_category === 'GROWING'
|
|
||||||
? docColumns
|
|
||||||
: pulletColumns
|
|
||||||
}
|
|
||||||
className={{
|
className={{
|
||||||
containerClassName: 'my-4',
|
containerClassName: 'my-4',
|
||||||
}}
|
}}
|
||||||
renderFooter={isResponseSuccess(sapronakCalculation)}
|
renderFooter={
|
||||||
|
isResponseSuccess(sapronakCalculation) &&
|
||||||
|
sapronakCalculation.data?.doc?.rows.length > 0
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
@@ -236,7 +229,10 @@ const ClosingSapronakCalculationTable = ({
|
|||||||
className={{
|
className={{
|
||||||
containerClassName: 'my-4',
|
containerClassName: 'my-4',
|
||||||
}}
|
}}
|
||||||
renderFooter={isResponseSuccess(sapronakCalculation)}
|
renderFooter={
|
||||||
|
isResponseSuccess(sapronakCalculation) &&
|
||||||
|
sapronakCalculation.data?.ovk?.rows.length > 0
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
@@ -259,7 +255,10 @@ const ClosingSapronakCalculationTable = ({
|
|||||||
className={{
|
className={{
|
||||||
containerClassName: 'my-4',
|
containerClassName: 'my-4',
|
||||||
}}
|
}}
|
||||||
renderFooter={isResponseSuccess(sapronakCalculation)}
|
renderFooter={
|
||||||
|
isResponseSuccess(sapronakCalculation) &&
|
||||||
|
sapronakCalculation.data?.pakan?.rows.length > 0
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -215,31 +215,31 @@ const SalesReportTable = ({
|
|||||||
return kandang?.name || '-';
|
return kandang?.name || '-';
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
// {
|
||||||
id: 'payment_status',
|
// id: 'payment_status',
|
||||||
accessorKey: 'payment_status',
|
// accessorKey: 'payment_status',
|
||||||
header: 'Status Pembayaran',
|
// header: 'Status Pembayaran',
|
||||||
cell: (props) => {
|
// cell: (props) => {
|
||||||
const status = props.getValue() as string;
|
// const status = props.getValue() as string;
|
||||||
const getStatusColor = (status: string) => {
|
// const getStatusColor = (status: string) => {
|
||||||
if (!status) return 'neutral';
|
// if (!status) return 'neutral';
|
||||||
switch (status.toLowerCase()) {
|
// switch (status.toLowerCase()) {
|
||||||
case 'paid':
|
// case 'paid':
|
||||||
return 'success';
|
// return 'success';
|
||||||
case 'tempo':
|
// case 'tempo':
|
||||||
return 'warning';
|
// return 'warning';
|
||||||
default:
|
// default:
|
||||||
return 'neutral';
|
// return 'neutral';
|
||||||
}
|
// }
|
||||||
};
|
// };
|
||||||
|
|
||||||
return (
|
// return (
|
||||||
<Badge variant='soft' size='sm' color={getStatusColor(status)}>
|
// <Badge variant='soft' size='sm' color={getStatusColor(status)}>
|
||||||
{status || '-'}
|
// {status || '-'}
|
||||||
</Badge>
|
// </Badge>
|
||||||
);
|
// );
|
||||||
},
|
// },
|
||||||
},
|
// },
|
||||||
],
|
],
|
||||||
[]
|
[]
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,48 +1,65 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import Button from '@/components/Button';
|
import Button from '@/components/Button';
|
||||||
import Card from '@/components/Card';
|
|
||||||
import { Icon } from '@iconify/react';
|
import { Icon } from '@iconify/react';
|
||||||
import ProductionLineChart from '@/components/pages/dashboard/chart/ProductionLineChart';
|
|
||||||
import StandardLineChart from '@/components/pages/dashboard/chart/StandardLineChart';
|
|
||||||
import EggWeightBarChart from '@/components/pages/dashboard/chart/EggWeightBarChart';
|
|
||||||
import FCRBarChart from '@/components/pages/dashboard/chart/FCRBarChart';
|
|
||||||
import ProductionStat from '@/components/pages/dashboard/chart/ProductionStat';
|
|
||||||
import Modal, { useModal } from '@/components/Modal';
|
import Modal, { useModal } from '@/components/Modal';
|
||||||
import DateInput from '@/components/input/DateInput';
|
import DateInput from '@/components/input/DateInput';
|
||||||
import SelectInput, {
|
import SelectInput, {
|
||||||
OptionType,
|
OptionType,
|
||||||
useSelect,
|
useSelect,
|
||||||
} from '@/components/input/SelectInput';
|
} from '@/components/input/SelectInput';
|
||||||
import { RadioGroup } from '@/components/input/RadioInput';
|
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import useSWR from 'swr';
|
import useSWR from 'swr';
|
||||||
import { DashboardApi } from '@/services/api/dashboard';
|
import { DashboardApi } from '@/services/api/dashboard';
|
||||||
import { useFormik } from 'formik';
|
import { useFormik } from 'formik';
|
||||||
import dashboardProductionFilterSchema from '@/components/pages/dashboard/filter/DashboardProductionFilter.schema';
|
|
||||||
import { ProjectFlockApi } from '@/services/api/production';
|
import { ProjectFlockApi } from '@/services/api/production';
|
||||||
import { ProductionStandardApi } from '@/services/api/master-data';
|
import { KandangApi, LocationApi } from '@/services/api/master-data';
|
||||||
|
|
||||||
|
import {
|
||||||
|
DashboardFilterType,
|
||||||
|
getDashboardFilterSchema,
|
||||||
|
} from '@/components/pages/dashboard/filter/DashboardProductionFilter.schema';
|
||||||
|
import DashboardLineChart from '@/components/pages/dashboard/chart/DashboardLineChart';
|
||||||
|
import DashboardLineChartSkeleton from '@/components/pages/dashboard/skeleton/DashboardLineChartSkeleton';
|
||||||
|
import { RadioGroup, RadioGroupItem } from '@/components/input/RadioInput';
|
||||||
|
import {
|
||||||
|
DashboardFilter,
|
||||||
|
DashboardMeta,
|
||||||
|
} from '@/types/api/dashboard/dashboard';
|
||||||
|
import DashboardStats from '@/components/pages/dashboard/chart/DashboardStats';
|
||||||
|
import { isResponseSuccess } from '@/lib/api-helper';
|
||||||
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
|
|
||||||
|
// Helper function to normalize values to array
|
||||||
|
const normalizeToArray = (
|
||||||
|
value: OptionType | OptionType[] | null | undefined
|
||||||
|
): number[] => {
|
||||||
|
if (!value) return [];
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
return value.map((v) => Number(v.value));
|
||||||
|
}
|
||||||
|
return [Number(value.value)];
|
||||||
|
};
|
||||||
|
|
||||||
const DashboardProduction = () => {
|
const DashboardProduction = () => {
|
||||||
const filterModal = useModal();
|
const filterModal = useModal();
|
||||||
const [selectedPeriod, setSelectedPeriod] = useState('daily');
|
const [analysisMode, setAnalysisMode] = useState<'OVERVIEW' | 'COMPARISON'>(
|
||||||
const [selectedStandards, setSelectedStandards] = useState<string[]>([
|
'OVERVIEW'
|
||||||
'hen_day',
|
);
|
||||||
'hen_house',
|
const [endpointUrl, setEndpointUrl] = useState('/dashboards');
|
||||||
]);
|
const [selectedLocationIds, setSelectedLocationIds] = useState<number[]>([]);
|
||||||
const [endpointUrl, setEndpointUrl] = useState('/dashboard');
|
|
||||||
|
|
||||||
// ===== FETCH DATA =====
|
// ===== FETCH DATA =====
|
||||||
const {
|
const {
|
||||||
data: dashboardProductionResponse,
|
data: dashboardProductionResponse,
|
||||||
isLoading: isLoadingDashboardProductionData,
|
isLoading: isLoadingDashboardProductionData,
|
||||||
error: dashboardProductionError,
|
mutate: refreshDashboardProductionData,
|
||||||
} = useSWR(endpointUrl, () =>
|
} = useSWR(endpointUrl, () =>
|
||||||
DashboardApi.getDashboardProductionFetcher(endpointUrl)
|
DashboardApi.getDashboardProductionFetcher(endpointUrl)
|
||||||
);
|
);
|
||||||
|
|
||||||
const dashboardProductionData =
|
const dashboardProductionData = isResponseSuccess(dashboardProductionResponse)
|
||||||
dashboardProductionResponse?.status === 'success'
|
|
||||||
? dashboardProductionResponse.data
|
? dashboardProductionResponse.data
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
@@ -50,14 +67,24 @@ const DashboardProduction = () => {
|
|||||||
const { options: flockOptions, isLoadingOptions: isLoadingFlockOptions } =
|
const { options: flockOptions, isLoadingOptions: isLoadingFlockOptions } =
|
||||||
useSelect(ProjectFlockApi.basePath, 'id', 'flock_name', '', {
|
useSelect(ProjectFlockApi.basePath, 'id', 'flock_name', '', {
|
||||||
limit: 'limit',
|
limit: 'limit',
|
||||||
category: 'LAYING',
|
location_id: selectedLocationIds ? selectedLocationIds.toString() : '',
|
||||||
});
|
});
|
||||||
const {
|
const {
|
||||||
options: standardProductionOptions,
|
options: locationOptions,
|
||||||
isLoadingOptions: isLoadingStandardProductionOptions,
|
isLoadingOptions: isLoadingLocationOptions,
|
||||||
} = useSelect(ProductionStandardApi.basePath, 'id', 'name', '', {
|
} = useSelect(LocationApi.basePath, 'id', 'name', '', {
|
||||||
limit: 'limit',
|
limit: 'limit',
|
||||||
});
|
});
|
||||||
|
const { options: kandangOptions, isLoadingOptions: isLoadingKandangOptions } =
|
||||||
|
useSelect(KandangApi.basePath, 'id', 'name', '', {
|
||||||
|
limit: 'limit',
|
||||||
|
location_id: selectedLocationIds ? selectedLocationIds.toString() : '',
|
||||||
|
});
|
||||||
|
const comparisonTypeOptions = [
|
||||||
|
{ value: 'FARM', label: 'Farm' },
|
||||||
|
{ value: 'FLOCK', label: 'Flock' },
|
||||||
|
{ value: 'KANDANG', label: 'Kandang' },
|
||||||
|
];
|
||||||
|
|
||||||
// ===== FORMIK =====
|
// ===== FORMIK =====
|
||||||
const formik = useFormik({
|
const formik = useFormik({
|
||||||
@@ -65,57 +92,63 @@ const DashboardProduction = () => {
|
|||||||
startDate: '',
|
startDate: '',
|
||||||
endDate: '',
|
endDate: '',
|
||||||
flock: [] as OptionType[],
|
flock: [] as OptionType[],
|
||||||
standard_production_id: [] as OptionType[],
|
location: [] as OptionType[],
|
||||||
standard_productions: [] as OptionType[],
|
kandang: [] as OptionType[],
|
||||||
period: selectedPeriod,
|
analysisMode: analysisMode,
|
||||||
},
|
comparisonType: '',
|
||||||
validationSchema: dashboardProductionFilterSchema,
|
lokasiIds: [],
|
||||||
|
flockIds: [],
|
||||||
|
kandangIds: [],
|
||||||
|
} as DashboardFilterType,
|
||||||
|
validationSchema: getDashboardFilterSchema(analysisMode),
|
||||||
onSubmit: (values) => {
|
onSubmit: (values) => {
|
||||||
console.log(values);
|
console.log(values);
|
||||||
// Build URL with query parameters
|
|
||||||
const params = new URLSearchParams();
|
|
||||||
|
|
||||||
if (values.startDate) params.set('startDate', values.startDate);
|
handleApplyFilter({
|
||||||
if (values.endDate) params.set('endDate', values.endDate);
|
start_date: values.startDate || '',
|
||||||
|
end_date: values.endDate || '',
|
||||||
if (values.flock && values.flock.length > 0) {
|
analysis_mode: values.analysisMode as 'OVERVIEW' | 'COMPARISON',
|
||||||
const flockIds = values.flock
|
location_ids: normalizeToArray(values.location),
|
||||||
.map((f: OptionType) => f.value || f)
|
flock_ids: normalizeToArray(values.flock),
|
||||||
.join(',');
|
kandang_ids: normalizeToArray(values.kandang),
|
||||||
params.set('flock', flockIds);
|
comparison_type: values.comparisonType,
|
||||||
}
|
});
|
||||||
|
|
||||||
if (
|
|
||||||
values.standard_production_id &&
|
|
||||||
values.standard_production_id.length > 0
|
|
||||||
) {
|
|
||||||
const standardIds = values.standard_production_id
|
|
||||||
.map((s: OptionType) => s.value || s)
|
|
||||||
.join(',');
|
|
||||||
params.set('standard_production_id', standardIds);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (selectedStandards.length > 0) {
|
|
||||||
params.set('standards', selectedStandards.join(','));
|
|
||||||
}
|
|
||||||
|
|
||||||
params.set('period', selectedPeriod);
|
|
||||||
|
|
||||||
const newUrl = `/dashboard?${params.toString()}`;
|
|
||||||
setEndpointUrl(newUrl);
|
|
||||||
|
|
||||||
// Close modal after applying filter
|
|
||||||
filterModal.closeModal();
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const handleResetFilter = () => {
|
const handleResetFilter = () => {
|
||||||
formik.resetForm();
|
formik.resetForm();
|
||||||
setSelectedPeriod('daily');
|
setAnalysisMode('OVERVIEW');
|
||||||
setSelectedStandards(['hen_day', 'hen_house']);
|
setEndpointUrl('/dashboards');
|
||||||
setEndpointUrl('/dashboard');
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleApplyFilter = (values: DashboardFilter) => {
|
||||||
|
console.log(values);
|
||||||
|
|
||||||
|
// Build query params object, only include non-empty values
|
||||||
|
const params: Record<string, string> = {};
|
||||||
|
|
||||||
|
if (values.start_date) params.start_date = values.start_date;
|
||||||
|
if (values.end_date) params.end_date = values.end_date;
|
||||||
|
if (values.analysis_mode) params.analysis_mode = values.analysis_mode;
|
||||||
|
if (values.location_ids.length > 0)
|
||||||
|
params.location_ids = values.location_ids.toString();
|
||||||
|
if (values.flock_ids.length > 0)
|
||||||
|
params.flock_ids = values.flock_ids.toString();
|
||||||
|
if (values.kandang_ids.length > 0)
|
||||||
|
params.kandang_ids = values.kandang_ids.toString();
|
||||||
|
if (values.comparison_type) params.comparison_type = values.comparison_type;
|
||||||
|
|
||||||
|
setEndpointUrl(`/dashboards?${new URLSearchParams(params).toString()}`);
|
||||||
|
console.log(endpointUrl);
|
||||||
|
filterModal.closeModal();
|
||||||
|
refreshDashboardProductionData();
|
||||||
|
formik.resetForm();
|
||||||
|
};
|
||||||
|
|
||||||
|
// ===== Formik Error List =====
|
||||||
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
|
|
||||||
if (isLoadingDashboardProductionData) {
|
if (isLoadingDashboardProductionData) {
|
||||||
return (
|
return (
|
||||||
<div className='w-full min-h-screen flex items-center justify-center'>
|
<div className='w-full min-h-screen flex items-center justify-center'>
|
||||||
@@ -127,15 +160,57 @@ const DashboardProduction = () => {
|
|||||||
<>
|
<>
|
||||||
<section className='w-full p-4 space-y-6'>
|
<section className='w-full p-4 space-y-6'>
|
||||||
<div className='flex flex-col sm:flex-row items-center justify-between gap-4'>
|
<div className='flex flex-col sm:flex-row items-center justify-between gap-4'>
|
||||||
<h1 className='text-3xl font-bold text-primary'>Dashboard</h1>
|
<div></div>
|
||||||
<div className='flex flex-row justify-end gap-2'>
|
<div className='flex flex-row justify-end gap-2'>
|
||||||
<Button
|
<Button
|
||||||
variant='outline'
|
variant='outline'
|
||||||
className='min-w-28 rounded-lg'
|
className={`min-w-28 rounded-lg ${
|
||||||
|
isResponseSuccess(dashboardProductionResponse) &&
|
||||||
|
(dashboardProductionResponse.meta as unknown as DashboardMeta)
|
||||||
|
.filters
|
||||||
|
? 'bg-gradient-to-r from-blue-50 to-blue-100 border-blue-500 text-blue-600 hover:from-blue-100 hover:to-blue-200'
|
||||||
|
: ''
|
||||||
|
}`}
|
||||||
onClick={() => filterModal.openModal()}
|
onClick={() => filterModal.openModal()}
|
||||||
>
|
>
|
||||||
<Icon icon='heroicons:funnel' width={20} height={20} />
|
<Icon
|
||||||
|
icon='heroicons:funnel'
|
||||||
|
width={20}
|
||||||
|
height={20}
|
||||||
|
className={
|
||||||
|
isResponseSuccess(dashboardProductionResponse) &&
|
||||||
|
(dashboardProductionResponse.meta as unknown as DashboardMeta)
|
||||||
|
.filters
|
||||||
|
? 'text-blue-600'
|
||||||
|
: ''
|
||||||
|
}
|
||||||
|
/>
|
||||||
Filter
|
Filter
|
||||||
|
{isResponseSuccess(dashboardProductionResponse) &&
|
||||||
|
dashboardProductionResponse.meta &&
|
||||||
|
(dashboardProductionResponse.meta as unknown as DashboardMeta)
|
||||||
|
.filters && (
|
||||||
|
<span className='w-6 h-6 text-white bg-red-500 rounded-lg flex items-center justify-center text-xs'>
|
||||||
|
{(() => {
|
||||||
|
const meta =
|
||||||
|
dashboardProductionResponse.meta as unknown as DashboardMeta;
|
||||||
|
if (!meta.filters) return 0;
|
||||||
|
const count =
|
||||||
|
(meta.filters.location_ids.length > 1
|
||||||
|
? meta.filters.location_ids.length
|
||||||
|
: 0) +
|
||||||
|
(meta.filters.flock_ids.length > 1
|
||||||
|
? meta.filters.flock_ids.length
|
||||||
|
: 0) +
|
||||||
|
(meta.filters.kandang_ids.length > 1
|
||||||
|
? meta.filters.kandang_ids.length
|
||||||
|
: 0);
|
||||||
|
return meta.filters.analysis_mode === 'OVERVIEW'
|
||||||
|
? 1
|
||||||
|
: count;
|
||||||
|
})()}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant='outline'
|
variant='outline'
|
||||||
@@ -149,55 +224,38 @@ const DashboardProduction = () => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Dashboard Statistics */}
|
{/* Dashboard Stats */}
|
||||||
<ProductionStat data={dashboardProductionData?.statistics_data} />
|
<DashboardStats data={dashboardProductionData?.statistics_data ?? []} />
|
||||||
|
|
||||||
{/* Charts Grid */}
|
{/* Use DashboardLineChart component or skeleton */}
|
||||||
<div className='grid grid-cols-1 gap-4'>
|
{isLoadingDashboardProductionData ? (
|
||||||
{/* Production Line Chart */}
|
<DashboardLineChartSkeleton />
|
||||||
<Card
|
) : dashboardProductionData &&
|
||||||
variant='bordered'
|
dashboardProductionData.charts &&
|
||||||
className={{ wrapper: 'w-full', body: 'p-6' }}
|
Object.keys(dashboardProductionData.charts).length > 0 ? (
|
||||||
>
|
<DashboardLineChart
|
||||||
<ProductionLineChart
|
analysisMode={
|
||||||
period={
|
isResponseSuccess(dashboardProductionResponse)
|
||||||
selectedPeriod as 'daily' | 'weekly' | 'monthly' | 'yearly'
|
? dashboardProductionResponse.meta
|
||||||
|
? (
|
||||||
|
dashboardProductionResponse.meta as unknown as DashboardMeta
|
||||||
|
).filters?.analysis_mode
|
||||||
|
: analysisMode
|
||||||
|
: analysisMode
|
||||||
}
|
}
|
||||||
data={dashboardProductionData?.production_charts}
|
data={dashboardProductionData}
|
||||||
/>
|
/>
|
||||||
</Card>
|
) : (
|
||||||
|
<DashboardLineChartSkeleton
|
||||||
{/* Standard Line Chart */}
|
meta={
|
||||||
<Card
|
isResponseSuccess(dashboardProductionResponse)
|
||||||
variant='bordered'
|
? (dashboardProductionResponse.meta as unknown as DashboardMeta)
|
||||||
className={{ wrapper: 'w-full', body: 'p-6' }}
|
: undefined
|
||||||
>
|
}
|
||||||
<StandardLineChart
|
|
||||||
selectedStandards={selectedStandards}
|
|
||||||
data={dashboardProductionData?.standard_productions}
|
|
||||||
/>
|
/>
|
||||||
</Card>
|
)}
|
||||||
|
|
||||||
{/* Bar Charts Grid - 2 columns */}
|
|
||||||
<div className='grid grid-cols-1 lg:grid-cols-2 gap-4'>
|
|
||||||
{/* FCR Bar Chart */}
|
|
||||||
<Card
|
|
||||||
variant='bordered'
|
|
||||||
className={{ wrapper: 'w-full', body: 'p-6' }}
|
|
||||||
>
|
|
||||||
<FCRBarChart data={dashboardProductionData?.fcr_data} />
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* Egg Weight Bar Chart */}
|
|
||||||
<Card
|
|
||||||
variant='bordered'
|
|
||||||
className={{ wrapper: 'w-full', body: 'p-6' }}
|
|
||||||
>
|
|
||||||
<EggWeightBarChart data={dashboardProductionData?.egg_weights} />
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<Modal
|
<Modal
|
||||||
ref={filterModal.ref}
|
ref={filterModal.ref}
|
||||||
className={{
|
className={{
|
||||||
@@ -221,13 +279,14 @@ const DashboardProduction = () => {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<form className='space-y-4' onSubmit={formik.handleSubmit}>
|
<form
|
||||||
|
className='space-y-4'
|
||||||
|
onSubmit={handleFormSubmit}
|
||||||
|
onReset={handleResetFilter}
|
||||||
|
>
|
||||||
{/* Rentang Waktu */}
|
{/* Rentang Waktu */}
|
||||||
<div className='px-4'>
|
<div className='px-4'>
|
||||||
<label className='flex items-center gap-2 mb-3'>
|
<label className='flex items-center gap-2 mb-3'>Tanggal</label>
|
||||||
<Icon icon='heroicons:calendar' width={20} height={20} />
|
|
||||||
Rentang Waktu
|
|
||||||
</label>
|
|
||||||
<div className='flex items-center gap-2'>
|
<div className='flex items-center gap-2'>
|
||||||
<DateInput
|
<DateInput
|
||||||
name='startDate'
|
name='startDate'
|
||||||
@@ -261,119 +320,152 @@ const DashboardProduction = () => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Analysis Mode */}
|
||||||
|
<div className='px-4'>
|
||||||
|
<label className='block mb-3'>Analysis Mode</label>
|
||||||
|
<RadioGroup
|
||||||
|
name='analysisMode'
|
||||||
|
value={formik.values.analysisMode}
|
||||||
|
onChange={(e) => {
|
||||||
|
formik.handleChange(e);
|
||||||
|
setAnalysisMode(e.target.value as 'OVERVIEW' | 'COMPARISON');
|
||||||
|
// Reset all dependent fields when analysis mode changes
|
||||||
|
formik.setFieldValue('location', []);
|
||||||
|
formik.setFieldValue('flock', []);
|
||||||
|
formik.setFieldValue('kandang', []);
|
||||||
|
formik.setFieldValue('comparisonType', '');
|
||||||
|
setSelectedLocationIds([]);
|
||||||
|
}}
|
||||||
|
color='primary'
|
||||||
|
className={{
|
||||||
|
wrapper: 'w-full my-6 font-semibold text-neutral-500',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<RadioGroupItem
|
||||||
|
color='primary'
|
||||||
|
value='OVERVIEW'
|
||||||
|
label='Performance Overview'
|
||||||
|
/>
|
||||||
|
<RadioGroupItem
|
||||||
|
color='primary'
|
||||||
|
value='COMPARISON'
|
||||||
|
label='Performance Comparison'
|
||||||
|
/>
|
||||||
|
</RadioGroup>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{formik.values.analysisMode === 'COMPARISON' && (
|
||||||
|
<div className='px-4'>
|
||||||
|
<SelectInput
|
||||||
|
label='Compared By'
|
||||||
|
value={comparisonTypeOptions.find(
|
||||||
|
(option) => option.value === formik.values.comparisonType
|
||||||
|
)}
|
||||||
|
onChange={(selected) =>
|
||||||
|
formik.setFieldValue(
|
||||||
|
'comparisonType',
|
||||||
|
selected ? (selected as OptionType).value : ''
|
||||||
|
)
|
||||||
|
}
|
||||||
|
errorMessage={formik.errors.comparisonType as string}
|
||||||
|
options={comparisonTypeOptions}
|
||||||
|
isLoading={isLoadingLocationOptions}
|
||||||
|
isError={
|
||||||
|
Boolean(formik.errors.comparisonType) &&
|
||||||
|
Boolean(formik.touched.comparisonType)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Location */}
|
||||||
|
<div className='px-4'>
|
||||||
|
<SelectInput
|
||||||
|
label='Farm'
|
||||||
|
value={formik.values.location}
|
||||||
|
onChange={(selected) => {
|
||||||
|
formik.setFieldValue('location', selected);
|
||||||
|
// Update selectedLocationIds for kandang filter
|
||||||
|
setSelectedLocationIds(normalizeToArray(selected));
|
||||||
|
// Reset dependent fields when location changes
|
||||||
|
formik.setFieldValue('flock', []);
|
||||||
|
formik.setFieldValue('kandang', []);
|
||||||
|
}}
|
||||||
|
errorMessage={formik.errors.location as string}
|
||||||
|
options={locationOptions}
|
||||||
|
isLoading={isLoadingLocationOptions}
|
||||||
|
isMulti={
|
||||||
|
comparisonTypeOptions.find(
|
||||||
|
(option) => option.value === formik.values.comparisonType
|
||||||
|
)?.value === 'FARM'
|
||||||
|
}
|
||||||
|
isError={
|
||||||
|
Boolean(formik.errors.location) &&
|
||||||
|
Boolean(formik.touched.location)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Flock */}
|
{/* Flock */}
|
||||||
|
{!(
|
||||||
|
formik.values.analysisMode === 'COMPARISON' &&
|
||||||
|
!(
|
||||||
|
formik.values.comparisonType === 'FLOCK' ||
|
||||||
|
formik.values.comparisonType === 'KANDANG'
|
||||||
|
)
|
||||||
|
) && (
|
||||||
<div className='px-4'>
|
<div className='px-4'>
|
||||||
<SelectInput
|
<SelectInput
|
||||||
label='Flock'
|
label='Flock'
|
||||||
value={formik.values.flock}
|
value={formik.values.flock}
|
||||||
onChange={(selected) => formik.setFieldValue('flock', selected)}
|
onChange={(selected) =>
|
||||||
|
formik.setFieldValue('flock', selected)
|
||||||
|
}
|
||||||
errorMessage={formik.errors.flock as string}
|
errorMessage={formik.errors.flock as string}
|
||||||
options={flockOptions}
|
options={flockOptions}
|
||||||
isLoading={isLoadingFlockOptions}
|
isLoading={isLoadingFlockOptions}
|
||||||
isMulti
|
isMulti={
|
||||||
|
comparisonTypeOptions.find(
|
||||||
|
(option) => option.value === formik.values.comparisonType
|
||||||
|
)?.value === 'FLOCK'
|
||||||
|
}
|
||||||
isError={
|
isError={
|
||||||
Boolean(formik.errors.flock) && Boolean(formik.touched.flock)
|
Boolean(formik.errors.flock) &&
|
||||||
|
Boolean(formik.touched.flock)
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Production */}
|
{/* Kandang */}
|
||||||
|
{!(
|
||||||
|
formik.values.analysisMode === 'COMPARISON' &&
|
||||||
|
!(formik.values.comparisonType === 'KANDANG')
|
||||||
|
) && (
|
||||||
<div className='px-4'>
|
<div className='px-4'>
|
||||||
<SelectInput
|
<SelectInput
|
||||||
label='Standard Produksi'
|
label='Kandang'
|
||||||
value={formik.values.standard_production_id}
|
value={formik.values.kandang}
|
||||||
onChange={(selected) =>
|
onChange={(selected) =>
|
||||||
formik.setFieldValue('standard_production_id', selected)
|
formik.setFieldValue('kandang', selected)
|
||||||
|
}
|
||||||
|
errorMessage={formik.errors.kandang as string}
|
||||||
|
options={kandangOptions}
|
||||||
|
isLoading={isLoadingKandangOptions}
|
||||||
|
isMulti={
|
||||||
|
comparisonTypeOptions.find(
|
||||||
|
(option) => option.value === formik.values.comparisonType
|
||||||
|
)?.value === 'KANDANG'
|
||||||
}
|
}
|
||||||
errorMessage={formik.errors.standard_production_id as string}
|
|
||||||
options={standardProductionOptions}
|
|
||||||
isLoading={isLoadingStandardProductionOptions}
|
|
||||||
isMulti
|
|
||||||
isError={
|
isError={
|
||||||
Boolean(formik.errors.standard_production_id) &&
|
Boolean(formik.errors.kandang) &&
|
||||||
Boolean(formik.touched.standard_production_id)
|
Boolean(formik.touched.kandang)
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Standard */}
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
<div className='px-4'>
|
|
||||||
<SelectInput
|
|
||||||
label='Standard'
|
|
||||||
value={selectedStandards.map((s) => ({
|
|
||||||
value: s,
|
|
||||||
label:
|
|
||||||
s === 'hen_day'
|
|
||||||
? 'Hen Day'
|
|
||||||
: s === 'hen_house'
|
|
||||||
? 'Hen House'
|
|
||||||
: s === 'uniformity'
|
|
||||||
? 'Uniformity'
|
|
||||||
: s === 'egg_weight'
|
|
||||||
? 'Egg Weight'
|
|
||||||
: 'Egg Mass',
|
|
||||||
}))}
|
|
||||||
options={[
|
|
||||||
{ value: 'hen_day', label: 'Hen Day' },
|
|
||||||
{ value: 'hen_house', label: 'Hen House' },
|
|
||||||
{ value: 'uniformity', label: 'Uniformity' },
|
|
||||||
{ value: 'egg_weight', label: 'Egg Weight' },
|
|
||||||
{ value: 'egg_mass', label: 'Egg Mass' },
|
|
||||||
]}
|
|
||||||
isMulti
|
|
||||||
onChange={(selected: OptionType | OptionType[] | null) => {
|
|
||||||
const values = Array.isArray(selected)
|
|
||||||
? selected.map((item) => String(item.value))
|
|
||||||
: [];
|
|
||||||
setSelectedStandards(
|
|
||||||
values.length > 0 ? values : ['hen_day']
|
|
||||||
);
|
|
||||||
}}
|
|
||||||
isError={
|
|
||||||
Boolean(formik.errors.standard_productions) &&
|
|
||||||
Boolean(formik.touched.standard_productions)
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Periode Perbandingan */}
|
|
||||||
<div className='px-4'>
|
|
||||||
<label className='block mb-3'>Periode Perbandingan</label>
|
|
||||||
<div className='grid grid-cols-4 gap-2'>
|
|
||||||
<Button
|
|
||||||
variant={selectedPeriod === 'daily' ? 'active' : 'soft'}
|
|
||||||
type='button'
|
|
||||||
className='rounded-lg'
|
|
||||||
onClick={() => setSelectedPeriod('daily')}
|
|
||||||
>
|
|
||||||
Harian
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant={selectedPeriod === 'weekly' ? 'active' : 'soft'}
|
|
||||||
type='button'
|
|
||||||
className='rounded-lg'
|
|
||||||
onClick={() => setSelectedPeriod('weekly')}
|
|
||||||
>
|
|
||||||
Mingguan
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant={selectedPeriod === 'monthly' ? 'active' : 'soft'}
|
|
||||||
type='button'
|
|
||||||
className='rounded-lg'
|
|
||||||
onClick={() => setSelectedPeriod('monthly')}
|
|
||||||
>
|
|
||||||
Bulanan
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant={selectedPeriod === 'yearly' ? 'active' : 'soft'}
|
|
||||||
type='button'
|
|
||||||
className='rounded-lg'
|
|
||||||
onClick={() => setSelectedPeriod('yearly')}
|
|
||||||
>
|
|
||||||
Tahunan
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Action Buttons */}
|
{/* Action Buttons */}
|
||||||
<div className='flex justify-between gap-4 py-4 mt-8 border-t border-gray-300 bg-gray-100'>
|
<div className='flex justify-between gap-4 py-4 mt-8 border-t border-gray-300 bg-gray-100'>
|
||||||
|
|||||||
@@ -0,0 +1,545 @@
|
|||||||
|
import Button from '@/components/Button';
|
||||||
|
import Card from '@/components/Card';
|
||||||
|
import Dropdown from '@/components/Dropdown';
|
||||||
|
import Menu from '@/components/menu/Menu';
|
||||||
|
import MenuItem from '@/components/menu/MenuItem';
|
||||||
|
import {
|
||||||
|
Dashboard,
|
||||||
|
DashboardOverviewCharts,
|
||||||
|
DashboardComparisonCharts,
|
||||||
|
DashboardChartsSeries,
|
||||||
|
DashboardChartsDataset,
|
||||||
|
} from '@/types/api/dashboard/dashboard';
|
||||||
|
import { Icon } from '@iconify/react';
|
||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import {
|
||||||
|
CartesianGrid,
|
||||||
|
Line,
|
||||||
|
LineChart,
|
||||||
|
ResponsiveContainer,
|
||||||
|
Tooltip,
|
||||||
|
XAxis,
|
||||||
|
YAxis,
|
||||||
|
} from 'recharts';
|
||||||
|
|
||||||
|
type DashboardLineChartProps = {
|
||||||
|
analysisMode: 'OVERVIEW' | 'COMPARISON';
|
||||||
|
data: Dashboard;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Type guard to check if charts is DashboardOverviewCharts
|
||||||
|
function isOverviewCharts(
|
||||||
|
charts: DashboardOverviewCharts | DashboardComparisonCharts
|
||||||
|
): charts is DashboardOverviewCharts {
|
||||||
|
return 'deplesi' in charts;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Type guard to check if charts is DashboardComparisonCharts
|
||||||
|
function isComparisonCharts(
|
||||||
|
charts: DashboardOverviewCharts | DashboardComparisonCharts
|
||||||
|
): charts is DashboardComparisonCharts {
|
||||||
|
return 'location' 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,
|
||||||
|
mode: 'OVERVIEW' | 'COMPARISON'
|
||||||
|
): string => {
|
||||||
|
// For COMPARISON mode, use default colors with cycling
|
||||||
|
if (mode === 'COMPARISON') {
|
||||||
|
return defaultLineColors[index % defaultLineColors.length];
|
||||||
|
}
|
||||||
|
|
||||||
|
// For OVERVIEW mode, use predefined colors or fallback to default
|
||||||
|
const predefinedColor = lineColors[seriesId];
|
||||||
|
if (predefinedColor) {
|
||||||
|
return predefinedColor;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback to default colors with cycling
|
||||||
|
return defaultLineColors[index % defaultLineColors.length];
|
||||||
|
};
|
||||||
|
|
||||||
|
const DashboardLineChart = ({
|
||||||
|
analysisMode,
|
||||||
|
data,
|
||||||
|
}: DashboardLineChartProps) => {
|
||||||
|
const [chartData, setChartData] =
|
||||||
|
useState<keyof DashboardOverviewCharts>('body_weight');
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
// Track which series are visible (by series id)
|
||||||
|
const [visibleSeries, setVisibleSeries] = useState<Set<string | number>>(
|
||||||
|
new Set()
|
||||||
|
);
|
||||||
|
|
||||||
|
// 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',
|
||||||
|
};
|
||||||
|
|
||||||
|
// Initialize all series as visible when chartData changes
|
||||||
|
useEffect(() => {
|
||||||
|
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 || [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set all series as visible by default
|
||||||
|
const allSeriesIds = new Set(seriesData.map((s) => s.id));
|
||||||
|
setVisibleSeries(allSeriesIds);
|
||||||
|
}, [chartData, analysisMode, data.charts]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card
|
||||||
|
className={{
|
||||||
|
wrapper: 'w-full rounded-lg',
|
||||||
|
}}
|
||||||
|
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'>
|
||||||
|
Performance{' '}
|
||||||
|
<Icon
|
||||||
|
icon='heroicons:information-circle'
|
||||||
|
width={20}
|
||||||
|
height={20}
|
||||||
|
className='inline text-neutral-500'
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{analysisMode == 'OVERVIEW' && (
|
||||||
|
<Dropdown
|
||||||
|
align='end'
|
||||||
|
direction='bottom'
|
||||||
|
trigger={
|
||||||
|
<Button
|
||||||
|
variant='outline'
|
||||||
|
color='none'
|
||||||
|
className='text-neutral-500 hover:text-neutral-700 rounded-lg px-4 py-2 border-neutral-300'
|
||||||
|
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} />
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
className={{
|
||||||
|
content: 'w-52 mt-3',
|
||||||
|
}}
|
||||||
|
controlled={open}
|
||||||
|
>
|
||||||
|
<Menu>
|
||||||
|
<MenuItem
|
||||||
|
title='Body weight'
|
||||||
|
onClick={() => {
|
||||||
|
setChartData('body_weight');
|
||||||
|
setOpen(!open);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<MenuItem
|
||||||
|
title='Performance'
|
||||||
|
onClick={() => {
|
||||||
|
setChartData('performance');
|
||||||
|
setOpen(!open);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<MenuItem
|
||||||
|
title='FCR'
|
||||||
|
onClick={() => {
|
||||||
|
setChartData('fcr');
|
||||||
|
setOpen(!open);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<MenuItem
|
||||||
|
title='Quality Control'
|
||||||
|
onClick={() => {
|
||||||
|
setChartData('quality_control');
|
||||||
|
setOpen(!open);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<MenuItem
|
||||||
|
title='Deplesi'
|
||||||
|
onClick={() => {
|
||||||
|
setChartData('deplesi');
|
||||||
|
setOpen(!open);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Menu>
|
||||||
|
</Dropdown>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Legend - Dynamic based on series data */}
|
||||||
|
<div className='flex flex-wrap gap-3 mb-6'>
|
||||||
|
{(() => {
|
||||||
|
// Get series data based on current mode and chartData
|
||||||
|
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.map((series, index) => {
|
||||||
|
const isVisible = visibleSeries.has(series.id);
|
||||||
|
const isStandard = series.id
|
||||||
|
.toString()
|
||||||
|
.toLowerCase()
|
||||||
|
.includes('std');
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={series.id}
|
||||||
|
onClick={() => {
|
||||||
|
const newVisible = new Set(visibleSeries);
|
||||||
|
if (isVisible) {
|
||||||
|
newVisible.delete(series.id);
|
||||||
|
} else {
|
||||||
|
newVisible.add(series.id);
|
||||||
|
}
|
||||||
|
setVisibleSeries(newVisible);
|
||||||
|
}}
|
||||||
|
className={`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors ${
|
||||||
|
isVisible
|
||||||
|
? 'border-neutral-400 bg-neutral-50'
|
||||||
|
: 'border-neutral-300 hover:bg-neutral-50'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className={`w-6 h-0.5 ${
|
||||||
|
isStandard ? 'border-t-2 border-dashed' : ''
|
||||||
|
} ${!isVisible ? 'opacity-30' : ''}`}
|
||||||
|
style={{
|
||||||
|
backgroundColor: isStandard
|
||||||
|
? 'transparent'
|
||||||
|
: getLineColor(series.id, index, analysisMode),
|
||||||
|
borderColor: isStandard
|
||||||
|
? getLineColor(series.id, index, analysisMode)
|
||||||
|
: 'transparent',
|
||||||
|
}}
|
||||||
|
></div>
|
||||||
|
<span
|
||||||
|
className={`text-sm ${isVisible ? 'text-neutral-900 font-medium' : 'text-neutral-700'}`}
|
||||||
|
>
|
||||||
|
{series.label}
|
||||||
|
</span>
|
||||||
|
<Icon
|
||||||
|
icon='heroicons:information-circle'
|
||||||
|
width={16}
|
||||||
|
height={16}
|
||||||
|
className='text-neutral-400'
|
||||||
|
/>
|
||||||
|
</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;
|
||||||
|
}
|
||||||
|
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',
|
||||||
|
}}
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
activeDot={isStandard ? undefined : { r: 5 }}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
})()}
|
||||||
|
</LineChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default DashboardLineChart;
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
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';
|
||||||
|
|
||||||
|
interface DashboardStatsProps {
|
||||||
|
data: DashboardStatisticsData[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 DashboardStats = ({ data }: DashboardStatsProps) => {
|
||||||
|
// 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-success' : 'text-error',
|
||||||
|
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-neutral-500'>{suffix}</span>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className='grid sm:grid-cols-2 xl:grid-cols-4 gap-6'>
|
||||||
|
{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',
|
||||||
|
}}
|
||||||
|
variant='bordered'
|
||||||
|
footer={
|
||||||
|
<div className='flex flex-row justify-between px-4 pb-4'>
|
||||||
|
<div className='text-neutral-400 font-semibold text-sm'>
|
||||||
|
From last month
|
||||||
|
</div>
|
||||||
|
<div className='text-neutral-400 font-semibold text-sm'>
|
||||||
|
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'>
|
||||||
|
<Icon
|
||||||
|
icon={config.icon}
|
||||||
|
width={32}
|
||||||
|
height={32}
|
||||||
|
className='text-neutral-400'
|
||||||
|
/>
|
||||||
|
</Alert>
|
||||||
|
<div>
|
||||||
|
<h3 className='text-neutral-400 font-semibold text-sm'>
|
||||||
|
{config.key}
|
||||||
|
</h3>
|
||||||
|
<p className='text-2xl font-semibold text-neutral-400'>
|
||||||
|
********
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const trend = getTrendDisplay(cardData.percent_last_month);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card
|
||||||
|
key={config.key}
|
||||||
|
className={{
|
||||||
|
wrapper: 'w-full rounded-lg',
|
||||||
|
body: 'p-0',
|
||||||
|
}}
|
||||||
|
variant='bordered'
|
||||||
|
footer={
|
||||||
|
<div className='flex flex-row justify-between px-4 pb-4'>
|
||||||
|
<div className='text-neutral-500 font-semibold text-sm'>
|
||||||
|
From last month
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className={`${trend.color} font-semibold flex flex-row items-center gap-1 text-sm`}
|
||||||
|
>
|
||||||
|
<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-3'
|
||||||
|
>
|
||||||
|
<Icon icon={config.icon} width={32} height={32} />
|
||||||
|
</Alert>
|
||||||
|
<div>
|
||||||
|
<h3 className='text-neutral-500 font-semibold text-sm'>
|
||||||
|
{cardData.label}
|
||||||
|
</h3>
|
||||||
|
<p className='text-2xl font-semibold'>
|
||||||
|
{formatValue(cardData.value, config.prefix, config.suffix)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default DashboardStats;
|
||||||
@@ -1,89 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import {
|
|
||||||
BarChart,
|
|
||||||
Bar,
|
|
||||||
XAxis,
|
|
||||||
YAxis,
|
|
||||||
CartesianGrid,
|
|
||||||
Tooltip,
|
|
||||||
ResponsiveContainer,
|
|
||||||
Cell,
|
|
||||||
} from 'recharts';
|
|
||||||
import { DashboardProductionEggWeights } from '@/types/api/dashboard/dashboard-production';
|
|
||||||
|
|
||||||
interface EggWeightBarChartProps {
|
|
||||||
data?: DashboardProductionEggWeights[];
|
|
||||||
}
|
|
||||||
|
|
||||||
const EggWeightBarChart = ({ data }: EggWeightBarChartProps) => {
|
|
||||||
// Show loading state if no data
|
|
||||||
if (!data || data.length === 0) {
|
|
||||||
return (
|
|
||||||
<div className='w-full h-full'>
|
|
||||||
<h3 className='text-lg font-semibold mb-4'>
|
|
||||||
Rata-rata Berat Telur (EW)
|
|
||||||
</h3>
|
|
||||||
<div className='flex items-center justify-center h-[350px]'>
|
|
||||||
<p className='text-gray-500'>Memuat data...</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className='w-full h-full'>
|
|
||||||
<h3 className='text-lg font-semibold mb-4'>Rata-rata Berat Telur (EW)</h3>
|
|
||||||
<ResponsiveContainer width='100%' height={350}>
|
|
||||||
<BarChart
|
|
||||||
data={data}
|
|
||||||
margin={{
|
|
||||||
top: 5,
|
|
||||||
right: 30,
|
|
||||||
left: 0,
|
|
||||||
bottom: 5,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<CartesianGrid strokeDasharray='3 3' stroke='#e5e7eb' />
|
|
||||||
<XAxis
|
|
||||||
dataKey='flock.name'
|
|
||||||
tick={{ fontSize: 12 }}
|
|
||||||
tickLine={false}
|
|
||||||
axisLine={{ stroke: '#e5e7eb' }}
|
|
||||||
/>
|
|
||||||
<YAxis
|
|
||||||
tick={{ fontSize: 12 }}
|
|
||||||
tickLine={false}
|
|
||||||
axisLine={{ stroke: '#e5e7eb' }}
|
|
||||||
domain={[0, 'auto']}
|
|
||||||
label={{
|
|
||||||
value: 'Berat (gram)',
|
|
||||||
angle: -90,
|
|
||||||
position: 'insideLeft',
|
|
||||||
style: { fontSize: 12 },
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<Tooltip
|
|
||||||
contentStyle={{
|
|
||||||
backgroundColor: 'white',
|
|
||||||
border: '1px solid #e5e7eb',
|
|
||||||
borderRadius: '8px',
|
|
||||||
padding: '8px 12px',
|
|
||||||
}}
|
|
||||||
formatter={(value: number | undefined) =>
|
|
||||||
value !== undefined ? [`${value} gram`, ''] : ['', '']
|
|
||||||
}
|
|
||||||
cursor={{ fill: 'rgba(59, 130, 246, 0.1)' }}
|
|
||||||
/>
|
|
||||||
<Bar dataKey='weight' radius={[8, 8, 0, 0]}>
|
|
||||||
{data.map((entry, index) => (
|
|
||||||
<Cell key={`cell-${index}`} fill='#3b82f6' />
|
|
||||||
))}
|
|
||||||
</Bar>
|
|
||||||
</BarChart>
|
|
||||||
</ResponsiveContainer>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default EggWeightBarChart;
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import {
|
|
||||||
BarChart,
|
|
||||||
Bar,
|
|
||||||
XAxis,
|
|
||||||
YAxis,
|
|
||||||
CartesianGrid,
|
|
||||||
Tooltip,
|
|
||||||
ResponsiveContainer,
|
|
||||||
Cell,
|
|
||||||
} from 'recharts';
|
|
||||||
import { DashboardProductionFcrData } from '@/types/api/dashboard/dashboard-production';
|
|
||||||
|
|
||||||
interface FCRBarChartProps {
|
|
||||||
data?: DashboardProductionFcrData[];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Alternating colors: green and red
|
|
||||||
const colors = ['#10b981', '#ef4444'];
|
|
||||||
|
|
||||||
const FCRBarChart = ({ data }: FCRBarChartProps) => {
|
|
||||||
// Show loading state if no data
|
|
||||||
if (!data || data.length === 0) {
|
|
||||||
return (
|
|
||||||
<div className='w-full h-full'>
|
|
||||||
<h3 className='text-lg font-semibold mb-4'>
|
|
||||||
Feed Conversion Ratio (FCR)
|
|
||||||
</h3>
|
|
||||||
<div className='flex items-center justify-center h-[350px]'>
|
|
||||||
<p className='text-gray-500'>Memuat data...</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className='w-full h-full'>
|
|
||||||
<h3 className='text-lg font-semibold mb-4'>
|
|
||||||
Feed Conversion Ratio (FCR)
|
|
||||||
</h3>
|
|
||||||
<ResponsiveContainer width='100%' height={350}>
|
|
||||||
<BarChart
|
|
||||||
data={data}
|
|
||||||
margin={{
|
|
||||||
top: 5,
|
|
||||||
right: 30,
|
|
||||||
left: 0,
|
|
||||||
bottom: 5,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<CartesianGrid strokeDasharray='3 3' stroke='#e5e7eb' />
|
|
||||||
<XAxis
|
|
||||||
dataKey='flock.name'
|
|
||||||
tick={{ fontSize: 12 }}
|
|
||||||
tickLine={false}
|
|
||||||
axisLine={{ stroke: '#e5e7eb' }}
|
|
||||||
/>
|
|
||||||
<YAxis
|
|
||||||
tick={{ fontSize: 12 }}
|
|
||||||
tickLine={false}
|
|
||||||
axisLine={{ stroke: '#e5e7eb' }}
|
|
||||||
domain={[0, 'auto']}
|
|
||||||
label={{
|
|
||||||
value: 'FCR',
|
|
||||||
angle: -90,
|
|
||||||
position: 'insideLeft',
|
|
||||||
style: { fontSize: 12 },
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<Tooltip
|
|
||||||
contentStyle={{
|
|
||||||
backgroundColor: 'white',
|
|
||||||
border: '1px solid #e5e7eb',
|
|
||||||
borderRadius: '8px',
|
|
||||||
padding: '8px 12px',
|
|
||||||
}}
|
|
||||||
formatter={(value: number | undefined) =>
|
|
||||||
value !== undefined ? [value.toFixed(2), 'FCR'] : ['', '']
|
|
||||||
}
|
|
||||||
cursor={{ fill: 'rgba(16, 185, 129, 0.1)' }}
|
|
||||||
/>
|
|
||||||
<Bar dataKey='fcr' radius={[8, 8, 0, 0]}>
|
|
||||||
{data.map((entry, index) => (
|
|
||||||
<Cell
|
|
||||||
key={`cell-${index}`}
|
|
||||||
fill={colors[index % colors.length]}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</Bar>
|
|
||||||
</BarChart>
|
|
||||||
</ResponsiveContainer>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default FCRBarChart;
|
|
||||||
@@ -1,357 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useState } from 'react';
|
|
||||||
import {
|
|
||||||
LineChart,
|
|
||||||
Line,
|
|
||||||
XAxis,
|
|
||||||
YAxis,
|
|
||||||
CartesianGrid,
|
|
||||||
Tooltip,
|
|
||||||
Legend,
|
|
||||||
ResponsiveContainer,
|
|
||||||
} from 'recharts';
|
|
||||||
|
|
||||||
// Sample data in API format
|
|
||||||
const sampleApiData: ProductionChartItem[] = [
|
|
||||||
{
|
|
||||||
date: '2025-12-01T00:00:00Z',
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-002', data: 88 },
|
|
||||||
{ id: 2, name: 'Flock A-001', data: 92 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 90 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 85 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: '2025-12-03T00:00:00Z',
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-002', data: 85 },
|
|
||||||
{ id: 2, name: 'Flock A-001', data: 95 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 93 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 87 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: '2025-12-05T00:00:00Z',
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-002', data: 82 },
|
|
||||||
{ id: 2, name: 'Flock A-001', data: 98 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 91 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 84 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: '2025-12-07T00:00:00Z',
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-002', data: 80 },
|
|
||||||
{ id: 2, name: 'Flock A-001', data: 89 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 88 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 82 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: '2025-12-08T00:00:00Z',
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-002', data: 83 },
|
|
||||||
{ id: 2, name: 'Flock A-001', data: 92 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 95 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 85 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: '2025-12-11T00:00:00Z',
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-002', data: 81 },
|
|
||||||
{ id: 2, name: 'Flock A-001', data: 88 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 92 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 83 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: '2025-12-13T00:00:00Z',
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-002', data: 84 },
|
|
||||||
{ id: 2, name: 'Flock A-001', data: 90 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 89 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 86 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: '2025-12-15T00:00:00Z',
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-002', data: 82 },
|
|
||||||
{ id: 2, name: 'Flock A-001', data: 94 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 96 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 84 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: '2025-12-17T00:00:00Z',
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-002', data: 80 },
|
|
||||||
{ id: 2, name: 'Flock A-001', data: 91 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 93 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 82 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: '2025-12-19T00:00:00Z',
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-002', data: 79 },
|
|
||||||
{ id: 2, name: 'Flock A-001', data: 88 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 90 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 81 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: '2025-12-21T00:00:00Z',
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-002', data: 81 },
|
|
||||||
{ id: 2, name: 'Flock A-001', data: 97 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 92 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 83 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: '2025-12-23T00:00:00Z',
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-002', data: 83 },
|
|
||||||
{ id: 2, name: 'Flock A-001', data: 95 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 98 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 85 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: '2025-12-25T00:00:00Z',
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-002', data: 80 },
|
|
||||||
{ id: 2, name: 'Flock A-001', data: 89 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 94 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 82 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: '2025-12-27T00:00:00Z',
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-002', data: 82 },
|
|
||||||
{ id: 2, name: 'Flock A-001', data: 93 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 96 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 84 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
date: '2025-12-28T00:00:00Z',
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-002', data: 85 },
|
|
||||||
{ id: 2, name: 'Flock A-001', data: 96 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 95 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 87 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
// Helper function to format date based on period
|
|
||||||
const formatDateByPeriod = (
|
|
||||||
dateString: string,
|
|
||||||
period: 'daily' | 'weekly' | 'monthly' | 'yearly'
|
|
||||||
): string => {
|
|
||||||
const date = new Date(dateString);
|
|
||||||
const monthNames = [
|
|
||||||
'Jan',
|
|
||||||
'Feb',
|
|
||||||
'Mar',
|
|
||||||
'Apr',
|
|
||||||
'Mei',
|
|
||||||
'Jun',
|
|
||||||
'Jul',
|
|
||||||
'Agu',
|
|
||||||
'Sep',
|
|
||||||
'Okt',
|
|
||||||
'Nov',
|
|
||||||
'Des',
|
|
||||||
];
|
|
||||||
|
|
||||||
switch (period) {
|
|
||||||
case 'daily':
|
|
||||||
// Format: "1 Des"
|
|
||||||
return `${date.getDate()} ${monthNames[date.getMonth()]}`;
|
|
||||||
|
|
||||||
case 'weekly':
|
|
||||||
// Format: "Week 1 Des"
|
|
||||||
const weekNumber = Math.ceil(date.getDate() / 7);
|
|
||||||
return `Week ${weekNumber} ${monthNames[date.getMonth()]}`;
|
|
||||||
|
|
||||||
case 'monthly':
|
|
||||||
// Format: "Des"
|
|
||||||
return monthNames[date.getMonth()];
|
|
||||||
|
|
||||||
case 'yearly':
|
|
||||||
// Format: "2025"
|
|
||||||
return date.getFullYear().toString();
|
|
||||||
|
|
||||||
default:
|
|
||||||
return dateString;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Type definitions for API data
|
|
||||||
interface FlockData {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
data: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ProductionChartItem {
|
|
||||||
date: string;
|
|
||||||
flocks: FlockData[];
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ProductionChartsData {
|
|
||||||
production_charts: ProductionChartItem[];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Transform API data to Recharts format
|
|
||||||
const transformProductionData = (apiData: ProductionChartItem[]) => {
|
|
||||||
return apiData.map((item) => {
|
|
||||||
const transformed: Record<string, string | number> = {
|
|
||||||
date: item.date.split('T')[0], // Extract YYYY-MM-DD from ISO string
|
|
||||||
};
|
|
||||||
|
|
||||||
// Add each flock's data as a property
|
|
||||||
item.flocks.forEach((flock) => {
|
|
||||||
transformed[flock.name] = flock.data;
|
|
||||||
});
|
|
||||||
|
|
||||||
return transformed;
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
interface ProductionLineChartProps {
|
|
||||||
period?: 'daily' | 'weekly' | 'monthly' | 'yearly';
|
|
||||||
data?: ProductionChartItem[]; // Optional API data
|
|
||||||
}
|
|
||||||
|
|
||||||
const ProductionLineChart = ({
|
|
||||||
period = 'daily',
|
|
||||||
data: apiData,
|
|
||||||
}: ProductionLineChartProps) => {
|
|
||||||
// State to track which lines are hidden
|
|
||||||
const [hiddenLines, setHiddenLines] = useState<string[]>([]);
|
|
||||||
|
|
||||||
// Use API data if provided, otherwise use sample data
|
|
||||||
const chartData = apiData
|
|
||||||
? transformProductionData(apiData)
|
|
||||||
: transformProductionData(sampleApiData);
|
|
||||||
|
|
||||||
// Handle legend click to show/hide lines
|
|
||||||
const handleLegendClick = (dataKey: string) => {
|
|
||||||
setHiddenLines((prev) =>
|
|
||||||
prev.includes(dataKey)
|
|
||||||
? prev.filter((key) => key !== dataKey)
|
|
||||||
: [...prev, dataKey]
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className='w-full h-full'>
|
|
||||||
<h3 className='text-lg font-semibold mb-4'>
|
|
||||||
Performa Produksi per Flock
|
|
||||||
</h3>
|
|
||||||
<ResponsiveContainer width='100%' height={400}>
|
|
||||||
<LineChart
|
|
||||||
data={chartData}
|
|
||||||
margin={{
|
|
||||||
top: 5,
|
|
||||||
right: 30,
|
|
||||||
left: 0,
|
|
||||||
bottom: 5,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<CartesianGrid strokeDasharray='3 3' stroke='#e5e7eb' />
|
|
||||||
<XAxis
|
|
||||||
dataKey='date'
|
|
||||||
tick={{ fontSize: 12 }}
|
|
||||||
tickLine={false}
|
|
||||||
axisLine={{ stroke: '#e5e7eb' }}
|
|
||||||
tickFormatter={(value) => formatDateByPeriod(value, period)}
|
|
||||||
/>
|
|
||||||
<YAxis
|
|
||||||
tick={{ fontSize: 12 }}
|
|
||||||
tickLine={false}
|
|
||||||
axisLine={{ stroke: '#e5e7eb' }}
|
|
||||||
domain={[0, 100]}
|
|
||||||
label={{
|
|
||||||
value: 'Persentase (%)',
|
|
||||||
angle: -90,
|
|
||||||
position: 'insideLeft',
|
|
||||||
style: { fontSize: 12 },
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<Tooltip
|
|
||||||
contentStyle={{
|
|
||||||
backgroundColor: 'white',
|
|
||||||
border: '1px solid #e5e7eb',
|
|
||||||
borderRadius: '8px',
|
|
||||||
padding: '8px 12px',
|
|
||||||
}}
|
|
||||||
labelFormatter={(value) =>
|
|
||||||
formatDateByPeriod(value as string, period)
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<Legend
|
|
||||||
wrapperStyle={{
|
|
||||||
paddingTop: '20px',
|
|
||||||
}}
|
|
||||||
iconType='circle'
|
|
||||||
onClick={(e) => {
|
|
||||||
if (e.dataKey) handleLegendClick(e.dataKey as string);
|
|
||||||
}}
|
|
||||||
style={{ cursor: 'pointer' }}
|
|
||||||
/>
|
|
||||||
<Line
|
|
||||||
type='monotone'
|
|
||||||
dataKey='Flock A-002'
|
|
||||||
stroke='#3b82f6'
|
|
||||||
strokeWidth={2}
|
|
||||||
dot={{ r: 4, fill: '#3b82f6' }}
|
|
||||||
activeDot={{ r: 6 }}
|
|
||||||
hide={hiddenLines.includes('Flock A-002')}
|
|
||||||
/>
|
|
||||||
<Line
|
|
||||||
type='monotone'
|
|
||||||
dataKey='Flock A-001'
|
|
||||||
stroke='#10b981'
|
|
||||||
strokeWidth={2}
|
|
||||||
dot={{ r: 4, fill: '#10b981' }}
|
|
||||||
activeDot={{ r: 6 }}
|
|
||||||
hide={hiddenLines.includes('Flock A-001')}
|
|
||||||
/>
|
|
||||||
<Line
|
|
||||||
type='monotone'
|
|
||||||
dataKey='Flock B-001'
|
|
||||||
stroke='#f59e0b'
|
|
||||||
strokeWidth={2}
|
|
||||||
dot={{ r: 4, fill: '#f59e0b' }}
|
|
||||||
activeDot={{ r: 6 }}
|
|
||||||
hide={hiddenLines.includes('Flock B-001')}
|
|
||||||
/>
|
|
||||||
<Line
|
|
||||||
type='monotone'
|
|
||||||
dataKey='Flock B-002'
|
|
||||||
stroke='#ef4444'
|
|
||||||
strokeWidth={2}
|
|
||||||
dot={{ r: 4, fill: '#ef4444' }}
|
|
||||||
activeDot={{ r: 6 }}
|
|
||||||
hide={hiddenLines.includes('Flock B-002')}
|
|
||||||
/>
|
|
||||||
</LineChart>
|
|
||||||
</ResponsiveContainer>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default ProductionLineChart;
|
|
||||||
|
|
||||||
// Export types for external use
|
|
||||||
export type { FlockData, ProductionChartItem, ProductionChartsData };
|
|
||||||
@@ -1,107 +0,0 @@
|
|||||||
import Card from '@/components/Card';
|
|
||||||
import { Icon } from '@iconify/react';
|
|
||||||
import { DashboardProductionStatisticsData } from '@/types/api/dashboard/dashboard-production';
|
|
||||||
import { formatCurrency } from '@/lib/helper';
|
|
||||||
|
|
||||||
interface ProductionStatProps {
|
|
||||||
data?: DashboardProductionStatisticsData[];
|
|
||||||
}
|
|
||||||
|
|
||||||
const ProductionStat = ({ data }: ProductionStatProps) => {
|
|
||||||
// Helper function to get icon based on title
|
|
||||||
const getIcon = (title: string) => {
|
|
||||||
if (title.toLowerCase().includes('keuangan'))
|
|
||||||
return 'heroicons:currency-dollar';
|
|
||||||
if (title.toLowerCase().includes('penjualan'))
|
|
||||||
return 'heroicons:arrow-trending-up';
|
|
||||||
if (title.toLowerCase().includes('pembelian'))
|
|
||||||
return 'heroicons:shopping-cart';
|
|
||||||
if (title.toLowerCase().includes('overhead')) return 'heroicons:calculator';
|
|
||||||
return 'heroicons:chart-bar';
|
|
||||||
};
|
|
||||||
|
|
||||||
// Helper function to get icon background color
|
|
||||||
const getIconBgColor = (title: string) => {
|
|
||||||
if (title.toLowerCase().includes('keuangan')) return 'bg-blue-500';
|
|
||||||
if (title.toLowerCase().includes('penjualan')) return 'bg-green-500';
|
|
||||||
if (title.toLowerCase().includes('pembelian')) return 'bg-orange-500';
|
|
||||||
if (title.toLowerCase().includes('overhead')) return 'bg-purple-500';
|
|
||||||
return 'bg-gray-500';
|
|
||||||
};
|
|
||||||
|
|
||||||
// Show loading state if no data
|
|
||||||
if (!data || data.length === 0) {
|
|
||||||
return (
|
|
||||||
<section className='grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4'>
|
|
||||||
{[1, 2, 3, 4].map((i) => (
|
|
||||||
<Card
|
|
||||||
key={i}
|
|
||||||
variant='bordered'
|
|
||||||
className={{ wrapper: 'w-full', body: 'p-4' }}
|
|
||||||
>
|
|
||||||
<div className='animate-pulse'>
|
|
||||||
<div className='h-4 bg-gray-200 rounded w-1/2 mb-2'></div>
|
|
||||||
<div className='h-6 bg-gray-200 rounded w-3/4 mb-1'></div>
|
|
||||||
<div className='h-4 bg-gray-200 rounded w-1/3'></div>
|
|
||||||
</div>
|
|
||||||
</Card>
|
|
||||||
))}
|
|
||||||
</section>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<section className='grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4'>
|
|
||||||
{data.map((stat, index) => (
|
|
||||||
<Card
|
|
||||||
key={index}
|
|
||||||
variant='bordered'
|
|
||||||
className={{ wrapper: 'w-full', body: 'p-4' }}
|
|
||||||
>
|
|
||||||
<div className='flex items-start justify-between'>
|
|
||||||
<div className='flex-1'>
|
|
||||||
<p className='text-sm text-gray-600 mb-2'>{stat.title}</p>
|
|
||||||
<p className='text-xl font-bold text-gray-900 mb-1'>
|
|
||||||
{formatCurrency(stat.value)}
|
|
||||||
</p>
|
|
||||||
<p
|
|
||||||
className={`text-sm flex items-center gap-1 ${
|
|
||||||
stat.changeType === 'increase'
|
|
||||||
? 'text-green-600'
|
|
||||||
: 'text-red-600'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<Icon
|
|
||||||
icon={
|
|
||||||
stat.changeType === 'increase'
|
|
||||||
? 'heroicons:arrow-trending-up'
|
|
||||||
: 'heroicons:arrow-trending-down'
|
|
||||||
}
|
|
||||||
width={16}
|
|
||||||
height={16}
|
|
||||||
/>
|
|
||||||
{stat.change > 0 ? '+' : ''}
|
|
||||||
{stat.change}% vs{' '}
|
|
||||||
{stat.period === 'monthly' ? 'bulan lalu' : 'periode lalu'}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className='flex-shrink-0'>
|
|
||||||
<div
|
|
||||||
className={`w-12 h-12 rounded-lg ${getIconBgColor(stat.title)} flex items-center justify-center`}
|
|
||||||
>
|
|
||||||
<Icon
|
|
||||||
icon={getIcon(stat.title)}
|
|
||||||
width={24}
|
|
||||||
height={24}
|
|
||||||
className='text-white'
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Card>
|
|
||||||
))}
|
|
||||||
</section>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default ProductionStat;
|
|
||||||
@@ -1,691 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useState } from 'react';
|
|
||||||
import {
|
|
||||||
LineChart,
|
|
||||||
Line,
|
|
||||||
XAxis,
|
|
||||||
YAxis,
|
|
||||||
CartesianGrid,
|
|
||||||
Tooltip,
|
|
||||||
Legend,
|
|
||||||
ResponsiveContainer,
|
|
||||||
} from 'recharts';
|
|
||||||
|
|
||||||
// Type definitions for API data
|
|
||||||
interface FlockData {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
data: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface StandardData {
|
|
||||||
name: string;
|
|
||||||
value: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface StandardChartItem {
|
|
||||||
week: number;
|
|
||||||
standards: StandardData[];
|
|
||||||
flocks: FlockData[];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sample data in API format
|
|
||||||
const sampleApiData: StandardChartItem[] = [
|
|
||||||
{
|
|
||||||
week: 18,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 40 },
|
|
||||||
{ name: 'hen_house', value: 38 },
|
|
||||||
{ name: 'uniformity', value: 85 },
|
|
||||||
{ name: 'egg_weight', value: 52 },
|
|
||||||
{ name: 'egg_mass', value: 20 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 38 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 37 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 39 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 36 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 20,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 45 },
|
|
||||||
{ name: 'hen_house', value: 43 },
|
|
||||||
{ name: 'uniformity', value: 86 },
|
|
||||||
{ name: 'egg_weight', value: 54 },
|
|
||||||
{ name: 'egg_mass', value: 24 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 43 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 42 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 44 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 41 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 22,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 48 },
|
|
||||||
{ name: 'hen_house', value: 46 },
|
|
||||||
{ name: 'uniformity', value: 87 },
|
|
||||||
{ name: 'egg_weight', value: 55 },
|
|
||||||
{ name: 'egg_mass', value: 26 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 47 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 46 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 48 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 45 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 24,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 50 },
|
|
||||||
{ name: 'hen_house', value: 48 },
|
|
||||||
{ name: 'uniformity', value: 88 },
|
|
||||||
{ name: 'egg_weight', value: 56 },
|
|
||||||
{ name: 'egg_mass', value: 28 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 49 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 48 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 50 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 47 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 26,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 52 },
|
|
||||||
{ name: 'hen_house', value: 50 },
|
|
||||||
{ name: 'uniformity', value: 89 },
|
|
||||||
{ name: 'egg_weight', value: 57 },
|
|
||||||
{ name: 'egg_mass', value: 30 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 50 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 49 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 51 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 48 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 28,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 55 },
|
|
||||||
{ name: 'hen_house', value: 53 },
|
|
||||||
{ name: 'uniformity', value: 90 },
|
|
||||||
{ name: 'egg_weight', value: 58 },
|
|
||||||
{ name: 'egg_mass', value: 32 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 53 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 52 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 54 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 51 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 30,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 58 },
|
|
||||||
{ name: 'hen_house', value: 56 },
|
|
||||||
{ name: 'uniformity', value: 91 },
|
|
||||||
{ name: 'egg_weight', value: 59 },
|
|
||||||
{ name: 'egg_mass', value: 34 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 55 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 54 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 56 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 53 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 32,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 60 },
|
|
||||||
{ name: 'hen_house', value: 58 },
|
|
||||||
{ name: 'uniformity', value: 92 },
|
|
||||||
{ name: 'egg_weight', value: 60 },
|
|
||||||
{ name: 'egg_mass', value: 36 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 58 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 57 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 59 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 56 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 34,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 62 },
|
|
||||||
{ name: 'hen_house', value: 60 },
|
|
||||||
{ name: 'uniformity', value: 92 },
|
|
||||||
{ name: 'egg_weight', value: 61 },
|
|
||||||
{ name: 'egg_mass', value: 38 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 60 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 59 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 61 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 58 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 36,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 64 },
|
|
||||||
{ name: 'hen_house', value: 62 },
|
|
||||||
{ name: 'uniformity', value: 93 },
|
|
||||||
{ name: 'egg_weight', value: 62 },
|
|
||||||
{ name: 'egg_mass', value: 40 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 62 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 61 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 63 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 60 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 38,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 66 },
|
|
||||||
{ name: 'hen_house', value: 64 },
|
|
||||||
{ name: 'uniformity', value: 93 },
|
|
||||||
{ name: 'egg_weight', value: 63 },
|
|
||||||
{ name: 'egg_mass', value: 42 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 64 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 63 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 65 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 62 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 40,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 68 },
|
|
||||||
{ name: 'hen_house', value: 66 },
|
|
||||||
{ name: 'uniformity', value: 94 },
|
|
||||||
{ name: 'egg_weight', value: 64 },
|
|
||||||
{ name: 'egg_mass', value: 44 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 66 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 65 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 67 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 64 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 42,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 70 },
|
|
||||||
{ name: 'hen_house', value: 68 },
|
|
||||||
{ name: 'uniformity', value: 94 },
|
|
||||||
{ name: 'egg_weight', value: 65 },
|
|
||||||
{ name: 'egg_mass', value: 46 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 68 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 67 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 69 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 66 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 44,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 72 },
|
|
||||||
{ name: 'hen_house', value: 70 },
|
|
||||||
{ name: 'uniformity', value: 95 },
|
|
||||||
{ name: 'egg_weight', value: 66 },
|
|
||||||
{ name: 'egg_mass', value: 48 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 70 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 69 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 71 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 68 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 46,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 74 },
|
|
||||||
{ name: 'hen_house', value: 72 },
|
|
||||||
{ name: 'uniformity', value: 95 },
|
|
||||||
{ name: 'egg_weight', value: 67 },
|
|
||||||
{ name: 'egg_mass', value: 50 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 72 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 71 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 73 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 70 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 48,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 76 },
|
|
||||||
{ name: 'hen_house', value: 74 },
|
|
||||||
{ name: 'uniformity', value: 95 },
|
|
||||||
{ name: 'egg_weight', value: 68 },
|
|
||||||
{ name: 'egg_mass', value: 52 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 74 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 73 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 75 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 72 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 50,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 78 },
|
|
||||||
{ name: 'hen_house', value: 76 },
|
|
||||||
{ name: 'uniformity', value: 96 },
|
|
||||||
{ name: 'egg_weight', value: 69 },
|
|
||||||
{ name: 'egg_mass', value: 54 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 76 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 75 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 77 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 74 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 52,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 80 },
|
|
||||||
{ name: 'hen_house', value: 78 },
|
|
||||||
{ name: 'uniformity', value: 96 },
|
|
||||||
{ name: 'egg_weight', value: 70 },
|
|
||||||
{ name: 'egg_mass', value: 56 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 78 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 77 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 79 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 76 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 54,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 82 },
|
|
||||||
{ name: 'hen_house', value: 80 },
|
|
||||||
{ name: 'uniformity', value: 96 },
|
|
||||||
{ name: 'egg_weight', value: 71 },
|
|
||||||
{ name: 'egg_mass', value: 58 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 80 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 79 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 81 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 78 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 56,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 84 },
|
|
||||||
{ name: 'hen_house', value: 82 },
|
|
||||||
{ name: 'uniformity', value: 97 },
|
|
||||||
{ name: 'egg_weight', value: 72 },
|
|
||||||
{ name: 'egg_mass', value: 60 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 82 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 81 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 83 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 80 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 58,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 86 },
|
|
||||||
{ name: 'hen_house', value: 84 },
|
|
||||||
{ name: 'uniformity', value: 97 },
|
|
||||||
{ name: 'egg_weight', value: 73 },
|
|
||||||
{ name: 'egg_mass', value: 62 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 84 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 83 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 85 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 82 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 60,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 88 },
|
|
||||||
{ name: 'hen_house', value: 86 },
|
|
||||||
{ name: 'uniformity', value: 97 },
|
|
||||||
{ name: 'egg_weight', value: 74 },
|
|
||||||
{ name: 'egg_mass', value: 64 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 86 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 85 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 87 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 84 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 62,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 90 },
|
|
||||||
{ name: 'hen_house', value: 88 },
|
|
||||||
{ name: 'uniformity', value: 98 },
|
|
||||||
{ name: 'egg_weight', value: 75 },
|
|
||||||
{ name: 'egg_mass', value: 66 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 88 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 87 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 89 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 86 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 64,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 92 },
|
|
||||||
{ name: 'hen_house', value: 90 },
|
|
||||||
{ name: 'uniformity', value: 98 },
|
|
||||||
{ name: 'egg_weight', value: 76 },
|
|
||||||
{ name: 'egg_mass', value: 68 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 90 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 89 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 91 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 88 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 66,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 94 },
|
|
||||||
{ name: 'hen_house', value: 92 },
|
|
||||||
{ name: 'uniformity', value: 98 },
|
|
||||||
{ name: 'egg_weight', value: 77 },
|
|
||||||
{ name: 'egg_mass', value: 70 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 92 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 91 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 93 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 90 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 68,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 95 },
|
|
||||||
{ name: 'hen_house', value: 93 },
|
|
||||||
{ name: 'uniformity', value: 98 },
|
|
||||||
{ name: 'egg_weight', value: 78 },
|
|
||||||
{ name: 'egg_mass', value: 72 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 93 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 92 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 94 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 91 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 70,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 96 },
|
|
||||||
{ name: 'hen_house', value: 94 },
|
|
||||||
{ name: 'uniformity', value: 99 },
|
|
||||||
{ name: 'egg_weight', value: 79 },
|
|
||||||
{ name: 'egg_mass', value: 74 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 94 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 93 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 95 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 92 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
week: 72,
|
|
||||||
standards: [
|
|
||||||
{ name: 'hen_day', value: 97 },
|
|
||||||
{ name: 'hen_house', value: 95 },
|
|
||||||
{ name: 'uniformity', value: 99 },
|
|
||||||
{ name: 'egg_weight', value: 80 },
|
|
||||||
{ name: 'egg_mass', value: 76 },
|
|
||||||
],
|
|
||||||
flocks: [
|
|
||||||
{ id: 1, name: 'Flock A-001', data: 95 },
|
|
||||||
{ id: 2, name: 'Flock A-002', data: 94 },
|
|
||||||
{ id: 3, name: 'Flock B-001', data: 96 },
|
|
||||||
{ id: 4, name: 'Flock B-002', data: 93 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
// Transform API data to Recharts format
|
|
||||||
const transformStandardData = (
|
|
||||||
apiData: StandardChartItem[],
|
|
||||||
selectedStandards: string[] = [
|
|
||||||
'hen_day',
|
|
||||||
'hen_house',
|
|
||||||
'uniformity',
|
|
||||||
'egg_weight',
|
|
||||||
'egg_mass',
|
|
||||||
]
|
|
||||||
) => {
|
|
||||||
return apiData.map((item) => {
|
|
||||||
const transformed: Record<string, number> = {
|
|
||||||
week: item.week,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Add selected standards as properties
|
|
||||||
selectedStandards.forEach((standardName) => {
|
|
||||||
const standardData = item.standards.find((s) => s.name === standardName);
|
|
||||||
if (standardData) {
|
|
||||||
transformed[standardName] = standardData.value;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Add each flock's data as a property
|
|
||||||
item.flocks.forEach((flock) => {
|
|
||||||
transformed[flock.name] = flock.data;
|
|
||||||
});
|
|
||||||
|
|
||||||
return transformed;
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
interface StandardLineChartProps {
|
|
||||||
data?: StandardChartItem[];
|
|
||||||
selectedStandards?: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
const StandardLineChart = ({
|
|
||||||
data: apiData,
|
|
||||||
selectedStandards = [
|
|
||||||
'hen_day',
|
|
||||||
'hen_house',
|
|
||||||
'uniformity',
|
|
||||||
'egg_weight',
|
|
||||||
'egg_mass',
|
|
||||||
],
|
|
||||||
}: StandardLineChartProps) => {
|
|
||||||
// State to track which lines are hidden
|
|
||||||
const [hiddenLines, setHiddenLines] = useState<string[]>([]);
|
|
||||||
|
|
||||||
// Use API data if provided, otherwise use sample data
|
|
||||||
const chartData = apiData
|
|
||||||
? transformStandardData(apiData, selectedStandards)
|
|
||||||
: transformStandardData(sampleApiData, selectedStandards);
|
|
||||||
|
|
||||||
// Handle legend click to show/hide lines
|
|
||||||
const handleLegendClick = (dataKey: string) => {
|
|
||||||
setHiddenLines((prev) =>
|
|
||||||
prev.includes(dataKey)
|
|
||||||
? prev.filter((key) => key !== dataKey)
|
|
||||||
: [...prev, dataKey]
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
// Standard line colors mapping
|
|
||||||
const standardColors: Record<string, string> = {
|
|
||||||
hen_day: '#94a3b8',
|
|
||||||
hen_house: '#64748b',
|
|
||||||
uniformity: '#475569',
|
|
||||||
egg_weight: '#334155',
|
|
||||||
egg_mass: '#1e293b',
|
|
||||||
};
|
|
||||||
|
|
||||||
// Standard names mapping for display
|
|
||||||
const standardLabels: Record<string, string> = {
|
|
||||||
hen_day: 'Hen Day',
|
|
||||||
hen_house: 'Hen House',
|
|
||||||
uniformity: 'Uniformity',
|
|
||||||
egg_weight: 'Egg Weight',
|
|
||||||
egg_mass: 'Egg Mass',
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className='w-full h-full'>
|
|
||||||
<h3 className='text-lg font-semibold mb-4'>
|
|
||||||
Perbandingan Henday per Umur
|
|
||||||
</h3>
|
|
||||||
<ResponsiveContainer width='100%' height={400}>
|
|
||||||
<LineChart
|
|
||||||
data={chartData}
|
|
||||||
margin={{
|
|
||||||
top: 5,
|
|
||||||
right: 30,
|
|
||||||
left: 0,
|
|
||||||
bottom: 5,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<CartesianGrid strokeDasharray='3 3' stroke='#e5e7eb' />
|
|
||||||
<XAxis
|
|
||||||
dataKey='week'
|
|
||||||
tick={{ fontSize: 12 }}
|
|
||||||
tickLine={false}
|
|
||||||
axisLine={{ stroke: '#e5e7eb' }}
|
|
||||||
label={{
|
|
||||||
value: 'Umur (minggu)',
|
|
||||||
position: 'insideBottom',
|
|
||||||
offset: -5,
|
|
||||||
style: { fontSize: 12 },
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<YAxis
|
|
||||||
tick={{ fontSize: 12 }}
|
|
||||||
tickLine={false}
|
|
||||||
axisLine={{ stroke: '#e5e7eb' }}
|
|
||||||
domain={[0, 100]}
|
|
||||||
label={{
|
|
||||||
value: 'Henday (%)',
|
|
||||||
angle: -90,
|
|
||||||
position: 'insideLeft',
|
|
||||||
style: { fontSize: 12 },
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<Tooltip
|
|
||||||
contentStyle={{
|
|
||||||
backgroundColor: 'white',
|
|
||||||
border: '1px solid #e5e7eb',
|
|
||||||
borderRadius: '8px',
|
|
||||||
padding: '8px 12px',
|
|
||||||
}}
|
|
||||||
formatter={(value: number | undefined) =>
|
|
||||||
value !== undefined ? [`${value}%`, ''] : ['', '']
|
|
||||||
}
|
|
||||||
labelFormatter={(label) => `Minggu ${label}`}
|
|
||||||
/>
|
|
||||||
<Legend
|
|
||||||
wrapperStyle={{
|
|
||||||
paddingTop: '20px',
|
|
||||||
}}
|
|
||||||
iconType='circle'
|
|
||||||
onClick={(e) => {
|
|
||||||
if (e.dataKey) handleLegendClick(e.dataKey as string);
|
|
||||||
}}
|
|
||||||
style={{ cursor: 'pointer' }}
|
|
||||||
/>
|
|
||||||
{/* Dynamic Standard Lines */}
|
|
||||||
{selectedStandards.map((standardName) => (
|
|
||||||
<Line
|
|
||||||
key={standardName}
|
|
||||||
type='monotone'
|
|
||||||
dataKey={standardName}
|
|
||||||
name={standardLabels[standardName] || standardName}
|
|
||||||
stroke={standardColors[standardName] || '#94a3b8'}
|
|
||||||
strokeWidth={2}
|
|
||||||
strokeDasharray='5 5'
|
|
||||||
dot={{ r: 3, fill: standardColors[standardName] || '#94a3b8' }}
|
|
||||||
activeDot={{ r: 5 }}
|
|
||||||
hide={hiddenLines.includes(standardName)}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
{/* Flock Lines */}
|
|
||||||
<Line
|
|
||||||
type='monotone'
|
|
||||||
dataKey='Flock A-002'
|
|
||||||
stroke='#3b82f6'
|
|
||||||
strokeWidth={2}
|
|
||||||
dot={{ r: 4, fill: '#3b82f6' }}
|
|
||||||
activeDot={{ r: 6 }}
|
|
||||||
hide={hiddenLines.includes('Flock A-002')}
|
|
||||||
/>
|
|
||||||
<Line
|
|
||||||
type='monotone'
|
|
||||||
dataKey='Flock A-001'
|
|
||||||
stroke='#10b981'
|
|
||||||
strokeWidth={2}
|
|
||||||
dot={{ r: 4, fill: '#10b981' }}
|
|
||||||
activeDot={{ r: 6 }}
|
|
||||||
hide={hiddenLines.includes('Flock A-001')}
|
|
||||||
/>
|
|
||||||
<Line
|
|
||||||
type='monotone'
|
|
||||||
dataKey='Flock B-001'
|
|
||||||
stroke='#f59e0b'
|
|
||||||
strokeWidth={2}
|
|
||||||
dot={{ r: 4, fill: '#f59e0b' }}
|
|
||||||
activeDot={{ r: 6 }}
|
|
||||||
hide={hiddenLines.includes('Flock B-001')}
|
|
||||||
/>
|
|
||||||
<Line
|
|
||||||
type='monotone'
|
|
||||||
dataKey='Flock B-002'
|
|
||||||
stroke='#ef4444'
|
|
||||||
strokeWidth={2}
|
|
||||||
dot={{ r: 4, fill: '#ef4444' }}
|
|
||||||
activeDot={{ r: 6 }}
|
|
||||||
hide={hiddenLines.includes('Flock B-002')}
|
|
||||||
/>
|
|
||||||
</LineChart>
|
|
||||||
</ResponsiveContainer>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default StandardLineChart;
|
|
||||||
|
|
||||||
// Export types for external use
|
|
||||||
export type { FlockData, StandardData, StandardChartItem };
|
|
||||||
@@ -1,16 +1,117 @@
|
|||||||
|
import { OptionType } from '@/components/input/SelectInput';
|
||||||
import * as yup from 'yup';
|
import * as yup from 'yup';
|
||||||
|
|
||||||
const dashboardProductionFilterSchema = yup.object({
|
export type DashboardFilterType = {
|
||||||
startDate: yup.string().optional(),
|
startDate: string;
|
||||||
endDate: yup.string().optional(),
|
endDate: string;
|
||||||
flock: yup.array().optional(),
|
analysisMode: string;
|
||||||
standard_production_id: yup.array().optional(),
|
comparisonType: string | undefined;
|
||||||
standard_productions: yup.array().optional(),
|
location: OptionType | OptionType[];
|
||||||
period: yup.string().optional(),
|
lokasiIds: number[] | undefined;
|
||||||
|
flock: OptionType | OptionType[] | undefined;
|
||||||
|
flockIds: number[] | undefined;
|
||||||
|
kandang: OptionType | OptionType[] | undefined;
|
||||||
|
kandangIds: number[] | undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Schema untuk mode OVERVIEW - semua field required
|
||||||
|
export const DashboardFilterOverviewSchema: yup.ObjectSchema<DashboardFilterType> =
|
||||||
|
yup.object({
|
||||||
|
startDate: yup.string().required('Start date is required'),
|
||||||
|
endDate: yup.string().required('End date is required'),
|
||||||
|
analysisMode: yup.string().required('Analysis mode is required'),
|
||||||
|
comparisonType: yup.string().when('analysisMode', {
|
||||||
|
is: 'COMPARISON',
|
||||||
|
then: (schema) => schema.required('Compared by is required'),
|
||||||
|
otherwise: (schema) => schema.optional(),
|
||||||
|
}),
|
||||||
|
lokasiIds: yup.array().optional(),
|
||||||
|
flockIds: yup.array().optional(),
|
||||||
|
kandangIds: yup.array().optional(),
|
||||||
|
location: yup
|
||||||
|
.mixed<OptionType | OptionType[]>()
|
||||||
|
.required('Farm is required')
|
||||||
|
.test('is-not-empty', 'Farm is required', (value) => {
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
return value.length > 0;
|
||||||
|
}
|
||||||
|
return !!value;
|
||||||
|
}),
|
||||||
|
flock: yup
|
||||||
|
.mixed<OptionType | OptionType[]>()
|
||||||
|
.required('Flock is required')
|
||||||
|
.test('is-not-empty', 'Flock is required', (value) => {
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
return value.length > 0;
|
||||||
|
}
|
||||||
|
return !!value;
|
||||||
|
}),
|
||||||
|
kandang: yup
|
||||||
|
.mixed<OptionType | OptionType[]>()
|
||||||
|
.required('Kandang is required')
|
||||||
|
.test('is-not-empty', 'Kandang is required', (value) => {
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
return value.length > 0;
|
||||||
|
}
|
||||||
|
return !!value;
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
export type DashboardProductionFilterValues = yup.InferType<
|
// Schema untuk mode COMPARISON - conditional validation
|
||||||
typeof dashboardProductionFilterSchema
|
export const DashboardFilterComparisonSchema: yup.ObjectSchema<DashboardFilterType> =
|
||||||
>;
|
yup.object({
|
||||||
|
startDate: yup.string().required('Start date is required'),
|
||||||
|
endDate: yup.string().required('End date is required'),
|
||||||
|
analysisMode: yup.string().required('Analysis mode is required'),
|
||||||
|
comparisonType: yup.string().when('analysisMode', {
|
||||||
|
is: 'COMPARISON',
|
||||||
|
then: (schema) => schema.required('Compared by is required'),
|
||||||
|
otherwise: (schema) => schema.optional(),
|
||||||
|
}),
|
||||||
|
lokasiIds: yup.array().optional(),
|
||||||
|
flockIds: yup.array().optional(),
|
||||||
|
kandangIds: yup.array().optional(),
|
||||||
|
location: yup
|
||||||
|
.mixed<OptionType | OptionType[]>()
|
||||||
|
.required('Farm is required')
|
||||||
|
.test('is-not-empty', 'Farm is required', (value) => {
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
return value.length > 0;
|
||||||
|
}
|
||||||
|
return !!value;
|
||||||
|
}),
|
||||||
|
flock: yup.mixed<OptionType | OptionType[]>().when('comparisonType', {
|
||||||
|
is: (value: string) => value === 'FLOCK' || value === 'KANDANG',
|
||||||
|
then: (schema) =>
|
||||||
|
schema.test('is-required', 'Flock is required', (value) => {
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
return value.length > 0;
|
||||||
|
}
|
||||||
|
return !!value;
|
||||||
|
}),
|
||||||
|
otherwise: (schema) => schema.optional(),
|
||||||
|
}),
|
||||||
|
kandang: yup.mixed<OptionType | OptionType[]>().when('comparisonType', {
|
||||||
|
is: 'KANDANG',
|
||||||
|
then: (schema) =>
|
||||||
|
schema.test('is-required', 'Kandang is required', (value) => {
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
return value.length > 0;
|
||||||
|
}
|
||||||
|
return !!value;
|
||||||
|
}),
|
||||||
|
otherwise: (schema) => schema.optional(),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
export default dashboardProductionFilterSchema;
|
// Helper function untuk mendapatkan schema yang sesuai berdasarkan analysis mode
|
||||||
|
export const getDashboardFilterSchema = (analysisMode?: string) => {
|
||||||
|
return analysisMode === 'OVERVIEW'
|
||||||
|
? DashboardFilterOverviewSchema
|
||||||
|
: DashboardFilterComparisonSchema;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Default schema
|
||||||
|
export const DashboardFilterSchema = DashboardFilterComparisonSchema;
|
||||||
|
|
||||||
|
export type DashboardFilterValues = yup.InferType<typeof DashboardFilterSchema>;
|
||||||
|
|||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import { Icon } from '@iconify/react';
|
||||||
|
import { DashboardMeta } from '@/types/api/dashboard/dashboard';
|
||||||
|
|
||||||
|
const DashboardLineChartSkeleton = ({ meta }: { meta?: DashboardMeta }) => {
|
||||||
|
return (
|
||||||
|
<div className='w-full bg-white rounded-lg shadow-sm border border-gray-200 p-6 relative'>
|
||||||
|
{/* Header with title skeleton */}
|
||||||
|
<div className='text-lg font-semibold'>
|
||||||
|
Performance{' '}
|
||||||
|
<Icon
|
||||||
|
icon='heroicons:information-circle'
|
||||||
|
width={20}
|
||||||
|
height={20}
|
||||||
|
className='inline text-neutral-500'
|
||||||
|
/>
|
||||||
|
</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'>
|
||||||
|
<Icon
|
||||||
|
icon='heroicons:funnel'
|
||||||
|
className='text-white'
|
||||||
|
width={24}
|
||||||
|
height={24}
|
||||||
|
/>
|
||||||
|
</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'>
|
||||||
|
<Icon
|
||||||
|
icon='heroicons:chart-bar'
|
||||||
|
className='text-white'
|
||||||
|
width={24}
|
||||||
|
height={24}
|
||||||
|
/>
|
||||||
|
</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>
|
||||||
|
|
||||||
|
{/* 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>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default DashboardLineChartSkeleton;
|
||||||
@@ -28,7 +28,7 @@ const ExpenseDetail: React.FC<ExpenseDetailProps> = ({ initialValues }) => {
|
|||||||
|
|
||||||
if (
|
if (
|
||||||
initialValues?.latest_approval &&
|
initialValues?.latest_approval &&
|
||||||
initialValues?.latest_approval.step_number >= 4 &&
|
initialValues?.latest_approval.step_number >= 5 &&
|
||||||
initialValues.latest_approval.action !== 'REJECTED'
|
initialValues.latest_approval.action !== 'REJECTED'
|
||||||
) {
|
) {
|
||||||
validTabs.push({
|
validTabs.push({
|
||||||
|
|||||||
@@ -48,6 +48,13 @@ const ExpenseRealizationContent = ({
|
|||||||
|
|
||||||
const realizationDocumentsChangeHandler = (val: File[]) => {
|
const realizationDocumentsChangeHandler = (val: File[]) => {
|
||||||
formik.setFieldTouched('documents', true);
|
formik.setFieldTouched('documents', true);
|
||||||
|
|
||||||
|
const invalidFiles = val.filter((file) => file.size > 5 * 1024 * 1024);
|
||||||
|
if (invalidFiles.length > 0) {
|
||||||
|
toast.error('Ukuran dokumen maksimal 5 MB!');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
formik.setFieldValue('documents', val);
|
formik.setFieldValue('documents', val);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -59,34 +59,40 @@ const ExpenseRequestContent = ({
|
|||||||
|
|
||||||
const isLatestApprovalRejectedOrDone =
|
const isLatestApprovalRejectedOrDone =
|
||||||
isLatestApprovalRejected ||
|
isLatestApprovalRejected ||
|
||||||
initialValues?.latest_approval.step_number === 5;
|
initialValues?.latest_approval.step_number === 6;
|
||||||
|
|
||||||
const isCurrentApprovalOnManager =
|
const isCurrentApprovalOnHeadArea =
|
||||||
!isLatestApprovalRejected &&
|
!isLatestApprovalRejected &&
|
||||||
initialValues?.latest_approval.step_number === 1;
|
initialValues?.latest_approval.step_number === 1;
|
||||||
|
|
||||||
const isCurrentApprovalOnFinance =
|
const isCurrentApprovalOnUnitVicePresident =
|
||||||
!isLatestApprovalRejected &&
|
!isLatestApprovalRejected &&
|
||||||
initialValues?.latest_approval.step_number === 2;
|
initialValues?.latest_approval.step_number === 2;
|
||||||
|
|
||||||
|
const isCurrentApprovalOnFinance =
|
||||||
|
!isLatestApprovalRejected &&
|
||||||
|
initialValues?.latest_approval.step_number === 3;
|
||||||
|
|
||||||
const isCurrentApprovalOnRealization =
|
const isCurrentApprovalOnRealization =
|
||||||
!isLatestApprovalRejected &&
|
!isLatestApprovalRejected &&
|
||||||
initialValues?.latest_approval.step_number === 4;
|
initialValues?.latest_approval.step_number === 5;
|
||||||
|
|
||||||
const showEditButton =
|
const showEditButton =
|
||||||
initialValues?.latest_approval.step_number !== 5 &&
|
initialValues?.latest_approval.step_number !== 6 &&
|
||||||
(initialValues?.latest_approval.step_number === 1 ||
|
(initialValues?.latest_approval.step_number === 1 ||
|
||||||
initialValues?.latest_approval.step_number === 2 ||
|
initialValues?.latest_approval.step_number === 2 ||
|
||||||
initialValues?.latest_approval.step_number === 3);
|
initialValues?.latest_approval.step_number === 3 ||
|
||||||
|
initialValues?.latest_approval.step_number === 4);
|
||||||
|
|
||||||
const showRejectButton =
|
const showRejectButton =
|
||||||
!isLatestApprovalRejected &&
|
!isLatestApprovalRejected &&
|
||||||
(initialValues?.latest_approval.step_number === 1 ||
|
(initialValues?.latest_approval.step_number === 1 ||
|
||||||
initialValues?.latest_approval.step_number === 2);
|
initialValues?.latest_approval.step_number === 2 ||
|
||||||
|
initialValues?.latest_approval.step_number === 3);
|
||||||
|
|
||||||
const isExpenseCanBeRealized =
|
const isExpenseCanBeRealized =
|
||||||
!isLatestApprovalRejected &&
|
!isLatestApprovalRejected &&
|
||||||
initialValues?.latest_approval.step_number === 3;
|
initialValues?.latest_approval.step_number === 4;
|
||||||
|
|
||||||
// Modal hooks
|
// Modal hooks
|
||||||
const deleteModal = useModal();
|
const deleteModal = useModal();
|
||||||
@@ -174,8 +180,15 @@ const ExpenseRequestContent = ({
|
|||||||
|
|
||||||
let approveResponse: BaseApiResponse<Expense> | undefined = undefined;
|
let approveResponse: BaseApiResponse<Expense> | undefined = undefined;
|
||||||
|
|
||||||
if (isCurrentApprovalOnManager) {
|
if (isCurrentApprovalOnHeadArea) {
|
||||||
approveResponse = await ExpenseApi.approveManager(
|
approveResponse = await ExpenseApi.approveHeadArea(
|
||||||
|
initialValues.id,
|
||||||
|
notes
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isCurrentApprovalOnUnitVicePresident) {
|
||||||
|
approveResponse = await ExpenseApi.approveUnitVicePresident(
|
||||||
initialValues.id,
|
initialValues.id,
|
||||||
notes
|
notes
|
||||||
);
|
);
|
||||||
@@ -207,8 +220,15 @@ const ExpenseRequestContent = ({
|
|||||||
|
|
||||||
let rejectResponse: BaseApiResponse<Expense> | undefined = undefined;
|
let rejectResponse: BaseApiResponse<Expense> | undefined = undefined;
|
||||||
|
|
||||||
if (isCurrentApprovalOnManager) {
|
if (isCurrentApprovalOnHeadArea) {
|
||||||
rejectResponse = await ExpenseApi.rejectManager(initialValues.id, notes);
|
rejectResponse = await ExpenseApi.rejectHeadArea(initialValues.id, notes);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isCurrentApprovalOnUnitVicePresident) {
|
||||||
|
rejectResponse = await ExpenseApi.rejectUnitVicePresident(
|
||||||
|
initialValues.id,
|
||||||
|
notes
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isCurrentApprovalOnFinance) {
|
if (isCurrentApprovalOnFinance) {
|
||||||
@@ -231,6 +251,13 @@ const ExpenseRequestContent = ({
|
|||||||
|
|
||||||
const requestDocumentsChangeHandler = (val: File[]) => {
|
const requestDocumentsChangeHandler = (val: File[]) => {
|
||||||
formik.setFieldTouched('documents', true);
|
formik.setFieldTouched('documents', true);
|
||||||
|
|
||||||
|
const invalidFiles = val.filter((file) => file.size > 5 * 1024 * 1024);
|
||||||
|
if (invalidFiles.length > 0) {
|
||||||
|
toast.error('Ukuran dokumen maksimal 5 MB!');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
formik.setFieldValue('documents', val);
|
formik.setFieldValue('documents', val);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -255,8 +282,8 @@ const ExpenseRequestContent = ({
|
|||||||
{/* TODO: apply RBAC */}
|
{/* 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 max-w-5xl mx-auto flex flex-col sm:flex-row justify-end gap-2'>
|
||||||
{isCurrentApprovalOnManager && (
|
{isCurrentApprovalOnHeadArea && (
|
||||||
<RequirePermission permissions='lti.expense.approve.manager'>
|
<RequirePermission permissions='lti.expense.approve.head_area'>
|
||||||
<Button
|
<Button
|
||||||
variant='outline'
|
variant='outline'
|
||||||
color='info'
|
color='info'
|
||||||
@@ -264,7 +291,21 @@ const ExpenseRequestContent = ({
|
|||||||
className='w-full sm:w-fit'
|
className='w-full sm:w-fit'
|
||||||
>
|
>
|
||||||
<Icon icon='lucide-lab:farm' width={24} height={24} />
|
<Icon icon='lucide-lab:farm' width={24} height={24} />
|
||||||
Approve Manager
|
Approve Head Area
|
||||||
|
</Button>
|
||||||
|
</RequirePermission>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{isCurrentApprovalOnUnitVicePresident && (
|
||||||
|
<RequirePermission permissions='lti.expense.approve.unit_vice_president'>
|
||||||
|
<Button
|
||||||
|
variant='outline'
|
||||||
|
color='success'
|
||||||
|
onClick={approveClickHandler}
|
||||||
|
className='w-full sm:w-fit'
|
||||||
|
>
|
||||||
|
<Icon icon='tdesign:money' width={24} height={24} />
|
||||||
|
Approve Unit Vice President
|
||||||
</Button>
|
</Button>
|
||||||
</RequirePermission>
|
</RequirePermission>
|
||||||
)}
|
)}
|
||||||
@@ -304,7 +345,8 @@ const ExpenseRequestContent = ({
|
|||||||
{showRejectButton && (
|
{showRejectButton && (
|
||||||
<RequirePermission
|
<RequirePermission
|
||||||
permissions={[
|
permissions={[
|
||||||
'lti.expense.approve.manager',
|
'lti.expense.approve.head_area',
|
||||||
|
'lti.expense.approve.unit_vice_president',
|
||||||
'lti.expense.approve.finance',
|
'lti.expense.approve.finance',
|
||||||
]}
|
]}
|
||||||
>
|
>
|
||||||
@@ -454,8 +496,8 @@ const ExpenseRequestContent = ({
|
|||||||
<th>:</th>
|
<th>:</th>
|
||||||
<td>
|
<td>
|
||||||
{formatCurrency(
|
{formatCurrency(
|
||||||
initialValues?.latest_approval.step_number === 4 ||
|
initialValues?.latest_approval.step_number === 5 ||
|
||||||
initialValues?.latest_approval.step_number === 5
|
initialValues?.latest_approval.step_number === 6
|
||||||
? (initialValues?.total_realisasi ?? 0)
|
? (initialValues?.total_realisasi ?? 0)
|
||||||
: (initialValues?.total_pengajuan ?? 0)
|
: (initialValues?.total_pengajuan ?? 0)
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -39,6 +39,10 @@ const ExpenseStatusBadge = ({ approval }: ExpenseStatusBadgeProps) => {
|
|||||||
case 5:
|
case 5:
|
||||||
expenseStatusPillBadgeColor = 'green';
|
expenseStatusPillBadgeColor = 'green';
|
||||||
break;
|
break;
|
||||||
|
|
||||||
|
case 6:
|
||||||
|
expenseStatusPillBadgeColor = 'green';
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isLatestApprovalRejected) {
|
if (isLatestApprovalRejected) {
|
||||||
|
|||||||
@@ -55,15 +55,16 @@ const RowOptionsMenu = ({
|
|||||||
deleteClickHandler: () => void;
|
deleteClickHandler: () => void;
|
||||||
}) => {
|
}) => {
|
||||||
const showEditButton =
|
const showEditButton =
|
||||||
props.row.original.latest_approval.step_number !== 5 &&
|
props.row.original.latest_approval.step_number !== 6 &&
|
||||||
(props.row.original.latest_approval.step_number === 1 ||
|
(props.row.original.latest_approval.step_number === 1 ||
|
||||||
props.row.original.latest_approval.step_number === 2 ||
|
props.row.original.latest_approval.step_number === 2 ||
|
||||||
props.row.original.latest_approval.step_number === 3);
|
props.row.original.latest_approval.step_number === 3 ||
|
||||||
|
props.row.original.latest_approval.step_number === 4);
|
||||||
|
|
||||||
// TODO: apply RBAC
|
// TODO: apply RBAC
|
||||||
const showRealizationButton =
|
const showRealizationButton =
|
||||||
props.row.original.latest_approval.action !== 'REJECTED' &&
|
props.row.original.latest_approval.action !== 'REJECTED' &&
|
||||||
props.row.original.latest_approval.step_number === 3;
|
props.row.original.latest_approval.step_number === 4;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<RowOptionsMenuWrapper type={type}>
|
<RowOptionsMenuWrapper type={type}>
|
||||||
@@ -193,7 +194,7 @@ const ExpensesTable = () => {
|
|||||||
parseInt(item)
|
parseInt(item)
|
||||||
);
|
);
|
||||||
|
|
||||||
const isAllSelectedRowLatestApprovalOnManager = useMemo(() => {
|
const isAllSelectedRowLatestApprovalOnHeadArea = useMemo(() => {
|
||||||
return selectedRowIds.every((rowId) => {
|
return selectedRowIds.every((rowId) => {
|
||||||
if (!isResponseSuccess(expenses)) return false;
|
if (!isResponseSuccess(expenses)) return false;
|
||||||
|
|
||||||
@@ -202,11 +203,28 @@ const ExpensesTable = () => {
|
|||||||
const isLatestApprovalRejected =
|
const isLatestApprovalRejected =
|
||||||
expenseItem?.latest_approval.action === 'REJECTED';
|
expenseItem?.latest_approval.action === 'REJECTED';
|
||||||
|
|
||||||
const isCurrentApprovalOnManager =
|
const isCurrentApprovalOnHeadArea =
|
||||||
!isLatestApprovalRejected &&
|
!isLatestApprovalRejected &&
|
||||||
expenseItem?.latest_approval.step_number === 1;
|
expenseItem?.latest_approval.step_number === 1;
|
||||||
|
|
||||||
return isCurrentApprovalOnManager;
|
return isCurrentApprovalOnHeadArea;
|
||||||
|
});
|
||||||
|
}, [expenses, selectedRowIds]);
|
||||||
|
|
||||||
|
const isAllSelectedRowLatestApprovalOnUnitVicePresident = 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 isCurrentApprovalOnUnitVicePresident =
|
||||||
|
!isLatestApprovalRejected &&
|
||||||
|
expenseItem?.latest_approval.step_number === 2;
|
||||||
|
|
||||||
|
return isCurrentApprovalOnUnitVicePresident;
|
||||||
});
|
});
|
||||||
}, [expenses, selectedRowIds]);
|
}, [expenses, selectedRowIds]);
|
||||||
|
|
||||||
@@ -221,7 +239,7 @@ const ExpensesTable = () => {
|
|||||||
|
|
||||||
const isCurrentApprovalOnFinance =
|
const isCurrentApprovalOnFinance =
|
||||||
!isLatestApprovalRejected &&
|
!isLatestApprovalRejected &&
|
||||||
expenseItem?.latest_approval.step_number === 2;
|
expenseItem?.latest_approval.step_number === 3;
|
||||||
|
|
||||||
return isCurrentApprovalOnFinance;
|
return isCurrentApprovalOnFinance;
|
||||||
});
|
});
|
||||||
@@ -238,7 +256,7 @@ const ExpensesTable = () => {
|
|||||||
|
|
||||||
const isCurrentApprovalOnRealization =
|
const isCurrentApprovalOnRealization =
|
||||||
!isLatestApprovalRejected &&
|
!isLatestApprovalRejected &&
|
||||||
expenseItem?.latest_approval.step_number === 4;
|
expenseItem?.latest_approval.step_number === 5;
|
||||||
|
|
||||||
return isCurrentApprovalOnRealization;
|
return isCurrentApprovalOnRealization;
|
||||||
});
|
});
|
||||||
@@ -397,7 +415,7 @@ const ExpensesTable = () => {
|
|||||||
) => {
|
) => {
|
||||||
return (
|
return (
|
||||||
row.original.latest_approval.action !== 'REJECTED' &&
|
row.original.latest_approval.action !== 'REJECTED' &&
|
||||||
row.original.latest_approval.step_number !== 5
|
row.original.latest_approval.step_number !== 6
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -441,8 +459,13 @@ const ExpensesTable = () => {
|
|||||||
|
|
||||||
let bulkApproveResponse: BaseApiResponse<Expense> | undefined = undefined;
|
let bulkApproveResponse: BaseApiResponse<Expense> | undefined = undefined;
|
||||||
|
|
||||||
if (isAllSelectedRowLatestApprovalOnManager) {
|
if (isAllSelectedRowLatestApprovalOnHeadArea) {
|
||||||
bulkApproveResponse = await ExpenseApi.bulkApproveManager(
|
bulkApproveResponse = await ExpenseApi.bulkApproveHeadArea(
|
||||||
|
selectedRowIds,
|
||||||
|
notes
|
||||||
|
);
|
||||||
|
} else if (isAllSelectedRowLatestApprovalOnUnitVicePresident) {
|
||||||
|
bulkApproveResponse = await ExpenseApi.bulkApproveUnitVicePresident(
|
||||||
selectedRowIds,
|
selectedRowIds,
|
||||||
notes
|
notes
|
||||||
);
|
);
|
||||||
@@ -478,8 +501,13 @@ const ExpensesTable = () => {
|
|||||||
|
|
||||||
let bulkRejectResponse: BaseApiResponse<Expense> | undefined = undefined;
|
let bulkRejectResponse: BaseApiResponse<Expense> | undefined = undefined;
|
||||||
|
|
||||||
if (isAllSelectedRowLatestApprovalOnManager) {
|
if (isAllSelectedRowLatestApprovalOnHeadArea) {
|
||||||
bulkRejectResponse = await ExpenseApi.bulkRejectManager(
|
bulkRejectResponse = await ExpenseApi.bulkRejectHeadArea(
|
||||||
|
selectedRowIds,
|
||||||
|
notes
|
||||||
|
);
|
||||||
|
} else if (isAllSelectedRowLatestApprovalOnUnitVicePresident) {
|
||||||
|
bulkRejectResponse = await ExpenseApi.bulkRejectUnitVicePresident(
|
||||||
selectedRowIds,
|
selectedRowIds,
|
||||||
notes
|
notes
|
||||||
);
|
);
|
||||||
@@ -594,16 +622,31 @@ const ExpensesTable = () => {
|
|||||||
|
|
||||||
{selectedRowIds.length > 0 && (
|
{selectedRowIds.length > 0 && (
|
||||||
<>
|
<>
|
||||||
<RequirePermission permissions='lti.expense.approve.manager'>
|
<RequirePermission permissions='lti.expense.approve.head_area'>
|
||||||
<Button
|
<Button
|
||||||
variant='outline'
|
variant='outline'
|
||||||
color='info'
|
color='info'
|
||||||
onClick={bulkApproveClickHandler}
|
onClick={bulkApproveClickHandler}
|
||||||
disabled={!isAllSelectedRowLatestApprovalOnManager}
|
disabled={!isAllSelectedRowLatestApprovalOnHeadArea}
|
||||||
className='w-full sm:w-fit'
|
className='w-full sm:w-fit'
|
||||||
>
|
>
|
||||||
<Icon icon='lucide-lab:farm' width={24} height={24} />
|
<Icon icon='lucide-lab:farm' width={24} height={24} />
|
||||||
Approve Manager
|
Approve Head Area
|
||||||
|
</Button>
|
||||||
|
</RequirePermission>
|
||||||
|
|
||||||
|
<RequirePermission permissions='lti.expense.approve.unit_vice_president'>
|
||||||
|
<Button
|
||||||
|
variant='outline'
|
||||||
|
color='success'
|
||||||
|
onClick={bulkApproveClickHandler}
|
||||||
|
disabled={
|
||||||
|
!isAllSelectedRowLatestApprovalOnUnitVicePresident
|
||||||
|
}
|
||||||
|
className='w-full sm:w-fit'
|
||||||
|
>
|
||||||
|
<Icon icon='tdesign:money' width={24} height={24} />
|
||||||
|
Approve Unit Vice President
|
||||||
</Button>
|
</Button>
|
||||||
</RequirePermission>
|
</RequirePermission>
|
||||||
|
|
||||||
@@ -622,7 +665,8 @@ const ExpensesTable = () => {
|
|||||||
|
|
||||||
<RequirePermission
|
<RequirePermission
|
||||||
permissions={[
|
permissions={[
|
||||||
'lti.expense.approve.manager',
|
'lti.expense.approve.head_area',
|
||||||
|
'lti.expense.approve.unit_vice_president',
|
||||||
'lti.expense.approve.finance',
|
'lti.expense.approve.finance',
|
||||||
]}
|
]}
|
||||||
>
|
>
|
||||||
@@ -631,7 +675,8 @@ const ExpensesTable = () => {
|
|||||||
color='error'
|
color='error'
|
||||||
onClick={bulkRejectClickHandler}
|
onClick={bulkRejectClickHandler}
|
||||||
disabled={
|
disabled={
|
||||||
!isAllSelectedRowLatestApprovalOnManager &&
|
!isAllSelectedRowLatestApprovalOnHeadArea &&
|
||||||
|
!isAllSelectedRowLatestApprovalOnUnitVicePresident &&
|
||||||
!isAllSelectedRowLatestApprovalOnFinance
|
!isAllSelectedRowLatestApprovalOnFinance
|
||||||
}
|
}
|
||||||
className='w-full sm:w-fit'
|
className='w-full sm:w-fit'
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ interface RealizationStatusBadgeProps {
|
|||||||
const RealizationStatusBadge = ({ approval }: RealizationStatusBadgeProps) => {
|
const RealizationStatusBadge = ({ approval }: RealizationStatusBadgeProps) => {
|
||||||
const isLatestApprovalRejected = approval?.action === 'REJECTED';
|
const isLatestApprovalRejected = approval?.action === 'REJECTED';
|
||||||
|
|
||||||
const isExpenseRealized = approval?.step_number && approval.step_number >= 4;
|
const isExpenseRealized = approval?.step_number && approval.step_number >= 5;
|
||||||
|
|
||||||
const realizationStatus = isExpenseRealized
|
const realizationStatus = isExpenseRealized
|
||||||
? 'Sudah Realisasi'
|
? 'Sudah Realisasi'
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import DropFileInput from '@/components/input/DropFileInput';
|
|||||||
import ExpenseKandangsTable from '@/components/pages/expense/form/ExpenseKandangsTable';
|
import ExpenseKandangsTable from '@/components/pages/expense/form/ExpenseKandangsTable';
|
||||||
import ExpenseRealizationKandangDetailExpense from '@/components/pages/expense/form/ExpenseRealizationKandangDetailExpense';
|
import ExpenseRealizationKandangDetailExpense from '@/components/pages/expense/form/ExpenseRealizationKandangDetailExpense';
|
||||||
import RequirePermission from '@/components/helper/RequirePermission';
|
import RequirePermission from '@/components/helper/RequirePermission';
|
||||||
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
CreateExpenseRealizationPayload,
|
CreateExpenseRealizationPayload,
|
||||||
@@ -35,6 +36,7 @@ import { LocationApi, SupplierApi } from '@/services/api/master-data';
|
|||||||
import { Supplier } from '@/types/api/master-data/supplier';
|
import { Supplier } from '@/types/api/master-data/supplier';
|
||||||
import { ACCEPTED_FILE_TYPE } from '@/config/constant';
|
import { ACCEPTED_FILE_TYPE } from '@/config/constant';
|
||||||
import { cn } from '@/lib/helper';
|
import { cn } from '@/lib/helper';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
|
|
||||||
interface ExpenseRealizationFormProps {
|
interface ExpenseRealizationFormProps {
|
||||||
type?: 'add' | 'edit' | 'detail';
|
type?: 'add' | 'edit' | 'detail';
|
||||||
@@ -132,6 +134,7 @@ const ExpenseRealizationForm = ({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const { setValues: formikSetValues } = formik;
|
const { setValues: formikSetValues } = formik;
|
||||||
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
setInputValue: setLocationInputValue,
|
setInputValue: setLocationInputValue,
|
||||||
@@ -223,6 +226,13 @@ const ExpenseRealizationForm = ({
|
|||||||
|
|
||||||
const realizationDocumentsChangeHandler = (val: File[]) => {
|
const realizationDocumentsChangeHandler = (val: File[]) => {
|
||||||
formik.setFieldTouched('documents', true);
|
formik.setFieldTouched('documents', true);
|
||||||
|
|
||||||
|
const invalidFiles = val.filter((file) => file.size > 5 * 1024 * 1024);
|
||||||
|
if (invalidFiles.length > 0) {
|
||||||
|
toast.error('Ukuran dokumen maksimal 5 MB!');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
formik.setFieldValue('documents', val);
|
formik.setFieldValue('documents', val);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -256,7 +266,7 @@ const ExpenseRealizationForm = ({
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
<form
|
<form
|
||||||
onSubmit={formik.handleSubmit}
|
onSubmit={handleFormSubmit}
|
||||||
onReset={formik.handleReset}
|
onReset={formik.handleReset}
|
||||||
className='w-full mt-8 flex flex-col gap-6'
|
className='w-full mt-8 flex flex-col gap-6'
|
||||||
>
|
>
|
||||||
@@ -365,6 +375,8 @@ const ExpenseRealizationForm = ({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
|
|
||||||
{expenseFormErrorMessage && (
|
{expenseFormErrorMessage && (
|
||||||
<div role='alert' className='alert alert-error w-full'>
|
<div role='alert' className='alert alert-error w-full'>
|
||||||
<Icon
|
<Icon
|
||||||
@@ -414,7 +426,7 @@ const ExpenseRealizationForm = ({
|
|||||||
type='submit'
|
type='submit'
|
||||||
color='primary'
|
color='primary'
|
||||||
isLoading={formik.isSubmitting}
|
isLoading={formik.isSubmitting}
|
||||||
disabled={!formik.isValid || formik.isSubmitting}
|
disabled={formik.isSubmitting}
|
||||||
className='px-4'
|
className='px-4'
|
||||||
>
|
>
|
||||||
Submit
|
Submit
|
||||||
|
|||||||
@@ -7,18 +7,19 @@ type ExpenseFormSchemaType = {
|
|||||||
category?: {
|
category?: {
|
||||||
value: 'BOP' | 'NON-BOP';
|
value: 'BOP' | 'NON-BOP';
|
||||||
label: 'BOP' | 'NON-BOP';
|
label: 'BOP' | 'NON-BOP';
|
||||||
};
|
} | null;
|
||||||
location?: {
|
location?: {
|
||||||
value: number;
|
value: number;
|
||||||
label: string;
|
label: string;
|
||||||
};
|
} | null;
|
||||||
location_id: number;
|
location_id: number;
|
||||||
transaction_date?: string;
|
transaction_date?: string;
|
||||||
kandangs?: { id?: number; name?: string }[];
|
kandangs?: { id?: number; name?: string }[];
|
||||||
supplier?: {
|
supplier?: {
|
||||||
value: number;
|
value: number;
|
||||||
label: string;
|
label: string;
|
||||||
};
|
} | null;
|
||||||
|
supplier_id: number;
|
||||||
existing_documents?: { id: number; name: string; url: string }[];
|
existing_documents?: { id: number; name: string; url: string }[];
|
||||||
deleted_documents?: number[];
|
deleted_documents?: number[];
|
||||||
documents?: File[];
|
documents?: File[];
|
||||||
@@ -28,7 +29,8 @@ type ExpenseFormSchemaType = {
|
|||||||
nonstock?: {
|
nonstock?: {
|
||||||
value: number;
|
value: number;
|
||||||
label: string;
|
label: string;
|
||||||
};
|
} | null;
|
||||||
|
nonstock_id?: number;
|
||||||
quantity?: number;
|
quantity?: number;
|
||||||
price?: number;
|
price?: number;
|
||||||
notes?: string;
|
notes?: string;
|
||||||
@@ -41,16 +43,24 @@ export const ExpenseRequestFormSchema: Yup.ObjectSchema<ExpenseFormSchemaType> =
|
|||||||
category: Yup.object({
|
category: Yup.object({
|
||||||
value: Yup.string().oneOf(['BOP', 'NON-BOP']).required(),
|
value: Yup.string().oneOf(['BOP', 'NON-BOP']).required(),
|
||||||
label: Yup.string().oneOf(['BOP', 'NON-BOP']).required(),
|
label: Yup.string().oneOf(['BOP', 'NON-BOP']).required(),
|
||||||
}).required('Kategori wajib diisi!'),
|
})
|
||||||
|
.nullable()
|
||||||
|
.optional(),
|
||||||
|
|
||||||
location: Yup.object({
|
location: Yup.object({
|
||||||
value: Yup.number().min(1).required(),
|
value: Yup.number().min(1).required(),
|
||||||
label: Yup.string().required(),
|
label: Yup.string().required(),
|
||||||
}).required('Lokasi wajib diisi!'),
|
})
|
||||||
|
.nullable()
|
||||||
|
.optional(),
|
||||||
|
|
||||||
location_id: Yup.number().min(1).required('Lokasi wajib diisi!'),
|
location_id: Yup.number()
|
||||||
|
.required('Lokasi wajib diisi!')
|
||||||
|
.min(1, 'Lokasi wajib diisi!')
|
||||||
|
.typeError('Lokasi wajib diisi!'),
|
||||||
|
|
||||||
transaction_date: Yup.string().required('Tanggal transaksi wajib diisi!'),
|
transaction_date: Yup.string().required('Tanggal transaksi wajib diisi!'),
|
||||||
|
|
||||||
kandangs: Yup.array()
|
kandangs: Yup.array()
|
||||||
.of(
|
.of(
|
||||||
Yup.object({
|
Yup.object({
|
||||||
@@ -63,15 +73,24 @@ export const ExpenseRequestFormSchema: Yup.ObjectSchema<ExpenseFormSchemaType> =
|
|||||||
supplier: Yup.object({
|
supplier: Yup.object({
|
||||||
value: Yup.number().min(1).required(),
|
value: Yup.number().min(1).required(),
|
||||||
label: Yup.string().required(),
|
label: Yup.string().required(),
|
||||||
}).required('Vendor wajib diisi!'),
|
})
|
||||||
|
.nullable()
|
||||||
|
.optional(),
|
||||||
|
|
||||||
existing_documents: Yup.array().of(
|
supplier_id: Yup.number()
|
||||||
|
.required('Vendor wajib diisi!')
|
||||||
|
.min(1, 'Vendor wajib diisi!')
|
||||||
|
.typeError('Vendor wajib diisi!'),
|
||||||
|
|
||||||
|
existing_documents: Yup.array()
|
||||||
|
.of(
|
||||||
Yup.object({
|
Yup.object({
|
||||||
id: Yup.number().required(),
|
id: Yup.number().required(),
|
||||||
name: Yup.string().required(),
|
name: Yup.string().required(),
|
||||||
url: Yup.string().required(),
|
url: Yup.string().required(),
|
||||||
})
|
})
|
||||||
),
|
)
|
||||||
|
.optional(),
|
||||||
|
|
||||||
deleted_documents: Yup.array().of(Yup.number().required()).optional(),
|
deleted_documents: Yup.array().of(Yup.number().required()).optional(),
|
||||||
|
|
||||||
@@ -87,9 +106,17 @@ export const ExpenseRequestFormSchema: Yup.ObjectSchema<ExpenseFormSchemaType> =
|
|||||||
nonstock: Yup.object({
|
nonstock: Yup.object({
|
||||||
value: Yup.number().min(1).required(),
|
value: Yup.number().min(1).required(),
|
||||||
label: Yup.string().required(),
|
label: Yup.string().required(),
|
||||||
}).required('Nonstock wajib diisi!'),
|
}).nullable(),
|
||||||
quantity: Yup.number().required('Total kuantitas wajib diisi!'),
|
nonstock_id: Yup.number()
|
||||||
price: Yup.number().required('Harga satuan wajib diisi!'),
|
.required('Nonstock wajib diisi!')
|
||||||
|
.min(1, 'Nonstock wajib diisi!')
|
||||||
|
.typeError('Nonstock wajib diisi!'),
|
||||||
|
quantity: Yup.number()
|
||||||
|
.required('Total kuantitas wajib diisi!')
|
||||||
|
.typeError('Total kuantitas wajib diisi!'),
|
||||||
|
price: Yup.number()
|
||||||
|
.required('Harga satuan wajib diisi!')
|
||||||
|
.typeError('Harga satuan wajib diisi!'),
|
||||||
notes: Yup.string(),
|
notes: Yup.string(),
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
@@ -104,7 +131,16 @@ export const ExpenseRequestFormSchema: Yup.ObjectSchema<ExpenseFormSchemaType> =
|
|||||||
export const UpdateExpenseRequestFormSchema = ExpenseRequestFormSchema;
|
export const UpdateExpenseRequestFormSchema = ExpenseRequestFormSchema;
|
||||||
|
|
||||||
export const UploadRequestDocumentsFormSchema = Yup.object({
|
export const UploadRequestDocumentsFormSchema = Yup.object({
|
||||||
documents: Yup.array().of(Yup.mixed<File>().required()).required(),
|
documents: Yup.array()
|
||||||
|
.of(
|
||||||
|
Yup.mixed<File>()
|
||||||
|
.required()
|
||||||
|
.test('fileSize', 'Ukuran dokumen maksimal 5 MB', (value) => {
|
||||||
|
if (!value || !(value instanceof File)) return true;
|
||||||
|
return value.size <= 5 * 1024 * 1024;
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.required(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export type ExpenseRequestFormValues = Yup.InferType<
|
export type ExpenseRequestFormValues = Yup.InferType<
|
||||||
@@ -124,13 +160,13 @@ export const getExpenseFormInitialValues = (
|
|||||||
value: initialValues.category,
|
value: initialValues.category,
|
||||||
label: initialValues.category,
|
label: initialValues.category,
|
||||||
}
|
}
|
||||||
: undefined,
|
: null,
|
||||||
location: initialValues?.location
|
location: initialValues?.location
|
||||||
? {
|
? {
|
||||||
value: initialValues.location.id,
|
value: initialValues.location.id,
|
||||||
label: initialValues.location.name,
|
label: initialValues.location.name,
|
||||||
}
|
}
|
||||||
: undefined,
|
: null,
|
||||||
location_id: Number(initialValues?.location.id || 0),
|
location_id: Number(initialValues?.location.id || 0),
|
||||||
transaction_date: initialValues?.transaction_date
|
transaction_date: initialValues?.transaction_date
|
||||||
? formatDate(initialValues.transaction_date, 'YYYY-MM-DD')
|
? formatDate(initialValues.transaction_date, 'YYYY-MM-DD')
|
||||||
@@ -144,7 +180,8 @@ export const getExpenseFormInitialValues = (
|
|||||||
value: initialValues.supplier.id,
|
value: initialValues.supplier.id,
|
||||||
label: initialValues.supplier.name,
|
label: initialValues.supplier.name,
|
||||||
}
|
}
|
||||||
: undefined,
|
: null,
|
||||||
|
supplier_id: initialValues?.supplier?.id ?? 0,
|
||||||
existing_documents: initialValues?.documents?.map((doc) => {
|
existing_documents: initialValues?.documents?.map((doc) => {
|
||||||
const path = doc.path.startsWith('/') ? doc.path.slice(1) : doc.path;
|
const path = doc.path.startsWith('/') ? doc.path.slice(1) : doc.path;
|
||||||
return {
|
return {
|
||||||
@@ -164,12 +201,25 @@ export const getExpenseFormInitialValues = (
|
|||||||
value: expenseItem.nonstock.id,
|
value: expenseItem.nonstock.id,
|
||||||
label: expenseItem.nonstock.name,
|
label: expenseItem.nonstock.name,
|
||||||
},
|
},
|
||||||
|
nonstock_id: expenseItem.nonstock.id,
|
||||||
quantity: expenseItem.qty,
|
quantity: expenseItem.qty,
|
||||||
price: expenseItem.price,
|
price: expenseItem.price,
|
||||||
notes: expenseItem.note,
|
notes: expenseItem.note,
|
||||||
}))
|
}))
|
||||||
: [],
|
: [],
|
||||||
}))
|
}))
|
||||||
: [],
|
: [
|
||||||
|
{
|
||||||
|
cost_items: [
|
||||||
|
{
|
||||||
|
nonstock: null,
|
||||||
|
nonstock_id: 0,
|
||||||
|
quantity: undefined,
|
||||||
|
price: undefined,
|
||||||
|
notes: '',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -37,6 +37,8 @@ import { cn, sleep } from '@/lib/helper';
|
|||||||
import { LocationApi, SupplierApi } from '@/services/api/master-data';
|
import { LocationApi, SupplierApi } from '@/services/api/master-data';
|
||||||
import { ACCEPTED_FILE_TYPE } from '@/config/constant';
|
import { ACCEPTED_FILE_TYPE } from '@/config/constant';
|
||||||
import { Supplier } from '@/types/api/master-data/supplier';
|
import { Supplier } from '@/types/api/master-data/supplier';
|
||||||
|
import { getUniqueFormikErrors } from '@/lib/formik-helper';
|
||||||
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
|
|
||||||
interface ExpenseFormProps {
|
interface ExpenseFormProps {
|
||||||
type?: 'add' | 'edit' | 'detail';
|
type?: 'add' | 'edit' | 'detail';
|
||||||
@@ -55,6 +57,7 @@ const ExpenseRequestForm = ({
|
|||||||
const rejectModal = useModal();
|
const rejectModal = useModal();
|
||||||
|
|
||||||
const [expenseFormErrorMessage, setExpenseFormErrorMessage] = useState('');
|
const [expenseFormErrorMessage, setExpenseFormErrorMessage] = useState('');
|
||||||
|
const [formErrorList, setFormErrorList] = useState<string[]>([]);
|
||||||
|
|
||||||
const createExpenseHandler = useCallback(
|
const createExpenseHandler = useCallback(
|
||||||
async (payload: CreateExpensePayload) => {
|
async (payload: CreateExpensePayload) => {
|
||||||
@@ -201,7 +204,8 @@ const ExpenseRequestForm = ({
|
|||||||
{
|
{
|
||||||
cost_items: [
|
cost_items: [
|
||||||
{
|
{
|
||||||
nonstock: undefined,
|
nonstock: null,
|
||||||
|
nonstock_id: 0,
|
||||||
quantity: undefined,
|
quantity: undefined,
|
||||||
price: undefined,
|
price: undefined,
|
||||||
notes: '',
|
notes: '',
|
||||||
@@ -223,7 +227,8 @@ const ExpenseRequestForm = ({
|
|||||||
{
|
{
|
||||||
cost_items: [
|
cost_items: [
|
||||||
{
|
{
|
||||||
nonstock: undefined,
|
nonstock: null,
|
||||||
|
nonstock_id: 0,
|
||||||
quantity: undefined,
|
quantity: undefined,
|
||||||
price: undefined,
|
price: undefined,
|
||||||
notes: '',
|
notes: '',
|
||||||
@@ -248,7 +253,8 @@ const ExpenseRequestForm = ({
|
|||||||
kandang_id: kandangItem.id,
|
kandang_id: kandangItem.id,
|
||||||
cost_items: existingExpenseNonstock?.cost_items || [
|
cost_items: existingExpenseNonstock?.cost_items || [
|
||||||
{
|
{
|
||||||
nonstock: undefined,
|
nonstock: null,
|
||||||
|
nonstock_id: 0,
|
||||||
quantity: undefined,
|
quantity: undefined,
|
||||||
price: undefined,
|
price: undefined,
|
||||||
notes: '',
|
notes: '',
|
||||||
@@ -263,10 +269,20 @@ const ExpenseRequestForm = ({
|
|||||||
const supplierChangeHandler = (val: OptionType | OptionType[] | null) => {
|
const supplierChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||||
formik.setFieldTouched('supplier', true);
|
formik.setFieldTouched('supplier', true);
|
||||||
formik.setFieldValue('supplier', val);
|
formik.setFieldValue('supplier', val);
|
||||||
|
|
||||||
|
const supplierId = Array.isArray(val) ? val[0]?.value : val?.value;
|
||||||
|
formik.setFieldValue('supplier_id', supplierId ?? 0);
|
||||||
};
|
};
|
||||||
|
|
||||||
const requestDocumentsChangeHandler = (val: File[]) => {
|
const requestDocumentsChangeHandler = (val: File[]) => {
|
||||||
formik.setFieldTouched('documents', true);
|
formik.setFieldTouched('documents', true);
|
||||||
|
|
||||||
|
const invalidFiles = val.filter((file) => file.size > 5 * 1024 * 1024);
|
||||||
|
if (invalidFiles.length > 0) {
|
||||||
|
toast.error('Ukuran dokumen maksimal 5 MB!');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
formik.setFieldValue('documents', val);
|
formik.setFieldValue('documents', val);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -322,6 +338,22 @@ const ExpenseRequestForm = ({
|
|||||||
router.push('/expense');
|
router.push('/expense');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleValidateForm = async () => {
|
||||||
|
const errors = await formik.validateForm();
|
||||||
|
|
||||||
|
if (Object.keys(errors).length > 0) {
|
||||||
|
const errorMessages = getUniqueFormikErrors(errors);
|
||||||
|
setFormErrorList(errorMessages);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
|
||||||
|
e.preventDefault();
|
||||||
|
handleValidateForm();
|
||||||
|
formik.handleSubmit(e);
|
||||||
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
formikSetValues(getExpenseFormInitialValues(initialValues));
|
formikSetValues(getExpenseFormInitialValues(initialValues));
|
||||||
}, [formikSetValues, getExpenseFormInitialValues, initialValues]);
|
}, [formikSetValues, getExpenseFormInitialValues, initialValues]);
|
||||||
@@ -347,10 +379,27 @@ const ExpenseRequestForm = ({
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
<form
|
<form
|
||||||
onSubmit={formik.handleSubmit}
|
onSubmit={handleFormSubmit}
|
||||||
onReset={formik.handleReset}
|
onReset={formik.handleReset}
|
||||||
className='w-full mt-8 flex flex-col gap-6'
|
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'>
|
<div className='grid grid-cols-12 gap-4'>
|
||||||
<SelectInput
|
<SelectInput
|
||||||
label='Kategori'
|
label='Kategori'
|
||||||
@@ -535,17 +584,6 @@ const ExpenseRequestForm = ({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{expenseFormErrorMessage && (
|
|
||||||
<div role='alert' className='alert alert-error w-full'>
|
|
||||||
<Icon
|
|
||||||
icon='material-symbols:error-outline'
|
|
||||||
width={24}
|
|
||||||
height={24}
|
|
||||||
/>
|
|
||||||
<span>{expenseFormErrorMessage}</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{type !== 'detail' && (
|
{type !== 'detail' && (
|
||||||
<div
|
<div
|
||||||
className={cn('flex flex-row justify-end gap-2', {
|
className={cn('flex flex-row justify-end gap-2', {
|
||||||
@@ -560,7 +598,7 @@ const ExpenseRequestForm = ({
|
|||||||
type='submit'
|
type='submit'
|
||||||
color='primary'
|
color='primary'
|
||||||
isLoading={formik.isSubmitting}
|
isLoading={formik.isSubmitting}
|
||||||
disabled={!formik.isValid || formik.isSubmitting}
|
disabled={formik.isSubmitting}
|
||||||
className='px-4'
|
className='px-4'
|
||||||
>
|
>
|
||||||
Submit
|
Submit
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ interface ExpenseRequestKandangDetailExpenseProps {
|
|||||||
location?: {
|
location?: {
|
||||||
value: number;
|
value: number;
|
||||||
label: string;
|
label: string;
|
||||||
};
|
} | null;
|
||||||
className?: {
|
className?: {
|
||||||
wrapper?: string;
|
wrapper?: string;
|
||||||
};
|
};
|
||||||
@@ -59,13 +59,20 @@ const ExpenseRequestKandangDetailExpense: React.FC<
|
|||||||
`expense_nonstocks[${kandangExpenseIdx}].cost_items[${expenseIdx}].nonstock`,
|
`expense_nonstocks[${kandangExpenseIdx}].cost_items[${expenseIdx}].nonstock`,
|
||||||
val
|
val
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const nonstockId = Array.isArray(val) ? val[0]?.value : val?.value;
|
||||||
|
formik.setFieldValue(
|
||||||
|
`expense_nonstocks[${kandangExpenseIdx}].cost_items[${expenseIdx}].nonstock_id`,
|
||||||
|
nonstockId ?? 0
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const addExpenseItemHandler = (kandangExpenseIdx: number) => {
|
const addExpenseItemHandler = (kandangExpenseIdx: number) => {
|
||||||
const newExpensesValue = [
|
const newExpensesValue = [
|
||||||
...formik.values.expense_nonstocks[kandangExpenseIdx].cost_items,
|
...formik.values.expense_nonstocks[kandangExpenseIdx].cost_items,
|
||||||
{
|
{
|
||||||
nonstock: undefined,
|
nonstock: null,
|
||||||
|
nonstock_id: 0,
|
||||||
price: undefined,
|
price: undefined,
|
||||||
quantity: undefined,
|
quantity: undefined,
|
||||||
notes: '',
|
notes: '',
|
||||||
|
|||||||
@@ -198,7 +198,7 @@ const ExpensePDF = ({ expense }: ExpensePDFProps) => {
|
|||||||
expense?.latest_approval?.action === 'REJECTED';
|
expense?.latest_approval?.action === 'REJECTED';
|
||||||
const isExpenseRealized =
|
const isExpenseRealized =
|
||||||
expense?.latest_approval?.step_number &&
|
expense?.latest_approval?.step_number &&
|
||||||
expense?.latest_approval.step_number >= 4;
|
expense?.latest_approval.step_number >= 5;
|
||||||
|
|
||||||
const realizationStatus = isExpenseRealized
|
const realizationStatus = isExpenseRealized
|
||||||
? 'Sudah Realisasi'
|
? 'Sudah Realisasi'
|
||||||
@@ -242,8 +242,8 @@ const ExpensePDF = ({ expense }: ExpensePDFProps) => {
|
|||||||
{
|
{
|
||||||
label: 'Nominal Biaya',
|
label: 'Nominal Biaya',
|
||||||
value: formatCurrency(
|
value: formatCurrency(
|
||||||
expense?.latest_approval.step_number === 4 ||
|
expense?.latest_approval.step_number === 5 ||
|
||||||
expense?.latest_approval.step_number === 5
|
expense?.latest_approval.step_number === 6
|
||||||
? (expense?.total_realisasi ?? 0)
|
? (expense?.total_realisasi ?? 0)
|
||||||
: (expense?.total_pengajuan ?? 0)
|
: (expense?.total_pengajuan ?? 0)
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import Button from '@/components/Button';
|
import Button from '@/components/Button';
|
||||||
import Card from '@/components/Card';
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
import { FormHeader } from '@/components/helper/form/FormHeader';
|
import { FormHeader } from '@/components/helper/form/FormHeader';
|
||||||
import DateInput from '@/components/input/DateInput';
|
import DateInput from '@/components/input/DateInput';
|
||||||
import NumberInput from '@/components/input/NumberInput';
|
import NumberInput from '@/components/input/NumberInput';
|
||||||
@@ -21,6 +21,7 @@ import {
|
|||||||
} from '@/config/constant';
|
} from '@/config/constant';
|
||||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||||
import { formatDate, formatTitleCase } from '@/lib/helper';
|
import { formatDate, formatTitleCase } from '@/lib/helper';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
import { FinanceApi } from '@/services/api/finance';
|
import { FinanceApi } from '@/services/api/finance';
|
||||||
import { BankApi, CustomerApi, SupplierApi } from '@/services/api/master-data';
|
import { BankApi, CustomerApi, SupplierApi } from '@/services/api/master-data';
|
||||||
import {
|
import {
|
||||||
@@ -104,6 +105,9 @@ const FormFinanceAdd = ({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ===== Formik Error List =====
|
||||||
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
|
|
||||||
// ===== Options =====
|
// ===== Options =====
|
||||||
const {
|
const {
|
||||||
options: partyOptions,
|
options: partyOptions,
|
||||||
@@ -180,7 +184,7 @@ const FormFinanceAdd = ({
|
|||||||
title={`${type === 'add' ? 'Tambah' : 'Ubah'} Data Keuangan`}
|
title={`${type === 'add' ? 'Tambah' : 'Ubah'} Data Keuangan`}
|
||||||
backUrl='/finance'
|
backUrl='/finance'
|
||||||
/>
|
/>
|
||||||
<form className='flex flex-col gap-4' onSubmit={formik.handleSubmit}>
|
<form className='flex flex-col gap-4' onSubmit={handleFormSubmit}>
|
||||||
<SelectInput
|
<SelectInput
|
||||||
label='Jenis Transaksi'
|
label='Jenis Transaksi'
|
||||||
placeholder='Pilih jenis transaksi'
|
placeholder='Pilih jenis transaksi'
|
||||||
@@ -384,6 +388,7 @@ const FormFinanceAdd = ({
|
|||||||
}
|
}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
<div className='flex justify-center gap-4'>
|
<div className='flex justify-center gap-4'>
|
||||||
<Button
|
<Button
|
||||||
type='reset'
|
type='reset'
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import Button from '@/components/Button';
|
import Button from '@/components/Button';
|
||||||
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
import { FormHeader } from '@/components/helper/form/FormHeader';
|
import { FormHeader } from '@/components/helper/form/FormHeader';
|
||||||
import NumberInput from '@/components/input/NumberInput';
|
import NumberInput from '@/components/input/NumberInput';
|
||||||
import SelectInput, {
|
import SelectInput, { useSelect } from '@/components/input/SelectInput';
|
||||||
OptionType,
|
|
||||||
useSelect,
|
|
||||||
} from '@/components/input/SelectInput';
|
|
||||||
import TextArea from '@/components/input/TextArea';
|
import TextArea from '@/components/input/TextArea';
|
||||||
import TextInput from '@/components/input/TextInput';
|
import TextInput from '@/components/input/TextInput';
|
||||||
import {
|
import {
|
||||||
@@ -17,6 +15,7 @@ import {
|
|||||||
FINANCE_INITIAL_BALANCE_TYPE_OPTIONS,
|
FINANCE_INITIAL_BALANCE_TYPE_OPTIONS,
|
||||||
FINANCE_PARTY_TYPE_OPTIONS,
|
FINANCE_PARTY_TYPE_OPTIONS,
|
||||||
} from '@/config/constant';
|
} from '@/config/constant';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||||
import { formatTitleCase } from '@/lib/helper';
|
import { formatTitleCase } from '@/lib/helper';
|
||||||
import { FinanceApi } from '@/services/api/finance';
|
import { FinanceApi } from '@/services/api/finance';
|
||||||
@@ -173,6 +172,9 @@ const FormFinanceAddInitialBalance = ({
|
|||||||
[router]
|
[router]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// ===== Formik Error List =====
|
||||||
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<section className='w-full max-w-xl mx-auto'>
|
<section className='w-full max-w-xl mx-auto'>
|
||||||
@@ -181,7 +183,7 @@ const FormFinanceAddInitialBalance = ({
|
|||||||
title={`${type === 'add' ? 'Tambah' : 'Ubah'} Saldo Awal`}
|
title={`${type === 'add' ? 'Tambah' : 'Ubah'} Saldo Awal`}
|
||||||
backUrl='/finance'
|
backUrl='/finance'
|
||||||
/>
|
/>
|
||||||
<form className='flex flex-col gap-4' onSubmit={formik.handleSubmit}>
|
<form className='flex flex-col gap-4' onSubmit={handleFormSubmit}>
|
||||||
<SelectInput
|
<SelectInput
|
||||||
label='Jenis Pihak'
|
label='Jenis Pihak'
|
||||||
placeholder='Pilih jenis pihak'
|
placeholder='Pilih jenis pihak'
|
||||||
@@ -352,6 +354,7 @@ const FormFinanceAddInitialBalance = ({
|
|||||||
}
|
}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
<div className='flex justify-center gap-4'>
|
<div className='flex justify-center gap-4'>
|
||||||
<Button
|
<Button
|
||||||
type='reset'
|
type='reset'
|
||||||
|
|||||||
@@ -1,18 +1,17 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import Button from '@/components/Button';
|
import Button from '@/components/Button';
|
||||||
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
import { FormHeader } from '@/components/helper/form/FormHeader';
|
import { FormHeader } from '@/components/helper/form/FormHeader';
|
||||||
import DateInput from '@/components/input/DateInput';
|
import DateInput from '@/components/input/DateInput';
|
||||||
import NumberInput from '@/components/input/NumberInput';
|
import NumberInput from '@/components/input/NumberInput';
|
||||||
import SelectInput, {
|
import SelectInput, { useSelect } from '@/components/input/SelectInput';
|
||||||
OptionType,
|
|
||||||
useSelect,
|
|
||||||
} from '@/components/input/SelectInput';
|
|
||||||
import TextArea from '@/components/input/TextArea';
|
import TextArea from '@/components/input/TextArea';
|
||||||
import {
|
import {
|
||||||
InjectionFormSchema,
|
InjectionFormSchema,
|
||||||
InjectionFormValues,
|
InjectionFormValues,
|
||||||
} from '@/components/pages/finance/add/injection/FormFinanceInjection.schema';
|
} from '@/components/pages/finance/add/injection/FormFinanceInjection.schema';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||||
import { formatDate } from '@/lib/helper';
|
import { formatDate } from '@/lib/helper';
|
||||||
import { FinanceApi } from '@/services/api/finance';
|
import { FinanceApi } from '@/services/api/finance';
|
||||||
@@ -128,6 +127,9 @@ const FormFinanceInjection = ({
|
|||||||
[router]
|
[router]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// ===== Formik Error List =====
|
||||||
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<section className='w-full max-w-xl mx-auto'>
|
<section className='w-full max-w-xl mx-auto'>
|
||||||
@@ -136,7 +138,7 @@ const FormFinanceInjection = ({
|
|||||||
title={`${type === 'add' ? 'Tambah' : 'Ubah'} Injeksi Dana`}
|
title={`${type === 'add' ? 'Tambah' : 'Ubah'} Injeksi Dana`}
|
||||||
backUrl='/finance'
|
backUrl='/finance'
|
||||||
/>
|
/>
|
||||||
<form className='flex flex-col gap-4' onSubmit={formik.handleSubmit}>
|
<form className='flex flex-col gap-4' onSubmit={handleFormSubmit}>
|
||||||
<SelectInput
|
<SelectInput
|
||||||
label='Bank'
|
label='Bank'
|
||||||
placeholder='Pilih bank'
|
placeholder='Pilih bank'
|
||||||
@@ -223,6 +225,7 @@ const FormFinanceInjection = ({
|
|||||||
}
|
}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
<div className='flex justify-center gap-4'>
|
<div className='flex justify-center gap-4'>
|
||||||
<Button
|
<Button
|
||||||
type='reset'
|
type='reset'
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import { Icon } from '@iconify/react';
|
|||||||
import { ColumnDef, ColumnSort, SortingState } from '@tanstack/react-table';
|
import { ColumnDef, ColumnSort, SortingState } from '@tanstack/react-table';
|
||||||
import { useCallback, useEffect, useState } from 'react';
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
import useSWR from 'swr';
|
import useSWR from 'swr';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
|
|
||||||
const InventoryAdjustmentTable = () => {
|
const InventoryAdjustmentTable = () => {
|
||||||
const {
|
const {
|
||||||
|
|||||||
@@ -1,26 +1,42 @@
|
|||||||
import * as Yup from 'yup';
|
import * as Yup from 'yup';
|
||||||
|
import { OptionType } from '@/components/input/SelectInput';
|
||||||
|
|
||||||
export const InventoryAdjustmentFormSchema = Yup.object({
|
export const InventoryAdjustmentFormSchema = Yup.object({
|
||||||
product_category: Yup.object({
|
product_category: Yup.mixed<OptionType>()
|
||||||
value: Yup.number().required('ID Kategori Produk wajib diisi!'),
|
.nullable()
|
||||||
label: Yup.string().required('Nama Kategori Produk wajib diisi!'),
|
.test(
|
||||||
}).nullable(),
|
'is-valid-option',
|
||||||
|
'Kategori Produk wajib diisi!',
|
||||||
|
(value) => value !== null && value !== undefined
|
||||||
|
),
|
||||||
|
|
||||||
product_category_id: Yup.number().nullable(),
|
product_category_id: Yup.number().nullable(),
|
||||||
|
|
||||||
product: Yup.object({
|
product: Yup.mixed<OptionType>()
|
||||||
value: Yup.number().required('ID Produk wajib diisi!'),
|
.nullable()
|
||||||
label: Yup.string().required('Nama Produk wajib diisi!'),
|
.test(
|
||||||
}).nullable(),
|
'is-valid-option',
|
||||||
|
'Produk wajib diisi!',
|
||||||
|
(value) => value !== null && value !== undefined
|
||||||
|
),
|
||||||
|
|
||||||
product_id: Yup.number().nullable(),
|
product_id: Yup.number()
|
||||||
|
.nullable()
|
||||||
|
.required('Produk wajib diisi!')
|
||||||
|
.min(1, 'Produk wajib diisi!'),
|
||||||
|
|
||||||
warehouse: Yup.object({
|
warehouse: Yup.mixed<OptionType>()
|
||||||
value: Yup.number().required('ID Gudang wajib diisi!'),
|
.nullable()
|
||||||
label: Yup.string().required('Nama Gudang wajib diisi!'),
|
.test(
|
||||||
}).nullable(),
|
'is-valid-option',
|
||||||
|
'Warehouse wajib diisi!',
|
||||||
|
(value) => value !== null && value !== undefined
|
||||||
|
),
|
||||||
|
|
||||||
warehouse_id: Yup.number().nullable(),
|
warehouse_id: Yup.number()
|
||||||
|
.nullable()
|
||||||
|
.required('Warehouse wajib diisi!')
|
||||||
|
.min(1, 'Warehouse wajib diisi!'),
|
||||||
|
|
||||||
transaction_type: Yup.string()
|
transaction_type: Yup.string()
|
||||||
.oneOf(['increase', 'decrease'], 'Tipe transaksi tidak valid')
|
.oneOf(['increase', 'decrease'], 'Tipe transaksi tidak valid')
|
||||||
|
|||||||
@@ -26,6 +26,8 @@ import SelectInput, { OptionType } from '@/components/input/SelectInput';
|
|||||||
import TextInput from '@/components/input/TextInput';
|
import TextInput from '@/components/input/TextInput';
|
||||||
import { RadioGroup } from '@/components/input/RadioInput';
|
import { RadioGroup } from '@/components/input/RadioInput';
|
||||||
import TextArea from '@/components/input/TextArea';
|
import TextArea from '@/components/input/TextArea';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
|
|
||||||
interface InventoryAdjustmentFormProps {
|
interface InventoryAdjustmentFormProps {
|
||||||
type?: 'add' | 'edit' | 'detail';
|
type?: 'add' | 'edit' | 'detail';
|
||||||
@@ -245,6 +247,9 @@ const InventoryAdjustmentForm = ({
|
|||||||
return decimal ? `${formattedInteger}.${decimal}` : formattedInteger;
|
return decimal ? `${formattedInteger}.${decimal}` : formattedInteger;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// ===== Formik Error List =====
|
||||||
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
|
|
||||||
// Render
|
// Render
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -266,7 +271,7 @@ const InventoryAdjustmentForm = ({
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
<form
|
<form
|
||||||
onSubmit={formik.handleSubmit}
|
onSubmit={handleFormSubmit}
|
||||||
onReset={formik.handleReset}
|
onReset={formik.handleReset}
|
||||||
className='w-full mt-8 flex flex-col gap-6'
|
className='w-full mt-8 flex flex-col gap-6'
|
||||||
>
|
>
|
||||||
@@ -390,6 +395,7 @@ const InventoryAdjustmentForm = ({
|
|||||||
readOnly={type === 'detail'}
|
readOnly={type === 'detail'}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
<div className='flex flex-row justify-between gap-2 flex-wrap'>
|
<div className='flex flex-row justify-between gap-2 flex-wrap'>
|
||||||
{type !== 'detail' && (
|
{type !== 'detail' && (
|
||||||
<div className='flex flex-row justify-end gap-2'>
|
<div className='flex flex-row justify-end gap-2'>
|
||||||
@@ -405,11 +411,7 @@ const InventoryAdjustmentForm = ({
|
|||||||
type='submit'
|
type='submit'
|
||||||
color='primary'
|
color='primary'
|
||||||
isLoading={formik.isSubmitting}
|
isLoading={formik.isSubmitting}
|
||||||
disabled={
|
disabled={formik.isSubmitting}
|
||||||
!formik.isValid ||
|
|
||||||
formik.isSubmitting ||
|
|
||||||
formik.values.product == undefined
|
|
||||||
}
|
|
||||||
className='px-4'
|
className='px-4'
|
||||||
>
|
>
|
||||||
Submit
|
Submit
|
||||||
|
|||||||
@@ -48,8 +48,8 @@ import DeliveryOrderProductForm from '@/components/pages/marketing/form/repeater
|
|||||||
import { SalesOrderProductFormValues } from '@/components/pages/marketing/form/repeater/sales-order/SalesOrderProduct.schema';
|
import { SalesOrderProductFormValues } from '@/components/pages/marketing/form/repeater/sales-order/SalesOrderProduct.schema';
|
||||||
import { DeliveryOrderProductFormValues } from '@/components/pages/marketing/form/repeater/delivery-order/DeliverOrderProduct.schema';
|
import { DeliveryOrderProductFormValues } from '@/components/pages/marketing/form/repeater/delivery-order/DeliverOrderProduct.schema';
|
||||||
import RequirePermission from '@/components/helper/RequirePermission';
|
import RequirePermission from '@/components/helper/RequirePermission';
|
||||||
import { getUniqueFormikErrors } from '@/lib/formik-helper';
|
|
||||||
import AlertErrorList from '@/components/helper/form/FormErrors';
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
|
|
||||||
const MemoizedSalesOrderProductTable = memo(SalesOrderProductTable);
|
const MemoizedSalesOrderProductTable = memo(SalesOrderProductTable);
|
||||||
const MemoizedSalesOrderProductForm = memo(SalesOrderProductForm);
|
const MemoizedSalesOrderProductForm = memo(SalesOrderProductForm);
|
||||||
@@ -219,7 +219,6 @@ const MarketingForm = ({
|
|||||||
const [deliveryFormState, setDeliveryFormState] = useState<'add' | 'edit'>(
|
const [deliveryFormState, setDeliveryFormState] = useState<'add' | 'edit'>(
|
||||||
'add'
|
'add'
|
||||||
);
|
);
|
||||||
const [formErrorList, setFormErrorList] = useState<string[]>([]);
|
|
||||||
const [deliveryOrderValues, setDeliveryOrderValues] = useState<
|
const [deliveryOrderValues, setDeliveryOrderValues] = useState<
|
||||||
DeliveryOrderProductFormValues[]
|
DeliveryOrderProductFormValues[]
|
||||||
>(
|
>(
|
||||||
@@ -561,22 +560,8 @@ const MarketingForm = ({
|
|||||||
);
|
);
|
||||||
}, [memoSalesOrder]);
|
}, [memoSalesOrder]);
|
||||||
|
|
||||||
const handleValidateForm = async () => {
|
// ===== Formik Error List =====
|
||||||
const errors = await formik.validateForm();
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
|
|
||||||
if (Object.keys(errors).length > 0) {
|
|
||||||
// Parse and display errors
|
|
||||||
const errorMessages = getUniqueFormikErrors(errors);
|
|
||||||
setFormErrorList(errorMessages);
|
|
||||||
return; // Stop submission
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
|
|
||||||
e.preventDefault();
|
|
||||||
handleValidateForm();
|
|
||||||
formik.handleSubmit();
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -686,13 +671,7 @@ const MarketingForm = ({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Error List Alert */}
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
{formErrorList.length > 0 && (
|
|
||||||
<AlertErrorList
|
|
||||||
formErrorList={formErrorList}
|
|
||||||
onClose={() => setFormErrorList([])}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Form Actions */}
|
{/* Form Actions */}
|
||||||
<div className='flex flex-row items-start justify-center gap-2 mt-4'>
|
<div className='flex flex-row items-start justify-center gap-2 mt-4'>
|
||||||
|
|||||||
+4
-23
@@ -16,8 +16,8 @@ import Badge from '@/components/Badge';
|
|||||||
import { SalesProductToFieldValues } from '@/components/pages/marketing/form/MarketingForm';
|
import { SalesProductToFieldValues } from '@/components/pages/marketing/form/MarketingForm';
|
||||||
import * as Yup from 'yup';
|
import * as Yup from 'yup';
|
||||||
import { isResponseSuccess } from '@/lib/api-helper';
|
import { isResponseSuccess } from '@/lib/api-helper';
|
||||||
import { getUniqueFormikErrors } from '@/lib/formik-helper';
|
|
||||||
import AlertErrorList from '@/components/helper/form/FormErrors';
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
|
|
||||||
const DeliveryOrderProductForm = ({
|
const DeliveryOrderProductForm = ({
|
||||||
formState,
|
formState,
|
||||||
@@ -42,7 +42,6 @@ const DeliveryOrderProductForm = ({
|
|||||||
null
|
null
|
||||||
);
|
);
|
||||||
const [currentInput, setCurrentInput] = useState<string>('');
|
const [currentInput, setCurrentInput] = useState<string>('');
|
||||||
const [formErrorList, setFormErrorList] = useState<string[]>([]);
|
|
||||||
|
|
||||||
const salesOrder = salesOrders.find(
|
const salesOrder = salesOrders.find(
|
||||||
(item) => item.id === initialValues?.marketing_product_id
|
(item) => item.id === initialValues?.marketing_product_id
|
||||||
@@ -168,21 +167,8 @@ const DeliveryOrderProductForm = ({
|
|||||||
}
|
}
|
||||||
}, [initialValues]);
|
}, [initialValues]);
|
||||||
|
|
||||||
const handleValidateForm = () => {
|
// ===== Formik Error List =====
|
||||||
formik.validateForm();
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
const formErrorList = getUniqueFormikErrors(formik.errors);
|
|
||||||
setFormErrorList(formErrorList);
|
|
||||||
if (formErrorList.length > 0) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
|
|
||||||
e.preventDefault();
|
|
||||||
handleBlurField(currentInput);
|
|
||||||
handleValidateForm();
|
|
||||||
formik.handleSubmit(e);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -388,12 +374,7 @@ const DeliveryOrderProductForm = ({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{formErrorList.length > 0 && (
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
<AlertErrorList
|
|
||||||
formErrorList={formErrorList}
|
|
||||||
onClose={() => setFormErrorList([])}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className='flex flex-row justify-end gap-3 mt-4'>
|
<div className='flex flex-row justify-end gap-3 mt-4'>
|
||||||
<Button type='reset' color='warning'>
|
<Button type='reset' color='warning'>
|
||||||
|
|||||||
@@ -24,8 +24,8 @@ import {
|
|||||||
} from '@/lib/helper';
|
} from '@/lib/helper';
|
||||||
import PatternInput from '@/components/input/PatternInput';
|
import PatternInput from '@/components/input/PatternInput';
|
||||||
import Alert from '@/components/Alert';
|
import Alert from '@/components/Alert';
|
||||||
import { getUniqueFormikErrors } from '@/lib/formik-helper';
|
|
||||||
import AlertErrorList from '@/components/helper/form/FormErrors';
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
|
|
||||||
const SalesOrderProductForm = ({
|
const SalesOrderProductForm = ({
|
||||||
initialValues,
|
initialValues,
|
||||||
@@ -39,7 +39,6 @@ const SalesOrderProductForm = ({
|
|||||||
}) => {
|
}) => {
|
||||||
const [formErrorMessage, setFormErrorMessage] = useState('');
|
const [formErrorMessage, setFormErrorMessage] = useState('');
|
||||||
const [currentInput, setCurrentInput] = useState<string>('');
|
const [currentInput, setCurrentInput] = useState<string>('');
|
||||||
const [formErrorList, setFormErrorList] = useState<string[]>([]);
|
|
||||||
|
|
||||||
// ============ Formik ============
|
// ============ Formik ============
|
||||||
const formik = useFormik<SalesOrderProductFormValues>({
|
const formik = useFormik<SalesOrderProductFormValues>({
|
||||||
@@ -172,23 +171,8 @@ const SalesOrderProductForm = ({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleValidateForm = async () => {
|
// ===== Formik Error List =====
|
||||||
const errors = await formik.validateForm();
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
|
|
||||||
if (Object.keys(errors).length > 0) {
|
|
||||||
// Parse and display errors
|
|
||||||
const errorMessages = getUniqueFormikErrors(errors);
|
|
||||||
setFormErrorList(errorMessages);
|
|
||||||
return; // Stop submission
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
|
|
||||||
e.preventDefault();
|
|
||||||
handleBlurField(currentInput);
|
|
||||||
handleValidateForm();
|
|
||||||
formik.handleSubmit(e);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -356,13 +340,7 @@ const SalesOrderProductForm = ({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Error List Alert */}
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
{formErrorList.length > 0 && (
|
|
||||||
<AlertErrorList
|
|
||||||
formErrorList={formErrorList}
|
|
||||||
onClose={() => setFormErrorList([])}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className='flex flex-row justify-end gap-3 mt-4'>
|
<div className='flex flex-row justify-end gap-3 mt-4'>
|
||||||
<Button type='reset' color='warning' onClick={handleResetForm}>
|
<Button type='reset' color='warning' onClick={handleResetForm}>
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ import {
|
|||||||
} from '@/types/api/master-data/area';
|
} from '@/types/api/master-data/area';
|
||||||
import { AreaApi } from '@/services/api/master-data';
|
import { AreaApi } from '@/services/api/master-data';
|
||||||
import { cn } from '@/lib/helper';
|
import { cn } from '@/lib/helper';
|
||||||
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
|
|
||||||
interface AreaFormProps {
|
interface AreaFormProps {
|
||||||
type?: 'add' | 'edit' | 'detail';
|
type?: 'add' | 'edit' | 'detail';
|
||||||
@@ -118,6 +120,9 @@ const AreaForm = ({ type = 'add', initialValues }: AreaFormProps) => {
|
|||||||
formikSetValues(formikInitialValues);
|
formikSetValues(formikInitialValues);
|
||||||
}, [formikSetValues, formikInitialValues]);
|
}, [formikSetValues, formikInitialValues]);
|
||||||
|
|
||||||
|
// ===== Formik Error List =====
|
||||||
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<section className='w-full max-w-xl'>
|
<section className='w-full max-w-xl'>
|
||||||
@@ -139,7 +144,7 @@ const AreaForm = ({ type = 'add', initialValues }: AreaFormProps) => {
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
<form
|
<form
|
||||||
onSubmit={formik.handleSubmit}
|
onSubmit={handleFormSubmit}
|
||||||
onReset={formik.handleReset}
|
onReset={formik.handleReset}
|
||||||
className='w-full mt-8 flex flex-col gap-6'
|
className='w-full mt-8 flex flex-col gap-6'
|
||||||
>
|
>
|
||||||
@@ -199,6 +204,8 @@ const AreaForm = ({ type = 'add', initialValues }: AreaFormProps) => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
|
|
||||||
{type !== 'detail' && (
|
{type !== 'detail' && (
|
||||||
<div
|
<div
|
||||||
className={cn('flex flex-row justify-end gap-2', {
|
className={cn('flex flex-row justify-end gap-2', {
|
||||||
@@ -213,7 +220,7 @@ const AreaForm = ({ type = 'add', initialValues }: AreaFormProps) => {
|
|||||||
type='submit'
|
type='submit'
|
||||||
color='primary'
|
color='primary'
|
||||||
isLoading={formik.isSubmitting}
|
isLoading={formik.isSubmitting}
|
||||||
disabled={!formik.isValid || formik.isSubmitting}
|
disabled={formik.isSubmitting}
|
||||||
className='px-4'
|
className='px-4'
|
||||||
>
|
>
|
||||||
Submit
|
Submit
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ import {
|
|||||||
} from '@/types/api/master-data/bank';
|
} from '@/types/api/master-data/bank';
|
||||||
import { BankApi } from '@/services/api/master-data';
|
import { BankApi } from '@/services/api/master-data';
|
||||||
import { cn } from '@/lib/helper';
|
import { cn } from '@/lib/helper';
|
||||||
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
|
|
||||||
interface BankFormProps {
|
interface BankFormProps {
|
||||||
type?: 'add' | 'edit' | 'detail';
|
type?: 'add' | 'edit' | 'detail';
|
||||||
@@ -124,6 +126,9 @@ const BankForm = ({ type = 'add', initialValues }: BankFormProps) => {
|
|||||||
formikSetValues(formikInitialValues);
|
formikSetValues(formikInitialValues);
|
||||||
}, [formikSetValues, formikInitialValues]);
|
}, [formikSetValues, formikInitialValues]);
|
||||||
|
|
||||||
|
// ===== Formik Error List =====
|
||||||
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<section className='w-full max-w-xl'>
|
<section className='w-full max-w-xl'>
|
||||||
@@ -145,7 +150,7 @@ const BankForm = ({ type = 'add', initialValues }: BankFormProps) => {
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
<form
|
<form
|
||||||
onSubmit={formik.handleSubmit}
|
onSubmit={handleFormSubmit}
|
||||||
onReset={formik.handleReset}
|
onReset={formik.handleReset}
|
||||||
className='w-full mt-8 flex flex-col gap-6'
|
className='w-full mt-8 flex flex-col gap-6'
|
||||||
>
|
>
|
||||||
@@ -247,6 +252,8 @@ const BankForm = ({ type = 'add', initialValues }: BankFormProps) => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
|
|
||||||
{type !== 'detail' && (
|
{type !== 'detail' && (
|
||||||
<div
|
<div
|
||||||
className={cn('flex flex-row justify-end gap-2', {
|
className={cn('flex flex-row justify-end gap-2', {
|
||||||
@@ -261,7 +268,7 @@ const BankForm = ({ type = 'add', initialValues }: BankFormProps) => {
|
|||||||
type='submit'
|
type='submit'
|
||||||
color='primary'
|
color='primary'
|
||||||
isLoading={formik.isSubmitting}
|
isLoading={formik.isSubmitting}
|
||||||
disabled={!formik.isValid || formik.isSubmitting}
|
disabled={formik.isSubmitting}
|
||||||
className='px-4'
|
className='px-4'
|
||||||
>
|
>
|
||||||
Submit
|
Submit
|
||||||
|
|||||||
@@ -28,6 +28,8 @@ import useSWR from 'swr';
|
|||||||
import { UserApi } from '@/services/api/user';
|
import { UserApi } from '@/services/api/user';
|
||||||
import { TYPE_OPTIONS } from '@/config/constant';
|
import { TYPE_OPTIONS } from '@/config/constant';
|
||||||
import RequirePermission from '@/components/helper/RequirePermission';
|
import RequirePermission from '@/components/helper/RequirePermission';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
|
|
||||||
interface CustomerFormProps {
|
interface CustomerFormProps {
|
||||||
formType?: 'add' | 'edit' | 'detail';
|
formType?: 'add' | 'edit' | 'detail';
|
||||||
@@ -191,6 +193,9 @@ const CustomerForm = ({
|
|||||||
formikSetValues(formikInitialValues);
|
formikSetValues(formikInitialValues);
|
||||||
}, [formikSetValues, formikInitialValues]);
|
}, [formikSetValues, formikInitialValues]);
|
||||||
|
|
||||||
|
// ===== Formik Error List =====
|
||||||
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
|
|
||||||
// Render
|
// Render
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -213,7 +218,7 @@ const CustomerForm = ({
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
<form
|
<form
|
||||||
onSubmit={formik.handleSubmit}
|
onSubmit={handleFormSubmit}
|
||||||
onReset={formik.handleReset}
|
onReset={formik.handleReset}
|
||||||
className='w-full mt-8 flex flex-col gap-6'
|
className='w-full mt-8 flex flex-col gap-6'
|
||||||
>
|
>
|
||||||
@@ -358,6 +363,8 @@ const CustomerForm = ({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
|
|
||||||
{formType !== 'detail' && (
|
{formType !== 'detail' && (
|
||||||
<div
|
<div
|
||||||
className={cn('flex flex-row justify-end gap-2', {
|
className={cn('flex flex-row justify-end gap-2', {
|
||||||
@@ -372,7 +379,7 @@ const CustomerForm = ({
|
|||||||
type='submit'
|
type='submit'
|
||||||
color='primary'
|
color='primary'
|
||||||
isLoading={formik.isSubmitting}
|
isLoading={formik.isSubmitting}
|
||||||
disabled={!formik.isValid || formik.isSubmitting}
|
disabled={formik.isSubmitting}
|
||||||
className='px-4'
|
className='px-4'
|
||||||
>
|
>
|
||||||
Submit
|
Submit
|
||||||
|
|||||||
@@ -26,6 +26,8 @@ import {
|
|||||||
} from '@/types/api/master-data/fcr';
|
} from '@/types/api/master-data/fcr';
|
||||||
import { FcrApi } from '@/services/api/master-data';
|
import { FcrApi } from '@/services/api/master-data';
|
||||||
import { cn } from '@/lib/helper';
|
import { cn } from '@/lib/helper';
|
||||||
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
|
|
||||||
interface FcrFormProps {
|
interface FcrFormProps {
|
||||||
type?: 'add' | 'edit' | 'detail';
|
type?: 'add' | 'edit' | 'detail';
|
||||||
@@ -158,6 +160,9 @@ const FcrForm = ({ type = 'add', initialValues }: FcrFormProps) => {
|
|||||||
formikSetValues(formikInitialValues);
|
formikSetValues(formikInitialValues);
|
||||||
}, [formikSetValues, formikInitialValues]);
|
}, [formikSetValues, formikInitialValues]);
|
||||||
|
|
||||||
|
// ===== Formik Error List =====
|
||||||
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<section className='w-full max-w-5xl'>
|
<section className='w-full max-w-5xl'>
|
||||||
@@ -179,7 +184,7 @@ const FcrForm = ({ type = 'add', initialValues }: FcrFormProps) => {
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
<form
|
<form
|
||||||
onSubmit={formik.handleSubmit}
|
onSubmit={handleFormSubmit}
|
||||||
onReset={formik.handleReset}
|
onReset={formik.handleReset}
|
||||||
className='w-full mt-8 flex flex-col gap-6'
|
className='w-full mt-8 flex flex-col gap-6'
|
||||||
>
|
>
|
||||||
@@ -294,6 +299,8 @@ const FcrForm = ({ type = 'add', initialValues }: FcrFormProps) => {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
|
|
||||||
<div className='flex flex-row justify-between gap-2 flex-wrap'>
|
<div className='flex flex-row justify-between gap-2 flex-wrap'>
|
||||||
{type !== 'add' && (
|
{type !== 'add' && (
|
||||||
<div className='flex flex-row justify-start gap-2'>
|
<div className='flex flex-row justify-start gap-2'>
|
||||||
@@ -349,7 +356,7 @@ const FcrForm = ({ type = 'add', initialValues }: FcrFormProps) => {
|
|||||||
type='submit'
|
type='submit'
|
||||||
color='primary'
|
color='primary'
|
||||||
isLoading={formik.isSubmitting}
|
isLoading={formik.isSubmitting}
|
||||||
disabled={!formik.isValid || formik.isSubmitting}
|
disabled={formik.isSubmitting}
|
||||||
className='px-4'
|
className='px-4'
|
||||||
>
|
>
|
||||||
Submit
|
Submit
|
||||||
|
|||||||
@@ -17,6 +17,8 @@ import TextInput from '@/components/input/TextInput';
|
|||||||
import { cn } from '@/lib/helper';
|
import { cn } from '@/lib/helper';
|
||||||
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||||
import RequirePermission from '@/components/helper/RequirePermission';
|
import RequirePermission from '@/components/helper/RequirePermission';
|
||||||
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
|
|
||||||
interface FlockCustomProps {
|
interface FlockCustomProps {
|
||||||
formType?: 'add' | 'edit' | 'detail';
|
formType?: 'add' | 'edit' | 'detail';
|
||||||
@@ -86,6 +88,9 @@ const FlockForm = ({ formType = 'add', initialValues }: FlockCustomProps) => {
|
|||||||
formikSetValues(formikInitialValue);
|
formikSetValues(formikInitialValue);
|
||||||
}, [formikSetValues, formikInitialValue]);
|
}, [formikSetValues, formikInitialValue]);
|
||||||
|
|
||||||
|
// ===== Formik Error List =====
|
||||||
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
|
|
||||||
// Render
|
// Render
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -107,7 +112,7 @@ const FlockForm = ({ formType = 'add', initialValues }: FlockCustomProps) => {
|
|||||||
</h1>
|
</h1>
|
||||||
</header>
|
</header>
|
||||||
<form
|
<form
|
||||||
onSubmit={formik.handleSubmit}
|
onSubmit={handleFormSubmit}
|
||||||
onReset={formik.handleReset}
|
onReset={formik.handleReset}
|
||||||
className='w-full mt-8 flex flex-col gap-6'
|
className='w-full mt-8 flex flex-col gap-6'
|
||||||
>
|
>
|
||||||
@@ -168,6 +173,8 @@ const FlockForm = ({ formType = 'add', initialValues }: FlockCustomProps) => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
|
|
||||||
{formType !== 'detail' && (
|
{formType !== 'detail' && (
|
||||||
<div
|
<div
|
||||||
className={cn('flex flex-row justify-end gap-2', {
|
className={cn('flex flex-row justify-end gap-2', {
|
||||||
@@ -182,7 +189,7 @@ const FlockForm = ({ formType = 'add', initialValues }: FlockCustomProps) => {
|
|||||||
type='submit'
|
type='submit'
|
||||||
color='primary'
|
color='primary'
|
||||||
isLoading={formik.isSubmitting}
|
isLoading={formik.isSubmitting}
|
||||||
disabled={!formik.isValid || formik.isSubmitting}
|
disabled={formik.isSubmitting}
|
||||||
className='px-4'
|
className='px-4'
|
||||||
>
|
>
|
||||||
Submit
|
Submit
|
||||||
|
|||||||
@@ -29,6 +29,8 @@ import { LocationApi, KandangApi } from '@/services/api/master-data';
|
|||||||
import { cn } from '@/lib/helper';
|
import { cn } from '@/lib/helper';
|
||||||
import { UserApi } from '@/services/api/user';
|
import { UserApi } from '@/services/api/user';
|
||||||
import NumberInput from '@/components/input/NumberInput';
|
import NumberInput from '@/components/input/NumberInput';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
|
|
||||||
interface KandangFormProps {
|
interface KandangFormProps {
|
||||||
type?: 'add' | 'edit' | 'detail';
|
type?: 'add' | 'edit' | 'detail';
|
||||||
@@ -198,6 +200,9 @@ const KandangForm = ({ type = 'add', initialValues }: KandangFormProps) => {
|
|||||||
formikSetValues(formikInitialValues);
|
formikSetValues(formikInitialValues);
|
||||||
}, [formikSetValues, formikInitialValues]);
|
}, [formikSetValues, formikInitialValues]);
|
||||||
|
|
||||||
|
// ===== Formik Error List =====
|
||||||
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<section className='w-full max-w-xl'>
|
<section className='w-full max-w-xl'>
|
||||||
@@ -219,7 +224,7 @@ const KandangForm = ({ type = 'add', initialValues }: KandangFormProps) => {
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
<form
|
<form
|
||||||
onSubmit={formik.handleSubmit}
|
onSubmit={handleFormSubmit}
|
||||||
onReset={formik.handleReset}
|
onReset={formik.handleReset}
|
||||||
className='w-full mt-8 flex flex-col gap-6'
|
className='w-full mt-8 flex flex-col gap-6'
|
||||||
>
|
>
|
||||||
@@ -324,6 +329,8 @@ const KandangForm = ({ type = 'add', initialValues }: KandangFormProps) => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
|
|
||||||
{type !== 'detail' && (
|
{type !== 'detail' && (
|
||||||
<div
|
<div
|
||||||
className={cn('flex flex-row justify-end gap-2', {
|
className={cn('flex flex-row justify-end gap-2', {
|
||||||
@@ -338,7 +345,7 @@ const KandangForm = ({ type = 'add', initialValues }: KandangFormProps) => {
|
|||||||
type='submit'
|
type='submit'
|
||||||
color='primary'
|
color='primary'
|
||||||
isLoading={formik.isSubmitting}
|
isLoading={formik.isSubmitting}
|
||||||
disabled={!formik.isValid || formik.isSubmitting}
|
disabled={formik.isSubmitting}
|
||||||
className='px-4'
|
className='px-4'
|
||||||
>
|
>
|
||||||
Submit
|
Submit
|
||||||
|
|||||||
@@ -27,6 +27,8 @@ import {
|
|||||||
} from '@/types/api/master-data/location';
|
} from '@/types/api/master-data/location';
|
||||||
import { AreaApi, LocationApi } from '@/services/api/master-data';
|
import { AreaApi, LocationApi } from '@/services/api/master-data';
|
||||||
import { cn } from '@/lib/helper';
|
import { cn } from '@/lib/helper';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
|
|
||||||
interface LocationFormProps {
|
interface LocationFormProps {
|
||||||
type?: 'add' | 'edit' | 'detail';
|
type?: 'add' | 'edit' | 'detail';
|
||||||
@@ -160,6 +162,9 @@ const LocationForm = ({ type = 'add', initialValues }: LocationFormProps) => {
|
|||||||
formikSetValues(formikInitialValues);
|
formikSetValues(formikInitialValues);
|
||||||
}, [formikSetValues, formikInitialValues]);
|
}, [formikSetValues, formikInitialValues]);
|
||||||
|
|
||||||
|
// ===== Formik Error List =====
|
||||||
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<section className='w-full max-w-xl'>
|
<section className='w-full max-w-xl'>
|
||||||
@@ -181,7 +186,7 @@ const LocationForm = ({ type = 'add', initialValues }: LocationFormProps) => {
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
<form
|
<form
|
||||||
onSubmit={formik.handleSubmit}
|
onSubmit={handleFormSubmit}
|
||||||
onReset={formik.handleReset}
|
onReset={formik.handleReset}
|
||||||
className='w-full mt-8 flex flex-col gap-6'
|
className='w-full mt-8 flex flex-col gap-6'
|
||||||
>
|
>
|
||||||
@@ -268,6 +273,8 @@ const LocationForm = ({ type = 'add', initialValues }: LocationFormProps) => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
|
|
||||||
{type !== 'detail' && (
|
{type !== 'detail' && (
|
||||||
<div
|
<div
|
||||||
className={cn('flex flex-row justify-end gap-2', {
|
className={cn('flex flex-row justify-end gap-2', {
|
||||||
@@ -282,7 +289,7 @@ const LocationForm = ({ type = 'add', initialValues }: LocationFormProps) => {
|
|||||||
type='submit'
|
type='submit'
|
||||||
color='primary'
|
color='primary'
|
||||||
isLoading={formik.isSubmitting}
|
isLoading={formik.isSubmitting}
|
||||||
disabled={!formik.isValid || formik.isSubmitting}
|
disabled={formik.isSubmitting}
|
||||||
className='px-4'
|
className='px-4'
|
||||||
>
|
>
|
||||||
Submit
|
Submit
|
||||||
|
|||||||
@@ -29,6 +29,8 @@ import { NonstockApi, SupplierApi, UomApi } from '@/services/api/master-data';
|
|||||||
import { cn } from '@/lib/helper';
|
import { cn } from '@/lib/helper';
|
||||||
import { flags } from '@/types/api/api-general';
|
import { flags } from '@/types/api/api-general';
|
||||||
import { SUPPLIER_FLAG_OPTIONS } from '@/config/constant';
|
import { SUPPLIER_FLAG_OPTIONS } from '@/config/constant';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
|
|
||||||
interface NonstockFormProps {
|
interface NonstockFormProps {
|
||||||
type?: 'add' | 'edit' | 'detail';
|
type?: 'add' | 'edit' | 'detail';
|
||||||
@@ -213,6 +215,9 @@ const NonstockForm = ({ type = 'add', initialValues }: NonstockFormProps) => {
|
|||||||
formikSetValues(formikInitialValues);
|
formikSetValues(formikInitialValues);
|
||||||
}, [formikSetValues, formikInitialValues]);
|
}, [formikSetValues, formikInitialValues]);
|
||||||
|
|
||||||
|
// ===== Formik Error List =====
|
||||||
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<section className='w-full max-w-xl'>
|
<section className='w-full max-w-xl'>
|
||||||
@@ -234,7 +239,7 @@ const NonstockForm = ({ type = 'add', initialValues }: NonstockFormProps) => {
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
<form
|
<form
|
||||||
onSubmit={formik.handleSubmit}
|
onSubmit={handleFormSubmit}
|
||||||
onReset={formik.handleReset}
|
onReset={formik.handleReset}
|
||||||
className='w-full mt-8 flex flex-col gap-6'
|
className='w-full mt-8 flex flex-col gap-6'
|
||||||
>
|
>
|
||||||
@@ -337,6 +342,8 @@ const NonstockForm = ({ type = 'add', initialValues }: NonstockFormProps) => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
|
|
||||||
{type !== 'detail' && (
|
{type !== 'detail' && (
|
||||||
<div
|
<div
|
||||||
className={cn('flex flex-row justify-end gap-2', {
|
className={cn('flex flex-row justify-end gap-2', {
|
||||||
@@ -351,7 +358,7 @@ const NonstockForm = ({ type = 'add', initialValues }: NonstockFormProps) => {
|
|||||||
type='submit'
|
type='submit'
|
||||||
color='primary'
|
color='primary'
|
||||||
isLoading={formik.isSubmitting}
|
isLoading={formik.isSubmitting}
|
||||||
disabled={!formik.isValid || formik.isSubmitting}
|
disabled={formik.isSubmitting}
|
||||||
className='px-4'
|
className='px-4'
|
||||||
>
|
>
|
||||||
Submit
|
Submit
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ import TextInput from '@/components/input/TextInput';
|
|||||||
import { useModal } from '@/components/Modal';
|
import { useModal } from '@/components/Modal';
|
||||||
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||||
import RequirePermission from '@/components/helper/RequirePermission';
|
import RequirePermission from '@/components/helper/RequirePermission';
|
||||||
import { getUniqueFormikErrors } from '@/lib/formik-helper';
|
|
||||||
import AlertErrorList from '@/components/helper/form/FormErrors';
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
@@ -27,6 +26,7 @@ import {
|
|||||||
} from '@/types/api/master-data/product-category';
|
} from '@/types/api/master-data/product-category';
|
||||||
import { ProductCategoryApi } from '@/services/api/master-data';
|
import { ProductCategoryApi } from '@/services/api/master-data';
|
||||||
import { cn } from '@/lib/helper';
|
import { cn } from '@/lib/helper';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
|
|
||||||
interface ProductCategoryFormProps {
|
interface ProductCategoryFormProps {
|
||||||
type?: 'add' | 'edit' | 'detail';
|
type?: 'add' | 'edit' | 'detail';
|
||||||
@@ -41,7 +41,6 @@ const ProductCategoryForm = ({
|
|||||||
const deleteModal = useModal();
|
const deleteModal = useModal();
|
||||||
|
|
||||||
const [formErrorMessage, setFormErrorMessage] = useState('');
|
const [formErrorMessage, setFormErrorMessage] = useState('');
|
||||||
const [formErrorList, setFormErrorList] = useState<string[]>([]);
|
|
||||||
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||||
|
|
||||||
const createProductCategoryHandler = useCallback(
|
const createProductCategoryHandler = useCallback(
|
||||||
@@ -132,21 +131,8 @@ const ProductCategoryForm = ({
|
|||||||
formikSetValues(formikInitialValues);
|
formikSetValues(formikInitialValues);
|
||||||
}, [formikSetValues, formikInitialValues]);
|
}, [formikSetValues, formikInitialValues]);
|
||||||
|
|
||||||
const handleValidateForm = async () => {
|
// ===== Formik Error List =====
|
||||||
const errors = await formik.validateForm();
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
|
|
||||||
if (Object.keys(errors).length > 0) {
|
|
||||||
const errorMessages = getUniqueFormikErrors(errors);
|
|
||||||
setFormErrorList(errorMessages);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
|
|
||||||
e.preventDefault();
|
|
||||||
handleValidateForm();
|
|
||||||
formik.handleSubmit(e);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -184,13 +170,7 @@ const ProductCategoryForm = ({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Error List Alert */}
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
{formErrorList.length > 0 && (
|
|
||||||
<AlertErrorList
|
|
||||||
formErrorList={formErrorList}
|
|
||||||
onClose={() => setFormErrorList([])}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className='flex flex-col gap-4'>
|
<div className='flex flex-col gap-4'>
|
||||||
<TextInput
|
<TextInput
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ import {
|
|||||||
} from '@/services/api/master-data';
|
} from '@/services/api/master-data';
|
||||||
import { cn } from '@/lib/helper';
|
import { cn } from '@/lib/helper';
|
||||||
import { PRODUCT_FLAG_OPTIONS } from '@/config/constant';
|
import { PRODUCT_FLAG_OPTIONS } from '@/config/constant';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
|
|
||||||
interface ProductFormProps {
|
interface ProductFormProps {
|
||||||
type?: 'add' | 'edit' | 'detail';
|
type?: 'add' | 'edit' | 'detail';
|
||||||
@@ -50,7 +51,6 @@ const ProductForm = ({ type = 'add', initialValues }: ProductFormProps) => {
|
|||||||
const deleteModal = useModal();
|
const deleteModal = useModal();
|
||||||
|
|
||||||
const [productFormErrorMessage, setProductFormErrorMessage] = useState('');
|
const [productFormErrorMessage, setProductFormErrorMessage] = useState('');
|
||||||
const [formErrorList, setFormErrorList] = useState<string[]>([]);
|
|
||||||
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||||
|
|
||||||
const createProductHandler = useCallback(
|
const createProductHandler = useCallback(
|
||||||
@@ -204,21 +204,8 @@ const ProductForm = ({ type = 'add', initialValues }: ProductFormProps) => {
|
|||||||
formikSetValues(formikInitialValues);
|
formikSetValues(formikInitialValues);
|
||||||
}, [formikSetValues, formikInitialValues]);
|
}, [formikSetValues, formikInitialValues]);
|
||||||
|
|
||||||
const handleValidateForm = async () => {
|
// ===== Formik Error List =====
|
||||||
const errors = await formik.validateForm();
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
|
|
||||||
if (Object.keys(errors).length > 0) {
|
|
||||||
const errorMessages = getUniqueFormikErrors(errors);
|
|
||||||
setFormErrorList(errorMessages);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
|
|
||||||
e.preventDefault();
|
|
||||||
handleValidateForm();
|
|
||||||
formik.handleSubmit(e);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -254,13 +241,7 @@ const ProductForm = ({ type = 'add', initialValues }: ProductFormProps) => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Error List Alert */}
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
{formErrorList.length > 0 && (
|
|
||||||
<AlertErrorList
|
|
||||||
formErrorList={formErrorList}
|
|
||||||
onClose={() => setFormErrorList([])}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className='grid grid-cols-1 gap-4'>
|
<div className='grid grid-cols-1 gap-4'>
|
||||||
<TextInput
|
<TextInput
|
||||||
|
|||||||
+24
-15
@@ -9,6 +9,7 @@ import {
|
|||||||
ProductionStandardRepeaterFormSchemaValues,
|
ProductionStandardRepeaterFormSchemaValues,
|
||||||
ProductionStandardFormValues,
|
ProductionStandardFormValues,
|
||||||
createProductionStandardRepeaterFormSchema,
|
createProductionStandardRepeaterFormSchema,
|
||||||
|
ProductionStandardFormSchema,
|
||||||
} from '@/components/pages/master-data/production-standard/form/ProductionStandardForm.schema';
|
} from '@/components/pages/master-data/production-standard/form/ProductionStandardForm.schema';
|
||||||
import Table, { TABLE_DEFAULT_STYLING } from '@/components/Table';
|
import Table, { TABLE_DEFAULT_STYLING } from '@/components/Table';
|
||||||
import { FLOCK_CATEGORY_OPTIONS } from '@/config/constant';
|
import { FLOCK_CATEGORY_OPTIONS } from '@/config/constant';
|
||||||
@@ -31,6 +32,8 @@ import { useModal } from '@/components/Modal';
|
|||||||
import RequirePermission from '@/components/helper/RequirePermission';
|
import RequirePermission from '@/components/helper/RequirePermission';
|
||||||
import Tooltip from '@/components/Tooltip';
|
import Tooltip from '@/components/Tooltip';
|
||||||
import Alert from '@/components/Alert';
|
import Alert from '@/components/Alert';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
|
|
||||||
type TableRowsType = {
|
type TableRowsType = {
|
||||||
customRow: boolean;
|
customRow: boolean;
|
||||||
@@ -207,6 +210,7 @@ const ProductionStandardForm = ({
|
|||||||
initialValues: formikInitialValues as ProductionStandardFormValues,
|
initialValues: formikInitialValues as ProductionStandardFormValues,
|
||||||
// Only enable reinitialize for edit/detail mode, not add mode
|
// Only enable reinitialize for edit/detail mode, not add mode
|
||||||
enableReinitialize: formType !== 'add',
|
enableReinitialize: formType !== 'add',
|
||||||
|
validationSchema: ProductionStandardFormSchema,
|
||||||
onSubmit: (values) => {
|
onSubmit: (values) => {
|
||||||
switch (formType) {
|
switch (formType) {
|
||||||
case 'add':
|
case 'add':
|
||||||
@@ -723,7 +727,8 @@ const ProductionStandardForm = ({
|
|||||||
router.push('/master-data/production-standard');
|
router.push('/master-data/production-standard');
|
||||||
};
|
};
|
||||||
|
|
||||||
// ===== Function =====
|
// ===== Formik Error List =====
|
||||||
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -1210,9 +1215,26 @@ const ProductionStandardForm = ({
|
|||||||
return null;
|
return null;
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
|
|
||||||
|
{productionStandardFormErrorMessage && (
|
||||||
|
<Alert color='error' className='w-full'>
|
||||||
|
<div className='flex items-center gap-2 stretch'>
|
||||||
|
<Icon icon='mdi:alert' />
|
||||||
|
<span>{productionStandardFormErrorMessage}</span>
|
||||||
|
</div>
|
||||||
|
<Icon
|
||||||
|
icon='mdi:close'
|
||||||
|
onClick={() => setProductionStandardFormErrorMessage('')}
|
||||||
|
className='ms-auto'
|
||||||
|
/>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
<form
|
<form
|
||||||
className='flex justify-between mt-6 gap-2 flex-wrap'
|
className='flex justify-between mt-6 gap-2 flex-wrap'
|
||||||
onSubmit={formik.handleSubmit}
|
onSubmit={handleFormSubmit}
|
||||||
>
|
>
|
||||||
{formType === 'detail' && (
|
{formType === 'detail' && (
|
||||||
<div className='gap-2 flex items-center'>
|
<div className='gap-2 flex items-center'>
|
||||||
@@ -1293,19 +1315,6 @@ const ProductionStandardForm = ({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</form>
|
</form>
|
||||||
{productionStandardFormErrorMessage && (
|
|
||||||
<Alert color='error' className='w-full'>
|
|
||||||
<div className='flex items-center gap-2 stretch'>
|
|
||||||
<Icon icon='mdi:alert' />
|
|
||||||
<span>{productionStandardFormErrorMessage}</span>
|
|
||||||
</div>
|
|
||||||
<Icon
|
|
||||||
icon='mdi:close'
|
|
||||||
onClick={() => setProductionStandardFormErrorMessage('')}
|
|
||||||
className='ms-auto'
|
|
||||||
/>
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<ConfirmationModal
|
<ConfirmationModal
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ import TextArea from '@/components/input/TextArea';
|
|||||||
import { cn } from '@/lib/helper';
|
import { cn } from '@/lib/helper';
|
||||||
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||||
import RequirePermission from '@/components/helper/RequirePermission';
|
import RequirePermission from '@/components/helper/RequirePermission';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
|
|
||||||
interface SupplierCustomProps {
|
interface SupplierCustomProps {
|
||||||
formType?: 'add' | 'edit' | 'detail';
|
formType?: 'add' | 'edit' | 'detail';
|
||||||
@@ -199,6 +201,9 @@ const SupplierForm = ({
|
|||||||
formik.setFieldValue('category', val);
|
formik.setFieldValue('category', val);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// ===== Formik Error List =====
|
||||||
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
|
|
||||||
// Render
|
// Render
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -221,7 +226,7 @@ const SupplierForm = ({
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
<form
|
<form
|
||||||
onSubmit={formik.handleSubmit}
|
onSubmit={handleFormSubmit}
|
||||||
onReset={formik.handleReset}
|
onReset={formik.handleReset}
|
||||||
className='w-full mt-8 flex flex-col gap-6'
|
className='w-full mt-8 flex flex-col gap-6'
|
||||||
>
|
>
|
||||||
@@ -444,6 +449,8 @@ const SupplierForm = ({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
|
|
||||||
{formType !== 'detail' && (
|
{formType !== 'detail' && (
|
||||||
<div
|
<div
|
||||||
className={cn('flex flex-row justify-end gap-2', {
|
className={cn('flex flex-row justify-end gap-2', {
|
||||||
@@ -458,7 +465,7 @@ const SupplierForm = ({
|
|||||||
type='submit'
|
type='submit'
|
||||||
color='primary'
|
color='primary'
|
||||||
isLoading={formik.isSubmitting}
|
isLoading={formik.isSubmitting}
|
||||||
disabled={!formik.isValid || formik.isSubmitting}
|
disabled={formik.isSubmitting}
|
||||||
className='px-4'
|
className='px-4'
|
||||||
>
|
>
|
||||||
Submit
|
Submit
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ import {
|
|||||||
} from '@/types/api/master-data/uom';
|
} from '@/types/api/master-data/uom';
|
||||||
import { UomApi } from '@/services/api/master-data';
|
import { UomApi } from '@/services/api/master-data';
|
||||||
import { cn } from '@/lib/helper';
|
import { cn } from '@/lib/helper';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
|
|
||||||
interface UomFormProps {
|
interface UomFormProps {
|
||||||
type?: 'add' | 'edit' | 'detail';
|
type?: 'add' | 'edit' | 'detail';
|
||||||
@@ -118,6 +120,9 @@ const UomForm = ({ type = 'add', initialValues }: UomFormProps) => {
|
|||||||
formikSetValues(formikInitialValues);
|
formikSetValues(formikInitialValues);
|
||||||
}, [formikSetValues, formikInitialValues]);
|
}, [formikSetValues, formikInitialValues]);
|
||||||
|
|
||||||
|
// ===== Formik Error List =====
|
||||||
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<section className='w-full max-w-xl'>
|
<section className='w-full max-w-xl'>
|
||||||
@@ -139,7 +144,7 @@ const UomForm = ({ type = 'add', initialValues }: UomFormProps) => {
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
<form
|
<form
|
||||||
onSubmit={formik.handleSubmit}
|
onSubmit={handleFormSubmit}
|
||||||
onReset={formik.handleReset}
|
onReset={formik.handleReset}
|
||||||
className='w-full mt-8 flex flex-col gap-6'
|
className='w-full mt-8 flex flex-col gap-6'
|
||||||
>
|
>
|
||||||
@@ -199,6 +204,8 @@ const UomForm = ({ type = 'add', initialValues }: UomFormProps) => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
|
|
||||||
{type !== 'detail' && (
|
{type !== 'detail' && (
|
||||||
<div
|
<div
|
||||||
className={cn('flex flex-row justify-end gap-2', {
|
className={cn('flex flex-row justify-end gap-2', {
|
||||||
@@ -213,7 +220,7 @@ const UomForm = ({ type = 'add', initialValues }: UomFormProps) => {
|
|||||||
type='submit'
|
type='submit'
|
||||||
color='primary'
|
color='primary'
|
||||||
isLoading={formik.isSubmitting}
|
isLoading={formik.isSubmitting}
|
||||||
disabled={!formik.isValid || formik.isSubmitting}
|
disabled={formik.isSubmitting}
|
||||||
className='px-4'
|
className='px-4'
|
||||||
>
|
>
|
||||||
Submit
|
Submit
|
||||||
|
|||||||
@@ -33,6 +33,8 @@ import {
|
|||||||
} from '@/services/api/master-data';
|
} from '@/services/api/master-data';
|
||||||
import { cn } from '@/lib/helper';
|
import { cn } from '@/lib/helper';
|
||||||
import { WAREHOUSE_TYPE_OPTIONS } from '@/config/constant';
|
import { WAREHOUSE_TYPE_OPTIONS } from '@/config/constant';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
|
|
||||||
interface WarehouseFormProps {
|
interface WarehouseFormProps {
|
||||||
type?: 'add' | 'edit' | 'detail';
|
type?: 'add' | 'edit' | 'detail';
|
||||||
@@ -323,6 +325,9 @@ const WarehouseForm = ({ type = 'add', initialValues }: WarehouseFormProps) => {
|
|||||||
formikSetValues(formikInitialValues);
|
formikSetValues(formikInitialValues);
|
||||||
}, [formikSetValues, formikInitialValues]);
|
}, [formikSetValues, formikInitialValues]);
|
||||||
|
|
||||||
|
// ===== Formik Error List =====
|
||||||
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<section className='w-full max-w-xl'>
|
<section className='w-full max-w-xl'>
|
||||||
@@ -344,7 +349,7 @@ const WarehouseForm = ({ type = 'add', initialValues }: WarehouseFormProps) => {
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
<form
|
<form
|
||||||
onSubmit={formik.handleSubmit}
|
onSubmit={handleFormSubmit}
|
||||||
onReset={formik.handleReset}
|
onReset={formik.handleReset}
|
||||||
className='w-full mt-8 flex flex-col gap-6'
|
className='w-full mt-8 flex flex-col gap-6'
|
||||||
>
|
>
|
||||||
@@ -474,6 +479,8 @@ const WarehouseForm = ({ type = 'add', initialValues }: WarehouseFormProps) => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
|
|
||||||
{type !== 'detail' && (
|
{type !== 'detail' && (
|
||||||
<div
|
<div
|
||||||
className={cn('flex flex-row justify-end gap-2', {
|
className={cn('flex flex-row justify-end gap-2', {
|
||||||
@@ -488,7 +495,7 @@ const WarehouseForm = ({ type = 'add', initialValues }: WarehouseFormProps) => {
|
|||||||
type='submit'
|
type='submit'
|
||||||
color='primary'
|
color='primary'
|
||||||
isLoading={formik.isSubmitting}
|
isLoading={formik.isSubmitting}
|
||||||
disabled={!formik.isValid || formik.isSubmitting}
|
disabled={formik.isSubmitting}
|
||||||
className='px-4'
|
className='px-4'
|
||||||
>
|
>
|
||||||
Submit
|
Submit
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import { useTableFilter } from '@/services/hooks/useTableFilter';
|
|||||||
import { Kandang } from '@/types/api/master-data/kandang';
|
import { Kandang } from '@/types/api/master-data/kandang';
|
||||||
import { ProjectFlock } from '@/types/api/production/project-flock';
|
import { ProjectFlock } from '@/types/api/production/project-flock';
|
||||||
import { Icon } from '@iconify/react';
|
import { Icon } from '@iconify/react';
|
||||||
import { CellContext, SortingState } from '@tanstack/react-table';
|
import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table';
|
||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
import { ChangeEventHandler, useEffect, useMemo, useState } from 'react';
|
import { ChangeEventHandler, useEffect, useMemo, useState } from 'react';
|
||||||
import toast from 'react-hot-toast';
|
import toast from 'react-hot-toast';
|
||||||
@@ -27,84 +27,6 @@ import useSWR from 'swr';
|
|||||||
|
|
||||||
import RequirePermission from '@/components/helper/RequirePermission';
|
import RequirePermission from '@/components/helper/RequirePermission';
|
||||||
|
|
||||||
const RowOptionsMenu = ({
|
|
||||||
type = 'dropdown',
|
|
||||||
props,
|
|
||||||
deleteClickHandler,
|
|
||||||
}: {
|
|
||||||
type: 'dropdown' | 'collapse';
|
|
||||||
props: CellContext<ProjectFlock, unknown>;
|
|
||||||
deleteClickHandler: () => void;
|
|
||||||
}) => {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
tabIndex={type == 'dropdown' ? 0 : undefined}
|
|
||||||
className={cn(
|
|
||||||
{
|
|
||||||
'dropdown-content': type === 'dropdown',
|
|
||||||
'mt-2': type === 'collapse',
|
|
||||||
},
|
|
||||||
'p-2.5 mr-2 bg-base-100 rounded-box z-10 border border-black/10 shadow'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<div className='flex flex-col gap-1'>
|
|
||||||
<RequirePermission permissions='lti.production.project_flocks.detail'>
|
|
||||||
<Button
|
|
||||||
href={`/production/project-flock/detail?projectFlockId=${props.row.original.id}`}
|
|
||||||
variant='ghost'
|
|
||||||
color='primary'
|
|
||||||
className='justify-start text-sm'
|
|
||||||
>
|
|
||||||
<Icon icon='mdi:eye-outline' width={16} height={16} />
|
|
||||||
Detail
|
|
||||||
</Button>
|
|
||||||
</RequirePermission>
|
|
||||||
{props.row.original.approval.step_name === 'Aktif' && (
|
|
||||||
<RequirePermission permissions='lti.production.chickins.create'>
|
|
||||||
<Button
|
|
||||||
href={`/production/project-flock/chickin/add?projectFlockId=${props.row.original.id}`}
|
|
||||||
variant='ghost'
|
|
||||||
color='success'
|
|
||||||
className='justify-start text-sm'
|
|
||||||
>
|
|
||||||
<Icon icon='mdi:home-import-outline' width={16} height={16} />
|
|
||||||
Chickin
|
|
||||||
</Button>
|
|
||||||
</RequirePermission>
|
|
||||||
)}
|
|
||||||
{props.row.original.approval.step_name === 'Pengajuan' && (
|
|
||||||
<RequirePermission permissions='lti.production.project_flocks.update'>
|
|
||||||
<Button
|
|
||||||
href={`/production/project-flock/detail/edit?projectFlockId=${props.row.original.id}`}
|
|
||||||
variant='ghost'
|
|
||||||
color='warning'
|
|
||||||
className='justify-start text-sm'
|
|
||||||
>
|
|
||||||
<Icon icon='mdi:pencil-outline' width={16} height={16} />
|
|
||||||
Edit
|
|
||||||
</Button>
|
|
||||||
</RequirePermission>
|
|
||||||
)}
|
|
||||||
<RequirePermission permissions='lti.production.project_flocks.delete'>
|
|
||||||
<Button
|
|
||||||
onClick={deleteClickHandler}
|
|
||||||
variant='ghost'
|
|
||||||
color='error'
|
|
||||||
className='text-error hover:text-inherit justify-start text-sm'
|
|
||||||
>
|
|
||||||
<Icon
|
|
||||||
icon='material-symbols:delete-outline-rounded'
|
|
||||||
width={16}
|
|
||||||
height={16}
|
|
||||||
/>
|
|
||||||
Delete
|
|
||||||
</Button>
|
|
||||||
</RequirePermission>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
|
const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
|
||||||
const {
|
const {
|
||||||
state: tableFilterState,
|
state: tableFilterState,
|
||||||
@@ -149,8 +71,6 @@ const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
|
|||||||
);
|
);
|
||||||
const [periodInputValue, setPeriodInputValue] = useState<number | null>(null);
|
const [periodInputValue, setPeriodInputValue] = useState<number | null>(null);
|
||||||
const [sorting, setSorting] = useState<SortingState>([]);
|
const [sorting, setSorting] = useState<SortingState>([]);
|
||||||
const [selectedProjectFlock, setSelectedProjectFlock] =
|
|
||||||
useState<ProjectFlock>();
|
|
||||||
const deleteModal = useModal();
|
const deleteModal = useModal();
|
||||||
const confirmModal = useModal();
|
const confirmModal = useModal();
|
||||||
const [approvalAction, setApprovalAction] = useState<'APPROVED' | 'REJECTED'>(
|
const [approvalAction, setApprovalAction] = useState<'APPROVED' | 'REJECTED'>(
|
||||||
@@ -221,10 +141,6 @@ const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
|
|||||||
: [];
|
: [];
|
||||||
|
|
||||||
// ====== HANDLER ======
|
// ====== HANDLER ======
|
||||||
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
|
|
||||||
const newVal = val as OptionType;
|
|
||||||
setPageSize(newVal.value as number);
|
|
||||||
};
|
|
||||||
const confirmationModalDeleteClickHandler = async () => {
|
const confirmationModalDeleteClickHandler = async () => {
|
||||||
setIsDeleteLoading(true);
|
setIsDeleteLoading(true);
|
||||||
|
|
||||||
@@ -292,12 +208,146 @@ const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
|
|||||||
const canApprove = useMemo(() => {
|
const canApprove = useMemo(() => {
|
||||||
if (!selectedSingleRow || isApproveLoading) return false;
|
if (!selectedSingleRow || isApproveLoading) return false;
|
||||||
|
|
||||||
const isPengajuan = selectedSingleRow.approval.step_number == 1;
|
const isPengajuan = selectedSingleRow.approval?.step_number == 1;
|
||||||
const isNotRejected = selectedSingleRow.approval.action != 'REJECTED';
|
const isNotRejected = selectedSingleRow.approval?.action != 'REJECTED';
|
||||||
|
|
||||||
return isPengajuan && isNotRejected;
|
return isPengajuan && isNotRejected;
|
||||||
}, [selectedSingleRow, isApproveLoading]);
|
}, [selectedSingleRow, isApproveLoading]);
|
||||||
|
|
||||||
|
// ====== COLUMNS ======
|
||||||
|
const columns = useMemo<ColumnDef<ProjectFlock>[]>(
|
||||||
|
() => [
|
||||||
|
{
|
||||||
|
id: 'select',
|
||||||
|
header: ({ table }) => {
|
||||||
|
const allRows = table.getRowModel().rows;
|
||||||
|
const selectableRows = allRows;
|
||||||
|
|
||||||
|
const allSelected =
|
||||||
|
selectableRows.every((row) => row.getIsSelected()) &&
|
||||||
|
selectableRows.length != 0;
|
||||||
|
|
||||||
|
const someSelected =
|
||||||
|
selectableRows.some((row) => row.getIsSelected()) && !allSelected;
|
||||||
|
|
||||||
|
const toggleSelectableRows = () => {
|
||||||
|
const shouldSelect = !allSelected;
|
||||||
|
selectableRows.forEach((row) => row.toggleSelected(shouldSelect));
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className='w-full flex flex-row justify-center'>
|
||||||
|
<CheckboxInput
|
||||||
|
name='allRow'
|
||||||
|
checked={allSelected}
|
||||||
|
indeterminate={someSelected}
|
||||||
|
onChange={toggleSelectableRows}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
cell: ({ row }) => {
|
||||||
|
return (
|
||||||
|
<CheckboxInput
|
||||||
|
name='row'
|
||||||
|
checked={row.getIsSelected()}
|
||||||
|
disabled={!row.getCanSelect()}
|
||||||
|
indeterminate={row.getIsSomeSelected()}
|
||||||
|
onChange={row.getToggleSelectedHandler()}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
accessorKey: 'flock_name',
|
||||||
|
header: 'Flock',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'area.name',
|
||||||
|
header: 'Area',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'location.name',
|
||||||
|
header: 'Lokasi',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'fcr.name',
|
||||||
|
header: 'FCR',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'category',
|
||||||
|
header: 'Kategori',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'approval.step_name',
|
||||||
|
header: 'Status',
|
||||||
|
cell: (props) => {
|
||||||
|
const approval = props.row.original.approval;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Badge
|
||||||
|
variant='soft'
|
||||||
|
className={{
|
||||||
|
badge: 'rounded-lg px-2 w-full flex flex-row justify-start',
|
||||||
|
}}
|
||||||
|
color={
|
||||||
|
approval?.step_number == 1
|
||||||
|
? 'neutral'
|
||||||
|
: approval?.step_number == 2
|
||||||
|
? 'success'
|
||||||
|
: 'error'
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Icon
|
||||||
|
icon='mdi:circle'
|
||||||
|
width={12}
|
||||||
|
height={12}
|
||||||
|
color={
|
||||||
|
approval?.step_number == 1
|
||||||
|
? 'neutral'
|
||||||
|
: approval?.step_number == 2
|
||||||
|
? 'success'
|
||||||
|
: 'error'
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{approval?.step_name}
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
header: 'Kandang',
|
||||||
|
cell: (props) => {
|
||||||
|
const kandang = props.row.original.kandangs;
|
||||||
|
if (kandang) {
|
||||||
|
const kandangNames = kandang.map((k: Kandang) => k.name);
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{kandangNames.length > 0
|
||||||
|
? kandangNames.join(', ')
|
||||||
|
: 'Tidak ada'}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
return '-';
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'period',
|
||||||
|
header: 'Periode',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: 'created_at',
|
||||||
|
header: 'Dibuat pada',
|
||||||
|
cell: (props) =>
|
||||||
|
formatDate(props.row.original.created_at, 'MMM DD, YYYY'),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className='min-h-screen w-full p-4'>
|
<div className='min-h-screen w-full p-4'>
|
||||||
@@ -320,7 +370,7 @@ const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
|
|||||||
<div className='ms-auto w-full sm:w-auto'>
|
<div className='ms-auto w-full sm:w-auto'>
|
||||||
<DebouncedTextInput
|
<DebouncedTextInput
|
||||||
name='search'
|
name='search'
|
||||||
placeholder='Cari Area'
|
placeholder='Cari Project Flock'
|
||||||
value={tableFilterState.search}
|
value={tableFilterState.search}
|
||||||
onChange={searchChangeHandler}
|
onChange={searchChangeHandler}
|
||||||
className={{
|
className={{
|
||||||
@@ -382,160 +432,18 @@ const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
|
|||||||
type='number'
|
type='number'
|
||||||
label='Periode'
|
label='Periode'
|
||||||
placeholder='Masukan periode'
|
placeholder='Masukan periode'
|
||||||
value={periodInputValue ?? ''}
|
value={periodInputValue?.toString() ?? ''}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
setPeriodInputValue(parseInt(e.target.value));
|
setPeriodInputValue(parseInt(e.target.value));
|
||||||
updateFilter('periodFilter', e.target.value);
|
updateFilter('periodFilter', e.target.value);
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<SelectInput
|
|
||||||
label='Baris'
|
|
||||||
options={ROWS_OPTIONS}
|
|
||||||
value={{
|
|
||||||
label: String(tableFilterState.pageSize),
|
|
||||||
value: tableFilterState.pageSize,
|
|
||||||
}}
|
|
||||||
onChange={pageSizeChangeHandler}
|
|
||||||
className={{ wrapper: 'max-w-28' }}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Table<ProjectFlock>
|
<Table<ProjectFlock>
|
||||||
data={isResponseSuccess(projectFlocks) ? projectFlocks?.data : []}
|
data={isResponseSuccess(projectFlocks) ? projectFlocks?.data : []}
|
||||||
columns={[
|
columns={columns}
|
||||||
{
|
|
||||||
id: 'select',
|
|
||||||
header: ({ table }) => {
|
|
||||||
const allRows = table.getRowModel().rows;
|
|
||||||
const selectableRows = allRows;
|
|
||||||
|
|
||||||
const allSelected =
|
|
||||||
selectableRows.every((row) => row.getIsSelected()) &&
|
|
||||||
selectableRows.length != 0;
|
|
||||||
|
|
||||||
const someSelected =
|
|
||||||
selectableRows.some((row) => row.getIsSelected()) &&
|
|
||||||
!allSelected;
|
|
||||||
|
|
||||||
const toggleSelectableRows = () => {
|
|
||||||
const shouldSelect = !allSelected;
|
|
||||||
selectableRows.forEach((row) =>
|
|
||||||
row.toggleSelected(shouldSelect)
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className='w-full flex flex-row justify-center'>
|
|
||||||
<CheckboxInput
|
|
||||||
name='allRow'
|
|
||||||
checked={allSelected}
|
|
||||||
indeterminate={someSelected}
|
|
||||||
onChange={toggleSelectableRows}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
cell: ({ row }) => {
|
|
||||||
return (
|
|
||||||
<CheckboxInput
|
|
||||||
name='row'
|
|
||||||
checked={row.getIsSelected()}
|
|
||||||
disabled={!row.getCanSelect()}
|
|
||||||
indeterminate={row.getIsSomeSelected()}
|
|
||||||
onChange={row.getToggleSelectedHandler()}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
{
|
|
||||||
accessorKey: 'flock_name',
|
|
||||||
header: 'Flock',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'area.name',
|
|
||||||
header: 'Area',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'location.name',
|
|
||||||
header: 'Lokasi',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'fcr.name',
|
|
||||||
header: 'FCR',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'category',
|
|
||||||
header: 'Kategori',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'approval.step_name',
|
|
||||||
header: 'Status',
|
|
||||||
cell: (props) => {
|
|
||||||
const approval = props.row.original.approval;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Badge
|
|
||||||
variant='soft'
|
|
||||||
className={{
|
|
||||||
badge:
|
|
||||||
'rounded-lg px-2 w-full flex flex-row justify-start',
|
|
||||||
}}
|
|
||||||
color={
|
|
||||||
approval.step_number == 1
|
|
||||||
? 'neutral'
|
|
||||||
: approval.step_number == 2
|
|
||||||
? 'success'
|
|
||||||
: 'error'
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<Icon
|
|
||||||
icon='mdi:circle'
|
|
||||||
width={12}
|
|
||||||
height={12}
|
|
||||||
color={
|
|
||||||
approval.step_number == 1
|
|
||||||
? 'neutral'
|
|
||||||
: approval.step_number == 2
|
|
||||||
? 'success'
|
|
||||||
: 'error'
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
{approval.step_name}
|
|
||||||
</Badge>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
header: 'Kandang',
|
|
||||||
cell: (props) => {
|
|
||||||
const kandang = props.row.original.kandangs;
|
|
||||||
if (kandang) {
|
|
||||||
const kandangNames = kandang.map((k: Kandang) => k.name);
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
{kandangNames.length > 0
|
|
||||||
? kandangNames.join(', ')
|
|
||||||
: 'Tidak ada'}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
return '-';
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'period',
|
|
||||||
header: 'Periode',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: 'created_at',
|
|
||||||
header: 'Dibuat pada',
|
|
||||||
cell: (props) =>
|
|
||||||
formatDate(props.row.original.created_at, 'MMM DD, YYYY'),
|
|
||||||
},
|
|
||||||
]}
|
|
||||||
pageSize={tableFilterState.pageSize}
|
pageSize={tableFilterState.pageSize}
|
||||||
page={
|
page={
|
||||||
isResponseSuccess(projectFlocks) ? projectFlocks?.meta?.page : 0
|
isResponseSuccess(projectFlocks) ? projectFlocks?.meta?.page : 0
|
||||||
@@ -545,7 +453,12 @@ const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
|
|||||||
? projectFlocks?.meta?.total_results
|
? projectFlocks?.meta?.total_results
|
||||||
: 0
|
: 0
|
||||||
}
|
}
|
||||||
onPageChange={setPage}
|
onPageChange={(page) => {
|
||||||
|
setPage(page);
|
||||||
|
}}
|
||||||
|
onPageSizeChange={(pageSize) => {
|
||||||
|
setPageSize(pageSize);
|
||||||
|
}}
|
||||||
isLoading={isLoading}
|
isLoading={isLoading}
|
||||||
sorting={sorting}
|
sorting={sorting}
|
||||||
setSorting={setSorting}
|
setSorting={setSorting}
|
||||||
@@ -553,9 +466,9 @@ const ProjectFlockTable = ({ refresh }: { refresh?: () => void }) => {
|
|||||||
setRowSelection={setRowSelection}
|
setRowSelection={setRowSelection}
|
||||||
className={{
|
className={{
|
||||||
containerClassName: cn({
|
containerClassName: cn({
|
||||||
'mb-20':
|
'mb-40':
|
||||||
isResponseSuccess(projectFlocks) &&
|
isResponseSuccess(projectFlocks) &&
|
||||||
projectFlocks?.data?.length === 0,
|
projectFlocks?.data?.length > 0,
|
||||||
}),
|
}),
|
||||||
tableWrapperClassName: 'overflow-x-auto min-h-full!',
|
tableWrapperClassName: 'overflow-x-auto min-h-full!',
|
||||||
tableClassName: 'font-inter w-full table-auto min-h-full!',
|
tableClassName: 'font-inter w-full table-auto min-h-full!',
|
||||||
|
|||||||
@@ -209,20 +209,6 @@ const ProjectFlockDetail = ({
|
|||||||
</Badge>
|
</Badge>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* <div className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2'>
|
|
||||||
<Icon width={14} height={14} icon={'mdi:clock'} /> History
|
|
||||||
</div>
|
|
||||||
<div className='col-span-2'>
|
|
||||||
<Button variant='outline' className='py-1 text-sm'>
|
|
||||||
See History{' '}
|
|
||||||
<Icon
|
|
||||||
icon='mdi:arrow-top-right-thin'
|
|
||||||
width={11}
|
|
||||||
height={11}
|
|
||||||
/>
|
|
||||||
</Button>
|
|
||||||
</div> */}
|
|
||||||
|
|
||||||
{/* BARIS 1 */}
|
{/* BARIS 1 */}
|
||||||
<div
|
<div
|
||||||
className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2
|
className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2
|
||||||
@@ -252,6 +238,18 @@ const ProjectFlockDetail = ({
|
|||||||
</div>
|
</div>
|
||||||
<div className='col-span-2'>{projectFlock?.fcr?.name}</div>
|
<div className='col-span-2'>{projectFlock?.fcr?.name}</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2
|
||||||
|
relative
|
||||||
|
before:content-[""] before:absolute before:left-[5px] before:top-[90%] before:bottom-[-100%] before:w-[1px] before:border-1 before:border-dashed before:border-gray-400'
|
||||||
|
>
|
||||||
|
<Icon width={14} height={14} icon='mdi:circle-slice-8' />{' '}
|
||||||
|
Standard
|
||||||
|
</div>
|
||||||
|
<div className='col-span-2'>
|
||||||
|
{projectFlock?.production_standard?.name ?? '-'}
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* BARIS 3 (Terakhir - TIDAK PERLU garis di bawahnya) */}
|
{/* BARIS 3 (Terakhir - TIDAK PERLU garis di bawahnya) */}
|
||||||
<div className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2'>
|
<div className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2'>
|
||||||
<Icon width={14} height={14} icon='mdi:circle-slice-8' />{' '}
|
<Icon width={14} height={14} icon='mdi:circle-slice-8' />{' '}
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import SelectInput, {
|
|||||||
useSelect,
|
useSelect,
|
||||||
} from '@/components/input/SelectInput';
|
} from '@/components/input/SelectInput';
|
||||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||||
import { getUniqueFormikErrors } from '@/lib/formik-helper';
|
|
||||||
import AlertErrorList from '@/components/helper/form/FormErrors';
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
import {
|
import {
|
||||||
AreaApi,
|
AreaApi,
|
||||||
@@ -47,6 +46,7 @@ import { Nonstock } from '@/types/api/master-data/nonstock';
|
|||||||
import { useUiStore } from '@/stores/ui/ui.store';
|
import { useUiStore } from '@/stores/ui/ui.store';
|
||||||
import RequirePermission from '@/components/helper/RequirePermission';
|
import RequirePermission from '@/components/helper/RequirePermission';
|
||||||
import DrawerHeader from '@/components/helper/drawer/DrawerHeader';
|
import DrawerHeader from '@/components/helper/drawer/DrawerHeader';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
|
|
||||||
interface ProjectFlockFormProps {
|
interface ProjectFlockFormProps {
|
||||||
formType?: 'add' | 'edit' | 'detail';
|
formType?: 'add' | 'edit' | 'detail';
|
||||||
@@ -66,7 +66,6 @@ const ProjectFlockForm = ({
|
|||||||
|
|
||||||
const [projectFlockFormErrorMessage, setProjectFlockFormErrorMessage] =
|
const [projectFlockFormErrorMessage, setProjectFlockFormErrorMessage] =
|
||||||
useState('');
|
useState('');
|
||||||
const [formErrorList, setFormErrorList] = useState<string[]>([]);
|
|
||||||
const [selectedArea, setSelectedArea] = useState('');
|
const [selectedArea, setSelectedArea] = useState('');
|
||||||
const [selectedLocation, setSelectedLocation] = useState('');
|
const [selectedLocation, setSelectedLocation] = useState('');
|
||||||
const [selectedCategory, setSelectedCategory] = useState('');
|
const [selectedCategory, setSelectedCategory] = useState('');
|
||||||
@@ -642,16 +641,8 @@ const ProjectFlockForm = ({
|
|||||||
return !isNonstockAlreadyInBudgets;
|
return !isNonstockAlreadyInBudgets;
|
||||||
});
|
});
|
||||||
|
|
||||||
const handleValidateForm = async () => {
|
// ===== Formik Error List =====
|
||||||
const errors = await formik.validateForm();
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
|
|
||||||
if (Object.keys(errors).length > 0) {
|
|
||||||
// Parse and display errors
|
|
||||||
const errorMessages = getUniqueFormikErrors(errors);
|
|
||||||
setFormErrorList(errorMessages);
|
|
||||||
return; // Stop submission
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -712,11 +703,7 @@ const ProjectFlockForm = ({
|
|||||||
|
|
||||||
<form
|
<form
|
||||||
className='w-auto h-auto'
|
className='w-auto h-auto'
|
||||||
onSubmit={(e) => {
|
onSubmit={handleFormSubmit}
|
||||||
e.preventDefault();
|
|
||||||
handleValidateForm();
|
|
||||||
formik.handleSubmit(e);
|
|
||||||
}}
|
|
||||||
onReset={formik.handleReset}
|
onReset={formik.handleReset}
|
||||||
>
|
>
|
||||||
{/* Form Informasi Umum */}
|
{/* Form Informasi Umum */}
|
||||||
@@ -1082,13 +1069,7 @@ const ProjectFlockForm = ({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Error List Alert */}
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
{formErrorList.length > 0 && (
|
|
||||||
<AlertErrorList
|
|
||||||
formErrorList={formErrorList}
|
|
||||||
onClose={() => setFormErrorList([])}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className='flex flex-row justify-center gap-2 flex-wrap my-6 px-4'>
|
<div className='flex flex-row justify-center gap-2 flex-wrap my-6 px-4'>
|
||||||
{formType !== 'detail' && (
|
{formType !== 'detail' && (
|
||||||
|
|||||||
@@ -1737,16 +1737,16 @@ const RecordingForm = ({ type = 'add', initialValues }: RecordingFormProps) => {
|
|||||||
<td className='py-3 font-medium'>Egg Mass</td>
|
<td className='py-3 font-medium'>Egg Mass</td>
|
||||||
<td className='text-center py-3'>
|
<td className='text-center py-3'>
|
||||||
<span className='font-semibold'>
|
<span className='font-semibold'>
|
||||||
{initialValues.egg_mesh &&
|
{initialValues.egg_mass &&
|
||||||
initialValues.egg_mesh > 0
|
initialValues.egg_mass > 0
|
||||||
? formatNumber(initialValues.egg_mesh)
|
? formatNumber(initialValues.egg_mass)
|
||||||
: '-'}
|
: '-'}
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td className='text-center py-3 text-gray-600'>
|
<td className='text-center py-3 text-gray-600'>
|
||||||
{initialValues.egg_mesh_std &&
|
{initialValues.egg_mass_std &&
|
||||||
initialValues.egg_mesh_std > 0
|
initialValues.egg_mass_std > 0
|
||||||
? formatNumber(initialValues.egg_mesh_std)
|
? formatNumber(initialValues.egg_mass_std)
|
||||||
: '-'}
|
: '-'}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -1773,16 +1773,16 @@ const RecordingForm = ({ type = 'add', initialValues }: RecordingFormProps) => {
|
|||||||
<td className='py-3 font-medium'>Hen Day</td>
|
<td className='py-3 font-medium'>Hen Day</td>
|
||||||
<td className='text-center py-3'>
|
<td className='text-center py-3'>
|
||||||
<span className='font-semibold'>
|
<span className='font-semibold'>
|
||||||
{initialValues.hand_day &&
|
{initialValues.hen_day &&
|
||||||
initialValues.hand_day > 0
|
initialValues.hen_day > 0
|
||||||
? formatNumber(initialValues.hand_day)
|
? formatNumber(initialValues.hen_day)
|
||||||
: '-'}
|
: '-'}
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td className='text-center py-3 text-gray-600'>
|
<td className='text-center py-3 text-gray-600'>
|
||||||
{initialValues.hand_day_std !== undefined &&
|
{initialValues.hen_day_std !== undefined &&
|
||||||
initialValues.hand_day_std > 0
|
initialValues.hen_day_std > 0
|
||||||
? `${initialValues.hand_day_std}%`
|
? `${initialValues.hen_day_std}%`
|
||||||
: '-'}
|
: '-'}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -1790,16 +1790,16 @@ const RecordingForm = ({ type = 'add', initialValues }: RecordingFormProps) => {
|
|||||||
<td className='py-3 font-medium'>Hen House</td>
|
<td className='py-3 font-medium'>Hen House</td>
|
||||||
<td className='text-center py-3'>
|
<td className='text-center py-3'>
|
||||||
<span className='font-semibold'>
|
<span className='font-semibold'>
|
||||||
{initialValues.hand_house &&
|
{initialValues.hen_house &&
|
||||||
initialValues.hand_house > 0
|
initialValues.hen_house > 0
|
||||||
? formatNumber(initialValues.hand_house)
|
? formatNumber(initialValues.hen_house)
|
||||||
: '-'}
|
: '-'}
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td className='text-center py-3 text-gray-600'>
|
<td className='text-center py-3 text-gray-600'>
|
||||||
{initialValues.hand_house_std !== undefined &&
|
{initialValues.hen_house_std !== undefined &&
|
||||||
initialValues.hand_house_std > 0
|
initialValues.hen_house_std > 0
|
||||||
? `${initialValues.hand_house_std}%`
|
? `${initialValues.hen_house_std}%`
|
||||||
: '-'}
|
: '-'}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|||||||
@@ -41,6 +41,8 @@ import { cn } from '@/lib/helper';
|
|||||||
import { TransferToLayingApi } from '@/services/api/production/transfer-to-laying';
|
import { TransferToLayingApi } from '@/services/api/production/transfer-to-laying';
|
||||||
import { ProjectFlock } from '@/types/api/production/project-flock';
|
import { ProjectFlock } from '@/types/api/production/project-flock';
|
||||||
import { TRANSFER_TO_LAYING_APPROVAL_LINE } from '@/config/approval-line';
|
import { TRANSFER_TO_LAYING_APPROVAL_LINE } from '@/config/approval-line';
|
||||||
|
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||||
|
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||||
|
|
||||||
interface TransferToLayingFormProps {
|
interface TransferToLayingFormProps {
|
||||||
type?: 'add' | 'edit' | 'detail';
|
type?: 'add' | 'edit' | 'detail';
|
||||||
@@ -160,6 +162,7 @@ const TransferToLayingForm = ({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const { setValues: formikSetValues, values: formikValues } = formik;
|
const { setValues: formikSetValues, values: formikValues } = formik;
|
||||||
|
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||||
const {
|
const {
|
||||||
flockSourceKandangs: flockSourceKandangsValue,
|
flockSourceKandangs: flockSourceKandangsValue,
|
||||||
flockDestinationKandangs: flockDestinationKandangsValue,
|
flockDestinationKandangs: flockDestinationKandangsValue,
|
||||||
@@ -539,7 +542,7 @@ const TransferToLayingForm = ({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<form
|
<form
|
||||||
onSubmit={formik.handleSubmit}
|
onSubmit={handleFormSubmit}
|
||||||
onReset={formik.handleReset}
|
onReset={formik.handleReset}
|
||||||
className='w-full flex flex-col gap-6'
|
className='w-full flex flex-col gap-6'
|
||||||
>
|
>
|
||||||
@@ -777,6 +780,8 @@ const TransferToLayingForm = ({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||||
|
|
||||||
{formErrorMessage && (
|
{formErrorMessage && (
|
||||||
<div role='alert' className='alert alert-error w-full'>
|
<div role='alert' className='alert alert-error w-full'>
|
||||||
<Icon
|
<Icon
|
||||||
@@ -852,7 +857,7 @@ const TransferToLayingForm = ({
|
|||||||
type='submit'
|
type='submit'
|
||||||
color='primary'
|
color='primary'
|
||||||
isLoading={formik.isSubmitting}
|
isLoading={formik.isSubmitting}
|
||||||
disabled={!formik.isValid || formik.isSubmitting}
|
disabled={formik.isSubmitting}
|
||||||
className='px-4'
|
className='px-4'
|
||||||
>
|
>
|
||||||
Submit
|
Submit
|
||||||
|
|||||||
@@ -31,7 +31,10 @@ import { MarketingReportApi } from '@/services/api/report/marketing-report';
|
|||||||
import { MARKETING_TYPE_OPTIONS } from '@/config/constant';
|
import { MARKETING_TYPE_OPTIONS } from '@/config/constant';
|
||||||
import { httpClient } from '@/services/http/client';
|
import { httpClient } from '@/services/http/client';
|
||||||
import { BaseApiResponse } from '@/types/api/api-general';
|
import { BaseApiResponse } from '@/types/api/api-general';
|
||||||
import { DailyMarketingReport } from '@/types/api/report/marketing';
|
import {
|
||||||
|
DailyMarketingReport,
|
||||||
|
DailyMarketingReportResponse,
|
||||||
|
} from '@/types/api/report/marketing';
|
||||||
import { isResponseError } from '@/lib/api-helper';
|
import { isResponseError } from '@/lib/api-helper';
|
||||||
|
|
||||||
const DailyMarketingReportContent = () => {
|
const DailyMarketingReportContent = () => {
|
||||||
@@ -191,9 +194,10 @@ const DailyMarketingReportContent = () => {
|
|||||||
const queryString = `?${params.toString()}`;
|
const queryString = `?${params.toString()}`;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const dailyMarketingsReport = await httpClient<
|
const dailyMarketingsReport =
|
||||||
BaseApiResponse<DailyMarketingReport>
|
await httpClient<DailyMarketingReportResponse>(
|
||||||
>(`${MarketingReportApi.basePath}${queryString}`);
|
`${MarketingReportApi.basePath}${queryString}`
|
||||||
|
);
|
||||||
|
|
||||||
if (isResponseError(dailyMarketingsReport)) {
|
if (isResponseError(dailyMarketingsReport)) {
|
||||||
toast.error('Gagal melakukan export penjualan harian! Coba lagi.');
|
toast.error('Gagal melakukan export penjualan harian! Coba lagi.');
|
||||||
@@ -202,7 +206,10 @@ const DailyMarketingReportContent = () => {
|
|||||||
|
|
||||||
const openPdf = async () => {
|
const openPdf = async () => {
|
||||||
const dailyMarketingReportPdfBlob = await pdf(
|
const dailyMarketingReportPdfBlob = await pdf(
|
||||||
<DailyMarketingReportPDF data={dailyMarketingsReport.data} />
|
<DailyMarketingReportPDF
|
||||||
|
data={dailyMarketingsReport.data}
|
||||||
|
total={dailyMarketingsReport.total}
|
||||||
|
/>
|
||||||
).toBlob();
|
).toBlob();
|
||||||
|
|
||||||
const dailyMarketingReportPdfUrl = URL.createObjectURL(
|
const dailyMarketingReportPdfUrl = URL.createObjectURL(
|
||||||
@@ -213,7 +220,10 @@ const DailyMarketingReportContent = () => {
|
|||||||
|
|
||||||
const downloadPdf = async () => {
|
const downloadPdf = async () => {
|
||||||
const blob = await pdf(
|
const blob = await pdf(
|
||||||
<DailyMarketingReportPDF data={dailyMarketingsReport.data} />
|
<DailyMarketingReportPDF
|
||||||
|
data={dailyMarketingsReport.data}
|
||||||
|
total={dailyMarketingsReport.total}
|
||||||
|
/>
|
||||||
).toBlob();
|
).toBlob();
|
||||||
const url = URL.createObjectURL(blob);
|
const url = URL.createObjectURL(blob);
|
||||||
|
|
||||||
|
|||||||
@@ -9,11 +9,15 @@ import {
|
|||||||
View,
|
View,
|
||||||
} from '@react-pdf/renderer';
|
} from '@react-pdf/renderer';
|
||||||
|
|
||||||
import { DailyMarketingReport } from '@/types/api/report/marketing';
|
import {
|
||||||
|
DailyMarketingReport,
|
||||||
|
SalesSummary,
|
||||||
|
} from '@/types/api/report/marketing';
|
||||||
import { formatCurrency, formatDate, formatNumber } from '@/lib/helper';
|
import { formatCurrency, formatDate, formatNumber } from '@/lib/helper';
|
||||||
|
|
||||||
interface DailyMarketingReportPDFProps {
|
interface DailyMarketingReportPDFProps {
|
||||||
data?: DailyMarketingReport;
|
data?: DailyMarketingReport;
|
||||||
|
total?: SalesSummary;
|
||||||
}
|
}
|
||||||
|
|
||||||
const DailyMarketingReportPDFStyle = StyleSheet.create({
|
const DailyMarketingReportPDFStyle = StyleSheet.create({
|
||||||
@@ -267,9 +271,12 @@ const DailyMarketingReportPDFStyle = StyleSheet.create({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const DailyMarketingReportPDF = ({ data }: DailyMarketingReportPDFProps) => {
|
const DailyMarketingReportPDF = ({
|
||||||
const rows = data?.rows || [];
|
data,
|
||||||
const summary = data?.summary;
|
total,
|
||||||
|
}: DailyMarketingReportPDFProps) => {
|
||||||
|
const rows = data || [];
|
||||||
|
const summary = total;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Document>
|
<Document>
|
||||||
@@ -409,7 +416,7 @@ const DailyMarketingReportPDF = ({ data }: DailyMarketingReportPDFProps) => {
|
|||||||
</View>
|
</View>
|
||||||
<View style={DailyMarketingReportPDFStyle.colDoDate}>
|
<View style={DailyMarketingReportPDFStyle.colDoDate}>
|
||||||
<Text style={DailyMarketingReportPDFStyle.cellText}>
|
<Text style={DailyMarketingReportPDFStyle.cellText}>
|
||||||
{formatDate(row.do_date, 'DD/MM/YYYY')}
|
{formatDate(row.realization_date, 'DD/MM/YYYY')}
|
||||||
</Text>
|
</Text>
|
||||||
</View>
|
</View>
|
||||||
<View style={DailyMarketingReportPDFStyle.colAging}>
|
<View style={DailyMarketingReportPDFStyle.colAging}>
|
||||||
@@ -429,7 +436,7 @@ const DailyMarketingReportPDF = ({ data }: DailyMarketingReportPDFProps) => {
|
|||||||
</View>
|
</View>
|
||||||
<View style={DailyMarketingReportPDFStyle.colSales}>
|
<View style={DailyMarketingReportPDFStyle.colSales}>
|
||||||
<Text style={DailyMarketingReportPDFStyle.cellText}>
|
<Text style={DailyMarketingReportPDFStyle.cellText}>
|
||||||
{row.sales}
|
{row.sales.name}
|
||||||
</Text>
|
</Text>
|
||||||
</View>
|
</View>
|
||||||
<View style={DailyMarketingReportPDFStyle.colProduct}>
|
<View style={DailyMarketingReportPDFStyle.colProduct}>
|
||||||
@@ -518,6 +525,19 @@ const DailyMarketingReportPDF = ({ data }: DailyMarketingReportPDFProps) => {
|
|||||||
{formatCurrency(summary?.total_sales_amount ?? 0)}
|
{formatCurrency(summary?.total_sales_amount ?? 0)}
|
||||||
</Text>
|
</Text>
|
||||||
</View>
|
</View>
|
||||||
|
<View
|
||||||
|
style={[
|
||||||
|
DailyMarketingReportPDFStyle.summaryRow,
|
||||||
|
{ borderBottomWidth: 0 },
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<Text style={DailyMarketingReportPDFStyle.summaryLabel}>
|
||||||
|
Total HPP Per KG:
|
||||||
|
</Text>
|
||||||
|
<Text style={DailyMarketingReportPDFStyle.summaryValue}>
|
||||||
|
{formatCurrency(summary?.total_hpp_price_per_kg ?? 0)}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
<View
|
<View
|
||||||
style={[
|
style={[
|
||||||
DailyMarketingReportPDFStyle.summaryRow,
|
DailyMarketingReportPDFStyle.summaryRow,
|
||||||
|
|||||||
@@ -60,9 +60,10 @@ const DailyMarketingsTable = ({
|
|||||||
footer: 'Total',
|
footer: 'Total',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: 'do_date',
|
accessorKey: 'realization_date',
|
||||||
header: 'Tanggal DO',
|
header: 'Tanggal Realisasi',
|
||||||
cell: (props) => formatDate(props.row.original.do_date, 'DD-MMM-YYYY'),
|
cell: (props) =>
|
||||||
|
formatDate(props.row.original.realization_date, 'DD-MMM-YYYY'),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: 'aging_days',
|
accessorKey: 'aging_days',
|
||||||
@@ -84,6 +85,7 @@ const DailyMarketingsTable = ({
|
|||||||
{
|
{
|
||||||
accessorKey: 'sales',
|
accessorKey: 'sales',
|
||||||
header: 'Sales/Marketing',
|
header: 'Sales/Marketing',
|
||||||
|
cell: (props) => props.row.original.sales.name,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: 'vehicle_number',
|
accessorKey: 'vehicle_number',
|
||||||
@@ -106,10 +108,10 @@ const DailyMarketingsTable = ({
|
|||||||
cell: (props) => formatNumber(props.row.original.qty),
|
cell: (props) => formatNumber(props.row.original.qty),
|
||||||
footer: () => {
|
footer: () => {
|
||||||
const totalQty = isResponseSuccess(dailyMarketings)
|
const totalQty = isResponseSuccess(dailyMarketings)
|
||||||
? dailyMarketings.data.summary.total_qty
|
? dailyMarketings?.total?.total_qty
|
||||||
: 0;
|
: 0;
|
||||||
|
|
||||||
return formatNumber(totalQty);
|
return totalQty ? formatNumber(totalQty) : '-';
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -123,10 +125,10 @@ const DailyMarketingsTable = ({
|
|||||||
cell: (props) => formatNumber(props.row.original.total_weight_kg),
|
cell: (props) => formatNumber(props.row.original.total_weight_kg),
|
||||||
footer: () => {
|
footer: () => {
|
||||||
const totalWeightKg = isResponseSuccess(dailyMarketings)
|
const totalWeightKg = isResponseSuccess(dailyMarketings)
|
||||||
? dailyMarketings.data.summary.total_weight_kg
|
? dailyMarketings?.total?.total_weight_kg
|
||||||
: 0;
|
: 0;
|
||||||
|
|
||||||
return formatNumber(totalWeightKg);
|
return totalWeightKg ? formatNumber(totalWeightKg) : '-';
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -138,6 +140,13 @@ const DailyMarketingsTable = ({
|
|||||||
accessorKey: 'hpp_price_per_kg',
|
accessorKey: 'hpp_price_per_kg',
|
||||||
header: 'HPP (Rp)',
|
header: 'HPP (Rp)',
|
||||||
cell: (props) => formatCurrency(props.row.original.hpp_price_per_kg),
|
cell: (props) => formatCurrency(props.row.original.hpp_price_per_kg),
|
||||||
|
footer: () => {
|
||||||
|
const totalHppPricePerKg = isResponseSuccess(dailyMarketings)
|
||||||
|
? dailyMarketings?.total?.total_hpp_price_per_kg
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
return totalHppPricePerKg ? formatCurrency(totalHppPricePerKg) : '-';
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: 'sales_amount',
|
accessorKey: 'sales_amount',
|
||||||
@@ -145,10 +154,10 @@ const DailyMarketingsTable = ({
|
|||||||
cell: (props) => formatCurrency(props.row.original.sales_amount),
|
cell: (props) => formatCurrency(props.row.original.sales_amount),
|
||||||
footer: () => {
|
footer: () => {
|
||||||
const totalSalesAmount = isResponseSuccess(dailyMarketings)
|
const totalSalesAmount = isResponseSuccess(dailyMarketings)
|
||||||
? dailyMarketings.data.summary.total_sales_amount
|
? dailyMarketings?.total?.total_sales_amount
|
||||||
: 0;
|
: 0;
|
||||||
|
|
||||||
return formatCurrency(totalSalesAmount);
|
return totalSalesAmount ? formatCurrency(totalSalesAmount) : '-';
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
@@ -167,7 +176,7 @@ const DailyMarketingsTable = ({
|
|||||||
if (!open) {
|
if (!open) {
|
||||||
setOpen(
|
setOpen(
|
||||||
isResponseSuccess(dailyMarketings)
|
isResponseSuccess(dailyMarketings)
|
||||||
? dailyMarketings.data.rows.length > 0
|
? dailyMarketings.data.length > 0
|
||||||
: false
|
: false
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -215,9 +224,7 @@ const DailyMarketingsTable = ({
|
|||||||
|
|
||||||
<Table<DailyMarketingRow>
|
<Table<DailyMarketingRow>
|
||||||
data={
|
data={
|
||||||
isResponseSuccess(dailyMarketings)
|
isResponseSuccess(dailyMarketings) ? dailyMarketings?.data : []
|
||||||
? dailyMarketings?.data.rows
|
|
||||||
: []
|
|
||||||
}
|
}
|
||||||
columns={dailyMarketingColumns}
|
columns={dailyMarketingColumns}
|
||||||
pageSize={pageSize}
|
pageSize={pageSize}
|
||||||
@@ -242,7 +249,7 @@ const DailyMarketingsTable = ({
|
|||||||
containerClassName: cn({
|
containerClassName: cn({
|
||||||
'w-full mb-20':
|
'w-full mb-20':
|
||||||
isResponseSuccess(dailyMarketings) &&
|
isResponseSuccess(dailyMarketings) &&
|
||||||
dailyMarketings?.data?.rows.length === 0,
|
dailyMarketings?.data?.length === 0,
|
||||||
}),
|
}),
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import Tabs from '@/components/Tabs';
|
||||||
|
import CustomerPaymentTab from '@/components/pages/report/finance/tab/CustomerPaymentTab';
|
||||||
|
import DebtSupplierTab from '@/components/pages/report/finance/tab/DebtSupplierTab';
|
||||||
|
|
||||||
|
const FinanceTabs = () => {
|
||||||
|
const tabs = [
|
||||||
|
{
|
||||||
|
id: '1',
|
||||||
|
label: 'Kontrol Pembayaran Customer',
|
||||||
|
|
||||||
|
content: <CustomerPaymentTab />,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '2',
|
||||||
|
label: 'Rekapitulasi Hutang Ke Supplier',
|
||||||
|
|
||||||
|
content: <DebtSupplierTab />,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className='w-full p-4'>
|
||||||
|
<Tabs tabs={tabs} variant='lifted' />
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default FinanceTabs;
|
||||||
@@ -0,0 +1,424 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import {
|
||||||
|
Page,
|
||||||
|
Text,
|
||||||
|
View,
|
||||||
|
Document,
|
||||||
|
StyleSheet,
|
||||||
|
Font,
|
||||||
|
pdf,
|
||||||
|
} from '@react-pdf/renderer';
|
||||||
|
|
||||||
|
import { formatDate, formatCurrency, formatNumber } from '@/lib/helper';
|
||||||
|
import { CustomerPaymentReport } from '@/types/api/report/customer-payment';
|
||||||
|
|
||||||
|
Font.register({
|
||||||
|
family: 'Helvetica',
|
||||||
|
src: 'helvetica',
|
||||||
|
});
|
||||||
|
|
||||||
|
const pdfStyles = StyleSheet.create({
|
||||||
|
page: {
|
||||||
|
fontSize: 10,
|
||||||
|
fontFamily: 'Helvetica',
|
||||||
|
padding: 20,
|
||||||
|
backgroundColor: '#FFFFFF',
|
||||||
|
},
|
||||||
|
titleSection: {
|
||||||
|
marginBottom: 10,
|
||||||
|
},
|
||||||
|
mainTitle: {
|
||||||
|
fontSize: 14,
|
||||||
|
fontWeight: 'bold',
|
||||||
|
marginBottom: 5,
|
||||||
|
color: '#1f74bf',
|
||||||
|
},
|
||||||
|
supplierTitle: {
|
||||||
|
fontSize: 12,
|
||||||
|
fontWeight: 'bold',
|
||||||
|
marginBottom: 8,
|
||||||
|
color: '#1f74bf',
|
||||||
|
},
|
||||||
|
supplierInfo: {
|
||||||
|
fontSize: 9,
|
||||||
|
marginBottom: 5,
|
||||||
|
color: '#333333',
|
||||||
|
},
|
||||||
|
table: {
|
||||||
|
borderWidth: 1,
|
||||||
|
borderColor: '#000000',
|
||||||
|
marginBottom: 15,
|
||||||
|
},
|
||||||
|
tableRow: {
|
||||||
|
flexDirection: 'row',
|
||||||
|
},
|
||||||
|
tableHeader: {
|
||||||
|
backgroundColor: '#F5F5F5',
|
||||||
|
},
|
||||||
|
tableCell: {
|
||||||
|
flex: 1,
|
||||||
|
borderRightWidth: 1,
|
||||||
|
borderRightColor: '#000000',
|
||||||
|
borderRightStyle: 'solid',
|
||||||
|
padding: 4,
|
||||||
|
fontSize: 7,
|
||||||
|
textAlign: 'left',
|
||||||
|
},
|
||||||
|
tableCellNo: {
|
||||||
|
flex: 0.5,
|
||||||
|
borderRightWidth: 1,
|
||||||
|
borderRightColor: '#000000',
|
||||||
|
borderRightStyle: 'solid',
|
||||||
|
padding: 4,
|
||||||
|
fontSize: 7,
|
||||||
|
textAlign: 'center',
|
||||||
|
},
|
||||||
|
tableCellLast: {
|
||||||
|
flex: 1,
|
||||||
|
padding: 4,
|
||||||
|
fontSize: 7,
|
||||||
|
},
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
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',
|
||||||
|
},
|
||||||
|
tableBorderBottom: {
|
||||||
|
borderBottomWidth: 1,
|
||||||
|
borderBottomColor: '#000000',
|
||||||
|
borderBottomStyle: 'solid',
|
||||||
|
},
|
||||||
|
summaryRow: {
|
||||||
|
backgroundColor: '#F0F0F0',
|
||||||
|
fontWeight: 'bold',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
interface CustomerPaymentExportPDFParams {
|
||||||
|
data: CustomerPaymentReport[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const createPDFDocument = (params: CustomerPaymentExportPDFParams) => {
|
||||||
|
return (
|
||||||
|
<Document>
|
||||||
|
{params.data.map((customerReport, customerIndex) => (
|
||||||
|
<Page
|
||||||
|
key={customerIndex}
|
||||||
|
size='A4'
|
||||||
|
orientation='landscape'
|
||||||
|
style={pdfStyles.page}
|
||||||
|
>
|
||||||
|
{/* Title and Customer Info */}
|
||||||
|
<View style={pdfStyles.titleSection}>
|
||||||
|
<Text style={pdfStyles.mainTitle}>
|
||||||
|
Laporan > Kontrol Pembayaran Customer
|
||||||
|
</Text>
|
||||||
|
<Text style={pdfStyles.supplierTitle}>
|
||||||
|
{customerReport.customer.name}
|
||||||
|
</Text>
|
||||||
|
<Text style={pdfStyles.supplierInfo}>
|
||||||
|
{customerReport.customer.address || ''}
|
||||||
|
</Text>
|
||||||
|
{customerReport.summary && (
|
||||||
|
<Text style={pdfStyles.supplierInfo}>
|
||||||
|
Total Saldo Piutang:{' '}
|
||||||
|
{formatCurrency(
|
||||||
|
customerReport.summary.total_accounts_receivable
|
||||||
|
)}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</View>
|
||||||
|
|
||||||
|
{/* Table */}
|
||||||
|
<View style={pdfStyles.table}>
|
||||||
|
{/* Table Header */}
|
||||||
|
<View style={[pdfStyles.tableRow, pdfStyles.tableHeader]}>
|
||||||
|
<View style={[pdfStyles.tableCellHeader, { flex: 0.5 }]}>
|
||||||
|
<Text>No</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeader, { flex: 1.2 }]}>
|
||||||
|
<Text>Tgl DO/Bayar</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeader, { flex: 1.2 }]}>
|
||||||
|
<Text>Tgl Realisasi</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeader, { flex: 0.8 }]}>
|
||||||
|
<Text>Aging</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
|
||||||
|
<Text>Referensi</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeader, { flex: 1.2 }]}>
|
||||||
|
<Text>No. Polisi</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeaderRight, { flex: 0.8 }]}>
|
||||||
|
<Text>Qty</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeaderRight, { flex: 1 }]}>
|
||||||
|
<Text>Berat (Kg)</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeaderRight, { flex: 0.8 }]}>
|
||||||
|
<Text>AVG</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
|
||||||
|
<Text>Harga Awal</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeaderRight, { flex: 1 }]}>
|
||||||
|
<Text>CN</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
|
||||||
|
<Text>Harga Akhir</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeaderRight, { flex: 0.8 }]}>
|
||||||
|
<Text>PPN (%)</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
|
||||||
|
<Text>Total</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
|
||||||
|
<Text>Pembayaran</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeaderRight, { flex: 1.2 }]}>
|
||||||
|
<Text>Saldo Piutang</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeader, { flex: 1.5 }]}>
|
||||||
|
<Text>Ket</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
|
||||||
|
<Text>Pengambilan</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeader, { flex: 1.5 }]}>
|
||||||
|
<Text>Sales</Text>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
|
||||||
|
{/* Table Body */}
|
||||||
|
{customerReport.rows.map((item, index) => (
|
||||||
|
<View
|
||||||
|
key={index}
|
||||||
|
style={[
|
||||||
|
pdfStyles.tableRow,
|
||||||
|
index < customerReport.rows.length - 1
|
||||||
|
? pdfStyles.tableBorderBottom
|
||||||
|
: {},
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<View style={[pdfStyles.tableCellNo, { flex: 0.5 }]}>
|
||||||
|
<Text>{index + 1}</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellCenter, { flex: 1.2 }]}>
|
||||||
|
<Text>
|
||||||
|
{item.do_date ? formatDate(item.do_date, 'DD MMM YY') : '-'}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellCenter, { flex: 1.2 }]}>
|
||||||
|
<Text>
|
||||||
|
{item.realization_date
|
||||||
|
? formatDate(item.realization_date, 'DD MMM YY')
|
||||||
|
: '-'}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellCenter, { flex: 0.8 }]}>
|
||||||
|
<Text>
|
||||||
|
{item.aging_day ? formatNumber(item.aging_day) : '-'} hari
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
|
||||||
|
<Text>{item.reference || '-'}</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1.2 }]}>
|
||||||
|
<Text>{item.vehicle_plate || '-'}</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellRight, { flex: 0.8 }]}>
|
||||||
|
<Text>{formatNumber(item.qty)}</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellRight, { flex: 1 }]}>
|
||||||
|
<Text>{formatNumber(item.weight)}</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellRight, { flex: 0.8 }]}>
|
||||||
|
<Text>{formatNumber(item.average_weight)}</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
|
||||||
|
<Text>{formatCurrency(item.price)}</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellRight, { flex: 1 }]}>
|
||||||
|
<Text>{formatCurrency(item.credit_note)}</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
|
||||||
|
<Text>{formatCurrency(item.final_price)}</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellRight, { flex: 0.8 }]}>
|
||||||
|
<Text>{formatNumber(item.ppn)}%</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
|
||||||
|
<Text>{formatCurrency(item.total)}</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
|
||||||
|
<Text>{formatCurrency(item.payment)}</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
|
||||||
|
<Text>{formatCurrency(item.accounts_receivable)}</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
|
||||||
|
<Text>{item.notes || '-'}</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
|
||||||
|
<Text>{item.pickup_info || '-'}</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
|
||||||
|
<Text>{item.sales_marketing || '-'}</Text>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{/* Summary Row */}
|
||||||
|
{customerReport.summary && (
|
||||||
|
<View style={[pdfStyles.tableRow, pdfStyles.summaryRow]}>
|
||||||
|
<View style={[pdfStyles.tableCellNo, { flex: 0.5 }]}>
|
||||||
|
<Text>Total</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1.2 }]}>
|
||||||
|
<Text></Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1.2 }]}>
|
||||||
|
<Text></Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 0.8 }]}>
|
||||||
|
<Text></Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
|
||||||
|
<Text></Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1.2 }]}>
|
||||||
|
<Text></Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellRight, { flex: 0.8 }]}>
|
||||||
|
<Text>{formatNumber(customerReport.summary.total_qty)}</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellRight, { flex: 1 }]}>
|
||||||
|
<Text>
|
||||||
|
{formatNumber(customerReport.summary.total_weight)}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellRight, { flex: 0.8 }]}>
|
||||||
|
<Text></Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
|
||||||
|
<Text>
|
||||||
|
{formatCurrency(
|
||||||
|
customerReport.summary.total_initial_amount
|
||||||
|
)}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellRight, { flex: 1 }]}>
|
||||||
|
<Text>
|
||||||
|
{formatCurrency(customerReport.summary.total_credit_note)}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
|
||||||
|
<Text>
|
||||||
|
{formatCurrency(customerReport.summary.total_final_amount)}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellRight, { flex: 0.8 }]}>
|
||||||
|
<Text></Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
|
||||||
|
<Text>
|
||||||
|
{formatCurrency(customerReport.summary.total_grand_amount)}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
|
||||||
|
<Text>
|
||||||
|
{formatCurrency(customerReport.summary.total_payment)}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellRight, { flex: 1.2 }]}>
|
||||||
|
<Text>
|
||||||
|
{formatCurrency(
|
||||||
|
customerReport.summary.total_accounts_receivable
|
||||||
|
)}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
|
||||||
|
<Text></Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
|
||||||
|
<Text></Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellLast, { flex: 1.5 }]}>
|
||||||
|
<Text></Text>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
|
</View>
|
||||||
|
</Page>
|
||||||
|
))}
|
||||||
|
</Document>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const generateCustomerPaymentPDF = async (
|
||||||
|
params: CustomerPaymentExportPDFParams
|
||||||
|
): Promise<void> => {
|
||||||
|
const PDFDocument = createPDFDocument(params);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const blob = await pdf(PDFDocument).toBlob();
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.href = url;
|
||||||
|
link.download = `laporan-kontrol-pembayaran-customer-${formatDate(new Date(), 'YYYY-MM-DD-HHmm')}.pdf`;
|
||||||
|
|
||||||
|
document.body.appendChild(link);
|
||||||
|
link.click();
|
||||||
|
document.body.removeChild(link);
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
} catch (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import * as XLSX from 'xlsx';
|
||||||
|
import { formatDate, formatCurrency, formatNumber } from '@/lib/helper';
|
||||||
|
import { CustomerPaymentReport } from '@/types/api/report/customer-payment';
|
||||||
|
|
||||||
|
interface CustomerPaymentExportExcelParams {
|
||||||
|
data: CustomerPaymentReport[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const generateCustomerPaymentExcel = (
|
||||||
|
params: CustomerPaymentExportExcelParams
|
||||||
|
): void => {
|
||||||
|
if (!params.data || params.data.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const workbook = XLSX.utils.book_new();
|
||||||
|
|
||||||
|
params.data.forEach((customerReport) => {
|
||||||
|
const customerData = customerReport.rows;
|
||||||
|
const customerName = customerReport.customer.name || 'Unknown Customer';
|
||||||
|
|
||||||
|
const excelData: { [key: string]: string | number }[] = customerData.map(
|
||||||
|
(item, index) => ({
|
||||||
|
No: index + 1,
|
||||||
|
'Tanggal DO/Bayar': item.do_date
|
||||||
|
? formatDate(item.do_date, 'DD MMM YYYY')
|
||||||
|
: '',
|
||||||
|
'Tanggal Realisasi': item.realization_date
|
||||||
|
? formatDate(item.realization_date, 'DD MMM YYYY')
|
||||||
|
: '',
|
||||||
|
Aging: formatNumber(item.aging_day || 0),
|
||||||
|
Referensi: item.reference || '',
|
||||||
|
'Nomor Polisi': Array.isArray(item.vehicle_plate)
|
||||||
|
? item.vehicle_plate.join(', ')
|
||||||
|
: '',
|
||||||
|
'Ekor/Qty': formatNumber(item.qty || 0),
|
||||||
|
'Berat (Kg)': formatNumber(item.weight || 0),
|
||||||
|
AVG: formatNumber(item.average_weight || 0),
|
||||||
|
'Harga Awal': formatCurrency(item.price || 0),
|
||||||
|
CN: formatCurrency(item.credit_note || 0),
|
||||||
|
'Harga Akhir': formatCurrency(item.final_price || 0),
|
||||||
|
'PPN (%)': formatNumber(item.ppn || 0),
|
||||||
|
Total: formatCurrency(item.total || 0),
|
||||||
|
Pembayaran: formatCurrency(item.payment || 0),
|
||||||
|
'Saldo Piutang': formatCurrency(item.accounts_receivable || 0),
|
||||||
|
Keterangan: item.notes || '',
|
||||||
|
Pengambilan: item.pickup_info || '',
|
||||||
|
'Sales/Marketing': item.sales_marketing || '',
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
if (customerReport.summary) {
|
||||||
|
excelData.push({
|
||||||
|
No: 'Total',
|
||||||
|
'Tanggal DO/Bayar': '',
|
||||||
|
'Tanggal Realisasi': '',
|
||||||
|
Aging: '',
|
||||||
|
Referensi: '',
|
||||||
|
'Nomor Polisi': '',
|
||||||
|
'Ekor/Qty': formatNumber(customerReport.summary.total_qty || 0),
|
||||||
|
'Berat (Kg)': formatNumber(customerReport.summary.total_weight || 0),
|
||||||
|
AVG: '',
|
||||||
|
'Harga Awal': formatCurrency(
|
||||||
|
customerReport.summary.total_initial_amount || 0
|
||||||
|
),
|
||||||
|
CN: formatCurrency(customerReport.summary.total_credit_note || 0),
|
||||||
|
'Harga Akhir': formatCurrency(
|
||||||
|
customerReport.summary.total_final_amount || 0
|
||||||
|
),
|
||||||
|
'PPN (%)': '',
|
||||||
|
Total: formatCurrency(customerReport.summary.total_grand_amount || 0),
|
||||||
|
Pembayaran: formatCurrency(customerReport.summary.total_payment || 0),
|
||||||
|
'Saldo Piutang': formatCurrency(
|
||||||
|
customerReport.summary.total_accounts_receivable || 0
|
||||||
|
),
|
||||||
|
Keterangan: '',
|
||||||
|
Pengambilan: '',
|
||||||
|
'Sales/Marketing': '',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const worksheet = XLSX.utils.json_to_sheet(excelData);
|
||||||
|
|
||||||
|
const colWidths = [
|
||||||
|
{ wch: 5 }, // No
|
||||||
|
{ wch: 15 }, // Tanggal DO/Bayar
|
||||||
|
{ wch: 15 }, // Tanggal Realisasi
|
||||||
|
{ wch: 8 }, // Aging
|
||||||
|
{ wch: 12 }, // Referensi
|
||||||
|
{ wch: 15 }, // Nomor Polisi
|
||||||
|
{ wch: 10 }, // Ekor/Qty
|
||||||
|
{ wch: 12 }, // Berat
|
||||||
|
{ wch: 10 }, // AVG
|
||||||
|
{ wch: 15 }, // Harga Awal
|
||||||
|
{ wch: 10 }, // CN
|
||||||
|
{ wch: 15 }, // Harga Akhir
|
||||||
|
{ wch: 10 }, // PPN
|
||||||
|
{ wch: 15 }, // Total
|
||||||
|
{ wch: 15 }, // Pembayaran
|
||||||
|
{ wch: 15 }, // Saldo Piutang
|
||||||
|
{ wch: 20 }, // Keterangan
|
||||||
|
{ wch: 15 }, // Pengambilan
|
||||||
|
{ wch: 20 }, // Sales/Marketing
|
||||||
|
];
|
||||||
|
worksheet['!cols'] = colWidths;
|
||||||
|
|
||||||
|
const sheetName =
|
||||||
|
customerName.length > 31 ? customerName.substring(0, 31) : customerName;
|
||||||
|
XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
|
||||||
|
});
|
||||||
|
|
||||||
|
const filename = `laporan-kontrol-pembayaran-customer-dicetak-pada-${formatDate(new Date(), 'YYYY-MM-DD-HHmm')}.xlsx`;
|
||||||
|
|
||||||
|
XLSX.writeFile(workbook, filename);
|
||||||
|
};
|
||||||
@@ -0,0 +1,423 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import {
|
||||||
|
Page,
|
||||||
|
Text,
|
||||||
|
View,
|
||||||
|
Document,
|
||||||
|
StyleSheet,
|
||||||
|
Font,
|
||||||
|
pdf,
|
||||||
|
} from '@react-pdf/renderer';
|
||||||
|
|
||||||
|
import { formatDate, formatCurrency, formatNumber } from '@/lib/helper';
|
||||||
|
import { DebtSupplier } from '@/types/api/report/debt-supplier';
|
||||||
|
|
||||||
|
Font.register({
|
||||||
|
family: 'Helvetica',
|
||||||
|
src: 'helvetica',
|
||||||
|
});
|
||||||
|
|
||||||
|
const pdfStyles = StyleSheet.create({
|
||||||
|
page: {
|
||||||
|
fontSize: 10,
|
||||||
|
fontFamily: 'Helvetica',
|
||||||
|
padding: 20,
|
||||||
|
backgroundColor: '#FFFFFF',
|
||||||
|
},
|
||||||
|
titleSection: {
|
||||||
|
marginBottom: 10,
|
||||||
|
},
|
||||||
|
mainTitle: {
|
||||||
|
fontSize: 14,
|
||||||
|
fontWeight: 'bold',
|
||||||
|
marginBottom: 5,
|
||||||
|
color: '#1f74bf',
|
||||||
|
},
|
||||||
|
supplierTitle: {
|
||||||
|
fontSize: 12,
|
||||||
|
fontWeight: 'bold',
|
||||||
|
marginBottom: 8,
|
||||||
|
color: '#1f74bf',
|
||||||
|
},
|
||||||
|
supplierInfo: {
|
||||||
|
fontSize: 9,
|
||||||
|
marginBottom: 5,
|
||||||
|
color: '#333333',
|
||||||
|
},
|
||||||
|
table: {
|
||||||
|
borderWidth: 1,
|
||||||
|
borderColor: '#000000',
|
||||||
|
marginBottom: 15,
|
||||||
|
},
|
||||||
|
tableRow: {
|
||||||
|
flexDirection: 'row',
|
||||||
|
},
|
||||||
|
tableHeader: {
|
||||||
|
backgroundColor: '#F5F5F5',
|
||||||
|
},
|
||||||
|
tableCell: {
|
||||||
|
flex: 1,
|
||||||
|
borderRightWidth: 1,
|
||||||
|
borderRightColor: '#000000',
|
||||||
|
borderRightStyle: 'solid',
|
||||||
|
padding: 4,
|
||||||
|
fontSize: 7,
|
||||||
|
textAlign: 'left',
|
||||||
|
},
|
||||||
|
tableCellNo: {
|
||||||
|
flex: 0.5,
|
||||||
|
borderRightWidth: 1,
|
||||||
|
borderRightColor: '#000000',
|
||||||
|
borderRightStyle: 'solid',
|
||||||
|
padding: 4,
|
||||||
|
fontSize: 7,
|
||||||
|
textAlign: 'center',
|
||||||
|
},
|
||||||
|
tableCellLast: {
|
||||||
|
flex: 1,
|
||||||
|
padding: 4,
|
||||||
|
fontSize: 7,
|
||||||
|
},
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
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',
|
||||||
|
},
|
||||||
|
tableBorderBottom: {
|
||||||
|
borderBottomWidth: 1,
|
||||||
|
borderBottomColor: '#000000',
|
||||||
|
borderBottomStyle: 'solid',
|
||||||
|
},
|
||||||
|
summaryRow: {
|
||||||
|
backgroundColor: '#F0F0F0',
|
||||||
|
fontWeight: 'bold',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
interface DebtSupplierExportPDFParams {
|
||||||
|
data: DebtSupplier[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const createPDFDocument = (params: DebtSupplierExportPDFParams) => {
|
||||||
|
return (
|
||||||
|
<Document>
|
||||||
|
{params.data.map((supplierReport, supplierIndex) => (
|
||||||
|
<Page
|
||||||
|
key={supplierIndex}
|
||||||
|
size='A4'
|
||||||
|
orientation='landscape'
|
||||||
|
style={pdfStyles.page}
|
||||||
|
>
|
||||||
|
{/* Title and Supplier Info */}
|
||||||
|
<View style={pdfStyles.titleSection}>
|
||||||
|
<Text style={pdfStyles.mainTitle}>
|
||||||
|
Laporan > Rekapitulasi Hutang ke Supplier
|
||||||
|
</Text>
|
||||||
|
<Text style={pdfStyles.supplierTitle}>
|
||||||
|
{supplierReport.supplier.name}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
|
||||||
|
{/* Table */}
|
||||||
|
<View style={pdfStyles.table}>
|
||||||
|
{/* Table Header */}
|
||||||
|
<View style={[pdfStyles.tableRow, pdfStyles.tableHeader]}>
|
||||||
|
<View style={[pdfStyles.tableCellHeader, { flex: 0.5 }]}>
|
||||||
|
<Text>No</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeader, { flex: 1.5 }]}>
|
||||||
|
<Text>No. PR</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeader, { flex: 1.5 }]}>
|
||||||
|
<Text>No. PO</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
|
||||||
|
<Text>Tgl Terima</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
|
||||||
|
<Text>Tgl PO</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeader, { flex: 0.6 }]}>
|
||||||
|
<Text>Aging</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
|
||||||
|
<Text>Area</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
|
||||||
|
<Text>Gudang</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
|
||||||
|
<Text>Tgl Jatuh Tempo</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
|
||||||
|
<Text>Status Jatuh Tempo</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeaderRight, { flex: 1.5 }]}>
|
||||||
|
<Text>Total Harga</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeaderRight, { flex: 1.5 }]}>
|
||||||
|
<Text>Pembayaran</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeaderRight, { flex: 1.5 }]}>
|
||||||
|
<Text>Hutang</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
|
||||||
|
<Text>Status</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
|
||||||
|
<Text>No. Perjalanan</Text>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
|
||||||
|
{/* Table Body */}
|
||||||
|
{supplierReport.rows.map((item, index) => (
|
||||||
|
<View
|
||||||
|
key={index}
|
||||||
|
style={[
|
||||||
|
pdfStyles.tableRow,
|
||||||
|
index < supplierReport.rows.length - 1
|
||||||
|
? pdfStyles.tableBorderBottom
|
||||||
|
: {},
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<View style={[pdfStyles.tableCellNo, { flex: 0.5 }]}>
|
||||||
|
<Text>{index + 1}</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
|
||||||
|
<Text>{item.pr_number || '-'}</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
|
||||||
|
<Text>{item.po_number || '-'}</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellCenter, { flex: 1 }]}>
|
||||||
|
<Text>
|
||||||
|
{item.received_date
|
||||||
|
? item.received_date != '-'
|
||||||
|
? formatDate(item.received_date, 'DD MMM YY')
|
||||||
|
: '-'
|
||||||
|
: '-'}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellCenter, { flex: 1 }]}>
|
||||||
|
<Text>
|
||||||
|
{item.po_date
|
||||||
|
? item.po_date != '-'
|
||||||
|
? formatDate(item.po_date, 'DD MMM YY')
|
||||||
|
: '-'
|
||||||
|
: '-'}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellCenter, { flex: 0.6 }]}>
|
||||||
|
<Text>{formatNumber(item.aging)} Hari</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
|
||||||
|
<Text>{item.area?.name || '-'}</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
|
||||||
|
<Text>{item.warehouse?.name || '-'}</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellCenter, { flex: 1 }]}>
|
||||||
|
<Text>
|
||||||
|
{item.due_date
|
||||||
|
? item.due_date != '-'
|
||||||
|
? formatDate(item.due_date, 'DD MMM YY')
|
||||||
|
: '-'
|
||||||
|
: '-'}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
|
||||||
|
<Text>{item.due_status || '-'}</Text>
|
||||||
|
</View>
|
||||||
|
<View
|
||||||
|
style={[
|
||||||
|
pdfStyles.tableCellRight,
|
||||||
|
{
|
||||||
|
flex: 1.5,
|
||||||
|
color: item.total_price < 0 ? 'red' : 'black',
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<Text>{formatCurrency(item.total_price)}</Text>
|
||||||
|
</View>
|
||||||
|
<View
|
||||||
|
style={[
|
||||||
|
pdfStyles.tableCellRight,
|
||||||
|
{
|
||||||
|
flex: 1.5,
|
||||||
|
color: item.payment_price < 0 ? 'red' : 'black',
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<Text>{formatCurrency(item.payment_price)}</Text>
|
||||||
|
</View>
|
||||||
|
<View
|
||||||
|
style={[
|
||||||
|
pdfStyles.tableCellRight,
|
||||||
|
{ flex: 1.5, color: item.debt_price < 0 ? 'red' : 'black' },
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<Text>{formatCurrency(item.debt_price)}</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
|
||||||
|
<Text>{item.status || '-'}</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
|
||||||
|
<Text>{item.travel_number || '-'}</Text>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{/* Summary Row */}
|
||||||
|
{supplierReport.total && (
|
||||||
|
<View style={[pdfStyles.tableRow, pdfStyles.summaryRow]}>
|
||||||
|
<View style={[pdfStyles.tableCellNo, { flex: 0.5 }]}>
|
||||||
|
<Text>Total</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
|
||||||
|
<Text></Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
|
||||||
|
<Text></Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
|
||||||
|
<Text></Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
|
||||||
|
<Text></Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellCenter, { flex: 0.6 }]}>
|
||||||
|
<Text>{formatNumber(supplierReport.total.aging)} Hari</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
|
||||||
|
<Text></Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
|
||||||
|
<Text></Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
|
||||||
|
<Text></Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
|
||||||
|
<Text></Text>
|
||||||
|
</View>
|
||||||
|
<View
|
||||||
|
style={[
|
||||||
|
pdfStyles.tableCellRight,
|
||||||
|
{
|
||||||
|
flex: 1.5,
|
||||||
|
color:
|
||||||
|
supplierReport.total.total_price < 0 ? 'red' : 'black',
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<Text>
|
||||||
|
{formatCurrency(supplierReport.total.total_price)}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<View
|
||||||
|
style={[
|
||||||
|
pdfStyles.tableCellRight,
|
||||||
|
{
|
||||||
|
flex: 1.5,
|
||||||
|
color:
|
||||||
|
supplierReport.total.payment_price < 0
|
||||||
|
? 'red'
|
||||||
|
: 'black',
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<Text>
|
||||||
|
{formatCurrency(supplierReport.total.payment_price)}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<View
|
||||||
|
style={[
|
||||||
|
pdfStyles.tableCellRight,
|
||||||
|
{
|
||||||
|
flex: 1.5,
|
||||||
|
color:
|
||||||
|
supplierReport.total.debt_price < 0 ? 'red' : 'black',
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<Text>{formatCurrency(supplierReport.total.debt_price)}</Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
|
||||||
|
<Text></Text>
|
||||||
|
</View>
|
||||||
|
<View style={[pdfStyles.tableCellLast, { flex: 1 }]}>
|
||||||
|
<Text></Text>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
|
</View>
|
||||||
|
</Page>
|
||||||
|
))}
|
||||||
|
</Document>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const generateDebtSupplierPDF = async (
|
||||||
|
params: DebtSupplierExportPDFParams
|
||||||
|
): Promise<void> => {
|
||||||
|
const PDFDocument = createPDFDocument(params);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const blob = await pdf(PDFDocument).toBlob();
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.href = url;
|
||||||
|
link.download = `laporan-hutang-supplier-${formatDate(new Date(), 'YYYY-MM-DD-HHmm')}.pdf`;
|
||||||
|
|
||||||
|
document.body.appendChild(link);
|
||||||
|
link.click();
|
||||||
|
document.body.removeChild(link);
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
} catch (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import * as XLSX from 'xlsx';
|
||||||
|
import { formatDate } from '@/lib/helper';
|
||||||
|
import { DebtSupplier } from '@/types/api/report/debt-supplier';
|
||||||
|
|
||||||
|
interface DebtSupplierExportExcelParams {
|
||||||
|
data: DebtSupplier[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const generateDebtSupplierExcel = (
|
||||||
|
params: DebtSupplierExportExcelParams
|
||||||
|
): void => {
|
||||||
|
if (!params.data || params.data.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const workbook = XLSX.utils.book_new();
|
||||||
|
|
||||||
|
params.data.forEach((supplierReport) => {
|
||||||
|
const supplierData = supplierReport.rows;
|
||||||
|
const supplierName = supplierReport.supplier.name || 'Unknown Supplier';
|
||||||
|
|
||||||
|
const excelData: { [key: string]: string | number }[] = supplierData.map(
|
||||||
|
(item, index) => ({
|
||||||
|
No: index + 1,
|
||||||
|
'Nomor PR': item.pr_number || '',
|
||||||
|
'Nomor PO': item.po_number || '',
|
||||||
|
'Tanggal Terima': item.received_date
|
||||||
|
? item.received_date != '-'
|
||||||
|
? formatDate(item.received_date, 'MM/DD/YYYY')
|
||||||
|
: '-'
|
||||||
|
: '-',
|
||||||
|
'Tanggal PO': item.po_date
|
||||||
|
? item.po_date != '-'
|
||||||
|
? formatDate(item.po_date, 'MM/DD/YYYY')
|
||||||
|
: '-'
|
||||||
|
: '-',
|
||||||
|
'Aging (Hari)': item.aging || 0,
|
||||||
|
Area: item.area?.name || '',
|
||||||
|
Gudang: item.warehouse?.name || '',
|
||||||
|
'Tanggal Jatuh Tempo': item.due_date
|
||||||
|
? item.due_date != '-'
|
||||||
|
? formatDate(item.due_date, 'MM/DD/YYYY')
|
||||||
|
: '-'
|
||||||
|
: '-',
|
||||||
|
'Status Jatuh Tempo': item.due_status || '',
|
||||||
|
'Total Harga': item.total_price || 0,
|
||||||
|
'Harga Pembayaran': item.payment_price || 0,
|
||||||
|
'Harga Hutang': item.debt_price || 0,
|
||||||
|
Status: item.status || '',
|
||||||
|
'Nomor Perjalanan': item.travel_number || '',
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
if (supplierReport.total) {
|
||||||
|
excelData.push({
|
||||||
|
No: 'Total',
|
||||||
|
'Nomor PR': '',
|
||||||
|
'Nomor PO': '',
|
||||||
|
'Tanggal Terima': '',
|
||||||
|
'Tanggal PO': '',
|
||||||
|
'Aging (Hari)': supplierReport.total.aging || 0,
|
||||||
|
Area: '',
|
||||||
|
Gudang: '',
|
||||||
|
'Tanggal Jatuh Tempo': '',
|
||||||
|
'Status Jatuh Tempo': '',
|
||||||
|
'Total Harga': supplierReport.total.total_price || 0,
|
||||||
|
'Harga Pembayaran': supplierReport.total.payment_price || 0,
|
||||||
|
'Harga Hutang': supplierReport.total.debt_price || 0,
|
||||||
|
Status: '',
|
||||||
|
'Nomor Perjalanan': '',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const worksheet = XLSX.utils.json_to_sheet(excelData);
|
||||||
|
|
||||||
|
const colWidths = [
|
||||||
|
{ wch: 5 }, // No
|
||||||
|
{ wch: 15 }, // Nomor PR
|
||||||
|
{ wch: 15 }, // Nomor PO
|
||||||
|
{ wch: 15 }, // Tanggal PR
|
||||||
|
{ wch: 15 }, // Tanggal PO
|
||||||
|
{ wch: 12 }, // Aging
|
||||||
|
{ wch: 15 }, // Area
|
||||||
|
{ wch: 15 }, // Gudang
|
||||||
|
{ wch: 18 }, // Tanggal Jatuh Tempo
|
||||||
|
{ wch: 18 }, // Status Jatuh Tempo
|
||||||
|
{ wch: 15 }, // Total Harga
|
||||||
|
{ wch: 15 }, // Harga Pembayaran
|
||||||
|
{ wch: 15 }, // Harga Hutang
|
||||||
|
{ wch: 12 }, // Status
|
||||||
|
{ wch: 15 }, // Nomor Perjalanan
|
||||||
|
];
|
||||||
|
worksheet['!cols'] = colWidths;
|
||||||
|
|
||||||
|
const sheetName =
|
||||||
|
supplierName.length > 31 ? supplierName.substring(0, 31) : supplierName;
|
||||||
|
XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
|
||||||
|
});
|
||||||
|
|
||||||
|
const filename = `laporan-hutang-supplier-${formatDate(new Date(), 'YYYY-MM-DD-HHmm')}.xlsx`;
|
||||||
|
|
||||||
|
XLSX.writeFile(workbook, filename);
|
||||||
|
};
|
||||||
@@ -0,0 +1,721 @@
|
|||||||
|
import { useState, useMemo, useCallback } from 'react';
|
||||||
|
import useSWR from 'swr';
|
||||||
|
import { Icon } from '@iconify/react';
|
||||||
|
import Card from '@/components/Card';
|
||||||
|
import SelectInput, {
|
||||||
|
useSelect,
|
||||||
|
OptionType,
|
||||||
|
} from '@/components/input/SelectInput';
|
||||||
|
import DateInput from '@/components/input/DateInput';
|
||||||
|
import { CustomerApi } from '@/services/api/master-data';
|
||||||
|
import { FinanceApi } from '@/services/api/report/finance-report';
|
||||||
|
import Table from '@/components/Table';
|
||||||
|
import { ColumnDef } from '@tanstack/react-table';
|
||||||
|
import { formatCurrency, formatDate, formatNumber } from '@/lib/helper';
|
||||||
|
import {
|
||||||
|
CustomerPaymentReport,
|
||||||
|
CustomerPaymentSummary,
|
||||||
|
} from '@/types/api/report/customer-payment';
|
||||||
|
import { isResponseSuccess } from '@/lib/api-helper';
|
||||||
|
import Pagination from '@/components/Pagination';
|
||||||
|
import Button from '@/components/Button';
|
||||||
|
import Dropdown from '@/components/Dropdown';
|
||||||
|
import MenuItem from '@/components/menu/MenuItem';
|
||||||
|
import Menu from '@/components/menu/Menu';
|
||||||
|
import Modal from '@/components/Modal';
|
||||||
|
import { useModal } from '@/components/Modal';
|
||||||
|
import toast from 'react-hot-toast';
|
||||||
|
import { generateCustomerPaymentExcel } from '@/components/pages/report/finance/export/CustomerPaymentExportXLSX';
|
||||||
|
import { generateCustomerPaymentPDF } from '@/components/pages/report/finance/export/CustomerPaymentExportPDF';
|
||||||
|
|
||||||
|
const CustomerPaymentTab = () => {
|
||||||
|
// ===== STATE MANAGEMENT =====
|
||||||
|
const [isPdfExportLoading, setIsPdfExportLoading] = useState(false);
|
||||||
|
const [isExcelExportLoading, setIsExcelExportLoading] = useState(false);
|
||||||
|
const isAnyExportLoading = isPdfExportLoading || isExcelExportLoading;
|
||||||
|
|
||||||
|
// ===== PAGINATION STATE =====
|
||||||
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
|
const [pageSize, setPageSize] = useState(10);
|
||||||
|
|
||||||
|
// ===== SUBMISSION STATE =====
|
||||||
|
const [isSubmitted, setIsSubmitted] = useState(false);
|
||||||
|
|
||||||
|
// ===== FILTER STATE =====
|
||||||
|
const [filterCustomer, setFilterCustomer] = useState<OptionType[]>([]);
|
||||||
|
const [filterSales, setFilterSales] = useState<OptionType[]>([]);
|
||||||
|
const [filterStartDate, setFilterStartDate] = useState('');
|
||||||
|
const [filterEndDate, setFilterEndDate] = useState('');
|
||||||
|
const [filterErrors, setFilterErrors] = useState<Record<string, string>>({});
|
||||||
|
|
||||||
|
const filterModal = useModal();
|
||||||
|
|
||||||
|
const { options: customerOptions, isLoadingOptions: isLoadingCustomers } =
|
||||||
|
useSelect(CustomerApi.basePath, 'id', 'name', 'search');
|
||||||
|
|
||||||
|
const salesOptions = useMemo(
|
||||||
|
() => [
|
||||||
|
{ value: 'Sales A', label: 'Sales A' },
|
||||||
|
{ value: 'Sales B', label: 'Sales B' },
|
||||||
|
{ value: 'Sales C', label: 'Sales C' },
|
||||||
|
// TODO: Fetch sales options from API
|
||||||
|
],
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
const dataTypeOptions = useMemo(
|
||||||
|
() => [{ value: 'do_date', label: 'Tanggal Jual' }],
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
// ===== FILTER HANDLERS =====
|
||||||
|
const handleResetFilters = useCallback(() => {
|
||||||
|
setIsSubmitted(false);
|
||||||
|
setFilterCustomer([]);
|
||||||
|
setFilterSales([]);
|
||||||
|
setFilterStartDate('');
|
||||||
|
setFilterEndDate('');
|
||||||
|
setFilterErrors({});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleApplyFilters = useCallback(() => {
|
||||||
|
const errors: Record<string, string> = {};
|
||||||
|
|
||||||
|
if (!filterStartDate) {
|
||||||
|
errors.start_date = 'Tanggal mulai wajib diisi';
|
||||||
|
}
|
||||||
|
if (!filterEndDate) {
|
||||||
|
errors.end_date = 'Tanggal akhir wajib diisi';
|
||||||
|
}
|
||||||
|
|
||||||
|
setFilterErrors(errors);
|
||||||
|
|
||||||
|
if (Object.keys(errors).length === 0) {
|
||||||
|
setIsSubmitted(true);
|
||||||
|
setCurrentPage(1);
|
||||||
|
filterModal.closeModal();
|
||||||
|
}
|
||||||
|
}, [filterModal, filterStartDate, filterEndDate]);
|
||||||
|
|
||||||
|
// ===== DATA FETCHING =====
|
||||||
|
const { data: customerPayment, isLoading } = useSWR(
|
||||||
|
isSubmitted
|
||||||
|
? () => {
|
||||||
|
const params = {
|
||||||
|
customer_id:
|
||||||
|
filterCustomer.length > 0
|
||||||
|
? filterCustomer.map((v) => String(v.value)).join(',')
|
||||||
|
: undefined,
|
||||||
|
sales:
|
||||||
|
filterSales.length > 0
|
||||||
|
? filterSales.map((v) => String(v.value)).join(',')
|
||||||
|
: undefined,
|
||||||
|
filter_by: 'do_date' as const,
|
||||||
|
start_date: filterStartDate || undefined,
|
||||||
|
end_date: filterEndDate || undefined,
|
||||||
|
page: currentPage,
|
||||||
|
limit: pageSize,
|
||||||
|
};
|
||||||
|
|
||||||
|
return ['customer-payment-report', params];
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
([, params]) =>
|
||||||
|
FinanceApi.getCustomerPaymentReport(
|
||||||
|
params.customer_id,
|
||||||
|
params.sales,
|
||||||
|
params.filter_by,
|
||||||
|
params.start_date,
|
||||||
|
params.end_date,
|
||||||
|
params.page,
|
||||||
|
params.limit
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
const data: CustomerPaymentReport[] = useMemo(
|
||||||
|
() =>
|
||||||
|
isResponseSuccess(customerPayment)
|
||||||
|
? (customerPayment?.data as unknown as CustomerPaymentReport[]) || []
|
||||||
|
: [],
|
||||||
|
[customerPayment]
|
||||||
|
);
|
||||||
|
|
||||||
|
const meta =
|
||||||
|
isResponseSuccess(customerPayment) && customerPayment?.meta
|
||||||
|
? customerPayment.meta
|
||||||
|
: null;
|
||||||
|
|
||||||
|
// ===== EXPORT DATA FETCHER =====
|
||||||
|
const customerPaymentExport = useCallback(async (): Promise<
|
||||||
|
CustomerPaymentReport[] | null
|
||||||
|
> => {
|
||||||
|
const params = {
|
||||||
|
customer_id:
|
||||||
|
filterCustomer.length > 0
|
||||||
|
? filterCustomer.map((v) => String(v.value)).join(',')
|
||||||
|
: undefined,
|
||||||
|
sales:
|
||||||
|
filterSales.length > 0
|
||||||
|
? filterSales.map((v) => String(v.value)).join(',')
|
||||||
|
: undefined,
|
||||||
|
filter_by: 'do_date' as const,
|
||||||
|
start_date: filterStartDate || undefined,
|
||||||
|
end_date: filterEndDate || undefined,
|
||||||
|
limit: 100,
|
||||||
|
page: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await FinanceApi.getCustomerPaymentReport(
|
||||||
|
params.customer_id,
|
||||||
|
params.sales,
|
||||||
|
params.filter_by,
|
||||||
|
params.start_date,
|
||||||
|
params.end_date,
|
||||||
|
params.page,
|
||||||
|
params.limit
|
||||||
|
);
|
||||||
|
|
||||||
|
return isResponseSuccess(response)
|
||||||
|
? (response.data as unknown as CustomerPaymentReport[])
|
||||||
|
: null;
|
||||||
|
}, [filterCustomer, filterSales, filterStartDate, filterEndDate]);
|
||||||
|
|
||||||
|
// ===== EXPORT HANDLERS =====
|
||||||
|
const handleExportExcel = useCallback(async () => {
|
||||||
|
setIsExcelExportLoading(true);
|
||||||
|
try {
|
||||||
|
const allDataForExport = await customerPaymentExport();
|
||||||
|
|
||||||
|
if (
|
||||||
|
!allDataForExport ||
|
||||||
|
!Array.isArray(allDataForExport) ||
|
||||||
|
allDataForExport.length === 0
|
||||||
|
) {
|
||||||
|
toast.error('Tidak ada data untuk diekspor.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
generateCustomerPaymentExcel({ data: allDataForExport });
|
||||||
|
toast.success('Excel berhasil dibuat dan diunduh.');
|
||||||
|
} catch {
|
||||||
|
toast.error('Gagal membuat Excel. Silakan coba lagi.');
|
||||||
|
} finally {
|
||||||
|
setIsExcelExportLoading(false);
|
||||||
|
}
|
||||||
|
}, [customerPaymentExport]);
|
||||||
|
|
||||||
|
const handleExportPdf = useCallback(async () => {
|
||||||
|
setIsPdfExportLoading(true);
|
||||||
|
try {
|
||||||
|
const allDataForExport = await customerPaymentExport();
|
||||||
|
|
||||||
|
if (
|
||||||
|
!allDataForExport ||
|
||||||
|
!Array.isArray(allDataForExport) ||
|
||||||
|
allDataForExport.length === 0
|
||||||
|
) {
|
||||||
|
toast.error('Tidak ada data untuk diekspor.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await generateCustomerPaymentPDF({ data: allDataForExport });
|
||||||
|
toast.success('PDF berhasil dibuat dan diunduh.');
|
||||||
|
} catch {
|
||||||
|
toast.error('Gagal membuat PDF. Silakan coba lagi.');
|
||||||
|
} finally {
|
||||||
|
setIsPdfExportLoading(false);
|
||||||
|
}
|
||||||
|
}, [customerPaymentExport]);
|
||||||
|
|
||||||
|
// ===== PAGINATION HANDLERS =====
|
||||||
|
const handlePageChange = (page: number) => {
|
||||||
|
setCurrentPage(page);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRowChange = (pageSize: number) => {
|
||||||
|
setPageSize(pageSize);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleNextPage = () => {
|
||||||
|
if (meta && currentPage < meta.total_pages) {
|
||||||
|
setCurrentPage(currentPage + 1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handlePrevPage = () => {
|
||||||
|
if (currentPage > 1) {
|
||||||
|
setCurrentPage(currentPage - 1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getTableColumns = (
|
||||||
|
summary: CustomerPaymentSummary
|
||||||
|
): ColumnDef<CustomerPaymentReport['rows'][0]>[] => {
|
||||||
|
const tableColumns: ColumnDef<CustomerPaymentReport['rows'][0]>[] = [
|
||||||
|
{
|
||||||
|
id: 'no',
|
||||||
|
header: 'No',
|
||||||
|
cell: (props) => props.row.index + 1,
|
||||||
|
footer: () => <div className='font-semibold text-gray-900'>Total</div>,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'do_date_or_payment_date',
|
||||||
|
header: 'Tanggal DO/Bayar',
|
||||||
|
accessorKey: 'do_date',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.do_date;
|
||||||
|
return formatDate(value, 'DD MMM YYYY');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'realization_date',
|
||||||
|
header: 'Tanggal Realisasi',
|
||||||
|
accessorKey: 'realization_date',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.realization_date;
|
||||||
|
return formatDate(value, 'DD MMM YYYY');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'aging',
|
||||||
|
header: 'Aging',
|
||||||
|
accessorKey: 'aging_day',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.aging_day;
|
||||||
|
return (
|
||||||
|
<div className='text-center'>
|
||||||
|
{value ? formatNumber(value) : '-'} hari
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'reference',
|
||||||
|
header: 'Referensi',
|
||||||
|
accessorKey: 'reference',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.reference;
|
||||||
|
return value || '-';
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'vehicle_plate',
|
||||||
|
header: 'Nomor Polisi',
|
||||||
|
accessorKey: 'vehicle_plate',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.vehicle_plate;
|
||||||
|
return value || '-';
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'qty',
|
||||||
|
header: 'Ekor/Qty',
|
||||||
|
accessorKey: 'qty',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.qty;
|
||||||
|
return <div className='text-right'>{formatNumber(value)}</div>;
|
||||||
|
},
|
||||||
|
footer: () => (
|
||||||
|
<div className='text-right font-semibold text-gray-900'>
|
||||||
|
{formatNumber(summary.total_qty) || '-'}
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'weight',
|
||||||
|
header: 'Berat (Kg)',
|
||||||
|
accessorKey: 'weight',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.weight;
|
||||||
|
return <div className='text-right'>{formatNumber(value)}</div>;
|
||||||
|
},
|
||||||
|
footer: () => (
|
||||||
|
<div className='text-right font-semibold text-gray-900'>
|
||||||
|
{formatNumber(summary.total_weight) || '-'}
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'average_weight',
|
||||||
|
header: 'AVG',
|
||||||
|
accessorKey: 'average_weight',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.average_weight;
|
||||||
|
return <div className='text-right'>{formatNumber(value)}</div>;
|
||||||
|
},
|
||||||
|
footer: () => (
|
||||||
|
<div className='text-right font-semibold text-gray-900'>-</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'price',
|
||||||
|
header: 'Harga Awal',
|
||||||
|
accessorKey: 'price',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.price;
|
||||||
|
return <div className='text-right'>{formatCurrency(value)}</div>;
|
||||||
|
},
|
||||||
|
footer: () => (
|
||||||
|
<div className='text-right font-semibold text-gray-900'>
|
||||||
|
{formatCurrency(summary.total_initial_amount) || '-'}
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'credit_note',
|
||||||
|
header: 'CN',
|
||||||
|
accessorKey: 'credit_note',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.credit_note;
|
||||||
|
return <div className='text-right'>{formatCurrency(value)}</div>;
|
||||||
|
},
|
||||||
|
footer: () => (
|
||||||
|
<div className='text-right font-semibold text-gray-900'>
|
||||||
|
{formatCurrency(summary.total_credit_note) || '-'}
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'final_price',
|
||||||
|
header: 'Harga Akhir',
|
||||||
|
accessorKey: 'final_price',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.final_price;
|
||||||
|
return <div className='text-right'>{formatCurrency(value)}</div>;
|
||||||
|
},
|
||||||
|
footer: () => (
|
||||||
|
<div className='text-right font-semibold text-gray-900'>
|
||||||
|
{formatCurrency(summary.total_final_amount) || '-'}
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'ppn',
|
||||||
|
header: 'PPN (%)',
|
||||||
|
accessorKey: 'ppn',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.ppn;
|
||||||
|
return <div className='text-right'>{formatNumber(value)}%</div>;
|
||||||
|
},
|
||||||
|
footer: () => (
|
||||||
|
<div className='text-right font-semibold text-gray-900'>-</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'total',
|
||||||
|
header: 'Total',
|
||||||
|
accessorKey: 'total',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.total;
|
||||||
|
return <div className='text-right'>{formatCurrency(value)}</div>;
|
||||||
|
},
|
||||||
|
footer: () => (
|
||||||
|
<div className='text-right font-semibold text-gray-900'>
|
||||||
|
{formatCurrency(summary.total_grand_amount) || '-'}
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'payment',
|
||||||
|
header: 'Pembayaran',
|
||||||
|
accessorKey: 'payment',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.payment;
|
||||||
|
return <div className='text-right'>{formatCurrency(value)}</div>;
|
||||||
|
},
|
||||||
|
footer: () => (
|
||||||
|
<div className='text-right font-semibold text-gray-900'>
|
||||||
|
{formatCurrency(summary.total_payment) || '-'}
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'accounts_receivable',
|
||||||
|
header: 'Saldo Piutang',
|
||||||
|
accessorKey: 'accounts_receivable',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.accounts_receivable;
|
||||||
|
return <div className='text-right'>{formatCurrency(value)}</div>;
|
||||||
|
},
|
||||||
|
footer: () => (
|
||||||
|
<div className='text-right font-semibold text-gray-900'>
|
||||||
|
{formatCurrency(summary.total_accounts_receivable) || '-'}
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'notes',
|
||||||
|
header: 'Keterangan',
|
||||||
|
accessorKey: 'notes',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.notes;
|
||||||
|
return value || '-';
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'pickup_info',
|
||||||
|
header: 'Pengambilan',
|
||||||
|
accessorKey: 'pickup_info',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.pickup_info;
|
||||||
|
return value || '-';
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'sales_marketing',
|
||||||
|
header: 'Sales/Marketing',
|
||||||
|
accessorKey: 'sales_marketing',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.sales_marketing;
|
||||||
|
return value || '-';
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
return tableColumns;
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className='w-full p-0 sm:p-4'>
|
||||||
|
<Card
|
||||||
|
subtitle='Laporan > Kontrol Pembayaran Customer'
|
||||||
|
className={{ wrapper: 'w-full', body: 'p-1!' }}
|
||||||
|
>
|
||||||
|
<div className='mb-4 flex justify-end gap-2 [&_button]:px-4'>
|
||||||
|
<Button variant='outline' onClick={filterModal.openModal}>
|
||||||
|
<Icon icon='heroicons:funnel' width={18} height={18} />
|
||||||
|
Filter
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Dropdown
|
||||||
|
trigger={
|
||||||
|
<Button variant='outline' isLoading={isAnyExportLoading}>
|
||||||
|
<Icon
|
||||||
|
icon='heroicons:cloud-arrow-down'
|
||||||
|
width={18}
|
||||||
|
height={18}
|
||||||
|
/>
|
||||||
|
Export
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
align='end'
|
||||||
|
>
|
||||||
|
<Menu>
|
||||||
|
<MenuItem title='Excel' onClick={handleExportExcel} />
|
||||||
|
<MenuItem title='PDF' onClick={handleExportPdf} />
|
||||||
|
</Menu>
|
||||||
|
</Dropdown>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Filter Modal */}
|
||||||
|
<Modal
|
||||||
|
ref={filterModal.ref}
|
||||||
|
className={{
|
||||||
|
modal: 'p-0',
|
||||||
|
modalBox: 'p-0 rounded-2xl xl:max-w-4/12 max-w-sm',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className='space-y-6'>
|
||||||
|
{/* Modal Header */}
|
||||||
|
<div className='flex items-center justify-between gap-2 py-3 border-b border-gray-300 px-4'>
|
||||||
|
<div className='flex items-center gap-2 text-primary'>
|
||||||
|
<Icon icon='heroicons:funnel' width={20} height={20} />
|
||||||
|
<h3 className='font-semibold'>Filter Data</h3>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
variant='link'
|
||||||
|
onClick={filterModal.closeModal}
|
||||||
|
className='text-gray-500 hover:text-gray-700 transition-colors cursor-pointer'
|
||||||
|
>
|
||||||
|
<Icon icon='heroicons:x-mark' width={20} height={20} />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<div className='space-y-4 px-4'>
|
||||||
|
<div className='grid grid-cols-1 sm:grid-cols-2 sm:gap-4'>
|
||||||
|
<div>
|
||||||
|
<DateInput
|
||||||
|
label='Tanggal'
|
||||||
|
name='start_date'
|
||||||
|
value={filterStartDate}
|
||||||
|
onChange={(e) => {
|
||||||
|
setFilterStartDate(e.target.value);
|
||||||
|
setFilterErrors((prev) => ({ ...prev, start_date: '' }));
|
||||||
|
}}
|
||||||
|
className={{ wrapper: 'w-full' }}
|
||||||
|
/>
|
||||||
|
{filterErrors.start_date && (
|
||||||
|
<p className='text-red-500 text-sm mt-1'>
|
||||||
|
{filterErrors.start_date}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<DateInput
|
||||||
|
label=' '
|
||||||
|
name='end_date'
|
||||||
|
value={filterEndDate}
|
||||||
|
onChange={(e) => {
|
||||||
|
setFilterEndDate(e.target.value);
|
||||||
|
setFilterErrors((prev) => ({ ...prev, end_date: '' }));
|
||||||
|
}}
|
||||||
|
className={{ wrapper: 'w-full' }}
|
||||||
|
/>
|
||||||
|
{filterErrors.end_date && (
|
||||||
|
<p className='text-red-500 text-sm mt-1'>
|
||||||
|
{filterErrors.end_date}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<SelectInput
|
||||||
|
label='Customer'
|
||||||
|
placeholder='Pilih Customer'
|
||||||
|
isMulti
|
||||||
|
options={customerOptions}
|
||||||
|
value={filterCustomer}
|
||||||
|
onChange={(val) => {
|
||||||
|
setFilterCustomer(
|
||||||
|
Array.isArray(val) ? val : val ? [val] : []
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
isLoading={isLoadingCustomers}
|
||||||
|
isClearable
|
||||||
|
className={{ wrapper: 'w-full' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<SelectInput
|
||||||
|
label='Sales'
|
||||||
|
placeholder='Pilih Sales'
|
||||||
|
isMulti
|
||||||
|
options={salesOptions}
|
||||||
|
value={filterSales}
|
||||||
|
onChange={(val) => {
|
||||||
|
setFilterSales(Array.isArray(val) ? val : val ? [val] : []);
|
||||||
|
}}
|
||||||
|
isClearable
|
||||||
|
className={{ wrapper: 'w-full' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<SelectInput
|
||||||
|
label='Filter Berdasarkan'
|
||||||
|
placeholder='Pilih Filter Berdasarkan'
|
||||||
|
options={dataTypeOptions}
|
||||||
|
value={dataTypeOptions[0]}
|
||||||
|
isDisabled={true}
|
||||||
|
className={{ wrapper: 'w-full' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Action Buttons */}
|
||||||
|
<div className='flex justify-between gap-4 py-4 mt-8 border-t border-gray-300 bg-gray-100'>
|
||||||
|
<Button
|
||||||
|
variant='soft'
|
||||||
|
className='ms-4 min-w-36 rounded-lg'
|
||||||
|
onClick={handleResetFilters}
|
||||||
|
>
|
||||||
|
Reset Filter
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
className='me-4 min-w-36 rounded-lg'
|
||||||
|
onClick={handleApplyFilters}
|
||||||
|
>
|
||||||
|
Apply Filter
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
{!isSubmitted ? (
|
||||||
|
<div className='mt-6 text-center text-gray-500'>
|
||||||
|
Silakan klik tombol Filter untuk mengatur filter dan menampilkan
|
||||||
|
data.
|
||||||
|
</div>
|
||||||
|
) : isLoading ? (
|
||||||
|
<div className='w-full flex flex-row justify-center items-center p-4'>
|
||||||
|
<span className='loading loading-spinner loading-xl' />
|
||||||
|
</div>
|
||||||
|
) : data.length === 0 ? (
|
||||||
|
<div className='mt-6 text-center text-gray-500'>
|
||||||
|
Tidak ada data yang dapat ditampilkan...
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
data.map((customerReport) => {
|
||||||
|
const summary = customerReport.summary || {
|
||||||
|
total_qty: 0,
|
||||||
|
total_weight: 0,
|
||||||
|
total_initial_amount: 0,
|
||||||
|
total_credit_note: 0,
|
||||||
|
total_final_amount: 0,
|
||||||
|
total_ppn: 0,
|
||||||
|
total_grand_amount: 0,
|
||||||
|
total_payment: 0,
|
||||||
|
total_accounts_receivable: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
const totalAccountsReceivable = summary.total_accounts_receivable;
|
||||||
|
const tableColumns = getTableColumns(summary);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card
|
||||||
|
key={customerReport.customer.id}
|
||||||
|
title={customerReport.customer.name}
|
||||||
|
subtitle={`${customerReport.customer.address || ''}\nSaldo Piutang: ${formatCurrency(totalAccountsReceivable)}`}
|
||||||
|
className={{ wrapper: 'w-full' }}
|
||||||
|
variant='bordered'
|
||||||
|
collapsible={true}
|
||||||
|
>
|
||||||
|
<Table
|
||||||
|
data={customerReport.rows}
|
||||||
|
columns={tableColumns}
|
||||||
|
pageSize={10}
|
||||||
|
renderFooter={customerReport.rows.length > 0}
|
||||||
|
className={{
|
||||||
|
containerClassName: 'w-full',
|
||||||
|
tableWrapperClassName: 'overflow-x-auto mt-4',
|
||||||
|
tableClassName: 'w-full table-auto text-sm',
|
||||||
|
headerRowClassName: 'border-b border-b-gray-200 bg-gray-50',
|
||||||
|
headerColumnClassName:
|
||||||
|
'px-4 py-3 text-xs font-semibold text-gray-700 text-left border border-gray-200',
|
||||||
|
bodyRowClassName:
|
||||||
|
'hover:bg-gray-50 transition-colors border-b border-l border-r border-b-gray-200 border-l-gray-200 border-r-gray-200',
|
||||||
|
bodyColumnClassName:
|
||||||
|
'px-4 py-3 text-xs text-gray-900 whitespace-nowrap',
|
||||||
|
tableFooterClassName:
|
||||||
|
'bg-gray-100 font-semibold border border-gray-200',
|
||||||
|
footerRowClassName: 'border-t-2 border-gray-300',
|
||||||
|
footerColumnClassName:
|
||||||
|
'px-4 py-3 text-xs text-gray-900 whitespace-nowrap',
|
||||||
|
paginationClassName: 'hidden',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
{meta && data.length > 0 && (
|
||||||
|
<div className='mt-6'>
|
||||||
|
<Pagination
|
||||||
|
currentPage={meta.page}
|
||||||
|
totalItems={meta.total_results}
|
||||||
|
onPageChange={handlePageChange}
|
||||||
|
onRowChange={handleRowChange}
|
||||||
|
onNextPage={handleNextPage}
|
||||||
|
onPrevPage={handlePrevPage}
|
||||||
|
rowOptions={[10, 25, 50, 100]}
|
||||||
|
itemsPerPage={meta.limit}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default CustomerPaymentTab;
|
||||||
@@ -0,0 +1,634 @@
|
|||||||
|
import Button from '@/components/Button';
|
||||||
|
import Card from '@/components/Card';
|
||||||
|
import Dropdown from '@/components/Dropdown';
|
||||||
|
import DateInput from '@/components/input/DateInput';
|
||||||
|
import SelectInput, {
|
||||||
|
OptionType,
|
||||||
|
useSelect,
|
||||||
|
} from '@/components/input/SelectInput';
|
||||||
|
import Menu from '@/components/menu/Menu';
|
||||||
|
import MenuItem from '@/components/menu/MenuItem';
|
||||||
|
import Modal, { useModal } from '@/components/Modal';
|
||||||
|
import Table from '@/components/Table';
|
||||||
|
import { isResponseSuccess } from '@/lib/api-helper';
|
||||||
|
import { formatCurrency, formatDate, formatNumber } from '@/lib/helper';
|
||||||
|
import { SupplierApi } from '@/services/api/master-data';
|
||||||
|
import { DebtRow, DebtSupplier } from '@/types/api/report/debt-supplier';
|
||||||
|
import { generateDebtSupplierExcel } from '@/components/pages/report/finance/export/DebtSupplierExportXLSX';
|
||||||
|
import { generateDebtSupplierPDF } from '@/components/pages/report/finance/export/DebtSupllierExportPDF';
|
||||||
|
import { Icon } from '@iconify/react';
|
||||||
|
import { ColumnDef } from '@tanstack/react-table';
|
||||||
|
import { useCallback, useMemo, useState } from 'react';
|
||||||
|
import toast from 'react-hot-toast';
|
||||||
|
import useSWR from 'swr';
|
||||||
|
import Pagination from '@/components/Pagination';
|
||||||
|
import { DebtSupplierApi } from '@/services/api/report/debt-supplier';
|
||||||
|
|
||||||
|
const DebtSupplierTab = () => {
|
||||||
|
// ===== STATE MANAGEMENT =====
|
||||||
|
const [isPdfExportLoading, setIsPdfExportLoading] = useState(false);
|
||||||
|
const [isExcelExportLoading, setIsExcelExportLoading] = useState(false);
|
||||||
|
const isAnyExportLoading = isPdfExportLoading || isExcelExportLoading;
|
||||||
|
|
||||||
|
// ===== PAGINATION STATE =====
|
||||||
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
|
const [pageSize, setPageSize] = useState(10);
|
||||||
|
|
||||||
|
// ===== SUBMISSION STATE =====
|
||||||
|
const [isSubmitted, setIsSubmitted] = useState(false);
|
||||||
|
|
||||||
|
// ===== FILTER STATE =====
|
||||||
|
const [filterSupplier, setFilterSupplier] = useState<OptionType[]>([]);
|
||||||
|
const [filterStartDate, setFilterStartDate] = useState('');
|
||||||
|
const [filterEndDate, setFilterEndDate] = useState('');
|
||||||
|
const [filterDateType, setFilterDateType] = useState<OptionType>();
|
||||||
|
const [filterErrors, setFilterErrors] = useState<Record<string, string>>({});
|
||||||
|
|
||||||
|
const filterModal = useModal();
|
||||||
|
|
||||||
|
const { options: supplierOptions, isLoadingOptions: isLoadingSuppliers } =
|
||||||
|
useSelect(SupplierApi.basePath, 'id', 'name', '', {
|
||||||
|
limit: 'limit',
|
||||||
|
});
|
||||||
|
|
||||||
|
const dataTypeOptions = useMemo(
|
||||||
|
() => [
|
||||||
|
{ value: 'received_date', label: 'Tanggal Terima' },
|
||||||
|
{ value: 'po_date', label: 'Tanggal PO' },
|
||||||
|
],
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
// ===== FILTER HANDLERS =====
|
||||||
|
const handleResetFilters = useCallback(() => {
|
||||||
|
setIsSubmitted(false);
|
||||||
|
setFilterSupplier([]);
|
||||||
|
setFilterStartDate('');
|
||||||
|
setFilterEndDate('');
|
||||||
|
setFilterErrors({});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleApplyFilters = useCallback(() => {
|
||||||
|
const errors: Record<string, string> = {};
|
||||||
|
|
||||||
|
if (!filterStartDate) {
|
||||||
|
errors.start_date = 'Tanggal mulai wajib diisi';
|
||||||
|
}
|
||||||
|
if (!filterEndDate) {
|
||||||
|
errors.end_date = 'Tanggal akhir wajib diisi';
|
||||||
|
}
|
||||||
|
|
||||||
|
setFilterErrors(errors);
|
||||||
|
|
||||||
|
if (Object.keys(errors).length === 0) {
|
||||||
|
setIsSubmitted(true);
|
||||||
|
setCurrentPage(1);
|
||||||
|
filterModal.closeModal();
|
||||||
|
}
|
||||||
|
}, [filterModal, filterStartDate, filterEndDate]);
|
||||||
|
|
||||||
|
// ===== DATA FETCHING =====
|
||||||
|
const { data: debtSupplier, isLoading } = useSWR(
|
||||||
|
isSubmitted
|
||||||
|
? () => {
|
||||||
|
const params = {
|
||||||
|
supplier_ids:
|
||||||
|
filterSupplier.length > 0
|
||||||
|
? filterSupplier.map((v) => String(v.value)).join(',')
|
||||||
|
: undefined,
|
||||||
|
filter_by: filterDateType?.value,
|
||||||
|
start_date: filterStartDate || undefined,
|
||||||
|
end_date: filterEndDate || undefined,
|
||||||
|
page: currentPage,
|
||||||
|
limit: pageSize,
|
||||||
|
};
|
||||||
|
|
||||||
|
return ['debt-supplier-report', params];
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
([, params]) =>
|
||||||
|
DebtSupplierApi.getDebtSupplierReport(
|
||||||
|
params.supplier_ids,
|
||||||
|
params.filter_by?.toString(),
|
||||||
|
params.start_date,
|
||||||
|
params.end_date,
|
||||||
|
params.page,
|
||||||
|
params.limit
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
const data: DebtSupplier[] = useMemo(
|
||||||
|
() =>
|
||||||
|
isResponseSuccess(debtSupplier)
|
||||||
|
? (debtSupplier?.data as unknown as DebtSupplier[]) || []
|
||||||
|
: [],
|
||||||
|
[debtSupplier]
|
||||||
|
);
|
||||||
|
const meta =
|
||||||
|
isResponseSuccess(debtSupplier) && debtSupplier?.meta
|
||||||
|
? debtSupplier.meta
|
||||||
|
: null;
|
||||||
|
|
||||||
|
// ===== EXPORT DATA FETCHER =====
|
||||||
|
const debtSupplierExport = useCallback(async (): Promise<
|
||||||
|
DebtSupplier[] | null
|
||||||
|
> => {
|
||||||
|
const params = {
|
||||||
|
supplier_ids:
|
||||||
|
filterSupplier.length > 0
|
||||||
|
? filterSupplier.map((v) => String(v.value)).join(',')
|
||||||
|
: undefined,
|
||||||
|
filter_by: filterDateType?.value?.toString(),
|
||||||
|
start_date: filterStartDate || undefined,
|
||||||
|
end_date: filterEndDate || undefined,
|
||||||
|
date_type: filterDateType ? filterDateType.value : undefined,
|
||||||
|
limit: 100,
|
||||||
|
page: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await DebtSupplierApi.getDebtSupplierReport(
|
||||||
|
params.supplier_ids,
|
||||||
|
params.filter_by,
|
||||||
|
params.start_date,
|
||||||
|
params.end_date,
|
||||||
|
params.page,
|
||||||
|
params.limit
|
||||||
|
);
|
||||||
|
|
||||||
|
return isResponseSuccess(response)
|
||||||
|
? (response.data as unknown as DebtSupplier[])
|
||||||
|
: null;
|
||||||
|
}, [filterSupplier, filterStartDate, filterEndDate]);
|
||||||
|
|
||||||
|
// ===== EXPORT HANDLERS =====
|
||||||
|
const handleExportExcel = useCallback(async () => {
|
||||||
|
setIsExcelExportLoading(true);
|
||||||
|
try {
|
||||||
|
const allDataForExport = await debtSupplierExport();
|
||||||
|
|
||||||
|
if (
|
||||||
|
!allDataForExport ||
|
||||||
|
!Array.isArray(allDataForExport) ||
|
||||||
|
allDataForExport.length === 0
|
||||||
|
) {
|
||||||
|
toast.error('Tidak ada data untuk diekspor.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
generateDebtSupplierExcel({ data: allDataForExport });
|
||||||
|
toast.success('Excel berhasil dibuat dan diunduh.');
|
||||||
|
} catch {
|
||||||
|
toast.error('Gagal membuat Excel. Silakan coba lagi.');
|
||||||
|
} finally {
|
||||||
|
setIsExcelExportLoading(false);
|
||||||
|
}
|
||||||
|
}, [debtSupplierExport]);
|
||||||
|
|
||||||
|
const handleExportPdf = useCallback(async () => {
|
||||||
|
setIsPdfExportLoading(true);
|
||||||
|
try {
|
||||||
|
const allDataForExport = await debtSupplierExport();
|
||||||
|
|
||||||
|
if (
|
||||||
|
!allDataForExport ||
|
||||||
|
!Array.isArray(allDataForExport) ||
|
||||||
|
allDataForExport.length === 0
|
||||||
|
) {
|
||||||
|
toast.error('Tidak ada data untuk diekspor.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await generateDebtSupplierPDF({ data: allDataForExport });
|
||||||
|
toast.success('PDF berhasil dibuat dan diunduh.');
|
||||||
|
} catch {
|
||||||
|
toast.error('Gagal membuat PDF. Silakan coba lagi.');
|
||||||
|
} finally {
|
||||||
|
setIsPdfExportLoading(false);
|
||||||
|
}
|
||||||
|
}, [debtSupplierExport]);
|
||||||
|
|
||||||
|
// ===== PAGINATION HANDLERS =====
|
||||||
|
const handlePageChange = (page: number) => {
|
||||||
|
setCurrentPage(page);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRowChange = (pageSize: number) => {
|
||||||
|
setPageSize(pageSize);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleNextPage = () => {
|
||||||
|
if (meta && currentPage < meta.total_pages) {
|
||||||
|
setCurrentPage(currentPage + 1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handlePrevPage = () => {
|
||||||
|
if (currentPage > 1) {
|
||||||
|
setCurrentPage(currentPage - 1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getTableColumns = (supplier: DebtSupplier): ColumnDef<DebtRow>[] => [
|
||||||
|
{
|
||||||
|
id: 'no',
|
||||||
|
header: 'No',
|
||||||
|
cell: (props) => props.row.index + 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'pr_number',
|
||||||
|
header: 'Nomor PR',
|
||||||
|
accessorKey: 'pr_number',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.pr_number;
|
||||||
|
return value || '-';
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'po_number',
|
||||||
|
header: 'Nomor PO',
|
||||||
|
accessorKey: 'po_number',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.po_number;
|
||||||
|
return value || '-';
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'received_date',
|
||||||
|
header: 'Tanggal Terima',
|
||||||
|
accessorKey: 'received_date',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.received_date;
|
||||||
|
return value
|
||||||
|
? value != '-'
|
||||||
|
? formatDate(value, 'DD MMM YYYY')
|
||||||
|
: '-'
|
||||||
|
: '-';
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'po_date',
|
||||||
|
header: 'Tanggal PO',
|
||||||
|
accessorKey: 'po_date',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.po_date;
|
||||||
|
return value
|
||||||
|
? value != '-'
|
||||||
|
? formatDate(value, 'DD MMM YYYY')
|
||||||
|
: '-'
|
||||||
|
: '-';
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'aging',
|
||||||
|
header: 'Aging',
|
||||||
|
accessorKey: 'aging',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.aging;
|
||||||
|
return <div className='text-center'>{formatNumber(value)} Hari</div>;
|
||||||
|
},
|
||||||
|
footer: () => {
|
||||||
|
const value = supplier.total.aging;
|
||||||
|
return <div className='text-center'>{formatNumber(value)} Hari</div>;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'area',
|
||||||
|
header: 'Area',
|
||||||
|
accessorKey: 'area',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.area?.name;
|
||||||
|
return value || '-';
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'warehouse',
|
||||||
|
header: 'Gudang',
|
||||||
|
accessorKey: 'warehouse',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.warehouse?.name;
|
||||||
|
return value || '-';
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'due_date',
|
||||||
|
header: 'Tanggal Jatuh Tempo',
|
||||||
|
accessorKey: 'due_date',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.due_date;
|
||||||
|
return value
|
||||||
|
? value != '-'
|
||||||
|
? formatDate(value, 'DD MMM YYYY')
|
||||||
|
: '-'
|
||||||
|
: '-';
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'due_status',
|
||||||
|
header: 'Status Jatuh Tempo',
|
||||||
|
accessorKey: 'due_status',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.due_status;
|
||||||
|
return value || '-';
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'total_price',
|
||||||
|
header: 'Total Harga',
|
||||||
|
accessorKey: 'total_price',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.total_price;
|
||||||
|
return (
|
||||||
|
<div className={`text-right ${value < 0 ? 'text-red-500' : ''}`}>
|
||||||
|
{formatCurrency(value)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
footer: () => {
|
||||||
|
const value = supplier.total.total_price;
|
||||||
|
return (
|
||||||
|
<div className={`text-right ${value < 0 ? 'text-red-500' : ''}`}>
|
||||||
|
{formatCurrency(value)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'payment_price',
|
||||||
|
header: 'Harga Pembayaran',
|
||||||
|
accessorKey: 'payment_price',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.payment_price;
|
||||||
|
return (
|
||||||
|
<div className={`text-right ${value < 0 ? 'text-red-500' : ''}`}>
|
||||||
|
{formatCurrency(value)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
footer: () => {
|
||||||
|
const value = supplier.total.payment_price;
|
||||||
|
return (
|
||||||
|
<div className={`text-right ${value < 0 ? 'text-red-500' : ''}`}>
|
||||||
|
{formatCurrency(value)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'debt_price',
|
||||||
|
header: 'Harga Hutang',
|
||||||
|
accessorKey: 'debt_price',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.debt_price;
|
||||||
|
return (
|
||||||
|
<div className={`text-right ${value < 0 ? 'text-red-500' : ''}`}>
|
||||||
|
{formatCurrency(value)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
footer: () => {
|
||||||
|
const value = supplier.total.debt_price;
|
||||||
|
return (
|
||||||
|
<div className={`text-right ${value < 0 ? 'text-red-500' : ''}`}>
|
||||||
|
{formatCurrency(value)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'status',
|
||||||
|
header: 'Status',
|
||||||
|
accessorKey: 'status',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.status;
|
||||||
|
return value || '-';
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'travel_number',
|
||||||
|
header: 'Nomor Perjalanan',
|
||||||
|
accessorKey: 'travel_number',
|
||||||
|
cell: (props) => {
|
||||||
|
const value = props.row.original.travel_number;
|
||||||
|
return value || '-';
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className='w-full p-0 sm:p-4 flex flex-col gap-4'>
|
||||||
|
<Card
|
||||||
|
subtitle='Laporan > Rekapitulasi Hutang ke Supplier'
|
||||||
|
className={{ wrapper: 'w-full', body: 'p-1!' }}
|
||||||
|
>
|
||||||
|
<div className='mb-4 flex justify-end gap-2 [&_button]:px-4'>
|
||||||
|
<Button variant='outline' onClick={filterModal.openModal}>
|
||||||
|
<Icon icon='heroicons:funnel' width={18} height={18} />
|
||||||
|
Filter
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Dropdown
|
||||||
|
trigger={
|
||||||
|
<Button variant='outline' isLoading={isAnyExportLoading}>
|
||||||
|
<Icon
|
||||||
|
icon='heroicons:cloud-arrow-down'
|
||||||
|
width={18}
|
||||||
|
height={18}
|
||||||
|
/>
|
||||||
|
Export
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
align='end'
|
||||||
|
>
|
||||||
|
<Menu>
|
||||||
|
<MenuItem title='Excel' onClick={handleExportExcel} />
|
||||||
|
<MenuItem title='PDF' onClick={handleExportPdf} />
|
||||||
|
</Menu>
|
||||||
|
</Dropdown>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{!isSubmitted ? (
|
||||||
|
<div className='mt-6 text-center text-gray-500'>
|
||||||
|
Silakan klik tombol Filter untuk mengatur filter dan menampilkan
|
||||||
|
data.
|
||||||
|
</div>
|
||||||
|
) : isLoading ? (
|
||||||
|
<div className='w-full flex flex-row justify-center items-center p-4'>
|
||||||
|
<span className='loading loading-spinner loading-xl' />
|
||||||
|
</div>
|
||||||
|
) : data.length === 0 ? (
|
||||||
|
<div className='mt-6 text-center text-gray-500'>
|
||||||
|
Tidak ada data yang dapat ditampilkan...
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
data.map((supplierReport) => {
|
||||||
|
return (
|
||||||
|
<Card
|
||||||
|
key={supplierReport.supplier.id}
|
||||||
|
title={supplierReport.supplier.name}
|
||||||
|
className={{ wrapper: 'w-full' }}
|
||||||
|
variant='bordered'
|
||||||
|
collapsible={true}
|
||||||
|
>
|
||||||
|
<Table
|
||||||
|
data={supplierReport.rows}
|
||||||
|
columns={getTableColumns(supplierReport)}
|
||||||
|
pageSize={supplierReport.rows.length}
|
||||||
|
renderFooter={supplierReport.rows.length > 0}
|
||||||
|
className={{
|
||||||
|
containerClassName: 'w-full',
|
||||||
|
tableWrapperClassName: 'overflow-x-auto mt-4',
|
||||||
|
tableClassName: 'w-full table-auto text-sm',
|
||||||
|
headerRowClassName: 'border-b border-b-gray-200 bg-gray-50',
|
||||||
|
headerColumnClassName:
|
||||||
|
'px-4 py-3 text-xs font-semibold text-gray-700 text-left border border-gray-200',
|
||||||
|
bodyRowClassName:
|
||||||
|
'hover:bg-gray-50 transition-colors border-b border-l border-r border-b-gray-200 border-l-gray-200 border-r-gray-200',
|
||||||
|
bodyColumnClassName:
|
||||||
|
'px-4 py-3 text-xs text-gray-900 whitespace-nowrap',
|
||||||
|
tableFooterClassName:
|
||||||
|
'bg-gray-100 font-semibold border border-gray-200',
|
||||||
|
footerRowClassName: 'border-t-2 border-gray-300',
|
||||||
|
footerColumnClassName:
|
||||||
|
'px-4 py-3 text-xs text-gray-900 whitespace-nowrap',
|
||||||
|
paginationClassName: 'hidden',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{meta && data.length > 0 && (
|
||||||
|
<div className='mt-6'>
|
||||||
|
<Pagination
|
||||||
|
currentPage={meta.page}
|
||||||
|
totalItems={meta.total_results}
|
||||||
|
onPageChange={handlePageChange}
|
||||||
|
onRowChange={handleRowChange}
|
||||||
|
onNextPage={handleNextPage}
|
||||||
|
onPrevPage={handlePrevPage}
|
||||||
|
rowOptions={[10, 25, 50, 100]}
|
||||||
|
itemsPerPage={meta.limit}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Filter Modal */}
|
||||||
|
<Modal
|
||||||
|
ref={filterModal.ref}
|
||||||
|
className={{
|
||||||
|
modal: 'p-0',
|
||||||
|
modalBox: 'p-0 rounded-2xl xl:max-w-4/12 max-w-sm',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className='space-y-6'>
|
||||||
|
{/* Modal Header */}
|
||||||
|
<div className='flex items-center justify-between gap-2 py-3 border-b border-gray-300 px-4'>
|
||||||
|
<div className='flex items-center gap-2 text-primary'>
|
||||||
|
<Icon icon='heroicons:funnel' width={20} height={20} />
|
||||||
|
<h3 className='font-semibold'>Filter Data</h3>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
variant='link'
|
||||||
|
onClick={filterModal.closeModal}
|
||||||
|
className='text-gray-500 hover:text-gray-700 transition-colors cursor-pointer'
|
||||||
|
>
|
||||||
|
<Icon icon='heroicons:x-mark' width={20} height={20} />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<div className='space-y-4 px-4'>
|
||||||
|
<div className='grid grid-cols-1 sm:grid-cols-2 sm:gap-4'>
|
||||||
|
<div>
|
||||||
|
<DateInput
|
||||||
|
label='Tanggal'
|
||||||
|
name='start_date'
|
||||||
|
value={filterStartDate}
|
||||||
|
onChange={(e) => {
|
||||||
|
setFilterStartDate(e.target.value);
|
||||||
|
setFilterErrors((prev) => ({ ...prev, start_date: '' }));
|
||||||
|
}}
|
||||||
|
className={{ wrapper: 'w-full' }}
|
||||||
|
/>
|
||||||
|
{filterErrors.start_date && (
|
||||||
|
<p className='text-red-500 text-sm mt-1'>
|
||||||
|
{filterErrors.start_date}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className='mt-auto'>
|
||||||
|
<DateInput
|
||||||
|
label=' '
|
||||||
|
name='end_date'
|
||||||
|
value={filterEndDate}
|
||||||
|
onChange={(e) => {
|
||||||
|
setFilterEndDate(e.target.value);
|
||||||
|
setFilterErrors((prev) => ({ ...prev, end_date: '' }));
|
||||||
|
}}
|
||||||
|
className={{ wrapper: 'w-full' }}
|
||||||
|
/>
|
||||||
|
{filterErrors.end_date && (
|
||||||
|
<p className='text-red-500 text-sm mt-1'>
|
||||||
|
{filterErrors.end_date}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<SelectInput
|
||||||
|
label='Supplier'
|
||||||
|
placeholder='Pilih Supplier'
|
||||||
|
isMulti
|
||||||
|
options={supplierOptions}
|
||||||
|
value={filterSupplier}
|
||||||
|
onChange={(val) => {
|
||||||
|
setFilterSupplier(
|
||||||
|
Array.isArray(val) ? val : val ? [val] : []
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
isLoading={isLoadingSuppliers}
|
||||||
|
isClearable
|
||||||
|
className={{ wrapper: 'w-full' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<SelectInput
|
||||||
|
label='Filter Berdasarkan'
|
||||||
|
placeholder='Pilih Filter Berdasarkan'
|
||||||
|
options={dataTypeOptions}
|
||||||
|
value={filterDateType}
|
||||||
|
onChange={(val) => {
|
||||||
|
setFilterDateType(val ? (val as OptionType) : undefined);
|
||||||
|
}}
|
||||||
|
className={{ wrapper: 'w-full' }}
|
||||||
|
isClearable
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Action Buttons */}
|
||||||
|
<div className='flex justify-between gap-4 py-4 mt-8 border-t border-gray-300 bg-gray-100'>
|
||||||
|
<Button
|
||||||
|
variant='soft'
|
||||||
|
className='ms-4 min-w-36 rounded-lg'
|
||||||
|
onClick={handleResetFilters}
|
||||||
|
>
|
||||||
|
Reset Filter
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
className='me-4 min-w-36 rounded-lg'
|
||||||
|
onClick={handleApplyFilters}
|
||||||
|
>
|
||||||
|
Apply Filter
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default DebtSupplierTab;
|
||||||
@@ -74,7 +74,23 @@ export const RECORDING_APPROVAL_LINE: ApprovalLine = [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
step_number: 2,
|
step_number: 2,
|
||||||
step_name: 'Disetujui',
|
step_name: 'Approval Head Area',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step_number: 3,
|
||||||
|
step_name: 'Approval Business Unit Vice President',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step_number: 4,
|
||||||
|
step_name: 'Approval Finance',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step_number: 5,
|
||||||
|
step_name: 'Realisasi',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step_number: 6,
|
||||||
|
step_name: 'Selesai',
|
||||||
},
|
},
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
@@ -130,18 +146,22 @@ export const EXPENSE_REQUEST_APPROVAL_LINE: ApprovalLine = [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
step_number: 2,
|
step_number: 2,
|
||||||
step_name: 'Approval Manager',
|
step_name: 'Approval Head Area',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
step_number: 3,
|
step_number: 3,
|
||||||
step_name: 'Approval Finance',
|
step_name: 'Approval Business Unit Vice President',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
step_number: 4,
|
step_number: 4,
|
||||||
step_name: 'Realisasi',
|
step_name: 'Approval Finance',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
step_number: 5,
|
step_number: 5,
|
||||||
|
step_name: 'Realisasi',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step_number: 6,
|
||||||
step_name: 'Selesai',
|
step_name: 'Selesai',
|
||||||
},
|
},
|
||||||
] as const;
|
] as const;
|
||||||
|
|||||||
@@ -60,6 +60,12 @@ export const MAIN_DRAWER_LINKS: SidebarMenuItem[] = [
|
|||||||
// TODO: add permission
|
// TODO: add permission
|
||||||
// permission: ['lti.daily_checklist.list'],
|
// permission: ['lti.daily_checklist.list'],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
text: 'Konfigurasi',
|
||||||
|
link: '/daily-checklist/master-data/configuration',
|
||||||
|
// TODO: add permission
|
||||||
|
// permission: ['lti.daily_checklist.list'],
|
||||||
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -127,6 +133,10 @@ export const MAIN_DRAWER_LINKS: SidebarMenuItem[] = [
|
|||||||
link: '/report',
|
link: '/report',
|
||||||
icon: 'mdi:chart-box-outline',
|
icon: 'mdi:chart-box-outline',
|
||||||
submenu: [
|
submenu: [
|
||||||
|
{
|
||||||
|
text: 'Keuangan',
|
||||||
|
link: '/report/finance',
|
||||||
|
},
|
||||||
{
|
{
|
||||||
text: 'Logistik & Persediaan',
|
text: 'Logistik & Persediaan',
|
||||||
link: '/report/logistic-stock',
|
link: '/report/logistic-stock',
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ export const ROUTE_PERMISSIONS: Record<string, string[]> = {
|
|||||||
'/daily-checklist/reports/': ['lti.dashboard.list'],
|
'/daily-checklist/reports/': ['lti.dashboard.list'],
|
||||||
'/daily-checklist/master-data/employee/': ['lti.dashboard.list'],
|
'/daily-checklist/master-data/employee/': ['lti.dashboard.list'],
|
||||||
'/daily-checklist/master-data/activity/': ['lti.dashboard.list'],
|
'/daily-checklist/master-data/activity/': ['lti.dashboard.list'],
|
||||||
|
'/daily-checklist/master-data/configuration/': ['lti.dashboard.list'],
|
||||||
|
|
||||||
// Production
|
// Production
|
||||||
// Production - Project Flock
|
// Production - Project Flock
|
||||||
@@ -117,6 +118,10 @@ export const ROUTE_PERMISSIONS: Record<string, string[]> = {
|
|||||||
'/report/expense/': ['lti.repport.expense.list'],
|
'/report/expense/': ['lti.repport.expense.list'],
|
||||||
'/report/marketing/': ['lti.repport.delivery.list'],
|
'/report/marketing/': ['lti.repport.delivery.list'],
|
||||||
'/report/production-result/': ['lti.repport.production_result.list'],
|
'/report/production-result/': ['lti.repport.production_result.list'],
|
||||||
|
'/report/finance/': [
|
||||||
|
'lti.repport.finance.list',
|
||||||
|
'lti.repport.debtsupplier.list',
|
||||||
|
],
|
||||||
|
|
||||||
// Inventory
|
// Inventory
|
||||||
'/inventory/adjustment/': ['lti.inventory.list'],
|
'/inventory/adjustment/': ['lti.inventory.list'],
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,39 +0,0 @@
|
|||||||
/**
|
|
||||||
* Dummy data for DashboardProduction
|
|
||||||
* Generated from: dashboard.production.dummy.json
|
|
||||||
*
|
|
||||||
* This file is auto-generated. Do not edit manually.
|
|
||||||
*/
|
|
||||||
|
|
||||||
import {
|
|
||||||
DashboardProductionStatisticsData,
|
|
||||||
DashboardProductionProductionChartsFlocks,
|
|
||||||
DashboardProductionProductionCharts,
|
|
||||||
DashboardProductionStandardProductionsStandards,
|
|
||||||
DashboardProductionStandardProductions,
|
|
||||||
DashboardProductionFcrDataFlock,
|
|
||||||
DashboardProductionEggWeights,
|
|
||||||
DashboardProductionFcrData,
|
|
||||||
DashboardProduction,
|
|
||||||
} from '../../types/api/dashboard/dashboard-production';
|
|
||||||
import { BaseApiResponse } from '@/types/api/api-general';
|
|
||||||
import dummyData from './dashboard.production.dummy.json';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get dummy DashboardProduction data
|
|
||||||
* @returns Promise with BaseApiResponse containing DashboardProduction
|
|
||||||
*/
|
|
||||||
export async function getDummySingle(): Promise<
|
|
||||||
BaseApiResponse<DashboardProduction>
|
|
||||||
> {
|
|
||||||
return new Promise((resolve) => {
|
|
||||||
setTimeout(() => {
|
|
||||||
resolve({
|
|
||||||
code: 200,
|
|
||||||
status: 'success',
|
|
||||||
message: 'Data retrieved successfully',
|
|
||||||
data: dummyData as unknown as DashboardProduction,
|
|
||||||
});
|
|
||||||
}, 500);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -30,7 +30,7 @@ import { KandangApi } from '@/services/api/master-data';
|
|||||||
import { DailyChecklistApi } from '@/services/api/daily-checklist/daily-checklist';
|
import { DailyChecklistApi } from '@/services/api/daily-checklist/daily-checklist';
|
||||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||||
import useSWR from 'swr';
|
import useSWR from 'swr';
|
||||||
import { BaseApiResponse } from '@/types/api/api-general';
|
import { BaseApiResponse, Document } from '@/types/api/api-general';
|
||||||
import { AxiosError } from 'axios';
|
import { AxiosError } from 'axios';
|
||||||
import { httpClientFetcher, SWRHttpKey } from '@/services/http/client';
|
import { httpClientFetcher, SWRHttpKey } from '@/services/http/client';
|
||||||
import { PhaseApi } from '@/services/api/daily-checklist/phase';
|
import { PhaseApi } from '@/services/api/daily-checklist/phase';
|
||||||
@@ -39,6 +39,9 @@ import { Employee } from '@/types/api/daily-checklist/employee';
|
|||||||
import { PhaseActivityApi } from '@/services/api/daily-checklist/phase-activity';
|
import { PhaseActivityApi } from '@/services/api/daily-checklist/phase-activity';
|
||||||
import { PhaseActivity } from '@/types/api/daily-checklist/phase-activity';
|
import { PhaseActivity } from '@/types/api/daily-checklist/phase-activity';
|
||||||
import DebouncedTextArea from '@/components/input/DebouncedTextArea';
|
import DebouncedTextArea from '@/components/input/DebouncedTextArea';
|
||||||
|
import DropFileInput from '@/components/input/DropFileInput';
|
||||||
|
import Link from 'next/link';
|
||||||
|
import { Icon } from '@iconify/react';
|
||||||
|
|
||||||
// Static categories
|
// Static categories
|
||||||
const CATEGORIES = [
|
const CATEGORIES = [
|
||||||
@@ -148,6 +151,10 @@ export function DailyChecklistContent() {
|
|||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [initialLoading, setInitialLoading] = useState(true);
|
const [initialLoading, setInitialLoading] = useState(true);
|
||||||
|
|
||||||
|
const [existingDocuments, setExistingDocuments] = useState<Document[]>([]);
|
||||||
|
const [documents, setDocuments] = useState<File[]>([]);
|
||||||
|
const [deletedDocumentIds, setDeletedDocumentIds] = useState<number[]>([]);
|
||||||
|
|
||||||
// Format date for display
|
// Format date for display
|
||||||
const formatDateForDisplay = (dateStr: string) => {
|
const formatDateForDisplay = (dateStr: string) => {
|
||||||
if (!dateStr) return 'Pilih tanggal';
|
if (!dateStr) return 'Pilih tanggal';
|
||||||
@@ -340,6 +347,9 @@ export function DailyChecklistContent() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// set existing document
|
||||||
|
setExistingDocuments(existingDailyChecklist?.data.document_urls || []);
|
||||||
|
|
||||||
// Build assignments map
|
// Build assignments map
|
||||||
const assignmentMap: {
|
const assignmentMap: {
|
||||||
[taskId: string]: {
|
[taskId: string]: {
|
||||||
@@ -729,7 +739,11 @@ export function DailyChecklistContent() {
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const submitRes = await DailyChecklistApi.submit(dailyChecklistId);
|
const submitRes = await DailyChecklistApi.submit(
|
||||||
|
dailyChecklistId,
|
||||||
|
documents,
|
||||||
|
deletedDocumentIds
|
||||||
|
);
|
||||||
|
|
||||||
if (isResponseError(submitRes)) {
|
if (isResponseError(submitRes)) {
|
||||||
console.error('Error submitting:', submitRes.message);
|
console.error('Error submitting:', submitRes.message);
|
||||||
@@ -750,6 +764,19 @@ export function DailyChecklistContent() {
|
|||||||
const handleSaveDraft = async () => {
|
const handleSaveDraft = async () => {
|
||||||
if (!dailyChecklistId) return;
|
if (!dailyChecklistId) return;
|
||||||
|
|
||||||
|
const uploadImageRes = await DailyChecklistApi.uploadImage(
|
||||||
|
Number(dailyChecklistId),
|
||||||
|
'DRAFT',
|
||||||
|
documents,
|
||||||
|
deletedDocumentIds
|
||||||
|
);
|
||||||
|
|
||||||
|
if (isResponseError(uploadImageRes)) {
|
||||||
|
console.error('Error saving draft:', uploadImageRes.message);
|
||||||
|
toast.error('Gagal menyimpan draft');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
toast.success('Draft tersimpan otomatis');
|
toast.success('Draft tersimpan otomatis');
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -1263,6 +1290,94 @@ export function DailyChecklistContent() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{dailyChecklistId &&
|
||||||
|
selectedPhaseIds.length > 0 &&
|
||||||
|
selectedEmployees.length > 0 && (
|
||||||
|
<>
|
||||||
|
{existingDocuments.length > 0 && (
|
||||||
|
<div className='mt-6'>
|
||||||
|
<h3 className='font-semibold text-gray-900 mb-2'>
|
||||||
|
Dokumen yang telah diupload
|
||||||
|
</h3>
|
||||||
|
{existingDocuments.map(
|
||||||
|
(existingDocument, existingDocumentIdx) => (
|
||||||
|
<div
|
||||||
|
key={existingDocumentIdx}
|
||||||
|
className='w-full flex flex-wrap justify-between'
|
||||||
|
>
|
||||||
|
<Link
|
||||||
|
href={existingDocument.url}
|
||||||
|
target='_blank'
|
||||||
|
rel='noopener noreferrer'
|
||||||
|
className='text-blue-500 underline'
|
||||||
|
>
|
||||||
|
{existingDocument.name}{' '}
|
||||||
|
<Icon
|
||||||
|
icon='cuida:open-in-new-tab-outline'
|
||||||
|
width={12}
|
||||||
|
height={12}
|
||||||
|
className='inline'
|
||||||
|
/>
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
type='button'
|
||||||
|
variant='ghost'
|
||||||
|
color='error'
|
||||||
|
onClick={() => {
|
||||||
|
setDeletedDocumentIds((prevIds) => [
|
||||||
|
...prevIds,
|
||||||
|
existingDocument.id,
|
||||||
|
]);
|
||||||
|
|
||||||
|
setExistingDocuments((prevExistingDocument) => {
|
||||||
|
const newExistingDocuments = [
|
||||||
|
...prevExistingDocument,
|
||||||
|
];
|
||||||
|
newExistingDocuments.splice(
|
||||||
|
existingDocumentIdx,
|
||||||
|
1
|
||||||
|
);
|
||||||
|
return newExistingDocuments;
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
className='p-1 rounded-full text-error focus-visible:text-error-content hover:text-error-content'
|
||||||
|
>
|
||||||
|
<Icon
|
||||||
|
icon='fluent:delete-12-regular'
|
||||||
|
width={20}
|
||||||
|
height={20}
|
||||||
|
/>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<DropFileInput
|
||||||
|
name='Dokumen'
|
||||||
|
label='Dokumen'
|
||||||
|
values={documents}
|
||||||
|
onChange={(files) => {
|
||||||
|
setDocuments(files);
|
||||||
|
}}
|
||||||
|
onDelete={(deletedFileIdx: number) => {
|
||||||
|
const newRequestDocuments = [...documents];
|
||||||
|
|
||||||
|
newRequestDocuments?.splice(deletedFileIdx, 1);
|
||||||
|
|
||||||
|
setDocuments(newRequestDocuments);
|
||||||
|
}}
|
||||||
|
className={{
|
||||||
|
wrapper: 'mt-6',
|
||||||
|
inputWrapper: 'flex items-center',
|
||||||
|
label: 'font-semibold text-gray-900',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Action Buttons */}
|
{/* Action Buttons */}
|
||||||
{dailyChecklistId &&
|
{dailyChecklistId &&
|
||||||
selectedPhaseIds.length > 0 &&
|
selectedPhaseIds.length > 0 &&
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useState, useEffect } from 'react';
|
import { useState } from 'react';
|
||||||
import {
|
import {
|
||||||
Card,
|
Card,
|
||||||
CardContent,
|
CardContent,
|
||||||
@@ -15,7 +15,6 @@ import {
|
|||||||
SelectTrigger,
|
SelectTrigger,
|
||||||
SelectValue,
|
SelectValue,
|
||||||
} from '@/figma-make/components/base/select';
|
} from '@/figma-make/components/base/select';
|
||||||
import { Input } from '@/figma-make/components/base/input';
|
|
||||||
import { Badge } from '@/figma-make/components/base/badge';
|
import { Badge } from '@/figma-make/components/base/badge';
|
||||||
import {
|
import {
|
||||||
Calendar as CalendarIcon,
|
Calendar as CalendarIcon,
|
||||||
@@ -35,53 +34,17 @@ import {
|
|||||||
ResponsiveContainer,
|
ResponsiveContainer,
|
||||||
Cell,
|
Cell,
|
||||||
} from 'recharts';
|
} from 'recharts';
|
||||||
import { supabase, isSupabaseConfigured } from '@/figma-make/lib/supabase';
|
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
|
import useSWR from 'swr';
|
||||||
interface EmployeePerformance {
|
import { BaseApiResponse } from '@/types/api/api-general';
|
||||||
employee_id: string;
|
import { DailyChecklistSummary } from '@/types/api/daily-checklist/daily-checklist';
|
||||||
employee_name: string;
|
import { AxiosError } from 'axios';
|
||||||
kandang_id: string;
|
import { httpClientFetcher, SWRHttpKey } from '@/services/http/client';
|
||||||
kandang_name: string;
|
import { DailyChecklistApi } from '@/services/api/daily-checklist/daily-checklist';
|
||||||
total_activities_in_category: number; // Total aktivitas di kategori
|
import { KandangApi } from '@/services/api/master-data';
|
||||||
completed_activities: number; // Aktivitas yang sudah di-check
|
import { useSelect } from '@/components/input/SelectInput';
|
||||||
completion_rate: number;
|
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||||
last_activity_date: string | null;
|
import { formatDate } from '@/lib/helper';
|
||||||
color: string; // Color based on kandang
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Kandang {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Category {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ChecklistKandang {
|
|
||||||
id: string;
|
|
||||||
date: string;
|
|
||||||
kandang_id: string;
|
|
||||||
category: string;
|
|
||||||
kandang: {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
} | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AssignmentEmployee {
|
|
||||||
id: string;
|
|
||||||
task_id: string;
|
|
||||||
employee_id: string;
|
|
||||||
checked: boolean;
|
|
||||||
updated_at: string;
|
|
||||||
employee: {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
} | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const KANDANG_COLORS = [
|
const KANDANG_COLORS = [
|
||||||
'#0069e0', // Blue (primary)
|
'#0069e0', // Blue (primary)
|
||||||
@@ -102,312 +65,65 @@ const CATEGORY_LABELS: { [key: string]: string } = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export function Dashboard() {
|
export function Dashboard() {
|
||||||
const [loading, setLoading] = useState(false);
|
|
||||||
const [employeePerformance, setEmployeePerformance] = useState<
|
|
||||||
EmployeePerformance[]
|
|
||||||
>([]);
|
|
||||||
|
|
||||||
// Master data
|
|
||||||
const [kandangList, setKandangList] = useState<Kandang[]>([]);
|
|
||||||
const [categoryList, setCategoryList] = useState<Category[]>([]);
|
|
||||||
|
|
||||||
// Filters
|
// Filters
|
||||||
const [dateFrom, setDateFrom] = useState('');
|
const [dateFrom, setDateFrom] = useState('');
|
||||||
const [dateTo, setDateTo] = useState('');
|
const [dateTo, setDateTo] = useState('');
|
||||||
const [kandangFilter, setKandangFilter] = useState('ALL');
|
const [kandangFilter, setKandangFilter] = useState('ALL');
|
||||||
const [categoryFilter, setCategoryFilter] = useState('ALL');
|
const [categoryFilter, setCategoryFilter] = useState('ALL');
|
||||||
|
|
||||||
// Color mapping for kandang
|
const {
|
||||||
const [kandangColorMap, setKandangColorMap] = useState<{
|
data: summaryResponse,
|
||||||
[key: string]: string;
|
isLoading: isLoadingSummary,
|
||||||
}>({});
|
mutate: refreshSummary,
|
||||||
|
} = useSWR<
|
||||||
useEffect(() => {
|
BaseApiResponse<DailyChecklistSummary | undefined>,
|
||||||
fetchMasterData();
|
AxiosError<BaseApiResponse>,
|
||||||
}, []);
|
SWRHttpKey
|
||||||
|
>(
|
||||||
useEffect(() => {
|
dateFrom && dateTo
|
||||||
// Only fetch when date filters are set
|
? `${DailyChecklistApi.basePath}/summary?date_from=${dateFrom}&date_to=${dateTo}&kandang_id=${kandangFilter === 'ALL' ? '' : kandangFilter}&category=${categoryFilter === 'ALL' ? '' : categoryFilter}`
|
||||||
if (dateFrom && dateTo) {
|
: '',
|
||||||
fetchEmployeePerformance();
|
httpClientFetcher,
|
||||||
} else {
|
|
||||||
setEmployeePerformance([]);
|
|
||||||
}
|
|
||||||
}, [dateFrom, dateTo, kandangFilter, categoryFilter]);
|
|
||||||
|
|
||||||
const fetchMasterData = async () => {
|
|
||||||
if (!isSupabaseConfigured()) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Fetch kandang
|
|
||||||
const { data: kandangData, error: kandangError } = await supabase
|
|
||||||
.from('kandang')
|
|
||||||
.select('id, name')
|
|
||||||
.order('name', { ascending: true });
|
|
||||||
|
|
||||||
if (kandangError) {
|
|
||||||
console.error('Error fetching kandang:', kandangError);
|
|
||||||
} else {
|
|
||||||
setKandangList(kandangData || []);
|
|
||||||
|
|
||||||
// Create color mapping
|
|
||||||
const colorMap: { [key: string]: string } = {};
|
|
||||||
(kandangData || []).forEach((k, index) => {
|
|
||||||
colorMap[k.id] = KANDANG_COLORS[index % KANDANG_COLORS.length];
|
|
||||||
});
|
|
||||||
setKandangColorMap(colorMap);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set categories from CATEGORY_LABELS (hardcoded list)
|
|
||||||
const categories: Category[] = Object.keys(CATEGORY_LABELS).map((id) => ({
|
|
||||||
id,
|
|
||||||
name: CATEGORY_LABELS[id],
|
|
||||||
}));
|
|
||||||
setCategoryList(categories);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error fetching master data:', error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchEmployeePerformance = async () => {
|
|
||||||
if (!isSupabaseConfigured() || !dateFrom || !dateTo) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
setLoading(true);
|
|
||||||
|
|
||||||
// Step 1: Get all checklists in date range + filters
|
|
||||||
let checklistQuery = supabase
|
|
||||||
.from('daily_checklists')
|
|
||||||
.select(
|
|
||||||
`
|
|
||||||
id,
|
|
||||||
date,
|
|
||||||
kandang_id,
|
|
||||||
category,
|
|
||||||
kandang:kandang_id (
|
|
||||||
id,
|
|
||||||
name
|
|
||||||
)
|
|
||||||
`
|
|
||||||
)
|
|
||||||
.gte('date', dateFrom)
|
|
||||||
.lte('date', dateTo);
|
|
||||||
|
|
||||||
if (kandangFilter !== 'ALL') {
|
|
||||||
checklistQuery = checklistQuery.eq('kandang_id', kandangFilter);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (categoryFilter !== 'ALL') {
|
|
||||||
checklistQuery = checklistQuery.eq('category', categoryFilter);
|
|
||||||
}
|
|
||||||
|
|
||||||
const { data: checklists, error: checklistError } = await checklistQuery;
|
|
||||||
|
|
||||||
if (checklistError) {
|
|
||||||
console.error('Error fetching checklists:', checklistError);
|
|
||||||
toast.error('Gagal memuat data checklist');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!checklists || checklists.length === 0) {
|
|
||||||
setEmployeePerformance([]);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const checklistsData = checklists as unknown as ChecklistKandang[];
|
|
||||||
|
|
||||||
// Step 2: Get all tasks from these checklists
|
|
||||||
const checklistIds = checklistsData.map((c) => c.id);
|
|
||||||
const { data: tasks, error: tasksError } = await supabase
|
|
||||||
.from('daily_checklist_activity_tasks')
|
|
||||||
.select('id, checklist_id')
|
|
||||||
.in('checklist_id', checklistIds);
|
|
||||||
|
|
||||||
if (tasksError) {
|
|
||||||
console.error('Error fetching tasks:', tasksError);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!tasks || tasks.length === 0) {
|
|
||||||
setEmployeePerformance([]);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const taskIds = tasks.map((t) => t.id);
|
|
||||||
|
|
||||||
// Step 3: Get all assignments for these tasks
|
|
||||||
const { data: assignments, error: assignmentsError } = await supabase
|
|
||||||
.from('daily_checklist_activity_task_assignments')
|
|
||||||
.select(
|
|
||||||
`
|
|
||||||
id,
|
|
||||||
task_id,
|
|
||||||
employee_id,
|
|
||||||
checked,
|
|
||||||
updated_at,
|
|
||||||
employee:employee_id (
|
|
||||||
id,
|
|
||||||
name
|
|
||||||
)
|
|
||||||
`
|
|
||||||
)
|
|
||||||
.in('task_id', taskIds);
|
|
||||||
|
|
||||||
if (assignmentsError) {
|
|
||||||
console.error('Error fetching assignments:', assignmentsError);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!assignments || assignments.length === 0) {
|
|
||||||
setEmployeePerformance([]);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const assignmentsData = assignments as unknown as AssignmentEmployee[];
|
|
||||||
|
|
||||||
// Step 4: Calculate total activities in selected category (if filtered)
|
|
||||||
let totalActivitiesInCategory = 0;
|
|
||||||
|
|
||||||
if (categoryFilter !== 'ALL') {
|
|
||||||
// Get total activities from master data for this category
|
|
||||||
const { data: phases } = await supabase
|
|
||||||
.from('phases')
|
|
||||||
.select('id')
|
|
||||||
.eq('category_id', categoryFilter);
|
|
||||||
|
|
||||||
if (phases && phases.length > 0) {
|
|
||||||
const phaseIds = phases.map((p) => p.id);
|
|
||||||
const { count } = await supabase
|
|
||||||
.from('activities')
|
|
||||||
.select('*', { count: 'exact', head: true })
|
|
||||||
.in('phase_id', phaseIds);
|
|
||||||
|
|
||||||
totalActivitiesInCategory = count || 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Step 5: Group by employee and calculate performance
|
|
||||||
const employeeMap = new Map<
|
|
||||||
string,
|
|
||||||
{
|
{
|
||||||
employee_id: string;
|
keepPreviousData: true,
|
||||||
employee_name: string;
|
|
||||||
kandang_id: string;
|
|
||||||
kandang_name: string;
|
|
||||||
completed_count: number;
|
|
||||||
total_count: number;
|
|
||||||
last_activity_date: string | null;
|
|
||||||
}
|
}
|
||||||
>();
|
|
||||||
|
|
||||||
assignmentsData.forEach((assignment) => {
|
|
||||||
const task = tasks.find((t) => t.id === assignment.task_id);
|
|
||||||
if (!task) return;
|
|
||||||
|
|
||||||
const checklist = checklistsData.find(
|
|
||||||
(c) => c.id === task.checklist_id
|
|
||||||
);
|
);
|
||||||
if (!checklist) return;
|
|
||||||
|
|
||||||
const employeeId = assignment.employee_id;
|
const { options: kandangOptions, isLoadingOptions: isLoadingKandangs } =
|
||||||
const employeeName = assignment.employee?.name || 'Unknown';
|
useSelect(KandangApi.basePath, 'id', 'name', 'search', {
|
||||||
const kandangId = checklist.kandang_id;
|
page: '1',
|
||||||
const kandangName = checklist.kandang?.name || 'Unknown';
|
limit: '100',
|
||||||
|
|
||||||
if (!employeeMap.has(employeeId)) {
|
|
||||||
employeeMap.set(employeeId, {
|
|
||||||
employee_id: employeeId,
|
|
||||||
employee_name: employeeName,
|
|
||||||
kandang_id: kandangId,
|
|
||||||
kandang_name: kandangName,
|
|
||||||
completed_count: 0,
|
|
||||||
total_count: 0,
|
|
||||||
last_activity_date: null,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const empData = employeeMap.get(employeeId)!;
|
|
||||||
empData.total_count += 1;
|
|
||||||
|
|
||||||
if (assignment.checked) {
|
|
||||||
empData.completed_count += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update last activity date
|
|
||||||
if (assignment.updated_at) {
|
|
||||||
if (
|
|
||||||
!empData.last_activity_date ||
|
|
||||||
assignment.updated_at > empData.last_activity_date
|
|
||||||
) {
|
|
||||||
empData.last_activity_date = assignment.updated_at;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Step 6: Convert to array and add calculated fields
|
const kandangColorMap: { [key: string]: string } = {};
|
||||||
const performanceData: EmployeePerformance[] = Array.from(
|
(kandangOptions || []).forEach((k, index) => {
|
||||||
employeeMap.values()
|
kandangColorMap[k.value] = KANDANG_COLORS[index % KANDANG_COLORS.length];
|
||||||
).map((emp) => {
|
});
|
||||||
// Use total activities in category if category is selected, otherwise use employee's assigned count
|
|
||||||
const totalActivities =
|
|
||||||
categoryFilter !== 'ALL' && totalActivitiesInCategory > 0
|
|
||||||
? totalActivitiesInCategory
|
|
||||||
: emp.total_count;
|
|
||||||
|
|
||||||
|
const employeePerformance = isResponseSuccess(summaryResponse)
|
||||||
|
? summaryResponse.data?.tracking_abk.map((abk) => {
|
||||||
return {
|
return {
|
||||||
employee_id: emp.employee_id,
|
...abk,
|
||||||
employee_name: emp.employee_name,
|
color: kandangColorMap[abk.kandang_id] || '#0069e0',
|
||||||
kandang_id: emp.kandang_id,
|
|
||||||
kandang_name: emp.kandang_name,
|
|
||||||
total_activities_in_category: totalActivities,
|
|
||||||
completed_activities: emp.completed_count,
|
|
||||||
completion_rate:
|
|
||||||
totalActivities > 0
|
|
||||||
? Math.round((emp.completed_count / totalActivities) * 100)
|
|
||||||
: 0,
|
|
||||||
last_activity_date: emp.last_activity_date,
|
|
||||||
color: kandangColorMap[emp.kandang_id] || '#0069e0',
|
|
||||||
};
|
};
|
||||||
});
|
})
|
||||||
|
: [];
|
||||||
|
|
||||||
// Sort by employee name
|
const chartData = employeePerformance?.map((emp) => ({
|
||||||
performanceData.sort((a, b) =>
|
|
||||||
a.employee_name.localeCompare(b.employee_name)
|
|
||||||
);
|
|
||||||
|
|
||||||
setEmployeePerformance(performanceData);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error fetching employee performance:', error);
|
|
||||||
toast.error('Terjadi kesalahan saat memuat data');
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const formatDate = (dateString: string | null) => {
|
|
||||||
if (!dateString) return '-';
|
|
||||||
const date = new Date(dateString);
|
|
||||||
return date.toLocaleDateString('id-ID', {
|
|
||||||
day: '2-digit',
|
|
||||||
month: 'short',
|
|
||||||
year: 'numeric',
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const hasFilters = dateFrom && dateTo;
|
|
||||||
|
|
||||||
// Prepare chart data
|
|
||||||
const chartData = employeePerformance.map((emp) => ({
|
|
||||||
name: emp.employee_name,
|
name: emp.employee_name,
|
||||||
completed: emp.completed_activities,
|
completed: emp.activity_done,
|
||||||
remaining: emp.total_activities_in_category - emp.completed_activities,
|
remaining: emp.activity_left,
|
||||||
total: emp.total_activities_in_category,
|
total: emp.total_activity,
|
||||||
color: emp.color,
|
color: emp.color,
|
||||||
kandang: emp.kandang_name,
|
kandang: emp.kandang_name,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
const hasFilters = dateFrom && dateTo;
|
||||||
|
|
||||||
|
if (summaryResponse && isResponseError(summaryResponse)) {
|
||||||
|
toast.error('Gagal memuat data: ' + summaryResponse.message);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className='min-h-screen'>
|
<div className='min-h-screen'>
|
||||||
<div className='p-6'>
|
<div className='p-6'>
|
||||||
@@ -457,9 +173,12 @@ export function Dashboard() {
|
|||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value='ALL'>Semua Kandang</SelectItem>
|
<SelectItem value='ALL'>Semua Kandang</SelectItem>
|
||||||
{kandangList.map((kandang) => (
|
{kandangOptions.map((kandang) => (
|
||||||
<SelectItem key={kandang.id} value={kandang.id}>
|
<SelectItem
|
||||||
{kandang.name}
|
key={kandang.value}
|
||||||
|
value={String(kandang.value)}
|
||||||
|
>
|
||||||
|
{kandang.label}
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
))}
|
))}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
@@ -482,9 +201,9 @@ export function Dashboard() {
|
|||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value='ALL'>Semua Kategori</SelectItem>
|
<SelectItem value='ALL'>Semua Kategori</SelectItem>
|
||||||
{categoryList.map((category) => (
|
{Object.keys(CATEGORY_LABELS).map((category) => (
|
||||||
<SelectItem key={category.id} value={category.id}>
|
<SelectItem key={category} value={category}>
|
||||||
{category.name}
|
{CATEGORY_LABELS[category]}
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
))}
|
))}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
@@ -523,11 +242,11 @@ export function Dashboard() {
|
|||||||
melihat performance ABK.
|
melihat performance ABK.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
) : loading ? (
|
) : isLoadingSummary ? (
|
||||||
<div className='text-center py-16 text-gray-500'>
|
<div className='text-center py-16 text-gray-500'>
|
||||||
Memuat data...
|
Memuat data...
|
||||||
</div>
|
</div>
|
||||||
) : employeePerformance.length === 0 ? (
|
) : employeePerformance && employeePerformance.length === 0 ? (
|
||||||
<div className='flex flex-col items-center justify-center py-16 text-center'>
|
<div className='flex flex-col items-center justify-center py-16 text-center'>
|
||||||
<Users className='w-16 h-16 text-gray-300 mb-4' />
|
<Users className='w-16 h-16 text-gray-300 mb-4' />
|
||||||
<h3 className='text-lg font-semibold text-gray-700 mb-2'>
|
<h3 className='text-lg font-semibold text-gray-700 mb-2'>
|
||||||
@@ -582,7 +301,7 @@ export function Dashboard() {
|
|||||||
fill='#10B981'
|
fill='#10B981'
|
||||||
radius={[0, 0, 0, 0]}
|
radius={[0, 0, 0, 0]}
|
||||||
>
|
>
|
||||||
{chartData.map((entry, index) => (
|
{chartData?.map((entry, index) => (
|
||||||
<Cell
|
<Cell
|
||||||
key={`cell-completed-${index}`}
|
key={`cell-completed-${index}`}
|
||||||
fill={entry.color}
|
fill={entry.color}
|
||||||
@@ -595,7 +314,7 @@ export function Dashboard() {
|
|||||||
fill='#E5E7EB'
|
fill='#E5E7EB'
|
||||||
radius={[4, 4, 0, 0]}
|
radius={[4, 4, 0, 0]}
|
||||||
>
|
>
|
||||||
{chartData.map((entry, index) => (
|
{chartData?.map((entry, index) => (
|
||||||
<Cell
|
<Cell
|
||||||
key={`cell-remaining-${index}`}
|
key={`cell-remaining-${index}`}
|
||||||
fill={`${entry.color}33`}
|
fill={`${entry.color}33`}
|
||||||
@@ -610,7 +329,9 @@ export function Dashboard() {
|
|||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
{/* Employee Tracking Table */}
|
{/* Employee Tracking Table */}
|
||||||
{hasFilters && employeePerformance.length > 0 && (
|
{hasFilters &&
|
||||||
|
employeePerformance &&
|
||||||
|
employeePerformance.length > 0 && (
|
||||||
<Card className='border-gray-200/60 shadow-sm rounded-xl bg-white'>
|
<Card className='border-gray-200/60 shadow-sm rounded-xl bg-white'>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className='text-lg'>Tracking ABK</CardTitle>
|
<CardTitle className='text-lg'>Tracking ABK</CardTitle>
|
||||||
@@ -647,7 +368,7 @@ export function Dashboard() {
|
|||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{employeePerformance.map((emp, index) => (
|
{employeePerformance?.map((emp, index) => (
|
||||||
<tr
|
<tr
|
||||||
key={emp.employee_id}
|
key={emp.employee_id}
|
||||||
className={
|
className={
|
||||||
@@ -670,14 +391,13 @@ export function Dashboard() {
|
|||||||
</Badge>
|
</Badge>
|
||||||
</td>
|
</td>
|
||||||
<td className='py-3 px-4 text-center text-sm text-gray-900'>
|
<td className='py-3 px-4 text-center text-sm text-gray-900'>
|
||||||
{emp.total_activities_in_category}
|
{emp.total_activity}
|
||||||
</td>
|
</td>
|
||||||
<td className='py-3 px-4 text-center text-sm font-semibold text-green-700'>
|
<td className='py-3 px-4 text-center text-sm font-semibold text-green-700'>
|
||||||
{emp.completed_activities}
|
{emp.activity_done}
|
||||||
</td>
|
</td>
|
||||||
<td className='py-3 px-4 text-center text-sm text-gray-600'>
|
<td className='py-3 px-4 text-center text-sm text-gray-600'>
|
||||||
{emp.total_activities_in_category -
|
{emp.activity_left}
|
||||||
emp.completed_activities}
|
|
||||||
</td>
|
</td>
|
||||||
<td className='py-3 px-4 text-center'>
|
<td className='py-3 px-4 text-center'>
|
||||||
<div className='flex items-center justify-center gap-2'>
|
<div className='flex items-center justify-center gap-2'>
|
||||||
@@ -696,7 +416,7 @@ export function Dashboard() {
|
|||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td className='py-3 px-4 text-sm text-gray-600'>
|
<td className='py-3 px-4 text-sm text-gray-600'>
|
||||||
{formatDate(emp.last_activity_date)}
|
{formatDate(emp.last_activity, 'DD MMM YYYY')}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
|
|||||||
+37
@@ -20,6 +20,9 @@ import { toast } from 'sonner';
|
|||||||
import { useRouter, useSearchParams } from 'next/navigation';
|
import { useRouter, useSearchParams } from 'next/navigation';
|
||||||
import { DailyChecklistApi } from '@/services/api/daily-checklist/daily-checklist';
|
import { DailyChecklistApi } from '@/services/api/daily-checklist/daily-checklist';
|
||||||
import { isResponseError } from '@/lib/api-helper';
|
import { isResponseError } from '@/lib/api-helper';
|
||||||
|
import Link from 'next/link';
|
||||||
|
import { Icon } from '@iconify/react';
|
||||||
|
import { Document } from '@/types/api/api-general';
|
||||||
|
|
||||||
interface ChecklistDetailRow {
|
interface ChecklistDetailRow {
|
||||||
checklist_id: string;
|
checklist_id: string;
|
||||||
@@ -125,6 +128,7 @@ export function DetailDailyChecklistContent() {
|
|||||||
const [employees, setEmployees] = useState<{ id: string; name: string }[]>(
|
const [employees, setEmployees] = useState<{ id: string; name: string }[]>(
|
||||||
[]
|
[]
|
||||||
);
|
);
|
||||||
|
const [documents, setDocuments] = useState<Document[]>([]);
|
||||||
|
|
||||||
// Modals
|
// Modals
|
||||||
const [showApproveModal, setShowApproveModal] = useState(false);
|
const [showApproveModal, setShowApproveModal] = useState(false);
|
||||||
@@ -160,6 +164,8 @@ export function DetailDailyChecklistContent() {
|
|||||||
|
|
||||||
const rawDetailChecklist = checklistDataRes?.data;
|
const rawDetailChecklist = checklistDataRes?.data;
|
||||||
|
|
||||||
|
setDocuments(rawDetailChecklist?.document_urls || []);
|
||||||
|
|
||||||
const checklistData = {
|
const checklistData = {
|
||||||
id: rawDetailChecklist?.id,
|
id: rawDetailChecklist?.id,
|
||||||
date: rawDetailChecklist?.date,
|
date: rawDetailChecklist?.date,
|
||||||
@@ -842,6 +848,37 @@ export function DetailDailyChecklistContent() {
|
|||||||
Tidak ada data aktivitas
|
Tidak ada data aktivitas
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{documents.length > 0 && (
|
||||||
|
<div className='mt-6'>
|
||||||
|
<h3 className='font-semibold text-gray-900 mb-2'>
|
||||||
|
Dokumen yang telah diupload
|
||||||
|
</h3>
|
||||||
|
|
||||||
|
<ul className='list-disc pl-4'>
|
||||||
|
{documents.map((existingDocument, existingDocumentIdx) => (
|
||||||
|
<li key={existingDocumentIdx}>
|
||||||
|
<div className='w-full flex flex-wrap justify-between'>
|
||||||
|
<Link
|
||||||
|
href={existingDocument.url}
|
||||||
|
target='_blank'
|
||||||
|
rel='noopener noreferrer'
|
||||||
|
className='text-blue-500 underline'
|
||||||
|
>
|
||||||
|
{existingDocument.name}{' '}
|
||||||
|
<Icon
|
||||||
|
icon='cuida:open-in-new-tab-outline'
|
||||||
|
width={12}
|
||||||
|
height={12}
|
||||||
|
className='inline'
|
||||||
|
/>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -328,6 +328,7 @@ export function MasterAktivitasContent() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
refreshPhases();
|
||||||
refreshPhaseActivities();
|
refreshPhaseActivities();
|
||||||
toast.success('Aktivitas berhasil ditambahkan');
|
toast.success('Aktivitas berhasil ditambahkan');
|
||||||
} else {
|
} else {
|
||||||
@@ -349,6 +350,7 @@ export function MasterAktivitasContent() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
refreshPhases();
|
||||||
refreshPhaseActivities();
|
refreshPhaseActivities();
|
||||||
toast.success('Aktivitas berhasil diubah');
|
toast.success('Aktivitas berhasil diubah');
|
||||||
}
|
}
|
||||||
@@ -387,6 +389,7 @@ export function MasterAktivitasContent() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
refreshPhases();
|
||||||
refreshPhaseActivities();
|
refreshPhaseActivities();
|
||||||
toast.success('Aktivitas berhasil dihapus');
|
toast.success('Aktivitas berhasil dihapus');
|
||||||
setShowActivityDeleteConfirm(false);
|
setShowActivityDeleteConfirm(false);
|
||||||
|
|||||||
+564
@@ -0,0 +1,564 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { Plus, MoreVertical, Pencil, Trash2 } from 'lucide-react';
|
||||||
|
import { Card, CardContent } from '@/figma-make/components/base/card';
|
||||||
|
import { Button } from '@/figma-make/components/base/button';
|
||||||
|
import { Label } from '@/figma-make/components/base/label';
|
||||||
|
import { Input } from '@/figma-make/components/base/input';
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
} from '@/figma-make/components/base/dialog';
|
||||||
|
import {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogAction,
|
||||||
|
AlertDialogCancel,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogTitle,
|
||||||
|
} from '@/figma-make/components/base/alert-dialog';
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from '@/figma-make/components/base/dropdown-menu';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
import useSWR from 'swr';
|
||||||
|
import Table from '@/components/Table';
|
||||||
|
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||||
|
import { cn, formatDate } from '@/lib/helper';
|
||||||
|
import { useTableFilter } from '@/services/hooks/useTableFilter';
|
||||||
|
import { ColumnDef } from '@tanstack/react-table';
|
||||||
|
import { DailyChecklistConfiguration } from '@/types/api/daily-checklist/configuration';
|
||||||
|
import { DailyChecklistConfigurationApi } from '@/services/api/daily-checklist/configuration';
|
||||||
|
import { DatePicker } from '@/figma-make/components/base/date-picker';
|
||||||
|
|
||||||
|
export function MasterConfigurationContent() {
|
||||||
|
const {
|
||||||
|
state: tableFilterState,
|
||||||
|
setPage,
|
||||||
|
setPageSize,
|
||||||
|
toQueryString: getTableFilterQueryString,
|
||||||
|
} = useTableFilter({
|
||||||
|
initial: {
|
||||||
|
search: '',
|
||||||
|
},
|
||||||
|
paramMap: {
|
||||||
|
page: 'page',
|
||||||
|
pageSize: 'limit',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const {
|
||||||
|
data: dailyChecklistConfigurations,
|
||||||
|
isLoading: isLoadingDailyChecklistConfigurations,
|
||||||
|
mutate: refreshDailyChecklistConfigurations,
|
||||||
|
} = useSWR(
|
||||||
|
`${DailyChecklistConfigurationApi.basePath}${getTableFilterQueryString()}`,
|
||||||
|
DailyChecklistConfigurationApi.getAllFetcher,
|
||||||
|
{
|
||||||
|
keepPreviousData: true,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
const [showModal, setShowModal] = useState(false);
|
||||||
|
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
|
||||||
|
const [configurationToDelete, setConfigurationToDelete] = useState<
|
||||||
|
number | null
|
||||||
|
>(null);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [modalMode, setModalMode] = useState<'create' | 'edit'>('create');
|
||||||
|
const [configurationForm, setConfigurationForm] = useState({
|
||||||
|
id: 0,
|
||||||
|
date: '',
|
||||||
|
percentage_threshold_bad: '',
|
||||||
|
percentage_threshold_enough: '',
|
||||||
|
});
|
||||||
|
|
||||||
|
const configurationColumns: ColumnDef<DailyChecklistConfiguration>[] = [
|
||||||
|
{
|
||||||
|
id: 'date',
|
||||||
|
header: 'Tanggal',
|
||||||
|
accessorKey: 'date',
|
||||||
|
enableSorting: false,
|
||||||
|
cell: ({ row }) => formatDate(row.original.date, 'DD MMM YYYY'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'percentage_threshold_bad',
|
||||||
|
header: 'Threshold Bad',
|
||||||
|
accessorKey: 'percentage_threshold_bad',
|
||||||
|
enableSorting: false,
|
||||||
|
cell: ({ row }) => `${row.original.percentage_threshold_bad}%`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'percentage_threshold_enough',
|
||||||
|
header: 'Threshold Enough',
|
||||||
|
accessorKey: 'percentage_threshold_enough',
|
||||||
|
enableSorting: false,
|
||||||
|
cell: ({ row }) => `${row.original.percentage_threshold_enough}%`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'action',
|
||||||
|
header: 'Aksi',
|
||||||
|
accessorKey: 'action',
|
||||||
|
enableSorting: false,
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button
|
||||||
|
variant='ghost'
|
||||||
|
size='sm'
|
||||||
|
className='h-8 w-8 p-0 hover:bg-gray-100'
|
||||||
|
>
|
||||||
|
<MoreVertical className='h-4 w-4 text-gray-600' />
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align='end'>
|
||||||
|
<DropdownMenuItem onClick={() => handleEdit(row.original)}>
|
||||||
|
<Pencil className='mr-2 h-4 w-4' />
|
||||||
|
Edit
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem
|
||||||
|
onClick={() => handleDeleteClick(row.original.id)}
|
||||||
|
className='text-red-600'
|
||||||
|
>
|
||||||
|
<Trash2 className='mr-2 h-4 w-4' />
|
||||||
|
Hapus
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const handleAdd = () => {
|
||||||
|
setModalMode('create');
|
||||||
|
setConfigurationForm({
|
||||||
|
id: 0,
|
||||||
|
date: '',
|
||||||
|
percentage_threshold_bad: '',
|
||||||
|
percentage_threshold_enough: '',
|
||||||
|
});
|
||||||
|
setShowModal(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleEdit = (configuration: DailyChecklistConfiguration) => {
|
||||||
|
setModalMode('edit');
|
||||||
|
setConfigurationForm({
|
||||||
|
id: configuration.id,
|
||||||
|
date: configuration.date,
|
||||||
|
percentage_threshold_bad: String(configuration.percentage_threshold_bad),
|
||||||
|
percentage_threshold_enough: String(
|
||||||
|
configuration.percentage_threshold_enough
|
||||||
|
),
|
||||||
|
});
|
||||||
|
setShowModal(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
if (
|
||||||
|
!configurationForm.date.trim() ||
|
||||||
|
Number(configurationForm.percentage_threshold_bad) === 0 ||
|
||||||
|
Number(configurationForm.percentage_threshold_enough) === 0
|
||||||
|
) {
|
||||||
|
toast.error('Tanggal dan persentase harus diisi');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (modalMode === 'create') {
|
||||||
|
const createConfigurationResponse =
|
||||||
|
await DailyChecklistConfigurationApi.create({
|
||||||
|
date: formatDate(configurationForm.date, 'YYYY-MM-DD'),
|
||||||
|
percentage_threshold_bad: Number(
|
||||||
|
configurationForm.percentage_threshold_bad
|
||||||
|
),
|
||||||
|
percentage_threshold_enough: Number(
|
||||||
|
configurationForm.percentage_threshold_enough
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (isResponseError(createConfigurationResponse)) {
|
||||||
|
console.error(
|
||||||
|
'Error creating configuration:',
|
||||||
|
createConfigurationResponse.message
|
||||||
|
);
|
||||||
|
toast.error('Gagal menambahkan konfigurasi');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
refreshDailyChecklistConfigurations();
|
||||||
|
toast.success('Konfigurasi berhasil ditambahkan');
|
||||||
|
} else {
|
||||||
|
const updateConfigurationResponse =
|
||||||
|
await DailyChecklistConfigurationApi.update(configurationForm.id, {
|
||||||
|
date: formatDate(configurationForm.date, 'YYYY-MM-DD'),
|
||||||
|
percentage_threshold_bad: Number(
|
||||||
|
configurationForm.percentage_threshold_bad
|
||||||
|
),
|
||||||
|
percentage_threshold_enough: Number(
|
||||||
|
configurationForm.percentage_threshold_enough
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (isResponseError(updateConfigurationResponse)) {
|
||||||
|
console.error(
|
||||||
|
'Error updating configuration:',
|
||||||
|
updateConfigurationResponse.message
|
||||||
|
);
|
||||||
|
toast.error('Gagal mengubah konfigurasi');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
refreshDailyChecklistConfigurations();
|
||||||
|
toast.success('Konfigurasi berhasil diubah');
|
||||||
|
}
|
||||||
|
|
||||||
|
setShowModal(false);
|
||||||
|
setConfigurationForm({
|
||||||
|
id: 0,
|
||||||
|
date: '',
|
||||||
|
percentage_threshold_bad: '',
|
||||||
|
percentage_threshold_enough: '',
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error saving configuration:', error);
|
||||||
|
toast.error('Terjadi kesalahan saat menyimpan konfigurasi');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDeleteClick = (configurationId: number) => {
|
||||||
|
setConfigurationToDelete(configurationId);
|
||||||
|
setShowDeleteConfirm(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleConfirmDelete = async () => {
|
||||||
|
if (!configurationToDelete) return;
|
||||||
|
|
||||||
|
setLoading(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const deleteConfigurationResponse =
|
||||||
|
await DailyChecklistConfigurationApi.delete(configurationToDelete);
|
||||||
|
|
||||||
|
if (isResponseError(deleteConfigurationResponse)) {
|
||||||
|
console.error(
|
||||||
|
'Error deleting configuration:',
|
||||||
|
deleteConfigurationResponse.message
|
||||||
|
);
|
||||||
|
toast.error('Gagal menghapus konfigurasi');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
refreshDailyChecklistConfigurations();
|
||||||
|
toast.success('Konfigurasi berhasil dihapus');
|
||||||
|
setShowDeleteConfirm(false);
|
||||||
|
setConfigurationToDelete(null);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error deleting employee:', error);
|
||||||
|
toast.error('Terjadi kesalahan saat menghapus konfigurasi');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleExport = (format: string) => {
|
||||||
|
toast.success(`Data berhasil diekspor ke ${format}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isLoadingDailyChecklistConfigurations && !dailyChecklistConfigurations) {
|
||||||
|
return (
|
||||||
|
<div className='min-h-screen'>
|
||||||
|
<div className='p-6'>
|
||||||
|
<div className='mb-6'>
|
||||||
|
<h1 className='text-2xl font-semibold text-gray-900'>
|
||||||
|
Master Konfigurasi
|
||||||
|
</h1>
|
||||||
|
<p className='text-sm text-gray-600 mt-1'>
|
||||||
|
Master Data • <span className='text-[#0069e0]'>Konfigurasi</span>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Card className='border-gray-200/60 shadow-sm rounded-xl bg-white'>
|
||||||
|
<CardContent className='p-12 text-center text-gray-500'>
|
||||||
|
Memuat data...
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatDateForDisplay = (dateStr: string) => {
|
||||||
|
if (!dateStr) return 'Pilih tanggal';
|
||||||
|
const [year, month, day] = dateStr.split('-');
|
||||||
|
const date = new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
|
||||||
|
return date.toLocaleDateString('id-ID', {
|
||||||
|
weekday: 'long',
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'long',
|
||||||
|
day: 'numeric',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className='min-h-screen'>
|
||||||
|
<div className='p-6'>
|
||||||
|
{/* Page Title */}
|
||||||
|
<div className='mb-6'>
|
||||||
|
<h1 className='text-2xl font-semibold text-gray-900'>
|
||||||
|
Master Konfigurasi
|
||||||
|
</h1>
|
||||||
|
<p className='text-sm text-gray-600 mt-1'>
|
||||||
|
Master Data • <span className='text-[#0069e0]'>Konfigurasi</span>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Main Card */}
|
||||||
|
<Card className='border-gray-200/60 shadow-sm rounded-xl bg-white'>
|
||||||
|
<CardContent className='p-0'>
|
||||||
|
{/* Single Toolbar Row */}
|
||||||
|
<div className='flex flex-wrap items-center justify-between gap-4 p-6 border-b border-gray-200/60'>
|
||||||
|
<div className='flex items-center gap-2 flex-wrap'>
|
||||||
|
<Button
|
||||||
|
onClick={handleAdd}
|
||||||
|
className='bg-[#0069e0] hover:bg-[#0052b3] text-white'
|
||||||
|
>
|
||||||
|
<Plus className='w-4 h-4 mr-2' />
|
||||||
|
Tambah Konfigurasi
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Table */}
|
||||||
|
<Table<DailyChecklistConfiguration>
|
||||||
|
data={
|
||||||
|
isResponseSuccess(dailyChecklistConfigurations)
|
||||||
|
? dailyChecklistConfigurations?.data
|
||||||
|
: []
|
||||||
|
}
|
||||||
|
columns={configurationColumns}
|
||||||
|
pageSize={tableFilterState.pageSize}
|
||||||
|
onPageSizeChange={setPageSize}
|
||||||
|
rowOptions={[10, 20, 50, 100]}
|
||||||
|
page={
|
||||||
|
isResponseSuccess(dailyChecklistConfigurations)
|
||||||
|
? dailyChecklistConfigurations?.meta?.page
|
||||||
|
: 0
|
||||||
|
}
|
||||||
|
totalItems={
|
||||||
|
isResponseSuccess(dailyChecklistConfigurations)
|
||||||
|
? dailyChecklistConfigurations?.meta?.total_results
|
||||||
|
: 0
|
||||||
|
}
|
||||||
|
onPageChange={setPage}
|
||||||
|
isLoading={isLoadingDailyChecklistConfigurations}
|
||||||
|
className={{
|
||||||
|
containerClassName: cn({
|
||||||
|
'w-full mb-20':
|
||||||
|
isResponseSuccess(dailyChecklistConfigurations) &&
|
||||||
|
dailyChecklistConfigurations?.data?.length === 0,
|
||||||
|
}),
|
||||||
|
tableWrapperClassName:
|
||||||
|
'overflow-x-auto border border-solid border-base-content/10 rounded-none',
|
||||||
|
headerRowClassName: 'bg-gray-50/50',
|
||||||
|
headerColumnClassName:
|
||||||
|
'text-left py-3.5 px-6 text-sm font-semibold text-gray-700',
|
||||||
|
paginationClassName: 'px-4',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Add/Edit Modal */}
|
||||||
|
<Dialog open={showModal} onOpenChange={setShowModal}>
|
||||||
|
<DialogContent className='sm:max-w-md bg-white rounded-xl shadow-lg'>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>
|
||||||
|
{modalMode === 'create'
|
||||||
|
? 'Tambah Konfigurasi'
|
||||||
|
: 'Edit Konfigurasi'}
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
{modalMode === 'create'
|
||||||
|
? 'Masukkan detail konfigurasi baru'
|
||||||
|
: 'Ubah detail konfigurasi'}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className='space-y-4 py-4'>
|
||||||
|
<div>
|
||||||
|
<Label htmlFor='date'>
|
||||||
|
Tanggal Efektif <span className='text-red-500'>*</span>
|
||||||
|
</Label>
|
||||||
|
<div className='mt-1.5'>
|
||||||
|
<DatePicker
|
||||||
|
date={configurationForm.date}
|
||||||
|
onDateChange={(e) =>
|
||||||
|
setConfigurationForm({
|
||||||
|
...configurationForm,
|
||||||
|
date: e,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
disabled={loading}
|
||||||
|
placeholder='Pilih tanggal'
|
||||||
|
formatDisplay={formatDateForDisplay}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<Label>
|
||||||
|
Threshold <span className='text-red-500'>*</span>
|
||||||
|
</Label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className='flex flex-row items-center justify-between gap-2 max-w-64'>
|
||||||
|
<Label htmlFor='thresholdBad'>
|
||||||
|
Kurang <span className='text-red-500'>*</span>
|
||||||
|
</Label>
|
||||||
|
|
||||||
|
<div className='flex flex-row items-center gap-1'>
|
||||||
|
<Input
|
||||||
|
id='thresholdBadGround'
|
||||||
|
value={0}
|
||||||
|
disabled
|
||||||
|
className='w-16'
|
||||||
|
/>
|
||||||
|
|
||||||
|
<span>{'<='}</span>
|
||||||
|
|
||||||
|
<Input
|
||||||
|
type='number'
|
||||||
|
id='percentageThresholdBad'
|
||||||
|
value={configurationForm.percentage_threshold_bad}
|
||||||
|
onChange={(e) =>
|
||||||
|
setConfigurationForm({
|
||||||
|
...configurationForm,
|
||||||
|
percentage_threshold_bad: e.target.value,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
placeholder='Kurang'
|
||||||
|
className='w-20'
|
||||||
|
disabled={loading}
|
||||||
|
max={100}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className='flex flex-row items-center justify-between gap-2 max-w-64'>
|
||||||
|
<Label htmlFor='thresholdEnough'>
|
||||||
|
Cukup <span className='text-red-500'>*</span>
|
||||||
|
</Label>
|
||||||
|
|
||||||
|
<div className='flex flex-row items-center gap-1'>
|
||||||
|
<Input
|
||||||
|
id='thresholdEnoughGround'
|
||||||
|
value={Number(configurationForm.percentage_threshold_bad) + 1}
|
||||||
|
disabled
|
||||||
|
className='w-16'
|
||||||
|
/>
|
||||||
|
|
||||||
|
<span>{'<='}</span>
|
||||||
|
|
||||||
|
<Input
|
||||||
|
type='number'
|
||||||
|
id='percentageThresholdEnough'
|
||||||
|
value={configurationForm.percentage_threshold_enough}
|
||||||
|
onChange={(e) =>
|
||||||
|
setConfigurationForm({
|
||||||
|
...configurationForm,
|
||||||
|
percentage_threshold_enough: e.target.value,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
placeholder='Cukup'
|
||||||
|
className='w-20'
|
||||||
|
disabled={loading}
|
||||||
|
min={Number(configurationForm.percentage_threshold_bad) + 1}
|
||||||
|
max={100}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className='flex flex-row items-center justify-between gap-2 max-w-64'>
|
||||||
|
<Label htmlFor='thresholdGood'>
|
||||||
|
Baik <span className='text-red-500'>*</span>
|
||||||
|
</Label>
|
||||||
|
|
||||||
|
<div className='flex flex-row items-center gap-1'>
|
||||||
|
<Input
|
||||||
|
id='thresholdGoodGround'
|
||||||
|
value={
|
||||||
|
Number(configurationForm.percentage_threshold_enough) + 1
|
||||||
|
}
|
||||||
|
disabled
|
||||||
|
className='w-16'
|
||||||
|
/>
|
||||||
|
|
||||||
|
<span>{'<='}</span>
|
||||||
|
|
||||||
|
<Input
|
||||||
|
type='number'
|
||||||
|
id='percentageThresholdGood'
|
||||||
|
value={100}
|
||||||
|
placeholder='Good'
|
||||||
|
className='w-20'
|
||||||
|
disabled
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button
|
||||||
|
variant='outline'
|
||||||
|
onClick={() => setShowModal(false)}
|
||||||
|
disabled={loading}
|
||||||
|
>
|
||||||
|
Batal
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={handleSave}
|
||||||
|
disabled={loading}
|
||||||
|
className='bg-[#0069e0] hover:bg-[#0052b3] text-white'
|
||||||
|
>
|
||||||
|
{loading ? 'Menyimpan...' : 'Simpan'}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
{/* Delete Confirmation */}
|
||||||
|
<AlertDialog open={showDeleteConfirm} onOpenChange={setShowDeleteConfirm}>
|
||||||
|
<AlertDialogContent className='bg-white rounded-xl shadow-lg sm:max-w-md'>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle>Hapus konfigurasi?</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>
|
||||||
|
Data konfigurasi akan dihapus secara permanen.
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel disabled={loading}>Batal</AlertDialogCancel>
|
||||||
|
<AlertDialogAction
|
||||||
|
onClick={handleConfirmDelete}
|
||||||
|
disabled={loading}
|
||||||
|
className='bg-red-600 hover:bg-red-700 text-white'
|
||||||
|
>
|
||||||
|
{loading ? 'Menghapus...' : 'Hapus'}
|
||||||
|
</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -283,10 +283,6 @@ export function MasterEmployeeContent() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleExport = (format: string) => {
|
|
||||||
toast.success(`Data berhasil diekspor ke ${format}`);
|
|
||||||
};
|
|
||||||
|
|
||||||
if (isLoadingEmployees && !employees) {
|
if (isLoadingEmployees && !employees) {
|
||||||
return (
|
return (
|
||||||
<div className='min-h-screen'>
|
<div className='min-h-screen'>
|
||||||
@@ -390,27 +386,6 @@ export function MasterEmployeeContent() {
|
|||||||
|
|
||||||
{/* RIGHT: Export + Add */}
|
{/* RIGHT: Export + Add */}
|
||||||
<div className='flex items-center gap-2 flex-wrap'>
|
<div className='flex items-center gap-2 flex-wrap'>
|
||||||
<DropdownMenu>
|
|
||||||
<DropdownMenuTrigger asChild>
|
|
||||||
<Button
|
|
||||||
variant='outline'
|
|
||||||
className='border-gray-200 text-gray-700'
|
|
||||||
>
|
|
||||||
<Download className='w-4 h-4 mr-2' />
|
|
||||||
Export
|
|
||||||
<ChevronDown className='w-4 h-4 ml-2' />
|
|
||||||
</Button>
|
|
||||||
</DropdownMenuTrigger>
|
|
||||||
<DropdownMenuContent align='end'>
|
|
||||||
<DropdownMenuItem onClick={() => handleExport('CSV')}>
|
|
||||||
Export CSV
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuItem onClick={() => handleExport('Excel')}>
|
|
||||||
Export Excel
|
|
||||||
</DropdownMenuItem>
|
|
||||||
</DropdownMenuContent>
|
|
||||||
</DropdownMenu>
|
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
onClick={handleAdd}
|
onClick={handleAdd}
|
||||||
className='bg-[#0069e0] hover:bg-[#0052b3] text-white'
|
className='bg-[#0069e0] hover:bg-[#0052b3] text-white'
|
||||||
|
|||||||
@@ -1,13 +1,9 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useState, useEffect } from 'react';
|
import { useMemo } from 'react';
|
||||||
import { Eye, Download, Search } from 'lucide-react';
|
|
||||||
import { Card, CardContent } from '@/figma-make/components/base/card';
|
import { Card, CardContent } from '@/figma-make/components/base/card';
|
||||||
import { Button } from '@/figma-make/components/base/button';
|
|
||||||
import { Badge } from '@/figma-make/components/base/badge';
|
import { Badge } from '@/figma-make/components/base/badge';
|
||||||
import { Input } from '@/figma-make/components/base/input';
|
|
||||||
import { Label } from '@/figma-make/components/base/label';
|
import { Label } from '@/figma-make/components/base/label';
|
||||||
import { DateRangePicker } from '@/figma-make/components/base/date-range-picker';
|
|
||||||
import {
|
import {
|
||||||
Select,
|
Select,
|
||||||
SelectContent,
|
SelectContent,
|
||||||
@@ -16,357 +12,291 @@ import {
|
|||||||
SelectValue,
|
SelectValue,
|
||||||
} from '@/figma-make/components/base/select';
|
} from '@/figma-make/components/base/select';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { supabase, isSupabaseConfigured } from '@/figma-make/lib/supabase';
|
|
||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
|
import { useSelect } from '@/components/input/SelectInput';
|
||||||
|
import { AreaApi, KandangApi, LocationApi } from '@/services/api/master-data';
|
||||||
|
import useSWR from 'swr';
|
||||||
|
import { BaseApiResponse } from '@/types/api/api-general';
|
||||||
|
import { DailyChecklistReport } from '@/types/api/daily-checklist/daily-checklist';
|
||||||
|
import { AxiosError } from 'axios';
|
||||||
|
import { httpClientFetcher, SWRHttpKey } from '@/services/http/client';
|
||||||
|
import { DailyChecklistApi } from '@/services/api/daily-checklist/daily-checklist';
|
||||||
|
import Table from '@/components/Table';
|
||||||
|
import { isResponseSuccess } from '@/lib/api-helper';
|
||||||
|
import { useTableFilter } from '@/services/hooks/useTableFilter';
|
||||||
|
import { cn } from '@/lib/helper';
|
||||||
|
import { ColumnDef } from '@tanstack/react-table';
|
||||||
|
import { report } from 'process';
|
||||||
|
import { PhaseApi } from '@/services/api/daily-checklist/phase';
|
||||||
|
import { EmployeeApi } from '@/services/api/daily-checklist/employee';
|
||||||
|
import { Button } from '@/figma-make/components/base/button';
|
||||||
|
import { Download } from 'lucide-react';
|
||||||
|
|
||||||
interface SubmissionReportItem {
|
const MONTH_OPTIONS = [
|
||||||
checklist_id: string;
|
{ value: '1', label: 'Januari' },
|
||||||
date: string;
|
{ value: '2', label: 'Februari' },
|
||||||
kandang_id: string;
|
{ value: '3', label: 'Maret' },
|
||||||
kandang_name: string;
|
{ value: '4', label: 'April' },
|
||||||
category: string;
|
{ value: '5', label: 'Mei' },
|
||||||
status: string;
|
{ value: '6', label: 'Juni' },
|
||||||
progress_percent: number;
|
{ value: '7', label: 'Juli' },
|
||||||
total_phases: number;
|
{ value: '8', label: 'Agustus' },
|
||||||
total_activities: number;
|
{ value: '9', label: 'September' },
|
||||||
total_employees: number;
|
{ value: '10', label: 'Oktober' },
|
||||||
updated_at: string;
|
{ value: '11', label: 'November' },
|
||||||
}
|
{ value: '12', label: 'Desember' },
|
||||||
|
|
||||||
interface Kandang {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ReportQueryResult {
|
|
||||||
id: string;
|
|
||||||
date: string;
|
|
||||||
kandang_id: string;
|
|
||||||
category: string;
|
|
||||||
status: string;
|
|
||||||
updated_at: string;
|
|
||||||
kandang: {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
} | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const STATUS_OPTIONS = [
|
|
||||||
{ value: 'ALL', label: 'Semua Status' },
|
|
||||||
{ value: 'DRAFT', label: 'Draft' },
|
|
||||||
{ value: 'SUBMITTED', label: 'Submitted' },
|
|
||||||
{ value: 'APPROVED', label: 'Approved' },
|
|
||||||
{ value: 'REJECTED', label: 'Rejected' },
|
|
||||||
];
|
];
|
||||||
|
|
||||||
const CATEGORY_LABELS: { [key: string]: string } = {
|
const YEAR_OPTIONS = [
|
||||||
pullet_open: 'Pullet Open',
|
{ value: '2027', label: '2027' },
|
||||||
pullet_close: 'Pullet Close',
|
{ value: '2026', label: '2026' },
|
||||||
produksi_open: 'Produksi Open',
|
{ value: '2025', label: '2025' },
|
||||||
produksi_close: 'Produksi Close',
|
{ value: '2024', label: '2024' },
|
||||||
};
|
{ value: '2023', label: '2023' },
|
||||||
|
{ value: '2022', label: '2022' },
|
||||||
|
{ value: '2021', label: '2021' },
|
||||||
|
{ value: '2020', label: '2020' },
|
||||||
|
];
|
||||||
|
|
||||||
|
// const CATEGORY_LABELS: { [key: string]: string } = {
|
||||||
|
// pullet_open: 'Pullet Open',
|
||||||
|
// pullet_close: 'Pullet Close',
|
||||||
|
// produksi_open: 'Produksi Open',
|
||||||
|
// produksi_close: 'Produksi Close',
|
||||||
|
// };
|
||||||
|
|
||||||
export function DailyChecklistReportsContent() {
|
export function DailyChecklistReportsContent() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
|
|
||||||
// Report State
|
const currentMonth = useMemo(() => new Date().getMonth() + 1, []);
|
||||||
const [reportList, setReportList] = useState<SubmissionReportItem[]>([]);
|
const currentYear = useMemo(() => new Date().getFullYear(), []);
|
||||||
const [filteredReportList, setFilteredReportList] = useState<
|
|
||||||
SubmissionReportItem[]
|
|
||||||
>([]);
|
|
||||||
|
|
||||||
// Master data
|
const {
|
||||||
const [kandangList, setKandangList] = useState<Kandang[]>([]);
|
state: tableFilterState,
|
||||||
|
updateFilter,
|
||||||
|
setPage,
|
||||||
|
setPageSize,
|
||||||
|
toQueryString: getTableFilterQueryString,
|
||||||
|
} = useTableFilter({
|
||||||
|
initial: {
|
||||||
|
bulan: currentMonth.toString(),
|
||||||
|
tahun: currentYear.toString(),
|
||||||
|
area_id: '',
|
||||||
|
location_id: '',
|
||||||
|
kandang_id: '',
|
||||||
|
employee_id: '',
|
||||||
|
phase_id: '',
|
||||||
|
},
|
||||||
|
paramMap: {
|
||||||
|
page: 'page',
|
||||||
|
pageSize: 'limit',
|
||||||
|
bulan: 'bulan',
|
||||||
|
tahun: 'tahun',
|
||||||
|
area_id: 'area_id',
|
||||||
|
location_id: 'location_id',
|
||||||
|
kandang_id: 'kandang_id',
|
||||||
|
employee_id: 'employee_id',
|
||||||
|
phase_id: 'phase_id',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
// Filters
|
const {
|
||||||
const [statusFilter, setStatusFilter] = useState('ALL');
|
data: reportResponse,
|
||||||
const [kandangFilter, setKandangFilter] = useState('ALL');
|
isLoading: isLoadingReport,
|
||||||
const [searchText, setSearchText] = useState('');
|
mutate: refreshReport,
|
||||||
const [dateFrom, setDateFrom] = useState('');
|
} = useSWR<
|
||||||
const [dateTo, setDateTo] = useState('');
|
BaseApiResponse<DailyChecklistReport[] | undefined>,
|
||||||
|
AxiosError<BaseApiResponse>,
|
||||||
useEffect(() => {
|
SWRHttpKey
|
||||||
fetchKandangList();
|
>(
|
||||||
fetchReports();
|
`${DailyChecklistApi.basePath}/report${getTableFilterQueryString()}`,
|
||||||
}, []);
|
httpClientFetcher,
|
||||||
|
{
|
||||||
useEffect(() => {
|
keepPreviousData: true,
|
||||||
applyFilters();
|
|
||||||
}, [reportList, statusFilter, kandangFilter, searchText, dateFrom, dateTo]);
|
|
||||||
|
|
||||||
const fetchKandangList = async () => {
|
|
||||||
if (!isSupabaseConfigured()) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { data, error } = await supabase
|
|
||||||
.from('kandang')
|
|
||||||
.select('id, name')
|
|
||||||
.order('name', { ascending: true });
|
|
||||||
|
|
||||||
if (error) {
|
|
||||||
console.error('Error fetching kandang:', error);
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
setKandangList(data || []);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error fetching kandang:', error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchReports = async () => {
|
|
||||||
if (!isSupabaseConfigured()) {
|
|
||||||
console.warn('Supabase not configured');
|
|
||||||
setLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
setLoading(true);
|
|
||||||
|
|
||||||
// Fetch checklists directly from daily_checklists table
|
|
||||||
const { data: checklists, error } = await supabase
|
|
||||||
.from('daily_checklists')
|
|
||||||
.select(
|
|
||||||
`
|
|
||||||
id,
|
|
||||||
date,
|
|
||||||
kandang_id,
|
|
||||||
category,
|
|
||||||
status,
|
|
||||||
updated_at,
|
|
||||||
kandang:kandang_id (
|
|
||||||
id,
|
|
||||||
name
|
|
||||||
)
|
|
||||||
`
|
|
||||||
)
|
|
||||||
.order('date', { ascending: false })
|
|
||||||
.order('updated_at', { ascending: false });
|
|
||||||
|
|
||||||
if (error) {
|
|
||||||
console.error('Error fetching reports:', error);
|
|
||||||
toast.error('Gagal memuat data reports');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Enrich data with calculations
|
|
||||||
const enrichedData = await Promise.all(
|
|
||||||
((checklists as unknown as ReportQueryResult[]) || [])
|
|
||||||
.filter((checklist) => checklist.id)
|
|
||||||
.map(async (checklist) => {
|
|
||||||
// Count phases
|
|
||||||
const { count: phaseCount } = await supabase
|
|
||||||
.from('daily_checklist_phases')
|
|
||||||
.select('*', { count: 'exact', head: true })
|
|
||||||
.eq('checklist_id', checklist.id);
|
|
||||||
|
|
||||||
// Count activities (tasks)
|
|
||||||
const { count: activityCount } = await supabase
|
|
||||||
.from('daily_checklist_activity_tasks')
|
|
||||||
.select('*', { count: 'exact', head: true })
|
|
||||||
.eq('checklist_id', checklist.id);
|
|
||||||
|
|
||||||
// Count unique employees
|
|
||||||
const { data: tasks } = await supabase
|
|
||||||
.from('daily_checklist_activity_tasks')
|
|
||||||
.select('id')
|
|
||||||
.eq('checklist_id', checklist.id);
|
|
||||||
|
|
||||||
const taskIds = (tasks || []).map((t) => t.id);
|
|
||||||
let uniqueEmployees = new Set<string>();
|
|
||||||
|
|
||||||
if (taskIds.length > 0) {
|
|
||||||
const { data: assignments } = await supabase
|
|
||||||
.from('daily_checklist_activity_task_assignments')
|
|
||||||
.select('employee_id')
|
|
||||||
.in('task_id', taskIds);
|
|
||||||
|
|
||||||
uniqueEmployees = new Set(
|
|
||||||
(assignments || []).map((a) => a.employee_id)
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const { options: areaOptions, isLoadingOptions: isLoadingAreas } = useSelect(
|
||||||
|
AreaApi.basePath,
|
||||||
|
'id',
|
||||||
|
'name',
|
||||||
|
'search',
|
||||||
|
{
|
||||||
|
page: '1',
|
||||||
|
limit: '100',
|
||||||
}
|
}
|
||||||
|
|
||||||
// ✅ Calculate progress based on phase coverage
|
|
||||||
const { count: totalPhasesInMaster } = await supabase
|
|
||||||
.from('phases')
|
|
||||||
.select('*', { count: 'exact', head: true })
|
|
||||||
.eq('category_id', checklist.category);
|
|
||||||
|
|
||||||
const { data: checklistTasks } = await supabase
|
|
||||||
.from('daily_checklist_activity_tasks')
|
|
||||||
.select('id, phase_id')
|
|
||||||
.eq('checklist_id', checklist.id);
|
|
||||||
|
|
||||||
const checklistTaskIds = (checklistTasks || []).map((t) => t.id);
|
|
||||||
const uniquePhasesWithChecked = new Set<string>();
|
|
||||||
|
|
||||||
if (checklistTaskIds.length > 0) {
|
|
||||||
const { data: checkedAssignments } = await supabase
|
|
||||||
.from('daily_checklist_activity_task_assignments')
|
|
||||||
.select('task_id')
|
|
||||||
.in('task_id', checklistTaskIds)
|
|
||||||
.eq('checked', true);
|
|
||||||
|
|
||||||
if (checkedAssignments && checkedAssignments.length > 0) {
|
|
||||||
const checkedTaskIds = new Set(
|
|
||||||
checkedAssignments.map((a) => a.task_id)
|
|
||||||
);
|
);
|
||||||
checklistTasks?.forEach((task) => {
|
|
||||||
if (checkedTaskIds.has(task.id)) {
|
const { options: locationOptions, isLoadingOptions: isLoadingLocations } =
|
||||||
uniquePhasesWithChecked.add(task.phase_id);
|
useSelect(LocationApi.basePath, 'id', 'name', 'search', {
|
||||||
}
|
page: '1',
|
||||||
|
limit: '100',
|
||||||
|
area_id: tableFilterState.area_id,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { options: kandangOptions, isLoadingOptions: isLoadingKandangs } =
|
||||||
|
useSelect(KandangApi.basePath, 'id', 'name', 'search', {
|
||||||
|
page: '1',
|
||||||
|
limit: '100',
|
||||||
|
area_id: tableFilterState.area_id,
|
||||||
|
location_id: tableFilterState.location_id,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { options: phaseOptions, isLoadingOptions: isLoadingPhases } =
|
||||||
|
useSelect(PhaseApi.basePath, 'id', 'name', 'search', {
|
||||||
|
page: '1',
|
||||||
|
limit: '100',
|
||||||
|
});
|
||||||
|
|
||||||
|
const { options: employeeOptions, isLoadingOptions: isLoadingEmployees } =
|
||||||
|
useSelect(EmployeeApi.basePath, 'id', 'name', 'search', {
|
||||||
|
page: '1',
|
||||||
|
limit: '500',
|
||||||
|
kandang_id: tableFilterState.kandang_id,
|
||||||
|
});
|
||||||
|
|
||||||
|
const currentMonthMaxDay = new Date(
|
||||||
|
Number(tableFilterState.tahun),
|
||||||
|
Number(tableFilterState.bulan),
|
||||||
|
0
|
||||||
|
).getDate();
|
||||||
|
|
||||||
|
const reportDateColumns: ColumnDef<DailyChecklistReport>[] = [];
|
||||||
|
|
||||||
|
if (isResponseSuccess(reportResponse) && reportResponse.data) {
|
||||||
|
for (let dateNumber = 1; dateNumber <= currentMonthMaxDay; dateNumber++) {
|
||||||
|
reportDateColumns.push({
|
||||||
|
accessorKey: `daily_activities[${dateNumber}]`,
|
||||||
|
header: `${dateNumber}`,
|
||||||
|
enableSorting: false,
|
||||||
|
cell: ({ row }) => row.original.daily_activities[dateNumber],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const phasesWithCheckedCount = uniquePhasesWithChecked.size;
|
const reportColumns: ColumnDef<DailyChecklistReport>[] = [
|
||||||
const progressPercent =
|
{
|
||||||
totalPhasesInMaster && totalPhasesInMaster > 0
|
accessorKey: 'area',
|
||||||
? Math.round(
|
header: 'Area',
|
||||||
(phasesWithCheckedCount / totalPhasesInMaster) * 100
|
enableSorting: false,
|
||||||
)
|
cell: ({ row }) => row.original.area.name,
|
||||||
: 0;
|
},
|
||||||
|
{
|
||||||
return {
|
accessorKey: 'farm',
|
||||||
checklist_id: checklist.id,
|
header: 'Farm',
|
||||||
date: checklist.date,
|
enableSorting: false,
|
||||||
kandang_id: checklist.kandang_id,
|
cell: ({ row }) => row.original.farm.name,
|
||||||
kandang_name: checklist.kandang?.name || '-',
|
},
|
||||||
category: checklist.category,
|
{
|
||||||
status: checklist.status,
|
accessorKey: 'kandang',
|
||||||
progress_percent: progressPercent,
|
header: 'Kandang',
|
||||||
total_phases: phaseCount || 0,
|
enableSorting: false,
|
||||||
total_activities: activityCount || 0,
|
cell: ({ row }) => row.original.kandang.name,
|
||||||
total_employees: uniqueEmployees.size,
|
},
|
||||||
updated_at: checklist.updated_at,
|
{
|
||||||
};
|
accessorKey: 'abk',
|
||||||
})
|
header: 'ABK',
|
||||||
);
|
enableSorting: false,
|
||||||
|
cell: ({ row }) => (
|
||||||
setReportList(enrichedData);
|
<span className='text-nowrap'>{row.original.abk.name}</span>
|
||||||
} catch (error) {
|
),
|
||||||
console.error('Error fetching reports:', error);
|
},
|
||||||
toast.error('Terjadi kesalahan');
|
{
|
||||||
} finally {
|
accessorKey: 'phase',
|
||||||
setLoading(false);
|
header: 'Phase',
|
||||||
}
|
enableSorting: false,
|
||||||
};
|
cell: ({ row }) => row.original.phase,
|
||||||
|
},
|
||||||
const applyFilters = () => {
|
{
|
||||||
let filtered = [...reportList];
|
header: `Tanggal - ${MONTH_OPTIONS[Number(tableFilterState.bulan) - 1].label} - ${tableFilterState.tahun}`,
|
||||||
|
columns: reportDateColumns,
|
||||||
if (statusFilter && statusFilter !== 'ALL') {
|
},
|
||||||
filtered = filtered.filter((item) => item.status === statusFilter);
|
{
|
||||||
}
|
accessorKey: 'summary.total_checklist',
|
||||||
|
header: 'Total Checklist',
|
||||||
if (kandangFilter && kandangFilter !== 'ALL') {
|
enableSorting: false,
|
||||||
filtered = filtered.filter((item) => item.kandang_id === kandangFilter);
|
},
|
||||||
}
|
{
|
||||||
|
accessorKey: 'summary.jumlah_hari_efektif',
|
||||||
if (searchText) {
|
header: 'Jumlah Hari Efektif',
|
||||||
filtered = filtered.filter(
|
enableSorting: false,
|
||||||
(item) =>
|
},
|
||||||
item.kandang_name.toLowerCase().includes(searchText.toLowerCase()) ||
|
{
|
||||||
item.category.toLowerCase().includes(searchText.toLowerCase()) ||
|
accessorKey: 'summary.abk_percentage',
|
||||||
(CATEGORY_LABELS[item.category] || '')
|
header: 'ABK (%)',
|
||||||
.toLowerCase()
|
enableSorting: false,
|
||||||
.includes(searchText.toLowerCase())
|
},
|
||||||
);
|
{
|
||||||
}
|
accessorKey: 'summary.kandang_percentage',
|
||||||
|
header: 'Kandang (%)',
|
||||||
if (dateFrom) {
|
enableSorting: false,
|
||||||
filtered = filtered.filter(
|
},
|
||||||
(item) => new Date(item.date) >= new Date(dateFrom)
|
{
|
||||||
);
|
header: 'Kategori',
|
||||||
}
|
columns: [
|
||||||
if (dateTo) {
|
{
|
||||||
filtered = filtered.filter(
|
accessorKey: 'summary.kategori.kurang',
|
||||||
(item) => new Date(item.date) <= new Date(dateTo)
|
header: 'Kurang',
|
||||||
);
|
enableSorting: false,
|
||||||
}
|
cell: ({ row }) => (
|
||||||
|
<span className='text-red-400'>
|
||||||
setFilteredReportList(filtered);
|
{row.original.summary.kategori.kurang}
|
||||||
};
|
</span>
|
||||||
|
),
|
||||||
const getStatusBadge = (status: string) => {
|
},
|
||||||
switch (status) {
|
{
|
||||||
case 'DRAFT':
|
accessorKey: 'summary.kategori.cukup',
|
||||||
return (
|
header: 'Cukup',
|
||||||
<Badge
|
enableSorting: false,
|
||||||
variant='outline'
|
cell: ({ row }) => row.original.summary.kategori.cukup,
|
||||||
className='border-gray-300 text-gray-700 bg-white'
|
},
|
||||||
>
|
{
|
||||||
Draft
|
accessorKey: 'summary.kategori.baik',
|
||||||
</Badge>
|
header: 'Baik',
|
||||||
);
|
enableSorting: false,
|
||||||
case 'SUBMITTED':
|
cell: ({ row }) => (
|
||||||
return (
|
<span className='text-green-400'>
|
||||||
<Badge
|
{row.original.summary.kategori.baik}
|
||||||
variant='outline'
|
</span>
|
||||||
className='border-orange-300 text-orange-700 bg-white'
|
),
|
||||||
>
|
},
|
||||||
Submitted
|
],
|
||||||
</Badge>
|
},
|
||||||
);
|
];
|
||||||
case 'APPROVED':
|
|
||||||
return (
|
|
||||||
<Badge
|
|
||||||
variant='outline'
|
|
||||||
className='border-green-300 text-green-700 bg-white'
|
|
||||||
>
|
|
||||||
Approved
|
|
||||||
</Badge>
|
|
||||||
);
|
|
||||||
case 'REJECTED':
|
|
||||||
return (
|
|
||||||
<Badge
|
|
||||||
variant='outline'
|
|
||||||
className='border-red-300 text-red-700 bg-white'
|
|
||||||
>
|
|
||||||
Rejected
|
|
||||||
</Badge>
|
|
||||||
);
|
|
||||||
default:
|
|
||||||
return (
|
|
||||||
<Badge
|
|
||||||
variant='outline'
|
|
||||||
className='border-gray-300 text-gray-700 bg-white'
|
|
||||||
>
|
|
||||||
{status}
|
|
||||||
</Badge>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const formatDate = (dateString: string) => {
|
|
||||||
const date = new Date(dateString);
|
|
||||||
return date.toLocaleDateString('id-ID', {
|
|
||||||
day: '2-digit',
|
|
||||||
month: 'short',
|
|
||||||
year: 'numeric',
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const formatDateTime = (dateString: string) => {
|
|
||||||
const date = new Date(dateString);
|
|
||||||
return date.toLocaleString('id-ID', {
|
|
||||||
day: '2-digit',
|
|
||||||
month: 'short',
|
|
||||||
year: 'numeric',
|
|
||||||
hour: '2-digit',
|
|
||||||
minute: '2-digit',
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleViewDetail = (checklistId: string) => {
|
|
||||||
// Navigate to detail page (same as List Daily Checklist)
|
|
||||||
router.push(`/list-daily-checklist/detail?checklistId=${checklistId}`);
|
|
||||||
};
|
|
||||||
|
|
||||||
const exportToCSV = () => {
|
const exportToCSV = () => {
|
||||||
toast.info('Export CSV akan segera tersedia');
|
DailyChecklistApi.exportDailyChecklistReportToExcel(
|
||||||
|
getTableFilterQueryString()
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const monthChangeHandler = (value: string) => updateFilter('bulan', value);
|
||||||
|
const yearChangeHandler = (value: string) => updateFilter('tahun', value);
|
||||||
|
|
||||||
|
const areaChangeHandler = (value: string) => {
|
||||||
|
updateFilter('area_id', value === 'ALL' ? '' : value);
|
||||||
|
updateFilter('location_id', '');
|
||||||
|
updateFilter('kandang_id', '');
|
||||||
|
updateFilter('employee_id', '');
|
||||||
|
};
|
||||||
|
|
||||||
|
const locationChangeHandler = (value: string) => {
|
||||||
|
updateFilter('location_id', value === 'ALL' ? '' : value);
|
||||||
|
updateFilter('kandang_id', '');
|
||||||
|
updateFilter('employee_id', '');
|
||||||
|
};
|
||||||
|
|
||||||
|
const kandangChangeHandler = (value: string) => {
|
||||||
|
updateFilter('kandang_id', value === 'ALL' ? '' : value);
|
||||||
|
updateFilter('employee_id', '');
|
||||||
|
};
|
||||||
|
|
||||||
|
const phaseChangeHandler = (value: string) => {
|
||||||
|
updateFilter('phase_id', value);
|
||||||
|
};
|
||||||
|
|
||||||
|
const employeeChangeHandler = (value: string) => {
|
||||||
|
updateFilter('employee_id', value === 'ALL' ? '' : value);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -395,22 +325,100 @@ export function DailyChecklistReportsContent() {
|
|||||||
{/* Filters Section */}
|
{/* Filters Section */}
|
||||||
<div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6 pb-6 border-b border-gray-200'>
|
<div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6 pb-6 border-b border-gray-200'>
|
||||||
<div>
|
<div>
|
||||||
<Label>Periode Tanggal</Label>
|
<Label htmlFor='bulan-filter-report'>Bulan</Label>
|
||||||
<div className='mt-1.5'>
|
<Select
|
||||||
<DateRangePicker
|
value={tableFilterState.bulan}
|
||||||
dateFrom={dateFrom}
|
onValueChange={monthChangeHandler}
|
||||||
dateTo={dateTo}
|
>
|
||||||
onDateChange={(from, to) => {
|
<SelectTrigger
|
||||||
setDateFrom(from);
|
id='bulan-filter-report'
|
||||||
setDateTo(to);
|
className='mt-1.5 border-gray-200'
|
||||||
}}
|
>
|
||||||
/>
|
<SelectValue placeholder='Semua Bulan' />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{MONTH_OPTIONS.map((bulan) => (
|
||||||
|
<SelectItem key={bulan.value} value={String(bulan.value)}>
|
||||||
|
{bulan.label}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
<div>
|
||||||
|
<Label htmlFor='tahun-filter-report'>Tahun</Label>
|
||||||
|
<Select
|
||||||
|
value={tableFilterState.tahun}
|
||||||
|
onValueChange={yearChangeHandler}
|
||||||
|
>
|
||||||
|
<SelectTrigger
|
||||||
|
id='tahun-filter-report'
|
||||||
|
className='mt-1.5 border-gray-200'
|
||||||
|
>
|
||||||
|
<SelectValue placeholder='Semua Tahun' />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{YEAR_OPTIONS.map((tahun) => (
|
||||||
|
<SelectItem key={tahun.value} value={String(tahun.value)}>
|
||||||
|
{tahun.label}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Label htmlFor='area-filter-report'>Area</Label>
|
||||||
|
<Select
|
||||||
|
value={tableFilterState.area_id}
|
||||||
|
onValueChange={areaChangeHandler}
|
||||||
|
>
|
||||||
|
<SelectTrigger
|
||||||
|
id='area-filter-report'
|
||||||
|
className='mt-1.5 border-gray-200'
|
||||||
|
>
|
||||||
|
<SelectValue placeholder='Semua Area' />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value='ALL'>Semua Area</SelectItem>
|
||||||
|
{areaOptions.map((area) => (
|
||||||
|
<SelectItem key={area.value} value={String(area.value)}>
|
||||||
|
{area.label}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Label htmlFor='location-filter-report'>Lokasi</Label>
|
||||||
|
<Select
|
||||||
|
value={tableFilterState.location_id}
|
||||||
|
onValueChange={locationChangeHandler}
|
||||||
|
>
|
||||||
|
<SelectTrigger
|
||||||
|
id='location-filter-report'
|
||||||
|
className='mt-1.5 border-gray-200'
|
||||||
|
>
|
||||||
|
<SelectValue placeholder='Semua Lokasi' />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value='ALL'>Semua Lokasi</SelectItem>
|
||||||
|
{locationOptions.map((location) => (
|
||||||
|
<SelectItem
|
||||||
|
key={location.value}
|
||||||
|
value={String(location.value)}
|
||||||
|
>
|
||||||
|
{location.label}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor='kandang-filter-report'>Kandang</Label>
|
<Label htmlFor='kandang-filter-report'>Kandang</Label>
|
||||||
<Select value={kandangFilter} onValueChange={setKandangFilter}>
|
<Select
|
||||||
|
value={tableFilterState.kandang_id}
|
||||||
|
onValueChange={kandangChangeHandler}
|
||||||
|
>
|
||||||
<SelectTrigger
|
<SelectTrigger
|
||||||
id='kandang-filter-report'
|
id='kandang-filter-report'
|
||||||
className='mt-1.5 border-gray-200'
|
className='mt-1.5 border-gray-200'
|
||||||
@@ -419,168 +427,105 @@ export function DailyChecklistReportsContent() {
|
|||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value='ALL'>Semua Kandang</SelectItem>
|
<SelectItem value='ALL'>Semua Kandang</SelectItem>
|
||||||
{kandangList.map((kandang) => (
|
{kandangOptions.map((kandang) => (
|
||||||
<SelectItem key={kandang.id} value={kandang.id}>
|
<SelectItem
|
||||||
{kandang.name}
|
key={kandang.value}
|
||||||
|
value={String(kandang.value)}
|
||||||
|
>
|
||||||
|
{kandang.label}
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
))}
|
))}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor='status-filter-report'>Status</Label>
|
<Label htmlFor='phase-filter-report'>Phase</Label>
|
||||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
<Select
|
||||||
|
value={tableFilterState.phase_id}
|
||||||
|
onValueChange={phaseChangeHandler}
|
||||||
|
>
|
||||||
<SelectTrigger
|
<SelectTrigger
|
||||||
id='status-filter-report'
|
id='phase-filter-report'
|
||||||
className='mt-1.5 border-gray-200'
|
className='mt-1.5 border-gray-200'
|
||||||
>
|
>
|
||||||
<SelectValue placeholder='Semua Status' />
|
<SelectValue placeholder='Semua Phase' />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
{STATUS_OPTIONS.map((option) => (
|
<SelectItem value='ALL'>Semua Phase</SelectItem>
|
||||||
<SelectItem key={option.value} value={option.value}>
|
{phaseOptions.map((phase) => (
|
||||||
{option.label}
|
<SelectItem key={phase.value} value={String(phase.value)}>
|
||||||
|
{phase.label}
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
))}
|
))}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor='search-text-report'>Cari</Label>
|
<Label htmlFor='employee-filter-report'>ABK</Label>
|
||||||
<div className='relative mt-1.5'>
|
<Select
|
||||||
<Input
|
value={tableFilterState.employee_id}
|
||||||
id='search-text-report'
|
onValueChange={employeeChangeHandler}
|
||||||
type='text'
|
>
|
||||||
placeholder='Kandang / Kategori...'
|
<SelectTrigger
|
||||||
value={searchText}
|
id='employee-filter-report'
|
||||||
onChange={(e) => setSearchText(e.target.value)}
|
className='mt-1.5 border-gray-200'
|
||||||
className='border-gray-200 pl-9'
|
>
|
||||||
/>
|
<SelectValue placeholder='Semua ABK' />
|
||||||
<Search className='absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400' />
|
</SelectTrigger>
|
||||||
</div>
|
<SelectContent>
|
||||||
|
<SelectItem value='ALL'>Semua ABK</SelectItem>
|
||||||
|
{employeeOptions.map((employee) => (
|
||||||
|
<SelectItem
|
||||||
|
key={employee.value}
|
||||||
|
value={String(employee.value)}
|
||||||
|
>
|
||||||
|
{employee.label}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Reports Table */}
|
{/* Reports Table */}
|
||||||
{loading ? (
|
<Table<DailyChecklistReport>
|
||||||
<div className='text-center py-12 text-gray-500'>
|
data={
|
||||||
Memuat data...
|
isResponseSuccess(reportResponse)
|
||||||
</div>
|
? reportResponse.data || []
|
||||||
) : filteredReportList.length > 0 ? (
|
: []
|
||||||
<div className='overflow-x-auto'>
|
|
||||||
<table className='w-full border border-gray-200 rounded-lg'>
|
|
||||||
<thead>
|
|
||||||
<tr className='bg-gray-50 border-b border-gray-200'>
|
|
||||||
<th className='text-left py-3 px-4 text-sm font-semibold text-gray-700'>
|
|
||||||
Tanggal
|
|
||||||
</th>
|
|
||||||
<th className='text-left py-3 px-4 text-sm font-semibold text-gray-700'>
|
|
||||||
Kandang
|
|
||||||
</th>
|
|
||||||
<th className='text-left py-3 px-4 text-sm font-semibold text-gray-700'>
|
|
||||||
Kategori
|
|
||||||
</th>
|
|
||||||
<th className='text-left py-3 px-4 text-sm font-semibold text-gray-700'>
|
|
||||||
Status
|
|
||||||
</th>
|
|
||||||
<th className='text-center py-3 px-4 text-sm font-semibold text-gray-700'>
|
|
||||||
Phase
|
|
||||||
</th>
|
|
||||||
<th className='text-center py-3 px-4 text-sm font-semibold text-gray-700'>
|
|
||||||
Aktivitas
|
|
||||||
</th>
|
|
||||||
<th className='text-center py-3 px-4 text-sm font-semibold text-gray-700'>
|
|
||||||
ABK
|
|
||||||
</th>
|
|
||||||
<th className='text-center py-3 px-4 text-sm font-semibold text-gray-700'>
|
|
||||||
Progress
|
|
||||||
</th>
|
|
||||||
<th className='text-left py-3 px-4 text-sm font-semibold text-gray-700'>
|
|
||||||
Updated At
|
|
||||||
</th>
|
|
||||||
<th className='text-center py-3 px-4 text-sm font-semibold text-gray-700'>
|
|
||||||
Aksi
|
|
||||||
</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{filteredReportList.map((item, index) => (
|
|
||||||
<tr
|
|
||||||
key={`${item.checklist_id}-${item.date}-${index}`}
|
|
||||||
className={
|
|
||||||
index % 2 === 0 ? 'bg-white' : 'bg-gray-50/50'
|
|
||||||
}
|
}
|
||||||
>
|
columns={reportColumns}
|
||||||
<td className='py-3 px-4 text-sm text-gray-900'>
|
isLoading={isLoadingReport}
|
||||||
{formatDate(item.date)}
|
pageSize={tableFilterState.pageSize}
|
||||||
</td>
|
onPageSizeChange={setPageSize}
|
||||||
<td className='py-3 px-4 text-sm text-gray-900'>
|
rowOptions={[10, 20, 50, 100]}
|
||||||
{item.kandang_name}
|
page={
|
||||||
</td>
|
isResponseSuccess(reportResponse)
|
||||||
<td className='py-3 px-4 text-sm text-gray-900'>
|
? reportResponse?.meta?.page
|
||||||
{CATEGORY_LABELS[item.category] || item.category}
|
: 0
|
||||||
</td>
|
}
|
||||||
<td className='py-3 px-4'>
|
totalItems={
|
||||||
{getStatusBadge(item.status)}
|
isResponseSuccess(reportResponse)
|
||||||
</td>
|
? reportResponse?.meta?.total_results
|
||||||
<td className='py-3 px-4 text-center text-sm text-gray-900'>
|
: 0
|
||||||
{item.total_phases}
|
}
|
||||||
</td>
|
onPageChange={setPage}
|
||||||
<td className='py-3 px-4 text-center text-sm text-gray-900'>
|
className={{
|
||||||
{item.total_activities}
|
containerClassName: cn({
|
||||||
</td>
|
'w-full mb-20':
|
||||||
<td className='py-3 px-4 text-center text-sm text-gray-900'>
|
isResponseSuccess(reportResponse) &&
|
||||||
{item.total_employees}
|
reportResponse?.data?.length === 0,
|
||||||
</td>
|
}),
|
||||||
<td className='py-3 px-4 text-center'>
|
tableWrapperClassName:
|
||||||
<div className='flex items-center justify-center gap-2'>
|
'overflow-x-auto border border-solid border-base-content/10 rounded-none',
|
||||||
<div className='w-20 bg-gray-200 rounded-full h-2'>
|
headerRowClassName: 'bg-gray-50/50',
|
||||||
<div
|
headerColumnClassName:
|
||||||
className='bg-[#0069e0] h-2 rounded-full transition-all'
|
'text-left py-3.5 px-6 text-sm font-semibold text-gray-700 border-x border-base-content/10',
|
||||||
style={{ width: `${item.progress_percent}%` }}
|
bodyColumnClassName:
|
||||||
|
'px-4 py-3 text-base-content border-x border-base-content/10',
|
||||||
|
paginationClassName: 'px-4',
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
<span className='text-sm text-gray-700 font-medium'>
|
|
||||||
{item.progress_percent}%
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
<td className='py-3 px-4 text-sm text-gray-600'>
|
|
||||||
{formatDateTime(item.updated_at)}
|
|
||||||
</td>
|
|
||||||
<td className='py-3 px-4'>
|
|
||||||
<div className='flex items-center justify-center'>
|
|
||||||
<Button
|
|
||||||
size='sm'
|
|
||||||
variant='outline'
|
|
||||||
onClick={() =>
|
|
||||||
handleViewDetail(item.checklist_id)
|
|
||||||
}
|
|
||||||
className='border-gray-200 text-gray-700 hover:bg-gray-50'
|
|
||||||
>
|
|
||||||
<Eye className='w-4 h-4 mr-1' />
|
|
||||||
Detail
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
))}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className='text-center py-12 text-gray-500'>
|
|
||||||
{searchText ||
|
|
||||||
dateFrom ||
|
|
||||||
dateTo ||
|
|
||||||
statusFilter !== 'ALL' ||
|
|
||||||
kandangFilter !== 'ALL'
|
|
||||||
? 'Tidak ada data yang sesuai dengan filter'
|
|
||||||
: 'Belum ada data checklist'}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,6 +0,0 @@
|
|||||||
// TODO: delete this file later
|
|
||||||
|
|
||||||
/* AUTOGENERATED FILE - DO NOT EDIT CONTENTS */
|
|
||||||
|
|
||||||
export const projectId = 'xxx';
|
|
||||||
export const publicAnonKey = 'xxx';
|
|
||||||
@@ -1,339 +0,0 @@
|
|||||||
import { createClient, SupabaseClient } from '@supabase/supabase-js';
|
|
||||||
import { projectId, publicAnonKey } from '@/figma-make/lib/info';
|
|
||||||
|
|
||||||
// ============================================
|
|
||||||
// 🔍 SUPABASE ENVIRONMENT DEBUG CHECK
|
|
||||||
// ============================================
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get environment variable from multiple sources
|
|
||||||
* Checks in order: __ENV__, window.__ENV__, process.env, import.meta.env
|
|
||||||
*/
|
|
||||||
function getEnv(key: string): string | undefined {
|
|
||||||
let value: string | undefined;
|
|
||||||
let source: string | undefined;
|
|
||||||
|
|
||||||
// Check globalThis.__ENV__
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
if ((globalThis as any).__ENV__?.[key]) {
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
value = (globalThis as any).__ENV__[key];
|
|
||||||
source = 'globalThis.__ENV__';
|
|
||||||
}
|
|
||||||
// Check window.__ENV__
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
else if (typeof window !== 'undefined' && (window as any).__ENV__?.[key]) {
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
value = (window as any).__ENV__[key];
|
|
||||||
source = 'window.__ENV__';
|
|
||||||
}
|
|
||||||
// Check process.env
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
else if ((globalThis as any).process?.env?.[key]) {
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
value = (globalThis as any).process.env[key];
|
|
||||||
source = 'process.env';
|
|
||||||
}
|
|
||||||
// Check import.meta.env (if available)
|
|
||||||
else if (
|
|
||||||
typeof import.meta !== 'undefined' &&
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
(import.meta as any)?.env?.[key]
|
|
||||||
) {
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
value = (import.meta as any).env[key];
|
|
||||||
source = 'import.meta.env';
|
|
||||||
}
|
|
||||||
|
|
||||||
if (value && source) {
|
|
||||||
console.log(`✅ ${key} loaded from: ${source}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Try to read from environment variables first
|
|
||||||
let supabaseUrl = getEnv('VITE_SUPABASE_URL');
|
|
||||||
let supabaseAnonKey = getEnv('VITE_SUPABASE_ANON_KEY');
|
|
||||||
|
|
||||||
// Fallback to Figma Make autogenerated credentials
|
|
||||||
if (!supabaseUrl || !supabaseAnonKey) {
|
|
||||||
console.log(
|
|
||||||
'📋 Using Figma Make autogenerated Supabase credentials from /utils/supabase/info.tsx'
|
|
||||||
);
|
|
||||||
supabaseUrl = `https://${projectId}.supabase.co`;
|
|
||||||
supabaseAnonKey = publicAnonKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Helper function to mask sensitive data
|
|
||||||
const maskString = (str: string | undefined): string => {
|
|
||||||
if (!str) return 'undefined';
|
|
||||||
if (str.length <= 20) return str.substring(0, 10) + '...';
|
|
||||||
return str.substring(0, 20) + '...' + `(${str.length - 20} chars masked)`;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Debug logging
|
|
||||||
console.group('🔍 Supabase Environment Check');
|
|
||||||
console.log('projectId (from info.tsx):', projectId);
|
|
||||||
console.log('SUPABASE_URL present?', !!supabaseUrl);
|
|
||||||
console.log('SUPABASE_KEY present?', !!supabaseAnonKey);
|
|
||||||
console.log('SUPABASE_URL value:', maskString(supabaseUrl));
|
|
||||||
console.log('SUPABASE_KEY value:', maskString(supabaseAnonKey));
|
|
||||||
console.groupEnd();
|
|
||||||
|
|
||||||
// Check if Supabase is configured
|
|
||||||
export const isSupabaseConfigured = () => {
|
|
||||||
return !!(supabaseUrl && supabaseAnonKey);
|
|
||||||
};
|
|
||||||
|
|
||||||
// Create Supabase client or throw error
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
let supabase: SupabaseClient<any>;
|
|
||||||
|
|
||||||
if (isSupabaseConfigured()) {
|
|
||||||
console.log('✅ Creating real Supabase client...');
|
|
||||||
supabase = createClient<Database>(supabaseUrl!, supabaseAnonKey!);
|
|
||||||
console.log('✅ Supabase client created successfully!');
|
|
||||||
} else {
|
|
||||||
const errorMessage = `
|
|
||||||
❌ SUPABASE CONFIGURATION ERROR ❌
|
|
||||||
|
|
||||||
Missing required environment variables:
|
|
||||||
- VITE_SUPABASE_URL: ${!!supabaseUrl ? '✅ Present' : '❌ Missing'}
|
|
||||||
- VITE_SUPABASE_ANON_KEY: ${!!supabaseAnonKey ? '✅ Present' : '❌ Missing'}
|
|
||||||
|
|
||||||
Please set Supabase environment variables in:
|
|
||||||
→ Figma Make Supabase integration settings
|
|
||||||
→ Deployment settings/environment configuration
|
|
||||||
|
|
||||||
The app checked the following sources:
|
|
||||||
- globalThis.__ENV__
|
|
||||||
- window.__ENV__
|
|
||||||
- process.env
|
|
||||||
- import.meta.env
|
|
||||||
|
|
||||||
None of these sources contained the required variables.
|
|
||||||
`.trim();
|
|
||||||
|
|
||||||
console.error(errorMessage);
|
|
||||||
throw new Error(errorMessage);
|
|
||||||
}
|
|
||||||
|
|
||||||
export { supabase };
|
|
||||||
|
|
||||||
// Database types
|
|
||||||
export interface Database {
|
|
||||||
public: {
|
|
||||||
Tables: {
|
|
||||||
kandang: {
|
|
||||||
Row: {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
created_at?: string;
|
|
||||||
};
|
|
||||||
Insert: {
|
|
||||||
id?: string;
|
|
||||||
name: string;
|
|
||||||
created_at?: string;
|
|
||||||
};
|
|
||||||
Update: {
|
|
||||||
id?: string;
|
|
||||||
name?: string;
|
|
||||||
created_at?: string;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
employees: {
|
|
||||||
Row: {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
kandang_id: string;
|
|
||||||
is_active: boolean;
|
|
||||||
created_at?: string;
|
|
||||||
};
|
|
||||||
Insert: {
|
|
||||||
id?: string;
|
|
||||||
name: string;
|
|
||||||
kandang_id: string;
|
|
||||||
is_active?: boolean;
|
|
||||||
created_at?: string;
|
|
||||||
};
|
|
||||||
Update: {
|
|
||||||
id?: string;
|
|
||||||
name?: string;
|
|
||||||
kandang_id?: string;
|
|
||||||
is_active?: boolean;
|
|
||||||
created_at?: string;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
phases: {
|
|
||||||
Row: {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
created_at?: string;
|
|
||||||
updated_at?: string;
|
|
||||||
};
|
|
||||||
Insert: {
|
|
||||||
id?: string;
|
|
||||||
name: string;
|
|
||||||
created_at?: string;
|
|
||||||
updated_at?: string;
|
|
||||||
};
|
|
||||||
Update: {
|
|
||||||
id?: string;
|
|
||||||
name?: string;
|
|
||||||
created_at?: string;
|
|
||||||
updated_at?: string;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
phase_activities: {
|
|
||||||
Row: {
|
|
||||||
id: string;
|
|
||||||
phase_id: string;
|
|
||||||
name: string;
|
|
||||||
description?: string;
|
|
||||||
created_at?: string;
|
|
||||||
updated_at?: string;
|
|
||||||
};
|
|
||||||
Insert: {
|
|
||||||
id?: string;
|
|
||||||
phase_id: string;
|
|
||||||
name: string;
|
|
||||||
description?: string;
|
|
||||||
created_at?: string;
|
|
||||||
updated_at?: string;
|
|
||||||
};
|
|
||||||
Update: {
|
|
||||||
id?: string;
|
|
||||||
phase_id?: string;
|
|
||||||
name?: string;
|
|
||||||
description?: string;
|
|
||||||
created_at?: string;
|
|
||||||
updated_at?: string;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
checklists: {
|
|
||||||
Row: {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
description?: string;
|
|
||||||
phase_id: string;
|
|
||||||
created_at?: string;
|
|
||||||
updated_at?: string;
|
|
||||||
};
|
|
||||||
Insert: {
|
|
||||||
id?: string;
|
|
||||||
name: string;
|
|
||||||
description?: string;
|
|
||||||
phase_id: string;
|
|
||||||
created_at?: string;
|
|
||||||
updated_at?: string;
|
|
||||||
};
|
|
||||||
Update: {
|
|
||||||
id?: string;
|
|
||||||
name?: string;
|
|
||||||
description?: string;
|
|
||||||
phase_id?: string;
|
|
||||||
created_at?: string;
|
|
||||||
updated_at?: string;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
daily_checklists: {
|
|
||||||
Row: {
|
|
||||||
id: string;
|
|
||||||
date: string;
|
|
||||||
kandang_id: string;
|
|
||||||
checklist_id: string;
|
|
||||||
category: string;
|
|
||||||
status: string;
|
|
||||||
name?: string;
|
|
||||||
total_score?: number;
|
|
||||||
document_path?: string;
|
|
||||||
reject_reason?: string;
|
|
||||||
created_by: string;
|
|
||||||
created_at?: string;
|
|
||||||
updated_at?: string;
|
|
||||||
};
|
|
||||||
Insert: {
|
|
||||||
id?: string;
|
|
||||||
date: string;
|
|
||||||
kandang_id: string;
|
|
||||||
checklist_id: string;
|
|
||||||
category: string;
|
|
||||||
status?: string;
|
|
||||||
name?: string;
|
|
||||||
total_score?: number;
|
|
||||||
document_path?: string;
|
|
||||||
reject_reason?: string;
|
|
||||||
created_at?: string;
|
|
||||||
updated_at?: string;
|
|
||||||
};
|
|
||||||
Update: {
|
|
||||||
id?: string;
|
|
||||||
date?: string;
|
|
||||||
kandang_id?: string;
|
|
||||||
checklist_id?: string;
|
|
||||||
category?: string;
|
|
||||||
status?: string;
|
|
||||||
name?: string;
|
|
||||||
total_score?: number;
|
|
||||||
document_path?: string;
|
|
||||||
reject_reason?: string;
|
|
||||||
created_at?: string;
|
|
||||||
updated_at?: string;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
daily_checklist_tasks: {
|
|
||||||
Row: {
|
|
||||||
id: string;
|
|
||||||
checklist_id: string;
|
|
||||||
activity_id: string;
|
|
||||||
notes?: string;
|
|
||||||
created_at?: string;
|
|
||||||
updated_at?: string;
|
|
||||||
};
|
|
||||||
Insert: {
|
|
||||||
id?: string;
|
|
||||||
checklist_id: string;
|
|
||||||
activity_id: string;
|
|
||||||
notes?: string;
|
|
||||||
created_at?: string;
|
|
||||||
updated_at?: string;
|
|
||||||
};
|
|
||||||
Update: {
|
|
||||||
id?: string;
|
|
||||||
checklist_id?: string;
|
|
||||||
activity_id?: string;
|
|
||||||
notes?: string;
|
|
||||||
created_at?: string;
|
|
||||||
updated_at?: string;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
task_assignees: {
|
|
||||||
Row: {
|
|
||||||
id: string;
|
|
||||||
task_id: string;
|
|
||||||
employee_id: string;
|
|
||||||
is_completed: boolean;
|
|
||||||
created_at?: string;
|
|
||||||
updated_at?: string;
|
|
||||||
};
|
|
||||||
Insert: {
|
|
||||||
id?: string;
|
|
||||||
task_id: string;
|
|
||||||
employee_id: string;
|
|
||||||
is_completed?: boolean;
|
|
||||||
created_at?: string;
|
|
||||||
updated_at?: string;
|
|
||||||
};
|
|
||||||
Update: {
|
|
||||||
id?: string;
|
|
||||||
task_id?: string;
|
|
||||||
employee_id?: string;
|
|
||||||
is_completed?: boolean;
|
|
||||||
created_at?: string;
|
|
||||||
updated_at?: string;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
};
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -37,6 +37,23 @@ export class ClosingApiService extends BaseApiService<Closing, null, null> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getPenjualanByKandang(
|
||||||
|
closingId: number,
|
||||||
|
kandangId: number
|
||||||
|
): Promise<BaseApiResponse<ClosingSales> | undefined> {
|
||||||
|
try {
|
||||||
|
const path = `${this.basePath}/${closingId}/${kandangId}/penjualan`;
|
||||||
|
return await httpClient<BaseApiResponse<ClosingSales>>(path, {
|
||||||
|
method: 'GET',
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (axios.isAxiosError<BaseApiResponse<ClosingSales>>(error)) {
|
||||||
|
return error.response?.data;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async getAllIncomingSapronakFetcher(
|
async getAllIncomingSapronakFetcher(
|
||||||
endpoint: string
|
endpoint: string
|
||||||
): Promise<BaseApiResponse<ClosingIncomingSapronak[]>> {
|
): Promise<BaseApiResponse<ClosingIncomingSapronak[]>> {
|
||||||
@@ -92,10 +109,11 @@ export class ClosingApiService extends BaseApiService<Closing, null, null> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async getPerhitunganSapronak(
|
async getPerhitunganSapronak(
|
||||||
id: number
|
id: number,
|
||||||
|
projectKandangId?: number
|
||||||
): Promise<BaseApiResponse<ClosingSapronakCalculation> | undefined> {
|
): Promise<BaseApiResponse<ClosingSapronakCalculation> | undefined> {
|
||||||
try {
|
try {
|
||||||
const path = `${this.basePath}/${id}/perhitungan_sapronak`;
|
const path = `${this.basePath}/${id}${projectKandangId ? `/${projectKandangId}` : ''}/perhitungan_sapronak`;
|
||||||
return await httpClient<BaseApiResponse<ClosingSapronakCalculation>>(
|
return await httpClient<BaseApiResponse<ClosingSapronakCalculation>>(
|
||||||
path,
|
path,
|
||||||
{
|
{
|
||||||
@@ -161,6 +179,23 @@ export class ClosingApiService extends BaseApiService<Closing, null, null> {
|
|||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getHppEkspedisiByKandang(
|
||||||
|
closingId: number,
|
||||||
|
kandangId: number
|
||||||
|
): Promise<BaseApiResponse<ClosingHppExpedition> | undefined> {
|
||||||
|
try {
|
||||||
|
const path = `${this.basePath}/${closingId}/${kandangId}/expedition-hpp`;
|
||||||
|
return await httpClient<BaseApiResponse<ClosingHppExpedition>>(path, {
|
||||||
|
method: 'GET',
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (axios.isAxiosError<BaseApiResponse<ClosingHppExpedition>>(error)) {
|
||||||
|
return error.response?.data;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const ClosingApi = new ClosingApiService('/closings');
|
export const ClosingApi = new ClosingApiService('/closings');
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { BaseApiService } from '@/services/api/base';
|
||||||
|
import {
|
||||||
|
CreateDailyChecklistConfigurationPayload,
|
||||||
|
DailyChecklistConfiguration,
|
||||||
|
UpdateDailyChecklistConfigurationPayload,
|
||||||
|
} from '@/types/api/daily-checklist/configuration';
|
||||||
|
|
||||||
|
export class DailyChecklistConfigurationApiService extends BaseApiService<
|
||||||
|
DailyChecklistConfiguration,
|
||||||
|
CreateDailyChecklistConfigurationPayload,
|
||||||
|
UpdateDailyChecklistConfigurationPayload
|
||||||
|
> {
|
||||||
|
constructor(basePath: string = '/master-data/config-checklists') {
|
||||||
|
super(basePath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DailyChecklistConfigurationApi =
|
||||||
|
new DailyChecklistConfigurationApiService('/master-data/config-checklists');
|
||||||
@@ -1,13 +1,18 @@
|
|||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
|
import * as XLSX from 'xlsx';
|
||||||
|
|
||||||
import { BaseApiService } from '@/services/api/base';
|
import { BaseApiService } from '@/services/api/base';
|
||||||
import { httpClient } from '@/services/http/client';
|
import { httpClient, httpClientFetcher } from '@/services/http/client';
|
||||||
import { BaseApiResponse } from '@/types/api/api-general';
|
import { BaseApiResponse } from '@/types/api/api-general';
|
||||||
import {
|
import {
|
||||||
CreateDailyChecklistPayload,
|
CreateDailyChecklistPayload,
|
||||||
DailyChecklist,
|
DailyChecklist,
|
||||||
|
DailyChecklistReport,
|
||||||
DetailDailyChecklist,
|
DetailDailyChecklist,
|
||||||
} from '@/types/api/daily-checklist/daily-checklist';
|
} from '@/types/api/daily-checklist/daily-checklist';
|
||||||
|
import { isResponseError } from '@/lib/api-helper';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
import { formatDate } from '@/lib/helper';
|
||||||
|
|
||||||
export class DailyChecklistApiService extends BaseApiService<
|
export class DailyChecklistApiService extends BaseApiService<
|
||||||
DailyChecklist,
|
DailyChecklist,
|
||||||
@@ -134,15 +139,26 @@ export class DailyChecklistApiService extends BaseApiService<
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async submit(id: string) {
|
async submit(
|
||||||
|
id: string,
|
||||||
|
files: File[] = [],
|
||||||
|
deletedDocumentIds: number[] = []
|
||||||
|
) {
|
||||||
try {
|
try {
|
||||||
|
const formData = new FormData();
|
||||||
|
|
||||||
|
formData.append('status', 'SUBMITTED');
|
||||||
|
|
||||||
|
formData.append('reject_reason', '');
|
||||||
|
|
||||||
|
files.forEach((file) => formData.append(`documents`, file));
|
||||||
|
|
||||||
|
formData.append('deleted_document_ids', deletedDocumentIds.join(','));
|
||||||
|
|
||||||
const submitPath = `${this.basePath}/${id}`;
|
const submitPath = `${this.basePath}/${id}`;
|
||||||
const submitRes = await httpClient<BaseApiResponse>(submitPath, {
|
const submitRes = await httpClient<BaseApiResponse>(submitPath, {
|
||||||
method: 'PATCH',
|
method: 'PATCH',
|
||||||
body: {
|
body: formData,
|
||||||
status: 'SUBMITTED',
|
|
||||||
reject_reason: '',
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return submitRes;
|
return submitRes;
|
||||||
@@ -156,13 +172,16 @@ export class DailyChecklistApiService extends BaseApiService<
|
|||||||
|
|
||||||
async approve(id: string) {
|
async approve(id: string) {
|
||||||
try {
|
try {
|
||||||
|
const formData = new FormData();
|
||||||
|
|
||||||
|
formData.append('status', 'APPROVED');
|
||||||
|
|
||||||
|
formData.append('reject_reason', '');
|
||||||
|
|
||||||
const approvePath = `${this.basePath}/${id}`;
|
const approvePath = `${this.basePath}/${id}`;
|
||||||
const approveRes = await httpClient<BaseApiResponse>(approvePath, {
|
const approveRes = await httpClient<BaseApiResponse>(approvePath, {
|
||||||
method: 'PATCH',
|
method: 'PATCH',
|
||||||
body: {
|
body: formData,
|
||||||
status: 'APPROVED',
|
|
||||||
reject_reason: '',
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return approveRes;
|
return approveRes;
|
||||||
@@ -176,13 +195,16 @@ export class DailyChecklistApiService extends BaseApiService<
|
|||||||
|
|
||||||
async reject(id: string, rejectReason: string) {
|
async reject(id: string, rejectReason: string) {
|
||||||
try {
|
try {
|
||||||
|
const formData = new FormData();
|
||||||
|
|
||||||
|
formData.append('status', 'REJECTED');
|
||||||
|
|
||||||
|
formData.append('reject_reason', rejectReason);
|
||||||
|
|
||||||
const rejectPath = `${this.basePath}/${id}`;
|
const rejectPath = `${this.basePath}/${id}`;
|
||||||
const rejectRes = await httpClient<BaseApiResponse>(rejectPath, {
|
const rejectRes = await httpClient<BaseApiResponse>(rejectPath, {
|
||||||
method: 'PATCH',
|
method: 'PATCH',
|
||||||
body: {
|
body: formData,
|
||||||
status: 'REJECTED',
|
|
||||||
reject_reason: rejectReason,
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return rejectRes;
|
return rejectRes;
|
||||||
@@ -193,6 +215,111 @@ export class DailyChecklistApiService extends BaseApiService<
|
|||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async uploadImage(
|
||||||
|
id: number,
|
||||||
|
status: string,
|
||||||
|
files: File[],
|
||||||
|
deletedDocumentIds: number[] = []
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const formData = new FormData();
|
||||||
|
|
||||||
|
formData.append('status', status);
|
||||||
|
|
||||||
|
files.forEach((file) => formData.append(`documents`, file));
|
||||||
|
|
||||||
|
formData.append('deleted_document_ids', deletedDocumentIds.join(','));
|
||||||
|
|
||||||
|
const uploadImagePath = `${this.basePath}/${id}`;
|
||||||
|
const uploadImageRes = await httpClient<BaseApiResponse>(
|
||||||
|
uploadImagePath,
|
||||||
|
{
|
||||||
|
method: 'PATCH',
|
||||||
|
body: formData,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
return uploadImageRes;
|
||||||
|
} catch (error) {
|
||||||
|
if (axios.isAxiosError<BaseApiResponse>(error)) {
|
||||||
|
return error.response?.data;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async exportDailyChecklistReportToExcel(initialQueryString: string) {
|
||||||
|
const params = new URLSearchParams(initialQueryString);
|
||||||
|
|
||||||
|
params.set('limit', '2000');
|
||||||
|
|
||||||
|
const queryString = `?${params.toString()}`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const dailyMarketingsReport = await httpClientFetcher<
|
||||||
|
BaseApiResponse<DailyChecklistReport[]>
|
||||||
|
>(`${this.basePath}/report${queryString}`);
|
||||||
|
|
||||||
|
if (isResponseError(dailyMarketingsReport)) {
|
||||||
|
toast.error('Gagal melakukan export daily checklist! Coba lagi.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const currentMonthMaxDay = new Date(
|
||||||
|
Number(params.get('tahun')),
|
||||||
|
Number(params.get('bulan')),
|
||||||
|
0
|
||||||
|
).getDate();
|
||||||
|
|
||||||
|
const rows = dailyMarketingsReport.data;
|
||||||
|
|
||||||
|
const formattedRows = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < rows.length; i++) {
|
||||||
|
const formattedData: Record<string, string | number> = {
|
||||||
|
Area: rows[i].area.name,
|
||||||
|
Farm: rows[i].farm.name,
|
||||||
|
Kandang: rows[i].kandang.name,
|
||||||
|
ABK: rows[i].abk.name,
|
||||||
|
Phase: rows[i].phase,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add day
|
||||||
|
for (let j = 1; j <= currentMonthMaxDay; j++) {
|
||||||
|
formattedData[`Day ${j}`] = rows[i].daily_activities[`${j}`];
|
||||||
|
}
|
||||||
|
|
||||||
|
// add summary
|
||||||
|
formattedData['Total Checklist'] = rows[i].summary.total_checklist;
|
||||||
|
formattedData['Jumlah Hari Efektif'] =
|
||||||
|
rows[i].summary.jumlah_hari_efektif;
|
||||||
|
formattedData['ABK %'] = rows[i].summary.abk_percentage;
|
||||||
|
formattedData['Kandang %'] = rows[i].summary.kandang_percentage;
|
||||||
|
formattedData['Kategori Kurang'] = rows[i].summary.kategori.kurang;
|
||||||
|
formattedData['Kategori Cukup'] = rows[i].summary.kategori.cukup;
|
||||||
|
formattedData['Kategori Baik'] = rows[i].summary.kategori.baik;
|
||||||
|
|
||||||
|
formattedRows.push(formattedData);
|
||||||
|
}
|
||||||
|
|
||||||
|
const ws = XLSX.utils.json_to_sheet(formattedRows);
|
||||||
|
const wb = XLSX.utils.book_new();
|
||||||
|
XLSX.utils.book_append_sheet(
|
||||||
|
wb,
|
||||||
|
ws,
|
||||||
|
`Daily Checklist ${params.get('tahun')}-${params.get('bulan')?.slice(0, 3)}`
|
||||||
|
);
|
||||||
|
|
||||||
|
// triggers download in browser
|
||||||
|
XLSX.writeFile(
|
||||||
|
wb,
|
||||||
|
`laporan-daily-checklist-${params.get('tahun')}-${params.get('bulan')}.xlsx`
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
toast.error('Gagal melakukan export daily checklist! Coba lagi.');
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const DailyChecklistApi = new DailyChecklistApiService(
|
export const DailyChecklistApi = new DailyChecklistApiService(
|
||||||
|
|||||||
@@ -1,13 +1,9 @@
|
|||||||
import { BaseApiService } from '@/services/api/base';
|
import { BaseApiService } from '@/services/api/base';
|
||||||
import { BaseApiResponse } from '@/types/api/api-general';
|
import { BaseApiResponse } from '@/types/api/api-general';
|
||||||
import { DashboardProduction } from '@/types/api/dashboard/dashboard-production';
|
import { Dashboard } from '@/types/api/dashboard/dashboard';
|
||||||
import { getDummySingle } from '@/dummy/dashboard/dashboard.production.dummy';
|
import { httpClientFetcher } from '@/services/http/client';
|
||||||
|
|
||||||
class DashboardService extends BaseApiService<
|
class DashboardService extends BaseApiService<Dashboard, unknown, unknown> {
|
||||||
DashboardProduction,
|
|
||||||
unknown,
|
|
||||||
unknown
|
|
||||||
> {
|
|
||||||
constructor(basePath: string) {
|
constructor(basePath: string) {
|
||||||
super(basePath);
|
super(basePath);
|
||||||
}
|
}
|
||||||
@@ -16,19 +12,14 @@ class DashboardService extends BaseApiService<
|
|||||||
* Fetch dashboard production data
|
* Fetch dashboard production data
|
||||||
* @param endpoint - The endpoint URL with query parameters
|
* @param endpoint - The endpoint URL with query parameters
|
||||||
* @returns Promise with BaseApiResponse containing DashboardProduction
|
* @returns Promise with BaseApiResponse containing DashboardProduction
|
||||||
*
|
|
||||||
* Note: Currently using dummy data. When real API is ready,
|
|
||||||
* uncomment the line below and remove getDummySingle() call:
|
|
||||||
* return await this.customRequest<BaseApiResponse<DashboardProduction>>(endpoint);
|
|
||||||
*/
|
*/
|
||||||
async getDashboardProductionFetcher(
|
async getDashboardProductionFetcher(
|
||||||
endpoint: string
|
endpoint: string
|
||||||
): Promise<BaseApiResponse<DashboardProduction>> {
|
): Promise<BaseApiResponse<Dashboard> | undefined> {
|
||||||
// For now, we're using dummy data regardless of the endpoint
|
return await httpClientFetcher<BaseApiResponse<Dashboard>>(
|
||||||
// The endpoint parameter is kept for future API integration
|
`${endpoint ? endpoint : this.basePath}`
|
||||||
console.log('Fetching dashboard data with endpoint:', endpoint);
|
);
|
||||||
return await getDummySingle();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const DashboardApi = new DashboardService('/dashboard');
|
export const DashboardApi = new DashboardService('/dashboards');
|
||||||
|
|||||||
+116
-8
@@ -169,13 +169,13 @@ export class ExpenseApiService extends BaseApiService<
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async approveManager(
|
async approveHeadArea(
|
||||||
id: number,
|
id: number,
|
||||||
notes?: string
|
notes?: string
|
||||||
): Promise<BaseApiResponse<Expense> | undefined> {
|
): Promise<BaseApiResponse<Expense> | undefined> {
|
||||||
try {
|
try {
|
||||||
const approveRes = await httpClient<BaseApiResponse<Expense>>(
|
const approveRes = await httpClient<BaseApiResponse<Expense>>(
|
||||||
`${this.basePath}/approvals/manager`,
|
`${this.basePath}/approvals/head-area`,
|
||||||
{
|
{
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: {
|
body: {
|
||||||
@@ -196,13 +196,67 @@ export class ExpenseApiService extends BaseApiService<
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async bulkApproveManager(
|
async bulkApproveHeadArea(
|
||||||
ids: number[],
|
ids: number[],
|
||||||
notes?: string
|
notes?: string
|
||||||
): Promise<BaseApiResponse<Expense> | undefined> {
|
): Promise<BaseApiResponse<Expense> | undefined> {
|
||||||
try {
|
try {
|
||||||
const bulkApproveRes = await httpClient<BaseApiResponse<Expense>>(
|
const bulkApproveRes = await httpClient<BaseApiResponse<Expense>>(
|
||||||
`${this.basePath}/approvals/manager`,
|
`${this.basePath}/approvals/head-area`,
|
||||||
|
{
|
||||||
|
method: 'POST',
|
||||||
|
body: {
|
||||||
|
action: 'APPROVED',
|
||||||
|
approvable_ids: ids,
|
||||||
|
notes: notes,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
return bulkApproveRes;
|
||||||
|
} catch (error) {
|
||||||
|
if (axios.isAxiosError<BaseApiResponse<Expense>>(error)) {
|
||||||
|
return error.response?.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async approveUnitVicePresident(
|
||||||
|
id: number,
|
||||||
|
notes?: string
|
||||||
|
): Promise<BaseApiResponse<Expense> | undefined> {
|
||||||
|
try {
|
||||||
|
const approveRes = await httpClient<BaseApiResponse<Expense>>(
|
||||||
|
`${this.basePath}/approvals/unit-vice-president`,
|
||||||
|
{
|
||||||
|
method: 'POST',
|
||||||
|
body: {
|
||||||
|
action: 'APPROVED',
|
||||||
|
approvable_ids: [id],
|
||||||
|
notes: notes,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
return approveRes;
|
||||||
|
} catch (error) {
|
||||||
|
if (axios.isAxiosError<BaseApiResponse<Expense>>(error)) {
|
||||||
|
return error.response?.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async bulkApproveUnitVicePresident(
|
||||||
|
ids: number[],
|
||||||
|
notes?: string
|
||||||
|
): Promise<BaseApiResponse<Expense> | undefined> {
|
||||||
|
try {
|
||||||
|
const bulkApproveRes = await httpClient<BaseApiResponse<Expense>>(
|
||||||
|
`${this.basePath}/approvals/unit-vice-president`,
|
||||||
{
|
{
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: {
|
body: {
|
||||||
@@ -277,13 +331,13 @@ export class ExpenseApiService extends BaseApiService<
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async rejectManager(
|
async rejectHeadArea(
|
||||||
id: number,
|
id: number,
|
||||||
notes?: string
|
notes?: string
|
||||||
): Promise<BaseApiResponse<Expense> | undefined> {
|
): Promise<BaseApiResponse<Expense> | undefined> {
|
||||||
try {
|
try {
|
||||||
const rejectRes = await httpClient<BaseApiResponse<Expense>>(
|
const rejectRes = await httpClient<BaseApiResponse<Expense>>(
|
||||||
`${this.basePath}/approvals/manager`,
|
`${this.basePath}/approvals/head-area`,
|
||||||
{
|
{
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: {
|
body: {
|
||||||
@@ -304,13 +358,67 @@ export class ExpenseApiService extends BaseApiService<
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async bulkRejectManager(
|
async bulkRejectHeadArea(
|
||||||
ids: number[],
|
ids: number[],
|
||||||
notes?: string
|
notes?: string
|
||||||
): Promise<BaseApiResponse<Expense> | undefined> {
|
): Promise<BaseApiResponse<Expense> | undefined> {
|
||||||
try {
|
try {
|
||||||
const bulkRejectRes = await httpClient<BaseApiResponse<Expense>>(
|
const bulkRejectRes = await httpClient<BaseApiResponse<Expense>>(
|
||||||
`${this.basePath}/approvals/manager`,
|
`${this.basePath}/approvals/head-area`,
|
||||||
|
{
|
||||||
|
method: 'POST',
|
||||||
|
body: {
|
||||||
|
action: 'REJECTED',
|
||||||
|
approvable_ids: ids,
|
||||||
|
notes: notes,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
return bulkRejectRes;
|
||||||
|
} catch (error) {
|
||||||
|
if (axios.isAxiosError<BaseApiResponse<Expense>>(error)) {
|
||||||
|
return error.response?.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async rejectUnitVicePresident(
|
||||||
|
id: number,
|
||||||
|
notes?: string
|
||||||
|
): Promise<BaseApiResponse<Expense> | undefined> {
|
||||||
|
try {
|
||||||
|
const rejectRes = await httpClient<BaseApiResponse<Expense>>(
|
||||||
|
`${this.basePath}/approvals/unit-vice-president`,
|
||||||
|
{
|
||||||
|
method: 'POST',
|
||||||
|
body: {
|
||||||
|
action: 'REJECTED',
|
||||||
|
approvable_ids: [id],
|
||||||
|
notes: notes,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
return rejectRes;
|
||||||
|
} catch (error) {
|
||||||
|
if (axios.isAxiosError<BaseApiResponse<Expense>>(error)) {
|
||||||
|
return error.response?.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async bulkRejectUnitVicePresident(
|
||||||
|
ids: number[],
|
||||||
|
notes?: string
|
||||||
|
): Promise<BaseApiResponse<Expense> | undefined> {
|
||||||
|
try {
|
||||||
|
const bulkRejectRes = await httpClient<BaseApiResponse<Expense>>(
|
||||||
|
`${this.basePath}/approvals/unit-vice-president`,
|
||||||
{
|
{
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: {
|
body: {
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { BaseApiService } from '@/services/api/base';
|
||||||
|
import { BaseApiResponse } from '@/types/api/api-general';
|
||||||
|
import { DebtSupplier } from '@/types/api/report/debt-supplier';
|
||||||
|
|
||||||
|
export class DebtSupplierApiService extends BaseApiService<
|
||||||
|
DebtSupplier,
|
||||||
|
unknown,
|
||||||
|
unknown
|
||||||
|
> {
|
||||||
|
constructor(basePath: string) {
|
||||||
|
super(basePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getDebtSupplierReport(
|
||||||
|
supplier_ids?: string,
|
||||||
|
filter_by?: string,
|
||||||
|
start_date?: string,
|
||||||
|
end_date?: string,
|
||||||
|
page?: number,
|
||||||
|
limit?: number
|
||||||
|
): Promise<BaseApiResponse<DebtSupplier[]> | undefined> {
|
||||||
|
return await this.customRequest<BaseApiResponse<DebtSupplier[]>>(
|
||||||
|
`debt-supplier`,
|
||||||
|
{
|
||||||
|
method: 'GET',
|
||||||
|
params: {
|
||||||
|
supplier_ids: supplier_ids,
|
||||||
|
filter_by: filter_by,
|
||||||
|
start_date: start_date,
|
||||||
|
end_date: end_date,
|
||||||
|
page: page,
|
||||||
|
limit: limit,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DebtSupplierApi = new DebtSupplierApiService('reports');
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import { BaseApiService } from '@/services/api/base';
|
||||||
|
import { BaseApiResponse } from '@/types/api/api-general';
|
||||||
|
import { CustomerPaymentReport } from '@/types/api/report/customer-payment';
|
||||||
|
import { DebtSupplier } from '@/types/api/report/debt-supplier';
|
||||||
|
|
||||||
|
export class FinanceApiService extends BaseApiService<
|
||||||
|
CustomerPaymentReport,
|
||||||
|
unknown,
|
||||||
|
unknown
|
||||||
|
> {
|
||||||
|
constructor(basePath: string) {
|
||||||
|
super(basePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getCustomerPaymentReport(
|
||||||
|
customer_id?: string,
|
||||||
|
sales?: string,
|
||||||
|
filter_by?: 'do_date',
|
||||||
|
start_date?: string,
|
||||||
|
end_date?: string,
|
||||||
|
page?: number,
|
||||||
|
limit?: number
|
||||||
|
): Promise<BaseApiResponse<CustomerPaymentReport> | undefined> {
|
||||||
|
return await this.customRequest<BaseApiResponse<CustomerPaymentReport>>(
|
||||||
|
`customer-payment`,
|
||||||
|
{
|
||||||
|
method: 'GET',
|
||||||
|
params: {
|
||||||
|
customer_id: customer_id,
|
||||||
|
sales: sales,
|
||||||
|
filter_by: filter_by,
|
||||||
|
start_date: start_date,
|
||||||
|
end_date: end_date,
|
||||||
|
page: page,
|
||||||
|
limit: limit,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// export const FinanceApi = new FinanceApiService('reports');
|
||||||
|
|
||||||
|
export const FinanceApi = new FinanceApiService(
|
||||||
|
'http://localhost:4010/api/reports/finance'
|
||||||
|
);
|
||||||
@@ -2,11 +2,14 @@ import * as XLSX from 'xlsx';
|
|||||||
import toast from 'react-hot-toast';
|
import toast from 'react-hot-toast';
|
||||||
|
|
||||||
import { BaseApiService } from '@/services/api/base';
|
import { BaseApiService } from '@/services/api/base';
|
||||||
import { httpClient, httpClientFetcher } from '@/services/http/client';
|
import { httpClientFetcher } from '@/services/http/client';
|
||||||
import { BaseApiResponse } from '@/types/api/api-general';
|
import { BaseApiResponse } from '@/types/api/api-general';
|
||||||
import { DailyMarketingReport } from '@/types/api/report/marketing';
|
import {
|
||||||
|
DailyMarketingReport,
|
||||||
|
DailyMarketingReportResponse,
|
||||||
|
} from '@/types/api/report/marketing';
|
||||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||||
import { formatDate, sleep } from '@/lib/helper';
|
import { formatDate } from '@/lib/helper';
|
||||||
|
|
||||||
export class MarketingReportApiService extends BaseApiService<
|
export class MarketingReportApiService extends BaseApiService<
|
||||||
DailyMarketingReport,
|
DailyMarketingReport,
|
||||||
@@ -19,10 +22,8 @@ export class MarketingReportApiService extends BaseApiService<
|
|||||||
|
|
||||||
async getAllDailyMarketingFetcher(
|
async getAllDailyMarketingFetcher(
|
||||||
endpoint: string
|
endpoint: string
|
||||||
): Promise<BaseApiResponse<DailyMarketingReport>> {
|
): Promise<DailyMarketingReportResponse> {
|
||||||
return await httpClientFetcher<BaseApiResponse<DailyMarketingReport>>(
|
return await httpClientFetcher<DailyMarketingReportResponse>(endpoint);
|
||||||
endpoint
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async exportDailyMarketingToExcel(initialQueryString: string) {
|
async exportDailyMarketingToExcel(initialQueryString: string) {
|
||||||
@@ -42,16 +43,19 @@ export class MarketingReportApiService extends BaseApiService<
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const rows = dailyMarketingsReport.data.rows;
|
const rows = dailyMarketingsReport.data;
|
||||||
|
|
||||||
const formattedRows = [];
|
const formattedRows = [];
|
||||||
|
|
||||||
for (let i = 0; i < rows.length; i++) {
|
for (let i = 0; i < rows.length; i++) {
|
||||||
formattedRows.push({
|
formattedRows.push({
|
||||||
...rows[i],
|
...rows[i],
|
||||||
created_user: rows[i].created_user.name,
|
// created_user: rows[i].created_user.name,
|
||||||
created_at: formatDate(rows[i].created_at, 'YYYY-MM-DD'),
|
// created_at: formatDate(rows[i].created_at, 'YYYY-MM-DD'),
|
||||||
updated_at: formatDate(rows[i].updated_at, 'YYYY-MM-DD'),
|
// updated_at: formatDate(rows[i].updated_at, 'YYYY-MM-DD'),
|
||||||
|
so_date: formatDate(rows[i].so_date, 'YYYY-MM-DD'),
|
||||||
|
realization_date: formatDate(rows[i].realization_date, 'YYYY-MM-DD'),
|
||||||
|
sales: rows[i].sales.name,
|
||||||
warehouse: rows[i].warehouse.name,
|
warehouse: rows[i].warehouse.name,
|
||||||
customer: rows[i].customer.name,
|
customer: rows[i].customer.name,
|
||||||
product: rows[i].product.name,
|
product: rows[i].product.name,
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import { getUniqueFormikErrors } from '@/lib/formik-helper';
|
||||||
|
import { FormikProps } from 'formik';
|
||||||
|
import { useState } from 'react';
|
||||||
|
|
||||||
|
interface UseFormikErrorListOptions {
|
||||||
|
onBeforeSubmit?: (e: React.FormEvent<HTMLFormElement>) => boolean | void;
|
||||||
|
onAfterValidation?: () => void | Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useFormikErrorList = <T>(
|
||||||
|
formik: FormikProps<T>,
|
||||||
|
options?: UseFormikErrorListOptions
|
||||||
|
) => {
|
||||||
|
const [formErrorList, setFormErrorList] = useState<string[]>([]);
|
||||||
|
|
||||||
|
const handleValidateForm = async () => {
|
||||||
|
const errors = await formik.validateForm();
|
||||||
|
|
||||||
|
if (Object.keys(errors).length > 0) {
|
||||||
|
const errorMessages = getUniqueFormikErrors(errors);
|
||||||
|
setFormErrorList(errorMessages);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFormSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
// Call onBeforeSubmit callback
|
||||||
|
if (options?.onBeforeSubmit) {
|
||||||
|
const shouldContinue = options.onBeforeSubmit(e);
|
||||||
|
if (shouldContinue === false) {
|
||||||
|
return; // Cancel submit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate form
|
||||||
|
const isValid = await handleValidateForm();
|
||||||
|
|
||||||
|
// Call onAfterValidation callback if validation passed
|
||||||
|
if (options?.onAfterValidation) {
|
||||||
|
await options.onAfterValidation();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Submit form
|
||||||
|
formik.handleSubmit();
|
||||||
|
};
|
||||||
|
|
||||||
|
const close = () => {
|
||||||
|
setFormErrorList([]);
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
formErrorList,
|
||||||
|
setFormErrorList,
|
||||||
|
close,
|
||||||
|
handleValidateForm,
|
||||||
|
handleFormSubmit,
|
||||||
|
};
|
||||||
|
};
|
||||||
Vendored
+7
@@ -116,3 +116,10 @@ export type BaseGroupedApproval = {
|
|||||||
export type Approvals = BaseApiResponse<BaseApproval>;
|
export type Approvals = BaseApiResponse<BaseApproval>;
|
||||||
|
|
||||||
export type GroupedApprovals = BaseApiResponse<BaseGroupedApproval[]>;
|
export type GroupedApprovals = BaseApiResponse<BaseGroupedApproval[]>;
|
||||||
|
|
||||||
|
export type Document = {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
size: number;
|
||||||
|
url: string;
|
||||||
|
};
|
||||||
|
|||||||
Vendored
+1
-1
@@ -63,6 +63,7 @@ export type BaseClosing = {
|
|||||||
location_id: number;
|
location_id: number;
|
||||||
location_name: string;
|
location_name: string;
|
||||||
project_category: 'GROWING' | 'LAYING';
|
project_category: 'GROWING' | 'LAYING';
|
||||||
|
project_type?: 'GROWING' | 'LAYING'; // berubah dari BE?
|
||||||
period: number;
|
period: number;
|
||||||
closing_date?: string;
|
closing_date?: string;
|
||||||
shed_label: string;
|
shed_label: string;
|
||||||
@@ -185,7 +186,6 @@ export type ClosingSapronakCalculation = {
|
|||||||
doc: ClosingSapronakCalculationItem;
|
doc: ClosingSapronakCalculationItem;
|
||||||
ovk: ClosingSapronakCalculationItem;
|
ovk: ClosingSapronakCalculationItem;
|
||||||
pakan: ClosingSapronakCalculationItem;
|
pakan: ClosingSapronakCalculationItem;
|
||||||
pullet: ClosingSapronakCalculationItem;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// ====== OVERHEAD ======
|
// ====== OVERHEAD ======
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { BaseMetadata } from '@/types/api/api-general';
|
||||||
|
|
||||||
|
export type BaseConfiguration = {
|
||||||
|
id: number;
|
||||||
|
date: string;
|
||||||
|
percentage_threshold_bad: number;
|
||||||
|
percentage_threshold_enough: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type DailyChecklistConfiguration = BaseMetadata & BaseConfiguration;
|
||||||
|
|
||||||
|
export type CreateDailyChecklistConfigurationPayload = {
|
||||||
|
date: string;
|
||||||
|
percentage_threshold_bad: number;
|
||||||
|
percentage_threshold_enough: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type UpdateDailyChecklistConfigurationPayload = {
|
||||||
|
date: string;
|
||||||
|
percentage_threshold_bad: number;
|
||||||
|
percentage_threshold_enough: number;
|
||||||
|
};
|
||||||
+51
-1
@@ -1,7 +1,10 @@
|
|||||||
import { BaseMetadata } from '@/types/api/api-general';
|
import { BaseMetadata, Document } from '@/types/api/api-general';
|
||||||
import { BaseKandang } from '@/types/api/master-data/kandang';
|
import { BaseKandang } from '@/types/api/master-data/kandang';
|
||||||
import { Phase } from '@/types/api/daily-checklist/phase';
|
import { Phase } from '@/types/api/daily-checklist/phase';
|
||||||
import { PhaseActivity } from '@/types/api/daily-checklist/phase-activity';
|
import { PhaseActivity } from '@/types/api/daily-checklist/phase-activity';
|
||||||
|
import { BaseArea } from '@/types/api/master-data/area';
|
||||||
|
import { BaseLocation } from '@/types/api/master-data/location';
|
||||||
|
import { BaseEmployee } from '@/types/api/master-data/employee';
|
||||||
|
|
||||||
export type BaseDailyChecklist = {
|
export type BaseDailyChecklist = {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -46,6 +49,7 @@ export type DetailDailyChecklist = BaseDailyChecklist & {
|
|||||||
id: number;
|
id: number;
|
||||||
name: string;
|
name: string;
|
||||||
}[];
|
}[];
|
||||||
|
document_urls: Document[];
|
||||||
};
|
};
|
||||||
|
|
||||||
export type CreateDailyChecklistPayload = {
|
export type CreateDailyChecklistPayload = {
|
||||||
@@ -54,3 +58,49 @@ export type CreateDailyChecklistPayload = {
|
|||||||
category: string;
|
category: string;
|
||||||
status: string;
|
status: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type PerformanceOverviewItem = {
|
||||||
|
employee_id: number;
|
||||||
|
employee_name: string;
|
||||||
|
total_activity: number;
|
||||||
|
activity_done: number;
|
||||||
|
activity_left: number;
|
||||||
|
kandang: Pick<BaseKandang, 'id' | 'name'>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type TrackingAbkItem = {
|
||||||
|
employee_id: number;
|
||||||
|
employee_name: string;
|
||||||
|
kandang_id: number;
|
||||||
|
kandang_name: string;
|
||||||
|
total_activity: number;
|
||||||
|
activity_done: number;
|
||||||
|
activity_left: number;
|
||||||
|
completion_rate: number;
|
||||||
|
last_activity: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type DailyChecklistSummary = {
|
||||||
|
performance_overview: PerformanceOverviewItem[];
|
||||||
|
tracking_abk: TrackingAbkItem[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type DailyChecklistReport = {
|
||||||
|
area: Pick<BaseArea, 'id' | 'name'>;
|
||||||
|
farm: Pick<BaseLocation, 'id' | 'name'>;
|
||||||
|
kandang: Pick<BaseKandang, 'id' | 'name'>;
|
||||||
|
abk: Pick<BaseEmployee, 'id' | 'name'>;
|
||||||
|
phase: string;
|
||||||
|
daily_activities: Record<string, number>;
|
||||||
|
summary: {
|
||||||
|
total_checklist: number;
|
||||||
|
jumlah_hari_efektif: number;
|
||||||
|
abk_percentage: number;
|
||||||
|
kandang_percentage: number;
|
||||||
|
kategori: {
|
||||||
|
kurang: number;
|
||||||
|
cukup: number;
|
||||||
|
baik: number;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|||||||
@@ -1,52 +0,0 @@
|
|||||||
export interface DashboardProduction {
|
|
||||||
statistics_data: DashboardProductionStatisticsData[];
|
|
||||||
production_charts: DashboardProductionProductionCharts[];
|
|
||||||
standard_productions: DashboardProductionStandardProductions[];
|
|
||||||
egg_weights: DashboardProductionEggWeights[];
|
|
||||||
fcr_data: DashboardProductionFcrData[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DashboardProductionFcrData {
|
|
||||||
flock: DashboardProductionFcrDataFlock;
|
|
||||||
fcr: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DashboardProductionEggWeights {
|
|
||||||
flock: DashboardProductionFcrDataFlock;
|
|
||||||
weight: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DashboardProductionStandardProductions {
|
|
||||||
week: number;
|
|
||||||
standards: DashboardProductionStandardProductionsStandards[];
|
|
||||||
flocks: DashboardProductionProductionChartsFlocks[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DashboardProductionProductionCharts {
|
|
||||||
date: string;
|
|
||||||
flocks: DashboardProductionProductionChartsFlocks[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DashboardProductionStatisticsData {
|
|
||||||
title: string;
|
|
||||||
value: number;
|
|
||||||
change: number;
|
|
||||||
period: string;
|
|
||||||
changeType: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DashboardProductionFcrDataFlock {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DashboardProductionStandardProductionsStandards {
|
|
||||||
name: string;
|
|
||||||
value: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DashboardProductionProductionChartsFlocks {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
data: number;
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user