Compare commits

..

12 Commits

431 changed files with 12136 additions and 63577 deletions
+27 -47
View File
@@ -2,17 +2,6 @@ stages:
- build
- deploy
# ==========================================================
# ✅ Global defaults
# ==========================================================
default:
tags:
- server-development-biznet
interruptible: true
# ==========================================================
# 🏗️ Build Template
# ==========================================================
.build_template: &build_template
stage: build
image: node:20-alpine
@@ -50,9 +39,6 @@ default:
- out/
expire_in: 1 week
# ==========================================================
# 🚀 Deploy Template
# ==========================================================
.deploy_template: &deploy_template
stage: deploy
image:
@@ -87,8 +73,8 @@ default:
if [ "$CI_COMMIT_BRANCH" = "development" ]; then
ENVIRONMENT_NAME="WEB-LTI-DEV"
elif [ "$CI_COMMIT_BRANCH" = "staging" ]; then
ENVIRONMENT_NAME="WEB-LTI-STAGING"
elif [ "$CI_COMMIT_BRANCH" = "master" ]; then
ENVIRONMENT_NAME="WEB-LTI-PROD"
else
ENVIRONMENT_NAME="UNKNOWN"
fi
@@ -96,11 +82,11 @@ default:
if [ "$STATUS" = "success" ]; then
COLOR=3066993
TITLE="✅ Deployment ${ENVIRONMENT_NAME} Succeeded"
DESC="Deployment job on branch \${CI_COMMIT_REF_NAME}\ completed successfully."
DESC="Deployment job on branch \`${CI_COMMIT_REF_NAME}\` completed successfully."
else
COLOR=15158332
TITLE="❌ Deployment ${ENVIRONMENT_NAME} Failed"
DESC="Deployment job on branch \${CI_COMMIT_REF_NAME}\ encountered issues."
DESC="Deployment job on branch \`${CI_COMMIT_REF_NAME}\` encountered issues."
fi
jq -n \
@@ -128,9 +114,7 @@ default:
curl -sS -H "Content-Type: application/json" -d @payload.json "$DISCORD_WEBHOOK_URL"
# ==========================================================
# ==== DEVELOPMENT (Branch development) ======
# ==========================================================
# ====== DEVELOPMENT (Branch development) ======
build:dev:
<<: *build_template
rules:
@@ -138,6 +122,8 @@ build:dev:
environment:
name: development
variables:
# NEXT_PUBLIC_API_BASE_URL: 'https://dev-api-lti.mbugroup.id'
# NEXT_PUBLIC_SSO_LOGIN_URL: 'https://dev-api-sso.mbugroup.id'
NEXT_PUBLIC_LTI_URL: 'https://dev-lti-erp.mbugroup.id'
NEXT_PUBLIC_SSO_LOGIN_URL: 'https://dev-auth-erp.mbugroup.id'
NEXT_PUBLIC_API_BASE_URL: 'https://dev-api-lti.mbugroup.id/api'
@@ -155,31 +141,25 @@ deploy:dev:
environment:
name: development
url: https://dev-lti-erp.mbugroup.id
# ====== PRODUCTION ======
# build:production:
# <<: *build_template
# rules:
# # pilih salah satu: pakai branch master ATAU pakai tags rilis
# - if: '$CI_COMMIT_BRANCH == "master"'
# # - if: '$CI_COMMIT_TAG' # kalau mau rilis via tag, uncomment ini dan hapus baris di atas
# environment:
# name: production
# ==========================================================
# ====== STAGING (Branch staging) ======
# ==========================================================
build:staging:
<<: *build_template
rules:
- if: '$CI_COMMIT_BRANCH == "staging"'
environment:
name: staging
variables:
NEXT_PUBLIC_LTI_URL: 'https://stg-lti-erp.mbugroup.id'
NEXT_PUBLIC_SSO_LOGIN_URL: 'https://stg-auth-erp.mbugroup.id'
NEXT_PUBLIC_API_BASE_URL: 'https://stg-api-lti.mbugroup.id/api'
NEXT_PUBLIC_CLIENT_ID: 'Lumbung-Telur-Indonesia'
# deploy:production:
# <<: *deploy_template
# needs: ["build:production"]
# rules:
# - if: '$CI_COMMIT_BRANCH == "master"'
# # - if: '$CI_COMMIT_TAG' # selaras dengan rule di build:production
# variables:
# S3_BUCKET: "lti-erp.mbugroup.id"
# CLOUDFRONT_DISTRIBUTION_ID: "ddfd"
# environment:
# name: production
deploy:staging:
<<: *deploy_template
needs: ['build:staging']
rules:
- if: '$CI_COMMIT_BRANCH == "staging"'
variables:
S3_BUCKET: 'stg-lti-erp.mbugroup.id'
AWS_REGION: 'ap-southeast-3'
CLOUDFRONT_DISTRIBUTION_ID: 'E2V6PPO1AUIU7H'
environment:
name: staging
url: https://stg-lti-erp.mbugroup.id
+1 -1
View File
@@ -1,3 +1,3 @@
npm run format
npm run lint
npx tsc --noEmit
npm run build
+43 -4369
View File
File diff suppressed because it is too large Load Diff
+4 -21
View File
@@ -15,37 +15,20 @@
"@tanstack/match-sorter-utils": "^8.19.4",
"@tanstack/react-table": "^8.21.3",
"axios": "^1.12.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"embla-carousel-react": "^8.6.0",
"exceljs": "^4.4.0",
"formik": "^2.4.6",
"html-to-image": "^1.11.13",
"input-otp": "^1.4.2",
"jspdf": "^3.0.4",
"jspdf-autotable": "^5.0.2",
"lucide-react": "^0.562.0",
"moment": "^2.30.1",
"next": "15.5.9",
"next-themes": "^0.4.6",
"radix-ui": "^1.4.3",
"react": "^19.1.2",
"next": "^15.5.7",
"react": "19.1.0",
"react-day-picker": "^9.11.1",
"react-dom": "^19.1.2",
"react-dom": "19.1.0",
"react-dropzone": "^14.3.8",
"react-hook-form": "^7.70.0",
"react-hot-toast": "^2.6.0",
"react-number-format": "^5.4.4",
"react-resizable-panels": "2.1.7",
"react-select": "^5.10.2",
"recharts": "^3.6.0",
"sonner": "^2.0.7",
"swr": "^2.3.6",
"tailwind-merge": "^3.3.1",
"use-debounce": "^10.0.6",
"vaul": "^1.1.2",
"xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
"yup": "^1.7.0",
"zustand": "^5.0.8"
},
@@ -56,7 +39,7 @@
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"daisyui": "^5.5.14",
"daisyui": "^5.5.8",
"eslint": "^9",
"eslint-config-next": "^15.5.7",
"husky": "^9.1.7",
+3 -56
View File
@@ -7,58 +7,21 @@ import ClosingDetail from '@/components/pages/closing/ClosingDetail';
import { ClosingApi } from '@/services/api/closing';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { FlockApi } from '@/services/api/master-data';
import { ProjectFlockApi } from '@/services/api/production/project-flock';
import { ProjectFlockKandangApi } from '@/services/api/production';
const ClosingDetailPage = () => {
const router = useRouter();
const searchParams = useSearchParams();
const closingId = searchParams.get('closingId');
const kandangId = searchParams.get('kandangId'); // project flock kandang ID
const { data: closing, isLoading: isLoadingClosing } = useSWR(
closingId,
(id: number) => ClosingApi.getGeneralInfo(id)
);
// WORKAROUND - get flock data from closing ID
const { data: projectData, isLoading: isLoadingProject } = useSWR(
`flock-${closingId}`,
() => ProjectFlockApi.getSingle(Number(closingId))
);
// WORKAROUND - get kandang data from closing ID
const { data: kandangData, isLoading: isLoadingKandang } = useSWR(
kandangId ? `kandang-${closingId}-${kandangId}` : null,
() => ProjectFlockKandangApi.getSingle(Number(kandangId))
);
const { data: salesData, isLoading: isLoadingSales } = useSWR(
kandangId
? `sales-${closingId}-${kandangId}`
: closingId
? `sales-${closingId}`
: null,
() =>
kandangId
? ClosingApi.getPenjualanByKandang(Number(closingId), Number(kandangId))
: ClosingApi.getPenjualan(Number(closingId))
);
const { data: hppEkspedisiData, isLoading: isLoadingHppEkspedisi } = useSWR(
kandangId
? `hpp-ekspedisi-${closingId}-${kandangId}`
: closingId
? `hpp-ekspedisi-${closingId}`
: null,
() =>
kandangId
? ClosingApi.getHppEkspedisiByKandang(
Number(closingId),
Number(kandangId)
)
: ClosingApi.getHppEkspedisi(Number(closingId))
closingId ? `sales-${closingId}` : null,
() => ClosingApi.getPenjualan(Number(closingId))
);
if (!closingId) {
@@ -76,12 +39,7 @@ const ClosingDetailPage = () => {
return;
}
const isLoading =
isLoadingClosing ||
isLoadingSales ||
isLoadingHppEkspedisi ||
isLoadingProject ||
isLoadingKandang;
const isLoading = isLoadingClosing || isLoadingSales;
return (
<div className='w-full p-4 flex flex-row justify-center'>
@@ -92,17 +50,6 @@ const ClosingDetailPage = () => {
id={Number(closingId)}
initialValue={closing.data}
salesData={isResponseSuccess(salesData) ? salesData.data : undefined}
hppExpeditionData={
isResponseSuccess(hppEkspedisiData)
? hppEkspedisiData.data
: undefined
}
projectData={
isResponseSuccess(projectData) ? projectData.data : undefined
}
kandangData={
isResponseSuccess(kandangData) ? kandangData.data : undefined
}
/>
)}
</div>
@@ -1,11 +0,0 @@
import { DailyChecklistContent } from '@/figma-make/components/pages/daily-checklist/DailyChecklistContent';
const DailyChecklistPage = () => {
return (
<section className='w-full'>
<DailyChecklistContent />
</section>
);
};
export default DailyChecklistPage;
@@ -1,11 +0,0 @@
import { Dashboard as DashboardDailyChecklist } from '@/figma-make/components/pages/dashboard/Dashboard';
const DailyChecklistDashboardPage = () => {
return (
<section className='w-full'>
<DashboardDailyChecklist />
</section>
);
};
export default DailyChecklistDashboardPage;
@@ -1,11 +0,0 @@
import { DetailDailyChecklistContent } from '@/figma-make/components/pages/list-daily-checklist/detail/DetailDailyChecklistContent';
const ListDailyChecklistDetailPage = () => {
return (
<section className='w-full'>
<DetailDailyChecklistContent />
</section>
);
};
export default ListDailyChecklistDetailPage;
@@ -1,11 +0,0 @@
import { ListDailyChecklistContent } from '@/figma-make/components/pages/list-daily-checklist/ListDailyChecklistContent';
const ListDailyChecklistPage = () => {
return (
<section className='w-full'>
<ListDailyChecklistContent />
</section>
);
};
export default ListDailyChecklistPage;
@@ -1,11 +0,0 @@
import { MasterAktivitasContent } from '@/figma-make/components/pages/master-data/activity/MasterAktivitasContent';
const MasterAktivitasPage = () => {
return (
<section className='w-full'>
<MasterAktivitasContent />
</section>
);
};
export default MasterAktivitasPage;
@@ -1,11 +0,0 @@
import { MasterConfigurationContent } from '@/figma-make/components/pages/master-data/configuration/MasterConfigurationContent';
const MasterConfigurationPage = () => {
return (
<section className='w-full'>
<MasterConfigurationContent />
</section>
);
};
export default MasterConfigurationPage;
@@ -1,11 +0,0 @@
import { MasterEmployeeContent } from '@/figma-make/components/pages/master-data/employee/MasterEmployeeContent';
const MasterEmployeePage = () => {
return (
<section className='w-full'>
<MasterEmployeeContent />
</section>
);
};
export default MasterEmployeePage;
-11
View File
@@ -1,11 +0,0 @@
import { DailyChecklistReportsContent } from '@/figma-make/components/pages/reports/DailyChecklistReportsContent';
const DailyChecklistReportsPage = () => {
return (
<section className='w-full'>
<DailyChecklistReportsContent />
</section>
);
};
export default DailyChecklistReportsPage;
+5 -3
View File
@@ -1,7 +1,9 @@
import DashboardProduction from '@/components/pages/dashboard/DashboardProduction';
const Dashboard = () => {
return <DashboardProduction />;
return (
<section className='w-full p-4'>
<h1 className='text-3xl font-bold text-primary'>Dashboard</h1>
</section>
);
};
export default Dashboard;
+1 -3
View File
@@ -38,11 +38,9 @@ const ExpenseEditPage = () => {
!isLoadingExpense &&
isResponseSuccess(expense) &&
expense.data.latest_approval.step_number !== 5 &&
expense.data.latest_approval.step_number !== 6 &&
(expense.data.latest_approval.step_number === 1 ||
expense.data.latest_approval.step_number === 2 ||
expense.data.latest_approval.step_number === 3 ||
expense.data.latest_approval.step_number === 4);
expense.data.latest_approval.step_number === 3);
if (!isLoadingExpense && !isExpenseCanBeEdited) {
router.back();
+1 -1
View File
@@ -2,7 +2,7 @@ import ExpensesTable from '@/components/pages/expense/ExpensesTable';
const Expense = () => {
return (
<section className='w-full p-4 sm:p-0'>
<section className='w-full p-4'>
<ExpensesTable />
</section>
);
+2 -2
View File
@@ -38,8 +38,8 @@ const ExpenseRealizationEditPage = () => {
!isLoadingExpense &&
isResponseSuccess(expense) &&
expense.data.latest_approval.action !== 'REJECTED' &&
(expense.data.latest_approval.step_number === 5 ||
expense.data.latest_approval.step_number === 6);
(expense.data.latest_approval.step_number === 4 ||
expense.data.latest_approval.step_number === 5);
if (!isLoadingExpense && !isExpenseRealizationCanBeEdited) {
router.back();
+1 -1
View File
@@ -37,7 +37,7 @@ const ExpenseRealization = () => {
const isExpenseCanBeRealized =
isResponseSuccess(expense) &&
expense.data.latest_approval.action !== 'REJECTED' &&
expense.data.latest_approval.step_number === 4;
expense.data.latest_approval.step_number === 3;
if (isResponseSuccess(expense) && !isExpenseCanBeRealized) {
if (typeof window !== 'undefined') {
-5
View File
@@ -1,5 +0,0 @@
const FinanceAdjust = () => {
return <div>Finance Adjust</div>;
};
export default FinanceAdjust;
@@ -1,7 +0,0 @@
import FormFinanceAddInitialBalance from '@/components/pages/finance/add/initial-balance/FormFinanceAddInitialBalance';
const FinanceAddInitialBalancePage = () => {
return <FormFinanceAddInitialBalance type='add' />;
};
export default FinanceAddInitialBalancePage;
-7
View File
@@ -1,7 +0,0 @@
import FormFinanceInjection from '@/components/pages/finance/add/injection/FormFinanceInjection';
const FinanceAddInjectionPage = () => {
return <FormFinanceInjection type='add' />;
};
export default FinanceAddInjectionPage;
+11 -2
View File
@@ -1,7 +1,16 @@
import FormFinanceAdd from '@/components/pages/finance/add/FormFinanceAdd';
import FinanceForm from '@/components/pages/finance/form/FinanceForm';
import { Metadata } from 'next';
export const metadata: Metadata = {
title: 'Finance | Add',
};
const FinanceAddPage = () => {
return <FormFinanceAdd />;
return (
<div className='w-full p-4 flex flex-row justify-center'>
<FinanceForm formType='add' />
</div>
);
};
export default FinanceAddPage;
@@ -1,51 +0,0 @@
'use client';
import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';
import { FinanceApi } from '@/services/api/finance';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import FormFinanceAddInitialBalance from '@/components/pages/finance/add/initial-balance/FormFinanceAddInitialBalance';
const EditFinanceInitialBalancePage = () => {
const router = useRouter();
const searchParams = useSearchParams();
const financeId = searchParams.get('financeId');
const { data: finance, isLoading: isLoadingFinance } = useSWR(
financeId,
(id: number) => FinanceApi.getSingle(id)
);
if (!financeId) {
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 (!isLoadingFinance && (!finance || isResponseError(finance))) {
router.replace('/404');
return;
}
return (
<div className='w-full p-4 flex flex-row justify-center'>
{isLoadingFinance && (
<span className='loading loading-spinner loading-xl' />
)}
{!isLoadingFinance && (
<FormFinanceAddInitialBalance
type='edit'
initialValues={isResponseSuccess(finance) ? finance.data : undefined}
/>
)}
</div>
);
};
export default EditFinanceInitialBalancePage;
@@ -1,51 +0,0 @@
'use client';
import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';
import { FinanceApi } from '@/services/api/finance';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import FormFinanceInjection from '@/components/pages/finance/add/injection/FormFinanceInjection';
const EditFinanceInjectionPage = () => {
const router = useRouter();
const searchParams = useSearchParams();
const financeId = searchParams.get('financeId');
const { data: finance, isLoading: isLoadingFinance } = useSWR(
financeId,
(id: number) => FinanceApi.getSingle(id)
);
if (!financeId) {
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 (!isLoadingFinance && (!finance || isResponseError(finance))) {
router.replace('/404');
return;
}
return (
<div className='w-full p-4 flex flex-row justify-center'>
{isLoadingFinance && (
<span className='loading loading-spinner loading-xl' />
)}
{!isLoadingFinance && (
<FormFinanceInjection
type='edit'
initialValues={isResponseSuccess(finance) ? finance.data : undefined}
/>
)}
</div>
);
};
export default EditFinanceInjectionPage;
-52
View File
@@ -1,52 +0,0 @@
'use client';
import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';
import { FinanceApi } from '@/services/api/finance';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import FormFinanceAdd from '@/components/pages/finance/add/FormFinanceAdd';
import FormFinanceAddInitialBalance from '@/components/pages/finance/add/initial-balance/FormFinanceAddInitialBalance';
const EditFinanceTransactionPage = () => {
const router = useRouter();
const searchParams = useSearchParams();
const financeId = searchParams.get('financeId');
const { data: finance, isLoading: isLoadingFinance } = useSWR(
financeId,
(id: number) => FinanceApi.getSingle(id)
);
if (!financeId) {
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 (!isLoadingFinance && (!finance || isResponseError(finance))) {
router.replace('/404');
return;
}
return (
<div className='w-full p-4 flex flex-row justify-center'>
{isLoadingFinance && (
<span className='loading loading-spinner loading-xl' />
)}
{!isLoadingFinance && (
<FormFinanceAdd
type='edit'
initialValues={isResponseSuccess(finance) ? finance.data : undefined}
/>
)}
</div>
);
};
export default EditFinanceTransactionPage;
-39
View File
@@ -1,39 +0,0 @@
'use client';
import FinanceDetail from '@/components/pages/finance/FinanceDetail';
import useSWR from 'swr';
import { useRouter, useSearchParams } from 'next/navigation';
import { FinanceApi } from '@/services/api/finance';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
const FinanceDetailPage = () => {
const router = useRouter();
const financeId = useSearchParams().get('financeId');
const { data: finance } = useSWR(financeId, () =>
FinanceApi.getSingle(Number(financeId))
);
if (!financeId) {
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 (!finance || isResponseError(finance)) {
// router.replace('/404');
// return;
// }
return (
<>
{isResponseSuccess(finance) && <FinanceDetail finance={finance.data} />}
</>
);
};
export default FinanceDetailPage;
+3 -6
View File
@@ -1,12 +1,9 @@
'use client';
import FinanceTable from '@/components/pages/finance/FinanceTable';
import FinancesTable from '@/components/pages/finance/FinancesTable';
const Finance = () => {
return (
<section className='size-full p-6'>
<div className='flex flex-row gap-4'></div>
<FinanceTable />
<section className='w-full p-4'>
<FinancesTable />
</section>
);
};
+5 -11
View File
@@ -1,8 +1,6 @@
@import 'tailwindcss';
@plugin "daisyui";
@import '../styles/tailwind.css';
@import '../styles/daisyui.css';
@import '../figma-make/styles/theme.css';
@plugin "daisyui/theme" {
name: 'lti';
@@ -30,16 +28,16 @@
--color-base-100: oklch(100% 0 0); /* #ffffff */
--color-base-200: oklch(97.2% 0 0); /* #f2f2f2 */
--color-base-300: oklch(93.1% 0.002 249.7); /* #e5e6e6 */
--color-base-content: #18181b;
--color-base-content: oklch(18.6% 0.024 257.7); /* #1f2937 */
/* Status/Utility Colors */
--color-info: oklch(67.4% 0.176 238.9);
--color-info-content: oklch(0% 0 0); /* #000000 */
--color-success: #00d390;
--color-success: oklch(62.3% 0.147 149);
--color-success-content: oklch(100% 0 0); /* #ffffff */
--color-warning: #fcb700;
--color-warning: oklch(82.2% 0.165 91.9);
--color-warning-content: oklch(0% 0 0); /* #000000 */
--color-error: #ff3a3a;
--color-error: oklch(61.8% 0.203 27.8);
--color-error-content: oklch(100% 0 0); /* #fffffff */
--radius-selector: 0rem;
@@ -53,21 +51,17 @@
}
:root {
--color-primary: #0069e0;
--color-primary: #1f74bf;
}
@theme {
--font-inter: var(--font-inter);
--font-roboto: var(--font-roboto);
--container-sm: 40rem;
--container-md: 48rem;
--container-lg: 64rem;
--container-xl: 80rem;
--container-2xl: 96rem;
--shadow-button-soft:
0 3px 2px -2px var(--color-base-200), 0 4px 3px -2px var(--color-base-200);
}
html {
+1 -1
View File
@@ -2,7 +2,7 @@ import MovementTable from '@/components/pages/inventory/movement/MovementTable';
const Movement = () => {
return (
<section className='w-full p-4 sm:p-0'>
<section className='w-full p-4'>
<MovementTable />
</section>
);
+2 -12
View File
@@ -1,9 +1,8 @@
import type { Metadata, Viewport } from 'next';
import { Inter, Roboto } from 'next/font/google';
import { Inter } from 'next/font/google';
import '@/app/globals.css';
import { Toaster } from 'react-hot-toast';
import { Toaster as SonnerToaster } from '@/figma-make/components/base/sonner';
import MainDrawer from '@/components/MainDrawer';
import RequireAuth from '@/components/helper/RequireAuth';
@@ -12,12 +11,6 @@ const inter = Inter({
subsets: ['latin'],
});
const roboto = Roboto({
variable: '--font-roboto',
subsets: ['latin'],
weight: ['200', '300', '400', '500', '600', '700', '900'],
});
export const viewport: Viewport = {
themeColor: '#1f74bf',
colorScheme: 'light',
@@ -36,15 +29,12 @@ export default function RootLayout({
}>) {
return (
<html lang='en' data-theme='lti'>
<body
className={`${inter.variable} ${roboto.variable} antialiased font-inter`}
>
<body className={`${inter.variable} antialiased font-inter`}>
<RequireAuth>
<MainDrawer>{children}</MainDrawer>
</RequireAuth>
<Toaster />
<SonnerToaster position='top-right' />
</body>
</html>
);
+1 -6
View File
@@ -1,14 +1,9 @@
import DeliveryOrderFormModal from '@/components/pages/marketing/DeliveryOrderFormModal';
import MarketingTable from '@/components/pages/marketing/MarketingTable';
import SalesOrderFormModal from '@/components/pages/marketing/SalesOrderFormModal';
const Marketing = () => {
return (
<div className='w-full'>
<div className='w-full p-4'>
<MarketingTable />
<SalesOrderFormModal />
<DeliveryOrderFormModal />
</div>
);
};
@@ -1,13 +0,0 @@
'use client';
import ProductionStandardForm from '@/components/pages/master-data/production-standard/form/ProductionStandardForm';
const AddProductionStandardPage = () => {
return (
<>
<ProductionStandardForm formType='add' />
</>
);
};
export default AddProductionStandardPage;
@@ -1,56 +0,0 @@
'use client';
import ProductionStandardForm from '@/components/pages/master-data/production-standard/form/ProductionStandardForm';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { ProductionStandardApi } from '@/services/api/master-data';
import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';
const EditProductionStandardPage = () => {
const router = useRouter();
const searchParams = useSearchParams();
// Get Query Params
const productionStandardId = searchParams.get('productionStandardId');
// Fetch Data
const { data: productionStandard, isLoading: isLoadingProductionStandard } =
useSWR(productionStandardId, (id: number) =>
ProductionStandardApi.getSingle(id)
);
if (!productionStandardId) {
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 (
!isLoadingProductionStandard &&
(!productionStandard || isResponseError(productionStandard))
) {
router.replace('/404');
return;
}
return (
<>
{isLoadingProductionStandard && (
<span className='loading loading-spinner loading-xl' />
)}
{!isLoadingProductionStandard &&
isResponseSuccess(productionStandard) && (
<ProductionStandardForm
formType='edit'
initialValue={productionStandard.data}
/>
)}
</>
);
};
export default EditProductionStandardPage;
@@ -1,11 +0,0 @@
import SuspenseHelper from '@/components/helper/SuspenseHelper';
const Layout = ({
children,
}: Readonly<{
children: React.ReactNode;
}>) => {
return <SuspenseHelper>{children}</SuspenseHelper>;
};
export default Layout;
@@ -1,56 +0,0 @@
'use client';
import ProductionStandardForm from '@/components/pages/master-data/production-standard/form/ProductionStandardForm';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { ProductionStandardApi } from '@/services/api/master-data';
import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';
const DetailProductionStandardPage = () => {
const router = useRouter();
const searchParams = useSearchParams();
// Get Query Params
const productionStandardId = searchParams.get('productionStandardId');
// Fetch Data
const { data: productionStandard, isLoading: isLoadingProductionStandard } =
useSWR(productionStandardId, (id: number) =>
ProductionStandardApi.getSingle(id)
);
if (!productionStandardId) {
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 (
!isLoadingProductionStandard &&
(!productionStandard || isResponseError(productionStandard))
) {
router.replace('/404');
return;
}
return (
<>
{isLoadingProductionStandard && (
<span className='loading loading-spinner loading-xl' />
)}
{!isLoadingProductionStandard &&
isResponseSuccess(productionStandard) && (
<ProductionStandardForm
formType='detail'
initialValue={productionStandard.data}
/>
)}
</>
);
};
export default DetailProductionStandardPage;
@@ -1,11 +0,0 @@
import ProductionStandardTable from '@/components/pages/master-data/production-standard/ProductionStandardTable';
const ProductionStandardPage = () => {
return (
<div className='w-full'>
<ProductionStandardTable />
</div>
);
};
export default ProductionStandardPage;
-5
View File
@@ -1,5 +0,0 @@
import PageNotFound from '@/components/helper/NotFoundPage';
export default function NotFound() {
return <PageNotFound />;
}
+1 -5
View File
@@ -25,9 +25,5 @@ export default function Home() {
);
}
return (
<main className='w-full h-full min-h-screen flex flex-row justify-center items-center'>
<span className='loading loading-spinner loading-lg'></span>
</main>
);
return <>Loading...</>;
}
@@ -0,0 +1,20 @@
'use client';
import { FormHeader } from '@/components/helper/form/FormHeader';
import ProjectFlockChickinDetail from '@/components/pages/production/project-flock/chickin/ProjectFlockChickinDetail';
import { useSearchParams } from 'next/navigation';
const AddChickin = () => {
const searchParams = useSearchParams();
const projectFlockId = searchParams.get('projectFlockId');
return (
<>
<section className='w-full'>
<ProjectFlockChickinDetail projectFlockId={Number(projectFlockId)} />
</section>
</>
);
};
export default AddChickin;
@@ -0,0 +1,10 @@
import ChickinTable from '@/components/pages/production/chickin/ChickinTable';
const Chickin = () => {
return (
<section className='w-full'>
<ChickinTable />
</section>
);
};
export default Chickin;
@@ -14,13 +14,13 @@ const ProjectFlockClosingPage = () => {
const projectFlockKandangId = searchParams.get('projectFlockKandangId');
const { data: projectFlockKandang, isLoading: isLoadingProjectFlockKandang } =
useSWR(`get-flock-kandang-id/${projectFlockKandangId}`, () =>
ProjectFlockKandangApi.getSingle(parseInt(projectFlockKandangId ?? ''))
useSWR(projectFlockKandangId, (id: number) =>
ProjectFlockKandangApi.getSingle(id)
);
const { data: projectFlock, isLoading: isLoadingProjectFlock } = useSWR(
`get-flock-id/${projectFlockId}`,
() => ProjectFlockApi.getSingle(parseInt(projectFlockId ?? ''))
projectFlockId,
(id: number) => ProjectFlockApi.getSingle(id)
);
if (!projectFlockId || !projectFlockKandangId) {
@@ -50,3 +50,5 @@ const ProjectFlockDetailPage = () => {
};
export default ProjectFlockDetailPage;
ProjectFlockDetail;
ProjectFlockDetail;
+1 -1
View File
@@ -15,7 +15,7 @@ export default function ProjectFlockLayout({
const router = useRouter();
const toggleValidate = useUiStore((s) => s.toggleValidate);
const isAdd = pathname.includes('/add');
const isAdd = pathname.endsWith('/add');
const isEdit = pathname.includes('/detail/edit');
const isDetail = pathname.includes('/detail');
const isChickin = pathname.includes('/chickin/add/kandang');
@@ -14,7 +14,7 @@ const RecordingEdit = () => {
const { data: recording, isLoading: isLoadingRecording } = useSWR(
recordingId,
(id: string) => RecordingApi.getSingle(parseInt(id))
(id: number) => RecordingApi.getSingle(id) // Gunakan RecordingApi
);
if (!recordingId) {
+1 -1
View File
@@ -14,7 +14,7 @@ const RecordingDetail = () => {
const { data: recording, isLoading: isLoadingRecording } = useSWR(
recordingId,
(id: string) => RecordingApi.getSingle(parseInt(id))
(id: number) => RecordingApi.getSingle(id)
);
if (!recordingId) {
+1 -1
View File
@@ -2,7 +2,7 @@ import RecordingTable from '@/components/pages/production/recording/RecordingTab
const Recording = () => {
return (
<section className='w-full p-4 sm:p-0'>
<section className='w-full p-4'>
<RecordingTable />
</section>
);
@@ -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,63 @@
'use client';
import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';
import TransferToLayingForm from '@/components/pages/production/transfer-to-laying/form/TransferToLayingForm';
import { TransferToLayingApi } from '@/services/api/production/transfer-to-laying';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
const TransferToLayingEdit = () => {
const router = useRouter();
const searchParams = useSearchParams();
const transferToLayingId = searchParams.get('transferToLayingId');
const { data: transferToLaying, isLoading: isLoadingTransferToLaying } =
useSWR(transferToLayingId, (id: number) =>
TransferToLayingApi.getSingle(id)
);
if (!transferToLayingId) {
router.back();
return (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
);
}
if (
!isLoadingTransferToLaying &&
(!transferToLaying || isResponseError(transferToLaying))
) {
router.replace('/404');
return;
}
if (
isResponseSuccess(transferToLaying) &&
transferToLaying.data.approval.step_number === 2
) {
router.replace('/production/transfer-to-laying');
return;
}
return (
<div className='w-full p-4 flex flex-row justify-center'>
{isLoadingTransferToLaying && (
<span className='loading loading-spinner loading-xl' />
)}
{!isLoadingTransferToLaying && isResponseSuccess(transferToLaying) && (
<TransferToLayingForm
type='edit'
initialValues={transferToLaying.data}
/>
)}
</div>
);
};
export default TransferToLayingEdit;
@@ -0,0 +1,56 @@
'use client';
import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';
import TransferToLayingForm from '@/components/pages/production/transfer-to-laying/form/TransferToLayingForm';
import { TransferToLayingApi } from '@/services/api/production/transfer-to-laying';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
const TransferToLayingDetail = () => {
const router = useRouter();
const searchParams = useSearchParams();
const transferToLayingId = searchParams.get('transferToLayingId');
const { data: transferToLaying, isLoading: isLoadingTransferToLaying } =
useSWR(transferToLayingId, (id: number) =>
TransferToLayingApi.getSingle(id)
);
if (!transferToLayingId) {
router.back();
return (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
);
}
if (
!isLoadingTransferToLaying &&
(!transferToLaying || isResponseError(transferToLaying))
) {
router.replace('/404');
return;
}
return (
<div className='w-full p-4 flex flex-row justify-center'>
{isLoadingTransferToLaying && (
<span className='loading loading-spinner loading-xl' />
)}
{!isLoadingTransferToLaying && isResponseSuccess(transferToLaying) && (
<TransferToLayingForm
type='detail'
initialValues={transferToLaying.data}
/>
)}
</div>
);
};
export default TransferToLayingDetail;
+1 -17
View File
@@ -1,25 +1,9 @@
import TransferToLayingsTable from '@/components/pages/production/transfer-to-laying/TransferToLayingsTable';
import TransferToLayingFormModal from '@/components/pages/production/transfer-to-laying/TransferToLayingFormModal';
import TransferToLayingDetailModal from '@/components/pages/production/transfer-to-laying/TransferToLayingDetailModal';
import RequirePermission from '@/components/helper/RequirePermission';
const TransferToLaying = () => {
return (
<section className='w-full'>
<section className='w-full p-4'>
<TransferToLayingsTable />
<RequirePermission
permissions={[
'lti.production.transfer_to_laying.create',
'lti.production.transfer_to_laying.update',
]}
>
<TransferToLayingFormModal />
</RequirePermission>
<RequirePermission permissions='lti.production.transfer_to_laying.detail'>
<TransferToLayingDetailModal />
</RequirePermission>
</section>
);
};
@@ -1,7 +0,0 @@
import UniformityForm from '@/components/pages/production/uniformity/form/UniformityForm';
const AddUniformity = () => {
return <UniformityForm formType='add' />;
};
export default AddUniformity;
@@ -1,49 +0,0 @@
'use client';
import UniformityDetail from '@/components/pages/production/uniformity/detail/UniformityDetail';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { UniformityApi } from '@/services/api/uniformity';
import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';
const UniformityDetailPage = () => {
const router = useRouter();
const searchParams = useSearchParams();
const uniformityId = searchParams.get('uniformityId');
const { data: uniformity, isLoading: isLoadingUniformity } = useSWR(
uniformityId,
(id: string) => UniformityApi.getUniformityDetail(parseInt(id))
);
if (!uniformityId) {
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 (!isLoadingUniformity && (!uniformity || isResponseError(uniformity))) {
router.replace('/404');
return;
}
return (
<div className='w-full h-full flex flex-col justify-center'>
{isLoadingUniformity && (
<div className='w-full flex flex-row justify-center items-center p-4 min-h-screen'>
<span className='loading loading-spinner loading-xl' />
</div>
)}
{isResponseSuccess(uniformity) && (
<UniformityDetail initialValues={uniformity.data} />
)}
</div>
);
};
export default UniformityDetailPage;
-10
View File
@@ -1,10 +0,0 @@
import { ReactNode } from 'react';
import UniformityPageWrapper from '@/components/pages/production/uniformity/UniformityPageWrapper';
export default function UniformityLayout({
children,
}: {
children: ReactNode;
}) {
return <UniformityPageWrapper>{children}</UniformityPageWrapper>;
}
-7
View File
@@ -1,7 +0,0 @@
import UniformityTable from '@/components/pages/production/uniformity/UniformityTable';
const Uniformity = () => {
return <UniformityTable />;
};
export default Uniformity;
+1 -1
View File
@@ -2,7 +2,7 @@ import PurchaseTable from '@/components/pages/purchase/PurchaseTable';
const Purchase = () => {
return (
<section className='w-full p-4 sm:p-0'>
<section className='w-full p-4'>
<PurchaseTable />
</section>
);
-11
View File
@@ -1,11 +0,0 @@
import SuspenseHelper from '@/components/helper/SuspenseHelper';
const Layout = ({
children,
}: Readonly<{
children: React.ReactNode;
}>) => {
return <SuspenseHelper>{children}</SuspenseHelper>;
};
export default Layout;
-5
View File
@@ -1,5 +0,0 @@
const ReportExpenseDetail = () => {
return <div>ReportExpenseDetail</div>;
};
export default ReportExpenseDetail;
-13
View File
@@ -1,13 +0,0 @@
'use client';
import ReportExpenseTable from '@/components/pages/report/expense/ReportExpenseTable';
const ReportExpense = () => {
return (
<div className='w-full p-4'>
<ReportExpenseTable />
</div>
);
};
export default ReportExpense;
-7
View File
@@ -1,7 +0,0 @@
import FinanceTabs from '@/components/pages/report/finance/FinanceTabs';
const Finance = () => {
return <FinanceTabs />;
};
export default Finance;
-11
View File
@@ -1,11 +0,0 @@
import SuspenseHelper from '@/components/helper/SuspenseHelper';
const Layout = ({
children,
}: Readonly<{
children: React.ReactNode;
}>) => {
return <SuspenseHelper>{children}</SuspenseHelper>;
};
export default Layout;
-7
View File
@@ -1,7 +0,0 @@
import LogisticStockTabs from '@/components/pages/report/logistic-stock/LogisticStockTabs';
const LogisticStock = () => {
return <LogisticStockTabs />;
};
export default LogisticStock;
-11
View File
@@ -1,11 +0,0 @@
import SuspenseHelper from '@/components/helper/SuspenseHelper';
const Layout = ({
children,
}: Readonly<{
children: React.ReactNode;
}>) => {
return <SuspenseHelper>{children}</SuspenseHelper>;
};
export default Layout;
-11
View File
@@ -1,11 +0,0 @@
import MarketingReportContent from '@/components/pages/report/MarketingReportContent';
const MarketingReportPage = () => {
return (
<section className='w-full p-4'>
<MarketingReportContent />
</section>
);
};
export default MarketingReportPage;
-11
View File
@@ -1,11 +0,0 @@
import ProductionResultContent from '@/components/pages/report/production-result/ProductionResultContent';
const ProductionResultReportPage = () => {
return (
<section className='w-full max-w-7xl pb-16'>
<ProductionResultContent />
</section>
);
};
export default ProductionResultReportPage;
+14 -34
View File
@@ -3,25 +3,29 @@
import { HTMLAttributes, ReactNode } from 'react';
import { cn } from '@/lib/helper';
import type { Color, Variant, Size } from '@/types/theme';
export interface BadgeProps
extends Omit<HTMLAttributes<HTMLSpanElement>, 'className'> {
children?: ReactNode;
className?: {
badge?: string;
status?: string;
};
statusIndicator?: boolean;
variant?: Variant;
color?: Color;
size?: Size;
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,
statusIndicator = false,
variant = 'default',
color,
size = 'md',
@@ -30,7 +34,7 @@ const Badge = ({
const getBadgeClasses = () => {
const baseClasses = 'badge';
const variantClasses: Record<Variant, string> = {
const variantClasses = {
default: '',
outline: 'badge-outline',
ghost: 'badge-ghost',
@@ -38,7 +42,7 @@ const Badge = ({
dash: 'badge-dash',
};
const colorClasses: Record<Color, string> = {
const colorClasses = {
neutral: 'badge-neutral',
primary: 'badge-primary',
secondary: 'badge-secondary',
@@ -47,10 +51,9 @@ const Badge = ({
success: 'badge-success',
warning: 'badge-warning',
error: 'badge-error',
none: '',
};
const sizeClasses: Record<Size, string> = {
const sizeClasses = {
xs: 'badge-xs',
sm: 'badge-sm',
md: 'badge-md',
@@ -67,31 +70,8 @@ const Badge = ({
);
};
const getStatusClasses = () => {
if (!statusIndicator) return '';
const statusIndicatorClasses: Record<Color, string> = {
neutral: 'bg-neutral',
primary: 'bg-primary',
secondary: 'bg-secondary',
accent: 'bg-accent',
info: 'bg-info',
success: 'bg-success',
warning: 'bg-warning',
error: 'bg-error',
none: '',
};
return cn(
'w-2.5 h-2.5 rounded-full',
color && statusIndicatorClasses[color],
className?.status
);
};
return (
<span className={getBadgeClasses()} {...props}>
{statusIndicator && <span className={getStatusClasses()} />}
{children}
</span>
);
-263
View File
@@ -1,263 +0,0 @@
import React, { useId } from 'react';
import Link from 'next/link';
import { Icon } from '@iconify/react';
import { cn, findMenuPath } from '@/lib/helper';
import { Size } from '@/types/theme';
import Button from '@/components/Button';
import { MAIN_DRAWER_LINKS } from '@/config/constant';
interface BreadcrumbItem {
label: string;
href?: string;
icon?: React.ReactNode;
isActive?: boolean;
isDisabled?: boolean;
}
interface BreadcrumbsProps extends React.HTMLAttributes<HTMLElement> {
items: BreadcrumbItem[];
size?: Size;
maxVisibleItems?: number;
showEllipsisDropdown?: boolean;
}
export function buildBreadcrumbs(pathname: string): BreadcrumbItem[] {
const menuPath = findMenuPath(MAIN_DRAWER_LINKS, pathname);
if (!menuPath) return [];
return menuPath.map((menu, index) => {
const isLast = index === menuPath.length - 1;
return {
label: menu.text,
href: isLast ? menu.link : undefined,
isActive: isLast,
icon: menu.icon ? (
<Icon icon={menu.icon} width={16} height={16} />
) : undefined,
};
});
}
const EllipsisDropdown = ({
hiddenItems,
}: {
hiddenItems: BreadcrumbItem[];
}) => {
const dropdownId = useId();
const anchorId = useId();
return (
<li>
{/* Ellipsis Button */}
<Button
popoverTarget={dropdownId}
variant='ghost'
color='none'
style={
{
anchorName: `--breadcrumb-ellipsis-anchor-${anchorId}`,
} as React.CSSProperties
}
>
<Icon icon='material-symbols:more-horiz' width={16} height={16} />
</Button>
{/* Dropdown Menu using popover API */}
<ul
className='dropdown menu rounded-box bg-base-100 border border-base-300 shadow-lg z-[9999] [&_a:hover]:no-underline [&_a:focus]:no-underline [&&]:no-underline [&&_a]:no-underline [&&]:hover:no-underline [&&]:flex [&&]:items-start [&&]:justify-start w-max'
popover='auto'
id={dropdownId}
style={
{
positionAnchor: `--breadcrumb-ellipsis-anchor-${anchorId}`,
} as React.CSSProperties
}
>
{hiddenItems.map((item, index) => {
const itemStyles = cn(
'[&]:flex [&]:items-center [&]:justify-start py-1 text-sm',
// Disabled state
item.isDisabled && 'text-base-content/40 opacity-50',
// Active/Last state
(item.isActive || item.isDisabled) && 'text-primary',
// Regular clickable state
!item.isDisabled && 'text-base-content/50'
);
const itemContent = (
<div className={itemStyles}>
{item.icon && (
<span className='inline-flex mr-2'>{item.icon}</span>
)}
{item.label}
</div>
);
return (
<li
key={`ellipsis-${index}`}
className='[&&]:text-left [&&]:block w-full'
>
{item.href && !item.isDisabled ? (
<Link
href={item.href}
className='block !no-underline [&&]:text-left w-full'
onClick={(e) => e.stopPropagation()}
>
{itemContent}
</Link>
) : (
<div className='block !no-underline [&&]:cursor-default [&&]:hover:cursor-default [&&]:hover:bg-base-100 [&&]:text-left'>
{itemContent}
</div>
)}
</li>
);
})}
</ul>
</li>
);
};
const Breadcrumb = ({
items,
size = 'md',
maxVisibleItems = 3,
showEllipsisDropdown = true,
className,
...props
}: BreadcrumbsProps) => {
const sizeClasses = {
xs: 'text-xs',
sm: 'text-sm',
md: 'text-base',
lg: 'text-lg',
xl: 'text-xl',
};
const getItemStyles = (
item: BreadcrumbItem,
position: 'first' | 'middle' | 'last' = 'middle'
) => {
const baseClasses = 'inline-flex items-center gap-2';
// Disabled state
if (item.isDisabled) {
return `${baseClasses} text-base-content/40 !cursor-default opacity-50 hover:!no-underline`;
}
// Active/Last state (no underline)
if (item.isActive || position === 'last') {
return `${baseClasses} text-primary !cursor-pointer hover:!no-underline`;
}
// Regular clickable state
return `${baseClasses} text-base-content/60`;
};
const renderItem = (
item: BreadcrumbItem,
position: 'first' | 'middle' | 'last' = 'middle'
) => {
const styles = getItemStyles(item, position);
// Disabled items
if (item.isDisabled) {
return (
<span className={styles}>
{item.icon && item.icon}
{item.label}
</span>
);
}
// Active/Last items
if (item.isActive || position === 'last') {
if (item.href) {
return (
<Link href={item.href} className={styles}>
{item.icon && (
<span className='inline-flex gap-2'>{item.icon}</span>
)}
{item.label}
</Link>
);
}
return (
<span className={styles}>
{item.icon && item.icon}
{item.label}
</span>
);
}
// Regular items
if (item.href) {
return (
<Link href={item.href} className={styles}>
{item.icon && <span className='inline-flex gap-2'>{item.icon}</span>}
{item.label}
</Link>
);
}
return (
<span className={styles}>
{item.icon && item.icon}
{item.label}
</span>
);
};
const renderBreadcrumbList = () => {
// Show all items if within limit
if (items.length <= maxVisibleItems) {
return items.map((item, index) => {
const position =
index === 0
? 'first'
: index === items.length - 1
? 'last'
: 'middle';
return <li key={index}>{renderItem(item, position)}</li>;
});
}
// Collapsed items indexing when exceeding limit
const firstItem = items[0];
const lastItem = items[items.length - 1];
const visibleMiddleItems = items.slice(1, -1).slice(-(maxVisibleItems - 2));
const hiddenItems = items.slice(1, -1).slice(0, -(maxVisibleItems - 2));
const showEllipsis = showEllipsisDropdown && hiddenItems.length > 0;
return (
<>
<li>{renderItem(firstItem, 'first')}</li>
{/* Ellipsis for hidden items with dropdown */}
{showEllipsis && <EllipsisDropdown hiddenItems={hiddenItems} />}
{/* Middle items */}
{visibleMiddleItems.map((item, index) => (
<li key={`middle-${index}`}>{renderItem(item, 'middle')}</li>
))}
<li>{renderItem(lastItem, 'last')}</li>
</>
);
};
return (
<nav
aria-label='Breadcrumb'
className={cn('breadcrumbs', sizeClasses[size], className)}
{...props}
>
<ul className='text-sm'>{renderBreadcrumbList()}</ul>
</nav>
);
};
export default Breadcrumb;
+1 -2
View File
@@ -2,12 +2,11 @@ import react from 'react';
import Link from 'next/link';
import { cn } from '@/lib/helper';
import { Color } from '@/types/theme';
import { UrlObject } from 'url';
export interface ButtonProps extends react.ComponentProps<'button'> {
variant?: 'soft' | 'outline' | 'dash' | 'ghost' | 'link' | 'active';
color?: Color;
href?: string | UrlObject;
href?: string;
isLoading?: boolean;
target?: string;
rel?: string;
+3 -17
View File
@@ -22,7 +22,6 @@ export interface CardProps
onCollapsedChange?: (collapsed: boolean) => void;
className?: {
wrapper?: string;
wrapperContent?: string;
image?: string;
body?: string;
title?: string;
@@ -123,10 +122,6 @@ const Card = ({
return cn(baseClasses, 'p-6', className?.body);
};
const getCollapsibleClasses = () => {
return cn('', className?.collapsible);
};
const getTitleClasses = () => {
const sizeClasses = {
sm: 'text-lg',
@@ -149,19 +144,11 @@ const Card = ({
return cn('border-t border-base-300 mt-4 pt-4', className?.footer);
};
const getWrapperContentClasses = () => {
return cn('space-y-4', className?.wrapperContent);
};
const renderCardContent = () => {
const hasContent = children || actions || footer;
const titleContent = (
<div
className={
`group flex items-center justify-between! w-full` + getTitleClasses()
}
>
<div className='group flex items-center !justify-between w-full'>
<div className='flex-1'>
{title && <h2 className={getTitleClasses()}>{title}</h2>}
{subtitle && <p className={getSubtitleClasses()}>{subtitle}</p>}
@@ -169,7 +156,7 @@ const Card = ({
{collapsible && (
<button
onClick={() => handleCollapsedChange(!isCollapsed)}
className={`btn btn-ghost btn-sm btn-circle` + getTitleClasses()}
className='btn btn-ghost btn-sm btn-circle'
aria-label={isCollapsed ? 'Expand content' : 'Collapse content'}
>
<Icon
@@ -186,7 +173,7 @@ const Card = ({
);
const cardContent = (
<div className={getWrapperContentClasses()}>
<div className='space-y-4'>
{children}
{actions && <div className={getActionsClasses()}>{actions}</div>}
{footer && <div className={getFooterClasses()}>{footer}</div>}
@@ -217,7 +204,6 @@ const Card = ({
titleClassName='w-full cursor-pointer'
contentClassName='p-0'
fullWidth={true}
className={getCollapsibleClasses()}
>
{cardContent}
</Collapse>
+8 -46
View File
@@ -15,7 +15,6 @@ interface DrawerProps {
className?: DrawerClassName;
onBackdropClick?: () => void;
closeOnBackdropClick?: boolean;
expandedContent?: ReactNode;
}
type DrawerClassName = {
@@ -24,7 +23,6 @@ type DrawerClassName = {
drawerSide?: string;
drawerOverlay?: string;
drawerSidebarContent?: string;
drawerExpandedContent?: string;
};
const Drawer = ({
@@ -38,7 +36,6 @@ const Drawer = ({
className,
onBackdropClick,
closeOnBackdropClick = true,
expandedContent,
}: DrawerProps) => {
const getDrawerClassNames = (): DrawerClassName => {
const baseClassNames = {
@@ -49,24 +46,12 @@ const Drawer = ({
drawerSidebarContent: 'min-h-full bg-base-100',
};
const getSidebarWidth = () => {
if (variant === 'sidebar') {
return expandedContent
? 'w-full lg:min-w-[600px] lg:max-w-[600px]'
: 'w-full max-w-[300px] lg:w-[300px]';
}
if (className?.drawerSidebarContent) {
return '';
}
return 'w-full sm:min-w-120 sm:w-fit';
};
if (variant === 'sidebar') {
return {
...baseClassNames,
drawerSidebarContent: cn(
baseClassNames.drawerSidebarContent,
getSidebarWidth()
'w-full max-w-[300px] lg:w-[300px]'
),
};
} else if (variant === 'right') {
@@ -75,11 +60,11 @@ const Drawer = ({
drawer: cn(baseClassNames.drawer, 'drawer-end'),
drawerSide: cn(
baseClassNames.drawerSide,
'border-l border-solid border-gray-200 sm:drawer-side w-screen top-0 right-0 fixed z-21'
'border-l border-solid border-gray-200 drawer-side w-screen top-0 right-0 fixed z-21'
),
drawerSidebarContent: cn(
baseClassNames.drawerSidebarContent,
getSidebarWidth()
'w-full min-w-120 sm:w-fit'
),
};
} else if (variant === 'left') {
@@ -91,7 +76,7 @@ const Drawer = ({
),
drawerSidebarContent: cn(
baseClassNames.drawerSidebarContent,
getSidebarWidth()
'w-full min-w-120 sm:w-fit'
),
};
}
@@ -153,37 +138,14 @@ const Drawer = ({
onClick={closeDrawer}
/>
{/* Sidebar Content - Full height container */}
{/* Sidebar Content */}
<div
className={cn(
'flex h-screen bg-base-100 overflow-hidden',
variant === 'right' && 'flex-row'
varianClassName?.drawerSidebarContent,
className?.drawerContent
)}
>
{/* Primary Sidebar Content */}
<div
className={cn(
varianClassName?.drawerSidebarContent,
className?.drawerSidebarContent,
'overflow-y-auto'
)}
>
{sidebarContent}
</div>
{/* Expanded Drawer (Right side, side-by-side) */}
{expandedContent && (
<div
className={cn(
'border-l border-gray-200 bg-white flex flex-col h-full',
className?.drawerExpandedContent
)}
>
<div className='overflow-y-auto flex-1 h-full'>
{expandedContent}
</div>
</div>
)}
{sidebarContent}
</div>
</div>
</div>
-114
View File
@@ -1,114 +0,0 @@
import React, { ReactNode, useState, useRef } from 'react';
import { cn } from '@/lib/helper';
export interface DropdownProps {
trigger: ReactNode;
children: ReactNode;
className?: {
wrapper?: string;
trigger?: string;
content?: string;
};
align?: 'start' | 'center' | 'end';
direction?: 'top' | 'bottom' | 'left' | 'right';
hover?: boolean;
defaultOpen?: boolean;
open?: boolean;
close?: boolean;
controlled?: boolean;
}
const Dropdown = ({
trigger,
children,
className,
align,
direction,
hover,
defaultOpen = false,
open,
close,
controlled = false,
}: DropdownProps) => {
const [isOpen, setIsOpen] = useState(defaultOpen);
const dropdownRef = useRef<HTMLDivElement>(null);
const toggleDropdown = () => {
if (!controlled) {
const newState = !isOpen;
setIsOpen(newState);
}
};
const getWrapperClasses = () => {
const openState = controlled ? open : isOpen;
return cn(
'dropdown',
{
'dropdown-start': align === 'start',
'dropdown-center': align === 'center',
'dropdown-end': align === 'end',
'dropdown-top': direction === 'top',
'dropdown-bottom': direction === 'bottom',
'dropdown-left': direction === 'left',
'dropdown-right': direction === 'right',
'dropdown-hover': hover,
'dropdown-open': openState && !close,
'dropdown-close': close,
},
className?.wrapper
);
};
const getTriggerClasses = () => {
return cn(className?.trigger);
};
const getContentClasses = () => {
return cn(
'dropdown-content z-[9999] shadow-sm bg-base-100 rounded-box',
className?.content
);
};
if (controlled) {
return (
<div className={getWrapperClasses()}>
{trigger}
{open && !close && (
<div tabIndex={-1} className={getContentClasses()}>
{children}
</div>
)}
</div>
);
}
return (
<div ref={dropdownRef} className={getWrapperClasses()}>
<div
tabIndex={0}
role='button'
className={getTriggerClasses()}
onClick={toggleDropdown}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
toggleDropdown();
}
}}
>
{trigger}
</div>
{!close && (
<div tabIndex={-1} className={getContentClasses()}>
{children}
</div>
)}
</div>
);
};
export default Dropdown;
+26 -56
View File
@@ -5,8 +5,6 @@ import Tooltip from '@/components/Tooltip';
import { cn } from '@/lib/helper';
import { Icon } from '@iconify/react';
import { useAuth } from '@/services/hooks/useAuth';
type FloatingActionsButtonProps = {
actions: {
action: 'DETAIL' | 'EDIT' | 'DELETE';
@@ -15,7 +13,6 @@ type FloatingActionsButtonProps = {
onClick?: () => void;
hidden?: boolean;
disabled?: boolean;
permissions?: string | string[];
}[];
approvals: {
action: 'APPROVED' | 'REJECTED';
@@ -23,7 +20,6 @@ type FloatingActionsButtonProps = {
label?: string;
onClick?: () => void;
disabled?: boolean;
permissions?: string | string[];
}[];
selectedRowIds: number[];
onClose: () => void;
@@ -35,12 +31,9 @@ const FloatingActionsButton = ({
selectedRowIds,
onClose,
}: FloatingActionsButtonProps) => {
const { permissionCheck } = useAuth();
// Jika tidak ada baris yang dipilih, jangan tampilkan FAB
const positionStyles =
selectedRowIds.length > 0
? 'bottom-[5%] opacity-100'
: 'bottom-[-5%] opacity-0';
selectedRowIds.length > 0 ? 'bottom-[10%]' : 'bottom-[-100%]';
// Helper untuk menentukan gaya warna tombol approval
const getApprovalColor = (action: 'APPROVED' | 'REJECTED') => {
@@ -60,7 +53,7 @@ const FloatingActionsButton = ({
// Container utama FAB
<div
className={cn(
`fixed ${positionStyles} inset-x-1/2 -translate-x-1/2 z-50`,
`absolute ${positionStyles} inset-x-1/2 -translate-x-1/2 z-50`,
'mx-auto w-full max-w-sm sm:mx-0 bg-base-300 p-4 rounded-xl shadow-md transition-all duration-300 transform',
'bg-slate-950 backdrop-blur-md'
)}
@@ -76,18 +69,7 @@ const FloatingActionsButton = ({
<div className='flex gap-4 items-center'>
{/* Render Aksi dari props.actions */}
{actions
.filter((action) => {
if (action.hidden) return false;
if (action.permissions) {
if (typeof action.permissions === 'string') {
return permissionCheck(action.permissions);
}
return action.permissions.some((permission) =>
permissionCheck(permission)
);
}
return true;
})
.filter((action) => !action.hidden)
.map((action, index) => {
return (
<Button
@@ -127,41 +109,29 @@ const FloatingActionsButton = ({
{/* === BARIS BAWAH: Approval Buttons (Approve/Reject) === */}
<div className={`grid grid-cols-${approvals.length} gap-3`}>
{approvals
.filter((approval) => {
if (approval.permissions) {
if (typeof approval.permissions === 'string') {
return permissionCheck(approval.permissions);
}
return approval.permissions.some((permission) =>
permissionCheck(permission)
);
}
return true;
})
.map((approval, index) => (
<Button
key={index}
onClick={approval.onClick}
className={cn(
'btn btn-lg w-full',
'bg-white/20 border-white/30',
'text-white/50 font-semibold flex items-center gap-2 rounded-lg transition-all duration-200',
approval.disabled
? 'cursor-not-allowed'
: 'hover:text-white/100 hover:bg-white/40 hover:border-white/50'
)}
disabled={approval.disabled}
>
<Icon
icon={approval.icon}
width={20}
height={20}
className={`text-${getApprovalColor(approval.action)}`}
/>
{approval.label || approval.action}
</Button>
))}
{approvals.map((approval, index) => (
<Button
key={index}
onClick={approval.onClick}
className={cn(
'btn btn-lg w-full',
'bg-white/20 border-white/30',
'text-white/50 font-semibold flex items-center gap-2 rounded-lg transition-all duration-200',
approval.disabled
? 'cursor-not-allowed'
: 'hover:text-white/100 hover:bg-white/40 hover:border-white/50'
)}
disabled={approval.disabled}
>
<Icon
icon={approval.icon}
width={20}
height={20}
className={`text-${getApprovalColor(approval.action)}`}
/>
{approval.label || approval.action}
</Button>
))}
</div>
</div>
</div>
+45 -40
View File
@@ -9,13 +9,10 @@ import Drawer from '@/components/Drawer';
import Navbar from '@/components/Navbar';
import Button from '@/components/Button';
import SidebarMenu from '@/components/molecules/SidebarMenu';
import PermissionNotFound from '@/components/helper/PermissionNotFound';
import { useUiStore } from '@/stores/ui/ui.store';
import { MAIN_DRAWER_LINKS } from '@/config/constant';
import { isPathActive } from '@/lib/helper';
import { ROUTE_PERMISSIONS } from '@/config/route-permission';
import { useAuth } from '@/services/hooks/useAuth';
const MainDrawerContent = () => {
const pathname = usePathname();
@@ -26,34 +23,29 @@ const MainDrawerContent = () => {
};
return (
<div className='w-full flex flex-col'>
<div className='p-3 flex flex-row items-center gap-4 border-b border-base-content/10'>
<div className='flex flex-row items-center gap-2'>
<Image
src='/assets/img/lti-logo.png'
alt='LTI Logo'
width={40}
height={40}
className='w-full max-w-10 h-auto'
/>
<div className='w-full p-4 flex flex-col gap-4'>
<div className='flex flex-row items-center gap-4'>
<Image
src='/assets/img/lti-logo.png'
alt='MBU Logo'
width={256}
height={256}
className='w-full max-w-16 h-auto'
/>
<div className='font-roboto'>
<h1 className='text-sm font-semibold'>LTI ERP</h1>
<p className='text-sm text-black/50'>Lumbung Telur Indonesia</p>
</div>
</div>
<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='p-1 rounded-full'
className='rounded-full'
>
<Icon
icon='material-symbols:close-rounded'
width={16}
height={16}
width={24}
height={24}
/>
</Button>
</div>
@@ -70,41 +62,54 @@ const MainDrawer = ({
}>) => {
const { mainDrawerOpen, setMainDrawerOpen } = useUiStore();
const pathname = usePathname();
const { permissionCheck } = useAuth();
const formattedPathname = pathname.endsWith('/') ? pathname : `${pathname}/`;
const getPageTitle = useCallback(() => {
let title = '';
const isPathnameNotFoundPage = formattedPathname === '/404/';
const activeMenu = MAIN_DRAWER_LINKS.find((item) =>
isPathActive(pathname, item.link)
);
const isPermitted = ROUTE_PERMISSIONS[formattedPathname]?.some((permission) =>
permissionCheck(permission)
);
const traverseMenuTitle = (menu: typeof activeMenu) => {
if (!menu) return;
const hasSubmenu = menu?.submenu && menu?.submenu.length > 0;
if (!title) {
title += menu?.text;
} else {
title += ' - ' + menu?.text;
}
if (!hasSubmenu || !menu.submenu) return;
const activeSubmenu = menu.submenu?.find((item) =>
isPathActive(pathname, item.link)
);
traverseMenuTitle(activeSubmenu);
};
traverseMenuTitle(activeMenu);
return title;
}, [pathname]);
const pageTitle = getPageTitle();
const toggleSidebar = () => {
setMainDrawerOpen(!mainDrawerOpen);
};
if (!isPermitted && !isPathnameNotFoundPage) {
return <PermissionNotFound />;
}
if (isPathnameNotFoundPage) {
return children;
}
return (
<Drawer
open={mainDrawerOpen}
setOpen={setMainDrawerOpen}
openOnLarge
sidebarContent={<MainDrawerContent />}
className={{
drawerSide: 'border-r border-base-content/10',
drawerSidebarContent: 'min-w-[244px] lg:w-[244px]',
}}
>
<main className='w-full h-full flex flex-col'>
<Navbar toggleSidebar={toggleSidebar} />
<Navbar title={pageTitle as string} toggleSidebar={toggleSidebar} />
{children}
</main>
+2 -22
View File
@@ -53,25 +53,15 @@ interface ModalProps {
ref: RefObject<HTMLDialogElement | null>;
children?: ReactNode;
closeOnBackdrop?: boolean;
onBackdropClick?: () => void;
position?: 'top' | 'middle' | 'bottom' | 'start' | 'end';
className?: {
modal?: string;
modalBox?: string;
};
}
const Modal = ({
ref,
children,
closeOnBackdrop,
onBackdropClick,
position = 'middle',
className,
}: ModalProps) => {
const Modal = ({ ref, children, closeOnBackdrop, className }: ModalProps) => {
const handleBackdropClick = (e: React.MouseEvent<HTMLDialogElement>) => {
if (closeOnBackdrop && e.target === ref.current) {
onBackdropClick?.();
ref.current?.close();
}
};
@@ -79,17 +69,7 @@ const Modal = ({
return (
<dialog
ref={ref}
className={cn(
'modal',
{
'modal-top': position === 'top',
'modal-middle': position === 'middle',
'modal-bottom': position === 'bottom',
'modal-start': position === 'start',
'modal-end': position === 'end',
},
className?.modal
)}
className={cn('modal', className?.modal)}
onClick={handleBackdropClick}
>
<div className={cn('modal-box', className?.modalBox)}>{children}</div>
+29 -46
View File
@@ -1,28 +1,26 @@
'use client';
import toast from 'react-hot-toast';
import { usePathname, useRouter } from 'next/navigation';
import { useRouter } from 'next/navigation';
import { Icon } from '@iconify/react';
import Menu from '@/components/menu/Menu';
import MenuItem from '@/components/menu/MenuItem';
import Button from '@/components/Button';
import Breadcrumb, { buildBreadcrumbs } from '@/components/Breadcrumb';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import Dropdown from '@/components/dropdown/Dropdown';
import { useAuth } from '@/services/hooks/useAuth';
import { AuthApi } from '@/services/api/auth';
import { isResponseError } from '@/lib/api-helper';
import { useUiStore } from '@/stores/ui/ui.store';
interface NavbarProps {
title: string;
toggleSidebar?: () => void;
}
const Navbar = ({ toggleSidebar }: NavbarProps) => {
const Navbar = ({ title, toggleSidebar }: NavbarProps) => {
const { setUser } = useAuth();
const router = useRouter();
const pathname = usePathname();
const navbarActions = useUiStore((state) => state.navbarActions);
const logoutClickHandler = async () => {
const logoutRes = await AuthApi.logout();
@@ -37,54 +35,39 @@ const Navbar = ({ toggleSidebar }: NavbarProps) => {
};
return (
<div className='navbar p-3 bg-base-100 border-b border-base-content/10'>
<div className='navbar px-4 bg-base-100 shadow-sm'>
<div className='flex-1'>
<div className='flex flex-row items-center gap-4'>
{toggleSidebar && (
<Button
variant='ghost'
color='none'
onClick={toggleSidebar}
className='block lg:hidden p-[9px] text-base-content/50 border border-base-content/10 rounded-xl shadow-button-soft'
>
<Icon icon='heroicons:bars-3' width={20} height={20} />
<Button onClick={toggleSidebar} className='block lg:hidden'>
<Icon
icon='material-symbols:menu-rounded'
width={24}
height={24}
/>
</Button>
)}
<Breadcrumb items={buildBreadcrumbs(pathname)} />
<span className='font-bold text-xl text-primary'>{title}</span>
</div>
</div>
<div className='flex gap-2 items-center'>
{/* Page-specific actions */}
{navbarActions && <div className='mr-2'>{navbarActions}</div>}
<PopoverButton
tabIndex={0}
variant='ghost'
color='none'
popoverTarget='accountNavbar'
anchorName='--account-navbar'
className='p-[9px] text-base-content/50 border border-base-content/10 rounded-xl shadow-button-soft'
<div className='flex gap-2'>
<Dropdown
position='bottom-end'
trigger={
<div className='btn btn-ghost btn-circle avatar'>
<div className='w-10 rounded-full border flex justify-center items-center'>
<Icon icon='uil:user' width={40} height={40} />
</div>
</div>
}
contentClassName='w-52 mt-3'
>
<Icon icon='heroicons:user' width={20} height={20} />
</PopoverButton>
<PopoverContent
id='accountNavbar'
anchorName='--account-navbar'
position='bottom-start'
className='rounded-xl border border-base-content/5 shadow-sm'
>
<Button
onClick={logoutClickHandler}
variant='ghost'
color='error'
className='p-3 justify-start text-sm font-semibold w-full'
>
<Icon icon='heroicons-outline:logout' width={20} height={20} />
Logout
</Button>
</PopoverContent>
<Menu className='p-2 bg-base-100 shadow rounded-box menu-sm'>
<MenuItem title='Logout' onClick={logoutClickHandler} />
</Menu>
</Dropdown>
</div>
</div>
);
+46 -195
View File
@@ -1,12 +1,11 @@
'use client';
import { Fragment, ReactNode, useCallback, useEffect, useState } from 'react';
import { ReactNode, useCallback, useEffect, useState } from 'react';
import {
flexRender,
getCoreRowModel,
getFilteredRowModel,
getPaginationRowModel,
getExpandedRowModel,
getSortedRowModel,
TableOptions,
useReactTable,
@@ -16,7 +15,6 @@ import {
OnChangeFn,
Row,
HeaderContext,
ExpandedState,
} from '@tanstack/react-table';
import { rankItem } from '@tanstack/match-sorter-utils';
import { Icon } from '@iconify/react';
@@ -33,16 +31,11 @@ interface TableClassNames {
headerColumnClassName?: string;
tableBodyClassName?: string;
bodyRowClassName?: string;
selectedBodyRowClassName?: string;
bodyColumnClassName?: string;
bodySubRowClassName?: (depth: number) => string;
selectedBodySubRowClassName?: (depth: number) => string;
bodySubRowColumnClassName?: (depth: number) => string;
tableFooterClassName?: string;
footerRowClassName?: string;
footerColumnClassName?: string;
paginationClassName?: string;
skeletonCellClassName?: string;
}
export interface TableProps<TData extends object> {
@@ -66,23 +59,10 @@ export interface TableProps<TData extends object> {
enableRowSelection?: boolean | ((row: Row<TData>) => boolean);
renderFooter?: boolean;
withCheckbox?: boolean;
withPagination?: boolean;
rowOptions?: number[];
/**
* Custom row renderer. Should return a complete <tr> element or null.
* This gives full control over the row structure including colspan.
* Return null to render the default row.
*/
renderCustomRow?: (row: Row<TData>) => ReactNode | null;
getRowCanExpand?: (row: Row<TData>) => boolean;
renderSubComponent?: (props: { row: Row<TData> }) => React.ReactElement;
expanded?: ExpandedState;
getSubRows?: (originalRow: TData, index: number) => TData[] | undefined;
}
const DUMMY_SKELETON_DATA = Array.from({ length: 10 }, (_, index) => ({
id: index,
}));
const DUMMY_SKELETON_DATA = [{}, {}, {}, {}, {}];
const emptyContentDefaultValue = (
<div className='w-full p-5 text-center'>
@@ -100,18 +80,11 @@ export const TABLE_DEFAULT_STYLING = {
tableHeaderClassName: '',
headerRowClassName: '',
headerColumnClassName:
'px-4 py-3 border-base-content/10 text-base-content/50 text-sm font-medium',
'px-4 py-3 border-base-content/10 text-base-content/50',
tableBodyClassName: '',
bodyRowClassName:
'transition-all duration-200 border-t border-base-content/10 bg-transparent',
selectedBodyRowClassName: 'bg-primary/5',
bodyColumnClassName: 'px-4 py-3 text-base-content font-medium',
bodySubRowClassName: (depth: number) =>
'transition-all duration-200 border-t border-base-content/10 bg-transparent',
selectedBodySubRowClassName: (depth: number) => 'bg-primary/5',
bodySubRowColumnClassName: (depth: number) =>
'px-4 py-3 text-base-content font-medium',
paginationClassName: 'px-3',
bodyRowClassName: 'border-t border-base-content/10',
bodyColumnClassName: 'px-4 py-3 text-base-content',
paginationClassName: '',
tableFooterClassName: 'font-semibold border-base-content/10',
footerRowClassName: 'bg-base-200 border-t-2 border-base-content/10',
footerColumnClassName: 'p-4 text-base-content whitespace-nowrap',
@@ -138,13 +111,7 @@ const Table = <TData extends object>({
enableRowSelection,
renderFooter = false,
withCheckbox = false,
withPagination = true,
rowOptions = [10, 20, 50, 100],
renderCustomRow,
getRowCanExpand,
renderSubComponent,
expanded = {},
getSubRows,
}: TableProps<TData>) => {
const isServerSideTable =
totalItems !== undefined &&
@@ -177,14 +144,10 @@ const Table = <TData extends object>({
getSortedRowModel: getSortedRowModel(),
getPaginationRowModel: getPaginationRowModel(),
onPaginationChange: setPagination,
getExpandedRowModel: getExpandedRowModel(),
getRowCanExpand: getRowCanExpand ?? (getSubRows ? undefined : () => false),
getSubRows,
manualSorting,
state: {
pagination,
globalFilter: fuzzySearchValue,
expanded,
},
filterFns: {
fuzzy: fuzzyFilter,
@@ -252,40 +215,14 @@ const Table = <TData extends object>({
}, [pageSize, setPageSize]);
return (
<div
className={cn(
TABLE_DEFAULT_STYLING.containerClassName,
tableClassNames.containerClassName,
{
'mb-0': !withPagination,
}
)}
>
<div
className={cn(
TABLE_DEFAULT_STYLING.tableWrapperClassName,
tableClassNames.tableWrapperClassName
)}
>
<table
className={cn(
TABLE_DEFAULT_STYLING.tableClassName,
tableClassNames.tableClassName
)}
>
<thead
className={cn(
TABLE_DEFAULT_STYLING.tableHeaderClassName,
tableClassNames.tableHeaderClassName
)}
>
<div className={tableClassNames.containerClassName}>
<div className={tableClassNames.tableWrapperClassName}>
<table className={tableClassNames.tableClassName}>
<thead className={tableClassNames.tableHeaderClassName}>
{table.getHeaderGroups().map((headerGroup) => (
<tr
key={headerGroup.id}
className={cn(
TABLE_DEFAULT_STYLING.headerRowClassName,
tableClassNames.headerRowClassName
)}
className={tableClassNames.headerRowClassName}
>
{headerGroup.headers.map((header) => {
const columnRelativeDepth =
@@ -318,7 +255,6 @@ const Table = <TData extends object>({
{
'border-b': header.colSpan > 1,
},
TABLE_DEFAULT_STYLING.headerColumnClassName,
tableClassNames.headerColumnClassName
)}
>
@@ -368,110 +304,34 @@ const Table = <TData extends object>({
))}
</thead>
<tbody
className={cn(
TABLE_DEFAULT_STYLING.tableBodyClassName,
tableClassNames.tableBodyClassName
)}
>
{table.getRowModel().rows.map((row) => {
const customRowContent = renderCustomRow?.(row);
if (customRowContent) {
return renderCustomRow?.(row);
}
return (
<Fragment key={row.id}>
<tr
data-depth={row.depth}
<tbody className={tableClassNames.tableBodyClassName}>
{table.getRowModel().rows.map((row) => (
<tr key={row.id} className={tableClassNames.bodyRowClassName}>
{row.getVisibleCells().map((cell) => (
<td
key={cell.id}
className={cn(
row.depth > 0
? tableClassNames.bodySubRowClassName(row.depth)
: tableClassNames.bodyRowClassName,
{
[tableClassNames.selectedBodyRowClassName!]:
row.getIsSelected() && row.depth === 0,
[tableClassNames.selectedBodySubRowClassName(
row.depth
)!]: row.getIsSelected() && row.depth > 0,
}
{ 'first:w-9 first:pr-0': withCheckbox },
tableClassNames.bodyColumnClassName
)}
>
{row.getVisibleCells().map((cell) => (
<td
key={cell.id}
className={cn(
{ 'first:w-9 first:pr-0': withCheckbox },
TABLE_DEFAULT_STYLING.bodyColumnClassName,
row.depth > 0
? tableClassNames.bodySubRowColumnClassName(
row.depth
)
: tableClassNames.bodyColumnClassName
)}
>
{!isLoading &&
flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
{!isLoading &&
flexRender(cell.column.columnDef.cell, cell.getContext())}
{isLoading && (
<div
className={cn(
'skeleton w-full h-4',
tableClassNames.skeletonCellClassName
)}
/>
)}
</td>
))}
</tr>
{row.getIsExpanded() && (
<>
{renderSubComponent && (
<tr
className={cn(
TABLE_DEFAULT_STYLING.bodySubRowClassName(1),
tableClassNames.bodySubRowClassName(1),
{
[tableClassNames.selectedBodySubRowClassName(1)]:
row.getIsSelected(),
}
)}
>
<td colSpan={row.getVisibleCells().length}>
{renderSubComponent({ row })}
</td>
</tr>
)}
</>
)}
</Fragment>
);
})}
{isLoading && <div className='skeleton w-full h-4' />}
</td>
))}
</tr>
))}
</tbody>
<tfoot
className={cn(
TABLE_DEFAULT_STYLING.tableFooterClassName,
tableClassNames.tableFooterClassName
)}
>
<tfoot className={cn(tableClassNames.tableFooterClassName)}>
{renderFooter && (
<tr
className={cn(
TABLE_DEFAULT_STYLING.footerRowClassName,
tableClassNames.footerRowClassName
)}
>
<tr className={cn(tableClassNames.footerRowClassName)}>
{table.getAllLeafColumns().map((column) => (
<td
key={column.id}
className={cn(
{ 'first:w-9 first:pr-0': withCheckbox },
TABLE_DEFAULT_STYLING.footerColumnClassName,
tableClassNames.footerColumnClassName
)}
>
@@ -493,33 +353,24 @@ const Table = <TData extends object>({
!isLoading &&
emptyContent}
{data.length > 0 &&
table.getRowModel().rows.length > 0 &&
!isLoading &&
withPagination && (
<div
className={cn(
'mt-5',
TABLE_DEFAULT_STYLING.paginationClassName,
tableClassNames.paginationClassName
)}
>
<Pagination
totalItems={isServerSideTable ? totalItems : table.getRowCount()}
itemsPerPage={table.getState().pagination.pageSize}
currentPage={
isServerSideTable
? page
: table.getState().pagination.pageIndex + 1
}
onPrevPage={prevPageClickHandler}
onNextPage={nextPageClickHandler}
onPageChange={pageChangeHandler}
rowOptions={rowOptions}
onRowChange={onPageSizeChange}
/>
</div>
)}
{data.length > 0 && table.getRowModel().rows.length > 0 && !isLoading && (
<div className={cn('mt-5', tableClassNames.paginationClassName)}>
<Pagination
totalItems={isServerSideTable ? totalItems : table.getRowCount()}
itemsPerPage={table.getState().pagination.pageSize}
currentPage={
isServerSideTable
? page
: table.getState().pagination.pageIndex + 1
}
onPrevPage={prevPageClickHandler}
onNextPage={nextPageClickHandler}
onPageChange={pageChangeHandler}
rowOptions={rowOptions}
onRowChange={onPageSizeChange}
/>
</div>
)}
</div>
);
};
+18 -36
View File
@@ -21,14 +21,11 @@ export interface TabsProps
className?:
| string
| {
container?: string;
wrapper?: string;
tab?: string;
content?: string;
tabHeaderWrapper?: string;
};
onTabChange?: (tabId: string) => void;
sideContent?: ReactNode;
}
const Tabs = ({
@@ -40,7 +37,6 @@ const Tabs = ({
activeTabId: controlledActiveId,
className,
onTabChange,
sideContent,
...props
}: TabsProps) => {
// State internal hanya dipakai kalau `activeTabId` (controlled) tidak diset
@@ -57,15 +53,10 @@ const Tabs = ({
onTabChange?.(tabId);
};
const {
container: containerClassName,
wrapper: wrapperClassName,
tab: tabClassName,
content: contentClassName,
tabHeaderWrapper: tabHeaderWrapperClassName,
} = typeof className === 'object'
? className
: { wrapper: className, tab: undefined };
const { wrapper: wrapperClassName, tab: tabClassName } =
typeof className === 'object'
? className
: { wrapper: className, tab: undefined };
const getTabsClasses = () => {
const variantClasses: Record<string, string> = {
@@ -106,10 +97,6 @@ const Tabs = ({
tabClassName
);
const getSideContentClasses = () => {
return cn('flex flex-row', tabHeaderWrapperClassName);
};
const activeContent = tabs.find((tab) => tab.id === activeTabId)?.content;
return (
@@ -117,29 +104,24 @@ const Tabs = ({
{...props}
className={cn(
'w-full',
typeof className === 'string' ? className : containerClassName
typeof className === 'string' ? className : undefined
)}
>
<div className={getSideContentClasses()}>
<div role='tablist' className={getTabsClasses()}>
{tabs.map(({ id, label, disabled }) => (
<button
key={id}
role='tab'
className={getTabClasses(id === activeTabId, disabled)}
onClick={() => !disabled && handleTabChange(id)}
disabled={disabled}
>
{label}
</button>
))}
</div>
{sideContent && sideContent}
<div role='tablist' className={getTabsClasses()}>
{tabs.map(({ id, label, disabled }) => (
<button
key={id}
role='tab'
className={getTabClasses(id === activeTabId, disabled)}
onClick={() => !disabled && handleTabChange(id)}
disabled={disabled}
>
{label}
</button>
))}
</div>
{activeContent && (
<div className={cn('mt-4', contentClassName)}>{activeContent}</div>
)}
{activeContent && <div className='mt-4'>{activeContent}</div>}
</div>
);
};
+84 -82
View File
@@ -1,109 +1,111 @@
import React, { ReactNode, useState, useRef } from 'react';
'use client';
import { ReactNode, useRef, useEffect, useState } from 'react';
import { cn } from '@/lib/helper';
export interface DropdownProps {
interface DropdownProps {
trigger: ReactNode;
children: ReactNode;
className?: {
wrapper?: string;
trigger?: string;
content?: string;
};
position?:
| 'top'
| 'bottom'
| 'left'
| 'right'
| 'top-start'
| 'top-end'
| 'bottom-start'
| 'bottom-end'
| 'left-start'
| 'left-end'
| 'right-start'
| 'right-end';
align?: 'start' | 'center' | 'end';
direction?: 'top' | 'bottom' | 'left' | 'right';
hover?: boolean;
defaultOpen?: boolean;
open?: boolean;
close?: boolean;
controlled?: boolean;
className?: string;
contentClassName?: string;
}
const Dropdown = ({
trigger,
children,
position = 'bottom',
align = 'start',
hover = false,
className,
align,
direction,
hover,
defaultOpen = false,
open,
close,
controlled = false,
contentClassName,
}: DropdownProps) => {
const [isOpen, setIsOpen] = useState(defaultOpen);
const [isOpen, setIsOpen] = useState(false);
const dropdownRef = useRef<HTMLDivElement>(null);
const toggleDropdown = () => {
if (!controlled) {
const newState = !isOpen;
setIsOpen(newState);
// Handle click outside to close dropdown
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (
dropdownRef.current &&
!dropdownRef.current.contains(event.target as Node)
) {
setIsOpen(false);
}
};
if (isOpen) {
document.addEventListener('mousedown', handleClickOutside);
}
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [isOpen]);
// Build position classes
const getPositionClasses = () => {
const classes: string[] = [];
// Handle combined positions like 'top-start'
if (position.includes('-')) {
const [pos, al] = position.split('-');
classes.push(`dropdown-${pos}`);
classes.push(`dropdown-${al}`);
} else {
classes.push(`dropdown-${position}`);
if (align !== 'start') {
classes.push(`dropdown-${align}`);
}
}
return classes.join(' ');
};
const getWrapperClasses = () => {
const openState = controlled ? open : isOpen;
return cn(
'dropdown',
{
'dropdown-start': align === 'start',
'dropdown-center': align === 'center',
'dropdown-end': align === 'end',
'dropdown-top': direction === 'top',
'dropdown-bottom': direction === 'bottom',
'dropdown-left': direction === 'left',
'dropdown-right': direction === 'right',
'dropdown-hover': hover,
'dropdown-open': openState && !close,
'dropdown-close': close,
},
className?.wrapper
);
const handleToggle = (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
// alert('clicked');
setIsOpen(!isOpen);
};
const getTriggerClasses = () => {
return cn(className?.trigger);
};
const getContentClasses = () => {
return cn(
'dropdown-content z-[9999] shadow-sm bg-base-100 rounded-box',
className?.content
);
};
if (controlled) {
return (
<div className={getWrapperClasses()}>
{trigger}
{open && !close && (
<div tabIndex={-1} className={getContentClasses()}>
{children}
</div>
)}
</div>
);
}
return (
<div ref={dropdownRef} className={getWrapperClasses()}>
<div
tabIndex={0}
role='button'
className={getTriggerClasses()}
onClick={toggleDropdown}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
toggleDropdown();
}
}}
>
<div
ref={dropdownRef}
className={cn(
'dropdown',
getPositionClasses(),
hover && 'dropdown-hover',
isOpen && 'dropdown-open',
className
)}
>
{/* Trigger Button */}
<div onClick={handleToggle} className='cursor-pointer'>
{trigger}
</div>
{!close && (
<div tabIndex={-1} className={getContentClasses()}>
{/* Dropdown Content - Only render when open */}
{isOpen && (
<div
tabIndex={-1}
className={cn('dropdown-content z-[10]', contentClassName)}
onClick={() => setIsOpen(false)} // Close on item click
>
{children}
</div>
)}
-203
View File
@@ -1,203 +0,0 @@
'use client';
import { useEffect, useMemo, useState } from 'react';
import { Icon } from '@iconify/react';
import { BaseApproval } from '@/types/api/api-general';
import Button from '@/components/Button';
import { cn, formatDate } from '@/lib/helper';
interface ApprovalStepsV2Props {
approvals?: BaseApproval[];
steps: {
step_number: number;
step_name: string;
}[];
maxVisibleSteps?: number;
className?: {
wrapper?: string;
stepsWrapper?: string;
stepsContainer?: string;
};
}
const ApprovalStepsV2 = ({
approvals,
steps,
maxVisibleSteps = 2,
className,
}: ApprovalStepsV2Props) => {
const [isSeeAll, setIsSeeAll] = useState(false);
const [formattedApprovals, setFormattedApprovals] = useState<
(BaseApproval & { isActive: boolean })[]
>([]);
const latestApprovalStepNumber =
approvals?.[approvals.length - 1].step_number ?? 0;
const lastStepNumber = steps[steps.length - 1].step_number;
const isLatestApprovalStepNumberLessThanLastStepNumber =
latestApprovalStepNumber < lastStepNumber;
const slicedFormattedApprovals = useMemo(() => {
return formattedApprovals.slice(0, isSeeAll ? undefined : maxVisibleSteps);
}, [formattedApprovals, isSeeAll]);
const seeMoreClickHandler = () => {
setIsSeeAll((prevVal) => !prevVal);
};
useEffect(() => {
if (approvals) {
const tempFormattedApprovals: (BaseApproval & { isActive: boolean })[] =
[];
approvals.forEach((approval) => {
tempFormattedApprovals.push({
...approval,
isActive: true,
});
});
if (isLatestApprovalStepNumberLessThanLastStepNumber) {
const latestApprovalStepNumberIndexInSteps = steps.findIndex(
(step) => step.step_number === latestApprovalStepNumber
);
const slicedSteps = steps.slice(
latestApprovalStepNumberIndexInSteps + 1
);
slicedSteps.forEach((step) => {
tempFormattedApprovals.push({
action: 'APPROVED',
action_at: new Date().toISOString(),
action_by: {
id: 0,
id_user: 0,
email: '',
name: '',
},
step_name: step.step_name,
step_number: step.step_number,
isActive: false,
});
});
}
setFormattedApprovals(tempFormattedApprovals);
}
}, [approvals]);
return (
<div
className={cn(
'w-full p-4 flex flex-col border-b border-base-content/10',
className?.wrapper
)}
>
<h4 className='text-base font-medium text-base-content/50 font-roboto'>
Progress Details
</h4>
<div
className={cn(
'mt-6 mb-8 flex flex-col gap-10',
className?.stepsWrapper
)}
>
{slicedFormattedApprovals.map((approval, idx) => {
const isApprovalActionCreated = approval.action === 'CREATED';
const isApprovalActionUpdated = approval.action === 'UPDATED';
const isApprovalActionRejected = approval.action === 'REJECTED';
const isApprovalActionApproved = approval.action === 'APPROVED';
const approvalIcon =
isApprovalActionCreated || isApprovalActionUpdated
? 'heroicons:clock-solid'
: isApprovalActionRejected
? 'heroicons:x-circle-solid'
: isApprovalActionApproved
? 'heroicons:check-badge-solid'
: 'heroicons:check-badge-solid';
return (
<div key={idx} className='w-full flex flex-row items-stretch gap-3'>
<div className='w-fit self-stretch relative'>
<div className='w-fit h-fit flex flex-col items-start'>
<Icon
icon={approvalIcon}
width={24}
height={24}
className={cn({
'text-warning':
isApprovalActionCreated || isApprovalActionUpdated,
'text-error': isApprovalActionRejected,
'text-success': isApprovalActionApproved,
'text-base-content/20': !approval.isActive,
})}
/>
{idx < formattedApprovals.length - 1 && (
<div className='absolute top-6 left-1/2 -translate-x-1/2 w-0 min-h-full h-[calc(100%)] mx-auto my-2 border border-dashed border-base-content/10' />
)}
</div>
</div>
<div
className={cn('w-full flex flex-col gap-1 text-base-content', {
'text-base-content/20': !approval.isActive,
})}
>
<div className='flex flex-col'>
<span className='text-xs'>{approval.step_name}</span>
<span className='text-sm font-semibold'>
{(isApprovalActionCreated || isApprovalActionUpdated) &&
'Diajukan oleh '}
{isApprovalActionRejected && 'Ditolak oleh '}
{isApprovalActionApproved && 'Disetujui oleh '}
{approval.isActive ? approval.action_by.name : '...'}
</span>
</div>
{approval.isActive && (
<p className='w-full max-w-60 p-3 bg-base-content/5 rounded-xl text-xs text-base-content/50'>
Created at :{' '}
{formatDate(approval.action_at, 'DD-MM-YYYY, HH:mm')}
<br />
Notes : {approval.notes ?? '-'}
</p>
)}
</div>
</div>
);
})}
</div>
{formattedApprovals.length > maxVisibleSteps && (
<Button
variant='outline'
color='none'
onClick={seeMoreClickHandler}
className={cn(
'px-3 py-2 gap-2.5 text-sm text-base-content/50 border border-base-content/10 rounded-lg transition-all'
)}
>
<Icon
icon='heroicons-outline:chevron-double-down'
width={20}
height={20}
className={cn('transition-all duration-300', {
'-rotate-180': isSeeAll,
})}
/>
See {isSeeAll ? 'Less' : 'More'}
</Button>
)}
</div>
);
};
export default ApprovalStepsV2;
-48
View File
@@ -1,48 +0,0 @@
import Button, { ButtonProps } from '@/components/Button';
import { getFilledFormikValuesCount } from '@/lib/formik-helper';
import { cn } from '@/lib/helper';
import { Icon } from '@iconify/react';
import { FormikValues } from 'formik';
export type ButtonFilterProps = ButtonProps & {
values: FormikValues;
onClick: () => void;
};
// 'bg-gradient-to-t from-blue-50 to-blue-100 border-blue-500 text-blue-600 hover:from-blue-100 hover:to-blue-200
const ButtonFilter = ({ values, onClick, ...props }: ButtonFilterProps) => {
return (
<Button
{...props}
onClick={onClick}
variant='outline'
color='none'
className={cn(
'rounded-lg max-h-10 font-semibold text-sm gap-1.5',
'text-sm text-base-content/50 border border-base-content/10 shadow-button-soft',
getFilledFormikValuesCount(values) > 0
? 'border-primary-gradient text-primary rounded-lg!'
: 'rounded-lg',
props.className
)}
>
<Icon
icon='heroicons:funnel'
width={20}
height={20}
className={
getFilledFormikValuesCount(values) > 0 ? 'text-blue-600' : ''
}
/>
Filter
{getFilledFormikValuesCount(values) > 0 && (
<span className='w-5 h-5 text-white bg-[#FF3535] rounded-lg border border-base-300 flex items-center justify-center text-xs'>
{getFilledFormikValuesCount(values)}
</span>
)}
</Button>
);
};
export default ButtonFilter;
-17
View File
@@ -1,17 +0,0 @@
import Button from '@/components/Button';
const PageNotFound = () => {
return (
<div className='w-full h-full flex-1 flex flex-col justify-center items-center gap-4'>
<h2 className='text-2xl font-bold text-error'>Halaman Tidak Ditemukan</h2>
<p className='text-gray-600 text-center'>
Halaman atau data yang anda cari tidak ditemukan.
</p>
<Button href='/dashboard' className='text-base-100'>
Kembali ke Dashboard
</Button>
</div>
);
};
export default PageNotFound;
@@ -1,19 +0,0 @@
import Button from '@/components/Button';
const PermissionNotFound = () => {
return (
<div className='w-full h-screen flex flex-col justify-center items-center gap-4'>
<h2 className='text-2xl font-bold text-error'>
Hak Akses Tidak Ditemukan
</h2>
<p className='text-gray-600 text-center'>
Anda tidak memiliki hak akses untuk mengakses halaman ini.
</p>
<Button href='/dashboard' className='text-base-100'>
Kembali ke Dashboard
</Button>
</div>
);
};
export default PermissionNotFound;
+5 -27
View File
@@ -5,7 +5,6 @@ import useSWR from 'swr';
import { useAuth } from '@/services/hooks/useAuth';
import { httpClientFetcher, SWRHttpKey } from '@/services/http/client';
import { AuthApi } from '@/services/api/auth';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { BaseApiResponse, GetMeResponse } from '@/types/api/api-general';
import { AxiosError } from 'axios';
@@ -28,9 +27,6 @@ const RequireAuth = ({ children }: RequireAuthProps) => {
SWRHttpKey
>('/sso/userinfo', httpClientFetcher, {
shouldRetryOnError: false,
// refresh every 12 minutes
refreshInterval: 12 * 60 * 1000,
});
useEffect(() => {
@@ -56,27 +52,6 @@ const RequireAuth = ({ children }: RequireAuthProps) => {
setIsLoadingUser(isLoadingUserResponse);
}, [isLoadingUserResponse]);
useEffect(() => {
const interval = setInterval(
async () => {
await AuthApi.refresh();
},
12 * 60 * 1000
);
return () => clearInterval(interval);
}, []);
useEffect(() => {
const refreshUserSession = async () => {
await AuthApi.refresh();
};
if (user) {
refreshUserSession();
}
}, [user]);
if (
(isLoadingUserResponse && !userResponse && !userErrorResponse) ||
(!userResponse && !userErrorResponse)
@@ -88,7 +63,7 @@ const RequireAuth = ({ children }: RequireAuthProps) => {
);
}
if (!isLoadingUserResponse && userErrorResponse) {
if (userErrorResponse) {
return (
<div className='w-full h-screen flex flex-col justify-center items-center gap-4'>
<h2 className='text-2xl font-bold text-error'>Authentication Failed</h2>
@@ -96,7 +71,10 @@ const RequireAuth = ({ children }: RequireAuthProps) => {
Please try refreshing the page or contact support if the problem
persists.
</p>
<button className='btn btn-primary' onClick={() => redirectToSSO()}>
<button
className='btn btn-primary'
onClick={() => window.location.reload()}
>
Retry
</button>
</div>
@@ -1,28 +0,0 @@
'use client';
import { useAuth } from '@/services/hooks/useAuth';
interface RequirePermissionProps {
children: React.ReactNode;
permissions: string | string[];
}
const RequirePermission = ({
children,
permissions,
}: RequirePermissionProps) => {
const { permissionCheck } = useAuth();
const isPermitted =
typeof permissions === 'string'
? permissionCheck(permissions)
: permissions.some((permission) => permissionCheck(permission));
if (!isPermitted) {
return null;
}
return <>{children}</>;
};
export default RequirePermission;
-60
View File
@@ -1,60 +0,0 @@
import Badge from '@/components/Badge';
import { cn } from '@/lib/helper';
import { Color } from '@/types/theme';
interface StatusBadgeProps {
color: Color;
text: string;
className?: {
badge?: string;
status?: string;
};
}
const StatusBadge = ({
color = 'neutral',
text,
className,
}: StatusBadgeProps) => {
return (
<Badge
variant='soft'
className={{
badge: cn(
'px-2 py-1 w-full flex flex-row justify-start gap-1 rounded-lg border border-base-content/10 text-xs font-medium text-base-content',
{
'bg-base-content/5': color === 'neutral',
'bg-success/30': color === 'success',
'bg-error/20': color === 'error',
'bg-primary/20': color === 'info',
'bg-[#FF9A20]/12': color === 'warning',
'bg-[#1166EF]/12': color === 'primary',
},
className?.badge
),
status: cn(className?.status),
}}
color={color}
>
<svg
height='12'
width='12'
xmlns='http://www.w3.org/2000/svg'
className={cn({
'text-base-content/10': color === 'neutral',
'text-[#008000]': color === 'success',
'text-error': color === 'error',
'text-primary': color === 'info',
'text-[#FF9A20]': color === 'warning',
'text-[#1166EF]': color === 'primary',
})}
>
<circle r='6' cx='6' cy='6' fill='currentColor' />
</svg>
{text}
</Badge>
);
};
export default StatusBadge;
@@ -58,7 +58,6 @@ const DrawerHeader = ({
if (leftIconOnClick) {
return (
<button
type='button'
onClick={leftIconOnClick}
className='hover:text-gray-400 bg-transparent border-none p-0'
>
@@ -73,12 +72,12 @@ const DrawerHeader = ({
return (
<div
className={cn(
'flex flex-row justify-between items-center px-4 pt-4 pb-4 border-b border-base-content/10',
'flex flex-row justify-between items-center px-4 pt-4',
className
)}
>
{/* Left Side */}
<div className='flex flex-row h-full gap-3 items-center'>
<div className='flex flex-row h-full gap-2 items-center'>
{renderLeftIcon()}
{showDivider && subtitle && (
@@ -86,12 +85,7 @@ const DrawerHeader = ({
)}
{subtitle && (
<div
className={cn(
'text-sm font-medium text-base-content/50',
subtitleClassName
)}
>
<div className={cn('text-sm text-neutral', subtitleClassName)}>
{subtitle}
</div>
)}
-84
View File
@@ -1,84 +0,0 @@
import Alert from '@/components/Alert';
import Button from '@/components/Button';
import { cn } from '@/lib/helper';
import { Icon } from '@iconify/react';
import { useState } from 'react';
/**
* Alert Unique Error List
* @param formErrorList - Array of error messages
* @param onClose - Function to close the alert
*/
const AlertErrorList = ({
formErrorList,
className,
onClose,
title,
}: {
formErrorList: string[];
className?: {
alert?: string;
button?: string;
headerWrapper?: string;
headerIcon?: string;
headerText?: string;
titleWrapper?: string;
ul?: string;
li?: string;
};
onClose: () => void;
title?: string;
}) => {
if (formErrorList.length === 0) return null;
return (
<Alert
color='error'
className={cn(
'w-full flex flex-col gap-2 px-3 rounded-lg',
className?.alert
)}
>
<div
className={cn(
'flex justify-between items-center gap-2 w-full',
className?.headerWrapper
)}
>
<div className={cn('flex items-center gap-2', className?.titleWrapper)}>
<Icon
icon='material-symbols:error-outline'
className={cn(className?.headerIcon)}
width={20}
height={20}
/>
<span className={cn('font-semibold text-sm', className?.headerText)}>
{title || `Terdapat ${formErrorList.length} error pada form:`}
</span>
</div>
<Button
onClick={onClose}
variant='link'
className={cn('ml-auto p-0 w-fit text-white', className?.button)}
color='none'
>
<Icon icon='material-symbols:close' width={20} height={20} />
</Button>
</div>
<ul
className={cn(
'list-disc list-inside pl-4 space-y-1.5 w-full',
className?.ul
)}
>
{formErrorList.map((error, index) => (
<li key={index} className={cn('text-sm', className?.li)}>
{error}
</li>
))}
</ul>
</Alert>
);
};
export default AlertErrorList;
@@ -1,45 +0,0 @@
'use client';
import { View, StyleSheet } from '@react-pdf/renderer';
import { PdfThead, PdfColumn } from './PdfThead';
import { PdfTbody, PdfTbodyCell } from './PdfTbody';
import { PdfTfoot, PdfTfootCell } from './PdfTfoot';
const styles = StyleSheet.create({
table: {
borderWidth: 1,
borderColor: '#000000',
marginBottom: 15,
},
});
interface PdfTableProps {
columns: PdfColumn[];
data: PdfTbodyCell[][];
footer?: PdfTfootCell[];
footerLabel?: string;
firstRow?: {
valueKey: string;
value: number;
align?: 'right';
color?: string;
};
}
export const PdfTable = ({
columns,
data,
footer,
footerLabel = 'Total',
firstRow,
}: PdfTableProps) => {
return (
<View style={styles.table}>
<PdfThead columns={columns} />
<PdfTbody columns={columns} rows={data} firstRow={firstRow} />
{footer && footer.length > 0 && (
<PdfTfoot columns={columns} cells={footer} label={footerLabel} />
)}
</View>
);
};
@@ -1,219 +0,0 @@
'use client';
import { Text, View, StyleSheet } from '@react-pdf/renderer';
export interface PdfColumn {
key: string;
header: string;
flex: number;
align?: 'left' | 'center' | 'right';
}
export interface PdfTbodyCell {
key: string;
value: string | number | React.ReactNode;
align?: 'left' | 'center' | 'right';
color?: string;
formatAs?: 'text' | 'date' | 'currency' | 'number';
formatDate?: string;
}
const styles = StyleSheet.create({
tableRow: {
flexDirection: 'row',
},
tableBorderBottom: {
borderBottomWidth: 1,
borderBottomColor: '#000000',
borderBottomStyle: 'solid',
},
tableCell: {
flex: 1,
borderRightWidth: 1,
borderRightColor: '#000000',
borderRightStyle: 'solid',
padding: 4,
fontSize: 7,
textAlign: 'left',
},
tableCellLast: {
flex: 1,
padding: 4,
fontSize: 7,
borderRightWidth: 0,
},
tableCellRight: {
flex: 1,
borderRightWidth: 1,
borderRightColor: '#000000',
borderRightStyle: 'solid',
padding: 4,
fontSize: 7,
textAlign: 'right',
},
tableCellCenter: {
flex: 1,
borderRightWidth: 1,
borderRightColor: '#000000',
borderRightStyle: 'solid',
padding: 4,
fontSize: 7,
textAlign: 'center',
},
tableCellNo: {
flex: 0.5,
borderRightWidth: 1,
borderRightColor: '#000000',
borderRightStyle: 'solid',
padding: 4,
fontSize: 7,
textAlign: 'center',
},
});
interface PdfTbodyProps {
columns: PdfColumn[];
rows: PdfTbodyCell[][];
firstRow?: {
valueKey: string;
value: number;
align?: 'right';
color?: string;
};
formatDate?: (date: string, format: string) => string;
formatNumber?: (num: number) => string;
formatCurrency?: (num: number) => string;
}
export const PdfTbody = ({ columns, rows, firstRow }: PdfTbodyProps) => {
return (
<>
{/* First Row */}
{firstRow && (
<View style={[styles.tableRow, styles.tableBorderBottom]}>
{columns.map((column, index) => {
const isLastColumn = index === columns.length - 1;
const isfirstRowColumn = column.key === firstRow.valueKey;
const align = column.align || 'center';
const cellStyle =
column.key === 'no'
? [styles.tableCellNo, { flex: column.flex }]
: isfirstRowColumn
? [
styles.tableCellRight,
{
flex: column.flex,
color: firstRow.color || 'black',
borderRightWidth: isLastColumn ? 0 : 1,
},
]
: align === 'right'
? [
styles.tableCellRight,
{
flex: column.flex,
borderRightWidth: isLastColumn ? 0 : 1,
},
]
: align === 'center'
? [
styles.tableCellCenter,
{
flex: column.flex,
borderRightWidth: isLastColumn ? 0 : 1,
},
]
: isLastColumn
? [
styles.tableCellLast,
{
flex: column.flex,
borderRightWidth: 0,
},
]
: [styles.tableCell, { flex: column.flex }];
return (
<View key={column.key} style={cellStyle}>
<Text>{isfirstRowColumn ? firstRow.value : ''}</Text>
</View>
);
})}
</View>
)}
{/* Data Rows */}
{rows.map((row, rowIndex) => {
const isLastRow = rowIndex === rows.length - 1;
return (
<View
key={rowIndex}
style={[
styles.tableRow,
!isLastRow ? styles.tableBorderBottom : {},
]}
>
{columns.map((column, colIndex) => {
const cell = row.find((c) => c.key === column.key);
const isLastColumn = colIndex === columns.length - 1;
const align = cell?.align || column.align || 'center';
const cellStyle =
column.key === 'no'
? [styles.tableCellNo, { flex: column.flex }]
: align === 'right'
? [
styles.tableCellRight,
{
flex: column.flex,
color: cell?.color || 'black',
borderRightWidth: isLastColumn ? 0 : 1,
},
]
: align === 'center'
? [
styles.tableCellCenter,
{
flex: column.flex,
color: cell?.color || 'black',
borderRightWidth: isLastColumn ? 0 : 1,
},
]
: isLastColumn
? [
styles.tableCellLast,
{ flex: column.flex, borderRightWidth: 0 },
]
: [
styles.tableCell,
{
flex: column.flex,
color: cell?.color || 'black',
borderRightWidth: isLastColumn ? 0 : 1,
},
];
return (
<View key={column.key} style={cellStyle}>
{cell?.value !== undefined &&
cell?.value !== null &&
cell?.value !== '' ? (
typeof cell.value === 'object' ? (
cell.value
) : (
<Text>{String(cell.value)}</Text>
)
) : (
<Text>-</Text>
)}
</View>
);
})}
</View>
);
})}
</>
);
};
@@ -1,131 +0,0 @@
'use client';
import { Text, View, StyleSheet } from '@react-pdf/renderer';
export interface PdfColumn {
key: string;
header: string;
flex: number;
align?: 'left' | 'center' | 'right';
}
export interface PdfTfootCell {
key: string;
value: string | number;
align?: 'left' | 'center' | 'right';
flex?: number;
color?: string;
}
const styles = StyleSheet.create({
tableRow: {
flexDirection: 'row',
},
summaryRow: {
backgroundColor: '#F0F0F0',
fontWeight: 'bold',
},
tableCell: {
flex: 1,
borderRightWidth: 1,
borderRightColor: '#000000',
borderRightStyle: 'solid',
padding: 4,
fontSize: 7,
textAlign: 'left',
},
tableCellLast: {
flex: 1,
padding: 4,
fontSize: 7,
borderRightWidth: 0,
},
tableCellRight: {
flex: 1,
borderRightWidth: 1,
borderRightColor: '#000000',
borderRightStyle: 'solid',
padding: 4,
fontSize: 7,
textAlign: 'right',
},
tableCellCenter: {
flex: 1,
borderRightWidth: 1,
borderRightColor: '#000000',
borderRightStyle: 'solid',
padding: 4,
fontSize: 7,
textAlign: 'center',
},
tableCellNo: {
flex: 0.5,
borderRightWidth: 1,
borderRightColor: '#000000',
borderRightStyle: 'solid',
padding: 4,
fontSize: 7,
textAlign: 'center',
},
});
interface PdfTfootProps {
columns: PdfColumn[];
cells: PdfTfootCell[];
label?: string;
}
export const PdfTfoot = ({
columns,
cells,
label = 'Total',
}: PdfTfootProps) => {
return (
<View style={[styles.tableRow, styles.summaryRow]}>
{columns.map((column, index) => {
const isLastColumn = index === columns.length - 1;
const cellData = cells.find((c) => c.key === column.key);
const cellStyle =
column.key === 'no'
? [
styles.tableCellNo,
{ flex: column.flex, borderRightWidth: isLastColumn ? 0 : 1 },
]
: cellData?.align === 'right'
? [
styles.tableCellRight,
{
flex: column.flex,
color: cellData?.color || 'black',
borderRightWidth: isLastColumn ? 0 : 1,
},
]
: cellData?.align === 'center'
? [
styles.tableCellCenter,
{
flex: column.flex,
color: cellData?.color || 'black',
borderRightWidth: isLastColumn ? 0 : 1,
},
]
: isLastColumn
? [styles.tableCellLast, { flex: column.flex }]
: [
styles.tableCell,
{
flex: column.flex,
color: cellData?.color || 'black',
},
];
return (
<View key={column.key} style={cellStyle}>
<Text>{column.key === 'no' ? label : cellData?.value || ''}</Text>
</View>
);
})}
</View>
);
};
@@ -1,89 +0,0 @@
'use client';
import { Text, View, StyleSheet } from '@react-pdf/renderer';
export interface PdfColumn {
key: string;
header: string;
flex: number;
align?: 'left' | 'center' | 'right';
}
const styles = StyleSheet.create({
tableRow: {
flexDirection: 'row',
},
tableHeader: {
backgroundColor: '#F5F5F5',
},
tableCellHeader: {
flex: 1,
borderRightWidth: 1,
borderRightColor: '#000000',
borderRightStyle: 'solid',
padding: 4,
fontSize: 7,
fontWeight: 'bold',
backgroundColor: '#F5F5F5',
borderBottomWidth: 1,
borderBottomColor: '#000000',
borderBottomStyle: 'solid',
paddingVertical: 12,
textAlign: 'center',
},
tableCellHeaderRight: {
flex: 1,
borderRightWidth: 1,
borderRightColor: '#000000',
borderRightStyle: 'solid',
padding: 4,
fontSize: 7,
fontWeight: 'bold',
backgroundColor: '#F5F5F5',
textAlign: 'right',
borderBottomWidth: 1,
borderBottomColor: '#000000',
borderBottomStyle: 'solid',
paddingVertical: 12,
},
});
interface PdfTheadProps {
columns: PdfColumn[];
}
export const PdfThead = ({ columns }: PdfTheadProps) => {
return (
<View style={[styles.tableRow, styles.tableHeader]}>
{columns.map((column, index) => {
const align = column.align || 'center';
const isLastColumn = index === columns.length - 1;
const cellStyle =
align === 'right'
? [
styles.tableCellHeaderRight,
{
flex: column.flex,
textAlign: 'right' as const,
borderRightWidth: isLastColumn ? 0 : 1,
},
]
: [
styles.tableCellHeader,
{
flex: column.flex,
textAlign: align as 'left' | 'center' | 'right',
borderRightWidth: isLastColumn ? 0 : 1,
},
];
return (
<View key={column.key} style={cellStyle}>
<Text>{column.header}</Text>
</View>
);
})}
</View>
);
};
-7
View File
@@ -1,7 +0,0 @@
export { PdfTable } from './PdfTable';
export { PdfThead } from './PdfThead';
export { PdfTbody } from './PdfTbody';
export { PdfTfoot } from './PdfTfoot';
export type { PdfColumn } from './PdfThead';
export type { PdfTbodyCell } from './PdfTbody';
export type { PdfTfootCell } from './PdfTfoot';
@@ -1,32 +0,0 @@
import IconSkeleton from '@/components/helper/skeleton/IconSkeleton';
import { Icon } from '@iconify/react';
const DataStateSkeleton = ({
icon,
title,
description,
}: {
icon: React.ReactNode;
title: string;
description: string;
}) => {
return (
<div className='flex flex-col items-center justify-center'>
<IconSkeleton
className={{
outer: 'mb-2.25',
}}
>
{icon}
</IconSkeleton>
<h3 className='text-base-content/50 font-semibold text-sm mb-1'>
{title}
</h3>
<p className='text-base-content/50 text-xs text-center max-w-xs'>
{description}
</p>
</div>
);
};
export default DataStateSkeleton;
@@ -1,33 +0,0 @@
import { cn } from '@/lib/helper';
import { ReactNode } from 'react';
const IconSkeleton = ({
children,
className,
}: {
children: ReactNode;
className?: {
outer?: string;
inner?: string;
};
}) => {
return (
<div
className={cn(
'w-12.5 h-12.5 bg-[var(--main-color-base-100,#FFFFFF)] border border-base-content/10 rounded-[0.875rem] shadow-[0px_25px_50px_-12px_#00000040] flex items-center justify-center',
className?.outer
)}
>
<div
className={cn(
'w-9.5 h-9.5 bg-primary rounded-lg border border-primary flex items-center justify-center shadow-[inset_0px_4px_4px_0px_#FFFFFF80,inset_0px_2px_0px_0px_#FFFFFF80]',
className?.inner
)}
>
{children}
</div>
</div>
);
};
export default IconSkeleton;
+24 -51
View File
@@ -113,15 +113,7 @@ const DateInput = ({
};
const handleSelectSingle = (selectedDate?: Date) => {
if (!selectedDate) {
setSelected(undefined);
setDisplayValue('');
const syntheticEvent = {
target: { name, value: '' },
} as unknown as React.ChangeEvent<HTMLInputElement>;
onChange?.(syntheticEvent);
return;
}
if (!selectedDate) return;
if (minDate && selectedDate < minDate) {
setInternalError(`Tanggal tidak boleh sebelum ${min}`);
return;
@@ -144,15 +136,7 @@ const DateInput = ({
};
const handleSelectRange = (range?: { from?: Date; to?: Date }) => {
if (!range) {
setSelectedRange({});
setDisplayValue('');
const syntheticEvent = {
target: { name, value: { from: '', to: '' } },
} as unknown as React.ChangeEvent<HTMLInputElement>;
onChange?.(syntheticEvent);
return;
}
if (!range) return;
setSelectedRange(range);
const fromStr = range.from ? formatDate(range.from, 'DD/MM/YYYY') : '';
@@ -204,12 +188,17 @@ const DateInput = ({
const finalErrorMessage = internalError || externalErrorMessage;
return (
<div className={cn('w-full flex flex-col text-start', className?.wrapper)}>
<div
className={cn(
'w-full flex flex-col gap-2 text-start',
className?.wrapper
)}
>
{label && (
<label
htmlFor={name}
className={cn(
'w-full py-2 text-xs font-semibold leading-5',
'w-full text-sm font-normal leading-5',
{ 'text-error': finalIsError },
className?.label
)}
@@ -226,7 +215,7 @@ const DateInput = ({
<div
className={cn(
'input h-fit bg-inherit px-3 py-2.5 text-base font-normal leading-6 w-full rounded-lg transition-all duration-200 flex items-center border border-base-content/10',
'input h-12 bg-inherit px-4 py-2 text-base font-normal leading-6 w-full rounded transition-all duration-200 flex items-center border',
{
'border-error': finalIsError,
'border-success': externalValid && !finalIsError,
@@ -245,10 +234,7 @@ const DateInput = ({
disabled={disabled}
readOnly // ✅ tidak bisa diketik manual
className={cn(
'grow bg-transparent cursor-pointer focus:outline-none text-sm leading-tight',
{
'cursor-not-allowed': readOnly,
},
'grow bg-transparent cursor-pointer focus:outline-none',
className?.input
)}
/>
@@ -259,10 +245,10 @@ const DateInput = ({
</div>
)}
<Icon
icon='heroicons:calendar-date-range'
width={15}
height={15}
className='cursor-pointer text-base-content/20'
icon='uil:calendar'
width={24}
height={24}
className='cursor-pointer text-dark'
onClick={(e) =>
handleClick(e as unknown as React.MouseEvent<HTMLInputElement>)
}
@@ -270,17 +256,17 @@ const DateInput = ({
</div>
{!finalIsError && bottomLabel && (
<p className='w-full mt-1.5 text-xs opacity-60'>{bottomLabel}</p>
<p className='w-full text-sm opacity-60'>{bottomLabel}</p>
)}
{finalIsError && finalErrorMessage && (
<p className='w-full mt-1.5 text-xs text-error'>{finalErrorMessage}</p>
<p className='w-full text-sm text-error'>{finalErrorMessage}</p>
)}
<Modal
ref={calendarModal.ref}
className={{
modal: 'rounded',
modalBox: `max-w-max flex flex-col`,
modalBox: `!max-w-max min-h-${isRange ? '124' : '110'} flex flex-col`,
}}
closeOnBackdrop
>
@@ -296,11 +282,7 @@ const DateInput = ({
endMonth={maxDate ?? new Date(new Date().getFullYear() + 5, 11)}
selected={selectedRange as DateRange}
onSelect={handleSelectRange}
footer={
<div className='text-center py-2 text-base-content/65 font-semibold text-xs'>
{displayValue}
</div>
}
footer={<div className='text-center mt-3'>{displayValue}</div>}
disabled={
[
minDate ? { before: minDate } : undefined,
@@ -330,26 +312,17 @@ const DateInput = ({
)}
<div className='mt-auto flex flex-col gap-2'>
{isRange && (
<small className='text-base-content/65'>
Tekan dua kali untuk reset tanggal awal
<small className='text-secondary'>
Tekan dua kali untuk memilih tanggal awal
</small>
)}
<div className='flex h-full justify-end items-end gap-1.5 mt-3'>
<Button
type='button'
color='none'
className='bg-transparent hover:bg-base-content/10 border-none text-base text-base-content/65 px-3'
onClick={handleResetDate}
>
<div className='flex h-full justify-end items-end gap-2'>
<Button type='button' color='warning' onClick={handleResetDate}>
Reset
</Button>
{isRange && (
<Button
type='button'
className='rounded-lg px-3 py-2 text-white'
onClick={handleSaveDate}
>
<Button type='button' onClick={handleSaveDate}>
Simpan
</Button>
)}
@@ -7,7 +7,6 @@ import TextArea, { TextAreaProps } from '@/components/input/TextArea';
interface DebouncedTextAreaProps extends TextAreaProps {
delay?: number;
ref?: React.RefObject<HTMLTextAreaElement | null>;
}
const DebouncedTextArea = (props: DebouncedTextAreaProps) => {
@@ -20,11 +19,6 @@ const DebouncedTextArea = (props: DebouncedTextAreaProps) => {
const [debouncedChangeEvent] = useDebounce(internalChangeEvent, delay ?? 300);
const [debouncedValue] = useDebounce(internalValue, delay ?? 300);
// Sync internal value with external props.value when it changes (e.g., form reset)
useEffect(() => {
setInternalValue(props.value);
}, [props.value]);
const internalChangeHandler: ChangeEventHandler<HTMLTextAreaElement> = (
e
) => {
@@ -41,7 +35,6 @@ const DebouncedTextArea = (props: DebouncedTextAreaProps) => {
return (
<TextArea
{...props}
ref={props.ref}
value={internalValue}
onChange={internalChangeHandler}
/>
@@ -24,11 +24,6 @@ const DebouncedTextInput = (props: DebouncedTextInputProps) => {
setInternalChangeEvent(e);
};
// Sync internal value with external value prop changes (e.g., from reset)
useEffect(() => {
setInternalValue(props.value);
}, [props.value]);
useEffect(() => {
if (debouncedChangeEvent) {
onChange?.(debouncedChangeEvent);
+7 -19
View File
@@ -33,7 +33,6 @@ const FileInput = ({
isError,
errorMessage,
disabled = false,
required = false,
onChange,
onBlur,
readOnly = false,
@@ -41,7 +40,7 @@ const FileInput = ({
return (
<div
className={cn(
'w-full flex flex-col gap-0 text-start rounded-lg',
'w-full flex flex-col gap-2 text-start',
className?.wrapper
)}
>
@@ -49,7 +48,7 @@ const FileInput = ({
<label
htmlFor={name}
className={cn(
'w-full py-2 text-xs font-semibold leading-5',
'w-full text-sm font-normal leading-5',
{
'text-error': isError,
},
@@ -57,13 +56,6 @@ const FileInput = ({
)}
>
{label}
{required && (
<>
<span className='tooltip tooltip-error' data-tip='required'>
<span className='text-error'> *</span>
</span>
</>
)}
</label>
)}
@@ -77,19 +69,15 @@ const FileInput = ({
onChange={onChange}
onBlur={onBlur}
disabled={disabled}
className={cn(
'grow file-input w-full h-fit px-3 py-1.5 text-sm font-normal leading-6 rounded-lg! outline-none! transition-all duration-200 bg-white border-base-content/10',
className?.input
)}
className={cn('grow file-input w-full h-12 rounded', className?.input)}
readOnly={readOnly}
/>
{!isError && bottomLabel && (
<p className='w-full mt-1.5 text-xs opacity-60'>{bottomLabel}</p>
)}
{isError && errorMessage && (
<p className='w-full mt-1.5 text-xs text-error'>{errorMessage}</p>
{bottomLabel && (
<p className='w-full text-sm opacity-60'>{bottomLabel}</p>
)}
{isError && <p className='w-full text-sm text-error'>{errorMessage}</p>}
</div>
);
};
+111 -395
View File
@@ -9,20 +9,15 @@ import Select, {
SingleValue,
components as ReactSelectComponents,
ControlProps,
MenuListProps,
} from 'react-select';
import CreatableSelect from 'react-select/creatable';
import makeAnimated from 'react-select/animated';
import { useDebounce } from 'use-debounce';
import { cn, getByPath } from '@/lib/helper';
import useSWRInfinite from 'swr/infinite';
import useSWR from 'swr';
import { httpClientFetcher } from '@/services/http/client';
import {
BaseApiResponse,
ErrorApiResponse,
SuccessApiResponse,
} from '@/types/api/api-general';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { BaseApiResponse } from '@/types/api/api-general';
import { isResponseSuccess } from '@/lib/api-helper';
export interface OptionType {
value: string | number;
@@ -40,9 +35,7 @@ interface SelectInputBaseProps<T = OptionType> {
bottomLabel?: ReactNode;
options: T[];
optionComponent?: OptionComponent<T>;
components?: Partial<typeof ReactSelectComponents>;
isDisabled?: boolean;
readOnly?: boolean;
isLoading?: boolean;
isClearable?: boolean;
isRtl?: boolean;
@@ -54,9 +47,6 @@ interface SelectInputBaseProps<T = OptionType> {
wrapper?: string;
label?: string;
select?: string;
inputPrefix?: string;
inputSuffix?: string;
inputPrefixSuffixWrapper?: string;
};
isError?: boolean;
errorMessage?: string;
@@ -65,16 +55,10 @@ interface SelectInputBaseProps<T = OptionType> {
delay?: number;
onInputChange?: (search: string) => void;
startAdornment?: ReactNode;
inputPrefix?: ReactNode;
inputSuffix?: ReactNode;
menuPortalTarget?: HTMLElement | null;
closeMenuOnSelect?: boolean;
hideSelectedOptions?: boolean;
onMenuScrollToBottom?: ((event: WheelEvent | TouchEvent) => void) | undefined;
}
export interface SelectInputProps<T = OptionType>
extends SelectInputBaseProps<T> {
interface SelectInputProps<T = OptionType> extends SelectInputBaseProps<T> {
createables?: boolean;
value?: T | T[] | null;
onChange?: (val: T | T[] | null) => void;
@@ -89,7 +73,7 @@ const CustomControl = <
>(
props: ControlProps<Option, IsMulti, Group>
) => {
const { children, innerProps } = props;
const { children } = props;
const customProps = props.selectProps as unknown as {
shouldShowAdornment?: boolean;
@@ -101,7 +85,7 @@ const CustomControl = <
return (
<ReactSelectComponents.Control {...props}>
<div className='flex-1 pl-3 gap-1 flex items-center' {...innerProps}>
<div className='flex-1 px-4! py-1.5 gap-1 flex items-center'>
{shouldShowAdornment && startAdornment}
{children}
</div>
@@ -109,29 +93,6 @@ const CustomControl = <
);
};
const CustomMenuList = <
Option,
IsMulti extends boolean,
Group extends GroupBase<Option>,
>(
props: MenuListProps<Option, IsMulti, Group>
) => {
const { children, selectProps, options } = props;
const { isLoading } = selectProps;
return (
<ReactSelectComponents.MenuList {...props}>
{children}
{options.length > 0 && isLoading && (
<div className='px-3 py-2 rounded-md text-center text-gray-400'>
<span className='loading loading-spinner loading-md' />
</div>
)}
</ReactSelectComponents.MenuList>
);
};
const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
const {
label,
@@ -140,7 +101,6 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
onChange,
options,
optionComponent,
components: customComponents,
isDisabled,
isLoading,
isClearable,
@@ -158,13 +118,7 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
createables = false,
onInputChange,
startAdornment,
inputPrefix,
inputSuffix,
menuPortalTarget,
closeMenuOnSelect,
hideSelectedOptions,
onMenuScrollToBottom,
readOnly,
} = props;
const [internalInputValue, setInternalInputValue] = useState('');
@@ -174,18 +128,14 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
const components = useMemo(() => {
const base = isAnimated ? animatedComponents : {};
const mergedComponents = { ...base, IndicatorSeparator: () => null };
const customComponents = { ...base, IndicatorSeparator: () => null };
if (startAdornment) {
mergedComponents.Control = CustomControl;
customComponents.Control = CustomControl;
}
if (customComponents) {
Object.assign(mergedComponents, customComponents);
}
return mergedComponents;
}, [isAnimated, startAdornment, customComponents]);
return customComponents;
}, [isAnimated, startAdornment]);
const internalInputChangeHandler = (val: string, meta: InputActionMeta) => {
if (meta.action === 'input-change') setInternalInputValue(val);
@@ -213,11 +163,16 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
};
return (
<div className={cn('w-full flex flex-col text-start', className?.wrapper)}>
<div
className={cn(
'w-full flex flex-col gap-2 text-start',
className?.wrapper
)}
>
{label && (
<span
className={cn(
'w-full py-2 text-xs font-semibold leading-5',
'w-full text-sm font-normal leading-5',
{ 'text-error': isError },
className?.label
)}
@@ -234,264 +189,87 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
</span>
)}
{inputPrefix || inputSuffix ? (
<div
className={cn(
'relative flex text-sm',
className?.inputPrefixSuffixWrapper
)}
>
{inputPrefix && (
<div
className={cn(
'inline-flex items-center px-3 border border-r-0 border-base-content/10 rounded-l-lg transition-all duration-200',
{
'bg-gray-100 border-base-content/10': !isDisabled,
'bg-gray-50 border-base-content/10': isDisabled,
'border-error': isError,
},
className?.inputPrefix
)}
>
{inputPrefix}
</div>
)}
<SelectComponent<T, boolean, GroupBase<T>>
instanceId='select'
value={value ?? (isMulti ? [] : null)}
onChange={onChange ? handleChange : undefined}
options={options}
menuIsOpen={openMenu}
inputValue={internalInputValue}
onInputChange={internalInputChangeHandler}
onMenuClose={() => setInternalInputValue('')}
isMulti={isMulti}
isDisabled={isDisabled || readOnly}
isLoading={isLoading}
isClearable={isClearable}
isRtl={isRtl}
isSearchable={isSearchable}
placeholder={placeholder}
closeMenuOnSelect={closeMenuOnSelect}
hideSelectedOptions={hideSelectedOptions}
className={cn('w-full flex-1', className?.select)}
classNames={{
control: ({ isFocused, isDisabled }) =>
cn('w-full border bg-white transition-shadow', 'rounded-lg!', {
'cursor-pointer!': !readOnly && !isDisabled,
'border-red-500! ring-2 ring-red-200': isError,
'border-indigo-500 ring-2 ring-indigo-200':
isFocused && !startAdornment,
'border-base-content/10!': !isError && !isFocused,
'bg-gray-100 text-gray-400 cursor-not-allowed':
isDisabled && !readOnly,
'bg-transparent! cursor-not-allowed!': readOnly,
'rounded-l-none!': inputPrefix && !startAdornment,
'rounded-r-none!': inputSuffix && !startAdornment,
}),
valueContainer: () => cn('flex-1 px-3! pr-2! py-2.5! gap-1'),
placeholder: () =>
cn({
'text-gray-400 text-sm leading-tight': !isError,
'text-red-300!': isError,
}),
singleValue: () =>
cn({
'm-0! text-gray-900 text-sm leading-tight': !isError,
'text-error!': isError,
'text-gray-900!': readOnly,
}),
input: () => cn('text-gray-900 m-0! p-0! text-sm leading-tight'),
indicatorsContainer: () =>
cn('flex items-center gap-1 pr-3 py-2'),
dropdownIndicator: ({ isFocused }) =>
cn('p-0! rounded hover:bg-gray-100', {
'text-gray-900': isFocused,
'text-gray-500': !isFocused,
'text-error!': isError,
}),
clearIndicator: () => cn('p-0! rounded hover:bg-gray-100'),
menu: () =>
cn(
'border border-base-content/5 rounded-xl! bg-base-100 shadow-lg! my-1.5!'
),
menuList: () => cn('p-0! max-h-60 overflow-auto'),
option: ({ isFocused, isSelected }) =>
cn('px-3 py-2 rounded-md cursor-pointer!', {
'bg-indigo-600 text-white': isFocused,
'bg-blue-500!': isSelected,
'text-gray-700': !isFocused && !isSelected,
}),
multiValue: ({ getValue, index }) => {
const selectedValues = getValue() as T[];
return cn(
'bg-base-200! rounded-lg! py-[3px] px-2.5 m-0! flex items-center gap-1! w-fit gap-2!',
selectedValues[index]?.className
);
},
multiValueRemove: () => cn('p-0! w-3 h-3'),
multiValueLabel: ({ getValue, index }) => {
const selectedValues = getValue() as T[];
return cn(
'p-0! text-base-content! text-xs!',
selectedValues[index]?.labelClassName
);
},
}}
components={{
...components,
...(optionComponent ? { Option: optionComponent } : {}),
MenuList: CustomMenuList,
}}
{...(startAdornment && {
shouldShowAdornment,
startAdornment,
})}
menuPortalTarget={
typeof document !== 'undefined'
? (menuPortalTarget ?? document.body)
: undefined
}
styles={{
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
multiValue(base) {
return {
...base,
borderRadius: '8px',
};
},
}}
onMenuScrollToBottom={onMenuScrollToBottom}
/>
{inputSuffix && (
<div
className={cn(
'inline-flex items-center px-3 border border-l-0 border-base-content/10 rounded-r-lg transition-all duration-200',
{
'bg-gray-100 border-base-content/10': !isDisabled,
'bg-gray-50 border-base-content/10': isDisabled,
'border-error': isError,
},
className?.inputSuffix
)}
>
{inputSuffix}
</div>
)}
</div>
) : (
<SelectComponent<T, boolean, GroupBase<T>>
instanceId='select'
value={value ?? (isMulti ? [] : null)}
onChange={onChange ? handleChange : undefined}
options={options}
menuIsOpen={openMenu}
inputValue={internalInputValue}
onInputChange={internalInputChangeHandler}
onMenuClose={() => setInternalInputValue('')}
isMulti={isMulti}
isDisabled={isDisabled || readOnly}
isLoading={isLoading}
isClearable={isClearable}
isRtl={isRtl}
isSearchable={isSearchable}
placeholder={placeholder}
closeMenuOnSelect={closeMenuOnSelect}
hideSelectedOptions={hideSelectedOptions}
className={cn('w-full', className?.select)}
classNames={{
<SelectComponent<T, boolean, GroupBase<T>>
instanceId='select'
value={value ?? (isMulti ? [] : null)}
onChange={onChange ? handleChange : undefined}
options={options}
menuIsOpen={openMenu}
inputValue={internalInputValue}
onInputChange={internalInputChangeHandler}
onMenuClose={() => setInternalInputValue('')}
isMulti={isMulti}
isDisabled={isDisabled}
isLoading={isLoading}
isClearable={isClearable}
isRtl={isRtl}
isSearchable={isSearchable}
placeholder={placeholder}
className={cn('w-full', className?.select)}
classNames={{
...(!startAdornment && {
control: ({ isFocused, isDisabled }) =>
cn(
'w-full border bg-white transition-shadow',
// Gunakan rounded-lg untuk semua kasus
'rounded-lg!',
'w-full min-h-12! rounded border bg-white transition-shadow cursor-pointer!',
{
'cursor-pointer!': !readOnly && !isDisabled,
'border-red-500! ring-2 ring-red-200': isError,
'border-indigo-500 ring-2 ring-indigo-200':
isFocused && !startAdornment,
'border-base-content/10!': !isError && !isFocused,
'bg-gray-100 text-gray-400 cursor-not-allowed':
isDisabled && !readOnly,
'bg-transparent! cursor-not-allowed!': readOnly,
'border-indigo-500 ring-2 ring-indigo-200': isFocused,
'border-gray-300': !isError && !isFocused,
'bg-gray-100 text-gray-400 cursor-not-allowed': isDisabled,
}
),
valueContainer: () => cn('flex-1 px-3! pr-2! py-2.5! gap-1'),
placeholder: () =>
cn({
'text-gray-400 text-sm leading-tight': !isError,
'text-red-300!': isError,
}),
singleValue: () =>
cn({
'm-0! text-gray-900 text-sm leading-tight': !isError,
'text-error!': isError,
'text-gray-900!': readOnly,
}),
input: () => cn('text-gray-900 m-0! p-0! text-sm leading-tight'),
indicatorsContainer: () => cn('flex items-center gap-1 pr-3 py-2'),
dropdownIndicator: ({ isFocused }) =>
cn('p-0! rounded hover:bg-gray-100', {
'text-gray-900': isFocused,
'text-gray-500': !isFocused,
'text-error!': isError,
}),
clearIndicator: () => cn('p-0! rounded hover:bg-gray-100'),
menu: () =>
cn(
'border border-base-content/5 rounded-xl! bg-base-100 shadow-lg! my-1.5!'
),
menuList: () => cn('p-0! max-h-60 overflow-auto'),
option: ({ isFocused, isSelected }) =>
cn('px-3 py-2 rounded-md cursor-pointer!', {
'bg-indigo-600 text-white': isFocused,
'bg-blue-500!': isSelected,
'text-gray-700': !isFocused && !isSelected,
}),
multiValue: ({ getValue, index }) => {
const selectedValues = getValue() as T[];
return cn(
'bg-base-200! rounded-lg! py-[3px] px-2.5 m-0! flex items-center gap-1! w-fit gap-2!',
selectedValues[index]?.className
);
},
multiValueRemove: () => cn('p-0! w-3 h-3'),
multiValueLabel: ({ getValue, index }) => {
const selectedValues = getValue() as T[];
return cn(
'p-0! text-base-content! text-xs!',
selectedValues[index]?.labelClassName
);
},
}}
components={{
...components,
...(optionComponent ? { Option: optionComponent } : {}),
MenuList: CustomMenuList,
}}
{...(startAdornment && {
shouldShowAdornment,
startAdornment,
})}
menuPortalTarget={
typeof document !== 'undefined'
? (menuPortalTarget ?? document.body)
: undefined
}
styles={{
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
multiValue(base) {
return {
...base,
borderRadius: '8px',
};
},
}}
onMenuScrollToBottom={onMenuScrollToBottom}
/>
)}
valueContainer: () => cn('flex-1 px-4! py-2! gap-1'),
}),
placeholder: () =>
cn({ 'text-gray-400': !isError, 'text-red-300!': isError }),
singleValue: () =>
cn({ 'text-gray-900': !isError, 'text-error!': isError }),
input: () => cn('text-gray-900'),
indicatorsContainer: () => cn('flex items-center gap-1 pr-2'),
dropdownIndicator: ({ isFocused }) =>
cn('p-1 rounded hover:bg-gray-100', {
'text-gray-900': isFocused,
'text-gray-500': !isFocused,
'text-error!': isError,
}),
menu: () =>
cn('border border-gray-200 rounded! bg-base-100 shadow-lg!'),
menuList: () => cn('p-2! max-h-60 overflow-auto'),
option: ({ isFocused, isSelected }) =>
cn('mt-1 px-3 py-2 rounded-md cursor-pointer!', {
'bg-indigo-600 text-white': isFocused,
'bg-blue-500!': isSelected,
'text-gray-700': !isFocused && !isSelected,
}),
multiValue: ({ getValue, index }) => {
const selectedValues = getValue() as T[];
return cn(
'bg-indigo-50 rounded py-0.5 pl-2 pr-1 flex items-center gap-1!',
selectedValues[index]?.className
);
},
multiValueLabel: ({ getValue, index }) => {
const selectedValues = getValue() as T[];
return cn('text-indigo-700', selectedValues[index]?.labelClassName);
},
}}
components={{
...components,
...(optionComponent ? { Option: optionComponent } : {}),
}}
{...(startAdornment && {
shouldShowAdornment,
startAdornment,
})}
menuPortalTarget={
typeof document !== 'undefined'
? (menuPortalTarget ?? document.body)
: undefined
}
styles={{
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
}}
/>
{isError && <p className='w-full text-sm text-error'>{errorMessage}</p>}
{!isError && bottomLabel && (
@@ -502,7 +280,7 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
};
const useSelect = <T,>(
basePath: string | null,
basePath: string,
valueKey: keyof T | string,
labelKey: keyof T | string,
searchKey: string = 'search',
@@ -510,96 +288,34 @@ const useSelect = <T,>(
) => {
const [inputValue, setInputValue] = useState('');
const pageKey = 'page';
const limitKey = 'limit';
const limit = params?.['limit'] ?? 10;
const getKey = (
pageIndex: number,
previousPageData?: BaseApiResponse<T[]>
) => {
// stop when backend says no more pages
if (previousPageData && isResponseSuccess(previousPageData)) {
const meta = previousPageData.meta;
if (meta && meta.page >= meta.total_pages) return null;
}
const qs = new URLSearchParams({
...(params ?? {}),
const optionsUrlParams = useMemo(() => {
return new URLSearchParams({
[searchKey]: inputValue ?? '',
[pageKey]: String(pageIndex + 1),
[limitKey]: String(limit),
...params,
}).toString();
}, [inputValue, searchKey, params]);
return basePath ? `${basePath}?${qs}` : null;
};
const optionsUrl = `${basePath}?${optionsUrlParams}`;
const {
data: pages,
isLoading,
isValidating,
size,
setSize,
} = useSWRInfinite<BaseApiResponse<T[]>>(getKey, (url) =>
httpClientFetcher<BaseApiResponse<T[]>>(url)
);
const { data, isLoading } = useSWR(optionsUrl, async (url) => {
return await httpClientFetcher<BaseApiResponse<T[]>>(url);
});
const options = useMemo(() => {
if (!pages) return [];
return pages.flatMap((page) =>
isResponseSuccess(page)
? page.data.map((item) => ({
value: getByPath<T, number>(item, valueKey as string),
label: getByPath<T, string>(item, labelKey as string),
}))
: []
);
}, [pages, valueKey, labelKey]);
const lastPage = pages?.[pages.length - 1];
const hasMore =
!!lastPage &&
isResponseSuccess(lastPage) &&
!!lastPage.meta &&
lastPage.meta.page < lastPage.meta.total_pages;
const loadMore = () => {
if (!hasMore) return;
setSize(size + 1);
};
let formattedSuccessRawData: SuccessApiResponse<T[]> | undefined = undefined;
let formattedErrorRawData: ErrorApiResponse | undefined = undefined;
const latestPagesIndex = pages?.length ? pages.length - 1 : 0;
if (isResponseSuccess(pages?.[latestPagesIndex])) {
formattedSuccessRawData = {
...pages?.[latestPagesIndex],
data:
pages?.flatMap((page) => (isResponseSuccess(page) ? page.data : [])) ??
[],
};
}
if (isResponseError(pages?.[latestPagesIndex])) {
formattedErrorRawData = pages?.[latestPagesIndex];
}
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,
rawData: isResponseSuccess(pages?.[latestPagesIndex])
? formattedSuccessRawData
: formattedErrorRawData,
isLoadingOptions: isLoading || isValidating,
isLoadingMore: isValidating && size > 1,
hasMore,
loadMore,
isLoadingOptions: isLoading,
rawData: data,
};
};

Some files were not shown because too many files have changed in this diff Show More