Account Page

This commit is contained in:
efrilm 2025-09-11 00:16:00 +07:00
parent e267a50946
commit 630d9c0e65
8 changed files with 929 additions and 2 deletions

View File

@ -0,0 +1,7 @@
import AccountList from '@/views/apps/account'
const AccountPage = () => {
return <AccountList />
}
export default AccountPage

View File

@ -129,6 +129,14 @@ const VerticalMenu = ({ dictionary, scrollMenu }: Props) => {
>
{dictionary['navigation'].cash_and_bank}
</MenuItem>
<MenuItem
href={`/${locale}/apps/account`}
icon={<i className='tabler-align-box-left-stretch' />}
exactMatch={false}
activeUrl='/apps/account'
>
{dictionary['navigation'].account}
</MenuItem>
<SubMenu label={dictionary['navigation'].inventory} icon={<i className='tabler-salad' />}>
<SubMenu label={dictionary['navigation'].products}>
<MenuItem href={`/${locale}/apps/inventory/products/list`}>{dictionary['navigation'].list}</MenuItem>

View File

@ -124,6 +124,7 @@
"sales_orders": "Orders",
"quotes": "Quotes",
"expenses": "Expenses",
"cash_and_bank": "Cash & Bank"
"cash_and_bank": "Cash & Bank",
"account": "Account"
}
}

View File

@ -124,6 +124,7 @@
"sales_orders": "Pemesanan",
"quotes": "Penawaran",
"expenses": "Biaya",
"cash_and_bank": "Kas & Bank"
"cash_and_bank": "Kas & Bank",
"account": "Akun"
}
}

View File

@ -0,0 +1,7 @@
export type AccountType = {
id: number
code: string
name: string
category: string
balance: string
}

View File

