Vendor Api

This commit is contained in:
efrilm 2025-09-12 03:11:01 +07:00
parent a019a4bdbc
commit 0e8216b0c9
4 changed files with 179 additions and 122 deletions

View File

@ -6,7 +6,7 @@ const getToken = () => {
} }
export const api = axios.create({ export const api = axios.create({
baseURL: 'https://api-pos.apskel.id/api/v1', baseURL: 'http://127.0.0.1:4000/api/v1',
headers: { headers: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },

View File

@ -0,0 +1,36 @@
import { useQuery } from '@tanstack/react-query'
import { api } from '../api'
import { Vendors } from '@/types/services/vendor'
interface VendorQueryParams {
page?: number
limit?: number
search?: string
}
export function useVendors(params: VendorQueryParams = {}) {
const { page = 1, limit = 10, search = '', ...filters } = params
return useQuery<Vendors>({
queryKey: ['vendors', { page, limit, search, ...filters }],
queryFn: async () => {
const queryParams = new URLSearchParams()
queryParams.append('page', page.toString())
queryParams.append('limit', limit.toString())
if (search) {
queryParams.append('search', search)
}
Object.entries(filters).forEach(([key, value]) => {
if (value !== undefined && value !== null && value !== '') {
queryParams.append(key, value.toString())
}
})
const res = await api.get(`/vendors?${queryParams.toString()}`)
return res.data.data
}
})
}

View File

@ -0,0 +1,23 @@
export interface Vendor {
id: string
organization_id: string
name: string
email?: string
phone_number?: string
address?: string
contact_person?: string
tax_number?: string
payment_terms?: string
notes?: string
is_active: boolean
created_at: string
updated_at: string
}
export interface Vendors {
vendors: Vendor[]
total_count: number
page: number
limit: number
total_pages: number
}

View File

@ -1,7 +1,7 @@
'use client' 'use client'
// React Imports // React Imports
import { useEffect, useState, useMemo } from 'react' import { useEffect, useState, useMemo, useCallback } from 'react'
// Next Imports // Next Imports
import Link from 'next/link' import Link from 'next/link'
@ -58,6 +58,9 @@ import { getLocalizedUrl } from '@/utils/i18n'
// Style Imports // Style Imports
import tableStyles from '@core/styles/table.module.css' import tableStyles from '@core/styles/table.module.css'
import { formatCurrency } from '@/utils/transform' import { formatCurrency } from '@/utils/transform'
import { useVendors } from '@/services/queries/vendor'
import { Vendor } from '@/types/services/vendor'
import Loading from '@/components/layout/shared/Loading'
declare module '@tanstack/table-core' { declare module '@tanstack/table-core' {
interface FilterFns { interface FilterFns {
@ -68,7 +71,7 @@ declare module '@tanstack/table-core' {
} }
} }
type VendorTypeWithAction = VendorType & { type VendorTypeWithAction = Vendor & {
action?: string action?: string
} }
@ -120,17 +123,37 @@ const DebouncedInput = ({
// Column Definitions // Column Definitions
const columnHelper = createColumnHelper<VendorTypeWithAction>() const columnHelper = createColumnHelper<VendorTypeWithAction>()
const VendorListTable = ({ tableData }: { tableData?: VendorType[] }) => { const VendorListTable = () => {
// States // States
const [addVendorOpen, setAddVendorOpen] = useState(false) const [addVendorOpen, setAddVendorOpen] = useState(false)
const [rowSelection, setRowSelection] = useState({}) const [rowSelection, setRowSelection] = useState({})
const [data, setData] = useState(...[tableData])
const [filteredData, setFilteredData] = useState(data)
const [globalFilter, setGlobalFilter] = useState('') const [globalFilter, setGlobalFilter] = useState('')
const [currentPage, setCurrentPage] = useState(1)
const [pageSize, setPageSize] = useState(10)
const [search, setSearch] = useState('')
const { data, isLoading, error, isFetching } = useVendors({
page: currentPage,
limit: pageSize,
search
})
const vendors = data?.vendors ?? []
const totalCount = data?.total_count ?? 0
// Hooks // Hooks
const { lang: locale } = useParams() const { lang: locale } = useParams()
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(1) // Reset to first page
}, [])
const columns = useMemo<ColumnDef<VendorTypeWithAction, any>[]>( const columns = useMemo<ColumnDef<VendorTypeWithAction, any>[]>(
() => [ () => [
{ {
@ -155,15 +178,14 @@ const VendorListTable = ({ tableData }: { tableData?: VendorType[] }) => {
/> />
) )
}, },
columnHelper.accessor('name', { columnHelper.accessor('contact_person', {
header: 'Vendor', header: 'Vendor',
cell: ({ row }) => ( cell: ({ row }) => (
<div className='flex items-center gap-4'> <div className='flex items-center gap-4'>
{getAvatar({ photo: row.original.photo, name: row.original.name })}
<div className='flex flex-col'> <div className='flex flex-col'>
<Link href={getLocalizedUrl(`/apps/vendor/detail`, locale as Locale)}> <Link href={getLocalizedUrl(`/apps/vendor/detail`, locale as Locale)}>
<Typography color='primary' className='font-medium cursor-pointer hover:underline'> <Typography color='primary' className='font-medium cursor-pointer hover:underline'>
{row.original.name} {row.original.contact_person}
</Typography> </Typography>
</Link> </Link>
<Typography variant='body2'>{row.original.email}</Typography> <Typography variant='body2'>{row.original.email}</Typography>
@ -171,87 +193,50 @@ const VendorListTable = ({ tableData }: { tableData?: VendorType[] }) => {
</div> </div>
) )
}), }),
columnHelper.accessor('company', { columnHelper.accessor('name', {
header: 'Perusahaan', header: 'Perusahaan',
cell: ({ row }) => ( cell: ({ row }) => (
<div className='flex items-center gap-2'> <div className='flex items-center gap-2'>
<Icon className='tabler-building' sx={{ color: 'var(--mui-palette-primary-main)' }} /> <Icon className='tabler-building' sx={{ color: 'var(--mui-palette-primary-main)' }} />
<Typography color='text.primary'>{row.original.company}</Typography> <Typography color='text.primary'>{row.original.name}</Typography>
</div> </div>
) )
}), }),
columnHelper.accessor('telephone', { columnHelper.accessor('phone_number', {
header: 'Telepon', header: 'Telepon',
cell: ({ row }) => <Typography color='text.primary'>{row.original.telephone}</Typography> cell: ({ row }) => <Typography color='text.primary'>{row.original.phone_number}</Typography>
}),
columnHelper.accessor('youPayable', {
header: () => <div className='text-right'>Anda Hutang</div>,
cell: ({ row }) => (
<div className='text-right'>
<Typography color='text.primary' className='font-medium'>
{formatCurrency(row.original.youPayable)}
</Typography>
</div>
)
}),
columnHelper.accessor('theyPayable', {
header: () => <div className='text-right'>Mereka Hutang</div>,
cell: ({ row }) => (
<div className='text-right'>
<Typography color='text.primary' className='font-medium'>
{formatCurrency(row.original.theyPayable)}
</Typography>
</div>
)
}) })
], ],
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
[data, filteredData] []
) )
const table = useReactTable({ const table = useReactTable({
data: filteredData as VendorType[], data: vendors as Vendor[],
columns, columns,
filterFns: { filterFns: {
fuzzy: fuzzyFilter fuzzy: fuzzyFilter
}, },
state: { state: {
rowSelection, rowSelection,
globalFilter globalFilter,
},
initialState: {
pagination: { pagination: {
pageSize: 10 pageIndex: currentPage,
pageSize
} }
}, },
enableRowSelection: true, enableRowSelection: true,
globalFilterFn: fuzzyFilter,
onRowSelectionChange: setRowSelection, onRowSelectionChange: setRowSelection,
getCoreRowModel: getCoreRowModel(), getCoreRowModel: getCoreRowModel(),
onGlobalFilterChange: setGlobalFilter, manualPagination: true,
getFilteredRowModel: getFilteredRowModel(), pageCount: Math.ceil(totalCount / pageSize)
getSortedRowModel: getSortedRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getFacetedRowModel: getFacetedRowModel(),
getFacetedUniqueValues: getFacetedUniqueValues(),
getFacetedMinMaxValues: getFacetedMinMaxValues()
}) })
const getAvatar = (params: Pick<VendorType, 'photo' | 'name'>) => {
const { photo, name } = params
if (photo) {
return <CustomAvatar src={photo} size={34} />
} else {
return <CustomAvatar size={34}>{getInitials(name as string)}</CustomAvatar>
}
}
return ( return (
<> <>
<Card> <Card>
<CardHeader title='Filter' className='pbe-4' /> <CardHeader title='Filter' className='pbe-4' />
<TableFilters setData={setFilteredData} tableData={data} /> {/* <TableFilters setData={setFilteredData} tableData={data} /> */}
<div className='flex justify-between flex-col items-start md:flex-row md:items-center p-6 border-bs gap-4'> <div className='flex justify-between flex-col items-start md:flex-row md:items-center p-6 border-bs gap-4'>
<CustomTextField <CustomTextField
select select
@ -265,8 +250,8 @@ const VendorListTable = ({ tableData }: { tableData?: VendorType[] }) => {
</CustomTextField> </CustomTextField>
<div className='flex flex-col sm:flex-row max-sm:is-full items-start sm:items-center gap-4'> <div className='flex flex-col sm:flex-row max-sm:is-full items-start sm:items-center gap-4'>
<DebouncedInput <DebouncedInput
value={globalFilter ?? ''} value={search ?? ''}
onChange={value => setGlobalFilter(String(value))} onChange={value => setSearch(value as string)}
placeholder='Cari Vendor' placeholder='Cari Vendor'
className='max-sm:is-full' className='max-sm:is-full'
/> />
@ -289,75 +274,88 @@ const VendorListTable = ({ tableData }: { tableData?: VendorType[] }) => {
</div> </div>
</div> </div>
<div className='overflow-x-auto'> <div className='overflow-x-auto'>
<table className={tableStyles.table}> {isLoading ? (
<thead> <Loading />
{table.getHeaderGroups().map(headerGroup => ( ) : (
<tr key={headerGroup.id}> <table className={tableStyles.table}>
{headerGroup.headers.map(header => ( <thead>
<th key={header.id}> {table.getHeaderGroups().map(headerGroup => (
{header.isPlaceholder ? null : ( <tr key={headerGroup.id}>
<> {headerGroup.headers.map(header => (
<div <th key={header.id}>
className={classnames({ {header.isPlaceholder ? null : (
'flex items-center': header.column.getIsSorted(), <>
'cursor-pointer select-none': header.column.getCanSort() <div
})} className={classnames({
onClick={header.column.getToggleSortingHandler()} 'flex items-center': header.column.getIsSorted(),
> 'cursor-pointer select-none': header.column.getCanSort()
{flexRender(header.column.columnDef.header, header.getContext())} })}
{{ onClick={header.column.getToggleSortingHandler()}
asc: <i className='tabler-chevron-up text-xl' />, >
desc: <i className='tabler-chevron-down text-xl' /> {flexRender(header.column.columnDef.header, header.getContext())}
}[header.column.getIsSorted() as 'asc' | 'desc'] ?? null} {{
</div> asc: <i className='tabler-chevron-up text-xl' />,
</> desc: <i className='tabler-chevron-down text-xl' />
)} }[header.column.getIsSorted() as 'asc' | 'desc'] ?? null}
</th> </div>
))} </>
</tr> )}
))} </th>
</thead> ))}
{table.getFilteredRowModel().rows.length === 0 ? ( </tr>
<tbody> ))}
<tr> </thead>
<td colSpan={table.getVisibleFlatColumns().length} className='text-center'> {table.getFilteredRowModel().rows.length === 0 ? (
Tidak ada data tersedia <tbody>
</td> <tr>
</tr> <td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
</tbody> Tidak ada data tersedia
) : ( </td>
<tbody> </tr>
{table </tbody>
.getRowModel() ) : (
.rows.slice(0, table.getState().pagination.pageSize) <tbody>
.map(row => { {table
return ( .getRowModel()
<tr key={row.id} className={classnames({ selected: row.getIsSelected() })}> .rows.slice(0, table.getState().pagination.pageSize)
{row.getVisibleCells().map(cell => ( .map(row => {
<td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td> return (
))} <tr key={row.id} className={classnames({ selected: row.getIsSelected() })}>
</tr> {row.getVisibleCells().map(cell => (
) <td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
})} ))}
</tbody> </tr>
)} )
</table> })}
</tbody>
)}
</table>
)}
</div> </div>
<TablePaginationComponent <TablePagination
pageIndex={table.getState().pagination.pageIndex} component={() => (
pageSize={table.getState().pagination.pageSize} <TablePaginationComponent
totalCount={table.getFilteredRowModel().rows.length} pageIndex={currentPage}
onPageChange={(_, page) => { pageSize={pageSize}
table.setPageIndex(page) totalCount={totalCount}
}} onPageChange={handlePageChange}
/>
)}
count={totalCount}
rowsPerPage={pageSize}
page={currentPage}
onPageChange={handlePageChange}
onRowsPerPageChange={handlePageSizeChange}
rowsPerPageOptions={[10, 25, 50]}
disabled={isLoading}
/> />
</Card> </Card>
<AddVendorDrawer {/* <AddVendorDrawer
open={addVendorOpen} open={addVendorOpen}
handleClose={() => setAddVendorOpen(!addVendorOpen)} handleClose={() => setAddVendorOpen(!addVendorOpen)}
vendorData={data} vendorData={data}
setData={setData} setData={setData}
/> /> */}
</> </>
) )
} }