Compare commits

...

2 Commits

Author SHA1 Message Date
efrilm
8ed2786bc2 tier 2025-09-17 20:54:54 +07:00
efrilm
4655411b24 tier page 2025-09-17 20:21:28 +07:00
12 changed files with 1307 additions and 3 deletions

View File

@ -0,0 +1,7 @@
import TierList from '@/views/apps/marketing/tier'
const TierPage = () => {
return <TierList />
}
export default TierPage

View File

@ -166,6 +166,7 @@ const VerticalMenu = ({ dictionary, scrollMenu }: Props) => {
{dictionary['navigation'].customer_analytics} {dictionary['navigation'].customer_analytics}
</MenuItem> </MenuItem>
<MenuItem href={`/${locale}/apps/marketing/voucher`}>{dictionary['navigation'].voucher}</MenuItem> <MenuItem href={`/${locale}/apps/marketing/voucher`}>{dictionary['navigation'].voucher}</MenuItem>
<MenuItem href={`/${locale}/apps/marketing/tier`}>{dictionary['navigation'].tiers_text}</MenuItem>
</SubMenu> </SubMenu>
<SubMenu label={dictionary['navigation'].inventory} icon={<i className='tabler-salad' />}> <SubMenu label={dictionary['navigation'].inventory} icon={<i className='tabler-salad' />}>
<SubMenu label={dictionary['navigation'].products}> <SubMenu label={dictionary['navigation'].products}>

View File

@ -134,6 +134,7 @@
"wheel_spin": "Wheel Spin", "wheel_spin": "Wheel Spin",
"campaign": "Campaign", "campaign": "Campaign",
"customer_analytics": "Customer Analytics", "customer_analytics": "Customer Analytics",
"voucher": "Voucher" "voucher": "Voucher",
"tiers_text": "Tiers"
} }
} }

View File

@ -134,6 +134,7 @@
"wheel_spin": "Wheel Spin", "wheel_spin": "Wheel Spin",
"campaign": "Kampanye", "campaign": "Kampanye",
"customer_analytics": "Analisis Pelanggan", "customer_analytics": "Analisis Pelanggan",
"voucher": "Vocher" "voucher": "Vocher",
"tiers_text": "Tiers"
} }
} }

View File

