efril #13

Merged
aefril merged 19 commits from efril into main 2025-09-18 04:01:33 +00:00
11 changed files with 1181 additions and 2 deletions
Showing only changes of commit 7252c05569 - Show all commits

View File

@ -0,0 +1,7 @@
import GamePrizeList from '@/views/apps/marketing/games/game-prizes'
const GamePrizePage = () => {
return <GamePrizeList />
}
export default GamePrizePage

View File

@ -163,6 +163,9 @@ const VerticalMenu = ({ dictionary, scrollMenu }: Props) => {
</SubMenu> </SubMenu>
<SubMenu label={dictionary['navigation'].games}> <SubMenu label={dictionary['navigation'].games}>
<MenuItem href={`/${locale}/apps/marketing/games/list`}>{dictionary['navigation'].list}</MenuItem> <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> </SubMenu>
<MenuItem href={`/${locale}/apps/marketing/campaign`}>{dictionary['navigation'].campaign}</MenuItem> <MenuItem href={`/${locale}/apps/marketing/campaign`}>{dictionary['navigation'].campaign}</MenuItem>
<MenuItem href={`/${locale}/apps/marketing/customer-analytics`}> <MenuItem href={`/${locale}/apps/marketing/customer-analytics`}>

View File

@ -136,6 +136,7 @@
"customer_analytics": "Customer Analytics", "customer_analytics": "Customer Analytics",
"voucher": "Voucher", "voucher": "Voucher",
"tiers_text": "Tiers", "tiers_text": "Tiers",
"games": "Games" "games": "Games",
"game_prizes": "Game Prizes"
} }
} }

View File

@ -136,6 +136,7 @@
"customer_analytics": "Analisis Pelanggan", "customer_analytics": "Analisis Pelanggan",
"voucher": "Vocher", "voucher": "Vocher",
"tiers_text": "Tiers", "tiers_text": "Tiers",
"games": "Permaninan" "games": "Permainan",
"game_prizes": "Hadiah Permainan"
} }
} }

View 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 }
}

View 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
}
})
}

View File

@ -0,0 +1,35 @@
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
}

View File

@ -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

View File

@ -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

View File

@ -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

View 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