Jelajahi Sumber

add the next and return page

gdias 4 bulan lalu
induk
melakukan
8c5d35c745
1 mengubah file dengan 66 tambahan dan 44 penghapusan
  1. 66 44
      src/lib/component/Report.svelte

+ 66 - 44
src/lib/component/Report.svelte

@@ -16,6 +16,7 @@
 	let orderId = null;
 	let csvDownload = [];
 	let topItems = [];
+	let defaultPage = 0;
 
 	if (browser) {
 		token = localStorage.getItem('token');
@@ -24,13 +25,31 @@
 	}
 
 	onMount(async () => {
+		fetchAllData();
+	});
+
+	function returnTable() {
+		if (defaultPage == 0) {
+			console.log('nao a pagina anterior');
+		} else {
+			defaultPage--;
+			fetchAllData();
+		}
+	}
+
+	function nextTable() {
+		defaultPage++;
+		fetchAllData();
+	}
+
+	async function fetchAllData() {
 		const myHeaders = new Headers();
 		myHeaders.append('Authorization', `Bearer ${token}`);
 		myHeaders.append('Content-Type', 'application/json');
 
 		const raw = JSON.stringify({
 			company_id: company,
-			page: 1,
+			page: 1 + defaultPage,
 			limit: 10
 		});
 
@@ -44,8 +63,6 @@
 		try {
 			const response = await fetch('https://dev2.mixtech.dev.br/reports/get', requestOptions);
 			const result = await response.json();
-			csvDownload = result;
-			console.log(result);
 
 			if (result.status === 'ok' && result.data) {
 				sales = result.data.orders.map((order) => ({
@@ -72,34 +89,6 @@
 		} catch (error) {
 			console.error('Erro ao buscar dados:', error);
 		}
-	});
-	function exportarCSV() {
-		if (!csvDownload.length) return;
-
-		const headers = ['order_item_id', 'product_name', 'product_price', 'product_is_kitchen'];
-
-		const linhas = [
-			headers.join(','),
-			...csvDownload.map((pedido) => {
-				const produto = pedido.product_details;
-				return [
-					pedido.order_item_id,
-					JSON.stringify(produto.product_name ?? ''),
-					produto.product_price,
-					produto.product_is_kitchen
-				].join(',');
-			})
-		];
-
-		const csvContent = linhas.join('\n');
-
-		const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
-		const url = URL.createObjectURL(blob);
-		const link = document.createElement('a');
-		link.href = url;
-		link.setAttribute('download', 'csvDownload.csv');
-		link.click();
-		URL.revokeObjectURL(url);
 	}
 
 	function formatDate(dateStr) {
@@ -183,15 +172,38 @@
 		}
 	}
 
-	function exportToCSV() {
+	async function exportToCSV() {
+		// Fetch todos os pedidos (sem paginação ou com paginação completa)
+		const myHeaders = new Headers();
+		myHeaders.append('Authorization', `Bearer ${token}`);
+		myHeaders.append('Content-Type', 'application/json');
+
+		const raw = JSON.stringify({
+			company_id: company
+		});
+
+		const requestOptions = {
+			method: 'POST',
+			headers: myHeaders,
+			body: raw
+		};
+
+		const response = await fetch('https://dev2.mixtech.dev.br/reports/get', requestOptions);
+		const result = await response.json();
+		const orders = result?.data?.orders || [];
+
 		const headers = ['Data', 'Mesa', 'Itens', 'Total', 'Forma de Pagamento'];
-		const rows = filteredSales.map((sale) => [
-			formatDate(sale.timestamp),
-			`Mesa ${sale.tableId}`,
-			sale.items.map((item) => `${item.quantity}x ${item.productName}`).join(', '),
-			`R$ ${sale.totalAmount.toFixed(2)}`,
-			getPaymentMethodName(sale.paymentMethod)
-		]);
+		const rows = orders.map((order) => {
+			const items = order.items.map((item) => `${item.product_name}`).join(', ');
+			return [
+				order.order_finished_at,
+				`Mesa ${order.table_id}`,
+				items,
+				`R$ ${order.items.reduce((a, b) => a + Number(b.product_price), 0).toFixed(2)}`,
+				order.order_flag
+			];
+		});
+
 		const csv = [headers, ...rows].map((row) => row.join(',')).join('\n');
 		const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
 		const url = URL.createObjectURL(blob);
@@ -213,7 +225,6 @@
 
 <div class="flex w-full flex-col rounded-md bg-stone-800 p-4">
 	<div class="flex flex-grow flex-col">
-		<!-- Cabeçalho e botões de ação -->
 		<div class="mb-6 flex flex-col justify-between md:flex-row md:items-center">
 			<h1 class="mb-4 text-2xl font-bold md:mb-0">Relatório de Vendas</h1>
 			<div class="flex w-full flex-col gap-2 sm:flex-row sm:justify-end md:w-auto">
@@ -276,10 +287,10 @@
 							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]"
 						>
 							<option value="">Todas</option>
-							<option value="CASH">Dinheiro</option>
+							<option value="Dinheiro">Dinheiro</option>
 							<option value="PIX">Pix</option>
-							<option value="DEBIT">Cartão de Débito</option>
-							<option value="CREDIT">Cartão de Crédito</option>
+							<option value="Cartão de Débito">Cartão de Débito</option>
+							<option value="Cartão de Crédito">Cartão de Crédito</option>
 						</select>
 					</div>
 				</div>
@@ -370,7 +381,18 @@
 				</tbody>
 			</table>
 		</div>
-
+		<div class="ml-2 mr-2 mt-2 flex justify-between">
+			<button
+				on:click={returnTable}
+				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"
+				>Anterior</button
+			>
+			<button
+				on:click={nextTable}
+				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"
+				>Próximo</button
+			>
+		</div>
 		<div class="rounded-lg bg-[#2C2C2E] shadow-lg sm:hidden">
 			<div class="divide-y divide-gray-700">
 				{#if filteredSales.length === 0}