Compare commits
74
Commits
7f646b82a9
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2641175e04 | ||
|
|
c78b32d7b8 | ||
|
|
e8609a0ab9 | ||
|
|
b22f400534 | ||
|
|
b506d97c06 | ||
|
|
a3dd214a99 | ||
|
|
3c13aa897c | ||
|
|
f4783236d2 | ||
|
|
67ebb2ebd7 | ||
|
|
de32d86e94 | ||
|
|
3cf7799a91 | ||
|
|
37de68879c | ||
|
|
80bab20f89 | ||
|
|
6b46f9070a | ||
|
|
c5cda37efb | ||
|
|
2897436c5f | ||
|
|
fe4176621c | ||
|
|
16deaf1890 | ||
|
|
f434373eaf | ||
|
|
8e4ab5dd69 | ||
|
|
5f65211432 | ||
|
|
ead773982a | ||
|
|
aae1d49721 | ||
|
|
347d00271b | ||
|
|
ac2fc4e920 | ||
|
|
e551ae7feb | ||
|
|
d059f31eaa | ||
|
|
f1cf351ca4 | ||
|
|
801fcdda2f | ||
|
|
4ba5b9def3 | ||
|
|
116f6b8009 | ||
|
|
1b9908e882 | ||
|
|
d245074904 | ||
|
|
8672f01261 | ||
|
|
256f035997 | ||
|
|
bd14adde23 | ||
|
|
726d1f4984 | ||
|
|
35b1426384 | ||
|
|
9b92f4742f | ||
|
|
1bf2bad52c | ||
|
|
e55357e305 | ||
|
|
9806400308 | ||
|
|
3bfd0b9e19 | ||
|
|
f98b61e527 | ||
|
|
97ed613cc6 | ||
|
|
fdcb0e12f4 | ||
|
|
7570e973b8 | ||
|
|
e82173c6e2 | ||
|
|
4640d14cb7 | ||
|
|
3a56e56c69 | ||
|
|
6d2e436b09 | ||
|
|
7252c05569 | ||
|
|
757d9f524a | ||
|
|
a6f80bbd02 | ||
|
|
8ed2786bc2 | ||
|
|
4655411b24 | ||
|
|
185edb94cb | ||
|
|
2643963b49 | ||
|
|
18ee652731 | ||
|
|
3d1b6eee39 | ||
|
|
966081214f | ||
|
|
1c5740a85b | ||
|
|
f527b6f004 | ||
|
|
84454e66dc | ||
|
|
54d8ff3444 | ||
|
|
ddbd5ba607 | ||
|
|
50a8f4a295 | ||
|
|
fb6e2571a5 | ||
|
|
5de78cb78f | ||
|
|
d85f081d3a | ||
|
|
f3358705b0 | ||
|
|
9959775c77 | ||
|
|
14efada9bb | ||
|
|
7384b38df5 |
@@ -39,3 +39,5 @@ next-env.d.ts
|
||||
# icon generated file
|
||||
src/assets/iconify-icons/generated-icons.js
|
||||
src/assets/iconify-icons/generated-icons.css
|
||||
|
||||
*.backup
|
||||
|
||||
Generated
+1222
-58
File diff suppressed because it is too large
Load Diff
+9
-2
@@ -30,6 +30,7 @@
|
||||
"@fullcalendar/list": "6.1.15",
|
||||
"@fullcalendar/react": "6.1.15",
|
||||
"@fullcalendar/timegrid": "6.1.15",
|
||||
"@hello-pangea/dnd": "^18.0.1",
|
||||
"@hookform/resolvers": "3.9.1",
|
||||
"@iconify/react": "^6.0.1",
|
||||
"@mui/lab": "6.0.0-beta.19",
|
||||
@@ -52,18 +53,23 @@
|
||||
"apexcharts": "3.49.0",
|
||||
"axios": "^1.11.0",
|
||||
"bootstrap-icons": "1.11.3",
|
||||
"chart.js": "^4.5.1",
|
||||
"chartjs-plugin-datalabels": "^2.2.0",
|
||||
"classnames": "2.5.1",
|
||||
"cmdk": "1.0.4",
|
||||
"date-fns": "4.1.0",
|
||||
"emoji-mart": "5.6.0",
|
||||
"exceljs": "^4.4.0",
|
||||
"fs-extra": "11.2.0",
|
||||
"html2canvas": "^1.4.1",
|
||||
"input-otp": "1.4.1",
|
||||
"jspdf": "^3.0.1",
|
||||
"jspdf-autotable": "^5.0.2",
|
||||
"keen-slider": "6.8.6",
|
||||
"lucide-react": "^0.544.0",
|
||||
"mapbox-gl": "3.9.0",
|
||||
"negotiator": "1.0.0",
|
||||
"next": "15.1.2",
|
||||
"next": "^15.1.9",
|
||||
"react": "18.3.1",
|
||||
"react-apexcharts": "1.4.1",
|
||||
"react-colorful": "5.6.1",
|
||||
@@ -79,7 +85,8 @@
|
||||
"react-use": "17.6.0",
|
||||
"recharts": "2.15.0",
|
||||
"use-debounce": "^10.0.5",
|
||||
"valibot": "0.42.1"
|
||||
"valibot": "0.42.1",
|
||||
"xlsx": "^0.18.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@iconify/json": "2.2.286",
|
||||
|
||||
@@ -0,0 +1,976 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { RotateCw, Trophy, Trash2, RefreshCw, Shuffle, Sparkles, Gift } from 'lucide-react';
|
||||
import { useVoucherRows } from '@/services/queries/vouchers';
|
||||
import { Voucher, VoucherRow } from '@/types/services/voucher';
|
||||
import { toast } from 'react-toastify';
|
||||
|
||||
interface SpinRow {
|
||||
id: string;
|
||||
rowNumber: number;
|
||||
vouchers: Voucher[];
|
||||
displayVouchers: Voucher[];
|
||||
isSpinning: boolean;
|
||||
isShuffling: boolean;
|
||||
winner: Voucher | null;
|
||||
wheelRef: React.RefObject<HTMLDivElement>;
|
||||
selectedWinner: Voucher | null;
|
||||
}
|
||||
|
||||
interface WinnerHistory {
|
||||
rowNumber: number;
|
||||
winner: Voucher;
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
const RandomDrawApp: React.FC = () => {
|
||||
const [spinRows, setSpinRows] = useState<SpinRow[]>([]);
|
||||
const [numberOfRows, setNumberOfRows] = useState<number>(5);
|
||||
const [winnersHistory, setWinnersHistory] = useState<WinnerHistory[]>([]);
|
||||
const [isRevealingWinners, setIsRevealingWinners] = useState<boolean>(false);
|
||||
const [revealedWinners, setRevealedWinners] = useState<Set<number>>(new Set());
|
||||
const [isSequentialSpinning, setIsSequentialSpinning] = useState<boolean>(false);
|
||||
const [currentSpinningRow, setCurrentSpinningRow] = useState<number | null>(null);
|
||||
const [selectedPrize, setSelectedPrize] = useState<number>(1); // 1 for Emas 0.25 Gram, 2 for Emas 3 Gram
|
||||
const audioContextRef = useRef<AudioContext | null>(null);
|
||||
const tickIntervalRefs = useRef<Map<string, NodeJS.Timeout>>(new Map());
|
||||
const shuffleIntervalRefs = useRef<Map<string, NodeJS.Timeout>>(new Map());
|
||||
|
||||
// Use React Query hook for fetching voucher data - disabled by default
|
||||
const { data: voucherData, isLoading: isLoadingData, refetch: refetchVouchers, error: fetchError } = useVoucherRows({
|
||||
rows: numberOfRows,
|
||||
winner_number: selectedPrize
|
||||
}, {
|
||||
enabled: false // Disable automatic fetching - only fetch when Load Data is clicked
|
||||
});
|
||||
|
||||
// Initialize Audio Context
|
||||
useEffect(() => {
|
||||
const initAudio = () => {
|
||||
if (!audioContextRef.current) {
|
||||
audioContextRef.current = new (window.AudioContext || (window as any).webkitAudioContext)();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('click', initAudio, { once: true });
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('click', initAudio);
|
||||
tickIntervalRefs.current.forEach(timeout => clearTimeout(timeout));
|
||||
shuffleIntervalRefs.current.forEach(timeout => clearTimeout(timeout));
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Create tick sound effect
|
||||
const playTickSound = () => {
|
||||
if (!audioContextRef.current) return;
|
||||
|
||||
const ctx = audioContextRef.current;
|
||||
const oscillator = ctx.createOscillator();
|
||||
const gainNode = ctx.createGain();
|
||||
|
||||
oscillator.connect(gainNode);
|
||||
gainNode.connect(ctx.destination);
|
||||
|
||||
oscillator.frequency.setValueAtTime(800, ctx.currentTime);
|
||||
oscillator.frequency.exponentialRampToValueAtTime(200, ctx.currentTime + 0.05);
|
||||
|
||||
gainNode.gain.setValueAtTime(0, ctx.currentTime);
|
||||
gainNode.gain.linearRampToValueAtTime(0.1, ctx.currentTime + 0.01);
|
||||
gainNode.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.05);
|
||||
|
||||
oscillator.start(ctx.currentTime);
|
||||
oscillator.stop(ctx.currentTime + 0.05);
|
||||
};
|
||||
|
||||
// Create drum roll sound
|
||||
const playDrumRoll = () => {
|
||||
if (!audioContextRef.current) return;
|
||||
|
||||
const ctx = audioContextRef.current;
|
||||
const oscillator = ctx.createOscillator();
|
||||
const gainNode = ctx.createGain();
|
||||
const noiseNode = ctx.createBufferSource();
|
||||
|
||||
// Create noise buffer for snare-like sound
|
||||
const bufferSize = ctx.sampleRate * 0.05;
|
||||
const buffer = ctx.createBuffer(1, bufferSize, ctx.sampleRate);
|
||||
const data = buffer.getChannelData(0);
|
||||
for (let i = 0; i < bufferSize; i++) {
|
||||
data[i] = Math.random() * 2 - 1;
|
||||
}
|
||||
noiseNode.buffer = buffer;
|
||||
|
||||
oscillator.connect(gainNode);
|
||||
noiseNode.connect(gainNode);
|
||||
gainNode.connect(ctx.destination);
|
||||
|
||||
oscillator.frequency.setValueAtTime(200, ctx.currentTime);
|
||||
gainNode.gain.setValueAtTime(0.05, ctx.currentTime);
|
||||
gainNode.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.1);
|
||||
|
||||
oscillator.start(ctx.currentTime);
|
||||
oscillator.stop(ctx.currentTime + 0.1);
|
||||
noiseNode.start(ctx.currentTime);
|
||||
};
|
||||
|
||||
// Create winner sound
|
||||
const playWinnerSound = () => {
|
||||
if (!audioContextRef.current) return;
|
||||
|
||||
const ctx = audioContextRef.current;
|
||||
const notes = [523.25, 659.25, 783.99, 1046.5]; // C, E, G, C (higher octave)
|
||||
|
||||
notes.forEach((freq, index) => {
|
||||
const oscillator = ctx.createOscillator();
|
||||
const gainNode = ctx.createGain();
|
||||
|
||||
oscillator.connect(gainNode);
|
||||
gainNode.connect(ctx.destination);
|
||||
|
||||
oscillator.frequency.setValueAtTime(freq, ctx.currentTime + index * 0.1);
|
||||
|
||||
gainNode.gain.setValueAtTime(0, ctx.currentTime + index * 0.1);
|
||||
gainNode.gain.linearRampToValueAtTime(0.2, ctx.currentTime + index * 0.1 + 0.05);
|
||||
gainNode.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + index * 0.1 + 0.5);
|
||||
|
||||
oscillator.start(ctx.currentTime + index * 0.1);
|
||||
oscillator.stop(ctx.currentTime + index * 0.1 + 0.5);
|
||||
});
|
||||
};
|
||||
|
||||
// Start tick sound during spinning
|
||||
const startTickSound = (rowId: string, duration: number) => {
|
||||
const existingInterval = tickIntervalRefs.current.get(rowId);
|
||||
if (existingInterval) {
|
||||
clearTimeout(existingInterval);
|
||||
}
|
||||
|
||||
let tickInterval = 50;
|
||||
const maxInterval = 200;
|
||||
const intervalIncrement = (maxInterval - tickInterval) / (duration / 100);
|
||||
|
||||
const tick = () => {
|
||||
playTickSound();
|
||||
tickInterval += intervalIncrement;
|
||||
|
||||
if (tickInterval < maxInterval) {
|
||||
const timeoutId = setTimeout(tick, Math.min(tickInterval, maxInterval));
|
||||
tickIntervalRefs.current.set(rowId, timeoutId);
|
||||
}
|
||||
};
|
||||
|
||||
tick();
|
||||
|
||||
setTimeout(() => {
|
||||
const interval = tickIntervalRefs.current.get(rowId);
|
||||
if (interval) {
|
||||
clearTimeout(interval);
|
||||
tickIntervalRefs.current.delete(rowId);
|
||||
}
|
||||
}, duration + 100);
|
||||
};
|
||||
|
||||
// Shuffle array
|
||||
const shuffleArray = <T,>(array: T[]): T[] => {
|
||||
const shuffled = [...array];
|
||||
for (let i = shuffled.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(Math.random() * (i + 1));
|
||||
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
|
||||
}
|
||||
return shuffled;
|
||||
};
|
||||
|
||||
// Process voucher data when it changes
|
||||
useEffect(() => {
|
||||
if (voucherData && voucherData.rows) {
|
||||
const newSpinRows: SpinRow[] = voucherData.rows.map(row => ({
|
||||
id: `row-${row.row_number}-${Date.now()}`,
|
||||
rowNumber: row.row_number,
|
||||
vouchers: row.vouchers,
|
||||
displayVouchers: [...row.vouchers],
|
||||
isSpinning: false,
|
||||
isShuffling: false,
|
||||
winner: null,
|
||||
wheelRef: React.createRef<HTMLDivElement>(),
|
||||
selectedWinner: null,
|
||||
}));
|
||||
setSpinRows(newSpinRows);
|
||||
setRevealedWinners(new Set());
|
||||
}
|
||||
}, [voucherData]);
|
||||
|
||||
// Show error if fetch failed
|
||||
useEffect(() => {
|
||||
if (fetchError) {
|
||||
toast.error('Failed to load voucher data. Please check your connection and try again.');
|
||||
}
|
||||
}, [fetchError]);
|
||||
|
||||
// Remove auto-refetch - data will only load when Load Data button is clicked
|
||||
|
||||
// Shuffle all rows (Acak functionality)
|
||||
const shuffleAllRows = () => {
|
||||
setSpinRows(prev => prev.map(row => ({
|
||||
...row,
|
||||
isShuffling: true
|
||||
})));
|
||||
|
||||
// Animate shuffling for each row
|
||||
spinRows.forEach((row, index) => {
|
||||
let shuffleCount = 0;
|
||||
const maxShuffles = 20;
|
||||
|
||||
const shuffleInterval = setInterval(() => {
|
||||
shuffleCount++;
|
||||
|
||||
setSpinRows(prev => prev.map(r => {
|
||||
if (r.id === row.id) {
|
||||
return {
|
||||
...r,
|
||||
displayVouchers: shuffleArray(r.vouchers)
|
||||
};
|
||||
}
|
||||
return r;
|
||||
}));
|
||||
|
||||
playTickSound();
|
||||
|
||||
if (shuffleCount >= maxShuffles) {
|
||||
clearInterval(shuffleInterval);
|
||||
setTimeout(() => {
|
||||
setSpinRows(prev => prev.map(r => {
|
||||
if (r.id === row.id) {
|
||||
return {
|
||||
...r,
|
||||
isShuffling: false
|
||||
};
|
||||
}
|
||||
return r;
|
||||
}));
|
||||
}, index * 100);
|
||||
}
|
||||
}, 100);
|
||||
|
||||
shuffleIntervalRefs.current.set(row.id, shuffleInterval as any);
|
||||
});
|
||||
};
|
||||
|
||||
// Reveal winners dramatically
|
||||
const revealWinnersDramatically = async () => {
|
||||
setIsRevealingWinners(true);
|
||||
setRevealedWinners(new Set());
|
||||
|
||||
// First, arrange winners to be in the winner zone for each row
|
||||
const arrangedRows = spinRows.map(row => {
|
||||
const winner = row.vouchers.find(v => v.is_winner);
|
||||
if (!winner) return row;
|
||||
|
||||
// Create a new display order with winner at position 3 or 4 (will be in winner zone)
|
||||
const otherVouchers = row.vouchers.filter(v => v.voucher_code !== winner.voucher_code);
|
||||
const shuffledOthers = shuffleArray(otherVouchers);
|
||||
|
||||
// Place winner at index 3 (4th position) which will be in the winner zone
|
||||
const newDisplayVouchers = [
|
||||
...shuffledOthers.slice(0, 3),
|
||||
winner,
|
||||
...shuffledOthers.slice(3)
|
||||
];
|
||||
|
||||
return {
|
||||
...row,
|
||||
displayVouchers: newDisplayVouchers
|
||||
};
|
||||
});
|
||||
|
||||
// Update display to show arranged vouchers
|
||||
setSpinRows(arrangedRows);
|
||||
|
||||
// Start drum roll effect
|
||||
const drumRollInterval = setInterval(() => {
|
||||
playDrumRoll();
|
||||
}, 100);
|
||||
|
||||
// Create a scrolling/spinning effect for all wheels simultaneously
|
||||
let scrollSpeed = 50;
|
||||
let currentScroll = 0;
|
||||
const maxScroll = 2000;
|
||||
const deceleration = 0.95;
|
||||
|
||||
const spinInterval = setInterval(() => {
|
||||
currentScroll += scrollSpeed;
|
||||
scrollSpeed *= deceleration;
|
||||
|
||||
// Apply scrolling to all wheels
|
||||
arrangedRows.forEach(row => {
|
||||
const wheelElement = row.wheelRef.current;
|
||||
if (wheelElement) {
|
||||
wheelElement.style.transition = 'none';
|
||||
wheelElement.style.transform = `translateY(${-currentScroll}px)`;
|
||||
}
|
||||
});
|
||||
|
||||
// Stop when speed is very slow
|
||||
if (scrollSpeed < 0.5 || currentScroll >= maxScroll) {
|
||||
clearInterval(spinInterval);
|
||||
clearInterval(drumRollInterval);
|
||||
|
||||
// Final positioning - snap to winner position
|
||||
arrangedRows.forEach(row => {
|
||||
const wheelElement = row.wheelRef.current;
|
||||
if (wheelElement) {
|
||||
const CARD_HEIGHT = 80;
|
||||
const WINNER_ZONE_TOP = 260; // Top position of winner zone
|
||||
// Position 4th card (index 3) exactly at the winner zone
|
||||
const finalPosition = -(3 * CARD_HEIGHT - WINNER_ZONE_TOP);
|
||||
|
||||
wheelElement.style.transition = 'transform 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94)';
|
||||
wheelElement.style.transform = `translateY(${finalPosition}px)`;
|
||||
}
|
||||
});
|
||||
}
|
||||
}, 20);
|
||||
|
||||
// Wait for scrolling to complete
|
||||
await new Promise(resolve => setTimeout(resolve, 3000));
|
||||
|
||||
// Play winner sound
|
||||
playWinnerSound();
|
||||
|
||||
// Collect all winners
|
||||
const winnersToReveal: { row: SpinRow, winner: Voucher }[] = [];
|
||||
arrangedRows.forEach(row => {
|
||||
const winner = row.vouchers.find(v => v.is_winner);
|
||||
if (winner) {
|
||||
winnersToReveal.push({ row, winner });
|
||||
}
|
||||
});
|
||||
|
||||
// Update all winners at once with highlighting
|
||||
const allWinnerNumbers = new Set<number>();
|
||||
const historyEntries: WinnerHistory[] = [];
|
||||
|
||||
winnersToReveal.forEach(({ row, winner }) => {
|
||||
allWinnerNumbers.add(row.rowNumber);
|
||||
historyEntries.push({
|
||||
rowNumber: row.rowNumber,
|
||||
winner: winner,
|
||||
timestamp: new Date()
|
||||
});
|
||||
});
|
||||
|
||||
// Update state to highlight winners
|
||||
setRevealedWinners(allWinnerNumbers);
|
||||
|
||||
setSpinRows(prev => prev.map(r => {
|
||||
const winnerInfo = winnersToReveal.find(w => w.row.id === r.id);
|
||||
if (winnerInfo) {
|
||||
return {
|
||||
...r,
|
||||
winner: winnerInfo.winner,
|
||||
selectedWinner: winnerInfo.winner
|
||||
};
|
||||
}
|
||||
return r;
|
||||
}));
|
||||
|
||||
setWinnersHistory(prev => [...prev, ...historyEntries]);
|
||||
|
||||
setIsRevealingWinners(false);
|
||||
};
|
||||
|
||||
const performDramaticSpin = (row: SpinRow, isSequential: boolean = false) => {
|
||||
const wheelElement = row.wheelRef.current;
|
||||
if (!wheelElement) return;
|
||||
|
||||
const winner = row.vouchers.find(v => v.is_winner);
|
||||
if (!winner) {
|
||||
console.error('No winner found in vouchers');
|
||||
return;
|
||||
}
|
||||
|
||||
const CARD_HEIGHT = 80;
|
||||
const WINNER_ZONE_TOP = 260; // Top position of winner zone
|
||||
|
||||
// Shuffle the display vouchers to create more dramatic effect
|
||||
const shuffledVouchers = shuffleArray([...row.vouchers]);
|
||||
const winnerIndex = shuffledVouchers.findIndex(v => v.voucher_code === winner.voucher_code);
|
||||
|
||||
// Update display vouchers with shuffled order
|
||||
setSpinRows(prev => prev.map(r =>
|
||||
r.id === row.id ? { ...r, displayVouchers: shuffledVouchers } : r
|
||||
));
|
||||
|
||||
wheelElement.style.transition = 'none';
|
||||
wheelElement.style.transform = 'translateY(0px)';
|
||||
wheelElement.offsetHeight;
|
||||
|
||||
setTimeout(() => {
|
||||
// More dramatic spinning with multiple phases
|
||||
const minSpins = 15;
|
||||
const maxSpins = 25;
|
||||
const spins = minSpins + Math.random() * (maxSpins - minSpins);
|
||||
const totalItems = shuffledVouchers.length;
|
||||
|
||||
const totalRotations = Math.floor(spins);
|
||||
const baseScrollDistance = totalRotations * totalItems * CARD_HEIGHT;
|
||||
const winnerScrollPosition = winnerIndex * CARD_HEIGHT;
|
||||
const finalPosition = -(baseScrollDistance + winnerScrollPosition) + WINNER_ZONE_TOP;
|
||||
|
||||
const distance = Math.abs(finalPosition);
|
||||
const baseDuration = 4000; // Longer base duration
|
||||
const maxDuration = 7000; // Longer max duration
|
||||
const duration = Math.min(baseDuration + (distance / 8000) * 2000, maxDuration);
|
||||
|
||||
// Phase 1: Fast initial spin
|
||||
const phase1Duration = duration * 0.3;
|
||||
const phase1Distance = finalPosition * 0.7;
|
||||
|
||||
wheelElement.style.transform = `translateY(${phase1Distance}px)`;
|
||||
wheelElement.style.transition = `transform ${phase1Duration}ms cubic-bezier(0.25, 0.46, 0.45, 0.94)`;
|
||||
|
||||
// Phase 2: Slower approach to final position
|
||||
setTimeout(() => {
|
||||
wheelElement.style.transform = `translateY(${finalPosition}px)`;
|
||||
wheelElement.style.transition = `transform ${duration - phase1Duration}ms cubic-bezier(0.17, 0.67, 0.12, 0.99)`;
|
||||
}, phase1Duration);
|
||||
|
||||
startTickSound(row.id, duration);
|
||||
|
||||
setTimeout(() => {
|
||||
const interval = tickIntervalRefs.current.get(row.id);
|
||||
if (interval) {
|
||||
clearTimeout(interval);
|
||||
tickIntervalRefs.current.delete(row.id);
|
||||
}
|
||||
|
||||
playWinnerSound();
|
||||
|
||||
setSpinRows(prev => prev.map(r =>
|
||||
r.id === row.id
|
||||
? { ...r, isSpinning: false, winner: winner, selectedWinner: winner }
|
||||
: r
|
||||
));
|
||||
|
||||
setWinnersHistory(prev => [...prev, {
|
||||
rowNumber: row.rowNumber,
|
||||
winner: winner,
|
||||
timestamp: new Date()
|
||||
}]);
|
||||
|
||||
// If this is sequential spinning, trigger next row
|
||||
if (isSequential) {
|
||||
const nextRowIndex = spinRows.findIndex(r => r.id === row.id) + 1;
|
||||
if (nextRowIndex < spinRows.length) {
|
||||
setTimeout(() => {
|
||||
spinSequentialRow(nextRowIndex);
|
||||
}, 2000); // Wait 2 seconds before next spin
|
||||
} else {
|
||||
// All rows completed
|
||||
setIsSequentialSpinning(false);
|
||||
setCurrentSpinningRow(null);
|
||||
}
|
||||
}
|
||||
|
||||
// Keep the winner in the winner zone - don't reset position
|
||||
// The winning card will stay exactly where it landed in the winner zone
|
||||
|
||||
}, duration);
|
||||
}, 100);
|
||||
};
|
||||
|
||||
const performSpin = (row: SpinRow) => {
|
||||
const wheelElement = row.wheelRef.current;
|
||||
if (!wheelElement) return;
|
||||
|
||||
const winner = row.vouchers.find(v => v.is_winner);
|
||||
if (!winner) {
|
||||
console.error('No winner found in vouchers');
|
||||
return;
|
||||
}
|
||||
|
||||
const CARD_HEIGHT = 80;
|
||||
const WINNER_ZONE_TOP = 260; // Top position of winner zone
|
||||
|
||||
// Shuffle the display vouchers to create more dramatic effect
|
||||
const shuffledVouchers = shuffleArray([...row.vouchers]);
|
||||
const winnerIndex = shuffledVouchers.findIndex(v => v.voucher_code === winner.voucher_code);
|
||||
|
||||
// Update display vouchers with shuffled order
|
||||
setSpinRows(prev => prev.map(r =>
|
||||
r.id === row.id ? { ...r, displayVouchers: shuffledVouchers } : r
|
||||
));
|
||||
|
||||
wheelElement.style.transition = 'none';
|
||||
wheelElement.style.transform = 'translateY(0px)';
|
||||
wheelElement.offsetHeight;
|
||||
|
||||
setTimeout(() => {
|
||||
// More dramatic spinning with multiple phases
|
||||
const minSpins = 15;
|
||||
const maxSpins = 25;
|
||||
const spins = minSpins + Math.random() * (maxSpins - minSpins);
|
||||
const totalItems = shuffledVouchers.length;
|
||||
|
||||
const totalRotations = Math.floor(spins);
|
||||
const baseScrollDistance = totalRotations * totalItems * CARD_HEIGHT;
|
||||
const winnerScrollPosition = winnerIndex * CARD_HEIGHT;
|
||||
const finalPosition = -(baseScrollDistance + winnerScrollPosition) + WINNER_ZONE_TOP;
|
||||
|
||||
const distance = Math.abs(finalPosition);
|
||||
const baseDuration = 4000; // Longer base duration
|
||||
const maxDuration = 7000; // Longer max duration
|
||||
const duration = Math.min(baseDuration + (distance / 8000) * 2000, maxDuration);
|
||||
|
||||
// Phase 1: Fast initial spin
|
||||
const phase1Duration = duration * 0.3;
|
||||
const phase1Distance = finalPosition * 0.7;
|
||||
|
||||
wheelElement.style.transform = `translateY(${phase1Distance}px)`;
|
||||
wheelElement.style.transition = `transform ${phase1Duration}ms cubic-bezier(0.25, 0.46, 0.45, 0.94)`;
|
||||
|
||||
// Phase 2: Slower approach to final position
|
||||
setTimeout(() => {
|
||||
wheelElement.style.transform = `translateY(${finalPosition}px)`;
|
||||
wheelElement.style.transition = `transform ${duration - phase1Duration}ms cubic-bezier(0.17, 0.67, 0.12, 0.99)`;
|
||||
}, phase1Duration);
|
||||
|
||||
startTickSound(row.id, duration);
|
||||
|
||||
setTimeout(() => {
|
||||
const interval = tickIntervalRefs.current.get(row.id);
|
||||
if (interval) {
|
||||
clearTimeout(interval);
|
||||
tickIntervalRefs.current.delete(row.id);
|
||||
}
|
||||
|
||||
playWinnerSound();
|
||||
|
||||
setSpinRows(prev => prev.map(r =>
|
||||
r.id === row.id
|
||||
? { ...r, isSpinning: false, winner: winner, selectedWinner: winner }
|
||||
: r
|
||||
));
|
||||
|
||||
setWinnersHistory(prev => [...prev, {
|
||||
rowNumber: row.rowNumber,
|
||||
winner: winner,
|
||||
timestamp: new Date()
|
||||
}]);
|
||||
|
||||
// Keep the winner in the winner zone - don't reset position
|
||||
// The winning card will stay exactly where it landed in the winner zone
|
||||
|
||||
}, duration);
|
||||
}, 100);
|
||||
};
|
||||
|
||||
const spinSequentialRow = (rowIndex: number) => {
|
||||
if (rowIndex >= spinRows.length) {
|
||||
setIsSequentialSpinning(false);
|
||||
setCurrentSpinningRow(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const row = spinRows[rowIndex];
|
||||
if (!row || row.isSpinning || row.winner) {
|
||||
// Skip this row and go to next
|
||||
spinSequentialRow(rowIndex + 1);
|
||||
return;
|
||||
}
|
||||
|
||||
setCurrentSpinningRow(row.rowNumber);
|
||||
setSpinRows(prev => prev.map(r =>
|
||||
r.id === row.id ? { ...r, isSpinning: true, selectedWinner: null } : r
|
||||
));
|
||||
|
||||
const wheelElement = row.wheelRef.current;
|
||||
if (wheelElement) {
|
||||
wheelElement.style.transition = 'none';
|
||||
wheelElement.style.transform = 'translateY(0px)';
|
||||
wheelElement.offsetHeight;
|
||||
}
|
||||
|
||||
performDramaticSpin(row, true);
|
||||
};
|
||||
|
||||
const startSequentialSpinning = () => {
|
||||
if (spinRows.length === 0) return;
|
||||
|
||||
// Clear any existing results
|
||||
setWinnersHistory([]);
|
||||
setRevealedWinners(new Set());
|
||||
setSpinRows(prev => prev.map(row => ({
|
||||
...row,
|
||||
isSpinning: false,
|
||||
isShuffling: false,
|
||||
winner: null,
|
||||
selectedWinner: null,
|
||||
displayVouchers: [...row.vouchers]
|
||||
})));
|
||||
|
||||
// Reset all wheel positions
|
||||
spinRows.forEach(row => {
|
||||
const wheelElement = row.wheelRef.current;
|
||||
if (wheelElement) {
|
||||
wheelElement.style.transition = 'none';
|
||||
wheelElement.style.transform = 'translateY(0px)';
|
||||
}
|
||||
});
|
||||
|
||||
setIsSequentialSpinning(true);
|
||||
setCurrentSpinningRow(null);
|
||||
|
||||
// Start with first row after a short delay
|
||||
setTimeout(() => {
|
||||
spinSequentialRow(0);
|
||||
}, 500);
|
||||
};
|
||||
|
||||
const spinWheel = (rowId: string) => {
|
||||
const row = spinRows.find(r => r.id === rowId);
|
||||
if (!row || row.isSpinning || row.winner) return;
|
||||
|
||||
setSpinRows(prev => prev.map(r =>
|
||||
r.id === rowId ? { ...r, isSpinning: true, selectedWinner: null } : r
|
||||
));
|
||||
|
||||
const wheelElement = row.wheelRef.current;
|
||||
if (wheelElement) {
|
||||
wheelElement.style.transition = 'none';
|
||||
wheelElement.style.transform = 'translateY(0px)';
|
||||
wheelElement.offsetHeight;
|
||||
}
|
||||
|
||||
performSpin(row);
|
||||
};
|
||||
|
||||
const clearResults = () => {
|
||||
tickIntervalRefs.current.forEach(timeout => clearTimeout(timeout));
|
||||
shuffleIntervalRefs.current.forEach(timeout => clearTimeout(timeout));
|
||||
tickIntervalRefs.current.clear();
|
||||
shuffleIntervalRefs.current.clear();
|
||||
|
||||
setWinnersHistory([]);
|
||||
setRevealedWinners(new Set());
|
||||
setIsSequentialSpinning(false);
|
||||
setCurrentSpinningRow(null);
|
||||
setSpinRows(prev => prev.map(row => ({
|
||||
...row,
|
||||
isSpinning: false,
|
||||
isShuffling: false,
|
||||
winner: null,
|
||||
selectedWinner: null,
|
||||
displayVouchers: [...row.vouchers]
|
||||
})));
|
||||
|
||||
spinRows.forEach(row => {
|
||||
const wheelElement = row.wheelRef.current;
|
||||
if (wheelElement) {
|
||||
wheelElement.style.transition = 'none';
|
||||
wheelElement.style.transform = 'translateY(0px)';
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const refreshData = async () => {
|
||||
tickIntervalRefs.current.forEach(timeout => clearTimeout(timeout));
|
||||
shuffleIntervalRefs.current.forEach(timeout => clearTimeout(timeout));
|
||||
tickIntervalRefs.current.clear();
|
||||
shuffleIntervalRefs.current.clear();
|
||||
|
||||
try {
|
||||
await refetchVouchers();
|
||||
toast.success('Data refreshed successfully');
|
||||
} catch (error) {
|
||||
toast.error('Failed to refresh data');
|
||||
}
|
||||
};
|
||||
|
||||
const formatPhoneNumber = (phone: string) => {
|
||||
return phone.substring(0, 5) + '****' + phone.substring(phone.length - 2);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 text-gray-900 p-6">
|
||||
<style jsx>{`
|
||||
@keyframes bounce-in {
|
||||
0% {
|
||||
transform: scale(0.3);
|
||||
opacity: 0;
|
||||
}
|
||||
50% {
|
||||
transform: scale(1.05);
|
||||
}
|
||||
70% {
|
||||
transform: scale(0.9);
|
||||
}
|
||||
100% {
|
||||
transform: scale(1);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.animate-bounce-in {
|
||||
animation: bounce-in 0.6s ease-out;
|
||||
}
|
||||
`}</style>
|
||||
|
||||
<div className="max-w-full px-4 mx-auto">
|
||||
{/* Header */}
|
||||
<div className="text-center mb-8">
|
||||
<h1 className="text-5xl font-bold bg-gradient-to-r from-primary to-purple-600 bg-clip-text text-transparent mb-2">
|
||||
Voucher Lucky Draw
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* Controls Section - Compact Layout */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-3">
|
||||
{/* Configuration Card */}
|
||||
<div className="bg-white rounded-lg p-4 border border-gray-200 shadow-sm">
|
||||
<h2 className="text-lg font-semibold mb-3 text-gray-900">
|
||||
Configuration
|
||||
</h2>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-gray-700 mb-1">
|
||||
Number of Rows
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
max="10"
|
||||
value={numberOfRows}
|
||||
onChange={(e) => setNumberOfRows(parseInt(e.target.value) || 1)}
|
||||
className="w-full bg-white border border-gray-300 rounded p-1.5 text-sm text-gray-900 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20"
|
||||
disabled={isLoadingData}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-gray-700 mb-1">
|
||||
Prize Selection
|
||||
</label>
|
||||
<select
|
||||
value={selectedPrize}
|
||||
onChange={(e) => setSelectedPrize(parseInt(e.target.value))}
|
||||
className="w-full bg-white border border-gray-300 rounded p-1.5 text-sm text-gray-900 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20"
|
||||
disabled={isLoadingData}
|
||||
>
|
||||
<option value={1}>🥇 Emas 0.25 Gram</option>
|
||||
<option value={2}>🥇 Emas 3 Gram</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={refreshData}
|
||||
disabled={isLoadingData}
|
||||
className="w-full px-3 py-1.5 bg-primary hover:bg-primary/90 disabled:bg-gray-400 text-white text-sm font-semibold rounded flex items-center justify-center gap-1 transition-colors"
|
||||
>
|
||||
<RefreshCw size={14} className={isLoadingData ? 'animate-spin' : ''} />
|
||||
{isLoadingData ? 'Loading...' : 'Load Data'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{spinRows.length > 0 && (
|
||||
<div className="mt-3 p-2 bg-gray-50 rounded text-xs text-gray-600">
|
||||
<div>Rows: {spinRows.length} | Vouchers: {spinRows.reduce((acc, row) => acc + row.vouchers.length, 0)}</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Actions Card */}
|
||||
<div className="bg-white rounded-lg p-4 border border-gray-200 shadow-sm">
|
||||
<h2 className="text-lg font-semibold mb-3 text-gray-900">
|
||||
Actions
|
||||
</h2>
|
||||
|
||||
<div className="space-y-2">
|
||||
<button
|
||||
onClick={shuffleAllRows}
|
||||
disabled={isLoadingData || spinRows.some(r => r.isShuffling) || spinRows.length === 0}
|
||||
className="w-full px-3 py-1.5 bg-purple-600 hover:bg-purple-700 disabled:bg-gray-400 text-white text-sm font-semibold rounded flex items-center justify-center gap-1 transition-colors"
|
||||
>
|
||||
<Shuffle size={14} className={spinRows.some(r => r.isShuffling) ? 'animate-pulse' : ''} />
|
||||
Shuffle All
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={startSequentialSpinning}
|
||||
disabled={isSequentialSpinning || spinRows.length === 0}
|
||||
className="w-full px-3 py-1.5 bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 disabled:from-gray-400 disabled:to-gray-500 text-white text-sm font-bold rounded flex items-center justify-center gap-1 transition-all"
|
||||
>
|
||||
<Trophy size={14} className={isSequentialSpinning ? 'animate-spin' : ''} />
|
||||
{isSequentialSpinning ? 'Spinning...' : 'Spin for Winner'}
|
||||
</button>
|
||||
|
||||
{winnersHistory.length > 0 && (
|
||||
<button
|
||||
onClick={clearResults}
|
||||
className="w-full px-3 py-1.5 bg-red-600 hover:bg-red-700 text-white text-sm font-semibold rounded flex items-center justify-center gap-1 transition-colors"
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
Clear Results
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Winners Summary Card */}
|
||||
<div className="bg-white rounded-lg p-4 border border-gray-200 shadow-sm">
|
||||
<h2 className="text-lg font-semibold mb-3 text-gray-900 flex items-center gap-2">
|
||||
<Trophy className="text-yellow-500" size={18} />
|
||||
Winners
|
||||
</h2>
|
||||
|
||||
{winnersHistory.length > 0 ? (
|
||||
<div className="space-y-1 max-h-32 overflow-y-auto">
|
||||
{winnersHistory.map((history) => (
|
||||
<div
|
||||
key={`${history.rowNumber}-${history.timestamp.getTime()}`}
|
||||
className="p-1.5 bg-yellow-50 border border-yellow-200 rounded text-xs"
|
||||
>
|
||||
<div className="font-semibold text-yellow-700">
|
||||
Row {history.rowNumber}: {history.winner.name}
|
||||
</div>
|
||||
<div className="text-xs text-yellow-600">
|
||||
{history.winner.voucher_code}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center py-2">
|
||||
<Trophy className="mx-auto text-gray-300 mb-1" size={20} />
|
||||
<p className="text-gray-500 text-xs">No winners yet</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Spin Rows - Display in grid */}
|
||||
<div className={`grid gap-4 ${
|
||||
spinRows.length === 1 ? 'grid-cols-1' :
|
||||
spinRows.length === 2 ? 'grid-cols-1 lg:grid-cols-2' :
|
||||
spinRows.length === 3 ? 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3' :
|
||||
spinRows.length === 4 ? 'grid-cols-1 md:grid-cols-2 xl:grid-cols-4' :
|
||||
spinRows.length === 5 ? 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5' :
|
||||
'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4'
|
||||
}`}>
|
||||
{spinRows.map((row) => (
|
||||
<div key={row.id} className={`bg-white rounded-lg border-2 shadow-sm transition-all ${
|
||||
row.isShuffling ? 'border-purple-400 animate-pulse' : 'border-gray-200'
|
||||
}`}>
|
||||
<div className="p-4 border-b border-gray-200">
|
||||
|
||||
{row.winner && (
|
||||
<div className="mt-2 p-2 bg-yellow-50 border border-yellow-200 rounded-lg animate-bounce-in">
|
||||
<div className="flex items-center gap-1 text-sm">
|
||||
<Trophy className="text-yellow-500" size={16} />
|
||||
<span className="font-semibold text-yellow-700 truncate">
|
||||
{row.winner.name}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-xs text-yellow-600 mt-1">
|
||||
{row.winner.voucher_code}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Wheel Container */}
|
||||
<div
|
||||
className="relative bg-gray-50 overflow-hidden"
|
||||
style={{ height: '600px' }}
|
||||
>
|
||||
{/* Subtle Winner Zone Indicator */}
|
||||
<div
|
||||
className="absolute left-0 right-0 z-10 pointer-events-none"
|
||||
style={{
|
||||
top: '260px',
|
||||
height: '80px',
|
||||
background: 'linear-gradient(90deg, transparent 0%, rgba(34, 197, 94, 0.1) 20%, rgba(34, 197, 94, 0.2) 50%, rgba(34, 197, 94, 0.1) 80%, transparent 100%)',
|
||||
borderTop: '2px dashed rgba(34, 197, 94, 0.3)',
|
||||
borderBottom: '2px dashed rgba(34, 197, 94, 0.3)'
|
||||
}}
|
||||
>
|
||||
<div className="absolute right-2 top-1/2 transform -translate-y-1/2">
|
||||
<div className="bg-green-500 text-white px-2 py-1 rounded text-xs font-bold shadow-lg">
|
||||
🏆 WINNER
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Scrolling Cards */}
|
||||
<div
|
||||
ref={row.wheelRef}
|
||||
className="absolute inset-0"
|
||||
style={{ transform: 'translateY(0px)' }}
|
||||
>
|
||||
{Array.from({ length: 50 }, (_, repeatIndex) =>
|
||||
row.displayVouchers.map((voucher, voucherIndex) => {
|
||||
const isSelectedWinner = row.selectedWinner?.voucher_code === voucher.voucher_code;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={`${repeatIndex}-${voucherIndex}`}
|
||||
className={`flex items-center px-4 border-b border-gray-300 transition-all duration-300 ${
|
||||
isSelectedWinner
|
||||
? 'bg-gradient-to-r from-yellow-100 to-yellow-200 border-yellow-300 shadow-lg'
|
||||
: voucherIndex % 2 === 0
|
||||
? 'bg-white hover:bg-gray-50'
|
||||
: 'bg-gray-50 hover:bg-gray-100'
|
||||
}`}
|
||||
style={{
|
||||
height: '80px',
|
||||
minHeight: '80px',
|
||||
maxHeight: '80px',
|
||||
boxSizing: 'border-box'
|
||||
}}
|
||||
>
|
||||
<div className="flex-1">
|
||||
<div className={`font-bold text-lg mb-1 ${
|
||||
isSelectedWinner ? 'text-yellow-600' : 'text-gray-900'
|
||||
}`}>
|
||||
{voucher.voucher_code}
|
||||
</div>
|
||||
<div className={`text-sm ${
|
||||
isSelectedWinner ? 'text-yellow-700' : 'text-gray-600'
|
||||
}`}>
|
||||
{voucher.name}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="text-right">
|
||||
<div className="text-gray-500 text-xs">
|
||||
{formatPhoneNumber(voucher.phone_number)}
|
||||
</div>
|
||||
{isSelectedWinner && (
|
||||
<Trophy className="inline ml-2 text-yellow-500" size={16} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Gradient Overlays */}
|
||||
<div className="absolute top-0 left-0 right-0 h-32 bg-gradient-to-b from-gray-50 via-gray-50/70 to-transparent pointer-events-none z-40"></div>
|
||||
<div className="absolute bottom-0 left-0 right-0 h-32 bg-gradient-to-t from-gray-50 via-gray-50/70 to-transparent pointer-events-none z-40"></div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default RandomDrawApp;
|
||||
@@ -0,0 +1,7 @@
|
||||
import CampaignDetailContent from '@/views/apps/marketing/campaign/detail'
|
||||
|
||||
const CampaignDetailPage = () => {
|
||||
return <CampaignDetailContent />
|
||||
}
|
||||
|
||||
export default CampaignDetailPage
|
||||
@@ -0,0 +1,7 @@
|
||||
import CampaignListTable from '@/views/apps/marketing/campaign/CampaignListTable'
|
||||
|
||||
const CampaignPage = () => {
|
||||
return <CampaignListTable />
|
||||
}
|
||||
|
||||
export default CampaignPage
|
||||
@@ -0,0 +1,7 @@
|
||||
import CustomerAnalyticList from '@/views/apps/marketing/customer-analytics'
|
||||
|
||||
const CustomerAnalyticsPage = () => {
|
||||
return <CustomerAnalyticList />
|
||||
}
|
||||
|
||||
export default CustomerAnalyticsPage
|
||||
@@ -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
|
||||
@@ -0,0 +1,7 @@
|
||||
import DiscountList from '@/views/apps/marketing/discount'
|
||||
|
||||
const DiscountPage = () => {
|
||||
return <DiscountList />
|
||||
}
|
||||
|
||||
export default DiscountPage
|
||||
@@ -0,0 +1,7 @@
|
||||
import GamePrizeList from '@/views/apps/marketing/games/game-prizes'
|
||||
|
||||
const GamePrizePage = () => {
|
||||
return <GamePrizeList />
|
||||
}
|
||||
|
||||
export default GamePrizePage
|
||||
@@ -0,0 +1,7 @@
|
||||
import GamesList from '@/views/apps/marketing/games/list'
|
||||
|
||||
const GamePage = () => {
|
||||
return <GamesList />
|
||||
}
|
||||
|
||||
export default GamePage
|
||||
@@ -0,0 +1,7 @@
|
||||
import WheelSpinList from '@/views/apps/marketing/gamification/wheel-spin'
|
||||
|
||||
const WheelSpinPage = () => {
|
||||
return <WheelSpinList />
|
||||
}
|
||||
|
||||
export default WheelSpinPage
|
||||
@@ -0,0 +1,7 @@
|
||||
import LoyaltyList from '@/views/apps/marketing/loyalty'
|
||||
|
||||
const LoyaltiPage = () => {
|
||||
return <LoyaltyList />
|
||||
}
|
||||
|
||||
export default LoyaltiPage
|
||||
@@ -0,0 +1,7 @@
|
||||
import RewardList from '@/views/apps/marketing/reward'
|
||||
|
||||
const RewardPage = () => {
|
||||
return <RewardList />
|
||||
}
|
||||
|
||||
export default RewardPage
|
||||
@@ -0,0 +1,7 @@
|
||||
import TierList from '@/views/apps/marketing/tier'
|
||||
|
||||
const TierPage = () => {
|
||||
return <TierList />
|
||||
}
|
||||
|
||||
export default TierPage
|
||||
@@ -0,0 +1,7 @@
|
||||
import VoucherList from '@/views/apps/marketing/voucher'
|
||||
|
||||
const VoucherPage = () => {
|
||||
return <VoucherList />
|
||||
}
|
||||
|
||||
export default VoucherPage
|
||||
@@ -8,23 +8,63 @@ import {
|
||||
useCategoryAnalytics
|
||||
} from '@/services/queries/analytics'
|
||||
import { useOutletById } from '@/services/queries/outlets'
|
||||
import { generateExcel } from '@/utils/excelGenerator'
|
||||
import { generatePDF } from '@/utils/pdfGenerator'
|
||||
import { formatCurrency, formatDate, formatDateDDMMYYYY, formatDatetime } from '@/utils/transform'
|
||||
import ReportGeneratorComponent from '@/views/dashboards/daily-report/report-generator'
|
||||
import ReportHeader from '@/views/dashboards/daily-report/report-header'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
|
||||
// Dummy HPP values — ganti dengan data real nantinya
|
||||
const DUMMY_STD_HPP = 30 // % — ganti dengan data real nantinya
|
||||
const DUMMY_REAL_HPP = 0 // % — ganti dengan kalkulasi real nantinya
|
||||
|
||||
const getHppStatus = (stdHpp: number, realHpp: number): 'Sehat' | 'Tidak Sehat' =>
|
||||
realHpp <= stdHpp ? 'Sehat' : 'Tidak Sehat'
|
||||
|
||||
const StatusBadge = ({ status }: { status: 'Sehat' | 'Tidak Sehat' }) => (
|
||||
<span
|
||||
className={`inline-block px-3 py-1 rounded-full text-base font-bold ${
|
||||
status === 'Sehat' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
|
||||
}`}
|
||||
>
|
||||
{status}
|
||||
</span>
|
||||
)
|
||||
|
||||
const DailyPOSReport = () => {
|
||||
const reportRef = useRef<HTMLDivElement | null>(null)
|
||||
|
||||
const [isGeneratingExcel, setIsGeneratingExcel] = useState(false)
|
||||
|
||||
const [now, setNow] = useState(new Date())
|
||||
const [selectedDate, setSelectedDate] = useState(new Date())
|
||||
const [dateRange, setDateRange] = useState({
|
||||
startDate: new Date(),
|
||||
endDate: new Date()
|
||||
})
|
||||
const [filterType, setFilterType] = useState<'single' | 'range'>('single') // 'single' or 'range'
|
||||
const [filterType, setFilterType] = useState<'single' | 'range'>('single')
|
||||
const [isGeneratingPDF, setIsGeneratingPDF] = useState(false)
|
||||
|
||||
// PDF Font Size Configuration
|
||||
const PDF_FONT_SIZES = {
|
||||
heading: 18,
|
||||
subheading: 16,
|
||||
tableContent: 12,
|
||||
tableHeader: 12,
|
||||
tableFooter: 12,
|
||||
grandTotal: 14,
|
||||
footer: 11
|
||||
}
|
||||
|
||||
// PDF Spacing Configuration
|
||||
const PDF_SPACING = {
|
||||
cellPadding: 5,
|
||||
cellPaddingLarge: 6,
|
||||
sectionGap: 20,
|
||||
headerGap: 15
|
||||
}
|
||||
|
||||
// Use selectedDate for single date filter, or dateRange for range filter
|
||||
const getDateParams = () => {
|
||||
if (filterType === 'single') {
|
||||
return {
|
||||
@@ -41,8 +81,15 @@ const DailyPOSReport = () => {
|
||||
|
||||
const dateParams = getDateParams()
|
||||
|
||||
const today = new Date()
|
||||
const sevenDaysAgo = new Date()
|
||||
sevenDaysAgo.setDate(today.getDate() - 7)
|
||||
|
||||
const { data: outlet } = useOutletById()
|
||||
const { data: sales } = useSalesAnalytics(dateParams)
|
||||
const { data: profitLoss7Days } = useProfitLossAnalytics({
|
||||
date_from: formatDateDDMMYYYY(sevenDaysAgo),
|
||||
date_to: formatDateDDMMYYYY(today)
|
||||
})
|
||||
const { data: profitLoss } = useProfitLossAnalytics(dateParams)
|
||||
const { data: products } = useProductSalesAnalytics(dateParams)
|
||||
const { data: paymentAnalytics } = usePaymentAnalytics(dateParams)
|
||||
@@ -54,14 +101,6 @@ const DailyPOSReport = () => {
|
||||
totalOrders: products?.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0
|
||||
}
|
||||
|
||||
// Calculate profit loss product summary
|
||||
const profitLossProductSummary = {
|
||||
totalRevenue: profitLoss?.product_data?.reduce((sum, item) => sum + (item?.revenue || 0), 0) || 0,
|
||||
totalCost: profitLoss?.product_data?.reduce((sum, item) => sum + (item?.cost || 0), 0) || 0,
|
||||
totalGrossProfit: profitLoss?.product_data?.reduce((sum, item) => sum + (item?.gross_profit || 0), 0) || 0,
|
||||
totalQuantity: profitLoss?.product_data?.reduce((sum, item) => sum + (item?.quantity_sold || 0), 0) || 0
|
||||
}
|
||||
|
||||
const categorySummary = {
|
||||
totalRevenue: category?.data?.reduce((sum, item) => sum + (item?.total_revenue || 0), 0) || 0,
|
||||
orderCount: category?.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0,
|
||||
@@ -73,12 +112,10 @@ const DailyPOSReport = () => {
|
||||
setNow(new Date())
|
||||
}, [])
|
||||
|
||||
// Format date for input field (YYYY-MM-DD)
|
||||
const formatDateForInput = (date: Date) => {
|
||||
return date.toISOString().split('T')[0]
|
||||
}
|
||||
|
||||
// Get display text for the report period
|
||||
const getReportPeriodText = () => {
|
||||
if (filterType === 'single') {
|
||||
return `${formatDateDDMMYYYY(selectedDate)} - ${formatDateDDMMYYYY(selectedDate)}`
|
||||
@@ -87,98 +124,107 @@ const DailyPOSReport = () => {
|
||||
}
|
||||
}
|
||||
|
||||
// Get report title based on filter type
|
||||
const getReportTitle = () => {
|
||||
if (filterType === 'single') {
|
||||
return 'Laporan Transaksi'
|
||||
} else {
|
||||
const daysDiff = Math.ceil((dateRange.endDate.getTime() - dateRange.startDate.getTime()) / (1000 * 3600 * 24)) + 1
|
||||
// return `Laporan Transaksi ${daysDiff} Hari`
|
||||
return `Laporan Transaksi`
|
||||
}
|
||||
return 'Laporan Transaksi'
|
||||
}
|
||||
|
||||
const handleGeneratePDF = async () => {
|
||||
const reportElement = reportRef.current
|
||||
|
||||
setIsGeneratingPDF(true)
|
||||
try {
|
||||
// Import jsPDF dan html2canvas
|
||||
const jsPDF = (await import('jspdf')).default
|
||||
const html2canvas = (await import('html2canvas')).default
|
||||
|
||||
// Optimized canvas capture dengan scale lebih rendah
|
||||
const canvas = await html2canvas(reportElement!, {
|
||||
scale: 1.5, // Reduced from 2 to 1.5
|
||||
useCORS: true,
|
||||
allowTaint: true,
|
||||
backgroundColor: '#ffffff',
|
||||
logging: false, // Disable logging for performance
|
||||
removeContainer: true, // Clean up after capture
|
||||
imageTimeout: 0, // No timeout for image loading
|
||||
height: reportElement!.scrollHeight,
|
||||
width: reportElement!.scrollWidth
|
||||
await generatePDF({
|
||||
reportRef,
|
||||
outlet,
|
||||
profitLoss,
|
||||
products,
|
||||
paymentAnalytics,
|
||||
category,
|
||||
productSummary,
|
||||
categorySummary,
|
||||
filterType,
|
||||
selectedDate,
|
||||
dateRange,
|
||||
now
|
||||
})
|
||||
|
||||
// Compress canvas using JPEG with quality setting
|
||||
const imgData = canvas.toDataURL('image/jpeg', 0.85) // JPEG with 85% quality instead of PNG
|
||||
|
||||
// Create PDF with compression
|
||||
const pdf = new jsPDF({
|
||||
orientation: 'portrait',
|
||||
unit: 'mm',
|
||||
format: 'a4',
|
||||
compress: true // Enable built-in compression
|
||||
})
|
||||
|
||||
const imgWidth = 210
|
||||
const pageHeight = 295
|
||||
const imgHeight = (canvas.height * imgWidth) / canvas.width
|
||||
let heightLeft = imgHeight
|
||||
let position = 0
|
||||
|
||||
// Add first page with compressed image
|
||||
pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight, '', 'FAST') // Use FAST compression
|
||||
heightLeft -= pageHeight
|
||||
|
||||
// Handle multiple pages if needed
|
||||
while (heightLeft >= 0) {
|
||||
position = heightLeft - imgHeight
|
||||
pdf.addPage()
|
||||
pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight, '', 'FAST')
|
||||
heightLeft -= pageHeight
|
||||
}
|
||||
|
||||
// Additional compression options
|
||||
pdf.setProperties({
|
||||
title: `${getReportTitle()}`,
|
||||
subject: 'Daily Transaction Report',
|
||||
author: 'Apskel POS System',
|
||||
creator: 'Apskel'
|
||||
})
|
||||
|
||||
// Save with optimized settings
|
||||
const fileName =
|
||||
filterType === 'single'
|
||||
? `laporan-transaksi-${formatDateForInput(selectedDate)}.pdf`
|
||||
: `laporan-transaksi-${formatDateForInput(dateRange.startDate)}-to-${formatDateForInput(dateRange.endDate)}.pdf`
|
||||
|
||||
pdf.save(fileName, {
|
||||
returnPromise: true
|
||||
})
|
||||
|
||||
// Clean up canvas to free memory
|
||||
canvas.width = canvas.height = 0
|
||||
} catch (error) {
|
||||
console.error('Error generating PDF:', error)
|
||||
alert('Terjadi kesalahan saat membuat PDF. Pastikan jsPDF dan html2canvas sudah terinstall.')
|
||||
alert(`Terjadi kesalahan saat membuat PDF: ${error}`)
|
||||
} finally {
|
||||
setIsGeneratingPDF(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleGenerateExcel = async () => {
|
||||
setIsGeneratingExcel(true)
|
||||
try {
|
||||
await generateExcel({
|
||||
outlet,
|
||||
profitLoss,
|
||||
products,
|
||||
paymentAnalytics,
|
||||
category,
|
||||
productSummary,
|
||||
categorySummary,
|
||||
filterType,
|
||||
selectedDate,
|
||||
dateRange
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Error generating Excel:', error)
|
||||
alert(`Terjadi kesalahan saat membuat Excel: ${error}`)
|
||||
} finally {
|
||||
setIsGeneratingExcel(false)
|
||||
}
|
||||
}
|
||||
|
||||
const LoadingOverlay = ({ isVisible, message = 'Generating PDF...' }: { isVisible: boolean; message?: string }) => {
|
||||
if (!isVisible) return null
|
||||
|
||||
return (
|
||||
<div className='fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 backdrop-blur-sm'>
|
||||
<div className='bg-white rounded-lg shadow-xl p-8 max-w-sm w-full mx-4'>
|
||||
<div className='text-center'>
|
||||
<div className='inline-block animate-spin rounded-full h-12 w-12 border-4 border-gray-200 border-t-purple-600 mb-4'></div>
|
||||
<h3 className='text-lg font-semibold text-gray-800 mb-2'>{message}</h3>
|
||||
<p className='text-sm text-gray-600'>Mohon tunggu, proses ini mungkin membutuhkan beberapa detik...</p>
|
||||
<div className='mt-6 space-y-2'>
|
||||
<div className='flex items-center text-xs text-gray-500'>
|
||||
<div className='w-2 h-2 bg-green-500 rounded-full mr-2 flex-shrink-0'></div>
|
||||
<span>Capturing report content</span>
|
||||
</div>
|
||||
<div className='flex items-center text-xs text-gray-500'>
|
||||
<div className='w-2 h-2 bg-blue-500 rounded-full mr-2 flex-shrink-0 animate-pulse'></div>
|
||||
<span>Processing pages</span>
|
||||
</div>
|
||||
<div className='flex items-center text-xs text-gray-500'>
|
||||
<div className='w-2 h-2 bg-gray-300 rounded-full mr-2 flex-shrink-0'></div>
|
||||
<span>Finalizing PDF</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Group products by category
|
||||
const groupedProducts =
|
||||
products?.data?.reduce(
|
||||
(acc, item) => {
|
||||
const categoryName = item.category_name || 'Tidak Berkategori'
|
||||
if (!acc[categoryName]) {
|
||||
acc[categoryName] = []
|
||||
}
|
||||
acc[categoryName].push(item)
|
||||
return acc
|
||||
},
|
||||
{} as Record<string, any[]>
|
||||
) || {}
|
||||
|
||||
return (
|
||||
<div className='min-h-screen'>
|
||||
{/* Control Panel */}
|
||||
<LoadingOverlay isVisible={isGeneratingPDF} message='Membuat PDF Laporan...' />
|
||||
|
||||
<ReportGeneratorComponent
|
||||
// Props wajib
|
||||
reportTitle='Laporan Penjualan'
|
||||
filterType={filterType}
|
||||
selectedDate={selectedDate}
|
||||
@@ -187,161 +233,99 @@ const DailyPOSReport = () => {
|
||||
onSingleDateChange={setSelectedDate}
|
||||
onDateRangeChange={setDateRange}
|
||||
onGeneratePDF={handleGeneratePDF}
|
||||
// Props opsional
|
||||
// isGenerating={isGenerating}
|
||||
// customQuickActions={customQuickActions}
|
||||
// labels={customLabels}
|
||||
onGenerateExcel={handleGenerateExcel}
|
||||
isGeneratingExcel={isGeneratingExcel}
|
||||
/>
|
||||
|
||||
{/* Report Template */}
|
||||
<div ref={reportRef} className='max-w-4xl mx-auto bg-white min-h-[297mm]' style={{ width: '210mm' }}>
|
||||
{/* Header */}
|
||||
<ReportHeader
|
||||
outlet={outlet}
|
||||
reportTitle={getReportTitle()}
|
||||
reportSubtitle='Laporan Bulanan'
|
||||
brandName='Apskel'
|
||||
brandColor='#36175e'
|
||||
periode={getReportPeriodText()}
|
||||
/>
|
||||
{/* Wrap header in a section for easy capture */}
|
||||
<div className='report-header-section'>
|
||||
<ReportHeader
|
||||
outlet={outlet}
|
||||
reportTitle={getReportTitle()}
|
||||
reportSubtitle='Laporan Bulanan'
|
||||
brandName='Apskel'
|
||||
brandColor='#36175e'
|
||||
periode={getReportPeriodText()}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Performance Summary */}
|
||||
<div className='p-8'>
|
||||
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
|
||||
1. Ringkasan
|
||||
<h3 className='text-3xl font-bold mb-8' style={{ color: '#36175e' }}>
|
||||
Ringkasan
|
||||
</h3>
|
||||
|
||||
<div className='grid grid-cols-2 gap-6'>
|
||||
<div className='space-y-4'>
|
||||
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
||||
<span className='text-gray-700'>Total Penjualan (termasuk rasik)</span>
|
||||
<span className='font-semibold text-gray-800'>
|
||||
{formatCurrency(profitLoss?.summary.total_revenue ?? 0)}
|
||||
</span>
|
||||
</div>
|
||||
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
||||
<span className='text-gray-700'>Total Terjual</span>
|
||||
<span className='font-semibold text-gray-800'>{productSummary.totalQuantitySold}</span>
|
||||
</div>
|
||||
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
||||
<span className='text-gray-700'>HPP</span>
|
||||
<span className='font-semibold text-gray-800'>
|
||||
{formatCurrency(profitLoss?.summary.total_cost ?? 0)} |{' '}
|
||||
{(((profitLoss?.summary.total_cost ?? 0) / (profitLoss?.summary.total_revenue || 1)) * 100).toFixed(
|
||||
0
|
||||
)}
|
||||
%
|
||||
</span>
|
||||
</div>
|
||||
<div className='flex justify-between items-center py-2 border-b-2 border-gray-300'>
|
||||
<span className='text-lg font-semibold text-green-800'>Laba Kotor</span>
|
||||
<span className='text-lg font-bold text-green-800'>
|
||||
{formatCurrency(profitLoss?.summary.gross_profit ?? 0)} |{' '}
|
||||
{(profitLoss?.summary.gross_profit_margin ?? 0).toFixed(0)}%
|
||||
</span>
|
||||
</div>
|
||||
<div className='space-y-5'>
|
||||
<div className='flex justify-between items-center py-3 border-b border-gray-200'>
|
||||
<span className='text-xl text-gray-700'>Total Penjualan</span>
|
||||
<span className='text-xl font-semibold text-gray-800'>
|
||||
{formatCurrency(profitLoss?.summary.total_revenue ?? 0)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className='space-y-4'>
|
||||
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
||||
<span className='text-gray-700'>Biaya lain²</span>
|
||||
<span className='font-semibold text-gray-800'>
|
||||
{formatCurrency(profitLoss?.summary.total_tax ?? 0)} |{' '}
|
||||
{(((profitLoss?.summary.total_tax ?? 0) / (profitLoss?.summary.total_revenue || 1)) * 100).toFixed(0)}
|
||||
%
|
||||
</span>
|
||||
</div>
|
||||
<div className='flex justify-between items-center py-2 border-b-2 border-gray-300'>
|
||||
<span className='text-lg font-bold text-blue-800'>Laba/Rugi</span>
|
||||
<span className='text-lg font-bold text-blue-800'>
|
||||
{formatCurrency(profitLoss?.summary.net_profit ?? 0)} |{' '}
|
||||
{(profitLoss?.summary.net_profit_margin ?? 0).toFixed(0)}%
|
||||
</span>
|
||||
</div>
|
||||
<div className='flex justify-between items-center py-3 border-b border-gray-200'>
|
||||
<span className='text-xl text-gray-700'>Total Diskon</span>
|
||||
<span className='text-xl font-semibold text-gray-800'>
|
||||
{formatCurrency(profitLoss?.summary.total_discount ?? 0)}
|
||||
</span>
|
||||
</div>
|
||||
<div className='flex justify-between items-center py-3 border-b border-gray-200'>
|
||||
<span className='text-xl text-gray-700'>Total Pajak</span>
|
||||
<span className='text-xl font-semibold text-gray-800'>
|
||||
{formatCurrency(profitLoss?.summary.total_tax ?? 0)}
|
||||
</span>
|
||||
</div>
|
||||
<div className='flex justify-between items-center py-3 border-b border-gray-200'>
|
||||
<span className='text-xl text-gray-700'>Service Charge</span>
|
||||
<span className='text-xl font-semibold text-gray-800'>{formatCurrency(0)}</span>
|
||||
</div>
|
||||
<div className='flex justify-between items-center py-3 border-b-2 border-gray-300'>
|
||||
<span className='text-xl text-gray-700 font-bold'>Total</span>
|
||||
<span className='text-xl font-bold text-gray-800'>
|
||||
{formatCurrency(profitLoss?.summary.total_revenue ?? 0)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Profit Loss Product Table */}
|
||||
{/* Invoice */}
|
||||
<div className='px-8 pb-8'>
|
||||
<h3 className='text-lg font-medium mb-6' style={{ color: '#36175e' }}>
|
||||
Laba Rugi Per Produk
|
||||
<h3 className='text-3xl font-bold mb-8' style={{ color: '#36175e' }}>
|
||||
Invoice
|
||||
</h3>
|
||||
|
||||
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
|
||||
<table className='w-full'>
|
||||
<thead>
|
||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
||||
<th className='text-left p-3 font-semibold'>Produk</th>
|
||||
<th className='text-center p-3 font-semibold'>Qty</th>
|
||||
<th className='text-right p-3 font-semibold'>Pendapatan</th>
|
||||
<th className='text-right p-3 font-semibold'>HPP</th>
|
||||
<th className='text-right p-3 font-semibold'>Laba Kotor</th>
|
||||
<th className='text-center p-3 font-semibold'>Margin (%)</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{profitLoss?.product_data?.map((item, index) => (
|
||||
<tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
|
||||
<td className='p-3 font-medium text-gray-800'>{item.product_name}</td>
|
||||
<td className='p-3 text-center text-gray-700'>{item.quantity_sold}</td>
|
||||
<td className='p-3 text-right font-semibold text-gray-800'>{formatCurrency(item.revenue)}</td>
|
||||
<td className='p-3 text-right font-semibold text-red-600'>{formatCurrency(item.cost)}</td>
|
||||
<td className='p-3 text-right font-semibold text-green-600'>{formatCurrency(item.gross_profit)}</td>
|
||||
<td className='p-3 text-center font-semibold' style={{ color: '#36175e' }}>
|
||||
{(item.gross_profit_margin ?? 0).toFixed(1)}%
|
||||
</td>
|
||||
</tr>
|
||||
)) || []}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
||||
<td className='p-3 font-bold'>TOTAL</td>
|
||||
<td className='p-3 text-center font-bold'>{profitLossProductSummary.totalQuantity}</td>
|
||||
<td className='p-3 text-right font-bold'>{formatCurrency(profitLossProductSummary.totalRevenue)}</td>
|
||||
<td className='p-3 text-right font-bold'>{formatCurrency(profitLossProductSummary.totalCost)}</td>
|
||||
<td className='p-3 text-right font-bold'>
|
||||
{formatCurrency(profitLossProductSummary.totalGrossProfit)}
|
||||
</td>
|
||||
<td className='p-3 text-center font-bold'>
|
||||
{profitLossProductSummary.totalRevenue > 0
|
||||
? (
|
||||
(profitLossProductSummary.totalGrossProfit / profitLossProductSummary.totalRevenue) *
|
||||
100
|
||||
).toFixed(1)
|
||||
: 0}
|
||||
%
|
||||
</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
<div className='space-y-5'>
|
||||
<div className='flex justify-between items-center py-3 border-b border-gray-200'>
|
||||
<span className='text-xl text-gray-700'>Total Invoice</span>
|
||||
<span className='text-xl font-semibold text-gray-800'>{profitLoss?.summary.total_orders ?? 0}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Payment Method Summary */}
|
||||
<div className='px-8 pb-8'>
|
||||
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
|
||||
2. Ringkasan Metode Pembayaran
|
||||
<h3 className='text-3xl font-bold mb-8' style={{ color: '#36175e' }}>
|
||||
Ringkasan Metode Pembayaran
|
||||
</h3>
|
||||
|
||||
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
|
||||
<table className='w-full'>
|
||||
<thead>
|
||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
||||
<th className='text-left p-3 font-semibold'>Metode Pembayaran</th>
|
||||
<th className='text-center p-3 font-semibold'>Tipe</th>
|
||||
<th className='text-center p-3 font-semibold'>Jumlah Order</th>
|
||||
<th className='text-right p-3 font-semibold'>Total Amount</th>
|
||||
<th className='text-center p-3 font-semibold'>Persentase</th>
|
||||
<tr className='text-gray-800 border-b-2 border-gray-300'>
|
||||
<th className='text-left text-xl p-4 font-semibold'>Metode Pembayaran</th>
|
||||
<th className='text-center text-xl p-4 font-semibold'>Tipe</th>
|
||||
<th className='text-center text-xl p-4 font-semibold'>Jumlah Order</th>
|
||||
<th className='text-right text-xl p-4 font-semibold'>Total Amount</th>
|
||||
<th className='text-center text-xl p-4 font-semibold'>Persentase</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{paymentAnalytics?.data?.map((payment, index) => (
|
||||
<tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
|
||||
<td className='p-3 font-medium text-gray-800'>{payment.payment_method_name}</td>
|
||||
<td className='p-3 text-center'>
|
||||
<td className='p-4 text-xl font-medium text-gray-800'>{payment.payment_method_name}</td>
|
||||
<td className='p-4 text-center'>
|
||||
<span
|
||||
className={`px-2 py-1 rounded-full text-xs font-medium ${
|
||||
className={`px-3 py-1 rounded-full text-lg font-medium ${
|
||||
payment.payment_method_type === 'cash'
|
||||
? 'bg-green-100 text-green-800'
|
||||
: 'bg-blue-100 text-blue-800'
|
||||
@@ -350,123 +334,240 @@ const DailyPOSReport = () => {
|
||||
{payment.payment_method_type.toUpperCase()}
|
||||
</span>
|
||||
</td>
|
||||
<td className='p-3 text-center text-gray-700'>{payment.order_count}</td>
|
||||
<td className='p-3 text-right font-semibold text-gray-800'>
|
||||
<td className='p-4 text-xl text-center text-gray-700'>{payment.order_count}</td>
|
||||
<td className='p-4 text-xl text-right font-semibold text-gray-800'>
|
||||
{formatCurrency(payment.total_amount)}
|
||||
</td>
|
||||
<td className='p-3 text-center font-medium' style={{ color: '#36175e' }}>
|
||||
<td className='p-4 text-xl text-center font-medium' style={{ color: '#36175e' }}>
|
||||
{(payment.percentage ?? 0).toFixed(1)}%
|
||||
</td>
|
||||
</tr>
|
||||
)) || []}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
||||
<td className='p-3 font-bold'>TOTAL</td>
|
||||
<td className='p-3'></td>
|
||||
<td className='p-3 text-center font-bold'>{paymentAnalytics?.summary.total_orders ?? 0}</td>
|
||||
<td className='p-3 text-right font-bold'>
|
||||
<tr className='text-gray-800 border-t-2 border-gray-300'>
|
||||
<td className='p-4 text-xl font-bold'>TOTAL</td>
|
||||
<td className='p-4'></td>
|
||||
<td className='p-4 text-xl text-center font-bold'>{paymentAnalytics?.summary.total_orders ?? 0}</td>
|
||||
<td className='p-4 text-xl text-right font-bold'>
|
||||
{formatCurrency(paymentAnalytics?.summary.total_amount ?? 0)}
|
||||
</td>
|
||||
<td className='p-3 text-center font-bold'></td>
|
||||
<td className='p-4 text-center font-bold'></td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Category Summary */}
|
||||
{/* Category Summary — +3 kolom baru */}
|
||||
<div className='px-8 pb-8'>
|
||||
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
|
||||
2. Ringkasan Kategori
|
||||
<h3 className='text-3xl font-bold mb-8' style={{ color: '#36175e' }}>
|
||||
Ringkasan Kategori
|
||||
</h3>
|
||||
|
||||
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
|
||||
<table className='w-full'>
|
||||
<thead>
|
||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
||||
<th className='text-left p-3 font-semibold'>Nama</th>
|
||||
<th className='text-center p-3 font-semibold'>Total Produk</th>
|
||||
<th className='text-center p-3 font-semibold'>Qty</th>
|
||||
<th className='text-right p-3 font-semibold'>Jumlah Order</th>
|
||||
<th className='text-center p-3 font-semibold'>Pendapatan</th>
|
||||
<tr className='text-gray-800 border-b-2 border-gray-300'>
|
||||
<th className='text-left text-xl p-4 font-semibold'>Nama</th>
|
||||
<th className='text-center text-xl p-4 font-semibold'>Qty</th>
|
||||
<th className='text-right text-xl p-4 font-semibold'>Pendapatan</th>
|
||||
<th className='text-center text-xl p-4 font-semibold'>% Std HPP</th>
|
||||
<th className='text-center text-xl p-4 font-semibold'>% Real HPP</th>
|
||||
<th className='text-center text-xl p-4 font-semibold'>Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{category?.data?.map((c, index) => (
|
||||
<tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
|
||||
<td className='p-3 font-medium text-gray-800'>{c.category_name}</td>
|
||||
<td className='p-3 text-center text-gray-700'>{c.product_count}</td>
|
||||
<td className='p-3 text-center text-gray-700'>{c.total_quantity}</td>
|
||||
<td className='p-3 text-center text-gray-700'>{c.order_count}</td>
|
||||
<td className='p-3 text-right font-semibold' style={{ color: '#36175e' }}>
|
||||
{formatCurrency(c.total_revenue)}
|
||||
{category?.data?.map((c, index) => {
|
||||
const stdHpp = DUMMY_STD_HPP
|
||||
const realHpp = DUMMY_REAL_HPP
|
||||
const status = getHppStatus(stdHpp, realHpp)
|
||||
return (
|
||||
<tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
|
||||
<td className='p-4 text-xl font-medium text-gray-800'>{c.category_name}</td>
|
||||
<td className='p-4 text-xl text-center text-gray-700'>{c.total_quantity}</td>
|
||||
<td className='p-4 text-xl text-right font-semibold' style={{ color: '#36175e' }}>
|
||||
{formatCurrency(c.total_revenue)}
|
||||
</td>
|
||||
<td className='p-4 text-xl text-center text-gray-700'>{stdHpp}%</td>
|
||||
<td className='p-4 text-xl text-center text-gray-700'>{realHpp}%</td>
|
||||
<td className='p-4 text-center'>
|
||||
<StatusBadge status={status} />
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
}) || []}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr className='text-gray-800 border-t-2 border-gray-300'>
|
||||
<td className='p-4 text-xl font-bold'>TOTAL</td>
|
||||
<td className='p-4 text-xl text-center font-bold'>{categorySummary?.totalQuantity ?? 0}</td>
|
||||
<td className='p-4 text-xl text-right font-bold'>
|
||||
{formatCurrency(categorySummary?.totalRevenue ?? 0)}
|
||||
</td>
|
||||
<td className='p-4'></td>
|
||||
<td className='p-4'></td>
|
||||
<td className='p-4'></td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Product Summary — +3 kolom baru */}
|
||||
<div className='px-8 pb-8'>
|
||||
<h3 className='text-3xl font-bold mb-8' style={{ color: '#36175e' }}>
|
||||
Ringkasan Item Per Kategori
|
||||
</h3>
|
||||
|
||||
<div className='space-y-12'>
|
||||
{Object.keys(groupedProducts)
|
||||
.sort((a, b) => {
|
||||
const productsA = groupedProducts[a]
|
||||
const productsB = groupedProducts[b]
|
||||
const orderA = productsA[0]?.category_order ?? 999
|
||||
const orderB = productsB[0]?.category_order ?? 999
|
||||
return orderA - orderB
|
||||
})
|
||||
.map((categoryName, catIndex) => {
|
||||
const categoryProducts = groupedProducts[categoryName].sort((a, b) => {
|
||||
const skuA = a.product_sku || ''
|
||||
const skuB = b.product_sku || ''
|
||||
return skuA.localeCompare(skuB)
|
||||
})
|
||||
const categoryTotalQty = categoryProducts.reduce((sum, item) => sum + (item.quantity_sold || 0), 0)
|
||||
const categoryTotalRevenue = categoryProducts.reduce((sum, item) => sum + (item.revenue || 0), 0)
|
||||
|
||||
return (
|
||||
<div key={categoryName} style={{ display: 'block', marginBottom: '70px' }}>
|
||||
<h4
|
||||
className='text-2xl font-bold mb-0 px-4 py-4 bg-gray-100 rounded-t-lg'
|
||||
style={{ color: '#36175e' }}
|
||||
>
|
||||
{categoryName.toUpperCase()}
|
||||
</h4>
|
||||
|
||||
<div className='bg-gray-50 rounded-b-lg border-l-2 border-r-2 border-b-2 border-gray-300'>
|
||||
<table
|
||||
className='w-full'
|
||||
style={{ borderCollapse: 'collapse', tableLayout: 'fixed', width: '100%' }}
|
||||
>
|
||||
<colgroup>
|
||||
<col style={{ width: '28%' }} />
|
||||
<col style={{ width: '10%' }} />
|
||||
<col style={{ width: '22%' }} />
|
||||
<col style={{ width: '13%' }} />
|
||||
<col style={{ width: '13%' }} />
|
||||
<col style={{ width: '14%' }} />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr className='text-gray-800 border-b-2 border-gray-300 bg-gray-100'>
|
||||
<th className='text-left text-xl p-5 font-semibold border-r border-gray-300'>Produk</th>
|
||||
<th className='text-center text-xl p-5 font-semibold border-r border-gray-300'>Qty</th>
|
||||
<th className='text-right text-xl p-5 font-semibold border-r border-gray-300'>
|
||||
Pendapatan
|
||||
</th>
|
||||
<th className='text-center text-xl p-5 font-semibold border-r border-gray-300'>
|
||||
% Std HPP
|
||||
</th>
|
||||
<th className='text-center text-xl p-5 font-semibold border-r border-gray-300'>
|
||||
% Real HPP
|
||||
</th>
|
||||
<th className='text-center text-xl p-5 font-semibold'>Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{categoryProducts.map((item, index) => {
|
||||
const stdHpp = DUMMY_STD_HPP
|
||||
const realHpp = DUMMY_REAL_HPP
|
||||
const status = getHppStatus(stdHpp, realHpp)
|
||||
return (
|
||||
<tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
|
||||
<td className='p-5 text-xl font-medium text-gray-800 border-r border-gray-200'>
|
||||
{item.product_name}
|
||||
</td>
|
||||
<td className='p-5 text-xl text-center text-gray-700 border-r border-gray-200'>
|
||||
{item.quantity_sold}
|
||||
</td>
|
||||
<td className='p-5 text-xl text-right font-semibold text-gray-800 border-r border-gray-200'>
|
||||
{formatCurrency(item.revenue)}
|
||||
</td>
|
||||
<td className='p-5 text-xl text-center text-gray-700 border-r border-gray-200'>
|
||||
{stdHpp}%
|
||||
</td>
|
||||
<td className='p-5 text-xl text-center text-gray-700 border-r border-gray-200'>
|
||||
{realHpp}%
|
||||
</td>
|
||||
<td className='p-5 text-center'>
|
||||
<StatusBadge status={status} />
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr className='bg-gray-200 border-t-2 border-gray-400'>
|
||||
<td className='p-5 text-xl font-bold text-gray-800 border-r border-gray-400'>
|
||||
Subtotal {categoryName}
|
||||
</td>
|
||||
<td className='p-5 text-xl text-center font-bold text-gray-800 border-r border-gray-400'>
|
||||
{categoryTotalQty}
|
||||
</td>
|
||||
<td className='p-5 text-xl text-right font-bold text-gray-800 border-r border-gray-400'>
|
||||
{formatCurrency(categoryTotalRevenue)}
|
||||
</td>
|
||||
<td className='p-5 border-r border-gray-400'></td>
|
||||
<td className='p-5 border-r border-gray-400'></td>
|
||||
<td className='p-5'></td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* Grand Total */}
|
||||
<div className='bg-purple-50 rounded-lg border-2 border-purple-300 mt-6'>
|
||||
<table className='w-full' style={{ borderCollapse: 'collapse', tableLayout: 'fixed' }}>
|
||||
<colgroup>
|
||||
<col style={{ width: '28%' }} />
|
||||
<col style={{ width: '10%' }} />
|
||||
<col style={{ width: '22%' }} />
|
||||
<col style={{ width: '13%' }} />
|
||||
<col style={{ width: '13%' }} />
|
||||
<col style={{ width: '14%' }} />
|
||||
</colgroup>
|
||||
<tfoot>
|
||||
<tr className='text-gray-800'>
|
||||
<td className='p-5 text-2xl font-bold border-r-2 border-purple-300' style={{ color: '#36175e' }}>
|
||||
TOTAL KESELURUHAN
|
||||
</td>
|
||||
<td
|
||||
className='p-5 text-2xl text-center font-bold border-r-2 border-purple-300'
|
||||
style={{ color: '#36175e' }}
|
||||
>
|
||||
{productSummary.totalQuantitySold ?? 0}
|
||||
</td>
|
||||
<td
|
||||
className='p-5 text-2xl text-right font-bold border-r-2 border-purple-300'
|
||||
style={{ color: '#36175e' }}
|
||||
>
|
||||
{formatCurrency(productSummary.totalRevenue ?? 0)}
|
||||
</td>
|
||||
<td className='p-5 border-r-2 border-purple-300'></td>
|
||||
<td className='p-5 border-r-2 border-purple-300'></td>
|
||||
<td className='p-5'></td>
|
||||
</tr>
|
||||
)) || []}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
||||
<td className='p-3 font-bold'>TOTAL</td>
|
||||
<td className='p-3 text-center font-bold'>{categorySummary?.productCount ?? 0}</td>
|
||||
<td className='p-3 text-center font-bold'>{categorySummary?.totalQuantity ?? 0}</td>
|
||||
<td className='p-3 text-center font-bold'>{categorySummary?.orderCount ?? 0}</td>
|
||||
<td className='p-3 text-right font-bold'>{formatCurrency(categorySummary?.totalRevenue ?? 0)}</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Transaction Summary */}
|
||||
<div className='px-8 pb-8'>
|
||||
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
|
||||
4. Ringkasan Item
|
||||
</h3>
|
||||
|
||||
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
|
||||
<table className='w-full'>
|
||||
<thead>
|
||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
||||
<th className='text-left p-3 font-semibold'>Produk</th>
|
||||
<th className='text-left p-3 font-semibold'>Kategori</th>
|
||||
<th className='text-center p-3 font-semibold'>Qty</th>
|
||||
<th className='text-right p-3 font-semibold'>Order</th>
|
||||
<th className='text-right p-3 font-semibold'>Pendapatan</th>
|
||||
<th className='text-right p-3 font-semibold'>Rata Rata</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{products?.data?.map((item, index) => (
|
||||
<tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
|
||||
<td className='p-3 font-medium text-gray-800'>{item.product_name}</td>
|
||||
<td className='p-3 font-medium text-gray-800'>{item.category_name}</td>
|
||||
<td className='p-3 text-center text-gray-700'>{item.quantity_sold}</td>
|
||||
<td className='p-3 text-center text-gray-700'>{item.order_count ?? 0}</td>
|
||||
<td className='p-3 text-right font-semibold text-gray-800'>{formatCurrency(item.revenue)}</td>
|
||||
<td className='p-3 text-right font-medium text-gray-800'>{formatCurrency(item.average_price)}</td>
|
||||
</tr>
|
||||
)) || []}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
||||
<td className='p-3 font-bold'>TOTAL</td>
|
||||
<td className='p-3 text-center'></td>
|
||||
<td className='p-3 text-center font-bold'>{productSummary.totalQuantitySold ?? 0}</td>
|
||||
<td className='p-3 text-right font-bold'>{productSummary.totalOrders ?? 0}</td>
|
||||
<td className='p-3 text-right font-bold'>{formatCurrency(productSummary.totalRevenue ?? 0)}</td>
|
||||
<td className='p-3 text-right font-bold'></td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Profit Loss Product Table */}
|
||||
|
||||
{/* Footer */}
|
||||
<div className='px-8 py-6 border-t-2 border-gray-200 mt-8'>
|
||||
<div className='flex justify-between items-center text-sm text-gray-600'>
|
||||
<div className='flex justify-between items-center text-base text-gray-600'>
|
||||
<p>© 2025 Apskel - Sistem POS Terpadu</p>
|
||||
<p></p>
|
||||
<p>Dicetak pada: {now.toLocaleDateString('id-ID')}</p>
|
||||
|
||||
@@ -4,7 +4,12 @@ import { TextField, Typography, useTheme } from '@mui/material'
|
||||
import { useState } from 'react'
|
||||
import Loading from '../../../../../../components/layout/shared/Loading'
|
||||
import { useDashboardAnalytics } from '../../../../../../services/queries/analytics'
|
||||
import { formatDateDDMMYYYY, formatForInputDate, formatShortCurrency } from '../../../../../../utils/transform'
|
||||
import {
|
||||
formatCurrency,
|
||||
formatDateDDMMYYYY,
|
||||
formatForInputDate,
|
||||
formatShortCurrency
|
||||
} from '../../../../../../utils/transform'
|
||||
import OrdersReport from '../../../../../../views/dashboards/orders/OrdersReport'
|
||||
import PaymentMethodReport from '../../../../../../views/dashboards/payment-methods/PaymentMethodReport'
|
||||
import ProductSales from '../../../../../../views/dashboards/products/ProductSales'
|
||||
@@ -115,14 +120,14 @@ const DashboardOverview = () => {
|
||||
<MetricCard
|
||||
iconClass='tabler-cash'
|
||||
title='Total Sales'
|
||||
value={formatShortCurrency(salesData.overview.total_sales)}
|
||||
value={formatCurrency(salesData.overview.total_sales)}
|
||||
bgColor='bg-green-500'
|
||||
isCurrency={true}
|
||||
/>
|
||||
<MetricCard
|
||||
iconClass='tabler-trending-up'
|
||||
title='Average Order Value'
|
||||
value={formatShortCurrency(salesData.overview.average_order_value)}
|
||||
value={formatCurrency(salesData.overview.average_order_value)}
|
||||
bgColor='bg-purple-500'
|
||||
isCurrency={true}
|
||||
/>
|
||||
|
||||
@@ -162,21 +162,21 @@ const DashboardProfitloss = () => {
|
||||
<MetricCard
|
||||
iconClass='tabler-currency-dollar'
|
||||
title='Total Revenue'
|
||||
value={formatShortCurrency(profitData.summary.total_revenue)}
|
||||
value={formatCurrency(profitData.summary.total_revenue)}
|
||||
bgColor='bg-green-500'
|
||||
isCurrency={true}
|
||||
/>
|
||||
<MetricCard
|
||||
iconClass='tabler-receipt'
|
||||
title='Total Cost'
|
||||
value={formatShortCurrency(profitData.summary.total_cost)}
|
||||
value={formatCurrency(profitData.summary.total_cost)}
|
||||
bgColor='bg-red-500'
|
||||
isCurrency={true}
|
||||
/>
|
||||
<MetricCard
|
||||
iconClass='tabler-trending-up'
|
||||
title='Gross Profit'
|
||||
value={formatShortCurrency(profitData.summary.gross_profit)}
|
||||
value={formatCurrency(profitData.summary.gross_profit)}
|
||||
subtitle={`Margin: ${formatPercentage(profitData.summary.gross_profit_margin)}`}
|
||||
bgColor='bg-blue-500'
|
||||
isNegative={profitData.summary.gross_profit < 0}
|
||||
@@ -186,7 +186,7 @@ const DashboardProfitloss = () => {
|
||||
iconClass='tabler-percentage'
|
||||
title='Profitability Ratio'
|
||||
value={formatPercentage(profitData.summary.profitability_ratio)}
|
||||
subtitle={`Avg Profit: ${formatShortCurrency(profitData.summary.average_profit)}`}
|
||||
subtitle={`Avg Profit: ${formatCurrency(profitData.summary.average_profit)}`}
|
||||
bgColor='bg-purple-500'
|
||||
/>
|
||||
</div>
|
||||
@@ -199,7 +199,7 @@ const DashboardProfitloss = () => {
|
||||
<h3 className='text-lg font-semibold text-gray-900'>Net Profit</h3>
|
||||
</div>
|
||||
<p className='text-3xl font-bold text-green-600 mb-2'>
|
||||
Rp {formatShortCurrency(profitData.summary.net_profit)}
|
||||
{formatCurrency(profitData.summary.net_profit)}
|
||||
</p>
|
||||
<p className='text-sm text-gray-600'>
|
||||
Margin: {formatPercentage(profitData.summary.net_profit_margin)}
|
||||
|
||||
@@ -0,0 +1,465 @@
|
||||
'use client'
|
||||
|
||||
// React Imports
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
// MUI Imports
|
||||
import type { BoxProps } from '@mui/material/Box'
|
||||
import Button from '@mui/material/Button'
|
||||
import IconButton from '@mui/material/IconButton'
|
||||
import List from '@mui/material/List'
|
||||
import ListItem from '@mui/material/ListItem'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import Chip from '@mui/material/Chip'
|
||||
import LinearProgress from '@mui/material/LinearProgress'
|
||||
import { styled } from '@mui/material/styles'
|
||||
|
||||
// Third-party Imports
|
||||
import { useDropzone } from 'react-dropzone'
|
||||
|
||||
// Component Imports
|
||||
import Link from '@components/Link'
|
||||
import CustomAvatar from '@core/components/mui/Avatar'
|
||||
|
||||
// Styled Component Imports
|
||||
import AppReactDropzone from '@/libs/styles/AppReactDropzone'
|
||||
|
||||
type FileProp = {
|
||||
name: string
|
||||
type: string
|
||||
size: number
|
||||
}
|
||||
|
||||
type UploadedImage = {
|
||||
id: string
|
||||
url: string
|
||||
name: string
|
||||
size: number
|
||||
}
|
||||
|
||||
type UploadProgress = {
|
||||
[fileId: string]: number
|
||||
}
|
||||
|
||||
interface MultipleImageUploadProps {
|
||||
// Required props
|
||||
onUpload: (files: File[]) => Promise<string[]> | string[] // Returns array of image URLs
|
||||
onSingleUpload?: (file: File) => Promise<string> | string // For individual file upload
|
||||
|
||||
// Optional customization props
|
||||
title?: string | null
|
||||
currentImages?: UploadedImage[]
|
||||
onImagesChange?: (images: UploadedImage[]) => void
|
||||
onImageRemove?: (imageId: string) => void
|
||||
|
||||
// Upload state
|
||||
isUploading?: boolean
|
||||
uploadProgress?: UploadProgress
|
||||
|
||||
// Limits
|
||||
maxFiles?: number
|
||||
maxFileSize?: number // in bytes
|
||||
acceptedFileTypes?: string[]
|
||||
|
||||
// UI customization
|
||||
showUrlOption?: boolean
|
||||
uploadButtonText?: string
|
||||
browseButtonText?: string
|
||||
dragDropText?: string
|
||||
replaceText?: string
|
||||
maxFilesText?: string
|
||||
|
||||
// Style customization
|
||||
className?: string
|
||||
disabled?: boolean
|
||||
|
||||
// Upload modes
|
||||
uploadMode?: 'batch' | 'individual' // batch: upload all at once, individual: upload one by one
|
||||
}
|
||||
|
||||
// Styled Dropzone Component
|
||||
const Dropzone = styled(AppReactDropzone)<BoxProps>(({ theme }) => ({
|
||||
'& .dropzone': {
|
||||
minHeight: 'unset',
|
||||
padding: theme.spacing(12),
|
||||
[theme.breakpoints.down('sm')]: {
|
||||
paddingInline: theme.spacing(5)
|
||||
},
|
||||
'&+.MuiList-root .MuiListItem-root .file-name': {
|
||||
fontWeight: theme.typography.body1.fontWeight
|
||||
}
|
||||
}
|
||||
}))
|
||||
|
||||
const MultipleImageUpload: React.FC<MultipleImageUploadProps> = ({
|
||||
onUpload,
|
||||
onSingleUpload,
|
||||
title = null,
|
||||
currentImages = [],
|
||||
onImagesChange,
|
||||
onImageRemove,
|
||||
isUploading = false,
|
||||
uploadProgress = {},
|
||||
maxFiles = 10,
|
||||
maxFileSize = 5 * 1024 * 1024, // 5MB default
|
||||
acceptedFileTypes = ['image/*'],
|
||||
showUrlOption = true,
|
||||
uploadButtonText = 'Upload All',
|
||||
browseButtonText = 'Browse Images',
|
||||
dragDropText = 'Drag and Drop Your Images Here.',
|
||||
replaceText = 'Drop Images to Add More',
|
||||
maxFilesText = 'Maximum {max} files allowed',
|
||||
className = '',
|
||||
disabled = false,
|
||||
uploadMode = 'batch'
|
||||
}) => {
|
||||
// States
|
||||
const [files, setFiles] = useState<File[]>([])
|
||||
const [error, setError] = useState<string>('')
|
||||
const [individualUploading, setIndividualUploading] = useState<Set<string>>(new Set())
|
||||
|
||||
const handleBatchUpload = async () => {
|
||||
if (!files.length) return
|
||||
|
||||
try {
|
||||
setError('')
|
||||
const imageUrls = await onUpload(files)
|
||||
|
||||
if (Array.isArray(imageUrls)) {
|
||||
const newImages: UploadedImage[] = files.map((file, index) => ({
|
||||
id: `${Date.now()}-${index}`,
|
||||
url: imageUrls[index],
|
||||
name: file.name,
|
||||
size: file.size
|
||||
}))
|
||||
|
||||
const updatedImages = [...currentImages, ...newImages]
|
||||
onImagesChange?.(updatedImages)
|
||||
setFiles([]) // Clear files after successful upload
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Upload failed')
|
||||
}
|
||||
}
|
||||
|
||||
const handleIndividualUpload = async (file: File, fileIndex: number) => {
|
||||
if (!onSingleUpload) return
|
||||
|
||||
const fileId = `${file.name}-${fileIndex}`
|
||||
setIndividualUploading(prev => new Set(prev).add(fileId))
|
||||
|
||||
try {
|
||||
setError('')
|
||||
const imageUrl = await onSingleUpload(file)
|
||||
|
||||
if (typeof imageUrl === 'string') {
|
||||
const newImage: UploadedImage = {
|
||||
id: `${Date.now()}-${fileIndex}`,
|
||||
url: imageUrl,
|
||||
name: file.name,
|
||||
size: file.size
|
||||
}
|
||||
|
||||
const updatedImages = [...currentImages, newImage]
|
||||
onImagesChange?.(updatedImages)
|
||||
|
||||
// Remove uploaded file from pending files
|
||||
setFiles(prev => prev.filter((_, index) => index !== fileIndex))
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Upload failed')
|
||||
} finally {
|
||||
setIndividualUploading(prev => {
|
||||
const newSet = new Set(prev)
|
||||
newSet.delete(fileId)
|
||||
return newSet
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Hooks
|
||||
const { getRootProps, getInputProps } = useDropzone({
|
||||
onDrop: (acceptedFiles: File[]) => {
|
||||
setError('')
|
||||
|
||||
if (acceptedFiles.length === 0) return
|
||||
|
||||
const totalFiles = currentImages.length + files.length + acceptedFiles.length
|
||||
|
||||
if (totalFiles > maxFiles) {
|
||||
setError(`Cannot upload more than ${maxFiles} files. Current: ${currentImages.length + files.length}`)
|
||||
return
|
||||
}
|
||||
|
||||
// Validate file sizes
|
||||
const invalidFiles = acceptedFiles.filter(file => file.size > maxFileSize)
|
||||
if (invalidFiles.length > 0) {
|
||||
setError(`Some files exceed ${formatFileSize(maxFileSize)} limit`)
|
||||
return
|
||||
}
|
||||
|
||||
// Add to existing files
|
||||
setFiles(prev => [...prev, ...acceptedFiles])
|
||||
},
|
||||
accept: acceptedFileTypes.reduce((acc, type) => ({ ...acc, [type]: [] }), {}),
|
||||
disabled: disabled || isUploading,
|
||||
multiple: true
|
||||
})
|
||||
|
||||
const formatFileSize = (bytes: number): string => {
|
||||
if (bytes === 0) return '0 Bytes'
|
||||
const k = 1024
|
||||
const sizes = ['Bytes', 'KB', 'MB', 'GB']
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
|
||||
}
|
||||
|
||||
const renderFilePreview = (file: FileProp) => {
|
||||
if (file.type.startsWith('image')) {
|
||||
return (
|
||||
<img
|
||||
width={38}
|
||||
height={38}
|
||||
alt={file.name}
|
||||
src={URL.createObjectURL(file as any)}
|
||||
className='rounded object-cover'
|
||||
/>
|
||||
)
|
||||
} else {
|
||||
return <i className='tabler-file-description' />
|
||||
}
|
||||
}
|
||||
|
||||
const handleRemoveFile = (fileIndex: number) => {
|
||||
setFiles(prev => prev.filter((_, index) => index !== fileIndex))
|
||||
setError('')
|
||||
}
|
||||
|
||||
const handleRemoveCurrentImage = (imageId: string) => {
|
||||
onImageRemove?.(imageId)
|
||||
}
|
||||
|
||||
const handleRemoveAllFiles = () => {
|
||||
setFiles([])
|
||||
setError('')
|
||||
}
|
||||
|
||||
const isIndividualUploading = (file: File, index: number) => {
|
||||
const fileId = `${file.name}-${index}`
|
||||
return individualUploading.has(fileId)
|
||||
}
|
||||
|
||||
const fileList = files.map((file: File, index: number) => {
|
||||
const isFileUploading = isIndividualUploading(file, index)
|
||||
const progress = uploadProgress[`${file.name}-${index}`] || 0
|
||||
|
||||
return (
|
||||
<ListItem key={`${file.name}-${index}`} className='pis-4 plb-3'>
|
||||
<div className='file-details flex-1'>
|
||||
<div className='file-preview'>{renderFilePreview(file)}</div>
|
||||
<div className='flex-1'>
|
||||
<Typography className='file-name font-medium' color='text.primary'>
|
||||
{file.name}
|
||||
</Typography>
|
||||
<Typography className='file-size' variant='body2'>
|
||||
{formatFileSize(file.size)}
|
||||
</Typography>
|
||||
{isFileUploading && progress > 0 && (
|
||||
<LinearProgress variant='determinate' value={progress} className='mt-1' />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex items-center gap-2'>
|
||||
{uploadMode === 'individual' && onSingleUpload && (
|
||||
<Button
|
||||
variant='outlined'
|
||||
size='small'
|
||||
onClick={() => handleIndividualUpload(file, index)}
|
||||
disabled={isUploading || isFileUploading}
|
||||
>
|
||||
{isFileUploading ? 'Uploading...' : 'Upload'}
|
||||
</Button>
|
||||
)}
|
||||
<IconButton onClick={() => handleRemoveFile(index)} disabled={isUploading || isFileUploading}>
|
||||
<i className='tabler-x text-xl' />
|
||||
</IconButton>
|
||||
</div>
|
||||
</ListItem>
|
||||
)
|
||||
})
|
||||
|
||||
const currentImagesList = currentImages.map(image => (
|
||||
<ListItem key={image.id} className='pis-4 plb-3'>
|
||||
<div className='file-details flex-1'>
|
||||
<div className='file-preview'>
|
||||
<img width={38} height={38} alt={image.name} src={image.url} className='rounded object-cover' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<Typography className='file-name font-medium' color='text.primary'>
|
||||
{image.name}
|
||||
</Typography>
|
||||
<Typography className='file-size' variant='body2'>
|
||||
{formatFileSize(image.size)}
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex items-center gap-2'>
|
||||
<Chip label='Uploaded' color='success' size='small' />
|
||||
{onImageRemove && (
|
||||
<IconButton onClick={() => handleRemoveCurrentImage(image.id)} color='error' disabled={isUploading}>
|
||||
<i className='tabler-x text-xl' />
|
||||
</IconButton>
|
||||
)}
|
||||
</div>
|
||||
</ListItem>
|
||||
))
|
||||
|
||||
return (
|
||||
<Dropzone className={className}>
|
||||
{/* Conditional title and URL option header */}
|
||||
{title && (
|
||||
<div className='flex justify-between items-center mb-4'>
|
||||
<Typography variant='h6' component='h2'>
|
||||
{title}
|
||||
</Typography>
|
||||
{showUrlOption && (
|
||||
<Typography component={Link} color='primary.main' className='font-medium'>
|
||||
Add media from URL
|
||||
</Typography>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* File limits info */}
|
||||
<div className='flex justify-between items-center mb-4'>
|
||||
<Typography variant='body2' color='text.secondary'>
|
||||
{maxFilesText.replace('{max}', maxFiles.toString())}
|
||||
</Typography>
|
||||
<Typography variant='body2' color='text.secondary'>
|
||||
{currentImages.length + files.length} / {maxFiles} files
|
||||
</Typography>
|
||||
</div>
|
||||
|
||||
<div {...getRootProps({ className: 'dropzone' })}>
|
||||
<input {...getInputProps()} />
|
||||
<div className='flex items-center flex-col gap-2 text-center'>
|
||||
<CustomAvatar variant='rounded' skin='light' color='secondary'>
|
||||
<i className='tabler-upload' />
|
||||
</CustomAvatar>
|
||||
<Typography variant='h4'>
|
||||
{currentImages.length > 0 || files.length > 0 ? replaceText : dragDropText}
|
||||
</Typography>
|
||||
<Typography color='text.disabled'>or</Typography>
|
||||
<Button variant='tonal' size='small' disabled={disabled || isUploading}>
|
||||
{browseButtonText}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Error Message */}
|
||||
{error && (
|
||||
<Typography color='error' variant='body2' className='mt-2 text-center'>
|
||||
{error}
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
{/* Current uploaded images */}
|
||||
{currentImages.length > 0 && (
|
||||
<div className='mt-4'>
|
||||
<Typography variant='subtitle2' className='mb-2'>
|
||||
Uploaded Images ({currentImages.length}):
|
||||
</Typography>
|
||||
<List>{currentImagesList}</List>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Pending files list and upload buttons */}
|
||||
{files.length > 0 && (
|
||||
<div className='mt-4'>
|
||||
<Typography variant='subtitle2' className='mb-2'>
|
||||
Pending Files ({files.length}):
|
||||
</Typography>
|
||||
<List>{fileList}</List>
|
||||
<div className='buttons flex gap-2 mt-3'>
|
||||
<Button color='error' variant='tonal' onClick={handleRemoveAllFiles} disabled={isUploading}>
|
||||
Remove All
|
||||
</Button>
|
||||
{uploadMode === 'batch' && (
|
||||
<Button variant='contained' onClick={handleBatchUpload} disabled={isUploading || files.length === 0}>
|
||||
{isUploading ? 'Uploading...' : `${uploadButtonText} (${files.length})`}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Dropzone>
|
||||
)
|
||||
}
|
||||
|
||||
export default MultipleImageUpload
|
||||
|
||||
// ===== USAGE EXAMPLES =====
|
||||
|
||||
// 1. Batch upload mode (upload all files at once)
|
||||
// const [images, setImages] = useState<UploadedImage[]>([])
|
||||
//
|
||||
// <MultipleImageUpload
|
||||
// title="Product Images"
|
||||
// onUpload={handleBatchUpload}
|
||||
// currentImages={images}
|
||||
// onImagesChange={setImages}
|
||||
// onImageRemove={(id) => setImages(prev => prev.filter(img => img.id !== id))}
|
||||
// maxFiles={5}
|
||||
// uploadMode="batch"
|
||||
// />
|
||||
|
||||
// 2. Individual upload mode (upload files one by one)
|
||||
// <MultipleImageUpload
|
||||
// title="Gallery Images"
|
||||
// onUpload={handleBatchUpload}
|
||||
// onSingleUpload={handleSingleUpload}
|
||||
// currentImages={images}
|
||||
// onImagesChange={setImages}
|
||||
// onImageRemove={(id) => setImages(prev => prev.filter(img => img.id !== id))}
|
||||
// maxFiles={10}
|
||||
// uploadMode="individual"
|
||||
// uploadProgress={uploadProgress}
|
||||
// />
|
||||
|
||||
// 3. Without title, custom limits
|
||||
// <MultipleImageUpload
|
||||
// title={null}
|
||||
// onUpload={handleBatchUpload}
|
||||
// currentImages={images}
|
||||
// onImagesChange={setImages}
|
||||
// maxFiles={3}
|
||||
// maxFileSize={2 * 1024 * 1024} // 2MB
|
||||
// acceptedFileTypes={['image/jpeg', 'image/png']}
|
||||
// />
|
||||
|
||||
// 4. Example upload handlers
|
||||
// const handleBatchUpload = async (files: File[]): Promise<string[]> => {
|
||||
// const formData = new FormData()
|
||||
// files.forEach(file => formData.append('images', file))
|
||||
//
|
||||
// const response = await fetch('/api/upload-multiple', {
|
||||
// method: 'POST',
|
||||
// body: formData
|
||||
// })
|
||||
//
|
||||
// const result = await response.json()
|
||||
// return result.urls // Array of uploaded image URLs
|
||||
// }
|
||||
//
|
||||
// const handleSingleUpload = async (file: File): Promise<string> => {
|
||||
// const formData = new FormData()
|
||||
// formData.append('image', file)
|
||||
//
|
||||
// const response = await fetch('/api/upload-single', {
|
||||
// method: 'POST',
|
||||
// body: formData
|
||||
// })
|
||||
//
|
||||
// const result = await response.json()
|
||||
// return result.url // Single uploaded image URL
|
||||
// }
|
||||
@@ -153,6 +153,28 @@ const VerticalMenu = ({ dictionary, scrollMenu }: Props) => {
|
||||
>
|
||||
{dictionary['navigation'].reports}
|
||||
</MenuItem>
|
||||
<SubMenu label={dictionary['navigation'].marketing} icon={<i className='tabler-shopping-cart' />}>
|
||||
{/* <MenuItem href={`/${locale}/apps/marketing/loyalty`}>{dictionary['navigation'].loyalty}</MenuItem> */}
|
||||
<MenuItem href={`/${locale}/apps/marketing/reward`}>{dictionary['navigation'].reward}</MenuItem>
|
||||
{/* <SubMenu label={dictionary['navigation'].gamification}>
|
||||
<MenuItem href={`/${locale}/apps/marketing/gamification/wheel-spin`}>
|
||||
{dictionary['navigation'].wheel_spin}
|
||||
</MenuItem>
|
||||
</SubMenu> */}
|
||||
<SubMenu label={dictionary['navigation'].games}>
|
||||
<MenuItem href={`/${locale}/apps/marketing/games/list`}>{dictionary['navigation'].list}</MenuItem>
|
||||
<MenuItem href={`/${locale}/apps/marketing/games/game-prizes`}>
|
||||
{dictionary['navigation'].game_prizes}
|
||||
</MenuItem>
|
||||
</SubMenu>
|
||||
<MenuItem href={`/${locale}/apps/marketing/campaign`}>{dictionary['navigation'].campaign}</MenuItem>
|
||||
{/* <MenuItem href={`/${locale}/apps/marketing/customer-analytics`}>
|
||||
{dictionary['navigation'].customer_analytics}
|
||||
</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/discount`}>{dictionary['navigation'].discount}</MenuItem> */}
|
||||
</SubMenu>
|
||||
<SubMenu label={dictionary['navigation'].inventory} icon={<i className='tabler-salad' />}>
|
||||
<SubMenu label={dictionary['navigation'].products}>
|
||||
<MenuItem href={`/${locale}/apps/inventory/products/list`}>{dictionary['navigation'].list}</MenuItem>
|
||||
@@ -212,6 +234,9 @@ const VerticalMenu = ({ dictionary, scrollMenu }: Props) => {
|
||||
>
|
||||
{dictionary['navigation'].vendor}
|
||||
</MenuItem>
|
||||
<MenuItem href={`/${locale}/draw`} icon={<i className='tabler-building' />} target='_blank'>
|
||||
Random Draw
|
||||
</MenuItem>
|
||||
</MenuSection>
|
||||
</Menu>
|
||||
</ScrollWrapper>
|
||||
|
||||
@@ -126,6 +126,18 @@
|
||||
"expenses": "Expenses",
|
||||
"cash_and_bank": "Cash & Bank",
|
||||
"account": "Account",
|
||||
"fixed_assets": "Fixed Assets"
|
||||
"fixed_assets": "Fixed Assets",
|
||||
"marketing": "Marketing",
|
||||
"loyalty": "Loyalty",
|
||||
"reward": "Reward",
|
||||
"gamification": "Gamification",
|
||||
"wheel_spin": "Wheel Spin",
|
||||
"campaign": "Campaign",
|
||||
"customer_analytics": "Customer Analytics",
|
||||
"voucher": "Voucher",
|
||||
"tiers_text": "Tiers",
|
||||
"games": "Games",
|
||||
"game_prizes": "Game Prizes",
|
||||
"discount": "Discount"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,6 +126,18 @@
|
||||
"expenses": "Biaya",
|
||||
"cash_and_bank": "Kas & Bank",
|
||||
"account": "Akun",
|
||||
"fixed_assets": "Aset Tetap"
|
||||
"fixed_assets": "Aset Tetap",
|
||||
"marketing": "Pemasaran",
|
||||
"loyalty": "Loyalti",
|
||||
"reward": "Reward",
|
||||
"gamification": "Gamifikasi",
|
||||
"wheel_spin": "Wheel Spin",
|
||||
"campaign": "Kampanye",
|
||||
"customer_analytics": "Analisis Pelanggan",
|
||||
"voucher": "Vocher",
|
||||
"tiers_text": "Tiers",
|
||||
"games": "Permainan",
|
||||
"game_prizes": "Hadiah Permainan",
|
||||
"Discount": "Diskon"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 })
|
||||
})
|
||||
|
||||
@@ -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)
|
||||
)
|
||||
}
|
||||
+3
-3
@@ -6,7 +6,8 @@ const getToken = () => {
|
||||
}
|
||||
|
||||
export const api = axios.create({
|
||||
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'
|
||||
},
|
||||
@@ -30,9 +31,8 @@ api.interceptors.response.use(
|
||||
response => response,
|
||||
error => {
|
||||
const status = error.response?.status
|
||||
const currentPath = window.location.pathname
|
||||
|
||||
if (status === 401 && !currentPath.endsWith('/login')) {
|
||||
if (status === 401) {
|
||||
localStorage.removeItem('user')
|
||||
localStorage.removeItem('authToken')
|
||||
window.location.href = '/login'
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { CampaignRequest, CampaignRuleRequest } from '@/types/services/campaign'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'react-toastify'
|
||||
import { api } from '../api'
|
||||
|
||||
export const useCampaignsMutation = () => {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const createCampaign = useMutation({
|
||||
mutationFn: async (newCampaign: CampaignRequest) => {
|
||||
const response = await api.post('/marketing/campaigns', newCampaign)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Campaign created successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['campaigns'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
|
||||
}
|
||||
})
|
||||
|
||||
const updateCampaign = useMutation({
|
||||
mutationFn: async ({ id, payload }: { id: string; payload: CampaignRequest }) => {
|
||||
const response = await api.put(`/marketing/campaigns/${id}`, payload)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Campaign updated successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['campaigns'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Update failed')
|
||||
}
|
||||
})
|
||||
|
||||
const deleteCampaign = useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const response = await api.delete(`/marketing/campaigns/${id}`)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Campaign deleted successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['campaigns'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Delete failed')
|
||||
}
|
||||
})
|
||||
|
||||
return { createCampaign, updateCampaign, deleteCampaign }
|
||||
}
|
||||
|
||||
export const useCampaignRulesMutation = () => {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const createCampaignRule = useMutation({
|
||||
mutationFn: async (newCampaignRule: CampaignRuleRequest) => {
|
||||
const response = await api.post('/marketing/campaign-rules', newCampaignRule)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('CampaignRule created successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['campaign-rules/campaign'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
|
||||
}
|
||||
})
|
||||
|
||||
const updateCampaignRule = useMutation({
|
||||
mutationFn: async ({ id, payload }: { id: string; payload: CampaignRuleRequest }) => {
|
||||
const response = await api.put(`/marketing/campaign-rules/${id}`, payload)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('CampaignRule updated successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['campaign-rules/campaign'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Update failed')
|
||||
}
|
||||
})
|
||||
|
||||
const deleteCampaignRule = useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const response = await api.delete(`/marketing/campaign-rules/${id}`)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('CampaignRule deleted successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['campaign-rules/campaign'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Delete failed')
|
||||
}
|
||||
})
|
||||
|
||||
return { createCampaignRule, updateCampaignRule, deleteCampaignRule }
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { GameRequest } from '@/types/services/game'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'react-toastify'
|
||||
import { api } from '../api'
|
||||
|
||||
export const useGamesMutation = () => {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const createGame = useMutation({
|
||||
mutationFn: async (newGame: GameRequest) => {
|
||||
const response = await api.post('/marketing/games', newGame)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Game created successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['games'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
|
||||
}
|
||||
})
|
||||
|
||||
const updateGame = useMutation({
|
||||
mutationFn: async ({ id, payload }: { id: string; payload: GameRequest }) => {
|
||||
const response = await api.put(`/marketing/games/${id}`, payload)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Game updated successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['games'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Update failed')
|
||||
}
|
||||
})
|
||||
|
||||
const deleteGame = useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const response = await api.delete(`/marketing/games/${id}`)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Game deleted successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['games'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Delete failed')
|
||||
}
|
||||
})
|
||||
|
||||
return { createGame, updateGame, deleteGame }
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { GamePrizeRequest } from '@/types/services/gamePrize'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'react-toastify'
|
||||
import { api } from '../api'
|
||||
|
||||
export const useGamePrizesMutation = () => {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const createGamePrize = useMutation({
|
||||
mutationFn: async (newGamePrize: GamePrizeRequest) => {
|
||||
const response = await api.post('/marketing/game-prizes', newGamePrize)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('GamePrize created successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['gamePrizes'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
|
||||
}
|
||||
})
|
||||
|
||||
const updateGamePrize = useMutation({
|
||||
mutationFn: async ({ id, payload }: { id: string; payload: GamePrizeRequest }) => {
|
||||
const response = await api.put(`/marketing/game-prizes/${id}`, payload)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('GamePrize updated successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['gamePrizes'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Update failed')
|
||||
}
|
||||
})
|
||||
|
||||
const deleteGamePrize = useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const response = await api.delete(`/marketing/game-prizes/${id}`)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('GamePrize deleted successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['gamePrizes'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Delete failed')
|
||||
}
|
||||
})
|
||||
|
||||
return { createGamePrize, updateGamePrize, deleteGamePrize }
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'react-toastify'
|
||||
import { api } from '../api'
|
||||
import { PurchaseOrderRequest } from '@/types/services/purchaseOrder'
|
||||
import { PurchaseOrderRequest, SendPaymentPurchaseOrderRequest } from '@/types/services/purchaseOrder'
|
||||
|
||||
export const usePurchaseOrdersMutation = () => {
|
||||
const queryClient = useQueryClient()
|
||||
@@ -13,12 +13,26 @@ export const usePurchaseOrdersMutation = () => {
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Purchase Order created successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['purchase-orders'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['purchase-orders', 'ingredients'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
|
||||
}
|
||||
})
|
||||
|
||||
return { createPurchaseOrder }
|
||||
const sendPaymentPurchaseOrder = useMutation({
|
||||
mutationFn: async ({ id, payload }: { id: string; payload: SendPaymentPurchaseOrderRequest }) => {
|
||||
const response = await api.put(`/purchase-orders/${id}/status/received`, payload)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Send Payment Order successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['purchase-orders'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Send Payment Order failed')
|
||||
}
|
||||
})
|
||||
|
||||
return { createPurchaseOrder, sendPaymentPurchaseOrder }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { RewardRequest } from '@/types/services/reward'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'react-toastify'
|
||||
import { api } from '../api'
|
||||
|
||||
export const useRewardsMutation = () => {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const createReward = useMutation({
|
||||
mutationFn: async (newReward: RewardRequest) => {
|
||||
const response = await api.post('/marketing/rewards', newReward)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Reward created successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['rewards'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
|
||||
}
|
||||
})
|
||||
|
||||
const updateReward = useMutation({
|
||||
mutationFn: async ({ id, payload }: { id: string; payload: RewardRequest }) => {
|
||||
const response = await api.put(`/marketing/rewards/${id}`, payload)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Reward updated successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['rewards'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Update failed')
|
||||
}
|
||||
})
|
||||
|
||||
const deleteReward = useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const response = await api.delete(`/marketing/rewards/${id}`)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Reward deleted successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['rewards'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Delete failed')
|
||||
}
|
||||
})
|
||||
|
||||
return { createReward, updateReward, deleteReward }
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { TierRequest } from '@/types/services/tier'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'react-toastify'
|
||||
import { api } from '../api'
|
||||
|
||||
export const useTiersMutation = () => {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const createTier = useMutation({
|
||||
mutationFn: async (newTier: TierRequest) => {
|
||||
const response = await api.post('/marketing/tiers', newTier)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Tier created successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['tiers'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
|
||||
}
|
||||
})
|
||||
|
||||
const updateTier = useMutation({
|
||||
mutationFn: async ({ id, payload }: { id: string; payload: TierRequest }) => {
|
||||
const response = await api.put(`/marketing/tiers/${id}`, payload)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Tier updated successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['tiers'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Update failed')
|
||||
}
|
||||
})
|
||||
|
||||
const deleteTier = useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const response = await api.delete(`/marketing/tiers/${id}`)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Tier deleted successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['tiers'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Delete failed')
|
||||
}
|
||||
})
|
||||
|
||||
return { createTier, updateTier, deleteTier }
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { api } from '../api'
|
||||
import { Campaign, CampaignRule, Campaigns } from '@/types/services/campaign'
|
||||
|
||||
interface CampaignQueryParams {
|
||||
page?: number
|
||||
limit?: number
|
||||
search?: string
|
||||
}
|
||||
|
||||
export function useCampaigns(params: CampaignQueryParams = {}) {
|
||||
const { page = 1, limit = 10, search = '', ...filters } = params
|
||||
|
||||
return useQuery<Campaigns>({
|
||||
queryKey: ['campaigns', { page, limit, search, ...filters }],
|
||||
queryFn: async () => {
|
||||
const queryParams = new URLSearchParams()
|
||||
|
||||
queryParams.append('page', page.toString())
|
||||
queryParams.append('limit', limit.toString())
|
||||
|
||||
if (search) {
|
||||
queryParams.append('search', search)
|
||||
}
|
||||
|
||||
Object.entries(filters).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== null && value !== '') {
|
||||
queryParams.append(key, value.toString())
|
||||
}
|
||||
})
|
||||
|
||||
const res = await api.get(`/marketing/campaigns?${queryParams.toString()}`)
|
||||
return res.data.data
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function useCampaignById(id: string) {
|
||||
return useQuery<Campaign>({
|
||||
queryKey: ['campaigns', id],
|
||||
queryFn: async () => {
|
||||
const res = await api.get(`/marketing/campaigns/${id}`)
|
||||
return res.data.data
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function useCampaignRulesByCampaignId(id: string) {
|
||||
return useQuery<CampaignRule[]>({
|
||||
queryKey: ['campaign-rules/campaign', id],
|
||||
queryFn: async () => {
|
||||
const res = await api.get(`/marketing/campaign-rules/campaign/${id}`)
|
||||
return res.data.data
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -9,7 +9,7 @@ interface CategoriesQueryParams {
|
||||
}
|
||||
|
||||
export function useCategories(params: CategoriesQueryParams = {}) {
|
||||
const { page = 1, limit = 10, search = '', ...filters } = params
|
||||
const { page = 1, limit = 50, search = '', ...filters } = params
|
||||
|
||||
return useQuery<Categories>({
|
||||
queryKey: ['categories', { page, limit, search, ...filters }],
|
||||
@@ -30,7 +30,9 @@ export function useCategories(params: CategoriesQueryParams = {}) {
|
||||
})
|
||||
|
||||
const res = await api.get(`/categories?${queryParams.toString()}`)
|
||||
return res.data.data
|
||||
const data = res.data.data
|
||||
|
||||
return data
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { api } from '../api'
|
||||
import { Game, Games } from '@/types/services/game'
|
||||
|
||||
interface GameQueryParams {
|
||||
page?: number
|
||||
limit?: number
|
||||
search?: string
|
||||
}
|
||||
|
||||
export function useGames(params: GameQueryParams = {}) {
|
||||
const { page = 1, limit = 10, search = '', ...filters } = params
|
||||
|
||||
return useQuery<Games>({
|
||||
queryKey: ['games', { page, limit, search, ...filters }],
|
||||
queryFn: async () => {
|
||||
const queryParams = new URLSearchParams()
|
||||
|
||||
queryParams.append('page', page.toString())
|
||||
queryParams.append('limit', limit.toString())
|
||||
|
||||
if (search) {
|
||||
queryParams.append('search', search)
|
||||
}
|
||||
|
||||
Object.entries(filters).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== null && value !== '') {
|
||||
queryParams.append(key, value.toString())
|
||||
}
|
||||
})
|
||||
|
||||
const res = await api.get(`/marketing/games?${queryParams.toString()}`)
|
||||
return res.data.data
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function useGameById(id: string) {
|
||||
return useQuery<Game>({
|
||||
queryKey: ['games', id],
|
||||
queryFn: async () => {
|
||||
const res = await api.get(`/marketing/games/${id}`)
|
||||
return res.data.data
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { api } from '../api'
|
||||
import { GamePrize, GamePrizes } from '@/types/services/gamePrize'
|
||||
|
||||
interface GamePrizeQueryParams {
|
||||
page?: number
|
||||
limit?: number
|
||||
search?: string
|
||||
}
|
||||
|
||||
export function useGamePrizes(params: GamePrizeQueryParams = {}) {
|
||||
const { page = 1, limit = 10, search = '', ...filters } = params
|
||||
|
||||
return useQuery<GamePrizes>({
|
||||
queryKey: ['gamePrizes', { page, limit, search, ...filters }],
|
||||
queryFn: async () => {
|
||||
const queryParams = new URLSearchParams()
|
||||
|
||||
queryParams.append('page', page.toString())
|
||||
queryParams.append('limit', limit.toString())
|
||||
|
||||
if (search) {
|
||||
queryParams.append('search', search)
|
||||
}
|
||||
|
||||
Object.entries(filters).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== null && value !== '') {
|
||||
queryParams.append(key, value.toString())
|
||||
}
|
||||
})
|
||||
|
||||
const res = await api.get(`/marketing/game-prizes?${queryParams.toString()}`)
|
||||
return res.data.data
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function useGamePrizeById(id: string) {
|
||||
return useQuery<GamePrize>({
|
||||
queryKey: ['gamePrizes', id],
|
||||
queryFn: async () => {
|
||||
const res = await api.get(`/marketing/game-prizes/${id}`)
|
||||
return res.data.data
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -6,6 +6,8 @@ interface OrdersQueryParams {
|
||||
page?: number
|
||||
limit?: number
|
||||
search?: string
|
||||
date_from?: string
|
||||
date_to?: string
|
||||
}
|
||||
|
||||
export function useOrders(params: OrdersQueryParams = {}) {
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { api } from '../api'
|
||||
import { Reward, Rewards } from '@/types/services/reward'
|
||||
|
||||
interface RewardQueryParams {
|
||||
page?: number
|
||||
limit?: number
|
||||
search?: string
|
||||
}
|
||||
|
||||
export function useRewards(params: RewardQueryParams = {}) {
|
||||
const { page = 1, limit = 10, search = '', ...filters } = params
|
||||
|
||||
return useQuery<Rewards>({
|
||||
queryKey: ['rewards', { page, limit, search, ...filters }],
|
||||
queryFn: async () => {
|
||||
const queryParams = new URLSearchParams()
|
||||
|
||||
queryParams.append('page', page.toString())
|
||||
queryParams.append('limit', limit.toString())
|
||||
|
||||
if (search) {
|
||||
queryParams.append('search', search)
|
||||
}
|
||||
|
||||
Object.entries(filters).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== null && value !== '') {
|
||||
queryParams.append(key, value.toString())
|
||||
}
|
||||
})
|
||||
|
||||
const res = await api.get(`/marketing/rewards?${queryParams.toString()}`)
|
||||
return res.data.data
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function useRewardById(id: string) {
|
||||
return useQuery<Reward>({
|
||||
queryKey: ['rewards', id],
|
||||
queryFn: async () => {
|
||||
const res = await api.get(`/marketing/rewards/${id}`)
|
||||
return res.data.data
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { api } from '../api'
|
||||
import { Tier, Tiers } from '@/types/services/tier'
|
||||
|
||||
interface TierQueryParams {
|
||||
page?: number
|
||||
limit?: number
|
||||
search?: string
|
||||
}
|
||||
|
||||
export function useTiers(params: TierQueryParams = {}) {
|
||||
const { page = 1, limit = 10, search = '', ...filters } = params
|
||||
|
||||
return useQuery<Tiers>({
|
||||
queryKey: ['tiers', { page, limit, search, ...filters }],
|
||||
queryFn: async () => {
|
||||
const queryParams = new URLSearchParams()
|
||||
|
||||
queryParams.append('page', page.toString())
|
||||
queryParams.append('limit', limit.toString())
|
||||
|
||||
if (search) {
|
||||
queryParams.append('search', search)
|
||||
}
|
||||
|
||||
Object.entries(filters).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== null && value !== '') {
|
||||
queryParams.append(key, value.toString())
|
||||
}
|
||||
})
|
||||
|
||||
const res = await api.get(`/marketing/tiers?${queryParams.toString()}`)
|
||||
return res.data.data
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function useTierById(id: string) {
|
||||
return useQuery<Tier>({
|
||||
queryKey: ['tiers', id],
|
||||
queryFn: async () => {
|
||||
const res = await api.get(`/marketing/tiers/${id}`)
|
||||
return res.data.data
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { VoucherRowsResponse } from '../../types/services/voucher'
|
||||
import { api } from '../api'
|
||||
|
||||
export interface VouchersQueryParams {
|
||||
rows?: number
|
||||
winner_number?: number
|
||||
}
|
||||
|
||||
export function useVoucherRows(params: VouchersQueryParams = {}, options: { enabled?: boolean } = {}) {
|
||||
const { rows = 5, winner_number = 1 } = params
|
||||
const { enabled = true } = options
|
||||
|
||||
return useQuery<VoucherRowsResponse>({
|
||||
queryKey: ['voucher-rows', { rows, winner_number }],
|
||||
queryFn: async () => {
|
||||
const res = await api.get(`/vouchers/rows`, {
|
||||
params: { rows, winner_number }
|
||||
})
|
||||
return res.data.data
|
||||
},
|
||||
enabled,
|
||||
staleTime: 5 * 60 * 1000,
|
||||
refetchOnWindowFocus: false
|
||||
})
|
||||
}
|
||||
|
||||
// Manual fetch function for cases where you need to fetch without using the hook
|
||||
export async function fetchVoucherRows(rows: number = 5, winner_number: number = 1): Promise<VoucherRowsResponse> {
|
||||
const res = await api.get(`/vouchers/rows`, {
|
||||
params: { rows, winner_number }
|
||||
})
|
||||
return res.data.data
|
||||
}
|
||||
@@ -31,8 +31,10 @@ export interface SalesReport {
|
||||
export interface ProductData {
|
||||
product_id: string
|
||||
product_name: string
|
||||
product_sku: string
|
||||
category_id: string
|
||||
category_name: string
|
||||
category_order: number
|
||||
quantity_sold: number
|
||||
revenue: number
|
||||
average_price: number
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
export type CampaignType = 'REWARD' | 'POINTS' | 'TOKENS' | 'MIXED'
|
||||
|
||||
export type RuleType = 'TIER' | 'SPEND' | 'PRODUCT' | 'CATEGORY' | 'DAY' | 'LOCATION'
|
||||
|
||||
export type RewardType = 'POINTS' | 'TOKENS' | 'REWARD'
|
||||
|
||||
export interface Campaign {
|
||||
id: string // UUID
|
||||
name: string
|
||||
description?: string
|
||||
type: CampaignType
|
||||
start_date: string // ISO string
|
||||
end_date: string // ISO string
|
||||
is_active: boolean
|
||||
show_on_app: boolean
|
||||
position: number
|
||||
metadata?: {
|
||||
banner_url?: string
|
||||
}
|
||||
created_at: string // ISO string
|
||||
updated_at: string // ISO string
|
||||
}
|
||||
|
||||
export interface CampaignRule {
|
||||
id: string // UUID
|
||||
campaign_id: string // UUID
|
||||
rule_type: RuleType
|
||||
condition_value?: string
|
||||
reward_type: RewardType
|
||||
reward_value?: number
|
||||
reward_subtype?: string
|
||||
reward_ref_id?: string // UUID
|
||||
metadata?: Record<string, any>
|
||||
created_at: string // ISO string
|
||||
updated_at: string // ISO string
|
||||
}
|
||||
|
||||
export interface CampaignRequest {
|
||||
name: string
|
||||
description?: string
|
||||
type: CampaignType
|
||||
start_date: string // ISO string
|
||||
end_date: string // ISO string
|
||||
is_active: boolean
|
||||
show_on_app: boolean
|
||||
position: number
|
||||
metadata?: {
|
||||
banner_url?: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface CampaignRuleRequest {
|
||||
campaign_id: string
|
||||
rule_type: 'TIER' | 'SPEND' | 'PRODUCT' | 'CATEGORY' | 'DAY' | 'LOCATION'
|
||||
condition_value?: string
|
||||
reward_type: 'POINTS' | 'TOKENS' | 'REWARD'
|
||||
reward_value?: number
|
||||
reward_subtype?: string
|
||||
reward_ref_id?: string
|
||||
}
|
||||
|
||||
export interface Campaigns {
|
||||
campaigns: Campaign[]
|
||||
total: number
|
||||
page: number
|
||||
limit: number
|
||||
}
|
||||
@@ -1,25 +1,26 @@
|
||||
export interface Category {
|
||||
id: string;
|
||||
organization_id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
business_type: string;
|
||||
metadata: Record<string, any>;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
id: string
|
||||
organization_id: string
|
||||
name: string
|
||||
description: string | null
|
||||
business_type: string
|
||||
order: number
|
||||
metadata: Record<string, any>
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface Categories {
|
||||
categories: Category[];
|
||||
total_count: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
total_pages: number;
|
||||
categories: Category[]
|
||||
total_count: number
|
||||
page: number
|
||||
limit: number
|
||||
total_pages: number
|
||||
}
|
||||
|
||||
|
||||
export interface CategoryRequest {
|
||||
name: string;
|
||||
description: string | null;
|
||||
business_type: string;
|
||||
name: string
|
||||
description: string | null
|
||||
business_type: string
|
||||
order: number
|
||||
}
|
||||
|
||||
@@ -1,29 +1,40 @@
|
||||
export interface Customer {
|
||||
id: string;
|
||||
organization_id: string;
|
||||
name: string;
|
||||
email?: string;
|
||||
phone?: string;
|
||||
address?: string;
|
||||
is_default: boolean;
|
||||
is_active: boolean;
|
||||
metadata: Record<string, any>;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
id: string
|
||||
organization_id: string
|
||||
name: string
|
||||
email?: string
|
||||
phone?: string
|
||||
address?: string
|
||||
is_default: boolean
|
||||
is_active: boolean
|
||||
metadata: Record<string, any>
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface Customers {
|
||||
data: Customer[];
|
||||
total_count: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
total_pages: number;
|
||||
data: Customer[]
|
||||
total_count: number
|
||||
page: number
|
||||
limit: number
|
||||
total_pages: number
|
||||
}
|
||||
|
||||
export interface CustomerRequest {
|
||||
name: string;
|
||||
email?: string;
|
||||
phone?: string;
|
||||
address?: string;
|
||||
is_active?: boolean;
|
||||
name: string
|
||||
email?: string
|
||||
phone?: string
|
||||
address?: string
|
||||
is_active?: boolean
|
||||
}
|
||||
|
||||
export interface CustomerAnalytics {
|
||||
id: string
|
||||
name: string
|
||||
email?: string
|
||||
phone?: string
|
||||
totalPoints: number
|
||||
totalSpent?: number
|
||||
loyaltyTier?: string // Bronze, Silver, Gold, dst
|
||||
lastTransactionDate?: Date
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
export interface Game {
|
||||
id: string // uuid
|
||||
name: string
|
||||
type: string
|
||||
is_active: boolean
|
||||
metadata: Record<string, any>
|
||||
created_at: string // ISO datetime
|
||||
updated_at: string // ISO datetime
|
||||
}
|
||||
|
||||
export interface Games {
|
||||
data: Game[]
|
||||
total_count: number
|
||||
page: number
|
||||
limit: number
|
||||
total_pages: number
|
||||
}
|
||||
|
||||
export interface GameRequest {
|
||||
name: string
|
||||
type: string
|
||||
is_active: boolean
|
||||
metadata: {
|
||||
imageUrl?: string
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Game } from './game'
|
||||
|
||||
export interface GamePrize {
|
||||
id: string // uuid
|
||||
game_id: string // uuid
|
||||
name: string
|
||||
weight: number
|
||||
stock: number
|
||||
max_stock?: number
|
||||
threshold?: number // int64 → number
|
||||
fallback_prize_id?: string // uuid
|
||||
metadata: Record<string, any>
|
||||
game?: Game // relasi ke GameResponse
|
||||
fallback_prize?: GamePrize // self reference
|
||||
created_at: string // ISO datetime
|
||||
updated_at: string // ISO datetime
|
||||
}
|
||||
|
||||
export interface GamePrizes {
|
||||
data: GamePrize[]
|
||||
total_count: number
|
||||
page: number
|
||||
limit: number
|
||||
total_pages: number
|
||||
}
|
||||
|
||||
export interface GamePrizeRequest {
|
||||
game_id: string // uuid
|
||||
name: string
|
||||
weight: number // min 1
|
||||
stock: number // min 0
|
||||
max_stock?: number // optional
|
||||
threshold?: number // optional (int64 → number in TS)
|
||||
fallback_prize_id?: string // optional uuid
|
||||
}
|
||||
|
||||
export interface GamePrizeRequest {
|
||||
game_id: string // uuid
|
||||
name: string
|
||||
weight: number // min 1
|
||||
stock: number // min 0
|
||||
max_stock?: number // optional
|
||||
threshold?: number // optional (int64 → number in TS)
|
||||
fallback_prize_id?: string // optional uuid
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export interface LoyaltyType {
|
||||
id: string
|
||||
name: string
|
||||
minimumPurchase: number
|
||||
pointMultiplier: number
|
||||
benefits: string[]
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}
|
||||
@@ -118,3 +118,9 @@ export interface PurchaseOrderFormItem {
|
||||
amount: number
|
||||
total: number // calculated field for UI
|
||||
}
|
||||
|
||||
export interface SendPaymentPurchaseOrderRequest {
|
||||
reference?: string
|
||||
status?: 'received'
|
||||
attachment_file_ids?: string[] // uuid.UUID[]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
export interface Reward {
|
||||
id: string // uuid
|
||||
name: string
|
||||
reward_type: 'VOUCHER' | 'PHYSICAL' | 'DIGITAL'
|
||||
cost_points: number
|
||||
stock?: number
|
||||
max_per_customer: number
|
||||
tnc?: TermsAndConditions
|
||||
metadata?: Record<string, any>
|
||||
images?: string[]
|
||||
created_at: string // ISO date-time
|
||||
updated_at: string // ISO date-time
|
||||
}
|
||||
|
||||
export interface Rewards {
|
||||
rewards: Reward[]
|
||||
total: number
|
||||
page: number
|
||||
limit: number
|
||||
}
|
||||
|
||||
export interface TermsAndConditions {
|
||||
sections: TncSection[]
|
||||
expiry_days: number
|
||||
}
|
||||
|
||||
export interface TncSection {
|
||||
title: string
|
||||
rules: string[]
|
||||
}
|
||||
|
||||
export interface RewardRequest {
|
||||
name: string // required, 1–150 chars
|
||||
reward_type: 'VOUCHER' | 'PHYSICAL' | 'DIGITAL' // enum
|
||||
cost_points: number // min 1
|
||||
stock?: number
|
||||
max_per_customer: number // min 1
|
||||
tnc?: TermsAndConditions
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
export interface Tier {
|
||||
id: string // uuid
|
||||
name: string
|
||||
min_points: number
|
||||
benefits: Record<string, any>
|
||||
created_at: string // ISO datetime
|
||||
updated_at: string // ISO datetime
|
||||
}
|
||||
|
||||
export interface Tiers {
|
||||
data: Tier[]
|
||||
total_count: number
|
||||
page: number
|
||||
limit: number
|
||||
total_pages: number
|
||||
}
|
||||
|
||||
export interface TierRequest {
|
||||
name: string
|
||||
min_points: number
|
||||
benefits: Record<string, any>
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
export interface Voucher {
|
||||
voucher_code: string
|
||||
name: string
|
||||
phone_number: string
|
||||
is_winner: boolean
|
||||
}
|
||||
|
||||
export interface VoucherRow {
|
||||
row_number: number
|
||||
vouchers: Voucher[]
|
||||
}
|
||||
|
||||
export interface VoucherRowsResponse {
|
||||
rows: VoucherRow[]
|
||||
total_rows: number
|
||||
total_vouchers: number
|
||||
}
|
||||
|
||||
export interface VoucherApiResponse {
|
||||
success: boolean
|
||||
data: VoucherRowsResponse
|
||||
errors: any
|
||||
}
|
||||
|
||||
export interface VoucherType {
|
||||
id: number
|
||||
code: string
|
||||
type: 'discount' | 'cashback' | 'free_shipping' | 'product'
|
||||
discountType?: 'fixed' | 'percent'
|
||||
discountValue?: number
|
||||
minPurchase?: number
|
||||
validFrom: string
|
||||
validUntil: string
|
||||
isActive: boolean
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export interface WheelSpinType {
|
||||
id: string
|
||||
name: string
|
||||
weight: number
|
||||
omset: number
|
||||
fallback: boolean
|
||||
stock?: number
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}
|
||||
@@ -0,0 +1,527 @@
|
||||
// excelGenerator.ts
|
||||
import { formatCurrency, formatDateDDMMYYYY } from '@/utils/transform'
|
||||
import type ExcelJS from 'exceljs'
|
||||
|
||||
interface ExcelGeneratorParams {
|
||||
outlet: any
|
||||
profitLoss: any
|
||||
products: any
|
||||
paymentAnalytics: any
|
||||
category: any
|
||||
productSummary: {
|
||||
totalQuantitySold: number
|
||||
totalRevenue: number
|
||||
totalOrders: number
|
||||
}
|
||||
categorySummary: {
|
||||
totalRevenue: number
|
||||
orderCount: number
|
||||
productCount: number
|
||||
totalQuantity: number
|
||||
}
|
||||
filterType: 'single' | 'range'
|
||||
selectedDate: Date
|
||||
dateRange: { startDate: Date; endDate: Date }
|
||||
}
|
||||
|
||||
const formatDateForInput = (date: Date) => {
|
||||
return date.toISOString().split('T')[0]
|
||||
}
|
||||
|
||||
const getReportPeriodText = (params: ExcelGeneratorParams) => {
|
||||
if (params.filterType === 'single') {
|
||||
return `${formatDateDDMMYYYY(params.selectedDate)} - ${formatDateDDMMYYYY(params.selectedDate)}`
|
||||
}
|
||||
return `${formatDateDDMMYYYY(params.dateRange.startDate)} - ${formatDateDDMMYYYY(params.dateRange.endDate)}`
|
||||
}
|
||||
|
||||
// ========== EXCEL STYLES ==========
|
||||
const headerStyle: Partial<ExcelJS.Style> = {
|
||||
font: { bold: true, size: 12, color: { argb: 'FFFFFFFF' } },
|
||||
fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF36175E' } } as ExcelJS.FillPattern,
|
||||
alignment: { vertical: 'middle', horizontal: 'center' },
|
||||
border: {
|
||||
top: { style: 'thin', color: { argb: 'FFD1D5DB' } },
|
||||
left: { style: 'thin', color: { argb: 'FFD1D5DB' } },
|
||||
bottom: { style: 'thin', color: { argb: 'FFD1D5DB' } },
|
||||
right: { style: 'thin', color: { argb: 'FFD1D5DB' } }
|
||||
}
|
||||
}
|
||||
|
||||
const titleStyle: Partial<ExcelJS.Style> = {
|
||||
font: { bold: true, size: 18 },
|
||||
alignment: { vertical: 'middle', horizontal: 'left' }
|
||||
}
|
||||
|
||||
const subtitleStyle: Partial<ExcelJS.Style> = {
|
||||
font: { size: 11, color: { argb: 'FF6B7280' } },
|
||||
alignment: { vertical: 'middle', horizontal: 'left' }
|
||||
}
|
||||
|
||||
const labelStyle: Partial<ExcelJS.Style> = {
|
||||
font: { bold: true, size: 11 },
|
||||
alignment: { vertical: 'middle', horizontal: 'left' }
|
||||
}
|
||||
|
||||
const totalRowStyle: Partial<ExcelJS.Style> = {
|
||||
font: { bold: true, size: 11 },
|
||||
fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFF3F4F6' } } as ExcelJS.FillPattern,
|
||||
border: {
|
||||
top: { style: 'thin', color: { argb: 'FFD1D5DB' } },
|
||||
left: { style: 'thin', color: { argb: 'FFD1D5DB' } },
|
||||
bottom: { style: 'thin', color: { argb: 'FFD1D5DB' } },
|
||||
right: { style: 'thin', color: { argb: 'FFD1D5DB' } }
|
||||
}
|
||||
}
|
||||
|
||||
const dataStyle: Partial<ExcelJS.Style> = {
|
||||
border: {
|
||||
top: { style: 'thin', color: { argb: 'FFF3F4F6' } },
|
||||
left: { style: 'thin', color: { argb: 'FFF3F4F6' } },
|
||||
bottom: { style: 'thin', color: { argb: 'FFF3F4F6' } },
|
||||
right: { style: 'thin', color: { argb: 'FFF3F4F6' } }
|
||||
}
|
||||
}
|
||||
|
||||
const dataStyleAlt: Partial<ExcelJS.Style> = {
|
||||
...dataStyle,
|
||||
fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFFAFAFA' } } as ExcelJS.FillPattern
|
||||
}
|
||||
|
||||
const currencyFormat = '#,##0'
|
||||
const percentageFormat = '0.0"%"'
|
||||
|
||||
// ========== HELPER: STATUS STYLE ==========
|
||||
// Sehat → teks hijau gelap, background hijau muda
|
||||
// Tidak Sehat → teks merah gelap, background merah muda
|
||||
const getStatusStyle = (status: 'Sehat' | 'Tidak Sehat', isAlt: boolean): Partial<ExcelJS.Style> => {
|
||||
const baseStyle = isAlt ? dataStyleAlt : dataStyle
|
||||
if (status === 'Sehat') {
|
||||
return {
|
||||
...baseStyle,
|
||||
font: { bold: true, size: 11, color: { argb: 'FF166534' } }, // green-800
|
||||
fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFDCFCE7' } } as ExcelJS.FillPattern, // green-100
|
||||
alignment: { horizontal: 'center', vertical: 'middle' },
|
||||
border: dataStyle.border
|
||||
}
|
||||
}
|
||||
return {
|
||||
...baseStyle,
|
||||
font: { bold: true, size: 11, color: { argb: 'FF991B1B' } }, // red-800
|
||||
fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFFEE2E2' } } as ExcelJS.FillPattern, // red-100
|
||||
alignment: { horizontal: 'center', vertical: 'middle' },
|
||||
border: dataStyle.border
|
||||
}
|
||||
}
|
||||
|
||||
// Dummy HPP values — ganti dengan data real nantinya
|
||||
const DUMMY_STD_HPP = 30 // 30% — ganti dengan data real nantinya
|
||||
const DUMMY_REAL_HPP = 0 // 0% — ganti dengan kalkulasi real nantinya
|
||||
const getDummyStatus = (stdHpp: number, realHpp: number): 'Sehat' | 'Tidak Sehat' =>
|
||||
realHpp <= stdHpp ? 'Sehat' : 'Tidak Sehat'
|
||||
|
||||
export const generateExcel = async (params: ExcelGeneratorParams) => {
|
||||
const {
|
||||
outlet,
|
||||
profitLoss,
|
||||
products,
|
||||
paymentAnalytics,
|
||||
category,
|
||||
productSummary,
|
||||
categorySummary,
|
||||
filterType,
|
||||
selectedDate,
|
||||
dateRange
|
||||
} = params
|
||||
|
||||
const ExcelJS = await import('exceljs')
|
||||
const workbook = new ExcelJS.Workbook()
|
||||
|
||||
workbook.creator = outlet?.name || 'POS System'
|
||||
workbook.created = new Date()
|
||||
|
||||
// ============ SHEET 1: RINGKASAN ============
|
||||
const ws1 = workbook.addWorksheet('Ringkasan', {
|
||||
views: [{ showGridLines: false }]
|
||||
})
|
||||
|
||||
ws1.mergeCells('A1:B1')
|
||||
const titleCell = ws1.getCell('A1')
|
||||
titleCell.value = 'LAPORAN TRANSAKSI'
|
||||
titleCell.style = {
|
||||
font: { bold: true, size: 20, color: { argb: 'FF1F2937' } },
|
||||
alignment: { vertical: 'middle', horizontal: 'left' }
|
||||
}
|
||||
ws1.getRow(1).height = 30
|
||||
|
||||
ws1.getCell('A2').value = outlet?.name || ''
|
||||
ws1.getCell('A2').style = { ...subtitleStyle, font: { size: 12, color: { argb: 'FF4B5563' } } }
|
||||
ws1.getCell('A3').value = outlet?.address || ''
|
||||
ws1.getCell('A3').style = subtitleStyle
|
||||
ws1.getCell('A4').value = outlet?.phone || ''
|
||||
ws1.getCell('A4').style = subtitleStyle
|
||||
|
||||
ws1.getCell('A5').value = 'Periode:'
|
||||
ws1.getCell('B5').value = getReportPeriodText(params)
|
||||
ws1.getCell('A5').style = labelStyle
|
||||
ws1.getCell('B5').style = { font: { size: 11 } }
|
||||
|
||||
ws1.getCell('A7').value = 'RINGKASAN'
|
||||
ws1.getCell('A7').style = {
|
||||
font: { bold: true, size: 14, color: { argb: 'FF36175E' } },
|
||||
alignment: { vertical: 'middle', horizontal: 'left' }
|
||||
}
|
||||
|
||||
ws1.getCell('A8').value = 'Keterangan'
|
||||
ws1.getCell('B8').value = 'Jumlah (IDR)'
|
||||
ws1.getCell('A8').style = headerStyle
|
||||
ws1.getCell('B8').style = headerStyle
|
||||
ws1.getRow(8).height = 25
|
||||
|
||||
const summaryData = [
|
||||
['Total Penjualan', profitLoss?.summary.total_revenue || 0],
|
||||
['Total Diskon', profitLoss?.summary.total_discount || 0],
|
||||
['Total Pajak', profitLoss?.summary.total_tax || 0],
|
||||
['PB1', 0],
|
||||
['Service Charge', profitLoss?.summary.service_charge || 0]
|
||||
]
|
||||
|
||||
summaryData.forEach((row, idx) => {
|
||||
const rowNum = idx + 9
|
||||
ws1.getCell(`A${rowNum}`).value = row[0]
|
||||
ws1.getCell(`B${rowNum}`).value = row[1]
|
||||
const isAlt = idx % 2 === 1
|
||||
const baseStyle = isAlt ? dataStyleAlt : dataStyle
|
||||
ws1.getCell(`A${rowNum}`).style = { ...baseStyle, alignment: { horizontal: 'left' } }
|
||||
ws1.getCell(`B${rowNum}`).style = { ...baseStyle, alignment: { horizontal: 'right' }, numFmt: currencyFormat }
|
||||
ws1.getRow(rowNum).height = 22
|
||||
})
|
||||
|
||||
const totalRow = 9 + summaryData.length
|
||||
ws1.getCell(`A${totalRow}`).value = 'Total'
|
||||
ws1.getCell(`B${totalRow}`).value = profitLoss?.summary.total_revenue || 0
|
||||
ws1.getCell(`A${totalRow}`).style = { ...totalRowStyle, alignment: { horizontal: 'left' } }
|
||||
ws1.getCell(`B${totalRow}`).style = { ...totalRowStyle, alignment: { horizontal: 'right' }, numFmt: currencyFormat }
|
||||
ws1.getRow(totalRow).height = 25
|
||||
|
||||
const invoiceRow = totalRow + 2
|
||||
ws1.getCell(`A${invoiceRow}`).value = 'INVOICE'
|
||||
ws1.getCell(`A${invoiceRow}`).style = {
|
||||
font: { bold: true, size: 14, color: { argb: 'FF36175E' } },
|
||||
alignment: { vertical: 'middle', horizontal: 'left' }
|
||||
}
|
||||
|
||||
ws1.getCell(`A${invoiceRow + 1}`).value = 'Total Invoice'
|
||||
ws1.getCell(`B${invoiceRow + 1}`).value = profitLoss?.summary.total_orders || 0
|
||||
ws1.getCell(`A${invoiceRow + 1}`).style = { ...dataStyle, font: { bold: true } }
|
||||
ws1.getCell(`B${invoiceRow + 1}`).style = { ...dataStyle, alignment: { horizontal: 'right' }, font: { bold: true } }
|
||||
|
||||
ws1.getColumn(1).width = 28
|
||||
ws1.getColumn(2).width = 22
|
||||
|
||||
// ============ SHEET 2: METODE PEMBAYARAN ============
|
||||
const ws2 = workbook.addWorksheet('Metode Pembayaran', {
|
||||
views: [{ showGridLines: false }]
|
||||
})
|
||||
|
||||
ws2.mergeCells('A1:D1')
|
||||
const paymentTitle = ws2.getCell('A1')
|
||||
paymentTitle.value = 'RINGKASAN METODE PEMBAYARAN'
|
||||
paymentTitle.style = titleStyle
|
||||
ws2.getRow(1).height = 30
|
||||
|
||||
const paymentHeaders = ['Metode', 'Jumlah Order', 'Total Amount (IDR)', 'Persentase']
|
||||
paymentHeaders.forEach((header, idx) => {
|
||||
const cell = ws2.getCell(3, idx + 1)
|
||||
cell.value = header
|
||||
cell.style = headerStyle
|
||||
})
|
||||
ws2.getRow(3).height = 25
|
||||
|
||||
let paymentRow = 4
|
||||
paymentAnalytics?.data?.forEach((payment: any, idx: number) => {
|
||||
const isAlt = idx % 2 === 1
|
||||
const baseStyle = isAlt ? dataStyleAlt : dataStyle
|
||||
|
||||
ws2.getCell(paymentRow, 1).value = payment.payment_method_name
|
||||
ws2.getCell(paymentRow, 2).value = payment.order_count
|
||||
ws2.getCell(paymentRow, 3).value = payment.total_amount
|
||||
ws2.getCell(paymentRow, 4).value = (payment.percentage || 0) / 100
|
||||
|
||||
ws2.getCell(paymentRow, 1).style = { ...baseStyle, alignment: { horizontal: 'left' } }
|
||||
ws2.getCell(paymentRow, 2).style = { ...baseStyle, alignment: { horizontal: 'center' } }
|
||||
ws2.getCell(paymentRow, 3).style = { ...baseStyle, alignment: { horizontal: 'right' }, numFmt: currencyFormat }
|
||||
ws2.getCell(paymentRow, 4).style = { ...baseStyle, alignment: { horizontal: 'center' }, numFmt: percentageFormat }
|
||||
|
||||
ws2.getRow(paymentRow).height = 22
|
||||
paymentRow++
|
||||
})
|
||||
|
||||
ws2.getCell(paymentRow, 1).value = 'TOTAL'
|
||||
ws2.getCell(paymentRow, 2).value = paymentAnalytics?.summary.total_orders || 0
|
||||
ws2.getCell(paymentRow, 3).value = paymentAnalytics?.summary.total_amount || 0
|
||||
ws2.getCell(paymentRow, 4).value = ''
|
||||
ws2.getCell(paymentRow, 1).style = { ...totalRowStyle, alignment: { horizontal: 'left' } }
|
||||
ws2.getCell(paymentRow, 2).style = { ...totalRowStyle, alignment: { horizontal: 'center' } }
|
||||
ws2.getCell(paymentRow, 3).style = { ...totalRowStyle, alignment: { horizontal: 'right' }, numFmt: currencyFormat }
|
||||
ws2.getCell(paymentRow, 4).style = totalRowStyle
|
||||
ws2.getRow(paymentRow).height = 25
|
||||
|
||||
ws2.getColumn(1).width = 28
|
||||
ws2.getColumn(2).width = 16
|
||||
ws2.getColumn(3).width = 22
|
||||
ws2.getColumn(4).width = 16
|
||||
|
||||
// ============ SHEET 3: KATEGORI ============
|
||||
// + 3 kolom baru: % Standard HPP | % Realisasi HPP | Status
|
||||
const ws3 = workbook.addWorksheet('Kategori', {
|
||||
views: [{ showGridLines: false }]
|
||||
})
|
||||
|
||||
ws3.mergeCells('A1:F1')
|
||||
const categoryTitle = ws3.getCell('A1')
|
||||
categoryTitle.value = 'RINGKASAN KATEGORI'
|
||||
categoryTitle.style = titleStyle
|
||||
ws3.getRow(1).height = 30
|
||||
|
||||
const categoryHeaders = ['Nama', 'Qty', 'Pendapatan (IDR)', '% Standard HPP', '% Realisasi HPP', 'Status']
|
||||
categoryHeaders.forEach((header, idx) => {
|
||||
const cell = ws3.getCell(3, idx + 1)
|
||||
cell.value = header
|
||||
cell.style = headerStyle
|
||||
})
|
||||
ws3.getRow(3).height = 25
|
||||
|
||||
let categoryRow = 4
|
||||
category?.data?.forEach((cat: any, idx: number) => {
|
||||
const isAlt = idx % 2 === 1
|
||||
const baseStyle = isAlt ? dataStyleAlt : dataStyle
|
||||
const stdHpp = DUMMY_STD_HPP
|
||||
const realHpp = DUMMY_REAL_HPP
|
||||
const status = getDummyStatus(stdHpp, realHpp)
|
||||
|
||||
ws3.getCell(categoryRow, 1).value = cat.category_name
|
||||
ws3.getCell(categoryRow, 2).value = cat.total_quantity
|
||||
ws3.getCell(categoryRow, 3).value = cat.total_revenue
|
||||
ws3.getCell(categoryRow, 4).value = stdHpp // akan diformat sebagai persentase
|
||||
ws3.getCell(categoryRow, 5).value = realHpp
|
||||
ws3.getCell(categoryRow, 6).value = status
|
||||
|
||||
ws3.getCell(categoryRow, 1).style = { ...baseStyle, alignment: { horizontal: 'left' } }
|
||||
ws3.getCell(categoryRow, 2).style = { ...baseStyle, alignment: { horizontal: 'center' } }
|
||||
ws3.getCell(categoryRow, 3).style = { ...baseStyle, alignment: { horizontal: 'right' }, numFmt: currencyFormat }
|
||||
ws3.getCell(categoryRow, 4).style = { ...baseStyle, alignment: { horizontal: 'center' }, numFmt: '0.0"%"' }
|
||||
ws3.getCell(categoryRow, 5).style = { ...baseStyle, alignment: { horizontal: 'center' }, numFmt: '0.0"%"' }
|
||||
ws3.getCell(categoryRow, 6).style = getStatusStyle(status, isAlt)
|
||||
|
||||
ws3.getRow(categoryRow).height = 22
|
||||
categoryRow++
|
||||
})
|
||||
|
||||
// Total row (3 kolom baru dikosongkan)
|
||||
ws3.getCell(categoryRow, 1).value = 'TOTAL'
|
||||
ws3.getCell(categoryRow, 2).value = categorySummary.totalQuantity
|
||||
ws3.getCell(categoryRow, 3).value = categorySummary.totalRevenue
|
||||
ws3.getCell(categoryRow, 4).value = ''
|
||||
ws3.getCell(categoryRow, 5).value = ''
|
||||
ws3.getCell(categoryRow, 6).value = ''
|
||||
|
||||
ws3.getCell(categoryRow, 1).style = { ...totalRowStyle, alignment: { horizontal: 'left' } }
|
||||
ws3.getCell(categoryRow, 2).style = { ...totalRowStyle, alignment: { horizontal: 'center' } }
|
||||
ws3.getCell(categoryRow, 3).style = { ...totalRowStyle, alignment: { horizontal: 'right' }, numFmt: currencyFormat }
|
||||
ws3.getCell(categoryRow, 4).style = totalRowStyle
|
||||
ws3.getCell(categoryRow, 5).style = totalRowStyle
|
||||
ws3.getCell(categoryRow, 6).style = totalRowStyle
|
||||
ws3.getRow(categoryRow).height = 25
|
||||
|
||||
ws3.getColumn(1).width = 35
|
||||
ws3.getColumn(2).width = 12
|
||||
ws3.getColumn(3).width = 22
|
||||
ws3.getColumn(4).width = 18 // % Standard HPP
|
||||
ws3.getColumn(5).width = 18 // % Realisasi HPP
|
||||
ws3.getColumn(6).width = 16 // Status
|
||||
|
||||
// ============ SHEET 4: DETAIL PRODUK ============
|
||||
// + 3 kolom baru: % Standard HPP | % Realisasi HPP | Status
|
||||
const ws4 = workbook.addWorksheet('Detail Produk', {
|
||||
views: [{ showGridLines: false }]
|
||||
})
|
||||
|
||||
ws4.mergeCells('A1:F1')
|
||||
const productTitle = ws4.getCell('A1')
|
||||
productTitle.value = 'RINGKASAN ITEM PER KATEGORI'
|
||||
productTitle.style = titleStyle
|
||||
ws4.getRow(1).height = 30
|
||||
|
||||
const groupedProducts =
|
||||
products?.data?.reduce(
|
||||
(acc: any, item: any) => {
|
||||
const categoryName = item.category_name || 'Tidak Berkategori'
|
||||
if (!acc[categoryName]) acc[categoryName] = []
|
||||
acc[categoryName].push(item)
|
||||
return acc
|
||||
},
|
||||
{} as Record<string, any[]>
|
||||
) || {}
|
||||
|
||||
let currentRow = 3
|
||||
|
||||
Object.keys(groupedProducts)
|
||||
.sort((a, b) => {
|
||||
const orderA = groupedProducts[a][0]?.category_order ?? 999
|
||||
const orderB = groupedProducts[b][0]?.category_order ?? 999
|
||||
return orderA - orderB
|
||||
})
|
||||
.forEach((categoryName, index) => {
|
||||
// Category header — span 6 kolom
|
||||
ws4.mergeCells(`A${currentRow}:F${currentRow}`)
|
||||
const catHeader = ws4.getCell(`A${currentRow}`)
|
||||
catHeader.value = `${index + 1}. ${categoryName.toUpperCase()}`
|
||||
catHeader.style = {
|
||||
font: { bold: true, size: 13, color: { argb: 'FF36175E' } },
|
||||
fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFF9FAFB' } } as ExcelJS.FillPattern,
|
||||
alignment: { vertical: 'middle', horizontal: 'left' },
|
||||
border: {
|
||||
top: { style: 'thin', color: { argb: 'FFD1D5DB' } },
|
||||
left: { style: 'thin', color: { argb: 'FFD1D5DB' } },
|
||||
bottom: { style: 'thin', color: { argb: 'FFD1D5DB' } },
|
||||
right: { style: 'thin', color: { argb: 'FFD1D5DB' } }
|
||||
}
|
||||
}
|
||||
ws4.getRow(currentRow).height = 28
|
||||
currentRow++
|
||||
|
||||
// Column headers — 6 kolom
|
||||
const prodHeaders = ['Produk', 'Qty', 'Pendapatan (IDR)', '% Standard HPP', '% Realisasi HPP', 'Status']
|
||||
prodHeaders.forEach((header, idx) => {
|
||||
const cell = ws4.getCell(currentRow, idx + 1)
|
||||
cell.value = header
|
||||
cell.style = {
|
||||
font: { bold: true, size: 11, color: { argb: 'FFFFFFFF' } },
|
||||
fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF36175E' } } as ExcelJS.FillPattern,
|
||||
alignment: { vertical: 'middle', horizontal: 'center' },
|
||||
border: {
|
||||
top: { style: 'thin', color: { argb: 'FFD1D5DB' } },
|
||||
left: { style: 'thin', color: { argb: 'FFD1D5DB' } },
|
||||
bottom: { style: 'thin', color: { argb: 'FFD1D5DB' } },
|
||||
right: { style: 'thin', color: { argb: 'FFD1D5DB' } }
|
||||
}
|
||||
}
|
||||
})
|
||||
ws4.getRow(currentRow).height = 24
|
||||
currentRow++
|
||||
|
||||
const categoryProducts = groupedProducts[categoryName].sort((a: any, b: any) =>
|
||||
(a.product_sku || '').localeCompare(b.product_sku || '')
|
||||
)
|
||||
|
||||
categoryProducts.forEach((product: any, idx: number) => {
|
||||
const isAlt = idx % 2 === 1
|
||||
const baseStyle = isAlt ? dataStyleAlt : dataStyle
|
||||
const stdHpp = DUMMY_STD_HPP
|
||||
const realHpp = DUMMY_REAL_HPP
|
||||
const status = getDummyStatus(stdHpp, realHpp)
|
||||
|
||||
ws4.getCell(currentRow, 1).value = product.product_name
|
||||
ws4.getCell(currentRow, 2).value = product.quantity_sold
|
||||
ws4.getCell(currentRow, 3).value = product.revenue
|
||||
ws4.getCell(currentRow, 4).value = stdHpp
|
||||
ws4.getCell(currentRow, 5).value = realHpp
|
||||
ws4.getCell(currentRow, 6).value = status
|
||||
|
||||
ws4.getCell(currentRow, 1).style = { ...baseStyle, alignment: { horizontal: 'left' } }
|
||||
ws4.getCell(currentRow, 2).style = { ...baseStyle, alignment: { horizontal: 'center' } }
|
||||
ws4.getCell(currentRow, 3).style = { ...baseStyle, alignment: { horizontal: 'right' }, numFmt: currencyFormat }
|
||||
ws4.getCell(currentRow, 4).style = { ...baseStyle, alignment: { horizontal: 'center' }, numFmt: '0.0"%"' }
|
||||
ws4.getCell(currentRow, 5).style = { ...baseStyle, alignment: { horizontal: 'center' }, numFmt: '0.0"%"' }
|
||||
ws4.getCell(currentRow, 6).style = getStatusStyle(status, isAlt)
|
||||
|
||||
ws4.getRow(currentRow).height = 20
|
||||
currentRow++
|
||||
})
|
||||
|
||||
// Subtotal — 3 kolom baru dikosongkan
|
||||
const subQty = categoryProducts.reduce((sum: number, p: any) => sum + p.quantity_sold, 0)
|
||||
const subRevenue = categoryProducts.reduce((sum: number, p: any) => sum + p.revenue, 0)
|
||||
|
||||
const subtotalFill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFF3F4F6' } } as ExcelJS.FillPattern
|
||||
ws4.getCell(currentRow, 1).value = `Subtotal ${categoryName}`
|
||||
ws4.getCell(currentRow, 2).value = subQty
|
||||
ws4.getCell(currentRow, 3).value = subRevenue
|
||||
ws4.getCell(currentRow, 4).value = ''
|
||||
ws4.getCell(currentRow, 5).value = ''
|
||||
ws4.getCell(currentRow, 6).value = ''
|
||||
|
||||
ws4.getCell(currentRow, 1).style = { ...totalRowStyle, alignment: { horizontal: 'left' }, fill: subtotalFill }
|
||||
ws4.getCell(currentRow, 2).style = { ...totalRowStyle, alignment: { horizontal: 'center' }, fill: subtotalFill }
|
||||
ws4.getCell(currentRow, 3).style = {
|
||||
...totalRowStyle,
|
||||
alignment: { horizontal: 'right' },
|
||||
numFmt: currencyFormat,
|
||||
fill: subtotalFill
|
||||
}
|
||||
ws4.getCell(currentRow, 4).style = { ...totalRowStyle, fill: subtotalFill }
|
||||
ws4.getCell(currentRow, 5).style = { ...totalRowStyle, fill: subtotalFill }
|
||||
ws4.getCell(currentRow, 6).style = { ...totalRowStyle, fill: subtotalFill }
|
||||
|
||||
ws4.getRow(currentRow).height = 24
|
||||
currentRow += 3
|
||||
})
|
||||
|
||||
// Grand Total
|
||||
const grandFill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF36175E' } } as ExcelJS.FillPattern
|
||||
const grandFont = { bold: true, size: 13, color: { argb: 'FFFFFFFF' } }
|
||||
|
||||
ws4.getCell(currentRow, 1).value = 'TOTAL KESELURUHAN'
|
||||
ws4.getCell(currentRow, 2).value = productSummary.totalQuantitySold
|
||||
ws4.getCell(currentRow, 3).value = productSummary.totalRevenue
|
||||
ws4.getCell(currentRow, 4).value = ''
|
||||
ws4.getCell(currentRow, 5).value = ''
|
||||
ws4.getCell(currentRow, 6).value = ''
|
||||
|
||||
ws4.getCell(currentRow, 1).style = {
|
||||
...totalRowStyle,
|
||||
alignment: { horizontal: 'left' },
|
||||
font: grandFont,
|
||||
fill: grandFill
|
||||
}
|
||||
ws4.getCell(currentRow, 2).style = {
|
||||
...totalRowStyle,
|
||||
alignment: { horizontal: 'center' },
|
||||
font: grandFont,
|
||||
fill: grandFill
|
||||
}
|
||||
ws4.getCell(currentRow, 3).style = {
|
||||
...totalRowStyle,
|
||||
alignment: { horizontal: 'right' },
|
||||
numFmt: currencyFormat,
|
||||
font: grandFont,
|
||||
fill: grandFill
|
||||
}
|
||||
ws4.getCell(currentRow, 4).style = { ...totalRowStyle, font: grandFont, fill: grandFill }
|
||||
ws4.getCell(currentRow, 5).style = { ...totalRowStyle, font: grandFont, fill: grandFill }
|
||||
ws4.getCell(currentRow, 6).style = { ...totalRowStyle, font: grandFont, fill: grandFill }
|
||||
ws4.getRow(currentRow).height = 28
|
||||
|
||||
ws4.getColumn(1).width = 45
|
||||
ws4.getColumn(2).width = 12
|
||||
ws4.getColumn(3).width = 22
|
||||
ws4.getColumn(4).width = 18 // % Standard HPP
|
||||
ws4.getColumn(5).width = 18 // % Realisasi HPP
|
||||
ws4.getColumn(6).width = 16 // Status
|
||||
|
||||
// ============ GENERATE & DOWNLOAD FILE ============
|
||||
const fileName =
|
||||
filterType === 'single'
|
||||
? `laporan-transaksi-${formatDateForInput(selectedDate)}.xlsx`
|
||||
: `laporan-transaksi-${formatDateForInput(dateRange.startDate)}-to-${formatDateForInput(dateRange.endDate)}.xlsx`
|
||||
|
||||
const buffer = await workbook.xlsx.writeBuffer()
|
||||
const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
|
||||
const url = window.URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = fileName
|
||||
a.click()
|
||||
window.URL.revokeObjectURL(url)
|
||||
}
|
||||
@@ -0,0 +1,535 @@
|
||||
// pdfGenerator.ts
|
||||
import { formatCurrency } from '@/utils/transform'
|
||||
|
||||
// PDF Configuration
|
||||
const PDF_FONT_SIZES = {
|
||||
heading: 18,
|
||||
subheading: 16,
|
||||
tableContent: 12,
|
||||
tableHeader: 12,
|
||||
tableFooter: 12,
|
||||
grandTotal: 14,
|
||||
footer: 11
|
||||
}
|
||||
|
||||
const PDF_SPACING = {
|
||||
cellPadding: 5,
|
||||
cellPaddingLarge: 6,
|
||||
sectionGap: 20,
|
||||
headerGap: 15
|
||||
}
|
||||
|
||||
interface PDFGeneratorParams {
|
||||
reportRef: React.RefObject<HTMLDivElement>
|
||||
outlet: any
|
||||
profitLoss: any
|
||||
products: any
|
||||
paymentAnalytics: any
|
||||
category: any
|
||||
productSummary: {
|
||||
totalQuantitySold: number
|
||||
totalRevenue: number
|
||||
totalOrders: number
|
||||
}
|
||||
categorySummary: {
|
||||
totalRevenue: number
|
||||
orderCount: number
|
||||
productCount: number
|
||||
totalQuantity: number
|
||||
}
|
||||
filterType: 'single' | 'range'
|
||||
selectedDate: Date
|
||||
dateRange: { startDate: Date; endDate: Date }
|
||||
now: Date
|
||||
}
|
||||
|
||||
const formatDateForInput = (date: Date) => {
|
||||
return date.toISOString().split('T')[0]
|
||||
}
|
||||
|
||||
// Helper: tentukan warna status
|
||||
const getStatusColor = (status: string): [number, number, number] => {
|
||||
return status === 'Sehat' ? [22, 163, 74] : [220, 38, 38] // green-600 / red-600
|
||||
}
|
||||
|
||||
export const generatePDF = async (params: PDFGeneratorParams) => {
|
||||
const {
|
||||
reportRef,
|
||||
outlet,
|
||||
profitLoss,
|
||||
products,
|
||||
paymentAnalytics,
|
||||
category,
|
||||
productSummary,
|
||||
categorySummary,
|
||||
filterType,
|
||||
selectedDate,
|
||||
dateRange,
|
||||
now
|
||||
} = params
|
||||
|
||||
const reportElement = reportRef.current
|
||||
if (!reportElement) {
|
||||
throw new Error('Report element tidak ditemukan')
|
||||
}
|
||||
|
||||
// Dynamic imports
|
||||
const jsPDF = (await import('jspdf')).default
|
||||
const html2canvas = (await import('html2canvas')).default
|
||||
const autoTable = (await import('jspdf-autotable')).default
|
||||
|
||||
const pdf = new jsPDF({
|
||||
orientation: 'portrait',
|
||||
unit: 'mm',
|
||||
format: 'a4',
|
||||
compress: true
|
||||
})
|
||||
|
||||
// Capture header section
|
||||
const headerElement = reportElement.querySelector('.report-header-section') as HTMLElement
|
||||
if (headerElement) {
|
||||
const headerCanvas = await html2canvas(headerElement, {
|
||||
scale: 2,
|
||||
useCORS: true,
|
||||
backgroundColor: '#ffffff',
|
||||
logging: false,
|
||||
windowWidth: 794
|
||||
})
|
||||
|
||||
const headerImgWidth = 190
|
||||
const headerImgHeight = (headerCanvas.height * headerImgWidth) / headerCanvas.width
|
||||
const headerImgData = headerCanvas.toDataURL('image/jpeg', 0.95)
|
||||
|
||||
pdf.addImage(headerImgData, 'JPEG', 10, 10, headerImgWidth, headerImgHeight)
|
||||
}
|
||||
|
||||
let currentY = 80
|
||||
|
||||
// ========== RINGKASAN SECTION ==========
|
||||
pdf.setFontSize(PDF_FONT_SIZES.heading)
|
||||
pdf.setTextColor(54, 23, 94)
|
||||
pdf.setFont('helvetica', 'bold')
|
||||
pdf.text('Ringkasan', 14, currentY)
|
||||
currentY += 15
|
||||
|
||||
autoTable(pdf, {
|
||||
startY: currentY,
|
||||
head: [],
|
||||
body: [
|
||||
['Total Penjualan', formatCurrency(profitLoss?.summary.total_revenue ?? 0)],
|
||||
['Total Diskon', formatCurrency(profitLoss?.summary.total_discount ?? 0)],
|
||||
['Total Pajak', formatCurrency(profitLoss?.summary.total_tax ?? 0)],
|
||||
['Service Charge', formatCurrency(profitLoss?.summary.service_charge ?? 0)],
|
||||
['Total', formatCurrency(profitLoss?.summary.total_revenue ?? 0)]
|
||||
],
|
||||
theme: 'grid',
|
||||
styles: {
|
||||
fontSize: PDF_FONT_SIZES.subheading,
|
||||
cellPadding: PDF_SPACING.cellPadding,
|
||||
lineColor: [0, 0, 0]
|
||||
},
|
||||
columnStyles: {
|
||||
0: { fontStyle: 'normal', textColor: [60, 60, 60] },
|
||||
1: { halign: 'right', fontStyle: 'bold', textColor: [60, 60, 60] }
|
||||
},
|
||||
margin: { left: 14, right: 14 }
|
||||
})
|
||||
|
||||
currentY = (pdf as any).lastAutoTable.finalY + 20
|
||||
|
||||
// ========== INVOICE SECTION ==========
|
||||
pdf.setFontSize(PDF_FONT_SIZES.heading)
|
||||
pdf.text('Invoice', 14, currentY)
|
||||
currentY += 15
|
||||
|
||||
autoTable(pdf, {
|
||||
startY: currentY,
|
||||
head: [],
|
||||
body: [['Total Invoice', String(profitLoss?.summary.total_orders ?? 0)]],
|
||||
theme: 'grid',
|
||||
styles: {
|
||||
lineColor: [0, 0, 0],
|
||||
fontSize: PDF_FONT_SIZES.subheading,
|
||||
cellPadding: PDF_SPACING.cellPadding
|
||||
},
|
||||
columnStyles: {
|
||||
0: { fontStyle: 'normal', textColor: [60, 60, 60] },
|
||||
1: { halign: 'right', fontStyle: 'bold', textColor: [60, 60, 60] }
|
||||
},
|
||||
margin: { left: 14, right: 14 }
|
||||
})
|
||||
|
||||
pdf.addPage()
|
||||
currentY = 20
|
||||
|
||||
// ========== PAYMENT METHOD SECTION ==========
|
||||
pdf.setFontSize(PDF_FONT_SIZES.heading)
|
||||
pdf.text('Ringkasan Metode Pembayaran', 14, currentY)
|
||||
currentY += 15
|
||||
|
||||
const paymentBody =
|
||||
paymentAnalytics?.data?.map((payment: any) => [
|
||||
payment.payment_method_name,
|
||||
String(payment.order_count),
|
||||
formatCurrency(payment.total_amount),
|
||||
`${(payment.percentage ?? 0).toFixed(1)}%`
|
||||
]) || []
|
||||
|
||||
autoTable(pdf, {
|
||||
startY: currentY,
|
||||
head: [['Metode', 'Jumlah', 'Total', 'Persentase']],
|
||||
body: paymentBody,
|
||||
foot: [
|
||||
[
|
||||
'TOTAL',
|
||||
String(paymentAnalytics?.summary.total_orders ?? 0),
|
||||
formatCurrency(paymentAnalytics?.summary.total_amount ?? 0),
|
||||
''
|
||||
]
|
||||
],
|
||||
theme: 'grid',
|
||||
styles: {
|
||||
fontSize: PDF_FONT_SIZES.tableContent,
|
||||
cellPadding: PDF_SPACING.cellPadding,
|
||||
lineColor: [0, 0, 0],
|
||||
lineWidth: 0.1
|
||||
},
|
||||
headStyles: {
|
||||
fillColor: [54, 23, 94],
|
||||
textColor: 255,
|
||||
fontStyle: 'bold',
|
||||
fontSize: PDF_FONT_SIZES.tableHeader,
|
||||
lineColor: [0, 0, 0],
|
||||
lineWidth: 0.1
|
||||
},
|
||||
footStyles: {
|
||||
fillColor: [220, 220, 220],
|
||||
textColor: [60, 60, 60],
|
||||
fontStyle: 'bold',
|
||||
fontSize: PDF_FONT_SIZES.tableFooter,
|
||||
lineColor: [0, 0, 0],
|
||||
lineWidth: 0.1,
|
||||
halign: 'center'
|
||||
},
|
||||
columnStyles: {
|
||||
1: { halign: 'center' },
|
||||
2: { halign: 'right' },
|
||||
3: { halign: 'right' }
|
||||
},
|
||||
didParseCell: (data: any) => {
|
||||
if (data.section === 'foot') {
|
||||
if (data.column.index === 0) {
|
||||
data.cell.styles.halign = 'left'
|
||||
} else if (data.column.index === 1) {
|
||||
data.cell.styles.halign = 'center'
|
||||
} else if (data.column.index === 2) {
|
||||
data.cell.styles.halign = 'right'
|
||||
}
|
||||
}
|
||||
},
|
||||
margin: { left: 14, right: 14 }
|
||||
})
|
||||
|
||||
currentY = (pdf as any).lastAutoTable.finalY + 20
|
||||
|
||||
// ========== CATEGORY SECTION ==========
|
||||
// Kolom baru: % Standard HPP, % Realisasi HPP, Status — diisi dummy visual untuk saat ini
|
||||
pdf.setFontSize(PDF_FONT_SIZES.heading)
|
||||
pdf.text('Ringkasan Kategori', 14, currentY)
|
||||
currentY += 15
|
||||
|
||||
const DUMMY_STD_HPP = 30 // % (nilai dummy — ganti dengan data real nantinya)
|
||||
|
||||
const categoryBody =
|
||||
category?.data?.map((c: any) => {
|
||||
const stdHpp = DUMMY_STD_HPP
|
||||
const realisasiHpp = 0 // dummy — ganti dengan kalkulasi real
|
||||
const status = realisasiHpp <= stdHpp ? 'Sehat' : 'Tidak Sehat'
|
||||
return [
|
||||
c.category_name,
|
||||
String(c.total_quantity),
|
||||
formatCurrency(c.total_revenue),
|
||||
`${stdHpp}%`,
|
||||
`${realisasiHpp}%`,
|
||||
'' // dikosongkan — status digambar manual via didDrawCell agar tidak double
|
||||
]
|
||||
}) || []
|
||||
|
||||
// Simpan status per baris untuk dipakai di didDrawCell
|
||||
const categoryStatuses: string[] =
|
||||
category?.data?.map(() => {
|
||||
const realisasiHpp = 0
|
||||
return realisasiHpp <= DUMMY_STD_HPP ? 'Sehat' : 'Tidak Sehat'
|
||||
}) || []
|
||||
|
||||
autoTable(pdf, {
|
||||
startY: currentY,
|
||||
head: [['Nama', 'Qty', 'Pendapatan', '% Std HPP', '% Real HPP', 'Status']],
|
||||
body: categoryBody,
|
||||
foot: [
|
||||
[
|
||||
'TOTAL',
|
||||
String(categorySummary?.totalQuantity ?? 0),
|
||||
formatCurrency(categorySummary?.totalRevenue ?? 0),
|
||||
'',
|
||||
'',
|
||||
''
|
||||
]
|
||||
],
|
||||
theme: 'grid',
|
||||
showFoot: 'lastPage',
|
||||
tableWidth: 'auto',
|
||||
styles: {
|
||||
fontSize: 9,
|
||||
cellPadding: PDF_SPACING.cellPadding,
|
||||
lineColor: [0, 0, 0],
|
||||
lineWidth: 0.1
|
||||
},
|
||||
headStyles: {
|
||||
fillColor: [54, 23, 94],
|
||||
textColor: 255,
|
||||
fontStyle: 'bold',
|
||||
fontSize: 9,
|
||||
lineColor: [0, 0, 0],
|
||||
lineWidth: 0.1
|
||||
},
|
||||
footStyles: {
|
||||
fillColor: [220, 220, 220],
|
||||
textColor: [60, 60, 60],
|
||||
fontStyle: 'bold',
|
||||
fontSize: 9,
|
||||
lineColor: [0, 0, 0],
|
||||
lineWidth: 0.1
|
||||
},
|
||||
columnStyles: {
|
||||
1: { halign: 'center' },
|
||||
2: { halign: 'right' },
|
||||
3: { halign: 'center' },
|
||||
4: { halign: 'center' },
|
||||
5: { halign: 'center' }
|
||||
},
|
||||
didParseCell: (data: any) => {
|
||||
// Footer alignment
|
||||
if (data.section === 'foot') {
|
||||
if (data.column.index === 0) data.cell.styles.halign = 'left'
|
||||
else if (data.column.index === 1) data.cell.styles.halign = 'center'
|
||||
else if (data.column.index === 2) data.cell.styles.halign = 'right'
|
||||
}
|
||||
// Paksa teks status tidak dirender oleh autoTable (set textColor = white)
|
||||
if (data.section === 'body' && data.column.index === 5) {
|
||||
data.cell.styles.textColor = [255, 255, 255]
|
||||
}
|
||||
},
|
||||
didDrawCell: (data: any) => {
|
||||
if (data.section === 'body' && data.column.index === 5) {
|
||||
const status = categoryStatuses[data.row.index] || 'Sehat'
|
||||
const color = getStatusColor(status)
|
||||
pdf.setTextColor(...color)
|
||||
pdf.setFontSize(9)
|
||||
pdf.setFont('helvetica', 'bold')
|
||||
pdf.text(status, data.cell.x + data.cell.width / 2, data.cell.y + data.cell.height / 2 + 1, { align: 'center' })
|
||||
pdf.setTextColor(0, 0, 0)
|
||||
pdf.setFont('helvetica', 'normal')
|
||||
}
|
||||
},
|
||||
margin: { left: 14, right: 14 }
|
||||
})
|
||||
|
||||
currentY = (pdf as any).lastAutoTable.finalY + 20
|
||||
|
||||
// ========== PRODUCT DETAILS BY CATEGORY ==========
|
||||
const groupedProducts =
|
||||
products?.data?.reduce(
|
||||
(acc: any, item: any) => {
|
||||
const categoryName = item.category_name || 'Tidak Berkategori'
|
||||
if (!acc[categoryName]) {
|
||||
acc[categoryName] = []
|
||||
}
|
||||
acc[categoryName].push(item)
|
||||
return acc
|
||||
},
|
||||
{} as Record<string, any[]>
|
||||
) || {}
|
||||
|
||||
pdf.addPage()
|
||||
currentY = 20
|
||||
|
||||
pdf.setFontSize(PDF_FONT_SIZES.heading)
|
||||
pdf.text('Ringkasan Item Per Kategori', 14, currentY)
|
||||
currentY += 10
|
||||
|
||||
Object.keys(groupedProducts)
|
||||
.sort((a, b) => {
|
||||
const productsA = groupedProducts[a]
|
||||
const productsB = groupedProducts[b]
|
||||
const orderA = productsA[0]?.category_order ?? 999
|
||||
const orderB = productsB[0]?.category_order ?? 999
|
||||
return orderA - orderB
|
||||
})
|
||||
.forEach((categoryName, index) => {
|
||||
const categoryProducts = groupedProducts[categoryName].sort((a: any, b: any) => {
|
||||
const skuA = a.product_sku || ''
|
||||
const skuB = b.product_sku || ''
|
||||
return skuA.localeCompare(skuB)
|
||||
})
|
||||
|
||||
const categoryTotalQty = categoryProducts.reduce((sum: number, item: any) => sum + (item.quantity_sold || 0), 0)
|
||||
const categoryTotalRevenue = categoryProducts.reduce((sum: number, item: any) => sum + (item.revenue || 0), 0)
|
||||
|
||||
// Kolom baru: % Standard HPP, % Realisasi HPP, Status — dummy visual
|
||||
const productBody = categoryProducts.map((item: any) => {
|
||||
const stdHpp = 0 // dummy — ganti dengan data real
|
||||
const realisasiHpp = 0 // dummy — ganti dengan kalkulasi real
|
||||
return [
|
||||
item.product_name,
|
||||
String(item.quantity_sold),
|
||||
formatCurrency(item.revenue),
|
||||
`${stdHpp}%`,
|
||||
`${realisasiHpp}%`,
|
||||
'' // dikosongkan — status digambar manual via didDrawCell agar tidak double
|
||||
]
|
||||
})
|
||||
|
||||
// Status per baris produk
|
||||
const productStatuses: string[] = categoryProducts.map(() => (0 <= 0 ? 'Sehat' : 'Tidak Sehat'))
|
||||
|
||||
const estimatedHeight = (productBody.length + 3) * 12
|
||||
if (currentY + estimatedHeight > 270) {
|
||||
pdf.addPage()
|
||||
currentY = 20
|
||||
}
|
||||
|
||||
pdf.setFontSize(PDF_FONT_SIZES.subheading)
|
||||
pdf.setFont('helvetica', 'bold')
|
||||
pdf.setTextColor(54, 23, 94)
|
||||
pdf.text(`${index + 1}. ${categoryName.toUpperCase()}`, 16, currentY)
|
||||
currentY += 15
|
||||
|
||||
autoTable(pdf, {
|
||||
startY: currentY,
|
||||
head: [['Produk', 'Qty', 'Pendapatan', '% Std HPP', '% Real HPP', 'Status']],
|
||||
body: productBody,
|
||||
foot: [
|
||||
[`Subtotal ${categoryName}`, String(categoryTotalQty), formatCurrency(categoryTotalRevenue), '', '', '']
|
||||
],
|
||||
showFoot: 'lastPage',
|
||||
theme: 'grid',
|
||||
styles: {
|
||||
fontSize: 9,
|
||||
cellPadding: PDF_SPACING.cellPadding,
|
||||
lineColor: [0, 0, 0],
|
||||
lineWidth: 0.1
|
||||
},
|
||||
headStyles: {
|
||||
fillColor: [54, 23, 94],
|
||||
textColor: 255,
|
||||
fontStyle: 'bold',
|
||||
fontSize: 9,
|
||||
lineColor: [0, 0, 0],
|
||||
lineWidth: 0.1
|
||||
},
|
||||
footStyles: {
|
||||
fillColor: [200, 200, 200],
|
||||
textColor: [60, 60, 60],
|
||||
fontStyle: 'bold',
|
||||
fontSize: 9,
|
||||
lineColor: [0, 0, 0],
|
||||
lineWidth: 0.1
|
||||
},
|
||||
columnStyles: {
|
||||
0: { cellWidth: 44 },
|
||||
1: { halign: 'center', cellWidth: 20 },
|
||||
2: { halign: 'right', cellWidth: 50 },
|
||||
3: { halign: 'center', cellWidth: 22 },
|
||||
4: { halign: 'center', cellWidth: 22 },
|
||||
5: { halign: 'center', cellWidth: 22 }
|
||||
},
|
||||
didParseCell: (data: any) => {
|
||||
if (data.section === 'foot') {
|
||||
if (data.column.index === 0) data.cell.styles.halign = 'left'
|
||||
else if (data.column.index === 1) data.cell.styles.halign = 'center'
|
||||
else if (data.column.index === 2) data.cell.styles.halign = 'right'
|
||||
}
|
||||
// Paksa teks status tidak dirender oleh autoTable (set textColor = white)
|
||||
if (data.section === 'body' && data.column.index === 5) {
|
||||
data.cell.styles.textColor = [255, 255, 255]
|
||||
}
|
||||
},
|
||||
didDrawCell: (data: any) => {
|
||||
// Warna teks Status (kolom index 5) — ambil dari array, bukan cell.text agar tidak double
|
||||
if (data.section === 'body' && data.column.index === 5) {
|
||||
const status = productStatuses[data.row.index] || 'Sehat'
|
||||
const color = getStatusColor(status)
|
||||
pdf.setTextColor(...color)
|
||||
pdf.setFontSize(9)
|
||||
pdf.setFont('helvetica', 'bold')
|
||||
pdf.text(status, data.cell.x + data.cell.width / 2, data.cell.y + data.cell.height / 2 + 1, {
|
||||
align: 'center'
|
||||
})
|
||||
pdf.setTextColor(0, 0, 0)
|
||||
pdf.setFont('helvetica', 'normal')
|
||||
}
|
||||
},
|
||||
margin: { left: 14, right: 14 }
|
||||
})
|
||||
|
||||
currentY = (pdf as any).lastAutoTable.finalY + 15
|
||||
})
|
||||
|
||||
// ========== GRAND TOTAL ==========
|
||||
if (currentY > 250) {
|
||||
pdf.addPage()
|
||||
currentY = 20
|
||||
}
|
||||
|
||||
autoTable(pdf, {
|
||||
startY: currentY,
|
||||
head: [],
|
||||
body: [
|
||||
[
|
||||
'TOTAL KESELURUHAN',
|
||||
String(productSummary.totalQuantitySold),
|
||||
formatCurrency(productSummary.totalRevenue),
|
||||
'',
|
||||
'',
|
||||
''
|
||||
]
|
||||
],
|
||||
theme: 'grid',
|
||||
styles: {
|
||||
fontSize: PDF_FONT_SIZES.grandTotal,
|
||||
cellPadding: 6,
|
||||
fontStyle: 'bold',
|
||||
textColor: [54, 23, 94],
|
||||
lineColor: [0, 0, 0],
|
||||
lineWidth: 0.2
|
||||
},
|
||||
columnStyles: {
|
||||
0: { cellWidth: 44 },
|
||||
1: { halign: 'center', cellWidth: 20 },
|
||||
2: { halign: 'right', cellWidth: 50 },
|
||||
3: { cellWidth: 22 },
|
||||
4: { cellWidth: 22 },
|
||||
5: { cellWidth: 22 }
|
||||
},
|
||||
margin: { left: 14, right: 14 }
|
||||
})
|
||||
|
||||
// ========== FOOTER ==========
|
||||
const pageCount = pdf.getNumberOfPages()
|
||||
for (let i = 1; i <= pageCount; i++) {
|
||||
pdf.setPage(i)
|
||||
pdf.setFontSize(11)
|
||||
pdf.setTextColor(120, 120, 120)
|
||||
pdf.text('© 2025 Apskel - Sistem POS Terpadu', 14, 287)
|
||||
pdf.text(`Dicetak pada: ${now.toLocaleDateString('id-ID')}`, 190, 287, { align: 'right' })
|
||||
}
|
||||
|
||||
// ========== SAVE PDF ==========
|
||||
const fileName =
|
||||
filterType === 'single'
|
||||
? `laporan-transaksi-${formatDateForInput(selectedDate)}.pdf`
|
||||
: `laporan-transaksi-${formatDateForInput(dateRange.startDate)}-to-${formatDateForInput(dateRange.endDate)}.pdf`
|
||||
|
||||
pdf.save(fileName)
|
||||
}
|
||||
@@ -43,6 +43,15 @@ export const formatDateDDMMYYYY = (dateString: Date | string) => {
|
||||
return `${day}-${month}-${year}`
|
||||
}
|
||||
|
||||
export const formatDateYYYYMMDD = (dateString: Date | string) => {
|
||||
const date = new Date(dateString)
|
||||
date.setHours(0, 0, 0, 0)
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const year = date.getFullYear()
|
||||
return `${year}-${month}-${day}`
|
||||
}
|
||||
|
||||
export const formatForInputDate = (dateString: Date | string) => {
|
||||
const date = new Date(dateString)
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
@@ -51,7 +60,6 @@ export const formatForInputDate = (dateString: Date | string) => {
|
||||
return `${year}-${month}-${day}`
|
||||
}
|
||||
|
||||
|
||||
export const formatDatetime = (dateString: string | number | Date) => {
|
||||
const date = new Date(dateString)
|
||||
|
||||
|
||||
@@ -13,8 +13,10 @@ import Checkbox from '@mui/material/Checkbox'
|
||||
import Chip from '@mui/material/Chip'
|
||||
import MenuItem from '@mui/material/MenuItem'
|
||||
import TablePagination from '@mui/material/TablePagination'
|
||||
import TextField from '@mui/material/TextField'
|
||||
import type { TextFieldProps } from '@mui/material/TextField'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import { Box, CircularProgress, useTheme } from '@mui/material'
|
||||
|
||||
// Third-party Imports
|
||||
import type { RankingInfo } from '@tanstack/match-sorter-utils'
|
||||
@@ -40,11 +42,10 @@ import { getLocalizedUrl } from '@/utils/i18n'
|
||||
|
||||
// Style Imports
|
||||
import tableStyles from '@core/styles/table.module.css'
|
||||
import { Box, CircularProgress } from '@mui/material'
|
||||
import Loading from '../../../../../components/layout/shared/Loading'
|
||||
import { useOrders } from '../../../../../services/queries/orders'
|
||||
import { Order } from '../../../../../types/services/order'
|
||||
import { formatCurrency } from '../../../../../utils/transform'
|
||||
import { formatCurrency, formatDateDDMMYYYY, formatForInputDate } from '../../../../../utils/transform'
|
||||
|
||||
declare module '@tanstack/table-core' {
|
||||
interface FilterFns {
|
||||
@@ -105,15 +106,28 @@ const DebouncedInput = ({
|
||||
const columnHelper = createColumnHelper<ECommerceOrderTypeWithAction>()
|
||||
|
||||
const OrderListTable = () => {
|
||||
const theme = useTheme()
|
||||
|
||||
// States
|
||||
const [rowSelection, setRowSelection] = useState({})
|
||||
const [currentPage, setCurrentPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(10)
|
||||
const [search, setSearch] = useState('')
|
||||
|
||||
// Set default date range to current month
|
||||
const today = new Date()
|
||||
const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1)
|
||||
|
||||
const [filter, setFilter] = useState({
|
||||
date_from: formatForInputDate(firstDayOfMonth),
|
||||
date_to: formatForInputDate(today)
|
||||
})
|
||||
|
||||
const { data, isLoading, error, isFetching } = useOrders({
|
||||
page: currentPage,
|
||||
limit: pageSize,
|
||||
date_from: formatDateDDMMYYYY(new Date(filter.date_from)),
|
||||
date_to: formatDateDDMMYYYY(new Date(filter.date_to)),
|
||||
search
|
||||
})
|
||||
|
||||
@@ -163,7 +177,7 @@ const OrderListTable = () => {
|
||||
cell: ({ row }) => (
|
||||
<Typography
|
||||
component={Link}
|
||||
href={getLocalizedUrl(`/apps/ecommerce/orders/details/${row.original.order_number}`, locale as Locale)}
|
||||
href={getLocalizedUrl(`/apps/inventory/orders/${row.original.id}/details`, locale as Locale)}
|
||||
color='primary.main'
|
||||
>{`#${row.original.order_number}`}</Typography>
|
||||
)
|
||||
@@ -203,6 +217,10 @@ const OrderListTable = () => {
|
||||
header: 'Discount',
|
||||
cell: ({ row }) => <Typography>{formatCurrency(row.original.discount_amount)}</Typography>
|
||||
}),
|
||||
columnHelper.accessor('created_at', {
|
||||
header: 'Created At',
|
||||
cell: ({ row }) => <Typography>{formatDateDDMMYYYY(new Date(row.original.created_at))}</Typography>
|
||||
}),
|
||||
columnHelper.accessor('action', {
|
||||
header: 'Action',
|
||||
cell: ({ row }) => (
|
||||
@@ -214,10 +232,7 @@ const OrderListTable = () => {
|
||||
{
|
||||
text: 'View',
|
||||
icon: 'tabler-eye',
|
||||
href: getLocalizedUrl(
|
||||
`/apps/ecommerce/orders/${row.original.id}/details`,
|
||||
locale as Locale
|
||||
),
|
||||
href: getLocalizedUrl(`/apps/inventory/orders/${row.original.id}/details`, locale as Locale),
|
||||
linkProps: { className: 'flex items-center gap-2 is-full plb-2 pli-4' }
|
||||
},
|
||||
{
|
||||
@@ -248,49 +263,104 @@ const OrderListTable = () => {
|
||||
state: {
|
||||
rowSelection,
|
||||
pagination: {
|
||||
pageIndex: currentPage, // <= penting!
|
||||
pageIndex: currentPage,
|
||||
pageSize
|
||||
}
|
||||
},
|
||||
enableRowSelection: true, //enable row selection for all rows
|
||||
enableRowSelection: true,
|
||||
onRowSelectionChange: setRowSelection,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
// Disable client-side pagination since we're handling it server-side
|
||||
manualPagination: true,
|
||||
pageCount: Math.ceil(totalCount / pageSize)
|
||||
})
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className='flex justify-between max-sm:flex-col sm:items-center gap-4'>
|
||||
<DebouncedInput
|
||||
value={search}
|
||||
onChange={value => setSearch(value as string)}
|
||||
placeholder='Search Order'
|
||||
className='sm:is-auto'
|
||||
/>
|
||||
<div className='flex items-center max-sm:flex-col gap-4 max-sm:is-full is-auto'>
|
||||
<CustomTextField
|
||||
select
|
||||
value={pageSize}
|
||||
onChange={handlePageSizeChange}
|
||||
className='is-[70px] max-sm:is-full'
|
||||
>
|
||||
<MenuItem value='10'>10</MenuItem>
|
||||
<MenuItem value='25'>25</MenuItem>
|
||||
<MenuItem value='50'>50</MenuItem>
|
||||
<MenuItem value='100'>100</MenuItem>
|
||||
</CustomTextField>
|
||||
<Button
|
||||
variant='tonal'
|
||||
color='secondary'
|
||||
startIcon={<i className='tabler-upload' />}
|
||||
className='max-sm:is-full is-auto'
|
||||
>
|
||||
Export
|
||||
</Button>
|
||||
<CardContent className='flex flex-col gap-4'>
|
||||
{/* Date Range Filter */}
|
||||
<div className='flex items-center gap-4 max-sm:flex-col'>
|
||||
<Typography variant='body2' className='min-w-fit'>
|
||||
Filter by Date:
|
||||
</Typography>
|
||||
<TextField
|
||||
type='date'
|
||||
value={filter.date_from}
|
||||
onChange={e => {
|
||||
setFilter({
|
||||
...filter,
|
||||
date_from: e.target.value
|
||||
})
|
||||
setCurrentPage(1)
|
||||
}}
|
||||
size='small'
|
||||
sx={{
|
||||
'& .MuiOutlinedInput-root': {
|
||||
'&.Mui-focused fieldset': {
|
||||
borderColor: 'primary.main'
|
||||
},
|
||||
'& fieldset': {
|
||||
borderColor: theme.palette.mode === 'dark' ? 'rgba(231, 227, 252, 0.22)' : theme.palette.divider
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Typography>-</Typography>
|
||||
<TextField
|
||||
type='date'
|
||||
value={filter.date_to}
|
||||
onChange={e => {
|
||||
setFilter({
|
||||
...filter,
|
||||
date_to: e.target.value
|
||||
})
|
||||
setCurrentPage(1)
|
||||
}}
|
||||
size='small'
|
||||
sx={{
|
||||
'& .MuiOutlinedInput-root': {
|
||||
'&.Mui-focused fieldset': {
|
||||
borderColor: 'primary.main'
|
||||
},
|
||||
'& fieldset': {
|
||||
borderColor: theme.palette.mode === 'dark' ? 'rgba(231, 227, 252, 0.22)' : theme.palette.divider
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Search and Actions */}
|
||||
<div className='flex justify-between max-sm:flex-col sm:items-center gap-4'>
|
||||
<DebouncedInput
|
||||
value={search}
|
||||
onChange={value => setSearch(value as string)}
|
||||
placeholder='Search Order'
|
||||
className='sm:is-auto'
|
||||
/>
|
||||
<div className='flex items-center max-sm:flex-col gap-4 max-sm:is-full is-auto'>
|
||||
<CustomTextField
|
||||
select
|
||||
value={pageSize}
|
||||
onChange={handlePageSizeChange}
|
||||
className='is-[70px] max-sm:is-full'
|
||||
>
|
||||
<MenuItem value='10'>10</MenuItem>
|
||||
<MenuItem value='25'>25</MenuItem>
|
||||
<MenuItem value='50'>50</MenuItem>
|
||||
<MenuItem value='100'>100</MenuItem>
|
||||
</CustomTextField>
|
||||
<Button
|
||||
variant='tonal'
|
||||
color='secondary'
|
||||
startIcon={<i className='tabler-upload' />}
|
||||
className='max-sm:is-full is-auto'
|
||||
>
|
||||
Export
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
<div className='overflow-x-auto'>
|
||||
{isLoading ? (
|
||||
<Loading />
|
||||
|
||||
@@ -82,6 +82,8 @@ const ProductOrganize = () => {
|
||||
onChange={e => handleSelectChange('printer_type', e.target.value)}
|
||||
>
|
||||
<MenuItem value={`kitchen`}>Kitchen</MenuItem>
|
||||
<MenuItem value={`bar`}>Bar</MenuItem>
|
||||
<MenuItem value={`ticket`}>Ticket</MenuItem>
|
||||
</CustomTextField>
|
||||
</form>
|
||||
</CardContent>
|
||||
|
||||
@@ -33,7 +33,8 @@ const AddCategoryDrawer = (props: Props) => {
|
||||
const [formData, setFormData] = useState<CategoryRequest>({
|
||||
name: '',
|
||||
description: '',
|
||||
business_type: ''
|
||||
business_type: '',
|
||||
order: 0
|
||||
})
|
||||
|
||||
// Handle Form Submit
|
||||
@@ -54,13 +55,21 @@ const AddCategoryDrawer = (props: Props) => {
|
||||
})
|
||||
}
|
||||
|
||||
const handleOrderChange = (e: any) => {
|
||||
setFormData({
|
||||
...formData,
|
||||
order: parseInt(e.target.value) || 0
|
||||
})
|
||||
}
|
||||
|
||||
// Handle Form Reset
|
||||
const handleReset = () => {
|
||||
handleClose()
|
||||
setFormData({
|
||||
name: '',
|
||||
description: '',
|
||||
business_type: ''
|
||||
business_type: '',
|
||||
order: 0
|
||||
})
|
||||
}
|
||||
|
||||
@@ -99,6 +108,15 @@ const AddCategoryDrawer = (props: Props) => {
|
||||
>
|
||||
<MenuItem value='restaurant'>Restaurant</MenuItem>
|
||||
</CustomTextField>
|
||||
<CustomTextField
|
||||
fullWidth
|
||||
label='Order'
|
||||
name='order'
|
||||
type='number'
|
||||
value={formData.order}
|
||||
onChange={handleOrderChange}
|
||||
placeholder='0'
|
||||
/>
|
||||
<CustomTextField
|
||||
fullWidth
|
||||
label='Description'
|
||||
|
||||
@@ -34,7 +34,8 @@ const EditCategoryDrawer = (props: Props) => {
|
||||
const [formData, setFormData] = useState<CategoryRequest>({
|
||||
name: '',
|
||||
description: '',
|
||||
business_type: ''
|
||||
business_type: '',
|
||||
order: 0
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
@@ -42,7 +43,8 @@ const EditCategoryDrawer = (props: Props) => {
|
||||
setFormData({
|
||||
name: data.name,
|
||||
description: data.description,
|
||||
business_type: data.business_type
|
||||
business_type: data.business_type,
|
||||
order: data.order
|
||||
})
|
||||
}
|
||||
}, [data])
|
||||
@@ -51,11 +53,14 @@ const EditCategoryDrawer = (props: Props) => {
|
||||
const handleFormSubmit = (e: any) => {
|
||||
e.preventDefault()
|
||||
|
||||
updateCategory({ id: data.id, payload: formData }, {
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
updateCategory(
|
||||
{ id: data.id, payload: formData },
|
||||
{
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
}
|
||||
}
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
const handleInputChange = (e: any) => {
|
||||
@@ -65,13 +70,21 @@ const EditCategoryDrawer = (props: Props) => {
|
||||
})
|
||||
}
|
||||
|
||||
const handleOrderChange = (e: any) => {
|
||||
setFormData({
|
||||
...formData,
|
||||
order: parseInt(e.target.value) || 0
|
||||
})
|
||||
}
|
||||
|
||||
// Handle Form Reset
|
||||
const handleReset = () => {
|
||||
handleClose()
|
||||
setFormData({
|
||||
name: '',
|
||||
description: '',
|
||||
business_type: ''
|
||||
business_type: '',
|
||||
order: 0
|
||||
})
|
||||
}
|
||||
|
||||
@@ -110,6 +123,15 @@ const EditCategoryDrawer = (props: Props) => {
|
||||
>
|
||||
<MenuItem value='restaurant'>Restaurant</MenuItem>
|
||||
</CustomTextField>
|
||||
<CustomTextField
|
||||
fullWidth
|
||||
label='Order'
|
||||
name='order'
|
||||
type='number'
|
||||
value={formData.order}
|
||||
onChange={handleOrderChange}
|
||||
placeholder='0'
|
||||
/>
|
||||
<CustomTextField
|
||||
fullWidth
|
||||
label='Description'
|
||||
|
||||
@@ -12,6 +12,7 @@ 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'
|
||||
@@ -19,24 +20,26 @@ 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'
|
||||
import { DragDropContext, Droppable, Draggable, DropResult } from '@hello-pangea/dnd'
|
||||
|
||||
// Component Imports
|
||||
import TablePaginationComponent from '@components/TablePaginationComponent'
|
||||
import CustomTextField from '@core/components/mui/TextField'
|
||||
import OptionMenu from '@core/components/option-menu'
|
||||
import AddCategoryDrawer from './AddCategoryDrawer'
|
||||
|
||||
// Style Imports
|
||||
import tableStyles from '@core/styles/table.module.css'
|
||||
import { Box, CircularProgress } from '@mui/material'
|
||||
import EditCategoryDrawer from './EditCategoryDrawer'
|
||||
import ConfirmDeleteDialog from '../../../../../components/dialogs/confirm-delete'
|
||||
import Loading from '../../../../../components/layout/shared/Loading'
|
||||
|
||||
// Services Imports
|
||||
import { useCategoriesMutation } from '../../../../../services/mutations/categories'
|
||||
import { useCategories } from '../../../../../services/queries/categories'
|
||||
import { Category } from '../../../../../types/services/category'
|
||||
import EditCategoryDrawer from './EditCategoryDrawer'
|
||||
import { formatDate } from '../../../../../utils/transform'
|
||||
|
||||
// Style Imports
|
||||
import tableStyles from '@core/styles/table.module.css'
|
||||
|
||||
declare module '@tanstack/table-core' {
|
||||
interface FilterFns {
|
||||
fuzzy: FilterFn<unknown>
|
||||
@@ -51,15 +54,8 @@ type CategoryWithActionsType = Category & {
|
||||
}
|
||||
|
||||
const fuzzyFilter: FilterFn<any> = (row, columnId, value, addMeta) => {
|
||||
// Rank the item
|
||||
const itemRank = rankItem(row.getValue(columnId), value)
|
||||
|
||||
// Store the itemRank info
|
||||
addMeta({
|
||||
itemRank
|
||||
})
|
||||
|
||||
// Return if the item should be filtered in/out
|
||||
addMeta({ itemRank })
|
||||
return itemRank.passed
|
||||
}
|
||||
|
||||
@@ -73,7 +69,6 @@ const DebouncedInput = ({
|
||||
onChange: (value: string | number) => void
|
||||
debounce?: number
|
||||
} & Omit<TextFieldProps, 'onChange'>) => {
|
||||
// States
|
||||
const [value, setValue] = useState(initialValue)
|
||||
|
||||
useEffect(() => {
|
||||
@@ -86,47 +81,51 @@ const DebouncedInput = ({
|
||||
}, debounce)
|
||||
|
||||
return () => clearTimeout(timeout)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [value])
|
||||
|
||||
return <CustomTextField {...props} value={value} onChange={e => setValue(e.target.value)} />
|
||||
}
|
||||
|
||||
// Column Definitions
|
||||
const columnHelper = createColumnHelper<CategoryWithActionsType>()
|
||||
|
||||
const ProductCategoryTable = () => {
|
||||
// States
|
||||
const [addCategoryOpen, setAddCategoryOpen] = useState(false)
|
||||
const [editCategoryOpen, setEditCategoryOpen] = useState(false)
|
||||
const [rowSelection, setRowSelection] = useState({})
|
||||
const [currentPage, setCurrentPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(10)
|
||||
const [pageSize, setPageSize] = useState(50)
|
||||
const [categoryId, setCategoryId] = useState('')
|
||||
const [openConfirm, setOpenConfirm] = useState(false)
|
||||
const [currentCategory, setCurrentCategory] = useState<Category>()
|
||||
const [search, setSearch] = useState('')
|
||||
const [localCategories, setLocalCategories] = useState<Category[]>([])
|
||||
|
||||
// Fetch products with pagination and search
|
||||
const { data, isLoading, error, isFetching } = useCategories({
|
||||
page: currentPage,
|
||||
limit: pageSize
|
||||
})
|
||||
|
||||
const { mutate: deleteCategory, isPending: isDeleting } = useCategoriesMutation().deleteCategory
|
||||
const { mutate: updateCategory } = useCategoriesMutation().updateCategory
|
||||
|
||||
const categories = data?.categories ?? []
|
||||
const totalCount = data?.total_count ?? 0
|
||||
|
||||
// Update local categories when data changes
|
||||
useEffect(() => {
|
||||
if (categories.length > 0) {
|
||||
setLocalCategories(categories)
|
||||
}
|
||||
}, [categories])
|
||||
|
||||
const handlePageChange = useCallback((event: unknown, newPage: number) => {
|
||||
setCurrentPage(newPage)
|
||||
}, [])
|
||||
|
||||
// Handle page size change
|
||||
const handlePageSizeChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newPageSize = parseInt(event.target.value, 10)
|
||||
const newPageSize = parseInt(event.target.value, 50)
|
||||
setPageSize(newPageSize)
|
||||
setCurrentPage(1) // Reset to first page
|
||||
setCurrentPage(1)
|
||||
}, [])
|
||||
|
||||
const handleDelete = () => {
|
||||
@@ -135,8 +134,56 @@ const ProductCategoryTable = () => {
|
||||
})
|
||||
}
|
||||
|
||||
const handleDragEnd = (result: DropResult) => {
|
||||
if (!result.destination) return
|
||||
|
||||
const items = Array.from(localCategories)
|
||||
const [reorderedItem] = items.splice(result.source.index, 1)
|
||||
items.splice(result.destination.index, 0, reorderedItem)
|
||||
|
||||
setLocalCategories(items)
|
||||
|
||||
// Update order for all affected items
|
||||
items.forEach((item, index) => {
|
||||
const newOrder = index + 1 // Order dimulai dari 1
|
||||
|
||||
// Only update if order changed
|
||||
if (item.order !== newOrder) {
|
||||
const updateData = {
|
||||
name: item.name,
|
||||
description: item.description,
|
||||
business_type: item.business_type,
|
||||
order: newOrder
|
||||
}
|
||||
|
||||
updateCategory(
|
||||
{ id: item.id, payload: updateData },
|
||||
{
|
||||
onSuccess: () => {
|
||||
console.log(`Category ${item.name} order updated to ${newOrder}`)
|
||||
},
|
||||
onError: error => {
|
||||
console.error(`Failed to update category ${item.name}:`, error)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const columns = useMemo<ColumnDef<CategoryWithActionsType, any>[]>(
|
||||
() => [
|
||||
{
|
||||
id: 'drag',
|
||||
header: '',
|
||||
cell: () => (
|
||||
<div className='cursor-move flex items-center justify-center'>
|
||||
<i className='tabler-grip-vertical text-textSecondary text-xl' />
|
||||
</div>
|
||||
),
|
||||
size: 50,
|
||||
enableSorting: false
|
||||
},
|
||||
{
|
||||
id: 'select',
|
||||
header: ({ table }) => (
|
||||
@@ -163,7 +210,6 @@ const ProductCategoryTable = () => {
|
||||
header: 'Name',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-3'>
|
||||
{/* <img src={row.original.image} width={38} height={38} className='rounded bg-actionHover' /> */}
|
||||
<div className='flex flex-col items-start'>
|
||||
<Typography className='font-medium' color='text.primary'>
|
||||
{row.original.name}
|
||||
@@ -173,7 +219,7 @@ const ProductCategoryTable = () => {
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('description', {
|
||||
header: 'Decription',
|
||||
header: 'Description',
|
||||
cell: ({ row }) => <Typography>{row.original.description || '-'}</Typography>
|
||||
}),
|
||||
columnHelper.accessor('business_type', {
|
||||
@@ -219,12 +265,11 @@ const ProductCategoryTable = () => {
|
||||
enableSorting: false
|
||||
})
|
||||
],
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[data]
|
||||
)
|
||||
|
||||
const table = useReactTable({
|
||||
data: categories as Category[],
|
||||
data: localCategories as Category[],
|
||||
columns,
|
||||
filterFns: {
|
||||
fuzzy: fuzzyFilter
|
||||
@@ -232,14 +277,13 @@ const ProductCategoryTable = () => {
|
||||
state: {
|
||||
rowSelection,
|
||||
pagination: {
|
||||
pageIndex: currentPage, // <= penting!
|
||||
pageIndex: currentPage,
|
||||
pageSize
|
||||
}
|
||||
},
|
||||
enableRowSelection: true, //enable row selection for all rows
|
||||
enableRowSelection: true,
|
||||
onRowSelectionChange: setRowSelection,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
// Disable client-side pagination since we're handling it server-side
|
||||
manualPagination: true,
|
||||
pageCount: Math.ceil(totalCount / pageSize)
|
||||
})
|
||||
@@ -261,9 +305,9 @@ const ProductCategoryTable = () => {
|
||||
onChange={handlePageSizeChange}
|
||||
className='flex-auto max-sm:is-full sm:is-[70px]'
|
||||
>
|
||||
<MenuItem value='10'>10</MenuItem>
|
||||
<MenuItem value='15'>15</MenuItem>
|
||||
<MenuItem value='25'>25</MenuItem>
|
||||
<MenuItem value='50'>50</MenuItem>
|
||||
<MenuItem value='75'>75</MenuItem>
|
||||
<MenuItem value='100'>100</MenuItem>
|
||||
</CustomTextField>
|
||||
<Button
|
||||
variant='contained'
|
||||
@@ -275,18 +319,18 @@ const ProductCategoryTable = () => {
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className='overflow-x-auto'>
|
||||
<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 : (
|
||||
<>
|
||||
<DragDropContext onDragEnd={handleDragEnd}>
|
||||
<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(),
|
||||
@@ -300,38 +344,58 @@ const ProductCategoryTable = () => {
|
||||
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>
|
||||
))}
|
||||
)}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
<Droppable droppableId='category-table'>
|
||||
{provided => (
|
||||
<tbody {...provided.droppableProps} ref={provided.innerRef}>
|
||||
{table.getFilteredRowModel().rows.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
|
||||
No data available
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
)}
|
||||
</table>
|
||||
) : (
|
||||
table
|
||||
.getRowModel()
|
||||
.rows.slice(0, table.getState().pagination.pageSize)
|
||||
.map((row, index) => {
|
||||
const categoryId = row.original.id
|
||||
return (
|
||||
<Draggable key={categoryId} draggableId={categoryId} index={index}>
|
||||
{(provided, snapshot) => (
|
||||
<tr
|
||||
ref={provided.innerRef}
|
||||
{...provided.draggableProps}
|
||||
className={classnames({
|
||||
selected: row.getIsSelected()
|
||||
})}
|
||||
style={{
|
||||
...provided.draggableProps.style,
|
||||
backgroundColor: snapshot.isDragging ? '#f3f4f6' : 'transparent'
|
||||
}}
|
||||
>
|
||||
{row.getVisibleCells().map((cell, cellIndex) => (
|
||||
<td key={cell.id} {...(cellIndex === 0 ? provided.dragHandleProps : {})}>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
)}
|
||||
</Draggable>
|
||||
)
|
||||
})
|
||||
)}
|
||||
{provided.placeholder}
|
||||
</tbody>
|
||||
)}
|
||||
</Droppable>
|
||||
</table>
|
||||
</DragDropContext>
|
||||
)}
|
||||
|
||||
{isFetching && !isLoading && (
|
||||
@@ -365,7 +429,7 @@ const ProductCategoryTable = () => {
|
||||
page={currentPage}
|
||||
onPageChange={handlePageChange}
|
||||
onRowsPerPageChange={handlePageSizeChange}
|
||||
rowsPerPageOptions={[10, 25, 50]}
|
||||
rowsPerPageOptions={[50, 75, 100]}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
@@ -0,0 +1,501 @@
|
||||
// React Imports
|
||||
import { useState, useEffect } from 'react'
|
||||
|
||||
// MUI Imports
|
||||
import Button from '@mui/material/Button'
|
||||
import Drawer from '@mui/material/Drawer'
|
||||
import IconButton from '@mui/material/IconButton'
|
||||
import MenuItem from '@mui/material/MenuItem'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import Box from '@mui/material/Box'
|
||||
import Switch from '@mui/material/Switch'
|
||||
import FormControlLabel from '@mui/material/FormControlLabel'
|
||||
|
||||
// Third-party Imports
|
||||
import { useForm, Controller } from 'react-hook-form'
|
||||
|
||||
// Component Imports
|
||||
import CustomTextField from '@core/components/mui/TextField'
|
||||
import ImageUpload from '@/components/ImageUpload'
|
||||
|
||||
// Types
|
||||
import { Campaign, CampaignRequest, CampaignType } from '@/types/services/campaign'
|
||||
import { useCampaignsMutation } from '@/services/mutations/campaign'
|
||||
import { useFilesMutation } from '@/services/mutations/files'
|
||||
import { formatDateYYYYMMDD } from '@/utils/transform'
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
handleClose: () => void
|
||||
data?: Campaign // Data campaign untuk edit (jika ada)
|
||||
}
|
||||
|
||||
type FormValidateType = {
|
||||
name: string
|
||||
description: string
|
||||
type: CampaignType
|
||||
start_date: string
|
||||
end_date: string
|
||||
is_active: boolean
|
||||
show_on_app: boolean
|
||||
position: number
|
||||
banner_url: string
|
||||
}
|
||||
|
||||
// Initial form data
|
||||
const initialData: FormValidateType = {
|
||||
name: '',
|
||||
description: '',
|
||||
type: 'POINTS',
|
||||
start_date: '',
|
||||
end_date: '',
|
||||
is_active: true,
|
||||
show_on_app: true,
|
||||
position: 1,
|
||||
banner_url: ''
|
||||
}
|
||||
|
||||
const AddEditCampaignDrawer = (props: Props) => {
|
||||
// Props
|
||||
const { open, handleClose, data } = props
|
||||
|
||||
// States
|
||||
const [showMore, setShowMore] = useState(false)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [bannerUrl, setBannerUrl] = useState<string>('')
|
||||
|
||||
const { createCampaign, updateCampaign } = useCampaignsMutation()
|
||||
const { mutate: uploadFile, isPending: isUploadPending } = useFilesMutation().uploadFile
|
||||
|
||||
// Determine if this is edit mode
|
||||
const isEditMode = Boolean(data?.id)
|
||||
|
||||
// Hooks
|
||||
const {
|
||||
control,
|
||||
reset: resetForm,
|
||||
handleSubmit,
|
||||
watch,
|
||||
setValue,
|
||||
formState: { errors }
|
||||
} = useForm<FormValidateType>({
|
||||
defaultValues: initialData
|
||||
})
|
||||
|
||||
const watchedStartDate = watch('start_date')
|
||||
const watchedEndDate = watch('end_date')
|
||||
|
||||
// Effect to populate form when editing
|
||||
useEffect(() => {
|
||||
if (isEditMode && data) {
|
||||
const formData: FormValidateType = {
|
||||
name: data.name || '',
|
||||
description: data.description || '',
|
||||
type: data.type || 'POINTS',
|
||||
start_date: data.start_date ? new Date(data.start_date).toISOString().split('T')[0] : '',
|
||||
end_date: data.end_date ? new Date(data.end_date).toISOString().split('T')[0] : '',
|
||||
is_active: data.is_active ?? true,
|
||||
show_on_app: data.show_on_app ?? true,
|
||||
position: data.position || 1,
|
||||
banner_url: data.metadata?.banner_url || ''
|
||||
}
|
||||
|
||||
resetForm(formData)
|
||||
setBannerUrl(data.metadata?.banner_url || '')
|
||||
setShowMore(true) // Always show more for edit mode
|
||||
} else {
|
||||
// Reset to initial data for add mode
|
||||
resetForm(initialData)
|
||||
setBannerUrl('')
|
||||
setShowMore(false)
|
||||
}
|
||||
}, [data, isEditMode, resetForm])
|
||||
|
||||
const handleFormSubmit = async (formData: FormValidateType) => {
|
||||
try {
|
||||
setIsSubmitting(true)
|
||||
|
||||
// Create metadata object
|
||||
const metadata: { banner_url?: string } = {}
|
||||
if (bannerUrl.trim()) {
|
||||
metadata.banner_url = bannerUrl.trim()
|
||||
}
|
||||
|
||||
// Create CampaignRequest object
|
||||
const campaignRequest: CampaignRequest = {
|
||||
name: formData.name,
|
||||
description: formData.description || undefined,
|
||||
type: formData.type,
|
||||
start_date: formatDateYYYYMMDD(formData.start_date),
|
||||
end_date: formatDateYYYYMMDD(formData.end_date),
|
||||
is_active: formData.is_active,
|
||||
show_on_app: formData.show_on_app,
|
||||
position: formData.position,
|
||||
metadata: Object.keys(metadata).length > 0 ? metadata : undefined
|
||||
}
|
||||
|
||||
if (isEditMode && data?.id) {
|
||||
// Update existing campaign
|
||||
updateCampaign.mutate(
|
||||
{ id: data.id, payload: campaignRequest },
|
||||
{
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
handleClose()
|
||||
}
|
||||
}
|
||||
)
|
||||
} else {
|
||||
// Create new campaign
|
||||
createCampaign.mutate(campaignRequest, {
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
handleClose()
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error submitting campaign:', error)
|
||||
// Handle error (show toast, etc.)
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleReset = () => {
|
||||
handleClose()
|
||||
resetForm(initialData)
|
||||
setBannerUrl('')
|
||||
setShowMore(false)
|
||||
}
|
||||
|
||||
// Handle file upload
|
||||
const handleBannerUpload = async (file: File): Promise<string> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
formData.append('file_type', 'image')
|
||||
formData.append('description', 'campaign banner upload')
|
||||
|
||||
uploadFile(formData, {
|
||||
onSuccess: r => {
|
||||
setBannerUrl(r.file_url)
|
||||
setValue('banner_url', r.file_url) // Update form value
|
||||
resolve(r.id)
|
||||
},
|
||||
onError: er => {
|
||||
reject(er)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
open={open}
|
||||
anchor='right'
|
||||
variant='temporary'
|
||||
onClose={handleReset}
|
||||
ModalProps={{ keepMounted: true }}
|
||||
sx={{
|
||||
'& .MuiDrawer-paper': {
|
||||
width: { xs: 300, sm: 400 },
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
height: '100%'
|
||||
}
|
||||
}}
|
||||
>
|
||||
{/* Sticky Header */}
|
||||
<Box
|
||||
sx={{
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
zIndex: 10,
|
||||
backgroundColor: 'background.paper',
|
||||
borderBottom: 1,
|
||||
borderColor: 'divider'
|
||||
}}
|
||||
>
|
||||
<div className='flex items-center justify-between plb-5 pli-6'>
|
||||
<Typography variant='h5'>{isEditMode ? 'Edit Kampanye' : 'Tambah Kampanye Baru'}</Typography>
|
||||
<IconButton size='small' onClick={handleReset}>
|
||||
<i className='tabler-x text-2xl text-textPrimary' />
|
||||
</IconButton>
|
||||
</div>
|
||||
</Box>
|
||||
|
||||
{/* Scrollable Content */}
|
||||
<Box sx={{ flex: 1, overflowY: 'auto' }}>
|
||||
<form id='campaign-form' onSubmit={handleSubmit(handleFormSubmit)}>
|
||||
<div className='flex flex-col gap-6 p-6'>
|
||||
{/* Nama Kampanye */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Nama Kampanye <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='name'
|
||||
control={control}
|
||||
rules={{ required: 'Nama kampanye wajib diisi' }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='Masukkan nama kampanye'
|
||||
error={!!errors.name}
|
||||
helperText={errors.name?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Jenis Kampanye */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Jenis Kampanye <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='type'
|
||||
control={control}
|
||||
rules={{ required: 'Jenis kampanye wajib dipilih' }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField {...field} select fullWidth error={!!errors.type} helperText={errors.type?.message}>
|
||||
<MenuItem value='POINTS'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<i className='tabler-coins text-primary' />
|
||||
Points
|
||||
</div>
|
||||
</MenuItem>
|
||||
<MenuItem value='TOKENS'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<i className='tabler-ticket text-success' />
|
||||
Tokens
|
||||
</div>
|
||||
</MenuItem>
|
||||
<MenuItem value='REWARD'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<i className='tabler-gift text-warning' />
|
||||
Reward
|
||||
</div>
|
||||
</MenuItem>
|
||||
<MenuItem value='MIXED'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<i className='tabler-layers-intersect text-info' />
|
||||
Mixed
|
||||
</div>
|
||||
</MenuItem>
|
||||
</CustomTextField>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Tanggal Mulai */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Tanggal Mulai <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='start_date'
|
||||
control={control}
|
||||
rules={{ required: 'Tanggal mulai wajib diisi' }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='date'
|
||||
error={!!errors.start_date}
|
||||
helperText={errors.start_date?.message}
|
||||
InputLabelProps={{
|
||||
shrink: true
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Tanggal Berakhir */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Tanggal Berakhir <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='end_date'
|
||||
control={control}
|
||||
rules={{
|
||||
required: 'Tanggal berakhir wajib diisi',
|
||||
validate: value => {
|
||||
if (watchedStartDate && value) {
|
||||
return (
|
||||
new Date(value) >= new Date(watchedStartDate) || 'Tanggal berakhir harus setelah tanggal mulai'
|
||||
)
|
||||
}
|
||||
return true
|
||||
}
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='date'
|
||||
error={!!errors.end_date}
|
||||
helperText={errors.end_date?.message}
|
||||
InputLabelProps={{
|
||||
shrink: true
|
||||
}}
|
||||
inputProps={{
|
||||
min: watchedStartDate || undefined
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Status Aktif */}
|
||||
<div>
|
||||
<Controller
|
||||
name='is_active'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<FormControlLabel
|
||||
control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
|
||||
label='Kampanye Aktif'
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Show on App */}
|
||||
<div>
|
||||
<Controller
|
||||
name='show_on_app'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<FormControlLabel
|
||||
control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
|
||||
label='Tampilkan di Aplikasi'
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Tampilkan selengkapnya */}
|
||||
{!showMore && (
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
size='small'
|
||||
sx={{ textTransform: 'none', fontSize: '14px', p: 0, textAlign: 'left', width: '200px' }}
|
||||
onClick={() => setShowMore(true)}
|
||||
>
|
||||
+ Tampilkan selengkapnya
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Konten tambahan */}
|
||||
{showMore && (
|
||||
<>
|
||||
{/* Description */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Deskripsi Kampanye
|
||||
</Typography>
|
||||
<Controller
|
||||
name='description'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='Deskripsi detail tentang kampanye'
|
||||
multiline
|
||||
rows={4}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Banner Upload */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Banner Kampanye
|
||||
</Typography>
|
||||
<ImageUpload
|
||||
onUpload={handleBannerUpload}
|
||||
maxFileSize={1 * 1024 * 1024} // 1MB
|
||||
currentImageUrl={bannerUrl}
|
||||
dragDropText='Drop banner image here'
|
||||
browseButtonText='Choose Banner'
|
||||
/>
|
||||
<Typography variant='caption' color='text.secondary' className='mt-1 block'>
|
||||
Format: JPG, PNG. Ukuran maksimal: 1MB
|
||||
</Typography>
|
||||
</div>
|
||||
|
||||
{/* Position */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Posisi Kampanye
|
||||
</Typography>
|
||||
<Controller
|
||||
name='position'
|
||||
control={control}
|
||||
rules={{
|
||||
min: { value: 1, message: 'Posisi minimal 1' }
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='number'
|
||||
placeholder='Urutan tampilan kampanye'
|
||||
error={!!errors.position}
|
||||
helperText={errors.position?.message || 'Semakin kecil angka, semakin atas posisinya'}
|
||||
onChange={e => field.onChange(Number(e.target.value))}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Sembunyikan */}
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
size='small'
|
||||
sx={{ textTransform: 'none', fontSize: '14px', p: 0, textAlign: 'left', width: '200px' }}
|
||||
onClick={() => setShowMore(false)}
|
||||
>
|
||||
- Sembunyikan
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</Box>
|
||||
|
||||
{/* Sticky Footer */}
|
||||
<Box
|
||||
sx={{
|
||||
position: 'sticky',
|
||||
bottom: 0,
|
||||
zIndex: 10,
|
||||
backgroundColor: 'background.paper',
|
||||
borderTop: 1,
|
||||
borderColor: 'divider',
|
||||
p: 3
|
||||
}}
|
||||
>
|
||||
<div className='flex items-center gap-4'>
|
||||
<Button variant='contained' type='submit' form='campaign-form' disabled={isSubmitting}>
|
||||
{isSubmitting ? (isEditMode ? 'Mengupdate...' : 'Menyimpan...') : isEditMode ? 'Update' : 'Simpan'}
|
||||
</Button>
|
||||
<Button variant='outlined' color='error' onClick={handleReset} disabled={isSubmitting}>
|
||||
Batal
|
||||
</Button>
|
||||
</div>
|
||||
</Box>
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
|
||||
export default AddEditCampaignDrawer
|
||||
@@ -0,0 +1,524 @@
|
||||
'use client'
|
||||
|
||||
// React Imports
|
||||
import { useEffect, useState, useMemo, useCallback } from 'react'
|
||||
|
||||
// Next Imports
|
||||
import Link from 'next/link'
|
||||
import { useParams } from 'next/navigation'
|
||||
|
||||
// MUI Imports
|
||||
import Card from '@mui/material/Card'
|
||||
import CardHeader from '@mui/material/CardHeader'
|
||||
import Button from '@mui/material/Button'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import Chip from '@mui/material/Chip'
|
||||
import Checkbox from '@mui/material/Checkbox'
|
||||
import IconButton from '@mui/material/IconButton'
|
||||
import { styled } from '@mui/material/styles'
|
||||
import TablePagination from '@mui/material/TablePagination'
|
||||
import type { TextFieldProps } from '@mui/material/TextField'
|
||||
import MenuItem from '@mui/material/MenuItem'
|
||||
|
||||
// Third-party Imports
|
||||
import classnames from 'classnames'
|
||||
import { rankItem } from '@tanstack/match-sorter-utils'
|
||||
import {
|
||||
createColumnHelper,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
useReactTable,
|
||||
getFilteredRowModel,
|
||||
getFacetedRowModel,
|
||||
getFacetedUniqueValues,
|
||||
getFacetedMinMaxValues,
|
||||
getPaginationRowModel,
|
||||
getSortedRowModel
|
||||
} from '@tanstack/react-table'
|
||||
import type { ColumnDef, FilterFn } from '@tanstack/react-table'
|
||||
import type { RankingInfo } from '@tanstack/match-sorter-utils'
|
||||
|
||||
// Type Imports
|
||||
import type { ThemeColor } from '@core/types'
|
||||
import type { Locale } from '@configs/i18n'
|
||||
|
||||
// Component Imports
|
||||
import OptionMenu from '@core/components/option-menu'
|
||||
import TablePaginationComponent from '@components/TablePaginationComponent'
|
||||
import CustomTextField from '@core/components/mui/TextField'
|
||||
import CustomAvatar from '@core/components/mui/Avatar'
|
||||
|
||||
// Util Imports
|
||||
import { getInitials } from '@/utils/getInitials'
|
||||
import { getLocalizedUrl } from '@/utils/i18n'
|
||||
import { formatCurrency } from '@/utils/transform'
|
||||
|
||||
// Style Imports
|
||||
import tableStyles from '@core/styles/table.module.css'
|
||||
import Loading from '@/components/layout/shared/Loading'
|
||||
import AddEditCampaignDrawer from './AddEditCampaignDrawer'
|
||||
import DeleteCampaignDialog from './DeleteCampaignDialog'
|
||||
import { Campaign } from '@/types/services/campaign'
|
||||
import { useCampaigns } from '@/services/queries/campaign'
|
||||
import { useCampaignsMutation } from '@/services/mutations/campaign'
|
||||
|
||||
declare module '@tanstack/table-core' {
|
||||
interface FilterFns {
|
||||
fuzzy: FilterFn<unknown>
|
||||
}
|
||||
interface FilterMeta {
|
||||
itemRank: RankingInfo
|
||||
}
|
||||
}
|
||||
|
||||
type CampaignWithAction = Campaign & {
|
||||
action?: string
|
||||
}
|
||||
|
||||
// Styled Components
|
||||
const Icon = styled('i')({})
|
||||
|
||||
const fuzzyFilter: FilterFn<any> = (row, columnId, value, addMeta) => {
|
||||
// Rank the item
|
||||
const itemRank = rankItem(row.getValue(columnId), value)
|
||||
|
||||
// Store the itemRank info
|
||||
addMeta({
|
||||
itemRank
|
||||
})
|
||||
|
||||
// Return if the item should be filtered in/out
|
||||
return itemRank.passed
|
||||
}
|
||||
|
||||
const DebouncedInput = ({
|
||||
value: initialValue,
|
||||
onChange,
|
||||
debounce = 500,
|
||||
...props
|
||||
}: {
|
||||
value: string | number
|
||||
onChange: (value: string | number) => void
|
||||
debounce?: number
|
||||
} & Omit<TextFieldProps, 'onChange'>) => {
|
||||
// States
|
||||
const [value, setValue] = useState(initialValue)
|
||||
|
||||
useEffect(() => {
|
||||
setValue(initialValue)
|
||||
}, [initialValue])
|
||||
|
||||
useEffect(() => {
|
||||
const timeout = setTimeout(() => {
|
||||
onChange(value)
|
||||
}, debounce)
|
||||
|
||||
return () => clearTimeout(timeout)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [value])
|
||||
|
||||
return <CustomTextField {...props} value={value} onChange={e => setValue(e.target.value)} />
|
||||
}
|
||||
|
||||
// Helper function untuk format points - SAMA SEPERTI REWARD TABLE
|
||||
const formatPoints = (points: number) => {
|
||||
return new Intl.NumberFormat('id-ID').format(points)
|
||||
}
|
||||
|
||||
// Helper functions untuk campaign utilities
|
||||
const getCampaignTypeColor = (type: string): ThemeColor => {
|
||||
switch (type) {
|
||||
case 'POINTS':
|
||||
return 'primary'
|
||||
case 'TOKENS':
|
||||
return 'success'
|
||||
case 'REWARD':
|
||||
return 'warning'
|
||||
case 'MIXED':
|
||||
return 'info'
|
||||
default:
|
||||
return 'secondary'
|
||||
}
|
||||
}
|
||||
|
||||
// Column Definitions
|
||||
const columnHelper = createColumnHelper<CampaignWithAction>()
|
||||
|
||||
const CampaignListTable = () => {
|
||||
// States - PERSIS SAMA SEPERTI REWARD TABLE
|
||||
const [addCampaignOpen, setAddCampaignOpen] = useState(false)
|
||||
const [editCampaignData, setEditCampaignData] = useState<Campaign | undefined>(undefined)
|
||||
const [rowSelection, setRowSelection] = useState({})
|
||||
const [globalFilter, setGlobalFilter] = useState('')
|
||||
const [deleteCampaignOpen, setDeleteCampaignOpen] = useState(false)
|
||||
const [campaignToDelete, setCampaignToDelete] = useState<Campaign | null>(null)
|
||||
|
||||
// FIX 1: PAGINATION SAMA SEPERTI REWARD (1-based, bukan 0-based)
|
||||
const [currentPage, setCurrentPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(10)
|
||||
const [search, setSearch] = useState('')
|
||||
|
||||
const { deleteCampaign } = useCampaignsMutation()
|
||||
|
||||
const { data, isLoading, error, isFetching } = useCampaigns({
|
||||
page: currentPage, // SAMA SEPERTI REWARD - langsung currentPage
|
||||
limit: pageSize,
|
||||
search
|
||||
})
|
||||
|
||||
const campaigns = data?.campaigns ?? []
|
||||
const totalCount = data?.total ?? 0
|
||||
|
||||
// Hooks
|
||||
const { lang: locale } = useParams()
|
||||
|
||||
const handlePageChange = useCallback((event: unknown, newPage: number) => {
|
||||
setCurrentPage(newPage)
|
||||
}, [])
|
||||
|
||||
const handlePageSizeChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newPageSize = parseInt(event.target.value, 10)
|
||||
setPageSize(newPageSize)
|
||||
setCurrentPage(1) // Reset to first page
|
||||
}, [])
|
||||
|
||||
const handleEditCampaign = (campaign: Campaign) => {
|
||||
setEditCampaignData(campaign)
|
||||
setAddCampaignOpen(true)
|
||||
}
|
||||
|
||||
const handleDeleteCampaign = (campaign: Campaign) => {
|
||||
setCampaignToDelete(campaign)
|
||||
setDeleteCampaignOpen(true)
|
||||
}
|
||||
|
||||
// ADD NEW HANDLERS FOR DELETE DIALOG
|
||||
const handleConfirmDelete = () => {
|
||||
if (campaignToDelete) {
|
||||
deleteCampaign.mutate(campaignToDelete.id, {
|
||||
onSuccess: () => {
|
||||
console.log('Campaign deleted successfully')
|
||||
setDeleteCampaignOpen(false)
|
||||
setCampaignToDelete(null)
|
||||
// You might want to refetch data here
|
||||
// refetch()
|
||||
},
|
||||
onError: error => {
|
||||
console.error('Error deleting campaign:', error)
|
||||
// Handle error (show toast, etc.)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const handleCloseDeleteDialog = () => {
|
||||
if (!deleteCampaign.isPending) {
|
||||
setDeleteCampaignOpen(false)
|
||||
setCampaignToDelete(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCloseCampaignDrawer = () => {
|
||||
setAddCampaignOpen(false)
|
||||
setEditCampaignData(undefined)
|
||||
}
|
||||
|
||||
const columns = useMemo<ColumnDef<CampaignWithAction, any>[]>(
|
||||
() => [
|
||||
{
|
||||
id: 'select',
|
||||
header: ({ table }) => (
|
||||
<Checkbox
|
||||
{...{
|
||||
checked: table.getIsAllRowsSelected(),
|
||||
indeterminate: table.getIsSomeRowsSelected(),
|
||||
onChange: table.getToggleAllRowsSelectedHandler()
|
||||
}}
|
||||
/>
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<Checkbox
|
||||
{...{
|
||||
checked: row.getIsSelected(),
|
||||
disabled: !row.getCanSelect(),
|
||||
indeterminate: row.getIsSomeSelected(),
|
||||
onChange: row.getToggleSelectedHandler()
|
||||
}}
|
||||
/>
|
||||
)
|
||||
},
|
||||
columnHelper.accessor('name', {
|
||||
header: 'Nama Kampanye',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-4'>
|
||||
<div className='flex flex-col'>
|
||||
<Link href={getLocalizedUrl(`/apps/marketing/campaign/${row.original.id}/detail`, locale as Locale)}>
|
||||
<Typography className='font-medium cursor-pointer hover:underline text-primary'>
|
||||
{row.original.name}
|
||||
</Typography>
|
||||
</Link>
|
||||
{row.original.description && (
|
||||
<Typography variant='body2' color='text.secondary' className='max-w-xs truncate'>
|
||||
{row.original.description}
|
||||
</Typography>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('type', {
|
||||
header: 'Jenis Kampanye',
|
||||
cell: ({ row }) => (
|
||||
<Chip
|
||||
label={row.original.type}
|
||||
color={getCampaignTypeColor(row.original.type)}
|
||||
variant='tonal'
|
||||
size='small'
|
||||
/>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('start_date', {
|
||||
header: 'Periode Kampanye',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex flex-col'>
|
||||
<Typography variant='body2' color='text.primary'>
|
||||
{new Date(row.original.start_date).toLocaleDateString('id-ID', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
})}
|
||||
</Typography>
|
||||
<Typography variant='body2' color='text.secondary'>
|
||||
s/d{' '}
|
||||
{new Date(row.original.end_date).toLocaleDateString('id-ID', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
})}
|
||||
</Typography>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('is_active', {
|
||||
header: 'Status',
|
||||
cell: ({ row }) => {
|
||||
const isActive = row.original.is_active
|
||||
const showOnApp = row.original.show_on_app
|
||||
|
||||
return (
|
||||
<div className='flex flex-col gap-1'>
|
||||
<Chip
|
||||
label={isActive ? 'Aktif' : 'Tidak Aktif'}
|
||||
color={isActive ? 'success' : 'error'}
|
||||
variant='tonal'
|
||||
size='small'
|
||||
/>
|
||||
{showOnApp && <Chip label='Tampil di App' color='info' variant='outlined' size='small' />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}),
|
||||
columnHelper.accessor('position', {
|
||||
header: 'Posisi',
|
||||
cell: ({ row }) => <Typography color='text.primary'>#{row.original.position}</Typography>
|
||||
}),
|
||||
columnHelper.accessor('created_at', {
|
||||
header: 'Tanggal Dibuat',
|
||||
cell: ({ row }) => (
|
||||
<Typography color='text.primary'>
|
||||
{/* FIX 3: FORMAT DATE YANG SAMA SEPERTI REWARD */}
|
||||
{new Date(row.original.created_at).toLocaleDateString('id-ID', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
})}
|
||||
</Typography>
|
||||
)
|
||||
}),
|
||||
{
|
||||
id: 'actions',
|
||||
header: 'Aksi',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center'>
|
||||
<OptionMenu
|
||||
iconButtonProps={{ size: 'medium' }}
|
||||
iconClassName='text-textSecondary text-[22px]'
|
||||
options={[
|
||||
{
|
||||
text: 'Edit',
|
||||
icon: 'tabler-edit text-[22px]',
|
||||
menuItemProps: {
|
||||
className: 'flex items-center gap-2 text-textSecondary',
|
||||
onClick: () => handleEditCampaign(row.original)
|
||||
}
|
||||
},
|
||||
{
|
||||
text: 'Hapus',
|
||||
icon: 'tabler-trash text-[22px]',
|
||||
menuItemProps: {
|
||||
className: 'flex items-center gap-2 text-textSecondary',
|
||||
onClick: () => handleDeleteCampaign(row.original)
|
||||
}
|
||||
}
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
enableSorting: false
|
||||
}
|
||||
],
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[locale, handleEditCampaign, handleDeleteCampaign]
|
||||
)
|
||||
|
||||
// FIX 4: TABLE CONFIG YANG SAMA PERSIS SEPERTI REWARD
|
||||
const table = useReactTable({
|
||||
data: campaigns as Campaign[], // SAMA SEPERTI REWARD
|
||||
columns,
|
||||
filterFns: {
|
||||
fuzzy: fuzzyFilter
|
||||
},
|
||||
state: {
|
||||
rowSelection,
|
||||
globalFilter,
|
||||
pagination: {
|
||||
pageIndex: currentPage, // SAMA SEPERTI REWARD - langsung currentPage
|
||||
pageSize
|
||||
}
|
||||
},
|
||||
enableRowSelection: true,
|
||||
onRowSelectionChange: setRowSelection,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
manualPagination: true, // SAMA SEPERTI REWARD
|
||||
pageCount: Math.ceil(totalCount / pageSize) // SAMA SEPERTI REWARD
|
||||
})
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card>
|
||||
<div className='flex justify-between flex-col items-start md:flex-row md:items-center p-6 border-bs gap-4'>
|
||||
<CustomTextField
|
||||
select
|
||||
value={table.getState().pagination.pageSize}
|
||||
onChange={e => table.setPageSize(Number(e.target.value))}
|
||||
className='max-sm:is-full sm:is-[70px]'
|
||||
>
|
||||
<MenuItem value='10'>10</MenuItem>
|
||||
<MenuItem value='25'>25</MenuItem>
|
||||
<MenuItem value='50'>50</MenuItem>
|
||||
</CustomTextField>
|
||||
<div className='flex flex-col sm:flex-row max-sm:is-full items-start sm:items-center gap-4'>
|
||||
<DebouncedInput
|
||||
value={search ?? ''}
|
||||
onChange={value => setSearch(value as string)}
|
||||
placeholder='Cari Kampanye'
|
||||
className='max-sm:is-full'
|
||||
/>
|
||||
<Button
|
||||
color='secondary'
|
||||
variant='tonal'
|
||||
startIcon={<i className='tabler-upload' />}
|
||||
className='max-sm:is-full'
|
||||
>
|
||||
Ekspor
|
||||
</Button>
|
||||
<Button
|
||||
variant='contained'
|
||||
startIcon={<i className='tabler-plus' />}
|
||||
onClick={() => setAddCampaignOpen(!addCampaignOpen)}
|
||||
className='max-sm:is-full'
|
||||
>
|
||||
Tambah Kampanye
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className='overflow-x-auto'>
|
||||
{isLoading ? (
|
||||
<Loading />
|
||||
) : (
|
||||
<table className={tableStyles.table}>
|
||||
<thead>
|
||||
{table.getHeaderGroups().map(headerGroup => (
|
||||
<tr key={headerGroup.id}>
|
||||
{headerGroup.headers.map(header => (
|
||||
<th key={header.id}>
|
||||
{header.isPlaceholder ? null : (
|
||||
<>
|
||||
<div
|
||||
className={classnames({
|
||||
'flex items-center': header.column.getIsSorted(),
|
||||
'cursor-pointer select-none': header.column.getCanSort()
|
||||
})}
|
||||
onClick={header.column.getToggleSortingHandler()}
|
||||
>
|
||||
{flexRender(header.column.columnDef.header, header.getContext())}
|
||||
{{
|
||||
asc: <i className='tabler-chevron-up text-xl' />,
|
||||
desc: <i className='tabler-chevron-down text-xl' />
|
||||
}[header.column.getIsSorted() as 'asc' | 'desc'] ?? null}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
{table.getFilteredRowModel().rows.length === 0 ? (
|
||||
<tbody>
|
||||
<tr>
|
||||
<td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
|
||||
Tidak ada data tersedia
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
) : (
|
||||
<tbody>
|
||||
{table
|
||||
.getRowModel()
|
||||
.rows.slice(0, table.getState().pagination.pageSize)
|
||||
.map(row => {
|
||||
return (
|
||||
<tr key={row.id} className={classnames({ selected: row.getIsSelected() })}>
|
||||
{row.getVisibleCells().map(cell => (
|
||||
<td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
|
||||
))}
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
)}
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
<TablePagination
|
||||
component={() => (
|
||||
<TablePaginationComponent
|
||||
pageIndex={currentPage}
|
||||
pageSize={pageSize}
|
||||
totalCount={totalCount}
|
||||
onPageChange={handlePageChange}
|
||||
/>
|
||||
)}
|
||||
count={totalCount}
|
||||
rowsPerPage={pageSize}
|
||||
page={currentPage}
|
||||
onPageChange={handlePageChange}
|
||||
onRowsPerPageChange={handlePageSizeChange}
|
||||
rowsPerPageOptions={[10, 25, 50]}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</Card>
|
||||
<AddEditCampaignDrawer open={addCampaignOpen} handleClose={handleCloseCampaignDrawer} data={editCampaignData} />
|
||||
<DeleteCampaignDialog
|
||||
open={deleteCampaignOpen}
|
||||
onClose={handleCloseDeleteDialog}
|
||||
onConfirm={handleConfirmDelete}
|
||||
campaign={campaignToDelete}
|
||||
isDeleting={deleteCampaign?.isPending || false}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default CampaignListTable
|
||||
@@ -0,0 +1,157 @@
|
||||
// React Imports
|
||||
import { useState } from 'react'
|
||||
|
||||
// MUI Imports
|
||||
import Dialog from '@mui/material/Dialog'
|
||||
import DialogTitle from '@mui/material/DialogTitle'
|
||||
import DialogContent from '@mui/material/DialogContent'
|
||||
import DialogActions from '@mui/material/DialogActions'
|
||||
import DialogContentText from '@mui/material/DialogContentText'
|
||||
import Button from '@mui/material/Button'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import Box from '@mui/material/Box'
|
||||
import Alert from '@mui/material/Alert'
|
||||
import Chip from '@mui/material/Chip'
|
||||
|
||||
// Types
|
||||
import { Campaign } from '@/types/services/campaign'
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onConfirm: () => void
|
||||
campaign: Campaign | null
|
||||
isDeleting?: boolean
|
||||
}
|
||||
|
||||
const DeleteCampaignDialog = ({ open, onClose, onConfirm, campaign, isDeleting = false }: Props) => {
|
||||
if (!campaign) return null
|
||||
|
||||
const getCampaignTypeColor = (type: string) => {
|
||||
switch (type) {
|
||||
case 'POINTS':
|
||||
return 'primary'
|
||||
case 'TOKENS':
|
||||
return 'success'
|
||||
case 'REWARD':
|
||||
return 'warning'
|
||||
case 'MIXED':
|
||||
return 'info'
|
||||
default:
|
||||
return 'secondary'
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
maxWidth='sm'
|
||||
fullWidth
|
||||
aria-labelledby='delete-dialog-title'
|
||||
aria-describedby='delete-dialog-description'
|
||||
>
|
||||
<DialogTitle id='delete-dialog-title'>
|
||||
<Box display='flex' alignItems='center' gap={2}>
|
||||
<i className='tabler-trash text-red-500 text-2xl' />
|
||||
<Typography variant='h6'>Hapus Kampanye</Typography>
|
||||
</Box>
|
||||
</DialogTitle>
|
||||
|
||||
<DialogContent>
|
||||
<DialogContentText id='delete-dialog-description' className='mb-4'>
|
||||
Apakah Anda yakin ingin menghapus kampanye berikut?
|
||||
</DialogContentText>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
backgroundColor: 'grey.50',
|
||||
p: 2,
|
||||
borderRadius: 1,
|
||||
border: '1px solid',
|
||||
borderColor: 'grey.200',
|
||||
mb: 2
|
||||
}}
|
||||
>
|
||||
<Box display='flex' alignItems='center' gap={2} className='mb-2'>
|
||||
<Typography variant='subtitle2' className='font-medium'>
|
||||
{campaign.name}
|
||||
</Typography>
|
||||
<Chip label={campaign.type} color={getCampaignTypeColor(campaign.type)} variant='tonal' size='small' />
|
||||
</Box>
|
||||
|
||||
{campaign.description && (
|
||||
<Typography variant='body2' color='text.secondary' className='mb-2'>
|
||||
{campaign.description}
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
<Box display='flex' flexDirection='column' gap={1}>
|
||||
<Typography variant='body2' color='text.secondary'>
|
||||
Periode:{' '}
|
||||
{new Date(campaign.start_date).toLocaleDateString('id-ID', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
})}{' '}
|
||||
-{' '}
|
||||
{new Date(campaign.end_date).toLocaleDateString('id-ID', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
})}
|
||||
</Typography>
|
||||
|
||||
<Typography variant='body2' color='text.secondary'>
|
||||
Status: {campaign.is_active ? 'Aktif' : 'Tidak Aktif'}
|
||||
{campaign.show_on_app && ' • Tampil di App'}
|
||||
</Typography>
|
||||
|
||||
<Typography variant='body2' color='text.secondary'>
|
||||
Dibuat:{' '}
|
||||
{new Date(campaign.created_at).toLocaleDateString('id-ID', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric'
|
||||
})}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Alert severity='warning' sx={{ mb: 2 }}>
|
||||
<Typography variant='body2'>
|
||||
<strong>Peringatan:</strong> Tindakan ini tidak dapat dibatalkan. Semua data yang terkait dengan kampanye
|
||||
ini akan dihapus secara permanen, termasuk:
|
||||
</Typography>
|
||||
<Box component='ul' sx={{ mt: 1, mb: 0, pl: 2 }}>
|
||||
<li>Aturan kampanye (rules)</li>
|
||||
<li>Riwayat penggunaan kampanye</li>
|
||||
<li>Data analitik kampanye</li>
|
||||
</Box>
|
||||
</Alert>
|
||||
|
||||
<DialogContentText>
|
||||
Pastikan tidak ada pengguna yang masih menggunakan kampanye ini dan tidak ada transaksi yang sedang berjalan
|
||||
sebelum menghapus.
|
||||
</DialogContentText>
|
||||
</DialogContent>
|
||||
|
||||
<DialogActions className='p-4'>
|
||||
<Button onClick={onClose} variant='outlined' disabled={isDeleting}>
|
||||
Batal
|
||||
</Button>
|
||||
<Button
|
||||
onClick={onConfirm}
|
||||
color='error'
|
||||
variant='contained'
|
||||
disabled={isDeleting}
|
||||
startIcon={isDeleting ? <i className='tabler-loader animate-spin' /> : <i className='tabler-trash' />}
|
||||
>
|
||||
{isDeleting ? 'Menghapus...' : 'Hapus'}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export default DeleteCampaignDialog
|
||||
@@ -0,0 +1,417 @@
|
||||
// React Imports
|
||||
import { useState, useEffect } from 'react'
|
||||
|
||||
// MUI Imports
|
||||
import Button from '@mui/material/Button'
|
||||
import Drawer from '@mui/material/Drawer'
|
||||
import IconButton from '@mui/material/IconButton'
|
||||
import MenuItem from '@mui/material/MenuItem'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import Box from '@mui/material/Box'
|
||||
|
||||
// Third-party Imports
|
||||
import { useForm, Controller } from 'react-hook-form'
|
||||
|
||||
// Component Imports
|
||||
import CustomTextField from '@core/components/mui/TextField'
|
||||
|
||||
// Types
|
||||
import { CampaignRule, RuleType, RewardType, CampaignRuleRequest } from '@/types/services/campaign'
|
||||
import { useCampaignRulesMutation } from '@/services/mutations/campaign'
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
handleClose: () => void
|
||||
campaignId: string // Required campaign ID
|
||||
data?: CampaignRule | null // Data for edit mode
|
||||
}
|
||||
|
||||
type FormValidateType = {
|
||||
rule_type: RuleType
|
||||
condition_value: string
|
||||
reward_type: RewardType
|
||||
reward_value: number
|
||||
reward_subtype: string
|
||||
reward_ref_id: string
|
||||
}
|
||||
|
||||
// Initial form data
|
||||
const initialData: FormValidateType = {
|
||||
rule_type: 'SPEND',
|
||||
condition_value: '',
|
||||
reward_type: 'POINTS',
|
||||
reward_value: 0,
|
||||
reward_subtype: '',
|
||||
reward_ref_id: ''
|
||||
}
|
||||
|
||||
const AddEditCampaignRuleDrawer = (props: Props) => {
|
||||
// Props
|
||||
const { open, handleClose, campaignId, data } = props
|
||||
|
||||
// States
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
|
||||
const { createCampaignRule, updateCampaignRule } = useCampaignRulesMutation()
|
||||
|
||||
// Determine if this is edit mode
|
||||
const isEditMode = Boolean(data?.id)
|
||||
|
||||
// Hooks
|
||||
const {
|
||||
control,
|
||||
reset: resetForm,
|
||||
handleSubmit,
|
||||
watch,
|
||||
formState: { errors }
|
||||
} = useForm<FormValidateType>({
|
||||
defaultValues: initialData
|
||||
})
|
||||
|
||||
const watchedRewardType = watch('reward_type')
|
||||
|
||||
// Effect to populate form when editing
|
||||
useEffect(() => {
|
||||
if (isEditMode && data) {
|
||||
const formData: FormValidateType = {
|
||||
rule_type: data.rule_type,
|
||||
condition_value: data.condition_value || '',
|
||||
reward_type: data.reward_type,
|
||||
reward_value: data.reward_value || 0,
|
||||
reward_subtype: data.reward_subtype || '',
|
||||
reward_ref_id: data.reward_ref_id || ''
|
||||
}
|
||||
|
||||
resetForm(formData)
|
||||
} else {
|
||||
// Reset to initial data for add mode
|
||||
resetForm(initialData)
|
||||
}
|
||||
}, [data, isEditMode, resetForm])
|
||||
|
||||
const handleFormSubmit = async (formData: FormValidateType) => {
|
||||
try {
|
||||
setIsSubmitting(true)
|
||||
|
||||
// Create CampaignRuleRequest object
|
||||
const ruleRequest: CampaignRuleRequest = {
|
||||
campaign_id: campaignId,
|
||||
rule_type: formData.rule_type,
|
||||
condition_value: formData.condition_value.trim() || undefined,
|
||||
reward_type: formData.reward_type,
|
||||
reward_value: formData.reward_value > 0 ? formData.reward_value : undefined,
|
||||
reward_subtype: formData.reward_subtype.trim() || undefined,
|
||||
reward_ref_id: formData.reward_ref_id.trim() || undefined
|
||||
}
|
||||
|
||||
if (isEditMode && data?.id) {
|
||||
// Update existing campaign rule
|
||||
updateCampaignRule.mutate(
|
||||
{ id: data.id, payload: ruleRequest },
|
||||
{
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
handleClose()
|
||||
},
|
||||
onError: error => {
|
||||
console.error('Error updating campaign rule:', error)
|
||||
}
|
||||
}
|
||||
)
|
||||
} else {
|
||||
// Create new campaign rule
|
||||
createCampaignRule.mutate(ruleRequest, {
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
handleClose()
|
||||
},
|
||||
onError: error => {
|
||||
console.error('Error creating campaign rule:', error)
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error submitting campaign rule:', error)
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleReset = () => {
|
||||
handleClose()
|
||||
resetForm(initialData)
|
||||
}
|
||||
|
||||
// Helper function to get rule type options
|
||||
const getRuleTypeOptions = () => [
|
||||
{ value: 'TIER', label: 'Tier Based', icon: 'tabler-medal' },
|
||||
{ value: 'SPEND', label: 'Spending Amount', icon: 'tabler-wallet' },
|
||||
{ value: 'PRODUCT', label: 'Product Based', icon: 'tabler-package' },
|
||||
{ value: 'CATEGORY', label: 'Category Based', icon: 'tabler-category' },
|
||||
{ value: 'DAY', label: 'Day Based', icon: 'tabler-calendar' },
|
||||
{ value: 'LOCATION', label: 'Location Based', icon: 'tabler-map-pin' }
|
||||
]
|
||||
|
||||
// Helper function to get reward type options
|
||||
const getRewardTypeOptions = () => [
|
||||
{ value: 'POINTS', label: 'Points', icon: 'tabler-coins' },
|
||||
{ value: 'TOKENS', label: 'Tokens', icon: 'tabler-ticket' },
|
||||
{ value: 'REWARD', label: 'Reward Item', icon: 'tabler-gift' }
|
||||
]
|
||||
|
||||
// Helper function to get condition placeholder based on rule type
|
||||
const getConditionPlaceholder = (ruleType: RuleType) => {
|
||||
switch (ruleType) {
|
||||
case 'TIER':
|
||||
return 'e.g., GOLD, SILVER, BRONZE'
|
||||
case 'SPEND':
|
||||
return 'e.g., 100000 (minimum spend amount)'
|
||||
case 'PRODUCT':
|
||||
return 'e.g., product_id_123'
|
||||
case 'CATEGORY':
|
||||
return 'e.g., electronics, fashion'
|
||||
case 'DAY':
|
||||
return 'e.g., monday, weekend'
|
||||
case 'LOCATION':
|
||||
return 'e.g., jakarta, bandung'
|
||||
default:
|
||||
return 'Enter condition value'
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to get reward subtype options based on reward type
|
||||
const getRewardSubtypeOptions = (rewardType: RewardType) => {
|
||||
switch (rewardType) {
|
||||
case 'POINTS':
|
||||
return ['bonus', 'cashback', 'referral']
|
||||
case 'TOKENS':
|
||||
return ['game', 'lottery', 'voucher']
|
||||
case 'REWARD':
|
||||
return ['product', 'discount', 'currency', 'experience']
|
||||
default:
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
open={open}
|
||||
anchor='right'
|
||||
variant='temporary'
|
||||
onClose={handleReset}
|
||||
ModalProps={{ keepMounted: true }}
|
||||
sx={{
|
||||
'& .MuiDrawer-paper': {
|
||||
width: { xs: 300, sm: 400 },
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
height: '100%'
|
||||
}
|
||||
}}
|
||||
>
|
||||
{/* Sticky Header */}
|
||||
<Box
|
||||
sx={{
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
zIndex: 10,
|
||||
backgroundColor: 'background.paper',
|
||||
borderBottom: 1,
|
||||
borderColor: 'divider'
|
||||
}}
|
||||
>
|
||||
<div className='flex items-center justify-between plb-5 pli-6'>
|
||||
<Typography variant='h5'>{isEditMode ? 'Edit Campaign Rule' : 'Add New Campaign Rule'}</Typography>
|
||||
<IconButton size='small' onClick={handleReset}>
|
||||
<i className='tabler-x text-2xl text-textPrimary' />
|
||||
</IconButton>
|
||||
</div>
|
||||
</Box>
|
||||
|
||||
{/* Scrollable Content */}
|
||||
<Box sx={{ flex: 1, overflowY: 'auto' }}>
|
||||
<form id='campaign-rule-form' onSubmit={handleSubmit(handleFormSubmit)}>
|
||||
<div className='flex flex-col gap-6 p-6'>
|
||||
{/* Rule Type */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Rule Type <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='rule_type'
|
||||
control={control}
|
||||
rules={{ required: 'Rule type is required' }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
select
|
||||
fullWidth
|
||||
error={!!errors.rule_type}
|
||||
helperText={errors.rule_type?.message}
|
||||
>
|
||||
{getRuleTypeOptions().map(option => (
|
||||
<MenuItem key={option.value} value={option.value}>
|
||||
<div className='flex items-center gap-2'>
|
||||
<i className={`${option.icon} text-primary`} />
|
||||
{option.label}
|
||||
</div>
|
||||
</MenuItem>
|
||||
))}
|
||||
</CustomTextField>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Condition Value */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Condition Value
|
||||
</Typography>
|
||||
<Controller
|
||||
name='condition_value'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder={getConditionPlaceholder(watch('rule_type'))}
|
||||
error={!!errors.condition_value}
|
||||
helperText={errors.condition_value?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Reward Type */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Reward Type <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='reward_type'
|
||||
control={control}
|
||||
rules={{ required: 'Reward type is required' }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
select
|
||||
fullWidth
|
||||
error={!!errors.reward_type}
|
||||
helperText={errors.reward_type?.message}
|
||||
>
|
||||
{getRewardTypeOptions().map(option => (
|
||||
<MenuItem key={option.value} value={option.value}>
|
||||
<div className='flex items-center gap-2'>
|
||||
<i className={`${option.icon} text-primary`} />
|
||||
{option.label}
|
||||
</div>
|
||||
</MenuItem>
|
||||
))}
|
||||
</CustomTextField>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Reward Value */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Reward Value
|
||||
</Typography>
|
||||
<Controller
|
||||
name='reward_value'
|
||||
control={control}
|
||||
rules={{
|
||||
min: { value: 1, message: 'Reward value must be at least 1' }
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='number'
|
||||
placeholder={`Enter ${watchedRewardType.toLowerCase()} amount`}
|
||||
error={!!errors.reward_value}
|
||||
helperText={errors.reward_value?.message}
|
||||
onChange={e => field.onChange(Number(e.target.value))}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Reward Subtype */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Reward Subtype
|
||||
</Typography>
|
||||
<Controller
|
||||
name='reward_subtype'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
select
|
||||
fullWidth
|
||||
error={!!errors.reward_subtype}
|
||||
helperText={errors.reward_subtype?.message}
|
||||
>
|
||||
<MenuItem value=''>
|
||||
<em>None</em>
|
||||
</MenuItem>
|
||||
{getRewardSubtypeOptions(watchedRewardType).map(subtype => (
|
||||
<MenuItem key={subtype} value={subtype}>
|
||||
{subtype.charAt(0).toUpperCase() + subtype.slice(1)}
|
||||
</MenuItem>
|
||||
))}
|
||||
</CustomTextField>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Reward Reference ID */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Reward Reference ID
|
||||
</Typography>
|
||||
<Controller
|
||||
name='reward_ref_id'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='e.g., product_id, voucher_id (optional)'
|
||||
error={!!errors.reward_ref_id}
|
||||
helperText={errors.reward_ref_id?.message || 'Optional reference to specific reward item'}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</Box>
|
||||
|
||||
{/* Sticky Footer */}
|
||||
<Box
|
||||
sx={{
|
||||
position: 'sticky',
|
||||
bottom: 0,
|
||||
zIndex: 10,
|
||||
backgroundColor: 'background.paper',
|
||||
borderTop: 1,
|
||||
borderColor: 'divider',
|
||||
p: 3
|
||||
}}
|
||||
>
|
||||
<div className='flex items-center gap-4'>
|
||||
<Button variant='contained' type='submit' form='campaign-rule-form' disabled={isSubmitting}>
|
||||
{isSubmitting ? (isEditMode ? 'Updating...' : 'Creating...') : isEditMode ? 'Update Rule' : 'Create Rule'}
|
||||
</Button>
|
||||
<Button variant='outlined' color='error' onClick={handleReset} disabled={isSubmitting}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</Box>
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
|
||||
export default AddEditCampaignRuleDrawer
|
||||
@@ -0,0 +1,401 @@
|
||||
'use client'
|
||||
|
||||
import Loading from '@/components/layout/shared/Loading'
|
||||
import { useCampaignById, useCampaignRulesByCampaignId } from '@/services/queries/campaign'
|
||||
import { CampaignRule, RewardType, RuleType } from '@/types/services/campaign'
|
||||
import { formatCurrency } from '@/utils/transform'
|
||||
import {
|
||||
Avatar,
|
||||
Card,
|
||||
CardHeader,
|
||||
CardContent,
|
||||
Chip,
|
||||
Typography,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableRow,
|
||||
Paper,
|
||||
Box,
|
||||
Divider,
|
||||
Button,
|
||||
IconButton,
|
||||
Tooltip,
|
||||
Dialog,
|
||||
DialogTitle,
|
||||
DialogContent,
|
||||
DialogActions,
|
||||
DialogContentText
|
||||
} from '@mui/material'
|
||||
// Using Tabler icons instead of Material-UI icons
|
||||
import { useParams } from 'next/navigation'
|
||||
import { useState } from 'react'
|
||||
|
||||
const CampaignDetailContent = () => {
|
||||
const params = useParams()
|
||||
|
||||
// State for dialogs
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
|
||||
const [selectedRuleId, setSelectedRuleId] = useState<string | null>(null)
|
||||
const [selectedRule, setSelectedRule] = useState<CampaignRule | null>(null)
|
||||
|
||||
const { data: campaign, isLoading, error } = useCampaignById(params?.id as string)
|
||||
const { data: rules, isLoading: rulesLoading, error: rulesError } = useCampaignRulesByCampaignId(params?.id as string)
|
||||
|
||||
if (isLoading) return <Loading />
|
||||
|
||||
// Action handlers
|
||||
const handleAddRule = () => {
|
||||
// TODO: Implement add rule functionality
|
||||
// Could open a modal/form or navigate to add rule page
|
||||
console.log('Add new rule for campaign:', params?.id)
|
||||
}
|
||||
|
||||
const handleEditRule = (rule: CampaignRule) => {
|
||||
// TODO: Implement edit rule functionality
|
||||
// Could open a modal/form or navigate to edit rule page
|
||||
console.log('Edit rule:', rule.id)
|
||||
setSelectedRule(rule)
|
||||
// You might want to open an edit modal here
|
||||
}
|
||||
|
||||
const handleDeleteRule = (rule: CampaignRule) => {
|
||||
setSelectedRule(rule)
|
||||
setSelectedRuleId(rule.id)
|
||||
setDeleteDialogOpen(true)
|
||||
}
|
||||
|
||||
const confirmDeleteRule = async () => {
|
||||
if (selectedRuleId) {
|
||||
try {
|
||||
// TODO: Implement actual delete API call
|
||||
console.log('Deleting rule:', selectedRuleId)
|
||||
// await deleteRuleMutation.mutateAsync(selectedRuleId)
|
||||
|
||||
// Close dialog and reset state
|
||||
setDeleteDialogOpen(false)
|
||||
setSelectedRuleId(null)
|
||||
setSelectedRule(null)
|
||||
|
||||
// Show success message or refresh data
|
||||
} catch (error) {
|
||||
console.error('Failed to delete rule:', error)
|
||||
// Handle error (show toast, etc.)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const cancelDelete = () => {
|
||||
setDeleteDialogOpen(false)
|
||||
setSelectedRuleId(null)
|
||||
setSelectedRule(null)
|
||||
}
|
||||
|
||||
// Helper function to format rule type display
|
||||
const formatRuleType = (ruleType: RuleType) => {
|
||||
const ruleTypeLabels: Record<RuleType, string> = {
|
||||
TIER: 'Tier Based',
|
||||
SPEND: 'Spending Amount',
|
||||
PRODUCT: 'Product Based',
|
||||
CATEGORY: 'Category Based',
|
||||
DAY: 'Day Based',
|
||||
LOCATION: 'Location Based'
|
||||
}
|
||||
return ruleTypeLabels[ruleType] || ruleType
|
||||
}
|
||||
|
||||
// Helper function to get rule type color
|
||||
const getRuleTypeColor = (ruleType: RuleType): 'primary' | 'secondary' | 'success' | 'warning' | 'info' => {
|
||||
const colorMap: Record<RuleType, 'primary' | 'secondary' | 'success' | 'warning' | 'info'> = {
|
||||
TIER: 'primary',
|
||||
SPEND: 'success',
|
||||
PRODUCT: 'info',
|
||||
CATEGORY: 'warning',
|
||||
DAY: 'secondary',
|
||||
LOCATION: 'primary'
|
||||
}
|
||||
return colorMap[ruleType] || 'primary'
|
||||
}
|
||||
|
||||
// Helper function to format reward type display
|
||||
const formatRewardType = (rewardType: RewardType) => {
|
||||
const rewardTypeLabels: Record<RewardType, string> = {
|
||||
POINTS: 'Points',
|
||||
TOKENS: 'Tokens',
|
||||
REWARD: 'Reward Item'
|
||||
}
|
||||
return rewardTypeLabels[rewardType] || rewardType
|
||||
}
|
||||
|
||||
// Helper function to get reward type color
|
||||
const getRewardTypeColor = (rewardType: RewardType): 'primary' | 'secondary' | 'success' => {
|
||||
const colorMap: Record<RewardType, 'primary' | 'secondary' | 'success'> = {
|
||||
POINTS: 'success',
|
||||
TOKENS: 'primary',
|
||||
REWARD: 'secondary'
|
||||
}
|
||||
return colorMap[rewardType] || 'primary'
|
||||
}
|
||||
|
||||
// Helper function to format reward value
|
||||
const formatRewardValue = (rewardValue?: number, rewardType?: RewardType, rewardSubtype?: string) => {
|
||||
if (!rewardValue) return '-'
|
||||
|
||||
// Format based on reward type
|
||||
switch (rewardType) {
|
||||
case 'POINTS':
|
||||
return `${rewardValue.toLocaleString()} pts`
|
||||
case 'TOKENS':
|
||||
return `${rewardValue.toLocaleString()} tokens`
|
||||
case 'REWARD':
|
||||
// For reward items, check if it's currency-based
|
||||
if (rewardSubtype === 'currency') {
|
||||
return formatCurrency(rewardValue)
|
||||
}
|
||||
return rewardValue.toString()
|
||||
default:
|
||||
return rewardValue.toString()
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to format date
|
||||
const formatDate = (dateString: string) => {
|
||||
return new Date(dateString).toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='space-y-6'>
|
||||
{/* Header Card */}
|
||||
<Card>
|
||||
<CardHeader
|
||||
avatar={<Avatar src={campaign?.metadata?.banner_url || ''} alt={campaign?.name} className='w-16 h-16' />}
|
||||
title={
|
||||
<div className='flex items-center gap-3'>
|
||||
<Typography variant='h4' component='h1' className='font-bold'>
|
||||
{campaign?.name} ({campaign?.type})
|
||||
</Typography>
|
||||
|
||||
<Chip
|
||||
label={campaign?.is_active ? 'Active' : 'Inactive'}
|
||||
color={campaign?.is_active ? 'success' : 'error'}
|
||||
size='small'
|
||||
/>
|
||||
<Chip
|
||||
label={campaign?.show_on_app ? 'Show on App' : 'Hide on App'}
|
||||
color={campaign?.show_on_app ? 'info' : 'error'}
|
||||
size='small'
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
subheader={
|
||||
<div className='flex flex-col gap-1 mt-2'>
|
||||
<Typography variant='body2' color='textSecondary'>
|
||||
{campaign?.start_date} - {campaign?.end_date}
|
||||
</Typography>
|
||||
<Typography variant='body2' color='textSecondary'>
|
||||
{campaign?.description}
|
||||
</Typography>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{/* Campaign Rules Table */}
|
||||
<Card>
|
||||
<CardHeader
|
||||
title={
|
||||
<div className='flex items-center justify-between'>
|
||||
<div>
|
||||
<Typography variant='h5' component='h2' className='font-semibold'>
|
||||
Campaign Rules
|
||||
</Typography>
|
||||
{rules && rules.length > 0 && (
|
||||
<Chip
|
||||
label={`${rules.length} rule${rules.length !== 1 ? 's' : ''}`}
|
||||
size='small'
|
||||
variant='outlined'
|
||||
className='mt-1'
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
variant='contained'
|
||||
startIcon={<i className='tabler-plus' />}
|
||||
onClick={handleAddRule}
|
||||
size='small'
|
||||
>
|
||||
Add Rule
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
subheader={
|
||||
<Typography variant='body2' color='textSecondary'>
|
||||
Rules and rewards configuration for this campaign
|
||||
</Typography>
|
||||
}
|
||||
/>
|
||||
<Divider />
|
||||
<CardContent className='p-0'>
|
||||
{rulesLoading ? (
|
||||
<Box className='p-8 text-center'>
|
||||
<Loading />
|
||||
</Box>
|
||||
) : rulesError ? (
|
||||
<Box className='p-8 text-center'>
|
||||
<Typography variant='body1' color='error'>
|
||||
Failed to load campaign rules
|
||||
</Typography>
|
||||
<Typography variant='body2' color='textSecondary' className='mt-1'>
|
||||
{rulesError.message || 'Please try refreshing the page'}
|
||||
</Typography>
|
||||
</Box>
|
||||
) : rules && rules.length > 0 ? (
|
||||
<TableContainer component={Paper} elevation={0}>
|
||||
<Table>
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Rule Type</TableCell>
|
||||
<TableCell>Condition</TableCell>
|
||||
<TableCell>Reward Type</TableCell>
|
||||
<TableCell>Reward Value</TableCell>
|
||||
<TableCell>Subtype</TableCell>
|
||||
<TableCell>Created</TableCell>
|
||||
<TableCell>Updated</TableCell>
|
||||
<TableCell align='center' width={120}>
|
||||
Actions
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{rules.map((rule: CampaignRule) => (
|
||||
<TableRow key={rule.id} hover>
|
||||
<TableCell>
|
||||
<Chip
|
||||
label={formatRuleType(rule.rule_type)}
|
||||
variant='outlined'
|
||||
size='small'
|
||||
color={getRuleTypeColor(rule.rule_type)}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Typography variant='body2'>{rule.condition_value || '-'}</Typography>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Chip
|
||||
label={formatRewardType(rule.reward_type)}
|
||||
variant='outlined'
|
||||
size='small'
|
||||
color={getRewardTypeColor(rule.reward_type)}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Typography variant='body2' className='font-medium'>
|
||||
{formatRewardValue(rule.reward_value, rule.reward_type, rule.reward_subtype)}
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{rule.reward_subtype && (
|
||||
<Chip label={rule.reward_subtype} variant='outlined' size='small' color='default' />
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Typography variant='caption' color='textSecondary'>
|
||||
{formatDate(rule.created_at)}
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Typography variant='caption' color='textSecondary'>
|
||||
{formatDate(rule.updated_at)}
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell align='center'>
|
||||
<Box className='flex items-center gap-1'>
|
||||
<Tooltip title='Edit rule'>
|
||||
<IconButton size='small' onClick={() => handleEditRule(rule)} color='primary'>
|
||||
<i className='tabler-edit' />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<Tooltip title='Delete rule'>
|
||||
<IconButton size='small' onClick={() => handleDeleteRule(rule)} color='error'>
|
||||
<i className='tabler-trash' />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
</Box>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
) : (
|
||||
<Box className='p-8 text-center'>
|
||||
<Typography variant='body1' color='textSecondary'>
|
||||
No rules configured for this campaign
|
||||
</Typography>
|
||||
<Typography variant='body2' color='textSecondary' className='mt-1'>
|
||||
Add rules to define how rewards are distributed
|
||||
</Typography>
|
||||
<Button
|
||||
variant='outlined'
|
||||
startIcon={<i className='tabler-plus' />}
|
||||
onClick={handleAddRule}
|
||||
className='mt-4'
|
||||
>
|
||||
Add First Rule
|
||||
</Button>
|
||||
</Box>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Delete Confirmation Dialog */}
|
||||
<Dialog
|
||||
open={deleteDialogOpen}
|
||||
onClose={cancelDelete}
|
||||
aria-labelledby='delete-rule-dialog-title'
|
||||
aria-describedby='delete-rule-dialog-description'
|
||||
>
|
||||
<DialogTitle id='delete-rule-dialog-title'>Confirm Delete Rule</DialogTitle>
|
||||
<DialogContent>
|
||||
<DialogContentText id='delete-rule-dialog-description'>
|
||||
Are you sure you want to delete this rule? This action cannot be undone.
|
||||
{selectedRule && (
|
||||
<Box className='mt-3 p-3 bg-gray-50 rounded'>
|
||||
<Typography variant='body2' className='font-medium'>
|
||||
Rule Details:
|
||||
</Typography>
|
||||
<Typography variant='caption' display='block'>
|
||||
Type: {formatRuleType(selectedRule.rule_type)}
|
||||
</Typography>
|
||||
<Typography variant='caption' display='block'>
|
||||
Reward:{' '}
|
||||
{formatRewardValue(selectedRule.reward_value, selectedRule.reward_type, selectedRule.reward_subtype)}
|
||||
</Typography>
|
||||
</Box>
|
||||
)}
|
||||
</DialogContentText>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={cancelDelete} color='primary'>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={confirmDeleteRule} color='error' variant='contained'>
|
||||
Delete
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default CampaignDetailContent
|
||||
@@ -0,0 +1,17 @@
|
||||
// MUI Imports
|
||||
import Grid from '@mui/material/Grid2'
|
||||
import LoyaltyListTable from './CampaignListTable'
|
||||
|
||||
// Type Imports
|
||||
|
||||
const LoyaltyList = () => {
|
||||
return (
|
||||
<Grid container spacing={6}>
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<LoyaltyListTable />
|
||||
</Grid>
|
||||
</Grid>
|
||||
)
|
||||
}
|
||||
|
||||
export default LoyaltyList
|
||||
@@ -0,0 +1,593 @@
|
||||
'use client'
|
||||
|
||||
// React Imports
|
||||
import { useEffect, useState, useMemo, useCallback } from 'react'
|
||||
|
||||
// Next Imports
|
||||
import Link from 'next/link'
|
||||
import { useParams } from 'next/navigation'
|
||||
|
||||
// MUI Imports
|
||||
import Card from '@mui/material/Card'
|
||||
import CardHeader from '@mui/material/CardHeader'
|
||||
import Button from '@mui/material/Button'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import Chip from '@mui/material/Chip'
|
||||
import Checkbox from '@mui/material/Checkbox'
|
||||
import IconButton from '@mui/material/IconButton'
|
||||
import { styled } from '@mui/material/styles'
|
||||
import TablePagination from '@mui/material/TablePagination'
|
||||
import type { TextFieldProps } from '@mui/material/TextField'
|
||||
import MenuItem from '@mui/material/MenuItem'
|
||||
|
||||
// Third-party Imports
|
||||
import classnames from 'classnames'
|
||||
import { rankItem } from '@tanstack/match-sorter-utils'
|
||||
import {
|
||||
createColumnHelper,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
useReactTable,
|
||||
getFilteredRowModel,
|
||||
getFacetedRowModel,
|
||||
getFacetedUniqueValues,
|
||||
getFacetedMinMaxValues,
|
||||
getPaginationRowModel,
|
||||
getSortedRowModel
|
||||
} from '@tanstack/react-table'
|
||||
import type { ColumnDef, FilterFn } from '@tanstack/react-table'
|
||||
import type { RankingInfo } from '@tanstack/match-sorter-utils'
|
||||
|
||||
// Type Imports
|
||||
import type { ThemeColor } from '@core/types'
|
||||
import type { Locale } from '@configs/i18n'
|
||||
|
||||
// Component Imports
|
||||
import OptionMenu from '@core/components/option-menu'
|
||||
import TablePaginationComponent from '@components/TablePaginationComponent'
|
||||
import CustomTextField from '@core/components/mui/TextField'
|
||||
import CustomAvatar from '@core/components/mui/Avatar'
|
||||
|
||||
// Util Imports
|
||||
import { getInitials } from '@/utils/getInitials'
|
||||
import { getLocalizedUrl } from '@/utils/i18n'
|
||||
import { formatCurrency } from '@/utils/transform'
|
||||
|
||||
// Style Imports
|
||||
import tableStyles from '@core/styles/table.module.css'
|
||||
import Loading from '@/components/layout/shared/Loading'
|
||||
|
||||
// Customer Analytics Interface
|
||||
export interface CustomerAnalytics {
|
||||
id: string
|
||||
name: string
|
||||
email?: string
|
||||
phone?: string
|
||||
totalPoints: number
|
||||
totalSpent?: number
|
||||
loyaltyTier?: string // Bronze, Silver, Gold, dst
|
||||
lastTransactionDate?: Date
|
||||
}
|
||||
|
||||
declare module '@tanstack/table-core' {
|
||||
interface FilterFns {
|
||||
fuzzy: FilterFn<unknown>
|
||||
}
|
||||
interface FilterMeta {
|
||||
itemRank: RankingInfo
|
||||
}
|
||||
}
|
||||
|
||||
type CustomerAnalyticsWithAction = CustomerAnalytics & {
|
||||
action?: string
|
||||
}
|
||||
|
||||
// Styled Components
|
||||
const Icon = styled('i')({})
|
||||
|
||||
const fuzzyFilter: FilterFn<any> = (row, columnId, value, addMeta) => {
|
||||
// Rank the item
|
||||
const itemRank = rankItem(row.getValue(columnId), value)
|
||||
|
||||
// Store the itemRank info
|
||||
addMeta({
|
||||
itemRank
|
||||
})
|
||||
|
||||
// Return if the item should be filtered in/out
|
||||
return itemRank.passed
|
||||
}
|
||||
|
||||
const DebouncedInput = ({
|
||||
value: initialValue,
|
||||
onChange,
|
||||
debounce = 500,
|
||||
...props
|
||||
}: {
|
||||
value: string | number
|
||||
onChange: (value: string | number) => void
|
||||
debounce?: number
|
||||
} & Omit<TextFieldProps, 'onChange'>) => {
|
||||
// States
|
||||
const [value, setValue] = useState(initialValue)
|
||||
|
||||
useEffect(() => {
|
||||
setValue(initialValue)
|
||||
}, [initialValue])
|
||||
|
||||
useEffect(() => {
|
||||
const timeout = setTimeout(() => {
|
||||
onChange(value)
|
||||
}, debounce)
|
||||
|
||||
return () => clearTimeout(timeout)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [value])
|
||||
|
||||
return <CustomTextField {...props} value={value} onChange={e => setValue(e.target.value)} />
|
||||
}
|
||||
|
||||
// Dummy data for customer analytics
|
||||
const DUMMY_CUSTOMER_ANALYTICS_DATA: CustomerAnalytics[] = [
|
||||
{
|
||||
id: '1',
|
||||
name: 'Ahmad Wijaya',
|
||||
email: 'ahmad.wijaya@email.com',
|
||||
phone: '+628123456789',
|
||||
totalPoints: 1250,
|
||||
totalSpent: 5500000,
|
||||
loyaltyTier: 'Gold',
|
||||
lastTransactionDate: new Date('2024-09-10')
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
name: 'Siti Nurhaliza',
|
||||
email: 'siti.nurhaliza@email.com',
|
||||
phone: '+628234567890',
|
||||
totalPoints: 850,
|
||||
totalSpent: 3200000,
|
||||
loyaltyTier: 'Silver',
|
||||
lastTransactionDate: new Date('2024-09-15')
|
||||
},
|
||||
{
|
||||
id: '3',
|
||||
name: 'Budi Santoso',
|
||||
email: 'budi.santoso@email.com',
|
||||
phone: '+628345678901',
|
||||
totalPoints: 2100,
|
||||
totalSpent: 8750000,
|
||||
loyaltyTier: 'Gold',
|
||||
lastTransactionDate: new Date('2024-09-12')
|
||||
},
|
||||
{
|
||||
id: '4',
|
||||
name: 'Maya Puspita',
|
||||
email: 'maya.puspita@email.com',
|
||||
phone: '+628456789012',
|
||||
totalPoints: 450,
|
||||
totalSpent: 1800000,
|
||||
loyaltyTier: 'Bronze',
|
||||
lastTransactionDate: new Date('2024-09-08')
|
||||
},
|
||||
{
|
||||
id: '5',
|
||||
name: 'Rizki Pratama',
|
||||
email: 'rizki.pratama@email.com',
|
||||
phone: '+628567890123',
|
||||
totalPoints: 1680,
|
||||
totalSpent: 6300000,
|
||||
loyaltyTier: 'Gold',
|
||||
lastTransactionDate: new Date('2024-09-16')
|
||||
},
|
||||
{
|
||||
id: '6',
|
||||
name: 'Dewi Lestari',
|
||||
email: 'dewi.lestari@email.com',
|
||||
phone: '+628678901234',
|
||||
totalPoints: 320,
|
||||
totalSpent: 1200000,
|
||||
loyaltyTier: 'Bronze',
|
||||
lastTransactionDate: new Date('2024-09-05')
|
||||
},
|
||||
{
|
||||
id: '7',
|
||||
name: 'Eko Prasetyo',
|
||||
email: 'eko.prasetyo@email.com',
|
||||
phone: '+628789012345',
|
||||
totalPoints: 975,
|
||||
totalSpent: 4100000,
|
||||
loyaltyTier: 'Silver',
|
||||
lastTransactionDate: new Date('2024-09-14')
|
||||
},
|
||||
{
|
||||
id: '8',
|
||||
name: 'Lina Marlina',
|
||||
email: 'lina.marlina@email.com',
|
||||
phone: '+628890123456',
|
||||
totalPoints: 1580,
|
||||
totalSpent: 6800000,
|
||||
loyaltyTier: 'Gold',
|
||||
lastTransactionDate: new Date('2024-09-11')
|
||||
}
|
||||
]
|
||||
|
||||
// Mock data hook with dummy data
|
||||
const useCustomerAnalytics = ({ page, limit, search }: { page: number; limit: number; search: string }) => {
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
// Simulate loading
|
||||
useEffect(() => {
|
||||
setIsLoading(true)
|
||||
const timer = setTimeout(() => setIsLoading(false), 500)
|
||||
return () => clearTimeout(timer)
|
||||
}, [page, limit, search])
|
||||
|
||||
// Filter data based on search
|
||||
const filteredData = useMemo(() => {
|
||||
if (!search) return DUMMY_CUSTOMER_ANALYTICS_DATA
|
||||
|
||||
return DUMMY_CUSTOMER_ANALYTICS_DATA.filter(
|
||||
customer =>
|
||||
customer.name.toLowerCase().includes(search.toLowerCase()) ||
|
||||
customer.email?.toLowerCase().includes(search.toLowerCase()) ||
|
||||
customer.phone?.toLowerCase().includes(search.toLowerCase()) ||
|
||||
customer.loyaltyTier?.toLowerCase().includes(search.toLowerCase())
|
||||
)
|
||||
}, [search])
|
||||
|
||||
// Paginate data
|
||||
const paginatedData = useMemo(() => {
|
||||
const startIndex = (page - 1) * limit
|
||||
const endIndex = startIndex + limit
|
||||
return filteredData.slice(startIndex, endIndex)
|
||||
}, [filteredData, page, limit])
|
||||
|
||||
return {
|
||||
data: {
|
||||
customers: paginatedData,
|
||||
total_count: filteredData.length
|
||||
},
|
||||
isLoading,
|
||||
error: null,
|
||||
isFetching: isLoading
|
||||
}
|
||||
}
|
||||
|
||||
// Utility functions
|
||||
const getLoyaltyTierColor = (loyaltyTier?: string): ThemeColor => {
|
||||
switch (loyaltyTier?.toLowerCase()) {
|
||||
case 'bronze':
|
||||
return 'warning'
|
||||
case 'silver':
|
||||
return 'info'
|
||||
case 'gold':
|
||||
return 'success'
|
||||
default:
|
||||
return 'secondary'
|
||||
}
|
||||
}
|
||||
|
||||
const getLoyaltyTierIcon = (loyaltyTier?: string): string => {
|
||||
switch (loyaltyTier?.toLowerCase()) {
|
||||
case 'bronze':
|
||||
return 'tabler-medal'
|
||||
case 'silver':
|
||||
return 'tabler-medal-2'
|
||||
case 'gold':
|
||||
return 'tabler-crown'
|
||||
default:
|
||||
return 'tabler-user'
|
||||
}
|
||||
}
|
||||
|
||||
// Column Definitions
|
||||
const columnHelper = createColumnHelper<CustomerAnalyticsWithAction>()
|
||||
|
||||
const CustomerAnalyticListTable = () => {
|
||||
// States
|
||||
const [rowSelection, setRowSelection] = useState({})
|
||||
const [globalFilter, setGlobalFilter] = useState('')
|
||||
const [currentPage, setCurrentPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(10)
|
||||
const [search, setSearch] = useState('')
|
||||
|
||||
const { data, isLoading, error, isFetching } = useCustomerAnalytics({
|
||||
page: currentPage,
|
||||
limit: pageSize,
|
||||
search
|
||||
})
|
||||
|
||||
const customers = data?.customers ?? []
|
||||
const totalCount = data?.total_count ?? 0
|
||||
|
||||
// Hooks
|
||||
const { lang: locale } = useParams()
|
||||
|
||||
const handlePageChange = useCallback((event: unknown, newPage: number) => {
|
||||
setCurrentPage(newPage)
|
||||
}, [])
|
||||
|
||||
const handlePageSizeChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newPageSize = parseInt(event.target.value, 10)
|
||||
setPageSize(newPageSize)
|
||||
setCurrentPage(1) // Reset to first page
|
||||
}, [])
|
||||
|
||||
const handleViewCustomer = (customerId: string) => {
|
||||
console.log('Viewing customer:', customerId)
|
||||
// Add your view logic here
|
||||
}
|
||||
|
||||
const handleDeleteCustomer = (customerId: string) => {
|
||||
if (confirm('Apakah Anda yakin ingin menghapus data pelanggan ini?')) {
|
||||
console.log('Deleting customer:', customerId)
|
||||
// Add your delete logic here
|
||||
}
|
||||
}
|
||||
|
||||
const columns = useMemo<ColumnDef<CustomerAnalyticsWithAction, any>[]>(
|
||||
() => [
|
||||
{
|
||||
id: 'select',
|
||||
header: ({ table }) => (
|
||||
<Checkbox
|
||||
{...{
|
||||
checked: table.getIsAllRowsSelected(),
|
||||
indeterminate: table.getIsSomeRowsSelected(),
|
||||
onChange: table.getToggleAllRowsSelectedHandler()
|
||||
}}
|
||||
/>
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<Checkbox
|
||||
{...{
|
||||
checked: row.getIsSelected(),
|
||||
disabled: !row.getCanSelect(),
|
||||
indeterminate: row.getIsSomeSelected(),
|
||||
onChange: row.getToggleSelectedHandler()
|
||||
}}
|
||||
/>
|
||||
)
|
||||
},
|
||||
columnHelper.accessor('name', {
|
||||
header: 'Pelanggan',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-4'>
|
||||
<CustomAvatar size={38}>{getInitials(row.original.name)}</CustomAvatar>
|
||||
<div className='flex flex-col'>
|
||||
<Link href={getLocalizedUrl(`/apps/customers/${row.original.id}/detail`, locale as Locale)}>
|
||||
<Typography className='font-medium cursor-pointer hover:underline text-primary'>
|
||||
{row.original.name}
|
||||
</Typography>
|
||||
</Link>
|
||||
{row.original.email && (
|
||||
<Typography variant='body2' color='text.secondary'>
|
||||
{row.original.email}
|
||||
</Typography>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('phone', {
|
||||
header: 'No. Telepon',
|
||||
cell: ({ row }) => <Typography color='text.primary'>{row.original.phone || '-'}</Typography>
|
||||
}),
|
||||
columnHelper.accessor('totalPoints', {
|
||||
header: 'Total Poin',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-2'>
|
||||
<Icon className='tabler-coins' sx={{ color: 'var(--mui-palette-primary-main)' }} />
|
||||
<Typography color='text.primary' className='font-medium'>
|
||||
{row.original.totalPoints.toLocaleString('id-ID')} Poin
|
||||
</Typography>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('totalSpent', {
|
||||
header: 'Total Belanja',
|
||||
cell: ({ row }) => (
|
||||
<Typography color='text.primary' className='font-medium'>
|
||||
{row.original.totalSpent ? formatCurrency(row.original.totalSpent) : '-'}
|
||||
</Typography>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('loyaltyTier', {
|
||||
header: 'Tier Loyalitas',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-2'>
|
||||
<Icon
|
||||
className={getLoyaltyTierIcon(row.original.loyaltyTier)}
|
||||
sx={{ color: `var(--mui-palette-${getLoyaltyTierColor(row.original.loyaltyTier)}-main)` }}
|
||||
/>
|
||||
<Chip
|
||||
label={row.original.loyaltyTier || 'Belum Ada'}
|
||||
color={getLoyaltyTierColor(row.original.loyaltyTier)}
|
||||
variant='tonal'
|
||||
size='small'
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('lastTransactionDate', {
|
||||
header: 'Transaksi Terakhir',
|
||||
cell: ({ row }) => (
|
||||
<Typography color='text.primary'>
|
||||
{row.original.lastTransactionDate
|
||||
? new Date(row.original.lastTransactionDate).toLocaleDateString('id-ID', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
})
|
||||
: '-'}
|
||||
</Typography>
|
||||
)
|
||||
}),
|
||||
{
|
||||
id: 'actions',
|
||||
header: 'Aksi',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center'>
|
||||
<OptionMenu
|
||||
iconButtonProps={{ size: 'medium' }}
|
||||
iconClassName='text-textSecondary text-[22px]'
|
||||
options={[
|
||||
{
|
||||
text: 'Lihat Detail',
|
||||
icon: 'tabler-eye text-[22px]',
|
||||
menuItemProps: {
|
||||
className: 'flex items-center gap-2 text-textSecondary',
|
||||
onClick: () => handleViewCustomer(row.original.id)
|
||||
}
|
||||
},
|
||||
{
|
||||
text: 'Hapus',
|
||||
icon: 'tabler-trash text-[22px]',
|
||||
menuItemProps: {
|
||||
className: 'flex items-center gap-2 text-textSecondary',
|
||||
onClick: () => handleDeleteCustomer(row.original.id)
|
||||
}
|
||||
}
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
enableSorting: false
|
||||
}
|
||||
],
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[locale, handleViewCustomer, handleDeleteCustomer]
|
||||
)
|
||||
|
||||
const table = useReactTable({
|
||||
data: customers as CustomerAnalytics[],
|
||||
columns,
|
||||
filterFns: {
|
||||
fuzzy: fuzzyFilter
|
||||
},
|
||||
state: {
|
||||
rowSelection,
|
||||
globalFilter,
|
||||
pagination: {
|
||||
pageIndex: currentPage,
|
||||
pageSize
|
||||
}
|
||||
},
|
||||
enableRowSelection: true,
|
||||
onRowSelectionChange: setRowSelection,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
manualPagination: true,
|
||||
pageCount: Math.ceil(totalCount / pageSize)
|
||||
})
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<div className='flex justify-between flex-col items-start md:flex-row md:items-center p-6 border-bs gap-4'>
|
||||
<CustomTextField
|
||||
select
|
||||
value={table.getState().pagination.pageSize}
|
||||
onChange={e => table.setPageSize(Number(e.target.value))}
|
||||
className='max-sm:is-full sm:is-[70px]'
|
||||
>
|
||||
<MenuItem value='10'>10</MenuItem>
|
||||
<MenuItem value='25'>25</MenuItem>
|
||||
<MenuItem value='50'>50</MenuItem>
|
||||
</CustomTextField>
|
||||
<div className='flex flex-col sm:flex-row max-sm:is-full items-start sm:items-center gap-4'>
|
||||
<DebouncedInput
|
||||
value={search ?? ''}
|
||||
onChange={value => setSearch(value as string)}
|
||||
placeholder='Cari Pelanggan'
|
||||
className='max-sm:is-full'
|
||||
/>
|
||||
<Button
|
||||
color='secondary'
|
||||
variant='tonal'
|
||||
startIcon={<i className='tabler-upload' />}
|
||||
className='max-sm:is-full'
|
||||
>
|
||||
Ekspor
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className='overflow-x-auto'>
|
||||
{isLoading ? (
|
||||
<Loading />
|
||||
) : (
|
||||
<table className={tableStyles.table}>
|
||||
<thead>
|
||||
{table.getHeaderGroups().map(headerGroup => (
|
||||
<tr key={headerGroup.id}>
|
||||
{headerGroup.headers.map(header => (
|
||||
<th key={header.id}>
|
||||
{header.isPlaceholder ? null : (
|
||||
<>
|
||||
<div
|
||||
className={classnames({
|
||||
'flex items-center': header.column.getIsSorted(),
|
||||
'cursor-pointer select-none': header.column.getCanSort()
|
||||
})}
|
||||
onClick={header.column.getToggleSortingHandler()}
|
||||
>
|
||||
{flexRender(header.column.columnDef.header, header.getContext())}
|
||||
{{
|
||||
asc: <i className='tabler-chevron-up text-xl' />,
|
||||
desc: <i className='tabler-chevron-down text-xl' />
|
||||
}[header.column.getIsSorted() as 'asc' | 'desc'] ?? null}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
{table.getFilteredRowModel().rows.length === 0 ? (
|
||||
<tbody>
|
||||
<tr>
|
||||
<td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
|
||||
Tidak ada data tersedia
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
) : (
|
||||
<tbody>
|
||||
{table
|
||||
.getRowModel()
|
||||
.rows.slice(0, table.getState().pagination.pageSize)
|
||||
.map(row => {
|
||||
return (
|
||||
<tr key={row.id} className={classnames({ selected: row.getIsSelected() })}>
|
||||
{row.getVisibleCells().map(cell => (
|
||||
<td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
|
||||
))}
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
)}
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
<TablePagination
|
||||
component={() => (
|
||||
<TablePaginationComponent
|
||||
pageIndex={currentPage}
|
||||
pageSize={pageSize}
|
||||
totalCount={totalCount}
|
||||
onPageChange={handlePageChange}
|
||||
/>
|
||||
)}
|
||||
count={totalCount}
|
||||
rowsPerPage={pageSize}
|
||||
page={currentPage}
|
||||
onPageChange={handlePageChange}
|
||||
onRowsPerPageChange={handlePageSizeChange}
|
||||
rowsPerPageOptions={[10, 25, 50]}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
export default CustomerAnalyticListTable
|
||||
@@ -0,0 +1,17 @@
|
||||
// MUI Imports
|
||||
import Grid from '@mui/material/Grid2'
|
||||
import CustomerAnalyticListTable from './CustomerAnalyticListTable'
|
||||
|
||||
// Type Imports
|
||||
|
||||
const CustomerAnalyticList = () => {
|
||||
return (
|
||||
<Grid container spacing={6}>
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<CustomerAnalyticListTable />
|
||||
</Grid>
|
||||
</Grid>
|
||||
)
|
||||
}
|
||||
|
||||
export default CustomerAnalyticList
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,430 @@
|
||||
// React Imports
|
||||
import { useState, useEffect } from 'react'
|
||||
|
||||
// MUI Imports
|
||||
import Button from '@mui/material/Button'
|
||||
import Drawer from '@mui/material/Drawer'
|
||||
import IconButton from '@mui/material/IconButton'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import Box from '@mui/material/Box'
|
||||
import Switch from '@mui/material/Switch'
|
||||
import FormControlLabel from '@mui/material/FormControlLabel'
|
||||
import InputAdornment from '@mui/material/InputAdornment'
|
||||
|
||||
// Third-party Imports
|
||||
import { useForm, Controller } from 'react-hook-form'
|
||||
|
||||
// Component Imports
|
||||
import CustomTextField from '@core/components/mui/TextField'
|
||||
import CustomAutocomplete from '@core/components/mui/Autocomplete'
|
||||
|
||||
// Services
|
||||
import { useGamePrizesMutation } from '@/services/mutations/gamePrize'
|
||||
import { useGames } from '@/services/queries/game'
|
||||
import { GamePrize, GamePrizeRequest } from '@/types/services/gamePrize'
|
||||
import { useGamePrizes } from '@/services/queries/gamePrize'
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
handleClose: () => void
|
||||
data?: GamePrize // GamePrize data for edit (if exists)
|
||||
}
|
||||
|
||||
type FormValidateType = {
|
||||
game_id: string
|
||||
name: string
|
||||
weight: number
|
||||
stock: number
|
||||
max_stock?: number
|
||||
threshold?: number
|
||||
fallback_prize_id?: string
|
||||
}
|
||||
|
||||
// Initial form data
|
||||
const initialData: FormValidateType = {
|
||||
game_id: '',
|
||||
name: '',
|
||||
weight: 1,
|
||||
stock: 0,
|
||||
max_stock: 0,
|
||||
threshold: 0,
|
||||
fallback_prize_id: undefined
|
||||
}
|
||||
|
||||
const AddEditGamePrizeDrawer = (props: Props) => {
|
||||
// Props
|
||||
const { open, handleClose, data } = props
|
||||
|
||||
// States
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
|
||||
// Queries
|
||||
const { data: gamesData } = useGames({ page: 1, limit: 100, search: '' })
|
||||
const { data: gamePrizesData } = useGamePrizes({ page: 1, limit: 100, search: '' })
|
||||
|
||||
// Mutations
|
||||
const { createGamePrize, updateGamePrize } = useGamePrizesMutation()
|
||||
|
||||
// Determine if this is edit mode
|
||||
const isEditMode = Boolean(data?.id)
|
||||
|
||||
// Get available games and fallback prizes
|
||||
const games = gamesData?.data ?? []
|
||||
const availablePrizes = gamePrizesData?.data?.filter(prize => prize.id !== data?.id) ?? []
|
||||
|
||||
// Hooks
|
||||
const {
|
||||
control,
|
||||
reset: resetForm,
|
||||
handleSubmit,
|
||||
watch,
|
||||
formState: { errors }
|
||||
} = useForm<FormValidateType>({
|
||||
defaultValues: initialData
|
||||
})
|
||||
|
||||
const watchedMaxStock = watch('max_stock')
|
||||
|
||||
// Effect to populate form when editing
|
||||
useEffect(() => {
|
||||
if (isEditMode && data) {
|
||||
// Populate form with existing data
|
||||
const formData: FormValidateType = {
|
||||
game_id: data.game_id || '',
|
||||
name: data.name || '',
|
||||
weight: data.weight || 1,
|
||||
stock: data.stock || 0,
|
||||
max_stock: data.max_stock,
|
||||
threshold: data.threshold,
|
||||
fallback_prize_id: data.fallback_prize_id
|
||||
}
|
||||
|
||||
resetForm(formData)
|
||||
} else {
|
||||
// Reset to initial data for add mode
|
||||
resetForm(initialData)
|
||||
}
|
||||
}, [data, isEditMode, resetForm])
|
||||
|
||||
const handleFormSubmit = async (formData: FormValidateType) => {
|
||||
try {
|
||||
setIsSubmitting(true)
|
||||
|
||||
// Create GamePrizeRequest object
|
||||
const gamePrizeRequest: GamePrizeRequest = {
|
||||
game_id: formData.game_id,
|
||||
name: formData.name,
|
||||
weight: typeof formData.weight === 'string' ? parseFloat(formData.weight) : formData.weight || 1,
|
||||
stock: typeof formData.stock === 'string' ? parseInt(formData.stock, 10) : formData.stock || 0,
|
||||
max_stock: formData.max_stock
|
||||
? typeof formData.max_stock === 'string'
|
||||
? parseInt(formData.max_stock, 10)
|
||||
: formData.max_stock
|
||||
: undefined,
|
||||
threshold: formData.threshold
|
||||
? typeof formData.threshold === 'string'
|
||||
? parseInt(formData.threshold, 10)
|
||||
: formData.threshold
|
||||
: undefined,
|
||||
fallback_prize_id: formData.fallback_prize_id || undefined
|
||||
}
|
||||
|
||||
if (isEditMode && data?.id) {
|
||||
// Update existing game prize
|
||||
updateGamePrize.mutate(
|
||||
{ id: data.id, payload: gamePrizeRequest },
|
||||
{
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
handleClose()
|
||||
}
|
||||
}
|
||||
)
|
||||
} else {
|
||||
// Create new game prize
|
||||
createGamePrize.mutate(gamePrizeRequest, {
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
handleClose()
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error submitting game prize:', error)
|
||||
// Handle error (show toast, etc.)
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleReset = () => {
|
||||
handleClose()
|
||||
resetForm(initialData)
|
||||
}
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
open={open}
|
||||
anchor='right'
|
||||
variant='temporary'
|
||||
onClose={handleReset}
|
||||
ModalProps={{ keepMounted: true }}
|
||||
sx={{
|
||||
'& .MuiDrawer-paper': {
|
||||
width: { xs: 350, sm: 450 },
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
height: '100%'
|
||||
}
|
||||
}}
|
||||
>
|
||||
{/* Sticky Header */}
|
||||
<Box
|
||||
sx={{
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
zIndex: 10,
|
||||
backgroundColor: 'background.paper',
|
||||
borderBottom: 1,
|
||||
borderColor: 'divider'
|
||||
}}
|
||||
>
|
||||
<div className='flex items-center justify-between plb-5 pli-6'>
|
||||
<Typography variant='h5'>{isEditMode ? 'Edit Hadiah Game' : 'Tambah Hadiah Game Baru'}</Typography>
|
||||
<IconButton size='small' onClick={handleReset}>
|
||||
<i className='tabler-x text-2xl text-textPrimary' />
|
||||
</IconButton>
|
||||
</div>
|
||||
</Box>
|
||||
|
||||
{/* Scrollable Content */}
|
||||
<Box sx={{ flex: 1, overflowY: 'auto' }}>
|
||||
<form id='game-prize-form' onSubmit={handleSubmit(handleFormSubmit)}>
|
||||
<div className='flex flex-col gap-6 p-6'>
|
||||
{/* Game Selection */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Pilih Game <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='game_id'
|
||||
control={control}
|
||||
rules={{ required: 'Game wajib dipilih' }}
|
||||
render={({ field: { onChange, value, ...field } }) => (
|
||||
<CustomAutocomplete
|
||||
{...field}
|
||||
options={games}
|
||||
getOptionLabel={option => `${option.name} (${option.type})`}
|
||||
value={games.find(game => game.id === value) || null}
|
||||
onChange={(_, newValue) => onChange(newValue?.id || '')}
|
||||
disabled={isEditMode}
|
||||
renderInput={params => (
|
||||
<CustomTextField
|
||||
{...params}
|
||||
placeholder='Pilih game'
|
||||
error={!!errors.game_id}
|
||||
helperText={errors.game_id?.message}
|
||||
/>
|
||||
)}
|
||||
isOptionEqualToValue={(option, value) => option.id === value?.id}
|
||||
noOptionsText='Tidak ada game tersedia'
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Nama Hadiah */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Nama Hadiah <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='name'
|
||||
control={control}
|
||||
rules={{ required: 'Nama hadiah wajib diisi' }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='Masukkan nama hadiah'
|
||||
error={!!errors.name}
|
||||
helperText={errors.name?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Bobot */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Bobot <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='weight'
|
||||
control={control}
|
||||
rules={{
|
||||
required: 'Bobot wajib diisi',
|
||||
min: { value: 1, message: 'Bobot minimal 1' }
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='number'
|
||||
placeholder='Masukkan bobot hadiah'
|
||||
error={!!errors.weight}
|
||||
helperText={errors.weight?.message}
|
||||
InputProps={{
|
||||
endAdornment: <InputAdornment position='end'>%</InputAdornment>
|
||||
}}
|
||||
inputProps={{ min: 1, max: 100 }}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Stock */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Stok <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='stock'
|
||||
control={control}
|
||||
rules={{
|
||||
required: 'Stok wajib diisi',
|
||||
min: { value: 0, message: 'Stok minimal 0' },
|
||||
validate: value => {
|
||||
if (watchedMaxStock && value > watchedMaxStock) {
|
||||
return 'Stok tidak boleh melebihi maksimal stok'
|
||||
}
|
||||
return true
|
||||
}
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='number'
|
||||
placeholder='Masukkan jumlah stok'
|
||||
error={!!errors.stock}
|
||||
helperText={errors.stock?.message}
|
||||
inputProps={{ min: 0 }}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Max Stock */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Maksimal Stok
|
||||
</Typography>
|
||||
<Controller
|
||||
name='max_stock'
|
||||
control={control}
|
||||
rules={{
|
||||
min: { value: 1, message: 'Maksimal stok minimal 1' }
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='number'
|
||||
placeholder='Masukkan maksimal stok (opsional)'
|
||||
error={!!errors.max_stock}
|
||||
helperText={errors.max_stock?.message}
|
||||
inputProps={{ min: 1 }}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Threshold */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Threshold
|
||||
</Typography>
|
||||
<Controller
|
||||
name='threshold'
|
||||
control={control}
|
||||
rules={{
|
||||
required: 'Threshold wajib diisi',
|
||||
min: { value: 0, message: 'Threshold minimal 0' }
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='number'
|
||||
placeholder='Masukkan threshold '
|
||||
error={!!errors.threshold}
|
||||
helperText={errors.threshold?.message}
|
||||
inputProps={{ min: 0 }}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Fallback Prize */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Hadiah Cadangan
|
||||
</Typography>
|
||||
<Controller
|
||||
name='fallback_prize_id'
|
||||
control={control}
|
||||
render={({ field: { onChange, value, ...field } }) => (
|
||||
<CustomAutocomplete
|
||||
{...field}
|
||||
options={availablePrizes}
|
||||
getOptionLabel={option => `${option.name} (Stok: ${option.stock})`}
|
||||
value={availablePrizes.find(prize => prize.id === value) || null}
|
||||
onChange={(_, newValue) => onChange(newValue?.id || '')}
|
||||
renderInput={params => (
|
||||
<CustomTextField
|
||||
{...params}
|
||||
placeholder='Pilih hadiah cadangan'
|
||||
error={!!errors.fallback_prize_id}
|
||||
helperText={
|
||||
errors.fallback_prize_id?.message || 'Hadiah yang diberikan ketika hadiah ini habis'
|
||||
}
|
||||
/>
|
||||
)}
|
||||
isOptionEqualToValue={(option, value) => option.id === value?.id}
|
||||
noOptionsText='Tidak ada hadiah tersedia'
|
||||
clearText='Hapus'
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</Box>
|
||||
|
||||
{/* Sticky Footer */}
|
||||
<Box
|
||||
sx={{
|
||||
position: 'sticky',
|
||||
bottom: 0,
|
||||
zIndex: 10,
|
||||
backgroundColor: 'background.paper',
|
||||
borderTop: 1,
|
||||
borderColor: 'divider',
|
||||
p: 3
|
||||
}}
|
||||
>
|
||||
<div className='flex items-center gap-4'>
|
||||
<Button variant='contained' type='submit' form='game-prize-form' disabled={isSubmitting}>
|
||||
{isSubmitting ? (isEditMode ? 'Mengupdate...' : 'Menyimpan...') : isEditMode ? 'Update' : 'Simpan'}
|
||||
</Button>
|
||||
<Button variant='outlined' color='error' onClick={handleReset} disabled={isSubmitting}>
|
||||
Batal
|
||||
</Button>
|
||||
</div>
|
||||
</Box>
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
|
||||
export default AddEditGamePrizeDrawer
|
||||
@@ -0,0 +1,104 @@
|
||||
// React Imports
|
||||
import { useState } from 'react'
|
||||
|
||||
// MUI Imports
|
||||
import Dialog from '@mui/material/Dialog'
|
||||
import DialogTitle from '@mui/material/DialogTitle'
|
||||
import DialogContent from '@mui/material/DialogContent'
|
||||
import DialogActions from '@mui/material/DialogActions'
|
||||
import DialogContentText from '@mui/material/DialogContentText'
|
||||
import Button from '@mui/material/Button'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import Box from '@mui/material/Box'
|
||||
import Alert from '@mui/material/Alert'
|
||||
import { GamePrize } from '@/types/services/gamePrize'
|
||||
import { useGamePrizes } from '@/services/queries/gamePrize'
|
||||
|
||||
// Types
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onConfirm: () => void
|
||||
gamePrize: GamePrize | null
|
||||
isDeleting?: boolean
|
||||
}
|
||||
|
||||
const DeleteGamePrizeDialog = ({ open, onClose, onConfirm, gamePrize, isDeleting = false }: Props) => {
|
||||
if (!gamePrize) return null
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
maxWidth='sm'
|
||||
fullWidth
|
||||
aria-labelledby='delete-dialog-title'
|
||||
aria-describedby='delete-dialog-description'
|
||||
>
|
||||
<DialogTitle id='delete-dialog-title'>
|
||||
<Box display='flex' alignItems='center' gap={2}>
|
||||
<i className='tabler-trash text-red-500 text-2xl' />
|
||||
<Typography variant='h6'>Hapus Game</Typography>
|
||||
</Box>
|
||||
</DialogTitle>
|
||||
|
||||
<DialogContent>
|
||||
<DialogContentText id='delete-dialog-description' className='mb-4'>
|
||||
Apakah Anda yakin ingin menghapus game berikut?
|
||||
</DialogContentText>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
backgroundColor: 'grey.50',
|
||||
p: 2,
|
||||
borderRadius: 1,
|
||||
border: '1px solid',
|
||||
borderColor: 'grey.200',
|
||||
mb: 2
|
||||
}}
|
||||
>
|
||||
<Typography variant='subtitle2' className='font-medium mb-1'>
|
||||
{gamePrize.name}
|
||||
</Typography>
|
||||
<Typography variant='body2' color='text.secondary'>
|
||||
Dibuat:{' '}
|
||||
{new Date(gamePrize.created_at).toLocaleDateString('id-ID', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric'
|
||||
})}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Alert severity='warning' sx={{ mb: 2 }}>
|
||||
<Typography variant='body2'>
|
||||
<strong>Peringatan:</strong> Tindakan ini tidak dapat dibatalkan. Semua data yang terkait dengan game ini
|
||||
akan dihapus secara permanen.
|
||||
</Typography>
|
||||
</Alert>
|
||||
|
||||
<DialogContentText>
|
||||
Pastikan tidak ada pengguna yang masih menggunakan game ini sebelum menghapus.
|
||||
</DialogContentText>
|
||||
</DialogContent>
|
||||
|
||||
<DialogActions className='p-4'>
|
||||
<Button onClick={onClose} variant='outlined' disabled={isDeleting}>
|
||||
Batal
|
||||
</Button>
|
||||
<Button
|
||||
onClick={onConfirm}
|
||||
color='error'
|
||||
variant='contained'
|
||||
disabled={isDeleting}
|
||||
startIcon={isDeleting ? <i className='tabler-loader animate-spin' /> : <i className='tabler-trash' />}
|
||||
>
|
||||
{isDeleting ? 'Menghapus...' : 'Hapus'}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export default DeleteGamePrizeDialog
|
||||
@@ -0,0 +1,483 @@
|
||||
'use client'
|
||||
|
||||
// React Imports
|
||||
import { useEffect, useState, useMemo, useCallback } from 'react'
|
||||
|
||||
// Next Imports
|
||||
import Link from 'next/link'
|
||||
import { useParams } from 'next/navigation'
|
||||
|
||||
// MUI Imports
|
||||
import Card from '@mui/material/Card'
|
||||
import CardHeader from '@mui/material/CardHeader'
|
||||
import Button from '@mui/material/Button'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import Chip from '@mui/material/Chip'
|
||||
import Checkbox from '@mui/material/Checkbox'
|
||||
import IconButton from '@mui/material/IconButton'
|
||||
import { styled } from '@mui/material/styles'
|
||||
import TablePagination from '@mui/material/TablePagination'
|
||||
import type { TextFieldProps } from '@mui/material/TextField'
|
||||
import MenuItem from '@mui/material/MenuItem'
|
||||
|
||||
// Third-party Imports
|
||||
import classnames from 'classnames'
|
||||
import { rankItem } from '@tanstack/match-sorter-utils'
|
||||
import {
|
||||
createColumnHelper,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
useReactTable,
|
||||
getFilteredRowModel,
|
||||
getFacetedRowModel,
|
||||
getFacetedUniqueValues,
|
||||
getFacetedMinMaxValues,
|
||||
getPaginationRowModel,
|
||||
getSortedRowModel
|
||||
} from '@tanstack/react-table'
|
||||
import type { ColumnDef, FilterFn } from '@tanstack/react-table'
|
||||
import type { RankingInfo } from '@tanstack/match-sorter-utils'
|
||||
|
||||
// Type Imports
|
||||
import type { ThemeColor } from '@core/types'
|
||||
import type { Locale } from '@configs/i18n'
|
||||
|
||||
// Component Imports
|
||||
import OptionMenu from '@core/components/option-menu'
|
||||
import TablePaginationComponent from '@components/TablePaginationComponent'
|
||||
import CustomTextField from '@core/components/mui/TextField'
|
||||
import CustomAvatar from '@core/components/mui/Avatar'
|
||||
|
||||
// Util Imports
|
||||
import { getInitials } from '@/utils/getInitials'
|
||||
import { getLocalizedUrl } from '@/utils/i18n'
|
||||
import { formatCurrency } from '@/utils/transform'
|
||||
|
||||
// Style Imports
|
||||
import tableStyles from '@core/styles/table.module.css'
|
||||
import Loading from '@/components/layout/shared/Loading'
|
||||
import AddEditGamePrizeDrawer from './AddEditGamePrizeDrawer'
|
||||
import DeleteGamePrizeDialog from './DeleteGamePrizeDialog'
|
||||
import { useGamePrizes } from '@/services/queries/gamePrize'
|
||||
import { useGamePrizesMutation } from '@/services/mutations/gamePrize'
|
||||
import { GamePrize } from '@/types/services/gamePrize'
|
||||
|
||||
declare module '@tanstack/table-core' {
|
||||
interface FilterFns {
|
||||
fuzzy: FilterFn<unknown>
|
||||
}
|
||||
interface FilterMeta {
|
||||
itemRank: RankingInfo
|
||||
}
|
||||
}
|
||||
|
||||
type GamePrizeWithAction = GamePrize & {
|
||||
action?: string
|
||||
}
|
||||
|
||||
// Styled Components
|
||||
const Icon = styled('i')({})
|
||||
|
||||
const fuzzyFilter: FilterFn<any> = (row, columnId, value, addMeta) => {
|
||||
// Rank the item
|
||||
const itemRank = rankItem(row.getValue(columnId), value)
|
||||
|
||||
// Store the itemRank info
|
||||
addMeta({
|
||||
itemRank
|
||||
})
|
||||
|
||||
// Return if the item should be filtered in/out
|
||||
return itemRank.passed
|
||||
}
|
||||
|
||||
const DebouncedInput = ({
|
||||
value: initialValue,
|
||||
onChange,
|
||||
debounce = 500,
|
||||
...props
|
||||
}: {
|
||||
value: string | number
|
||||
onChange: (value: string | number) => void
|
||||
debounce?: number
|
||||
} & Omit<TextFieldProps, 'onChange'>) => {
|
||||
// States
|
||||
const [value, setValue] = useState(initialValue)
|
||||
|
||||
useEffect(() => {
|
||||
setValue(initialValue)
|
||||
}, [initialValue])
|
||||
|
||||
useEffect(() => {
|
||||
const timeout = setTimeout(() => {
|
||||
onChange(value)
|
||||
}, debounce)
|
||||
|
||||
return () => clearTimeout(timeout)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [value])
|
||||
|
||||
return <CustomTextField {...props} value={value} onChange={e => setValue(e.target.value)} />
|
||||
}
|
||||
|
||||
// Column Definitions
|
||||
const columnHelper = createColumnHelper<GamePrizeWithAction>()
|
||||
|
||||
const GamePrizeListTable = () => {
|
||||
// States
|
||||
const [addGamePrizeOpen, setAddGamePrizeOpen] = useState(false)
|
||||
const [editGamePrizeData, setEditGamePrizeData] = useState<GamePrize | undefined>(undefined)
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
|
||||
const [gamePrizeToDelete, setGamePrizeToDelete] = useState<GamePrize | null>(null)
|
||||
const [rowSelection, setRowSelection] = useState({})
|
||||
const [globalFilter, setGlobalFilter] = useState('')
|
||||
const [currentPage, setCurrentPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(10)
|
||||
const [search, setSearch] = useState('')
|
||||
|
||||
// Replace with actual hook for game prizes
|
||||
const { data, isLoading, error, isFetching } = useGamePrizes({
|
||||
page: currentPage,
|
||||
limit: pageSize,
|
||||
search
|
||||
})
|
||||
|
||||
const { deleteGamePrize } = useGamePrizesMutation()
|
||||
|
||||
const gamePrizes = data?.data ?? []
|
||||
const totalCount = data?.total_count ?? 0
|
||||
|
||||
// Hooks
|
||||
const { lang: locale } = useParams()
|
||||
|
||||
const handlePageChange = useCallback((event: unknown, newPage: number) => {
|
||||
setCurrentPage(newPage)
|
||||
}, [])
|
||||
|
||||
const handlePageSizeChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newPageSize = parseInt(event.target.value, 10)
|
||||
setPageSize(newPageSize)
|
||||
setCurrentPage(1) // Reset to first page
|
||||
}, [])
|
||||
|
||||
const handleEditGamePrize = (gamePrize: GamePrize) => {
|
||||
setEditGamePrizeData(gamePrize)
|
||||
setAddGamePrizeOpen(true)
|
||||
}
|
||||
|
||||
const handleDeleteGamePrize = (gamePrize: GamePrize) => {
|
||||
setGamePrizeToDelete(gamePrize)
|
||||
setDeleteDialogOpen(true)
|
||||
}
|
||||
|
||||
const handleConfirmDelete = () => {
|
||||
if (gamePrizeToDelete) {
|
||||
deleteGamePrize.mutate(gamePrizeToDelete.id, {
|
||||
onSuccess: () => {
|
||||
console.log('Game Prize deleted successfully')
|
||||
setDeleteDialogOpen(false)
|
||||
setGamePrizeToDelete(null)
|
||||
},
|
||||
onError: error => {
|
||||
console.error('Error deleting game prize:', error)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const handleCloseDeleteDialog = () => {
|
||||
if (deleteGamePrize.isPending) return
|
||||
setDeleteDialogOpen(false)
|
||||
setGamePrizeToDelete(null)
|
||||
}
|
||||
|
||||
const handleCloseGamePrizeDrawer = () => {
|
||||
setAddGamePrizeOpen(false)
|
||||
setEditGamePrizeData(undefined)
|
||||
}
|
||||
|
||||
const columns = useMemo<ColumnDef<GamePrizeWithAction, any>[]>(
|
||||
() => [
|
||||
{
|
||||
id: 'select',
|
||||
header: ({ table }) => (
|
||||
<Checkbox
|
||||
{...{
|
||||
checked: table.getIsAllRowsSelected(),
|
||||
indeterminate: table.getIsSomeRowsSelected(),
|
||||
onChange: table.getToggleAllRowsSelectedHandler()
|
||||
}}
|
||||
/>
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<Checkbox
|
||||
{...{
|
||||
checked: row.getIsSelected(),
|
||||
disabled: !row.getCanSelect(),
|
||||
indeterminate: row.getIsSomeSelected(),
|
||||
onChange: row.getToggleSelectedHandler()
|
||||
}}
|
||||
/>
|
||||
)
|
||||
},
|
||||
columnHelper.accessor('name', {
|
||||
header: 'Nama Hadiah',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-4'>
|
||||
<CustomAvatar src={row.original.metadata?.imageUrl} size={40}>
|
||||
{getInitials(row.original.name)}
|
||||
</CustomAvatar>
|
||||
<div className='flex flex-col'>
|
||||
<Link href={getLocalizedUrl(`/apps/game-prizes/${row.original.id}/detail`, locale as Locale)}>
|
||||
<Typography className='font-medium cursor-pointer hover:underline text-primary'>
|
||||
{row.original.name}
|
||||
</Typography>
|
||||
</Link>
|
||||
<Typography variant='caption' color='textSecondary'>
|
||||
{row.original.game?.name || 'Game tidak tersedia'}
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('game', {
|
||||
header: 'Game',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex flex-col'>
|
||||
<Typography className='font-medium'>{row.original.game?.name || 'N/A'}</Typography>
|
||||
<Typography variant='caption' color='textSecondary'>
|
||||
{row.original.game?.type || ''}
|
||||
</Typography>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('weight', {
|
||||
header: 'Bobot',
|
||||
cell: ({ row }) => <Typography color='text.primary'>{row.original.weight}%</Typography>
|
||||
}),
|
||||
columnHelper.accessor('stock', {
|
||||
header: 'Stok',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex flex-col gap-1'>
|
||||
<Typography className='font-medium'>
|
||||
{row.original.stock}
|
||||
{row.original.max_stock && ` / ${row.original.max_stock}`}
|
||||
</Typography>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('threshold', {
|
||||
header: 'Threshold',
|
||||
cell: ({ row }) => <Typography color='text.primary'>{row.original.threshold || 'Tidak Ada'}</Typography>
|
||||
}),
|
||||
columnHelper.accessor('fallback_prize', {
|
||||
header: 'Hadiah Cadangan',
|
||||
cell: ({ row }) => (
|
||||
<Typography color='text.primary'>{row.original.fallback_prize?.name || 'Tidak Ada'}</Typography>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('created_at', {
|
||||
header: 'Tanggal Dibuat',
|
||||
cell: ({ row }) => (
|
||||
<Typography color='text.primary'>
|
||||
{new Date(row.original.created_at).toLocaleDateString('id-ID', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
})}
|
||||
</Typography>
|
||||
)
|
||||
}),
|
||||
{
|
||||
id: 'actions',
|
||||
header: 'Aksi',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center'>
|
||||
<OptionMenu
|
||||
iconButtonProps={{ size: 'medium' }}
|
||||
iconClassName='text-textSecondary text-[22px]'
|
||||
options={[
|
||||
{
|
||||
text: 'Edit',
|
||||
icon: 'tabler-edit text-[22px]',
|
||||
menuItemProps: {
|
||||
className: 'flex items-center gap-2 text-textSecondary',
|
||||
onClick: () => handleEditGamePrize(row.original)
|
||||
}
|
||||
},
|
||||
{
|
||||
text: 'Hapus',
|
||||
icon: 'tabler-trash text-[22px]',
|
||||
menuItemProps: {
|
||||
className: 'flex items-center gap-2 text-textSecondary',
|
||||
onClick: () => handleDeleteGamePrize(row.original)
|
||||
}
|
||||
}
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
enableSorting: false
|
||||
}
|
||||
],
|
||||
[locale, handleEditGamePrize, handleDeleteGamePrize]
|
||||
)
|
||||
|
||||
const table = useReactTable({
|
||||
data: gamePrizes as GamePrize[],
|
||||
columns,
|
||||
filterFns: {
|
||||
fuzzy: fuzzyFilter
|
||||
},
|
||||
state: {
|
||||
rowSelection,
|
||||
globalFilter,
|
||||
pagination: {
|
||||
pageIndex: currentPage,
|
||||
pageSize
|
||||
}
|
||||
},
|
||||
enableRowSelection: true,
|
||||
onRowSelectionChange: setRowSelection,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
manualPagination: true,
|
||||
pageCount: Math.ceil(totalCount / pageSize)
|
||||
})
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card>
|
||||
<div className='flex justify-between flex-col items-start md:flex-row md:items-center p-6 border-bs gap-4'>
|
||||
<CustomTextField
|
||||
select
|
||||
value={table.getState().pagination.pageSize}
|
||||
onChange={e => table.setPageSize(Number(e.target.value))}
|
||||
className='max-sm:is-full sm:is-[70px]'
|
||||
>
|
||||
<MenuItem value='10'>10</MenuItem>
|
||||
<MenuItem value='25'>25</MenuItem>
|
||||
<MenuItem value='50'>50</MenuItem>
|
||||
</CustomTextField>
|
||||
<div className='flex flex-col sm:flex-row max-sm:is-full items-start sm:items-center gap-4'>
|
||||
<DebouncedInput
|
||||
value={search ?? ''}
|
||||
onChange={value => setSearch(value as string)}
|
||||
placeholder='Cari Hadiah Game'
|
||||
className='max-sm:is-full'
|
||||
/>
|
||||
<Button
|
||||
color='secondary'
|
||||
variant='tonal'
|
||||
startIcon={<i className='tabler-upload' />}
|
||||
className='max-sm:is-full'
|
||||
>
|
||||
Ekspor
|
||||
</Button>
|
||||
<Button
|
||||
variant='contained'
|
||||
startIcon={<i className='tabler-plus' />}
|
||||
onClick={() => setAddGamePrizeOpen(!addGamePrizeOpen)}
|
||||
className='max-sm:is-full'
|
||||
>
|
||||
Tambah Hadiah
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className='overflow-x-auto'>
|
||||
{isLoading ? (
|
||||
<Loading />
|
||||
) : (
|
||||
<table className={tableStyles.table}>
|
||||
<thead>
|
||||
{table.getHeaderGroups().map(headerGroup => (
|
||||
<tr key={headerGroup.id}>
|
||||
{headerGroup.headers.map(header => (
|
||||
<th key={header.id}>
|
||||
{header.isPlaceholder ? null : (
|
||||
<>
|
||||
<div
|
||||
className={classnames({
|
||||
'flex items-center': header.column.getIsSorted(),
|
||||
'cursor-pointer select-none': header.column.getCanSort()
|
||||
})}
|
||||
onClick={header.column.getToggleSortingHandler()}
|
||||
>
|
||||
{flexRender(header.column.columnDef.header, header.getContext())}
|
||||
{{
|
||||
asc: <i className='tabler-chevron-up text-xl' />,
|
||||
desc: <i className='tabler-chevron-down text-xl' />
|
||||
}[header.column.getIsSorted() as 'asc' | 'desc'] ?? null}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
{table.getFilteredRowModel().rows.length === 0 ? (
|
||||
<tbody>
|
||||
<tr>
|
||||
<td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
|
||||
Tidak ada data tersedia
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
) : (
|
||||
<tbody>
|
||||
{table
|
||||
.getRowModel()
|
||||
.rows.slice(0, table.getState().pagination.pageSize)
|
||||
.map(row => {
|
||||
return (
|
||||
<tr key={row.id} className={classnames({ selected: row.getIsSelected() })}>
|
||||
{row.getVisibleCells().map(cell => (
|
||||
<td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
|
||||
))}
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
)}
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
<TablePagination
|
||||
component={() => (
|
||||
<TablePaginationComponent
|
||||
pageIndex={currentPage}
|
||||
pageSize={pageSize}
|
||||
totalCount={totalCount}
|
||||
onPageChange={handlePageChange}
|
||||
/>
|
||||
)}
|
||||
count={totalCount}
|
||||
rowsPerPage={pageSize}
|
||||
page={currentPage}
|
||||
onPageChange={handlePageChange}
|
||||
onRowsPerPageChange={handlePageSizeChange}
|
||||
rowsPerPageOptions={[10, 25, 50]}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{/* Add/Edit Game Prize Drawer */}
|
||||
<AddEditGamePrizeDrawer
|
||||
open={addGamePrizeOpen}
|
||||
handleClose={handleCloseGamePrizeDrawer}
|
||||
data={editGamePrizeData}
|
||||
/>
|
||||
|
||||
{/* Delete Game Prize Dialog */}
|
||||
<DeleteGamePrizeDialog
|
||||
open={deleteDialogOpen}
|
||||
onClose={handleCloseDeleteDialog}
|
||||
onConfirm={handleConfirmDelete}
|
||||
gamePrize={gamePrizeToDelete}
|
||||
isDeleting={deleteGamePrize.isPending}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default GamePrizeListTable
|
||||
@@ -0,0 +1,17 @@
|
||||
// MUI Imports
|
||||
import Grid from '@mui/material/Grid2'
|
||||
import GamePrizeListTable from './GamePrizeListTable'
|
||||
|
||||
// Type Imports
|
||||
|
||||
const GamePrizeList = () => {
|
||||
return (
|
||||
<Grid container spacing={6}>
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<GamePrizeListTable />
|
||||
</Grid>
|
||||
</Grid>
|
||||
)
|
||||
}
|
||||
|
||||
export default GamePrizeList
|
||||
@@ -0,0 +1,325 @@
|
||||
// React Imports
|
||||
import { useState, useEffect } from 'react'
|
||||
|
||||
// MUI Imports
|
||||
import Button from '@mui/material/Button'
|
||||
import Drawer from '@mui/material/Drawer'
|
||||
import IconButton from '@mui/material/IconButton'
|
||||
import MenuItem from '@mui/material/MenuItem'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import Box from '@mui/material/Box'
|
||||
import Switch from '@mui/material/Switch'
|
||||
import FormControlLabel from '@mui/material/FormControlLabel'
|
||||
|
||||
// Third-party Imports
|
||||
import { useForm, Controller } from 'react-hook-form'
|
||||
|
||||
// Component Imports
|
||||
import CustomTextField from '@core/components/mui/TextField'
|
||||
import ImageUpload from '@/components/ImageUpload'
|
||||
|
||||
// Services
|
||||
import { useFilesMutation } from '@/services/mutations/files'
|
||||
import { Game, GameRequest } from '@/types/services/game'
|
||||
import { useGamesMutation } from '@/services/mutations/game'
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
handleClose: () => void
|
||||
data?: Game // Game data for edit (if exists)
|
||||
}
|
||||
|
||||
type FormValidateType = {
|
||||
name: string
|
||||
type: string
|
||||
is_active: boolean
|
||||
imageUrl: string
|
||||
}
|
||||
|
||||
// Initial form data
|
||||
const initialData: FormValidateType = {
|
||||
name: '',
|
||||
type: 'quiz',
|
||||
is_active: true,
|
||||
imageUrl: ''
|
||||
}
|
||||
|
||||
// Mock mutation hooks (replace with actual hooks)
|
||||
|
||||
// Game types
|
||||
const GAME_TYPES = [
|
||||
{ value: 'SPIN', label: 'Spin' },
|
||||
{ value: 'RUFFLE', label: 'Ruffle' },
|
||||
{ value: 'MINIGAME', label: 'Mini Game' }
|
||||
]
|
||||
|
||||
const AddEditGamesDrawer = (props: Props) => {
|
||||
// Props
|
||||
const { open, handleClose, data } = props
|
||||
|
||||
// States
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [imageUrl, setImageUrl] = useState<string>('')
|
||||
|
||||
const { createGame, updateGame } = useGamesMutation()
|
||||
const { mutate, isPending } = useFilesMutation().uploadFile
|
||||
|
||||
// Determine if this is edit mode
|
||||
const isEditMode = Boolean(data?.id)
|
||||
|
||||
// Handle file upload
|
||||
const handleUpload = async (file: File): Promise<string> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
formData.append('file_type', 'image')
|
||||
formData.append('description', 'game image upload')
|
||||
|
||||
mutate(formData, {
|
||||
onSuccess: r => {
|
||||
setImageUrl(r.file_url)
|
||||
setValue('imageUrl', r.file_url) // Update form value
|
||||
resolve(r.id)
|
||||
},
|
||||
onError: er => {
|
||||
reject(er)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// Hooks
|
||||
const {
|
||||
control,
|
||||
reset: resetForm,
|
||||
handleSubmit,
|
||||
watch,
|
||||
setValue,
|
||||
formState: { errors }
|
||||
} = useForm<FormValidateType>({
|
||||
defaultValues: initialData
|
||||
})
|
||||
|
||||
const watchedImageUrl = watch('imageUrl')
|
||||
|
||||
// Effect to populate form when editing
|
||||
useEffect(() => {
|
||||
if (isEditMode && data) {
|
||||
// Extract imageUrl from metadata
|
||||
const imageUrlFromData = data.metadata?.imageUrl || ''
|
||||
|
||||
// Populate form with existing data
|
||||
const formData: FormValidateType = {
|
||||
name: data.name || '',
|
||||
type: data.type || 'SPIN',
|
||||
is_active: data.is_active ?? true,
|
||||
imageUrl: imageUrlFromData
|
||||
}
|
||||
|
||||
resetForm(formData)
|
||||
setImageUrl(imageUrlFromData)
|
||||
} else {
|
||||
// Reset to initial data for add mode
|
||||
resetForm(initialData)
|
||||
setImageUrl('')
|
||||
}
|
||||
}, [data, isEditMode, resetForm])
|
||||
|
||||
// Sync imageUrl state with form value
|
||||
useEffect(() => {
|
||||
if (watchedImageUrl !== imageUrl) {
|
||||
setImageUrl(watchedImageUrl)
|
||||
}
|
||||
}, [watchedImageUrl, imageUrl])
|
||||
|
||||
const handleFormSubmit = async (formData: FormValidateType) => {
|
||||
try {
|
||||
setIsSubmitting(true)
|
||||
|
||||
// Create GameRequest object
|
||||
const gameRequest: GameRequest = {
|
||||
name: formData.name,
|
||||
type: formData.type,
|
||||
is_active: formData.is_active,
|
||||
metadata: {
|
||||
imageUrl: formData.imageUrl || undefined
|
||||
}
|
||||
}
|
||||
|
||||
if (isEditMode && data?.id) {
|
||||
// Update existing game
|
||||
updateGame.mutate(
|
||||
{ id: data.id, payload: gameRequest },
|
||||
{
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
handleClose()
|
||||
}
|
||||
}
|
||||
)
|
||||
} else {
|
||||
// Create new game
|
||||
createGame.mutate(gameRequest, {
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
handleClose()
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error submitting game:', error)
|
||||
// Handle error (show toast, etc.)
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleReset = () => {
|
||||
handleClose()
|
||||
resetForm(initialData)
|
||||
setImageUrl('')
|
||||
}
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
open={open}
|
||||
anchor='right'
|
||||
variant='temporary'
|
||||
onClose={handleReset}
|
||||
ModalProps={{ keepMounted: true }}
|
||||
sx={{
|
||||
'& .MuiDrawer-paper': {
|
||||
width: { xs: 300, sm: 400 },
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
height: '100%'
|
||||
}
|
||||
}}
|
||||
>
|
||||
{/* Sticky Header */}
|
||||
<Box
|
||||
sx={{
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
zIndex: 10,
|
||||
backgroundColor: 'background.paper',
|
||||
borderBottom: 1,
|
||||
borderColor: 'divider'
|
||||
}}
|
||||
>
|
||||
<div className='flex items-center justify-between plb-5 pli-6'>
|
||||
<Typography variant='h5'>{isEditMode ? 'Edit Game' : 'Tambah Game Baru'}</Typography>
|
||||
<IconButton size='small' onClick={handleReset}>
|
||||
<i className='tabler-x text-2xl text-textPrimary' />
|
||||
</IconButton>
|
||||
</div>
|
||||
</Box>
|
||||
|
||||
{/* Scrollable Content */}
|
||||
<Box sx={{ flex: 1, overflowY: 'auto' }}>
|
||||
<form id='game-form' onSubmit={handleSubmit(handleFormSubmit)}>
|
||||
<div className='flex flex-col gap-6 p-6'>
|
||||
{/* Nama Game */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Nama Game <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='name'
|
||||
control={control}
|
||||
rules={{ required: 'Nama game wajib diisi' }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='Masukkan nama game'
|
||||
error={!!errors.name}
|
||||
helperText={errors.name?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Tipe Game */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Tipe Game <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='type'
|
||||
control={control}
|
||||
rules={{ required: 'Tipe game wajib dipilih' }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField {...field} select fullWidth error={!!errors.type} helperText={errors.type?.message}>
|
||||
{GAME_TYPES.map(type => (
|
||||
<MenuItem key={type.value} value={type.value}>
|
||||
{type.label}
|
||||
</MenuItem>
|
||||
))}
|
||||
</CustomTextField>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Image Upload */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Gambar Game
|
||||
</Typography>
|
||||
<ImageUpload
|
||||
onUpload={handleUpload}
|
||||
maxFileSize={1 * 1024 * 1024} // 1MB
|
||||
currentImageUrl={imageUrl}
|
||||
dragDropText='Drop your image here'
|
||||
browseButtonText='Choose Image'
|
||||
/>
|
||||
<Controller
|
||||
name='imageUrl'
|
||||
control={control}
|
||||
render={({ field }) => <input type='hidden' {...field} value={imageUrl} />}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Status Aktif */}
|
||||
<div>
|
||||
<Controller
|
||||
name='is_active'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<FormControlLabel
|
||||
control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
|
||||
label='Game Aktif'
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</Box>
|
||||
|
||||
{/* Sticky Footer */}
|
||||
<Box
|
||||
sx={{
|
||||
position: 'sticky',
|
||||
bottom: 0,
|
||||
zIndex: 10,
|
||||
backgroundColor: 'background.paper',
|
||||
borderTop: 1,
|
||||
borderColor: 'divider',
|
||||
p: 3
|
||||
}}
|
||||
>
|
||||
<div className='flex items-center gap-4'>
|
||||
<Button variant='contained' type='submit' form='game-form' disabled={isSubmitting || isPending}>
|
||||
{isSubmitting ? (isEditMode ? 'Mengupdate...' : 'Menyimpan...') : isEditMode ? 'Update' : 'Simpan'}
|
||||
</Button>
|
||||
<Button variant='outlined' color='error' onClick={handleReset} disabled={isSubmitting || isPending}>
|
||||
Batal
|
||||
</Button>
|
||||
</div>
|
||||
</Box>
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
|
||||
export default AddEditGamesDrawer
|
||||
@@ -0,0 +1,103 @@
|
||||
// React Imports
|
||||
import { useState } from 'react'
|
||||
|
||||
// MUI Imports
|
||||
import Dialog from '@mui/material/Dialog'
|
||||
import DialogTitle from '@mui/material/DialogTitle'
|
||||
import DialogContent from '@mui/material/DialogContent'
|
||||
import DialogActions from '@mui/material/DialogActions'
|
||||
import DialogContentText from '@mui/material/DialogContentText'
|
||||
import Button from '@mui/material/Button'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import Box from '@mui/material/Box'
|
||||
import Alert from '@mui/material/Alert'
|
||||
|
||||
// Types
|
||||
import { Game } from '@/types/services/game'
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onConfirm: () => void
|
||||
game: Game | null
|
||||
isDeleting?: boolean
|
||||
}
|
||||
|
||||
const DeleteGameDialog = ({ open, onClose, onConfirm, game, isDeleting = false }: Props) => {
|
||||
if (!game) return null
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
maxWidth='sm'
|
||||
fullWidth
|
||||
aria-labelledby='delete-dialog-title'
|
||||
aria-describedby='delete-dialog-description'
|
||||
>
|
||||
<DialogTitle id='delete-dialog-title'>
|
||||
<Box display='flex' alignItems='center' gap={2}>
|
||||
<i className='tabler-trash text-red-500 text-2xl' />
|
||||
<Typography variant='h6'>Hapus Game</Typography>
|
||||
</Box>
|
||||
</DialogTitle>
|
||||
|
||||
<DialogContent>
|
||||
<DialogContentText id='delete-dialog-description' className='mb-4'>
|
||||
Apakah Anda yakin ingin menghapus game berikut?
|
||||
</DialogContentText>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
backgroundColor: 'grey.50',
|
||||
p: 2,
|
||||
borderRadius: 1,
|
||||
border: '1px solid',
|
||||
borderColor: 'grey.200',
|
||||
mb: 2
|
||||
}}
|
||||
>
|
||||
<Typography variant='subtitle2' className='font-medium mb-1'>
|
||||
{game.name}
|
||||
</Typography>
|
||||
<Typography variant='body2' color='text.secondary'>
|
||||
Dibuat:{' '}
|
||||
{new Date(game.created_at).toLocaleDateString('id-ID', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric'
|
||||
})}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Alert severity='warning' sx={{ mb: 2 }}>
|
||||
<Typography variant='body2'>
|
||||
<strong>Peringatan:</strong> Tindakan ini tidak dapat dibatalkan. Semua data yang terkait dengan game ini
|
||||
akan dihapus secara permanen.
|
||||
</Typography>
|
||||
</Alert>
|
||||
|
||||
<DialogContentText>
|
||||
Pastikan tidak ada pengguna yang masih menggunakan game ini sebelum menghapus.
|
||||
</DialogContentText>
|
||||
</DialogContent>
|
||||
|
||||
<DialogActions className='p-4'>
|
||||
<Button onClick={onClose} variant='outlined' disabled={isDeleting}>
|
||||
Batal
|
||||
</Button>
|
||||
<Button
|
||||
onClick={onConfirm}
|
||||
color='error'
|
||||
variant='contained'
|
||||
disabled={isDeleting}
|
||||
startIcon={isDeleting ? <i className='tabler-loader animate-spin' /> : <i className='tabler-trash' />}
|
||||
>
|
||||
{isDeleting ? 'Menghapus...' : 'Hapus'}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export default DeleteGameDialog
|
||||
@@ -0,0 +1,467 @@
|
||||
'use client'
|
||||
|
||||
// React Imports
|
||||
import { useEffect, useState, useMemo, useCallback } from 'react'
|
||||
|
||||
// Next Imports
|
||||
import Link from 'next/link'
|
||||
import { useParams } from 'next/navigation'
|
||||
|
||||
// MUI Imports
|
||||
import Card from '@mui/material/Card'
|
||||
import CardHeader from '@mui/material/CardHeader'
|
||||
import Button from '@mui/material/Button'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import Chip from '@mui/material/Chip'
|
||||
import Checkbox from '@mui/material/Checkbox'
|
||||
import IconButton from '@mui/material/IconButton'
|
||||
import { styled } from '@mui/material/styles'
|
||||
import TablePagination from '@mui/material/TablePagination'
|
||||
import type { TextFieldProps } from '@mui/material/TextField'
|
||||
import MenuItem from '@mui/material/MenuItem'
|
||||
|
||||
// Third-party Imports
|
||||
import classnames from 'classnames'
|
||||
import { rankItem } from '@tanstack/match-sorter-utils'
|
||||
import {
|
||||
createColumnHelper,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
useReactTable,
|
||||
getFilteredRowModel,
|
||||
getFacetedRowModel,
|
||||
getFacetedUniqueValues,
|
||||
getFacetedMinMaxValues,
|
||||
getPaginationRowModel,
|
||||
getSortedRowModel
|
||||
} from '@tanstack/react-table'
|
||||
import type { ColumnDef, FilterFn } from '@tanstack/react-table'
|
||||
import type { RankingInfo } from '@tanstack/match-sorter-utils'
|
||||
|
||||
// Type Imports
|
||||
import type { ThemeColor } from '@core/types'
|
||||
import type { Locale } from '@configs/i18n'
|
||||
|
||||
// Component Imports
|
||||
import OptionMenu from '@core/components/option-menu'
|
||||
import TablePaginationComponent from '@components/TablePaginationComponent'
|
||||
import CustomTextField from '@core/components/mui/TextField'
|
||||
import CustomAvatar from '@core/components/mui/Avatar'
|
||||
|
||||
// Util Imports
|
||||
import { getInitials } from '@/utils/getInitials'
|
||||
import { getLocalizedUrl } from '@/utils/i18n'
|
||||
import { formatCurrency } from '@/utils/transform'
|
||||
|
||||
// Style Imports
|
||||
import tableStyles from '@core/styles/table.module.css'
|
||||
import Loading from '@/components/layout/shared/Loading'
|
||||
import AddEditGamesDrawer from './AddEditGamesDrawer'
|
||||
import DeleteGameDialog from './DeleteGamesDialog'
|
||||
import { Game } from '@/types/services/game'
|
||||
import { useGames } from '@/services/queries/game'
|
||||
import { useGamesMutation } from '@/services/mutations/game'
|
||||
|
||||
declare module '@tanstack/table-core' {
|
||||
interface FilterFns {
|
||||
fuzzy: FilterFn<unknown>
|
||||
}
|
||||
interface FilterMeta {
|
||||
itemRank: RankingInfo
|
||||
}
|
||||
}
|
||||
|
||||
type GameWithAction = Game & {
|
||||
action?: string
|
||||
}
|
||||
|
||||
// Styled Components
|
||||
const Icon = styled('i')({})
|
||||
|
||||
const fuzzyFilter: FilterFn<any> = (row, columnId, value, addMeta) => {
|
||||
// Rank the item
|
||||
const itemRank = rankItem(row.getValue(columnId), value)
|
||||
|
||||
// Store the itemRank info
|
||||
addMeta({
|
||||
itemRank
|
||||
})
|
||||
|
||||
// Return if the item should be filtered in/out
|
||||
return itemRank.passed
|
||||
}
|
||||
|
||||
const DebouncedInput = ({
|
||||
value: initialValue,
|
||||
onChange,
|
||||
debounce = 500,
|
||||
...props
|
||||
}: {
|
||||
value: string | number
|
||||
onChange: (value: string | number) => void
|
||||
debounce?: number
|
||||
} & Omit<TextFieldProps, 'onChange'>) => {
|
||||
// States
|
||||
const [value, setValue] = useState(initialValue)
|
||||
|
||||
useEffect(() => {
|
||||
setValue(initialValue)
|
||||
}, [initialValue])
|
||||
|
||||
useEffect(() => {
|
||||
const timeout = setTimeout(() => {
|
||||
onChange(value)
|
||||
}, debounce)
|
||||
|
||||
return () => clearTimeout(timeout)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [value])
|
||||
|
||||
return <CustomTextField {...props} value={value} onChange={e => setValue(e.target.value)} />
|
||||
}
|
||||
|
||||
// Column Definitions
|
||||
const columnHelper = createColumnHelper<GameWithAction>()
|
||||
|
||||
const GameListTable = () => {
|
||||
// States
|
||||
const [addGameOpen, setAddGameOpen] = useState(false)
|
||||
const [editGameData, setEditGameData] = useState<Game | undefined>(undefined)
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
|
||||
const [gameToDelete, setGameToDelete] = useState<Game | null>(null)
|
||||
const [rowSelection, setRowSelection] = useState({})
|
||||
const [globalFilter, setGlobalFilter] = useState('')
|
||||
const [currentPage, setCurrentPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(10)
|
||||
const [search, setSearch] = useState('')
|
||||
|
||||
const { data, isLoading, error, isFetching } = useGames({
|
||||
page: currentPage,
|
||||
limit: pageSize,
|
||||
search
|
||||
})
|
||||
|
||||
const { deleteGame } = useGamesMutation()
|
||||
|
||||
const games = data?.data ?? []
|
||||
const totalCount = data?.total_count ?? 0
|
||||
|
||||
// Hooks
|
||||
const { lang: locale } = useParams()
|
||||
|
||||
const handlePageChange = useCallback((event: unknown, newPage: number) => {
|
||||
setCurrentPage(newPage)
|
||||
}, [])
|
||||
|
||||
const handlePageSizeChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newPageSize = parseInt(event.target.value, 10)
|
||||
setPageSize(newPageSize)
|
||||
setCurrentPage(1) // Reset to first page
|
||||
}, [])
|
||||
|
||||
const handleEditGame = (game: Game) => {
|
||||
setEditGameData(game)
|
||||
setAddGameOpen(true)
|
||||
}
|
||||
|
||||
const handleDeleteGame = (game: Game) => {
|
||||
setGameToDelete(game)
|
||||
setDeleteDialogOpen(true)
|
||||
}
|
||||
|
||||
const handleConfirmDelete = () => {
|
||||
if (gameToDelete) {
|
||||
deleteGame.mutate(gameToDelete.id, {
|
||||
onSuccess: () => {
|
||||
console.log('Game deleted successfully')
|
||||
setDeleteDialogOpen(false)
|
||||
setGameToDelete(null)
|
||||
// You might want to refetch data here
|
||||
// refetch()
|
||||
},
|
||||
onError: error => {
|
||||
console.error('Error deleting game:', error)
|
||||
// Handle error (show toast, etc.)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const handleCloseDeleteDialog = () => {
|
||||
if (deleteGame.isPending) return // Prevent closing while deleting
|
||||
setDeleteDialogOpen(false)
|
||||
setGameToDelete(null)
|
||||
}
|
||||
|
||||
const handleToggleActive = (gameId: string, currentStatus: boolean) => {
|
||||
console.log('Toggling active status for game:', gameId, !currentStatus)
|
||||
// Add your toggle logic here
|
||||
// toggleGameStatus.mutate({ id: gameId, is_active: !currentStatus })
|
||||
}
|
||||
|
||||
const handleCloseGameDrawer = () => {
|
||||
setAddGameOpen(false)
|
||||
setEditGameData(undefined)
|
||||
}
|
||||
|
||||
const columns = useMemo<ColumnDef<GameWithAction, any>[]>(
|
||||
() => [
|
||||
{
|
||||
id: 'select',
|
||||
header: ({ table }) => (
|
||||
<Checkbox
|
||||
{...{
|
||||
checked: table.getIsAllRowsSelected(),
|
||||
indeterminate: table.getIsSomeRowsSelected(),
|
||||
onChange: table.getToggleAllRowsSelectedHandler()
|
||||
}}
|
||||
/>
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<Checkbox
|
||||
{...{
|
||||
checked: row.getIsSelected(),
|
||||
disabled: !row.getCanSelect(),
|
||||
indeterminate: row.getIsSomeSelected(),
|
||||
onChange: row.getToggleSelectedHandler()
|
||||
}}
|
||||
/>
|
||||
)
|
||||
},
|
||||
columnHelper.accessor('name', {
|
||||
header: 'Nama Game',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-4'>
|
||||
<CustomAvatar src={row.original.metadata?.imageUrl} size={40}>
|
||||
{getInitials(row.original.name)}
|
||||
</CustomAvatar>
|
||||
<div className='flex flex-col'>
|
||||
<Link href={getLocalizedUrl(`/apps/games/${row.original.id}/detail`, locale as Locale)}>
|
||||
<Typography className='font-medium cursor-pointer hover:underline text-primary'>
|
||||
{row.original.name}
|
||||
</Typography>
|
||||
</Link>
|
||||
<Typography variant='caption' color='textSecondary'>
|
||||
{row.original.type}
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('type', {
|
||||
header: 'Tipe Game',
|
||||
cell: ({ row }) => <Chip label={row.original.type} color='primary' variant='tonal' size='small' />
|
||||
}),
|
||||
columnHelper.accessor('is_active', {
|
||||
header: 'Status',
|
||||
cell: ({ row }) => (
|
||||
<Chip
|
||||
label={row.original.is_active ? 'Aktif' : 'Nonaktif'}
|
||||
color={row.original.is_active ? 'success' : 'error'}
|
||||
variant='tonal'
|
||||
size='small'
|
||||
/>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('created_at', {
|
||||
header: 'Tanggal Dibuat',
|
||||
cell: ({ row }) => (
|
||||
<Typography color='text.primary'>
|
||||
{new Date(row.original.created_at).toLocaleDateString('id-ID', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
})}
|
||||
</Typography>
|
||||
)
|
||||
}),
|
||||
{
|
||||
id: 'actions',
|
||||
header: 'Aksi',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center'>
|
||||
<OptionMenu
|
||||
iconButtonProps={{ size: 'medium' }}
|
||||
iconClassName='text-textSecondary text-[22px]'
|
||||
options={[
|
||||
{
|
||||
text: 'Edit',
|
||||
icon: 'tabler-edit text-[22px]',
|
||||
menuItemProps: {
|
||||
className: 'flex items-center gap-2 text-textSecondary',
|
||||
onClick: () => handleEditGame(row.original)
|
||||
}
|
||||
},
|
||||
{
|
||||
text: 'Hapus',
|
||||
icon: 'tabler-trash text-[22px]',
|
||||
menuItemProps: {
|
||||
className: 'flex items-center gap-2 text-textSecondary',
|
||||
onClick: () => handleDeleteGame(row.original)
|
||||
}
|
||||
}
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
enableSorting: false
|
||||
}
|
||||
],
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[locale, handleEditGame, handleDeleteGame, handleToggleActive]
|
||||
)
|
||||
|
||||
const table = useReactTable({
|
||||
data: games as Game[],
|
||||
columns,
|
||||
filterFns: {
|
||||
fuzzy: fuzzyFilter
|
||||
},
|
||||
state: {
|
||||
rowSelection,
|
||||
globalFilter,
|
||||
pagination: {
|
||||
pageIndex: currentPage,
|
||||
pageSize
|
||||
}
|
||||
},
|
||||
enableRowSelection: true,
|
||||
onRowSelectionChange: setRowSelection,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
manualPagination: true,
|
||||
pageCount: Math.ceil(totalCount / pageSize)
|
||||
})
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card>
|
||||
<div className='flex justify-between flex-col items-start md:flex-row md:items-center p-6 border-bs gap-4'>
|
||||
<CustomTextField
|
||||
select
|
||||
value={table.getState().pagination.pageSize}
|
||||
onChange={e => table.setPageSize(Number(e.target.value))}
|
||||
className='max-sm:is-full sm:is-[70px]'
|
||||
>
|
||||
<MenuItem value='10'>10</MenuItem>
|
||||
<MenuItem value='25'>25</MenuItem>
|
||||
<MenuItem value='50'>50</MenuItem>
|
||||
</CustomTextField>
|
||||
<div className='flex flex-col sm:flex-row max-sm:is-full items-start sm:items-center gap-4'>
|
||||
<DebouncedInput
|
||||
value={search ?? ''}
|
||||
onChange={value => setSearch(value as string)}
|
||||
placeholder='Cari Game'
|
||||
className='max-sm:is-full'
|
||||
/>
|
||||
<Button
|
||||
color='secondary'
|
||||
variant='tonal'
|
||||
startIcon={<i className='tabler-upload' />}
|
||||
className='max-sm:is-full'
|
||||
>
|
||||
Ekspor
|
||||
</Button>
|
||||
<Button
|
||||
variant='contained'
|
||||
startIcon={<i className='tabler-plus' />}
|
||||
onClick={() => setAddGameOpen(!addGameOpen)}
|
||||
className='max-sm:is-full'
|
||||
>
|
||||
Tambah Game
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className='overflow-x-auto'>
|
||||
{isLoading ? (
|
||||
<Loading />
|
||||
) : (
|
||||
<table className={tableStyles.table}>
|
||||
<thead>
|
||||
{table.getHeaderGroups().map(headerGroup => (
|
||||
<tr key={headerGroup.id}>
|
||||
{headerGroup.headers.map(header => (
|
||||
<th key={header.id}>
|
||||
{header.isPlaceholder ? null : (
|
||||
<>
|
||||
<div
|
||||
className={classnames({
|
||||
'flex items-center': header.column.getIsSorted(),
|
||||
'cursor-pointer select-none': header.column.getCanSort()
|
||||
})}
|
||||
onClick={header.column.getToggleSortingHandler()}
|
||||
>
|
||||
{flexRender(header.column.columnDef.header, header.getContext())}
|
||||
{{
|
||||
asc: <i className='tabler-chevron-up text-xl' />,
|
||||
desc: <i className='tabler-chevron-down text-xl' />
|
||||
}[header.column.getIsSorted() as 'asc' | 'desc'] ?? null}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
{table.getFilteredRowModel().rows.length === 0 ? (
|
||||
<tbody>
|
||||
<tr>
|
||||
<td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
|
||||
Tidak ada data tersedia
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
) : (
|
||||
<tbody>
|
||||
{table
|
||||
.getRowModel()
|
||||
.rows.slice(0, table.getState().pagination.pageSize)
|
||||
.map(row => {
|
||||
return (
|
||||
<tr key={row.id} className={classnames({ selected: row.getIsSelected() })}>
|
||||
{row.getVisibleCells().map(cell => (
|
||||
<td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
|
||||
))}
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
)}
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
<TablePagination
|
||||
component={() => (
|
||||
<TablePaginationComponent
|
||||
pageIndex={currentPage}
|
||||
pageSize={pageSize}
|
||||
totalCount={totalCount}
|
||||
onPageChange={handlePageChange}
|
||||
/>
|
||||
)}
|
||||
count={totalCount}
|
||||
rowsPerPage={pageSize}
|
||||
page={currentPage}
|
||||
onPageChange={handlePageChange}
|
||||
onRowsPerPageChange={handlePageSizeChange}
|
||||
rowsPerPageOptions={[10, 25, 50]}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{/* Add/Edit Game Drawer */}
|
||||
<AddEditGamesDrawer open={addGameOpen} handleClose={handleCloseGameDrawer} data={editGameData} />
|
||||
|
||||
{/* Delete Game Dialog */}
|
||||
<DeleteGameDialog
|
||||
open={deleteDialogOpen}
|
||||
onClose={handleCloseDeleteDialog}
|
||||
onConfirm={handleConfirmDelete}
|
||||
game={gameToDelete}
|
||||
isDeleting={deleteGame.isPending}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default GameListTable
|
||||
@@ -0,0 +1,17 @@
|
||||
// MUI Imports
|
||||
import Grid from '@mui/material/Grid2'
|
||||
import GameListTable from './GameListTable'
|
||||
|
||||
// Type Imports
|
||||
|
||||
const GamesList = () => {
|
||||
return (
|
||||
<Grid container spacing={6}>
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<GameListTable />
|
||||
</Grid>
|
||||
</Grid>
|
||||
)
|
||||
}
|
||||
|
||||
export default GamesList
|
||||
@@ -0,0 +1,513 @@
|
||||
// React Imports
|
||||
import { useState, useEffect } from 'react'
|
||||
|
||||
// MUI Imports
|
||||
import Button from '@mui/material/Button'
|
||||
import Drawer from '@mui/material/Drawer'
|
||||
import IconButton from '@mui/material/IconButton'
|
||||
import MenuItem from '@mui/material/MenuItem'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import Divider from '@mui/material/Divider'
|
||||
import Grid from '@mui/material/Grid2'
|
||||
import Box from '@mui/material/Box'
|
||||
import Switch from '@mui/material/Switch'
|
||||
import FormControlLabel from '@mui/material/FormControlLabel'
|
||||
import Chip from '@mui/material/Chip'
|
||||
import InputAdornment from '@mui/material/InputAdornment'
|
||||
import Alert from '@mui/material/Alert'
|
||||
|
||||
// Third-party Imports
|
||||
import { useForm, Controller } from 'react-hook-form'
|
||||
|
||||
// Component Imports
|
||||
import CustomTextField from '@core/components/mui/TextField'
|
||||
|
||||
// Types
|
||||
export interface WheelSpinType {
|
||||
id: string
|
||||
name: string
|
||||
weight: number
|
||||
omset: number
|
||||
fallback: boolean
|
||||
stock?: number
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}
|
||||
|
||||
export interface WheelSpinRequest {
|
||||
name: string
|
||||
weight: number
|
||||
omset: number
|
||||
fallback: boolean
|
||||
stock?: number
|
||||
description?: string
|
||||
isActive?: boolean
|
||||
}
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
handleClose: () => void
|
||||
data?: WheelSpinType // Data wheel spin untuk edit (jika ada)
|
||||
}
|
||||
|
||||
type FormValidateType = {
|
||||
name: string
|
||||
weight: number
|
||||
omset: number
|
||||
fallback: boolean
|
||||
stock?: number
|
||||
description: string
|
||||
isActive: boolean
|
||||
}
|
||||
|
||||
// Initial form data
|
||||
const initialData: FormValidateType = {
|
||||
name: '',
|
||||
weight: 10,
|
||||
omset: 0,
|
||||
fallback: false,
|
||||
stock: undefined,
|
||||
description: '',
|
||||
isActive: true
|
||||
}
|
||||
|
||||
// Mock mutation hooks (replace with actual hooks)
|
||||
const useWheelSpinMutation = () => {
|
||||
const createWheelSpin = {
|
||||
mutate: (data: WheelSpinRequest, options?: { onSuccess?: () => void }) => {
|
||||
console.log('Creating wheel spin:', data)
|
||||
setTimeout(() => options?.onSuccess?.(), 1000)
|
||||
}
|
||||
}
|
||||
|
||||
const updateWheelSpin = {
|
||||
mutate: (data: { id: string; payload: WheelSpinRequest }, options?: { onSuccess?: () => void }) => {
|
||||
console.log('Updating wheel spin:', data)
|
||||
setTimeout(() => options?.onSuccess?.(), 1000)
|
||||
}
|
||||
}
|
||||
|
||||
return { createWheelSpin, updateWheelSpin }
|
||||
}
|
||||
|
||||
const AddEditWheelSpinDrawer = (props: Props) => {
|
||||
// Props
|
||||
const { open, handleClose, data } = props
|
||||
|
||||
// States
|
||||
const [showMore, setShowMore] = useState(false)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [hasStock, setHasStock] = useState(false)
|
||||
|
||||
const { createWheelSpin, updateWheelSpin } = useWheelSpinMutation()
|
||||
|
||||
// Determine if this is edit mode
|
||||
const isEditMode = Boolean(data?.id)
|
||||
|
||||
// Hooks
|
||||
const {
|
||||
control,
|
||||
reset: resetForm,
|
||||
handleSubmit,
|
||||
watch,
|
||||
setValue,
|
||||
formState: { errors }
|
||||
} = useForm<FormValidateType>({
|
||||
defaultValues: initialData
|
||||
})
|
||||
|
||||
const watchedFallback = watch('fallback')
|
||||
const watchedStock = watch('stock')
|
||||
const watchedWeight = watch('weight')
|
||||
|
||||
// Effect to populate form when editing
|
||||
useEffect(() => {
|
||||
if (isEditMode && data) {
|
||||
// Populate form with existing data
|
||||
const formData: FormValidateType = {
|
||||
name: data.name || '',
|
||||
weight: data.weight || 10,
|
||||
omset: data.omset || 0,
|
||||
fallback: data.fallback || false,
|
||||
stock: data.stock,
|
||||
description: '', // Add description field if available in your data
|
||||
isActive: true // Add isActive field if available in your data
|
||||
}
|
||||
|
||||
resetForm(formData)
|
||||
setHasStock(data.stock !== undefined)
|
||||
setShowMore(true) // Always show more for edit mode
|
||||
} else {
|
||||
// Reset to initial data for add mode
|
||||
resetForm(initialData)
|
||||
setHasStock(false)
|
||||
setShowMore(false)
|
||||
}
|
||||
}, [data, isEditMode, resetForm])
|
||||
|
||||
// Handle stock toggle
|
||||
const handleStockToggle = (checked: boolean) => {
|
||||
setHasStock(checked)
|
||||
if (!checked) {
|
||||
setValue('stock', undefined)
|
||||
} else {
|
||||
setValue('stock', 0)
|
||||
}
|
||||
}
|
||||
|
||||
const handleFormSubmit = async (formData: FormValidateType) => {
|
||||
try {
|
||||
setIsSubmitting(true)
|
||||
|
||||
// Create WheelSpinRequest object
|
||||
const wheelSpinRequest: WheelSpinRequest = {
|
||||
name: formData.name,
|
||||
weight: formData.weight,
|
||||
omset: formData.omset,
|
||||
fallback: formData.fallback,
|
||||
stock: hasStock ? formData.stock : undefined,
|
||||
description: formData.description || undefined,
|
||||
isActive: formData.isActive
|
||||
}
|
||||
|
||||
if (isEditMode && data?.id) {
|
||||
// Update existing wheel spin
|
||||
updateWheelSpin.mutate(
|
||||
{ id: data.id, payload: wheelSpinRequest },
|
||||
{
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
handleClose()
|
||||
}
|
||||
}
|
||||
)
|
||||
} else {
|
||||
// Create new wheel spin
|
||||
createWheelSpin.mutate(wheelSpinRequest, {
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
handleClose()
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error submitting wheel spin:', error)
|
||||
// Handle error (show toast, etc.)
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleReset = () => {
|
||||
handleClose()
|
||||
resetForm(initialData)
|
||||
setShowMore(false)
|
||||
setHasStock(false)
|
||||
}
|
||||
|
||||
const formatCurrency = (value: number) => {
|
||||
return new Intl.NumberFormat('id-ID', {
|
||||
style: 'currency',
|
||||
currency: 'IDR',
|
||||
minimumFractionDigits: 0
|
||||
}).format(value)
|
||||
}
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
open={open}
|
||||
anchor='right'
|
||||
variant='temporary'
|
||||
onClose={handleReset}
|
||||
ModalProps={{ keepMounted: true }}
|
||||
sx={{
|
||||
'& .MuiDrawer-paper': {
|
||||
width: { xs: 300, sm: 400 },
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
height: '100%'
|
||||
}
|
||||
}}
|
||||
>
|
||||
{/* Sticky Header */}
|
||||
<Box
|
||||
sx={{
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
zIndex: 10,
|
||||
backgroundColor: 'background.paper',
|
||||
borderBottom: 1,
|
||||
borderColor: 'divider'
|
||||
}}
|
||||
>
|
||||
<div className='flex items-center justify-between plb-5 pli-6'>
|
||||
<Typography variant='h5'>{isEditMode ? 'Edit Hadiah Wheel Spin' : 'Tambah Hadiah Baru'}</Typography>
|
||||
<IconButton size='small' onClick={handleReset}>
|
||||
<i className='tabler-x text-2xl text-textPrimary' />
|
||||
</IconButton>
|
||||
</div>
|
||||
</Box>
|
||||
|
||||
{/* Scrollable Content */}
|
||||
<Box sx={{ flex: 1, overflowY: 'auto' }}>
|
||||
<form id='wheel-spin-form' onSubmit={handleSubmit(handleFormSubmit)}>
|
||||
<div className='flex flex-col gap-6 p-6'>
|
||||
{/* Nama Hadiah */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Nama Hadiah <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='name'
|
||||
control={control}
|
||||
rules={{ required: 'Nama hadiah wajib diisi' }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='Masukkan nama hadiah'
|
||||
error={!!errors.name}
|
||||
helperText={errors.name?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Weight */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Bobot Kemunculan <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='weight'
|
||||
control={control}
|
||||
rules={{
|
||||
required: 'Bobot wajib diisi',
|
||||
min: {
|
||||
value: 1,
|
||||
message: 'Bobot minimal 1%'
|
||||
},
|
||||
max: {
|
||||
value: 100,
|
||||
message: 'Bobot maksimal 100%'
|
||||
}
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='number'
|
||||
placeholder='10'
|
||||
error={!!errors.weight}
|
||||
helperText={errors.weight?.message || `Peluang kemunculan: ${watchedWeight}%`}
|
||||
InputProps={{
|
||||
endAdornment: <InputAdornment position='end'>%</InputAdornment>
|
||||
}}
|
||||
onChange={e => field.onChange(Number(e.target.value))}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Minimum Omset */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Minimum Omset <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='omset'
|
||||
control={control}
|
||||
rules={{
|
||||
required: 'Minimum omset wajib diisi',
|
||||
min: {
|
||||
value: 0,
|
||||
message: 'Minimum omset tidak boleh negatif'
|
||||
}
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='number'
|
||||
placeholder='0'
|
||||
error={!!errors.omset}
|
||||
helperText={
|
||||
errors.omset?.message ||
|
||||
(field.value > 0 ? formatCurrency(field.value) : 'Omset minimum untuk mendapatkan hadiah ini')
|
||||
}
|
||||
InputProps={{
|
||||
startAdornment: <InputAdornment position='start'>Rp</InputAdornment>
|
||||
}}
|
||||
onChange={e => field.onChange(Number(e.target.value))}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Fallback Option */}
|
||||
<div>
|
||||
<Controller
|
||||
name='fallback'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<FormControlLabel
|
||||
control={<Switch checked={field.value} onChange={field.onChange} color='warning' />}
|
||||
label='Hadiah Fallback'
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{watchedFallback && (
|
||||
<Alert severity='info' sx={{ mt: 1 }}>
|
||||
Hadiah fallback akan muncul ketika hadiah lain tidak tersedia atau habis
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Stock Management */}
|
||||
<div>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Switch checked={hasStock} onChange={e => handleStockToggle(e.target.checked)} color='primary' />
|
||||
}
|
||||
label='Batasi Stok'
|
||||
/>
|
||||
|
||||
{hasStock && (
|
||||
<div className='mt-3'>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Jumlah Stok <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='stock'
|
||||
control={control}
|
||||
rules={
|
||||
hasStock
|
||||
? {
|
||||
required: 'Jumlah stok wajib diisi',
|
||||
min: {
|
||||
value: 0,
|
||||
message: 'Stok tidak boleh negatif'
|
||||
}
|
||||
}
|
||||
: {}
|
||||
}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='number'
|
||||
placeholder='0'
|
||||
error={!!errors.stock}
|
||||
helperText={errors.stock?.message || 'Kosongkan untuk stok unlimited'}
|
||||
onChange={e => field.onChange(Number(e.target.value))}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Status Aktif */}
|
||||
<div>
|
||||
<Controller
|
||||
name='isActive'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<FormControlLabel
|
||||
control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
|
||||
label='Hadiah Aktif'
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Tampilkan selengkapnya */}
|
||||
{!showMore && (
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
size='small'
|
||||
sx={{ textTransform: 'none', fontSize: '14px', p: 0, textAlign: 'left', width: '200px' }}
|
||||
onClick={() => setShowMore(true)}
|
||||
>
|
||||
+ Tampilkan selengkapnya
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Konten tambahan */}
|
||||
{showMore && (
|
||||
<>
|
||||
{/* Description */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Deskripsi Hadiah
|
||||
</Typography>
|
||||
<Controller
|
||||
name='description'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='Deskripsi detail tentang hadiah ini'
|
||||
multiline
|
||||
rows={4}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Tips */}
|
||||
<Alert severity='info'>
|
||||
<Typography variant='body2'>
|
||||
<strong>Tips:</strong>
|
||||
<br />
|
||||
• Bobot yang lebih tinggi = peluang menang lebih besar
|
||||
<br />
|
||||
• Hadiah fallback sebaiknya selalu ada untuk backup
|
||||
<br />• Minimum omset membantu mendorong transaksi lebih besar
|
||||
</Typography>
|
||||
</Alert>
|
||||
|
||||
{/* Sembunyikan */}
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
size='small'
|
||||
sx={{ textTransform: 'none', fontSize: '14px', p: 0, textAlign: 'left', width: '200px' }}
|
||||
onClick={() => setShowMore(false)}
|
||||
>
|
||||
- Sembunyikan
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</Box>
|
||||
|
||||
{/* Sticky Footer */}
|
||||
<Box
|
||||
sx={{
|
||||
position: 'sticky',
|
||||
bottom: 0,
|
||||
zIndex: 10,
|
||||
backgroundColor: 'background.paper',
|
||||
borderTop: 1,
|
||||
borderColor: 'divider',
|
||||
p: 3
|
||||
}}
|
||||
>
|
||||
<div className='flex items-center gap-4'>
|
||||
<Button variant='contained' type='submit' form='wheel-spin-form' disabled={isSubmitting}>
|
||||
{isSubmitting ? (isEditMode ? 'Mengupdate...' : 'Menyimpan...') : isEditMode ? 'Update' : 'Simpan'}
|
||||
</Button>
|
||||
<Button variant='outlined' color='error' onClick={handleReset} disabled={isSubmitting}>
|
||||
Batal
|
||||
</Button>
|
||||
</div>
|
||||
</Box>
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
|
||||
export default AddEditWheelSpinDrawer
|
||||
@@ -0,0 +1,599 @@
|
||||
'use client'
|
||||
|
||||
// React Imports
|
||||
import { useEffect, useState, useMemo, useCallback } from 'react'
|
||||
|
||||
// Next Imports
|
||||
import Link from 'next/link'
|
||||
import { useParams } from 'next/navigation'
|
||||
|
||||
// MUI Imports
|
||||
import Card from '@mui/material/Card'
|
||||
import CardHeader from '@mui/material/CardHeader'
|
||||
import Button from '@mui/material/Button'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import Chip from '@mui/material/Chip'
|
||||
import Checkbox from '@mui/material/Checkbox'
|
||||
import IconButton from '@mui/material/IconButton'
|
||||
import { styled } from '@mui/material/styles'
|
||||
import TablePagination from '@mui/material/TablePagination'
|
||||
import type { TextFieldProps } from '@mui/material/TextField'
|
||||
import MenuItem from '@mui/material/MenuItem'
|
||||
|
||||
// Third-party Imports
|
||||
import classnames from 'classnames'
|
||||
import { rankItem } from '@tanstack/match-sorter-utils'
|
||||
import {
|
||||
createColumnHelper,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
useReactTable,
|
||||
getFilteredRowModel,
|
||||
getFacetedRowModel,
|
||||
getFacetedUniqueValues,
|
||||
getFacetedMinMaxValues,
|
||||
getPaginationRowModel,
|
||||
getSortedRowModel
|
||||
} from '@tanstack/react-table'
|
||||
import type { ColumnDef, FilterFn } from '@tanstack/react-table'
|
||||
import type { RankingInfo } from '@tanstack/match-sorter-utils'
|
||||
|
||||
// Type Imports
|
||||
import type { ThemeColor } from '@core/types'
|
||||
import type { Locale } from '@configs/i18n'
|
||||
|
||||
// Component Imports
|
||||
import OptionMenu from '@core/components/option-menu'
|
||||
import TablePaginationComponent from '@components/TablePaginationComponent'
|
||||
import CustomTextField from '@core/components/mui/TextField'
|
||||
import CustomAvatar from '@core/components/mui/Avatar'
|
||||
|
||||
// Util Imports
|
||||
import { getInitials } from '@/utils/getInitials'
|
||||
import { getLocalizedUrl } from '@/utils/i18n'
|
||||
import { formatCurrency } from '@/utils/transform'
|
||||
|
||||
// Style Imports
|
||||
import tableStyles from '@core/styles/table.module.css'
|
||||
import Loading from '@/components/layout/shared/Loading'
|
||||
import AddEditWheelSpinDrawer from './AddEditWheelSpinDrawer'
|
||||
|
||||
// WheelSpin Type Interface
|
||||
export interface WheelSpinType {
|
||||
id: string
|
||||
name: string
|
||||
weight: number
|
||||
omset: number
|
||||
fallback: boolean
|
||||
stock?: number
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}
|
||||
|
||||
declare module '@tanstack/table-core' {
|
||||
interface FilterFns {
|
||||
fuzzy: FilterFn<unknown>
|
||||
}
|
||||
interface FilterMeta {
|
||||
itemRank: RankingInfo
|
||||
}
|
||||
}
|
||||
|
||||
type WheelSpinTypeWithAction = WheelSpinType & {
|
||||
action?: string
|
||||
}
|
||||
|
||||
// Styled Components
|
||||
const Icon = styled('i')({})
|
||||
|
||||
const fuzzyFilter: FilterFn<any> = (row, columnId, value, addMeta) => {
|
||||
// Rank the item
|
||||
const itemRank = rankItem(row.getValue(columnId), value)
|
||||
|
||||
// Store the itemRank info
|
||||
addMeta({
|
||||
itemRank
|
||||
})
|
||||
|
||||
// Return if the item should be filtered in/out
|
||||
return itemRank.passed
|
||||
}
|
||||
|
||||
const DebouncedInput = ({
|
||||
value: initialValue,
|
||||
onChange,
|
||||
debounce = 500,
|
||||
...props
|
||||
}: {
|
||||
value: string | number
|
||||
onChange: (value: string | number) => void
|
||||
debounce?: number
|
||||
} & Omit<TextFieldProps, 'onChange'>) => {
|
||||
// States
|
||||
const [value, setValue] = useState(initialValue)
|
||||
|
||||
useEffect(() => {
|
||||
setValue(initialValue)
|
||||
}, [initialValue])
|
||||
|
||||
useEffect(() => {
|
||||
const timeout = setTimeout(() => {
|
||||
onChange(value)
|
||||
}, debounce)
|
||||
|
||||
return () => clearTimeout(timeout)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [value])
|
||||
|
||||
return <CustomTextField {...props} value={value} onChange={e => setValue(e.target.value)} />
|
||||
}
|
||||
|
||||
// Dummy data for wheel spin prizes
|
||||
const DUMMY_WHEEL_SPIN_DATA: WheelSpinType[] = [
|
||||
{
|
||||
id: '1',
|
||||
name: 'Diskon 10%',
|
||||
weight: 25,
|
||||
omset: 500000,
|
||||
fallback: false,
|
||||
stock: 100,
|
||||
createdAt: new Date('2024-01-15'),
|
||||
updatedAt: new Date('2024-02-10')
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
name: 'Gratis Ongkir',
|
||||
weight: 30,
|
||||
omset: 200000,
|
||||
fallback: false,
|
||||
stock: 200,
|
||||
createdAt: new Date('2024-01-20'),
|
||||
updatedAt: new Date('2024-02-15')
|
||||
},
|
||||
{
|
||||
id: '3',
|
||||
name: 'Cashback 50k',
|
||||
weight: 15,
|
||||
omset: 1000000,
|
||||
fallback: false,
|
||||
stock: 50,
|
||||
createdAt: new Date('2024-01-25'),
|
||||
updatedAt: new Date('2024-02-20')
|
||||
},
|
||||
{
|
||||
id: '4',
|
||||
name: 'Voucher 100k',
|
||||
weight: 10,
|
||||
omset: 2000000,
|
||||
fallback: false,
|
||||
stock: 25,
|
||||
createdAt: new Date('2024-02-01'),
|
||||
updatedAt: new Date('2024-02-25')
|
||||
},
|
||||
{
|
||||
id: '5',
|
||||
name: 'Poin 500',
|
||||
weight: 35,
|
||||
omset: 100000,
|
||||
fallback: false,
|
||||
stock: 500,
|
||||
createdAt: new Date('2024-02-05'),
|
||||
updatedAt: new Date('2024-03-01')
|
||||
},
|
||||
{
|
||||
id: '6',
|
||||
name: 'Produk Gratis',
|
||||
weight: 5,
|
||||
omset: 5000000,
|
||||
fallback: false,
|
||||
stock: 10,
|
||||
createdAt: new Date('2024-02-10'),
|
||||
updatedAt: new Date('2024-03-05')
|
||||
},
|
||||
{
|
||||
id: '7',
|
||||
name: 'Coba Lagi',
|
||||
weight: 50,
|
||||
omset: 0,
|
||||
fallback: true,
|
||||
createdAt: new Date('2024-02-15'),
|
||||
updatedAt: new Date('2024-03-10')
|
||||
},
|
||||
{
|
||||
id: '8',
|
||||
name: 'Double Poin',
|
||||
weight: 20,
|
||||
omset: 750000,
|
||||
fallback: false,
|
||||
stock: 75,
|
||||
createdAt: new Date('2024-03-01'),
|
||||
updatedAt: new Date('2024-03-15')
|
||||
},
|
||||
{
|
||||
id: '9',
|
||||
name: 'Mystery Box',
|
||||
weight: 8,
|
||||
omset: 1500000,
|
||||
fallback: false,
|
||||
stock: 30,
|
||||
createdAt: new Date('2024-03-05'),
|
||||
updatedAt: new Date('2024-03-20')
|
||||
},
|
||||
{
|
||||
id: '10',
|
||||
name: 'Diskon 25%',
|
||||
weight: 12,
|
||||
omset: 3000000,
|
||||
fallback: false,
|
||||
stock: 20,
|
||||
createdAt: new Date('2024-03-10'),
|
||||
updatedAt: new Date('2024-03-25')
|
||||
}
|
||||
]
|
||||
|
||||
// Mock data hook with dummy data
|
||||
const useWheelSpin = ({ page, limit, search }: { page: number; limit: number; search: string }) => {
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
// Simulate loading
|
||||
useEffect(() => {
|
||||
setIsLoading(true)
|
||||
const timer = setTimeout(() => setIsLoading(false), 500)
|
||||
return () => clearTimeout(timer)
|
||||
}, [page, limit, search])
|
||||
|
||||
// Filter data based on search
|
||||
const filteredData = useMemo(() => {
|
||||
if (!search) return DUMMY_WHEEL_SPIN_DATA
|
||||
|
||||
return DUMMY_WHEEL_SPIN_DATA.filter(wheelSpin => wheelSpin.name.toLowerCase().includes(search.toLowerCase()))
|
||||
}, [search])
|
||||
|
||||
// Paginate data
|
||||
const paginatedData = useMemo(() => {
|
||||
const startIndex = (page - 1) * limit
|
||||
const endIndex = startIndex + limit
|
||||
return filteredData.slice(startIndex, endIndex)
|
||||
}, [filteredData, page, limit])
|
||||
|
||||
return {
|
||||
data: {
|
||||
wheelSpins: paginatedData,
|
||||
total_count: filteredData.length
|
||||
},
|
||||
isLoading,
|
||||
error: null,
|
||||
isFetching: isLoading
|
||||
}
|
||||
}
|
||||
|
||||
// Column Definitions
|
||||
const columnHelper = createColumnHelper<WheelSpinTypeWithAction>()
|
||||
|
||||
const WheelSpinListTable = () => {
|
||||
// States
|
||||
const [addWheelSpinOpen, setAddWheelSpinOpen] = useState(false)
|
||||
const [editWheelSpinData, setEditWheelSpinData] = useState<WheelSpinType | undefined>(undefined)
|
||||
const [rowSelection, setRowSelection] = useState({})
|
||||
const [globalFilter, setGlobalFilter] = useState('')
|
||||
const [currentPage, setCurrentPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(10)
|
||||
const [search, setSearch] = useState('')
|
||||
|
||||
const { data, isLoading, error, isFetching } = useWheelSpin({
|
||||
page: currentPage,
|
||||
limit: pageSize,
|
||||
search
|
||||
})
|
||||
|
||||
const wheelSpins = data?.wheelSpins ?? []
|
||||
const totalCount = data?.total_count ?? 0
|
||||
|
||||
// Hooks
|
||||
const { lang: locale } = useParams()
|
||||
|
||||
const handlePageChange = useCallback((event: unknown, newPage: number) => {
|
||||
setCurrentPage(newPage)
|
||||
}, [])
|
||||
|
||||
const handlePageSizeChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newPageSize = parseInt(event.target.value, 10)
|
||||
setPageSize(newPageSize)
|
||||
setCurrentPage(1) // Reset to first page
|
||||
}, [])
|
||||
|
||||
const handleEditWheelSpin = (wheelSpin: WheelSpinType) => {
|
||||
setEditWheelSpinData(wheelSpin)
|
||||
setAddWheelSpinOpen(true)
|
||||
}
|
||||
|
||||
const handleDeleteWheelSpin = (wheelSpinId: string) => {
|
||||
if (confirm('Apakah Anda yakin ingin menghapus hadiah wheel spin ini?')) {
|
||||
console.log('Deleting wheel spin:', wheelSpinId)
|
||||
// Add your delete logic here
|
||||
// deleteWheelSpin.mutate(wheelSpinId)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCloseWheelSpinDrawer = () => {
|
||||
setAddWheelSpinOpen(false)
|
||||
setEditWheelSpinData(undefined)
|
||||
}
|
||||
|
||||
const columns = useMemo<ColumnDef<WheelSpinTypeWithAction, any>[]>(
|
||||
() => [
|
||||
{
|
||||
id: 'select',
|
||||
header: ({ table }) => (
|
||||
<Checkbox
|
||||
{...{
|
||||
checked: table.getIsAllRowsSelected(),
|
||||
indeterminate: table.getIsSomeRowsSelected(),
|
||||
onChange: table.getToggleAllRowsSelectedHandler()
|
||||
}}
|
||||
/>
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<Checkbox
|
||||
{...{
|
||||
checked: row.getIsSelected(),
|
||||
disabled: !row.getCanSelect(),
|
||||
indeterminate: row.getIsSomeSelected(),
|
||||
onChange: row.getToggleSelectedHandler()
|
||||
}}
|
||||
/>
|
||||
)
|
||||
},
|
||||
columnHelper.accessor('name', {
|
||||
header: 'Nama Hadiah',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-4'>
|
||||
<div className='flex flex-col'>
|
||||
<Link href={getLocalizedUrl(`/apps/wheel-spin/${row.original.id}/detail`, locale as Locale)}>
|
||||
<Typography className='font-medium cursor-pointer hover:underline text-primary'>
|
||||
{row.original.name}
|
||||
</Typography>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('weight', {
|
||||
header: 'Bobot',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-2'>
|
||||
<Icon className='tabler-percentage' sx={{ color: 'var(--mui-palette-primary-main)' }} />
|
||||
<Typography color='text.primary'>{row.original.weight}%</Typography>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('omset', {
|
||||
header: 'Min. Omset',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-2'>
|
||||
<Icon className='tabler-coin' sx={{ color: 'var(--mui-palette-success-main)' }} />
|
||||
<Typography color='text.primary'>{formatCurrency(row.original.omset)}</Typography>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('stock', {
|
||||
header: 'Stok',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-2'>
|
||||
{row.original.stock !== undefined ? (
|
||||
<>
|
||||
<Icon className='tabler-package' sx={{ color: 'var(--mui-palette-info-main)' }} />
|
||||
<Typography color='text.primary'>{row.original.stock}</Typography>
|
||||
</>
|
||||
) : (
|
||||
<Typography color='text.secondary'>Unlimited</Typography>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('fallback', {
|
||||
header: 'Status',
|
||||
cell: ({ row }) => (
|
||||
<Chip
|
||||
label={row.original.fallback ? 'Fallback' : 'Aktif'}
|
||||
color={row.original.fallback ? 'warning' : 'success'}
|
||||
variant='tonal'
|
||||
size='small'
|
||||
/>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('createdAt', {
|
||||
header: 'Tanggal Dibuat',
|
||||
cell: ({ row }) => (
|
||||
<Typography color='text.primary'>
|
||||
{new Date(row.original.createdAt).toLocaleDateString('id-ID', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
})}
|
||||
</Typography>
|
||||
)
|
||||
}),
|
||||
{
|
||||
id: 'actions',
|
||||
header: 'Aksi',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center'>
|
||||
<OptionMenu
|
||||
iconButtonProps={{ size: 'medium' }}
|
||||
iconClassName='text-textSecondary text-[22px]'
|
||||
options={[
|
||||
{
|
||||
text: 'Edit',
|
||||
icon: 'tabler-edit text-[22px]',
|
||||
menuItemProps: {
|
||||
className: 'flex items-center gap-2 text-textSecondary',
|
||||
onClick: () => handleEditWheelSpin(row.original)
|
||||
}
|
||||
},
|
||||
{
|
||||
text: 'Hapus',
|
||||
icon: 'tabler-trash text-[22px]',
|
||||
menuItemProps: {
|
||||
className: 'flex items-center gap-2 text-textSecondary',
|
||||
onClick: () => handleDeleteWheelSpin(row.original.id)
|
||||
}
|
||||
}
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
enableSorting: false
|
||||
}
|
||||
],
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[locale, handleEditWheelSpin, handleDeleteWheelSpin]
|
||||
)
|
||||
|
||||
const table = useReactTable({
|
||||
data: wheelSpins as WheelSpinType[],
|
||||
columns,
|
||||
filterFns: {
|
||||
fuzzy: fuzzyFilter
|
||||
},
|
||||
state: {
|
||||
rowSelection,
|
||||
globalFilter,
|
||||
pagination: {
|
||||
pageIndex: currentPage,
|
||||
pageSize
|
||||
}
|
||||
},
|
||||
enableRowSelection: true,
|
||||
onRowSelectionChange: setRowSelection,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
manualPagination: true,
|
||||
pageCount: Math.ceil(totalCount / pageSize)
|
||||
})
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card>
|
||||
<div className='flex justify-between flex-col items-start md:flex-row md:items-center p-6 border-bs gap-4'>
|
||||
<CustomTextField
|
||||
select
|
||||
value={table.getState().pagination.pageSize}
|
||||
onChange={e => table.setPageSize(Number(e.target.value))}
|
||||
className='max-sm:is-full sm:is-[70px]'
|
||||
>
|
||||
<MenuItem value='10'>10</MenuItem>
|
||||
<MenuItem value='25'>25</MenuItem>
|
||||
<MenuItem value='50'>50</MenuItem>
|
||||
</CustomTextField>
|
||||
<div className='flex flex-col sm:flex-row max-sm:is-full items-start sm:items-center gap-4'>
|
||||
<DebouncedInput
|
||||
value={search ?? ''}
|
||||
onChange={value => setSearch(value as string)}
|
||||
placeholder='Cari Hadiah Wheel Spin'
|
||||
className='max-sm:is-full'
|
||||
/>
|
||||
<Button
|
||||
color='secondary'
|
||||
variant='tonal'
|
||||
startIcon={<i className='tabler-upload' />}
|
||||
className='max-sm:is-full'
|
||||
>
|
||||
Ekspor
|
||||
</Button>
|
||||
<Button
|
||||
variant='contained'
|
||||
startIcon={<i className='tabler-plus' />}
|
||||
onClick={() => setAddWheelSpinOpen(!addWheelSpinOpen)}
|
||||
className='max-sm:is-full'
|
||||
>
|
||||
Tambah Hadiah
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className='overflow-x-auto'>
|
||||
{isLoading ? (
|
||||
<Loading />
|
||||
) : (
|
||||
<table className={tableStyles.table}>
|
||||
<thead>
|
||||
{table.getHeaderGroups().map(headerGroup => (
|
||||
<tr key={headerGroup.id}>
|
||||
{headerGroup.headers.map(header => (
|
||||
<th key={header.id}>
|
||||
{header.isPlaceholder ? null : (
|
||||
<>
|
||||
<div
|
||||
className={classnames({
|
||||
'flex items-center': header.column.getIsSorted(),
|
||||
'cursor-pointer select-none': header.column.getCanSort()
|
||||
})}
|
||||
onClick={header.column.getToggleSortingHandler()}
|
||||
>
|
||||
{flexRender(header.column.columnDef.header, header.getContext())}
|
||||
{{
|
||||
asc: <i className='tabler-chevron-up text-xl' />,
|
||||
desc: <i className='tabler-chevron-down text-xl' />
|
||||
}[header.column.getIsSorted() as 'asc' | 'desc'] ?? null}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
{table.getFilteredRowModel().rows.length === 0 ? (
|
||||
<tbody>
|
||||
<tr>
|
||||
<td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
|
||||
Tidak ada data tersedia
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
) : (
|
||||
<tbody>
|
||||
{table
|
||||
.getRowModel()
|
||||
.rows.slice(0, table.getState().pagination.pageSize)
|
||||
.map(row => {
|
||||
return (
|
||||
<tr key={row.id} className={classnames({ selected: row.getIsSelected() })}>
|
||||
{row.getVisibleCells().map(cell => (
|
||||
<td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
|
||||
))}
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
)}
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
<TablePagination
|
||||
component={() => (
|
||||
<TablePaginationComponent
|
||||
pageIndex={currentPage}
|
||||
pageSize={pageSize}
|
||||
totalCount={totalCount}
|
||||
onPageChange={handlePageChange}
|
||||
/>
|
||||
)}
|
||||
count={totalCount}
|
||||
rowsPerPage={pageSize}
|
||||
page={currentPage}
|
||||
onPageChange={handlePageChange}
|
||||
onRowsPerPageChange={handlePageSizeChange}
|
||||
rowsPerPageOptions={[10, 25, 50]}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</Card>
|
||||
<AddEditWheelSpinDrawer
|
||||
open={addWheelSpinOpen}
|
||||
handleClose={handleCloseWheelSpinDrawer}
|
||||
data={editWheelSpinData}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default WheelSpinListTable
|
||||
@@ -0,0 +1,17 @@
|
||||
// MUI Imports
|
||||
import Grid from '@mui/material/Grid2'
|
||||
import WheelSpinListTable from './WheelSpinListTable'
|
||||
|
||||
// Type Imports
|
||||
|
||||
const WheelSpinList = () => {
|
||||
return (
|
||||
<Grid container spacing={6}>
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<WheelSpinListTable />
|
||||
</Grid>
|
||||
</Grid>
|
||||
)
|
||||
}
|
||||
|
||||
export default WheelSpinList
|
||||
@@ -0,0 +1,495 @@
|
||||
// React Imports
|
||||
import { useState, useEffect } from 'react'
|
||||
|
||||
// MUI Imports
|
||||
import Button from '@mui/material/Button'
|
||||
import Drawer from '@mui/material/Drawer'
|
||||
import IconButton from '@mui/material/IconButton'
|
||||
import MenuItem from '@mui/material/MenuItem'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import Divider from '@mui/material/Divider'
|
||||
import Grid from '@mui/material/Grid2'
|
||||
import Box from '@mui/material/Box'
|
||||
import Switch from '@mui/material/Switch'
|
||||
import FormControlLabel from '@mui/material/FormControlLabel'
|
||||
import Chip from '@mui/material/Chip'
|
||||
import InputAdornment from '@mui/material/InputAdornment'
|
||||
|
||||
// Third-party Imports
|
||||
import { useForm, Controller, useFieldArray } from 'react-hook-form'
|
||||
|
||||
// Component Imports
|
||||
import CustomTextField from '@core/components/mui/TextField'
|
||||
|
||||
// Types
|
||||
export interface LoyaltyType {
|
||||
id: string
|
||||
name: string
|
||||
minimumPurchase: number
|
||||
pointMultiplier: number
|
||||
benefits: string[]
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}
|
||||
|
||||
export interface LoyaltyRequest {
|
||||
name: string
|
||||
minimumPurchase: number
|
||||
pointMultiplier: number
|
||||
benefits: string[]
|
||||
description?: string
|
||||
isActive?: boolean
|
||||
}
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
handleClose: () => void
|
||||
data?: LoyaltyType // Data loyalty untuk edit (jika ada)
|
||||
}
|
||||
|
||||
type FormValidateType = {
|
||||
name: string
|
||||
minimumPurchase: number
|
||||
pointMultiplier: number
|
||||
benefits: string[]
|
||||
description: string
|
||||
isActive: boolean
|
||||
newBenefit: string // Temporary field for adding new benefits
|
||||
}
|
||||
|
||||
// Initial form data
|
||||
const initialData: FormValidateType = {
|
||||
name: '',
|
||||
minimumPurchase: 0,
|
||||
pointMultiplier: 1,
|
||||
benefits: [],
|
||||
description: '',
|
||||
isActive: true,
|
||||
newBenefit: ''
|
||||
}
|
||||
|
||||
// Mock mutation hooks (replace with actual hooks)
|
||||
const useLoyaltyMutation = () => {
|
||||
const createLoyalty = {
|
||||
mutate: (data: LoyaltyRequest, options?: { onSuccess?: () => void }) => {
|
||||
console.log('Creating loyalty:', data)
|
||||
setTimeout(() => options?.onSuccess?.(), 1000)
|
||||
}
|
||||
}
|
||||
|
||||
const updateLoyalty = {
|
||||
mutate: (data: { id: string; payload: LoyaltyRequest }, options?: { onSuccess?: () => void }) => {
|
||||
console.log('Updating loyalty:', data)
|
||||
setTimeout(() => options?.onSuccess?.(), 1000)
|
||||
}
|
||||
}
|
||||
|
||||
return { createLoyalty, updateLoyalty }
|
||||
}
|
||||
|
||||
const AddEditLoyaltyDrawer = (props: Props) => {
|
||||
// Props
|
||||
const { open, handleClose, data } = props
|
||||
|
||||
// States
|
||||
const [showMore, setShowMore] = useState(false)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
|
||||
const { createLoyalty, updateLoyalty } = useLoyaltyMutation()
|
||||
|
||||
// Determine if this is edit mode
|
||||
const isEditMode = Boolean(data?.id)
|
||||
|
||||
// Hooks
|
||||
const {
|
||||
control,
|
||||
reset: resetForm,
|
||||
handleSubmit,
|
||||
watch,
|
||||
setValue,
|
||||
formState: { errors }
|
||||
} = useForm<FormValidateType>({
|
||||
defaultValues: initialData
|
||||
})
|
||||
|
||||
const watchedBenefits = watch('benefits')
|
||||
const watchedNewBenefit = watch('newBenefit')
|
||||
|
||||
// Effect to populate form when editing
|
||||
useEffect(() => {
|
||||
if (isEditMode && data) {
|
||||
// Populate form with existing data
|
||||
const formData: FormValidateType = {
|
||||
name: data.name || '',
|
||||
minimumPurchase: data.minimumPurchase || 0,
|
||||
pointMultiplier: data.pointMultiplier || 1,
|
||||
benefits: data.benefits || [],
|
||||
description: '', // Add description field if available in your data
|
||||
isActive: true, // Add isActive field if available in your data
|
||||
newBenefit: ''
|
||||
}
|
||||
|
||||
resetForm(formData)
|
||||
setShowMore(true) // Always show more for edit mode
|
||||
} else {
|
||||
// Reset to initial data for add mode
|
||||
resetForm(initialData)
|
||||
setShowMore(false)
|
||||
}
|
||||
}, [data, isEditMode, resetForm])
|
||||
|
||||
const handleAddBenefit = () => {
|
||||
if (watchedNewBenefit.trim()) {
|
||||
const currentBenefits = watchedBenefits || []
|
||||
setValue('benefits', [...currentBenefits, watchedNewBenefit.trim()])
|
||||
setValue('newBenefit', '')
|
||||
}
|
||||
}
|
||||
|
||||
const handleRemoveBenefit = (index: number) => {
|
||||
const currentBenefits = watchedBenefits || []
|
||||
const newBenefits = currentBenefits.filter((_, i) => i !== index)
|
||||
setValue('benefits', newBenefits)
|
||||
}
|
||||
|
||||
const handleKeyPress = (event: React.KeyboardEvent) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault()
|
||||
handleAddBenefit()
|
||||
}
|
||||
}
|
||||
|
||||
const handleFormSubmit = async (formData: FormValidateType) => {
|
||||
try {
|
||||
setIsSubmitting(true)
|
||||
|
||||
// Create LoyaltyRequest object
|
||||
const loyaltyRequest: LoyaltyRequest = {
|
||||
name: formData.name,
|
||||
minimumPurchase: formData.minimumPurchase,
|
||||
pointMultiplier: formData.pointMultiplier,
|
||||
benefits: formData.benefits,
|
||||
description: formData.description || undefined,
|
||||
isActive: formData.isActive
|
||||
}
|
||||
|
||||
if (isEditMode && data?.id) {
|
||||
// Update existing loyalty
|
||||
updateLoyalty.mutate(
|
||||
{ id: data.id, payload: loyaltyRequest },
|
||||
{
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
handleClose()
|
||||
}
|
||||
}
|
||||
)
|
||||
} else {
|
||||
// Create new loyalty
|
||||
createLoyalty.mutate(loyaltyRequest, {
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
handleClose()
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error submitting loyalty:', error)
|
||||
// Handle error (show toast, etc.)
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleReset = () => {
|
||||
handleClose()
|
||||
resetForm(initialData)
|
||||
setShowMore(false)
|
||||
}
|
||||
|
||||
const formatCurrency = (value: number) => {
|
||||
return new Intl.NumberFormat('id-ID', {
|
||||
style: 'currency',
|
||||
currency: 'IDR',
|
||||
minimumFractionDigits: 0
|
||||
}).format(value)
|
||||
}
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
open={open}
|
||||
anchor='right'
|
||||
variant='temporary'
|
||||
onClose={handleReset}
|
||||
ModalProps={{ keepMounted: true }}
|
||||
sx={{
|
||||
'& .MuiDrawer-paper': {
|
||||
width: { xs: 300, sm: 400 },
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
height: '100%'
|
||||
}
|
||||
}}
|
||||
>
|
||||
{/* Sticky Header */}
|
||||
<Box
|
||||
sx={{
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
zIndex: 10,
|
||||
backgroundColor: 'background.paper',
|
||||
borderBottom: 1,
|
||||
borderColor: 'divider'
|
||||
}}
|
||||
>
|
||||
<div className='flex items-center justify-between plb-5 pli-6'>
|
||||
<Typography variant='h5'>{isEditMode ? 'Edit Program Loyalty' : 'Tambah Program Loyalty Baru'}</Typography>
|
||||
<IconButton size='small' onClick={handleReset}>
|
||||
<i className='tabler-x text-2xl text-textPrimary' />
|
||||
</IconButton>
|
||||
</div>
|
||||
</Box>
|
||||
|
||||
{/* Scrollable Content */}
|
||||
<Box sx={{ flex: 1, overflowY: 'auto' }}>
|
||||
<form id='loyalty-form' onSubmit={handleSubmit(handleFormSubmit)}>
|
||||
<div className='flex flex-col gap-6 p-6'>
|
||||
{/* Nama Program Loyalty */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Nama Program Loyalty <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='name'
|
||||
control={control}
|
||||
rules={{ required: 'Nama program loyalty wajib diisi' }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='Masukkan nama program loyalty'
|
||||
error={!!errors.name}
|
||||
helperText={errors.name?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Minimum Purchase */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Minimum Pembelian <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='minimumPurchase'
|
||||
control={control}
|
||||
rules={{
|
||||
required: 'Minimum pembelian wajib diisi',
|
||||
min: {
|
||||
value: 0,
|
||||
message: 'Minimum pembelian tidak boleh negatif'
|
||||
}
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='number'
|
||||
placeholder='0'
|
||||
error={!!errors.minimumPurchase}
|
||||
helperText={errors.minimumPurchase?.message || (field.value > 0 ? formatCurrency(field.value) : '')}
|
||||
InputProps={{
|
||||
startAdornment: <InputAdornment position='start'>Rp</InputAdornment>
|
||||
}}
|
||||
onChange={e => field.onChange(Number(e.target.value))}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Point Multiplier */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Pengali Poin <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='pointMultiplier'
|
||||
control={control}
|
||||
rules={{
|
||||
required: 'Pengali poin wajib diisi',
|
||||
min: {
|
||||
value: 1,
|
||||
message: 'Pengali poin minimal 1'
|
||||
},
|
||||
max: {
|
||||
value: 10,
|
||||
message: 'Pengali poin maksimal 10'
|
||||
}
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
select
|
||||
fullWidth
|
||||
error={!!errors.pointMultiplier}
|
||||
helperText={errors.pointMultiplier?.message}
|
||||
onChange={e => field.onChange(Number(e.target.value))}
|
||||
>
|
||||
{[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(multiplier => (
|
||||
<MenuItem key={multiplier} value={multiplier}>
|
||||
{multiplier}x
|
||||
</MenuItem>
|
||||
))}
|
||||
</CustomTextField>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Benefits */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Manfaat Program <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
|
||||
{/* Display current benefits */}
|
||||
{watchedBenefits && watchedBenefits.length > 0 && (
|
||||
<div className='flex flex-wrap gap-2 mb-3'>
|
||||
{watchedBenefits.map((benefit, index) => (
|
||||
<Chip
|
||||
key={index}
|
||||
label={benefit}
|
||||
onDelete={() => handleRemoveBenefit(index)}
|
||||
color='primary'
|
||||
variant='outlined'
|
||||
size='small'
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Add new benefit */}
|
||||
<Controller
|
||||
name='newBenefit'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='Tambah manfaat baru'
|
||||
onKeyPress={handleKeyPress}
|
||||
InputProps={{
|
||||
endAdornment: (
|
||||
<InputAdornment position='end'>
|
||||
<Button size='small' onClick={handleAddBenefit} disabled={!watchedNewBenefit?.trim()}>
|
||||
Tambah
|
||||
</Button>
|
||||
</InputAdornment>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{(!watchedBenefits || watchedBenefits.length === 0) && (
|
||||
<Typography variant='caption' color='error'>
|
||||
Minimal satu manfaat harus ditambahkan
|
||||
</Typography>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Status Aktif */}
|
||||
<div>
|
||||
<Controller
|
||||
name='isActive'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<FormControlLabel
|
||||
control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
|
||||
label='Program Aktif'
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Tampilkan selengkapnya */}
|
||||
{!showMore && (
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
size='small'
|
||||
sx={{ textTransform: 'none', fontSize: '14px', p: 0, textAlign: 'left', width: '200px' }}
|
||||
onClick={() => setShowMore(true)}
|
||||
>
|
||||
+ Tampilkan selengkapnya
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Konten tambahan */}
|
||||
{showMore && (
|
||||
<>
|
||||
{/* Description */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Deskripsi Program
|
||||
</Typography>
|
||||
<Controller
|
||||
name='description'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='Deskripsi detail tentang program loyalty'
|
||||
multiline
|
||||
rows={4}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Sembunyikan */}
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
size='small'
|
||||
sx={{ textTransform: 'none', fontSize: '14px', p: 0, textAlign: 'left', width: '200px' }}
|
||||
onClick={() => setShowMore(false)}
|
||||
>
|
||||
- Sembunyikan
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</Box>
|
||||
|
||||
{/* Sticky Footer */}
|
||||
<Box
|
||||
sx={{
|
||||
position: 'sticky',
|
||||
bottom: 0,
|
||||
zIndex: 10,
|
||||
backgroundColor: 'background.paper',
|
||||
borderTop: 1,
|
||||
borderColor: 'divider',
|
||||
p: 3
|
||||
}}
|
||||
>
|
||||
<div className='flex items-center gap-4'>
|
||||
<Button
|
||||
variant='contained'
|
||||
type='submit'
|
||||
form='loyalty-form'
|
||||
disabled={isSubmitting || !watchedBenefits || watchedBenefits.length === 0}
|
||||
>
|
||||
{isSubmitting ? (isEditMode ? 'Mengupdate...' : 'Menyimpan...') : isEditMode ? 'Update' : 'Simpan'}
|
||||
</Button>
|
||||
<Button variant='outlined' color='error' onClick={handleReset} disabled={isSubmitting}>
|
||||
Batal
|
||||
</Button>
|
||||
</div>
|
||||
</Box>
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
|
||||
export default AddEditLoyaltyDrawer
|
||||
@@ -0,0 +1,635 @@
|
||||
'use client'
|
||||
|
||||
// React Imports
|
||||
import { useEffect, useState, useMemo, useCallback } from 'react'
|
||||
|
||||
// Next Imports
|
||||
import Link from 'next/link'
|
||||
import { useParams } from 'next/navigation'
|
||||
|
||||
// MUI Imports
|
||||
import Card from '@mui/material/Card'
|
||||
import CardHeader from '@mui/material/CardHeader'
|
||||
import Button from '@mui/material/Button'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import Chip from '@mui/material/Chip'
|
||||
import Checkbox from '@mui/material/Checkbox'
|
||||
import IconButton from '@mui/material/IconButton'
|
||||
import { styled } from '@mui/material/styles'
|
||||
import TablePagination from '@mui/material/TablePagination'
|
||||
import type { TextFieldProps } from '@mui/material/TextField'
|
||||
import MenuItem from '@mui/material/MenuItem'
|
||||
|
||||
// Third-party Imports
|
||||
import classnames from 'classnames'
|
||||
import { rankItem } from '@tanstack/match-sorter-utils'
|
||||
import {
|
||||
createColumnHelper,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
useReactTable,
|
||||
getFilteredRowModel,
|
||||
getFacetedRowModel,
|
||||
getFacetedUniqueValues,
|
||||
getFacetedMinMaxValues,
|
||||
getPaginationRowModel,
|
||||
getSortedRowModel
|
||||
} from '@tanstack/react-table'
|
||||
import type { ColumnDef, FilterFn } from '@tanstack/react-table'
|
||||
import type { RankingInfo } from '@tanstack/match-sorter-utils'
|
||||
|
||||
// Type Imports
|
||||
import type { ThemeColor } from '@core/types'
|
||||
import type { Locale } from '@configs/i18n'
|
||||
|
||||
// Component Imports
|
||||
import OptionMenu from '@core/components/option-menu'
|
||||
import TablePaginationComponent from '@components/TablePaginationComponent'
|
||||
import CustomTextField from '@core/components/mui/TextField'
|
||||
import CustomAvatar from '@core/components/mui/Avatar'
|
||||
|
||||
// Util Imports
|
||||
import { getInitials } from '@/utils/getInitials'
|
||||
import { getLocalizedUrl } from '@/utils/i18n'
|
||||
import { formatCurrency } from '@/utils/transform'
|
||||
|
||||
// Style Imports
|
||||
import tableStyles from '@core/styles/table.module.css'
|
||||
import Loading from '@/components/layout/shared/Loading'
|
||||
import AddEditLoyaltyDrawer from './AddLoyaltiDrawer'
|
||||
|
||||
// Loyalty Type Interface
|
||||
export interface LoyaltyType {
|
||||
id: string
|
||||
name: string
|
||||
minimumPurchase: number
|
||||
pointMultiplier: number
|
||||
benefits: string[]
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}
|
||||
|
||||
declare module '@tanstack/table-core' {
|
||||
interface FilterFns {
|
||||
fuzzy: FilterFn<unknown>
|
||||
}
|
||||
interface FilterMeta {
|
||||
itemRank: RankingInfo
|
||||
}
|
||||
}
|
||||
|
||||
type LoyaltyTypeWithAction = LoyaltyType & {
|
||||
action?: string
|
||||
}
|
||||
|
||||
// Styled Components
|
||||
const Icon = styled('i')({})
|
||||
|
||||
const fuzzyFilter: FilterFn<any> = (row, columnId, value, addMeta) => {
|
||||
// Rank the item
|
||||
const itemRank = rankItem(row.getValue(columnId), value)
|
||||
|
||||
// Store the itemRank info
|
||||
addMeta({
|
||||
itemRank
|
||||
})
|
||||
|
||||
// Return if the item should be filtered in/out
|
||||
return itemRank.passed
|
||||
}
|
||||
|
||||
const DebouncedInput = ({
|
||||
value: initialValue,
|
||||
onChange,
|
||||
debounce = 500,
|
||||
...props
|
||||
}: {
|
||||
value: string | number
|
||||
onChange: (value: string | number) => void
|
||||
debounce?: number
|
||||
} & Omit<TextFieldProps, 'onChange'>) => {
|
||||
// States
|
||||
const [value, setValue] = useState(initialValue)
|
||||
|
||||
useEffect(() => {
|
||||
setValue(initialValue)
|
||||
}, [initialValue])
|
||||
|
||||
useEffect(() => {
|
||||
const timeout = setTimeout(() => {
|
||||
onChange(value)
|
||||
}, debounce)
|
||||
|
||||
return () => clearTimeout(timeout)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [value])
|
||||
|
||||
return <CustomTextField {...props} value={value} onChange={e => setValue(e.target.value)} />
|
||||
}
|
||||
|
||||
// Dummy data for loyalty programs
|
||||
const DUMMY_LOYALTY_DATA: LoyaltyType[] = [
|
||||
{
|
||||
id: '1',
|
||||
name: 'Silver Member',
|
||||
minimumPurchase: 500000,
|
||||
pointMultiplier: 1,
|
||||
benefits: ['Gratis ongkir', 'Diskon 5%', 'Priority customer service'],
|
||||
createdAt: new Date('2024-01-15'),
|
||||
updatedAt: new Date('2024-02-10')
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
name: 'Gold Member',
|
||||
minimumPurchase: 2000000,
|
||||
pointMultiplier: 2,
|
||||
benefits: ['Gratis ongkir', 'Diskon 10%', 'Birthday bonus', 'Priority customer service', 'Akses early sale'],
|
||||
createdAt: new Date('2024-01-20'),
|
||||
updatedAt: new Date('2024-02-15')
|
||||
},
|
||||
{
|
||||
id: '3',
|
||||
name: 'Platinum Member',
|
||||
minimumPurchase: 5000000,
|
||||
pointMultiplier: 3,
|
||||
benefits: [
|
||||
'Gratis ongkir',
|
||||
'Diskon 15%',
|
||||
'Birthday bonus',
|
||||
'Dedicated account manager',
|
||||
'VIP event access',
|
||||
'Personal shopper'
|
||||
],
|
||||
createdAt: new Date('2024-01-25'),
|
||||
updatedAt: new Date('2024-02-20')
|
||||
},
|
||||
{
|
||||
id: '4',
|
||||
name: 'Diamond Member',
|
||||
minimumPurchase: 10000000,
|
||||
pointMultiplier: 5,
|
||||
benefits: [
|
||||
'Gratis ongkir',
|
||||
'Diskon 20%',
|
||||
'Birthday bonus',
|
||||
'Dedicated account manager',
|
||||
'VIP event access',
|
||||
'Personal shopper',
|
||||
'Annual gift',
|
||||
'Luxury experiences'
|
||||
],
|
||||
createdAt: new Date('2024-02-01'),
|
||||
updatedAt: new Date('2024-02-25')
|
||||
},
|
||||
{
|
||||
id: '5',
|
||||
name: 'Student Discount',
|
||||
minimumPurchase: 100000,
|
||||
pointMultiplier: 1,
|
||||
benefits: ['Diskon 10% khusus mahasiswa', 'Gratis ongkir untuk pembelian minimal 200k'],
|
||||
createdAt: new Date('2024-02-05'),
|
||||
updatedAt: new Date('2024-03-01')
|
||||
},
|
||||
{
|
||||
id: '6',
|
||||
name: 'Senior Citizen',
|
||||
minimumPurchase: 200000,
|
||||
pointMultiplier: 2,
|
||||
benefits: ['Diskon 15% untuk usia 60+', 'Gratis ongkir', 'Konsultasi gratis', 'Priority support'],
|
||||
createdAt: new Date('2024-02-10'),
|
||||
updatedAt: new Date('2024-03-05')
|
||||
},
|
||||
{
|
||||
id: '7',
|
||||
name: 'Corporate Partner',
|
||||
minimumPurchase: 15000000,
|
||||
pointMultiplier: 4,
|
||||
benefits: [
|
||||
'Diskon 25% untuk pembelian korporat',
|
||||
'Payment terms 30 hari',
|
||||
'Dedicated sales rep',
|
||||
'Bulk discount',
|
||||
'Invoice payment'
|
||||
],
|
||||
createdAt: new Date('2024-02-15'),
|
||||
updatedAt: new Date('2024-03-10')
|
||||
},
|
||||
{
|
||||
id: '8',
|
||||
name: 'New Customer Bonus',
|
||||
minimumPurchase: 0,
|
||||
pointMultiplier: 1,
|
||||
benefits: ['Welcome bonus 50 poin', 'Diskon 15% pembelian pertama', 'Gratis ongkir'],
|
||||
createdAt: new Date('2024-03-01'),
|
||||
updatedAt: new Date('2024-03-15')
|
||||
},
|
||||
{
|
||||
id: '9',
|
||||
name: 'Family Package',
|
||||
minimumPurchase: 1000000,
|
||||
pointMultiplier: 2,
|
||||
benefits: [
|
||||
'Diskon 12% untuk keluarga',
|
||||
'Poin dapat dibagi ke anggota keluarga',
|
||||
'Family rewards',
|
||||
'Group discount'
|
||||
],
|
||||
createdAt: new Date('2024-03-05'),
|
||||
updatedAt: new Date('2024-03-20')
|
||||
},
|
||||
{
|
||||
id: '10',
|
||||
name: 'Loyalty Plus',
|
||||
minimumPurchase: 3000000,
|
||||
pointMultiplier: 3,
|
||||
benefits: [
|
||||
'Cashback 8%',
|
||||
'Exclusive member-only products',
|
||||
'Free premium packaging',
|
||||
'Extended warranty',
|
||||
'Member appreciation events'
|
||||
],
|
||||
createdAt: new Date('2024-03-10'),
|
||||
updatedAt: new Date('2024-03-25')
|
||||
},
|
||||
{
|
||||
id: '11',
|
||||
name: 'VIP Collector',
|
||||
minimumPurchase: 7500000,
|
||||
pointMultiplier: 4,
|
||||
benefits: [
|
||||
'Limited edition access',
|
||||
'Collector item discounts',
|
||||
'Pre-order privileges',
|
||||
'Authentication service',
|
||||
'Storage solutions'
|
||||
],
|
||||
createdAt: new Date('2024-03-15'),
|
||||
updatedAt: new Date('2024-03-30')
|
||||
},
|
||||
{
|
||||
id: '12',
|
||||
name: 'Seasonal Member',
|
||||
minimumPurchase: 800000,
|
||||
pointMultiplier: 2,
|
||||
benefits: ['Seasonal sale access', 'Holiday bonuses', 'Festival discounts', 'Seasonal gift wrapping'],
|
||||
createdAt: new Date('2024-03-20'),
|
||||
updatedAt: new Date('2024-04-05')
|
||||
}
|
||||
]
|
||||
|
||||
// Mock data hook with dummy data
|
||||
const useLoyalty = ({ page, limit, search }: { page: number; limit: number; search: string }) => {
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
// Simulate loading
|
||||
useEffect(() => {
|
||||
setIsLoading(true)
|
||||
const timer = setTimeout(() => setIsLoading(false), 500)
|
||||
return () => clearTimeout(timer)
|
||||
}, [page, limit, search])
|
||||
|
||||
// Filter data based on search
|
||||
const filteredData = useMemo(() => {
|
||||
if (!search) return DUMMY_LOYALTY_DATA
|
||||
|
||||
return DUMMY_LOYALTY_DATA.filter(
|
||||
loyalty =>
|
||||
loyalty.name.toLowerCase().includes(search.toLowerCase()) ||
|
||||
loyalty.benefits.some(benefit => benefit.toLowerCase().includes(search.toLowerCase()))
|
||||
)
|
||||
}, [search])
|
||||
|
||||
// Paginate data
|
||||
const paginatedData = useMemo(() => {
|
||||
const startIndex = (page - 1) * limit
|
||||
const endIndex = startIndex + limit
|
||||
return filteredData.slice(startIndex, endIndex)
|
||||
}, [filteredData, page, limit])
|
||||
|
||||
return {
|
||||
data: {
|
||||
loyalties: paginatedData,
|
||||
total_count: filteredData.length
|
||||
},
|
||||
isLoading,
|
||||
error: null,
|
||||
isFetching: isLoading
|
||||
}
|
||||
}
|
||||
|
||||
// Column Definitions
|
||||
const columnHelper = createColumnHelper<LoyaltyTypeWithAction>()
|
||||
|
||||
const LoyaltyListTable = () => {
|
||||
// States
|
||||
const [addLoyaltyOpen, setAddLoyaltyOpen] = useState(false)
|
||||
const [editLoyaltyData, setEditLoyaltyData] = useState<LoyaltyType | undefined>(undefined)
|
||||
const [rowSelection, setRowSelection] = useState({})
|
||||
const [globalFilter, setGlobalFilter] = useState('')
|
||||
const [currentPage, setCurrentPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(10)
|
||||
const [search, setSearch] = useState('')
|
||||
|
||||
const { data, isLoading, error, isFetching } = useLoyalty({
|
||||
page: currentPage,
|
||||
limit: pageSize,
|
||||
search
|
||||
})
|
||||
|
||||
const loyalties = data?.loyalties ?? []
|
||||
const totalCount = data?.total_count ?? 0
|
||||
|
||||
// Hooks
|
||||
const { lang: locale } = useParams()
|
||||
|
||||
const handlePageChange = useCallback((event: unknown, newPage: number) => {
|
||||
setCurrentPage(newPage)
|
||||
}, [])
|
||||
|
||||
const handlePageSizeChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newPageSize = parseInt(event.target.value, 10)
|
||||
setPageSize(newPageSize)
|
||||
setCurrentPage(1) // Reset to first page
|
||||
}, [])
|
||||
|
||||
const handleEditLoyalty = (loyalty: LoyaltyType) => {
|
||||
setEditLoyaltyData(loyalty)
|
||||
setAddLoyaltyOpen(true)
|
||||
}
|
||||
|
||||
const handleDeleteLoyalty = (loyaltyId: string) => {
|
||||
if (confirm('Apakah Anda yakin ingin menghapus program loyalty ini?')) {
|
||||
console.log('Deleting loyalty:', loyaltyId)
|
||||
// Add your delete logic here
|
||||
// deleteLoyalty.mutate(loyaltyId)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCloseLoyaltyDrawer = () => {
|
||||
setAddLoyaltyOpen(false)
|
||||
setEditLoyaltyData(undefined)
|
||||
}
|
||||
|
||||
const columns = useMemo<ColumnDef<LoyaltyTypeWithAction, any>[]>(
|
||||
() => [
|
||||
{
|
||||
id: 'select',
|
||||
header: ({ table }) => (
|
||||
<Checkbox
|
||||
{...{
|
||||
checked: table.getIsAllRowsSelected(),
|
||||
indeterminate: table.getIsSomeRowsSelected(),
|
||||
onChange: table.getToggleAllRowsSelectedHandler()
|
||||
}}
|
||||
/>
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<Checkbox
|
||||
{...{
|
||||
checked: row.getIsSelected(),
|
||||
disabled: !row.getCanSelect(),
|
||||
indeterminate: row.getIsSomeSelected(),
|
||||
onChange: row.getToggleSelectedHandler()
|
||||
}}
|
||||
/>
|
||||
)
|
||||
},
|
||||
columnHelper.accessor('name', {
|
||||
header: 'Program Loyalty',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-4'>
|
||||
<div className='flex flex-col'>
|
||||
<Link href={getLocalizedUrl(`/apps/loyalty/${row.original.id}/detail`, locale as Locale)}>
|
||||
<Typography className='font-medium cursor-pointer hover:underline text-primary'>
|
||||
{row.original.name}
|
||||
</Typography>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('minimumPurchase', {
|
||||
header: 'Minimum Pembelian',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-2'>
|
||||
<Icon className='tabler-coin' sx={{ color: 'var(--mui-palette-primary-main)' }} />
|
||||
<Typography color='text.primary'>{formatCurrency(row.original.minimumPurchase)}</Typography>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('pointMultiplier', {
|
||||
header: 'Pengali Poin',
|
||||
cell: ({ row }) => (
|
||||
<Chip label={`${row.original.pointMultiplier}x`} color='primary' variant='tonal' size='small' />
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('benefits', {
|
||||
header: 'Manfaat',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex flex-wrap gap-1 max-w-xs'>
|
||||
{row.original.benefits.slice(0, 2).map((benefit, index) => (
|
||||
<Chip key={index} label={benefit} size='small' variant='outlined' color='secondary' />
|
||||
))}
|
||||
{row.original.benefits.length > 2 && (
|
||||
<Chip
|
||||
label={`+${row.original.benefits.length - 2} lainnya`}
|
||||
size='small'
|
||||
variant='outlined'
|
||||
color='default'
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('createdAt', {
|
||||
header: 'Tanggal Dibuat',
|
||||
cell: ({ row }) => (
|
||||
<Typography color='text.primary'>
|
||||
{new Date(row.original.createdAt).toLocaleDateString('id-ID', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
})}
|
||||
</Typography>
|
||||
)
|
||||
}),
|
||||
{
|
||||
id: 'actions',
|
||||
header: 'Aksi',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center'>
|
||||
<OptionMenu
|
||||
iconButtonProps={{ size: 'medium' }}
|
||||
iconClassName='text-textSecondary text-[22px]'
|
||||
options={[
|
||||
{
|
||||
text: 'Edit',
|
||||
icon: 'tabler-edit text-[22px]',
|
||||
menuItemProps: {
|
||||
className: 'flex items-center gap-2 text-textSecondary',
|
||||
onClick: () => handleEditLoyalty(row.original)
|
||||
}
|
||||
},
|
||||
{
|
||||
text: 'Hapus',
|
||||
icon: 'tabler-trash text-[22px]',
|
||||
menuItemProps: {
|
||||
className: 'flex items-center gap-2 text-textSecondary',
|
||||
onClick: () => handleDeleteLoyalty(row.original.id)
|
||||
}
|
||||
}
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
enableSorting: false
|
||||
}
|
||||
],
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[locale, handleEditLoyalty, handleDeleteLoyalty]
|
||||
)
|
||||
|
||||
const table = useReactTable({
|
||||
data: loyalties as LoyaltyType[],
|
||||
columns,
|
||||
filterFns: {
|
||||
fuzzy: fuzzyFilter
|
||||
},
|
||||
state: {
|
||||
rowSelection,
|
||||
globalFilter,
|
||||
pagination: {
|
||||
pageIndex: currentPage,
|
||||
pageSize
|
||||
}
|
||||
},
|
||||
enableRowSelection: true,
|
||||
onRowSelectionChange: setRowSelection,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
manualPagination: true,
|
||||
pageCount: Math.ceil(totalCount / pageSize)
|
||||
})
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card>
|
||||
<div className='flex justify-between flex-col items-start md:flex-row md:items-center p-6 border-bs gap-4'>
|
||||
<CustomTextField
|
||||
select
|
||||
value={table.getState().pagination.pageSize}
|
||||
onChange={e => table.setPageSize(Number(e.target.value))}
|
||||
className='max-sm:is-full sm:is-[70px]'
|
||||
>
|
||||
<MenuItem value='10'>10</MenuItem>
|
||||
<MenuItem value='25'>25</MenuItem>
|
||||
<MenuItem value='50'>50</MenuItem>
|
||||
</CustomTextField>
|
||||
<div className='flex flex-col sm:flex-row max-sm:is-full items-start sm:items-center gap-4'>
|
||||
<DebouncedInput
|
||||
value={search ?? ''}
|
||||
onChange={value => setSearch(value as string)}
|
||||
placeholder='Cari Program Loyalty'
|
||||
className='max-sm:is-full'
|
||||
/>
|
||||
<Button
|
||||
color='secondary'
|
||||
variant='tonal'
|
||||
startIcon={<i className='tabler-upload' />}
|
||||
className='max-sm:is-full'
|
||||
>
|
||||
Ekspor
|
||||
</Button>
|
||||
<Button
|
||||
variant='contained'
|
||||
startIcon={<i className='tabler-plus' />}
|
||||
onClick={() => setAddLoyaltyOpen(!addLoyaltyOpen)}
|
||||
className='max-sm:is-full'
|
||||
>
|
||||
Tambah Program Loyalty
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className='overflow-x-auto'>
|
||||
{isLoading ? (
|
||||
<Loading />
|
||||
) : (
|
||||
<table className={tableStyles.table}>
|
||||
<thead>
|
||||
{table.getHeaderGroups().map(headerGroup => (
|
||||
<tr key={headerGroup.id}>
|
||||
{headerGroup.headers.map(header => (
|
||||
<th key={header.id}>
|
||||
{header.isPlaceholder ? null : (
|
||||
<>
|
||||
<div
|
||||
className={classnames({
|
||||
'flex items-center': header.column.getIsSorted(),
|
||||
'cursor-pointer select-none': header.column.getCanSort()
|
||||
})}
|
||||
onClick={header.column.getToggleSortingHandler()}
|
||||
>
|
||||
{flexRender(header.column.columnDef.header, header.getContext())}
|
||||
{{
|
||||
asc: <i className='tabler-chevron-up text-xl' />,
|
||||
desc: <i className='tabler-chevron-down text-xl' />
|
||||
}[header.column.getIsSorted() as 'asc' | 'desc'] ?? null}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
{table.getFilteredRowModel().rows.length === 0 ? (
|
||||
<tbody>
|
||||
<tr>
|
||||
<td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
|
||||
Tidak ada data tersedia
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
) : (
|
||||
<tbody>
|
||||
{table
|
||||
.getRowModel()
|
||||
.rows.slice(0, table.getState().pagination.pageSize)
|
||||
.map(row => {
|
||||
return (
|
||||
<tr key={row.id} className={classnames({ selected: row.getIsSelected() })}>
|
||||
{row.getVisibleCells().map(cell => (
|
||||
<td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
|
||||
))}
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
)}
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
<TablePagination
|
||||
component={() => (
|
||||
<TablePaginationComponent
|
||||
pageIndex={currentPage}
|
||||
pageSize={pageSize}
|
||||
totalCount={totalCount}
|
||||
onPageChange={handlePageChange}
|
||||
/>
|
||||
)}
|
||||
count={totalCount}
|
||||
rowsPerPage={pageSize}
|
||||
page={currentPage}
|
||||
onPageChange={handlePageChange}
|
||||
onRowsPerPageChange={handlePageSizeChange}
|
||||
rowsPerPageOptions={[10, 25, 50]}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</Card>
|
||||
<AddEditLoyaltyDrawer open={addLoyaltyOpen} handleClose={handleCloseLoyaltyDrawer} data={editLoyaltyData} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default LoyaltyListTable
|
||||
@@ -0,0 +1,17 @@
|
||||
// MUI Imports
|
||||
import Grid from '@mui/material/Grid2'
|
||||
import LoyaltyListTable from './LoyaltyListTable'
|
||||
|
||||
// Type Imports
|
||||
|
||||
const LoyaltyList = () => {
|
||||
return (
|
||||
<Grid container spacing={6}>
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<LoyaltyListTable />
|
||||
</Grid>
|
||||
</Grid>
|
||||
)
|
||||
}
|
||||
|
||||
export default LoyaltyList
|
||||
@@ -0,0 +1,758 @@
|
||||
// React Imports
|
||||
import { useState, useEffect } from 'react'
|
||||
|
||||
// MUI Imports
|
||||
import Button from '@mui/material/Button'
|
||||
import Drawer from '@mui/material/Drawer'
|
||||
import IconButton from '@mui/material/IconButton'
|
||||
import MenuItem from '@mui/material/MenuItem'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import Divider from '@mui/material/Divider'
|
||||
import Grid from '@mui/material/Grid2'
|
||||
import Box from '@mui/material/Box'
|
||||
import Switch from '@mui/material/Switch'
|
||||
import FormControlLabel from '@mui/material/FormControlLabel'
|
||||
import Chip from '@mui/material/Chip'
|
||||
import InputAdornment from '@mui/material/InputAdornment'
|
||||
import Avatar from '@mui/material/Avatar'
|
||||
import Card from '@mui/material/Card'
|
||||
import CardContent from '@mui/material/CardContent'
|
||||
import FormHelperText from '@mui/material/FormHelperText'
|
||||
import TextField from '@mui/material/TextField'
|
||||
import Accordion from '@mui/material/Accordion'
|
||||
import AccordionSummary from '@mui/material/AccordionSummary'
|
||||
import AccordionDetails from '@mui/material/AccordionDetails'
|
||||
import List from '@mui/material/List'
|
||||
import ListItem from '@mui/material/ListItem'
|
||||
import ListItemText from '@mui/material/ListItemText'
|
||||
import ListItemSecondaryAction from '@mui/material/ListItemSecondaryAction'
|
||||
|
||||
// Third-party Imports
|
||||
import { useForm, Controller, useFieldArray } from 'react-hook-form'
|
||||
|
||||
// Component Imports
|
||||
import CustomTextField from '@core/components/mui/TextField'
|
||||
import MultipleImageUpload from '@/components/MultipleImageUpload' // Import the component
|
||||
|
||||
// Import the actual upload mutation
|
||||
import { useFilesMutation } from '@/services/mutations/files'
|
||||
import { useRewardsMutation } from '@/services/mutations/reward'
|
||||
|
||||
// Updated Types based on new API structure
|
||||
export interface TermsAndConditions {
|
||||
sections: TncSection[]
|
||||
expiry_days: number
|
||||
}
|
||||
|
||||
export interface TncSection {
|
||||
title: string
|
||||
rules: string[]
|
||||
}
|
||||
|
||||
export interface RewardRequest {
|
||||
name: string // required, 1–150 chars
|
||||
reward_type: 'VOUCHER' | 'PHYSICAL' | 'DIGITAL' // enum
|
||||
cost_points: number // min 1
|
||||
stock?: number
|
||||
max_per_customer: number // min 1
|
||||
tnc?: TermsAndConditions
|
||||
images?: string[] // Add images to request
|
||||
}
|
||||
|
||||
export interface Reward {
|
||||
id: string // uuid
|
||||
name: string
|
||||
reward_type: 'VOUCHER' | 'PHYSICAL' | 'DIGITAL'
|
||||
cost_points: number
|
||||
stock?: number
|
||||
max_per_customer: number
|
||||
tnc?: TermsAndConditions
|
||||
metadata?: Record<string, any>
|
||||
images?: string[]
|
||||
created_at: string // ISO date-time
|
||||
updated_at: string // ISO date-time
|
||||
}
|
||||
|
||||
// Type for uploaded image in the component
|
||||
type UploadedImage = {
|
||||
id: string
|
||||
url: string
|
||||
name: string
|
||||
size: number
|
||||
}
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
handleClose: () => void
|
||||
data?: Reward // Data reward untuk edit (jika ada)
|
||||
}
|
||||
|
||||
type FormValidateType = {
|
||||
name: string
|
||||
reward_type: 'VOUCHER' | 'PHYSICAL' | 'DIGITAL'
|
||||
cost_points: number
|
||||
stock: number | ''
|
||||
max_per_customer: number
|
||||
hasUnlimitedStock: boolean
|
||||
hasTnc: boolean
|
||||
tnc_expiry_days: number
|
||||
tnc_sections: TncSection[]
|
||||
uploadedImages: UploadedImage[] // Changed from images array to uploaded images
|
||||
metadata: Record<string, any>
|
||||
}
|
||||
|
||||
// Initial form data
|
||||
const initialData: FormValidateType = {
|
||||
name: '',
|
||||
reward_type: 'VOUCHER',
|
||||
cost_points: 100,
|
||||
stock: '',
|
||||
max_per_customer: 1,
|
||||
hasUnlimitedStock: false,
|
||||
hasTnc: false,
|
||||
tnc_expiry_days: 30,
|
||||
tnc_sections: [],
|
||||
uploadedImages: [], // Initialize as empty array
|
||||
metadata: {}
|
||||
}
|
||||
|
||||
// Reward types
|
||||
const REWARD_TYPES = [
|
||||
{ value: 'VOUCHER', label: 'Voucher' },
|
||||
{ value: 'PHYSICAL', label: 'Barang Fisik' },
|
||||
{ value: 'DIGITAL', label: 'Digital' }
|
||||
] as const
|
||||
|
||||
const AddEditRewardDrawer = (props: Props) => {
|
||||
// Props
|
||||
const { open, handleClose, data } = props
|
||||
|
||||
// States
|
||||
const [showMore, setShowMore] = useState(false)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [uploadingFiles, setUploadingFiles] = useState<Set<string>>(new Set())
|
||||
|
||||
const { createReward, updateReward } = useRewardsMutation()
|
||||
const { mutate: uploadFile, isPending: isFileUploading } = useFilesMutation().uploadFile
|
||||
|
||||
// Determine if this is edit mode
|
||||
const isEditMode = Boolean(data?.id)
|
||||
|
||||
// Hooks
|
||||
const {
|
||||
control,
|
||||
reset: resetForm,
|
||||
handleSubmit,
|
||||
watch,
|
||||
setValue,
|
||||
formState: { errors }
|
||||
} = useForm<FormValidateType>({
|
||||
defaultValues: initialData
|
||||
})
|
||||
|
||||
// Field arrays for dynamic sections
|
||||
const {
|
||||
fields: tncSectionFields,
|
||||
append: appendTncSection,
|
||||
remove: removeTncSection
|
||||
} = useFieldArray({
|
||||
control,
|
||||
name: 'tnc_sections'
|
||||
})
|
||||
|
||||
const watchedUploadedImages = watch('uploadedImages')
|
||||
const watchedHasUnlimitedStock = watch('hasUnlimitedStock')
|
||||
const watchedHasTnc = watch('hasTnc')
|
||||
const watchedStock = watch('stock')
|
||||
const watchedCostPoints = watch('cost_points')
|
||||
|
||||
// Effect to populate form when editing
|
||||
useEffect(() => {
|
||||
if (isEditMode && data) {
|
||||
// Convert existing images to UploadedImage format
|
||||
const existingImages: UploadedImage[] = (data.images || []).map((url, index) => ({
|
||||
id: `existing_${index}`,
|
||||
url: url,
|
||||
name: `Image ${index + 1}`,
|
||||
size: 0 // We don't have size info for existing images
|
||||
}))
|
||||
|
||||
// Populate form with existing data
|
||||
const formData: FormValidateType = {
|
||||
name: data.name || '',
|
||||
reward_type: data.reward_type || 'VOUCHER',
|
||||
cost_points: data.cost_points || 100,
|
||||
stock: data.stock ?? '',
|
||||
max_per_customer: data.max_per_customer || 1,
|
||||
hasUnlimitedStock: data.stock === undefined || data.stock === null,
|
||||
hasTnc: Boolean(data.tnc),
|
||||
tnc_expiry_days: data.tnc?.expiry_days || 30,
|
||||
tnc_sections: data.tnc?.sections || [],
|
||||
uploadedImages: existingImages,
|
||||
metadata: data.metadata || {}
|
||||
}
|
||||
|
||||
resetForm(formData)
|
||||
setShowMore(true) // Always show more for edit mode
|
||||
} else {
|
||||
// Reset to initial data for add mode
|
||||
resetForm(initialData)
|
||||
setShowMore(false)
|
||||
}
|
||||
}, [data, isEditMode, resetForm])
|
||||
|
||||
// Handle unlimited stock toggle
|
||||
useEffect(() => {
|
||||
if (watchedHasUnlimitedStock) {
|
||||
setValue('stock', '')
|
||||
}
|
||||
}, [watchedHasUnlimitedStock, setValue])
|
||||
|
||||
// Image upload handlers
|
||||
const handleSingleUpload = async (file: File): Promise<string> => {
|
||||
const fileId = `${file.name}-${Date.now()}`
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
// Add file to uploading set
|
||||
setUploadingFiles(prev => new Set(prev).add(fileId))
|
||||
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
formData.append('file_type', 'image')
|
||||
formData.append('description', 'reward image upload')
|
||||
|
||||
uploadFile(formData, {
|
||||
onSuccess: response => {
|
||||
// Remove file from uploading set
|
||||
setUploadingFiles(prev => {
|
||||
const newSet = new Set(prev)
|
||||
newSet.delete(fileId)
|
||||
return newSet
|
||||
})
|
||||
resolve(response.file_url)
|
||||
},
|
||||
onError: error => {
|
||||
// Remove file from uploading set
|
||||
setUploadingFiles(prev => {
|
||||
const newSet = new Set(prev)
|
||||
newSet.delete(fileId)
|
||||
return newSet
|
||||
})
|
||||
reject(error)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const handleMultipleUpload = async (files: File[]): Promise<string[]> => {
|
||||
const uploadedUrls: string[] = []
|
||||
|
||||
try {
|
||||
// Sequential upload to avoid overwhelming the server
|
||||
for (const file of files) {
|
||||
const url = await handleSingleUpload(file)
|
||||
uploadedUrls.push(url)
|
||||
}
|
||||
return uploadedUrls
|
||||
} catch (error) {
|
||||
console.error('Failed to upload images:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const handleImagesChange = (images: UploadedImage[]) => {
|
||||
setValue('uploadedImages', images)
|
||||
}
|
||||
|
||||
const handleImageRemove = (imageId: string) => {
|
||||
const currentImages = watchedUploadedImages || []
|
||||
const updatedImages = currentImages.filter(img => img.id !== imageId)
|
||||
setValue('uploadedImages', updatedImages)
|
||||
}
|
||||
|
||||
const handleFormSubmit = async (formData: FormValidateType) => {
|
||||
try {
|
||||
setIsSubmitting(true)
|
||||
|
||||
// Extract image URLs from uploaded images
|
||||
const imageUrls = formData.uploadedImages.map(img => img.url)
|
||||
|
||||
// Create RewardRequest object
|
||||
const rewardRequest: RewardRequest = {
|
||||
name: formData.name,
|
||||
reward_type: formData.reward_type,
|
||||
cost_points: formData.cost_points,
|
||||
stock: formData.hasUnlimitedStock ? undefined : (formData.stock as number) || undefined,
|
||||
max_per_customer: formData.max_per_customer,
|
||||
images: imageUrls.length > 0 ? imageUrls : undefined, // Include images in request
|
||||
tnc:
|
||||
formData.hasTnc && formData.tnc_sections.length > 0
|
||||
? {
|
||||
sections: formData.tnc_sections,
|
||||
expiry_days: formData.tnc_expiry_days
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
|
||||
if (isEditMode && data?.id) {
|
||||
// Update existing reward
|
||||
updateReward.mutate(
|
||||
{ id: data.id, payload: rewardRequest },
|
||||
{
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
handleClose()
|
||||
}
|
||||
}
|
||||
)
|
||||
} else {
|
||||
// Create new reward
|
||||
createReward.mutate(rewardRequest, {
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
handleClose()
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error submitting reward:', error)
|
||||
// Handle error (show toast, etc.)
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleReset = () => {
|
||||
handleClose()
|
||||
resetForm(initialData)
|
||||
setShowMore(false)
|
||||
setUploadingFiles(new Set())
|
||||
}
|
||||
|
||||
const formatPoints = (value: number) => {
|
||||
return value.toLocaleString('id-ID') + ' poin'
|
||||
}
|
||||
|
||||
const getStockDisplay = () => {
|
||||
if (watchedHasUnlimitedStock) return 'Unlimited'
|
||||
if (watchedStock === '' || watchedStock === 0) return 'Tidak ada stok'
|
||||
return `${watchedStock} item`
|
||||
}
|
||||
|
||||
const addTncSection = () => {
|
||||
appendTncSection({ title: '', rules: [''] })
|
||||
}
|
||||
|
||||
// Check if any files are currently uploading
|
||||
const isAnyFileUploading = uploadingFiles.size > 0 || isFileUploading
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
open={open}
|
||||
anchor='right'
|
||||
variant='temporary'
|
||||
onClose={handleReset}
|
||||
ModalProps={{ keepMounted: true }}
|
||||
sx={{
|
||||
'& .MuiDrawer-paper': {
|
||||
width: { xs: 300, sm: 400 },
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
height: '100%'
|
||||
}
|
||||
}}
|
||||
>
|
||||
{/* Sticky Header */}
|
||||
<Box
|
||||
sx={{
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
zIndex: 10,
|
||||
backgroundColor: 'background.paper',
|
||||
borderBottom: 1,
|
||||
borderColor: 'divider'
|
||||
}}
|
||||
>
|
||||
<div className='flex items-center justify-between plb-5 pli-6'>
|
||||
<Typography variant='h5'>{isEditMode ? 'Edit Reward' : 'Tambah Reward Baru'}</Typography>
|
||||
<IconButton size='small' onClick={handleReset}>
|
||||
<i className='tabler-x text-2xl text-textPrimary' />
|
||||
</IconButton>
|
||||
</div>
|
||||
</Box>
|
||||
|
||||
{/* Scrollable Content */}
|
||||
<Box sx={{ flex: 1, overflowY: 'auto' }}>
|
||||
<form id='reward-form' onSubmit={handleSubmit(handleFormSubmit)}>
|
||||
<div className='flex flex-col gap-6 p-6'>
|
||||
{/* Nama Reward */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Nama Reward <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='name'
|
||||
control={control}
|
||||
rules={{
|
||||
required: 'Nama reward wajib diisi',
|
||||
minLength: { value: 1, message: 'Nama reward minimal 1 karakter' },
|
||||
maxLength: { value: 150, message: 'Nama reward maksimal 150 karakter' }
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='Masukkan nama reward'
|
||||
error={!!errors.name}
|
||||
helperText={errors.name?.message || `${field.value.length}/150 karakter`}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Tipe Reward */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Tipe Reward <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='reward_type'
|
||||
control={control}
|
||||
rules={{ required: 'Tipe reward wajib dipilih' }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
select
|
||||
fullWidth
|
||||
error={!!errors.reward_type}
|
||||
helperText={errors.reward_type?.message}
|
||||
>
|
||||
{REWARD_TYPES.map(type => (
|
||||
<MenuItem key={type.value} value={type.value}>
|
||||
{type.label}
|
||||
</MenuItem>
|
||||
))}
|
||||
</CustomTextField>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Cost Points */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Biaya Poin <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='cost_points'
|
||||
control={control}
|
||||
rules={{
|
||||
required: 'Biaya poin wajib diisi',
|
||||
min: {
|
||||
value: 1,
|
||||
message: 'Biaya poin minimal 1'
|
||||
}
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='number'
|
||||
placeholder='100'
|
||||
error={!!errors.cost_points}
|
||||
helperText={errors.cost_points?.message || (field.value > 0 ? formatPoints(field.value) : '')}
|
||||
InputProps={{
|
||||
startAdornment: (
|
||||
<InputAdornment position='start'>
|
||||
<i className='tabler-star-filled text-warning' />
|
||||
</InputAdornment>
|
||||
)
|
||||
}}
|
||||
onChange={e => field.onChange(Number(e.target.value))}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Max Per Customer */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Maksimal per Pelanggan <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='max_per_customer'
|
||||
control={control}
|
||||
rules={{
|
||||
required: 'Maksimal per pelanggan wajib diisi',
|
||||
min: {
|
||||
value: 1,
|
||||
message: 'Minimal 1 per pelanggan'
|
||||
}
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='number'
|
||||
placeholder='1'
|
||||
error={!!errors.max_per_customer}
|
||||
helperText={errors.max_per_customer?.message}
|
||||
InputProps={{
|
||||
startAdornment: <InputAdornment position='start'>Max</InputAdornment>
|
||||
}}
|
||||
onChange={e => field.onChange(Number(e.target.value))}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Stock Management */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Manajemen Stok
|
||||
</Typography>
|
||||
<Controller
|
||||
name='hasUnlimitedStock'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<FormControlLabel
|
||||
control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
|
||||
label='Stok Unlimited'
|
||||
className='mb-2'
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{!watchedHasUnlimitedStock && (
|
||||
<Controller
|
||||
name='stock'
|
||||
control={control}
|
||||
rules={{
|
||||
required: !watchedHasUnlimitedStock ? 'Jumlah stok wajib diisi' : false,
|
||||
min: {
|
||||
value: 0,
|
||||
message: 'Stok tidak boleh negatif'
|
||||
}
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='number'
|
||||
placeholder='0'
|
||||
error={!!errors.stock}
|
||||
helperText={errors.stock?.message || getStockDisplay()}
|
||||
InputProps={{
|
||||
startAdornment: <InputAdornment position='start'>Qty</InputAdornment>
|
||||
}}
|
||||
onChange={e => field.onChange(e.target.value ? Number(e.target.value) : '')}
|
||||
value={field.value === '' ? '' : field.value}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Tampilkan selengkapnya */}
|
||||
{!showMore && (
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
size='small'
|
||||
sx={{ textTransform: 'none', fontSize: '14px', p: 0, textAlign: 'left', width: '200px' }}
|
||||
onClick={() => setShowMore(true)}
|
||||
>
|
||||
+ Tampilkan selengkapnya
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Konten tambahan */}
|
||||
{showMore && (
|
||||
<>
|
||||
{/* Multiple Image Upload Section */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-3'>
|
||||
Gambar Reward
|
||||
</Typography>
|
||||
<MultipleImageUpload
|
||||
title={null} // No title since we have our own
|
||||
onUpload={handleMultipleUpload}
|
||||
onSingleUpload={handleSingleUpload}
|
||||
currentImages={watchedUploadedImages || []}
|
||||
onImagesChange={handleImagesChange}
|
||||
onImageRemove={handleImageRemove}
|
||||
isUploading={isAnyFileUploading}
|
||||
maxFiles={5}
|
||||
maxFileSize={5 * 1024 * 1024} // 5MB
|
||||
acceptedFileTypes={['image/jpeg', 'image/png', 'image/webp']}
|
||||
showUrlOption={false}
|
||||
uploadMode='individual'
|
||||
uploadButtonText='Upload Gambar'
|
||||
browseButtonText='Pilih Gambar'
|
||||
dragDropText='Drag & drop gambar reward di sini'
|
||||
replaceText='Drop gambar untuk menambah lebih banyak'
|
||||
maxFilesText='Maksimal {max} gambar'
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
<FormHelperText>Format yang didukung: JPG, PNG, WebP. Maksimal 5MB per file.</FormHelperText>
|
||||
</div>
|
||||
|
||||
{/* Terms & Conditions */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Syarat & Ketentuan
|
||||
</Typography>
|
||||
<Controller
|
||||
name='hasTnc'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<FormControlLabel
|
||||
control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
|
||||
label='Memiliki syarat & ketentuan'
|
||||
className='mb-2'
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
||||
{watchedHasTnc && (
|
||||
<>
|
||||
<Controller
|
||||
name='tnc_expiry_days'
|
||||
control={control}
|
||||
rules={{
|
||||
required: watchedHasTnc ? 'Masa berlaku T&C wajib diisi' : false,
|
||||
min: { value: 1, message: 'Minimal 1 hari' }
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='number'
|
||||
label='Masa Berlaku T&C (hari)'
|
||||
placeholder='30'
|
||||
error={!!errors.tnc_expiry_days}
|
||||
helperText={errors.tnc_expiry_days?.message}
|
||||
className='mb-4'
|
||||
onChange={e => field.onChange(Number(e.target.value))}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
||||
{tncSectionFields.map((section, sectionIndex) => (
|
||||
<Accordion key={section.id} className='mb-2'>
|
||||
<AccordionSummary expandIcon={<i className='tabler-chevron-down' />}>
|
||||
<Typography>Bagian {sectionIndex + 1}</Typography>
|
||||
</AccordionSummary>
|
||||
<AccordionDetails>
|
||||
<Controller
|
||||
name={`tnc_sections.${sectionIndex}.title`}
|
||||
control={control}
|
||||
rules={{ required: 'Judul bagian wajib diisi' }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
label='Judul Bagian'
|
||||
placeholder='Judul bagian'
|
||||
className='mb-2'
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Aturan:
|
||||
</Typography>
|
||||
{section.rules?.map((rule, ruleIndex) => (
|
||||
<Controller
|
||||
key={ruleIndex}
|
||||
name={`tnc_sections.${sectionIndex}.rules.${ruleIndex}`}
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder={`Aturan ${ruleIndex + 1}`}
|
||||
className='mb-1'
|
||||
multiline
|
||||
rows={2}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
|
||||
<Box className='flex gap-2 mt-2'>
|
||||
<Button
|
||||
size='small'
|
||||
onClick={() => {
|
||||
const currentSection = watch(`tnc_sections.${sectionIndex}`)
|
||||
setValue(`tnc_sections.${sectionIndex}.rules`, [...(currentSection.rules || []), ''])
|
||||
}}
|
||||
>
|
||||
+ Aturan
|
||||
</Button>
|
||||
<Button size='small' color='error' onClick={() => removeTncSection(sectionIndex)}>
|
||||
Hapus Bagian
|
||||
</Button>
|
||||
</Box>
|
||||
</AccordionDetails>
|
||||
</Accordion>
|
||||
))}
|
||||
|
||||
<Button
|
||||
variant='outlined'
|
||||
size='small'
|
||||
onClick={addTncSection}
|
||||
startIcon={<i className='tabler-plus' />}
|
||||
className='mb-4'
|
||||
>
|
||||
Tambah Bagian T&C
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Sembunyikan */}
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
size='small'
|
||||
sx={{ textTransform: 'none', fontSize: '14px', p: 0, textAlign: 'left', width: '200px' }}
|
||||
onClick={() => setShowMore(false)}
|
||||
>
|
||||
- Sembunyikan
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</Box>
|
||||
|
||||
{/* Sticky Footer */}
|
||||
<Box
|
||||
sx={{
|
||||
position: 'sticky',
|
||||
bottom: 0,
|
||||
zIndex: 10,
|
||||
backgroundColor: 'background.paper',
|
||||
borderTop: 1,
|
||||
borderColor: 'divider',
|
||||
p: 3
|
||||
}}
|
||||
>
|
||||
<div className='flex items-center gap-4'>
|
||||
<Button variant='contained' type='submit' form='reward-form' disabled={isSubmitting || isAnyFileUploading}>
|
||||
{isSubmitting ? (isEditMode ? 'Mengupdate...' : 'Menyimpan...') : isEditMode ? 'Update' : 'Simpan'}
|
||||
</Button>
|
||||
<Button variant='outlined' color='error' onClick={handleReset} disabled={isSubmitting || isAnyFileUploading}>
|
||||
Batal
|
||||
</Button>
|
||||
</div>
|
||||
{isAnyFileUploading && (
|
||||
<Typography variant='caption' color='textSecondary' className='mt-2'>
|
||||
Sedang mengupload gambar... ({uploadingFiles.size} file)
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
|
||||
export default AddEditRewardDrawer
|
||||
@@ -0,0 +1,164 @@
|
||||
// React Imports
|
||||
import { useState } from 'react'
|
||||
|
||||
// MUI Imports
|
||||
import Dialog from '@mui/material/Dialog'
|
||||
import DialogTitle from '@mui/material/DialogTitle'
|
||||
import DialogContent from '@mui/material/DialogContent'
|
||||
import DialogActions from '@mui/material/DialogActions'
|
||||
import DialogContentText from '@mui/material/DialogContentText'
|
||||
import Button from '@mui/material/Button'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import Box from '@mui/material/Box'
|
||||
import Alert from '@mui/material/Alert'
|
||||
import Chip from '@mui/material/Chip'
|
||||
|
||||
// Component Imports
|
||||
import CustomAvatar from '@core/components/mui/Avatar'
|
||||
|
||||
// Utils
|
||||
import { getInitials } from '@/utils/getInitials'
|
||||
|
||||
// Types
|
||||
import { Reward } from '@/types/services/reward'
|
||||
import type { ThemeColor } from '@core/types'
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onConfirm: () => void
|
||||
reward: Reward | null
|
||||
isDeleting?: boolean
|
||||
}
|
||||
|
||||
// Helper function to get reward type color
|
||||
const getRewardTypeColor = (type: string): ThemeColor => {
|
||||
switch (type) {
|
||||
case 'VOUCHER':
|
||||
return 'info'
|
||||
case 'PHYSICAL':
|
||||
return 'success'
|
||||
case 'DIGITAL':
|
||||
return 'warning'
|
||||
default:
|
||||
return 'primary'
|
||||
}
|
||||
}
|
||||
|
||||
const DeleteRewardDialog = ({ open, onClose, onConfirm, reward, isDeleting = false }: Props) => {
|
||||
if (!reward) return null
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
maxWidth='sm'
|
||||
fullWidth
|
||||
aria-labelledby='delete-dialog-title'
|
||||
aria-describedby='delete-dialog-description'
|
||||
>
|
||||
<DialogTitle id='delete-dialog-title'>
|
||||
<Box display='flex' alignItems='center' gap={2}>
|
||||
<i className='tabler-trash text-red-500 text-2xl' />
|
||||
<Typography variant='h6'>Hapus Reward</Typography>
|
||||
</Box>
|
||||
</DialogTitle>
|
||||
|
||||
<DialogContent>
|
||||
<DialogContentText id='delete-dialog-description' className='mb-4'>
|
||||
Apakah Anda yakin ingin menghapus reward berikut?
|
||||
</DialogContentText>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
backgroundColor: 'grey.50',
|
||||
p: 2,
|
||||
borderRadius: 1,
|
||||
border: '1px solid',
|
||||
borderColor: 'grey.200',
|
||||
mb: 2
|
||||
}}
|
||||
>
|
||||
{/* Reward Info with Avatar */}
|
||||
<Box display='flex' alignItems='center' gap={2} className='mb-3'>
|
||||
<CustomAvatar src={reward.images?.[0]} size={50}>
|
||||
{getInitials(reward.name)}
|
||||
</CustomAvatar>
|
||||
<Box>
|
||||
<Typography variant='subtitle2' className='font-medium mb-1'>
|
||||
{reward.name}
|
||||
</Typography>
|
||||
<Chip
|
||||
label={reward.reward_type}
|
||||
color={getRewardTypeColor(reward.reward_type)}
|
||||
variant='tonal'
|
||||
size='small'
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
{/* Reward Details */}
|
||||
<Box display='flex' flexDirection='column' gap={1}>
|
||||
<Typography variant='body2' color='text.secondary'>
|
||||
<strong>Biaya Poin:</strong> {new Intl.NumberFormat('id-ID').format(reward.cost_points)} poin
|
||||
</Typography>
|
||||
|
||||
{reward.stock !== undefined && (
|
||||
<Typography variant='body2' color='text.secondary'>
|
||||
<strong>Stok:</strong>{' '}
|
||||
{reward.stock === 0 ? 'Habis' : reward.stock === null ? 'Unlimited' : reward.stock}
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
<Typography variant='body2' color='text.secondary'>
|
||||
<strong>Maks per Customer:</strong> {reward.max_per_customer} item
|
||||
</Typography>
|
||||
|
||||
{reward.tnc?.expiry_days && (
|
||||
<Typography variant='body2' color='text.secondary'>
|
||||
<strong>Berlaku Hingga:</strong> {reward.tnc.expiry_days} hari
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
<Typography variant='body2' color='text.secondary'>
|
||||
<strong>Dibuat:</strong>{' '}
|
||||
{new Date(reward.created_at).toLocaleDateString('id-ID', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric'
|
||||
})}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Alert severity='warning' sx={{ mb: 2 }}>
|
||||
<Typography variant='body2'>
|
||||
<strong>Peringatan:</strong> Tindakan ini tidak dapat dibatalkan. Semua data yang terkait dengan reward ini
|
||||
akan dihapus secara permanen.
|
||||
</Typography>
|
||||
</Alert>
|
||||
|
||||
<DialogContentText>
|
||||
Pastikan tidak ada pengguna yang masih memiliki atau menukarkan reward ini sebelum menghapus.
|
||||
</DialogContentText>
|
||||
</DialogContent>
|
||||
|
||||
<DialogActions className='p-4'>
|
||||
<Button onClick={onClose} variant='outlined' disabled={isDeleting}>
|
||||
Batal
|
||||
</Button>
|
||||
<Button
|
||||
onClick={onConfirm}
|
||||
color='error'
|
||||
variant='contained'
|
||||
disabled={isDeleting}
|
||||
startIcon={isDeleting ? <i className='tabler-loader animate-spin' /> : <i className='tabler-trash' />}
|
||||
>
|
||||
{isDeleting ? 'Menghapus...' : 'Hapus'}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export default DeleteRewardDialog
|
||||
@@ -0,0 +1,505 @@
|
||||
'use client'
|
||||
|
||||
// React Imports
|
||||
import { useEffect, useState, useMemo, useCallback } from 'react'
|
||||
|
||||
// Next Imports
|
||||
import Link from 'next/link'
|
||||
import { useParams } from 'next/navigation'
|
||||
|
||||
// MUI Imports
|
||||
import Card from '@mui/material/Card'
|
||||
import CardHeader from '@mui/material/CardHeader'
|
||||
import Button from '@mui/material/Button'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import Chip from '@mui/material/Chip'
|
||||
import Checkbox from '@mui/material/Checkbox'
|
||||
import IconButton from '@mui/material/IconButton'
|
||||
import { styled } from '@mui/material/styles'
|
||||
import TablePagination from '@mui/material/TablePagination'
|
||||
import type { TextFieldProps } from '@mui/material/TextField'
|
||||
import MenuItem from '@mui/material/MenuItem'
|
||||
|
||||
// Third-party Imports
|
||||
import classnames from 'classnames'
|
||||
import { rankItem } from '@tanstack/match-sorter-utils'
|
||||
import {
|
||||
createColumnHelper,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
useReactTable,
|
||||
getFilteredRowModel,
|
||||
getFacetedRowModel,
|
||||
getFacetedUniqueValues,
|
||||
getFacetedMinMaxValues,
|
||||
getPaginationRowModel,
|
||||
getSortedRowModel
|
||||
} from '@tanstack/react-table'
|
||||
import type { ColumnDef, FilterFn } from '@tanstack/react-table'
|
||||
import type { RankingInfo } from '@tanstack/match-sorter-utils'
|
||||
|
||||
// Type Imports
|
||||
import type { ThemeColor } from '@core/types'
|
||||
import type { Locale } from '@configs/i18n'
|
||||
|
||||
// Component Imports
|
||||
import OptionMenu from '@core/components/option-menu'
|
||||
import TablePaginationComponent from '@components/TablePaginationComponent'
|
||||
import CustomTextField from '@core/components/mui/TextField'
|
||||
import CustomAvatar from '@core/components/mui/Avatar'
|
||||
|
||||
// Util Imports
|
||||
import { getInitials } from '@/utils/getInitials'
|
||||
import { getLocalizedUrl } from '@/utils/i18n'
|
||||
import { formatCurrency } from '@/utils/transform'
|
||||
|
||||
// Style Imports
|
||||
import tableStyles from '@core/styles/table.module.css'
|
||||
import Loading from '@/components/layout/shared/Loading'
|
||||
import AddEditRewardDrawer from './AddEditRewardDrawer'
|
||||
import { Reward } from '@/types/services/reward'
|
||||
import { useRewards } from '@/services/queries/reward'
|
||||
import { useRewardsMutation } from '@/services/mutations/reward'
|
||||
import DeleteRewardDialog from './DeleteRewardDialog'
|
||||
|
||||
declare module '@tanstack/table-core' {
|
||||
interface FilterFns {
|
||||
fuzzy: FilterFn<unknown>
|
||||
}
|
||||
interface FilterMeta {
|
||||
itemRank: RankingInfo
|
||||
}
|
||||
}
|
||||
|
||||
type RewardWithAction = Reward & {
|
||||
action?: string
|
||||
}
|
||||
|
||||
// Styled Components
|
||||
const Icon = styled('i')({})
|
||||
|
||||
const fuzzyFilter: FilterFn<any> = (row, columnId, value, addMeta) => {
|
||||
// Rank the item
|
||||
const itemRank = rankItem(row.getValue(columnId), value)
|
||||
|
||||
// Store the itemRank info
|
||||
addMeta({
|
||||
itemRank
|
||||
})
|
||||
|
||||
// Return if the item should be filtered in/out
|
||||
return itemRank.passed
|
||||
}
|
||||
|
||||
const DebouncedInput = ({
|
||||
value: initialValue,
|
||||
onChange,
|
||||
debounce = 500,
|
||||
...props
|
||||
}: {
|
||||
value: string | number
|
||||
onChange: (value: string | number) => void
|
||||
debounce?: number
|
||||
} & Omit<TextFieldProps, 'onChange'>) => {
|
||||
// States
|
||||
const [value, setValue] = useState(initialValue)
|
||||
|
||||
useEffect(() => {
|
||||
setValue(initialValue)
|
||||
}, [initialValue])
|
||||
|
||||
useEffect(() => {
|
||||
const timeout = setTimeout(() => {
|
||||
onChange(value)
|
||||
}, debounce)
|
||||
|
||||
return () => clearTimeout(timeout)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [value])
|
||||
|
||||
return <CustomTextField {...props} value={value} onChange={e => setValue(e.target.value)} />
|
||||
}
|
||||
|
||||
// Helper function untuk format points - SAMA SEPERTI TIER TABLE
|
||||
const formatPoints = (points: number) => {
|
||||
return new Intl.NumberFormat('id-ID').format(points)
|
||||
}
|
||||
|
||||
// Column Definitions
|
||||
const columnHelper = createColumnHelper<RewardWithAction>()
|
||||
|
||||
const RewardListTable = () => {
|
||||
// States - PERSIS SAMA SEPERTI TIER TABLE
|
||||
const [addRewardOpen, setAddRewardOpen] = useState(false)
|
||||
const [editRewardData, setEditRewardData] = useState<Reward | undefined>(undefined)
|
||||
const [rowSelection, setRowSelection] = useState({})
|
||||
const [globalFilter, setGlobalFilter] = useState('')
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
|
||||
const [rewardToDelete, setRewardToDelete] = useState<Reward | null>(null)
|
||||
|
||||
// FIX 1: PAGINATION SAMA SEPERTI TIER (1-based, bukan 0-based)
|
||||
const [currentPage, setCurrentPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(10)
|
||||
const [search, setSearch] = useState('')
|
||||
|
||||
const { deleteReward } = useRewardsMutation()
|
||||
|
||||
const { data, isLoading, error, isFetching } = useRewards({
|
||||
page: currentPage, // SAMA SEPERTI TIER - langsung currentPage
|
||||
limit: pageSize,
|
||||
search
|
||||
})
|
||||
|
||||
const rewards = data?.rewards ?? []
|
||||
const totalCount = data?.total ?? 0
|
||||
|
||||
// Hooks
|
||||
const { lang: locale } = useParams()
|
||||
|
||||
const handlePageChange = useCallback((event: unknown, newPage: number) => {
|
||||
setCurrentPage(newPage)
|
||||
}, [])
|
||||
|
||||
const handlePageSizeChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newPageSize = parseInt(event.target.value, 10)
|
||||
setPageSize(newPageSize)
|
||||
setCurrentPage(1) // Reset to first page
|
||||
}, [])
|
||||
|
||||
const handleEditReward = (reward: Reward) => {
|
||||
setEditRewardData(reward)
|
||||
setAddRewardOpen(true)
|
||||
}
|
||||
|
||||
const handleDeleteReward = (reward: Reward) => {
|
||||
setRewardToDelete(reward)
|
||||
setDeleteDialogOpen(true)
|
||||
}
|
||||
|
||||
// ADD NEW HANDLERS FOR DELETE DIALOG
|
||||
const handleConfirmDelete = () => {
|
||||
if (rewardToDelete) {
|
||||
deleteReward.mutate(rewardToDelete.id, {
|
||||
onSuccess: () => {
|
||||
console.log('Reward deleted successfully')
|
||||
setDeleteDialogOpen(false)
|
||||
setRewardToDelete(null)
|
||||
// You might want to refetch data here
|
||||
// refetch()
|
||||
},
|
||||
onError: error => {
|
||||
console.error('Error deleting reward:', error)
|
||||
// Handle error (show toast, etc.)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const handleCloseDeleteDialog = () => {
|
||||
if (!deleteReward.isPending) {
|
||||
setDeleteDialogOpen(false)
|
||||
setRewardToDelete(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCloseRewardDrawer = () => {
|
||||
setAddRewardOpen(false)
|
||||
setEditRewardData(undefined)
|
||||
}
|
||||
|
||||
// Helper function to get reward type color
|
||||
const getRewardTypeColor = (type: string): ThemeColor => {
|
||||
switch (type) {
|
||||
case 'VOUCHER':
|
||||
return 'info'
|
||||
case 'PHYSICAL':
|
||||
return 'success'
|
||||
case 'DIGITAL':
|
||||
return 'warning'
|
||||
default:
|
||||
return 'primary'
|
||||
}
|
||||
}
|
||||
|
||||
const columns = useMemo<ColumnDef<RewardWithAction, any>[]>(
|
||||
() => [
|
||||
{
|
||||
id: 'select',
|
||||
header: ({ table }) => (
|
||||
<Checkbox
|
||||
{...{
|
||||
checked: table.getIsAllRowsSelected(),
|
||||
indeterminate: table.getIsSomeRowsSelected(),
|
||||
onChange: table.getToggleAllRowsSelectedHandler()
|
||||
}}
|
||||
/>
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<Checkbox
|
||||
{...{
|
||||
checked: row.getIsSelected(),
|
||||
disabled: !row.getCanSelect(),
|
||||
indeterminate: row.getIsSomeSelected(),
|
||||
onChange: row.getToggleSelectedHandler()
|
||||
}}
|
||||
/>
|
||||
)
|
||||
},
|
||||
columnHelper.accessor('name', {
|
||||
header: 'Nama Reward',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-4'>
|
||||
<CustomAvatar src={row.original.images?.[0]} size={40}>
|
||||
{getInitials(row.original.name)}
|
||||
</CustomAvatar>
|
||||
<div className='flex flex-col'>
|
||||
<Link href={getLocalizedUrl(`/apps/rewards/${row.original.id}/detail`, locale as Locale)}>
|
||||
<Typography className='font-medium cursor-pointer hover:underline text-primary'>
|
||||
{row.original.name}
|
||||
</Typography>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('reward_type', {
|
||||
header: 'Tipe Reward',
|
||||
cell: ({ row }) => (
|
||||
<Chip
|
||||
label={row.original.reward_type}
|
||||
color={getRewardTypeColor(row.original.reward_type)}
|
||||
variant='tonal'
|
||||
size='small'
|
||||
/>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('cost_points', {
|
||||
header: 'Biaya Poin',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-2'>
|
||||
<Icon className='tabler-star-filled' sx={{ color: 'var(--mui-palette-warning-main)' }} />
|
||||
<Typography color='text.primary' className='font-medium'>
|
||||
{/* FIX 2: GUNAKAN formatPoints YANG SAMA SEPERTI TIER */}
|
||||
{formatPoints(row.original.cost_points)} poin
|
||||
</Typography>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('stock', {
|
||||
header: 'Stok',
|
||||
cell: ({ row }) => {
|
||||
const stock = row.original.stock
|
||||
const stockColor = stock === 0 ? 'error' : stock && stock <= 10 ? 'warning' : 'success'
|
||||
const stockText = stock === undefined ? 'Unlimited' : stock === 0 ? 'Habis' : stock.toString()
|
||||
|
||||
return <Chip label={stockText} color={stockColor} variant='tonal' size='small' />
|
||||
}
|
||||
}),
|
||||
columnHelper.accessor('max_per_customer', {
|
||||
header: 'Maks/Customer',
|
||||
cell: ({ row }) => <Typography color='text.primary'>{row.original.max_per_customer} item</Typography>
|
||||
}),
|
||||
columnHelper.accessor('tnc', {
|
||||
header: 'Berlaku Hingga',
|
||||
cell: ({ row }) => <Typography color='text.primary'>{row.original.tnc?.expiry_days} days</Typography>
|
||||
}),
|
||||
columnHelper.accessor('created_at', {
|
||||
header: 'Tanggal Dibuat',
|
||||
cell: ({ row }) => (
|
||||
<Typography color='text.primary'>
|
||||
{/* FIX 3: FORMAT DATE YANG SAMA SEPERTI TIER */}
|
||||
{new Date(row.original.created_at).toLocaleDateString('id-ID', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
})}
|
||||
</Typography>
|
||||
)
|
||||
}),
|
||||
{
|
||||
id: 'actions',
|
||||
header: 'Aksi',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center'>
|
||||
<OptionMenu
|
||||
iconButtonProps={{ size: 'medium' }}
|
||||
iconClassName='text-textSecondary text-[22px]'
|
||||
options={[
|
||||
{
|
||||
text: 'Edit',
|
||||
icon: 'tabler-edit text-[22px]',
|
||||
menuItemProps: {
|
||||
className: 'flex items-center gap-2 text-textSecondary',
|
||||
onClick: () => handleEditReward(row.original)
|
||||
}
|
||||
},
|
||||
{
|
||||
text: 'Hapus',
|
||||
icon: 'tabler-trash text-[22px]',
|
||||
menuItemProps: {
|
||||
className: 'flex items-center gap-2 text-textSecondary',
|
||||
onClick: () => handleDeleteReward(row.original)
|
||||
}
|
||||
}
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
enableSorting: false
|
||||
}
|
||||
],
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[locale, handleEditReward, handleDeleteReward]
|
||||
)
|
||||
|
||||
// FIX 4: TABLE CONFIG YANG SAMA PERSIS SEPERTI TIER
|
||||
const table = useReactTable({
|
||||
data: rewards as Reward[], // SAMA SEPERTI TIER
|
||||
columns,
|
||||
filterFns: {
|
||||
fuzzy: fuzzyFilter
|
||||
},
|
||||
state: {
|
||||
rowSelection,
|
||||
globalFilter,
|
||||
pagination: {
|
||||
pageIndex: currentPage, // SAMA SEPERTI TIER - langsung currentPage
|
||||
pageSize
|
||||
}
|
||||
},
|
||||
enableRowSelection: true,
|
||||
onRowSelectionChange: setRowSelection,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
manualPagination: true, // SAMA SEPERTI TIER
|
||||
pageCount: Math.ceil(totalCount / pageSize) // SAMA SEPERTI TIER
|
||||
})
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card>
|
||||
<div className='flex justify-between flex-col items-start md:flex-row md:items-center p-6 border-bs gap-4'>
|
||||
<CustomTextField
|
||||
select
|
||||
value={table.getState().pagination.pageSize}
|
||||
onChange={e => table.setPageSize(Number(e.target.value))}
|
||||
className='max-sm:is-full sm:is-[70px]'
|
||||
>
|
||||
<MenuItem value='10'>10</MenuItem>
|
||||
<MenuItem value='25'>25</MenuItem>
|
||||
<MenuItem value='50'>50</MenuItem>
|
||||
</CustomTextField>
|
||||
<div className='flex flex-col sm:flex-row max-sm:is-full items-start sm:items-center gap-4'>
|
||||
<DebouncedInput
|
||||
value={search ?? ''}
|
||||
onChange={value => setSearch(value as string)}
|
||||
placeholder='Cari Reward'
|
||||
className='max-sm:is-full'
|
||||
/>
|
||||
<Button
|
||||
color='secondary'
|
||||
variant='tonal'
|
||||
startIcon={<i className='tabler-upload' />}
|
||||
className='max-sm:is-full'
|
||||
>
|
||||
Ekspor
|
||||
</Button>
|
||||
<Button
|
||||
variant='contained'
|
||||
startIcon={<i className='tabler-plus' />}
|
||||
onClick={() => setAddRewardOpen(!addRewardOpen)}
|
||||
className='max-sm:is-full'
|
||||
>
|
||||
Tambah Reward
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className='overflow-x-auto'>
|
||||
{isLoading ? (
|
||||
<Loading />
|
||||
) : (
|
||||
<table className={tableStyles.table}>
|
||||
<thead>
|
||||
{table.getHeaderGroups().map(headerGroup => (
|
||||
<tr key={headerGroup.id}>
|
||||
{headerGroup.headers.map(header => (
|
||||
<th key={header.id}>
|
||||
{header.isPlaceholder ? null : (
|
||||
<>
|
||||
<div
|
||||
className={classnames({
|
||||
'flex items-center': header.column.getIsSorted(),
|
||||
'cursor-pointer select-none': header.column.getCanSort()
|
||||
})}
|
||||
onClick={header.column.getToggleSortingHandler()}
|
||||
>
|
||||
{flexRender(header.column.columnDef.header, header.getContext())}
|
||||
{{
|
||||
asc: <i className='tabler-chevron-up text-xl' />,
|
||||
desc: <i className='tabler-chevron-down text-xl' />
|
||||
}[header.column.getIsSorted() as 'asc' | 'desc'] ?? null}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
{table.getFilteredRowModel().rows.length === 0 ? (
|
||||
<tbody>
|
||||
<tr>
|
||||
<td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
|
||||
Tidak ada data tersedia
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
) : (
|
||||
<tbody>
|
||||
{table
|
||||
.getRowModel()
|
||||
.rows.slice(0, table.getState().pagination.pageSize)
|
||||
.map(row => {
|
||||
return (
|
||||
<tr key={row.id} className={classnames({ selected: row.getIsSelected() })}>
|
||||
{row.getVisibleCells().map(cell => (
|
||||
<td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
|
||||
))}
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
)}
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
<TablePagination
|
||||
component={() => (
|
||||
<TablePaginationComponent
|
||||
pageIndex={currentPage}
|
||||
pageSize={pageSize}
|
||||
totalCount={totalCount}
|
||||
onPageChange={handlePageChange}
|
||||
/>
|
||||
)}
|
||||
count={totalCount}
|
||||
rowsPerPage={pageSize}
|
||||
page={currentPage}
|
||||
onPageChange={handlePageChange}
|
||||
onRowsPerPageChange={handlePageSizeChange}
|
||||
rowsPerPageOptions={[10, 25, 50]}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</Card>
|
||||
<AddEditRewardDrawer open={addRewardOpen} handleClose={handleCloseRewardDrawer} data={editRewardData} />
|
||||
<DeleteRewardDialog
|
||||
open={deleteDialogOpen}
|
||||
onClose={handleCloseDeleteDialog}
|
||||
onConfirm={handleConfirmDelete}
|
||||
reward={rewardToDelete}
|
||||
isDeleting={deleteReward?.isPending || false}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default RewardListTable
|
||||
@@ -0,0 +1,17 @@
|
||||
// MUI Imports
|
||||
import Grid from '@mui/material/Grid2'
|
||||
import RewardListTable from './RewardListTable'
|
||||
|
||||
// Type Imports
|
||||
|
||||
const RewardList = () => {
|
||||
return (
|
||||
<Grid container spacing={6}>
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<RewardListTable />
|
||||
</Grid>
|
||||
</Grid>
|
||||
)
|
||||
}
|
||||
|
||||
export default RewardList
|
||||
@@ -0,0 +1,507 @@
|
||||
// React Imports
|
||||
import { useState, useEffect } from 'react'
|
||||
|
||||
// MUI Imports
|
||||
import Button from '@mui/material/Button'
|
||||
import Drawer from '@mui/material/Drawer'
|
||||
import IconButton from '@mui/material/IconButton'
|
||||
import MenuItem from '@mui/material/MenuItem'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import Divider from '@mui/material/Divider'
|
||||
import Grid from '@mui/material/Grid2'
|
||||
import Box from '@mui/material/Box'
|
||||
import Switch from '@mui/material/Switch'
|
||||
import FormControlLabel from '@mui/material/FormControlLabel'
|
||||
import Chip from '@mui/material/Chip'
|
||||
import InputAdornment from '@mui/material/InputAdornment'
|
||||
import Select from '@mui/material/Select'
|
||||
import FormControl from '@mui/material/FormControl'
|
||||
import InputLabel from '@mui/material/InputLabel'
|
||||
|
||||
// Third-party Imports
|
||||
import { useForm, Controller } from 'react-hook-form'
|
||||
|
||||
// Component Imports
|
||||
import CustomTextField from '@core/components/mui/TextField'
|
||||
import { Tier, TierRequest } from '@/types/services/tier'
|
||||
import { useTiersMutation } from '@/services/mutations/tier'
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
handleClose: () => void
|
||||
data?: Tier // Data tier untuk edit (jika ada)
|
||||
}
|
||||
|
||||
// Static benefit keys with their configurations
|
||||
const STATIC_BENEFIT_KEYS = {
|
||||
birthday_bonus: {
|
||||
label: 'Birthday Bonus',
|
||||
type: 'boolean' as const,
|
||||
description: 'Bonus ulang tahun khusus member'
|
||||
},
|
||||
exclusive_discounts: {
|
||||
label: 'Exclusive Discounts',
|
||||
type: 'boolean' as const,
|
||||
description: 'Akses diskon eksklusif'
|
||||
},
|
||||
point_multiplier: {
|
||||
label: 'Point Multiplier',
|
||||
type: 'number' as const,
|
||||
description: 'Pengali poin (contoh: 1.1 = +10%)',
|
||||
suffix: 'x'
|
||||
},
|
||||
priority_support: {
|
||||
label: 'Priority Support',
|
||||
type: 'boolean' as const,
|
||||
description: 'Dukungan pelanggan prioritas'
|
||||
},
|
||||
special_discount: {
|
||||
label: 'Special Discount',
|
||||
type: 'number' as const,
|
||||
description: 'Diskon khusus dalam persen',
|
||||
suffix: '%'
|
||||
}
|
||||
} as const
|
||||
|
||||
// Benefit item type
|
||||
type BenefitItem = {
|
||||
key: keyof typeof STATIC_BENEFIT_KEYS
|
||||
value: any
|
||||
type: 'boolean' | 'number' | 'string'
|
||||
}
|
||||
|
||||
type FormValidateType = {
|
||||
name: string
|
||||
min_points: number
|
||||
benefits: BenefitItem[]
|
||||
}
|
||||
|
||||
// Initial form data
|
||||
const initialData: FormValidateType = {
|
||||
name: '',
|
||||
min_points: 0,
|
||||
benefits: []
|
||||
}
|
||||
|
||||
const AddEditTierDrawer = (props: Props) => {
|
||||
// Props
|
||||
const { open, handleClose, data } = props
|
||||
|
||||
// States
|
||||
const [showMore, setShowMore] = useState(false)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
|
||||
const { createTier, updateTier } = useTiersMutation()
|
||||
|
||||
// Determine if this is edit mode
|
||||
const isEditMode = Boolean(data?.id)
|
||||
|
||||
// Hooks
|
||||
const {
|
||||
control,
|
||||
reset: resetForm,
|
||||
handleSubmit,
|
||||
watch,
|
||||
setValue,
|
||||
formState: { errors }
|
||||
} = useForm<FormValidateType>({
|
||||
defaultValues: initialData
|
||||
})
|
||||
|
||||
const watchedBenefits = watch('benefits')
|
||||
|
||||
// Helper function to convert benefits object to BenefitItem array
|
||||
const convertBenefitsToArray = (benefits: Record<string, any>): BenefitItem[] => {
|
||||
if (!benefits) return []
|
||||
return Object.entries(benefits)
|
||||
.filter(([key]) => key in STATIC_BENEFIT_KEYS)
|
||||
.map(([key, value]) => ({
|
||||
key: key as keyof typeof STATIC_BENEFIT_KEYS,
|
||||
value,
|
||||
type: STATIC_BENEFIT_KEYS[key as keyof typeof STATIC_BENEFIT_KEYS].type
|
||||
}))
|
||||
}
|
||||
|
||||
// Helper function to convert BenefitItem array to benefits object
|
||||
const convertBenefitsToObject = (benefits: BenefitItem[]): Record<string, any> => {
|
||||
const benefitsObj: Record<string, any> = {}
|
||||
benefits.forEach(benefit => {
|
||||
let value = benefit.value
|
||||
// Convert string values to appropriate types
|
||||
if (benefit.type === 'boolean') {
|
||||
value = value === true || value === 'true' || value === 'yes'
|
||||
} else if (benefit.type === 'number') {
|
||||
value = Number(value)
|
||||
}
|
||||
benefitsObj[benefit.key] = value
|
||||
})
|
||||
return benefitsObj
|
||||
}
|
||||
|
||||
// Helper function to format benefit display
|
||||
const formatBenefitDisplay = (item: BenefitItem): string => {
|
||||
const config = STATIC_BENEFIT_KEYS[item.key]
|
||||
|
||||
if (item.type === 'boolean') {
|
||||
return `${config.label}: ${item.value ? 'Ya' : 'Tidak'}`
|
||||
} else if (item.type === 'number') {
|
||||
const suffix = config.suffix || ''
|
||||
return `${config.label}: ${item.value}${suffix}`
|
||||
}
|
||||
return `${config.label}: ${item.value}`
|
||||
}
|
||||
|
||||
// Get available benefit keys (not already added)
|
||||
const getAvailableBenefitKeys = () => {
|
||||
const usedKeys = watchedBenefits?.map(b => b.key) || []
|
||||
return Object.entries(STATIC_BENEFIT_KEYS)
|
||||
.filter(([key]) => !usedKeys.includes(key as keyof typeof STATIC_BENEFIT_KEYS))
|
||||
.map(([key, config]) => ({
|
||||
key: key as keyof typeof STATIC_BENEFIT_KEYS,
|
||||
...config
|
||||
}))
|
||||
}
|
||||
|
||||
// Effect to populate form when editing
|
||||
useEffect(() => {
|
||||
if (isEditMode && data) {
|
||||
// Convert benefits object to array for form handling
|
||||
const benefitsArray = convertBenefitsToArray(data.benefits)
|
||||
|
||||
// Populate form with existing data
|
||||
const formData: FormValidateType = {
|
||||
name: data.name || '',
|
||||
min_points: data.min_points || 0,
|
||||
benefits: benefitsArray
|
||||
}
|
||||
|
||||
resetForm(formData)
|
||||
setShowMore(true) // Always show more for edit mode
|
||||
} else {
|
||||
// Reset to initial data for add mode
|
||||
resetForm(initialData)
|
||||
setShowMore(false)
|
||||
}
|
||||
}, [data, isEditMode, resetForm])
|
||||
|
||||
const handleFormSubmit = async (formData: FormValidateType) => {
|
||||
try {
|
||||
setIsSubmitting(true)
|
||||
|
||||
// Convert benefits array back to object format
|
||||
const benefitsObj = convertBenefitsToObject(formData.benefits)
|
||||
|
||||
// Create TierRequest object
|
||||
const tierRequest: TierRequest = {
|
||||
name: formData.name,
|
||||
min_points: formData.min_points,
|
||||
benefits: benefitsObj
|
||||
}
|
||||
|
||||
console.log('Submitting tier data:', tierRequest)
|
||||
|
||||
if (isEditMode && data?.id) {
|
||||
// Update existing tier
|
||||
updateTier.mutate(
|
||||
{ id: data.id, payload: tierRequest },
|
||||
{
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
handleClose()
|
||||
}
|
||||
}
|
||||
)
|
||||
} else {
|
||||
// Create new tier
|
||||
createTier.mutate(tierRequest, {
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
handleClose()
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error submitting tier:', error)
|
||||
// Handle error (show toast, etc.)
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleReset = () => {
|
||||
handleClose()
|
||||
resetForm(initialData)
|
||||
setShowMore(false)
|
||||
}
|
||||
|
||||
// Get placeholder and validation info based on selected benefit key
|
||||
const getBenefitInputInfo = () => {
|
||||
return { placeholder: 'Tidak diperlukan lagi', type: 'text' }
|
||||
}
|
||||
|
||||
const formatNumber = (value: number) => {
|
||||
return new Intl.NumberFormat('id-ID').format(value)
|
||||
}
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
open={open}
|
||||
anchor='right'
|
||||
variant='temporary'
|
||||
onClose={handleReset}
|
||||
ModalProps={{ keepMounted: true }}
|
||||
sx={{
|
||||
'& .MuiDrawer-paper': {
|
||||
width: { xs: 300, sm: 400 },
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
height: '100%'
|
||||
}
|
||||
}}
|
||||
>
|
||||
{/* Sticky Header */}
|
||||
<Box
|
||||
sx={{
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
zIndex: 10,
|
||||
backgroundColor: 'background.paper',
|
||||
borderBottom: 1,
|
||||
borderColor: 'divider'
|
||||
}}
|
||||
>
|
||||
<div className='flex items-center justify-between plb-5 pli-6'>
|
||||
<Typography variant='h5'>{isEditMode ? 'Edit Tier' : 'Tambah Tier Baru'}</Typography>
|
||||
<IconButton size='small' onClick={handleReset}>
|
||||
<i className='tabler-x text-2xl text-textPrimary' />
|
||||
</IconButton>
|
||||
</div>
|
||||
</Box>
|
||||
|
||||
{/* Scrollable Content */}
|
||||
<Box sx={{ flex: 1, overflowY: 'auto' }}>
|
||||
<form id='tier-form' onSubmit={handleSubmit(handleFormSubmit)}>
|
||||
<div className='flex flex-col gap-6 p-6'>
|
||||
{/* Nama Tier */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Nama Tier <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='name'
|
||||
control={control}
|
||||
rules={{ required: 'Nama tier wajib diisi' }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='Masukkan nama tier (contoh: Bronze, Silver, Gold)'
|
||||
error={!!errors.name}
|
||||
helperText={errors.name?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Minimum Points */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Minimum Poin <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='min_points'
|
||||
control={control}
|
||||
rules={{
|
||||
required: 'Minimum poin wajib diisi',
|
||||
min: {
|
||||
value: 0,
|
||||
message: 'Minimum poin tidak boleh negatif'
|
||||
}
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='number'
|
||||
placeholder='0'
|
||||
error={!!errors.min_points}
|
||||
helperText={
|
||||
errors.min_points?.message || (field.value > 0 ? `${formatNumber(field.value)} poin` : '')
|
||||
}
|
||||
InputProps={{
|
||||
endAdornment: <InputAdornment position='end'>poin</InputAdornment>
|
||||
}}
|
||||
onChange={e => field.onChange(Number(e.target.value))}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Benefits */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-3'>
|
||||
Manfaat Tier <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
|
||||
{/* All Benefits in Horizontal Layout */}
|
||||
<div className='space-y-4'>
|
||||
{Object.entries(STATIC_BENEFIT_KEYS).map(([key, config]) => {
|
||||
const benefitKey = key as keyof typeof STATIC_BENEFIT_KEYS
|
||||
const existingBenefit = watchedBenefits?.find(b => b.key === benefitKey)
|
||||
const isActive = Boolean(existingBenefit)
|
||||
|
||||
return (
|
||||
<div key={benefitKey} className='border rounded-lg p-3'>
|
||||
<div className='flex items-center justify-between mb-2'>
|
||||
<div className='flex-1'>
|
||||
<Typography variant='body2' className='font-medium'>
|
||||
{config.label}
|
||||
</Typography>
|
||||
<Typography variant='caption' color='text.secondary'>
|
||||
{config.description}
|
||||
</Typography>
|
||||
</div>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Switch
|
||||
checked={isActive}
|
||||
onChange={e => {
|
||||
if (e.target.checked) {
|
||||
// Add default benefit
|
||||
const defaultValue =
|
||||
config.type === 'boolean'
|
||||
? true
|
||||
: config.type === 'number'
|
||||
? benefitKey === 'point_multiplier'
|
||||
? 1.1
|
||||
: benefitKey === 'special_discount'
|
||||
? 5
|
||||
: 1
|
||||
: ''
|
||||
|
||||
const newBenefit: BenefitItem = {
|
||||
key: benefitKey,
|
||||
value: defaultValue,
|
||||
type: config.type
|
||||
}
|
||||
|
||||
const currentBenefits = watchedBenefits || []
|
||||
setValue('benefits', [...currentBenefits, newBenefit])
|
||||
} else {
|
||||
// Remove benefit
|
||||
const currentBenefits = watchedBenefits || []
|
||||
const newBenefits = currentBenefits.filter(b => b.key !== benefitKey)
|
||||
setValue('benefits', newBenefits)
|
||||
}
|
||||
}}
|
||||
size='small'
|
||||
/>
|
||||
}
|
||||
label=''
|
||||
sx={{ margin: 0 }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Value Input - Only show when active */}
|
||||
{isActive && (
|
||||
<div className='mt-2'>
|
||||
{config.type === 'boolean' ? (
|
||||
<FormControl size='small' fullWidth>
|
||||
<Select
|
||||
value={existingBenefit?.value ? 'true' : 'false'}
|
||||
onChange={e => {
|
||||
const currentBenefits = watchedBenefits || []
|
||||
const updatedBenefits = currentBenefits.map(b =>
|
||||
b.key === benefitKey ? { ...b, value: e.target.value === 'true' } : b
|
||||
)
|
||||
setValue('benefits', updatedBenefits)
|
||||
}}
|
||||
>
|
||||
<MenuItem value='true'>Ya</MenuItem>
|
||||
<MenuItem value='false'>Tidak</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
) : (
|
||||
<CustomTextField
|
||||
fullWidth
|
||||
size='small'
|
||||
type='number'
|
||||
value={existingBenefit?.value || ''}
|
||||
onChange={e => {
|
||||
const newValue = Number(e.target.value)
|
||||
if (!isNaN(newValue)) {
|
||||
const currentBenefits = watchedBenefits || []
|
||||
const updatedBenefits = currentBenefits.map(b =>
|
||||
b.key === benefitKey ? { ...b, value: newValue } : b
|
||||
)
|
||||
setValue('benefits', updatedBenefits)
|
||||
}
|
||||
}}
|
||||
placeholder={
|
||||
benefitKey === 'point_multiplier'
|
||||
? 'Contoh: 1.1, 1.5, 2.0'
|
||||
: benefitKey === 'special_discount'
|
||||
? 'Contoh: 5, 10, 15'
|
||||
: 'Masukkan angka'
|
||||
}
|
||||
InputProps={{
|
||||
endAdornment: config.suffix && (
|
||||
<InputAdornment position='end'>{config.suffix}</InputAdornment>
|
||||
),
|
||||
inputProps: {
|
||||
step: benefitKey === 'point_multiplier' ? '0.1' : '1',
|
||||
min: benefitKey === 'point_multiplier' ? '0.1' : '0',
|
||||
max: benefitKey === 'special_discount' ? '100' : undefined
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{(!watchedBenefits || watchedBenefits.length === 0) && (
|
||||
<Typography variant='caption' color='error' className='mt-2 block'>
|
||||
Minimal satu manfaat harus diaktifkan
|
||||
</Typography>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</Box>
|
||||
|
||||
{/* Sticky Footer */}
|
||||
<Box
|
||||
sx={{
|
||||
position: 'sticky',
|
||||
bottom: 0,
|
||||
zIndex: 10,
|
||||
backgroundColor: 'background.paper',
|
||||
borderTop: 1,
|
||||
borderColor: 'divider',
|
||||
p: 3
|
||||
}}
|
||||
>
|
||||
<div className='flex items-center gap-4'>
|
||||
<Button
|
||||
variant='contained'
|
||||
type='submit'
|
||||
form='tier-form'
|
||||
disabled={isSubmitting || !watchedBenefits || watchedBenefits.length === 0}
|
||||
startIcon={isSubmitting ? <i className='tabler-loader animate-spin' /> : null}
|
||||
>
|
||||
{isSubmitting ? (isEditMode ? 'Mengupdate...' : 'Menyimpan...') : isEditMode ? 'Update' : 'Simpan'}
|
||||
</Button>
|
||||
<Button variant='outlined' color='error' onClick={handleReset} disabled={isSubmitting}>
|
||||
Batal
|
||||
</Button>
|
||||
</div>
|
||||
</Box>
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
|
||||
export default AddEditTierDrawer
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user