This commit is contained in:
efrilm 2025-12-23 13:26:32 +07:00
parent 37de68879c
commit 3cf7799a91
21 changed files with 2487 additions and 5 deletions

View File

@ -0,0 +1,38 @@
import DiscountAddHeader from '@/views/apps/marketing/discount/add/DiscountAddHeader'
import DiscountInformation from '@/views/apps/marketing/discount/add/DiscountAddInformation'
import DiscountOutlets from '@/views/apps/marketing/discount/add/DiscountAddOutlets'
import DiscountRules from '@/views/apps/marketing/discount/add/DiscountAddRule'
import DiscountSettings from '@/views/apps/marketing/discount/add/DiscountAddSetting'
import Grid from '@mui/material/Grid2'
const DiscountsAddPage = () => {
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<DiscountAddHeader />
</Grid>
<Grid size={{ xs: 12, md: 8 }}>
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<DiscountInformation />
</Grid>
<Grid size={{ xs: 12 }}>
<DiscountRules />
</Grid>
</Grid>
</Grid>
<Grid size={{ xs: 12, md: 4 }}>
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<DiscountSettings />
</Grid>
<Grid size={{ xs: 12 }}>
<DiscountOutlets />
</Grid>
</Grid>
</Grid>
</Grid>
)
}
export default DiscountsAddPage

View File

@ -0,0 +1,7 @@
import DiscountList from '@/views/apps/marketing/discount'
const DiscountPage = () => {
return <DiscountList />
}
export default DiscountPage

View File

@ -173,6 +173,7 @@ const VerticalMenu = ({ dictionary, scrollMenu }: Props) => {
</MenuItem> */} </MenuItem> */}
{/* <MenuItem href={`/${locale}/apps/marketing/voucher`}>{dictionary['navigation'].voucher}</MenuItem> */} {/* <MenuItem href={`/${locale}/apps/marketing/voucher`}>{dictionary['navigation'].voucher}</MenuItem> */}
<MenuItem href={`/${locale}/apps/marketing/tier`}>{dictionary['navigation'].tiers_text}</MenuItem> <MenuItem href={`/${locale}/apps/marketing/tier`}>{dictionary['navigation'].tiers_text}</MenuItem>
<MenuItem href={`/${locale}/apps/marketing/discount`}>{dictionary['navigation'].discount}</MenuItem>
</SubMenu> </SubMenu>
<SubMenu label={dictionary['navigation'].inventory} icon={<i className='tabler-salad' />}> <SubMenu label={dictionary['navigation'].inventory} icon={<i className='tabler-salad' />}>
<SubMenu label={dictionary['navigation'].products}> <SubMenu label={dictionary['navigation'].products}>

View File

@ -137,6 +137,7 @@
"voucher": "Voucher", "voucher": "Voucher",
"tiers_text": "Tiers", "tiers_text": "Tiers",
"games": "Games", "games": "Games",
"game_prizes": "Game Prizes" "game_prizes": "Game Prizes",
"discount": "Discount"
} }
} }

View File

@ -137,6 +137,7 @@
"voucher": "Vocher", "voucher": "Vocher",
"tiers_text": "Tiers", "tiers_text": "Tiers",
"games": "Permainan", "games": "Permainan",
"game_prizes": "Hadiah Permainan" "game_prizes": "Hadiah Permainan",
"Discount": "Diskon"
} }
} }

View File

