Compare commits
102
Commits
00620026e4
..
efril
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bf0f4cfa38 | ||
|
|
82e79463b5 | ||
|
|
c3ad938a79 | ||
|
|
69c49238d4 | ||
|
|
191937e647 | ||
|
|
ce9120e7e6 | ||
|
|
52879b58fe | ||
|
|
a7b6e15818 | ||
|
|
8ac6ff6d14 | ||
|
|
0dc6e967bb | ||
|
|
daa3c4e9a2 | ||
|
|
27ddd137eb | ||
|
|
073f3dd89c | ||
|
|
07c0bdb3af | ||
|
|
e6bcf287ea | ||
|
|
d317e8d06f | ||
|
|
dc32c8553b | ||
|
|
79cd4f9dcb | ||
|
|
cfa3686de3 | ||
|
|
c7d29f4041 | ||
|
|
1b9908e882 | ||
|
|
d245074904 | ||
|
|
256f035997 | ||
|
|
726d1f4984 | ||
|
|
9b92f4742f | ||
|
|
1bf2bad52c | ||
|
|
e55357e305 | ||
|
|
3bfd0b9e19 | ||
|
|
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 | ||
|
|
2c754d96fd | ||
|
|
66589abdd4 |
@@ -39,3 +39,5 @@ next-env.d.ts
|
|||||||
# icon generated file
|
# icon generated file
|
||||||
src/assets/iconify-icons/generated-icons.js
|
src/assets/iconify-icons/generated-icons.js
|
||||||
src/assets/iconify-icons/generated-icons.css
|
src/assets/iconify-icons/generated-icons.css
|
||||||
|
|
||||||
|
*.backup
|
||||||
|
|||||||
Generated
+179
-32
@@ -52,9 +52,12 @@
|
|||||||
"emoji-mart": "5.6.0",
|
"emoji-mart": "5.6.0",
|
||||||
"fs-extra": "11.2.0",
|
"fs-extra": "11.2.0",
|
||||||
"html2canvas": "^1.4.1",
|
"html2canvas": "^1.4.1",
|
||||||
|
"html2pdf.js": "^0.12.1",
|
||||||
"input-otp": "1.4.1",
|
"input-otp": "1.4.1",
|
||||||
"jspdf": "^3.0.1",
|
"jspdf": "^3.0.3",
|
||||||
|
"jspdf-autotable": "^5.0.2",
|
||||||
"keen-slider": "6.8.6",
|
"keen-slider": "6.8.6",
|
||||||
|
"lucide-react": "^0.544.0",
|
||||||
"mapbox-gl": "3.9.0",
|
"mapbox-gl": "3.9.0",
|
||||||
"negotiator": "1.0.0",
|
"negotiator": "1.0.0",
|
||||||
"next": "15.1.2",
|
"next": "15.1.2",
|
||||||
@@ -73,7 +76,8 @@
|
|||||||
"react-use": "17.6.0",
|
"react-use": "17.6.0",
|
||||||
"recharts": "2.15.0",
|
"recharts": "2.15.0",
|
||||||
"use-debounce": "^10.0.5",
|
"use-debounce": "^10.0.5",
|
||||||
"valibot": "0.42.1"
|
"valibot": "0.42.1",
|
||||||
|
"xlsx": "^0.18.5"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@iconify/json": "2.2.286",
|
"@iconify/json": "2.2.286",
|
||||||
@@ -81,6 +85,7 @@
|
|||||||
"@iconify/types": "2.0.0",
|
"@iconify/types": "2.0.0",
|
||||||
"@iconify/utils": "2.2.1",
|
"@iconify/utils": "2.2.1",
|
||||||
"@types/fs-extra": "^11.0.4",
|
"@types/fs-extra": "^11.0.4",
|
||||||
|
"@types/jspdf": "^1.3.3",
|
||||||
"@types/mapbox-gl": "^3.4.1",
|
"@types/mapbox-gl": "^3.4.1",
|
||||||
"@types/negotiator": "^0.6.3",
|
"@types/negotiator": "^0.6.3",
|
||||||
"@types/node": "^22.10.2",
|
"@types/node": "^22.10.2",
|
||||||
@@ -3506,6 +3511,13 @@
|
|||||||
"@types/node": "*"
|
"@types/node": "*"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@types/jspdf": {
|
||||||
|
"version": "1.3.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/jspdf/-/jspdf-1.3.3.tgz",
|
||||||
|
"integrity": "sha512-DqwyAKpVuv+7DniCp2Deq1xGvfdnKSNgl9Agun2w6dFvR5UKamiv4VfYUgcypd8S9ojUyARFIlZqBrYrBMQlew==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/@types/linkify-it": {
|
"node_modules/@types/linkify-it": {
|
||||||
"version": "5.0.0",
|
"version": "5.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-5.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-5.0.0.tgz",
|
||||||
@@ -3571,6 +3583,12 @@
|
|||||||
"undici-types": "~6.21.0"
|
"undici-types": "~6.21.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@types/pako": {
|
||||||
|
"version": "2.0.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/pako/-/pako-2.0.4.tgz",
|
||||||
|
"integrity": "sha512-VWDCbrLeVXJM9fihYodcLiIv0ku+AlOa/TQ1SvYOaBuyrSKgEcro95LJyIsJ4vSo6BXIxOKxiJAat04CmST9Fw==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/@types/parse-json": {
|
"node_modules/@types/parse-json": {
|
||||||
"version": "4.0.2",
|
"version": "4.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.2.tgz",
|
||||||
@@ -3935,6 +3953,15 @@
|
|||||||
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/adler-32": {
|
||||||
|
"version": "1.3.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/adler-32/-/adler-32-1.3.1.tgz",
|
||||||
|
"integrity": "sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/ajv": {
|
"node_modules/ajv": {
|
||||||
"version": "6.12.6",
|
"version": "6.12.6",
|
||||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
|
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
|
||||||
@@ -4270,18 +4297,6 @@
|
|||||||
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
|
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/atob": {
|
|
||||||
"version": "2.1.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/atob/-/atob-2.1.2.tgz",
|
|
||||||
"integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==",
|
|
||||||
"license": "(MIT OR Apache-2.0)",
|
|
||||||
"bin": {
|
|
||||||
"atob": "bin/atob.js"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 4.5.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/attr-accept": {
|
"node_modules/attr-accept": {
|
||||||
"version": "2.2.5",
|
"version": "2.2.5",
|
||||||
"resolved": "https://registry.npmjs.org/attr-accept/-/attr-accept-2.2.5.tgz",
|
"resolved": "https://registry.npmjs.org/attr-accept/-/attr-accept-2.2.5.tgz",
|
||||||
@@ -4499,18 +4514,6 @@
|
|||||||
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
|
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/btoa": {
|
|
||||||
"version": "1.2.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/btoa/-/btoa-1.2.1.tgz",
|
|
||||||
"integrity": "sha512-SB4/MIGlsiVkMcHmT+pSmIPoNDoHg+7cMzmt3Uxt628MTz2487DKSqK/fuhFBrkuqrYv5UCEnACpF4dTFNKc/g==",
|
|
||||||
"license": "(MIT OR Apache-2.0)",
|
|
||||||
"bin": {
|
|
||||||
"btoa": "bin/btoa.js"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 0.4.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/buffer-crc32": {
|
"node_modules/buffer-crc32": {
|
||||||
"version": "0.2.13",
|
"version": "0.2.13",
|
||||||
"resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz",
|
"resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz",
|
||||||
@@ -4659,6 +4662,19 @@
|
|||||||
"node": ">=10.0.0"
|
"node": ">=10.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/cfb": {
|
||||||
|
"version": "1.2.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/cfb/-/cfb-1.2.2.tgz",
|
||||||
|
"integrity": "sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"adler-32": "~1.3.0",
|
||||||
|
"crc-32": "~1.2.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/chalk": {
|
"node_modules/chalk": {
|
||||||
"version": "4.1.2",
|
"version": "4.1.2",
|
||||||
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
|
||||||
@@ -4811,6 +4827,15 @@
|
|||||||
"react-dom": "^18 || ^19 || ^19.0.0-rc"
|
"react-dom": "^18 || ^19 || ^19.0.0-rc"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/codepage": {
|
||||||
|
"version": "1.15.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/codepage/-/codepage-1.15.0.tgz",
|
||||||
|
"integrity": "sha512-3g6NUTPd/YtuuGrhMnOMRjFc+LJw/bnMp3+0r/Wcz3IXUuCosKRJvMphm5+Q+bvTVGcJJuRvVLuYba+WojaFaA==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/color": {
|
"node_modules/color": {
|
||||||
"version": "4.2.3",
|
"version": "4.2.3",
|
||||||
"resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz",
|
"resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz",
|
||||||
@@ -4952,6 +4977,18 @@
|
|||||||
"node": ">=10"
|
"node": ">=10"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/crc-32": {
|
||||||
|
"version": "1.2.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz",
|
||||||
|
"integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"bin": {
|
||||||
|
"crc32": "bin/crc32.njs"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/crelt": {
|
"node_modules/crelt": {
|
||||||
"version": "1.0.6",
|
"version": "1.0.6",
|
||||||
"resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.6.tgz",
|
"resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.6.tgz",
|
||||||
@@ -6597,6 +6634,17 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/fast-png": {
|
||||||
|
"version": "6.4.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/fast-png/-/fast-png-6.4.0.tgz",
|
||||||
|
"integrity": "sha512-kAqZq1TlgBjZcLr5mcN6NP5Rv4V2f22z00c3g8vRrwkcqjerx7BEhPbOnWCPqaHUl2XWQBJQvOT/FQhdMT7X/Q==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/pako": "^2.0.3",
|
||||||
|
"iobuffer": "^5.3.2",
|
||||||
|
"pako": "^2.1.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/fast-shallow-equal": {
|
"node_modules/fast-shallow-equal": {
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/fast-shallow-equal/-/fast-shallow-equal-1.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/fast-shallow-equal/-/fast-shallow-equal-1.0.0.tgz",
|
||||||
@@ -6876,6 +6924,15 @@
|
|||||||
"node": ">= 6"
|
"node": ">= 6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/frac": {
|
||||||
|
"version": "1.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/frac/-/frac-1.1.2.tgz",
|
||||||
|
"integrity": "sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/fraction.js": {
|
"node_modules/fraction.js": {
|
||||||
"version": "4.3.7",
|
"version": "4.3.7",
|
||||||
"resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.3.7.tgz",
|
"resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.3.7.tgz",
|
||||||
@@ -7455,6 +7512,16 @@
|
|||||||
"node": ">=8.0.0"
|
"node": ">=8.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/html2pdf.js": {
|
||||||
|
"version": "0.12.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/html2pdf.js/-/html2pdf.js-0.12.1.tgz",
|
||||||
|
"integrity": "sha512-3rBWQ96H5oOU9jtoz3MnE/epGi27ig9h8aonBk4JTpvUERM3lMRxhIRckhJZEi4wE0YfRINoYOIDY0hLY0CHgQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"html2canvas": "^1.0.0",
|
||||||
|
"jspdf": "^3.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/htmlparser2": {
|
"node_modules/htmlparser2": {
|
||||||
"version": "9.1.0",
|
"version": "9.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-9.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-9.1.0.tgz",
|
||||||
@@ -7629,6 +7696,12 @@
|
|||||||
"node": ">=12"
|
"node": ">=12"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/iobuffer": {
|
||||||
|
"version": "5.4.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/iobuffer/-/iobuffer-5.4.0.tgz",
|
||||||
|
"integrity": "sha512-DRebOWuqDvxunfkNJAlc3IzWIPD5xVxwUNbHr7xKB8E6aLJxIPfNX3CoMJghcFjpv6RWQsrcJbghtEwSPoJqMA==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/is-array-buffer": {
|
"node_modules/is-array-buffer": {
|
||||||
"version": "3.0.5",
|
"version": "3.0.5",
|
||||||
"resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz",
|
"resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz",
|
||||||
@@ -8250,14 +8323,13 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/jspdf": {
|
"node_modules/jspdf": {
|
||||||
"version": "3.0.1",
|
"version": "3.0.3",
|
||||||
"resolved": "https://registry.npmjs.org/jspdf/-/jspdf-3.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/jspdf/-/jspdf-3.0.3.tgz",
|
||||||
"integrity": "sha512-qaGIxqxetdoNnFQQXxTKUD9/Z7AloLaw94fFsOiJMxbfYdBbrBuhWmbzI8TVjrw7s3jBY1PFHofBKMV/wZPapg==",
|
"integrity": "sha512-eURjAyz5iX1H8BOYAfzvdPfIKK53V7mCpBTe7Kb16PaM8JSXEcUQNBQaiWMI8wY5RvNOPj4GccMjTlfwRBd+oQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@babel/runtime": "^7.26.7",
|
"@babel/runtime": "^7.26.9",
|
||||||
"atob": "^2.1.2",
|
"fast-png": "^6.2.0",
|
||||||
"btoa": "^1.2.1",
|
|
||||||
"fflate": "^0.8.1"
|
"fflate": "^0.8.1"
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
@@ -8267,6 +8339,15 @@
|
|||||||
"html2canvas": "^1.0.0-rc.5"
|
"html2canvas": "^1.0.0-rc.5"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/jspdf-autotable": {
|
||||||
|
"version": "5.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/jspdf-autotable/-/jspdf-autotable-5.0.2.tgz",
|
||||||
|
"integrity": "sha512-YNKeB7qmx3pxOLcNeoqAv3qTS7KuvVwkFe5AduCawpop3NOkBUtqDToxNc225MlNecxT4kP2Zy3z/y/yvGdXUQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"peerDependencies": {
|
||||||
|
"jspdf": "^2 || ^3"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/jsx-ast-utils": {
|
"node_modules/jsx-ast-utils": {
|
||||||
"version": "3.3.5",
|
"version": "3.3.5",
|
||||||
"resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz",
|
"resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz",
|
||||||
@@ -8462,6 +8543,15 @@
|
|||||||
"loose-envify": "cli.js"
|
"loose-envify": "cli.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/lucide-react": {
|
||||||
|
"version": "0.544.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.544.0.tgz",
|
||||||
|
"integrity": "sha512-t5tS44bqd825zAW45UQxpG2CvcC4urOwn2TrwSH8u+MjeE+1NnWl6QqeQ/6NdjMqdOygyiT9p3Ev0p1NJykxjw==",
|
||||||
|
"license": "ISC",
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/mapbox-gl": {
|
"node_modules/mapbox-gl": {
|
||||||
"version": "3.9.0",
|
"version": "3.9.0",
|
||||||
"resolved": "https://registry.npmjs.org/mapbox-gl/-/mapbox-gl-3.9.0.tgz",
|
"resolved": "https://registry.npmjs.org/mapbox-gl/-/mapbox-gl-3.9.0.tgz",
|
||||||
@@ -9133,6 +9223,12 @@
|
|||||||
"quansync": "^0.2.7"
|
"quansync": "^0.2.7"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/pako": {
|
||||||
|
"version": "2.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/pako/-/pako-2.1.0.tgz",
|
||||||
|
"integrity": "sha512-w+eufiZ1WuJYgPXbV/PO3NCMEc3xqylkKHzp8bxp1uW4qaSNQUkwmLLEc3kKsfz8lpV1F8Ht3U1Cm+9Srog2ug==",
|
||||||
|
"license": "(MIT AND Zlib)"
|
||||||
|
},
|
||||||
"node_modules/parent-module": {
|
"node_modules/parent-module": {
|
||||||
"version": "1.0.1",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",
|
||||||
@@ -11083,6 +11179,18 @@
|
|||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/ssf": {
|
||||||
|
"version": "0.11.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/ssf/-/ssf-0.11.2.tgz",
|
||||||
|
"integrity": "sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"frac": "~1.1.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/stable-hash": {
|
"node_modules/stable-hash": {
|
||||||
"version": "0.0.4",
|
"version": "0.0.4",
|
||||||
"resolved": "https://registry.npmjs.org/stable-hash/-/stable-hash-0.0.4.tgz",
|
"resolved": "https://registry.npmjs.org/stable-hash/-/stable-hash-0.0.4.tgz",
|
||||||
@@ -13035,6 +13143,24 @@
|
|||||||
"url": "https://github.com/sponsors/ljharb"
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/wmf": {
|
||||||
|
"version": "1.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/wmf/-/wmf-1.0.2.tgz",
|
||||||
|
"integrity": "sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/word": {
|
||||||
|
"version": "0.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/word/-/word-0.3.0.tgz",
|
||||||
|
"integrity": "sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/word-wrap": {
|
"node_modules/word-wrap": {
|
||||||
"version": "1.2.5",
|
"version": "1.2.5",
|
||||||
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",
|
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",
|
||||||
@@ -13167,6 +13293,27 @@
|
|||||||
"node": "^14.17.0 || ^16.13.0 || >=18.0.0"
|
"node": "^14.17.0 || ^16.13.0 || >=18.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/xlsx": {
|
||||||
|
"version": "0.18.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/xlsx/-/xlsx-0.18.5.tgz",
|
||||||
|
"integrity": "sha512-dmg3LCjBPHZnQp5/F/+nnTa+miPJxUXB6vtk42YjBBKayDNagxGEeIdWApkYPOf3Z3pm3k62Knjzp7lMeTEtFQ==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"adler-32": "~1.3.0",
|
||||||
|
"cfb": "~1.2.1",
|
||||||
|
"codepage": "~1.15.0",
|
||||||
|
"crc-32": "~1.2.1",
|
||||||
|
"ssf": "~0.11.2",
|
||||||
|
"wmf": "~1.0.1",
|
||||||
|
"word": "~0.3.0"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"xlsx": "bin/xlsx.njs"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/yallist": {
|
"node_modules/yallist": {
|
||||||
"version": "4.0.0",
|
"version": "4.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
|
||||||
|
|||||||
+7
-2
@@ -58,9 +58,12 @@
|
|||||||
"emoji-mart": "5.6.0",
|
"emoji-mart": "5.6.0",
|
||||||
"fs-extra": "11.2.0",
|
"fs-extra": "11.2.0",
|
||||||
"html2canvas": "^1.4.1",
|
"html2canvas": "^1.4.1",
|
||||||
|
"html2pdf.js": "^0.12.1",
|
||||||
"input-otp": "1.4.1",
|
"input-otp": "1.4.1",
|
||||||
"jspdf": "^3.0.1",
|
"jspdf": "^3.0.3",
|
||||||
|
"jspdf-autotable": "^5.0.2",
|
||||||
"keen-slider": "6.8.6",
|
"keen-slider": "6.8.6",
|
||||||
|
"lucide-react": "^0.544.0",
|
||||||
"mapbox-gl": "3.9.0",
|
"mapbox-gl": "3.9.0",
|
||||||
"negotiator": "1.0.0",
|
"negotiator": "1.0.0",
|
||||||
"next": "15.1.2",
|
"next": "15.1.2",
|
||||||
@@ -79,7 +82,8 @@
|
|||||||
"react-use": "17.6.0",
|
"react-use": "17.6.0",
|
||||||
"recharts": "2.15.0",
|
"recharts": "2.15.0",
|
||||||
"use-debounce": "^10.0.5",
|
"use-debounce": "^10.0.5",
|
||||||
"valibot": "0.42.1"
|
"valibot": "0.42.1",
|
||||||
|
"xlsx": "^0.18.5"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@iconify/json": "2.2.286",
|
"@iconify/json": "2.2.286",
|
||||||
@@ -87,6 +91,7 @@
|
|||||||
"@iconify/types": "2.0.0",
|
"@iconify/types": "2.0.0",
|
||||||
"@iconify/utils": "2.2.1",
|
"@iconify/utils": "2.2.1",
|
||||||
"@types/fs-extra": "^11.0.4",
|
"@types/fs-extra": "^11.0.4",
|
||||||
|
"@types/jspdf": "^1.3.3",
|
||||||
"@types/mapbox-gl": "^3.4.1",
|
"@types/mapbox-gl": "^3.4.1",
|
||||||
"@types/negotiator": "^0.6.3",
|
"@types/negotiator": "^0.6.3",
|
||||||
"@types/node": "^22.10.2",
|
"@types/node": "^22.10.2",
|
||||||
|
|||||||
@@ -13,10 +13,11 @@ export const metadata: Metadata = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const LoginPage = async () => {
|
const LoginPage = async () => {
|
||||||
// Vars
|
return (
|
||||||
const mode = await getServerMode()
|
<div className='flex flex-col justify-center items-center min-bs-[100dvh] p-6'>
|
||||||
|
<Login />
|
||||||
return <Login mode={mode} />
|
</div>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export default LoginPage
|
export default LoginPage
|
||||||
|
|||||||
@@ -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,7 @@
|
|||||||
|
import CashBankList from '@/views/apps/cash-bank/CashBankList'
|
||||||
|
|
||||||
|
const CashBankPage = () => {
|
||||||
|
return <CashBankList />
|
||||||
|
}
|
||||||
|
|
||||||
|
export default CashBankPage
|
||||||
@@ -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,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,18 @@
|
|||||||
|
import ReportTitle from '@/components/report/ReportTitle'
|
||||||
|
import ReportPaymentMethodContent from '@/views/apps/report/financial/payment-method-report/ReportPaymentMethodContent'
|
||||||
|
import Grid from '@mui/material/Grid2'
|
||||||
|
|
||||||
|
const SalesProductReportPage = () => {
|
||||||
|
return (
|
||||||
|
<Grid container spacing={6}>
|
||||||
|
<Grid size={{ xs: 12 }}>
|
||||||
|
<ReportTitle title='Laporan Metode Pembayaran' />
|
||||||
|
</Grid>
|
||||||
|
<Grid size={{ xs: 12 }}>
|
||||||
|
<ReportPaymentMethodContent />
|
||||||
|
</Grid>
|
||||||
|
</Grid>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default SalesProductReportPage
|
||||||
@@ -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,72 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
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'
|
||||||
|
import { CircularProgress, Box } from '@mui/material'
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { useProfitLossAnalytics } from '@/services/queries/analytics'
|
||||||
|
import { formatDateDDMMYYYY } from '@/utils/transform'
|
||||||
|
import Loading from '@/components/layout/shared/Loading'
|
||||||
|
|
||||||
|
const ProfitLossPage = () => {
|
||||||
|
const today = new Date()
|
||||||
|
const monthAgo = new Date()
|
||||||
|
monthAgo.setDate(today.getDate() - 30)
|
||||||
|
const [startDate, setStartDate] = useState<Date | null>(monthAgo)
|
||||||
|
const [endDate, setEndDate] = useState<Date | null>(today)
|
||||||
|
|
||||||
|
// Single API call at parent level
|
||||||
|
const {
|
||||||
|
data: profitData,
|
||||||
|
isLoading,
|
||||||
|
error
|
||||||
|
} = useProfitLossAnalytics({
|
||||||
|
date_from: formatDateDDMMYYYY(startDate!),
|
||||||
|
date_to: formatDateDDMMYYYY(endDate!)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Handle loading state
|
||||||
|
if (isLoading) {
|
||||||
|
return <Loading />
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle error state
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<Grid container spacing={6}>
|
||||||
|
<Grid size={{ xs: 12 }}>
|
||||||
|
<ReportTitle title='Laba Rugi' />
|
||||||
|
</Grid>
|
||||||
|
<Grid size={{ xs: 12 }}>
|
||||||
|
<Box display='flex' justifyContent='center' alignItems='center' minHeight={400}>
|
||||||
|
<span>Error loading data: {error.message}</span>
|
||||||
|
</Box>
|
||||||
|
</Grid>
|
||||||
|
</Grid>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Grid container spacing={6}>
|
||||||
|
<Grid size={{ xs: 12 }}>
|
||||||
|
<ReportTitle title='Laba Rugi' />
|
||||||
|
</Grid>
|
||||||
|
<Grid size={{ xs: 12 }}>
|
||||||
|
<ReportProfitLossCard profitData={profitData} />
|
||||||
|
</Grid>
|
||||||
|
<Grid size={{ xs: 12 }}>
|
||||||
|
<ReportProfitLossContent
|
||||||
|
profitData={profitData}
|
||||||
|
startDate={startDate}
|
||||||
|
endDate={endDate}
|
||||||
|
onStartDateChange={setStartDate}
|
||||||
|
onEndDateChange={setEndDate}
|
||||||
|
/>
|
||||||
|
</Grid>
|
||||||
|
</Grid>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default ProfitLossPage
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import ReportTitle from '@/components/report/ReportTitle'
|
||||||
|
import ReportSalesOrderContent from '@/views/apps/report/sales/sales-order/ReportSalesOrderContent'
|
||||||
|
import Grid from '@mui/material/Grid2'
|
||||||
|
|
||||||
|
const SalesOrderReportPage = () => {
|
||||||
|
return (
|
||||||
|
<Grid container spacing={6}>
|
||||||
|
<Grid size={{ xs: 12 }}>
|
||||||
|
<ReportTitle title='Laporan Penjualan Pesanan' />
|
||||||
|
</Grid>
|
||||||
|
<Grid size={{ xs: 12 }}>
|
||||||
|
<ReportSalesOrderContent />
|
||||||
|
</Grid>
|
||||||
|
z
|
||||||
|
</Grid>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default SalesOrderReportPage
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
import ReportTitle from '@/components/report/ReportTitle'
|
||||||
|
import ReportSalesProductCategoryContent from '@/views/apps/report/sales/sales-product-category/ReportSalesProductCategoryReport'
|
||||||
|
import Grid from '@mui/material/Grid2'
|
||||||
|
|
||||||
|
const SalesProductCategoryReportPage = () => {
|
||||||
|
return (
|
||||||
|
<Grid container spacing={6}>
|
||||||
|
<Grid size={{ xs: 12 }}>
|
||||||
|
<ReportTitle title='Laporan Penjualan per Kategori Produk' />
|
||||||
|
</Grid>
|
||||||
|
<Grid size={{ xs: 12 }}>
|
||||||
|
<ReportSalesProductCategoryContent />
|
||||||
|
</Grid>
|
||||||
|
</Grid>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default SalesProductCategoryReportPage
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import ReportTitle from '@/components/report/ReportTitle'
|
||||||
|
import ReportSalesPerProductContent from '@/views/apps/report/sales/sales-per-product/ReportSalesPerProductContent'
|
||||||
|
import Grid from '@mui/material/Grid2'
|
||||||
|
|
||||||
|
const SalesProductReportPage = () => {
|
||||||
|
return (
|
||||||
|
<Grid container spacing={6}>
|
||||||
|
<Grid size={{ xs: 12 }}>
|
||||||
|
<ReportTitle title='Laporan Penjualan per Produk' />
|
||||||
|
</Grid>
|
||||||
|
<Grid size={{ xs: 12 }}>
|
||||||
|
<ReportSalesPerProductContent />
|
||||||
|
</Grid>
|
||||||
|
</Grid>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default SalesProductReportPage
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import ReportTitle from '@/components/report/ReportTitle'
|
||||||
|
import ReportSalesContent from '@/views/apps/report/sales/sales-report/ReportSalesContent'
|
||||||
|
import Grid from '@mui/material/Grid2'
|
||||||
|
|
||||||
|
const SalesReportPage = () => {
|
||||||
|
return (
|
||||||
|
<Grid container spacing={6}>
|
||||||
|
<Grid size={{ xs: 12 }}>
|
||||||
|
<ReportTitle title='Laporan Penjualan' />
|
||||||
|
</Grid>
|
||||||
|
<Grid size={{ xs: 12 }}>
|
||||||
|
<ReportSalesContent />
|
||||||
|
</Grid>
|
||||||
|
</Grid>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default SalesReportPage
|
||||||
@@ -23,6 +23,7 @@ const DailyPOSReport = () => {
|
|||||||
endDate: new Date()
|
endDate: new Date()
|
||||||
})
|
})
|
||||||
const [filterType, setFilterType] = useState<'single' | 'range'>('single') // 'single' or 'range'
|
const [filterType, setFilterType] = useState<'single' | 'range'>('single') // 'single' or 'range'
|
||||||
|
const [isGeneratingPDF, setIsGeneratingPDF] = useState(false)
|
||||||
|
|
||||||
// Use selectedDate for single date filter, or dateRange for range filter
|
// Use selectedDate for single date filter, or dateRange for range filter
|
||||||
const getDateParams = () => {
|
const getDateParams = () => {
|
||||||
@@ -54,14 +55,6 @@ const DailyPOSReport = () => {
|
|||||||
totalOrders: products?.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0
|
totalOrders: products?.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// Calculate profit loss product summary
|
|
||||||
const profitLossProductSummary = {
|
|
||||||
totalRevenue: profitLoss?.product_data?.reduce((sum, item) => sum + (item?.revenue || 0), 0) || 0,
|
|
||||||
totalCost: profitLoss?.product_data?.reduce((sum, item) => sum + (item?.cost || 0), 0) || 0,
|
|
||||||
totalGrossProfit: profitLoss?.product_data?.reduce((sum, item) => sum + (item?.gross_profit || 0), 0) || 0,
|
|
||||||
totalQuantity: profitLoss?.product_data?.reduce((sum, item) => sum + (item?.quantity_sold || 0), 0) || 0
|
|
||||||
}
|
|
||||||
|
|
||||||
const categorySummary = {
|
const categorySummary = {
|
||||||
totalRevenue: category?.data?.reduce((sum, item) => sum + (item?.total_revenue || 0), 0) || 0,
|
totalRevenue: category?.data?.reduce((sum, item) => sum + (item?.total_revenue || 0), 0) || 0,
|
||||||
orderCount: category?.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0,
|
orderCount: category?.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0,
|
||||||
@@ -101,84 +94,216 @@ const DailyPOSReport = () => {
|
|||||||
const handleGeneratePDF = async () => {
|
const handleGeneratePDF = async () => {
|
||||||
const reportElement = reportRef.current
|
const reportElement = reportRef.current
|
||||||
|
|
||||||
|
if (!reportElement) {
|
||||||
|
alert('Report element tidak ditemukan')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set loading state
|
||||||
|
setIsGeneratingPDF(true)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Import jsPDF dan html2canvas
|
// Import jsPDF dan html2canvas
|
||||||
const jsPDF = (await import('jspdf')).default
|
const jsPDF = (await import('jspdf')).default
|
||||||
const html2canvas = (await import('html2canvas')).default
|
const html2canvas = (await import('html2canvas')).default
|
||||||
|
|
||||||
// Optimized canvas capture dengan scale lebih rendah
|
// Pastikan element terlihat penuh
|
||||||
const canvas = await html2canvas(reportElement!, {
|
const originalOverflow = reportElement.style.overflow
|
||||||
scale: 1.5, // Reduced from 2 to 1.5
|
reportElement.style.overflow = 'visible'
|
||||||
|
|
||||||
|
// Wait untuk memastikan rendering selesai
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 300))
|
||||||
|
|
||||||
|
console.log('Starting PDF generation...')
|
||||||
|
|
||||||
|
// Update loading message
|
||||||
|
console.log('Capturing content...')
|
||||||
|
|
||||||
|
// Capture canvas dengan setting yang optimal
|
||||||
|
const canvas = await html2canvas(reportElement, {
|
||||||
|
scale: 1.5,
|
||||||
useCORS: true,
|
useCORS: true,
|
||||||
allowTaint: true,
|
allowTaint: true,
|
||||||
backgroundColor: '#ffffff',
|
backgroundColor: '#ffffff',
|
||||||
logging: false, // Disable logging for performance
|
logging: false,
|
||||||
removeContainer: true, // Clean up after capture
|
removeContainer: true,
|
||||||
imageTimeout: 0, // No timeout for image loading
|
imageTimeout: 0,
|
||||||
height: reportElement!.scrollHeight,
|
height: reportElement.scrollHeight,
|
||||||
width: reportElement!.scrollWidth
|
width: reportElement.scrollWidth,
|
||||||
|
scrollX: 0,
|
||||||
|
scrollY: 0,
|
||||||
|
// Pastikan capture semua content
|
||||||
|
windowWidth: Math.max(reportElement.scrollWidth, window.innerWidth),
|
||||||
|
windowHeight: Math.max(reportElement.scrollHeight, window.innerHeight)
|
||||||
})
|
})
|
||||||
|
|
||||||
// Compress canvas using JPEG with quality setting
|
console.log('Canvas captured:', canvas.width, 'x', canvas.height)
|
||||||
const imgData = canvas.toDataURL('image/jpeg', 0.85) // JPEG with 85% quality instead of PNG
|
console.log('Generating PDF pages...')
|
||||||
|
|
||||||
// Create PDF with compression
|
// Restore overflow
|
||||||
|
reportElement.style.overflow = originalOverflow
|
||||||
|
|
||||||
|
// Create PDF
|
||||||
const pdf = new jsPDF({
|
const pdf = new jsPDF({
|
||||||
orientation: 'portrait',
|
orientation: 'portrait',
|
||||||
unit: 'mm',
|
unit: 'mm',
|
||||||
format: 'a4',
|
format: 'a4',
|
||||||
compress: true // Enable built-in compression
|
compress: true
|
||||||
})
|
})
|
||||||
|
|
||||||
const imgWidth = 210
|
// A4 dimensions
|
||||||
const pageHeight = 295
|
const pdfWidth = 210
|
||||||
const imgHeight = (canvas.height * imgWidth) / canvas.width
|
const pdfHeight = 297
|
||||||
let heightLeft = imgHeight
|
const margin = 5 // Small margin to prevent cutoff
|
||||||
let position = 0
|
|
||||||
|
|
||||||
// Add first page with compressed image
|
// Calculate scaling
|
||||||
pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight, '', 'FAST') // Use FAST compression
|
const availableWidth = pdfWidth - 2 * margin
|
||||||
heightLeft -= pageHeight
|
const availableHeight = pdfHeight - 2 * margin
|
||||||
|
|
||||||
// Handle multiple pages if needed
|
const imgWidth = availableWidth
|
||||||
while (heightLeft >= 0) {
|
const imgHeight = (canvas.height * availableWidth) / canvas.width
|
||||||
position = heightLeft - imgHeight
|
|
||||||
|
console.log('PDF dimensions - Canvas:', canvas.width, 'x', canvas.height)
|
||||||
|
console.log('PDF dimensions - Image:', imgWidth, 'x', imgHeight)
|
||||||
|
console.log('Available height per page:', availableHeight)
|
||||||
|
|
||||||
|
// Split content across pages
|
||||||
|
let yPosition = margin
|
||||||
|
let sourceY = 0
|
||||||
|
let pageCount = 1
|
||||||
|
let remainingHeight = imgHeight
|
||||||
|
|
||||||
|
while (remainingHeight > 0) {
|
||||||
|
console.log(`Processing page ${pageCount}, remaining height: ${remainingHeight}`)
|
||||||
|
|
||||||
|
if (pageCount > 1) {
|
||||||
pdf.addPage()
|
pdf.addPage()
|
||||||
pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight, '', 'FAST')
|
yPosition = margin
|
||||||
heightLeft -= pageHeight
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Additional compression options
|
// Calculate how much content fits on this page
|
||||||
|
const heightForThisPage = Math.min(remainingHeight, availableHeight)
|
||||||
|
|
||||||
|
// Calculate source dimensions for cropping
|
||||||
|
const sourceHeight = (heightForThisPage * canvas.height) / imgHeight
|
||||||
|
|
||||||
|
// Create temporary canvas for this page portion
|
||||||
|
const tempCanvas = document.createElement('canvas')
|
||||||
|
const tempCtx = tempCanvas.getContext('2d')
|
||||||
|
|
||||||
|
if (!tempCtx) {
|
||||||
|
throw new Error('Unable to get 2D context from canvas')
|
||||||
|
}
|
||||||
|
|
||||||
|
tempCanvas.width = canvas.width
|
||||||
|
tempCanvas.height = sourceHeight
|
||||||
|
|
||||||
|
// Draw the portion we need
|
||||||
|
tempCtx.drawImage(
|
||||||
|
canvas,
|
||||||
|
0,
|
||||||
|
sourceY,
|
||||||
|
canvas.width,
|
||||||
|
sourceHeight, // Source rectangle
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
canvas.width,
|
||||||
|
sourceHeight // Destination rectangle
|
||||||
|
)
|
||||||
|
|
||||||
|
// Convert to image data
|
||||||
|
const pageImageData = tempCanvas.toDataURL('image/jpeg', 0.9)
|
||||||
|
|
||||||
|
// Add to PDF
|
||||||
|
pdf.addImage(pageImageData, 'JPEG', margin, yPosition, imgWidth, heightForThisPage)
|
||||||
|
|
||||||
|
// Update for next page
|
||||||
|
sourceY += sourceHeight
|
||||||
|
remainingHeight -= heightForThisPage
|
||||||
|
pageCount++
|
||||||
|
|
||||||
|
// Safety check to prevent infinite loop
|
||||||
|
if (pageCount > 20) {
|
||||||
|
console.warn('Too many pages, breaking loop')
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`Generated ${pageCount - 1} pages`)
|
||||||
|
console.log('Finalizing PDF...')
|
||||||
|
|
||||||
|
// Add metadata
|
||||||
pdf.setProperties({
|
pdf.setProperties({
|
||||||
title: `${getReportTitle()}`,
|
title: getReportTitle(),
|
||||||
subject: 'Daily Transaction Report',
|
subject: 'Transaction Report',
|
||||||
author: 'Apskel POS System',
|
author: 'Apskel POS System',
|
||||||
creator: 'Apskel'
|
creator: 'Apskel'
|
||||||
})
|
})
|
||||||
|
|
||||||
// Save with optimized settings
|
// Generate filename
|
||||||
const fileName =
|
const fileName =
|
||||||
filterType === 'single'
|
filterType === 'single'
|
||||||
? `laporan-transaksi-${formatDateForInput(selectedDate)}.pdf`
|
? `laporan-transaksi-${formatDateForInput(selectedDate)}.pdf`
|
||||||
: `laporan-transaksi-${formatDateForInput(dateRange.startDate)}-to-${formatDateForInput(dateRange.endDate)}.pdf`
|
: `laporan-transaksi-${formatDateForInput(dateRange.startDate)}-to-${formatDateForInput(dateRange.endDate)}.pdf`
|
||||||
|
|
||||||
pdf.save(fileName, {
|
console.log('Saving PDF:', fileName)
|
||||||
returnPromise: true
|
|
||||||
})
|
|
||||||
|
|
||||||
// Clean up canvas to free memory
|
// Save PDF
|
||||||
canvas.width = canvas.height = 0
|
pdf.save(fileName)
|
||||||
|
|
||||||
|
console.log('PDF generated successfully!')
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error generating PDF:', error)
|
console.error('Error generating PDF:', error)
|
||||||
alert('Terjadi kesalahan saat membuat PDF. Pastikan jsPDF dan html2canvas sudah terinstall.')
|
alert(`Terjadi kesalahan saat membuat PDF: ${error}`)
|
||||||
|
} finally {
|
||||||
|
// Reset loading state
|
||||||
|
setIsGeneratingPDF(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'>
|
||||||
|
{/* Animated Spinner */}
|
||||||
|
<div className='inline-block animate-spin rounded-full h-12 w-12 border-4 border-gray-200 border-t-purple-600 mb-4'></div>
|
||||||
|
|
||||||
|
{/* Loading Message */}
|
||||||
|
<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>
|
||||||
|
|
||||||
|
{/* Progress Steps */}
|
||||||
|
<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>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className='min-h-screen'>
|
<div className='min-h-screen'>
|
||||||
|
<LoadingOverlay isVisible={isGeneratingPDF} message='Membuat PDF Laporan...' />
|
||||||
{/* Control Panel */}
|
{/* Control Panel */}
|
||||||
<ReportGeneratorComponent
|
<ReportGeneratorComponent
|
||||||
// Props wajib
|
// Props wajib
|
||||||
|
className='min-w-full'
|
||||||
reportTitle='Laporan Penjualan'
|
reportTitle='Laporan Penjualan'
|
||||||
filterType={filterType}
|
filterType={filterType}
|
||||||
selectedDate={selectedDate}
|
selectedDate={selectedDate}
|
||||||
@@ -208,126 +333,62 @@ const DailyPOSReport = () => {
|
|||||||
{/* Performance Summary */}
|
{/* Performance Summary */}
|
||||||
<div className='p-8'>
|
<div className='p-8'>
|
||||||
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
|
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
|
||||||
1. Ringkasan
|
Ringkasan
|
||||||
</h3>
|
</h3>
|
||||||
|
|
||||||
<div className='grid grid-cols-2 gap-6'>
|
|
||||||
<div className='space-y-4'>
|
<div className='space-y-4'>
|
||||||
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
<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='text-gray-700'>Total Penjualan</span>
|
||||||
<span className='font-semibold text-gray-800'>
|
<span className='font-semibold text-gray-800'>
|
||||||
{formatCurrency(profitLoss?.summary.total_revenue ?? 0)}
|
{formatCurrency(profitLoss?.summary.total_revenue ?? 0)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
||||||
<span className='text-gray-700'>Total Terjual</span>
|
<span className='text-gray-700'>Total Diskon</span>
|
||||||
<span className='font-semibold text-gray-800'>{productSummary.totalQuantitySold}</span>
|
<span className='font-semibold text-gray-800'>
|
||||||
|
{formatCurrency(profitLoss?.summary.total_discount ?? 0)}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
||||||
<span className='text-gray-700'>HPP</span>
|
<span className='text-gray-700'>Total Pajak</span>
|
||||||
<span className='font-semibold text-gray-800'>
|
<span className='font-semibold text-gray-800'>{formatCurrency(profitLoss?.summary.total_tax ?? 0)}</span>
|
||||||
{formatCurrency(profitLoss?.summary.total_cost ?? 0)} |{' '}
|
|
||||||
{(((profitLoss?.summary.total_cost ?? 0) / (profitLoss?.summary.total_revenue || 1)) * 100).toFixed(
|
|
||||||
0
|
|
||||||
)}
|
|
||||||
%
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
<div className='flex justify-between items-center py-2 border-b-2 border-gray-300'>
|
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
||||||
<span className='text-lg font-semibold text-green-800'>Laba Kotor</span>
|
<span className='text-gray-700 font-bold'>Total</span>
|
||||||
<span className='text-lg font-bold text-green-800'>
|
<span className='font-bold text-gray-800'>{formatCurrency(profitLoss?.summary.total_revenue ?? 0)}</span>
|
||||||
{formatCurrency(profitLoss?.summary.gross_profit ?? 0)} |{' '}
|
|
||||||
{(profitLoss?.summary.gross_profit_margin ?? 0).toFixed(0)}%
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className='px-8 pb-8'>
|
||||||
|
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
|
||||||
|
Invoice
|
||||||
|
</h3>
|
||||||
|
|
||||||
<div className='space-y-4'>
|
<div className='space-y-4'>
|
||||||
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
||||||
<span className='text-gray-700'>Biaya lain²</span>
|
<span className='text-gray-700'>Total Invoice</span>
|
||||||
|
<span className='font-semibold text-gray-800'>{profitLoss?.summary.total_orders ?? 0}</span>
|
||||||
|
</div>
|
||||||
|
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
|
||||||
|
<span className='text-gray-700'>Rata-rata Tagihan Per Invoice </span>
|
||||||
<span className='font-semibold text-gray-800'>
|
<span className='font-semibold text-gray-800'>
|
||||||
{formatCurrency(profitLoss?.summary.total_tax ?? 0)} |{' '}
|
{formatCurrency(profitLoss?.summary.average_profit ?? 0)}
|
||||||
{(((profitLoss?.summary.total_tax ?? 0) / (profitLoss?.summary.total_revenue || 1)) * 100).toFixed(0)}
|
|
||||||
%
|
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</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>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Profit Loss Product Table */}
|
|
||||||
<div className='px-8 pb-8'>
|
|
||||||
<h3 className='text-lg font-medium mb-6' style={{ color: '#36175e' }}>
|
|
||||||
Laba Rugi Per Produk
|
|
||||||
</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>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Payment Method Summary */}
|
{/* Payment Method Summary */}
|
||||||
<div className='px-8 pb-8'>
|
<div className='px-8 pb-8'>
|
||||||
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
|
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
|
||||||
2. Ringkasan Metode Pembayaran
|
Ringkasan Metode Pembayaran
|
||||||
</h3>
|
</h3>
|
||||||
|
|
||||||
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
|
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
|
||||||
<table className='w-full'>
|
<table className='w-full'>
|
||||||
<thead>
|
<thead>
|
||||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
<tr className='text-gray-800 border-b-2 border-gray-300'>
|
||||||
<th className='text-left p-3 font-semibold'>Metode Pembayaran</th>
|
<th className='text-left 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'>Tipe</th>
|
||||||
<th className='text-center p-3 font-semibold'>Jumlah Order</th>
|
<th className='text-center p-3 font-semibold'>Jumlah Order</th>
|
||||||
@@ -361,7 +422,7 @@ const DailyPOSReport = () => {
|
|||||||
)) || []}
|
)) || []}
|
||||||
</tbody>
|
</tbody>
|
||||||
<tfoot>
|
<tfoot>
|
||||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
<tr className='text-gray-800 border-t-2 border-gray-300'>
|
||||||
<td className='p-3 font-bold'>TOTAL</td>
|
<td className='p-3 font-bold'>TOTAL</td>
|
||||||
<td className='p-3'></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-center font-bold'>{paymentAnalytics?.summary.total_orders ?? 0}</td>
|
||||||
@@ -378,18 +439,17 @@ const DailyPOSReport = () => {
|
|||||||
{/* Category Summary */}
|
{/* Category Summary */}
|
||||||
<div className='px-8 pb-8'>
|
<div className='px-8 pb-8'>
|
||||||
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
|
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
|
||||||
2. Ringkasan Kategori
|
Ringkasan Kategori
|
||||||
</h3>
|
</h3>
|
||||||
|
|
||||||
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
|
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
|
||||||
<table className='w-full'>
|
<table className='w-full'>
|
||||||
<thead>
|
<thead>
|
||||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
<tr className='text-gray-800 border-b-2 border-gray-300'>
|
||||||
<th className='text-left p-3 font-semibold'>Nama</th>
|
<th className='text-left 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'>Total Produk</th>
|
||||||
<th className='text-center p-3 font-semibold'>Qty</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-right p-3 font-semibold'>Pendapatan</th>
|
||||||
<th className='text-center p-3 font-semibold'>Pendapatan</th>
|
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
@@ -398,7 +458,6 @@ const DailyPOSReport = () => {
|
|||||||
<td className='p-3 font-medium text-gray-800'>{c.category_name}</td>
|
<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.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.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' }}>
|
<td className='p-3 text-right font-semibold' style={{ color: '#36175e' }}>
|
||||||
{formatCurrency(c.total_revenue)}
|
{formatCurrency(c.total_revenue)}
|
||||||
</td>
|
</td>
|
||||||
@@ -406,11 +465,10 @@ const DailyPOSReport = () => {
|
|||||||
)) || []}
|
)) || []}
|
||||||
</tbody>
|
</tbody>
|
||||||
<tfoot>
|
<tfoot>
|
||||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
<tr className='text-gray-800 border-t-2 border-gray-300'>
|
||||||
<td className='p-3 font-bold'>TOTAL</td>
|
<td className='p-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?.productCount ?? 0}</td>
|
||||||
<td className='p-3 text-center font-bold'>{categorySummary?.totalQuantity ?? 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>
|
<td className='p-3 text-right font-bold'>{formatCurrency(categorySummary?.totalRevenue ?? 0)}</td>
|
||||||
</tr>
|
</tr>
|
||||||
</tfoot>
|
</tfoot>
|
||||||
@@ -421,48 +479,163 @@ const DailyPOSReport = () => {
|
|||||||
{/* Transaction Summary */}
|
{/* Transaction Summary */}
|
||||||
<div className='px-8 pb-8'>
|
<div className='px-8 pb-8'>
|
||||||
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
|
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
|
||||||
4. Ringkasan Item
|
Ringkasan Item
|
||||||
</h3>
|
</h3>
|
||||||
|
|
||||||
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
|
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-visible'>
|
||||||
<table className='w-full'>
|
<div className='overflow-x-auto'>
|
||||||
|
<table className='w-full table-fixed' style={{ minWidth: '100%' }}>
|
||||||
|
<colgroup>
|
||||||
|
<col style={{ width: '40%' }} />
|
||||||
|
<col style={{ width: '15%' }} />
|
||||||
|
<col style={{ width: '15%' }} />
|
||||||
|
<col style={{ width: '15%' }} />
|
||||||
|
<col style={{ width: '15%' }} />
|
||||||
|
</colgroup>
|
||||||
<thead>
|
<thead>
|
||||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
<tr className='text-gray-800 border-b-2 border-gray-300'>
|
||||||
<th className='text-left p-3 font-semibold'>Produk</th>
|
<th className='text-left p-3 font-semibold border-r border-gray-300'>Produk</th>
|
||||||
<th className='text-left p-3 font-semibold'>Kategori</th>
|
<th className='text-center p-3 font-semibold border-r border-gray-300'>Qty</th>
|
||||||
<th className='text-center p-3 font-semibold'>Qty</th>
|
<th className='text-center p-3 font-semibold border-r border-gray-300'>Order</th>
|
||||||
<th className='text-right p-3 font-semibold'>Order</th>
|
<th className='text-right p-3 font-semibold border-r border-gray-300'>Pendapatan</th>
|
||||||
<th className='text-right p-3 font-semibold'>Pendapatan</th>
|
|
||||||
<th className='text-right p-3 font-semibold'>Rata Rata</th>
|
<th className='text-right p-3 font-semibold'>Rata Rata</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{products?.data?.map((item, index) => (
|
{(() => {
|
||||||
<tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
|
// Group products by category
|
||||||
<td className='p-3 font-medium text-gray-800'>{item.product_name}</td>
|
const groupedProducts =
|
||||||
<td className='p-3 font-medium text-gray-800'>{item.category_name}</td>
|
products?.data?.reduce(
|
||||||
<td className='p-3 text-center text-gray-700'>{item.quantity_sold}</td>
|
(acc, item) => {
|
||||||
<td className='p-3 text-center text-gray-700'>{item.order_count ?? 0}</td>
|
const categoryName = item.category_name || 'Tidak Berkategori'
|
||||||
<td className='p-3 text-right font-semibold text-gray-800'>{formatCurrency(item.revenue)}</td>
|
if (!acc[categoryName]) {
|
||||||
<td className='p-3 text-right font-medium text-gray-800'>{formatCurrency(item.average_price)}</td>
|
acc[categoryName] = []
|
||||||
|
}
|
||||||
|
acc[categoryName].push(item)
|
||||||
|
return acc
|
||||||
|
},
|
||||||
|
{} as Record<string, any[]>
|
||||||
|
) || {}
|
||||||
|
|
||||||
|
const rows: JSX.Element[] = []
|
||||||
|
let globalIndex = 0
|
||||||
|
|
||||||
|
// Sort categories alphabetically
|
||||||
|
Object.keys(groupedProducts)
|
||||||
|
.sort()
|
||||||
|
.forEach(categoryName => {
|
||||||
|
const categoryProducts = groupedProducts[categoryName]
|
||||||
|
|
||||||
|
// Category header row
|
||||||
|
rows.push(
|
||||||
|
<tr
|
||||||
|
key={`category-${categoryName}`}
|
||||||
|
className='bg-gray-100 border-b border-gray-300'
|
||||||
|
style={{ pageBreakInside: 'avoid' }}
|
||||||
|
>
|
||||||
|
<td
|
||||||
|
className='p-3 font-bold text-gray-900 border-r border-gray-300'
|
||||||
|
style={{ color: '#36175e' }}
|
||||||
|
>
|
||||||
|
{categoryName.toUpperCase()}
|
||||||
|
</td>
|
||||||
|
<td className='p-3 border-r border-gray-300'></td>
|
||||||
|
<td className='p-3 border-r border-gray-300'></td>
|
||||||
|
<td className='p-3 border-r border-gray-300'></td>
|
||||||
|
<td className='p-3'></td>
|
||||||
</tr>
|
</tr>
|
||||||
)) || []}
|
)
|
||||||
|
|
||||||
|
// Product rows for this category
|
||||||
|
categoryProducts.forEach((item, index) => {
|
||||||
|
globalIndex++
|
||||||
|
rows.push(
|
||||||
|
<tr
|
||||||
|
key={`product-${item.product_name}-${index}`}
|
||||||
|
className={`${globalIndex % 2 === 0 ? 'bg-white' : 'bg-gray-50'} border-b border-gray-200`}
|
||||||
|
style={{ pageBreakInside: 'avoid' }}
|
||||||
|
>
|
||||||
|
<td
|
||||||
|
className='p-3 pl-6 font-medium text-gray-800 border-r border-gray-200'
|
||||||
|
style={{ wordWrap: 'break-word' }}
|
||||||
|
>
|
||||||
|
{item.product_name}
|
||||||
|
</td>
|
||||||
|
<td className='p-3 text-center text-gray-700 border-r border-gray-200'>
|
||||||
|
{item.quantity_sold}
|
||||||
|
</td>
|
||||||
|
<td className='p-3 text-center text-gray-700 border-r border-gray-200'>
|
||||||
|
{item.order_count ?? 0}
|
||||||
|
</td>
|
||||||
|
<td className='p-3 text-right font-semibold text-gray-800 border-r border-gray-200'>
|
||||||
|
{formatCurrency(item.revenue)}
|
||||||
|
</td>
|
||||||
|
<td className='p-3 text-right font-medium text-gray-800'>
|
||||||
|
{formatCurrency(item.average_price)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Category subtotal row
|
||||||
|
const categoryTotalQty = categoryProducts.reduce(
|
||||||
|
(sum, item) => sum + (item.quantity_sold || 0),
|
||||||
|
0
|
||||||
|
)
|
||||||
|
const categoryTotalOrders = categoryProducts.reduce(
|
||||||
|
(sum, item) => sum + (item.order_count || 0),
|
||||||
|
0
|
||||||
|
)
|
||||||
|
const categoryTotalRevenue = categoryProducts.reduce(
|
||||||
|
(sum, item) => sum + (item.revenue || 0),
|
||||||
|
0
|
||||||
|
)
|
||||||
|
|
||||||
|
rows.push(
|
||||||
|
<tr
|
||||||
|
key={`subtotal-${categoryName}`}
|
||||||
|
className='bg-gray-200 border-b-2 border-gray-400'
|
||||||
|
style={{ pageBreakInside: 'avoid' }}
|
||||||
|
>
|
||||||
|
<td className='p-3 pl-6 font-semibold text-gray-800 border-r border-gray-400'>
|
||||||
|
Subtotal {categoryName}
|
||||||
|
</td>
|
||||||
|
<td className='p-3 text-center font-semibold text-gray-800 border-r border-gray-400'>
|
||||||
|
{categoryTotalQty}
|
||||||
|
</td>
|
||||||
|
<td className='p-3 text-center font-semibold text-gray-800 border-r border-gray-400'>
|
||||||
|
{categoryTotalOrders}
|
||||||
|
</td>
|
||||||
|
<td className='p-3 text-right font-semibold text-gray-800 border-r border-gray-400'>
|
||||||
|
{formatCurrency(categoryTotalRevenue)}
|
||||||
|
</td>
|
||||||
|
<td className='p-3'></td>
|
||||||
|
</tr>
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
return rows
|
||||||
|
})()}
|
||||||
</tbody>
|
</tbody>
|
||||||
<tfoot>
|
<tfoot>
|
||||||
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
|
<tr className='text-gray-800 border-t-2 border-gray-300' style={{ pageBreakInside: 'avoid' }}>
|
||||||
<td className='p-3 font-bold'>TOTAL</td>
|
<td className='p-3 font-bold border-r border-gray-300'>TOTAL KESELURUHAN</td>
|
||||||
<td className='p-3 text-center'></td>
|
<td className='p-3 text-center font-bold border-r border-gray-300'>
|
||||||
<td className='p-3 text-center font-bold'>{productSummary.totalQuantitySold ?? 0}</td>
|
{productSummary.totalQuantitySold ?? 0}
|
||||||
<td className='p-3 text-right font-bold'>{productSummary.totalOrders ?? 0}</td>
|
</td>
|
||||||
<td className='p-3 text-right font-bold'>{formatCurrency(productSummary.totalRevenue ?? 0)}</td>
|
<td className='p-3 text-center font-bold border-r border-gray-300'>
|
||||||
<td className='p-3 text-right font-bold'></td>
|
{productSummary.totalOrders ?? 0}
|
||||||
|
</td>
|
||||||
|
<td className='p-3 text-right font-bold border-r border-gray-300'>
|
||||||
|
{formatCurrency(productSummary.totalRevenue ?? 0)}
|
||||||
|
</td>
|
||||||
|
<td className='p-3'></td>
|
||||||
</tr>
|
</tr>
|
||||||
</tfoot>
|
</tfoot>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
{/* Profit Loss Product Table */}
|
|
||||||
|
|
||||||
{/* Footer */}
|
{/* Footer */}
|
||||||
<div className='px-8 py-6 border-t-2 border-gray-200 mt-8'>
|
<div className='px-8 py-6 border-t-2 border-gray-200 mt-8'>
|
||||||
|
|||||||
@@ -0,0 +1,465 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
// React Imports
|
||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
|
||||||
|
// MUI Imports
|
||||||
|
import type { BoxProps } from '@mui/material/Box'
|
||||||
|
import Button from '@mui/material/Button'
|
||||||
|
import IconButton from '@mui/material/IconButton'
|
||||||
|
import List from '@mui/material/List'
|
||||||
|
import ListItem from '@mui/material/ListItem'
|
||||||
|
import Typography from '@mui/material/Typography'
|
||||||
|
import Chip from '@mui/material/Chip'
|
||||||
|
import LinearProgress from '@mui/material/LinearProgress'
|
||||||
|
import { styled } from '@mui/material/styles'
|
||||||
|
|
||||||
|
// Third-party Imports
|
||||||
|
import { useDropzone } from 'react-dropzone'
|
||||||
|
|
||||||
|
// Component Imports
|
||||||
|
import Link from '@components/Link'
|
||||||
|
import CustomAvatar from '@core/components/mui/Avatar'
|
||||||
|
|
||||||
|
// Styled Component Imports
|
||||||
|
import AppReactDropzone from '@/libs/styles/AppReactDropzone'
|
||||||
|
|
||||||
|
type FileProp = {
|
||||||
|
name: string
|
||||||
|
type: string
|
||||||
|
size: number
|
||||||
|
}
|
||||||
|
|
||||||
|
type UploadedImage = {
|
||||||
|
id: string
|
||||||
|
url: string
|
||||||
|
name: string
|
||||||
|
size: number
|
||||||
|
}
|
||||||
|
|
||||||
|
type UploadProgress = {
|
||||||
|
[fileId: string]: number
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MultipleImageUploadProps {
|
||||||
|
// Required props
|
||||||
|
onUpload: (files: File[]) => Promise<string[]> | string[] // Returns array of image URLs
|
||||||
|
onSingleUpload?: (file: File) => Promise<string> | string // For individual file upload
|
||||||
|
|
||||||
|
// Optional customization props
|
||||||
|
title?: string | null
|
||||||
|
currentImages?: UploadedImage[]
|
||||||
|
onImagesChange?: (images: UploadedImage[]) => void
|
||||||
|
onImageRemove?: (imageId: string) => void
|
||||||
|
|
||||||
|
// Upload state
|
||||||
|
isUploading?: boolean
|
||||||
|
uploadProgress?: UploadProgress
|
||||||
|
|
||||||
|
// Limits
|
||||||
|
maxFiles?: number
|
||||||
|
maxFileSize?: number // in bytes
|
||||||
|
acceptedFileTypes?: string[]
|
||||||
|
|
||||||
|
// UI customization
|
||||||
|
showUrlOption?: boolean
|
||||||
|
uploadButtonText?: string
|
||||||
|
browseButtonText?: string
|
||||||
|
dragDropText?: string
|
||||||
|
replaceText?: string
|
||||||
|
maxFilesText?: string
|
||||||
|
|
||||||
|
// Style customization
|
||||||
|
className?: string
|
||||||
|
disabled?: boolean
|
||||||
|
|
||||||
|
// Upload modes
|
||||||
|
uploadMode?: 'batch' | 'individual' // batch: upload all at once, individual: upload one by one
|
||||||
|
}
|
||||||
|
|
||||||
|
// Styled Dropzone Component
|
||||||
|
const Dropzone = styled(AppReactDropzone)<BoxProps>(({ theme }) => ({
|
||||||
|
'& .dropzone': {
|
||||||
|
minHeight: 'unset',
|
||||||
|
padding: theme.spacing(12),
|
||||||
|
[theme.breakpoints.down('sm')]: {
|
||||||
|
paddingInline: theme.spacing(5)
|
||||||
|
},
|
||||||
|
'&+.MuiList-root .MuiListItem-root .file-name': {
|
||||||
|
fontWeight: theme.typography.body1.fontWeight
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
|
||||||
|
const MultipleImageUpload: React.FC<MultipleImageUploadProps> = ({
|
||||||
|
onUpload,
|
||||||
|
onSingleUpload,
|
||||||
|
title = null,
|
||||||
|
currentImages = [],
|
||||||
|
onImagesChange,
|
||||||
|
onImageRemove,
|
||||||
|
isUploading = false,
|
||||||
|
uploadProgress = {},
|
||||||
|
maxFiles = 10,
|
||||||
|
maxFileSize = 5 * 1024 * 1024, // 5MB default
|
||||||
|
acceptedFileTypes = ['image/*'],
|
||||||
|
showUrlOption = true,
|
||||||
|
uploadButtonText = 'Upload All',
|
||||||
|
browseButtonText = 'Browse Images',
|
||||||
|
dragDropText = 'Drag and Drop Your Images Here.',
|
||||||
|
replaceText = 'Drop Images to Add More',
|
||||||
|
maxFilesText = 'Maximum {max} files allowed',
|
||||||
|
className = '',
|
||||||
|
disabled = false,
|
||||||
|
uploadMode = 'batch'
|
||||||
|
}) => {
|
||||||
|
// States
|
||||||
|
const [files, setFiles] = useState<File[]>([])
|
||||||
|
const [error, setError] = useState<string>('')
|
||||||
|
const [individualUploading, setIndividualUploading] = useState<Set<string>>(new Set())
|
||||||
|
|
||||||
|
const handleBatchUpload = async () => {
|
||||||
|
if (!files.length) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
setError('')
|
||||||
|
const imageUrls = await onUpload(files)
|
||||||
|
|
||||||
|
if (Array.isArray(imageUrls)) {
|
||||||
|
const newImages: UploadedImage[] = files.map((file, index) => ({
|
||||||
|
id: `${Date.now()}-${index}`,
|
||||||
|
url: imageUrls[index],
|
||||||
|
name: file.name,
|
||||||
|
size: file.size
|
||||||
|
}))
|
||||||
|
|
||||||
|
const updatedImages = [...currentImages, ...newImages]
|
||||||
|
onImagesChange?.(updatedImages)
|
||||||
|
setFiles([]) // Clear files after successful upload
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Upload failed')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleIndividualUpload = async (file: File, fileIndex: number) => {
|
||||||
|
if (!onSingleUpload) return
|
||||||
|
|
||||||
|
const fileId = `${file.name}-${fileIndex}`
|
||||||
|
setIndividualUploading(prev => new Set(prev).add(fileId))
|
||||||
|
|
||||||
|
try {
|
||||||
|
setError('')
|
||||||
|
const imageUrl = await onSingleUpload(file)
|
||||||
|
|
||||||
|
if (typeof imageUrl === 'string') {
|
||||||
|
const newImage: UploadedImage = {
|
||||||
|
id: `${Date.now()}-${fileIndex}`,
|
||||||
|
url: imageUrl,
|
||||||
|
name: file.name,
|
||||||
|
size: file.size
|
||||||
|
}
|
||||||
|
|
||||||
|
const updatedImages = [...currentImages, newImage]
|
||||||
|
onImagesChange?.(updatedImages)
|
||||||
|
|
||||||
|
// Remove uploaded file from pending files
|
||||||
|
setFiles(prev => prev.filter((_, index) => index !== fileIndex))
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Upload failed')
|
||||||
|
} finally {
|
||||||
|
setIndividualUploading(prev => {
|
||||||
|
const newSet = new Set(prev)
|
||||||
|
newSet.delete(fileId)
|
||||||
|
return newSet
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hooks
|
||||||
|
const { getRootProps, getInputProps } = useDropzone({
|
||||||
|
onDrop: (acceptedFiles: File[]) => {
|
||||||
|
setError('')
|
||||||
|
|
||||||
|
if (acceptedFiles.length === 0) return
|
||||||
|
|
||||||
|
const totalFiles = currentImages.length + files.length + acceptedFiles.length
|
||||||
|
|
||||||
|
if (totalFiles > maxFiles) {
|
||||||
|
setError(`Cannot upload more than ${maxFiles} files. Current: ${currentImages.length + files.length}`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate file sizes
|
||||||
|
const invalidFiles = acceptedFiles.filter(file => file.size > maxFileSize)
|
||||||
|
if (invalidFiles.length > 0) {
|
||||||
|
setError(`Some files exceed ${formatFileSize(maxFileSize)} limit`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add to existing files
|
||||||
|
setFiles(prev => [...prev, ...acceptedFiles])
|
||||||
|
},
|
||||||
|
accept: acceptedFileTypes.reduce((acc, type) => ({ ...acc, [type]: [] }), {}),
|
||||||
|
disabled: disabled || isUploading,
|
||||||
|
multiple: true
|
||||||
|
})
|
||||||
|
|
||||||
|
const formatFileSize = (bytes: number): string => {
|
||||||
|
if (bytes === 0) return '0 Bytes'
|
||||||
|
const k = 1024
|
||||||
|
const sizes = ['Bytes', 'KB', 'MB', 'GB']
|
||||||
|
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||||
|
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
|
||||||
|
}
|
||||||
|
|
||||||
|
const renderFilePreview = (file: FileProp) => {
|
||||||
|
if (file.type.startsWith('image')) {
|
||||||
|
return (
|
||||||
|
<img
|
||||||
|
width={38}
|
||||||
|
height={38}
|
||||||
|
alt={file.name}
|
||||||
|
src={URL.createObjectURL(file as any)}
|
||||||
|
className='rounded object-cover'
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
return <i className='tabler-file-description' />
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleRemoveFile = (fileIndex: number) => {
|
||||||
|
setFiles(prev => prev.filter((_, index) => index !== fileIndex))
|
||||||
|
setError('')
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleRemoveCurrentImage = (imageId: string) => {
|
||||||
|
onImageRemove?.(imageId)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleRemoveAllFiles = () => {
|
||||||
|
setFiles([])
|
||||||
|
setError('')
|
||||||
|
}
|
||||||
|
|
||||||
|
const isIndividualUploading = (file: File, index: number) => {
|
||||||
|
const fileId = `${file.name}-${index}`
|
||||||
|
return individualUploading.has(fileId)
|
||||||
|
}
|
||||||
|
|
||||||
|
const fileList = files.map((file: File, index: number) => {
|
||||||
|
const isFileUploading = isIndividualUploading(file, index)
|
||||||
|
const progress = uploadProgress[`${file.name}-${index}`] || 0
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ListItem key={`${file.name}-${index}`} className='pis-4 plb-3'>
|
||||||
|
<div className='file-details flex-1'>
|
||||||
|
<div className='file-preview'>{renderFilePreview(file)}</div>
|
||||||
|
<div className='flex-1'>
|
||||||
|
<Typography className='file-name font-medium' color='text.primary'>
|
||||||
|
{file.name}
|
||||||
|
</Typography>
|
||||||
|
<Typography className='file-size' variant='body2'>
|
||||||
|
{formatFileSize(file.size)}
|
||||||
|
</Typography>
|
||||||
|
{isFileUploading && progress > 0 && (
|
||||||
|
<LinearProgress variant='determinate' value={progress} className='mt-1' />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className='flex items-center gap-2'>
|
||||||
|
{uploadMode === 'individual' && onSingleUpload && (
|
||||||
|
<Button
|
||||||
|
variant='outlined'
|
||||||
|
size='small'
|
||||||
|
onClick={() => handleIndividualUpload(file, index)}
|
||||||
|
disabled={isUploading || isFileUploading}
|
||||||
|
>
|
||||||
|
{isFileUploading ? 'Uploading...' : 'Upload'}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<IconButton onClick={() => handleRemoveFile(index)} disabled={isUploading || isFileUploading}>
|
||||||
|
<i className='tabler-x text-xl' />
|
||||||
|
</IconButton>
|
||||||
|
</div>
|
||||||
|
</ListItem>
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
const currentImagesList = currentImages.map(image => (
|
||||||
|
<ListItem key={image.id} className='pis-4 plb-3'>
|
||||||
|
<div className='file-details flex-1'>
|
||||||
|
<div className='file-preview'>
|
||||||
|
<img width={38} height={38} alt={image.name} src={image.url} className='rounded object-cover' />
|
||||||
|
</div>
|
||||||
|
<div className='flex-1'>
|
||||||
|
<Typography className='file-name font-medium' color='text.primary'>
|
||||||
|
{image.name}
|
||||||
|
</Typography>
|
||||||
|
<Typography className='file-size' variant='body2'>
|
||||||
|
{formatFileSize(image.size)}
|
||||||
|
</Typography>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className='flex items-center gap-2'>
|
||||||
|
<Chip label='Uploaded' color='success' size='small' />
|
||||||
|
{onImageRemove && (
|
||||||
|
<IconButton onClick={() => handleRemoveCurrentImage(image.id)} color='error' disabled={isUploading}>
|
||||||
|
<i className='tabler-x text-xl' />
|
||||||
|
</IconButton>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</ListItem>
|
||||||
|
))
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dropzone className={className}>
|
||||||
|
{/* Conditional title and URL option header */}
|
||||||
|
{title && (
|
||||||
|
<div className='flex justify-between items-center mb-4'>
|
||||||
|
<Typography variant='h6' component='h2'>
|
||||||
|
{title}
|
||||||
|
</Typography>
|
||||||
|
{showUrlOption && (
|
||||||
|
<Typography component={Link} color='primary.main' className='font-medium'>
|
||||||
|
Add media from URL
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* File limits info */}
|
||||||
|
<div className='flex justify-between items-center mb-4'>
|
||||||
|
<Typography variant='body2' color='text.secondary'>
|
||||||
|
{maxFilesText.replace('{max}', maxFiles.toString())}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant='body2' color='text.secondary'>
|
||||||
|
{currentImages.length + files.length} / {maxFiles} files
|
||||||
|
</Typography>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div {...getRootProps({ className: 'dropzone' })}>
|
||||||
|
<input {...getInputProps()} />
|
||||||
|
<div className='flex items-center flex-col gap-2 text-center'>
|
||||||
|
<CustomAvatar variant='rounded' skin='light' color='secondary'>
|
||||||
|
<i className='tabler-upload' />
|
||||||
|
</CustomAvatar>
|
||||||
|
<Typography variant='h4'>
|
||||||
|
{currentImages.length > 0 || files.length > 0 ? replaceText : dragDropText}
|
||||||
|
</Typography>
|
||||||
|
<Typography color='text.disabled'>or</Typography>
|
||||||
|
<Button variant='tonal' size='small' disabled={disabled || isUploading}>
|
||||||
|
{browseButtonText}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Error Message */}
|
||||||
|
{error && (
|
||||||
|
<Typography color='error' variant='body2' className='mt-2 text-center'>
|
||||||
|
{error}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Current uploaded images */}
|
||||||
|
{currentImages.length > 0 && (
|
||||||
|
<div className='mt-4'>
|
||||||
|
<Typography variant='subtitle2' className='mb-2'>
|
||||||
|
Uploaded Images ({currentImages.length}):
|
||||||
|
</Typography>
|
||||||
|
<List>{currentImagesList}</List>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Pending files list and upload buttons */}
|
||||||
|
{files.length > 0 && (
|
||||||
|
<div className='mt-4'>
|
||||||
|
<Typography variant='subtitle2' className='mb-2'>
|
||||||
|
Pending Files ({files.length}):
|
||||||
|
</Typography>
|
||||||
|
<List>{fileList}</List>
|
||||||
|
<div className='buttons flex gap-2 mt-3'>
|
||||||
|
<Button color='error' variant='tonal' onClick={handleRemoveAllFiles} disabled={isUploading}>
|
||||||
|
Remove All
|
||||||
|
</Button>
|
||||||
|
{uploadMode === 'batch' && (
|
||||||
|
<Button variant='contained' onClick={handleBatchUpload} disabled={isUploading || files.length === 0}>
|
||||||
|
{isUploading ? 'Uploading...' : `${uploadButtonText} (${files.length})`}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Dropzone>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default MultipleImageUpload
|
||||||
|
|
||||||
|
// ===== USAGE EXAMPLES =====
|
||||||
|
|
||||||
|
// 1. Batch upload mode (upload all files at once)
|
||||||
|
// const [images, setImages] = useState<UploadedImage[]>([])
|
||||||
|
//
|
||||||
|
// <MultipleImageUpload
|
||||||
|
// title="Product Images"
|
||||||
|
// onUpload={handleBatchUpload}
|
||||||
|
// currentImages={images}
|
||||||
|
// onImagesChange={setImages}
|
||||||
|
// onImageRemove={(id) => setImages(prev => prev.filter(img => img.id !== id))}
|
||||||
|
// maxFiles={5}
|
||||||
|
// uploadMode="batch"
|
||||||
|
// />
|
||||||
|
|
||||||
|
// 2. Individual upload mode (upload files one by one)
|
||||||
|
// <MultipleImageUpload
|
||||||
|
// title="Gallery Images"
|
||||||
|
// onUpload={handleBatchUpload}
|
||||||
|
// onSingleUpload={handleSingleUpload}
|
||||||
|
// currentImages={images}
|
||||||
|
// onImagesChange={setImages}
|
||||||
|
// onImageRemove={(id) => setImages(prev => prev.filter(img => img.id !== id))}
|
||||||
|
// maxFiles={10}
|
||||||
|
// uploadMode="individual"
|
||||||
|
// uploadProgress={uploadProgress}
|
||||||
|
// />
|
||||||
|
|
||||||
|
// 3. Without title, custom limits
|
||||||
|
// <MultipleImageUpload
|
||||||
|
// title={null}
|
||||||
|
// onUpload={handleBatchUpload}
|
||||||
|
// currentImages={images}
|
||||||
|
// onImagesChange={setImages}
|
||||||
|
// maxFiles={3}
|
||||||
|
// maxFileSize={2 * 1024 * 1024} // 2MB
|
||||||
|
// acceptedFileTypes={['image/jpeg', 'image/png']}
|
||||||
|
// />
|
||||||
|
|
||||||
|
// 4. Example upload handlers
|
||||||
|
// const handleBatchUpload = async (files: File[]): Promise<string[]> => {
|
||||||
|
// const formData = new FormData()
|
||||||
|
// files.forEach(file => formData.append('images', file))
|
||||||
|
//
|
||||||
|
// const response = await fetch('/api/upload-multiple', {
|
||||||
|
// method: 'POST',
|
||||||
|
// body: formData
|
||||||
|
// })
|
||||||
|
//
|
||||||
|
// const result = await response.json()
|
||||||
|
// return result.urls // Array of uploaded image URLs
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// const handleSingleUpload = async (file: File): Promise<string> => {
|
||||||
|
// const formData = new FormData()
|
||||||
|
// formData.append('image', file)
|
||||||
|
//
|
||||||
|
// const response = await fetch('/api/upload-single', {
|
||||||
|
// method: 'POST',
|
||||||
|
// body: formData
|
||||||
|
// })
|
||||||
|
//
|
||||||
|
// const result = await response.json()
|
||||||
|
// return result.url // Single uploaded image URL
|
||||||
|
// }
|
||||||
@@ -7,6 +7,14 @@ import Menu from '@mui/material/Menu'
|
|||||||
import MenuItem from '@mui/material/MenuItem'
|
import MenuItem from '@mui/material/MenuItem'
|
||||||
import { styled } from '@mui/material/styles'
|
import { styled } from '@mui/material/styles'
|
||||||
|
|
||||||
|
function toTitleCase(str: string): string {
|
||||||
|
return str
|
||||||
|
.toLowerCase()
|
||||||
|
.split(/\s+/) // split by spaces
|
||||||
|
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
|
||||||
|
.join(' ')
|
||||||
|
}
|
||||||
|
|
||||||
const DropdownButton = styled(Button)(({ theme }) => ({
|
const DropdownButton = styled(Button)(({ theme }) => ({
|
||||||
textTransform: 'none',
|
textTransform: 'none',
|
||||||
fontWeight: 400,
|
fontWeight: 400,
|
||||||
@@ -102,7 +110,7 @@ const StatusFilterTabs: React.FC<StatusFilterTabsProps> = ({
|
|||||||
})
|
})
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{status}
|
{toTitleCase(status)}
|
||||||
</Button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -135,7 +143,7 @@ const StatusFilterTabs: React.FC<StatusFilterTabsProps> = ({
|
|||||||
})
|
})
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{status}
|
{toTitleCase(status)}
|
||||||
</Button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
|
|
||||||
@@ -158,7 +166,7 @@ const StatusFilterTabs: React.FC<StatusFilterTabsProps> = ({
|
|||||||
})
|
})
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{isDropdownItemSelected ? selectedStatus : dropdownLabel}
|
{isDropdownItemSelected ? toTitleCase(selectedStatus) : dropdownLabel}
|
||||||
</DropdownButton>
|
</DropdownButton>
|
||||||
|
|
||||||
<Menu
|
<Menu
|
||||||
@@ -187,7 +195,7 @@ const StatusFilterTabs: React.FC<StatusFilterTabsProps> = ({
|
|||||||
color: selectedStatus === status ? 'primary.main' : 'text.primary'
|
color: selectedStatus === status ? 'primary.main' : 'text.primary'
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{status}
|
{toTitleCase(status)}
|
||||||
</MenuItem>
|
</MenuItem>
|
||||||
))}
|
))}
|
||||||
</Menu>
|
</Menu>
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ const HorizontalWithSubtitle = (props: UserDataType) => {
|
|||||||
<div className='flex flex-col gap-1 flex-grow'>
|
<div className='flex flex-col gap-1 flex-grow'>
|
||||||
<Typography color='text.primary'>{title}</Typography>
|
<Typography color='text.primary'>{title}</Typography>
|
||||||
<div className='flex items-center gap-2 flex-wrap'>
|
<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'}>
|
<Typography color={trend === 'negative' ? 'error.main' : 'success.main'}>
|
||||||
{`(${trend === 'negative' ? '-' : '+'}${trendNumber})`}
|
{`(${trend === 'negative' ? '-' : '+'}${trendNumber})`}
|
||||||
</Typography>
|
</Typography>
|
||||||
|
|||||||
@@ -31,27 +31,27 @@ import { getLocalizedUrl } from '@/utils/i18n'
|
|||||||
const shortcuts: ShortcutsType[] = [
|
const shortcuts: ShortcutsType[] = [
|
||||||
{
|
{
|
||||||
url: '/apps/calendar',
|
url: '/apps/calendar',
|
||||||
icon: 'tabler-calendar',
|
icon: 'tabler-box',
|
||||||
title: 'Calendar',
|
title: 'Produk',
|
||||||
subtitle: 'Appointments'
|
subtitle: 'Kelola Produk'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
url: '/apps/invoice/list',
|
url: '/apps/invoice/list',
|
||||||
icon: 'tabler-file-dollar',
|
icon: 'tabler-file-dollar',
|
||||||
title: 'Invoice App',
|
title: 'Pembelian',
|
||||||
subtitle: 'Manage Accounts'
|
subtitle: 'Kelola Pembelian'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
url: '/apps/user/list',
|
url: '/apps/user/list',
|
||||||
icon: 'tabler-user',
|
icon: 'tabler-user',
|
||||||
title: 'Users',
|
title: 'Pengguna',
|
||||||
subtitle: 'Manage Users'
|
subtitle: 'Kelola Pengguna'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
url: '/apps/roles',
|
url: '/apps/vendor',
|
||||||
icon: 'tabler-users-group',
|
icon: 'tabler-users-group',
|
||||||
title: 'Role Management',
|
title: 'Vendor',
|
||||||
subtitle: 'Permissions'
|
subtitle: 'Kelola Vendor'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
url: '/',
|
url: '/',
|
||||||
@@ -60,10 +60,10 @@ const shortcuts: ShortcutsType[] = [
|
|||||||
subtitle: 'User Dashboard'
|
subtitle: 'User Dashboard'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
url: '/pages/account-settings',
|
url: '/apps/reports',
|
||||||
icon: 'tabler-settings',
|
icon: 'tabler-settings',
|
||||||
title: 'Settings',
|
title: 'Laporan',
|
||||||
subtitle: 'Account Settings'
|
subtitle: 'Lihat Laporan'
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -20,28 +20,28 @@ import { verticalLayoutClasses } from '@layouts/utils/layoutClasses'
|
|||||||
// Vars
|
// Vars
|
||||||
const shortcuts: ShortcutsType[] = [
|
const shortcuts: ShortcutsType[] = [
|
||||||
{
|
{
|
||||||
url: '/apps/calendar',
|
url: '/apps/inventory/products/list',
|
||||||
icon: 'tabler-calendar',
|
icon: 'tabler-box',
|
||||||
title: 'Calendar',
|
title: 'Produk',
|
||||||
subtitle: 'Appointments'
|
subtitle: 'Kelola Produk'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
url: '/apps/invoice/list',
|
url: '/apps/purchase/purchase-orders',
|
||||||
icon: 'tabler-file-dollar',
|
icon: 'tabler-file-dollar',
|
||||||
title: 'Invoice App',
|
title: 'Pembelian',
|
||||||
subtitle: 'Manage Accounts'
|
subtitle: 'Kelola Pembelian'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
url: '/apps/user/list',
|
url: '/apps/user/list',
|
||||||
icon: 'tabler-user',
|
icon: 'tabler-user',
|
||||||
title: 'Users',
|
title: 'Pengguna',
|
||||||
subtitle: 'Manage Users'
|
subtitle: 'Kelola Pengguna'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
url: '/apps/roles',
|
url: '/apps/vendor/list',
|
||||||
icon: 'tabler-users-group',
|
icon: 'tabler-users-group',
|
||||||
title: 'Role Management',
|
title: 'Vendor',
|
||||||
subtitle: 'Permissions'
|
subtitle: 'Kelola Vendor'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
url: '/',
|
url: '/',
|
||||||
@@ -50,10 +50,10 @@ const shortcuts: ShortcutsType[] = [
|
|||||||
subtitle: 'User Dashboard'
|
subtitle: 'User Dashboard'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
url: '/pages/account-settings',
|
url: '/apps/report',
|
||||||
icon: 'tabler-settings',
|
icon: 'tabler-settings',
|
||||||
title: 'Settings',
|
title: 'Laporan',
|
||||||
subtitle: 'Account Settings'
|
subtitle: 'Lihat Laporan'
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -91,30 +91,88 @@ const VerticalMenu = ({ dictionary, scrollMenu }: Props) => {
|
|||||||
<MenuItem href={`/${locale}/dashboards/daily-report`}>{dictionary['navigation'].dailyReport}</MenuItem>
|
<MenuItem href={`/${locale}/dashboards/daily-report`}>{dictionary['navigation'].dailyReport}</MenuItem>
|
||||||
</SubMenu>
|
</SubMenu>
|
||||||
<MenuSection label={dictionary['navigation'].appsPages}>
|
<MenuSection label={dictionary['navigation'].appsPages}>
|
||||||
<SubMenu label={dictionary['navigation'].sales} icon={<i className='tabler-receipt-2' />}>
|
{/* <SubMenu label={dictionary['navigation'].sales} icon={<i className='tabler-receipt-2' />}>
|
||||||
<MenuItem href={`/${locale}/apps/sales/overview`}>{dictionary['navigation'].overview}</MenuItem>
|
<MenuItem href={`/${locale}/apps/sales/overview`}>{dictionary['navigation'].overview}</MenuItem>
|
||||||
<MenuItem href={`/${locale}/apps/sales/sales-bills`}>{dictionary['navigation'].invoices}</MenuItem>
|
<MenuItem href={`/${locale}/apps/sales/sales-bills`}>{dictionary['navigation'].invoices}</MenuItem>
|
||||||
<MenuItem href={`/${locale}/apps/sales/sales-deliveries`}>{dictionary['navigation'].deliveries}</MenuItem>
|
<MenuItem href={`/${locale}/apps/sales/sales-deliveries`}>{dictionary['navigation'].deliveries}</MenuItem>
|
||||||
<MenuItem href={`/${locale}/apps/sales/sales-orders`}>{dictionary['navigation'].sales_orders}</MenuItem>
|
<MenuItem href={`/${locale}/apps/sales/sales-orders`}>{dictionary['navigation'].sales_orders}</MenuItem>
|
||||||
<MenuItem href={`/${locale}/apps/sales/sales-quotes`}>{dictionary['navigation'].quotes}</MenuItem>
|
<MenuItem href={`/${locale}/apps/sales/sales-quotes`}>{dictionary['navigation'].quotes}</MenuItem>
|
||||||
</SubMenu>
|
</SubMenu> */}
|
||||||
<SubMenu label={dictionary['navigation'].purchase_text} icon={<i className='tabler-shopping-cart' />}>
|
<SubMenu label={dictionary['navigation'].purchase_text} icon={<i className='tabler-shopping-cart' />}>
|
||||||
<MenuItem href={`/${locale}/apps/purchase/overview`}>{dictionary['navigation'].overview}</MenuItem>
|
<MenuItem href={`/${locale}/apps/purchase/overview`}>{dictionary['navigation'].overview}</MenuItem>
|
||||||
<MenuItem href={`/${locale}/apps/purchase/purchase-bills`}>
|
{/* <MenuItem href={`/${locale}/apps/purchase/purchase-bills`}>
|
||||||
{dictionary['navigation'].purchase_bills}
|
{dictionary['navigation'].purchase_bills}
|
||||||
</MenuItem>
|
</MenuItem>
|
||||||
<MenuItem href={`/${locale}/apps/purchase/purchase-deliveries`}>
|
<MenuItem href={`/${locale}/apps/purchase/purchase-deliveries`}>
|
||||||
{dictionary['navigation'].purchase_delivery}
|
{dictionary['navigation'].purchase_delivery}
|
||||||
</MenuItem>
|
</MenuItem> */}
|
||||||
<MenuItem href={`/${locale}/apps/purchase/purchase-orders`}>
|
<MenuItem href={`/${locale}/apps/purchase/purchase-orders`}>
|
||||||
{dictionary['navigation'].purchase_orders}
|
{dictionary['navigation'].purchase_orders}
|
||||||
</MenuItem>
|
</MenuItem>
|
||||||
<MenuItem href={`/${locale}/apps/purchase/purchase-quotes`}>
|
{/* <MenuItem href={`/${locale}/apps/purchase/purchase-quotes`}>
|
||||||
{dictionary['navigation'].purchase_quotes}
|
{dictionary['navigation'].purchase_quotes}
|
||||||
|
</MenuItem> */}
|
||||||
|
</SubMenu>
|
||||||
|
<MenuItem
|
||||||
|
href={`/${locale}/apps/expense`}
|
||||||
|
icon={<i className='tabler-cash' />}
|
||||||
|
exactMatch={false}
|
||||||
|
activeUrl='/apps/expense'
|
||||||
|
>
|
||||||
|
{dictionary['navigation'].expenses}
|
||||||
|
</MenuItem>
|
||||||
|
<MenuItem
|
||||||
|
href={`/${locale}/apps/cash-bank`}
|
||||||
|
icon={<i className='tabler-building-bank' />}
|
||||||
|
exactMatch={false}
|
||||||
|
activeUrl='/apps/cash-bank'
|
||||||
|
>
|
||||||
|
{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>
|
</MenuItem>
|
||||||
</SubMenu>
|
</SubMenu>
|
||||||
<SubMenu label={dictionary['navigation'].expenses} icon={<i className='tabler-cash' />}>
|
<MenuItem href={`/${locale}/apps/marketing/campaign`}>{dictionary['navigation'].campaign}</MenuItem>
|
||||||
<MenuItem href={`/${locale}/apps/expense`}>{dictionary['navigation'].list}</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>
|
||||||
</SubMenu>
|
</SubMenu>
|
||||||
<SubMenu label={dictionary['navigation'].inventory} icon={<i className='tabler-salad' />}>
|
<SubMenu label={dictionary['navigation'].inventory} icon={<i className='tabler-salad' />}>
|
||||||
<SubMenu label={dictionary['navigation'].products}>
|
<SubMenu label={dictionary['navigation'].products}>
|
||||||
@@ -159,14 +217,25 @@ const VerticalMenu = ({ dictionary, scrollMenu }: Props) => {
|
|||||||
<MenuItem href={`/${locale}/apps/finance/payment-methods/list`}>{dictionary['navigation'].list}</MenuItem>
|
<MenuItem href={`/${locale}/apps/finance/payment-methods/list`}>{dictionary['navigation'].list}</MenuItem>
|
||||||
</SubMenu>
|
</SubMenu>
|
||||||
</SubMenu>
|
</SubMenu>
|
||||||
<SubMenu label={dictionary['navigation'].user} icon={<i className='tabler-user' />}>
|
<MenuItem
|
||||||
<MenuItem href={`/${locale}/apps/user/list`}>{dictionary['navigation'].list}</MenuItem>
|
href={`/${locale}/apps/user/list`}
|
||||||
{/* <MenuItem href={`/${locale}/apps/user/view`}>{dictionary['navigation'].view}</MenuItem> */}
|
icon={<i className='tabler-user' />}
|
||||||
</SubMenu>
|
exactMatch={false}
|
||||||
<SubMenu label={dictionary['navigation'].vendor} icon={<i className='tabler-building' />}>
|
activeUrl='/apps/user/list'
|
||||||
<MenuItem href={`/${locale}/apps/vendor/list`}>{dictionary['navigation'].list}</MenuItem>
|
>
|
||||||
{/* <MenuItem href={`/${locale}/apps/user/view`}>{dictionary['navigation'].view}</MenuItem> */}
|
{dictionary['navigation'].user}
|
||||||
</SubMenu>
|
</MenuItem>
|
||||||
|
<MenuItem
|
||||||
|
href={`/${locale}/apps/vendor/list`}
|
||||||
|
icon={<i className='tabler-building' />}
|
||||||
|
exactMatch={false}
|
||||||
|
activeUrl='/apps/vendor/list'
|
||||||
|
>
|
||||||
|
{dictionary['navigation'].vendor}
|
||||||
|
</MenuItem>
|
||||||
|
<MenuItem href={`/${locale}/draw`} icon={<i className='tabler-building' />} target='_blank'>
|
||||||
|
Random Draw
|
||||||
|
</MenuItem>
|
||||||
</MenuSection>
|
</MenuSection>
|
||||||
</Menu>
|
</Menu>
|
||||||
</ScrollWrapper>
|
</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
|
||||||
@@ -123,6 +123,20 @@
|
|||||||
"deliveries": "Deliveries",
|
"deliveries": "Deliveries",
|
||||||
"sales_orders": "Orders",
|
"sales_orders": "Orders",
|
||||||
"quotes": "Quotes",
|
"quotes": "Quotes",
|
||||||
"expenses": "Expenses"
|
"expenses": "Expenses",
|
||||||
|
"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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -123,6 +123,20 @@
|
|||||||
"deliveries": "Pengiriman",
|
"deliveries": "Pengiriman",
|
||||||
"sales_orders": "Pemesanan",
|
"sales_orders": "Pemesanan",
|
||||||
"quotes": "Penawaran",
|
"quotes": "Penawaran",
|
||||||
"expenses": "Biaya"
|
"expenses": "Biaya",
|
||||||
|
"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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import orderReducer from '@/redux-store/slices/order'
|
|||||||
import productRecipeReducer from '@/redux-store/slices/productRecipe'
|
import productRecipeReducer from '@/redux-store/slices/productRecipe'
|
||||||
import organizationReducer from '@/redux-store/slices/organization'
|
import organizationReducer from '@/redux-store/slices/organization'
|
||||||
import userReducer from '@/redux-store/slices/user'
|
import userReducer from '@/redux-store/slices/user'
|
||||||
|
import vendorReducer from '@/redux-store/slices/vendor'
|
||||||
|
|
||||||
export const store = configureStore({
|
export const store = configureStore({
|
||||||
reducer: {
|
reducer: {
|
||||||
@@ -19,7 +20,8 @@ export const store = configureStore({
|
|||||||
orderReducer,
|
orderReducer,
|
||||||
productRecipeReducer,
|
productRecipeReducer,
|
||||||
organizationReducer,
|
organizationReducer,
|
||||||
userReducer
|
userReducer,
|
||||||
|
vendorReducer
|
||||||
},
|
},
|
||||||
middleware: getDefaultMiddleware => getDefaultMiddleware({ serializableCheck: false })
|
middleware: getDefaultMiddleware => getDefaultMiddleware({ serializableCheck: false })
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -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({
|
export const api = axios.create({
|
||||||
baseURL: 'https://api-pos.apskel.id/api/v1',
|
baseURL: 'https://api-pos.apskel.id/api/v1',
|
||||||
|
// baseURL: 'http://127.0.0.1:4000/api/v1',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
},
|
},
|
||||||
@@ -30,9 +31,8 @@ api.interceptors.response.use(
|
|||||||
response => response,
|
response => response,
|
||||||
error => {
|
error => {
|
||||||
const status = error.response?.status
|
const status = error.response?.status
|
||||||
const currentPath = window.location.pathname
|
|
||||||
|
|
||||||
if (status === 401 && !currentPath.endsWith('/login')) {
|
if (status === 401) {
|
||||||
localStorage.removeItem('user')
|
localStorage.removeItem('user')
|
||||||
localStorage.removeItem('authToken')
|
localStorage.removeItem('authToken')
|
||||||
window.location.href = '/login'
|
window.location.href = '/login'
|
||||||
|
|||||||
@@ -0,0 +1,251 @@
|
|||||||
|
import type { PaymentReport } from '@/types/services/analytic'
|
||||||
|
|
||||||
|
export class ExcelExportPaymentService {
|
||||||
|
/**
|
||||||
|
* Export Payment Method Report to Excel
|
||||||
|
*/
|
||||||
|
static async exportPaymentMethodToExcel(paymentData: PaymentReport, filename?: string) {
|
||||||
|
try {
|
||||||
|
// Dynamic import untuk xlsx library
|
||||||
|
const XLSX = await import('xlsx')
|
||||||
|
|
||||||
|
// Prepare data untuk Excel
|
||||||
|
const worksheetData: any[][] = []
|
||||||
|
|
||||||
|
// Header dengan report info (baris 1-2)
|
||||||
|
worksheetData.push(['LAPORAN METODE PEMBAYARAN']) // Row 0 - Main title
|
||||||
|
worksheetData.push([`Periode: ${paymentData.date_from.split('T')[0]} - ${paymentData.date_to.split('T')[0]}`]) // Row 1 - Period
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
// Add Summary Section
|
||||||
|
worksheetData.push(['RINGKASAN PERIODE']) // Section header
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
const summaryData = [
|
||||||
|
['Total Amount:', `Rp ${paymentData.summary.total_amount.toLocaleString('id-ID')}`],
|
||||||
|
['Total Orders:', paymentData.summary.total_orders.toString()],
|
||||||
|
['Total Payments:', paymentData.summary.total_payments.toString()],
|
||||||
|
['Average Order Value:', `Rp ${paymentData.summary.average_order_value.toLocaleString('id-ID')}`]
|
||||||
|
]
|
||||||
|
|
||||||
|
summaryData.forEach(row => {
|
||||||
|
worksheetData.push([row[0], row[1]]) // Only 2 columns needed
|
||||||
|
})
|
||||||
|
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
// Payment Method Details Section Header
|
||||||
|
worksheetData.push(['RINCIAN METODE PEMBAYARAN']) // Section header
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
// Header row untuk tabel payment method data
|
||||||
|
const headerRow = ['No', 'Metode Pembayaran', 'Tipe', 'Jumlah Order', 'Total Amount', 'Persentase']
|
||||||
|
worksheetData.push(headerRow)
|
||||||
|
|
||||||
|
// Add payment method data rows
|
||||||
|
paymentData.data.forEach((payment, index) => {
|
||||||
|
const rowData = [
|
||||||
|
index + 1, // No
|
||||||
|
payment.payment_method_name,
|
||||||
|
payment.payment_method_type.toUpperCase(),
|
||||||
|
payment.order_count,
|
||||||
|
payment.total_amount, // Store as number for Excel formatting
|
||||||
|
`${(payment.percentage ?? 0).toFixed(1)}%`
|
||||||
|
]
|
||||||
|
worksheetData.push(rowData)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Add total row
|
||||||
|
const totalRow = ['TOTAL', '', '', paymentData.summary.total_orders, paymentData.summary.total_amount, '100.0%']
|
||||||
|
worksheetData.push(totalRow)
|
||||||
|
|
||||||
|
// Create workbook dan worksheet
|
||||||
|
const workbook = XLSX.utils.book_new()
|
||||||
|
const worksheet = XLSX.utils.aoa_to_sheet(worksheetData)
|
||||||
|
|
||||||
|
// Apply basic formatting
|
||||||
|
this.applyBasicFormatting(worksheet, worksheetData.length, XLSX)
|
||||||
|
|
||||||
|
// Add worksheet ke workbook
|
||||||
|
XLSX.utils.book_append_sheet(workbook, worksheet, 'Metode Pembayaran')
|
||||||
|
|
||||||
|
// Generate filename
|
||||||
|
const exportFilename = filename || this.generateFilename('Metode_Pembayaran')
|
||||||
|
|
||||||
|
// Download file
|
||||||
|
XLSX.writeFile(workbook, exportFilename)
|
||||||
|
|
||||||
|
return { success: true, filename: exportFilename }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting to Excel:', error)
|
||||||
|
return { success: false, error: 'Failed to export Excel file' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Apply basic formatting (SheetJS compatible)
|
||||||
|
*/
|
||||||
|
private static applyBasicFormatting(worksheet: any, totalRows: number, XLSX: any) {
|
||||||
|
// Set column widths
|
||||||
|
const colWidths = [
|
||||||
|
{ wch: 8 }, // No
|
||||||
|
{ wch: 25 }, // Metode Pembayaran
|
||||||
|
{ wch: 12 }, // Tipe
|
||||||
|
{ wch: 15 }, // Jumlah Order
|
||||||
|
{ wch: 20 }, // Total Amount
|
||||||
|
{ wch: 12 } // Persentase
|
||||||
|
]
|
||||||
|
worksheet['!cols'] = colWidths
|
||||||
|
|
||||||
|
// Set row heights for better spacing
|
||||||
|
worksheet['!rows'] = [
|
||||||
|
{ hpt: 30 }, // Title row
|
||||||
|
{ hpt: 25 }, // Period row
|
||||||
|
{ hpt: 15 }, // Empty row
|
||||||
|
{ hpt: 25 }, // Summary header
|
||||||
|
{ hpt: 15 } // Empty row
|
||||||
|
]
|
||||||
|
|
||||||
|
// Merge cells untuk headers
|
||||||
|
const merges = [
|
||||||
|
{ s: { r: 0, c: 0 }, e: { r: 0, c: 5 } }, // Title (span across all columns)
|
||||||
|
{ s: { r: 1, c: 0 }, e: { r: 1, c: 5 } }, // Period (span across all columns)
|
||||||
|
{ s: { r: 3, c: 0 }, e: { r: 3, c: 5 } } // Summary header (span across all columns)
|
||||||
|
]
|
||||||
|
|
||||||
|
// Find and add merge for payment method details header
|
||||||
|
for (let i = 0; i < totalRows; i++) {
|
||||||
|
const cell = worksheet[XLSX.utils.encode_cell({ r: i, c: 0 })]
|
||||||
|
if (cell && cell.v === 'RINCIAN METODE PEMBAYARAN') {
|
||||||
|
merges.push({ s: { r: i, c: 0 }, e: { r: i, c: 5 } }) // Span across all columns
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
worksheet['!merges'] = merges
|
||||||
|
|
||||||
|
// Apply number formatting untuk currency cells
|
||||||
|
this.applyNumberFormatting(worksheet, totalRows, XLSX)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Apply number formatting for currency and styling
|
||||||
|
*/
|
||||||
|
private static applyNumberFormatting(worksheet: any, totalRows: number, XLSX: any) {
|
||||||
|
// Find table data start (after header row)
|
||||||
|
let dataStartRow = -1
|
||||||
|
for (let i = 0; i < totalRows; i++) {
|
||||||
|
const cell = worksheet[XLSX.utils.encode_cell({ r: i, c: 0 })]
|
||||||
|
if (cell && cell.v === 'No') {
|
||||||
|
dataStartRow = i + 1
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dataStartRow === -1) return
|
||||||
|
|
||||||
|
// Count actual data rows (excluding total row)
|
||||||
|
const dataRowsCount = totalRows - dataStartRow - 1 // -1 for total row
|
||||||
|
|
||||||
|
// Apply currency formatting to Total Amount column (column 4 - index 4)
|
||||||
|
for (let row = dataStartRow; row <= dataStartRow + dataRowsCount; row++) {
|
||||||
|
// Include total row
|
||||||
|
const cellAddress = XLSX.utils.encode_cell({ r: row, c: 4 }) // Total Amount column
|
||||||
|
const cell = worksheet[cellAddress]
|
||||||
|
|
||||||
|
if (cell && typeof cell.v === 'number') {
|
||||||
|
// Apply Indonesian currency format
|
||||||
|
cell.z = '#,##0'
|
||||||
|
cell.t = 'n'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply styling to header row
|
||||||
|
const headerRowIndex = dataStartRow - 1
|
||||||
|
for (let col = 0; col < 6; col++) {
|
||||||
|
const cellAddress = XLSX.utils.encode_cell({ r: headerRowIndex, c: col })
|
||||||
|
const cell = worksheet[cellAddress]
|
||||||
|
|
||||||
|
if (cell) {
|
||||||
|
// Apply bold formatting (basic approach for SheetJS)
|
||||||
|
cell.s = {
|
||||||
|
font: { bold: true },
|
||||||
|
fill: { fgColor: { rgb: 'F3F4F6' } }, // Light gray background
|
||||||
|
border: {
|
||||||
|
bottom: { style: 'medium', color: { rgb: '000000' } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply styling to total row
|
||||||
|
const totalRowIndex = dataStartRow + dataRowsCount
|
||||||
|
for (let col = 0; col < 6; col++) {
|
||||||
|
const cellAddress = XLSX.utils.encode_cell({ r: totalRowIndex, c: col })
|
||||||
|
const cell = worksheet[cellAddress]
|
||||||
|
|
||||||
|
if (cell) {
|
||||||
|
// Apply bold formatting for total row
|
||||||
|
cell.s = {
|
||||||
|
font: { bold: true },
|
||||||
|
border: {
|
||||||
|
top: { style: 'medium', color: { rgb: '000000' } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate filename with timestamp
|
||||||
|
*/
|
||||||
|
private static generateFilename(prefix: string): string {
|
||||||
|
const now = new Date()
|
||||||
|
const year = now.getFullYear()
|
||||||
|
const month = (now.getMonth() + 1).toString().padStart(2, '0')
|
||||||
|
const day = now.getDate().toString().padStart(2, '0')
|
||||||
|
const hour = now.getHours().toString().padStart(2, '0')
|
||||||
|
const minute = now.getMinutes().toString().padStart(2, '0')
|
||||||
|
|
||||||
|
return `${prefix}_${year}_${month}_${day}_${hour}${minute}.xlsx`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Export Payment Method data with custom configuration
|
||||||
|
*/
|
||||||
|
static async exportCustomPaymentData(
|
||||||
|
data: any[][],
|
||||||
|
sheetName: string = 'Payment Method',
|
||||||
|
filename?: string,
|
||||||
|
options?: {
|
||||||
|
colWidths?: { wch: number }[]
|
||||||
|
merges?: { s: { r: number; c: number }; e: { r: number; c: number } }[]
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const XLSX = await import('xlsx')
|
||||||
|
|
||||||
|
const workbook = XLSX.utils.book_new()
|
||||||
|
const worksheet = XLSX.utils.aoa_to_sheet(data)
|
||||||
|
|
||||||
|
// Apply options
|
||||||
|
if (options?.colWidths) {
|
||||||
|
worksheet['!cols'] = options.colWidths
|
||||||
|
}
|
||||||
|
if (options?.merges) {
|
||||||
|
worksheet['!merges'] = options.merges
|
||||||
|
}
|
||||||
|
|
||||||
|
XLSX.utils.book_append_sheet(workbook, worksheet, sheetName)
|
||||||
|
|
||||||
|
const exportFilename = filename || this.generateFilename('Payment_Method_Export')
|
||||||
|
XLSX.writeFile(workbook, exportFilename)
|
||||||
|
|
||||||
|
return { success: true, filename: exportFilename }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting to Excel:', error)
|
||||||
|
return { success: false, error: 'Failed to export Excel file' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,278 @@
|
|||||||
|
// services/excelExportService.ts
|
||||||
|
import type { ProfitLossReport } from '@/types/services/analytic'
|
||||||
|
|
||||||
|
export class ExcelExportProfitLossService {
|
||||||
|
/**
|
||||||
|
* Export Profit Loss Report to Excel
|
||||||
|
*/
|
||||||
|
static async exportProfitLossToExcel(profitData: ProfitLossReport, filename?: string) {
|
||||||
|
try {
|
||||||
|
// Dynamic import untuk xlsx library
|
||||||
|
const XLSX = await import('xlsx')
|
||||||
|
|
||||||
|
// Prepare data untuk Excel
|
||||||
|
const worksheetData: any[][] = []
|
||||||
|
|
||||||
|
// Header dengan company info (baris 1-2) - update data
|
||||||
|
worksheetData.push(['LABA RUGI']) // Row 0 - Main title
|
||||||
|
worksheetData.push([`Periode: ${profitData.date_from.split('T')[0]} - ${profitData.date_to.split('T')[0]}`]) // Row 1 - Period
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
// Add Summary Section
|
||||||
|
worksheetData.push(['RINGKASAN PERIODE']) // Section header
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
const summaryData = [
|
||||||
|
['Total Revenue:', `Rp ${profitData.summary.total_revenue.toLocaleString('id-ID')}`],
|
||||||
|
['Total Cost:', `Rp ${profitData.summary.total_cost.toLocaleString('id-ID')}`],
|
||||||
|
['Gross Profit:', `Rp ${profitData.summary.gross_profit.toLocaleString('id-ID')}`],
|
||||||
|
['Gross Profit Margin:', `${profitData.summary.gross_profit_margin.toFixed(1)}%`],
|
||||||
|
['Total Tax:', `Rp ${profitData.summary.total_tax.toLocaleString('id-ID')}`],
|
||||||
|
['Total Discount:', `Rp ${profitData.summary.total_discount.toLocaleString('id-ID')}`],
|
||||||
|
['Net Profit:', `Rp ${profitData.summary.net_profit.toLocaleString('id-ID')}`],
|
||||||
|
['Net Profit Margin:', `${profitData.summary.net_profit_margin.toFixed(1)}%`],
|
||||||
|
['Total Orders:', profitData.summary.total_orders.toString()],
|
||||||
|
['Average Profit:', `Rp ${profitData.summary.average_profit.toLocaleString('id-ID')}`],
|
||||||
|
['Profitability Ratio:', `${profitData.summary.profitability_ratio.toFixed(1)}%`]
|
||||||
|
]
|
||||||
|
|
||||||
|
summaryData.forEach(row => {
|
||||||
|
worksheetData.push([row[0], row[1]]) // Only 2 columns needed
|
||||||
|
})
|
||||||
|
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
// Daily Data Section Header
|
||||||
|
worksheetData.push(['RINCIAN HARIAN']) // Section header
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
// Prepare date columns - ambil dari daily data
|
||||||
|
const dateColumns = profitData.data.map(daily => {
|
||||||
|
const date = new Date(daily.date)
|
||||||
|
return date.toLocaleDateString('id-ID', {
|
||||||
|
day: '2-digit',
|
||||||
|
month: 'short'
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// Header row untuk tabel daily data (hanya tanggal)
|
||||||
|
const headerRow = ['NO', 'KET', '', ...dateColumns]
|
||||||
|
worksheetData.push(headerRow)
|
||||||
|
|
||||||
|
// Prepare data rows
|
||||||
|
const rows = this.prepareProfitLossRows(profitData)
|
||||||
|
|
||||||
|
// Add data rows ke worksheet (hanya nilai per tanggal)
|
||||||
|
rows.forEach(row => {
|
||||||
|
const rowData = [
|
||||||
|
row.no,
|
||||||
|
row.label,
|
||||||
|
':',
|
||||||
|
...row.values.map(val => val.today) // Store as numbers for better Excel handling
|
||||||
|
]
|
||||||
|
worksheetData.push(rowData)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Create workbook dan worksheet
|
||||||
|
const workbook = XLSX.utils.book_new()
|
||||||
|
const worksheet = XLSX.utils.aoa_to_sheet(worksheetData)
|
||||||
|
|
||||||
|
// Apply basic formatting
|
||||||
|
this.applyBasicFormatting(worksheet, dateColumns.length, worksheetData.length, XLSX)
|
||||||
|
|
||||||
|
// Add worksheet ke workbook
|
||||||
|
XLSX.utils.book_append_sheet(workbook, worksheet, 'Laba Rugi')
|
||||||
|
|
||||||
|
// Generate filename
|
||||||
|
const exportFilename = filename || this.generateFilename('Laba_Rugi')
|
||||||
|
|
||||||
|
// Download file
|
||||||
|
XLSX.writeFile(workbook, exportFilename)
|
||||||
|
|
||||||
|
return { success: true, filename: exportFilename }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting to Excel:', error)
|
||||||
|
return { success: false, error: 'Failed to export Excel file' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prepare profit loss data rows (tanpa percentage)
|
||||||
|
*/
|
||||||
|
private static prepareProfitLossRows(profitData: ProfitLossReport) {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
no: 1,
|
||||||
|
label: 'TOTAL PENJ',
|
||||||
|
values: profitData.data.map(daily => ({
|
||||||
|
today: daily.revenue,
|
||||||
|
mtd: daily.revenue // TODO: Replace with actual MTD data from API
|
||||||
|
}))
|
||||||
|
},
|
||||||
|
{
|
||||||
|
no: 2,
|
||||||
|
label: 'HPP',
|
||||||
|
values: profitData.data.map(daily => ({
|
||||||
|
today: daily.cost,
|
||||||
|
mtd: daily.cost
|
||||||
|
}))
|
||||||
|
},
|
||||||
|
{
|
||||||
|
no: 3,
|
||||||
|
label: 'Laba Kotor (1-2)',
|
||||||
|
values: profitData.data.map(daily => ({
|
||||||
|
today: daily.gross_profit,
|
||||||
|
mtd: daily.gross_profit
|
||||||
|
}))
|
||||||
|
},
|
||||||
|
{
|
||||||
|
no: 4,
|
||||||
|
label: 'Biaya lain',
|
||||||
|
values: profitData.data.map(daily => {
|
||||||
|
const totalCosts = daily.tax + daily.discount
|
||||||
|
return {
|
||||||
|
today: totalCosts,
|
||||||
|
mtd: totalCosts
|
||||||
|
}
|
||||||
|
})
|
||||||
|
},
|
||||||
|
{
|
||||||
|
no: 5,
|
||||||
|
label: 'Laba/Rugi (3-4)',
|
||||||
|
values: profitData.data.map(daily => ({
|
||||||
|
today: daily.net_profit,
|
||||||
|
mtd: daily.net_profit
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Apply basic formatting (SheetJS compatible)
|
||||||
|
*/
|
||||||
|
private static applyBasicFormatting(worksheet: any, dateColumnsCount: number, totalRows: number, XLSX: any) {
|
||||||
|
// Set column widths
|
||||||
|
const colWidths = [
|
||||||
|
{ wch: 5 }, // NO
|
||||||
|
{ wch: 25 }, // KET
|
||||||
|
{ wch: 3 }, // :
|
||||||
|
...Array(dateColumnsCount).fill({ wch: 18 })
|
||||||
|
]
|
||||||
|
worksheet['!cols'] = colWidths
|
||||||
|
|
||||||
|
// Set row heights for better spacing
|
||||||
|
worksheet['!rows'] = [
|
||||||
|
{ hpt: 30 }, // Title row
|
||||||
|
{ hpt: 25 }, // Period row
|
||||||
|
{ hpt: 15 }, // Empty row
|
||||||
|
{ hpt: 25 }, // Summary header
|
||||||
|
{ hpt: 15 } // Empty row
|
||||||
|
]
|
||||||
|
|
||||||
|
// Merge cells untuk headers
|
||||||
|
const merges = [
|
||||||
|
{ s: { r: 0, c: 0 }, e: { r: 0, c: dateColumnsCount + 2 } }, // Title
|
||||||
|
{ s: { r: 1, c: 0 }, e: { r: 1, c: dateColumnsCount + 2 } }, // Period
|
||||||
|
{ s: { r: 3, c: 0 }, e: { r: 3, c: dateColumnsCount + 2 } } // Summary header
|
||||||
|
]
|
||||||
|
|
||||||
|
// Find and add merge for daily data header
|
||||||
|
for (let i = 0; i < totalRows; i++) {
|
||||||
|
const cell = worksheet[XLSX.utils.encode_cell({ r: i, c: 0 })]
|
||||||
|
if (cell && cell.v === 'RINCIAN HARIAN') {
|
||||||
|
merges.push({ s: { r: i, c: 0 }, e: { r: i, c: dateColumnsCount + 2 } })
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
worksheet['!merges'] = merges
|
||||||
|
|
||||||
|
// Apply number formatting untuk currency cells
|
||||||
|
this.applyNumberFormatting(worksheet, totalRows, dateColumnsCount + 3, XLSX)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Apply number formatting for currency
|
||||||
|
*/
|
||||||
|
private static applyNumberFormatting(worksheet: any, totalRows: number, totalCols: number, XLSX: any) {
|
||||||
|
// Find table data start (after "NO" header)
|
||||||
|
let dataStartRow = -1
|
||||||
|
for (let i = 0; i < totalRows; i++) {
|
||||||
|
const cell = worksheet[XLSX.utils.encode_cell({ r: i, c: 0 })]
|
||||||
|
if (cell && cell.v === 'NO') {
|
||||||
|
dataStartRow = i + 1
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dataStartRow === -1) return
|
||||||
|
|
||||||
|
// Apply currency formatting to data cells (starting from column 3 - after NO, KET, :)
|
||||||
|
for (let row = dataStartRow; row < dataStartRow + 5; row++) {
|
||||||
|
// 5 data rows
|
||||||
|
for (let col = 3; col < totalCols; col++) {
|
||||||
|
const cellAddress = XLSX.utils.encode_cell({ r: row, c: col })
|
||||||
|
const cell = worksheet[cellAddress]
|
||||||
|
|
||||||
|
if (cell && typeof cell.v === 'number') {
|
||||||
|
// Apply Indonesian currency format
|
||||||
|
cell.z = '#,##0'
|
||||||
|
cell.t = 'n'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate filename with timestamp
|
||||||
|
*/
|
||||||
|
private static generateFilename(prefix: string): string {
|
||||||
|
const now = new Date()
|
||||||
|
const year = now.getFullYear()
|
||||||
|
const month = (now.getMonth() + 1).toString().padStart(2, '0')
|
||||||
|
const day = now.getDate().toString().padStart(2, '0')
|
||||||
|
const hour = now.getHours().toString().padStart(2, '0')
|
||||||
|
const minute = now.getMinutes().toString().padStart(2, '0')
|
||||||
|
|
||||||
|
return `${prefix}_${year}_${month}_${day}_${hour}${minute}.xlsx`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Export any data to Excel with custom configuration
|
||||||
|
*/
|
||||||
|
static async exportToExcel(
|
||||||
|
data: any[][],
|
||||||
|
sheetName: string = 'Sheet1',
|
||||||
|
filename?: string,
|
||||||
|
options?: {
|
||||||
|
colWidths?: { wch: number }[]
|
||||||
|
merges?: { s: { r: number; c: number }; e: { r: number; c: number } }[]
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const XLSX = await import('xlsx')
|
||||||
|
|
||||||
|
const workbook = XLSX.utils.book_new()
|
||||||
|
const worksheet = XLSX.utils.aoa_to_sheet(data)
|
||||||
|
|
||||||
|
// Apply options
|
||||||
|
if (options?.colWidths) {
|
||||||
|
worksheet['!cols'] = options.colWidths
|
||||||
|
}
|
||||||
|
if (options?.merges) {
|
||||||
|
worksheet['!merges'] = options.merges
|
||||||
|
}
|
||||||
|
|
||||||
|
XLSX.utils.book_append_sheet(workbook, worksheet, sheetName)
|
||||||
|
|
||||||
|
const exportFilename = filename || this.generateFilename('Export')
|
||||||
|
XLSX.writeFile(workbook, exportFilename)
|
||||||
|
|
||||||
|
return { success: true, filename: exportFilename }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting to Excel:', error)
|
||||||
|
return { success: false, error: 'Failed to export Excel file' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,335 @@
|
|||||||
|
// services/excelExportSalesOrderService.ts
|
||||||
|
import type { SalesReport } from '@/types/services/analytic'
|
||||||
|
|
||||||
|
export class ExcelExportSalesOrderService {
|
||||||
|
/**
|
||||||
|
* Export Sales Order Report to Excel
|
||||||
|
*/
|
||||||
|
static async exportSalesOrderToExcel(salesData: SalesReport, filename?: string) {
|
||||||
|
try {
|
||||||
|
// Dynamic import untuk xlsx library
|
||||||
|
const XLSX = await import('xlsx')
|
||||||
|
|
||||||
|
// Prepare data untuk Excel
|
||||||
|
const worksheetData: any[][] = []
|
||||||
|
|
||||||
|
// Header dengan report info (baris 1-2)
|
||||||
|
worksheetData.push(['LAPORAN PESANAN PENJUALAN']) // Row 0 - Main title
|
||||||
|
worksheetData.push([`Periode: ${salesData.date_from.split('T')[0]} - ${salesData.date_to.split('T')[0]}`]) // Row 1 - Period
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
// Add Summary Section
|
||||||
|
worksheetData.push(['RINGKASAN PERIODE']) // Section header
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
const summaryData = [
|
||||||
|
['Total Sales:', `Rp ${salesData.summary.total_sales.toLocaleString('id-ID')}`],
|
||||||
|
['Total Orders:', salesData.summary.total_orders.toString()],
|
||||||
|
['Total Items:', salesData.summary.total_items.toString()],
|
||||||
|
['Average Order Value:', `Rp ${salesData.summary.average_order_value.toLocaleString('id-ID')}`],
|
||||||
|
['Total Tax:', `Rp ${salesData.summary.total_tax.toLocaleString('id-ID')}`],
|
||||||
|
['Total Discount:', `Rp ${salesData.summary.total_discount.toLocaleString('id-ID')}`],
|
||||||
|
['Net Sales:', `Rp ${salesData.summary.net_sales.toLocaleString('id-ID')}`]
|
||||||
|
]
|
||||||
|
|
||||||
|
summaryData.forEach(row => {
|
||||||
|
worksheetData.push([row[0], row[1]]) // Only 2 columns needed
|
||||||
|
})
|
||||||
|
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
// Daily Sales Section Header
|
||||||
|
worksheetData.push(['RINCIAN HARIAN']) // Section header
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
// Header row untuk tabel daily sales data
|
||||||
|
const headerRow = ['No', 'Tanggal', 'Penjualan', 'Pesanan', 'Qty', 'Pajak', 'Diskon', 'Pendapatan']
|
||||||
|
worksheetData.push(headerRow)
|
||||||
|
|
||||||
|
// Add daily sales data rows
|
||||||
|
salesData.data?.forEach((dailySales, index) => {
|
||||||
|
const rowData = [
|
||||||
|
index + 1, // No
|
||||||
|
this.formatDate(dailySales.date),
|
||||||
|
dailySales.sales, // Store as number for Excel formatting
|
||||||
|
dailySales.orders,
|
||||||
|
dailySales.items,
|
||||||
|
dailySales.tax, // Store as number for Excel formatting
|
||||||
|
dailySales.discount, // Store as number for Excel formatting
|
||||||
|
dailySales.net_sales // Store as number for Excel formatting
|
||||||
|
]
|
||||||
|
worksheetData.push(rowData)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Add total row
|
||||||
|
const totalRow = [
|
||||||
|
'TOTAL',
|
||||||
|
'',
|
||||||
|
salesData.summary.total_sales,
|
||||||
|
salesData.summary.total_orders,
|
||||||
|
salesData.summary.total_items,
|
||||||
|
salesData.summary.total_tax,
|
||||||
|
salesData.summary.total_discount,
|
||||||
|
salesData.summary.net_sales
|
||||||
|
]
|
||||||
|
worksheetData.push(totalRow)
|
||||||
|
|
||||||
|
// Create workbook dan worksheet
|
||||||
|
const workbook = XLSX.utils.book_new()
|
||||||
|
const worksheet = XLSX.utils.aoa_to_sheet(worksheetData)
|
||||||
|
|
||||||
|
// Apply basic formatting
|
||||||
|
this.applyBasicFormatting(worksheet, worksheetData.length, XLSX)
|
||||||
|
|
||||||
|
// Add worksheet ke workbook
|
||||||
|
XLSX.utils.book_append_sheet(workbook, worksheet, 'Pesanan Penjualan')
|
||||||
|
|
||||||
|
// Generate filename
|
||||||
|
const exportFilename = filename || this.generateFilename('Pesanan_Penjualan')
|
||||||
|
|
||||||
|
// Download file
|
||||||
|
XLSX.writeFile(workbook, exportFilename)
|
||||||
|
|
||||||
|
return { success: true, filename: exportFilename }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting to Excel:', error)
|
||||||
|
return { success: false, error: 'Failed to export Excel file' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Apply basic formatting (SheetJS compatible)
|
||||||
|
*/
|
||||||
|
private static applyBasicFormatting(worksheet: any, totalRows: number, XLSX: any) {
|
||||||
|
// Set column widths
|
||||||
|
const colWidths = [
|
||||||
|
{ wch: 8 }, // No
|
||||||
|
{ wch: 15 }, // Tanggal
|
||||||
|
{ wch: 18 }, // Penjualan
|
||||||
|
{ wch: 12 }, // Pesanan
|
||||||
|
{ wch: 10 }, // Qty
|
||||||
|
{ wch: 15 }, // Pajak
|
||||||
|
{ wch: 15 }, // Diskon
|
||||||
|
{ wch: 18 } // Pendapatan
|
||||||
|
]
|
||||||
|
worksheet['!cols'] = colWidths
|
||||||
|
|
||||||
|
// Set row heights for better spacing
|
||||||
|
worksheet['!rows'] = [
|
||||||
|
{ hpt: 30 }, // Title row
|
||||||
|
{ hpt: 25 }, // Period row
|
||||||
|
{ hpt: 15 }, // Empty row
|
||||||
|
{ hpt: 25 }, // Summary header
|
||||||
|
{ hpt: 15 } // Empty row
|
||||||
|
]
|
||||||
|
|
||||||
|
// Merge cells untuk headers
|
||||||
|
const merges = [
|
||||||
|
{ s: { r: 0, c: 0 }, e: { r: 0, c: 7 } }, // Title (span across all columns)
|
||||||
|
{ s: { r: 1, c: 0 }, e: { r: 1, c: 7 } }, // Period (span across all columns)
|
||||||
|
{ s: { r: 3, c: 0 }, e: { r: 3, c: 7 } } // Summary header (span across all columns)
|
||||||
|
]
|
||||||
|
|
||||||
|
// Find and add merge for daily sales header
|
||||||
|
for (let i = 0; i < totalRows; i++) {
|
||||||
|
const cell = worksheet[XLSX.utils.encode_cell({ r: i, c: 0 })]
|
||||||
|
if (cell && cell.v === 'RINCIAN HARIAN') {
|
||||||
|
merges.push({ s: { r: i, c: 0 }, e: { r: i, c: 7 } }) // Span across all columns
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
worksheet['!merges'] = merges
|
||||||
|
|
||||||
|
// Apply number formatting untuk currency cells
|
||||||
|
this.applyNumberFormatting(worksheet, totalRows, XLSX)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Apply number formatting for currency and styling
|
||||||
|
*/
|
||||||
|
private static applyNumberFormatting(worksheet: any, totalRows: number, XLSX: any) {
|
||||||
|
// Find table data start (after header row)
|
||||||
|
let dataStartRow = -1
|
||||||
|
for (let i = 0; i < totalRows; i++) {
|
||||||
|
const cell = worksheet[XLSX.utils.encode_cell({ r: i, c: 0 })]
|
||||||
|
if (cell && cell.v === 'No') {
|
||||||
|
dataStartRow = i + 1
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dataStartRow === -1) return
|
||||||
|
|
||||||
|
// Count actual data rows (excluding total row)
|
||||||
|
const dataRowsCount = totalRows - dataStartRow - 1 // -1 for total row
|
||||||
|
|
||||||
|
// Apply currency formatting to currency columns (columns 2, 5, 6, 7 - Penjualan, Pajak, Diskon, Pendapatan)
|
||||||
|
const currencyColumns = [2, 5, 6, 7]
|
||||||
|
for (let row = dataStartRow; row <= dataStartRow + dataRowsCount; row++) {
|
||||||
|
// Include total row
|
||||||
|
currencyColumns.forEach(col => {
|
||||||
|
const cellAddress = XLSX.utils.encode_cell({ r: row, c: col })
|
||||||
|
const cell = worksheet[cellAddress]
|
||||||
|
|
||||||
|
if (cell && typeof cell.v === 'number') {
|
||||||
|
// Apply Indonesian currency format
|
||||||
|
cell.z = '#,##0'
|
||||||
|
cell.t = 'n'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply styling to header row
|
||||||
|
const headerRowIndex = dataStartRow - 1
|
||||||
|
for (let col = 0; col < 8; col++) {
|
||||||
|
const cellAddress = XLSX.utils.encode_cell({ r: headerRowIndex, c: col })
|
||||||
|
const cell = worksheet[cellAddress]
|
||||||
|
|
||||||
|
if (cell) {
|
||||||
|
// Apply bold formatting (basic approach for SheetJS)
|
||||||
|
cell.s = {
|
||||||
|
font: { bold: true },
|
||||||
|
fill: { fgColor: { rgb: 'F3F4F6' } }, // Light gray background
|
||||||
|
border: {
|
||||||
|
bottom: { style: 'medium', color: { rgb: '000000' } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply styling to total row
|
||||||
|
const totalRowIndex = dataStartRow + dataRowsCount
|
||||||
|
for (let col = 0; col < 8; col++) {
|
||||||
|
const cellAddress = XLSX.utils.encode_cell({ r: totalRowIndex, c: col })
|
||||||
|
const cell = worksheet[cellAddress]
|
||||||
|
|
||||||
|
if (cell) {
|
||||||
|
// Apply bold formatting for total row
|
||||||
|
cell.s = {
|
||||||
|
font: { bold: true },
|
||||||
|
border: {
|
||||||
|
top: { style: 'medium', color: { rgb: '000000' } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format date for display
|
||||||
|
*/
|
||||||
|
private static formatDate(dateString: string): string {
|
||||||
|
const date = new Date(dateString)
|
||||||
|
return date.toLocaleDateString('id-ID', {
|
||||||
|
day: '2-digit',
|
||||||
|
month: '2-digit',
|
||||||
|
year: 'numeric'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate filename with timestamp
|
||||||
|
*/
|
||||||
|
private static generateFilename(prefix: string): string {
|
||||||
|
const now = new Date()
|
||||||
|
const year = now.getFullYear()
|
||||||
|
const month = (now.getMonth() + 1).toString().padStart(2, '0')
|
||||||
|
const day = now.getDate().toString().padStart(2, '0')
|
||||||
|
const hour = now.getHours().toString().padStart(2, '0')
|
||||||
|
const minute = now.getMinutes().toString().padStart(2, '0')
|
||||||
|
|
||||||
|
return `${prefix}_${year}_${month}_${day}_${hour}${minute}.xlsx`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Export Sales Order data with custom configuration
|
||||||
|
*/
|
||||||
|
static async exportCustomSalesOrderData(
|
||||||
|
salesData: SalesReport,
|
||||||
|
options?: {
|
||||||
|
includeSummary?: boolean
|
||||||
|
includeItemsColumn?: boolean
|
||||||
|
customFilename?: string
|
||||||
|
sheetName?: string
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const XLSX = await import('xlsx')
|
||||||
|
const worksheetData: any[][] = []
|
||||||
|
|
||||||
|
// Always include title and period
|
||||||
|
worksheetData.push(['LAPORAN PESANAN PENJUALAN'])
|
||||||
|
worksheetData.push([`Periode: ${salesData.date_from.split('T')[0]} - ${salesData.date_to.split('T')[0]}`])
|
||||||
|
worksheetData.push([])
|
||||||
|
|
||||||
|
// Optional summary
|
||||||
|
if (options?.includeSummary !== false) {
|
||||||
|
worksheetData.push(['RINGKASAN PERIODE'])
|
||||||
|
worksheetData.push([])
|
||||||
|
const summaryData = [
|
||||||
|
['Total Sales:', `Rp ${salesData.summary.total_sales.toLocaleString('id-ID')}`],
|
||||||
|
['Total Orders:', salesData.summary.total_orders.toString()],
|
||||||
|
['Total Items:', salesData.summary.total_items.toString()],
|
||||||
|
['Net Sales:', `Rp ${salesData.summary.net_sales.toLocaleString('id-ID')}`]
|
||||||
|
]
|
||||||
|
summaryData.forEach(row => worksheetData.push([row[0], row[1]]))
|
||||||
|
worksheetData.push([])
|
||||||
|
worksheetData.push([])
|
||||||
|
}
|
||||||
|
|
||||||
|
worksheetData.push(['RINCIAN HARIAN'])
|
||||||
|
worksheetData.push([])
|
||||||
|
|
||||||
|
// Header row based on options
|
||||||
|
const headerRow =
|
||||||
|
options?.includeItemsColumn !== false
|
||||||
|
? ['No', 'Tanggal', 'Penjualan', 'Pesanan', 'Qty', 'Pajak', 'Diskon', 'Pendapatan']
|
||||||
|
: ['No', 'Tanggal', 'Penjualan', 'Pesanan', 'Pajak', 'Diskon', 'Pendapatan']
|
||||||
|
worksheetData.push(headerRow)
|
||||||
|
|
||||||
|
// Add daily data based on options
|
||||||
|
salesData.data?.forEach((dailySales, index) => {
|
||||||
|
const rowData =
|
||||||
|
options?.includeItemsColumn !== false
|
||||||
|
? [
|
||||||
|
index + 1,
|
||||||
|
this.formatDate(dailySales.date),
|
||||||
|
dailySales.sales,
|
||||||
|
dailySales.orders,
|
||||||
|
dailySales.items,
|
||||||
|
dailySales.tax,
|
||||||
|
dailySales.discount,
|
||||||
|
dailySales.net_sales
|
||||||
|
]
|
||||||
|
: [
|
||||||
|
index + 1,
|
||||||
|
this.formatDate(dailySales.date),
|
||||||
|
dailySales.sales,
|
||||||
|
dailySales.orders,
|
||||||
|
dailySales.tax,
|
||||||
|
dailySales.discount,
|
||||||
|
dailySales.net_sales
|
||||||
|
]
|
||||||
|
worksheetData.push(rowData)
|
||||||
|
})
|
||||||
|
|
||||||
|
const workbook = XLSX.utils.book_new()
|
||||||
|
const worksheet = XLSX.utils.aoa_to_sheet(worksheetData)
|
||||||
|
|
||||||
|
this.applyBasicFormatting(worksheet, worksheetData.length, XLSX)
|
||||||
|
|
||||||
|
const sheetName = options?.sheetName || 'Pesanan Penjualan'
|
||||||
|
XLSX.utils.book_append_sheet(workbook, worksheet, sheetName)
|
||||||
|
|
||||||
|
const exportFilename = options?.customFilename || this.generateFilename('Custom_Sales_Order')
|
||||||
|
XLSX.writeFile(workbook, exportFilename)
|
||||||
|
|
||||||
|
return { success: true, filename: exportFilename }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting custom sales order data to Excel:', error)
|
||||||
|
return { success: false, error: 'Failed to export Excel file' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,325 @@
|
|||||||
|
// services/excelExportCategoryService.ts
|
||||||
|
import type { CategoryReport } from '@/types/services/analytic'
|
||||||
|
|
||||||
|
export class ExcelExportSalesProductCategoryService {
|
||||||
|
/**
|
||||||
|
* Export Category Sales Report to Excel
|
||||||
|
*/
|
||||||
|
static async exportCategorySalesToExcel(categoryData: CategoryReport, filename?: string) {
|
||||||
|
try {
|
||||||
|
// Dynamic import untuk xlsx library
|
||||||
|
const XLSX = await import('xlsx')
|
||||||
|
|
||||||
|
// Prepare data untuk Excel
|
||||||
|
const worksheetData: any[][] = []
|
||||||
|
|
||||||
|
// Header dengan report info (baris 1-2)
|
||||||
|
worksheetData.push(['LAPORAN PENJUALAN KATEGORI']) // Row 0 - Main title
|
||||||
|
worksheetData.push([`Periode: ${categoryData.date_from.split('T')[0]} - ${categoryData.date_to.split('T')[0]}`]) // Row 1 - Period
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
// Calculate summary
|
||||||
|
const categorySummary = {
|
||||||
|
totalRevenue: categoryData.data?.reduce((sum, item) => sum + (item?.total_revenue || 0), 0) || 0,
|
||||||
|
orderCount: categoryData.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0,
|
||||||
|
productCount: categoryData.data?.reduce((sum, item) => sum + (item?.product_count || 0), 0) || 0,
|
||||||
|
totalQuantity: categoryData.data?.reduce((sum, item) => sum + (item?.total_quantity || 0), 0) || 0,
|
||||||
|
totalCategories: categoryData.data?.length || 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add Summary Section
|
||||||
|
worksheetData.push(['RINGKASAN PERIODE']) // Section header
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
const summaryData = [
|
||||||
|
['Total Kategori:', categorySummary.totalCategories.toString()],
|
||||||
|
['Total Produk:', categorySummary.productCount.toString()],
|
||||||
|
['Total Quantity:', categorySummary.totalQuantity.toString()],
|
||||||
|
['Total Orders:', categorySummary.orderCount.toString()],
|
||||||
|
['Total Revenue:', `Rp ${categorySummary.totalRevenue.toLocaleString('id-ID')}`]
|
||||||
|
]
|
||||||
|
|
||||||
|
summaryData.forEach(row => {
|
||||||
|
worksheetData.push([row[0], row[1]]) // Only 2 columns needed
|
||||||
|
})
|
||||||
|
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
// Category Details Section Header
|
||||||
|
worksheetData.push(['RINCIAN KATEGORI']) // Section header
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
// Header row untuk tabel category data
|
||||||
|
const headerRow = ['No', 'Nama', 'Total Produk', 'Qty', 'Total Orders', 'Pendapatan']
|
||||||
|
worksheetData.push(headerRow)
|
||||||
|
|
||||||
|
// Add category data rows
|
||||||
|
categoryData.data?.forEach((category, index) => {
|
||||||
|
const rowData = [
|
||||||
|
index + 1, // No
|
||||||
|
category.category_name,
|
||||||
|
category.product_count,
|
||||||
|
category.total_quantity,
|
||||||
|
category.order_count,
|
||||||
|
category.total_revenue // Store as number for Excel formatting
|
||||||
|
]
|
||||||
|
worksheetData.push(rowData)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Add total row
|
||||||
|
const totalRow = [
|
||||||
|
'TOTAL',
|
||||||
|
'',
|
||||||
|
categorySummary.productCount,
|
||||||
|
categorySummary.totalQuantity,
|
||||||
|
categorySummary.orderCount,
|
||||||
|
categorySummary.totalRevenue
|
||||||
|
]
|
||||||
|
worksheetData.push(totalRow)
|
||||||
|
|
||||||
|
// Create workbook dan worksheet
|
||||||
|
const workbook = XLSX.utils.book_new()
|
||||||
|
const worksheet = XLSX.utils.aoa_to_sheet(worksheetData)
|
||||||
|
|
||||||
|
// Apply basic formatting
|
||||||
|
this.applyBasicFormatting(worksheet, worksheetData.length, XLSX)
|
||||||
|
|
||||||
|
// Add worksheet ke workbook
|
||||||
|
XLSX.utils.book_append_sheet(workbook, worksheet, 'Penjualan Kategori')
|
||||||
|
|
||||||
|
// Generate filename
|
||||||
|
const exportFilename = filename || this.generateFilename('Penjualan_Kategori')
|
||||||
|
|
||||||
|
// Download file
|
||||||
|
XLSX.writeFile(workbook, exportFilename)
|
||||||
|
|
||||||
|
return { success: true, filename: exportFilename }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting to Excel:', error)
|
||||||
|
return { success: false, error: 'Failed to export Excel file' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Apply basic formatting (SheetJS compatible)
|
||||||
|
*/
|
||||||
|
private static applyBasicFormatting(worksheet: any, totalRows: number, XLSX: any) {
|
||||||
|
// Set column widths
|
||||||
|
const colWidths = [
|
||||||
|
{ wch: 8 }, // No
|
||||||
|
{ wch: 30 }, // Nama
|
||||||
|
{ wch: 15 }, // Total Produk
|
||||||
|
{ wch: 12 }, // Qty
|
||||||
|
{ wch: 15 }, // Total Orders
|
||||||
|
{ wch: 20 } // Pendapatan
|
||||||
|
]
|
||||||
|
worksheet['!cols'] = colWidths
|
||||||
|
|
||||||
|
// Set row heights for better spacing
|
||||||
|
worksheet['!rows'] = [
|
||||||
|
{ hpt: 30 }, // Title row
|
||||||
|
{ hpt: 25 }, // Period row
|
||||||
|
{ hpt: 15 }, // Empty row
|
||||||
|
{ hpt: 25 }, // Summary header
|
||||||
|
{ hpt: 15 } // Empty row
|
||||||
|
]
|
||||||
|
|
||||||
|
// Merge cells untuk headers
|
||||||
|
const merges = [
|
||||||
|
{ s: { r: 0, c: 0 }, e: { r: 0, c: 5 } }, // Title (span across all columns)
|
||||||
|
{ s: { r: 1, c: 0 }, e: { r: 1, c: 5 } }, // Period (span across all columns)
|
||||||
|
{ s: { r: 3, c: 0 }, e: { r: 3, c: 5 } } // Summary header (span across all columns)
|
||||||
|
]
|
||||||
|
|
||||||
|
// Find and add merge for category details header
|
||||||
|
for (let i = 0; i < totalRows; i++) {
|
||||||
|
const cell = worksheet[XLSX.utils.encode_cell({ r: i, c: 0 })]
|
||||||
|
if (cell && cell.v === 'RINCIAN KATEGORI') {
|
||||||
|
merges.push({ s: { r: i, c: 0 }, e: { r: i, c: 5 } }) // Span across all columns
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
worksheet['!merges'] = merges
|
||||||
|
|
||||||
|
// Apply number formatting untuk currency cells
|
||||||
|
this.applyNumberFormatting(worksheet, totalRows, XLSX)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Apply number formatting for currency and styling
|
||||||
|
*/
|
||||||
|
private static applyNumberFormatting(worksheet: any, totalRows: number, XLSX: any) {
|
||||||
|
// Find table data start (after header row)
|
||||||
|
let dataStartRow = -1
|
||||||
|
for (let i = 0; i < totalRows; i++) {
|
||||||
|
const cell = worksheet[XLSX.utils.encode_cell({ r: i, c: 0 })]
|
||||||
|
if (cell && cell.v === 'No') {
|
||||||
|
dataStartRow = i + 1
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dataStartRow === -1) return
|
||||||
|
|
||||||
|
// Count actual data rows (excluding total row)
|
||||||
|
const dataRowsCount = totalRows - dataStartRow - 1 // -1 for total row
|
||||||
|
|
||||||
|
// Apply currency formatting to Pendapatan column (column 5 - index 5)
|
||||||
|
for (let row = dataStartRow; row <= dataStartRow + dataRowsCount; row++) {
|
||||||
|
// Include total row
|
||||||
|
const cellAddress = XLSX.utils.encode_cell({ r: row, c: 5 }) // Pendapatan column
|
||||||
|
const cell = worksheet[cellAddress]
|
||||||
|
|
||||||
|
if (cell && typeof cell.v === 'number') {
|
||||||
|
// Apply Indonesian currency format
|
||||||
|
cell.z = '#,##0'
|
||||||
|
cell.t = 'n'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply styling to header row
|
||||||
|
const headerRowIndex = dataStartRow - 1
|
||||||
|
for (let col = 0; col < 6; col++) {
|
||||||
|
const cellAddress = XLSX.utils.encode_cell({ r: headerRowIndex, c: col })
|
||||||
|
const cell = worksheet[cellAddress]
|
||||||
|
|
||||||
|
if (cell) {
|
||||||
|
// Apply bold formatting (basic approach for SheetJS)
|
||||||
|
cell.s = {
|
||||||
|
font: { bold: true },
|
||||||
|
fill: { fgColor: { rgb: 'F3F4F6' } }, // Light gray background
|
||||||
|
border: {
|
||||||
|
bottom: { style: 'medium', color: { rgb: '000000' } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply styling to total row
|
||||||
|
const totalRowIndex = dataStartRow + dataRowsCount
|
||||||
|
for (let col = 0; col < 6; col++) {
|
||||||
|
const cellAddress = XLSX.utils.encode_cell({ r: totalRowIndex, c: col })
|
||||||
|
const cell = worksheet[cellAddress]
|
||||||
|
|
||||||
|
if (cell) {
|
||||||
|
// Apply bold formatting for total row
|
||||||
|
cell.s = {
|
||||||
|
font: { bold: true },
|
||||||
|
border: {
|
||||||
|
top: { style: 'medium', color: { rgb: '000000' } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate filename with timestamp
|
||||||
|
*/
|
||||||
|
private static generateFilename(prefix: string): string {
|
||||||
|
const now = new Date()
|
||||||
|
const year = now.getFullYear()
|
||||||
|
const month = (now.getMonth() + 1).toString().padStart(2, '0')
|
||||||
|
const day = now.getDate().toString().padStart(2, '0')
|
||||||
|
const hour = now.getHours().toString().padStart(2, '0')
|
||||||
|
const minute = now.getMinutes().toString().padStart(2, '0')
|
||||||
|
|
||||||
|
return `${prefix}_${year}_${month}_${day}_${hour}${minute}.xlsx`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Export Category Sales data with custom configuration
|
||||||
|
*/
|
||||||
|
static async exportCustomCategoryData(
|
||||||
|
categoryData: CategoryReport,
|
||||||
|
options?: {
|
||||||
|
includeSummary?: boolean
|
||||||
|
includeOrderCount?: boolean
|
||||||
|
customFilename?: string
|
||||||
|
sheetName?: string
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const XLSX = await import('xlsx')
|
||||||
|
const worksheetData: any[][] = []
|
||||||
|
|
||||||
|
// Always include title and period
|
||||||
|
worksheetData.push(['LAPORAN PENJUALAN KATEGORI'])
|
||||||
|
worksheetData.push([`Periode: ${categoryData.date_from.split('T')[0]} - ${categoryData.date_to.split('T')[0]}`])
|
||||||
|
worksheetData.push([])
|
||||||
|
|
||||||
|
// Optional summary
|
||||||
|
if (options?.includeSummary !== false) {
|
||||||
|
const categorySummary = {
|
||||||
|
totalRevenue: categoryData.data?.reduce((sum, item) => sum + (item?.total_revenue || 0), 0) || 0,
|
||||||
|
orderCount: categoryData.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0,
|
||||||
|
productCount: categoryData.data?.reduce((sum, item) => sum + (item?.product_count || 0), 0) || 0,
|
||||||
|
totalQuantity: categoryData.data?.reduce((sum, item) => sum + (item?.total_quantity || 0), 0) || 0,
|
||||||
|
totalCategories: categoryData.data?.length || 0
|
||||||
|
}
|
||||||
|
|
||||||
|
worksheetData.push(['RINGKASAN PERIODE'])
|
||||||
|
worksheetData.push([])
|
||||||
|
const summaryData = [
|
||||||
|
['Total Kategori:', categorySummary.totalCategories.toString()],
|
||||||
|
['Total Produk:', categorySummary.productCount.toString()],
|
||||||
|
['Total Quantity:', categorySummary.totalQuantity.toString()],
|
||||||
|
['Total Revenue:', `Rp ${categorySummary.totalRevenue.toLocaleString('id-ID')}`]
|
||||||
|
]
|
||||||
|
summaryData.forEach(row => worksheetData.push([row[0], row[1]]))
|
||||||
|
worksheetData.push([])
|
||||||
|
worksheetData.push([])
|
||||||
|
}
|
||||||
|
|
||||||
|
worksheetData.push(['RINCIAN KATEGORI'])
|
||||||
|
worksheetData.push([])
|
||||||
|
|
||||||
|
// Header row based on options
|
||||||
|
const headerRow =
|
||||||
|
options?.includeOrderCount !== false
|
||||||
|
? ['No', 'Nama', 'Total Produk', 'Qty', 'Total Orders', 'Pendapatan']
|
||||||
|
: ['No', 'Nama', 'Total Produk', 'Qty', 'Pendapatan']
|
||||||
|
worksheetData.push(headerRow)
|
||||||
|
|
||||||
|
// Add category data based on options
|
||||||
|
categoryData.data?.forEach((category, index) => {
|
||||||
|
const rowData =
|
||||||
|
options?.includeOrderCount !== false
|
||||||
|
? [
|
||||||
|
index + 1,
|
||||||
|
category.category_name,
|
||||||
|
category.product_count,
|
||||||
|
category.total_quantity,
|
||||||
|
category.order_count,
|
||||||
|
category.total_revenue
|
||||||
|
]
|
||||||
|
: [
|
||||||
|
index + 1,
|
||||||
|
category.category_name,
|
||||||
|
category.product_count,
|
||||||
|
category.total_quantity,
|
||||||
|
category.total_revenue
|
||||||
|
]
|
||||||
|
worksheetData.push(rowData)
|
||||||
|
})
|
||||||
|
|
||||||
|
const workbook = XLSX.utils.book_new()
|
||||||
|
const worksheet = XLSX.utils.aoa_to_sheet(worksheetData)
|
||||||
|
|
||||||
|
this.applyBasicFormatting(worksheet, worksheetData.length, XLSX)
|
||||||
|
|
||||||
|
const sheetName = options?.sheetName || 'Penjualan Kategori'
|
||||||
|
XLSX.utils.book_append_sheet(workbook, worksheet, sheetName)
|
||||||
|
|
||||||
|
const exportFilename = options?.customFilename || this.generateFilename('Custom_Category_Sales')
|
||||||
|
XLSX.writeFile(workbook, exportFilename)
|
||||||
|
|
||||||
|
return { success: true, filename: exportFilename }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting custom category data to Excel:', error)
|
||||||
|
return { success: false, error: 'Failed to export Excel file' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,414 @@
|
|||||||
|
// services/excelExportProductService.ts
|
||||||
|
import type { ProductSalesReport } from '@/types/services/analytic'
|
||||||
|
|
||||||
|
export class ExcelExportSalesProductService {
|
||||||
|
/**
|
||||||
|
* Export Product Sales Report to Excel
|
||||||
|
*/
|
||||||
|
static async exportProductSalesToExcel(productData: ProductSalesReport, filename?: string) {
|
||||||
|
try {
|
||||||
|
// Dynamic import untuk xlsx library
|
||||||
|
const XLSX = await import('xlsx')
|
||||||
|
|
||||||
|
// Prepare data untuk Excel
|
||||||
|
const worksheetData: any[][] = []
|
||||||
|
|
||||||
|
// Header dengan report info (baris 1-2)
|
||||||
|
worksheetData.push(['LAPORAN PENJUALAN PRODUK']) // Row 0 - Main title
|
||||||
|
worksheetData.push([`Periode: ${productData.date_from.split('T')[0]} - ${productData.date_to.split('T')[0]}`]) // Row 1 - Period
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
// Calculate summary
|
||||||
|
const productSummary = {
|
||||||
|
totalQuantitySold: productData.data?.reduce((sum, item) => sum + (item?.quantity_sold || 0), 0) || 0,
|
||||||
|
totalRevenue: productData.data?.reduce((sum, item) => sum + (item?.revenue || 0), 0) || 0,
|
||||||
|
totalOrders: productData.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0,
|
||||||
|
averageRevenue: 0
|
||||||
|
}
|
||||||
|
productSummary.averageRevenue =
|
||||||
|
productSummary.totalQuantitySold > 0 ? productSummary.totalRevenue / productSummary.totalQuantitySold : 0
|
||||||
|
|
||||||
|
// Add Summary Section
|
||||||
|
worksheetData.push(['RINGKASAN PERIODE']) // Section header
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
const summaryData = [
|
||||||
|
['Total Quantity Sold:', productSummary.totalQuantitySold.toString()],
|
||||||
|
['Total Orders:', productSummary.totalOrders.toString()],
|
||||||
|
['Total Revenue:', `Rp ${productSummary.totalRevenue.toLocaleString('id-ID')}`],
|
||||||
|
['Average Revenue per Item:', `Rp ${productSummary.averageRevenue.toLocaleString('id-ID')}`]
|
||||||
|
]
|
||||||
|
|
||||||
|
summaryData.forEach(row => {
|
||||||
|
worksheetData.push([row[0], row[1]]) // Only 2 columns needed
|
||||||
|
})
|
||||||
|
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
// Product Details Section Header
|
||||||
|
worksheetData.push(['RINCIAN PRODUK']) // Section header
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
// Group products by category
|
||||||
|
const groupedProducts =
|
||||||
|
productData.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[]>
|
||||||
|
) || {}
|
||||||
|
|
||||||
|
// Header row untuk tabel product data
|
||||||
|
const headerRow = ['Kategori', 'Produk', 'Qty', 'Order', 'Pendapatan', 'Rata Rata']
|
||||||
|
worksheetData.push(headerRow)
|
||||||
|
|
||||||
|
// Add grouped products data
|
||||||
|
Object.keys(groupedProducts)
|
||||||
|
.sort()
|
||||||
|
.forEach(categoryName => {
|
||||||
|
const categoryProducts = groupedProducts[categoryName]
|
||||||
|
|
||||||
|
// Category header row
|
||||||
|
worksheetData.push([categoryName.toUpperCase(), '', '', '', '', ''])
|
||||||
|
|
||||||
|
// Category products
|
||||||
|
categoryProducts.forEach(item => {
|
||||||
|
const rowData = [
|
||||||
|
'', // Empty for category column (indented effect)
|
||||||
|
item.product_name,
|
||||||
|
item.quantity_sold,
|
||||||
|
item.order_count || 0,
|
||||||
|
item.revenue, // Store as number for Excel formatting
|
||||||
|
item.average_price // Store as number for Excel formatting
|
||||||
|
]
|
||||||
|
worksheetData.push(rowData)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Category subtotal
|
||||||
|
const categoryTotalQty = categoryProducts.reduce((sum, item) => sum + (item.quantity_sold || 0), 0)
|
||||||
|
const categoryTotalOrders = categoryProducts.reduce((sum, item) => sum + (item.order_count || 0), 0)
|
||||||
|
const categoryTotalRevenue = categoryProducts.reduce((sum, item) => sum + (item.revenue || 0), 0)
|
||||||
|
|
||||||
|
const categorySubtotalRow = [
|
||||||
|
`Subtotal ${categoryName}`,
|
||||||
|
'',
|
||||||
|
categoryTotalQty,
|
||||||
|
categoryTotalOrders,
|
||||||
|
categoryTotalRevenue,
|
||||||
|
''
|
||||||
|
]
|
||||||
|
worksheetData.push(categorySubtotalRow)
|
||||||
|
worksheetData.push([]) // Empty row between categories
|
||||||
|
})
|
||||||
|
|
||||||
|
// Grand total
|
||||||
|
const grandTotalRow = [
|
||||||
|
'TOTAL KESELURUHAN',
|
||||||
|
'',
|
||||||
|
productSummary.totalQuantitySold,
|
||||||
|
productSummary.totalOrders,
|
||||||
|
productSummary.totalRevenue,
|
||||||
|
''
|
||||||
|
]
|
||||||
|
worksheetData.push(grandTotalRow)
|
||||||
|
|
||||||
|
// Create workbook dan worksheet
|
||||||
|
const workbook = XLSX.utils.book_new()
|
||||||
|
const worksheet = XLSX.utils.aoa_to_sheet(worksheetData)
|
||||||
|
|
||||||
|
// Apply basic formatting
|
||||||
|
this.applyBasicFormatting(worksheet, worksheetData.length, XLSX)
|
||||||
|
|
||||||
|
// Add worksheet ke workbook
|
||||||
|
XLSX.utils.book_append_sheet(workbook, worksheet, 'Penjualan Produk')
|
||||||
|
|
||||||
|
// Generate filename
|
||||||
|
const exportFilename = filename || this.generateFilename('Penjualan_Produk')
|
||||||
|
|
||||||
|
// Download file
|
||||||
|
XLSX.writeFile(workbook, exportFilename)
|
||||||
|
|
||||||
|
return { success: true, filename: exportFilename }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting to Excel:', error)
|
||||||
|
return { success: false, error: 'Failed to export Excel file' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Apply basic formatting (SheetJS compatible)
|
||||||
|
*/
|
||||||
|
private static applyBasicFormatting(worksheet: any, totalRows: number, XLSX: any) {
|
||||||
|
// Set column widths
|
||||||
|
const colWidths = [
|
||||||
|
{ wch: 25 }, // Kategori
|
||||||
|
{ wch: 40 }, // Produk
|
||||||
|
{ wch: 12 }, // Qty
|
||||||
|
{ wch: 12 }, // Order
|
||||||
|
{ wch: 20 }, // Pendapatan
|
||||||
|
{ wch: 18 } // Rata Rata
|
||||||
|
]
|
||||||
|
worksheet['!cols'] = colWidths
|
||||||
|
|
||||||
|
// Set row heights for better spacing
|
||||||
|
worksheet['!rows'] = [
|
||||||
|
{ hpt: 30 }, // Title row
|
||||||
|
{ hpt: 25 }, // Period row
|
||||||
|
{ hpt: 15 }, // Empty row
|
||||||
|
{ hpt: 25 }, // Summary header
|
||||||
|
{ hpt: 15 } // Empty row
|
||||||
|
]
|
||||||
|
|
||||||
|
// Merge cells untuk headers
|
||||||
|
const merges = [
|
||||||
|
{ s: { r: 0, c: 0 }, e: { r: 0, c: 5 } }, // Title (span across all columns)
|
||||||
|
{ s: { r: 1, c: 0 }, e: { r: 1, c: 5 } }, // Period (span across all columns)
|
||||||
|
{ s: { r: 3, c: 0 }, e: { r: 3, c: 5 } } // Summary header (span across all columns)
|
||||||
|
]
|
||||||
|
|
||||||
|
// Find and add merge for product details header
|
||||||
|
for (let i = 0; i < totalRows; i++) {
|
||||||
|
const cell = worksheet[XLSX.utils.encode_cell({ r: i, c: 0 })]
|
||||||
|
if (cell && cell.v === 'RINCIAN PRODUK') {
|
||||||
|
merges.push({ s: { r: i, c: 0 }, e: { r: i, c: 5 } }) // Span across all columns
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
worksheet['!merges'] = merges
|
||||||
|
|
||||||
|
// Apply number formatting untuk currency cells
|
||||||
|
this.applyNumberFormatting(worksheet, totalRows, XLSX)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Apply number formatting for currency and styling
|
||||||
|
*/
|
||||||
|
private static applyNumberFormatting(worksheet: any, totalRows: number, XLSX: any) {
|
||||||
|
// Find table data start (after header row)
|
||||||
|
let dataStartRow = -1
|
||||||
|
for (let i = 0; i < totalRows; i++) {
|
||||||
|
const cell = worksheet[XLSX.utils.encode_cell({ r: i, c: 0 })]
|
||||||
|
if (cell && cell.v === 'Kategori') {
|
||||||
|
dataStartRow = i + 1
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dataStartRow === -1) return
|
||||||
|
|
||||||
|
// Apply currency formatting to Pendapatan and Rata Rata columns (columns 4 and 5)
|
||||||
|
for (let row = dataStartRow; row < totalRows; row++) {
|
||||||
|
// Pendapatan column (index 4)
|
||||||
|
const revenueCell = worksheet[XLSX.utils.encode_cell({ r: row, c: 4 })]
|
||||||
|
if (revenueCell && typeof revenueCell.v === 'number') {
|
||||||
|
revenueCell.z = '#,##0'
|
||||||
|
revenueCell.t = 'n'
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rata Rata column (index 5)
|
||||||
|
const avgCell = worksheet[XLSX.utils.encode_cell({ r: row, c: 5 })]
|
||||||
|
if (avgCell && typeof avgCell.v === 'number') {
|
||||||
|
avgCell.z = '#,##0'
|
||||||
|
avgCell.t = 'n'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply styling to header row
|
||||||
|
const headerRowIndex = dataStartRow - 1
|
||||||
|
for (let col = 0; col < 6; col++) {
|
||||||
|
const cellAddress = XLSX.utils.encode_cell({ r: headerRowIndex, c: col })
|
||||||
|
const cell = worksheet[cellAddress]
|
||||||
|
|
||||||
|
if (cell) {
|
||||||
|
// Apply bold formatting (basic approach for SheetJS)
|
||||||
|
cell.s = {
|
||||||
|
font: { bold: true },
|
||||||
|
fill: { fgColor: { rgb: 'F3F4F6' } }, // Light gray background
|
||||||
|
border: {
|
||||||
|
bottom: { style: 'medium', color: { rgb: '000000' } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply styling to category headers and totals
|
||||||
|
for (let row = dataStartRow; row < totalRows; row++) {
|
||||||
|
const cell = worksheet[XLSX.utils.encode_cell({ r: row, c: 0 })]
|
||||||
|
|
||||||
|
if (cell && cell.v) {
|
||||||
|
const cellValue = cell.v.toString()
|
||||||
|
|
||||||
|
// Style category headers (uppercase text without "Subtotal" or "TOTAL")
|
||||||
|
if (
|
||||||
|
cellValue === cellValue.toUpperCase() &&
|
||||||
|
!cellValue.includes('Subtotal') &&
|
||||||
|
!cellValue.includes('TOTAL') &&
|
||||||
|
cellValue.length > 0
|
||||||
|
) {
|
||||||
|
for (let col = 0; col < 6; col++) {
|
||||||
|
const categoryCellAddress = XLSX.utils.encode_cell({ r: row, c: col })
|
||||||
|
const categoryCell = worksheet[categoryCellAddress]
|
||||||
|
if (categoryCell) {
|
||||||
|
categoryCell.s = {
|
||||||
|
font: { bold: true, color: { rgb: '36175E' } },
|
||||||
|
fill: { fgColor: { rgb: 'F8F8F8' } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Style subtotal and total rows
|
||||||
|
if (cellValue.startsWith('Subtotal') || cellValue.startsWith('TOTAL')) {
|
||||||
|
for (let col = 0; col < 6; col++) {
|
||||||
|
const totalCellAddress = XLSX.utils.encode_cell({ r: row, c: col })
|
||||||
|
const totalCell = worksheet[totalCellAddress]
|
||||||
|
if (totalCell) {
|
||||||
|
totalCell.s = {
|
||||||
|
font: { bold: true },
|
||||||
|
border: {
|
||||||
|
top: { style: 'medium', color: { rgb: '000000' } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate filename with timestamp
|
||||||
|
*/
|
||||||
|
private static generateFilename(prefix: string): string {
|
||||||
|
const now = new Date()
|
||||||
|
const year = now.getFullYear()
|
||||||
|
const month = (now.getMonth() + 1).toString().padStart(2, '0')
|
||||||
|
const day = now.getDate().toString().padStart(2, '0')
|
||||||
|
const hour = now.getHours().toString().padStart(2, '0')
|
||||||
|
const minute = now.getMinutes().toString().padStart(2, '0')
|
||||||
|
|
||||||
|
return `${prefix}_${year}_${month}_${day}_${hour}${minute}.xlsx`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Export Product Sales data with custom configuration
|
||||||
|
*/
|
||||||
|
static async exportCustomProductData(
|
||||||
|
productData: ProductSalesReport,
|
||||||
|
options?: {
|
||||||
|
includeSummary?: boolean
|
||||||
|
customFilename?: string
|
||||||
|
sheetName?: string
|
||||||
|
groupByCategory?: boolean
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const XLSX = await import('xlsx')
|
||||||
|
const worksheetData: any[][] = []
|
||||||
|
|
||||||
|
// Always include title and period
|
||||||
|
worksheetData.push(['LAPORAN PENJUALAN PRODUK'])
|
||||||
|
worksheetData.push([`Periode: ${productData.date_from.split('T')[0]} - ${productData.date_to.split('T')[0]}`])
|
||||||
|
worksheetData.push([])
|
||||||
|
|
||||||
|
// Optional summary
|
||||||
|
if (options?.includeSummary !== false) {
|
||||||
|
const productSummary = {
|
||||||
|
totalQuantitySold: productData.data?.reduce((sum, item) => sum + (item?.quantity_sold || 0), 0) || 0,
|
||||||
|
totalRevenue: productData.data?.reduce((sum, item) => sum + (item?.revenue || 0), 0) || 0,
|
||||||
|
totalOrders: productData.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0
|
||||||
|
}
|
||||||
|
|
||||||
|
worksheetData.push(['RINGKASAN PERIODE'])
|
||||||
|
worksheetData.push([])
|
||||||
|
const summaryData = [
|
||||||
|
['Total Quantity Sold:', productSummary.totalQuantitySold.toString()],
|
||||||
|
['Total Orders:', productSummary.totalOrders.toString()],
|
||||||
|
['Total Revenue:', `Rp ${productSummary.totalRevenue.toLocaleString('id-ID')}`]
|
||||||
|
]
|
||||||
|
summaryData.forEach(row => worksheetData.push([row[0], row[1]]))
|
||||||
|
worksheetData.push([])
|
||||||
|
worksheetData.push([])
|
||||||
|
}
|
||||||
|
|
||||||
|
worksheetData.push(['RINCIAN PRODUK'])
|
||||||
|
worksheetData.push([])
|
||||||
|
|
||||||
|
// Header row
|
||||||
|
const headerRow =
|
||||||
|
options?.groupByCategory !== false
|
||||||
|
? ['Kategori', 'Produk', 'Qty', 'Order', 'Pendapatan', 'Rata Rata']
|
||||||
|
: ['Produk', 'Kategori', 'Qty', 'Order', 'Pendapatan', 'Rata Rata']
|
||||||
|
worksheetData.push(headerRow)
|
||||||
|
|
||||||
|
// Add product data based on grouping option
|
||||||
|
if (options?.groupByCategory !== false) {
|
||||||
|
// Group by category (default)
|
||||||
|
const groupedProducts =
|
||||||
|
productData.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[]>
|
||||||
|
) || {}
|
||||||
|
|
||||||
|
Object.keys(groupedProducts)
|
||||||
|
.sort()
|
||||||
|
.forEach(categoryName => {
|
||||||
|
const categoryProducts = groupedProducts[categoryName]
|
||||||
|
worksheetData.push([categoryName.toUpperCase(), '', '', '', '', ''])
|
||||||
|
categoryProducts.forEach(item => {
|
||||||
|
worksheetData.push([
|
||||||
|
'',
|
||||||
|
item.product_name,
|
||||||
|
item.quantity_sold,
|
||||||
|
item.order_count || 0,
|
||||||
|
item.revenue,
|
||||||
|
item.average_price
|
||||||
|
])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
// Flat list without grouping
|
||||||
|
productData.data?.forEach(item => {
|
||||||
|
worksheetData.push([
|
||||||
|
item.product_name,
|
||||||
|
item.category_name,
|
||||||
|
item.quantity_sold,
|
||||||
|
item.order_count || 0,
|
||||||
|
item.revenue,
|
||||||
|
item.average_price
|
||||||
|
])
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const workbook = XLSX.utils.book_new()
|
||||||
|
const worksheet = XLSX.utils.aoa_to_sheet(worksheetData)
|
||||||
|
|
||||||
|
this.applyBasicFormatting(worksheet, worksheetData.length, XLSX)
|
||||||
|
|
||||||
|
const sheetName = options?.sheetName || 'Penjualan Produk'
|
||||||
|
XLSX.utils.book_append_sheet(workbook, worksheet, sheetName)
|
||||||
|
|
||||||
|
const exportFilename = options?.customFilename || this.generateFilename('Custom_Product_Sales')
|
||||||
|
XLSX.writeFile(workbook, exportFilename)
|
||||||
|
|
||||||
|
return { success: true, filename: exportFilename }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting custom product data to Excel:', error)
|
||||||
|
return { success: false, error: 'Failed to export Excel file' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,469 @@
|
|||||||
|
// services/excelExportSalesService.ts
|
||||||
|
import type { CategoryReport, PaymentReport, ProductSalesReport, ProfitLossReport } from '@/types/services/analytic'
|
||||||
|
|
||||||
|
export interface SalesReportData {
|
||||||
|
profitLoss: ProfitLossReport
|
||||||
|
paymentAnalytics: PaymentReport
|
||||||
|
categoryAnalytics: CategoryReport
|
||||||
|
productAnalytics: ProductSalesReport
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ExcelExportSalesService {
|
||||||
|
/**
|
||||||
|
* Export Sales Report to Excel
|
||||||
|
*/
|
||||||
|
static async exportSalesReportToExcel(salesData: SalesReportData, filename?: string) {
|
||||||
|
try {
|
||||||
|
// Dynamic import untuk xlsx library
|
||||||
|
const XLSX = await import('xlsx')
|
||||||
|
|
||||||
|
// Prepare data untuk Excel
|
||||||
|
const worksheetData: any[][] = []
|
||||||
|
|
||||||
|
// Header dengan report info (baris 1-2)
|
||||||
|
worksheetData.push(['LAPORAN TRANSAKSI']) // Row 0 - Main title
|
||||||
|
worksheetData.push([
|
||||||
|
`Periode: ${salesData.profitLoss.date_from.split('T')[0]} - ${salesData.profitLoss.date_to.split('T')[0]}`
|
||||||
|
]) // Row 1 - Period
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
// Add Summary Section (Ringkasan)
|
||||||
|
worksheetData.push(['RINGKASAN PERIODE']) // Section header
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
const ringkasanData = [
|
||||||
|
['Total Penjualan:', `Rp ${salesData.profitLoss.summary.total_revenue.toLocaleString('id-ID')}`],
|
||||||
|
['Total Diskon:', `Rp ${salesData.profitLoss.summary.total_discount.toLocaleString('id-ID')}`],
|
||||||
|
['Total Pajak:', `Rp ${salesData.profitLoss.summary.total_tax.toLocaleString('id-ID')}`],
|
||||||
|
['Total:', `Rp ${salesData.profitLoss.summary.total_revenue.toLocaleString('id-ID')}`]
|
||||||
|
]
|
||||||
|
|
||||||
|
ringkasanData.forEach(row => {
|
||||||
|
worksheetData.push([row[0], row[1]])
|
||||||
|
})
|
||||||
|
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
// Add Invoice Section
|
||||||
|
worksheetData.push(['INVOICE']) // Section header
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
const invoiceData = [
|
||||||
|
['Total Invoice:', salesData.profitLoss.summary.total_orders.toString()],
|
||||||
|
['Rata-rata Tagihan Per Invoice:', `Rp ${salesData.profitLoss.summary.average_profit.toLocaleString('id-ID')}`]
|
||||||
|
]
|
||||||
|
|
||||||
|
invoiceData.forEach(row => {
|
||||||
|
worksheetData.push([row[0], row[1]])
|
||||||
|
})
|
||||||
|
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
// Add Payment Methods Section
|
||||||
|
worksheetData.push(['RINGKASAN METODE PEMBAYARAN']) // Section header
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
// Payment methods table header
|
||||||
|
const paymentHeaderRow = ['No', 'Metode Pembayaran', 'Tipe', 'Jumlah Order', 'Total Amount', 'Persentase']
|
||||||
|
worksheetData.push(paymentHeaderRow)
|
||||||
|
|
||||||
|
// Payment methods data
|
||||||
|
salesData.paymentAnalytics.data?.forEach((payment, index) => {
|
||||||
|
const rowData = [
|
||||||
|
index + 1,
|
||||||
|
payment.payment_method_name,
|
||||||
|
payment.payment_method_type.toUpperCase(),
|
||||||
|
payment.order_count,
|
||||||
|
payment.total_amount,
|
||||||
|
`${(payment.percentage ?? 0).toFixed(1)}%`
|
||||||
|
]
|
||||||
|
worksheetData.push(rowData)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Payment methods total row
|
||||||
|
const paymentTotalRow = [
|
||||||
|
'TOTAL',
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
salesData.paymentAnalytics.summary?.total_orders ?? 0,
|
||||||
|
salesData.paymentAnalytics.summary?.total_amount ?? 0,
|
||||||
|
'100.0%'
|
||||||
|
]
|
||||||
|
worksheetData.push(paymentTotalRow)
|
||||||
|
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
// Add Category Section
|
||||||
|
worksheetData.push(['RINGKASAN KATEGORI']) // Section header
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
// Category table header
|
||||||
|
const categoryHeaderRow = ['No', 'Nama', 'Total Produk', 'Qty', 'Pendapatan']
|
||||||
|
worksheetData.push(categoryHeaderRow)
|
||||||
|
|
||||||
|
// Calculate category summaries
|
||||||
|
const categorySummary = {
|
||||||
|
totalRevenue: salesData.categoryAnalytics.data?.reduce((sum, item) => sum + (item?.total_revenue || 0), 0) || 0,
|
||||||
|
productCount: salesData.categoryAnalytics.data?.reduce((sum, item) => sum + (item?.product_count || 0), 0) || 0,
|
||||||
|
totalQuantity:
|
||||||
|
salesData.categoryAnalytics.data?.reduce((sum, item) => sum + (item?.total_quantity || 0), 0) || 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Category data
|
||||||
|
salesData.categoryAnalytics.data?.forEach((category, index) => {
|
||||||
|
const rowData = [
|
||||||
|
index + 1,
|
||||||
|
category.category_name,
|
||||||
|
category.product_count,
|
||||||
|
category.total_quantity,
|
||||||
|
category.total_revenue
|
||||||
|
]
|
||||||
|
worksheetData.push(rowData)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Category total row
|
||||||
|
const categoryTotalRow = [
|
||||||
|
'TOTAL',
|
||||||
|
'',
|
||||||
|
categorySummary.productCount,
|
||||||
|
categorySummary.totalQuantity,
|
||||||
|
categorySummary.totalRevenue
|
||||||
|
]
|
||||||
|
worksheetData.push(categoryTotalRow)
|
||||||
|
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
// Add Product Section
|
||||||
|
worksheetData.push(['RINGKASAN ITEM']) // Section header
|
||||||
|
worksheetData.push([]) // Empty row
|
||||||
|
|
||||||
|
// Group products by category
|
||||||
|
const groupedProducts =
|
||||||
|
salesData.productAnalytics.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[]>
|
||||||
|
) || {}
|
||||||
|
|
||||||
|
// Calculate product summary
|
||||||
|
const productSummary = {
|
||||||
|
totalQuantitySold:
|
||||||
|
salesData.productAnalytics.data?.reduce((sum, item) => sum + (item?.quantity_sold || 0), 0) || 0,
|
||||||
|
totalRevenue: salesData.productAnalytics.data?.reduce((sum, item) => sum + (item?.revenue || 0), 0) || 0,
|
||||||
|
totalOrders: salesData.productAnalytics.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Product table header
|
||||||
|
const productHeaderRow = ['Kategori', 'Produk', 'Qty', 'Order', 'Pendapatan', 'Rata Rata']
|
||||||
|
worksheetData.push(productHeaderRow)
|
||||||
|
|
||||||
|
// Add grouped products data
|
||||||
|
Object.keys(groupedProducts)
|
||||||
|
.sort()
|
||||||
|
.forEach(categoryName => {
|
||||||
|
const categoryProducts = groupedProducts[categoryName]
|
||||||
|
|
||||||
|
// Category header row
|
||||||
|
worksheetData.push([categoryName.toUpperCase(), '', '', '', '', ''])
|
||||||
|
|
||||||
|
// Category products
|
||||||
|
categoryProducts.forEach(item => {
|
||||||
|
const rowData = [
|
||||||
|
'',
|
||||||
|
item.product_name,
|
||||||
|
item.quantity_sold,
|
||||||
|
item.order_count || 0,
|
||||||
|
item.revenue,
|
||||||
|
item.average_price
|
||||||
|
]
|
||||||
|
worksheetData.push(rowData)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Category subtotal
|
||||||
|
const categoryTotalQty = categoryProducts.reduce((sum, item) => sum + (item.quantity_sold || 0), 0)
|
||||||
|
const categoryTotalOrders = categoryProducts.reduce((sum, item) => sum + (item.order_count || 0), 0)
|
||||||
|
const categoryTotalRevenue = categoryProducts.reduce((sum, item) => sum + (item.revenue || 0), 0)
|
||||||
|
const categoryAverage = categoryTotalQty > 0 ? categoryTotalRevenue / categoryTotalQty : 0
|
||||||
|
|
||||||
|
const categorySubtotalRow = [
|
||||||
|
`Subtotal ${categoryName}`,
|
||||||
|
'',
|
||||||
|
categoryTotalQty,
|
||||||
|
categoryTotalOrders,
|
||||||
|
categoryTotalRevenue,
|
||||||
|
categoryAverage
|
||||||
|
]
|
||||||
|
worksheetData.push(categorySubtotalRow)
|
||||||
|
worksheetData.push([]) // Empty row between categories
|
||||||
|
})
|
||||||
|
|
||||||
|
// Grand total
|
||||||
|
const grandTotalAverage =
|
||||||
|
productSummary.totalQuantitySold > 0 ? productSummary.totalRevenue / productSummary.totalQuantitySold : 0
|
||||||
|
const grandTotalRow = [
|
||||||
|
'TOTAL KESELURUHAN',
|
||||||
|
'',
|
||||||
|
productSummary.totalQuantitySold,
|
||||||
|
productSummary.totalOrders,
|
||||||
|
productSummary.totalRevenue,
|
||||||
|
grandTotalAverage
|
||||||
|
]
|
||||||
|
worksheetData.push(grandTotalRow)
|
||||||
|
|
||||||
|
// Create workbook dan worksheet
|
||||||
|
const workbook = XLSX.utils.book_new()
|
||||||
|
const worksheet = XLSX.utils.aoa_to_sheet(worksheetData)
|
||||||
|
|
||||||
|
// Apply basic formatting
|
||||||
|
this.applyBasicFormatting(worksheet, worksheetData.length, XLSX)
|
||||||
|
|
||||||
|
// Add worksheet ke workbook
|
||||||
|
XLSX.utils.book_append_sheet(workbook, worksheet, 'Laporan Transaksi')
|
||||||
|
|
||||||
|
// Generate filename
|
||||||
|
const exportFilename = filename || this.generateFilename('Laporan_Transaksi')
|
||||||
|
|
||||||
|
// Download file
|
||||||
|
XLSX.writeFile(workbook, exportFilename)
|
||||||
|
|
||||||
|
return { success: true, filename: exportFilename }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting sales report to Excel:', error)
|
||||||
|
return { success: false, error: 'Failed to export Excel file' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Apply basic formatting (SheetJS compatible)
|
||||||
|
*/
|
||||||
|
private static applyBasicFormatting(worksheet: any, totalRows: number, XLSX: any) {
|
||||||
|
// Set column widths
|
||||||
|
const colWidths = [
|
||||||
|
{ wch: 25 }, // First column (category/label)
|
||||||
|
{ wch: 30 }, // Second column (description/name)
|
||||||
|
{ wch: 15 }, // Third column (numbers)
|
||||||
|
{ wch: 15 }, // Fourth column (numbers)
|
||||||
|
{ wch: 20 }, // Fifth column (amounts)
|
||||||
|
{ wch: 15 } // Sixth column (percentages/averages)
|
||||||
|
]
|
||||||
|
worksheet['!cols'] = colWidths
|
||||||
|
|
||||||
|
// Set row heights for better spacing
|
||||||
|
worksheet['!rows'] = [
|
||||||
|
{ hpt: 30 }, // Title row
|
||||||
|
{ hpt: 25 }, // Period row
|
||||||
|
{ hpt: 15 }, // Empty row
|
||||||
|
{ hpt: 25 }, // Section headers
|
||||||
|
{ hpt: 15 } // Empty row
|
||||||
|
]
|
||||||
|
|
||||||
|
// Merge cells untuk main headers
|
||||||
|
const merges = [
|
||||||
|
{ s: { r: 0, c: 0 }, e: { r: 0, c: 5 } }, // Main title
|
||||||
|
{ s: { r: 1, c: 0 }, e: { r: 1, c: 5 } } // Period
|
||||||
|
]
|
||||||
|
|
||||||
|
// Find and add merges for section headers
|
||||||
|
const sectionHeaders = [
|
||||||
|
'RINGKASAN PERIODE',
|
||||||
|
'INVOICE',
|
||||||
|
'RINGKASAN METODE PEMBAYARAN',
|
||||||
|
'RINGKASAN KATEGORI',
|
||||||
|
'RINGKASAN ITEM'
|
||||||
|
]
|
||||||
|
|
||||||
|
for (let i = 0; i < totalRows; i++) {
|
||||||
|
const cell = worksheet[XLSX.utils.encode_cell({ r: i, c: 0 })]
|
||||||
|
if (cell && sectionHeaders.includes(cell.v)) {
|
||||||
|
merges.push({ s: { r: i, c: 0 }, e: { r: i, c: 5 } })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
worksheet['!merges'] = merges
|
||||||
|
|
||||||
|
// Apply number formatting untuk currency cells
|
||||||
|
this.applyNumberFormatting(worksheet, totalRows, XLSX)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Apply number formatting for currency
|
||||||
|
*/
|
||||||
|
private static applyNumberFormatting(worksheet: any, totalRows: number, XLSX: any) {
|
||||||
|
// Apply currency formatting to amount columns
|
||||||
|
for (let row = 0; row < totalRows; row++) {
|
||||||
|
// Check columns that might contain currency values (columns 1, 4, 5)
|
||||||
|
;[1, 4, 5].forEach(col => {
|
||||||
|
const cellAddress = XLSX.utils.encode_cell({ r: row, c: col })
|
||||||
|
const cell = worksheet[cellAddress]
|
||||||
|
|
||||||
|
if (cell && typeof cell.v === 'number' && cell.v > 1000) {
|
||||||
|
// Apply Indonesian currency format for large numbers
|
||||||
|
cell.z = '#,##0'
|
||||||
|
cell.t = 'n'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply formatting to specific sections
|
||||||
|
this.applySectionFormatting(worksheet, totalRows, XLSX)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Apply specific formatting to sections
|
||||||
|
*/
|
||||||
|
private static applySectionFormatting(worksheet: any, totalRows: number, XLSX: any) {
|
||||||
|
// Find and format table headers and total rows
|
||||||
|
const headerKeywords = ['No', 'Metode Pembayaran', 'Nama', 'Kategori', 'Produk']
|
||||||
|
const totalKeywords = ['TOTAL', 'Subtotal']
|
||||||
|
|
||||||
|
for (let row = 0; row < totalRows; row++) {
|
||||||
|
const cell = worksheet[XLSX.utils.encode_cell({ r: row, c: 0 })]
|
||||||
|
|
||||||
|
if (cell) {
|
||||||
|
// Format table headers
|
||||||
|
if (headerKeywords.some(keyword => cell.v === keyword)) {
|
||||||
|
for (let col = 0; col < 6; col++) {
|
||||||
|
const headerCellAddress = XLSX.utils.encode_cell({ r: row, c: col })
|
||||||
|
const headerCell = worksheet[headerCellAddress]
|
||||||
|
if (headerCell) {
|
||||||
|
headerCell.s = {
|
||||||
|
font: { bold: true },
|
||||||
|
fill: { fgColor: { rgb: 'F3F4F6' } },
|
||||||
|
border: {
|
||||||
|
bottom: { style: 'medium', color: { rgb: '000000' } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Format total rows
|
||||||
|
if (totalKeywords.some(keyword => cell.v?.toString().startsWith(keyword))) {
|
||||||
|
for (let col = 0; col < 6; col++) {
|
||||||
|
const totalCellAddress = XLSX.utils.encode_cell({ r: row, c: col })
|
||||||
|
const totalCell = worksheet[totalCellAddress]
|
||||||
|
if (totalCell) {
|
||||||
|
totalCell.s = {
|
||||||
|
font: { bold: true },
|
||||||
|
border: {
|
||||||
|
top: { style: 'medium', color: { rgb: '000000' } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Format section headers
|
||||||
|
const sectionHeaders = [
|
||||||
|
'RINGKASAN PERIODE',
|
||||||
|
'INVOICE',
|
||||||
|
'RINGKASAN METODE PEMBAYARAN',
|
||||||
|
'RINGKASAN KATEGORI',
|
||||||
|
'RINGKASAN ITEM'
|
||||||
|
]
|
||||||
|
if (sectionHeaders.includes(cell.v)) {
|
||||||
|
cell.s = {
|
||||||
|
font: { bold: true, color: { rgb: '662D91' } },
|
||||||
|
fill: { fgColor: { rgb: 'F8F9FA' } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate filename with timestamp
|
||||||
|
*/
|
||||||
|
private static generateFilename(prefix: string): string {
|
||||||
|
const now = new Date()
|
||||||
|
const year = now.getFullYear()
|
||||||
|
const month = (now.getMonth() + 1).toString().padStart(2, '0')
|
||||||
|
const day = now.getDate().toString().padStart(2, '0')
|
||||||
|
const hour = now.getHours().toString().padStart(2, '0')
|
||||||
|
const minute = now.getMinutes().toString().padStart(2, '0')
|
||||||
|
|
||||||
|
return `${prefix}_${year}_${month}_${day}_${hour}${minute}.xlsx`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Export custom sales data to Excel with configuration
|
||||||
|
*/
|
||||||
|
static async exportCustomSalesData(
|
||||||
|
salesData: SalesReportData,
|
||||||
|
options?: {
|
||||||
|
includeSections?: {
|
||||||
|
ringkasan?: boolean
|
||||||
|
invoice?: boolean
|
||||||
|
paymentMethods?: boolean
|
||||||
|
categories?: boolean
|
||||||
|
products?: boolean
|
||||||
|
}
|
||||||
|
customFilename?: string
|
||||||
|
sheetName?: string
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const XLSX = await import('xlsx')
|
||||||
|
const worksheetData: any[][] = []
|
||||||
|
|
||||||
|
// Always include title and period
|
||||||
|
worksheetData.push(['LAPORAN TRANSAKSI'])
|
||||||
|
worksheetData.push([
|
||||||
|
`Periode: ${salesData.profitLoss.date_from.split('T')[0]} - ${salesData.profitLoss.date_to.split('T')[0]}`
|
||||||
|
])
|
||||||
|
worksheetData.push([])
|
||||||
|
|
||||||
|
const sections = options?.includeSections || {
|
||||||
|
ringkasan: true,
|
||||||
|
invoice: true,
|
||||||
|
paymentMethods: true,
|
||||||
|
categories: true,
|
||||||
|
products: true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Conditionally add sections based on options
|
||||||
|
if (sections.ringkasan) {
|
||||||
|
worksheetData.push(['RINGKASAN PERIODE'])
|
||||||
|
worksheetData.push([])
|
||||||
|
// Add ringkasan data...
|
||||||
|
const ringkasanData = [
|
||||||
|
['Total Penjualan:', `Rp ${salesData.profitLoss.summary.total_revenue.toLocaleString('id-ID')}`],
|
||||||
|
['Total Diskon:', `Rp ${salesData.profitLoss.summary.total_discount.toLocaleString('id-ID')}`],
|
||||||
|
['Total Pajak:', `Rp ${salesData.profitLoss.summary.total_tax.toLocaleString('id-ID')}`],
|
||||||
|
['Total:', `Rp ${salesData.profitLoss.summary.total_revenue.toLocaleString('id-ID')}`]
|
||||||
|
]
|
||||||
|
ringkasanData.forEach(row => worksheetData.push([row[0], row[1]]))
|
||||||
|
worksheetData.push([])
|
||||||
|
worksheetData.push([])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add other sections similarly based on options...
|
||||||
|
|
||||||
|
const workbook = XLSX.utils.book_new()
|
||||||
|
const worksheet = XLSX.utils.aoa_to_sheet(worksheetData)
|
||||||
|
|
||||||
|
this.applyBasicFormatting(worksheet, worksheetData.length, XLSX)
|
||||||
|
|
||||||
|
const sheetName = options?.sheetName || 'Laporan Transaksi'
|
||||||
|
XLSX.utils.book_append_sheet(workbook, worksheet, sheetName)
|
||||||
|
|
||||||
|
const exportFilename = options?.customFilename || this.generateFilename('Custom_Sales_Report')
|
||||||
|
XLSX.writeFile(workbook, exportFilename)
|
||||||
|
|
||||||
|
return { success: true, filename: exportFilename }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting custom sales report to Excel:', error)
|
||||||
|
return { success: false, error: 'Failed to export Excel file' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,364 @@
|
|||||||
|
// services/pdfExportPaymentService.ts
|
||||||
|
import { PaymentReport } from '@/types/services/analytic'
|
||||||
|
|
||||||
|
export class PDFExportPaymentService {
|
||||||
|
/**
|
||||||
|
* Export Payment Method Report to PDF
|
||||||
|
*/
|
||||||
|
static async exportPaymentMethodToPDF(paymentData: PaymentReport, filename?: string) {
|
||||||
|
try {
|
||||||
|
// Dynamic import untuk jsPDF
|
||||||
|
const jsPDFModule = await import('jspdf')
|
||||||
|
const jsPDF = jsPDFModule.default
|
||||||
|
|
||||||
|
// Create new PDF document - PORTRAIT A4
|
||||||
|
const pdf = new jsPDF('p', 'mm', 'a4')
|
||||||
|
|
||||||
|
// Add content
|
||||||
|
await this.addPaymentReportContent(pdf, paymentData)
|
||||||
|
|
||||||
|
// Generate filename
|
||||||
|
const exportFilename = filename || this.generateFilename('Laporan_Metode_Pembayaran', 'pdf')
|
||||||
|
|
||||||
|
// Save PDF
|
||||||
|
pdf.save(exportFilename)
|
||||||
|
|
||||||
|
return { success: true, filename: exportFilename }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting payment report to PDF:', error)
|
||||||
|
return { success: false, error: `PDF export failed: ${(error as Error).message}` }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add payment report content to PDF
|
||||||
|
*/
|
||||||
|
private static async addPaymentReportContent(pdf: any, paymentData: PaymentReport) {
|
||||||
|
let yPos = 20
|
||||||
|
const pageWidth = pdf.internal.pageSize.getWidth()
|
||||||
|
const pageHeight = pdf.internal.pageSize.getHeight()
|
||||||
|
const marginLeft = 20
|
||||||
|
const marginRight = 20
|
||||||
|
const marginBottom = 15
|
||||||
|
|
||||||
|
// Helper function to check page break
|
||||||
|
const checkPageBreak = (neededSpace: number) => {
|
||||||
|
if (yPos + neededSpace > pageHeight - marginBottom) {
|
||||||
|
pdf.addPage()
|
||||||
|
yPos = 20
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Title
|
||||||
|
yPos = this.addReportTitle(pdf, paymentData, yPos, pageWidth, marginLeft, marginRight)
|
||||||
|
|
||||||
|
// Section 1: Ringkasan
|
||||||
|
checkPageBreak(50)
|
||||||
|
yPos = this.addRingkasanSection(pdf, paymentData, yPos, pageWidth, marginLeft, marginRight, checkPageBreak)
|
||||||
|
|
||||||
|
// Section 2: Payment Methods Detail
|
||||||
|
checkPageBreak(80)
|
||||||
|
yPos = this.addPaymentMethodsSection(pdf, paymentData, yPos, pageWidth, marginLeft, marginRight, checkPageBreak)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add report title
|
||||||
|
*/
|
||||||
|
private static addReportTitle(
|
||||||
|
pdf: any,
|
||||||
|
paymentData: PaymentReport,
|
||||||
|
startY: number,
|
||||||
|
pageWidth: number,
|
||||||
|
marginLeft: number,
|
||||||
|
marginRight: number
|
||||||
|
): number {
|
||||||
|
let yPos = startY
|
||||||
|
|
||||||
|
// Title
|
||||||
|
pdf.setFontSize(20)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
pdf.text('Laporan Metode Pembayaran', pageWidth / 2, yPos, { align: 'center' })
|
||||||
|
yPos += 10
|
||||||
|
|
||||||
|
// Period
|
||||||
|
pdf.setFontSize(12)
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
const periodText = `${paymentData.date_from.split('T')[0]} - ${paymentData.date_to.split('T')[0]}`
|
||||||
|
pdf.text(periodText, pageWidth / 2, yPos, { align: 'center' })
|
||||||
|
yPos += 10
|
||||||
|
|
||||||
|
// Purple line separator
|
||||||
|
pdf.setDrawColor(102, 45, 145)
|
||||||
|
pdf.setLineWidth(2)
|
||||||
|
pdf.line(marginLeft, yPos, pageWidth - marginRight, yPos)
|
||||||
|
yPos += 15
|
||||||
|
|
||||||
|
return yPos
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add Ringkasan section - SAMA SEPERTI SALES REPORT STYLE
|
||||||
|
*/
|
||||||
|
private static addRingkasanSection(
|
||||||
|
pdf: any,
|
||||||
|
paymentData: PaymentReport,
|
||||||
|
startY: number,
|
||||||
|
pageWidth: number,
|
||||||
|
marginLeft: number,
|
||||||
|
marginRight: number,
|
||||||
|
checkPageBreak: (space: number) => boolean
|
||||||
|
): number {
|
||||||
|
let yPos = startY
|
||||||
|
|
||||||
|
// Section title - SAMA SEPERTI SALES REPORT
|
||||||
|
pdf.setFontSize(14)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(102, 45, 145)
|
||||||
|
pdf.text('Ringkasan', marginLeft, yPos)
|
||||||
|
yPos += 12
|
||||||
|
|
||||||
|
// Reset text color
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
pdf.setFontSize(11)
|
||||||
|
|
||||||
|
const ringkasanItems = [
|
||||||
|
{ label: 'Total Amount', value: this.formatCurrency(paymentData.summary.total_amount), bold: false },
|
||||||
|
{ label: 'Total Orders', value: paymentData.summary.total_orders.toString(), bold: false },
|
||||||
|
{ label: 'Total Payments', value: paymentData.summary.total_payments.toString(), bold: false },
|
||||||
|
{ label: 'Average Order Value', value: this.formatCurrency(paymentData.summary.average_order_value), bold: true }
|
||||||
|
]
|
||||||
|
|
||||||
|
ringkasanItems.forEach((item, index) => {
|
||||||
|
if (checkPageBreak(15)) yPos = 20
|
||||||
|
|
||||||
|
// Set font weight
|
||||||
|
pdf.setFont('helvetica', item.bold ? 'bold' : 'normal')
|
||||||
|
|
||||||
|
pdf.text(item.label, marginLeft, yPos)
|
||||||
|
pdf.text(item.value, pageWidth - marginRight, yPos, { align: 'right' })
|
||||||
|
|
||||||
|
// Light separator line (except for last row)
|
||||||
|
if (!item.bold) {
|
||||||
|
pdf.setDrawColor(230, 230, 230)
|
||||||
|
pdf.setLineWidth(0.5)
|
||||||
|
pdf.line(marginLeft, yPos + 2, pageWidth - marginRight, yPos + 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
yPos += 8
|
||||||
|
})
|
||||||
|
|
||||||
|
return yPos + 20
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add Payment Methods section - ORIGINAL STYLE DARI SALES REPORT
|
||||||
|
*/
|
||||||
|
private static addPaymentMethodsSection(
|
||||||
|
pdf: any,
|
||||||
|
paymentData: PaymentReport,
|
||||||
|
startY: number,
|
||||||
|
pageWidth: number,
|
||||||
|
marginLeft: number,
|
||||||
|
marginRight: number,
|
||||||
|
checkPageBreak: (space: number) => boolean
|
||||||
|
): number {
|
||||||
|
let yPos = startY
|
||||||
|
|
||||||
|
// Section title
|
||||||
|
pdf.setFontSize(14)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(102, 45, 145)
|
||||||
|
pdf.text('Rincian Metode Pembayaran', marginLeft, yPos)
|
||||||
|
yPos += 12
|
||||||
|
|
||||||
|
// Reset formatting
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
|
||||||
|
// Table setup
|
||||||
|
const tableWidth = pageWidth - marginLeft - marginRight
|
||||||
|
const colWidths = [50, 25, 30, 35, 25] // Method, Type, Order, Amount, %
|
||||||
|
let currentX = marginLeft
|
||||||
|
|
||||||
|
// Table header
|
||||||
|
pdf.setFillColor(240, 240, 240)
|
||||||
|
pdf.rect(marginLeft, yPos, tableWidth, 10, 'F')
|
||||||
|
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
const headers = ['Metode Pembayaran', 'Tipe', 'Jumlah Order', 'Total Amount', 'Persentase']
|
||||||
|
currentX = marginLeft
|
||||||
|
|
||||||
|
headers.forEach((header, index) => {
|
||||||
|
if (index === 0) {
|
||||||
|
pdf.text(header, currentX + 2, yPos + 6)
|
||||||
|
} else {
|
||||||
|
pdf.text(header, currentX + colWidths[index] / 2, yPos + 6, { align: 'center' })
|
||||||
|
}
|
||||||
|
currentX += colWidths[index]
|
||||||
|
})
|
||||||
|
|
||||||
|
yPos += 12
|
||||||
|
|
||||||
|
// Table rows
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
paymentData.data?.forEach((payment, index) => {
|
||||||
|
if (checkPageBreak(10)) yPos = 20
|
||||||
|
|
||||||
|
currentX = marginLeft
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
|
||||||
|
// Method name
|
||||||
|
pdf.text(payment.payment_method_name, currentX + 2, yPos + 5)
|
||||||
|
currentX += colWidths[0]
|
||||||
|
|
||||||
|
// Type with simple color coding
|
||||||
|
const typeText = payment.payment_method_type.toUpperCase()
|
||||||
|
if (payment.payment_method_type === 'cash') {
|
||||||
|
pdf.setTextColor(0, 120, 0) // Green
|
||||||
|
} else if (payment.payment_method_type === 'card') {
|
||||||
|
pdf.setTextColor(0, 80, 200) // Blue
|
||||||
|
} else {
|
||||||
|
pdf.setTextColor(200, 100, 0) // Orange
|
||||||
|
}
|
||||||
|
pdf.text(typeText, currentX + colWidths[1] / 2, yPos + 5, { align: 'center' })
|
||||||
|
pdf.setTextColor(0, 0, 0) // Reset color
|
||||||
|
currentX += colWidths[1]
|
||||||
|
|
||||||
|
// Order count
|
||||||
|
pdf.text(payment.order_count.toString(), currentX + colWidths[2] / 2, yPos + 5, { align: 'center' })
|
||||||
|
currentX += colWidths[2]
|
||||||
|
|
||||||
|
// Amount
|
||||||
|
pdf.text(this.formatCurrency(payment.total_amount), currentX + colWidths[3] - 2, yPos + 5, { align: 'right' })
|
||||||
|
currentX += colWidths[3]
|
||||||
|
|
||||||
|
// Percentage
|
||||||
|
pdf.text(`${(payment.percentage ?? 0).toFixed(1)}%`, currentX + colWidths[4] / 2, yPos + 5, { align: 'center' })
|
||||||
|
|
||||||
|
// Draw bottom border line
|
||||||
|
pdf.setDrawColor(230, 230, 230)
|
||||||
|
pdf.setLineWidth(0.3)
|
||||||
|
pdf.line(marginLeft, yPos + 8, marginLeft + tableWidth, yPos + 8)
|
||||||
|
|
||||||
|
yPos += 10
|
||||||
|
})
|
||||||
|
|
||||||
|
// Table footer (Total) - directly after last row
|
||||||
|
pdf.setFillColor(245, 245, 245) // Lighter gray
|
||||||
|
pdf.rect(marginLeft, yPos, tableWidth, 10, 'F')
|
||||||
|
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
currentX = marginLeft
|
||||||
|
pdf.text('TOTAL', currentX + 2, yPos + 6)
|
||||||
|
currentX += colWidths[0] + colWidths[1]
|
||||||
|
|
||||||
|
pdf.text((paymentData.summary?.total_orders ?? 0).toString(), currentX + colWidths[2] / 2, yPos + 6, {
|
||||||
|
align: 'center'
|
||||||
|
})
|
||||||
|
currentX += colWidths[2]
|
||||||
|
|
||||||
|
pdf.text(this.formatCurrency(paymentData.summary?.total_amount ?? 0), currentX + colWidths[3] - 2, yPos + 6, {
|
||||||
|
align: 'right'
|
||||||
|
})
|
||||||
|
|
||||||
|
currentX += colWidths[3]
|
||||||
|
pdf.text('100.0%', currentX + colWidths[4] / 2, yPos + 6, { align: 'center' })
|
||||||
|
|
||||||
|
return yPos + 20
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format currency for display
|
||||||
|
*/
|
||||||
|
private static formatCurrency(amount: number): string {
|
||||||
|
return `Rp ${amount.toLocaleString('id-ID')}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate filename with timestamp
|
||||||
|
*/
|
||||||
|
private static generateFilename(prefix: string, extension: string): string {
|
||||||
|
const now = new Date()
|
||||||
|
const year = now.getFullYear()
|
||||||
|
const month = (now.getMonth() + 1).toString().padStart(2, '0')
|
||||||
|
const day = now.getDate().toString().padStart(2, '0')
|
||||||
|
const hour = now.getHours().toString().padStart(2, '0')
|
||||||
|
const minute = now.getMinutes().toString().padStart(2, '0')
|
||||||
|
|
||||||
|
return `${prefix}_${year}_${month}_${day}_${hour}${minute}.${extension}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Export Payment Method data with custom configuration
|
||||||
|
*/
|
||||||
|
static async exportCustomPaymentToPDF(
|
||||||
|
paymentData: PaymentReport,
|
||||||
|
options?: {
|
||||||
|
title?: string
|
||||||
|
includeSummary?: boolean
|
||||||
|
customFilename?: string
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const jsPDFModule = await import('jspdf')
|
||||||
|
const jsPDF = jsPDFModule.default
|
||||||
|
|
||||||
|
const pdf = new jsPDF('p', 'mm', 'a4')
|
||||||
|
|
||||||
|
let yPos = 20
|
||||||
|
const pageWidth = pdf.internal.pageSize.getWidth()
|
||||||
|
const pageHeight = pdf.internal.pageSize.getHeight()
|
||||||
|
const marginLeft = 20
|
||||||
|
const marginRight = 20
|
||||||
|
const marginBottom = 15
|
||||||
|
|
||||||
|
const checkPageBreak = (neededSpace: number) => {
|
||||||
|
if (yPos + neededSpace > pageHeight - marginBottom) {
|
||||||
|
pdf.addPage()
|
||||||
|
yPos = 20
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Custom title if provided
|
||||||
|
if (options?.title) {
|
||||||
|
pdf.setFontSize(20)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
pdf.text(options.title, pageWidth / 2, yPos, { align: 'center' })
|
||||||
|
yPos += 15
|
||||||
|
} else {
|
||||||
|
yPos = this.addReportTitle(pdf, paymentData, yPos, pageWidth, marginLeft, marginRight)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Optional summary section
|
||||||
|
if (options?.includeSummary !== false) {
|
||||||
|
checkPageBreak(50)
|
||||||
|
yPos = this.addRingkasanSection(pdf, paymentData, yPos, pageWidth, marginLeft, marginRight, checkPageBreak)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Payment methods detail
|
||||||
|
checkPageBreak(80)
|
||||||
|
yPos = this.addPaymentMethodsSection(pdf, paymentData, yPos, pageWidth, marginLeft, marginRight, checkPageBreak)
|
||||||
|
|
||||||
|
const exportFilename = options?.customFilename || this.generateFilename('Custom_Payment_Report', 'pdf')
|
||||||
|
pdf.save(exportFilename)
|
||||||
|
|
||||||
|
return { success: true, filename: exportFilename }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting custom payment report to PDF:', error)
|
||||||
|
return { success: false, error: `PDF export failed: ${(error as Error).message}` }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,577 @@
|
|||||||
|
// services/pdfExportService.ts
|
||||||
|
import type { ProfitLossReport } from '@/types/services/analytic'
|
||||||
|
|
||||||
|
export class PDFExportProfitLossService {
|
||||||
|
/**
|
||||||
|
* Export Profit Loss Report to PDF (Simple approach)
|
||||||
|
*/
|
||||||
|
static async exportProfitLossToPDF(profitData: ProfitLossReport, filename?: string) {
|
||||||
|
try {
|
||||||
|
// Dynamic import untuk jsPDF
|
||||||
|
const jsPDFModule = await import('jspdf')
|
||||||
|
const jsPDF = jsPDFModule.default
|
||||||
|
|
||||||
|
// Create new PDF document - PORTRAIT A4
|
||||||
|
const pdf = new jsPDF('p', 'mm', 'a4') // portrait
|
||||||
|
|
||||||
|
// Add content
|
||||||
|
this.addBasicContent(pdf, profitData)
|
||||||
|
|
||||||
|
// Generate filename
|
||||||
|
const exportFilename = filename || this.generateFilename('Laba_Rugi', 'pdf')
|
||||||
|
|
||||||
|
// Save PDF
|
||||||
|
pdf.save(exportFilename)
|
||||||
|
|
||||||
|
return { success: true, filename: exportFilename }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting to PDF:', error)
|
||||||
|
return { success: false, error: `PDF export failed: ${(error as Error).message}` }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add basic content to PDF with proper page management
|
||||||
|
*/
|
||||||
|
private static addBasicContent(pdf: any, profitData: ProfitLossReport) {
|
||||||
|
let yPos = 20 // Reduced from 30
|
||||||
|
const pageWidth = pdf.internal.pageSize.getWidth()
|
||||||
|
const pageHeight = pdf.internal.pageSize.getHeight()
|
||||||
|
const marginBottom = 15 // Reduced from 20
|
||||||
|
|
||||||
|
// Title - Center aligned
|
||||||
|
pdf.setFontSize(18) // Reduced from 20
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.text('Laporan Laba Rugi', pageWidth / 2, yPos, { align: 'center' })
|
||||||
|
yPos += 10 // Reduced from 15
|
||||||
|
|
||||||
|
// Period - Center aligned
|
||||||
|
pdf.setFontSize(11) // Reduced from 12
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
const periodText = `${profitData.date_from.split('T')[0]} - ${profitData.date_to.split('T')[0]}`
|
||||||
|
pdf.text(periodText, pageWidth / 2, yPos, { align: 'center' })
|
||||||
|
yPos += 12 // Reduced from 20
|
||||||
|
|
||||||
|
// Purple line separator
|
||||||
|
pdf.setDrawColor(102, 45, 145) // Purple color
|
||||||
|
pdf.setLineWidth(1.5) // Reduced from 2
|
||||||
|
pdf.line(20, yPos, pageWidth - 20, yPos)
|
||||||
|
yPos += 15 // Reduced from 25
|
||||||
|
|
||||||
|
// Ringkasan section
|
||||||
|
pdf.setFontSize(14) // Reduced from 16
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(102, 45, 145) // Purple color
|
||||||
|
pdf.text('Ringkasan', 20, yPos)
|
||||||
|
yPos += 12 // Reduced from 20
|
||||||
|
|
||||||
|
// Reset text color to black
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
pdf.setFontSize(11) // Reduced from 12
|
||||||
|
|
||||||
|
// Summary items with consistent spacing
|
||||||
|
const summaryItems = [
|
||||||
|
{ label: 'Total Penjualan', value: this.formatCurrency(profitData.summary.total_revenue) },
|
||||||
|
{ label: 'Total Biaya', value: this.formatCurrency(profitData.summary.total_cost) },
|
||||||
|
{ label: 'Total Diskon', value: this.formatCurrency(profitData.summary.total_discount) },
|
||||||
|
{ label: 'Total Pajak', value: this.formatCurrency(profitData.summary.total_tax) },
|
||||||
|
{ label: 'Laba Kotor', value: this.formatCurrency(profitData.summary.gross_profit) },
|
||||||
|
{ label: 'Laba Bersih', value: this.formatCurrency(profitData.summary.net_profit) }
|
||||||
|
]
|
||||||
|
|
||||||
|
summaryItems.forEach((item, index) => {
|
||||||
|
// Add some spacing between items
|
||||||
|
if (index > 0) yPos += 8 // Reduced from 12
|
||||||
|
|
||||||
|
// Check if we need new page for summary items
|
||||||
|
if (yPos > pageHeight - marginBottom - 15) {
|
||||||
|
pdf.addPage()
|
||||||
|
yPos = 20 // Reduced from 30
|
||||||
|
}
|
||||||
|
|
||||||
|
// Label on left
|
||||||
|
pdf.text(item.label, 20, yPos)
|
||||||
|
|
||||||
|
// Value on right
|
||||||
|
pdf.text(item.value, pageWidth - 20, yPos, { align: 'right' })
|
||||||
|
|
||||||
|
// Light gray line separator
|
||||||
|
pdf.setDrawColor(230, 230, 230)
|
||||||
|
pdf.setLineWidth(0.3)
|
||||||
|
pdf.line(20, yPos + 3, pageWidth - 20, yPos + 3)
|
||||||
|
})
|
||||||
|
|
||||||
|
yPos += 20 // Reduced from 30
|
||||||
|
|
||||||
|
// Check if we need new page before daily breakdown
|
||||||
|
if (yPos > pageHeight - marginBottom - 40) {
|
||||||
|
pdf.addPage()
|
||||||
|
yPos = 20 // Reduced from 30
|
||||||
|
}
|
||||||
|
|
||||||
|
// Daily breakdown section
|
||||||
|
pdf.setFontSize(14) // Reduced from 16
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(102, 45, 145) // Purple color
|
||||||
|
pdf.text('Rincian Harian', 20, yPos)
|
||||||
|
yPos += 12 // Reduced from 20
|
||||||
|
|
||||||
|
// Reset text color
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
|
||||||
|
// Create simple daily breakdown with page management
|
||||||
|
profitData.data.forEach((daily, index) => {
|
||||||
|
// Estimate space needed for this daily section (approx 100mm)
|
||||||
|
const estimatedSpace = 100
|
||||||
|
|
||||||
|
// Check if we need new page before adding daily section
|
||||||
|
if (yPos + estimatedSpace > pageHeight - marginBottom) {
|
||||||
|
pdf.addPage()
|
||||||
|
yPos = 20 // Reduced from 30
|
||||||
|
}
|
||||||
|
|
||||||
|
yPos = this.addCleanDailySection(pdf, daily, yPos, pageWidth, pageHeight, marginBottom)
|
||||||
|
yPos += 10 // Reduced from 15 - Space between daily sections
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add clean daily section with page break management
|
||||||
|
*/
|
||||||
|
private static addCleanDailySection(
|
||||||
|
pdf: any,
|
||||||
|
dailyData: any,
|
||||||
|
startY: number,
|
||||||
|
pageWidth: number,
|
||||||
|
pageHeight: number,
|
||||||
|
marginBottom: number
|
||||||
|
) {
|
||||||
|
const date = new Date(dailyData.date).toLocaleDateString('id-ID', {
|
||||||
|
day: '2-digit',
|
||||||
|
month: 'long',
|
||||||
|
year: 'numeric'
|
||||||
|
})
|
||||||
|
|
||||||
|
let yPos = startY
|
||||||
|
|
||||||
|
// Check if we have enough space for the header
|
||||||
|
if (yPos > pageHeight - marginBottom - 20) {
|
||||||
|
pdf.addPage()
|
||||||
|
yPos = 20 // Reduced from 30
|
||||||
|
}
|
||||||
|
|
||||||
|
// Date header
|
||||||
|
pdf.setFontSize(12) // Reduced from 14
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.text(date, 20, yPos)
|
||||||
|
yPos += 10 // Reduced from 15
|
||||||
|
|
||||||
|
// Daily data items
|
||||||
|
pdf.setFontSize(10) // Reduced from 11
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
|
||||||
|
const dailyItems = [
|
||||||
|
{ label: 'Penjualan', value: this.formatCurrency(dailyData.revenue) },
|
||||||
|
{ label: 'HPP (Biaya Pokok)', value: this.formatCurrency(dailyData.cost) },
|
||||||
|
{ label: 'Laba Kotor', value: this.formatCurrency(dailyData.gross_profit) },
|
||||||
|
{ label: 'Pajak', value: this.formatCurrency(dailyData.tax) },
|
||||||
|
{ label: 'Diskon', value: this.formatCurrency(dailyData.discount) },
|
||||||
|
{ label: 'Jumlah Order', value: dailyData.orders.toString() + ' transaksi' },
|
||||||
|
{ label: 'Laba Bersih', value: this.formatCurrency(dailyData.net_profit), isTotal: true }
|
||||||
|
]
|
||||||
|
|
||||||
|
dailyItems.forEach((item, index) => {
|
||||||
|
if (index > 0) yPos += 7 // Reduced from 10
|
||||||
|
|
||||||
|
// Check if we need new page for each item
|
||||||
|
if (yPos > pageHeight - marginBottom - 15) {
|
||||||
|
pdf.addPage()
|
||||||
|
yPos = 20 // Reduced from 30
|
||||||
|
}
|
||||||
|
|
||||||
|
// Special styling for total (Laba Bersih)
|
||||||
|
if (item.isTotal) {
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
|
||||||
|
// Light background for total row - adjusted to center with text
|
||||||
|
pdf.setFillColor(248, 248, 248)
|
||||||
|
pdf.rect(20, yPos - 4, pageWidth - 40, 9, 'F') // Slightly bigger and better positioned
|
||||||
|
} else {
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
}
|
||||||
|
|
||||||
|
// Label on left - consistent with other rows
|
||||||
|
pdf.text(item.label, 25, yPos)
|
||||||
|
|
||||||
|
// Value on right - consistent with other rows
|
||||||
|
pdf.text(item.value, pageWidth - 25, yPos, { align: 'right' })
|
||||||
|
|
||||||
|
// Subtle line separator (except for last item)
|
||||||
|
if (index < dailyItems.length - 1) {
|
||||||
|
pdf.setDrawColor(245, 245, 245)
|
||||||
|
pdf.setLineWidth(0.2)
|
||||||
|
pdf.line(25, yPos + 1.5, pageWidth - 25, yPos + 1.5) // Reduced from yPos + 2
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return yPos + 6 // Reduced from 8
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format currency for display
|
||||||
|
*/
|
||||||
|
private static formatCurrency(amount: number): string {
|
||||||
|
return `Rp ${amount.toLocaleString('id-ID')}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate filename with timestamp
|
||||||
|
*/
|
||||||
|
private static generateFilename(prefix: string, extension: string): string {
|
||||||
|
const now = new Date()
|
||||||
|
const year = now.getFullYear()
|
||||||
|
const month = (now.getMonth() + 1).toString().padStart(2, '0')
|
||||||
|
const day = now.getDate().toString().padStart(2, '0')
|
||||||
|
const hour = now.getHours().toString().padStart(2, '0')
|
||||||
|
const minute = now.getMinutes().toString().padStart(2, '0')
|
||||||
|
|
||||||
|
return `${prefix}_${year}_${month}_${day}_${hour}${minute}.${extension}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Alternative: More precise page break management
|
||||||
|
*/
|
||||||
|
static async exportWithBetterPageBreaks(profitData: ProfitLossReport, filename?: string) {
|
||||||
|
try {
|
||||||
|
const jsPDFModule = await import('jspdf')
|
||||||
|
const jsPDF = jsPDFModule.default
|
||||||
|
const pdf = new jsPDF('p', 'mm', 'a4')
|
||||||
|
|
||||||
|
// Use more precise measurements
|
||||||
|
const pageHeight = pdf.internal.pageSize.getHeight() // ~297mm for A4
|
||||||
|
const safeHeight = pageHeight - 30 // Keep 30mm margin from bottom
|
||||||
|
|
||||||
|
let currentY = 30
|
||||||
|
|
||||||
|
// Helper function to check and add new page
|
||||||
|
const checkPageBreak = (neededSpace: number) => {
|
||||||
|
if (currentY + neededSpace > safeHeight) {
|
||||||
|
pdf.addPage()
|
||||||
|
currentY = 30
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add title and header
|
||||||
|
currentY = this.addTitleSection(pdf, profitData, currentY)
|
||||||
|
|
||||||
|
// Add summary with page break check
|
||||||
|
checkPageBreak(80) // Estimate 80mm needed for summary
|
||||||
|
currentY = this.addSummarySection(pdf, profitData, currentY, checkPageBreak)
|
||||||
|
|
||||||
|
// Add daily breakdown
|
||||||
|
checkPageBreak(40) // Space for section header
|
||||||
|
currentY = this.addDailyBreakdownSection(pdf, profitData, currentY, checkPageBreak)
|
||||||
|
|
||||||
|
const exportFilename = filename || this.generateFilename('Laba_Rugi', 'pdf')
|
||||||
|
pdf.save(exportFilename)
|
||||||
|
|
||||||
|
return { success: true, filename: exportFilename }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting to PDF:', error)
|
||||||
|
return { success: false, error: `PDF export failed: ${(error as Error).message}` }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add title section
|
||||||
|
*/
|
||||||
|
private static addTitleSection(pdf: any, profitData: ProfitLossReport, startY: number): number {
|
||||||
|
let yPos = startY
|
||||||
|
const pageWidth = pdf.internal.pageSize.getWidth()
|
||||||
|
|
||||||
|
// Title
|
||||||
|
pdf.setFontSize(20)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.text('Laporan Laba Rugi', pageWidth / 2, yPos, { align: 'center' })
|
||||||
|
yPos += 15
|
||||||
|
|
||||||
|
// Period
|
||||||
|
pdf.setFontSize(12)
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
const periodText = `${profitData.date_from.split('T')[0]} - ${profitData.date_to.split('T')[0]}`
|
||||||
|
pdf.text(periodText, pageWidth / 2, yPos, { align: 'center' })
|
||||||
|
yPos += 20
|
||||||
|
|
||||||
|
// Separator line
|
||||||
|
pdf.setDrawColor(102, 45, 145)
|
||||||
|
pdf.setLineWidth(2)
|
||||||
|
pdf.line(20, yPos, pageWidth - 20, yPos)
|
||||||
|
yPos += 25
|
||||||
|
|
||||||
|
return yPos
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add summary section with page break callback
|
||||||
|
*/
|
||||||
|
private static addSummarySection(
|
||||||
|
pdf: any,
|
||||||
|
profitData: ProfitLossReport,
|
||||||
|
startY: number,
|
||||||
|
checkPageBreak: (space: number) => boolean
|
||||||
|
): number {
|
||||||
|
let yPos = startY
|
||||||
|
const pageWidth = pdf.internal.pageSize.getWidth()
|
||||||
|
|
||||||
|
// Section title
|
||||||
|
pdf.setFontSize(16)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(102, 45, 145)
|
||||||
|
pdf.text('Ringkasan', 20, yPos)
|
||||||
|
yPos += 20
|
||||||
|
|
||||||
|
// Reset formatting
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
pdf.setFontSize(12)
|
||||||
|
|
||||||
|
const summaryItems = [
|
||||||
|
{ label: 'Total Penjualan', value: this.formatCurrency(profitData.summary.total_revenue) },
|
||||||
|
{ label: 'Total Biaya', value: this.formatCurrency(profitData.summary.total_cost) },
|
||||||
|
{ label: 'Total Diskon', value: this.formatCurrency(profitData.summary.total_discount) },
|
||||||
|
{ label: 'Total Pajak', value: this.formatCurrency(profitData.summary.total_tax) },
|
||||||
|
{ label: 'Laba Kotor', value: this.formatCurrency(profitData.summary.gross_profit) },
|
||||||
|
{ label: 'Laba Bersih', value: this.formatCurrency(profitData.summary.net_profit) }
|
||||||
|
]
|
||||||
|
|
||||||
|
summaryItems.forEach((item, index) => {
|
||||||
|
if (index > 0) yPos += 12
|
||||||
|
|
||||||
|
// Check page break for each item
|
||||||
|
if (checkPageBreak(15)) {
|
||||||
|
yPos = 30
|
||||||
|
}
|
||||||
|
|
||||||
|
pdf.text(item.label, 20, yPos)
|
||||||
|
pdf.text(item.value, pageWidth - 20, yPos, { align: 'right' })
|
||||||
|
|
||||||
|
// Separator line
|
||||||
|
pdf.setDrawColor(230, 230, 230)
|
||||||
|
pdf.setLineWidth(0.3)
|
||||||
|
pdf.line(20, yPos + 3, pageWidth - 20, yPos + 3)
|
||||||
|
})
|
||||||
|
|
||||||
|
return yPos + 30
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add daily breakdown section with page break management
|
||||||
|
*/
|
||||||
|
private static addDailyBreakdownSection(
|
||||||
|
pdf: any,
|
||||||
|
profitData: ProfitLossReport,
|
||||||
|
startY: number,
|
||||||
|
checkPageBreak: (space: number) => boolean
|
||||||
|
): number {
|
||||||
|
let yPos = startY
|
||||||
|
|
||||||
|
// Section title
|
||||||
|
pdf.setFontSize(16)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(102, 45, 145)
|
||||||
|
pdf.text('Rincian Harian', 20, yPos)
|
||||||
|
yPos += 20
|
||||||
|
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
|
||||||
|
profitData.data.forEach((daily, index) => {
|
||||||
|
// Check if we need space for this daily section (estimate ~90mm)
|
||||||
|
if (checkPageBreak(90)) {
|
||||||
|
yPos = 30
|
||||||
|
}
|
||||||
|
|
||||||
|
yPos = this.addSingleDayData(pdf, daily, yPos)
|
||||||
|
yPos += 15
|
||||||
|
})
|
||||||
|
|
||||||
|
return yPos
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add single day data
|
||||||
|
*/
|
||||||
|
private static addSingleDayData(pdf: any, dailyData: any, startY: number): number {
|
||||||
|
const pageWidth = pdf.internal.pageSize.getWidth()
|
||||||
|
let yPos = startY
|
||||||
|
|
||||||
|
const date = new Date(dailyData.date).toLocaleDateString('id-ID', {
|
||||||
|
day: '2-digit',
|
||||||
|
month: 'long',
|
||||||
|
year: 'numeric'
|
||||||
|
})
|
||||||
|
|
||||||
|
// Date header
|
||||||
|
pdf.setFontSize(14)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.text(date, 20, yPos)
|
||||||
|
yPos += 15
|
||||||
|
|
||||||
|
// Daily items
|
||||||
|
pdf.setFontSize(11)
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
|
||||||
|
const items = [
|
||||||
|
{ label: 'Penjualan', value: this.formatCurrency(dailyData.revenue) },
|
||||||
|
{ label: 'HPP (Biaya Pokok)', value: this.formatCurrency(dailyData.cost) },
|
||||||
|
{ label: 'Laba Kotor', value: this.formatCurrency(dailyData.gross_profit) },
|
||||||
|
{ label: 'Pajak', value: this.formatCurrency(dailyData.tax) },
|
||||||
|
{ label: 'Diskon', value: this.formatCurrency(dailyData.discount) },
|
||||||
|
{ label: 'Jumlah Order', value: dailyData.orders.toString() + ' transaksi' },
|
||||||
|
{ label: 'Laba Bersih', value: this.formatCurrency(dailyData.net_profit), isTotal: true }
|
||||||
|
]
|
||||||
|
|
||||||
|
items.forEach((item, index) => {
|
||||||
|
if (index > 0) yPos += 10
|
||||||
|
|
||||||
|
if (item.isTotal) {
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setFillColor(248, 248, 248)
|
||||||
|
pdf.rect(20, yPos - 4, pageWidth - 40, 10, 'F')
|
||||||
|
} else {
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
}
|
||||||
|
|
||||||
|
pdf.text(item.label, 25, yPos)
|
||||||
|
pdf.text(item.value, pageWidth - 25, yPos, { align: 'right' })
|
||||||
|
|
||||||
|
if (index < items.length - 1) {
|
||||||
|
pdf.setDrawColor(245, 245, 245)
|
||||||
|
pdf.setLineWidth(0.2)
|
||||||
|
pdf.line(25, yPos + 2, pageWidth - 25, yPos + 2)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return yPos + 8
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Alternative HTML to PDF method (if needed)
|
||||||
|
*/
|
||||||
|
static async exportToHTMLPDF(profitData: ProfitLossReport, filename?: string) {
|
||||||
|
try {
|
||||||
|
const htmlContent = this.generateSimpleHTML(profitData)
|
||||||
|
|
||||||
|
// Create a temporary element and trigger print
|
||||||
|
const printWindow = window.open('', '_blank')
|
||||||
|
if (printWindow) {
|
||||||
|
printWindow.document.write(htmlContent)
|
||||||
|
printWindow.document.close()
|
||||||
|
printWindow.focus()
|
||||||
|
printWindow.print()
|
||||||
|
printWindow.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true, filename: filename || 'Laba_Rugi.pdf' }
|
||||||
|
} catch (error) {
|
||||||
|
return { success: false, error: `HTML PDF export failed: ${(error as Error).message}` }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate simple HTML for printing
|
||||||
|
*/
|
||||||
|
private static generateSimpleHTML(profitData: ProfitLossReport): string {
|
||||||
|
const dateColumns = profitData.data.map(daily => {
|
||||||
|
const date = new Date(daily.date)
|
||||||
|
return date.toLocaleDateString('id-ID', { day: '2-digit', month: 'short' })
|
||||||
|
})
|
||||||
|
|
||||||
|
return `
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Laporan Laba Rugi</title>
|
||||||
|
<style>
|
||||||
|
body { font-family: Arial, sans-serif; margin: 20px; }
|
||||||
|
h1 { color: #1f4e79; text-align: center; }
|
||||||
|
h2 { color: #333; border-bottom: 2px solid #ccc; }
|
||||||
|
.summary { margin-bottom: 30px; }
|
||||||
|
.summary-item { margin: 5px 0; padding: 5px; background: #f9f9f9; }
|
||||||
|
table { width: 100%; border-collapse: collapse; margin-top: 20px; }
|
||||||
|
th, td { border: 1px solid #ccc; padding: 8px; text-align: left; }
|
||||||
|
th { background-color: #d35400; color: white; text-align: center; }
|
||||||
|
.number { text-align: right; }
|
||||||
|
.center { text-align: center; }
|
||||||
|
@media print {
|
||||||
|
body { margin: 10px; }
|
||||||
|
.page-break { page-break-before: always; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>LAPORAN LABA RUGI</h1>
|
||||||
|
<p style="text-align: center;">
|
||||||
|
Periode: ${profitData.date_from.split('T')[0]} - ${profitData.date_to.split('T')[0]}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h2>RINGKASAN PERIODE</h2>
|
||||||
|
<div class="summary">
|
||||||
|
<div class="summary-item">Total Revenue: <strong>${this.formatCurrency(profitData.summary.total_revenue)}</strong></div>
|
||||||
|
<div class="summary-item">Total Cost: <strong>${this.formatCurrency(profitData.summary.total_cost)}</strong></div>
|
||||||
|
<div class="summary-item">Gross Profit: <strong>${this.formatCurrency(profitData.summary.gross_profit)}</strong></div>
|
||||||
|
<div class="summary-item">Net Profit: <strong>${this.formatCurrency(profitData.summary.net_profit)}</strong></div>
|
||||||
|
<div class="summary-item">Total Orders: <strong>${profitData.summary.total_orders}</strong></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="page-break"></div>
|
||||||
|
<h2>RINCIAN HARIAN</h2>
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>NO</th>
|
||||||
|
<th>KETERANGAN</th>
|
||||||
|
<th></th>
|
||||||
|
${dateColumns.map(date => `<th>${date}</th>`).join('')}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr>
|
||||||
|
<td class="center">1</td>
|
||||||
|
<td><strong>TOTAL PENJ</strong></td>
|
||||||
|
<td class="center">:</td>
|
||||||
|
${profitData.data.map(daily => `<td class="number">${this.formatCurrency(daily.revenue)}</td>`).join('')}
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td class="center">2</td>
|
||||||
|
<td><strong>HPP</strong></td>
|
||||||
|
<td class="center">:</td>
|
||||||
|
${profitData.data.map(daily => `<td class="number">${this.formatCurrency(daily.cost)}</td>`).join('')}
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td class="center">3</td>
|
||||||
|
<td><strong>Laba Kotor</strong></td>
|
||||||
|
<td class="center">:</td>
|
||||||
|
${profitData.data.map(daily => `<td class="number">${this.formatCurrency(daily.gross_profit)}</td>`).join('')}
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td class="center">4</td>
|
||||||
|
<td><strong>Biaya lain</strong></td>
|
||||||
|
<td class="center">:</td>
|
||||||
|
${profitData.data.map(daily => `<td class="number">${this.formatCurrency(daily.tax + daily.discount)}</td>`).join('')}
|
||||||
|
</tr>
|
||||||
|
<tr style="background-color: #154360; color: white; font-weight: bold;">
|
||||||
|
<td class="center">5</td>
|
||||||
|
<td>Laba/Rugi</td>
|
||||||
|
<td class="center">:</td>
|
||||||
|
${profitData.data.map(daily => `<td class="number">${this.formatCurrency(daily.net_profit)}</td>`).join('')}
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
`
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,529 @@
|
|||||||
|
// services/pdfExportSalesOrderService.ts
|
||||||
|
import { SalesReport } from '@/types/services/analytic'
|
||||||
|
|
||||||
|
export class PDFExportSalesOrderService {
|
||||||
|
/**
|
||||||
|
* Export Sales Order Report to PDF
|
||||||
|
*/
|
||||||
|
static async exportSalesOrderToPDF(salesData: SalesReport, filename?: string) {
|
||||||
|
try {
|
||||||
|
// Dynamic import untuk jsPDF
|
||||||
|
const jsPDFModule = await import('jspdf')
|
||||||
|
const jsPDF = jsPDFModule.default
|
||||||
|
|
||||||
|
// Create new PDF document - PORTRAIT A4
|
||||||
|
const pdf = new jsPDF('p', 'mm', 'a4')
|
||||||
|
|
||||||
|
// Add content
|
||||||
|
await this.addSalesOrderReportContent(pdf, salesData)
|
||||||
|
|
||||||
|
// Generate filename
|
||||||
|
const exportFilename = filename || this.generateFilename('Laporan_Pesanan_Penjualan', 'pdf')
|
||||||
|
|
||||||
|
// Save PDF
|
||||||
|
pdf.save(exportFilename)
|
||||||
|
|
||||||
|
return { success: true, filename: exportFilename }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting sales order report to PDF:', error)
|
||||||
|
return { success: false, error: `PDF export failed: ${(error as Error).message}` }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add sales order report content to PDF
|
||||||
|
*/
|
||||||
|
private static async addSalesOrderReportContent(pdf: any, salesData: SalesReport) {
|
||||||
|
let yPos = 20
|
||||||
|
const pageWidth = pdf.internal.pageSize.getWidth()
|
||||||
|
const pageHeight = pdf.internal.pageSize.getHeight()
|
||||||
|
const marginLeft = 20
|
||||||
|
const marginRight = 20
|
||||||
|
const marginBottom = 15
|
||||||
|
|
||||||
|
// Helper function to check page break
|
||||||
|
const checkPageBreak = (neededSpace: number) => {
|
||||||
|
if (yPos + neededSpace > pageHeight - marginBottom) {
|
||||||
|
pdf.addPage()
|
||||||
|
yPos = 20
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Title
|
||||||
|
yPos = this.addReportTitle(pdf, salesData, yPos, pageWidth, marginLeft, marginRight)
|
||||||
|
|
||||||
|
// Section 1: Ringkasan
|
||||||
|
checkPageBreak(60)
|
||||||
|
yPos = this.addRingkasanSection(pdf, salesData, yPos, pageWidth, marginLeft, marginRight, checkPageBreak)
|
||||||
|
|
||||||
|
// Section 2: Daily Sales Details
|
||||||
|
checkPageBreak(100)
|
||||||
|
yPos = this.addDailySalesSection(pdf, salesData, yPos, pageWidth, marginLeft, marginRight, checkPageBreak)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add report title
|
||||||
|
*/
|
||||||
|
private static addReportTitle(
|
||||||
|
pdf: any,
|
||||||
|
salesData: SalesReport,
|
||||||
|
startY: number,
|
||||||
|
pageWidth: number,
|
||||||
|
marginLeft: number,
|
||||||
|
marginRight: number
|
||||||
|
): number {
|
||||||
|
let yPos = startY
|
||||||
|
|
||||||
|
// Title
|
||||||
|
pdf.setFontSize(20)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
pdf.text('Laporan Pesanan Penjualan', pageWidth / 2, yPos, { align: 'center' })
|
||||||
|
yPos += 10
|
||||||
|
|
||||||
|
// Period
|
||||||
|
pdf.setFontSize(12)
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
const periodText = `${salesData.date_from.split('T')[0]} - ${salesData.date_to.split('T')[0]}`
|
||||||
|
pdf.text(periodText, pageWidth / 2, yPos, { align: 'center' })
|
||||||
|
yPos += 10
|
||||||
|
|
||||||
|
// Purple line separator
|
||||||
|
pdf.setDrawColor(102, 45, 145)
|
||||||
|
pdf.setLineWidth(2)
|
||||||
|
pdf.line(marginLeft, yPos, pageWidth - marginRight, yPos)
|
||||||
|
yPos += 15
|
||||||
|
|
||||||
|
return yPos
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add Ringkasan section
|
||||||
|
*/
|
||||||
|
private static addRingkasanSection(
|
||||||
|
pdf: any,
|
||||||
|
salesData: SalesReport,
|
||||||
|
startY: number,
|
||||||
|
pageWidth: number,
|
||||||
|
marginLeft: number,
|
||||||
|
marginRight: number,
|
||||||
|
checkPageBreak: (space: number) => boolean
|
||||||
|
): number {
|
||||||
|
let yPos = startY
|
||||||
|
|
||||||
|
// Section title
|
||||||
|
pdf.setFontSize(14)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(102, 45, 145)
|
||||||
|
pdf.text('Ringkasan', marginLeft, yPos)
|
||||||
|
yPos += 12
|
||||||
|
|
||||||
|
// Reset text color
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
pdf.setFontSize(11)
|
||||||
|
|
||||||
|
const ringkasanItems = [
|
||||||
|
{ label: 'Total Sales', value: this.formatCurrency(salesData.summary.total_sales), bold: false },
|
||||||
|
{ label: 'Total Orders', value: salesData.summary.total_orders.toString(), bold: false },
|
||||||
|
{ label: 'Total Items', value: salesData.summary.total_items.toString(), bold: false },
|
||||||
|
{ label: 'Average Order Value', value: this.formatCurrency(salesData.summary.average_order_value), bold: false },
|
||||||
|
{ label: 'Total Tax', value: this.formatCurrency(salesData.summary.total_tax), bold: false },
|
||||||
|
{ label: 'Total Discount', value: this.formatCurrency(salesData.summary.total_discount), bold: false },
|
||||||
|
{ label: 'Net Sales', value: this.formatCurrency(salesData.summary.net_sales), bold: true }
|
||||||
|
]
|
||||||
|
|
||||||
|
ringkasanItems.forEach((item, index) => {
|
||||||
|
if (checkPageBreak(15)) yPos = 20
|
||||||
|
|
||||||
|
// Set font weight
|
||||||
|
pdf.setFont('helvetica', item.bold ? 'bold' : 'normal')
|
||||||
|
|
||||||
|
pdf.text(item.label, marginLeft, yPos)
|
||||||
|
pdf.text(item.value, pageWidth - marginRight, yPos, { align: 'right' })
|
||||||
|
|
||||||
|
// Light separator line (except for bold row)
|
||||||
|
if (!item.bold) {
|
||||||
|
pdf.setDrawColor(230, 230, 230)
|
||||||
|
pdf.setLineWidth(0.5)
|
||||||
|
pdf.line(marginLeft, yPos + 2, pageWidth - marginRight, yPos + 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
yPos += 8
|
||||||
|
})
|
||||||
|
|
||||||
|
return yPos + 20
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add Daily Sales section
|
||||||
|
*/
|
||||||
|
private static addDailySalesSection(
|
||||||
|
pdf: any,
|
||||||
|
salesData: SalesReport,
|
||||||
|
startY: number,
|
||||||
|
pageWidth: number,
|
||||||
|
marginLeft: number,
|
||||||
|
marginRight: number,
|
||||||
|
checkPageBreak: (space: number) => boolean
|
||||||
|
): number {
|
||||||
|
let yPos = startY
|
||||||
|
|
||||||
|
// Section title
|
||||||
|
pdf.setFontSize(14)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(102, 45, 145)
|
||||||
|
pdf.text('Rincian Harian', marginLeft, yPos)
|
||||||
|
yPos += 12
|
||||||
|
|
||||||
|
// Reset formatting
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
|
||||||
|
// Table setup - adjust for 7 columns
|
||||||
|
const tableWidth = pageWidth - marginLeft - marginRight
|
||||||
|
const colWidths = [20, 20, 25, 15, 20, 20, 25] // Date, Sales, Orders, Items, Tax, Discount, Net Sales
|
||||||
|
let currentX = marginLeft
|
||||||
|
|
||||||
|
// Table header
|
||||||
|
pdf.setFillColor(240, 240, 240)
|
||||||
|
pdf.rect(marginLeft, yPos, tableWidth, 10, 'F')
|
||||||
|
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setFontSize(8) // Smaller font for more columns
|
||||||
|
|
||||||
|
const headers = ['Tanggal', 'Penjualan', 'Pesanan', 'Qty', 'Pajak', 'Diskon', 'Pendapatan']
|
||||||
|
currentX = marginLeft
|
||||||
|
|
||||||
|
headers.forEach((header, index) => {
|
||||||
|
if (index === 0) {
|
||||||
|
pdf.text(header, currentX + 2, yPos + 6)
|
||||||
|
} else {
|
||||||
|
pdf.text(header, currentX + colWidths[index] / 2, yPos + 6, { align: 'center' })
|
||||||
|
}
|
||||||
|
currentX += colWidths[index]
|
||||||
|
})
|
||||||
|
|
||||||
|
yPos += 12
|
||||||
|
|
||||||
|
// Table rows
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
pdf.setFontSize(8)
|
||||||
|
|
||||||
|
salesData.data?.forEach((dailySales, index) => {
|
||||||
|
if (checkPageBreak(10)) yPos = 20
|
||||||
|
|
||||||
|
currentX = marginLeft
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
pdf.setFontSize(8)
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
|
||||||
|
// Date
|
||||||
|
pdf.text(this.formatDate(dailySales.date), currentX + 2, yPos + 5)
|
||||||
|
currentX += colWidths[0]
|
||||||
|
|
||||||
|
// Sales
|
||||||
|
pdf.text(this.formatCurrencyShort(dailySales.sales), currentX + colWidths[1] - 2, yPos + 5, { align: 'right' })
|
||||||
|
currentX += colWidths[1]
|
||||||
|
|
||||||
|
// Orders
|
||||||
|
pdf.text(dailySales.orders.toString(), currentX + colWidths[2] / 2, yPos + 5, { align: 'center' })
|
||||||
|
currentX += colWidths[2]
|
||||||
|
|
||||||
|
// Items
|
||||||
|
pdf.text(dailySales.items.toString(), currentX + colWidths[3] / 2, yPos + 5, { align: 'center' })
|
||||||
|
currentX += colWidths[3]
|
||||||
|
|
||||||
|
// Tax
|
||||||
|
pdf.text(this.formatCurrencyShort(dailySales.tax), currentX + colWidths[4] - 2, yPos + 5, { align: 'right' })
|
||||||
|
currentX += colWidths[4]
|
||||||
|
|
||||||
|
// Discount
|
||||||
|
pdf.text(this.formatCurrencyShort(dailySales.discount), currentX + colWidths[5] - 2, yPos + 5, { align: 'right' })
|
||||||
|
currentX += colWidths[5]
|
||||||
|
|
||||||
|
// Net Sales
|
||||||
|
pdf.text(this.formatCurrencyShort(dailySales.net_sales), currentX + colWidths[6] - 2, yPos + 5, {
|
||||||
|
align: 'right'
|
||||||
|
})
|
||||||
|
|
||||||
|
// Draw bottom border line
|
||||||
|
pdf.setDrawColor(230, 230, 230)
|
||||||
|
pdf.setLineWidth(0.3)
|
||||||
|
pdf.line(marginLeft, yPos + 8, marginLeft + tableWidth, yPos + 8)
|
||||||
|
|
||||||
|
yPos += 10
|
||||||
|
})
|
||||||
|
|
||||||
|
// Table footer (Total)
|
||||||
|
pdf.setFillColor(245, 245, 245) // Lighter gray
|
||||||
|
pdf.rect(marginLeft, yPos, tableWidth, 10, 'F')
|
||||||
|
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setFontSize(8)
|
||||||
|
|
||||||
|
currentX = marginLeft
|
||||||
|
pdf.text('TOTAL', currentX + 2, yPos + 6)
|
||||||
|
currentX += colWidths[0]
|
||||||
|
|
||||||
|
pdf.text(this.formatCurrencyShort(salesData.summary.total_sales), currentX + colWidths[1] - 2, yPos + 6, {
|
||||||
|
align: 'right'
|
||||||
|
})
|
||||||
|
currentX += colWidths[1]
|
||||||
|
|
||||||
|
pdf.text(salesData.summary.total_orders.toString(), currentX + colWidths[2] / 2, yPos + 6, { align: 'center' })
|
||||||
|
currentX += colWidths[2]
|
||||||
|
|
||||||
|
pdf.text(salesData.summary.total_items.toString(), currentX + colWidths[3] / 2, yPos + 6, { align: 'center' })
|
||||||
|
currentX += colWidths[3]
|
||||||
|
|
||||||
|
pdf.text(this.formatCurrencyShort(salesData.summary.total_tax), currentX + colWidths[4] - 2, yPos + 6, {
|
||||||
|
align: 'right'
|
||||||
|
})
|
||||||
|
currentX += colWidths[4]
|
||||||
|
|
||||||
|
pdf.text(this.formatCurrencyShort(salesData.summary.total_discount), currentX + colWidths[5] - 2, yPos + 6, {
|
||||||
|
align: 'right'
|
||||||
|
})
|
||||||
|
currentX += colWidths[5]
|
||||||
|
|
||||||
|
pdf.text(this.formatCurrencyShort(salesData.summary.net_sales), currentX + colWidths[6] - 2, yPos + 6, {
|
||||||
|
align: 'right'
|
||||||
|
})
|
||||||
|
|
||||||
|
return yPos + 20
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format currency for display
|
||||||
|
*/
|
||||||
|
private static formatCurrency(amount: number): string {
|
||||||
|
return `Rp ${amount.toLocaleString('id-ID')}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format currency short for table display
|
||||||
|
*/
|
||||||
|
private static formatCurrencyShort(amount: number): string {
|
||||||
|
if (amount >= 1000000) {
|
||||||
|
return `${(amount / 1000000).toFixed(1)}M`
|
||||||
|
} else if (amount >= 1000) {
|
||||||
|
return `${(amount / 1000).toFixed(0)}K`
|
||||||
|
} else {
|
||||||
|
return amount.toString()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format date for display
|
||||||
|
*/
|
||||||
|
private static formatDate(dateString: string): string {
|
||||||
|
const date = new Date(dateString)
|
||||||
|
return date.toLocaleDateString('id-ID', {
|
||||||
|
day: '2-digit',
|
||||||
|
month: '2-digit'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate filename with timestamp
|
||||||
|
*/
|
||||||
|
private static generateFilename(prefix: string, extension: string): string {
|
||||||
|
const now = new Date()
|
||||||
|
const year = now.getFullYear()
|
||||||
|
const month = (now.getMonth() + 1).toString().padStart(2, '0')
|
||||||
|
const day = now.getDate().toString().padStart(2, '0')
|
||||||
|
const hour = now.getHours().toString().padStart(2, '0')
|
||||||
|
const minute = now.getMinutes().toString().padStart(2, '0')
|
||||||
|
|
||||||
|
return `${prefix}_${year}_${month}_${day}_${hour}${minute}.${extension}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Export Sales Order data with custom configuration
|
||||||
|
*/
|
||||||
|
static async exportCustomSalesOrderToPDF(
|
||||||
|
salesData: SalesReport,
|
||||||
|
options?: {
|
||||||
|
title?: string
|
||||||
|
includeSummary?: boolean
|
||||||
|
customFilename?: string
|
||||||
|
compactMode?: boolean
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const jsPDFModule = await import('jspdf')
|
||||||
|
const jsPDF = jsPDFModule.default
|
||||||
|
|
||||||
|
const pdf = new jsPDF('p', 'mm', 'a4')
|
||||||
|
|
||||||
|
let yPos = 20
|
||||||
|
const pageWidth = pdf.internal.pageSize.getWidth()
|
||||||
|
const pageHeight = pdf.internal.pageSize.getHeight()
|
||||||
|
const marginLeft = 20
|
||||||
|
const marginRight = 20
|
||||||
|
const marginBottom = 15
|
||||||
|
|
||||||
|
const checkPageBreak = (neededSpace: number) => {
|
||||||
|
if (yPos + neededSpace > pageHeight - marginBottom) {
|
||||||
|
pdf.addPage()
|
||||||
|
yPos = 20
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Custom title if provided
|
||||||
|
if (options?.title) {
|
||||||
|
pdf.setFontSize(20)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
pdf.text(options.title, pageWidth / 2, yPos, { align: 'center' })
|
||||||
|
yPos += 15
|
||||||
|
} else {
|
||||||
|
yPos = this.addReportTitle(pdf, salesData, yPos, pageWidth, marginLeft, marginRight)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Optional summary section
|
||||||
|
if (options?.includeSummary !== false) {
|
||||||
|
checkPageBreak(60)
|
||||||
|
yPos = this.addRingkasanSection(pdf, salesData, yPos, pageWidth, marginLeft, marginRight, checkPageBreak)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Daily sales details
|
||||||
|
checkPageBreak(100)
|
||||||
|
if (options?.compactMode) {
|
||||||
|
yPos = this.addCompactDailySalesSection(
|
||||||
|
pdf,
|
||||||
|
salesData,
|
||||||
|
yPos,
|
||||||
|
pageWidth,
|
||||||
|
marginLeft,
|
||||||
|
marginRight,
|
||||||
|
checkPageBreak
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
yPos = this.addDailySalesSection(pdf, salesData, yPos, pageWidth, marginLeft, marginRight, checkPageBreak)
|
||||||
|
}
|
||||||
|
|
||||||
|
const exportFilename = options?.customFilename || this.generateFilename('Custom_Sales_Order', 'pdf')
|
||||||
|
pdf.save(exportFilename)
|
||||||
|
|
||||||
|
return { success: true, filename: exportFilename }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting custom sales order report to PDF:', error)
|
||||||
|
return { success: false, error: `PDF export failed: ${(error as Error).message}` }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add Compact Daily Sales section (fewer columns)
|
||||||
|
*/
|
||||||
|
private static addCompactDailySalesSection(
|
||||||
|
pdf: any,
|
||||||
|
salesData: SalesReport,
|
||||||
|
startY: number,
|
||||||
|
pageWidth: number,
|
||||||
|
marginLeft: number,
|
||||||
|
marginRight: number,
|
||||||
|
checkPageBreak: (space: number) => boolean
|
||||||
|
): number {
|
||||||
|
let yPos = startY
|
||||||
|
|
||||||
|
// Section title
|
||||||
|
pdf.setFontSize(14)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(102, 45, 145)
|
||||||
|
pdf.text('Rincian Harian (Compact)', marginLeft, yPos)
|
||||||
|
yPos += 12
|
||||||
|
|
||||||
|
// Reset formatting
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
|
||||||
|
// Table setup - compact with 4 columns
|
||||||
|
const tableWidth = pageWidth - marginLeft - marginRight
|
||||||
|
const colWidths = [30, 40, 30, 40] // Date, Sales, Orders, Net Sales
|
||||||
|
let currentX = marginLeft
|
||||||
|
|
||||||
|
// Table header
|
||||||
|
pdf.setFillColor(240, 240, 240)
|
||||||
|
pdf.rect(marginLeft, yPos, tableWidth, 10, 'F')
|
||||||
|
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
const headers = ['Tanggal', 'Penjualan', 'Pesanan', 'Pendapatan']
|
||||||
|
currentX = marginLeft
|
||||||
|
|
||||||
|
headers.forEach((header, index) => {
|
||||||
|
if (index === 0) {
|
||||||
|
pdf.text(header, currentX + 2, yPos + 6)
|
||||||
|
} else {
|
||||||
|
pdf.text(header, currentX + colWidths[index] / 2, yPos + 6, { align: 'center' })
|
||||||
|
}
|
||||||
|
currentX += colWidths[index]
|
||||||
|
})
|
||||||
|
|
||||||
|
yPos += 12
|
||||||
|
|
||||||
|
// Table rows
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
salesData.data?.forEach((dailySales, index) => {
|
||||||
|
if (checkPageBreak(10)) yPos = 20
|
||||||
|
|
||||||
|
currentX = marginLeft
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
|
||||||
|
// Date
|
||||||
|
pdf.text(this.formatDate(dailySales.date), currentX + 2, yPos + 5)
|
||||||
|
currentX += colWidths[0]
|
||||||
|
|
||||||
|
// Sales
|
||||||
|
pdf.text(this.formatCurrency(dailySales.sales), currentX + colWidths[1] - 2, yPos + 5, { align: 'right' })
|
||||||
|
currentX += colWidths[1]
|
||||||
|
|
||||||
|
// Orders
|
||||||
|
pdf.text(dailySales.orders.toString(), currentX + colWidths[2] / 2, yPos + 5, { align: 'center' })
|
||||||
|
currentX += colWidths[2]
|
||||||
|
|
||||||
|
// Net Sales
|
||||||
|
pdf.text(this.formatCurrency(dailySales.net_sales), currentX + colWidths[3] - 2, yPos + 5, { align: 'right' })
|
||||||
|
|
||||||
|
// Draw bottom border line
|
||||||
|
pdf.setDrawColor(230, 230, 230)
|
||||||
|
pdf.setLineWidth(0.3)
|
||||||
|
pdf.line(marginLeft, yPos + 8, marginLeft + tableWidth, yPos + 8)
|
||||||
|
|
||||||
|
yPos += 10
|
||||||
|
})
|
||||||
|
|
||||||
|
// Table footer (Total)
|
||||||
|
pdf.setFillColor(245, 245, 245)
|
||||||
|
pdf.rect(marginLeft, yPos, tableWidth, 10, 'F')
|
||||||
|
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
currentX = marginLeft
|
||||||
|
pdf.text('TOTAL', currentX + 2, yPos + 6)
|
||||||
|
currentX += colWidths[0]
|
||||||
|
|
||||||
|
pdf.text(this.formatCurrency(salesData.summary.total_sales), currentX + colWidths[1] - 2, yPos + 6, {
|
||||||
|
align: 'right'
|
||||||
|
})
|
||||||
|
currentX += colWidths[1]
|
||||||
|
|
||||||
|
pdf.text(salesData.summary.total_orders.toString(), currentX + colWidths[2] / 2, yPos + 6, { align: 'center' })
|
||||||
|
currentX += colWidths[2]
|
||||||
|
|
||||||
|
pdf.text(this.formatCurrency(salesData.summary.net_sales), currentX + colWidths[3] - 2, yPos + 6, {
|
||||||
|
align: 'right'
|
||||||
|
})
|
||||||
|
|
||||||
|
return yPos + 20
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,556 @@
|
|||||||
|
// services/pdfExportCategoryService.ts
|
||||||
|
import { CategoryReport } from '@/types/services/analytic'
|
||||||
|
|
||||||
|
export class PDFExportSalesProductCategoryService {
|
||||||
|
/**
|
||||||
|
* Export Category Sales Report to PDF
|
||||||
|
*/
|
||||||
|
static async exportCategorySalesToPDF(categoryData: CategoryReport, filename?: string) {
|
||||||
|
try {
|
||||||
|
// Dynamic import untuk jsPDF
|
||||||
|
const jsPDFModule = await import('jspdf')
|
||||||
|
const jsPDF = jsPDFModule.default
|
||||||
|
|
||||||
|
// Create new PDF document - PORTRAIT A4
|
||||||
|
const pdf = new jsPDF('p', 'mm', 'a4')
|
||||||
|
|
||||||
|
// Add content
|
||||||
|
await this.addCategoryReportContent(pdf, categoryData)
|
||||||
|
|
||||||
|
// Generate filename
|
||||||
|
const exportFilename = filename || this.generateFilename('Laporan_Penjualan_Kategori', 'pdf')
|
||||||
|
|
||||||
|
// Save PDF
|
||||||
|
pdf.save(exportFilename)
|
||||||
|
|
||||||
|
return { success: true, filename: exportFilename }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting category report to PDF:', error)
|
||||||
|
return { success: false, error: `PDF export failed: ${(error as Error).message}` }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add category report content to PDF
|
||||||
|
*/
|
||||||
|
private static async addCategoryReportContent(pdf: any, categoryData: CategoryReport) {
|
||||||
|
let yPos = 20
|
||||||
|
const pageWidth = pdf.internal.pageSize.getWidth()
|
||||||
|
const pageHeight = pdf.internal.pageSize.getHeight()
|
||||||
|
const marginLeft = 20
|
||||||
|
const marginRight = 20
|
||||||
|
const marginBottom = 15
|
||||||
|
|
||||||
|
// Helper function to check page break
|
||||||
|
const checkPageBreak = (neededSpace: number) => {
|
||||||
|
if (yPos + neededSpace > pageHeight - marginBottom) {
|
||||||
|
pdf.addPage()
|
||||||
|
yPos = 20
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Title
|
||||||
|
yPos = this.addReportTitle(pdf, categoryData, yPos, pageWidth, marginLeft, marginRight)
|
||||||
|
|
||||||
|
// Section 1: Ringkasan
|
||||||
|
checkPageBreak(50)
|
||||||
|
yPos = this.addRingkasanSection(pdf, categoryData, yPos, pageWidth, marginLeft, marginRight, checkPageBreak)
|
||||||
|
|
||||||
|
// Section 2: Category Details
|
||||||
|
checkPageBreak(80)
|
||||||
|
yPos = this.addCategoryDetailsSection(pdf, categoryData, yPos, pageWidth, marginLeft, marginRight, checkPageBreak)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add report title
|
||||||
|
*/
|
||||||
|
private static addReportTitle(
|
||||||
|
pdf: any,
|
||||||
|
categoryData: CategoryReport,
|
||||||
|
startY: number,
|
||||||
|
pageWidth: number,
|
||||||
|
marginLeft: number,
|
||||||
|
marginRight: number
|
||||||
|
): number {
|
||||||
|
let yPos = startY
|
||||||
|
|
||||||
|
// Title
|
||||||
|
pdf.setFontSize(20)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
pdf.text('Laporan Penjualan Kategori', pageWidth / 2, yPos, { align: 'center' })
|
||||||
|
yPos += 10
|
||||||
|
|
||||||
|
// Period
|
||||||
|
pdf.setFontSize(12)
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
const periodText = `${categoryData.date_from.split('T')[0]} - ${categoryData.date_to.split('T')[0]}`
|
||||||
|
pdf.text(periodText, pageWidth / 2, yPos, { align: 'center' })
|
||||||
|
yPos += 10
|
||||||
|
|
||||||
|
// Purple line separator
|
||||||
|
pdf.setDrawColor(102, 45, 145)
|
||||||
|
pdf.setLineWidth(2)
|
||||||
|
pdf.line(marginLeft, yPos, pageWidth - marginRight, yPos)
|
||||||
|
yPos += 15
|
||||||
|
|
||||||
|
return yPos
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add Ringkasan section
|
||||||
|
*/
|
||||||
|
private static addRingkasanSection(
|
||||||
|
pdf: any,
|
||||||
|
categoryData: CategoryReport,
|
||||||
|
startY: number,
|
||||||
|
pageWidth: number,
|
||||||
|
marginLeft: number,
|
||||||
|
marginRight: number,
|
||||||
|
checkPageBreak: (space: number) => boolean
|
||||||
|
): number {
|
||||||
|
let yPos = startY
|
||||||
|
|
||||||
|
// Section title
|
||||||
|
pdf.setFontSize(14)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(102, 45, 145)
|
||||||
|
pdf.text('Ringkasan', marginLeft, yPos)
|
||||||
|
yPos += 12
|
||||||
|
|
||||||
|
// Reset text color
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
pdf.setFontSize(11)
|
||||||
|
|
||||||
|
// Calculate summary
|
||||||
|
const categorySummary = {
|
||||||
|
totalRevenue: categoryData.data?.reduce((sum, item) => sum + (item?.total_revenue || 0), 0) || 0,
|
||||||
|
orderCount: categoryData.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0,
|
||||||
|
productCount: categoryData.data?.reduce((sum, item) => sum + (item?.product_count || 0), 0) || 0,
|
||||||
|
totalQuantity: categoryData.data?.reduce((sum, item) => sum + (item?.total_quantity || 0), 0) || 0,
|
||||||
|
totalCategories: categoryData.data?.length || 0,
|
||||||
|
averageRevenuePerCategory: 0
|
||||||
|
}
|
||||||
|
categorySummary.averageRevenuePerCategory =
|
||||||
|
categorySummary.totalCategories > 0 ? categorySummary.totalRevenue / categorySummary.totalCategories : 0
|
||||||
|
|
||||||
|
const ringkasanItems = [
|
||||||
|
{ label: 'Total Kategori', value: categorySummary.totalCategories.toString(), bold: false },
|
||||||
|
{ label: 'Total Produk', value: categorySummary.productCount.toString(), bold: false },
|
||||||
|
{ label: 'Total Quantity', value: categorySummary.totalQuantity.toString(), bold: false },
|
||||||
|
{ label: 'Total Orders', value: categorySummary.orderCount.toString(), bold: false },
|
||||||
|
{ label: 'Total Revenue', value: this.formatCurrency(categorySummary.totalRevenue), bold: true },
|
||||||
|
{
|
||||||
|
label: 'Rata-rata Revenue per Kategori',
|
||||||
|
value: this.formatCurrency(categorySummary.averageRevenuePerCategory),
|
||||||
|
bold: false
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
ringkasanItems.forEach((item, index) => {
|
||||||
|
if (checkPageBreak(15)) yPos = 20
|
||||||
|
|
||||||
|
// Set font weight
|
||||||
|
pdf.setFont('helvetica', item.bold ? 'bold' : 'normal')
|
||||||
|
|
||||||
|
pdf.text(item.label, marginLeft, yPos)
|
||||||
|
pdf.text(item.value, pageWidth - marginRight, yPos, { align: 'right' })
|
||||||
|
|
||||||
|
// Light separator line (except for bold row)
|
||||||
|
if (!item.bold) {
|
||||||
|
pdf.setDrawColor(230, 230, 230)
|
||||||
|
pdf.setLineWidth(0.5)
|
||||||
|
pdf.line(marginLeft, yPos + 2, pageWidth - marginRight, yPos + 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
yPos += 8
|
||||||
|
})
|
||||||
|
|
||||||
|
return yPos + 20
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add Category Details section
|
||||||
|
*/
|
||||||
|
private static addCategoryDetailsSection(
|
||||||
|
pdf: any,
|
||||||
|
categoryData: CategoryReport,
|
||||||
|
startY: number,
|
||||||
|
pageWidth: number,
|
||||||
|
marginLeft: number,
|
||||||
|
marginRight: number,
|
||||||
|
checkPageBreak: (space: number) => boolean
|
||||||
|
): number {
|
||||||
|
let yPos = startY
|
||||||
|
|
||||||
|
// Section title
|
||||||
|
pdf.setFontSize(14)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(102, 45, 145)
|
||||||
|
pdf.text('Rincian Kategori', marginLeft, yPos)
|
||||||
|
yPos += 12
|
||||||
|
|
||||||
|
// Reset formatting
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
|
||||||
|
// Table setup
|
||||||
|
const tableWidth = pageWidth - marginLeft - marginRight
|
||||||
|
const colWidths = [50, 30, 25, 35] // Name, Products, Qty, Revenue
|
||||||
|
let currentX = marginLeft
|
||||||
|
|
||||||
|
// Table header
|
||||||
|
pdf.setFillColor(240, 240, 240)
|
||||||
|
pdf.rect(marginLeft, yPos, tableWidth, 10, 'F')
|
||||||
|
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
const headers = ['Nama', 'Total Produk', 'Qty', 'Pendapatan']
|
||||||
|
currentX = marginLeft
|
||||||
|
|
||||||
|
headers.forEach((header, index) => {
|
||||||
|
if (index === 0) {
|
||||||
|
pdf.text(header, currentX + 2, yPos + 6)
|
||||||
|
} else {
|
||||||
|
pdf.text(header, currentX + colWidths[index] / 2, yPos + 6, { align: 'center' })
|
||||||
|
}
|
||||||
|
currentX += colWidths[index]
|
||||||
|
})
|
||||||
|
|
||||||
|
yPos += 12
|
||||||
|
|
||||||
|
// Calculate summary for footer
|
||||||
|
const categorySummary = {
|
||||||
|
totalRevenue: categoryData.data?.reduce((sum, item) => sum + (item?.total_revenue || 0), 0) || 0,
|
||||||
|
productCount: categoryData.data?.reduce((sum, item) => sum + (item?.product_count || 0), 0) || 0,
|
||||||
|
totalQuantity: categoryData.data?.reduce((sum, item) => sum + (item?.total_quantity || 0), 0) || 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Table rows
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
categoryData.data?.forEach((category, index) => {
|
||||||
|
if (checkPageBreak(10)) yPos = 20
|
||||||
|
|
||||||
|
currentX = marginLeft
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
|
||||||
|
// Category name
|
||||||
|
pdf.text(category.category_name, currentX + 2, yPos + 5)
|
||||||
|
currentX += colWidths[0]
|
||||||
|
|
||||||
|
// Product count
|
||||||
|
pdf.text(category.product_count.toString(), currentX + colWidths[1] / 2, yPos + 5, { align: 'center' })
|
||||||
|
currentX += colWidths[1]
|
||||||
|
|
||||||
|
// Quantity
|
||||||
|
pdf.text(category.total_quantity.toString(), currentX + colWidths[2] / 2, yPos + 5, { align: 'center' })
|
||||||
|
currentX += colWidths[2]
|
||||||
|
|
||||||
|
// Revenue
|
||||||
|
pdf.text(this.formatCurrency(category.total_revenue), currentX + colWidths[3] - 2, yPos + 5, { align: 'right' })
|
||||||
|
|
||||||
|
// Draw bottom border line
|
||||||
|
pdf.setDrawColor(230, 230, 230)
|
||||||
|
pdf.setLineWidth(0.3)
|
||||||
|
pdf.line(marginLeft, yPos + 8, marginLeft + tableWidth, yPos + 8)
|
||||||
|
|
||||||
|
yPos += 10
|
||||||
|
})
|
||||||
|
|
||||||
|
// Table footer (Total)
|
||||||
|
pdf.setFillColor(245, 245, 245) // Lighter gray
|
||||||
|
pdf.rect(marginLeft, yPos, tableWidth, 10, 'F')
|
||||||
|
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
currentX = marginLeft
|
||||||
|
pdf.text('TOTAL', currentX + 2, yPos + 6)
|
||||||
|
currentX += colWidths[0]
|
||||||
|
|
||||||
|
pdf.text(categorySummary.productCount.toString(), currentX + colWidths[1] / 2, yPos + 6, { align: 'center' })
|
||||||
|
currentX += colWidths[1]
|
||||||
|
|
||||||
|
pdf.text(categorySummary.totalQuantity.toString(), currentX + colWidths[2] / 2, yPos + 6, { align: 'center' })
|
||||||
|
currentX += colWidths[2]
|
||||||
|
|
||||||
|
pdf.text(this.formatCurrency(categorySummary.totalRevenue), currentX + colWidths[3] - 2, yPos + 6, {
|
||||||
|
align: 'right'
|
||||||
|
})
|
||||||
|
|
||||||
|
return yPos + 20
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format currency for display
|
||||||
|
*/
|
||||||
|
private static formatCurrency(amount: number): string {
|
||||||
|
return `Rp ${amount.toLocaleString('id-ID')}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate filename with timestamp
|
||||||
|
*/
|
||||||
|
private static generateFilename(prefix: string, extension: string): string {
|
||||||
|
const now = new Date()
|
||||||
|
const year = now.getFullYear()
|
||||||
|
const month = (now.getMonth() + 1).toString().padStart(2, '0')
|
||||||
|
const day = now.getDate().toString().padStart(2, '0')
|
||||||
|
const hour = now.getHours().toString().padStart(2, '0')
|
||||||
|
const minute = now.getMinutes().toString().padStart(2, '0')
|
||||||
|
|
||||||
|
return `${prefix}_${year}_${month}_${day}_${hour}${minute}.${extension}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Export Category Sales data with custom configuration
|
||||||
|
*/
|
||||||
|
static async exportCustomCategoryToPDF(
|
||||||
|
categoryData: CategoryReport,
|
||||||
|
options?: {
|
||||||
|
title?: string
|
||||||
|
includeSummary?: boolean
|
||||||
|
customFilename?: string
|
||||||
|
includeOrderCount?: boolean
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const jsPDFModule = await import('jspdf')
|
||||||
|
const jsPDF = jsPDFModule.default
|
||||||
|
|
||||||
|
const pdf = new jsPDF('p', 'mm', 'a4')
|
||||||
|
|
||||||
|
let yPos = 20
|
||||||
|
const pageWidth = pdf.internal.pageSize.getWidth()
|
||||||
|
const pageHeight = pdf.internal.pageSize.getHeight()
|
||||||
|
const marginLeft = 20
|
||||||
|
const marginRight = 20
|
||||||
|
const marginBottom = 15
|
||||||
|
|
||||||
|
const checkPageBreak = (neededSpace: number) => {
|
||||||
|
if (yPos + neededSpace > pageHeight - marginBottom) {
|
||||||
|
pdf.addPage()
|
||||||
|
yPos = 20
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Custom title if provided
|
||||||
|
if (options?.title) {
|
||||||
|
pdf.setFontSize(20)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
pdf.text(options.title, pageWidth / 2, yPos, { align: 'center' })
|
||||||
|
yPos += 15
|
||||||
|
} else {
|
||||||
|
yPos = this.addReportTitle(pdf, categoryData, yPos, pageWidth, marginLeft, marginRight)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Optional summary section
|
||||||
|
if (options?.includeSummary !== false) {
|
||||||
|
checkPageBreak(50)
|
||||||
|
yPos = this.addRingkasanSection(pdf, categoryData, yPos, pageWidth, marginLeft, marginRight, checkPageBreak)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Category details
|
||||||
|
checkPageBreak(80)
|
||||||
|
yPos = this.addCategoryDetailsSection(pdf, categoryData, yPos, pageWidth, marginLeft, marginRight, checkPageBreak)
|
||||||
|
|
||||||
|
const exportFilename = options?.customFilename || this.generateFilename('Custom_Category_Sales', 'pdf')
|
||||||
|
pdf.save(exportFilename)
|
||||||
|
|
||||||
|
return { success: true, filename: exportFilename }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting custom category report to PDF:', error)
|
||||||
|
return { success: false, error: `PDF export failed: ${(error as Error).message}` }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Export Category Sales with extended table including order count
|
||||||
|
*/
|
||||||
|
static async exportExtendedCategoryToPDF(categoryData: CategoryReport, filename?: string) {
|
||||||
|
try {
|
||||||
|
const jsPDFModule = await import('jspdf')
|
||||||
|
const jsPDF = jsPDFModule.default
|
||||||
|
|
||||||
|
const pdf = new jsPDF('p', 'mm', 'a4')
|
||||||
|
|
||||||
|
let yPos = 20
|
||||||
|
const pageWidth = pdf.internal.pageSize.getWidth()
|
||||||
|
const pageHeight = pdf.internal.pageSize.getHeight()
|
||||||
|
const marginLeft = 20
|
||||||
|
const marginRight = 20
|
||||||
|
const marginBottom = 15
|
||||||
|
|
||||||
|
const checkPageBreak = (neededSpace: number) => {
|
||||||
|
if (yPos + neededSpace > pageHeight - marginBottom) {
|
||||||
|
pdf.addPage()
|
||||||
|
yPos = 20
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Title section
|
||||||
|
yPos = this.addReportTitle(pdf, categoryData, yPos, pageWidth, marginLeft, marginRight)
|
||||||
|
|
||||||
|
// Summary section
|
||||||
|
checkPageBreak(50)
|
||||||
|
yPos = this.addRingkasanSection(pdf, categoryData, yPos, pageWidth, marginLeft, marginRight, checkPageBreak)
|
||||||
|
|
||||||
|
// Extended table with order count
|
||||||
|
checkPageBreak(80)
|
||||||
|
yPos = this.addExtendedCategoryDetailsSection(
|
||||||
|
pdf,
|
||||||
|
categoryData,
|
||||||
|
yPos,
|
||||||
|
pageWidth,
|
||||||
|
marginLeft,
|
||||||
|
marginRight,
|
||||||
|
checkPageBreak
|
||||||
|
)
|
||||||
|
|
||||||
|
const exportFilename = filename || this.generateFilename('Laporan_Kategori_Extended', 'pdf')
|
||||||
|
pdf.save(exportFilename)
|
||||||
|
|
||||||
|
return { success: true, filename: exportFilename }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting extended category report to PDF:', error)
|
||||||
|
return { success: false, error: `PDF export failed: ${(error as Error).message}` }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add Extended Category Details section with order count
|
||||||
|
*/
|
||||||
|
private static addExtendedCategoryDetailsSection(
|
||||||
|
pdf: any,
|
||||||
|
categoryData: CategoryReport,
|
||||||
|
startY: number,
|
||||||
|
pageWidth: number,
|
||||||
|
marginLeft: number,
|
||||||
|
marginRight: number,
|
||||||
|
checkPageBreak: (space: number) => boolean
|
||||||
|
): number {
|
||||||
|
let yPos = startY
|
||||||
|
|
||||||
|
// Section title
|
||||||
|
pdf.setFontSize(14)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(102, 45, 145)
|
||||||
|
pdf.text('Rincian Kategori (Extended)', marginLeft, yPos)
|
||||||
|
yPos += 12
|
||||||
|
|
||||||
|
// Reset formatting
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
|
||||||
|
// Table setup - wider for 5 columns
|
||||||
|
const tableWidth = pageWidth - marginLeft - marginRight
|
||||||
|
const colWidths = [40, 25, 20, 20, 35] // Name, Products, Qty, Orders, Revenue
|
||||||
|
let currentX = marginLeft
|
||||||
|
|
||||||
|
// Table header
|
||||||
|
pdf.setFillColor(240, 240, 240)
|
||||||
|
pdf.rect(marginLeft, yPos, tableWidth, 10, 'F')
|
||||||
|
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
const headers = ['Nama', 'Total Produk', 'Qty', 'Orders', 'Pendapatan']
|
||||||
|
currentX = marginLeft
|
||||||
|
|
||||||
|
headers.forEach((header, index) => {
|
||||||
|
if (index === 0) {
|
||||||
|
pdf.text(header, currentX + 2, yPos + 6)
|
||||||
|
} else {
|
||||||
|
pdf.text(header, currentX + colWidths[index] / 2, yPos + 6, { align: 'center' })
|
||||||
|
}
|
||||||
|
currentX += colWidths[index]
|
||||||
|
})
|
||||||
|
|
||||||
|
yPos += 12
|
||||||
|
|
||||||
|
// Calculate summary for footer
|
||||||
|
const categorySummary = {
|
||||||
|
totalRevenue: categoryData.data?.reduce((sum, item) => sum + (item?.total_revenue || 0), 0) || 0,
|
||||||
|
productCount: categoryData.data?.reduce((sum, item) => sum + (item?.product_count || 0), 0) || 0,
|
||||||
|
totalQuantity: categoryData.data?.reduce((sum, item) => sum + (item?.total_quantity || 0), 0) || 0,
|
||||||
|
orderCount: categoryData.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Table rows
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
categoryData.data?.forEach((category, index) => {
|
||||||
|
if (checkPageBreak(10)) yPos = 20
|
||||||
|
|
||||||
|
currentX = marginLeft
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
|
||||||
|
// Category name
|
||||||
|
const categoryName =
|
||||||
|
category.category_name.length > 30 ? category.category_name.substring(0, 27) + '...' : category.category_name
|
||||||
|
pdf.text(categoryName, currentX + 2, yPos + 5)
|
||||||
|
currentX += colWidths[0]
|
||||||
|
|
||||||
|
// Product count
|
||||||
|
pdf.text(category.product_count.toString(), currentX + colWidths[1] / 2, yPos + 5, { align: 'center' })
|
||||||
|
currentX += colWidths[1]
|
||||||
|
|
||||||
|
// Quantity
|
||||||
|
pdf.text(category.total_quantity.toString(), currentX + colWidths[2] / 2, yPos + 5, { align: 'center' })
|
||||||
|
currentX += colWidths[2]
|
||||||
|
|
||||||
|
// Order count
|
||||||
|
pdf.text(category.order_count.toString(), currentX + colWidths[3] / 2, yPos + 5, { align: 'center' })
|
||||||
|
currentX += colWidths[3]
|
||||||
|
|
||||||
|
// Revenue
|
||||||
|
pdf.text(this.formatCurrency(category.total_revenue), currentX + colWidths[4] - 2, yPos + 5, { align: 'right' })
|
||||||
|
|
||||||
|
// Draw bottom border line
|
||||||
|
pdf.setDrawColor(230, 230, 230)
|
||||||
|
pdf.setLineWidth(0.3)
|
||||||
|
pdf.line(marginLeft, yPos + 8, marginLeft + tableWidth, yPos + 8)
|
||||||
|
|
||||||
|
yPos += 10
|
||||||
|
})
|
||||||
|
|
||||||
|
// Table footer (Total)
|
||||||
|
pdf.setFillColor(245, 245, 245) // Lighter gray
|
||||||
|
pdf.rect(marginLeft, yPos, tableWidth, 10, 'F')
|
||||||
|
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
currentX = marginLeft
|
||||||
|
pdf.text('TOTAL', currentX + 2, yPos + 6)
|
||||||
|
currentX += colWidths[0]
|
||||||
|
|
||||||
|
pdf.text(categorySummary.productCount.toString(), currentX + colWidths[1] / 2, yPos + 6, { align: 'center' })
|
||||||
|
currentX += colWidths[1]
|
||||||
|
|
||||||
|
pdf.text(categorySummary.totalQuantity.toString(), currentX + colWidths[2] / 2, yPos + 6, { align: 'center' })
|
||||||
|
currentX += colWidths[2]
|
||||||
|
|
||||||
|
pdf.text(categorySummary.orderCount.toString(), currentX + colWidths[3] / 2, yPos + 6, { align: 'center' })
|
||||||
|
currentX += colWidths[3]
|
||||||
|
|
||||||
|
pdf.text(this.formatCurrency(categorySummary.totalRevenue), currentX + colWidths[4] - 2, yPos + 6, {
|
||||||
|
align: 'right'
|
||||||
|
})
|
||||||
|
|
||||||
|
return yPos + 20
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,691 @@
|
|||||||
|
import { CategoryReport, PaymentReport, ProductSalesReport, ProfitLossReport } from '@/types/services/analytic'
|
||||||
|
|
||||||
|
export interface SalesReportData {
|
||||||
|
profitLoss: ProfitLossReport
|
||||||
|
paymentAnalytics: PaymentReport
|
||||||
|
categoryAnalytics: CategoryReport
|
||||||
|
productAnalytics: ProductSalesReport
|
||||||
|
}
|
||||||
|
|
||||||
|
export class PDFExportSalesService {
|
||||||
|
/**
|
||||||
|
* Export Sales Report to PDF
|
||||||
|
*/
|
||||||
|
static async exportSalesReportToPDF(salesData: SalesReportData, filename?: string) {
|
||||||
|
try {
|
||||||
|
// Dynamic import untuk jsPDF
|
||||||
|
const jsPDFModule = await import('jspdf')
|
||||||
|
const jsPDF = jsPDFModule.default
|
||||||
|
|
||||||
|
// Create new PDF document - PORTRAIT A4
|
||||||
|
const pdf = new jsPDF('p', 'mm', 'a4')
|
||||||
|
|
||||||
|
// Add content
|
||||||
|
await this.addSalesReportContent(pdf, salesData)
|
||||||
|
|
||||||
|
// Generate filename
|
||||||
|
const exportFilename = filename || this.generateFilename('Laporan_Transaksi', 'pdf')
|
||||||
|
|
||||||
|
// Save PDF
|
||||||
|
pdf.save(exportFilename)
|
||||||
|
|
||||||
|
return { success: true, filename: exportFilename }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting sales report to PDF:', error)
|
||||||
|
return { success: false, error: `PDF export failed: ${(error as Error).message}` }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add sales report content to PDF
|
||||||
|
*/
|
||||||
|
private static async addSalesReportContent(pdf: any, salesData: SalesReportData) {
|
||||||
|
let yPos = 20
|
||||||
|
const pageWidth = pdf.internal.pageSize.getWidth()
|
||||||
|
const pageHeight = pdf.internal.pageSize.getHeight()
|
||||||
|
const marginLeft = 20
|
||||||
|
const marginRight = 20
|
||||||
|
const marginBottom = 15
|
||||||
|
|
||||||
|
// Helper function to check page break
|
||||||
|
const checkPageBreak = (neededSpace: number) => {
|
||||||
|
if (yPos + neededSpace > pageHeight - marginBottom) {
|
||||||
|
pdf.addPage()
|
||||||
|
yPos = 20
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Title
|
||||||
|
yPos = this.addReportTitle(pdf, salesData.profitLoss, yPos, pageWidth, marginLeft, marginRight)
|
||||||
|
|
||||||
|
// Section 1: Ringkasan
|
||||||
|
checkPageBreak(50)
|
||||||
|
yPos = this.addRingkasanSection(pdf, salesData.profitLoss, yPos, pageWidth, marginLeft, marginRight, checkPageBreak)
|
||||||
|
|
||||||
|
// Section 2: Invoice Summary
|
||||||
|
checkPageBreak(40)
|
||||||
|
yPos = this.addInvoiceSection(pdf, salesData.profitLoss, yPos, pageWidth, marginLeft, marginRight, checkPageBreak)
|
||||||
|
|
||||||
|
// Section 3: Payment Methods
|
||||||
|
checkPageBreak(80)
|
||||||
|
yPos = this.addPaymentMethodsSection(
|
||||||
|
pdf,
|
||||||
|
salesData.paymentAnalytics,
|
||||||
|
yPos,
|
||||||
|
pageWidth,
|
||||||
|
marginLeft,
|
||||||
|
marginRight,
|
||||||
|
checkPageBreak
|
||||||
|
)
|
||||||
|
|
||||||
|
// Section 4: Category Summary
|
||||||
|
checkPageBreak(80)
|
||||||
|
yPos = this.addCategorySection(
|
||||||
|
pdf,
|
||||||
|
salesData.categoryAnalytics,
|
||||||
|
yPos,
|
||||||
|
pageWidth,
|
||||||
|
marginLeft,
|
||||||
|
marginRight,
|
||||||
|
checkPageBreak
|
||||||
|
)
|
||||||
|
|
||||||
|
// Section 5: Product Summary
|
||||||
|
checkPageBreak(100)
|
||||||
|
yPos = this.addProductSection(
|
||||||
|
pdf,
|
||||||
|
salesData.productAnalytics,
|
||||||
|
yPos,
|
||||||
|
pageWidth,
|
||||||
|
marginLeft,
|
||||||
|
marginRight,
|
||||||
|
checkPageBreak
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add report title
|
||||||
|
*/
|
||||||
|
private static addReportTitle(
|
||||||
|
pdf: any,
|
||||||
|
profitLoss: ProfitLossReport,
|
||||||
|
startY: number,
|
||||||
|
pageWidth: number,
|
||||||
|
marginLeft: number,
|
||||||
|
marginRight: number
|
||||||
|
): number {
|
||||||
|
let yPos = startY
|
||||||
|
|
||||||
|
// Title
|
||||||
|
pdf.setFontSize(20)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
pdf.text('Laporan Transaksi', pageWidth / 2, yPos, { align: 'center' })
|
||||||
|
yPos += 10
|
||||||
|
|
||||||
|
// Period
|
||||||
|
pdf.setFontSize(12)
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
const periodText = `${profitLoss.date_from.split('T')[0]} - ${profitLoss.date_to.split('T')[0]}`
|
||||||
|
pdf.text(periodText, pageWidth / 2, yPos, { align: 'center' })
|
||||||
|
yPos += 10
|
||||||
|
|
||||||
|
// Purple line separator
|
||||||
|
pdf.setDrawColor(102, 45, 145)
|
||||||
|
pdf.setLineWidth(2)
|
||||||
|
pdf.line(marginLeft, yPos, pageWidth - marginRight, yPos)
|
||||||
|
yPos += 15
|
||||||
|
|
||||||
|
return yPos
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add Ringkasan section - SAMAKAN DENGAN PAYMENT METHODS STYLE
|
||||||
|
*/
|
||||||
|
private static addRingkasanSection(
|
||||||
|
pdf: any,
|
||||||
|
profitLoss: ProfitLossReport,
|
||||||
|
startY: number,
|
||||||
|
pageWidth: number,
|
||||||
|
marginLeft: number,
|
||||||
|
marginRight: number,
|
||||||
|
checkPageBreak: (space: number) => boolean
|
||||||
|
): number {
|
||||||
|
let yPos = startY
|
||||||
|
|
||||||
|
// Section title - SAMA SEPERTI PAYMENT METHODS
|
||||||
|
pdf.setFontSize(14)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(102, 45, 145)
|
||||||
|
pdf.text('Ringkasan', marginLeft, yPos)
|
||||||
|
yPos += 12
|
||||||
|
|
||||||
|
// Reset text color
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
pdf.setFontSize(11)
|
||||||
|
|
||||||
|
const ringkasanItems = [
|
||||||
|
{ label: 'Total Penjualan', value: this.formatCurrency(profitLoss.summary.total_revenue), bold: false },
|
||||||
|
{ label: 'Total Diskon', value: this.formatCurrency(profitLoss.summary.total_discount), bold: false },
|
||||||
|
{ label: 'Total Pajak', value: this.formatCurrency(profitLoss.summary.total_tax), bold: false },
|
||||||
|
{ label: 'Total', value: this.formatCurrency(profitLoss.summary.total_revenue), bold: true }
|
||||||
|
]
|
||||||
|
|
||||||
|
ringkasanItems.forEach((item, index) => {
|
||||||
|
if (checkPageBreak(15)) yPos = 20
|
||||||
|
|
||||||
|
// Set font weight
|
||||||
|
pdf.setFont('helvetica', item.bold ? 'bold' : 'normal')
|
||||||
|
|
||||||
|
pdf.text(item.label, marginLeft, yPos)
|
||||||
|
pdf.text(item.value, pageWidth - marginRight, yPos, { align: 'right' })
|
||||||
|
|
||||||
|
// Light separator line (except for total row)
|
||||||
|
if (!item.bold) {
|
||||||
|
pdf.setDrawColor(230, 230, 230)
|
||||||
|
pdf.setLineWidth(0.5)
|
||||||
|
pdf.line(marginLeft, yPos + 2, pageWidth - marginRight, yPos + 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
yPos += 8
|
||||||
|
})
|
||||||
|
|
||||||
|
return yPos + 20
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add Invoice section - SAMAKAN DENGAN PAYMENT METHODS STYLE
|
||||||
|
*/
|
||||||
|
private static addInvoiceSection(
|
||||||
|
pdf: any,
|
||||||
|
profitLoss: ProfitLossReport,
|
||||||
|
startY: number,
|
||||||
|
pageWidth: number,
|
||||||
|
marginLeft: number,
|
||||||
|
marginRight: number,
|
||||||
|
checkPageBreak: (space: number) => boolean
|
||||||
|
): number {
|
||||||
|
let yPos = startY
|
||||||
|
|
||||||
|
// Section title - SAMA SEPERTI PAYMENT METHODS
|
||||||
|
pdf.setFontSize(14)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(102, 45, 145)
|
||||||
|
pdf.text('Invoice', marginLeft, yPos)
|
||||||
|
yPos += 12
|
||||||
|
|
||||||
|
// Reset formatting
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
pdf.setFontSize(11)
|
||||||
|
|
||||||
|
const invoiceItems = [
|
||||||
|
{ label: 'Total Invoice', value: profitLoss.summary.total_orders.toString() },
|
||||||
|
{ label: 'Rata-rata Tagihan Per Invoice', value: this.formatCurrency(profitLoss.summary.average_profit) }
|
||||||
|
]
|
||||||
|
|
||||||
|
invoiceItems.forEach((item, index) => {
|
||||||
|
if (checkPageBreak(15)) yPos = 20
|
||||||
|
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
pdf.text(item.label, marginLeft, yPos)
|
||||||
|
pdf.text(item.value, pageWidth - marginRight, yPos, { align: 'right' })
|
||||||
|
|
||||||
|
// Light separator line
|
||||||
|
if (index < invoiceItems.length - 1) {
|
||||||
|
pdf.setDrawColor(230, 230, 230)
|
||||||
|
pdf.setLineWidth(0.5)
|
||||||
|
pdf.line(marginLeft, yPos + 2, pageWidth - marginRight, yPos + 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
yPos += 8
|
||||||
|
})
|
||||||
|
|
||||||
|
return yPos + 20
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add Payment Methods section - ORIGINAL STYLE (3 jam lu bikin ini!)
|
||||||
|
*/
|
||||||
|
private static addPaymentMethodsSection(
|
||||||
|
pdf: any,
|
||||||
|
paymentAnalytics: PaymentReport,
|
||||||
|
startY: number,
|
||||||
|
pageWidth: number,
|
||||||
|
marginLeft: number,
|
||||||
|
marginRight: number,
|
||||||
|
checkPageBreak: (space: number) => boolean
|
||||||
|
): number {
|
||||||
|
let yPos = startY
|
||||||
|
|
||||||
|
// Section title
|
||||||
|
pdf.setFontSize(14)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(102, 45, 145)
|
||||||
|
pdf.text('Ringkasan Metode Pembayaran', marginLeft, yPos)
|
||||||
|
yPos += 12
|
||||||
|
|
||||||
|
// Reset formatting
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
|
||||||
|
// Table setup
|
||||||
|
const tableWidth = pageWidth - marginLeft - marginRight
|
||||||
|
const colWidths = [50, 25, 30, 35, 25] // Method, Type, Order, Amount, %
|
||||||
|
let currentX = marginLeft
|
||||||
|
|
||||||
|
// Table header
|
||||||
|
pdf.setFillColor(240, 240, 240)
|
||||||
|
pdf.rect(marginLeft, yPos, tableWidth, 10, 'F')
|
||||||
|
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
const headers = ['Metode Pembayaran', 'Tipe', 'Jumlah Order', 'Total Amount', 'Persentase']
|
||||||
|
currentX = marginLeft
|
||||||
|
|
||||||
|
headers.forEach((header, index) => {
|
||||||
|
if (index === 0) {
|
||||||
|
pdf.text(header, currentX + 2, yPos + 6)
|
||||||
|
} else {
|
||||||
|
pdf.text(header, currentX + colWidths[index] / 2, yPos + 6, { align: 'center' })
|
||||||
|
}
|
||||||
|
currentX += colWidths[index]
|
||||||
|
})
|
||||||
|
|
||||||
|
yPos += 12
|
||||||
|
|
||||||
|
// Table rows
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
paymentAnalytics.data?.forEach((payment, index) => {
|
||||||
|
if (checkPageBreak(10)) yPos = 20
|
||||||
|
|
||||||
|
currentX = marginLeft
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
|
||||||
|
// Method name
|
||||||
|
pdf.text(payment.payment_method_name, currentX + 2, yPos + 5)
|
||||||
|
currentX += colWidths[0]
|
||||||
|
|
||||||
|
// Type with simple color coding
|
||||||
|
const typeText = payment.payment_method_type.toUpperCase()
|
||||||
|
if (payment.payment_method_type === 'cash') {
|
||||||
|
pdf.setTextColor(0, 120, 0) // Green
|
||||||
|
} else if (payment.payment_method_type === 'card') {
|
||||||
|
pdf.setTextColor(0, 80, 200) // Blue
|
||||||
|
} else {
|
||||||
|
pdf.setTextColor(200, 100, 0) // Orange
|
||||||
|
}
|
||||||
|
pdf.text(typeText, currentX + colWidths[1] / 2, yPos + 5, { align: 'center' })
|
||||||
|
pdf.setTextColor(0, 0, 0) // Reset color
|
||||||
|
currentX += colWidths[1]
|
||||||
|
|
||||||
|
// Order count
|
||||||
|
pdf.text(payment.order_count.toString(), currentX + colWidths[2] / 2, yPos + 5, { align: 'center' })
|
||||||
|
currentX += colWidths[2]
|
||||||
|
|
||||||
|
// Amount
|
||||||
|
pdf.text(this.formatCurrency(payment.total_amount), currentX + colWidths[3] - 2, yPos + 5, { align: 'right' })
|
||||||
|
currentX += colWidths[3]
|
||||||
|
|
||||||
|
// Percentage
|
||||||
|
pdf.text(`${(payment.percentage ?? 0).toFixed(1)}%`, currentX + colWidths[4] / 2, yPos + 5, { align: 'center' })
|
||||||
|
|
||||||
|
// Draw bottom border line
|
||||||
|
pdf.setDrawColor(230, 230, 230)
|
||||||
|
pdf.setLineWidth(0.3)
|
||||||
|
pdf.line(marginLeft, yPos + 8, marginLeft + tableWidth, yPos + 8)
|
||||||
|
|
||||||
|
yPos += 10
|
||||||
|
})
|
||||||
|
|
||||||
|
// Table footer (Total) - directly after last row
|
||||||
|
pdf.setFillColor(245, 245, 245) // Lighter gray
|
||||||
|
pdf.rect(marginLeft, yPos, tableWidth, 10, 'F')
|
||||||
|
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
currentX = marginLeft
|
||||||
|
pdf.text('TOTAL', currentX + 2, yPos + 6)
|
||||||
|
currentX += colWidths[0] + colWidths[1]
|
||||||
|
|
||||||
|
pdf.text((paymentAnalytics.summary?.total_orders ?? 0).toString(), currentX + colWidths[2] / 2, yPos + 6, {
|
||||||
|
align: 'center'
|
||||||
|
})
|
||||||
|
currentX += colWidths[2]
|
||||||
|
|
||||||
|
pdf.text(this.formatCurrency(paymentAnalytics.summary?.total_amount ?? 0), currentX + colWidths[3] - 2, yPos + 6, {
|
||||||
|
align: 'right'
|
||||||
|
})
|
||||||
|
|
||||||
|
return yPos + 20
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add Category section - SAMAKAN DENGAN PAYMENT METHODS STYLE
|
||||||
|
*/
|
||||||
|
private static addCategorySection(
|
||||||
|
pdf: any,
|
||||||
|
categoryAnalytics: CategoryReport,
|
||||||
|
startY: number,
|
||||||
|
pageWidth: number,
|
||||||
|
marginLeft: number,
|
||||||
|
marginRight: number,
|
||||||
|
checkPageBreak: (space: number) => boolean
|
||||||
|
): number {
|
||||||
|
let yPos = startY
|
||||||
|
|
||||||
|
// Section title - SAMA SEPERTI PAYMENT METHODS
|
||||||
|
pdf.setFontSize(14)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(102, 45, 145)
|
||||||
|
pdf.text('Ringkasan Kategori', marginLeft, yPos)
|
||||||
|
yPos += 12
|
||||||
|
|
||||||
|
// Reset formatting
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
|
||||||
|
// Table setup
|
||||||
|
const tableWidth = pageWidth - marginLeft - marginRight
|
||||||
|
const colWidths = [50, 30, 25, 35] // Name, Products, Qty, Revenue
|
||||||
|
let currentX = marginLeft
|
||||||
|
|
||||||
|
// Table header - SAMA SEPERTI PAYMENT METHODS
|
||||||
|
pdf.setFillColor(240, 240, 240)
|
||||||
|
pdf.rect(marginLeft, yPos, tableWidth, 10, 'F')
|
||||||
|
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
const headers = ['Nama', 'Total Produk', 'Qty', 'Pendapatan']
|
||||||
|
currentX = marginLeft
|
||||||
|
|
||||||
|
headers.forEach((header, index) => {
|
||||||
|
if (index === 0) {
|
||||||
|
pdf.text(header, currentX + 2, yPos + 6)
|
||||||
|
} else {
|
||||||
|
pdf.text(header, currentX + colWidths[index] / 2, yPos + 6, { align: 'center' })
|
||||||
|
}
|
||||||
|
currentX += colWidths[index]
|
||||||
|
})
|
||||||
|
|
||||||
|
yPos += 12
|
||||||
|
|
||||||
|
// Calculate summaries
|
||||||
|
const categorySummary = {
|
||||||
|
totalRevenue: categoryAnalytics.data?.reduce((sum, item) => sum + (item?.total_revenue || 0), 0) || 0,
|
||||||
|
productCount: categoryAnalytics.data?.reduce((sum, item) => sum + (item?.product_count || 0), 0) || 0,
|
||||||
|
totalQuantity: categoryAnalytics.data?.reduce((sum, item) => sum + (item?.total_quantity || 0), 0) || 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Table rows - SAMA SEPERTI PAYMENT METHODS
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
categoryAnalytics.data?.forEach((category, index) => {
|
||||||
|
if (checkPageBreak(10)) yPos = 20
|
||||||
|
|
||||||
|
currentX = marginLeft
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
|
||||||
|
// Category name
|
||||||
|
pdf.text(category.category_name, currentX + 2, yPos + 5)
|
||||||
|
currentX += colWidths[0]
|
||||||
|
|
||||||
|
// Product count
|
||||||
|
pdf.text(category.product_count.toString(), currentX + colWidths[1] / 2, yPos + 5, { align: 'center' })
|
||||||
|
currentX += colWidths[1]
|
||||||
|
|
||||||
|
// Quantity
|
||||||
|
pdf.text(category.total_quantity.toString(), currentX + colWidths[2] / 2, yPos + 5, { align: 'center' })
|
||||||
|
currentX += colWidths[2]
|
||||||
|
|
||||||
|
// Revenue
|
||||||
|
pdf.text(this.formatCurrency(category.total_revenue), currentX + colWidths[3] - 2, yPos + 5, { align: 'right' })
|
||||||
|
|
||||||
|
// Draw bottom border line - SAMA SEPERTI PAYMENT METHODS
|
||||||
|
pdf.setDrawColor(230, 230, 230)
|
||||||
|
pdf.setLineWidth(0.3)
|
||||||
|
pdf.line(marginLeft, yPos + 8, marginLeft + tableWidth, yPos + 8)
|
||||||
|
|
||||||
|
yPos += 10
|
||||||
|
})
|
||||||
|
|
||||||
|
// Table footer (Total) - SAMA SEPERTI PAYMENT METHODS
|
||||||
|
pdf.setFillColor(245, 245, 245) // Lighter gray
|
||||||
|
pdf.rect(marginLeft, yPos, tableWidth, 10, 'F')
|
||||||
|
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
currentX = marginLeft
|
||||||
|
pdf.text('TOTAL', currentX + 2, yPos + 6)
|
||||||
|
currentX += colWidths[0]
|
||||||
|
|
||||||
|
pdf.text(categorySummary.productCount.toString(), currentX + colWidths[1] / 2, yPos + 6, { align: 'center' })
|
||||||
|
currentX += colWidths[1]
|
||||||
|
|
||||||
|
pdf.text(categorySummary.totalQuantity.toString(), currentX + colWidths[2] / 2, yPos + 6, { align: 'center' })
|
||||||
|
currentX += colWidths[2]
|
||||||
|
|
||||||
|
pdf.text(this.formatCurrency(categorySummary.totalRevenue), currentX + colWidths[3] - 2, yPos + 6, {
|
||||||
|
align: 'right'
|
||||||
|
})
|
||||||
|
|
||||||
|
return yPos + 20
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add Product section - SAMAKAN DENGAN PAYMENT METHODS STYLE
|
||||||
|
*/
|
||||||
|
private static addProductSection(
|
||||||
|
pdf: any,
|
||||||
|
productAnalytics: ProductSalesReport,
|
||||||
|
startY: number,
|
||||||
|
pageWidth: number,
|
||||||
|
marginLeft: number,
|
||||||
|
marginRight: number,
|
||||||
|
checkPageBreak: (space: number) => boolean
|
||||||
|
): number {
|
||||||
|
let yPos = startY // Hapus extra spacing, biar sama dengan section lain
|
||||||
|
|
||||||
|
// Section title - SAMA SEPERTI PAYMENT METHODS
|
||||||
|
pdf.setFontSize(14)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(102, 45, 145)
|
||||||
|
pdf.text('Ringkasan Item', marginLeft, yPos)
|
||||||
|
yPos += 12
|
||||||
|
|
||||||
|
// Reset formatting
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
|
||||||
|
// Table setup
|
||||||
|
const tableWidth = pageWidth - marginLeft - marginRight
|
||||||
|
const colWidths = [60, 20, 20, 30, 30] // Product, Qty, Order, Revenue, Average
|
||||||
|
let currentX = marginLeft
|
||||||
|
|
||||||
|
// Table header - SAMA SEPERTI PAYMENT METHODS
|
||||||
|
pdf.setFillColor(240, 240, 240)
|
||||||
|
pdf.rect(marginLeft, yPos, tableWidth, 10, 'F')
|
||||||
|
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
const headers = ['Produk', 'Qty', 'Order', 'Pendapatan', 'Rata Rata']
|
||||||
|
currentX = marginLeft
|
||||||
|
|
||||||
|
headers.forEach((header, index) => {
|
||||||
|
if (index === 0) {
|
||||||
|
pdf.text(header, currentX + 2, yPos + 6)
|
||||||
|
} else {
|
||||||
|
pdf.text(header, currentX + colWidths[index] / 2, yPos + 6, { align: 'center' })
|
||||||
|
}
|
||||||
|
currentX += colWidths[index]
|
||||||
|
})
|
||||||
|
|
||||||
|
yPos += 12
|
||||||
|
|
||||||
|
// Group products by category
|
||||||
|
const groupedProducts =
|
||||||
|
productAnalytics.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[]>
|
||||||
|
) || {}
|
||||||
|
|
||||||
|
// Calculate product summary
|
||||||
|
const productSummary = {
|
||||||
|
totalQuantitySold: productAnalytics.data?.reduce((sum, item) => sum + (item?.quantity_sold || 0), 0) || 0,
|
||||||
|
totalRevenue: productAnalytics.data?.reduce((sum, item) => sum + (item?.revenue || 0), 0) || 0,
|
||||||
|
totalOrders: productAnalytics.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Table rows - SAMA SEPERTI PAYMENT METHODS
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
// Render grouped products
|
||||||
|
Object.keys(groupedProducts)
|
||||||
|
.sort()
|
||||||
|
.forEach(categoryName => {
|
||||||
|
const categoryProducts = groupedProducts[categoryName]
|
||||||
|
|
||||||
|
// Check page break for category header
|
||||||
|
if (checkPageBreak(10)) yPos = 20
|
||||||
|
|
||||||
|
// Category header - SAMA STYLE SEPERTI PAYMENT METHODS TAPI WARNA LEBIH SOFT
|
||||||
|
pdf.setFillColor(248, 248, 248) // Warna lebih soft
|
||||||
|
pdf.rect(marginLeft, yPos, tableWidth, 10, 'F')
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
pdf.setTextColor(102, 45, 145)
|
||||||
|
pdf.text(categoryName.toUpperCase(), marginLeft + 2, yPos + 6)
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
yPos += 10 // Kurangi jarak, langsung ke 10px seperti row normal
|
||||||
|
|
||||||
|
// Category products
|
||||||
|
categoryProducts.forEach((item, index) => {
|
||||||
|
if (checkPageBreak(10)) yPos = 20
|
||||||
|
|
||||||
|
currentX = marginLeft
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
|
||||||
|
// Product name (indented and truncated if needed)
|
||||||
|
const productName =
|
||||||
|
item.product_name.length > 45 ? item.product_name.substring(0, 42) + '...' : item.product_name
|
||||||
|
|
||||||
|
pdf.text(` ${productName}`, currentX + 2, yPos + 5) // Indented for products
|
||||||
|
currentX += colWidths[0]
|
||||||
|
|
||||||
|
// Quantity
|
||||||
|
pdf.text(item.quantity_sold.toString(), currentX + colWidths[1] / 2, yPos + 5, { align: 'center' })
|
||||||
|
currentX += colWidths[1]
|
||||||
|
|
||||||
|
// Order count
|
||||||
|
pdf.text((item.order_count || 0).toString(), currentX + colWidths[2] / 2, yPos + 5, { align: 'center' })
|
||||||
|
currentX += colWidths[2]
|
||||||
|
|
||||||
|
// Revenue
|
||||||
|
pdf.text(this.formatCurrency(item.revenue), currentX + colWidths[3] - 2, yPos + 5, { align: 'right' })
|
||||||
|
currentX += colWidths[3]
|
||||||
|
|
||||||
|
// Average price
|
||||||
|
pdf.text(this.formatCurrency(item.average_price), currentX + colWidths[4] - 2, yPos + 5, { align: 'right' })
|
||||||
|
|
||||||
|
// Draw bottom border line - SAMA SEPERTI PAYMENT METHODS
|
||||||
|
pdf.setDrawColor(230, 230, 230)
|
||||||
|
pdf.setLineWidth(0.3)
|
||||||
|
pdf.line(marginLeft, yPos + 8, marginLeft + tableWidth, yPos + 8)
|
||||||
|
|
||||||
|
yPos += 10
|
||||||
|
})
|
||||||
|
|
||||||
|
// Category subtotal - WARNA LEBIH SOFT
|
||||||
|
if (checkPageBreak(10)) yPos = 20
|
||||||
|
|
||||||
|
const categoryTotalQty = categoryProducts.reduce((sum, item) => sum + (item.quantity_sold || 0), 0)
|
||||||
|
const categoryTotalOrders = categoryProducts.reduce((sum, item) => sum + (item.order_count || 0), 0)
|
||||||
|
const categoryTotalRevenue = categoryProducts.reduce((sum, item) => sum + (item.revenue || 0), 0)
|
||||||
|
|
||||||
|
pdf.setFillColor(240, 240, 240) // Sama dengan table header, lebih soft
|
||||||
|
pdf.rect(marginLeft, yPos, tableWidth, 10, 'F')
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
currentX = marginLeft
|
||||||
|
pdf.text(`Subtotal ${categoryName}`, currentX + 2, yPos + 6)
|
||||||
|
currentX += colWidths[0]
|
||||||
|
|
||||||
|
pdf.text(categoryTotalQty.toString(), currentX + colWidths[1] / 2, yPos + 6, { align: 'center' })
|
||||||
|
currentX += colWidths[1]
|
||||||
|
|
||||||
|
pdf.text(categoryTotalOrders.toString(), currentX + colWidths[2] / 2, yPos + 6, { align: 'center' })
|
||||||
|
currentX += colWidths[2]
|
||||||
|
|
||||||
|
pdf.text(this.formatCurrency(categoryTotalRevenue), currentX + colWidths[3] - 2, yPos + 6, { align: 'right' })
|
||||||
|
|
||||||
|
yPos += 10 // Kurangi spacing dari 15 ke 10
|
||||||
|
})
|
||||||
|
|
||||||
|
// Grand total - SAMA SEPERTI PAYMENT METHODS FOOTER
|
||||||
|
if (checkPageBreak(10)) yPos = 20
|
||||||
|
|
||||||
|
pdf.setFillColor(245, 245, 245) // Lighter gray - SAMA SEPERTI PAYMENT METHODS
|
||||||
|
pdf.rect(marginLeft, yPos, tableWidth, 10, 'F')
|
||||||
|
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
currentX = marginLeft
|
||||||
|
pdf.text('TOTAL KESELURUHAN', currentX + 2, yPos + 6)
|
||||||
|
currentX += colWidths[0]
|
||||||
|
|
||||||
|
pdf.text(productSummary.totalQuantitySold.toString(), currentX + colWidths[1] / 2, yPos + 6, { align: 'center' })
|
||||||
|
currentX += colWidths[1]
|
||||||
|
|
||||||
|
pdf.text(productSummary.totalOrders.toString(), currentX + colWidths[2] / 2, yPos + 6, { align: 'center' })
|
||||||
|
currentX += colWidths[2]
|
||||||
|
|
||||||
|
pdf.text(this.formatCurrency(productSummary.totalRevenue), currentX + colWidths[3] - 2, yPos + 6, {
|
||||||
|
align: 'right'
|
||||||
|
})
|
||||||
|
|
||||||
|
return yPos + 25
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format currency for display
|
||||||
|
*/
|
||||||
|
private static formatCurrency(amount: number): string {
|
||||||
|
return `Rp ${amount.toLocaleString('id-ID')}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate filename with timestamp
|
||||||
|
*/
|
||||||
|
private static generateFilename(prefix: string, extension: string): string {
|
||||||
|
const now = new Date()
|
||||||
|
const year = now.getFullYear()
|
||||||
|
const month = (now.getMonth() + 1).toString().padStart(2, '0')
|
||||||
|
const day = now.getDate().toString().padStart(2, '0')
|
||||||
|
const hour = now.getHours().toString().padStart(2, '0')
|
||||||
|
const minute = now.getMinutes().toString().padStart(2, '0')
|
||||||
|
|
||||||
|
return `${prefix}_${year}_${month}_${day}_${hour}${minute}.${extension}`
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,439 @@
|
|||||||
|
// services/pdfExportProductService.ts
|
||||||
|
import { ProductSalesReport } from '@/types/services/analytic'
|
||||||
|
|
||||||
|
export class PDFExportSalesProductService {
|
||||||
|
/**
|
||||||
|
* Export Product Sales Report to PDF
|
||||||
|
*/
|
||||||
|
static async exportProductSalesToPDF(productData: ProductSalesReport, filename?: string) {
|
||||||
|
try {
|
||||||
|
// Dynamic import untuk jsPDF
|
||||||
|
const jsPDFModule = await import('jspdf')
|
||||||
|
const jsPDF = jsPDFModule.default
|
||||||
|
|
||||||
|
// Create new PDF document - PORTRAIT A4
|
||||||
|
const pdf = new jsPDF('p', 'mm', 'a4')
|
||||||
|
|
||||||
|
// Add content
|
||||||
|
await this.addProductReportContent(pdf, productData)
|
||||||
|
|
||||||
|
// Generate filename
|
||||||
|
const exportFilename = filename || this.generateFilename('Laporan_Penjualan_Produk', 'pdf')
|
||||||
|
|
||||||
|
// Save PDF
|
||||||
|
pdf.save(exportFilename)
|
||||||
|
|
||||||
|
return { success: true, filename: exportFilename }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting product report to PDF:', error)
|
||||||
|
return { success: false, error: `PDF export failed: ${(error as Error).message}` }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add product report content to PDF
|
||||||
|
*/
|
||||||
|
private static async addProductReportContent(pdf: any, productData: ProductSalesReport) {
|
||||||
|
let yPos = 20
|
||||||
|
const pageWidth = pdf.internal.pageSize.getWidth()
|
||||||
|
const pageHeight = pdf.internal.pageSize.getHeight()
|
||||||
|
const marginLeft = 20
|
||||||
|
const marginRight = 20
|
||||||
|
const marginBottom = 15
|
||||||
|
|
||||||
|
// Helper function to check page break
|
||||||
|
const checkPageBreak = (neededSpace: number) => {
|
||||||
|
if (yPos + neededSpace > pageHeight - marginBottom) {
|
||||||
|
pdf.addPage()
|
||||||
|
yPos = 20
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Title
|
||||||
|
yPos = this.addReportTitle(pdf, productData, yPos, pageWidth, marginLeft, marginRight)
|
||||||
|
|
||||||
|
// Section 1: Ringkasan
|
||||||
|
checkPageBreak(50)
|
||||||
|
yPos = this.addRingkasanSection(pdf, productData, yPos, pageWidth, marginLeft, marginRight, checkPageBreak)
|
||||||
|
|
||||||
|
// Section 2: Product Details
|
||||||
|
checkPageBreak(100)
|
||||||
|
yPos = this.addProductDetailsSection(pdf, productData, yPos, pageWidth, marginLeft, marginRight, checkPageBreak)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add report title
|
||||||
|
*/
|
||||||
|
private static addReportTitle(
|
||||||
|
pdf: any,
|
||||||
|
productData: ProductSalesReport,
|
||||||
|
startY: number,
|
||||||
|
pageWidth: number,
|
||||||
|
marginLeft: number,
|
||||||
|
marginRight: number
|
||||||
|
): number {
|
||||||
|
let yPos = startY
|
||||||
|
|
||||||
|
// Title
|
||||||
|
pdf.setFontSize(20)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
pdf.text('Laporan Penjualan Produk', pageWidth / 2, yPos, { align: 'center' })
|
||||||
|
yPos += 10
|
||||||
|
|
||||||
|
// Period
|
||||||
|
pdf.setFontSize(12)
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
const periodText = `${productData.date_from.split('T')[0]} - ${productData.date_to.split('T')[0]}`
|
||||||
|
pdf.text(periodText, pageWidth / 2, yPos, { align: 'center' })
|
||||||
|
yPos += 10
|
||||||
|
|
||||||
|
// Purple line separator
|
||||||
|
pdf.setDrawColor(102, 45, 145)
|
||||||
|
pdf.setLineWidth(2)
|
||||||
|
pdf.line(marginLeft, yPos, pageWidth - marginRight, yPos)
|
||||||
|
yPos += 15
|
||||||
|
|
||||||
|
return yPos
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add Ringkasan section
|
||||||
|
*/
|
||||||
|
private static addRingkasanSection(
|
||||||
|
pdf: any,
|
||||||
|
productData: ProductSalesReport,
|
||||||
|
startY: number,
|
||||||
|
pageWidth: number,
|
||||||
|
marginLeft: number,
|
||||||
|
marginRight: number,
|
||||||
|
checkPageBreak: (space: number) => boolean
|
||||||
|
): number {
|
||||||
|
let yPos = startY
|
||||||
|
|
||||||
|
// Section title
|
||||||
|
pdf.setFontSize(14)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(102, 45, 145)
|
||||||
|
pdf.text('Ringkasan', marginLeft, yPos)
|
||||||
|
yPos += 12
|
||||||
|
|
||||||
|
// Reset text color
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
pdf.setFontSize(11)
|
||||||
|
|
||||||
|
// Calculate summary
|
||||||
|
const productSummary = {
|
||||||
|
totalQuantitySold: productData.data?.reduce((sum, item) => sum + (item?.quantity_sold || 0), 0) || 0,
|
||||||
|
totalRevenue: productData.data?.reduce((sum, item) => sum + (item?.revenue || 0), 0) || 0,
|
||||||
|
totalOrders: productData.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0,
|
||||||
|
averageRevenue: 0,
|
||||||
|
totalProducts: productData.data?.length || 0
|
||||||
|
}
|
||||||
|
productSummary.averageRevenue =
|
||||||
|
productSummary.totalQuantitySold > 0 ? productSummary.totalRevenue / productSummary.totalQuantitySold : 0
|
||||||
|
|
||||||
|
const ringkasanItems = [
|
||||||
|
{ label: 'Total Produk', value: productSummary.totalProducts.toString(), bold: false },
|
||||||
|
{ label: 'Total Quantity Sold', value: productSummary.totalQuantitySold.toString(), bold: false },
|
||||||
|
{ label: 'Total Orders', value: productSummary.totalOrders.toString(), bold: false },
|
||||||
|
{ label: 'Total Revenue', value: this.formatCurrency(productSummary.totalRevenue), bold: true },
|
||||||
|
{ label: 'Average Revenue per Item', value: this.formatCurrency(productSummary.averageRevenue), bold: false }
|
||||||
|
]
|
||||||
|
|
||||||
|
ringkasanItems.forEach((item, index) => {
|
||||||
|
if (checkPageBreak(15)) yPos = 20
|
||||||
|
|
||||||
|
// Set font weight
|
||||||
|
pdf.setFont('helvetica', item.bold ? 'bold' : 'normal')
|
||||||
|
|
||||||
|
pdf.text(item.label, marginLeft, yPos)
|
||||||
|
pdf.text(item.value, pageWidth - marginRight, yPos, { align: 'right' })
|
||||||
|
|
||||||
|
// Light separator line (except for bold row)
|
||||||
|
if (!item.bold) {
|
||||||
|
pdf.setDrawColor(230, 230, 230)
|
||||||
|
pdf.setLineWidth(0.5)
|
||||||
|
pdf.line(marginLeft, yPos + 2, pageWidth - marginRight, yPos + 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
yPos += 8
|
||||||
|
})
|
||||||
|
|
||||||
|
return yPos + 20
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add Product Details section - SAMA STYLE SEPERTI SALES REPORT
|
||||||
|
*/
|
||||||
|
private static addProductDetailsSection(
|
||||||
|
pdf: any,
|
||||||
|
productData: ProductSalesReport,
|
||||||
|
startY: number,
|
||||||
|
pageWidth: number,
|
||||||
|
marginLeft: number,
|
||||||
|
marginRight: number,
|
||||||
|
checkPageBreak: (space: number) => boolean
|
||||||
|
): number {
|
||||||
|
let yPos = startY
|
||||||
|
|
||||||
|
// Section title
|
||||||
|
pdf.setFontSize(14)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(102, 45, 145)
|
||||||
|
pdf.text('Rincian Produk', marginLeft, yPos)
|
||||||
|
yPos += 12
|
||||||
|
|
||||||
|
// Reset formatting
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
|
||||||
|
// Table setup
|
||||||
|
const tableWidth = pageWidth - marginLeft - marginRight
|
||||||
|
const colWidths = [60, 20, 20, 30, 30] // Product, Qty, Order, Revenue, Average
|
||||||
|
let currentX = marginLeft
|
||||||
|
|
||||||
|
// Table header
|
||||||
|
pdf.setFillColor(240, 240, 240)
|
||||||
|
pdf.rect(marginLeft, yPos, tableWidth, 10, 'F')
|
||||||
|
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
const headers = ['Produk', 'Qty', 'Order', 'Pendapatan', 'Rata Rata']
|
||||||
|
currentX = marginLeft
|
||||||
|
|
||||||
|
headers.forEach((header, index) => {
|
||||||
|
if (index === 0) {
|
||||||
|
pdf.text(header, currentX + 2, yPos + 6)
|
||||||
|
} else {
|
||||||
|
pdf.text(header, currentX + colWidths[index] / 2, yPos + 6, { align: 'center' })
|
||||||
|
}
|
||||||
|
currentX += colWidths[index]
|
||||||
|
})
|
||||||
|
|
||||||
|
yPos += 12
|
||||||
|
|
||||||
|
// Group products by category
|
||||||
|
const groupedProducts =
|
||||||
|
productData.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[]>
|
||||||
|
) || {}
|
||||||
|
|
||||||
|
// Calculate product summary
|
||||||
|
const productSummary = {
|
||||||
|
totalQuantitySold: productData.data?.reduce((sum, item) => sum + (item?.quantity_sold || 0), 0) || 0,
|
||||||
|
totalRevenue: productData.data?.reduce((sum, item) => sum + (item?.revenue || 0), 0) || 0,
|
||||||
|
totalOrders: productData.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Table rows
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
// Render grouped products
|
||||||
|
Object.keys(groupedProducts)
|
||||||
|
.sort()
|
||||||
|
.forEach(categoryName => {
|
||||||
|
const categoryProducts = groupedProducts[categoryName]
|
||||||
|
|
||||||
|
// Check page break for category header
|
||||||
|
if (checkPageBreak(10)) yPos = 20
|
||||||
|
|
||||||
|
// Category header
|
||||||
|
pdf.setFillColor(248, 248, 248) // Soft background
|
||||||
|
pdf.rect(marginLeft, yPos, tableWidth, 10, 'F')
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
pdf.setTextColor(102, 45, 145)
|
||||||
|
pdf.text(categoryName.toUpperCase(), marginLeft + 2, yPos + 6)
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
yPos += 10
|
||||||
|
|
||||||
|
// Category products
|
||||||
|
categoryProducts.forEach((item, index) => {
|
||||||
|
if (checkPageBreak(10)) yPos = 20
|
||||||
|
|
||||||
|
currentX = marginLeft
|
||||||
|
pdf.setFont('helvetica', 'normal')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
|
||||||
|
// Product name (indented and truncated if needed)
|
||||||
|
const productName =
|
||||||
|
item.product_name.length > 45 ? item.product_name.substring(0, 42) + '...' : item.product_name
|
||||||
|
|
||||||
|
pdf.text(` ${productName}`, currentX + 2, yPos + 5) // Indented for products
|
||||||
|
currentX += colWidths[0]
|
||||||
|
|
||||||
|
// Quantity
|
||||||
|
pdf.text(item.quantity_sold.toString(), currentX + colWidths[1] / 2, yPos + 5, { align: 'center' })
|
||||||
|
currentX += colWidths[1]
|
||||||
|
|
||||||
|
// Order count
|
||||||
|
pdf.text((item.order_count || 0).toString(), currentX + colWidths[2] / 2, yPos + 5, { align: 'center' })
|
||||||
|
currentX += colWidths[2]
|
||||||
|
|
||||||
|
// Revenue
|
||||||
|
pdf.text(this.formatCurrency(item.revenue), currentX + colWidths[3] - 2, yPos + 5, { align: 'right' })
|
||||||
|
currentX += colWidths[3]
|
||||||
|
|
||||||
|
// Average price
|
||||||
|
pdf.text(this.formatCurrency(item.average_price), currentX + colWidths[4] - 2, yPos + 5, { align: 'right' })
|
||||||
|
|
||||||
|
// Draw bottom border line
|
||||||
|
pdf.setDrawColor(230, 230, 230)
|
||||||
|
pdf.setLineWidth(0.3)
|
||||||
|
pdf.line(marginLeft, yPos + 8, marginLeft + tableWidth, yPos + 8)
|
||||||
|
|
||||||
|
yPos += 10
|
||||||
|
})
|
||||||
|
|
||||||
|
// Category subtotal
|
||||||
|
if (checkPageBreak(10)) yPos = 20
|
||||||
|
|
||||||
|
const categoryTotalQty = categoryProducts.reduce((sum, item) => sum + (item.quantity_sold || 0), 0)
|
||||||
|
const categoryTotalOrders = categoryProducts.reduce((sum, item) => sum + (item.order_count || 0), 0)
|
||||||
|
const categoryTotalRevenue = categoryProducts.reduce((sum, item) => sum + (item.revenue || 0), 0)
|
||||||
|
|
||||||
|
pdf.setFillColor(240, 240, 240) // Sama dengan table header
|
||||||
|
pdf.rect(marginLeft, yPos, tableWidth, 10, 'F')
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
currentX = marginLeft
|
||||||
|
pdf.text(`Subtotal ${categoryName}`, currentX + 2, yPos + 6)
|
||||||
|
currentX += colWidths[0]
|
||||||
|
|
||||||
|
pdf.text(categoryTotalQty.toString(), currentX + colWidths[1] / 2, yPos + 6, { align: 'center' })
|
||||||
|
currentX += colWidths[1]
|
||||||
|
|
||||||
|
pdf.text(categoryTotalOrders.toString(), currentX + colWidths[2] / 2, yPos + 6, { align: 'center' })
|
||||||
|
currentX += colWidths[2]
|
||||||
|
|
||||||
|
pdf.text(this.formatCurrency(categoryTotalRevenue), currentX + colWidths[3] - 2, yPos + 6, { align: 'right' })
|
||||||
|
|
||||||
|
yPos += 10
|
||||||
|
})
|
||||||
|
|
||||||
|
// Grand total
|
||||||
|
if (checkPageBreak(10)) yPos = 20
|
||||||
|
|
||||||
|
pdf.setFillColor(245, 245, 245) // Lighter gray
|
||||||
|
pdf.rect(marginLeft, yPos, tableWidth, 10, 'F')
|
||||||
|
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setFontSize(9)
|
||||||
|
|
||||||
|
currentX = marginLeft
|
||||||
|
pdf.text('TOTAL KESELURUHAN', currentX + 2, yPos + 6)
|
||||||
|
currentX += colWidths[0]
|
||||||
|
|
||||||
|
pdf.text(productSummary.totalQuantitySold.toString(), currentX + colWidths[1] / 2, yPos + 6, { align: 'center' })
|
||||||
|
currentX += colWidths[1]
|
||||||
|
|
||||||
|
pdf.text(productSummary.totalOrders.toString(), currentX + colWidths[2] / 2, yPos + 6, { align: 'center' })
|
||||||
|
currentX += colWidths[2]
|
||||||
|
|
||||||
|
pdf.text(this.formatCurrency(productSummary.totalRevenue), currentX + colWidths[3] - 2, yPos + 6, {
|
||||||
|
align: 'right'
|
||||||
|
})
|
||||||
|
|
||||||
|
return yPos + 25
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format currency for display
|
||||||
|
*/
|
||||||
|
private static formatCurrency(amount: number): string {
|
||||||
|
return `Rp ${amount.toLocaleString('id-ID')}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate filename with timestamp
|
||||||
|
*/
|
||||||
|
private static generateFilename(prefix: string, extension: string): string {
|
||||||
|
const now = new Date()
|
||||||
|
const year = now.getFullYear()
|
||||||
|
const month = (now.getMonth() + 1).toString().padStart(2, '0')
|
||||||
|
const day = now.getDate().toString().padStart(2, '0')
|
||||||
|
const hour = now.getHours().toString().padStart(2, '0')
|
||||||
|
const minute = now.getMinutes().toString().padStart(2, '0')
|
||||||
|
|
||||||
|
return `${prefix}_${year}_${month}_${day}_${hour}${minute}.${extension}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Export Product Sales data with custom configuration
|
||||||
|
*/
|
||||||
|
static async exportCustomProductToPDF(
|
||||||
|
productData: ProductSalesReport,
|
||||||
|
options?: {
|
||||||
|
title?: string
|
||||||
|
includeSummary?: boolean
|
||||||
|
customFilename?: string
|
||||||
|
groupByCategory?: boolean
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const jsPDFModule = await import('jspdf')
|
||||||
|
const jsPDF = jsPDFModule.default
|
||||||
|
|
||||||
|
const pdf = new jsPDF('p', 'mm', 'a4')
|
||||||
|
|
||||||
|
let yPos = 20
|
||||||
|
const pageWidth = pdf.internal.pageSize.getWidth()
|
||||||
|
const pageHeight = pdf.internal.pageSize.getHeight()
|
||||||
|
const marginLeft = 20
|
||||||
|
const marginRight = 20
|
||||||
|
const marginBottom = 15
|
||||||
|
|
||||||
|
const checkPageBreak = (neededSpace: number) => {
|
||||||
|
if (yPos + neededSpace > pageHeight - marginBottom) {
|
||||||
|
pdf.addPage()
|
||||||
|
yPos = 20
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Custom title if provided
|
||||||
|
if (options?.title) {
|
||||||
|
pdf.setFontSize(20)
|
||||||
|
pdf.setFont('helvetica', 'bold')
|
||||||
|
pdf.setTextColor(0, 0, 0)
|
||||||
|
pdf.text(options.title, pageWidth / 2, yPos, { align: 'center' })
|
||||||
|
yPos += 15
|
||||||
|
} else {
|
||||||
|
yPos = this.addReportTitle(pdf, productData, yPos, pageWidth, marginLeft, marginRight)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Optional summary section
|
||||||
|
if (options?.includeSummary !== false) {
|
||||||
|
checkPageBreak(50)
|
||||||
|
yPos = this.addRingkasanSection(pdf, productData, yPos, pageWidth, marginLeft, marginRight, checkPageBreak)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Product details
|
||||||
|
checkPageBreak(100)
|
||||||
|
yPos = this.addProductDetailsSection(pdf, productData, yPos, pageWidth, marginLeft, marginRight, checkPageBreak)
|
||||||
|
|
||||||
|
const exportFilename = options?.customFilename || this.generateFilename('Custom_Product_Sales', 'pdf')
|
||||||
|
pdf.save(exportFilename)
|
||||||
|
|
||||||
|
return { success: true, filename: exportFilename }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error exporting custom product report to PDF:', error)
|
||||||
|
return { success: false, error: `PDF export failed: ${(error as Error).message}` }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,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,52 @@
|
|||||||
|
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'] })
|
||||||
|
},
|
||||||
|
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}`, payload)
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('Purchase Order Payment successfully!')
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['purchase-orders'] })
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const updateStatus = useMutation({
|
||||||
|
mutationFn: async ({ id, payload }: { id: string; payload: 'approved' | 'rejected' }) => {
|
||||||
|
const response = await api.put(`/purchase-orders/${id}`, { status: payload })
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('Purchase Order Status successfully!')
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['purchase-orders'] })
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return { createPurchaseOrder, sendPaymentPurchaseOrder, updateStatus }
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -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,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 { useQuery } from '@tanstack/react-query'
|
||||||
import { Ingredients } from '../../types/services/ingredient'
|
import { Ingredients } from '../../types/services/ingredient'
|
||||||
import { api } from '../api'
|
import { api } from '../api'
|
||||||
|
import { Ingredient } from '@/types/services/productRecipe'
|
||||||
|
|
||||||
interface IngredientsQueryParams {
|
interface IngredientsQueryParams {
|
||||||
page?: number
|
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
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
@@ -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
|
total: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface IngredientItem {
|
|
||||||
id: number
|
|
||||||
ingredient: { label: string; value: string } | null
|
|
||||||
deskripsi: string
|
|
||||||
kuantitas: number
|
|
||||||
satuan: { label: string; value: string } | null
|
|
||||||
discount: string
|
|
||||||
harga: number
|
|
||||||
pajak: { label: string; value: string } | null
|
|
||||||
waste: { label: string; value: string } | null
|
|
||||||
total: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface PurchaseOrderFormData {
|
|
||||||
vendor: { label: string; value: string } | null
|
|
||||||
nomor: string
|
|
||||||
tglTransaksi: string
|
|
||||||
tglJatuhTempo: string
|
|
||||||
referensi: string
|
|
||||||
termin: { label: string; value: string } | null
|
|
||||||
hargaTermasukPajak: boolean
|
|
||||||
showShippingInfo: boolean
|
|
||||||
tanggalPengiriman: string
|
|
||||||
ekspedisi: { label: string; value: string } | null
|
|
||||||
noResi: string
|
|
||||||
showPesan: boolean
|
|
||||||
showAttachment: boolean
|
|
||||||
showTambahDiskon: boolean
|
|
||||||
showBiayaPengiriman: boolean
|
|
||||||
showBiayaTransaksi: boolean
|
|
||||||
showUangMuka: boolean
|
|
||||||
pesan: string
|
|
||||||
ingredientItems: IngredientItem[]
|
|
||||||
transactionCosts?: TransactionCost[]
|
|
||||||
subtotal?: number
|
|
||||||
discountType?: 'percentage' | 'fixed'
|
|
||||||
downPaymentType?: 'percentage' | 'fixed'
|
|
||||||
discountValue?: string
|
|
||||||
shippingCost?: string
|
|
||||||
transactionCost?: string
|
|
||||||
downPayment?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface TransactionCost {
|
export interface TransactionCost {
|
||||||
id: string
|
id: string
|
||||||
type: string
|
type: string
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
export interface ChartOfAccountType {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
code: string
|
||||||
|
description: string
|
||||||
|
is_active: boolean
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChartOfAccountTypes {
|
||||||
|
data: ChartOfAccountType[]
|
||||||
|
limit: number
|
||||||
|
page: number
|
||||||
|
total: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChartOfAccount {
|
||||||
|
id: string
|
||||||
|
organization_id: string
|
||||||
|
outlet_id: string
|
||||||
|
chart_of_account_type_id: string
|
||||||
|
parent_id: string
|
||||||
|
name: string
|
||||||
|
code: string
|
||||||
|
description: string
|
||||||
|
is_active: boolean
|
||||||
|
is_system: boolean
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
chart_of_account_type: ChartOfAccountType
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChartOfAccounts {
|
||||||
|
data: ChartOfAccount[]
|
||||||
|
limit: number
|
||||||
|
page: number
|
||||||
|
total: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Account {
|
||||||
|
id: string
|
||||||
|
organization_id: string
|
||||||
|
outlet_id: string
|
||||||
|
chart_of_account_id: string
|
||||||
|
name: string
|
||||||
|
number: string
|
||||||
|
account_type: string
|
||||||
|
opening_balance: number
|
||||||
|
current_balance: number
|
||||||
|
description: string
|
||||||
|
is_active: true
|
||||||
|
is_system: false
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
chart_of_account: ChartOfAccount
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Accounts {
|
||||||
|
data: Account[]
|
||||||
|
limit: number
|
||||||
|
page: number
|
||||||
|
total: number
|
||||||
|
}
|
||||||
@@ -1,29 +1,40 @@
|
|||||||
export interface Customer {
|
export interface Customer {
|
||||||
id: string;
|
id: string
|
||||||
organization_id: string;
|
organization_id: string
|
||||||
name: string;
|
name: string
|
||||||
email?: string;
|
email?: string
|
||||||
phone?: string;
|
phone?: string
|
||||||
address?: string;
|
address?: string
|
||||||
is_default: boolean;
|
is_default: boolean
|
||||||
is_active: boolean;
|
is_active: boolean
|
||||||
metadata: Record<string, any>;
|
metadata: Record<string, any>
|
||||||
created_at: string;
|
created_at: string
|
||||||
updated_at: string;
|
updated_at: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Customers {
|
export interface Customers {
|
||||||
data: Customer[];
|
data: Customer[]
|
||||||
total_count: number;
|
total_count: number
|
||||||
page: number;
|
page: number
|
||||||
limit: number;
|
limit: number
|
||||||
total_pages: number;
|
total_pages: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CustomerRequest {
|
export interface CustomerRequest {
|
||||||
name: string;
|
name: string
|
||||||
email?: string;
|
email?: string
|
||||||
phone?: string;
|
phone?: string
|
||||||
address?: string;
|
address?: string
|
||||||
is_active?: boolean;
|
is_active?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CustomerAnalytics {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
email?: string
|
||||||
|
phone?: string
|
||||||
|
totalPoints: number
|
||||||
|
totalSpent?: number
|
||||||
|
loyaltyTier?: string // Bronze, Silver, Gold, dst
|
||||||
|
lastTransactionDate?: Date
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,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 {
|
export interface Product {
|
||||||
ID: string;
|
ID: string
|
||||||
OrganizationID: string;
|
OrganizationID: string
|
||||||
CategoryID: string;
|
CategoryID: string
|
||||||
SKU: string;
|
SKU: string
|
||||||
Name: string;
|
Name: string
|
||||||
Description: string | null;
|
Description: string | null
|
||||||
Price: number;
|
Price: number
|
||||||
Cost: number;
|
Cost: number
|
||||||
BusinessType: string;
|
BusinessType: string
|
||||||
ImageURL: string;
|
ImageURL: string
|
||||||
PrinterType: string;
|
PrinterType: string
|
||||||
UnitID: string | null;
|
UnitID: string | null
|
||||||
HasIngredients: boolean;
|
HasIngredients: boolean
|
||||||
Metadata: Record<string, any>;
|
Metadata: Record<string, any>
|
||||||
IsActive: boolean;
|
IsActive: boolean
|
||||||
CreatedAt: string; // ISO date string
|
CreatedAt: string // ISO date string
|
||||||
UpdatedAt: string; // ISO date string
|
UpdatedAt: string // ISO date string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Ingredient {
|
export interface Ingredient {
|
||||||
id: string;
|
id: string
|
||||||
organization_id: string;
|
organization_id: string
|
||||||
outlet_id: string | null;
|
outlet_id: string | null
|
||||||
name: string;
|
name: string
|
||||||
unit_id: string;
|
unit_id: string
|
||||||
cost: number;
|
cost: number
|
||||||
stock: number;
|
stock: number
|
||||||
is_semi_finished: boolean;
|
is_semi_finished: boolean
|
||||||
is_active: boolean;
|
is_active: boolean
|
||||||
metadata: Record<string, any>;
|
metadata: Record<string, any>
|
||||||
created_at: string;
|
created_at: string
|
||||||
updated_at: string;
|
updated_at: string
|
||||||
|
unit: IngredientUnit
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ProductRecipe {
|
export interface ProductRecipe {
|
||||||
id: string;
|
id: string
|
||||||
organization_id: string;
|
organization_id: string
|
||||||
outlet_id: string | null;
|
outlet_id: string | null
|
||||||
product_id: string;
|
product_id: string
|
||||||
variant_id: string | null;
|
variant_id: string | null
|
||||||
ingredient_id: string;
|
ingredient_id: string
|
||||||
quantity: number;
|
quantity: number
|
||||||
created_at: string;
|
waste: number
|
||||||
updated_at: string;
|
created_at: string
|
||||||
product: Product;
|
updated_at: string
|
||||||
ingredient: Ingredient;
|
product: Product
|
||||||
|
ingredient: Ingredient
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ProductRecipeRequest {
|
export interface ProductRecipeRequest {
|
||||||
product_id: string;
|
product_id: string
|
||||||
variant_id: string | null;
|
variant_id: string | null
|
||||||
ingredient_id: string;
|
ingredient_id: string
|
||||||
quantity: number;
|
quantity: number
|
||||||
outlet_id: string | null;
|
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
|
||||||
|
}
|
||||||
@@ -43,6 +43,15 @@ export const formatDateDDMMYYYY = (dateString: Date | string) => {
|
|||||||
return `${day}-${month}-${year}`
|
return `${day}-${month}-${year}`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const formatDateYYYYMMDD = (dateString: Date | string) => {
|
||||||
|
const date = new Date(dateString)
|
||||||
|
date.setHours(0, 0, 0, 0)
|
||||||
|
const day = String(date.getDate()).padStart(2, '0')
|
||||||
|
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||||
|
const year = date.getFullYear()
|
||||||
|
return `${year}-${month}-${day}`
|
||||||
|
}
|
||||||
|
|
||||||
export const formatForInputDate = (dateString: Date | string) => {
|
export const formatForInputDate = (dateString: Date | string) => {
|
||||||
const date = new Date(dateString)
|
const date = new Date(dateString)
|
||||||
const day = String(date.getDate()).padStart(2, '0')
|
const day = String(date.getDate()).padStart(2, '0')
|
||||||
@@ -51,7 +60,6 @@ export const formatForInputDate = (dateString: Date | string) => {
|
|||||||
return `${year}-${month}-${day}`
|
return `${year}-${month}-${day}`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export const formatDatetime = (dateString: string | number | Date) => {
|
export const formatDatetime = (dateString: string | number | Date) => {
|
||||||
const date = new Date(dateString)
|
const date = new Date(dateString)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
// MUI Imports
|
||||||
|
import { styled } from '@mui/material/styles'
|
||||||
|
|
||||||
|
// Styled Component
|
||||||
|
const AuthIllustrationWrapper = styled('div')(({ theme }) => ({
|
||||||
|
width: '100%',
|
||||||
|
maxWidth: 450,
|
||||||
|
position: 'relative',
|
||||||
|
[theme.breakpoints.up('md')]: {
|
||||||
|
'&:before': {
|
||||||
|
zIndex: -1,
|
||||||
|
position: 'absolute',
|
||||||
|
height: '234px',
|
||||||
|
width: '238px',
|
||||||
|
content: '""',
|
||||||
|
top: '-80px',
|
||||||
|
left: '-45px',
|
||||||
|
backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='238' height='234' viewBox='0 0 238 234' fill='none'%3E%3Crect x='87.9395' y='0.5' width='149' height='149' rx='19.5' stroke='%23${theme.palette.primary.main.slice(
|
||||||
|
1
|
||||||
|
)}' stroke-opacity='0.16'/%3E%3Crect y='33.5608' width='200' height='200' rx='10' fill='%23${theme.palette.primary.main.slice(
|
||||||
|
1
|
||||||
|
)}' fill-opacity='0.08'/%3E%3C/svg%3E")`
|
||||||
|
},
|
||||||
|
'&:after': {
|
||||||
|
zIndex: -1,
|
||||||
|
position: 'absolute',
|
||||||
|
height: '180px',
|
||||||
|
width: '180px',
|
||||||
|
content: '""',
|
||||||
|
right: '-57px',
|
||||||
|
bottom: '-64px',
|
||||||
|
backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='180' height='180' viewBox='0 0 180 180' fill='none'%3E%3Crect x='1' y='1' width='178' height='178' rx='19' stroke='%23${theme.palette.primary.main.slice(
|
||||||
|
1
|
||||||
|
)}' stroke-opacity='0.16' stroke-width='2' stroke-dasharray='8 8'/%3E%3Crect x='22.5' y='22.5' width='135' height='135' rx='10' fill='%23${theme.palette.primary.main.slice(
|
||||||
|
1
|
||||||
|
)}' fill-opacity='0.08'/%3E%3C/svg%3E")`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
|
||||||
|
export default AuthIllustrationWrapper
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user