diff --git a/src/app/[lang]/(dashboard)/(private)/apps/marketing/discount/add/page.tsx b/src/app/[lang]/(dashboard)/(private)/apps/marketing/discount/add/page.tsx new file mode 100644 index 0000000..7d8cc73 --- /dev/null +++ b/src/app/[lang]/(dashboard)/(private)/apps/marketing/discount/add/page.tsx @@ -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 ( + + + + + + + + + + + + + + + + + + + + + + + + + + ) +} + +export default DiscountsAddPage diff --git a/src/app/[lang]/(dashboard)/(private)/apps/marketing/discount/page.tsx b/src/app/[lang]/(dashboard)/(private)/apps/marketing/discount/page.tsx new file mode 100644 index 0000000..7aa690d --- /dev/null +++ b/src/app/[lang]/(dashboard)/(private)/apps/marketing/discount/page.tsx @@ -0,0 +1,7 @@ +import DiscountList from '@/views/apps/marketing/discount' + +const DiscountPage = () => { + return +} + +export default DiscountPage diff --git a/src/components/layout/vertical/VerticalMenu.tsx b/src/components/layout/vertical/VerticalMenu.tsx index a1c3d69..464aef9 100644 --- a/src/components/layout/vertical/VerticalMenu.tsx +++ b/src/components/layout/vertical/VerticalMenu.tsx @@ -173,6 +173,7 @@ const VerticalMenu = ({ dictionary, scrollMenu }: Props) => { */} {/* {dictionary['navigation'].voucher} */} {dictionary['navigation'].tiers_text} + {dictionary['navigation'].discount} }> diff --git a/src/data/dictionaries/en.json b/src/data/dictionaries/en.json index 2a15cd5..0ed0b48 100644 --- a/src/data/dictionaries/en.json +++ b/src/data/dictionaries/en.json @@ -137,6 +137,7 @@ "voucher": "Voucher", "tiers_text": "Tiers", "games": "Games", - "game_prizes": "Game Prizes" + "game_prizes": "Game Prizes", + "discount": "Discount" } } diff --git a/src/data/dictionaries/id.json b/src/data/dictionaries/id.json index f23fb6b..71391f9 100644 --- a/src/data/dictionaries/id.json +++ b/src/data/dictionaries/id.json @@ -137,6 +137,7 @@ "voucher": "Vocher", "tiers_text": "Tiers", "games": "Permainan", - "game_prizes": "Hadiah Permainan" + "game_prizes": "Hadiah Permainan", + "Discount": "Diskon" } } diff --git a/src/redux-store/index.ts b/src/redux-store/index.ts index 1bc3401..d13ef06 100644 --- a/src/redux-store/index.ts +++ b/src/redux-store/index.ts @@ -10,6 +10,7 @@ import productRecipeReducer from '@/redux-store/slices/productRecipe' import organizationReducer from '@/redux-store/slices/organization' import userReducer from '@/redux-store/slices/user' import vendorReducer from '@/redux-store/slices/vendor' +import discountReducer from '@/redux-store/slices/discount' export const store = configureStore({ reducer: { @@ -21,7 +22,8 @@ export const store = configureStore({ productRecipeReducer, organizationReducer, userReducer, - vendorReducer + vendorReducer, + discountReducer }, middleware: getDefaultMiddleware => getDefaultMiddleware({ serializableCheck: false }) }) diff --git a/src/redux-store/slices/discount.ts b/src/redux-store/slices/discount.ts new file mode 100644 index 0000000..953d9b9 --- /dev/null +++ b/src/redux-store/slices/discount.ts @@ -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) => { + 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) => { + state.selectedOutlets = action.payload + }, + + addDiscountOutlet: (state, action: PayloadAction) => { + if (!state.selectedOutlets.includes(action.payload)) { + state.selectedOutlets.push(action.payload) + } + }, + + removeDiscountOutlet: (state, action: PayloadAction) => { + state.selectedOutlets = state.selectedOutlets.filter(id => id !== action.payload) + }, + + // Product rules management + setProductRules: (state, action: PayloadAction) => { + state.productRules = action.payload + }, + + addProductRule: (state, action: PayloadAction) => { + 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) => { + state.productRules = state.productRules.filter((_, index) => index !== action.payload) + }, + + clearProductRules: state => { + state.productRules = [] + }, + + // Category rules management + setCategoryRules: (state, action: PayloadAction) => { + state.categoryRules = action.payload + }, + + addCategoryRule: (state, action: PayloadAction) => { + 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) => { + 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>) => { + 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) + ) +} diff --git a/src/services/api.ts b/src/services/api.ts index 2f7d1d8..5890323 100644 --- a/src/services/api.ts +++ b/src/services/api.ts @@ -6,8 +6,8 @@ const getToken = () => { } export const api = axios.create({ - baseURL: 'https://api-pos.apskel.id/api/v1', - // baseURL: 'http://127.0.0.1:4000/api/v1', + // baseURL: 'https://api-pos.apskel.id/api/v1', + baseURL: 'http://127.0.0.1:4000/api/v1', headers: { 'Content-Type': 'application/json' }, diff --git a/src/services/mutations/discount.ts b/src/services/mutations/discount.ts new file mode 100644 index 0000000..8ef1383 --- /dev/null +++ b/src/services/mutations/discount.ts @@ -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 } +} diff --git a/src/services/queries/discount.ts b/src/services/queries/discount.ts new file mode 100644 index 0000000..f086b5e --- /dev/null +++ b/src/services/queries/discount.ts @@ -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({ + 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({ + 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({ + 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({ + 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({ + 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({ + 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({ + 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({ + queryKey: ['discount', discountId, 'category-rules'], + queryFn: async () => { + const res = await api.get(`/discounts/${discountId}/categories`) + return res.data + }, + enabled: !!discountId + }) +} diff --git a/src/types/services/discount.ts b/src/types/services/discount.ts new file mode 100644 index 0000000..f562b72 --- /dev/null +++ b/src/types/services/discount.ts @@ -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 +} diff --git a/src/views/apps/marketing/discount/add/Dialog/CategoryRuleDialog.tsx b/src/views/apps/marketing/discount/add/Dialog/CategoryRuleDialog.tsx new file mode 100644 index 0000000..38b338d --- /dev/null +++ b/src/views/apps/marketing/discount/add/Dialog/CategoryRuleDialog.tsx @@ -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('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 ( + +
+ Add Category Rule + + + +
+ +
+
+ {/* Category Search & Select */} +
+ + Select Category * + + setSearchQuery(e.target.value)} + className='mbe-2' + /> +
+ {filteredCategories.length === 0 ? ( +
+ + No categories found + +
+ ) : ( + setSelectedCategory(e.target.value)}> + {filteredCategories.map(category => ( +
setSelectedCategory(category.id)} + > + } + label={ +
+ {category.name} + {category.description && ( + + {category.description} + + )} +
+ } + sx={{ margin: 0, width: '100%' }} + /> +
+ ))} +
+ )} +
+
+ + {/* Rule Type */} + setRuleType(e.target.value as CategoryRuleType)} + > + Included (Apply discount) + Excluded (No discount) + + + + {ruleType === 'included' && 'Only products in this category can get discount'} + {ruleType === 'excluded' && 'Products in this category will not get discount'} + + + {/* Action Buttons */} +
+ + +
+
+
+
+ ) +} + +export default CategoryRuleDialog diff --git a/src/views/apps/marketing/discount/add/Dialog/OutletSelectionDrawer.tsx b/src/views/apps/marketing/discount/add/Dialog/OutletSelectionDrawer.tsx new file mode 100644 index 0000000..2cc97bb --- /dev/null +++ b/src/views/apps/marketing/discount/add/Dialog/OutletSelectionDrawer.tsx @@ -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(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 ( + +
+ Select Outlets + + + +
+ +
+ {/* Search */} + setSearchQuery(e.target.value)} + className='mbe-4' + /> + + {/* Select All */} +
+ + + {selected.length} selected + +
+ + {/* Outlet List */} +
+ {filteredOutlets.length === 0 ? ( +
+ + No outlets found + +
+ ) : ( + filteredOutlets.map(outlet => ( +
handleToggle(outlet.id)} + > + } + label={ +
+ {outlet.name} + {outlet.address && ( + + {outlet.address} + + )} +
+ } + sx={{ margin: 0, width: '100%' }} + /> +
+ )) + )} +
+ + {/* Action Buttons */} +
+ + +
+
+
+ ) +} + +export default OutletSelectionDialog diff --git a/src/views/apps/marketing/discount/add/Dialog/ProductRuleDialog.tsx b/src/views/apps/marketing/discount/add/Dialog/ProductRuleDialog.tsx new file mode 100644 index 0000000..c603fec --- /dev/null +++ b/src/views/apps/marketing/discount/add/Dialog/ProductRuleDialog.tsx @@ -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('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 ( + +
+ Add Product Rule + + + +
+ +
+
+ {/* Product Search & Select */} +
+ + Select Product * + + setSearchQuery(e.target.value)} + className='mbe-2' + /> +
+ {filteredProducts.length === 0 ? ( +
+ + No products found + +
+ ) : ( + setSelectedProduct(e.target.value)}> + {filteredProducts.map(product => ( +
setSelectedProduct(product.id)} + > + } + label={ +
+ {product.name} + + SKU: {product.sku} + +
+ } + sx={{ margin: 0, width: '100%' }} + /> +
+ ))} +
+ )} +
+
+ + {/* Rule Type */} + setRuleType(e.target.value as ProductRuleType)} + > + Required (Must buy) + Free (Get free) + Excluded (No discount) + + + + {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'} + + + {/* Quantity */} + {ruleType !== 'excluded' && ( + setQuantity(Number(e.target.value))} + inputProps={{ min: 1 }} + /> + )} + + {/* Free Quantity */} + {ruleType === 'free' && ( + setFreeQuantity(Number(e.target.value))} + inputProps={{ min: 0 }} + helperText={`Buy ${quantity}, get ${freeQuantity} free`} + /> + )} + + {/* Action Buttons */} +
+ + +
+
+
+
+ ) +} + +export default ProductRuleDialog diff --git a/src/views/apps/marketing/discount/add/DiscountAddHeader.tsx b/src/views/apps/marketing/discount/add/DiscountAddHeader.tsx new file mode 100644 index 0000000..451fa8b --- /dev/null +++ b/src/views/apps/marketing/discount/add/DiscountAddHeader.tsx @@ -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 ( +
+
+ + {isEdit ? 'Edit Discount' : 'Add a new discount'} + + Create promotional discounts for your store +
+
+ + +
+
+ ) +} + +export default DiscountAddHeader diff --git a/src/views/apps/marketing/discount/add/DiscountAddInformation.tsx b/src/views/apps/marketing/discount/add/DiscountAddInformation.tsx new file mode 100644 index 0000000..176b844 --- /dev/null +++ b/src/views/apps/marketing/discount/add/DiscountAddInformation.tsx @@ -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 + + return ( + + + + + + handleInputChange('campaign_id', e.target.value)} + > + Select Campaign + {campaigns.map(campaign => ( + + {campaign.name} + + ))} + + + + + handleInputChange('code', e.target.value.toUpperCase())} + helperText='Only uppercase letters and numbers' + /> + + + handleInputChange('name', e.target.value)} + /> + + + + handleInputChange('type', e.target.value)} + > + Percentage (%) + Fixed Amount (Rp) + Free Product + + + + {discountRequest.type !== 'free_product' && ( + + handleInputChange('value', e.target.value)} + /> + + )} + + + handleInputChange('min_purchase_amount', e.target.value)} + helperText='Leave 0 if no minimum' + /> + + + + handleInputChange('min_purchase_qty', e.target.value)} + helperText='Leave 0 if no minimum' + /> + + + + handleInputChange('start_date', e.target.value)} + InputLabelProps={{ shrink: true }} + /> + + + + handleInputChange('end_date', e.target.value)} + InputLabelProps={{ shrink: true }} + /> + + + + + ) +} + +export default DiscountInformation diff --git a/src/views/apps/marketing/discount/add/DiscountAddOutlets.tsx b/src/views/apps/marketing/discount/add/DiscountAddOutlets.tsx new file mode 100644 index 0000000..e20dcdc --- /dev/null +++ b/src/views/apps/marketing/discount/add/DiscountAddOutlets.tsx @@ -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 ( + <> + + setOpenDialog(true)}> + Select Outlets + + } + /> + + {selectedOutlets.length === 0 ? ( + + No outlets selected. Click "Select Outlets" to add. + + ) : ( +
+ {selectedOutlets.map(outletId => ( + handleRemove(outletId)} + color='primary' + variant='tonal' + /> + ))} +
+ )} +
+
+ + setOpenDialog(false)} + selectedOutlets={selectedOutlets} + onConfirm={handleConfirm} + /> + + ) +} + +export default DiscountOutlets diff --git a/src/views/apps/marketing/discount/add/DiscountAddRule.tsx b/src/views/apps/marketing/discount/add/DiscountAddRule.tsx new file mode 100644 index 0000000..e1c8924 --- /dev/null +++ b/src/views/apps/marketing/discount/add/DiscountAddRule.tsx @@ -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 ( + <> + + + + {/* Product Rules */} +
+
+ Product Rules + +
+ + {productRules.length === 0 ? ( + + No product rules. Click "Add Product" to create rules. + + ) : ( +
+ {productRules.map((rule, index) => ( +
+
+ + {rule.product_name || `Product ${rule.product_id}`} + +
+ + + {rule.rule_type === 'free' && ( + + )} +
+
+ dispatch(removeProductRule(index))}> + + +
+ ))} +
+ )} +
+ + + + {/* Category Rules */} +
+
+ Category Rules + +
+ + {categoryRules.length === 0 ? ( + + No category rules. Click "Add Category" to create rules. + + ) : ( +
+ {categoryRules.map((rule, index) => ( +
+
+ + {rule.category_name || `Category ${rule.category_id}`} + + +
+ dispatch(removeCategoryRule(index))}> + + +
+ ))} +
+ )} +
+
+
+ + setOpenProductDialog(false)} + onConfirm={handleAddProductRule} + /> + + setOpenCategoryDialog(false)} + onConfirm={handleAddCategoryRule} + /> + + ) +} + +export default DiscountRules diff --git a/src/views/apps/marketing/discount/add/DiscountAddSetting.tsx b/src/views/apps/marketing/discount/add/DiscountAddSetting.tsx new file mode 100644 index 0000000..e762b4d --- /dev/null +++ b/src/views/apps/marketing/discount/add/DiscountAddSetting.tsx @@ -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 ( + + + + + handleInputChange('usage_limit_per_customer', e.target.value ? Number(e.target.value) : undefined) + } + helperText='Leave empty for unlimited' + /> + + handleInputChange('usage_limit_total', e.target.value ? Number(e.target.value) : undefined)} + helperText='Leave empty for unlimited' + /> + + handleInputChange('customer_type', e.target.value)} + > + All Customers + Member Only + VIP Only + + + handleInputChange('priority', e.target.value)} + helperText='Higher number = higher priority (1-100)' + /> + + + + handleInputChange('is_stackable', e.target.checked)} + /> + } + label='Can be combined with other discounts (Stackable)' + /> + + + ) +} + +export default DiscountSettings diff --git a/src/views/apps/marketing/discount/index.tsx b/src/views/apps/marketing/discount/index.tsx new file mode 100644 index 0000000..08465be --- /dev/null +++ b/src/views/apps/marketing/discount/index.tsx @@ -0,0 +1,17 @@ +// MUI Imports +import Grid from '@mui/material/Grid2' +import DiscountListTable from './list' + +// Type Imports + +const DiscountList = () => { + return ( + + + + + + ) +} + +export default DiscountList diff --git a/src/views/apps/marketing/discount/list/index.tsx b/src/views/apps/marketing/discount/list/index.tsx new file mode 100644 index 0000000..b7a60e8 --- /dev/null +++ b/src/views/apps/marketing/discount/list/index.tsx @@ -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 + } + interface FilterMeta { + itemRank: RankingInfo + } +} + +type DiscountWithActionsType = Discount & { + actions?: string +} + +const fuzzyFilter: FilterFn = (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) => { + const [value, setValue] = useState(initialValue) + + useEffect(() => { + setValue(initialValue) + }, [initialValue]) + + useEffect(() => { + const timeout = setTimeout(() => { + onChange(value) + }, debounce) + + return () => clearTimeout(timeout) + }, [value]) + + return setValue(e.target.value)} /> +} + +// Column Definitions +const columnHelper = createColumnHelper() + +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({ + 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) => { + 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[]>( + () => [ + { + id: 'select', + header: ({ table }) => ( + + ), + cell: ({ row }) => ( + + ) + }, + columnHelper.accessor('code', { + header: 'Discount Code', + cell: ({ row }) => ( +
+ + {row.original.code} + + + {row.original.name} + +
+ ) + }), + columnHelper.accessor('type', { + header: 'Type', + cell: ({ row }) => ( + + ) + }), + columnHelper.accessor('value', { + header: 'Value', + cell: ({ row }) => {formatDiscountValue(row.original)} + }), + columnHelper.accessor('customer_type', { + header: 'Customer Type', + cell: ({ row }) => ( + + ) + }), + columnHelper.accessor('min_purchase_amount', { + header: 'Min Purchase', + cell: ({ row }) => ( + + {row.original.min_purchase_amount ? formatCurrency(row.original.min_purchase_amount) : '-'} + + ) + }), + columnHelper.accessor('usage_count', { + header: 'Usage', + cell: ({ row }) => ( +
+ + {row.original.usage_count} / {row.original.usage_limit_total || '∞'} + +
+ ) + }), + columnHelper.accessor('start_date', { + header: 'Period', + cell: ({ row }) => ( +
+ {new Date(row.original.start_date).toLocaleDateString()} + + to {new Date(row.original.end_date).toLocaleDateString()} + +
+ ) + }), + columnHelper.accessor('is_active', { + header: 'Status', + cell: ({ row }) => ( +
+ +
+ ) + }), + columnHelper.accessor('actions', { + header: 'Actions', + cell: ({ row }) => ( +
+ + + + + + + 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' } + ]} + /> +
+ ), + 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 ( + <> + + + +
+ setSearch(value as string)} + placeholder='Search Discount Code or Name' + className='max-sm:is-full' + /> +
+ + 10 + 25 + 50 + + + +
+
+
+ {isLoading ? ( + + ) : ( + + + {table.getHeaderGroups().map(headerGroup => ( + + {headerGroup.headers.map(header => ( + + ))} + + ))} + + {table.getFilteredRowModel().rows.length === 0 ? ( + + + + + + ) : ( + + {table + .getRowModel() + .rows.slice(0, table.getState().pagination.pageSize) + .map(row => { + return ( + + {row.getVisibleCells().map(cell => ( + + ))} + + ) + })} + + )} +
+ {header.isPlaceholder ? null : ( +
+ {flexRender(header.column.columnDef.header, header.getContext())} + {{ + asc: , + desc: + }[header.column.getIsSorted() as 'asc' | 'desc'] ?? null} +
+ )} +
+ No data available +
{flexRender(cell.column.columnDef.cell, cell.getContext())}
+ )} + + {isFetching && !isLoading && ( + + + + )} +
+ + ( + + )} + count={totalCount} + rowsPerPage={pageSize} + page={currentPage} + onPageChange={handlePageChange} + onRowsPerPageChange={handlePageSizeChange} + rowsPerPageOptions={[10, 25, 50]} + disabled={isLoading} + /> +
+ + setOpenConfirm(false)} + onConfirm={handleDelete} + isLoading={deleteDiscount.isPending} + /> + + ) +} + +export default DiscountListTable