Report.svelte 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. <script>
  2. import { onMount } from 'svelte';
  3. import { browser } from '$app/environment';
  4. let sales = [];
  5. let dateFilter = '';
  6. let paymentMethodFilter = '';
  7. let searchTerm = '';
  8. let sortBy = 'date';
  9. let sortDirection = 'desc';
  10. let selectedSale = null;
  11. let totalSales = null;
  12. let token = null;
  13. let company = null;
  14. let orderId = null;
  15. let csvDownload = [];
  16. let topItems = [];
  17. if (browser) {
  18. token = localStorage.getItem('token');
  19. company = Number(localStorage.getItem('company'));
  20. orderId = Number(localStorage.getItem('order'));
  21. }
  22. onMount(async () => {
  23. const myHeaders = new Headers();
  24. myHeaders.append('Authorization', `Bearer ${token}`);
  25. myHeaders.append('Content-Type', 'application/json');
  26. const raw = JSON.stringify({
  27. company_id: company,
  28. page: 1,
  29. limit: 10
  30. });
  31. const requestOptions = {
  32. method: 'POST',
  33. headers: myHeaders,
  34. body: raw,
  35. redirect: 'follow'
  36. };
  37. try {
  38. const response = await fetch('https://dev2.mixtech.dev.br/reports/get', requestOptions);
  39. const result = await response.json();
  40. csvDownload = result;
  41. console.log(result);
  42. if (result.status === 'ok' && result.data) {
  43. sales = result.data.orders.map((order) => ({
  44. id: order.order_id,
  45. timestamp: order.order_finished_at?.trim()
  46. ? order.order_finished_at
  47. : new Date().toISOString(),
  48. tableId: order.table_id,
  49. items: order.items.map((item) => ({
  50. productName: item.product_name,
  51. quantity: 1,
  52. priceAtSale: parseFloat(item.product_price)
  53. })),
  54. totalAmount: order.items.reduce((sum, item) => sum + parseFloat(item.product_price), 0),
  55. paymentMethod: order.order_flag
  56. }));
  57. totalSales = Number(result.data.total_sales).toFixed(2);
  58. topItems = result.data.top_items;
  59. console.log(topItems);
  60. } else {
  61. console.error('Erro na resposta da API:', result.msg);
  62. }
  63. } catch (error) {
  64. console.error('Erro ao buscar dados:', error);
  65. }
  66. });
  67. function exportarCSV() {
  68. if (!csvDownload.length) return;
  69. const headers = ['order_item_id', 'product_name', 'product_price', 'product_is_kitchen'];
  70. const linhas = [
  71. headers.join(','),
  72. ...csvDownload.map((pedido) => {
  73. const produto = pedido.product_details;
  74. return [
  75. pedido.order_item_id,
  76. JSON.stringify(produto.product_name ?? ''),
  77. produto.product_price,
  78. produto.product_is_kitchen
  79. ].join(',');
  80. })
  81. ];
  82. const csvContent = linhas.join('\n');
  83. const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  84. const url = URL.createObjectURL(blob);
  85. const link = document.createElement('a');
  86. link.href = url;
  87. link.setAttribute('download', 'csvDownload.csv');
  88. link.click();
  89. URL.revokeObjectURL(url);
  90. }
  91. function formatDate(dateStr) {
  92. const date = new Date(dateStr);
  93. return `${date.toLocaleDateString()} ${date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
  94. }
  95. function getPaymentMethodName(method) {
  96. return (
  97. {
  98. CASH: 'Dinheiro',
  99. PIX: 'Pix',
  100. DEBIT: 'Cartão de Débito',
  101. CREDIT: 'Cartão de Crédito'
  102. }[method] || method
  103. );
  104. }
  105. $: filteredSales = sales
  106. .filter((sale) => {
  107. const saleDate = new Date(sale.timestamp).toISOString().slice(0, 10);
  108. const includesSearchTerm = sale.items.some((item) =>
  109. item.productName.toLowerCase().includes(searchTerm.toLowerCase())
  110. );
  111. return (
  112. (!dateFilter || saleDate === dateFilter) &&
  113. (!paymentMethodFilter || sale.paymentMethod === paymentMethodFilter) &&
  114. (!searchTerm || includesSearchTerm)
  115. );
  116. })
  117. .sort((a, b) => {
  118. if (sortBy === 'date') {
  119. return sortDirection === 'asc'
  120. ? new Date(a.timestamp) - new Date(b.timestamp)
  121. : new Date(b.timestamp) - new Date(a.timestamp);
  122. } else {
  123. return sortDirection === 'asc'
  124. ? a.totalAmount - b.totalAmount
  125. : b.totalAmount - a.totalAmount;
  126. }
  127. });
  128. $: salesSummary = {
  129. total: filteredSales.reduce((sum, sale) => sum + sale.totalAmount, 0),
  130. count: filteredSales.reduce(
  131. (sum, sale) => sum + sale.items.reduce((itemSum, item) => itemSum + item.quantity, 0),
  132. 0
  133. ),
  134. byPaymentMethod: {
  135. cash: filteredSales
  136. .filter((s) => s.paymentMethod === 'CASH')
  137. .reduce((sum, s) => sum + s.totalAmount, 0),
  138. pix: filteredSales
  139. .filter((s) => s.paymentMethod === 'PIX')
  140. .reduce((sum, s) => sum + s.totalAmount, 0),
  141. debit: filteredSales
  142. .filter((s) => s.paymentMethod === 'DEBIT')
  143. .reduce((sum, s) => sum + s.totalAmount, 0),
  144. credit: filteredSales
  145. .filter((s) => s.paymentMethod === 'CREDIT')
  146. .reduce((sum, s) => sum + s.totalAmount, 0)
  147. },
  148. topProducts: Object.entries(
  149. filteredSales
  150. .flatMap((s) => s.items)
  151. .reduce((acc, item) => {
  152. if (!acc[item.productName]) acc[item.productName] = { quantity: 0, total: 0 };
  153. acc[item.productName].quantity += item.quantity;
  154. acc[item.productName].total += (item.priceAtSale || 0) * item.quantity;
  155. return acc;
  156. }, {})
  157. ).sort((a, b) => b[1].quantity - a[1].quantity)
  158. };
  159. function toggleSort(field) {
  160. if (sortBy === field) {
  161. sortDirection = sortDirection === 'asc' ? 'desc' : 'asc';
  162. } else {
  163. sortBy = field;
  164. sortDirection = 'desc';
  165. }
  166. }
  167. function exportToCSV() {
  168. const headers = ['Data', 'Mesa', 'Itens', 'Total', 'Forma de Pagamento'];
  169. const rows = filteredSales.map((sale) => [
  170. formatDate(sale.timestamp),
  171. `Mesa ${sale.tableId}`,
  172. sale.items.map((item) => `${item.quantity}x ${item.productName}`).join(', '),
  173. `R$ ${sale.totalAmount.toFixed(2)}`,
  174. getPaymentMethodName(sale.paymentMethod)
  175. ]);
  176. const csv = [headers, ...rows].map((row) => row.join(',')).join('\n');
  177. const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
  178. const url = URL.createObjectURL(blob);
  179. const link = document.createElement('a');
  180. link.href = url;
  181. link.download = `relatorio_vendas_${new Date().toISOString().slice(0, 10)}.csv`;
  182. document.body.appendChild(link);
  183. link.click();
  184. document.body.removeChild(link);
  185. }
  186. function handleCancelSale(id) {
  187. if (confirm('Tem certeza que deseja cancelar esta venda?')) {
  188. sales = sales.filter((sale) => sale.id !== id);
  189. selectedSale = null;
  190. }
  191. }
  192. </script>
  193. <div class="flex w-full flex-col rounded-md bg-stone-800 p-4">
  194. <div class="flex flex-grow flex-col">
  195. <!-- Cabeçalho e botões de ação -->
  196. <div class="mb-6 flex flex-col justify-between md:flex-row md:items-center">
  197. <h1 class="mb-4 text-2xl font-bold md:mb-0">Relatório de Vendas</h1>
  198. <div class="flex w-full flex-col gap-2 sm:flex-row sm:justify-end md:w-auto">
  199. <button
  200. on:click={exportToCSV}
  201. disabled={filteredSales.length === 0}
  202. class=" flex w-full items-center justify-center rounded-lg bg-[#D4AF37] px-4 py-2 text-[#1C1C1E] transition-colors hover:bg-[#3C3C3E] disabled:cursor-not-allowed sm:w-auto"
  203. >
  204. Exportar CSV
  205. </button>
  206. </div>
  207. </div>
  208. <div class="mb-6 grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4">
  209. <div class="rounded-lg bg-[#2C2C2E] p-4">
  210. <h3 class="mb-2 text-sm text-[#A0A0A0]">Total em Vendas</h3>
  211. <p class="text-2xl font-bold text-[#D4AF37]">R$ {totalSales}</p>
  212. </div>
  213. <div class="rounded-lg bg-[#2C2C2E] p-4">
  214. <h3 class="mb-2 text-sm text-[#A0A0A0]">Produtos Mais Vendidos</h3>
  215. <div class="space-y-1">
  216. {#each topItems as topItem}
  217. <div class="flex justify-between text-sm">
  218. <span class="text-white">{topItem.product_name}</span>
  219. <span class="text-[#A0A0A0]">{topItem.sold_quantity}x</span>
  220. </div>
  221. {/each}
  222. </div>
  223. </div>
  224. </div>
  225. <div class="mb-6 rounded-lg bg-[#2C2C2E] p-4 shadow-lg">
  226. <div class="flex flex-col flex-wrap items-start gap-4 md:flex-row md:items-center">
  227. <div class="w-full flex-grow md:w-auto">
  228. <label for="dateFilter" class="mb-1 block text-sm font-medium text-[#A0A0A0]">Data</label>
  229. <div class="relative">
  230. <div
  231. class="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3 text-[#A0A0A0]"
  232. ></div>
  233. <input
  234. type="date"
  235. id="dateFilter"
  236. bind:value={dateFilter}
  237. class="block w-full rounded-md border border-[#A0A0A0]/20 bg-[#1C1C1E] py-2 pl-10 pr-3 text-white focus:outline-none focus:ring-2 focus:ring-[#D4AF37]"
  238. />
  239. </div>
  240. </div>
  241. <div class="w-full flex-grow md:w-auto">
  242. <label for="paymentMethodFilter" class="mb-1 block text-sm font-medium text-[#A0A0A0]"
  243. >Forma de Pagamento</label
  244. >
  245. <div class="relative">
  246. <div
  247. class="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3 text-[#A0A0A0]"
  248. ></div>
  249. <select
  250. id="paymentMethodFilter"
  251. bind:value={paymentMethodFilter}
  252. class="block w-full rounded-md border border-[#A0A0A0]/20 bg-[#1C1C1E] py-2 pl-10 pr-3 text-white focus:outline-none focus:ring-2 focus:ring-[#D4AF37]"
  253. >
  254. <option value="">Todas</option>
  255. <option value="CASH">Dinheiro</option>
  256. <option value="PIX">Pix</option>
  257. <option value="DEBIT">Cartão de Débito</option>
  258. <option value="CREDIT">Cartão de Crédito</option>
  259. </select>
  260. </div>
  261. </div>
  262. <div class="w-full flex-grow md:flex-1">
  263. <label for="searchTerm" class="mb-1 block text-sm font-medium text-[#A0A0A0]"
  264. >Buscar Produtos</label
  265. >
  266. <div class="relative">
  267. <div
  268. class="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3 text-[#A0A0A0]"
  269. ></div>
  270. <input
  271. type="text"
  272. id="searchTerm"
  273. bind:value={searchTerm}
  274. placeholder="Busque por nome de produto..."
  275. class="block w-full rounded-md border border-[#A0A0A0]/20 bg-[#1C1C1E] py-2 pl-10 pr-3 text-white focus:outline-none focus:ring-2 focus:ring-[#D4AF37]"
  276. />
  277. </div>
  278. </div>
  279. <div class="mt-6 w-full self-end md:mt-0 md:w-auto">
  280. <button
  281. on:click={() => {
  282. dateFilter = '';
  283. paymentMethodFilter = '';
  284. searchTerm = '';
  285. }}
  286. class="flex w-full items-center justify-center rounded-lg bg-[#1C1C1E] px-4 py-2 transition-colors hover:bg-[#2C2C2E]"
  287. >
  288. Limpar Filtros
  289. </button>
  290. </div>
  291. </div>
  292. </div>
  293. <div class="hidden overflow-hidden rounded-lg bg-[#2C2C2E] shadow-lg sm:block">
  294. <table class="min-w-full divide-y divide-gray-700">
  295. <thead class="sticky top-0 z-10 bg-[#1C1C1E]">
  296. <tr>
  297. <th
  298. class="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-[#A0A0A0]"
  299. >
  300. <button on:click={() => toggleSort('date')} class="flex items-center">
  301. Data/Hora
  302. </button>
  303. </th>
  304. <th>Mesa</th>
  305. <th>Itens</th>
  306. <th>
  307. <button on:click={() => toggleSort('amount')} class="flex items-center">
  308. Total
  309. </button>
  310. </th>
  311. <th>Pagamento</th>
  312. </tr>
  313. </thead>
  314. <tbody class="divide-y divide-gray-700 bg-[#2C2C2E]">
  315. {#if filteredSales.length === 0}
  316. <tr>
  317. <td colspan="6" class="px-6 py-4 text-center text-[#A0A0A0]"
  318. >Nenhuma venda encontrada</td
  319. >
  320. </tr>
  321. {:else}
  322. {#each filteredSales as sale}
  323. <tr class="cursor-pointer hover:bg-[#3C3C3E]" on:click={() => (selectedSale = sale)}>
  324. <td class="whitespace-nowrap px-6 py-4 text-sm">{formatDate(sale.timestamp)}</td>
  325. <td class="whitespace-nowrap px-6 py-4 text-sm">Mesa {sale.tableId}</td>
  326. <td class="px-6 py-4 text-sm">
  327. <div class="line-clamp-1">
  328. {#each sale.items as item, i}
  329. {#if i > 0},
  330. {/if}{item.quantity}x {item.productName}
  331. {/each}
  332. </div>
  333. </td>
  334. <td class="whitespace-nowrap px-6 py-4 text-sm font-medium"
  335. >R$ {sale.totalAmount.toFixed(2)}</td
  336. >
  337. <td class="whitespace-nowrap px-6 py-4 text-sm"
  338. >{getPaymentMethodName(sale.paymentMethod)}</td
  339. >
  340. </tr>
  341. {/each}
  342. {/if}
  343. </tbody>
  344. </table>
  345. </div>
  346. <div class="rounded-lg bg-[#2C2C2E] shadow-lg sm:hidden">
  347. <div class="divide-y divide-gray-700">
  348. {#if filteredSales.length === 0}
  349. <div class="p-4 text-center text-[#A0A0A0]">Nenhuma venda encontrada</div>
  350. {:else}
  351. {#each filteredSales as sale}
  352. <div
  353. class="flex cursor-pointer flex-col space-y-2 p-4 hover:bg-[#3C3C3E]"
  354. on:click={() => (selectedSale = sale)}
  355. >
  356. <div class="flex items-center justify-between">
  357. <span class="text-sm font-medium">{formatDate(sale.timestamp)}</span>
  358. <span class="text-sm font-medium">Mesa {sale.tableId}</span>
  359. </div>
  360. <div class="flex items-center justify-between">
  361. <span class="text-sm text-[#A0A0A0]">Total:</span>
  362. <span class="text-base font-bold text-white">R$ {sale.totalAmount.toFixed(2)}</span>
  363. </div>
  364. <div class="text-xs text-[#A0A0A0]">
  365. Itens: <span class="line-clamp-1 text-white"
  366. >{sale.items
  367. .map((item) => `${item.quantity}x ${item.productName}`)
  368. .join(', ')}</span
  369. >
  370. </div>
  371. <div class="text-xs text-[#A0A0A0]">
  372. Pagamento: <span class="text-white">{getPaymentMethodName(sale.paymentMethod)}</span
  373. >
  374. </div>
  375. <!-- <div class="mt-2 flex justify-end">
  376. <button
  377. on:click|stopPropagation={() => handleCancelSale(sale.id)}
  378. class="rounded-lg p-1.5 text-[#FF3B30] hover:bg-[#FF3B30]/20"
  379. >
  380. </button>
  381. </div> -->
  382. </div>
  383. {/each}
  384. {/if}
  385. </div>
  386. </div>
  387. </div>
  388. </div>