@ -10,6 +10,7 @@ import productRecipeReducer from '@/redux-store/slices/productRecipe'
import organizationReducer from '@/redux-store/slices/organization' import organizationReducer from '@/redux-store/slices/organization'
import userReducer from '@/redux-store/slices/user' import userReducer from '@/redux-store/slices/user'
import vendorReducer from '@/redux-store/slices/vendor' import vendorReducer from '@/redux-store/slices/vendor'
import discountReducer from '@/redux-store/slices/discount'
export const store = configureStore({ export const store = configureStore({
reducer: { reducer: {
@ -21,7 +22,8 @@ export const store = configureStore({
productRecipeReducer, productRecipeReducer,
organizationReducer, organizationReducer,
userReducer, userReducer,
vendorReducer vendorReducer,
discountReducer
}, },
middleware: getDefaultMiddleware => getDefaultMiddleware({ serializableCheck: false }) middleware: getDefaultMiddleware => getDefaultMiddleware({ serializableCheck: false })
}) })

View File

@ -0,0 +1,193 @@
// redux-store/slices/discount.ts
import { CategoryRuleType, CreateDiscountPayload, ProductRuleType } from '@/types/services/discount'
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
// Temporary interfaces for rules before discount is created
interface TempProductRule {
product_id: string
product_name?: string
rule_type: ProductRuleType
quantity: number
free_quantity: number
}
interface TempCategoryRule {
category_id: string
category_name?: string
rule_type: CategoryRuleType
}
interface DiscountState {
discountRequest: CreateDiscountPayload
selectedOutlets: string[]
productRules: TempProductRule[]
categoryRules: TempCategoryRule[]
}
const initialState: DiscountState = {
discountRequest: {
campaign_id: '',
code: '',
name: '',
type: 'percentage',
value: 0,
min_purchase_amount: 0,
min_purchase_qty: 0,
start_date: '',
end_date: '',
usage_limit_per_customer: undefined,
usage_limit_total: undefined,
customer_type: 'all',
is_stackable: false,
priority: 10
},
selectedOutlets: [],
productRules: [],
categoryRules: []
}
const discountSlice = createSlice({
name: 'discount',
initialState,
reducers: {
// Set entire discount object
setDiscount: (state, action: PayloadAction<CreateDiscountPayload>) => {
state.discountRequest = action.payload
},
// Set individual field
setDiscountField: (state, action: PayloadAction<{ field: keyof CreateDiscountPayload; value: any }>) => {
const { field, value } = action.payload
state.discountRequest[field] = value as never
},
// Reset discount to initial state
resetDiscount: state => {
state.discountRequest = initialState.discountRequest
state.selectedOutlets = []
state.productRules = []
state.categoryRules = []
},
// Outlet management
setDiscountOutlets: (state, action: PayloadAction<string[]>) => {
state.selectedOutlets = action.payload
},
addDiscountOutlet: (state, action: PayloadAction<string>) => {
if (!state.selectedOutlets.includes(action.payload)) {
state.selectedOutlets.push(action.payload)
}
},
removeDiscountOutlet: (state, action: PayloadAction<string>) => {
state.selectedOutlets = state.selectedOutlets.filter(id => id !== action.payload)
},
// Product rules management
setProductRules: (state, action: PayloadAction<TempProductRule[]>) => {
state.productRules = action.payload
},
addProductRule: (state, action: PayloadAction<TempProductRule>) => {
state.productRules.push(action.payload)
},
updateProductRule: (state, action: PayloadAction<{ index: number; rule: TempProductRule }>) => {
const { index, rule } = action.payload
if (index >= 0 && index < state.productRules.length) {
state.productRules[index] = rule
}
},
removeProductRule: (state, action: PayloadAction<number>) => {
state.productRules = state.productRules.filter((_, index) => index !== action.payload)
},
clearProductRules: state => {
state.productRules = []
},
// Category rules management
setCategoryRules: (state, action: PayloadAction<TempCategoryRule[]>) => {
state.categoryRules = action.payload
},
addCategoryRule: (state, action: PayloadAction<TempCategoryRule>) => {
state.categoryRules.push(action.payload)
},
updateCategoryRule: (state, action: PayloadAction<{ index: number; rule: TempCategoryRule }>) => {
const { index, rule } = action.payload
if (index >= 0 && index < state.categoryRules.length) {
state.categoryRules[index] = rule
}
},
removeCategoryRule: (state, action: PayloadAction<number>) => {
state.categoryRules = state.categoryRules.filter((_, index) => index !== action.payload)
},
clearCategoryRules: state => {
state.categoryRules = []
},
// Bulk operations
clearAllRules: state => {
state.productRules = []
state.categoryRules = []
},
// Set multiple fields at once
setDiscountFields: (state, action: PayloadAction<Partial<CreateDiscountPayload>>) => {
state.discountRequest = { ...state.discountRequest, ...action.payload }
}
}
})
export const {
setDiscount,
setDiscountField,
resetDiscount,
setDiscountOutlets,
addDiscountOutlet,
removeDiscountOutlet,
setProductRules,
addProductRule,
updateProductRule,
removeProductRule,
clearProductRules,
setCategoryRules,
addCategoryRule,
updateCategoryRule,
removeCategoryRule,
clearCategoryRules,
clearAllRules,
setDiscountFields
} = discountSlice.actions
export default discountSlice.reducer
// Selectors (optional but recommended)
export const selectDiscountRequest = (state: { discountReducer: DiscountState }) =>
state.discountReducer.discountRequest
export const selectSelectedOutlets = (state: { discountReducer: DiscountState }) =>
state.discountReducer.selectedOutlets
export const selectProductRules = (state: { discountReducer: DiscountState }) => state.discountReducer.productRules
export const selectCategoryRules = (state: { discountReducer: DiscountState }) => state.discountReducer.categoryRules
export const selectIsDiscountValid = (state: { discountReducer: DiscountState }) => {
const { discountRequest } = state.discountReducer
return (
discountRequest.campaign_id !== '' &&
discountRequest.code !== '' &&
discountRequest.name !== '' &&
discountRequest.start_date !== '' &&
discountRequest.end_date !== '' &&
(discountRequest.type === 'free_product' || discountRequest.value > 0)
)
}

View File

@ -6,8 +6,8 @@ const getToken = () => {
} }
export const api = axios.create({ export const api = axios.create({
baseURL: 'https://api-pos.apskel.id/api/v1', // baseURL: 'https://api-pos.apskel.id/api/v1',
// baseURL: 'http://127.0.0.1:4000/api/v1', baseURL: 'http://127.0.0.1:4000/api/v1',
headers: { headers: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },

View File

@ -0,0 +1,287 @@
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { api } from '../api'
import { toast } from 'react-toastify'
import {
CreateDiscountPayload,
UpdateDiscountPayload,
AddOutletsPayload,
ReplaceOutletsPayload,
AddProductRulePayload,
UpdateProductRulePayload,
AddCategoryRulePayload,
UpdateCategoryRulePayload,
Discount,
DiscountOutlet,
ProductRule,
CategoryRule
} from '@/types/services/discount'
export const useDiscountsMutation = () => {
const queryClient = useQueryClient()
const createDiscount = useMutation({
mutationFn: async (payload: CreateDiscountPayload) => {
const response = await api.post('/discounts', payload)
return response.data
},
onSuccess: () => {
toast.success('Discount created successfully!')
queryClient.invalidateQueries({ queryKey: ['discounts'] })
},
onError: (error: any) => {
toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
}
})
const updateDiscount = useMutation({
mutationFn: async ({ id, payload }: { id: string; payload: UpdateDiscountPayload }) => {
const response = await api.put(`/discounts/${id}`, payload)
return response.data
},
onSuccess: () => {
toast.success('Discount updated successfully!')
queryClient.invalidateQueries({ queryKey: ['discounts'] })
queryClient.invalidateQueries({ queryKey: ['discount'] })
},
onError: (error: any) => {
toast.error(error.response?.data?.errors?.[0]?.cause || 'Update failed')
}
})
const toggleDiscountStatus = useMutation({
mutationFn: async ({ id, isActive }: { id: string; isActive: boolean }) => {
const response = await api.patch(`/discounts/${id}/toggle-status`, { is_active: isActive })
return response.data
},
onSuccess: () => {
toast.success('Discount status updated!')
queryClient.invalidateQueries({ queryKey: ['discounts'] })
queryClient.invalidateQueries({ queryKey: ['discount'] })
},
onError: (error: any) => {
toast.error(error.response?.data?.errors?.[0]?.cause || 'Status update failed')
}
})
const deleteDiscount = useMutation({
mutationFn: async (id: string) => {
const response = await api.delete(`/discounts/${id}`)
return response.data
},
onSuccess: () => {
toast.success('Discount deleted successfully!')
queryClient.invalidateQueries({ queryKey: ['discounts'] })
},
onError: (error: any) => {
toast.error(error.response?.data?.errors?.[0]?.cause || 'Delete failed')
}
})
const validateDiscount = useMutation({
mutationFn: async ({
code,
purchaseAmount,
customerId
}: {
code: string
purchaseAmount: number
customerId?: string
}) => {
const response = await api.post('/discounts/validate', {
code,
purchase_amount: purchaseAmount,
customer_id: customerId
})
return response.data
},
onError: (error: any) => {
toast.error(error.response?.data?.message || 'Validation failed')
}
})
return {
createDiscount,
updateDiscount,
toggleDiscountStatus,
deleteDiscount,
validateDiscount
}
}
export const useDiscountOutletsMutation = () => {
const queryClient = useQueryClient()
const addOutlets = useMutation({
mutationFn: async ({ discountId, payload }: { discountId: string; payload: AddOutletsPayload }) => {
const response = await api.post(`/discounts/${discountId}/outlets`, payload)
return response.data
},
onSuccess: (_, variables) => {
toast.success('Outlets added successfully!')
queryClient.invalidateQueries({
queryKey: ['discount', variables.discountId, 'outlets']
})
},
onError: (error: any) => {
toast.error(error.response?.data?.errors?.[0]?.cause || 'Add outlets failed')
}
})
const replaceOutlets = useMutation({
mutationFn: async ({ discountId, payload }: { discountId: string; payload: ReplaceOutletsPayload }) => {
const response = await api.put(`/discounts/${discountId}/outlets`, payload)
return response.data
},
onSuccess: (_, variables) => {
toast.success('Outlets replaced successfully!')
queryClient.invalidateQueries({
queryKey: ['discount', variables.discountId, 'outlets']
})
},
onError: (error: any) => {
toast.error(error.response?.data?.errors?.[0]?.cause || 'Replace outlets failed')
}
})
const removeOutlet = useMutation({
mutationFn: async ({ discountId, outletId }: { discountId: string; outletId: string }) => {
const response = await api.delete(`/discounts/${discountId}/outlets/${outletId}`)
return response.data
},
onSuccess: (_, variables) => {
toast.success('Outlet removed successfully!')
queryClient.invalidateQueries({
queryKey: ['discount', variables.discountId, 'outlets']
})
},
onError: (error: any) => {
toast.error(error.response?.data?.errors?.[0]?.cause || 'Remove outlet failed')
}
})
return { addOutlets, replaceOutlets, removeOutlet }
}
export const useProductRulesMutation = () => {
const queryClient = useQueryClient()
const addProductRule = useMutation({
mutationFn: async ({ discountId, payload }: { discountId: string; payload: AddProductRulePayload }) => {
const response = await api.post(`/discounts/${discountId}/products`, payload)
return response.data
},
onSuccess: (_, variables) => {
toast.success('Product rule added successfully!')
queryClient.invalidateQueries({
queryKey: ['discount', variables.discountId, 'product-rules']
})
},
onError: (error: any) => {
toast.error(error.response?.data?.errors?.[0]?.cause || 'Add product rule failed')
}
})
const updateProductRule = useMutation({
mutationFn: async ({
discountId,
productRuleId,
payload
}: {
discountId: string
productRuleId: string
payload: UpdateProductRulePayload
}) => {
const response = await api.put(`/discounts/${discountId}/products/${productRuleId}`, payload)
return response.data
},
onSuccess: (_, variables) => {
toast.success('Product rule updated successfully!')
queryClient.invalidateQueries({
queryKey: ['discount', variables.discountId, 'product-rules']
})
},
onError: (error: any) => {
toast.error(error.response?.data?.errors?.[0]?.cause || 'Update product rule failed')
}
})
const deleteProductRule = useMutation({
mutationFn: async ({ discountId, productRuleId }: { discountId: string; productRuleId: string }) => {
const response = await api.delete(`/discounts/${discountId}/products/${productRuleId}`)
return response.data
},
onSuccess: (_, variables) => {
toast.success('Product rule deleted successfully!')
queryClient.invalidateQueries({
queryKey: ['discount', variables.discountId, 'product-rules']
})
},
onError: (error: any) => {
toast.error(error.response?.data?.errors?.[0]?.cause || 'Delete product rule failed')
}
})
return { addProductRule, updateProductRule, deleteProductRule }
}
export const useCategoryRulesMutation = () => {
const queryClient = useQueryClient()
const addCategoryRule = useMutation({
mutationFn: async ({ discountId, payload }: { discountId: string; payload: AddCategoryRulePayload }) => {
const response = await api.post(`/discounts/${discountId}/categories`, payload)
return response.data
},
onSuccess: (_, variables) => {
toast.success('Category rule added successfully!')
queryClient.invalidateQueries({
queryKey: ['discount', variables.discountId, 'category-rules']
})
},
onError: (error: any) => {
toast.error(error.response?.data?.errors?.[0]?.cause || 'Add category rule failed')
}
})
const updateCategoryRule = useMutation({
mutationFn: async ({
discountId,
categoryRuleId,
payload
}: {
discountId: string
categoryRuleId: string
payload: UpdateCategoryRulePayload
}) => {
const response = await api.put(`/discounts/${discountId}/categories/${categoryRuleId}`, payload)
return response.data
},
onSuccess: (_, variables) => {
toast.success('Category rule updated successfully!')
queryClient.invalidateQueries({
queryKey: ['discount', variables.discountId, 'category-rules']
})
},
onError: (error: any) => {
toast.error(error.response?.data?.errors?.[0]?.cause || 'Update category rule failed')
}
})
const deleteCategoryRule = useMutation({
mutationFn: async ({ discountId, categoryRuleId }: { discountId: string; categoryRuleId: string }) => {
const response = await api.delete(`/discounts/${discountId}/categories/${categoryRuleId}`)
return response.data
},
onSuccess: (_, variables) => {
toast.success('Category rule deleted successfully!')
queryClient.invalidateQueries({
queryKey: ['discount', variables.discountId, 'category-rules']
})
},
onError: (error: any) => {
toast.error(error.response?.data?.errors?.[0]?.cause || 'Delete category rule failed')
}
})
return { addCategoryRule, updateCategoryRule, deleteCategoryRule }
}

View File

@ -0,0 +1,116 @@
import { useQuery } from '@tanstack/react-query'
import { api } from '../api'
import {
CategoryRule,
Discount,
DiscountOutlet,
DiscountsResponse,
FetchDiscountsParams,
ProductRule
} from '@/types/services/discount'
export function useDiscounts(params: FetchDiscountsParams = {}) {
const { page = 1, limit = 10, search = '', ...filters } = params
return useQuery<DiscountsResponse>({
queryKey: ['discounts', { 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(`/discounts?${queryParams.toString()}`)
console.log(res.data.data)
return res.data.data
}
})
}
export function useAllDiscounts() {
return useQuery<Discount[]>({
queryKey: ['discounts', 'all'],
queryFn: async () => {
const res = await api.get('/discounts?page=1&limit=100')
return res.data.discounts
}
})
}
export function useDiscountsByCampaign(campaignId: string) {
return useQuery<Discount[]>({
queryKey: ['discounts', 'campaign', campaignId],
queryFn: async () => {
const res = await api.get(`/discounts?campaign_id=${campaignId}&limit=100`)
return res.data.discounts
},
enabled: !!campaignId
})
}
export function useDiscountById(id: string) {
return useQuery<Discount>({
queryKey: ['discount', id],
queryFn: async () => {
const res = await api.get(`/discounts/${id}`)
return res.data
},
enabled: !!id,
staleTime: 5 * 60 * 1000
})
}
export function useDiscountByCode(code: string) {
return useQuery<Discount>({
queryKey: ['discount', 'code', code],
queryFn: async () => {
const res = await api.get(`/discounts/code/${code}`)
return res.data
},
enabled: !!code,
staleTime: 5 * 60 * 1000
})
}
export function useDiscountOutlets(discountId: string) {
return useQuery<DiscountOutlet[]>({
queryKey: ['discount', discountId, 'outlets'],
queryFn: async () => {
const res = await api.get(`/discounts/${discountId}/outlets`)
return res.data
},
enabled: !!discountId
})
}
export function useProductRules(discountId: string) {
return useQuery<ProductRule[]>({
queryKey: ['discount', discountId, 'product-rules'],
queryFn: async () => {
const res = await api.get(`/discounts/${discountId}/products`)
return res.data
},
enabled: !!discountId
})
}
export function useCategoryRules(discountId: string) {
return useQuery<CategoryRule[]>({
queryKey: ['discount', discountId, 'category-rules'],
queryFn: async () => {
const res = await api.get(`/discounts/${discountId}/categories`)
return res.data
},
enabled: !!discountId
})
}

View File

@ -0,0 +1,215 @@
/**
* Discount type enum
*/
export type DiscountType = 'percentage' | 'fixed_amout' | 'free_product'
/**
* Customer type enum
*/
export type CustomerType = 'all' | 'member' | 'vip'
/**
* Product rule type enum
*/
export type ProductRuleType = 'required' | 'free' | 'excluded'
/**
* Category rule type enum
*/
export type CategoryRuleType = 'included' | 'excluded'
/**
* Discount interface
*/
export interface Discount {
id: string
campaign_id: string
code: string
name: string
type: DiscountType
value: number
min_purchase_qty: number
min_purchase_amount: number
start_date: string
end_date: string
usage_limit_per_customer: number | null
usage_limit_total: number | null
usage_count: number
customer_type: CustomerType
is_stackable: boolean
is_active: boolean
priority: number
created_at: string
updated_at: string
}
/**
* Discount Outlet interface
*/
export interface DiscountOutlet {
id: string
discount_id: string
outlet_id: string
created_at: string
}
/**
* Product Rule interface
*/
export interface ProductRule {
id: string
discount_id: string
product_id: string
rule_type: ProductRuleType
quantity: number
free_quantity: number
created_at: string
}
/**
* Category Rule interface
*/
export interface CategoryRule {
id: string
discount_id: string
category_id: string
rule_type: CategoryRuleType
created_at: string
}
/**
* Pagination metadata
*/
export interface Pagination {
page: number
limit: number
total_count: number
total_pages: number
}
/**
* Discounts response with pagination
*/
export interface DiscountsResponse {
discounts: Discount[]
pagination: Pagination
}
/**
* Fetch discounts parameters
*/
export interface FetchDiscountsParams {
page?: number
limit?: number
sort?: string
order?: 'asc' | 'desc'
search?: string
campaign_id?: string
type?: DiscountType
customer_type?: CustomerType
is_active?: boolean
}
/**
* Create discount payload
*/
export interface CreateDiscountPayload {
campaign_id: string
code: string
name: string
type: DiscountType
value: number
min_purchase_amount?: number
min_purchase_qty?: number
start_date: string
end_date: string
usage_limit_per_customer?: number
usage_limit_total?: number
customer_type: CustomerType
is_stackable: boolean
priority: number
}
/**
* Update discount payload
*/
export interface UpdateDiscountPayload {
campaign_id?: string
code?: string
name?: string
type?: DiscountType
value?: number
min_purchase_amount?: number
min_purchase_qty?: number
start_date?: string
end_date?: string
usage_limit_per_customer?: number
usage_limit_total?: number
customer_type?: CustomerType
is_stackable?: boolean
is_active?: boolean
priority?: number
}
/**
* Add outlets payload
*/
export interface AddOutletsPayload {
outlet_ids: string[]
}
/**
* Replace outlets payload
*/
export interface ReplaceOutletsPayload {
outlet_ids: string[]
}
/**
* Add product rule payload
*/
export interface AddProductRulePayload {
product_id: string
rule_type: ProductRuleType
quantity?: number
free_quantity?: number
}
/**
* Update product rule payload
*/
export interface UpdateProductRulePayload {
rule_type: ProductRuleType
quantity?: number
free_quantity?: number
}
/**
* Add category rule payload
*/
export interface AddCategoryRulePayload {
category_id: string
rule_type: CategoryRuleType
}
/**
* Update category rule payload
*/
export interface UpdateCategoryRulePayload {
rule_type: CategoryRuleType
}
/**
* Discount State for Redux
*/
export interface DiscountState {
discounts: Discount[]
allDiscounts: Discount[]
discountsPagination: Pagination | null
selectedDiscount: Discount | null
discountOutlets: DiscountOutlet[]
productRules: ProductRule[]
categoryRules: CategoryRule[]
loading: boolean
error: string | null
}

View File

@ -0,0 +1,171 @@
'use client'
import { useState, useEffect } from 'react'
import Button from '@mui/material/Button'
import Divider from '@mui/material/Divider'
import Drawer from '@mui/material/Drawer'
import IconButton from '@mui/material/IconButton'
import Typography from '@mui/material/Typography'
import Radio from '@mui/material/Radio'
import RadioGroup from '@mui/material/RadioGroup'
import FormControlLabel from '@mui/material/FormControlLabel'
import MenuItem from '@mui/material/MenuItem'
import CustomTextField from '@core/components/mui/TextField'
import { useCategories } from '@/services/queries/categories'
import { CategoryRuleType } from '@/types/services/discount'
interface CategoryRule {
category_id: string
category_name?: string
rule_type: CategoryRuleType
}
type Props = {
open: boolean
onClose: () => void
onConfirm: (rule: CategoryRule) => void
}
const CategoryRuleDialog = (props: Props) => {
const { open, onClose, onConfirm } = props
const [selectedCategory, setSelectedCategory] = useState('')
const [ruleType, setRuleType] = useState<CategoryRuleType>('included')
const [searchQuery, setSearchQuery] = useState('')
const { data: categoriesData } = useCategories({ page: 1, limit: 100 })
const categories = categoriesData?.categories ?? []
useEffect(() => {
if (open) {
setSelectedCategory('')
setRuleType('included')
setSearchQuery('')
}
}, [open])
const filteredCategories = categories.filter(category =>
category.name.toLowerCase().includes(searchQuery.toLowerCase())
)
const handleConfirm = () => {
if (!selectedCategory) return
const category = categories.find(c => c.id === selectedCategory)
onConfirm({
category_id: selectedCategory,
category_name: category?.name,
rule_type: ruleType
})
handleReset()
}
const handleReset = () => {
setSelectedCategory('')
setRuleType('included')
setSearchQuery('')
onClose()
}
return (
<Drawer
open={open}
anchor='right'
variant='temporary'
onClose={handleReset}
ModalProps={{ keepMounted: true }}
sx={{ '& .MuiDrawer-paper': { width: { xs: 300, sm: 500 } } }}
>
<div className='flex items-center justify-between pli-6 plb-5'>
<Typography variant='h5'>Add Category Rule</Typography>
<IconButton size='small' onClick={handleReset}>
<i className='tabler-x text-textSecondary text-2xl' />
</IconButton>
</div>
<Divider />
<div className='p-6'>
<div className='flex flex-col gap-5'>
{/* Category Search & Select */}
<div>
<Typography variant='body2' className='mbe-2'>
Select Category *
</Typography>
<CustomTextField
fullWidth
placeholder='Search category...'
value={searchQuery}
onChange={e => setSearchQuery(e.target.value)}
className='mbe-2'
/>
<div className='max-h-48 overflow-y-auto border rounded'>
{filteredCategories.length === 0 ? (
<div className='text-center py-4'>
<Typography variant='body2' color='text.secondary'>
No categories found
</Typography>
</div>
) : (
<RadioGroup value={selectedCategory} onChange={e => setSelectedCategory(e.target.value)}>
{filteredCategories.map(category => (
<div
key={category.id}
className='flex items-center p-3 hover:bg-actionHover cursor-pointer border-b last:border-b-0'
onClick={() => setSelectedCategory(category.id)}
>
<FormControlLabel
value={category.id}
control={<Radio />}
label={
<div>
<Typography variant='body1'>{category.name}</Typography>
{category.description && (
<Typography variant='body2' color='text.secondary'>
{category.description}
</Typography>
)}
</div>
}
sx={{ margin: 0, width: '100%' }}
/>
</div>
))}
</RadioGroup>
)}
</div>
</div>
{/* Rule Type */}
<CustomTextField
select
fullWidth
label='Rule Type *'
value={ruleType}
onChange={e => setRuleType(e.target.value as CategoryRuleType)}
>
<MenuItem value='included'>Included (Apply discount)</MenuItem>
<MenuItem value='excluded'>Excluded (No discount)</MenuItem>
</CustomTextField>
<Typography variant='caption' color='text.secondary' className='-mbs-4'>
{ruleType === 'included' && 'Only products in this category can get discount'}
{ruleType === 'excluded' && 'Products in this category will not get discount'}
</Typography>
{/* Action Buttons */}
<div className='flex items-center gap-4'>
<Button variant='contained' onClick={handleConfirm} disabled={!selectedCategory}>
Add Rule
</Button>
<Button variant='tonal' color='error' onClick={handleReset}>
Cancel
</Button>
</div>
</div>
</div>
</Drawer>
)
}
export default CategoryRuleDialog

View File

@ -0,0 +1,144 @@
'use client'
import CustomTextField from '@/@core/components/mui/TextField'
import { useOutlets } from '@/services/queries/outlets'
import { Button, Checkbox, Divider, Drawer, FormControlLabel, IconButton, Typography } from '@mui/material'
import { useEffect, useState } from 'react'
type Props = {
open: boolean
onClose: () => void
selectedOutlets: string[]
onConfirm: (outletIds: string[]) => void
}
const OutletSelectionDialog = (props: Props) => {
const { open, onClose, selectedOutlets, onConfirm } = props
const [selected, setSelected] = useState<string[]>(selectedOutlets)
const [searchQuery, setSearchQuery] = useState('')
const { data: outletsData } = useOutlets({ page: 1, limit: 100 })
const outlets = outletsData?.outlets ?? []
useEffect(() => {
if (open) {
setSelected(selectedOutlets)
setSearchQuery('')
}
}, [open, selectedOutlets])
const filteredOutlets = outlets.filter(outlet => outlet.name.toLowerCase().includes(searchQuery.toLowerCase()))
const handleToggle = (outletId: string) => {
if (selected.includes(outletId)) {
setSelected(selected.filter(id => id !== outletId))
} else {
setSelected([...selected, outletId])
}
}
const handleSelectAll = () => {
if (selected.length === filteredOutlets.length) {
setSelected([])
} else {
setSelected(filteredOutlets.map(o => o.id))
}
}
const handleConfirm = () => {
onConfirm(selected)
onClose()
}
const handleReset = () => {
setSelected(selectedOutlets)
setSearchQuery('')
onClose()
}
return (
<Drawer
open={open}
anchor='right'
variant='temporary'
onClose={handleReset}
ModalProps={{ keepMounted: true }}
sx={{ '& .MuiDrawer-paper': { width: { xs: 300, sm: 500 } } }}
>
<div className='flex items-center justify-between pli-6 plb-5'>
<Typography variant='h5'>Select Outlets</Typography>
<IconButton size='small' onClick={handleReset}>
<i className='tabler-x text-textSecondary text-2xl' />
</IconButton>
</div>
<Divider />
<div className='p-6'>
{/* Search */}
<CustomTextField
fullWidth
placeholder='Search outlets...'
value={searchQuery}
onChange={e => setSearchQuery(e.target.value)}
className='mbe-4'
/>
{/* Select All */}
<div className='flex items-center justify-between mbe-4'>
<Button variant='text' size='small' onClick={handleSelectAll}>
{selected.length === filteredOutlets.length ? 'Deselect All' : 'Select All'}
</Button>
<Typography variant='body2' color='text.secondary'>
{selected.length} selected
</Typography>
</div>
{/* Outlet List */}
<div className='max-h-[400px] overflow-y-auto border rounded'>
{filteredOutlets.length === 0 ? (
<div className='text-center py-8'>
<Typography variant='body2' color='text.secondary'>
No outlets found
</Typography>
</div>
) : (
filteredOutlets.map(outlet => (
<div
key={outlet.id}
className='flex items-center p-3 hover:bg-actionHover cursor-pointer border-b last:border-b-0'
onClick={() => handleToggle(outlet.id)}
>
<FormControlLabel
control={<Checkbox checked={selected.includes(outlet.id)} />}
label={
<div>
<Typography variant='body1'>{outlet.name}</Typography>
{outlet.address && (
<Typography variant='body2' color='text.secondary'>
{outlet.address}
</Typography>
)}
</div>
}
sx={{ margin: 0, width: '100%' }}
/>
</div>
))
)}
</div>
{/* Action Buttons */}
<div className='flex items-center gap-4 mbs-6'>
<Button variant='contained' onClick={handleConfirm}>
Confirm ({selected.length})
</Button>
<Button variant='tonal' color='error' onClick={handleReset}>
Cancel
</Button>
</div>
</div>
</Drawer>
)
}
export default OutletSelectionDialog

View File

@ -0,0 +1,204 @@
'use client'
import { useState, useEffect } from 'react'
import Button from '@mui/material/Button'
import Divider from '@mui/material/Divider'
import Drawer from '@mui/material/Drawer'
import IconButton from '@mui/material/IconButton'
import Typography from '@mui/material/Typography'
import Radio from '@mui/material/Radio'
import RadioGroup from '@mui/material/RadioGroup'
import FormControlLabel from '@mui/material/FormControlLabel'
import MenuItem from '@mui/material/MenuItem'
import CustomTextField from '@core/components/mui/TextField'
import { useProducts } from '@/services/queries/products'
import { ProductRuleType } from '@/types/services/discount'
interface ProductRule {
product_id: string
product_name?: string
rule_type: ProductRuleType
quantity: number
free_quantity: number
}
type Props = {
open: boolean
onClose: () => void
onConfirm: (rule: ProductRule) => void
}
const ProductRuleDialog = (props: Props) => {
const { open, onClose, onConfirm } = props
const [selectedProduct, setSelectedProduct] = useState('')
const [ruleType, setRuleType] = useState<ProductRuleType>('required')
const [quantity, setQuantity] = useState(1)
const [freeQuantity, setFreeQuantity] = useState(0)
const [searchQuery, setSearchQuery] = useState('')
const { data: productsData } = useProducts({ page: 1, limit: 100 })
const products = productsData?.products ?? []
useEffect(() => {
if (open) {
setSelectedProduct('')
setRuleType('required')
setQuantity(1)
setFreeQuantity(0)
setSearchQuery('')
}
}, [open])
const filteredProducts = products.filter(product => product.name.toLowerCase().includes(searchQuery.toLowerCase()))
const handleConfirm = () => {
if (!selectedProduct) return
const product = products.find(p => p.id === selectedProduct)
onConfirm({
product_id: selectedProduct,
product_name: product?.name,
rule_type: ruleType,
quantity,
free_quantity: ruleType === 'free' ? freeQuantity : 0
})
handleReset()
}
const handleReset = () => {
setSelectedProduct('')
setRuleType('required')
setQuantity(1)
setFreeQuantity(0)
setSearchQuery('')
onClose()
}
return (
<Drawer
open={open}
anchor='right'
variant='temporary'
onClose={handleReset}
ModalProps={{ keepMounted: true }}
sx={{ '& .MuiDrawer-paper': { width: { xs: 300, sm: 500 } } }}
>
<div className='flex items-center justify-between pli-6 plb-5'>
<Typography variant='h5'>Add Product Rule</Typography>
<IconButton size='small' onClick={handleReset}>
<i className='tabler-x text-textSecondary text-2xl' />
</IconButton>
</div>
<Divider />
<div className='p-6'>
<div className='flex flex-col gap-5'>
{/* Product Search & Select */}
<div>
<Typography variant='body2' className='mbe-2'>
Select Product *
</Typography>
<CustomTextField
fullWidth
placeholder='Search product...'
value={searchQuery}
onChange={e => setSearchQuery(e.target.value)}
className='mbe-2'
/>
<div className='max-h-48 overflow-y-auto border rounded'>
{filteredProducts.length === 0 ? (
<div className='text-center py-4'>
<Typography variant='body2' color='text.secondary'>
No products found
</Typography>
</div>
) : (
<RadioGroup value={selectedProduct} onChange={e => setSelectedProduct(e.target.value)}>
{filteredProducts.map(product => (
<div
key={product.id}
className='flex items-center p-3 hover:bg-actionHover cursor-pointer border-b last:border-b-0'
onClick={() => setSelectedProduct(product.id)}
>
<FormControlLabel
value={product.id}
control={<Radio />}
label={
<div>
<Typography variant='body1'>{product.name}</Typography>
<Typography variant='body2' color='text.secondary'>
SKU: {product.sku}
</Typography>
</div>
}
sx={{ margin: 0, width: '100%' }}
/>
</div>
))}
</RadioGroup>
)}
</div>
</div>
{/* Rule Type */}
<CustomTextField
select
fullWidth
label='Rule Type *'
value={ruleType}
onChange={e => setRuleType(e.target.value as ProductRuleType)}
>
<MenuItem value='required'>Required (Must buy)</MenuItem>
<MenuItem value='free'>Free (Get free)</MenuItem>
<MenuItem value='excluded'>Excluded (No discount)</MenuItem>
</CustomTextField>
<Typography variant='caption' color='text.secondary' className='-mbs-4'>
{ruleType === 'required' && 'Product must be in cart to get discount'}
{ruleType === 'free' && 'Product will be given for free when conditions met'}
{ruleType === 'excluded' && 'Product will not get discount'}
</Typography>
{/* Quantity */}
{ruleType !== 'excluded' && (
<CustomTextField
fullWidth
type='number'
label={`${ruleType === 'required' ? 'Minimum ' : ''}Quantity`}
value={quantity}
onChange={e => setQuantity(Number(e.target.value))}
inputProps={{ min: 1 }}
/>
)}
{/* Free Quantity */}
{ruleType === 'free' && (
<CustomTextField
fullWidth
type='number'
label='Free Quantity'
value={freeQuantity}
onChange={e => setFreeQuantity(Number(e.target.value))}
inputProps={{ min: 0 }}
helperText={`Buy ${quantity}, get ${freeQuantity} free`}
/>
)}
{/* Action Buttons */}
<div className='flex items-center gap-4'>
<Button variant='contained' onClick={handleConfirm} disabled={!selectedProduct}>
Add Rule
</Button>
<Button variant='tonal' color='error' onClick={handleReset}>
Cancel
</Button>
</div>
</div>
</div>
</Drawer>
)
}
export default ProductRuleDialog

View File

@ -0,0 +1,88 @@
'use client'
import { useParams, useRouter } from 'next/navigation'
import Button from '@mui/material/Button'
import Typography from '@mui/material/Typography'
import { CircularProgress } from '@mui/material'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/redux-store'
import { getLocalizedUrl } from '@/utils/i18n'
import type { Locale } from '@configs/i18n'
import { useDiscountsMutation } from '@/services/mutations/discount'
import { resetDiscount } from '@/redux-store/slices/discount'
const DiscountAddHeader = () => {
const dispatch = useDispatch()
const params = useParams()
const router = useRouter()
const { lang: locale } = params
const { createDiscount, updateDiscount } = useDiscountsMutation()
const { discountRequest } = useSelector((state: RootState) => state.discountReducer)
const isEdit = !!params?.id
const isCreating = createDiscount.isPending
const isUpdating = updateDiscount.isPending
const handleSubmit = () => {
const payload = {
...discountRequest,
value: Number(discountRequest.value),
min_purchase_amount: Number(discountRequest.min_purchase_amount) || 0,
min_purchase_qty: Number(discountRequest.min_purchase_qty) || 0,
usage_limit_per_customer: discountRequest.usage_limit_per_customer
? Number(discountRequest.usage_limit_per_customer)
: undefined,
usage_limit_total: discountRequest.usage_limit_total ? Number(discountRequest.usage_limit_total) : undefined,
priority: Number(discountRequest.priority),
start_date: discountRequest.start_date ? new Date(discountRequest.start_date + 'T00:00:00').toISOString() : '',
end_date: discountRequest.end_date ? new Date(discountRequest.end_date + 'T23:59:59').toISOString() : ''
}
if (isEdit) {
updateDiscount.mutate(
{ id: params?.id as string, payload },
{
onSuccess: () => {
dispatch(resetDiscount())
router.push(getLocalizedUrl('/apps/marketing/discount', locale as Locale))
}
}
)
} else {
createDiscount.mutate(payload, {
onSuccess: () => {
dispatch(resetDiscount())
router.push(getLocalizedUrl('/apps/marketing/discount', locale as Locale))
}
})
}
}
const handleDiscard = () => {
dispatch(resetDiscount())
router.push(getLocalizedUrl('/apps/marketing/discount', locale as Locale))
}
return (
<div className='flex flex-wrap sm:items-center justify-between max-sm:flex-col gap-6'>
<div>
<Typography variant='h4' className='mbe-1'>
{isEdit ? 'Edit Discount' : 'Add a new discount'}
</Typography>
<Typography>Create promotional discounts for your store</Typography>
</div>
<div className='flex flex-wrap max-sm:flex-col gap-4'>
<Button variant='tonal' color='secondary' onClick={handleDiscard} disabled={isCreating || isUpdating}>
Discard
</Button>
<Button variant='contained' disabled={isCreating || isUpdating} onClick={handleSubmit}>
{isEdit ? 'Update Discount' : 'Publish Discount'}
{(isCreating || isUpdating) && <CircularProgress color='inherit' size={16} className='ml-2' />}
</Button>
</div>
</div>
)
}
export default DiscountAddHeader

View File

@ -0,0 +1,183 @@
'use client'
import { useEffect } from 'react'
import { useParams } from 'next/navigation'
import Grid from '@mui/material/Grid2'
import Card from '@mui/material/Card'
import CardHeader from '@mui/material/CardHeader'
import CardContent from '@mui/material/CardContent'
import MenuItem from '@mui/material/MenuItem'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/redux-store'
import CustomTextField from '@core/components/mui/TextField'
import Loading from '@/components/layout/shared/Loading'
import { useDiscountById } from '@/services/queries/discount'
import { useCampaigns } from '@/services/queries/campaign'
import { resetDiscount, setDiscount, setDiscountField } from '@/redux-store/slices/discount'
const DiscountInformation = () => {
const dispatch = useDispatch()
const params = useParams()
const { data: discount, isLoading } = useDiscountById(params?.id as string)
const { data: campaignsData } = useCampaigns({ page: 1, limit: 100 })
const { discountRequest } = useSelector((state: RootState) => state.discountReducer)
const isEdit = !!params?.id
const campaigns = campaignsData?.campaigns ?? []
useEffect(() => {
if (params?.id) {
if (discount) {
dispatch(
setDiscount({
campaign_id: discount.campaign_id,
code: discount.code,
name: discount.name,
type: discount.type,
value: discount.value,
min_purchase_amount: discount.min_purchase_amount,
min_purchase_qty: discount.min_purchase_qty,
start_date: new Date(discount.start_date).toISOString().split('T')[0],
end_date: new Date(discount.end_date).toISOString().split('T')[0],
usage_limit_per_customer: discount.usage_limit_per_customer ?? 0,
usage_limit_total: discount.usage_limit_total ?? 0,
customer_type: discount.customer_type,
is_stackable: discount.is_stackable,
priority: discount.priority
})
)
}
} else {
dispatch(resetDiscount())
}
}, [params?.id, discount, dispatch])
const handleInputChange = (field: any, value: any) => {
dispatch(setDiscountField({ field, value }))
}
if (isLoading) return <Loading />
return (
<Card>
<CardHeader title='Discount Information' />
<CardContent>
<Grid container spacing={6} className='mbe-6'>
<Grid size={{ xs: 12 }}>
<CustomTextField
select
fullWidth
label='Campaign'
value={discountRequest.campaign_id || ''}
onChange={e => handleInputChange('campaign_id', e.target.value)}
>
<MenuItem value=''>Select Campaign</MenuItem>
{campaigns.map(campaign => (
<MenuItem key={campaign.id} value={campaign.id}>
{campaign.name}
</MenuItem>
))}
</CustomTextField>
</Grid>
<Grid size={{ xs: 12, sm: 6 }}>
<CustomTextField
fullWidth
label='Discount Code'
placeholder='FLASH50'
value={discountRequest.code || ''}
onChange={e => handleInputChange('code', e.target.value.toUpperCase())}
helperText='Only uppercase letters and numbers'
/>
</Grid>
<Grid size={{ xs: 12, sm: 6 }}>
<CustomTextField
fullWidth
label='Discount Name'
placeholder='Flash Sale 50%'
value={discountRequest.name || ''}
onChange={e => handleInputChange('name', e.target.value)}
/>
</Grid>
<Grid size={{ xs: 12, sm: 6 }}>
<CustomTextField
select
fullWidth
label='Discount Type'
value={discountRequest.type || 'percentage'}
onChange={e => handleInputChange('type', e.target.value)}
>
<MenuItem value='percentage'>Percentage (%)</MenuItem>
<MenuItem value='fixed_amount'>Fixed Amount (Rp)</MenuItem>
<MenuItem value='free_product'>Free Product</MenuItem>
</CustomTextField>
</Grid>
{discountRequest.type !== 'free_product' && (
<Grid size={{ xs: 12, sm: 6 }}>
<CustomTextField
fullWidth
type='number'
label={`Discount Value ${discountRequest.type === 'percentage' ? '(%)' : '(Rp)'}`}
placeholder={discountRequest.type === 'percentage' ? '50' : '50000'}
value={discountRequest.value || ''}
onChange={e => handleInputChange('value', e.target.value)}
/>
</Grid>
)}
<Grid size={{ xs: 12, sm: 6 }}>
<CustomTextField
fullWidth
type='number'
label='Minimum Purchase Amount (Rp)'
placeholder='100000'
value={discountRequest.min_purchase_amount || ''}
onChange={e => handleInputChange('min_purchase_amount', e.target.value)}
helperText='Leave 0 if no minimum'
/>
</Grid>
<Grid size={{ xs: 12, sm: 6 }}>
<CustomTextField
fullWidth
type='number'
label='Minimum Purchase Quantity'
placeholder='1'
value={discountRequest.min_purchase_qty || ''}
onChange={e => handleInputChange('min_purchase_qty', e.target.value)}
helperText='Leave 0 if no minimum'
/>
</Grid>
<Grid size={{ xs: 12, sm: 6 }}>
<CustomTextField
fullWidth
type='date'
label='Start Date'
value={discountRequest.start_date || ''}
onChange={e => handleInputChange('start_date', e.target.value)}
InputLabelProps={{ shrink: true }}
/>
</Grid>
<Grid size={{ xs: 12, sm: 6 }}>
<CustomTextField
fullWidth
type='date'
label='End Date'
value={discountRequest.end_date || ''}
onChange={e => handleInputChange('end_date', e.target.value)}
InputLabelProps={{ shrink: true }}
/>
</Grid>
</Grid>
</CardContent>
</Card>
)
}
export default DiscountInformation

View File

@ -0,0 +1,72 @@
'use client'
import { useState } from 'react'
import Card from '@mui/material/Card'
import CardHeader from '@mui/material/CardHeader'
import CardContent from '@mui/material/CardContent'
import Button from '@mui/material/Button'
import Chip from '@mui/material/Chip'
import IconButton from '@mui/material/IconButton'
import Typography from '@mui/material/Typography'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/redux-store'
import { setDiscountOutlets } from '@/redux-store/slices/discount'
import OutletSelectionDialog from './Dialog/OutletSelectionDrawer'
const DiscountOutlets = () => {
const dispatch = useDispatch()
const [openDialog, setOpenDialog] = useState(false)
const { selectedOutlets } = useSelector((state: RootState) => state.discountReducer)
const handleConfirm = (outletIds: string[]) => {
dispatch(setDiscountOutlets(outletIds))
setOpenDialog(false)
}
const handleRemove = (outletId: string) => {
dispatch(setDiscountOutlets(selectedOutlets.filter(id => id !== outletId)))
}
return (
<>
<Card>
<CardHeader
title='Applicable Outlets'
action={
<Button variant='tonal' size='small' onClick={() => setOpenDialog(true)}>
Select Outlets
</Button>
}
/>
<CardContent>
{selectedOutlets.length === 0 ? (
<Typography variant='body2' color='text.secondary' className='text-center py-4'>
No outlets selected. Click "Select Outlets" to add.
</Typography>
) : (
<div className='flex flex-wrap gap-2'>
{selectedOutlets.map(outletId => (
<Chip
key={outletId}
label={`Outlet ${outletId}`}
onDelete={() => handleRemove(outletId)}
color='primary'
variant='tonal'
/>
))}
</div>
)}
</CardContent>
</Card>
<OutletSelectionDialog
open={openDialog}
onClose={() => setOpenDialog(false)}
selectedOutlets={selectedOutlets}
onConfirm={handleConfirm}
/>
</>
)
}
export default DiscountOutlets

View File

@ -0,0 +1,147 @@
'use client'
import { useState } from 'react'
import Card from '@mui/material/Card'
import CardHeader from '@mui/material/CardHeader'
import CardContent from '@mui/material/CardContent'
import Button from '@mui/material/Button'
import Typography from '@mui/material/Typography'
import IconButton from '@mui/material/IconButton'
import Chip from '@mui/material/Chip'
import Divider from '@mui/material/Divider'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/redux-store'
import { removeCategoryRule, removeProductRule, setCategoryRules, setProductRules } from '@/redux-store/slices/discount'
import CategoryRuleDialog from './Dialog/CategoryRuleDialog'
import ProductRuleDialog from './Dialog/ProductRuleDialog'
const DiscountRules = () => {
const dispatch = useDispatch()
const [openProductDialog, setOpenProductDialog] = useState(false)
const [openCategoryDialog, setOpenCategoryDialog] = useState(false)
const { productRules, categoryRules } = useSelector((state: RootState) => state.discountReducer)
const handleAddProductRule = (rule: any) => {
dispatch(setProductRules([...productRules, rule]))
setOpenProductDialog(false)
}
const handleAddCategoryRule = (rule: any) => {
dispatch(setCategoryRules([...categoryRules, rule]))
setOpenCategoryDialog(false)
}
return (
<>
<Card>
<CardHeader title='Discount Rules' />
<CardContent>
{/* Product Rules */}
<div className='mbe-6'>
<div className='flex justify-between items-center mbe-4'>
<Typography variant='h6'>Product Rules</Typography>
<Button
variant='tonal'
size='small'
startIcon={<i className='tabler-plus' />}
onClick={() => setOpenProductDialog(true)}
>
Add Product
</Button>
</div>
{productRules.length === 0 ? (
<Typography
variant='body2'
color='text.secondary'
className='text-center py-4 border border-dashed rounded'
>
No product rules. Click "Add Product" to create rules.
</Typography>
) : (
<div className='flex flex-col gap-3'>
{productRules.map((rule, index) => (
<div key={index} className='flex justify-between items-center p-3 border rounded'>
<div>
<Typography variant='body1' className='font-medium'>
{rule.product_name || `Product ${rule.product_id}`}
</Typography>
<div className='flex gap-2 mbs-2'>
<Chip label={rule.rule_type} size='small' variant='tonal' />
<Chip label={`Qty: ${rule.quantity}`} size='small' variant='outlined' />
{rule.rule_type === 'free' && (
<Chip label={`Free: ${rule.free_quantity}`} size='small' variant='outlined' color='success' />
)}
</div>
</div>
<IconButton size='small' color='error' onClick={() => dispatch(removeProductRule(index))}>
<i className='tabler-trash' />
</IconButton>
</div>
))}
</div>
)}
</div>
<Divider className='mbe-6' />
{/* Category Rules */}
<div>
<div className='flex justify-between items-center mbe-4'>
<Typography variant='h6'>Category Rules</Typography>
<Button
variant='tonal'
size='small'
startIcon={<i className='tabler-plus' />}
onClick={() => setOpenCategoryDialog(true)}
>
Add Category
</Button>
</div>
{categoryRules.length === 0 ? (
<Typography
variant='body2'
color='text.secondary'
className='text-center py-4 border border-dashed rounded'
>
No category rules. Click "Add Category" to create rules.
</Typography>
) : (
<div className='flex flex-col gap-3'>
{categoryRules.map((rule, index) => (
<div key={index} className='flex justify-between items-center p-3 border rounded'>
<div>
<Typography variant='body1' className='font-medium'>
{rule.category_name || `Category ${rule.category_id}`}
</Typography>
<Chip label={rule.rule_type} size='small' variant='tonal' className='mbs-2' />
</div>
<IconButton size='small' color='error' onClick={() => dispatch(removeCategoryRule(index))}>
<i className='tabler-trash' />
</IconButton>
</div>
))}
</div>
)}
</div>
</CardContent>
</Card>
<ProductRuleDialog
open={openProductDialog}
onClose={() => setOpenProductDialog(false)}
onConfirm={handleAddProductRule}
/>
<CategoryRuleDialog
open={openCategoryDialog}
onClose={() => setOpenCategoryDialog(false)}
onConfirm={handleAddCategoryRule}
/>
</>
)
}
export default DiscountRules

View File

@ -0,0 +1,87 @@
'use client'
import Card from '@mui/material/Card'
import CardHeader from '@mui/material/CardHeader'
import CardContent from '@mui/material/CardContent'
import MenuItem from '@mui/material/MenuItem'
import FormControlLabel from '@mui/material/FormControlLabel'
import Switch from '@mui/material/Switch'
import Divider from '@mui/material/Divider'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/redux-store'
import CustomTextField from '@core/components/mui/TextField'
import { setDiscountField } from '@/redux-store/slices/discount'
const DiscountSettings = () => {
const dispatch = useDispatch()
const { discountRequest } = useSelector((state: RootState) => state.discountReducer)
const handleInputChange = (field: any, value: any) => {
dispatch(setDiscountField({ field, value }))
}
return (
<Card>
<CardHeader title='Settings' />
<CardContent className='flex flex-col gap-4'>
<CustomTextField
fullWidth
type='number'
label='Usage Limit Per Customer'
placeholder='5'
value={discountRequest.usage_limit_per_customer || ''}
onChange={e =>
handleInputChange('usage_limit_per_customer', e.target.value ? Number(e.target.value) : undefined)
}
helperText='Leave empty for unlimited'
/>
<CustomTextField
fullWidth
type='number'
label='Total Usage Limit'
placeholder='100'
value={discountRequest.usage_limit_total || ''}
onChange={e => handleInputChange('usage_limit_total', e.target.value ? Number(e.target.value) : undefined)}
helperText='Leave empty for unlimited'
/>
<CustomTextField
select
fullWidth
label='Customer Type'
value={discountRequest.customer_type || 'all'}
onChange={e => handleInputChange('customer_type', e.target.value)}
>
<MenuItem value='all'>All Customers</MenuItem>
<MenuItem value='member'>Member Only</MenuItem>
<MenuItem value='vip'>VIP Only</MenuItem>
</CustomTextField>
<CustomTextField
fullWidth
type='number'
label='Priority'
placeholder='10'
value={discountRequest.priority || 10}
onChange={e => handleInputChange('priority', e.target.value)}
helperText='Higher number = higher priority (1-100)'
/>
<Divider />
<FormControlLabel
control={
<Switch
checked={discountRequest.is_stackable || false}
onChange={e => handleInputChange('is_stackable', e.target.checked)}
/>
}
label='Can be combined with other discounts (Stackable)'
/>
</CardContent>
</Card>
)
}
export default DiscountSettings

View File

@ -0,0 +1,17 @@
// MUI Imports
import Grid from '@mui/material/Grid2'
import DiscountListTable from './list'
// Type Imports
const DiscountList = () => {
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<DiscountListTable />
</Grid>
</Grid>
)
}
export default DiscountList

View File

@ -0,0 +1,508 @@
'use client'
// React Imports
import { useCallback, useEffect, useMemo, useState } from 'react'
// Next Imports
import Link from 'next/link'
import { useParams } from 'next/navigation'
// MUI Imports
import Button from '@mui/material/Button'
import Card from '@mui/material/Card'
import CardHeader from '@mui/material/CardHeader'
import Checkbox from '@mui/material/Checkbox'
import Chip from '@mui/material/Chip'
import Divider from '@mui/material/Divider'
import IconButton from '@mui/material/IconButton'
import MenuItem from '@mui/material/MenuItem'
import TablePagination from '@mui/material/TablePagination'
import type { TextFieldProps } from '@mui/material/TextField'
import Typography from '@mui/material/Typography'
import { Box, CircularProgress } from '@mui/material'
// Third-party Imports
import type { RankingInfo } from '@tanstack/match-sorter-utils'
import { rankItem } from '@tanstack/match-sorter-utils'
import type { ColumnDef, FilterFn } from '@tanstack/react-table'
import { createColumnHelper, flexRender, getCoreRowModel, useReactTable } from '@tanstack/react-table'
import classnames from 'classnames'
// Type Imports
import type { Locale } from '@configs/i18n'
// Component Imports
import TablePaginationComponent from '@components/TablePaginationComponent'
import CustomTextField from '@core/components/mui/TextField'
import OptionMenu from '@core/components/option-menu'
import Loading from '@/components/layout/shared/Loading'
import ConfirmDeleteDialog from '@/components/dialogs/confirm-delete'
// Service Imports
// Util Imports
import { getLocalizedUrl } from '@/utils/i18n'
import { formatCurrency } from '@/utils/transform'
// Style Imports
import tableStyles from '@core/styles/table.module.css'
import { Discount, FetchDiscountsParams } from '@/types/services/discount'
import { useDiscounts } from '@/services/queries/discount'
import { useDiscountsMutation } from '@/services/mutations/discount'
declare module '@tanstack/table-core' {
interface FilterFns {
fuzzy: FilterFn<unknown>
}
interface FilterMeta {
itemRank: RankingInfo
}
}
type DiscountWithActionsType = Discount & {
actions?: string
}
const fuzzyFilter: FilterFn<any> = (row, columnId, value, addMeta) => {
const itemRank = rankItem(row.getValue(columnId), value)
addMeta({ itemRank })
return itemRank.passed
}
const DebouncedInput = ({
value: initialValue,
onChange,
debounce = 500,
...props
}: {
value: string | number
onChange: (value: string | number) => void
debounce?: number
} & Omit<TextFieldProps, 'onChange'>) => {
const [value, setValue] = useState(initialValue)
useEffect(() => {
setValue(initialValue)
}, [initialValue])
useEffect(() => {
const timeout = setTimeout(() => {
onChange(value)
}, debounce)
return () => clearTimeout(timeout)
}, [value])
return <CustomTextField {...props} value={value} onChange={e => setValue(e.target.value)} />
}
// Column Definitions
const columnHelper = createColumnHelper<DiscountWithActionsType>()
const DiscountListTable = () => {
const [rowSelection, setRowSelection] = useState({})
const [currentPage, setCurrentPage] = useState(1)
const [pageSize, setPageSize] = useState(10)
const [openConfirm, setOpenConfirm] = useState(false)
const [discountId, setDiscountId] = useState('')
const [search, setSearch] = useState('')
const [filter, setFilter] = useState<FetchDiscountsParams>({
type: undefined,
customer_type: undefined,
is_active: undefined,
campaign_id: undefined
})
// Hooks
const { lang: locale } = useParams()
// Fetch discounts with pagination and search
const { data, isLoading, error, isFetching } = useDiscounts({
page: currentPage,
limit: pageSize,
search: search,
...filter
})
const { deleteDiscount, toggleDiscountStatus } = useDiscountsMutation()
const discounts = data?.discounts ?? []
const totalCount = data?.pagination.total_count ?? 0
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)
}, [])
const handleDelete = () => {
deleteDiscount.mutate(discountId, {
onSuccess: () => setOpenConfirm(false)
})
}
const handleToggleStatus = (id: string, currentStatus: boolean) => {
toggleDiscountStatus.mutate({ id, isActive: !currentStatus })
}
const getDiscountTypeColor = (type: string) => {
switch (type) {
case 'percentage':
return 'primary'
case 'fixed_amount':
return 'success'
case 'free_product':
return 'info'
default:
return 'default'
}
}
const getCustomerTypeColor = (type: string) => {
switch (type) {
case 'all':
return 'default'
case 'member':
return 'warning'
case 'vip':
return 'error'
default:
return 'default'
}
}
const formatDiscountValue = (discount: Discount) => {
if (discount.type === 'percentage') {
return `${discount.value}%`
} else if (discount.type === 'fixed_amount') {
return formatCurrency(discount.value)
} else {
return 'Free Product'
}
}
const columns = useMemo<ColumnDef<DiscountWithActionsType, 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('code', {
header: 'Discount Code',
cell: ({ row }) => (
<div className='flex flex-col'>
<Typography className='font-medium' color='text.primary'>
{row.original.code}
</Typography>
<Typography variant='body2' color='text.secondary'>
{row.original.name}
</Typography>
</div>
)
}),
columnHelper.accessor('type', {
header: 'Type',
cell: ({ row }) => (
<Chip
label={row.original.type.replace('_', ' ').toUpperCase()}
variant='tonal'
color={getDiscountTypeColor(row.original.type)}
size='small'
/>
)
}),
columnHelper.accessor('value', {
header: 'Value',
cell: ({ row }) => <Typography className='font-medium'>{formatDiscountValue(row.original)}</Typography>
}),
columnHelper.accessor('customer_type', {
header: 'Customer Type',
cell: ({ row }) => (
<Chip
label={row.original.customer_type.toUpperCase()}
variant='tonal'
color={getCustomerTypeColor(row.original.customer_type)}
size='small'
/>
)
}),
columnHelper.accessor('min_purchase_amount', {
header: 'Min Purchase',
cell: ({ row }) => (
<Typography>
{row.original.min_purchase_amount ? formatCurrency(row.original.min_purchase_amount) : '-'}
</Typography>
)
}),
columnHelper.accessor('usage_count', {
header: 'Usage',
cell: ({ row }) => (
<div className='flex flex-col'>
<Typography variant='body2'>
{row.original.usage_count} / {row.original.usage_limit_total || '∞'}
</Typography>
</div>
)
}),
columnHelper.accessor('start_date', {
header: 'Period',
cell: ({ row }) => (
<div className='flex flex-col'>
<Typography variant='body2'>{new Date(row.original.start_date).toLocaleDateString()}</Typography>
<Typography variant='body2' color='text.secondary'>
to {new Date(row.original.end_date).toLocaleDateString()}
</Typography>
</div>
)
}),
columnHelper.accessor('is_active', {
header: 'Status',
cell: ({ row }) => (
<div className='flex items-center gap-2'>
<Chip
label={row.original.is_active ? 'Active' : 'Inactive'}
variant='tonal'
color={row.original.is_active ? 'success' : 'error'}
size='small'
/>
</div>
)
}),
columnHelper.accessor('actions', {
header: 'Actions',
cell: ({ row }) => (
<div className='flex items-center'>
<IconButton
LinkComponent={Link}
href={getLocalizedUrl(`/apps/marketing/discount/${row.original.id}/detail`, locale as Locale)}
>
<i className='tabler-eye text-textSecondary' />
</IconButton>
<IconButton
LinkComponent={Link}
href={getLocalizedUrl(`/apps/marketing/discount/${row.original.id}/edit`, locale as Locale)}
>
<i className='tabler-edit text-textSecondary' />
</IconButton>
<OptionMenu
iconButtonProps={{ size: 'medium' }}
iconClassName='text-textSecondary'
options={[
{
text: row.original.is_active ? 'Deactivate' : 'Activate',
icon: row.original.is_active ? 'tabler-toggle-left' : 'tabler-toggle-right',
menuItemProps: {
onClick: () => handleToggleStatus(row.original.id, row.original.is_active)
}
},
{
text: 'Delete',
icon: 'tabler-trash',
menuItemProps: {
onClick: () => {
setOpenConfirm(true)
setDiscountId(row.original.id)
}
}
},
{ text: 'Duplicate', icon: 'tabler-copy' }
]}
/>
</div>
),
enableSorting: false
})
],
[locale]
)
const table = useReactTable({
data: discounts as Discount[],
columns,
filterFns: {
fuzzy: fuzzyFilter
},
state: {
rowSelection,
pagination: {
pageIndex: currentPage,
pageSize
}
},
enableRowSelection: true,
onRowSelectionChange: setRowSelection,
getCoreRowModel: getCoreRowModel(),
manualPagination: true,
pageCount: Math.ceil(totalCount / pageSize)
})
return (
<>
<Card>
<CardHeader title='Filters' />
<Divider />
<div className='flex flex-wrap justify-between gap-4 p-6'>
<DebouncedInput
value={search}
onChange={value => setSearch(value as string)}
placeholder='Search Discount Code or Name'
className='max-sm:is-full'
/>
<div className='flex flex-wrap items-center max-sm:flex-col gap-4 max-sm:is-full is-auto'>
<CustomTextField
select
value={pageSize}
onChange={handlePageSizeChange}
className='flex-auto is-[70px] max-sm:is-full'
>
<MenuItem value='10'>10</MenuItem>
<MenuItem value='25'>25</MenuItem>
<MenuItem value='50'>50</MenuItem>
</CustomTextField>
<Button
color='secondary'
variant='tonal'
className='max-sm:is-full is-auto'
startIcon={<i className='tabler-upload' />}
>
Export
</Button>
<Button
variant='contained'
component={Link}
className='max-sm:is-full is-auto'
href={getLocalizedUrl('/apps/marketing/discount/add', locale as Locale)}
startIcon={<i className='tabler-plus' />}
>
Add Discount
</Button>
</div>
</div>
<div className='overflow-x-auto relative'>
{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'>
No data available
</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>
)}
{isFetching && !isLoading && (
<Box
position='absolute'
top={0}
left={0}
right={0}
bottom={0}
display='flex'
alignItems='center'
justifyContent='center'
bgcolor='rgba(255,255,255,0.7)'
zIndex={1}
>
<CircularProgress size={24} />
</Box>
)}
</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>
<ConfirmDeleteDialog
open={openConfirm}
onClose={() => setOpenConfirm(false)}
onConfirm={handleDelete}
isLoading={deleteDiscount.isPending}
/>
</>
)
}
export default DiscountListTable