efril #13
@ -0,0 +1,7 @@
|
|||||||
|
import CampaignListTable from '@/views/apps/marketing/campaign/CampaignListTable'
|
||||||
|
|
||||||
|
const CampaignPage = () => {
|
||||||
|
return <CampaignListTable />
|
||||||
|
}
|
||||||
|
|
||||||
|
export default CampaignPage
|
||||||
@ -0,0 +1,7 @@
|
|||||||
|
import CustomerAnalyticList from '@/views/apps/marketing/customer-analytics'
|
||||||
|
|
||||||
|
const CustomerAnalyticsPage = () => {
|
||||||
|
return <CustomerAnalyticList />
|
||||||
|
}
|
||||||
|
|
||||||
|
export default CustomerAnalyticsPage
|
||||||
@ -0,0 +1,7 @@
|
|||||||
|
import GamePrizeList from '@/views/apps/marketing/games/game-prizes'
|
||||||
|
|
||||||
|
const GamePrizePage = () => {
|
||||||
|
return <GamePrizeList />
|
||||||
|
}
|
||||||
|
|
||||||
|
export default GamePrizePage
|
||||||
@ -0,0 +1,7 @@
|
|||||||
|
import GamesList from '@/views/apps/marketing/games/list'
|
||||||
|
|
||||||
|
const GamePage = () => {
|
||||||
|
return <GamesList />
|
||||||
|
}
|
||||||
|
|
||||||
|
export default GamePage
|
||||||
@ -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
|
||||||
@ -0,0 +1,7 @@
|
|||||||
|
import TierList from '@/views/apps/marketing/tier'
|
||||||
|
|
||||||
|
const TierPage = () => {
|
||||||
|
return <TierList />
|
||||||
|
}
|
||||||
|
|
||||||
|
export default TierPage
|
||||||
@ -0,0 +1,7 @@
|
|||||||
|
import VoucherList from '@/views/apps/marketing/voucher'
|
||||||
|
|
||||||
|
const VoucherPage = () => {
|
||||||
|
return <VoucherList />
|
||||||
|
}
|
||||||
|
|
||||||
|
export default VoucherPage
|
||||||
465
src/components/MultipleImageUpload.tsx
Normal file
465
src/components/MultipleImageUpload.tsx
Normal file
@ -0,0 +1,465 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
// React Imports
|
||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
|
||||||
|
// MUI Imports
|
||||||
|
import type { BoxProps } from '@mui/material/Box'
|
||||||
|
import Button from '@mui/material/Button'
|
||||||
|
import IconButton from '@mui/material/IconButton'
|
||||||
|
import List from '@mui/material/List'
|
||||||
|
import ListItem from '@mui/material/ListItem'
|
||||||
|
import Typography from '@mui/material/Typography'
|
||||||
|
import Chip from '@mui/material/Chip'
|
||||||
|
import LinearProgress from '@mui/material/LinearProgress'
|
||||||
|
import { styled } from '@mui/material/styles'
|
||||||
|
|
||||||
|
// Third-party Imports
|
||||||
|
import { useDropzone } from 'react-dropzone'
|
||||||
|
|
||||||
|
// Component Imports
|
||||||
|
import Link from '@components/Link'
|
||||||
|
import CustomAvatar from '@core/components/mui/Avatar'
|
||||||
|
|
||||||
|
// Styled Component Imports
|
||||||
|
import AppReactDropzone from '@/libs/styles/AppReactDropzone'
|
||||||
|
|
||||||
|
type FileProp = {
|
||||||
|
name: string
|
||||||
|
type: string
|
||||||
|
size: number
|
||||||
|
}
|
||||||
|
|
||||||
|
type UploadedImage = {
|
||||||
|
id: string
|
||||||
|
url: string
|
||||||
|
name: string
|
||||||
|
size: number
|
||||||
|
}
|
||||||
|
|
||||||
|
type UploadProgress = {
|
||||||
|
[fileId: string]: number
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MultipleImageUploadProps {
|
||||||
|
// Required props
|
||||||
|
onUpload: (files: File[]) => Promise<string[]> | string[] // Returns array of image URLs
|
||||||
|
onSingleUpload?: (file: File) => Promise<string> | string // For individual file upload
|
||||||
|
|
||||||
|
// Optional customization props
|
||||||
|
title?: string | null
|
||||||
|
currentImages?: UploadedImage[]
|
||||||
|
onImagesChange?: (images: UploadedImage[]) => void
|
||||||
|
onImageRemove?: (imageId: string) => void
|
||||||
|
|
||||||
|
// Upload state
|
||||||
|
isUploading?: boolean
|
||||||
|
uploadProgress?: UploadProgress
|
||||||
|
|
||||||
|
// Limits
|
||||||
|
maxFiles?: number
|
||||||
|
maxFileSize?: number // in bytes
|
||||||
|
acceptedFileTypes?: string[]
|
||||||
|
|
||||||
|
// UI customization
|
||||||
|
showUrlOption?: boolean
|
||||||
|
uploadButtonText?: string
|
||||||
|
browseButtonText?: string
|
||||||
|
dragDropText?: string
|
||||||
|
replaceText?: string
|
||||||
|
maxFilesText?: string
|
||||||
|
|
||||||
|
// Style customization
|
||||||
|
className?: string
|
||||||
|
disabled?: boolean
|
||||||
|
|
||||||
|
// Upload modes
|
||||||
|
uploadMode?: 'batch' | 'individual' // batch: upload all at once, individual: upload one by one
|
||||||
|
}
|
||||||
|
|
||||||
|
// Styled Dropzone Component
|
||||||
|
const Dropzone = styled(AppReactDropzone)<BoxProps>(({ theme }) => ({
|
||||||
|
'& .dropzone': {
|
||||||
|
minHeight: 'unset',
|
||||||
|
padding: theme.spacing(12),
|
||||||
|
[theme.breakpoints.down('sm')]: {
|
||||||
|
paddingInline: theme.spacing(5)
|
||||||
|
},
|
||||||
|
'&+.MuiList-root .MuiListItem-root .file-name': {
|
||||||
|
fontWeight: theme.typography.body1.fontWeight
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
|
||||||
|
const MultipleImageUpload: React.FC<MultipleImageUploadProps> = ({
|
||||||
|
onUpload,
|
||||||
|
onSingleUpload,
|
||||||
|
title = null,
|
||||||
|
currentImages = [],
|
||||||
|
onImagesChange,
|
||||||
|
onImageRemove,
|
||||||
|
isUploading = false,
|
||||||
|
uploadProgress = {},
|
||||||
|
maxFiles = 10,
|
||||||
|
maxFileSize = 5 * 1024 * 1024, // 5MB default
|
||||||
|
acceptedFileTypes = ['image/*'],
|
||||||
|
showUrlOption = true,
|
||||||
|
uploadButtonText = 'Upload All',
|
||||||
|
browseButtonText = 'Browse Images',
|
||||||
|
dragDropText = 'Drag and Drop Your Images Here.',
|
||||||
|
replaceText = 'Drop Images to Add More',
|
||||||
|
maxFilesText = 'Maximum {max} files allowed',
|
||||||
|
className = '',
|
||||||
|
disabled = false,
|
||||||
|
uploadMode = 'batch'
|
||||||
|
}) => {
|
||||||
|
// States
|
||||||
|
const [files, setFiles] = useState<File[]>([])
|
||||||
|
const [error, setError] = useState<string>('')
|
||||||
|
const [individualUploading, setIndividualUploading] = useState<Set<string>>(new Set())
|
||||||
|
|
||||||
|
const handleBatchUpload = async () => {
|
||||||
|
if (!files.length) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
setError('')
|
||||||
|
const imageUrls = await onUpload(files)
|
||||||
|
|
||||||
|
if (Array.isArray(imageUrls)) {
|
||||||
|
const newImages: UploadedImage[] = files.map((file, index) => ({
|
||||||
|
id: `${Date.now()}-${index}`,
|
||||||
|
url: imageUrls[index],
|
||||||
|
name: file.name,
|
||||||
|
size: file.size
|
||||||
|
}))
|
||||||
|
|
||||||
|
const updatedImages = [...currentImages, ...newImages]
|
||||||
|
onImagesChange?.(updatedImages)
|
||||||
|
setFiles([]) // Clear files after successful upload
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Upload failed')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleIndividualUpload = async (file: File, fileIndex: number) => {
|
||||||
|
if (!onSingleUpload) return
|
||||||
|
|
||||||
|
const fileId = `${file.name}-${fileIndex}`
|
||||||
|
setIndividualUploading(prev => new Set(prev).add(fileId))
|
||||||
|
|
||||||
|
try {
|
||||||
|
setError('')
|
||||||
|
const imageUrl = await onSingleUpload(file)
|
||||||
|
|
||||||
|
if (typeof imageUrl === 'string') {
|
||||||
|
const newImage: UploadedImage = {
|
||||||
|
id: `${Date.now()}-${fileIndex}`,
|
||||||
|
url: imageUrl,
|
||||||
|
name: file.name,
|
||||||
|
size: file.size
|
||||||
|
}
|
||||||
|
|
||||||
|
const updatedImages = [...currentImages, newImage]
|
||||||
|
onImagesChange?.(updatedImages)
|
||||||
|
|
||||||
|
// Remove uploaded file from pending files
|
||||||
|
setFiles(prev => prev.filter((_, index) => index !== fileIndex))
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Upload failed')
|
||||||
|
} finally {
|
||||||
|
setIndividualUploading(prev => {
|
||||||
|
const newSet = new Set(prev)
|
||||||
|
newSet.delete(fileId)
|
||||||
|
return newSet
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hooks
|
||||||
|
const { getRootProps, getInputProps } = useDropzone({
|
||||||
|
onDrop: (acceptedFiles: File[]) => {
|
||||||
|
setError('')
|
||||||
|
|
||||||
|
if (acceptedFiles.length === 0) return
|
||||||
|
|
||||||
|
const totalFiles = currentImages.length + files.length + acceptedFiles.length
|
||||||
|
|
||||||
|
if (totalFiles > maxFiles) {
|
||||||
|
setError(`Cannot upload more than ${maxFiles} files. Current: ${currentImages.length + files.length}`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate file sizes
|
||||||
|
const invalidFiles = acceptedFiles.filter(file => file.size > maxFileSize)
|
||||||
|
if (invalidFiles.length > 0) {
|
||||||
|
setError(`Some files exceed ${formatFileSize(maxFileSize)} limit`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add to existing files
|
||||||
|
setFiles(prev => [...prev, ...acceptedFiles])
|
||||||
|
},
|
||||||
|
accept: acceptedFileTypes.reduce((acc, type) => ({ ...acc, [type]: [] }), {}),
|
||||||
|
disabled: disabled || isUploading,
|
||||||
|
multiple: true
|
||||||
|
})
|
||||||
|
|
||||||
|
const formatFileSize = (bytes: number): string => {
|
||||||
|
if (bytes === 0) return '0 Bytes'
|
||||||
|
const k = 1024
|
||||||
|
const sizes = ['Bytes', 'KB', 'MB', 'GB']
|
||||||
|
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||||
|
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
|
||||||
|
}
|
||||||
|
|
||||||
|
const renderFilePreview = (file: FileProp) => {
|
||||||
|
if (file.type.startsWith('image')) {
|
||||||
|
return (
|
||||||
|
<img
|
||||||
|
width={38}
|
||||||
|
height={38}
|
||||||
|
alt={file.name}
|
||||||
|
src={URL.createObjectURL(file as any)}
|
||||||
|
className='rounded object-cover'
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
return <i className='tabler-file-description' />
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleRemoveFile = (fileIndex: number) => {
|
||||||
|
setFiles(prev => prev.filter((_, index) => index !== fileIndex))
|
||||||
|
setError('')
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleRemoveCurrentImage = (imageId: string) => {
|
||||||
|
onImageRemove?.(imageId)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleRemoveAllFiles = () => {
|
||||||
|
setFiles([])
|
||||||
|
setError('')
|
||||||
|
}
|
||||||
|
|
||||||
|
const isIndividualUploading = (file: File, index: number) => {
|
||||||
|
const fileId = `${file.name}-${index}`
|
||||||
|
return individualUploading.has(fileId)
|
||||||
|
}
|
||||||
|
|
||||||
|
const fileList = files.map((file: File, index: number) => {
|
||||||
|
const isFileUploading = isIndividualUploading(file, index)
|
||||||
|
const progress = uploadProgress[`${file.name}-${index}`] || 0
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ListItem key={`${file.name}-${index}`} className='pis-4 plb-3'>
|
||||||
|
<div className='file-details flex-1'>
|
||||||
|
<div className='file-preview'>{renderFilePreview(file)}</div>
|
||||||
|
<div className='flex-1'>
|
||||||
|
<Typography className='file-name font-medium' color='text.primary'>
|
||||||
|
{file.name}
|
||||||
|
</Typography>
|
||||||
|
<Typography className='file-size' variant='body2'>
|
||||||
|
{formatFileSize(file.size)}
|
||||||
|
</Typography>
|
||||||
|
{isFileUploading && progress > 0 && (
|
||||||
|
<LinearProgress variant='determinate' value={progress} className='mt-1' />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className='flex items-center gap-2'>
|
||||||
|
{uploadMode === 'individual' && onSingleUpload && (
|
||||||
|
<Button
|
||||||
|
variant='outlined'
|
||||||
|
size='small'
|
||||||
|
onClick={() => handleIndividualUpload(file, index)}
|
||||||
|
disabled={isUploading || isFileUploading}
|
||||||
|
>
|
||||||
|
{isFileUploading ? 'Uploading...' : 'Upload'}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<IconButton onClick={() => handleRemoveFile(index)} disabled={isUploading || isFileUploading}>
|
||||||
|
<i className='tabler-x text-xl' />
|
||||||
|
</IconButton>
|
||||||
|
</div>
|
||||||
|
</ListItem>
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
const currentImagesList = currentImages.map(image => (
|
||||||
|
<ListItem key={image.id} className='pis-4 plb-3'>
|
||||||
|
<div className='file-details flex-1'>
|
||||||
|
<div className='file-preview'>
|
||||||
|
<img width={38} height={38} alt={image.name} src={image.url} className='rounded object-cover' />
|
||||||
|
</div>
|
||||||
|
<div className='flex-1'>
|
||||||
|
<Typography className='file-name font-medium' color='text.primary'>
|
||||||
|
{image.name}
|
||||||
|
</Typography>
|
||||||
|
<Typography className='file-size' variant='body2'>
|
||||||
|
{formatFileSize(image.size)}
|
||||||
|
</Typography>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className='flex items-center gap-2'>
|
||||||
|
<Chip label='Uploaded' color='success' size='small' />
|
||||||
|
{onImageRemove && (
|
||||||
|
<IconButton onClick={() => handleRemoveCurrentImage(image.id)} color='error' disabled={isUploading}>
|
||||||
|
<i className='tabler-x text-xl' />
|
||||||
|
</IconButton>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</ListItem>
|
||||||
|
))
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dropzone className={className}>
|
||||||
|
{/* Conditional title and URL option header */}
|
||||||
|
{title && (
|
||||||
|
<div className='flex justify-between items-center mb-4'>
|
||||||
|
<Typography variant='h6' component='h2'>
|
||||||
|
{title}
|
||||||
|
</Typography>
|
||||||
|
{showUrlOption && (
|
||||||
|
<Typography component={Link} color='primary.main' className='font-medium'>
|
||||||
|
Add media from URL
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* File limits info */}
|
||||||
|
<div className='flex justify-between items-center mb-4'>
|
||||||
|
<Typography variant='body2' color='text.secondary'>
|
||||||
|
{maxFilesText.replace('{max}', maxFiles.toString())}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant='body2' color='text.secondary'>
|
||||||
|
{currentImages.length + files.length} / {maxFiles} files
|
||||||
|
</Typography>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div {...getRootProps({ className: 'dropzone' })}>
|
||||||
|
<input {...getInputProps()} />
|
||||||
|
<div className='flex items-center flex-col gap-2 text-center'>
|
||||||
|
<CustomAvatar variant='rounded' skin='light' color='secondary'>
|
||||||
|
<i className='tabler-upload' />
|
||||||
|
</CustomAvatar>
|
||||||
|
<Typography variant='h4'>
|
||||||
|
{currentImages.length > 0 || files.length > 0 ? replaceText : dragDropText}
|
||||||
|
</Typography>
|
||||||
|
<Typography color='text.disabled'>or</Typography>
|
||||||
|
<Button variant='tonal' size='small' disabled={disabled || isUploading}>
|
||||||
|
{browseButtonText}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Error Message */}
|
||||||
|
{error && (
|
||||||
|
<Typography color='error' variant='body2' className='mt-2 text-center'>
|
||||||
|
{error}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Current uploaded images */}
|
||||||
|
{currentImages.length > 0 && (
|
||||||
|
<div className='mt-4'>
|
||||||
|
<Typography variant='subtitle2' className='mb-2'>
|
||||||
|
Uploaded Images ({currentImages.length}):
|
||||||
|
</Typography>
|
||||||
|
<List>{currentImagesList}</List>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Pending files list and upload buttons */}
|
||||||
|
{files.length > 0 && (
|
||||||
|
<div className='mt-4'>
|
||||||
|
<Typography variant='subtitle2' className='mb-2'>
|
||||||
|
Pending Files ({files.length}):
|
||||||
|
</Typography>
|
||||||
|
<List>{fileList}</List>
|
||||||
|
<div className='buttons flex gap-2 mt-3'>
|
||||||
|
<Button color='error' variant='tonal' onClick={handleRemoveAllFiles} disabled={isUploading}>
|
||||||
|
Remove All
|
||||||
|
</Button>
|
||||||
|
{uploadMode === 'batch' && (
|
||||||
|
<Button variant='contained' onClick={handleBatchUpload} disabled={isUploading || files.length === 0}>
|
||||||
|
{isUploading ? 'Uploading...' : `${uploadButtonText} (${files.length})`}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Dropzone>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default MultipleImageUpload
|
||||||
|
|
||||||
|
// ===== USAGE EXAMPLES =====
|
||||||
|
|
||||||
|
// 1. Batch upload mode (upload all files at once)
|
||||||
|
// const [images, setImages] = useState<UploadedImage[]>([])
|
||||||
|
//
|
||||||
|
// <MultipleImageUpload
|
||||||
|
// title="Product Images"
|
||||||
|
// onUpload={handleBatchUpload}
|
||||||
|
// currentImages={images}
|
||||||
|
// onImagesChange={setImages}
|
||||||
|
// onImageRemove={(id) => setImages(prev => prev.filter(img => img.id !== id))}
|
||||||
|
// maxFiles={5}
|
||||||
|
// uploadMode="batch"
|
||||||
|
// />
|
||||||
|
|
||||||
|
// 2. Individual upload mode (upload files one by one)
|
||||||
|
// <MultipleImageUpload
|
||||||
|
// title="Gallery Images"
|
||||||
|
// onUpload={handleBatchUpload}
|
||||||
|
// onSingleUpload={handleSingleUpload}
|
||||||
|
// currentImages={images}
|
||||||
|
// onImagesChange={setImages}
|
||||||
|
// onImageRemove={(id) => setImages(prev => prev.filter(img => img.id !== id))}
|
||||||
|
// maxFiles={10}
|
||||||
|
// uploadMode="individual"
|
||||||
|
// uploadProgress={uploadProgress}
|
||||||
|
// />
|
||||||
|
|
||||||
|
// 3. Without title, custom limits
|
||||||
|
// <MultipleImageUpload
|
||||||
|
// title={null}
|
||||||
|
// onUpload={handleBatchUpload}
|
||||||
|
// currentImages={images}
|
||||||
|
// onImagesChange={setImages}
|
||||||
|
// maxFiles={3}
|
||||||
|
// maxFileSize={2 * 1024 * 1024} // 2MB
|
||||||
|
// acceptedFileTypes={['image/jpeg', 'image/png']}
|
||||||
|
// />
|
||||||
|
|
||||||
|
// 4. Example upload handlers
|
||||||
|
// const handleBatchUpload = async (files: File[]): Promise<string[]> => {
|
||||||
|
// const formData = new FormData()
|
||||||
|
// files.forEach(file => formData.append('images', file))
|
||||||
|
//
|
||||||
|
// const response = await fetch('/api/upload-multiple', {
|
||||||
|
// method: 'POST',
|
||||||
|
// body: formData
|
||||||
|
// })
|
||||||
|
//
|
||||||
|
// const result = await response.json()
|
||||||
|
// return result.urls // Array of uploaded image URLs
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// const handleSingleUpload = async (file: File): Promise<string> => {
|
||||||
|
// const formData = new FormData()
|
||||||
|
// formData.append('image', file)
|
||||||
|
//
|
||||||
|
// const response = await fetch('/api/upload-single', {
|
||||||
|
// method: 'POST',
|
||||||
|
// body: formData
|
||||||
|
// })
|
||||||
|
//
|
||||||
|
// const result = await response.json()
|
||||||
|
// return result.url // Single uploaded image URL
|
||||||
|
// }
|
||||||
@ -153,6 +153,27 @@ const VerticalMenu = ({ dictionary, scrollMenu }: Props) => {
|
|||||||
>
|
>
|
||||||
{dictionary['navigation'].reports}
|
{dictionary['navigation'].reports}
|
||||||
</MenuItem>
|
</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 label={dictionary['navigation'].games}>
|
||||||
|
<MenuItem href={`/${locale}/apps/marketing/games/list`}>{dictionary['navigation'].list}</MenuItem>
|
||||||
|
<MenuItem href={`/${locale}/apps/marketing/games/game-prizes`}>
|
||||||
|
{dictionary['navigation'].game_prizes}
|
||||||
|
</MenuItem>
|
||||||
|
</SubMenu>
|
||||||
|
<MenuItem href={`/${locale}/apps/marketing/campaign`}>{dictionary['navigation'].campaign}</MenuItem>
|
||||||
|
{/* <MenuItem href={`/${locale}/apps/marketing/customer-analytics`}>
|
||||||
|
{dictionary['navigation'].customer_analytics}
|
||||||
|
</MenuItem> */}
|
||||||
|
{/* <MenuItem href={`/${locale}/apps/marketing/voucher`}>{dictionary['navigation'].voucher}</MenuItem> */}
|
||||||
|
<MenuItem href={`/${locale}/apps/marketing/tier`}>{dictionary['navigation'].tiers_text}</MenuItem>
|
||||||
|
</SubMenu>
|
||||||
<SubMenu label={dictionary['navigation'].inventory} icon={<i className='tabler-salad' />}>
|
<SubMenu label={dictionary['navigation'].inventory} icon={<i className='tabler-salad' />}>
|
||||||
<SubMenu label={dictionary['navigation'].products}>
|
<SubMenu label={dictionary['navigation'].products}>
|
||||||
<MenuItem href={`/${locale}/apps/inventory/products/list`}>{dictionary['navigation'].list}</MenuItem>
|
<MenuItem href={`/${locale}/apps/inventory/products/list`}>{dictionary['navigation'].list}</MenuItem>
|
||||||
|
|||||||
@ -126,6 +126,17 @@
|
|||||||
"expenses": "Expenses",
|
"expenses": "Expenses",
|
||||||
"cash_and_bank": "Cash & Bank",
|
"cash_and_bank": "Cash & Bank",
|
||||||
"account": "Account",
|
"account": "Account",
|
||||||
"fixed_assets": "Fixed Assets"
|
"fixed_assets": "Fixed Assets",
|
||||||
|
"marketing": "Marketing",
|
||||||
|
"loyalty": "Loyalty",
|
||||||
|
"reward": "Reward",
|
||||||
|
"gamification": "Gamification",
|
||||||
|
"wheel_spin": "Wheel Spin",
|
||||||
|
"campaign": "Campaign",
|
||||||
|
"customer_analytics": "Customer Analytics",
|
||||||
|
"voucher": "Voucher",
|
||||||
|
"tiers_text": "Tiers",
|
||||||
|
"games": "Games",
|
||||||
|
"game_prizes": "Game Prizes"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -126,6 +126,17 @@
|
|||||||
"expenses": "Biaya",
|
"expenses": "Biaya",
|
||||||
"cash_and_bank": "Kas & Bank",
|
"cash_and_bank": "Kas & Bank",
|
||||||
"account": "Akun",
|
"account": "Akun",
|
||||||
"fixed_assets": "Aset Tetap"
|
"fixed_assets": "Aset Tetap",
|
||||||
|
"marketing": "Pemasaran",
|
||||||
|
"loyalty": "Loyalti",
|
||||||
|
"reward": "Reward",
|
||||||
|
"gamification": "Gamifikasi",
|
||||||
|
"wheel_spin": "Wheel Spin",
|
||||||
|
"campaign": "Kampanye",
|
||||||
|
"customer_analytics": "Analisis Pelanggan",
|
||||||
|
"voucher": "Vocher",
|
||||||
|
"tiers_text": "Tiers",
|
||||||
|
"games": "Permainan",
|
||||||
|
"game_prizes": "Hadiah Permainan"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -6,7 +6,7 @@ const getToken = () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const api = axios.create({
|
export const api = axios.create({
|
||||||
baseURL: 'https://api-pos.apskel.id/api/v1',
|
baseURL: 'https://enaklo-pos-be.altru.id/api/v1',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
},
|
},
|
||||||
@ -30,9 +30,10 @@ api.interceptors.response.use(
|
|||||||
response => response,
|
response => response,
|
||||||
error => {
|
error => {
|
||||||
const status = error.response?.status
|
const status = error.response?.status
|
||||||
const currentPath = window.location.pathname
|
|
||||||
|
|
||||||
if (status === 401 && !currentPath.endsWith('/login')) {
|
if (status === 401) {
|
||||||
|
localStorage.removeItem('user')
|
||||||
|
localStorage.removeItem('authToken')
|
||||||
window.location.href = '/login'
|
window.location.href = '/login'
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -47,4 +48,3 @@ api.interceptors.response.use(
|
|||||||
return Promise.reject(error)
|
return Promise.reject(error)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
52
src/services/mutations/campaign.ts
Normal file
52
src/services/mutations/campaign.ts
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
import { CampaignRequest } from '@/types/services/campaign'
|
||||||
|
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { toast } from 'react-toastify'
|
||||||
|
import { api } from '../api'
|
||||||
|
|
||||||
|
export const useCampaignsMutation = () => {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
const createCampaign = useMutation({
|
||||||
|
mutationFn: async (newCampaign: CampaignRequest) => {
|
||||||
|
const response = await api.post('/marketing/campaigns', newCampaign)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('Campaign created successfully!')
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['campaigns'] })
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const updateCampaign = useMutation({
|
||||||
|
mutationFn: async ({ id, payload }: { id: string; payload: CampaignRequest }) => {
|
||||||
|
const response = await api.put(`/marketing/campaigns/${id}`, payload)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('Campaign updated successfully!')
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['campaigns'] })
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
toast.error(error.response?.data?.errors?.[0]?.cause || 'Update failed')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const deleteCampaign = useMutation({
|
||||||
|
mutationFn: async (id: string) => {
|
||||||
|
const response = await api.delete(`/marketing/campaigns/${id}`)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('Campaign deleted successfully!')
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['campaigns'] })
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
toast.error(error.response?.data?.errors?.[0]?.cause || 'Delete failed')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return { createCampaign, updateCampaign, deleteCampaign }
|
||||||
|
}
|
||||||
52
src/services/mutations/game.ts
Normal file
52
src/services/mutations/game.ts
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
import { GameRequest } from '@/types/services/game'
|
||||||
|
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { toast } from 'react-toastify'
|
||||||
|
import { api } from '../api'
|
||||||
|
|
||||||
|
export const useGamesMutation = () => {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
const createGame = useMutation({
|
||||||
|
mutationFn: async (newGame: GameRequest) => {
|
||||||
|
const response = await api.post('/marketing/games', newGame)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('Game created successfully!')
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['games'] })
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const updateGame = useMutation({
|
||||||
|
mutationFn: async ({ id, payload }: { id: string; payload: GameRequest }) => {
|
||||||
|
const response = await api.put(`/marketing/games/${id}`, payload)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('Game updated successfully!')
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['games'] })
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
toast.error(error.response?.data?.errors?.[0]?.cause || 'Update failed')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const deleteGame = useMutation({
|
||||||
|
mutationFn: async (id: string) => {
|
||||||
|
const response = await api.delete(`/marketing/games/${id}`)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('Game deleted successfully!')
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['games'] })
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
toast.error(error.response?.data?.errors?.[0]?.cause || 'Delete failed')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return { createGame, updateGame, deleteGame }
|
||||||
|
}
|
||||||
52
src/services/mutations/gamePrize.ts
Normal file
52
src/services/mutations/gamePrize.ts
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
import { GamePrizeRequest } from '@/types/services/gamePrize'
|
||||||
|
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { toast } from 'react-toastify'
|
||||||
|
import { api } from '../api'
|
||||||
|
|
||||||
|
export const useGamePrizesMutation = () => {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
const createGamePrize = useMutation({
|
||||||
|
mutationFn: async (newGamePrize: GamePrizeRequest) => {
|
||||||
|
const response = await api.post('/marketing/game-prizes', newGamePrize)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('GamePrize created successfully!')
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['gamePrizes'] })
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const updateGamePrize = useMutation({
|
||||||
|
mutationFn: async ({ id, payload }: { id: string; payload: GamePrizeRequest }) => {
|
||||||
|
const response = await api.put(`/marketing/game-prizes/${id}`, payload)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('GamePrize updated successfully!')
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['gamePrizes'] })
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
toast.error(error.response?.data?.errors?.[0]?.cause || 'Update failed')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const deleteGamePrize = useMutation({
|
||||||
|
mutationFn: async (id: string) => {
|
||||||
|
const response = await api.delete(`/marketing/game-prizes/${id}`)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('GamePrize deleted successfully!')
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['gamePrizes'] })
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
toast.error(error.response?.data?.errors?.[0]?.cause || 'Delete failed')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return { createGamePrize, updateGamePrize, deleteGamePrize }
|
||||||
|
}
|
||||||
52
src/services/mutations/reward.ts
Normal file
52
src/services/mutations/reward.ts
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
import { RewardRequest } from '@/types/services/reward'
|
||||||
|
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { toast } from 'react-toastify'
|
||||||
|
import { api } from '../api'
|
||||||
|
|
||||||
|
export const useRewardsMutation = () => {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
const createReward = useMutation({
|
||||||
|
mutationFn: async (newReward: RewardRequest) => {
|
||||||
|
const response = await api.post('/marketing/rewards', newReward)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('Reward created successfully!')
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['rewards'] })
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const updateReward = useMutation({
|
||||||
|
mutationFn: async ({ id, payload }: { id: string; payload: RewardRequest }) => {
|
||||||
|
const response = await api.put(`/marketing/rewards/${id}`, payload)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('Reward updated successfully!')
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['rewards'] })
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
toast.error(error.response?.data?.errors?.[0]?.cause || 'Update failed')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const deleteReward = useMutation({
|
||||||
|
mutationFn: async (id: string) => {
|
||||||
|
const response = await api.delete(`/marketing/rewards/${id}`)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('Reward deleted successfully!')
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['rewards'] })
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
toast.error(error.response?.data?.errors?.[0]?.cause || 'Delete failed')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return { createReward, updateReward, deleteReward }
|
||||||
|
}
|
||||||
52
src/services/mutations/tier.ts
Normal file
52
src/services/mutations/tier.ts
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
import { TierRequest } from '@/types/services/tier'
|
||||||
|
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { toast } from 'react-toastify'
|
||||||
|
import { api } from '../api'
|
||||||
|
|
||||||
|
export const useTiersMutation = () => {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
const createTier = useMutation({
|
||||||
|
mutationFn: async (newTier: TierRequest) => {
|
||||||
|
const response = await api.post('/marketing/tiers', newTier)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('Tier created successfully!')
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['tiers'] })
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const updateTier = useMutation({
|
||||||
|
mutationFn: async ({ id, payload }: { id: string; payload: TierRequest }) => {
|
||||||
|
const response = await api.put(`/marketing/tiers/${id}`, payload)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('Tier updated successfully!')
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['tiers'] })
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
toast.error(error.response?.data?.errors?.[0]?.cause || 'Update failed')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const deleteTier = useMutation({
|
||||||
|
mutationFn: async (id: string) => {
|
||||||
|
const response = await api.delete(`/marketing/tiers/${id}`)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('Tier deleted successfully!')
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['tiers'] })
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
toast.error(error.response?.data?.errors?.[0]?.cause || 'Delete failed')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return { createTier, updateTier, deleteTier }
|
||||||
|
}
|
||||||
46
src/services/queries/campaign.ts
Normal file
46
src/services/queries/campaign.ts
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { api } from '../api'
|
||||||
|
import { Campaign, Campaigns } from '@/types/services/campaign'
|
||||||
|
|
||||||
|
interface CampaignQueryParams {
|
||||||
|
page?: number
|
||||||
|
limit?: number
|
||||||
|
search?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCampaigns(params: CampaignQueryParams = {}) {
|
||||||
|
const { page = 1, limit = 10, search = '', ...filters } = params
|
||||||
|
|
||||||
|
return useQuery<Campaigns>({
|
||||||
|
queryKey: ['campaigns', { page, limit, search, ...filters }],
|
||||||
|
queryFn: async () => {
|
||||||
|
const queryParams = new URLSearchParams()
|
||||||
|
|
||||||
|
queryParams.append('page', page.toString())
|
||||||
|
queryParams.append('limit', limit.toString())
|
||||||
|
|
||||||
|
if (search) {
|
||||||
|
queryParams.append('search', search)
|
||||||
|
}
|
||||||
|
|
||||||
|
Object.entries(filters).forEach(([key, value]) => {
|
||||||
|
if (value !== undefined && value !== null && value !== '') {
|
||||||
|
queryParams.append(key, value.toString())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const res = await api.get(`/marketing/campaigns?${queryParams.toString()}`)
|
||||||
|
return res.data.data
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCampaignById(id: string) {
|
||||||
|
return useQuery<Campaign>({
|
||||||
|
queryKey: ['campaigns', id],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await api.get(`/marketing/campaigns/${id}`)
|
||||||
|
return res.data.data
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
46
src/services/queries/game.ts
Normal file
46
src/services/queries/game.ts
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { api } from '../api'
|
||||||
|
import { Game, Games } from '@/types/services/game'
|
||||||
|
|
||||||
|
interface GameQueryParams {
|
||||||
|
page?: number
|
||||||
|
limit?: number
|
||||||
|
search?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useGames(params: GameQueryParams = {}) {
|
||||||
|
const { page = 1, limit = 10, search = '', ...filters } = params
|
||||||
|
|
||||||
|
return useQuery<Games>({
|
||||||
|
queryKey: ['games', { page, limit, search, ...filters }],
|
||||||
|
queryFn: async () => {
|
||||||
|
const queryParams = new URLSearchParams()
|
||||||
|
|
||||||
|
queryParams.append('page', page.toString())
|
||||||
|
queryParams.append('limit', limit.toString())
|
||||||
|
|
||||||
|
if (search) {
|
||||||
|
queryParams.append('search', search)
|
||||||
|
}
|
||||||
|
|
||||||
|
Object.entries(filters).forEach(([key, value]) => {
|
||||||
|
if (value !== undefined && value !== null && value !== '') {
|
||||||
|
queryParams.append(key, value.toString())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const res = await api.get(`/marketing/games?${queryParams.toString()}`)
|
||||||
|
return res.data.data
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useGameById(id: string) {
|
||||||
|
return useQuery<Game>({
|
||||||
|
queryKey: ['games', id],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await api.get(`/marketing/games/${id}`)
|
||||||
|
return res.data.data
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
46
src/services/queries/gamePrize.ts
Normal file
46
src/services/queries/gamePrize.ts
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { api } from '../api'
|
||||||
|
import { GamePrize, GamePrizes } from '@/types/services/gamePrize'
|
||||||
|
|
||||||
|
interface GamePrizeQueryParams {
|
||||||
|
page?: number
|
||||||
|
limit?: number
|
||||||
|
search?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useGamePrizes(params: GamePrizeQueryParams = {}) {
|
||||||
|
const { page = 1, limit = 10, search = '', ...filters } = params
|
||||||
|
|
||||||
|
return useQuery<GamePrizes>({
|
||||||
|
queryKey: ['gamePrizes', { page, limit, search, ...filters }],
|
||||||
|
queryFn: async () => {
|
||||||
|
const queryParams = new URLSearchParams()
|
||||||
|
|
||||||
|
queryParams.append('page', page.toString())
|
||||||
|
queryParams.append('limit', limit.toString())
|
||||||
|
|
||||||
|
if (search) {
|
||||||
|
queryParams.append('search', search)
|
||||||
|
}
|
||||||
|
|
||||||
|
Object.entries(filters).forEach(([key, value]) => {
|
||||||
|
if (value !== undefined && value !== null && value !== '') {
|
||||||
|
queryParams.append(key, value.toString())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const res = await api.get(`/marketing/game-prizes?${queryParams.toString()}`)
|
||||||
|
return res.data.data
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useGamePrizeById(id: string) {
|
||||||
|
return useQuery<GamePrize>({
|
||||||
|
queryKey: ['gamePrizes', id],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await api.get(`/marketing/game-prizes/${id}`)
|
||||||
|
return res.data.data
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
46
src/services/queries/reward.ts
Normal file
46
src/services/queries/reward.ts
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { api } from '../api'
|
||||||
|
import { Reward, Rewards } from '@/types/services/reward'
|
||||||
|
|
||||||
|
interface RewardQueryParams {
|
||||||
|
page?: number
|
||||||
|
limit?: number
|
||||||
|
search?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useRewards(params: RewardQueryParams = {}) {
|
||||||
|
const { page = 1, limit = 10, search = '', ...filters } = params
|
||||||
|
|
||||||
|
return useQuery<Rewards>({
|
||||||
|
queryKey: ['rewards', { page, limit, search, ...filters }],
|
||||||
|
queryFn: async () => {
|
||||||
|
const queryParams = new URLSearchParams()
|
||||||
|
|
||||||
|
queryParams.append('page', page.toString())
|
||||||
|
queryParams.append('limit', limit.toString())
|
||||||
|
|
||||||
|
if (search) {
|
||||||
|
queryParams.append('search', search)
|
||||||
|
}
|
||||||
|
|
||||||
|
Object.entries(filters).forEach(([key, value]) => {
|
||||||
|
if (value !== undefined && value !== null && value !== '') {
|
||||||
|
queryParams.append(key, value.toString())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const res = await api.get(`/marketing/rewards?${queryParams.toString()}`)
|
||||||
|
return res.data.data
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useRewardById(id: string) {
|
||||||
|
return useQuery<Reward>({
|
||||||
|
queryKey: ['rewards', id],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await api.get(`/marketing/rewards/${id}`)
|
||||||
|
return res.data.data
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
46
src/services/queries/tier.ts
Normal file
46
src/services/queries/tier.ts
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { api } from '../api'
|
||||||
|
import { Tier, Tiers } from '@/types/services/tier'
|
||||||
|
|
||||||
|
interface TierQueryParams {
|
||||||
|
page?: number
|
||||||
|
limit?: number
|
||||||
|
search?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useTiers(params: TierQueryParams = {}) {
|
||||||
|
const { page = 1, limit = 10, search = '', ...filters } = params
|
||||||
|
|
||||||
|
return useQuery<Tiers>({
|
||||||
|
queryKey: ['tiers', { page, limit, search, ...filters }],
|
||||||
|
queryFn: async () => {
|
||||||
|
const queryParams = new URLSearchParams()
|
||||||
|
|
||||||
|
queryParams.append('page', page.toString())
|
||||||
|
queryParams.append('limit', limit.toString())
|
||||||
|
|
||||||
|
if (search) {
|
||||||
|
queryParams.append('search', search)
|
||||||
|
}
|
||||||
|
|
||||||
|
Object.entries(filters).forEach(([key, value]) => {
|
||||||
|
if (value !== undefined && value !== null && value !== '') {
|
||||||
|
queryParams.append(key, value.toString())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const res = await api.get(`/marketing/tiers?${queryParams.toString()}`)
|
||||||
|
return res.data.data
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useTierById(id: string) {
|
||||||
|
return useQuery<Tier>({
|
||||||
|
queryKey: ['tiers', id],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await api.get(`/marketing/tiers/${id}`)
|
||||||
|
return res.data.data
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
63
src/types/services/campaign.ts
Normal file
63
src/types/services/campaign.ts
Normal file
@ -0,0 +1,63 @@
|
|||||||
|
export type CampaignType = 'REWARD' | 'POINTS' | 'TOKENS' | 'MIXED'
|
||||||
|
|
||||||
|
export type RuleType = 'TIER' | 'SPEND' | 'PRODUCT' | 'CATEGORY' | 'DAY' | 'LOCATION'
|
||||||
|
|
||||||
|
export type RewardType = 'POINTS' | 'TOKENS' | 'REWARD'
|
||||||
|
|
||||||
|
export interface Campaign {
|
||||||
|
id: string // UUID
|
||||||
|
name: string
|
||||||
|
description?: string
|
||||||
|
type: CampaignType
|
||||||
|
start_date: string // ISO string
|
||||||
|
end_date: string // ISO string
|
||||||
|
is_active: boolean
|
||||||
|
show_on_app: boolean
|
||||||
|
position: number
|
||||||
|
metadata?: Record<string, any>
|
||||||
|
rules?: CampaignRule[]
|
||||||
|
created_at: string // ISO string
|
||||||
|
updated_at: string // ISO string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CampaignRule {
|
||||||
|
id: string // UUID
|
||||||
|
campaign_id: string // UUID
|
||||||
|
rule_type: RuleType
|
||||||
|
condition_value?: string
|
||||||
|
reward_type: RewardType
|
||||||
|
reward_value?: number
|
||||||
|
reward_subtype?: string
|
||||||
|
reward_ref_id?: string // UUID
|
||||||
|
metadata?: Record<string, any>
|
||||||
|
created_at: string // ISO string
|
||||||
|
updated_at: string // ISO string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CampaignRequest {
|
||||||
|
name: string
|
||||||
|
description?: string
|
||||||
|
type: CampaignType
|
||||||
|
start_date: string // ISO string
|
||||||
|
end_date: string // ISO string
|
||||||
|
is_active: boolean
|
||||||
|
show_on_app: boolean
|
||||||
|
position: number
|
||||||
|
metadata?: Record<string, any>
|
||||||
|
rules: CampaignRuleRequest[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CampaignRuleRequest {
|
||||||
|
rule_type: RuleType
|
||||||
|
condition_value?: string
|
||||||
|
reward_type: RewardType
|
||||||
|
reward_value?: number
|
||||||
|
reward_subtype?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Campaigns {
|
||||||
|
campaigns: Campaign[]
|
||||||
|
total: number
|
||||||
|
page: number
|
||||||
|
limit: number
|
||||||
|
}
|
||||||
@ -1,29 +1,40 @@
|
|||||||
export interface Customer {
|
export interface Customer {
|
||||||
id: string;
|
id: string
|
||||||
organization_id: string;
|
organization_id: string
|
||||||
name: string;
|
name: string
|
||||||
email?: string;
|
email?: string
|
||||||
phone?: string;
|
phone?: string
|
||||||
address?: string;
|
address?: string
|
||||||
is_default: boolean;
|
is_default: boolean
|
||||||
is_active: boolean;
|
is_active: boolean
|
||||||
metadata: Record<string, any>;
|
metadata: Record<string, any>
|
||||||
created_at: string;
|
created_at: string
|
||||||
updated_at: string;
|
updated_at: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Customers {
|
export interface Customers {
|
||||||
data: Customer[];
|
data: Customer[]
|
||||||
total_count: number;
|
total_count: number
|
||||||
page: number;
|
page: number
|
||||||
limit: number;
|
limit: number
|
||||||
total_pages: number;
|
total_pages: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CustomerRequest {
|
export interface CustomerRequest {
|
||||||
name: string;
|
name: string
|
||||||
email?: string;
|
email?: string
|
||||||
phone?: string;
|
phone?: string
|
||||||
address?: string;
|
address?: string
|
||||||
is_active?: boolean;
|
is_active?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CustomerAnalytics {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
email?: string
|
||||||
|
phone?: string
|
||||||
|
totalPoints: number
|
||||||
|
totalSpent?: number
|
||||||
|
loyaltyTier?: string // Bronze, Silver, Gold, dst
|
||||||
|
lastTransactionDate?: Date
|
||||||
}
|
}
|
||||||
|
|||||||
26
src/types/services/game.ts
Normal file
26
src/types/services/game.ts
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
export interface Game {
|
||||||
|
id: string // uuid
|
||||||
|
name: string
|
||||||
|
type: string
|
||||||
|
is_active: boolean
|
||||||
|
metadata: Record<string, any>
|
||||||
|
created_at: string // ISO datetime
|
||||||
|
updated_at: string // ISO datetime
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Games {
|
||||||
|
data: Game[]
|
||||||
|
total_count: number
|
||||||
|
page: number
|
||||||
|
limit: number
|
||||||
|
total_pages: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GameRequest {
|
||||||
|
name: string
|
||||||
|
type: string
|
||||||
|
is_active: boolean
|
||||||
|
metadata: {
|
||||||
|
imageUrl?: string
|
||||||
|
}
|
||||||
|
}
|
||||||
45
src/types/services/gamePrize.ts
Normal file
45
src/types/services/gamePrize.ts
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
import { Game } from './game'
|
||||||
|
|
||||||
|
export interface GamePrize {
|
||||||
|
id: string // uuid
|
||||||
|
game_id: string // uuid
|
||||||
|
name: string
|
||||||
|
weight: number
|
||||||
|
stock: number
|
||||||
|
max_stock?: number
|
||||||
|
threshold?: number // int64 → number
|
||||||
|
fallback_prize_id?: string // uuid
|
||||||
|
metadata: Record<string, any>
|
||||||
|
game?: Game // relasi ke GameResponse
|
||||||
|
fallback_prize?: GamePrize // self reference
|
||||||
|
created_at: string // ISO datetime
|
||||||
|
updated_at: string // ISO datetime
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GamePrizes {
|
||||||
|
data: GamePrize[]
|
||||||
|
total_count: number
|
||||||
|
page: number
|
||||||
|
limit: number
|
||||||
|
total_pages: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GamePrizeRequest {
|
||||||
|
game_id: string // uuid
|
||||||
|
name: string
|
||||||
|
weight: number // min 1
|
||||||
|
stock: number // min 0
|
||||||
|
max_stock?: number // optional
|
||||||
|
threshold?: number // optional (int64 → number in TS)
|
||||||
|
fallback_prize_id?: string // optional uuid
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GamePrizeRequest {
|
||||||
|
game_id: string // uuid
|
||||||
|
name: string
|
||||||
|
weight: number // min 1
|
||||||
|
stock: number // min 0
|
||||||
|
max_stock?: number // optional
|
||||||
|
threshold?: number // optional (int64 → number in TS)
|
||||||
|
fallback_prize_id?: string // optional uuid
|
||||||
|
}
|
||||||
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
|
||||||
|
}
|
||||||
39
src/types/services/reward.ts
Normal file
39
src/types/services/reward.ts
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
export interface Reward {
|
||||||
|
id: string // uuid
|
||||||
|
name: string
|
||||||
|
reward_type: 'VOUCHER' | 'PHYSICAL' | 'DIGITAL'
|
||||||
|
cost_points: number
|
||||||
|
stock?: number
|
||||||
|
max_per_customer: number
|
||||||
|
tnc?: TermsAndConditions
|
||||||
|
metadata?: Record<string, any>
|
||||||
|
images?: string[]
|
||||||
|
created_at: string // ISO date-time
|
||||||
|
updated_at: string // ISO date-time
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Rewards {
|
||||||
|
rewards: Reward[]
|
||||||
|
total: number
|
||||||
|
page: number
|
||||||
|
limit: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TermsAndConditions {
|
||||||
|
sections: TncSection[]
|
||||||
|
expiry_days: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TncSection {
|
||||||
|
title: string
|
||||||
|
rules: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RewardRequest {
|
||||||
|
name: string // required, 1–150 chars
|
||||||
|
reward_type: 'VOUCHER' | 'PHYSICAL' | 'DIGITAL' // enum
|
||||||
|
cost_points: number // min 1
|
||||||
|
stock?: number
|
||||||
|
max_per_customer: number // min 1
|
||||||
|
tnc?: TermsAndConditions
|
||||||
|
}
|
||||||
22
src/types/services/tier.ts
Normal file
22
src/types/services/tier.ts
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
export interface Tier {
|
||||||
|
id: string // uuid
|
||||||
|
name: string
|
||||||
|
min_points: number
|
||||||
|
benefits: Record<string, any>
|
||||||
|
created_at: string // ISO datetime
|
||||||
|
updated_at: string // ISO datetime
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Tiers {
|
||||||
|
data: Tier[]
|
||||||
|
total_count: number
|
||||||
|
page: number
|
||||||
|
limit: number
|
||||||
|
total_pages: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TierRequest {
|
||||||
|
name: string
|
||||||
|
min_points: number
|
||||||
|
benefits: Record<string, any>
|
||||||
|
}
|
||||||
@ -20,4 +20,16 @@ export interface VoucherApiResponse {
|
|||||||
success: boolean
|
success: boolean
|
||||||
data: VoucherRowsResponse
|
data: VoucherRowsResponse
|
||||||
errors: any
|
errors: any
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface VoucherType {
|
||||||
|
id: number
|
||||||
|
code: string
|
||||||
|
type: 'discount' | 'cashback' | 'free_shipping' | 'product'
|
||||||
|
discountType?: 'fixed' | 'percent'
|
||||||
|
discountValue?: number
|
||||||
|
minPurchase?: number
|
||||||
|
validFrom: string
|
||||||
|
validUntil: string
|
||||||
|
isActive: boolean
|
||||||
|
}
|
||||||
|
|||||||
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
|
||||||
|
}
|
||||||
792
src/views/apps/marketing/campaign/AddEditCampaignDrawer.tsx
Normal file
792
src/views/apps/marketing/campaign/AddEditCampaignDrawer.tsx
Normal file
@ -0,0 +1,792 @@
|
|||||||
|
// 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
|
||||||
|
import { Campaign } from '@/types/services/campaign'
|
||||||
|
import { useCampaignsMutation } from '@/services/mutations/campaign'
|
||||||
|
|
||||||
|
// Updated Type Definitions
|
||||||
|
export type CampaignType = 'REWARD' | 'POINTS' | 'TOKENS' | 'MIXED'
|
||||||
|
export type RuleType = 'TIER' | 'SPEND' | 'PRODUCT' | 'CATEGORY' | 'DAY' | 'LOCATION'
|
||||||
|
export type RewardType = 'POINTS' | 'TOKENS' | 'REWARD'
|
||||||
|
|
||||||
|
export interface CampaignRequest {
|
||||||
|
name: string
|
||||||
|
description?: string
|
||||||
|
type: CampaignType
|
||||||
|
start_date: string // ISO string
|
||||||
|
end_date: string // ISO string
|
||||||
|
is_active: boolean
|
||||||
|
show_on_app: boolean
|
||||||
|
position: number
|
||||||
|
metadata?: Record<string, any>
|
||||||
|
rules: CampaignRuleRequest[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CampaignRuleRequest {
|
||||||
|
rule_type: RuleType
|
||||||
|
condition_value?: string
|
||||||
|
reward_type: RewardType
|
||||||
|
reward_value?: number
|
||||||
|
reward_subtype?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
open: boolean
|
||||||
|
handleClose: () => void
|
||||||
|
data?: Campaign // Data campaign untuk edit (jika ada)
|
||||||
|
}
|
||||||
|
|
||||||
|
type FormValidateType = {
|
||||||
|
name: string
|
||||||
|
description: string
|
||||||
|
type: CampaignType
|
||||||
|
start_date: string
|
||||||
|
end_date: string
|
||||||
|
is_active: boolean
|
||||||
|
show_on_app: boolean
|
||||||
|
position: number
|
||||||
|
// Rules array
|
||||||
|
rules: {
|
||||||
|
rule_type: RuleType
|
||||||
|
condition_value: string
|
||||||
|
reward_type: RewardType
|
||||||
|
reward_value: number
|
||||||
|
reward_subtype: string
|
||||||
|
}[]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initial form data
|
||||||
|
const initialData: FormValidateType = {
|
||||||
|
name: '',
|
||||||
|
description: '',
|
||||||
|
type: 'POINTS',
|
||||||
|
start_date: '',
|
||||||
|
end_date: '',
|
||||||
|
is_active: true,
|
||||||
|
show_on_app: true,
|
||||||
|
position: 1,
|
||||||
|
// Initial rule
|
||||||
|
rules: [
|
||||||
|
{
|
||||||
|
rule_type: 'SPEND',
|
||||||
|
condition_value: '',
|
||||||
|
reward_type: 'POINTS',
|
||||||
|
reward_value: 0,
|
||||||
|
reward_subtype: ''
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
const AddEditCampaignDrawer = (props: Props) => {
|
||||||
|
// Props
|
||||||
|
const { open, handleClose, data } = props
|
||||||
|
|
||||||
|
// States
|
||||||
|
const [showMore, setShowMore] = useState(false)
|
||||||
|
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||||
|
|
||||||
|
const { createCampaign, updateCampaign } = useCampaignsMutation()
|
||||||
|
|
||||||
|
// 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
|
||||||
|
})
|
||||||
|
|
||||||
|
// Field array for rules
|
||||||
|
const { fields, append, remove } = useFieldArray({
|
||||||
|
control,
|
||||||
|
name: 'rules'
|
||||||
|
})
|
||||||
|
|
||||||
|
const watchedStartDate = watch('start_date')
|
||||||
|
const watchedEndDate = watch('end_date')
|
||||||
|
|
||||||
|
// Effect to populate form when editing
|
||||||
|
useEffect(() => {
|
||||||
|
if (isEditMode && data) {
|
||||||
|
const formData: FormValidateType = {
|
||||||
|
name: data.name || '',
|
||||||
|
description: data.description || '',
|
||||||
|
type: data.type || 'POINTS',
|
||||||
|
start_date: data.start_date ? new Date(data.start_date).toISOString().split('T')[0] : '',
|
||||||
|
end_date: data.end_date ? new Date(data.end_date).toISOString().split('T')[0] : '',
|
||||||
|
is_active: data.is_active ?? true,
|
||||||
|
show_on_app: data.show_on_app ?? true,
|
||||||
|
position: data.position || 1,
|
||||||
|
// Map existing rules
|
||||||
|
rules: data.rules?.map(rule => ({
|
||||||
|
rule_type: rule.rule_type,
|
||||||
|
condition_value: rule.condition_value || '',
|
||||||
|
reward_type: rule.reward_type,
|
||||||
|
reward_value: rule.reward_value || 0,
|
||||||
|
reward_subtype: rule.reward_subtype || ''
|
||||||
|
})) || [
|
||||||
|
{
|
||||||
|
rule_type: 'SPEND',
|
||||||
|
condition_value: '',
|
||||||
|
reward_type: 'POINTS',
|
||||||
|
reward_value: 0,
|
||||||
|
reward_subtype: ''
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
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 handleFormSubmit = async (formData: FormValidateType) => {
|
||||||
|
try {
|
||||||
|
setIsSubmitting(true)
|
||||||
|
|
||||||
|
// Create rules array
|
||||||
|
const rulesRequest: CampaignRuleRequest[] = formData.rules.map(rule => ({
|
||||||
|
rule_type: rule.rule_type,
|
||||||
|
condition_value: rule.condition_value || undefined,
|
||||||
|
reward_type: rule.reward_type,
|
||||||
|
reward_value: rule.reward_value || undefined,
|
||||||
|
reward_subtype: rule.reward_subtype || undefined
|
||||||
|
}))
|
||||||
|
|
||||||
|
// Create metadata from rules if needed
|
||||||
|
const metadata: Record<string, any> = {}
|
||||||
|
const spendRule = formData.rules.find(rule => rule.rule_type === 'SPEND')
|
||||||
|
if (spendRule?.condition_value) {
|
||||||
|
metadata.minPurchase = parseInt(spendRule.condition_value)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create CampaignRequest object
|
||||||
|
const campaignRequest: CampaignRequest = {
|
||||||
|
name: formData.name,
|
||||||
|
description: formData.description || undefined,
|
||||||
|
type: formData.type,
|
||||||
|
start_date: new Date(formData.start_date).toISOString(),
|
||||||
|
end_date: new Date(formData.end_date).toISOString(),
|
||||||
|
is_active: formData.is_active,
|
||||||
|
show_on_app: formData.show_on_app,
|
||||||
|
position: formData.position,
|
||||||
|
metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
|
||||||
|
rules: rulesRequest
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isEditMode && data?.id) {
|
||||||
|
// Update existing campaign
|
||||||
|
updateCampaign.mutate(
|
||||||
|
{ id: data.id, payload: campaignRequest },
|
||||||
|
{
|
||||||
|
onSuccess: () => {
|
||||||
|
handleReset()
|
||||||
|
handleClose()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
// Create new campaign
|
||||||
|
createCampaign.mutate(campaignRequest, {
|
||||||
|
onSuccess: () => {
|
||||||
|
handleReset()
|
||||||
|
handleClose()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error submitting campaign:', 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)
|
||||||
|
}
|
||||||
|
|
||||||
|
const getRewardTypeLabel = (type: RewardType) => {
|
||||||
|
switch (type) {
|
||||||
|
case 'POINTS':
|
||||||
|
return 'Poin'
|
||||||
|
case 'TOKENS':
|
||||||
|
return 'Token'
|
||||||
|
case 'REWARD':
|
||||||
|
return 'Reward'
|
||||||
|
default:
|
||||||
|
return type
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const getRewardValuePlaceholder = (type: RewardType) => {
|
||||||
|
switch (type) {
|
||||||
|
case 'POINTS':
|
||||||
|
return 'Jumlah poin yang diberikan'
|
||||||
|
case 'TOKENS':
|
||||||
|
return 'Jumlah token yang diberikan'
|
||||||
|
case 'REWARD':
|
||||||
|
return 'Nilai reward'
|
||||||
|
default:
|
||||||
|
return 'Nilai reward'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const getConditionValuePlaceholder = (ruleType: RuleType) => {
|
||||||
|
switch (ruleType) {
|
||||||
|
case 'SPEND':
|
||||||
|
return 'Minimum pembelian (Rupiah)'
|
||||||
|
case 'TIER':
|
||||||
|
return 'Tier pelanggan (misal: GOLD, SILVER)'
|
||||||
|
case 'PRODUCT':
|
||||||
|
return 'ID atau nama produk'
|
||||||
|
case 'CATEGORY':
|
||||||
|
return 'Kategori produk'
|
||||||
|
case 'DAY':
|
||||||
|
return 'Hari dalam seminggu (misal: MONDAY)'
|
||||||
|
case 'LOCATION':
|
||||||
|
return 'Lokasi atau kota'
|
||||||
|
default:
|
||||||
|
return 'Nilai kondisi'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const getConditionValueInputProps = (ruleType: RuleType) => {
|
||||||
|
if (ruleType === 'SPEND') {
|
||||||
|
return {
|
||||||
|
startAdornment: <InputAdornment position='start'>Rp</InputAdornment>,
|
||||||
|
type: 'number' as const
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { type: 'text' as const }
|
||||||
|
}
|
||||||
|
|
||||||
|
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 Kampanye' : 'Tambah Kampanye 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='campaign-form' onSubmit={handleSubmit(handleFormSubmit)}>
|
||||||
|
<div className='flex flex-col gap-6 p-6'>
|
||||||
|
{/* Nama Kampanye */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Nama Kampanye <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='name'
|
||||||
|
control={control}
|
||||||
|
rules={{ required: 'Nama kampanye wajib diisi' }}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
placeholder='Masukkan nama kampanye'
|
||||||
|
error={!!errors.name}
|
||||||
|
helperText={errors.name?.message}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Jenis Kampanye */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Jenis Kampanye <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='type'
|
||||||
|
control={control}
|
||||||
|
rules={{ required: 'Jenis kampanye wajib dipilih' }}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField {...field} select fullWidth error={!!errors.type} helperText={errors.type?.message}>
|
||||||
|
<MenuItem value='POINTS'>
|
||||||
|
<div className='flex items-center gap-2'>
|
||||||
|
<i className='tabler-coins text-primary' />
|
||||||
|
Points
|
||||||
|
</div>
|
||||||
|
</MenuItem>
|
||||||
|
<MenuItem value='TOKENS'>
|
||||||
|
<div className='flex items-center gap-2'>
|
||||||
|
<i className='tabler-ticket text-success' />
|
||||||
|
Tokens
|
||||||
|
</div>
|
||||||
|
</MenuItem>
|
||||||
|
<MenuItem value='REWARD'>
|
||||||
|
<div className='flex items-center gap-2'>
|
||||||
|
<i className='tabler-gift text-warning' />
|
||||||
|
Reward
|
||||||
|
</div>
|
||||||
|
</MenuItem>
|
||||||
|
<MenuItem value='MIXED'>
|
||||||
|
<div className='flex items-center gap-2'>
|
||||||
|
<i className='tabler-layers-intersect text-info' />
|
||||||
|
Mixed
|
||||||
|
</div>
|
||||||
|
</MenuItem>
|
||||||
|
</CustomTextField>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Rules Section */}
|
||||||
|
<div>
|
||||||
|
<Box display='flex' alignItems='center' justifyContent='space-between' className='mb-4'>
|
||||||
|
<Typography variant='h6'>Aturan Kampanye</Typography>
|
||||||
|
<Button
|
||||||
|
variant='outlined'
|
||||||
|
size='small'
|
||||||
|
startIcon={<i className='tabler-plus' />}
|
||||||
|
onClick={() =>
|
||||||
|
append({
|
||||||
|
rule_type: 'SPEND',
|
||||||
|
condition_value: '',
|
||||||
|
reward_type: 'POINTS',
|
||||||
|
reward_value: 0,
|
||||||
|
reward_subtype: ''
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Tambah Aturan
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{fields.map((field, index) => (
|
||||||
|
<Box key={field.id} className='mb-6 p-4 border border-gray-200 rounded-lg'>
|
||||||
|
<Box display='flex' alignItems='center' justifyContent='between' className='mb-3'>
|
||||||
|
<Typography variant='subtitle2' className='font-medium'>
|
||||||
|
Aturan {index + 1}
|
||||||
|
</Typography>
|
||||||
|
{fields.length > 1 && (
|
||||||
|
<IconButton size='small' color='error' onClick={() => remove(index)}>
|
||||||
|
<i className='tabler-trash text-lg' />
|
||||||
|
</IconButton>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<div className='flex flex-col gap-4'>
|
||||||
|
{/* Rule Type */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Tipe Aturan <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name={`rules.${index}.rule_type`}
|
||||||
|
control={control}
|
||||||
|
rules={{ required: 'Tipe aturan wajib dipilih' }}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
select
|
||||||
|
fullWidth
|
||||||
|
size='small'
|
||||||
|
error={!!errors.rules?.[index]?.rule_type}
|
||||||
|
helperText={errors.rules?.[index]?.rule_type?.message}
|
||||||
|
>
|
||||||
|
<MenuItem value='SPEND'>Minimum Pembelian</MenuItem>
|
||||||
|
<MenuItem value='TIER'>Tier Pelanggan</MenuItem>
|
||||||
|
<MenuItem value='PRODUCT'>Produk Tertentu</MenuItem>
|
||||||
|
<MenuItem value='CATEGORY'>Kategori Produk</MenuItem>
|
||||||
|
<MenuItem value='DAY'>Hari Tertentu</MenuItem>
|
||||||
|
<MenuItem value='LOCATION'>Lokasi Tertentu</MenuItem>
|
||||||
|
</CustomTextField>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Condition Value */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Nilai Kondisi <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name={`rules.${index}.condition_value`}
|
||||||
|
control={control}
|
||||||
|
rules={{ required: 'Nilai kondisi wajib diisi' }}
|
||||||
|
render={({ field }) => {
|
||||||
|
const ruleType = watch(`rules.${index}.rule_type`)
|
||||||
|
return (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
size='small'
|
||||||
|
placeholder={getConditionValuePlaceholder(ruleType)}
|
||||||
|
error={!!errors.rules?.[index]?.condition_value}
|
||||||
|
helperText={errors.rules?.[index]?.condition_value?.message}
|
||||||
|
InputProps={getConditionValueInputProps(ruleType)}
|
||||||
|
type={getConditionValueInputProps(ruleType).type}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Reward Type */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Jenis Reward <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name={`rules.${index}.reward_type`}
|
||||||
|
control={control}
|
||||||
|
rules={{ required: 'Jenis reward wajib dipilih' }}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
select
|
||||||
|
fullWidth
|
||||||
|
size='small'
|
||||||
|
error={!!errors.rules?.[index]?.reward_type}
|
||||||
|
helperText={errors.rules?.[index]?.reward_type?.message}
|
||||||
|
>
|
||||||
|
<MenuItem value='POINTS'>
|
||||||
|
<div className='flex items-center gap-2'>
|
||||||
|
<i className='tabler-coins text-primary' />
|
||||||
|
Points
|
||||||
|
</div>
|
||||||
|
</MenuItem>
|
||||||
|
<MenuItem value='TOKENS'>
|
||||||
|
<div className='flex items-center gap-2'>
|
||||||
|
<i className='tabler-ticket text-success' />
|
||||||
|
Tokens
|
||||||
|
</div>
|
||||||
|
</MenuItem>
|
||||||
|
<MenuItem value='REWARD'>
|
||||||
|
<div className='flex items-center gap-2'>
|
||||||
|
<i className='tabler-percentage text-warning' />
|
||||||
|
Reward
|
||||||
|
</div>
|
||||||
|
</MenuItem>
|
||||||
|
</CustomTextField>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Reward Value */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Nilai Reward <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name={`rules.${index}.reward_value`}
|
||||||
|
control={control}
|
||||||
|
rules={{
|
||||||
|
required: 'Nilai reward wajib diisi',
|
||||||
|
min: { value: 1, message: 'Nilai reward minimal 1' }
|
||||||
|
}}
|
||||||
|
render={({ field }) => {
|
||||||
|
const rewardType = watch(`rules.${index}.reward_type`)
|
||||||
|
return (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
size='small'
|
||||||
|
type='number'
|
||||||
|
placeholder={getRewardValuePlaceholder(rewardType)}
|
||||||
|
error={!!errors.rules?.[index]?.reward_value}
|
||||||
|
helperText={errors.rules?.[index]?.reward_value?.message}
|
||||||
|
InputProps={{
|
||||||
|
endAdornment:
|
||||||
|
rewardType === 'POINTS' ? (
|
||||||
|
<InputAdornment position='end'>Poin</InputAdornment>
|
||||||
|
) : rewardType === 'TOKENS' ? (
|
||||||
|
<InputAdornment position='end'>Token</InputAdornment>
|
||||||
|
) : undefined
|
||||||
|
}}
|
||||||
|
onChange={e => field.onChange(Number(e.target.value))}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Reward Subtype (jika reward type adalah REWARD) */}
|
||||||
|
{watch(`rules.${index}.reward_type`) === 'REWARD' && (
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Sub-tipe Reward
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name={`rules.${index}.reward_subtype`}
|
||||||
|
control={control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField {...field} select fullWidth size='small'>
|
||||||
|
<MenuItem value='DISCOUNT_PERCENT'>Diskon Persentase</MenuItem>
|
||||||
|
<MenuItem value='DISCOUNT_AMOUNT'>Diskon Nominal</MenuItem>
|
||||||
|
<MenuItem value='CASHBACK'>Cashback</MenuItem>
|
||||||
|
<MenuItem value='FREE_SHIPPING'>Gratis Ongkir</MenuItem>
|
||||||
|
</CustomTextField>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Box>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tanggal Mulai */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Tanggal Mulai <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='start_date'
|
||||||
|
control={control}
|
||||||
|
rules={{ required: 'Tanggal mulai wajib diisi' }}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
type='date'
|
||||||
|
error={!!errors.start_date}
|
||||||
|
helperText={errors.start_date?.message}
|
||||||
|
InputLabelProps={{
|
||||||
|
shrink: true
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tanggal Berakhir */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Tanggal Berakhir <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='end_date'
|
||||||
|
control={control}
|
||||||
|
rules={{
|
||||||
|
required: 'Tanggal berakhir wajib diisi',
|
||||||
|
validate: value => {
|
||||||
|
if (watchedStartDate && value) {
|
||||||
|
return (
|
||||||
|
new Date(value) >= new Date(watchedStartDate) || 'Tanggal berakhir harus setelah tanggal mulai'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
type='date'
|
||||||
|
error={!!errors.end_date}
|
||||||
|
helperText={errors.end_date?.message}
|
||||||
|
InputLabelProps={{
|
||||||
|
shrink: true
|
||||||
|
}}
|
||||||
|
inputProps={{
|
||||||
|
min: watchedStartDate || undefined
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Status Aktif */}
|
||||||
|
<div>
|
||||||
|
<Controller
|
||||||
|
name='is_active'
|
||||||
|
control={control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormControlLabel
|
||||||
|
control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
|
||||||
|
label='Kampanye Aktif'
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Show on App */}
|
||||||
|
<div>
|
||||||
|
<Controller
|
||||||
|
name='show_on_app'
|
||||||
|
control={control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormControlLabel
|
||||||
|
control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
|
||||||
|
label='Tampilkan di Aplikasi'
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</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 Kampanye
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='description'
|
||||||
|
control={control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
placeholder='Deskripsi detail tentang kampanye'
|
||||||
|
multiline
|
||||||
|
rows={4}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Position */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Posisi Kampanye
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='position'
|
||||||
|
control={control}
|
||||||
|
rules={{
|
||||||
|
min: { value: 1, message: 'Posisi minimal 1' }
|
||||||
|
}}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
type='number'
|
||||||
|
placeholder='Urutan tampilan kampanye'
|
||||||
|
error={!!errors.position}
|
||||||
|
helperText={errors.position?.message || 'Semakin kecil angka, semakin atas posisinya'}
|
||||||
|
onChange={e => field.onChange(Number(e.target.value))}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</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='campaign-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 AddEditCampaignDrawer
|
||||||
635
src/views/apps/marketing/campaign/CampaignListTable.tsx
Normal file
635
src/views/apps/marketing/campaign/CampaignListTable.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 AddEditCampaignDrawer from './AddEditCampaignDrawer'
|
||||||
|
import DeleteCampaignDialog from './DeleteCampaignDialog'
|
||||||
|
import { Campaign } from '@/types/services/campaign'
|
||||||
|
import { useCampaigns } from '@/services/queries/campaign'
|
||||||
|
import { useCampaignsMutation } from '@/services/mutations/campaign'
|
||||||
|
|
||||||
|
declare module '@tanstack/table-core' {
|
||||||
|
interface FilterFns {
|
||||||
|
fuzzy: FilterFn<unknown>
|
||||||
|
}
|
||||||
|
interface FilterMeta {
|
||||||
|
itemRank: RankingInfo
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type CampaignWithAction = Campaign & {
|
||||||
|
action?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Styled Components
|
||||||
|
const Icon = styled('i')({})
|
||||||
|
|
||||||
|
const fuzzyFilter: FilterFn<any> = (row, columnId, value, addMeta) => {
|
||||||
|
// Rank the item
|
||||||
|
const itemRank = rankItem(row.getValue(columnId), value)
|
||||||
|
|
||||||
|
// Store the itemRank info
|
||||||
|
addMeta({
|
||||||
|
itemRank
|
||||||
|
})
|
||||||
|
|
||||||
|
// Return if the item should be filtered in/out
|
||||||
|
return itemRank.passed
|
||||||
|
}
|
||||||
|
|
||||||
|
const DebouncedInput = ({
|
||||||
|
value: initialValue,
|
||||||
|
onChange,
|
||||||
|
debounce = 500,
|
||||||
|
...props
|
||||||
|
}: {
|
||||||
|
value: string | number
|
||||||
|
onChange: (value: string | number) => void
|
||||||
|
debounce?: number
|
||||||
|
} & Omit<TextFieldProps, 'onChange'>) => {
|
||||||
|
// States
|
||||||
|
const [value, setValue] = useState(initialValue)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setValue(initialValue)
|
||||||
|
}, [initialValue])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const timeout = setTimeout(() => {
|
||||||
|
onChange(value)
|
||||||
|
}, debounce)
|
||||||
|
|
||||||
|
return () => clearTimeout(timeout)
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [value])
|
||||||
|
|
||||||
|
return <CustomTextField {...props} value={value} onChange={e => setValue(e.target.value)} />
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper function untuk format points - SAMA SEPERTI REWARD TABLE
|
||||||
|
const formatPoints = (points: number) => {
|
||||||
|
return new Intl.NumberFormat('id-ID').format(points)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper functions untuk campaign utilities
|
||||||
|
const getCampaignTypeColor = (type: string): ThemeColor => {
|
||||||
|
switch (type) {
|
||||||
|
case 'POINTS':
|
||||||
|
return 'primary'
|
||||||
|
case 'TOKENS':
|
||||||
|
return 'success'
|
||||||
|
case 'REWARD':
|
||||||
|
return 'warning'
|
||||||
|
case 'MIXED':
|
||||||
|
return 'info'
|
||||||
|
default:
|
||||||
|
return 'secondary'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const getCampaignTypeIcon = (type: string): string => {
|
||||||
|
switch (type) {
|
||||||
|
case 'POINTS':
|
||||||
|
return 'tabler-coins'
|
||||||
|
case 'TOKENS':
|
||||||
|
return 'tabler-ticket'
|
||||||
|
case 'REWARD':
|
||||||
|
return 'tabler-gift'
|
||||||
|
case 'MIXED':
|
||||||
|
return 'tabler-layers-intersect'
|
||||||
|
default:
|
||||||
|
return 'tabler-tag'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const getRewardTypeColor = (rewardType: string): ThemeColor => {
|
||||||
|
switch (rewardType) {
|
||||||
|
case 'POINTS':
|
||||||
|
return 'primary'
|
||||||
|
case 'TOKENS':
|
||||||
|
return 'success'
|
||||||
|
case 'REWARD':
|
||||||
|
return 'warning'
|
||||||
|
default:
|
||||||
|
return 'info'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const getRewardTypeIcon = (rewardType: string): string => {
|
||||||
|
switch (rewardType) {
|
||||||
|
case 'POINTS':
|
||||||
|
return 'tabler-coins'
|
||||||
|
case 'TOKENS':
|
||||||
|
return 'tabler-ticket'
|
||||||
|
case 'REWARD':
|
||||||
|
return 'tabler-percentage'
|
||||||
|
default:
|
||||||
|
return 'tabler-gift'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatRewardValue = (rewardType: string, rewardValue?: number, rewardSubtype?: string): string => {
|
||||||
|
if (!rewardValue) return '-'
|
||||||
|
|
||||||
|
switch (rewardType) {
|
||||||
|
case 'POINTS':
|
||||||
|
return `${formatPoints(rewardValue)} Poin`
|
||||||
|
case 'TOKENS':
|
||||||
|
return formatCurrency(rewardValue)
|
||||||
|
case 'REWARD':
|
||||||
|
if (rewardSubtype === 'DISCOUNT_PERCENT') {
|
||||||
|
return `${rewardValue}%`
|
||||||
|
}
|
||||||
|
return formatCurrency(rewardValue)
|
||||||
|
default:
|
||||||
|
return rewardValue.toString()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const getMinimumPurchase = (campaign: Campaign): number => {
|
||||||
|
// Check rules for spend condition
|
||||||
|
const spendRule = campaign.rules?.find(rule => rule.rule_type === 'SPEND')
|
||||||
|
if (spendRule?.condition_value) {
|
||||||
|
return parseInt(spendRule.condition_value)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback to metadata
|
||||||
|
return campaign.metadata?.minPurchase || 0
|
||||||
|
}
|
||||||
|
|
||||||
|
const getPrimaryReward = (campaign: Campaign): { type: string; value?: number; subtype?: string } => {
|
||||||
|
const primaryRule = campaign.rules?.[0]
|
||||||
|
return {
|
||||||
|
type: primaryRule?.reward_type || 'POINTS',
|
||||||
|
value: primaryRule?.reward_value,
|
||||||
|
subtype: primaryRule?.reward_subtype
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Column Definitions
|
||||||
|
const columnHelper = createColumnHelper<CampaignWithAction>()
|
||||||
|
|
||||||
|
const CampaignListTable = () => {
|
||||||
|
// States - PERSIS SAMA SEPERTI REWARD TABLE
|
||||||
|
const [addCampaignOpen, setAddCampaignOpen] = useState(false)
|
||||||
|
const [editCampaignData, setEditCampaignData] = useState<Campaign | undefined>(undefined)
|
||||||
|
const [rowSelection, setRowSelection] = useState({})
|
||||||
|
const [globalFilter, setGlobalFilter] = useState('')
|
||||||
|
const [deleteCampaignOpen, setDeleteCampaignOpen] = useState(false)
|
||||||
|
const [campaignToDelete, setCampaignToDelete] = useState<Campaign | null>(null)
|
||||||
|
|
||||||
|
// FIX 1: PAGINATION SAMA SEPERTI REWARD (1-based, bukan 0-based)
|
||||||
|
const [currentPage, setCurrentPage] = useState(1)
|
||||||
|
const [pageSize, setPageSize] = useState(10)
|
||||||
|
const [search, setSearch] = useState('')
|
||||||
|
|
||||||
|
const { deleteCampaign } = useCampaignsMutation()
|
||||||
|
|
||||||
|
const { data, isLoading, error, isFetching } = useCampaigns({
|
||||||
|
page: currentPage, // SAMA SEPERTI REWARD - langsung currentPage
|
||||||
|
limit: pageSize,
|
||||||
|
search
|
||||||
|
})
|
||||||
|
|
||||||
|
const campaigns = data?.campaigns ?? []
|
||||||
|
const totalCount = data?.total ?? 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 handleEditCampaign = (campaign: Campaign) => {
|
||||||
|
setEditCampaignData(campaign)
|
||||||
|
setAddCampaignOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDeleteCampaign = (campaign: Campaign) => {
|
||||||
|
setCampaignToDelete(campaign)
|
||||||
|
setDeleteCampaignOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ADD NEW HANDLERS FOR DELETE DIALOG
|
||||||
|
const handleConfirmDelete = () => {
|
||||||
|
if (campaignToDelete) {
|
||||||
|
deleteCampaign.mutate(campaignToDelete.id, {
|
||||||
|
onSuccess: () => {
|
||||||
|
console.log('Campaign deleted successfully')
|
||||||
|
setDeleteCampaignOpen(false)
|
||||||
|
setCampaignToDelete(null)
|
||||||
|
// You might want to refetch data here
|
||||||
|
// refetch()
|
||||||
|
},
|
||||||
|
onError: error => {
|
||||||
|
console.error('Error deleting campaign:', error)
|
||||||
|
// Handle error (show toast, etc.)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCloseDeleteDialog = () => {
|
||||||
|
if (!deleteCampaign.isPending) {
|
||||||
|
setDeleteCampaignOpen(false)
|
||||||
|
setCampaignToDelete(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCloseCampaignDrawer = () => {
|
||||||
|
setAddCampaignOpen(false)
|
||||||
|
setEditCampaignData(undefined)
|
||||||
|
}
|
||||||
|
|
||||||
|
const columns = useMemo<ColumnDef<CampaignWithAction, 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 Kampanye',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<div className='flex items-center gap-4'>
|
||||||
|
<div className='flex flex-col'>
|
||||||
|
<Link href={getLocalizedUrl(`/apps/campaigns/${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='body2' color='text.secondary' className='max-w-xs truncate'>
|
||||||
|
{row.original.description}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('type', {
|
||||||
|
header: 'Jenis Kampanye',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<Chip
|
||||||
|
label={row.original.type}
|
||||||
|
color={getCampaignTypeColor(row.original.type)}
|
||||||
|
variant='tonal'
|
||||||
|
size='small'
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('metadata', {
|
||||||
|
header: 'Minimum Pembelian',
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const minPurchase = getMinimumPurchase(row.original)
|
||||||
|
return (
|
||||||
|
<div className='flex items-center gap-2'>
|
||||||
|
<Icon className='tabler-coin' sx={{ color: 'var(--mui-palette-primary-main)' }} />
|
||||||
|
<Typography color='text.primary'>{minPurchase > 0 ? formatCurrency(minPurchase) : '-'}</Typography>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('rules', {
|
||||||
|
header: 'Reward Utama',
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const reward = getPrimaryReward(row.original)
|
||||||
|
return (
|
||||||
|
<div className='flex items-center gap-2'>
|
||||||
|
<Icon
|
||||||
|
className={getRewardTypeIcon(reward.type)}
|
||||||
|
sx={{ color: `var(--mui-palette-${getRewardTypeColor(reward.type)}-main)` }}
|
||||||
|
/>
|
||||||
|
<Chip
|
||||||
|
label={formatRewardValue(reward.type, reward.value, reward.subtype)}
|
||||||
|
color={getRewardTypeColor(reward.type)}
|
||||||
|
variant='tonal'
|
||||||
|
size='small'
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('start_date', {
|
||||||
|
header: 'Periode Kampanye',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<div className='flex flex-col'>
|
||||||
|
<Typography variant='body2' color='text.primary'>
|
||||||
|
{new Date(row.original.start_date).toLocaleDateString('id-ID', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric'
|
||||||
|
})}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant='body2' color='text.secondary'>
|
||||||
|
s/d{' '}
|
||||||
|
{new Date(row.original.end_date).toLocaleDateString('id-ID', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric'
|
||||||
|
})}
|
||||||
|
</Typography>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('is_active', {
|
||||||
|
header: 'Status',
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const isActive = row.original.is_active
|
||||||
|
const showOnApp = row.original.show_on_app
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className='flex flex-col gap-1'>
|
||||||
|
<Chip
|
||||||
|
label={isActive ? 'Aktif' : 'Tidak Aktif'}
|
||||||
|
color={isActive ? 'success' : 'error'}
|
||||||
|
variant='tonal'
|
||||||
|
size='small'
|
||||||
|
/>
|
||||||
|
{showOnApp && <Chip label='Tampil di App' color='info' variant='outlined' size='small' />}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('position', {
|
||||||
|
header: 'Posisi',
|
||||||
|
cell: ({ row }) => <Typography color='text.primary'>#{row.original.position}</Typography>
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('created_at', {
|
||||||
|
header: 'Tanggal Dibuat',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<Typography color='text.primary'>
|
||||||
|
{/* FIX 3: FORMAT DATE YANG SAMA SEPERTI REWARD */}
|
||||||
|
{new Date(row.original.created_at).toLocaleDateString('id-ID', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric'
|
||||||
|
})}
|
||||||
|
</Typography>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
id: 'actions',
|
||||||
|
header: 'Aksi',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<div className='flex items-center'>
|
||||||
|
<OptionMenu
|
||||||
|
iconButtonProps={{ size: 'medium' }}
|
||||||
|
iconClassName='text-textSecondary text-[22px]'
|
||||||
|
options={[
|
||||||
|
{
|
||||||
|
text: 'Edit',
|
||||||
|
icon: 'tabler-edit text-[22px]',
|
||||||
|
menuItemProps: {
|
||||||
|
className: 'flex items-center gap-2 text-textSecondary',
|
||||||
|
onClick: () => handleEditCampaign(row.original)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
text: 'Hapus',
|
||||||
|
icon: 'tabler-trash text-[22px]',
|
||||||
|
menuItemProps: {
|
||||||
|
className: 'flex items-center gap-2 text-textSecondary',
|
||||||
|
onClick: () => handleDeleteCampaign(row.original)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
enableSorting: false
|
||||||
|
}
|
||||||
|
],
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
[locale, handleEditCampaign, handleDeleteCampaign]
|
||||||
|
)
|
||||||
|
|
||||||
|
// FIX 4: TABLE CONFIG YANG SAMA PERSIS SEPERTI REWARD
|
||||||
|
const table = useReactTable({
|
||||||
|
data: campaigns as Campaign[], // SAMA SEPERTI REWARD
|
||||||
|
columns,
|
||||||
|
filterFns: {
|
||||||
|
fuzzy: fuzzyFilter
|
||||||
|
},
|
||||||
|
state: {
|
||||||
|
rowSelection,
|
||||||
|
globalFilter,
|
||||||
|
pagination: {
|
||||||
|
pageIndex: currentPage, // SAMA SEPERTI REWARD - langsung currentPage
|
||||||
|
pageSize
|
||||||
|
}
|
||||||
|
},
|
||||||
|
enableRowSelection: true,
|
||||||
|
onRowSelectionChange: setRowSelection,
|
||||||
|
getCoreRowModel: getCoreRowModel(),
|
||||||
|
manualPagination: true, // SAMA SEPERTI REWARD
|
||||||
|
pageCount: Math.ceil(totalCount / pageSize) // SAMA SEPERTI REWARD
|
||||||
|
})
|
||||||
|
|
||||||
|
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 Kampanye'
|
||||||
|
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={() => setAddCampaignOpen(!addCampaignOpen)}
|
||||||
|
className='max-sm:is-full'
|
||||||
|
>
|
||||||
|
Tambah Kampanye
|
||||||
|
</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>
|
||||||
|
<AddEditCampaignDrawer open={addCampaignOpen} handleClose={handleCloseCampaignDrawer} data={editCampaignData} />
|
||||||
|
<DeleteCampaignDialog
|
||||||
|
open={deleteCampaignOpen}
|
||||||
|
onClose={handleCloseDeleteDialog}
|
||||||
|
onConfirm={handleConfirmDelete}
|
||||||
|
campaign={campaignToDelete}
|
||||||
|
isDeleting={deleteCampaign?.isPending || false}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default CampaignListTable
|
||||||
157
src/views/apps/marketing/campaign/DeleteCampaignDialog.tsx
Normal file
157
src/views/apps/marketing/campaign/DeleteCampaignDialog.tsx
Normal file
@ -0,0 +1,157 @@
|
|||||||
|
// React Imports
|
||||||
|
import { useState } from 'react'
|
||||||
|
|
||||||
|
// MUI Imports
|
||||||
|
import Dialog from '@mui/material/Dialog'
|
||||||
|
import DialogTitle from '@mui/material/DialogTitle'
|
||||||
|
import DialogContent from '@mui/material/DialogContent'
|
||||||
|
import DialogActions from '@mui/material/DialogActions'
|
||||||
|
import DialogContentText from '@mui/material/DialogContentText'
|
||||||
|
import Button from '@mui/material/Button'
|
||||||
|
import Typography from '@mui/material/Typography'
|
||||||
|
import Box from '@mui/material/Box'
|
||||||
|
import Alert from '@mui/material/Alert'
|
||||||
|
import Chip from '@mui/material/Chip'
|
||||||
|
|
||||||
|
// Types
|
||||||
|
import { Campaign } from '@/types/services/campaign'
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
open: boolean
|
||||||
|
onClose: () => void
|
||||||
|
onConfirm: () => void
|
||||||
|
campaign: Campaign | null
|
||||||
|
isDeleting?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
const DeleteCampaignDialog = ({ open, onClose, onConfirm, campaign, isDeleting = false }: Props) => {
|
||||||
|
if (!campaign) return null
|
||||||
|
|
||||||
|
const getCampaignTypeColor = (type: string) => {
|
||||||
|
switch (type) {
|
||||||
|
case 'POINTS':
|
||||||
|
return 'primary'
|
||||||
|
case 'TOKENS':
|
||||||
|
return 'success'
|
||||||
|
case 'REWARD':
|
||||||
|
return 'warning'
|
||||||
|
case 'MIXED':
|
||||||
|
return 'info'
|
||||||
|
default:
|
||||||
|
return 'secondary'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog
|
||||||
|
open={open}
|
||||||
|
onClose={onClose}
|
||||||
|
maxWidth='sm'
|
||||||
|
fullWidth
|
||||||
|
aria-labelledby='delete-dialog-title'
|
||||||
|
aria-describedby='delete-dialog-description'
|
||||||
|
>
|
||||||
|
<DialogTitle id='delete-dialog-title'>
|
||||||
|
<Box display='flex' alignItems='center' gap={2}>
|
||||||
|
<i className='tabler-trash text-red-500 text-2xl' />
|
||||||
|
<Typography variant='h6'>Hapus Kampanye</Typography>
|
||||||
|
</Box>
|
||||||
|
</DialogTitle>
|
||||||
|
|
||||||
|
<DialogContent>
|
||||||
|
<DialogContentText id='delete-dialog-description' className='mb-4'>
|
||||||
|
Apakah Anda yakin ingin menghapus kampanye berikut?
|
||||||
|
</DialogContentText>
|
||||||
|
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
backgroundColor: 'grey.50',
|
||||||
|
p: 2,
|
||||||
|
borderRadius: 1,
|
||||||
|
border: '1px solid',
|
||||||
|
borderColor: 'grey.200',
|
||||||
|
mb: 2
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Box display='flex' alignItems='center' gap={2} className='mb-2'>
|
||||||
|
<Typography variant='subtitle2' className='font-medium'>
|
||||||
|
{campaign.name}
|
||||||
|
</Typography>
|
||||||
|
<Chip label={campaign.type} color={getCampaignTypeColor(campaign.type)} variant='tonal' size='small' />
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{campaign.description && (
|
||||||
|
<Typography variant='body2' color='text.secondary' className='mb-2'>
|
||||||
|
{campaign.description}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Box display='flex' flexDirection='column' gap={1}>
|
||||||
|
<Typography variant='body2' color='text.secondary'>
|
||||||
|
Periode:{' '}
|
||||||
|
{new Date(campaign.start_date).toLocaleDateString('id-ID', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric'
|
||||||
|
})}{' '}
|
||||||
|
-{' '}
|
||||||
|
{new Date(campaign.end_date).toLocaleDateString('id-ID', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric'
|
||||||
|
})}
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
<Typography variant='body2' color='text.secondary'>
|
||||||
|
Status: {campaign.is_active ? 'Aktif' : 'Tidak Aktif'}
|
||||||
|
{campaign.show_on_app && ' • Tampil di App'}
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
<Typography variant='body2' color='text.secondary'>
|
||||||
|
Dibuat:{' '}
|
||||||
|
{new Date(campaign.created_at).toLocaleDateString('id-ID', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'long',
|
||||||
|
day: 'numeric'
|
||||||
|
})}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Alert severity='warning' sx={{ mb: 2 }}>
|
||||||
|
<Typography variant='body2'>
|
||||||
|
<strong>Peringatan:</strong> Tindakan ini tidak dapat dibatalkan. Semua data yang terkait dengan kampanye
|
||||||
|
ini akan dihapus secara permanen, termasuk:
|
||||||
|
</Typography>
|
||||||
|
<Box component='ul' sx={{ mt: 1, mb: 0, pl: 2 }}>
|
||||||
|
<li>Aturan kampanye (rules)</li>
|
||||||
|
<li>Riwayat penggunaan kampanye</li>
|
||||||
|
<li>Data analitik kampanye</li>
|
||||||
|
</Box>
|
||||||
|
</Alert>
|
||||||
|
|
||||||
|
<DialogContentText>
|
||||||
|
Pastikan tidak ada pengguna yang masih menggunakan kampanye ini dan tidak ada transaksi yang sedang berjalan
|
||||||
|
sebelum menghapus.
|
||||||
|
</DialogContentText>
|
||||||
|
</DialogContent>
|
||||||
|
|
||||||
|
<DialogActions className='p-4'>
|
||||||
|
<Button onClick={onClose} variant='outlined' disabled={isDeleting}>
|
||||||
|
Batal
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={onConfirm}
|
||||||
|
color='error'
|
||||||
|
variant='contained'
|
||||||
|
disabled={isDeleting}
|
||||||
|
startIcon={isDeleting ? <i className='tabler-loader animate-spin' /> : <i className='tabler-trash' />}
|
||||||
|
>
|
||||||
|
{isDeleting ? 'Menghapus...' : 'Hapus'}
|
||||||
|
</Button>
|
||||||
|
</DialogActions>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default DeleteCampaignDialog
|
||||||
17
src/views/apps/marketing/campaign/index.tsx
Normal file
17
src/views/apps/marketing/campaign/index.tsx
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
// MUI Imports
|
||||||
|
import Grid from '@mui/material/Grid2'
|
||||||
|
import LoyaltyListTable from './CampaignListTable'
|
||||||
|
|
||||||
|
// Type Imports
|
||||||
|
|
||||||
|
const LoyaltyList = () => {
|
||||||
|
return (
|
||||||
|
<Grid container spacing={6}>
|
||||||
|
<Grid size={{ xs: 12 }}>
|
||||||
|
<LoyaltyListTable />
|
||||||
|
</Grid>
|
||||||
|
</Grid>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default LoyaltyList
|
||||||
@ -0,0 +1,593 @@
|
|||||||
|
'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'
|
||||||
|
|
||||||
|
// Customer Analytics Interface
|
||||||
|
export interface CustomerAnalytics {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
email?: string
|
||||||
|
phone?: string
|
||||||
|
totalPoints: number
|
||||||
|
totalSpent?: number
|
||||||
|
loyaltyTier?: string // Bronze, Silver, Gold, dst
|
||||||
|
lastTransactionDate?: Date
|
||||||
|
}
|
||||||
|
|
||||||
|
declare module '@tanstack/table-core' {
|
||||||
|
interface FilterFns {
|
||||||
|
fuzzy: FilterFn<unknown>
|
||||||
|
}
|
||||||
|
interface FilterMeta {
|
||||||
|
itemRank: RankingInfo
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type CustomerAnalyticsWithAction = CustomerAnalytics & {
|
||||||
|
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 customer analytics
|
||||||
|
const DUMMY_CUSTOMER_ANALYTICS_DATA: CustomerAnalytics[] = [
|
||||||
|
{
|
||||||
|
id: '1',
|
||||||
|
name: 'Ahmad Wijaya',
|
||||||
|
email: 'ahmad.wijaya@email.com',
|
||||||
|
phone: '+628123456789',
|
||||||
|
totalPoints: 1250,
|
||||||
|
totalSpent: 5500000,
|
||||||
|
loyaltyTier: 'Gold',
|
||||||
|
lastTransactionDate: new Date('2024-09-10')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '2',
|
||||||
|
name: 'Siti Nurhaliza',
|
||||||
|
email: 'siti.nurhaliza@email.com',
|
||||||
|
phone: '+628234567890',
|
||||||
|
totalPoints: 850,
|
||||||
|
totalSpent: 3200000,
|
||||||
|
loyaltyTier: 'Silver',
|
||||||
|
lastTransactionDate: new Date('2024-09-15')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '3',
|
||||||
|
name: 'Budi Santoso',
|
||||||
|
email: 'budi.santoso@email.com',
|
||||||
|
phone: '+628345678901',
|
||||||
|
totalPoints: 2100,
|
||||||
|
totalSpent: 8750000,
|
||||||
|
loyaltyTier: 'Gold',
|
||||||
|
lastTransactionDate: new Date('2024-09-12')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '4',
|
||||||
|
name: 'Maya Puspita',
|
||||||
|
email: 'maya.puspita@email.com',
|
||||||
|
phone: '+628456789012',
|
||||||
|
totalPoints: 450,
|
||||||
|
totalSpent: 1800000,
|
||||||
|
loyaltyTier: 'Bronze',
|
||||||
|
lastTransactionDate: new Date('2024-09-08')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '5',
|
||||||
|
name: 'Rizki Pratama',
|
||||||
|
email: 'rizki.pratama@email.com',
|
||||||
|
phone: '+628567890123',
|
||||||
|
totalPoints: 1680,
|
||||||
|
totalSpent: 6300000,
|
||||||
|
loyaltyTier: 'Gold',
|
||||||
|
lastTransactionDate: new Date('2024-09-16')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '6',
|
||||||
|
name: 'Dewi Lestari',
|
||||||
|
email: 'dewi.lestari@email.com',
|
||||||
|
phone: '+628678901234',
|
||||||
|
totalPoints: 320,
|
||||||
|
totalSpent: 1200000,
|
||||||
|
loyaltyTier: 'Bronze',
|
||||||
|
lastTransactionDate: new Date('2024-09-05')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '7',
|
||||||
|
name: 'Eko Prasetyo',
|
||||||
|
email: 'eko.prasetyo@email.com',
|
||||||
|
phone: '+628789012345',
|
||||||
|
totalPoints: 975,
|
||||||
|
totalSpent: 4100000,
|
||||||
|
loyaltyTier: 'Silver',
|
||||||
|
lastTransactionDate: new Date('2024-09-14')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '8',
|
||||||
|
name: 'Lina Marlina',
|
||||||
|
email: 'lina.marlina@email.com',
|
||||||
|
phone: '+628890123456',
|
||||||
|
totalPoints: 1580,
|
||||||
|
totalSpent: 6800000,
|
||||||
|
loyaltyTier: 'Gold',
|
||||||
|
lastTransactionDate: new Date('2024-09-11')
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
// Mock data hook with dummy data
|
||||||
|
const useCustomerAnalytics = ({ 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_CUSTOMER_ANALYTICS_DATA
|
||||||
|
|
||||||
|
return DUMMY_CUSTOMER_ANALYTICS_DATA.filter(
|
||||||
|
customer =>
|
||||||
|
customer.name.toLowerCase().includes(search.toLowerCase()) ||
|
||||||
|
customer.email?.toLowerCase().includes(search.toLowerCase()) ||
|
||||||
|
customer.phone?.toLowerCase().includes(search.toLowerCase()) ||
|
||||||
|
customer.loyaltyTier?.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: {
|
||||||
|
customers: paginatedData,
|
||||||
|
total_count: filteredData.length
|
||||||
|
},
|
||||||
|
isLoading,
|
||||||
|
error: null,
|
||||||
|
isFetching: isLoading
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Utility functions
|
||||||
|
const getLoyaltyTierColor = (loyaltyTier?: string): ThemeColor => {
|
||||||
|
switch (loyaltyTier?.toLowerCase()) {
|
||||||
|
case 'bronze':
|
||||||
|
return 'warning'
|
||||||
|
case 'silver':
|
||||||
|
return 'info'
|
||||||
|
case 'gold':
|
||||||
|
return 'success'
|
||||||
|
default:
|
||||||
|
return 'secondary'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const getLoyaltyTierIcon = (loyaltyTier?: string): string => {
|
||||||
|
switch (loyaltyTier?.toLowerCase()) {
|
||||||
|
case 'bronze':
|
||||||
|
return 'tabler-medal'
|
||||||
|
case 'silver':
|
||||||
|
return 'tabler-medal-2'
|
||||||
|
case 'gold':
|
||||||
|
return 'tabler-crown'
|
||||||
|
default:
|
||||||
|
return 'tabler-user'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Column Definitions
|
||||||
|
const columnHelper = createColumnHelper<CustomerAnalyticsWithAction>()
|
||||||
|
|
||||||
|
const CustomerAnalyticListTable = () => {
|
||||||
|
// States
|
||||||
|
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 } = useCustomerAnalytics({
|
||||||
|
page: currentPage,
|
||||||
|
limit: pageSize,
|
||||||
|
search
|
||||||
|
})
|
||||||
|
|
||||||
|
const customers = data?.customers ?? []
|
||||||
|
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 handleViewCustomer = (customerId: string) => {
|
||||||
|
console.log('Viewing customer:', customerId)
|
||||||
|
// Add your view logic here
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDeleteCustomer = (customerId: string) => {
|
||||||
|
if (confirm('Apakah Anda yakin ingin menghapus data pelanggan ini?')) {
|
||||||
|
console.log('Deleting customer:', customerId)
|
||||||
|
// Add your delete logic here
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const columns = useMemo<ColumnDef<CustomerAnalyticsWithAction, 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: 'Pelanggan',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<div className='flex items-center gap-4'>
|
||||||
|
<CustomAvatar size={38}>{getInitials(row.original.name)}</CustomAvatar>
|
||||||
|
<div className='flex flex-col'>
|
||||||
|
<Link href={getLocalizedUrl(`/apps/customers/${row.original.id}/detail`, locale as Locale)}>
|
||||||
|
<Typography className='font-medium cursor-pointer hover:underline text-primary'>
|
||||||
|
{row.original.name}
|
||||||
|
</Typography>
|
||||||
|
</Link>
|
||||||
|
{row.original.email && (
|
||||||
|
<Typography variant='body2' color='text.secondary'>
|
||||||
|
{row.original.email}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('phone', {
|
||||||
|
header: 'No. Telepon',
|
||||||
|
cell: ({ row }) => <Typography color='text.primary'>{row.original.phone || '-'}</Typography>
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('totalPoints', {
|
||||||
|
header: 'Total Poin',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<div className='flex items-center gap-2'>
|
||||||
|
<Icon className='tabler-coins' sx={{ color: 'var(--mui-palette-primary-main)' }} />
|
||||||
|
<Typography color='text.primary' className='font-medium'>
|
||||||
|
{row.original.totalPoints.toLocaleString('id-ID')} Poin
|
||||||
|
</Typography>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('totalSpent', {
|
||||||
|
header: 'Total Belanja',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<Typography color='text.primary' className='font-medium'>
|
||||||
|
{row.original.totalSpent ? formatCurrency(row.original.totalSpent) : '-'}
|
||||||
|
</Typography>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('loyaltyTier', {
|
||||||
|
header: 'Tier Loyalitas',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<div className='flex items-center gap-2'>
|
||||||
|
<Icon
|
||||||
|
className={getLoyaltyTierIcon(row.original.loyaltyTier)}
|
||||||
|
sx={{ color: `var(--mui-palette-${getLoyaltyTierColor(row.original.loyaltyTier)}-main)` }}
|
||||||
|
/>
|
||||||
|
<Chip
|
||||||
|
label={row.original.loyaltyTier || 'Belum Ada'}
|
||||||
|
color={getLoyaltyTierColor(row.original.loyaltyTier)}
|
||||||
|
variant='tonal'
|
||||||
|
size='small'
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('lastTransactionDate', {
|
||||||
|
header: 'Transaksi Terakhir',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<Typography color='text.primary'>
|
||||||
|
{row.original.lastTransactionDate
|
||||||
|
? new Date(row.original.lastTransactionDate).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: 'Lihat Detail',
|
||||||
|
icon: 'tabler-eye text-[22px]',
|
||||||
|
menuItemProps: {
|
||||||
|
className: 'flex items-center gap-2 text-textSecondary',
|
||||||
|
onClick: () => handleViewCustomer(row.original.id)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
text: 'Hapus',
|
||||||
|
icon: 'tabler-trash text-[22px]',
|
||||||
|
menuItemProps: {
|
||||||
|
className: 'flex items-center gap-2 text-textSecondary',
|
||||||
|
onClick: () => handleDeleteCustomer(row.original.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
enableSorting: false
|
||||||
|
}
|
||||||
|
],
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
[locale, handleViewCustomer, handleDeleteCustomer]
|
||||||
|
)
|
||||||
|
|
||||||
|
const table = useReactTable({
|
||||||
|
data: customers as CustomerAnalytics[],
|
||||||
|
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 Pelanggan'
|
||||||
|
className='max-sm:is-full'
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
color='secondary'
|
||||||
|
variant='tonal'
|
||||||
|
startIcon={<i className='tabler-upload' />}
|
||||||
|
className='max-sm:is-full'
|
||||||
|
>
|
||||||
|
Ekspor
|
||||||
|
</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>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default CustomerAnalyticListTable
|
||||||
17
src/views/apps/marketing/customer-analytics/index.tsx
Normal file
17
src/views/apps/marketing/customer-analytics/index.tsx
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
// MUI Imports
|
||||||
|
import Grid from '@mui/material/Grid2'
|
||||||
|
import CustomerAnalyticListTable from './CustomerAnalyticListTable'
|
||||||
|
|
||||||
|
// Type Imports
|
||||||
|
|
||||||
|
const CustomerAnalyticList = () => {
|
||||||
|
return (
|
||||||
|
<Grid container spacing={6}>
|
||||||
|
<Grid size={{ xs: 12 }}>
|
||||||
|
<CustomerAnalyticListTable />
|
||||||
|
</Grid>
|
||||||
|
</Grid>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default CustomerAnalyticList
|
||||||
@ -0,0 +1,430 @@
|
|||||||
|
// 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 Typography from '@mui/material/Typography'
|
||||||
|
import Box from '@mui/material/Box'
|
||||||
|
import Switch from '@mui/material/Switch'
|
||||||
|
import FormControlLabel from '@mui/material/FormControlLabel'
|
||||||
|
import InputAdornment from '@mui/material/InputAdornment'
|
||||||
|
|
||||||
|
// Third-party Imports
|
||||||
|
import { useForm, Controller } from 'react-hook-form'
|
||||||
|
|
||||||
|
// Component Imports
|
||||||
|
import CustomTextField from '@core/components/mui/TextField'
|
||||||
|
import CustomAutocomplete from '@core/components/mui/Autocomplete'
|
||||||
|
|
||||||
|
// Services
|
||||||
|
import { useGamePrizesMutation } from '@/services/mutations/gamePrize'
|
||||||
|
import { useGames } from '@/services/queries/game'
|
||||||
|
import { GamePrize, GamePrizeRequest } from '@/types/services/gamePrize'
|
||||||
|
import { useGamePrizes } from '@/services/queries/gamePrize'
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
open: boolean
|
||||||
|
handleClose: () => void
|
||||||
|
data?: GamePrize // GamePrize data for edit (if exists)
|
||||||
|
}
|
||||||
|
|
||||||
|
type FormValidateType = {
|
||||||
|
game_id: string
|
||||||
|
name: string
|
||||||
|
weight: number
|
||||||
|
stock: number
|
||||||
|
max_stock?: number
|
||||||
|
threshold?: number
|
||||||
|
fallback_prize_id?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initial form data
|
||||||
|
const initialData: FormValidateType = {
|
||||||
|
game_id: '',
|
||||||
|
name: '',
|
||||||
|
weight: 1,
|
||||||
|
stock: 0,
|
||||||
|
max_stock: 0,
|
||||||
|
threshold: 0,
|
||||||
|
fallback_prize_id: undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
const AddEditGamePrizeDrawer = (props: Props) => {
|
||||||
|
// Props
|
||||||
|
const { open, handleClose, data } = props
|
||||||
|
|
||||||
|
// States
|
||||||
|
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||||
|
|
||||||
|
// Queries
|
||||||
|
const { data: gamesData } = useGames({ page: 1, limit: 100, search: '' })
|
||||||
|
const { data: gamePrizesData } = useGamePrizes({ page: 1, limit: 100, search: '' })
|
||||||
|
|
||||||
|
// Mutations
|
||||||
|
const { createGamePrize, updateGamePrize } = useGamePrizesMutation()
|
||||||
|
|
||||||
|
// Determine if this is edit mode
|
||||||
|
const isEditMode = Boolean(data?.id)
|
||||||
|
|
||||||
|
// Get available games and fallback prizes
|
||||||
|
const games = gamesData?.data ?? []
|
||||||
|
const availablePrizes = gamePrizesData?.data?.filter(prize => prize.id !== data?.id) ?? []
|
||||||
|
|
||||||
|
// Hooks
|
||||||
|
const {
|
||||||
|
control,
|
||||||
|
reset: resetForm,
|
||||||
|
handleSubmit,
|
||||||
|
watch,
|
||||||
|
formState: { errors }
|
||||||
|
} = useForm<FormValidateType>({
|
||||||
|
defaultValues: initialData
|
||||||
|
})
|
||||||
|
|
||||||
|
const watchedMaxStock = watch('max_stock')
|
||||||
|
|
||||||
|
// Effect to populate form when editing
|
||||||
|
useEffect(() => {
|
||||||
|
if (isEditMode && data) {
|
||||||
|
// Populate form with existing data
|
||||||
|
const formData: FormValidateType = {
|
||||||
|
game_id: data.game_id || '',
|
||||||
|
name: data.name || '',
|
||||||
|
weight: data.weight || 1,
|
||||||
|
stock: data.stock || 0,
|
||||||
|
max_stock: data.max_stock,
|
||||||
|
threshold: data.threshold,
|
||||||
|
fallback_prize_id: data.fallback_prize_id
|
||||||
|
}
|
||||||
|
|
||||||
|
resetForm(formData)
|
||||||
|
} else {
|
||||||
|
// Reset to initial data for add mode
|
||||||
|
resetForm(initialData)
|
||||||
|
}
|
||||||
|
}, [data, isEditMode, resetForm])
|
||||||
|
|
||||||
|
const handleFormSubmit = async (formData: FormValidateType) => {
|
||||||
|
try {
|
||||||
|
setIsSubmitting(true)
|
||||||
|
|
||||||
|
// Create GamePrizeRequest object
|
||||||
|
const gamePrizeRequest: GamePrizeRequest = {
|
||||||
|
game_id: formData.game_id,
|
||||||
|
name: formData.name,
|
||||||
|
weight: typeof formData.weight === 'string' ? parseFloat(formData.weight) : formData.weight || 1,
|
||||||
|
stock: typeof formData.stock === 'string' ? parseInt(formData.stock, 10) : formData.stock || 0,
|
||||||
|
max_stock: formData.max_stock
|
||||||
|
? typeof formData.max_stock === 'string'
|
||||||
|
? parseInt(formData.max_stock, 10)
|
||||||
|
: formData.max_stock
|
||||||
|
: undefined,
|
||||||
|
threshold: formData.threshold
|
||||||
|
? typeof formData.threshold === 'string'
|
||||||
|
? parseInt(formData.threshold, 10)
|
||||||
|
: formData.threshold
|
||||||
|
: undefined,
|
||||||
|
fallback_prize_id: formData.fallback_prize_id || undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isEditMode && data?.id) {
|
||||||
|
// Update existing game prize
|
||||||
|
updateGamePrize.mutate(
|
||||||
|
{ id: data.id, payload: gamePrizeRequest },
|
||||||
|
{
|
||||||
|
onSuccess: () => {
|
||||||
|
handleReset()
|
||||||
|
handleClose()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
// Create new game prize
|
||||||
|
createGamePrize.mutate(gamePrizeRequest, {
|
||||||
|
onSuccess: () => {
|
||||||
|
handleReset()
|
||||||
|
handleClose()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error submitting game prize:', error)
|
||||||
|
// Handle error (show toast, etc.)
|
||||||
|
} finally {
|
||||||
|
setIsSubmitting(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleReset = () => {
|
||||||
|
handleClose()
|
||||||
|
resetForm(initialData)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Drawer
|
||||||
|
open={open}
|
||||||
|
anchor='right'
|
||||||
|
variant='temporary'
|
||||||
|
onClose={handleReset}
|
||||||
|
ModalProps={{ keepMounted: true }}
|
||||||
|
sx={{
|
||||||
|
'& .MuiDrawer-paper': {
|
||||||
|
width: { xs: 350, sm: 450 },
|
||||||
|
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 Game' : 'Tambah Hadiah Game 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='game-prize-form' onSubmit={handleSubmit(handleFormSubmit)}>
|
||||||
|
<div className='flex flex-col gap-6 p-6'>
|
||||||
|
{/* Game Selection */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Pilih Game <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='game_id'
|
||||||
|
control={control}
|
||||||
|
rules={{ required: 'Game wajib dipilih' }}
|
||||||
|
render={({ field: { onChange, value, ...field } }) => (
|
||||||
|
<CustomAutocomplete
|
||||||
|
{...field}
|
||||||
|
options={games}
|
||||||
|
getOptionLabel={option => `${option.name} (${option.type})`}
|
||||||
|
value={games.find(game => game.id === value) || null}
|
||||||
|
onChange={(_, newValue) => onChange(newValue?.id || '')}
|
||||||
|
disabled={isEditMode}
|
||||||
|
renderInput={params => (
|
||||||
|
<CustomTextField
|
||||||
|
{...params}
|
||||||
|
placeholder='Pilih game'
|
||||||
|
error={!!errors.game_id}
|
||||||
|
helperText={errors.game_id?.message}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
isOptionEqualToValue={(option, value) => option.id === value?.id}
|
||||||
|
noOptionsText='Tidak ada game tersedia'
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 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>
|
||||||
|
|
||||||
|
{/* Bobot */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Bobot <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='weight'
|
||||||
|
control={control}
|
||||||
|
rules={{
|
||||||
|
required: 'Bobot wajib diisi',
|
||||||
|
min: { value: 1, message: 'Bobot minimal 1' }
|
||||||
|
}}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
type='number'
|
||||||
|
placeholder='Masukkan bobot hadiah'
|
||||||
|
error={!!errors.weight}
|
||||||
|
helperText={errors.weight?.message}
|
||||||
|
InputProps={{
|
||||||
|
endAdornment: <InputAdornment position='end'>%</InputAdornment>
|
||||||
|
}}
|
||||||
|
inputProps={{ min: 1, max: 100 }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Stock */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Stok <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='stock'
|
||||||
|
control={control}
|
||||||
|
rules={{
|
||||||
|
required: 'Stok wajib diisi',
|
||||||
|
min: { value: 0, message: 'Stok minimal 0' },
|
||||||
|
validate: value => {
|
||||||
|
if (watchedMaxStock && value > watchedMaxStock) {
|
||||||
|
return 'Stok tidak boleh melebihi maksimal stok'
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
type='number'
|
||||||
|
placeholder='Masukkan jumlah stok'
|
||||||
|
error={!!errors.stock}
|
||||||
|
helperText={errors.stock?.message}
|
||||||
|
inputProps={{ min: 0 }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Max Stock */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Maksimal Stok
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='max_stock'
|
||||||
|
control={control}
|
||||||
|
rules={{
|
||||||
|
min: { value: 1, message: 'Maksimal stok minimal 1' }
|
||||||
|
}}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
type='number'
|
||||||
|
placeholder='Masukkan maksimal stok (opsional)'
|
||||||
|
error={!!errors.max_stock}
|
||||||
|
helperText={errors.max_stock?.message}
|
||||||
|
inputProps={{ min: 1 }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Threshold */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Threshold
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='threshold'
|
||||||
|
control={control}
|
||||||
|
rules={{
|
||||||
|
required: 'Threshold wajib diisi',
|
||||||
|
min: { value: 0, message: 'Threshold minimal 0' }
|
||||||
|
}}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
type='number'
|
||||||
|
placeholder='Masukkan threshold '
|
||||||
|
error={!!errors.threshold}
|
||||||
|
helperText={errors.threshold?.message}
|
||||||
|
inputProps={{ min: 0 }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Fallback Prize */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Hadiah Cadangan
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='fallback_prize_id'
|
||||||
|
control={control}
|
||||||
|
render={({ field: { onChange, value, ...field } }) => (
|
||||||
|
<CustomAutocomplete
|
||||||
|
{...field}
|
||||||
|
options={availablePrizes}
|
||||||
|
getOptionLabel={option => `${option.name} (Stok: ${option.stock})`}
|
||||||
|
value={availablePrizes.find(prize => prize.id === value) || null}
|
||||||
|
onChange={(_, newValue) => onChange(newValue?.id || '')}
|
||||||
|
renderInput={params => (
|
||||||
|
<CustomTextField
|
||||||
|
{...params}
|
||||||
|
placeholder='Pilih hadiah cadangan'
|
||||||
|
error={!!errors.fallback_prize_id}
|
||||||
|
helperText={
|
||||||
|
errors.fallback_prize_id?.message || 'Hadiah yang diberikan ketika hadiah ini habis'
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
isOptionEqualToValue={(option, value) => option.id === value?.id}
|
||||||
|
noOptionsText='Tidak ada hadiah tersedia'
|
||||||
|
clearText='Hapus'
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{/* Sticky Footer */}
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
position: 'sticky',
|
||||||
|
bottom: 0,
|
||||||
|
zIndex: 10,
|
||||||
|
backgroundColor: 'background.paper',
|
||||||
|
borderTop: 1,
|
||||||
|
borderColor: 'divider',
|
||||||
|
p: 3
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className='flex items-center gap-4'>
|
||||||
|
<Button variant='contained' type='submit' form='game-prize-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 AddEditGamePrizeDrawer
|
||||||
@ -0,0 +1,104 @@
|
|||||||
|
// React Imports
|
||||||
|
import { useState } from 'react'
|
||||||
|
|
||||||
|
// MUI Imports
|
||||||
|
import Dialog from '@mui/material/Dialog'
|
||||||
|
import DialogTitle from '@mui/material/DialogTitle'
|
||||||
|
import DialogContent from '@mui/material/DialogContent'
|
||||||
|
import DialogActions from '@mui/material/DialogActions'
|
||||||
|
import DialogContentText from '@mui/material/DialogContentText'
|
||||||
|
import Button from '@mui/material/Button'
|
||||||
|
import Typography from '@mui/material/Typography'
|
||||||
|
import Box from '@mui/material/Box'
|
||||||
|
import Alert from '@mui/material/Alert'
|
||||||
|
import { GamePrize } from '@/types/services/gamePrize'
|
||||||
|
import { useGamePrizes } from '@/services/queries/gamePrize'
|
||||||
|
|
||||||
|
// Types
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
open: boolean
|
||||||
|
onClose: () => void
|
||||||
|
onConfirm: () => void
|
||||||
|
gamePrize: GamePrize | null
|
||||||
|
isDeleting?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
const DeleteGamePrizeDialog = ({ open, onClose, onConfirm, gamePrize, isDeleting = false }: Props) => {
|
||||||
|
if (!gamePrize) return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog
|
||||||
|
open={open}
|
||||||
|
onClose={onClose}
|
||||||
|
maxWidth='sm'
|
||||||
|
fullWidth
|
||||||
|
aria-labelledby='delete-dialog-title'
|
||||||
|
aria-describedby='delete-dialog-description'
|
||||||
|
>
|
||||||
|
<DialogTitle id='delete-dialog-title'>
|
||||||
|
<Box display='flex' alignItems='center' gap={2}>
|
||||||
|
<i className='tabler-trash text-red-500 text-2xl' />
|
||||||
|
<Typography variant='h6'>Hapus Game</Typography>
|
||||||
|
</Box>
|
||||||
|
</DialogTitle>
|
||||||
|
|
||||||
|
<DialogContent>
|
||||||
|
<DialogContentText id='delete-dialog-description' className='mb-4'>
|
||||||
|
Apakah Anda yakin ingin menghapus game berikut?
|
||||||
|
</DialogContentText>
|
||||||
|
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
backgroundColor: 'grey.50',
|
||||||
|
p: 2,
|
||||||
|
borderRadius: 1,
|
||||||
|
border: '1px solid',
|
||||||
|
borderColor: 'grey.200',
|
||||||
|
mb: 2
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Typography variant='subtitle2' className='font-medium mb-1'>
|
||||||
|
{gamePrize.name}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant='body2' color='text.secondary'>
|
||||||
|
Dibuat:{' '}
|
||||||
|
{new Date(gamePrize.created_at).toLocaleDateString('id-ID', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'long',
|
||||||
|
day: 'numeric'
|
||||||
|
})}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Alert severity='warning' sx={{ mb: 2 }}>
|
||||||
|
<Typography variant='body2'>
|
||||||
|
<strong>Peringatan:</strong> Tindakan ini tidak dapat dibatalkan. Semua data yang terkait dengan game ini
|
||||||
|
akan dihapus secara permanen.
|
||||||
|
</Typography>
|
||||||
|
</Alert>
|
||||||
|
|
||||||
|
<DialogContentText>
|
||||||
|
Pastikan tidak ada pengguna yang masih menggunakan game ini sebelum menghapus.
|
||||||
|
</DialogContentText>
|
||||||
|
</DialogContent>
|
||||||
|
|
||||||
|
<DialogActions className='p-4'>
|
||||||
|
<Button onClick={onClose} variant='outlined' disabled={isDeleting}>
|
||||||
|
Batal
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={onConfirm}
|
||||||
|
color='error'
|
||||||
|
variant='contained'
|
||||||
|
disabled={isDeleting}
|
||||||
|
startIcon={isDeleting ? <i className='tabler-loader animate-spin' /> : <i className='tabler-trash' />}
|
||||||
|
>
|
||||||
|
{isDeleting ? 'Menghapus...' : 'Hapus'}
|
||||||
|
</Button>
|
||||||
|
</DialogActions>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default DeleteGamePrizeDialog
|
||||||
@ -0,0 +1,483 @@
|
|||||||
|
'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 AddEditGamePrizeDrawer from './AddEditGamePrizeDrawer'
|
||||||
|
import DeleteGamePrizeDialog from './DeleteGamePrizeDialog'
|
||||||
|
import { useGamePrizes } from '@/services/queries/gamePrize'
|
||||||
|
import { useGamePrizesMutation } from '@/services/mutations/gamePrize'
|
||||||
|
import { GamePrize } from '@/types/services/gamePrize'
|
||||||
|
|
||||||
|
declare module '@tanstack/table-core' {
|
||||||
|
interface FilterFns {
|
||||||
|
fuzzy: FilterFn<unknown>
|
||||||
|
}
|
||||||
|
interface FilterMeta {
|
||||||
|
itemRank: RankingInfo
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type GamePrizeWithAction = GamePrize & {
|
||||||
|
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)} />
|
||||||
|
}
|
||||||
|
|
||||||
|
// Column Definitions
|
||||||
|
const columnHelper = createColumnHelper<GamePrizeWithAction>()
|
||||||
|
|
||||||
|
const GamePrizeListTable = () => {
|
||||||
|
// States
|
||||||
|
const [addGamePrizeOpen, setAddGamePrizeOpen] = useState(false)
|
||||||
|
const [editGamePrizeData, setEditGamePrizeData] = useState<GamePrize | undefined>(undefined)
|
||||||
|
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
|
||||||
|
const [gamePrizeToDelete, setGamePrizeToDelete] = useState<GamePrize | null>(null)
|
||||||
|
const [rowSelection, setRowSelection] = useState({})
|
||||||
|
const [globalFilter, setGlobalFilter] = useState('')
|
||||||
|
const [currentPage, setCurrentPage] = useState(1)
|
||||||
|
const [pageSize, setPageSize] = useState(10)
|
||||||
|
const [search, setSearch] = useState('')
|
||||||
|
|
||||||
|
// Replace with actual hook for game prizes
|
||||||
|
const { data, isLoading, error, isFetching } = useGamePrizes({
|
||||||
|
page: currentPage,
|
||||||
|
limit: pageSize,
|
||||||
|
search
|
||||||
|
})
|
||||||
|
|
||||||
|
const { deleteGamePrize } = useGamePrizesMutation()
|
||||||
|
|
||||||
|
const gamePrizes = data?.data ?? []
|
||||||
|
const totalCount = data?.total_count ?? 0
|
||||||
|
|
||||||
|
// Hooks
|
||||||
|
const { lang: locale } = useParams()
|
||||||
|
|
||||||
|
const handlePageChange = useCallback((event: unknown, newPage: number) => {
|
||||||
|
setCurrentPage(newPage)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const handlePageSizeChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const newPageSize = parseInt(event.target.value, 10)
|
||||||
|
setPageSize(newPageSize)
|
||||||
|
setCurrentPage(1) // Reset to first page
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const handleEditGamePrize = (gamePrize: GamePrize) => {
|
||||||
|
setEditGamePrizeData(gamePrize)
|
||||||
|
setAddGamePrizeOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDeleteGamePrize = (gamePrize: GamePrize) => {
|
||||||
|
setGamePrizeToDelete(gamePrize)
|
||||||
|
setDeleteDialogOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleConfirmDelete = () => {
|
||||||
|
if (gamePrizeToDelete) {
|
||||||
|
deleteGamePrize.mutate(gamePrizeToDelete.id, {
|
||||||
|
onSuccess: () => {
|
||||||
|
console.log('Game Prize deleted successfully')
|
||||||
|
setDeleteDialogOpen(false)
|
||||||
|
setGamePrizeToDelete(null)
|
||||||
|
},
|
||||||
|
onError: error => {
|
||||||
|
console.error('Error deleting game prize:', error)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCloseDeleteDialog = () => {
|
||||||
|
if (deleteGamePrize.isPending) return
|
||||||
|
setDeleteDialogOpen(false)
|
||||||
|
setGamePrizeToDelete(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCloseGamePrizeDrawer = () => {
|
||||||
|
setAddGamePrizeOpen(false)
|
||||||
|
setEditGamePrizeData(undefined)
|
||||||
|
}
|
||||||
|
|
||||||
|
const columns = useMemo<ColumnDef<GamePrizeWithAction, 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'>
|
||||||
|
<CustomAvatar src={row.original.metadata?.imageUrl} size={40}>
|
||||||
|
{getInitials(row.original.name)}
|
||||||
|
</CustomAvatar>
|
||||||
|
<div className='flex flex-col'>
|
||||||
|
<Link href={getLocalizedUrl(`/apps/game-prizes/${row.original.id}/detail`, locale as Locale)}>
|
||||||
|
<Typography className='font-medium cursor-pointer hover:underline text-primary'>
|
||||||
|
{row.original.name}
|
||||||
|
</Typography>
|
||||||
|
</Link>
|
||||||
|
<Typography variant='caption' color='textSecondary'>
|
||||||
|
{row.original.game?.name || 'Game tidak tersedia'}
|
||||||
|
</Typography>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('game', {
|
||||||
|
header: 'Game',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<div className='flex flex-col'>
|
||||||
|
<Typography className='font-medium'>{row.original.game?.name || 'N/A'}</Typography>
|
||||||
|
<Typography variant='caption' color='textSecondary'>
|
||||||
|
{row.original.game?.type || ''}
|
||||||
|
</Typography>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('weight', {
|
||||||
|
header: 'Bobot',
|
||||||
|
cell: ({ row }) => <Typography color='text.primary'>{row.original.weight}%</Typography>
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('stock', {
|
||||||
|
header: 'Stok',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<div className='flex flex-col gap-1'>
|
||||||
|
<Typography className='font-medium'>
|
||||||
|
{row.original.stock}
|
||||||
|
{row.original.max_stock && ` / ${row.original.max_stock}`}
|
||||||
|
</Typography>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('threshold', {
|
||||||
|
header: 'Threshold',
|
||||||
|
cell: ({ row }) => <Typography color='text.primary'>{row.original.threshold || 'Tidak Ada'}</Typography>
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('fallback_prize', {
|
||||||
|
header: 'Hadiah Cadangan',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<Typography color='text.primary'>{row.original.fallback_prize?.name || 'Tidak Ada'}</Typography>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('created_at', {
|
||||||
|
header: 'Tanggal Dibuat',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<Typography color='text.primary'>
|
||||||
|
{new Date(row.original.created_at).toLocaleDateString('id-ID', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric'
|
||||||
|
})}
|
||||||
|
</Typography>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
id: 'actions',
|
||||||
|
header: 'Aksi',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<div className='flex items-center'>
|
||||||
|
<OptionMenu
|
||||||
|
iconButtonProps={{ size: 'medium' }}
|
||||||
|
iconClassName='text-textSecondary text-[22px]'
|
||||||
|
options={[
|
||||||
|
{
|
||||||
|
text: 'Edit',
|
||||||
|
icon: 'tabler-edit text-[22px]',
|
||||||
|
menuItemProps: {
|
||||||
|
className: 'flex items-center gap-2 text-textSecondary',
|
||||||
|
onClick: () => handleEditGamePrize(row.original)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
text: 'Hapus',
|
||||||
|
icon: 'tabler-trash text-[22px]',
|
||||||
|
menuItemProps: {
|
||||||
|
className: 'flex items-center gap-2 text-textSecondary',
|
||||||
|
onClick: () => handleDeleteGamePrize(row.original)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
enableSorting: false
|
||||||
|
}
|
||||||
|
],
|
||||||
|
[locale, handleEditGamePrize, handleDeleteGamePrize]
|
||||||
|
)
|
||||||
|
|
||||||
|
const table = useReactTable({
|
||||||
|
data: gamePrizes as GamePrize[],
|
||||||
|
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 Game'
|
||||||
|
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={() => setAddGamePrizeOpen(!addGamePrizeOpen)}
|
||||||
|
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>
|
||||||
|
|
||||||
|
{/* Add/Edit Game Prize Drawer */}
|
||||||
|
<AddEditGamePrizeDrawer
|
||||||
|
open={addGamePrizeOpen}
|
||||||
|
handleClose={handleCloseGamePrizeDrawer}
|
||||||
|
data={editGamePrizeData}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Delete Game Prize Dialog */}
|
||||||
|
<DeleteGamePrizeDialog
|
||||||
|
open={deleteDialogOpen}
|
||||||
|
onClose={handleCloseDeleteDialog}
|
||||||
|
onConfirm={handleConfirmDelete}
|
||||||
|
gamePrize={gamePrizeToDelete}
|
||||||
|
isDeleting={deleteGamePrize.isPending}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default GamePrizeListTable
|
||||||
17
src/views/apps/marketing/games/game-prizes/index.tsx
Normal file
17
src/views/apps/marketing/games/game-prizes/index.tsx
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
// MUI Imports
|
||||||
|
import Grid from '@mui/material/Grid2'
|
||||||
|
import GamePrizeListTable from './GamePrizeListTable'
|
||||||
|
|
||||||
|
// Type Imports
|
||||||
|
|
||||||
|
const GamePrizeList = () => {
|
||||||
|
return (
|
||||||
|
<Grid container spacing={6}>
|
||||||
|
<Grid size={{ xs: 12 }}>
|
||||||
|
<GamePrizeListTable />
|
||||||
|
</Grid>
|
||||||
|
</Grid>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default GamePrizeList
|
||||||
325
src/views/apps/marketing/games/list/AddEditGamesDrawer.tsx
Normal file
325
src/views/apps/marketing/games/list/AddEditGamesDrawer.tsx
Normal file
@ -0,0 +1,325 @@
|
|||||||
|
// React Imports
|
||||||
|
import { useState, useEffect } from 'react'
|
||||||
|
|
||||||
|
// MUI Imports
|
||||||
|
import Button from '@mui/material/Button'
|
||||||
|
import Drawer from '@mui/material/Drawer'
|
||||||
|
import IconButton from '@mui/material/IconButton'
|
||||||
|
import MenuItem from '@mui/material/MenuItem'
|
||||||
|
import Typography from '@mui/material/Typography'
|
||||||
|
import Box from '@mui/material/Box'
|
||||||
|
import Switch from '@mui/material/Switch'
|
||||||
|
import FormControlLabel from '@mui/material/FormControlLabel'
|
||||||
|
|
||||||
|
// Third-party Imports
|
||||||
|
import { useForm, Controller } from 'react-hook-form'
|
||||||
|
|
||||||
|
// Component Imports
|
||||||
|
import CustomTextField from '@core/components/mui/TextField'
|
||||||
|
import ImageUpload from '@/components/ImageUpload'
|
||||||
|
|
||||||
|
// Services
|
||||||
|
import { useFilesMutation } from '@/services/mutations/files'
|
||||||
|
import { Game, GameRequest } from '@/types/services/game'
|
||||||
|
import { useGamesMutation } from '@/services/mutations/game'
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
open: boolean
|
||||||
|
handleClose: () => void
|
||||||
|
data?: Game // Game data for edit (if exists)
|
||||||
|
}
|
||||||
|
|
||||||
|
type FormValidateType = {
|
||||||
|
name: string
|
||||||
|
type: string
|
||||||
|
is_active: boolean
|
||||||
|
imageUrl: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initial form data
|
||||||
|
const initialData: FormValidateType = {
|
||||||
|
name: '',
|
||||||
|
type: 'quiz',
|
||||||
|
is_active: true,
|
||||||
|
imageUrl: ''
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mock mutation hooks (replace with actual hooks)
|
||||||
|
|
||||||
|
// Game types
|
||||||
|
const GAME_TYPES = [
|
||||||
|
{ value: 'SPIN', label: 'Spin' },
|
||||||
|
{ value: 'RUFFLE', label: 'Ruffle' },
|
||||||
|
{ value: 'MINIGAME', label: 'Mini Game' }
|
||||||
|
]
|
||||||
|
|
||||||
|
const AddEditGamesDrawer = (props: Props) => {
|
||||||
|
// Props
|
||||||
|
const { open, handleClose, data } = props
|
||||||
|
|
||||||
|
// States
|
||||||
|
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||||
|
const [imageUrl, setImageUrl] = useState<string>('')
|
||||||
|
|
||||||
|
const { createGame, updateGame } = useGamesMutation()
|
||||||
|
const { mutate, isPending } = useFilesMutation().uploadFile
|
||||||
|
|
||||||
|
// Determine if this is edit mode
|
||||||
|
const isEditMode = Boolean(data?.id)
|
||||||
|
|
||||||
|
// Handle file upload
|
||||||
|
const handleUpload = async (file: File): Promise<string> => {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const formData = new FormData()
|
||||||
|
formData.append('file', file)
|
||||||
|
formData.append('file_type', 'image')
|
||||||
|
formData.append('description', 'game image upload')
|
||||||
|
|
||||||
|
mutate(formData, {
|
||||||
|
onSuccess: r => {
|
||||||
|
setImageUrl(r.file_url)
|
||||||
|
setValue('imageUrl', r.file_url) // Update form value
|
||||||
|
resolve(r.id)
|
||||||
|
},
|
||||||
|
onError: er => {
|
||||||
|
reject(er)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hooks
|
||||||
|
const {
|
||||||
|
control,
|
||||||
|
reset: resetForm,
|
||||||
|
handleSubmit,
|
||||||
|
watch,
|
||||||
|
setValue,
|
||||||
|
formState: { errors }
|
||||||
|
} = useForm<FormValidateType>({
|
||||||
|
defaultValues: initialData
|
||||||
|
})
|
||||||
|
|
||||||
|
const watchedImageUrl = watch('imageUrl')
|
||||||
|
|
||||||
|
// Effect to populate form when editing
|
||||||
|
useEffect(() => {
|
||||||
|
if (isEditMode && data) {
|
||||||
|
// Extract imageUrl from metadata
|
||||||
|
const imageUrlFromData = data.metadata?.imageUrl || ''
|
||||||
|
|
||||||
|
// Populate form with existing data
|
||||||
|
const formData: FormValidateType = {
|
||||||
|
name: data.name || '',
|
||||||
|
type: data.type || 'SPIN',
|
||||||
|
is_active: data.is_active ?? true,
|
||||||
|
imageUrl: imageUrlFromData
|
||||||
|
}
|
||||||
|
|
||||||
|
resetForm(formData)
|
||||||
|
setImageUrl(imageUrlFromData)
|
||||||
|
} else {
|
||||||
|
// Reset to initial data for add mode
|
||||||
|
resetForm(initialData)
|
||||||
|
setImageUrl('')
|
||||||
|
}
|
||||||
|
}, [data, isEditMode, resetForm])
|
||||||
|
|
||||||
|
// Sync imageUrl state with form value
|
||||||
|
useEffect(() => {
|
||||||
|
if (watchedImageUrl !== imageUrl) {
|
||||||
|
setImageUrl(watchedImageUrl)
|
||||||
|
}
|
||||||
|
}, [watchedImageUrl, imageUrl])
|
||||||
|
|
||||||
|
const handleFormSubmit = async (formData: FormValidateType) => {
|
||||||
|
try {
|
||||||
|
setIsSubmitting(true)
|
||||||
|
|
||||||
|
// Create GameRequest object
|
||||||
|
const gameRequest: GameRequest = {
|
||||||
|
name: formData.name,
|
||||||
|
type: formData.type,
|
||||||
|
is_active: formData.is_active,
|
||||||
|
metadata: {
|
||||||
|
imageUrl: formData.imageUrl || undefined
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isEditMode && data?.id) {
|
||||||
|
// Update existing game
|
||||||
|
updateGame.mutate(
|
||||||
|
{ id: data.id, payload: gameRequest },
|
||||||
|
{
|
||||||
|
onSuccess: () => {
|
||||||
|
handleReset()
|
||||||
|
handleClose()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
// Create new game
|
||||||
|
createGame.mutate(gameRequest, {
|
||||||
|
onSuccess: () => {
|
||||||
|
handleReset()
|
||||||
|
handleClose()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error submitting game:', error)
|
||||||
|
// Handle error (show toast, etc.)
|
||||||
|
} finally {
|
||||||
|
setIsSubmitting(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleReset = () => {
|
||||||
|
handleClose()
|
||||||
|
resetForm(initialData)
|
||||||
|
setImageUrl('')
|
||||||
|
}
|
||||||
|
|
||||||
|
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 Game' : 'Tambah Game 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='game-form' onSubmit={handleSubmit(handleFormSubmit)}>
|
||||||
|
<div className='flex flex-col gap-6 p-6'>
|
||||||
|
{/* Nama Game */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Nama Game <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='name'
|
||||||
|
control={control}
|
||||||
|
rules={{ required: 'Nama game wajib diisi' }}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
placeholder='Masukkan nama game'
|
||||||
|
error={!!errors.name}
|
||||||
|
helperText={errors.name?.message}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tipe Game */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Tipe Game <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='type'
|
||||||
|
control={control}
|
||||||
|
rules={{ required: 'Tipe game wajib dipilih' }}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField {...field} select fullWidth error={!!errors.type} helperText={errors.type?.message}>
|
||||||
|
{GAME_TYPES.map(type => (
|
||||||
|
<MenuItem key={type.value} value={type.value}>
|
||||||
|
{type.label}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</CustomTextField>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Image Upload */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Gambar Game
|
||||||
|
</Typography>
|
||||||
|
<ImageUpload
|
||||||
|
onUpload={handleUpload}
|
||||||
|
maxFileSize={1 * 1024 * 1024} // 1MB
|
||||||
|
currentImageUrl={imageUrl}
|
||||||
|
dragDropText='Drop your image here'
|
||||||
|
browseButtonText='Choose Image'
|
||||||
|
/>
|
||||||
|
<Controller
|
||||||
|
name='imageUrl'
|
||||||
|
control={control}
|
||||||
|
render={({ field }) => <input type='hidden' {...field} value={imageUrl} />}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Status Aktif */}
|
||||||
|
<div>
|
||||||
|
<Controller
|
||||||
|
name='is_active'
|
||||||
|
control={control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormControlLabel
|
||||||
|
control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
|
||||||
|
label='Game Aktif'
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{/* Sticky Footer */}
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
position: 'sticky',
|
||||||
|
bottom: 0,
|
||||||
|
zIndex: 10,
|
||||||
|
backgroundColor: 'background.paper',
|
||||||
|
borderTop: 1,
|
||||||
|
borderColor: 'divider',
|
||||||
|
p: 3
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className='flex items-center gap-4'>
|
||||||
|
<Button variant='contained' type='submit' form='game-form' disabled={isSubmitting || isPending}>
|
||||||
|
{isSubmitting ? (isEditMode ? 'Mengupdate...' : 'Menyimpan...') : isEditMode ? 'Update' : 'Simpan'}
|
||||||
|
</Button>
|
||||||
|
<Button variant='outlined' color='error' onClick={handleReset} disabled={isSubmitting || isPending}>
|
||||||
|
Batal
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</Box>
|
||||||
|
</Drawer>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default AddEditGamesDrawer
|
||||||
103
src/views/apps/marketing/games/list/DeleteGamesDialog.tsx
Normal file
103
src/views/apps/marketing/games/list/DeleteGamesDialog.tsx
Normal file
@ -0,0 +1,103 @@
|
|||||||
|
// React Imports
|
||||||
|
import { useState } from 'react'
|
||||||
|
|
||||||
|
// MUI Imports
|
||||||
|
import Dialog from '@mui/material/Dialog'
|
||||||
|
import DialogTitle from '@mui/material/DialogTitle'
|
||||||
|
import DialogContent from '@mui/material/DialogContent'
|
||||||
|
import DialogActions from '@mui/material/DialogActions'
|
||||||
|
import DialogContentText from '@mui/material/DialogContentText'
|
||||||
|
import Button from '@mui/material/Button'
|
||||||
|
import Typography from '@mui/material/Typography'
|
||||||
|
import Box from '@mui/material/Box'
|
||||||
|
import Alert from '@mui/material/Alert'
|
||||||
|
|
||||||
|
// Types
|
||||||
|
import { Game } from '@/types/services/game'
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
open: boolean
|
||||||
|
onClose: () => void
|
||||||
|
onConfirm: () => void
|
||||||
|
game: Game | null
|
||||||
|
isDeleting?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
const DeleteGameDialog = ({ open, onClose, onConfirm, game, isDeleting = false }: Props) => {
|
||||||
|
if (!game) return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog
|
||||||
|
open={open}
|
||||||
|
onClose={onClose}
|
||||||
|
maxWidth='sm'
|
||||||
|
fullWidth
|
||||||
|
aria-labelledby='delete-dialog-title'
|
||||||
|
aria-describedby='delete-dialog-description'
|
||||||
|
>
|
||||||
|
<DialogTitle id='delete-dialog-title'>
|
||||||
|
<Box display='flex' alignItems='center' gap={2}>
|
||||||
|
<i className='tabler-trash text-red-500 text-2xl' />
|
||||||
|
<Typography variant='h6'>Hapus Game</Typography>
|
||||||
|
</Box>
|
||||||
|
</DialogTitle>
|
||||||
|
|
||||||
|
<DialogContent>
|
||||||
|
<DialogContentText id='delete-dialog-description' className='mb-4'>
|
||||||
|
Apakah Anda yakin ingin menghapus game berikut?
|
||||||
|
</DialogContentText>
|
||||||
|
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
backgroundColor: 'grey.50',
|
||||||
|
p: 2,
|
||||||
|
borderRadius: 1,
|
||||||
|
border: '1px solid',
|
||||||
|
borderColor: 'grey.200',
|
||||||
|
mb: 2
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Typography variant='subtitle2' className='font-medium mb-1'>
|
||||||
|
{game.name}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant='body2' color='text.secondary'>
|
||||||
|
Dibuat:{' '}
|
||||||
|
{new Date(game.created_at).toLocaleDateString('id-ID', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'long',
|
||||||
|
day: 'numeric'
|
||||||
|
})}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Alert severity='warning' sx={{ mb: 2 }}>
|
||||||
|
<Typography variant='body2'>
|
||||||
|
<strong>Peringatan:</strong> Tindakan ini tidak dapat dibatalkan. Semua data yang terkait dengan game ini
|
||||||
|
akan dihapus secara permanen.
|
||||||
|
</Typography>
|
||||||
|
</Alert>
|
||||||
|
|
||||||
|
<DialogContentText>
|
||||||
|
Pastikan tidak ada pengguna yang masih menggunakan game ini sebelum menghapus.
|
||||||
|
</DialogContentText>
|
||||||
|
</DialogContent>
|
||||||
|
|
||||||
|
<DialogActions className='p-4'>
|
||||||
|
<Button onClick={onClose} variant='outlined' disabled={isDeleting}>
|
||||||
|
Batal
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={onConfirm}
|
||||||
|
color='error'
|
||||||
|
variant='contained'
|
||||||
|
disabled={isDeleting}
|
||||||
|
startIcon={isDeleting ? <i className='tabler-loader animate-spin' /> : <i className='tabler-trash' />}
|
||||||
|
>
|
||||||
|
{isDeleting ? 'Menghapus...' : 'Hapus'}
|
||||||
|
</Button>
|
||||||
|
</DialogActions>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default DeleteGameDialog
|
||||||
467
src/views/apps/marketing/games/list/GameListTable.tsx
Normal file
467
src/views/apps/marketing/games/list/GameListTable.tsx
Normal file
@ -0,0 +1,467 @@
|
|||||||
|
'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 AddEditGamesDrawer from './AddEditGamesDrawer'
|
||||||
|
import DeleteGameDialog from './DeleteGamesDialog'
|
||||||
|
import { Game } from '@/types/services/game'
|
||||||
|
import { useGames } from '@/services/queries/game'
|
||||||
|
import { useGamesMutation } from '@/services/mutations/game'
|
||||||
|
|
||||||
|
declare module '@tanstack/table-core' {
|
||||||
|
interface FilterFns {
|
||||||
|
fuzzy: FilterFn<unknown>
|
||||||
|
}
|
||||||
|
interface FilterMeta {
|
||||||
|
itemRank: RankingInfo
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type GameWithAction = Game & {
|
||||||
|
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)} />
|
||||||
|
}
|
||||||
|
|
||||||
|
// Column Definitions
|
||||||
|
const columnHelper = createColumnHelper<GameWithAction>()
|
||||||
|
|
||||||
|
const GameListTable = () => {
|
||||||
|
// States
|
||||||
|
const [addGameOpen, setAddGameOpen] = useState(false)
|
||||||
|
const [editGameData, setEditGameData] = useState<Game | undefined>(undefined)
|
||||||
|
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
|
||||||
|
const [gameToDelete, setGameToDelete] = useState<Game | null>(null)
|
||||||
|
const [rowSelection, setRowSelection] = useState({})
|
||||||
|
const [globalFilter, setGlobalFilter] = useState('')
|
||||||
|
const [currentPage, setCurrentPage] = useState(1)
|
||||||
|
const [pageSize, setPageSize] = useState(10)
|
||||||
|
const [search, setSearch] = useState('')
|
||||||
|
|
||||||
|
const { data, isLoading, error, isFetching } = useGames({
|
||||||
|
page: currentPage,
|
||||||
|
limit: pageSize,
|
||||||
|
search
|
||||||
|
})
|
||||||
|
|
||||||
|
const { deleteGame } = useGamesMutation()
|
||||||
|
|
||||||
|
const games = data?.data ?? []
|
||||||
|
const totalCount = data?.total_count ?? 0
|
||||||
|
|
||||||
|
// Hooks
|
||||||
|
const { lang: locale } = useParams()
|
||||||
|
|
||||||
|
const handlePageChange = useCallback((event: unknown, newPage: number) => {
|
||||||
|
setCurrentPage(newPage)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const handlePageSizeChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const newPageSize = parseInt(event.target.value, 10)
|
||||||
|
setPageSize(newPageSize)
|
||||||
|
setCurrentPage(1) // Reset to first page
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const handleEditGame = (game: Game) => {
|
||||||
|
setEditGameData(game)
|
||||||
|
setAddGameOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDeleteGame = (game: Game) => {
|
||||||
|
setGameToDelete(game)
|
||||||
|
setDeleteDialogOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleConfirmDelete = () => {
|
||||||
|
if (gameToDelete) {
|
||||||
|
deleteGame.mutate(gameToDelete.id, {
|
||||||
|
onSuccess: () => {
|
||||||
|
console.log('Game deleted successfully')
|
||||||
|
setDeleteDialogOpen(false)
|
||||||
|
setGameToDelete(null)
|
||||||
|
// You might want to refetch data here
|
||||||
|
// refetch()
|
||||||
|
},
|
||||||
|
onError: error => {
|
||||||
|
console.error('Error deleting game:', error)
|
||||||
|
// Handle error (show toast, etc.)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCloseDeleteDialog = () => {
|
||||||
|
if (deleteGame.isPending) return // Prevent closing while deleting
|
||||||
|
setDeleteDialogOpen(false)
|
||||||
|
setGameToDelete(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleToggleActive = (gameId: string, currentStatus: boolean) => {
|
||||||
|
console.log('Toggling active status for game:', gameId, !currentStatus)
|
||||||
|
// Add your toggle logic here
|
||||||
|
// toggleGameStatus.mutate({ id: gameId, is_active: !currentStatus })
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCloseGameDrawer = () => {
|
||||||
|
setAddGameOpen(false)
|
||||||
|
setEditGameData(undefined)
|
||||||
|
}
|
||||||
|
|
||||||
|
const columns = useMemo<ColumnDef<GameWithAction, 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 Game',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<div className='flex items-center gap-4'>
|
||||||
|
<CustomAvatar src={row.original.metadata?.imageUrl} size={40}>
|
||||||
|
{getInitials(row.original.name)}
|
||||||
|
</CustomAvatar>
|
||||||
|
<div className='flex flex-col'>
|
||||||
|
<Link href={getLocalizedUrl(`/apps/games/${row.original.id}/detail`, locale as Locale)}>
|
||||||
|
<Typography className='font-medium cursor-pointer hover:underline text-primary'>
|
||||||
|
{row.original.name}
|
||||||
|
</Typography>
|
||||||
|
</Link>
|
||||||
|
<Typography variant='caption' color='textSecondary'>
|
||||||
|
{row.original.type}
|
||||||
|
</Typography>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('type', {
|
||||||
|
header: 'Tipe Game',
|
||||||
|
cell: ({ row }) => <Chip label={row.original.type} color='primary' variant='tonal' size='small' />
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('is_active', {
|
||||||
|
header: 'Status',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<Chip
|
||||||
|
label={row.original.is_active ? 'Aktif' : 'Nonaktif'}
|
||||||
|
color={row.original.is_active ? 'success' : 'error'}
|
||||||
|
variant='tonal'
|
||||||
|
size='small'
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('created_at', {
|
||||||
|
header: 'Tanggal Dibuat',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<Typography color='text.primary'>
|
||||||
|
{new Date(row.original.created_at).toLocaleDateString('id-ID', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric'
|
||||||
|
})}
|
||||||
|
</Typography>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
id: 'actions',
|
||||||
|
header: 'Aksi',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<div className='flex items-center'>
|
||||||
|
<OptionMenu
|
||||||
|
iconButtonProps={{ size: 'medium' }}
|
||||||
|
iconClassName='text-textSecondary text-[22px]'
|
||||||
|
options={[
|
||||||
|
{
|
||||||
|
text: 'Edit',
|
||||||
|
icon: 'tabler-edit text-[22px]',
|
||||||
|
menuItemProps: {
|
||||||
|
className: 'flex items-center gap-2 text-textSecondary',
|
||||||
|
onClick: () => handleEditGame(row.original)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
text: 'Hapus',
|
||||||
|
icon: 'tabler-trash text-[22px]',
|
||||||
|
menuItemProps: {
|
||||||
|
className: 'flex items-center gap-2 text-textSecondary',
|
||||||
|
onClick: () => handleDeleteGame(row.original)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
enableSorting: false
|
||||||
|
}
|
||||||
|
],
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
[locale, handleEditGame, handleDeleteGame, handleToggleActive]
|
||||||
|
)
|
||||||
|
|
||||||
|
const table = useReactTable({
|
||||||
|
data: games as Game[],
|
||||||
|
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 Game'
|
||||||
|
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={() => setAddGameOpen(!addGameOpen)}
|
||||||
|
className='max-sm:is-full'
|
||||||
|
>
|
||||||
|
Tambah Game
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className='overflow-x-auto'>
|
||||||
|
{isLoading ? (
|
||||||
|
<Loading />
|
||||||
|
) : (
|
||||||
|
<table className={tableStyles.table}>
|
||||||
|
<thead>
|
||||||
|
{table.getHeaderGroups().map(headerGroup => (
|
||||||
|
<tr key={headerGroup.id}>
|
||||||
|
{headerGroup.headers.map(header => (
|
||||||
|
<th key={header.id}>
|
||||||
|
{header.isPlaceholder ? null : (
|
||||||
|
<>
|
||||||
|
<div
|
||||||
|
className={classnames({
|
||||||
|
'flex items-center': header.column.getIsSorted(),
|
||||||
|
'cursor-pointer select-none': header.column.getCanSort()
|
||||||
|
})}
|
||||||
|
onClick={header.column.getToggleSortingHandler()}
|
||||||
|
>
|
||||||
|
{flexRender(header.column.columnDef.header, header.getContext())}
|
||||||
|
{{
|
||||||
|
asc: <i className='tabler-chevron-up text-xl' />,
|
||||||
|
desc: <i className='tabler-chevron-down text-xl' />
|
||||||
|
}[header.column.getIsSorted() as 'asc' | 'desc'] ?? null}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</th>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</thead>
|
||||||
|
{table.getFilteredRowModel().rows.length === 0 ? (
|
||||||
|
<tbody>
|
||||||
|
<tr>
|
||||||
|
<td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
|
||||||
|
Tidak ada data tersedia
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
) : (
|
||||||
|
<tbody>
|
||||||
|
{table
|
||||||
|
.getRowModel()
|
||||||
|
.rows.slice(0, table.getState().pagination.pageSize)
|
||||||
|
.map(row => {
|
||||||
|
return (
|
||||||
|
<tr key={row.id} className={classnames({ selected: row.getIsSelected() })}>
|
||||||
|
{row.getVisibleCells().map(cell => (
|
||||||
|
<td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</tbody>
|
||||||
|
)}
|
||||||
|
</table>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<TablePagination
|
||||||
|
component={() => (
|
||||||
|
<TablePaginationComponent
|
||||||
|
pageIndex={currentPage}
|
||||||
|
pageSize={pageSize}
|
||||||
|
totalCount={totalCount}
|
||||||
|
onPageChange={handlePageChange}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
count={totalCount}
|
||||||
|
rowsPerPage={pageSize}
|
||||||
|
page={currentPage}
|
||||||
|
onPageChange={handlePageChange}
|
||||||
|
onRowsPerPageChange={handlePageSizeChange}
|
||||||
|
rowsPerPageOptions={[10, 25, 50]}
|
||||||
|
disabled={isLoading}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Add/Edit Game Drawer */}
|
||||||
|
<AddEditGamesDrawer open={addGameOpen} handleClose={handleCloseGameDrawer} data={editGameData} />
|
||||||
|
|
||||||
|
{/* Delete Game Dialog */}
|
||||||
|
<DeleteGameDialog
|
||||||
|
open={deleteDialogOpen}
|
||||||
|
onClose={handleCloseDeleteDialog}
|
||||||
|
onConfirm={handleConfirmDelete}
|
||||||
|
game={gameToDelete}
|
||||||
|
isDeleting={deleteGame.isPending}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default GameListTable
|
||||||
17
src/views/apps/marketing/games/list/index.tsx
Normal file
17
src/views/apps/marketing/games/list/index.tsx
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
// MUI Imports
|
||||||
|
import Grid from '@mui/material/Grid2'
|
||||||
|
import GameListTable from './GameListTable'
|
||||||
|
|
||||||
|
// Type Imports
|
||||||
|
|
||||||
|
const GamesList = () => {
|
||||||
|
return (
|
||||||
|
<Grid container spacing={6}>
|
||||||
|
<Grid size={{ xs: 12 }}>
|
||||||
|
<GameListTable />
|
||||||
|
</Grid>
|
||||||
|
</Grid>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default GamesList
|
||||||
@ -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
|
||||||
758
src/views/apps/marketing/reward/AddEditRewardDrawer.tsx
Normal file
758
src/views/apps/marketing/reward/AddEditRewardDrawer.tsx
Normal file
@ -0,0 +1,758 @@
|
|||||||
|
// 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'
|
||||||
|
import TextField from '@mui/material/TextField'
|
||||||
|
import Accordion from '@mui/material/Accordion'
|
||||||
|
import AccordionSummary from '@mui/material/AccordionSummary'
|
||||||
|
import AccordionDetails from '@mui/material/AccordionDetails'
|
||||||
|
import List from '@mui/material/List'
|
||||||
|
import ListItem from '@mui/material/ListItem'
|
||||||
|
import ListItemText from '@mui/material/ListItemText'
|
||||||
|
import ListItemSecondaryAction from '@mui/material/ListItemSecondaryAction'
|
||||||
|
|
||||||
|
// Third-party Imports
|
||||||
|
import { useForm, Controller, useFieldArray } from 'react-hook-form'
|
||||||
|
|
||||||
|
// Component Imports
|
||||||
|
import CustomTextField from '@core/components/mui/TextField'
|
||||||
|
import MultipleImageUpload from '@/components/MultipleImageUpload' // Import the component
|
||||||
|
|
||||||
|
// Import the actual upload mutation
|
||||||
|
import { useFilesMutation } from '@/services/mutations/files'
|
||||||
|
import { useRewardsMutation } from '@/services/mutations/reward'
|
||||||
|
|
||||||
|
// Updated Types based on new API structure
|
||||||
|
export interface TermsAndConditions {
|
||||||
|
sections: TncSection[]
|
||||||
|
expiry_days: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TncSection {
|
||||||
|
title: string
|
||||||
|
rules: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RewardRequest {
|
||||||
|
name: string // required, 1–150 chars
|
||||||
|
reward_type: 'VOUCHER' | 'PHYSICAL' | 'DIGITAL' // enum
|
||||||
|
cost_points: number // min 1
|
||||||
|
stock?: number
|
||||||
|
max_per_customer: number // min 1
|
||||||
|
tnc?: TermsAndConditions
|
||||||
|
images?: string[] // Add images to request
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Reward {
|
||||||
|
id: string // uuid
|
||||||
|
name: string
|
||||||
|
reward_type: 'VOUCHER' | 'PHYSICAL' | 'DIGITAL'
|
||||||
|
cost_points: number
|
||||||
|
stock?: number
|
||||||
|
max_per_customer: number
|
||||||
|
tnc?: TermsAndConditions
|
||||||
|
metadata?: Record<string, any>
|
||||||
|
images?: string[]
|
||||||
|
created_at: string // ISO date-time
|
||||||
|
updated_at: string // ISO date-time
|
||||||
|
}
|
||||||
|
|
||||||
|
// Type for uploaded image in the component
|
||||||
|
type UploadedImage = {
|
||||||
|
id: string
|
||||||
|
url: string
|
||||||
|
name: string
|
||||||
|
size: number
|
||||||
|
}
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
open: boolean
|
||||||
|
handleClose: () => void
|
||||||
|
data?: Reward // Data reward untuk edit (jika ada)
|
||||||
|
}
|
||||||
|
|
||||||
|
type FormValidateType = {
|
||||||
|
name: string
|
||||||
|
reward_type: 'VOUCHER' | 'PHYSICAL' | 'DIGITAL'
|
||||||
|
cost_points: number
|
||||||
|
stock: number | ''
|
||||||
|
max_per_customer: number
|
||||||
|
hasUnlimitedStock: boolean
|
||||||
|
hasTnc: boolean
|
||||||
|
tnc_expiry_days: number
|
||||||
|
tnc_sections: TncSection[]
|
||||||
|
uploadedImages: UploadedImage[] // Changed from images array to uploaded images
|
||||||
|
metadata: Record<string, any>
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initial form data
|
||||||
|
const initialData: FormValidateType = {
|
||||||
|
name: '',
|
||||||
|
reward_type: 'VOUCHER',
|
||||||
|
cost_points: 100,
|
||||||
|
stock: '',
|
||||||
|
max_per_customer: 1,
|
||||||
|
hasUnlimitedStock: false,
|
||||||
|
hasTnc: false,
|
||||||
|
tnc_expiry_days: 30,
|
||||||
|
tnc_sections: [],
|
||||||
|
uploadedImages: [], // Initialize as empty array
|
||||||
|
metadata: {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reward types
|
||||||
|
const REWARD_TYPES = [
|
||||||
|
{ value: 'VOUCHER', label: 'Voucher' },
|
||||||
|
{ value: 'PHYSICAL', label: 'Barang Fisik' },
|
||||||
|
{ value: 'DIGITAL', label: 'Digital' }
|
||||||
|
] as const
|
||||||
|
|
||||||
|
const AddEditRewardDrawer = (props: Props) => {
|
||||||
|
// Props
|
||||||
|
const { open, handleClose, data } = props
|
||||||
|
|
||||||
|
// States
|
||||||
|
const [showMore, setShowMore] = useState(false)
|
||||||
|
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||||
|
const [uploadingFiles, setUploadingFiles] = useState<Set<string>>(new Set())
|
||||||
|
|
||||||
|
const { createReward, updateReward } = useRewardsMutation()
|
||||||
|
const { mutate: uploadFile, isPending: isFileUploading } = useFilesMutation().uploadFile
|
||||||
|
|
||||||
|
// 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
|
||||||
|
})
|
||||||
|
|
||||||
|
// Field arrays for dynamic sections
|
||||||
|
const {
|
||||||
|
fields: tncSectionFields,
|
||||||
|
append: appendTncSection,
|
||||||
|
remove: removeTncSection
|
||||||
|
} = useFieldArray({
|
||||||
|
control,
|
||||||
|
name: 'tnc_sections'
|
||||||
|
})
|
||||||
|
|
||||||
|
const watchedUploadedImages = watch('uploadedImages')
|
||||||
|
const watchedHasUnlimitedStock = watch('hasUnlimitedStock')
|
||||||
|
const watchedHasTnc = watch('hasTnc')
|
||||||
|
const watchedStock = watch('stock')
|
||||||
|
const watchedCostPoints = watch('cost_points')
|
||||||
|
|
||||||
|
// Effect to populate form when editing
|
||||||
|
useEffect(() => {
|
||||||
|
if (isEditMode && data) {
|
||||||
|
// Convert existing images to UploadedImage format
|
||||||
|
const existingImages: UploadedImage[] = (data.images || []).map((url, index) => ({
|
||||||
|
id: `existing_${index}`,
|
||||||
|
url: url,
|
||||||
|
name: `Image ${index + 1}`,
|
||||||
|
size: 0 // We don't have size info for existing images
|
||||||
|
}))
|
||||||
|
|
||||||
|
// Populate form with existing data
|
||||||
|
const formData: FormValidateType = {
|
||||||
|
name: data.name || '',
|
||||||
|
reward_type: data.reward_type || 'VOUCHER',
|
||||||
|
cost_points: data.cost_points || 100,
|
||||||
|
stock: data.stock ?? '',
|
||||||
|
max_per_customer: data.max_per_customer || 1,
|
||||||
|
hasUnlimitedStock: data.stock === undefined || data.stock === null,
|
||||||
|
hasTnc: Boolean(data.tnc),
|
||||||
|
tnc_expiry_days: data.tnc?.expiry_days || 30,
|
||||||
|
tnc_sections: data.tnc?.sections || [],
|
||||||
|
uploadedImages: existingImages,
|
||||||
|
metadata: data.metadata || {}
|
||||||
|
}
|
||||||
|
|
||||||
|
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])
|
||||||
|
|
||||||
|
// Handle unlimited stock toggle
|
||||||
|
useEffect(() => {
|
||||||
|
if (watchedHasUnlimitedStock) {
|
||||||
|
setValue('stock', '')
|
||||||
|
}
|
||||||
|
}, [watchedHasUnlimitedStock, setValue])
|
||||||
|
|
||||||
|
// Image upload handlers
|
||||||
|
const handleSingleUpload = async (file: File): Promise<string> => {
|
||||||
|
const fileId = `${file.name}-${Date.now()}`
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
// Add file to uploading set
|
||||||
|
setUploadingFiles(prev => new Set(prev).add(fileId))
|
||||||
|
|
||||||
|
const formData = new FormData()
|
||||||
|
formData.append('file', file)
|
||||||
|
formData.append('file_type', 'image')
|
||||||
|
formData.append('description', 'reward image upload')
|
||||||
|
|
||||||
|
uploadFile(formData, {
|
||||||
|
onSuccess: response => {
|
||||||
|
// Remove file from uploading set
|
||||||
|
setUploadingFiles(prev => {
|
||||||
|
const newSet = new Set(prev)
|
||||||
|
newSet.delete(fileId)
|
||||||
|
return newSet
|
||||||
|
})
|
||||||
|
resolve(response.file_url)
|
||||||
|
},
|
||||||
|
onError: error => {
|
||||||
|
// Remove file from uploading set
|
||||||
|
setUploadingFiles(prev => {
|
||||||
|
const newSet = new Set(prev)
|
||||||
|
newSet.delete(fileId)
|
||||||
|
return newSet
|
||||||
|
})
|
||||||
|
reject(error)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleMultipleUpload = async (files: File[]): Promise<string[]> => {
|
||||||
|
const uploadedUrls: string[] = []
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Sequential upload to avoid overwhelming the server
|
||||||
|
for (const file of files) {
|
||||||
|
const url = await handleSingleUpload(file)
|
||||||
|
uploadedUrls.push(url)
|
||||||
|
}
|
||||||
|
return uploadedUrls
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to upload images:', error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleImagesChange = (images: UploadedImage[]) => {
|
||||||
|
setValue('uploadedImages', images)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleImageRemove = (imageId: string) => {
|
||||||
|
const currentImages = watchedUploadedImages || []
|
||||||
|
const updatedImages = currentImages.filter(img => img.id !== imageId)
|
||||||
|
setValue('uploadedImages', updatedImages)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleFormSubmit = async (formData: FormValidateType) => {
|
||||||
|
try {
|
||||||
|
setIsSubmitting(true)
|
||||||
|
|
||||||
|
// Extract image URLs from uploaded images
|
||||||
|
const imageUrls = formData.uploadedImages.map(img => img.url)
|
||||||
|
|
||||||
|
// Create RewardRequest object
|
||||||
|
const rewardRequest: RewardRequest = {
|
||||||
|
name: formData.name,
|
||||||
|
reward_type: formData.reward_type,
|
||||||
|
cost_points: formData.cost_points,
|
||||||
|
stock: formData.hasUnlimitedStock ? undefined : (formData.stock as number) || undefined,
|
||||||
|
max_per_customer: formData.max_per_customer,
|
||||||
|
images: imageUrls.length > 0 ? imageUrls : undefined, // Include images in request
|
||||||
|
tnc:
|
||||||
|
formData.hasTnc && formData.tnc_sections.length > 0
|
||||||
|
? {
|
||||||
|
sections: formData.tnc_sections,
|
||||||
|
expiry_days: formData.tnc_expiry_days
|
||||||
|
}
|
||||||
|
: 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)
|
||||||
|
setUploadingFiles(new Set())
|
||||||
|
}
|
||||||
|
|
||||||
|
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`
|
||||||
|
}
|
||||||
|
|
||||||
|
const addTncSection = () => {
|
||||||
|
appendTncSection({ title: '', rules: [''] })
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if any files are currently uploading
|
||||||
|
const isAnyFileUploading = uploadingFiles.size > 0 || isFileUploading
|
||||||
|
|
||||||
|
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'>
|
||||||
|
{/* 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',
|
||||||
|
minLength: { value: 1, message: 'Nama reward minimal 1 karakter' },
|
||||||
|
maxLength: { value: 150, message: 'Nama reward maksimal 150 karakter' }
|
||||||
|
}}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
placeholder='Masukkan nama reward'
|
||||||
|
error={!!errors.name}
|
||||||
|
helperText={errors.name?.message || `${field.value.length}/150 karakter`}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tipe Reward */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Tipe Reward <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='reward_type'
|
||||||
|
control={control}
|
||||||
|
rules={{ required: 'Tipe reward wajib dipilih' }}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
select
|
||||||
|
fullWidth
|
||||||
|
error={!!errors.reward_type}
|
||||||
|
helperText={errors.reward_type?.message}
|
||||||
|
>
|
||||||
|
{REWARD_TYPES.map(type => (
|
||||||
|
<MenuItem key={type.value} value={type.value}>
|
||||||
|
{type.label}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</CustomTextField>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Cost Points */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Biaya Poin <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='cost_points'
|
||||||
|
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.cost_points}
|
||||||
|
helperText={errors.cost_points?.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>
|
||||||
|
|
||||||
|
{/* Max Per Customer */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Maksimal per Pelanggan <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='max_per_customer'
|
||||||
|
control={control}
|
||||||
|
rules={{
|
||||||
|
required: 'Maksimal per pelanggan wajib diisi',
|
||||||
|
min: {
|
||||||
|
value: 1,
|
||||||
|
message: 'Minimal 1 per pelanggan'
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
type='number'
|
||||||
|
placeholder='1'
|
||||||
|
error={!!errors.max_per_customer}
|
||||||
|
helperText={errors.max_per_customer?.message}
|
||||||
|
InputProps={{
|
||||||
|
startAdornment: <InputAdornment position='start'>Max</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>
|
||||||
|
|
||||||
|
{/* 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 && (
|
||||||
|
<>
|
||||||
|
{/* Multiple Image Upload Section */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-3'>
|
||||||
|
Gambar Reward
|
||||||
|
</Typography>
|
||||||
|
<MultipleImageUpload
|
||||||
|
title={null} // No title since we have our own
|
||||||
|
onUpload={handleMultipleUpload}
|
||||||
|
onSingleUpload={handleSingleUpload}
|
||||||
|
currentImages={watchedUploadedImages || []}
|
||||||
|
onImagesChange={handleImagesChange}
|
||||||
|
onImageRemove={handleImageRemove}
|
||||||
|
isUploading={isAnyFileUploading}
|
||||||
|
maxFiles={5}
|
||||||
|
maxFileSize={5 * 1024 * 1024} // 5MB
|
||||||
|
acceptedFileTypes={['image/jpeg', 'image/png', 'image/webp']}
|
||||||
|
showUrlOption={false}
|
||||||
|
uploadMode='individual'
|
||||||
|
uploadButtonText='Upload Gambar'
|
||||||
|
browseButtonText='Pilih Gambar'
|
||||||
|
dragDropText='Drag & drop gambar reward di sini'
|
||||||
|
replaceText='Drop gambar untuk menambah lebih banyak'
|
||||||
|
maxFilesText='Maksimal {max} gambar'
|
||||||
|
disabled={isSubmitting}
|
||||||
|
/>
|
||||||
|
<FormHelperText>Format yang didukung: JPG, PNG, WebP. Maksimal 5MB per file.</FormHelperText>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Terms & Conditions */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Syarat & Ketentuan
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='hasTnc'
|
||||||
|
control={control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormControlLabel
|
||||||
|
control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
|
||||||
|
label='Memiliki syarat & ketentuan'
|
||||||
|
className='mb-2'
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{watchedHasTnc && (
|
||||||
|
<>
|
||||||
|
<Controller
|
||||||
|
name='tnc_expiry_days'
|
||||||
|
control={control}
|
||||||
|
rules={{
|
||||||
|
required: watchedHasTnc ? 'Masa berlaku T&C wajib diisi' : false,
|
||||||
|
min: { value: 1, message: 'Minimal 1 hari' }
|
||||||
|
}}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
type='number'
|
||||||
|
label='Masa Berlaku T&C (hari)'
|
||||||
|
placeholder='30'
|
||||||
|
error={!!errors.tnc_expiry_days}
|
||||||
|
helperText={errors.tnc_expiry_days?.message}
|
||||||
|
className='mb-4'
|
||||||
|
onChange={e => field.onChange(Number(e.target.value))}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{tncSectionFields.map((section, sectionIndex) => (
|
||||||
|
<Accordion key={section.id} className='mb-2'>
|
||||||
|
<AccordionSummary expandIcon={<i className='tabler-chevron-down' />}>
|
||||||
|
<Typography>Bagian {sectionIndex + 1}</Typography>
|
||||||
|
</AccordionSummary>
|
||||||
|
<AccordionDetails>
|
||||||
|
<Controller
|
||||||
|
name={`tnc_sections.${sectionIndex}.title`}
|
||||||
|
control={control}
|
||||||
|
rules={{ required: 'Judul bagian wajib diisi' }}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
label='Judul Bagian'
|
||||||
|
placeholder='Judul bagian'
|
||||||
|
className='mb-2'
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Aturan:
|
||||||
|
</Typography>
|
||||||
|
{section.rules?.map((rule, ruleIndex) => (
|
||||||
|
<Controller
|
||||||
|
key={ruleIndex}
|
||||||
|
name={`tnc_sections.${sectionIndex}.rules.${ruleIndex}`}
|
||||||
|
control={control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
placeholder={`Aturan ${ruleIndex + 1}`}
|
||||||
|
className='mb-1'
|
||||||
|
multiline
|
||||||
|
rows={2}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<Box className='flex gap-2 mt-2'>
|
||||||
|
<Button
|
||||||
|
size='small'
|
||||||
|
onClick={() => {
|
||||||
|
const currentSection = watch(`tnc_sections.${sectionIndex}`)
|
||||||
|
setValue(`tnc_sections.${sectionIndex}.rules`, [...(currentSection.rules || []), ''])
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
+ Aturan
|
||||||
|
</Button>
|
||||||
|
<Button size='small' color='error' onClick={() => removeTncSection(sectionIndex)}>
|
||||||
|
Hapus Bagian
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
</AccordionDetails>
|
||||||
|
</Accordion>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant='outlined'
|
||||||
|
size='small'
|
||||||
|
onClick={addTncSection}
|
||||||
|
startIcon={<i className='tabler-plus' />}
|
||||||
|
className='mb-4'
|
||||||
|
>
|
||||||
|
Tambah Bagian T&C
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</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 || isAnyFileUploading}>
|
||||||
|
{isSubmitting ? (isEditMode ? 'Mengupdate...' : 'Menyimpan...') : isEditMode ? 'Update' : 'Simpan'}
|
||||||
|
</Button>
|
||||||
|
<Button variant='outlined' color='error' onClick={handleReset} disabled={isSubmitting || isAnyFileUploading}>
|
||||||
|
Batal
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
{isAnyFileUploading && (
|
||||||
|
<Typography variant='caption' color='textSecondary' className='mt-2'>
|
||||||
|
Sedang mengupload gambar... ({uploadingFiles.size} file)
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Drawer>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default AddEditRewardDrawer
|
||||||
164
src/views/apps/marketing/reward/DeleteRewardDialog.tsx
Normal file
164
src/views/apps/marketing/reward/DeleteRewardDialog.tsx
Normal file
@ -0,0 +1,164 @@
|
|||||||
|
// React Imports
|
||||||
|
import { useState } from 'react'
|
||||||
|
|
||||||
|
// MUI Imports
|
||||||
|
import Dialog from '@mui/material/Dialog'
|
||||||
|
import DialogTitle from '@mui/material/DialogTitle'
|
||||||
|
import DialogContent from '@mui/material/DialogContent'
|
||||||
|
import DialogActions from '@mui/material/DialogActions'
|
||||||
|
import DialogContentText from '@mui/material/DialogContentText'
|
||||||
|
import Button from '@mui/material/Button'
|
||||||
|
import Typography from '@mui/material/Typography'
|
||||||
|
import Box from '@mui/material/Box'
|
||||||
|
import Alert from '@mui/material/Alert'
|
||||||
|
import Chip from '@mui/material/Chip'
|
||||||
|
|
||||||
|
// Component Imports
|
||||||
|
import CustomAvatar from '@core/components/mui/Avatar'
|
||||||
|
|
||||||
|
// Utils
|
||||||
|
import { getInitials } from '@/utils/getInitials'
|
||||||
|
|
||||||
|
// Types
|
||||||
|
import { Reward } from '@/types/services/reward'
|
||||||
|
import type { ThemeColor } from '@core/types'
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
open: boolean
|
||||||
|
onClose: () => void
|
||||||
|
onConfirm: () => void
|
||||||
|
reward: Reward | null
|
||||||
|
isDeleting?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper function to get reward type color
|
||||||
|
const getRewardTypeColor = (type: string): ThemeColor => {
|
||||||
|
switch (type) {
|
||||||
|
case 'VOUCHER':
|
||||||
|
return 'info'
|
||||||
|
case 'PHYSICAL':
|
||||||
|
return 'success'
|
||||||
|
case 'DIGITAL':
|
||||||
|
return 'warning'
|
||||||
|
default:
|
||||||
|
return 'primary'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const DeleteRewardDialog = ({ open, onClose, onConfirm, reward, isDeleting = false }: Props) => {
|
||||||
|
if (!reward) return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog
|
||||||
|
open={open}
|
||||||
|
onClose={onClose}
|
||||||
|
maxWidth='sm'
|
||||||
|
fullWidth
|
||||||
|
aria-labelledby='delete-dialog-title'
|
||||||
|
aria-describedby='delete-dialog-description'
|
||||||
|
>
|
||||||
|
<DialogTitle id='delete-dialog-title'>
|
||||||
|
<Box display='flex' alignItems='center' gap={2}>
|
||||||
|
<i className='tabler-trash text-red-500 text-2xl' />
|
||||||
|
<Typography variant='h6'>Hapus Reward</Typography>
|
||||||
|
</Box>
|
||||||
|
</DialogTitle>
|
||||||
|
|
||||||
|
<DialogContent>
|
||||||
|
<DialogContentText id='delete-dialog-description' className='mb-4'>
|
||||||
|
Apakah Anda yakin ingin menghapus reward berikut?
|
||||||
|
</DialogContentText>
|
||||||
|
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
backgroundColor: 'grey.50',
|
||||||
|
p: 2,
|
||||||
|
borderRadius: 1,
|
||||||
|
border: '1px solid',
|
||||||
|
borderColor: 'grey.200',
|
||||||
|
mb: 2
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* Reward Info with Avatar */}
|
||||||
|
<Box display='flex' alignItems='center' gap={2} className='mb-3'>
|
||||||
|
<CustomAvatar src={reward.images?.[0]} size={50}>
|
||||||
|
{getInitials(reward.name)}
|
||||||
|
</CustomAvatar>
|
||||||
|
<Box>
|
||||||
|
<Typography variant='subtitle2' className='font-medium mb-1'>
|
||||||
|
{reward.name}
|
||||||
|
</Typography>
|
||||||
|
<Chip
|
||||||
|
label={reward.reward_type}
|
||||||
|
color={getRewardTypeColor(reward.reward_type)}
|
||||||
|
variant='tonal'
|
||||||
|
size='small'
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{/* Reward Details */}
|
||||||
|
<Box display='flex' flexDirection='column' gap={1}>
|
||||||
|
<Typography variant='body2' color='text.secondary'>
|
||||||
|
<strong>Biaya Poin:</strong> {new Intl.NumberFormat('id-ID').format(reward.cost_points)} poin
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
{reward.stock !== undefined && (
|
||||||
|
<Typography variant='body2' color='text.secondary'>
|
||||||
|
<strong>Stok:</strong>{' '}
|
||||||
|
{reward.stock === 0 ? 'Habis' : reward.stock === null ? 'Unlimited' : reward.stock}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Typography variant='body2' color='text.secondary'>
|
||||||
|
<strong>Maks per Customer:</strong> {reward.max_per_customer} item
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
{reward.tnc?.expiry_days && (
|
||||||
|
<Typography variant='body2' color='text.secondary'>
|
||||||
|
<strong>Berlaku Hingga:</strong> {reward.tnc.expiry_days} hari
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Typography variant='body2' color='text.secondary'>
|
||||||
|
<strong>Dibuat:</strong>{' '}
|
||||||
|
{new Date(reward.created_at).toLocaleDateString('id-ID', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'long',
|
||||||
|
day: 'numeric'
|
||||||
|
})}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Alert severity='warning' sx={{ mb: 2 }}>
|
||||||
|
<Typography variant='body2'>
|
||||||
|
<strong>Peringatan:</strong> Tindakan ini tidak dapat dibatalkan. Semua data yang terkait dengan reward ini
|
||||||
|
akan dihapus secara permanen.
|
||||||
|
</Typography>
|
||||||
|
</Alert>
|
||||||
|
|
||||||
|
<DialogContentText>
|
||||||
|
Pastikan tidak ada pengguna yang masih memiliki atau menukarkan reward ini sebelum menghapus.
|
||||||
|
</DialogContentText>
|
||||||
|
</DialogContent>
|
||||||
|
|
||||||
|
<DialogActions className='p-4'>
|
||||||
|
<Button onClick={onClose} variant='outlined' disabled={isDeleting}>
|
||||||
|
Batal
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={onConfirm}
|
||||||
|
color='error'
|
||||||
|
variant='contained'
|
||||||
|
disabled={isDeleting}
|
||||||
|
startIcon={isDeleting ? <i className='tabler-loader animate-spin' /> : <i className='tabler-trash' />}
|
||||||
|
>
|
||||||
|
{isDeleting ? 'Menghapus...' : 'Hapus'}
|
||||||
|
</Button>
|
||||||
|
</DialogActions>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default DeleteRewardDialog
|
||||||
505
src/views/apps/marketing/reward/RewardListTable.tsx
Normal file
505
src/views/apps/marketing/reward/RewardListTable.tsx
Normal file
@ -0,0 +1,505 @@
|
|||||||
|
'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'
|
||||||
|
import { Reward } from '@/types/services/reward'
|
||||||
|
import { useRewards } from '@/services/queries/reward'
|
||||||
|
import { useRewardsMutation } from '@/services/mutations/reward'
|
||||||
|
import DeleteRewardDialog from './DeleteRewardDialog'
|
||||||
|
|
||||||
|
declare module '@tanstack/table-core' {
|
||||||
|
interface FilterFns {
|
||||||
|
fuzzy: FilterFn<unknown>
|
||||||
|
}
|
||||||
|
interface FilterMeta {
|
||||||
|
itemRank: RankingInfo
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type RewardWithAction = Reward & {
|
||||||
|
action?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Styled Components
|
||||||
|
const Icon = styled('i')({})
|
||||||
|
|
||||||
|
const fuzzyFilter: FilterFn<any> = (row, columnId, value, addMeta) => {
|
||||||
|
// Rank the item
|
||||||
|
const itemRank = rankItem(row.getValue(columnId), value)
|
||||||
|
|
||||||
|
// Store the itemRank info
|
||||||
|
addMeta({
|
||||||
|
itemRank
|
||||||
|
})
|
||||||
|
|
||||||
|
// Return if the item should be filtered in/out
|
||||||
|
return itemRank.passed
|
||||||
|
}
|
||||||
|
|
||||||
|
const DebouncedInput = ({
|
||||||
|
value: initialValue,
|
||||||
|
onChange,
|
||||||
|
debounce = 500,
|
||||||
|
...props
|
||||||
|
}: {
|
||||||
|
value: string | number
|
||||||
|
onChange: (value: string | number) => void
|
||||||
|
debounce?: number
|
||||||
|
} & Omit<TextFieldProps, 'onChange'>) => {
|
||||||
|
// States
|
||||||
|
const [value, setValue] = useState(initialValue)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setValue(initialValue)
|
||||||
|
}, [initialValue])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const timeout = setTimeout(() => {
|
||||||
|
onChange(value)
|
||||||
|
}, debounce)
|
||||||
|
|
||||||
|
return () => clearTimeout(timeout)
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [value])
|
||||||
|
|
||||||
|
return <CustomTextField {...props} value={value} onChange={e => setValue(e.target.value)} />
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper function untuk format points - SAMA SEPERTI TIER TABLE
|
||||||
|
const formatPoints = (points: number) => {
|
||||||
|
return new Intl.NumberFormat('id-ID').format(points)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Column Definitions
|
||||||
|
const columnHelper = createColumnHelper<RewardWithAction>()
|
||||||
|
|
||||||
|
const RewardListTable = () => {
|
||||||
|
// States - PERSIS SAMA SEPERTI TIER TABLE
|
||||||
|
const [addRewardOpen, setAddRewardOpen] = useState(false)
|
||||||
|
const [editRewardData, setEditRewardData] = useState<Reward | undefined>(undefined)
|
||||||
|
const [rowSelection, setRowSelection] = useState({})
|
||||||
|
const [globalFilter, setGlobalFilter] = useState('')
|
||||||
|
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
|
||||||
|
const [rewardToDelete, setRewardToDelete] = useState<Reward | null>(null)
|
||||||
|
|
||||||
|
// FIX 1: PAGINATION SAMA SEPERTI TIER (1-based, bukan 0-based)
|
||||||
|
const [currentPage, setCurrentPage] = useState(1)
|
||||||
|
const [pageSize, setPageSize] = useState(10)
|
||||||
|
const [search, setSearch] = useState('')
|
||||||
|
|
||||||
|
const { deleteReward } = useRewardsMutation()
|
||||||
|
|
||||||
|
const { data, isLoading, error, isFetching } = useRewards({
|
||||||
|
page: currentPage, // SAMA SEPERTI TIER - langsung currentPage
|
||||||
|
limit: pageSize,
|
||||||
|
search
|
||||||
|
})
|
||||||
|
|
||||||
|
const rewards = data?.rewards ?? []
|
||||||
|
const totalCount = data?.total ?? 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: Reward) => {
|
||||||
|
setEditRewardData(reward)
|
||||||
|
setAddRewardOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDeleteReward = (reward: Reward) => {
|
||||||
|
setRewardToDelete(reward)
|
||||||
|
setDeleteDialogOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ADD NEW HANDLERS FOR DELETE DIALOG
|
||||||
|
const handleConfirmDelete = () => {
|
||||||
|
if (rewardToDelete) {
|
||||||
|
deleteReward.mutate(rewardToDelete.id, {
|
||||||
|
onSuccess: () => {
|
||||||
|
console.log('Reward deleted successfully')
|
||||||
|
setDeleteDialogOpen(false)
|
||||||
|
setRewardToDelete(null)
|
||||||
|
// You might want to refetch data here
|
||||||
|
// refetch()
|
||||||
|
},
|
||||||
|
onError: error => {
|
||||||
|
console.error('Error deleting reward:', error)
|
||||||
|
// Handle error (show toast, etc.)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCloseDeleteDialog = () => {
|
||||||
|
if (!deleteReward.isPending) {
|
||||||
|
setDeleteDialogOpen(false)
|
||||||
|
setRewardToDelete(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCloseRewardDrawer = () => {
|
||||||
|
setAddRewardOpen(false)
|
||||||
|
setEditRewardData(undefined)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper function to get reward type color
|
||||||
|
const getRewardTypeColor = (type: string): ThemeColor => {
|
||||||
|
switch (type) {
|
||||||
|
case 'VOUCHER':
|
||||||
|
return 'info'
|
||||||
|
case 'PHYSICAL':
|
||||||
|
return 'success'
|
||||||
|
case 'DIGITAL':
|
||||||
|
return 'warning'
|
||||||
|
default:
|
||||||
|
return 'primary'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const columns = useMemo<ColumnDef<RewardWithAction, 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.images?.[0]} 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>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('reward_type', {
|
||||||
|
header: 'Tipe Reward',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<Chip
|
||||||
|
label={row.original.reward_type}
|
||||||
|
color={getRewardTypeColor(row.original.reward_type)}
|
||||||
|
variant='tonal'
|
||||||
|
size='small'
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('cost_points', {
|
||||||
|
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'>
|
||||||
|
{/* FIX 2: GUNAKAN formatPoints YANG SAMA SEPERTI TIER */}
|
||||||
|
{formatPoints(row.original.cost_points)} 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('max_per_customer', {
|
||||||
|
header: 'Maks/Customer',
|
||||||
|
cell: ({ row }) => <Typography color='text.primary'>{row.original.max_per_customer} item</Typography>
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('tnc', {
|
||||||
|
header: 'Berlaku Hingga',
|
||||||
|
cell: ({ row }) => <Typography color='text.primary'>{row.original.tnc?.expiry_days} days</Typography>
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('created_at', {
|
||||||
|
header: 'Tanggal Dibuat',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<Typography color='text.primary'>
|
||||||
|
{/* FIX 3: FORMAT DATE YANG SAMA SEPERTI TIER */}
|
||||||
|
{new Date(row.original.created_at).toLocaleDateString('id-ID', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric'
|
||||||
|
})}
|
||||||
|
</Typography>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
id: 'actions',
|
||||||
|
header: 'Aksi',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<div className='flex items-center'>
|
||||||
|
<OptionMenu
|
||||||
|
iconButtonProps={{ size: 'medium' }}
|
||||||
|
iconClassName='text-textSecondary text-[22px]'
|
||||||
|
options={[
|
||||||
|
{
|
||||||
|
text: 'Edit',
|
||||||
|
icon: 'tabler-edit text-[22px]',
|
||||||
|
menuItemProps: {
|
||||||
|
className: 'flex items-center gap-2 text-textSecondary',
|
||||||
|
onClick: () => handleEditReward(row.original)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
text: 'Hapus',
|
||||||
|
icon: 'tabler-trash text-[22px]',
|
||||||
|
menuItemProps: {
|
||||||
|
className: 'flex items-center gap-2 text-textSecondary',
|
||||||
|
onClick: () => handleDeleteReward(row.original)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
enableSorting: false
|
||||||
|
}
|
||||||
|
],
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
[locale, handleEditReward, handleDeleteReward]
|
||||||
|
)
|
||||||
|
|
||||||
|
// FIX 4: TABLE CONFIG YANG SAMA PERSIS SEPERTI TIER
|
||||||
|
const table = useReactTable({
|
||||||
|
data: rewards as Reward[], // SAMA SEPERTI TIER
|
||||||
|
columns,
|
||||||
|
filterFns: {
|
||||||
|
fuzzy: fuzzyFilter
|
||||||
|
},
|
||||||
|
state: {
|
||||||
|
rowSelection,
|
||||||
|
globalFilter,
|
||||||
|
pagination: {
|
||||||
|
pageIndex: currentPage, // SAMA SEPERTI TIER - langsung currentPage
|
||||||
|
pageSize
|
||||||
|
}
|
||||||
|
},
|
||||||
|
enableRowSelection: true,
|
||||||
|
onRowSelectionChange: setRowSelection,
|
||||||
|
getCoreRowModel: getCoreRowModel(),
|
||||||
|
manualPagination: true, // SAMA SEPERTI TIER
|
||||||
|
pageCount: Math.ceil(totalCount / pageSize) // SAMA SEPERTI TIER
|
||||||
|
})
|
||||||
|
|
||||||
|
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} />
|
||||||
|
<DeleteRewardDialog
|
||||||
|
open={deleteDialogOpen}
|
||||||
|
onClose={handleCloseDeleteDialog}
|
||||||
|
onConfirm={handleConfirmDelete}
|
||||||
|
reward={rewardToDelete}
|
||||||
|
isDeleting={deleteReward?.isPending || false}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
507
src/views/apps/marketing/tier/AddTierDrawer.tsx
Normal file
507
src/views/apps/marketing/tier/AddTierDrawer.tsx
Normal file
@ -0,0 +1,507 @@
|
|||||||
|
// React Imports
|
||||||
|
import { useState, useEffect } from 'react'
|
||||||
|
|
||||||
|
// MUI Imports
|
||||||
|
import Button from '@mui/material/Button'
|
||||||
|
import Drawer from '@mui/material/Drawer'
|
||||||
|
import IconButton from '@mui/material/IconButton'
|
||||||
|
import MenuItem from '@mui/material/MenuItem'
|
||||||
|
import Typography from '@mui/material/Typography'
|
||||||
|
import Divider from '@mui/material/Divider'
|
||||||
|
import Grid from '@mui/material/Grid2'
|
||||||
|
import Box from '@mui/material/Box'
|
||||||
|
import Switch from '@mui/material/Switch'
|
||||||
|
import FormControlLabel from '@mui/material/FormControlLabel'
|
||||||
|
import Chip from '@mui/material/Chip'
|
||||||
|
import InputAdornment from '@mui/material/InputAdornment'
|
||||||
|
import Select from '@mui/material/Select'
|
||||||
|
import FormControl from '@mui/material/FormControl'
|
||||||
|
import InputLabel from '@mui/material/InputLabel'
|
||||||
|
|
||||||
|
// Third-party Imports
|
||||||
|
import { useForm, Controller } from 'react-hook-form'
|
||||||
|
|
||||||
|
// Component Imports
|
||||||
|
import CustomTextField from '@core/components/mui/TextField'
|
||||||
|
import { Tier, TierRequest } from '@/types/services/tier'
|
||||||
|
import { useTiersMutation } from '@/services/mutations/tier'
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
open: boolean
|
||||||
|
handleClose: () => void
|
||||||
|
data?: Tier // Data tier untuk edit (jika ada)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Static benefit keys with their configurations
|
||||||
|
const STATIC_BENEFIT_KEYS = {
|
||||||
|
birthday_bonus: {
|
||||||
|
label: 'Birthday Bonus',
|
||||||
|
type: 'boolean' as const,
|
||||||
|
description: 'Bonus ulang tahun khusus member'
|
||||||
|
},
|
||||||
|
exclusive_discounts: {
|
||||||
|
label: 'Exclusive Discounts',
|
||||||
|
type: 'boolean' as const,
|
||||||
|
description: 'Akses diskon eksklusif'
|
||||||
|
},
|
||||||
|
point_multiplier: {
|
||||||
|
label: 'Point Multiplier',
|
||||||
|
type: 'number' as const,
|
||||||
|
description: 'Pengali poin (contoh: 1.1 = +10%)',
|
||||||
|
suffix: 'x'
|
||||||
|
},
|
||||||
|
priority_support: {
|
||||||
|
label: 'Priority Support',
|
||||||
|
type: 'boolean' as const,
|
||||||
|
description: 'Dukungan pelanggan prioritas'
|
||||||
|
},
|
||||||
|
special_discount: {
|
||||||
|
label: 'Special Discount',
|
||||||
|
type: 'number' as const,
|
||||||
|
description: 'Diskon khusus dalam persen',
|
||||||
|
suffix: '%'
|
||||||
|
}
|
||||||
|
} as const
|
||||||
|
|
||||||
|
// Benefit item type
|
||||||
|
type BenefitItem = {
|
||||||
|
key: keyof typeof STATIC_BENEFIT_KEYS
|
||||||
|
value: any
|
||||||
|
type: 'boolean' | 'number' | 'string'
|
||||||
|
}
|
||||||
|
|
||||||
|
type FormValidateType = {
|
||||||
|
name: string
|
||||||
|
min_points: number
|
||||||
|
benefits: BenefitItem[]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initial form data
|
||||||
|
const initialData: FormValidateType = {
|
||||||
|
name: '',
|
||||||
|
min_points: 0,
|
||||||
|
benefits: []
|
||||||
|
}
|
||||||
|
|
||||||
|
const AddEditTierDrawer = (props: Props) => {
|
||||||
|
// Props
|
||||||
|
const { open, handleClose, data } = props
|
||||||
|
|
||||||
|
// States
|
||||||
|
const [showMore, setShowMore] = useState(false)
|
||||||
|
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||||
|
|
||||||
|
const { createTier, updateTier } = useTiersMutation()
|
||||||
|
|
||||||
|
// Determine if this is edit mode
|
||||||
|
const isEditMode = Boolean(data?.id)
|
||||||
|
|
||||||
|
// Hooks
|
||||||
|
const {
|
||||||
|
control,
|
||||||
|
reset: resetForm,
|
||||||
|
handleSubmit,
|
||||||
|
watch,
|
||||||
|
setValue,
|
||||||
|
formState: { errors }
|
||||||
|
} = useForm<FormValidateType>({
|
||||||
|
defaultValues: initialData
|
||||||
|
})
|
||||||
|
|
||||||
|
const watchedBenefits = watch('benefits')
|
||||||
|
|
||||||
|
// Helper function to convert benefits object to BenefitItem array
|
||||||
|
const convertBenefitsToArray = (benefits: Record<string, any>): BenefitItem[] => {
|
||||||
|
if (!benefits) return []
|
||||||
|
return Object.entries(benefits)
|
||||||
|
.filter(([key]) => key in STATIC_BENEFIT_KEYS)
|
||||||
|
.map(([key, value]) => ({
|
||||||
|
key: key as keyof typeof STATIC_BENEFIT_KEYS,
|
||||||
|
value,
|
||||||
|
type: STATIC_BENEFIT_KEYS[key as keyof typeof STATIC_BENEFIT_KEYS].type
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper function to convert BenefitItem array to benefits object
|
||||||
|
const convertBenefitsToObject = (benefits: BenefitItem[]): Record<string, any> => {
|
||||||
|
const benefitsObj: Record<string, any> = {}
|
||||||
|
benefits.forEach(benefit => {
|
||||||
|
let value = benefit.value
|
||||||
|
// Convert string values to appropriate types
|
||||||
|
if (benefit.type === 'boolean') {
|
||||||
|
value = value === true || value === 'true' || value === 'yes'
|
||||||
|
} else if (benefit.type === 'number') {
|
||||||
|
value = Number(value)
|
||||||
|
}
|
||||||
|
benefitsObj[benefit.key] = value
|
||||||
|
})
|
||||||
|
return benefitsObj
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper function to format benefit display
|
||||||
|
const formatBenefitDisplay = (item: BenefitItem): string => {
|
||||||
|
const config = STATIC_BENEFIT_KEYS[item.key]
|
||||||
|
|
||||||
|
if (item.type === 'boolean') {
|
||||||
|
return `${config.label}: ${item.value ? 'Ya' : 'Tidak'}`
|
||||||
|
} else if (item.type === 'number') {
|
||||||
|
const suffix = config.suffix || ''
|
||||||
|
return `${config.label}: ${item.value}${suffix}`
|
||||||
|
}
|
||||||
|
return `${config.label}: ${item.value}`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get available benefit keys (not already added)
|
||||||
|
const getAvailableBenefitKeys = () => {
|
||||||
|
const usedKeys = watchedBenefits?.map(b => b.key) || []
|
||||||
|
return Object.entries(STATIC_BENEFIT_KEYS)
|
||||||
|
.filter(([key]) => !usedKeys.includes(key as keyof typeof STATIC_BENEFIT_KEYS))
|
||||||
|
.map(([key, config]) => ({
|
||||||
|
key: key as keyof typeof STATIC_BENEFIT_KEYS,
|
||||||
|
...config
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Effect to populate form when editing
|
||||||
|
useEffect(() => {
|
||||||
|
if (isEditMode && data) {
|
||||||
|
// Convert benefits object to array for form handling
|
||||||
|
const benefitsArray = convertBenefitsToArray(data.benefits)
|
||||||
|
|
||||||
|
// Populate form with existing data
|
||||||
|
const formData: FormValidateType = {
|
||||||
|
name: data.name || '',
|
||||||
|
min_points: data.min_points || 0,
|
||||||
|
benefits: benefitsArray
|
||||||
|
}
|
||||||
|
|
||||||
|
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 handleFormSubmit = async (formData: FormValidateType) => {
|
||||||
|
try {
|
||||||
|
setIsSubmitting(true)
|
||||||
|
|
||||||
|
// Convert benefits array back to object format
|
||||||
|
const benefitsObj = convertBenefitsToObject(formData.benefits)
|
||||||
|
|
||||||
|
// Create TierRequest object
|
||||||
|
const tierRequest: TierRequest = {
|
||||||
|
name: formData.name,
|
||||||
|
min_points: formData.min_points,
|
||||||
|
benefits: benefitsObj
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Submitting tier data:', tierRequest)
|
||||||
|
|
||||||
|
if (isEditMode && data?.id) {
|
||||||
|
// Update existing tier
|
||||||
|
updateTier.mutate(
|
||||||
|
{ id: data.id, payload: tierRequest },
|
||||||
|
{
|
||||||
|
onSuccess: () => {
|
||||||
|
handleReset()
|
||||||
|
handleClose()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
// Create new tier
|
||||||
|
createTier.mutate(tierRequest, {
|
||||||
|
onSuccess: () => {
|
||||||
|
handleReset()
|
||||||
|
handleClose()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error submitting tier:', error)
|
||||||
|
// Handle error (show toast, etc.)
|
||||||
|
} finally {
|
||||||
|
setIsSubmitting(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleReset = () => {
|
||||||
|
handleClose()
|
||||||
|
resetForm(initialData)
|
||||||
|
setShowMore(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get placeholder and validation info based on selected benefit key
|
||||||
|
const getBenefitInputInfo = () => {
|
||||||
|
return { placeholder: 'Tidak diperlukan lagi', type: 'text' }
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatNumber = (value: number) => {
|
||||||
|
return new Intl.NumberFormat('id-ID').format(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Drawer
|
||||||
|
open={open}
|
||||||
|
anchor='right'
|
||||||
|
variant='temporary'
|
||||||
|
onClose={handleReset}
|
||||||
|
ModalProps={{ keepMounted: true }}
|
||||||
|
sx={{
|
||||||
|
'& .MuiDrawer-paper': {
|
||||||
|
width: { xs: 300, sm: 400 },
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
height: '100%'
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* Sticky Header */}
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
position: 'sticky',
|
||||||
|
top: 0,
|
||||||
|
zIndex: 10,
|
||||||
|
backgroundColor: 'background.paper',
|
||||||
|
borderBottom: 1,
|
||||||
|
borderColor: 'divider'
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className='flex items-center justify-between plb-5 pli-6'>
|
||||||
|
<Typography variant='h5'>{isEditMode ? 'Edit Tier' : 'Tambah Tier Baru'}</Typography>
|
||||||
|
<IconButton size='small' onClick={handleReset}>
|
||||||
|
<i className='tabler-x text-2xl text-textPrimary' />
|
||||||
|
</IconButton>
|
||||||
|
</div>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{/* Scrollable Content */}
|
||||||
|
<Box sx={{ flex: 1, overflowY: 'auto' }}>
|
||||||
|
<form id='tier-form' onSubmit={handleSubmit(handleFormSubmit)}>
|
||||||
|
<div className='flex flex-col gap-6 p-6'>
|
||||||
|
{/* Nama Tier */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Nama Tier <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='name'
|
||||||
|
control={control}
|
||||||
|
rules={{ required: 'Nama tier wajib diisi' }}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
placeholder='Masukkan nama tier (contoh: Bronze, Silver, Gold)'
|
||||||
|
error={!!errors.name}
|
||||||
|
helperText={errors.name?.message}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Minimum Points */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Minimum Poin <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='min_points'
|
||||||
|
control={control}
|
||||||
|
rules={{
|
||||||
|
required: 'Minimum poin wajib diisi',
|
||||||
|
min: {
|
||||||
|
value: 0,
|
||||||
|
message: 'Minimum poin tidak boleh negatif'
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
type='number'
|
||||||
|
placeholder='0'
|
||||||
|
error={!!errors.min_points}
|
||||||
|
helperText={
|
||||||
|
errors.min_points?.message || (field.value > 0 ? `${formatNumber(field.value)} poin` : '')
|
||||||
|
}
|
||||||
|
InputProps={{
|
||||||
|
endAdornment: <InputAdornment position='end'>poin</InputAdornment>
|
||||||
|
}}
|
||||||
|
onChange={e => field.onChange(Number(e.target.value))}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Benefits */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-3'>
|
||||||
|
Manfaat Tier <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
{/* All Benefits in Horizontal Layout */}
|
||||||
|
<div className='space-y-4'>
|
||||||
|
{Object.entries(STATIC_BENEFIT_KEYS).map(([key, config]) => {
|
||||||
|
const benefitKey = key as keyof typeof STATIC_BENEFIT_KEYS
|
||||||
|
const existingBenefit = watchedBenefits?.find(b => b.key === benefitKey)
|
||||||
|
const isActive = Boolean(existingBenefit)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div key={benefitKey} className='border rounded-lg p-3'>
|
||||||
|
<div className='flex items-center justify-between mb-2'>
|
||||||
|
<div className='flex-1'>
|
||||||
|
<Typography variant='body2' className='font-medium'>
|
||||||
|
{config.label}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant='caption' color='text.secondary'>
|
||||||
|
{config.description}
|
||||||
|
</Typography>
|
||||||
|
</div>
|
||||||
|
<FormControlLabel
|
||||||
|
control={
|
||||||
|
<Switch
|
||||||
|
checked={isActive}
|
||||||
|
onChange={e => {
|
||||||
|
if (e.target.checked) {
|
||||||
|
// Add default benefit
|
||||||
|
const defaultValue =
|
||||||
|
config.type === 'boolean'
|
||||||
|
? true
|
||||||
|
: config.type === 'number'
|
||||||
|
? benefitKey === 'point_multiplier'
|
||||||
|
? 1.1
|
||||||
|
: benefitKey === 'special_discount'
|
||||||
|
? 5
|
||||||
|
: 1
|
||||||
|
: ''
|
||||||
|
|
||||||
|
const newBenefit: BenefitItem = {
|
||||||
|
key: benefitKey,
|
||||||
|
value: defaultValue,
|
||||||
|
type: config.type
|
||||||
|
}
|
||||||
|
|
||||||
|
const currentBenefits = watchedBenefits || []
|
||||||
|
setValue('benefits', [...currentBenefits, newBenefit])
|
||||||
|
} else {
|
||||||
|
// Remove benefit
|
||||||
|
const currentBenefits = watchedBenefits || []
|
||||||
|
const newBenefits = currentBenefits.filter(b => b.key !== benefitKey)
|
||||||
|
setValue('benefits', newBenefits)
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
size='small'
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
label=''
|
||||||
|
sx={{ margin: 0 }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Value Input - Only show when active */}
|
||||||
|
{isActive && (
|
||||||
|
<div className='mt-2'>
|
||||||
|
{config.type === 'boolean' ? (
|
||||||
|
<FormControl size='small' fullWidth>
|
||||||
|
<Select
|
||||||
|
value={existingBenefit?.value ? 'true' : 'false'}
|
||||||
|
onChange={e => {
|
||||||
|
const currentBenefits = watchedBenefits || []
|
||||||
|
const updatedBenefits = currentBenefits.map(b =>
|
||||||
|
b.key === benefitKey ? { ...b, value: e.target.value === 'true' } : b
|
||||||
|
)
|
||||||
|
setValue('benefits', updatedBenefits)
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<MenuItem value='true'>Ya</MenuItem>
|
||||||
|
<MenuItem value='false'>Tidak</MenuItem>
|
||||||
|
</Select>
|
||||||
|
</FormControl>
|
||||||
|
) : (
|
||||||
|
<CustomTextField
|
||||||
|
fullWidth
|
||||||
|
size='small'
|
||||||
|
type='number'
|
||||||
|
value={existingBenefit?.value || ''}
|
||||||
|
onChange={e => {
|
||||||
|
const newValue = Number(e.target.value)
|
||||||
|
if (!isNaN(newValue)) {
|
||||||
|
const currentBenefits = watchedBenefits || []
|
||||||
|
const updatedBenefits = currentBenefits.map(b =>
|
||||||
|
b.key === benefitKey ? { ...b, value: newValue } : b
|
||||||
|
)
|
||||||
|
setValue('benefits', updatedBenefits)
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
placeholder={
|
||||||
|
benefitKey === 'point_multiplier'
|
||||||
|
? 'Contoh: 1.1, 1.5, 2.0'
|
||||||
|
: benefitKey === 'special_discount'
|
||||||
|
? 'Contoh: 5, 10, 15'
|
||||||
|
: 'Masukkan angka'
|
||||||
|
}
|
||||||
|
InputProps={{
|
||||||
|
endAdornment: config.suffix && (
|
||||||
|
<InputAdornment position='end'>{config.suffix}</InputAdornment>
|
||||||
|
),
|
||||||
|
inputProps: {
|
||||||
|
step: benefitKey === 'point_multiplier' ? '0.1' : '1',
|
||||||
|
min: benefitKey === 'point_multiplier' ? '0.1' : '0',
|
||||||
|
max: benefitKey === 'special_discount' ? '100' : undefined
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{(!watchedBenefits || watchedBenefits.length === 0) && (
|
||||||
|
<Typography variant='caption' color='error' className='mt-2 block'>
|
||||||
|
Minimal satu manfaat harus diaktifkan
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{/* Sticky Footer */}
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
position: 'sticky',
|
||||||
|
bottom: 0,
|
||||||
|
zIndex: 10,
|
||||||
|
backgroundColor: 'background.paper',
|
||||||
|
borderTop: 1,
|
||||||
|
borderColor: 'divider',
|
||||||
|
p: 3
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className='flex items-center gap-4'>
|
||||||
|
<Button
|
||||||
|
variant='contained'
|
||||||
|
type='submit'
|
||||||
|
form='tier-form'
|
||||||
|
disabled={isSubmitting || !watchedBenefits || watchedBenefits.length === 0}
|
||||||
|
startIcon={isSubmitting ? <i className='tabler-loader animate-spin' /> : null}
|
||||||
|
>
|
||||||
|
{isSubmitting ? (isEditMode ? 'Mengupdate...' : 'Menyimpan...') : isEditMode ? 'Update' : 'Simpan'}
|
||||||
|
</Button>
|
||||||
|
<Button variant='outlined' color='error' onClick={handleReset} disabled={isSubmitting}>
|
||||||
|
Batal
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</Box>
|
||||||
|
</Drawer>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default AddEditTierDrawer
|
||||||
106
src/views/apps/marketing/tier/DeleteTierDialog.tsx
Normal file
106
src/views/apps/marketing/tier/DeleteTierDialog.tsx
Normal file
@ -0,0 +1,106 @@
|
|||||||
|
// React Imports
|
||||||
|
import { useState } from 'react'
|
||||||
|
|
||||||
|
// MUI Imports
|
||||||
|
import Dialog from '@mui/material/Dialog'
|
||||||
|
import DialogTitle from '@mui/material/DialogTitle'
|
||||||
|
import DialogContent from '@mui/material/DialogContent'
|
||||||
|
import DialogActions from '@mui/material/DialogActions'
|
||||||
|
import DialogContentText from '@mui/material/DialogContentText'
|
||||||
|
import Button from '@mui/material/Button'
|
||||||
|
import Typography from '@mui/material/Typography'
|
||||||
|
import Box from '@mui/material/Box'
|
||||||
|
import Alert from '@mui/material/Alert'
|
||||||
|
|
||||||
|
// Types
|
||||||
|
import { Tier } from '@/types/services/tier'
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
open: boolean
|
||||||
|
onClose: () => void
|
||||||
|
onConfirm: () => void
|
||||||
|
tier: Tier | null
|
||||||
|
isDeleting?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
const DeleteTierDialog = ({ open, onClose, onConfirm, tier, isDeleting = false }: Props) => {
|
||||||
|
if (!tier) return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog
|
||||||
|
open={open}
|
||||||
|
onClose={onClose}
|
||||||
|
maxWidth='sm'
|
||||||
|
fullWidth
|
||||||
|
aria-labelledby='delete-dialog-title'
|
||||||
|
aria-describedby='delete-dialog-description'
|
||||||
|
>
|
||||||
|
<DialogTitle id='delete-dialog-title'>
|
||||||
|
<Box display='flex' alignItems='center' gap={2}>
|
||||||
|
<i className='tabler-trash text-red-500 text-2xl' />
|
||||||
|
<Typography variant='h6'>Hapus Tier</Typography>
|
||||||
|
</Box>
|
||||||
|
</DialogTitle>
|
||||||
|
|
||||||
|
<DialogContent>
|
||||||
|
<DialogContentText id='delete-dialog-description' className='mb-4'>
|
||||||
|
Apakah Anda yakin ingin menghapus tier berikut?
|
||||||
|
</DialogContentText>
|
||||||
|
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
backgroundColor: 'grey.50',
|
||||||
|
p: 2,
|
||||||
|
borderRadius: 1,
|
||||||
|
border: '1px solid',
|
||||||
|
borderColor: 'grey.200',
|
||||||
|
mb: 2
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Typography variant='subtitle2' className='font-medium mb-1'>
|
||||||
|
{tier.name}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant='body2' color='text.secondary' className='mb-1'>
|
||||||
|
Minimum Poin: {new Intl.NumberFormat('id-ID').format(tier.min_points)} poin
|
||||||
|
</Typography>
|
||||||
|
<Typography variant='body2' color='text.secondary'>
|
||||||
|
Dibuat:{' '}
|
||||||
|
{new Date(tier.created_at).toLocaleDateString('id-ID', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'long',
|
||||||
|
day: 'numeric'
|
||||||
|
})}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Alert severity='warning' sx={{ mb: 2 }}>
|
||||||
|
<Typography variant='body2'>
|
||||||
|
<strong>Peringatan:</strong> Tindakan ini tidak dapat dibatalkan. Semua data yang terkait dengan tier ini
|
||||||
|
akan dihapus secara permanen.
|
||||||
|
</Typography>
|
||||||
|
</Alert>
|
||||||
|
|
||||||
|
<DialogContentText>
|
||||||
|
Pastikan tidak ada pengguna yang masih menggunakan tier ini sebelum menghapus.
|
||||||
|
</DialogContentText>
|
||||||
|
</DialogContent>
|
||||||
|
|
||||||
|
<DialogActions className='p-4'>
|
||||||
|
<Button onClick={onClose} variant='outlined' disabled={isDeleting}>
|
||||||
|
Batal
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={onConfirm}
|
||||||
|
color='error'
|
||||||
|
variant='contained'
|
||||||
|
disabled={isDeleting}
|
||||||
|
startIcon={isDeleting ? <i className='tabler-loader animate-spin' /> : <i className='tabler-trash' />}
|
||||||
|
>
|
||||||
|
{isDeleting ? 'Menghapus...' : 'Hapus'}
|
||||||
|
</Button>
|
||||||
|
</DialogActions>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default DeleteTierDialog
|
||||||
549
src/views/apps/marketing/tier/TierListTable.tsx
Normal file
549
src/views/apps/marketing/tier/TierListTable.tsx
Normal file
@ -0,0 +1,549 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
// React Imports
|
||||||
|
import { useEffect, useState, useMemo, useCallback } from 'react'
|
||||||
|
|
||||||
|
// Next Imports
|
||||||
|
import Link from 'next/link'
|
||||||
|
import { useParams } from 'next/navigation'
|
||||||
|
|
||||||
|
// MUI Imports
|
||||||
|
import Card from '@mui/material/Card'
|
||||||
|
import CardHeader from '@mui/material/CardHeader'
|
||||||
|
import Button from '@mui/material/Button'
|
||||||
|
import Typography from '@mui/material/Typography'
|
||||||
|
import Chip from '@mui/material/Chip'
|
||||||
|
import Checkbox from '@mui/material/Checkbox'
|
||||||
|
import IconButton from '@mui/material/IconButton'
|
||||||
|
import { styled } from '@mui/material/styles'
|
||||||
|
import TablePagination from '@mui/material/TablePagination'
|
||||||
|
import type { TextFieldProps } from '@mui/material/TextField'
|
||||||
|
import MenuItem from '@mui/material/MenuItem'
|
||||||
|
|
||||||
|
// Third-party Imports
|
||||||
|
import classnames from 'classnames'
|
||||||
|
import { rankItem } from '@tanstack/match-sorter-utils'
|
||||||
|
import {
|
||||||
|
createColumnHelper,
|
||||||
|
flexRender,
|
||||||
|
getCoreRowModel,
|
||||||
|
useReactTable,
|
||||||
|
getFilteredRowModel,
|
||||||
|
getFacetedRowModel,
|
||||||
|
getFacetedUniqueValues,
|
||||||
|
getFacetedMinMaxValues,
|
||||||
|
getPaginationRowModel,
|
||||||
|
getSortedRowModel
|
||||||
|
} from '@tanstack/react-table'
|
||||||
|
import type { ColumnDef, FilterFn } from '@tanstack/react-table'
|
||||||
|
import type { RankingInfo } from '@tanstack/match-sorter-utils'
|
||||||
|
|
||||||
|
// Type Imports
|
||||||
|
import type { ThemeColor } from '@core/types'
|
||||||
|
import type { Locale } from '@configs/i18n'
|
||||||
|
|
||||||
|
// Component Imports
|
||||||
|
import OptionMenu from '@core/components/option-menu'
|
||||||
|
import TablePaginationComponent from '@components/TablePaginationComponent'
|
||||||
|
import CustomTextField from '@core/components/mui/TextField'
|
||||||
|
import CustomAvatar from '@core/components/mui/Avatar'
|
||||||
|
|
||||||
|
// Util Imports
|
||||||
|
import { getInitials } from '@/utils/getInitials'
|
||||||
|
import { getLocalizedUrl } from '@/utils/i18n'
|
||||||
|
import { formatCurrency } from '@/utils/transform'
|
||||||
|
|
||||||
|
// Style Imports
|
||||||
|
import tableStyles from '@core/styles/table.module.css'
|
||||||
|
import Loading from '@/components/layout/shared/Loading'
|
||||||
|
import AddEditTierDrawer from './AddTierDrawer'
|
||||||
|
import DeleteTierDialog from './DeleteTierDialog'
|
||||||
|
import { Tier } from '@/types/services/tier'
|
||||||
|
import { useTiers } from '@/services/queries/tier'
|
||||||
|
import { useTiersMutation } from '@/services/mutations/tier'
|
||||||
|
|
||||||
|
declare module '@tanstack/table-core' {
|
||||||
|
interface FilterFns {
|
||||||
|
fuzzy: FilterFn<unknown>
|
||||||
|
}
|
||||||
|
interface FilterMeta {
|
||||||
|
itemRank: RankingInfo
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type TierTypeWithAction = Tier & {
|
||||||
|
action?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Styled Components
|
||||||
|
const Icon = styled('i')({})
|
||||||
|
|
||||||
|
const fuzzyFilter: FilterFn<any> = (row, columnId, value, addMeta) => {
|
||||||
|
// Rank the item
|
||||||
|
const itemRank = rankItem(row.getValue(columnId), value)
|
||||||
|
|
||||||
|
// Store the itemRank info
|
||||||
|
addMeta({
|
||||||
|
itemRank
|
||||||
|
})
|
||||||
|
|
||||||
|
// Return if the item should be filtered in/out
|
||||||
|
return itemRank.passed
|
||||||
|
}
|
||||||
|
|
||||||
|
const DebouncedInput = ({
|
||||||
|
value: initialValue,
|
||||||
|
onChange,
|
||||||
|
debounce = 500,
|
||||||
|
...props
|
||||||
|
}: {
|
||||||
|
value: string | number
|
||||||
|
onChange: (value: string | number) => void
|
||||||
|
debounce?: number
|
||||||
|
} & Omit<TextFieldProps, 'onChange'>) => {
|
||||||
|
// States
|
||||||
|
const [value, setValue] = useState(initialValue)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setValue(initialValue)
|
||||||
|
}, [initialValue])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const timeout = setTimeout(() => {
|
||||||
|
onChange(value)
|
||||||
|
}, debounce)
|
||||||
|
|
||||||
|
return () => clearTimeout(timeout)
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [value])
|
||||||
|
|
||||||
|
return <CustomTextField {...props} value={value} onChange={e => setValue(e.target.value)} />
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper function to get all benefits as array
|
||||||
|
const getAllBenefits = (benefits: Record<string, any>): Array<{ key: string; value: any; display: string }> => {
|
||||||
|
return Object.entries(benefits).map(([key, value]) => ({
|
||||||
|
key,
|
||||||
|
value,
|
||||||
|
display: formatBenefitDisplay(key, value)
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatBenefitDisplay = (key: string, value: any): string => {
|
||||||
|
// Convert snake_case to readable format
|
||||||
|
const readableKey = key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())
|
||||||
|
|
||||||
|
if (value === true) {
|
||||||
|
return readableKey
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value === false) {
|
||||||
|
return `${readableKey} (Tidak Aktif)`
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof value === 'number') {
|
||||||
|
// Handle multipliers
|
||||||
|
if (key.includes('multiplier')) {
|
||||||
|
return `${readableKey} ${value}x`
|
||||||
|
}
|
||||||
|
// Handle percentages
|
||||||
|
if (key.includes('discount') || key.includes('bonus')) {
|
||||||
|
return `${readableKey} ${value}%`
|
||||||
|
}
|
||||||
|
// Default number formatting
|
||||||
|
return `${readableKey} ${value}`
|
||||||
|
}
|
||||||
|
|
||||||
|
return `${readableKey}: ${value}`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper function to format points
|
||||||
|
const formatPoints = (points: number) => {
|
||||||
|
return new Intl.NumberFormat('id-ID').format(points)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mock mutation hook for delete (replace with actual hook)
|
||||||
|
|
||||||
|
// Column Definitions
|
||||||
|
const columnHelper = createColumnHelper<TierTypeWithAction>()
|
||||||
|
|
||||||
|
const TierListTable = () => {
|
||||||
|
// States
|
||||||
|
const [addTierOpen, setAddTierOpen] = useState(false)
|
||||||
|
const [editTierData, setEditTierData] = useState<Tier | undefined>(undefined)
|
||||||
|
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
|
||||||
|
const [tierToDelete, setTierToDelete] = useState<Tier | null>(null)
|
||||||
|
const [rowSelection, setRowSelection] = useState({})
|
||||||
|
const [globalFilter, setGlobalFilter] = useState('')
|
||||||
|
const [currentPage, setCurrentPage] = useState(1)
|
||||||
|
const [pageSize, setPageSize] = useState(10)
|
||||||
|
const [search, setSearch] = useState('')
|
||||||
|
|
||||||
|
const { data, isLoading, error, isFetching } = useTiers({
|
||||||
|
page: currentPage,
|
||||||
|
limit: pageSize,
|
||||||
|
search
|
||||||
|
})
|
||||||
|
|
||||||
|
const { deleteTier } = useTiersMutation()
|
||||||
|
|
||||||
|
const tiers = data?.data ?? []
|
||||||
|
const totalCount = data?.total_count ?? 0
|
||||||
|
|
||||||
|
// Hooks
|
||||||
|
const { lang: locale } = useParams()
|
||||||
|
|
||||||
|
const handlePageChange = useCallback((event: unknown, newPage: number) => {
|
||||||
|
setCurrentPage(newPage)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const handlePageSizeChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const newPageSize = parseInt(event.target.value, 10)
|
||||||
|
setPageSize(newPageSize)
|
||||||
|
setCurrentPage(1) // Reset to first page
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const handleEditTier = (tier: Tier) => {
|
||||||
|
setEditTierData(tier)
|
||||||
|
setAddTierOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDeleteTier = (tier: Tier) => {
|
||||||
|
setTierToDelete(tier)
|
||||||
|
setDeleteDialogOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleConfirmDelete = () => {
|
||||||
|
if (tierToDelete) {
|
||||||
|
deleteTier.mutate(tierToDelete.id, {
|
||||||
|
onSuccess: () => {
|
||||||
|
console.log('Tier deleted successfully')
|
||||||
|
setDeleteDialogOpen(false)
|
||||||
|
setTierToDelete(null)
|
||||||
|
// You might want to refetch data here
|
||||||
|
// refetch()
|
||||||
|
},
|
||||||
|
onError: error => {
|
||||||
|
console.error('Error deleting tier:', error)
|
||||||
|
// Handle error (show toast, etc.)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCloseDeleteDialog = () => {
|
||||||
|
if (!deleteTier.isPending) {
|
||||||
|
setDeleteDialogOpen(false)
|
||||||
|
setTierToDelete(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCloseTierDrawer = () => {
|
||||||
|
setAddTierOpen(false)
|
||||||
|
setEditTierData(undefined)
|
||||||
|
}
|
||||||
|
|
||||||
|
const columns = useMemo<ColumnDef<TierTypeWithAction, any>[]>(
|
||||||
|
() => [
|
||||||
|
{
|
||||||
|
id: 'select',
|
||||||
|
header: ({ table }) => (
|
||||||
|
<Checkbox
|
||||||
|
{...{
|
||||||
|
checked: table.getIsAllRowsSelected(),
|
||||||
|
indeterminate: table.getIsSomeRowsSelected(),
|
||||||
|
onChange: table.getToggleAllRowsSelectedHandler()
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<Checkbox
|
||||||
|
{...{
|
||||||
|
checked: row.getIsSelected(),
|
||||||
|
disabled: !row.getCanSelect(),
|
||||||
|
indeterminate: row.getIsSomeSelected(),
|
||||||
|
onChange: row.getToggleSelectedHandler()
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
columnHelper.accessor('name', {
|
||||||
|
header: 'Nama Tier',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<div className='flex items-center gap-4'>
|
||||||
|
<div className='flex flex-col'>
|
||||||
|
<Link href={getLocalizedUrl(`/apps/tier/${row.original.id}/detail`, locale as Locale)}>
|
||||||
|
<Typography className='font-medium cursor-pointer hover:underline text-primary'>
|
||||||
|
{row.original.name}
|
||||||
|
</Typography>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('min_points', {
|
||||||
|
header: 'Minimum Poin',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<div className='flex items-center gap-2'>
|
||||||
|
<Icon className='tabler-star' sx={{ color: 'var(--mui-palette-warning-main)' }} />
|
||||||
|
<Typography color='text.primary'>{formatPoints(row.original.min_points)} poin</Typography>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('benefits', {
|
||||||
|
header: 'Manfaat',
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const allBenefits = getAllBenefits(row.original.benefits)
|
||||||
|
|
||||||
|
if (allBenefits.length === 0) {
|
||||||
|
return (
|
||||||
|
<Typography variant='body2' color='text.secondary'>
|
||||||
|
Tidak ada manfaat
|
||||||
|
</Typography>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className='flex flex-wrap gap-1 max-w-xs'>
|
||||||
|
{allBenefits.slice(0, 2).map((benefit, index) => {
|
||||||
|
// Different colors for different value types
|
||||||
|
let chipColor: 'default' | 'primary' | 'secondary' | 'error' | 'info' | 'success' | 'warning' =
|
||||||
|
'secondary'
|
||||||
|
|
||||||
|
if (benefit.value === false) {
|
||||||
|
chipColor = 'default'
|
||||||
|
} else if (benefit.value === true) {
|
||||||
|
chipColor = 'success'
|
||||||
|
} else if (typeof benefit.value === 'number') {
|
||||||
|
chipColor = 'info'
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Chip
|
||||||
|
key={benefit.key}
|
||||||
|
label={benefit.display}
|
||||||
|
size='small'
|
||||||
|
variant='outlined'
|
||||||
|
color={chipColor}
|
||||||
|
title={benefit.display} // Tooltip for full text
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
{allBenefits.length > 2 && (
|
||||||
|
<Chip
|
||||||
|
label={`+${allBenefits.length - 2} lainnya`}
|
||||||
|
size='small'
|
||||||
|
variant='outlined'
|
||||||
|
color='default'
|
||||||
|
title={allBenefits
|
||||||
|
.slice(2)
|
||||||
|
.map(b => b.display)
|
||||||
|
.join(', ')} // Show remaining benefits in tooltip
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('created_at', {
|
||||||
|
header: 'Tanggal Dibuat',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<Typography color='text.primary'>
|
||||||
|
{new Date(row.original.created_at).toLocaleDateString('id-ID', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric'
|
||||||
|
})}
|
||||||
|
</Typography>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
id: 'actions',
|
||||||
|
header: 'Aksi',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<div className='flex items-center'>
|
||||||
|
<OptionMenu
|
||||||
|
iconButtonProps={{ size: 'medium' }}
|
||||||
|
iconClassName='text-textSecondary text-[22px]'
|
||||||
|
options={[
|
||||||
|
{
|
||||||
|
text: 'Edit',
|
||||||
|
icon: 'tabler-edit text-[22px]',
|
||||||
|
menuItemProps: {
|
||||||
|
className: 'flex items-center gap-2 text-textSecondary',
|
||||||
|
onClick: () => handleEditTier(row.original)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
text: 'Hapus',
|
||||||
|
icon: 'tabler-trash text-[22px]',
|
||||||
|
menuItemProps: {
|
||||||
|
className: 'flex items-center gap-2 text-textSecondary',
|
||||||
|
onClick: () => handleDeleteTier(row.original)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
enableSorting: false
|
||||||
|
}
|
||||||
|
],
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
[locale, handleEditTier, handleDeleteTier]
|
||||||
|
)
|
||||||
|
|
||||||
|
const table = useReactTable({
|
||||||
|
data: tiers as Tier[],
|
||||||
|
columns,
|
||||||
|
filterFns: {
|
||||||
|
fuzzy: fuzzyFilter
|
||||||
|
},
|
||||||
|
state: {
|
||||||
|
rowSelection,
|
||||||
|
globalFilter,
|
||||||
|
pagination: {
|
||||||
|
pageIndex: currentPage,
|
||||||
|
pageSize
|
||||||
|
}
|
||||||
|
},
|
||||||
|
enableRowSelection: true,
|
||||||
|
onRowSelectionChange: setRowSelection,
|
||||||
|
getCoreRowModel: getCoreRowModel(),
|
||||||
|
manualPagination: true,
|
||||||
|
pageCount: Math.ceil(totalCount / pageSize)
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Card>
|
||||||
|
<div className='flex justify-between flex-col items-start md:flex-row md:items-center p-6 border-bs gap-4'>
|
||||||
|
<CustomTextField
|
||||||
|
select
|
||||||
|
value={table.getState().pagination.pageSize}
|
||||||
|
onChange={e => table.setPageSize(Number(e.target.value))}
|
||||||
|
className='max-sm:is-full sm:is-[70px]'
|
||||||
|
>
|
||||||
|
<MenuItem value='10'>10</MenuItem>
|
||||||
|
<MenuItem value='25'>25</MenuItem>
|
||||||
|
<MenuItem value='50'>50</MenuItem>
|
||||||
|
</CustomTextField>
|
||||||
|
<div className='flex flex-col sm:flex-row max-sm:is-full items-start sm:items-center gap-4'>
|
||||||
|
<DebouncedInput
|
||||||
|
value={search ?? ''}
|
||||||
|
onChange={value => setSearch(value as string)}
|
||||||
|
placeholder='Cari Tier'
|
||||||
|
className='max-sm:is-full'
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
color='secondary'
|
||||||
|
variant='tonal'
|
||||||
|
startIcon={<i className='tabler-upload' />}
|
||||||
|
className='max-sm:is-full'
|
||||||
|
>
|
||||||
|
Ekspor
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant='contained'
|
||||||
|
startIcon={<i className='tabler-plus' />}
|
||||||
|
onClick={() => setAddTierOpen(!addTierOpen)}
|
||||||
|
className='max-sm:is-full'
|
||||||
|
>
|
||||||
|
Tambah Tier
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className='overflow-x-auto'>
|
||||||
|
{isLoading ? (
|
||||||
|
<Loading />
|
||||||
|
) : (
|
||||||
|
<table className={tableStyles.table}>
|
||||||
|
<thead>
|
||||||
|
{table.getHeaderGroups().map(headerGroup => (
|
||||||
|
<tr key={headerGroup.id}>
|
||||||
|
{headerGroup.headers.map(header => (
|
||||||
|
<th key={header.id}>
|
||||||
|
{header.isPlaceholder ? null : (
|
||||||
|
<>
|
||||||
|
<div
|
||||||
|
className={classnames({
|
||||||
|
'flex items-center': header.column.getIsSorted(),
|
||||||
|
'cursor-pointer select-none': header.column.getCanSort()
|
||||||
|
})}
|
||||||
|
onClick={header.column.getToggleSortingHandler()}
|
||||||
|
>
|
||||||
|
{flexRender(header.column.columnDef.header, header.getContext())}
|
||||||
|
{{
|
||||||
|
asc: <i className='tabler-chevron-up text-xl' />,
|
||||||
|
desc: <i className='tabler-chevron-down text-xl' />
|
||||||
|
}[header.column.getIsSorted() as 'asc' | 'desc'] ?? null}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</th>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</thead>
|
||||||
|
{table.getFilteredRowModel().rows.length === 0 ? (
|
||||||
|
<tbody>
|
||||||
|
<tr>
|
||||||
|
<td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
|
||||||
|
Tidak ada data tersedia
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
) : (
|
||||||
|
<tbody>
|
||||||
|
{table
|
||||||
|
.getRowModel()
|
||||||
|
.rows.slice(0, table.getState().pagination.pageSize)
|
||||||
|
.map(row => {
|
||||||
|
return (
|
||||||
|
<tr key={row.id} className={classnames({ selected: row.getIsSelected() })}>
|
||||||
|
{row.getVisibleCells().map(cell => (
|
||||||
|
<td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</tbody>
|
||||||
|
)}
|
||||||
|
</table>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<TablePagination
|
||||||
|
component={() => (
|
||||||
|
<TablePaginationComponent
|
||||||
|
pageIndex={currentPage}
|
||||||
|
pageSize={pageSize}
|
||||||
|
totalCount={totalCount}
|
||||||
|
onPageChange={handlePageChange}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
count={totalCount}
|
||||||
|
rowsPerPage={pageSize}
|
||||||
|
page={currentPage}
|
||||||
|
onPageChange={handlePageChange}
|
||||||
|
onRowsPerPageChange={handlePageSizeChange}
|
||||||
|
rowsPerPageOptions={[10, 25, 50]}
|
||||||
|
disabled={isLoading}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Add/Edit Tier Drawer */}
|
||||||
|
<AddEditTierDrawer open={addTierOpen} handleClose={handleCloseTierDrawer} data={editTierData} />
|
||||||
|
|
||||||
|
{/* Delete Confirmation Dialog */}
|
||||||
|
<DeleteTierDialog
|
||||||
|
open={deleteDialogOpen}
|
||||||
|
onClose={handleCloseDeleteDialog}
|
||||||
|
onConfirm={handleConfirmDelete}
|
||||||
|
tier={tierToDelete}
|
||||||
|
isDeleting={deleteTier.isPending}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default TierListTable
|
||||||
17
src/views/apps/marketing/tier/index.tsx
Normal file
17
src/views/apps/marketing/tier/index.tsx
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
// MUI Imports
|
||||||
|
import Grid from '@mui/material/Grid2'
|
||||||
|
import TierListTable from './TierListTable'
|
||||||
|
|
||||||
|
// Type Imports
|
||||||
|
|
||||||
|
const TierList = () => {
|
||||||
|
return (
|
||||||
|
<Grid container spacing={6}>
|
||||||
|
<Grid size={{ xs: 12 }}>
|
||||||
|
<TierListTable />
|
||||||
|
</Grid>
|
||||||
|
</Grid>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default TierList
|
||||||
896
src/views/apps/marketing/voucher/AddEditVoucherDrawer.tsx
Normal file
896
src/views/apps/marketing/voucher/AddEditVoucherDrawer.tsx
Normal file
@ -0,0 +1,896 @@
|
|||||||
|
// 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 - Updated to match the integrated voucher structure
|
||||||
|
export interface VoucherCatalogType {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
description?: string
|
||||||
|
pointCost: number
|
||||||
|
stock?: number
|
||||||
|
isActive: boolean
|
||||||
|
validUntil?: Date
|
||||||
|
imageUrl?: string
|
||||||
|
createdAt: Date
|
||||||
|
updatedAt: Date
|
||||||
|
// Voucher-specific fields
|
||||||
|
code: string
|
||||||
|
type: 'discount' | 'cashback' | 'free_shipping' | 'product'
|
||||||
|
discountType?: 'fixed' | 'percent'
|
||||||
|
discountValue?: number
|
||||||
|
minPurchase?: number
|
||||||
|
validFrom: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VoucherRequest {
|
||||||
|
name: string
|
||||||
|
description?: string
|
||||||
|
pointCost: number
|
||||||
|
stock?: number
|
||||||
|
isActive: boolean
|
||||||
|
validUntil?: Date
|
||||||
|
imageUrl?: string
|
||||||
|
code: string
|
||||||
|
type: 'discount' | 'cashback' | 'free_shipping' | 'product'
|
||||||
|
discountType?: 'fixed' | 'percent'
|
||||||
|
discountValue?: number
|
||||||
|
minPurchase?: number
|
||||||
|
validFrom: string
|
||||||
|
terms?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
open: boolean
|
||||||
|
handleClose: () => void
|
||||||
|
data?: VoucherCatalogType // Data voucher untuk edit (jika ada)
|
||||||
|
}
|
||||||
|
|
||||||
|
type FormValidateType = {
|
||||||
|
name: string
|
||||||
|
description: string
|
||||||
|
pointCost: number
|
||||||
|
stock: number | ''
|
||||||
|
isActive: boolean
|
||||||
|
validUntil: string
|
||||||
|
imageUrl: string
|
||||||
|
code: string
|
||||||
|
type: 'discount' | 'cashback' | 'free_shipping' | 'product'
|
||||||
|
discountType: 'fixed' | 'percent'
|
||||||
|
discountValue: number | ''
|
||||||
|
minPurchase: number | ''
|
||||||
|
validFrom: string
|
||||||
|
terms: string
|
||||||
|
hasUnlimitedStock: boolean
|
||||||
|
hasValidUntil: boolean
|
||||||
|
hasMinPurchase: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initial form data
|
||||||
|
const initialData: FormValidateType = {
|
||||||
|
name: '',
|
||||||
|
description: '',
|
||||||
|
pointCost: 100,
|
||||||
|
stock: '',
|
||||||
|
isActive: true,
|
||||||
|
validUntil: '',
|
||||||
|
imageUrl: '',
|
||||||
|
code: '',
|
||||||
|
type: 'discount',
|
||||||
|
discountType: 'fixed',
|
||||||
|
discountValue: '',
|
||||||
|
minPurchase: '',
|
||||||
|
validFrom: new Date().toISOString().split('T')[0],
|
||||||
|
terms: '',
|
||||||
|
hasUnlimitedStock: false,
|
||||||
|
hasValidUntil: false,
|
||||||
|
hasMinPurchase: false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mock mutation hooks (replace with actual hooks)
|
||||||
|
const useVoucherMutation = () => {
|
||||||
|
const createVoucher = {
|
||||||
|
mutate: (data: VoucherRequest, options?: { onSuccess?: () => void }) => {
|
||||||
|
console.log('Creating voucher:', data)
|
||||||
|
setTimeout(() => options?.onSuccess?.(), 1000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateVoucher = {
|
||||||
|
mutate: (data: { id: string; payload: VoucherRequest }, options?: { onSuccess?: () => void }) => {
|
||||||
|
console.log('Updating voucher:', data)
|
||||||
|
setTimeout(() => options?.onSuccess?.(), 1000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { createVoucher, updateVoucher }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Voucher types
|
||||||
|
const VOUCHER_TYPES = [
|
||||||
|
{ value: 'discount', label: 'Diskon', icon: 'tabler-percentage' },
|
||||||
|
{ value: 'cashback', label: 'Cashback', icon: 'tabler-cash' },
|
||||||
|
{ value: 'free_shipping', label: 'Gratis Ongkir', icon: 'tabler-truck-delivery' },
|
||||||
|
{ value: 'product', label: 'Produk Fisik', icon: 'tabler-package' }
|
||||||
|
]
|
||||||
|
|
||||||
|
// Discount types
|
||||||
|
const DISCOUNT_TYPES = [
|
||||||
|
{ value: 'fixed', label: 'Nilai Tetap (Rp)' },
|
||||||
|
{ value: 'percent', label: 'Persentase (%)' }
|
||||||
|
]
|
||||||
|
|
||||||
|
const AddEditVoucherDrawer = (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 { createVoucher, updateVoucher } = useVoucherMutation()
|
||||||
|
|
||||||
|
// 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 watchedHasMinPurchase = watch('hasMinPurchase')
|
||||||
|
const watchedStock = watch('stock')
|
||||||
|
const watchedPointCost = watch('pointCost')
|
||||||
|
const watchedType = watch('type')
|
||||||
|
const watchedDiscountType = watch('discountType')
|
||||||
|
const watchedDiscountValue = watch('discountValue')
|
||||||
|
|
||||||
|
// 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 || '',
|
||||||
|
code: data.code || '',
|
||||||
|
type: data.type || 'discount',
|
||||||
|
discountType: data.discountType || 'fixed',
|
||||||
|
discountValue: data.discountValue ?? '',
|
||||||
|
minPurchase: data.minPurchase ?? '',
|
||||||
|
validFrom: data.validFrom
|
||||||
|
? new Date(data.validFrom).toISOString().split('T')[0]
|
||||||
|
: new Date().toISOString().split('T')[0],
|
||||||
|
terms: '',
|
||||||
|
hasUnlimitedStock: data.stock === undefined || data.stock === null,
|
||||||
|
hasValidUntil: Boolean(data.validUntil),
|
||||||
|
hasMinPurchase: Boolean(data.minPurchase)
|
||||||
|
}
|
||||||
|
|
||||||
|
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])
|
||||||
|
|
||||||
|
// Handle minimum purchase toggle
|
||||||
|
useEffect(() => {
|
||||||
|
if (!watchedHasMinPurchase) {
|
||||||
|
setValue('minPurchase', '')
|
||||||
|
}
|
||||||
|
}, [watchedHasMinPurchase, setValue])
|
||||||
|
|
||||||
|
// Auto-generate voucher code
|
||||||
|
const generateVoucherCode = () => {
|
||||||
|
const prefix = watchedType.toUpperCase()
|
||||||
|
const randomSuffix = Math.random().toString(36).substring(2, 8).toUpperCase()
|
||||||
|
return `${prefix}_${randomSuffix}`
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleFormSubmit = async (formData: FormValidateType) => {
|
||||||
|
try {
|
||||||
|
setIsSubmitting(true)
|
||||||
|
|
||||||
|
// Create VoucherRequest object
|
||||||
|
const voucherRequest: VoucherRequest = {
|
||||||
|
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,
|
||||||
|
code: formData.code,
|
||||||
|
type: formData.type,
|
||||||
|
discountType: ['discount', 'cashback'].includes(formData.type) ? formData.discountType : undefined,
|
||||||
|
discountValue:
|
||||||
|
['discount', 'cashback'].includes(formData.type) && formData.discountValue
|
||||||
|
? Number(formData.discountValue)
|
||||||
|
: undefined,
|
||||||
|
minPurchase: formData.hasMinPurchase && formData.minPurchase ? Number(formData.minPurchase) : undefined,
|
||||||
|
validFrom: formData.validFrom,
|
||||||
|
terms: formData.terms || undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isEditMode && data?.id) {
|
||||||
|
// Update existing voucher
|
||||||
|
updateVoucher.mutate(
|
||||||
|
{ id: data.id, payload: voucherRequest },
|
||||||
|
{
|
||||||
|
onSuccess: () => {
|
||||||
|
handleReset()
|
||||||
|
handleClose()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
// Create new voucher
|
||||||
|
createVoucher.mutate(voucherRequest, {
|
||||||
|
onSuccess: () => {
|
||||||
|
handleReset()
|
||||||
|
handleClose()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error submitting voucher:', 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 formatCurrency = (value: number) => {
|
||||||
|
return new Intl.NumberFormat('id-ID', {
|
||||||
|
style: 'currency',
|
||||||
|
currency: 'IDR'
|
||||||
|
}).format(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
const getStockDisplay = () => {
|
||||||
|
if (watchedHasUnlimitedStock) return 'Unlimited'
|
||||||
|
if (watchedStock === '' || watchedStock === 0) return 'Tidak ada stok'
|
||||||
|
return `${watchedStock} item`
|
||||||
|
}
|
||||||
|
|
||||||
|
const getDiscountValueDisplay = () => {
|
||||||
|
if (!watchedDiscountValue) return ''
|
||||||
|
if (watchedDiscountType === 'percent') {
|
||||||
|
return `${watchedDiscountValue}%`
|
||||||
|
} else {
|
||||||
|
return formatCurrency(Number(watchedDiscountValue))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const shouldShowDiscountFields = ['discount', 'cashback'].includes(watchedType)
|
||||||
|
|
||||||
|
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 Voucher' : 'Tambah Voucher 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='voucher-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-ticket text-2xl' />
|
||||||
|
</Avatar>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Nama Voucher */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Nama Voucher <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='name'
|
||||||
|
control={control}
|
||||||
|
rules={{ required: 'Nama voucher wajib diisi' }}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
placeholder='Masukkan nama voucher'
|
||||||
|
error={!!errors.name}
|
||||||
|
helperText={errors.name?.message}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tipe Voucher */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Tipe Voucher <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='type'
|
||||||
|
control={control}
|
||||||
|
rules={{ required: 'Tipe voucher wajib dipilih' }}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField {...field} select fullWidth error={!!errors.type} helperText={errors.type?.message}>
|
||||||
|
{VOUCHER_TYPES.map(type => (
|
||||||
|
<MenuItem key={type.value} value={type.value}>
|
||||||
|
<div className='flex items-center gap-2'>
|
||||||
|
<i className={type.icon} />
|
||||||
|
{type.label}
|
||||||
|
</div>
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</CustomTextField>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Kode Voucher */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Kode Voucher <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='code'
|
||||||
|
control={control}
|
||||||
|
rules={{
|
||||||
|
required: 'Kode voucher wajib diisi',
|
||||||
|
pattern: {
|
||||||
|
value: /^[A-Z0-9_-]+$/,
|
||||||
|
message: 'Kode voucher hanya boleh menggunakan huruf besar, angka, underscore, dan strip'
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
placeholder='DISC50K'
|
||||||
|
error={!!errors.code}
|
||||||
|
helperText={errors.code?.message || 'Gunakan huruf besar, angka, _, dan - saja'}
|
||||||
|
InputProps={{
|
||||||
|
endAdornment: (
|
||||||
|
<InputAdornment position='end'>
|
||||||
|
<Button
|
||||||
|
variant='text'
|
||||||
|
size='small'
|
||||||
|
onClick={() => setValue('code', generateVoucherCode())}
|
||||||
|
sx={{ minWidth: 'auto', p: 1 }}
|
||||||
|
>
|
||||||
|
<i className='tabler-refresh text-lg' />
|
||||||
|
</Button>
|
||||||
|
</InputAdornment>
|
||||||
|
)
|
||||||
|
}}
|
||||||
|
onChange={e => field.onChange(e.target.value.toUpperCase())}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Discount Fields - Only show for discount and cashback */}
|
||||||
|
{shouldShowDiscountFields && (
|
||||||
|
<>
|
||||||
|
{/* Tipe Diskon */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Tipe Diskon <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='discountType'
|
||||||
|
control={control}
|
||||||
|
rules={{ required: shouldShowDiscountFields ? 'Tipe diskon wajib dipilih' : false }}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
select
|
||||||
|
fullWidth
|
||||||
|
error={!!errors.discountType}
|
||||||
|
helperText={errors.discountType?.message}
|
||||||
|
>
|
||||||
|
{DISCOUNT_TYPES.map(type => (
|
||||||
|
<MenuItem key={type.value} value={type.value}>
|
||||||
|
{type.label}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</CustomTextField>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Nilai Diskon */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Nilai Diskon <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='discountValue'
|
||||||
|
control={control}
|
||||||
|
rules={{
|
||||||
|
required: shouldShowDiscountFields ? 'Nilai diskon wajib diisi' : false,
|
||||||
|
min: {
|
||||||
|
value: watchedDiscountType === 'percent' ? 1 : 1000,
|
||||||
|
message: watchedDiscountType === 'percent' ? 'Minimal 1%' : 'Minimal Rp 1.000'
|
||||||
|
},
|
||||||
|
max: {
|
||||||
|
value: watchedDiscountType === 'percent' ? 100 : 100,
|
||||||
|
message: 'Maksimal 100%'
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
type='number'
|
||||||
|
placeholder={watchedDiscountType === 'percent' ? '10' : '50000'}
|
||||||
|
error={!!errors.discountValue}
|
||||||
|
helperText={errors.discountValue?.message || getDiscountValueDisplay()}
|
||||||
|
InputProps={{
|
||||||
|
startAdornment: (
|
||||||
|
<InputAdornment position='start'>
|
||||||
|
{watchedDiscountType === 'percent' ? '%' : 'Rp'}
|
||||||
|
</InputAdornment>
|
||||||
|
)
|
||||||
|
}}
|
||||||
|
onChange={e => field.onChange(e.target.value ? Number(e.target.value) : '')}
|
||||||
|
value={field.value === '' ? '' : field.value}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</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>
|
||||||
|
|
||||||
|
{/* Valid From */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Berlaku Mulai <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='validFrom'
|
||||||
|
control={control}
|
||||||
|
rules={{ required: 'Tanggal mulai berlaku wajib diisi' }}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
type='date'
|
||||||
|
error={!!errors.validFrom}
|
||||||
|
helperText={errors.validFrom?.message}
|
||||||
|
InputLabelProps={{
|
||||||
|
shrink: true
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Minimum Purchase */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Pembelian Minimum
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='hasMinPurchase'
|
||||||
|
control={control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormControlLabel
|
||||||
|
control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
|
||||||
|
label='Memiliki syarat pembelian minimum'
|
||||||
|
className='mb-2'
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
{watchedHasMinPurchase && (
|
||||||
|
<Controller
|
||||||
|
name='minPurchase'
|
||||||
|
control={control}
|
||||||
|
rules={{
|
||||||
|
required: watchedHasMinPurchase ? 'Minimal pembelian wajib diisi' : false,
|
||||||
|
min: {
|
||||||
|
value: 1000,
|
||||||
|
message: 'Minimal pembelian tidak boleh kurang dari Rp 1.000'
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
type='number'
|
||||||
|
placeholder='50000'
|
||||||
|
error={!!errors.minPurchase}
|
||||||
|
helperText={
|
||||||
|
errors.minPurchase?.message || (field.value ? formatCurrency(Number(field.value)) : '')
|
||||||
|
}
|
||||||
|
InputProps={{
|
||||||
|
startAdornment: <InputAdornment position='start'>Rp</InputAdornment>
|
||||||
|
}}
|
||||||
|
onChange={e => field.onChange(e.target.value ? Number(e.target.value) : '')}
|
||||||
|
value={field.value === '' ? '' : field.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='Voucher 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 Voucher
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='description'
|
||||||
|
control={control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
placeholder='Deskripsi detail tentang voucher'
|
||||||
|
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 voucher'
|
||||||
|
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='voucher-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 AddEditVoucherDrawer
|
||||||
755
src/views/apps/marketing/voucher/VoucherListTable.tsx
Normal file
755
src/views/apps/marketing/voucher/VoucherListTable.tsx
Normal file
@ -0,0 +1,755 @@
|
|||||||
|
'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 AddEditVoucherDrawer from './AddEditVoucherDrawer'
|
||||||
|
|
||||||
|
// Voucher Type Interface
|
||||||
|
export interface VoucherType {
|
||||||
|
id: number
|
||||||
|
code: string
|
||||||
|
type: 'discount' | 'cashback' | 'free_shipping' | 'product'
|
||||||
|
discountType?: 'fixed' | 'percent'
|
||||||
|
discountValue?: number
|
||||||
|
minPurchase?: number
|
||||||
|
validFrom: string
|
||||||
|
validUntil: string
|
||||||
|
isActive: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
// Main Voucher Catalog Type Interface
|
||||||
|
export interface VoucherCatalogType {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
description?: string
|
||||||
|
pointCost: number
|
||||||
|
stock?: number
|
||||||
|
isActive: boolean
|
||||||
|
validUntil?: Date
|
||||||
|
imageUrl?: string
|
||||||
|
createdAt: Date
|
||||||
|
updatedAt: Date
|
||||||
|
// Voucher-specific fields
|
||||||
|
code: string
|
||||||
|
type: 'discount' | 'cashback' | 'free_shipping' | 'product'
|
||||||
|
discountType?: 'fixed' | 'percent'
|
||||||
|
discountValue?: number
|
||||||
|
minPurchase?: number
|
||||||
|
validFrom: string
|
||||||
|
}
|
||||||
|
|
||||||
|
declare module '@tanstack/table-core' {
|
||||||
|
interface FilterFns {
|
||||||
|
fuzzy: FilterFn<unknown>
|
||||||
|
}
|
||||||
|
interface FilterMeta {
|
||||||
|
itemRank: RankingInfo
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type VoucherCatalogTypeWithAction = VoucherCatalogType & {
|
||||||
|
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)} />
|
||||||
|
}
|
||||||
|
|
||||||
|
// Updated dummy data with integrated voucher information
|
||||||
|
const DUMMY_VOUCHER_DATA: VoucherCatalogType[] = [
|
||||||
|
{
|
||||||
|
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'),
|
||||||
|
code: 'DISC50K',
|
||||||
|
type: 'discount',
|
||||||
|
discountType: 'fixed',
|
||||||
|
discountValue: 50000,
|
||||||
|
minPurchase: 200000,
|
||||||
|
validFrom: '2024-01-15'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
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'),
|
||||||
|
code: 'FREESHIP',
|
||||||
|
type: 'free_shipping',
|
||||||
|
validFrom: '2024-01-20'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
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'),
|
||||||
|
code: 'SPEAKER25',
|
||||||
|
type: 'product',
|
||||||
|
validFrom: '2024-01-25'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
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'),
|
||||||
|
code: 'CASHBACK20',
|
||||||
|
type: 'cashback',
|
||||||
|
discountType: 'percent',
|
||||||
|
discountValue: 20,
|
||||||
|
minPurchase: 100000,
|
||||||
|
validFrom: '2024-02-01'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
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'),
|
||||||
|
code: 'WATCH15',
|
||||||
|
type: 'product',
|
||||||
|
validFrom: '2024-02-05'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
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'),
|
||||||
|
code: 'TUMBLER50',
|
||||||
|
type: 'product',
|
||||||
|
validFrom: '2024-02-10'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
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'),
|
||||||
|
code: 'GIFT100K',
|
||||||
|
type: 'discount',
|
||||||
|
discountType: 'fixed',
|
||||||
|
discountValue: 100000,
|
||||||
|
validFrom: '2024-02-15'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
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'),
|
||||||
|
code: 'EARBUDS30',
|
||||||
|
type: 'product',
|
||||||
|
validFrom: '2024-03-01'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
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'),
|
||||||
|
code: 'BUY1GET1',
|
||||||
|
type: 'discount',
|
||||||
|
discountType: 'percent',
|
||||||
|
discountValue: 50,
|
||||||
|
minPurchase: 50000,
|
||||||
|
validFrom: '2024-03-05'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
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'),
|
||||||
|
code: 'POWERBANK40',
|
||||||
|
type: 'product',
|
||||||
|
validFrom: '2024-03-10'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
// Helper function to get voucher type display text
|
||||||
|
const getVoucherTypeDisplay = (type: string) => {
|
||||||
|
const typeMap = {
|
||||||
|
discount: 'Diskon',
|
||||||
|
cashback: 'Cashback',
|
||||||
|
free_shipping: 'Gratis Ongkir',
|
||||||
|
product: 'Produk'
|
||||||
|
}
|
||||||
|
return typeMap[type as keyof typeof typeMap] || type
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper function to get voucher value display
|
||||||
|
const getVoucherValueDisplay = (voucher: VoucherCatalogType) => {
|
||||||
|
if (voucher.type === 'free_shipping') return 'Gratis Ongkir'
|
||||||
|
if (voucher.type === 'product') return 'Produk Fisik'
|
||||||
|
|
||||||
|
if (voucher.discountValue) {
|
||||||
|
if (voucher.discountType === 'percent') {
|
||||||
|
return `${voucher.discountValue}%`
|
||||||
|
} else {
|
||||||
|
return formatCurrency(voucher.discountValue)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return '-'
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mock data hook with dummy data
|
||||||
|
const useVoucherCatalog = ({ 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_VOUCHER_DATA
|
||||||
|
|
||||||
|
return DUMMY_VOUCHER_DATA.filter(
|
||||||
|
voucher =>
|
||||||
|
voucher.name.toLowerCase().includes(search.toLowerCase()) ||
|
||||||
|
voucher.description?.toLowerCase().includes(search.toLowerCase()) ||
|
||||||
|
voucher.code.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: {
|
||||||
|
vouchers: paginatedData,
|
||||||
|
total_count: filteredData.length
|
||||||
|
},
|
||||||
|
isLoading,
|
||||||
|
error: null,
|
||||||
|
isFetching: isLoading
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Column Definitions
|
||||||
|
const columnHelper = createColumnHelper<VoucherCatalogTypeWithAction>()
|
||||||
|
|
||||||
|
const VoucherListTable = () => {
|
||||||
|
// States
|
||||||
|
const [addVoucherOpen, setAddVoucherOpen] = useState(false)
|
||||||
|
const [editVoucherData, setEditVoucherData] = useState<VoucherCatalogType | 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 } = useVoucherCatalog({
|
||||||
|
page: currentPage,
|
||||||
|
limit: pageSize,
|
||||||
|
search
|
||||||
|
})
|
||||||
|
|
||||||
|
const vouchers = data?.vouchers ?? []
|
||||||
|
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 handleEditVoucher = (voucher: VoucherCatalogType) => {
|
||||||
|
setEditVoucherData(voucher)
|
||||||
|
setAddVoucherOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDeleteVoucher = (voucherId: string) => {
|
||||||
|
if (confirm('Apakah Anda yakin ingin menghapus voucher ini?')) {
|
||||||
|
console.log('Deleting voucher:', voucherId)
|
||||||
|
// Add your delete logic here
|
||||||
|
// deleteVoucher.mutate(voucherId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleToggleActive = (voucherId: string, currentStatus: boolean) => {
|
||||||
|
console.log('Toggling active status for voucher:', voucherId, !currentStatus)
|
||||||
|
// Add your toggle logic here
|
||||||
|
// toggleVoucherStatus.mutate({ id: voucherId, isActive: !currentStatus })
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCloseVoucherDrawer = () => {
|
||||||
|
setAddVoucherOpen(false)
|
||||||
|
setEditVoucherData(undefined)
|
||||||
|
}
|
||||||
|
|
||||||
|
const columns = useMemo<ColumnDef<VoucherCatalogTypeWithAction, 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 Voucher',
|
||||||
|
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/vouchers/${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>
|
||||||
|
)}
|
||||||
|
<Typography variant='caption' color='textSecondary' className='font-mono'>
|
||||||
|
{row.original.code}
|
||||||
|
</Typography>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('type', {
|
||||||
|
header: 'Tipe Voucher',
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const typeColors = {
|
||||||
|
discount: 'primary',
|
||||||
|
cashback: 'success',
|
||||||
|
free_shipping: 'info',
|
||||||
|
product: 'warning'
|
||||||
|
} as const
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Chip
|
||||||
|
label={getVoucherTypeDisplay(row.original.type)}
|
||||||
|
color={typeColors[row.original.type] || 'default'}
|
||||||
|
variant='tonal'
|
||||||
|
size='small'
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
columnHelper.accessor('discountValue', {
|
||||||
|
header: 'Nilai Voucher',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<Typography color='text.primary' className='font-medium'>
|
||||||
|
{getVoucherValueDisplay(row.original)}
|
||||||
|
</Typography>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
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('minPurchase', {
|
||||||
|
header: 'Min. Pembelian',
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<Typography color='text.primary'>
|
||||||
|
{row.original.minPurchase ? formatCurrency(row.original.minPurchase) : '-'}
|
||||||
|
</Typography>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
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>
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
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: () => handleEditVoucher(row.original)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
text: 'Hapus',
|
||||||
|
icon: 'tabler-trash text-[22px]',
|
||||||
|
menuItemProps: {
|
||||||
|
className: 'flex items-center gap-2 text-textSecondary',
|
||||||
|
onClick: () => handleDeleteVoucher(row.original.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
enableSorting: false
|
||||||
|
}
|
||||||
|
],
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
[locale, handleEditVoucher, handleDeleteVoucher, handleToggleActive]
|
||||||
|
)
|
||||||
|
|
||||||
|
const table = useReactTable({
|
||||||
|
data: vouchers as VoucherCatalogType[],
|
||||||
|
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 Voucher'
|
||||||
|
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={() => setAddVoucherOpen(!addVoucherOpen)}
|
||||||
|
className='max-sm:is-full'
|
||||||
|
>
|
||||||
|
Tambah Voucher
|
||||||
|
</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>
|
||||||
|
<AddEditVoucherDrawer open={addVoucherOpen} handleClose={handleCloseVoucherDrawer} data={editVoucherData} />
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default VoucherListTable
|
||||||
17
src/views/apps/marketing/voucher/index.tsx
Normal file
17
src/views/apps/marketing/voucher/index.tsx
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
// MUI Imports
|
||||||
|
import Grid from '@mui/material/Grid2'
|
||||||
|
import VoucherListTable from './VoucherListTable'
|
||||||
|
|
||||||
|
// Type Imports
|
||||||
|
|
||||||
|
const VoucherList = () => {
|
||||||
|
return (
|
||||||
|
<Grid container spacing={6}>
|
||||||
|
<Grid size={{ xs: 12 }}>
|
||||||
|
<VoucherListTable />
|
||||||
|
</Grid>
|
||||||
|
</Grid>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default VoucherList
|
||||||
Loading…
x
Reference in New Issue
Block a user