Parcourir la source

fix the routes

gdias il y a 4 mois
Parent
commit
a17f4133c3

+ 57 - 150
src/lib/component/AddProducts.svelte

@@ -22,44 +22,25 @@
 	}
 
 	let selectedCategory = null;
-	let isPaymentModalOpen = false;
-	let selectedPaymentMethod = null;
 
-	let orderItems = [];
+	let localOrderItems = [];
 	let products = [];
 	let categories = [];
 
-	$: totalAmount = orderItems.reduce(
+	if (browser) {
+		const storedItems = localStorage.getItem(`orderItems_${orderId}`);
+		if (storedItems) {
+			localOrderItems = JSON.parse(storedItems);
+		}
+	}
+
+	$: totalAmount = localOrderItems.reduce(
 		(sum, item) => sum + Number(item.product_details?.product_price ?? 0) * (item.quantity ?? 1),
 		0
 	);
 
-	async function fetchOrderItems() {
-		try {
-			const myHeaders = new Headers();
-			myHeaders.append('Authorization', `Bearer ${token}`);
-			myHeaders.append('Content-Type', 'application/json');
-
-			if (orderId) {
-				const rawItems = JSON.stringify({
-					order_id: orderId,
-					company_id: company
-				});
-
-				const resItems = await fetch('https://dev2.mixtech.dev.br/order_item/get', {
-					method: 'POST',
-					headers: myHeaders,
-					body: rawItems
-				});
-				const itemsResult = await resItems.json();
-				orderItems = itemsResult.data || [];
-				orderItems = orderItems.map((item) => ({ ...item, quantity: item.quantity ?? 1 }));
-			} else {
-				orderItems = [];
-			}
-		} catch (error) {
-			console.error('Erro ao buscar itens do pedido:', error);
-		}
+	$: if (browser && localOrderItems) {
+		localStorage.setItem(`orderItems_${orderId}`, JSON.stringify(localOrderItems));
 	}
 
 	async function fetchProductsAndCategories() {
@@ -92,7 +73,6 @@
 	}
 
 	onMount(async () => {
-		await fetchOrderItems();
 		await fetchProductsAndCategories();
 	});
 
@@ -107,57 +87,54 @@
 			})
 		: products;
 
