mirror of
https://gitlab.com/mbugroup/lti-web-client.git
synced 2026-05-20 13:32:00 +00:00
Compare commits
289 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fa32995802 | |||
| c832c4adeb | |||
| eda3f0f1be | |||
| d0d201bf3a | |||
| c7b04c5bc6 | |||
| c37950a230 | |||
| f88af89562 | |||
| 7da95b80b0 | |||
| 883d68032a | |||
| c74ed18a16 | |||
| e45a9ba5e4 | |||
| de7076e513 | |||
| 6706f361d8 | |||
| 15e6372c30 | |||
| 6dd3593f70 | |||
| 5d376f8783 | |||
| 304d14a6fe | |||
| 4bd6fe8c35 | |||
| 0b0ecd3bc4 | |||
| 58369b8ffa | |||
| cbb4f7421e | |||
| 459605f133 | |||
| 943c0e05b9 | |||
| 9143248e1d | |||
| 4b9d0d2064 | |||
| c8f596ad2a | |||
| a65d00edc8 | |||
| 1e9d02b4b7 | |||
| 135fc2d5d3 | |||
| 189c152745 | |||
| f0f6ec53cb | |||
| a0556ea1f4 | |||
| 81ce36e326 | |||
| 48c31373bf | |||
| d7ce8c667a | |||
| 6290199074 | |||
| 4f3dfb4221 | |||
| a13a51a16f | |||
| 896a0c6de2 | |||
| 9c5dc0dbb5 | |||
| 81003eac63 | |||
| e322e0d078 | |||
| 17e6eef0c5 | |||
| 6114d706ad | |||
| d14fa2ed2b | |||
| 537fc617ff | |||
| 7a6a35568f | |||
| d2c485fdf0 | |||
| 0c49978033 | |||
| 00de4782e7 | |||
| c546bd6b3c | |||
| 258324f092 | |||
| 12a69b7c6c | |||
| b148a09e84 | |||
| adc995dbe7 | |||
| 9cbc703a63 | |||
| 41e6848d75 | |||
| fa21fe8da4 | |||
| ca5b236565 | |||
| 714072aea1 | |||
| 8337fa5f55 | |||
| a9f0696b38 | |||
| 54bff12e1a | |||
| aa17143532 | |||
| 4381e42aaf | |||
| 24ed2cccbe | |||
| a9b0c084f8 | |||
| 16823fa84a | |||
| c30fcd81b2 | |||
| 7f5ae94706 | |||
| 6060ec0f7e | |||
| ef249fee12 | |||
| 71df86c8df | |||
| d61c0ab844 | |||
| b653cc1dab | |||
| 51bce1a2c7 | |||
| e76d881d8a | |||
| 392e211181 | |||
| cebe738beb | |||
| 6e5875a7b7 | |||
| b2044ac7bd | |||
| 8a467c2d65 | |||
| db8cb56984 | |||
| d1d152ef5a | |||
| 82950b0ec0 | |||
| 3110b96305 | |||
| 7e44226a6d | |||
| 3f76cb58fe | |||
| 3cf8f4c89b | |||
| 90ae7c469a | |||
| ae967c5ddb | |||
| e801ba08ad | |||
| e6f5b2493b | |||
| 5f677f5076 | |||
| 2de32dc944 | |||
| ab534e203a | |||
| eaf41805d7 | |||
| 631ebb9346 | |||
| 7e53743b07 | |||
| 70e1aca6c7 | |||
| d0d323954b | |||
| d1c24bc486 | |||
| f998d32b0a | |||
| 3226b22dfb | |||
| 9a51b2876f | |||
| ab9fbc9032 | |||
| d2f24723fc | |||
| 5e710a792f | |||
| 3c8bdfbdac | |||
| 204369e0fe | |||
| 1e2ea79a6a | |||
| 22f1a32e1b | |||
| c24c0817ae | |||
| e53325cdc5 | |||
| 6687f4af98 | |||
| 575a317eed | |||
| bdb3ab1a50 | |||
| f486a659d0 | |||
| 58b4204aab | |||
| c249585bc2 | |||
| 9c114628c7 | |||
| b35d513e44 | |||
| a904c35b7f | |||
| 2e595b5e86 | |||
| 46fa3e57cd | |||
| 79b6d6917d | |||
| 9f24d22a2c | |||
| 06f1d3f6a4 | |||
| e29613a37e | |||
| 6e6675d0a7 | |||
| 32d4c0268f | |||
| 2ab26153fd | |||
| a29bbc9a42 | |||
| e7e0e308c7 | |||
| 1ade8f8a38 | |||
| 791e8e787c | |||
| a2c43a7f1e | |||
| 12202c2021 | |||
| 4127075b13 | |||
| d9fa685ae6 | |||
| 2f4daea253 | |||
| bac72b8eb3 | |||
| 5af9c3ee27 | |||
| 1a76913f3f | |||
| 8b403a4208 | |||
| 0bab704163 | |||
| d550dcbf48 | |||
| 7fdbfe6dfb | |||
| 4e6d2088e1 | |||
| 67b180bf7c | |||
| 7853899486 | |||
| 9a04724095 | |||
| 831995e8e4 | |||
| c8cdb3e772 | |||
| e5b3af3239 | |||
| 0740f2d094 | |||
| 25a97e34c7 | |||
| 1ee1cf9ea9 | |||
| e4a1138d8d | |||
| 41bb05413c | |||
| c746bd94b2 | |||
| acea3a3063 | |||
| b269728ecd | |||
| e7a861d8a1 | |||
| 1a5a76c0f1 | |||
| 838d7277c3 | |||
| 1672705464 | |||
| 9ef4484fb3 | |||
| 645668e1f9 | |||
| fb29cea8d2 | |||
| 1ecdff855e | |||
| 7c6e079f56 | |||
| 41f8067727 | |||
| f733b0750a | |||
| 83d31b7047 | |||
| 966e0886e1 | |||
| a67d353bcb | |||
| ac2f246988 | |||
| e0ce571000 | |||
| 1bcfd9bbb4 | |||
| c561c47eae | |||
| c3338d3e05 | |||
| ba9ae07455 | |||
| c64ff527dd | |||
| f27e34128e | |||
| c8db992b17 | |||
| d76f897840 | |||
| 5e0cc3699f | |||
| 895b7afa25 | |||
| a088189ed1 | |||
| 406cfad31a | |||
| 6c9c0e1839 | |||
| eb02a8b6f7 | |||
| 73f379832c | |||
| 4233c19dc9 | |||
| 403765a2b5 | |||
| d30d7328cf | |||
| 376fa29f7e | |||
| 16d72ebf6f | |||
| 52ad696178 | |||
| 2b3aa9c3ee | |||
| 6fe85fac13 | |||
| 9964e1797a | |||
| e4f554bcd4 | |||
| c25b49c179 | |||
| a573551110 | |||
| 881e2bfc4a | |||
| 474c2a1f7d | |||
| c4de085e11 | |||
| 0676411dd5 | |||
| f05d367a5d | |||
| edb5f30d6c | |||
| 7abe9b7dc6 | |||
| caf68d438f | |||
| fa60f884c1 | |||
| c77968940e | |||
| cfb9b53b54 | |||
| caac9c20e6 | |||
| 8bf7603f66 | |||
| 8c662a5152 | |||
| da92874a40 | |||
| 5113bf4d3f | |||
| 1bdec0c9ae | |||
| 57dbcf3624 | |||
| 501a68267e | |||
| a2a57f758c | |||
| 157dfc75ed | |||
| f5ce898bd2 | |||
| c6a0c542aa | |||
| b0e11095f4 | |||
| 79acdb4b7b | |||
| 19db9a4eac | |||
| 1e0b342bbc | |||
| 23d5a41d56 | |||
| b7a30cc73a | |||
| 93beb86f91 | |||
| 0577f6ce1d | |||
| 76dd2e4c54 | |||
| 156de6112b | |||
| eb0f04310e | |||
| 27d2792a9c | |||
| ec387637ed | |||
| 64e6724664 | |||
| f319a9b5d1 | |||
| e2b35e765c | |||
| 8bfce061e6 | |||
| 64a32fd214 | |||
| 2ee88a2742 | |||
| aa21088e99 | |||
| 06dc869b84 | |||
| df73ee1fdf | |||
| cf78687315 | |||
| 66e6fa84c8 | |||
| dcd5d2692f | |||
| 3c4333021f | |||
| 56a9fc2349 | |||
| 24144f01d4 | |||
| 6f0467918b | |||
| 53ee4cdc1b | |||
| b1a3796eca | |||
| 89318407ea | |||
| 6dcb97bcac | |||
| 1869fa8dc5 | |||
| 4b4b74d07c | |||
| ff9e35eb52 | |||
| 19bca9ec73 | |||
| 6facfd3d3c | |||
| b2f0bd6698 | |||
| e7085ab4ff | |||
| 44e07ddc50 | |||
| a4ff4f7b2a | |||
| 754e3d526b | |||
| 478f52c94b | |||
| 757893c757 | |||
| a1dc13ceb4 | |||
| 157235433e | |||
| 57831646d9 | |||
| 095190d757 | |||
| 27f58051ad | |||
| a9cdea7318 | |||
| 7dbf880228 | |||
| aacdbf0742 | |||
| c17ffc6aff | |||
| 1ea9ee3069 | |||
| 558a1788dc | |||
| e2036ab3dc | |||
| ddbf8b0896 | |||
| 3f97ec45f8 | |||
| 7ceb25ea71 |
@@ -40,8 +40,5 @@ yarn-error.log*
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
|
||||
# prettier
|
||||
.prettierrc
|
||||
|
||||
# idea
|
||||
.idea
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
npm run lint
|
||||
npm run build
|
||||
@@ -0,0 +1,11 @@
|
||||
#!/bin/bash
|
||||
|
||||
echo "VERCEL_GIT_COMMIT_REF: $VERCEL_GIT_COMMIT_REF"
|
||||
|
||||
if [[ "$VERCEL_GIT_COMMIT_REF" == "master" || "$VERCEL_GIT_COMMIT_REF" == "development" ]]; then
|
||||
echo "✅ - Build can proceed"
|
||||
exit 1
|
||||
else
|
||||
echo "🛑 - Build cancelled"
|
||||
exit 0
|
||||
fi
|
||||
Generated
+505
-537
File diff suppressed because it is too large
Load Diff
+7
-1
@@ -6,7 +6,8 @@
|
||||
"dev": "eslint && next dev --turbopack",
|
||||
"build": "next build --turbopack",
|
||||
"start": "next start",
|
||||
"lint": "eslint"
|
||||
"lint": "eslint",
|
||||
"prepare": "husky"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/match-sorter-utils": "^8.19.4",
|
||||
@@ -14,11 +15,13 @@
|
||||
"axios": "^1.12.2",
|
||||
"clsx": "^2.1.1",
|
||||
"formik": "^2.4.6",
|
||||
"inputmask": "^5.0.9",
|
||||
"moment": "^2.30.1",
|
||||
"next": "15.5.3",
|
||||
"react": "19.1.0",
|
||||
"react-dom": "19.1.0",
|
||||
"react-hot-toast": "^2.6.0",
|
||||
"react-number-format": "^5.4.4",
|
||||
"react-select": "^5.10.2",
|
||||
"swr": "^2.3.6",
|
||||
"tailwind-merge": "^3.3.1",
|
||||
@@ -30,12 +33,15 @@
|
||||
"@eslint/eslintrc": "^3",
|
||||
"@iconify/react": "^6.0.2",
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@types/inputmask": "^5.0.7",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"daisyui": "^5.1.12",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "15.5.3",
|
||||
"husky": "^9.1.7",
|
||||
"prettier": "3.6.2",
|
||||
"tailwindcss": "^4",
|
||||
"typescript": "^5"
|
||||
}
|
||||
|
||||
@@ -1,5 +1,43 @@
|
||||
@import 'tailwindcss';
|
||||
@plugin "daisyui";
|
||||
@import '../styles/daisyui.css';
|
||||
|
||||
@plugin "daisyui/theme" {
|
||||
name: "lti";
|
||||
default: false;
|
||||
prefersdark: false;
|
||||
color-scheme: "light";
|
||||
--color-base-100: oklch(98% 0.001 106.423);
|
||||
--color-base-200: oklch(97% 0.001 106.424);
|
||||
--color-base-300: oklch(92% 0.003 48.717);
|
||||
--color-base-content: oklch(22.389% 0.031 278.072);
|
||||
--color-primary: oklch(60% 0.126 221.723);
|
||||
--color-primary-content: oklch(100% 0 0);
|
||||
--color-secondary: oklch(52% 0.105 223.128);
|
||||
--color-secondary-content: oklch(100% 0 0);
|
||||
--color-accent: oklch(45% 0.085 224.283);
|
||||
--color-accent-content: oklch(100% 0 0);
|
||||
--color-neutral: oklch(39% 0.07 227.392);
|
||||
--color-neutral-content: oklch(100% 0 0);
|
||||
--color-info: oklch(58% 0.158 241.966);
|
||||
--color-info-content: oklch(100% 0 0);
|
||||
--color-success: oklch(62% 0.194 149.214);
|
||||
--color-success-content: oklch(100% 0 0);
|
||||
--color-warning: oklch(85% 0.199 91.936);
|
||||
--color-warning-content: oklch(0% 0 0);
|
||||
--color-error: oklch(57% 0.245 27.325);
|
||||
--color-error-content: oklch(100% 0 0);
|
||||
--radius-selector: 0rem;
|
||||
--radius-field: 0.25rem;
|
||||
--radius-box: 0.25rem;
|
||||
--size-selector: 0.21875rem;
|
||||
--size-field: 0.1875rem;
|
||||
--border: 1px;
|
||||
--depth: 0;
|
||||
--noise: 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
:root {
|
||||
--color-primary: #1f74bf;
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import SuspenseHelper from "@/components/helper/SuspenseHelper"
|
||||
|
||||
const Layout = ({
|
||||
children
|
||||
}: Readonly<{
|
||||
children: React.ReactNode
|
||||
}>) => {
|
||||
return <SuspenseHelper>{children}</SuspenseHelper>
|
||||
}
|
||||
|
||||
export default Layout;
|
||||
@@ -0,0 +1,11 @@
|
||||
import MovementForm from '@/components/pages/inventory/movement/form/MovementForm';
|
||||
|
||||
const AddMovement = () => {
|
||||
return (
|
||||
<div className='w-full p-4 flex flex-row justify-center'>
|
||||
<MovementForm />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AddMovement;
|
||||
@@ -0,0 +1,48 @@
|
||||
'use client';
|
||||
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import useSWR from 'swr';
|
||||
|
||||
import MovementForm from '@/components/pages/inventory/movement/form/MovementForm';
|
||||
import { MovementApi } from '@/services/api/inventory';
|
||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||
|
||||
const MovementEdit = () => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const movementId = searchParams.get('movementId');
|
||||
|
||||
const { data: movement, isLoading: isLoadingMovement } = useSWR(
|
||||
movementId,
|
||||
(id: number) => MovementApi.getSingle(id)
|
||||
);
|
||||
|
||||
if (!movementId) {
|
||||
router.back();
|
||||
|
||||
return (
|
||||
<div className='w-full flex flex-row justify-center items-center p-4'>
|
||||
<span className='loading loading-spinner loading-xl' />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!isLoadingMovement && (!movement || isResponseError(movement))) {
|
||||
router.replace('/404');
|
||||
return;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='w-full p-4 flex flex-row justify-center'>
|
||||
{isLoadingMovement && (
|
||||
<span className='loading loading-spinner loading-xl' />
|
||||
)}
|
||||
{!isLoadingMovement && isResponseSuccess(movement) && (
|
||||
<MovementForm type='edit' initialValues={movement.data} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default MovementEdit;
|
||||
@@ -0,0 +1,11 @@
|
||||
import SuspenseHelper from '@/components/helper/SuspenseHelper';
|
||||
|
||||
const Layout = ({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) => {
|
||||
return <SuspenseHelper>{children}</SuspenseHelper>;
|
||||
};
|
||||
|
||||
export default Layout;
|
||||
@@ -0,0 +1,48 @@
|
||||
'use client';
|
||||
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import useSWR from 'swr';
|
||||
|
||||
import MovementForm from '@/components/pages/inventory/movement/form/MovementForm';
|
||||
import { MovementApi } from '@/services/api/inventory';
|
||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||
|
||||
const MovementDetail = () => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const movementId = searchParams.get('movementId');
|
||||
|
||||
const { data: movement, isLoading: isLoadingMovement } = useSWR(
|
||||
movementId,
|
||||
(id: number) => MovementApi.getSingle(id)
|
||||
);
|
||||
|
||||
if (!movementId) {
|
||||
router.back();
|
||||
|
||||
return (
|
||||
<div className='w-full flex flex-row justify-center items-center p-4'>
|
||||
<span className='loading loading-spinner loading-xl' />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!isLoadingMovement && (!movement || isResponseError(movement))) {
|
||||
router.replace('/404');
|
||||
return;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='w-full p-4 flex flex-row justify-center'>
|
||||
{isLoadingMovement && (
|
||||
<span className='loading loading-spinner loading-xl' />
|
||||
)}
|
||||
{!isLoadingMovement && isResponseSuccess(movement) && (
|
||||
<MovementForm type='detail' initialValues={movement.data} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default MovementDetail;
|
||||
@@ -0,0 +1,11 @@
|
||||
import MovementTable from '@/components/pages/inventory/movement/MovementTable';
|
||||
|
||||
const Movement = () => {
|
||||
return (
|
||||
<section className='w-full p-4'>
|
||||
<MovementTable />
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
export default Movement;
|
||||
+1
-1
@@ -28,7 +28,7 @@ export default function RootLayout({
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html lang='en'>
|
||||
<html lang='en' data-theme='lti'>
|
||||
<body className={`${inter.variable} antialiased font-inter`}>
|
||||
<RequireAuth>
|
||||
<MainDrawer>{children}</MainDrawer>
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import SuspenseHelper from '@/components/helper/SuspenseHelper';
|
||||
|
||||
const Layout = ({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) => {
|
||||
return <SuspenseHelper>{children}</SuspenseHelper>;
|
||||
};
|
||||
|
||||
export default Layout;
|
||||
@@ -0,0 +1,11 @@
|
||||
import FlockForm from "@/components/pages/master-data/flock/form/FlockForm";
|
||||
|
||||
const AddFlock = () => {
|
||||
return (
|
||||
<section className="w-full p-4 flex flex-row justify-center">
|
||||
<FlockForm />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export default AddFlock;
|
||||
@@ -0,0 +1,49 @@
|
||||
'use client'
|
||||
|
||||
import FlockForm from "@/components/pages/master-data/flock/form/FlockForm";
|
||||
import { isResponseError, isResponseSuccess } from "@/lib/api-helper";
|
||||
import { FlockApi } from "@/services/api/master-data";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import useSWR from "swr";
|
||||
|
||||
const FlockEdit = () => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
// Get Query Params
|
||||
const flockId = searchParams.get('flockId');
|
||||
|
||||
// Fetch Data
|
||||
const { data: flock, isLoading: isLoadingFlock } = useSWR(
|
||||
flockId,
|
||||
(id: number) => FlockApi.getSingle(id)
|
||||
);
|
||||
|
||||
if (!flockId) {
|
||||
router.back();
|
||||
|
||||
return (
|
||||
<div className='w-full flex flex-row justify-center items-center p-4'>
|
||||
<span className='loading loading-spinner loading-xl' />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!isLoadingFlock && (!flock || isResponseError(flock))) {
|
||||
router.replace('/404');
|
||||
return;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='w-full p-4 flex flex-row justify-center'>
|
||||
{isLoadingFlock && (
|
||||
<span className='loading loading-spinner loading-xl' />
|
||||
)}
|
||||
{!isLoadingFlock && isResponseSuccess(flock) && (
|
||||
<FlockForm formType='edit' initialValues={flock.data} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default FlockEdit;
|
||||
@@ -0,0 +1,11 @@
|
||||
import SuspenseHelper from "@/components/helper/SuspenseHelper"
|
||||
|
||||
const Layout = ({
|
||||
children
|
||||
}: Readonly<{
|
||||
children: React.ReactNode
|
||||
}>) => {
|
||||
return <SuspenseHelper>{children}</SuspenseHelper>
|
||||
}
|
||||
|
||||
export default Layout;
|
||||
@@ -0,0 +1,46 @@
|
||||
'use client'
|
||||
|
||||
import FlockForm from "@/components/pages/master-data/flock/form/FlockForm";
|
||||
import { isResponseError, isResponseSuccess } from "@/lib/api-helper";
|
||||
import { FlockApi } from "@/services/api/master-data";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import useSWR from "swr";
|
||||
|
||||
const FlockDetail = () => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
// Get Query Params
|
||||
const flockId = searchParams.get('flockId');
|
||||
|
||||
// Fetch Data
|
||||
const { data: flock, isLoading: isLoadingFlock } = useSWR(flockId, (id: number) => FlockApi.getSingle(id));
|
||||
|
||||
if(!flockId){
|
||||
router.back();
|
||||
|
||||
return (
|
||||
<div className="w-full flex flex-row justify-center items-center p-4">
|
||||
<span className="loading loading-spinner loading-xl" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if(!isLoadingFlock && (!flock || isResponseError(flock))){
|
||||
router.replace('/404');
|
||||
return;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-full p-4 flex flex-row justify-center">
|
||||
{isLoadingFlock && (
|
||||
<span className="loading loading-spinner loading-xl" />
|
||||
)}
|
||||
{!isLoadingFlock && isResponseSuccess(flock) && (
|
||||
<FlockForm formType="detail" initialValues={flock.data} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default FlockDetail;
|
||||
@@ -0,0 +1,11 @@
|
||||
import FlockTable from "@/components/pages/master-data/flock/FlocksTable";
|
||||
|
||||
const Flock = () => {
|
||||
return (
|
||||
<section className="w-full p-4">
|
||||
<FlockTable/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export default Flock;
|
||||
@@ -0,0 +1,11 @@
|
||||
import SuspenseHelper from '@/components/helper/SuspenseHelper';
|
||||
|
||||
const Layout = ({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) => {
|
||||
return <SuspenseHelper>{children}</SuspenseHelper>;
|
||||
};
|
||||
|
||||
export default Layout;
|
||||
@@ -0,0 +1,11 @@
|
||||
import SuspenseHelper from "@/components/helper/SuspenseHelper"
|
||||
|
||||
const Layout = ({
|
||||
children
|
||||
}: Readonly<{
|
||||
children: React.ReactNode
|
||||
}>) => {
|
||||
return <SuspenseHelper>{children}</SuspenseHelper>
|
||||
}
|
||||
|
||||
export default Layout;
|
||||
@@ -0,0 +1,270 @@
|
||||
'use client';
|
||||
|
||||
import Button from '@/components/Button';
|
||||
import SelectInput, { OptionType } from '@/components/input/SelectInput';
|
||||
import Modal, { useModal } from '@/components/Modal';
|
||||
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||
import ChickinForm from '@/components/pages/production/chickin/form/ChickinForm';
|
||||
import Table from '@/components/Table';
|
||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||
import { cn } from '@/lib/helper';
|
||||
import { ProjectFlockApi } from '@/services/api/production';
|
||||
import { useTableFilter } from '@/services/hooks/useTableFilter';
|
||||
import { BaseApiResponse } from '@/types/api/api-general';
|
||||
import { Kandang } from '@/types/api/master-data/kandang';
|
||||
import { ProjectFlockKandang } from '@/types/api/production/project-flock-kandang';
|
||||
import { Icon } from '@iconify/react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
|
||||
import useSWR from 'swr';
|
||||
|
||||
const AddChickin = () => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const projectFlockId = searchParams.get('projectFlockId');
|
||||
|
||||
// Tables Props
|
||||
const { state: tableFilterState } = useTableFilter({
|
||||
initial: { search: '' },
|
||||
paramMap: { page: 'page', pageSize: 'limit' },
|
||||
});
|
||||
|
||||
// States
|
||||
const [selectedKandang, setSelectedKandang] = useState<Kandang | undefined>(
|
||||
undefined
|
||||
);
|
||||
const [projectFlockKandang, setProjectFlockKandang] =
|
||||
useState<BaseApiResponse<ProjectFlockKandang>>();
|
||||
const [isLoadingProjectFlockKandang, setIsLoadingProjectFlockKandang] =
|
||||
useState(false);
|
||||
const [searchProjectFlock, setSearchProjectFlock] = useState('');
|
||||
|
||||
// Fetch Data
|
||||
const { data: projectFlock, isLoading: isLoadingProjectFlock } = useSWR(
|
||||
projectFlockId,
|
||||
(id: number) => ProjectFlockApi.getSingle(id)
|
||||
);
|
||||
const { data: listProjectFlock, isLoading: isLoadingListProjectFlock } =
|
||||
useSWR(
|
||||
`${ProjectFlockApi.basePath}?${new URLSearchParams({
|
||||
search: searchProjectFlock,
|
||||
}).toString()}`,
|
||||
ProjectFlockApi.getAllFetcher
|
||||
);
|
||||
|
||||
const getProjectFlockKandangUrl = `/kandangs/lookup`;
|
||||
// Mapping Options
|
||||
const options = isResponseSuccess(listProjectFlock)
|
||||
? listProjectFlock?.data.map((projectFlock) => {
|
||||
return {
|
||||
value: projectFlock.id,
|
||||
label: `${projectFlock?.flock?.name} - ${projectFlock?.category} - Periode ${projectFlock.period}`,
|
||||
};
|
||||
})
|
||||
: [];
|
||||
|
||||
const chickinModal = useModal();
|
||||
const alertModal = useModal();
|
||||
|
||||
if (!projectFlockId) {
|
||||
router.back();
|
||||
|
||||
return (
|
||||
<div className='w-full flex flex-row justify-center items-center p-4'>
|
||||
<span className='loading loading-spinner loading-xl' />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
!isLoadingProjectFlock &&
|
||||
(!projectFlock || isResponseError(projectFlock))
|
||||
) {
|
||||
router.replace('/404');
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle Function
|
||||
const handleChickinClick = async (kandang: Kandang) => {
|
||||
setIsLoadingProjectFlockKandang(true);
|
||||
setSelectedKandang(kandang);
|
||||
const ProjectFlockKandangRes = await ProjectFlockApi.customRequest<
|
||||
BaseApiResponse<ProjectFlockKandang>,
|
||||
'GET'
|
||||
>(getProjectFlockKandangUrl, {
|
||||
method: 'GET',
|
||||
params: {
|
||||
project_flock_id: projectFlockId ?? 0,
|
||||
kandang_id: kandang.id,
|
||||
},
|
||||
});
|
||||
if (isResponseSuccess(ProjectFlockKandangRes)) {
|
||||
setProjectFlockKandang(ProjectFlockKandangRes);
|
||||
setIsLoadingProjectFlockKandang(false);
|
||||
if (
|
||||
ProjectFlockKandangRes.data.available_quantity &&
|
||||
ProjectFlockKandangRes.data.available_quantity > 0
|
||||
) {
|
||||
chickinModal.openModal();
|
||||
} else {
|
||||
alertModal.openModal();
|
||||
}
|
||||
}
|
||||
};
|
||||
const handleAfterSubmit = () => {
|
||||
chickinModal.closeModal();
|
||||
router.push('/production/chickin');
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{isResponseSuccess(projectFlock) && (
|
||||
<>
|
||||
<section className='w-full p-4'>
|
||||
<header className='flex flex-col gap-4'>
|
||||
<Button
|
||||
href='/production/project-flock'
|
||||
variant='link'
|
||||
className='w-fit p-0 text-primary'
|
||||
>
|
||||
<Icon icon='uil:arrow-left' width={24} height={24} />
|
||||
Kembali
|
||||
</Button>
|
||||
|
||||
<div className='flex flex-col gap-4 w-full my-4'>
|
||||
<div className='max-w-full sm:max-w-1/2 md:max-w-3/5 lg:max-w-2/5'>
|
||||
<SelectInput
|
||||
required
|
||||
isSearchable
|
||||
label='Project Flock'
|
||||
options={options}
|
||||
isLoading={isLoadingListProjectFlock}
|
||||
value={{
|
||||
label: `${projectFlock.data?.flock?.name} - ${projectFlock.data?.category} - Periode ${projectFlock.data?.period}`,
|
||||
value: projectFlock.data?.id,
|
||||
}}
|
||||
onChange={(val) =>
|
||||
router.push(
|
||||
`/production/chickin/add?projectFlockId=${
|
||||
(val as OptionType | null)?.value
|
||||
}`
|
||||
)
|
||||
}
|
||||
onInputChange={(val) => {
|
||||
setSearchProjectFlock(val);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<Table<Kandang>
|
||||
data={projectFlock.data?.kandangs}
|
||||
columns={[
|
||||
{
|
||||
header: '#',
|
||||
cell: (props) =>
|
||||
tableFilterState.pageSize * (tableFilterState.page - 1) +
|
||||
props.row.index +
|
||||
1,
|
||||
},
|
||||
{
|
||||
accessorKey: 'name',
|
||||
header: 'Nama Kandang',
|
||||
},
|
||||
{
|
||||
header: 'Aksi',
|
||||
cell: (props) => {
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
color='success'
|
||||
variant='outline'
|
||||
onClick={() => {
|
||||
handleChickinClick(props.row.original);
|
||||
}}
|
||||
disabled={isLoadingProjectFlockKandang}
|
||||
>
|
||||
<Icon
|
||||
icon='mdi:home-import-outline'
|
||||
width={24}
|
||||
height={24}
|
||||
/>
|
||||
Chickin
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
},
|
||||
},
|
||||
]}
|
||||
page={undefined}
|
||||
className={{
|
||||
containerClassName: cn({
|
||||
'mb-20':
|
||||
isResponseSuccess(projectFlock) &&
|
||||
projectFlock.data?.kandangs?.length === 0,
|
||||
}),
|
||||
tableWrapperClassName: 'overflow-x-auto min-h-full!',
|
||||
tableClassName: 'font-inter w-full table-auto min-h-full!',
|
||||
headerRowClassName: 'border-b border-b-gray-200',
|
||||
headerColumnClassName:
|
||||
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
|
||||
bodyRowClassName: 'border-b border-b-gray-200',
|
||||
bodyColumnClassName:
|
||||
'px-6 py-3 last:flex last:flex-row last:justify-end',
|
||||
paginationClassName: 'hidden',
|
||||
}}
|
||||
/>
|
||||
</section>
|
||||
<Modal ref={chickinModal.ref}>
|
||||
<div className='flex flex-row justify-between items-center'>
|
||||
<h1 className='text-xl font-semibold text-center mb-6'>
|
||||
Chickin Kandang - {selectedKandang?.name}
|
||||
</h1>
|
||||
<Button
|
||||
color='error'
|
||||
variant='link'
|
||||
onClick={chickinModal.closeModal}
|
||||
>
|
||||
<Icon
|
||||
className='text-black'
|
||||
icon='uil:times'
|
||||
width={24}
|
||||
height={24}
|
||||
/>
|
||||
</Button>
|
||||
</div>
|
||||
{isResponseSuccess(projectFlockKandang) &&
|
||||
!isLoadingProjectFlockKandang && (
|
||||
<ChickinForm
|
||||
initialValues={{
|
||||
project_flock_kandang: projectFlockKandang.data,
|
||||
created_user: projectFlock.data?.created_user,
|
||||
created_at: projectFlock.data?.created_at,
|
||||
updated_at: projectFlock.data?.updated_at,
|
||||
approval: projectFlock.data?.approval,
|
||||
}}
|
||||
afterSubmit={handleAfterSubmit}
|
||||
/>
|
||||
)}
|
||||
</Modal>
|
||||
<ConfirmationModal
|
||||
ref={alertModal.ref}
|
||||
type='info'
|
||||
text={`Persediaan Day Old Chick pada kandang (${selectedKandang?.name}) belum ada, mohon isi terlebih dahulu di bagian Persediaan!`}
|
||||
secondaryButton={undefined}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: 'info',
|
||||
onClick: () => {
|
||||
alertModal.closeModal();
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default AddChickin;
|
||||
@@ -0,0 +1,11 @@
|
||||
import SuspenseHelper from "@/components/helper/SuspenseHelper"
|
||||
|
||||
const Layout = ({
|
||||
children
|
||||
}: Readonly<{
|
||||
children: React.ReactNode
|
||||
}>) => {
|
||||
return <SuspenseHelper>{children}</SuspenseHelper>
|
||||
}
|
||||
|
||||
export default Layout;
|
||||
@@ -0,0 +1,351 @@
|
||||
'use client';
|
||||
|
||||
import Button from '@/components/Button';
|
||||
import Card from '@/components/Card';
|
||||
import Modal, { useModal } from '@/components/Modal';
|
||||
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||
import ChickinForm from '@/components/pages/production/chickin/form/ChickinForm';
|
||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||
import { ChickinApi } from '@/services/api/production';
|
||||
import { BaseApiResponse } from '@/types/api/api-general';
|
||||
import {
|
||||
Chickin,
|
||||
ChickinApprovalPayload,
|
||||
} from '@/types/api/production/chickin';
|
||||
import { Icon } from '@iconify/react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import useSWR from 'swr';
|
||||
|
||||
/**
|
||||
* TODO: Refactor code - pindahin detail ke reuseable component
|
||||
* setelah implement approval and reject
|
||||
*/
|
||||
|
||||
const DetailChickin = () => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const chickinId = searchParams.get('chickinId');
|
||||
const [isApproveLoading, setIsApproveLoading] = useState(false);
|
||||
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||
|
||||
const confirmModal = useModal();
|
||||
const deleteModal = useModal();
|
||||
const chickinModal = useModal();
|
||||
const {
|
||||
data: chickin,
|
||||
isLoading,
|
||||
mutate: refreshChickin,
|
||||
} = useSWR(chickinId, (id: number) => ChickinApi.getSingle(id));
|
||||
|
||||
const [isApprovedDisabled, setIsApprovedDisabled] = useState(
|
||||
// chickin.data?.approval.step_number == 1 ? false : true
|
||||
true
|
||||
);
|
||||
const [isRejectedDisabled, setIsRejectedDisabled] = useState(
|
||||
!isApprovedDisabled
|
||||
);
|
||||
const [approvalAction, setApprovalAction] = useState<'APPROVED' | 'REJECTED'>(
|
||||
!isApprovedDisabled ? 'APPROVED' : 'REJECTED'
|
||||
);
|
||||
|
||||
if (!chickinId) {
|
||||
router.back();
|
||||
|
||||
return (
|
||||
<div className='w-full flex flex-row justify-center items-center p-4'>
|
||||
<span className='loading loading-spinner loading-xl' />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!isLoading && (!chickin || isResponseError(chickin))) {
|
||||
router.replace('/404');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isResponseSuccess(chickin)) {
|
||||
return (
|
||||
<div className='w-full flex flex-row justify-center items-center p-4'>
|
||||
<span className='loading loading-spinner loading-xl' />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const confirmationModalClickHandler = async ({
|
||||
action = 'APPROVED',
|
||||
}: {
|
||||
action: 'APPROVED' | 'REJECTED';
|
||||
}) => {
|
||||
if (chickin?.data.id === undefined) return;
|
||||
setIsApproveLoading(true);
|
||||
const approveChickinRes = await ChickinApi.customRequest<
|
||||
BaseApiResponse<Chickin>,
|
||||
ChickinApprovalPayload
|
||||
>(`/approvals`, {
|
||||
method: 'POST',
|
||||
payload: {
|
||||
action: action,
|
||||
approvable_ids: [chickin.data.id],
|
||||
},
|
||||
});
|
||||
|
||||
if (isResponseSuccess(approveChickinRes)) {
|
||||
if (refreshChickin) {
|
||||
await refreshChickin();
|
||||
}
|
||||
toast.success(approveChickinRes.message as string);
|
||||
}
|
||||
if (isResponseError(approveChickinRes)) {
|
||||
toast.error(approveChickinRes?.message as string);
|
||||
}
|
||||
confirmModal.closeModal();
|
||||
setIsApproveLoading(false);
|
||||
};
|
||||
|
||||
const confirmationModalDeleteClickHandler = async () => {
|
||||
setIsDeleteLoading(true);
|
||||
const deleteProjectFlockRes = await ChickinApi.delete(
|
||||
chickin.data?.id as number
|
||||
);
|
||||
|
||||
if (isResponseSuccess(deleteProjectFlockRes)) {
|
||||
toast.success(deleteProjectFlockRes?.message as string);
|
||||
router.push('/production/chickin');
|
||||
}
|
||||
if (isResponseError(deleteProjectFlockRes)) {
|
||||
toast.error(deleteProjectFlockRes?.message as string);
|
||||
}
|
||||
deleteModal.closeModal();
|
||||
setIsDeleteLoading(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='w-full p-4 flex flex-col justify-center gap-4'>
|
||||
{isLoading && <span className='loading loading-spinner loading-xl' />}
|
||||
{!isLoading && isResponseSuccess(chickin) && (
|
||||
<>
|
||||
{/* <div className='w-full flex flex-col sm:flex-row gap-2'>
|
||||
<Button
|
||||
variant='outline'
|
||||
color='success'
|
||||
onClick={(() => {
|
||||
if (chickin?.data.id) {
|
||||
setApprovalAction('APPROVED');
|
||||
confirmModal.openModal();
|
||||
}
|
||||
})}
|
||||
disabled={!chickin?.data.id || isApprovedDisabled}
|
||||
className='w-full sm:w-fit'
|
||||
>
|
||||
<Icon icon='material-symbols:check' width={24} height={24} />
|
||||
Approve
|
||||
</Button>
|
||||
<Button
|
||||
variant='outline'
|
||||
color='error'
|
||||
onClick={() => {
|
||||
if (chickin?.data.id) {
|
||||
setApprovalAction('REJECTED');
|
||||
confirmModal.openModal();
|
||||
}
|
||||
}}
|
||||
disabled={!chickin?.data.id || isRejectedDisabled}
|
||||
className='w-full sm:w-fit'
|
||||
>
|
||||
<Icon icon='mdi:times' width={24} height={24} />
|
||||
Reject
|
||||
</Button>
|
||||
</div> */}
|
||||
<Card
|
||||
title='Informasi Umum'
|
||||
variant='bordered'
|
||||
className={{
|
||||
wrapper: 'w-full',
|
||||
}}
|
||||
>
|
||||
<div className='grid grid-cols-2 gap-4 mt-4'>
|
||||
<div className='flex flex-col gap-2'>
|
||||
<div className='font-semibold text-sm'>Flock</div>
|
||||
<div className='text-sm'>
|
||||
{
|
||||
chickin.data.project_flock_kandang?.project_flock.flock
|
||||
.name
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex flex-col gap-2'>
|
||||
<div className='font-semibold text-sm'>Area</div>
|
||||
<div className='text-sm'>
|
||||
{
|
||||
chickin.data.project_flock_kandang?.project_flock.area
|
||||
.name
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex flex-col gap-2'>
|
||||
<div className='font-semibold text-sm'>Kategori</div>
|
||||
<div className='text-sm'>
|
||||
{chickin.data.project_flock_kandang?.project_flock.category}
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex flex-col gap-2'>
|
||||
<div className='font-semibold text-sm'>Lokasi</div>
|
||||
<div className='text-sm'>
|
||||
{
|
||||
chickin.data.project_flock_kandang?.project_flock.location
|
||||
.name
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex flex-col gap-2'>
|
||||
<div className='font-semibold text-sm'>Periode</div>
|
||||
<div className='text-sm'>
|
||||
{chickin.data.project_flock_kandang?.project_flock.period}
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex flex-col gap-2'>
|
||||
<div className='font-semibold text-sm'>Kandang</div>
|
||||
<div className='text-sm'>
|
||||
{chickin.data.project_flock_kandang?.kandang.name}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
<Card
|
||||
title='Detail Chickin'
|
||||
variant='bordered'
|
||||
className={{
|
||||
wrapper: 'w-full',
|
||||
}}
|
||||
>
|
||||
<div className='grid grid-cols-2 gap-4 mt-4'>
|
||||
<div className='flex flex-col gap-2'>
|
||||
<div className='font-semibold text-sm'>Flock Kandang</div>
|
||||
<div className='text-sm'>
|
||||
{
|
||||
chickin.data.project_flock_kandang?.project_flock.flock
|
||||
.name
|
||||
}{' '}
|
||||
- {chickin.data.project_flock_kandang?.kandang.name}
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex flex-col gap-2'>
|
||||
<div className='font-semibold text-sm'>Tanggal Chickin</div>
|
||||
<div className='text-sm'>
|
||||
{chickin.data.chick_in_date
|
||||
? new Date(chickin.data.chick_in_date).toLocaleDateString(
|
||||
'id-ID'
|
||||
)
|
||||
: '-'}
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex flex-col gap-2'>
|
||||
<div className='font-semibold text-sm'>Jumlah (Ekor)</div>
|
||||
<div className='text-sm'>
|
||||
{chickin.data.quantity?.toLocaleString('id-ID')}
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex flex-col gap-2'>
|
||||
<div className='font-semibold text-sm'>Catatan</div>
|
||||
<div className='text-sm'>{chickin.data.note}</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
<div className='w-full flex flex-col sm:flex-row gap-2'>
|
||||
<Button
|
||||
color='error'
|
||||
onClick={() => {
|
||||
deleteModal.openModal();
|
||||
}}
|
||||
>
|
||||
<Icon icon='mdi:times' width={24} height={24} />
|
||||
Delete
|
||||
</Button>
|
||||
<Button color='warning'
|
||||
onClick={() => {
|
||||
chickinModal.openModal();
|
||||
}}
|
||||
>
|
||||
<Icon icon='mdi:pencil-outline' width={24} height={24} />
|
||||
Edit
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ConfirmationModal
|
||||
ref={deleteModal.ref}
|
||||
type='error'
|
||||
text={`Apakah anda yakin ingin menghapus data Project Flock ini (${chickin?.data.project_flock_kandang?.project_flock.flock.name} - ${chickin?.data.project_flock_kandang?.kandang.name})?`}
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: 'error',
|
||||
isLoading: isDeleteLoading,
|
||||
onClick: confirmationModalDeleteClickHandler,
|
||||
}}
|
||||
/>
|
||||
|
||||
<Modal ref={chickinModal.ref}>
|
||||
<div className='flex flex-row justify-between items-center'>
|
||||
<h1 className='text-xl font-semibold text-center mb-6'>
|
||||
Chickin Kandang -{' '}
|
||||
{chickin?.data?.project_flock_kandang &&
|
||||
chickin?.data?.project_flock_kandang.kandang?.name}
|
||||
</h1>
|
||||
<Button
|
||||
color='error'
|
||||
variant='link'
|
||||
onClick={chickinModal.closeModal}
|
||||
>
|
||||
<Icon
|
||||
className='text-black'
|
||||
icon='uil:times'
|
||||
width={24}
|
||||
height={24}
|
||||
/>
|
||||
</Button>
|
||||
</div>
|
||||
<ChickinForm
|
||||
initialValues={chickin?.data}
|
||||
formType='edit'
|
||||
afterSubmit={() => {
|
||||
refreshChickin();
|
||||
chickinModal.closeModal();
|
||||
}}
|
||||
/>
|
||||
</Modal>
|
||||
|
||||
<ConfirmationModal
|
||||
ref={confirmModal.ref}
|
||||
type={approvalAction == 'APPROVED' ? 'success' : 'error'}
|
||||
text={`Apakah anda yakin ingin ${
|
||||
approvalAction == 'APPROVED' ? 'approve' : 'reject'
|
||||
} chickin berikut? (${
|
||||
chickin?.data.project_flock_kandang?.project_flock.flock.name
|
||||
} - ${chickin?.data.project_flock_kandang?.kandang.name})?`}
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: approvalAction == 'APPROVED' ? 'success' : 'error',
|
||||
isLoading: isApproveLoading,
|
||||
onClick: () => {
|
||||
confirmationModalClickHandler({
|
||||
action: approvalAction,
|
||||
});
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default DetailChickin;
|
||||
@@ -0,0 +1,10 @@
|
||||
import ChickinTable from "@/components/pages/production/chickin/ChickinTable";
|
||||
|
||||
const Chickin = () => {
|
||||
return (
|
||||
<section className="w-full p-4">
|
||||
<ChickinTable/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
export default Chickin;
|
||||
@@ -0,0 +1,13 @@
|
||||
'use client'
|
||||
|
||||
import ProjectFlockForm from "@/components/pages/production/project-flock/form/ProjectFlockForm";
|
||||
|
||||
const AddProjectFlock = () => {
|
||||
return (
|
||||
<section className="w-full p-4 flex flex-row justify-center">
|
||||
<ProjectFlockForm formType="add"/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export default AddProjectFlock;
|
||||
@@ -0,0 +1,46 @@
|
||||
'use client'
|
||||
|
||||
|
||||
import ProjectFlockForm from "@/components/pages/production/project-flock/form/ProjectFlockForm";
|
||||
import { isResponseError, isResponseSuccess } from "@/lib/api-helper";
|
||||
import { ProjectFlockApi } from "@/services/api/production";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import useSWR from "swr";
|
||||
|
||||
const ProjectFlockEdit = () => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const projectFlockId = searchParams.get("projectFlockId");
|
||||
|
||||
const { data: projectFlock, isLoading: isLoadingCostumer } = useSWR(
|
||||
projectFlockId,
|
||||
(id: number) => ProjectFlockApi.getSingle(id)
|
||||
);
|
||||
|
||||
if(!projectFlockId){
|
||||
router.back();
|
||||
|
||||
return (
|
||||
<div className="w-full flex flex-row justify-center items-center p-4">
|
||||
<span className="loading loading-spinner loading-xl" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if(!isLoadingCostumer && (!projectFlock || isResponseError(projectFlock))){
|
||||
router.replace("/404");
|
||||
return;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-full p-4 flex flex-row justify-center">
|
||||
{isLoadingCostumer && <span className="loading loading-spinner loading-xl" />}
|
||||
{!isLoadingCostumer && isResponseSuccess(projectFlock) && (
|
||||
<ProjectFlockForm formType="edit" initialValues={projectFlock.data} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ProjectFlockEdit;
|
||||
@@ -0,0 +1,11 @@
|
||||
import SuspenseHelper from "@/components/helper/SuspenseHelper"
|
||||
|
||||
const Layout = ({
|
||||
children
|
||||
}: Readonly<{
|
||||
children: React.ReactNode
|
||||
}>) => {
|
||||
return <SuspenseHelper>{children}</SuspenseHelper>
|
||||
}
|
||||
|
||||
export default Layout;
|
||||
@@ -0,0 +1,51 @@
|
||||
'use client';
|
||||
|
||||
import ProjectFlockForm from '@/components/pages/production/project-flock/form/ProjectFlockForm';
|
||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||
import { ProjectFlockApi } from '@/services/api/production';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import useSWR from 'swr';
|
||||
|
||||
const ProjectFlockDetail = () => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const projectFlockId = searchParams.get('projectFlockId');
|
||||
|
||||
const {
|
||||
data: projectFlock,
|
||||
isLoading: isLoadingProjectFlock,
|
||||
mutate: refreshProjectFlock,
|
||||
} = useSWR(projectFlockId, (id: number) => ProjectFlockApi.getSingle(id));
|
||||
|
||||
if (!projectFlockId) {
|
||||
router.back();
|
||||
|
||||
return (
|
||||
<div className='w-full flex flex-row justify-center items-center p-4'>
|
||||
<span className='loading loading-spinner loading-xl' />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
!isLoadingProjectFlock &&
|
||||
(!projectFlock || isResponseError(projectFlock))
|
||||
) {
|
||||
router.replace('/404');
|
||||
return;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='w-full p-4 flex flex-row justify-center'>
|
||||
{isLoadingProjectFlock && (
|
||||
<span className='loading loading-spinner loading-xl' />
|
||||
)}
|
||||
{!isLoadingProjectFlock && isResponseSuccess(projectFlock) && (
|
||||
<ProjectFlockForm formType='detail' initialValues={projectFlock.data} refreshProjectFlocks={refreshProjectFlock} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProjectFlockDetail;
|
||||
@@ -0,0 +1,11 @@
|
||||
import ProjectFlockTable from "@/components/pages/production/project-flock/ProjectFlockTable";
|
||||
|
||||
const ProjectFlock = () => {
|
||||
return (
|
||||
<section className="w-full p-4">
|
||||
<ProjectFlockTable/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export default ProjectFlock;
|
||||
@@ -0,0 +1,11 @@
|
||||
import RecordingForm from '@/components/pages/production/recording/form/RecordingForm';
|
||||
|
||||
const AddRecording = () => {
|
||||
return (
|
||||
<div className='w-full p-4 flex flex-row justify-center'>
|
||||
<RecordingForm />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AddRecording;
|
||||
@@ -0,0 +1,47 @@
|
||||
'use client';
|
||||
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import useSWR from 'swr';
|
||||
import RecordingForm from '@/components/pages/production/recording/form/RecordingForm';
|
||||
import { RecordingApi } from '@/services/api/production';
|
||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||
|
||||
const RecordingEdit = () => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const recordingId = searchParams.get('recordingId');
|
||||
|
||||
const { data: recording, isLoading: isLoadingRecording } = useSWR(
|
||||
recordingId,
|
||||
(id: number) => RecordingApi.getSingle(id) // Gunakan RecordingApi
|
||||
);
|
||||
|
||||
if (!recordingId) {
|
||||
router.back();
|
||||
|
||||
return (
|
||||
<div className='w-full flex flex-row justify-center items-center p-4'>
|
||||
<span className='loading loading-spinner loading-xl' />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!isLoadingRecording && (!recording || isResponseError(recording))) {
|
||||
router.replace('/404');
|
||||
return;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='w-full p-4 flex flex-row justify-center'>
|
||||
{isLoadingRecording && (
|
||||
<span className='loading loading-spinner loading-xl' />
|
||||
)}
|
||||
{!isLoadingRecording && isResponseSuccess(recording) && (
|
||||
<RecordingForm type='edit' initialValues={recording.data} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default RecordingEdit;
|
||||
@@ -0,0 +1,11 @@
|
||||
import SuspenseHelper from '@/components/helper/SuspenseHelper';
|
||||
|
||||
const Layout = ({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) => {
|
||||
return <SuspenseHelper>{children}</SuspenseHelper>;
|
||||
};
|
||||
|
||||
export default Layout;
|
||||
@@ -0,0 +1,47 @@
|
||||
'use client';
|
||||
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import useSWR from 'swr';
|
||||
import RecordingForm from '@/components/pages/production/recording/form/RecordingForm';
|
||||
import { RecordingApi } from '@/services/api/production';
|
||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||
|
||||
const RecordingDetail = () => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const recordingId = searchParams.get('recordingId');
|
||||
|
||||
const { data: recording, isLoading: isLoadingRecording } = useSWR(
|
||||
recordingId,
|
||||
(id: number) => RecordingApi.getSingle(id)
|
||||
);
|
||||
|
||||
if (!recordingId) {
|
||||
router.back();
|
||||
|
||||
return (
|
||||
<div className='w-full flex flex-row justify-center items-center p-4'>
|
||||
<span className='loading loading-spinner loading-xl' />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!isLoadingRecording && (!recording || isResponseError(recording))) {
|
||||
router.replace('/404');
|
||||
return;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='w-full p-4 flex flex-row justify-center'>
|
||||
{isLoadingRecording && (
|
||||
<span className='loading loading-spinner loading-xl' />
|
||||
)}
|
||||
{!isLoadingRecording && isResponseSuccess(recording) && (
|
||||
<RecordingForm type='detail' initialValues={recording.data} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default RecordingDetail;
|
||||
@@ -0,0 +1,11 @@
|
||||
import RecordingTable from '@/components/pages/production/recording/RecordingTable';
|
||||
|
||||
const Recording = () => {
|
||||
return (
|
||||
<section className='w-full p-4'>
|
||||
<RecordingTable />
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
export default Recording;
|
||||
@@ -0,0 +1,11 @@
|
||||
import TransferToLayingForm from '@/components/pages/production/transfer-to-laying/form/TransferToLayingForm';
|
||||
|
||||
const AddTransferToLaying = () => {
|
||||
return (
|
||||
<div className='w-full p-4 flex flex-row justify-center'>
|
||||
<TransferToLayingForm />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AddTransferToLaying;
|
||||
@@ -0,0 +1,148 @@
|
||||
'use client';
|
||||
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import useSWR from 'swr';
|
||||
|
||||
import TransferToLayingForm from '@/components/pages/production/transfer-to-laying/form/TransferToLayingForm';
|
||||
|
||||
import { TransferToLayingApi } from '@/services/api/production/transfer-to-laying';
|
||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||
|
||||
import { TransferToLaying } from '@/types/api/production/transfer-to-laying';
|
||||
|
||||
// TODO: delete dummy data
|
||||
const DUMMY_TRANSFER_TO_LAYING_EDIT: TransferToLaying = {
|
||||
id: 1,
|
||||
transfer_date: '2025-10-14',
|
||||
flock_source: {
|
||||
id: 1,
|
||||
name: 'Flock asal test',
|
||||
},
|
||||
flock_destination: {
|
||||
id: 2,
|
||||
name: 'Flock tujuan destination',
|
||||
},
|
||||
quantity: 10,
|
||||
kandangs: [
|
||||
{
|
||||
kandang: {
|
||||
id: 1,
|
||||
name: 'Kandang test',
|
||||
status: 'ACTIVE',
|
||||
location: {
|
||||
id: 1,
|
||||
name: 'test location',
|
||||
address: 'test address 1',
|
||||
area: { id: 1, name: 'test area 1' },
|
||||
},
|
||||
pic: {
|
||||
id: 1,
|
||||
id_user: 2,
|
||||
email: 'test@gmail.com',
|
||||
name: 'test',
|
||||
},
|
||||
created_user: {
|
||||
id: 1,
|
||||
id_user: 2,
|
||||
email: 'test@gmail.com',
|
||||
name: 'test',
|
||||
},
|
||||
created_at: '14-10-2025',
|
||||
updated_at: '14-10-2025',
|
||||
},
|
||||
quantity: 8,
|
||||
},
|
||||
{
|
||||
kandang: {
|
||||
id: 1,
|
||||
name: 'Kandang test 2',
|
||||
status: 'ACTIVE',
|
||||
location: {
|
||||
id: 1,
|
||||
name: 'test location',
|
||||
address: 'test address 1',
|
||||
area: { id: 1, name: 'test area 1' },
|
||||
},
|
||||
pic: {
|
||||
id: 1,
|
||||
id_user: 2,
|
||||
email: 'test@gmail.com',
|
||||
name: 'test',
|
||||
},
|
||||
created_user: {
|
||||
id: 1,
|
||||
id_user: 2,
|
||||
email: 'test@gmail.com',
|
||||
name: 'test',
|
||||
},
|
||||
created_at: '14-10-2025',
|
||||
updated_at: '14-10-2025',
|
||||
},
|
||||
quantity: 2,
|
||||
},
|
||||
],
|
||||
reason: 'Test alasan',
|
||||
|
||||
created_user: {
|
||||
id: 1,
|
||||
id_user: 2,
|
||||
email: 'test@gmail.com',
|
||||
name: 'test',
|
||||
},
|
||||
created_at: '14-10-2025',
|
||||
updated_at: '14-10-2025',
|
||||
};
|
||||
|
||||
const TransferToLayingEdit = () => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const transferToLayingId = searchParams.get('transferToLayingId');
|
||||
|
||||
const { data: transferToLaying, isLoading: isLoadingTransferToLaying } =
|
||||
useSWR(transferToLayingId, (id: number) =>
|
||||
TransferToLayingApi.getSingle(id)
|
||||
);
|
||||
|
||||
if (!transferToLayingId) {
|
||||
router.back();
|
||||
|
||||
return (
|
||||
<div className='w-full flex flex-row justify-center items-center p-4'>
|
||||
<span className='loading loading-spinner loading-xl' />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// TODO: remove dummy data and integrate with real API
|
||||
if (
|
||||
!isLoadingTransferToLaying &&
|
||||
(!transferToLaying ||
|
||||
(isResponseError(transferToLaying) && !DUMMY_TRANSFER_TO_LAYING_EDIT))
|
||||
) {
|
||||
router.replace('/404');
|
||||
return;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='w-full p-4 flex flex-row justify-center'>
|
||||
{isLoadingTransferToLaying && (
|
||||
<span className='loading loading-spinner loading-xl' />
|
||||
)}
|
||||
{/* {!isLoadingTransferToLaying && isResponseSuccess(transferToLaying) && (
|
||||
<TransferToLayingForm
|
||||
type='detail'
|
||||
initialValues={transferToLaying.data}
|
||||
/>
|
||||
)} */}
|
||||
|
||||
{/* TODO: remove this dummy data and integrate to real API */}
|
||||
<TransferToLayingForm
|
||||
type='edit'
|
||||
initialValues={DUMMY_TRANSFER_TO_LAYING_EDIT}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default TransferToLayingEdit;
|
||||
@@ -0,0 +1,11 @@
|
||||
import SuspenseHelper from '@/components/helper/SuspenseHelper';
|
||||
|
||||
const Layout = ({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) => {
|
||||
return <SuspenseHelper>{children}</SuspenseHelper>;
|
||||
};
|
||||
|
||||
export default Layout;
|
||||
@@ -0,0 +1,148 @@
|
||||
'use client';
|
||||
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import useSWR from 'swr';
|
||||
|
||||
import TransferToLayingForm from '@/components/pages/production/transfer-to-laying/form/TransferToLayingForm';
|
||||
|
||||
import { TransferToLayingApi } from '@/services/api/production/transfer-to-laying';
|
||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||
|
||||
import { TransferToLaying } from '@/types/api/production/transfer-to-laying';
|
||||
|
||||
// TODO: delete dummy data
|
||||
const DUMMY_TRANSFER_TO_LAYING_DETAIL: TransferToLaying = {
|
||||
id: 1,
|
||||
transfer_date: '2025-10-14',
|
||||
flock_source: {
|
||||
id: 1,
|
||||
name: 'Flock asal test',
|
||||
},
|
||||
flock_destination: {
|
||||
id: 2,
|
||||
name: 'Flock tujuan destination',
|
||||
},
|
||||
quantity: 10,
|
||||
kandangs: [
|
||||
{
|
||||
kandang: {
|
||||
id: 1,
|
||||
name: 'Kandang test',
|
||||
status: 'ACTIVE',
|
||||
location: {
|
||||
id: 1,
|
||||
name: 'test location',
|
||||
address: 'test address 1',
|
||||
area: { id: 1, name: 'test area 1' },
|
||||
},
|
||||
pic: {
|
||||
id: 1,
|
||||
id_user: 2,
|
||||
email: 'test@gmail.com',
|
||||
name: 'test',
|
||||
},
|
||||
created_user: {
|
||||
id: 1,
|
||||
id_user: 2,
|
||||
email: 'test@gmail.com',
|
||||
name: 'test',
|
||||
},
|
||||
created_at: '14-10-2025',
|
||||
updated_at: '14-10-2025',
|
||||
},
|
||||
quantity: 8,
|
||||
},
|
||||
{
|
||||
kandang: {
|
||||
id: 1,
|
||||
name: 'Kandang test 2',
|
||||
status: 'ACTIVE',
|
||||
location: {
|
||||
id: 1,
|
||||
name: 'test location',
|
||||
address: 'test address 1',
|
||||
area: { id: 1, name: 'test area 1' },
|
||||
},
|
||||
pic: {
|
||||
id: 1,
|
||||
id_user: 2,
|
||||
email: 'test@gmail.com',
|
||||
name: 'test',
|
||||
},
|
||||
created_user: {
|
||||
id: 1,
|
||||
id_user: 2,
|
||||
email: 'test@gmail.com',
|
||||
name: 'test',
|
||||
},
|
||||
created_at: '14-10-2025',
|
||||
updated_at: '14-10-2025',
|
||||
},
|
||||
quantity: 2,
|
||||
},
|
||||
],
|
||||
reason: 'Test alasan',
|
||||
|
||||
created_user: {
|
||||
id: 1,
|
||||
id_user: 2,
|
||||
email: 'test@gmail.com',
|
||||
name: 'test',
|
||||
},
|
||||
created_at: '14-10-2025',
|
||||
updated_at: '14-10-2025',
|
||||
};
|
||||
|
||||
const TransferToLayingDetail = () => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const transferToLayingId = searchParams.get('transferToLayingId');
|
||||
|
||||
const { data: transferToLaying, isLoading: isLoadingTransferToLaying } =
|
||||
useSWR(transferToLayingId, (id: number) =>
|
||||
TransferToLayingApi.getSingle(id)
|
||||
);
|
||||
|
||||
if (!transferToLayingId) {
|
||||
router.back();
|
||||
|
||||
return (
|
||||
<div className='w-full flex flex-row justify-center items-center p-4'>
|
||||
<span className='loading loading-spinner loading-xl' />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// TODO: remove dummy data and integrate with real API
|
||||
if (
|
||||
!isLoadingTransferToLaying &&
|
||||
(!transferToLaying ||
|
||||
(isResponseError(transferToLaying) && !DUMMY_TRANSFER_TO_LAYING_DETAIL))
|
||||
) {
|
||||
router.replace('/404');
|
||||
return;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='w-full p-4 flex flex-row justify-center'>
|
||||
{isLoadingTransferToLaying && (
|
||||
<span className='loading loading-spinner loading-xl' />
|
||||
)}
|
||||
{/* {!isLoadingTransferToLaying && isResponseSuccess(transferToLaying) && (
|
||||
<TransferToLayingForm
|
||||
type='detail'
|
||||
initialValues={transferToLaying.data}
|
||||
/>
|
||||
)} */}
|
||||
|
||||
{/* TODO: remove this dummy data and integrate to real API */}
|
||||
<TransferToLayingForm
|
||||
type='detail'
|
||||
initialValues={DUMMY_TRANSFER_TO_LAYING_DETAIL}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default TransferToLayingDetail;
|
||||
@@ -0,0 +1,11 @@
|
||||
import TransferToLayingsTable from '@/components/pages/production/transfer-to-laying/TransferToLayingsTable';
|
||||
|
||||
const TransferToLaying = () => {
|
||||
return (
|
||||
<section className='w-full p-4'>
|
||||
<TransferToLayingsTable />
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
export default TransferToLaying;
|
||||
@@ -0,0 +1,80 @@
|
||||
'use client';
|
||||
|
||||
import { HTMLAttributes, ReactNode } from 'react';
|
||||
|
||||
import { cn } from '@/lib/helper';
|
||||
|
||||
export interface BadgeProps
|
||||
extends Omit<HTMLAttributes<HTMLSpanElement>, 'className'> {
|
||||
children?: ReactNode;
|
||||
className?: {
|
||||
badge?: string;
|
||||
};
|
||||
variant?: 'default' | 'outline' | 'ghost' | 'soft' | 'dash';
|
||||
color?:
|
||||
| 'neutral'
|
||||
| 'primary'
|
||||
| 'secondary'
|
||||
| 'accent'
|
||||
| 'info'
|
||||
| 'success'
|
||||
| 'warning'
|
||||
| 'error';
|
||||
size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl';
|
||||
}
|
||||
|
||||
const Badge = ({
|
||||
children,
|
||||
className,
|
||||
variant = 'default',
|
||||
color,
|
||||
size = 'md',
|
||||
...props
|
||||
}: BadgeProps) => {
|
||||
const getBadgeClasses = () => {
|
||||
const baseClasses = 'badge';
|
||||
|
||||
const variantClasses = {
|
||||
default: '',
|
||||
outline: 'badge-outline',
|
||||
ghost: 'badge-ghost',
|
||||
soft: 'badge-soft',
|
||||
dash: 'badge-dash',
|
||||
};
|
||||
|
||||
const colorClasses = {
|
||||
neutral: 'badge-neutral',
|
||||
primary: 'badge-primary',
|
||||
secondary: 'badge-secondary',
|
||||
accent: 'badge-accent',
|
||||
info: 'badge-info',
|
||||
success: 'badge-success',
|
||||
warning: 'badge-warning',
|
||||
error: 'badge-error',
|
||||
};
|
||||
|
||||
const sizeClasses = {
|
||||
xs: 'badge-xs',
|
||||
sm: 'badge-sm',
|
||||
md: 'badge-md',
|
||||
lg: 'badge-lg',
|
||||
xl: 'badge-xl',
|
||||
};
|
||||
|
||||
return cn(
|
||||
baseClasses,
|
||||
variantClasses[variant],
|
||||
color && colorClasses[color],
|
||||
sizeClasses[size],
|
||||
className?.badge
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<span className={getBadgeClasses()} {...props}>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
export default Badge;
|
||||
@@ -1,7 +1,5 @@
|
||||
import react from 'react';
|
||||
|
||||
import Link from 'next/link';
|
||||
|
||||
import { cn } from '@/lib/helper';
|
||||
import { Color } from '@/types/theme';
|
||||
|
||||
@@ -10,6 +8,8 @@ interface ButtonProps extends react.ComponentProps<'button'> {
|
||||
color?: Color;
|
||||
href?: string;
|
||||
isLoading?: boolean;
|
||||
target?: string;
|
||||
rel?: string;
|
||||
}
|
||||
|
||||
const Button = ({
|
||||
@@ -22,6 +22,8 @@ const Button = ({
|
||||
className,
|
||||
disabled,
|
||||
onClick,
|
||||
target,
|
||||
rel,
|
||||
...props
|
||||
}: ButtonProps) => {
|
||||
const btnBaseClassName = cn(
|
||||
@@ -43,7 +45,7 @@ const Button = ({
|
||||
'btn-warning': color === 'warning',
|
||||
'btn-error': color === 'error',
|
||||
},
|
||||
'h-fit justify-center items-center gap-2 rounded-xl p-2 text-base transition-all'
|
||||
'h-fit justify-center items-center gap-2 rounded p-2 text-base transition-all'
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -68,6 +70,8 @@ const Button = ({
|
||||
{href && (
|
||||
<Link
|
||||
href={disabled ? '#' : href}
|
||||
target={target}
|
||||
rel={rel}
|
||||
aria-disabled={disabled}
|
||||
className={cn(
|
||||
btnBaseClassName,
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
'use client';
|
||||
|
||||
import {
|
||||
HTMLAttributes,
|
||||
ReactNode,
|
||||
} from 'react';
|
||||
|
||||
import { cn } from '@/lib/helper';
|
||||
import Image from 'next/image';
|
||||
|
||||
export interface CardProps extends Omit<HTMLAttributes<HTMLDivElement>, 'className'> {
|
||||
title?: string;
|
||||
subtitle?: string;
|
||||
image?: string;
|
||||
imageAlt?: string;
|
||||
actions?: ReactNode;
|
||||
footer?: ReactNode;
|
||||
className?: {
|
||||
wrapper?: string;
|
||||
image?: string;
|
||||
body?: string;
|
||||
title?: string;
|
||||
subtitle?: string;
|
||||
actions?: string;
|
||||
footer?: string;
|
||||
};
|
||||
variant?: 'default' | 'compact' | 'bordered' | 'shadow' | 'image-full';
|
||||
size?: 'sm' | 'md' | 'lg';
|
||||
}
|
||||
|
||||
const Card = ({
|
||||
title,
|
||||
subtitle,
|
||||
image,
|
||||
imageAlt,
|
||||
actions,
|
||||
footer,
|
||||
className,
|
||||
variant = 'default',
|
||||
size = 'md',
|
||||
children,
|
||||
...props
|
||||
}: CardProps) => {
|
||||
const getCardClasses = () => {
|
||||
const baseClasses = 'card bg-base-100';
|
||||
|
||||
const variantClasses = {
|
||||
'default': '',
|
||||
'compact': 'card-compact',
|
||||
'bordered': 'border border-base-300',
|
||||
'shadow': 'shadow-xl',
|
||||
'image-full': 'card-side card-compact shadow-xl',
|
||||
};
|
||||
|
||||
const sizeClasses = {
|
||||
'sm': 'w-64',
|
||||
'md': 'w-96',
|
||||
'lg': 'w-[28rem]',
|
||||
};
|
||||
|
||||
return cn(
|
||||
baseClasses,
|
||||
variantClasses[variant],
|
||||
variant !== 'image-full' ? sizeClasses[size] : '',
|
||||
className?.wrapper
|
||||
);
|
||||
};
|
||||
|
||||
const getImageClasses = () => {
|
||||
if (variant === 'image-full') {
|
||||
return cn('w-32 h-32 object-cover', className?.image);
|
||||
}
|
||||
return cn('h-48 object-cover', className?.image);
|
||||
};
|
||||
|
||||
const getBodyClasses = () => {
|
||||
const baseClasses = 'card-body';
|
||||
|
||||
if (variant === 'compact' || variant === 'image-full') {
|
||||
return cn(baseClasses, 'p-4', className?.body);
|
||||
}
|
||||
|
||||
return cn(baseClasses, 'p-6', className?.body);
|
||||
};
|
||||
|
||||
const getTitleClasses = () => {
|
||||
const sizeClasses = {
|
||||
'sm': 'text-lg',
|
||||
'md': 'text-xl',
|
||||
'lg': 'text-2xl',
|
||||
};
|
||||
|
||||
return cn('card-title font-bold', sizeClasses[size], className?.title);
|
||||
};
|
||||
|
||||
const getSubtitleClasses = () => {
|
||||
return cn('text-base-content/70 text-sm mt-1', className?.subtitle);
|
||||
};
|
||||
|
||||
const getActionsClasses = () => {
|
||||
return cn('card-actions justify-end mt-4', className?.actions);
|
||||
};
|
||||
|
||||
const getFooterClasses = () => {
|
||||
return cn('border-t border-base-300 mt-4 pt-4', className?.footer);
|
||||
};
|
||||
|
||||
if (variant === 'image-full' && image) {
|
||||
return (
|
||||
<div className={getCardClasses()} {...props}>
|
||||
<figure>
|
||||
<Image
|
||||
src={image}
|
||||
alt={imageAlt || title || 'Card image'}
|
||||
className={getImageClasses()}
|
||||
/>
|
||||
</figure>
|
||||
<div className={getBodyClasses()}>
|
||||
{title && <h2 className={getTitleClasses()}>{title}</h2>}
|
||||
{subtitle && <p className={getSubtitleClasses()}>{subtitle}</p>}
|
||||
{children}
|
||||
{actions && <div className={getActionsClasses()}>{actions}</div>}
|
||||
</div>
|
||||
{footer && <div className={getFooterClasses()}>{footer}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={getCardClasses()} {...props}>
|
||||
{image && (
|
||||
<figure>
|
||||
<Image
|
||||
src={image}
|
||||
alt={imageAlt || title || 'Card image'}
|
||||
className={getImageClasses()}
|
||||
/>
|
||||
</figure>
|
||||
)}
|
||||
<div className={getBodyClasses()}>
|
||||
{title && <h2 className={getTitleClasses()}>{title}</h2>}
|
||||
{subtitle && <p className={getSubtitleClasses()}>{subtitle}</p>}
|
||||
{children}
|
||||
{actions && <div className={getActionsClasses()}>{actions}</div>}
|
||||
</div>
|
||||
{footer && <div className={getFooterClasses()}>{footer}</div>}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Card;
|
||||
@@ -68,7 +68,7 @@ export const Collapse = ({
|
||||
'collapse',
|
||||
variant === 'arrow' && 'collapse-arrow',
|
||||
variant === 'plus' && 'collapse-plus',
|
||||
bordered && 'border base-content/20 border-opacity-20 rounded-box',
|
||||
bordered && 'border base-content/20 border-opacity-20 rounded',
|
||||
disabled && 'opacity-60 pointer-events-none',
|
||||
!open && 'w-fit',
|
||||
className
|
||||
|
||||
@@ -10,6 +10,7 @@ import Menu from '@/components/menu/Menu';
|
||||
import MenuItem from '@/components/menu/MenuItem';
|
||||
import Navbar from '@/components/Navbar';
|
||||
import Collapse from '@/components/Collapse';
|
||||
import Button from '@/components/Button';
|
||||
|
||||
import { useUiStore } from '@/stores/ui/ui.store';
|
||||
import { MAIN_DRAWER_LINKS } from '@/config/constant';
|
||||
@@ -155,9 +156,15 @@ const MainDrawerMenu = () => {
|
||||
};
|
||||
|
||||
const MainDrawerContent = () => {
|
||||
const { setMainDrawerOpen } = useUiStore();
|
||||
|
||||
const closeMainDrawerHandler = () => {
|
||||
setMainDrawerOpen(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className='w-full p-4 flex flex-col gap-4'>
|
||||
<div className='flex items-center gap-4'>
|
||||
<div className='flex flex-row items-center gap-4'>
|
||||
<Image
|
||||
src='/assets/img/lti-logo.png'
|
||||
alt='MBU Logo'
|
||||
@@ -167,6 +174,21 @@ const MainDrawerContent = () => {
|
||||
/>
|
||||
|
||||
<h1 className='text-xl font-bold'>LTI ERP</h1>
|
||||
|
||||
<div className='grow flex flex-row justify-end sm:hidden'>
|
||||
<Button
|
||||
variant='soft'
|
||||
color='error'
|
||||
onClick={closeMainDrawerHandler}
|
||||
className='rounded-full'
|
||||
>
|
||||
<Icon
|
||||
icon='material-symbols:close-rounded'
|
||||
width={24}
|
||||
height={24}
|
||||
/>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<MainDrawerMenu />
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { ReactNode } from 'react';
|
||||
import { cn } from '@/lib/helper';
|
||||
|
||||
interface PillBadgeProps {
|
||||
content: ReactNode;
|
||||
color?: 'yellow' | 'blue' | 'green' | 'red' | 'purple' | 'gray';
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const PillBadge = ({ content, color = 'gray', className }: PillBadgeProps) => {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'w-fit min-w-max px-2 py-0.5 flex justify-center items-center gap-1 rounded-full border border-gray-200 bg-gray-50 text-gray-500 drop-shadow-xs capitalize',
|
||||
{
|
||||
'border-yellow-200 bg-yellow-50 text-yellow-500': color === 'yellow',
|
||||
'border-blue-200 bg-blue-50 text-blue-500': color === 'blue',
|
||||
'border-green-200 bg-green-50 text-green-500': color === 'green',
|
||||
'border-red-200 bg-red-50 text-red-500': color === 'red',
|
||||
'border-purple-200 bg-purple-50 text-purple-500': color === 'purple',
|
||||
'border-neutral-200 bg-neutral-50 text-neutral-500': color === 'gray',
|
||||
},
|
||||
className
|
||||
)}
|
||||
>
|
||||
{content}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default PillBadge;
|
||||
@@ -48,6 +48,8 @@ export interface TableProps<TData extends object> {
|
||||
sorting?: SortingState;
|
||||
setSorting?: OnChangeFn<SortingState>;
|
||||
manualSorting?: boolean;
|
||||
rowSelection?: Record<string, boolean>;
|
||||
setRowSelection?: OnChangeFn<Record<string, boolean>>;
|
||||
}
|
||||
|
||||
const DUMMY_SKELETON_DATA = [{}, {}, {}, {}, {}];
|
||||
@@ -86,6 +88,8 @@ const Table = <TData extends object>({
|
||||
sorting,
|
||||
setSorting,
|
||||
manualSorting = false,
|
||||
rowSelection,
|
||||
setRowSelection,
|
||||
}: TableProps<TData>) => {
|
||||
const isServerSideTable =
|
||||
totalItems !== undefined &&
|
||||
@@ -137,6 +141,15 @@ const Table = <TData extends object>({
|
||||
};
|
||||
}
|
||||
|
||||
if (rowSelection && setRowSelection) {
|
||||
tableOptions.onRowSelectionChange = setRowSelection;
|
||||
tableOptions.state = {
|
||||
...tableOptions.state,
|
||||
rowSelection,
|
||||
};
|
||||
tableOptions.getRowId = (row) => (row as { id: string }).id;
|
||||
}
|
||||
|
||||
const table = useReactTable(tableOptions);
|
||||
const { setPageSize } = table;
|
||||
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { ReactNode } from 'react';
|
||||
|
||||
import { cn } from '@/lib/helper';
|
||||
import { Color } from '@/types/theme';
|
||||
|
||||
interface TooltipProps {
|
||||
children?: ReactNode;
|
||||
content?: ReactNode;
|
||||
className?: {
|
||||
wrapper?: string;
|
||||
content?: string;
|
||||
};
|
||||
open?: boolean;
|
||||
color?: Color;
|
||||
position?: 'top' | 'bottom' | 'left' | 'right';
|
||||
}
|
||||
|
||||
const Tooltip = ({
|
||||
children,
|
||||
content,
|
||||
className,
|
||||
open,
|
||||
color,
|
||||
position,
|
||||
}: TooltipProps) => {
|
||||
const tooltipBaseClassName = cn('tooltip', {
|
||||
'tooltip-open': typeof open === 'boolean' && open,
|
||||
|
||||
'tooltip-top': position === 'top',
|
||||
'tooltip-bottom': position === 'bottom',
|
||||
'tooltip-left': position === 'left',
|
||||
'tooltip-right': position === 'right',
|
||||
|
||||
'tooltip-primary': color === 'primary',
|
||||
'tooltip-secondary': color === 'secondary',
|
||||
'tooltip-accent': color === 'accent',
|
||||
'tooltip-neutral': color === 'neutral',
|
||||
'tooltip-info': color === 'info',
|
||||
'tooltip-success': color === 'success',
|
||||
'tooltip-warning': color === 'warning',
|
||||
'tooltip-error': color === 'error',
|
||||
});
|
||||
return (
|
||||
<div className={cn(tooltipBaseClassName, className?.wrapper)}>
|
||||
<div
|
||||
className={cn(
|
||||
'tooltip-content',
|
||||
'max-w-60 sm:max-w-xs',
|
||||
className?.content
|
||||
)}
|
||||
>
|
||||
{content}
|
||||
</div>
|
||||
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Tooltip;
|
||||
@@ -158,7 +158,7 @@ const RequireAuth = ({ children }: RequireAuthProps) => {
|
||||
|
||||
const { data: userResponse, isLoading: isLoadingUserResponse } =
|
||||
useSWRImmutable<GetMeResponse & { ok?: boolean }, unknown, SWRHttpKey>(
|
||||
'/auth/get-me',
|
||||
'/auth/sso/userinfo',
|
||||
httpClientFetcher,
|
||||
{
|
||||
shouldRetryOnError: false,
|
||||
@@ -194,4 +194,4 @@ const RequireAuth = ({ children }: RequireAuthProps) => {
|
||||
return <>{children}</>;
|
||||
};
|
||||
|
||||
export default RequireAuth;
|
||||
export default RequireAuth;
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import { Icon } from '@iconify/react';
|
||||
import { FormikContextType } from 'formik';
|
||||
import Button from '@/components/Button';
|
||||
import { cn } from '@/lib/helper';
|
||||
|
||||
interface FormActionsProps<T> {
|
||||
type: 'add' | 'edit' | 'detail';
|
||||
formik: FormikContextType<T>;
|
||||
editUrl?: string;
|
||||
onDelete?: () => void;
|
||||
disableSubmit?: boolean;
|
||||
onApprove?: () => void;
|
||||
onReject?: () => void;
|
||||
isApproveLoading?: boolean;
|
||||
isRejectLoading?: boolean;
|
||||
showApproveReject?: boolean;
|
||||
}
|
||||
|
||||
export const FormActions = <T,>({
|
||||
type,
|
||||
formik,
|
||||
editUrl,
|
||||
onDelete,
|
||||
disableSubmit = false,
|
||||
onApprove,
|
||||
onReject,
|
||||
isApproveLoading = false,
|
||||
isRejectLoading = false,
|
||||
showApproveReject = false,
|
||||
}: FormActionsProps<T>) => {
|
||||
return (
|
||||
<div className='flex flex-row justify-between gap-2 flex-wrap'>
|
||||
{type !== 'add' && (
|
||||
<div className='flex flex-row justify-start gap-2'>
|
||||
{onDelete && (
|
||||
<Button
|
||||
type='button'
|
||||
color='error'
|
||||
onClick={onDelete}
|
||||
className='px-4'
|
||||
>
|
||||
<Icon
|
||||
icon='material-symbols:delete-outline-rounded'
|
||||
width={24}
|
||||
height={24}
|
||||
className='justify-start text-sm'
|
||||
/>
|
||||
Delete
|
||||
</Button>
|
||||
)}
|
||||
{type !== 'edit' && editUrl && (
|
||||
<Button
|
||||
type='button'
|
||||
color='warning'
|
||||
href={editUrl}
|
||||
className='px-4'
|
||||
>
|
||||
<Icon
|
||||
icon='material-symbols:edit-outline'
|
||||
width={24}
|
||||
height={24}
|
||||
className='justify-start text-sm'
|
||||
/>
|
||||
Edit
|
||||
</Button>
|
||||
)}
|
||||
{type === 'detail' && showApproveReject && (onApprove || onReject) && (
|
||||
<>
|
||||
{onApprove && (
|
||||
<Button
|
||||
type='button'
|
||||
color='success'
|
||||
onClick={onApprove}
|
||||
className='px-4'
|
||||
isLoading={isApproveLoading}
|
||||
>
|
||||
<Icon
|
||||
icon='material-symbols:check-circle-outline'
|
||||
width={24}
|
||||
height={24}
|
||||
className='justify-start text-sm'
|
||||
/>
|
||||
Approve
|
||||
</Button>
|
||||
)}
|
||||
{onReject && (
|
||||
<Button
|
||||
type='button'
|
||||
color='error'
|
||||
onClick={onReject}
|
||||
className='px-4'
|
||||
isLoading={isRejectLoading}
|
||||
>
|
||||
<Icon
|
||||
icon='material-symbols:cancel-outline'
|
||||
width={24}
|
||||
height={24}
|
||||
className='justify-start text-sm'
|
||||
/>
|
||||
Reject
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{type !== 'detail' && (
|
||||
<div
|
||||
className={cn('flex flex-row justify-end gap-2', {
|
||||
'w-full': type === 'add',
|
||||
})}
|
||||
>
|
||||
<Button
|
||||
type='reset'
|
||||
color='warning'
|
||||
className='px-4'
|
||||
onClick={() => {
|
||||
formik.handleReset();
|
||||
formik.validateForm();
|
||||
}}
|
||||
>
|
||||
Reset
|
||||
</Button>
|
||||
<Button
|
||||
type='submit'
|
||||
color='primary'
|
||||
className='px-4'
|
||||
isLoading={formik.isSubmitting}
|
||||
disabled={disableSubmit || !formik.isValid || formik.isSubmitting}
|
||||
>
|
||||
Submit
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
import Button from '@/components/Button';
|
||||
import { Icon } from '@iconify/react';
|
||||
|
||||
interface FormHeaderProps {
|
||||
type: 'add' | 'edit' | 'detail';
|
||||
title: string;
|
||||
backUrl: string;
|
||||
}
|
||||
|
||||
export const FormHeader = ({ type, title, backUrl }: FormHeaderProps) => {
|
||||
return (
|
||||
<header className='flex flex-col gap-4'>
|
||||
<Button href={backUrl} variant='link' className='w-fit p-0 text-primary'>
|
||||
<Icon icon='uil:arrow-left' width={24} height={24} />
|
||||
Kembali
|
||||
</Button>
|
||||
<h1 className='text-2xl font-bold text-center'>
|
||||
{type === 'add' && `Tambah ${title}`}
|
||||
{type === 'edit' && `Edit ${title}`}
|
||||
{type === 'detail' && `Detail ${title}`}
|
||||
</h1>
|
||||
</header>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,89 @@
|
||||
'use client';
|
||||
|
||||
import { HTMLProps, useEffect, useRef } from 'react';
|
||||
import { cn } from '@/lib/helper';
|
||||
|
||||
interface CheckboxInputProps extends HTMLProps<HTMLInputElement> {
|
||||
name: string;
|
||||
label?: string;
|
||||
indeterminate?: boolean;
|
||||
classNames?: {
|
||||
wrapper?: string;
|
||||
inputWrapper?: string;
|
||||
checkbox?: string;
|
||||
label?: string;
|
||||
};
|
||||
isError?: boolean;
|
||||
isValid?: boolean;
|
||||
errorMessage?: string;
|
||||
}
|
||||
|
||||
const CheckboxInput = ({
|
||||
indeterminate,
|
||||
name,
|
||||
label,
|
||||
className,
|
||||
classNames,
|
||||
isValid,
|
||||
isError,
|
||||
errorMessage,
|
||||
...rest
|
||||
}: CheckboxInputProps) => {
|
||||
const ref = useRef<HTMLInputElement>(null!);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof indeterminate === 'boolean') {
|
||||
ref.current.indeterminate = !rest.checked && indeterminate;
|
||||
}
|
||||
}, [ref, indeterminate]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn('flex flex-col items-center gap-1', classNames?.wrapper)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-row justify-center items-center gap-2',
|
||||
classNames?.inputWrapper
|
||||
)}
|
||||
>
|
||||
<input
|
||||
type='checkbox'
|
||||
ref={ref}
|
||||
id={name}
|
||||
name={name}
|
||||
className={cn(
|
||||
'checkbox cursor-pointer',
|
||||
{
|
||||
'border-error': isError,
|
||||
'border-success': isValid,
|
||||
},
|
||||
className,
|
||||
classNames?.checkbox
|
||||
)}
|
||||
{...rest}
|
||||
/>
|
||||
|
||||
{label && (
|
||||
<label
|
||||
htmlFor={name}
|
||||
className={cn(
|
||||
'text-inherit',
|
||||
{
|
||||
'text-error': isError,
|
||||
'text-success': isValid,
|
||||
},
|
||||
classNames?.label
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{errorMessage && <span className='text-error'>{errorMessage}</span>}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default CheckboxInput;
|
||||
@@ -0,0 +1,137 @@
|
||||
'use client';
|
||||
|
||||
import {
|
||||
ChangeEventHandler,
|
||||
FocusEventHandler,
|
||||
ReactNode,
|
||||
} from 'react';
|
||||
|
||||
import { cn } from '@/lib/helper';
|
||||
|
||||
export interface DateInputProps {
|
||||
label?: string;
|
||||
bottomLabel?: string;
|
||||
name: string;
|
||||
value?: string;
|
||||
placeholder?: string;
|
||||
min?: string;
|
||||
max?: string;
|
||||
className?: {
|
||||
wrapper?: string;
|
||||
label?: string;
|
||||
inputWrapper?: string;
|
||||
input?: string;
|
||||
};
|
||||
isError?: boolean;
|
||||
isValid?: boolean;
|
||||
disabled?: boolean;
|
||||
readOnly?: boolean;
|
||||
required?: boolean;
|
||||
isLoading?: boolean;
|
||||
errorMessage?: string;
|
||||
startAdornment?: ReactNode;
|
||||
endAdornment?: ReactNode;
|
||||
onChange?: ChangeEventHandler<HTMLInputElement>;
|
||||
onBlur?: FocusEventHandler<HTMLInputElement>;
|
||||
}
|
||||
|
||||
const DateInput = ({
|
||||
label,
|
||||
bottomLabel,
|
||||
name,
|
||||
value,
|
||||
placeholder,
|
||||
min,
|
||||
max,
|
||||
className,
|
||||
isError,
|
||||
isValid,
|
||||
errorMessage,
|
||||
startAdornment,
|
||||
endAdornment,
|
||||
disabled = false,
|
||||
required = false,
|
||||
onChange,
|
||||
onBlur,
|
||||
readOnly = false,
|
||||
isLoading = false,
|
||||
}: DateInputProps) => {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'w-full flex flex-col gap-2 text-start',
|
||||
className?.wrapper
|
||||
)}
|
||||
>
|
||||
{label && (
|
||||
<label
|
||||
htmlFor={name}
|
||||
className={cn(
|
||||
'w-full text-sm font-normal leading-5',
|
||||
{
|
||||
'text-error': isError,
|
||||
},
|
||||
className?.label
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
{required && (
|
||||
<>
|
||||
{' '}
|
||||
<span className='tooltip tooltip-error' data-tip='required'>
|
||||
<span className='text-error'>*</span>
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</label>
|
||||
)}
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'input h-12 px-4 py-2 text-base font-normal leading-6 w-full rounded outline-none! transition-all duration-200 flex items-center',
|
||||
{
|
||||
'border-error': isError,
|
||||
'border-success!': isValid,
|
||||
},
|
||||
className?.inputWrapper
|
||||
)}
|
||||
>
|
||||
{startAdornment && startAdornment}
|
||||
|
||||
<input
|
||||
type='date'
|
||||
id={name}
|
||||
name={name}
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
onBlur={onBlur}
|
||||
min={min}
|
||||
max={max}
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
'grow bg-transparent cursor-pointer',
|
||||
className?.input
|
||||
)}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
|
||||
{(isLoading || endAdornment) && (
|
||||
<div className='flex flex-row gap-2'>
|
||||
{isLoading && <span className='loading loading-spinner' />}
|
||||
{endAdornment && endAdornment}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!isError && bottomLabel && (
|
||||
<p className='w-full text-sm opacity-60'>{bottomLabel}</p>
|
||||
)}
|
||||
{isError && errorMessage && (
|
||||
<p className='w-full text-sm text-error'>{errorMessage}</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default DateInput;
|
||||
@@ -70,7 +70,7 @@ const FileInput = ({
|
||||
onBlur={onBlur}
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
'grow file-input w-full h-12 rounded-lg!',
|
||||
'grow file-input w-full h-12 rounded',
|
||||
className?.input
|
||||
)}
|
||||
readOnly={readOnly}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
'use client';
|
||||
|
||||
import { ChangeEvent, ReactNode } from 'react';
|
||||
import { NumericFormat, OnValueChange } from 'react-number-format';
|
||||
import TextInput, { TextInputProps } from '@/components/input/TextInput';
|
||||
|
||||
interface NumberInputProps extends Omit<TextInputProps, 'type'> {
|
||||
thousandSeparator?: string;
|
||||
decimalSeparator?: string;
|
||||
decimalScale?: number;
|
||||
allowNegative?: boolean;
|
||||
prefix?: string;
|
||||
suffix?: string;
|
||||
fixedDecimalScale?: boolean;
|
||||
inputPrefix?: ReactNode;
|
||||
inputSuffix?: ReactNode;
|
||||
}
|
||||
|
||||
const NumberInput = ({
|
||||
thousandSeparator = ',',
|
||||
decimalSeparator = '.',
|
||||
decimalScale = 5,
|
||||
allowNegative = true,
|
||||
onChange,
|
||||
inputPrefix,
|
||||
inputSuffix,
|
||||
...restProps
|
||||
}: NumberInputProps) => {
|
||||
const valueChangeHandler: OnValueChange = (
|
||||
numberFormatValues,
|
||||
sourceInfo
|
||||
) => {
|
||||
const newChangeEvent = sourceInfo.event as
|
||||
| ChangeEvent<HTMLInputElement>
|
||||
| undefined;
|
||||
|
||||
if (newChangeEvent) {
|
||||
newChangeEvent.target.value = numberFormatValues.value;
|
||||
|
||||
onChange?.(newChangeEvent);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<NumericFormat
|
||||
thousandSeparator={thousandSeparator}
|
||||
decimalSeparator={decimalSeparator}
|
||||
customInput={TextInput}
|
||||
onValueChange={valueChangeHandler}
|
||||
decimalScale={decimalScale}
|
||||
allowNegative={allowNegative}
|
||||
inputPrefix={inputPrefix}
|
||||
inputSuffix={inputSuffix}
|
||||
{...restProps}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default NumberInput;
|
||||
@@ -0,0 +1,60 @@
|
||||
'use client';
|
||||
|
||||
import { ChangeEvent } from 'react';
|
||||
import { PatternFormat, OnValueChange } from 'react-number-format';
|
||||
import TextInput, { TextInputProps } from '@/components/input/TextInput';
|
||||
|
||||
interface PatternInputProps extends Omit<TextInputProps, 'type'> {
|
||||
type?: 'password' | 'tel' | 'text' | undefined;
|
||||
|
||||
/** Format pattern, e.g. "##/##/####", "(###) ###-####", "####-####-####" */
|
||||
format: string;
|
||||
|
||||
/** Mask character for empty slots, e.g. "_" */
|
||||
mask?: string;
|
||||
|
||||
/** Allow showing mask even when value is empty */
|
||||
allowEmptyFormatting?: boolean;
|
||||
|
||||
patternChar?: string;
|
||||
}
|
||||
|
||||
const PatternInput = ({
|
||||
type = 'text',
|
||||
format,
|
||||
mask = '_',
|
||||
allowEmptyFormatting = false,
|
||||
patternChar = '#',
|
||||
onChange,
|
||||
...restProps
|
||||
}: PatternInputProps) => {
|
||||
const valueChangeHandler: OnValueChange = (
|
||||
patternFormatValues,
|
||||
sourceInfo
|
||||
) => {
|
||||
const newChangeEvent = sourceInfo.event as
|
||||
| ChangeEvent<HTMLInputElement>
|
||||
| undefined;
|
||||
|
||||
if (newChangeEvent) {
|
||||
newChangeEvent.target.value = patternFormatValues.value;
|
||||
|
||||
onChange?.(newChangeEvent);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<PatternFormat
|
||||
type={type}
|
||||
format={format}
|
||||
mask={mask}
|
||||
allowEmptyFormatting={allowEmptyFormatting}
|
||||
patternChar={patternChar}
|
||||
customInput={TextInput}
|
||||
onValueChange={valueChangeHandler}
|
||||
{...restProps}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default PatternInput;
|
||||
@@ -1,12 +1,8 @@
|
||||
'use client';
|
||||
|
||||
import {
|
||||
ComponentType,
|
||||
ReactNode,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { ComponentType, ReactNode, useEffect, useMemo, useState } from 'react';
|
||||
import useSWR from 'swr';
|
||||
|
||||
import Select, {
|
||||
OptionProps,
|
||||
GroupBase,
|
||||
@@ -17,7 +13,10 @@ import Select, {
|
||||
import CreatableSelect from 'react-select/creatable';
|
||||
import makeAnimated from 'react-select/animated';
|
||||
import { useDebounce } from 'use-debounce';
|
||||
import { cn } from '@/lib/helper';
|
||||
import { cn, getByPath } from '@/lib/helper';
|
||||
import { httpClientFetcher } from '@/services/http/client';
|
||||
import { isResponseSuccess } from '@/lib/api-helper';
|
||||
import { BaseApiResponse } from '@/types/api/api-general';
|
||||
|
||||
export interface OptionType {
|
||||
value: string | number;
|
||||
@@ -54,6 +53,7 @@ interface SelectInputBaseProps<T = OptionType> {
|
||||
openMenu?: boolean;
|
||||
delay?: number;
|
||||
onInputChange?: (search: string) => void;
|
||||
startAdornment?: ReactNode;
|
||||
}
|
||||
|
||||
interface SelectInputProps<T = OptionType> extends SelectInputBaseProps<T> {
|
||||
@@ -88,6 +88,7 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
|
||||
delay = 300,
|
||||
createables = false,
|
||||
onInputChange,
|
||||
startAdornment,
|
||||
} = props;
|
||||
|
||||
const [internalInputValue, setInternalInputValue] = useState('');
|
||||
@@ -98,10 +99,7 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
|
||||
return { ...base, IndicatorSeparator: () => null };
|
||||
}, [isAnimated]);
|
||||
|
||||
const internalInputChangeHandler = (
|
||||
val: string,
|
||||
meta: InputActionMeta
|
||||
) => {
|
||||
const internalInputChangeHandler = (val: string, meta: InputActionMeta) => {
|
||||
if (meta.action === 'input-change') setInternalInputValue(val);
|
||||
if (meta.action === 'menu-close') setInternalInputValue('');
|
||||
};
|
||||
@@ -113,9 +111,7 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
|
||||
const SelectComponent = createables ? CreatableSelect : Select;
|
||||
|
||||
/** 🎯 handleChange tanpa any */
|
||||
const handleChange = (
|
||||
val: MultiValue<T> | SingleValue<T>
|
||||
): void => {
|
||||
const handleChange = (val: MultiValue<T> | SingleValue<T>): void => {
|
||||
if (!val) {
|
||||
onChange?.(null);
|
||||
return;
|
||||
@@ -145,17 +141,17 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
|
||||
>
|
||||
{label}
|
||||
{required && (
|
||||
<span className="tooltip tooltip-error" data-tip="required">
|
||||
<span className="text-error"> *</span>
|
||||
<span className='tooltip tooltip-error' data-tip='required'>
|
||||
<span className='text-error'> *</span>
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
|
||||
<SelectComponent<T, boolean, GroupBase<T>>
|
||||
instanceId="select"
|
||||
instanceId='select'
|
||||
value={value ?? (isMulti ? [] : null)}
|
||||
onChange={handleChange}
|
||||
onChange={onChange ? handleChange : undefined}
|
||||
options={options}
|
||||
menuIsOpen={openMenu}
|
||||
inputValue={internalInputValue}
|
||||
@@ -171,7 +167,7 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
|
||||
classNames={{
|
||||
control: ({ isFocused, isDisabled }) =>
|
||||
cn(
|
||||
'w-full min-h-12! rounded-lg! border bg-white transition-shadow cursor-pointer!',
|
||||
'w-full min-h-12! rounded border bg-white transition-shadow cursor-pointer!',
|
||||
{
|
||||
'border-red-500! ring-2 ring-red-200': isError,
|
||||
'border-indigo-500 ring-2 ring-indigo-200': isFocused,
|
||||
@@ -187,16 +183,16 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
|
||||
input: () => cn('text-gray-900'),
|
||||
indicatorsContainer: () => cn('flex items-center gap-1 pr-2'),
|
||||
dropdownIndicator: ({ isFocused }) =>
|
||||
cn('p-1 rounded-md hover:bg-gray-100', {
|
||||
cn('p-1 rounded hover:bg-gray-100', {
|
||||
'text-gray-900': isFocused,
|
||||
'text-gray-500': !isFocused,
|
||||
'text-error!': isError,
|
||||
}),
|
||||
menu: () =>
|
||||
cn('border border-gray-200 rounded-lg bg-white shadow-lg!'),
|
||||
cn('border border-gray-200 rounded! bg-base-100 shadow-lg!'),
|
||||
menuList: () => cn('p-2! max-h-60 overflow-auto'),
|
||||
option: ({ isFocused, isSelected }) =>
|
||||
cn('mt-1 px-3 py-2 rounded-md cursor-pointer!', {
|
||||
cn('mt-1 px-3 py-2 rounded cursor-pointer!', {
|
||||
'bg-indigo-600 text-white': isFocused,
|
||||
'bg-blue-500!': isSelected,
|
||||
'text-gray-700': !isFocused && !isSelected,
|
||||
@@ -204,7 +200,7 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
|
||||
multiValue: ({ getValue, index }) => {
|
||||
const selectedValues = getValue() as T[];
|
||||
return cn(
|
||||
'bg-indigo-50 rounded-md py-0.5 pl-2 pr-1 flex items-center gap-1!',
|
||||
'bg-indigo-50 rounded py-0.5 pl-2 pr-1 flex items-center gap-1!',
|
||||
selectedValues[index]?.className
|
||||
);
|
||||
},
|
||||
@@ -216,6 +212,28 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
|
||||
components={{
|
||||
...components,
|
||||
...(optionComponent ? { Option: optionComponent } : {}),
|
||||
...(startAdornment ? {
|
||||
Control: ({ children, innerRef, innerProps, menuIsOpen, isFocused, isDisabled }) => (
|
||||
<div
|
||||
ref={innerRef}
|
||||
{...innerProps}
|
||||
className={cn(
|
||||
'w-full min-h-12! rounded-lg! border bg-white transition-shadow cursor-pointer! flex items-center',
|
||||
{
|
||||
'border-red-500! ring-2 ring-red-200': isError,
|
||||
'border-indigo-500 ring-2 ring-indigo-200': isFocused,
|
||||
'border-gray-300': !isError && !isFocused,
|
||||
'bg-gray-100 text-gray-400 cursor-not-allowed': isDisabled,
|
||||
}
|
||||
)}
|
||||
>
|
||||
<div className='flex-1 px-4! gap-1 flex items-center'>
|
||||
{startAdornment}
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
} : {}),
|
||||
}}
|
||||
menuPortalTarget={
|
||||
typeof document !== 'undefined' ? document.body : undefined
|
||||
@@ -225,12 +243,53 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
|
||||
}}
|
||||
/>
|
||||
|
||||
{isError && <p className="w-full text-sm text-error">{errorMessage}</p>}
|
||||
{isError && <p className='w-full text-sm text-error'>{errorMessage}</p>}
|
||||
{!isError && bottomLabel && (
|
||||
<p className="w-full text-sm opacity-60">{bottomLabel}</p>
|
||||
<p className='w-full text-sm opacity-60'>{bottomLabel}</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const useSelect = <T,>(
|
||||
basePath: string,
|
||||
valueKey: keyof T,
|
||||
labelKey: keyof T,
|
||||
searchKey: string = 'search',
|
||||
params?: { [key: string]: string }
|
||||
) => {
|
||||
const [inputValue, setInputValue] = useState('');
|
||||
|
||||
const optionsUrlParams = useMemo(() => {
|
||||
return new URLSearchParams({
|
||||
[searchKey]: inputValue ?? '',
|
||||
...params,
|
||||
}).toString();
|
||||
}, [inputValue, searchKey]);
|
||||
|
||||
const optionsUrl = `${basePath}?${optionsUrlParams}`;
|
||||
|
||||
const { data, isLoading } = useSWR(optionsUrl, async (url) => {
|
||||
return await httpClientFetcher<BaseApiResponse<T[]>>(url);
|
||||
});
|
||||
|
||||
const options = isResponseSuccess(data)
|
||||
? data.data.map((item) => {
|
||||
return {
|
||||
value: getByPath<T, number>(item, valueKey as string),
|
||||
label: getByPath<T, string>(item, labelKey as string),
|
||||
};
|
||||
})
|
||||
: [];
|
||||
|
||||
return {
|
||||
inputValue,
|
||||
setInputValue,
|
||||
options,
|
||||
isLoadingOptions: isLoading,
|
||||
rawData: data,
|
||||
};
|
||||
};
|
||||
|
||||
export { useSelect };
|
||||
export default SelectInput;
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import {
|
||||
ChangeEventHandler,
|
||||
FocusEventHandler,
|
||||
ReactNode,
|
||||
} from 'react';
|
||||
import { ChangeEventHandler, FocusEventHandler, ReactNode } from 'react';
|
||||
|
||||
import { cn } from '@/lib/helper';
|
||||
|
||||
@@ -52,7 +48,7 @@ const TextArea = ({
|
||||
onBlur,
|
||||
readOnly = false,
|
||||
isLoading = false,
|
||||
rows = 3
|
||||
rows = 3,
|
||||
}: TextAreaProps) => {
|
||||
return (
|
||||
<div
|
||||
@@ -83,35 +79,35 @@ const TextArea = ({
|
||||
)}
|
||||
</label>
|
||||
)}
|
||||
{startAdornment && startAdornment}
|
||||
{startAdornment && startAdornment}
|
||||
|
||||
<textarea
|
||||
className={cn(
|
||||
'input h-auto px-4 py-2 text-base font-normal leading-6 w-full rounded-lg! outline-none! transition-all',
|
||||
{
|
||||
'border-error': isError,
|
||||
'border-success!': isValid,
|
||||
},
|
||||
className?.inputWrapper
|
||||
)}
|
||||
id={name}
|
||||
name={name}
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
rows={rows}
|
||||
onChange={onChange}
|
||||
onBlur={onBlur}
|
||||
disabled={disabled}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
|
||||
{(isLoading || endAdornment) && (
|
||||
<div className='flex flex-row gap-2'>
|
||||
{isLoading && <span className='loading loading-spinner' />}
|
||||
|
||||
{endAdornment && endAdornment}
|
||||
</div>
|
||||
<textarea
|
||||
className={cn(
|
||||
'input h-auto px-4 py-2 text-base font-normal leading-6 w-full rounded outline-none! transition-all bg-white',
|
||||
{
|
||||
'border-error': isError,
|
||||
'border-success!': isValid,
|
||||
},
|
||||
className?.inputWrapper
|
||||
)}
|
||||
id={name}
|
||||
name={name}
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
rows={rows}
|
||||
onChange={onChange}
|
||||
onBlur={onBlur}
|
||||
disabled={disabled}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
|
||||
{(isLoading || endAdornment) && (
|
||||
<div className='flex flex-row gap-2'>
|
||||
{isLoading && <span className='loading loading-spinner' />}
|
||||
|
||||
{endAdornment && endAdornment}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isError && bottomLabel && (
|
||||
<p className='w-full text-sm opacity-60'>{bottomLabel}</p>
|
||||
|
||||
@@ -31,6 +31,8 @@ export interface TextInputProps {
|
||||
errorMessage?: string;
|
||||
startAdornment?: ReactNode;
|
||||
endAdornment?: ReactNode;
|
||||
inputPrefix?: ReactNode;
|
||||
inputSuffix?: ReactNode;
|
||||
onChange?: ChangeEventHandler<HTMLInputElement>;
|
||||
onBlur?: FocusEventHandler<HTMLInputElement>;
|
||||
}
|
||||
@@ -48,6 +50,8 @@ const TextInput = ({
|
||||
errorMessage,
|
||||
startAdornment,
|
||||
endAdornment,
|
||||
inputPrefix,
|
||||
inputSuffix,
|
||||
disabled = false,
|
||||
required = false,
|
||||
onChange,
|
||||
@@ -85,39 +89,117 @@ const TextInput = ({
|
||||
</label>
|
||||
)}
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'input h-12 px-4 py-2 text-base font-normal leading-6 w-full rounded-lg! outline-none! transition-all duration-200',
|
||||
{
|
||||
'border-error': isError,
|
||||
'border-success!': isValid,
|
||||
},
|
||||
className?.inputWrapper
|
||||
)}
|
||||
>
|
||||
{startAdornment && startAdornment}
|
||||
{inputPrefix || inputSuffix ? (
|
||||
<div className='relative flex'>
|
||||
{inputPrefix && (
|
||||
<div
|
||||
className={cn(
|
||||
'inline-flex items-center px-4 py-2 border border-r-0 rounded-l-md transition-all duration-200',
|
||||
{
|
||||
'bg-gray-100 border-gray-300': !disabled,
|
||||
'bg-gray-50 border-gray-200': disabled,
|
||||
}
|
||||
)}
|
||||
>
|
||||
{inputPrefix}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<input
|
||||
type={type}
|
||||
id={name}
|
||||
name={name}
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
onBlur={onBlur}
|
||||
disabled={disabled}
|
||||
className={cn('grow', className?.input)}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
'input h-12 text-base font-normal leading-6 flex-1 rounded-lg! outline-none! transition-all duration-200 flex items-center bg-white',
|
||||
{
|
||||
'border-error': isError,
|
||||
'border-success!': isValid,
|
||||
'rounded-l-none!': inputPrefix,
|
||||
'rounded-r-none!': inputSuffix,
|
||||
'input-disabled': disabled,
|
||||
'cursor-not-allowed': disabled,
|
||||
'bg-gray-50': disabled,
|
||||
},
|
||||
className?.inputWrapper
|
||||
)}
|
||||
>
|
||||
{startAdornment && startAdornment}
|
||||
|
||||
{(isLoading || endAdornment) && (
|
||||
<div className='flex flex-row gap-2'>
|
||||
{isLoading && <span className='loading loading-spinner' />}
|
||||
<input
|
||||
type={type}
|
||||
id={name}
|
||||
name={name}
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
onBlur={onBlur}
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
'grow bg-transparent outline-none',
|
||||
{
|
||||
'cursor-not-allowed': disabled,
|
||||
'text-gray-500': disabled,
|
||||
},
|
||||
className?.input
|
||||
)}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
|
||||
{endAdornment && endAdornment}
|
||||
{(isLoading || endAdornment) && (
|
||||
<div className='flex flex-row gap-2'>
|
||||
{isLoading && <span className='loading loading-spinner' />}
|
||||
|
||||
{endAdornment && endAdornment}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{inputSuffix && (
|
||||
<div
|
||||
className={cn(
|
||||
'inline-flex items-center px-4 py-2 border border-l-0 rounded-r-md transition-all duration-200',
|
||||
{
|
||||
'bg-gray-100 border-gray-300': !disabled,
|
||||
'bg-gray-50 border-gray-200': disabled,
|
||||
}
|
||||
)}
|
||||
>
|
||||
{inputSuffix}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className={cn(
|
||||
'input h-12 px-4 py-2 text-base font-normal leading-6 w-full rounded-lg! outline-none! transition-all duration-200 bg-white',
|
||||
{
|
||||
'border-error': isError,
|
||||
'border-success!': isValid,
|
||||
},
|
||||
className?.inputWrapper
|
||||
)}
|
||||
>
|
||||
{startAdornment && startAdornment}
|
||||
|
||||
<input
|
||||
type={type}
|
||||
id={name}
|
||||
name={name}
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
onBlur={onBlur}
|
||||
disabled={disabled}
|
||||
className={cn('grow', className?.input)}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
|
||||
{(isLoading || endAdornment) && (
|
||||
<div className='flex flex-row gap-2'>
|
||||
{isLoading && <span className='loading loading-spinner' />}
|
||||
|
||||
{endAdornment && endAdornment}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isError && bottomLabel && (
|
||||
<p className='w-full text-sm opacity-60'>{bottomLabel}</p>
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { Icon } from '@iconify/react';
|
||||
import Steps from '@/components/steps/Steps';
|
||||
import StepItem from '@/components/steps/StepItem';
|
||||
import Tooltip from '@/components/Tooltip';
|
||||
|
||||
import { formatDate } from '@/lib/helper';
|
||||
import { ApprovalsLine } from '@/types/api/api-general';
|
||||
|
||||
interface ApprovalStepsProps {
|
||||
approvals: ApprovalsLine;
|
||||
}
|
||||
|
||||
const ApprovalSteps = ({ approvals }: ApprovalStepsProps) => {
|
||||
return (
|
||||
<Steps direction='vertical' className='w-full md:steps-horizontal'>
|
||||
{approvals.map((approval, idx) => {
|
||||
const stepItemColor =
|
||||
approval.status === 'approved'
|
||||
? 'success'
|
||||
: approval.status === 'rejected'
|
||||
? 'error'
|
||||
: undefined;
|
||||
|
||||
const stepItemIcon =
|
||||
approval.status === 'approved'
|
||||
? 'material-symbols:check-rounded'
|
||||
: approval.status === 'rejected'
|
||||
? 'material-symbols:close-rounded'
|
||||
: 'bxs:hourglass';
|
||||
|
||||
return (
|
||||
<StepItem
|
||||
key={idx}
|
||||
color={stepItemColor}
|
||||
icon={
|
||||
approval.status !== 'waiting' && (
|
||||
<Tooltip
|
||||
color={stepItemColor}
|
||||
position='right'
|
||||
className={{
|
||||
wrapper: 'md:tooltip-bottom',
|
||||
}}
|
||||
content={
|
||||
<div className='flex flex-col text-base'>
|
||||
<span>{formatDate(approval.date, 'YYYY-MM-DD')}</span>
|
||||
<span>Oleh: {approval.action_by}</span>
|
||||
<span>Catatan: {approval.notes}</span>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Icon icon={stepItemIcon} width={24} height={24} />
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
>
|
||||
{approval.role}
|
||||
</StepItem>
|
||||
);
|
||||
})}
|
||||
</Steps>
|
||||
);
|
||||
};
|
||||
|
||||
export default ApprovalSteps;
|
||||
@@ -13,7 +13,7 @@ import toast from 'react-hot-toast';
|
||||
import {
|
||||
InventoryAdjustmentFormSchema,
|
||||
InventoryAdjustmentFormValues,
|
||||
} from './InventoryAdjustmentForm.schema';
|
||||
} from '@/components/pages/inventory/adjustment/form/InventoryAdjustmentForm.schema';
|
||||
import useSWR from 'swr';
|
||||
import {
|
||||
ProductApi,
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import useSWR from 'swr';
|
||||
import { SortingState } from '@tanstack/react-table';
|
||||
|
||||
import Table from '@/components/Table';
|
||||
import { useModal } from '@/components/Modal';
|
||||
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||
import { Movement } from '@/types/api/inventory/movement';
|
||||
import { MovementApi } from '@/services/api/inventory';
|
||||
import { cn } from '@/lib/helper';
|
||||
import { isResponseSuccess } from '@/lib/api-helper';
|
||||
import { useTableFilter } from '@/services/hooks/useTableFilter';
|
||||
import { ROWS_OPTIONS } from '@/config/constant';
|
||||
import { TableToolbar } from '@/components/table/TableToolbar';
|
||||
import { TableRowSizeSelector } from '@/components/table/TableRowSizeSelector';
|
||||
import { OptionType } from '@/components/input/SelectInput';
|
||||
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
|
||||
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
|
||||
import { TableRowOptions } from '@/components/table/TableRowOptions';
|
||||
|
||||
const MovementTable = () => {
|
||||
const {
|
||||
state: tableFilterState,
|
||||
updateFilter,
|
||||
setPage,
|
||||
setPageSize,
|
||||
toQueryString: getTableFilterQueryString,
|
||||
} = useTableFilter({
|
||||
initial: { search: '' },
|
||||
paramMap: { page: 'page', pageSize: 'limit' },
|
||||
});
|
||||
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
const [selectedMovement, setSelectedMovement] = useState<
|
||||
Movement | undefined
|
||||
>(undefined);
|
||||
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||
|
||||
const deleteModal = useModal();
|
||||
|
||||
const {
|
||||
data: movements,
|
||||
isLoading,
|
||||
mutate: refreshMovements,
|
||||
} = useSWR(
|
||||
`${MovementApi.basePath}${getTableFilterQueryString()}`,
|
||||
MovementApi.getAllFetcher
|
||||
);
|
||||
|
||||
const searchChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
updateFilter('search', e.target.value);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||
const newVal = val as OptionType;
|
||||
setPageSize(newVal.value as number);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const confirmationModalDeleteClickHandler = async () => {
|
||||
setIsDeleteLoading(true);
|
||||
try {
|
||||
await MovementApi.delete(selectedMovement?.id as number);
|
||||
refreshMovements();
|
||||
deleteModal.closeModal();
|
||||
} finally {
|
||||
setIsDeleteLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className='flex flex-col gap-4'>
|
||||
<div className='flex flex-col gap-2 mb-4'>
|
||||
<TableToolbar
|
||||
addButton={{
|
||||
href: '/inventory/movement/add',
|
||||
label: 'Tambah Movement',
|
||||
}}
|
||||
search={{
|
||||
value: tableFilterState.search,
|
||||
onChange: searchChangeHandler,
|
||||
placeholder: 'Cari Movement',
|
||||
}}
|
||||
/>
|
||||
<TableRowSizeSelector
|
||||
value={tableFilterState.pageSize}
|
||||
onChange={pageSizeChangeHandler}
|
||||
options={ROWS_OPTIONS}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Table<Movement>
|
||||
data={isResponseSuccess(movements) ? movements?.data : []}
|
||||
columns={[
|
||||
{
|
||||
header: '#',
|
||||
cell: (props) =>
|
||||
tableFilterState.pageSize * (tableFilterState.page - 1) +
|
||||
props.row.index +
|
||||
1,
|
||||
},
|
||||
{
|
||||
accessorFn: (row) => row.source_warehouse?.name,
|
||||
header: 'Gudang Asal',
|
||||
},
|
||||
{
|
||||
accessorFn: (row) => row.destination_warehouse?.name,
|
||||
header: 'Gudang Tujuan',
|
||||
},
|
||||
{
|
||||
accessorKey: 'transfer_reason',
|
||||
header: 'Catatan',
|
||||
},
|
||||
{
|
||||
accessorKey: 'transfer_date',
|
||||
header: 'Tanggal',
|
||||
cell: (props) =>
|
||||
new Date(props.row.original.transfer_date).toLocaleDateString(
|
||||
'id-ID'
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorFn: (row) => {
|
||||
const totalCost = row.deliveries?.reduce(
|
||||
(sum, d) => sum + (d.shipping_cost_total || 0),
|
||||
0
|
||||
);
|
||||
return totalCost?.toLocaleString('id-ID');
|
||||
},
|
||||
header: 'Biaya Pengiriman',
|
||||
},
|
||||
{
|
||||
header: 'Aksi',
|
||||
cell: (props) => {
|
||||
const currentPageSize =
|
||||
props.table.getPaginationRowModel().rows.length;
|
||||
const currentPageRows =
|
||||
props.table.getPaginationRowModel().flatRows;
|
||||
const currentRowRelativeIndex =
|
||||
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
|
||||
|
||||
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
|
||||
|
||||
const deleteClickHandler = () => {
|
||||
setSelectedMovement(props.row.original);
|
||||
deleteModal.openModal();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{currentPageSize > 2 && (
|
||||
<RowDropdownOptions isLast2Rows={isLast2Rows}>
|
||||
<TableRowOptions
|
||||
type='dropdown'
|
||||
recordId={props.row.original.id}
|
||||
basePath='/inventory/movement'
|
||||
queryParam='movementId'
|
||||
showEdit={false}
|
||||
showDelete={false}
|
||||
/>
|
||||
</RowDropdownOptions>
|
||||
)}
|
||||
|
||||
{currentPageSize <= 2 && (
|
||||
<RowCollapseOptions>
|
||||
<TableRowOptions
|
||||
type='collapse'
|
||||
recordId={props.row.original.id}
|
||||
basePath='/inventory/movement'
|
||||
queryParam='movementId'
|
||||
showEdit={false}
|
||||
showDelete={false}
|
||||
/>
|
||||
</RowCollapseOptions>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
},
|
||||
},
|
||||
]}
|
||||
pageSize={tableFilterState.pageSize}
|
||||
page={isResponseSuccess(movements) ? movements?.meta?.page : 0}
|
||||
totalItems={
|
||||
isResponseSuccess(movements) ? movements?.meta?.total_results : 0
|
||||
}
|
||||
onPageChange={setPage}
|
||||
isLoading={isLoading}
|
||||
sorting={sorting}
|
||||
setSorting={setSorting}
|
||||
className={{
|
||||
containerClassName: cn({
|
||||
'mb-20':
|
||||
isResponseSuccess(movements) && movements?.data?.length === 0,
|
||||
}),
|
||||
tableWrapperClassName: 'overflow-x-auto min-h-full!',
|
||||
tableClassName: 'font-inter w-full table-auto min-h-full!',
|
||||
headerRowClassName: 'border-b border-b-gray-200',
|
||||
headerColumnClassName:
|
||||
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
|
||||
bodyRowClassName: 'border-b border-b-gray-200',
|
||||
bodyColumnClassName:
|
||||
'px-6 py-3 last:flex last:flex-row last:justify-end',
|
||||
}}
|
||||
/>
|
||||
|
||||
<ConfirmationModal
|
||||
ref={deleteModal.ref}
|
||||
type='error'
|
||||
text={`Apakah anda yakin ingin menghapus data Movement ini?`}
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: 'error',
|
||||
isLoading: isDeleteLoading,
|
||||
onClick: confirmationModalDeleteClickHandler,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default MovementTable;
|
||||
@@ -0,0 +1,210 @@
|
||||
import * as Yup from 'yup';
|
||||
import { Movement } from '@/types/api/inventory/movement';
|
||||
|
||||
export type ProductSchema = {
|
||||
product: {
|
||||
value: number;
|
||||
label: string;
|
||||
} | null;
|
||||
product_id: number;
|
||||
product_qty: number;
|
||||
};
|
||||
|
||||
export type DeliverySchema = {
|
||||
delivery_cost?: number | undefined;
|
||||
delivery_cost_per_item?: number | undefined;
|
||||
document?: File | string | null;
|
||||
document_path?: string | null;
|
||||
driver_name: string;
|
||||
vehicle_plate: string;
|
||||
supplier: {
|
||||
value: number;
|
||||
label: string;
|
||||
} | null;
|
||||
supplier_id: number;
|
||||
products: {
|
||||
product: {
|
||||
value: number;
|
||||
label: string;
|
||||
} | null;
|
||||
product_id: number;
|
||||
product_qty: number;
|
||||
}[];
|
||||
};
|
||||
|
||||
const ProductObjectSchema: Yup.ObjectSchema<ProductSchema> = Yup.object({
|
||||
product: Yup.object({
|
||||
value: Yup.number().min(1).required(),
|
||||
label: Yup.string().required(),
|
||||
}).nullable(),
|
||||
product_id: Yup.number().required('Produk wajib diisi!'),
|
||||
product_qty: Yup.number()
|
||||
.required('Qty wajib diisi!')
|
||||
.min(1, 'Qty minimal 1!')
|
||||
.typeError('Qty harus berupa angka!'),
|
||||
});
|
||||
|
||||
const DeliveryProductObjectSchema = Yup.object({
|
||||
product: Yup.object({
|
||||
value: Yup.number().min(1).required(),
|
||||
label: Yup.string().required(),
|
||||
}).nullable(),
|
||||
product_id: Yup.number().required('Produk wajib diisi!'),
|
||||
product_qty: Yup.number()
|
||||
.required('Qty wajib diisi!')
|
||||
.min(1, 'Qty minimal 1!')
|
||||
.typeError('Qty harus berupa angka!'),
|
||||
});
|
||||
|
||||
const DeliveryObjectSchema: Yup.ObjectSchema<DeliverySchema> = Yup.object({
|
||||
delivery_cost: Yup.number()
|
||||
.transform((value) => (isNaN(value) || value === 0 ? undefined : value))
|
||||
.min(1, 'Biaya minimal 1!')
|
||||
.typeError('Biaya harus berupa angka!')
|
||||
.test('one-of-cost-fields', 'Wajib diisi salah satu!', function (value) {
|
||||
const { delivery_cost_per_item } = this.parent;
|
||||
return (
|
||||
(value !== undefined && value > 0) ||
|
||||
(delivery_cost_per_item !== undefined && delivery_cost_per_item > 0)
|
||||
);
|
||||
}),
|
||||
delivery_cost_per_item: Yup.number()
|
||||
.transform((value) => (isNaN(value) || value === 0 ? undefined : value))
|
||||
.min(1, 'Biaya per item minimal 1!')
|
||||
.typeError('Biaya per item harus berupa angka!')
|
||||
.test('one-of-cost-fields', 'Wajib diisi salah satu!', function (value) {
|
||||
const { delivery_cost } = this.parent;
|
||||
return (
|
||||
(value !== undefined && value > 0) ||
|
||||
(delivery_cost !== undefined && delivery_cost > 0)
|
||||
);
|
||||
}),
|
||||
document_path: Yup.string().optional(),
|
||||
document_index: Yup.number().optional(),
|
||||
document: Yup.mixed<File | string>()
|
||||
.nullable()
|
||||
.test('fileSize', 'Ukuran dokumen maksimal 2 MB', (value) => {
|
||||
if (!value) return true;
|
||||
if (typeof value === 'string') return true;
|
||||
if (value instanceof File) return value.size <= 2 * 1024 * 1024;
|
||||
return false;
|
||||
}),
|
||||
driver_name: Yup.string().required('Nama sopir wajib diisi!'),
|
||||
vehicle_plate: Yup.string().required('Plat nomor wajib diisi!'),
|
||||
supplier: Yup.object({
|
||||
value: Yup.number().min(1).required(),
|
||||
label: Yup.string().required(),
|
||||
}).nullable(),
|
||||
supplier_id: Yup.number().required('Supplier wajib diisi!'),
|
||||
products: Yup.array()
|
||||
.of(DeliveryProductObjectSchema)
|
||||
.min(1, 'Minimal harus ada 1 produk!')
|
||||
.required('Produk wajib diisi!'),
|
||||
});
|
||||
|
||||
export const MovementFormSchema = Yup.object({
|
||||
transfer_reason: Yup.string().required('Alasan transfer wajib diisi!'),
|
||||
transfer_date: Yup.string().required('Tanggal transfer wajib diisi!'),
|
||||
source_warehouse: Yup.object({
|
||||
value: Yup.number().min(1).required(),
|
||||
label: Yup.string().required(),
|
||||
area: Yup.string().optional(),
|
||||
location: Yup.string().optional(),
|
||||
}).nullable(),
|
||||
source_warehouse_id: Yup.number()
|
||||
.required('Gudang asal wajib diisi!')
|
||||
.typeError('Gudang asal wajib diisi!'),
|
||||
destination_warehouse: Yup.object({
|
||||
value: Yup.number().min(1).required(),
|
||||
label: Yup.string().required(),
|
||||
area: Yup.string().optional(),
|
||||
location: Yup.string().optional(),
|
||||
}).nullable(),
|
||||
destination_warehouse_id: Yup.number()
|
||||
.required('Gudang tujuan wajib diisi!')
|
||||
.typeError('Gudang tujuan wajib diisi!'),
|
||||
products: Yup.array()
|
||||
.of(ProductObjectSchema)
|
||||
.min(1, 'Minimal harus ada 1 produk!')
|
||||
.required('Produk wajib diisi!'),
|
||||
deliveries: Yup.array()
|
||||
.of(DeliveryObjectSchema)
|
||||
.min(1, 'Minimal harus ada 1 pengiriman!')
|
||||
.required('Pengiriman wajib diisi!'),
|
||||
});
|
||||
|
||||
export const UpdateMovementFormSchema = MovementFormSchema;
|
||||
|
||||
export type MovementFormValues = Yup.InferType<typeof MovementFormSchema>;
|
||||
|
||||
export const getMovementFormInitialValues = (
|
||||
initialValues?: Movement
|
||||
): MovementFormValues => {
|
||||
const detailIdToProductId = new Map<number, { id: number; name: string }>();
|
||||
initialValues?.details?.forEach((detail) => {
|
||||
detailIdToProductId.set(detail.id, {
|
||||
id: detail.product.id,
|
||||
name: detail.product.name,
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
transfer_reason: initialValues?.transfer_reason ?? '',
|
||||
transfer_date: initialValues?.transfer_date ?? '',
|
||||
source_warehouse: initialValues?.source_warehouse
|
||||
? {
|
||||
value: initialValues.source_warehouse.id,
|
||||
label: initialValues.source_warehouse.name,
|
||||
area: initialValues.source_warehouse.area?.name ?? undefined,
|
||||
location: initialValues.source_warehouse.location?.name ?? undefined,
|
||||
}
|
||||
: null,
|
||||
source_warehouse_id: initialValues?.source_warehouse?.id ?? 0,
|
||||
destination_warehouse: initialValues?.destination_warehouse
|
||||
? {
|
||||
value: initialValues.destination_warehouse.id,
|
||||
label: initialValues.destination_warehouse.name,
|
||||
area: initialValues.destination_warehouse.area?.name ?? undefined,
|
||||
location:
|
||||
initialValues.destination_warehouse.location?.name ?? undefined,
|
||||
}
|
||||
: null,
|
||||
destination_warehouse_id: initialValues?.destination_warehouse?.id ?? 0,
|
||||
products:
|
||||
initialValues?.details?.map((detail) => ({
|
||||
product: {
|
||||
value: detail.product.id,
|
||||
label: detail.product.name,
|
||||
},
|
||||
product_id: detail.product.id,
|
||||
product_qty: detail.quantity,
|
||||
})) ?? [],
|
||||
deliveries:
|
||||
initialValues?.deliveries?.map((d) => ({
|
||||
delivery_cost: d.shipping_cost_total ?? undefined,
|
||||
delivery_cost_per_item: d.shipping_cost_item ?? undefined,
|
||||
document_number: d.document_number ?? '',
|
||||
document: d.document_path ?? null,
|
||||
document_path: d.document_path ?? null,
|
||||
driver_name: d.driver_name ?? '',
|
||||
vehicle_plate: d.vehicle_plate ?? '',
|
||||
supplier: d.supplier
|
||||
? { value: d.supplier.id, label: d.supplier.name }
|
||||
: null,
|
||||
supplier_id: d.supplier?.id ?? 0,
|
||||
products:
|
||||
d.items?.map((item) => {
|
||||
const productData = detailIdToProductId.get(
|
||||
item.stock_transfer_detail_id
|
||||
);
|
||||
return {
|
||||
product: productData
|
||||
? { value: productData.id, label: productData.name }
|
||||
: null,
|
||||
product_id: productData?.id ?? 0,
|
||||
product_qty: item.quantity,
|
||||
};
|
||||
}) ?? [],
|
||||
})) ?? [],
|
||||
};
|
||||
};
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,95 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { useModal } from '@/components/Modal';
|
||||
import { MovementApi } from '@/services/api/inventory';
|
||||
import {
|
||||
CreateMovementPayload,
|
||||
UpdateMovementPayload,
|
||||
} from '@/types/api/inventory/movement';
|
||||
import { isResponseError } from '@/lib/api-helper';
|
||||
|
||||
export const useMovementFormHandlers = (initialValuesId?: number) => {
|
||||
const router = useRouter();
|
||||
const deleteModal = useModal();
|
||||
const [movementFormErrorMessage, setMovementFormErrorMessage] = useState('');
|
||||
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||
|
||||
const createMovementHandler = useCallback(
|
||||
async (payload: CreateMovementPayload, documents: File[] = []) => {
|
||||
const formData = new FormData();
|
||||
formData.append('data', JSON.stringify(payload));
|
||||
documents.forEach((file, index) => {
|
||||
formData.append(`documents[${index}]`, file);
|
||||
});
|
||||
|
||||
const res = await MovementApi.create(
|
||||
formData as unknown as CreateMovementPayload
|
||||
);
|
||||
if (isResponseError(res)) {
|
||||
setMovementFormErrorMessage(res.message);
|
||||
return;
|
||||
}
|
||||
toast.success(res?.message as string);
|
||||
router.push('/inventory/movement');
|
||||
},
|
||||
[router]
|
||||
);
|
||||
|
||||
const updateMovementHandler = useCallback(
|
||||
async (
|
||||
movementId: number,
|
||||
payload: UpdateMovementPayload,
|
||||
documents: File[] = []
|
||||
) => {
|
||||
let finalPayload: UpdateMovementPayload | FormData;
|
||||
|
||||
if (documents.length > 0) {
|
||||
const formData = new FormData();
|
||||
formData.append('data', JSON.stringify(payload));
|
||||
documents.forEach((file, index) => {
|
||||
formData.append(`documents[${index}]`, file);
|
||||
});
|
||||
|
||||
finalPayload = formData as unknown as UpdateMovementPayload;
|
||||
} else {
|
||||
finalPayload = payload;
|
||||
}
|
||||
|
||||
const res = await MovementApi.update(movementId, finalPayload);
|
||||
if (res?.status === 'error') {
|
||||
setMovementFormErrorMessage(res.message);
|
||||
return;
|
||||
}
|
||||
toast.success(res?.message as string);
|
||||
router.refresh();
|
||||
router.push('/inventory/movement');
|
||||
},
|
||||
[router]
|
||||
);
|
||||
|
||||
const deleteMovementClickHandler = useCallback(() => {
|
||||
deleteModal.openModal();
|
||||
}, [deleteModal]);
|
||||
|
||||
const confirmationModalDeleteClickHandler = useCallback(async () => {
|
||||
if (!initialValuesId) return;
|
||||
|
||||
setIsDeleteLoading(true);
|
||||
await MovementApi.delete(initialValuesId);
|
||||
deleteModal.closeModal();
|
||||
toast.success('Successfully delete Movement!');
|
||||
setIsDeleteLoading(false);
|
||||
router.push('/inventory/movement');
|
||||
}, [deleteModal, initialValuesId, router]);
|
||||
|
||||
return {
|
||||
deleteModal,
|
||||
movementFormErrorMessage,
|
||||
isDeleteLoading,
|
||||
createMovementHandler,
|
||||
updateMovementHandler,
|
||||
deleteMovementClickHandler,
|
||||
confirmationModalDeleteClickHandler,
|
||||
};
|
||||
};
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import { CustomerFormSchema, CustomerFormValues, UpdateCustomerFormSchema } from './CustomerForm.schema';
|
||||
import { CustomerFormSchema, CustomerFormValues, UpdateCustomerFormSchema } from '@/components/pages/master-data/customer/form/CustomerForm.schema';
|
||||
import { useFormik } from 'formik';
|
||||
import Button from '@/components/Button';
|
||||
import { Icon } from '@iconify/react';
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
'use client';
|
||||
|
||||
import { CellContext, ColumnDef } from '@tanstack/react-table';
|
||||
import { Flock } from '@/types/api/master-data/flock';
|
||||
import { cn } from '@/lib/helper';
|
||||
import Button from '@/components/Button';
|
||||
import { Icon } from '@iconify/react';
|
||||
import { useTableFilter } from '@/services/hooks/useTableFilter';
|
||||
import { useState } from 'react';
|
||||
import useSWR from 'swr';
|
||||
import { FlockApi } from '@/services/api/master-data';
|
||||
import { useModal } from '@/components/Modal';
|
||||
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
|
||||
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
|
||||
import toast from 'react-hot-toast';
|
||||
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
|
||||
import SelectInput, { OptionType } from '@/components/input/SelectInput';
|
||||
import { ROWS_OPTIONS } from '@/config/constant';
|
||||
import Table from '@/components/Table';
|
||||
import { isResponseSuccess } from '@/lib/api-helper';
|
||||
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||
|
||||
const RowsOptions = ({
|
||||
type = 'dropdown',
|
||||
props,
|
||||
deleteClickHandler,
|
||||
}: {
|
||||
type: 'dropdown' | 'collapse';
|
||||
props: CellContext<Flock, 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 flex flex-col gap-1 bg-base-100 rounded-box z-10 border border-black/10 shadow'
|
||||
)}
|
||||
>
|
||||
<Button
|
||||
href={`/master-data/flock/detail/edit/?flockId=${props.row.original.id}`}
|
||||
variant='ghost'
|
||||
color='warning'
|
||||
className='justify-start text-sm'
|
||||
>
|
||||
<Icon
|
||||
icon='material-symbols:edit-outline'
|
||||
width={16}
|
||||
height={16}
|
||||
className='justify-start text-sm'
|
||||
/>
|
||||
Edit
|
||||
</Button>
|
||||
<Button
|
||||
href={`/master-data/flock/detail/?flockId=${props.row.original.id}`}
|
||||
variant='ghost'
|
||||
color='primary'
|
||||
className='justify-start text-sm'
|
||||
>
|
||||
<Icon
|
||||
icon='mdi:eye-outline'
|
||||
width={16}
|
||||
height={16}
|
||||
className='justify-start text-sm'
|
||||
/>
|
||||
Detail
|
||||
</Button>
|
||||
<Button
|
||||
onClick={deleteClickHandler}
|
||||
variant='ghost'
|
||||
color='error'
|
||||
className='text-error hover:text-inherit'
|
||||
>
|
||||
<Icon
|
||||
icon='material-symbols:delete-outline-rounded'
|
||||
width={16}
|
||||
height={16}
|
||||
className='justify-start text-sm'
|
||||
/>
|
||||
Delete
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const FlockTable = () => {
|
||||
const {
|
||||
state: tableFilterState,
|
||||
updateFilter,
|
||||
setPage,
|
||||
setPageSize,
|
||||
toQueryString: getTableFilterQueryString,
|
||||
} = useTableFilter({
|
||||
initial: { search: '', nameSort: '' },
|
||||
paramMap: {
|
||||
page: 'page',
|
||||
pageSize: 'limit',
|
||||
nameSort: 'sort_name',
|
||||
},
|
||||
});
|
||||
|
||||
// Fetch Data
|
||||
const {
|
||||
data: flocks,
|
||||
isLoading,
|
||||
mutate: refreshFlocks,
|
||||
} = useSWR(
|
||||
`${FlockApi.basePath}${getTableFilterQueryString()}`,
|
||||
FlockApi.getAllFetcher
|
||||
);
|
||||
|
||||
// State
|
||||
const deleteModal = useModal();
|
||||
const [selectedFlock, setSelectedFlock] = useState<Flock | undefined>(
|
||||
undefined
|
||||
);
|
||||
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||
|
||||
// Columns Definition
|
||||
const flocksColumns: ColumnDef<Flock>[] = [
|
||||
{
|
||||
header: '#',
|
||||
cell: (props) =>
|
||||
tableFilterState.pageSize * (tableFilterState.page - 1) +
|
||||
props.row.index +
|
||||
1,
|
||||
},
|
||||
{
|
||||
accessorKey: 'name',
|
||||
header: 'Nama',
|
||||
},
|
||||
{
|
||||
accessorKey: 'created_at',
|
||||
header: 'Dibuat pada',
|
||||
cell: (props) =>
|
||||
new Date(props.row.original.created_at).toLocaleDateString(),
|
||||
},
|
||||
{
|
||||
header: 'Aksi',
|
||||
cell: (props) => {
|
||||
const currentPageSize = props.table.getPaginationRowModel().rows.length;
|
||||
const currentPageRows = props.table.getPaginationRowModel().flatRows;
|
||||
const currentRowRelativeIndex =
|
||||
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
|
||||
|
||||
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
|
||||
|
||||
const deleteClickHandler = () => {
|
||||
setSelectedFlock(props.row.original);
|
||||
deleteModal.openModal();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{currentPageSize > 2 && (
|
||||
<RowDropdownOptions isLast2Rows={isLast2Rows}>
|
||||
<RowsOptions
|
||||
type='dropdown'
|
||||
props={props}
|
||||
deleteClickHandler={deleteClickHandler}
|
||||
/>
|
||||
</RowDropdownOptions>
|
||||
)}
|
||||
{currentPageSize <= 2 && (
|
||||
<RowCollapseOptions>
|
||||
<RowsOptions
|
||||
type='collapse'
|
||||
props={props}
|
||||
deleteClickHandler={deleteClickHandler}
|
||||
/>
|
||||
</RowCollapseOptions>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
// Handler
|
||||
const confirmationModalDeleteClickHandler = async () => {
|
||||
setIsDeleteLoading(true);
|
||||
|
||||
await FlockApi.delete(selectedFlock?.id as number);
|
||||
refreshFlocks();
|
||||
|
||||
deleteModal.closeModal();
|
||||
toast.success('Successfully delete Flock!');
|
||||
setIsDeleteLoading(false);
|
||||
};
|
||||
const searchChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
updateFilter('search', e.target.value);
|
||||
};
|
||||
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||
const newVal = val as OptionType;
|
||||
setPageSize(newVal.value as number);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='w-full p-0 sm:p-4'>
|
||||
<div className='flex flex-col gap-2 mb-4'>
|
||||
<div className='w-full flex flex-col sm:flex-row justify-between items-end sm:items-center gap-2'>
|
||||
<div className='flex flex-row'>
|
||||
<Button href='/master-data/flock/add' color='primary'>
|
||||
Tambah Flock
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<DebouncedTextInput
|
||||
name='search'
|
||||
placeholder='Cari Flock'
|
||||
value={tableFilterState.search}
|
||||
onChange={searchChangeHandler}
|
||||
className={{ wrapper: 'sm:max-w-3xs' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className='flex flex-row justify-end'>
|
||||
<SelectInput
|
||||
label='Baris'
|
||||
options={ROWS_OPTIONS}
|
||||
value={{
|
||||
label: String(tableFilterState.pageSize),
|
||||
value: tableFilterState.pageSize,
|
||||
}}
|
||||
onChange={pageSizeChangeHandler}
|
||||
className={{ wrapper: 'max-w-28' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Table<Flock>
|
||||
data={isResponseSuccess(flocks) ? flocks?.data : []}
|
||||
columns={flocksColumns}
|
||||
pageSize={tableFilterState.pageSize}
|
||||
page={isResponseSuccess(flocks) ? flocks?.meta?.page : 0}
|
||||
totalItems={
|
||||
isResponseSuccess(flocks) ? flocks?.meta?.total_results : 0
|
||||
}
|
||||
onPageChange={setPage}
|
||||
isLoading={isLoading}
|
||||
className={{
|
||||
containerClassName: cn({
|
||||
'mb-20': isResponseSuccess(flocks) && flocks?.data?.length === 0,
|
||||
}),
|
||||
tableWrapperClassName: 'overflow-x-auto min-h-full!',
|
||||
tableClassName: 'font-inter w-full table-auto min-h-full!',
|
||||
headerRowClassName: 'border-b border-b-gray-200',
|
||||
headerColumnClassName:
|
||||
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
|
||||
bodyRowClassName: 'border-b border-b-gray-200',
|
||||
bodyColumnClassName:
|
||||
'px-6 py-3 last:flex last:flex-row last:justify-end',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<ConfirmationModal
|
||||
ref={deleteModal.ref}
|
||||
type='error'
|
||||
text={`Apakah anda yakin ingin menghapus data Supplier ini (${selectedFlock?.name})?`}
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: 'error',
|
||||
isLoading: isDeleteLoading,
|
||||
onClick: confirmationModalDeleteClickHandler,
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default FlockTable;
|
||||
@@ -0,0 +1,14 @@
|
||||
import * as Yup from 'yup';
|
||||
|
||||
export const FlockFormSchema = Yup.object({
|
||||
name: Yup.string()
|
||||
.required('Nama wajib diisi!')
|
||||
.matches(
|
||||
/^[\p{L}\p{N}\s]+$/u,
|
||||
'Nama tidak boleh mengandung simbol'
|
||||
),
|
||||
});
|
||||
|
||||
export const UpdateFlockFormSchema = FlockFormSchema;
|
||||
|
||||
export type FlockFormValues = Yup.InferType<typeof FlockFormSchema>;
|
||||
@@ -0,0 +1,217 @@
|
||||
'use client'
|
||||
|
||||
import { useModal } from '@/components/Modal';
|
||||
import { FlockApi } from '@/services/api/master-data';
|
||||
import { Flock } from '@/types/api/master-data/flock';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { FlockFormSchema, FlockFormValues, UpdateFlockFormSchema } from '@/components/pages/master-data/flock/form/FlockForm.schema';
|
||||
import { useFormik } from 'formik';
|
||||
import Button from '@/components/Button';
|
||||
import { Icon } from '@iconify/react';
|
||||
import TextInput from '@/components/input/TextInput';
|
||||
import { cn } from '@/lib/helper';
|
||||
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||
|
||||
interface FlockCustomProps {
|
||||
formType?: 'add' | 'edit' | 'detail';
|
||||
initialValues?: Flock;
|
||||
}
|
||||
|
||||
const FlockForm = ({ formType = 'add', initialValues }: FlockCustomProps) => {
|
||||
const router = useRouter();
|
||||
const deleteModal = useModal();
|
||||
|
||||
// State
|
||||
const [flockFormErrorMessage, setFlockFormErrorMessage] = useState('');
|
||||
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||
|
||||
// Handler
|
||||
const confirmationModalDeleteClickHandler = async () => {
|
||||
setIsDeleteLoading(true);
|
||||
|
||||
await FlockApi.delete(initialValues?.id as number);
|
||||
|
||||
deleteModal.closeModal();
|
||||
setIsDeleteLoading(false);
|
||||
router.push('/master-data/flock');
|
||||
};
|
||||
|
||||
// Initital Value
|
||||
const formikInitialValue = useMemo<FlockFormValues>(() => {
|
||||
return {
|
||||
name: initialValues?.name ?? '',
|
||||
};
|
||||
}, [initialValues]);
|
||||
|
||||
// Formik
|
||||
const formik = useFormik<FlockFormValues>({
|
||||
initialValues: formikInitialValue,
|
||||
enableReinitialize: true,
|
||||
validationSchema: formType === 'edit' ? UpdateFlockFormSchema : FlockFormSchema,
|
||||
onSubmit: async (values) => {
|
||||
// reset error message
|
||||
setFlockFormErrorMessage('');
|
||||
|
||||
// create payload
|
||||
const payload = {
|
||||
name: values.name,
|
||||
};
|
||||
|
||||
// cek type form yang disubmit
|
||||
switch (formType) {
|
||||
case 'add':
|
||||
await FlockApi.create(payload);
|
||||
break;
|
||||
case 'edit':
|
||||
await FlockApi.update(initialValues?.id as number, payload);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
router.push('/master-data/flock');
|
||||
},
|
||||
});
|
||||
|
||||
// Initialize Formik
|
||||
const { setValues: formikSetValues } = formik;
|
||||
useEffect(() => {
|
||||
formikSetValues(formikInitialValue);
|
||||
}, [formikSetValues, formikInitialValue]);
|
||||
|
||||
// Render
|
||||
return (
|
||||
<>
|
||||
<section className='w-full max-w-xl'>
|
||||
<header className='flex flex-col gap-4'>
|
||||
<Button
|
||||
href='/master-data/flock'
|
||||
variant='link'
|
||||
className='w-fit p-0 text-primary'
|
||||
>
|
||||
<Icon icon='uil:arrow-left' width={24} height={24} />
|
||||
Kembali
|
||||
</Button>
|
||||
|
||||
<h1 className='text-2xl font-bold text-center'>
|
||||
{formType === 'add' && 'Tambah Flock'}
|
||||
{formType === 'edit' && 'Ubah Flock'}
|
||||
{formType === 'detail' && 'Detail Flock'}
|
||||
</h1>
|
||||
</header>
|
||||
<form
|
||||
onSubmit={formik.handleSubmit}
|
||||
onReset={formik.handleReset}
|
||||
className='w-full mt-8 flex flex-col gap-6'
|
||||
>
|
||||
{/* Fields Form */}
|
||||
<div className='flex flex-col gap-4'>
|
||||
<TextInput
|
||||
required
|
||||
label='Nama Flock'
|
||||
name='name'
|
||||
placeholder='Masukkan nama flock'
|
||||
value={formik.values.name}
|
||||
onChange={formik.handleChange}
|
||||
onBlur={formik.handleBlur}
|
||||
isError={formik.touched.name && Boolean(formik.errors.name)}
|
||||
errorMessage={formik.errors.name}
|
||||
readOnly={formType === 'detail'}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Action Button */}
|
||||
<div className='flex flex-row justify-between gap-2 flex-wrap'>
|
||||
{formType !== 'add' && (
|
||||
<div className='flex flex-row justify-start gap-2'>
|
||||
<Button
|
||||
type='button'
|
||||
color='error'
|
||||
onClick={() => deleteModal.openModal()}
|
||||
className='px-4'
|
||||
>
|
||||
<Icon
|
||||
icon='material-symbols:delete-outline-rounded'
|
||||
width={24}
|
||||
height={24}
|
||||
className='justify-start text-sm'
|
||||
/>
|
||||
Delete
|
||||
</Button>
|
||||
{formType !== 'edit' && (
|
||||
<Button
|
||||
type='button'
|
||||
color='warning'
|
||||
href={`/master-data/flock/detail/edit/?flockId=${initialValues?.id}`}
|
||||
className='px-4'
|
||||
>
|
||||
<Icon
|
||||
icon='material-symbols:edit-outline'
|
||||
width={24}
|
||||
height={24}
|
||||
className='justify-start text-sm'
|
||||
/>
|
||||
Edit
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{formType !== 'detail' && (
|
||||
<div
|
||||
className={cn('flex flex-row justify-end gap-2', {
|
||||
'w-full': formType === 'add',
|
||||
})}
|
||||
>
|
||||
<Button type='reset' color='warning' className='px-4'>
|
||||
Reset
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
type='submit'
|
||||
color='primary'
|
||||
isLoading={formik.isSubmitting}
|
||||
disabled={!formik.isValid || formik.isSubmitting}
|
||||
className='px-4'
|
||||
>
|
||||
Submit
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{flockFormErrorMessage && (
|
||||
<div role='alert' className='alert alert-error'>
|
||||
<Icon
|
||||
icon='material-symbols:error-outline'
|
||||
width={24}
|
||||
height={24}
|
||||
/>
|
||||
<span>{flockFormErrorMessage}</span>
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
</section>
|
||||
|
||||
{formType !== 'add' && (
|
||||
<ConfirmationModal
|
||||
ref={deleteModal.ref}
|
||||
type='error'
|
||||
text={`Apakah anda yakin ingin menghapus data Flock ini (${initialValues?.name})?`}
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: 'error',
|
||||
onClick: confirmationModalDeleteClickHandler,
|
||||
isLoading: isDeleteLoading,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default FlockForm;
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
SupplierFormSchema,
|
||||
SupplierFormValues,
|
||||
UpdateSupplierFormSchema,
|
||||
} from './SupplierForm.schema';
|
||||
} from '@/components/pages/master-data/supplier/form/SupplierForm.schema';
|
||||
import { useFormik } from 'formik';
|
||||
import SelectInput, { OptionType } from '@/components/input/SelectInput';
|
||||
import { Icon } from '@iconify/react';
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
'use client';
|
||||
|
||||
import Button from '@/components/Button';
|
||||
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
|
||||
import { OptionType } from '@/components/input/SelectInput';
|
||||
import Modal, { useModal } from '@/components/Modal';
|
||||
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||
import Table from '@/components/Table';
|
||||
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
|
||||
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
|
||||
import { TableRowSizeSelector } from '@/components/table/TableRowSizeSelector';
|
||||
import { ROWS_OPTIONS } from '@/config/constant';
|
||||
import { isResponseSuccess } from '@/lib/api-helper';
|
||||
import { cn, formatNumber } from '@/lib/helper';
|
||||
import { ChickinApi } from '@/services/api/production';
|
||||
import { useTableFilter } from '@/services/hooks/useTableFilter';
|
||||
import { Chickin } from '@/types/api/production/chickin';
|
||||
import { Icon } from '@iconify/react';
|
||||
import { CellContext, SortingState } from '@tanstack/react-table';
|
||||
import { useState } from 'react';
|
||||
import useSWR from 'swr';
|
||||
import ChickinForm from './form/ChickinForm';
|
||||
|
||||
const ChickinTable = () => {
|
||||
const {
|
||||
state: tableFilterState,
|
||||
updateFilter,
|
||||
setPage,
|
||||
setPageSize,
|
||||
toQueryString: getTableFilterQueryString,
|
||||
} = useTableFilter({
|
||||
initial: {
|
||||
search: '',
|
||||
},
|
||||
paramMap: {
|
||||
page: 'page',
|
||||
pageSize: 'limit',
|
||||
search: 'search',
|
||||
},
|
||||
});
|
||||
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
const [selectedChickin, setSelectedChickin] = useState<Chickin | undefined>(
|
||||
undefined
|
||||
);
|
||||
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||
|
||||
const deleteModal = useModal();
|
||||
const chickinModal = useModal();
|
||||
|
||||
// Data Fetching
|
||||
const {
|
||||
data: chickins,
|
||||
isLoading,
|
||||
mutate: refreshChickins,
|
||||
} = useSWR(
|
||||
`${ChickinApi.basePath}${getTableFilterQueryString()}`,
|
||||
ChickinApi.getAllFetcher
|
||||
);
|
||||
|
||||
const searchChangeHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
updateFilter('search', event.target.value);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||
const newVal = val as OptionType;
|
||||
setPageSize(newVal.value as number);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const confirmationModalDeleteClickHandler = async () => {
|
||||
setIsDeleteLoading(true);
|
||||
try {
|
||||
await ChickinApi.delete(selectedChickin?.id as number);
|
||||
refreshChickins();
|
||||
deleteModal.closeModal();
|
||||
} finally {
|
||||
setIsDeleteLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='flex flex-col gap-4'>
|
||||
<div className='flex flex-col gap-2 mb-4'>
|
||||
<div className='w-full flex flex-col sm:flex-row justify-between items-end sm:items-center gap-2'>
|
||||
<Button
|
||||
href='/production/chickin/add?projectFlockId=1'
|
||||
color='primary'
|
||||
>
|
||||
<Icon icon='uil:plus' width={24} height={24} />
|
||||
Tambah
|
||||
</Button>
|
||||
<DebouncedTextInput
|
||||
name='search'
|
||||
placeholder='Cari Chickin'
|
||||
value={tableFilterState.search}
|
||||
onChange={searchChangeHandler}
|
||||
className={{ wrapper: 'sm:max-w-3xs' }}
|
||||
/>
|
||||
</div>
|
||||
<TableRowSizeSelector
|
||||
value={tableFilterState.pageSize}
|
||||
onChange={pageSizeChangeHandler}
|
||||
options={ROWS_OPTIONS}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<Table<Chickin>
|
||||
data={isResponseSuccess(chickins) ? chickins?.data : []}
|
||||
columns={[
|
||||
{
|
||||
header: '#',
|
||||
cell: (props) =>
|
||||
tableFilterState.pageSize * (tableFilterState.page - 1) +
|
||||
props.row.index +
|
||||
1,
|
||||
},
|
||||
{
|
||||
accessorFn: (row) => row.project_flock_kandang?.kandang.name,
|
||||
header: 'Kandang',
|
||||
},
|
||||
{
|
||||
accessorFn: (row) => row.quantity,
|
||||
header: 'Jumlah Chickin',
|
||||
cell: (props) => {
|
||||
if (props.row.original.quantity) {
|
||||
return formatNumber(props.row.original.quantity);
|
||||
} else {
|
||||
return '-';
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorFn: (row) => row.chick_in_date,
|
||||
header: 'Tanggal Chickin',
|
||||
cell: (props) => {
|
||||
if (props.row.original.chick_in_date) {
|
||||
return new Date(props.row.original.chick_in_date).toLocaleDateString(
|
||||
'id-ID'
|
||||
);
|
||||
} else {
|
||||
return '-';
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorFn: (row) => row.note,
|
||||
header: 'Catatan',
|
||||
},
|
||||
{
|
||||
header: 'Aksi',
|
||||
cell: (props) => {
|
||||
const currentPageSize =
|
||||
props.table.getPaginationRowModel().rows.length;
|
||||
const currentPageRows =
|
||||
props.table.getPaginationRowModel().flatRows;
|
||||
const currentRowRelativeIndex =
|
||||
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
|
||||
|
||||
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
|
||||
|
||||
const deleteClickHandler = () => {
|
||||
setSelectedChickin(props.row.original);
|
||||
deleteModal.openModal();
|
||||
};
|
||||
|
||||
const editClickHandler = () => {
|
||||
setSelectedChickin(props.row.original);
|
||||
chickinModal.openModal();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{currentPageSize > 2 && (
|
||||
<RowDropdownOptions isLast2Rows={isLast2Rows}>
|
||||
<RowOptionsMenu
|
||||
type='dropdown'
|
||||
props={props}
|
||||
deleteClickHandler={deleteClickHandler}
|
||||
editClickHandler={editClickHandler}
|
||||
/>
|
||||
</RowDropdownOptions>
|
||||
)}
|
||||
|
||||
{currentPageSize <= 2 && (
|
||||
<RowCollapseOptions>
|
||||
<RowOptionsMenu
|
||||
type='collapse'
|
||||
props={props}
|
||||
deleteClickHandler={deleteClickHandler}
|
||||
editClickHandler={editClickHandler}
|
||||
/>
|
||||
</RowCollapseOptions>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
},
|
||||
},
|
||||
]}
|
||||
pageSize={tableFilterState.pageSize}
|
||||
page={isResponseSuccess(chickins) ? chickins?.meta?.page : 0}
|
||||
totalItems={
|
||||
isResponseSuccess(chickins) ? chickins?.meta?.total_results : 0
|
||||
}
|
||||
onPageChange={setPage}
|
||||
isLoading={isLoading}
|
||||
sorting={sorting}
|
||||
setSorting={setSorting}
|
||||
className={{
|
||||
containerClassName: cn({
|
||||
'mb-20':
|
||||
isResponseSuccess(chickins) && chickins?.data?.length === 0,
|
||||
}),
|
||||
tableWrapperClassName: 'overflow-x-auto min-h-full!',
|
||||
tableClassName: 'font-inter w-full table-auto min-h-full!',
|
||||
headerRowClassName: 'border-b border-b-gray-200',
|
||||
headerColumnClassName:
|
||||
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
|
||||
bodyRowClassName: 'border-b border-b-gray-200',
|
||||
bodyColumnClassName:
|
||||
'px-6 py-3 last:flex last:flex-row last:justify-end',
|
||||
}}
|
||||
/>
|
||||
<ConfirmationModal
|
||||
ref={deleteModal.ref}
|
||||
type='error'
|
||||
text={`Apakah anda yakin ingin menghapus data Chickin ini?`}
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
onClick: confirmationModalDeleteClickHandler,
|
||||
isLoading: isDeleteLoading,
|
||||
color: 'error',
|
||||
}}
|
||||
/>
|
||||
<Modal ref={chickinModal.ref}>
|
||||
<div className='flex flex-row justify-between items-center'>
|
||||
<h1 className='text-xl font-semibold text-center mb-6'>
|
||||
Chickin Kandang - { selectedChickin?.project_flock_kandang && selectedChickin?.project_flock_kandang.kandang?.name}
|
||||
</h1>
|
||||
<Button
|
||||
color='error'
|
||||
variant='link'
|
||||
onClick={chickinModal.closeModal}
|
||||
>
|
||||
<Icon
|
||||
className='text-black'
|
||||
icon='uil:times'
|
||||
width={24}
|
||||
height={24}
|
||||
/>
|
||||
</Button>
|
||||
</div>
|
||||
<ChickinForm initialValues={selectedChickin} formType='edit' afterSubmit={() => {
|
||||
refreshChickins()
|
||||
chickinModal.closeModal()
|
||||
}}/>
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const RowOptionsMenu = ({
|
||||
type = 'dropdown',
|
||||
props,
|
||||
editClickHandler,
|
||||
deleteClickHandler,
|
||||
}: {
|
||||
type: 'dropdown' | 'collapse';
|
||||
props: CellContext<Chickin, unknown>;
|
||||
editClickHandler: () => void;
|
||||
deleteClickHandler: () => void;
|
||||
}) => {
|
||||
return (
|
||||
<div
|
||||
tabIndex={type == 'dropdown' ? 0 : undefined}
|
||||
className={cn(
|
||||
{
|
||||
'dropdown-content': type === 'dropdown',
|
||||
'mt-2': type === 'collapse',
|
||||
},
|
||||
'p-2.5 mr-2 flex flex-col gap-1 bg-base-100 rounded-box z-10 border border-black/10 shadow'
|
||||
)}
|
||||
>
|
||||
<Button
|
||||
href={`/production/chickin/detail?chickinId=${props.row.original.id}`}
|
||||
variant='ghost'
|
||||
color='primary'
|
||||
className='justify-start text-sm'
|
||||
>
|
||||
<Icon icon='mdi:eye-outline' width={16} height={16} />
|
||||
Detail
|
||||
</Button>
|
||||
<Button
|
||||
variant='ghost'
|
||||
color='warning'
|
||||
className='justify-start text-sm'
|
||||
onClick={editClickHandler}
|
||||
>
|
||||
<Icon icon='mdi:pencil-outline' width={16} height={16} />
|
||||
Edit
|
||||
</Button>
|
||||
<Button
|
||||
onClick={deleteClickHandler}
|
||||
variant='ghost'
|
||||
color='error'
|
||||
className='text-error hover:text-inherit'
|
||||
>
|
||||
<Icon
|
||||
icon='material-symbols:delete-outline-rounded'
|
||||
width={16}
|
||||
height={16}
|
||||
className='justify-start text-sm'
|
||||
/>
|
||||
Delete
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ChickinTable;
|
||||
@@ -0,0 +1,11 @@
|
||||
import * as Yup from 'yup';
|
||||
|
||||
export const ChickinFormSchema = Yup.object({
|
||||
chick_in_date: Yup.string().required('Tanggal masuk wajib diisi!'),
|
||||
note: Yup.string().required('Catatan wajib diisi!'),
|
||||
quantity: Yup.number().min(1, 'Jumlah wajib diisi!').required('Jumlah wajib diisi!'),
|
||||
})
|
||||
|
||||
export type ChickinFormValues = Yup.InferType<typeof ChickinFormSchema>;
|
||||
|
||||
export const UpdateChickinFormSchema = ChickinFormSchema;
|
||||
@@ -0,0 +1,220 @@
|
||||
'use client';
|
||||
|
||||
import Button from '@/components/Button';
|
||||
import {
|
||||
Chickin,
|
||||
CreateChickinPayload,
|
||||
UpdateChickinPayload,
|
||||
} from '@/types/api/production/chickin';
|
||||
import {
|
||||
ChickinFormSchema,
|
||||
ChickinFormValues,
|
||||
UpdateChickinFormSchema,
|
||||
} from '@/components/pages/production/chickin/form/ChickinForm.schema';
|
||||
import { use, useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useFormik } from 'formik';
|
||||
import { ChickinApi } from '@/services/api/production';
|
||||
import DateInput from '@/components/input/DateInput';
|
||||
import { isResponseError } from '@/lib/api-helper';
|
||||
import toast from 'react-hot-toast';
|
||||
import { Icon } from '@iconify/react';
|
||||
import TextArea from '@/components/input/TextArea';
|
||||
import TextInput from '@/components/input/TextInput';
|
||||
import NumberInput from '@/components/input/NumberInput';
|
||||
|
||||
interface ChickinFormProps {
|
||||
formType?: 'add' | 'detail' | 'edit';
|
||||
initialValues?: Chickin;
|
||||
afterSubmit?: () => void;
|
||||
}
|
||||
|
||||
const ChickinForm = ({
|
||||
formType = 'add',
|
||||
initialValues,
|
||||
afterSubmit,
|
||||
}: ChickinFormProps) => {
|
||||
// Helper Function
|
||||
const formatDateForInput = (dateString?: string): string => {
|
||||
if (!dateString) return '';
|
||||
return new Date(dateString).toISOString().split('T')[0];
|
||||
};
|
||||
|
||||
// State
|
||||
const [chickinFormErrorMessage, setChickinFormErrorMessage] = useState('');
|
||||
|
||||
// Initial Value
|
||||
const formikInitialValue = useMemo<ChickinFormValues>(() => {
|
||||
return {
|
||||
chick_in_date: formatDateForInput(initialValues?.chick_in_date) ?? '',
|
||||
note: initialValues?.note ?? '',
|
||||
quantity:
|
||||
initialValues?.quantity ??
|
||||
initialValues?.project_flock_kandang?.available_quantity ??
|
||||
0,
|
||||
};
|
||||
}, [initialValues]);
|
||||
|
||||
// Handle Submit Function
|
||||
const handleCreate = useCallback(
|
||||
async (
|
||||
payload: CreateChickinPayload,
|
||||
afterSubmit: (() => void) | undefined
|
||||
) => {
|
||||
const res = await ChickinApi.create(payload);
|
||||
if (isResponseError(res)) {
|
||||
setChickinFormErrorMessage(res.message);
|
||||
return;
|
||||
}
|
||||
toast.success(res?.message as string);
|
||||
afterSubmit?.();
|
||||
},
|
||||
[]
|
||||
);
|
||||
const handleUpdate = useCallback(
|
||||
async (
|
||||
payload: UpdateChickinPayload,
|
||||
afterSubmit: (() => void) | undefined
|
||||
) => {
|
||||
const res = await ChickinApi.update(payload.id, payload);
|
||||
if (isResponseError(res)) {
|
||||
setChickinFormErrorMessage(res.message);
|
||||
return;
|
||||
}
|
||||
toast.success(res?.message as string);
|
||||
afterSubmit?.();
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
// Formik
|
||||
const formik = useFormik<ChickinFormValues>({
|
||||
initialValues: formikInitialValue,
|
||||
enableReinitialize: true,
|
||||
validationSchema:
|
||||
formType === 'edit' ? UpdateChickinFormSchema : ChickinFormSchema,
|
||||
onSubmit: async (values) => {
|
||||
// reset error message
|
||||
setChickinFormErrorMessage('');
|
||||
|
||||
if (
|
||||
initialValues?.project_flock_kandang?.id == undefined ||
|
||||
(formType == 'edit' && initialValues?.id == undefined)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
// create payload
|
||||
const payload = {
|
||||
chick_in_date: values.chick_in_date,
|
||||
project_flock_kandang_id: initialValues?.project_flock_kandang?.id,
|
||||
note: values.note,
|
||||
quantity: values.quantity,
|
||||
id: initialValues.id ?? 0,
|
||||
};
|
||||
|
||||
// cek type form yang disubmit
|
||||
console.log(formType);
|
||||
switch (formType) {
|
||||
case 'add':
|
||||
handleCreate(payload, afterSubmit);
|
||||
break;
|
||||
case 'edit':
|
||||
handleUpdate(payload, afterSubmit);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// Initialize Formik
|
||||
const { setValues: formikSetValues } = formik;
|
||||
useEffect(() => {
|
||||
formikSetValues(formikInitialValue);
|
||||
}, [formikSetValues, formikInitialValue]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<form
|
||||
className='min-h-48 flex flex-col gap-4'
|
||||
onSubmit={formik.handleSubmit}
|
||||
onReset={formik.handleReset}
|
||||
>
|
||||
<DateInput
|
||||
value={formik.values.chick_in_date}
|
||||
onChange={formik.handleChange}
|
||||
onBlur={formik.handleBlur}
|
||||
name='chick_in_date'
|
||||
label='Tanggal Chickin'
|
||||
required
|
||||
isError={
|
||||
formik.touched.chick_in_date && Boolean(formik.errors.chick_in_date)
|
||||
}
|
||||
errorMessage={formik.errors.chick_in_date}
|
||||
/>
|
||||
<NumberInput
|
||||
value={formik.values.quantity}
|
||||
onChange={formik.handleChange}
|
||||
onBlur={formik.handleBlur}
|
||||
name='quantity'
|
||||
label='Jumlah (Ekor)'
|
||||
required
|
||||
isError={
|
||||
(formik.touched.quantity && Boolean(formik.errors.quantity)) ||
|
||||
formik.values.quantity == 0
|
||||
}
|
||||
errorMessage={
|
||||
formik.values.quantity == 0
|
||||
? 'Masukan Persediaan Day Old Chick terlebih dahulu.'
|
||||
: formik.errors.quantity
|
||||
}
|
||||
readOnly
|
||||
/>
|
||||
<TextArea
|
||||
required
|
||||
label='Catatan'
|
||||
name='note'
|
||||
placeholder='Masukan catatan chickin'
|
||||
value={formik.values.note}
|
||||
onChange={formik.handleChange}
|
||||
onBlur={formik.handleBlur}
|
||||
isError={formik.touched.note && Boolean(formik.errors.note)}
|
||||
errorMessage={formik.errors.note}
|
||||
/>
|
||||
{initialValues?.project_flock_kandang?.id == undefined && (
|
||||
<p className='text-error'>Project Flock Kandang tidak ditemukan.</p>
|
||||
)}
|
||||
{chickinFormErrorMessage && (
|
||||
<div
|
||||
role='alert'
|
||||
className='alert alert-error'
|
||||
onClick={() => {
|
||||
setChickinFormErrorMessage('');
|
||||
}}
|
||||
>
|
||||
<Icon icon='mdi:times' />
|
||||
<span>{chickinFormErrorMessage}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className='flex justify-center mt-auto gap-2'>
|
||||
<Button color='warning' type='reset'>
|
||||
Reset
|
||||
</Button>
|
||||
<Button
|
||||
type='submit'
|
||||
isLoading={formik.isSubmitting}
|
||||
disabled={
|
||||
!formik.isValid ||
|
||||
formik.isSubmitting ||
|
||||
!initialValues?.project_flock_kandang?.id
|
||||
}
|
||||
>
|
||||
Submit
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default ChickinForm;
|
||||
@@ -0,0 +1,601 @@
|
||||
'use client';
|
||||
|
||||
import Button from '@/components/Button';
|
||||
import CheckboxInput from '@/components/input/CheckboxInput';
|
||||
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
|
||||
import SelectInput, { OptionType } from '@/components/input/SelectInput';
|
||||
import { useModal } from '@/components/Modal';
|
||||
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||
import Table from '@/components/Table';
|
||||
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
|
||||
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
|
||||
import { ROWS_OPTIONS } from '@/config/constant';
|
||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||
import { cn } from '@/lib/helper';
|
||||
import { AreaApi, KandangApi, LocationApi } from '@/services/api/master-data';
|
||||
import { ProjectFlockApi } from '@/services/api/production';
|
||||
import { useTableFilter } from '@/services/hooks/useTableFilter';
|
||||
import { BaseApiResponse } from '@/types/api/api-general';
|
||||
import { Kandang } from '@/types/api/master-data/kandang';
|
||||
import {
|
||||
ProjectFlockApprovalPayload,
|
||||
ProjectFlock,
|
||||
} from '@/types/api/production/project-flock';
|
||||
import { Icon } from '@iconify/react';
|
||||
import { CellContext, SortingState } from '@tanstack/react-table';
|
||||
import { ChangeEventHandler, useState } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import useSWR from 'swr';
|
||||
|
||||
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 flex flex-col gap-1 bg-base-100 rounded-box z-10 border border-black/10 shadow'
|
||||
)}
|
||||
>
|
||||
<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>
|
||||
{props.row.original.approval.step_name === 'Aktif' && (
|
||||
<Button
|
||||
href={`/production/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>
|
||||
)}
|
||||
{props.row.original.approval.step_name === 'Pengajuan' && (
|
||||
<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>
|
||||
)}
|
||||
<Button
|
||||
onClick={deleteClickHandler}
|
||||
variant='ghost'
|
||||
color='error'
|
||||
className='text-error hover:text-inherit'
|
||||
>
|
||||
<Icon
|
||||
icon='material-symbols:delete-outline-rounded'
|
||||
width={16}
|
||||
height={16}
|
||||
className='justify-start text-sm'
|
||||
/>
|
||||
Delete
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const ProjectFlockTable = () => {
|
||||
const {
|
||||
state: tableFilterState,
|
||||
updateFilter,
|
||||
setPage,
|
||||
setPageSize,
|
||||
toQueryString: getTableFilterQueryString,
|
||||
} = useTableFilter({
|
||||
initial: {
|
||||
search: '',
|
||||
areaFilter: '',
|
||||
locationFilter: '',
|
||||
kandangFilter: '',
|
||||
periodFilter: '',
|
||||
},
|
||||
paramMap: {
|
||||
page: 'page',
|
||||
pageSize: 'limit',
|
||||
search: 'search',
|
||||
areaFilter: 'area_id',
|
||||
locationFilter: 'location_id',
|
||||
kandangFilter: 'kandang_id',
|
||||
periodFilter: 'period',
|
||||
},
|
||||
});
|
||||
|
||||
// State
|
||||
const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});
|
||||
const selectedRowIds = Object.keys(rowSelection)
|
||||
.filter((id) => rowSelection[id])
|
||||
.map((id) => parseInt(id));
|
||||
const [locationSelectInputValue, setLocationSelectInputValue] = useState('');
|
||||
const [areaSelectInputValue, setAreaSelectInputValue] = useState('');
|
||||
const [kandangSelectInputValue, setKandangSelectInputValue] = useState('');
|
||||
const [selectedArea, setSelectedArea] = useState<OptionType | null>(null);
|
||||
const [selectedLocation, setSelectedLocation] = useState<OptionType | null>(
|
||||
null
|
||||
);
|
||||
const [selectedKandang, setSelectedKandang] = useState<OptionType | null>(
|
||||
null
|
||||
);
|
||||
const [periodInputValue, setPeriodInputValue] = useState<number | null>(null);
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
const [selectedProjectFlock, setSelectedProjectFlock] =
|
||||
useState<ProjectFlock>();
|
||||
const deleteModal = useModal();
|
||||
const confirmModal = useModal();
|
||||
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||
const [isApproveLoading, setIsApproveLoading] = useState(false);
|
||||
|
||||
// Fetch Data
|
||||
const {
|
||||
data: projectFlocks,
|
||||
isLoading,
|
||||
mutate: refreshProjectFlocks,
|
||||
} = useSWR(
|
||||
`${ProjectFlockApi.basePath}${getTableFilterQueryString()}`,
|
||||
ProjectFlockApi.getAllFetcher
|
||||
);
|
||||
|
||||
const areaUrl = `${AreaApi.basePath}?${new URLSearchParams({
|
||||
search: areaSelectInputValue,
|
||||
limit: '100',
|
||||
}).toString()}`;
|
||||
const { data: areas, isLoading: isLoadingAreas } = useSWR(
|
||||
areaUrl,
|
||||
AreaApi.getAllFetcher
|
||||
);
|
||||
|
||||
const locationUrl = `${LocationApi.basePath}?${new URLSearchParams({
|
||||
search: locationSelectInputValue,
|
||||
area_id: selectedArea != null ? selectedArea.value.toString() : '',
|
||||
limit: '100',
|
||||
}).toString()}`;
|
||||
const { data: locations, isLoading: isLoadingLocations } = useSWR(
|
||||
locationUrl,
|
||||
LocationApi.getAllFetcher
|
||||
);
|
||||
|
||||
const kandangUrl = `${KandangApi.basePath}?${new URLSearchParams({
|
||||
search: kandangSelectInputValue,
|
||||
location_id:
|
||||
selectedLocation != null ? selectedLocation.value.toString() : '',
|
||||
limit: '100',
|
||||
}).toString()}`;
|
||||
const { data: kandangs, isLoading: isLoadingKandang } = useSWR(
|
||||
kandangUrl,
|
||||
KandangApi.getAllFetcher
|
||||
);
|
||||
|
||||
// Data to Options Mapping
|
||||
const optionsArea = isResponseSuccess(areas)
|
||||
? areas?.data.map((area) => ({
|
||||
value: area.id,
|
||||
label: area.name,
|
||||
}))
|
||||
: [];
|
||||
const optionsKandang = isResponseSuccess(kandangs)
|
||||
? kandangs?.data.map((kandang) => ({
|
||||
value: kandang.id,
|
||||
label: kandang.name,
|
||||
}))
|
||||
: [];
|
||||
const optionsLocation = isResponseSuccess(locations)
|
||||
? locations?.data.map((location) => ({
|
||||
value: location.id,
|
||||
label: location.name,
|
||||
}))
|
||||
: [];
|
||||
|
||||
// Handler
|
||||
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||
const newVal = val as OptionType;
|
||||
setPageSize(newVal.value as number);
|
||||
};
|
||||
const confirmationModalDeleteClickHandler = async () => {
|
||||
setIsDeleteLoading(true);
|
||||
|
||||
await ProjectFlockApi.delete(selectedProjectFlock?.id as number);
|
||||
refreshProjectFlocks();
|
||||
|
||||
deleteModal.closeModal();
|
||||
toast.success('Successfully delete Project Flock!');
|
||||
setIsDeleteLoading(false);
|
||||
};
|
||||
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
|
||||
updateFilter('search', e.target.value);
|
||||
};
|
||||
|
||||
const confirmationModalApproveClickHandler = async () => {
|
||||
setIsApproveLoading(true);
|
||||
const approveProjectFlockRes = await ProjectFlockApi.customRequest<
|
||||
BaseApiResponse<ProjectFlock>,
|
||||
ProjectFlockApprovalPayload
|
||||
>(`/approvals`, {
|
||||
method: 'POST',
|
||||
payload: {
|
||||
action: 'APPROVED',
|
||||
approvable_ids: selectedRowIds.map((id) => id),
|
||||
},
|
||||
});
|
||||
|
||||
if (isResponseSuccess(approveProjectFlockRes)) {
|
||||
toast.success('Project Flock berhasil di-approve!');
|
||||
confirmModal.closeModal();
|
||||
}
|
||||
if (isResponseError(approveProjectFlockRes)) {
|
||||
toast.error(approveProjectFlockRes?.message as string);
|
||||
confirmModal.closeModal();
|
||||
}
|
||||
setRowSelection({});
|
||||
refreshProjectFlocks();
|
||||
setIsApproveLoading(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='w-full p-0 sm:p-4'>
|
||||
<div className='flex flex-col gap-2 mb-4'>
|
||||
<div className='w-full flex flex-col justify-between items-end gap-2'>
|
||||
<div className='flex flex-col sm:flex-row gap-3 w-full'>
|
||||
<Button
|
||||
href='/production/project-flock/add'
|
||||
color='primary'
|
||||
className='w-full sm:w-fit'
|
||||
>
|
||||
<Icon icon='ic:round-plus' width={24} height={24} />
|
||||
Tambah
|
||||
</Button>
|
||||
<Button
|
||||
variant='outline'
|
||||
color='success'
|
||||
onClick={() => {
|
||||
confirmModal.openModal();
|
||||
}}
|
||||
disabled={selectedRowIds.length === 0}
|
||||
className='w-full sm:w-fit'
|
||||
>
|
||||
<Icon icon='material-symbols:check' width={24} height={24} />
|
||||
Approve
|
||||
</Button>
|
||||
<div className='ms-auto w-full sm:w-auto'>
|
||||
<DebouncedTextInput
|
||||
name='search'
|
||||
placeholder='Cari Area'
|
||||
value={tableFilterState.search}
|
||||
onChange={searchChangeHandler}
|
||||
className={{
|
||||
wrapper: 'w-full sm:max-w-3xs',
|
||||
input: 'w-full',
|
||||
inputWrapper: 'w-full',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className='hidden sm:flex flex-row justify-end gap-6 w-full'>
|
||||
<SelectInput
|
||||
label='Area'
|
||||
options={optionsArea}
|
||||
isLoading={isLoadingAreas}
|
||||
value={selectedArea}
|
||||
onChange={(val) => {
|
||||
setSelectedArea(val as OptionType);
|
||||
updateFilter(
|
||||
'areaFilter',
|
||||
(val as OptionType)?.value.toString()
|
||||
);
|
||||
}}
|
||||
onInputChange={setAreaSelectInputValue}
|
||||
isClearable
|
||||
/>
|
||||
<SelectInput
|
||||
label='Lokasi'
|
||||
options={optionsLocation}
|
||||
isLoading={isLoadingLocations}
|
||||
value={selectedLocation}
|
||||
onChange={(val) => {
|
||||
setSelectedLocation(val as OptionType);
|
||||
updateFilter(
|
||||
'locationFilter',
|
||||
(val as OptionType)?.value.toString()
|
||||
);
|
||||
}}
|
||||
onInputChange={setLocationSelectInputValue}
|
||||
isClearable
|
||||
/>
|
||||
<SelectInput
|
||||
label='Kandang'
|
||||
options={optionsKandang}
|
||||
isLoading={isLoadingKandang}
|
||||
value={selectedKandang}
|
||||
onChange={(val) => {
|
||||
setSelectedKandang(val as OptionType);
|
||||
updateFilter(
|
||||
'kandangFilter',
|
||||
(val as OptionType)?.value.toString()
|
||||
);
|
||||
}}
|
||||
onInputChange={setKandangSelectInputValue}
|
||||
isClearable
|
||||
/>
|
||||
<DebouncedTextInput
|
||||
name='period'
|
||||
type='number'
|
||||
label='Periode'
|
||||
placeholder='Masukan periode'
|
||||
value={periodInputValue ?? ''}
|
||||
onChange={(e) => {
|
||||
setPeriodInputValue(parseInt(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>
|
||||
|
||||
<Table<ProjectFlock>
|
||||
data={isResponseSuccess(projectFlocks) ? projectFlocks?.data : []}
|
||||
columns={[
|
||||
{
|
||||
id: 'select',
|
||||
header: ({ table }) => {
|
||||
const allRows = table.getRowModel().rows;
|
||||
const selectableRows = allRows.filter(
|
||||
(row) => row.original?.approval?.step_number == 1
|
||||
);
|
||||
|
||||
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}
|
||||
disabled={
|
||||
isResponseSuccess(projectFlocks) &&
|
||||
projectFlocks?.data?.filter(
|
||||
(flock) => flock.approval.step_number == 1
|
||||
).length == 0
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<CheckboxInput
|
||||
name='row'
|
||||
checked={
|
||||
row.getIsSelected() &&
|
||||
row.original.approval.step_number == 1
|
||||
}
|
||||
disabled={
|
||||
!row.getCanSelect() ||
|
||||
row.original.approval.step_number != 1
|
||||
}
|
||||
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',
|
||||
},
|
||||
{
|
||||
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) =>
|
||||
new Date(props.row.original.created_at).toLocaleDateString(),
|
||||
},
|
||||
{
|
||||
header: 'Aksi',
|
||||
cell: (props) => {
|
||||
const currentPageSize =
|
||||
props.table.getPaginationRowModel().rows.length;
|
||||
const currentPageRows =
|
||||
props.table.getPaginationRowModel().flatRows;
|
||||
const currentRowRelativeIndex =
|
||||
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
|
||||
|
||||
const isLast2Rows =
|
||||
currentRowRelativeIndex > currentPageSize - 2;
|
||||
|
||||
const deleteClickHandler = () => {
|
||||
setSelectedProjectFlock(props.row.original);
|
||||
deleteModal.openModal();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{currentPageSize > 2 && (
|
||||
<RowDropdownOptions isLast2Rows={isLast2Rows}>
|
||||
<RowOptionsMenu
|
||||
type='dropdown'
|
||||
props={props}
|
||||
deleteClickHandler={deleteClickHandler}
|
||||
/>
|
||||
</RowDropdownOptions>
|
||||
)}
|
||||
|
||||
{currentPageSize <= 2 && (
|
||||
<RowCollapseOptions>
|
||||
<RowOptionsMenu
|
||||
type='dropdown'
|
||||
props={props}
|
||||
deleteClickHandler={deleteClickHandler}
|
||||
/>
|
||||
</RowCollapseOptions>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
},
|
||||
},
|
||||
]}
|
||||
pageSize={tableFilterState.pageSize}
|
||||
page={
|
||||
isResponseSuccess(projectFlocks) ? projectFlocks?.meta?.page : 0
|
||||
}
|
||||
totalItems={
|
||||
isResponseSuccess(projectFlocks)
|
||||
? projectFlocks?.meta?.total_results
|
||||
: 0
|
||||
}
|
||||
onPageChange={setPage}
|
||||
isLoading={isLoading}
|
||||
sorting={sorting}
|
||||
setSorting={setSorting}
|
||||
rowSelection={rowSelection}
|
||||
setRowSelection={setRowSelection}
|
||||
className={{
|
||||
containerClassName: cn({
|
||||
'mb-20':
|
||||
isResponseSuccess(projectFlocks) &&
|
||||
projectFlocks?.data?.length === 0,
|
||||
}),
|
||||
tableWrapperClassName: 'overflow-x-auto min-h-full!',
|
||||
tableClassName: 'font-inter w-full table-auto min-h-full!',
|
||||
headerRowClassName: 'border-b border-b-gray-200',
|
||||
headerColumnClassName:
|
||||
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
|
||||
bodyRowClassName: 'border-b border-b-gray-200',
|
||||
bodyColumnClassName:
|
||||
'px-6 py-3 last:flex last:flex-row last:justify-end',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ConfirmationModal
|
||||
ref={deleteModal.ref}
|
||||
type='error'
|
||||
text={`Apakah anda yakin ingin menghapus data Project Flock ini (${selectedProjectFlock?.flock?.name})?`}
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: 'error',
|
||||
isLoading: isDeleteLoading,
|
||||
onClick: confirmationModalDeleteClickHandler,
|
||||
}}
|
||||
/>
|
||||
|
||||
<ConfirmationModal
|
||||
ref={confirmModal.ref}
|
||||
type='success'
|
||||
text={`Apakah anda yakin ingin reject data transfer ke laying ini (${selectedRowIds.length} data)?`}
|
||||
// text={
|
||||
// selectedFlocks.length > 0
|
||||
// ? `Apakah anda yakin ingin approve Project Flock berikut? (${selectedFlocks
|
||||
// .map(
|
||||
// (flock) =>
|
||||
// `${flock.flock?.name ?? '(Tanpa nama)'} - ${
|
||||
// flock.area?.name ?? '-'
|
||||
// }`
|
||||
// )
|
||||
// .join(', ')})`
|
||||
// : 'Tidak ada Project Flock yang dipilih.'
|
||||
// }
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: 'success',
|
||||
onClick: confirmationModalApproveClickHandler,
|
||||
isLoading: isApproveLoading,
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProjectFlockTable;
|
||||
@@ -0,0 +1,61 @@
|
||||
import * as Yup from 'yup';
|
||||
|
||||
export const ProjectFlockFormSchema = Yup.object({
|
||||
// Flock
|
||||
flock: Yup.object({
|
||||
value: Yup.number().required('ID Flock wajib diisi!'),
|
||||
label: Yup.string().required('Nama Flock wajib diisi!'),
|
||||
}).nullable(),
|
||||
flock_id: Yup.number()
|
||||
.min(1, 'Flock wajib diisi!')
|
||||
.required('Flock wajib diisi!'),
|
||||
|
||||
// Area
|
||||
area: Yup.object({
|
||||
value: Yup.number().required('ID Area wajib diisi!'),
|
||||
label: Yup.string().required('Nama Area wajib diisi!'),
|
||||
}).nullable(),
|
||||
area_id: Yup.number()
|
||||
.min(1, 'Area wajib diisi!')
|
||||
.required('Area wajib diisi!'),
|
||||
|
||||
// Kategori
|
||||
category_option: Yup.object({
|
||||
value: Yup.string().required('Nilai Kategori wajib diisi!'),
|
||||
label: Yup.string().required('Label Kategori wajib diisi!'),
|
||||
}).nullable(),
|
||||
category: Yup.string().oneOf(['GROWING', 'LAYING'], 'Kategori wajib diisi!')
|
||||
.required('Kategori wajib diisi!'),
|
||||
|
||||
// FCR
|
||||
fcr: Yup.object({
|
||||
value: Yup.number().required('ID FCR wajib diisi!'),
|
||||
label: Yup.string().required('Nama FCR wajib diisi!'),
|
||||
}).nullable(),
|
||||
fcr_id: Yup.number().min(1, 'FCR wajib diisi!').required('FCR wajib diisi!'),
|
||||
|
||||
// Location
|
||||
location: Yup.object({
|
||||
value: Yup.number().required('ID Lokasi wajib diisi!'),
|
||||
label: Yup.string().required('Nama Lokasi wajib diisi!'),
|
||||
}).nullable(),
|
||||
location_id: Yup.number()
|
||||
.min(1, 'Lokasi wajib diisi!')
|
||||
.required('Lokasi wajib diisi!'),
|
||||
|
||||
period: Yup.number()
|
||||
.required('Periode wajib diisi!')
|
||||
.typeError('Periode harus berupa angka')
|
||||
.min(1, 'Minimal periode adalah 1'),
|
||||
|
||||
kandang_ids: Yup.array()
|
||||
.of(Yup.number().typeError('Kandang tidak valid!'))
|
||||
.min(1, 'Minimal harus ada 1 kandang!')
|
||||
.required('Kandang wajib diisi!'),
|
||||
});
|
||||
|
||||
export type ProjectFlockFormValues = Yup.InferType<
|
||||
typeof ProjectFlockFormSchema
|
||||
>;
|
||||
|
||||
export const UpdateProjectFlockFormSchema = ProjectFlockFormSchema;
|
||||
@@ -0,0 +1,794 @@
|
||||
'use client';
|
||||
|
||||
import Button from '@/components/Button';
|
||||
import SelectInput, { OptionType } from '@/components/input/SelectInput';
|
||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||
import {
|
||||
AreaApi,
|
||||
FcrApi,
|
||||
FlockApi,
|
||||
KandangApi,
|
||||
LocationApi,
|
||||
} from '@/services/api/master-data';
|
||||
import { Icon } from '@iconify/react';
|
||||
import { useFormik } from 'formik';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import useSWR, { KeyedMutator } from 'swr';
|
||||
import {
|
||||
ProjectFlockFormSchema,
|
||||
ProjectFlockFormValues,
|
||||
UpdateProjectFlockFormSchema,
|
||||
} from '@/components/pages/production/project-flock/form/ProjectFlockForm.schema';
|
||||
import {
|
||||
ProjectFlockApprovalPayload,
|
||||
CreateProjectFlockPayload,
|
||||
PeriodFlock,
|
||||
ProjectFlock,
|
||||
} from '@/types/api/production/project-flock';
|
||||
import toast from 'react-hot-toast';
|
||||
import TextInput from '@/components/input/TextInput';
|
||||
import { Kandang } from '@/types/api/master-data/kandang';
|
||||
import Collapse from '@/components/Collapse';
|
||||
import { ProjectFlockApi } from '@/services/api/production';
|
||||
import { BaseApiResponse } from '@/types/api/api-general';
|
||||
import { FLOCK_CATEGORY_OPTIONS } from '@/config/constant';
|
||||
import { useModal } from '@/components/Modal';
|
||||
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||
import ProjectFlockKandangTable from './ProjectFlockKandangTable';
|
||||
|
||||
interface ProjectFlockFormProps {
|
||||
formType?: 'add' | 'edit' | 'detail';
|
||||
initialValues?: ProjectFlock;
|
||||
refreshProjectFlocks?: KeyedMutator<
|
||||
BaseApiResponse<ProjectFlock> | undefined
|
||||
>;
|
||||
}
|
||||
|
||||
const ProjectFlockForm = ({
|
||||
formType = 'add',
|
||||
initialValues,
|
||||
refreshProjectFlocks,
|
||||
}: ProjectFlockFormProps) => {
|
||||
// State
|
||||
const router = useRouter();
|
||||
const [projectFlockFormErrorMessage, setProjectFlockFormErrorMessage] =
|
||||
useState('');
|
||||
const [selectedArea, setSelectedArea] = useState('');
|
||||
|
||||
const [selectedLocation, setSelectedLocation] = useState('');
|
||||
const [disabledLocation, setDisabledLocation] = useState(true);
|
||||
const [optionsLocation, setOptionsLocation] = useState<OptionType[]>([]);
|
||||
|
||||
const [openSelectKandangs, setOpenSelectKandangs] = useState(
|
||||
initialValues?.kandangs && initialValues?.kandangs?.length > 0
|
||||
);
|
||||
const [optionsKandang, setOptionsKandang] = useState<Kandang[]>(
|
||||
initialValues?.kandangs ?? []
|
||||
);
|
||||
|
||||
const [selectedFlock, setSelectedFlock] = useState<number>(
|
||||
initialValues?.flock?.id ?? 0
|
||||
);
|
||||
|
||||
const deleteModal = useModal();
|
||||
const confirmModal = useModal();
|
||||
|
||||
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||
const [isApproveLoading, setIsApproveLoading] = useState(false);
|
||||
const [isApprovedDisabled, setIsApprovedDisabled] = useState(
|
||||
initialValues?.approval.step_name == 'Pengajuan' ? false : true
|
||||
);
|
||||
const [isRejectedDisabled, setIsRejectedDisabled] = useState(
|
||||
!isApprovedDisabled
|
||||
);
|
||||
const [approvalAction, setApprovalAction] = useState<'APPROVED' | 'REJECTED'>(
|
||||
!isApprovedDisabled ? 'APPROVED' : 'REJECTED'
|
||||
);
|
||||
|
||||
const [rowSelection, setRowSelection] = useState<Record<string, boolean>>(
|
||||
() =>
|
||||
Object.fromEntries(
|
||||
(initialValues?.kandangs ?? []).map((k: Kandang) => [
|
||||
k.id.toString(),
|
||||
true,
|
||||
])
|
||||
)
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (initialValues?.approval?.step_name) {
|
||||
const approvedDisabled = initialValues.approval.step_name !== 'Pengajuan';
|
||||
setIsApprovedDisabled(approvedDisabled);
|
||||
setIsRejectedDisabled(!approvedDisabled);
|
||||
setApprovalAction(!approvedDisabled ? 'APPROVED' : 'REJECTED');
|
||||
}
|
||||
}, [initialValues]);
|
||||
|
||||
// Fetch Data
|
||||
const flockUrl = `${FlockApi.basePath}?${new URLSearchParams({
|
||||
search: '',
|
||||
}).toString()}`;
|
||||
const { data: flocks, isLoading: isLoadingFlocks } = useSWR(
|
||||
flockUrl,
|
||||
FlockApi.getAllFetcher
|
||||
);
|
||||
|
||||
const areaUrl = `${AreaApi.basePath}?${new URLSearchParams({
|
||||
search: '',
|
||||
}).toString()}`;
|
||||
const { data: areas, isLoading: isLoadingAreas } = useSWR(
|
||||
areaUrl,
|
||||
AreaApi.getAllFetcher
|
||||
);
|
||||
|
||||
const locationUrl = `${LocationApi.basePath}?${new URLSearchParams({
|
||||
search: '',
|
||||
area_id: selectedArea,
|
||||
}).toString()}`;
|
||||
const { data: locations, isLoading: isLoadingLocations } = useSWR(
|
||||
locationUrl,
|
||||
LocationApi.getAllFetcher
|
||||
);
|
||||
|
||||
const fcrUrl = `${FcrApi.basePath}?${new URLSearchParams({
|
||||
search: '',
|
||||
}).toString()}`;
|
||||
const { data: fcrs, isLoading: isLoadingFcrs } = useSWR(
|
||||
fcrUrl,
|
||||
FcrApi.getAllFetcher
|
||||
);
|
||||
|
||||
const kandangUrl = `${KandangApi.basePath}?${new URLSearchParams({
|
||||
search: '',
|
||||
location_id: selectedLocation == '' ? '0' : selectedLocation,
|
||||
}).toString()}`;
|
||||
const { data: kandang, isLoading: isLoadingKandang, mutate: refreshKandang} = useSWR(
|
||||
kandangUrl,
|
||||
KandangApi.getAllFetcher
|
||||
);
|
||||
|
||||
const getPeriodFlocksUrl = `flocks/${selectedFlock}/periods`;
|
||||
|
||||
const { data: periodFlocks, isLoading: isLoadingPeriodFlocks } = useSWR(
|
||||
getPeriodFlocksUrl,
|
||||
() =>
|
||||
ProjectFlockApi.customRequest<BaseApiResponse<PeriodFlock>, 'GET'>(
|
||||
getPeriodFlocksUrl,
|
||||
{ method: 'GET' }
|
||||
)
|
||||
);
|
||||
|
||||
// Map Data to Options
|
||||
const optionsArea = isResponseSuccess(areas)
|
||||
? areas?.data.map((area) => ({
|
||||
value: area.id,
|
||||
label: area.name,
|
||||
}))
|
||||
: [];
|
||||
const optionsFcr = isResponseSuccess(fcrs)
|
||||
? fcrs?.data.map((fcr) => ({
|
||||
value: fcr.id,
|
||||
label: fcr.name,
|
||||
}))
|
||||
: [];
|
||||
const optionsFlock = isResponseSuccess(flocks)
|
||||
? flocks?.data.map((flock) => ({
|
||||
value: flock.id,
|
||||
label: flock.name,
|
||||
}))
|
||||
: [];
|
||||
|
||||
useEffect(() => {
|
||||
if (isResponseSuccess(locations)) {
|
||||
const options = locations.data.map((location) => ({
|
||||
value: location.id,
|
||||
label: location.name,
|
||||
}));
|
||||
setOptionsLocation(options);
|
||||
}
|
||||
}, [locations, setSelectedLocation]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isResponseSuccess(kandang)) {
|
||||
if (selectedLocation) {
|
||||
setOptionsKandang(kandang.data);
|
||||
setOpenSelectKandangs(true);
|
||||
} else {
|
||||
setOptionsKandang([]);
|
||||
setOpenSelectKandangs(false);
|
||||
formik.setFieldValue('kandang_ids', []);
|
||||
}
|
||||
}
|
||||
}, [kandang]);
|
||||
useEffect(() => {
|
||||
if (initialValues?.kandangs) {
|
||||
refreshKandang();
|
||||
setOpenSelectKandangs(true);
|
||||
|
||||
const newRowSelection = Object.fromEntries(
|
||||
initialValues.kandangs.map((k: Kandang) => [
|
||||
k.id.toString(),
|
||||
true,
|
||||
])
|
||||
);
|
||||
setRowSelection(newRowSelection);
|
||||
}
|
||||
}, [initialValues, refreshKandang]);
|
||||
|
||||
// Options Handler
|
||||
const areaChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||
formik.setFieldValue('area_id', (val as OptionType)?.value);
|
||||
formik.setFieldValue('area', val);
|
||||
|
||||
formik.setFieldTouched('area_id', true);
|
||||
|
||||
setSelectedArea((val as OptionType)?.value as string);
|
||||
setSelectedLocation('');
|
||||
const disabled = (val as OptionType)?.value == null;
|
||||
setDisabledLocation(disabled);
|
||||
|
||||
formik.setFieldValue('location', null);
|
||||
formik.setFieldValue('location_id', 0);
|
||||
formik.setFieldTouched('location', false);
|
||||
formik.setFieldTouched('location_id', false);
|
||||
};
|
||||
|
||||
const locationChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||
setSelectedLocation((val as OptionType)?.value as string);
|
||||
optionChangeHandler(val, 'location');
|
||||
formik.setFieldValue('kandang_ids', []);
|
||||
};
|
||||
|
||||
const optionChangeHandler = (
|
||||
val: OptionType | OptionType[] | null,
|
||||
inputName: string
|
||||
) => {
|
||||
formik.setFieldValue(inputName, val);
|
||||
formik.setFieldValue(
|
||||
`${inputName}_id`,
|
||||
val ? (val as OptionType)?.value : 0
|
||||
);
|
||||
|
||||
formik.setFieldTouched(`${inputName}_id`, true);
|
||||
};
|
||||
|
||||
const categoryChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||
formik.setFieldValue('category', (val as OptionType)?.value);
|
||||
formik.setFieldValue('category_option', val);
|
||||
formik.setFieldTouched('category', true);
|
||||
};
|
||||
|
||||
// Submit Handler
|
||||
const createProjectFlockHandler = async (
|
||||
payload: CreateProjectFlockPayload
|
||||
) => {
|
||||
const createProjectFlockRes = await ProjectFlockApi.create(payload);
|
||||
|
||||
if (isResponseSuccess(createProjectFlockRes)) {
|
||||
toast.success(createProjectFlockRes?.message as string);
|
||||
router.push('/production/project-flock');
|
||||
}
|
||||
if (isResponseError(createProjectFlockRes)) {
|
||||
setProjectFlockFormErrorMessage(createProjectFlockRes?.message as string);
|
||||
toast.error(createProjectFlockRes?.message as string);
|
||||
}
|
||||
};
|
||||
const updateProjectFlockHandler = async (
|
||||
payload: CreateProjectFlockPayload
|
||||
) => {
|
||||
const updateProjectFlockRes = await ProjectFlockApi.update(
|
||||
initialValues?.id as number,
|
||||
payload
|
||||
);
|
||||
|
||||
if (isResponseSuccess(updateProjectFlockRes)) {
|
||||
toast.success(updateProjectFlockRes?.message as string);
|
||||
router.push('/production/project-flock');
|
||||
}
|
||||
if (isResponseError(updateProjectFlockRes)) {
|
||||
setProjectFlockFormErrorMessage(updateProjectFlockRes?.message as string);
|
||||
toast.error(updateProjectFlockRes?.message as string);
|
||||
}
|
||||
};
|
||||
|
||||
// Formik InitialValue
|
||||
const formikInitialValues = useMemo<ProjectFlockFormValues>(() => {
|
||||
return {
|
||||
name: initialValues?.name ?? '',
|
||||
flock: initialValues?.flock
|
||||
? {
|
||||
value: initialValues.flock.id,
|
||||
label: initialValues.flock.name,
|
||||
}
|
||||
: null,
|
||||
area: initialValues?.area
|
||||
? {
|
||||
value: initialValues.area.id,
|
||||
label: initialValues.area.name,
|
||||
}
|
||||
: null,
|
||||
category_option: initialValues?.category
|
||||
? {
|
||||
value: initialValues.category,
|
||||
label: initialValues.category,
|
||||
}
|
||||
: null,
|
||||
fcr: initialValues?.fcr
|
||||
? {
|
||||
value: initialValues.fcr.id,
|
||||
label: initialValues.fcr.name,
|
||||
}
|
||||
: null,
|
||||
location: initialValues?.location
|
||||
? {
|
||||
value: initialValues.location.id,
|
||||
label: initialValues.location.name,
|
||||
}
|
||||
: null,
|
||||
flock_id: initialValues?.flock?.id ?? 0,
|
||||
area_id: initialValues?.area?.id ?? 0,
|
||||
category: initialValues?.category as NonNullable<
|
||||
'GROWING' | 'LAYING' | undefined
|
||||
>,
|
||||
fcr_id: initialValues?.fcr?.id ?? 0,
|
||||
location_id: initialValues?.location?.id ?? 0,
|
||||
period: initialValues?.period ?? 0,
|
||||
kandang_ids: initialValues?.kandangs?.map((k: Kandang) => k.id) as (
|
||||
| number
|
||||
| undefined
|
||||
)[],
|
||||
};
|
||||
}, [initialValues]);
|
||||
|
||||
// Formik
|
||||
const formik = useFormik<ProjectFlockFormValues>({
|
||||
initialValues: formikInitialValues,
|
||||
enableReinitialize: true,
|
||||
validationSchema:
|
||||
formType == 'add' ? ProjectFlockFormSchema : UpdateProjectFlockFormSchema,
|
||||
validateOnBlur: true,
|
||||
validateOnChange: true,
|
||||
validateOnMount: true,
|
||||
onSubmit: async (values) => {
|
||||
setProjectFlockFormErrorMessage('');
|
||||
const payload: CreateProjectFlockPayload = {
|
||||
flock_id: values.flock_id as number,
|
||||
area_id: values.area_id as number,
|
||||
category: values.category as string,
|
||||
fcr_id: values.fcr_id as number,
|
||||
location_id: values.location_id as number,
|
||||
period: values.period as number,
|
||||
kandang_ids: values.kandang_ids as number[],
|
||||
};
|
||||
|
||||
switch (formType) {
|
||||
case 'add':
|
||||
await createProjectFlockHandler(payload);
|
||||
break;
|
||||
case 'edit':
|
||||
await updateProjectFlockHandler(payload);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const { setValues: formikSetValues } = formik;
|
||||
// Effect Initial
|
||||
useEffect(() => {
|
||||
if (formType == 'detail') {
|
||||
formik.setFieldValue('area', {
|
||||
value: initialValues?.area.id,
|
||||
label: initialValues?.area.name,
|
||||
});
|
||||
formik.setFieldValue('area_id', initialValues?.area_id);
|
||||
if (initialValues?.area_id) {
|
||||
setSelectedArea(initialValues?.area_id.toString() as string);
|
||||
}
|
||||
|
||||
formik.setFieldValue('period', initialValues?.period);
|
||||
}
|
||||
}, [initialValues, setSelectedArea, formType]);
|
||||
|
||||
useEffect(() => {
|
||||
formikSetValues(formikInitialValues);
|
||||
}, [formikSetValues, formikInitialValues]);
|
||||
|
||||
// Aktifkan lokasi jika formType = 'detail'
|
||||
useEffect(() => {
|
||||
if (formType === 'detail') {
|
||||
setDisabledLocation(false);
|
||||
}
|
||||
}, [formType]);
|
||||
|
||||
// Set lokasi otomatis berdasarkan initialValues saat formType = 'detail'
|
||||
useEffect(() => {
|
||||
if (formType != 'add' && initialValues?.location?.id) {
|
||||
setSelectedLocation(initialValues.location?.id.toString());
|
||||
setDisabledLocation(false); // biar dropdown lokasi aktif juga
|
||||
}
|
||||
}, [formType, initialValues]);
|
||||
|
||||
useEffect(() => {
|
||||
formik.validateForm();
|
||||
}, [formik.values]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isResponseSuccess(periodFlocks)) {
|
||||
formik.setFieldValue('period', periodFlocks.data.next_period);
|
||||
}
|
||||
}, [periodFlocks]);
|
||||
|
||||
useEffect(() => {
|
||||
const selectedRowIds = Object.keys(rowSelection)
|
||||
.filter((id) => rowSelection[id])
|
||||
.map((id) => parseInt(id));
|
||||
formikSetValues({
|
||||
...formik.values,
|
||||
kandang_ids: selectedRowIds,
|
||||
});
|
||||
}, [rowSelection, formikSetValues]);
|
||||
|
||||
// Actions handler
|
||||
const confirmationModalDeleteClickHandler = async () => {
|
||||
setIsDeleteLoading(true);
|
||||
const deleteProjectFlockRes = await ProjectFlockApi.delete(
|
||||
initialValues?.id as number
|
||||
);
|
||||
|
||||
if (isResponseSuccess(deleteProjectFlockRes)) {
|
||||
toast.success(deleteProjectFlockRes?.message as string);
|
||||
router.push('/production/project-flock');
|
||||
}
|
||||
if (isResponseError(deleteProjectFlockRes)) {
|
||||
toast.error(deleteProjectFlockRes?.message as string);
|
||||
}
|
||||
setIsDeleteLoading(false);
|
||||
};
|
||||
|
||||
const confirmationModalClickHandler = async ({
|
||||
action = 'APPROVED',
|
||||
}: {
|
||||
action: 'APPROVED' | 'REJECTED';
|
||||
}) => {
|
||||
if (initialValues?.id === undefined) return;
|
||||
setIsApproveLoading(true);
|
||||
const approveProjectFlockRes = await ProjectFlockApi.customRequest<
|
||||
BaseApiResponse<ProjectFlock>,
|
||||
ProjectFlockApprovalPayload
|
||||
>(`/approvals`, {
|
||||
method: 'POST',
|
||||
payload: {
|
||||
action: action,
|
||||
approvable_ids: [initialValues.id],
|
||||
},
|
||||
});
|
||||
|
||||
if (isResponseSuccess(approveProjectFlockRes)) {
|
||||
if (refreshProjectFlocks) {
|
||||
await refreshProjectFlocks();
|
||||
}
|
||||
// if (action == 'APPROVED') {
|
||||
// setIsApprovedDisabled(true);
|
||||
// setIsRejectedDisabled(false);
|
||||
// }
|
||||
// if (action == 'REJECTED') {
|
||||
// setIsRejectedDisabled(true);
|
||||
// setIsApprovedDisabled(false);
|
||||
// }
|
||||
toast.success(approveProjectFlockRes.message as string);
|
||||
}
|
||||
if (isResponseError(approveProjectFlockRes)) {
|
||||
toast.error(approveProjectFlockRes?.message as string);
|
||||
}
|
||||
confirmModal.closeModal();
|
||||
setIsApproveLoading(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<section className='w-full'>
|
||||
<header className='flex flex-col gap-4'>
|
||||
<Button
|
||||
href='/production/project-flock'
|
||||
variant='link'
|
||||
className='w-fit p-0 text-primary'
|
||||
>
|
||||
<Icon icon='uil:arrow-left' width={24} height={24} />
|
||||
Kembali
|
||||
</Button>
|
||||
|
||||
<h1 className='text-2xl font-bold text-center'>
|
||||
{formType === 'add' && 'Tambah Project Flock'}
|
||||
{formType === 'detail' && 'Detail Project Flock'}
|
||||
</h1>
|
||||
</header>
|
||||
{projectFlockFormErrorMessage && (
|
||||
<div className='my-4'>
|
||||
<div role='alert' className='alert alert-error'>
|
||||
<Icon
|
||||
icon='material-symbols:error-outline'
|
||||
width={24}
|
||||
height={24}
|
||||
/>
|
||||
<span>{projectFlockFormErrorMessage}</span>
|
||||
<Button
|
||||
onClick={() => {
|
||||
setProjectFlockFormErrorMessage('');
|
||||
}}
|
||||
variant='link'
|
||||
>
|
||||
<Icon icon='material-symbols:close' width={24} height={24} />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{formType == 'detail' && (
|
||||
<div className='w-full flex flex-col sm:flex-row gap-2 py-4'>
|
||||
<Button
|
||||
variant='outline'
|
||||
color='success'
|
||||
onClick={() => {
|
||||
if (initialValues?.id) {
|
||||
setApprovalAction('APPROVED');
|
||||
confirmModal.openModal();
|
||||
}
|
||||
}}
|
||||
disabled={!initialValues?.id || isApprovedDisabled}
|
||||
className='w-full sm:w-fit'
|
||||
>
|
||||
<Icon icon='material-symbols:check' width={24} height={24} />
|
||||
Approve
|
||||
</Button>
|
||||
<Button
|
||||
variant='outline'
|
||||
color='error'
|
||||
onClick={() => {
|
||||
if (initialValues?.id) {
|
||||
setApprovalAction('REJECTED');
|
||||
confirmModal.openModal();
|
||||
}
|
||||
}}
|
||||
disabled={!initialValues?.id || isRejectedDisabled}
|
||||
className='w-full sm:w-fit'
|
||||
>
|
||||
<Icon icon='mdi:times' width={24} height={24} />
|
||||
Reject
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<form
|
||||
className='w-auto h-auto'
|
||||
onSubmit={formik.handleSubmit}
|
||||
onReset={formik.handleReset}
|
||||
>
|
||||
<div className='card bg-base-100 shadow w-full mb-6'>
|
||||
<div className='card-body'>
|
||||
<div className='card-title mb-4'>Informasi Umum</div>
|
||||
|
||||
<div className='grid sm:grid-cols-2 gap-4'>
|
||||
<SelectInput
|
||||
required
|
||||
label='Area'
|
||||
value={formik.values.area as OptionType}
|
||||
onChange={areaChangeHandler}
|
||||
options={optionsArea}
|
||||
isLoading={isLoadingAreas}
|
||||
isError={
|
||||
formik.touched.area_id && Boolean(formik.errors.area_id)
|
||||
}
|
||||
errorMessage={formik.errors.area_id as string}
|
||||
isClearable
|
||||
isDisabled={formType === 'detail'}
|
||||
/>
|
||||
<SelectInput
|
||||
required
|
||||
label='Flock'
|
||||
value={formik.values.flock as OptionType}
|
||||
onChange={(val) => {
|
||||
optionChangeHandler(val, 'flock');
|
||||
setSelectedFlock((val as OptionType)?.value as number);
|
||||
}}
|
||||
options={optionsFlock}
|
||||
isLoading={isLoadingFlocks}
|
||||
isError={
|
||||
formik.touched.flock_id && Boolean(formik.errors.flock_id)
|
||||
}
|
||||
errorMessage={formik.errors.flock_id as string}
|
||||
isClearable
|
||||
isDisabled={formType === 'detail'}
|
||||
/>
|
||||
<SelectInput
|
||||
required
|
||||
label='Lokasi'
|
||||
value={formik.values.location as OptionType}
|
||||
onChange={locationChangeHandler}
|
||||
options={optionsLocation}
|
||||
isLoading={isLoadingLocations}
|
||||
isError={
|
||||
formik.touched.location_id &&
|
||||
Boolean(formik.errors.location_id)
|
||||
}
|
||||
errorMessage={formik.errors.location_id as string}
|
||||
isClearable
|
||||
isDisabled={formType === 'detail' || disabledLocation}
|
||||
/>
|
||||
<SelectInput
|
||||
required
|
||||
label='FCR'
|
||||
value={formik.values.fcr as OptionType}
|
||||
onChange={(val) => {
|
||||
optionChangeHandler(val, 'fcr');
|
||||
}}
|
||||
options={optionsFcr}
|
||||
isLoading={isLoadingFcrs}
|
||||
isError={
|
||||
formik.touched.fcr_id && Boolean(formik.errors.fcr_id)
|
||||
}
|
||||
errorMessage={formik.errors.fcr_id as string}
|
||||
isClearable
|
||||
isDisabled={formType === 'detail'}
|
||||
/>
|
||||
<SelectInput
|
||||
required
|
||||
label='Kategori'
|
||||
value={formik.values.category_option as OptionType}
|
||||
onChange={categoryChangeHandler}
|
||||
options={FLOCK_CATEGORY_OPTIONS}
|
||||
isError={
|
||||
formik.touched.category && Boolean(formik.errors.category)
|
||||
}
|
||||
errorMessage={formik.errors.category as string}
|
||||
isClearable
|
||||
isDisabled={formType === 'detail'}
|
||||
/>
|
||||
<TextInput
|
||||
required
|
||||
type='number'
|
||||
name='period'
|
||||
label='Periode'
|
||||
placeholder='Masukkan periode yang project'
|
||||
value={formik.values.period as number}
|
||||
onChange={formik.handleChange}
|
||||
isError={
|
||||
formik.touched.period && Boolean(formik.errors.period)
|
||||
}
|
||||
errorMessage={formik.errors.period as string}
|
||||
readOnly={formType === 'detail'}
|
||||
disabled={true}
|
||||
isLoading={isLoadingPeriodFlocks}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className='card bg-base-100 shadow w-full'>
|
||||
<div className='card-body'>
|
||||
<Collapse
|
||||
title={
|
||||
<div className='card-actions justify-between w-full'>
|
||||
<div className='card-title'>Pilih Kandang</div>
|
||||
<Button
|
||||
variant='link'
|
||||
className={`text-primary rotate-${
|
||||
openSelectKandangs ? '180' : '0'
|
||||
} transition-transform hover:text-inherit me-3`}
|
||||
>
|
||||
<Icon
|
||||
icon='material-symbols:keyboard-arrow-down'
|
||||
width={24}
|
||||
height={24}
|
||||
/>
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
className='sm:w-full'
|
||||
titleClassName='w-full p-0!'
|
||||
onOpenChange={setOpenSelectKandangs}
|
||||
open={openSelectKandangs}
|
||||
>
|
||||
<div className='overflow-x-auto'>
|
||||
{isLoadingKandang && (
|
||||
<span className='loading loading-dots loading-xl'></span>
|
||||
)}
|
||||
<ProjectFlockKandangTable
|
||||
listKandang={optionsKandang}
|
||||
rowSelection={rowSelection}
|
||||
setRowSelection={setRowSelection}
|
||||
selectedIds={formik.values.kandang_ids}
|
||||
formType={formType}
|
||||
/>
|
||||
</div>
|
||||
</Collapse>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='flex flex-row justify-center gap-2 flex-wrap my-6'>
|
||||
{formType !== 'detail' && (
|
||||
<div className='flex flex-row justify-end gap-2'>
|
||||
<Button
|
||||
type='button'
|
||||
color='warning'
|
||||
className='px-4'
|
||||
onClick={formik.handleReset}
|
||||
>
|
||||
Reset
|
||||
</Button>
|
||||
<Button
|
||||
type='submit'
|
||||
color='primary'
|
||||
isLoading={formik.isSubmitting}
|
||||
disabled={!formik.isValid || formik.isSubmitting}
|
||||
className='px-4'
|
||||
>
|
||||
Submit
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
{formType != 'add' && (
|
||||
<div className='w-full'>
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (initialValues?.id) {
|
||||
deleteModal.openModal();
|
||||
}
|
||||
}}
|
||||
color='error'
|
||||
>
|
||||
<Icon
|
||||
icon='material-symbols:delete-outline-rounded'
|
||||
width={16}
|
||||
height={16}
|
||||
className='justify-start text-sm'
|
||||
/>
|
||||
Delete
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<ConfirmationModal
|
||||
ref={deleteModal.ref}
|
||||
type='error'
|
||||
text={`Apakah anda yakin ingin menghapus data Project Flock ini (${initialValues?.flock?.name} - ${initialValues?.area?.name})?`}
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: 'error',
|
||||
isLoading: isDeleteLoading,
|
||||
onClick: confirmationModalDeleteClickHandler,
|
||||
}}
|
||||
/>
|
||||
|
||||
<ConfirmationModal
|
||||
ref={confirmModal.ref}
|
||||
type={approvalAction == 'APPROVED' ? 'success' : 'error'}
|
||||
text={`Apakah anda yakin ingin ${
|
||||
approvalAction == 'APPROVED' ? 'approve' : 'reject'
|
||||
} Project Flock berikut? (${initialValues?.flock?.name} - ${
|
||||
initialValues?.area?.name
|
||||
})?`}
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: approvalAction == 'APPROVED' ? 'success' : 'error',
|
||||
isLoading: isApproveLoading,
|
||||
onClick: () => {
|
||||
confirmationModalClickHandler({
|
||||
action: approvalAction,
|
||||
});
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProjectFlockForm;
|
||||
@@ -0,0 +1,146 @@
|
||||
'use client';
|
||||
|
||||
import CheckboxInput from '@/components/input/CheckboxInput';
|
||||
import PillBadge from '@/components/PillBadge';
|
||||
import Table from '@/components/Table';
|
||||
import { cn } from '@/lib/helper';
|
||||
import { Kandang } from '@/types/api/master-data/kandang';
|
||||
import { OnChangeFn } from '@tanstack/react-table';
|
||||
|
||||
const ProjectFlockKandangTable = ({
|
||||
listKandang,
|
||||
rowSelection,
|
||||
setRowSelection,
|
||||
selectedIds,
|
||||
formType = 'add',
|
||||
}: {
|
||||
listKandang: Kandang[];
|
||||
rowSelection: Record<string, boolean>;
|
||||
setRowSelection: OnChangeFn<Record<string, boolean>>;
|
||||
selectedIds: (number | undefined)[];
|
||||
formType: 'add' | 'edit' | 'detail';
|
||||
}) => {
|
||||
console.log('selectedIds');
|
||||
console.log(selectedIds);
|
||||
return (
|
||||
<Table<Kandang>
|
||||
data={listKandang}
|
||||
columns={[
|
||||
{
|
||||
id: 'select',
|
||||
header: ({ table }) => {
|
||||
const allRows = table.getRowModel().rows;
|
||||
const selectableRows = allRows.filter(
|
||||
(row) =>
|
||||
row.original.status == 'NON_ACTIVE' ||
|
||||
row.original.status == 'PENGAJUAN'
|
||||
);
|
||||
|
||||
const allSelected =
|
||||
selectableRows.every((row) => row.getIsSelected()) &&
|
||||
selectableRows.length != 0 && formType != 'detail';
|
||||
|
||||
const someSelected =
|
||||
selectableRows.some((row) => row.getIsSelected()) && !allSelected && formType != 'detail';
|
||||
|
||||
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}
|
||||
disabled={
|
||||
listKandang.filter(
|
||||
(kandang) =>
|
||||
kandang.status == 'NON_ACTIVE' ||
|
||||
kandang.status == 'PENGAJUAN'
|
||||
).length == 0 || formType == 'detail'
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<CheckboxInput
|
||||
name='row'
|
||||
checked={
|
||||
(row.getIsSelected() &&
|
||||
(row.original.status == 'NON_ACTIVE' ||
|
||||
row.original.status == 'PENGAJUAN')) ||
|
||||
selectedIds.includes(row.original.id)
|
||||
}
|
||||
disabled={
|
||||
!row.getCanSelect() ||
|
||||
(row.original.status != 'NON_ACTIVE' &&
|
||||
row.original.status != 'PENGAJUAN') ||
|
||||
formType == 'detail'
|
||||
}
|
||||
indeterminate={row.getIsSomeSelected()}
|
||||
onChange={row.getToggleSelectedHandler()}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorFn: (row) => row.name,
|
||||
header: 'Kandang',
|
||||
},
|
||||
{
|
||||
accessorFn: (row) => row.status,
|
||||
header: 'Status',
|
||||
cell: (props) => {
|
||||
return (
|
||||
<PillBadge
|
||||
color={(() => {
|
||||
switch (props.row.original.status) {
|
||||
case 'ACTIVE':
|
||||
return 'red';
|
||||
case 'PENGAJUAN':
|
||||
return 'green';
|
||||
case 'NON_ACTIVE':
|
||||
return 'blue';
|
||||
default:
|
||||
return 'gray';
|
||||
}
|
||||
})()}
|
||||
content={props.row.original.status
|
||||
.toLowerCase()
|
||||
.replace(/_/g, ' ')
|
||||
.replace(/\b\w/g, (char) => char.toUpperCase())}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorFn: (row) => row.pic?.name,
|
||||
header: 'Penanggung Jawab',
|
||||
},
|
||||
]}
|
||||
className={{
|
||||
containerClassName: cn({
|
||||
'mb-20': listKandang?.length === 0,
|
||||
}),
|
||||
tableWrapperClassName: 'overflow-x-auto min-h-full!',
|
||||
tableClassName: 'font-inter w-full table-auto min-h-full!',
|
||||
headerRowClassName: 'border-b border-b-gray-200',
|
||||
headerColumnClassName:
|
||||
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
|
||||
bodyRowClassName: 'border-b border-b-gray-200',
|
||||
bodyColumnClassName:
|
||||
'px-6 py-3 last:flex last:flex-row last:justify-end',
|
||||
paginationClassName: 'hidden',
|
||||
}}
|
||||
rowSelection={rowSelection}
|
||||
setRowSelection={setRowSelection}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProjectFlockKandangTable;
|
||||
@@ -0,0 +1,704 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import useSWR from 'swr';
|
||||
import { Icon } from '@iconify/react';
|
||||
import { SortingState } from '@tanstack/react-table';
|
||||
import { cn } from '@/lib/helper';
|
||||
import { useModal } from '@/components/Modal';
|
||||
import Button from '@/components/Button';
|
||||
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||
import { OptionType } from '@/components/input/SelectInput';
|
||||
import SelectInput from '@/components/input/SelectInput';
|
||||
import { ROWS_OPTIONS } from '@/config/constant';
|
||||
import CheckboxInput from '@/components/input/CheckboxInput';
|
||||
import { TableToolbar } from '@/components/table/TableToolbar';
|
||||
import { TableRowSizeSelector } from '@/components/table/TableRowSizeSelector';
|
||||
import Table from '@/components/Table';
|
||||
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
|
||||
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
|
||||
import { type CellContext } from '@tanstack/react-table';
|
||||
import { type Recording } from '@/types/api/production/recording';
|
||||
import { type BaseApiResponse } from '@/types/api/api-general';
|
||||
import { RecordingApi } from '@/services/api/production';
|
||||
import { AreaApi } from '@/services/api/master-data';
|
||||
import { LocationApi } from '@/services/api/master-data';
|
||||
import { KandangApi } from '@/services/api/master-data';
|
||||
import { isResponseSuccess, isResponseError } from '@/lib/api-helper';
|
||||
import { useTableFilter } from '@/services/hooks/useTableFilter';
|
||||
import toast from 'react-hot-toast';
|
||||
|
||||
const RowOptionsMenu = ({
|
||||
type = 'dropdown',
|
||||
props,
|
||||
deleteClickHandler,
|
||||
}: {
|
||||
type: 'dropdown' | 'collapse';
|
||||
props: CellContext<Recording, 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 flex flex-col gap-1 bg-base-100 rounded-box z-10 border border-black/10 shadow'
|
||||
)}
|
||||
>
|
||||
<Button
|
||||
href={`recording/detail/?recordingId=${props.row.original.id}`}
|
||||
variant='ghost'
|
||||
color='primary'
|
||||
className='justify-start text-sm'
|
||||
>
|
||||
<Icon icon='mdi:eye-outline' width={16} height={16} />
|
||||
Detail
|
||||
</Button>
|
||||
<Button
|
||||
href={`recording/detail/edit/?recordingId=${props.row.original.id}`}
|
||||
variant='ghost'
|
||||
color='warning'
|
||||
className='justify-start text-sm'
|
||||
>
|
||||
<Icon icon='mdi:pencil-outline' width={16} height={16} />
|
||||
Edit
|
||||
</Button>
|
||||
<Button
|
||||
onClick={deleteClickHandler}
|
||||
variant='ghost'
|
||||
color='error'
|
||||
className='text-error hover:text-inherit'
|
||||
>
|
||||
<Icon
|
||||
icon='mdi:delete-outline'
|
||||
width={16}
|
||||
height={16}
|
||||
className='justify-start text-sm'
|
||||
/>
|
||||
Delete
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const RecordingTable = () => {
|
||||
const {
|
||||
state: tableFilterState,
|
||||
updateFilter,
|
||||
setPage,
|
||||
setPageSize,
|
||||
toQueryString: getTableFilterQueryString,
|
||||
} = useTableFilter({
|
||||
initial: {
|
||||
search: '',
|
||||
areaFilter: '',
|
||||
locationFilter: '',
|
||||
kandangFilter: '',
|
||||
periodFilter: '',
|
||||
},
|
||||
paramMap: {
|
||||
page: 'page',
|
||||
pageSize: 'limit',
|
||||
search: 'search',
|
||||
areaFilter: 'area_id',
|
||||
locationFilter: 'location_id',
|
||||
kandangFilter: 'kandang_id',
|
||||
periodFilter: 'period',
|
||||
},
|
||||
});
|
||||
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});
|
||||
const [selectedRecording, setSelectedRecording] = useState<Recording | undefined>(undefined);
|
||||
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||
const [isBulkApproveLoading, setIsBulkApproveLoading] = useState(false);
|
||||
const [isBulkRejectLoading, setIsBulkRejectLoading] = useState(false);
|
||||
|
||||
const singleDeleteModal = useModal();
|
||||
const bulkApproveModal = useModal();
|
||||
const bulkRejectModal = useModal();
|
||||
|
||||
// State for dropdown search
|
||||
const [locationSelectInputValue, setLocationSelectInputValue] = useState('');
|
||||
const [areaSelectInputValue, setAreaSelectInputValue] = useState('');
|
||||
const [kandangSelectInputValue, setKandangSelectInputValue] = useState('');
|
||||
|
||||
const [selectedArea, setSelectedArea] = useState<OptionType | null>(null);
|
||||
const [selectedLocation, setSelectedLocation] = useState<OptionType | null>(null);
|
||||
const [selectedKandang, setSelectedKandang] = useState<OptionType | null>(null);
|
||||
|
||||
const {
|
||||
data: recordings,
|
||||
isLoading,
|
||||
mutate: refreshRecordings,
|
||||
} = useSWR(
|
||||
`${RecordingApi.basePath}${getTableFilterQueryString()}`,
|
||||
RecordingApi.getAllFetcher
|
||||
);
|
||||
|
||||
// Fetch data for dropdowns
|
||||
const areaUrl = `${AreaApi.basePath}?${new URLSearchParams({
|
||||
search: areaSelectInputValue,
|
||||
limit: '100',
|
||||
}).toString()}`;
|
||||
const {
|
||||
data: areas,
|
||||
isLoading: isLoadingAreas,
|
||||
} = useSWR(areaUrl, AreaApi.getAllFetcher);
|
||||
|
||||
const locationUrl = `${LocationApi.basePath}?${new URLSearchParams({
|
||||
search: locationSelectInputValue,
|
||||
area_id: selectedArea != null ? selectedArea.value.toString() : '',
|
||||
limit: '100',
|
||||
}).toString()}`;
|
||||
const {
|
||||
data: locations,
|
||||
isLoading: isLoadingLocations,
|
||||
} = useSWR(locationUrl, LocationApi.getAllFetcher);
|
||||
|
||||
const kandangUrl = `${KandangApi.basePath}?${new URLSearchParams({
|
||||
search: kandangSelectInputValue,
|
||||
location_id:
|
||||
selectedLocation != null ? selectedLocation.value.toString() : '',
|
||||
limit: '100',
|
||||
}).toString()}`;
|
||||
const {
|
||||
data: kandangs,
|
||||
isLoading: isLoadingKandang,
|
||||
} = useSWR(kandangUrl, KandangApi.getAllFetcher);
|
||||
|
||||
// Data to Options Mapping
|
||||
const optionsArea = isResponseSuccess(areas)
|
||||
? areas?.data.map((area) => ({
|
||||
value: area.id,
|
||||
label: area.name,
|
||||
}))
|
||||
: [];
|
||||
const optionsLocation = isResponseSuccess(locations)
|
||||
? locations?.data.map((location) => ({
|
||||
value: location.id,
|
||||
label: location.name,
|
||||
}))
|
||||
: [];
|
||||
const optionsKandang = isResponseSuccess(kandangs)
|
||||
? kandangs?.data.map((kandang) => ({
|
||||
value: kandang.id,
|
||||
label: kandang.name,
|
||||
}))
|
||||
: [];
|
||||
|
||||
const searchChangeHandler = useCallback(
|
||||
(e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
updateFilter('search', e.target.value);
|
||||
setPage(1);
|
||||
},
|
||||
[updateFilter, setPage]
|
||||
);
|
||||
|
||||
const pageSizeChangeHandler = useCallback(
|
||||
(val: OptionType | OptionType[] | null) => {
|
||||
const newVal = val as OptionType;
|
||||
setPageSize(newVal.value as number);
|
||||
setPage(1);
|
||||
},
|
||||
[setPageSize, setPage]
|
||||
);
|
||||
|
||||
const paginatedData = useMemo(() => {
|
||||
if (!recordings || recordings.status !== 'success') return [];
|
||||
|
||||
return recordings.data;
|
||||
}, [recordings]);
|
||||
|
||||
const selectedRowIds = Object.keys(rowSelection).map((item) => parseInt(item));
|
||||
|
||||
const bulkApproveHandler = async () => {
|
||||
setIsBulkApproveLoading(true);
|
||||
|
||||
const approveResponse = await RecordingApi.customRequest<
|
||||
BaseApiResponse<Recording[]>
|
||||
>('approvals', {
|
||||
method: 'POST',
|
||||
payload: {
|
||||
action: 'APPROVED',
|
||||
approvable_ids: selectedRowIds,
|
||||
notes: 'Bulk Approved',
|
||||
},
|
||||
});
|
||||
|
||||
if (isResponseSuccess(approveResponse)) {
|
||||
await refreshRecordings();
|
||||
setRowSelection({});
|
||||
bulkApproveModal.closeModal();
|
||||
toast.success(`Successfully approved ${selectedRowIds.length} recordings!`);
|
||||
}
|
||||
if (isResponseError(approveResponse)) {
|
||||
toast.error(approveResponse?.message as string);
|
||||
bulkApproveModal.closeModal();
|
||||
}
|
||||
setIsBulkApproveLoading(false);
|
||||
};
|
||||
|
||||
const bulkRejectHandler = async () => {
|
||||
setIsBulkRejectLoading(true);
|
||||
|
||||
const rejectResponse = await RecordingApi.customRequest<
|
||||
BaseApiResponse<Recording[]>
|
||||
>('approvals', {
|
||||
method: 'POST',
|
||||
payload: {
|
||||
action: 'REJECTED',
|
||||
approvable_ids: selectedRowIds,
|
||||
notes: 'Bulk Rejected',
|
||||
},
|
||||
});
|
||||
|
||||
if (isResponseSuccess(rejectResponse)) {
|
||||
refreshRecordings();
|
||||
setRowSelection({});
|
||||
bulkRejectModal.closeModal();
|
||||
toast.success(`Successfully rejected ${selectedRowIds.length} recordings!`);
|
||||
}
|
||||
if (isResponseError(rejectResponse)) {
|
||||
toast.error(rejectResponse?.message as string);
|
||||
bulkRejectModal.closeModal();
|
||||
}
|
||||
setIsBulkRejectLoading(false);
|
||||
};
|
||||
|
||||
const singleDeleteHandler = async () => {
|
||||
setIsDeleteLoading(true);
|
||||
|
||||
await RecordingApi.delete(selectedRecording?.id as number);
|
||||
refreshRecordings();
|
||||
|
||||
singleDeleteModal.closeModal();
|
||||
toast.success('Successfully delete Recording!');
|
||||
setIsDeleteLoading(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className='flex flex-col gap-4'>
|
||||
<div className='flex flex-col gap-2 mb-4'>
|
||||
<TableToolbar
|
||||
addButton={{
|
||||
href: 'recording/add',
|
||||
label: 'Tambah Recording',
|
||||
}}
|
||||
search={{
|
||||
value: tableFilterState.search,
|
||||
onChange: searchChangeHandler,
|
||||
placeholder: 'Cari Recording',
|
||||
}}
|
||||
/>
|
||||
<TableRowSizeSelector
|
||||
value={tableFilterState.pageSize}
|
||||
onChange={pageSizeChangeHandler}
|
||||
options={ROWS_OPTIONS}
|
||||
/>
|
||||
|
||||
{/* Filter Dropdowns - Desktop */}
|
||||
<div className='hidden sm:grid sm:grid-cols-4 gap-4 mt-4'>
|
||||
<SelectInput
|
||||
label='Area'
|
||||
placeholder='Pilih Area'
|
||||
options={optionsArea}
|
||||
value={selectedArea}
|
||||
onChange={(selected) => {
|
||||
const selectedValue = selected as OptionType | null;
|
||||
setSelectedArea(selectedValue);
|
||||
setSelectedLocation(null);
|
||||
setSelectedKandang(null);
|
||||
updateFilter('areaFilter', selectedValue ? selectedValue.value.toString() : '');
|
||||
updateFilter('locationFilter', '');
|
||||
updateFilter('kandangFilter', '');
|
||||
setPage(1);
|
||||
}}
|
||||
className={{ wrapper: 'w-full' }}
|
||||
onInputChange={(value) => setAreaSelectInputValue(value)}
|
||||
isLoading={isLoadingAreas}
|
||||
isClearable
|
||||
/>
|
||||
|
||||
<SelectInput
|
||||
label='Lokasi'
|
||||
placeholder='Pilih Lokasi'
|
||||
options={optionsLocation}
|
||||
value={selectedLocation}
|
||||
onChange={(selected) => {
|
||||
const selectedValue = selected as OptionType | null;
|
||||
setSelectedLocation(selectedValue);
|
||||
setSelectedKandang(null);
|
||||
updateFilter('locationFilter', selectedValue ? selectedValue.value.toString() : '');
|
||||
updateFilter('kandangFilter', '');
|
||||
setPage(1);
|
||||
}}
|
||||
className={{ wrapper: 'w-full' }}
|
||||
onInputChange={(value) => setLocationSelectInputValue(value)}
|
||||
isLoading={isLoadingLocations}
|
||||
isClearable
|
||||
isDisabled={!selectedArea}
|
||||
/>
|
||||
|
||||
<SelectInput
|
||||
label='Kandang'
|
||||
placeholder='Pilih Kandang'
|
||||
options={optionsKandang}
|
||||
value={selectedKandang}
|
||||
onChange={(selected) => {
|
||||
const selectedValue = selected as OptionType | null;
|
||||
setSelectedKandang(selectedValue);
|
||||
updateFilter('kandangFilter', selectedValue ? selectedValue.value.toString() : '');
|
||||
setPage(1);
|
||||
}}
|
||||
className={{ wrapper: 'w-full' }}
|
||||
onInputChange={(value) => setKandangSelectInputValue(value)}
|
||||
isLoading={isLoadingKandang}
|
||||
isClearable
|
||||
isDisabled={!selectedLocation}
|
||||
/>
|
||||
|
||||
<SelectInput
|
||||
label='Periode'
|
||||
placeholder='Pilih Periode'
|
||||
options={[
|
||||
{ value: '1', label: 'Periode 1' },
|
||||
{ value: '2', label: 'Periode 2' },
|
||||
{ value: '3', label: 'Periode 3' },
|
||||
]}
|
||||
value={
|
||||
tableFilterState.periodFilter
|
||||
? { value: tableFilterState.periodFilter, label: `Periode ${tableFilterState.periodFilter}` }
|
||||
: null
|
||||
}
|
||||
onChange={(selected) => {
|
||||
const selectedValue = selected as OptionType | null;
|
||||
updateFilter('periodFilter', selectedValue ? selectedValue.value.toString() : '');
|
||||
setPage(1);
|
||||
}}
|
||||
className={{ wrapper: 'w-full' }}
|
||||
isClearable
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Filter Dropdowns - Mobile */}
|
||||
<div className='sm:hidden flex flex-col gap-3 mt-4'>
|
||||
<SelectInput
|
||||
label='Area'
|
||||
placeholder='Pilih Area'
|
||||
options={optionsArea}
|
||||
value={selectedArea}
|
||||
onChange={(selected) => {
|
||||
const selectedValue = selected as OptionType | null;
|
||||
setSelectedArea(selectedValue);
|
||||
setSelectedLocation(null);
|
||||
setSelectedKandang(null);
|
||||
updateFilter('areaFilter', selectedValue ? selectedValue.value.toString() : '');
|
||||
updateFilter('locationFilter', '');
|
||||
updateFilter('kandangFilter', '');
|
||||
setPage(1);
|
||||
}}
|
||||
className={{ wrapper: 'w-full' }}
|
||||
onInputChange={(value) => setAreaSelectInputValue(value)}
|
||||
isLoading={isLoadingAreas}
|
||||
isClearable
|
||||
/>
|
||||
|
||||
<SelectInput
|
||||
label='Lokasi'
|
||||
placeholder='Pilih Lokasi'
|
||||
options={optionsLocation}
|
||||
value={selectedLocation}
|
||||
onChange={(selected) => {
|
||||
const selectedValue = selected as OptionType | null;
|
||||
setSelectedLocation(selectedValue);
|
||||
setSelectedKandang(null);
|
||||
updateFilter('locationFilter', selectedValue ? selectedValue.value.toString() : '');
|
||||
updateFilter('kandangFilter', '');
|
||||
setPage(1);
|
||||
}}
|
||||
className={{ wrapper: 'w-full' }}
|
||||
onInputChange={(value) => setLocationSelectInputValue(value)}
|
||||
isLoading={isLoadingLocations}
|
||||
isClearable
|
||||
isDisabled={!selectedArea}
|
||||
/>
|
||||
|
||||
<SelectInput
|
||||
label='Kandang'
|
||||
placeholder='Pilih Kandang'
|
||||
options={optionsKandang}
|
||||
value={selectedKandang}
|
||||
onChange={(selected) => {
|
||||
const selectedValue = selected as OptionType | null;
|
||||
setSelectedKandang(selectedValue);
|
||||
updateFilter('kandangFilter', selectedValue ? selectedValue.value.toString() : '');
|
||||
setPage(1);
|
||||
}}
|
||||
className={{ wrapper: 'w-full' }}
|
||||
onInputChange={(value) => setKandangSelectInputValue(value)}
|
||||
isLoading={isLoadingKandang}
|
||||
isClearable
|
||||
isDisabled={!selectedLocation}
|
||||
/>
|
||||
|
||||
<SelectInput
|
||||
label='Periode'
|
||||
placeholder='Pilih Periode'
|
||||
options={[
|
||||
{ value: '1', label: 'Periode 1' },
|
||||
{ value: '2', label: 'Periode 2' },
|
||||
{ value: '3', label: 'Periode 3' },
|
||||
]}
|
||||
value={
|
||||
tableFilterState.periodFilter
|
||||
? { value: tableFilterState.periodFilter, label: `Periode ${tableFilterState.periodFilter}` }
|
||||
: null
|
||||
}
|
||||
onChange={(selected) => {
|
||||
const selectedValue = selected as OptionType | null;
|
||||
updateFilter('periodFilter', selectedValue ? selectedValue.value.toString() : '');
|
||||
setPage(1);
|
||||
}}
|
||||
className={{ wrapper: 'w-full' }}
|
||||
isClearable
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Bulk action buttons */}
|
||||
<div className={'flex justify-end items-center'}>
|
||||
{selectedRowIds.length > 0 && (
|
||||
<div className='flex gap-2 mb-4'>
|
||||
<Button
|
||||
type='button'
|
||||
color='success'
|
||||
onClick={() => bulkApproveModal.openModal()}
|
||||
className='flex items-center gap-2'
|
||||
>
|
||||
<Icon
|
||||
icon='material-symbols:check-circle-outline'
|
||||
width={20}
|
||||
height={20}
|
||||
/>
|
||||
Approve ({selectedRowIds.length})
|
||||
</Button>
|
||||
<Button
|
||||
type='button'
|
||||
color='error'
|
||||
onClick={() => bulkRejectModal.openModal()}
|
||||
className='flex items-center gap-2'
|
||||
>
|
||||
<Icon
|
||||
icon='material-symbols:cancel-outline'
|
||||
width={20}
|
||||
height={20}
|
||||
/>
|
||||
Reject ({selectedRowIds.length})
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ConfirmationModal
|
||||
ref={bulkApproveModal.ref}
|
||||
type='success'
|
||||
text={`Apakah anda yakin ingin menyetujui ${selectedRowIds.length} data Recording yang dipilih?`}
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: 'success',
|
||||
isLoading: isBulkApproveLoading,
|
||||
onClick: bulkApproveHandler,
|
||||
}}
|
||||
/>
|
||||
|
||||
<ConfirmationModal
|
||||
ref={bulkRejectModal.ref}
|
||||
type='error'
|
||||
text={`Apakah anda yakin ingin menolak ${selectedRowIds.length} data Recording yang dipilih?`}
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: 'error',
|
||||
isLoading: isBulkRejectLoading,
|
||||
onClick: bulkRejectHandler,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Table
|
||||
data={paginatedData}
|
||||
columns={[
|
||||
{
|
||||
id: 'select',
|
||||
header: ({ table }) => (
|
||||
<div className='w-full flex flex-row justify-center'>
|
||||
<CheckboxInput
|
||||
name='allRow'
|
||||
checked={table.getIsAllRowsSelected()}
|
||||
indeterminate={table.getIsSomeRowsSelected()}
|
||||
onChange={table.getToggleAllRowsSelectedHandler()}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<div>
|
||||
<CheckboxInput
|
||||
name='row'
|
||||
checked={row.getIsSelected()}
|
||||
disabled={!row.getCanSelect()}
|
||||
indeterminate={row.getIsSomeSelected()}
|
||||
onChange={row.getToggleSelectedHandler()}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: '#',
|
||||
cell: (props) => tableFilterState.pageSize * (tableFilterState.page - 1) + props.row.index + 1,
|
||||
},
|
||||
{
|
||||
header: 'Nama Project',
|
||||
cell: (props) => `Project ${props.row.original.project_flock_kandang_id}`,
|
||||
},
|
||||
{
|
||||
header: 'Umur (hari)',
|
||||
cell: (props) => props.row.original.day,
|
||||
},
|
||||
{
|
||||
accessorKey: 'record_date',
|
||||
header: 'Waktu Recording',
|
||||
cell: (props) =>
|
||||
new Date(props.row.original.record_date).toLocaleDateString(),
|
||||
},
|
||||
{
|
||||
header: 'Populasi Awal',
|
||||
cell: (props) => props.row.original.total_chick?.toLocaleString() || '-',
|
||||
},
|
||||
{
|
||||
header: 'BW',
|
||||
cell: (props) => props.row.original.avg_daily_gain?.toFixed(2) || '-',
|
||||
},
|
||||
{
|
||||
header: 'Pakan',
|
||||
cell: (props) => props.row.original.cum_intake?.toLocaleString() || '-',
|
||||
},
|
||||
{
|
||||
header: 'FCR',
|
||||
cell: (props) => props.row.original.fcr_value?.toFixed(2) || '-',
|
||||
},
|
||||
{
|
||||
accessorKey: 'total_depletion',
|
||||
header: 'Total Deplesi',
|
||||
cell: (props) => props.row.original.total_depletion,
|
||||
},
|
||||
{
|
||||
header: 'Deplesi (%)',
|
||||
cell: (props) => props.row.original.daily_depletion_rate?.toFixed(2) || '-',
|
||||
},
|
||||
{
|
||||
header: 'Populasi Akhir',
|
||||
cell: (props) => (props.row.original.total_chick - props.row.original.total_depletion)?.toLocaleString() || '-',
|
||||
},
|
||||
{
|
||||
header: 'Ketepatan Waktu',
|
||||
cell: (props) => props.row.original.ontime ? 'Tepat Waktu' : 'Terlambat',
|
||||
},
|
||||
{
|
||||
header: 'Tanggal Submit',
|
||||
cell: (props) =>
|
||||
new Date(props.row.original.created_at).toLocaleString(),
|
||||
},
|
||||
{
|
||||
header: 'Aksi',
|
||||
cell: (props: CellContext<Recording, unknown>) => {
|
||||
const currentPageSize =
|
||||
props.table.getPaginationRowModel().rows.length;
|
||||
const currentPageRows =
|
||||
props.table.getPaginationRowModel().flatRows;
|
||||
const currentRowRelativeIndex =
|
||||
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
|
||||
|
||||
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
|
||||
|
||||
const deleteClickHandler = () => {
|
||||
setSelectedRecording(props.row.original);
|
||||
singleDeleteModal.openModal();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{currentPageSize > 2 && (
|
||||
<RowDropdownOptions isLast2Rows={isLast2Rows}>
|
||||
<RowOptionsMenu
|
||||
type='dropdown'
|
||||
props={props}
|
||||
deleteClickHandler={deleteClickHandler}
|
||||
/>
|
||||
</RowDropdownOptions>
|
||||
)}
|
||||
|
||||
{currentPageSize <= 2 && (
|
||||
<RowCollapseOptions>
|
||||
<RowOptionsMenu
|
||||
type='collapse'
|
||||
props={props}
|
||||
deleteClickHandler={deleteClickHandler}
|
||||
/>
|
||||
</RowCollapseOptions>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
},
|
||||
},
|
||||
]}
|
||||
pageSize={tableFilterState.pageSize}
|
||||
page={recordings?.status === 'success' ? recordings.meta?.page : tableFilterState.page}
|
||||
totalItems={recordings?.status === 'success' ? recordings.meta?.total_results : 0}
|
||||
onPageChange={setPage}
|
||||
isLoading={isLoading}
|
||||
sorting={sorting}
|
||||
setSorting={setSorting}
|
||||
rowSelection={rowSelection}
|
||||
setRowSelection={setRowSelection}
|
||||
className={{
|
||||
containerClassName: cn({
|
||||
'mb-20': paginatedData.length === 0,
|
||||
}),
|
||||
tableWrapperClassName: 'overflow-x-auto min-h-full!',
|
||||
tableClassName: 'font-inter w-full table-auto min-h-full!',
|
||||
headerRowClassName: 'border-b border-b-gray-200',
|
||||
headerColumnClassName:
|
||||
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
|
||||
bodyRowClassName: 'border-b border-b-gray-200',
|
||||
bodyColumnClassName:
|
||||
'px-6 py-3 last:flex last:flex-row last:justify-end',
|
||||
}}
|
||||
/>
|
||||
|
||||
<ConfirmationModal
|
||||
ref={singleDeleteModal.ref}
|
||||
type='error'
|
||||
text={`Apakah anda yakin ingin menghapus data Recording ini (ID: ${selectedRecording?.id})?`}
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: 'error',
|
||||
isLoading: isDeleteLoading,
|
||||
onClick: singleDeleteHandler,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default RecordingTable;
|
||||
@@ -0,0 +1,222 @@
|
||||
import * as Yup from 'yup';
|
||||
import { RECORDING_FLAG_OPTIONS } from '@/config/constant';
|
||||
import {
|
||||
Recording,
|
||||
CreateRecordingPayload,
|
||||
} from '@/types/api/production/recording';
|
||||
|
||||
export const RecordingFormSchema = Yup.object({
|
||||
project_flock_kandang: Yup.object({
|
||||
value: Yup.number().min(1).required(),
|
||||
label: Yup.string().required(),
|
||||
}).nullable(),
|
||||
project_flock_kandang_id: Yup.number()
|
||||
.default(0)
|
||||
.typeError('Project Flock Kandang wajib diisi!')
|
||||
.test(
|
||||
'is-valid-project-flock-kandang',
|
||||
'Project Flock Kandang wajib diisi!',
|
||||
(value) => value !== undefined && value !== null && value > 0
|
||||
)
|
||||
.required('Project Flock Kandang wajib diisi!')
|
||||
.test(
|
||||
'not-already-recorded',
|
||||
'Project Flock ini sudah direcord hari ini!',
|
||||
function(value) {
|
||||
const recordedProjectFlockIds = this.options.context?.recordedProjectFlockIds as Set<number>;
|
||||
const formType = this.options.context?.type as 'add' | 'edit' | 'detail';
|
||||
if (formType !== 'add') return true;
|
||||
if (value && recordedProjectFlockIds?.has(value)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
),
|
||||
body_weights: Yup.array()
|
||||
.of(
|
||||
Yup.object({
|
||||
weight: Yup.number()
|
||||
.required('Berat ayam wajib diisi!')
|
||||
.min(1, 'Berat ayam minimal 1 gram!')
|
||||
.typeError('Berat ayam harus berupa angka!'),
|
||||
qty: Yup.number()
|
||||
.required('Jumlah ayam wajib diisi!')
|
||||
.min(1, 'Jumlah ayam minimal 1 ekor!')
|
||||
.typeError('Jumlah ayam harus berupa angka!')
|
||||
.default(1),
|
||||
average_weight: Yup.number()
|
||||
.optional()
|
||||
.min(0, 'Rata-rata berat tidak boleh negatif!')
|
||||
.typeError('Rata-rata berat harus berupa angka!')
|
||||
.default(0),
|
||||
})
|
||||
)
|
||||
.min(1, 'Minimal harus ada 1 data bobot badan!')
|
||||
.required('Data bobot badan wajib diisi!'),
|
||||
stocks: Yup.array()
|
||||
.of(
|
||||
Yup.object({
|
||||
product_warehouse_id: Yup.number()
|
||||
.required('Produk wajib diisi!')
|
||||
.min(1, 'Produk wajib diisi!')
|
||||
.typeError('Produk harus berupa angka!'),
|
||||
usage_amount: Yup.number()
|
||||
.required('Jumlah penggunaan wajib diisi!')
|
||||
.min(0, 'Jumlah penggunaan tidak boleh negatif!')
|
||||
.typeError('Jumlah penggunaan harus berupa angka!'),
|
||||
notes: Yup.string().optional(),
|
||||
})
|
||||
)
|
||||
.min(1, 'Minimal harus ada 1 data stok!')
|
||||
.required('Data stok wajib diisi!'),
|
||||
depletions: Yup.array()
|
||||
.of(
|
||||
Yup.object({
|
||||
total: Yup.number()
|
||||
.required('Jumlah depletions wajib diisi!')
|
||||
.min(1, 'Jumlah depletions minimal 1!')
|
||||
.typeError('Jumlah depletions harus berupa angka!'),
|
||||
notes: Yup.string()
|
||||
.required('Kondisi depletions wajib diisi!')
|
||||
.oneOf(
|
||||
RECORDING_FLAG_OPTIONS.map((option) => option.value),
|
||||
'Kondisi depletions tidak valid!'
|
||||
)
|
||||
.typeError('Kondisi depletions harus berupa teks!')
|
||||
.min(1, 'Kondisi depletions wajib diisi!'),
|
||||
})
|
||||
)
|
||||
.min(1, 'Minimal harus ada 1 data depletions!')
|
||||
.required('Data depletions wajib diisi!'),
|
||||
});
|
||||
|
||||
export const UpdateRecordingFormSchema = Yup.object({
|
||||
project_flock_kandang: Yup.object({
|
||||
value: Yup.number().min(1).required(),
|
||||
label: Yup.string().required(),
|
||||
}).nullable(),
|
||||
project_flock_kandang_id: Yup.number()
|
||||
.default(0)
|
||||
.typeError('Project Flock Kandang wajib diisi!')
|
||||
.test(
|
||||
'is-valid-project-flock-kandang',
|
||||
'Project Flock Kandang wajib diisi!',
|
||||
(value) => value !== undefined && value !== null && value > 0
|
||||
)
|
||||
.required('Project Flock Kandang wajib diisi!'),
|
||||
body_weights: Yup.array()
|
||||
.of(
|
||||
Yup.object({
|
||||
weight: Yup.number()
|
||||
.required('Berat ayam wajib diisi!')
|
||||
.min(1, 'Berat ayam minimal 1 gram!')
|
||||
.typeError('Berat ayam harus berupa angka!'),
|
||||
qty: Yup.number()
|
||||
.required('Jumlah ayam wajib diisi!')
|
||||
.min(1, 'Jumlah ayam minimal 1 ekor!')
|
||||
.typeError('Jumlah ayam harus berupa angka!')
|
||||
.default(1),
|
||||
average_weight: Yup.number()
|
||||
.optional()
|
||||
.min(0, 'Rata-rata berat tidak boleh negatif!')
|
||||
.typeError('Rata-rata berat harus berupa angka!')
|
||||
.default(0),
|
||||
})
|
||||
)
|
||||
.min(1, 'Minimal harus ada 1 data bobot badan!')
|
||||
.required('Data bobot badan wajib diisi!'),
|
||||
stocks: Yup.array()
|
||||
.of(
|
||||
Yup.object({
|
||||
product_warehouse_id: Yup.number()
|
||||
.required('Produk wajib diisi!')
|
||||
.min(1, 'Produk wajib diisi!')
|
||||
.typeError('Produk harus berupa angka!'),
|
||||
usage_amount: Yup.number()
|
||||
.required('Jumlah penggunaan wajib diisi!')
|
||||
.min(0, 'Jumlah penggunaan tidak boleh negatif!')
|
||||
.typeError('Jumlah penggunaan harus berupa angka!'),
|
||||
notes: Yup.string().optional(),
|
||||
})
|
||||
)
|
||||
.min(1, 'Minimal harus ada 1 data stok!')
|
||||
.required('Data stok wajib diisi!'),
|
||||
depletions: Yup.array()
|
||||
.of(
|
||||
Yup.object({
|
||||
total: Yup.number()
|
||||
.required('Jumlah depletions wajib diisi!')
|
||||
.min(1, 'Jumlah depletions minimal 1!')
|
||||
.typeError('Jumlah depletions harus berupa angka!'),
|
||||
notes: Yup.string()
|
||||
.required('Kondisi depletions wajib diisi!')
|
||||
.oneOf(
|
||||
RECORDING_FLAG_OPTIONS.map((option) => option.value),
|
||||
'Kondisi depletions tidak valid!'
|
||||
)
|
||||
.typeError('Kondisi depletions harus berupa teks!')
|
||||
.min(1, 'Kondisi depletions wajib diisi!'),
|
||||
})
|
||||
)
|
||||
.min(1, 'Minimal harus ada 1 data depletions!')
|
||||
.required('Data depletions wajib diisi!'),
|
||||
});
|
||||
|
||||
export type RecordingFormValues = Yup.InferType<typeof RecordingFormSchema>;
|
||||
|
||||
type RecordingFormData = Partial<Recording> & {
|
||||
body_weights?: CreateRecordingPayload['body_weights'];
|
||||
stocks?: CreateRecordingPayload['stocks'];
|
||||
depletions?: CreateRecordingPayload['depletions'];
|
||||
};
|
||||
|
||||
export const getRecordingFormInitialValues = (
|
||||
initialValues?: RecordingFormData
|
||||
): RecordingFormValues => ({
|
||||
project_flock_kandang: initialValues?.project_flock_kandang_id
|
||||
? {
|
||||
value: initialValues.project_flock_kandang_id,
|
||||
label: `Project Flock #${initialValues.project_flock_kandang_id}`,
|
||||
}
|
||||
: null,
|
||||
project_flock_kandang_id: initialValues?.project_flock_kandang_id ?? 0,
|
||||
body_weights: initialValues?.body_weights?.map(
|
||||
(bw: NonNullable<CreateRecordingPayload['body_weights']>[0]) => ({
|
||||
weight: bw.weight,
|
||||
qty: bw.qty,
|
||||
average_weight: bw.qty > 0 ? Math.round(bw.weight / bw.qty) : 0,
|
||||
})
|
||||
) ?? [
|
||||
{
|
||||
weight: 0,
|
||||
qty: 0,
|
||||
average_weight: 0,
|
||||
},
|
||||
],
|
||||
stocks: initialValues?.stocks?.map(
|
||||
(stock: NonNullable<CreateRecordingPayload['stocks']>[0]) => ({
|
||||
product_warehouse_id: stock.product_warehouse_id,
|
||||
usage_amount: stock.usage_amount,
|
||||
notes: stock.notes,
|
||||
})
|
||||
) ?? [
|
||||
{
|
||||
product_warehouse_id: 0,
|
||||
usage_amount: 0,
|
||||
notes: '',
|
||||
},
|
||||
],
|
||||
depletions: initialValues?.depletions?.map(
|
||||
(depletion: NonNullable<CreateRecordingPayload['depletions']>[0]) => ({
|
||||
product_warehouse_id: depletion.product_warehouse_id,
|
||||
total: depletion.total,
|
||||
notes: depletion.notes,
|
||||
})
|
||||
) ?? [
|
||||
{
|
||||
product_warehouse_id: 0,
|
||||
total: 0,
|
||||
notes: '',
|
||||
},
|
||||
],
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,70 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import { useModal } from '@/components/Modal';
|
||||
import { RecordingApi } from '@/services/api/production';
|
||||
import {
|
||||
CreateRecordingPayload,
|
||||
UpdateRecordingPayload,
|
||||
} from '@/types/api/production/recording';
|
||||
import { isResponseError } from '@/lib/api-helper';
|
||||
|
||||
export const useRecordingFormHandlers = (initialValuesId?: number) => {
|
||||
const router = useRouter();
|
||||
const deleteModal = useModal();
|
||||
const [recordingFormErrorMessage, setRecordingFormErrorMessage] =
|
||||
useState('');
|
||||
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||
|
||||
const createRecordingHandler = useCallback(
|
||||
async (payload: CreateRecordingPayload) => {
|
||||
const res = await RecordingApi.create(payload);
|
||||
if (isResponseError(res)) {
|
||||
setRecordingFormErrorMessage(res.message);
|
||||
return;
|
||||
}
|
||||
toast.success(res?.message as string);
|
||||
router.push('/production/recording');
|
||||
},
|
||||
[router]
|
||||
);
|
||||
|
||||
const updateRecordingHandler = useCallback(
|
||||
async (recordingId: number, payload: UpdateRecordingPayload) => {
|
||||
const res = await RecordingApi.update(recordingId, payload);
|
||||
if (res?.status === 'error') {
|
||||
setRecordingFormErrorMessage(res.message);
|
||||
return;
|
||||
}
|
||||
toast.success(res?.message as string);
|
||||
router.refresh();
|
||||
router.push('/production/recording');
|
||||
},
|
||||
[router]
|
||||
);
|
||||
|
||||
const deleteRecordingClickHandler = useCallback(() => {
|
||||
deleteModal.openModal();
|
||||
}, [deleteModal]);
|
||||
|
||||
const confirmationModalDeleteClickHandler = useCallback(async () => {
|
||||
if (!initialValuesId) return;
|
||||
|
||||
setIsDeleteLoading(true);
|
||||
await RecordingApi.delete(initialValuesId);
|
||||
deleteModal.closeModal();
|
||||
toast.success('Successfully delete Recording!');
|
||||
setIsDeleteLoading(false);
|
||||
router.push('/production/recording');
|
||||
}, [deleteModal, initialValuesId, router]);
|
||||
|
||||
return {
|
||||
deleteModal,
|
||||
recordingFormErrorMessage,
|
||||
isDeleteLoading,
|
||||
createRecordingHandler,
|
||||
updateRecordingHandler,
|
||||
deleteRecordingClickHandler,
|
||||
confirmationModalDeleteClickHandler,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,633 @@
|
||||
'use client';
|
||||
|
||||
import { ChangeEventHandler, useState } from 'react';
|
||||
import useSWR from 'swr';
|
||||
import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table';
|
||||
import toast from 'react-hot-toast';
|
||||
|
||||
import { Icon } from '@iconify/react';
|
||||
import Table from '@/components/Table';
|
||||
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
|
||||
import Button from '@/components/Button';
|
||||
import { useModal } from '@/components/Modal';
|
||||
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||
import SelectInput, {
|
||||
OptionType,
|
||||
useSelect,
|
||||
} from '@/components/input/SelectInput';
|
||||
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
|
||||
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
|
||||
import TextInput from '@/components/input/TextInput';
|
||||
import CheckboxInput from '@/components/input/CheckboxInput';
|
||||
|
||||
import { TransferToLaying } from '@/types/api/production/transfer-to-laying';
|
||||
import { TransferToLayingApi } from '@/services/api/production/transfer-to-laying';
|
||||
import { cn, formatDate } from '@/lib/helper';
|
||||
import { isResponseSuccess } from '@/lib/api-helper';
|
||||
import { useTableFilter } from '@/services/hooks/useTableFilter';
|
||||
import { ROWS_OPTIONS } from '@/config/constant';
|
||||
import { Flock } from '@/types/api/master-data/flock';
|
||||
import { FlockApi } from '@/services/api/master-data';
|
||||
|
||||
const RowOptionsMenu = ({
|
||||
type = 'dropdown',
|
||||
props,
|
||||
approveClickHandler,
|
||||
rejectClickHandler,
|
||||
deleteClickHandler,
|
||||
}: {
|
||||
type: 'dropdown' | 'collapse';
|
||||
props: CellContext<TransferToLaying, unknown>;
|
||||
approveClickHandler: () => void;
|
||||
rejectClickHandler: () => void;
|
||||
deleteClickHandler: () => void;
|
||||
}) => {
|
||||
return (
|
||||
<div
|
||||
tabIndex={type === 'dropdown' ? 0 : undefined}
|
||||
className={cn(
|
||||
{
|
||||
'dropdown-content': type === 'dropdown',
|
||||
'mt-2': type === 'collapse',
|
||||
},
|
||||
'p-2.5 mr-2 flex flex-col gap-1 bg-base-100 rounded-box z-10 border border-black/10 shadow'
|
||||
)}
|
||||
>
|
||||
<Button
|
||||
href={`/production/transfer-to-laying/detail/?transferToLayingId=${props.row.original.id}`}
|
||||
variant='ghost'
|
||||
color='primary'
|
||||
className='justify-start text-sm'
|
||||
>
|
||||
<Icon icon='mdi:eye-outline' width={16} height={16} />
|
||||
Detail
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
href={`/production/transfer-to-laying/detail/edit/?transferToLayingId=${props.row.original.id}`}
|
||||
variant='ghost'
|
||||
color='warning'
|
||||
className='justify-start text-sm'
|
||||
>
|
||||
<Icon icon='material-symbols:edit-outline' width={16} height={16} />
|
||||
Edit
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant='ghost'
|
||||
color='success'
|
||||
onClick={approveClickHandler}
|
||||
className='justify-start text-sm'
|
||||
>
|
||||
<Icon icon='material-symbols:check' width={24} height={24} />
|
||||
Approve
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant='ghost'
|
||||
color='error'
|
||||
onClick={rejectClickHandler}
|
||||
className='justify-start text-sm'
|
||||
>
|
||||
<Icon icon='material-symbols:close' width={24} height={24} />
|
||||
Reject
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={deleteClickHandler}
|
||||
variant='ghost'
|
||||
color='error'
|
||||
className='text-error hover:text-inherit'
|
||||
>
|
||||
<Icon
|
||||
icon='material-symbols:delete-outline-rounded'
|
||||
width={16}
|
||||
height={16}
|
||||
className='justify-start text-sm'
|
||||
/>
|
||||
Delete
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const TransferToLayingsTable = () => {
|
||||
const {
|
||||
state: tableFilterState,
|
||||
updateFilter,
|
||||
setPage,
|
||||
setPageSize,
|
||||
toQueryString: getTableFilterQueryString,
|
||||
} = useTableFilter({
|
||||
initial: {
|
||||
search: '',
|
||||
transferDate: '',
|
||||
flockSource: '',
|
||||
flockDestination: '',
|
||||
},
|
||||
paramMap: {
|
||||
page: 'page',
|
||||
pageSize: 'limit',
|
||||
transferDate: 'transfer_date',
|
||||
flockSource: 'flock_source',
|
||||
flockDestination: 'flock_destination',
|
||||
},
|
||||
});
|
||||
|
||||
const {
|
||||
data: transferToLayings,
|
||||
isLoading,
|
||||
mutate: refreshTransferToLayings,
|
||||
} = useSWR(
|
||||
`${TransferToLayingApi.basePath}${getTableFilterQueryString()}`,
|
||||
TransferToLayingApi.getAllFetcher
|
||||
);
|
||||
|
||||
// Modal hooks
|
||||
const deleteModal = useModal();
|
||||
const approveModal = useModal();
|
||||
const rejectModal = useModal();
|
||||
|
||||
// Flocks data
|
||||
const {
|
||||
setInputValue: setFlockSourceInputValue,
|
||||
options: flockSourceOptions,
|
||||
isLoadingOptions: isLoadingFlockSourceOptions,
|
||||
} = useSelect<Flock>(FlockApi.basePath, 'id', 'name');
|
||||
|
||||
const {
|
||||
setInputValue: setFlockDestinationInputValue,
|
||||
options: flockDestinationOptions,
|
||||
isLoadingOptions: isLoadingFlockDestinationOptions,
|
||||
} = useSelect<Flock>(FlockApi.basePath, 'id', 'name');
|
||||
|
||||
// Flocks value
|
||||
const [selectedFlockSource, setSelectedFlockSource] =
|
||||
useState<OptionType | null>(null);
|
||||
const [selectedFlockDestination, setSelectedFlockDestination] =
|
||||
useState<OptionType | null>(null);
|
||||
|
||||
const [selectedTransferToLaying, setSelectedTransferToLaying] = useState<
|
||||
TransferToLaying | undefined
|
||||
>(undefined);
|
||||
|
||||
// Modal loading state
|
||||
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||
const [isApproveLoading, setIsApproveLoading] = useState(false);
|
||||
const [isRejectLoading, setIsRejectLoading] = useState(false);
|
||||
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});
|
||||
const selectedRowIds = Object.keys(rowSelection).map((item) =>
|
||||
parseInt(item)
|
||||
);
|
||||
|
||||
const transferToLayingsColumns: ColumnDef<TransferToLaying>[] = [
|
||||
{
|
||||
id: 'select',
|
||||
header: ({ table }) => (
|
||||
<div className='w-full flex flex-row justify-center'>
|
||||
<CheckboxInput
|
||||
name='allRow'
|
||||
checked={table.getIsAllRowsSelected()}
|
||||
indeterminate={table.getIsSomeRowsSelected()}
|
||||
onChange={table.getToggleAllRowsSelectedHandler()}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<div>
|
||||
<CheckboxInput
|
||||
name='row'
|
||||
checked={row.getIsSelected()}
|
||||
disabled={!row.getCanSelect()}
|
||||
indeterminate={row.getIsSomeSelected()}
|
||||
onChange={row.getToggleSelectedHandler()}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: '#',
|
||||
cell: (props) =>
|
||||
tableFilterState.pageSize * (tableFilterState.page - 1) +
|
||||
props.row.index +
|
||||
1,
|
||||
},
|
||||
{
|
||||
accessorKey: 'transfer_date',
|
||||
header: 'Tanggal Transfer',
|
||||
cell: (props) => formatDate(props.getValue() as string, 'DD MMM YYYY'),
|
||||
},
|
||||
{
|
||||
accessorKey: 'flock_source',
|
||||
header: 'Flock Asal',
|
||||
cell: (props) => props.row.original.flock_source.name,
|
||||
},
|
||||
{
|
||||
accessorKey: 'flock_destination',
|
||||
header: 'Flock Tujuan',
|
||||
cell: (props) => props.row.original.flock_destination.name,
|
||||
},
|
||||
{
|
||||
accessorKey: 'quantity',
|
||||
header: 'Kuantitas',
|
||||
},
|
||||
{
|
||||
accessorKey: 'reason',
|
||||
header: 'Alasan Transfer',
|
||||
},
|
||||
{
|
||||
header: 'Aksi',
|
||||
cell: (props) => {
|
||||
const currentPageSize = props.table.getPaginationRowModel().rows.length;
|
||||
const currentPageRows = props.table.getPaginationRowModel().flatRows;
|
||||
const currentRowRelativeIndex =
|
||||
currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
|
||||
|
||||
const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2;
|
||||
|
||||
const approveClickHandler = () => {
|
||||
setSelectedTransferToLaying(props.row.original);
|
||||
|
||||
// Set row selection
|
||||
setRowSelection({
|
||||
[String(props.row.original.id)]: true,
|
||||
});
|
||||
|
||||
approveModal.openModal();
|
||||
};
|
||||
|
||||
const rejectClickHandler = () => {
|
||||
setSelectedTransferToLaying(props.row.original);
|
||||
|
||||
// Set row selection
|
||||
setRowSelection({
|
||||
[String(props.row.original.id)]: true,
|
||||
});
|
||||
|
||||
rejectModal.openModal();
|
||||
};
|
||||
|
||||
const deleteClickHandler = () => {
|
||||
setSelectedTransferToLaying(props.row.original);
|
||||
deleteModal.openModal();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{currentPageSize > 2 && (
|
||||
<RowDropdownOptions isLast2Rows={isLast2Rows}>
|
||||
<RowOptionsMenu
|
||||
type='dropdown'
|
||||
props={props}
|
||||
approveClickHandler={approveClickHandler}
|
||||
rejectClickHandler={rejectClickHandler}
|
||||
deleteClickHandler={deleteClickHandler}
|
||||
/>
|
||||
</RowDropdownOptions>
|
||||
)}
|
||||
|
||||
{currentPageSize <= 2 && (
|
||||
<RowCollapseOptions>
|
||||
<RowOptionsMenu
|
||||
type='dropdown'
|
||||
props={props}
|
||||
approveClickHandler={approveClickHandler}
|
||||
rejectClickHandler={rejectClickHandler}
|
||||
deleteClickHandler={deleteClickHandler}
|
||||
/>
|
||||
</RowCollapseOptions>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const bulkApproveClickHandler = () => {
|
||||
approveModal.openModal();
|
||||
};
|
||||
|
||||
const bulkRejectClickHandler = () => {
|
||||
rejectModal.openModal();
|
||||
};
|
||||
|
||||
// Modal confirm click handler
|
||||
const confirmationModalDeleteClickHandler = async () => {
|
||||
setIsDeleteLoading(true);
|
||||
|
||||
await TransferToLayingApi.delete(selectedTransferToLaying?.id as number);
|
||||
refreshTransferToLayings();
|
||||
|
||||
deleteModal.closeModal();
|
||||
toast.success('Berhasil menghapus data transfer ke laying!');
|
||||
setIsDeleteLoading(false);
|
||||
};
|
||||
|
||||
const confirmationModalApproveClickHandler = async () => {
|
||||
setIsApproveLoading(true);
|
||||
|
||||
const bulkApproveResponse = await TransferToLayingApi.bulkApprove(
|
||||
selectedRowIds
|
||||
);
|
||||
|
||||
if (isResponseSuccess(bulkApproveResponse)) {
|
||||
refreshTransferToLayings();
|
||||
approveModal.closeModal();
|
||||
|
||||
// TODO: remove console.log
|
||||
console.log('Approved data:', selectedRowIds);
|
||||
|
||||
toast.success(
|
||||
`Berhasil approve ${selectedRowIds.length} data transfer ke laying!`
|
||||
);
|
||||
|
||||
setRowSelection({});
|
||||
} else {
|
||||
approveModal.closeModal();
|
||||
|
||||
toast.error(
|
||||
`Gagal approve ${selectedRowIds.length} data transfer ke laying!`
|
||||
);
|
||||
}
|
||||
|
||||
setIsApproveLoading(false);
|
||||
};
|
||||
|
||||
const confirmationModalRejectClickHandler = async () => {
|
||||
setIsRejectLoading(true);
|
||||
|
||||
const bulkRejectResponse = await TransferToLayingApi.bulkReject(
|
||||
selectedRowIds
|
||||
);
|
||||
|
||||
if (isResponseSuccess(bulkRejectResponse)) {
|
||||
refreshTransferToLayings();
|
||||
rejectModal.closeModal();
|
||||
|
||||
// TODO: remove console.log
|
||||
console.log('Rejected data:', selectedRowIds);
|
||||
|
||||
toast.success(
|
||||
`Berhasil reject ${selectedRowIds.length} data transfer ke laying!`
|
||||
);
|
||||
setRowSelection({});
|
||||
} else {
|
||||
rejectModal.closeModal();
|
||||
|
||||
toast.error(
|
||||
`Gagal reject ${selectedRowIds.length} data transfer ke laying!`
|
||||
);
|
||||
}
|
||||
|
||||
setIsRejectLoading(false);
|
||||
};
|
||||
|
||||
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
|
||||
updateFilter('search', e.target.value);
|
||||
};
|
||||
|
||||
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||
const newVal = val as OptionType;
|
||||
|
||||
setPageSize(newVal.value as number);
|
||||
};
|
||||
|
||||
const transferDateChangeHandler: ChangeEventHandler<HTMLInputElement> = (
|
||||
e
|
||||
) => {
|
||||
updateFilter('transferDate', e.target.value);
|
||||
};
|
||||
|
||||
const flockSourceChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||
setSelectedFlockSource(val as OptionType);
|
||||
updateFilter(
|
||||
'flockSource',
|
||||
val ? ((val as OptionType).value as string) : ''
|
||||
);
|
||||
};
|
||||
|
||||
const flockDestinationChangeHandler = (
|
||||
val: OptionType | OptionType[] | null
|
||||
) => {
|
||||
setSelectedFlockDestination(val as OptionType);
|
||||
updateFilter(
|
||||
'flockDestination',
|
||||
val ? ((val as OptionType).value as string) : ''
|
||||
);
|
||||
};
|
||||
|
||||
// track sorting
|
||||
// useEffect(() => {
|
||||
// const isNameSorted = sorting.find((sortItem) => sortItem.id === 'name');
|
||||
|
||||
// if (!isNameSorted) {
|
||||
// updateFilter('nameSort', '');
|
||||
// } else {
|
||||
// updateFilter('nameSort', isNameSorted.desc ? 'desc' : 'asc');
|
||||
// }
|
||||
// }, [sorting, updateFilter]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='w-full p-0 sm:p-4'>
|
||||
<div className='flex flex-col gap-2 mb-4'>
|
||||
<div className='w-full flex flex-col xl:flex-row justify-between items-end xl:items-center gap-2'>
|
||||
<div className='w-full sm:w-fit flex flex-col sm:flex-row self-start gap-2'>
|
||||
<Button
|
||||
href='/production/transfer-to-laying/add'
|
||||
color='primary'
|
||||
className='w-full sm:w-fit'
|
||||
>
|
||||
<Icon icon='ic:round-plus' width={24} height={24} />
|
||||
Tambah Transfer ke Laying
|
||||
</Button>
|
||||
|
||||
{selectedRowIds.length > 0 && (
|
||||
<>
|
||||
<Button
|
||||
variant='outline'
|
||||
color='success'
|
||||
onClick={bulkApproveClickHandler}
|
||||
disabled={selectedRowIds.length === 0}
|
||||
className='w-full sm:w-fit'
|
||||
>
|
||||
<Icon
|
||||
icon='material-symbols:check'
|
||||
width={24}
|
||||
height={24}
|
||||
/>
|
||||
Approve
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant='outline'
|
||||
color='error'
|
||||
onClick={bulkRejectClickHandler}
|
||||
disabled={selectedRowIds.length === 0}
|
||||
className='w-full sm:w-fit'
|
||||
>
|
||||
<Icon
|
||||
icon='material-symbols:close'
|
||||
width={24}
|
||||
height={24}
|
||||
/>
|
||||
Reject
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DebouncedTextInput
|
||||
name='search'
|
||||
placeholder='Cari TransferToLaying'
|
||||
value={tableFilterState.search}
|
||||
onChange={searchChangeHandler}
|
||||
className={{ wrapper: 'sm:max-w-3xs' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className='grid grid-cols-12 justify-end gap-4'>
|
||||
<TextInput
|
||||
required
|
||||
type='date'
|
||||
label='Tanggal Transfer'
|
||||
name='transfer_date'
|
||||
placeholder='Masukkan tanggal transfer'
|
||||
value={tableFilterState.transferDate}
|
||||
onChange={transferDateChangeHandler}
|
||||
className={{ wrapper: 'col-span-12 sm:col-span-3' }}
|
||||
/>
|
||||
|
||||
<SelectInput
|
||||
label='Flock Asal'
|
||||
options={flockSourceOptions}
|
||||
isLoading={isLoadingFlockSourceOptions}
|
||||
value={selectedFlockSource}
|
||||
onChange={flockSourceChangeHandler}
|
||||
onInputChange={setFlockSourceInputValue}
|
||||
isClearable
|
||||
className={{
|
||||
wrapper: 'col-span-12 sm:col-span-3',
|
||||
}}
|
||||
/>
|
||||
|
||||
<SelectInput
|
||||
label='Flock Tujuan'
|
||||
options={flockDestinationOptions}
|
||||
isLoading={isLoadingFlockDestinationOptions}
|
||||
value={selectedFlockDestination}
|
||||
onChange={flockDestinationChangeHandler}
|
||||
onInputChange={setFlockDestinationInputValue}
|
||||
isClearable
|
||||
className={{
|
||||
wrapper: 'col-span-12 sm:col-span-3',
|
||||
}}
|
||||
/>
|
||||
|
||||
<SelectInput
|
||||
label='Baris'
|
||||
options={ROWS_OPTIONS}
|
||||
value={{
|
||||
label: String(tableFilterState.pageSize),
|
||||
value: tableFilterState.pageSize,
|
||||
}}
|
||||
onChange={pageSizeChangeHandler}
|
||||
className={{
|
||||
wrapper:
|
||||
'col-span-6 sm:col-span-3 max-w-28 sm:justify-self-end',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Table<TransferToLaying>
|
||||
data={
|
||||
isResponseSuccess(transferToLayings) ? transferToLayings?.data : []
|
||||
}
|
||||
columns={transferToLayingsColumns}
|
||||
pageSize={tableFilterState.pageSize}
|
||||
page={
|
||||
isResponseSuccess(transferToLayings)
|
||||
? transferToLayings?.meta?.page
|
||||
: 0
|
||||
}
|
||||
totalItems={
|
||||
isResponseSuccess(transferToLayings)
|
||||
? transferToLayings?.meta?.total_results
|
||||
: 0
|
||||
}
|
||||
onPageChange={setPage}
|
||||
isLoading={isLoading}
|
||||
sorting={sorting}
|
||||
setSorting={setSorting}
|
||||
rowSelection={rowSelection}
|
||||
setRowSelection={setRowSelection}
|
||||
className={{
|
||||
containerClassName: cn({
|
||||
'mb-20':
|
||||
isResponseSuccess(transferToLayings) &&
|
||||
transferToLayings?.data?.length === 0,
|
||||
}),
|
||||
tableWrapperClassName: 'overflow-x-auto min-h-full!',
|
||||
tableClassName: 'font-inter w-full table-auto min-h-full!',
|
||||
headerRowClassName: 'border-b border-b-gray-200',
|
||||
headerColumnClassName:
|
||||
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
|
||||
bodyRowClassName: 'border-b border-b-gray-200',
|
||||
bodyColumnClassName:
|
||||
'px-6 py-3 last:flex last:flex-row last:justify-end',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ConfirmationModal
|
||||
ref={deleteModal.ref}
|
||||
type='error'
|
||||
text={`Apakah anda yakin ingin menghapus data transfer ke laying ini?`}
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: 'error',
|
||||
isLoading: isDeleteLoading,
|
||||
onClick: confirmationModalDeleteClickHandler,
|
||||
}}
|
||||
/>
|
||||
|
||||
<ConfirmationModal
|
||||
ref={approveModal.ref}
|
||||
type='success'
|
||||
text={`Apakah anda yakin ingin approve data transfer ke laying ini (${selectedRowIds.length} data)?`}
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: 'success',
|
||||
isLoading: isApproveLoading,
|
||||
onClick: confirmationModalApproveClickHandler,
|
||||
}}
|
||||
/>
|
||||
|
||||
<ConfirmationModal
|
||||
ref={rejectModal.ref}
|
||||
type='error'
|
||||
text={`Apakah anda yakin ingin reject data transfer ke laying ini (${selectedRowIds.length} data)?`}
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: 'error',
|
||||
isLoading: isRejectLoading,
|
||||
onClick: confirmationModalRejectClickHandler,
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default TransferToLayingsTable;
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
import * as Yup from 'yup';
|
||||
|
||||
type TransferToLayingFormSchemaType = {
|
||||
transfer_date?: string;
|
||||
flockSource?: {
|
||||
value: number;
|
||||
label: string;
|
||||
};
|
||||
flockDestination?: {
|
||||
value: number;
|
||||
label: string;
|
||||
};
|
||||
|
||||
totalQuantity?: number;
|
||||
maxTotalQuantity?: number; // original cap (hidden), helper
|
||||
|
||||
kandangs: {
|
||||
kandang: {
|
||||
value: number;
|
||||
label: string;
|
||||
};
|
||||
quantity: number | string; // editable
|
||||
maxQuantity?: number; // original cap (hidden), helper
|
||||
}[];
|
||||
reason?: string;
|
||||
};
|
||||
|
||||
export const TransferToLayingFormSchema: Yup.ObjectSchema<TransferToLayingFormSchemaType> =
|
||||
Yup.object({
|
||||
transfer_date: Yup.string().required('Tanggal transfer wajib diisi!'),
|
||||
|
||||
flockSource: Yup.object({
|
||||
value: Yup.number().min(1).required(),
|
||||
label: Yup.string().required(),
|
||||
}).required('Flock asal wajib diisi!'),
|
||||
|
||||
flockDestination: Yup.object({
|
||||
value: Yup.number().min(1).required(),
|
||||
label: Yup.string().required(),
|
||||
}).required('Flock tujuan wajib diisi!'),
|
||||
|
||||
totalQuantity: Yup.number()
|
||||
.min(1, 'Jumlah transfer minimal 1')
|
||||
.max(
|
||||
Yup.ref('maxTotalQuantity'),
|
||||
({ max }) => `Kuantitas maksimal ${max}!`
|
||||
)
|
||||
.required('Jumlah transfer wajib diisi!'),
|
||||
|
||||
maxTotalQuantity: Yup.number()
|
||||
.min(1, 'Jumlah transfer minimal 1')
|
||||
.required('Jumlah transfer wajib diisi!'),
|
||||
|
||||
kandangs: Yup.array()
|
||||
.of(
|
||||
Yup.object({
|
||||
kandang: Yup.object({
|
||||
value: Yup.number().min(1).required(),
|
||||
label: Yup.string().required(),
|
||||
}).required('Kandang wajib diisi!'),
|
||||
|
||||
quantity: Yup.number()
|
||||
.min(0, 'Kuantitas minimal 0!')
|
||||
.max(
|
||||
Yup.ref('maxQuantity'),
|
||||
({ max }) => `Kuantitas maksimal ${max}!`
|
||||
)
|
||||
.required('Kuantitas wajib diisi!'),
|
||||
|
||||
maxQuantity: Yup.number().min(1).required(), // internal helper field
|
||||
})
|
||||
)
|
||||
.min(1, 'Minimal 1 kandang terisi!')
|
||||
.required('Kandang wajib diisi!'),
|
||||
|
||||
reason: Yup.string().required('Alasan transfer wajib diisi!'),
|
||||
});
|
||||
|
||||
export const UpdateTransferToLayingFormSchema = TransferToLayingFormSchema;
|
||||
|
||||
export type TransferToLayingFormValues = Yup.InferType<
|
||||
typeof TransferToLayingFormSchema
|
||||
>;
|
||||
@@ -0,0 +1,688 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useFormik } from 'formik';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import useSWR from 'swr';
|
||||
|
||||
import { Icon } from '@iconify/react';
|
||||
import Button from '@/components/Button';
|
||||
import TextInput from '@/components/input/TextInput';
|
||||
import SelectInput, {
|
||||
OptionType,
|
||||
// useSelect,
|
||||
} from '@/components/input/SelectInput';
|
||||
import TextArea from '@/components/input/TextArea';
|
||||
import { useModal } from '@/components/Modal';
|
||||
import ConfirmationModal from '@/components/modal/ConfirmationModal';
|
||||
|
||||
import {
|
||||
TransferToLayingFormSchema,
|
||||
TransferToLayingFormValues,
|
||||
UpdateTransferToLayingFormSchema,
|
||||
} from '@/components/pages/production/transfer-to-laying/form/TransferToLayingForm.schema';
|
||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||
import {
|
||||
TransferToLaying,
|
||||
CreateTransferToLayingPayload,
|
||||
UpdateTransferToLayingPayload,
|
||||
} from '@/types/api/production/transfer-to-laying';
|
||||
import { cn } from '@/lib/helper';
|
||||
|
||||
import { TransferToLayingApi } from '@/services/api/production/transfer-to-laying';
|
||||
|
||||
interface TransferToLayingFormProps {
|
||||
type?: 'add' | 'edit' | 'detail';
|
||||
initialValues?: TransferToLaying;
|
||||
}
|
||||
|
||||
const TransferToLayingForm = ({
|
||||
type = 'add',
|
||||
initialValues,
|
||||
}: TransferToLayingFormProps) => {
|
||||
const router = useRouter();
|
||||
|
||||
// Modal hooks
|
||||
const deleteModal = useModal();
|
||||
const approveModal = useModal();
|
||||
const rejectModal = useModal();
|
||||
|
||||
const [formErrorMessage, setFormErrorMessage] = useState('');
|
||||
|
||||
// Modal loading state
|
||||
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||
const [isApproveLoading, setIsApproveLoading] = useState(false);
|
||||
const [isRejectLoading, setIsRejectLoading] = useState(false);
|
||||
|
||||
const createTransferToLayingHandler = useCallback(
|
||||
async (payload: CreateTransferToLayingPayload) => {
|
||||
console.log('Create transfer to laying:', { payload });
|
||||
|
||||
toast.success('Berhasil menambahkan data transfer ke laying!');
|
||||
},
|
||||
[router]
|
||||
);
|
||||
|
||||
const updateTransferToLayingHandler = useCallback(
|
||||
async (
|
||||
transferToLayingId: number,
|
||||
payload: UpdateTransferToLayingPayload
|
||||
) => {
|
||||
console.log(
|
||||
`Update transfer to laying with ID of ${transferToLayingId}:`,
|
||||
{ payload }
|
||||
);
|
||||
|
||||
toast.success('Berhasil mengubah data transfer ke laying!');
|
||||
},
|
||||
[router]
|
||||
);
|
||||
|
||||
const formikInitialValues = useMemo<TransferToLayingFormValues>(() => {
|
||||
return {
|
||||
transfer_date: initialValues?.transfer_date ?? '',
|
||||
flockSource: initialValues?.flock_source
|
||||
? {
|
||||
value: initialValues?.flock_source.id,
|
||||
label: initialValues?.flock_source.name,
|
||||
}
|
||||
: undefined,
|
||||
flockDestination: initialValues?.flock_destination
|
||||
? {
|
||||
value: initialValues?.flock_destination.id,
|
||||
label: initialValues?.flock_destination.name,
|
||||
}
|
||||
: undefined,
|
||||
totalQuantity: initialValues?.quantity ?? undefined,
|
||||
|
||||
kandangs: initialValues?.kandangs
|
||||
? initialValues.kandangs.map((kandang) => ({
|
||||
kandang: {
|
||||
value: kandang.kandang.id,
|
||||
label: kandang.kandang.name,
|
||||
},
|
||||
quantity: kandang.quantity,
|
||||
}))
|
||||
: [],
|
||||
|
||||
reason: initialValues?.reason ?? undefined,
|
||||
};
|
||||
}, [initialValues]);
|
||||
|
||||
const formik = useFormik<TransferToLayingFormValues>({
|
||||
initialValues: formikInitialValues,
|
||||
validationSchema:
|
||||
type === 'edit'
|
||||
? UpdateTransferToLayingFormSchema
|
||||
: TransferToLayingFormSchema,
|
||||
onSubmit: async (values) => {
|
||||
console.log({ values });
|
||||
|
||||
setFormErrorMessage('');
|
||||
|
||||
const transferToLayingPayload: CreateTransferToLayingPayload = {
|
||||
transfer_date: values.transfer_date as string,
|
||||
flock_source_id: values.flockSource?.value as number,
|
||||
flock_destination_id: values.flockDestination?.value as number,
|
||||
totalQuantity: values.totalQuantity as number,
|
||||
|
||||
kandangs: values.kandangs?.map((kandang) => ({
|
||||
kandang_id: kandang.kandang.value,
|
||||
quantity: kandang.quantity,
|
||||
})) as {
|
||||
kandang_id: number;
|
||||
quantity: number;
|
||||
}[],
|
||||
|
||||
reason: values.reason as string,
|
||||
};
|
||||
|
||||
switch (type) {
|
||||
case 'add':
|
||||
await createTransferToLayingHandler(transferToLayingPayload);
|
||||
break;
|
||||
|
||||
case 'edit':
|
||||
await updateTransferToLayingHandler(
|
||||
initialValues?.id as number,
|
||||
transferToLayingPayload
|
||||
);
|
||||
break;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const { setValues: formikSetValues, values: formikValues } = formik;
|
||||
const { kandangs: kandangsValue } = formikValues;
|
||||
|
||||
const deleteTransferToLayingClickHandler = () => {
|
||||
deleteModal.openModal();
|
||||
};
|
||||
|
||||
const approveClickHandler = () => {
|
||||
approveModal.openModal();
|
||||
};
|
||||
|
||||
const rejectClickHandler = () => {
|
||||
rejectModal.openModal();
|
||||
};
|
||||
|
||||
// Modal confirm click handler
|
||||
const confirmationModalDeleteClickHandler = async () => {
|
||||
setIsDeleteLoading(true);
|
||||
|
||||
// TODO: delete data and integrate to real API
|
||||
deleteModal.closeModal();
|
||||
toast.success('Berhasil menghapus data transfer ke laying!');
|
||||
|
||||
setIsDeleteLoading(false);
|
||||
};
|
||||
|
||||
const confirmationModalApproveClickHandler = async () => {
|
||||
setIsApproveLoading(true);
|
||||
|
||||
const approveResponse = await TransferToLayingApi.approve(
|
||||
initialValues?.id as number
|
||||
);
|
||||
|
||||
if (isResponseSuccess(approveResponse)) {
|
||||
approveModal.closeModal();
|
||||
|
||||
toast.success('Berhasil approve data transfer ke laying!');
|
||||
} else {
|
||||
approveModal.closeModal();
|
||||
|
||||
toast.error('Gagal approve data transfer ke laying!');
|
||||
}
|
||||
|
||||
setIsApproveLoading(false);
|
||||
};
|
||||
|
||||
const confirmationModalRejectClickHandler = async () => {
|
||||
setIsRejectLoading(true);
|
||||
|
||||
const rejectResponse = await TransferToLayingApi.reject(
|
||||
initialValues?.id as number
|
||||
);
|
||||
|
||||
if (isResponseSuccess(rejectResponse)) {
|
||||
rejectModal.closeModal();
|
||||
|
||||
toast.success('Berhasil reject data transfer ke laying!');
|
||||
} else {
|
||||
rejectModal.closeModal();
|
||||
|
||||
toast.error('Gagal reject data transfer ke laying!');
|
||||
}
|
||||
|
||||
setIsRejectLoading(false);
|
||||
};
|
||||
|
||||
const isRepeaterInputError = (
|
||||
column: keyof TransferToLayingFormValues['kandangs'][0],
|
||||
idx: number
|
||||
) => {
|
||||
return (
|
||||
formik.touched.kandangs?.[idx]?.[column] &&
|
||||
Boolean(
|
||||
formik.errors.kandangs?.[idx] instanceof Object &&
|
||||
formik.errors.kandangs?.[idx]?.[column]
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
const repeaterInputErrorMessage = (
|
||||
column: keyof TransferToLayingFormValues['kandangs'][0],
|
||||
idx: number
|
||||
) => {
|
||||
return (formik.errors.kandangs?.[idx] as Record<string, string>)?.[column];
|
||||
};
|
||||
|
||||
// TODO: remove dummy data and use real data
|
||||
// Flock Source
|
||||
// const {
|
||||
// inputValue: flockSourceInputValue,
|
||||
// setInputValue: setFlockSourceInputValue,
|
||||
// options: flockSourceOptions,
|
||||
// isLoadingOptions: isLoadingFlockSourceOptions,
|
||||
// } = useSelect<FlockWithKandangs>('/transfer-to-laying/production/get-flock-source', 'id', 'name');
|
||||
|
||||
// TODO: remove this dummy data
|
||||
const { data: flockSources, isLoading: isLoadingFlockSourceOptions } = useSWR(
|
||||
'test',
|
||||
() => TransferToLayingApi.getFlockSource()
|
||||
);
|
||||
|
||||
const flockSourceOptions = isResponseSuccess(flockSources)
|
||||
? flockSources?.data.map((flockSource) => ({
|
||||
value: flockSource.id,
|
||||
label: flockSource.name,
|
||||
}))
|
||||
: [];
|
||||
|
||||
const flockSourceChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||
// Get flock source data for total quantity and kandang
|
||||
const flockSource =
|
||||
isResponseSuccess(flockSources) && val !== null
|
||||
? flockSources.data.find(
|
||||
(item) => item.id === (val as OptionType).value
|
||||
)
|
||||
: undefined;
|
||||
|
||||
// Set total quantity and kandangs
|
||||
if (flockSource) {
|
||||
const formattedKandangs = flockSource.kandangs.map((item) => ({
|
||||
kandang: {
|
||||
value: item.kandang.id,
|
||||
label: item.kandang.name,
|
||||
},
|
||||
quantity: '',
|
||||
maxQuantity: item.quantity,
|
||||
}));
|
||||
|
||||
formik.setFieldValue('totalQuantity', flockSource.totalQuantity);
|
||||
formik.setFieldValue('maxTotalQuantity', flockSource.totalQuantity);
|
||||
formik.setFieldValue('kandangs', formattedKandangs);
|
||||
} else {
|
||||
formik.setFieldValue('totalQuantity', undefined);
|
||||
formik.setFieldValue('kandangs', undefined);
|
||||
formik.setFieldValue('reason', '');
|
||||
}
|
||||
|
||||
formik.setFieldTouched('flockSource', true);
|
||||
formik.setFieldValue('flockSource', val);
|
||||
};
|
||||
|
||||
// TODO: remove dummy data and use real data
|
||||
// Flock Destination
|
||||
// const {
|
||||
// inputValue: flockDestinationInputValue,
|
||||
// setInputValue: setFlockDestinationInputValue,
|
||||
// options: flockDestinationOptions,
|
||||
// isLoadingOptions: isLoadingFlockDestinationOptions,
|
||||
// } = useSelect<FlockWithKandangs>('/transfer-to-laying/production/get-flock-destination', 'id', 'name');
|
||||
|
||||
// TODO: remove this dummy data
|
||||
const {
|
||||
data: flockDestinations,
|
||||
isLoading: isLoadingFlockDestinationOptions,
|
||||
} = useSWR('test', () => TransferToLayingApi.getFlockSource());
|
||||
|
||||
const flockDestinationOptions = isResponseSuccess(flockDestinations)
|
||||
? flockDestinations?.data.map((flockDestination) => ({
|
||||
value: flockDestination.id,
|
||||
label: flockDestination.name,
|
||||
}))
|
||||
: [];
|
||||
|
||||
const flockDestinationChangeHandler = (
|
||||
val: OptionType | OptionType[] | null
|
||||
) => {
|
||||
formik.setFieldTouched('flockDestination', true);
|
||||
formik.setFieldValue('flockDestination', val);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
formikSetValues(formikInitialValues);
|
||||
}, [formikSetValues, formikInitialValues]);
|
||||
|
||||
useEffect(() => {
|
||||
// calculate total quantity if kandangs quantity change
|
||||
if (kandangsValue && kandangsValue.length > 0) {
|
||||
let newTotalQuantity = 0;
|
||||
|
||||
kandangsValue.forEach((item) => {
|
||||
newTotalQuantity += item.quantity as number;
|
||||
});
|
||||
|
||||
formik.setFieldValue('totalQuantity', newTotalQuantity);
|
||||
formik.validateField('totalQuantity');
|
||||
}
|
||||
}, [formikSetValues, kandangsValue]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<section className='w-full max-w-3xl'>
|
||||
<header className='flex flex-col gap-4'>
|
||||
<Button
|
||||
href='/production/transfer-to-laying'
|
||||
variant='link'
|
||||
className='w-fit p-0 text-primary'
|
||||
>
|
||||
<Icon icon='uil:arrow-left' width={24} height={24} />
|
||||
Kembali
|
||||
</Button>
|
||||
|
||||
<h1 className='text-2xl font-bold text-center'>
|
||||
{type === 'add' && 'Tambah Transfer ke Laying'}
|
||||
{type === 'edit' && 'Edit Transfer ke Laying'}
|
||||
{type === 'detail' && 'Detail Transfer ke Laying'}
|
||||
</h1>
|
||||
</header>
|
||||
|
||||
<div className='w-full my-4 flex flex-row justify-end gap-2'>
|
||||
{type === 'detail' && (
|
||||
<>
|
||||
<Button
|
||||
variant='outline'
|
||||
color='success'
|
||||
onClick={approveClickHandler}
|
||||
// disabled={selectedRowIds.length === 0}
|
||||
className='w-full sm:w-fit'
|
||||
>
|
||||
<Icon icon='material-symbols:check' width={24} height={24} />
|
||||
Approve
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant='outline'
|
||||
color='error'
|
||||
onClick={rejectClickHandler}
|
||||
// disabled={selectedRowIds.length === 0}
|
||||
className='w-full sm:w-fit'
|
||||
>
|
||||
<Icon icon='material-symbols:close' width={24} height={24} />
|
||||
Reject
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<form
|
||||
onSubmit={formik.handleSubmit}
|
||||
onReset={formik.handleReset}
|
||||
className='w-full flex flex-col gap-6'
|
||||
>
|
||||
<div className='flex flex-col gap-4'>
|
||||
<TextInput
|
||||
required
|
||||
type='date'
|
||||
label='Tanggal Transfer'
|
||||
name='transfer_date'
|
||||
placeholder='Masukkan tanggal transfer'
|
||||
value={formik.values.transfer_date}
|
||||
onChange={formik.handleChange}
|
||||
onBlur={formik.handleBlur}
|
||||
isError={
|
||||
formik.touched.transfer_date &&
|
||||
Boolean(formik.errors.transfer_date)
|
||||
}
|
||||
errorMessage={formik.errors.transfer_date}
|
||||
readOnly={type === 'detail'}
|
||||
/>
|
||||
|
||||
<div className='flex flex-col sm:flex-row gap-4'>
|
||||
<SelectInput
|
||||
required
|
||||
label='Flock Asal'
|
||||
placeholder='Flock asal'
|
||||
value={formik.values.flockSource as OptionType}
|
||||
options={flockSourceOptions}
|
||||
onChange={flockSourceChangeHandler}
|
||||
isLoading={isLoadingFlockSourceOptions}
|
||||
// onInputChange={setFlockSourceInputValue}
|
||||
isError={
|
||||
formik.touched.flockSource &&
|
||||
Boolean(typeof formik.errors.flockSource === 'string')
|
||||
}
|
||||
errorMessage={formik.errors.flockSource as string}
|
||||
isDisabled={type === 'detail'}
|
||||
isClearable
|
||||
/>
|
||||
|
||||
<SelectInput
|
||||
required
|
||||
label='Flock Tujuan'
|
||||
placeholder='Flock tujuan'
|
||||
value={formik.values.flockDestination as OptionType}
|
||||
options={flockDestinationOptions}
|
||||
onChange={flockDestinationChangeHandler}
|
||||
isLoading={isLoadingFlockDestinationOptions}
|
||||
// onInputChange={setFlockDestinationInputValue}
|
||||
isError={
|
||||
formik.touched.flockDestination &&
|
||||
Boolean(typeof formik.errors.flockDestination === 'string')
|
||||
}
|
||||
errorMessage={formik.errors.flockDestination as string}
|
||||
isDisabled={type === 'detail'}
|
||||
isClearable
|
||||
/>
|
||||
</div>
|
||||
|
||||
<TextInput
|
||||
required
|
||||
type='number'
|
||||
name='totalQuantity'
|
||||
label='Jumlah Transfer'
|
||||
bottomLabel={
|
||||
formikValues.maxTotalQuantity
|
||||
? `Max: ${formikValues.maxTotalQuantity}`
|
||||
: undefined
|
||||
}
|
||||
placeholder='Masukkan jumlah transfer'
|
||||
value={formik.values.totalQuantity ?? ''}
|
||||
onChange={formik.handleChange}
|
||||
onBlur={formik.handleBlur}
|
||||
isError={
|
||||
formik.touched.totalQuantity &&
|
||||
Boolean(formik.errors.totalQuantity)
|
||||
}
|
||||
errorMessage={formik.errors.totalQuantity}
|
||||
// readOnly={type === 'detail'}
|
||||
// disabled={Boolean(formik.errors.flockSource)}
|
||||
disabled
|
||||
/>
|
||||
|
||||
<div>
|
||||
<div className='overflow-x-auto'>
|
||||
<table className='table'>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Kandang</th>
|
||||
<th>Kuantitas</th>
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
{(!formik.values.kandangs ||
|
||||
formik.values.kandangs.length === 0) && (
|
||||
<tr>
|
||||
<td colSpan={2}>
|
||||
<p className='w-full text-center text-gray-400'>
|
||||
Pilih flock asal terlebih dahulu!
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
|
||||
{formik.values.kandangs &&
|
||||
formik.values.kandangs.map((kandang, idx) => (
|
||||
<tr key={idx}>
|
||||
<td>
|
||||
<SelectInput
|
||||
value={kandang.kandang}
|
||||
options={[]}
|
||||
isDisabled
|
||||
className={{
|
||||
wrapper: 'min-w-52',
|
||||
}}
|
||||
/>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
<TextInput
|
||||
required
|
||||
type='number'
|
||||
name={`kandangs[${idx}].quantity`}
|
||||
bottomLabel={
|
||||
kandang.maxQuantity
|
||||
? `Max: ${kandang.maxQuantity}`
|
||||
: undefined
|
||||
}
|
||||
placeholder='Masukkan kuantitas'
|
||||
value={kandang.quantity}
|
||||
onChange={formik.handleChange}
|
||||
onBlur={formik.handleBlur}
|
||||
isError={isRepeaterInputError('quantity', idx)}
|
||||
errorMessage={repeaterInputErrorMessage(
|
||||
'quantity',
|
||||
idx
|
||||
)}
|
||||
readOnly={type === 'detail'}
|
||||
className={{
|
||||
wrapper: 'min-w-52',
|
||||
}}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<TextArea
|
||||
required
|
||||
rows={5}
|
||||
name='reason'
|
||||
label='Alasan Transfer'
|
||||
placeholder='Alasan transfer'
|
||||
value={formik.values.reason}
|
||||
onChange={formik.handleChange}
|
||||
onBlur={formik.handleBlur}
|
||||
isError={formik.touched.reason && Boolean(formik.errors.reason)}
|
||||
errorMessage={formik.errors.reason}
|
||||
readOnly={type === 'detail'}
|
||||
disabled={Boolean(formik.errors.flockSource)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className='flex flex-row justify-between gap-2 flex-wrap'>
|
||||
{type !== 'add' && (
|
||||
<div className='flex flex-row justify-start gap-2'>
|
||||
<Button
|
||||
type='button'
|
||||
color='error'
|
||||
onClick={deleteTransferToLayingClickHandler}
|
||||
className='px-4'
|
||||
>
|
||||
<Icon
|
||||
icon='material-symbols:delete-outline-rounded'
|
||||
width={24}
|
||||
height={24}
|
||||
className='justify-start text-sm'
|
||||
/>
|
||||
Delete
|
||||
</Button>
|
||||
|
||||
{type !== 'edit' && (
|
||||
<Button
|
||||
type='button'
|
||||
color='warning'
|
||||
href={`/production/transfer-to-laying/detail/edit/?transferToLayingId=${initialValues?.id}`}
|
||||
className='px-4'
|
||||
>
|
||||
<Icon
|
||||
icon='material-symbols:edit-outline'
|
||||
width={24}
|
||||
height={24}
|
||||
className='justify-start text-sm'
|
||||
/>
|
||||
Edit
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{type !== 'detail' && (
|
||||
<div
|
||||
className={cn('flex flex-row justify-end gap-2', {
|
||||
'w-full': type === 'add',
|
||||
})}
|
||||
>
|
||||
<Button type='reset' color='warning' className='px-4'>
|
||||
Reset
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
type='submit'
|
||||
color='primary'
|
||||
isLoading={formik.isSubmitting}
|
||||
disabled={!formik.isValid || formik.isSubmitting}
|
||||
className='px-4'
|
||||
>
|
||||
Submit
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{formErrorMessage && (
|
||||
<div role='alert' className='alert alert-error'>
|
||||
<Icon
|
||||
icon='material-symbols:error-outline'
|
||||
width={24}
|
||||
height={24}
|
||||
/>
|
||||
<span>{formErrorMessage}</span>
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
</section>
|
||||
|
||||
{type !== 'add' && (
|
||||
<ConfirmationModal
|
||||
ref={deleteModal.ref}
|
||||
type='error'
|
||||
text='Apakah anda yakin ingin menghapus data transfer ke laying ini?'
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: 'error',
|
||||
isLoading: isDeleteLoading,
|
||||
onClick: confirmationModalDeleteClickHandler,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{type === 'detail' && (
|
||||
<>
|
||||
<ConfirmationModal
|
||||
ref={approveModal.ref}
|
||||
type='success'
|
||||
text='Apakah anda yakin ingin approve data transfer ke laying ini?'
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: 'success',
|
||||
isLoading: isApproveLoading,
|
||||
onClick: confirmationModalApproveClickHandler,
|
||||
}}
|
||||
/>
|
||||
|
||||
<ConfirmationModal
|
||||
ref={rejectModal.ref}
|
||||
type='error'
|
||||
text='Apakah anda yakin ingin reject data transfer ke laying ini?'
|
||||
secondaryButton={{
|
||||
text: 'Tidak',
|
||||
}}
|
||||
primaryButton={{
|
||||
text: 'Ya',
|
||||
color: 'error',
|
||||
isLoading: isRejectLoading,
|
||||
onClick: confirmationModalRejectClickHandler,
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default TransferToLayingForm;
|
||||
@@ -0,0 +1,34 @@
|
||||
import { ReactNode } from 'react';
|
||||
|
||||
import { cn } from '@/lib/helper';
|
||||
import { Color } from '@/types/theme';
|
||||
|
||||
interface StepItemProps {
|
||||
children?: ReactNode;
|
||||
icon?: ReactNode;
|
||||
className?: string;
|
||||
color?: Color;
|
||||
}
|
||||
|
||||
const StepItem = ({ children, icon, className, color }: StepItemProps) => {
|
||||
const stepItemBaseClassName = cn('step', {
|
||||
'step-primary': color === 'primary',
|
||||
'step-secondary': color === 'secondary',
|
||||
'step-accent': color === 'accent',
|
||||
'step-neutral': color === 'neutral',
|
||||
'step-info': color === 'info',
|
||||
'step-success': color === 'success',
|
||||
'step-warning': color === 'warning',
|
||||
'step-error': color === 'error',
|
||||
});
|
||||
|
||||
return (
|
||||
<li className={cn(stepItemBaseClassName, className)}>
|
||||
<span className='step-icon'>{icon}</span>
|
||||
|
||||
<div>{children}</div>
|
||||
</li>
|
||||
);
|
||||
};
|
||||
|
||||
export default StepItem;
|
||||
@@ -0,0 +1,23 @@
|
||||
import { ReactNode } from 'react';
|
||||
import { cn } from '@/lib/helper';
|
||||
|
||||
interface StepsProps {
|
||||
children?: ReactNode;
|
||||
className?: string;
|
||||
direction?: 'horizontal' | 'vertical';
|
||||
}
|
||||
|
||||
const Steps = ({ children, className, direction }: StepsProps) => {
|
||||
const stepsBaseClassName = cn('steps gap-2', {
|
||||
'steps-horizontal': direction === 'horizontal',
|
||||
'steps-vertical': direction === 'vertical',
|
||||
});
|
||||
|
||||
return (
|
||||
<ul className={cn(stepsBaseClassName, 'overflow-visible!', className)}>
|
||||
{children}
|
||||
</ul>
|
||||
);
|
||||
};
|
||||
|
||||
export default Steps;
|
||||
@@ -0,0 +1,71 @@
|
||||
import { Icon } from '@iconify/react';
|
||||
import Button from '../Button';
|
||||
import { cn } from '@/lib/helper';
|
||||
|
||||
interface TableRowOptionsProps {
|
||||
type?: 'dropdown' | 'collapse';
|
||||
recordId: string | number;
|
||||
basePath: string;
|
||||
onDelete?: () => void;
|
||||
queryParam?: string;
|
||||
showEdit?: boolean;
|
||||
showDelete?: boolean;
|
||||
}
|
||||
|
||||
export const TableRowOptions = ({
|
||||
type = 'dropdown',
|
||||
recordId,
|
||||
basePath,
|
||||
onDelete,
|
||||
queryParam = 'id',
|
||||
showEdit = true,
|
||||
showDelete = true,
|
||||
}: TableRowOptionsProps) => (
|
||||
<div
|
||||
tabIndex={type === 'dropdown' ? 0 : undefined}
|
||||
className={cn(
|
||||
{
|
||||
'dropdown-content': type === 'dropdown',
|
||||
'mt-2': type === 'collapse',
|
||||
},
|
||||
'p-2.5 mr-2 flex flex-col gap-1 bg-base-100 rounded-box z-10 border border-black/10 shadow'
|
||||
)}
|
||||
>
|
||||
<Button
|
||||
href={`${basePath}/detail/?${queryParam}=${recordId}`}
|
||||
variant='ghost'
|
||||
color='primary'
|
||||
className='justify-start text-sm'
|
||||
>
|
||||
<Icon icon='mdi:eye-outline' width={16} height={16} />
|
||||
Detail
|
||||
</Button>
|
||||
{showEdit && (
|
||||
<Button
|
||||
href={`${basePath}/detail/edit/?${queryParam}=${recordId}`}
|
||||
variant='ghost'
|
||||
color='warning'
|
||||
className='justify-start text-sm'
|
||||
>
|
||||
<Icon icon='mdi:pencil-outline' width={16} height={16} />
|
||||
Edit
|
||||
</Button>
|
||||
)}
|
||||
{showDelete && onDelete && (
|
||||
<Button
|
||||
onClick={onDelete}
|
||||
variant='ghost'
|
||||
color='error'
|
||||
className='text-error hover:text-inherit justify-start text-sm'
|
||||
>
|
||||
<Icon
|
||||
icon='mdi:delete-outline'
|
||||
width={16}
|
||||
height={16}
|
||||
className='justify-start text-sm'
|
||||
/>
|
||||
Delete
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
@@ -0,0 +1,33 @@
|
||||
import SelectInput from '../input/SelectInput';
|
||||
|
||||
export interface OptionType {
|
||||
label: string;
|
||||
value: string | number;
|
||||
}
|
||||
|
||||
interface TableRowSizeSelectorProps {
|
||||
value: number;
|
||||
onChange: (val: OptionType | OptionType[] | null) => void;
|
||||
options: OptionType[];
|
||||
}
|
||||
|
||||
export const TableRowSizeSelector = ({
|
||||
value,
|
||||
onChange,
|
||||
options,
|
||||
}: TableRowSizeSelectorProps) => {
|
||||
return (
|
||||
<div className='flex flex-row justify-end'>
|
||||
<SelectInput
|
||||
label='Baris'
|
||||
options={options}
|
||||
value={{
|
||||
label: String(value),
|
||||
value: value,
|
||||
}}
|
||||
onChange={onChange}
|
||||
className={{ wrapper: 'max-w-28' }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,37 @@
|
||||
import { Icon } from '@iconify/react';
|
||||
import Button from '../Button';
|
||||
import DebouncedTextInput from '../input/DebouncedTextInput';
|
||||
|
||||
interface TableToolbarProps {
|
||||
addButton?: {
|
||||
href: string;
|
||||
label: string;
|
||||
};
|
||||
search: {
|
||||
value: string;
|
||||
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
|
||||
placeholder?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export const TableToolbar = ({ addButton, search }: TableToolbarProps) => {
|
||||
return (
|
||||
<div className='w-full flex flex-col sm:flex-row justify-between items-end sm:items-center gap-2'>
|
||||
{addButton && (
|
||||
<div className='flex flex-row'>
|
||||
<Button href={addButton.href} color='primary'>
|
||||
<Icon icon='ic:round-plus' width={24} height={24} />
|
||||
{addButton.label}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<DebouncedTextInput
|
||||
name='search'
|
||||
placeholder={search.placeholder || 'Cari...'}
|
||||
value={search.value}
|
||||
onChange={search.onChange}
|
||||
className={{ wrapper: 'sm:max-w-3xs' }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
+73
-12
@@ -12,6 +12,57 @@ export const MAIN_DRAWER_LINKS: MAIN_DRAWER_MENU[] = [
|
||||
icon: 'gg:chart',
|
||||
},
|
||||
|
||||
{
|
||||
title: 'Produksi',
|
||||
link: '/production',
|
||||
icon: 'material-symbols:conveyor-belt-outline-rounded',
|
||||
submenu: [
|
||||
{
|
||||
title: 'List Flock',
|
||||
link: '/production/project-flock',
|
||||
icon: 'material-symbols:list-alt-add-outline-rounded',
|
||||
},
|
||||
{
|
||||
title: 'Chick In',
|
||||
link: '/production/chickin',
|
||||
icon: 'mdi:home-import-outline',
|
||||
},
|
||||
{
|
||||
title: 'Recording',
|
||||
link: '/production/recording',
|
||||
icon: 'mdi:clipboard-text',
|
||||
},
|
||||
{
|
||||
title: 'Transfer ke Laying',
|
||||
link: '/production/transfer-to-laying',
|
||||
icon: 'streamline:transfer-van',
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
{
|
||||
title: 'Persediaan',
|
||||
link: '/inventory',
|
||||
icon: 'mdi:warehouse',
|
||||
submenu: [
|
||||
// {
|
||||
// title: 'Product',
|
||||
// link: '/inventory/product',
|
||||
// icon: 'mdi:package-variant-closed',
|
||||
// },
|
||||
{
|
||||
title: 'Penyesuaian Stok',
|
||||
link: '/inventory/adjustment',
|
||||
icon: 'mdi:database-edit',
|
||||
},
|
||||
{
|
||||
title: 'Transfer Stok',
|
||||
link: '/inventory/movement',
|
||||
icon: 'mdi:swap-horizontal',
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
{
|
||||
title: 'Master Data',
|
||||
link: '/master-data',
|
||||
@@ -77,19 +128,12 @@ export const MAIN_DRAWER_LINKS: MAIN_DRAWER_MENU[] = [
|
||||
link: '/master-data/supplier',
|
||||
icon: 'material-symbols:add-business-outline-rounded',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Persediaan',
|
||||
link: '/inventory',
|
||||
icon: 'material-symbols:box-outline-rounded',
|
||||
submenu: [
|
||||
{
|
||||
title: 'Penyesuaian Persediaan',
|
||||
link: '/inventory/adjustment',
|
||||
icon: 'material-symbols:box-edit-outline-rounded',
|
||||
}
|
||||
]
|
||||
title: 'Flock',
|
||||
link: '/master-data/flock',
|
||||
icon: 'material-symbols:raven-outline-rounded',
|
||||
},
|
||||
],
|
||||
},
|
||||
] as const;
|
||||
|
||||
@@ -149,6 +193,17 @@ export const CATEGORY_OPTIONS = [
|
||||
},
|
||||
];
|
||||
|
||||
export const FLOCK_CATEGORY_OPTIONS = [
|
||||
{
|
||||
label: 'GROWING',
|
||||
value: 'GROWING',
|
||||
},
|
||||
{
|
||||
label: 'LAYING',
|
||||
value: 'LAYING',
|
||||
},
|
||||
];
|
||||
|
||||
export const PRODUCT_FLAG_OPTIONS = [
|
||||
{ label: 'DOC', value: 'DOC' },
|
||||
{ label: 'PAKAN', value: 'PAKAN' },
|
||||
@@ -164,3 +219,9 @@ export const PRODUCT_FLAG_OPTIONS = [
|
||||
export const SUPPLIER_FLAG_OPTIONS = [
|
||||
{ label: 'EKSPEDISI', value: 'EKSPEDISI' },
|
||||
];
|
||||
|
||||
export const RECORDING_FLAG_OPTIONS = [
|
||||
{ label: 'Ayam Afkir', value: 'Afkir' },
|
||||
{ label: 'Ayam Culling', value: 'Culling' },
|
||||
{ label: 'Ayam Mati', value: 'Mati' },
|
||||
];
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
export function toFormData(
|
||||
value: unknown,
|
||||
form = new FormData(),
|
||||
parentKey?: string
|
||||
) {
|
||||
if (value === undefined || value === null) {
|
||||
if (parentKey) form.append(parentKey, '');
|
||||
return form;
|
||||
}
|
||||
|
||||
if (value instanceof File) {
|
||||
if (!parentKey) throw new Error('File must have a key');
|
||||
form.append(parentKey, value);
|
||||
return form;
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((v, i) => {
|
||||
const key = parentKey ? `${parentKey}[${i}]` : `${i}`;
|
||||
toFormData(v, form, key);
|
||||
});
|
||||
return form;
|
||||
}
|
||||
|
||||
if (typeof value === 'object') {
|
||||
Object.entries(value as Record<string, unknown>).forEach(([k, v]) => {
|
||||
const key = parentKey ? `${parentKey}[${k}]` : k;
|
||||
toFormData(v, form, key);
|
||||
});
|
||||
return form;
|
||||
}
|
||||
|
||||
if (parentKey) form.append(parentKey, String(value));
|
||||
return form;
|
||||
}
|
||||
|
||||
export function containsFile(obj: unknown): boolean {
|
||||
if (!obj) return false;
|
||||
if (obj instanceof File) return true;
|
||||
if (Array.isArray(obj)) return obj.some(containsFile);
|
||||
if (typeof obj === 'object') {
|
||||
return Object.values(obj as Record<string, unknown>).some(containsFile);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
import moment from 'moment';
|
||||
import 'moment/locale/id';
|
||||
import { twMerge } from 'tailwind-merge';
|
||||
import clsx, { ClassValue } from 'clsx';
|
||||
|
||||
// set locale globally
|
||||
moment.locale('id');
|
||||
|
||||
export const sleep = (ms: number = 1000) =>
|
||||
new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
@@ -13,6 +17,19 @@ export const cn = (...inputs: ClassValue[]) => {
|
||||
return twMerge(clsx(inputs));
|
||||
};
|
||||
|
||||
export const formatNumber = (
|
||||
value: number | bigint | Intl.StringNumericLiteral,
|
||||
locale = 'en-US',
|
||||
minimumFractionDigits = 0,
|
||||
maximumFractionDigits = 2
|
||||
) => {
|
||||
return new Intl.NumberFormat(locale, {
|
||||
minimumFractionDigits,
|
||||
maximumFractionDigits,
|
||||
}).format(value);
|
||||
};
|
||||
|
||||
|
||||
export const formatCurrency = (
|
||||
value: number | bigint | Intl.StringNumericLiteral,
|
||||
currency = 'USD',
|
||||
@@ -27,3 +44,37 @@ export const formatCurrency = (
|
||||
maximumFractionDigits,
|
||||
}).format(value);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves a nested value from an object using a dot-delimited key path.
|
||||
* Supports array indexes (e.g., "users.0.name") and returns a default value
|
||||
* if the path does not exist.
|
||||
*
|
||||
* @param obj - The source object to search.
|
||||
* @param path - Dot-delimited key string (e.g., "user.address.city").
|
||||
* @param defaultValue - Optional value to return if the key path is not found.
|
||||
* @returns The value found at the specified path, or the default value.
|
||||
*/
|
||||
export function getByPath<T, D = undefined>(
|
||||
obj: T,
|
||||
path: string,
|
||||
defaultValue?: D
|
||||
): D {
|
||||
if (obj == null) return defaultValue as D;
|
||||
if (!path) return obj as D;
|
||||
|
||||
const segments = path.split('.').filter(Boolean);
|
||||
let cur: { [key: string]: unknown } = obj;
|
||||
|
||||
for (const seg of segments) {
|
||||
if (cur == null) return defaultValue as D;
|
||||
const key: string | number =
|
||||
Array.isArray(cur) && /^\d+$/.test(seg) ? Number(seg) : seg;
|
||||
if (Object(cur) !== cur || !(key in cur)) {
|
||||
return defaultValue as D;
|
||||
}
|
||||
cur = cur[key] as { [key: string]: unknown };
|
||||
}
|
||||
|
||||
return cur as D;
|
||||
}
|
||||
|
||||
@@ -4,9 +4,11 @@ import { BaseApiResponse } from '@/types/api/api-general';
|
||||
|
||||
export class BaseApiService<T, CreatePayloadGeneric, UpdatePayloadGeneric> {
|
||||
basePath: string;
|
||||
header?: Record<string, string>;
|
||||
|
||||
constructor(basePath: string) {
|
||||
constructor(basePath: string, header?: Record<string, string>) {
|
||||
this.basePath = basePath;
|
||||
this.header = header;
|
||||
}
|
||||
|
||||
async getAllFetcher(endpoint: string): Promise<BaseApiResponse<T[]>> {
|
||||
@@ -23,42 +25,52 @@ export class BaseApiService<T, CreatePayloadGeneric, UpdatePayloadGeneric> {
|
||||
if (axios.isAxiosError<BaseApiResponse<T>>(error)) {
|
||||
return error.response?.data;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
async create(payload: CreatePayloadGeneric) {
|
||||
const isFormData =
|
||||
typeof FormData !== 'undefined' && payload instanceof FormData;
|
||||
try {
|
||||
const headers = isFormData
|
||||
? { ...(this.header ?? {}) }
|
||||
: { 'Content-Type': 'application/json', ...(this.header ?? {}) };
|
||||
|
||||
const createRes = await httpClient<BaseApiResponse<T>>(this.basePath, {
|
||||
method: 'POST',
|
||||
body: payload,
|
||||
headers,
|
||||
});
|
||||
|
||||
return createRes;
|
||||
} catch (error: unknown) {
|
||||
if (axios.isAxiosError<BaseApiResponse<T>>(error)) {
|
||||
return error.response?.data;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
async update(id: number, payload: UpdatePayloadGeneric) {
|
||||
const isFormData =
|
||||
typeof FormData !== 'undefined' && payload instanceof FormData;
|
||||
try {
|
||||
const updatePath = `${this.basePath}/${id}`;
|
||||
|
||||
const headers = isFormData
|
||||
? { ...(this.header ?? {}) }
|
||||
: { 'Content-Type': 'application/json', ...(this.header ?? {}) };
|
||||
|
||||
const updateRes = await httpClient<BaseApiResponse<T>>(updatePath, {
|
||||
method: 'PATCH',
|
||||
body: payload,
|
||||
headers,
|
||||
});
|
||||
|
||||
return updateRes;
|
||||
} catch (error: unknown) {
|
||||
if (axios.isAxiosError<BaseApiResponse<T>>(error)) {
|
||||
return error.response?.data;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -69,13 +81,47 @@ export class BaseApiService<T, CreatePayloadGeneric, UpdatePayloadGeneric> {
|
||||
const deleteRes = await httpClient<BaseApiResponse>(deletePath, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
|
||||
return deleteRes;
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError<BaseApiResponse>(error)) {
|
||||
return error.response?.data;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
async customRequest<ResponseType = T, PayloadType = unknown>(
|
||||
endpoint: string,
|
||||
options?: {
|
||||
method?: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';
|
||||
payload?: PayloadType;
|
||||
params?: Record<string, string | number | boolean | undefined>;
|
||||
}
|
||||
): Promise<ResponseType | undefined> {
|
||||
try {
|
||||
const urlBase = endpoint.startsWith('http')
|
||||
? endpoint
|
||||
: `${this.basePath.replace(/\/$/, '')}/${endpoint.replace(/^\//, '')}`;
|
||||
|
||||
const url = options?.params
|
||||
? `${urlBase}?${new URLSearchParams(
|
||||
Object.entries(options.params).reduce((acc, [key, value]) => {
|
||||
if (value !== undefined) acc[key] = String(value);
|
||||
return acc;
|
||||
}, {} as Record<string, string>)
|
||||
)}`
|
||||
: urlBase;
|
||||
|
||||
const res = await httpClient<ResponseType>(url, {
|
||||
method: options?.method || 'GET',
|
||||
body: options?.payload,
|
||||
});
|
||||
|
||||
return res;
|
||||
} catch (error: unknown) {
|
||||
if (axios.isAxiosError<ResponseType>(error)) {
|
||||
return error.response?.data;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,33 @@
|
||||
import { BaseApiService } from '@/services/api/base';
|
||||
import {
|
||||
InventoryAdjustment,
|
||||
CreateInventoryAdjustmentPayload,
|
||||
CreateProductWarehousePayload,
|
||||
ProductWarehouse,
|
||||
UpdateProductWarehousePayload,
|
||||
} from '@/types/api/inventory/product-warehouse';
|
||||
import {
|
||||
CreateMovementPayload,
|
||||
Movement,
|
||||
UpdateMovementPayload,
|
||||
} from '@/types/api/inventory/movement';
|
||||
import {
|
||||
CreateInventoryAdjustmentPayload,
|
||||
InventoryAdjustment,
|
||||
} from '@/types/api/inventory/adjustment';
|
||||
import { BaseApiService } from './base';
|
||||
|
||||
export const ProductWarehouseApi = new BaseApiService<
|
||||
ProductWarehouse,
|
||||
CreateProductWarehousePayload,
|
||||
UpdateProductWarehousePayload
|
||||
>('/inventory/product-warehouses');
|
||||
|
||||
export const MovementApi = new BaseApiService<
|
||||
Movement,
|
||||
CreateMovementPayload,
|
||||
UpdateMovementPayload
|
||||
>('/inventory/transfers');
|
||||
|
||||
export const inventoryAdjustmentApi = new BaseApiService<
|
||||
InventoryAdjustment,
|
||||
CreateInventoryAdjustmentPayload,
|
||||
unknown
|
||||
>('/inventory/adjustments');
|
||||
InventoryAdjustment,
|
||||
CreateInventoryAdjustmentPayload,
|
||||
unknown
|
||||
>('/inventory/adjustments');
|
||||
|
||||
@@ -59,6 +59,11 @@ import {
|
||||
Fcr,
|
||||
UpdateFcrPayload,
|
||||
} from '@/types/api/master-data/fcr';
|
||||
import {
|
||||
CreateFlockPayload,
|
||||
Flock,
|
||||
UpdateFlockPayload,
|
||||
} from '@/types/api/master-data/flock';
|
||||
|
||||
export const UomApi = new BaseApiService<
|
||||
Uom,
|
||||
@@ -130,3 +135,9 @@ export const FcrApi = new BaseApiService<
|
||||
CreateFcrPayload,
|
||||
UpdateFcrPayload
|
||||
>('/master-data/fcrs');
|
||||
|
||||
export const FlockApi = new BaseApiService<
|
||||
Flock,
|
||||
CreateFlockPayload,
|
||||
UpdateFlockPayload
|
||||
>('/master-data/flocks');
|
||||
@@ -0,0 +1,32 @@
|
||||
import { BaseApiService } from './base';
|
||||
import {
|
||||
CreateProjectFlockPayload,
|
||||
ProjectFlock,
|
||||
UpdateProjectFlockPayload,
|
||||
} from '@/types/api/production/project-flock';
|
||||
import {
|
||||
CreateRecordingPayload,
|
||||
Recording,
|
||||
UpdateRecordingPayload,
|
||||
} from '@/types/api/production/recording';
|
||||
import {
|
||||
Chickin,
|
||||
CreateChickinPayload,
|
||||
UpdateChickinPayload,
|
||||
} from '@/types/api/production/chickin';
|
||||
|
||||
export const ProjectFlockApi = new BaseApiService<
|
||||
ProjectFlock,
|
||||
CreateProjectFlockPayload,
|
||||
UpdateProjectFlockPayload
|
||||
>('/production/project_flocks');
|
||||
export const RecordingApi = new BaseApiService<
|
||||
Recording,
|
||||
CreateRecordingPayload,
|
||||
UpdateRecordingPayload
|
||||
>('/production/recordings');
|
||||
export const ChickinApi = new BaseApiService<
|
||||
Chickin,
|
||||
CreateChickinPayload,
|
||||
UpdateChickinPayload
|
||||
>('/production/chickins');
|
||||
@@ -0,0 +1,876 @@
|
||||
import { sleep } from '@/lib/helper';
|
||||
import { BaseApiService } from '@/services/api/base';
|
||||
import { BaseApiResponse } from '@/types/api/api-general';
|
||||
|
||||
import {
|
||||
CreateTransferToLayingPayload,
|
||||
TransferToLaying,
|
||||
UpdateTransferToLayingPayload,
|
||||
} from '@/types/api/production/transfer-to-laying';
|
||||
import { FlockWithKandangs } from '@/types/api/master-data/flock';
|
||||
|
||||
// TODO: delete this dummy data
|
||||
const GET_ALL_TRANSFER_TO_LAYING_DUMMY_DATA: BaseApiResponse<
|
||||
TransferToLaying[]
|
||||
> = {
|
||||
code: 200,
|
||||
status: 'success',
|
||||
message: 'Successfully get all transfer to laying data!',
|
||||
meta: {
|
||||
page: 1,
|
||||
limit: 10,
|
||||
total_pages: 1,
|
||||
total_results: 8,
|
||||
},
|
||||
data: [
|
||||
{
|
||||
id: 201,
|
||||
transfer_date: '2025-10-10',
|
||||
flock_source: { id: 1, name: 'Flock A' },
|
||||
flock_destination: { id: 10, name: 'Laying House 1' },
|
||||
quantity: 1200,
|
||||
kandangs: [
|
||||
{
|
||||
kandang: {
|
||||
id: 11,
|
||||
name: 'KDG-11',
|
||||
status: 'ACTIVE',
|
||||
location: {
|
||||
id: 101,
|
||||
name: 'Farm Alpha',
|
||||
address: 'Jl. Raya Alpha No. 1',
|
||||
area: { id: 1001, name: 'Area Utara' },
|
||||
},
|
||||
pic: {
|
||||
id: 501,
|
||||
id_user: 501,
|
||||
email: 'rina@farm.co',
|
||||
name: 'Rina Setiawan',
|
||||
},
|
||||
created_user: {
|
||||
id: 9001,
|
||||
id_user: 9001,
|
||||
email: 'admin@farm.co',
|
||||
name: 'System Admin',
|
||||
},
|
||||
created_at: '2025-09-01T08:00:00Z',
|
||||
updated_at: '2025-10-01T08:00:00Z',
|
||||
},
|
||||
quantity: 600,
|
||||
},
|
||||
{
|
||||
kandang: {
|
||||
id: 12,
|
||||
name: 'KDG-12',
|
||||
status: 'ACTIVE',
|
||||
location: {
|
||||
id: 101,
|
||||
name: 'Farm Alpha',
|
||||
address: 'Jl. Raya Alpha No. 1',
|
||||
area: { id: 1001, name: 'Area Utara' },
|
||||
},
|
||||
pic: {
|
||||
id: 502,
|
||||
id_user: 502,
|
||||
email: 'budi@farm.co',
|
||||
name: 'Budi Hartono',
|
||||
},
|
||||
created_user: {
|
||||
id: 9002,
|
||||
id_user: 9002,
|
||||
email: 'ops@farm.co',
|
||||
name: 'Ops Bot',
|
||||
},
|
||||
created_at: '2025-08-25T08:00:00Z',
|
||||
updated_at: '2025-09-20T08:00:00Z',
|
||||
},
|
||||
quantity: 600,
|
||||
},
|
||||
],
|
||||
reason: 'Start laying cycle',
|
||||
created_user: {
|
||||
id: 9100,
|
||||
id_user: 9100,
|
||||
email: 'planner@farm.co',
|
||||
name: 'Planning',
|
||||
},
|
||||
created_at: '2025-10-10T06:00:00Z',
|
||||
updated_at: '2025-10-10T06:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 202,
|
||||
transfer_date: '2025-10-11',
|
||||
flock_source: { id: 2, name: 'Flock B' },
|
||||
flock_destination: { id: 10, name: 'Laying House 1' },
|
||||
quantity: 950,
|
||||
kandangs: [
|
||||
{
|
||||
kandang: {
|
||||
id: 13,
|
||||
name: 'KDG-13',
|
||||
status: 'ACTIVE',
|
||||
location: {
|
||||
id: 102,
|
||||
name: 'Farm Beta',
|
||||
address: 'Jl. Melati 2',
|
||||
area: { id: 1002, name: 'Area Selatan' },
|
||||
},
|
||||
pic: {
|
||||
id: 503,
|
||||
id_user: 503,
|
||||
email: 'sari@farm.co',
|
||||
name: 'Sari Wulandari',
|
||||
},
|
||||
created_user: {
|
||||
id: 9003,
|
||||
id_user: 9003,
|
||||
email: 'system@farm.co',
|
||||
name: 'System',
|
||||
},
|
||||
created_at: '2025-09-05T08:00:00Z',
|
||||
updated_at: '2025-10-02T08:00:00Z',
|
||||
},
|
||||
quantity: 500,
|
||||
},
|
||||
{
|
||||
kandang: {
|
||||
id: 14,
|
||||
name: 'KDG-14',
|
||||
status: 'MAINTENANCE',
|
||||
location: {
|
||||
id: 102,
|
||||
name: 'Farm Beta',
|
||||
address: 'Jl. Melati 2',
|
||||
area: { id: 1002, name: 'Area Selatan' },
|
||||
},
|
||||
pic: {
|
||||
id: 504,
|
||||
id_user: 504,
|
||||
email: 'agus@farm.co',
|
||||
name: 'Agus Pratama',
|
||||
},
|
||||
created_user: {
|
||||
id: 9003,
|
||||
id_user: 9003,
|
||||
email: 'system@farm.co',
|
||||
name: 'System',
|
||||
},
|
||||
created_at: '2025-07-15T08:00:00Z',
|
||||
updated_at: '2025-09-15T08:00:00Z',
|
||||
},
|
||||
quantity: 450,
|
||||
},
|
||||
],
|
||||
reason: 'Capacity balancing',
|
||||
created_user: {
|
||||
id: 9101,
|
||||
id_user: 9101,
|
||||
email: 'planner@farm.co',
|
||||
name: 'Planning',
|
||||
},
|
||||
created_at: '2025-10-11T06:00:00Z',
|
||||
updated_at: '2025-10-11T06:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 203,
|
||||
transfer_date: '2025-10-12',
|
||||
flock_source: { id: 3, name: 'Flock C' },
|
||||
flock_destination: { id: 11, name: 'Laying House 2' },
|
||||
quantity: 1100,
|
||||
kandangs: [
|
||||
{
|
||||
kandang: {
|
||||
id: 21,
|
||||
name: 'KDG-21',
|
||||
status: 'ACTIVE',
|
||||
location: {
|
||||
id: 103,
|
||||
name: 'Farm Gamma',
|
||||
address: 'Dusun Gamma',
|
||||
area: { id: 1003, name: 'Area Timur' },
|
||||
},
|
||||
pic: {
|
||||
id: 505,
|
||||
id_user: 505,
|
||||
email: 'dewi@farm.co',
|
||||
name: 'Dewi Lestari',
|
||||
},
|
||||
created_user: {
|
||||
id: 9004,
|
||||
id_user: 9004,
|
||||
email: 'ops@farm.co',
|
||||
name: 'Ops Bot',
|
||||
},
|
||||
created_at: '2025-09-10T08:00:00Z',
|
||||
updated_at: '2025-10-05T08:00:00Z',
|
||||
},
|
||||
quantity: 700,
|
||||
},
|
||||
{
|
||||
kandang: {
|
||||
id: 22,
|
||||
name: 'KDG-22',
|
||||
status: 'ACTIVE',
|
||||
location: {
|
||||
id: 103,
|
||||
name: 'Farm Gamma',
|
||||
address: 'Dusun Gamma',
|
||||
area: { id: 1003, name: 'Area Timur' },
|
||||
},
|
||||
pic: {
|
||||
id: 506,
|
||||
id_user: 506,
|
||||
email: 'hadi@farm.co',
|
||||
name: 'Hadi Santoso',
|
||||
},
|
||||
created_user: {
|
||||
id: 9004,
|
||||
id_user: 9004,
|
||||
email: 'ops@farm.co',
|
||||
name: 'Ops Bot',
|
||||
},
|
||||
created_at: '2025-09-12T08:00:00Z',
|
||||
updated_at: '2025-10-06T08:00:00Z',
|
||||
},
|
||||
quantity: 400,
|
||||
},
|
||||
],
|
||||
reason: 'Align age group',
|
||||
created_user: {
|
||||
id: 9102,
|
||||
id_user: 9102,
|
||||
email: 'scheduler@farm.co',
|
||||
name: 'Scheduler',
|
||||
},
|
||||
created_at: '2025-10-12T06:00:00Z',
|
||||
updated_at: '2025-10-12T06:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 204,
|
||||
transfer_date: '2025-10-13',
|
||||
flock_source: { id: 1, name: 'Flock A' },
|
||||
flock_destination: { id: 12, name: 'Laying House 3' },
|
||||
quantity: 800,
|
||||
kandangs: [
|
||||
{
|
||||
kandang: {
|
||||
id: 15,
|
||||
name: 'KDG-15',
|
||||
status: 'ACTIVE',
|
||||
location: {
|
||||
id: 101,
|
||||
name: 'Farm Alpha',
|
||||
address: 'Jl. Raya Alpha No. 1',
|
||||
area: { id: 1001, name: 'Area Utara' },
|
||||
},
|
||||
pic: {
|
||||
id: 507,
|
||||
id_user: 507,
|
||||
email: 'nadia@farm.co',
|
||||
name: 'Nadia Putri',
|
||||
},
|
||||
created_user: {
|
||||
id: 9001,
|
||||
id_user: 9001,
|
||||
email: 'admin@farm.co',
|
||||
name: 'System Admin',
|
||||
},
|
||||
created_at: '2025-08-01T08:00:00Z',
|
||||
updated_at: '2025-09-28T08:00:00Z',
|
||||
},
|
||||
quantity: 800,
|
||||
},
|
||||
],
|
||||
reason: 'Open capacity in LH3',
|
||||
created_user: {
|
||||
id: 9103,
|
||||
id_user: 9103,
|
||||
email: 'opslead@farm.co',
|
||||
name: 'Ops Lead',
|
||||
},
|
||||
created_at: '2025-10-13T06:00:00Z',
|
||||
updated_at: '2025-10-13T06:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 205,
|
||||
transfer_date: '2025-10-14',
|
||||
flock_source: { id: 4, name: 'Flock D' },
|
||||
flock_destination: { id: 11, name: 'Laying House 2' },
|
||||
quantity: 650,
|
||||
kandangs: [
|
||||
{
|
||||
kandang: {
|
||||
id: 23,
|
||||
name: 'KDG-23',
|
||||
status: 'ACTIVE',
|
||||
location: {
|
||||
id: 104,
|
||||
name: 'Farm Delta',
|
||||
address: 'Jl. Delta 4',
|
||||
area: { id: 1004, name: 'Area Barat' },
|
||||
},
|
||||
pic: {
|
||||
id: 508,
|
||||
id_user: 508,
|
||||
email: 'yoga@farm.co',
|
||||
name: 'Yoga Prabowo',
|
||||
},
|
||||
created_user: {
|
||||
id: 9005,
|
||||
id_user: 9005,
|
||||
email: 'ops@farm.co',
|
||||
name: 'Ops Bot',
|
||||
},
|
||||
created_at: '2025-09-20T08:00:00Z',
|
||||
updated_at: '2025-10-10T08:00:00Z',
|
||||
},
|
||||
quantity: 350,
|
||||
},
|
||||
{
|
||||
kandang: {
|
||||
id: 24,
|
||||
name: 'KDG-24',
|
||||
status: 'ACTIVE',
|
||||
location: {
|
||||
id: 104,
|
||||
name: 'Farm Delta',
|
||||
address: 'Jl. Delta 4',
|
||||
area: { id: 1004, name: 'Area Barat' },
|
||||
},
|
||||
pic: {
|
||||
id: 509,
|
||||
id_user: 509,
|
||||
email: 'mega@farm.co',
|
||||
name: 'Mega Anggraini',
|
||||
},
|
||||
created_user: {
|
||||
id: 9005,
|
||||
id_user: 9005,
|
||||
email: 'ops@farm.co',
|
||||
name: 'Ops Bot',
|
||||
},
|
||||
created_at: '2025-09-21T08:00:00Z',
|
||||
updated_at: '2025-10-10T08:00:00Z',
|
||||
},
|
||||
quantity: 300,
|
||||
},
|
||||
],
|
||||
reason: 'Fill remaining LH2 slots',
|
||||
created_user: {
|
||||
id: 9104,
|
||||
id_user: 9104,
|
||||
email: 'scheduler@farm.co',
|
||||
name: 'Scheduler',
|
||||
},
|
||||
created_at: '2025-10-14T06:00:00Z',
|
||||
updated_at: '2025-10-14T06:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 206,
|
||||
transfer_date: '2025-10-15',
|
||||
flock_source: { id: 2, name: 'Flock B' },
|
||||
flock_destination: { id: 12, name: 'Laying House 3' },
|
||||
quantity: 720,
|
||||
kandangs: [
|
||||
{
|
||||
kandang: {
|
||||
id: 16,
|
||||
name: 'KDG-16',
|
||||
status: 'ACTIVE',
|
||||
location: {
|
||||
id: 102,
|
||||
name: 'Farm Beta',
|
||||
address: 'Jl. Melati 2',
|
||||
area: { id: 1002, name: 'Area Selatan' },
|
||||
},
|
||||
pic: {
|
||||
id: 510,
|
||||
id_user: 510,
|
||||
email: 'rizky@farm.co',
|
||||
name: 'Rizky Maulana',
|
||||
},
|
||||
created_user: {
|
||||
id: 9003,
|
||||
id_user: 9003,
|
||||
email: 'system@farm.co',
|
||||
name: 'System',
|
||||
},
|
||||
created_at: '2025-08-12T08:00:00Z',
|
||||
updated_at: '2025-10-01T08:00:00Z',
|
||||
},
|
||||
quantity: 420,
|
||||
},
|
||||
{
|
||||
kandang: {
|
||||
id: 17,
|
||||
name: 'KDG-17',
|
||||
status: 'ACTIVE',
|
||||
location: {
|
||||
id: 102,
|
||||
name: 'Farm Beta',
|
||||
address: 'Jl. Melati 2',
|
||||
area: { id: 1002, name: 'Area Selatan' },
|
||||
},
|
||||
pic: {
|
||||
id: 511,
|
||||
id_user: 511,
|
||||
email: 'tia@farm.co',
|
||||
name: 'Tia Safitri',
|
||||
},
|
||||
created_user: {
|
||||
id: 9003,
|
||||
id_user: 9003,
|
||||
email: 'system@farm.co',
|
||||
name: 'System',
|
||||
},
|
||||
created_at: '2025-08-18T08:00:00Z',
|
||||
updated_at: '2025-10-01T08:00:00Z',
|
||||
},
|
||||
quantity: 300,
|
||||
},
|
||||
],
|
||||
reason: 'Stage-by-stage transfer',
|
||||
created_user: {
|
||||
id: 9105,
|
||||
id_user: 9105,
|
||||
email: 'opslead@farm.co',
|
||||
name: 'Ops Lead',
|
||||
},
|
||||
created_at: '2025-10-15T06:00:00Z',
|
||||
updated_at: '2025-10-15T06:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 207,
|
||||
transfer_date: '2025-10-16',
|
||||
flock_source: { id: 5, name: 'Flock E' },
|
||||
flock_destination: { id: 10, name: 'Laying House 1' },
|
||||
quantity: 500,
|
||||
kandangs: [
|
||||
{
|
||||
kandang: {
|
||||
id: 18,
|
||||
name: 'KDG-18',
|
||||
status: 'ACTIVE',
|
||||
location: {
|
||||
id: 105,
|
||||
name: 'Farm Epsilon',
|
||||
address: 'Kp. Epsilon',
|
||||
area: { id: 1005, name: 'Area Tengah' },
|
||||
},
|
||||
pic: {
|
||||
id: 512,
|
||||
id_user: 512,
|
||||
email: 'lukas@farm.co',
|
||||
name: 'Lukas Aditya',
|
||||
},
|
||||
created_user: {
|
||||
id: 9006,
|
||||
id_user: 9006,
|
||||
email: 'ops@farm.co',
|
||||
name: 'Ops Bot',
|
||||
},
|
||||
created_at: '2025-09-01T08:00:00Z',
|
||||
updated_at: '2025-10-12T08:00:00Z',
|
||||
},
|
||||
quantity: 250,
|
||||
},
|
||||
{
|
||||
kandang: {
|
||||
id: 19,
|
||||
name: 'KDG-19',
|
||||
status: 'ACTIVE',
|
||||
location: {
|
||||
id: 105,
|
||||
name: 'Farm Epsilon',
|
||||
address: 'Kp. Epsilon',
|
||||
area: { id: 1005, name: 'Area Tengah' },
|
||||
},
|
||||
pic: {
|
||||
id: 513,
|
||||
id_user: 513,
|
||||
email: 'maya@farm.co',
|
||||
name: 'Maya Kartika',
|
||||
},
|
||||
created_user: {
|
||||
id: 9006,
|
||||
id_user: 9006,
|
||||
email: 'ops@farm.co',
|
||||
name: 'Ops Bot',
|
||||
},
|
||||
created_at: '2025-09-03T08:00:00Z',
|
||||
updated_at: '2025-10-12T08:00:00Z',
|
||||
},
|
||||
quantity: 250,
|
||||
},
|
||||
],
|
||||
reason: 'Trial batch',
|
||||
created_user: {
|
||||
id: 9106,
|
||||
id_user: 9106,
|
||||
email: 'planner@farm.co',
|
||||
name: 'Planning',
|
||||
},
|
||||
created_at: '2025-10-16T06:00:00Z',
|
||||
updated_at: '2025-10-16T06:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 208,
|
||||
transfer_date: '2025-10-17',
|
||||
flock_source: { id: 6, name: 'Flock F' },
|
||||
flock_destination: { id: 13, name: 'Laying House 4' },
|
||||
quantity: 1300,
|
||||
kandangs: [
|
||||
{
|
||||
kandang: {
|
||||
id: 25,
|
||||
name: 'KDG-25',
|
||||
status: 'ACTIVE',
|
||||
location: {
|
||||
id: 106,
|
||||
name: 'Farm Zeta',
|
||||
address: 'Jl. Zeta 6',
|
||||
area: { id: 1006, name: 'Area Tenggara' },
|
||||
},
|
||||
pic: {
|
||||
id: 514,
|
||||
id_user: 514,
|
||||
email: 'rara@farm.co',
|
||||
name: 'Rara Pertiwi',
|
||||
},
|
||||
created_user: {
|
||||
id: 9007,
|
||||
id_user: 9007,
|
||||
email: 'ops@farm.co',
|
||||
name: 'Ops Bot',
|
||||
},
|
||||
created_at: '2025-09-07T08:00:00Z',
|
||||
updated_at: '2025-10-13T08:00:00Z',
|
||||
},
|
||||
quantity: 700,
|
||||
},
|
||||
{
|
||||
kandang: {
|
||||
id: 26,
|
||||
name: 'KDG-26',
|
||||
status: 'ACTIVE',
|
||||
location: {
|
||||
id: 106,
|
||||
name: 'Farm Zeta',
|
||||
address: 'Jl. Zeta 6',
|
||||
area: { id: 1006, name: 'Area Tenggara' },
|
||||
},
|
||||
pic: {
|
||||
id: 515,
|
||||
id_user: 515,
|
||||
email: 'doni@farm.co',
|
||||
name: 'Doni Firmansyah',
|
||||
},
|
||||
created_user: {
|
||||
id: 9007,
|
||||
id_user: 9007,
|
||||
email: 'ops@farm.co',
|
||||
name: 'Ops Bot',
|
||||
},
|
||||
created_at: '2025-09-09T08:00:00Z',
|
||||
updated_at: '2025-10-13T08:00:00Z',
|
||||
},
|
||||
quantity: 600,
|
||||
},
|
||||
],
|
||||
reason: 'Open new house',
|
||||
created_user: {
|
||||
id: 9107,
|
||||
id_user: 9107,
|
||||
email: 'scheduler@farm.co',
|
||||
name: 'Scheduler',
|
||||
},
|
||||
created_at: '2025-10-17T06:00:00Z',
|
||||
updated_at: '2025-10-17T06:00:00Z',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// TODO: delete this dummy data
|
||||
const FLOCK_SOURCE_DUMMY_DATA: BaseApiResponse<FlockWithKandangs[]> = {
|
||||
code: 200,
|
||||
status: 'success',
|
||||
message: 'Get all projectflocks successfully',
|
||||
meta: {
|
||||
page: 1,
|
||||
limit: 10,
|
||||
total_pages: 1,
|
||||
total_results: 2,
|
||||
},
|
||||
data: [
|
||||
{
|
||||
id: 2,
|
||||
name: 'Flock Banten',
|
||||
totalQuantity: 300,
|
||||
kandangs: [
|
||||
{
|
||||
kandang: {
|
||||
id: 3,
|
||||
name: 'Cikaum 1',
|
||||
status: 'ACTIVE',
|
||||
location: {
|
||||
id: 1,
|
||||
name: 'Singaparna',
|
||||
address: 'Tasik',
|
||||
area: {
|
||||
id: 1,
|
||||
name: 'test area',
|
||||
},
|
||||
},
|
||||
pic: {
|
||||
id: 1,
|
||||
id_user: 1,
|
||||
email: 'admin@mbugroup.id',
|
||||
name: 'Super Admin',
|
||||
},
|
||||
},
|
||||
quantity: 100,
|
||||
},
|
||||
{
|
||||
kandang: {
|
||||
id: 4,
|
||||
name: 'Cikaum 2',
|
||||
status: 'ACTIVE',
|
||||
location: {
|
||||
id: 1,
|
||||
name: 'Singaparna',
|
||||
address: 'Tasik',
|
||||
area: {
|
||||
id: 1,
|
||||
name: 'test area',
|
||||
},
|
||||
},
|
||||
pic: {
|
||||
id: 1,
|
||||
id_user: 1,
|
||||
email: 'admin@mbugroup.id',
|
||||
name: 'Super Admin',
|
||||
},
|
||||
},
|
||||
quantity: 150,
|
||||
},
|
||||
{
|
||||
kandang: {
|
||||
id: 5,
|
||||
name: 'Cikaum 3',
|
||||
status: 'ACTIVE',
|
||||
location: {
|
||||
id: 1,
|
||||
name: 'Singaparna',
|
||||
address: 'Tasik',
|
||||
area: {
|
||||
id: 1,
|
||||
name: 'test area',
|
||||
},
|
||||
},
|
||||
pic: {
|
||||
id: 1,
|
||||
id_user: 1,
|
||||
email: 'admin@mbugroup.id',
|
||||
name: 'Super Admin',
|
||||
},
|
||||
},
|
||||
quantity: 50,
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
{
|
||||
id: 3,
|
||||
name: 'Flock Priangan',
|
||||
totalQuantity: 200,
|
||||
kandangs: [
|
||||
{
|
||||
kandang: {
|
||||
id: 3,
|
||||
name: 'Cikaum 1',
|
||||
status: 'ACTIVE',
|
||||
location: {
|
||||
id: 1,
|
||||
name: 'Singaparna',
|
||||
address: 'Tasik',
|
||||
area: {
|
||||
id: 1,
|
||||
name: 'Priangan',
|
||||
},
|
||||
},
|
||||
pic: {
|
||||
id: 1,
|
||||
id_user: 1,
|
||||
email: 'admin@mbugroup.id',
|
||||
name: 'Super Admin',
|
||||
},
|
||||
},
|
||||
quantity: 100,
|
||||
},
|
||||
{
|
||||
kandang: {
|
||||
id: 4,
|
||||
name: 'Cikaum 2',
|
||||
status: 'ACTIVE',
|
||||
location: {
|
||||
id: 1,
|
||||
name: 'Singaparna',
|
||||
address: 'Tasik',
|
||||
area: {
|
||||
id: 1,
|
||||
name: 'test area',
|
||||
},
|
||||
},
|
||||
pic: {
|
||||
id: 1,
|
||||
id_user: 1,
|
||||
email: 'admin@mbugroup.id',
|
||||
name: 'Super Admin',
|
||||
},
|
||||
},
|
||||
quantity: 100,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export class TransferToLayingService extends BaseApiService<
|
||||
TransferToLaying,
|
||||
CreateTransferToLayingPayload,
|
||||
UpdateTransferToLayingPayload
|
||||
> {
|
||||
constructor(basePath: string = '') {
|
||||
super(basePath);
|
||||
}
|
||||
|
||||
// TODO: remove dummy data and integrate to real API
|
||||
override async getAllFetcher(
|
||||
endpoint: string
|
||||
): Promise<BaseApiResponse<TransferToLaying[]>> {
|
||||
// return await httpClientFetcher<BaseApiResponse<T[]>>(endpoint);
|
||||
|
||||
await sleep(750);
|
||||
|
||||
return GET_ALL_TRANSFER_TO_LAYING_DUMMY_DATA;
|
||||
}
|
||||
|
||||
// TODO: remove dummy data and integrate to real API
|
||||
async getFlockSource(): Promise<
|
||||
BaseApiResponse<FlockWithKandangs[]> | undefined
|
||||
> {
|
||||
try {
|
||||
// const getFlockSourcePath = `${this.basePath}/${flockSourcePath}`;
|
||||
// const getSingleRes = await httpClient<FlockSourceType>(getFlockSourcePath);
|
||||
// return getSingleRes;
|
||||
|
||||
await sleep(500);
|
||||
|
||||
return FLOCK_SOURCE_DUMMY_DATA;
|
||||
} catch (error) {
|
||||
// if (axios.isAxiosError<BaseApiResponse<T>>(error)) {
|
||||
// return error.response?.data;
|
||||
// }
|
||||
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: remove dummy data and integrate to real API
|
||||
async approve(
|
||||
id: number
|
||||
): Promise<BaseApiResponse<{ message: string }> | undefined> {
|
||||
try {
|
||||
await sleep(750);
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
status: 'success',
|
||||
message: 'Berhasil approve data transfer ke laying!',
|
||||
data: {
|
||||
message: 'Berhasil approve data transfer ke laying!',
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
// if (axios.isAxiosError<BaseApiResponse<T>>(error)) {
|
||||
// return error.response?.data;
|
||||
// }
|
||||
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: remove dummy data and integrate to real API
|
||||
async bulkApprove(
|
||||
ids: number[]
|
||||
): Promise<BaseApiResponse<{ message: string }> | undefined> {
|
||||
try {
|
||||
await sleep(750);
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
status: 'success',
|
||||
message: 'Berhasil approve data transfer ke laying!',
|
||||
data: {
|
||||
message: 'Berhasil approve data transfer ke laying!',
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
// if (axios.isAxiosError<BaseApiResponse<T>>(error)) {
|
||||
// return error.response?.data;
|
||||
// }
|
||||
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: remove dummy data and integrate to real API
|
||||
async reject(
|
||||
id: number
|
||||
): Promise<BaseApiResponse<{ message: string }> | undefined> {
|
||||
try {
|
||||
await sleep(750);
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
status: 'success',
|
||||
message: 'Berhasil reject data transfer ke laying!',
|
||||
data: {
|
||||
message: 'Berhasil reject data transfer ke laying!',
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
// if (axios.isAxiosError<BaseApiResponse<T>>(error)) {
|
||||
// return error.response?.data;
|
||||
// }
|
||||
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: remove dummy data and integrate to real API
|
||||
async bulkReject(
|
||||
ids: number[]
|
||||
): Promise<BaseApiResponse<{ message: string }> | undefined> {
|
||||
try {
|
||||
await sleep(750);
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
status: 'success',
|
||||
message: 'Berhasil reject data transfer ke laying!',
|
||||
data: {
|
||||
message: 'Berhasil reject data transfer ke laying!',
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
// if (axios.isAxiosError<BaseApiResponse<T>>(error)) {
|
||||
// return error.response?.data;
|
||||
// }
|
||||
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const TransferToLayingApi = new TransferToLayingService('');
|
||||
@@ -6,22 +6,43 @@ type AuthStore = {
|
||||
isLoadingUser?: boolean;
|
||||
setUser: (newUserData?: UserWithRoles) => void;
|
||||
setIsLoadingUser: (isLoading?: boolean) => void;
|
||||
permissionCheck: (permissionName: string) => boolean;
|
||||
};
|
||||
|
||||
const useAuthStore = create<AuthStore>()((set) => ({
|
||||
const useAuthStore = create<AuthStore>()((set, get) => ({
|
||||
user: undefined,
|
||||
isLoadingUser: false,
|
||||
setUser: (newUserData) => set({ user: newUserData }),
|
||||
setIsLoadingUser: (isLoading) => set({ isLoadingUser: Boolean(isLoading) }),
|
||||
|
||||
permissionCheck: (name) => {
|
||||
const { user, isLoadingUser } = get();
|
||||
|
||||
if (!isLoadingUser && user) {
|
||||
const isAllowed = user.roles.some((role) => {
|
||||
const isPermissionNameAllowed = role.permissions.some(
|
||||
(permission) => permission.name === name
|
||||
);
|
||||
|
||||
return isPermissionNameAllowed;
|
||||
});
|
||||
|
||||
return isAllowed;
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
}));
|
||||
|
||||
export const useAuth = () => {
|
||||
const { user, setUser, isLoadingUser, setIsLoadingUser } = useAuthStore();
|
||||
const { user, setUser, isLoadingUser, setIsLoadingUser, permissionCheck } =
|
||||
useAuthStore();
|
||||
|
||||
return {
|
||||
user,
|
||||
setUser,
|
||||
isLoadingUser,
|
||||
setIsLoadingUser,
|
||||
permissionCheck,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -14,6 +14,9 @@ export async function httpClient<T, B = unknown>(
|
||||
(!opts.auth && opts.auth !== 'none' && opts.auth !== 'bearer');
|
||||
const isBearerAuth = opts.auth === 'bearer' && !!opts.token;
|
||||
|
||||
const isFormData =
|
||||
typeof FormData !== 'undefined' && opts.body instanceof FormData;
|
||||
|
||||
const config: AxiosRequestConfig = {
|
||||
url: path,
|
||||
method: opts.method ?? 'GET',
|
||||
@@ -22,7 +25,7 @@ export async function httpClient<T, B = unknown>(
|
||||
timeout: opts.timeoutMs ?? 10_000,
|
||||
withCredentials: isCookieAuth && !isBearerAuth,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(isFormData ? {} : { 'Content-Type': 'application/json' }),
|
||||
...(opts.headers ?? {}),
|
||||
...(isBearerAuth && !isCookieAuth
|
||||
? { Authorization: `Bearer ${opts.token}` }
|
||||
|
||||
@@ -4,7 +4,7 @@ import { create } from 'zustand';
|
||||
import { devtools } from 'zustand/middleware';
|
||||
|
||||
import { UIStore } from '@/types/stores';
|
||||
import { createMainUiSlice } from './slices/main.slice';
|
||||
import { createMainUiSlice } from '@/stores/ui/slices/main.slice';
|
||||
|
||||
export const useUiStore = create<UIStore>()(
|
||||
devtools(
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user