@ -0,0 +1,308 @@
// React Imports
import { useState, useEffect } from 'react'
// MUI Imports
import Button from '@mui/material/Button'
import Drawer from '@mui/material/Drawer'
import IconButton from '@mui/material/IconButton'
import MenuItem from '@mui/material/MenuItem'
import Typography from '@mui/material/Typography'
import Box from '@mui/material/Box'
// Third-party Imports
import { useForm, Controller } from 'react-hook-form'
// Component Imports
import CustomTextField from '@core/components/mui/TextField'
import CustomAutocomplete from '@/@core/components/mui/Autocomplete'
// Account Type
export type AccountType = {
id: number
code: string
name: string
category: string
balance: string
}
type Props = {
open: boolean
handleClose: () => void
accountData?: AccountType[]
setData: (data: AccountType[]) => void
editingAccount?: AccountType | null
}
type FormValidateType = {
name: string
code: string
category: string
parentAccount?: string
}
// Categories available for accounts
const accountCategories = [
'Kas & Bank',
'Piutang',
'Persediaan',
'Aset Tetap',
'Hutang',
'Ekuitas',
'Pendapatan',
'Beban'
]
// Parent accounts (dummy data for dropdown)
const parentAccounts = [
{ id: 1, code: '1-10001', name: 'Kas' },
{ id: 2, code: '1-10002', name: 'Bank BCA' },
{ id: 3, code: '1-10003', name: 'Bank Mandiri' },
{ id: 4, code: '1-10101', name: 'Piutang Usaha' },
{ id: 5, code: '1-10201', name: 'Persediaan Barang' },
{ id: 6, code: '2-20001', name: 'Hutang Usaha' },
{ id: 7, code: '3-30001', name: 'Modal Pemilik' },
{ id: 8, code: '4-40001', name: 'Penjualan' },
{ id: 9, code: '5-50001', name: 'Beban Gaji' }
]
// Vars
const initialData = {
name: '',
code: '',
category: '',
parentAccount: ''
}
const AccountFormDrawer = (props: Props) => {
// Props
const { open, handleClose, accountData, setData, editingAccount } = props
// Determine if we're editing
const isEdit = !!editingAccount
// Hooks
const {
control,
reset: resetForm,
handleSubmit,
formState: { errors }
} = useForm<FormValidateType>({
defaultValues: initialData
})
// Reset form when editingAccount changes or drawer opens
useEffect(() => {
if (open) {
if (editingAccount) {
// Populate form with existing data
resetForm({
name: editingAccount.name,
code: editingAccount.code,
category: editingAccount.category,
parentAccount: ''
})
} else {
// Reset to initial data for new account
resetForm(initialData)
}
}
}, [editingAccount, open, resetForm])
const onSubmit = (data: FormValidateType) => {
if (isEdit && editingAccount) {
// Update existing account
const updatedAccounts =
accountData?.map(account =>
account.id === editingAccount.id
? {
...account,
code: data.code,
name: data.name,
category: data.category
}
: account
) || []
setData(updatedAccounts)
} else {
// Create new account
const newAccount: AccountType = {
id: accountData?.length ? Math.max(...accountData.map(a => a.id)) + 1 : 1,
code: data.code,
name: data.name,
category: data.category,
balance: '0'
}
setData([...(accountData ?? []), newAccount])
}
handleClose()
resetForm(initialData)
}
const handleReset = () => {
handleClose()
resetForm(initialData)
}
return (
<Drawer
open={open}
anchor='right'
variant='temporary'
onClose={handleReset}
ModalProps={{ keepMounted: true }}
sx={{
'& .MuiDrawer-paper': {
width: { xs: 300, sm: 400 },
display: 'flex',
flexDirection: 'column',
height: '100%'
}
}}
>
{/* Sticky Header */}
<Box
sx={{
position: 'sticky',
top: 0,
zIndex: 10,
backgroundColor: 'background.paper',
borderBottom: 1,
borderColor: 'divider'
}}
>
<div className='flex items-center justify-between plb-5 pli-6'>
<Typography variant='h5'>{isEdit ? 'Edit Akun' : 'Tambah Akun Baru'}</Typography>
<IconButton size='small' onClick={handleReset}>
<i className='tabler-x text-2xl text-textPrimary' />
</IconButton>
</div>
</Box>
{/* Scrollable Content */}
<Box sx={{ flex: 1, overflowY: 'auto' }}>
<form id='account-form' onSubmit={handleSubmit(data => onSubmit(data))}>
<div className='flex flex-col gap-6 p-6'>
{/* Nama */}
<div>
<Typography variant='body2' className='mb-2'>
Nama <span className='text-red-500'>*</span>
</Typography>
<Controller
name='name'
control={control}
rules={{ required: true }}
render={({ field }) => (
<CustomTextField
{...field}
fullWidth
placeholder='Nama'
{...(errors.name && { error: true, helperText: 'Field ini wajib diisi.' })}
/>
)}
/>
</div>
{/* Kode */}
<div>
<Typography variant='body2' className='mb-2'>
Kode <span className='text-red-500'>*</span>
</Typography>
<Controller
name='code'
control={control}
rules={{ required: true }}
render={({ field }) => (
<CustomTextField
{...field}
fullWidth
placeholder='Kode'
{...(errors.code && { error: true, helperText: 'Field ini wajib diisi.' })}
/>
)}
/>
</div>
{/* Kategori */}
<div>
<Typography variant='body2' className='mb-2'>
Kategori <span className='text-red-500'>*</span>
</Typography>
<Controller
name='category'
control={control}
rules={{ required: true }}
render={({ field: { onChange, value, ...field } }) => (
<CustomAutocomplete
{...field}
options={accountCategories}
value={value || null}
onChange={(_, newValue) => onChange(newValue || '')}
renderInput={params => (
<CustomTextField
{...params}
placeholder='Pilih kategori'
{...(errors.category && { error: true, helperText: 'Field ini wajib diisi.' })}
/>
)}
isOptionEqualToValue={(option, value) => option === value}
/>
)}
/>
</div>
{/* Sub Akun dari */}
<div>
<Typography variant='body2' className='mb-2'>
Sub Akun dari
</Typography>
<Controller
name='parentAccount'
control={control}
render={({ field: { onChange, value, ...field } }) => (
<CustomAutocomplete
{...field}
options={parentAccounts}
value={parentAccounts.find(account => `${account.code} ${account.name}` === value) || null}
onChange={(_, newValue) => onChange(newValue ? `${newValue.code} ${newValue.name}` : '')}
getOptionLabel={option => `${option.code} ${option.name}`}
renderInput={params => <CustomTextField {...params} placeholder='Pilih akun' />}
isOptionEqualToValue={(option, value) =>
`${option.code} ${option.name}` === `${value.code} ${value.name}`
}
/>
)}
/>
</div>
</div>
</form>
</Box>
{/* Sticky Footer */}
<Box
sx={{
position: 'sticky',
bottom: 0,
zIndex: 10,
backgroundColor: 'background.paper',
borderTop: 1,
borderColor: 'divider',
p: 3
}}
>
<div className='flex items-center gap-4'>
<Button variant='contained' type='submit' form='account-form'>
{isEdit ? 'Update' : 'Simpan'}
</Button>
<Button variant='tonal' color='error' onClick={() => handleReset()}>
Batal
</Button>
</div>
</Box>
</Drawer>
)
}
export default AccountFormDrawer

