Merge branch 'staging' into 'production'

Staging

See merge request mbugroup/lti-web-client!292
This commit is contained in:
Adnan Zahir
2026-01-30 16:13:35 +07:00
61 changed files with 3121 additions and 1770 deletions
+11 -1
View File
@@ -22,6 +22,7 @@ export interface CardProps
onCollapsedChange?: (collapsed: boolean) => void;
className?: {
wrapper?: string;
wrapperContent?: string;
image?: string;
body?: string;
title?: string;
@@ -122,6 +123,10 @@ const Card = ({
return cn(baseClasses, 'p-6', className?.body);
};
const getCollapsibleClasses = () => {
return cn('', className?.collapsible);
};
const getTitleClasses = () => {
const sizeClasses = {
sm: 'text-lg',
@@ -144,6 +149,10 @@ 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;
@@ -177,7 +186,7 @@ const Card = ({
);
const cardContent = (
<div className='space-y-4'>
<div className={getWrapperContentClasses()}>
{children}
{actions && <div className={getActionsClasses()}>{actions}</div>}
{footer && <div className={getFooterClasses()}>{footer}</div>}
@@ -208,6 +217,7 @@ const Card = ({
titleClassName='w-full cursor-pointer'
contentClassName='p-0'
fullWidth={true}
className={getCollapsibleClasses()}
>
{cardContent}
</Collapse>
+5 -1
View File
@@ -12,6 +12,7 @@ import PopoverContent from '@/components/popover/PopoverContent';
import { useAuth } from '@/services/hooks/useAuth';
import { AuthApi } from '@/services/api/auth';
import { isResponseError } from '@/lib/api-helper';
import { useUiStore } from '@/stores/ui/ui.store';
interface NavbarProps {
toggleSidebar?: () => void;
@@ -21,6 +22,7 @@ const Navbar = ({ toggleSidebar }: NavbarProps) => {
const { setUser } = useAuth();
const router = useRouter();
const pathname = usePathname();
const navbarActions = useUiStore((state) => state.navbarActions);
const logoutClickHandler = async () => {
const logoutRes = await AuthApi.logout();
@@ -53,7 +55,9 @@ const Navbar = ({ toggleSidebar }: NavbarProps) => {
</div>
</div>
<div className='flex gap-2'>
<div className='flex gap-2 items-center'>
{/* Page-specific actions */}
{navbarActions && <div className='mr-2'>{navbarActions}</div>}
<PopoverButton
tabIndex={0}
variant='ghost'
+12 -2
View File
@@ -42,6 +42,7 @@ interface TableClassNames {
footerRowClassName?: string;
footerColumnClassName?: string;
paginationClassName?: string;
skeletonCellClassName?: string;
}
export interface TableProps<TData extends object> {
@@ -79,7 +80,9 @@ export interface TableProps<TData extends object> {
getSubRows?: (originalRow: TData, index: number) => TData[] | undefined;
}
const DUMMY_SKELETON_DATA = [{}, {}, {}, {}, {}];
const DUMMY_SKELETON_DATA = Array.from({ length: 10 }, (_, index) => ({
id: index,
}));
const emptyContentDefaultValue = (
<div className='w-full p-5 text-center'>
@@ -414,7 +417,14 @@ const Table = <TData extends object>({
cell.getContext()
)}
{isLoading && <div className='skeleton w-full h-4' />}
{isLoading && (
<div
className={cn(
'skeleton w-full h-4',
tableClassNames.skeletonCellClassName
)}
/>
)}
</td>
))}
</tr>
+23 -12
View File
@@ -25,8 +25,10 @@ export interface TabsProps
wrapper?: string;
tab?: string;
content?: string;
tabHeaderWrapper?: string;
};
onTabChange?: (tabId: string) => void;
sideContent?: ReactNode;
}
const Tabs = ({
@@ -38,6 +40,7 @@ const Tabs = ({
activeTabId: controlledActiveId,
className,
onTabChange,
sideContent,
...props
}: TabsProps) => {
// State internal hanya dipakai kalau `activeTabId` (controlled) tidak diset
@@ -59,6 +62,7 @@ const Tabs = ({
wrapper: wrapperClassName,
tab: tabClassName,
content: contentClassName,
tabHeaderWrapper: tabHeaderWrapperClassName,
} = typeof className === 'object'
? className
: { wrapper: className, tab: undefined };
@@ -102,6 +106,10 @@ const Tabs = ({
tabClassName
);
const getSideContentClasses = () => {
return cn('flex flex-row', tabHeaderWrapperClassName);
};
const activeContent = tabs.find((tab) => tab.id === activeTabId)?.content;
return (
@@ -112,18 +120,21 @@ const Tabs = ({
typeof className === 'string' ? className : containerClassName
)}
>
<div role='tablist' className={getTabsClasses()}>
{tabs.map(({ id, label, disabled }) => (
<button
key={id}
role='tab'
className={getTabClasses(id === activeTabId, disabled)}
onClick={() => !disabled && handleTabChange(id)}
disabled={disabled}
>
{label}
</button>
))}
<div className={getSideContentClasses()}>
<div role='tablist' className={getTabsClasses()}>
{tabs.map(({ id, label, disabled }) => (
<button
key={id}
role='tab'
className={getTabClasses(id === activeTabId, disabled)}
onClick={() => !disabled && handleTabChange(id)}
disabled={disabled}
>
{label}
</button>
))}
</div>
{sideContent && sideContent}
</div>
{activeContent && (
+9 -3
View File
@@ -9,15 +9,21 @@ export type ButtonFilterProps = ButtonProps & {
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
? 'bg-gradient-to-t from-blue-50 to-blue-100 border-blue-500 text-blue-600 hover:from-blue-100 hover:to-blue-200'
: '',
? 'border-primary-gradient text-primary rounded-lg!'
: 'rounded-lg',
props.className
)}
>
@@ -31,7 +37,7 @@ const ButtonFilter = ({ values, onClick, ...props }: ButtonFilterProps) => {
/>
Filter
{getFilledFormikValuesCount(values) > 0 && (
<span className='w-6 h-6 text-white bg-red-500 rounded-lg flex items-center justify-center text-xs'>
<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>
)}
+9 -2
View File
@@ -1,10 +1,17 @@
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'>Permission Not Found</h2>
<h2 className='text-2xl font-bold text-error'>
Hak Akses Tidak Ditemukan
</h2>
<p className='text-gray-600 text-center'>
You do not have permission to access this page.
Anda tidak memiliki hak akses untuk mengakses halaman ini.
</p>
<Button href='/dashboard' className='text-base-100'>
Kembali ke Dashboard
</Button>
</div>
);
};
+4 -2
View File
@@ -72,8 +72,10 @@ const RequireAuth = ({ children }: RequireAuthProps) => {
await AuthApi.refresh();
};
refreshUserSession();
}, []);
if (user) {
refreshUserSession();
}
}, [user]);
if (
(isLoadingUserResponse && !userResponse && !userErrorResponse) ||
+2
View File
@@ -27,6 +27,7 @@ const StatusBadge = ({
'bg-success/30': color === 'success',
'bg-error/20': color === 'error',
'bg-primary/20': color === 'info',
'bg-[#FF9A20]/12': color === 'warning',
},
className?.badge
),
@@ -43,6 +44,7 @@ const StatusBadge = ({
'text-[#008000]': color === 'success',
'text-error': color === 'error',
'text-primary': color === 'info',
'text-[#FF9A20]': color === 'warning',
})}
>
<circle r='6' cx='6' cy='6' fill='currentColor' />
@@ -58,6 +58,7 @@ const DrawerHeader = ({
if (leftIconOnClick) {
return (
<button
type='button'
onClick={leftIconOnClick}
className='hover:text-gray-400 bg-transparent border-none p-0'
>
@@ -72,12 +73,12 @@ const DrawerHeader = ({
return (
<div
className={cn(
'flex flex-row justify-between items-center px-4 pt-4',
'flex flex-row justify-between items-center px-4 pt-4 pb-4 border-b border-base-content/10',
className
)}
>
{/* Left Side */}
<div className='flex flex-row h-full gap-2 items-center'>
<div className='flex flex-row h-full gap-3 items-center'>
{renderLeftIcon()}
{showDivider && subtitle && (
@@ -85,7 +86,12 @@ const DrawerHeader = ({
)}
{subtitle && (
<div className={cn('text-sm text-neutral', subtitleClassName)}>
<div
className={cn(
'text-sm font-medium text-base-content/50',
subtitleClassName
)}
>
{subtitle}
</div>
)}
@@ -0,0 +1,32 @@
import IconSkeleton from '@/components/helper/skeleton/IconSkeleton';
import { Icon } from '@iconify/react';
const DataStateSkeleton = ({
icon,
title,
description,
}: {
icon: React.ReactNode;
title: string;
description: string;
}) => {
return (
<div className='flex flex-col items-center justify-center'>
<IconSkeleton
className={{
outer: 'mb-2.25',
}}
>
{icon}
</IconSkeleton>
<h3 className='text-base-content/50 font-semibold text-sm mb-1'>
{title}
</h3>
<p className='text-base-content/50 text-xs text-center max-w-xs'>
{description}
</p>
</div>
);
};
export default DataStateSkeleton;
@@ -0,0 +1,33 @@
import { cn } from '@/lib/helper';
import { ReactNode } from 'react';
const IconSkeleton = ({
children,
className,
}: {
children: ReactNode;
className?: {
outer?: string;
inner?: string;
};
}) => {
return (
<div
className={cn(
'w-12.5 h-12.5 bg-[var(--main-color-base-100,#FFFFFF)] border border-base-content/10 rounded-[0.875rem] shadow-[0px_25px_50px_-12px_#00000040] flex items-center justify-center',
className?.outer
)}
>
<div
className={cn(
'w-9.5 h-9.5 bg-primary rounded-lg border border-primary flex items-center justify-center shadow-[inset_0px_4px_4px_0px_#FFFFFF80,inset_0px_2px_0px_0px_#FFFFFF80]',
className?.inner
)}
>
{children}
</div>
</div>
);
};
export default IconSkeleton;
+20 -7
View File
@@ -280,7 +280,7 @@ const DateInput = ({
ref={calendarModal.ref}
className={{
modal: 'rounded',
modalBox: `!max-w-max min-h-${isRange ? '124' : '110'} flex flex-col`,
modalBox: `max-w-max flex flex-col`,
}}
closeOnBackdrop
>
@@ -296,7 +296,11 @@ const DateInput = ({
endMonth={maxDate ?? new Date(new Date().getFullYear() + 5, 11)}
selected={selectedRange as DateRange}
onSelect={handleSelectRange}
footer={<div className='text-center mt-3'>{displayValue}</div>}
footer={
<div className='text-center py-2 text-base-content/65 font-semibold text-xs'>
{displayValue}
</div>
}
disabled={
[
minDate ? { before: minDate } : undefined,
@@ -326,17 +330,26 @@ const DateInput = ({
)}
<div className='mt-auto flex flex-col gap-2'>
{isRange && (
<small className='text-secondary'>
Tekan dua kali untuk memilih tanggal awal
<small className='text-base-content/65'>
Tekan dua kali untuk reset tanggal awal
</small>
)}
<div className='flex h-full justify-end items-end gap-2'>
<Button type='button' color='warning' onClick={handleResetDate}>
<div className='flex h-full justify-end items-end gap-1.5 mt-3'>
<Button
type='button'
color='none'
className='bg-transparent hover:bg-base-content/10 border-none text-base text-base-content/65 px-3'
onClick={handleResetDate}
>
Reset
</Button>
{isRange && (
<Button type='button' onClick={handleSaveDate}>
<Button
type='button'
className='rounded-lg px-3 py-2 text-white'
onClick={handleSaveDate}
>
Simpan
</Button>
)}
+11 -7
View File
@@ -41,7 +41,7 @@ const FileInput = ({
return (
<div
className={cn(
'w-full flex flex-col gap-2 text-start',
'w-full flex flex-col gap-0 text-start rounded-lg',
className?.wrapper
)}
>
@@ -49,7 +49,7 @@ const FileInput = ({
<label
htmlFor={name}
className={cn(
'w-full text-sm font-normal leading-5',
'w-full py-2 text-xs font-semibold leading-5',
{
'text-error': isError,
},
@@ -77,15 +77,19 @@ const FileInput = ({
onChange={onChange}
onBlur={onBlur}
disabled={disabled}
className={cn('grow file-input w-full h-12 rounded', className?.input)}
className={cn(
'grow file-input w-full h-fit px-3 py-1.5 text-sm font-normal leading-6 rounded-lg! outline-none! transition-all duration-200 bg-white border-base-content/10',
className?.input
)}
readOnly={readOnly}
/>
{bottomLabel && (
<p className='w-full text-sm opacity-60'>{bottomLabel}</p>
{!isError && bottomLabel && (
<p className='w-full mt-1.5 text-xs opacity-60'>{bottomLabel}</p>
)}
{isError && errorMessage && (
<p className='w-full mt-1.5 text-xs text-error'>{errorMessage}</p>
)}
{isError && <p className='w-full text-sm text-error'>{errorMessage}</p>}
</div>
);
};
+265 -105
View File
@@ -54,6 +54,9 @@ interface SelectInputBaseProps<T = OptionType> {
wrapper?: string;
label?: string;
select?: string;
inputPrefix?: string;
inputSuffix?: string;
inputPrefixSuffixWrapper?: string;
};
isError?: boolean;
errorMessage?: string;
@@ -62,6 +65,8 @@ interface SelectInputBaseProps<T = OptionType> {
delay?: number;
onInputChange?: (search: string) => void;
startAdornment?: ReactNode;
inputPrefix?: ReactNode;
inputSuffix?: ReactNode;
menuPortalTarget?: HTMLElement | null;
closeMenuOnSelect?: boolean;
hideSelectedOptions?: boolean;
@@ -84,7 +89,7 @@ const CustomControl = <
>(
props: ControlProps<Option, IsMulti, Group>
) => {
const { children } = props;
const { children, innerProps } = props;
const customProps = props.selectProps as unknown as {
shouldShowAdornment?: boolean;
@@ -96,7 +101,7 @@ const CustomControl = <
return (
<ReactSelectComponents.Control {...props}>
<div className='flex-1 p-3! py-1.5 gap-1 flex items-center'>
<div className='flex-1 pl-3 gap-1 flex items-center' {...innerProps}>
{shouldShowAdornment && startAdornment}
{children}
</div>
@@ -153,6 +158,8 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
createables = false,
onInputChange,
startAdornment,
inputPrefix,
inputSuffix,
menuPortalTarget,
closeMenuOnSelect,
hideSelectedOptions,
@@ -227,111 +234,264 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
</span>
)}
<SelectComponent<T, boolean, GroupBase<T>>
instanceId='select'
value={value ?? (isMulti ? [] : null)}
onChange={onChange ? handleChange : undefined}
options={options}
menuIsOpen={openMenu}
inputValue={internalInputValue}
onInputChange={internalInputChangeHandler}
onMenuClose={() => setInternalInputValue('')}
isMulti={isMulti}
isDisabled={isDisabled || readOnly}
isLoading={isLoading}
isClearable={isClearable}
isRtl={isRtl}
isSearchable={isSearchable}
placeholder={placeholder}
closeMenuOnSelect={closeMenuOnSelect}
hideSelectedOptions={hideSelectedOptions}
className={cn('w-full', className?.select)}
classNames={{
...(!startAdornment && {
{inputPrefix || inputSuffix ? (
<div
className={cn(
'relative flex text-sm',
className?.inputPrefixSuffixWrapper
)}
>
{inputPrefix && (
<div
className={cn(
'inline-flex items-center px-3 border border-r-0 border-base-content/10 rounded-l-lg transition-all duration-200',
{
'bg-gray-100 border-base-content/10': !isDisabled,
'bg-gray-50 border-base-content/10': isDisabled,
'border-error': isError,
},
className?.inputPrefix
)}
>
{inputPrefix}
</div>
)}
<SelectComponent<T, boolean, GroupBase<T>>
instanceId='select'
value={value ?? (isMulti ? [] : null)}
onChange={onChange ? handleChange : undefined}
options={options}
menuIsOpen={openMenu}
inputValue={internalInputValue}
onInputChange={internalInputChangeHandler}
onMenuClose={() => setInternalInputValue('')}
isMulti={isMulti}
isDisabled={isDisabled || readOnly}
isLoading={isLoading}
isClearable={isClearable}
isRtl={isRtl}
isSearchable={isSearchable}
placeholder={placeholder}
closeMenuOnSelect={closeMenuOnSelect}
hideSelectedOptions={hideSelectedOptions}
className={cn('w-full flex-1', className?.select)}
classNames={{
control: ({ isFocused, isDisabled }) =>
cn('w-full border bg-white transition-shadow', 'rounded-lg!', {
'cursor-pointer!': !readOnly && !isDisabled,
'border-red-500! ring-2 ring-red-200': isError,
'border-indigo-500 ring-2 ring-indigo-200':
isFocused && !startAdornment,
'border-base-content/10!': !isError && !isFocused,
'bg-gray-100 text-gray-400 cursor-not-allowed':
isDisabled && !readOnly,
'bg-transparent! cursor-not-allowed!': readOnly,
'rounded-l-none!': inputPrefix && !startAdornment,
'rounded-r-none!': inputSuffix && !startAdornment,
}),
valueContainer: () => cn('flex-1 px-3! pr-2! py-2.5! gap-1'),
placeholder: () =>
cn({
'text-gray-400 text-sm leading-tight': !isError,
'text-red-300!': isError,
}),
singleValue: () =>
cn({
'm-0! text-gray-900 text-sm leading-tight': !isError,
'text-error!': isError,
'text-gray-900!': readOnly,
}),
input: () => cn('text-gray-900 m-0! p-0! text-sm leading-tight'),
indicatorsContainer: () =>
cn('flex items-center gap-1 pr-3 py-2'),
dropdownIndicator: ({ isFocused }) =>
cn('p-0! rounded hover:bg-gray-100', {
'text-gray-900': isFocused,
'text-gray-500': !isFocused,
'text-error!': isError,
}),
clearIndicator: () => cn('p-0! rounded hover:bg-gray-100'),
menu: () =>
cn(
'border border-base-content/5 rounded-xl! bg-base-100 shadow-lg! my-1.5!'
),
menuList: () => cn('p-0! max-h-60 overflow-auto'),
option: ({ isFocused, isSelected }) =>
cn('px-3 py-2 rounded-md cursor-pointer!', {
'bg-indigo-600 text-white': isFocused,
'bg-blue-500!': isSelected,
'text-gray-700': !isFocused && !isSelected,
}),
multiValue: ({ getValue, index }) => {
const selectedValues = getValue() as T[];
return cn(
'bg-base-200! rounded-lg! py-[3px] px-2.5 m-0! flex items-center gap-1! w-fit gap-2!',
selectedValues[index]?.className
);
},
multiValueRemove: () => cn('p-0! w-3 h-3'),
multiValueLabel: ({ getValue, index }) => {
const selectedValues = getValue() as T[];
return cn(
'p-0! text-base-content! text-xs!',
selectedValues[index]?.labelClassName
);
},
}}
components={{
...components,
...(optionComponent ? { Option: optionComponent } : {}),
MenuList: CustomMenuList,
}}
{...(startAdornment && {
shouldShowAdornment,
startAdornment,
})}
menuPortalTarget={
typeof document !== 'undefined'
? (menuPortalTarget ?? document.body)
: undefined
}
styles={{
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
multiValue(base) {
return {
...base,
borderRadius: '8px',
};
},
}}
onMenuScrollToBottom={onMenuScrollToBottom}
/>
{inputSuffix && (
<div
className={cn(
'inline-flex items-center px-3 border border-l-0 border-base-content/10 rounded-r-lg transition-all duration-200',
{
'bg-gray-100 border-base-content/10': !isDisabled,
'bg-gray-50 border-base-content/10': isDisabled,
'border-error': isError,
},
className?.inputSuffix
)}
>
{inputSuffix}
</div>
)}
</div>
) : (
<SelectComponent<T, boolean, GroupBase<T>>
instanceId='select'
value={value ?? (isMulti ? [] : null)}
onChange={onChange ? handleChange : undefined}
options={options}
menuIsOpen={openMenu}
inputValue={internalInputValue}
onInputChange={internalInputChangeHandler}
onMenuClose={() => setInternalInputValue('')}
isMulti={isMulti}
isDisabled={isDisabled || readOnly}
isLoading={isLoading}
isClearable={isClearable}
isRtl={isRtl}
isSearchable={isSearchable}
placeholder={placeholder}
closeMenuOnSelect={closeMenuOnSelect}
hideSelectedOptions={hideSelectedOptions}
className={cn('w-full', className?.select)}
classNames={{
control: ({ isFocused, isDisabled }) =>
cn('w-full rounded-lg! border bg-white transition-shadow', {
'cursor-pointer!': !readOnly && !isDisabled,
'border-red-500! ring-2 ring-red-200': isError,
'border-indigo-500 ring-2 ring-indigo-200': isFocused,
'border-base-content/10!': !isError && !isFocused,
'bg-gray-100 text-gray-400 cursor-not-allowed':
isDisabled && !readOnly,
'bg-transparent! cursor-not-allowed!': readOnly,
}),
cn(
'w-full border bg-white transition-shadow',
// Gunakan rounded-lg untuk semua kasus
'rounded-lg!',
{
'cursor-pointer!': !readOnly && !isDisabled,
'border-red-500! ring-2 ring-red-200': isError,
'border-indigo-500 ring-2 ring-indigo-200':
isFocused && !startAdornment,
'border-base-content/10!': !isError && !isFocused,
'bg-gray-100 text-gray-400 cursor-not-allowed':
isDisabled && !readOnly,
'bg-transparent! cursor-not-allowed!': readOnly,
}
),
valueContainer: () => cn('flex-1 px-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}
/>
placeholder: () =>
cn({
'text-gray-400 text-sm leading-tight': !isError,
'text-red-300!': isError,
}),
singleValue: () =>
cn({
'm-0! text-gray-900 text-sm leading-tight': !isError,
'text-error!': isError,
'text-gray-900!': readOnly,
}),
input: () => cn('text-gray-900 m-0! p-0! text-sm leading-tight'),
indicatorsContainer: () => cn('flex items-center gap-1 pr-3 py-2'),
dropdownIndicator: ({ isFocused }) =>
cn('p-0! rounded hover:bg-gray-100', {
'text-gray-900': isFocused,
'text-gray-500': !isFocused,
'text-error!': isError,
}),
clearIndicator: () => cn('p-0! rounded hover:bg-gray-100'),
menu: () =>
cn(
'border border-base-content/5 rounded-xl! bg-base-100 shadow-lg! my-1.5!'
),
menuList: () => cn('p-0! max-h-60 overflow-auto'),
option: ({ isFocused, isSelected }) =>
cn('px-3 py-2 rounded-md cursor-pointer!', {
'bg-indigo-600 text-white': isFocused,
'bg-blue-500!': isSelected,
'text-gray-700': !isFocused && !isSelected,
}),
multiValue: ({ getValue, index }) => {
const selectedValues = getValue() as T[];
return cn(
'bg-base-200! rounded-lg! py-[3px] px-2.5 m-0! flex items-center gap-1! w-fit gap-2!',
selectedValues[index]?.className
);
},
multiValueRemove: () => cn('p-0! w-3 h-3'),
multiValueLabel: ({ getValue, index }) => {
const selectedValues = getValue() as T[];
return cn(
'p-0! text-base-content! text-xs!',
selectedValues[index]?.labelClassName
);
},
}}
components={{
...components,
...(optionComponent ? { Option: optionComponent } : {}),
MenuList: CustomMenuList,
}}
{...(startAdornment && {
shouldShowAdornment,
startAdornment,
})}
menuPortalTarget={
typeof document !== 'undefined'
? (menuPortalTarget ?? document.body)
: undefined
}
styles={{
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
multiValue(base) {
return {
...base,
borderRadius: '8px',
};
},
}}
onMenuScrollToBottom={onMenuScrollToBottom}
/>
)}
{isError && <p className='w-full text-sm text-error'>{errorMessage}</p>}
{!isError && bottomLabel && (
+4 -4
View File
@@ -102,7 +102,7 @@ const TextInput = ({
{inputPrefix && (
<div
className={cn(
'inline-flex items-center px-3 py-2.5 border border-r-0 border-base-content/10 rounded-l-lg transition-all duration-200',
'inline-flex items-center px-3 border border-r-0 border-base-content/10 rounded-l-lg transition-all duration-200',
{
'bg-gray-100 border-base-content/10': !disabled,
'bg-gray-50 border-base-content/10': disabled,
@@ -165,10 +165,10 @@ const TextInput = ({
{inputSuffix && (
<div
className={cn(
'inline-flex items-center px-3 py-2.5 border border-l-0 border-base-content/10 rounded-r-lg transition-all duration-200',
'inline-flex items-center px-3 border border-l-0 border-base-content/10 rounded-r-lg transition-all duration-200',
{
'bg-gray-100 border-gray-300': !disabled,
'bg-gray-50 border-gray-200': disabled,
'bg-gray-100 border-base-content/10': !disabled,
'bg-gray-50 border-base-content/10': disabled,
'border-error': isError,
'border-success!': isValid,
},
@@ -4,10 +4,7 @@ import Button from '@/components/Button';
import { Icon } from '@iconify/react';
import Modal, { useModal } from '@/components/Modal';
import DateInput from '@/components/input/DateInput';
import SelectInput, {
OptionType,
useSelect,
} from '@/components/input/SelectInput';
import { OptionType, useSelect } from '@/components/input/SelectInput';
import { useState, useEffect, useRef, useCallback } from 'react';
import useSWR from 'swr';
import { DashboardApi } from '@/services/api/dashboard';
@@ -21,9 +18,9 @@ import {
} from '@/components/pages/dashboard/filter/DashboardProductionFilter.schema';
import DashboardLineChart from '@/components/pages/dashboard/chart/DashboardLineChart';
import DashboardLineChartSkeleton from '@/components/pages/dashboard/skeleton/DashboardLineChartSkeleton';
import DashboardAllCharts, {
DashboardAllChartsRef,
} from '@/components/pages/dashboard/chart/DashboardAllCharts';
import DashboardExportCharts, {
DashboardExportChartsRef,
} from '@/components/pages/dashboard/export/DashboardExportCharts';
import { RadioGroup, RadioGroupItem } from '@/components/input/RadioInput';
import {
DashboardFilter,
@@ -40,6 +37,11 @@ import MenuItem from '@/components/menu/MenuItem';
import { useDashboardStore } from '@/stores/dashboard';
import SelectInputRadio from '@/components/input/SelectInputRadio';
import SelectInputCheckbox from '@/components/input/SelectInputCheckbox';
import { useUiStore } from '@/stores/ui/ui.store';
import { cn } from '@/lib/helper';
import DashboardExportStats, {
DashboardExportStatsRef,
} from '@/components/pages/dashboard/export/DashboardExportStats';
// Helper function to normalize values to array
const normalizeToArray = (
@@ -59,6 +61,10 @@ const DashboardProduction = () => {
const { filterValues, setFilterValues, resetFilterValues } =
useDashboardStore();
// ===== UI STORE (for navbar actions) =====
const setNavbarActions = useUiStore((state) => state.setNavbarActions);
const clearNavbarActions = useUiStore((state) => state.clearNavbarActions);
const [analysisMode, setAnalysisMode] = useState<'OVERVIEW' | 'COMPARISON'>(
(filterValues.analysisMode as 'OVERVIEW' | 'COMPARISON') || 'OVERVIEW'
);
@@ -67,9 +73,8 @@ const DashboardProduction = () => {
normalizeToArray(filterValues.location)
);
const [exporting, setExporting] = useState(false);
const statsRef = useRef<HTMLDivElement>(null);
const chartRef = useRef<HTMLDivElement>(null);
const allChartsRef = useRef<DashboardAllChartsRef>(null);
const allChartsRef = useRef<DashboardExportChartsRef>(null);
const allStatsRef = useRef<DashboardExportStatsRef>(null);
// ===== FETCH DATA =====
const {
@@ -194,12 +199,69 @@ const DashboardProduction = () => {
const handleExportPDF = async () => {
await generateDashboardPDF({
filterValues: formik.values,
statsRef,
allStatsRef,
allChartsRef,
setExporting,
});
};
// ===== Register Navbar Actions =====
const openFilterModalRef = useRef(filterModal.openModal);
openFilterModalRef.current = filterModal.openModal;
useEffect(() => {
setNavbarActions(
<div className='hidden sm:flex flex-row justify-end gap-3 '>
<ButtonFilter
values={{
...formik.values,
analysisMode: undefined,
}}
variant='outline'
onClick={() => openFilterModalRef.current()}
/>
<Dropdown
trigger={
<Button
variant='outline'
color='none'
className={cn(
'rounded-lg font-semibold text-sm gap-1.5',
'text-sm text-base-content/50 border border-base-content/10 shadow-button-soft'
)}
>
<Icon width={20} height={20} icon='heroicons:cloud-arrow-down' />
Export
<div className='w-6.5 h-5 flex items-center justify-center border-l border-base-content/10'>
<Icon width={14} height={14} icon='heroicons:chevron-down' />
</div>
</Button>
}
className={{
content: 'w-full mt-1 p-0',
}}
>
<Menu
className={`p-0 w-full shadow-button-soft border border-base-content/10 rounded-lg ${exporting ? 'hidden' : ''}`}
>
<MenuItem
className='text-sm p-3'
title='PDF'
onClick={handleExportPDF}
/>
</Menu>
</Dropdown>
</div>
);
}, [formik.values, exporting, setNavbarActions]);
// Cleanup only on unmount
useEffect(() => {
return () => {
clearNavbarActions();
};
}, [clearNavbarActions]);
if (isLoadingDashboardProductionData) {
return (
<div className='w-full min-h-screen flex items-center justify-center'>
@@ -210,48 +272,62 @@ const DashboardProduction = () => {
return (
<>
<section className='w-full p-4 space-y-6'>
<div className='flex flex-col sm:flex-row items-center justify-between gap-4'>
<div></div>
<div className='flex flex-row justify-end gap-2'>
<ButtonFilter
values={{
...formik.values,
analysisMode: undefined,
}}
variant='outline'
className='min-w-28 rounded-lg'
onClick={() => filterModal.openModal()}
/>
<Dropdown
trigger={
<Button variant='outline' className='min-w-28 rounded-lg z-50'>
<Icon icon='heroicons:arrow-down-tray' />
Export
<Icon icon='heroicons:chevron-down' />
</Button>
}
className={{
content: 'w-full',
}}
<section className='w-full p-3 space-y-3'>
<div className='flex sm:hidden flex-row justify-end gap-3 '>
<ButtonFilter
values={{
...formik.values,
analysisMode: undefined,
}}
variant='outline'
onClick={() => openFilterModalRef.current()}
/>
<Dropdown
trigger={
<Button
variant='outline'
color='none'
className={cn(
'p-2 rounded-lg font-semibold text-sm gap-1.5',
'text-sm text-base-content/50 border border-base-content/10 shadow-button-soft'
)}
>
<Icon
width={20}
height={20}
icon='heroicons:cloud-arrow-down'
/>
Export
<div className='w-6.5 h-5 flex items-center justify-center border-l border-base-content/10'>
<Icon width={14} height={14} icon='heroicons:chevron-down' />
</div>
</Button>
}
className={{
content:
'w-full mt-1 p-0 shadow-button-soft border border-base-content/10 rounded-lg',
}}
>
<Menu
className={`p-0 w-full shadow-button-soft border border-base-content/10 rounded-lg ${exporting ? 'hidden' : ''}`}
>
<Menu className={exporting ? 'hidden' : ''}>
<MenuItem title='PDF' onClick={handleExportPDF} />
</Menu>
</Dropdown>
</div>
<MenuItem
className='text-sm p-3'
title='PDF'
onClick={handleExportPDF}
/>
</Menu>
</Dropdown>
</div>
{/* Dashboard Stats */}
<div ref={statsRef}>
<div>
<DashboardStats
data={dashboardProductionData?.statistics_data ?? []}
/>
</div>
{/* Use DashboardLineChart component or skeleton */}
<div ref={chartRef}>
<div>
{isLoadingDashboardProductionData ? (
<DashboardLineChartSkeleton />
) : dashboardProductionData &&
@@ -287,28 +363,46 @@ const DashboardProduction = () => {
{/* Hidden container for all charts (used for PDF export in OVERVIEW mode) */}
{dashboardProductionData && (
<div
style={{
position: 'absolute',
left: '-9999px',
top: 0,
width: '1200px', // Fixed width for consistent PDF rendering
}}
>
<DashboardAllCharts
ref={allChartsRef}
data={dashboardProductionData}
analysisMode={
isResponseSuccess(dashboardProductionResponse)
? dashboardProductionResponse.meta
? (
dashboardProductionResponse.meta as unknown as DashboardMeta
).filters?.analysis_mode
<>
{/* Export Stats Charts */}
<div
style={{
position: 'absolute',
left: '-9999px',
top: 0,
width: '1200px', // Fixed width for consistent PDF rendering
}}
>
<DashboardExportStats
ref={allStatsRef}
data={dashboardProductionData?.statistics_data ?? []}
/>
</div>
{/* Export ALL Charts */}
<div
style={{
position: 'absolute',
left: '-9999px',
top: 0,
width: '1200px', // Fixed width for consistent PDF rendering
}}
>
<DashboardExportCharts
ref={allChartsRef}
data={dashboardProductionData}
analysisMode={
isResponseSuccess(dashboardProductionResponse)
? dashboardProductionResponse.meta
? (
dashboardProductionResponse.meta as unknown as DashboardMeta
).filters?.analysis_mode
: analysisMode
: analysisMode
: analysisMode
}
/>
</div>
}
/>
</div>
</>
)}
</section>
@@ -316,102 +410,106 @@ const DashboardProduction = () => {
ref={filterModal.ref}
className={{
modal: 'p-0',
modalBox: 'p-0 rounded-xl',
modalBox: 'p-0 rounded-[0.875rem]',
}}
>
<div className='space-y-6'>
<div className='flex flex-col'>
{/* Modal Header */}
<div className='flex items-center justify-between gap-2 py-3 border-b border-gray-300'>
<div className='flex items-center gap-2 ms-4'>
<div className='flex items-center justify-between p-4 border-b border-base-content/10'>
<div className='flex items-center gap-2 text-primary'>
<Icon icon='heroicons:funnel' width={20} height={20} />
<h3 className='font-semibold'>Filter Data</h3>
<h3 className='font-medium text-sm'>Filter Data</h3>
</div>
<Button
variant='link'
onClick={() => filterModal.closeModal()}
className='text-gray-500 hover:text-gray-700 me-4 '
className='text-gray-500 hover:text-gray-700'
>
<Icon icon='heroicons:x-mark' width={20} height={20} />
</Button>
</div>
<form
className='space-y-4'
className='flex flex-col'
onSubmit={handleFormSubmit}
onReset={handleResetFilter}
>
{/* Rentang Waktu */}
<div className='px-4'>
<label className='flex items-center gap-2 mb-3'>Tanggal</label>
<div className='flex items-start gap-2'>
<DateInput
name='startDate'
placeholder='Tanggal Mulai'
value={formik.values.startDate}
errorMessage={formik.errors.startDate}
onChange={formik.handleChange}
className={{
inputWrapper: 'rounded-lg',
}}
isError={
Boolean(formik.errors.startDate) &&
Boolean(formik.touched.startDate)
}
/>
<div className='hidden md:block mt-3 text-center'></div>
<DateInput
name='endDate'
placeholder='Tanggal Akhir'
value={formik.values.endDate}
errorMessage={formik.errors.endDate}
onChange={formik.handleChange}
className={{
inputWrapper: 'rounded-lg',
}}
isError={
Boolean(formik.errors.endDate) &&
Boolean(formik.touched.endDate)
}
/>
<div className='flex flex-col p-4 gap-1.5'>
{/* Rentang Waktu */}
<div>
<label className='flex text-xs items-center gap-2 py-2 font-semibold'>
Tanggal
</label>
<div className='flex items-center gap-2'>
<DateInput
name='startDate'
placeholder='Tanggal Mulai'
value={formik.values.startDate}
errorMessage={formik.errors.startDate}
onChange={formik.handleChange}
isError={
Boolean(formik.errors.startDate) &&
Boolean(formik.touched.startDate)
}
/>
<hr className='w-full max-w-3 h-px border-base-content/10'></hr>
<DateInput
name='endDate'
placeholder='Tanggal Akhir'
value={formik.values.endDate}
errorMessage={formik.errors.endDate}
onChange={formik.handleChange}
isError={
Boolean(formik.errors.endDate) &&
Boolean(formik.touched.endDate)
}
/>
</div>
</div>
</div>
{/* Analysis Mode */}
<div className='px-4'>
<label className='block mb-3'>Analysis Mode</label>
<RadioGroup
name='analysisMode'
value={formik.values.analysisMode}
onChange={(e) => {
formik.handleChange(e);
setAnalysisMode(e.target.value as 'OVERVIEW' | 'COMPARISON');
// Reset all dependent fields when analysis mode changes
formik.setFieldValue('location', []);
formik.setFieldValue('flock', []);
formik.setFieldValue('kandang', []);
formik.setFieldValue('comparisonType', '');
setSelectedLocationIds([]);
}}
color='primary'
className={{
wrapper: 'w-full my-6 font-semibold text-neutral-500',
}}
>
<RadioGroupItem
{/* Analysis Mode */}
<div>
<label className='block py-2 text-xs font-semibold'>
Analysis Mode
</label>
<RadioGroup
name='analysisMode'
value={formik.values.analysisMode}
onChange={(e) => {
formik.handleChange(e);
setAnalysisMode(
e.target.value as 'OVERVIEW' | 'COMPARISON'
);
// Reset all dependent fields when analysis mode changes
formik.setFieldValue('location', []);
formik.setFieldValue('flock', []);
formik.setFieldValue('kandang', []);
formik.setFieldValue('comparisonType', '');
setSelectedLocationIds([]);
}}
color='primary'
value='OVERVIEW'
label='Performance Overview'
/>
<RadioGroupItem
color='primary'
value='COMPARISON'
label='Performance Comparison'
/>
</RadioGroup>
</div>
className={{
wrapper:
'w-full flex flex-row items-center font-medium text-base-content/50',
radioWrapper: 'w-full grid grid-cols-2 gap-0 p-0',
}}
>
<RadioGroupItem
color='primary'
value='OVERVIEW'
label='Performance Overview'
className='w-full p-3'
/>
<RadioGroupItem
color='primary'
value='COMPARISON'
label='Performance Comparison'
className='w-full p-3'
/>
</RadioGroup>
</div>
{formik.values.analysisMode === 'COMPARISON' && (
<div className='px-4'>
{formik.values.analysisMode === 'COMPARISON' && (
<SelectInputRadio
label='Compared By'
value={comparisonTypeOptions.find(
@@ -430,12 +528,13 @@ const DashboardProduction = () => {
Boolean(formik.errors.comparisonType) &&
Boolean(formik.touched.comparisonType)
}
className={{
select: 'rounded-lg text-sm border-base-content/10',
}}
/>
</div>
)}
)}
{/* Location */}
<div className='px-4'>
{/* Location */}
{comparisonTypeOptions.find(
(option) => option.value === formik.values.comparisonType
)?.value === 'FARM' ? (
@@ -465,6 +564,9 @@ const DashboardProduction = () => {
Boolean(formik.errors.location) &&
Boolean(formik.touched.location)
}
className={{
select: 'rounded-lg text-sm border-base-content/10',
}}
/>
) : (
<SelectInputRadio
@@ -493,144 +595,167 @@ const DashboardProduction = () => {
Boolean(formik.errors.location) &&
Boolean(formik.touched.location)
}
className={{
select: 'rounded-lg text-sm border-base-content/10',
}}
/>
)}
{/* Flock */}
{!(
formik.values.analysisMode === 'COMPARISON' &&
!(
formik.values.comparisonType === 'FLOCK' ||
formik.values.comparisonType === 'KANDANG'
)
) && (
<>
{comparisonTypeOptions.find(
(option) => option.value === formik.values.comparisonType
)?.value === 'FLOCK' ? (
<SelectInputCheckbox
label='Flock'
value={
formik.values.flock as
| { value: number; label: string }
| { value: number; label: string }[]
| null
| undefined
}
onChange={(selected) =>
formik.setFieldValue('flock', selected)
}
errorMessage={formik.errors.flock as string}
onInputChange={setInputValueFlock}
onMenuScrollToBottom={loadMoreFlock}
options={flockOptions}
isLoading={isLoadingFlockOptions}
isError={
Boolean(formik.errors.flock) &&
Boolean(formik.touched.flock)
}
className={{
select: 'rounded-lg text-sm border-base-content/10',
}}
/>
) : (
<SelectInputRadio
label='Flock'
value={
formik.values.flock as
| { value: number; label: string }
| { value: number; label: string }[]
| null
| undefined
}
onChange={(selected) =>
formik.setFieldValue('flock', selected)
}
errorMessage={formik.errors.flock as string}
onInputChange={setInputValueFlock}
onMenuScrollToBottom={loadMoreFlock}
options={flockOptions}
isLoading={isLoadingFlockOptions}
isError={
Boolean(formik.errors.flock) &&
Boolean(formik.touched.flock)
}
className={{
select: 'rounded-lg text-sm border-base-content/10',
}}
/>
)}
</>
)}
{/* Kandang */}
{!(
formik.values.analysisMode === 'COMPARISON' &&
!(formik.values.comparisonType === 'KANDANG')
) && (
<>
{comparisonTypeOptions.find(
(option) => option.value === formik.values.comparisonType
)?.value === 'KANDANG' ? (
<SelectInputCheckbox
label='Kandang'
value={
formik.values.kandang as
| { value: number; label: string }
| { value: number; label: string }[]
| null
| undefined
}
onChange={(selected) =>
formik.setFieldValue('kandang', selected)
}
errorMessage={formik.errors.kandang as string}
onInputChange={setInputValueKandang}
onMenuScrollToBottom={loadMoreKandang}
options={kandangOptions}
isLoading={isLoadingKandangOptions}
isError={
Boolean(formik.errors.kandang) &&
Boolean(formik.touched.kandang)
}
className={{
select: 'rounded-lg text-sm border-base-content/10',
}}
/>
) : (
<SelectInputRadio
label='Kandang'
value={
formik.values.kandang as
| { value: number; label: string }
| { value: number; label: string }[]
| null
| undefined
}
onChange={(selected) =>
formik.setFieldValue('kandang', selected)
}
errorMessage={formik.errors.kandang as string}
onInputChange={setInputValueKandang}
onMenuScrollToBottom={loadMoreKandang}
options={kandangOptions}
isLoading={isLoadingKandangOptions}
isError={
Boolean(formik.errors.kandang) &&
Boolean(formik.touched.kandang)
}
className={{
select: 'rounded-lg text-sm border-base-content/10',
}}
/>
)}
</>
)}
{formErrorList.length > 0 && (
<div className='w-full'>
<AlertErrorList
formErrorList={formErrorList}
onClose={close}
/>
</div>
)}
</div>
{/* Flock */}
{!(
formik.values.analysisMode === 'COMPARISON' &&
!(
formik.values.comparisonType === 'FLOCK' ||
formik.values.comparisonType === 'KANDANG'
)
) && (
<div className='px-4'>
{comparisonTypeOptions.find(
(option) => option.value === formik.values.comparisonType
)?.value === 'FLOCK' ? (
<SelectInputCheckbox
label='Flock'
value={
formik.values.flock as
| { value: number; label: string }
| { value: number; label: string }[]
| null
| undefined
}
onChange={(selected) =>
formik.setFieldValue('flock', selected)
}
errorMessage={formik.errors.flock as string}
onInputChange={setInputValueFlock}
onMenuScrollToBottom={loadMoreFlock}
options={flockOptions}
isLoading={isLoadingFlockOptions}
isError={
Boolean(formik.errors.flock) &&
Boolean(formik.touched.flock)
}
/>
) : (
<SelectInputRadio
label='Flock'
value={
formik.values.flock as
| { value: number; label: string }
| { value: number; label: string }[]
| null
| undefined
}
onChange={(selected) =>
formik.setFieldValue('flock', selected)
}
errorMessage={formik.errors.flock as string}
onInputChange={setInputValueFlock}
onMenuScrollToBottom={loadMoreFlock}
options={flockOptions}
isLoading={isLoadingFlockOptions}
isError={
Boolean(formik.errors.flock) &&
Boolean(formik.touched.flock)
}
/>
)}
</div>
)}
{/* Kandang */}
{!(
formik.values.analysisMode === 'COMPARISON' &&
!(formik.values.comparisonType === 'KANDANG')
) && (
<div className='px-4'>
{comparisonTypeOptions.find(
(option) => option.value === formik.values.comparisonType
)?.value === 'KANDANG' ? (
<SelectInputCheckbox
label='Kandang'
value={
formik.values.kandang as
| { value: number; label: string }
| { value: number; label: string }[]
| null
| undefined
}
onChange={(selected) =>
formik.setFieldValue('kandang', selected)
}
errorMessage={formik.errors.kandang as string}
onInputChange={setInputValueKandang}
onMenuScrollToBottom={loadMoreKandang}
options={kandangOptions}
isLoading={isLoadingKandangOptions}
isError={
Boolean(formik.errors.kandang) &&
Boolean(formik.touched.kandang)
}
/>
) : (
<SelectInputRadio
label='Kandang'
value={
formik.values.kandang as
| { value: number; label: string }
| { value: number; label: string }[]
| null
| undefined
}
onChange={(selected) =>
formik.setFieldValue('kandang', selected)
}
errorMessage={formik.errors.kandang as string}
onInputChange={setInputValueKandang}
onMenuScrollToBottom={loadMoreKandang}
options={kandangOptions}
isLoading={isLoadingKandangOptions}
isError={
Boolean(formik.errors.kandang) &&
Boolean(formik.touched.kandang)
}
/>
)}
</div>
)}
<div className='w-full p-4'>
<AlertErrorList formErrorList={formErrorList} onClose={close} />
</div>
{/* Action Buttons */}
<div className='flex justify-between gap-4 py-4 mt-8 border-t border-gray-300 bg-gray-100'>
<div className='flex justify-between gap-4 p-4 border-t border-base-content/10 bg-gray-100'>
<Button
type='reset'
variant='soft'
className='ms-4 min-w-36 rounded-lg'
className='rounded-lg p-3 bg-gray-100 border-gray-100 text-base-content/65 hover:bg-base-content/10'
>
Reset Filter
</Button>
<Button type='submit' className='me-4 min-w-36 rounded-lg'>
Terapkan Filter
<Button
type='submit'
className='min-w-40 text-sm p-3 text-white rounded-lg'
>
Apply Filter
</Button>
</div>
</form>
@@ -1,6 +1,7 @@
import Button from '@/components/Button';
import Card from '@/components/Card';
import Dropdown from '@/components/Dropdown';
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
import { OptionType } from '@/components/input/SelectInput';
import Menu from '@/components/menu/Menu';
import MenuItem from '@/components/menu/MenuItem';
@@ -147,11 +148,12 @@ const DashboardLineChart = ({
return (
<Card
className={{
wrapper: 'w-full rounded-lg',
wrapper: 'w-full rounded-lg p-0',
body: 'p-4',
}}
variant='bordered'
>
<div className='flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6'>
<div className='flex flex-col sm:flex-row justify-between items-start gap-4 mb-3'>
<div className='text-lg font-semibold'>
Performance{' '}
<Icon
@@ -165,26 +167,28 @@ const DashboardLineChart = ({
<Dropdown
align='end'
direction='bottom'
className={{
content: 'mt-1 min-w-full',
}}
trigger={
<Button
variant='outline'
color='none'
className='text-neutral-500 hover:text-neutral-700 rounded-lg px-4 py-2 border-neutral-300'
className='py-2.5 pl-3 pr-2 text-base-content/50 rounded-lg text-sm border-base-content/10 shadow-button-soft'
onClick={() => setOpen(!open)}
>
{chartTypeLabels[chartData]}{' '}
<div className='divider divider-horizontal p-0 m-0 before:bg-neutral-300 after:bg-neutral-300'></div>
<Icon icon='heroicons:chevron-down' width={20} height={20} />
<div className='w-6 h-5 flex items-center justify-center border-l border-base-content/10'>
<Icon icon='heroicons:chevron-down' width={14} height={14} />
</div>
</Button>
}
className={{
content: 'w-52 mt-3',
}}
controlled={open}
>
<Menu>
<Menu className='p-0 w-full shadow-button-soft border border-base-content/10 rounded-lg'>
<MenuItem
title='Body weight'
className='text-sm padding-3 whitespace-nowrap'
onClick={() => {
setChartData('body_weight');
setOpen(!open);
@@ -192,6 +196,7 @@ const DashboardLineChart = ({
/>
<MenuItem
title='Performance'
className='text-sm padding-3 whitespace-nowrap'
onClick={() => {
setChartData('performance');
setOpen(!open);
@@ -199,6 +204,7 @@ const DashboardLineChart = ({
/>
<MenuItem
title='FCR'
className='text-sm padding-3 whitespace-nowrap'
onClick={() => {
setChartData('fcr');
setOpen(!open);
@@ -206,6 +212,7 @@ const DashboardLineChart = ({
/>
<MenuItem
title='Quality Control'
className='text-sm padding-3 whitespace-nowrap'
onClick={() => {
setChartData('quality_control');
setOpen(!open);
@@ -213,6 +220,7 @@ const DashboardLineChart = ({
/>
<MenuItem
title='Deplesi'
className='text-sm padding-3 whitespace-nowrap'
onClick={() => {
setChartData('deplesi');
setOpen(!open);
@@ -248,8 +256,8 @@ const DashboardLineChart = ({
.includes('std');
return (
<button
key={series.id}
<Button
key={`${series.id}-${index}`}
onClick={() => {
const newVisible = new Set(visibleSeries);
if (isVisible) {
@@ -259,14 +267,16 @@ const DashboardLineChart = ({
}
setVisibleSeries(newVisible);
}}
className={`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors ${
variant='outline'
color='none'
className={`flex items-center gap-2 p-3 rounded-lg border transition-colors ${
isVisible
? 'border-neutral-400 bg-neutral-50'
: 'border-neutral-300 hover:bg-neutral-50'
? 'border-base-content/10 hover:bg-base-content/4'
: 'border-base-content/10 bg-base-content/4'
}`}
>
<div
className={`w-6 h-0.5 ${
className={`w-5 h-0.5 ${
isStandard ? 'border-t-2 border-dashed' : ''
} ${!isVisible ? 'opacity-30' : ''}`}
style={{
@@ -279,17 +289,17 @@ const DashboardLineChart = ({
}}
></div>
<span
className={`text-sm ${isVisible ? 'text-neutral-900 font-medium' : 'text-neutral-700'}`}
className={`font-semibold text-sm ${isVisible ? 'text-base-content/50' : 'text-base-content/50'}`}
>
{series.label}
</span>
<Icon
icon='heroicons:information-circle'
icon='heroicons:eye'
width={16}
height={16}
className='text-neutral-400'
className='text-base-content/40'
/>
</button>
</Button>
);
});
})()}
@@ -335,20 +345,68 @@ const DashboardLineChart = ({
<CartesianGrid strokeDasharray='3 3' stroke='#e5e7eb' />
<XAxis
dataKey='week'
tick={{ fontSize: 11, fill: '#9ca3af' }}
tick={{
fontSize: 12,
fill: '#18181B',
opacity: 0.5,
fontWeight: 600,
}}
tickLine={false}
axisLine={{ stroke: '#e5e7eb' }}
axisLine={{ stroke: '#C1C1C180', opacity: 0.5 }}
label={{
value: 'Weeks',
position: 'insideBottom',
offset: -5,
style: { fontSize: 12, fill: '#9ca3af' },
style: {
fontSize: 12,
fill: '#18181B',
opacity: 0.2,
fontWeight: 600,
},
}}
/>
<YAxis
tick={{ fontSize: 11, fill: '#9ca3af' }}
tick={{
fontSize: 12,
fill: '#18181B',
opacity: 0.5,
fontWeight: 600,
}}
label={
(chartData === 'body_weight' || chartData === 'performance') &&
analysisMode === 'OVERVIEW'
? {
value:
chartData === 'body_weight'
? 'Body Weight'
: 'Percentage',
position: 'insideLeft',
angle: -90,
offset: 5,
style: {
fontSize: 12,
fill: '#18181B',
opacity: 0.2,
fontWeight: 600,
},
}
: analysisMode === 'COMPARISON'
? {
value: 'Percentage',
position: 'insideLeft',
angle: -90,
offset: 5,
style: {
fontSize: 12,
fill: '#18181B',
opacity: 0.2,
fontWeight: 600,
},
}
: undefined
}
tickLine={false}
axisLine={{ stroke: '#e5e7eb' }}
axisLine={{ stroke: '#C1C1C180', opacity: 0.5 }}
domain={(() => {
// Calculate dynamic domain based on visible data
let seriesData: DashboardChartsSeries[] = [];
@@ -399,14 +457,12 @@ const DashboardLineChart = ({
})()}
ticks={(() => {
// Calculate dynamic ticks based on domain
let seriesData: DashboardChartsSeries[] = [];
let dataset: DashboardChartsDataset[] = [];
if (
analysisMode === 'OVERVIEW' &&
isOverviewCharts(data.charts)
) {
seriesData = data.charts[chartData]?.series || [];
dataset = data.charts[chartData]?.dataset || [];
} else if (
analysisMode === 'COMPARISON' &&
@@ -416,7 +472,6 @@ const DashboardLineChart = ({
data.charts.farm ||
data.charts.flock ||
data.charts.kandang;
seriesData = comparisonChart?.series || [];
dataset = comparisonChart?.dataset || [];
}
@@ -436,6 +491,20 @@ const DashboardLineChart = ({
const minValue = Math.min(...allValues);
const maxValue = Math.max(...allValues);
// Handle edge case where min equals max
if (minValue === maxValue) {
const value = Math.round(minValue);
const padding = Math.max(10, Math.abs(value) * 0.2);
return [
Math.floor(value - padding),
Math.floor(value - padding / 2),
value,
Math.ceil(value + padding / 2),
Math.ceil(value + padding),
];
}
const padding = (maxValue - minValue) * 0.1;
const domainMin = Math.floor(Math.max(0, minValue - padding));
const domainMax = Math.ceil(maxValue + padding);
@@ -444,21 +513,25 @@ const DashboardLineChart = ({
const range = domainMax - domainMin;
const step = range / 4;
return [
// Use Set to ensure unique values
const tickSet = new Set([
domainMin,
Math.round(domainMin + step),
Math.round(domainMin + step * 2),
Math.round(domainMin + step * 3),
domainMax,
];
]);
return Array.from(tickSet).sort((a, b) => a - b);
})()}
tickFormatter={(value) => formatNumber(Number(value))}
/>
<Tooltip
contentStyle={{
backgroundColor: '#1f2937',
border: 'none',
borderRadius: '8px',
padding: '8px 12px',
padding: '12px 12px',
color: 'white',
}}
labelStyle={{ color: 'white', marginBottom: '4px' }}
@@ -466,8 +539,8 @@ const DashboardLineChart = ({
labelFormatter={(value) => `Week ${value}`}
content={(props) => {
return (
<div className='flex flex-col gap-2 rounded-lg bg-neutral-950 p-4 text-white'>
<p className='text-neutral-300 text-xs font-semibold text-start'>
<div className='flex flex-col gap-1.5 rounded-lg bg-neutral-950 p-4 text-white'>
<p className='text-white/50 text-xs font-semibold text-start'>
{analysisMode === 'OVERVIEW'
? selectedKandang
? selectedKandang.label || 'Overview Performance'
@@ -506,12 +579,12 @@ const DashboardLineChart = ({
return (
<li
key={item.name}
className='flex w-full justify-between items-center flex-row gap-6 p-0'
key={`${item.name}-${index}`}
className='flex w-full justify-between items-center flex-row gap-y-1.5 gap-x-3 p-0'
>
<span className='flex flex-row gap-1 items-center'>
<span className='flex flex-row gap-1.5 items-center'>
<div
className='h-4 w-4 m-0 rounded-md'
className='h-5 w-5 m-0 rounded'
style={{
backgroundColor: color,
}}
@@ -526,7 +599,7 @@ const DashboardLineChart = ({
);
})}
</ul>
<p className='text-neutral-300 text-xs text-start'>
<p className='text-white/50 text-xs text-start'>
Week {props.label}
</p>
</div>
@@ -598,7 +671,7 @@ const DashboardLineChart = ({
return (
<Line
key={series.id}
key={`${series.id}--${index}`}
type='monotone'
dataKey={dataKey}
name={series.label}
@@ -649,22 +722,18 @@ const DashboardLineChart = ({
return (
<div className='absolute inset-x-0 inset-y-15 z-10 flex flex-col items-center justify-center rounded-lg'>
{/* Chart icon */}
<div className='w-12 h-12 bg-blue-500 rounded-xl flex items-center justify-center mb-4'>
<Icon
icon='heroicons:chart-bar'
className='text-white'
width={24}
height={24}
/>
</div>
{/* Empty state text */}
<h3 className='text-gray-900 font-semibold text-base mb-2'>
Data Not Yet Available
</h3>
<p className='text-gray-500 text-sm text-center max-w-xs'>
Please change your filters to get the data.
</p>
<DataStateSkeleton
icon={
<Icon
icon='heroicons:chart-bar'
className='text-white'
width={20}
height={20}
/>
}
title='Data Not Yet Available'
description='Please change your filters to get the data.'
/>
</div>
);
}
@@ -21,7 +21,7 @@ const CARD_CONFIG = [
key: 'Avg. Selling Price',
icon: 'heroicons:document-currency-dollar',
alertColor: 'success' as const,
suffix: ' /Kg',
suffix: ' /Kg Telur',
prefix: '',
},
{
@@ -48,7 +48,7 @@ const DashboardStats = ({ data }: DashboardStatsProps) => {
icon: isPositive
? 'heroicons:arrow-trending-up'
: 'heroicons:arrow-trending-down',
color: isPositive ? 'text-success' : 'text-error',
color: isPositive ? 'text-[#008000]' : 'text-[#FF3A3A]',
value: Math.abs(percent),
};
};
@@ -60,14 +60,16 @@ const DashboardStats = ({ data }: DashboardStatsProps) => {
{prefix}
{formatNumber(value)}
{suffix && (
<span className='text-sm font-normal text-neutral-500'>{suffix}</span>
<span className='text-sm font-normal text-base-content/50'>
{suffix}
</span>
)}
</>
);
};
return (
<div className='grid sm:grid-cols-2 xl:grid-cols-4 gap-6'>
<div className='grid sm:grid-cols-2 xl:grid-cols-4 gap-3'>
{CARD_CONFIG.map((config) => {
// Find matching data from API
const cardData = data.find((item) => item.label === config.key);
@@ -78,35 +80,41 @@ const DashboardStats = ({ data }: DashboardStatsProps) => {
<Card
key={config.key}
className={{
wrapper: 'w-full rounded-lg',
wrapper: 'w-full rounded-xl border border-base-content/10',
body: 'p-0',
wrapperContent:
'h-full flex flex-col items-between justify-between',
footer: 'mt-0!',
}}
variant='bordered'
footer={
<div className='flex flex-row justify-between px-4 pb-4'>
<div className='text-neutral-400 font-semibold text-sm'>
<div className='flex flex-row justify-between px-4 pb-4 max-h-12'>
<div className='text-base-content/50 font-semibold text-xs'>
From last month
</div>
<div className='text-neutral-400 font-semibold text-sm'>
<div className='text-base-content/50 font-semibold text-xs'>
Filter Required
</div>
</div>
}
>
<div className='flex flex-row items-center gap-4 px-4 pt-4'>
<Alert variant='soft' className='rounded-lg p-3 bg-neutral-100'>
<div className='flex flex-row items-center gap-3 px-4 py-4'>
<Alert
variant='soft'
className={`rounded-lg p-0 w-12.5 h-12.5 bg-[${config.alertColor}]/12 flex items-center justify-center`}
>
<Icon
icon={config.icon}
width={32}
height={32}
className='text-neutral-400'
width={24}
height={24}
className='text-base-content/50'
/>
</Alert>
<div>
<h3 className='text-neutral-400 font-semibold text-sm'>
<h3 className='text-base-content/50 font-semibold text-sm'>
{config.key}
</h3>
<p className='text-2xl font-semibold text-neutral-400'>
<p className='text-xl font-semibold text-base-content/50'>
********
</p>
</div>
@@ -121,17 +129,20 @@ const DashboardStats = ({ data }: DashboardStatsProps) => {
<Card
key={config.key}
className={{
wrapper: 'w-full rounded-lg',
wrapper: 'w-full rounded-xl border border-base-content/10',
body: 'p-0',
wrapperContent:
'h-full flex flex-col items-between justify-between',
footer: 'mt-0!',
}}
variant='bordered'
footer={
<div className='flex flex-row justify-between px-4 pb-4'>
<div className='text-neutral-500 font-semibold text-sm'>
<div className='text-base-content/50 font-semibold text-xs'>
From last month
</div>
<div
className={`${trend.color} font-semibold flex flex-row items-center gap-1 text-sm`}
className={`${trend.color} font-semibold flex flex-row items-center gap-2 text-xs`}
>
<Icon icon={trend.icon} width={16} height={16} />
{trend.value}%
@@ -143,15 +154,15 @@ const DashboardStats = ({ data }: DashboardStatsProps) => {
<Alert
variant='soft'
color={config.alertColor}
className='rounded-lg p-3'
className={`rounded-lg p-3 bg-[${config.alertColor}]/12 flex items-center justify-center`}
>
<Icon icon={config.icon} width={32} height={32} />
<Icon icon={config.icon} width={24} height={24} />
</Alert>
<div>
<h3 className='text-neutral-500 font-semibold text-sm'>
<div className='space-y-1'>
<h3 className='text-base-content/50 font-semibold text-sm'>
{cardData.label}
</h3>
<p className='text-2xl font-semibold'>
<p className='text-xl font-semibold'>
{formatValue(cardData.value, config.prefix, config.suffix)}
</p>
</div>
@@ -17,12 +17,12 @@ import {
YAxis,
} from 'recharts';
type DashboardAllChartsProps = {
type DashboardExportChartsProps = {
data: Dashboard;
analysisMode: string;
};
export type DashboardAllChartsRef = {
export type DashboardExportChartsRef = {
getChartRefs: () => {
key: string;
ref: HTMLDivElement | null;
@@ -99,9 +99,9 @@ const chartTypeLabels: Record<keyof DashboardOverviewCharts, string> = {
deplesi: 'Deplesi',
};
const DashboardAllCharts = forwardRef<
DashboardAllChartsRef,
DashboardAllChartsProps
const DashboardExportCharts = forwardRef<
DashboardExportChartsRef,
DashboardExportChartsProps
>(({ data, analysisMode }, ref) => {
// Create refs for charts - use string keys for flexibility
const chartRefs = useRef<{
@@ -189,7 +189,8 @@ const DashboardAllCharts = forwardRef<
>
<Card
className={{
wrapper: 'w-full rounded-lg',
wrapper: 'w-full rounded-lg p-0',
body: 'p-4',
}}
variant='bordered'
>
@@ -338,6 +339,6 @@ const DashboardAllCharts = forwardRef<
);
});
DashboardAllCharts.displayName = 'DashboardAllCharts';
DashboardExportCharts.displayName = 'DashboardExportCharts';
export default DashboardAllCharts;
export default DashboardExportCharts;
@@ -0,0 +1,197 @@
import Alert from '@/components/Alert';
import Card from '@/components/Card';
import { formatNumber } from '@/lib/helper';
import { DashboardStatisticsData } from '@/types/api/dashboard/dashboard';
import { Icon } from '@iconify/react';
import { forwardRef, useImperativeHandle, useRef } from 'react';
interface DashboardStatsProps {
data: DashboardStatisticsData[];
}
export type DashboardExportStatsRef = {
getStatsRefs: () => {
key: string;
ref: HTMLDivElement | null;
label: string;
}[];
getContainerRef: () => HTMLDivElement | null;
};
// Konfigurasi untuk setiap kartu
const CARD_CONFIG = [
{
key: 'HPP Global',
icon: 'heroicons:banknotes',
alertColor: 'warning' as const,
suffix: ' /Kg',
prefix: 'RP ',
},
{
key: 'Avg. Selling Price',
icon: 'heroicons:document-currency-dollar',
alertColor: 'success' as const,
suffix: ' /Kg',
prefix: '',
},
{
key: 'FCR',
icon: 'heroicons:clipboard-document-list',
alertColor: 'info' as const,
suffix: '',
prefix: '',
},
{
key: 'Mortality',
icon: 'heroicons:exclamation-triangle',
alertColor: 'error' as const,
suffix: ' %',
prefix: '',
},
];
const DashboardExportStats = forwardRef<
DashboardExportStatsRef,
DashboardStatsProps
>(({ data }, ref) => {
const containerRef = useRef<HTMLDivElement>(null);
// Helper to get trend icon and color
const getTrendDisplay = (percent: number) => {
const isPositive = percent >= 0;
return {
icon: isPositive
? 'heroicons:arrow-trending-up'
: 'heroicons:arrow-trending-down',
color: isPositive ? 'text-[#008000]' : 'text-[#FF3A3A]',
value: Math.abs(percent),
};
};
// Helper to format value
const formatValue = (value: number, prefix: string, suffix: string) => {
return (
<>
{prefix}
{formatNumber(value)}
{suffix && (
<span className='text-sm font-normal text-base-content/50'>
{suffix}
</span>
)}
</>
);
};
// Expose container ref through imperative handle
useImperativeHandle(ref, () => ({
getStatsRefs: () => [],
getContainerRef: () => containerRef.current,
}));
return (
<div ref={containerRef} className='grid grid-cols-4 gap-3'>
{CARD_CONFIG.map((config) => {
// Find matching data from API
const cardData = data.find((item) => item.label === config.key);
if (!cardData) {
// Show placeholder card for missing data (FCR & Mortality)
return (
<Card
key={config.key}
className={{
wrapper: 'w-full rounded-lg',
body: 'p-0',
wrapperContent:
'h-full flex flex-col items-between justify-between',
footer: 'mt-0!',
}}
variant='bordered'
footer={
<div className='flex flex-row justify-between px-4 pb-4 max-h-12'>
<div className='text-base-content/50 font-semibold text-xs'>
From last month
</div>
<div className='text-base-content/50 font-semibold text-xs'>
Filter Required
</div>
</div>
}
>
<div className='flex flex-row items-center gap-3 px-4 pt-4'>
<Alert
variant='soft'
className={`rounded-lg p-0 w-12.5 h-12.5 bg-[${config.alertColor}]/12 flex items-center justify-center`}
>
<Icon
icon={config.icon}
width={24}
height={24}
className='text-base-content/50'
/>
</Alert>
<div>
<h3 className='text-base-content/50 font-semibold text-sm'>
{config.key}
</h3>
<p className='text-xl font-semibold text-base-content/50'>
********
</p>
</div>
</div>
</Card>
);
}
const trend = getTrendDisplay(cardData.percent_last_month);
return (
<Card
key={config.key}
className={{
wrapper: 'w-full rounded-lg border border-base-content/10',
body: 'p-0',
wrapperContent:
'h-full flex flex-col items-between justify-between',
footer: 'mt-0!',
}}
variant='bordered'
footer={
<div className='flex flex-row justify-between px-4 pb-4 max-h-12'>
<div className='text-base-content/50 font-semibold text-xs'>
From last month
</div>
<div
className={`${trend.color} font-semibold flex flex-row items-center gap-2 text-xs`}
>
<Icon icon={trend.icon} width={16} height={16} />
{trend.value}%
</div>
</div>
}
>
<div className='flex flex-row items-center gap-4 px-4 pt-4'>
<Alert
variant='soft'
color={config.alertColor}
className={`rounded-lg p-0 w-12.5 h-12.5 bg-[${config.alertColor}]/12 flex items-center justify-center`}
>
<Icon icon={config.icon} width={24} height={24} />
</Alert>
<div>
<h3 className='text-base-content/50 font-semibold text-sm'>
{cardData.label}
</h3>
<p className='text-xl font-semibold'>
{formatValue(cardData.value, config.prefix, config.suffix)}
</p>
</div>
</div>
</Card>
);
})}
</div>
);
});
DashboardExportStats.displayName = 'DashboardExportStats';
export default DashboardExportStats;
@@ -3,18 +3,19 @@ import { toPng } from 'html-to-image';
import toast from 'react-hot-toast';
import { formatDate } from '@/lib/helper';
import { DashboardFilterType } from '@/components/pages/dashboard/filter/DashboardProductionFilter.schema';
import { DashboardAllChartsRef } from '@/components/pages/dashboard/chart/DashboardAllCharts';
import { DashboardExportChartsRef } from '@/components/pages/dashboard/export/DashboardExportCharts';
import { DashboardExportStatsRef } from '@/components/pages/dashboard/export/DashboardExportStats';
interface DashboardPDFExportParams {
filterValues: DashboardFilterType;
statsRef: React.RefObject<HTMLDivElement | null>;
allChartsRef: React.RefObject<DashboardAllChartsRef | null>;
allStatsRef: React.RefObject<DashboardExportStatsRef | null>;
allChartsRef: React.RefObject<DashboardExportChartsRef | null>;
setExporting: (value: boolean) => void;
}
export const generateDashboardPDF = async ({
filterValues,
statsRef,
allStatsRef,
allChartsRef,
setExporting,
}: DashboardPDFExportParams): Promise<void> => {
@@ -168,31 +169,34 @@ export const generateDashboardPDF = async ({
yPosition += 10;
// Capture and add stats if available
if (statsRef.current) {
const statsImage = await toPng(statsRef.current, {
quality: 1,
pixelRatio: 2,
});
const statsImgProps = pdf.getImageProperties(statsImage);
const statsWidth = pageWidth - 2 * margin;
const statsHeight =
(statsImgProps.height * statsWidth) / statsImgProps.width;
if (allStatsRef.current) {
const statsContainer = allStatsRef.current.getContainerRef();
if (statsContainer) {
const statsImage = await toPng(statsContainer, {
quality: 1,
pixelRatio: 2,
});
const statsImgProps = pdf.getImageProperties(statsImage);
const statsWidth = pageWidth - 2 * margin;
const statsHeight =
(statsImgProps.height * statsWidth) / statsImgProps.width;
// Check if we need a new page
if (yPosition + statsHeight > pageHeight - margin) {
pdf.addPage();
yPosition = margin;
// Check if we need a new page
if (yPosition + statsHeight > pageHeight - margin) {
pdf.addPage();
yPosition = margin;
}
pdf.addImage(
statsImage,
'PNG',
margin,
yPosition,
statsWidth,
statsHeight
);
yPosition += statsHeight + 10;
}
pdf.addImage(
statsImage,
'PNG',
margin,
yPosition,
statsWidth,
statsHeight
);
yPosition += statsHeight + 10;
}
if (allChartsRef.current) {
@@ -1,96 +1,89 @@
import { Icon } from '@iconify/react';
import { DashboardMeta } from '@/types/api/dashboard/dashboard';
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
const DashboardLineChartSkeleton = ({ meta }: { meta?: DashboardMeta }) => {
return (
<div className='w-full bg-white rounded-lg shadow-sm border border-gray-200 p-6 relative'>
<div className='w-full bg-white rounded-xl border border-base-content/10 p-4 relative'>
{/* Header with title skeleton */}
<div className='text-lg font-semibold'>
<div className='text-base font-semibold'>
Performance{' '}
<Icon
icon='heroicons:information-circle'
width={20}
height={20}
className='inline text-neutral-500'
className='inline text-base-content/50'
/>
</div>
{/* Chart area with axes skeleton */}
<div className='relative mt-6'>
{/* Main chart container */}
<div className='flex gap-4'>
{/* Y-axis skeleton (left side) */}
<div className='flex flex-col justify-between py-4 space-y-4'>
{[1, 2, 3, 4, 5, 6].map((item) => (
<div
key={item}
className='h-4 w-12 bg-gray-100 rounded animate-pulse'
></div>
))}
</div>
{/* Chart content area */}
<div className='flex-1 relative'>
{/* Empty state centered in chart area */}
<div className='absolute inset-0 flex flex-col items-center justify-center pb-12'>
{!meta?.filters && (
<>
{/* Filter icon */}
<div className='w-12 h-12 bg-blue-500 rounded-xl flex items-center justify-center mb-4'>
<div className='relative mt-6 '>
{/* Chart content area */}
<div className='flex-1 relative'>
{/* Empty state centered in chart area */}
<div className='absolute inset-0 flex flex-col items-center justify-center pb-10'>
{!meta?.filters && (
<>
{/* Filter icon */}
<DataStateSkeleton
icon={
<Icon
icon='heroicons:funnel'
className='text-white'
width={24}
height={24}
width={20}
height={20}
/>
</div>
{/* Empty state text */}
<h3 className='text-gray-900 font-semibold text-base mb-2'>
No Filters Selected
</h3>
<p className='text-gray-500 text-sm text-center max-w-xs'>
Please choose filters to narrow down your results and make
your search easier.
</p>
</>
)}
{meta?.filters && (
<>
{/* Filter icon */}
<div className='w-12 h-12 bg-blue-500 rounded-xl flex items-center justify-center mb-4'>
}
title='No Filters Selected'
description='Please choose filters to narrow down your results and make your search easier.'
/>
</>
)}
{meta?.filters && (
<>
{/* Filter icon */}
<DataStateSkeleton
icon={
<Icon
icon='heroicons:chart-bar'
className='text-white'
width={24}
height={24}
width={20}
height={20}
/>
</div>
}
title='Data Not Yet Available'
description='Please change your filters to get the data.'
/>
</>
)}
</div>
{/* Empty state text */}
<h3 className='text-gray-900 font-semibold text-base mb-2'>
Data Not Yet Available
</h3>
<p className='text-gray-500 text-sm text-center max-w-xs'>
Please change your filters to get the data.
</p>
</>
)}
<div className='flex flex-row w-full items-center gap-4'>
<div className='flex-1 h-full min-w-4'>
<div className='h-28.5 w-4 bg-base-content/4 rounded'></div>
</div>
{/* Placeholder for chart height */}
<div className='h-64'></div>
{/* X-axis skeleton (bottom) */}
<div className='flex justify-between pt-4 border-t border-gray-100'>
{[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((item) => (
<div
key={item}
className='h-4 w-8 bg-gray-100 rounded animate-pulse'
></div>
<div className='w-full grid grid-cols-1 gap-y-13.25 mb-2'>
{[1, 2, 3, 4].map((item) => (
<div key={item} className='flex items-center w-full h-4 gap-4'>
<div className='h-4 w-6 bg-base-content/4 rounded'></div>
<div className='h-0.25 w-full bg-base-content/4 rounded'></div>
</div>
))}
</div>
</div>
{/* X-axis skeleton (bottom) */}
<div className='grid grid-cols-10 gap-15 mt-4 ps-13 sm:ps-26 overflow-x-hidden'>
{[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((item) => (
<div
key={item}
className='h-4 w-9.5 bg-base-content/4 rounded'
></div>
))}
</div>
<div className='flex justify-center pt-4 ps-13 sm:ps-26'>
<div className='h-4 w-28.5 bg-base-content/4 rounded'></div>
</div>
</div>
</div>
</div>
@@ -372,23 +372,6 @@ const ExpenseRequestForm = ({
onReset={formik.handleReset}
className='w-full mt-8 flex flex-col gap-6'
>
{expenseFormErrorMessage && (
<div role='alert' className='alert alert-error'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{expenseFormErrorMessage}</span>
</div>
)}
{formErrorList.length > 0 && (
<AlertErrorList
formErrorList={formErrorList}
onClose={() => setFormErrorList([])}
/>
)}
<div className='grid grid-cols-12 gap-4'>
<SelectInput
label='Kategori'
@@ -557,6 +540,24 @@ const ExpenseRequestForm = ({
/>
</div>
{expenseFormErrorMessage && (
<div role='alert' className='alert alert-error'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{expenseFormErrorMessage}</span>
</div>
)}
{formErrorList.length > 0 && (
<AlertErrorList
formErrorList={formErrorList}
onClose={() => setFormErrorList([])}
/>
)}
<div className='flex flex-row justify-between gap-2 flex-wrap'>
{type !== 'add' && (
<div className='flex flex-row justify-start gap-2'>
@@ -27,12 +27,12 @@ type MovementFormSchemaType = {
product_qty: number | string;
}[];
deliveries: {
delivery_cost?: number | string;
delivery_cost_per_item?: number | string;
delivery_cost?: number | string | null;
delivery_cost_per_item?: number | string | null;
document?: File | MovementDocument | null;
document_path?: string | null;
driver_name: string;
vehicle_plate: string;
driver_name?: string | null;
vehicle_plate?: string | null;
supplier?: {
value: number;
label: string;
@@ -59,12 +59,12 @@ export type ProductSchema = {
};
export type DeliverySchema = {
delivery_cost?: number | string;
delivery_cost_per_item?: number | string;
delivery_cost?: number | string | null;
delivery_cost_per_item?: number | string | null;
document?: File | MovementDocument | null;
document_path?: string | null;
driver_name: string;
vehicle_plate: string;
driver_name?: string | null;
vehicle_plate?: string | null;
supplier?: {
value: number;
label: string;
@@ -120,32 +120,64 @@ const DeliveryDocumentSchema = Yup.mixed<File | MovementDocument>()
const DeliveryObjectSchema: Yup.ObjectSchema<DeliverySchema> = Yup.object({
delivery_cost: Yup.number()
.transform((value) => (isNaN(value) || value === 0 ? undefined : value))
.min(1, 'Biaya minimal 1!')
.typeError('Biaya harus berupa angka!')
.test('one-of-cost-fields', 'Wajib diisi salah satu!', function (value) {
const { delivery_cost_per_item } = this.parent;
return (
(value !== undefined && value > 0) ||
(delivery_cost_per_item !== undefined && delivery_cost_per_item > 0)
);
.transform((value) =>
isNaN(value) || value === '' || value === null ? undefined : value
)
.when('supplier_id', {
is: (supplier_id: number | null | undefined) =>
supplier_id !== null && supplier_id !== undefined && supplier_id > 0,
then: (schema) =>
schema
.required('Biaya pengiriman wajib diisi!')
.min(1, 'Biaya minimal 1!')
.typeError('Biaya harus berupa angka!'),
otherwise: (schema) =>
schema
.optional()
.nullable()
.min(1, 'Biaya minimal 1!')
.typeError('Biaya harus berupa angka!'),
}),
delivery_cost_per_item: Yup.number()
.transform((value) => (isNaN(value) || value === 0 ? undefined : value))
.min(1, 'Biaya per item minimal 1!')
.typeError('Biaya per item harus berupa angka!')
.test('one-of-cost-fields', 'Wajib diisi salah satu!', function (value) {
const { delivery_cost } = this.parent;
return (
(value !== undefined && value > 0) ||
(delivery_cost !== undefined && delivery_cost > 0)
);
.transform((value) =>
isNaN(value) || value === '' || value === null ? undefined : value
)
.when('supplier_id', {
is: (supplier_id: number | null | undefined) =>
supplier_id !== null && supplier_id !== undefined && supplier_id > 0,
then: (schema) =>
schema
.required('Biaya per item wajib diisi!')
.min(1, 'Biaya per item minimal 1!')
.typeError('Biaya per item harus berupa angka!'),
otherwise: (schema) =>
schema
.optional()
.nullable()
.min(1, 'Biaya per item minimal 1!')
.typeError('Biaya per item harus berupa angka!'),
}),
document_path: Yup.string().nullable().optional(),
document_index: Yup.number().optional(),
document: DeliveryDocumentSchema,
driver_name: Yup.string().required('Nama sopir wajib diisi!'),
vehicle_plate: Yup.string().required('Plat nomor wajib diisi!'),
driver_name: Yup.string().when('supplier_id', {
is: (supplier_id: number | null | undefined) =>
supplier_id !== null && supplier_id !== undefined && supplier_id > 0,
then: (schema) =>
schema
.required('Nama sopir wajib diisi!')
.min(1, 'Nama sopir wajib diisi!'),
otherwise: (schema) => schema.optional().nullable(),
}),
vehicle_plate: Yup.string().when('supplier_id', {
is: (supplier_id: number | null | undefined) =>
supplier_id !== null && supplier_id !== undefined && supplier_id > 0,
then: (schema) =>
schema
.required('Plat nomor wajib diisi!')
.min(1, 'Plat nomor wajib diisi!'),
otherwise: (schema) => schema.optional().nullable(),
}),
supplier: Yup.object({
value: Yup.number().min(1).required(),
label: Yup.string().required(),
@@ -279,12 +311,12 @@ export const getMovementFormInitialValues = (
}) ?? [],
})) ?? [
{
delivery_cost: undefined,
delivery_cost_per_item: undefined,
delivery_cost: null,
delivery_cost_per_item: null,
document: null,
document_path: null,
driver_name: '',
vehicle_plate: '',
driver_name: null,
vehicle_plate: null,
supplier: null,
supplier_id: 0,
products: [
@@ -86,6 +86,15 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
}
// ===== USE SELECT HOOKS =====
const {
setInputValue: setSourceWarehouseSelectInputValue,
isLoadingOptions: isLoadingSourceWarehouses,
loadMore: loadMoreSourceWarehouses,
rawData: sourceWarehouses,
} = useSelect<Warehouse>(WarehouseApi.basePath, 'id', 'name', 'search', {
transfer_context: 'inventory_transfer',
});
const {
setInputValue: setWarehouseSelectInputValue,
isLoadingOptions: isLoadingWarehouses,
@@ -136,6 +145,25 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
return stockMap;
}, [allProductWarehouses]);
const sourceWarehouseOptions = useMemo(() => {
if (!isResponseSuccess(sourceWarehouses)) return [];
return (
sourceWarehouses?.data.map((w) => {
warehouseStockMap.get(w.id);
return {
value: w.id,
label: w.name,
area: w.area?.name,
location:
'type' in w && (w.type === 'LOKASI' || w.type === 'KANDANG')
? w.location?.name
: undefined,
};
}) || []
);
}, [sourceWarehouses, warehouseStockMap]);
const warehouseOptions = useMemo(() => {
if (!isResponseSuccess(warehouses)) return [];
@@ -228,19 +256,49 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
}
}
return {
delivery_cost: parseInt((d.delivery_cost || '').toString()) || 0,
delivery_cost_per_item:
parseInt((d.delivery_cost_per_item || '').toString()) || 0,
document_index: documentIndex,
driver_name: d.driver_name,
vehicle_plate: d.vehicle_plate,
supplier_id: d.supplier_id,
const deliveryObj: {
products: Array<{ product_id: number; product_qty: number }>;
delivery_cost?: number;
delivery_cost_per_item?: number;
document_index?: number;
driver_name?: string;
vehicle_plate?: string;
supplier_id?: number;
} = {
products: d.products.map((p) => ({
product_id: p.product_id,
product_qty: parseInt(p.product_qty.toString()) || 0,
})),
};
const deliveryCost = parseInt((d.delivery_cost || '').toString()) || 0;
if (deliveryCost > 0) {
deliveryObj.delivery_cost = deliveryCost;
}
const deliveryCostPerItem =
parseInt((d.delivery_cost_per_item || '').toString()) || 0;
if (deliveryCostPerItem > 0) {
deliveryObj.delivery_cost_per_item = deliveryCostPerItem;
}
if (documentIndex >= 0) {
deliveryObj.document_index = documentIndex;
}
if (d.driver_name) {
deliveryObj.driver_name = d.driver_name;
}
if (d.vehicle_plate) {
deliveryObj.vehicle_plate = d.vehicle_plate;
}
if (d.supplier_id) {
deliveryObj.supplier_id = d.supplier_id;
}
return deliveryObj;
});
const payload: CreateMovementPayload = {
@@ -844,32 +902,15 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
(warehouseId: number) => {
const stockInfo = warehouseStockMap.get(warehouseId);
if (!stockInfo) {
return (
<Badge
variant='ghost'
color='neutral'
size='sm'
className={{ badge: 'whitespace-nowrap font-semibold' }}
>
Kosong
</Badge>
);
return <span className='text-xs'>Kosong</span>;
}
const { productCount } = stockInfo;
let color: 'neutral' | 'success' | 'warning' = 'neutral';
if (productCount === 0) color = 'warning';
else if (productCount > 0) color = 'success';
return (
<Badge
variant='soft'
color={color}
size='sm'
className={{ badge: 'whitespace-nowrap font-semibold' }}
>
<span className='text-xs whitespace-nowrap'>
Tersedia {productCount} produk
</Badge>
</span>
);
},
[warehouseStockMap]
@@ -971,6 +1012,28 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
[formik.values.deliveries, formik.values.products, type]
);
const isSupplierSelected = useCallback(
(deliveryIdx: number) => {
const delivery = formik.values.deliveries?.[deliveryIdx];
return (
delivery &&
delivery.supplier_id !== null &&
delivery.supplier_id !== undefined &&
delivery.supplier_id > 0
);
},
[formik.values.deliveries]
);
const hasAnySupplierSelected = useMemo(() => {
return formik.values.deliveries?.some(
(delivery) =>
delivery.supplier_id !== null &&
delivery.supplier_id !== undefined &&
delivery.supplier_id > 0
);
}, [formik.values.deliveries]);
// ===== COMPUTED VALUES =====
const invalidQtyRows = useMemo(
() =>
@@ -1263,25 +1326,6 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
onReset={formik.handleReset}
className='w-full mt-8 flex flex-col gap-6'
>
{movementFormErrorMessage && (
<div role='alert' className='alert alert-error'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{movementFormErrorMessage}</span>
</div>
)}
{/* Error List Alert */}
{formErrorList.length > 0 && (
<AlertErrorList
formErrorList={formErrorList}
onClose={() => setFormErrorList([])}
/>
)}
{/* Top card - Movement details */}
<Card
title='Detail Movement'
@@ -1338,10 +1382,10 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
placeholder='Pilih gudang asal...'
value={formik.values.source_warehouse}
onChange={handleSourceWarehouseChange}
options={warehouseOptions}
onInputChange={setWarehouseSelectInputValue}
onMenuScrollToBottom={loadMoreWarehouses}
isLoading={isLoadingWarehouses}
options={sourceWarehouseOptions}
onInputChange={setSourceWarehouseSelectInputValue}
onMenuScrollToBottom={loadMoreSourceWarehouses}
isLoading={isLoadingSourceWarehouses}
isError={
formik.touched.source_warehouse_id &&
Boolean(formik.errors.source_warehouse_id)
@@ -1349,7 +1393,7 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
errorMessage={formik.errors.source_warehouse_id as string}
isDisabled={type === 'detail'}
isClearable
startAdornment={
inputPrefix={
formik.values.source_warehouse_id
? getWarehouseStockAdornment(
formik.values.source_warehouse_id
@@ -1407,7 +1451,7 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
errorMessage={formik.errors.destination_warehouse_id as string}
isDisabled={type === 'detail'}
isClearable
startAdornment={
inputPrefix={
formik.values.destination_warehouse_id
? getWarehouseStockAdornment(
formik.values.destination_warehouse_id
@@ -1665,43 +1709,61 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
<span className='text-error'>*</span>
</span>
</th>
<th>Supplier</th>
<th>
Supplier
{hasAnySupplierSelected && (
<span
className='tooltip tooltip-error tooltip-bottom z-9999'
data-tip='required jika supplier dipilih'
>
<span className='text-error'>*</span>
</span>
)}
</th>
<th>
Plat Nomor
<span
className='tooltip tooltip-error tooltip-bottom z-9999'
data-tip='required'
>
<span className='text-error'>*</span>
</span>
{hasAnySupplierSelected && (
<span
className='tooltip tooltip-error tooltip-bottom z-9999'
data-tip='required jika supplier dipilih'
>
<span className='text-error'>*</span>
</span>
)}
</th>
<th>Dokumen</th>
<th>
Biaya Pengiriman (Rp.)
<span
className='tooltip tooltip-error tooltip-bottom z-9999'
data-tip='required'
>
<span className='text-error'>*</span>
</span>
{hasAnySupplierSelected && (
<span
className='tooltip tooltip-error tooltip-bottom z-9999'
data-tip='required jika supplier dipilih'
>
<span className='text-error'>*</span>
</span>
)}
</th>
<th>
Biaya Per Item (Rp.)
<span
className='tooltip tooltip-error tooltip-bottom z-9999'
data-tip='required'
>
<span className='text-error'>*</span>
</span>
{hasAnySupplierSelected && (
<span
className='tooltip tooltip-error tooltip-bottom z-9999'
data-tip='required jika supplier dipilih'
>
<span className='text-error'>*</span>
</span>
)}
</th>
<th>
Nama Sopir
<span
className='tooltip tooltip-error tooltip-bottom z-9999'
data-tip='required'
>
<span className='text-error'>*</span>
</span>
{hasAnySupplierSelected && (
<span
className='tooltip tooltip-error tooltip-bottom z-9999'
data-tip='required jika supplier dipilih'
>
<span className='text-error'>*</span>
</span>
)}
</th>
{type !== 'detail' && <th>Aksi</th>}
</tr>
@@ -1799,10 +1861,9 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
</td>
<td>
<TextInput
required
name={`deliveries.${idx}.vehicle_plate`}
placeholder='Masukkan plat nomor...'
value={delivery.vehicle_plate}
value={delivery.vehicle_plate ?? ''}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
{...isRepeaterInputError(
@@ -1811,6 +1872,7 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
idx
)}
readOnly={type === 'detail'}
required={isSupplierSelected(idx)}
className={{
wrapper: 'w-full min-w-52 md:min-w-72 lg:min-w-80',
}}
@@ -1890,10 +1952,9 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
</td>
<td>
<NumberInput
required
name={`deliveries.${idx}.delivery_cost`}
placeholder='Masukkan biaya pengiriman...'
value={delivery.delivery_cost || ''}
value={delivery.delivery_cost ?? ''}
onChange={handleDeliveryCostChangeWrapper(idx)}
onBlur={formik.handleBlur}
decimalScale={0}
@@ -1907,6 +1968,7 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
idx
)}
readOnly={type === 'detail'}
required={isSupplierSelected(idx)}
className={{
wrapper: 'w-full min-w-52 md:min-w-72 lg:min-w-80',
}}
@@ -1914,10 +1976,9 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
</td>
<td>
<NumberInput
required
name={`deliveries.${idx}.delivery_cost_per_item`}
placeholder='Masukkan biaya per item...'
value={delivery.delivery_cost_per_item || ''}
value={delivery.delivery_cost_per_item ?? ''}
onChange={handleDeliveryCostPerItemChangeWrapper(idx)}
onBlur={formik.handleBlur}
decimalScale={0}
@@ -1931,6 +1992,7 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
idx
)}
readOnly={type === 'detail'}
required={isSupplierSelected(idx)}
className={{
wrapper: 'w-full min-w-52 md:min-w-72 lg:min-w-80',
}}
@@ -1938,10 +2000,9 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
</td>
<td>
<TextInput
required
name={`deliveries.${idx}.driver_name`}
placeholder='Masukkan nama sopir...'
value={delivery.driver_name}
value={delivery.driver_name ?? ''}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
{...isRepeaterInputError(
@@ -1950,6 +2011,7 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
idx
)}
readOnly={type === 'detail'}
required={isSupplierSelected(idx)}
className={{
wrapper: 'w-full min-w-52 md:min-w-72 lg:min-w-80',
}}
@@ -2007,6 +2069,27 @@ const MovementForm = ({ type = 'add', initialValues }: MovementFormProps) => {
)}
</Card>
<div className='w-full'>
{movementFormErrorMessage && (
<div role='alert' className='alert alert-error'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{movementFormErrorMessage}</span>
</div>
)}
{/* Error List Alert */}
{formErrorList.length > 0 && (
<AlertErrorList
formErrorList={formErrorList}
onClose={() => setFormErrorList([])}
/>
)}
</div>
{/* Action buttons */}
<div className='flex flex-row justify-between gap-2 flex-wrap'>
{type !== 'detail' && (
@@ -159,19 +159,6 @@ const ProductCategoryForm = ({
onReset={formik.handleReset}
className='w-full mt-8 flex flex-col gap-6'
>
{formErrorMessage && (
<div role='alert' className='alert alert-error'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{formErrorMessage}</span>
</div>
)}
<AlertErrorList formErrorList={formErrorList} onClose={close} />
<div className='flex flex-col gap-4'>
<TextInput
required
@@ -240,6 +227,21 @@ const ProductCategoryForm = ({
</div>
)}
<div className='w-full mb-4'>
{formErrorMessage && (
<div role='alert' className='alert alert-error'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{formErrorMessage}</span>
</div>
)}
<AlertErrorList formErrorList={formErrorList} onClose={close} />
</div>
{type !== 'detail' && (
<div
className={cn('flex flex-row justify-end gap-2', {
@@ -273,19 +273,6 @@ const ProductForm = ({ type = 'add', initialValues }: ProductFormProps) => {
onReset={formik.handleReset}
className='w-full mt-8 flex flex-col gap-6'
>
{productFormErrorMessage && (
<div role='alert' className='alert alert-error'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{productFormErrorMessage}</span>
</div>
)}
<AlertErrorList formErrorList={formErrorList} onClose={close} />
<div className='grid grid-cols-1 gap-4'>
<TextInput
required
@@ -627,6 +614,22 @@ const ProductForm = ({ type = 'add', initialValues }: ProductFormProps) => {
)}
</div>
)}
<div className='mb-4 w-full'>
{productFormErrorMessage && (
<div role='alert' className='alert alert-error'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{productFormErrorMessage}</span>
</div>
)}
<AlertErrorList formErrorList={formErrorList} onClose={close} />
</div>
{type !== 'detail' && (
<div
className={cn('flex flex-row justify-end gap-2', {
@@ -1125,16 +1125,9 @@ const RecordingForm = ({ type = 'add', initialValues }: RecordingFormProps) => {
}
return (
<Badge
variant='soft'
color={color}
size='sm'
className={{
badge: 'whitespace-nowrap font-semibold text-xs px-2',
}}
>
<span className={'whitespace-nowrap text-xs'}>
Periode {projectFlockKandangLookup.project_flock?.period}
</Badge>
</span>
);
}, [recordedProjectFlockKandangIds, projectFlockKandangLookup]);
@@ -1150,33 +1143,11 @@ const RecordingForm = ({ type = 'add', initialValues }: RecordingFormProps) => {
const hasOvkFlag = productWarehouse.product.flags?.includes('OVK');
if (hasPakanFlag) {
return (
<Badge
variant='soft'
color='info'
size='sm'
className={{
badge: 'whitespace-nowrap font-semibold text-xs px-2',
}}
>
PAKAN
</Badge>
);
return <span className={'whitespace-nowrap text-xs'}>PAKAN</span>;
}
if (hasOvkFlag) {
return (
<Badge
variant='soft'
color='secondary'
size='sm'
className={{
badge: 'whitespace-nowrap font-semibold text-xs px-2',
}}
>
OVK
</Badge>
);
return <span className={'whitespace-nowrap text-xs'}>OVK</span>;
}
return null;
@@ -1734,22 +1705,6 @@ const RecordingForm = ({ type = 'add', initialValues }: RecordingFormProps) => {
onSubmit={handleFormSubmit}
className='w-full mt-8 flex flex-col gap-6'
>
{recordingFormErrorMessage && (
<div role='alert' className='alert alert-error'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{recordingFormErrorMessage}</span>
</div>
)}
{/* Error List Alert */}
{formErrorList.length > 0 && (
<AlertErrorList formErrorList={formErrorList} onClose={close} />
)}
{/* Basic Info Card */}
{(type === 'add' || type === 'edit') && (
<Card
@@ -1842,7 +1797,7 @@ const RecordingForm = ({ type = 'add', initialValues }: RecordingFormProps) => {
Boolean(formik.errors.kandang_id)
}
errorMessage={formik.errors.kandang_id as string}
startAdornment={
inputPrefix={
projectFlockKandangLookup || projectFlockKandangDetail
? getProjectFlockBadgeAdornment()
: undefined
@@ -2474,7 +2429,7 @@ const RecordingForm = ({ type = 'add', initialValues }: RecordingFormProps) => {
!formik.values.project_flock_kandang_id
}
isClearable={type !== 'detail'}
startAdornment={
inputPrefix={
stock.product_warehouse_id
? getProductFlagBadgeAdornment(
stock.product_warehouse_id
@@ -3010,6 +2965,24 @@ const RecordingForm = ({ type = 'add', initialValues }: RecordingFormProps) => {
</Card>
)}
<div className='w-full'>
{recordingFormErrorMessage && (
<div role='alert' className='alert alert-error'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{recordingFormErrorMessage}</span>
</div>
)}
{/* Error List Alert */}
{formErrorList.length > 0 && (
<AlertErrorList formErrorList={formErrorList} onClose={close} />
)}
</div>
{/* Action buttons */}
<div className='flex flex-col sm:flex-row sm:justify-between gap-2'>
{/* Left side - Detail & Edit actions */}
@@ -98,6 +98,7 @@ const TransferToLayingFormModal = () => {
'search',
{
category: 'GROWING',
transfer_context: 'transfer_to_laying',
}
);
@@ -5,6 +5,7 @@ import UniformityGaugeChart from '@/components/pages/production/uniformity/chart
import UniformityBarChartSkeleton from '@/components/pages/production/uniformity/skeleton/UniformityBarChartSkeleton';
import UniformityGaugeChartSkeleton from '@/components/pages/production/uniformity/skeleton/UniformityGaugeChartSkeleton';
import { Uniformity, type ChartData } from '@/types/api/production/uniformity';
import { Icon } from '@iconify/react';
interface UniformityChartProps {
uniformityData?: Uniformity | null;
@@ -101,15 +102,26 @@ const UniformityChart = ({
const shouldShowEmptyState = !isFiltered;
return (
<section className='w-full grid grid-cols-1 xl:grid-cols-2 2xl:grid-cols-4 gap-4'>
<section className='w-full grid grid-cols-1 xl:grid-cols-2 2xl:grid-cols-[1fr_350px] gap-3'>
<Card
title='Performance Overview ⓘ'
variant='bordered'
className={{
wrapper: 'xl:col-span-1 2xl:col-span-3 w-full',
body: 'h-96',
wrapper:
'2xl:col-span-1 w-full rounded-xl border border-base-content/10',
body: 'h-96 p-4',
}}
>
<div className='flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-3'>
<div className='text-base font-semibold leading-7 flex gap-3 items-center'>
Performance Overview{' '}
<Icon
icon='heroicons:information-circle'
width={20}
height={20}
className='inline text-neutral-500'
/>
</div>
</div>
<div className='w-full h-full flex items-center justify-center'>
{shouldShowEmptyState ||
!uniformityData ||
@@ -120,26 +132,31 @@ const UniformityChart = ({
)}
</div>
</Card>
{shouldShowEmptyState || !uniformityData || !gaugeChartData ? (
<Card
variant='bordered'
title='Weekly Performance ⓘ'
className={{
wrapper: 'xl:col-span-1 2xl:col-span-1 w-full',
body: 'h-110',
}}
>
<Card
variant='bordered'
className={{
wrapper:
'2xl:col-span-1 w-full rounded-xl border border-base-content/10',
body:
shouldShowEmptyState || !uniformityData || !gaugeChartData
? 'h-110 p-4'
: 'p-4',
}}
>
<div className='flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-3'>
<div className='text-base font-semibold leading-7 flex gap-3 items-center'>
Weekly Performance{' '}
<Icon
icon='heroicons:information-circle'
width={20}
height={20}
className='inline text-neutral-500'
/>
</div>
</div>
{shouldShowEmptyState || !uniformityData || !gaugeChartData ? (
<UniformityGaugeChartSkeleton />
</Card>
) : (
<Card
variant='bordered'
title='Weekly Performance ⓘ'
className={{
wrapper: 'xl:col-span-1 2xl:col-span-1 w-full',
body: 'p-4',
}}
>
) : (
<UniformityGaugeChart
value={gaugeChartData.value}
label={gaugeChartData.label}
@@ -150,8 +167,8 @@ const UniformityChart = ({
hasPrevWeek={gaugeChartData.hasPrevWeek}
hasNextWeek={gaugeChartData.hasNextWeek}
/>
</Card>
)}
)}
</Card>
</section>
);
};
@@ -3,7 +3,7 @@
import { usePathname, useRouter } from 'next/navigation';
import Drawer from '@/components/Drawer';
import React, { ReactNode } from 'react';
import UniformityTable from '@/components/pages/production/uniformity/UniformityTable';
import Uniformity from '@/app/production/uniformity/page';
import { useUiStore } from '@/stores/ui/ui.store';
export default function UniformityPageWrapper({
@@ -40,8 +40,8 @@ export default function UniformityPageWrapper({
return (
<>
<div className='w-full p-4'>
<UniformityTable />
<div className='w-full'>
<Uniformity />
</div>
<Drawer
@@ -19,11 +19,11 @@ import { isResponseSuccess } from '@/lib/api-helper';
import { type BaseApiResponse } from '@/types/api/api-general';
import Table from '@/components/Table';
import Badge from '@/components/Badge';
import StatusBadge from '@/components/helper/StatusBadge';
import CheckboxInput from '@/components/input/CheckboxInput';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import toast from 'react-hot-toast';
import Card from '@/components/Card';
import UniformityTableSkeleton from '@/components/pages/production/uniformity/skeleton/UniformityTableSkeleton';
import RequirePermission from '@/components/helper/RequirePermission';
import { useUniformityStore } from '@/stores/uniformity/uniformity.store';
@@ -45,12 +45,11 @@ import {
getStatusColor,
getStatusIndicatorColor,
getStatusText,
getStatusBadgeColor,
} from '@/components/pages/production/uniformity/uniformity-utils';
import { generateUniformityPDF } from '@/components/pages/production/uniformity/export/UniformityExportPDF';
import { generateUniformityExcel } from '@/components/pages/production/uniformity/export/UniformityExportExcel';
import Dropdown from '@/components/Dropdown';
import Menu from '@/components/menu/Menu';
import MenuItem from '@/components/menu/MenuItem';
import { useFormik } from 'formik';
import {
UniformityTableFilterSchema,
@@ -113,12 +112,10 @@ const UniformityConfirmationPreview = ({
const columns: ColumnDef<DetailOptionType>[] = [
{
accessorKey: 'label',
header: 'Label',
cell: (props) => props.row.original.label,
},
{
accessorKey: 'value',
header: 'Value',
cell: (props) => {
const id = props.row.original.id;
@@ -819,7 +816,7 @@ const UniformityTable = () => {
);
return (
<div className='w-full flex flex-row justify-center'>
<div className='w-full flex flex-row xl:justify-center justify-end'>
<CheckboxInput
name='allRow'
checked={isAllSelected}
@@ -832,7 +829,7 @@ const UniformityTable = () => {
},
cell: ({ row }) => {
return (
<div>
<div className='w-full flex flex-row xl:justify-center justify-end'>
<CheckboxInput
name='row'
checked={row.getIsSelected()}
@@ -862,8 +859,11 @@ const UniformityTable = () => {
{
accessorKey: 'week',
header: 'Tanggal (Week)',
cell: (props) =>
`${formatDate(props.row.original.applied_at, 'DD MMM YYYY')} (${props.row.original.week})`,
cell: (props) => (
<span className='text-nowrap'>
{`${formatDate(props.row.original.applied_at, 'DD MMM YYYY')} (${props.row.original.week})`}
</span>
),
},
{
accessorKey: 'status',
@@ -872,20 +872,11 @@ const UniformityTable = () => {
const uniformity = props.row.original;
const status =
uniformity.latest_approval?.action ?? uniformity.status;
return (
<div className='w-full'>
<Badge
statusIndicator={true}
variant='soft'
className={{
badge: `rounded-xl w-full justify-start border border-gray-200 text-black ${getStatusColor(status)}`,
status: getStatusIndicatorColor(status),
}}
>
{getStatusText(status)}
</Badge>
</div>
);
const badgeColor = getStatusBadgeColor(status);
const statusText = getStatusText(status);
return <StatusBadge color={badgeColor} text={statusText} />;
},
},
{
@@ -900,334 +891,410 @@ const UniformityTable = () => {
[]
);
// ===== CALCULATE FILTER COUNT =====
const filterCount = useMemo(() => {
let count = 0;
if (filterStartDate && filterEndDate) {
count += 1;
}
if (filterLocation) {
count += 1;
}
if (filterProjectFlock) {
count += 1;
}
if (filterKandang) {
count += 1;
}
return count;
}, [
filterStartDate,
filterEndDate,
filterLocation,
filterProjectFlock,
filterKandang,
]);
const isFilterActive = filterCount > 0;
return (
<>
<section className='[&_button]:w-full [&_button]:sm:w-fit [&_button]:last:mt-2 [&_button]:last:sm:mt-0 sm:flex sm:justify-between grid grid-cols-1 sm:gap-0 gap-2'>
<div className='w-full sm:w-fit flex flex-col sm:flex-row self-start gap-2'>
<RequirePermission permissions='lti.production.uniformity.create'>
<Button color='primary' href='/production/uniformity/add'>
<Icon icon='ic:round-plus' width={18} height={18} />
Add Uniformity
</Button>
</RequirePermission>
</div>
<div className='sm:flex gap-2'>
<Button variant='outline' onClick={filterModal.openModal}>
<Icon icon='heroicons:funnel' width={18} height={18} />
Filter
</Button>
<Dropdown
trigger={
<Button variant='outline' isLoading={isAnyExportLoading}>
<Icon
icon='heroicons:cloud-arrow-down'
width={18}
height={18}
/>
Export
<div className='@container w-full'>
<div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
<div className='w-fit flex flex-row gap-3 flex-wrap'>
<RequirePermission permissions='lti.production.uniformity.create'>
<Button
href='/production/uniformity/add'
color='primary'
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
>
<Icon icon='heroicons:plus' width={20} height={20} />
Add Uniformity
</Button>
}
align='end'
>
<Menu>
<MenuItem title='Excel' onClick={handleExportExcel} />
<MenuItem title='PDF' onClick={handleExportPDF} />
</Menu>
</Dropdown>
</RequirePermission>
</div>
<div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
<Button
variant='outline'
color='none'
onClick={filterModal.openModal}
className={cn(
'px-3 py-2.5 gap-1.5 text-sm text-base-content/50 border border-base-content/10 rounded-xl shadow-button-soft transition-all',
{
'border-primary-gradient text-primary': isFilterActive,
}
)}
>
<Icon icon='heroicons:funnel' width={20} height={20} />
Filter
{isFilterActive && (
<Badge
className={{
badge:
'p-1.5 bg-[#FF3535] text-xs text-base-100 border border-base-300 rounded-lg',
}}
>
{filterCount}
</Badge>
)}
</Button>
<Dropdown
align='end'
direction='bottom'
className={{
content:
'mt-1 rounded-xl border border-base-content/5 shadow-sm overflow-hidden',
}}
trigger={
<Button
variant='outline'
color='none'
className='px-3 py-2.5 text-sm text-base-content/50 border border-base-content/10 rounded-xl shadow-button-soft'
>
<div className='flex flex-row items-center gap-1.5'>
<Icon
icon='heroicons:cloud-arrow-down'
width={20}
height={20}
/>
<span>Export</span>
<div className='w-px self-stretch bg-base-content/10' />
<Icon
icon='heroicons:chevron-down'
width={14}
height={14}
/>
</div>
</Button>
}
>
<Button
variant='ghost'
color='none'
onClick={handleExportExcel}
isLoading={isExcelExportLoading}
className='w-full p-3 justify-start text-sm text-base-content/50 font-semibold text-nowrap'
>
<Icon icon='heroicons:table-cells' width={20} height={20} />
Export to Excel
</Button>
<Button
variant='ghost'
color='none'
onClick={handleExportPDF}
isLoading={isPdfExportLoading}
className='w-full p-3 justify-start text-sm text-base-content/50 font-semibold text-nowrap hover:bg-base-content/5'
>
<Icon icon='heroicons:document-text' width={20} height={20} />
Export to PDF
</Button>
</Dropdown>
</div>
</div>
</section>
<div className='my-4 divider'></div>
<section className='p-3'>
<UniformityChartWrapper
uniformitySwrKey={uniformitySwrKey}
isFiltered={isSubmitted}
/>
</section>
</div>
<section>
<UniformityChartWrapper
uniformitySwrKey={uniformitySwrKey}
isFiltered={isSubmitted}
/>
</section>
<Card
variant='bordered'
<Table<Uniformity>
data={isResponseSuccess(uniformities) ? uniformities?.data : []}
columns={uniformityColumns}
pageSize={tableFilterState.pageSize}
page={isResponseSuccess(uniformities) ? uniformities?.meta?.page : 0}
totalItems={
isResponseSuccess(uniformities)
? uniformities?.meta?.total_results
: 0
}
onPageChange={setPage}
isLoading={isLoading}
sorting={sorting}
setSorting={setSorting}
rowSelection={rowSelection}
setRowSelection={setRowSelection}
className={{
wrapper: 'my-4 w-full relative',
containerClassName: cn('p-3 pt-0', {
'mb-20':
isResponseSuccess(uniformities) &&
uniformities?.data?.length === 0,
}),
headerColumnClassName:
'first:pl-3 first:pr-0 xl:first:pl-3 py-3 text-nowrap',
bodyColumnClassName:
'first:pl-3 first:pr-0 xl:first:pl-3 py-3 text-nowrap',
}}
emptyContent={<UniformityTableSkeleton />}
/>
<ConfirmationModal
ref={successModal.ref}
type='success'
iconPosition='left'
text='Data Berhasil Ditambahkan'
subtitleText='Data uniformity telah berhasil disimpan.'
closeOnBackdrop={false}
primaryButton={{
text: 'Ok',
color: 'primary',
onClick: handleSuccessModalClose,
}}
className={{
modalBox: 'rounded-2xl',
}}
>
<Table<Uniformity>
data={isResponseSuccess(uniformities) ? uniformities?.data : []}
columns={uniformityColumns}
pageSize={tableFilterState.pageSize}
page={isResponseSuccess(uniformities) ? uniformities?.meta?.page : 0}
totalItems={
isResponseSuccess(uniformities)
? uniformities?.meta?.total_results
: 0
}
onPageChange={setPage}
isLoading={isLoading}
sorting={sorting}
setSorting={setSorting}
rowSelection={rowSelection}
setRowSelection={setRowSelection}
className={{
containerClassName: cn({
'mb-20':
isResponseSuccess(uniformities) &&
uniformities?.data?.length === 0,
}),
tableWrapperClassName: 'overflow-x-auto min-h-full ',
tableClassName: 'font-inter w-full table-auto min-h-full!',
headerRowClassName: 'border-b border-b-gray-200',
headerColumnClassName:
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
bodyRowClassName: 'border-b border-b-gray-200',
bodyColumnClassName:
'px-6 py-3 last:flex last:flex-row last:justify-end',
}}
emptyContent={<UniformityTableSkeleton />}
/>
<ConfirmationModal
ref={successModal.ref}
type='success'
iconPosition='left'
text='Data Berhasil Ditambahkan'
subtitleText='Data uniformity telah berhasil disimpan.'
closeOnBackdrop={false}
primaryButton={{
text: 'Ok',
color: 'primary',
onClick: handleSuccessModalClose,
}}
className={{
modalBox: 'rounded-2xl',
}}
>
<div className='flex flex-col gap-4 mt-4'>
{createdUniformity ? (
<UniformityConfirmationPreview
uniformityDetail={createdUniformity}
/>
) : selectedRowIds.length === 1 ? (
<UniformityConfirmationPreview
uniformity={selectedUniformities[0]}
/>
) : (
<div className='text-center text-gray-500'>
{selectedRowIds.length} data dipilih
</div>
)}
</div>
</ConfirmationModal>
<ConfirmationModal
ref={singleDeleteModal.ref}
type='error'
iconPosition='left'
text={`Delete This Data?`}
subtitleText='Are you sure you want to delete this data?'
secondaryButton={{
text: 'Cancel',
}}
primaryButton={{
text: 'Delete',
color: 'primary',
isLoading: isDeleteLoading,
onClick: singleDeleteHandler,
}}
className={{
modalBox: 'rounded-2xl',
}}
>
<div className='flex flex-col gap-4 mt-4'>
<UniformityConfirmationPreview uniformity={selectedUniformity} />
</div>
</ConfirmationModal>
<ConfirmationModal
ref={singleApproveModal.ref}
type='success'
iconPosition='left'
text='Approve This Submission?'
subtitleText='Are you sure you want to approve this submission?'
secondaryButton={{
text: 'Cancel',
}}
primaryButton={{
text: 'Approve',
color: 'primary',
isLoading: isDeleteLoading,
onClick: singleApproveHandler,
}}
className={{
modalBox: 'rounded-2xl',
}}
>
<div className='flex flex-col gap-4 mt-4'>
{selectedRowIds.length === 1 ? (
<UniformityConfirmationPreview
uniformity={selectedUniformities[0]}
/>
) : (
<div className='text-center text-gray-500'>
{selectedRowIds.length} data dipilih
</div>
)}
</div>
</ConfirmationModal>
<ConfirmationModal
ref={bulkApproveModal.ref}
type='success'
iconPosition='left'
text={`Approve This Submission?`}
subtitleText={`Are you sure you want to approve this submission? (${selectedRowIds.length} data)`}
secondaryButton={{
text: 'Cancel',
}}
primaryButton={{
text: 'Approve',
color: 'primary',
isLoading: isBulkActionLoading,
onClick: bulkApproveHandler,
}}
className={{
modalBox: 'rounded-2xl',
}}
>
<div className='flex flex-col gap-4 mt-4'>
<UniformityConfirmationPreview uniformity={selectedUniformity} />
</div>
</ConfirmationModal>
<ConfirmationModal
ref={singleRejectModal.ref}
type='error'
iconPosition='left'
text='Reject This Submission?'
subtitleText='Are you sure you want to reject this submission?'
secondaryButton={{
text: 'Cancel',
}}
primaryButton={{
text: 'Reject',
color: 'primary',
isLoading: isDeleteLoading,
onClick: singleRejectHandler,
}}
className={{
modalBox: 'rounded-2xl',
}}
>
<div className='flex flex-col gap-4 mt-4'>
{selectedRowIds.length === 1 ? (
<UniformityConfirmationPreview
uniformity={selectedUniformities[0]}
/>
) : (
<div className='text-center text-gray-500'>
{selectedRowIds.length} data dipilih
</div>
)}
</div>
</ConfirmationModal>
<ConfirmationModal
ref={bulkRejectModal.ref}
type='error'
iconPosition='left'
text={`Apakah anda yakin ingin menolak ${selectedRowIds.length} data Uniformity yang dipilih?`}
secondaryButton={{
text: 'Cancel',
}}
primaryButton={{
text: 'Reject',
color: 'primary',
isLoading: isBulkActionLoading,
onClick: bulkRejectHandler,
}}
className={{
modalBox: 'rounded-2xl',
}}
>
<div className='flex flex-col gap-4 mt-4'>
{selectedRowIds.length === 1 ? (
<UniformityConfirmationPreview
uniformity={selectedUniformities[0]}
/>
) : (
<div className='text-center text-gray-500'>
{selectedRowIds.length} data dipilih
</div>
)}
</div>
</ConfirmationModal>
{/* Filter Modal */}
<Modal
ref={filterModal.ref}
className={{
modal: 'p-0',
modalBox: 'p-0 rounded-2xl xl:max-w-4/12 max-w-sm',
}}
>
<div className='space-y-6'>
{/* Modal Header */}
<div className='flex items-center justify-between gap-2 py-3 border-b border-gray-300 px-4'>
<div className='flex items-center gap-2 text-primary'>
<Icon icon='heroicons:funnel' width={20} height={20} />
<h3 className='font-semibold'>Filter Data</h3>
</div>
<Button
variant='link'
onClick={filterModal.closeModal}
className='text-gray-500 hover:text-gray-700 transition-colors cursor-pointer'
>
<Icon icon='heroicons:x-mark' width={20} height={20} />
</Button>
<div className='flex flex-col gap-4 mt-4'>
{createdUniformity ? (
<UniformityConfirmationPreview
uniformityDetail={createdUniformity}
/>
) : selectedRowIds.length === 1 ? (
<UniformityConfirmationPreview
uniformity={selectedUniformities[0]}
/>
) : (
<div className='text-center text-gray-500'>
{selectedRowIds.length} data dipilih
</div>
)}
</div>
</ConfirmationModal>
{/* Error List Alert */}
{formErrorList.length > 0 && (
<div className='w-full px-4'>
<AlertErrorList formErrorList={formErrorList} onClose={close} />
</div>
)}
<ConfirmationModal
ref={singleDeleteModal.ref}
type='error'
iconPosition='left'
text={`Delete This Data?`}
subtitleText='Are you sure you want to delete this data?'
secondaryButton={{
text: 'Cancel',
}}
primaryButton={{
text: 'Delete',
color: 'primary',
isLoading: isDeleteLoading,
onClick: singleDeleteHandler,
}}
className={{
modalBox: 'rounded-2xl',
}}
>
<div className='flex flex-col gap-4 mt-4'>
<UniformityConfirmationPreview uniformity={selectedUniformity} />
</div>
</ConfirmationModal>
<div className='space-y-4 px-4'>
<div className='grid grid-cols-1 sm:grid-cols-2 sm:gap-4'>
<div>
<ConfirmationModal
ref={singleApproveModal.ref}
type='success'
iconPosition='left'
text='Approve This Submission?'
subtitleText='Are you sure you want to approve this submission?'
secondaryButton={{
text: 'Cancel',
}}
primaryButton={{
text: 'Approve',
color: 'primary',
isLoading: isDeleteLoading,
onClick: singleApproveHandler,
}}
className={{
modalBox: 'rounded-2xl',
}}
>
<div className='flex flex-col gap-4 mt-4'>
{selectedRowIds.length === 1 ? (
<UniformityConfirmationPreview
uniformity={selectedUniformities[0]}
/>
) : (
<div className='text-center text-gray-500'>
{selectedRowIds.length} data dipilih
</div>
)}
</div>
</ConfirmationModal>
<ConfirmationModal
ref={bulkApproveModal.ref}
type='success'
iconPosition='left'
text={`Approve This Submission?`}
subtitleText={`Are you sure you want to approve this submission? (${selectedRowIds.length} data)`}
secondaryButton={{
text: 'Cancel',
}}
primaryButton={{
text: 'Approve',
color: 'primary',
isLoading: isBulkActionLoading,
onClick: bulkApproveHandler,
}}
className={{
modalBox: 'rounded-2xl',
}}
>
<div className='flex flex-col gap-4 mt-4'>
<UniformityConfirmationPreview uniformity={selectedUniformity} />
</div>
</ConfirmationModal>
<ConfirmationModal
ref={singleRejectModal.ref}
type='error'
iconPosition='left'
text='Reject This Submission?'
subtitleText='Are you sure you want to reject this submission?'
secondaryButton={{
text: 'Cancel',
}}
primaryButton={{
text: 'Reject',
color: 'primary',
isLoading: isDeleteLoading,
onClick: singleRejectHandler,
}}
className={{
modalBox: 'rounded-2xl',
}}
>
<div className='flex flex-col gap-4 mt-4'>
{selectedRowIds.length === 1 ? (
<UniformityConfirmationPreview
uniformity={selectedUniformities[0]}
/>
) : (
<div className='text-center text-gray-500'>
{selectedRowIds.length} data dipilih
</div>
)}
</div>
</ConfirmationModal>
<ConfirmationModal
ref={bulkRejectModal.ref}
type='error'
iconPosition='left'
text={`Reject This Submission?`}
subtitleText={`Are you sure you want to reject this submission? (${selectedRowIds.length} data)`}
secondaryButton={{
text: 'Cancel',
}}
primaryButton={{
text: 'Reject',
color: 'primary',
isLoading: isBulkActionLoading,
onClick: bulkRejectHandler,
}}
className={{
modalBox: 'rounded-2xl',
}}
>
<div className='flex flex-col gap-4 mt-4'>
{selectedRowIds.length === 1 ? (
<UniformityConfirmationPreview
uniformity={selectedUniformities[0]}
/>
) : (
<div className='text-center text-gray-500'>
{selectedRowIds.length} data dipilih
</div>
)}
</div>
</ConfirmationModal>
{/* Filter Modal */}
<Modal
ref={filterModal.ref}
className={{
modal: 'p-0',
modalBox: 'p-0 rounded-[0.875rem]',
}}
>
<div className='flex flex-col'>
{/* Modal Header */}
<div className='flex items-center justify-between p-4 border-b border-base-content/10'>
<div className='flex items-center gap-2 text-primary'>
<Icon icon='heroicons:funnel' width={20} height={20} />
<h3 className='font-medium text-sm'>Filter Data</h3>
</div>
<Button
variant='link'
onClick={filterModal.closeModal}
className='text-gray-500 hover:text-gray-700'
>
<Icon icon='heroicons:x-mark' width={20} height={20} />
</Button>
</div>
<form
className='flex flex-col'
onSubmit={handleFormSubmit}
onReset={handleResetFilters}
>
<div className='flex flex-col p-4 gap-1.5'>
{/* Rentang Waktu */}
<div>
<label className='flex text-xs items-center gap-2 py-2 font-semibold'>
Tanggal
</label>
<div className='flex items-center gap-2'>
<DateInput
required
label='Tanggal mulai'
name='start_date'
placeholder='Tanggal Mulai'
value={filterFormik.values.start_date}
errorMessage={filterFormik.errors.start_date}
onChange={handleFilterStartDateChange}
onBlur={filterFormik.handleBlur}
isError={
filterFormik.touched.start_date &&
Boolean(filterFormik.errors.start_date)
}
errorMessage={filterFormik.errors.start_date}
className={{ wrapper: 'w-full' }}
/>
</div>
<div>
<hr className='w-full max-w-3 h-px border-base-content/10'></hr>
<DateInput
required
label='Tanggal akhir'
name='end_date'
placeholder='Tanggal Akhir'
value={filterFormik.values.end_date}
errorMessage={filterFormik.errors.end_date}
onChange={handleFilterEndDateChange}
onBlur={filterFormik.handleBlur}
isError={
filterFormik.touched.end_date &&
Boolean(filterFormik.errors.end_date)
}
errorMessage={filterFormik.errors.end_date}
className={{ wrapper: 'w-full' }}
/>
</div>
</div>
@@ -1299,74 +1366,83 @@ const UniformityTable = () => {
className={{ wrapper: 'w-full' }}
/>
</div>
{formErrorList.length > 0 && (
<div className='w-full'>
<AlertErrorList
formErrorList={formErrorList}
onClose={close}
/>
</div>
)}
</div>
{/* Action Buttons */}
<div className='flex justify-between gap-4 py-4 mt-8 border-t border-gray-300 bg-gray-100'>
<div className='flex justify-between gap-4 p-4 border-t border-base-content/10 bg-gray-100'>
<Button
type='reset'
variant='soft'
className='ms-4 min-w-36 rounded-lg'
onClick={handleResetFilters}
className='rounded-lg p-3 bg-gray-100 border-gray-100 text-base-content/65 hover:bg-base-content/10'
>
Reset Filter
</Button>
<Button
className='me-4 min-w-36 rounded-lg'
onClick={handleApplyFilters}
type='submit'
className='min-w-40 text-sm p-3 text-white rounded-lg'
>
Apply Filter
</Button>
</div>
</div>
</Modal>
</form>
</div>
</Modal>
{/* Floating Actions Button */}
<FloatingActionsButton
actions={[
{
action: 'DETAIL',
icon: 'mdi:eye-outline',
label: 'Lihat Detail',
hidden: selectedRowIds.length !== 1,
onClick() {
router.push(
`/production/uniformity/detail?uniformityId=${selectedRowIds[0]}`
);
setRowSelection({});
},
permissions: 'lti.production.uniformity.detail',
{/* Floating Actions Button */}
<FloatingActionsButton
actions={[
{
action: 'DETAIL',
icon: 'mdi:eye-outline',
label: 'Lihat Detail',
hidden: selectedRowIds.length !== 1,
onClick() {
router.push(
`/production/uniformity/detail?uniformityId=${selectedRowIds[0]}`
);
setRowSelection({});
},
{
action: 'DELETE',
icon: 'mdi:delete-outline',
label: 'Delete',
hidden: selectedRowIds.length !== 1,
onClick: handleDelete,
permissions: 'lti.production.uniformity.delete',
},
]}
approvals={[
{
action: 'APPROVED',
icon: 'mdi:check-circle-outline',
label: 'Approve',
onClick: handleBulkApprove,
permissions: 'lti.production.uniformity.approve',
disabled: !canApproveReject,
},
{
action: 'REJECTED',
icon: 'mdi:close-circle-outline',
label: 'Reject',
onClick: handleBulkReject,
permissions: 'lti.production.uniformity.approve',
disabled: !canApproveReject,
},
]}
selectedRowIds={selectedRowIds}
onClose={handleCloseFab}
/>
</Card>
permissions: 'lti.production.uniformity.detail',
},
{
action: 'DELETE',
icon: 'mdi:delete-outline',
label: 'Delete',
hidden: selectedRowIds.length !== 1,
onClick: handleDelete,
permissions: 'lti.production.uniformity.delete',
},
]}
approvals={[
{
action: 'APPROVED',
icon: 'mdi:check-circle-outline',
label: 'Approve',
onClick: handleBulkApprove,
permissions: 'lti.production.uniformity.approve',
disabled: !canApproveReject,
},
{
action: 'REJECTED',
icon: 'mdi:close-circle-outline',
label: 'Reject',
onClick: handleBulkReject,
permissions: 'lti.production.uniformity.approve',
disabled: !canApproveReject,
},
]}
selectedRowIds={selectedRowIds}
onClose={handleCloseFab}
/>
</>
);
};
@@ -319,18 +319,19 @@ const UniformityDetail: React.FC<UniformityDetailProps> = ({
<DrawerHeader
leftIconHref='/production/uniformity'
subtitle={`Details`}
subtitleClassName='text-sm text-neutral'
subtitleClassName='text-sm font-medium text-base-content/50'
showDivider
/>
{/* Form Section */}
<div className='divider mt-3.5'></div>
<section className='w-full px-6 mb-6'>
<section className='w-full p-4'>
{initialValues ? (
<div className='flex flex-col gap-4'>
{/* Info Umum */}
<div className=''>
<p className='text-sm font-medium mb-5'>Informasi Umum</p>
<h2 className='text-base font-medium text-base-content/50 font-roboto mb-5'>
Informasi Umum
</h2>
<Table<DetailOptionType>
data={infoUmumTableData}
columns={columnsInfoUmum}
@@ -345,7 +346,9 @@ const UniformityDetail: React.FC<UniformityDetailProps> = ({
{/* Sampling and Range */}
{initialValues.sampling && (
<div className=''>
<p className='text-sm font-medium mb-5'>Sampling and Range</p>
<h2 className='text-base font-medium text-base-content/50 font-roboto mb-5'>
Sampling and Range
</h2>
<Table<DetailOptionType>
data={samplingTableData}
columns={columnsSampling}
@@ -361,7 +364,9 @@ const UniformityDetail: React.FC<UniformityDetailProps> = ({
{/* Result */}
{initialValues.result && (
<div className=''>
<p className='text-sm font-medium mb-5'>Result</p>
<h2 className='text-base font-medium text-base-content/50 font-roboto mb-5'>
Result
</h2>
<Table<DetailOptionType>
data={resultTableData}
columns={resultColumns}
@@ -10,11 +10,10 @@ import {
UniformityInfoUmum,
} from '@/types/api/production/uniformity';
import Table from '@/components/Table';
import Badge from '@/components/Badge';
import StatusBadge from '@/components/helper/StatusBadge';
import {
getWeightStatusColor,
getWeightStatusIndicatorColor,
getWeightStatusText,
getWeightStatusBadgeColor,
} from '@/components/pages/production/uniformity/uniformity-utils';
import { BodyWeightData } from '@/types/api/production/uniformity';
@@ -51,7 +50,7 @@ const UniformityDetailsPreview = ({
() => [
{
accessorKey: 'number',
header: 'No',
header: 'Number',
cell: (props) => props.row.original.number,
},
{
@@ -65,30 +64,12 @@ const UniformityDetailsPreview = ({
cell: (props) => {
const status = props.row.original.status;
return status ? (
<div className='w-full'>
<Badge
statusIndicator={true}
variant='soft'
className={{
badge: `rounded-xl w-full justify-start border border-gray-200 text-black ${getWeightStatusColor(status)}`,
status: getWeightStatusIndicatorColor(status),
}}
>
{getWeightStatusText(status)}
</Badge>
</div>
<StatusBadge
color={getWeightStatusBadgeColor(status)}
text={getWeightStatusText(status)}
/>
) : (
<Badge
statusIndicator={true}
variant='soft'
className={{
badge:
'rounded-xl w-full justify-start border border-gray-200 text-black bg-info/10',
status: 'bg-info',
}}
>
Unknown
</Badge>
<StatusBadge color='info' text='Unknown' />
);
},
},
@@ -102,7 +83,7 @@ const UniformityDetailsPreview = ({
<DrawerHeader
leftIcon=''
subtitle={info_umum?.file_name ?? 'Uniformity Details'}
subtitleClassName='text-sm text-neutral line-clamp-1'
subtitleClassName='text-sm font-medium text-base-content/50 line-clamp-1'
showDivider={false}
>
<button
@@ -114,8 +95,7 @@ const UniformityDetailsPreview = ({
</DrawerHeader>
{/* Form Section */}
<div className='divider mt-3.5'></div>
<section className='w-full px-6'>
<section className='w-full p-4'>
{info_umum ? (
<div className='flex flex-col gap-4'>
{/* Body Weight Details */}
@@ -493,43 +493,25 @@ const UniformityForm = ({
<>
<section className='w-full'>
<DrawerHeader
leftIcon={formType == 'add' ? 'mdi:close' : 'mdi:arrow-left'}
leftIconSize={24}
leftIcon={formType == 'add' ? 'heroicons:x-mark' : 'mdi:arrow-left'}
leftIconSize={20}
leftIconHref={
formType == 'add'
? '/production/uniformity'
: `/production/uniformity/detail`
}
leftIconClassName='hover:text-gray-400'
leftIconClassName='hover:text-base-content'
subtitle={formType == 'add' ? 'Add Uniformity' : 'Update Uniformity'}
subtitleClassName='text-sm text-neutral'
subtitleClassName='text-sm font-medium text-base-content/50'
showDivider
/>
<div className='divider mt-3'></div>
<section className='w-full px-6 mb-6'>
<h2 className='text-2xl font-semibold mb-6'>Informasi Umum</h2>
<form onSubmit={handleFormSubmit} className='flex flex-col gap-6'>
{uniformityFormErrorMessage && (
<div className='alert alert-error' role='alert'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{uniformityFormErrorMessage}</span>
</div>
)}
{/* Error List Alert */}
{formErrorList.length > 0 && (
<AlertErrorList
formErrorList={formErrorList}
onClose={() => setFormErrorList([])}
/>
)}
<section className='w-full p-4'>
<h2 className='text-base font-medium text-base-content/50 font-roboto'>
Informasi Umum
</h2>
<form onSubmit={handleFormSubmit} className='flex flex-col gap-1.5'>
<DateInput
required
label='Tanggal'
@@ -753,21 +735,45 @@ const UniformityForm = ({
)}
</div>
<div className='w-full'>
{uniformityFormErrorMessage && (
<div className='alert alert-error' role='alert'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{uniformityFormErrorMessage}</span>
</div>
)}
{/* Error List Alert */}
{formErrorList.length > 0 && (
<AlertErrorList
formErrorList={formErrorList}
onClose={() => setFormErrorList([])}
/>
)}
</div>
{!isNextStep && (
<RequirePermission permissions='lti.production.uniformity.create'>
<Button
type='submit'
color='primary'
className='w-full'
disabled={formik.isSubmitting}
>
{formik.isSubmitting ? (
<span className='loading loading-spinner'></span>
) : (
'Next'
)}
</Button>
</RequirePermission>
<>
<div className='border-t border-base-content/20 mt-3' />
<RequirePermission permissions='lti.production.uniformity.create'>
<Button
type='submit'
color='primary'
className='w-full mt-4'
disabled={formik.isSubmitting}
>
{formik.isSubmitting ? (
<span className='loading loading-spinner'></span>
) : (
'Next'
)}
</Button>
</RequirePermission>
</>
)}
</form>
</section>
@@ -50,7 +50,7 @@ const UniformityPreviewForm = () => {
() => [
{
accessorKey: 'number',
header: 'No',
header: 'Number',
cell: (props) => props.row.original.number,
},
{
@@ -68,19 +68,18 @@ const UniformityPreviewForm = () => {
<DrawerHeader
leftIcon=''
subtitle={uniformityFormData?.file_name || 'Add Body Weight'}
subtitleClassName='text-sm text-neutral line-clamp-1'
subtitleClassName='text-sm font-medium text-base-content/50 line-clamp-1'
showDivider={false}
>
<Button variant='link' className='p-0 text-error' onClick={handleClose}>
<Tooltip content='Hapus' position='left'>
<Icon icon='mdi:trash-can-outline' width={20} height={20} />
<Icon icon='heroicons-outline:trash' width={18} height={18} />
</Tooltip>
</Button>
</DrawerHeader>
{/* Form Section */}
<div className='divider mt-3.5'></div>
<section className='w-full px-6'>
<section className='w-full p-4'>
{verifyUniformityResult ? (
<div className='flex flex-col gap-4'>
<Table<BodyWeightData>
@@ -14,12 +14,11 @@ import { useRouter } from 'next/navigation';
import toast from 'react-hot-toast';
import { UniformityApi } from '@/services/api/uniformity';
import { isResponseError } from '@/lib/api-helper';
import Badge from '@/components/Badge';
import StatusBadge from '@/components/helper/StatusBadge';
import { formatNumber } from '@/lib/helper';
import {
getWeightStatusColor,
getWeightStatusIndicatorColor,
getWeightStatusText,
getWeightStatusBadgeColor,
} from '@/components/pages/production/uniformity/uniformity-utils';
import { DetailOptionType } from '@/types/api/production/uniformity';
import {
@@ -190,7 +189,7 @@ const UniformityResultForm = () => {
() => [
{
accessorKey: 'number',
header: 'No',
header: 'Number',
cell: (props) => props.row.original.number,
},
{
@@ -204,30 +203,12 @@ const UniformityResultForm = () => {
cell: (props) => {
const status = props.row.original.status;
return status ? (
<div className='w-full'>
<Badge
statusIndicator={true}
variant='soft'
className={{
badge: `rounded-xl w-full justify-start border border-gray-200 text-black ${getWeightStatusColor(status)}`,
status: getWeightStatusIndicatorColor(status),
}}
>
{getWeightStatusText(status)}
</Badge>
</div>
<StatusBadge
color={getWeightStatusBadgeColor(status)}
text={getWeightStatusText(status)}
/>
) : (
<Badge
statusIndicator={true}
variant='soft'
className={{
badge:
'rounded-xl w-full justify-start border border-gray-200 text-black bg-info/10',
status: 'bg-info',
}}
>
Unknown
</Badge>
<StatusBadge color='info' text='Unknown' />
);
},
},
@@ -241,23 +222,24 @@ const UniformityResultForm = () => {
<DrawerHeader
leftIcon=''
subtitle={uniformityFormData?.document_name || 'Uniformity Result'}
subtitleClassName='text-sm text-neutral line-clamp-1'
subtitleClassName='text-sm font-medium text-base-content/50 line-clamp-1'
showDivider={false}
>
<Button variant='link' className='p-0 text-error' onClick={handleClose}>
<Tooltip content='Hapus' position='left'>
<Icon icon='mdi:trash-can-outline' width={20} height={20} />
<Icon icon='heroicons-outline:trash' width={20} height={20} />
</Tooltip>
</Button>
</DrawerHeader>
{/* Form Section */}
<div className='divider mt-3.5'></div>
<section className='w-full px-6'>
<section className='w-full p-4'>
{verifyUniformityResult ? (
<div className='flex flex-col gap-4'>
<div className=''>
<p className='text-sm font-medium mb-5'>Sampling and Range</p>
<h2 className='text-base font-medium text-base-content/50 font-roboto mb-5'>
Sampling and Range
</h2>
<Table<DetailOptionType>
data={samplingTableData}
columns={columnsSampling}
@@ -270,7 +252,9 @@ const UniformityResultForm = () => {
</div>
<div className=''>
<p className='text-sm font-medium mb-5'>Result</p>
<h2 className='text-base font-medium text-base-content/50 font-roboto mb-5'>
Result
</h2>
<Table<DetailOptionType>
data={resultTableData}
columns={resultColumns}
@@ -1,4 +1,3 @@
import Button from '@/components/Button';
import { Icon } from '@iconify/react';
const LeftLegend = () => {
@@ -45,11 +44,11 @@ const ChartArea = () => {
))}
</div>
<div className='flex justify-between gap-2 sm:gap-4 md:gap-8 lg:gap-12 px-2 sm:px-4 py-2'>
<div className='flex justify-between gap-1 xs:gap-2 sm:gap-3 md:gap-4 lg:gap-6 px-1 xs:px-2 sm:px-3 md:px-4 py-2'>
{ranges.map((range) => (
<div
key={range}
className='skeleton h-3 w-8 sm:w-12 md:w-16 shrink-0'
className='skeleton h-3 w-6 xs:w-8 sm:w-10 md:w-12 flex-1 max-w-12 xs:max-w-14 sm:max-w-16'
/>
))}
</div>
@@ -65,28 +64,38 @@ const ChartArea = () => {
const EmptyState = () => {
return (
<>
<div className='absolute inset-0 flex flex-col items-center justify-center z-10 gap-2'>
<div className='border border-[#18181B]/25 rounded-2xl p-1 flex items-center justify-center my-2'>
<Button className='rounded-2xl border border-sky-500 bg-primary text-white'>
<Icon icon={'heroicons:funnel'} className='text-4xl text-whitd' />
</Button>
<div className='absolute inset-0 flex items-center justify-center z-10'>
<div className='flex flex-col items-center justify-center'>
{/* Filter icon */}
<div className='mb-2'>
<div className='w-12.5 h-12.5 bg-(--main-color-base-100,#FFFFFF) border border-base-content/10 rounded-[0.875rem] shadow-[0px_25px_50px_-12px_#00000040] flex items-center justify-center'>
<div className='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]'>
<Icon
icon='heroicons:funnel'
className='text-white'
width={20}
height={20}
/>
</div>
</div>
</div>
<span className='text-xl font-semibold text-[#18181B80] leading-5'>
{/* Empty state text */}
<h3 className='text-base-content/50 font-semibold text-sm mb-1'>
No Filters Selected
</span>
<span className='text-xs font-light text-[#18181B80] leading-4 text-center max-w-xs px-4'>
</h3>
<p className='text-base-content/50 text-xs text-center max-w-xs'>
Please choose filters to narrow down your results and make your search
easier.
</span>
</p>
</div>
</>
</div>
);
};
const UniformityBarChartSkeleton = () => {
return (
<div className='relative w-full h-full min-h-[300px] xl:min-h-[350px]'>
<div className='relative w-full h-full min-h-[270px] xl:min-h-[330px]'>
<div className='sm:flex hidden h-full gap-4'>
<LeftLegend />
<ChartArea />
@@ -1,4 +1,3 @@
import Button from '@/components/Button';
import { Icon } from '@iconify/react';
import React from 'react';
import { Cell, Pie, PieChart, ResponsiveContainer } from 'recharts';
@@ -55,22 +54,29 @@ const UniformityGaugeChartSkeleton: React.FC<
</Pie>
</PieChart>
</ResponsiveContainer>
<div className='absolute inset-x-0 top-24 flex flex-col items-center justify-center'>
<div className='border border-[#18181B]/25 rounded-2xl p-1 flex items-center justify-center mt-5'>
<Button className='rounded-2xl border border-sky-500 bg-primary text-white'>
<Icon
icon={'heroicons:funnel'}
className='text-4xl text-whitd'
/>
</Button>
<div className='absolute inset-x-0 top-24 flex flex-col items-center justify-center mt-4'>
{/* Filter icon */}
<div className='mb-2 mt-5'>
<div className='w-12.5 h-12.5 bg-(--main-color-base-100,#FFFFFF) border border-base-content/10 rounded-[0.875rem] shadow-[0px_25px_50px_-12px_#00000040] flex items-center justify-center'>
<div className='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]'>
<Icon
icon='heroicons:funnel'
className='text-white'
width={20}
height={20}
/>
</div>
</div>
</div>
<span className='text-lg font-semibold text-[#18181B80] leading-5 my-3'>
{/* Empty state text */}
<h3 className='text-base-content/50 font-semibold text-sm mb-1'>
No Filters Selected
</span>
<span className='text-xs font-light text-[#18181B80] leading-4 text-center max-w-xs px-4'>
</h3>
<p className='text-base-content/50 text-xs text-center max-w-xs'>
Please choose filters to narrow down your results and make your
search easier.
</span>
</p>
</div>
</div>
</div>
@@ -1,24 +1,30 @@
import Button from '@/components/Button';
import { Icon } from '@iconify/react';
const UniformityTableSkeleton = () => {
return (
<div className='flex flex-col items-center justify-center gap-2 my-20'>
<div className='border border-[#18181B]/25 rounded-2xl p-1 flex items-center justify-center'>
<Button className='rounded-2xl border border-sky-500 bg-primary text-white'>
<Icon
icon={'heroicons-outline:chart-bar'}
className='text-4xl text-whitd'
/>
</Button>
<div className='flex flex-col items-center justify-center my-20'>
{/* Document icon */}
<div className='mb-2'>
<div className='w-12.5 h-12.5 bg-(--main-color-base-100,#FFFFFF) border border-base-content/10 rounded-[0.875rem] shadow-[0px_25px_50px_-12px_#00000040] flex items-center justify-center'>
<div className='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]'>
<Icon
icon='heroicons:document-text'
className='text-white'
width={20}
height={20}
/>
</div>
</div>
</div>
<span className='text-xl font-semibold text-[#18181B80] leading-5'>
{/* Empty state text */}
<h3 className='text-base-content/50 font-semibold text-sm mb-1'>
No Data Available
</span>
<span className='text-xs font-light text-[#18181B80] leading-4 text-center max-w-xs px-4'>
</h3>
<p className='text-base-content/50 text-xs text-center max-w-xs'>
There is no uniformity data displayed. Enter uniformity check data to
get started.
</span>
</p>
</div>
);
};
@@ -25,6 +25,20 @@ export const getWeightStatusText = (status: string): string => {
return weightStatusTextMap[status] || status;
};
export const weightStatusBadgeColorMap: Record<
string,
'success' | 'error' | 'neutral' | 'info'
> = {
ideal: 'success',
outside: 'error',
};
export const getWeightStatusBadgeColor = (
status: string
): 'success' | 'error' | 'neutral' | 'info' => {
return weightStatusBadgeColorMap[status] || 'neutral';
};
export const statusColorMap: Record<string, string> = {
APPROVED: 'bg-[#00D39033]',
Disetujui: 'bg-[#00D39033]',
@@ -63,3 +77,29 @@ export const getStatusIndicatorColor = (status: string): string => {
export const getStatusText = (status: string): string => {
return statusTextMap[status] || status;
};
export const statusBadgeColorMap: Record<
string,
'success' | 'error' | 'neutral' | 'info'
> = {
APPROVED: 'success',
Disetujui: 'success',
approved: 'success',
disetujui: 'success',
REJECTED: 'error',
Ditolak: 'error',
rejected: 'error',
ditolak: 'error',
CREATED: 'neutral',
Pengajuan: 'neutral',
created: 'neutral',
pengajuan: 'neutral',
PENDING: 'neutral',
pending: 'neutral',
};
export const getStatusBadgeColor = (
status: string
): 'success' | 'error' | 'neutral' | 'info' => {
return statusBadgeColorMap[status] || 'neutral';
};
@@ -370,25 +370,6 @@ const PurchaseOrderAcceptApprovalForm = ({
? 'Konfirmasi Penerimaan Produk'
: 'Edit Penerimaan Produk'}
</h2>
{purchaseOrderFormErrorMessage && (
<div role='alert' className='alert alert-error'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{purchaseOrderFormErrorMessage}</span>
</div>
)}
{/* Error List Alert */}
{formErrorList.length > 0 && (
<AlertErrorList
formErrorList={formErrorList}
onClose={() => setFormErrorList([])}
/>
)}
<div className='overflow-x-auto'>
<table className='table'>
<thead>
@@ -709,6 +690,27 @@ const PurchaseOrderAcceptApprovalForm = ({
/>
</div>
<div className='w-full mt-4'>
{purchaseOrderFormErrorMessage && (
<div role='alert' className='alert alert-error'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{purchaseOrderFormErrorMessage}</span>
</div>
)}
{/* Error List Alert */}
{formErrorList.length > 0 && (
<AlertErrorList
formErrorList={formErrorList}
onClose={() => setFormErrorList([])}
/>
)}
</div>
{/* Action buttons */}
<div className='flex flex-row justify-between gap-2 flex-wrap mt-5'>
<div className='flex flex-row justify-end gap-2 w-full'>
@@ -688,25 +688,6 @@ const PurchaseOrderStaffApprovalForm = ({
? 'Konfirmasi Item Pembelian'
: 'Edit Item Pembelian'}
</h2>
{purchaseOrderFormErrorMessage && (
<div role='alert' className='alert alert-error'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{purchaseOrderFormErrorMessage}</span>
</div>
)}
{/* Error List Alert */}
{formErrorList.length > 0 && (
<AlertErrorList
formErrorList={formErrorList}
onClose={() => setFormErrorList([])}
/>
)}
<div className='overflow-x-auto'>
{groupedPurchaseItems.length > 0 ? (
<div>
@@ -1186,6 +1167,27 @@ const PurchaseOrderStaffApprovalForm = ({
/>
</div>
<div className='w-full mt-4'>
{purchaseOrderFormErrorMessage && (
<div role='alert' className='alert alert-error'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{purchaseOrderFormErrorMessage}</span>
</div>
)}
{/* Error List Alert */}
{formErrorList.length > 0 && (
<AlertErrorList
formErrorList={formErrorList}
onClose={() => setFormErrorList([])}
/>
)}
</div>
{/* Action buttons */}
<div className='flex flex-row justify-between gap-2 flex-wrap mt-5'>
<div className='flex flex-row justify-end gap-2 w-full'>
@@ -494,25 +494,6 @@ const PurchaseRequestForm = ({
onReset={formik.handleReset}
className='w-full mt-8 flex flex-col gap-6'
>
{purchaseRequestFormErrorMessage && (
<div role='alert' className='alert alert-error'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{purchaseRequestFormErrorMessage}</span>
</div>
)}
{/* Error List Alert */}
{formErrorList.length > 0 && (
<AlertErrorList
formErrorList={formErrorList}
onClose={() => setFormErrorList([])}
/>
)}
{/* Basic Info Card */}
<Card
title='Informasi Purchase Request'
@@ -912,6 +893,27 @@ const PurchaseRequestForm = ({
)}
</Card>
<div className='w-full mb-4'>
{purchaseRequestFormErrorMessage && (
<div role='alert' className='alert alert-error'>
<Icon
icon='material-symbols:error-outline'
width={24}
height={24}
/>
<span>{purchaseRequestFormErrorMessage}</span>
</div>
)}
{/* Error List Alert */}
{formErrorList.length > 0 && (
<AlertErrorList
formErrorList={formErrorList}
onClose={() => setFormErrorList([])}
/>
)}
</div>
{/* Action buttons */}
<div className='flex flex-row justify-between gap-2 flex-wrap'>
{type !== 'detail' && (
@@ -10,7 +10,13 @@ import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import Card from '@/components/Card';
import Collapse from '@/components/Collapse';
import { cn, formatCurrency, formatDate, formatNumber } from '@/lib/helper';
import {
cn,
formatCurrency,
formatDate,
formatNumber,
formatVechicleNumber,
} from '@/lib/helper';
import { isResponseSuccess } from '@/lib/api-helper';
import { DailyMarketingRow } from '@/types/api/report/marketing';
import { MarketingReportApi } from '@/services/api/report/marketing-report';
@@ -94,7 +100,9 @@ const DailyMarketingsTable = ({
accessorKey: 'vehicle_number',
header: 'No. Polisi',
cell: (props) => (
<span className='text-nowrap'>{props.row.original.vehicle_number}</span>
<span className='text-nowrap'>
{formatVechicleNumber(props.row.original.vehicle_number)}
</span>
),
},
{
@@ -1,28 +1,43 @@
'use client';
import { useState } from 'react';
import Tabs from '@/components/Tabs';
import CustomerPaymentTab from '@/components/pages/report/finance/tab/CustomerPaymentTab';
import DebtSupplierTab from '@/components/pages/report/finance/tab/DebtSupplierTab';
import { useFinanceTabStore } from '@/stores/finance-tab/finance-tab.store';
const FinanceTabs = () => {
const [activeTabId, setActiveTabId] = useState<string>('1');
const tabActions = useFinanceTabStore((state) => state.tabActions);
const tabs = [
{
id: '1',
label: 'Rekapitulasi Hutang Ke Supplier',
content: <DebtSupplierTab />,
content: <DebtSupplierTab tabId={'1'} />,
},
{
id: '2',
label: 'Kontrol Pembayaran Customer',
content: <CustomerPaymentTab />,
content: <CustomerPaymentTab tabId={'2'} />,
},
];
return (
<section className='w-full p-4'>
<Tabs tabs={tabs} variant='lifted' />
<section className='w-full'>
<Tabs
tabs={tabs}
variant='boxed'
activeTabId={activeTabId}
onTabChange={setActiveTabId}
className={{
tabHeaderWrapper:
'justify-between items-center p-3 border-b border-base-content/10',
tab: 'w-fit',
content: 'p-0 m-0',
}}
sideContent={tabActions[activeTabId] || null}
/>
</section>
);
};
@@ -281,16 +281,16 @@ const createPDFDocument = (params: DebtSupplierExportPDFParams) => {
<View style={[pdfStyles.tableCellHeader, { flex: 0.5 }]}>
<Text>No</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 1.5 }]}>
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
<Text>No. PR</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 1.5 }]}>
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
<Text>No. PO</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
<View style={[pdfStyles.tableCellHeader, { flex: 0.7 }]}>
<Text>Tgl Terima/Bayar</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
<View style={[pdfStyles.tableCellHeader, { flex: 0.7 }]}>
<Text>Tgl PO</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 0.6 }]}>
@@ -320,7 +320,12 @@ const createPDFDocument = (params: DebtSupplierExportPDFParams) => {
<View style={[pdfStyles.tableCellHeader, { flex: 1.2 }]}>
<Text>Status</Text>
</View>
<View style={[pdfStyles.tableCellHeader, { flex: 1 }]}>
<View
style={[
pdfStyles.tableCellHeader,
{ flex: 1, borderRight: 'none' },
]}
>
<Text>No. Perjalanan</Text>
</View>
</View>
@@ -330,16 +335,16 @@ const createPDFDocument = (params: DebtSupplierExportPDFParams) => {
<View style={[pdfStyles.tableCellNo, { flex: 0.5 }]}>
<Text></Text> {/* NO */}
</View>
<View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text></Text> {/* No. PR */}
</View>
<View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text></Text> {/* No. PO */}
</View>
<View style={[pdfStyles.tableCellCenter, { flex: 1 }]}>
<View style={[pdfStyles.tableCellCenter, { flex: 0.7 }]}>
<Text></Text> {/* Tgl Terima/Bayar */}
</View>
<View style={[pdfStyles.tableCellCenter, { flex: 1 }]}>
<View style={[pdfStyles.tableCellCenter, { flex: 0.7 }]}>
<Text></Text> {/* Tgl PO */}
</View>
<View style={[pdfStyles.tableCellCenter, { flex: 0.6 }]}>
@@ -381,8 +386,13 @@ const createPDFDocument = (params: DebtSupplierExportPDFParams) => {
<View style={[pdfStyles.tableCell, { flex: 1.2 }]}>
<Text></Text> {/* Status */}
</View>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text></Text> {/* No. Perjalanan */}
<View
style={[
pdfStyles.tableCell, // No. Perjalanan
{ flex: 1, borderRight: 'none' },
]}
>
<Text></Text>
</View>
</View>
@@ -400,13 +410,13 @@ const createPDFDocument = (params: DebtSupplierExportPDFParams) => {
<View style={[pdfStyles.tableCellNo, { flex: 0.5 }]}>
<Text>{index + 1}</Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text>{item.pr_number || '-'}</Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text>{item.po_number || '-'}</Text>
</View>
<View style={[pdfStyles.tableCellCenter, { flex: 1 }]}>
<View style={[pdfStyles.tableCellCenter, { flex: 0.7 }]}>
<Text>
{item.received_date
? item.received_date != '-'
@@ -415,7 +425,7 @@ const createPDFDocument = (params: DebtSupplierExportPDFParams) => {
: '-'}
</Text>
</View>
<View style={[pdfStyles.tableCellCenter, { flex: 1 }]}>
<View style={[pdfStyles.tableCellCenter, { flex: 0.7 }]}>
<Text>
{item.po_date
? item.po_date != '-'
@@ -526,7 +536,12 @@ const createPDFDocument = (params: DebtSupplierExportPDFParams) => {
<Text>-</Text>
)}
</View>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<View
style={[
pdfStyles.tableCell, // No. Perjalanan
{ flex: 1, borderRight: 'none' },
]}
>
<Text>{item.travel_number || '-'}</Text>
</View>
</View>
@@ -538,18 +553,18 @@ const createPDFDocument = (params: DebtSupplierExportPDFParams) => {
<View style={[pdfStyles.tableCellNo, { flex: 0.5 }]}>
<Text>Total</Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
<Text></Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1.5 }]}>
<Text></Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text></Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 1 }]}>
<Text></Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 0.7 }]}>
<Text></Text>
</View>
<View style={[pdfStyles.tableCell, { flex: 0.7 }]}>
<Text></Text>
</View>
<View style={[pdfStyles.tableCellCenter, { flex: 0.6 }]}>
<Text>{formatNumber(supplierReport.total.aging)} Hari</Text>
</View>
@@ -0,0 +1,37 @@
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
import Table from '@/components/Table';
import { CustomerPaymentRow } from '@/types/api/report/customer-payment';
import { ColumnDef } from '@tanstack/react-table';
const CustomerSupplierSkeleton = ({
columns,
icon,
title,
subtitle,
}: {
columns: ColumnDef<CustomerPaymentRow>[];
icon: React.ReactNode;
title: string;
subtitle: string;
}) => {
return (
<div className='relative size-full'>
<Table
data={[]}
columns={columns}
isLoading={true}
className={{
skeletonCellClassName: 'animate-none w-full h-5 bg-base-content/4',
headerColumnClassName: 'whitespace-nowrap',
containerClassName: 'mb-0 overflow-hidden',
tableWrapperClassName: 'overflow-hidden',
}}
/>
<div className='absolute inset-0 flex items-center justify-center'>
<DataStateSkeleton icon={icon} title={title} description={subtitle} />
</div>
</div>
);
};
export default CustomerSupplierSkeleton;
@@ -0,0 +1,38 @@
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
import Table from '@/components/Table';
import { DebtRow } from '@/types/api/report/debt-supplier';
import { Icon } from '@iconify/react';
import { ColumnDef } from '@tanstack/react-table';
const DebtSupplierSkeleton = ({
columns,
icon,
title,
subtitle,
}: {
columns: ColumnDef<DebtRow>[];
icon: React.ReactNode;
title: string;
subtitle: string;
}) => {
return (
<div className='relative size-full'>
<Table
data={[]}
columns={columns}
isLoading={true}
className={{
skeletonCellClassName: 'animate-none w-full h-5 bg-base-content/4',
headerColumnClassName: 'whitespace-nowrap',
containerClassName: 'mb-0 overflow-hidden',
tableWrapperClassName: 'overflow-hidden',
}}
/>
<div className='absolute inset-0 flex items-center justify-center'>
<DataStateSkeleton icon={icon} title={title} description={subtitle} />
</div>
</div>
);
};
export default DebtSupplierSkeleton;
@@ -1,4 +1,4 @@
import { useState, useMemo, useCallback } from 'react';
import { useState, useMemo, useCallback, useEffect } from 'react';
import useSWR from 'swr';
import { Icon } from '@iconify/react';
import Card from '@/components/Card';
@@ -11,9 +11,10 @@ import { FinanceApi } from '@/services/api/report/finance-report';
import { UserApi } from '@/services/api/user';
import Table from '@/components/Table';
import { ColumnDef } from '@tanstack/react-table';
import { formatCurrency, formatDate, formatNumber } from '@/lib/helper';
import { formatCurrency, formatDate, formatNumber, cn } from '@/lib/helper';
import {
CustomerPaymentReport,
CustomerPaymentRow,
CustomerPaymentSummary,
} from '@/types/api/report/customer-payment';
import { isResponseSuccess } from '@/lib/api-helper';
@@ -26,8 +27,14 @@ import { useModal } from '@/components/Modal';
import toast from 'react-hot-toast';
import { generateCustomerPaymentExcel } from '@/components/pages/report/finance/export/CustomerPaymentExportXLSX';
import { generateCustomerPaymentPDF } from '@/components/pages/report/finance/export/CustomerPaymentExportPDF';
import { useFinanceTabStore } from '@/stores/finance-tab/finance-tab.store';
import CustomerSupplierSkeleton from '@/components/pages/report/finance/skeleton/CustomerSupplierSkeleton';
const CustomerPaymentTab = () => {
interface CustomerPaymentTabProps {
tabId: string;
}
const CustomerPaymentTab = ({ tabId }: CustomerPaymentTabProps) => {
// ===== STATE MANAGEMENT =====
const [isPdfExportLoading, setIsPdfExportLoading] = useState(false);
const [isExcelExportLoading, setIsExcelExportLoading] = useState(false);
@@ -111,6 +118,10 @@ const CustomerPaymentTab = () => {
};
// ===== FILTER HANDLERS =====
const handleFilterModalOpen = useCallback(() => {
filterModal.openModal();
}, [filterModal]);
const handleResetFilters = useCallback(() => {
setIsSubmitted(false);
setFilterCustomer([]);
@@ -298,6 +309,92 @@ const CustomerPaymentTab = () => {
}
}, [customerPaymentExport]);
// ===== REGISTER TAB ACTIONS TO STORE =====
const setTabActions = useFinanceTabStore((state) => state.setTabActions);
const clearTabActions = useFinanceTabStore((state) => state.clearTabActions);
useEffect(() => {
setTabActions(
tabId,
<div className='flex flex-row gap-3'>
<Button
variant='outline'
color='none'
onClick={handleFilterModalOpen}
className={cn(
'px-3 py-2.5',
'rounded-lg! font-semibold text-sm gap-1.5',
'text-sm text-base-content/50 border border-base-content/10 shadow-button-soft',
hasFilters && 'border-primary-gradient text-primary'
)}
>
<Icon icon='heroicons:funnel' width={18} height={18} />
Filter
{hasFilters && (
<span className='w-5 h-5 text-white bg-[#FF3535] rounded-lg border border-base-300 flex items-center justify-center text-xs'>
{activeFiltersCount}
</span>
)}
</Button>
<Dropdown
trigger={
<Button
variant='outline'
color='none'
isLoading={isAnyExportLoading}
className={cn(
'px-3 py-2.5',
'rounded-lg font-semibold text-sm gap-1.5',
'text-sm text-base-content/50 border border-base-content/10 shadow-button-soft'
)}
>
<Icon icon='heroicons:cloud-arrow-down' width={20} height={20} />
Export
<div className='w-6.5 h-5 flex items-center justify-center border-l border-base-content/10'>
<Icon width={14} height={14} icon='heroicons:chevron-down' />
</div>
</Button>
}
align='end'
className={{
content:
'mt-1 p-0 w-full shadow-button-soft border border-base-content/10 rounded-lg',
}}
>
<Menu className='p-0 w-full'>
<MenuItem
className='text-sm p-3'
title='Excel'
onClick={handleExportExcel}
/>
<MenuItem
className='text-sm p-3'
title='PDF'
onClick={handleExportPdf}
/>
</Menu>
</Dropdown>
</div>
);
}, [
tabId,
hasFilters,
activeFiltersCount,
isAnyExportLoading,
handleExportExcel,
handleExportPdf,
filterModal.open,
setTabActions,
]);
// Cleanup on unmount
useEffect(() => {
return () => {
clearTabActions(tabId);
};
}, [tabId, clearTabActions]);
const getTableColumns = (
summary: CustomerPaymentSummary
): ColumnDef<CustomerPaymentReport['rows'][0]>[] => {
@@ -552,192 +649,40 @@ const CustomerPaymentTab = () => {
};
return (
<div className='w-full p-0 sm:p-4'>
<Card
subtitle='Laporan > Kontrol Pembayaran Customer'
className={{ wrapper: 'w-full', body: 'p-1!' }}
>
<div className='mb-4 flex justify-end gap-2 [&_button]:px-4'>
<Button
variant='outline'
onClick={filterModal.openModal}
className={
hasFilters
? 'bg-linear-to-b from-[#0069E0]/40 to-white text-[#0069E0] rounded-lg'
: 'rounded-lg'
}
>
<Icon icon='heroicons:funnel' width={18} height={18} />
Filter
{hasFilters && (
<Badge
variant='default'
className={{
badge:
'rounded-lg px-1.5 py-2.5 text-xs font-semibold bg-error text-white',
}}
>
{activeFiltersCount}
</Badge>
)}
</Button>
<Dropdown
trigger={
<Button
variant='outline'
isLoading={isAnyExportLoading}
className='rounded-lg'
>
<Icon
icon='heroicons:cloud-arrow-down'
width={18}
height={18}
/>
Export
</Button>
}
align='end'
>
<Menu className={'w-full'}>
<MenuItem title='Excel' onClick={handleExportExcel} />
<MenuItem title='PDF' onClick={handleExportPdf} />
</Menu>
</Dropdown>
</div>
{/* Filter Modal */}
<Modal
ref={filterModal.ref}
className={{
modal: 'p-0',
modalBox: 'p-0 rounded-2xl xl:max-w-4/12 max-w-sm',
}}
>
<div className='space-y-6'>
{/* Modal Header */}
<div className='flex items-center justify-between gap-2 py-3 border-b border-gray-300 px-4'>
<div className='flex items-center gap-2 text-primary'>
<Icon icon='heroicons:funnel' width={20} height={20} />
<h3 className='font-semibold'>Filter Data</h3>
</div>
<Button
variant='link'
onClick={filterModal.closeModal}
className='text-gray-500 hover:text-gray-700 transition-colors cursor-pointer'
>
<Icon icon='heroicons:x-mark' width={20} height={20} />
</Button>
</div>
<div className='space-y-4 px-4'>
<div className='grid grid-cols-1 sm:grid-cols-2 sm:gap-4'>
<div>
<DateInput
label='Tanggal'
name='start_date'
value={filterStartDate}
onChange={(e) => {
setFilterStartDate(e.target.value);
}}
className={{ wrapper: 'w-full' }}
/>
</div>
<div>
<DateInput
label=' '
name='end_date'
value={filterEndDate}
onChange={(e) => {
setFilterEndDate(e.target.value);
}}
className={{ wrapper: 'w-full' }}
/>
</div>
</div>
<div>
<SelectInputCheckbox
label='Customer'
placeholder='Pilih Customer'
options={customerOptions}
value={filterCustomer}
onChange={(val) => {
setFilterCustomer(
Array.isArray(val) ? val : val ? [val] : []
);
}}
onInputChange={setCustomerInputValue}
isLoading={isLoadingCustomers}
isClearable
onMenuScrollToBottom={loadMoreCustomers}
className={{ wrapper: 'w-full' }}
/>
</div>
{/* TODO: Uncomment when BE is ready */}
{/* <div>
<SelectInputCheckbox
label='Sales'
placeholder='Pilih Sales'
options={salesOptions}
value={filterSales}
onChange={(val) => {
setFilterSales(Array.isArray(val) ? val : val ? [val] : []);
}}
onInputChange={setSalesInputValue}
isLoading={isLoadingSales}
isClearable
onMenuScrollToBottom={loadMoreSales}
className={{ wrapper: 'w-full' }}
/>
</div> */}
{/* TODO: Uncomment when BE is ready */}
{/* <div>
<SelectInput
label='Filter Berdasarkan'
placeholder='Pilih Filter Berdasarkan'
options={dataTypeOptions}
value={dataTypeOptions[0]}
isDisabled={true}
className={{ wrapper: 'w-full' }}
/>
</div> */}
</div>
{/* Action Buttons */}
<div className='flex justify-between gap-4 py-4 mt-8 border-t border-gray-300 bg-gray-100'>
<Button
variant='soft'
className='ms-4 min-w-36 rounded-lg'
onClick={handleResetFilters}
>
Reset Filter
</Button>
<Button
className='me-4 min-w-36 rounded-lg'
onClick={handleApplyFilters}
>
Apply Filter
</Button>
</div>
</div>
</Modal>
<>
<div className='w-full p-0 sm:p-3 flex flex-col gap-3'>
{!isSubmitted ? (
<div className='mt-6 text-center text-gray-500'>
Silakan klik tombol Filter untuk mengatur filter dan menampilkan
data.
</div>
<CustomerSupplierSkeleton
columns={getTableColumns({} as CustomerPaymentSummary)}
icon={
<Icon
icon='heroicons:funnel'
className='text-white'
width={20}
height={20}
/>
}
title='No Filters Selected'
subtitle='Please choose filters to narrow down your results and make your search easier.'
/>
) : isLoading ? (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
) : data.length === 0 ? (
<div className='mt-6 text-center text-gray-500'>
Tidak ada data yang dapat ditampilkan...
</div>
<CustomerSupplierSkeleton
columns={getTableColumns({} as CustomerPaymentSummary)}
icon={
<Icon
icon='heroicons:chart-bar'
className='text-white'
width={20}
height={20}
/>
}
title='Data Not Yet Available'
subtitle='Please change your filters to get the data.'
/>
) : (
data.map((customerReport) => {
const summary = customerReport.summary || {
@@ -757,15 +702,17 @@ const CustomerPaymentTab = () => {
title={customerReport.customer.name}
subtitle={`(${customerReport.customer.address})`}
className={{
wrapper: 'w-full rounded-2xl',
wrapper: 'w-full rounded-lg border-none',
body: 'p-0',
title:
'py-1.5 px-3 bg-primary text-white text-lg font-normal',
'px-2 py-1.5 font-normal text-sm bg-primary text-white',
subtitle:
'px-3 pb-1 bg-primary text-white text-sm font-normal',
'px-2 pb-1.5 bg-primary text-white text-xs font-normal',
collapsible: 'rounded-lg',
}}
variant='bordered'
collapsible={true}
defaultCollapsed={true}
>
<Table
data={[
@@ -779,7 +726,8 @@ const CustomerPaymentTab = () => {
renderFooter={customerReport.rows.length > 0}
className={{
containerClassName: 'w-full mb-0!',
tableWrapperClassName: 'overflow-x-auto',
tableWrapperClassName:
'overflow-x-auto rounded-tr-none rounded-tl-none',
tableClassName: 'w-full table-auto text-sm',
headerRowClassName: 'border-b border-b-gray-200 bg-gray-50',
headerColumnClassName:
@@ -799,8 +747,8 @@ const CustomerPaymentTab = () => {
if (row.index === 0) {
return (
<tr
className='hover:bg-gray-50 transition-colors border-b border-l border-r border-b-gray-200 border-l-gray-200 border-r-gray-200'
key={row.index}
className='hover:bg-gray-50 transition-colors border-b border-l border-r border-b-gray-200 border-l-gray-200 border-r-gray-200'
>
<td
className='px-4 py-3 text-xs text-gray-900 whitespace-nowrap'
@@ -830,8 +778,123 @@ const CustomerPaymentTab = () => {
);
})
)}
</Card>
</div>
</div>
{/* Filter Modal */}
<Modal
ref={filterModal.ref}
className={{
modal: 'p-0',
modalBox: 'p-0 rounded-[0.875rem] xl:max-w-4/12 max-w-sm',
}}
>
{/* Modal Header */}
<div className='flex items-center justify-between gap-2 border-b border-base-content/10 p-4'>
<div className='flex items-center gap-2 text-primary'>
<Icon icon='heroicons:funnel' width={20} height={20} />
<h3 className='font-medium text-sm'>Filter Data</h3>
</div>
<Button
variant='link'
onClick={filterModal.closeModal}
className='text-base-content/50 hover:text-base-content transition-colors cursor-pointer'
>
<Icon icon='heroicons:x-mark' width={20} height={20} />
</Button>
</div>
<div className='p-4 flex flex-col gap-1.5'>
<div>
<label className='block text-xs font-semibold text-base-content py-2'>
Tanggal
</label>
<div className='flex flex-row gap-1.5 items-center justify-between'>
<DateInput
name='start_date'
value={filterStartDate}
onChange={(e) => {
setFilterStartDate(e.target.value);
}}
className={{ wrapper: 'w-full' }}
isNestedModal
/>
<hr className='w-full max-w-3 h-px border-base-content/10' />
<DateInput
name='end_date'
value={filterEndDate}
onChange={(e) => {
setFilterEndDate(e.target.value);
}}
className={{ wrapper: 'w-full' }}
isNestedModal
/>
</div>
</div>
<SelectInputCheckbox
label='Customer'
placeholder='Pilih Customer'
options={customerOptions}
value={filterCustomer}
onChange={(val) => {
setFilterCustomer(Array.isArray(val) ? val : val ? [val] : []);
}}
onInputChange={setCustomerInputValue}
isLoading={isLoadingCustomers}
isClearable
onMenuScrollToBottom={loadMoreCustomers}
className={{ wrapper: 'w-full' }}
/>
{/* TODO: Uncomment when BE is ready */}
{/* <div>
<SelectInputCheckbox
label='Sales'
placeholder='Pilih Sales'
options={salesOptions}
value={filterSales}
onChange={(val) => {
setFilterSales(Array.isArray(val) ? val : val ? [val] : []);
}}
onInputChange={setSalesInputValue}
isLoading={isLoadingSales}
isClearable
onMenuScrollToBottom={loadMoreSales}
className={{ wrapper: 'w-full' }}
/>
</div> */}
{/* TODO: Uncomment when BE is ready */}
{/* <div>
<SelectInput
label='Filter Berdasarkan'
placeholder='Pilih Filter Berdasarkan'
options={dataTypeOptions}
value={dataTypeOptions[0]}
isDisabled={true}
className={{ wrapper: 'w-full' }}
/>
</div> */}
{/* Action Buttons */}
</div>
<div className='flex justify-between items-center gap-4 p-4 border-t border-base-content/10 bg-gray-50'>
<Button
variant='soft'
className='rounded-lg text-base-content/65 bg-transparent border-none hover:bg-base-content/10 hover:text-base-content/65 transition-colors px-3 py-2'
onClick={handleResetFilters}
>
Reset Filter
</Button>
<Button
className='min-w-40 text-sm rounded-lg py-3 text-white font-semibold'
onClick={handleApplyFilters}
>
Apply Filter
</Button>
</div>
</Modal>
</>
);
};
@@ -2,10 +2,7 @@ import Button from '@/components/Button';
import Card from '@/components/Card';
import Dropdown from '@/components/Dropdown';
import DateInput from '@/components/input/DateInput';
import SelectInput, {
OptionType,
useSelect,
} from '@/components/input/SelectInput';
import { OptionType, useSelect } from '@/components/input/SelectInput';
import Menu from '@/components/menu/Menu';
import MenuItem from '@/components/menu/MenuItem';
import Modal, { useModal } from '@/components/Modal';
@@ -22,7 +19,7 @@ import { generateDebtSupplierExcel } from '@/components/pages/report/finance/exp
import { generateDebtSupplierPDF } from '@/components/pages/report/finance/export/DebtSupllierExportPDF';
import { Icon } from '@iconify/react';
import { ColumnDef } from '@tanstack/react-table';
import { useCallback, useMemo, useState } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import toast from 'react-hot-toast';
import useSWR from 'swr';
import { DebtSupplierApi } from '@/services/api/report/debt-supplier';
@@ -32,11 +29,14 @@ import {
DebtSupplierFilterType,
} from '@/components/pages/report/finance/filter/DebtSupplierFilter';
import ButtonFilter from '@/components/helper/ButtonFilter';
import Badge from '@/components/Badge';
import { Color } from '@/types/theme';
import { Supplier } from '@/types/api/master-data/supplier';
import SelectInputCheckbox from '@/components/input/SelectInputCheckbox';
import SelectInputRadio from '@/components/input/SelectInputRadio';
import { useFinanceTabStore } from '@/stores/finance-tab/finance-tab.store';
import StatusBadge from '@/components/helper/StatusBadge';
import DebtSupplierSkeleton from '@/components/pages/report/finance/skeleton/DebtSupplierSkeleton';
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
const dueStatus: Record<string, Color> = {
'Sudah Jatuh Tempo': 'error',
@@ -60,22 +60,14 @@ const getPillBadge = (
? dueStatus[statusText] || 'neutral'
: paymentStatus[statusText] || 'neutral';
return (
<Badge
color={color as Color}
size='sm'
variant='soft'
className={{
badge: `py-2.5 px-2 font-medium text-base-content rounded-full border border-${color}`,
}}
statusIndicator
>
{statusText}
</Badge>
);
return <StatusBadge color={color as Color} text={statusText} />;
};
const DebtSupplierTab = () => {
interface DebtSupplierTabProps {
tabId: string;
}
const DebtSupplierTab = ({ tabId }: DebtSupplierTabProps) => {
// ===== STATE MANAGEMENT =====
const [isPdfExportLoading, setIsPdfExportLoading] = useState(false);
const [isExcelExportLoading, setIsExcelExportLoading] = useState(false);
@@ -271,7 +263,78 @@ const DebtSupplierTab = () => {
}
}, [debtSupplierExport]);
const getTableColumns = (supplier: DebtSupplier): ColumnDef<DebtRow>[] => [
// ===== REGISTER TAB ACTIONS TO STORE =====
const setTabActions = useFinanceTabStore((state) => state.setTabActions);
const clearTabActions = useFinanceTabStore((state) => state.clearTabActions);
useEffect(() => {
setTabActions(
tabId,
<div className='flex flex-row gap-3 '>
<ButtonFilter
values={formik.values}
onClick={handleFilterModalOpen}
variant='outline'
className='px-3 py-2.5'
/>
<Dropdown
trigger={
<Button
variant='outline'
color='none'
isLoading={isAnyExportLoading}
className={cn(
'px-3 py-2.5',
'rounded-lg font-semibold text-sm gap-1.5',
'text-sm text-base-content/50 border border-base-content/10 shadow-button-soft'
)}
>
<Icon icon='heroicons:cloud-arrow-down' width={20} height={20} />
Export
<div className='w-6.5 h-5 flex items-center justify-center border-l border-base-content/10'>
<Icon width={14} height={14} icon='heroicons:chevron-down' />
</div>
</Button>
}
align='end'
className={{
content:
'mt-1 p-0 w-full shadow-button-soft border border-base-content/10 rounded-lg',
}}
>
<Menu className='p-0 w-full'>
<MenuItem
className='text-sm p-3'
title='Excel'
onClick={handleExportExcel}
/>
<MenuItem
className='text-sm p-3'
title='PDF'
onClick={handleExportPdf}
/>
</Menu>
</Dropdown>
</div>
);
}, [
tabId,
formik.values,
isAnyExportLoading,
handleExportExcel,
handleExportPdf,
setTabActions,
]);
// Cleanup on unmount
useEffect(() => {
return () => {
clearTabActions(tabId);
};
}, [tabId, clearTabActions]);
const getTableColumns = (supplier?: DebtSupplier): ColumnDef<DebtRow>[] => [
{
id: 'no',
header: 'No',
@@ -337,8 +400,10 @@ const DebtSupplierTab = () => {
return <div className='text-center'>{formatNumber(value)} Hari</div>;
},
footer: () => {
const value = supplier.total.aging;
return <div className='text-center'>{formatNumber(value)} Hari</div>;
const value = supplier?.total.aging;
return (
<div className='text-center'>{formatNumber(value || 0)} Hari</div>
);
},
},
{
@@ -399,10 +464,10 @@ const DebtSupplierTab = () => {
);
},
footer: () => {
const value = supplier.total.total_price;
const value = supplier?.total.total_price;
return (
<div className={`text-right ${value < 0 ? 'text-red-500' : ''}`}>
{formatCurrency(value)}
<div className={`text-right ${value || 0 < 0 ? 'text-red-500' : ''}`}>
{formatCurrency(value || 0)}
</div>
);
},
@@ -421,10 +486,10 @@ const DebtSupplierTab = () => {
);
},
footer: () => {
const value = supplier.total.payment_price;
const value = supplier?.total.payment_price;
return (
<div className={`text-right ${value < 0 ? 'text-red-500' : ''}`}>
{formatCurrency(value)}
<div className={`text-right ${value || 0 < 0 ? 'text-red-500' : ''}`}>
{formatCurrency(value || 0)}
</div>
);
},
@@ -443,10 +508,10 @@ const DebtSupplierTab = () => {
);
},
footer: () => {
const value = supplier.total.debt_price;
const value = supplier?.total.debt_price;
return (
<div className={`text-right ${value < 0 ? 'text-red-500' : ''}`}>
{formatCurrency(value)}
<div className={`text-right ${value || 0 < 0 ? 'text-red-500' : ''}`}>
{formatCurrency(value || 0)}
</div>
);
},
@@ -478,52 +543,39 @@ const DebtSupplierTab = () => {
];
return (
<>
<div className='w-full p-0 sm:p-4 flex flex-col gap-4'>
<Card
subtitle='Laporan > Rekapitulasi Hutang ke Supplier'
className={{ wrapper: 'w-full', body: 'p-1!' }}
>
<div className='mb-4 flex justify-end gap-2 [&_button]:px-4'>
<ButtonFilter
values={formik.values}
onClick={handleFilterModalOpen}
variant='outline'
/>
<Dropdown
trigger={
<Button variant='outline' isLoading={isAnyExportLoading}>
<Icon
icon='heroicons:cloud-arrow-down'
width={18}
height={18}
/>
Export
</Button>
}
align='end'
>
<Menu>
<MenuItem title='Excel' onClick={handleExportExcel} />
<MenuItem title='PDF' onClick={handleExportPdf} />
</Menu>
</Dropdown>
</div>
</Card>
<div className='w-full p-0 sm:p-3 flex flex-col gap-3'>
{!isSubmitted ? (
<div className='mt-6 text-center text-gray-500'>
Silakan klik tombol Filter untuk mengatur filter dan menampilkan
data.
</div>
<DebtSupplierSkeleton
columns={getTableColumns()}
icon={
<Icon
icon='heroicons:funnel'
className='text-white'
width={20}
height={20}
/>
}
title='No Filters Selected'
subtitle='Please choose filters to narrow down your results and make your search easier.'
/>
) : isLoading ? (
<div className='w-full flex flex-row justify-center items-center p-4'>
<span className='loading loading-spinner loading-xl' />
</div>
) : data.length === 0 ? (
<div className='mt-6 text-center text-gray-500'>
Tidak ada data yang dapat ditampilkan...
</div>
<DebtSupplierSkeleton
columns={getTableColumns()}
icon={
<Icon
icon='heroicons:chart-bar'
className='text-white'
width={20}
height={20}
/>
}
title='Data Not Yet Available'
subtitle='Please change your filters to get the data.'
/>
) : (
data.map((supplierReport) => {
return (
@@ -531,10 +583,11 @@ const DebtSupplierTab = () => {
key={supplierReport.supplier.id}
title={supplierReport.supplier.name}
className={{
wrapper: 'w-full !rounded-lg',
body: 'p-0 rounded-lg',
wrapper: 'w-full rounded-lg border-none',
body: 'p-0',
title:
'ps-2 pt-1 pb-1 font-normal text-md bg-primary text-white',
'px-2 py-1.5 font-normal text-sm bg-primary text-white',
collapsible: 'rounded-lg',
}}
variant='bordered'
collapsible={true}
@@ -551,8 +604,9 @@ const DebtSupplierTab = () => {
pageSize={supplierReport.rows.length + 1}
renderFooter={supplierReport.rows.length > 0}
className={{
containerClassName: 'w-full',
tableWrapperClassName: 'overflow-x-auto',
containerClassName: 'w-full mb-0',
tableWrapperClassName:
'overflow-x-auto rounded-tr-none rounded-tl-none',
headerColumnClassName: cn(
TABLE_DEFAULT_STYLING.headerColumnClassName,
'whitespace-nowrap'
@@ -617,33 +671,34 @@ const DebtSupplierTab = () => {
ref={filterModal.ref}
className={{
modal: 'p-0',
modalBox: 'p-0 rounded-2xl xl:max-w-4/12 max-w-sm',
modalBox: 'p-0 rounded-[0.875rem] xl:max-w-4/12 max-w-sm',
}}
>
<form
className='space-y-6'
onSubmit={formik.handleSubmit}
onReset={formik.handleReset}
>
<form onSubmit={formik.handleSubmit} onReset={formik.handleReset}>
{/* Modal Header */}
<div className='flex items-center justify-between gap-2 py-3 border-b border-gray-300 px-4'>
<div className='flex items-center justify-between gap-2 border-b border-base-content/10 p-4'>
<div className='flex items-center gap-2 text-primary'>
<Icon icon='heroicons:funnel' width={20} height={20} />
<h3 className='font-semibold'>Filter Data</h3>
<h3 className='font-medium text-sm'>Filter Data</h3>
</div>
<Button
variant='link'
type='button'
onClick={filterModal.closeModal}
className='text-gray-500 hover:text-gray-700 transition-colors cursor-pointer'
className='text-base-content/50 hover:text-base-content transition-colors cursor-pointer'
>
<Icon icon='heroicons:x-mark' width={20} height={20} />
</Button>
</div>
<div className='space-y-4 px-4'>
<div className='grid grid-cols-1 sm:grid-cols-2 sm:gap-4'>
<div>
{/* Modal Body */}
<div className='p-4 flex flex-col gap-1.5'>
<div>
<label className='block text-xs font-semibold text-base-content py-2'>
Tanggal
</label>
<div className='flex flex-row gap-1.5 items-center justify-between'>
<DateInput
label='Tanggal'
name='startDate'
value={formik.values.startDate || ''}
onChange={(e) => {
@@ -654,12 +709,10 @@ const DebtSupplierTab = () => {
formik.touched.startDate && !!formik.errors.startDate
}
errorMessage={formik.errors.startDate}
isNestedModal
/>
</div>
<div className='mt-auto'>
<hr className='w-full max-w-3 h-px border-base-content/10'></hr>
<DateInput
label=' '
name='endDate'
value={formik.values.endDate || ''}
onChange={(e) => {
@@ -668,6 +721,7 @@ const DebtSupplierTab = () => {
className={{ wrapper: 'w-full' }}
isError={formik.touched.endDate && !!formik.errors.endDate}
errorMessage={formik.errors.endDate}
isNestedModal
/>
</div>
</div>
@@ -730,15 +784,19 @@ const DebtSupplierTab = () => {
</div>
{/* Action Buttons */}
<div className='flex justify-between gap-4 py-4 mt-8 border-t border-gray-300 bg-gray-100'>
<div className='flex justify-between items-center gap-4 p-4 border-t border-base-content/10 bg-gray-50'>
<Button
variant='soft'
className='ms-4 min-w-36 rounded-lg'
color='none'
className='rounded-lg text-base-content/65 bg-transparent border-none hover:bg-base-content/10 hover:text-base-content/65 transition-colors px-3 py-2'
type='reset'
>
Reset Filter
</Button>
<Button className='me-4 min-w-36 rounded-lg' type='submit'>
<Button
className='min-w-40 text-sm rounded-lg py-3 text-white font-semibold'
type='submit'
>
Apply Filter
</Button>
</div>
+25
View File
@@ -5,6 +5,7 @@ export const MAIN_DRAWER_LINKS: SidebarMenuItem[] = [
text: 'Dashboard',
link: '/dashboard',
icon: 'heroicons-outline:chart-bar-square',
permission: ['lti.dashboard.list'],
},
{
text: 'Daily Checklist',
@@ -114,11 +115,13 @@ export const MAIN_DRAWER_LINKS: SidebarMenuItem[] = [
text: 'Penjualan',
link: '/marketing',
icon: 'heroicons-outline:currency-dollar',
permission: ['lti.marketing.delivery_order.list'],
},
{
text: 'Keuangan',
link: '/finance',
icon: 'heroicons-outline:banknotes',
permission: ['lti.finance.transactions.list'],
},
{
text: 'Biaya',
@@ -136,26 +139,46 @@ export const MAIN_DRAWER_LINKS: SidebarMenuItem[] = [
text: 'Laporan',
link: '/report',
icon: 'mdi:chart-box-outline',
permission: [
'lti.repport.debtsupplier.list',
'lti.repport.customerpayment.list',
'lti.repport.purchasesupplier.list',
'lti.repport.expense.list',
'lti.repport.delivery.list',
'lti.repport.gethppperkandang.list',
'lti.repport.production_result.list',
],
submenu: [
{
text: 'Keuangan',
link: '/report/finance',
permission: [
'lti.repport.debtsupplier.list',
'lti.repport.customerpayment.list',
],
},
{
text: 'Logistik & Persediaan',
link: '/report/logistic-stock',
permission: ['lti.repport.purchasesupplier.list'],
},
{
text: 'Biaya Operasional',
link: '/report/expense',
permission: ['lti.repport.expense.list'],
},
{
text: 'Penjualan',
link: '/report/marketing',
permission: [
'lti.repport.delivery.list',
'lti.repport.gethppperkandang.list',
],
},
{
text: 'Hasil Produksi',
link: '/report/production-result',
permission: ['lti.repport.production_result.list'],
},
],
},
@@ -204,6 +227,7 @@ export const MAIN_DRAWER_LINKS: SidebarMenuItem[] = [
'lti.master.suppliers.list',
'lti.master.uoms.list',
'lti.master.warehouses.list',
'lti.master.production_standards.list',
],
submenu: [
{
@@ -274,6 +298,7 @@ export const MAIN_DRAWER_LINKS: SidebarMenuItem[] = [
{
text: 'Standar Produksi',
link: '/master-data/production-standard',
permission: ['lti.master.production_standards.list'],
},
],
},
+4 -1
View File
@@ -116,7 +116,10 @@ export const ROUTE_PERMISSIONS: Record<string, string[]> = {
// Report
'/report/logistic-stock/': ['lti.repport.purchasesupplier.list'],
'/report/expense/': ['lti.repport.expense.list'],
'/report/marketing/': ['lti.repport.delivery.list'],
'/report/marketing/': [
'lti.repport.delivery.list',
'lti.repport.gethppperkandang.list',
],
'/report/production-result/': ['lti.repport.production_result.list'],
'/report/finance/': [
'lti.repport.finance.list',
@@ -127,6 +127,10 @@ export function DailyChecklistContent() {
{ id: number; name: string }[]
>([]);
const sortedSelectedEmployees = selectedEmployees.toSorted((a, b) =>
a.name.localeCompare(b.name)
);
const [dailyChecklistId, setDailyChecklistId] = useState<string | null>(null);
const [checklistStatus, setChecklistStatus] = useState<string>('DRAFT');
// const [isEditMode, setIsEditMode] = useState(false);
@@ -486,6 +490,11 @@ export function DailyChecklistContent() {
return;
}
if (!tempSelectedPhaseIds.length) {
toast.error('Pilih minimal satu fase');
return;
}
try {
// Insert new phase links
const setDailyChecklistPhaseRes =
@@ -535,14 +544,6 @@ export function DailyChecklistContent() {
}
};
const toggleSelectAllAbk = () => {
if (tempSelectedEmployees.length === employees.length) {
setTempSelectedEmployees([]);
} else {
setTempSelectedEmployees([...employees]);
}
};
const applyAbkSelection = async () => {
if (!dailyChecklistId) {
toast.error('Checklist belum tersedia');
@@ -853,10 +854,34 @@ export function DailyChecklistContent() {
);
const isAllAbkSelected =
tempSelectedEmployees.length === employees.length && employees.length > 0;
tempSelectedEmployees.length === filteredEmployees.length &&
filteredEmployees.length > 0 &&
tempSelectedEmployees.every((tempSelectedEmployee) => {
return (
filteredEmployees.findIndex(
(filteredEmployee) => filteredEmployee.id === tempSelectedEmployee.id
) >= 0
);
});
const isAllPhasesSelected =
tempSelectedPhaseIds.length === availablePhases.length &&
availablePhases.length > 0;
tempSelectedPhaseIds.length === filteredPhases.length &&
filteredPhases.length > 0 &&
tempSelectedPhaseIds.every((tempSelectedPhaseId) => {
return (
filteredPhases.findIndex(
(filteredPhase) =>
String(filteredPhase.id) === String(tempSelectedPhaseId)
) >= 0
);
});
const toggleSelectAllAbk = () => {
if (isAllAbkSelected) {
setTempSelectedEmployees([]);
} else {
setTempSelectedEmployees([...filteredEmployees]);
}
};
// Group activities by PHASE → TIME_TYPE → ACTIVITIES
const groupActivitiesByPhase = () => {
@@ -1130,7 +1155,7 @@ export function DailyChecklistContent() {
<th className='text-left py-3 px-4 text-sm font-semibold text-gray-700 border-r border-gray-200 min-w-[200px]'>
Aktivitas
</th>
{selectedEmployees.map((emp) => (
{sortedSelectedEmployees.map((emp) => (
<th
key={emp.id}
className='text-center py-3 px-4 text-sm font-semibold text-gray-700 border-r border-gray-200 min-w-[100px]'
@@ -1216,6 +1241,14 @@ export function DailyChecklistContent() {
}
// ACTIVITY rows (Child rows with checkboxes)
activities.sort((a, b) =>
a.name.localeCompare(b.name, undefined, {
sensitivity: 'base',
})
);
console.log(activities);
activities.forEach((activity, index) => {
const taskId =
taskIdsByPhaseActivityId[activity.id];
@@ -1244,7 +1277,7 @@ export function DailyChecklistContent() {
</p>
)}
</td>
{selectedEmployees.map((emp) => (
{sortedSelectedEmployees.map((emp) => (
<td
key={emp.id}
className='text-center py-3 px-4 border-r border-gray-200'
@@ -1445,6 +1478,8 @@ export function DailyChecklistContent() {
inputWrapper: 'flex items-center',
label: 'font-semibold text-gray-900',
}}
maxSize={5242880} // 5 MB
bottomLabel='Ukuran file maksimal 5MB'
/>
)}
</>
@@ -1519,14 +1554,14 @@ export function DailyChecklistContent() {
setTempSelectedPhaseIds([]);
} else {
setTempSelectedPhaseIds(
availablePhases.map((p) => String(p.id))
filteredPhases.map((p) => String(p.id))
);
}
}}
className='checkbox-clean'
/>
<span className='text-sm font-medium text-gray-700 group-hover:text-gray-900'>
Pilih Semua ({availablePhases.length} Fase)
Pilih Semua ({filteredPhases.length} Fase)
</span>
</label>
</div>
@@ -1621,7 +1656,7 @@ export function DailyChecklistContent() {
/>
</div>
{employees.length > 0 && (
{filteredEmployees.length > 0 && (
<div className='flex items-center gap-3 px-1 py-2'>
<label className='flex items-center gap-2 cursor-pointer group'>
<input
@@ -1631,7 +1666,7 @@ export function DailyChecklistContent() {
className='checkbox-clean'
/>
<span className='text-sm font-medium text-gray-700 group-hover:text-gray-900'>
Pilih Semua ({employees.length} ABK)
Pilih Semua ({filteredEmployees.length} ABK)
</span>
</label>
</div>
@@ -275,6 +275,13 @@ export function DetailDailyChecklistContent() {
])
).values()
);
uniqueEmployees.sort((a, b) =>
a.name.localeCompare(b.name, undefined, {
sensitivity: 'base',
})
);
setEmployees(uniqueEmployees);
// Group data by Phase → Time Type → Activity
@@ -779,11 +786,23 @@ export function DetailDailyChecklistContent() {
}
// ACTIVITY rows
timeGroup.activities.forEach((activity, index) => {
const activities = timeGroup.activities;
activities.sort((a, b) =>
a.name.localeCompare(b.name, undefined, {
sensitivity: 'base',
})
);
activities.forEach((activity, index) => {
const indentClass = hasMultipleTimeTypes
? 'pl-12'
: 'pl-8';
console.log({
activity,
});
rows.push(
<tr
key={`activity-${activity.id}-${index}`}
@@ -823,9 +842,15 @@ export function DetailDailyChecklistContent() {
})}
<td className='py-3 px-4'>
{activity.employees.length > 0 &&
activity.employees[0].note ? (
activity.employees[
activity.employees.length - 1
].note ? (
<p className='text-sm text-gray-600'>
{activity.employees[0].note}
{
activity.employees[
activity.employees.length - 1
].note
}
</p>
) : (
<p className='text-xs text-gray-400 italic'>
@@ -1,6 +1,6 @@
'use client';
import { useState } from 'react';
import { useEffect, useState } from 'react';
import { Plus, MoreVertical, Pencil, Trash2 } from 'lucide-react';
import { Card, CardContent } from '@/figma-make/components/base/card';
import { Button } from '@/figma-make/components/base/button';
@@ -404,7 +404,22 @@ export function MasterConfigurationContent() {
</div>
{/* Add/Edit Modal */}
<Dialog open={showModal} onOpenChange={setShowModal}>
<Dialog
open={showModal}
onOpenChange={(open) => {
if (!open) {
setIsFormInvalid(false);
setConfigurationForm({
id: 0,
date: '',
percentage_threshold_bad: '',
percentage_threshold_enough: '',
});
}
setShowModal(open);
}}
>
<DialogContent className='sm:max-w-md bg-white rounded-xl shadow-lg'>
<DialogHeader>
<DialogTitle>
@@ -0,0 +1,51 @@
'use client';
import { ReactNode } from 'react';
import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
export type FinanceTabActionsSlice = {
// State - actions per tab ID
tabActions: Record<string, ReactNode>;
// Actions
setTabActions: (tabId: string, actions: ReactNode) => void;
clearTabActions: (tabId: string) => void;
clearAllTabActions: () => void;
};
export const useFinanceTabStore = create<FinanceTabActionsSlice>()(
devtools(
(set) => ({
tabActions: {},
setTabActions: (tabId, actions) =>
set(
(state) => ({
tabActions: {
...state.tabActions,
[tabId]: actions,
},
}),
false,
'setTabActions'
),
clearTabActions: (tabId) =>
set(
(state) => {
const { [tabId]: _, ...rest } = state.tabActions;
return { tabActions: rest };
},
false,
'clearTabActions'
),
clearAllTabActions: () =>
set({ tabActions: {} }, false, 'clearAllTabActions'),
}),
{
name: 'FinanceTabStore',
}
)
);
+22
View File
@@ -0,0 +1,22 @@
'use client';
import { ReactNode } from 'react';
import { StateCreator } from 'zustand';
import { UIStore } from '@/types/stores';
type NavbarActionsSlice = {
navbarActions: ReactNode | null;
setNavbarActions: (actions: ReactNode) => void;
clearNavbarActions: () => void;
};
export const createNavbarActionsSlice: StateCreator<
UIStore,
[],
[],
NavbarActionsSlice
> = (set) => ({
navbarActions: null,
setNavbarActions: (actions) => set({ navbarActions: actions }),
clearNavbarActions: () => set({ navbarActions: null }),
});
+2
View File
@@ -7,6 +7,7 @@ import { UIStore } from '@/types/stores';
import { createMainUiSlice } from '@/stores/ui/slices/main.slice';
import { createDrawerUISlice } from '@/stores/ui/slices/drawer.slice';
import { createTableUISlice } from '@/stores/ui/slices/table.slice';
import { createNavbarActionsSlice } from '@/stores/ui/slices/navbar.slice';
export const useUiStore = create<UIStore>()(
devtools(
@@ -15,6 +16,7 @@ export const useUiStore = create<UIStore>()(
...createMainUiSlice(...args),
...createDrawerUISlice(...args),
...createTableUISlice(...args),
...createNavbarActionsSlice(...args),
}),
{
name: 'ui-cache',
+4 -4
View File
@@ -68,11 +68,11 @@ export type CreateMovementPayloadData = {
product_qty: number;
}[];
deliveries: {
delivery_cost: number;
delivery_cost_per_item: number;
delivery_cost?: number;
delivery_cost_per_item?: number;
document_index?: number;
driver_name: string;
vehicle_plate: string;
driver_name?: string;
vehicle_plate?: string;
supplier_id?: number | null;
products: {
product_id: number;
+11 -1
View File
@@ -32,7 +32,17 @@ type TableUISlice = {
resetSearchValue: () => void;
};
export type UIStore = MainUiSlice & DrawerUISlice & TableUISlice;
// Navbar Actions Slice
type NavbarActionsSlice = {
navbarActions: ReactNode | null;
setNavbarActions: (actions: ReactNode) => void;
clearNavbarActions: () => void;
};
export type UIStore = MainUiSlice &
DrawerUISlice &
TableUISlice &
NavbarActionsSlice;
type ProductionStandardFormSlice = {
formData: {