feat: payment & customer

This commit is contained in:
ferdiansyah783
2025-08-07 14:31:42 +07:00
parent a72a64215a
commit a5d22db27b
35 changed files with 2033 additions and 599 deletions
@@ -1,117 +1,93 @@
// React Imports
import { useState } from 'react'
import { use, useEffect, useState } from 'react'
// MUI Imports
import Button from '@mui/material/Button'
import Drawer from '@mui/material/Drawer'
import Divider from '@mui/material/Divider'
import Drawer from '@mui/material/Drawer'
import IconButton from '@mui/material/IconButton'
import MenuItem from '@mui/material/MenuItem'
import Switch from '@mui/material/Switch'
import Typography from '@mui/material/Typography'
// Third-party Imports
import PerfectScrollbar from 'react-perfect-scrollbar'
import { useForm, Controller } from 'react-hook-form'
// Type Imports
import type { Customer } from '@/types/apps/ecommerceTypes'
// Component Imports
import CustomTextField from '@core/components/mui/TextField'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '../../../../../redux-store'
import { useCustomersMutation } from '../../../../../services/mutations/customers'
import { CustomerRequest } from '../../../../../types/services/customer'
import { resetCustomer } from '../../../../../redux-store/slices/customer'
type Props = {
open: boolean
handleClose: () => void
setData: (data: Customer[]) => void
customerData?: Customer[]
}
type FormValidateType = {
fullName: string
email: string
country: string
}
type FormNonValidateType = {
contact: string
address1: string
address2: string
town: string
state: string
postcode: string
}
type countryType = {
country: string
}
export const country: { [key: string]: countryType } = {
india: { country: 'India' },
australia: { country: 'Australia' },
france: { country: 'France' },
brazil: { country: 'Brazil' },
us: { country: 'United States' },
china: { country: 'China' }
}
// Vars
const initialData = {
contact: '',
address1: '',
address2: '',
town: '',
state: '',
postcode: ''
name: '',
email: '',
phone: '',
address: '',
is_active: true
}
const AddCustomerDrawer = (props: Props) => {
const dispatch = useDispatch()
// Props
const { open, handleClose, setData, customerData } = props
const { open, handleClose } = props
const { createCustomer, updateCustomer } = useCustomersMutation()
const { currentCustomer } = useSelector((state: RootState) => state.customerReducer)
// States
const [formData, setFormData] = useState<FormNonValidateType>(initialData)
const [formData, setFormData] = useState<CustomerRequest>(initialData)
// Hooks
const {
control,
reset: resetForm,
handleSubmit,
formState: { errors }
} = useForm<FormValidateType>({
defaultValues: {
fullName: '',
email: '',
country: ''
useEffect(() => {
if (currentCustomer.id) {
setFormData(currentCustomer)
}
})
}, [currentCustomer])
const onSubmit = (data: FormValidateType) => {
const newData: Customer = {
id: (customerData?.length && customerData?.length + 1) || 1,
customer: data.fullName,
customerId: customerData?.[Math.floor(Math.random() * 100) + 1].customerId ?? '1',
email: data.email,
country: `${country[data.country].country}`,
countryCode: 'st',
countryFlag: `/images/cards/${data.country}.png`,
order: Math.floor(Math.random() * 1000) + 1,
totalSpent: Math.floor(Math.random() * (1000000 - 100) + 100) / 100,
avatar: `/images/avatars/${Math.floor(Math.random() * 8) + 1}.png`
const handleSubmit = (e: any) => {
e.preventDefault()
if (currentCustomer.id) {
updateCustomer.mutate(
{ id: currentCustomer.id, payload: formData },
{
onSuccess: () => {
handleReset()
}
}
)
} else {
createCustomer.mutate(formData, {
onSuccess: () => {
handleReset()
}
})
}
setData([...(customerData ?? []), newData])
resetForm({ fullName: '', email: '', country: '' })
setFormData(initialData)
handleClose()
}
const handleReset = () => {
handleClose()
resetForm({ fullName: '', email: '', country: '' })
dispatch(resetCustomer())
setFormData(initialData)
}
const handleInputChange = (e: any) => {
setFormData({
...formData,
[e.target.name]: e.target.value
})
}
return (
<Drawer
open={open}
@@ -122,7 +98,7 @@ const AddCustomerDrawer = (props: Props) => {
sx={{ '& .MuiDrawer-paper': { width: { xs: 300, sm: 400 } } }}
>
<div className='flex items-center justify-between pli-6 plb-5'>
<Typography variant='h5'>Add a Customer</Typography>
<Typography variant='h5'>{currentCustomer.id ? 'Edit' : 'Add'} Customer</Typography>
<IconButton size='small' onClick={handleReset}>
<i className='tabler-x text-2xl' />
</IconButton>
@@ -130,60 +106,26 @@ const AddCustomerDrawer = (props: Props) => {
<Divider />
<PerfectScrollbar options={{ wheelPropagation: false, suppressScrollX: true }}>
<div className='p-6'>
<form onSubmit={handleSubmit(data => onSubmit(data))} className='flex flex-col gap-5'>
<form onSubmit={handleSubmit} className='flex flex-col gap-5'>
<Typography color='text.primary' className='font-medium'>
Basic Information
</Typography>
<Controller
name='fullName'
control={control}
rules={{ required: true }}
render={({ field }) => (
<CustomTextField
{...field}
fullWidth
label='Name'
placeholder='John Doe'
{...(errors.fullName && { error: true, helperText: 'This field is required.' })}
/>
)}
<CustomTextField
fullWidth
label='Name'
name='name'
placeholder='John Doe'
value={formData.name}
onChange={handleInputChange}
/>
<Controller
<CustomTextField
fullWidth
type='email'
label='Email'
name='email'
control={control}
rules={{ required: true }}
render={({ field }) => (
<CustomTextField
{...field}
fullWidth
type='email'
label='Email'
placeholder='johndoe@gmail.com'
{...(errors.email && { error: true, helperText: 'This field is required.' })}
/>
)}
/>
<Controller
name='country'
control={control}
rules={{ required: true }}
render={({ field }) => (
<CustomTextField
select
fullWidth
id='country'
label='Country'
{...field}
{...(errors.country && { error: true, helperText: 'This field is required.' })}
>
<MenuItem value='india'>India</MenuItem>
<MenuItem value='australia'>Australia</MenuItem>
<MenuItem value='france'>France</MenuItem>
<MenuItem value='brazil'>Brazil</MenuItem>
<MenuItem value='us'>USA</MenuItem>
<MenuItem value='china'>China</MenuItem>
</CustomTextField>
)}
placeholder='johndoe@email'
value={formData.email}
onChange={handleInputChange}
/>
<Typography color='text.primary' className='font-medium'>
Shipping Information
@@ -191,63 +133,41 @@ const AddCustomerDrawer = (props: Props) => {
<CustomTextField
fullWidth
label='Address Line 1'
name='address1'
name='address'
placeholder='45 Roker Terrace'
value={formData.address1}
onChange={e => setFormData({ ...formData, address1: e.target.value })}
/>
<CustomTextField
fullWidth
label='Address Line 2'
name='address2'
placeholder='Street 69'
value={formData.address2}
onChange={e => setFormData({ ...formData, address2: e.target.value })}
/>
<CustomTextField
fullWidth
label='Town'
name='town'
placeholder='New York'
value={formData.town}
onChange={e => setFormData({ ...formData, town: e.target.value })}
/>
<CustomTextField
fullWidth
label='State/Province'
name='state'
placeholder='Southern tip'
value={formData.state}
onChange={e => setFormData({ ...formData, state: e.target.value })}
/>
<CustomTextField
fullWidth
label='Post Code'
name='postcode'
placeholder='734990'
value={formData.postcode}
onChange={e => setFormData({ ...formData, postcode: e.target.value })}
value={formData.address}
onChange={handleInputChange}
/>
<CustomTextField
label='Mobile'
type='number'
fullWidth
placeholder='+(123) 456-7890'
value={formData.contact}
onChange={e => setFormData({ ...formData, contact: e.target.value })}
name='phone'
value={formData.phone}
onChange={handleInputChange}
/>
<div className='flex justify-between'>
<div className='flex items-center'>
<div className='flex flex-col items-start gap-1'>
<Typography color='text.primary' className='font-medium'>
Use as a billing address?
Active
</Typography>
<Typography variant='body2'>Please check budget for more info.</Typography>
</div>
<Switch defaultChecked />
<Switch
checked={formData.is_active}
name='is_active'
onChange={e => setFormData({ ...formData, is_active: e.target.checked })}
/>
</div>
<div className='flex items-center gap-4'>
<Button variant='contained' type='submit'>
Add
<Button variant='contained' type='submit' disabled={createCustomer.isPending || updateCustomer.isPending}>
{currentCustomer.id
? updateCustomer.isPending
? 'Updating...'
: 'Update'
: createCustomer.isPending
? 'Creating...'
: 'Create'}
</Button>
<Button variant='tonal' color='error' type='reset' onClick={handleReset}>
Discard
@@ -1,11 +1,9 @@
'use client'
// React Imports
import { useEffect, useMemo, useState } from 'react'
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'
@@ -24,32 +22,30 @@ import {
createColumnHelper,
flexRender,
getCoreRowModel,
getFacetedMinMaxValues,
getFacetedRowModel,
getFacetedUniqueValues,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
useReactTable
} from '@tanstack/react-table'
import classnames from 'classnames'
// Type Imports
import type { Customer } from '@/types/apps/ecommerceTypes'
import type { Locale } from '@configs/i18n'
import type { ThemeColor } from '@core/types'
// Component Imports
import CustomAvatar from '@core/components/mui/Avatar'
import CustomTextField from '@core/components/mui/TextField'
import AddCustomerDrawer from './AddCustomerDrawer'
// Util Imports
import { getInitials } from '@/utils/getInitials'
import { getLocalizedUrl } from '@/utils/i18n'
// Style Imports
import tableStyles from '@core/styles/table.module.css'
import { Box, Chip, CircularProgress, IconButton, TablePagination } from '@mui/material'
import { useDispatch } from 'react-redux'
import OptionMenu from '../../../../../@core/components/option-menu'
import ConfirmDeleteDialog from '../../../../../components/dialogs/confirm-delete'
import Loading from '../../../../../components/layout/shared/Loading'
import TablePaginationComponent from '../../../../../components/TablePaginationComponent'
import { setCustomer } from '../../../../../redux-store/slices/customer'
import { useCustomersMutation } from '../../../../../services/mutations/customers'
import { useCustomers } from '../../../../../services/queries/customers'
import { Customer } from '../../../../../types/services/customer'
declare module '@tanstack/table-core' {
interface FilterFns {
@@ -60,31 +56,8 @@ declare module '@tanstack/table-core' {
}
}
type PayementStatusType = {
text: string
color: ThemeColor
}
type StatusChipColorType = {
color: ThemeColor
}
export const paymentStatus: { [key: number]: PayementStatusType } = {
1: { text: 'Paid', color: 'success' },
2: { text: 'Pending', color: 'warning' },
3: { text: 'Cancelled', color: 'secondary' },
4: { text: 'Failed', color: 'error' }
}
export const statusChipColor: { [key: string]: StatusChipColorType } = {
Delivered: { color: 'success' },
'Out for Delivery': { color: 'primary' },
'Ready to Pickup': { color: 'info' },
Dispatched: { color: 'warning' }
}
type ECommerceOrderTypeWithAction = Customer & {
action?: string
actions?: string
}
const fuzzyFilter: FilterFn<any> = (row, columnId, value, addMeta) => {
@@ -132,15 +105,45 @@ const DebouncedInput = ({
// Column Definitions
const columnHelper = createColumnHelper<ECommerceOrderTypeWithAction>()
const CustomerListTable = ({ customerData }: { customerData?: Customer[] }) => {
const CustomerListTable = () => {
const dispatch = useDispatch()
// States
const [customerUserOpen, setCustomerUserOpen] = useState(false)
const [rowSelection, setRowSelection] = useState({})
const [data, setData] = useState(...[customerData])
const [globalFilter, setGlobalFilter] = useState('')
const [currentPage, setCurrentPage] = useState(1)
const [pageSize, setPageSize] = useState(10)
const [openConfirm, setOpenConfirm] = useState(false)
const [customerId, setCustomerId] = useState('')
const [search, setSearch] = useState('')
// Hooks
const { lang: locale } = useParams()
const { data, isLoading, error, isFetching } = useCustomers({
page: currentPage,
limit: pageSize,
search
})
const { deleteCustomer } = useCustomersMutation()
const customers = data?.data ?? []
const totalCount = data?.total_count ?? 0
const handlePageChange = useCallback((event: unknown, newPage: number) => {
setCurrentPage(newPage)
}, [])
// Handle page size change
const handlePageSizeChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
const newPageSize = parseInt(event.target.value, 10)
setPageSize(newPageSize)
setCurrentPage(1) // Reset to first page
}, [])
const handleDelete = () => {
deleteCustomer.mutate(customerId, {
onSuccess: () => setOpenConfirm(false)
})
}
const columns = useMemo<ColumnDef<ECommerceOrderTypeWithAction, any>[]>(
() => [
@@ -166,49 +169,64 @@ const CustomerListTable = ({ customerData }: { customerData?: Customer[] }) => {
/>
)
},
columnHelper.accessor('customer', {
header: 'Customers',
columnHelper.accessor('name', {
header: 'Name',
cell: ({ row }) => <Typography color='text.primary'>{row.original.name || '-'}</Typography>
}),
columnHelper.accessor('email', {
header: 'Email',
cell: ({ row }) => <Typography color='text.primary'>{row.original.email || '-'}</Typography>
}),
columnHelper.accessor('phone', {
header: 'Phone',
cell: ({ row }) => <Typography>{row.original.phone || '-'}</Typography>
}),
columnHelper.accessor('address', {
header: 'Address',
cell: ({ row }) => <Typography>{row.original.address || '-'}</Typography>
}),
columnHelper.accessor('is_active', {
header: 'Status',
cell: ({ row }) => (
<div className='flex items-center gap-3'>
{getAvatar({ avatar: row.original.avatar, customer: row.original.customer })}
<div className='flex flex-col items-start'>
<Typography
component={Link}
color='text.primary'
href={getLocalizedUrl(`/apps/ecommerce/customers/details/${row.original.customerId}`, locale as Locale)}
className='font-medium hover:text-primary'
>
{row.original.customer}
</Typography>
<Typography variant='body2'>{row.original.email}</Typography>
</div>
<Chip
label={row.original.is_active ? 'Active' : 'Inactive'}
variant='tonal'
color={row.original.is_active ? 'success' : 'error'}
size='small'
/>
)
}),
columnHelper.accessor('actions', {
header: 'Actions',
cell: ({ row }) => (
<div className='flex items-center'>
<IconButton onClick={() => {
dispatch(setCustomer(row.original))
setCustomerUserOpen(true)
}}>
<i className='tabler-edit text-textSecondary' />
</IconButton>
<OptionMenu
iconButtonProps={{ size: 'medium' }}
iconClassName='text-textSecondary'
options={[
{ text: 'Download', icon: 'tabler-download' },
{
text: 'Delete',
icon: 'tabler-trash',
menuItemProps: {
onClick: () => {
setOpenConfirm(true)
setCustomerId(row.original.id)
}
}
},
{ text: 'Duplicate', icon: 'tabler-copy' }
]}
/>
</div>
)
}),
columnHelper.accessor('customerId', {
header: 'Customer Id',
cell: ({ row }) => <Typography color='text.primary'>#{row.original.customerId}</Typography>
}),
columnHelper.accessor('country', {
header: 'Country',
cell: ({ row }) => (
<div className='flex items-center gap-2'>
<img src={row.original.countryFlag} height={22} />
<Typography>{row.original.country}</Typography>
</div>
)
}),
columnHelper.accessor('order', {
header: 'Orders',
cell: ({ row }) => <Typography>{row.original.order}</Typography>
}),
columnHelper.accessor('totalSpent', {
header: 'Total Spent',
cell: ({ row }) => (
<Typography className='font-medium' color='text.primary'>
${row.original.totalSpent.toLocaleString()}
</Typography>
)
),
enableSorting: false
})
],
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -216,63 +234,41 @@ const CustomerListTable = ({ customerData }: { customerData?: Customer[] }) => {
)
const table = useReactTable({
data: data as Customer[],
data: customers as Customer[],
columns,
filterFns: {
fuzzy: fuzzyFilter
},
state: {
rowSelection,
globalFilter
},
initialState: {
pagination: {
pageSize: 10
pageIndex: currentPage,
pageSize
}
},
enableRowSelection: true, //enable row selection for all rows
// enableRowSelection: row => row.original.age > 18, // or enable row selection conditionally per row
globalFilterFn: fuzzyFilter,
onRowSelectionChange: setRowSelection,
getCoreRowModel: getCoreRowModel(),
onGlobalFilterChange: setGlobalFilter,
getFilteredRowModel: getFilteredRowModel(),
getSortedRowModel: getSortedRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getFacetedRowModel: getFacetedRowModel(),
getFacetedUniqueValues: getFacetedUniqueValues(),
getFacetedMinMaxValues: getFacetedMinMaxValues()
// Disable client-side pagination since we're handling it server-side
manualPagination: true,
pageCount: Math.ceil(totalCount / pageSize)
})
const getAvatar = (params: Pick<Customer, 'avatar' | 'customer'>) => {
const { avatar, customer } = params
if (avatar) {
return <CustomAvatar src={avatar} skin='light' size={34} />
} else {
return (
<CustomAvatar skin='light' size={34}>
{getInitials(customer as string)}
</CustomAvatar>
)
}
}
return (
<>
<Card>
<CardContent className='flex justify-between flex-wrap max-sm:flex-col sm:items-center gap-4'>
<DebouncedInput
value={globalFilter ?? ''}
onChange={value => setGlobalFilter(String(value))}
value={search}
onChange={value => setSearch(value as string)}
placeholder='Search'
className='max-sm:is-full'
/>
<div className='flex max-sm:flex-col items-start sm:items-center gap-4 max-sm:is-full'>
<CustomTextField
select
value={table.getState().pagination.pageSize}
onChange={e => table.setPageSize(Number(e.target.value))}
value={pageSize}
onChange={handlePageSizeChange}
className='is-full sm:is-[70px]'
>
<MenuItem value='10'>10</MenuItem>
@@ -300,75 +296,110 @@ const CustomerListTable = ({ customerData }: { customerData?: Customer[] }) => {
</div>
</CardContent>
<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>
{table.getFilteredRowModel().rows.length === 0 ? (
<tbody>
<tr>
<td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
No data available
</td>
</tr>
</tbody>
) : (
<tbody>
{table
.getRowModel()
.rows.slice(0, table.getState().pagination.pageSize)
.map(row => {
return (
<tr key={row.id} className={classnames({ selected: row.getIsSelected() })}>
{row.getVisibleCells().map(cell => (
<td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
))}
</tr>
)
})}
</tbody>
)}
</table>
{isLoading ? (
<Loading />
) : (
<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>
{table.getFilteredRowModel().rows.length === 0 ? (
<tbody>
<tr>
<td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
No data available
</td>
</tr>
</tbody>
) : (
<tbody>
{table
.getRowModel()
.rows.slice(0, table.getState().pagination.pageSize)
.map(row => {
return (
<tr key={row.id} className={classnames({ selected: row.getIsSelected() })}>
{row.getVisibleCells().map(cell => (
<td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
))}
</tr>
)
})}
</tbody>
)}
</table>
)}
{isFetching && !isLoading && (
<Box
position='absolute'
top={0}
left={0}
right={0}
bottom={0}
display='flex'
alignItems='center'
justifyContent='center'
bgcolor='rgba(255,255,255,0.7)'
zIndex={1}
>
<CircularProgress size={24} />
</Box>
)}
</div>
{/* <TablePagination
component={() => <TablePaginationComponent table={table} />}
count={table.getFilteredRowModel().rows.length}
rowsPerPage={table.getState().pagination.pageSize}
page={table.getState().pagination.pageIndex}
onPageChange={(_, page) => {
table.setPageIndex(page)
}}
/> */}
<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]}
disabled={isLoading}
/>
</Card>
<AddCustomerDrawer
open={customerUserOpen}
handleClose={() => setCustomerUserOpen(!customerUserOpen)}
setData={setData}
customerData={data}
<AddCustomerDrawer open={customerUserOpen} handleClose={() => setCustomerUserOpen(!customerUserOpen)} />
<ConfirmDeleteDialog
open={openConfirm}
onClose={() => setOpenConfirm(false)}
onConfirm={handleDelete}
isLoading={deleteCustomer.isPending}
title='Delete Customer'
message='Are you sure you want to delete this customer? This action cannot be undone.'
/>
</>
)