-	async function handleAddItem(product) {
-		const myHeaders = new Headers();
-		myHeaders.append('Authorization', `Bearer ${token}`);
-		myHeaders.append('Content-Type', 'application/json');
-		const payload = {
-			company_id: company,
-			order_id: orderId,
-			product_id: product.product_id
+	function handleAddItem(product) {
+		const newItem = {
+			order_item_id: Date.now(), // Temporary ID for local use
+			product_details: product,
+			quantity: 1
 		};
-		await fetch('https://dev2.mixtech.dev.br/order_item/create', {
-			method: 'POST',
-			headers: myHeaders,
-			body: JSON.stringify(payload)
-		});
-		await fetchOrderItems();
+		localOrderItems = [...localOrderItems, newItem]; // Update localOrderItems
 	}
 
-	async function removeItemFromOrder(tableId, itemId) {
-		const myHeaders = new Headers();
-		myHeaders.append('Authorization', `Bearer ${token}`);
-		myHeaders.append('Content-Type', 'application/json');
-		await fetch('https://dev2.mixtech.dev.br/order_item/delete', {
-			method: 'DELETE',
-			headers: myHeaders,
-			body: JSON.stringify({
-				company_id: company,
-				item_id: itemId
-			})
-		});
-		await fetchOrderItems();
+	function removeItemFromOrder(itemId) {
+		localOrderItems = localOrderItems.filter((item) => item.order_item_id !== itemId); // Update localOrderItems
 	}
 
-	async function handlePaymentConfirm() {
-		if (!selectedPaymentMethod) {
-			console.warn('Selecione uma forma de pagamento');
-			return;
-		}
+	async function handleSendToKitchen() {
+		if (localOrderItems.length === 0) return;
+
 		const myHeaders = new Headers();
 		myHeaders.append('Authorization', `Bearer ${token}`);
 		myHeaders.append('Content-Type', 'application/json');
-		await fetch('https://dev2.mixtech.dev.br/order/close', {
-			method: 'POST',
-			headers: myHeaders,
-			body: JSON.stringify({
-				company_id: company,
-				order_id: orderId,
-				payment_method: selectedPaymentMethod
-			})
-		});
-		isPaymentModalOpen = false;
-		goto('/tables');
+
+		try {
+			let success = true;
+			for (const item of localOrderItems) {
+				const payload = {
+					company_id: company,
+					order_id: orderId,
+					product_id: item.product_details.product_id
+				};
+				const response = await fetch('https://dev2.mixtech.dev.br/order_item/create', {
+					method: 'POST',
+					headers: myHeaders,
+					body: JSON.stringify(payload)
+				});
+				if (!response.ok) {
+					success = false;
+					console.error('Erro ao enviar item para cozinha:', response.statusText);
+					break;
+				}
+			}
+			if (success) {
+				localOrderItems = [];
+				if (browser) {
+					localStorage.removeItem(`orderItems_${orderId}`);
+				}
+			}
+		} catch (error) {
+			console.error('Erro ao enviar para cozinha:', error);
+		}
 	}
 </script>
 
@@ -229,13 +206,13 @@
 			</div>
 
 			<div class="flex-1 overflow-y-auto p-4">
-				{#if orderItems.length === 0}
+				{#if localOrderItems.length === 0}
 					<div class="py-6 text-center text-gray-400">
 						<img src={cart_icon} class="mx-auto mb-2 h-10 w-10 opacity-50" alt="Nenhum item" />
 						<p>Nenhum item adicionado</p>
 					</div>
 				{:else}
-					{#each orderItems as item, index}
+					{#each localOrderItems as item, index}
 						<div class="bg-gray-750 flex items-center justify-between rounded-lg p-3">
 							<div class="flex-1">
 								<h3 class="font-medium">
@@ -248,7 +225,7 @@
 							</div>
 							<div class="flex items-center space-x-2">
 								<button
-									on:click={() => removeItemFromOrder(tableIdNum, item.order_item_id)}
+									on:click={() => removeItemFromOrder(item.order_item_id)}
 									class="ml-2 rounded bg-red-700 p-1 hover:bg-red-600"
 								>
 									<img src={trash_icon} class="h-4 w-4" alt="Remover" />
@@ -266,83 +243,13 @@
 				</div>
 
 				<button
-					on:click={() => (isPaymentModalOpen = true)}
-					disabled={orderItems.length === 0}
+					on:click={handleSendToKitchen}
+					disabled={localOrderItems.length === 0}
 					class="flex w-full items-center justify-center rounded-lg bg-emerald-600 py-3 font-medium hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-50"
 				>
-					Fechar Atendimento
+					Enviar para Cozinha
 				</button>
 			</div>
 		</div>
 	</div>
-
-	{#if isPaymentModalOpen}
-		<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4">
-			<div class="w-full max-w-lg rounded-lg bg-gray-800 p-6 shadow-xl">
-				<h2 class="mb-4 text-xl font-bold">Finalizar Pedido</h2>
-
-				<div class="mb-6">
-					<h3 class="mb-3 text-lg font-medium">Resumo do Pedido</h3>
-					<div class="mb-4 max-h-60 overflow-y-auto sm:max-h-80">
-						{#each orderItems as item}
-							<div class="flex justify-between border-b border-gray-700 py-2">
-								<span
-									>{item.quantity ?? 1}x {item.product_details?.product_name ??
-										'Nome Indisponível'}</span
-								>
-								<span
-									>R$ {(
-										Number(item.product_details?.product_price ?? 0) * (item.quantity ?? 1)
-									).toFixed(2)}</span
-								>
-							</div>
-						{/each}
-					</div>
-					<div class="flex justify-between text-lg font-semibold">
-						<span>Total:</span>
-						<span>R$ {totalAmount.toFixed(2)}</span>
-					</div>
-				</div>
-
-				<h3 class="mb-3 text-lg font-medium">Forma de Pagamento</h3>
-				<div class="mb-6 grid grid-cols-1 gap-3 sm:grid-cols-2">
-					{#each ['CASH', 'PIX', 'DEBIT', 'CREDIT'] as method}
-						<button
-							class="flex flex-col items-center justify-center rounded-lg border-2 p-4 transition-colors {selectedPaymentMethod ===
-							method
-								? 'border-emerald-500 bg-emerald-900/20'
-								: 'border-gray-700 hover:border-gray-600'}"
-							on:click={() => (selectedPaymentMethod = method)}
-						>
-							<span
-								>{method === 'CASH'
-									? 'Dinheiro'
-									: method === 'PIX'
-										? 'Pix'
-										: method === 'DEBIT'
-											? 'Cart\u00e3o de D\u00e9bito'
-											: 'Cart\u00e3o de Cr\u00e9dito'}</span
-							>
-						</button>
-					{/each}
-				</div>
-
-				<div class="flex space-x-3">
-					<button
-						on:click={() => (isPaymentModalOpen = false)}
-						class="flex-1 rounded-lg bg-gray-700 py-3 font-medium hover:bg-gray-600"
-					>
-						Cancelar
-					</button>
-					<button
-						on:click={handlePaymentConfirm}
-						disabled={!selectedPaymentMethod}
-						class="flex-1 rounded-lg bg-emerald-600 py-3 font-medium hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-50"
-					>
-						Confirmar Pagamento
-					</button>
-				</div>
-			</div>
-		</div>
-	{/if}
 </div>

+ 5 - 1
src/lib/component/Commands.svelte

@@ -104,6 +104,10 @@
 	};
 
 	function handleAddProduct(order_id) {
+		localStorage.setItem('order', order_id);
+		goto('/dashboard/addproducts');
+	}
+	function handleEndProduct(order_id) {
 		localStorage.setItem('order', order_id);
 		goto('/dashboard/endcommand');
 	}
@@ -145,7 +149,7 @@
 					{#if flag == 'admin'}
 						<button
 							class="mb-2 w-full rounded bg-yellow-600 py-2 hover:bg-yellow-700"
-							on:click={handleAddProduct(order.id)}
+							on:click={handleEndProduct(order.id)}
 						>
 							Finalizar Comanda
 						</button>

+ 150 - 57
src/lib/component/EndCommand.svelte

@@ -22,25 +22,44 @@
 	}
 
 	let selectedCategory = null;
+	let isPaymentModalOpen = false;
+	let selectedPaymentMethod = null;
 
-	let localOrderItems = [];
+	let orderItems = [];
 	let products = [];
 	let categories = [];
 
-	if (browser) {
-		const storedItems = localStorage.getItem(`orderItems_${orderId}`);
-		if (storedItems) {
-			localOrderItems = JSON.parse(storedItems);
-		}
-	}
-
-	$: totalAmount = localOrderItems.reduce(
+	$: totalAmount = orderItems.reduce(
 		(sum, item) => sum + Number(item.product_details?.product_price ?? 0) * (item.quantity ?? 1),
 		0
 	);
 
-	$: if (browser && localOrderItems) {
-		localStorage.setItem(`orderItems_${orderId}`, JSON.stringify(localOrderItems));
+	async function fetchOrderItems() {
+		try {
+			const myHeaders = new Headers();
+			myHeaders.append('Authorization', `Bearer ${token}`);
+			myHeaders.append('Content-Type', 'application/json');
+
+			if (orderId) {
+				const rawItems = JSON.stringify({
+					order_id: orderId,
+					company_id: company
+				});
+
+				const resItems = await fetch('https://dev2.mixtech.dev.br/order_item/get', {
+					method: 'POST',
+					headers: myHeaders,
+					body: rawItems
+				});
+				const itemsResult = await resItems.json();
+				orderItems = itemsResult.data || [];
+				orderItems = orderItems.map((item) => ({ ...item, quantity: item.quantity ?? 1 }));
+			} else {
+				orderItems = [];
+			}
+		} catch (error) {
+			console.error('Erro ao buscar itens do pedido:', error);
+		}
 	}
 
 	async function fetchProductsAndCategories() {
@@ -73,6 +92,7 @@
 	}
 
 	onMount(async () => {
+		await fetchOrderItems();
 		await fetchProductsAndCategories();
 	});
 
@@ -87,54 +107,57 @@
 			})
 		: products;
 
-	function handleAddItem(product) {
-		const newItem = {
-			order_item_id: Date.now(), // Temporary ID for local use
-			product_details: product,
-			quantity: 1
+	async function handleAddItem(product) {
+		const myHeaders = new Headers();
+		myHeaders.append('Authorization', `Bearer ${token}`);
+		myHeaders.append('Content-Type', 'application/json');
+		const payload = {
+			company_id: company,
+			order_id: orderId,
+			product_id: product.product_id
 		};
-		localOrderItems = [...localOrderItems, newItem]; // Update localOrderItems
-	}
-
-	function removeItemFromOrder(itemId) {
-		localOrderItems = localOrderItems.filter((item) => item.order_item_id !== itemId); // Update localOrderItems
+		await fetch('https://dev2.mixtech.dev.br/order_item/create', {
+			method: 'POST',
+			headers: myHeaders,
+			body: JSON.stringify(payload)
+		});
+		await fetchOrderItems();
 	}
 
-	async function handleSendToKitchen() {
-		if (localOrderItems.length === 0) return;
-
+	async function removeItemFromOrder(tableId, itemId) {
 		const myHeaders = new Headers();
 		myHeaders.append('Authorization', `Bearer ${token}`);
 		myHeaders.append('Content-Type', 'application/json');
+		await fetch('https://dev2.mixtech.dev.br/order_item/delete', {
+			method: 'DELETE',
+			headers: myHeaders,
+			body: JSON.stringify({
+				company_id: company,
+				item_id: itemId
+			})
+		});
+		await fetchOrderItems();
+	}
 
-		try {
-			let success = true;
-			for (const item of localOrderItems) {
-				const payload = {
-					company_id: company,
-					order_id: orderId,
-					product_id: item.product_details.product_id
-				};
-				const response = await fetch('https://dev2.mixtech.dev.br/order_item/create', {
-					method: 'POST',
-					headers: myHeaders,
-					body: JSON.stringify(payload)
-				});
-				if (!response.ok) {
-					success = false;
-					console.error('Erro ao enviar item para cozinha:', response.statusText);
-					break;
-				}
-			}
-			if (success) {
-				localOrderItems = [];
-				if (browser) {
-					localStorage.removeItem(`orderItems_${orderId}`);
-				}
-			}
-		} catch (error) {
-			console.error('Erro ao enviar para cozinha:', error);
+	async function handlePaymentConfirm() {
+		if (!selectedPaymentMethod) {
+			console.warn('Selecione uma forma de pagamento');
+			return;
 		}
+		const myHeaders = new Headers();
+		myHeaders.append('Authorization', `Bearer ${token}`);
+		myHeaders.append('Content-Type', 'application/json');
+		await fetch('https://dev2.mixtech.dev.br/order/close', {
+			method: 'POST',
+			headers: myHeaders,
+			body: JSON.stringify({
+				company_id: company,
+				order_id: orderId,
+				payment_method: selectedPaymentMethod
+			})
+		});
+		isPaymentModalOpen = false;
+		goto('/tables');
 	}
 </script>
 
@@ -206,13 +229,13 @@
 			</div>
 
 			<div class="flex-1 overflow-y-auto p-4">
-				{#if localOrderItems.length === 0}
+				{#if orderItems.length === 0}
 					<div class="py-6 text-center text-gray-400">
 						<img src={cart_icon} class="mx-auto mb-2 h-10 w-10 opacity-50" alt="Nenhum item" />
 						<p>Nenhum item adicionado</p>
 					</div>
 				{:else}
-					{#each localOrderItems as item, index}
+					{#each orderItems as item, index}
 						<div class="bg-gray-750 flex items-center justify-between rounded-lg p-3">
 							<div class="flex-1">
 								<h3 class="font-medium">
@@ -225,7 +248,7 @@
 							</div>
 							<div class="flex items-center space-x-2">
 								<button
-									on:click={() => removeItemFromOrder(item.order_item_id)}
+									on:click={() => removeItemFromOrder(tableIdNum, item.order_item_id)}
 									class="ml-2 rounded bg-red-700 p-1 hover:bg-red-600"
 								>
 									<img src={trash_icon} class="h-4 w-4" alt="Remover" />
@@ -243,13 +266,83 @@
 				</div>
 
 				<button
-					on:click={handleSendToKitchen}
-					disabled={localOrderItems.length === 0}
+					on:click={() => (isPaymentModalOpen = true)}
+					disabled={orderItems.length === 0}
 					class="flex w-full items-center justify-center rounded-lg bg-emerald-600 py-3 font-medium hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-50"
 				>
-					Enviar para Cozinha
+					Fechar Atendimento
 				</button>
 			</div>
 		</div>
 	</div>
+
+	{#if isPaymentModalOpen}
+		<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4">
+			<div class="w-full max-w-lg rounded-lg bg-gray-800 p-6 shadow-xl">
+				<h2 class="mb-4 text-xl font-bold">Finalizar Pedido</h2>
+
+				<div class="mb-6">
+					<h3 class="mb-3 text-lg font-medium">Resumo do Pedido</h3>
+					<div class="mb-4 max-h-60 overflow-y-auto sm:max-h-80">
+						{#each orderItems as item}
+							<div class="flex justify-between border-b border-gray-700 py-2">
+								<span
+									>{item.quantity ?? 1}x {item.product_details?.product_name ??
+										'Nome Indisponível'}</span
+								>
+								<span
+									>R$ {(
+										Number(item.product_details?.product_price ?? 0) * (item.quantity ?? 1)
+									).toFixed(2)}</span
+								>
+							</div>
+						{/each}
+					</div>
+					<div class="flex justify-between text-lg font-semibold">
+						<span>Total:</span>
+						<span>R$ {totalAmount.toFixed(2)}</span>
+					</div>
+				</div>
+
+				<h3 class="mb-3 text-lg font-medium">Forma de Pagamento</h3>
+				<div class="mb-6 grid grid-cols-1 gap-3 sm:grid-cols-2">
+					{#each ['CASH', 'PIX', 'DEBIT', 'CREDIT'] as method}
+						<button
+							class="flex flex-col items-center justify-center rounded-lg border-2 p-4 transition-colors {selectedPaymentMethod ===
+							method
+								? 'border-emerald-500 bg-emerald-900/20'
+								: 'border-gray-700 hover:border-gray-600'}"
+							on:click={() => (selectedPaymentMethod = method)}
+						>
+							<span
+								>{method === 'CASH'
+									? 'Dinheiro'
+									: method === 'PIX'
+										? 'Pix'
+										: method === 'DEBIT'
+											? 'Cart\u00e3o de D\u00e9bito'
+											: 'Cart\u00e3o de Cr\u00e9dito'}</span
+							>
+						</button>
+					{/each}
+				</div>
+
+				<div class="flex space-x-3">
+					<button
+						on:click={() => (isPaymentModalOpen = false)}
+						class="flex-1 rounded-lg bg-gray-700 py-3 font-medium hover:bg-gray-600"
+					>
+						Cancelar
+					</button>
+					<button
+						on:click={handlePaymentConfirm}
+						disabled={!selectedPaymentMethod}
+						class="flex-1 rounded-lg bg-emerald-600 py-3 font-medium hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-50"
+					>
+						Confirmar Pagamento
+					</button>
+				</div>
+			</div>
+		</div>
+	{/if}
 </div>