Campaign
This commit is contained in:
parent
4640d14cb7
commit
e82173c6e2
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 }
|
||||
}
|
||||
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
|
||||
}
|
||||
})
|
||||
}
|
||||
@ -1,13 +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
|
||||
id: string // UUID
|
||||
name: string
|
||||
description?: string
|
||||
minimumPurchase: number
|
||||
rewardType: 'point' | 'voucher' | 'discount'
|
||||
rewardValue: number
|
||||
startDate: Date
|
||||
endDate: Date
|
||||
isActive: boolean
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
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
|
||||
}
|
||||
|
||||
@ -22,29 +22,33 @@ import { useForm, Controller, useFieldArray } from 'react-hook-form'
|
||||
import CustomTextField from '@core/components/mui/TextField'
|
||||
|
||||
// Types
|
||||
export interface Campaign {
|
||||
id: string
|
||||
name: string
|
||||
description?: string
|
||||
minimumPurchase: number
|
||||
rewardType: 'point' | 'voucher' | 'discount'
|
||||
rewardValue: number
|
||||
startDate: Date
|
||||
endDate: Date
|
||||
isActive: boolean
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}
|
||||
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
|
||||
minimumPurchase: number
|
||||
rewardType: 'point' | 'voucher' | 'discount'
|
||||
rewardValue: number
|
||||
startDate: Date
|
||||
endDate: Date
|
||||
isActive: boolean
|
||||
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 = {
|
||||
@ -56,43 +60,42 @@ type Props = {
|
||||
type FormValidateType = {
|
||||
name: string
|
||||
description: string
|
||||
minimumPurchase: number
|
||||
rewardType: 'point' | 'voucher' | 'discount'
|
||||
rewardValue: number
|
||||
startDate: string
|
||||
endDate: string
|
||||
isActive: boolean
|
||||
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: '',
|
||||
minimumPurchase: 0,
|
||||
rewardType: 'point',
|
||||
rewardValue: 0,
|
||||
startDate: '',
|
||||
endDate: '',
|
||||
isActive: true
|
||||
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: ''
|
||||
}
|
||||
|
||||
// Mock mutation hooks (replace with actual hooks)
|
||||
const useCampaignMutation = () => {
|
||||
const createCampaign = {
|
||||
mutate: (data: CampaignRequest, options?: { onSuccess?: () => void }) => {
|
||||
console.log('Creating campaign:', data)
|
||||
setTimeout(() => options?.onSuccess?.(), 1000)
|
||||
}
|
||||
}
|
||||
|
||||
const updateCampaign = {
|
||||
mutate: (data: { id: string; payload: CampaignRequest }, options?: { onSuccess?: () => void }) => {
|
||||
console.log('Updating campaign:', data)
|
||||
setTimeout(() => options?.onSuccess?.(), 1000)
|
||||
}
|
||||
}
|
||||
|
||||
return { createCampaign, updateCampaign }
|
||||
]
|
||||
}
|
||||
|
||||
const AddEditCampaignDrawer = (props: Props) => {
|
||||
@ -103,7 +106,7 @@ const AddEditCampaignDrawer = (props: Props) => {
|
||||
const [showMore, setShowMore] = useState(false)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
|
||||
const { createCampaign, updateCampaign } = useCampaignMutation()
|
||||
const { createCampaign, updateCampaign } = useCampaignsMutation()
|
||||
|
||||
// Determine if this is edit mode
|
||||
const isEditMode = Boolean(data?.id)
|
||||
@ -120,23 +123,43 @@ const AddEditCampaignDrawer = (props: Props) => {
|
||||
defaultValues: initialData
|
||||
})
|
||||
|
||||
const watchedRewardType = watch('rewardType')
|
||||
const watchedStartDate = watch('startDate')
|
||||
const watchedEndDate = watch('endDate')
|
||||
// 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) {
|
||||
// Populate form with existing data
|
||||
const formData: FormValidateType = {
|
||||
name: data.name || '',
|
||||
description: data.description || '',
|
||||
minimumPurchase: data.minimumPurchase || 0,
|
||||
rewardType: data.rewardType || 'point',
|
||||
rewardValue: data.rewardValue || 0,
|
||||
startDate: data.startDate ? new Date(data.startDate).toISOString().split('T')[0] : '',
|
||||
endDate: data.endDate ? new Date(data.endDate).toISOString().split('T')[0] : '',
|
||||
isActive: data.isActive ?? true
|
||||
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)
|
||||
@ -152,16 +175,34 @@ const AddEditCampaignDrawer = (props: Props) => {
|
||||
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,
|
||||
minimumPurchase: formData.minimumPurchase,
|
||||
rewardType: formData.rewardType,
|
||||
rewardValue: formData.rewardValue,
|
||||
startDate: new Date(formData.startDate),
|
||||
endDate: new Date(formData.endDate),
|
||||
isActive: formData.isActive
|
||||
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) {
|
||||
@ -206,52 +247,59 @@ const AddEditCampaignDrawer = (props: Props) => {
|
||||
}).format(value)
|
||||
}
|
||||
|
||||
const getRewardTypeLabel = (type: 'point' | 'voucher' | 'discount') => {
|
||||
const getRewardTypeLabel = (type: RewardType) => {
|
||||
switch (type) {
|
||||
case 'point':
|
||||
case 'POINTS':
|
||||
return 'Poin'
|
||||
case 'voucher':
|
||||
return 'Voucher'
|
||||
case 'discount':
|
||||
return 'Diskon'
|
||||
case 'TOKENS':
|
||||
return 'Token'
|
||||
case 'REWARD':
|
||||
return 'Reward'
|
||||
default:
|
||||
return type
|
||||
}
|
||||
}
|
||||
|
||||
const getRewardValuePlaceholder = (type: 'point' | 'voucher' | 'discount') => {
|
||||
const getRewardValuePlaceholder = (type: RewardType) => {
|
||||
switch (type) {
|
||||
case 'point':
|
||||
case 'POINTS':
|
||||
return 'Jumlah poin yang diberikan'
|
||||
case 'voucher':
|
||||
return 'Nilai voucher dalam Rupiah'
|
||||
case 'discount':
|
||||
return 'Persentase diskon (1-100)'
|
||||
case 'TOKENS':
|
||||
return 'Jumlah token yang diberikan'
|
||||
case 'REWARD':
|
||||
return 'Nilai reward'
|
||||
default:
|
||||
return 'Nilai reward'
|
||||
}
|
||||
}
|
||||
|
||||
const getRewardValueRules = (type: 'point' | 'voucher' | 'discount') => {
|
||||
const baseRules = {
|
||||
required: 'Nilai reward wajib diisi',
|
||||
min: {
|
||||
value: 1,
|
||||
message: 'Nilai reward minimal 1'
|
||||
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'
|
||||
}
|
||||
}
|
||||
|
||||
if (type === 'discount') {
|
||||
const getConditionValueInputProps = (ruleType: RuleType) => {
|
||||
if (ruleType === 'SPEND') {
|
||||
return {
|
||||
...baseRules,
|
||||
max: {
|
||||
value: 100,
|
||||
message: 'Persentase diskon maksimal 100%'
|
||||
startAdornment: <InputAdornment position='start'>Rp</InputAdornment>,
|
||||
type: 'number' as const
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return baseRules
|
||||
return { type: 'text' as const }
|
||||
}
|
||||
|
||||
return (
|
||||
@ -314,71 +362,39 @@ const AddEditCampaignDrawer = (props: Props) => {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Minimum Purchase */}
|
||||
{/* Jenis Kampanye */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Minimum Pembelian <span className='text-red-500'>*</span>
|
||||
Jenis Kampanye <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='minimumPurchase'
|
||||
name='type'
|
||||
control={control}
|
||||
rules={{
|
||||
required: 'Minimum pembelian wajib diisi',
|
||||
min: {
|
||||
value: 0,
|
||||
message: 'Minimum pembelian tidak boleh negatif'
|
||||
}
|
||||
}}
|
||||
rules={{ required: 'Jenis kampanye wajib dipilih' }}
|
||||
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>
|
||||
|
||||
{/* Jenis Reward */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Jenis Reward <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='rewardType'
|
||||
control={control}
|
||||
rules={{ required: 'Jenis reward wajib dipilih' }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
select
|
||||
fullWidth
|
||||
error={!!errors.rewardType}
|
||||
helperText={errors.rewardType?.message}
|
||||
>
|
||||
<MenuItem value='point'>
|
||||
<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' />
|
||||
Poin
|
||||
Points
|
||||
</div>
|
||||
</MenuItem>
|
||||
<MenuItem value='voucher'>
|
||||
<MenuItem value='TOKENS'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<i className='tabler-ticket text-success' />
|
||||
Voucher
|
||||
Tokens
|
||||
</div>
|
||||
</MenuItem>
|
||||
<MenuItem value='discount'>
|
||||
<MenuItem value='REWARD'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<i className='tabler-percentage text-warning' />
|
||||
Diskon
|
||||
<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>
|
||||
@ -386,40 +402,201 @@ const AddEditCampaignDrawer = (props: Props) => {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Nilai Reward */}
|
||||
{/* 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'>
|
||||
Nilai {getRewardTypeLabel(watchedRewardType)} <span className='text-red-500'>*</span>
|
||||
Tipe Aturan <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='rewardValue'
|
||||
name={`rules.${index}.rule_type`}
|
||||
control={control}
|
||||
rules={getRewardValueRules(watchedRewardType)}
|
||||
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(watchedRewardType)}
|
||||
error={!!errors.rewardValue}
|
||||
helperText={errors.rewardValue?.message}
|
||||
placeholder={getRewardValuePlaceholder(rewardType)}
|
||||
error={!!errors.rules?.[index]?.reward_value}
|
||||
helperText={errors.rules?.[index]?.reward_value?.message}
|
||||
InputProps={{
|
||||
startAdornment:
|
||||
watchedRewardType === 'voucher' ? (
|
||||
<InputAdornment position='start'>Rp</InputAdornment>
|
||||
) : undefined,
|
||||
endAdornment:
|
||||
watchedRewardType === 'discount' ? (
|
||||
<InputAdornment position='end'>%</InputAdornment>
|
||||
) : watchedRewardType === 'point' ? (
|
||||
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>
|
||||
@ -427,7 +604,7 @@ const AddEditCampaignDrawer = (props: Props) => {
|
||||
Tanggal Mulai <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='startDate'
|
||||
name='start_date'
|
||||
control={control}
|
||||
rules={{ required: 'Tanggal mulai wajib diisi' }}
|
||||
render={({ field }) => (
|
||||
@ -435,8 +612,8 @@ const AddEditCampaignDrawer = (props: Props) => {
|
||||
{...field}
|
||||
fullWidth
|
||||
type='date'
|
||||
error={!!errors.startDate}
|
||||
helperText={errors.startDate?.message}
|
||||
error={!!errors.start_date}
|
||||
helperText={errors.start_date?.message}
|
||||
InputLabelProps={{
|
||||
shrink: true
|
||||
}}
|
||||
@ -451,7 +628,7 @@ const AddEditCampaignDrawer = (props: Props) => {
|
||||
Tanggal Berakhir <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='endDate'
|
||||
name='end_date'
|
||||
control={control}
|
||||
rules={{
|
||||
required: 'Tanggal berakhir wajib diisi',
|
||||
@ -469,8 +646,8 @@ const AddEditCampaignDrawer = (props: Props) => {
|
||||
{...field}
|
||||
fullWidth
|
||||
type='date'
|
||||
error={!!errors.endDate}
|
||||
helperText={errors.endDate?.message}
|
||||
error={!!errors.end_date}
|
||||
helperText={errors.end_date?.message}
|
||||
InputLabelProps={{
|
||||
shrink: true
|
||||
}}
|
||||
@ -485,7 +662,7 @@ const AddEditCampaignDrawer = (props: Props) => {
|
||||
{/* Status Aktif */}
|
||||
<div>
|
||||
<Controller
|
||||
name='isActive'
|
||||
name='is_active'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<FormControlLabel
|
||||
@ -496,6 +673,20 @@ const AddEditCampaignDrawer = (props: Props) => {
|
||||
/>
|
||||
</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
|
||||
@ -532,6 +723,31 @@ const AddEditCampaignDrawer = (props: Props) => {
|
||||
/>
|
||||
</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'
|
||||
|
||||
@ -57,21 +57,10 @@ import { formatCurrency } from '@/utils/transform'
|
||||
import tableStyles from '@core/styles/table.module.css'
|
||||
import Loading from '@/components/layout/shared/Loading'
|
||||
import AddEditCampaignDrawer from './AddEditCampaignDrawer'
|
||||
|
||||
// Campaign Type Interface
|
||||
export interface Campaign {
|
||||
id: string
|
||||
name: string
|
||||
description?: string
|
||||
minimumPurchase: number
|
||||
rewardType: 'point' | 'voucher' | 'discount'
|
||||
rewardValue: number
|
||||
startDate: Date
|
||||
endDate: Date
|
||||
isActive: boolean
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}
|
||||
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 {
|
||||
@ -131,216 +120,133 @@ const DebouncedInput = ({
|
||||
return <CustomTextField {...props} value={value} onChange={e => setValue(e.target.value)} />
|
||||
}
|
||||
|
||||
// Dummy data for campaigns
|
||||
const DUMMY_CAMPAIGN_DATA: Campaign[] = [
|
||||
{
|
||||
id: '1',
|
||||
name: 'Summer Sale Campaign',
|
||||
description: 'Get extra points during summer season',
|
||||
minimumPurchase: 500000,
|
||||
rewardType: 'point',
|
||||
rewardValue: 100,
|
||||
startDate: new Date('2024-06-01'),
|
||||
endDate: new Date('2024-08-31'),
|
||||
isActive: true,
|
||||
createdAt: new Date('2024-05-15'),
|
||||
updatedAt: new Date('2024-06-01')
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
name: 'Welcome Bonus',
|
||||
description: 'Special discount for new customers',
|
||||
minimumPurchase: 200000,
|
||||
rewardType: 'discount',
|
||||
rewardValue: 15,
|
||||
startDate: new Date('2024-01-01'),
|
||||
endDate: new Date('2024-12-31'),
|
||||
isActive: true,
|
||||
createdAt: new Date('2024-01-01'),
|
||||
updatedAt: new Date('2024-03-15')
|
||||
},
|
||||
{
|
||||
id: '3',
|
||||
name: 'Flash Sale Weekend',
|
||||
description: 'Weekend special voucher campaign',
|
||||
minimumPurchase: 1000000,
|
||||
rewardType: 'voucher',
|
||||
rewardValue: 50000,
|
||||
startDate: new Date('2024-07-06'),
|
||||
endDate: new Date('2024-07-07'),
|
||||
isActive: false,
|
||||
createdAt: new Date('2024-07-01'),
|
||||
updatedAt: new Date('2024-07-08')
|
||||
},
|
||||
{
|
||||
id: '4',
|
||||
name: 'Loyalty Rewards',
|
||||
description: 'Extra points for loyal customers',
|
||||
minimumPurchase: 2000000,
|
||||
rewardType: 'point',
|
||||
rewardValue: 300,
|
||||
startDate: new Date('2024-03-01'),
|
||||
endDate: new Date('2024-09-30'),
|
||||
isActive: true,
|
||||
createdAt: new Date('2024-02-25'),
|
||||
updatedAt: new Date('2024-05-10')
|
||||
},
|
||||
{
|
||||
id: '5',
|
||||
name: 'Black Friday Special',
|
||||
description: 'Biggest discount of the year',
|
||||
minimumPurchase: 800000,
|
||||
rewardType: 'discount',
|
||||
rewardValue: 25,
|
||||
startDate: new Date('2024-11-29'),
|
||||
endDate: new Date('2024-11-29'),
|
||||
isActive: false,
|
||||
createdAt: new Date('2024-11-01'),
|
||||
updatedAt: new Date('2024-11-30')
|
||||
},
|
||||
{
|
||||
id: '6',
|
||||
name: 'Student Promo',
|
||||
description: 'Special voucher for students',
|
||||
minimumPurchase: 300000,
|
||||
rewardType: 'voucher',
|
||||
rewardValue: 25000,
|
||||
startDate: new Date('2024-09-01'),
|
||||
endDate: new Date('2024-12-20'),
|
||||
isActive: true,
|
||||
createdAt: new Date('2024-08-25'),
|
||||
updatedAt: new Date('2024-09-01')
|
||||
},
|
||||
{
|
||||
id: '7',
|
||||
name: 'Holiday Celebration',
|
||||
description: 'Special points during holidays',
|
||||
minimumPurchase: 1500000,
|
||||
rewardType: 'point',
|
||||
rewardValue: 200,
|
||||
startDate: new Date('2024-12-15'),
|
||||
endDate: new Date('2025-01-15'),
|
||||
isActive: true,
|
||||
createdAt: new Date('2024-12-01'),
|
||||
updatedAt: new Date('2024-12-15')
|
||||
},
|
||||
{
|
||||
id: '8',
|
||||
name: 'Mid Year Sale',
|
||||
description: 'Mid year discount campaign',
|
||||
minimumPurchase: 600000,
|
||||
rewardType: 'discount',
|
||||
rewardValue: 20,
|
||||
startDate: new Date('2024-06-15'),
|
||||
endDate: new Date('2024-07-15'),
|
||||
isActive: false,
|
||||
createdAt: new Date('2024-06-01'),
|
||||
updatedAt: new Date('2024-07-16')
|
||||
}
|
||||
]
|
||||
|
||||
// Mock data hook with dummy data
|
||||
const useCampaigns = ({ 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_CAMPAIGN_DATA
|
||||
|
||||
return DUMMY_CAMPAIGN_DATA.filter(
|
||||
campaign =>
|
||||
campaign.name.toLowerCase().includes(search.toLowerCase()) ||
|
||||
campaign.description?.toLowerCase().includes(search.toLowerCase()) ||
|
||||
campaign.rewardType.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: {
|
||||
campaigns: paginatedData,
|
||||
total_count: filteredData.length
|
||||
},
|
||||
isLoading,
|
||||
error: null,
|
||||
isFetching: isLoading
|
||||
}
|
||||
// Helper function untuk format points - SAMA SEPERTI REWARD TABLE
|
||||
const formatPoints = (points: number) => {
|
||||
return new Intl.NumberFormat('id-ID').format(points)
|
||||
}
|
||||
|
||||
// Utility functions
|
||||
const getRewardTypeColor = (rewardType: Campaign['rewardType']): ThemeColor => {
|
||||
switch (rewardType) {
|
||||
case 'point':
|
||||
// Helper functions untuk campaign utilities
|
||||
const getCampaignTypeColor = (type: string): ThemeColor => {
|
||||
switch (type) {
|
||||
case 'POINTS':
|
||||
return 'primary'
|
||||
case 'voucher':
|
||||
case 'TOKENS':
|
||||
return 'success'
|
||||
case 'discount':
|
||||
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: Campaign['rewardType']): string => {
|
||||
const getRewardTypeIcon = (rewardType: string): string => {
|
||||
switch (rewardType) {
|
||||
case 'point':
|
||||
case 'POINTS':
|
||||
return 'tabler-coins'
|
||||
case 'voucher':
|
||||
case 'TOKENS':
|
||||
return 'tabler-ticket'
|
||||
case 'discount':
|
||||
case 'REWARD':
|
||||
return 'tabler-percentage'
|
||||
default:
|
||||
return 'tabler-gift'
|
||||
}
|
||||
}
|
||||
|
||||
const formatRewardValue = (rewardType: Campaign['rewardType'], rewardValue: number): string => {
|
||||
const formatRewardValue = (rewardType: string, rewardValue?: number, rewardSubtype?: string): string => {
|
||||
if (!rewardValue) return '-'
|
||||
|
||||
switch (rewardType) {
|
||||
case 'point':
|
||||
return `${rewardValue} Poin`
|
||||
case 'voucher':
|
||||
case 'POINTS':
|
||||
return `${formatPoints(rewardValue)} Poin`
|
||||
case 'TOKENS':
|
||||
return formatCurrency(rewardValue)
|
||||
case 'discount':
|
||||
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
|
||||
// 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,
|
||||
page: currentPage, // SAMA SEPERTI REWARD - langsung currentPage
|
||||
limit: pageSize,
|
||||
search
|
||||
})
|
||||
|
||||
const campaigns = data?.campaigns ?? []
|
||||
const totalCount = data?.total_count ?? 0
|
||||
const totalCount = data?.total ?? 0
|
||||
|
||||
// Hooks
|
||||
const { lang: locale } = useParams()
|
||||
@ -360,11 +266,34 @@ const CampaignListTable = () => {
|
||||
setAddCampaignOpen(true)
|
||||
}
|
||||
|
||||
const handleDeleteCampaign = (campaignId: string) => {
|
||||
if (confirm('Apakah Anda yakin ingin menghapus kampanye ini?')) {
|
||||
console.log('Deleting campaign:', campaignId)
|
||||
// Add your delete logic here
|
||||
// deleteCampaign.mutate(campaignId)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@ -416,38 +345,55 @@ const CampaignListTable = () => {
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('minimumPurchase', {
|
||||
header: 'Minimum Pembelian',
|
||||
columnHelper.accessor('type', {
|
||||
header: 'Jenis Kampanye',
|
||||
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>
|
||||
<Chip
|
||||
label={row.original.type}
|
||||
color={getCampaignTypeColor(row.original.type)}
|
||||
variant='tonal'
|
||||
size='small'
|
||||
/>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('rewardType', {
|
||||
header: 'Jenis Reward',
|
||||
cell: ({ row }) => (
|
||||
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(row.original.rewardType)}
|
||||
sx={{ color: `var(--mui-palette-${getRewardTypeColor(row.original.rewardType)}-main)` }}
|
||||
className={getRewardTypeIcon(reward.type)}
|
||||
sx={{ color: `var(--mui-palette-${getRewardTypeColor(reward.type)}-main)` }}
|
||||
/>
|
||||
<Chip
|
||||
label={formatRewardValue(row.original.rewardType, row.original.rewardValue)}
|
||||
color={getRewardTypeColor(row.original.rewardType)}
|
||||
label={formatRewardValue(reward.type, reward.value, reward.subtype)}
|
||||
color={getRewardTypeColor(reward.type)}
|
||||
variant='tonal'
|
||||
size='small'
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}),
|
||||
columnHelper.accessor('startDate', {
|
||||
columnHelper.accessor('start_date', {
|
||||
header: 'Periode Kampanye',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex flex-col'>
|
||||
<Typography variant='body2' color='text.primary'>
|
||||
{new Date(row.original.startDate).toLocaleDateString('id-ID', {
|
||||
{new Date(row.original.start_date).toLocaleDateString('id-ID', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
@ -455,7 +401,7 @@ const CampaignListTable = () => {
|
||||
</Typography>
|
||||
<Typography variant='body2' color='text.secondary'>
|
||||
s/d{' '}
|
||||
{new Date(row.original.endDate).toLocaleDateString('id-ID', {
|
||||
{new Date(row.original.end_date).toLocaleDateString('id-ID', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
@ -464,22 +410,35 @@ const CampaignListTable = () => {
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('isActive', {
|
||||
columnHelper.accessor('is_active', {
|
||||
header: 'Status',
|
||||
cell: ({ row }) => (
|
||||
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={row.original.isActive ? 'Aktif' : 'Tidak Aktif'}
|
||||
color={row.original.isActive ? 'success' : 'error'}
|
||||
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('createdAt', {
|
||||
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'>
|
||||
{new Date(row.original.createdAt).toLocaleDateString('id-ID', {
|
||||
{/* FIX 3: FORMAT DATE YANG SAMA SEPERTI REWARD */}
|
||||
{new Date(row.original.created_at).toLocaleDateString('id-ID', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
@ -509,7 +468,7 @@ const CampaignListTable = () => {
|
||||
icon: 'tabler-trash text-[22px]',
|
||||
menuItemProps: {
|
||||
className: 'flex items-center gap-2 text-textSecondary',
|
||||
onClick: () => handleDeleteCampaign(row.original.id)
|
||||
onClick: () => handleDeleteCampaign(row.original)
|
||||
}
|
||||
}
|
||||
]}
|
||||
@ -523,8 +482,9 @@ const CampaignListTable = () => {
|
||||
[locale, handleEditCampaign, handleDeleteCampaign]
|
||||
)
|
||||
|
||||
// FIX 4: TABLE CONFIG YANG SAMA PERSIS SEPERTI REWARD
|
||||
const table = useReactTable({
|
||||
data: campaigns as Campaign[],
|
||||
data: campaigns as Campaign[], // SAMA SEPERTI REWARD
|
||||
columns,
|
||||
filterFns: {
|
||||
fuzzy: fuzzyFilter
|
||||
@ -533,15 +493,15 @@ const CampaignListTable = () => {
|
||||
rowSelection,
|
||||
globalFilter,
|
||||
pagination: {
|
||||
pageIndex: currentPage,
|
||||
pageIndex: currentPage, // SAMA SEPERTI REWARD - langsung currentPage
|
||||
pageSize
|
||||
}
|
||||
},
|
||||
enableRowSelection: true,
|
||||
onRowSelectionChange: setRowSelection,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
manualPagination: true,
|
||||
pageCount: Math.ceil(totalCount / pageSize)
|
||||
manualPagination: true, // SAMA SEPERTI REWARD
|
||||
pageCount: Math.ceil(totalCount / pageSize) // SAMA SEPERTI REWARD
|
||||
})
|
||||
|
||||
return (
|
||||
@ -661,6 +621,13 @@ const CampaignListTable = () => {
|
||||
/>
|
||||
</Card>
|
||||
<AddEditCampaignDrawer open={addCampaignOpen} handleClose={handleCloseCampaignDrawer} data={editCampaignData} />
|
||||
<DeleteCampaignDialog
|
||||
open={deleteCampaignOpen}
|
||||
onClose={handleCloseDeleteDialog}
|
||||
onConfirm={handleConfirmDelete}
|
||||
campaign={campaignToDelete}
|
||||
isDeleting={deleteCampaign?.isPending || false}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
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
|
||||
Loading…
x
Reference in New Issue
Block a user