View File

@ -0,0 +1,576 @@
'use client'
// React Imports
import { useCallback, useEffect, useMemo, useState } from 'react'
// Next Imports
import Link from 'next/link'
import { useParams } from 'next/navigation'
// MUI Imports
import Button from '@mui/material/Button'
import Card from '@mui/material/Card'
import CardHeader from '@mui/material/CardHeader'
import Checkbox from '@mui/material/Checkbox'
import Chip from '@mui/material/Chip'
import IconButton from '@mui/material/IconButton'
import MenuItem from '@mui/material/MenuItem'
import { styled } from '@mui/material/styles'
import type { TextFieldProps } from '@mui/material/TextField'
import Typography from '@mui/material/Typography'
// Third-party Imports
import type { RankingInfo } from '@tanstack/match-sorter-utils'
import { rankItem } from '@tanstack/match-sorter-utils'
import type { ColumnDef, FilterFn } from '@tanstack/react-table'
import { createColumnHelper, flexRender, getCoreRowModel, useReactTable } from '@tanstack/react-table'
import classnames from 'classnames'
// Type Imports
import type { Locale } from '@configs/i18n'
// Component Imports
import CustomTextField from '@core/components/mui/TextField'
import OptionMenu from '@core/components/option-menu'
// Style Imports
import tableStyles from '@core/styles/table.module.css'
import { Box, CircularProgress, TablePagination } from '@mui/material'
import { useDispatch } from 'react-redux'
import TablePaginationComponent from '@/components/TablePaginationComponent'
import Loading from '@/components/layout/shared/Loading'
import { getLocalizedUrl } from '@/utils/i18n'
import AccountFormDrawer from './AccountFormDrawer'
// Account Type
export type AccountType = {
id: number
code: string
name: string
category: string
balance: string
}
declare module '@tanstack/table-core' {
interface FilterFns {
fuzzy: FilterFn<unknown>
}
interface FilterMeta {
itemRank: RankingInfo
}
}
type AccountTypeWithAction = AccountType & {
actions?: string
}
// Dummy Account Data
const accountsData: AccountType[] = [
{
id: 1,
code: '1-10001',
name: 'Kas',
category: 'Kas & Bank',
balance: '20000000'
},
{
id: 2,
code: '1-10002',
name: 'Bank BCA',
category: 'Kas & Bank',
balance: '150000000'
},
{
id: 3,
code: '1-10003',
name: 'Bank Mandiri',
category: 'Kas & Bank',
balance: '75000000'
},
{
id: 4,
code: '1-10101',
name: 'Piutang Usaha',
category: 'Piutang',
balance: '50000000'
},
{
id: 5,
code: '1-10102',
name: 'Piutang Karyawan',
category: 'Piutang',
balance: '5000000'
},
{
id: 6,
code: '1-10201',
name: 'Persediaan Barang',
category: 'Persediaan',
balance: '100000000'
},
{
id: 7,
code: '1-10301',
name: 'Peralatan Kantor',
category: 'Aset Tetap',
balance: '25000000'
},
{
id: 8,
code: '1-10302',
name: 'Kendaraan',
category: 'Aset Tetap',
balance: '200000000'
},
{
id: 9,
code: '2-20001',
name: 'Hutang Usaha',
category: 'Hutang',
balance: '-30000000'
},
{
id: 10,
code: '2-20002',
name: 'Hutang Gaji',
category: 'Hutang',
balance: '-15000000'
},
{
id: 11,
code: '3-30001',
name: 'Modal Pemilik',
category: 'Ekuitas',
balance: '500000000'
},
{
id: 12,
code: '4-40001',
name: 'Penjualan',
category: 'Pendapatan',
balance: '250000000'
},
{
id: 13,
code: '5-50001',
name: 'Beban Gaji',
category: 'Beban',
balance: '-80000000'
},
{
id: 14,
code: '5-50002',
name: 'Beban Listrik',
category: 'Beban',
balance: '-5000000'
},
{
id: 15,
code: '5-50003',
name: 'Beban Telepon',
category: 'Beban',
balance: '-2000000'
}
]
// Styled Components
const Icon = styled('i')({})
const fuzzyFilter: FilterFn<any> = (row, columnId, value, addMeta) => {
// Rank the item
const itemRank = rankItem(row.getValue(columnId), value)
// Store the itemRank info
addMeta({
itemRank
})
// Return if the item should be filtered in/out
return itemRank.passed
}
const DebouncedInput = ({
value: initialValue,
onChange,
debounce = 500,
...props
}: {
value: string | number
onChange: (value: string | number) => void
debounce?: number
} & Omit<TextFieldProps, 'onChange'>) => {
// States
const [value, setValue] = useState(initialValue)
useEffect(() => {
setValue(initialValue)
}, [initialValue])
useEffect(() => {
const timeout = setTimeout(() => {
onChange(value)
}, debounce)
return () => clearTimeout(timeout)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value])
return <CustomTextField {...props} value={value} onChange={e => setValue(e.target.value)} />
}
// Category color mapping for Accounts
const getCategoryColor = (category: string) => {
switch (category) {
case 'Kas & Bank':
return 'success'
case 'Piutang':
return 'info'
case 'Persediaan':
return 'warning'
case 'Aset Tetap':
return 'primary'
case 'Hutang':
return 'error'
case 'Ekuitas':
return 'secondary'
case 'Pendapatan':
return 'success'
case 'Beban':
return 'error'
default:
return 'default'
}
}
// Format currency
const formatCurrency = (amount: string) => {
const numAmount = parseInt(amount)
return new Intl.NumberFormat('id-ID', {
style: 'currency',
currency: 'IDR',
minimumFractionDigits: 0
}).format(Math.abs(numAmount))
}
// Column Definitions
const columnHelper = createColumnHelper<AccountTypeWithAction>()
const AccountListTable = () => {
const dispatch = useDispatch()
// States
const [addAccountOpen, setAddAccountOpen] = useState(false)
const [rowSelection, setRowSelection] = useState({})
const [currentPage, setCurrentPage] = useState(0)
const [pageSize, setPageSize] = useState(10)
const [openConfirm, setOpenConfirm] = useState(false)
const [accountId, setAccountId] = useState('')
const [search, setSearch] = useState('')
const [categoryFilter, setCategoryFilter] = useState<string>('Semua')
const [filteredData, setFilteredData] = useState<AccountType[]>(accountsData)
const [data, setData] = useState<AccountType[]>(accountsData)
const [editingAccount, setEditingAccount] = useState<AccountType | null>(null)
// Hooks
const { lang: locale } = useParams()
// Get unique categories for filter
const categories = useMemo(() => {
const uniqueCategories = [...new Set(data.map(account => account.category))]
return ['Semua', ...uniqueCategories]
}, [data])
// Filter data based on search and category
useEffect(() => {
let filtered = data
// Filter by search
if (search) {
filtered = filtered.filter(
account =>
account.code.toLowerCase().includes(search.toLowerCase()) ||
account.name.toLowerCase().includes(search.toLowerCase()) ||
account.category.toLowerCase().includes(search.toLowerCase())
)
}
// Filter by category
if (categoryFilter !== 'Semua') {
filtered = filtered.filter(account => account.category === categoryFilter)
}
setFilteredData(filtered)
setCurrentPage(0)
}, [search, categoryFilter, data])
const totalCount = filteredData.length
const paginatedData = useMemo(() => {
const startIndex = currentPage * pageSize
return filteredData.slice(startIndex, startIndex + pageSize)
}, [filteredData, currentPage, pageSize])
const handlePageChange = useCallback((event: unknown, newPage: number) => {
setCurrentPage(newPage)
}, [])
const handlePageSizeChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
const newPageSize = parseInt(event.target.value, 10)
setPageSize(newPageSize)
setCurrentPage(0)
}, [])
const handleDelete = () => {
setOpenConfirm(false)
}
// Handle row click for edit
const handleRowClick = (account: AccountType, event: React.MouseEvent) => {
// Don't trigger row click if clicking on checkbox or link
const target = event.target as HTMLElement
if (target.closest('input[type="checkbox"]') || target.closest('a') || target.closest('button')) {
return
}
setEditingAccount(account)
setAddAccountOpen(true)
}
// Handle closing drawer and reset editing state
const handleCloseDrawer = () => {
setAddAccountOpen(false)
setEditingAccount(null)
}
const columns = useMemo<ColumnDef<AccountTypeWithAction, any>[]>(
() => [
{
id: 'select',
header: ({ table }) => (
<Checkbox
{...{
checked: table.getIsAllRowsSelected(),
indeterminate: table.getIsSomeRowsSelected(),
onChange: table.getToggleAllRowsSelectedHandler()
}}
/>
),
cell: ({ row }) => (
<Checkbox
{...{
checked: row.getIsSelected(),
disabled: !row.getCanSelect(),
indeterminate: row.getIsSomeSelected(),
onChange: row.getToggleSelectedHandler()
}}
/>
)
},
columnHelper.accessor('code', {
header: 'Kode Akun',
cell: ({ row }) => (
<Button
variant='text'
color='primary'
className='p-0 min-w-0 font-medium normal-case justify-start'
component={Link}
href={getLocalizedUrl(`/apps/accounting/accounts/${row.original.id}/detail`, locale as Locale)}
sx={{
textTransform: 'none',
fontWeight: 500,
'&:hover': {
textDecoration: 'underline',
backgroundColor: 'transparent'
}
}}
>
{row.original.code}
</Button>
)
}),
columnHelper.accessor('name', {
header: 'Nama Akun',
cell: ({ row }) => (
<Typography color='text.primary' className='font-medium'>
{row.original.name}
</Typography>
)
}),
columnHelper.accessor('category', {
header: 'Kategori',
cell: ({ row }) => (
<Chip
variant='tonal'
label={row.original.category}
size='small'
color={getCategoryColor(row.original.category) as any}
className='capitalize'
/>
)
}),
columnHelper.accessor('balance', {
header: 'Saldo',
cell: ({ row }) => {
const balance = parseInt(row.original.balance)
return (
<Typography className='font-medium text-right text-primary'>
{balance < 0 ? '-' : ''}
{formatCurrency(row.original.balance)}
</Typography>
)
}
})
],
[locale]
)
const table = useReactTable({
data: paginatedData as AccountType[],
columns,
filterFns: {
fuzzy: fuzzyFilter
},
state: {
rowSelection,
pagination: {
pageIndex: currentPage,
pageSize
}
},
enableRowSelection: true,
onRowSelectionChange: setRowSelection,
getCoreRowModel: getCoreRowModel(),
manualPagination: true,
pageCount: Math.ceil(totalCount / pageSize)
})
return (
<>
<Card>
<div className='flex justify-between flex-col items-start md:flex-row md:items-center p-6 border-bs gap-4'>
<DebouncedInput
value={search}
onChange={value => setSearch(value as string)}
placeholder='Cari Akun'
className='max-sm:is-full'
/>
<div className='flex flex-col sm:flex-row max-sm:is-full items-start sm:items-center gap-4'>
<CustomTextField
select
value={pageSize}
onChange={handlePageSizeChange}
className='max-sm:is-full sm:is-[70px]'
>
<MenuItem value={10}>10</MenuItem>
<MenuItem value={25}>25</MenuItem>
<MenuItem value={50}>50</MenuItem>
</CustomTextField>
<Button
color='secondary'
variant='tonal'
startIcon={<i className='tabler-upload' />}
className='max-sm:is-full'
>
Ekspor
</Button>
<Button
variant='contained'
className='max-sm:is-full is-auto'
startIcon={<i className='tabler-plus' />}
onClick={() => {
setEditingAccount(null)
setAddAccountOpen(true)
}}
>
Tambah Akun
</Button>
</div>
</div>
<div className='overflow-x-auto'>
<table className={tableStyles.table}>
<thead>
{table.getHeaderGroups().map(headerGroup => (
<tr key={headerGroup.id}>
{headerGroup.headers.map(header => (
<th key={header.id}>
{header.isPlaceholder ? null : (
<>
<div
className={classnames({
'flex items-center': header.column.getIsSorted(),
'cursor-pointer select-none': header.column.getCanSort()
})}
onClick={header.column.getToggleSortingHandler()}
>
{flexRender(header.column.columnDef.header, header.getContext())}
{{
asc: <i className='tabler-chevron-up text-xl' />,
desc: <i className='tabler-chevron-down text-xl' />
}[header.column.getIsSorted() as 'asc' | 'desc'] ?? null}
</div>
</>
)}
</th>
))}
</tr>
))}
</thead>
{filteredData.length === 0 ? (
<tbody>
<tr>
<td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
Tidak ada data tersedia
</td>
</tr>
</tbody>
) : (
<tbody>
{table.getRowModel().rows.map(row => {
return (
<tr
key={row.id}
className={classnames({
selected: row.getIsSelected(),
'cursor-pointer hover:bg-gray-50': true
})}
onClick={e => handleRowClick(row.original, e)}
>
{row.getVisibleCells().map(cell => (
<td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
))}
</tr>
)
})}
</tbody>
)}
</table>
</div>
<TablePagination
component={() => (
<TablePaginationComponent
pageIndex={currentPage}
pageSize={pageSize}
totalCount={totalCount}
onPageChange={handlePageChange}
/>
)}
count={totalCount}
rowsPerPage={pageSize}
page={currentPage}
onPageChange={handlePageChange}
onRowsPerPageChange={handlePageSizeChange}
rowsPerPageOptions={[10, 25, 50]}
/>
</Card>
<AccountFormDrawer
open={addAccountOpen}
handleClose={handleCloseDrawer}
accountData={data}
setData={setData}
editingAccount={editingAccount}
/>
</>
)
}
export default AccountListTable

View File

@ -0,0 +1,19 @@
// MUI Imports
import Grid from '@mui/material/Grid2'
// Type Imports
// Component Imports
import AccountListTable from './AccountListTable'
const AccountList = () => {
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<AccountListTable />
</Grid>
</Grid>
)
}
export default AccountList