Compare commits
93
Commits
54c7598e7a
...
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 | ||
|
|
7f646b82a9 | ||
|
|
fab31f1540 | ||
|
|
aa2946e627 | ||
|
|
2d3274d3bf | ||
|
|
e1084277e0 | ||
|
|
222beb5043 | ||
|
|
98d6446b0c | ||
|
|
d54d623d4c | ||
|
|
140822763e | ||
|
|
0b51b29474 | ||
|
|
20203942d2 | ||
|
|
b2840ca27c | ||
|
|
ce344e4a98 | ||
|
|
2d69a024c1 | ||
|
|
27fe48e99e | ||
|
|
5a0d96ee43 | ||
|
|
9cbb41c2ad | ||
|
|
76ee71e7fe | ||
|
|
e8c1d02843 |
@@ -39,3 +39,5 @@ next-env.d.ts
|
|||||||
# icon generated file
|
# icon generated file
|
||||||
src/assets/iconify-icons/generated-icons.js
|
src/assets/iconify-icons/generated-icons.js
|
||||||
src/assets/iconify-icons/generated-icons.css
|
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/list": "6.1.15",
|
||||||
"@fullcalendar/react": "6.1.15",
|
"@fullcalendar/react": "6.1.15",
|
||||||
"@fullcalendar/timegrid": "6.1.15",
|
"@fullcalendar/timegrid": "6.1.15",
|
||||||
|
"@hello-pangea/dnd": "^18.0.1",
|
||||||
"@hookform/resolvers": "3.9.1",
|
"@hookform/resolvers": "3.9.1",
|
||||||
"@iconify/react": "^6.0.1",
|
"@iconify/react": "^6.0.1",
|
||||||
"@mui/lab": "6.0.0-beta.19",
|
"@mui/lab": "6.0.0-beta.19",
|
||||||
@@ -52,18 +53,23 @@
|
|||||||
"apexcharts": "3.49.0",
|
"apexcharts": "3.49.0",
|
||||||
"axios": "^1.11.0",
|
"axios": "^1.11.0",
|
||||||
"bootstrap-icons": "1.11.3",
|
"bootstrap-icons": "1.11.3",
|
||||||
|
"chart.js": "^4.5.1",
|
||||||
|
"chartjs-plugin-datalabels": "^2.2.0",
|
||||||
"classnames": "2.5.1",
|
"classnames": "2.5.1",
|
||||||
"cmdk": "1.0.4",
|
"cmdk": "1.0.4",
|
||||||
"date-fns": "4.1.0",
|
"date-fns": "4.1.0",
|
||||||
"emoji-mart": "5.6.0",
|
"emoji-mart": "5.6.0",
|
||||||
|
"exceljs": "^4.4.0",
|
||||||
"fs-extra": "11.2.0",
|
"fs-extra": "11.2.0",
|
||||||
"html2canvas": "^1.4.1",
|
"html2canvas": "^1.4.1",
|
||||||
"input-otp": "1.4.1",
|
"input-otp": "1.4.1",
|
||||||
"jspdf": "^3.0.1",
|
"jspdf": "^3.0.1",
|
||||||
|
"jspdf-autotable": "^5.0.2",
|
||||||
"keen-slider": "6.8.6",
|
"keen-slider": "6.8.6",
|
||||||
|
"lucide-react": "^0.544.0",
|
||||||
"mapbox-gl": "3.9.0",
|
"mapbox-gl": "3.9.0",
|
||||||
"negotiator": "1.0.0",
|
"negotiator": "1.0.0",
|
||||||
"next": "15.1.2",
|
"next": "^15.1.9",
|
||||||
"react": "18.3.1",
|
"react": "18.3.1",
|
||||||
"react-apexcharts": "1.4.1",
|
"react-apexcharts": "1.4.1",
|
||||||
"react-colorful": "5.6.1",
|
"react-colorful": "5.6.1",
|
||||||
@@ -79,7 +85,8 @@
|
|||||||
"react-use": "17.6.0",
|
"react-use": "17.6.0",
|
||||||
"recharts": "2.15.0",
|
"recharts": "2.15.0",
|
||||||
"use-debounce": "^10.0.5",
|
"use-debounce": "^10.0.5",
|
||||||
"valibot": "0.42.1"
|
"valibot": "0.42.1",
|
||||||
|
"xlsx": "^0.18.5"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@iconify/json": "2.2.286",
|
"@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
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
import PurchaseDetailContent from '@/views/apps/purchase/purchase-detail/PurchaseDetailContent'
|
||||||
|
import PurchaseDetailHeader from '@/views/apps/purchase/purchase-detail/PurchaseDetailHeader'
|
||||||
|
import Grid from '@mui/material/Grid2'
|
||||||
|
|
||||||
|
const PurchaseOrderDetailPage = () => {
|
||||||
|
return (
|
||||||
|
<Grid container spacing={6}>
|
||||||
|
<Grid size={{ xs: 12 }}>
|
||||||
|
<PurchaseDetailHeader title='Detail Pesanan Pembelian' />
|
||||||
|
</Grid>
|
||||||
|
<Grid size={{ xs: 12 }}>
|
||||||
|
<PurchaseDetailContent />
|
||||||
|
</Grid>
|
||||||
|
</Grid>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default PurchaseOrderDetailPage
|
||||||
@@ -8,23 +8,63 @@ import {
|
|||||||
useCategoryAnalytics
|
useCategoryAnalytics
|
||||||
} from '@/services/queries/analytics'
|
} from '@/services/queries/analytics'
|
||||||
import { useOutletById } from '@/services/queries/outlets'
|
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 { formatCurrency, formatDate, formatDateDDMMYYYY, formatDatetime } from '@/utils/transform'
|
||||||
import ReportGeneratorComponent from '@/views/dashboards/daily-report/report-generator'
|
import ReportGeneratorComponent from '@/views/dashboards/daily-report/report-generator'
|
||||||
import ReportHeader from '@/views/dashboards/daily-report/report-header'
|
import ReportHeader from '@/views/dashboards/daily-report/report-header'
|
||||||
import React, { useEffect, useRef, useState } from 'react'
|
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 DailyPOSReport = () => {
|
||||||
const reportRef = useRef<HTMLDivElement | null>(null)
|
const reportRef = useRef<HTMLDivElement | null>(null)
|
||||||
|
|
||||||
|
const [isGeneratingExcel, setIsGeneratingExcel] = useState(false)
|
||||||
|
|
||||||
const [now, setNow] = useState(new Date())
|
const [now, setNow] = useState(new Date())
|
||||||
const [selectedDate, setSelectedDate] = useState(new Date())
|
const [selectedDate, setSelectedDate] = useState(new Date())
|
||||||
const [dateRange, setDateRange] = useState({
|
const [dateRange, setDateRange] = useState({
|
||||||
startDate: new Date(),
|
startDate: new Date(),
|
||||||
endDate: 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 = () => {
|
const getDateParams = () => {
|
||||||
if (filterType === 'single') {
|
if (filterType === 'single') {
|
||||||
return {
|
return {
|
||||||
@@ -41,8 +81,15 @@ const DailyPOSReport = () => {
|
|||||||
|
|
||||||
const dateParams = getDateParams()
|
const dateParams = getDateParams()
|
||||||
|
|
||||||
|
const today = new Date()
|
||||||
|
const sevenDaysAgo = new Date()
|
||||||
|
sevenDaysAgo.setDate(today.getDate() - 7)
|
||||||
|
|
||||||
const { data: outlet } = useOutletById()
|
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: profitLoss } = useProfitLossAnalytics(dateParams)
|
||||||
const { data: products } = useProductSalesAnalytics(dateParams)
|
const { data: products } = useProductSalesAnalytics(dateParams)
|
||||||
const { data: paymentAnalytics } = usePaymentAnalytics(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
|
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 = {
|
const categorySummary = {
|
||||||
totalRevenue: category?.data?.reduce((sum, item) => sum + (item?.total_revenue || 0), 0) || 0,
|
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,
|
orderCount: category?.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0,
|
||||||
@@ -73,12 +112,10 @@ const DailyPOSReport = () => {
|
|||||||
setNow(new Date())
|
setNow(new Date())
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
// Format date for input field (YYYY-MM-DD)
|
|
||||||
const formatDateForInput = (date: Date) => {
|
const formatDateForInput = (date: Date) => {
|
||||||
return date.toISOString().split('T')[0]
|
return date.toISOString().split('T')[0]
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get display text for the report period
|
|
||||||
const getReportPeriodText = () => {
|
const getReportPeriodText = () => {
|
||||||
if (filterType === 'single') {
|
if (filterType === 'single') {
|
||||||
return `${formatDateDDMMYYYY(selectedDate)} - ${formatDateDDMMYYYY(selectedDate)}`
|
return `${formatDateDDMMYYYY(selectedDate)} - ${formatDateDDMMYYYY(selectedDate)}`
|
||||||
@@ -87,98 +124,107 @@ const DailyPOSReport = () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get report title based on filter type
|
|
||||||
const getReportTitle = () => {
|
const getReportTitle = () => {
|
||||||
if (filterType === 'single') {
|
return 'Laporan Transaksi'
|
||||||
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`
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleGeneratePDF = async () => {
|
const handleGeneratePDF = async () => {
|
||||||
const reportElement = reportRef.current
|
setIsGeneratingPDF(true)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Import jsPDF dan html2canvas
|
await generatePDF({
|
||||||
const jsPDF = (await import('jspdf')).default
|
reportRef,
|
||||||
const html2canvas = (await import('html2canvas')).default
|
outlet,
|
||||||
|
profitLoss,
|
||||||
// Optimized canvas capture dengan scale lebih rendah
|
products,
|
||||||
const canvas = await html2canvas(reportElement!, {
|
paymentAnalytics,
|
||||||
scale: 1.5, // Reduced from 2 to 1.5
|
category,
|
||||||
useCORS: true,
|
productSummary,
|
||||||
allowTaint: true,
|
categorySummary,
|
||||||
backgroundColor: '#ffffff',
|
filterType,
|
||||||
logging: false, // Disable logging for performance
|
selectedDate,
|
||||||
removeContainer: true, // Clean up after capture
|
dateRange,
|
||||||
imageTimeout: 0, // No timeout for image loading
|
now
|
||||||
height: reportElement!.scrollHeight,
|
|
||||||
width: reportElement!.scrollWidth
|
|
||||||
})
|
})
|
||||||
|
|
||||||
// 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) {
|
} catch (error) {
|
||||||
console.error('Error generating PDF:', 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 (
|
return (
|
||||||
<div className='min-h-screen'>
|
<div className='min-h-screen'>
|
||||||
{/* Control Panel */}
|
<LoadingOverlay isVisible={isGeneratingPDF} message='Membuat PDF Laporan...' />
|
||||||
|
|
||||||
<ReportGeneratorComponent
|
<ReportGeneratorComponent
|
||||||
// Props wajib
|
|
||||||
reportTitle='Laporan Penjualan'
|
reportTitle='Laporan Penjualan'
|
||||||
filterType={filterType}
|
filterType={filterType}
|
||||||
selectedDate={selectedDate}
|
selectedDate={selectedDate}
|
||||||
@@ -187,161 +233,99 @@ const DailyPOSReport = () => {
|
|||||||
onSingleDateChange={setSelectedDate}
|
onSingleDateChange={setSelectedDate}
|
||||||
onDateRangeChange={setDateRange}
|
onDateRangeChange={setDateRange}
|
||||||
onGeneratePDF={handleGeneratePDF}
|
onGeneratePDF={handleGeneratePDF}
|
||||||
// Props opsional
|
onGenerateExcel={handleGenerateExcel}
|
||||||
// isGenerating={isGenerating}
|
isGeneratingExcel={isGeneratingExcel}
|
||||||
// customQuickActions={customQuickActions}
|
|
||||||
// labels={customLabels}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Report Template */}
|
|
||||||
<div ref={reportRef} className='max-w-4xl mx-auto bg-white min-h-[297mm]' style={{ width: '210mm' }}>
|
<div ref={reportRef} className='max-w-4xl mx-auto bg-white min-h-[297mm]' style={{ width: '210mm' }}>
|
||||||
{/* Header */}
|
{/* Wrap header in a section for easy capture */}
|
||||||
<ReportHeader
|
<div className='report-header-section'>
|
||||||
outlet={outlet}
|
<ReportHeader
|
||||||
reportTitle={getReportTitle()}
|
outlet={outlet}
|
||||||
reportSubtitle='Laporan Bulanan'
|
reportTitle={getReportTitle()}
|
||||||
brandName='Apskel'
|
reportSubtitle='Laporan Bulanan'
|
||||||
brandColor='#36175e'
|
brandName='Apskel'
|
||||||
periode={getReportPeriodText()}
|
brandColor='#36175e'
|
||||||
/>
|
periode={getReportPeriodText()}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Performance Summary */}
|
{/* Performance Summary */}
|
||||||
<div className='p-8'>
|
<div className='p-8'>
|
||||||
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
|
<h3 className='text-3xl font-bold mb-8' style={{ color: '#36175e' }}>
|
||||||
1. Ringkasan
|
Ringkasan
|
||||||
</h3>
|
</h3>
|
||||||
|
|
||||||
<div className='grid grid-cols-2 gap-6'>
|
<div className='space-y-5'>
|
||||||
<div className='space-y-4'>
|
<div className='flex justify-between items-center py-3 border-b border-gray-200'>
|
||||||
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
<span className='text-xl text-gray-700'>Total Penjualan</span>
|
||||||
<span className='text-gray-700'>Total Penjualan (termasuk rasik)</span>
|
<span className='text-xl font-semibold text-gray-800'>
|
||||||
<span className='font-semibold text-gray-800'>
|
{formatCurrency(profitLoss?.summary.total_revenue ?? 0)}
|
||||||
{formatCurrency(profitLoss?.summary.total_revenue ?? 0)}
|
</span>
|
||||||
</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>
|
</div>
|
||||||
|
<div className='flex justify-between items-center py-3 border-b border-gray-200'>
|
||||||
<div className='space-y-4'>
|
<span className='text-xl text-gray-700'>Total Diskon</span>
|
||||||
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
<span className='text-xl font-semibold text-gray-800'>
|
||||||
<span className='text-gray-700'>Biaya lain²</span>
|
{formatCurrency(profitLoss?.summary.total_discount ?? 0)}
|
||||||
<span className='font-semibold text-gray-800'>
|
</span>
|
||||||
{formatCurrency(profitLoss?.summary.total_tax ?? 0)} |{' '}
|
</div>
|
||||||
{(((profitLoss?.summary.total_tax ?? 0) / (profitLoss?.summary.total_revenue || 1)) * 100).toFixed(0)}
|
<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>
|
<span className='text-xl font-semibold text-gray-800'>
|
||||||
</div>
|
{formatCurrency(profitLoss?.summary.total_tax ?? 0)}
|
||||||
<div className='flex justify-between items-center py-2 border-b-2 border-gray-300'>
|
</span>
|
||||||
<span className='text-lg font-bold text-blue-800'>Laba/Rugi</span>
|
</div>
|
||||||
<span className='text-lg font-bold text-blue-800'>
|
<div className='flex justify-between items-center py-3 border-b border-gray-200'>
|
||||||
{formatCurrency(profitLoss?.summary.net_profit ?? 0)} |{' '}
|
<span className='text-xl text-gray-700'>Service Charge</span>
|
||||||
{(profitLoss?.summary.net_profit_margin ?? 0).toFixed(0)}%
|
<span className='text-xl font-semibold text-gray-800'>{formatCurrency(0)}</span>
|
||||||
</span>
|
</div>
|
||||||
</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>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Profit Loss Product Table */}
|
{/* Invoice */}
|
||||||
<div className='px-8 pb-8'>
|
<div className='px-8 pb-8'>
|
||||||
<h3 className='text-lg font-medium mb-6' style={{ color: '#36175e' }}>
|
<h3 className='text-3xl font-bold mb-8' style={{ color: '#36175e' }}>
|
||||||
Laba Rugi Per Produk
|
Invoice
|
||||||
</h3>
|
</h3>
|
||||||
|
|
||||||
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
|
<div className='space-y-5'>
|
||||||
<table className='w-full'>
|
<div className='flex justify-between items-center py-3 border-b border-gray-200'>
|
||||||
<thead>
|
<span className='text-xl text-gray-700'>Total Invoice</span>
|
||||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
<span className='text-xl font-semibold text-gray-800'>{profitLoss?.summary.total_orders ?? 0}</span>
|
||||||
<th className='text-left p-3 font-semibold'>Produk</th>
|
</div>
|
||||||
<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>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Payment Method Summary */}
|
{/* Payment Method Summary */}
|
||||||
<div className='px-8 pb-8'>
|
<div className='px-8 pb-8'>
|
||||||
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
|
<h3 className='text-3xl font-bold mb-8' style={{ color: '#36175e' }}>
|
||||||
2. Ringkasan Metode Pembayaran
|
Ringkasan Metode Pembayaran
|
||||||
</h3>
|
</h3>
|
||||||
|
|
||||||
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
|
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
|
||||||
<table className='w-full'>
|
<table className='w-full'>
|
||||||
<thead>
|
<thead>
|
||||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
<tr className='text-gray-800 border-b-2 border-gray-300'>
|
||||||
<th className='text-left p-3 font-semibold'>Metode Pembayaran</th>
|
<th className='text-left text-xl p-4 font-semibold'>Metode Pembayaran</th>
|
||||||
<th className='text-center p-3 font-semibold'>Tipe</th>
|
<th className='text-center text-xl p-4 font-semibold'>Tipe</th>
|
||||||
<th className='text-center p-3 font-semibold'>Jumlah Order</th>
|
<th className='text-center text-xl p-4 font-semibold'>Jumlah Order</th>
|
||||||
<th className='text-right p-3 font-semibold'>Total Amount</th>
|
<th className='text-right text-xl p-4 font-semibold'>Total Amount</th>
|
||||||
<th className='text-center p-3 font-semibold'>Persentase</th>
|
<th className='text-center text-xl p-4 font-semibold'>Persentase</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{paymentAnalytics?.data?.map((payment, index) => (
|
{paymentAnalytics?.data?.map((payment, index) => (
|
||||||
<tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
|
<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-4 text-xl font-medium text-gray-800'>{payment.payment_method_name}</td>
|
||||||
<td className='p-3 text-center'>
|
<td className='p-4 text-center'>
|
||||||
<span
|
<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'
|
payment.payment_method_type === 'cash'
|
||||||
? 'bg-green-100 text-green-800'
|
? 'bg-green-100 text-green-800'
|
||||||
: 'bg-blue-100 text-blue-800'
|
: 'bg-blue-100 text-blue-800'
|
||||||
@@ -350,123 +334,240 @@ const DailyPOSReport = () => {
|
|||||||
{payment.payment_method_type.toUpperCase()}
|
{payment.payment_method_type.toUpperCase()}
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td className='p-3 text-center text-gray-700'>{payment.order_count}</td>
|
<td className='p-4 text-xl 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-right font-semibold text-gray-800'>
|
||||||
{formatCurrency(payment.total_amount)}
|
{formatCurrency(payment.total_amount)}
|
||||||
</td>
|
</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)}%
|
{(payment.percentage ?? 0).toFixed(1)}%
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
)) || []}
|
)) || []}
|
||||||
</tbody>
|
</tbody>
|
||||||
<tfoot>
|
<tfoot>
|
||||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
<tr className='text-gray-800 border-t-2 border-gray-300'>
|
||||||
<td className='p-3 font-bold'>TOTAL</td>
|
<td className='p-4 text-xl font-bold'>TOTAL</td>
|
||||||
<td className='p-3'></td>
|
<td className='p-4'></td>
|
||||||
<td className='p-3 text-center font-bold'>{paymentAnalytics?.summary.total_orders ?? 0}</td>
|
<td className='p-4 text-xl text-center font-bold'>{paymentAnalytics?.summary.total_orders ?? 0}</td>
|
||||||
<td className='p-3 text-right font-bold'>
|
<td className='p-4 text-xl text-right font-bold'>
|
||||||
{formatCurrency(paymentAnalytics?.summary.total_amount ?? 0)}
|
{formatCurrency(paymentAnalytics?.summary.total_amount ?? 0)}
|
||||||
</td>
|
</td>
|
||||||
<td className='p-3 text-center font-bold'></td>
|
<td className='p-4 text-center font-bold'></td>
|
||||||
</tr>
|
</tr>
|
||||||
</tfoot>
|
</tfoot>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Category Summary */}
|
{/* Category Summary — +3 kolom baru */}
|
||||||
<div className='px-8 pb-8'>
|
<div className='px-8 pb-8'>
|
||||||
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
|
<h3 className='text-3xl font-bold mb-8' style={{ color: '#36175e' }}>
|
||||||
2. Ringkasan Kategori
|
Ringkasan Kategori
|
||||||
</h3>
|
</h3>
|
||||||
|
|
||||||
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
|
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
|
||||||
<table className='w-full'>
|
<table className='w-full'>
|
||||||
<thead>
|
<thead>
|
||||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
<tr className='text-gray-800 border-b-2 border-gray-300'>
|
||||||
<th className='text-left p-3 font-semibold'>Nama</th>
|
<th className='text-left text-xl p-4 font-semibold'>Nama</th>
|
||||||
<th className='text-center p-3 font-semibold'>Total Produk</th>
|
<th className='text-center text-xl p-4 font-semibold'>Qty</th>
|
||||||
<th className='text-center p-3 font-semibold'>Qty</th>
|
<th className='text-right text-xl p-4 font-semibold'>Pendapatan</th>
|
||||||
<th className='text-right p-3 font-semibold'>Jumlah Order</th>
|
<th className='text-center text-xl p-4 font-semibold'>% Std HPP</th>
|
||||||
<th className='text-center p-3 font-semibold'>Pendapatan</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>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{category?.data?.map((c, index) => (
|
{category?.data?.map((c, index) => {
|
||||||
<tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
|
const stdHpp = DUMMY_STD_HPP
|
||||||
<td className='p-3 font-medium text-gray-800'>{c.category_name}</td>
|
const realHpp = DUMMY_REAL_HPP
|
||||||
<td className='p-3 text-center text-gray-700'>{c.product_count}</td>
|
const status = getHppStatus(stdHpp, realHpp)
|
||||||
<td className='p-3 text-center text-gray-700'>{c.total_quantity}</td>
|
return (
|
||||||
<td className='p-3 text-center text-gray-700'>{c.order_count}</td>
|
<tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
|
||||||
<td className='p-3 text-right font-semibold' style={{ color: '#36175e' }}>
|
<td className='p-4 text-xl font-medium text-gray-800'>{c.category_name}</td>
|
||||||
{formatCurrency(c.total_revenue)}
|
<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>
|
||||||
|
<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>
|
</tr>
|
||||||
)) || []}
|
</tfoot>
|
||||||
</tbody>
|
</table>
|
||||||
<tfoot>
|
</div>
|
||||||
<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>
|
|
||||||
</div>
|
</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 */}
|
{/* Footer */}
|
||||||
<div className='px-8 py-6 border-t-2 border-gray-200 mt-8'>
|
<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>© 2025 Apskel - Sistem POS Terpadu</p>
|
||||||
<p></p>
|
<p></p>
|
||||||
<p>Dicetak pada: {now.toLocaleDateString('id-ID')}</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 { useState } from 'react'
|
||||||
import Loading from '../../../../../../components/layout/shared/Loading'
|
import Loading from '../../../../../../components/layout/shared/Loading'
|
||||||
import { useDashboardAnalytics } from '../../../../../../services/queries/analytics'
|
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 OrdersReport from '../../../../../../views/dashboards/orders/OrdersReport'
|
||||||
import PaymentMethodReport from '../../../../../../views/dashboards/payment-methods/PaymentMethodReport'
|
import PaymentMethodReport from '../../../../../../views/dashboards/payment-methods/PaymentMethodReport'
|
||||||
import ProductSales from '../../../../../../views/dashboards/products/ProductSales'
|
import ProductSales from '../../../../../../views/dashboards/products/ProductSales'
|
||||||
@@ -115,14 +120,14 @@ const DashboardOverview = () => {
|
|||||||
<MetricCard
|
<MetricCard
|
||||||
iconClass='tabler-cash'
|
iconClass='tabler-cash'
|
||||||
title='Total Sales'
|
title='Total Sales'
|
||||||
value={formatShortCurrency(salesData.overview.total_sales)}
|
value={formatCurrency(salesData.overview.total_sales)}
|
||||||
bgColor='bg-green-500'
|
bgColor='bg-green-500'
|
||||||
isCurrency={true}
|
isCurrency={true}
|
||||||
/>
|
/>
|
||||||
<MetricCard
|
<MetricCard
|
||||||
iconClass='tabler-trending-up'
|
iconClass='tabler-trending-up'
|
||||||
title='Average Order Value'
|
title='Average Order Value'
|
||||||
value={formatShortCurrency(salesData.overview.average_order_value)}
|
value={formatCurrency(salesData.overview.average_order_value)}
|
||||||
bgColor='bg-purple-500'
|
bgColor='bg-purple-500'
|
||||||
isCurrency={true}
|
isCurrency={true}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -162,21 +162,21 @@ const DashboardProfitloss = () => {
|
|||||||
<MetricCard
|
<MetricCard
|
||||||
iconClass='tabler-currency-dollar'
|
iconClass='tabler-currency-dollar'
|
||||||
title='Total Revenue'
|
title='Total Revenue'
|
||||||
value={formatShortCurrency(profitData.summary.total_revenue)}
|
value={formatCurrency(profitData.summary.total_revenue)}
|
||||||
bgColor='bg-green-500'
|
bgColor='bg-green-500'
|
||||||
isCurrency={true}
|
isCurrency={true}
|
||||||
/>
|
/>
|
||||||
<MetricCard
|
<MetricCard
|
||||||
iconClass='tabler-receipt'
|
iconClass='tabler-receipt'
|
||||||
title='Total Cost'
|
title='Total Cost'
|
||||||
value={formatShortCurrency(profitData.summary.total_cost)}
|
value={formatCurrency(profitData.summary.total_cost)}
|
||||||
bgColor='bg-red-500'
|
bgColor='bg-red-500'
|
||||||
isCurrency={true}
|
isCurrency={true}
|
||||||
/>
|
/>
|
||||||
<MetricCard
|
<MetricCard
|
||||||
iconClass='tabler-trending-up'
|
iconClass='tabler-trending-up'
|
||||||
title='Gross Profit'
|
title='Gross Profit'
|
||||||
value={formatShortCurrency(profitData.summary.gross_profit)}
|
value={formatCurrency(profitData.summary.gross_profit)}
|
||||||
subtitle={`Margin: ${formatPercentage(profitData.summary.gross_profit_margin)}`}
|
subtitle={`Margin: ${formatPercentage(profitData.summary.gross_profit_margin)}`}
|
||||||
bgColor='bg-blue-500'
|
bgColor='bg-blue-500'
|
||||||
isNegative={profitData.summary.gross_profit < 0}
|
isNegative={profitData.summary.gross_profit < 0}
|
||||||
@@ -186,7 +186,7 @@ const DashboardProfitloss = () => {
|
|||||||
iconClass='tabler-percentage'
|
iconClass='tabler-percentage'
|
||||||
title='Profitability Ratio'
|
title='Profitability Ratio'
|
||||||
value={formatPercentage(profitData.summary.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'
|
bgColor='bg-purple-500'
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -199,7 +199,7 @@ const DashboardProfitloss = () => {
|
|||||||
<h3 className='text-lg font-semibold text-gray-900'>Net Profit</h3>
|
<h3 className='text-lg font-semibold text-gray-900'>Net Profit</h3>
|
||||||
</div>
|
</div>
|
||||||
<p className='text-3xl font-bold text-green-600 mb-2'>
|
<p className='text-3xl font-bold text-green-600 mb-2'>
|
||||||
Rp {formatShortCurrency(profitData.summary.net_profit)}
|
{formatCurrency(profitData.summary.net_profit)}
|
||||||
</p>
|
</p>
|
||||||
<p className='text-sm text-gray-600'>
|
<p className='text-sm text-gray-600'>
|
||||||
Margin: {formatPercentage(profitData.summary.net_profit_margin)}
|
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
|
||||||
|
// }
|
||||||
@@ -7,6 +7,14 @@ import Menu from '@mui/material/Menu'
|
|||||||
import MenuItem from '@mui/material/MenuItem'
|
import MenuItem from '@mui/material/MenuItem'
|
||||||
import { styled } from '@mui/material/styles'
|
import { styled } from '@mui/material/styles'
|
||||||
|
|
||||||
|
function toTitleCase(str: string): string {
|
||||||
|
return str
|
||||||
|
.toLowerCase()
|
||||||
|
.split(/\s+/) // split by spaces
|
||||||
|
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
|
||||||
|
.join(' ')
|
||||||
|
}
|
||||||
|
|
||||||
const DropdownButton = styled(Button)(({ theme }) => ({
|
const DropdownButton = styled(Button)(({ theme }) => ({
|
||||||
textTransform: 'none',
|
textTransform: 'none',
|
||||||
fontWeight: 400,
|
fontWeight: 400,
|
||||||
@@ -102,7 +110,7 @@ const StatusFilterTabs: React.FC<StatusFilterTabsProps> = ({
|
|||||||
})
|
})
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{status}
|
{toTitleCase(status)}
|
||||||
</Button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -135,7 +143,7 @@ const StatusFilterTabs: React.FC<StatusFilterTabsProps> = ({
|
|||||||
})
|
})
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{status}
|
{toTitleCase(status)}
|
||||||
</Button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
|
|
||||||
@@ -158,7 +166,7 @@ const StatusFilterTabs: React.FC<StatusFilterTabsProps> = ({
|
|||||||
})
|
})
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{isDropdownItemSelected ? selectedStatus : dropdownLabel}
|
{isDropdownItemSelected ? toTitleCase(selectedStatus) : dropdownLabel}
|
||||||
</DropdownButton>
|
</DropdownButton>
|
||||||
|
|
||||||
<Menu
|
<Menu
|
||||||
@@ -187,7 +195,7 @@ const StatusFilterTabs: React.FC<StatusFilterTabsProps> = ({
|
|||||||
color: selectedStatus === status ? 'primary.main' : 'text.primary'
|
color: selectedStatus === status ? 'primary.main' : 'text.primary'
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{status}
|
{toTitleCase(status)}
|
||||||
</MenuItem>
|
</MenuItem>
|
||||||
))}
|
))}
|
||||||
</Menu>
|
</Menu>
|
||||||
|
|||||||
@@ -91,27 +91,27 @@ const VerticalMenu = ({ dictionary, scrollMenu }: Props) => {
|
|||||||
<MenuItem href={`/${locale}/dashboards/daily-report`}>{dictionary['navigation'].dailyReport}</MenuItem>
|
<MenuItem href={`/${locale}/dashboards/daily-report`}>{dictionary['navigation'].dailyReport}</MenuItem>
|
||||||
</SubMenu>
|
</SubMenu>
|
||||||
<MenuSection label={dictionary['navigation'].appsPages}>
|
<MenuSection label={dictionary['navigation'].appsPages}>
|
||||||
<SubMenu label={dictionary['navigation'].sales} icon={<i className='tabler-receipt-2' />}>
|
{/* <SubMenu label={dictionary['navigation'].sales} icon={<i className='tabler-receipt-2' />}>
|
||||||
<MenuItem href={`/${locale}/apps/sales/overview`}>{dictionary['navigation'].overview}</MenuItem>
|
<MenuItem href={`/${locale}/apps/sales/overview`}>{dictionary['navigation'].overview}</MenuItem>
|
||||||
<MenuItem href={`/${locale}/apps/sales/sales-bills`}>{dictionary['navigation'].invoices}</MenuItem>
|
<MenuItem href={`/${locale}/apps/sales/sales-bills`}>{dictionary['navigation'].invoices}</MenuItem>
|
||||||
<MenuItem href={`/${locale}/apps/sales/sales-deliveries`}>{dictionary['navigation'].deliveries}</MenuItem>
|
<MenuItem href={`/${locale}/apps/sales/sales-deliveries`}>{dictionary['navigation'].deliveries}</MenuItem>
|
||||||
<MenuItem href={`/${locale}/apps/sales/sales-orders`}>{dictionary['navigation'].sales_orders}</MenuItem>
|
<MenuItem href={`/${locale}/apps/sales/sales-orders`}>{dictionary['navigation'].sales_orders}</MenuItem>
|
||||||
<MenuItem href={`/${locale}/apps/sales/sales-quotes`}>{dictionary['navigation'].quotes}</MenuItem>
|
<MenuItem href={`/${locale}/apps/sales/sales-quotes`}>{dictionary['navigation'].quotes}</MenuItem>
|
||||||
</SubMenu>
|
</SubMenu> */}
|
||||||
<SubMenu label={dictionary['navigation'].purchase_text} icon={<i className='tabler-shopping-cart' />}>
|
<SubMenu label={dictionary['navigation'].purchase_text} icon={<i className='tabler-shopping-cart' />}>
|
||||||
<MenuItem href={`/${locale}/apps/purchase/overview`}>{dictionary['navigation'].overview}</MenuItem>
|
<MenuItem href={`/${locale}/apps/purchase/overview`}>{dictionary['navigation'].overview}</MenuItem>
|
||||||
<MenuItem href={`/${locale}/apps/purchase/purchase-bills`}>
|
{/* <MenuItem href={`/${locale}/apps/purchase/purchase-bills`}>
|
||||||
{dictionary['navigation'].purchase_bills}
|
{dictionary['navigation'].purchase_bills}
|
||||||
</MenuItem>
|
</MenuItem>
|
||||||
<MenuItem href={`/${locale}/apps/purchase/purchase-deliveries`}>
|
<MenuItem href={`/${locale}/apps/purchase/purchase-deliveries`}>
|
||||||
{dictionary['navigation'].purchase_delivery}
|
{dictionary['navigation'].purchase_delivery}
|
||||||
</MenuItem>
|
</MenuItem> */}
|
||||||
<MenuItem href={`/${locale}/apps/purchase/purchase-orders`}>
|
<MenuItem href={`/${locale}/apps/purchase/purchase-orders`}>
|
||||||
{dictionary['navigation'].purchase_orders}
|
{dictionary['navigation'].purchase_orders}
|
||||||
</MenuItem>
|
</MenuItem>
|
||||||
<MenuItem href={`/${locale}/apps/purchase/purchase-quotes`}>
|
{/* <MenuItem href={`/${locale}/apps/purchase/purchase-quotes`}>
|
||||||
{dictionary['navigation'].purchase_quotes}
|
{dictionary['navigation'].purchase_quotes}
|
||||||
</MenuItem>
|
</MenuItem> */}
|
||||||
</SubMenu>
|
</SubMenu>
|
||||||
<MenuItem
|
<MenuItem
|
||||||
href={`/${locale}/apps/expense`}
|
href={`/${locale}/apps/expense`}
|
||||||
@@ -153,6 +153,28 @@ const VerticalMenu = ({ dictionary, scrollMenu }: Props) => {
|
|||||||
>
|
>
|
||||||
{dictionary['navigation'].reports}
|
{dictionary['navigation'].reports}
|
||||||
</MenuItem>
|
</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'].inventory} icon={<i className='tabler-salad' />}>
|
||||||
<SubMenu label={dictionary['navigation'].products}>
|
<SubMenu label={dictionary['navigation'].products}>
|
||||||
<MenuItem href={`/${locale}/apps/inventory/products/list`}>{dictionary['navigation'].list}</MenuItem>
|
<MenuItem href={`/${locale}/apps/inventory/products/list`}>{dictionary['navigation'].list}</MenuItem>
|
||||||
@@ -212,6 +234,9 @@ const VerticalMenu = ({ dictionary, scrollMenu }: Props) => {
|
|||||||
>
|
>
|
||||||
{dictionary['navigation'].vendor}
|
{dictionary['navigation'].vendor}
|
||||||
</MenuItem>
|
</MenuItem>
|
||||||
|
<MenuItem href={`/${locale}/draw`} icon={<i className='tabler-building' />} target='_blank'>
|
||||||
|
Random Draw
|
||||||
|
</MenuItem>
|
||||||
</MenuSection>
|
</MenuSection>
|
||||||
</Menu>
|
</Menu>
|
||||||
</ScrollWrapper>
|
</ScrollWrapper>
|
||||||
|
|||||||
@@ -126,6 +126,18 @@
|
|||||||
"expenses": "Expenses",
|
"expenses": "Expenses",
|
||||||
"cash_and_bank": "Cash & Bank",
|
"cash_and_bank": "Cash & Bank",
|
||||||
"account": "Account",
|
"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",
|
"expenses": "Biaya",
|
||||||
"cash_and_bank": "Kas & Bank",
|
"cash_and_bank": "Kas & Bank",
|
||||||
"account": "Akun",
|
"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 organizationReducer from '@/redux-store/slices/organization'
|
||||||
import userReducer from '@/redux-store/slices/user'
|
import userReducer from '@/redux-store/slices/user'
|
||||||
import vendorReducer from '@/redux-store/slices/vendor'
|
import vendorReducer from '@/redux-store/slices/vendor'
|
||||||
|
import discountReducer from '@/redux-store/slices/discount'
|
||||||
|
|
||||||
export const store = configureStore({
|
export const store = configureStore({
|
||||||
reducer: {
|
reducer: {
|
||||||
@@ -21,7 +22,8 @@ export const store = configureStore({
|
|||||||
productRecipeReducer,
|
productRecipeReducer,
|
||||||
organizationReducer,
|
organizationReducer,
|
||||||
userReducer,
|
userReducer,
|
||||||
vendorReducer
|
vendorReducer,
|
||||||
|
discountReducer
|
||||||
},
|
},
|
||||||
middleware: getDefaultMiddleware => getDefaultMiddleware({ serializableCheck: false })
|
middleware: getDefaultMiddleware => getDefaultMiddleware({ serializableCheck: false })
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -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({
|
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: {
|
headers: {
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
},
|
},
|
||||||
@@ -30,9 +31,8 @@ api.interceptors.response.use(
|
|||||||
response => response,
|
response => response,
|
||||||
error => {
|
error => {
|
||||||
const status = error.response?.status
|
const status = error.response?.status
|
||||||
const currentPath = window.location.pathname
|
|
||||||
|
|
||||||
if (status === 401 && !currentPath.endsWith('/login')) {
|
if (status === 401) {
|
||||||
localStorage.removeItem('user')
|
localStorage.removeItem('user')
|
||||||
localStorage.removeItem('authToken')
|
localStorage.removeItem('authToken')
|
||||||
window.location.href = '/login'
|
window.location.href = '/login'
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { toast } from 'react-toastify'
|
||||||
|
import { api } from '../api'
|
||||||
|
import { AccountRequest } from '../queries/chartOfAccountType'
|
||||||
|
|
||||||
|
export const useAccountsMutation = () => {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
const createAccount = useMutation({
|
||||||
|
mutationFn: async (newAccount: AccountRequest) => {
|
||||||
|
const response = await api.post('/accounts', newAccount)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('Account created successfully!')
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['accounts'] })
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const updateAccount = useMutation({
|
||||||
|
mutationFn: async ({ id, payload }: { id: string; payload: AccountRequest }) => {
|
||||||
|
const response = await api.put(`/accounts/${id}`, payload)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('Account updated successfully!')
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['accounts'] })
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
toast.error(error.response?.data?.errors?.[0]?.cause || 'Update failed')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const deleteAccount = useMutation({
|
||||||
|
mutationFn: async (id: string) => {
|
||||||
|
const response = await api.delete(`/accounts/${id}`)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('Account deleted successfully!')
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['accounts'] })
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
toast.error(error.response?.data?.errors?.[0]?.cause || 'Delete failed')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return { createAccount, updateAccount, deleteAccount }
|
||||||
|
}
|
||||||
@@ -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 }
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { toast } from 'react-toastify'
|
||||||
|
import { api } from '../api'
|
||||||
|
import { PurchaseOrderRequest, SendPaymentPurchaseOrderRequest } from '@/types/services/purchaseOrder'
|
||||||
|
|
||||||
|
export const usePurchaseOrdersMutation = () => {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
const createPurchaseOrder = useMutation({
|
||||||
|
mutationFn: async (newPurchaseOrder: PurchaseOrderRequest) => {
|
||||||
|
const response = await api.post('/purchase-orders', newPurchaseOrder)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('Purchase Order created successfully!')
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['purchase-orders', 'ingredients'] })
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
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,36 @@
|
|||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { api } from '../api'
|
||||||
|
import { Accounts } from '@/types/services/chartOfAccount'
|
||||||
|
|
||||||
|
interface AccountQueryParams {
|
||||||
|
page?: number
|
||||||
|
limit?: number
|
||||||
|
search?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAccounts(params: AccountQueryParams = {}) {
|
||||||
|
const { page = 1, limit = 10, search = '', ...filters } = params
|
||||||
|
|
||||||
|
return useQuery<Accounts>({
|
||||||
|
queryKey: ['accounts', { 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(`/accounts?${queryParams.toString()}`)
|
||||||
|
return res.data.data
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -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 = {}) {
|
export function useCategories(params: CategoriesQueryParams = {}) {
|
||||||
const { page = 1, limit = 10, search = '', ...filters } = params
|
const { page = 1, limit = 50, search = '', ...filters } = params
|
||||||
|
|
||||||
return useQuery<Categories>({
|
return useQuery<Categories>({
|
||||||
queryKey: ['categories', { page, limit, search, ...filters }],
|
queryKey: ['categories', { page, limit, search, ...filters }],
|
||||||
@@ -30,7 +30,9 @@ export function useCategories(params: CategoriesQueryParams = {}) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
const res = await api.get(`/categories?${queryParams.toString()}`)
|
const res = await api.get(`/categories?${queryParams.toString()}`)
|
||||||
return res.data.data
|
const data = res.data.data
|
||||||
|
|
||||||
|
return data
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { api } from '../api'
|
||||||
|
import { ChartOfAccounts } from '@/types/services/chartOfAccount'
|
||||||
|
|
||||||
|
interface ChartOfAccountQueryParams {
|
||||||
|
page?: number
|
||||||
|
limit?: number
|
||||||
|
search?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useChartOfAccount(params: ChartOfAccountQueryParams = {}) {
|
||||||
|
const { page = 1, limit = 10, search = '', ...filters } = params
|
||||||
|
|
||||||
|
return useQuery<ChartOfAccounts>({
|
||||||
|
queryKey: ['chart-of-accounts', { 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(`/chart-of-accounts?${queryParams.toString()}`)
|
||||||
|
return res.data.data
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { ChartOfAccountTypes } from '@/types/services/chartOfAccount'
|
||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { api } from '../api'
|
||||||
|
|
||||||
|
interface ChartOfAccountQueryParams {
|
||||||
|
page?: number
|
||||||
|
limit?: number
|
||||||
|
search?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useChartOfAccountTypes(params: ChartOfAccountQueryParams = {}) {
|
||||||
|
const { page = 1, limit = 10, search = '', ...filters } = params
|
||||||
|
|
||||||
|
return useQuery<ChartOfAccountTypes>({
|
||||||
|
queryKey: ['chart-of-account-types', { 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(`/chart-of-account-types?${queryParams.toString()}`)
|
||||||
|
return res.data.data
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AccountRequest {
|
||||||
|
chart_of_account_id: string
|
||||||
|
name: string
|
||||||
|
number: string
|
||||||
|
account_type: string
|
||||||
|
opening_balance: number
|
||||||
|
description: string
|
||||||
|
}
|
||||||
@@ -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
|
page?: number
|
||||||
limit?: number
|
limit?: number
|
||||||
search?: string
|
search?: string
|
||||||
|
date_from?: string
|
||||||
|
date_to?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useOrders(params: OrdersQueryParams = {}) {
|
export function useOrders(params: OrdersQueryParams = {}) {
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { PurchaseOrder, PurchaseOrders } from '@/types/services/purchaseOrder'
|
||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { api } from '../api'
|
||||||
|
|
||||||
|
interface PurchaseOrderQueryParams {
|
||||||
|
page?: number
|
||||||
|
limit?: number
|
||||||
|
search?: string
|
||||||
|
status?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function usePurchaseOrders(params: PurchaseOrderQueryParams = {}) {
|
||||||
|
const { page = 1, limit = 10, search = '', status = '', ...filters } = params
|
||||||
|
|
||||||
|
return useQuery<PurchaseOrders>({
|
||||||
|
queryKey: ['purchase-orders', { page, limit, search, status, ...filters }],
|
||||||
|
queryFn: async () => {
|
||||||
|
const queryParams = new URLSearchParams()
|
||||||
|
|
||||||
|
queryParams.append('page', page.toString())
|
||||||
|
queryParams.append('limit', limit.toString())
|
||||||
|
|
||||||
|
if (search) {
|
||||||
|
queryParams.append('search', search)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (status) {
|
||||||
|
queryParams.append('status', status)
|
||||||
|
}
|
||||||
|
|
||||||
|
Object.entries(filters).forEach(([key, value]) => {
|
||||||
|
if (value !== undefined && value !== null && value !== '') {
|
||||||
|
queryParams.append(key, value.toString())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const res = await api.get(`/purchase-orders?${queryParams.toString()}`)
|
||||||
|
return res.data.data
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function usePurchaseOrderById(id: string) {
|
||||||
|
return useQuery<PurchaseOrder>({
|
||||||
|
queryKey: ['purchase-orders', id],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await api.get(`/purchase-orders/${id}`)
|
||||||
|
return res.data.data
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -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,13 @@
|
|||||||
|
import { UnitConversion } from '@/types/services/productRecipe'
|
||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { api } from '../api'
|
||||||
|
|
||||||
|
export function useUnitConverterByIngredient(IngredientId: string) {
|
||||||
|
return useQuery<UnitConversion[]>({
|
||||||
|
queryKey: ['unit-converters/ingredient', IngredientId],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await api.get(`/unit-converters/ingredient/${IngredientId}`)
|
||||||
|
return res.data.data
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -35,6 +35,16 @@ export function useVendors(params: VendorQueryParams = {}) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function useVendorActive() {
|
||||||
|
return useQuery<Vendor[]>({
|
||||||
|
queryKey: ['vendors/active'],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await api.get(`/vendors/active`)
|
||||||
|
return res.data.data
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
export function useVendorById(id: string) {
|
export function useVendorById(id: string) {
|
||||||
return useQuery<Vendor>({
|
return useQuery<Vendor>({
|
||||||
queryKey: ['vendors', id],
|
queryKey: ['vendors', id],
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -10,49 +10,6 @@ export type PurchaseOrderType = {
|
|||||||
total: number
|
total: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface IngredientItem {
|
|
||||||
id: number
|
|
||||||
ingredient: { label: string; value: string } | null
|
|
||||||
deskripsi: string
|
|
||||||
kuantitas: number
|
|
||||||
satuan: { label: string; value: string } | null
|
|
||||||
discount: string
|
|
||||||
harga: number
|
|
||||||
pajak: { label: string; value: string } | null
|
|
||||||
waste: { label: string; value: string } | null
|
|
||||||
total: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface PurchaseOrderFormData {
|
|
||||||
vendor: { label: string; value: string } | null
|
|
||||||
nomor: string
|
|
||||||
tglTransaksi: string
|
|
||||||
tglJatuhTempo: string
|
|
||||||
referensi: string
|
|
||||||
termin: { label: string; value: string } | null
|
|
||||||
hargaTermasukPajak: boolean
|
|
||||||
showShippingInfo: boolean
|
|
||||||
tanggalPengiriman: string
|
|
||||||
ekspedisi: { label: string; value: string } | null
|
|
||||||
noResi: string
|
|
||||||
showPesan: boolean
|
|
||||||
showAttachment: boolean
|
|
||||||
showTambahDiskon: boolean
|
|
||||||
showBiayaPengiriman: boolean
|
|
||||||
showBiayaTransaksi: boolean
|
|
||||||
showUangMuka: boolean
|
|
||||||
pesan: string
|
|
||||||
ingredientItems: IngredientItem[]
|
|
||||||
transactionCosts?: TransactionCost[]
|
|
||||||
subtotal?: number
|
|
||||||
discountType?: 'percentage' | 'fixed'
|
|
||||||
downPaymentType?: 'percentage' | 'fixed'
|
|
||||||
discountValue?: string
|
|
||||||
shippingCost?: string
|
|
||||||
transactionCost?: string
|
|
||||||
downPayment?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface TransactionCost {
|
export interface TransactionCost {
|
||||||
id: string
|
id: string
|
||||||
type: string
|
type: string
|
||||||
|
|||||||
@@ -31,8 +31,10 @@ export interface SalesReport {
|
|||||||
export interface ProductData {
|
export interface ProductData {
|
||||||
product_id: string
|
product_id: string
|
||||||
product_name: string
|
product_name: string
|
||||||
|
product_sku: string
|
||||||
category_id: string
|
category_id: string
|
||||||
category_name: string
|
category_name: string
|
||||||
|
category_order: number
|
||||||
quantity_sold: number
|
quantity_sold: number
|
||||||
revenue: number
|
revenue: number
|
||||||
average_price: 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 {
|
export interface Category {
|
||||||
id: string;
|
id: string
|
||||||
organization_id: string;
|
organization_id: string
|
||||||
name: string;
|
name: string
|
||||||
description: string | null;
|
description: string | null
|
||||||
business_type: string;
|
business_type: string
|
||||||
metadata: Record<string, any>;
|
order: number
|
||||||
created_at: string;
|
metadata: Record<string, any>
|
||||||
updated_at: string;
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Categories {
|
export interface Categories {
|
||||||
categories: Category[];
|
categories: Category[]
|
||||||
total_count: number;
|
total_count: number
|
||||||
page: number;
|
page: number
|
||||||
limit: number;
|
limit: number
|
||||||
total_pages: number;
|
total_pages: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export interface CategoryRequest {
|
export interface CategoryRequest {
|
||||||
name: string;
|
name: string
|
||||||
description: string | null;
|
description: string | null
|
||||||
business_type: string;
|
business_type: string
|
||||||
|
order: number
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
export interface ChartOfAccountType {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
code: string
|
||||||
|
description: string
|
||||||
|
is_active: boolean
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChartOfAccountTypes {
|
||||||
|
data: ChartOfAccountType[]
|
||||||
|
limit: number
|
||||||
|
page: number
|
||||||
|
total: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChartOfAccount {
|
||||||
|
id: string
|
||||||
|
organization_id: string
|
||||||
|
outlet_id: string
|
||||||
|
chart_of_account_type_id: string
|
||||||
|
parent_id: string
|
||||||
|
name: string
|
||||||
|
code: string
|
||||||
|
description: string
|
||||||
|
is_active: boolean
|
||||||
|
is_system: boolean
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
chart_of_account_type: ChartOfAccountType
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChartOfAccounts {
|
||||||
|
data: ChartOfAccount[]
|
||||||
|
limit: number
|
||||||
|
page: number
|
||||||
|
total: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Account {
|
||||||
|
id: string
|
||||||
|
organization_id: string
|
||||||
|
outlet_id: string
|
||||||
|
chart_of_account_id: string
|
||||||
|
name: string
|
||||||
|
number: string
|
||||||
|
account_type: string
|
||||||
|
opening_balance: number
|
||||||
|
current_balance: number
|
||||||
|
description: string
|
||||||
|
is_active: true
|
||||||
|
is_system: false
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
chart_of_account: ChartOfAccount
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Accounts {
|
||||||
|
data: Account[]
|
||||||
|
limit: number
|
||||||
|
page: number
|
||||||
|
total: number
|
||||||
|
}
|
||||||
@@ -1,29 +1,40 @@
|
|||||||
export interface Customer {
|
export interface Customer {
|
||||||
id: string;
|
id: string
|
||||||
organization_id: string;
|
organization_id: string
|
||||||
name: string;
|
name: string
|
||||||
email?: string;
|
email?: string
|
||||||
phone?: string;
|
phone?: string
|
||||||
address?: string;
|
address?: string
|
||||||
is_default: boolean;
|
is_default: boolean
|
||||||
is_active: boolean;
|
is_active: boolean
|
||||||
metadata: Record<string, any>;
|
metadata: Record<string, any>
|
||||||
created_at: string;
|
created_at: string
|
||||||
updated_at: string;
|
updated_at: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Customers {
|
export interface Customers {
|
||||||
data: Customer[];
|
data: Customer[]
|
||||||
total_count: number;
|
total_count: number
|
||||||
page: number;
|
page: number
|
||||||
limit: number;
|
limit: number
|
||||||
total_pages: number;
|
total_pages: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CustomerRequest {
|
export interface CustomerRequest {
|
||||||
name: string;
|
name: string
|
||||||
email?: string;
|
email?: string
|
||||||
phone?: string;
|
phone?: string
|
||||||
address?: string;
|
address?: string
|
||||||
is_active?: boolean;
|
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
|
||||||
|
}
|
||||||
@@ -42,6 +42,7 @@ export interface ProductRecipe {
|
|||||||
variant_id: string | null
|
variant_id: string | null
|
||||||
ingredient_id: string
|
ingredient_id: string
|
||||||
quantity: number
|
quantity: number
|
||||||
|
waste: number
|
||||||
created_at: string
|
created_at: string
|
||||||
updated_at: string
|
updated_at: string
|
||||||
product: Product
|
product: Product
|
||||||
@@ -54,6 +55,7 @@ export interface ProductRecipeRequest {
|
|||||||
ingredient_id: string
|
ingredient_id: string
|
||||||
quantity: number
|
quantity: number
|
||||||
outlet_id: string | null
|
outlet_id: string | null
|
||||||
|
waste: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface IngredientUnit {
|
export interface IngredientUnit {
|
||||||
@@ -73,3 +75,29 @@ export interface IngredientUnitConverterRequest {
|
|||||||
to_unit_id: string
|
to_unit_id: string
|
||||||
conversion_factor: number
|
conversion_factor: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface UnitConversion {
|
||||||
|
id: string
|
||||||
|
organization_id: string
|
||||||
|
ingredient_id: string
|
||||||
|
from_unit_id: string
|
||||||
|
to_unit_id: string
|
||||||
|
conversion_factor: number
|
||||||
|
is_active: boolean
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
created_by: string
|
||||||
|
updated_by: string
|
||||||
|
from_unit: UnitConversionFrom
|
||||||
|
to_unit: UnitConversionTo
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UnitConversionFrom {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UnitConversionTo {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import { IngredientItem } from './ingredient'
|
||||||
|
import { Vendor } from './vendor'
|
||||||
|
|
||||||
|
export interface PurchaseOrderRequest {
|
||||||
|
vendor_id: string // uuid.UUID
|
||||||
|
po_number: string
|
||||||
|
transaction_date: string // ISO date string
|
||||||
|
due_date: string // ISO date string
|
||||||
|
reference?: string
|
||||||
|
status?: 'draft' | 'sent' | 'approved' | 'received' | 'cancelled'
|
||||||
|
message?: string
|
||||||
|
items: PurchaseOrderItemRequest[]
|
||||||
|
attachment_file_ids?: string[] // uuid.UUID[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PurchaseOrderItemRequest {
|
||||||
|
ingredient_id: string // uuid.UUID
|
||||||
|
description?: string
|
||||||
|
quantity: number
|
||||||
|
unit_id: string // uuid.UUID
|
||||||
|
amount: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PurchaseOrders {
|
||||||
|
purchase_orders: PurchaseOrder[]
|
||||||
|
total_count: number
|
||||||
|
page: number
|
||||||
|
limit: number
|
||||||
|
total_pages: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PurchaseOrder {
|
||||||
|
id: string
|
||||||
|
organization_id: string
|
||||||
|
vendor_id: string
|
||||||
|
po_number: string
|
||||||
|
transaction_date: string // RFC3339
|
||||||
|
due_date: string // RFC3339
|
||||||
|
reference: string | null
|
||||||
|
status: string
|
||||||
|
message: string | null
|
||||||
|
total_amount: number
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
vendor: Vendor
|
||||||
|
items: PurchaseOrderItem[]
|
||||||
|
attachments: PurchaseOrderAttachment[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PurchaseOrderItem {
|
||||||
|
id: string
|
||||||
|
purchase_order_id: string
|
||||||
|
ingredient_id: string
|
||||||
|
description: string
|
||||||
|
quantity: number
|
||||||
|
unit_id: string
|
||||||
|
amount: number
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
ingredient: PurchaseOrderIngredient
|
||||||
|
unit: PurchaseOrderUnit
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PurchaseOrderIngredient {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PurchaseOrderUnit {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PurchaseOrderAttachment {
|
||||||
|
id: string
|
||||||
|
purchase_order_id: string
|
||||||
|
file_id: string
|
||||||
|
created_at: string
|
||||||
|
file: PurchaseOrderFile
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PurchaseOrderFile {
|
||||||
|
id: string
|
||||||
|
organization_id: string
|
||||||
|
user_id: string
|
||||||
|
file_name: string
|
||||||
|
original_name: string
|
||||||
|
file_url: string
|
||||||
|
file_size: number
|
||||||
|
mime_type: string
|
||||||
|
file_type: string
|
||||||
|
upload_path: string
|
||||||
|
is_public: boolean
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PurchaseOrderFormData {
|
||||||
|
vendor: { label: string; value: string } | null
|
||||||
|
po_number: string
|
||||||
|
transaction_date: string
|
||||||
|
due_date: string
|
||||||
|
reference: string
|
||||||
|
status: 'draft' | 'sent' | 'approved' | 'received' | 'cancelled'
|
||||||
|
showPesan: boolean
|
||||||
|
showAttachment: boolean
|
||||||
|
message: string
|
||||||
|
items: PurchaseOrderFormItem[]
|
||||||
|
attachment_file_ids: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PurchaseOrderFormItem {
|
||||||
|
id: number // for UI tracking
|
||||||
|
ingredient: { label: string; value: string; originalData?: IngredientItem } | null
|
||||||
|
description: string
|
||||||
|
quantity: number
|
||||||
|
unit: { label: string; value: string } | null
|
||||||
|
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}`
|
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) => {
|
export const formatForInputDate = (dateString: Date | string) => {
|
||||||
const date = new Date(dateString)
|
const date = new Date(dateString)
|
||||||
const day = String(date.getDate()).padStart(2, '0')
|
const day = String(date.getDate()).padStart(2, '0')
|
||||||
@@ -51,7 +60,6 @@ export const formatForInputDate = (dateString: Date | string) => {
|
|||||||
return `${year}-${month}-${day}`
|
return `${year}-${month}-${day}`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export const formatDatetime = (dateString: string | number | Date) => {
|
export const formatDatetime = (dateString: string | number | Date) => {
|
||||||
const date = new Date(dateString)
|
const date = new Date(dateString)
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import { useState, useEffect } from 'react'
|
|||||||
import Button from '@mui/material/Button'
|
import Button from '@mui/material/Button'
|
||||||
import Drawer from '@mui/material/Drawer'
|
import Drawer from '@mui/material/Drawer'
|
||||||
import IconButton from '@mui/material/IconButton'
|
import IconButton from '@mui/material/IconButton'
|
||||||
import MenuItem from '@mui/material/MenuItem'
|
|
||||||
import Typography from '@mui/material/Typography'
|
import Typography from '@mui/material/Typography'
|
||||||
import Box from '@mui/material/Box'
|
import Box from '@mui/material/Box'
|
||||||
|
|
||||||
@@ -15,64 +14,52 @@ import { useForm, Controller } from 'react-hook-form'
|
|||||||
// Component Imports
|
// Component Imports
|
||||||
import CustomTextField from '@core/components/mui/TextField'
|
import CustomTextField from '@core/components/mui/TextField'
|
||||||
import CustomAutocomplete from '@/@core/components/mui/Autocomplete'
|
import CustomAutocomplete from '@/@core/components/mui/Autocomplete'
|
||||||
|
import { AccountRequest } from '@/services/queries/chartOfAccountType'
|
||||||
// Account Type
|
import { useChartOfAccount } from '@/services/queries/chartOfAccount'
|
||||||
export type AccountType = {
|
import { Account, ChartOfAccount } from '@/types/services/chartOfAccount'
|
||||||
id: number
|
import { useAccountsMutation } from '@/services/mutations/account'
|
||||||
code: string
|
|
||||||
name: string
|
|
||||||
category: string
|
|
||||||
balance: string
|
|
||||||
}
|
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
open: boolean
|
open: boolean
|
||||||
handleClose: () => void
|
handleClose: () => void
|
||||||
accountData?: AccountType[]
|
accountData?: Account[]
|
||||||
setData: (data: AccountType[]) => void
|
setData: (data: Account[]) => void
|
||||||
editingAccount?: AccountType | null
|
editingAccount?: Account | null
|
||||||
}
|
}
|
||||||
|
|
||||||
type FormValidateType = {
|
type FormValidateType = {
|
||||||
name: string
|
name: string
|
||||||
code: string
|
code: string
|
||||||
category: string
|
account_type: string
|
||||||
parentAccount?: string
|
opening_balance: number
|
||||||
|
description: string
|
||||||
|
chart_of_account_id: string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Categories available for accounts
|
|
||||||
const accountCategories = [
|
|
||||||
'Kas & Bank',
|
|
||||||
'Piutang',
|
|
||||||
'Persediaan',
|
|
||||||
'Aset Tetap',
|
|
||||||
'Hutang',
|
|
||||||
'Ekuitas',
|
|
||||||
'Pendapatan',
|
|
||||||
'Beban'
|
|
||||||
]
|
|
||||||
|
|
||||||
// Parent accounts (dummy data for dropdown)
|
|
||||||
const parentAccounts = [
|
|
||||||
{ id: 1, code: '1-10001', name: 'Kas' },
|
|
||||||
{ id: 2, code: '1-10002', name: 'Bank BCA' },
|
|
||||||
{ id: 3, code: '1-10003', name: 'Bank Mandiri' },
|
|
||||||
{ id: 4, code: '1-10101', name: 'Piutang Usaha' },
|
|
||||||
{ id: 5, code: '1-10201', name: 'Persediaan Barang' },
|
|
||||||
{ id: 6, code: '2-20001', name: 'Hutang Usaha' },
|
|
||||||
{ id: 7, code: '3-30001', name: 'Modal Pemilik' },
|
|
||||||
{ id: 8, code: '4-40001', name: 'Penjualan' },
|
|
||||||
{ id: 9, code: '5-50001', name: 'Beban Gaji' }
|
|
||||||
]
|
|
||||||
|
|
||||||
// Vars
|
// Vars
|
||||||
const initialData = {
|
const initialData = {
|
||||||
name: '',
|
name: '',
|
||||||
code: '',
|
code: '',
|
||||||
category: '',
|
account_type: '',
|
||||||
parentAccount: ''
|
opening_balance: 0,
|
||||||
|
description: '',
|
||||||
|
chart_of_account_id: ''
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Static Account Types
|
||||||
|
const staticAccountTypes = [
|
||||||
|
{ id: '1', name: 'Cash', code: 'cash', description: 'Cash account' },
|
||||||
|
{ id: '2', name: 'Wallet', code: 'wallet', description: 'Digital wallet account' },
|
||||||
|
{ id: '3', name: 'Bank', code: 'bank', description: 'Bank account' },
|
||||||
|
{ id: '4', name: 'Credit', code: 'credit', description: 'Credit account' },
|
||||||
|
{ id: '5', name: 'Debit', code: 'debit', description: 'Debit account' },
|
||||||
|
{ id: '6', name: 'Asset', code: 'asset', description: 'Asset account' },
|
||||||
|
{ id: '7', name: 'Liability', code: 'liability', description: 'Liability account' },
|
||||||
|
{ id: '8', name: 'Equity', code: 'equity', description: 'Equity account' },
|
||||||
|
{ id: '9', name: 'Revenue', code: 'revenue', description: 'Revenue account' },
|
||||||
|
{ id: '10', name: 'Expense', code: 'expense', description: 'Expense account' }
|
||||||
|
]
|
||||||
|
|
||||||
const AccountFormDrawer = (props: Props) => {
|
const AccountFormDrawer = (props: Props) => {
|
||||||
// Props
|
// Props
|
||||||
const { open, handleClose, accountData, setData, editingAccount } = props
|
const { open, handleClose, accountData, setData, editingAccount } = props
|
||||||
@@ -80,6 +67,28 @@ const AccountFormDrawer = (props: Props) => {
|
|||||||
// Determine if we're editing
|
// Determine if we're editing
|
||||||
const isEdit = !!editingAccount
|
const isEdit = !!editingAccount
|
||||||
|
|
||||||
|
const { data: accounts, isLoading: isLoadingAccounts } = useChartOfAccount({
|
||||||
|
page: 1,
|
||||||
|
limit: 100
|
||||||
|
})
|
||||||
|
|
||||||
|
const { createAccount, updateAccount } = useAccountsMutation()
|
||||||
|
|
||||||
|
// Use static account types
|
||||||
|
const accountTypeOptions = staticAccountTypes
|
||||||
|
|
||||||
|
// Process chart of accounts for the dropdown
|
||||||
|
const chartOfAccountOptions = accounts?.data.length
|
||||||
|
? accounts.data
|
||||||
|
.filter(account => account.is_active) // Only show active accounts
|
||||||
|
.map(account => ({
|
||||||
|
id: account.id,
|
||||||
|
code: account.code,
|
||||||
|
name: account.name,
|
||||||
|
description: account.description
|
||||||
|
}))
|
||||||
|
: []
|
||||||
|
|
||||||
// Hooks
|
// Hooks
|
||||||
const {
|
const {
|
||||||
control,
|
control,
|
||||||
@@ -97,9 +106,11 @@ const AccountFormDrawer = (props: Props) => {
|
|||||||
// Populate form with existing data
|
// Populate form with existing data
|
||||||
resetForm({
|
resetForm({
|
||||||
name: editingAccount.name,
|
name: editingAccount.name,
|
||||||
code: editingAccount.code,
|
code: editingAccount.number,
|
||||||
category: editingAccount.category,
|
account_type: editingAccount.account_type,
|
||||||
parentAccount: ''
|
opening_balance: editingAccount.opening_balance,
|
||||||
|
description: editingAccount.description || '',
|
||||||
|
chart_of_account_id: editingAccount.chart_of_account_id
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
// Reset to initial data for new account
|
// Reset to initial data for new account
|
||||||
@@ -110,35 +121,40 @@ const AccountFormDrawer = (props: Props) => {
|
|||||||
|
|
||||||
const onSubmit = (data: FormValidateType) => {
|
const onSubmit = (data: FormValidateType) => {
|
||||||
if (isEdit && editingAccount) {
|
if (isEdit && editingAccount) {
|
||||||
// Update existing account
|
const accountRequest: AccountRequest = {
|
||||||
const updatedAccounts =
|
chart_of_account_id: data.chart_of_account_id,
|
||||||
accountData?.map(account =>
|
|
||||||
account.id === editingAccount.id
|
|
||||||
? {
|
|
||||||
...account,
|
|
||||||
code: data.code,
|
|
||||||
name: data.name,
|
|
||||||
category: data.category
|
|
||||||
}
|
|
||||||
: account
|
|
||||||
) || []
|
|
||||||
|
|
||||||
setData(updatedAccounts)
|
|
||||||
} else {
|
|
||||||
// Create new account
|
|
||||||
const newAccount: AccountType = {
|
|
||||||
id: accountData?.length ? Math.max(...accountData.map(a => a.id)) + 1 : 1,
|
|
||||||
code: data.code,
|
|
||||||
name: data.name,
|
name: data.name,
|
||||||
category: data.category,
|
number: data.code,
|
||||||
balance: '0'
|
account_type: data.account_type,
|
||||||
|
opening_balance: data.opening_balance,
|
||||||
|
description: data.description
|
||||||
}
|
}
|
||||||
|
updateAccount.mutate(
|
||||||
setData([...(accountData ?? []), newAccount])
|
{ id: editingAccount.id, payload: accountRequest },
|
||||||
|
{
|
||||||
|
onSuccess: () => {
|
||||||
|
handleClose()
|
||||||
|
resetForm(initialData)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
// Create new account - this would typically be sent as AccountRequest to API
|
||||||
|
const accountRequest: AccountRequest = {
|
||||||
|
chart_of_account_id: data.chart_of_account_id,
|
||||||
|
name: data.name,
|
||||||
|
number: data.code,
|
||||||
|
account_type: data.account_type,
|
||||||
|
opening_balance: data.opening_balance,
|
||||||
|
description: data.description
|
||||||
|
}
|
||||||
|
createAccount.mutate(accountRequest, {
|
||||||
|
onSuccess: () => {
|
||||||
|
handleClose()
|
||||||
|
resetForm(initialData)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
handleClose()
|
|
||||||
resetForm(initialData)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleReset = () => {
|
const handleReset = () => {
|
||||||
@@ -225,57 +241,129 @@ const AccountFormDrawer = (props: Props) => {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Kategori */}
|
{/* Tipe Akun */}
|
||||||
<div>
|
<div>
|
||||||
<Typography variant='body2' className='mb-2'>
|
<Typography variant='body2' className='mb-2'>
|
||||||
Kategori <span className='text-red-500'>*</span>
|
Tipe Akun <span className='text-red-500'>*</span>
|
||||||
</Typography>
|
</Typography>
|
||||||
<Controller
|
<Controller
|
||||||
name='category'
|
name='account_type'
|
||||||
control={control}
|
control={control}
|
||||||
rules={{ required: true }}
|
rules={{ required: true }}
|
||||||
render={({ field: { onChange, value, ...field } }) => (
|
render={({ field: { onChange, value, ...field } }) => (
|
||||||
<CustomAutocomplete
|
<CustomAutocomplete
|
||||||
{...field}
|
{...field}
|
||||||
options={accountCategories}
|
options={accountTypeOptions}
|
||||||
value={value || null}
|
value={accountTypeOptions.find(option => option.code === value) || null}
|
||||||
onChange={(_, newValue) => onChange(newValue || '')}
|
onChange={(_, newValue) => onChange(newValue?.code || '')}
|
||||||
|
getOptionLabel={option => option.name}
|
||||||
|
renderOption={(props, option) => (
|
||||||
|
<Box component='li' {...props}>
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2'>{option.name}</Typography>
|
||||||
|
</div>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
renderInput={params => (
|
renderInput={params => (
|
||||||
<CustomTextField
|
<CustomTextField
|
||||||
{...params}
|
{...params}
|
||||||
placeholder='Pilih kategori'
|
placeholder='Pilih tipe akun'
|
||||||
{...(errors.category && { error: true, helperText: 'Field ini wajib diisi.' })}
|
{...(errors.account_type && { error: true, helperText: 'Field ini wajib diisi.' })}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
isOptionEqualToValue={(option, value) => option === value}
|
isOptionEqualToValue={(option, value) => option.code === value.code}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Sub Akun dari */}
|
{/* Chart of Account */}
|
||||||
<div>
|
<div>
|
||||||
<Typography variant='body2' className='mb-2'>
|
<Typography variant='body2' className='mb-2'>
|
||||||
Sub Akun dari
|
Chart of Account <span className='text-red-500'>*</span>
|
||||||
</Typography>
|
</Typography>
|
||||||
<Controller
|
<Controller
|
||||||
name='parentAccount'
|
name='chart_of_account_id'
|
||||||
control={control}
|
control={control}
|
||||||
|
rules={{ required: true }}
|
||||||
render={({ field: { onChange, value, ...field } }) => (
|
render={({ field: { onChange, value, ...field } }) => (
|
||||||
<CustomAutocomplete
|
<CustomAutocomplete
|
||||||
{...field}
|
{...field}
|
||||||
options={parentAccounts}
|
loading={isLoadingAccounts}
|
||||||
value={parentAccounts.find(account => `${account.code} ${account.name}` === value) || null}
|
options={chartOfAccountOptions}
|
||||||
onChange={(_, newValue) => onChange(newValue ? `${newValue.code} ${newValue.name}` : '')}
|
value={chartOfAccountOptions.find(option => option.id === value) || null}
|
||||||
getOptionLabel={option => `${option.code} ${option.name}`}
|
onChange={(_, newValue) => onChange(newValue?.id || '')}
|
||||||
renderInput={params => <CustomTextField {...params} placeholder='Pilih akun' />}
|
getOptionLabel={option => `${option.code} - ${option.name}`}
|
||||||
isOptionEqualToValue={(option, value) =>
|
renderOption={(props, option) => (
|
||||||
`${option.code} ${option.name}` === `${value.code} ${value.name}`
|
<Box component='li' {...props}>
|
||||||
}
|
<div>
|
||||||
|
<Typography variant='body2'>
|
||||||
|
{option.code} - {option.name}
|
||||||
|
</Typography>
|
||||||
|
{option.description && (
|
||||||
|
<Typography variant='caption' color='textSecondary'>
|
||||||
|
{option.description}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
renderInput={params => (
|
||||||
|
<CustomTextField
|
||||||
|
{...params}
|
||||||
|
placeholder={isLoadingAccounts ? 'Loading chart of accounts...' : 'Pilih chart of account'}
|
||||||
|
{...(errors.chart_of_account_id && { error: true, helperText: 'Field ini wajib diisi.' })}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
isOptionEqualToValue={(option, value) => option.id === value.id}
|
||||||
|
disabled={isLoadingAccounts}
|
||||||
|
noOptionsText={isLoadingAccounts ? 'Loading...' : 'Tidak ada chart of account tersedia'}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Opening Balance */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Saldo Awal <span className='text-red-500'>*</span>
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='opening_balance'
|
||||||
|
control={control}
|
||||||
|
rules={{ required: true, min: 0 }}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField
|
||||||
|
{...field}
|
||||||
|
fullWidth
|
||||||
|
type='number'
|
||||||
|
placeholder='0'
|
||||||
|
onChange={e => field.onChange(Number(e.target.value))}
|
||||||
|
{...(errors.opening_balance && {
|
||||||
|
error: true,
|
||||||
|
helperText:
|
||||||
|
errors.opening_balance.type === 'min'
|
||||||
|
? 'Saldo awal tidak boleh negatif.'
|
||||||
|
: 'Field ini wajib diisi.'
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Deskripsi */}
|
||||||
|
<div>
|
||||||
|
<Typography variant='body2' className='mb-2'>
|
||||||
|
Deskripsi
|
||||||
|
</Typography>
|
||||||
|
<Controller
|
||||||
|
name='description'
|
||||||
|
control={control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<CustomTextField {...field} fullWidth multiline rows={3} placeholder='Deskripsi akun' />
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</Box>
|
</Box>
|
||||||
|
|||||||
@@ -41,6 +41,11 @@ import TablePaginationComponent from '@/components/TablePaginationComponent'
|
|||||||
import Loading from '@/components/layout/shared/Loading'
|
import Loading from '@/components/layout/shared/Loading'
|
||||||
import { getLocalizedUrl } from '@/utils/i18n'
|
import { getLocalizedUrl } from '@/utils/i18n'
|
||||||
import AccountFormDrawer from './AccountFormDrawer'
|
import AccountFormDrawer from './AccountFormDrawer'
|
||||||
|
import { useChartOfAccount } from '@/services/queries/chartOfAccount'
|
||||||
|
import { Account, ChartOfAccount } from '@/types/services/chartOfAccount'
|
||||||
|
import { useAccounts } from '@/services/queries/account'
|
||||||
|
import { formatCurrency } from '@/utils/transform'
|
||||||
|
import { useChartOfAccountTypes } from '@/services/queries/chartOfAccountType'
|
||||||
|
|
||||||
// Account Type
|
// Account Type
|
||||||
export type AccountType = {
|
export type AccountType = {
|
||||||
@@ -60,119 +65,10 @@ declare module '@tanstack/table-core' {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type AccountTypeWithAction = AccountType & {
|
type AccountTypeWithAction = Account & {
|
||||||
actions?: string
|
actions?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dummy Account Data
|
|
||||||
export const accountsData: AccountType[] = [
|
|
||||||
{
|
|
||||||
id: 1,
|
|
||||||
code: '1-10001',
|
|
||||||
name: 'Kas',
|
|
||||||
category: 'Kas & Bank',
|
|
||||||
balance: '20000000'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 2,
|
|
||||||
code: '1-10002',
|
|
||||||
name: 'Bank BCA',
|
|
||||||
category: 'Kas & Bank',
|
|
||||||
balance: '150000000'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 3,
|
|
||||||
code: '1-10003',
|
|
||||||
name: 'Bank Mandiri',
|
|
||||||
category: 'Kas & Bank',
|
|
||||||
balance: '75000000'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 4,
|
|
||||||
code: '1-10101',
|
|
||||||
name: 'Piutang Usaha',
|
|
||||||
category: 'Piutang',
|
|
||||||
balance: '50000000'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 5,
|
|
||||||
code: '1-10102',
|
|
||||||
name: 'Piutang Karyawan',
|
|
||||||
category: 'Piutang',
|
|
||||||
balance: '5000000'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 6,
|
|
||||||
code: '1-10201',
|
|
||||||
name: 'Persediaan Barang',
|
|
||||||
category: 'Persediaan',
|
|
||||||
balance: '100000000'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 7,
|
|
||||||
code: '1-10301',
|
|
||||||
name: 'Peralatan Kantor',
|
|
||||||
category: 'Aset Tetap',
|
|
||||||
balance: '25000000'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 8,
|
|
||||||
code: '1-10302',
|
|
||||||
name: 'Kendaraan',
|
|
||||||
category: 'Aset Tetap',
|
|
||||||
balance: '200000000'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 9,
|
|
||||||
code: '2-20001',
|
|
||||||
name: 'Hutang Usaha',
|
|
||||||
category: 'Hutang',
|
|
||||||
balance: '-30000000'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 10,
|
|
||||||
code: '2-20002',
|
|
||||||
name: 'Hutang Gaji',
|
|
||||||
category: 'Hutang',
|
|
||||||
balance: '-15000000'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 11,
|
|
||||||
code: '3-30001',
|
|
||||||
name: 'Modal Pemilik',
|
|
||||||
category: 'Ekuitas',
|
|
||||||
balance: '500000000'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 12,
|
|
||||||
code: '4-40001',
|
|
||||||
name: 'Penjualan',
|
|
||||||
category: 'Pendapatan',
|
|
||||||
balance: '250000000'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 13,
|
|
||||||
code: '5-50001',
|
|
||||||
name: 'Beban Gaji',
|
|
||||||
category: 'Beban',
|
|
||||||
balance: '-80000000'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 14,
|
|
||||||
code: '5-50002',
|
|
||||||
name: 'Beban Listrik',
|
|
||||||
category: 'Beban',
|
|
||||||
balance: '-5000000'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 15,
|
|
||||||
code: '5-50003',
|
|
||||||
name: 'Beban Telepon',
|
|
||||||
category: 'Beban',
|
|
||||||
balance: '-2000000'
|
|
||||||
}
|
|
||||||
]
|
|
||||||
|
|
||||||
// Styled Components
|
// Styled Components
|
||||||
const Icon = styled('i')({})
|
const Icon = styled('i')({})
|
||||||
|
|
||||||
@@ -242,16 +138,6 @@ const getCategoryColor = (category: string) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Format currency
|
|
||||||
const formatCurrency = (amount: string) => {
|
|
||||||
const numAmount = parseInt(amount)
|
|
||||||
return new Intl.NumberFormat('id-ID', {
|
|
||||||
style: 'currency',
|
|
||||||
currency: 'IDR',
|
|
||||||
minimumFractionDigits: 0
|
|
||||||
}).format(Math.abs(numAmount))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Column Definitions
|
// Column Definitions
|
||||||
const columnHelper = createColumnHelper<AccountTypeWithAction>()
|
const columnHelper = createColumnHelper<AccountTypeWithAction>()
|
||||||
|
|
||||||
@@ -261,53 +147,25 @@ const AccountListTable = () => {
|
|||||||
// States
|
// States
|
||||||
const [addAccountOpen, setAddAccountOpen] = useState(false)
|
const [addAccountOpen, setAddAccountOpen] = useState(false)
|
||||||
const [rowSelection, setRowSelection] = useState({})
|
const [rowSelection, setRowSelection] = useState({})
|
||||||
const [currentPage, setCurrentPage] = useState(0)
|
const [currentPage, setCurrentPage] = useState(1)
|
||||||
const [pageSize, setPageSize] = useState(10)
|
const [pageSize, setPageSize] = useState(10)
|
||||||
const [openConfirm, setOpenConfirm] = useState(false)
|
const [openConfirm, setOpenConfirm] = useState(false)
|
||||||
const [accountId, setAccountId] = useState('')
|
const [accountId, setAccountId] = useState('')
|
||||||
const [search, setSearch] = useState('')
|
const [search, setSearch] = useState('')
|
||||||
const [categoryFilter, setCategoryFilter] = useState<string>('Semua')
|
const [categoryFilter, setCategoryFilter] = useState<string>('Semua')
|
||||||
const [filteredData, setFilteredData] = useState<AccountType[]>(accountsData)
|
const [editingAccount, setEditingAccount] = useState<Account | null>(null)
|
||||||
const [data, setData] = useState<AccountType[]>(accountsData)
|
|
||||||
const [editingAccount, setEditingAccount] = useState<AccountType | null>(null)
|
const { data, isLoading } = useAccounts({
|
||||||
|
page: currentPage,
|
||||||
|
limit: pageSize,
|
||||||
|
search
|
||||||
|
})
|
||||||
|
|
||||||
// Hooks
|
// Hooks
|
||||||
const { lang: locale } = useParams()
|
const { lang: locale } = useParams()
|
||||||
|
|
||||||
// Get unique categories for filter
|
const accounts = data?.data ?? []
|
||||||
const categories = useMemo(() => {
|
const totalCount = data?.total ?? 0
|
||||||
const uniqueCategories = [...new Set(data.map(account => account.category))]
|
|
||||||
return ['Semua', ...uniqueCategories]
|
|
||||||
}, [data])
|
|
||||||
|
|
||||||
// Filter data based on search and category
|
|
||||||
useEffect(() => {
|
|
||||||
let filtered = data
|
|
||||||
|
|
||||||
// Filter by search
|
|
||||||
if (search) {
|
|
||||||
filtered = filtered.filter(
|
|
||||||
account =>
|
|
||||||
account.code.toLowerCase().includes(search.toLowerCase()) ||
|
|
||||||
account.name.toLowerCase().includes(search.toLowerCase()) ||
|
|
||||||
account.category.toLowerCase().includes(search.toLowerCase())
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Filter by category
|
|
||||||
if (categoryFilter !== 'Semua') {
|
|
||||||
filtered = filtered.filter(account => account.category === categoryFilter)
|
|
||||||
}
|
|
||||||
|
|
||||||
setFilteredData(filtered)
|
|
||||||
setCurrentPage(0)
|
|
||||||
}, [search, categoryFilter, data])
|
|
||||||
|
|
||||||
const totalCount = filteredData.length
|
|
||||||
const paginatedData = useMemo(() => {
|
|
||||||
const startIndex = currentPage * pageSize
|
|
||||||
return filteredData.slice(startIndex, startIndex + pageSize)
|
|
||||||
}, [filteredData, currentPage, pageSize])
|
|
||||||
|
|
||||||
const handlePageChange = useCallback((event: unknown, newPage: number) => {
|
const handlePageChange = useCallback((event: unknown, newPage: number) => {
|
||||||
setCurrentPage(newPage)
|
setCurrentPage(newPage)
|
||||||
@@ -319,12 +177,8 @@ const AccountListTable = () => {
|
|||||||
setCurrentPage(0)
|
setCurrentPage(0)
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
const handleDelete = () => {
|
|
||||||
setOpenConfirm(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle row click for edit
|
// Handle row click for edit
|
||||||
const handleRowClick = (account: AccountType, event: React.MouseEvent) => {
|
const handleRowClick = (account: Account, event: React.MouseEvent) => {
|
||||||
// Don't trigger row click if clicking on checkbox or link
|
// Don't trigger row click if clicking on checkbox or link
|
||||||
const target = event.target as HTMLElement
|
const target = event.target as HTMLElement
|
||||||
if (target.closest('input[type="checkbox"]') || target.closest('a') || target.closest('button')) {
|
if (target.closest('input[type="checkbox"]') || target.closest('a') || target.closest('button')) {
|
||||||
@@ -365,13 +219,17 @@ const AccountListTable = () => {
|
|||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
columnHelper.accessor('code', {
|
columnHelper.accessor('number', {
|
||||||
header: 'Kode Akun',
|
header: 'Kode Akun',
|
||||||
cell: ({ row }) => (
|
cell: ({ row }) => (
|
||||||
<Button
|
<Button
|
||||||
variant='text'
|
variant='text'
|
||||||
color='primary'
|
color='primary'
|
||||||
className='p-0 min-w-0 font-medium normal-case justify-start'
|
className='p-0 min-w-0 font-medium normal-case justify-start'
|
||||||
|
onClick={() => {
|
||||||
|
setEditingAccount(row.original)
|
||||||
|
setAddAccountOpen(true)
|
||||||
|
}}
|
||||||
sx={{
|
sx={{
|
||||||
textTransform: 'none',
|
textTransform: 'none',
|
||||||
fontWeight: 500,
|
fontWeight: 500,
|
||||||
@@ -381,7 +239,7 @@ const AccountListTable = () => {
|
|||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{row.original.code}
|
{row.original.number}
|
||||||
</Button>
|
</Button>
|
||||||
)
|
)
|
||||||
}),
|
}),
|
||||||
@@ -393,26 +251,21 @@ const AccountListTable = () => {
|
|||||||
</Typography>
|
</Typography>
|
||||||
)
|
)
|
||||||
}),
|
}),
|
||||||
columnHelper.accessor('category', {
|
columnHelper.accessor('chart_of_account.name', {
|
||||||
header: 'Kategori',
|
header: 'Kategori',
|
||||||
cell: ({ row }) => (
|
cell: ({ row }) => (
|
||||||
<Chip
|
<Typography color='text.primary' className='font-medium'>
|
||||||
variant='tonal'
|
{row.original.chart_of_account.name}
|
||||||
label={row.original.category}
|
</Typography>
|
||||||
size='small'
|
|
||||||
color={getCategoryColor(row.original.category) as any}
|
|
||||||
className='capitalize'
|
|
||||||
/>
|
|
||||||
)
|
)
|
||||||
}),
|
}),
|
||||||
columnHelper.accessor('balance', {
|
columnHelper.accessor('current_balance', {
|
||||||
header: 'Saldo',
|
header: 'Saldo',
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const balance = parseInt(row.original.balance)
|
|
||||||
return (
|
return (
|
||||||
<Typography className='font-medium text-right text-primary'>
|
<Typography className='font-medium text-right text-primary'>
|
||||||
{balance < 0 ? '-' : ''}
|
{row.original.current_balance < 0 ? '-' : ''}
|
||||||
{formatCurrency(row.original.balance)}
|
{formatCurrency(row.original.current_balance)}
|
||||||
</Typography>
|
</Typography>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -422,7 +275,7 @@ const AccountListTable = () => {
|
|||||||
)
|
)
|
||||||
|
|
||||||
const table = useReactTable({
|
const table = useReactTable({
|
||||||
data: paginatedData as AccountType[],
|
data: accounts as Account[],
|
||||||
columns,
|
columns,
|
||||||
filterFns: {
|
filterFns: {
|
||||||
fuzzy: fuzzyFilter
|
fuzzy: fuzzyFilter
|
||||||
@@ -484,63 +337,67 @@ const AccountListTable = () => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className='overflow-x-auto'>
|
<div className='overflow-x-auto'>
|
||||||
<table className={tableStyles.table}>
|
{isLoading ? (
|
||||||
<thead>
|
<Loading />
|
||||||
{table.getHeaderGroups().map(headerGroup => (
|
) : (
|
||||||
<tr key={headerGroup.id}>
|
<table className={tableStyles.table}>
|
||||||
{headerGroup.headers.map(header => (
|
<thead>
|
||||||
<th key={header.id}>
|
{table.getHeaderGroups().map(headerGroup => (
|
||||||
{header.isPlaceholder ? null : (
|
<tr key={headerGroup.id}>
|
||||||
<>
|
{headerGroup.headers.map(header => (
|
||||||
<div
|
<th key={header.id}>
|
||||||
className={classnames({
|
{header.isPlaceholder ? null : (
|
||||||
'flex items-center': header.column.getIsSorted(),
|
<>
|
||||||
'cursor-pointer select-none': header.column.getCanSort()
|
<div
|
||||||
})}
|
className={classnames({
|
||||||
onClick={header.column.getToggleSortingHandler()}
|
'flex items-center': header.column.getIsSorted(),
|
||||||
>
|
'cursor-pointer select-none': header.column.getCanSort()
|
||||||
{flexRender(header.column.columnDef.header, header.getContext())}
|
})}
|
||||||
{{
|
onClick={header.column.getToggleSortingHandler()}
|
||||||
asc: <i className='tabler-chevron-up text-xl' />,
|
>
|
||||||
desc: <i className='tabler-chevron-down text-xl' />
|
{flexRender(header.column.columnDef.header, header.getContext())}
|
||||||
}[header.column.getIsSorted() as 'asc' | 'desc'] ?? null}
|
{{
|
||||||
</div>
|
asc: <i className='tabler-chevron-up text-xl' />,
|
||||||
</>
|
desc: <i className='tabler-chevron-down text-xl' />
|
||||||
)}
|
}[header.column.getIsSorted() as 'asc' | 'desc'] ?? null}
|
||||||
</th>
|
</div>
|
||||||
))}
|
</>
|
||||||
</tr>
|
)}
|
||||||
))}
|
</th>
|
||||||
</thead>
|
))}
|
||||||
{filteredData.length === 0 ? (
|
</tr>
|
||||||
<tbody>
|
))}
|
||||||
<tr>
|
</thead>
|
||||||
<td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
|
{accounts.length === 0 ? (
|
||||||
Tidak ada data tersedia
|
<tbody>
|
||||||
</td>
|
<tr>
|
||||||
</tr>
|
<td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
|
||||||
</tbody>
|
Tidak ada data tersedia
|
||||||
) : (
|
</td>
|
||||||
<tbody>
|
</tr>
|
||||||
{table.getRowModel().rows.map(row => {
|
</tbody>
|
||||||
return (
|
) : (
|
||||||
<tr
|
<tbody>
|
||||||
key={row.id}
|
{table.getRowModel().rows.map(row => {
|
||||||
className={classnames({
|
return (
|
||||||
selected: row.getIsSelected(),
|
<tr
|
||||||
'cursor-pointer hover:bg-gray-50': true
|
key={row.id}
|
||||||
})}
|
className={classnames({
|
||||||
onClick={e => handleRowClick(row.original, e)}
|
selected: row.getIsSelected(),
|
||||||
>
|
'cursor-pointer hover:bg-gray-50': true
|
||||||
{row.getVisibleCells().map(cell => (
|
})}
|
||||||
<td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
|
onClick={e => handleRowClick(row.original, e)}
|
||||||
))}
|
>
|
||||||
</tr>
|
{row.getVisibleCells().map(cell => (
|
||||||
)
|
<td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
|
||||||
})}
|
))}
|
||||||
</tbody>
|
</tr>
|
||||||
)}
|
)
|
||||||
</table>
|
})}
|
||||||
|
</tbody>
|
||||||
|
)}
|
||||||
|
</table>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<TablePagination
|
<TablePagination
|
||||||
@@ -558,13 +415,14 @@ const AccountListTable = () => {
|
|||||||
onPageChange={handlePageChange}
|
onPageChange={handlePageChange}
|
||||||
onRowsPerPageChange={handlePageSizeChange}
|
onRowsPerPageChange={handlePageSizeChange}
|
||||||
rowsPerPageOptions={[10, 25, 50]}
|
rowsPerPageOptions={[10, 25, 50]}
|
||||||
|
disabled={isLoading}
|
||||||
/>
|
/>
|
||||||
</Card>
|
</Card>
|
||||||
<AccountFormDrawer
|
<AccountFormDrawer
|
||||||
open={addAccountOpen}
|
open={addAccountOpen}
|
||||||
handleClose={handleCloseDrawer}
|
handleClose={handleCloseDrawer}
|
||||||
accountData={data}
|
accountData={accounts}
|
||||||
setData={setData}
|
setData={() => {}}
|
||||||
editingAccount={editingAccount}
|
editingAccount={editingAccount}
|
||||||
/>
|
/>
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -11,16 +11,18 @@ import FormControl from '@mui/material/FormControl'
|
|||||||
import InputLabel from '@mui/material/InputLabel'
|
import InputLabel from '@mui/material/InputLabel'
|
||||||
import Select from '@mui/material/Select'
|
import Select from '@mui/material/Select'
|
||||||
import MenuItem from '@mui/material/MenuItem'
|
import MenuItem from '@mui/material/MenuItem'
|
||||||
|
import CircularProgress from '@mui/material/CircularProgress'
|
||||||
import CashBankCard from './CashBankCard' // Adjust import path as needed
|
import CashBankCard from './CashBankCard' // Adjust import path as needed
|
||||||
import CustomTextField from '@/@core/components/mui/TextField'
|
import CustomTextField from '@/@core/components/mui/TextField'
|
||||||
import { getLocalizedUrl } from '@/utils/i18n'
|
import { getLocalizedUrl } from '@/utils/i18n'
|
||||||
import { Locale } from '@/configs/i18n'
|
import { Locale } from '@/configs/i18n'
|
||||||
import { useParams } from 'next/navigation'
|
import { useParams } from 'next/navigation'
|
||||||
import AccountFormDrawer, { AccountType } from '../account/AccountFormDrawer'
|
import AccountFormDrawer from '../account/AccountFormDrawer'
|
||||||
import { accountsData } from '../account/AccountListTable'
|
|
||||||
import { Button } from '@mui/material'
|
import { Button } from '@mui/material'
|
||||||
|
import { Account } from '@/types/services/chartOfAccount'
|
||||||
|
import { useAccounts } from '@/services/queries/account'
|
||||||
|
import { formatCurrency } from '@/utils/transform'
|
||||||
|
|
||||||
// Types
|
|
||||||
interface BankAccount {
|
interface BankAccount {
|
||||||
id: string
|
id: string
|
||||||
title: string
|
title: string
|
||||||
@@ -41,188 +43,28 @@ interface BankAccount {
|
|||||||
status: 'active' | 'inactive' | 'blocked'
|
status: 'active' | 'inactive' | 'blocked'
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dummy Data
|
// Static chart data for fallback/demo purposes
|
||||||
const dummyAccounts: BankAccount[] = [
|
const generateChartData = (accountType: string, balance: number) => {
|
||||||
{
|
const baseValue = balance || 1000000
|
||||||
id: '1',
|
const variation = baseValue * 0.2
|
||||||
title: 'Giro',
|
|
||||||
accountNumber: '1-10003',
|
return Array.from({ length: 12 }, (_, i) => {
|
||||||
balances: [
|
const randomVariation = (Math.random() - 0.5) * variation
|
||||||
{ amount: '7.313.321', label: 'Saldo di bank' },
|
return Math.max(baseValue + randomVariation, baseValue * 0.5)
|
||||||
{ amount: '30.631.261', label: 'Saldo di kledo' }
|
})
|
||||||
],
|
}
|
||||||
chartData: [
|
|
||||||
{
|
const getChartColor = (accountType: string) => {
|
||||||
name: 'Saldo',
|
const colors = {
|
||||||
data: [
|
giro: '#ff6b9d',
|
||||||
20000000, 21000000, 20500000, 20800000, 21500000, 22000000, 25000000, 26000000, 28000000, 29000000, 30000000,
|
savings: '#4285f4',
|
||||||
31000000
|
investment: '#00bcd4',
|
||||||
]
|
credit: '#ff9800',
|
||||||
}
|
cash: '#4caf50'
|
||||||
],
|
|
||||||
categories: ['Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des', 'Jan', 'Feb', 'Mar'],
|
|
||||||
chartColor: '#ff6b9d',
|
|
||||||
currency: 'IDR',
|
|
||||||
accountType: 'giro',
|
|
||||||
bank: 'Bank Mandiri',
|
|
||||||
status: 'active'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: '2',
|
|
||||||
title: 'Tabungan Premium',
|
|
||||||
accountNumber: 'SAV-001234',
|
|
||||||
balances: [
|
|
||||||
{ amount: 15420000, label: 'Saldo Tersedia' },
|
|
||||||
{ amount: 18750000, label: 'Total Saldo' }
|
|
||||||
],
|
|
||||||
chartData: [
|
|
||||||
{
|
|
||||||
name: 'Balance',
|
|
||||||
data: [
|
|
||||||
12000000, 13500000, 14200000, 15000000, 15800000, 16200000, 17000000, 17500000, 18000000, 18200000, 18500000,
|
|
||||||
18750000
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'],
|
|
||||||
chartColor: '#4285f4',
|
|
||||||
currency: 'IDR',
|
|
||||||
accountType: 'savings',
|
|
||||||
bank: 'Bank BCA',
|
|
||||||
status: 'active'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: '3',
|
|
||||||
title: 'Investment Portfolio',
|
|
||||||
accountNumber: 'INV-789012',
|
|
||||||
balances: [
|
|
||||||
{ amount: 125000, label: 'Portfolio Value' },
|
|
||||||
{ amount: 8750, label: 'Total Gains' }
|
|
||||||
],
|
|
||||||
chartData: [
|
|
||||||
{
|
|
||||||
name: 'Portfolio Value',
|
|
||||||
data: [110000, 115000, 112000, 118000, 122000, 119000, 125000, 128000, 126000, 130000, 127000, 125000]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
|
|
||||||
currency: 'USD',
|
|
||||||
accountType: 'investment',
|
|
||||||
bank: 'Charles Schwab',
|
|
||||||
status: 'active'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: '4',
|
|
||||||
title: 'Kartu Kredit Platinum',
|
|
||||||
accountNumber: 'CC-456789',
|
|
||||||
balances: [
|
|
||||||
{ amount: 2500000, label: 'Saldo Saat Ini' },
|
|
||||||
{ amount: 47500000, label: 'Limit Tersedia' }
|
|
||||||
],
|
|
||||||
chartData: [
|
|
||||||
{
|
|
||||||
name: 'Spending',
|
|
||||||
data: [
|
|
||||||
1200000, 1800000, 2200000, 1900000, 2100000, 2400000, 2800000, 2600000, 2300000, 2500000, 2700000, 2500000
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'],
|
|
||||||
currency: 'IDR',
|
|
||||||
accountType: 'credit',
|
|
||||||
bank: 'Bank BNI',
|
|
||||||
status: 'active'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: '5',
|
|
||||||
title: 'Deposito Berjangka',
|
|
||||||
accountNumber: 'DEP-334455',
|
|
||||||
balances: [
|
|
||||||
{ amount: 50000000, label: 'Pokok Deposito' },
|
|
||||||
{ amount: 2500000, label: 'Bunga Terkumpul' }
|
|
||||||
],
|
|
||||||
chartData: [
|
|
||||||
{
|
|
||||||
name: 'Deposito Growth',
|
|
||||||
data: [
|
|
||||||
50000000, 50200000, 50420000, 50650000, 50880000, 51120000, 51360000, 51610000, 51860000, 52120000, 52380000,
|
|
||||||
52500000
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'],
|
|
||||||
currency: 'IDR',
|
|
||||||
accountType: 'savings',
|
|
||||||
bank: 'Bank BRI',
|
|
||||||
status: 'active'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: '6',
|
|
||||||
title: 'Cash Management',
|
|
||||||
accountNumber: 'CSH-111222',
|
|
||||||
balances: [{ amount: 5000, label: 'Available Cash' }],
|
|
||||||
chartData: [
|
|
||||||
{
|
|
||||||
name: 'Cash Flow',
|
|
||||||
data: [4000, 4500, 4200, 4800, 5200, 4900, 5000, 5300, 5100, 5400, 5200, 5000]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
categories: ['Q1', 'Q2', 'Q3', 'Q4', 'Q1', 'Q2', 'Q3', 'Q4', 'Q1', 'Q2', 'Q3', 'Q4'],
|
|
||||||
chartColor: '#00bcd4',
|
|
||||||
currency: 'USD',
|
|
||||||
accountType: 'cash',
|
|
||||||
bank: 'Wells Fargo',
|
|
||||||
status: 'active'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: '7',
|
|
||||||
title: 'Rekening Bisnis',
|
|
||||||
accountNumber: 'BIZ-998877',
|
|
||||||
balances: [
|
|
||||||
{ amount: 85000000, label: 'Saldo Operasional' },
|
|
||||||
{ amount: 15000000, label: 'Dana Cadangan' }
|
|
||||||
],
|
|
||||||
chartData: [
|
|
||||||
{
|
|
||||||
name: 'Business Account',
|
|
||||||
data: [
|
|
||||||
70000000, 75000000, 80000000, 82000000, 85000000, 88000000, 90000000, 87000000, 85000000, 89000000, 92000000,
|
|
||||||
100000000
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'],
|
|
||||||
chartColor: '#ff9800',
|
|
||||||
currency: 'IDR',
|
|
||||||
accountType: 'giro',
|
|
||||||
bank: 'Bank Mandiri',
|
|
||||||
status: 'active'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: '8',
|
|
||||||
title: 'Tabungan Pendidikan',
|
|
||||||
accountNumber: 'EDU-567890',
|
|
||||||
balances: [
|
|
||||||
{ amount: 25000000, label: 'Dana Pendidikan' },
|
|
||||||
{ amount: 3500000, label: 'Bunga Terkumpul' }
|
|
||||||
],
|
|
||||||
chartData: [
|
|
||||||
{
|
|
||||||
name: 'Education Savings',
|
|
||||||
data: [
|
|
||||||
20000000, 21000000, 22000000, 23000000, 24000000, 24500000, 25000000, 25500000, 26000000, 27000000, 28000000,
|
|
||||||
28500000
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'],
|
|
||||||
chartColor: '#3f51b5',
|
|
||||||
currency: 'IDR',
|
|
||||||
accountType: 'savings',
|
|
||||||
bank: 'Bank BCA',
|
|
||||||
status: 'inactive'
|
|
||||||
}
|
}
|
||||||
]
|
return colors[accountType as keyof typeof colors] || '#757575'
|
||||||
|
}
|
||||||
|
|
||||||
const DebouncedInput = ({
|
const DebouncedInput = ({
|
||||||
value: initialValue,
|
value: initialValue,
|
||||||
onChange,
|
onChange,
|
||||||
@@ -251,28 +93,122 @@ const DebouncedInput = ({
|
|||||||
|
|
||||||
return <CustomTextField {...props} value={value} onChange={e => setValue(e.target.value)} />
|
return <CustomTextField {...props} value={value} onChange={e => setValue(e.target.value)} />
|
||||||
}
|
}
|
||||||
|
|
||||||
const CashBankList = () => {
|
const CashBankList = () => {
|
||||||
const [searchQuery, setSearchQuery] = useState('')
|
const [searchQuery, setSearchQuery] = useState('')
|
||||||
const [editingAccount, setEditingAccount] = useState<AccountType | null>(null)
|
const [editingAccount, setEditingAccount] = useState<Account | null>(null)
|
||||||
const [addAccountOpen, setAddAccountOpen] = useState(false)
|
const [addAccountOpen, setAddAccountOpen] = useState(false)
|
||||||
const [data, setData] = useState<AccountType[]>(accountsData)
|
const [data, setData] = useState<Account[]>([])
|
||||||
const { lang: locale } = useParams()
|
const { lang: locale } = useParams()
|
||||||
|
|
||||||
|
// Use the accounts hook with search parameter
|
||||||
|
const { data: accountsResponse, isLoading } = useAccounts({
|
||||||
|
page: 1,
|
||||||
|
limit: 10,
|
||||||
|
search: searchQuery
|
||||||
|
})
|
||||||
|
|
||||||
const handleCloseDrawer = () => {
|
const handleCloseDrawer = () => {
|
||||||
setAddAccountOpen(false)
|
setAddAccountOpen(false)
|
||||||
setEditingAccount(null)
|
setEditingAccount(null)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Filter and search logic
|
// Transform API data to match our BankAccount interface
|
||||||
|
const transformedAccounts = useMemo((): BankAccount[] => {
|
||||||
|
if (!accountsResponse?.data) return []
|
||||||
|
|
||||||
|
return accountsResponse.data.map((account: Account) => {
|
||||||
|
const chartData = generateChartData(account.account_type, account.current_balance)
|
||||||
|
|
||||||
|
// Map account type to display type
|
||||||
|
const typeMapping = {
|
||||||
|
current_asset: 'giro' as const,
|
||||||
|
non_current_asset: 'investment' as const,
|
||||||
|
current_liability: 'credit' as const,
|
||||||
|
non_current_liability: 'credit' as const,
|
||||||
|
other_current_asset: 'cash' as const,
|
||||||
|
other_current_liability: 'credit' as const,
|
||||||
|
equity: 'savings' as const,
|
||||||
|
revenue: 'savings' as const,
|
||||||
|
expense: 'cash' as const
|
||||||
|
}
|
||||||
|
const displayAccountType = typeMapping[account.account_type as keyof typeof typeMapping] || 'giro'
|
||||||
|
|
||||||
|
// Get bank name from account
|
||||||
|
const getBankName = (acc: Account): string => {
|
||||||
|
if (acc.chart_of_account?.name) {
|
||||||
|
return acc.chart_of_account.name
|
||||||
|
}
|
||||||
|
|
||||||
|
const typeToBank = {
|
||||||
|
current_asset: 'Bank Account',
|
||||||
|
non_current_asset: 'Investment Account',
|
||||||
|
current_liability: 'Credit Account',
|
||||||
|
other_current_asset: 'Cash Account',
|
||||||
|
equity: 'Equity Account',
|
||||||
|
revenue: 'Revenue Account',
|
||||||
|
expense: 'Expense Account'
|
||||||
|
}
|
||||||
|
|
||||||
|
return typeToBank[acc.account_type as keyof typeof typeToBank] || 'General Account'
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create balance information
|
||||||
|
const balances = []
|
||||||
|
|
||||||
|
if (account.current_balance !== account.opening_balance) {
|
||||||
|
balances.push({
|
||||||
|
amount: formatCurrency(account.current_balance),
|
||||||
|
label: 'Saldo Saat Ini'
|
||||||
|
})
|
||||||
|
balances.push({
|
||||||
|
amount: formatCurrency(account.opening_balance),
|
||||||
|
label: 'Saldo Awal'
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
balances.push({
|
||||||
|
amount: formatCurrency(account.current_balance),
|
||||||
|
label: 'Saldo'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: account.id,
|
||||||
|
title: account.name,
|
||||||
|
accountNumber: account.number,
|
||||||
|
balances,
|
||||||
|
chartData: [
|
||||||
|
{
|
||||||
|
name: 'Saldo',
|
||||||
|
data: chartData
|
||||||
|
}
|
||||||
|
],
|
||||||
|
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'],
|
||||||
|
chartColor: getChartColor(account.account_type),
|
||||||
|
currency: 'IDR', // Assuming IDR as default, adjust as needed
|
||||||
|
accountType: displayAccountType,
|
||||||
|
bank: getBankName(account),
|
||||||
|
status: account.is_active ? 'active' : 'inactive'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}, [accountsResponse])
|
||||||
|
|
||||||
|
// Filter accounts based on search (if not handled by API)
|
||||||
const filteredAccounts = useMemo(() => {
|
const filteredAccounts = useMemo(() => {
|
||||||
return dummyAccounts.filter(account => {
|
if (!searchQuery || accountsResponse) {
|
||||||
|
// If using API search or no search, return transformed accounts as is
|
||||||
|
return transformedAccounts
|
||||||
|
}
|
||||||
|
|
||||||
|
// Local filtering fallback
|
||||||
|
return transformedAccounts.filter(account => {
|
||||||
const matchesSearch =
|
const matchesSearch =
|
||||||
account.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
account.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||||
account.accountNumber.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
account.accountNumber.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||||
account.bank.toLowerCase().includes(searchQuery.toLowerCase())
|
account.bank.toLowerCase().includes(searchQuery.toLowerCase())
|
||||||
return matchesSearch
|
return matchesSearch
|
||||||
})
|
})
|
||||||
}, [searchQuery])
|
}, [transformedAccounts, searchQuery, accountsResponse])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -283,8 +219,16 @@ const CashBankList = () => {
|
|||||||
<DebouncedInput
|
<DebouncedInput
|
||||||
value={searchQuery}
|
value={searchQuery}
|
||||||
onChange={value => setSearchQuery(value as string)}
|
onChange={value => setSearchQuery(value as string)}
|
||||||
placeholder='Cari '
|
placeholder='Cari akun...'
|
||||||
className='max-sm:is-full'
|
className='max-sm:is-full'
|
||||||
|
disabled={isLoading}
|
||||||
|
InputProps={{
|
||||||
|
startAdornment: (
|
||||||
|
<InputAdornment position='start'>
|
||||||
|
<i className='tabler-search' />
|
||||||
|
</InputAdornment>
|
||||||
|
)
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
<Box>
|
<Box>
|
||||||
<Button
|
<Button
|
||||||
@@ -295,6 +239,7 @@ const CashBankList = () => {
|
|||||||
setEditingAccount(null)
|
setEditingAccount(null)
|
||||||
setAddAccountOpen(true)
|
setAddAccountOpen(true)
|
||||||
}}
|
}}
|
||||||
|
disabled={isLoading}
|
||||||
>
|
>
|
||||||
Tambah Akun
|
Tambah Akun
|
||||||
</Button>
|
</Button>
|
||||||
@@ -302,45 +247,77 @@ const CashBankList = () => {
|
|||||||
</div>
|
</div>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
|
{/* Loading State */}
|
||||||
|
{isLoading && (
|
||||||
|
<Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
|
||||||
|
<CircularProgress />
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Account Cards */}
|
{/* Account Cards */}
|
||||||
<Grid container spacing={3}>
|
{!isLoading && (
|
||||||
{filteredAccounts.length > 0 ? (
|
<Grid container spacing={3}>
|
||||||
filteredAccounts.map(account => (
|
{filteredAccounts.length > 0 ? (
|
||||||
<Grid key={account.id} size={{ xs: 12, lg: 6, xl: 4 }}>
|
filteredAccounts.map(account => (
|
||||||
<CashBankCard
|
<Grid key={account.id} size={{ xs: 12, lg: 6, xl: 4 }}>
|
||||||
title={account.title}
|
<CashBankCard
|
||||||
accountNumber={account.accountNumber}
|
title={account.title}
|
||||||
balances={account.balances}
|
accountNumber={account.accountNumber}
|
||||||
chartData={account.chartData}
|
balances={account.balances}
|
||||||
categories={account.categories}
|
chartData={account.chartData}
|
||||||
chartColor={account.chartColor}
|
categories={account.categories}
|
||||||
currency={account.currency}
|
chartColor={account.chartColor}
|
||||||
showButton={account.accountType !== 'cash'}
|
currency={account.currency}
|
||||||
href={getLocalizedUrl(`/apps/cash-bank/${account.accountNumber}/detail`, locale as Locale)}
|
showButton={account.accountType !== 'cash'}
|
||||||
/>
|
href={getLocalizedUrl(`/apps/cash-bank/${account.accountNumber}/detail`, locale as Locale)}
|
||||||
|
/>
|
||||||
|
</Grid>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<Grid size={{ xs: 12 }}>
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
textAlign: 'center',
|
||||||
|
py: 8,
|
||||||
|
backgroundColor: 'grey.50',
|
||||||
|
borderRadius: 2
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Typography variant='h6' color='text.secondary' gutterBottom>
|
||||||
|
{searchQuery ? 'Tidak ada akun yang ditemukan' : 'Belum ada akun'}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant='body2' color='text.secondary'>
|
||||||
|
{searchQuery
|
||||||
|
? 'Coba ubah kata kunci pencarian yang digunakan'
|
||||||
|
: 'Mulai dengan menambahkan akun baru'}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
</Grid>
|
</Grid>
|
||||||
))
|
)}
|
||||||
) : (
|
</Grid>
|
||||||
<Grid size={{ xs: 12 }}>
|
)}
|
||||||
<Box
|
|
||||||
sx={{
|
{/* Error State (if needed) */}
|
||||||
textAlign: 'center',
|
{!isLoading && !accountsResponse && (
|
||||||
py: 8,
|
<Grid size={{ xs: 12 }}>
|
||||||
backgroundColor: 'grey.50',
|
<Box
|
||||||
borderRadius: 2
|
sx={{
|
||||||
}}
|
textAlign: 'center',
|
||||||
>
|
py: 8,
|
||||||
<Typography variant='h6' color='text.secondary' gutterBottom>
|
backgroundColor: 'error.light',
|
||||||
Tidak ada akun yang ditemukan
|
borderRadius: 2,
|
||||||
</Typography>
|
color: 'error.contrastText'
|
||||||
<Typography variant='body2' color='text.secondary'>
|
}}
|
||||||
Coba ubah kata kunci pencarian atau filter yang digunakan
|
>
|
||||||
</Typography>
|
<Typography variant='h6' gutterBottom>
|
||||||
</Box>
|
Terjadi kesalahan saat memuat data
|
||||||
</Grid>
|
</Typography>
|
||||||
)}
|
<Typography variant='body2'>Silakan coba lagi atau hubungi administrator</Typography>
|
||||||
</Grid>
|
</Box>
|
||||||
|
</Grid>
|
||||||
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
<AccountFormDrawer
|
<AccountFormDrawer
|
||||||
open={addAccountOpen}
|
open={addAccountOpen}
|
||||||
handleClose={handleCloseDrawer}
|
handleClose={handleCloseDrawer}
|
||||||
|
|||||||
@@ -13,8 +13,10 @@ import Checkbox from '@mui/material/Checkbox'
|
|||||||
import Chip from '@mui/material/Chip'
|
import Chip from '@mui/material/Chip'
|
||||||
import MenuItem from '@mui/material/MenuItem'
|
import MenuItem from '@mui/material/MenuItem'
|
||||||
import TablePagination from '@mui/material/TablePagination'
|
import TablePagination from '@mui/material/TablePagination'
|
||||||
|
import TextField from '@mui/material/TextField'
|
||||||
import type { TextFieldProps } from '@mui/material/TextField'
|
import type { TextFieldProps } from '@mui/material/TextField'
|
||||||
import Typography from '@mui/material/Typography'
|
import Typography from '@mui/material/Typography'
|
||||||
|
import { Box, CircularProgress, useTheme } from '@mui/material'
|
||||||
|
|
||||||
// Third-party Imports
|
// Third-party Imports
|
||||||
import type { RankingInfo } from '@tanstack/match-sorter-utils'
|
import type { RankingInfo } from '@tanstack/match-sorter-utils'
|
||||||
@@ -40,11 +42,10 @@ import { getLocalizedUrl } from '@/utils/i18n'
|
|||||||
|
|
||||||
// Style Imports
|
// Style Imports
|
||||||
import tableStyles from '@core/styles/table.module.css'
|
import tableStyles from '@core/styles/table.module.css'
|
||||||
import { Box, CircularProgress } from '@mui/material'
|
|
||||||
import Loading from '../../../../../components/layout/shared/Loading'
|
import Loading from '../../../../../components/layout/shared/Loading'
|
||||||
import { useOrders } from '../../../../../services/queries/orders'
|
import { useOrders } from '../../../../../services/queries/orders'
|
||||||
import { Order } from '../../../../../types/services/order'
|
import { Order } from '../../../../../types/services/order'
|
||||||
import { formatCurrency } from '../../../../../utils/transform'
|
import { formatCurrency, formatDateDDMMYYYY, formatForInputDate } from '../../../../../utils/transform'
|
||||||
|
|
||||||
declare module '@tanstack/table-core' {
|
declare module '@tanstack/table-core' {
|
||||||
interface FilterFns {
|
interface FilterFns {
|
||||||
@@ -105,15 +106,28 @@ const DebouncedInput = ({
|
|||||||
const columnHelper = createColumnHelper<ECommerceOrderTypeWithAction>()
|
const columnHelper = createColumnHelper<ECommerceOrderTypeWithAction>()
|
||||||
|
|
||||||
const OrderListTable = () => {
|
const OrderListTable = () => {
|
||||||
|
const theme = useTheme()
|
||||||
|
|
||||||
// States
|
// States
|
||||||
const [rowSelection, setRowSelection] = useState({})
|
const [rowSelection, setRowSelection] = useState({})
|
||||||
const [currentPage, setCurrentPage] = useState(1)
|
const [currentPage, setCurrentPage] = useState(1)
|
||||||
const [pageSize, setPageSize] = useState(10)
|
const [pageSize, setPageSize] = useState(10)
|
||||||
const [search, setSearch] = useState('')
|
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({
|
const { data, isLoading, error, isFetching } = useOrders({
|
||||||
page: currentPage,
|
page: currentPage,
|
||||||
limit: pageSize,
|
limit: pageSize,
|
||||||
|
date_from: formatDateDDMMYYYY(new Date(filter.date_from)),
|
||||||
|
date_to: formatDateDDMMYYYY(new Date(filter.date_to)),
|
||||||
search
|
search
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -163,7 +177,7 @@ const OrderListTable = () => {
|
|||||||
cell: ({ row }) => (
|
cell: ({ row }) => (
|
||||||
<Typography
|
<Typography
|
||||||
component={Link}
|
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'
|
color='primary.main'
|
||||||
>{`#${row.original.order_number}`}</Typography>
|
>{`#${row.original.order_number}`}</Typography>
|
||||||
)
|
)
|
||||||
@@ -203,6 +217,10 @@ const OrderListTable = () => {
|
|||||||
header: 'Discount',
|
header: 'Discount',
|
||||||
cell: ({ row }) => <Typography>{formatCurrency(row.original.discount_amount)}</Typography>
|
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', {
|
columnHelper.accessor('action', {
|
||||||
header: 'Action',
|
header: 'Action',
|
||||||
cell: ({ row }) => (
|
cell: ({ row }) => (
|
||||||
@@ -214,10 +232,7 @@ const OrderListTable = () => {
|
|||||||
{
|
{
|
||||||
text: 'View',
|
text: 'View',
|
||||||
icon: 'tabler-eye',
|
icon: 'tabler-eye',
|
||||||
href: getLocalizedUrl(
|
href: getLocalizedUrl(`/apps/inventory/orders/${row.original.id}/details`, locale as Locale),
|
||||||
`/apps/ecommerce/orders/${row.original.id}/details`,
|
|
||||||
locale as Locale
|
|
||||||
),
|
|
||||||
linkProps: { className: 'flex items-center gap-2 is-full plb-2 pli-4' }
|
linkProps: { className: 'flex items-center gap-2 is-full plb-2 pli-4' }
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -248,49 +263,104 @@ const OrderListTable = () => {
|
|||||||
state: {
|
state: {
|
||||||
rowSelection,
|
rowSelection,
|
||||||
pagination: {
|
pagination: {
|
||||||
pageIndex: currentPage, // <= penting!
|
pageIndex: currentPage,
|
||||||
pageSize
|
pageSize
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
enableRowSelection: true, //enable row selection for all rows
|
enableRowSelection: true,
|
||||||
onRowSelectionChange: setRowSelection,
|
onRowSelectionChange: setRowSelection,
|
||||||
getCoreRowModel: getCoreRowModel(),
|
getCoreRowModel: getCoreRowModel(),
|
||||||
// Disable client-side pagination since we're handling it server-side
|
|
||||||
manualPagination: true,
|
manualPagination: true,
|
||||||
pageCount: Math.ceil(totalCount / pageSize)
|
pageCount: Math.ceil(totalCount / pageSize)
|
||||||
})
|
})
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card>
|
<Card>
|
||||||
<CardContent className='flex justify-between max-sm:flex-col sm:items-center gap-4'>
|
<CardContent className='flex flex-col gap-4'>
|
||||||
<DebouncedInput
|
{/* Date Range Filter */}
|
||||||
value={search}
|
<div className='flex items-center gap-4 max-sm:flex-col'>
|
||||||
onChange={value => setSearch(value as string)}
|
<Typography variant='body2' className='min-w-fit'>
|
||||||
placeholder='Search Order'
|
Filter by Date:
|
||||||
className='sm:is-auto'
|
</Typography>
|
||||||
/>
|
<TextField
|
||||||
<div className='flex items-center max-sm:flex-col gap-4 max-sm:is-full is-auto'>
|
type='date'
|
||||||
<CustomTextField
|
value={filter.date_from}
|
||||||
select
|
onChange={e => {
|
||||||
value={pageSize}
|
setFilter({
|
||||||
onChange={handlePageSizeChange}
|
...filter,
|
||||||
className='is-[70px] max-sm:is-full'
|
date_from: e.target.value
|
||||||
>
|
})
|
||||||
<MenuItem value='10'>10</MenuItem>
|
setCurrentPage(1)
|
||||||
<MenuItem value='25'>25</MenuItem>
|
}}
|
||||||
<MenuItem value='50'>50</MenuItem>
|
size='small'
|
||||||
<MenuItem value='100'>100</MenuItem>
|
sx={{
|
||||||
</CustomTextField>
|
'& .MuiOutlinedInput-root': {
|
||||||
<Button
|
'&.Mui-focused fieldset': {
|
||||||
variant='tonal'
|
borderColor: 'primary.main'
|
||||||
color='secondary'
|
},
|
||||||
startIcon={<i className='tabler-upload' />}
|
'& fieldset': {
|
||||||
className='max-sm:is-full is-auto'
|
borderColor: theme.palette.mode === 'dark' ? 'rgba(231, 227, 252, 0.22)' : theme.palette.divider
|
||||||
>
|
}
|
||||||
Export
|
}
|
||||||
</Button>
|
}}
|
||||||
|
/>
|
||||||
|
<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>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
|
|
||||||
<div className='overflow-x-auto'>
|
<div className='overflow-x-auto'>
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<Loading />
|
<Loading />
|
||||||
|
|||||||
@@ -82,6 +82,8 @@ const ProductOrganize = () => {
|
|||||||
onChange={e => handleSelectChange('printer_type', e.target.value)}
|
onChange={e => handleSelectChange('printer_type', e.target.value)}
|
||||||
>
|
>
|
||||||
<MenuItem value={`kitchen`}>Kitchen</MenuItem>
|
<MenuItem value={`kitchen`}>Kitchen</MenuItem>
|
||||||
|
<MenuItem value={`bar`}>Bar</MenuItem>
|
||||||
|
<MenuItem value={`ticket`}>Ticket</MenuItem>
|
||||||
</CustomTextField>
|
</CustomTextField>
|
||||||
</form>
|
</form>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
|
|||||||
@@ -33,7 +33,8 @@ const AddCategoryDrawer = (props: Props) => {
|
|||||||
const [formData, setFormData] = useState<CategoryRequest>({
|
const [formData, setFormData] = useState<CategoryRequest>({
|
||||||
name: '',
|
name: '',
|
||||||
description: '',
|
description: '',
|
||||||
business_type: ''
|
business_type: '',
|
||||||
|
order: 0
|
||||||
})
|
})
|
||||||
|
|
||||||
// Handle Form Submit
|
// 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
|
// Handle Form Reset
|
||||||
const handleReset = () => {
|
const handleReset = () => {
|
||||||
handleClose()
|
handleClose()
|
||||||
setFormData({
|
setFormData({
|
||||||
name: '',
|
name: '',
|
||||||
description: '',
|
description: '',
|
||||||
business_type: ''
|
business_type: '',
|
||||||
|
order: 0
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,6 +108,15 @@ const AddCategoryDrawer = (props: Props) => {
|
|||||||
>
|
>
|
||||||
<MenuItem value='restaurant'>Restaurant</MenuItem>
|
<MenuItem value='restaurant'>Restaurant</MenuItem>
|
||||||
</CustomTextField>
|
</CustomTextField>
|
||||||
|
<CustomTextField
|
||||||
|
fullWidth
|
||||||
|
label='Order'
|
||||||
|
name='order'
|
||||||
|
type='number'
|
||||||
|
value={formData.order}
|
||||||
|
onChange={handleOrderChange}
|
||||||
|
placeholder='0'
|
||||||
|
/>
|
||||||
<CustomTextField
|
<CustomTextField
|
||||||
fullWidth
|
fullWidth
|
||||||
label='Description'
|
label='Description'
|
||||||
|
|||||||
@@ -34,7 +34,8 @@ const EditCategoryDrawer = (props: Props) => {
|
|||||||
const [formData, setFormData] = useState<CategoryRequest>({
|
const [formData, setFormData] = useState<CategoryRequest>({
|
||||||
name: '',
|
name: '',
|
||||||
description: '',
|
description: '',
|
||||||
business_type: ''
|
business_type: '',
|
||||||
|
order: 0
|
||||||
})
|
})
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -42,7 +43,8 @@ const EditCategoryDrawer = (props: Props) => {
|
|||||||
setFormData({
|
setFormData({
|
||||||
name: data.name,
|
name: data.name,
|
||||||
description: data.description,
|
description: data.description,
|
||||||
business_type: data.business_type
|
business_type: data.business_type,
|
||||||
|
order: data.order
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}, [data])
|
}, [data])
|
||||||
@@ -51,11 +53,14 @@ const EditCategoryDrawer = (props: Props) => {
|
|||||||
const handleFormSubmit = (e: any) => {
|
const handleFormSubmit = (e: any) => {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
|
|
||||||
updateCategory({ id: data.id, payload: formData }, {
|
updateCategory(
|
||||||
onSuccess: () => {
|
{ id: data.id, payload: formData },
|
||||||
handleReset()
|
{
|
||||||
|
onSuccess: () => {
|
||||||
|
handleReset()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
})
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleInputChange = (e: any) => {
|
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
|
// Handle Form Reset
|
||||||
const handleReset = () => {
|
const handleReset = () => {
|
||||||
handleClose()
|
handleClose()
|
||||||
setFormData({
|
setFormData({
|
||||||
name: '',
|
name: '',
|
||||||
description: '',
|
description: '',
|
||||||
business_type: ''
|
business_type: '',
|
||||||
|
order: 0
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,6 +123,15 @@ const EditCategoryDrawer = (props: Props) => {
|
|||||||
>
|
>
|
||||||
<MenuItem value='restaurant'>Restaurant</MenuItem>
|
<MenuItem value='restaurant'>Restaurant</MenuItem>
|
||||||
</CustomTextField>
|
</CustomTextField>
|
||||||
|
<CustomTextField
|
||||||
|
fullWidth
|
||||||
|
label='Order'
|
||||||
|
name='order'
|
||||||
|
type='number'
|
||||||
|
value={formData.order}
|
||||||
|
onChange={handleOrderChange}
|
||||||
|
placeholder='0'
|
||||||
|
/>
|
||||||
<CustomTextField
|
<CustomTextField
|
||||||
fullWidth
|
fullWidth
|
||||||
label='Description'
|
label='Description'
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import MenuItem from '@mui/material/MenuItem'
|
|||||||
import TablePagination from '@mui/material/TablePagination'
|
import TablePagination from '@mui/material/TablePagination'
|
||||||
import type { TextFieldProps } from '@mui/material/TextField'
|
import type { TextFieldProps } from '@mui/material/TextField'
|
||||||
import Typography from '@mui/material/Typography'
|
import Typography from '@mui/material/Typography'
|
||||||
|
import { Box, CircularProgress } from '@mui/material'
|
||||||
|
|
||||||
// Third-party Imports
|
// Third-party Imports
|
||||||
import type { RankingInfo } from '@tanstack/match-sorter-utils'
|
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 type { ColumnDef, FilterFn } from '@tanstack/react-table'
|
||||||
import { createColumnHelper, flexRender, getCoreRowModel, useReactTable } from '@tanstack/react-table'
|
import { createColumnHelper, flexRender, getCoreRowModel, useReactTable } from '@tanstack/react-table'
|
||||||
import classnames from 'classnames'
|
import classnames from 'classnames'
|
||||||
|
import { DragDropContext, Droppable, Draggable, DropResult } from '@hello-pangea/dnd'
|
||||||
|
|
||||||
// Component Imports
|
// Component Imports
|
||||||
import TablePaginationComponent from '@components/TablePaginationComponent'
|
import TablePaginationComponent from '@components/TablePaginationComponent'
|
||||||
import CustomTextField from '@core/components/mui/TextField'
|
import CustomTextField from '@core/components/mui/TextField'
|
||||||
import OptionMenu from '@core/components/option-menu'
|
import OptionMenu from '@core/components/option-menu'
|
||||||
import AddCategoryDrawer from './AddCategoryDrawer'
|
import AddCategoryDrawer from './AddCategoryDrawer'
|
||||||
|
import EditCategoryDrawer from './EditCategoryDrawer'
|
||||||
// Style Imports
|
|
||||||
import tableStyles from '@core/styles/table.module.css'
|
|
||||||
import { Box, CircularProgress } from '@mui/material'
|
|
||||||
import ConfirmDeleteDialog from '../../../../../components/dialogs/confirm-delete'
|
import ConfirmDeleteDialog from '../../../../../components/dialogs/confirm-delete'
|
||||||
import Loading from '../../../../../components/layout/shared/Loading'
|
import Loading from '../../../../../components/layout/shared/Loading'
|
||||||
|
|
||||||
|
// Services Imports
|
||||||
import { useCategoriesMutation } from '../../../../../services/mutations/categories'
|
import { useCategoriesMutation } from '../../../../../services/mutations/categories'
|
||||||
import { useCategories } from '../../../../../services/queries/categories'
|
import { useCategories } from '../../../../../services/queries/categories'
|
||||||
import { Category } from '../../../../../types/services/category'
|
import { Category } from '../../../../../types/services/category'
|
||||||
import EditCategoryDrawer from './EditCategoryDrawer'
|
|
||||||
import { formatDate } from '../../../../../utils/transform'
|
import { formatDate } from '../../../../../utils/transform'
|
||||||
|
|
||||||
|
// Style Imports
|
||||||
|
import tableStyles from '@core/styles/table.module.css'
|
||||||
|
|
||||||
declare module '@tanstack/table-core' {
|
declare module '@tanstack/table-core' {
|
||||||
interface FilterFns {
|
interface FilterFns {
|
||||||
fuzzy: FilterFn<unknown>
|
fuzzy: FilterFn<unknown>
|
||||||
@@ -51,15 +54,8 @@ type CategoryWithActionsType = Category & {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const fuzzyFilter: FilterFn<any> = (row, columnId, value, addMeta) => {
|
const fuzzyFilter: FilterFn<any> = (row, columnId, value, addMeta) => {
|
||||||
// Rank the item
|
|
||||||
const itemRank = rankItem(row.getValue(columnId), value)
|
const itemRank = rankItem(row.getValue(columnId), value)
|
||||||
|
addMeta({ itemRank })
|
||||||
// Store the itemRank info
|
|
||||||
addMeta({
|
|
||||||
itemRank
|
|
||||||
})
|
|
||||||
|
|
||||||
// Return if the item should be filtered in/out
|
|
||||||
return itemRank.passed
|
return itemRank.passed
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,7 +69,6 @@ const DebouncedInput = ({
|
|||||||
onChange: (value: string | number) => void
|
onChange: (value: string | number) => void
|
||||||
debounce?: number
|
debounce?: number
|
||||||
} & Omit<TextFieldProps, 'onChange'>) => {
|
} & Omit<TextFieldProps, 'onChange'>) => {
|
||||||
// States
|
|
||||||
const [value, setValue] = useState(initialValue)
|
const [value, setValue] = useState(initialValue)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -86,47 +81,51 @@ const DebouncedInput = ({
|
|||||||
}, debounce)
|
}, debounce)
|
||||||
|
|
||||||
return () => clearTimeout(timeout)
|
return () => clearTimeout(timeout)
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
||||||
}, [value])
|
}, [value])
|
||||||
|
|
||||||
return <CustomTextField {...props} value={value} onChange={e => setValue(e.target.value)} />
|
return <CustomTextField {...props} value={value} onChange={e => setValue(e.target.value)} />
|
||||||
}
|
}
|
||||||
|
|
||||||
// Column Definitions
|
|
||||||
const columnHelper = createColumnHelper<CategoryWithActionsType>()
|
const columnHelper = createColumnHelper<CategoryWithActionsType>()
|
||||||
|
|
||||||
const ProductCategoryTable = () => {
|
const ProductCategoryTable = () => {
|
||||||
// States
|
|
||||||
const [addCategoryOpen, setAddCategoryOpen] = useState(false)
|
const [addCategoryOpen, setAddCategoryOpen] = useState(false)
|
||||||
const [editCategoryOpen, setEditCategoryOpen] = useState(false)
|
const [editCategoryOpen, setEditCategoryOpen] = useState(false)
|
||||||
const [rowSelection, setRowSelection] = useState({})
|
const [rowSelection, setRowSelection] = useState({})
|
||||||
const [currentPage, setCurrentPage] = useState(1)
|
const [currentPage, setCurrentPage] = useState(1)
|
||||||
const [pageSize, setPageSize] = useState(10)
|
const [pageSize, setPageSize] = useState(50)
|
||||||
const [categoryId, setCategoryId] = useState('')
|
const [categoryId, setCategoryId] = useState('')
|
||||||
const [openConfirm, setOpenConfirm] = useState(false)
|
const [openConfirm, setOpenConfirm] = useState(false)
|
||||||
const [currentCategory, setCurrentCategory] = useState<Category>()
|
const [currentCategory, setCurrentCategory] = useState<Category>()
|
||||||
const [search, setSearch] = useState('')
|
const [search, setSearch] = useState('')
|
||||||
|
const [localCategories, setLocalCategories] = useState<Category[]>([])
|
||||||
|
|
||||||
// Fetch products with pagination and search
|
|
||||||
const { data, isLoading, error, isFetching } = useCategories({
|
const { data, isLoading, error, isFetching } = useCategories({
|
||||||
page: currentPage,
|
page: currentPage,
|
||||||
limit: pageSize
|
limit: pageSize
|
||||||
})
|
})
|
||||||
|
|
||||||
const { mutate: deleteCategory, isPending: isDeleting } = useCategoriesMutation().deleteCategory
|
const { mutate: deleteCategory, isPending: isDeleting } = useCategoriesMutation().deleteCategory
|
||||||
|
const { mutate: updateCategory } = useCategoriesMutation().updateCategory
|
||||||
|
|
||||||
const categories = data?.categories ?? []
|
const categories = data?.categories ?? []
|
||||||
const totalCount = data?.total_count ?? 0
|
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) => {
|
const handlePageChange = useCallback((event: unknown, newPage: number) => {
|
||||||
setCurrentPage(newPage)
|
setCurrentPage(newPage)
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
// Handle page size change
|
|
||||||
const handlePageSizeChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
|
const handlePageSizeChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
const newPageSize = parseInt(event.target.value, 10)
|
const newPageSize = parseInt(event.target.value, 50)
|
||||||
setPageSize(newPageSize)
|
setPageSize(newPageSize)
|
||||||
setCurrentPage(1) // Reset to first page
|
setCurrentPage(1)
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
const handleDelete = () => {
|
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>[]>(
|
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',
|
id: 'select',
|
||||||
header: ({ table }) => (
|
header: ({ table }) => (
|
||||||
@@ -163,7 +210,6 @@ const ProductCategoryTable = () => {
|
|||||||
header: 'Name',
|
header: 'Name',
|
||||||
cell: ({ row }) => (
|
cell: ({ row }) => (
|
||||||
<div className='flex items-center gap-3'>
|
<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'>
|
<div className='flex flex-col items-start'>
|
||||||
<Typography className='font-medium' color='text.primary'>
|
<Typography className='font-medium' color='text.primary'>
|
||||||
{row.original.name}
|
{row.original.name}
|
||||||
@@ -173,7 +219,7 @@ const ProductCategoryTable = () => {
|
|||||||
)
|
)
|
||||||
}),
|
}),
|
||||||
columnHelper.accessor('description', {
|
columnHelper.accessor('description', {
|
||||||
header: 'Decription',
|
header: 'Description',
|
||||||
cell: ({ row }) => <Typography>{row.original.description || '-'}</Typography>
|
cell: ({ row }) => <Typography>{row.original.description || '-'}</Typography>
|
||||||
}),
|
}),
|
||||||
columnHelper.accessor('business_type', {
|
columnHelper.accessor('business_type', {
|
||||||
@@ -219,12 +265,11 @@ const ProductCategoryTable = () => {
|
|||||||
enableSorting: false
|
enableSorting: false
|
||||||
})
|
})
|
||||||
],
|
],
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
||||||
[data]
|
[data]
|
||||||
)
|
)
|
||||||
|
|
||||||
const table = useReactTable({
|
const table = useReactTable({
|
||||||
data: categories as Category[],
|
data: localCategories as Category[],
|
||||||
columns,
|
columns,
|
||||||
filterFns: {
|
filterFns: {
|
||||||
fuzzy: fuzzyFilter
|
fuzzy: fuzzyFilter
|
||||||
@@ -232,14 +277,13 @@ const ProductCategoryTable = () => {
|
|||||||
state: {
|
state: {
|
||||||
rowSelection,
|
rowSelection,
|
||||||
pagination: {
|
pagination: {
|
||||||
pageIndex: currentPage, // <= penting!
|
pageIndex: currentPage,
|
||||||
pageSize
|
pageSize
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
enableRowSelection: true, //enable row selection for all rows
|
enableRowSelection: true,
|
||||||
onRowSelectionChange: setRowSelection,
|
onRowSelectionChange: setRowSelection,
|
||||||
getCoreRowModel: getCoreRowModel(),
|
getCoreRowModel: getCoreRowModel(),
|
||||||
// Disable client-side pagination since we're handling it server-side
|
|
||||||
manualPagination: true,
|
manualPagination: true,
|
||||||
pageCount: Math.ceil(totalCount / pageSize)
|
pageCount: Math.ceil(totalCount / pageSize)
|
||||||
})
|
})
|
||||||
@@ -261,9 +305,9 @@ const ProductCategoryTable = () => {
|
|||||||
onChange={handlePageSizeChange}
|
onChange={handlePageSizeChange}
|
||||||
className='flex-auto max-sm:is-full sm:is-[70px]'
|
className='flex-auto max-sm:is-full sm:is-[70px]'
|
||||||
>
|
>
|
||||||
<MenuItem value='10'>10</MenuItem>
|
<MenuItem value='50'>50</MenuItem>
|
||||||
<MenuItem value='15'>15</MenuItem>
|
<MenuItem value='75'>75</MenuItem>
|
||||||
<MenuItem value='25'>25</MenuItem>
|
<MenuItem value='100'>100</MenuItem>
|
||||||
</CustomTextField>
|
</CustomTextField>
|
||||||
<Button
|
<Button
|
||||||
variant='contained'
|
variant='contained'
|
||||||
@@ -275,18 +319,18 @@ const ProductCategoryTable = () => {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className='overflow-x-auto'>
|
<div className='overflow-x-auto relative'>
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<Loading />
|
<Loading />
|
||||||
) : (
|
) : (
|
||||||
<table className={tableStyles.table}>
|
<DragDropContext onDragEnd={handleDragEnd}>
|
||||||
<thead>
|
<table className={tableStyles.table}>
|
||||||
{table.getHeaderGroups().map(headerGroup => (
|
<thead>
|
||||||
<tr key={headerGroup.id}>
|
{table.getHeaderGroups().map(headerGroup => (
|
||||||
{headerGroup.headers.map(header => (
|
<tr key={headerGroup.id}>
|
||||||
<th key={header.id}>
|
{headerGroup.headers.map(header => (
|
||||||
{header.isPlaceholder ? null : (
|
<th key={header.id}>
|
||||||
<>
|
{header.isPlaceholder ? null : (
|
||||||
<div
|
<div
|
||||||
className={classnames({
|
className={classnames({
|
||||||
'flex items-center': header.column.getIsSorted(),
|
'flex items-center': header.column.getIsSorted(),
|
||||||
@@ -300,38 +344,58 @@ const ProductCategoryTable = () => {
|
|||||||
desc: <i className='tabler-chevron-down text-xl' />
|
desc: <i className='tabler-chevron-down text-xl' />
|
||||||
}[header.column.getIsSorted() as 'asc' | 'desc'] ?? null}
|
}[header.column.getIsSorted() as 'asc' | 'desc'] ?? null}
|
||||||
</div>
|
</div>
|
||||||
</>
|
)}
|
||||||
)}
|
</th>
|
||||||
</th>
|
))}
|
||||||
))}
|
</tr>
|
||||||
</tr>
|
))}
|
||||||
))}
|
</thead>
|
||||||
</thead>
|
<Droppable droppableId='category-table'>
|
||||||
{table.getFilteredRowModel().rows.length === 0 ? (
|
{provided => (
|
||||||
<tbody>
|
<tbody {...provided.droppableProps} ref={provided.innerRef}>
|
||||||
<tr>
|
{table.getFilteredRowModel().rows.length === 0 ? (
|
||||||
<td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
|
<tr>
|
||||||
No data available
|
<td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
|
||||||
</td>
|
No data available
|
||||||
</tr>
|
</td>
|
||||||
</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>
|
</tr>
|
||||||
)
|
) : (
|
||||||
})}
|
table
|
||||||
</tbody>
|
.getRowModel()
|
||||||
)}
|
.rows.slice(0, table.getState().pagination.pageSize)
|
||||||
</table>
|
.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 && (
|
{isFetching && !isLoading && (
|
||||||
@@ -365,7 +429,7 @@ const ProductCategoryTable = () => {
|
|||||||
page={currentPage}
|
page={currentPage}
|
||||||
onPageChange={handlePageChange}
|
onPageChange={handlePageChange}
|
||||||
onRowsPerPageChange={handlePageSizeChange}
|
onRowsPerPageChange={handlePageSizeChange}
|
||||||
rowsPerPageOptions={[10, 25, 50]}
|
rowsPerPageOptions={[50, 75, 100]}
|
||||||
disabled={isLoading}
|
disabled={isLoading}
|
||||||
/>
|
/>
|
||||||
</Card>
|
</Card>
|
||||||
|
|||||||
@@ -11,8 +11,6 @@ import Typography from '@mui/material/Typography'
|
|||||||
// Third-party Imports
|
// Third-party Imports
|
||||||
import PerfectScrollbar from 'react-perfect-scrollbar'
|
import PerfectScrollbar from 'react-perfect-scrollbar'
|
||||||
|
|
||||||
// Type Imports
|
|
||||||
|
|
||||||
// Component Imports
|
// Component Imports
|
||||||
import CustomTextField from '@core/components/mui/TextField'
|
import CustomTextField from '@core/components/mui/TextField'
|
||||||
import { Autocomplete } from '@mui/material'
|
import { Autocomplete } from '@mui/material'
|
||||||
@@ -25,6 +23,7 @@ import { useOutlets } from '../../../../../services/queries/outlets'
|
|||||||
import { Product } from '../../../../../types/services/product'
|
import { Product } from '../../../../../types/services/product'
|
||||||
import { ProductRecipeRequest } from '../../../../../types/services/productRecipe'
|
import { ProductRecipeRequest } from '../../../../../types/services/productRecipe'
|
||||||
import { resetProductVariant } from '../../../../../redux-store/slices/productRecipe'
|
import { resetProductVariant } from '../../../../../redux-store/slices/productRecipe'
|
||||||
|
import { IngredientItem } from '@/types/services/ingredient'
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
open: boolean
|
open: boolean
|
||||||
@@ -38,7 +37,8 @@ const initialData = {
|
|||||||
product_id: '',
|
product_id: '',
|
||||||
variant_id: '',
|
variant_id: '',
|
||||||
ingredient_id: '',
|
ingredient_id: '',
|
||||||
quantity: 0
|
quantity: 0,
|
||||||
|
waste: 0
|
||||||
}
|
}
|
||||||
|
|
||||||
const AddRecipeDrawer = (props: Props) => {
|
const AddRecipeDrawer = (props: Props) => {
|
||||||
@@ -55,23 +55,45 @@ const AddRecipeDrawer = (props: Props) => {
|
|||||||
const [ingredientDebouncedInput] = useDebounce(ingredientInput, 500)
|
const [ingredientDebouncedInput] = useDebounce(ingredientInput, 500)
|
||||||
const [formData, setFormData] = useState<ProductRecipeRequest>(initialData)
|
const [formData, setFormData] = useState<ProductRecipeRequest>(initialData)
|
||||||
|
|
||||||
|
// Add state untuk menyimpan selected ingredient
|
||||||
|
const [selectedIngredient, setSelectedIngredient] = useState<IngredientItem | null>(null)
|
||||||
|
|
||||||
const { data: outlets, isLoading: outletsLoading } = useOutlets({
|
const { data: outlets, isLoading: outletsLoading } = useOutlets({
|
||||||
search: outletDebouncedInput
|
search: outletDebouncedInput
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Modifikasi query ingredients dengan enabled condition
|
||||||
const { data: ingredients, isLoading: ingredientsLoading } = useIngredients({
|
const { data: ingredients, isLoading: ingredientsLoading } = useIngredients({
|
||||||
search: ingredientDebouncedInput
|
search: ingredientDebouncedInput
|
||||||
})
|
})
|
||||||
|
|
||||||
const outletOptions = useMemo(() => outlets?.outlets || [], [outlets])
|
const outletOptions = useMemo(() => outlets?.outlets || [], [outlets])
|
||||||
const ingredientOptions = useMemo(() => ingredients?.data || [], [ingredients])
|
|
||||||
|
// Perbaiki ingredient options untuk include selected ingredient
|
||||||
|
const ingredientOptions = useMemo(() => {
|
||||||
|
const options = ingredients?.data || []
|
||||||
|
|
||||||
|
// Jika ada selected ingredient dan tidak ada di current options, tambahkan
|
||||||
|
if (selectedIngredient && !options.find(opt => opt.id === selectedIngredient.id)) {
|
||||||
|
return [selectedIngredient, ...options]
|
||||||
|
}
|
||||||
|
|
||||||
|
return options
|
||||||
|
}, [ingredients, selectedIngredient])
|
||||||
|
|
||||||
const { createProductRecipe, updateProductRecipe } = useProductRecipesMutation()
|
const { createProductRecipe, updateProductRecipe } = useProductRecipesMutation()
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (currentProductRecipe.id) {
|
if (currentProductRecipe.id) {
|
||||||
setFormData(currentProductRecipe)
|
setFormData(currentProductRecipe)
|
||||||
|
|
||||||
|
// Set selected ingredient dari current product recipe
|
||||||
|
const currentIngredient = ingredients?.data?.find(ing => ing.id === currentProductRecipe.ingredient_id)
|
||||||
|
if (currentIngredient) {
|
||||||
|
setSelectedIngredient(currentIngredient)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}, [currentProductRecipe])
|
}, [currentProductRecipe, ingredients])
|
||||||
|
|
||||||
const handleSubmit = (e: any) => {
|
const handleSubmit = (e: any) => {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
@@ -101,24 +123,16 @@ const AddRecipeDrawer = (props: Props) => {
|
|||||||
handleClose()
|
handleClose()
|
||||||
dispatch(resetProductVariant())
|
dispatch(resetProductVariant())
|
||||||
setFormData(initialData)
|
setFormData(initialData)
|
||||||
}
|
setSelectedIngredient(null) // Reset selected ingredient
|
||||||
|
setIngredientInput('') // Reset input
|
||||||
const handleInputChange = (e: any) => {
|
|
||||||
setFormData({
|
|
||||||
...formData,
|
|
||||||
[e.target.name]: e.target.value
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const setTitleDrawer = (recipe: any) => {
|
const setTitleDrawer = (recipe: any) => {
|
||||||
const addOrEdit = currentProductRecipe.id ? 'Edit ' : 'Add '
|
const addOrEdit = currentProductRecipe.id ? 'Edit ' : 'Add '
|
||||||
|
|
||||||
let title = 'Original'
|
let title = 'Original'
|
||||||
|
|
||||||
if (recipe?.name) {
|
if (recipe?.name) {
|
||||||
title = recipe?.name
|
title = recipe?.name
|
||||||
}
|
}
|
||||||
|
|
||||||
return addOrEdit + title
|
return addOrEdit + title
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -144,13 +158,14 @@ const AddRecipeDrawer = (props: Props) => {
|
|||||||
<Typography color='text.primary' className='font-medium'>
|
<Typography color='text.primary' className='font-medium'>
|
||||||
Basic Information
|
Basic Information
|
||||||
</Typography>
|
</Typography>
|
||||||
|
|
||||||
<Autocomplete
|
<Autocomplete
|
||||||
options={outletOptions}
|
options={outletOptions}
|
||||||
loading={outletsLoading}
|
loading={outletsLoading}
|
||||||
getOptionLabel={option => option.name}
|
getOptionLabel={option => option.name}
|
||||||
value={outletOptions.find(p => p.id === formData.outlet_id) || null}
|
value={outletOptions.find(p => p.id === formData.outlet_id) || null}
|
||||||
onInputChange={(event, newOutlettInput) => {
|
onInputChange={(event, newOutletInput) => {
|
||||||
setOutletInput(newOutlettInput)
|
setOutletInput(newOutletInput)
|
||||||
}}
|
}}
|
||||||
onChange={(event, newValue) => {
|
onChange={(event, newValue) => {
|
||||||
setFormData({
|
setFormData({
|
||||||
@@ -161,7 +176,6 @@ const AddRecipeDrawer = (props: Props) => {
|
|||||||
renderInput={params => (
|
renderInput={params => (
|
||||||
<CustomTextField
|
<CustomTextField
|
||||||
{...params}
|
{...params}
|
||||||
className=''
|
|
||||||
label='Outlet'
|
label='Outlet'
|
||||||
fullWidth
|
fullWidth
|
||||||
InputProps={{
|
InputProps={{
|
||||||
@@ -171,24 +185,35 @@ const AddRecipeDrawer = (props: Props) => {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* Perbaiki Autocomplete untuk Ingredients */}
|
||||||
<Autocomplete
|
<Autocomplete
|
||||||
options={ingredientOptions || []}
|
options={ingredientOptions || []}
|
||||||
loading={ingredientsLoading}
|
loading={ingredientsLoading}
|
||||||
getOptionLabel={option => option.name}
|
getOptionLabel={option => option.name}
|
||||||
value={ingredientOptions?.find(p => p.id === formData.ingredient_id) || null}
|
value={selectedIngredient}
|
||||||
onInputChange={(event, newIngredientInput) => {
|
onInputChange={(event, newIngredientInput) => {
|
||||||
setIngredientInput(newIngredientInput)
|
setIngredientInput(newIngredientInput)
|
||||||
}}
|
}}
|
||||||
onChange={(event, newValue) => {
|
onChange={(event, newValue) => {
|
||||||
|
setSelectedIngredient(newValue) // Set selected ingredient
|
||||||
setFormData({
|
setFormData({
|
||||||
...formData,
|
...formData,
|
||||||
ingredient_id: newValue?.id || ''
|
ingredient_id: newValue?.id || ''
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Clear input search setelah selection
|
||||||
|
if (newValue) {
|
||||||
|
setIngredientInput('')
|
||||||
|
}
|
||||||
}}
|
}}
|
||||||
|
// Tambahkan props untuk mencegah clear on blur
|
||||||
|
clearOnBlur={false}
|
||||||
|
// Handle case ketika input kosong tapi ada selected value
|
||||||
|
inputValue={selectedIngredient ? selectedIngredient.name : ingredientInput}
|
||||||
renderInput={params => (
|
renderInput={params => (
|
||||||
<CustomTextField
|
<CustomTextField
|
||||||
{...params}
|
{...params}
|
||||||
className=''
|
|
||||||
label='Ingredient'
|
label='Ingredient'
|
||||||
fullWidth
|
fullWidth
|
||||||
InputProps={{
|
InputProps={{
|
||||||
@@ -198,6 +223,18 @@ const AddRecipeDrawer = (props: Props) => {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* Unit Field - Disabled, value from selected ingredient */}
|
||||||
|
<CustomTextField
|
||||||
|
label='Unit'
|
||||||
|
fullWidth
|
||||||
|
disabled
|
||||||
|
value={selectedIngredient?.unit?.name || ''}
|
||||||
|
InputProps={{
|
||||||
|
readOnly: true
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
<CustomTextField
|
<CustomTextField
|
||||||
type='number'
|
type='number'
|
||||||
label='Quantity'
|
label='Quantity'
|
||||||
@@ -205,6 +242,15 @@ const AddRecipeDrawer = (props: Props) => {
|
|||||||
value={formData.quantity}
|
value={formData.quantity}
|
||||||
onChange={e => setFormData({ ...formData, quantity: Number(e.target.value) })}
|
onChange={e => setFormData({ ...formData, quantity: Number(e.target.value) })}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<CustomTextField
|
||||||
|
type='number'
|
||||||
|
label='Waste'
|
||||||
|
fullWidth
|
||||||
|
value={formData.waste}
|
||||||
|
onChange={e => setFormData({ ...formData, waste: Number(e.target.value) })}
|
||||||
|
/>
|
||||||
|
|
||||||
<div className='flex items-center gap-4'>
|
<div className='flex items-center gap-4'>
|
||||||
<Button
|
<Button
|
||||||
variant='contained'
|
variant='contained'
|
||||||
|
|||||||
@@ -161,7 +161,7 @@ const ProductDetail = () => {
|
|||||||
<TableCell className='font-semibold text-center'>
|
<TableCell className='font-semibold text-center'>
|
||||||
<div className='flex items-center justify-center gap-2'>
|
<div className='flex items-center justify-center gap-2'>
|
||||||
<i className='tabler-package text-blue-600' />
|
<i className='tabler-package text-blue-600' />
|
||||||
Stock Available
|
Waste
|
||||||
</div>
|
</div>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className='font-semibold text-right'>
|
<TableCell className='font-semibold text-right'>
|
||||||
@@ -197,12 +197,7 @@ const ProductDetail = () => {
|
|||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className='text-center'>{formatCurrency(item.ingredient.cost)}</TableCell>
|
<TableCell className='text-center'>{formatCurrency(item.ingredient.cost)}</TableCell>
|
||||||
<TableCell className='text-center'>
|
<TableCell className='text-center'>
|
||||||
<Chip
|
<Chip label={item.waste ?? 0} size='small' color={'success'} variant='outlined' />
|
||||||
label={item.ingredient.stock}
|
|
||||||
size='small'
|
|
||||||
color={item.ingredient.stock > 5 ? 'success' : 'warning'}
|
|
||||||
variant='outlined'
|
|
||||||
/>
|
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className='text-right font-medium'>
|
<TableCell className='text-right font-medium'>
|
||||||
{formatCurrency(item.ingredient.cost * item.quantity)}
|
{formatCurrency(item.ingredient.cost * item.quantity)}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import React, { useState } from 'react'
|
|||||||
import { Card, CardContent, CardHeader, Typography, Button, Box, Stack } from '@mui/material'
|
import { Card, CardContent, CardHeader, Typography, Button, Box, Stack } from '@mui/material'
|
||||||
import IngedientUnitConversionDrawer from './IngedientUnitConversionDrawer' // Sesuaikan dengan path file Anda
|
import IngedientUnitConversionDrawer from './IngedientUnitConversionDrawer' // Sesuaikan dengan path file Anda
|
||||||
import { Ingredient } from '@/types/services/productRecipe'
|
import { Ingredient } from '@/types/services/productRecipe'
|
||||||
|
import { useUnitConverterByIngredient } from '@/services/queries/unitConverter'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
data: Ingredient | undefined
|
data: Ingredient | undefined
|
||||||
@@ -12,6 +13,8 @@ const IngredientDetailUnit = ({ data }: Props) => {
|
|||||||
// State untuk mengontrol drawer
|
// State untuk mengontrol drawer
|
||||||
const [openConversionDrawer, setOpenConversionDrawer] = useState(false)
|
const [openConversionDrawer, setOpenConversionDrawer] = useState(false)
|
||||||
|
|
||||||
|
const { data: unitConverters, isLoading } = useUnitConverterByIngredient(data?.id as string)
|
||||||
|
|
||||||
// Function untuk membuka drawer
|
// Function untuk membuka drawer
|
||||||
const handleOpenConversionDrawer = () => {
|
const handleOpenConversionDrawer = () => {
|
||||||
setOpenConversionDrawer(true)
|
setOpenConversionDrawer(true)
|
||||||
@@ -42,6 +45,16 @@ const IngredientDetailUnit = ({ data }: Props) => {
|
|||||||
: {data?.unit.name ?? '-'}
|
: {data?.unit.name ?? '-'}
|
||||||
</Typography>
|
</Typography>
|
||||||
</Box>
|
</Box>
|
||||||
|
{unitConverters?.map(unitConverter => (
|
||||||
|
<Box sx={{ display: 'flex', alignItems: 'center' }}>
|
||||||
|
<Typography variant='body1' color='text.secondary'>
|
||||||
|
1 {unitConverter.from_unit.name}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant='body1' sx={{ fontWeight: 'medium' }}>
|
||||||
|
: {unitConverter.conversion_factor} {unitConverter.to_unit.name}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
)) ?? []}
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
|
|||||||
@@ -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
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user