Compare commits
3 Commits
ddbd5ba607
...
966081214f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
966081214f | ||
|
|
1c5740a85b | ||
|
|
f527b6f004 |
@ -0,0 +1,7 @@
|
||||
import WheelSpinList from '@/views/apps/marketing/gamification/wheel-spin'
|
||||
|
||||
const WheelSpinPage = () => {
|
||||
return <WheelSpinList />
|
||||
}
|
||||
|
||||
export default WheelSpinPage
|
||||
@ -0,0 +1,7 @@
|
||||
import LoyaltyList from '@/views/apps/marketing/loyalty'
|
||||
|
||||
const LoyaltiPage = () => {
|
||||
return <LoyaltyList />
|
||||
}
|
||||
|
||||
export default LoyaltiPage
|
||||
@ -0,0 +1,7 @@
|
||||
import RewardList from '@/views/apps/marketing/reward'
|
||||
|
||||
const RewardPage = () => {
|
||||
return <RewardList />
|
||||
}
|
||||
|
||||
export default RewardPage
|
||||
@ -153,6 +153,15 @@ const VerticalMenu = ({ dictionary, scrollMenu }: Props) => {
|
||||
>
|
||||
{dictionary['navigation'].reports}
|
||||
</MenuItem>
|
||||
<SubMenu label={dictionary['navigation'].marketing} icon={<i className='tabler-shopping-cart' />}>
|
||||
<MenuItem href={`/${locale}/apps/marketing/loyalty`}>{dictionary['navigation'].loyalty}</MenuItem>
|
||||
<MenuItem href={`/${locale}/apps/marketing/reward`}>{dictionary['navigation'].reward}</MenuItem>
|
||||
<SubMenu label={dictionary['navigation'].gamification}>
|
||||
<MenuItem href={`/${locale}/apps/marketing/gamification/wheel-spin`}>
|
||||
{dictionary['navigation'].wheel_spin}
|
||||
</MenuItem>
|
||||
</SubMenu>
|
||||
</SubMenu>
|
||||
<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>
|
||||
|
||||
@ -126,6 +126,11 @@
|
||||
"expenses": "Expenses",
|
||||
"cash_and_bank": "Cash & Bank",
|
||||
"account": "Account",
|
||||
"fixed_assets": "Fixed Assets"
|
||||
"fixed_assets": "Fixed Assets",
|
||||
"marketing": "Marketing",
|
||||
"loyalty": "Loyalty",
|
||||
"reward": "Reward",
|
||||
"gamification": "Gamification",
|
||||
"wheel_spin": "Wheel Spin"
|
||||
}
|
||||
}
|
||||
|
||||
@ -126,6 +126,11 @@
|
||||
"expenses": "Biaya",
|
||||
"cash_and_bank": "Kas & Bank",
|
||||
"account": "Akun",
|
||||
"fixed_assets": "Aset Tetap"
|
||||
"fixed_assets": "Aset Tetap",
|
||||
"marketing": "Pemasaran",
|
||||
"loyalty": "Loyalti",
|
||||
"reward": "Reward",
|
||||
"gamification": "Gamifikasi",
|
||||
"wheel_spin": "Wheel Spin"
|
||||
}
|
||||
}
|
||||
|
||||
9
src/types/services/loyalty.ts
Normal file
9
src/types/services/loyalty.ts
Normal file
@ -0,0 +1,9 @@
|
||||
export interface LoyaltyType {
|
||||
id: string
|
||||
name: string
|
||||
minimumPurchase: number
|
||||
pointMultiplier: number
|
||||
benefits: string[]
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}
|
||||
12
src/types/services/reward.ts
Normal file
12
src/types/services/reward.ts
Normal file
@ -0,0 +1,12 @@
|
||||
export interface RewardCatalogType {
|
||||
id: string
|
||||
name: string
|
||||
description?: string
|
||||
pointCost: number
|
||||
stock?: number
|
||||
isActive: boolean
|
||||
validUntil?: Date
|
||||
imageUrl?: string
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}
|
||||
10
src/types/services/wheelSpin.ts
Normal file
10
src/types/services/wheelSpin.ts
Normal file
@ -0,0 +1,10 @@
|
||||
export interface WheelSpinType {
|
||||
id: string
|
||||
name: string
|
||||
weight: number
|
||||
omset: number
|
||||
fallback: boolean
|
||||
stock?: number
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}
|
||||
@ -0,0 +1,513 @@
|
||||
// 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 Alert from '@mui/material/Alert'
|
||||
|
||||
// Third-party Imports
|
||||
import { useForm, Controller } from 'react-hook-form'
|
||||
|
||||
// Component Imports
|
||||
import CustomTextField from '@core/components/mui/TextField'
|
||||
|
||||
// Types
|
||||
export interface WheelSpinType {
|
||||
id: string
|
||||
name: string
|
||||
weight: number
|
||||
omset: number
|
||||
fallback: boolean
|
||||
stock?: number
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}
|
||||
|
||||
export interface WheelSpinRequest {
|
||||
name: string
|
||||
weight: number
|
||||
omset: number
|
||||
fallback: boolean
|
||||
stock?: number
|
||||
description?: string
|
||||
isActive?: boolean
|
||||
}
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
handleClose: () => void
|
||||
data?: WheelSpinType // Data wheel spin untuk edit (jika ada)
|
||||
}
|
||||
|
||||
type FormValidateType = {
|
||||
name: string
|
||||
weight: number
|
||||
omset: number
|
||||
fallback: boolean
|
||||
stock?: number
|
||||
description: string
|
||||
isActive: boolean
|
||||
}
|
||||
|
||||
// Initial form data
|
||||
const initialData: FormValidateType = {
|
||||
name: '',
|
||||
weight: 10,
|
||||
omset: 0,
|
||||
fallback: false,
|
||||
stock: undefined,
|
||||
description: '',
|
||||
isActive: true
|
||||
}
|
||||
|
||||
// Mock mutation hooks (replace with actual hooks)
|
||||
const useWheelSpinMutation = () => {
|
||||
const createWheelSpin = {
|
||||
mutate: (data: WheelSpinRequest, options?: { onSuccess?: () => void }) => {
|
||||
console.log('Creating wheel spin:', data)
|
||||
setTimeout(() => options?.onSuccess?.(), 1000)
|
||||
}
|
||||
}
|
||||
|
||||
const updateWheelSpin = {
|
||||
mutate: (data: { id: string; payload: WheelSpinRequest }, options?: { onSuccess?: () => void }) => {
|
||||
console.log('Updating wheel spin:', data)
|
||||
setTimeout(() => options?.onSuccess?.(), 1000)
|
||||
}
|
||||
}
|
||||
|
||||
return { createWheelSpin, updateWheelSpin }
|
||||
}
|
||||
|
||||
const AddEditWheelSpinDrawer = (props: Props) => {
|
||||
// Props
|
||||
const { open, handleClose, data } = props
|
||||
|
||||
// States
|
||||
const [showMore, setShowMore] = useState(false)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [hasStock, setHasStock] = useState(false)
|
||||
|
||||
const { createWheelSpin, updateWheelSpin } = useWheelSpinMutation()
|
||||
|
||||
// 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 watchedFallback = watch('fallback')
|
||||
const watchedStock = watch('stock')
|
||||
const watchedWeight = watch('weight')
|
||||
|
||||
// Effect to populate form when editing
|
||||
useEffect(() => {
|
||||
if (isEditMode && data) {
|
||||
// Populate form with existing data
|
||||
const formData: FormValidateType = {
|
||||
name: data.name || '',
|
||||
weight: data.weight || 10,
|
||||
omset: data.omset || 0,
|
||||
fallback: data.fallback || false,
|
||||
stock: data.stock,
|
||||
description: '', // Add description field if available in your data
|
||||
isActive: true // Add isActive field if available in your data
|
||||
}
|
||||
|
||||
resetForm(formData)
|
||||
setHasStock(data.stock !== undefined)
|
||||
setShowMore(true) // Always show more for edit mode
|
||||
} else {
|
||||
// Reset to initial data for add mode
|
||||
resetForm(initialData)
|
||||
setHasStock(false)
|
||||
setShowMore(false)
|
||||
}
|
||||
}, [data, isEditMode, resetForm])
|
||||
|
||||
// Handle stock toggle
|
||||
const handleStockToggle = (checked: boolean) => {
|
||||
setHasStock(checked)
|
||||
if (!checked) {
|
||||
setValue('stock', undefined)
|
||||
} else {
|
||||
setValue('stock', 0)
|
||||
}
|
||||
}
|
||||
|
||||
const handleFormSubmit = async (formData: FormValidateType) => {
|
||||
try {
|
||||
setIsSubmitting(true)
|
||||
|
||||
// Create WheelSpinRequest object
|
||||
const wheelSpinRequest: WheelSpinRequest = {
|
||||
name: formData.name,
|
||||
weight: formData.weight,
|
||||
omset: formData.omset,
|
||||
fallback: formData.fallback,
|
||||
stock: hasStock ? formData.stock : undefined,
|
||||
description: formData.description || undefined,
|
||||
isActive: formData.isActive
|
||||
}
|
||||
|
||||
if (isEditMode && data?.id) {
|
||||
// Update existing wheel spin
|
||||
updateWheelSpin.mutate(
|
||||
{ id: data.id, payload: wheelSpinRequest },
|
||||
{
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
handleClose()
|
||||
}
|
||||
}
|
||||
)
|
||||
} else {
|
||||
// Create new wheel spin
|
||||
createWheelSpin.mutate(wheelSpinRequest, {
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
handleClose()
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error submitting wheel spin:', error)
|
||||
// Handle error (show toast, etc.)
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleReset = () => {
|
||||
handleClose()
|
||||
resetForm(initialData)
|
||||
setShowMore(false)
|
||||
setHasStock(false)
|
||||
}
|
||||
|
||||
const formatCurrency = (value: number) => {
|
||||
return new Intl.NumberFormat('id-ID', {
|
||||
style: 'currency',
|
||||
currency: 'IDR',
|
||||
minimumFractionDigits: 0
|
||||
}).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 Hadiah Wheel Spin' : 'Tambah Hadiah 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='wheel-spin-form' onSubmit={handleSubmit(handleFormSubmit)}>
|
||||
<div className='flex flex-col gap-6 p-6'>
|
||||
{/* Nama Hadiah */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Nama Hadiah <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='name'
|
||||
control={control}
|
||||
rules={{ required: 'Nama hadiah wajib diisi' }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='Masukkan nama hadiah'
|
||||
error={!!errors.name}
|
||||
helperText={errors.name?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Weight */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Bobot Kemunculan <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='weight'
|
||||
control={control}
|
||||
rules={{
|
||||
required: 'Bobot wajib diisi',
|
||||
min: {
|
||||
value: 1,
|
||||
message: 'Bobot minimal 1%'
|
||||
},
|
||||
max: {
|
||||
value: 100,
|
||||
message: 'Bobot maksimal 100%'
|
||||
}
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='number'
|
||||
placeholder='10'
|
||||
error={!!errors.weight}
|
||||
helperText={errors.weight?.message || `Peluang kemunculan: ${watchedWeight}%`}
|
||||
InputProps={{
|
||||
endAdornment: <InputAdornment position='end'>%</InputAdornment>
|
||||
}}
|
||||
onChange={e => field.onChange(Number(e.target.value))}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Minimum Omset */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Minimum Omset <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='omset'
|
||||
control={control}
|
||||
rules={{
|
||||
required: 'Minimum omset wajib diisi',
|
||||
min: {
|
||||
value: 0,
|
||||
message: 'Minimum omset tidak boleh negatif'
|
||||
}
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='number'
|
||||
placeholder='0'
|
||||
error={!!errors.omset}
|
||||
helperText={
|
||||
errors.omset?.message ||
|
||||
(field.value > 0 ? formatCurrency(field.value) : 'Omset minimum untuk mendapatkan hadiah ini')
|
||||
}
|
||||
InputProps={{
|
||||
startAdornment: <InputAdornment position='start'>Rp</InputAdornment>
|
||||
}}
|
||||
onChange={e => field.onChange(Number(e.target.value))}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Fallback Option */}
|
||||
<div>
|
||||
<Controller
|
||||
name='fallback'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<FormControlLabel
|
||||
control={<Switch checked={field.value} onChange={field.onChange} color='warning' />}
|
||||
label='Hadiah Fallback'
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{watchedFallback && (
|
||||
<Alert severity='info' sx={{ mt: 1 }}>
|
||||
Hadiah fallback akan muncul ketika hadiah lain tidak tersedia atau habis
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Stock Management */}
|
||||
<div>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Switch checked={hasStock} onChange={e => handleStockToggle(e.target.checked)} color='primary' />
|
||||
}
|
||||
label='Batasi Stok'
|
||||
/>
|
||||
|
||||
{hasStock && (
|
||||
<div className='mt-3'>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Jumlah Stok <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='stock'
|
||||
control={control}
|
||||
rules={
|
||||
hasStock
|
||||
? {
|
||||
required: 'Jumlah stok wajib diisi',
|
||||
min: {
|
||||
value: 0,
|
||||
message: 'Stok tidak boleh negatif'
|
||||
}
|
||||
}
|
||||
: {}
|
||||
}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='number'
|
||||
placeholder='0'
|
||||
error={!!errors.stock}
|
||||
helperText={errors.stock?.message || 'Kosongkan untuk stok unlimited'}
|
||||
onChange={e => field.onChange(Number(e.target.value))}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Status Aktif */}
|
||||
<div>
|
||||
<Controller
|
||||
name='isActive'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<FormControlLabel
|
||||
control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
|
||||
label='Hadiah Aktif'
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Tampilkan selengkapnya */}
|
||||
{!showMore && (
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
size='small'
|
||||
sx={{ textTransform: 'none', fontSize: '14px', p: 0, textAlign: 'left', width: '200px' }}
|
||||
onClick={() => setShowMore(true)}
|
||||
>
|
||||
+ Tampilkan selengkapnya
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Konten tambahan */}
|
||||
{showMore && (
|
||||
<>
|
||||
{/* Description */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Deskripsi Hadiah
|
||||
</Typography>
|
||||
<Controller
|
||||
name='description'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='Deskripsi detail tentang hadiah ini'
|
||||
multiline
|
||||
rows={4}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Tips */}
|
||||
<Alert severity='info'>
|
||||
<Typography variant='body2'>
|
||||
<strong>Tips:</strong>
|
||||
<br />
|
||||
• Bobot yang lebih tinggi = peluang menang lebih besar
|
||||
<br />
|
||||
• Hadiah fallback sebaiknya selalu ada untuk backup
|
||||
<br />• Minimum omset membantu mendorong transaksi lebih besar
|
||||
</Typography>
|
||||
</Alert>
|
||||
|
||||
{/* Sembunyikan */}
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
size='small'
|
||||
sx={{ textTransform: 'none', fontSize: '14px', p: 0, textAlign: 'left', width: '200px' }}
|
||||
onClick={() => setShowMore(false)}
|
||||
>
|
||||
- Sembunyikan
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</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='wheel-spin-form' disabled={isSubmitting}>
|
||||
{isSubmitting ? (isEditMode ? 'Mengupdate...' : 'Menyimpan...') : isEditMode ? 'Update' : 'Simpan'}
|
||||
</Button>
|
||||
<Button variant='outlined' color='error' onClick={handleReset} disabled={isSubmitting}>
|
||||
Batal
|
||||
</Button>
|
||||
</div>
|
||||
</Box>
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
|
||||
export default AddEditWheelSpinDrawer
|
||||
@ -0,0 +1,599 @@
|
||||
'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 AddEditWheelSpinDrawer from './AddEditWheelSpinDrawer'
|
||||
|
||||
// WheelSpin Type Interface
|
||||
export interface WheelSpinType {
|
||||
id: string
|
||||
name: string
|
||||
weight: number
|
||||
omset: number
|
||||
fallback: boolean
|
||||
stock?: number
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}
|
||||
|
||||
declare module '@tanstack/table-core' {
|
||||
interface FilterFns {
|
||||
fuzzy: FilterFn<unknown>
|
||||
}
|
||||
interface FilterMeta {
|
||||
itemRank: RankingInfo
|
||||
}
|
||||
}
|
||||
|
||||
type WheelSpinTypeWithAction = WheelSpinType & {
|
||||
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)} />
|
||||
}
|
||||
|
||||
// Dummy data for wheel spin prizes
|
||||
const DUMMY_WHEEL_SPIN_DATA: WheelSpinType[] = [
|
||||
{
|
||||
id: '1',
|
||||
name: 'Diskon 10%',
|
||||
weight: 25,
|
||||
omset: 500000,
|
||||
fallback: false,
|
||||
stock: 100,
|
||||
createdAt: new Date('2024-01-15'),
|
||||
updatedAt: new Date('2024-02-10')
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
name: 'Gratis Ongkir',
|
||||
weight: 30,
|
||||
omset: 200000,
|
||||
fallback: false,
|
||||
stock: 200,
|
||||
createdAt: new Date('2024-01-20'),
|
||||
updatedAt: new Date('2024-02-15')
|
||||
},
|
||||
{
|
||||
id: '3',
|
||||
name: 'Cashback 50k',
|
||||
weight: 15,
|
||||
omset: 1000000,
|
||||
fallback: false,
|
||||
stock: 50,
|
||||
createdAt: new Date('2024-01-25'),
|
||||
updatedAt: new Date('2024-02-20')
|
||||
},
|
||||
{
|
||||
id: '4',
|
||||
name: 'Voucher 100k',
|
||||
weight: 10,
|
||||
omset: 2000000,
|
||||
fallback: false,
|
||||
stock: 25,
|
||||
createdAt: new Date('2024-02-01'),
|
||||
updatedAt: new Date('2024-02-25')
|
||||
},
|
||||
{
|
||||
id: '5',
|
||||
name: 'Poin 500',
|
||||
weight: 35,
|
||||
omset: 100000,
|
||||
fallback: false,
|
||||
stock: 500,
|
||||
createdAt: new Date('2024-02-05'),
|
||||
updatedAt: new Date('2024-03-01')
|
||||
},
|
||||
{
|
||||
id: '6',
|
||||
name: 'Produk Gratis',
|
||||
weight: 5,
|
||||
omset: 5000000,
|
||||
fallback: false,
|
||||
stock: 10,
|
||||
createdAt: new Date('2024-02-10'),
|
||||
updatedAt: new Date('2024-03-05')
|
||||
},
|
||||
{
|
||||
id: '7',
|
||||
name: 'Coba Lagi',
|
||||
weight: 50,
|
||||
omset: 0,
|
||||
fallback: true,
|
||||
createdAt: new Date('2024-02-15'),
|
||||
updatedAt: new Date('2024-03-10')
|
||||
},
|
||||
{
|
||||
id: '8',
|
||||
name: 'Double Poin',
|
||||
weight: 20,
|
||||
omset: 750000,
|
||||
fallback: false,
|
||||
stock: 75,
|
||||
createdAt: new Date('2024-03-01'),
|
||||
updatedAt: new Date('2024-03-15')
|
||||
},
|
||||
{
|
||||
id: '9',
|
||||
name: 'Mystery Box',
|
||||
weight: 8,
|
||||
omset: 1500000,
|
||||
fallback: false,
|
||||
stock: 30,
|
||||
createdAt: new Date('2024-03-05'),
|
||||
updatedAt: new Date('2024-03-20')
|
||||
},
|
||||
{
|
||||
id: '10',
|
||||
name: 'Diskon 25%',
|
||||
weight: 12,
|
||||
omset: 3000000,
|
||||
fallback: false,
|
||||
stock: 20,
|
||||
createdAt: new Date('2024-03-10'),
|
||||
updatedAt: new Date('2024-03-25')
|
||||
}
|
||||
]
|
||||
|
||||
// Mock data hook with dummy data
|
||||
const useWheelSpin = ({ page, limit, search }: { page: number; limit: number; search: string }) => {
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
// Simulate loading
|
||||
useEffect(() => {
|
||||
setIsLoading(true)
|
||||
const timer = setTimeout(() => setIsLoading(false), 500)
|
||||
return () => clearTimeout(timer)
|
||||
}, [page, limit, search])
|
||||
|
||||
// Filter data based on search
|
||||
const filteredData = useMemo(() => {
|
||||
if (!search) return DUMMY_WHEEL_SPIN_DATA
|
||||
|
||||
return DUMMY_WHEEL_SPIN_DATA.filter(wheelSpin => wheelSpin.name.toLowerCase().includes(search.toLowerCase()))
|
||||
}, [search])
|
||||
|
||||
// Paginate data
|
||||
const paginatedData = useMemo(() => {
|
||||
const startIndex = (page - 1) * limit
|
||||
const endIndex = startIndex + limit
|
||||
return filteredData.slice(startIndex, endIndex)
|
||||
}, [filteredData, page, limit])
|
||||
|
||||
return {
|
||||
data: {
|
||||
wheelSpins: paginatedData,
|
||||
total_count: filteredData.length
|
||||
},
|
||||
isLoading,
|
||||
error: null,
|
||||
isFetching: isLoading
|
||||
}
|
||||
}
|
||||
|
||||
// Column Definitions
|
||||
const columnHelper = createColumnHelper<WheelSpinTypeWithAction>()
|
||||
|
||||
const WheelSpinListTable = () => {
|
||||
// States
|
||||
const [addWheelSpinOpen, setAddWheelSpinOpen] = useState(false)
|
||||
const [editWheelSpinData, setEditWheelSpinData] = useState<WheelSpinType | undefined>(undefined)
|
||||
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 } = useWheelSpin({
|
||||
page: currentPage,
|
||||
limit: pageSize,
|
||||
search
|
||||
})
|
||||
|
||||
const wheelSpins = data?.wheelSpins ?? []
|
||||
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 handleEditWheelSpin = (wheelSpin: WheelSpinType) => {
|
||||
setEditWheelSpinData(wheelSpin)
|
||||
setAddWheelSpinOpen(true)
|
||||
}
|
||||
|
||||
const handleDeleteWheelSpin = (wheelSpinId: string) => {
|
||||
if (confirm('Apakah Anda yakin ingin menghapus hadiah wheel spin ini?')) {
|
||||
console.log('Deleting wheel spin:', wheelSpinId)
|
||||
// Add your delete logic here
|
||||
// deleteWheelSpin.mutate(wheelSpinId)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCloseWheelSpinDrawer = () => {
|
||||
setAddWheelSpinOpen(false)
|
||||
setEditWheelSpinData(undefined)
|
||||
}
|
||||
|
||||
const columns = useMemo<ColumnDef<WheelSpinTypeWithAction, 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 Hadiah',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-4'>
|
||||
<div className='flex flex-col'>
|
||||
<Link href={getLocalizedUrl(`/apps/wheel-spin/${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('weight', {
|
||||
header: 'Bobot',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-2'>
|
||||
<Icon className='tabler-percentage' sx={{ color: 'var(--mui-palette-primary-main)' }} />
|
||||
<Typography color='text.primary'>{row.original.weight}%</Typography>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('omset', {
|
||||
header: 'Min. Omset',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-2'>
|
||||
<Icon className='tabler-coin' sx={{ color: 'var(--mui-palette-success-main)' }} />
|
||||
<Typography color='text.primary'>{formatCurrency(row.original.omset)}</Typography>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('stock', {
|
||||
header: 'Stok',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-2'>
|
||||
{row.original.stock !== undefined ? (
|
||||
<>
|
||||
<Icon className='tabler-package' sx={{ color: 'var(--mui-palette-info-main)' }} />
|
||||
<Typography color='text.primary'>{row.original.stock}</Typography>
|
||||
</>
|
||||
) : (
|
||||
<Typography color='text.secondary'>Unlimited</Typography>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('fallback', {
|
||||
header: 'Status',
|
||||
cell: ({ row }) => (
|
||||
<Chip
|
||||
label={row.original.fallback ? 'Fallback' : 'Aktif'}
|
||||
color={row.original.fallback ? 'warning' : 'success'}
|
||||
variant='tonal'
|
||||
size='small'
|
||||
/>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('createdAt', {
|
||||
header: 'Tanggal Dibuat',
|
||||
cell: ({ row }) => (
|
||||
<Typography color='text.primary'>
|
||||
{new Date(row.original.createdAt).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: () => handleEditWheelSpin(row.original)
|
||||
}
|
||||
},
|
||||
{
|
||||
text: 'Hapus',
|
||||
icon: 'tabler-trash text-[22px]',
|
||||
menuItemProps: {
|
||||
className: 'flex items-center gap-2 text-textSecondary',
|
||||
onClick: () => handleDeleteWheelSpin(row.original.id)
|
||||
}
|
||||
}
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
enableSorting: false
|
||||
}
|
||||
],
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[locale, handleEditWheelSpin, handleDeleteWheelSpin]
|
||||
)
|
||||
|
||||
const table = useReactTable({
|
||||
data: wheelSpins as WheelSpinType[],
|
||||
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 Hadiah Wheel Spin'
|
||||
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={() => setAddWheelSpinOpen(!addWheelSpinOpen)}
|
||||
className='max-sm:is-full'
|
||||
>
|
||||
Tambah Hadiah
|
||||
</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>
|
||||
<AddEditWheelSpinDrawer
|
||||
open={addWheelSpinOpen}
|
||||
handleClose={handleCloseWheelSpinDrawer}
|
||||
data={editWheelSpinData}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default WheelSpinListTable
|
||||
17
src/views/apps/marketing/gamification/wheel-spin/index.tsx
Normal file
17
src/views/apps/marketing/gamification/wheel-spin/index.tsx
Normal file
@ -0,0 +1,17 @@
|
||||
// MUI Imports
|
||||
import Grid from '@mui/material/Grid2'
|
||||
import WheelSpinListTable from './WheelSpinListTable'
|
||||
|
||||
// Type Imports
|
||||
|
||||
const WheelSpinList = () => {
|
||||
return (
|
||||
<Grid container spacing={6}>
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<WheelSpinListTable />
|
||||
</Grid>
|
||||
</Grid>
|
||||
)
|
||||
}
|
||||
|
||||
export default WheelSpinList
|
||||
495
src/views/apps/marketing/loyalty/AddLoyaltiDrawer.tsx
Normal file
495
src/views/apps/marketing/loyalty/AddLoyaltiDrawer.tsx
Normal file
@ -0,0 +1,495 @@
|
||||
// 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'
|
||||
|
||||
// Third-party Imports
|
||||
import { useForm, Controller, useFieldArray } from 'react-hook-form'
|
||||
|
||||
// Component Imports
|
||||
import CustomTextField from '@core/components/mui/TextField'
|
||||
|
||||
// Types
|
||||
export interface LoyaltyType {
|
||||
id: string
|
||||
name: string
|
||||
minimumPurchase: number
|
||||
pointMultiplier: number
|
||||
benefits: string[]
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}
|
||||
|
||||
export interface LoyaltyRequest {
|
||||
name: string
|
||||
minimumPurchase: number
|
||||
pointMultiplier: number
|
||||
benefits: string[]
|
||||
description?: string
|
||||
isActive?: boolean
|
||||
}
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
handleClose: () => void
|
||||
data?: LoyaltyType // Data loyalty untuk edit (jika ada)
|
||||
}
|
||||
|
||||
type FormValidateType = {
|
||||
name: string
|
||||
minimumPurchase: number
|
||||
pointMultiplier: number
|
||||
benefits: string[]
|
||||
description: string
|
||||
isActive: boolean
|
||||
newBenefit: string // Temporary field for adding new benefits
|
||||
}
|
||||
|
||||
// Initial form data
|
||||
const initialData: FormValidateType = {
|
||||
name: '',
|
||||
minimumPurchase: 0,
|
||||
pointMultiplier: 1,
|
||||
benefits: [],
|
||||
description: '',
|
||||
isActive: true,
|
||||
newBenefit: ''
|
||||
}
|
||||
|
||||
// Mock mutation hooks (replace with actual hooks)
|
||||
const useLoyaltyMutation = () => {
|
||||
const createLoyalty = {
|
||||
mutate: (data: LoyaltyRequest, options?: { onSuccess?: () => void }) => {
|
||||
console.log('Creating loyalty:', data)
|
||||
setTimeout(() => options?.onSuccess?.(), 1000)
|
||||
}
|
||||
}
|
||||
|
||||
const updateLoyalty = {
|
||||
mutate: (data: { id: string; payload: LoyaltyRequest }, options?: { onSuccess?: () => void }) => {
|
||||
console.log('Updating loyalty:', data)
|
||||
setTimeout(() => options?.onSuccess?.(), 1000)
|
||||
}
|
||||
}
|
||||
|
||||
return { createLoyalty, updateLoyalty }
|
||||
}
|
||||
|
||||
const AddEditLoyaltyDrawer = (props: Props) => {
|
||||
// Props
|
||||
const { open, handleClose, data } = props
|
||||
|
||||
// States
|
||||
const [showMore, setShowMore] = useState(false)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
|
||||
const { createLoyalty, updateLoyalty } = useLoyaltyMutation()
|
||||
|
||||
// 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 watchedNewBenefit = watch('newBenefit')
|
||||
|
||||
// Effect to populate form when editing
|
||||
useEffect(() => {
|
||||
if (isEditMode && data) {
|
||||
// Populate form with existing data
|
||||
const formData: FormValidateType = {
|
||||
name: data.name || '',
|
||||
minimumPurchase: data.minimumPurchase || 0,
|
||||
pointMultiplier: data.pointMultiplier || 1,
|
||||
benefits: data.benefits || [],
|
||||
description: '', // Add description field if available in your data
|
||||
isActive: true, // Add isActive field if available in your data
|
||||
newBenefit: ''
|
||||
}
|
||||
|
||||
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 = () => {
|
||||
if (watchedNewBenefit.trim()) {
|
||||
const currentBenefits = watchedBenefits || []
|
||||
setValue('benefits', [...currentBenefits, watchedNewBenefit.trim()])
|
||||
setValue('newBenefit', '')
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
// Create LoyaltyRequest object
|
||||
const loyaltyRequest: LoyaltyRequest = {
|
||||
name: formData.name,
|
||||
minimumPurchase: formData.minimumPurchase,
|
||||
pointMultiplier: formData.pointMultiplier,
|
||||
benefits: formData.benefits,
|
||||
description: formData.description || undefined,
|
||||
isActive: formData.isActive
|
||||
}
|
||||
|
||||
if (isEditMode && data?.id) {
|
||||
// Update existing loyalty
|
||||
updateLoyalty.mutate(
|
||||
{ id: data.id, payload: loyaltyRequest },
|
||||
{
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
handleClose()
|
||||
}
|
||||
}
|
||||
)
|
||||
} else {
|
||||
// Create new loyalty
|
||||
createLoyalty.mutate(loyaltyRequest, {
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
handleClose()
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error submitting loyalty:', error)
|
||||
// Handle error (show toast, etc.)
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleReset = () => {
|
||||
handleClose()
|
||||
resetForm(initialData)
|
||||
setShowMore(false)
|
||||
}
|
||||
|
||||
const formatCurrency = (value: number) => {
|
||||
return new Intl.NumberFormat('id-ID', {
|
||||
style: 'currency',
|
||||
currency: 'IDR',
|
||||
minimumFractionDigits: 0
|
||||
}).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 Program Loyalty' : 'Tambah Program Loyalty 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='loyalty-form' onSubmit={handleSubmit(handleFormSubmit)}>
|
||||
<div className='flex flex-col gap-6 p-6'>
|
||||
{/* Nama Program Loyalty */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Nama Program Loyalty <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='name'
|
||||
control={control}
|
||||
rules={{ required: 'Nama program loyalty wajib diisi' }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='Masukkan nama program loyalty'
|
||||
error={!!errors.name}
|
||||
helperText={errors.name?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Minimum Purchase */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Minimum Pembelian <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='minimumPurchase'
|
||||
control={control}
|
||||
rules={{
|
||||
required: 'Minimum pembelian wajib diisi',
|
||||
min: {
|
||||
value: 0,
|
||||
message: 'Minimum pembelian tidak boleh negatif'
|
||||
}
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='number'
|
||||
placeholder='0'
|
||||
error={!!errors.minimumPurchase}
|
||||
helperText={errors.minimumPurchase?.message || (field.value > 0 ? formatCurrency(field.value) : '')}
|
||||
InputProps={{
|
||||
startAdornment: <InputAdornment position='start'>Rp</InputAdornment>
|
||||
}}
|
||||
onChange={e => field.onChange(Number(e.target.value))}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Point Multiplier */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Pengali Poin <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='pointMultiplier'
|
||||
control={control}
|
||||
rules={{
|
||||
required: 'Pengali poin wajib diisi',
|
||||
min: {
|
||||
value: 1,
|
||||
message: 'Pengali poin minimal 1'
|
||||
},
|
||||
max: {
|
||||
value: 10,
|
||||
message: 'Pengali poin maksimal 10'
|
||||
}
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
select
|
||||
fullWidth
|
||||
error={!!errors.pointMultiplier}
|
||||
helperText={errors.pointMultiplier?.message}
|
||||
onChange={e => field.onChange(Number(e.target.value))}
|
||||
>
|
||||
{[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(multiplier => (
|
||||
<MenuItem key={multiplier} value={multiplier}>
|
||||
{multiplier}x
|
||||
</MenuItem>
|
||||
))}
|
||||
</CustomTextField>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Benefits */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Manfaat Program <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
|
||||
{/* Display current benefits */}
|
||||
{watchedBenefits && watchedBenefits.length > 0 && (
|
||||
<div className='flex flex-wrap gap-2 mb-3'>
|
||||
{watchedBenefits.map((benefit, index) => (
|
||||
<Chip
|
||||
key={index}
|
||||
label={benefit}
|
||||
onDelete={() => handleRemoveBenefit(index)}
|
||||
color='primary'
|
||||
variant='outlined'
|
||||
size='small'
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Add new benefit */}
|
||||
<Controller
|
||||
name='newBenefit'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='Tambah manfaat baru'
|
||||
onKeyPress={handleKeyPress}
|
||||
InputProps={{
|
||||
endAdornment: (
|
||||
<InputAdornment position='end'>
|
||||
<Button size='small' onClick={handleAddBenefit} disabled={!watchedNewBenefit?.trim()}>
|
||||
Tambah
|
||||
</Button>
|
||||
</InputAdornment>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{(!watchedBenefits || watchedBenefits.length === 0) && (
|
||||
<Typography variant='caption' color='error'>
|
||||
Minimal satu manfaat harus ditambahkan
|
||||
</Typography>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Status Aktif */}
|
||||
<div>
|
||||
<Controller
|
||||
name='isActive'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<FormControlLabel
|
||||
control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
|
||||
label='Program Aktif'
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Tampilkan selengkapnya */}
|
||||
{!showMore && (
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
size='small'
|
||||
sx={{ textTransform: 'none', fontSize: '14px', p: 0, textAlign: 'left', width: '200px' }}
|
||||
onClick={() => setShowMore(true)}
|
||||
>
|
||||
+ Tampilkan selengkapnya
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Konten tambahan */}
|
||||
{showMore && (
|
||||
<>
|
||||
{/* Description */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Deskripsi Program
|
||||
</Typography>
|
||||
<Controller
|
||||
name='description'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='Deskripsi detail tentang program loyalty'
|
||||
multiline
|
||||
rows={4}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Sembunyikan */}
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
size='small'
|
||||
sx={{ textTransform: 'none', fontSize: '14px', p: 0, textAlign: 'left', width: '200px' }}
|
||||
onClick={() => setShowMore(false)}
|
||||
>
|
||||
- Sembunyikan
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</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='loyalty-form'
|
||||
disabled={isSubmitting || !watchedBenefits || watchedBenefits.length === 0}
|
||||
>
|
||||
{isSubmitting ? (isEditMode ? 'Mengupdate...' : 'Menyimpan...') : isEditMode ? 'Update' : 'Simpan'}
|
||||
</Button>
|
||||
<Button variant='outlined' color='error' onClick={handleReset} disabled={isSubmitting}>
|
||||
Batal
|
||||
</Button>
|
||||
</div>
|
||||
</Box>
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
|
||||
export default AddEditLoyaltyDrawer
|
||||
635
src/views/apps/marketing/loyalty/LoyaltyListTable.tsx
Normal file
635
src/views/apps/marketing/loyalty/LoyaltyListTable.tsx
Normal file
@ -0,0 +1,635 @@
|
||||
'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 AddEditLoyaltyDrawer from './AddLoyaltiDrawer'
|
||||
|
||||
// Loyalty Type Interface
|
||||
export interface LoyaltyType {
|
||||
id: string
|
||||
name: string
|
||||
minimumPurchase: number
|
||||
pointMultiplier: number
|
||||
benefits: string[]
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}
|
||||
|
||||
declare module '@tanstack/table-core' {
|
||||
interface FilterFns {
|
||||
fuzzy: FilterFn<unknown>
|
||||
}
|
||||
interface FilterMeta {
|
||||
itemRank: RankingInfo
|
||||
}
|
||||
}
|
||||
|
||||
type LoyaltyTypeWithAction = LoyaltyType & {
|
||||
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)} />
|
||||
}
|
||||
|
||||
// Dummy data for loyalty programs
|
||||
const DUMMY_LOYALTY_DATA: LoyaltyType[] = [
|
||||
{
|
||||
id: '1',
|
||||
name: 'Silver Member',
|
||||
minimumPurchase: 500000,
|
||||
pointMultiplier: 1,
|
||||
benefits: ['Gratis ongkir', 'Diskon 5%', 'Priority customer service'],
|
||||
createdAt: new Date('2024-01-15'),
|
||||
updatedAt: new Date('2024-02-10')
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
name: 'Gold Member',
|
||||
minimumPurchase: 2000000,
|
||||
pointMultiplier: 2,
|
||||
benefits: ['Gratis ongkir', 'Diskon 10%', 'Birthday bonus', 'Priority customer service', 'Akses early sale'],
|
||||
createdAt: new Date('2024-01-20'),
|
||||
updatedAt: new Date('2024-02-15')
|
||||
},
|
||||
{
|
||||
id: '3',
|
||||
name: 'Platinum Member',
|
||||
minimumPurchase: 5000000,
|
||||
pointMultiplier: 3,
|
||||
benefits: [
|
||||
'Gratis ongkir',
|
||||
'Diskon 15%',
|
||||
'Birthday bonus',
|
||||
'Dedicated account manager',
|
||||
'VIP event access',
|
||||
'Personal shopper'
|
||||
],
|
||||
createdAt: new Date('2024-01-25'),
|
||||
updatedAt: new Date('2024-02-20')
|
||||
},
|
||||
{
|
||||
id: '4',
|
||||
name: 'Diamond Member',
|
||||
minimumPurchase: 10000000,
|
||||
pointMultiplier: 5,
|
||||
benefits: [
|
||||
'Gratis ongkir',
|
||||
'Diskon 20%',
|
||||
'Birthday bonus',
|
||||
'Dedicated account manager',
|
||||
'VIP event access',
|
||||
'Personal shopper',
|
||||
'Annual gift',
|
||||
'Luxury experiences'
|
||||
],
|
||||
createdAt: new Date('2024-02-01'),
|
||||
updatedAt: new Date('2024-02-25')
|
||||
},
|
||||
{
|
||||
id: '5',
|
||||
name: 'Student Discount',
|
||||
minimumPurchase: 100000,
|
||||
pointMultiplier: 1,
|
||||
benefits: ['Diskon 10% khusus mahasiswa', 'Gratis ongkir untuk pembelian minimal 200k'],
|
||||
createdAt: new Date('2024-02-05'),
|
||||
updatedAt: new Date('2024-03-01')
|
||||
},
|
||||
{
|
||||
id: '6',
|
||||
name: 'Senior Citizen',
|
||||
minimumPurchase: 200000,
|
||||
pointMultiplier: 2,
|
||||
benefits: ['Diskon 15% untuk usia 60+', 'Gratis ongkir', 'Konsultasi gratis', 'Priority support'],
|
||||
createdAt: new Date('2024-02-10'),
|
||||
updatedAt: new Date('2024-03-05')
|
||||
},
|
||||
{
|
||||
id: '7',
|
||||
name: 'Corporate Partner',
|
||||
minimumPurchase: 15000000,
|
||||
pointMultiplier: 4,
|
||||
benefits: [
|
||||
'Diskon 25% untuk pembelian korporat',
|
||||
'Payment terms 30 hari',
|
||||
'Dedicated sales rep',
|
||||
'Bulk discount',
|
||||
'Invoice payment'
|
||||
],
|
||||
createdAt: new Date('2024-02-15'),
|
||||
updatedAt: new Date('2024-03-10')
|
||||
},
|
||||
{
|
||||
id: '8',
|
||||
name: 'New Customer Bonus',
|
||||
minimumPurchase: 0,
|
||||
pointMultiplier: 1,
|
||||
benefits: ['Welcome bonus 50 poin', 'Diskon 15% pembelian pertama', 'Gratis ongkir'],
|
||||
createdAt: new Date('2024-03-01'),
|
||||
updatedAt: new Date('2024-03-15')
|
||||
},
|
||||
{
|
||||
id: '9',
|
||||
name: 'Family Package',
|
||||
minimumPurchase: 1000000,
|
||||
pointMultiplier: 2,
|
||||
benefits: [
|
||||
'Diskon 12% untuk keluarga',
|
||||
'Poin dapat dibagi ke anggota keluarga',
|
||||
'Family rewards',
|
||||
'Group discount'
|
||||
],
|
||||
createdAt: new Date('2024-03-05'),
|
||||
updatedAt: new Date('2024-03-20')
|
||||
},
|
||||
{
|
||||
id: '10',
|
||||
name: 'Loyalty Plus',
|
||||
minimumPurchase: 3000000,
|
||||
pointMultiplier: 3,
|
||||
benefits: [
|
||||
'Cashback 8%',
|
||||
'Exclusive member-only products',
|
||||
'Free premium packaging',
|
||||
'Extended warranty',
|
||||
'Member appreciation events'
|
||||
],
|
||||
createdAt: new Date('2024-03-10'),
|
||||
updatedAt: new Date('2024-03-25')
|
||||
},
|
||||
{
|
||||
id: '11',
|
||||
name: 'VIP Collector',
|
||||
minimumPurchase: 7500000,
|
||||
pointMultiplier: 4,
|
||||
benefits: [
|
||||
'Limited edition access',
|
||||
'Collector item discounts',
|
||||
'Pre-order privileges',
|
||||
'Authentication service',
|
||||
'Storage solutions'
|
||||
],
|
||||
createdAt: new Date('2024-03-15'),
|
||||
updatedAt: new Date('2024-03-30')
|
||||
},
|
||||
{
|
||||
id: '12',
|
||||
name: 'Seasonal Member',
|
||||
minimumPurchase: 800000,
|
||||
pointMultiplier: 2,
|
||||
benefits: ['Seasonal sale access', 'Holiday bonuses', 'Festival discounts', 'Seasonal gift wrapping'],
|
||||
createdAt: new Date('2024-03-20'),
|
||||
updatedAt: new Date('2024-04-05')
|
||||
}
|
||||
]
|
||||
|
||||
// Mock data hook with dummy data
|
||||
const useLoyalty = ({ page, limit, search }: { page: number; limit: number; search: string }) => {
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
// Simulate loading
|
||||
useEffect(() => {
|
||||
setIsLoading(true)
|
||||
const timer = setTimeout(() => setIsLoading(false), 500)
|
||||
return () => clearTimeout(timer)
|
||||
}, [page, limit, search])
|
||||
|
||||
// Filter data based on search
|
||||
const filteredData = useMemo(() => {
|
||||
if (!search) return DUMMY_LOYALTY_DATA
|
||||
|
||||
return DUMMY_LOYALTY_DATA.filter(
|
||||
loyalty =>
|
||||
loyalty.name.toLowerCase().includes(search.toLowerCase()) ||
|
||||
loyalty.benefits.some(benefit => benefit.toLowerCase().includes(search.toLowerCase()))
|
||||
)
|
||||
}, [search])
|
||||
|
||||
// Paginate data
|
||||
const paginatedData = useMemo(() => {
|
||||
const startIndex = (page - 1) * limit
|
||||
const endIndex = startIndex + limit
|
||||
return filteredData.slice(startIndex, endIndex)
|
||||
}, [filteredData, page, limit])
|
||||
|
||||
return {
|
||||
data: {
|
||||
loyalties: paginatedData,
|
||||
total_count: filteredData.length
|
||||
},
|
||||
isLoading,
|
||||
error: null,
|
||||
isFetching: isLoading
|
||||
}
|
||||
}
|
||||
|
||||
// Column Definitions
|
||||
const columnHelper = createColumnHelper<LoyaltyTypeWithAction>()
|
||||
|
||||
const LoyaltyListTable = () => {
|
||||
// States
|
||||
const [addLoyaltyOpen, setAddLoyaltyOpen] = useState(false)
|
||||
const [editLoyaltyData, setEditLoyaltyData] = useState<LoyaltyType | undefined>(undefined)
|
||||
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 } = useLoyalty({
|
||||
page: currentPage,
|
||||
limit: pageSize,
|
||||
search
|
||||
})
|
||||
|
||||
const loyalties = data?.loyalties ?? []
|
||||
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 handleEditLoyalty = (loyalty: LoyaltyType) => {
|
||||
setEditLoyaltyData(loyalty)
|
||||
setAddLoyaltyOpen(true)
|
||||
}
|
||||
|
||||
const handleDeleteLoyalty = (loyaltyId: string) => {
|
||||
if (confirm('Apakah Anda yakin ingin menghapus program loyalty ini?')) {
|
||||
console.log('Deleting loyalty:', loyaltyId)
|
||||
// Add your delete logic here
|
||||
// deleteLoyalty.mutate(loyaltyId)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCloseLoyaltyDrawer = () => {
|
||||
setAddLoyaltyOpen(false)
|
||||
setEditLoyaltyData(undefined)
|
||||
}
|
||||
|
||||
const columns = useMemo<ColumnDef<LoyaltyTypeWithAction, 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: 'Program Loyalty',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-4'>
|
||||
<div className='flex flex-col'>
|
||||
<Link href={getLocalizedUrl(`/apps/loyalty/${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('minimumPurchase', {
|
||||
header: 'Minimum Pembelian',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-2'>
|
||||
<Icon className='tabler-coin' sx={{ color: 'var(--mui-palette-primary-main)' }} />
|
||||
<Typography color='text.primary'>{formatCurrency(row.original.minimumPurchase)}</Typography>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('pointMultiplier', {
|
||||
header: 'Pengali Poin',
|
||||
cell: ({ row }) => (
|
||||
<Chip label={`${row.original.pointMultiplier}x`} color='primary' variant='tonal' size='small' />
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('benefits', {
|
||||
header: 'Manfaat',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex flex-wrap gap-1 max-w-xs'>
|
||||
{row.original.benefits.slice(0, 2).map((benefit, index) => (
|
||||
<Chip key={index} label={benefit} size='small' variant='outlined' color='secondary' />
|
||||
))}
|
||||
{row.original.benefits.length > 2 && (
|
||||
<Chip
|
||||
label={`+${row.original.benefits.length - 2} lainnya`}
|
||||
size='small'
|
||||
variant='outlined'
|
||||
color='default'
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('createdAt', {
|
||||
header: 'Tanggal Dibuat',
|
||||
cell: ({ row }) => (
|
||||
<Typography color='text.primary'>
|
||||
{new Date(row.original.createdAt).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: () => handleEditLoyalty(row.original)
|
||||
}
|
||||
},
|
||||
{
|
||||
text: 'Hapus',
|
||||
icon: 'tabler-trash text-[22px]',
|
||||
menuItemProps: {
|
||||
className: 'flex items-center gap-2 text-textSecondary',
|
||||
onClick: () => handleDeleteLoyalty(row.original.id)
|
||||
}
|
||||
}
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
enableSorting: false
|
||||
}
|
||||
],
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[locale, handleEditLoyalty, handleDeleteLoyalty]
|
||||
)
|
||||
|
||||
const table = useReactTable({
|
||||
data: loyalties as LoyaltyType[],
|
||||
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 Program Loyalty'
|
||||
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={() => setAddLoyaltyOpen(!addLoyaltyOpen)}
|
||||
className='max-sm:is-full'
|
||||
>
|
||||
Tambah Program Loyalty
|
||||
</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>
|
||||
<AddEditLoyaltyDrawer open={addLoyaltyOpen} handleClose={handleCloseLoyaltyDrawer} data={editLoyaltyData} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default LoyaltyListTable
|
||||
17
src/views/apps/marketing/loyalty/index.tsx
Normal file
17
src/views/apps/marketing/loyalty/index.tsx
Normal file
@ -0,0 +1,17 @@
|
||||
// MUI Imports
|
||||
import Grid from '@mui/material/Grid2'
|
||||
import LoyaltyListTable from './LoyaltyListTable'
|
||||
|
||||
// Type Imports
|
||||
|
||||
const LoyaltyList = () => {
|
||||
return (
|
||||
<Grid container spacing={6}>
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<LoyaltyListTable />
|
||||
</Grid>
|
||||
</Grid>
|
||||
)
|
||||
}
|
||||
|
||||
export default LoyaltyList
|
||||
633
src/views/apps/marketing/reward/AddEditRewardDrawer.tsx
Normal file
633
src/views/apps/marketing/reward/AddEditRewardDrawer.tsx
Normal file
@ -0,0 +1,633 @@
|
||||
// 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 Avatar from '@mui/material/Avatar'
|
||||
import Card from '@mui/material/Card'
|
||||
import CardContent from '@mui/material/CardContent'
|
||||
import FormHelperText from '@mui/material/FormHelperText'
|
||||
|
||||
// Third-party Imports
|
||||
import { useForm, Controller } from 'react-hook-form'
|
||||
|
||||
// Component Imports
|
||||
import CustomTextField from '@core/components/mui/TextField'
|
||||
|
||||
// Types
|
||||
export interface RewardCatalogType {
|
||||
id: string
|
||||
name: string
|
||||
description?: string
|
||||
pointCost: number
|
||||
stock?: number
|
||||
isActive: boolean
|
||||
validUntil?: Date
|
||||
imageUrl?: string
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}
|
||||
|
||||
export interface RewardRequest {
|
||||
name: string
|
||||
description?: string
|
||||
pointCost: number
|
||||
stock?: number
|
||||
isActive: boolean
|
||||
validUntil?: Date
|
||||
imageUrl?: string
|
||||
category?: string
|
||||
terms?: string
|
||||
}
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
handleClose: () => void
|
||||
data?: RewardCatalogType // Data reward untuk edit (jika ada)
|
||||
}
|
||||
|
||||
type FormValidateType = {
|
||||
name: string
|
||||
description: string
|
||||
pointCost: number
|
||||
stock: number | ''
|
||||
isActive: boolean
|
||||
validUntil: string
|
||||
imageUrl: string
|
||||
category: string
|
||||
terms: string
|
||||
hasUnlimitedStock: boolean
|
||||
hasValidUntil: boolean
|
||||
}
|
||||
|
||||
// Initial form data
|
||||
const initialData: FormValidateType = {
|
||||
name: '',
|
||||
description: '',
|
||||
pointCost: 100,
|
||||
stock: '',
|
||||
isActive: true,
|
||||
validUntil: '',
|
||||
imageUrl: '',
|
||||
category: 'voucher',
|
||||
terms: '',
|
||||
hasUnlimitedStock: false,
|
||||
hasValidUntil: false
|
||||
}
|
||||
|
||||
// Mock mutation hooks (replace with actual hooks)
|
||||
const useRewardMutation = () => {
|
||||
const createReward = {
|
||||
mutate: (data: RewardRequest, options?: { onSuccess?: () => void }) => {
|
||||
console.log('Creating reward:', data)
|
||||
setTimeout(() => options?.onSuccess?.(), 1000)
|
||||
}
|
||||
}
|
||||
|
||||
const updateReward = {
|
||||
mutate: (data: { id: string; payload: RewardRequest }, options?: { onSuccess?: () => void }) => {
|
||||
console.log('Updating reward:', data)
|
||||
setTimeout(() => options?.onSuccess?.(), 1000)
|
||||
}
|
||||
}
|
||||
|
||||
return { createReward, updateReward }
|
||||
}
|
||||
|
||||
// Reward categories
|
||||
const REWARD_CATEGORIES = [
|
||||
{ value: 'voucher', label: 'Voucher Diskon' },
|
||||
{ value: 'cashback', label: 'Cashback' },
|
||||
{ value: 'shipping', label: 'Gratis Ongkir' },
|
||||
{ value: 'gift_card', label: 'Gift Card' },
|
||||
{ value: 'physical', label: 'Barang Fisik' },
|
||||
{ value: 'experience', label: 'Pengalaman' },
|
||||
{ value: 'service', label: 'Layanan' }
|
||||
]
|
||||
|
||||
const AddEditRewardDrawer = (props: Props) => {
|
||||
// Props
|
||||
const { open, handleClose, data } = props
|
||||
|
||||
// States
|
||||
const [showMore, setShowMore] = useState(false)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [imagePreview, setImagePreview] = useState<string | null>(null)
|
||||
|
||||
const { createReward, updateReward } = useRewardMutation()
|
||||
|
||||
// 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 watchedImageUrl = watch('imageUrl')
|
||||
const watchedHasUnlimitedStock = watch('hasUnlimitedStock')
|
||||
const watchedHasValidUntil = watch('hasValidUntil')
|
||||
const watchedStock = watch('stock')
|
||||
const watchedPointCost = watch('pointCost')
|
||||
|
||||
// Effect to populate form when editing
|
||||
useEffect(() => {
|
||||
if (isEditMode && data) {
|
||||
// Populate form with existing data
|
||||
const formData: FormValidateType = {
|
||||
name: data.name || '',
|
||||
description: data.description || '',
|
||||
pointCost: data.pointCost || 100,
|
||||
stock: data.stock ?? '',
|
||||
isActive: data.isActive ?? true,
|
||||
validUntil: data.validUntil ? new Date(data.validUntil).toISOString().split('T')[0] : '',
|
||||
imageUrl: data.imageUrl || '',
|
||||
category: 'voucher', // Default category
|
||||
terms: '',
|
||||
hasUnlimitedStock: data.stock === undefined || data.stock === null,
|
||||
hasValidUntil: Boolean(data.validUntil)
|
||||
}
|
||||
|
||||
resetForm(formData)
|
||||
setShowMore(true) // Always show more for edit mode
|
||||
setImagePreview(data.imageUrl || null)
|
||||
} else {
|
||||
// Reset to initial data for add mode
|
||||
resetForm(initialData)
|
||||
setShowMore(false)
|
||||
setImagePreview(null)
|
||||
}
|
||||
}, [data, isEditMode, resetForm])
|
||||
|
||||
// Handle image URL change
|
||||
useEffect(() => {
|
||||
if (watchedImageUrl) {
|
||||
setImagePreview(watchedImageUrl)
|
||||
} else {
|
||||
setImagePreview(null)
|
||||
}
|
||||
}, [watchedImageUrl])
|
||||
|
||||
// Handle unlimited stock toggle
|
||||
useEffect(() => {
|
||||
if (watchedHasUnlimitedStock) {
|
||||
setValue('stock', '')
|
||||
}
|
||||
}, [watchedHasUnlimitedStock, setValue])
|
||||
|
||||
// Handle valid until toggle
|
||||
useEffect(() => {
|
||||
if (!watchedHasValidUntil) {
|
||||
setValue('validUntil', '')
|
||||
}
|
||||
}, [watchedHasValidUntil, setValue])
|
||||
|
||||
const handleFormSubmit = async (formData: FormValidateType) => {
|
||||
try {
|
||||
setIsSubmitting(true)
|
||||
|
||||
// Create RewardRequest object
|
||||
const rewardRequest: RewardRequest = {
|
||||
name: formData.name,
|
||||
description: formData.description || undefined,
|
||||
pointCost: formData.pointCost,
|
||||
stock: formData.hasUnlimitedStock ? undefined : (formData.stock as number) || undefined,
|
||||
isActive: formData.isActive,
|
||||
validUntil: formData.hasValidUntil && formData.validUntil ? new Date(formData.validUntil) : undefined,
|
||||
imageUrl: formData.imageUrl || undefined,
|
||||
category: formData.category || undefined,
|
||||
terms: formData.terms || undefined
|
||||
}
|
||||
|
||||
if (isEditMode && data?.id) {
|
||||
// Update existing reward
|
||||
updateReward.mutate(
|
||||
{ id: data.id, payload: rewardRequest },
|
||||
{
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
handleClose()
|
||||
}
|
||||
}
|
||||
)
|
||||
} else {
|
||||
// Create new reward
|
||||
createReward.mutate(rewardRequest, {
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
handleClose()
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error submitting reward:', error)
|
||||
// Handle error (show toast, etc.)
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleReset = () => {
|
||||
handleClose()
|
||||
resetForm(initialData)
|
||||
setShowMore(false)
|
||||
setImagePreview(null)
|
||||
}
|
||||
|
||||
const formatPoints = (value: number) => {
|
||||
return value.toLocaleString('id-ID') + ' poin'
|
||||
}
|
||||
|
||||
const getStockDisplay = () => {
|
||||
if (watchedHasUnlimitedStock) return 'Unlimited'
|
||||
if (watchedStock === '' || watchedStock === 0) return 'Tidak ada stok'
|
||||
return `${watchedStock} item`
|
||||
}
|
||||
|
||||
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 Reward' : 'Tambah Reward 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='reward-form' onSubmit={handleSubmit(handleFormSubmit)}>
|
||||
<div className='flex flex-col gap-6 p-6'>
|
||||
{/* Image Preview */}
|
||||
{imagePreview && (
|
||||
<Card variant='outlined' sx={{ mb: 2 }}>
|
||||
<CardContent sx={{ p: 2 }}>
|
||||
<Typography variant='subtitle2' className='mb-2'>
|
||||
Preview Gambar
|
||||
</Typography>
|
||||
<Avatar
|
||||
src={imagePreview}
|
||||
sx={{
|
||||
width: 80,
|
||||
height: 80,
|
||||
mx: 'auto',
|
||||
mb: 1
|
||||
}}
|
||||
variant='rounded'
|
||||
>
|
||||
<i className='tabler-gift text-2xl' />
|
||||
</Avatar>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Nama Reward */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Nama Reward <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='name'
|
||||
control={control}
|
||||
rules={{ required: 'Nama reward wajib diisi' }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='Masukkan nama reward'
|
||||
error={!!errors.name}
|
||||
helperText={errors.name?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Kategori Reward */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Kategori Reward <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='category'
|
||||
control={control}
|
||||
rules={{ required: 'Kategori reward wajib dipilih' }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
select
|
||||
fullWidth
|
||||
error={!!errors.category}
|
||||
helperText={errors.category?.message}
|
||||
>
|
||||
{REWARD_CATEGORIES.map(category => (
|
||||
<MenuItem key={category.value} value={category.value}>
|
||||
{category.label}
|
||||
</MenuItem>
|
||||
))}
|
||||
</CustomTextField>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Point Cost */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Biaya Poin <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='pointCost'
|
||||
control={control}
|
||||
rules={{
|
||||
required: 'Biaya poin wajib diisi',
|
||||
min: {
|
||||
value: 1,
|
||||
message: 'Biaya poin minimal 1'
|
||||
}
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='number'
|
||||
placeholder='100'
|
||||
error={!!errors.pointCost}
|
||||
helperText={errors.pointCost?.message || (field.value > 0 ? formatPoints(field.value) : '')}
|
||||
InputProps={{
|
||||
startAdornment: (
|
||||
<InputAdornment position='start'>
|
||||
<i className='tabler-star-filled text-warning' />
|
||||
</InputAdornment>
|
||||
)
|
||||
}}
|
||||
onChange={e => field.onChange(Number(e.target.value))}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Stock Management */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Manajemen Stok
|
||||
</Typography>
|
||||
<Controller
|
||||
name='hasUnlimitedStock'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<FormControlLabel
|
||||
control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
|
||||
label='Stok Unlimited'
|
||||
className='mb-2'
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{!watchedHasUnlimitedStock && (
|
||||
<Controller
|
||||
name='stock'
|
||||
control={control}
|
||||
rules={{
|
||||
required: !watchedHasUnlimitedStock ? 'Jumlah stok wajib diisi' : false,
|
||||
min: {
|
||||
value: 0,
|
||||
message: 'Stok tidak boleh negatif'
|
||||
}
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='number'
|
||||
placeholder='0'
|
||||
error={!!errors.stock}
|
||||
helperText={errors.stock?.message || getStockDisplay()}
|
||||
InputProps={{
|
||||
startAdornment: <InputAdornment position='start'>Qty</InputAdornment>
|
||||
}}
|
||||
onChange={e => field.onChange(e.target.value ? Number(e.target.value) : '')}
|
||||
value={field.value === '' ? '' : field.value}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Status Aktif */}
|
||||
<div>
|
||||
<Controller
|
||||
name='isActive'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<FormControlLabel
|
||||
control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
|
||||
label='Reward Aktif'
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Tampilkan selengkapnya */}
|
||||
{!showMore && (
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
size='small'
|
||||
sx={{ textTransform: 'none', fontSize: '14px', p: 0, textAlign: 'left', width: '200px' }}
|
||||
onClick={() => setShowMore(true)}
|
||||
>
|
||||
+ Tampilkan selengkapnya
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Konten tambahan */}
|
||||
{showMore && (
|
||||
<>
|
||||
{/* Description */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Deskripsi Reward
|
||||
</Typography>
|
||||
<Controller
|
||||
name='description'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='Deskripsi detail tentang reward'
|
||||
multiline
|
||||
rows={3}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Image URL */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
URL Gambar
|
||||
</Typography>
|
||||
<Controller
|
||||
name='imageUrl'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='https://example.com/image.jpg'
|
||||
type='url'
|
||||
InputProps={{
|
||||
startAdornment: (
|
||||
<InputAdornment position='start'>
|
||||
<i className='tabler-photo' />
|
||||
</InputAdornment>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Valid Until */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Masa Berlaku
|
||||
</Typography>
|
||||
<Controller
|
||||
name='hasValidUntil'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<FormControlLabel
|
||||
control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
|
||||
label='Memiliki batas waktu'
|
||||
className='mb-2'
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{watchedHasValidUntil && (
|
||||
<Controller
|
||||
name='validUntil'
|
||||
control={control}
|
||||
rules={{
|
||||
required: watchedHasValidUntil ? 'Tanggal kadaluarsa wajib diisi' : false
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='date'
|
||||
error={!!errors.validUntil}
|
||||
helperText={errors.validUntil?.message}
|
||||
InputLabelProps={{
|
||||
shrink: true
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Terms & Conditions */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Syarat & Ketentuan
|
||||
</Typography>
|
||||
<Controller
|
||||
name='terms'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='Syarat dan ketentuan penggunaan reward'
|
||||
multiline
|
||||
rows={3}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Sembunyikan */}
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
size='small'
|
||||
sx={{ textTransform: 'none', fontSize: '14px', p: 0, textAlign: 'left', width: '200px' }}
|
||||
onClick={() => setShowMore(false)}
|
||||
>
|
||||
- Sembunyikan
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</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='reward-form' disabled={isSubmitting}>
|
||||
{isSubmitting ? (isEditMode ? 'Mengupdate...' : 'Menyimpan...') : isEditMode ? 'Update' : 'Simpan'}
|
||||
</Button>
|
||||
<Button variant='outlined' color='error' onClick={handleReset} disabled={isSubmitting}>
|
||||
Batal
|
||||
</Button>
|
||||
</div>
|
||||
</Box>
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
|
||||
export default AddEditRewardDrawer
|
||||
661
src/views/apps/marketing/reward/RewardListTable.tsx
Normal file
661
src/views/apps/marketing/reward/RewardListTable.tsx
Normal file
@ -0,0 +1,661 @@
|
||||
'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 AddEditRewardDrawer from './AddEditRewardDrawer'
|
||||
|
||||
// Reward Catalog Type Interface
|
||||
export interface RewardCatalogType {
|
||||
id: string
|
||||
name: string
|
||||
description?: string
|
||||
pointCost: number
|
||||
stock?: number
|
||||
isActive: boolean
|
||||
validUntil?: Date
|
||||
imageUrl?: string
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}
|
||||
|
||||
declare module '@tanstack/table-core' {
|
||||
interface FilterFns {
|
||||
fuzzy: FilterFn<unknown>
|
||||
}
|
||||
interface FilterMeta {
|
||||
itemRank: RankingInfo
|
||||
}
|
||||
}
|
||||
|
||||
type RewardCatalogTypeWithAction = RewardCatalogType & {
|
||||
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)} />
|
||||
}
|
||||
|
||||
// Dummy data for reward catalog
|
||||
const DUMMY_REWARD_DATA: RewardCatalogType[] = [
|
||||
{
|
||||
id: '1',
|
||||
name: 'Voucher Diskon 50K',
|
||||
description: 'Voucher diskon Rp 50.000 untuk pembelian minimal Rp 200.000',
|
||||
pointCost: 500,
|
||||
stock: 100,
|
||||
isActive: true,
|
||||
validUntil: new Date('2024-12-31'),
|
||||
imageUrl: 'https://example.com/voucher-50k.jpg',
|
||||
createdAt: new Date('2024-01-15'),
|
||||
updatedAt: new Date('2024-02-10')
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
name: 'Free Shipping Voucher',
|
||||
description: 'Gratis ongkos kirim untuk seluruh Indonesia',
|
||||
pointCost: 200,
|
||||
stock: 500,
|
||||
isActive: true,
|
||||
validUntil: new Date('2024-06-30'),
|
||||
imageUrl: 'https://example.com/free-shipping.jpg',
|
||||
createdAt: new Date('2024-01-20'),
|
||||
updatedAt: new Date('2024-02-15')
|
||||
},
|
||||
{
|
||||
id: '3',
|
||||
name: 'Bluetooth Speaker Premium',
|
||||
description: 'Speaker bluetooth kualitas premium dengan bass yang menggelegar',
|
||||
pointCost: 2500,
|
||||
stock: 25,
|
||||
isActive: true,
|
||||
validUntil: new Date('2024-09-30'),
|
||||
imageUrl: 'https://example.com/bluetooth-speaker.jpg',
|
||||
createdAt: new Date('2024-01-25'),
|
||||
updatedAt: new Date('2024-02-20')
|
||||
},
|
||||
{
|
||||
id: '4',
|
||||
name: 'Voucher Cashback 20%',
|
||||
description: 'Cashback 20% maksimal Rp 100.000 untuk kategori elektronik',
|
||||
pointCost: 800,
|
||||
stock: 200,
|
||||
isActive: true,
|
||||
validUntil: new Date('2024-08-31'),
|
||||
createdAt: new Date('2024-02-01'),
|
||||
updatedAt: new Date('2024-02-25')
|
||||
},
|
||||
{
|
||||
id: '5',
|
||||
name: 'Smartwatch Fitness',
|
||||
description: 'Smartwatch dengan fitur fitness tracking dan heart rate monitor',
|
||||
pointCost: 5000,
|
||||
stock: 15,
|
||||
isActive: true,
|
||||
validUntil: new Date('2024-12-31'),
|
||||
createdAt: new Date('2024-02-05'),
|
||||
updatedAt: new Date('2024-03-01')
|
||||
},
|
||||
{
|
||||
id: '6',
|
||||
name: 'Tumbler Stainless Premium',
|
||||
description: 'Tumbler stainless steel 500ml dengan desain eksklusif',
|
||||
pointCost: 1200,
|
||||
stock: 50,
|
||||
isActive: true,
|
||||
validUntil: new Date('2024-10-31'),
|
||||
createdAt: new Date('2024-02-10'),
|
||||
updatedAt: new Date('2024-03-05')
|
||||
},
|
||||
{
|
||||
id: '7',
|
||||
name: 'Gift Card 100K',
|
||||
description: 'Gift card senilai Rp 100.000 yang bisa digunakan untuk semua produk',
|
||||
pointCost: 1000,
|
||||
stock: 300,
|
||||
isActive: true,
|
||||
validUntil: new Date('2024-12-31'),
|
||||
createdAt: new Date('2024-02-15'),
|
||||
updatedAt: new Date('2024-03-10')
|
||||
},
|
||||
{
|
||||
id: '8',
|
||||
name: 'Wireless Earbuds',
|
||||
description: 'Earbuds wireless dengan noise cancellation dan case charging',
|
||||
pointCost: 3500,
|
||||
stock: 30,
|
||||
isActive: true,
|
||||
validUntil: new Date('2024-11-30'),
|
||||
createdAt: new Date('2024-03-01'),
|
||||
updatedAt: new Date('2024-03-15')
|
||||
},
|
||||
{
|
||||
id: '9',
|
||||
name: 'Voucher Buy 1 Get 1',
|
||||
description: 'Beli 1 gratis 1 untuk kategori fashion wanita',
|
||||
pointCost: 600,
|
||||
stock: 150,
|
||||
isActive: false,
|
||||
validUntil: new Date('2024-07-31'),
|
||||
createdAt: new Date('2024-03-05'),
|
||||
updatedAt: new Date('2024-03-20')
|
||||
},
|
||||
{
|
||||
id: '10',
|
||||
name: 'Power Bank 20000mAh',
|
||||
description: 'Power bank fast charging 20000mAh dengan 3 port USB',
|
||||
pointCost: 1800,
|
||||
stock: 40,
|
||||
isActive: true,
|
||||
validUntil: new Date('2024-12-31'),
|
||||
createdAt: new Date('2024-03-10'),
|
||||
updatedAt: new Date('2024-03-25')
|
||||
},
|
||||
{
|
||||
id: '11',
|
||||
name: 'Backpack Travel Exclusive',
|
||||
description: 'Tas ransel travel anti air dengan compartment laptop',
|
||||
pointCost: 2200,
|
||||
stock: 20,
|
||||
isActive: true,
|
||||
validUntil: new Date('2024-09-30'),
|
||||
createdAt: new Date('2024-03-15'),
|
||||
updatedAt: new Date('2024-03-30')
|
||||
},
|
||||
{
|
||||
id: '12',
|
||||
name: 'Voucher Anniversary 75K',
|
||||
description: 'Voucher spesial anniversary diskon Rp 75.000 tanpa minimum pembelian',
|
||||
pointCost: 750,
|
||||
stock: 0,
|
||||
isActive: true,
|
||||
validUntil: new Date('2024-12-31'),
|
||||
createdAt: new Date('2024-03-20'),
|
||||
updatedAt: new Date('2024-04-05')
|
||||
}
|
||||
]
|
||||
|
||||
// Mock data hook with dummy data
|
||||
const useRewardCatalog = ({ page, limit, search }: { page: number; limit: number; search: string }) => {
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
// Simulate loading
|
||||
useEffect(() => {
|
||||
setIsLoading(true)
|
||||
const timer = setTimeout(() => setIsLoading(false), 500)
|
||||
return () => clearTimeout(timer)
|
||||
}, [page, limit, search])
|
||||
|
||||
// Filter data based on search
|
||||
const filteredData = useMemo(() => {
|
||||
if (!search) return DUMMY_REWARD_DATA
|
||||
|
||||
return DUMMY_REWARD_DATA.filter(
|
||||
reward =>
|
||||
reward.name.toLowerCase().includes(search.toLowerCase()) ||
|
||||
reward.description?.toLowerCase().includes(search.toLowerCase())
|
||||
)
|
||||
}, [search])
|
||||
|
||||
// Paginate data
|
||||
const paginatedData = useMemo(() => {
|
||||
const startIndex = (page - 1) * limit
|
||||
const endIndex = startIndex + limit
|
||||
return filteredData.slice(startIndex, endIndex)
|
||||
}, [filteredData, page, limit])
|
||||
|
||||
return {
|
||||
data: {
|
||||
rewards: paginatedData,
|
||||
total_count: filteredData.length
|
||||
},
|
||||
isLoading,
|
||||
error: null,
|
||||
isFetching: isLoading
|
||||
}
|
||||
}
|
||||
|
||||
// Column Definitions
|
||||
const columnHelper = createColumnHelper<RewardCatalogTypeWithAction>()
|
||||
|
||||
const RewardListTable = () => {
|
||||
// States
|
||||
const [addRewardOpen, setAddRewardOpen] = useState(false)
|
||||
const [editRewardData, setEditRewardData] = useState<RewardCatalogType | undefined>(undefined)
|
||||
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 } = useRewardCatalog({
|
||||
page: currentPage,
|
||||
limit: pageSize,
|
||||
search
|
||||
})
|
||||
|
||||
const rewards = data?.rewards ?? []
|
||||
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 handleEditReward = (reward: RewardCatalogType) => {
|
||||
setEditRewardData(reward)
|
||||
setAddRewardOpen(true)
|
||||
}
|
||||
|
||||
const handleDeleteReward = (rewardId: string) => {
|
||||
if (confirm('Apakah Anda yakin ingin menghapus reward ini?')) {
|
||||
console.log('Deleting reward:', rewardId)
|
||||
// Add your delete logic here
|
||||
// deleteReward.mutate(rewardId)
|
||||
}
|
||||
}
|
||||
|
||||
const handleToggleActive = (rewardId: string, currentStatus: boolean) => {
|
||||
console.log('Toggling active status for reward:', rewardId, !currentStatus)
|
||||
// Add your toggle logic here
|
||||
// toggleRewardStatus.mutate({ id: rewardId, isActive: !currentStatus })
|
||||
}
|
||||
|
||||
const handleCloseRewardDrawer = () => {
|
||||
setAddRewardOpen(false)
|
||||
setEditRewardData(undefined)
|
||||
}
|
||||
|
||||
const columns = useMemo<ColumnDef<RewardCatalogTypeWithAction, 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 Reward',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-4'>
|
||||
<CustomAvatar src={row.original.imageUrl} size={40}>
|
||||
{getInitials(row.original.name)}
|
||||
</CustomAvatar>
|
||||
<div className='flex flex-col'>
|
||||
<Link href={getLocalizedUrl(`/apps/rewards/${row.original.id}/detail`, locale as Locale)}>
|
||||
<Typography className='font-medium cursor-pointer hover:underline text-primary'>
|
||||
{row.original.name}
|
||||
</Typography>
|
||||
</Link>
|
||||
{row.original.description && (
|
||||
<Typography variant='caption' color='textSecondary' className='max-w-xs truncate'>
|
||||
{row.original.description}
|
||||
</Typography>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('pointCost', {
|
||||
header: 'Biaya Poin',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-2'>
|
||||
<Icon className='tabler-star-filled' sx={{ color: 'var(--mui-palette-warning-main)' }} />
|
||||
<Typography color='text.primary' className='font-medium'>
|
||||
{row.original.pointCost.toLocaleString('id-ID')} poin
|
||||
</Typography>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('stock', {
|
||||
header: 'Stok',
|
||||
cell: ({ row }) => {
|
||||
const stock = row.original.stock
|
||||
const stockColor = stock === 0 ? 'error' : stock && stock <= 10 ? 'warning' : 'success'
|
||||
const stockText = stock === undefined ? 'Unlimited' : stock === 0 ? 'Habis' : stock.toString()
|
||||
|
||||
return <Chip label={stockText} color={stockColor} variant='tonal' size='small' />
|
||||
}
|
||||
}),
|
||||
columnHelper.accessor('isActive', {
|
||||
header: 'Status',
|
||||
cell: ({ row }) => (
|
||||
<Chip
|
||||
label={row.original.isActive ? 'Aktif' : 'Nonaktif'}
|
||||
color={row.original.isActive ? 'success' : 'error'}
|
||||
variant='tonal'
|
||||
size='small'
|
||||
/>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('validUntil', {
|
||||
header: 'Berlaku Hingga',
|
||||
cell: ({ row }) => (
|
||||
<Typography color='text.primary'>
|
||||
{row.original.validUntil
|
||||
? new Date(row.original.validUntil).toLocaleDateString('id-ID', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
})
|
||||
: 'Tidak terbatas'}
|
||||
</Typography>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('createdAt', {
|
||||
header: 'Tanggal Dibuat',
|
||||
cell: ({ row }) => (
|
||||
<Typography color='text.primary'>
|
||||
{new Date(row.original.createdAt).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: row.original.isActive ? 'Nonaktifkan' : 'Aktifkan',
|
||||
icon: row.original.isActive ? 'tabler-eye-off text-[22px]' : 'tabler-eye text-[22px]',
|
||||
menuItemProps: {
|
||||
className: 'flex items-center gap-2 text-textSecondary',
|
||||
onClick: () => handleToggleActive(row.original.id, row.original.isActive)
|
||||
}
|
||||
},
|
||||
{
|
||||
text: 'Edit',
|
||||
icon: 'tabler-edit text-[22px]',
|
||||
menuItemProps: {
|
||||
className: 'flex items-center gap-2 text-textSecondary',
|
||||
onClick: () => handleEditReward(row.original)
|
||||
}
|
||||
},
|
||||
{
|
||||
text: 'Hapus',
|
||||
icon: 'tabler-trash text-[22px]',
|
||||
menuItemProps: {
|
||||
className: 'flex items-center gap-2 text-textSecondary',
|
||||
onClick: () => handleDeleteReward(row.original.id)
|
||||
}
|
||||
}
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
enableSorting: false
|
||||
}
|
||||
],
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[locale, handleEditReward, handleDeleteReward, handleToggleActive]
|
||||
)
|
||||
|
||||
const table = useReactTable({
|
||||
data: rewards as RewardCatalogType[],
|
||||
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 Reward'
|
||||
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={() => setAddRewardOpen(!addRewardOpen)}
|
||||
className='max-sm:is-full'
|
||||
>
|
||||
Tambah Reward
|
||||
</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>
|
||||
<AddEditRewardDrawer open={addRewardOpen} handleClose={handleCloseRewardDrawer} data={editRewardData} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default RewardListTable
|
||||
17
src/views/apps/marketing/reward/index.tsx
Normal file
17
src/views/apps/marketing/reward/index.tsx
Normal file
@ -0,0 +1,17 @@
|
||||
// MUI Imports
|
||||
import Grid from '@mui/material/Grid2'
|
||||
import RewardListTable from './RewardListTable'
|
||||
|
||||
// Type Imports
|
||||
|
||||
const RewardList = () => {
|
||||
return (
|
||||
<Grid container spacing={6}>
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<RewardListTable />
|
||||
</Grid>
|
||||
</Grid>
|
||||
)
|
||||
}
|
||||
|
||||
export default RewardList
|
||||
Loading…
x
Reference in New Issue
Block a user