Compare commits
116
Commits
2c754d96fd
...
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 | ||
|
|
54c7598e7a | ||
|
|
40c417ec72 | ||
|
|
c91be1812b | ||
|
|
3a74e32e64 | ||
|
|
8026004630 | ||
|
|
0e8216b0c9 | ||
|
|
e8c1d02843 | ||
|
|
a019a4bdbc | ||
|
|
5def10dc64 | ||
|
|
5723d49090 | ||
|
|
1a9015563f | ||
|
|
34442740e2 | ||
|
|
e13fbab564 | ||
|
|
f2eb142dec | ||
|
|
a1d23cad9e | ||
|
|
b3a41fe0e0 | ||
|
|
5a77d3c2ea | ||
|
|
29defb68c8 | ||
|
|
c9e260860c | ||
|
|
9c1b1fc1db | ||
|
|
42b95bb212 | ||
|
|
63eea38d48 | ||
|
|
630d9c0e65 | ||
|
|
e267a50946 |
@@ -39,3 +39,5 @@ next-env.d.ts
|
||||
# icon generated file
|
||||
src/assets/iconify-icons/generated-icons.js
|
||||
src/assets/iconify-icons/generated-icons.css
|
||||
|
||||
*.backup
|
||||
|
||||
Generated
+1222
-58
File diff suppressed because it is too large
Load Diff
+9
-2
@@ -30,6 +30,7 @@
|
||||
"@fullcalendar/list": "6.1.15",
|
||||
"@fullcalendar/react": "6.1.15",
|
||||
"@fullcalendar/timegrid": "6.1.15",
|
||||
"@hello-pangea/dnd": "^18.0.1",
|
||||
"@hookform/resolvers": "3.9.1",
|
||||
"@iconify/react": "^6.0.1",
|
||||
"@mui/lab": "6.0.0-beta.19",
|
||||
@@ -52,18 +53,23 @@
|
||||
"apexcharts": "3.49.0",
|
||||
"axios": "^1.11.0",
|
||||
"bootstrap-icons": "1.11.3",
|
||||
"chart.js": "^4.5.1",
|
||||
"chartjs-plugin-datalabels": "^2.2.0",
|
||||
"classnames": "2.5.1",
|
||||
"cmdk": "1.0.4",
|
||||
"date-fns": "4.1.0",
|
||||
"emoji-mart": "5.6.0",
|
||||
"exceljs": "^4.4.0",
|
||||
"fs-extra": "11.2.0",
|
||||
"html2canvas": "^1.4.1",
|
||||
"input-otp": "1.4.1",
|
||||
"jspdf": "^3.0.1",
|
||||
"jspdf-autotable": "^5.0.2",
|
||||
"keen-slider": "6.8.6",
|
||||
"lucide-react": "^0.544.0",
|
||||
"mapbox-gl": "3.9.0",
|
||||
"negotiator": "1.0.0",
|
||||
"next": "15.1.2",
|
||||
"next": "^15.1.9",
|
||||
"react": "18.3.1",
|
||||
"react-apexcharts": "1.4.1",
|
||||
"react-colorful": "5.6.1",
|
||||
@@ -79,7 +85,8 @@
|
||||
"react-use": "17.6.0",
|
||||
"recharts": "2.15.0",
|
||||
"use-debounce": "^10.0.5",
|
||||
"valibot": "0.42.1"
|
||||
"valibot": "0.42.1",
|
||||
"xlsx": "^0.18.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@iconify/json": "2.2.286",
|
||||
|
||||
@@ -0,0 +1,976 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { RotateCw, Trophy, Trash2, RefreshCw, Shuffle, Sparkles, Gift } from 'lucide-react';
|
||||
import { useVoucherRows } from '@/services/queries/vouchers';
|
||||
import { Voucher, VoucherRow } from '@/types/services/voucher';
|
||||
import { toast } from 'react-toastify';
|
||||
|
||||
interface SpinRow {
|
||||
id: string;
|
||||
rowNumber: number;
|
||||
vouchers: Voucher[];
|
||||
displayVouchers: Voucher[];
|
||||
isSpinning: boolean;
|
||||
isShuffling: boolean;
|
||||
winner: Voucher | null;
|
||||
wheelRef: React.RefObject<HTMLDivElement>;
|
||||
selectedWinner: Voucher | null;
|
||||
}
|
||||
|
||||
interface WinnerHistory {
|
||||
rowNumber: number;
|
||||
winner: Voucher;
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
const RandomDrawApp: React.FC = () => {
|
||||
const [spinRows, setSpinRows] = useState<SpinRow[]>([]);
|
||||
const [numberOfRows, setNumberOfRows] = useState<number>(5);
|
||||
const [winnersHistory, setWinnersHistory] = useState<WinnerHistory[]>([]);
|
||||
const [isRevealingWinners, setIsRevealingWinners] = useState<boolean>(false);
|
||||
const [revealedWinners, setRevealedWinners] = useState<Set<number>>(new Set());
|
||||
const [isSequentialSpinning, setIsSequentialSpinning] = useState<boolean>(false);
|
||||
const [currentSpinningRow, setCurrentSpinningRow] = useState<number | null>(null);
|
||||
const [selectedPrize, setSelectedPrize] = useState<number>(1); // 1 for Emas 0.25 Gram, 2 for Emas 3 Gram
|
||||
const audioContextRef = useRef<AudioContext | null>(null);
|
||||
const tickIntervalRefs = useRef<Map<string, NodeJS.Timeout>>(new Map());
|
||||
const shuffleIntervalRefs = useRef<Map<string, NodeJS.Timeout>>(new Map());
|
||||
|
||||
// Use React Query hook for fetching voucher data - disabled by default
|
||||
const { data: voucherData, isLoading: isLoadingData, refetch: refetchVouchers, error: fetchError } = useVoucherRows({
|
||||
rows: numberOfRows,
|
||||
winner_number: selectedPrize
|
||||
}, {
|
||||
enabled: false // Disable automatic fetching - only fetch when Load Data is clicked
|
||||
});
|
||||
|
||||
// Initialize Audio Context
|
||||
useEffect(() => {
|
||||
const initAudio = () => {
|
||||
if (!audioContextRef.current) {
|
||||
audioContextRef.current = new (window.AudioContext || (window as any).webkitAudioContext)();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('click', initAudio, { once: true });
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('click', initAudio);
|
||||
tickIntervalRefs.current.forEach(timeout => clearTimeout(timeout));
|
||||
shuffleIntervalRefs.current.forEach(timeout => clearTimeout(timeout));
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Create tick sound effect
|
||||
const playTickSound = () => {
|
||||
if (!audioContextRef.current) return;
|
||||
|
||||
const ctx = audioContextRef.current;
|
||||
const oscillator = ctx.createOscillator();
|
||||
const gainNode = ctx.createGain();
|
||||
|
||||
oscillator.connect(gainNode);
|
||||
gainNode.connect(ctx.destination);
|
||||
|
||||
oscillator.frequency.setValueAtTime(800, ctx.currentTime);
|
||||
oscillator.frequency.exponentialRampToValueAtTime(200, ctx.currentTime + 0.05);
|
||||
|
||||
gainNode.gain.setValueAtTime(0, ctx.currentTime);
|
||||
gainNode.gain.linearRampToValueAtTime(0.1, ctx.currentTime + 0.01);
|
||||
gainNode.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.05);
|
||||
|
||||
oscillator.start(ctx.currentTime);
|
||||
oscillator.stop(ctx.currentTime + 0.05);
|
||||
};
|
||||
|
||||
// Create drum roll sound
|
||||
const playDrumRoll = () => {
|
||||
if (!audioContextRef.current) return;
|
||||
|
||||
const ctx = audioContextRef.current;
|
||||
const oscillator = ctx.createOscillator();
|
||||
const gainNode = ctx.createGain();
|
||||
const noiseNode = ctx.createBufferSource();
|
||||
|
||||
// Create noise buffer for snare-like sound
|
||||
const bufferSize = ctx.sampleRate * 0.05;
|
||||
const buffer = ctx.createBuffer(1, bufferSize, ctx.sampleRate);
|
||||
const data = buffer.getChannelData(0);
|
||||
for (let i = 0; i < bufferSize; i++) {
|
||||
data[i] = Math.random() * 2 - 1;
|
||||
}
|
||||
noiseNode.buffer = buffer;
|
||||
|
||||
oscillator.connect(gainNode);
|
||||
noiseNode.connect(gainNode);
|
||||
gainNode.connect(ctx.destination);
|
||||
|
||||
oscillator.frequency.setValueAtTime(200, ctx.currentTime);
|
||||
gainNode.gain.setValueAtTime(0.05, ctx.currentTime);
|
||||
gainNode.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.1);
|
||||
|
||||
oscillator.start(ctx.currentTime);
|
||||
oscillator.stop(ctx.currentTime + 0.1);
|
||||
noiseNode.start(ctx.currentTime);
|
||||
};
|
||||
|
||||
// Create winner sound
|
||||
const playWinnerSound = () => {
|
||||
if (!audioContextRef.current) return;
|
||||
|
||||
const ctx = audioContextRef.current;
|
||||
const notes = [523.25, 659.25, 783.99, 1046.5]; // C, E, G, C (higher octave)
|
||||
|
||||
notes.forEach((freq, index) => {
|
||||
const oscillator = ctx.createOscillator();
|
||||
const gainNode = ctx.createGain();
|
||||
|
||||
oscillator.connect(gainNode);
|
||||
gainNode.connect(ctx.destination);
|
||||
|
||||
oscillator.frequency.setValueAtTime(freq, ctx.currentTime + index * 0.1);
|
||||
|
||||
gainNode.gain.setValueAtTime(0, ctx.currentTime + index * 0.1);
|
||||
gainNode.gain.linearRampToValueAtTime(0.2, ctx.currentTime + index * 0.1 + 0.05);
|
||||
gainNode.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + index * 0.1 + 0.5);
|
||||
|
||||
oscillator.start(ctx.currentTime + index * 0.1);
|
||||
oscillator.stop(ctx.currentTime + index * 0.1 + 0.5);
|
||||
});
|
||||
};
|
||||
|
||||
// Start tick sound during spinning
|
||||
const startTickSound = (rowId: string, duration: number) => {
|
||||
const existingInterval = tickIntervalRefs.current.get(rowId);
|
||||
if (existingInterval) {
|
||||
clearTimeout(existingInterval);
|
||||
}
|
||||
|
||||
let tickInterval = 50;
|
||||
const maxInterval = 200;
|
||||
const intervalIncrement = (maxInterval - tickInterval) / (duration / 100);
|
||||
|
||||
const tick = () => {
|
||||
playTickSound();
|
||||
tickInterval += intervalIncrement;
|
||||
|
||||
if (tickInterval < maxInterval) {
|
||||
const timeoutId = setTimeout(tick, Math.min(tickInterval, maxInterval));
|
||||
tickIntervalRefs.current.set(rowId, timeoutId);
|
||||
}
|
||||
};
|
||||
|
||||
tick();
|
||||
|
||||
setTimeout(() => {
|
||||
const interval = tickIntervalRefs.current.get(rowId);
|
||||
if (interval) {
|
||||
clearTimeout(interval);
|
||||
tickIntervalRefs.current.delete(rowId);
|
||||
}
|
||||
}, duration + 100);
|
||||
};
|
||||
|
||||
// Shuffle array
|
||||
const shuffleArray = <T,>(array: T[]): T[] => {
|
||||
const shuffled = [...array];
|
||||
for (let i = shuffled.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(Math.random() * (i + 1));
|
||||
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
|
||||
}
|
||||
return shuffled;
|
||||
};
|
||||
|
||||
// Process voucher data when it changes
|
||||
useEffect(() => {
|
||||
if (voucherData && voucherData.rows) {
|
||||
const newSpinRows: SpinRow[] = voucherData.rows.map(row => ({
|
||||
id: `row-${row.row_number}-${Date.now()}`,
|
||||
rowNumber: row.row_number,
|
||||
vouchers: row.vouchers,
|
||||
displayVouchers: [...row.vouchers],
|
||||
isSpinning: false,
|
||||
isShuffling: false,
|
||||
winner: null,
|
||||
wheelRef: React.createRef<HTMLDivElement>(),
|
||||
selectedWinner: null,
|
||||
}));
|
||||
setSpinRows(newSpinRows);
|
||||
setRevealedWinners(new Set());
|
||||
}
|
||||
}, [voucherData]);
|
||||
|
||||
// Show error if fetch failed
|
||||
useEffect(() => {
|
||||
if (fetchError) {
|
||||
toast.error('Failed to load voucher data. Please check your connection and try again.');
|
||||
}
|
||||
}, [fetchError]);
|
||||
|
||||
// Remove auto-refetch - data will only load when Load Data button is clicked
|
||||
|
||||
// Shuffle all rows (Acak functionality)
|
||||
const shuffleAllRows = () => {
|
||||
setSpinRows(prev => prev.map(row => ({
|
||||
...row,
|
||||
isShuffling: true
|
||||
})));
|
||||
|
||||
// Animate shuffling for each row
|
||||
spinRows.forEach((row, index) => {
|
||||
let shuffleCount = 0;
|
||||
const maxShuffles = 20;
|
||||
|
||||
const shuffleInterval = setInterval(() => {
|
||||
shuffleCount++;
|
||||
|
||||
setSpinRows(prev => prev.map(r => {
|
||||
if (r.id === row.id) {
|
||||
return {
|
||||
...r,
|
||||
displayVouchers: shuffleArray(r.vouchers)
|
||||
};
|
||||
}
|
||||
return r;
|
||||
}));
|
||||
|
||||
playTickSound();
|
||||
|
||||
if (shuffleCount >= maxShuffles) {
|
||||
clearInterval(shuffleInterval);
|
||||
setTimeout(() => {
|
||||
setSpinRows(prev => prev.map(r => {
|
||||
if (r.id === row.id) {
|
||||
return {
|
||||
...r,
|
||||
isShuffling: false
|
||||
};
|
||||
}
|
||||
return r;
|
||||
}));
|
||||
}, index * 100);
|
||||
}
|
||||
}, 100);
|
||||
|
||||
shuffleIntervalRefs.current.set(row.id, shuffleInterval as any);
|
||||
});
|
||||
};
|
||||
|
||||
// Reveal winners dramatically
|
||||
const revealWinnersDramatically = async () => {
|
||||
setIsRevealingWinners(true);
|
||||
setRevealedWinners(new Set());
|
||||
|
||||
// First, arrange winners to be in the winner zone for each row
|
||||
const arrangedRows = spinRows.map(row => {
|
||||
const winner = row.vouchers.find(v => v.is_winner);
|
||||
if (!winner) return row;
|
||||
|
||||
// Create a new display order with winner at position 3 or 4 (will be in winner zone)
|
||||
const otherVouchers = row.vouchers.filter(v => v.voucher_code !== winner.voucher_code);
|
||||
const shuffledOthers = shuffleArray(otherVouchers);
|
||||
|
||||
// Place winner at index 3 (4th position) which will be in the winner zone
|
||||
const newDisplayVouchers = [
|
||||
...shuffledOthers.slice(0, 3),
|
||||
winner,
|
||||
...shuffledOthers.slice(3)
|
||||
];
|
||||
|
||||
return {
|
||||
...row,
|
||||
displayVouchers: newDisplayVouchers
|
||||
};
|
||||
});
|
||||
|
||||
// Update display to show arranged vouchers
|
||||
setSpinRows(arrangedRows);
|
||||
|
||||
// Start drum roll effect
|
||||
const drumRollInterval = setInterval(() => {
|
||||
playDrumRoll();
|
||||
}, 100);
|
||||
|
||||
// Create a scrolling/spinning effect for all wheels simultaneously
|
||||
let scrollSpeed = 50;
|
||||
let currentScroll = 0;
|
||||
const maxScroll = 2000;
|
||||
const deceleration = 0.95;
|
||||
|
||||
const spinInterval = setInterval(() => {
|
||||
currentScroll += scrollSpeed;
|
||||
scrollSpeed *= deceleration;
|
||||
|
||||
// Apply scrolling to all wheels
|
||||
arrangedRows.forEach(row => {
|
||||
const wheelElement = row.wheelRef.current;
|
||||
if (wheelElement) {
|
||||
wheelElement.style.transition = 'none';
|
||||
wheelElement.style.transform = `translateY(${-currentScroll}px)`;
|
||||
}
|
||||
});
|
||||
|
||||
// Stop when speed is very slow
|
||||
if (scrollSpeed < 0.5 || currentScroll >= maxScroll) {
|
||||
clearInterval(spinInterval);
|
||||
clearInterval(drumRollInterval);
|
||||
|
||||
// Final positioning - snap to winner position
|
||||
arrangedRows.forEach(row => {
|
||||
const wheelElement = row.wheelRef.current;
|
||||
if (wheelElement) {
|
||||
const CARD_HEIGHT = 80;
|
||||
const WINNER_ZONE_TOP = 260; // Top position of winner zone
|
||||
// Position 4th card (index 3) exactly at the winner zone
|
||||
const finalPosition = -(3 * CARD_HEIGHT - WINNER_ZONE_TOP);
|
||||
|
||||
wheelElement.style.transition = 'transform 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94)';
|
||||
wheelElement.style.transform = `translateY(${finalPosition}px)`;
|
||||
}
|
||||
});
|
||||
}
|
||||
}, 20);
|
||||
|
||||
// Wait for scrolling to complete
|
||||
await new Promise(resolve => setTimeout(resolve, 3000));
|
||||
|
||||
// Play winner sound
|
||||
playWinnerSound();
|
||||
|
||||
// Collect all winners
|
||||
const winnersToReveal: { row: SpinRow, winner: Voucher }[] = [];
|
||||
arrangedRows.forEach(row => {
|
||||
const winner = row.vouchers.find(v => v.is_winner);
|
||||
if (winner) {
|
||||
winnersToReveal.push({ row, winner });
|
||||
}
|
||||
});
|
||||
|
||||
// Update all winners at once with highlighting
|
||||
const allWinnerNumbers = new Set<number>();
|
||||
const historyEntries: WinnerHistory[] = [];
|
||||
|
||||
winnersToReveal.forEach(({ row, winner }) => {
|
||||
allWinnerNumbers.add(row.rowNumber);
|
||||
historyEntries.push({
|
||||
rowNumber: row.rowNumber,
|
||||
winner: winner,
|
||||
timestamp: new Date()
|
||||
});
|
||||
});
|
||||
|
||||
// Update state to highlight winners
|
||||
setRevealedWinners(allWinnerNumbers);
|
||||
|
||||
setSpinRows(prev => prev.map(r => {
|
||||
const winnerInfo = winnersToReveal.find(w => w.row.id === r.id);
|
||||
if (winnerInfo) {
|
||||
return {
|
||||
...r,
|
||||
winner: winnerInfo.winner,
|
||||
selectedWinner: winnerInfo.winner
|
||||
};
|
||||
}
|
||||
return r;
|
||||
}));
|
||||
|
||||
setWinnersHistory(prev => [...prev, ...historyEntries]);
|
||||
|
||||
setIsRevealingWinners(false);
|
||||
};
|
||||
|
||||
const performDramaticSpin = (row: SpinRow, isSequential: boolean = false) => {
|
||||
const wheelElement = row.wheelRef.current;
|
||||
if (!wheelElement) return;
|
||||
|
||||
const winner = row.vouchers.find(v => v.is_winner);
|
||||
if (!winner) {
|
||||
console.error('No winner found in vouchers');
|
||||
return;
|
||||
}
|
||||
|
||||
const CARD_HEIGHT = 80;
|
||||
const WINNER_ZONE_TOP = 260; // Top position of winner zone
|
||||
|
||||
// Shuffle the display vouchers to create more dramatic effect
|
||||
const shuffledVouchers = shuffleArray([...row.vouchers]);
|
||||
const winnerIndex = shuffledVouchers.findIndex(v => v.voucher_code === winner.voucher_code);
|
||||
|
||||
// Update display vouchers with shuffled order
|
||||
setSpinRows(prev => prev.map(r =>
|
||||
r.id === row.id ? { ...r, displayVouchers: shuffledVouchers } : r
|
||||
));
|
||||
|
||||
wheelElement.style.transition = 'none';
|
||||
wheelElement.style.transform = 'translateY(0px)';
|
||||
wheelElement.offsetHeight;
|
||||
|
||||
setTimeout(() => {
|
||||
// More dramatic spinning with multiple phases
|
||||
const minSpins = 15;
|
||||
const maxSpins = 25;
|
||||
const spins = minSpins + Math.random() * (maxSpins - minSpins);
|
||||
const totalItems = shuffledVouchers.length;
|
||||
|
||||
const totalRotations = Math.floor(spins);
|
||||
const baseScrollDistance = totalRotations * totalItems * CARD_HEIGHT;
|
||||
const winnerScrollPosition = winnerIndex * CARD_HEIGHT;
|
||||
const finalPosition = -(baseScrollDistance + winnerScrollPosition) + WINNER_ZONE_TOP;
|
||||
|
||||
const distance = Math.abs(finalPosition);
|
||||
const baseDuration = 4000; // Longer base duration
|
||||
const maxDuration = 7000; // Longer max duration
|
||||
const duration = Math.min(baseDuration + (distance / 8000) * 2000, maxDuration);
|
||||
|
||||
// Phase 1: Fast initial spin
|
||||
const phase1Duration = duration * 0.3;
|
||||
const phase1Distance = finalPosition * 0.7;
|
||||
|
||||
wheelElement.style.transform = `translateY(${phase1Distance}px)`;
|
||||
wheelElement.style.transition = `transform ${phase1Duration}ms cubic-bezier(0.25, 0.46, 0.45, 0.94)`;
|
||||
|
||||
// Phase 2: Slower approach to final position
|
||||
setTimeout(() => {
|
||||
wheelElement.style.transform = `translateY(${finalPosition}px)`;
|
||||
wheelElement.style.transition = `transform ${duration - phase1Duration}ms cubic-bezier(0.17, 0.67, 0.12, 0.99)`;
|
||||
}, phase1Duration);
|
||||
|
||||
startTickSound(row.id, duration);
|
||||
|
||||
setTimeout(() => {
|
||||
const interval = tickIntervalRefs.current.get(row.id);
|
||||
if (interval) {
|
||||
clearTimeout(interval);
|
||||
tickIntervalRefs.current.delete(row.id);
|
||||
}
|
||||
|
||||
playWinnerSound();
|
||||
|
||||
setSpinRows(prev => prev.map(r =>
|
||||
r.id === row.id
|
||||
? { ...r, isSpinning: false, winner: winner, selectedWinner: winner }
|
||||
: r
|
||||
));
|
||||
|
||||
setWinnersHistory(prev => [...prev, {
|
||||
rowNumber: row.rowNumber,
|
||||
winner: winner,
|
||||
timestamp: new Date()
|
||||
}]);
|
||||
|
||||
// If this is sequential spinning, trigger next row
|
||||
if (isSequential) {
|
||||
const nextRowIndex = spinRows.findIndex(r => r.id === row.id) + 1;
|
||||
if (nextRowIndex < spinRows.length) {
|
||||
setTimeout(() => {
|
||||
spinSequentialRow(nextRowIndex);
|
||||
}, 2000); // Wait 2 seconds before next spin
|
||||
} else {
|
||||
// All rows completed
|
||||
setIsSequentialSpinning(false);
|
||||
setCurrentSpinningRow(null);
|
||||
}
|
||||
}
|
||||
|
||||
// Keep the winner in the winner zone - don't reset position
|
||||
// The winning card will stay exactly where it landed in the winner zone
|
||||
|
||||
}, duration);
|
||||
}, 100);
|
||||
};
|
||||
|
||||
const performSpin = (row: SpinRow) => {
|
||||
const wheelElement = row.wheelRef.current;
|
||||
if (!wheelElement) return;
|
||||
|
||||
const winner = row.vouchers.find(v => v.is_winner);
|
||||
if (!winner) {
|
||||
console.error('No winner found in vouchers');
|
||||
return;
|
||||
}
|
||||
|
||||
const CARD_HEIGHT = 80;
|
||||
const WINNER_ZONE_TOP = 260; // Top position of winner zone
|
||||
|
||||
// Shuffle the display vouchers to create more dramatic effect
|
||||
const shuffledVouchers = shuffleArray([...row.vouchers]);
|
||||
const winnerIndex = shuffledVouchers.findIndex(v => v.voucher_code === winner.voucher_code);
|
||||
|
||||
// Update display vouchers with shuffled order
|
||||
setSpinRows(prev => prev.map(r =>
|
||||
r.id === row.id ? { ...r, displayVouchers: shuffledVouchers } : r
|
||||
));
|
||||
|
||||
wheelElement.style.transition = 'none';
|
||||
wheelElement.style.transform = 'translateY(0px)';
|
||||
wheelElement.offsetHeight;
|
||||
|
||||
setTimeout(() => {
|
||||
// More dramatic spinning with multiple phases
|
||||
const minSpins = 15;
|
||||
const maxSpins = 25;
|
||||
const spins = minSpins + Math.random() * (maxSpins - minSpins);
|
||||
const totalItems = shuffledVouchers.length;
|
||||
|
||||
const totalRotations = Math.floor(spins);
|
||||
const baseScrollDistance = totalRotations * totalItems * CARD_HEIGHT;
|
||||
const winnerScrollPosition = winnerIndex * CARD_HEIGHT;
|
||||
const finalPosition = -(baseScrollDistance + winnerScrollPosition) + WINNER_ZONE_TOP;
|
||||
|
||||
const distance = Math.abs(finalPosition);
|
||||
const baseDuration = 4000; // Longer base duration
|
||||
const maxDuration = 7000; // Longer max duration
|
||||
const duration = Math.min(baseDuration + (distance / 8000) * 2000, maxDuration);
|
||||
|
||||
// Phase 1: Fast initial spin
|
||||
const phase1Duration = duration * 0.3;
|
||||
const phase1Distance = finalPosition * 0.7;
|
||||
|
||||
wheelElement.style.transform = `translateY(${phase1Distance}px)`;
|
||||
wheelElement.style.transition = `transform ${phase1Duration}ms cubic-bezier(0.25, 0.46, 0.45, 0.94)`;
|
||||
|
||||
// Phase 2: Slower approach to final position
|
||||
setTimeout(() => {
|
||||
wheelElement.style.transform = `translateY(${finalPosition}px)`;
|
||||
wheelElement.style.transition = `transform ${duration - phase1Duration}ms cubic-bezier(0.17, 0.67, 0.12, 0.99)`;
|
||||
}, phase1Duration);
|
||||
|
||||
startTickSound(row.id, duration);
|
||||
|
||||
setTimeout(() => {
|
||||
const interval = tickIntervalRefs.current.get(row.id);
|
||||
if (interval) {
|
||||
clearTimeout(interval);
|
||||
tickIntervalRefs.current.delete(row.id);
|
||||
}
|
||||
|
||||
playWinnerSound();
|
||||
|
||||
setSpinRows(prev => prev.map(r =>
|
||||
r.id === row.id
|
||||
? { ...r, isSpinning: false, winner: winner, selectedWinner: winner }
|
||||
: r
|
||||
));
|
||||
|
||||
setWinnersHistory(prev => [...prev, {
|
||||
rowNumber: row.rowNumber,
|
||||
winner: winner,
|
||||
timestamp: new Date()
|
||||
}]);
|
||||
|
||||
// Keep the winner in the winner zone - don't reset position
|
||||
// The winning card will stay exactly where it landed in the winner zone
|
||||
|
||||
}, duration);
|
||||
}, 100);
|
||||
};
|
||||
|
||||
const spinSequentialRow = (rowIndex: number) => {
|
||||
if (rowIndex >= spinRows.length) {
|
||||
setIsSequentialSpinning(false);
|
||||
setCurrentSpinningRow(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const row = spinRows[rowIndex];
|
||||
if (!row || row.isSpinning || row.winner) {
|
||||
// Skip this row and go to next
|
||||
spinSequentialRow(rowIndex + 1);
|
||||
return;
|
||||
}
|
||||
|
||||
setCurrentSpinningRow(row.rowNumber);
|
||||
setSpinRows(prev => prev.map(r =>
|
||||
r.id === row.id ? { ...r, isSpinning: true, selectedWinner: null } : r
|
||||
));
|
||||
|
||||
const wheelElement = row.wheelRef.current;
|
||||
if (wheelElement) {
|
||||
wheelElement.style.transition = 'none';
|
||||
wheelElement.style.transform = 'translateY(0px)';
|
||||
wheelElement.offsetHeight;
|
||||
}
|
||||
|
||||
performDramaticSpin(row, true);
|
||||
};
|
||||
|
||||
const startSequentialSpinning = () => {
|
||||
if (spinRows.length === 0) return;
|
||||
|
||||
// Clear any existing results
|
||||
setWinnersHistory([]);
|
||||
setRevealedWinners(new Set());
|
||||
setSpinRows(prev => prev.map(row => ({
|
||||
...row,
|
||||
isSpinning: false,
|
||||
isShuffling: false,
|
||||
winner: null,
|
||||
selectedWinner: null,
|
||||
displayVouchers: [...row.vouchers]
|
||||
})));
|
||||
|
||||
// Reset all wheel positions
|
||||
spinRows.forEach(row => {
|
||||
const wheelElement = row.wheelRef.current;
|
||||
if (wheelElement) {
|
||||
wheelElement.style.transition = 'none';
|
||||
wheelElement.style.transform = 'translateY(0px)';
|
||||
}
|
||||
});
|
||||
|
||||
setIsSequentialSpinning(true);
|
||||
setCurrentSpinningRow(null);
|
||||
|
||||
// Start with first row after a short delay
|
||||
setTimeout(() => {
|
||||
spinSequentialRow(0);
|
||||
}, 500);
|
||||
};
|
||||
|
||||
const spinWheel = (rowId: string) => {
|
||||
const row = spinRows.find(r => r.id === rowId);
|
||||
if (!row || row.isSpinning || row.winner) return;
|
||||
|
||||
setSpinRows(prev => prev.map(r =>
|
||||
r.id === rowId ? { ...r, isSpinning: true, selectedWinner: null } : r
|
||||
));
|
||||
|
||||
const wheelElement = row.wheelRef.current;
|
||||
if (wheelElement) {
|
||||
wheelElement.style.transition = 'none';
|
||||
wheelElement.style.transform = 'translateY(0px)';
|
||||
wheelElement.offsetHeight;
|
||||
}
|
||||
|
||||
performSpin(row);
|
||||
};
|
||||
|
||||
const clearResults = () => {
|
||||
tickIntervalRefs.current.forEach(timeout => clearTimeout(timeout));
|
||||
shuffleIntervalRefs.current.forEach(timeout => clearTimeout(timeout));
|
||||
tickIntervalRefs.current.clear();
|
||||
shuffleIntervalRefs.current.clear();
|
||||
|
||||
setWinnersHistory([]);
|
||||
setRevealedWinners(new Set());
|
||||
setIsSequentialSpinning(false);
|
||||
setCurrentSpinningRow(null);
|
||||
setSpinRows(prev => prev.map(row => ({
|
||||
...row,
|
||||
isSpinning: false,
|
||||
isShuffling: false,
|
||||
winner: null,
|
||||
selectedWinner: null,
|
||||
displayVouchers: [...row.vouchers]
|
||||
})));
|
||||
|
||||
spinRows.forEach(row => {
|
||||
const wheelElement = row.wheelRef.current;
|
||||
if (wheelElement) {
|
||||
wheelElement.style.transition = 'none';
|
||||
wheelElement.style.transform = 'translateY(0px)';
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const refreshData = async () => {
|
||||
tickIntervalRefs.current.forEach(timeout => clearTimeout(timeout));
|
||||
shuffleIntervalRefs.current.forEach(timeout => clearTimeout(timeout));
|
||||
tickIntervalRefs.current.clear();
|
||||
shuffleIntervalRefs.current.clear();
|
||||
|
||||
try {
|
||||
await refetchVouchers();
|
||||
toast.success('Data refreshed successfully');
|
||||
} catch (error) {
|
||||
toast.error('Failed to refresh data');
|
||||
}
|
||||
};
|
||||
|
||||
const formatPhoneNumber = (phone: string) => {
|
||||
return phone.substring(0, 5) + '****' + phone.substring(phone.length - 2);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 text-gray-900 p-6">
|
||||
<style jsx>{`
|
||||
@keyframes bounce-in {
|
||||
0% {
|
||||
transform: scale(0.3);
|
||||
opacity: 0;
|
||||
}
|
||||
50% {
|
||||
transform: scale(1.05);
|
||||
}
|
||||
70% {
|
||||
transform: scale(0.9);
|
||||
}
|
||||
100% {
|
||||
transform: scale(1);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.animate-bounce-in {
|
||||
animation: bounce-in 0.6s ease-out;
|
||||
}
|
||||
`}</style>
|
||||
|
||||
<div className="max-w-full px-4 mx-auto">
|
||||
{/* Header */}
|
||||
<div className="text-center mb-8">
|
||||
<h1 className="text-5xl font-bold bg-gradient-to-r from-primary to-purple-600 bg-clip-text text-transparent mb-2">
|
||||
Voucher Lucky Draw
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* Controls Section - Compact Layout */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-3">
|
||||
{/* Configuration Card */}
|
||||
<div className="bg-white rounded-lg p-4 border border-gray-200 shadow-sm">
|
||||
<h2 className="text-lg font-semibold mb-3 text-gray-900">
|
||||
Configuration
|
||||
</h2>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-gray-700 mb-1">
|
||||
Number of Rows
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
max="10"
|
||||
value={numberOfRows}
|
||||
onChange={(e) => setNumberOfRows(parseInt(e.target.value) || 1)}
|
||||
className="w-full bg-white border border-gray-300 rounded p-1.5 text-sm text-gray-900 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20"
|
||||
disabled={isLoadingData}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-gray-700 mb-1">
|
||||
Prize Selection
|
||||
</label>
|
||||
<select
|
||||
value={selectedPrize}
|
||||
onChange={(e) => setSelectedPrize(parseInt(e.target.value))}
|
||||
className="w-full bg-white border border-gray-300 rounded p-1.5 text-sm text-gray-900 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20"
|
||||
disabled={isLoadingData}
|
||||
>
|
||||
<option value={1}>🥇 Emas 0.25 Gram</option>
|
||||
<option value={2}>🥇 Emas 3 Gram</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={refreshData}
|
||||
disabled={isLoadingData}
|
||||
className="w-full px-3 py-1.5 bg-primary hover:bg-primary/90 disabled:bg-gray-400 text-white text-sm font-semibold rounded flex items-center justify-center gap-1 transition-colors"
|
||||
>
|
||||
<RefreshCw size={14} className={isLoadingData ? 'animate-spin' : ''} />
|
||||
{isLoadingData ? 'Loading...' : 'Load Data'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{spinRows.length > 0 && (
|
||||
<div className="mt-3 p-2 bg-gray-50 rounded text-xs text-gray-600">
|
||||
<div>Rows: {spinRows.length} | Vouchers: {spinRows.reduce((acc, row) => acc + row.vouchers.length, 0)}</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Actions Card */}
|
||||
<div className="bg-white rounded-lg p-4 border border-gray-200 shadow-sm">
|
||||
<h2 className="text-lg font-semibold mb-3 text-gray-900">
|
||||
Actions
|
||||
</h2>
|
||||
|
||||
<div className="space-y-2">
|
||||
<button
|
||||
onClick={shuffleAllRows}
|
||||
disabled={isLoadingData || spinRows.some(r => r.isShuffling) || spinRows.length === 0}
|
||||
className="w-full px-3 py-1.5 bg-purple-600 hover:bg-purple-700 disabled:bg-gray-400 text-white text-sm font-semibold rounded flex items-center justify-center gap-1 transition-colors"
|
||||
>
|
||||
<Shuffle size={14} className={spinRows.some(r => r.isShuffling) ? 'animate-pulse' : ''} />
|
||||
Shuffle All
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={startSequentialSpinning}
|
||||
disabled={isSequentialSpinning || spinRows.length === 0}
|
||||
className="w-full px-3 py-1.5 bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 disabled:from-gray-400 disabled:to-gray-500 text-white text-sm font-bold rounded flex items-center justify-center gap-1 transition-all"
|
||||
>
|
||||
<Trophy size={14} className={isSequentialSpinning ? 'animate-spin' : ''} />
|
||||
{isSequentialSpinning ? 'Spinning...' : 'Spin for Winner'}
|
||||
</button>
|
||||
|
||||
{winnersHistory.length > 0 && (
|
||||
<button
|
||||
onClick={clearResults}
|
||||
className="w-full px-3 py-1.5 bg-red-600 hover:bg-red-700 text-white text-sm font-semibold rounded flex items-center justify-center gap-1 transition-colors"
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
Clear Results
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Winners Summary Card */}
|
||||
<div className="bg-white rounded-lg p-4 border border-gray-200 shadow-sm">
|
||||
<h2 className="text-lg font-semibold mb-3 text-gray-900 flex items-center gap-2">
|
||||
<Trophy className="text-yellow-500" size={18} />
|
||||
Winners
|
||||
</h2>
|
||||
|
||||
{winnersHistory.length > 0 ? (
|
||||
<div className="space-y-1 max-h-32 overflow-y-auto">
|
||||
{winnersHistory.map((history) => (
|
||||
<div
|
||||
key={`${history.rowNumber}-${history.timestamp.getTime()}`}
|
||||
className="p-1.5 bg-yellow-50 border border-yellow-200 rounded text-xs"
|
||||
>
|
||||
<div className="font-semibold text-yellow-700">
|
||||
Row {history.rowNumber}: {history.winner.name}
|
||||
</div>
|
||||
<div className="text-xs text-yellow-600">
|
||||
{history.winner.voucher_code}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center py-2">
|
||||
<Trophy className="mx-auto text-gray-300 mb-1" size={20} />
|
||||
<p className="text-gray-500 text-xs">No winners yet</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Spin Rows - Display in grid */}
|
||||
<div className={`grid gap-4 ${
|
||||
spinRows.length === 1 ? 'grid-cols-1' :
|
||||
spinRows.length === 2 ? 'grid-cols-1 lg:grid-cols-2' :
|
||||
spinRows.length === 3 ? 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3' :
|
||||
spinRows.length === 4 ? 'grid-cols-1 md:grid-cols-2 xl:grid-cols-4' :
|
||||
spinRows.length === 5 ? 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5' :
|
||||
'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4'
|
||||
}`}>
|
||||
{spinRows.map((row) => (
|
||||
<div key={row.id} className={`bg-white rounded-lg border-2 shadow-sm transition-all ${
|
||||
row.isShuffling ? 'border-purple-400 animate-pulse' : 'border-gray-200'
|
||||
}`}>
|
||||
<div className="p-4 border-b border-gray-200">
|
||||
|
||||
{row.winner && (
|
||||
<div className="mt-2 p-2 bg-yellow-50 border border-yellow-200 rounded-lg animate-bounce-in">
|
||||
<div className="flex items-center gap-1 text-sm">
|
||||
<Trophy className="text-yellow-500" size={16} />
|
||||
<span className="font-semibold text-yellow-700 truncate">
|
||||
{row.winner.name}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-xs text-yellow-600 mt-1">
|
||||
{row.winner.voucher_code}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Wheel Container */}
|
||||
<div
|
||||
className="relative bg-gray-50 overflow-hidden"
|
||||
style={{ height: '600px' }}
|
||||
>
|
||||
{/* Subtle Winner Zone Indicator */}
|
||||
<div
|
||||
className="absolute left-0 right-0 z-10 pointer-events-none"
|
||||
style={{
|
||||
top: '260px',
|
||||
height: '80px',
|
||||
background: 'linear-gradient(90deg, transparent 0%, rgba(34, 197, 94, 0.1) 20%, rgba(34, 197, 94, 0.2) 50%, rgba(34, 197, 94, 0.1) 80%, transparent 100%)',
|
||||
borderTop: '2px dashed rgba(34, 197, 94, 0.3)',
|
||||
borderBottom: '2px dashed rgba(34, 197, 94, 0.3)'
|
||||
}}
|
||||
>
|
||||
<div className="absolute right-2 top-1/2 transform -translate-y-1/2">
|
||||
<div className="bg-green-500 text-white px-2 py-1 rounded text-xs font-bold shadow-lg">
|
||||
🏆 WINNER
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Scrolling Cards */}
|
||||
<div
|
||||
ref={row.wheelRef}
|
||||
className="absolute inset-0"
|
||||
style={{ transform: 'translateY(0px)' }}
|
||||
>
|
||||
{Array.from({ length: 50 }, (_, repeatIndex) =>
|
||||
row.displayVouchers.map((voucher, voucherIndex) => {
|
||||
const isSelectedWinner = row.selectedWinner?.voucher_code === voucher.voucher_code;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={`${repeatIndex}-${voucherIndex}`}
|
||||
className={`flex items-center px-4 border-b border-gray-300 transition-all duration-300 ${
|
||||
isSelectedWinner
|
||||
? 'bg-gradient-to-r from-yellow-100 to-yellow-200 border-yellow-300 shadow-lg'
|
||||
: voucherIndex % 2 === 0
|
||||
? 'bg-white hover:bg-gray-50'
|
||||
: 'bg-gray-50 hover:bg-gray-100'
|
||||
}`}
|
||||
style={{
|
||||
height: '80px',
|
||||
minHeight: '80px',
|
||||
maxHeight: '80px',
|
||||
boxSizing: 'border-box'
|
||||
}}
|
||||
>
|
||||
<div className="flex-1">
|
||||
<div className={`font-bold text-lg mb-1 ${
|
||||
isSelectedWinner ? 'text-yellow-600' : 'text-gray-900'
|
||||
}`}>
|
||||
{voucher.voucher_code}
|
||||
</div>
|
||||
<div className={`text-sm ${
|
||||
isSelectedWinner ? 'text-yellow-700' : 'text-gray-600'
|
||||
}`}>
|
||||
{voucher.name}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="text-right">
|
||||
<div className="text-gray-500 text-xs">
|
||||
{formatPhoneNumber(voucher.phone_number)}
|
||||
</div>
|
||||
{isSelectedWinner && (
|
||||
<Trophy className="inline ml-2 text-yellow-500" size={16} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Gradient Overlays */}
|
||||
<div className="absolute top-0 left-0 right-0 h-32 bg-gradient-to-b from-gray-50 via-gray-50/70 to-transparent pointer-events-none z-40"></div>
|
||||
<div className="absolute bottom-0 left-0 right-0 h-32 bg-gradient-to-t from-gray-50 via-gray-50/70 to-transparent pointer-events-none z-40"></div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default RandomDrawApp;
|
||||
@@ -0,0 +1,7 @@
|
||||
import AccountList from '@/views/apps/account'
|
||||
|
||||
const AccountPage = () => {
|
||||
return <AccountList />
|
||||
}
|
||||
|
||||
export default AccountPage
|
||||
@@ -0,0 +1,7 @@
|
||||
import CashBankDetail from '@/views/apps/cash-bank/detail'
|
||||
|
||||
const CashBankDetailPage = () => {
|
||||
return <CashBankDetail />
|
||||
}
|
||||
|
||||
export default CashBankDetailPage
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
import CashBankDetailTransactionContent from '@/views/apps/cash-bank/detail/transaction/CashBankDetailTransactionContent'
|
||||
import CashBankDetailTransactionHeader from '@/views/apps/cash-bank/detail/transaction/CashBankDetailTransactionHeader'
|
||||
import Grid from '@mui/material/Grid2'
|
||||
|
||||
const TransactionPage = () => {
|
||||
return (
|
||||
<Grid container spacing={6}>
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<CashBankDetailTransactionHeader title='Giro 1-10003' transaction='Terima Pembayaran Tagihan' />
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<CashBankDetailTransactionContent />
|
||||
</Grid>
|
||||
</Grid>
|
||||
)
|
||||
}
|
||||
|
||||
export default TransactionPage
|
||||
@@ -0,0 +1,18 @@
|
||||
import FixedAssetAddForm from '@/views/apps/fixed-assets/add/FixedAssetAddForm'
|
||||
import FixedAssetAddHeader from '@/views/apps/fixed-assets/add/FixedAssetAddHeader'
|
||||
import Grid from '@mui/material/Grid2'
|
||||
|
||||
const FixedAssetPage = () => {
|
||||
return (
|
||||
<Grid container spacing={6}>
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<FixedAssetAddHeader />
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<FixedAssetAddForm />
|
||||
</Grid>
|
||||
</Grid>
|
||||
)
|
||||
}
|
||||
|
||||
export default FixedAssetPage
|
||||
@@ -0,0 +1,7 @@
|
||||
import FixedAssetList from '@/views/apps/fixed-assets'
|
||||
|
||||
const FixedAssetPage = () => {
|
||||
return <FixedAssetList />
|
||||
}
|
||||
|
||||
export default FixedAssetPage
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import IngredientDetail from '@/views/apps/ecommerce/products/ingredient/detail'
|
||||
|
||||
const IngredientDetailPage = () => {
|
||||
return <IngredientDetail />
|
||||
}
|
||||
|
||||
export default IngredientDetailPage
|
||||
@@ -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
|
||||
@@ -0,0 +1,22 @@
|
||||
import ReportTitle from '@/components/report/ReportTitle'
|
||||
import ReportCashFlowCard from '@/views/apps/report/cash-flow/ReportCashFlowCard'
|
||||
import ReportCashFlowContent from '@/views/apps/report/cash-flow/ReportCashFlowContent'
|
||||
import Grid from '@mui/material/Grid2'
|
||||
|
||||
const CashFlowPage = () => {
|
||||
return (
|
||||
<Grid container spacing={6}>
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<ReportTitle title='Arus Kas' />
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<ReportCashFlowCard />
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<ReportCashFlowContent />
|
||||
</Grid>
|
||||
</Grid>
|
||||
)
|
||||
}
|
||||
|
||||
export default CashFlowPage
|
||||
@@ -0,0 +1,22 @@
|
||||
import ReportTitle from '@/components/report/ReportTitle'
|
||||
import ReportNeracaCard from '@/views/apps/report/neraca/ReportNeracaCard'
|
||||
import ReportNeracaContent from '@/views/apps/report/neraca/ReportNeracaContent'
|
||||
import Grid from '@mui/material/Grid2'
|
||||
|
||||
const NeracaPage = () => {
|
||||
return (
|
||||
<Grid container spacing={6}>
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<ReportTitle title='Neraca' />
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<ReportNeracaCard />
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<ReportNeracaContent />
|
||||
</Grid>
|
||||
</Grid>
|
||||
)
|
||||
}
|
||||
|
||||
export default NeracaPage
|
||||
@@ -0,0 +1,7 @@
|
||||
import ReportList from '@/views/apps/report'
|
||||
|
||||
const ReportPage = () => {
|
||||
return <ReportList />
|
||||
}
|
||||
|
||||
export default ReportPage
|
||||
@@ -0,0 +1,22 @@
|
||||
import ReportTitle from '@/components/report/ReportTitle'
|
||||
import ReportProfitLossCard from '@/views/apps/report/profit-loss/ReportProfitLossCard'
|
||||
import ReportProfitLossContent from '@/views/apps/report/profit-loss/ReportProfitLossContent'
|
||||
import Grid from '@mui/material/Grid2'
|
||||
|
||||
const ProfiltLossPage = () => {
|
||||
return (
|
||||
<Grid container spacing={6}>
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<ReportTitle title='Laba Rugi' />
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<ReportProfitLossCard />
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<ReportProfitLossContent />
|
||||
</Grid>
|
||||
</Grid>
|
||||
)
|
||||
}
|
||||
|
||||
export default ProfiltLossPage
|
||||
@@ -8,23 +8,63 @@ import {
|
||||
useCategoryAnalytics
|
||||
} from '@/services/queries/analytics'
|
||||
import { useOutletById } from '@/services/queries/outlets'
|
||||
import { generateExcel } from '@/utils/excelGenerator'
|
||||
import { generatePDF } from '@/utils/pdfGenerator'
|
||||
import { formatCurrency, formatDate, formatDateDDMMYYYY, formatDatetime } from '@/utils/transform'
|
||||
import ReportGeneratorComponent from '@/views/dashboards/daily-report/report-generator'
|
||||
import ReportHeader from '@/views/dashboards/daily-report/report-header'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
|
||||
// Dummy HPP values — ganti dengan data real nantinya
|
||||
const DUMMY_STD_HPP = 30 // % — ganti dengan data real nantinya
|
||||
const DUMMY_REAL_HPP = 0 // % — ganti dengan kalkulasi real nantinya
|
||||
|
||||
const getHppStatus = (stdHpp: number, realHpp: number): 'Sehat' | 'Tidak Sehat' =>
|
||||
realHpp <= stdHpp ? 'Sehat' : 'Tidak Sehat'
|
||||
|
||||
const StatusBadge = ({ status }: { status: 'Sehat' | 'Tidak Sehat' }) => (
|
||||
<span
|
||||
className={`inline-block px-3 py-1 rounded-full text-base font-bold ${
|
||||
status === 'Sehat' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
|
||||
}`}
|
||||
>
|
||||
{status}
|
||||
</span>
|
||||
)
|
||||
|
||||
const DailyPOSReport = () => {
|
||||
const reportRef = useRef<HTMLDivElement | null>(null)
|
||||
|
||||
const [isGeneratingExcel, setIsGeneratingExcel] = useState(false)
|
||||
|
||||
const [now, setNow] = useState(new Date())
|
||||
const [selectedDate, setSelectedDate] = useState(new Date())
|
||||
const [dateRange, setDateRange] = useState({
|
||||
startDate: new Date(),
|
||||
endDate: new Date()
|
||||
})
|
||||
const [filterType, setFilterType] = useState<'single' | 'range'>('single') // 'single' or 'range'
|
||||
const [filterType, setFilterType] = useState<'single' | 'range'>('single')
|
||||
const [isGeneratingPDF, setIsGeneratingPDF] = useState(false)
|
||||
|
||||
// PDF Font Size Configuration
|
||||
const PDF_FONT_SIZES = {
|
||||
heading: 18,
|
||||
subheading: 16,
|
||||
tableContent: 12,
|
||||
tableHeader: 12,
|
||||
tableFooter: 12,
|
||||
grandTotal: 14,
|
||||
footer: 11
|
||||
}
|
||||
|
||||
// PDF Spacing Configuration
|
||||
const PDF_SPACING = {
|
||||
cellPadding: 5,
|
||||
cellPaddingLarge: 6,
|
||||
sectionGap: 20,
|
||||
headerGap: 15
|
||||
}
|
||||
|
||||
// Use selectedDate for single date filter, or dateRange for range filter
|
||||
const getDateParams = () => {
|
||||
if (filterType === 'single') {
|
||||
return {
|
||||
@@ -41,8 +81,15 @@ const DailyPOSReport = () => {
|
||||
|
||||
const dateParams = getDateParams()
|
||||
|
||||
const today = new Date()
|
||||
const sevenDaysAgo = new Date()
|
||||
sevenDaysAgo.setDate(today.getDate() - 7)
|
||||
|
||||
const { data: outlet } = useOutletById()
|
||||
const { data: sales } = useSalesAnalytics(dateParams)
|
||||
const { data: profitLoss7Days } = useProfitLossAnalytics({
|
||||
date_from: formatDateDDMMYYYY(sevenDaysAgo),
|
||||
date_to: formatDateDDMMYYYY(today)
|
||||
})
|
||||
const { data: profitLoss } = useProfitLossAnalytics(dateParams)
|
||||
const { data: products } = useProductSalesAnalytics(dateParams)
|
||||
const { data: paymentAnalytics } = usePaymentAnalytics(dateParams)
|
||||
@@ -54,14 +101,6 @@ const DailyPOSReport = () => {
|
||||
totalOrders: products?.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0
|
||||
}
|
||||
|
||||
// Calculate profit loss product summary
|
||||
const profitLossProductSummary = {
|
||||
totalRevenue: profitLoss?.product_data?.reduce((sum, item) => sum + (item?.revenue || 0), 0) || 0,
|
||||
totalCost: profitLoss?.product_data?.reduce((sum, item) => sum + (item?.cost || 0), 0) || 0,
|
||||
totalGrossProfit: profitLoss?.product_data?.reduce((sum, item) => sum + (item?.gross_profit || 0), 0) || 0,
|
||||
totalQuantity: profitLoss?.product_data?.reduce((sum, item) => sum + (item?.quantity_sold || 0), 0) || 0
|
||||
}
|
||||
|
||||
const categorySummary = {
|
||||
totalRevenue: category?.data?.reduce((sum, item) => sum + (item?.total_revenue || 0), 0) || 0,
|
||||
orderCount: category?.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0,
|
||||
@@ -73,12 +112,10 @@ const DailyPOSReport = () => {
|
||||
setNow(new Date())
|
||||
}, [])
|
||||
|
||||
// Format date for input field (YYYY-MM-DD)
|
||||
const formatDateForInput = (date: Date) => {
|
||||
return date.toISOString().split('T')[0]
|
||||
}
|
||||
|
||||
// Get display text for the report period
|
||||
const getReportPeriodText = () => {
|
||||
if (filterType === 'single') {
|
||||
return `${formatDateDDMMYYYY(selectedDate)} - ${formatDateDDMMYYYY(selectedDate)}`
|
||||
@@ -87,98 +124,107 @@ const DailyPOSReport = () => {
|
||||
}
|
||||
}
|
||||
|
||||
// Get report title based on filter type
|
||||
const getReportTitle = () => {
|
||||
if (filterType === 'single') {
|
||||
return 'Laporan Transaksi'
|
||||
} else {
|
||||
const daysDiff = Math.ceil((dateRange.endDate.getTime() - dateRange.startDate.getTime()) / (1000 * 3600 * 24)) + 1
|
||||
// return `Laporan Transaksi ${daysDiff} Hari`
|
||||
return `Laporan Transaksi`
|
||||
}
|
||||
return 'Laporan Transaksi'
|
||||
}
|
||||
|
||||
const handleGeneratePDF = async () => {
|
||||
const reportElement = reportRef.current
|
||||
|
||||
setIsGeneratingPDF(true)
|
||||
try {
|
||||
// Import jsPDF dan html2canvas
|
||||
const jsPDF = (await import('jspdf')).default
|
||||
const html2canvas = (await import('html2canvas')).default
|
||||
|
||||
// Optimized canvas capture dengan scale lebih rendah
|
||||
const canvas = await html2canvas(reportElement!, {
|
||||
scale: 1.5, // Reduced from 2 to 1.5
|
||||
useCORS: true,
|
||||
allowTaint: true,
|
||||
backgroundColor: '#ffffff',
|
||||
logging: false, // Disable logging for performance
|
||||
removeContainer: true, // Clean up after capture
|
||||
imageTimeout: 0, // No timeout for image loading
|
||||
height: reportElement!.scrollHeight,
|
||||
width: reportElement!.scrollWidth
|
||||
await generatePDF({
|
||||
reportRef,
|
||||
outlet,
|
||||
profitLoss,
|
||||
products,
|
||||
paymentAnalytics,
|
||||
category,
|
||||
productSummary,
|
||||
categorySummary,
|
||||
filterType,
|
||||
selectedDate,
|
||||
dateRange,
|
||||
now
|
||||
})
|
||||
|
||||
// Compress canvas using JPEG with quality setting
|
||||
const imgData = canvas.toDataURL('image/jpeg', 0.85) // JPEG with 85% quality instead of PNG
|
||||
|
||||
// Create PDF with compression
|
||||
const pdf = new jsPDF({
|
||||
orientation: 'portrait',
|
||||
unit: 'mm',
|
||||
format: 'a4',
|
||||
compress: true // Enable built-in compression
|
||||
})
|
||||
|
||||
const imgWidth = 210
|
||||
const pageHeight = 295
|
||||
const imgHeight = (canvas.height * imgWidth) / canvas.width
|
||||
let heightLeft = imgHeight
|
||||
let position = 0
|
||||
|
||||
// Add first page with compressed image
|
||||
pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight, '', 'FAST') // Use FAST compression
|
||||
heightLeft -= pageHeight
|
||||
|
||||
// Handle multiple pages if needed
|
||||
while (heightLeft >= 0) {
|
||||
position = heightLeft - imgHeight
|
||||
pdf.addPage()
|
||||
pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight, '', 'FAST')
|
||||
heightLeft -= pageHeight
|
||||
}
|
||||
|
||||
// Additional compression options
|
||||
pdf.setProperties({
|
||||
title: `${getReportTitle()}`,
|
||||
subject: 'Daily Transaction Report',
|
||||
author: 'Apskel POS System',
|
||||
creator: 'Apskel'
|
||||
})
|
||||
|
||||
// Save with optimized settings
|
||||
const fileName =
|
||||
filterType === 'single'
|
||||
? `laporan-transaksi-${formatDateForInput(selectedDate)}.pdf`
|
||||
: `laporan-transaksi-${formatDateForInput(dateRange.startDate)}-to-${formatDateForInput(dateRange.endDate)}.pdf`
|
||||
|
||||
pdf.save(fileName, {
|
||||
returnPromise: true
|
||||
})
|
||||
|
||||
// Clean up canvas to free memory
|
||||
canvas.width = canvas.height = 0
|
||||
} catch (error) {
|
||||
console.error('Error generating PDF:', error)
|
||||
alert('Terjadi kesalahan saat membuat PDF. Pastikan jsPDF dan html2canvas sudah terinstall.')
|
||||
alert(`Terjadi kesalahan saat membuat PDF: ${error}`)
|
||||
} finally {
|
||||
setIsGeneratingPDF(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleGenerateExcel = async () => {
|
||||
setIsGeneratingExcel(true)
|
||||
try {
|
||||
await generateExcel({
|
||||
outlet,
|
||||
profitLoss,
|
||||
products,
|
||||
paymentAnalytics,
|
||||
category,
|
||||
productSummary,
|
||||
categorySummary,
|
||||
filterType,
|
||||
selectedDate,
|
||||
dateRange
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Error generating Excel:', error)
|
||||
alert(`Terjadi kesalahan saat membuat Excel: ${error}`)
|
||||
} finally {
|
||||
setIsGeneratingExcel(false)
|
||||
}
|
||||
}
|
||||
|
||||
const LoadingOverlay = ({ isVisible, message = 'Generating PDF...' }: { isVisible: boolean; message?: string }) => {
|
||||
if (!isVisible) return null
|
||||
|
||||
return (
|
||||
<div className='fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 backdrop-blur-sm'>
|
||||
<div className='bg-white rounded-lg shadow-xl p-8 max-w-sm w-full mx-4'>
|
||||
<div className='text-center'>
|
||||
<div className='inline-block animate-spin rounded-full h-12 w-12 border-4 border-gray-200 border-t-purple-600 mb-4'></div>
|
||||
<h3 className='text-lg font-semibold text-gray-800 mb-2'>{message}</h3>
|
||||
<p className='text-sm text-gray-600'>Mohon tunggu, proses ini mungkin membutuhkan beberapa detik...</p>
|
||||
<div className='mt-6 space-y-2'>
|
||||
<div className='flex items-center text-xs text-gray-500'>
|
||||
<div className='w-2 h-2 bg-green-500 rounded-full mr-2 flex-shrink-0'></div>
|
||||
<span>Capturing report content</span>
|
||||
</div>
|
||||
<div className='flex items-center text-xs text-gray-500'>
|
||||
<div className='w-2 h-2 bg-blue-500 rounded-full mr-2 flex-shrink-0 animate-pulse'></div>
|
||||
<span>Processing pages</span>
|
||||
</div>
|
||||
<div className='flex items-center text-xs text-gray-500'>
|
||||
<div className='w-2 h-2 bg-gray-300 rounded-full mr-2 flex-shrink-0'></div>
|
||||
<span>Finalizing PDF</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Group products by category
|
||||
const groupedProducts =
|
||||
products?.data?.reduce(
|
||||
(acc, item) => {
|
||||
const categoryName = item.category_name || 'Tidak Berkategori'
|
||||
if (!acc[categoryName]) {
|
||||
acc[categoryName] = []
|
||||
}
|
||||
acc[categoryName].push(item)
|
||||
return acc
|
||||
},
|
||||
{} as Record<string, any[]>
|
||||
) || {}
|
||||
|
||||
return (
|
||||
<div className='min-h-screen'>
|
||||
{/* Control Panel */}
|
||||
<LoadingOverlay isVisible={isGeneratingPDF} message='Membuat PDF Laporan...' />
|
||||
|
||||
<ReportGeneratorComponent
|
||||
// Props wajib
|
||||
reportTitle='Laporan Penjualan'
|
||||
filterType={filterType}
|
||||
selectedDate={selectedDate}
|
||||
@@ -187,161 +233,99 @@ const DailyPOSReport = () => {
|
||||
onSingleDateChange={setSelectedDate}
|
||||
onDateRangeChange={setDateRange}
|
||||
onGeneratePDF={handleGeneratePDF}
|
||||
// Props opsional
|
||||
// isGenerating={isGenerating}
|
||||
// customQuickActions={customQuickActions}
|
||||
// labels={customLabels}
|
||||
onGenerateExcel={handleGenerateExcel}
|
||||
isGeneratingExcel={isGeneratingExcel}
|
||||
/>
|
||||
|
||||
{/* Report Template */}
|
||||
<div ref={reportRef} className='max-w-4xl mx-auto bg-white min-h-[297mm]' style={{ width: '210mm' }}>
|
||||
{/* Header */}
|
||||
<ReportHeader
|
||||
outlet={outlet}
|
||||
reportTitle={getReportTitle()}
|
||||
reportSubtitle='Laporan Bulanan'
|
||||
brandName='Apskel'
|
||||
brandColor='#36175e'
|
||||
periode={getReportPeriodText()}
|
||||
/>
|
||||
{/* Wrap header in a section for easy capture */}
|
||||
<div className='report-header-section'>
|
||||
<ReportHeader
|
||||
outlet={outlet}
|
||||
reportTitle={getReportTitle()}
|
||||
reportSubtitle='Laporan Bulanan'
|
||||
brandName='Apskel'
|
||||
brandColor='#36175e'
|
||||
periode={getReportPeriodText()}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Performance Summary */}
|
||||
<div className='p-8'>
|
||||
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
|
||||
1. Ringkasan
|
||||
<h3 className='text-3xl font-bold mb-8' style={{ color: '#36175e' }}>
|
||||
Ringkasan
|
||||
</h3>
|
||||
|
||||
<div className='grid grid-cols-2 gap-6'>
|
||||
<div className='space-y-4'>
|
||||
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
||||
<span className='text-gray-700'>Total Penjualan (termasuk rasik)</span>
|
||||
<span className='font-semibold text-gray-800'>
|
||||
{formatCurrency(profitLoss?.summary.total_revenue ?? 0)}
|
||||
</span>
|
||||
</div>
|
||||
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
||||
<span className='text-gray-700'>Total Terjual</span>
|
||||
<span className='font-semibold text-gray-800'>{productSummary.totalQuantitySold}</span>
|
||||
</div>
|
||||
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
||||
<span className='text-gray-700'>HPP</span>
|
||||
<span className='font-semibold text-gray-800'>
|
||||
{formatCurrency(profitLoss?.summary.total_cost ?? 0)} |{' '}
|
||||
{(((profitLoss?.summary.total_cost ?? 0) / (profitLoss?.summary.total_revenue || 1)) * 100).toFixed(
|
||||
0
|
||||
)}
|
||||
%
|
||||
</span>
|
||||
</div>
|
||||
<div className='flex justify-between items-center py-2 border-b-2 border-gray-300'>
|
||||
<span className='text-lg font-semibold text-green-800'>Laba Kotor</span>
|
||||
<span className='text-lg font-bold text-green-800'>
|
||||
{formatCurrency(profitLoss?.summary.gross_profit ?? 0)} |{' '}
|
||||
{(profitLoss?.summary.gross_profit_margin ?? 0).toFixed(0)}%
|
||||
</span>
|
||||
</div>
|
||||
<div className='space-y-5'>
|
||||
<div className='flex justify-between items-center py-3 border-b border-gray-200'>
|
||||
<span className='text-xl text-gray-700'>Total Penjualan</span>
|
||||
<span className='text-xl font-semibold text-gray-800'>
|
||||
{formatCurrency(profitLoss?.summary.total_revenue ?? 0)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className='space-y-4'>
|
||||
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
||||
<span className='text-gray-700'>Biaya lain²</span>
|
||||
<span className='font-semibold text-gray-800'>
|
||||
{formatCurrency(profitLoss?.summary.total_tax ?? 0)} |{' '}
|
||||
{(((profitLoss?.summary.total_tax ?? 0) / (profitLoss?.summary.total_revenue || 1)) * 100).toFixed(0)}
|
||||
%
|
||||
</span>
|
||||
</div>
|
||||
<div className='flex justify-between items-center py-2 border-b-2 border-gray-300'>
|
||||
<span className='text-lg font-bold text-blue-800'>Laba/Rugi</span>
|
||||
<span className='text-lg font-bold text-blue-800'>
|
||||
{formatCurrency(profitLoss?.summary.net_profit ?? 0)} |{' '}
|
||||
{(profitLoss?.summary.net_profit_margin ?? 0).toFixed(0)}%
|
||||
</span>
|
||||
</div>
|
||||
<div className='flex justify-between items-center py-3 border-b border-gray-200'>
|
||||
<span className='text-xl text-gray-700'>Total Diskon</span>
|
||||
<span className='text-xl font-semibold text-gray-800'>
|
||||
{formatCurrency(profitLoss?.summary.total_discount ?? 0)}
|
||||
</span>
|
||||
</div>
|
||||
<div className='flex justify-between items-center py-3 border-b border-gray-200'>
|
||||
<span className='text-xl text-gray-700'>Total Pajak</span>
|
||||
<span className='text-xl font-semibold text-gray-800'>
|
||||
{formatCurrency(profitLoss?.summary.total_tax ?? 0)}
|
||||
</span>
|
||||
</div>
|
||||
<div className='flex justify-between items-center py-3 border-b border-gray-200'>
|
||||
<span className='text-xl text-gray-700'>Service Charge</span>
|
||||
<span className='text-xl font-semibold text-gray-800'>{formatCurrency(0)}</span>
|
||||
</div>
|
||||
<div className='flex justify-between items-center py-3 border-b-2 border-gray-300'>
|
||||
<span className='text-xl text-gray-700 font-bold'>Total</span>
|
||||
<span className='text-xl font-bold text-gray-800'>
|
||||
{formatCurrency(profitLoss?.summary.total_revenue ?? 0)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Profit Loss Product Table */}
|
||||
{/* Invoice */}
|
||||
<div className='px-8 pb-8'>
|
||||
<h3 className='text-lg font-medium mb-6' style={{ color: '#36175e' }}>
|
||||
Laba Rugi Per Produk
|
||||
<h3 className='text-3xl font-bold mb-8' style={{ color: '#36175e' }}>
|
||||
Invoice
|
||||
</h3>
|
||||
|
||||
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
|
||||
<table className='w-full'>
|
||||
<thead>
|
||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
||||
<th className='text-left p-3 font-semibold'>Produk</th>
|
||||
<th className='text-center p-3 font-semibold'>Qty</th>
|
||||
<th className='text-right p-3 font-semibold'>Pendapatan</th>
|
||||
<th className='text-right p-3 font-semibold'>HPP</th>
|
||||
<th className='text-right p-3 font-semibold'>Laba Kotor</th>
|
||||
<th className='text-center p-3 font-semibold'>Margin (%)</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{profitLoss?.product_data?.map((item, index) => (
|
||||
<tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
|
||||
<td className='p-3 font-medium text-gray-800'>{item.product_name}</td>
|
||||
<td className='p-3 text-center text-gray-700'>{item.quantity_sold}</td>
|
||||
<td className='p-3 text-right font-semibold text-gray-800'>{formatCurrency(item.revenue)}</td>
|
||||
<td className='p-3 text-right font-semibold text-red-600'>{formatCurrency(item.cost)}</td>
|
||||
<td className='p-3 text-right font-semibold text-green-600'>{formatCurrency(item.gross_profit)}</td>
|
||||
<td className='p-3 text-center font-semibold' style={{ color: '#36175e' }}>
|
||||
{(item.gross_profit_margin ?? 0).toFixed(1)}%
|
||||
</td>
|
||||
</tr>
|
||||
)) || []}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
||||
<td className='p-3 font-bold'>TOTAL</td>
|
||||
<td className='p-3 text-center font-bold'>{profitLossProductSummary.totalQuantity}</td>
|
||||
<td className='p-3 text-right font-bold'>{formatCurrency(profitLossProductSummary.totalRevenue)}</td>
|
||||
<td className='p-3 text-right font-bold'>{formatCurrency(profitLossProductSummary.totalCost)}</td>
|
||||
<td className='p-3 text-right font-bold'>
|
||||
{formatCurrency(profitLossProductSummary.totalGrossProfit)}
|
||||
</td>
|
||||
<td className='p-3 text-center font-bold'>
|
||||
{profitLossProductSummary.totalRevenue > 0
|
||||
? (
|
||||
(profitLossProductSummary.totalGrossProfit / profitLossProductSummary.totalRevenue) *
|
||||
100
|
||||
).toFixed(1)
|
||||
: 0}
|
||||
%
|
||||
</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
<div className='space-y-5'>
|
||||
<div className='flex justify-between items-center py-3 border-b border-gray-200'>
|
||||
<span className='text-xl text-gray-700'>Total Invoice</span>
|
||||
<span className='text-xl font-semibold text-gray-800'>{profitLoss?.summary.total_orders ?? 0}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Payment Method Summary */}
|
||||
<div className='px-8 pb-8'>
|
||||
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
|
||||
2. Ringkasan Metode Pembayaran
|
||||
<h3 className='text-3xl font-bold mb-8' style={{ color: '#36175e' }}>
|
||||
Ringkasan Metode Pembayaran
|
||||
</h3>
|
||||
|
||||
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
|
||||
<table className='w-full'>
|
||||
<thead>
|
||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
||||
<th className='text-left p-3 font-semibold'>Metode Pembayaran</th>
|
||||
<th className='text-center p-3 font-semibold'>Tipe</th>
|
||||
<th className='text-center p-3 font-semibold'>Jumlah Order</th>
|
||||
<th className='text-right p-3 font-semibold'>Total Amount</th>
|
||||
<th className='text-center p-3 font-semibold'>Persentase</th>
|
||||
<tr className='text-gray-800 border-b-2 border-gray-300'>
|
||||
<th className='text-left text-xl p-4 font-semibold'>Metode Pembayaran</th>
|
||||
<th className='text-center text-xl p-4 font-semibold'>Tipe</th>
|
||||
<th className='text-center text-xl p-4 font-semibold'>Jumlah Order</th>
|
||||
<th className='text-right text-xl p-4 font-semibold'>Total Amount</th>
|
||||
<th className='text-center text-xl p-4 font-semibold'>Persentase</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{paymentAnalytics?.data?.map((payment, index) => (
|
||||
<tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
|
||||
<td className='p-3 font-medium text-gray-800'>{payment.payment_method_name}</td>
|
||||
<td className='p-3 text-center'>
|
||||
<td className='p-4 text-xl font-medium text-gray-800'>{payment.payment_method_name}</td>
|
||||
<td className='p-4 text-center'>
|
||||
<span
|
||||
className={`px-2 py-1 rounded-full text-xs font-medium ${
|
||||
className={`px-3 py-1 rounded-full text-lg font-medium ${
|
||||
payment.payment_method_type === 'cash'
|
||||
? 'bg-green-100 text-green-800'
|
||||
: 'bg-blue-100 text-blue-800'
|
||||
@@ -350,123 +334,240 @@ const DailyPOSReport = () => {
|
||||
{payment.payment_method_type.toUpperCase()}
|
||||
</span>
|
||||
</td>
|
||||
<td className='p-3 text-center text-gray-700'>{payment.order_count}</td>
|
||||
<td className='p-3 text-right font-semibold text-gray-800'>
|
||||
<td className='p-4 text-xl text-center text-gray-700'>{payment.order_count}</td>
|
||||
<td className='p-4 text-xl text-right font-semibold text-gray-800'>
|
||||
{formatCurrency(payment.total_amount)}
|
||||
</td>
|
||||
<td className='p-3 text-center font-medium' style={{ color: '#36175e' }}>
|
||||
<td className='p-4 text-xl text-center font-medium' style={{ color: '#36175e' }}>
|
||||
{(payment.percentage ?? 0).toFixed(1)}%
|
||||
</td>
|
||||
</tr>
|
||||
)) || []}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
||||
<td className='p-3 font-bold'>TOTAL</td>
|
||||
<td className='p-3'></td>
|
||||
<td className='p-3 text-center font-bold'>{paymentAnalytics?.summary.total_orders ?? 0}</td>
|
||||
<td className='p-3 text-right font-bold'>
|
||||
<tr className='text-gray-800 border-t-2 border-gray-300'>
|
||||
<td className='p-4 text-xl font-bold'>TOTAL</td>
|
||||
<td className='p-4'></td>
|
||||
<td className='p-4 text-xl text-center font-bold'>{paymentAnalytics?.summary.total_orders ?? 0}</td>
|
||||
<td className='p-4 text-xl text-right font-bold'>
|
||||
{formatCurrency(paymentAnalytics?.summary.total_amount ?? 0)}
|
||||
</td>
|
||||
<td className='p-3 text-center font-bold'></td>
|
||||
<td className='p-4 text-center font-bold'></td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Category Summary */}
|
||||
{/* Category Summary — +3 kolom baru */}
|
||||
<div className='px-8 pb-8'>
|
||||
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
|
||||
2. Ringkasan Kategori
|
||||
<h3 className='text-3xl font-bold mb-8' style={{ color: '#36175e' }}>
|
||||
Ringkasan Kategori
|
||||
</h3>
|
||||
|
||||
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
|
||||
<table className='w-full'>
|
||||
<thead>
|
||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
||||
<th className='text-left p-3 font-semibold'>Nama</th>
|
||||
<th className='text-center p-3 font-semibold'>Total Produk</th>
|
||||
<th className='text-center p-3 font-semibold'>Qty</th>
|
||||
<th className='text-right p-3 font-semibold'>Jumlah Order</th>
|
||||
<th className='text-center p-3 font-semibold'>Pendapatan</th>
|
||||
<tr className='text-gray-800 border-b-2 border-gray-300'>
|
||||
<th className='text-left text-xl p-4 font-semibold'>Nama</th>
|
||||
<th className='text-center text-xl p-4 font-semibold'>Qty</th>
|
||||
<th className='text-right text-xl p-4 font-semibold'>Pendapatan</th>
|
||||
<th className='text-center text-xl p-4 font-semibold'>% Std HPP</th>
|
||||
<th className='text-center text-xl p-4 font-semibold'>% Real HPP</th>
|
||||
<th className='text-center text-xl p-4 font-semibold'>Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{category?.data?.map((c, index) => (
|
||||
<tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
|
||||
<td className='p-3 font-medium text-gray-800'>{c.category_name}</td>
|
||||
<td className='p-3 text-center text-gray-700'>{c.product_count}</td>
|
||||
<td className='p-3 text-center text-gray-700'>{c.total_quantity}</td>
|
||||
<td className='p-3 text-center text-gray-700'>{c.order_count}</td>
|
||||
<td className='p-3 text-right font-semibold' style={{ color: '#36175e' }}>
|
||||
{formatCurrency(c.total_revenue)}
|
||||
{category?.data?.map((c, index) => {
|
||||
const stdHpp = DUMMY_STD_HPP
|
||||
const realHpp = DUMMY_REAL_HPP
|
||||
const status = getHppStatus(stdHpp, realHpp)
|
||||
return (
|
||||
<tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
|
||||
<td className='p-4 text-xl font-medium text-gray-800'>{c.category_name}</td>
|
||||
<td className='p-4 text-xl text-center text-gray-700'>{c.total_quantity}</td>
|
||||
<td className='p-4 text-xl text-right font-semibold' style={{ color: '#36175e' }}>
|
||||
{formatCurrency(c.total_revenue)}
|
||||
</td>
|
||||
<td className='p-4 text-xl text-center text-gray-700'>{stdHpp}%</td>
|
||||
<td className='p-4 text-xl text-center text-gray-700'>{realHpp}%</td>
|
||||
<td className='p-4 text-center'>
|
||||
<StatusBadge status={status} />
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
}) || []}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr className='text-gray-800 border-t-2 border-gray-300'>
|
||||
<td className='p-4 text-xl font-bold'>TOTAL</td>
|
||||
<td className='p-4 text-xl text-center font-bold'>{categorySummary?.totalQuantity ?? 0}</td>
|
||||
<td className='p-4 text-xl text-right font-bold'>
|
||||
{formatCurrency(categorySummary?.totalRevenue ?? 0)}
|
||||
</td>
|
||||
<td className='p-4'></td>
|
||||
<td className='p-4'></td>
|
||||
<td className='p-4'></td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Product Summary — +3 kolom baru */}
|
||||
<div className='px-8 pb-8'>
|
||||
<h3 className='text-3xl font-bold mb-8' style={{ color: '#36175e' }}>
|
||||
Ringkasan Item Per Kategori
|
||||
</h3>
|
||||
|
||||
<div className='space-y-12'>
|
||||
{Object.keys(groupedProducts)
|
||||
.sort((a, b) => {
|
||||
const productsA = groupedProducts[a]
|
||||
const productsB = groupedProducts[b]
|
||||
const orderA = productsA[0]?.category_order ?? 999
|
||||
const orderB = productsB[0]?.category_order ?? 999
|
||||
return orderA - orderB
|
||||
})
|
||||
.map((categoryName, catIndex) => {
|
||||
const categoryProducts = groupedProducts[categoryName].sort((a, b) => {
|
||||
const skuA = a.product_sku || ''
|
||||
const skuB = b.product_sku || ''
|
||||
return skuA.localeCompare(skuB)
|
||||
})
|
||||
const categoryTotalQty = categoryProducts.reduce((sum, item) => sum + (item.quantity_sold || 0), 0)
|
||||
const categoryTotalRevenue = categoryProducts.reduce((sum, item) => sum + (item.revenue || 0), 0)
|
||||
|
||||
return (
|
||||
<div key={categoryName} style={{ display: 'block', marginBottom: '70px' }}>
|
||||
<h4
|
||||
className='text-2xl font-bold mb-0 px-4 py-4 bg-gray-100 rounded-t-lg'
|
||||
style={{ color: '#36175e' }}
|
||||
>
|
||||
{categoryName.toUpperCase()}
|
||||
</h4>
|
||||
|
||||
<div className='bg-gray-50 rounded-b-lg border-l-2 border-r-2 border-b-2 border-gray-300'>
|
||||
<table
|
||||
className='w-full'
|
||||
style={{ borderCollapse: 'collapse', tableLayout: 'fixed', width: '100%' }}
|
||||
>
|
||||
<colgroup>
|
||||
<col style={{ width: '28%' }} />
|
||||
<col style={{ width: '10%' }} />
|
||||
<col style={{ width: '22%' }} />
|
||||
<col style={{ width: '13%' }} />
|
||||
<col style={{ width: '13%' }} />
|
||||
<col style={{ width: '14%' }} />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr className='text-gray-800 border-b-2 border-gray-300 bg-gray-100'>
|
||||
<th className='text-left text-xl p-5 font-semibold border-r border-gray-300'>Produk</th>
|
||||
<th className='text-center text-xl p-5 font-semibold border-r border-gray-300'>Qty</th>
|
||||
<th className='text-right text-xl p-5 font-semibold border-r border-gray-300'>
|
||||
Pendapatan
|
||||
</th>
|
||||
<th className='text-center text-xl p-5 font-semibold border-r border-gray-300'>
|
||||
% Std HPP
|
||||
</th>
|
||||
<th className='text-center text-xl p-5 font-semibold border-r border-gray-300'>
|
||||
% Real HPP
|
||||
</th>
|
||||
<th className='text-center text-xl p-5 font-semibold'>Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{categoryProducts.map((item, index) => {
|
||||
const stdHpp = DUMMY_STD_HPP
|
||||
const realHpp = DUMMY_REAL_HPP
|
||||
const status = getHppStatus(stdHpp, realHpp)
|
||||
return (
|
||||
<tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
|
||||
<td className='p-5 text-xl font-medium text-gray-800 border-r border-gray-200'>
|
||||
{item.product_name}
|
||||
</td>
|
||||
<td className='p-5 text-xl text-center text-gray-700 border-r border-gray-200'>
|
||||
{item.quantity_sold}
|
||||
</td>
|
||||
<td className='p-5 text-xl text-right font-semibold text-gray-800 border-r border-gray-200'>
|
||||
{formatCurrency(item.revenue)}
|
||||
</td>
|
||||
<td className='p-5 text-xl text-center text-gray-700 border-r border-gray-200'>
|
||||
{stdHpp}%
|
||||
</td>
|
||||
<td className='p-5 text-xl text-center text-gray-700 border-r border-gray-200'>
|
||||
{realHpp}%
|
||||
</td>
|
||||
<td className='p-5 text-center'>
|
||||
<StatusBadge status={status} />
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr className='bg-gray-200 border-t-2 border-gray-400'>
|
||||
<td className='p-5 text-xl font-bold text-gray-800 border-r border-gray-400'>
|
||||
Subtotal {categoryName}
|
||||
</td>
|
||||
<td className='p-5 text-xl text-center font-bold text-gray-800 border-r border-gray-400'>
|
||||
{categoryTotalQty}
|
||||
</td>
|
||||
<td className='p-5 text-xl text-right font-bold text-gray-800 border-r border-gray-400'>
|
||||
{formatCurrency(categoryTotalRevenue)}
|
||||
</td>
|
||||
<td className='p-5 border-r border-gray-400'></td>
|
||||
<td className='p-5 border-r border-gray-400'></td>
|
||||
<td className='p-5'></td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* Grand Total */}
|
||||
<div className='bg-purple-50 rounded-lg border-2 border-purple-300 mt-6'>
|
||||
<table className='w-full' style={{ borderCollapse: 'collapse', tableLayout: 'fixed' }}>
|
||||
<colgroup>
|
||||
<col style={{ width: '28%' }} />
|
||||
<col style={{ width: '10%' }} />
|
||||
<col style={{ width: '22%' }} />
|
||||
<col style={{ width: '13%' }} />
|
||||
<col style={{ width: '13%' }} />
|
||||
<col style={{ width: '14%' }} />
|
||||
</colgroup>
|
||||
<tfoot>
|
||||
<tr className='text-gray-800'>
|
||||
<td className='p-5 text-2xl font-bold border-r-2 border-purple-300' style={{ color: '#36175e' }}>
|
||||
TOTAL KESELURUHAN
|
||||
</td>
|
||||
<td
|
||||
className='p-5 text-2xl text-center font-bold border-r-2 border-purple-300'
|
||||
style={{ color: '#36175e' }}
|
||||
>
|
||||
{productSummary.totalQuantitySold ?? 0}
|
||||
</td>
|
||||
<td
|
||||
className='p-5 text-2xl text-right font-bold border-r-2 border-purple-300'
|
||||
style={{ color: '#36175e' }}
|
||||
>
|
||||
{formatCurrency(productSummary.totalRevenue ?? 0)}
|
||||
</td>
|
||||
<td className='p-5 border-r-2 border-purple-300'></td>
|
||||
<td className='p-5 border-r-2 border-purple-300'></td>
|
||||
<td className='p-5'></td>
|
||||
</tr>
|
||||
)) || []}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
||||
<td className='p-3 font-bold'>TOTAL</td>
|
||||
<td className='p-3 text-center font-bold'>{categorySummary?.productCount ?? 0}</td>
|
||||
<td className='p-3 text-center font-bold'>{categorySummary?.totalQuantity ?? 0}</td>
|
||||
<td className='p-3 text-center font-bold'>{categorySummary?.orderCount ?? 0}</td>
|
||||
<td className='p-3 text-right font-bold'>{formatCurrency(categorySummary?.totalRevenue ?? 0)}</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Transaction Summary */}
|
||||
<div className='px-8 pb-8'>
|
||||
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
|
||||
4. Ringkasan Item
|
||||
</h3>
|
||||
|
||||
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
|
||||
<table className='w-full'>
|
||||
<thead>
|
||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
||||
<th className='text-left p-3 font-semibold'>Produk</th>
|
||||
<th className='text-left p-3 font-semibold'>Kategori</th>
|
||||
<th className='text-center p-3 font-semibold'>Qty</th>
|
||||
<th className='text-right p-3 font-semibold'>Order</th>
|
||||
<th className='text-right p-3 font-semibold'>Pendapatan</th>
|
||||
<th className='text-right p-3 font-semibold'>Rata Rata</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{products?.data?.map((item, index) => (
|
||||
<tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
|
||||
<td className='p-3 font-medium text-gray-800'>{item.product_name}</td>
|
||||
<td className='p-3 font-medium text-gray-800'>{item.category_name}</td>
|
||||
<td className='p-3 text-center text-gray-700'>{item.quantity_sold}</td>
|
||||
<td className='p-3 text-center text-gray-700'>{item.order_count ?? 0}</td>
|
||||
<td className='p-3 text-right font-semibold text-gray-800'>{formatCurrency(item.revenue)}</td>
|
||||
<td className='p-3 text-right font-medium text-gray-800'>{formatCurrency(item.average_price)}</td>
|
||||
</tr>
|
||||
)) || []}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
||||
<td className='p-3 font-bold'>TOTAL</td>
|
||||
<td className='p-3 text-center'></td>
|
||||
<td className='p-3 text-center font-bold'>{productSummary.totalQuantitySold ?? 0}</td>
|
||||
<td className='p-3 text-right font-bold'>{productSummary.totalOrders ?? 0}</td>
|
||||
<td className='p-3 text-right font-bold'>{formatCurrency(productSummary.totalRevenue ?? 0)}</td>
|
||||
<td className='p-3 text-right font-bold'></td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Profit Loss Product Table */}
|
||||
|
||||
{/* Footer */}
|
||||
<div className='px-8 py-6 border-t-2 border-gray-200 mt-8'>
|
||||
<div className='flex justify-between items-center text-sm text-gray-600'>
|
||||
<div className='flex justify-between items-center text-base text-gray-600'>
|
||||
<p>© 2025 Apskel - Sistem POS Terpadu</p>
|
||||
<p></p>
|
||||
<p>Dicetak pada: {now.toLocaleDateString('id-ID')}</p>
|
||||
|
||||
@@ -4,7 +4,12 @@ import { TextField, Typography, useTheme } from '@mui/material'
|
||||
import { useState } from 'react'
|
||||
import Loading from '../../../../../../components/layout/shared/Loading'
|
||||
import { useDashboardAnalytics } from '../../../../../../services/queries/analytics'
|
||||
import { formatDateDDMMYYYY, formatForInputDate, formatShortCurrency } from '../../../../../../utils/transform'
|
||||
import {
|
||||
formatCurrency,
|
||||
formatDateDDMMYYYY,
|
||||
formatForInputDate,
|
||||
formatShortCurrency
|
||||
} from '../../../../../../utils/transform'
|
||||
import OrdersReport from '../../../../../../views/dashboards/orders/OrdersReport'
|
||||
import PaymentMethodReport from '../../../../../../views/dashboards/payment-methods/PaymentMethodReport'
|
||||
import ProductSales from '../../../../../../views/dashboards/products/ProductSales'
|
||||
@@ -115,14 +120,14 @@ const DashboardOverview = () => {
|
||||
<MetricCard
|
||||
iconClass='tabler-cash'
|
||||
title='Total Sales'
|
||||
value={formatShortCurrency(salesData.overview.total_sales)}
|
||||
value={formatCurrency(salesData.overview.total_sales)}
|
||||
bgColor='bg-green-500'
|
||||
isCurrency={true}
|
||||
/>
|
||||
<MetricCard
|
||||
iconClass='tabler-trending-up'
|
||||
title='Average Order Value'
|
||||
value={formatShortCurrency(salesData.overview.average_order_value)}
|
||||
value={formatCurrency(salesData.overview.average_order_value)}
|
||||
bgColor='bg-purple-500'
|
||||
isCurrency={true}
|
||||
/>
|
||||
|
||||
@@ -162,21 +162,21 @@ const DashboardProfitloss = () => {
|
||||
<MetricCard
|
||||
iconClass='tabler-currency-dollar'
|
||||
title='Total Revenue'
|
||||
value={formatShortCurrency(profitData.summary.total_revenue)}
|
||||
value={formatCurrency(profitData.summary.total_revenue)}
|
||||
bgColor='bg-green-500'
|
||||
isCurrency={true}
|
||||
/>
|
||||
<MetricCard
|
||||
iconClass='tabler-receipt'
|
||||
title='Total Cost'
|
||||
value={formatShortCurrency(profitData.summary.total_cost)}
|
||||
value={formatCurrency(profitData.summary.total_cost)}
|
||||
bgColor='bg-red-500'
|
||||
isCurrency={true}
|
||||
/>
|
||||
<MetricCard
|
||||
iconClass='tabler-trending-up'
|
||||
title='Gross Profit'
|
||||
value={formatShortCurrency(profitData.summary.gross_profit)}
|
||||
value={formatCurrency(profitData.summary.gross_profit)}
|
||||
subtitle={`Margin: ${formatPercentage(profitData.summary.gross_profit_margin)}`}
|
||||
bgColor='bg-blue-500'
|
||||
isNegative={profitData.summary.gross_profit < 0}
|
||||
@@ -186,7 +186,7 @@ const DashboardProfitloss = () => {
|
||||
iconClass='tabler-percentage'
|
||||
title='Profitability Ratio'
|
||||
value={formatPercentage(profitData.summary.profitability_ratio)}
|
||||
subtitle={`Avg Profit: ${formatShortCurrency(profitData.summary.average_profit)}`}
|
||||
subtitle={`Avg Profit: ${formatCurrency(profitData.summary.average_profit)}`}
|
||||
bgColor='bg-purple-500'
|
||||
/>
|
||||
</div>
|
||||
@@ -199,7 +199,7 @@ const DashboardProfitloss = () => {
|
||||
<h3 className='text-lg font-semibold text-gray-900'>Net Profit</h3>
|
||||
</div>
|
||||
<p className='text-3xl font-bold text-green-600 mb-2'>
|
||||
Rp {formatShortCurrency(profitData.summary.net_profit)}
|
||||
{formatCurrency(profitData.summary.net_profit)}
|
||||
</p>
|
||||
<p className='text-sm text-gray-600'>
|
||||
Margin: {formatPercentage(profitData.summary.net_profit_margin)}
|
||||
|
||||
@@ -0,0 +1,465 @@
|
||||
'use client'
|
||||
|
||||
// React Imports
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
// MUI Imports
|
||||
import type { BoxProps } from '@mui/material/Box'
|
||||
import Button from '@mui/material/Button'
|
||||
import IconButton from '@mui/material/IconButton'
|
||||
import List from '@mui/material/List'
|
||||
import ListItem from '@mui/material/ListItem'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import Chip from '@mui/material/Chip'
|
||||
import LinearProgress from '@mui/material/LinearProgress'
|
||||
import { styled } from '@mui/material/styles'
|
||||
|
||||
// Third-party Imports
|
||||
import { useDropzone } from 'react-dropzone'
|
||||
|
||||
// Component Imports
|
||||
import Link from '@components/Link'
|
||||
import CustomAvatar from '@core/components/mui/Avatar'
|
||||
|
||||
// Styled Component Imports
|
||||
import AppReactDropzone from '@/libs/styles/AppReactDropzone'
|
||||
|
||||
type FileProp = {
|
||||
name: string
|
||||
type: string
|
||||
size: number
|
||||
}
|
||||
|
||||
type UploadedImage = {
|
||||
id: string
|
||||
url: string
|
||||
name: string
|
||||
size: number
|
||||
}
|
||||
|
||||
type UploadProgress = {
|
||||
[fileId: string]: number
|
||||
}
|
||||
|
||||
interface MultipleImageUploadProps {
|
||||
// Required props
|
||||
onUpload: (files: File[]) => Promise<string[]> | string[] // Returns array of image URLs
|
||||
onSingleUpload?: (file: File) => Promise<string> | string // For individual file upload
|
||||
|
||||
// Optional customization props
|
||||
title?: string | null
|
||||
currentImages?: UploadedImage[]
|
||||
onImagesChange?: (images: UploadedImage[]) => void
|
||||
onImageRemove?: (imageId: string) => void
|
||||
|
||||
// Upload state
|
||||
isUploading?: boolean
|
||||
uploadProgress?: UploadProgress
|
||||
|
||||
// Limits
|
||||
maxFiles?: number
|
||||
maxFileSize?: number // in bytes
|
||||
acceptedFileTypes?: string[]
|
||||
|
||||
// UI customization
|
||||
showUrlOption?: boolean
|
||||
uploadButtonText?: string
|
||||
browseButtonText?: string
|
||||
dragDropText?: string
|
||||
replaceText?: string
|
||||
maxFilesText?: string
|
||||
|
||||
// Style customization
|
||||
className?: string
|
||||
disabled?: boolean
|
||||
|
||||
// Upload modes
|
||||
uploadMode?: 'batch' | 'individual' // batch: upload all at once, individual: upload one by one
|
||||
}
|
||||
|
||||
// Styled Dropzone Component
|
||||
const Dropzone = styled(AppReactDropzone)<BoxProps>(({ theme }) => ({
|
||||
'& .dropzone': {
|
||||
minHeight: 'unset',
|
||||
padding: theme.spacing(12),
|
||||
[theme.breakpoints.down('sm')]: {
|
||||
paddingInline: theme.spacing(5)
|
||||
},
|
||||
'&+.MuiList-root .MuiListItem-root .file-name': {
|
||||
fontWeight: theme.typography.body1.fontWeight
|
||||
}
|
||||
}
|
||||
}))
|
||||
|
||||
const MultipleImageUpload: React.FC<MultipleImageUploadProps> = ({
|
||||
onUpload,
|
||||
onSingleUpload,
|
||||
title = null,
|
||||
currentImages = [],
|
||||
onImagesChange,
|
||||
onImageRemove,
|
||||
isUploading = false,
|
||||
uploadProgress = {},
|
||||
maxFiles = 10,
|
||||
maxFileSize = 5 * 1024 * 1024, // 5MB default
|
||||
acceptedFileTypes = ['image/*'],
|
||||
showUrlOption = true,
|
||||
uploadButtonText = 'Upload All',
|
||||
browseButtonText = 'Browse Images',
|
||||
dragDropText = 'Drag and Drop Your Images Here.',
|
||||
replaceText = 'Drop Images to Add More',
|
||||
maxFilesText = 'Maximum {max} files allowed',
|
||||
className = '',
|
||||
disabled = false,
|
||||
uploadMode = 'batch'
|
||||
}) => {
|
||||
// States
|
||||
const [files, setFiles] = useState<File[]>([])
|
||||
const [error, setError] = useState<string>('')
|
||||
const [individualUploading, setIndividualUploading] = useState<Set<string>>(new Set())
|
||||
|
||||
const handleBatchUpload = async () => {
|
||||
if (!files.length) return
|
||||
|
||||
try {
|
||||
setError('')
|
||||
const imageUrls = await onUpload(files)
|
||||
|
||||
if (Array.isArray(imageUrls)) {
|
||||
const newImages: UploadedImage[] = files.map((file, index) => ({
|
||||
id: `${Date.now()}-${index}`,
|
||||
url: imageUrls[index],
|
||||
name: file.name,
|
||||
size: file.size
|
||||
}))
|
||||
|
||||
const updatedImages = [...currentImages, ...newImages]
|
||||
onImagesChange?.(updatedImages)
|
||||
setFiles([]) // Clear files after successful upload
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Upload failed')
|
||||
}
|
||||
}
|
||||
|
||||
const handleIndividualUpload = async (file: File, fileIndex: number) => {
|
||||
if (!onSingleUpload) return
|
||||
|
||||
const fileId = `${file.name}-${fileIndex}`
|
||||
setIndividualUploading(prev => new Set(prev).add(fileId))
|
||||
|
||||
try {
|
||||
setError('')
|
||||
const imageUrl = await onSingleUpload(file)
|
||||
|
||||
if (typeof imageUrl === 'string') {
|
||||
const newImage: UploadedImage = {
|
||||
id: `${Date.now()}-${fileIndex}`,
|
||||
url: imageUrl,
|
||||
name: file.name,
|
||||
size: file.size
|
||||
}
|
||||
|
||||
const updatedImages = [...currentImages, newImage]
|
||||
onImagesChange?.(updatedImages)
|
||||
|
||||
// Remove uploaded file from pending files
|
||||
setFiles(prev => prev.filter((_, index) => index !== fileIndex))
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Upload failed')
|
||||
} finally {
|
||||
setIndividualUploading(prev => {
|
||||
const newSet = new Set(prev)
|
||||
newSet.delete(fileId)
|
||||
return newSet
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Hooks
|
||||
const { getRootProps, getInputProps } = useDropzone({
|
||||
onDrop: (acceptedFiles: File[]) => {
|
||||
setError('')
|
||||
|
||||
if (acceptedFiles.length === 0) return
|
||||
|
||||
const totalFiles = currentImages.length + files.length + acceptedFiles.length
|
||||
|
||||
if (totalFiles > maxFiles) {
|
||||
setError(`Cannot upload more than ${maxFiles} files. Current: ${currentImages.length + files.length}`)
|
||||
return
|
||||
}
|
||||
|
||||
// Validate file sizes
|
||||
const invalidFiles = acceptedFiles.filter(file => file.size > maxFileSize)
|
||||
if (invalidFiles.length > 0) {
|
||||
setError(`Some files exceed ${formatFileSize(maxFileSize)} limit`)
|
||||
return
|
||||
}
|
||||
|
||||
// Add to existing files
|
||||
setFiles(prev => [...prev, ...acceptedFiles])
|
||||
},
|
||||
accept: acceptedFileTypes.reduce((acc, type) => ({ ...acc, [type]: [] }), {}),
|
||||
disabled: disabled || isUploading,
|
||||
multiple: true
|
||||
})
|
||||
|
||||
const formatFileSize = (bytes: number): string => {
|
||||
if (bytes === 0) return '0 Bytes'
|
||||
const k = 1024
|
||||
const sizes = ['Bytes', 'KB', 'MB', 'GB']
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
|
||||
}
|
||||
|
||||
const renderFilePreview = (file: FileProp) => {
|
||||
if (file.type.startsWith('image')) {
|
||||
return (
|
||||
<img
|
||||
width={38}
|
||||
height={38}
|
||||
alt={file.name}
|
||||
src={URL.createObjectURL(file as any)}
|
||||
className='rounded object-cover'
|
||||
/>
|
||||
)
|
||||
} else {
|
||||
return <i className='tabler-file-description' />
|
||||
}
|
||||
}
|
||||
|
||||
const handleRemoveFile = (fileIndex: number) => {
|
||||
setFiles(prev => prev.filter((_, index) => index !== fileIndex))
|
||||
setError('')
|
||||
}
|
||||
|
||||
const handleRemoveCurrentImage = (imageId: string) => {
|
||||
onImageRemove?.(imageId)
|
||||
}
|
||||
|
||||
const handleRemoveAllFiles = () => {
|
||||
setFiles([])
|
||||
setError('')
|
||||
}
|
||||
|
||||
const isIndividualUploading = (file: File, index: number) => {
|
||||
const fileId = `${file.name}-${index}`
|
||||
return individualUploading.has(fileId)
|
||||
}
|
||||
|
||||
const fileList = files.map((file: File, index: number) => {
|
||||
const isFileUploading = isIndividualUploading(file, index)
|
||||
const progress = uploadProgress[`${file.name}-${index}`] || 0
|
||||
|
||||
return (
|
||||
<ListItem key={`${file.name}-${index}`} className='pis-4 plb-3'>
|
||||
<div className='file-details flex-1'>
|
||||
<div className='file-preview'>{renderFilePreview(file)}</div>
|
||||
<div className='flex-1'>
|
||||
<Typography className='file-name font-medium' color='text.primary'>
|
||||
{file.name}
|
||||
</Typography>
|
||||
<Typography className='file-size' variant='body2'>
|
||||
{formatFileSize(file.size)}
|
||||
</Typography>
|
||||
{isFileUploading && progress > 0 && (
|
||||
<LinearProgress variant='determinate' value={progress} className='mt-1' />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex items-center gap-2'>
|
||||
{uploadMode === 'individual' && onSingleUpload && (
|
||||
<Button
|
||||
variant='outlined'
|
||||
size='small'
|
||||
onClick={() => handleIndividualUpload(file, index)}
|
||||
disabled={isUploading || isFileUploading}
|
||||
>
|
||||
{isFileUploading ? 'Uploading...' : 'Upload'}
|
||||
</Button>
|
||||
)}
|
||||
<IconButton onClick={() => handleRemoveFile(index)} disabled={isUploading || isFileUploading}>
|
||||
<i className='tabler-x text-xl' />
|
||||
</IconButton>
|
||||
</div>
|
||||
</ListItem>
|
||||
)
|
||||
})
|
||||
|
||||
const currentImagesList = currentImages.map(image => (
|
||||
<ListItem key={image.id} className='pis-4 plb-3'>
|
||||
<div className='file-details flex-1'>
|
||||
<div className='file-preview'>
|
||||
<img width={38} height={38} alt={image.name} src={image.url} className='rounded object-cover' />
|
||||
</div>
|
||||
<div className='flex-1'>
|
||||
<Typography className='file-name font-medium' color='text.primary'>
|
||||
{image.name}
|
||||
</Typography>
|
||||
<Typography className='file-size' variant='body2'>
|
||||
{formatFileSize(image.size)}
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex items-center gap-2'>
|
||||
<Chip label='Uploaded' color='success' size='small' />
|
||||
{onImageRemove && (
|
||||
<IconButton onClick={() => handleRemoveCurrentImage(image.id)} color='error' disabled={isUploading}>
|
||||
<i className='tabler-x text-xl' />
|
||||
</IconButton>
|
||||
)}
|
||||
</div>
|
||||
</ListItem>
|
||||
))
|
||||
|
||||
return (
|
||||
<Dropzone className={className}>
|
||||
{/* Conditional title and URL option header */}
|
||||
{title && (
|
||||
<div className='flex justify-between items-center mb-4'>
|
||||
<Typography variant='h6' component='h2'>
|
||||
{title}
|
||||
</Typography>
|
||||
{showUrlOption && (
|
||||
<Typography component={Link} color='primary.main' className='font-medium'>
|
||||
Add media from URL
|
||||
</Typography>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* File limits info */}
|
||||
<div className='flex justify-between items-center mb-4'>
|
||||
<Typography variant='body2' color='text.secondary'>
|
||||
{maxFilesText.replace('{max}', maxFiles.toString())}
|
||||
</Typography>
|
||||
<Typography variant='body2' color='text.secondary'>
|
||||
{currentImages.length + files.length} / {maxFiles} files
|
||||
</Typography>
|
||||
</div>
|
||||
|
||||
<div {...getRootProps({ className: 'dropzone' })}>
|
||||
<input {...getInputProps()} />
|
||||
<div className='flex items-center flex-col gap-2 text-center'>
|
||||
<CustomAvatar variant='rounded' skin='light' color='secondary'>
|
||||
<i className='tabler-upload' />
|
||||
</CustomAvatar>
|
||||
<Typography variant='h4'>
|
||||
{currentImages.length > 0 || files.length > 0 ? replaceText : dragDropText}
|
||||
</Typography>
|
||||
<Typography color='text.disabled'>or</Typography>
|
||||
<Button variant='tonal' size='small' disabled={disabled || isUploading}>
|
||||
{browseButtonText}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Error Message */}
|
||||
{error && (
|
||||
<Typography color='error' variant='body2' className='mt-2 text-center'>
|
||||
{error}
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
{/* Current uploaded images */}
|
||||
{currentImages.length > 0 && (
|
||||
<div className='mt-4'>
|
||||
<Typography variant='subtitle2' className='mb-2'>
|
||||
Uploaded Images ({currentImages.length}):
|
||||
</Typography>
|
||||
<List>{currentImagesList}</List>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Pending files list and upload buttons */}
|
||||
{files.length > 0 && (
|
||||
<div className='mt-4'>
|
||||
<Typography variant='subtitle2' className='mb-2'>
|
||||
Pending Files ({files.length}):
|
||||
</Typography>
|
||||
<List>{fileList}</List>
|
||||
<div className='buttons flex gap-2 mt-3'>
|
||||
<Button color='error' variant='tonal' onClick={handleRemoveAllFiles} disabled={isUploading}>
|
||||
Remove All
|
||||
</Button>
|
||||
{uploadMode === 'batch' && (
|
||||
<Button variant='contained' onClick={handleBatchUpload} disabled={isUploading || files.length === 0}>
|
||||
{isUploading ? 'Uploading...' : `${uploadButtonText} (${files.length})`}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Dropzone>
|
||||
)
|
||||
}
|
||||
|
||||
export default MultipleImageUpload
|
||||
|
||||
// ===== USAGE EXAMPLES =====
|
||||
|
||||
// 1. Batch upload mode (upload all files at once)
|
||||
// const [images, setImages] = useState<UploadedImage[]>([])
|
||||
//
|
||||
// <MultipleImageUpload
|
||||
// title="Product Images"
|
||||
// onUpload={handleBatchUpload}
|
||||
// currentImages={images}
|
||||
// onImagesChange={setImages}
|
||||
// onImageRemove={(id) => setImages(prev => prev.filter(img => img.id !== id))}
|
||||
// maxFiles={5}
|
||||
// uploadMode="batch"
|
||||
// />
|
||||
|
||||
// 2. Individual upload mode (upload files one by one)
|
||||
// <MultipleImageUpload
|
||||
// title="Gallery Images"
|
||||
// onUpload={handleBatchUpload}
|
||||
// onSingleUpload={handleSingleUpload}
|
||||
// currentImages={images}
|
||||
// onImagesChange={setImages}
|
||||
// onImageRemove={(id) => setImages(prev => prev.filter(img => img.id !== id))}
|
||||
// maxFiles={10}
|
||||
// uploadMode="individual"
|
||||
// uploadProgress={uploadProgress}
|
||||
// />
|
||||
|
||||
// 3. Without title, custom limits
|
||||
// <MultipleImageUpload
|
||||
// title={null}
|
||||
// onUpload={handleBatchUpload}
|
||||
// currentImages={images}
|
||||
// onImagesChange={setImages}
|
||||
// maxFiles={3}
|
||||
// maxFileSize={2 * 1024 * 1024} // 2MB
|
||||
// acceptedFileTypes={['image/jpeg', 'image/png']}
|
||||
// />
|
||||
|
||||
// 4. Example upload handlers
|
||||
// const handleBatchUpload = async (files: File[]): Promise<string[]> => {
|
||||
// const formData = new FormData()
|
||||
// files.forEach(file => formData.append('images', file))
|
||||
//
|
||||
// const response = await fetch('/api/upload-multiple', {
|
||||
// method: 'POST',
|
||||
// body: formData
|
||||
// })
|
||||
//
|
||||
// const result = await response.json()
|
||||
// return result.urls // Array of uploaded image URLs
|
||||
// }
|
||||
//
|
||||
// const handleSingleUpload = async (file: File): Promise<string> => {
|
||||
// const formData = new FormData()
|
||||
// formData.append('image', file)
|
||||
//
|
||||
// const response = await fetch('/api/upload-single', {
|
||||
// method: 'POST',
|
||||
// body: formData
|
||||
// })
|
||||
//
|
||||
// const result = await response.json()
|
||||
// return result.url // Single uploaded image URL
|
||||
// }
|
||||
@@ -7,6 +7,14 @@ import Menu from '@mui/material/Menu'
|
||||
import MenuItem from '@mui/material/MenuItem'
|
||||
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 }) => ({
|
||||
textTransform: 'none',
|
||||
fontWeight: 400,
|
||||
@@ -102,7 +110,7 @@ const StatusFilterTabs: React.FC<StatusFilterTabsProps> = ({
|
||||
})
|
||||
}}
|
||||
>
|
||||
{status}
|
||||
{toTitleCase(status)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
@@ -135,7 +143,7 @@ const StatusFilterTabs: React.FC<StatusFilterTabsProps> = ({
|
||||
})
|
||||
}}
|
||||
>
|
||||
{status}
|
||||
{toTitleCase(status)}
|
||||
</Button>
|
||||
))}
|
||||
|
||||
@@ -158,7 +166,7 @@ const StatusFilterTabs: React.FC<StatusFilterTabsProps> = ({
|
||||
})
|
||||
}}
|
||||
>
|
||||
{isDropdownItemSelected ? selectedStatus : dropdownLabel}
|
||||
{isDropdownItemSelected ? toTitleCase(selectedStatus) : dropdownLabel}
|
||||
</DropdownButton>
|
||||
|
||||
<Menu
|
||||
@@ -187,7 +195,7 @@ const StatusFilterTabs: React.FC<StatusFilterTabsProps> = ({
|
||||
color: selectedStatus === status ? 'primary.main' : 'text.primary'
|
||||
}}
|
||||
>
|
||||
{status}
|
||||
{toTitleCase(status)}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Menu>
|
||||
|
||||
@@ -32,7 +32,7 @@ const HorizontalWithSubtitle = (props: UserDataType) => {
|
||||
<div className='flex flex-col gap-1 flex-grow'>
|
||||
<Typography color='text.primary'>{title}</Typography>
|
||||
<div className='flex items-center gap-2 flex-wrap'>
|
||||
<Typography variant='h4'>{stats}</Typography>
|
||||
<Typography variant='h5'>{stats}</Typography>
|
||||
<Typography color={trend === 'negative' ? 'error.main' : 'success.main'}>
|
||||
{`(${trend === 'negative' ? '-' : '+'}${trendNumber})`}
|
||||
</Typography>
|
||||
|
||||
@@ -91,27 +91,27 @@ const VerticalMenu = ({ dictionary, scrollMenu }: Props) => {
|
||||
<MenuItem href={`/${locale}/dashboards/daily-report`}>{dictionary['navigation'].dailyReport}</MenuItem>
|
||||
</SubMenu>
|
||||
<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/sales-bills`}>{dictionary['navigation'].invoices}</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-quotes`}>{dictionary['navigation'].quotes}</MenuItem>
|
||||
</SubMenu>
|
||||
</SubMenu> */}
|
||||
<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/purchase-bills`}>
|
||||
{/* <MenuItem href={`/${locale}/apps/purchase/purchase-bills`}>
|
||||
{dictionary['navigation'].purchase_bills}
|
||||
</MenuItem>
|
||||
<MenuItem href={`/${locale}/apps/purchase/purchase-deliveries`}>
|
||||
{dictionary['navigation'].purchase_delivery}
|
||||
</MenuItem>
|
||||
</MenuItem> */}
|
||||
<MenuItem href={`/${locale}/apps/purchase/purchase-orders`}>
|
||||
{dictionary['navigation'].purchase_orders}
|
||||
</MenuItem>
|
||||
<MenuItem href={`/${locale}/apps/purchase/purchase-quotes`}>
|
||||
{/* <MenuItem href={`/${locale}/apps/purchase/purchase-quotes`}>
|
||||
{dictionary['navigation'].purchase_quotes}
|
||||
</MenuItem>
|
||||
</MenuItem> */}
|
||||
</SubMenu>
|
||||
<MenuItem
|
||||
href={`/${locale}/apps/expense`}
|
||||
@@ -129,6 +129,52 @@ const VerticalMenu = ({ dictionary, scrollMenu }: Props) => {
|
||||
>
|
||||
{dictionary['navigation'].cash_and_bank}
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
href={`/${locale}/apps/account`}
|
||||
icon={<i className='tabler-align-box-left-stretch' />}
|
||||
exactMatch={false}
|
||||
activeUrl='/apps/account'
|
||||
>
|
||||
{dictionary['navigation'].account}
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
href={`/${locale}/apps/fixed-assets`}
|
||||
icon={<i className='tabler-apps' />}
|
||||
exactMatch={false}
|
||||
activeUrl='/apps/fixed-assets'
|
||||
>
|
||||
{dictionary['navigation'].fixed_assets}
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
href={`/${locale}/apps/report`}
|
||||
icon={<i className='tabler-file-analytics' />}
|
||||
exactMatch={false}
|
||||
activeUrl='/apps/report'
|
||||
>
|
||||
{dictionary['navigation'].reports}
|
||||
</MenuItem>
|
||||
<SubMenu label={dictionary['navigation'].marketing} icon={<i className='tabler-shopping-cart' />}>
|
||||
{/* <MenuItem href={`/${locale}/apps/marketing/loyalty`}>{dictionary['navigation'].loyalty}</MenuItem> */}
|
||||
<MenuItem href={`/${locale}/apps/marketing/reward`}>{dictionary['navigation'].reward}</MenuItem>
|
||||
{/* <SubMenu label={dictionary['navigation'].gamification}>
|
||||
<MenuItem href={`/${locale}/apps/marketing/gamification/wheel-spin`}>
|
||||
{dictionary['navigation'].wheel_spin}
|
||||
</MenuItem>
|
||||
</SubMenu> */}
|
||||
<SubMenu label={dictionary['navigation'].games}>
|
||||
<MenuItem href={`/${locale}/apps/marketing/games/list`}>{dictionary['navigation'].list}</MenuItem>
|
||||
<MenuItem href={`/${locale}/apps/marketing/games/game-prizes`}>
|
||||
{dictionary['navigation'].game_prizes}
|
||||
</MenuItem>
|
||||
</SubMenu>
|
||||
<MenuItem href={`/${locale}/apps/marketing/campaign`}>{dictionary['navigation'].campaign}</MenuItem>
|
||||
{/* <MenuItem href={`/${locale}/apps/marketing/customer-analytics`}>
|
||||
{dictionary['navigation'].customer_analytics}
|
||||
</MenuItem> */}
|
||||
{/* <MenuItem href={`/${locale}/apps/marketing/voucher`}>{dictionary['navigation'].voucher}</MenuItem> */}
|
||||
<MenuItem href={`/${locale}/apps/marketing/tier`}>{dictionary['navigation'].tiers_text}</MenuItem>
|
||||
{/* <MenuItem href={`/${locale}/apps/marketing/discount`}>{dictionary['navigation'].discount}</MenuItem> */}
|
||||
</SubMenu>
|
||||
<SubMenu label={dictionary['navigation'].inventory} icon={<i className='tabler-salad' />}>
|
||||
<SubMenu label={dictionary['navigation'].products}>
|
||||
<MenuItem href={`/${locale}/apps/inventory/products/list`}>{dictionary['navigation'].list}</MenuItem>
|
||||
@@ -188,6 +234,9 @@ const VerticalMenu = ({ dictionary, scrollMenu }: Props) => {
|
||||
>
|
||||
{dictionary['navigation'].vendor}
|
||||
</MenuItem>
|
||||
<MenuItem href={`/${locale}/draw`} icon={<i className='tabler-building' />} target='_blank'>
|
||||
Random Draw
|
||||
</MenuItem>
|
||||
</MenuSection>
|
||||
</Menu>
|
||||
</ScrollWrapper>
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import React from 'react'
|
||||
import { Box, Typography, Paper } from '@mui/material'
|
||||
|
||||
// Types
|
||||
type ReportItemHeaderProps = {
|
||||
title: string
|
||||
date?: string
|
||||
amount?: number
|
||||
}
|
||||
|
||||
type ReportItemSubheaderProps = {
|
||||
title: string
|
||||
}
|
||||
|
||||
type ReportItemProps = {
|
||||
accountCode: string
|
||||
accountName: string
|
||||
amount: number
|
||||
onClick?: () => void
|
||||
isSubtitle?: boolean
|
||||
}
|
||||
|
||||
type ReportItemFooterProps = {
|
||||
title: string
|
||||
amount: number
|
||||
children?: React.ReactNode
|
||||
}
|
||||
|
||||
// Helper function to format currency
|
||||
const formatCurrency = (amount: number) => {
|
||||
return new Intl.NumberFormat('id-ID', {
|
||||
minimumFractionDigits: 0,
|
||||
maximumFractionDigits: 0
|
||||
}).format(amount)
|
||||
}
|
||||
|
||||
// ReportItemHeader Component
|
||||
export const ReportItemHeader: React.FC<ReportItemHeaderProps> = ({ title, date, amount }) => {
|
||||
return (
|
||||
<Box className='bg-slate-200 px-6 py-4 flex justify-between items-center'>
|
||||
<Typography variant='h6' className='text-primary font-semibold'>
|
||||
{title}
|
||||
</Typography>
|
||||
<Typography variant='body1' className='text-primary font-medium'>
|
||||
{amount ? formatCurrency(amount) : date}
|
||||
</Typography>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
// ReportItemSubheader Component
|
||||
export const ReportItemSubheader: React.FC<ReportItemSubheaderProps> = ({ title }) => {
|
||||
return (
|
||||
<Box className='px-6 py-3 bg-white border-b border-gray-300 hover:bg-gray-50 transition-colors'>
|
||||
<Typography variant='subtitle1' className='font-semibold text-gray-900'>
|
||||
{title}
|
||||
</Typography>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
// ReportItem Component
|
||||
export const ReportItem: React.FC<ReportItemProps> = ({
|
||||
accountCode,
|
||||
accountName,
|
||||
amount,
|
||||
onClick,
|
||||
isSubtitle = true
|
||||
}) => {
|
||||
return (
|
||||
<Box
|
||||
onClick={onClick}
|
||||
className={`px-6 py-3 flex justify-between items-center bg-white border-b border-gray-300 transition-all duration-200 ease-in-out ${
|
||||
onClick ? 'cursor-pointer hover:bg-gray-50' : 'cursor-default'
|
||||
}`}
|
||||
>
|
||||
<Typography variant='body1' className={`text-gray-900 font-normal ${isSubtitle ? 'ml-4' : ''}`}>
|
||||
{accountCode} {accountName}
|
||||
</Typography>
|
||||
<Typography variant='body1' className='text-primary font-medium text-right'>
|
||||
{formatCurrency(amount)}
|
||||
</Typography>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
// ReportItemFooter Component
|
||||
export const ReportItemFooter: React.FC<ReportItemFooterProps> = ({ title, amount, children }) => {
|
||||
return (
|
||||
<Box className='px-6 py-4 border-b border-gray-300 hover:bg-gray-50 transition-colors'>
|
||||
<Box className='flex justify-between items-center'>
|
||||
<Typography variant='subtitle1' className='font-bold text-gray-900'>
|
||||
{title}
|
||||
</Typography>
|
||||
<Typography variant='subtitle1' className='text-primary font-bold text-right'>
|
||||
{formatCurrency(amount)}
|
||||
</Typography>
|
||||
</Box>
|
||||
{children && <Box className='mt-2'>{children}</Box>}
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
'use client'
|
||||
|
||||
// MUI Imports
|
||||
import Button from '@mui/material/Button'
|
||||
import Typography from '@mui/material/Typography'
|
||||
|
||||
interface Props {
|
||||
title: string
|
||||
}
|
||||
|
||||
const ReportTitle = ({ title }: Props) => {
|
||||
return (
|
||||
<div className='flex flex-wrap sm:items-center justify-between max-sm:flex-col gap-6'>
|
||||
<div>
|
||||
<Typography variant='h4' className='mbe-1'>
|
||||
{title}
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface Props {
|
||||
title: string
|
||||
}
|
||||
|
||||
export default ReportTitle
|
||||
@@ -124,6 +124,20 @@
|
||||
"sales_orders": "Orders",
|
||||
"quotes": "Quotes",
|
||||
"expenses": "Expenses",
|
||||
"cash_and_bank": "Cash & Bank"
|
||||
"cash_and_bank": "Cash & Bank",
|
||||
"account": "Account",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,6 +124,20 @@
|
||||
"sales_orders": "Pemesanan",
|
||||
"quotes": "Penawaran",
|
||||
"expenses": "Biaya",
|
||||
"cash_and_bank": "Kas & Bank"
|
||||
"cash_and_bank": "Kas & Bank",
|
||||
"account": "Akun",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ import orderReducer from '@/redux-store/slices/order'
|
||||
import productRecipeReducer from '@/redux-store/slices/productRecipe'
|
||||
import organizationReducer from '@/redux-store/slices/organization'
|
||||
import userReducer from '@/redux-store/slices/user'
|
||||
import vendorReducer from '@/redux-store/slices/vendor'
|
||||
import discountReducer from '@/redux-store/slices/discount'
|
||||
|
||||
export const store = configureStore({
|
||||
reducer: {
|
||||
@@ -19,7 +21,9 @@ export const store = configureStore({
|
||||
orderReducer,
|
||||
productRecipeReducer,
|
||||
organizationReducer,
|
||||
userReducer
|
||||
userReducer,
|
||||
vendorReducer,
|
||||
discountReducer
|
||||
},
|
||||
middleware: getDefaultMiddleware => getDefaultMiddleware({ serializableCheck: false })
|
||||
})
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
// redux-store/slices/discount.ts
|
||||
|
||||
import { CategoryRuleType, CreateDiscountPayload, ProductRuleType } from '@/types/services/discount'
|
||||
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
|
||||
|
||||
// Temporary interfaces for rules before discount is created
|
||||
interface TempProductRule {
|
||||
product_id: string
|
||||
product_name?: string
|
||||
rule_type: ProductRuleType
|
||||
quantity: number
|
||||
free_quantity: number
|
||||
}
|
||||
|
||||
interface TempCategoryRule {
|
||||
category_id: string
|
||||
category_name?: string
|
||||
rule_type: CategoryRuleType
|
||||
}
|
||||
|
||||
interface DiscountState {
|
||||
discountRequest: CreateDiscountPayload
|
||||
selectedOutlets: string[]
|
||||
productRules: TempProductRule[]
|
||||
categoryRules: TempCategoryRule[]
|
||||
}
|
||||
|
||||
const initialState: DiscountState = {
|
||||
discountRequest: {
|
||||
campaign_id: '',
|
||||
code: '',
|
||||
name: '',
|
||||
type: 'percentage',
|
||||
value: 0,
|
||||
min_purchase_amount: 0,
|
||||
min_purchase_qty: 0,
|
||||
start_date: '',
|
||||
end_date: '',
|
||||
usage_limit_per_customer: undefined,
|
||||
usage_limit_total: undefined,
|
||||
customer_type: 'all',
|
||||
is_stackable: false,
|
||||
priority: 10
|
||||
},
|
||||
selectedOutlets: [],
|
||||
productRules: [],
|
||||
categoryRules: []
|
||||
}
|
||||
|
||||
const discountSlice = createSlice({
|
||||
name: 'discount',
|
||||
initialState,
|
||||
reducers: {
|
||||
// Set entire discount object
|
||||
setDiscount: (state, action: PayloadAction<CreateDiscountPayload>) => {
|
||||
state.discountRequest = action.payload
|
||||
},
|
||||
|
||||
// Set individual field
|
||||
setDiscountField: (state, action: PayloadAction<{ field: keyof CreateDiscountPayload; value: any }>) => {
|
||||
const { field, value } = action.payload
|
||||
state.discountRequest[field] = value as never
|
||||
},
|
||||
|
||||
// Reset discount to initial state
|
||||
resetDiscount: state => {
|
||||
state.discountRequest = initialState.discountRequest
|
||||
state.selectedOutlets = []
|
||||
state.productRules = []
|
||||
state.categoryRules = []
|
||||
},
|
||||
|
||||
// Outlet management
|
||||
setDiscountOutlets: (state, action: PayloadAction<string[]>) => {
|
||||
state.selectedOutlets = action.payload
|
||||
},
|
||||
|
||||
addDiscountOutlet: (state, action: PayloadAction<string>) => {
|
||||
if (!state.selectedOutlets.includes(action.payload)) {
|
||||
state.selectedOutlets.push(action.payload)
|
||||
}
|
||||
},
|
||||
|
||||
removeDiscountOutlet: (state, action: PayloadAction<string>) => {
|
||||
state.selectedOutlets = state.selectedOutlets.filter(id => id !== action.payload)
|
||||
},
|
||||
|
||||
// Product rules management
|
||||
setProductRules: (state, action: PayloadAction<TempProductRule[]>) => {
|
||||
state.productRules = action.payload
|
||||
},
|
||||
|
||||
addProductRule: (state, action: PayloadAction<TempProductRule>) => {
|
||||
state.productRules.push(action.payload)
|
||||
},
|
||||
|
||||
updateProductRule: (state, action: PayloadAction<{ index: number; rule: TempProductRule }>) => {
|
||||
const { index, rule } = action.payload
|
||||
if (index >= 0 && index < state.productRules.length) {
|
||||
state.productRules[index] = rule
|
||||
}
|
||||
},
|
||||
|
||||
removeProductRule: (state, action: PayloadAction<number>) => {
|
||||
state.productRules = state.productRules.filter((_, index) => index !== action.payload)
|
||||
},
|
||||
|
||||
clearProductRules: state => {
|
||||
state.productRules = []
|
||||
},
|
||||
|
||||
// Category rules management
|
||||
setCategoryRules: (state, action: PayloadAction<TempCategoryRule[]>) => {
|
||||
state.categoryRules = action.payload
|
||||
},
|
||||
|
||||
addCategoryRule: (state, action: PayloadAction<TempCategoryRule>) => {
|
||||
state.categoryRules.push(action.payload)
|
||||
},
|
||||
|
||||
updateCategoryRule: (state, action: PayloadAction<{ index: number; rule: TempCategoryRule }>) => {
|
||||
const { index, rule } = action.payload
|
||||
if (index >= 0 && index < state.categoryRules.length) {
|
||||
state.categoryRules[index] = rule
|
||||
}
|
||||
},
|
||||
|
||||
removeCategoryRule: (state, action: PayloadAction<number>) => {
|
||||
state.categoryRules = state.categoryRules.filter((_, index) => index !== action.payload)
|
||||
},
|
||||
|
||||
clearCategoryRules: state => {
|
||||
state.categoryRules = []
|
||||
},
|
||||
|
||||
// Bulk operations
|
||||
clearAllRules: state => {
|
||||
state.productRules = []
|
||||
state.categoryRules = []
|
||||
},
|
||||
|
||||
// Set multiple fields at once
|
||||
setDiscountFields: (state, action: PayloadAction<Partial<CreateDiscountPayload>>) => {
|
||||
state.discountRequest = { ...state.discountRequest, ...action.payload }
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export const {
|
||||
setDiscount,
|
||||
setDiscountField,
|
||||
resetDiscount,
|
||||
setDiscountOutlets,
|
||||
addDiscountOutlet,
|
||||
removeDiscountOutlet,
|
||||
setProductRules,
|
||||
addProductRule,
|
||||
updateProductRule,
|
||||
removeProductRule,
|
||||
clearProductRules,
|
||||
setCategoryRules,
|
||||
addCategoryRule,
|
||||
updateCategoryRule,
|
||||
removeCategoryRule,
|
||||
clearCategoryRules,
|
||||
clearAllRules,
|
||||
setDiscountFields
|
||||
} = discountSlice.actions
|
||||
|
||||
export default discountSlice.reducer
|
||||
|
||||
// Selectors (optional but recommended)
|
||||
export const selectDiscountRequest = (state: { discountReducer: DiscountState }) =>
|
||||
state.discountReducer.discountRequest
|
||||
|
||||
export const selectSelectedOutlets = (state: { discountReducer: DiscountState }) =>
|
||||
state.discountReducer.selectedOutlets
|
||||
|
||||
export const selectProductRules = (state: { discountReducer: DiscountState }) => state.discountReducer.productRules
|
||||
|
||||
export const selectCategoryRules = (state: { discountReducer: DiscountState }) => state.discountReducer.categoryRules
|
||||
|
||||
export const selectIsDiscountValid = (state: { discountReducer: DiscountState }) => {
|
||||
const { discountRequest } = state.discountReducer
|
||||
return (
|
||||
discountRequest.campaign_id !== '' &&
|
||||
discountRequest.code !== '' &&
|
||||
discountRequest.name !== '' &&
|
||||
discountRequest.start_date !== '' &&
|
||||
discountRequest.end_date !== '' &&
|
||||
(discountRequest.type === 'free_product' || discountRequest.value > 0)
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// Third-party Imports
|
||||
import type { PayloadAction } from '@reduxjs/toolkit'
|
||||
import { createSlice } from '@reduxjs/toolkit'
|
||||
|
||||
// Type Imports
|
||||
|
||||
// Data Imports
|
||||
import { Vendor } from '../../types/services/vendor'
|
||||
|
||||
const initialState: { currentVendor: Vendor } = {
|
||||
currentVendor: {
|
||||
id: '',
|
||||
organization_id: '',
|
||||
name: '',
|
||||
email: '',
|
||||
phone_number: '',
|
||||
address: '',
|
||||
contact_person: '',
|
||||
tax_number: '',
|
||||
payment_terms: '',
|
||||
notes: '',
|
||||
is_active: true,
|
||||
created_at: '',
|
||||
updated_at: ''
|
||||
}
|
||||
}
|
||||
|
||||
export const VendorSlice = createSlice({
|
||||
name: 'vendor',
|
||||
initialState,
|
||||
reducers: {
|
||||
setVendor: (state, action: PayloadAction<Vendor>) => {
|
||||
state.currentVendor = action.payload
|
||||
},
|
||||
resetVendor: state => {
|
||||
state.currentVendor = initialState.currentVendor
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export const { setVendor, resetVendor } = VendorSlice.actions
|
||||
|
||||
export default VendorSlice.reducer
|
||||
+2
-2
@@ -7,6 +7,7 @@ const getToken = () => {
|
||||
|
||||
export const api = axios.create({
|
||||
baseURL: 'https://api-pos.apskel.id/api/v1',
|
||||
// baseURL: 'http://127.0.0.1:4000/api/v1',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
@@ -30,9 +31,8 @@ api.interceptors.response.use(
|
||||
response => response,
|
||||
error => {
|
||||
const status = error.response?.status
|
||||
const currentPath = window.location.pathname
|
||||
|
||||
if (status === 401 && !currentPath.endsWith('/login')) {
|
||||
if (status === 401) {
|
||||
localStorage.removeItem('user')
|
||||
localStorage.removeItem('authToken')
|
||||
window.location.href = '/login'
|
||||
|
||||
@@ -0,0 +1,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,52 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'react-toastify'
|
||||
import { api } from '../api'
|
||||
import { IngredientUnitConverterRequest } from '@/types/services/productRecipe'
|
||||
|
||||
export const useUnitConventorMutation = () => {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const createUnitConventer = useMutation({
|
||||
mutationFn: async (newUnitConventer: IngredientUnitConverterRequest) => {
|
||||
const response = await api.post('/unit-converters', newUnitConventer)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('UnitConventer created successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['unitConventers'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
|
||||
}
|
||||
})
|
||||
|
||||
const updateUnitConventer = useMutation({
|
||||
mutationFn: async ({ id, payload }: { id: string; payload: IngredientUnitConverterRequest }) => {
|
||||
const response = await api.put(`/unit-converters/${id}`, payload)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('UnitConventer updated successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['unit-converters'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Update failed')
|
||||
}
|
||||
})
|
||||
|
||||
const deleteUnitConventer = useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const response = await api.delete(`/unit-converters/${id}`)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('UnitConventer deleted successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['unitConventers'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Delete failed')
|
||||
}
|
||||
})
|
||||
|
||||
return { createUnitConventer, updateUnitConventer, deleteUnitConventer }
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { VendorRequest } from '@/types/services/vendor'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'react-toastify'
|
||||
import { api } from '../api'
|
||||
|
||||
export const useVendorsMutation = () => {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const createVendor = useMutation({
|
||||
mutationFn: async (newVendor: VendorRequest) => {
|
||||
const response = await api.post('/vendors', newVendor)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Vendor created successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['vendors'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
|
||||
}
|
||||
})
|
||||
|
||||
const updateVendor = useMutation({
|
||||
mutationFn: async ({ id, payload }: { id: string; payload: VendorRequest }) => {
|
||||
const response = await api.put(`/vendors/${id}`, payload)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Vendor updated successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['vendors'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Update failed')
|
||||
}
|
||||
})
|
||||
|
||||
const deleteVendor = useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const response = await api.delete(`/vendors/${id}`)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Vendor deleted successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['vendors'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Delete failed')
|
||||
}
|
||||
})
|
||||
|
||||
return { createVendor, updateVendor, deleteVendor }
|
||||
}
|
||||
@@ -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 = {}) {
|
||||
const { page = 1, limit = 10, search = '', ...filters } = params
|
||||
const { page = 1, limit = 50, search = '', ...filters } = params
|
||||
|
||||
return useQuery<Categories>({
|
||||
queryKey: ['categories', { page, limit, search, ...filters }],
|
||||
@@ -30,7 +30,9 @@ export function useCategories(params: CategoriesQueryParams = {}) {
|
||||
})
|
||||
|
||||
const res = await api.get(`/categories?${queryParams.toString()}`)
|
||||
return res.data.data
|
||||
const data = res.data.data
|
||||
|
||||
return data
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,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
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Ingredients } from '../../types/services/ingredient'
|
||||
import { api } from '../api'
|
||||
import { Ingredient } from '@/types/services/productRecipe'
|
||||
|
||||
interface IngredientsQueryParams {
|
||||
page?: number
|
||||
@@ -34,3 +35,13 @@ export function useIngredients(params: IngredientsQueryParams = {}) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function useIngredientById(id: string) {
|
||||
return useQuery<Ingredient>({
|
||||
queryKey: ['ingredients', id],
|
||||
queryFn: async () => {
|
||||
const res = await api.get(`/ingredients/${id}`)
|
||||
return res.data.data
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ interface OrdersQueryParams {
|
||||
page?: number
|
||||
limit?: number
|
||||
search?: string
|
||||
date_from?: string
|
||||
date_to?: string
|
||||
}
|
||||
|
||||
export function useOrders(params: OrdersQueryParams = {}) {
|
||||
|
||||
@@ -0,0 +1,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
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { api } from '../api'
|
||||
import { Vendor, Vendors } from '@/types/services/vendor'
|
||||
|
||||
interface VendorQueryParams {
|
||||
page?: number
|
||||
limit?: number
|
||||
search?: string
|
||||
}
|
||||
|
||||
export function useVendors(params: VendorQueryParams = {}) {
|
||||
const { page = 1, limit = 10, search = '', ...filters } = params
|
||||
|
||||
return useQuery<Vendors>({
|
||||
queryKey: ['vendors', { 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(`/vendors?${queryParams.toString()}`)
|
||||
return res.data.data
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
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) {
|
||||
return useQuery<Vendor>({
|
||||
queryKey: ['vendors', id],
|
||||
queryFn: async () => {
|
||||
const res = await api.get(`/vendors/${id}`)
|
||||
return res.data.data
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { VoucherRowsResponse } from '../../types/services/voucher'
|
||||
import { api } from '../api'
|
||||
|
||||
export interface VouchersQueryParams {
|
||||
rows?: number
|
||||
winner_number?: number
|
||||
}
|
||||
|
||||
export function useVoucherRows(params: VouchersQueryParams = {}, options: { enabled?: boolean } = {}) {
|
||||
const { rows = 5, winner_number = 1 } = params
|
||||
const { enabled = true } = options
|
||||
|
||||
return useQuery<VoucherRowsResponse>({
|
||||
queryKey: ['voucher-rows', { rows, winner_number }],
|
||||
queryFn: async () => {
|
||||
const res = await api.get(`/vouchers/rows`, {
|
||||
params: { rows, winner_number }
|
||||
})
|
||||
return res.data.data
|
||||
},
|
||||
enabled,
|
||||
staleTime: 5 * 60 * 1000,
|
||||
refetchOnWindowFocus: false
|
||||
})
|
||||
}
|
||||
|
||||
// Manual fetch function for cases where you need to fetch without using the hook
|
||||
export async function fetchVoucherRows(rows: number = 5, winner_number: number = 1): Promise<VoucherRowsResponse> {
|
||||
const res = await api.get(`/vouchers/rows`, {
|
||||
params: { rows, winner_number }
|
||||
})
|
||||
return res.data.data
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export type AccountType = {
|
||||
id: number
|
||||
code: string
|
||||
name: string
|
||||
category: string
|
||||
balance: string
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export type CashBankType = {
|
||||
id: number
|
||||
date: string
|
||||
description: string
|
||||
reference: string
|
||||
accept: number
|
||||
send: number
|
||||
balance: number
|
||||
status: string
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export type FixedAssetType = {
|
||||
id: number
|
||||
assetName: string
|
||||
puchaseBill: string // Code Purchase
|
||||
reference: string
|
||||
date: string
|
||||
price: number
|
||||
}
|
||||
@@ -10,49 +10,6 @@ export type PurchaseOrderType = {
|
||||
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 {
|
||||
id: string
|
||||
type: string
|
||||
|
||||
@@ -31,8 +31,10 @@ export interface SalesReport {
|
||||
export interface ProductData {
|
||||
product_id: string
|
||||
product_name: string
|
||||
product_sku: string
|
||||
category_id: string
|
||||
category_name: string
|
||||
category_order: number
|
||||
quantity_sold: number
|
||||
revenue: number
|
||||
average_price: number
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
export type CampaignType = 'REWARD' | 'POINTS' | 'TOKENS' | 'MIXED'
|
||||
|
||||
export type RuleType = 'TIER' | 'SPEND' | 'PRODUCT' | 'CATEGORY' | 'DAY' | 'LOCATION'
|
||||
|
||||
export type RewardType = 'POINTS' | 'TOKENS' | 'REWARD'
|
||||
|
||||
export interface Campaign {
|
||||
id: string // UUID
|
||||
name: string
|
||||
description?: string
|
||||
type: CampaignType
|
||||
start_date: string // ISO string
|
||||
end_date: string // ISO string
|
||||
is_active: boolean
|
||||
show_on_app: boolean
|
||||
position: number
|
||||
metadata?: {
|
||||
banner_url?: string
|
||||
}
|
||||
created_at: string // ISO string
|
||||
updated_at: string // ISO string
|
||||
}
|
||||
|
||||
export interface CampaignRule {
|
||||
id: string // UUID
|
||||
campaign_id: string // UUID
|
||||
rule_type: RuleType
|
||||
condition_value?: string
|
||||
reward_type: RewardType
|
||||
reward_value?: number
|
||||
reward_subtype?: string
|
||||
reward_ref_id?: string // UUID
|
||||
metadata?: Record<string, any>
|
||||
created_at: string // ISO string
|
||||
updated_at: string // ISO string
|
||||
}
|
||||
|
||||
export interface CampaignRequest {
|
||||
name: string
|
||||
description?: string
|
||||
type: CampaignType
|
||||
start_date: string // ISO string
|
||||
end_date: string // ISO string
|
||||
is_active: boolean
|
||||
show_on_app: boolean
|
||||
position: number
|
||||
metadata?: {
|
||||
banner_url?: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface CampaignRuleRequest {
|
||||
campaign_id: string
|
||||
rule_type: 'TIER' | 'SPEND' | 'PRODUCT' | 'CATEGORY' | 'DAY' | 'LOCATION'
|
||||
condition_value?: string
|
||||
reward_type: 'POINTS' | 'TOKENS' | 'REWARD'
|
||||
reward_value?: number
|
||||
reward_subtype?: string
|
||||
reward_ref_id?: string
|
||||
}
|
||||
|
||||
export interface Campaigns {
|
||||
campaigns: Campaign[]
|
||||
total: number
|
||||
page: number
|
||||
limit: number
|
||||
}
|
||||
@@ -1,25 +1,26 @@
|
||||
export interface Category {
|
||||
id: string;
|
||||
organization_id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
business_type: string;
|
||||
metadata: Record<string, any>;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
id: string
|
||||
organization_id: string
|
||||
name: string
|
||||
description: string | null
|
||||
business_type: string
|
||||
order: number
|
||||
metadata: Record<string, any>
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface Categories {
|
||||
categories: Category[];
|
||||
total_count: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
total_pages: number;
|
||||
categories: Category[]
|
||||
total_count: number
|
||||
page: number
|
||||
limit: number
|
||||
total_pages: number
|
||||
}
|
||||
|
||||
|
||||
export interface CategoryRequest {
|
||||
name: string;
|
||||
description: string | null;
|
||||
business_type: string;
|
||||
name: string
|
||||
description: string | null
|
||||
business_type: string
|
||||
order: number
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
id: string;
|
||||
organization_id: string;
|
||||
name: string;
|
||||
email?: string;
|
||||
phone?: string;
|
||||
address?: string;
|
||||
is_default: boolean;
|
||||
is_active: boolean;
|
||||
metadata: Record<string, any>;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
id: string
|
||||
organization_id: string
|
||||
name: string
|
||||
email?: string
|
||||
phone?: string
|
||||
address?: string
|
||||
is_default: boolean
|
||||
is_active: boolean
|
||||
metadata: Record<string, any>
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface Customers {
|
||||
data: Customer[];
|
||||
total_count: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
total_pages: number;
|
||||
data: Customer[]
|
||||
total_count: number
|
||||
page: number
|
||||
limit: number
|
||||
total_pages: number
|
||||
}
|
||||
|
||||
export interface CustomerRequest {
|
||||
name: string;
|
||||
email?: string;
|
||||
phone?: string;
|
||||
address?: string;
|
||||
is_active?: boolean;
|
||||
name: string
|
||||
email?: string
|
||||
phone?: string
|
||||
address?: string
|
||||
is_active?: boolean
|
||||
}
|
||||
|
||||
export interface CustomerAnalytics {
|
||||
id: string
|
||||
name: string
|
||||
email?: string
|
||||
phone?: string
|
||||
totalPoints: number
|
||||
totalSpent?: number
|
||||
loyaltyTier?: string // Bronze, Silver, Gold, dst
|
||||
lastTransactionDate?: Date
|
||||
}
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
/**
|
||||
* Discount type enum
|
||||
*/
|
||||
export type DiscountType = 'percentage' | 'fixed_amout' | 'free_product'
|
||||
|
||||
/**
|
||||
* Customer type enum
|
||||
*/
|
||||
export type CustomerType = 'all' | 'member' | 'vip'
|
||||
|
||||
/**
|
||||
* Product rule type enum
|
||||
*/
|
||||
export type ProductRuleType = 'required' | 'free' | 'excluded'
|
||||
|
||||
/**
|
||||
* Category rule type enum
|
||||
*/
|
||||
export type CategoryRuleType = 'included' | 'excluded'
|
||||
|
||||
/**
|
||||
* Discount interface
|
||||
*/
|
||||
export interface Discount {
|
||||
id: string
|
||||
campaign_id: string
|
||||
code: string
|
||||
name: string
|
||||
type: DiscountType
|
||||
value: number
|
||||
min_purchase_qty: number
|
||||
min_purchase_amount: number
|
||||
start_date: string
|
||||
end_date: string
|
||||
usage_limit_per_customer: number | null
|
||||
usage_limit_total: number | null
|
||||
usage_count: number
|
||||
customer_type: CustomerType
|
||||
is_stackable: boolean
|
||||
is_active: boolean
|
||||
priority: number
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Discount Outlet interface
|
||||
*/
|
||||
export interface DiscountOutlet {
|
||||
id: string
|
||||
discount_id: string
|
||||
outlet_id: string
|
||||
created_at: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Product Rule interface
|
||||
*/
|
||||
export interface ProductRule {
|
||||
id: string
|
||||
discount_id: string
|
||||
product_id: string
|
||||
rule_type: ProductRuleType
|
||||
quantity: number
|
||||
free_quantity: number
|
||||
created_at: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Category Rule interface
|
||||
*/
|
||||
export interface CategoryRule {
|
||||
id: string
|
||||
discount_id: string
|
||||
category_id: string
|
||||
rule_type: CategoryRuleType
|
||||
created_at: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Pagination metadata
|
||||
*/
|
||||
export interface Pagination {
|
||||
page: number
|
||||
limit: number
|
||||
total_count: number
|
||||
total_pages: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Discounts response with pagination
|
||||
*/
|
||||
export interface DiscountsResponse {
|
||||
discounts: Discount[]
|
||||
pagination: Pagination
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch discounts parameters
|
||||
*/
|
||||
export interface FetchDiscountsParams {
|
||||
page?: number
|
||||
limit?: number
|
||||
sort?: string
|
||||
order?: 'asc' | 'desc'
|
||||
search?: string
|
||||
campaign_id?: string
|
||||
type?: DiscountType
|
||||
customer_type?: CustomerType
|
||||
is_active?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Create discount payload
|
||||
*/
|
||||
export interface CreateDiscountPayload {
|
||||
campaign_id: string
|
||||
code: string
|
||||
name: string
|
||||
type: DiscountType
|
||||
value: number
|
||||
min_purchase_amount?: number
|
||||
min_purchase_qty?: number
|
||||
start_date: string
|
||||
end_date: string
|
||||
usage_limit_per_customer?: number
|
||||
usage_limit_total?: number
|
||||
customer_type: CustomerType
|
||||
is_stackable: boolean
|
||||
priority: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Update discount payload
|
||||
*/
|
||||
export interface UpdateDiscountPayload {
|
||||
campaign_id?: string
|
||||
code?: string
|
||||
name?: string
|
||||
type?: DiscountType
|
||||
value?: number
|
||||
min_purchase_amount?: number
|
||||
min_purchase_qty?: number
|
||||
start_date?: string
|
||||
end_date?: string
|
||||
usage_limit_per_customer?: number
|
||||
usage_limit_total?: number
|
||||
customer_type?: CustomerType
|
||||
is_stackable?: boolean
|
||||
is_active?: boolean
|
||||
priority?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Add outlets payload
|
||||
*/
|
||||
export interface AddOutletsPayload {
|
||||
outlet_ids: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace outlets payload
|
||||
*/
|
||||
export interface ReplaceOutletsPayload {
|
||||
outlet_ids: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Add product rule payload
|
||||
*/
|
||||
export interface AddProductRulePayload {
|
||||
product_id: string
|
||||
rule_type: ProductRuleType
|
||||
quantity?: number
|
||||
free_quantity?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Update product rule payload
|
||||
*/
|
||||
export interface UpdateProductRulePayload {
|
||||
rule_type: ProductRuleType
|
||||
quantity?: number
|
||||
free_quantity?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Add category rule payload
|
||||
*/
|
||||
export interface AddCategoryRulePayload {
|
||||
category_id: string
|
||||
rule_type: CategoryRuleType
|
||||
}
|
||||
|
||||
/**
|
||||
* Update category rule payload
|
||||
*/
|
||||
export interface UpdateCategoryRulePayload {
|
||||
rule_type: CategoryRuleType
|
||||
}
|
||||
|
||||
/**
|
||||
* Discount State for Redux
|
||||
*/
|
||||
export interface DiscountState {
|
||||
discounts: Discount[]
|
||||
allDiscounts: Discount[]
|
||||
discountsPagination: Pagination | null
|
||||
selectedDiscount: Discount | null
|
||||
discountOutlets: DiscountOutlet[]
|
||||
productRules: ProductRule[]
|
||||
categoryRules: CategoryRule[]
|
||||
loading: boolean
|
||||
error: string | null
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
export interface Game {
|
||||
id: string // uuid
|
||||
name: string
|
||||
type: string
|
||||
is_active: boolean
|
||||
metadata: Record<string, any>
|
||||
created_at: string // ISO datetime
|
||||
updated_at: string // ISO datetime
|
||||
}
|
||||
|
||||
export interface Games {
|
||||
data: Game[]
|
||||
total_count: number
|
||||
page: number
|
||||
limit: number
|
||||
total_pages: number
|
||||
}
|
||||
|
||||
export interface GameRequest {
|
||||
name: string
|
||||
type: string
|
||||
is_active: boolean
|
||||
metadata: {
|
||||
imageUrl?: string
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Game } from './game'
|
||||
|
||||
export interface GamePrize {
|
||||
id: string // uuid
|
||||
game_id: string // uuid
|
||||
name: string
|
||||
weight: number
|
||||
stock: number
|
||||
max_stock?: number
|
||||
threshold?: number // int64 → number
|
||||
fallback_prize_id?: string // uuid
|
||||
metadata: Record<string, any>
|
||||
game?: Game // relasi ke GameResponse
|
||||
fallback_prize?: GamePrize // self reference
|
||||
created_at: string // ISO datetime
|
||||
updated_at: string // ISO datetime
|
||||
}
|
||||
|
||||
export interface GamePrizes {
|
||||
data: GamePrize[]
|
||||
total_count: number
|
||||
page: number
|
||||
limit: number
|
||||
total_pages: number
|
||||
}
|
||||
|
||||
export interface GamePrizeRequest {
|
||||
game_id: string // uuid
|
||||
name: string
|
||||
weight: number // min 1
|
||||
stock: number // min 0
|
||||
max_stock?: number // optional
|
||||
threshold?: number // optional (int64 → number in TS)
|
||||
fallback_prize_id?: string // optional uuid
|
||||
}
|
||||
|
||||
export interface GamePrizeRequest {
|
||||
game_id: string // uuid
|
||||
name: string
|
||||
weight: number // min 1
|
||||
stock: number // min 0
|
||||
max_stock?: number // optional
|
||||
threshold?: number // optional (int64 → number in TS)
|
||||
fallback_prize_id?: string // optional uuid
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export interface LoyaltyType {
|
||||
id: string
|
||||
name: string
|
||||
minimumPurchase: number
|
||||
pointMultiplier: number
|
||||
benefits: string[]
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}
|
||||
@@ -1,56 +1,103 @@
|
||||
export interface Product {
|
||||
ID: string;
|
||||
OrganizationID: string;
|
||||
CategoryID: string;
|
||||
SKU: string;
|
||||
Name: string;
|
||||
Description: string | null;
|
||||
Price: number;
|
||||
Cost: number;
|
||||
BusinessType: string;
|
||||
ImageURL: string;
|
||||
PrinterType: string;
|
||||
UnitID: string | null;
|
||||
HasIngredients: boolean;
|
||||
Metadata: Record<string, any>;
|
||||
IsActive: boolean;
|
||||
CreatedAt: string; // ISO date string
|
||||
UpdatedAt: string; // ISO date string
|
||||
ID: string
|
||||
OrganizationID: string
|
||||
CategoryID: string
|
||||
SKU: string
|
||||
Name: string
|
||||
Description: string | null
|
||||
Price: number
|
||||
Cost: number
|
||||
BusinessType: string
|
||||
ImageURL: string
|
||||
PrinterType: string
|
||||
UnitID: string | null
|
||||
HasIngredients: boolean
|
||||
Metadata: Record<string, any>
|
||||
IsActive: boolean
|
||||
CreatedAt: string // ISO date string
|
||||
UpdatedAt: string // ISO date string
|
||||
}
|
||||
|
||||
export interface Ingredient {
|
||||
id: string;
|
||||
organization_id: string;
|
||||
outlet_id: string | null;
|
||||
name: string;
|
||||
unit_id: string;
|
||||
cost: number;
|
||||
stock: number;
|
||||
is_semi_finished: boolean;
|
||||
is_active: boolean;
|
||||
metadata: Record<string, any>;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
id: string
|
||||
organization_id: string
|
||||
outlet_id: string | null
|
||||
name: string
|
||||
unit_id: string
|
||||
cost: number
|
||||
stock: number
|
||||
is_semi_finished: boolean
|
||||
is_active: boolean
|
||||
metadata: Record<string, any>
|
||||
created_at: string
|
||||
updated_at: string
|
||||
unit: IngredientUnit
|
||||
}
|
||||
|
||||
export interface ProductRecipe {
|
||||
id: string;
|
||||
organization_id: string;
|
||||
outlet_id: string | null;
|
||||
product_id: string;
|
||||
variant_id: string | null;
|
||||
ingredient_id: string;
|
||||
quantity: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
product: Product;
|
||||
ingredient: Ingredient;
|
||||
id: string
|
||||
organization_id: string
|
||||
outlet_id: string | null
|
||||
product_id: string
|
||||
variant_id: string | null
|
||||
ingredient_id: string
|
||||
quantity: number
|
||||
waste: number
|
||||
created_at: string
|
||||
updated_at: string
|
||||
product: Product
|
||||
ingredient: Ingredient
|
||||
}
|
||||
|
||||
export interface ProductRecipeRequest {
|
||||
product_id: string;
|
||||
variant_id: string | null;
|
||||
ingredient_id: string;
|
||||
quantity: number;
|
||||
outlet_id: string | null;
|
||||
product_id: string
|
||||
variant_id: string | null
|
||||
ingredient_id: string
|
||||
quantity: number
|
||||
outlet_id: string | null
|
||||
waste: number
|
||||
}
|
||||
|
||||
export interface IngredientUnit {
|
||||
id: string
|
||||
organization_id: string
|
||||
outlet_id: string
|
||||
name: string
|
||||
abbreviation: string
|
||||
is_active: boolean
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface IngredientUnitConverterRequest {
|
||||
ingredient_id: string
|
||||
from_unit_id: string
|
||||
to_unit_id: string
|
||||
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 Vendor {
|
||||
id: string
|
||||
organization_id: string
|
||||
name: string
|
||||
email?: string
|
||||
phone_number?: string
|
||||
address?: string
|
||||
contact_person?: string
|
||||
tax_number?: string
|
||||
payment_terms?: string
|
||||
notes?: string
|
||||
is_active: boolean
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface Vendors {
|
||||
vendors: Vendor[]
|
||||
total_count: number
|
||||
page: number
|
||||
limit: number
|
||||
total_pages: number
|
||||
}
|
||||
|
||||
export interface VendorRequest {
|
||||
name: string
|
||||
email?: string
|
||||
phone_number?: string
|
||||
address?: string
|
||||
contact_person?: string
|
||||
tax_number?: string
|
||||
payment_terms?: string
|
||||
notes?: string
|
||||
is_active: boolean
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
export interface Voucher {
|
||||
voucher_code: string
|
||||
name: string
|
||||
phone_number: string
|
||||
is_winner: boolean
|
||||
}
|
||||
|
||||
export interface VoucherRow {
|
||||
row_number: number
|
||||
vouchers: Voucher[]
|
||||
}
|
||||
|
||||
export interface VoucherRowsResponse {
|
||||
rows: VoucherRow[]
|
||||
total_rows: number
|
||||
total_vouchers: number
|
||||
}
|
||||
|
||||
export interface VoucherApiResponse {
|
||||
success: boolean
|
||||
data: VoucherRowsResponse
|
||||
errors: any
|
||||
}
|
||||
|
||||
export interface VoucherType {
|
||||
id: number
|
||||
code: string
|
||||
type: 'discount' | 'cashback' | 'free_shipping' | 'product'
|
||||
discountType?: 'fixed' | 'percent'
|
||||
discountValue?: number
|
||||
minPurchase?: number
|
||||
validFrom: string
|
||||
validUntil: string
|
||||
isActive: boolean
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export interface WheelSpinType {
|
||||
id: string
|
||||
name: string
|
||||
weight: number
|
||||
omset: number
|
||||
fallback: boolean
|
||||
stock?: number
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}
|
||||
@@ -0,0 +1,527 @@
|
||||
// excelGenerator.ts
|
||||
import { formatCurrency, formatDateDDMMYYYY } from '@/utils/transform'
|
||||
import type ExcelJS from 'exceljs'
|
||||
|
||||
interface ExcelGeneratorParams {
|
||||
outlet: any
|
||||
profitLoss: any
|
||||
products: any
|
||||
paymentAnalytics: any
|
||||
category: any
|
||||
productSummary: {
|
||||
totalQuantitySold: number
|
||||
totalRevenue: number
|
||||
totalOrders: number
|
||||
}
|
||||
categorySummary: {
|
||||
totalRevenue: number
|
||||
orderCount: number
|
||||
productCount: number
|
||||
totalQuantity: number
|
||||
}
|
||||
filterType: 'single' | 'range'
|
||||
selectedDate: Date
|
||||
dateRange: { startDate: Date; endDate: Date }
|
||||
}
|
||||
|
||||
const formatDateForInput = (date: Date) => {
|
||||
return date.toISOString().split('T')[0]
|
||||
}
|
||||
|
||||
const getReportPeriodText = (params: ExcelGeneratorParams) => {
|
||||
if (params.filterType === 'single') {
|
||||
return `${formatDateDDMMYYYY(params.selectedDate)} - ${formatDateDDMMYYYY(params.selectedDate)}`
|
||||
}
|
||||
return `${formatDateDDMMYYYY(params.dateRange.startDate)} - ${formatDateDDMMYYYY(params.dateRange.endDate)}`
|
||||
}
|
||||
|
||||
// ========== EXCEL STYLES ==========
|
||||
const headerStyle: Partial<ExcelJS.Style> = {
|
||||
font: { bold: true, size: 12, color: { argb: 'FFFFFFFF' } },
|
||||
fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF36175E' } } as ExcelJS.FillPattern,
|
||||
alignment: { vertical: 'middle', horizontal: 'center' },
|
||||
border: {
|
||||
top: { style: 'thin', color: { argb: 'FFD1D5DB' } },
|
||||
left: { style: 'thin', color: { argb: 'FFD1D5DB' } },
|
||||
bottom: { style: 'thin', color: { argb: 'FFD1D5DB' } },
|
||||
right: { style: 'thin', color: { argb: 'FFD1D5DB' } }
|
||||
}
|
||||
}
|
||||
|
||||
const titleStyle: Partial<ExcelJS.Style> = {
|
||||
font: { bold: true, size: 18 },
|
||||
alignment: { vertical: 'middle', horizontal: 'left' }
|
||||
}
|
||||
|
||||
const subtitleStyle: Partial<ExcelJS.Style> = {
|
||||
font: { size: 11, color: { argb: 'FF6B7280' } },
|
||||
alignment: { vertical: 'middle', horizontal: 'left' }
|
||||
}
|
||||
|
||||
const labelStyle: Partial<ExcelJS.Style> = {
|
||||
font: { bold: true, size: 11 },
|
||||
alignment: { vertical: 'middle', horizontal: 'left' }
|
||||
}
|
||||
|
||||
const totalRowStyle: Partial<ExcelJS.Style> = {
|
||||
font: { bold: true, size: 11 },
|
||||
fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFF3F4F6' } } as ExcelJS.FillPattern,
|
||||
border: {
|
||||
top: { style: 'thin', color: { argb: 'FFD1D5DB' } },
|
||||
left: { style: 'thin', color: { argb: 'FFD1D5DB' } },
|
||||
bottom: { style: 'thin', color: { argb: 'FFD1D5DB' } },
|
||||
right: { style: 'thin', color: { argb: 'FFD1D5DB' } }
|
||||
}
|
||||
}
|
||||
|
||||
const dataStyle: Partial<ExcelJS.Style> = {
|
||||
border: {
|
||||
top: { style: 'thin', color: { argb: 'FFF3F4F6' } },
|
||||
left: { style: 'thin', color: { argb: 'FFF3F4F6' } },
|
||||
bottom: { style: 'thin', color: { argb: 'FFF3F4F6' } },
|
||||
right: { style: 'thin', color: { argb: 'FFF3F4F6' } }
|
||||
}
|
||||
}
|
||||
|
||||
const dataStyleAlt: Partial<ExcelJS.Style> = {
|
||||
...dataStyle,
|
||||
fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFFAFAFA' } } as ExcelJS.FillPattern
|
||||
}
|
||||
|
||||
const currencyFormat = '#,##0'
|
||||
const percentageFormat = '0.0"%"'
|
||||
|
||||
// ========== HELPER: STATUS STYLE ==========
|
||||
// Sehat → teks hijau gelap, background hijau muda
|
||||
// Tidak Sehat → teks merah gelap, background merah muda
|
||||
const getStatusStyle = (status: 'Sehat' | 'Tidak Sehat', isAlt: boolean): Partial<ExcelJS.Style> => {
|
||||
const baseStyle = isAlt ? dataStyleAlt : dataStyle
|
||||
if (status === 'Sehat') {
|
||||
return {
|
||||
...baseStyle,
|
||||
font: { bold: true, size: 11, color: { argb: 'FF166534' } }, // green-800
|
||||
fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFDCFCE7' } } as ExcelJS.FillPattern, // green-100
|
||||
alignment: { horizontal: 'center', vertical: 'middle' },
|
||||
border: dataStyle.border
|
||||
}
|
||||
}
|
||||
return {
|
||||
...baseStyle,
|
||||
font: { bold: true, size: 11, color: { argb: 'FF991B1B' } }, // red-800
|
||||
fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFFEE2E2' } } as ExcelJS.FillPattern, // red-100
|
||||
alignment: { horizontal: 'center', vertical: 'middle' },
|
||||
border: dataStyle.border
|
||||
}
|
||||
}
|
||||
|
||||
// Dummy HPP values — ganti dengan data real nantinya
|
||||
const DUMMY_STD_HPP = 30 // 30% — ganti dengan data real nantinya
|
||||
const DUMMY_REAL_HPP = 0 // 0% — ganti dengan kalkulasi real nantinya
|
||||
const getDummyStatus = (stdHpp: number, realHpp: number): 'Sehat' | 'Tidak Sehat' =>
|
||||
realHpp <= stdHpp ? 'Sehat' : 'Tidak Sehat'
|
||||
|
||||
export const generateExcel = async (params: ExcelGeneratorParams) => {
|
||||
const {
|
||||
outlet,
|
||||
profitLoss,
|
||||
products,
|
||||
paymentAnalytics,
|
||||
category,
|
||||
productSummary,
|
||||
categorySummary,
|
||||
filterType,
|
||||
selectedDate,
|
||||
dateRange
|
||||
} = params
|
||||
|
||||
const ExcelJS = await import('exceljs')
|
||||
const workbook = new ExcelJS.Workbook()
|
||||
|
||||
workbook.creator = outlet?.name || 'POS System'
|
||||
workbook.created = new Date()
|
||||
|
||||
// ============ SHEET 1: RINGKASAN ============
|
||||
const ws1 = workbook.addWorksheet('Ringkasan', {
|
||||
views: [{ showGridLines: false }]
|
||||
})
|
||||
|
||||
ws1.mergeCells('A1:B1')
|
||||
const titleCell = ws1.getCell('A1')
|
||||
titleCell.value = 'LAPORAN TRANSAKSI'
|
||||
titleCell.style = {
|
||||
font: { bold: true, size: 20, color: { argb: 'FF1F2937' } },
|
||||
alignment: { vertical: 'middle', horizontal: 'left' }
|
||||
}
|
||||
ws1.getRow(1).height = 30
|
||||
|
||||
ws1.getCell('A2').value = outlet?.name || ''
|
||||
ws1.getCell('A2').style = { ...subtitleStyle, font: { size: 12, color: { argb: 'FF4B5563' } } }
|
||||
ws1.getCell('A3').value = outlet?.address || ''
|
||||
ws1.getCell('A3').style = subtitleStyle
|
||||
ws1.getCell('A4').value = outlet?.phone || ''
|
||||
ws1.getCell('A4').style = subtitleStyle
|
||||
|
||||
ws1.getCell('A5').value = 'Periode:'
|
||||
ws1.getCell('B5').value = getReportPeriodText(params)
|
||||
ws1.getCell('A5').style = labelStyle
|
||||
ws1.getCell('B5').style = { font: { size: 11 } }
|
||||
|
||||
ws1.getCell('A7').value = 'RINGKASAN'
|
||||
ws1.getCell('A7').style = {
|
||||
font: { bold: true, size: 14, color: { argb: 'FF36175E' } },
|
||||
alignment: { vertical: 'middle', horizontal: 'left' }
|
||||
}
|
||||
|
||||
ws1.getCell('A8').value = 'Keterangan'
|
||||
ws1.getCell('B8').value = 'Jumlah (IDR)'
|
||||
ws1.getCell('A8').style = headerStyle
|
||||
ws1.getCell('B8').style = headerStyle
|
||||
ws1.getRow(8).height = 25
|
||||
|
||||
const summaryData = [
|
||||
['Total Penjualan', profitLoss?.summary.total_revenue || 0],
|
||||
['Total Diskon', profitLoss?.summary.total_discount || 0],
|
||||
['Total Pajak', profitLoss?.summary.total_tax || 0],
|
||||
['PB1', 0],
|
||||
['Service Charge', profitLoss?.summary.service_charge || 0]
|
||||
]
|
||||
|
||||
summaryData.forEach((row, idx) => {
|
||||
const rowNum = idx + 9
|
||||
ws1.getCell(`A${rowNum}`).value = row[0]
|
||||
ws1.getCell(`B${rowNum}`).value = row[1]
|
||||
const isAlt = idx % 2 === 1
|
||||
const baseStyle = isAlt ? dataStyleAlt : dataStyle
|
||||
ws1.getCell(`A${rowNum}`).style = { ...baseStyle, alignment: { horizontal: 'left' } }
|
||||
ws1.getCell(`B${rowNum}`).style = { ...baseStyle, alignment: { horizontal: 'right' }, numFmt: currencyFormat }
|
||||
ws1.getRow(rowNum).height = 22
|
||||
})
|
||||
|
||||
const totalRow = 9 + summaryData.length
|
||||
ws1.getCell(`A${totalRow}`).value = 'Total'
|
||||
ws1.getCell(`B${totalRow}`).value = profitLoss?.summary.total_revenue || 0
|
||||
ws1.getCell(`A${totalRow}`).style = { ...totalRowStyle, alignment: { horizontal: 'left' } }
|
||||
ws1.getCell(`B${totalRow}`).style = { ...totalRowStyle, alignment: { horizontal: 'right' }, numFmt: currencyFormat }
|
||||
ws1.getRow(totalRow).height = 25
|
||||
|
||||
const invoiceRow = totalRow + 2
|
||||
ws1.getCell(`A${invoiceRow}`).value = 'INVOICE'
|
||||
ws1.getCell(`A${invoiceRow}`).style = {
|
||||
font: { bold: true, size: 14, color: { argb: 'FF36175E' } },
|
||||
alignment: { vertical: 'middle', horizontal: 'left' }
|
||||
}
|
||||
|
||||
ws1.getCell(`A${invoiceRow + 1}`).value = 'Total Invoice'
|
||||
ws1.getCell(`B${invoiceRow + 1}`).value = profitLoss?.summary.total_orders || 0
|
||||
ws1.getCell(`A${invoiceRow + 1}`).style = { ...dataStyle, font: { bold: true } }
|
||||
ws1.getCell(`B${invoiceRow + 1}`).style = { ...dataStyle, alignment: { horizontal: 'right' }, font: { bold: true } }
|
||||
|
||||
ws1.getColumn(1).width = 28
|
||||
ws1.getColumn(2).width = 22
|
||||
|
||||
// ============ SHEET 2: METODE PEMBAYARAN ============
|
||||
const ws2 = workbook.addWorksheet('Metode Pembayaran', {
|
||||
views: [{ showGridLines: false }]
|
||||
})
|
||||
|
||||
ws2.mergeCells('A1:D1')
|
||||
const paymentTitle = ws2.getCell('A1')
|
||||
paymentTitle.value = 'RINGKASAN METODE PEMBAYARAN'
|
||||
paymentTitle.style = titleStyle
|
||||
ws2.getRow(1).height = 30
|
||||
|
||||
const paymentHeaders = ['Metode', 'Jumlah Order', 'Total Amount (IDR)', 'Persentase']
|
||||
paymentHeaders.forEach((header, idx) => {
|
||||
const cell = ws2.getCell(3, idx + 1)
|
||||
cell.value = header
|
||||
cell.style = headerStyle
|
||||
})
|
||||
ws2.getRow(3).height = 25
|
||||
|
||||
let paymentRow = 4
|
||||
paymentAnalytics?.data?.forEach((payment: any, idx: number) => {
|
||||
const isAlt = idx % 2 === 1
|
||||
const baseStyle = isAlt ? dataStyleAlt : dataStyle
|
||||
|
||||
ws2.getCell(paymentRow, 1).value = payment.payment_method_name
|
||||
ws2.getCell(paymentRow, 2).value = payment.order_count
|
||||
ws2.getCell(paymentRow, 3).value = payment.total_amount
|
||||
ws2.getCell(paymentRow, 4).value = (payment.percentage || 0) / 100
|
||||
|
||||
ws2.getCell(paymentRow, 1).style = { ...baseStyle, alignment: { horizontal: 'left' } }
|
||||
ws2.getCell(paymentRow, 2).style = { ...baseStyle, alignment: { horizontal: 'center' } }
|
||||
ws2.getCell(paymentRow, 3).style = { ...baseStyle, alignment: { horizontal: 'right' }, numFmt: currencyFormat }
|
||||
ws2.getCell(paymentRow, 4).style = { ...baseStyle, alignment: { horizontal: 'center' }, numFmt: percentageFormat }
|
||||
|
||||
ws2.getRow(paymentRow).height = 22
|
||||
paymentRow++
|
||||
})
|
||||
|
||||
ws2.getCell(paymentRow, 1).value = 'TOTAL'
|
||||
ws2.getCell(paymentRow, 2).value = paymentAnalytics?.summary.total_orders || 0
|
||||
ws2.getCell(paymentRow, 3).value = paymentAnalytics?.summary.total_amount || 0
|
||||
ws2.getCell(paymentRow, 4).value = ''
|
||||
ws2.getCell(paymentRow, 1).style = { ...totalRowStyle, alignment: { horizontal: 'left' } }
|
||||
ws2.getCell(paymentRow, 2).style = { ...totalRowStyle, alignment: { horizontal: 'center' } }
|
||||
ws2.getCell(paymentRow, 3).style = { ...totalRowStyle, alignment: { horizontal: 'right' }, numFmt: currencyFormat }
|
||||
ws2.getCell(paymentRow, 4).style = totalRowStyle
|
||||
ws2.getRow(paymentRow).height = 25
|
||||
|
||||
ws2.getColumn(1).width = 28
|
||||
ws2.getColumn(2).width = 16
|
||||
ws2.getColumn(3).width = 22
|
||||
ws2.getColumn(4).width = 16
|
||||
|
||||
// ============ SHEET 3: KATEGORI ============
|
||||
// + 3 kolom baru: % Standard HPP | % Realisasi HPP | Status
|
||||
const ws3 = workbook.addWorksheet('Kategori', {
|
||||
views: [{ showGridLines: false }]
|
||||
})
|
||||
|
||||
ws3.mergeCells('A1:F1')
|
||||
const categoryTitle = ws3.getCell('A1')
|
||||
categoryTitle.value = 'RINGKASAN KATEGORI'
|
||||
categoryTitle.style = titleStyle
|
||||
ws3.getRow(1).height = 30
|
||||
|
||||
const categoryHeaders = ['Nama', 'Qty', 'Pendapatan (IDR)', '% Standard HPP', '% Realisasi HPP', 'Status']
|
||||
categoryHeaders.forEach((header, idx) => {
|
||||
const cell = ws3.getCell(3, idx + 1)
|
||||
cell.value = header
|
||||
cell.style = headerStyle
|
||||
})
|
||||
ws3.getRow(3).height = 25
|
||||
|
||||
let categoryRow = 4
|
||||
category?.data?.forEach((cat: any, idx: number) => {
|
||||
const isAlt = idx % 2 === 1
|
||||
const baseStyle = isAlt ? dataStyleAlt : dataStyle
|
||||
const stdHpp = DUMMY_STD_HPP
|
||||
const realHpp = DUMMY_REAL_HPP
|
||||
const status = getDummyStatus(stdHpp, realHpp)
|
||||
|
||||
ws3.getCell(categoryRow, 1).value = cat.category_name
|
||||
ws3.getCell(categoryRow, 2).value = cat.total_quantity
|
||||
ws3.getCell(categoryRow, 3).value = cat.total_revenue
|
||||
ws3.getCell(categoryRow, 4).value = stdHpp // akan diformat sebagai persentase
|
||||
ws3.getCell(categoryRow, 5).value = realHpp
|
||||
ws3.getCell(categoryRow, 6).value = status
|
||||
|
||||
ws3.getCell(categoryRow, 1).style = { ...baseStyle, alignment: { horizontal: 'left' } }
|
||||
ws3.getCell(categoryRow, 2).style = { ...baseStyle, alignment: { horizontal: 'center' } }
|
||||
ws3.getCell(categoryRow, 3).style = { ...baseStyle, alignment: { horizontal: 'right' }, numFmt: currencyFormat }
|
||||
ws3.getCell(categoryRow, 4).style = { ...baseStyle, alignment: { horizontal: 'center' }, numFmt: '0.0"%"' }
|
||||
ws3.getCell(categoryRow, 5).style = { ...baseStyle, alignment: { horizontal: 'center' }, numFmt: '0.0"%"' }
|
||||
ws3.getCell(categoryRow, 6).style = getStatusStyle(status, isAlt)
|
||||
|
||||
ws3.getRow(categoryRow).height = 22
|
||||
categoryRow++
|
||||
})
|
||||
|
||||
// Total row (3 kolom baru dikosongkan)
|
||||
ws3.getCell(categoryRow, 1).value = 'TOTAL'
|
||||
ws3.getCell(categoryRow, 2).value = categorySummary.totalQuantity
|
||||
ws3.getCell(categoryRow, 3).value = categorySummary.totalRevenue
|
||||
ws3.getCell(categoryRow, 4).value = ''
|
||||
ws3.getCell(categoryRow, 5).value = ''
|
||||
ws3.getCell(categoryRow, 6).value = ''
|
||||
|
||||
ws3.getCell(categoryRow, 1).style = { ...totalRowStyle, alignment: { horizontal: 'left' } }
|
||||
ws3.getCell(categoryRow, 2).style = { ...totalRowStyle, alignment: { horizontal: 'center' } }
|
||||
ws3.getCell(categoryRow, 3).style = { ...totalRowStyle, alignment: { horizontal: 'right' }, numFmt: currencyFormat }
|
||||
ws3.getCell(categoryRow, 4).style = totalRowStyle
|
||||
ws3.getCell(categoryRow, 5).style = totalRowStyle
|
||||
ws3.getCell(categoryRow, 6).style = totalRowStyle
|
||||
ws3.getRow(categoryRow).height = 25
|
||||
|
||||
ws3.getColumn(1).width = 35
|
||||
ws3.getColumn(2).width = 12
|
||||
ws3.getColumn(3).width = 22
|
||||
ws3.getColumn(4).width = 18 // % Standard HPP
|
||||
ws3.getColumn(5).width = 18 // % Realisasi HPP
|
||||
ws3.getColumn(6).width = 16 // Status
|
||||
|
||||
// ============ SHEET 4: DETAIL PRODUK ============
|
||||
// + 3 kolom baru: % Standard HPP | % Realisasi HPP | Status
|
||||
const ws4 = workbook.addWorksheet('Detail Produk', {
|
||||
views: [{ showGridLines: false }]
|
||||
})
|
||||
|
||||
ws4.mergeCells('A1:F1')
|
||||
const productTitle = ws4.getCell('A1')
|
||||
productTitle.value = 'RINGKASAN ITEM PER KATEGORI'
|
||||
productTitle.style = titleStyle
|
||||
ws4.getRow(1).height = 30
|
||||
|
||||
const groupedProducts =
|
||||
products?.data?.reduce(
|
||||
(acc: any, item: any) => {
|
||||
const categoryName = item.category_name || 'Tidak Berkategori'
|
||||
if (!acc[categoryName]) acc[categoryName] = []
|
||||
acc[categoryName].push(item)
|
||||
return acc
|
||||
},
|
||||
{} as Record<string, any[]>
|
||||
) || {}
|
||||
|
||||
let currentRow = 3
|
||||
|
||||
Object.keys(groupedProducts)
|
||||
.sort((a, b) => {
|
||||
const orderA = groupedProducts[a][0]?.category_order ?? 999
|
||||
const orderB = groupedProducts[b][0]?.category_order ?? 999
|
||||
return orderA - orderB
|
||||
})
|
||||
.forEach((categoryName, index) => {
|
||||
// Category header — span 6 kolom
|
||||
ws4.mergeCells(`A${currentRow}:F${currentRow}`)
|
||||
const catHeader = ws4.getCell(`A${currentRow}`)
|
||||
catHeader.value = `${index + 1}. ${categoryName.toUpperCase()}`
|
||||
catHeader.style = {
|
||||
font: { bold: true, size: 13, color: { argb: 'FF36175E' } },
|
||||
fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFF9FAFB' } } as ExcelJS.FillPattern,
|
||||
alignment: { vertical: 'middle', horizontal: 'left' },
|
||||
border: {
|
||||
top: { style: 'thin', color: { argb: 'FFD1D5DB' } },
|
||||
left: { style: 'thin', color: { argb: 'FFD1D5DB' } },
|
||||
bottom: { style: 'thin', color: { argb: 'FFD1D5DB' } },
|
||||
right: { style: 'thin', color: { argb: 'FFD1D5DB' } }
|
||||
}
|
||||
}
|
||||
ws4.getRow(currentRow).height = 28
|
||||
currentRow++
|
||||
|
||||
// Column headers — 6 kolom
|
||||
const prodHeaders = ['Produk', 'Qty', 'Pendapatan (IDR)', '% Standard HPP', '% Realisasi HPP', 'Status']
|
||||
prodHeaders.forEach((header, idx) => {
|
||||
const cell = ws4.getCell(currentRow, idx + 1)
|
||||
cell.value = header
|
||||
cell.style = {
|
||||
font: { bold: true, size: 11, color: { argb: 'FFFFFFFF' } },
|
||||
fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF36175E' } } as ExcelJS.FillPattern,
|
||||
alignment: { vertical: 'middle', horizontal: 'center' },
|
||||
border: {
|
||||
top: { style: 'thin', color: { argb: 'FFD1D5DB' } },
|
||||
left: { style: 'thin', color: { argb: 'FFD1D5DB' } },
|
||||
bottom: { style: 'thin', color: { argb: 'FFD1D5DB' } },
|
||||
right: { style: 'thin', color: { argb: 'FFD1D5DB' } }
|
||||
}
|
||||
}
|
||||
})
|
||||
ws4.getRow(currentRow).height = 24
|
||||
currentRow++
|
||||
|
||||
const categoryProducts = groupedProducts[categoryName].sort((a: any, b: any) =>
|
||||
(a.product_sku || '').localeCompare(b.product_sku || '')
|
||||
)
|
||||
|
||||
categoryProducts.forEach((product: any, idx: number) => {
|
||||
const isAlt = idx % 2 === 1
|
||||
const baseStyle = isAlt ? dataStyleAlt : dataStyle
|
||||
const stdHpp = DUMMY_STD_HPP
|
||||
const realHpp = DUMMY_REAL_HPP
|
||||
const status = getDummyStatus(stdHpp, realHpp)
|
||||
|
||||
ws4.getCell(currentRow, 1).value = product.product_name
|
||||
ws4.getCell(currentRow, 2).value = product.quantity_sold
|
||||
ws4.getCell(currentRow, 3).value = product.revenue
|
||||
ws4.getCell(currentRow, 4).value = stdHpp
|
||||
ws4.getCell(currentRow, 5).value = realHpp
|
||||
ws4.getCell(currentRow, 6).value = status
|
||||
|
||||
ws4.getCell(currentRow, 1).style = { ...baseStyle, alignment: { horizontal: 'left' } }
|
||||
ws4.getCell(currentRow, 2).style = { ...baseStyle, alignment: { horizontal: 'center' } }
|
||||
ws4.getCell(currentRow, 3).style = { ...baseStyle, alignment: { horizontal: 'right' }, numFmt: currencyFormat }
|
||||
ws4.getCell(currentRow, 4).style = { ...baseStyle, alignment: { horizontal: 'center' }, numFmt: '0.0"%"' }
|
||||
ws4.getCell(currentRow, 5).style = { ...baseStyle, alignment: { horizontal: 'center' }, numFmt: '0.0"%"' }
|
||||
ws4.getCell(currentRow, 6).style = getStatusStyle(status, isAlt)
|
||||
|
||||
ws4.getRow(currentRow).height = 20
|
||||
currentRow++
|
||||
})
|
||||
|
||||
// Subtotal — 3 kolom baru dikosongkan
|
||||
const subQty = categoryProducts.reduce((sum: number, p: any) => sum + p.quantity_sold, 0)
|
||||
const subRevenue = categoryProducts.reduce((sum: number, p: any) => sum + p.revenue, 0)
|
||||
|
||||
const subtotalFill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFF3F4F6' } } as ExcelJS.FillPattern
|
||||
ws4.getCell(currentRow, 1).value = `Subtotal ${categoryName}`
|
||||
ws4.getCell(currentRow, 2).value = subQty
|
||||
ws4.getCell(currentRow, 3).value = subRevenue
|
||||
ws4.getCell(currentRow, 4).value = ''
|
||||
ws4.getCell(currentRow, 5).value = ''
|
||||
ws4.getCell(currentRow, 6).value = ''
|
||||
|
||||
ws4.getCell(currentRow, 1).style = { ...totalRowStyle, alignment: { horizontal: 'left' }, fill: subtotalFill }
|
||||
ws4.getCell(currentRow, 2).style = { ...totalRowStyle, alignment: { horizontal: 'center' }, fill: subtotalFill }
|
||||
ws4.getCell(currentRow, 3).style = {
|
||||
...totalRowStyle,
|
||||
alignment: { horizontal: 'right' },
|
||||
numFmt: currencyFormat,
|
||||
fill: subtotalFill
|
||||
}
|
||||
ws4.getCell(currentRow, 4).style = { ...totalRowStyle, fill: subtotalFill }
|
||||
ws4.getCell(currentRow, 5).style = { ...totalRowStyle, fill: subtotalFill }
|
||||
ws4.getCell(currentRow, 6).style = { ...totalRowStyle, fill: subtotalFill }
|
||||
|
||||
ws4.getRow(currentRow).height = 24
|
||||
currentRow += 3
|
||||
})
|
||||
|
||||
// Grand Total
|
||||
const grandFill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF36175E' } } as ExcelJS.FillPattern
|
||||
const grandFont = { bold: true, size: 13, color: { argb: 'FFFFFFFF' } }
|
||||
|
||||
ws4.getCell(currentRow, 1).value = 'TOTAL KESELURUHAN'
|
||||
ws4.getCell(currentRow, 2).value = productSummary.totalQuantitySold
|
||||
ws4.getCell(currentRow, 3).value = productSummary.totalRevenue
|
||||
ws4.getCell(currentRow, 4).value = ''
|
||||
ws4.getCell(currentRow, 5).value = ''
|
||||
ws4.getCell(currentRow, 6).value = ''
|
||||
|
||||
ws4.getCell(currentRow, 1).style = {
|
||||
...totalRowStyle,
|
||||
alignment: { horizontal: 'left' },
|
||||
font: grandFont,
|
||||
fill: grandFill
|
||||
}
|
||||
ws4.getCell(currentRow, 2).style = {
|
||||
...totalRowStyle,
|
||||
alignment: { horizontal: 'center' },
|
||||
font: grandFont,
|
||||
fill: grandFill
|
||||
}
|
||||
ws4.getCell(currentRow, 3).style = {
|
||||
...totalRowStyle,
|
||||
alignment: { horizontal: 'right' },
|
||||
numFmt: currencyFormat,
|
||||
font: grandFont,
|
||||
fill: grandFill
|
||||
}
|
||||
ws4.getCell(currentRow, 4).style = { ...totalRowStyle, font: grandFont, fill: grandFill }
|
||||
ws4.getCell(currentRow, 5).style = { ...totalRowStyle, font: grandFont, fill: grandFill }
|
||||
ws4.getCell(currentRow, 6).style = { ...totalRowStyle, font: grandFont, fill: grandFill }
|
||||
ws4.getRow(currentRow).height = 28
|
||||
|
||||
ws4.getColumn(1).width = 45
|
||||
ws4.getColumn(2).width = 12
|
||||
ws4.getColumn(3).width = 22
|
||||
ws4.getColumn(4).width = 18 // % Standard HPP
|
||||
ws4.getColumn(5).width = 18 // % Realisasi HPP
|
||||
ws4.getColumn(6).width = 16 // Status
|
||||
|
||||
// ============ GENERATE & DOWNLOAD FILE ============
|
||||
const fileName =
|
||||
filterType === 'single'
|
||||
? `laporan-transaksi-${formatDateForInput(selectedDate)}.xlsx`
|
||||
: `laporan-transaksi-${formatDateForInput(dateRange.startDate)}-to-${formatDateForInput(dateRange.endDate)}.xlsx`
|
||||
|
||||
const buffer = await workbook.xlsx.writeBuffer()
|
||||
const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
|
||||
const url = window.URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = fileName
|
||||
a.click()
|
||||
window.URL.revokeObjectURL(url)
|
||||
}
|
||||
@@ -0,0 +1,535 @@
|
||||
// pdfGenerator.ts
|
||||
import { formatCurrency } from '@/utils/transform'
|
||||
|
||||
// PDF Configuration
|
||||
const PDF_FONT_SIZES = {
|
||||
heading: 18,
|
||||
subheading: 16,
|
||||
tableContent: 12,
|
||||
tableHeader: 12,
|
||||
tableFooter: 12,
|
||||
grandTotal: 14,
|
||||
footer: 11
|
||||
}
|
||||
|
||||
const PDF_SPACING = {
|
||||
cellPadding: 5,
|
||||
cellPaddingLarge: 6,
|
||||
sectionGap: 20,
|
||||
headerGap: 15
|
||||
}
|
||||
|
||||
interface PDFGeneratorParams {
|
||||
reportRef: React.RefObject<HTMLDivElement>
|
||||
outlet: any
|
||||
profitLoss: any
|
||||
products: any
|
||||
paymentAnalytics: any
|
||||
category: any
|
||||
productSummary: {
|
||||
totalQuantitySold: number
|
||||
totalRevenue: number
|
||||
totalOrders: number
|
||||
}
|
||||
categorySummary: {
|
||||
totalRevenue: number
|
||||
orderCount: number
|
||||
productCount: number
|
||||
totalQuantity: number
|
||||
}
|
||||
filterType: 'single' | 'range'
|
||||
selectedDate: Date
|
||||
dateRange: { startDate: Date; endDate: Date }
|
||||
now: Date
|
||||
}
|
||||
|
||||
const formatDateForInput = (date: Date) => {
|
||||
return date.toISOString().split('T')[0]
|
||||
}
|
||||
|
||||
// Helper: tentukan warna status
|
||||
const getStatusColor = (status: string): [number, number, number] => {
|
||||
return status === 'Sehat' ? [22, 163, 74] : [220, 38, 38] // green-600 / red-600
|
||||
}
|
||||
|
||||
export const generatePDF = async (params: PDFGeneratorParams) => {
|
||||
const {
|
||||
reportRef,
|
||||
outlet,
|
||||
profitLoss,
|
||||
products,
|
||||
paymentAnalytics,
|
||||
category,
|
||||
productSummary,
|
||||
categorySummary,
|
||||
filterType,
|
||||
selectedDate,
|
||||
dateRange,
|
||||
now
|
||||
} = params
|
||||
|
||||
const reportElement = reportRef.current
|
||||
if (!reportElement) {
|
||||
throw new Error('Report element tidak ditemukan')
|
||||
}
|
||||
|
||||
// Dynamic imports
|
||||
const jsPDF = (await import('jspdf')).default
|
||||
const html2canvas = (await import('html2canvas')).default
|
||||
const autoTable = (await import('jspdf-autotable')).default
|
||||
|
||||
const pdf = new jsPDF({
|
||||
orientation: 'portrait',
|
||||
unit: 'mm',
|
||||
format: 'a4',
|
||||
compress: true
|
||||
})
|
||||
|
||||
// Capture header section
|
||||
const headerElement = reportElement.querySelector('.report-header-section') as HTMLElement
|
||||
if (headerElement) {
|
||||
const headerCanvas = await html2canvas(headerElement, {
|
||||
scale: 2,
|
||||
useCORS: true,
|
||||
backgroundColor: '#ffffff',
|
||||
logging: false,
|
||||
windowWidth: 794
|
||||
})
|
||||
|
||||
const headerImgWidth = 190
|
||||
const headerImgHeight = (headerCanvas.height * headerImgWidth) / headerCanvas.width
|
||||
const headerImgData = headerCanvas.toDataURL('image/jpeg', 0.95)
|
||||
|
||||
pdf.addImage(headerImgData, 'JPEG', 10, 10, headerImgWidth, headerImgHeight)
|
||||
}
|
||||
|
||||
let currentY = 80
|
||||
|
||||
// ========== RINGKASAN SECTION ==========
|
||||
pdf.setFontSize(PDF_FONT_SIZES.heading)
|
||||
pdf.setTextColor(54, 23, 94)
|
||||
pdf.setFont('helvetica', 'bold')
|
||||
pdf.text('Ringkasan', 14, currentY)
|
||||
currentY += 15
|
||||
|
||||
autoTable(pdf, {
|
||||
startY: currentY,
|
||||
head: [],
|
||||
body: [
|
||||
['Total Penjualan', formatCurrency(profitLoss?.summary.total_revenue ?? 0)],
|
||||
['Total Diskon', formatCurrency(profitLoss?.summary.total_discount ?? 0)],
|
||||
['Total Pajak', formatCurrency(profitLoss?.summary.total_tax ?? 0)],
|
||||
['Service Charge', formatCurrency(profitLoss?.summary.service_charge ?? 0)],
|
||||
['Total', formatCurrency(profitLoss?.summary.total_revenue ?? 0)]
|
||||
],
|
||||
theme: 'grid',
|
||||
styles: {
|
||||
fontSize: PDF_FONT_SIZES.subheading,
|
||||
cellPadding: PDF_SPACING.cellPadding,
|
||||
lineColor: [0, 0, 0]
|
||||
},
|
||||
columnStyles: {
|
||||
0: { fontStyle: 'normal', textColor: [60, 60, 60] },
|
||||
1: { halign: 'right', fontStyle: 'bold', textColor: [60, 60, 60] }
|
||||
},
|
||||
margin: { left: 14, right: 14 }
|
||||
})
|
||||
|
||||
currentY = (pdf as any).lastAutoTable.finalY + 20
|
||||
|
||||
// ========== INVOICE SECTION ==========
|
||||
pdf.setFontSize(PDF_FONT_SIZES.heading)
|
||||
pdf.text('Invoice', 14, currentY)
|
||||
currentY += 15
|
||||
|
||||
autoTable(pdf, {
|
||||
startY: currentY,
|
||||
head: [],
|
||||
body: [['Total Invoice', String(profitLoss?.summary.total_orders ?? 0)]],
|
||||
theme: 'grid',
|
||||
styles: {
|
||||
lineColor: [0, 0, 0],
|
||||
fontSize: PDF_FONT_SIZES.subheading,
|
||||
cellPadding: PDF_SPACING.cellPadding
|
||||
},
|
||||
columnStyles: {
|
||||
0: { fontStyle: 'normal', textColor: [60, 60, 60] },
|
||||
1: { halign: 'right', fontStyle: 'bold', textColor: [60, 60, 60] }
|
||||
},
|
||||
margin: { left: 14, right: 14 }
|
||||
})
|
||||
|
||||
pdf.addPage()
|
||||
currentY = 20
|
||||
|
||||
// ========== PAYMENT METHOD SECTION ==========
|
||||
pdf.setFontSize(PDF_FONT_SIZES.heading)
|
||||
pdf.text('Ringkasan Metode Pembayaran', 14, currentY)
|
||||
currentY += 15
|
||||
|
||||
const paymentBody =
|
||||
paymentAnalytics?.data?.map((payment: any) => [
|
||||
payment.payment_method_name,
|
||||
String(payment.order_count),
|
||||
formatCurrency(payment.total_amount),
|
||||
`${(payment.percentage ?? 0).toFixed(1)}%`
|
||||
]) || []
|
||||
|
||||
autoTable(pdf, {
|
||||
startY: currentY,
|
||||
head: [['Metode', 'Jumlah', 'Total', 'Persentase']],
|
||||
body: paymentBody,
|
||||
foot: [
|
||||
[
|
||||
'TOTAL',
|
||||
String(paymentAnalytics?.summary.total_orders ?? 0),
|
||||
formatCurrency(paymentAnalytics?.summary.total_amount ?? 0),
|
||||
''
|
||||
]
|
||||
],
|
||||
theme: 'grid',
|
||||
styles: {
|
||||
fontSize: PDF_FONT_SIZES.tableContent,
|
||||
cellPadding: PDF_SPACING.cellPadding,
|
||||
lineColor: [0, 0, 0],
|
||||
lineWidth: 0.1
|
||||
},
|
||||
headStyles: {
|
||||
fillColor: [54, 23, 94],
|
||||
textColor: 255,
|
||||
fontStyle: 'bold',
|
||||
fontSize: PDF_FONT_SIZES.tableHeader,
|
||||
lineColor: [0, 0, 0],
|
||||
lineWidth: 0.1
|
||||
},
|
||||
footStyles: {
|
||||
fillColor: [220, 220, 220],
|
||||
textColor: [60, 60, 60],
|
||||
fontStyle: 'bold',
|
||||
fontSize: PDF_FONT_SIZES.tableFooter,
|
||||
lineColor: [0, 0, 0],
|
||||
lineWidth: 0.1,
|
||||
halign: 'center'
|
||||
},
|
||||
columnStyles: {
|
||||
1: { halign: 'center' },
|
||||
2: { halign: 'right' },
|
||||
3: { halign: 'right' }
|
||||
},
|
||||
didParseCell: (data: any) => {
|
||||
if (data.section === 'foot') {
|
||||
if (data.column.index === 0) {
|
||||
data.cell.styles.halign = 'left'
|
||||
} else if (data.column.index === 1) {
|
||||
data.cell.styles.halign = 'center'
|
||||
} else if (data.column.index === 2) {
|
||||
data.cell.styles.halign = 'right'
|
||||
}
|
||||
}
|
||||
},
|
||||
margin: { left: 14, right: 14 }
|
||||
})
|
||||
|
||||
currentY = (pdf as any).lastAutoTable.finalY + 20
|
||||
|
||||
// ========== CATEGORY SECTION ==========
|
||||
// Kolom baru: % Standard HPP, % Realisasi HPP, Status — diisi dummy visual untuk saat ini
|
||||
pdf.setFontSize(PDF_FONT_SIZES.heading)
|
||||
pdf.text('Ringkasan Kategori', 14, currentY)
|
||||
currentY += 15
|
||||
|
||||
const DUMMY_STD_HPP = 30 // % (nilai dummy — ganti dengan data real nantinya)
|
||||
|
||||
const categoryBody =
|
||||
category?.data?.map((c: any) => {
|
||||
const stdHpp = DUMMY_STD_HPP
|
||||
const realisasiHpp = 0 // dummy — ganti dengan kalkulasi real
|
||||
const status = realisasiHpp <= stdHpp ? 'Sehat' : 'Tidak Sehat'
|
||||
return [
|
||||
c.category_name,
|
||||
String(c.total_quantity),
|
||||
formatCurrency(c.total_revenue),
|
||||
`${stdHpp}%`,
|
||||
`${realisasiHpp}%`,
|
||||
'' // dikosongkan — status digambar manual via didDrawCell agar tidak double
|
||||
]
|
||||
}) || []
|
||||
|
||||
// Simpan status per baris untuk dipakai di didDrawCell
|
||||
const categoryStatuses: string[] =
|
||||
category?.data?.map(() => {
|
||||
const realisasiHpp = 0
|
||||
return realisasiHpp <= DUMMY_STD_HPP ? 'Sehat' : 'Tidak Sehat'
|
||||
}) || []
|
||||
|
||||
autoTable(pdf, {
|
||||
startY: currentY,
|
||||
head: [['Nama', 'Qty', 'Pendapatan', '% Std HPP', '% Real HPP', 'Status']],
|
||||
body: categoryBody,
|
||||
foot: [
|
||||
[
|
||||
'TOTAL',
|
||||
String(categorySummary?.totalQuantity ?? 0),
|
||||
formatCurrency(categorySummary?.totalRevenue ?? 0),
|
||||
'',
|
||||
'',
|
||||
''
|
||||
]
|
||||
],
|
||||
theme: 'grid',
|
||||
showFoot: 'lastPage',
|
||||
tableWidth: 'auto',
|
||||
styles: {
|
||||
fontSize: 9,
|
||||
cellPadding: PDF_SPACING.cellPadding,
|
||||
lineColor: [0, 0, 0],
|
||||
lineWidth: 0.1
|
||||
},
|
||||
headStyles: {
|
||||
fillColor: [54, 23, 94],
|
||||
textColor: 255,
|
||||
fontStyle: 'bold',
|
||||
fontSize: 9,
|
||||
lineColor: [0, 0, 0],
|
||||
lineWidth: 0.1
|
||||
},
|
||||
footStyles: {
|
||||
fillColor: [220, 220, 220],
|
||||
textColor: [60, 60, 60],
|
||||
fontStyle: 'bold',
|
||||
fontSize: 9,
|
||||
lineColor: [0, 0, 0],
|
||||
lineWidth: 0.1
|
||||
},
|
||||
columnStyles: {
|
||||
1: { halign: 'center' },
|
||||
2: { halign: 'right' },
|
||||
3: { halign: 'center' },
|
||||
4: { halign: 'center' },
|
||||
5: { halign: 'center' }
|
||||
},
|
||||
didParseCell: (data: any) => {
|
||||
// Footer alignment
|
||||
if (data.section === 'foot') {
|
||||
if (data.column.index === 0) data.cell.styles.halign = 'left'
|
||||
else if (data.column.index === 1) data.cell.styles.halign = 'center'
|
||||
else if (data.column.index === 2) data.cell.styles.halign = 'right'
|
||||
}
|
||||
// Paksa teks status tidak dirender oleh autoTable (set textColor = white)
|
||||
if (data.section === 'body' && data.column.index === 5) {
|
||||
data.cell.styles.textColor = [255, 255, 255]
|
||||
}
|
||||
},
|
||||
didDrawCell: (data: any) => {
|
||||
if (data.section === 'body' && data.column.index === 5) {
|
||||
const status = categoryStatuses[data.row.index] || 'Sehat'
|
||||
const color = getStatusColor(status)
|
||||
pdf.setTextColor(...color)
|
||||
pdf.setFontSize(9)
|
||||
pdf.setFont('helvetica', 'bold')
|
||||
pdf.text(status, data.cell.x + data.cell.width / 2, data.cell.y + data.cell.height / 2 + 1, { align: 'center' })
|
||||
pdf.setTextColor(0, 0, 0)
|
||||
pdf.setFont('helvetica', 'normal')
|
||||
}
|
||||
},
|
||||
margin: { left: 14, right: 14 }
|
||||
})
|
||||
|
||||
currentY = (pdf as any).lastAutoTable.finalY + 20
|
||||
|
||||
// ========== PRODUCT DETAILS BY CATEGORY ==========
|
||||
const groupedProducts =
|
||||
products?.data?.reduce(
|
||||
(acc: any, item: any) => {
|
||||
const categoryName = item.category_name || 'Tidak Berkategori'
|
||||
if (!acc[categoryName]) {
|
||||
acc[categoryName] = []
|
||||
}
|
||||
acc[categoryName].push(item)
|
||||
return acc
|
||||
},
|
||||
{} as Record<string, any[]>
|
||||
) || {}
|
||||
|
||||
pdf.addPage()
|
||||
currentY = 20
|
||||
|
||||
pdf.setFontSize(PDF_FONT_SIZES.heading)
|
||||
pdf.text('Ringkasan Item Per Kategori', 14, currentY)
|
||||
currentY += 10
|
||||
|
||||
Object.keys(groupedProducts)
|
||||
.sort((a, b) => {
|
||||
const productsA = groupedProducts[a]
|
||||
const productsB = groupedProducts[b]
|
||||
const orderA = productsA[0]?.category_order ?? 999
|
||||
const orderB = productsB[0]?.category_order ?? 999
|
||||
return orderA - orderB
|
||||
})
|
||||
.forEach((categoryName, index) => {
|
||||
const categoryProducts = groupedProducts[categoryName].sort((a: any, b: any) => {
|
||||
const skuA = a.product_sku || ''
|
||||
const skuB = b.product_sku || ''
|
||||
return skuA.localeCompare(skuB)
|
||||
})
|
||||
|
||||
const categoryTotalQty = categoryProducts.reduce((sum: number, item: any) => sum + (item.quantity_sold || 0), 0)
|
||||
const categoryTotalRevenue = categoryProducts.reduce((sum: number, item: any) => sum + (item.revenue || 0), 0)
|
||||
|
||||
// Kolom baru: % Standard HPP, % Realisasi HPP, Status — dummy visual
|
||||
const productBody = categoryProducts.map((item: any) => {
|
||||
const stdHpp = 0 // dummy — ganti dengan data real
|
||||
const realisasiHpp = 0 // dummy — ganti dengan kalkulasi real
|
||||
return [
|
||||
item.product_name,
|
||||
String(item.quantity_sold),
|
||||
formatCurrency(item.revenue),
|
||||
`${stdHpp}%`,
|
||||
`${realisasiHpp}%`,
|
||||
'' // dikosongkan — status digambar manual via didDrawCell agar tidak double
|
||||
]
|
||||
})
|
||||
|
||||
// Status per baris produk
|
||||
const productStatuses: string[] = categoryProducts.map(() => (0 <= 0 ? 'Sehat' : 'Tidak Sehat'))
|
||||
|
||||
const estimatedHeight = (productBody.length + 3) * 12
|
||||
if (currentY + estimatedHeight > 270) {
|
||||
pdf.addPage()
|
||||
currentY = 20
|
||||
}
|
||||
|
||||
pdf.setFontSize(PDF_FONT_SIZES.subheading)
|
||||
pdf.setFont('helvetica', 'bold')
|
||||
pdf.setTextColor(54, 23, 94)
|
||||
pdf.text(`${index + 1}. ${categoryName.toUpperCase()}`, 16, currentY)
|
||||
currentY += 15
|
||||
|
||||
autoTable(pdf, {
|
||||
startY: currentY,
|
||||
head: [['Produk', 'Qty', 'Pendapatan', '% Std HPP', '% Real HPP', 'Status']],
|
||||
body: productBody,
|
||||
foot: [
|
||||
[`Subtotal ${categoryName}`, String(categoryTotalQty), formatCurrency(categoryTotalRevenue), '', '', '']
|
||||
],
|
||||
showFoot: 'lastPage',
|
||||
theme: 'grid',
|
||||
styles: {
|
||||
fontSize: 9,
|
||||
cellPadding: PDF_SPACING.cellPadding,
|
||||
lineColor: [0, 0, 0],
|
||||
lineWidth: 0.1
|
||||
},
|
||||
headStyles: {
|
||||
fillColor: [54, 23, 94],
|
||||
textColor: 255,
|
||||
fontStyle: 'bold',
|
||||
fontSize: 9,
|
||||
lineColor: [0, 0, 0],
|
||||
lineWidth: 0.1
|
||||
},
|
||||
footStyles: {
|
||||
fillColor: [200, 200, 200],
|
||||
textColor: [60, 60, 60],
|
||||
fontStyle: 'bold',
|
||||
fontSize: 9,
|
||||
lineColor: [0, 0, 0],
|
||||
lineWidth: 0.1
|
||||
},
|
||||
columnStyles: {
|
||||
0: { cellWidth: 44 },
|
||||
1: { halign: 'center', cellWidth: 20 },
|
||||
2: { halign: 'right', cellWidth: 50 },
|
||||
3: { halign: 'center', cellWidth: 22 },
|
||||
4: { halign: 'center', cellWidth: 22 },
|
||||
5: { halign: 'center', cellWidth: 22 }
|
||||
},
|
||||
didParseCell: (data: any) => {
|
||||
if (data.section === 'foot') {
|
||||
if (data.column.index === 0) data.cell.styles.halign = 'left'
|
||||
else if (data.column.index === 1) data.cell.styles.halign = 'center'
|
||||
else if (data.column.index === 2) data.cell.styles.halign = 'right'
|
||||
}
|
||||
// Paksa teks status tidak dirender oleh autoTable (set textColor = white)
|
||||
if (data.section === 'body' && data.column.index === 5) {
|
||||
data.cell.styles.textColor = [255, 255, 255]
|
||||
}
|
||||
},
|
||||
didDrawCell: (data: any) => {
|
||||
// Warna teks Status (kolom index 5) — ambil dari array, bukan cell.text agar tidak double
|
||||
if (data.section === 'body' && data.column.index === 5) {
|
||||
const status = productStatuses[data.row.index] || 'Sehat'
|
||||
const color = getStatusColor(status)
|
||||
pdf.setTextColor(...color)
|
||||
pdf.setFontSize(9)
|
||||
pdf.setFont('helvetica', 'bold')
|
||||
pdf.text(status, data.cell.x + data.cell.width / 2, data.cell.y + data.cell.height / 2 + 1, {
|
||||
align: 'center'
|
||||
})
|
||||
pdf.setTextColor(0, 0, 0)
|
||||
pdf.setFont('helvetica', 'normal')
|
||||
}
|
||||
},
|
||||
margin: { left: 14, right: 14 }
|
||||
})
|
||||
|
||||
currentY = (pdf as any).lastAutoTable.finalY + 15
|
||||
})
|
||||
|
||||
// ========== GRAND TOTAL ==========
|
||||
if (currentY > 250) {
|
||||
pdf.addPage()
|
||||
currentY = 20
|
||||
}
|
||||
|
||||
autoTable(pdf, {
|
||||
startY: currentY,
|
||||
head: [],
|
||||
body: [
|
||||
[
|
||||
'TOTAL KESELURUHAN',
|
||||
String(productSummary.totalQuantitySold),
|
||||
formatCurrency(productSummary.totalRevenue),
|
||||
'',
|
||||
'',
|
||||
''
|
||||
]
|
||||
],
|
||||
theme: 'grid',
|
||||
styles: {
|
||||
fontSize: PDF_FONT_SIZES.grandTotal,
|
||||
cellPadding: 6,
|
||||
fontStyle: 'bold',
|
||||
textColor: [54, 23, 94],
|
||||
lineColor: [0, 0, 0],
|
||||
lineWidth: 0.2
|
||||
},
|
||||
columnStyles: {
|
||||
0: { cellWidth: 44 },
|
||||
1: { halign: 'center', cellWidth: 20 },
|
||||
2: { halign: 'right', cellWidth: 50 },
|
||||
3: { cellWidth: 22 },
|
||||
4: { cellWidth: 22 },
|
||||
5: { cellWidth: 22 }
|
||||
},
|
||||
margin: { left: 14, right: 14 }
|
||||
})
|
||||
|
||||
// ========== FOOTER ==========
|
||||
const pageCount = pdf.getNumberOfPages()
|
||||
for (let i = 1; i <= pageCount; i++) {
|
||||
pdf.setPage(i)
|
||||
pdf.setFontSize(11)
|
||||
pdf.setTextColor(120, 120, 120)
|
||||
pdf.text('© 2025 Apskel - Sistem POS Terpadu', 14, 287)
|
||||
pdf.text(`Dicetak pada: ${now.toLocaleDateString('id-ID')}`, 190, 287, { align: 'right' })
|
||||
}
|
||||
|
||||
// ========== SAVE PDF ==========
|
||||
const fileName =
|
||||
filterType === 'single'
|
||||
? `laporan-transaksi-${formatDateForInput(selectedDate)}.pdf`
|
||||
: `laporan-transaksi-${formatDateForInput(dateRange.startDate)}-to-${formatDateForInput(dateRange.endDate)}.pdf`
|
||||
|
||||
pdf.save(fileName)
|
||||
}
|
||||
@@ -43,6 +43,15 @@ export const formatDateDDMMYYYY = (dateString: Date | string) => {
|
||||
return `${day}-${month}-${year}`
|
||||
}
|
||||
|
||||
export const formatDateYYYYMMDD = (dateString: Date | string) => {
|
||||
const date = new Date(dateString)
|
||||
date.setHours(0, 0, 0, 0)
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const year = date.getFullYear()
|
||||
return `${year}-${month}-${day}`
|
||||
}
|
||||
|
||||
export const formatForInputDate = (dateString: Date | string) => {
|
||||
const date = new Date(dateString)
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
@@ -51,7 +60,6 @@ export const formatForInputDate = (dateString: Date | string) => {
|
||||
return `${year}-${month}-${day}`
|
||||
}
|
||||
|
||||
|
||||
export const formatDatetime = (dateString: string | number | Date) => {
|
||||
const date = new Date(dateString)
|
||||
|
||||
|
||||
@@ -0,0 +1,396 @@
|
||||
// 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'
|
||||
|
||||
// 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'
|
||||
import { AccountRequest } from '@/services/queries/chartOfAccountType'
|
||||
import { useChartOfAccount } from '@/services/queries/chartOfAccount'
|
||||
import { Account, ChartOfAccount } from '@/types/services/chartOfAccount'
|
||||
import { useAccountsMutation } from '@/services/mutations/account'
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
handleClose: () => void
|
||||
accountData?: Account[]
|
||||
setData: (data: Account[]) => void
|
||||
editingAccount?: Account | null
|
||||
}
|
||||
|
||||
type FormValidateType = {
|
||||
name: string
|
||||
code: string
|
||||
account_type: string
|
||||
opening_balance: number
|
||||
description: string
|
||||
chart_of_account_id: string
|
||||
}
|
||||
|
||||
// Vars
|
||||
const initialData = {
|
||||
name: '',
|
||||
code: '',
|
||||
account_type: '',
|
||||
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) => {
|
||||
// Props
|
||||
const { open, handleClose, accountData, setData, editingAccount } = props
|
||||
|
||||
// Determine if we're editing
|
||||
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
|
||||
const {
|
||||
control,
|
||||
reset: resetForm,
|
||||
handleSubmit,
|
||||
formState: { errors }
|
||||
} = useForm<FormValidateType>({
|
||||
defaultValues: initialData
|
||||
})
|
||||
|
||||
// Reset form when editingAccount changes or drawer opens
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
if (editingAccount) {
|
||||
// Populate form with existing data
|
||||
resetForm({
|
||||
name: editingAccount.name,
|
||||
code: editingAccount.number,
|
||||
account_type: editingAccount.account_type,
|
||||
opening_balance: editingAccount.opening_balance,
|
||||
description: editingAccount.description || '',
|
||||
chart_of_account_id: editingAccount.chart_of_account_id
|
||||
})
|
||||
} else {
|
||||
// Reset to initial data for new account
|
||||
resetForm(initialData)
|
||||
}
|
||||
}
|
||||
}, [editingAccount, open, resetForm])
|
||||
|
||||
const onSubmit = (data: FormValidateType) => {
|
||||
if (isEdit && editingAccount) {
|
||||
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
|
||||
}
|
||||
updateAccount.mutate(
|
||||
{ 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const handleReset = () => {
|
||||
handleClose()
|
||||
resetForm(initialData)
|
||||
}
|
||||
|
||||
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'>{isEdit ? 'Edit Akun' : 'Tambah Akun 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='account-form' onSubmit={handleSubmit(data => onSubmit(data))}>
|
||||
<div className='flex flex-col gap-6 p-6'>
|
||||
{/* Nama */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Nama <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='name'
|
||||
control={control}
|
||||
rules={{ required: true }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='Nama'
|
||||
{...(errors.name && { error: true, helperText: 'Field ini wajib diisi.' })}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Kode */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Kode <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='code'
|
||||
control={control}
|
||||
rules={{ required: true }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='Kode'
|
||||
{...(errors.code && { error: true, helperText: 'Field ini wajib diisi.' })}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Tipe Akun */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Tipe Akun <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='account_type'
|
||||
control={control}
|
||||
rules={{ required: true }}
|
||||
render={({ field: { onChange, value, ...field } }) => (
|
||||
<CustomAutocomplete
|
||||
{...field}
|
||||
options={accountTypeOptions}
|
||||
value={accountTypeOptions.find(option => option.code === value) || null}
|
||||
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 => (
|
||||
<CustomTextField
|
||||
{...params}
|
||||
placeholder='Pilih tipe akun'
|
||||
{...(errors.account_type && { error: true, helperText: 'Field ini wajib diisi.' })}
|
||||
/>
|
||||
)}
|
||||
isOptionEqualToValue={(option, value) => option.code === value.code}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Chart of Account */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Chart of Account <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='chart_of_account_id'
|
||||
control={control}
|
||||
rules={{ required: true }}
|
||||
render={({ field: { onChange, value, ...field } }) => (
|
||||
<CustomAutocomplete
|
||||
{...field}
|
||||
loading={isLoadingAccounts}
|
||||
options={chartOfAccountOptions}
|
||||
value={chartOfAccountOptions.find(option => option.id === value) || null}
|
||||
onChange={(_, newValue) => onChange(newValue?.id || '')}
|
||||
getOptionLabel={option => `${option.code} - ${option.name}`}
|
||||
renderOption={(props, option) => (
|
||||
<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>
|
||||
|
||||
{/* 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>
|
||||
</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='account-form'>
|
||||
{isEdit ? 'Update' : 'Simpan'}
|
||||
</Button>
|
||||
<Button variant='tonal' color='error' onClick={() => handleReset()}>
|
||||
Batal
|
||||
</Button>
|
||||
</div>
|
||||
</Box>
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
|
||||
export default AccountFormDrawer
|
||||
@@ -0,0 +1,432 @@
|
||||
'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 IconButton from '@mui/material/IconButton'
|
||||
import MenuItem from '@mui/material/MenuItem'
|
||||
import { styled } from '@mui/material/styles'
|
||||
import type { TextFieldProps } from '@mui/material/TextField'
|
||||
import Typography from '@mui/material/Typography'
|
||||
|
||||
// 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 CustomTextField from '@core/components/mui/TextField'
|
||||
import OptionMenu from '@core/components/option-menu'
|
||||
|
||||
// Style Imports
|
||||
import tableStyles from '@core/styles/table.module.css'
|
||||
import { Box, CircularProgress, TablePagination } from '@mui/material'
|
||||
import { useDispatch } from 'react-redux'
|
||||
import TablePaginationComponent from '@/components/TablePaginationComponent'
|
||||
import Loading from '@/components/layout/shared/Loading'
|
||||
import { getLocalizedUrl } from '@/utils/i18n'
|
||||
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
|
||||
export type AccountType = {
|
||||
id: number
|
||||
code: string
|
||||
name: string
|
||||
category: string
|
||||
balance: string
|
||||
}
|
||||
|
||||
declare module '@tanstack/table-core' {
|
||||
interface FilterFns {
|
||||
fuzzy: FilterFn<unknown>
|
||||
}
|
||||
interface FilterMeta {
|
||||
itemRank: RankingInfo
|
||||
}
|
||||
}
|
||||
|
||||
type AccountTypeWithAction = Account & {
|
||||
actions?: 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)} />
|
||||
}
|
||||
|
||||
// Category color mapping for Accounts
|
||||
const getCategoryColor = (category: string) => {
|
||||
switch (category) {
|
||||
case 'Kas & Bank':
|
||||
return 'success'
|
||||
case 'Piutang':
|
||||
return 'info'
|
||||
case 'Persediaan':
|
||||
return 'warning'
|
||||
case 'Aset Tetap':
|
||||
return 'primary'
|
||||
case 'Hutang':
|
||||
return 'error'
|
||||
case 'Ekuitas':
|
||||
return 'secondary'
|
||||
case 'Pendapatan':
|
||||
return 'success'
|
||||
case 'Beban':
|
||||
return 'error'
|
||||
default:
|
||||
return 'default'
|
||||
}
|
||||
}
|
||||
|
||||
// Column Definitions
|
||||
const columnHelper = createColumnHelper<AccountTypeWithAction>()
|
||||
|
||||
const AccountListTable = () => {
|
||||
const dispatch = useDispatch()
|
||||
|
||||
// States
|
||||
const [addAccountOpen, setAddAccountOpen] = useState(false)
|
||||
const [rowSelection, setRowSelection] = useState({})
|
||||
const [currentPage, setCurrentPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(10)
|
||||
const [openConfirm, setOpenConfirm] = useState(false)
|
||||
const [accountId, setAccountId] = useState('')
|
||||
const [search, setSearch] = useState('')
|
||||
const [categoryFilter, setCategoryFilter] = useState<string>('Semua')
|
||||
const [editingAccount, setEditingAccount] = useState<Account | null>(null)
|
||||
|
||||
const { data, isLoading } = useAccounts({
|
||||
page: currentPage,
|
||||
limit: pageSize,
|
||||
search
|
||||
})
|
||||
|
||||
// Hooks
|
||||
const { lang: locale } = useParams()
|
||||
|
||||
const accounts = data?.data ?? []
|
||||
const totalCount = data?.total ?? 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(0)
|
||||
}, [])
|
||||
|
||||
// Handle row click for edit
|
||||
const handleRowClick = (account: Account, event: React.MouseEvent) => {
|
||||
// Don't trigger row click if clicking on checkbox or link
|
||||
const target = event.target as HTMLElement
|
||||
if (target.closest('input[type="checkbox"]') || target.closest('a') || target.closest('button')) {
|
||||
return
|
||||
}
|
||||
|
||||
setEditingAccount(account)
|
||||
setAddAccountOpen(true)
|
||||
}
|
||||
|
||||
// Handle closing drawer and reset editing state
|
||||
const handleCloseDrawer = () => {
|
||||
setAddAccountOpen(false)
|
||||
setEditingAccount(null)
|
||||
}
|
||||
|
||||
const columns = useMemo<ColumnDef<AccountTypeWithAction, 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('number', {
|
||||
header: 'Kode Akun',
|
||||
cell: ({ row }) => (
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
className='p-0 min-w-0 font-medium normal-case justify-start'
|
||||
onClick={() => {
|
||||
setEditingAccount(row.original)
|
||||
setAddAccountOpen(true)
|
||||
}}
|
||||
sx={{
|
||||
textTransform: 'none',
|
||||
fontWeight: 500,
|
||||
'&:hover': {
|
||||
textDecoration: 'underline',
|
||||
backgroundColor: 'transparent'
|
||||
}
|
||||
}}
|
||||
>
|
||||
{row.original.number}
|
||||
</Button>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('name', {
|
||||
header: 'Nama Akun',
|
||||
cell: ({ row }) => (
|
||||
<Typography color='text.primary' className='font-medium'>
|
||||
{row.original.name}
|
||||
</Typography>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('chart_of_account.name', {
|
||||
header: 'Kategori',
|
||||
cell: ({ row }) => (
|
||||
<Typography color='text.primary' className='font-medium'>
|
||||
{row.original.chart_of_account.name}
|
||||
</Typography>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('current_balance', {
|
||||
header: 'Saldo',
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<Typography className='font-medium text-right text-primary'>
|
||||
{row.original.current_balance < 0 ? '-' : ''}
|
||||
{formatCurrency(row.original.current_balance)}
|
||||
</Typography>
|
||||
)
|
||||
}
|
||||
})
|
||||
],
|
||||
[locale]
|
||||
)
|
||||
|
||||
const table = useReactTable({
|
||||
data: accounts as Account[],
|
||||
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>
|
||||
<div className='flex justify-between flex-col items-start md:flex-row md:items-center p-6 border-bs gap-4'>
|
||||
<DebouncedInput
|
||||
value={search}
|
||||
onChange={value => setSearch(value as string)}
|
||||
placeholder='Cari Akun'
|
||||
className='max-sm:is-full'
|
||||
/>
|
||||
<div className='flex flex-col sm:flex-row max-sm:is-full items-start sm:items-center gap-4'>
|
||||
<CustomTextField
|
||||
select
|
||||
value={pageSize}
|
||||
onChange={handlePageSizeChange}
|
||||
className='max-sm:is-full sm:is-[70px]'
|
||||
>
|
||||
<MenuItem value={10}>10</MenuItem>
|
||||
<MenuItem value={25}>25</MenuItem>
|
||||
<MenuItem value={50}>50</MenuItem>
|
||||
</CustomTextField>
|
||||
<Button
|
||||
color='secondary'
|
||||
variant='tonal'
|
||||
startIcon={<i className='tabler-upload' />}
|
||||
className='max-sm:is-full'
|
||||
>
|
||||
Ekspor
|
||||
</Button>
|
||||
<Button
|
||||
variant='contained'
|
||||
className='max-sm:is-full is-auto'
|
||||
startIcon={<i className='tabler-plus' />}
|
||||
onClick={() => {
|
||||
setEditingAccount(null)
|
||||
setAddAccountOpen(true)
|
||||
}}
|
||||
>
|
||||
Tambah Akun
|
||||
</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>
|
||||
{accounts.length === 0 ? (
|
||||
<tbody>
|
||||
<tr>
|
||||
<td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
|
||||
Tidak ada data tersedia
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
) : (
|
||||
<tbody>
|
||||
{table.getRowModel().rows.map(row => {
|
||||
return (
|
||||
<tr
|
||||
key={row.id}
|
||||
className={classnames({
|
||||
selected: row.getIsSelected(),
|
||||
'cursor-pointer hover:bg-gray-50': true
|
||||
})}
|
||||
onClick={e => handleRowClick(row.original, e)}
|
||||
>
|
||||
{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>
|
||||
<AccountFormDrawer
|
||||
open={addAccountOpen}
|
||||
handleClose={handleCloseDrawer}
|
||||
accountData={accounts}
|
||||
setData={() => {}}
|
||||
editingAccount={editingAccount}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default AccountListTable
|
||||
@@ -0,0 +1,19 @@
|
||||
// MUI Imports
|
||||
import Grid from '@mui/material/Grid2'
|
||||
|
||||
// Type Imports
|
||||
|
||||
// Component Imports
|
||||
import AccountListTable from './AccountListTable'
|
||||
|
||||
const AccountList = () => {
|
||||
return (
|
||||
<Grid container spacing={6}>
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<AccountListTable />
|
||||
</Grid>
|
||||
</Grid>
|
||||
)
|
||||
}
|
||||
|
||||
export default AccountList
|
||||
@@ -13,6 +13,7 @@ import Button from '@mui/material/Button'
|
||||
|
||||
// Third-party Imports
|
||||
import type { ApexOptions } from 'apexcharts'
|
||||
import Link from 'next/link'
|
||||
|
||||
// Styled Component Imports
|
||||
const AppReactApexCharts = dynamic(() => import('@/libs/styles/AppReactApexCharts'))
|
||||
@@ -36,7 +37,7 @@ interface CashBankCardProps {
|
||||
categories: string[]
|
||||
buttonText?: string
|
||||
buttonIcon?: string
|
||||
onButtonClick?: () => void
|
||||
href?: string
|
||||
chartColor?: string
|
||||
height?: number
|
||||
currency?: 'IDR' | 'USD' | 'EUR'
|
||||
@@ -51,7 +52,7 @@ const CashBankCard = ({
|
||||
balances,
|
||||
chartData,
|
||||
categories,
|
||||
onButtonClick,
|
||||
href,
|
||||
chartColor = '#ff6b9d',
|
||||
height = 300,
|
||||
currency = 'IDR',
|
||||
@@ -220,7 +221,8 @@ const CashBankCard = ({
|
||||
<Button
|
||||
variant='contained'
|
||||
size='small'
|
||||
onClick={onButtonClick}
|
||||
component={Link}
|
||||
href={href}
|
||||
className='bg-primary '
|
||||
sx={{
|
||||
textTransform: 'none',
|
||||
|
||||
@@ -11,10 +11,18 @@ import FormControl from '@mui/material/FormControl'
|
||||
import InputLabel from '@mui/material/InputLabel'
|
||||
import Select from '@mui/material/Select'
|
||||
import MenuItem from '@mui/material/MenuItem'
|
||||
import CircularProgress from '@mui/material/CircularProgress'
|
||||
import CashBankCard from './CashBankCard' // Adjust import path as needed
|
||||
import CustomTextField from '@/@core/components/mui/TextField'
|
||||
import { getLocalizedUrl } from '@/utils/i18n'
|
||||
import { Locale } from '@/configs/i18n'
|
||||
import { useParams } from 'next/navigation'
|
||||
import AccountFormDrawer from '../account/AccountFormDrawer'
|
||||
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 {
|
||||
id: string
|
||||
title: string
|
||||
@@ -35,188 +43,28 @@ interface BankAccount {
|
||||
status: 'active' | 'inactive' | 'blocked'
|
||||
}
|
||||
|
||||
// Dummy Data
|
||||
const dummyAccounts: BankAccount[] = [
|
||||
{
|
||||
id: '1',
|
||||
title: 'Giro',
|
||||
accountNumber: '1-10003',
|
||||
balances: [
|
||||
{ amount: '7.313.321', label: 'Saldo di bank' },
|
||||
{ amount: '30.631.261', label: 'Saldo di kledo' }
|
||||
],
|
||||
chartData: [
|
||||
{
|
||||
name: 'Saldo',
|
||||
data: [
|
||||
20000000, 21000000, 20500000, 20800000, 21500000, 22000000, 25000000, 26000000, 28000000, 29000000, 30000000,
|
||||
31000000
|
||||
]
|
||||
}
|
||||
],
|
||||
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'
|
||||
// Static chart data for fallback/demo purposes
|
||||
const generateChartData = (accountType: string, balance: number) => {
|
||||
const baseValue = balance || 1000000
|
||||
const variation = baseValue * 0.2
|
||||
|
||||
return Array.from({ length: 12 }, (_, i) => {
|
||||
const randomVariation = (Math.random() - 0.5) * variation
|
||||
return Math.max(baseValue + randomVariation, baseValue * 0.5)
|
||||
})
|
||||
}
|
||||
|
||||
const getChartColor = (accountType: string) => {
|
||||
const colors = {
|
||||
giro: '#ff6b9d',
|
||||
savings: '#4285f4',
|
||||
investment: '#00bcd4',
|
||||
credit: '#ff9800',
|
||||
cash: '#4caf50'
|
||||
}
|
||||
]
|
||||
return colors[accountType as keyof typeof colors] || '#757575'
|
||||
}
|
||||
|
||||
const DebouncedInput = ({
|
||||
value: initialValue,
|
||||
onChange,
|
||||
@@ -245,81 +93,239 @@ const DebouncedInput = ({
|
||||
|
||||
return <CustomTextField {...props} value={value} onChange={e => setValue(e.target.value)} />
|
||||
}
|
||||
|
||||
const CashBankList = () => {
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const [editingAccount, setEditingAccount] = useState<Account | null>(null)
|
||||
const [addAccountOpen, setAddAccountOpen] = useState(false)
|
||||
const [data, setData] = useState<Account[]>([])
|
||||
const { lang: locale } = useParams()
|
||||
|
||||
// Handle button clicks
|
||||
const handleAccountAction = (accountId: string, action: string) => {
|
||||
console.log(`Action: ${action} for account: ${accountId}`)
|
||||
// Implement your action logic here
|
||||
// Use the accounts hook with search parameter
|
||||
const { data: accountsResponse, isLoading } = useAccounts({
|
||||
page: 1,
|
||||
limit: 10,
|
||||
search: searchQuery
|
||||
})
|
||||
|
||||
const handleCloseDrawer = () => {
|
||||
setAddAccountOpen(false)
|
||||
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(() => {
|
||||
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 =
|
||||
account.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||
account.accountNumber.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||
account.bank.toLowerCase().includes(searchQuery.toLowerCase())
|
||||
return matchesSearch
|
||||
})
|
||||
}, [searchQuery])
|
||||
}, [transformedAccounts, searchQuery, accountsResponse])
|
||||
|
||||
return (
|
||||
<Box sx={{ p: 3 }}>
|
||||
{/* Search and Filters */}
|
||||
<Box sx={{ mb: 4 }}>
|
||||
<Grid container spacing={2} sx={{ mb: 3 }}>
|
||||
<Grid size={{ xs: 12, md: 6 }}>
|
||||
<>
|
||||
<Box sx={{ p: 3 }}>
|
||||
{/* Search and Filters */}
|
||||
<Box sx={{ mb: 4 }}>
|
||||
<div className='flex justify-between items-center'>
|
||||
<DebouncedInput
|
||||
value={searchQuery}
|
||||
onChange={value => setSearchQuery(value as string)}
|
||||
placeholder='Cari '
|
||||
placeholder='Cari akun...'
|
||||
className='max-sm:is-full'
|
||||
disabled={isLoading}
|
||||
InputProps={{
|
||||
startAdornment: (
|
||||
<InputAdornment position='start'>
|
||||
<i className='tabler-search' />
|
||||
</InputAdornment>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Box>
|
||||
<Box>
|
||||
<Button
|
||||
variant='contained'
|
||||
className='max-sm:is-full is-auto'
|
||||
startIcon={<i className='tabler-plus' />}
|
||||
onClick={() => {
|
||||
setEditingAccount(null)
|
||||
setAddAccountOpen(true)
|
||||
}}
|
||||
disabled={isLoading}
|
||||
>
|
||||
Tambah Akun
|
||||
</Button>
|
||||
</Box>
|
||||
</div>
|
||||
</Box>
|
||||
|
||||
{/* Account Cards */}
|
||||
<Grid container spacing={3}>
|
||||
{filteredAccounts.length > 0 ? (
|
||||
filteredAccounts.map(account => (
|
||||
<Grid key={account.id} size={{ xs: 12, lg: 6, xl: 4 }}>
|
||||
<CashBankCard
|
||||
title={account.title}
|
||||
accountNumber={account.accountNumber}
|
||||
balances={account.balances}
|
||||
chartData={account.chartData}
|
||||
categories={account.categories}
|
||||
chartColor={account.chartColor}
|
||||
currency={account.currency}
|
||||
showButton={account.accountType !== 'cash'}
|
||||
onButtonClick={() => handleAccountAction(account.id, account.accountType || 'default')}
|
||||
/>
|
||||
</Grid>
|
||||
))
|
||||
) : (
|
||||
{/* Loading State */}
|
||||
{isLoading && (
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* Account Cards */}
|
||||
{!isLoading && (
|
||||
<Grid container spacing={3}>
|
||||
{filteredAccounts.length > 0 ? (
|
||||
filteredAccounts.map(account => (
|
||||
<Grid key={account.id} size={{ xs: 12, lg: 6, xl: 4 }}>
|
||||
<CashBankCard
|
||||
title={account.title}
|
||||
accountNumber={account.accountNumber}
|
||||
balances={account.balances}
|
||||
chartData={account.chartData}
|
||||
categories={account.categories}
|
||||
chartColor={account.chartColor}
|
||||
currency={account.currency}
|
||||
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>
|
||||
)}
|
||||
|
||||
{/* Error State (if needed) */}
|
||||
{!isLoading && !accountsResponse && (
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<Box
|
||||
sx={{
|
||||
textAlign: 'center',
|
||||
py: 8,
|
||||
backgroundColor: 'grey.50',
|
||||
borderRadius: 2
|
||||
backgroundColor: 'error.light',
|
||||
borderRadius: 2,
|
||||
color: 'error.contrastText'
|
||||
}}
|
||||
>
|
||||
<Typography variant='h6' color='text.secondary' gutterBottom>
|
||||
Tidak ada akun yang ditemukan
|
||||
</Typography>
|
||||
<Typography variant='body2' color='text.secondary'>
|
||||
Coba ubah kata kunci pencarian atau filter yang digunakan
|
||||
<Typography variant='h6' gutterBottom>
|
||||
Terjadi kesalahan saat memuat data
|
||||
</Typography>
|
||||
<Typography variant='body2'>Silakan coba lagi atau hubungi administrator</Typography>
|
||||
</Box>
|
||||
</Grid>
|
||||
)}
|
||||
</Grid>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<AccountFormDrawer
|
||||
open={addAccountOpen}
|
||||
handleClose={handleCloseDrawer}
|
||||
accountData={data}
|
||||
setData={setData}
|
||||
editingAccount={editingAccount}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
// MUI Imports
|
||||
import Grid from '@mui/material/Grid2'
|
||||
|
||||
// Type Imports
|
||||
import type { UserDataType } from '@components/card-statistics/HorizontalWithSubtitle'
|
||||
|
||||
// Component Imports
|
||||
import HorizontalWithSubtitle from '@components/card-statistics/HorizontalWithSubtitle'
|
||||
|
||||
// Vars
|
||||
const data: UserDataType[] = [
|
||||
{
|
||||
title: 'SALDO',
|
||||
stats: '30.631.261',
|
||||
avatarIcon: 'tabler-wallet',
|
||||
avatarColor: 'success',
|
||||
trend: 'positive',
|
||||
trendNumber: '22.3%',
|
||||
subtitle: 'Hari ini vs 30 hari lalu'
|
||||
},
|
||||
{
|
||||
title: 'MASUK',
|
||||
stats: '3.486.871',
|
||||
avatarIcon: 'tabler-arrow-down-circle',
|
||||
avatarColor: 'success',
|
||||
trend: 'negative',
|
||||
trendNumber: '44.1%',
|
||||
subtitle: 'Bulan ini vs tanggal sama bulan lalu'
|
||||
},
|
||||
{
|
||||
title: 'KELUAR',
|
||||
stats: '3.163.000',
|
||||
avatarIcon: 'tabler-arrow-up-circle',
|
||||
avatarColor: 'info',
|
||||
trend: 'positive',
|
||||
trendNumber: '137.8%',
|
||||
subtitle: 'Bulan ini vs tanggal sama bulan lalu'
|
||||
},
|
||||
{
|
||||
title: 'NET',
|
||||
stats: '323.871',
|
||||
avatarIcon: 'tabler-trending-up',
|
||||
avatarColor: 'error',
|
||||
trend: 'negative',
|
||||
trendNumber: '93.4%',
|
||||
subtitle: 'Bulan ini vs tanggal sama bulan lalu'
|
||||
}
|
||||
]
|
||||
|
||||
const CashBankDetailCard = () => {
|
||||
return (
|
||||
<Grid container spacing={6}>
|
||||
{data.map((item, i) => (
|
||||
<Grid key={i} size={{ xs: 12, sm: 6, md: 3 }}>
|
||||
<HorizontalWithSubtitle {...item} />
|
||||
</Grid>
|
||||
))}
|
||||
</Grid>
|
||||
)
|
||||
}
|
||||
|
||||
export default CashBankDetailCard
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Typography } from '@mui/material'
|
||||
|
||||
interface Props {
|
||||
title: string
|
||||
}
|
||||
|
||||
const CashBankDetailHeader = ({ title }: Props) => {
|
||||
return (
|
||||
<div className='flex flex-wrap sm:items-center justify-between max-sm:flex-col gap-6'>
|
||||
<div>
|
||||
<Typography variant='h4' className='mbe-1'>
|
||||
{title}
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default CashBankDetailHeader
|
||||
@@ -0,0 +1,615 @@
|
||||
'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 IconButton from '@mui/material/IconButton'
|
||||
import MenuItem from '@mui/material/MenuItem'
|
||||
import { styled } from '@mui/material/styles'
|
||||
import type { TextFieldProps } from '@mui/material/TextField'
|
||||
import Typography from '@mui/material/Typography'
|
||||
|
||||
// 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 CustomTextField from '@core/components/mui/TextField'
|
||||
import OptionMenu from '@core/components/option-menu'
|
||||
|
||||
// Style Imports
|
||||
import tableStyles from '@core/styles/table.module.css'
|
||||
import { Box, CircularProgress, TablePagination } from '@mui/material'
|
||||
import { useDispatch } from 'react-redux'
|
||||
import TablePaginationComponent from '@/components/TablePaginationComponent'
|
||||
import Loading from '@/components/layout/shared/Loading'
|
||||
import { getLocalizedUrl } from '@/utils/i18n'
|
||||
import StatusFilterTabs from '@/components/StatusFilterTab'
|
||||
import DateRangePicker from '@/components/RangeDatePicker'
|
||||
|
||||
// Updated CashBankType
|
||||
export type CashBankType = {
|
||||
id: number
|
||||
date: string
|
||||
description: string
|
||||
reference: string
|
||||
accept: number
|
||||
send: number
|
||||
balance: number
|
||||
status: string
|
||||
}
|
||||
|
||||
declare module '@tanstack/table-core' {
|
||||
interface FilterFns {
|
||||
fuzzy: FilterFn<unknown>
|
||||
}
|
||||
interface FilterMeta {
|
||||
itemRank: RankingInfo
|
||||
}
|
||||
}
|
||||
|
||||
type CashBankTypeWithAction = CashBankType & {
|
||||
actions?: 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)} />
|
||||
}
|
||||
|
||||
// Status color mapping for CashBank
|
||||
const getStatusColor = (status: string) => {
|
||||
switch (status) {
|
||||
case 'Transaksi di Apskel':
|
||||
return 'info'
|
||||
case 'Transaksi di Bank':
|
||||
return 'primary'
|
||||
case 'Rekonsiliasi':
|
||||
return 'success'
|
||||
case 'Transaksi Berulang':
|
||||
return 'secondary'
|
||||
case 'Void':
|
||||
return 'error'
|
||||
case 'Menunggu Persetujuan':
|
||||
return 'warning'
|
||||
case 'Di tolak':
|
||||
return 'error'
|
||||
default:
|
||||
return 'default'
|
||||
}
|
||||
}
|
||||
|
||||
// Format currency
|
||||
const formatCurrency = (amount: number) => {
|
||||
return new Intl.NumberFormat('id-ID', {
|
||||
style: 'currency',
|
||||
currency: 'IDR',
|
||||
minimumFractionDigits: 0
|
||||
}).format(amount)
|
||||
}
|
||||
|
||||
// Sample CashBank data
|
||||
const cashBankData: CashBankType[] = [
|
||||
{
|
||||
id: 1,
|
||||
date: '2024-01-15',
|
||||
description: 'Transfer ke supplier ABC',
|
||||
reference: 'TRF-001',
|
||||
accept: 0,
|
||||
send: 5000000,
|
||||
balance: 45000000,
|
||||
status: 'Transaksi di Bank'
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
date: '2024-01-16',
|
||||
description: 'Pembayaran dari customer XYZ',
|
||||
reference: 'PAY-002',
|
||||
accept: 10000000,
|
||||
send: 0,
|
||||
balance: 55000000,
|
||||
status: 'Rekonsiliasi'
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
date: '2024-01-17',
|
||||
description: 'Pembayaran gaji karyawan',
|
||||
reference: 'SALARY-001',
|
||||
accept: 0,
|
||||
send: 25000000,
|
||||
balance: 30000000,
|
||||
status: 'Menunggu Persetujuan'
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
date: '2024-01-18',
|
||||
description: 'Transfer antar rekening',
|
||||
reference: 'TRF-002',
|
||||
accept: 0,
|
||||
send: 2000000,
|
||||
balance: 28000000,
|
||||
status: 'Transaksi di Apskel'
|
||||
},
|
||||
{
|
||||
id: 5,
|
||||
date: '2024-01-19',
|
||||
description: 'Pembayaran otomatis tagihan listrik',
|
||||
reference: 'AUTO-001',
|
||||
accept: 0,
|
||||
send: 1500000,
|
||||
balance: 26500000,
|
||||
status: 'Transaksi Berulang'
|
||||
},
|
||||
{
|
||||
id: 6,
|
||||
date: '2024-01-20',
|
||||
description: 'Transfer yang dibatalkan',
|
||||
reference: 'TRF-003',
|
||||
accept: 0,
|
||||
send: 3000000,
|
||||
balance: 26500000,
|
||||
status: 'Void'
|
||||
},
|
||||
{
|
||||
id: 7,
|
||||
date: '2024-01-21',
|
||||
description: 'Pembayaran yang ditolak sistem',
|
||||
reference: 'PAY-003',
|
||||
accept: 0,
|
||||
send: 5000000,
|
||||
balance: 26500000,
|
||||
status: 'Di tolak'
|
||||
}
|
||||
]
|
||||
|
||||
// Column Definitions
|
||||
const columnHelper = createColumnHelper<CashBankTypeWithAction>()
|
||||
|
||||
const CashBankDetailTable = () => {
|
||||
const dispatch = useDispatch()
|
||||
|
||||
// States
|
||||
const [addTransactionOpen, setAddTransactionOpen] = useState(false)
|
||||
const [rowSelection, setRowSelection] = useState({})
|
||||
const [currentPage, setCurrentPage] = useState(0)
|
||||
const [pageSize, setPageSize] = useState(10)
|
||||
const [openConfirm, setOpenConfirm] = useState(false)
|
||||
const [transactionId, setTransactionId] = useState('')
|
||||
const [search, setSearch] = useState('')
|
||||
const [statusFilter, setStatusFilter] = useState<string>('Semua')
|
||||
const [filteredData, setFilteredData] = useState<CashBankType[]>(cashBankData)
|
||||
const [startDate, setStartDate] = useState<Date | null>(new Date())
|
||||
const [endDate, setEndDate] = useState<Date | null>(new Date())
|
||||
|
||||
// Hooks
|
||||
const { lang: locale } = useParams()
|
||||
|
||||
// Filter data based on search and status
|
||||
useEffect(() => {
|
||||
let filtered = cashBankData
|
||||
|
||||
// Filter by search
|
||||
if (search) {
|
||||
filtered = filtered.filter(
|
||||
transaction =>
|
||||
transaction.description.toLowerCase().includes(search.toLowerCase()) ||
|
||||
transaction.reference.toLowerCase().includes(search.toLowerCase()) ||
|
||||
transaction.status.toLowerCase().includes(search.toLowerCase())
|
||||
)
|
||||
}
|
||||
|
||||
// Filter by status
|
||||
if (statusFilter !== 'Semua') {
|
||||
filtered = filtered.filter(transaction => transaction.status === statusFilter)
|
||||
}
|
||||
|
||||
setFilteredData(filtered)
|
||||
setCurrentPage(0)
|
||||
}, [search, statusFilter])
|
||||
|
||||
const totalCount = filteredData.length
|
||||
const paginatedData = useMemo(() => {
|
||||
const startIndex = currentPage * pageSize
|
||||
return filteredData.slice(startIndex, startIndex + pageSize)
|
||||
}, [filteredData, currentPage, pageSize])
|
||||
|
||||
// Calculate totals from filtered data
|
||||
const subtotalAccept = useMemo(() => {
|
||||
return filteredData.reduce((sum, transaction) => sum + transaction.accept, 0)
|
||||
}, [filteredData])
|
||||
|
||||
const subtotalSend = useMemo(() => {
|
||||
return filteredData.reduce((sum, transaction) => sum + transaction.send, 0)
|
||||
}, [filteredData])
|
||||
|
||||
const netBalance = subtotalAccept - subtotalSend
|
||||
|
||||
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(0)
|
||||
}, [])
|
||||
|
||||
const handleDelete = () => {
|
||||
setOpenConfirm(false)
|
||||
}
|
||||
|
||||
const handleTransactionClick = (transactionId: string) => {
|
||||
console.log('Navigasi ke detail Transaksi:', transactionId)
|
||||
}
|
||||
|
||||
const handleStatusFilter = (status: string) => {
|
||||
setStatusFilter(status)
|
||||
}
|
||||
|
||||
const columns = useMemo<ColumnDef<CashBankTypeWithAction, 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('date', {
|
||||
header: 'Tanggal',
|
||||
cell: ({ row }) => <Typography>{row.original.date}</Typography>
|
||||
}),
|
||||
columnHelper.accessor('description', {
|
||||
header: 'Keterangan',
|
||||
cell: ({ row }) => (
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
className='p-0 min-w-0 font-medium normal-case justify-start'
|
||||
component={Link}
|
||||
href={getLocalizedUrl(`/apps/cash-bank/1-10003/detail/transaction/${row.original.id}`, locale as Locale)}
|
||||
sx={{
|
||||
textTransform: 'none',
|
||||
fontWeight: 500,
|
||||
'&:hover': {
|
||||
textDecoration: 'underline',
|
||||
backgroundColor: 'transparent'
|
||||
}
|
||||
}}
|
||||
>
|
||||
{row.original.description}
|
||||
</Button>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('reference', {
|
||||
header: 'Referensi',
|
||||
cell: ({ row }) => <Typography color='text.secondary'>{row.original.reference || '-'}</Typography>
|
||||
}),
|
||||
columnHelper.accessor('status', {
|
||||
header: 'Status',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-3'>
|
||||
<Chip
|
||||
variant='tonal'
|
||||
label={row.original.status}
|
||||
size='small'
|
||||
color={getStatusColor(row.original.status) as any}
|
||||
className='capitalize'
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('accept', {
|
||||
header: 'Penerimaan',
|
||||
cell: ({ row }) => (
|
||||
<Typography className={`font-medium ${row.original.accept > 0 ? 'text-green-600' : 'text-gray-500'}`}>
|
||||
{row.original.accept > 0 ? formatCurrency(row.original.accept) : '-'}
|
||||
</Typography>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('send', {
|
||||
header: 'Pengeluaran',
|
||||
cell: ({ row }) => (
|
||||
<Typography className={`font-medium ${row.original.send > 0 ? 'text-red-600' : 'text-gray-500'}`}>
|
||||
{row.original.send > 0 ? formatCurrency(row.original.send) : '-'}
|
||||
</Typography>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('balance', {
|
||||
header: 'Saldo',
|
||||
cell: ({ row }) => (
|
||||
<Typography className={`font-medium ${row.original.balance >= 0 ? 'text-green-600' : 'text-red-600'}`}>
|
||||
{formatCurrency(row.original.balance)}
|
||||
</Typography>
|
||||
)
|
||||
})
|
||||
],
|
||||
[]
|
||||
)
|
||||
|
||||
const table = useReactTable({
|
||||
data: paginatedData as CashBankType[],
|
||||
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>
|
||||
{/* Filter Status Tabs and Range Date */}
|
||||
<div className='p-6 border-bs'>
|
||||
<div className='flex items-center justify-between'>
|
||||
<StatusFilterTabs
|
||||
statusOptions={[
|
||||
'Semua',
|
||||
'Transaksi di Apskel',
|
||||
'Transaksi di Bank',
|
||||
'Rekonsiliasi',
|
||||
'Transaksi Berulang',
|
||||
'Void',
|
||||
'Menunggu Persetujuan',
|
||||
'Di tolak'
|
||||
]}
|
||||
selectedStatus={statusFilter}
|
||||
onStatusChange={handleStatusFilter}
|
||||
/>
|
||||
<DateRangePicker
|
||||
startDate={startDate}
|
||||
endDate={endDate}
|
||||
onStartDateChange={setStartDate}
|
||||
onEndDateChange={setEndDate}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='flex justify-between flex-col items-start md:flex-row md:items-center p-6 border-bs gap-4'>
|
||||
<DebouncedInput
|
||||
value={search}
|
||||
onChange={value => setSearch(value as string)}
|
||||
placeholder='Cari Transaksi Cash/Bank'
|
||||
className='max-sm:is-full'
|
||||
/>
|
||||
<div className='flex flex-col sm:flex-row max-sm:is-full items-start sm:items-center gap-4'>
|
||||
<CustomTextField
|
||||
select
|
||||
value={pageSize}
|
||||
onChange={handlePageSizeChange}
|
||||
className='max-sm:is-full sm:is-[70px]'
|
||||
>
|
||||
<MenuItem value={10}>10</MenuItem>
|
||||
<MenuItem value={25}>25</MenuItem>
|
||||
<MenuItem value={50}>50</MenuItem>
|
||||
</CustomTextField>
|
||||
<Button
|
||||
color='secondary'
|
||||
variant='tonal'
|
||||
startIcon={<i className='tabler-upload' />}
|
||||
className='max-sm:is-full'
|
||||
>
|
||||
Ekspor
|
||||
</Button>
|
||||
<Button
|
||||
variant='contained'
|
||||
component={Link}
|
||||
className='max-sm:is-full is-auto'
|
||||
startIcon={<i className='tabler-plus' />}
|
||||
href={getLocalizedUrl('/apps/cashbank/add', locale as Locale)}
|
||||
>
|
||||
Tambah Transaksi
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className='overflow-x-auto'>
|
||||
<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>
|
||||
{filteredData.length === 0 ? (
|
||||
<tbody>
|
||||
<tr>
|
||||
<td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
|
||||
Tidak ada data tersedia
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
) : (
|
||||
<tbody>
|
||||
{table.getRowModel().rows.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>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* Subtotal Row */}
|
||||
<tr className='border-t-2 bg-gray-50'>
|
||||
<td className='font-semibold text-lg py-4'>
|
||||
<Typography variant='h6' className='font-semibold'>
|
||||
Subtotal
|
||||
</Typography>
|
||||
</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
<td className='font-semibold text-lg py-4'>
|
||||
<Typography variant='h6' className='font-semibold text-green-600'>
|
||||
{formatCurrency(subtotalAccept)}
|
||||
</Typography>
|
||||
</td>
|
||||
<td className='font-semibold text-lg py-4'>
|
||||
<Typography variant='h6' className='font-semibold text-red-600'>
|
||||
{formatCurrency(subtotalSend)}
|
||||
</Typography>
|
||||
</td>
|
||||
<td className='font-semibold text-lg py-4'>
|
||||
<Typography
|
||||
variant='h6'
|
||||
className={`font-semibold ${netBalance >= 0 ? 'text-green-600' : 'text-red-600'}`}
|
||||
>
|
||||
{formatCurrency(netBalance)}
|
||||
</Typography>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
{/* Total Row */}
|
||||
<tr className='border-t bg-gray-100'>
|
||||
<td className='font-bold text-xl py-4'>
|
||||
<Typography variant='h6' className='font-bold'>
|
||||
Total
|
||||
</Typography>
|
||||
</td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
<td className='font-bold text-xl py-4'>
|
||||
<Typography
|
||||
variant='h6'
|
||||
className={`font-bold ${netBalance >= 0 ? 'text-green-600' : 'text-red-600'}`}
|
||||
>
|
||||
{formatCurrency(netBalance)}
|
||||
</Typography>
|
||||
</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]}
|
||||
/>
|
||||
</Card>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default CashBankDetailTable
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user