@ -6,7 +6,8 @@ const getToken = () => {
} }
export const api = axios.create({ export const api = axios.create({
baseURL: 'https://enaklo-pos-be.altru.id/api/v1', // baseURL: 'https://enaklo-pos-be.altru.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,52 @@
import { TierRequest } from '@/types/services/tier'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'react-toastify'
import { api } from '../api'
export const useTiersMutation = () => {
const queryClient = useQueryClient()
const createTier = useMutation({
mutationFn: async (newTier: TierRequest) => {
const response = await api.post('/marketing/tiers', newTier)
return response.data
},
onSuccess: () => {
toast.success('Tier created successfully!')
queryClient.invalidateQueries({ queryKey: ['tiers'] })
},
onError: (error: any) => {
toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
}
})
const updateTier = useMutation({
mutationFn: async ({ id, payload }: { id: string; payload: TierRequest }) => {
const response = await api.put(`/marketing/tiers/${id}`, payload)
return response.data
},
onSuccess: () => {
toast.success('Tier updated successfully!')
queryClient.invalidateQueries({ queryKey: ['tiers'] })
},
onError: (error: any) => {
toast.error(error.response?.data?.errors?.[0]?.cause || 'Update failed')
}
})
const deleteTier = useMutation({
mutationFn: async (id: string) => {
const response = await api.delete(`/marketing/tiers/${id}`)
return response.data
},
onSuccess: () => {
toast.success('Tier deleted successfully!')
queryClient.invalidateQueries({ queryKey: ['tiers'] })
},
onError: (error: any) => {
toast.error(error.response?.data?.errors?.[0]?.cause || 'Delete failed')
}
})
return { createTier, updateTier, deleteTier }
}

View File

@ -0,0 +1,46 @@
import { useQuery } from '@tanstack/react-query'
import { api } from '../api'
import { Tier, Tiers } from '@/types/services/tier'
interface TierQueryParams {
page?: number
limit?: number
search?: string
}
export function useTiers(params: TierQueryParams = {}) {
const { page = 1, limit = 10, search = '', ...filters } = params
return useQuery<Tiers>({
queryKey: ['tiers', { 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(`/marketing/tiers?${queryParams.toString()}`)
return res.data.data
}
})
}
export function useTierById(id: string) {
return useQuery<Tier>({
queryKey: ['tiers', id],
queryFn: async () => {
const res = await api.get(`/marketing/tiers/${id}`)
return res.data.data
}
})
}

View File

@ -0,0 +1,22 @@
export interface Tier {
id: string // uuid
name: string
min_points: number
benefits: Record<string, any>
created_at: string // ISO datetime
updated_at: string // ISO datetime
}
export interface Tiers {
data: Tier[]
total_count: number
page: number
limit: number
total_pages: number
}
export interface TierRequest {
name: string
min_points: number
benefits: Record<string, any>
}

View File

@ -0,0 +1,501 @@
// 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 Divider from '@mui/material/Divider'
import Grid from '@mui/material/Grid2'
import Box from '@mui/material/Box'
import Switch from '@mui/material/Switch'
import FormControlLabel from '@mui/material/FormControlLabel'
import Chip from '@mui/material/Chip'
import InputAdornment from '@mui/material/InputAdornment'
import Select from '@mui/material/Select'
import FormControl from '@mui/material/FormControl'
import InputLabel from '@mui/material/InputLabel'
// Third-party Imports
import { useForm, Controller } from 'react-hook-form'
// Component Imports
import CustomTextField from '@core/components/mui/TextField'
import { Tier, TierRequest } from '@/types/services/tier'
import { useTiersMutation } from '@/services/mutations/tier'
type Props = {
open: boolean
handleClose: () => void
data?: Tier // Data tier untuk edit (jika ada)
}
// Benefit item type
type BenefitItem = {
key: string
value: any
type: 'boolean' | 'number' | 'string'
}
type FormValidateType = {
name: string
min_points: number
benefits: BenefitItem[]
newBenefitKey: string
newBenefitValue: string
newBenefitType: 'boolean' | 'number' | 'string'
}
// Initial form data
const initialData: FormValidateType = {
name: '',
min_points: 0,
benefits: [],
newBenefitKey: '',
newBenefitValue: '',
newBenefitType: 'boolean'
}
const AddEditTierDrawer = (props: Props) => {
// Props
const { open, handleClose, data } = props
// States
const [showMore, setShowMore] = useState(false)
const [isSubmitting, setIsSubmitting] = useState(false)
const { createTier, updateTier } = useTiersMutation()
// Determine if this is edit mode
const isEditMode = Boolean(data?.id)
// Hooks
const {
control,
reset: resetForm,
handleSubmit,
watch,
setValue,
formState: { errors }
} = useForm<FormValidateType>({
defaultValues: initialData
})
const watchedBenefits = watch('benefits')
const watchedNewBenefitKey = watch('newBenefitKey')
const watchedNewBenefitValue = watch('newBenefitValue')
const watchedNewBenefitType = watch('newBenefitType')
// Helper function to convert benefits object to BenefitItem array
const convertBenefitsToArray = (benefits: Record<string, any>): BenefitItem[] => {
if (!benefits) return []
return Object.entries(benefits).map(([key, value]) => ({
key,
value,
type: typeof value === 'boolean' ? 'boolean' : typeof value === 'number' ? 'number' : 'string'
}))
}
// Helper function to convert BenefitItem array to benefits object
const convertBenefitsToObject = (benefits: BenefitItem[]): Record<string, any> => {
const benefitsObj: Record<string, any> = {}
benefits.forEach(benefit => {
let value = benefit.value
// Convert string values to appropriate types
if (benefit.type === 'boolean') {
value = value === true || value === 'true' || value === 'yes'
} else if (benefit.type === 'number') {
value = Number(value)
}
benefitsObj[benefit.key] = value
})
return benefitsObj
}
// Helper function to format benefit display
const formatBenefitDisplay = (item: BenefitItem): string => {
const readableKey = item.key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())
if (item.type === 'boolean') {
return `${readableKey}: ${item.value ? 'Ya' : 'Tidak'}`
} else if (item.type === 'number') {
if (item.key.includes('multiplier')) {
return `${readableKey}: ${item.value}x`
} else if (item.key.includes('discount') || item.key.includes('bonus')) {
return `${readableKey}: ${item.value}%`
}
return `${readableKey}: ${item.value}`
}
return `${readableKey}: ${item.value}`
}
// Effect to populate form when editing
useEffect(() => {
if (isEditMode && data) {
// Convert benefits object to array for form handling
const benefitsArray = convertBenefitsToArray(data.benefits)
// Populate form with existing data
const formData: FormValidateType = {
name: data.name || '',
min_points: data.min_points || 0,
benefits: benefitsArray,
newBenefitKey: '',
newBenefitValue: '',
newBenefitType: 'boolean'
}
resetForm(formData)
setShowMore(true) // Always show more for edit mode
} else {
// Reset to initial data for add mode
resetForm(initialData)
setShowMore(false)
}
}, [data, isEditMode, resetForm])
const handleAddBenefit = () => {
const key = watchedNewBenefitKey.trim()
const value = watchedNewBenefitValue.trim()
const type = watchedNewBenefitType
if (key && value) {
// Check if key already exists
const existingKeys = watchedBenefits.map(b => b.key)
if (existingKeys.includes(key)) {
alert('Key benefit sudah ada!')
return
}
let processedValue: any = value
if (type === 'boolean') {
processedValue = value === 'true' || value === 'yes' || value === '1'
} else if (type === 'number') {
processedValue = Number(value)
if (isNaN(processedValue)) {
alert('Nilai harus berupa angka!')
return
}
}
const newBenefit: BenefitItem = {
key,
value: processedValue,
type
}
const currentBenefits = watchedBenefits || []
setValue('benefits', [...currentBenefits, newBenefit])
setValue('newBenefitKey', '')
setValue('newBenefitValue', '')
setValue('newBenefitType', 'boolean')
}
}
const handleRemoveBenefit = (index: number) => {
const currentBenefits = watchedBenefits || []
const newBenefits = currentBenefits.filter((_, i) => i !== index)
setValue('benefits', newBenefits)
}
const handleKeyPress = (event: React.KeyboardEvent) => {
if (event.key === 'Enter') {
event.preventDefault()
handleAddBenefit()
}
}
const handleFormSubmit = async (formData: FormValidateType) => {
try {
setIsSubmitting(true)
// Convert benefits array back to object format
const benefitsObj = convertBenefitsToObject(formData.benefits)
// Create TierRequest object
const tierRequest: TierRequest = {
name: formData.name,
min_points: formData.min_points,
benefits: benefitsObj
}
console.log('Submitting tier data:', tierRequest)
if (isEditMode && data?.id) {
// Update existing tier
updateTier.mutate(
{ id: data.id, payload: tierRequest },
{
onSuccess: () => {
handleReset()
handleClose()
}
}
)
} else {
// Create new tier
createTier.mutate(tierRequest, {
onSuccess: () => {
handleReset()
handleClose()
}
})
}
} catch (error) {
console.error('Error submitting tier:', error)
// Handle error (show toast, etc.)
} finally {
setIsSubmitting(false)
}
}
const handleReset = () => {
handleClose()
resetForm(initialData)
setShowMore(false)
}
const formatNumber = (value: number) => {
return new Intl.NumberFormat('id-ID').format(value)
}
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'>{isEditMode ? 'Edit Tier' : 'Tambah Tier 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='tier-form' onSubmit={handleSubmit(handleFormSubmit)}>
<div className='flex flex-col gap-6 p-6'>
{/* Nama Tier */}
<div>
<Typography variant='body2' className='mb-2'>
Nama Tier <span className='text-red-500'>*</span>
</Typography>
<Controller
name='name'
control={control}
rules={{ required: 'Nama tier wajib diisi' }}
render={({ field }) => (
<CustomTextField
{...field}
fullWidth
placeholder='Masukkan nama tier (contoh: Bronze, Silver, Gold)'
error={!!errors.name}
helperText={errors.name?.message}
/>
)}
/>
</div>
{/* Minimum Points */}
<div>
<Typography variant='body2' className='mb-2'>
Minimum Poin <span className='text-red-500'>*</span>
</Typography>
<Controller
name='min_points'
control={control}
rules={{
required: 'Minimum poin wajib diisi',
min: {
value: 0,
message: 'Minimum poin tidak boleh negatif'
}
}}
render={({ field }) => (
<CustomTextField
{...field}
fullWidth
type='number'
placeholder='0'
error={!!errors.min_points}
helperText={
errors.min_points?.message || (field.value > 0 ? `${formatNumber(field.value)} poin` : '')
}
InputProps={{
endAdornment: <InputAdornment position='end'>poin</InputAdornment>
}}
onChange={e => field.onChange(Number(e.target.value))}
/>
)}
/>
</div>
{/* Benefits */}
<div>
<Typography variant='body2' className='mb-2'>
Manfaat Tier <span className='text-red-500'>*</span>
</Typography>
{/* Display current benefits */}
{watchedBenefits && watchedBenefits.length > 0 && (
<div className='flex flex-col gap-2 mb-3'>
{watchedBenefits.map((benefit, index) => (
<Chip
key={index}
label={formatBenefitDisplay(benefit)}
onDelete={() => handleRemoveBenefit(index)}
color='primary'
variant='outlined'
size='small'
sx={{
justifyContent: 'space-between',
'& .MuiChip-label': {
overflow: 'visible',
textOverflow: 'unset',
whiteSpace: 'normal'
}
}}
/>
))}
</div>
)}
{/* Add new benefit - Key */}
<div className='mb-3'>
<Controller
name='newBenefitKey'
control={control}
render={({ field }) => (
<CustomTextField
{...field}
fullWidth
placeholder='Key benefit (contoh: birthday_bonus, point_multiplier)'
label='Key Benefit'
size='small'
/>
)}
/>
</div>
{/* Type selector */}
<div className='mb-3'>
<Controller
name='newBenefitType'
control={control}
render={({ field }) => (
<FormControl fullWidth size='small'>
<InputLabel>Tipe Value</InputLabel>
<Select {...field} label='Tipe Value'>
<MenuItem value='boolean'>Boolean (Ya/Tidak)</MenuItem>
<MenuItem value='number'>Number (Angka)</MenuItem>
<MenuItem value='string'>String (Teks)</MenuItem>
</Select>
</FormControl>
)}
/>
</div>
{/* Add new benefit - Value */}
<div className='mb-3'>
<Controller
name='newBenefitValue'
control={control}
render={({ field }) => (
<CustomTextField
{...field}
fullWidth
placeholder={
watchedNewBenefitType === 'boolean'
? 'true/false, yes/no, 1/0'
: watchedNewBenefitType === 'number'
? 'Contoh: 1.5, 10, 5'
: 'Contoh: Premium access, VIP status'
}
label='Value Benefit'
size='small'
onKeyPress={handleKeyPress}
InputProps={{
endAdornment: (
<InputAdornment position='end'>
<Button
size='small'
onClick={handleAddBenefit}
disabled={!watchedNewBenefitKey?.trim() || !watchedNewBenefitValue?.trim()}
>
Tambah
</Button>
</InputAdornment>
)
}}
/>
)}
/>
</div>
{(!watchedBenefits || watchedBenefits.length === 0) && (
<Typography variant='caption' color='error'>
Minimal satu manfaat harus ditambahkan
</Typography>
)}
</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='tier-form'
disabled={isSubmitting || !watchedBenefits || watchedBenefits.length === 0}
startIcon={isSubmitting ? <i className='tabler-loader animate-spin' /> : null}
>
{isSubmitting ? (isEditMode ? 'Mengupdate...' : 'Menyimpan...') : isEditMode ? 'Update' : 'Simpan'}
</Button>
<Button variant='outlined' color='error' onClick={handleReset} disabled={isSubmitting}>
Batal
</Button>
</div>
</Box>
</Drawer>
)
}
export default AddEditTierDrawer

View File

@ -0,0 +1,106 @@
// React Imports
import { useState } from 'react'
// MUI Imports
import Dialog from '@mui/material/Dialog'
import DialogTitle from '@mui/material/DialogTitle'
import DialogContent from '@mui/material/DialogContent'
import DialogActions from '@mui/material/DialogActions'
import DialogContentText from '@mui/material/DialogContentText'
import Button from '@mui/material/Button'
import Typography from '@mui/material/Typography'
import Box from '@mui/material/Box'
import Alert from '@mui/material/Alert'
// Types
import { Tier } from '@/types/services/tier'
type Props = {
open: boolean
onClose: () => void
onConfirm: () => void
tier: Tier | null
isDeleting?: boolean
}
const DeleteTierDialog = ({ open, onClose, onConfirm, tier, isDeleting = false }: Props) => {
if (!tier) return null
return (
<Dialog
open={open}
onClose={onClose}
maxWidth='sm'
fullWidth
aria-labelledby='delete-dialog-title'
aria-describedby='delete-dialog-description'
>
<DialogTitle id='delete-dialog-title'>
<Box display='flex' alignItems='center' gap={2}>
<i className='tabler-trash text-red-500 text-2xl' />
<Typography variant='h6'>Hapus Tier</Typography>
</Box>
</DialogTitle>
<DialogContent>
<DialogContentText id='delete-dialog-description' className='mb-4'>
Apakah Anda yakin ingin menghapus tier berikut?
</DialogContentText>
<Box
sx={{
backgroundColor: 'grey.50',
p: 2,
borderRadius: 1,
border: '1px solid',
borderColor: 'grey.200',
mb: 2
}}
>
<Typography variant='subtitle2' className='font-medium mb-1'>
{tier.name}
</Typography>
<Typography variant='body2' color='text.secondary' className='mb-1'>
Minimum Poin: {new Intl.NumberFormat('id-ID').format(tier.min_points)} poin
</Typography>
<Typography variant='body2' color='text.secondary'>
Dibuat:{' '}
{new Date(tier.created_at).toLocaleDateString('id-ID', {
year: 'numeric',
month: 'long',
day: 'numeric'
})}
</Typography>
</Box>
<Alert severity='warning' sx={{ mb: 2 }}>
<Typography variant='body2'>
<strong>Peringatan:</strong> Tindakan ini tidak dapat dibatalkan. Semua data yang terkait dengan tier ini
akan dihapus secara permanen.
</Typography>
</Alert>
<DialogContentText>
Pastikan tidak ada pengguna yang masih menggunakan tier ini sebelum menghapus.
</DialogContentText>
</DialogContent>
<DialogActions className='p-4'>
<Button onClick={onClose} variant='outlined' disabled={isDeleting}>
Batal
</Button>
<Button
onClick={onConfirm}
color='error'
variant='contained'
disabled={isDeleting}
startIcon={isDeleting ? <i className='tabler-loader animate-spin' /> : <i className='tabler-trash' />}
>
{isDeleting ? 'Menghapus...' : 'Hapus'}
</Button>
</DialogActions>
</Dialog>
)
}
export default DeleteTierDialog

View File

@ -0,0 +1,549 @@
'use client'
// React Imports
import { useEffect, useState, useMemo, useCallback } from 'react'
// Next Imports
import Link from 'next/link'
import { useParams } from 'next/navigation'
// MUI Imports
import Card from '@mui/material/Card'
import CardHeader from '@mui/material/CardHeader'
import Button from '@mui/material/Button'
import Typography from '@mui/material/Typography'
import Chip from '@mui/material/Chip'
import Checkbox from '@mui/material/Checkbox'
import IconButton from '@mui/material/IconButton'
import { styled } from '@mui/material/styles'
import TablePagination from '@mui/material/TablePagination'
import type { TextFieldProps } from '@mui/material/TextField'
import MenuItem from '@mui/material/MenuItem'
// Third-party Imports
import classnames from 'classnames'
import { rankItem } from '@tanstack/match-sorter-utils'
import {
createColumnHelper,
flexRender,
getCoreRowModel,
useReactTable,
getFilteredRowModel,
getFacetedRowModel,
getFacetedUniqueValues,
getFacetedMinMaxValues,
getPaginationRowModel,
getSortedRowModel
} from '@tanstack/react-table'
import type { ColumnDef, FilterFn } from '@tanstack/react-table'
import type { RankingInfo } from '@tanstack/match-sorter-utils'
// Type Imports
import type { ThemeColor } from '@core/types'
import type { Locale } from '@configs/i18n'
// Component Imports
import OptionMenu from '@core/components/option-menu'
import TablePaginationComponent from '@components/TablePaginationComponent'
import CustomTextField from '@core/components/mui/TextField'
import CustomAvatar from '@core/components/mui/Avatar'
// Util Imports
import { getInitials } from '@/utils/getInitials'
import { getLocalizedUrl } from '@/utils/i18n'
import { formatCurrency } from '@/utils/transform'
// Style Imports
import tableStyles from '@core/styles/table.module.css'
import Loading from '@/components/layout/shared/Loading'
import AddEditTierDrawer from './AddTierDrawer'
import DeleteTierDialog from './DeleteTierDialog'
import { Tier } from '@/types/services/tier'
import { useTiers } from '@/services/queries/tier'
import { useTiersMutation } from '@/services/mutations/tier'
declare module '@tanstack/table-core' {
interface FilterFns {
fuzzy: FilterFn<unknown>
}
interface FilterMeta {
itemRank: RankingInfo
}
}
type TierTypeWithAction = Tier & {
action?: string
}
// 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)} />
}
// Helper function to get all benefits as array
const getAllBenefits = (benefits: Record<string, any>): Array<{ key: string; value: any; display: string }> => {
return Object.entries(benefits).map(([key, value]) => ({
key,
value,
display: formatBenefitDisplay(key, value)
}))
}
const formatBenefitDisplay = (key: string, value: any): string => {
// Convert snake_case to readable format
const readableKey = key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())
if (value === true) {
return readableKey
}
if (value === false) {
return `${readableKey} (Tidak Aktif)`
}
if (typeof value === 'number') {
// Handle multipliers
if (key.includes('multiplier')) {
return `${readableKey} ${value}x`
}
// Handle percentages
if (key.includes('discount') || key.includes('bonus')) {
return `${readableKey} ${value}%`
}
// Default number formatting
return `${readableKey} ${value}`
}
return `${readableKey}: ${value}`
}
// Helper function to format points
const formatPoints = (points: number) => {
return new Intl.NumberFormat('id-ID').format(points)
}
// Mock mutation hook for delete (replace with actual hook)
// Column Definitions
const columnHelper = createColumnHelper<TierTypeWithAction>()
const TierListTable = () => {
// States
const [addTierOpen, setAddTierOpen] = useState(false)
const [editTierData, setEditTierData] = useState<Tier | undefined>(undefined)
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
const [tierToDelete, setTierToDelete] = useState<Tier | null>(null)
const [rowSelection, setRowSelection] = useState({})
const [globalFilter, setGlobalFilter] = useState('')
const [currentPage, setCurrentPage] = useState(1)
const [pageSize, setPageSize] = useState(10)
const [search, setSearch] = useState('')
const { data, isLoading, error, isFetching } = useTiers({
page: currentPage,
limit: pageSize,
search
})
const { deleteTier } = useTiersMutation()
const tiers = data?.data ?? []
const totalCount = data?.total_count ?? 0
// Hooks
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 handleEditTier = (tier: Tier) => {
setEditTierData(tier)
setAddTierOpen(true)
}
const handleDeleteTier = (tier: Tier) => {
setTierToDelete(tier)
setDeleteDialogOpen(true)
}
const handleConfirmDelete = () => {
if (tierToDelete) {
deleteTier.mutate(tierToDelete.id, {
onSuccess: () => {
console.log('Tier deleted successfully')
setDeleteDialogOpen(false)
setTierToDelete(null)
// You might want to refetch data here
// refetch()
},
onError: error => {
console.error('Error deleting tier:', error)
// Handle error (show toast, etc.)
}
})
}
}
const handleCloseDeleteDialog = () => {
if (!deleteTier.isPending) {
setDeleteDialogOpen(false)
setTierToDelete(null)
}
}
const handleCloseTierDrawer = () => {
setAddTierOpen(false)
setEditTierData(undefined)
}
const columns = useMemo<ColumnDef<TierTypeWithAction, 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('name', {
header: 'Nama Tier',
cell: ({ row }) => (
<div className='flex items-center gap-4'>
<div className='flex flex-col'>
<Link href={getLocalizedUrl(`/apps/tier/${row.original.id}/detail`, locale as Locale)}>
<Typography className='font-medium cursor-pointer hover:underline text-primary'>
{row.original.name}
</Typography>
</Link>
</div>
</div>
)
}),
columnHelper.accessor('min_points', {
header: 'Minimum Poin',
cell: ({ row }) => (
<div className='flex items-center gap-2'>
<Icon className='tabler-star' sx={{ color: 'var(--mui-palette-warning-main)' }} />
<Typography color='text.primary'>{formatPoints(row.original.min_points)} poin</Typography>
</div>
)
}),
columnHelper.accessor('benefits', {
header: 'Manfaat',
cell: ({ row }) => {
const allBenefits = getAllBenefits(row.original.benefits)
if (allBenefits.length === 0) {
return (
<Typography variant='body2' color='text.secondary'>
Tidak ada manfaat
</Typography>
)
}
return (
<div className='flex flex-wrap gap-1 max-w-xs'>
{allBenefits.slice(0, 2).map((benefit, index) => {
// Different colors for different value types
let chipColor: 'default' | 'primary' | 'secondary' | 'error' | 'info' | 'success' | 'warning' =
'secondary'
if (benefit.value === false) {
chipColor = 'default'
} else if (benefit.value === true) {
chipColor = 'success'
} else if (typeof benefit.value === 'number') {
chipColor = 'info'
}
return (
<Chip
key={benefit.key}
label={benefit.display}
size='small'
variant='outlined'
color={chipColor}
title={benefit.display} // Tooltip for full text
/>
)
})}
{allBenefits.length > 2 && (
<Chip
label={`+${allBenefits.length - 2} lainnya`}
size='small'
variant='outlined'
color='default'
title={allBenefits
.slice(2)
.map(b => b.display)
.join(', ')} // Show remaining benefits in tooltip
/>
)}
</div>
)
}
}),
columnHelper.accessor('created_at', {
header: 'Tanggal Dibuat',
cell: ({ row }) => (
<Typography color='text.primary'>
{new Date(row.original.created_at).toLocaleDateString('id-ID', {
year: 'numeric',
month: 'short',
day: 'numeric'
})}
</Typography>
)
}),
{
id: 'actions',
header: 'Aksi',
cell: ({ row }) => (
<div className='flex items-center'>
<OptionMenu
iconButtonProps={{ size: 'medium' }}
iconClassName='text-textSecondary text-[22px]'
options={[
{
text: 'Edit',
icon: 'tabler-edit text-[22px]',
menuItemProps: {
className: 'flex items-center gap-2 text-textSecondary',
onClick: () => handleEditTier(row.original)
}
},
{
text: 'Hapus',
icon: 'tabler-trash text-[22px]',
menuItemProps: {
className: 'flex items-center gap-2 text-textSecondary',
onClick: () => handleDeleteTier(row.original)
}
}
]}
/>
</div>
),
enableSorting: false
}
],
// eslint-disable-next-line react-hooks/exhaustive-deps
[locale, handleEditTier, handleDeleteTier]
)
const table = useReactTable({
data: tiers as Tier[],
columns,
filterFns: {
fuzzy: fuzzyFilter
},
state: {
rowSelection,
globalFilter,
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'>
<CustomTextField
select
value={table.getState().pagination.pageSize}
onChange={e => table.setPageSize(Number(e.target.value))}
className='max-sm:is-full sm:is-[70px]'
>
<MenuItem value='10'>10</MenuItem>
<MenuItem value='25'>25</MenuItem>
<MenuItem value='50'>50</MenuItem>
</CustomTextField>
<div className='flex flex-col sm:flex-row max-sm:is-full items-start sm:items-center gap-4'>
<DebouncedInput
value={search ?? ''}
onChange={value => setSearch(value as string)}
placeholder='Cari Tier'
className='max-sm:is-full'
/>
<Button
color='secondary'
variant='tonal'
startIcon={<i className='tabler-upload' />}
className='max-sm:is-full'
>
Ekspor
</Button>
<Button
variant='contained'
startIcon={<i className='tabler-plus' />}
onClick={() => setAddTierOpen(!addTierOpen)}
className='max-sm:is-full'
>
Tambah Tier
</Button>
</div>
</div>
<div className='overflow-x-auto'>
{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'>
Tidak ada data tersedia
</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>
)}
</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]}
disabled={isLoading}
/>
</Card>
{/* Add/Edit Tier Drawer */}
<AddEditTierDrawer open={addTierOpen} handleClose={handleCloseTierDrawer} data={editTierData} />
{/* Delete Confirmation Dialog */}
<DeleteTierDialog
open={deleteDialogOpen}
onClose={handleCloseDeleteDialog}
onConfirm={handleConfirmDelete}
tier={tierToDelete}
isDeleting={deleteTier.isPending}
/>
</>
)
}
export default TierListTable

View File

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