diff --git a/src/app/[lang]/(dashboard)/(private)/apps/marketing/gamification/wheel-spin/page.tsx b/src/app/[lang]/(dashboard)/(private)/apps/marketing/gamification/wheel-spin/page.tsx new file mode 100644 index 0000000..bd53c1d --- /dev/null +++ b/src/app/[lang]/(dashboard)/(private)/apps/marketing/gamification/wheel-spin/page.tsx @@ -0,0 +1,7 @@ +import WheelSpinList from '@/views/apps/marketing/gamification/wheel-spin' + +const WheelSpinPage = () => { + return +} + +export default WheelSpinPage diff --git a/src/components/layout/vertical/VerticalMenu.tsx b/src/components/layout/vertical/VerticalMenu.tsx index c817458..5a33103 100644 --- a/src/components/layout/vertical/VerticalMenu.tsx +++ b/src/components/layout/vertical/VerticalMenu.tsx @@ -156,6 +156,11 @@ const VerticalMenu = ({ dictionary, scrollMenu }: Props) => { }> {dictionary['navigation'].loyalty} {dictionary['navigation'].reward} + + + {dictionary['navigation'].wheel_spin} + + }> diff --git a/src/data/dictionaries/en.json b/src/data/dictionaries/en.json index c91b7ec..9ef9e1e 100644 --- a/src/data/dictionaries/en.json +++ b/src/data/dictionaries/en.json @@ -129,6 +129,8 @@ "fixed_assets": "Fixed Assets", "marketing": "Marketing", "loyalty": "Loyalty", - "reward": "Reward" + "reward": "Reward", + "gamification": "Gamification", + "wheel_spin": "Wheel Spin" } } diff --git a/src/data/dictionaries/id.json b/src/data/dictionaries/id.json index 7bb1d23..03fdd66 100644 --- a/src/data/dictionaries/id.json +++ b/src/data/dictionaries/id.json @@ -129,6 +129,8 @@ "fixed_assets": "Aset Tetap", "marketing": "Pemasaran", "loyalty": "Loyalti", - "reward": "Reward" + "reward": "Reward", + "gamification": "Gamifikasi", + "wheel_spin": "Wheel Spin" } } diff --git a/src/types/services/reward.ts b/src/types/services/reward.ts index d9a3238..ebf0c08 100644 --- a/src/types/services/reward.ts +++ b/src/types/services/reward.ts @@ -1,4 +1,4 @@ -export interface RewardCatalog { +export interface RewardCatalogType { id: string name: string description?: string diff --git a/src/types/services/wheelSpin.ts b/src/types/services/wheelSpin.ts new file mode 100644 index 0000000..67a0d82 --- /dev/null +++ b/src/types/services/wheelSpin.ts @@ -0,0 +1,10 @@ +export interface WheelSpinType { + id: string + name: string + weight: number + omset: number + fallback: boolean + stock?: number + createdAt: Date + updatedAt: Date +} diff --git a/src/views/apps/marketing/gamification/wheel-spin/AddEditWheelSpinDrawer.tsx b/src/views/apps/marketing/gamification/wheel-spin/AddEditWheelSpinDrawer.tsx new file mode 100644 index 0000000..758e23d --- /dev/null +++ b/src/views/apps/marketing/gamification/wheel-spin/AddEditWheelSpinDrawer.tsx @@ -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({ + 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 ( + + {/* Sticky Header */} + +
+ {isEditMode ? 'Edit Hadiah Wheel Spin' : 'Tambah Hadiah Baru'} + + + +
+
+ + {/* Scrollable Content */} + +
+
+ {/* Nama Hadiah */} +
+ + Nama Hadiah * + + ( + + )} + /> +
+ + {/* Weight */} +
+ + Bobot Kemunculan * + + ( + % + }} + onChange={e => field.onChange(Number(e.target.value))} + /> + )} + /> +
+ + {/* Minimum Omset */} +
+ + Minimum Omset * + + ( + 0 ? formatCurrency(field.value) : 'Omset minimum untuk mendapatkan hadiah ini') + } + InputProps={{ + startAdornment: Rp + }} + onChange={e => field.onChange(Number(e.target.value))} + /> + )} + /> +
+ + {/* Fallback Option */} +
+ ( + } + label='Hadiah Fallback' + /> + )} + /> + {watchedFallback && ( + + Hadiah fallback akan muncul ketika hadiah lain tidak tersedia atau habis + + )} +
+ + {/* Stock Management */} +
+ handleStockToggle(e.target.checked)} color='primary' /> + } + label='Batasi Stok' + /> + + {hasStock && ( +
+ + Jumlah Stok * + + ( + field.onChange(Number(e.target.value))} + /> + )} + /> +
+ )} +
+ + {/* Status Aktif */} +
+ ( + } + label='Hadiah Aktif' + /> + )} + /> +
+ + {/* Tampilkan selengkapnya */} + {!showMore && ( + + )} + + {/* Konten tambahan */} + {showMore && ( + <> + {/* Description */} +
+ + Deskripsi Hadiah + + ( + + )} + /> +
+ + {/* Tips */} + + + Tips: +
+ • Bobot yang lebih tinggi = peluang menang lebih besar +
+ • Hadiah fallback sebaiknya selalu ada untuk backup +
• Minimum omset membantu mendorong transaksi lebih besar +
+
+ + {/* Sembunyikan */} + + + )} +
+
+
+ + {/* Sticky Footer */} + +
+ + +
+
+
+ ) +} + +export default AddEditWheelSpinDrawer diff --git a/src/views/apps/marketing/gamification/wheel-spin/WheelSpinListTable.tsx b/src/views/apps/marketing/gamification/wheel-spin/WheelSpinListTable.tsx new file mode 100644 index 0000000..9268421 --- /dev/null +++ b/src/views/apps/marketing/gamification/wheel-spin/WheelSpinListTable.tsx @@ -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 + } + interface FilterMeta { + itemRank: RankingInfo + } +} + +type WheelSpinTypeWithAction = WheelSpinType & { + action?: string +} + +// Styled Components +const Icon = styled('i')({}) + +const fuzzyFilter: FilterFn = (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) => { + // 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 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() + +const WheelSpinListTable = () => { + // States + const [addWheelSpinOpen, setAddWheelSpinOpen] = useState(false) + const [editWheelSpinData, setEditWheelSpinData] = useState(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) => { + 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[]>( + () => [ + { + id: 'select', + header: ({ table }) => ( + + ), + cell: ({ row }) => ( + + ) + }, + columnHelper.accessor('name', { + header: 'Nama Hadiah', + cell: ({ row }) => ( +
+
+ + + {row.original.name} + + +
+
+ ) + }), + columnHelper.accessor('weight', { + header: 'Bobot', + cell: ({ row }) => ( +
+ + {row.original.weight}% +
+ ) + }), + columnHelper.accessor('omset', { + header: 'Min. Omset', + cell: ({ row }) => ( +
+ + {formatCurrency(row.original.omset)} +
+ ) + }), + columnHelper.accessor('stock', { + header: 'Stok', + cell: ({ row }) => ( +
+ {row.original.stock !== undefined ? ( + <> + + {row.original.stock} + + ) : ( + Unlimited + )} +
+ ) + }), + columnHelper.accessor('fallback', { + header: 'Status', + cell: ({ row }) => ( + + ) + }), + columnHelper.accessor('createdAt', { + header: 'Tanggal Dibuat', + cell: ({ row }) => ( + + {new Date(row.original.createdAt).toLocaleDateString('id-ID', { + year: 'numeric', + month: 'short', + day: 'numeric' + })} + + ) + }), + { + id: 'actions', + header: 'Aksi', + cell: ({ row }) => ( +
+ handleEditWheelSpin(row.original) + } + }, + { + text: 'Hapus', + icon: 'tabler-trash text-[22px]', + menuItemProps: { + className: 'flex items-center gap-2 text-textSecondary', + onClick: () => handleDeleteWheelSpin(row.original.id) + } + } + ]} + /> +
+ ), + 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 ( + <> + +
+ table.setPageSize(Number(e.target.value))} + className='max-sm:is-full sm:is-[70px]' + > + 10 + 25 + 50 + +
+ setSearch(value as string)} + placeholder='Cari Hadiah Wheel Spin' + className='max-sm:is-full' + /> + + +
+
+
+ {isLoading ? ( + + ) : ( + + + {table.getHeaderGroups().map(headerGroup => ( + + {headerGroup.headers.map(header => ( + + ))} + + ))} + + {table.getFilteredRowModel().rows.length === 0 ? ( + + + + + + ) : ( + + {table + .getRowModel() + .rows.slice(0, table.getState().pagination.pageSize) + .map(row => { + return ( + + {row.getVisibleCells().map(cell => ( + + ))} + + ) + })} + + )} +
+ {header.isPlaceholder ? null : ( + <> +
+ {flexRender(header.column.columnDef.header, header.getContext())} + {{ + asc: , + desc: + }[header.column.getIsSorted() as 'asc' | 'desc'] ?? null} +
+ + )} +
+ Tidak ada data tersedia +
{flexRender(cell.column.columnDef.cell, cell.getContext())}
+ )} +
+ ( + + )} + count={totalCount} + rowsPerPage={pageSize} + page={currentPage} + onPageChange={handlePageChange} + onRowsPerPageChange={handlePageSizeChange} + rowsPerPageOptions={[10, 25, 50]} + disabled={isLoading} + /> +
+ + + ) +} + +export default WheelSpinListTable diff --git a/src/views/apps/marketing/gamification/wheel-spin/index.tsx b/src/views/apps/marketing/gamification/wheel-spin/index.tsx new file mode 100644 index 0000000..fc47158 --- /dev/null +++ b/src/views/apps/marketing/gamification/wheel-spin/index.tsx @@ -0,0 +1,17 @@ +// MUI Imports +import Grid from '@mui/material/Grid2' +import WheelSpinListTable from './WheelSpinListTable' + +// Type Imports + +const WheelSpinList = () => { + return ( + + + + + + ) +} + +export default WheelSpinList