Auto commit: 2026-02-28T19:54:09.195Z

This commit is contained in:
Flatlogic Bot 2026-02-28 19:54:09 +00:00
parent 822bf63804
commit 67db9ff153
15 changed files with 904 additions and 304 deletions

View File

@ -1,4 +1,3 @@
const express = require('express');
const Order_itemsService = require('../services/order_items');
@ -89,8 +88,7 @@ router.use(checkCrudPermissions('order_items'));
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await Order_itemsService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
const payload = await Order_itemsService.create(req.body.data, req.currentUser, true, link.host);
res.status(200).send(payload);
}));
@ -438,4 +436,4 @@ router.get('/:id', wrapAsync(async (req, res) => {
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;
module.exports = router;

View File

@ -1,4 +1,3 @@
const express = require('express');
const OrdersService = require('../services/orders');
@ -97,8 +96,7 @@ router.use(checkCrudPermissions('orders'));
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await OrdersService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
const payload = await OrdersService.create(req.body.data, req.currentUser, true, link.host);
res.status(200).send(payload);
}));
@ -446,4 +444,4 @@ router.get('/:id', wrapAsync(async (req, res) => {
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;
module.exports = router;

View File

@ -15,7 +15,7 @@ module.exports = class Order_itemsService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await Order_itemsDBApi.create(
const order_items = await Order_itemsDBApi.create(
data,
{
currentUser,
@ -24,6 +24,7 @@ module.exports = class Order_itemsService {
);
await transaction.commit();
return order_items;
} catch (error) {
await transaction.rollback();
throw error;
@ -133,6 +134,4 @@ module.exports = class Order_itemsService {
}
};
};

View File

@ -15,7 +15,7 @@ module.exports = class OrdersService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await OrdersDBApi.create(
const orders = await OrdersDBApi.create(
data,
{
currentUser,
@ -24,6 +24,7 @@ module.exports = class OrdersService {
);
await transaction.commit();
return orders;
} catch (error) {
await transaction.rollback();
throw error;
@ -121,7 +122,7 @@ module.exports = class OrdersService {
id,
{
currentUser,
transaction,
transaction,
},
);
@ -133,6 +134,4 @@ module.exports = class OrdersService {
}
};
};

View File

@ -1,110 +1,153 @@
import React from 'react';
import { mdiClose, mdiTrashCan, mdiMinus, mdiPlus } from '@mdi/js';
import { useAppDispatch, useAppSelector } from '../stores/hooks';
import { removeFromCart, updateQuantity, toggleCart } from '../stores/localCartSlice';
import { mdiClose, mdiPlus, mdiMinus, mdiTrashCan, mdiCartOutline } from '@mdi/js';
import BaseButton from './BaseButton';
import BaseIcon from './BaseIcon';
import { useAppDispatch, useAppSelector } from '../stores/hooks';
import { removeFromCart, updateQuantity } from '../stores/localCartSlice';
import { useRouter } from 'next/router';
const CartDrawer = () => {
interface CartDrawerProps {
isOpen: boolean;
onClose: () => void;
}
const CartDrawer: React.FC<CartDrawerProps> = ({ isOpen, onClose }) => {
const dispatch = useAppDispatch();
const { items, isOpen } = useAppSelector((state) => state.localCart);
const router = useRouter();
const cartItems = useAppSelector((state) => state.localCart.items);
const totalPrice = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
const subtotal = cartItems.reduce((acc, item) => acc + item.price * item.quantity, 0);
if (!isOpen) return null;
return (
<div className="fixed inset-0 z-50 flex justify-end">
<div className="fixed inset-0 z-50 overflow-hidden">
{/* Backdrop */}
<div
className="fixed inset-0 bg-black bg-opacity-50 transition-opacity"
onClick={() => dispatch(toggleCart())}
></div>
className="absolute inset-0 bg-black bg-opacity-50 transition-opacity"
onClick={onClose}
/>
{/* Drawer */}
<div className="relative w-full max-w-md bg-white h-full shadow-xl flex flex-col animate-fade-in-right">
<div className="p-4 border-b flex items-center justify-between bg-orange-600 text-white">
<h2 className="text-xl font-bold">Tu Carrito</h2>
<button onClick={() => dispatch(toggleCart())} className="p-1 hover:bg-orange-700 rounded">
<BaseIcon path={mdiClose} size={24} />
</button>
</div>
<div className="flex-grow overflow-y-auto p-4 space-y-4">
{items.length === 0 ? (
<div className="text-center py-10">
<p className="text-gray-500 mb-4">Tu carrito está vacío</p>
<BaseButton
label="Empezar a comprar"
color="info"
onClick={() => dispatch(toggleCart())}
/>
<div className="absolute inset-y-0 right-0 max-w-full flex">
<div className="w-screen max-w-md">
<div className="h-full flex flex-col bg-white shadow-xl">
{/* Header */}
<div className="flex items-center justify-between px-4 py-6 border-b">
<h2 className="text-xl font-bold flex items-center gap-2">
<BaseIcon path={mdiCartOutline} size={24} />
Your Selection
</h2>
<button
onClick={onClose}
className="text-gray-400 hover:text-gray-500 transition-colors"
>
<BaseIcon path={mdiClose} size={32} />
</button>
</div>
) : (
items.map((item) => (
<div key={item.id} className="flex items-center space-x-4 border-b pb-4">
{item.image && (
<img src={item.image} alt={item.name} className="w-16 h-16 object-cover rounded" />
)}
<div className="flex-grow">
<h3 className="font-semibold text-gray-800">{item.name}</h3>
<p className="text-orange-600 font-bold">${item.price.toFixed(2)}</p>
<div className="flex items-center space-x-2 mt-2">
<button
onClick={() => dispatch(updateQuantity({ id: item.id, quantity: item.quantity - 1 }))}
className="p-1 border rounded hover:bg-gray-100"
>
<BaseIcon path={mdiMinus} size={16} />
</button>
<span className="w-8 text-center">{item.quantity}</span>
<button
onClick={() => dispatch(updateQuantity({ id: item.id, quantity: item.quantity + 1 }))}
className="p-1 border rounded hover:bg-gray-100"
>
<BaseIcon path={mdiPlus} size={16} />
</button>
{/* Content */}
<div className="flex-1 overflow-y-auto aside-scrollbars px-4 py-4">
{cartItems.length === 0 ? (
<div className="flex flex-col items-center justify-center h-full text-center py-20">
<div className="bg-gray-100 p-6 rounded-full mb-4">
<BaseIcon path={mdiCartOutline} size={64} className="text-gray-400" />
</div>
<p className="text-gray-500 text-lg">Your cart is empty.</p>
<BaseButton
label="Explore Menu"
color="pavitra"
onClick={onClose}
className="mt-4"
/>
</div>
<button
onClick={() => dispatch(removeFromCart(item.id))}
className="text-red-500 hover:text-red-700"
>
<BaseIcon path={mdiTrashCan} size={20} />
</button>
</div>
))
)}
</div>
) : (
<div className="space-y-6">
{cartItems.map((item) => (
<div key={item.id} className="flex gap-4 border-b pb-4 last:border-0">
<div className="w-20 h-20 bg-gray-100 rounded-lg flex items-center justify-center overflow-hidden flex-shrink-0">
{item.image ? (
<img src={item.image} alt={item.name} className="w-full h-full object-cover" />
) : (
<BaseIcon path={mdiCartOutline} size={24} className="text-gray-300" />
)}
</div>
<div className="flex-1 flex flex-col">
<div className="flex justify-between items-start">
<h3 className="font-bold text-gray-800">{item.name}</h3>
<p className="font-bold text-pavitra-600">${item.price.toFixed(2)}</p>
</div>
<div className="mt-auto flex justify-between items-center">
{/* Quantity Controls */}
<div className="flex items-center border rounded-lg">
<button
className="p-1 hover:bg-gray-100 text-gray-500 transition-colors"
onClick={() => {
if (item.quantity > 1) {
dispatch(updateQuantity({ id: item.id, quantity: item.quantity - 1 }));
} else {
dispatch(removeFromCart(item.id));
}
}}
>
<BaseIcon path={mdiMinus} size={18} />
</button>
<span className="px-3 font-semibold w-8 text-center">{item.quantity}</span>
<button
className="p-1 hover:bg-gray-100 text-gray-500 transition-colors"
onClick={() => dispatch(updateQuantity({ id: item.id, quantity: item.quantity + 1 }))}
>
<BaseIcon path={mdiPlus} size={18} />
</button>
</div>
{items.length > 0 && (
<div className="p-4 border-t bg-gray-50">
<div className="flex justify-between items-center mb-4">
<span className="text-lg font-semibold text-gray-600">Total:</span>
<span className="text-2xl font-bold text-orange-600">${totalPrice.toFixed(2)}</span>
<button
className="text-red-500 hover:text-red-700 p-1 transition-colors"
onClick={() => dispatch(removeFromCart(item.id))}
>
<BaseIcon path={mdiTrashCan} size={20} />
</button>
</div>
</div>
</div>
))}
</div>
)}
</div>
<BaseButton
label="Finalizar Compra"
color="success"
className="w-full py-3 text-lg font-bold"
onClick={() => {
alert('¡Próximamente! Estamos preparando el proceso de pago.');
}}
/>
<p className="text-xs text-center text-gray-400 mt-2">
Envío gratuito en pedidos superiores a $50
</p>
{/* Footer */}
{cartItems.length > 0 && (
<div className="border-t px-4 py-6 bg-gray-50">
<div className="flex justify-between items-center text-lg font-bold mb-4">
<span>Subtotal</span>
<span className="text-pavitra-600">${subtotal.toFixed(2)}</span>
</div>
<p className="text-sm text-gray-500 mb-6">
Shipping and taxes calculated at checkout.
</p>
<div className="flex flex-col gap-3">
<BaseButton
label="Checkout"
color="pavitra"
className="w-full py-4 text-lg"
onClick={() => {
onClose();
router.push('/checkout');
}}
/>
<BaseButton
label="Continue Browsing"
color="white"
className="w-full border"
onClick={onClose}
/>
</div>
</div>
)}
</div>
)}
</div>
</div>
<style jsx>{`
@keyframes fade-in-right {
from { opacity: 0; transform: translateX(100%); }
to { opacity: 1; transform: translateX(0); }
}
.animate-fade-in-right {
animation: fade-in-right 0.3s ease-out forwards;
}
`}</style>
</div>
);
};

View File

@ -0,0 +1,46 @@
import React from 'react';
import Link from 'next/link';
import { useAppSelector } from '../../stores/hooks';
const ElCalenticoFooter = () => {
const darkMode = useAppSelector((state) => state.style.darkMode);
return (
<footer className={`py-12 ${darkMode ? 'bg-dark-800 text-gray-400' : 'bg-gray-100 text-gray-600'}`}>
<div className="container mx-auto px-4">
<div className="grid grid-cols-1 md:grid-cols-4 gap-12 mb-12 border-b border-gray-200 dark:border-dark-700 pb-12">
<div className="col-span-1 md:col-span-2">
<h3 className="text-2xl font-bold text-orange-600 mb-6">El Calentico</h3>
<p className="mb-6 max-w-md text-lg">
Tu tienda virtual de confianza para alimentos, bebidas y productos del día a día. Llevamos la mejor calidad directamente a tu puerta.
</p>
</div>
<div>
<h4 className="text-lg font-bold mb-6 text-gray-900 dark:text-white">Enlaces Rápidos</h4>
<ul className="space-y-4">
<li><Link href="/search" className="hover:text-orange-600 transition-colors">Productos</Link></li>
<li><Link href="/#categories" className="hover:text-orange-600 transition-colors">Categorías</Link></li>
<li><Link href="/login" className="hover:text-orange-600 transition-colors">Mi Cuenta</Link></li>
</ul>
</div>
<div>
<h4 className="text-lg font-bold mb-6 text-gray-900 dark:text-white">Legal</h4>
<ul className="space-y-4">
<li><Link href="/privacy-policy" className="hover:text-orange-600 transition-colors">Privacidad</Link></li>
<li><Link href="/terms-of-use" className="hover:text-orange-600 transition-colors">Términos</Link></li>
</ul>
</div>
</div>
<div className="flex flex-col md:flex-row justify-between items-center gap-4 text-sm font-medium">
<p>© 2026 El Calentico. Todos los derechos reservados.</p>
<div className="flex gap-8">
<Link href="/terms-of-use" className="hover:text-orange-600 transition-colors">Términos de Uso</Link>
<Link href="/privacy-policy" className="hover:text-orange-600 transition-colors">Política de Privacidad</Link>
</div>
</div>
</div>
</footer>
);
};
export default ElCalenticoFooter;

View File

@ -0,0 +1,67 @@
import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { mdiCartOutline } from '@mdi/js';
import BaseIcon from '../BaseIcon';
import { useAppSelector, useAppDispatch } from '../../stores/hooks';
import { toggleCart } from '../../stores/localCartSlice';
const ElCalenticoHeader = () => {
const dispatch = useAppDispatch();
const cartItems = useAppSelector((state) => state.localCart.items);
const darkMode = useAppSelector((state) => state.style.darkMode);
const [isScrolled, setIsScrolled] = useState(false);
useEffect(() => {
const handleScroll = () => {
setIsScrolled(window.scrollY > 20);
};
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
const cartCount = cartItems.reduce((acc, item) => acc + item.quantity, 0);
return (
<nav className={`fixed top-0 left-0 right-0 z-40 transition-all duration-300 ${
isScrolled ? (darkMode ? 'bg-dark-900/95 backdrop-blur-md py-4' : 'bg-white/95 backdrop-blur-md py-4 shadow-md') : 'bg-transparent py-6'
}`}>
<div className="container mx-auto px-4 flex justify-between items-center">
<Link href="/" className="flex items-center gap-2 group">
<div className="bg-orange-600 p-2 rounded-lg rotate-12 group-hover:rotate-0 transition-transform duration-300">
<span className="text-white font-black text-2xl">C</span>
</div>
<span className="text-2xl font-black text-orange-600 tracking-tighter">EL CALENTICO</span>
</Link>
<div className="hidden md:flex items-center gap-10">
<Link href="/" className={`font-bold hover:text-orange-600 transition-colors ${isScrolled ? 'text-gray-800 dark:text-gray-200' : 'text-gray-900'}`}>Menu</Link>
<Link href="/search" className={`font-bold hover:text-orange-600 transition-colors ${isScrolled ? 'text-gray-800 dark:text-gray-200' : 'text-gray-900'}`}>Ofertas</Link>
<Link href="/login" className={`font-bold hover:text-orange-600 transition-colors ${isScrolled ? 'text-gray-800 dark:text-gray-200' : 'text-gray-900'}`}>Mi Cuenta</Link>
</div>
<div className="flex items-center gap-4">
<button
onClick={() => dispatch(toggleCart())}
className="relative p-2 text-orange-600 hover:bg-orange-600/10 rounded-full transition-all group"
title="Ver carrito"
>
<BaseIcon path={mdiCartOutline} size={32} />
{cartCount > 0 && (
<span className="absolute -top-1 -right-1 bg-red-600 text-white text-xs font-black w-6 h-6 flex items-center justify-center rounded-full border-2 border-white animate-bounce">
{cartCount}
</span>
)}
</button>
<Link
href="/login"
className="hidden md:block bg-orange-600 hover:bg-orange-700 text-white font-bold py-3 px-8 rounded-full transition-all duration-300 hover:scale-105"
>
Iniciar Sesión
</Link>
</div>
</div>
</nav>
);
};
export default ElCalenticoHeader;

View File

@ -1,6 +1,5 @@
import React, {useEffect, useRef} from 'react'
import React, {useEffect, useRef, useState} from 'react'
import Link from 'next/link'
import { useState } from 'react'
import { mdiChevronUp, mdiChevronDown } from '@mdi/js'
import BaseDivider from './BaseDivider'
import BaseIcon from './BaseIcon'
@ -129,4 +128,4 @@ export default function NavBarItem({ item }: Props) {
}
return <div className={componentClass} ref={excludedRef}>{NavBarItemComponentContents}</div>
}
}

View File

@ -1,5 +1,4 @@
import React, { ReactNode, useEffect } from 'react'
import { useState } from 'react'
import React, { ReactNode, useEffect, useState } from 'react'
import jwt from 'jsonwebtoken';
import { mdiForwardburger, mdiBackburger, mdiMenu } from '@mdi/js'
import menuAside from '../menuAside'
@ -126,4 +125,4 @@ export default function LayoutAuthenticated({
</div>
</div>
)
}
}

View File

@ -7,6 +7,14 @@ const menuAside: MenuAsideItem[] = [
icon: icon.mdiViewDashboardOutline,
label: 'Dashboard',
},
{
href: '/orders/dashboard',
label: 'Order Dashboard',
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
icon: icon.mdiMonitorDashboard ?? icon.mdiTable,
permissions: 'READ_ORDERS'
},
{
href: '/users/users-list',
@ -160,4 +168,4 @@ const menuAside: MenuAsideItem[] = [
},
]
export default menuAside
export default menuAside

View File

@ -0,0 +1,272 @@
import { mdiCartCheck, mdiChevronLeft, mdiTruckDelivery } from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement, useState } from 'react';
import CardBox from '../components/CardBox';
import LayoutGuest from '../layouts/Guest';
import SectionMain from '../components/SectionMain';
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
import { getPageTitle } from '../config';
import { useAppDispatch, useAppSelector } from '../stores/hooks';
import BaseButton from '../components/BaseButton';
import FormField from '../components/FormField';
import { clearCart } from '../stores/localCartSlice';
import axios from 'axios';
import { useRouter } from 'next/router';
import ElCalenticoHeader from '../components/ElCalentico/Header';
import ElCalenticoFooter from '../components/ElCalentico/Footer';
import BaseIcon from '../components/BaseIcon';
const CheckoutPage = () => {
const dispatch = useAppDispatch();
const router = useRouter();
const cartItems = useAppSelector((state) => state.localCart.items);
const [formData, setFormData] = useState({
firstName: '',
lastName: '',
email: '',
phone: '',
address: '',
notes: '',
});
const [isSubmitting, setIsSubmitting] = useState(false);
const [orderSuccess, setOrderSuccess] = useState(false);
const subtotal = cartItems.reduce((acc, item) => acc + item.price * item.quantity, 0);
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const { name, value } = e.target;
setFormData((prev) => ({ ...prev, [name]: value }));
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (cartItems.length === 0) return;
setIsSubmitting(true);
try {
// 1. Create Order
const orderData = {
data: {
order_number: `ORD-${Date.now()}`,
status: 'pending',
payment_status: 'unpaid',
subtotal_amount: subtotal,
total_amount: subtotal,
customer_note: `Guest: ${formData.firstName} ${formData.lastName}\nEmail: ${formData.email}\nPhone: ${formData.phone}\nAddress: ${formData.address}\nNotes: ${formData.notes}`,
placed_at: new Date().toISOString(),
},
};
const orderResponse = await axios.post('/orders', orderData);
const orderId = orderResponse.data.id;
// 2. Create Order Items
for (const item of cartItems) {
await axios.post('/order_items', {
data: {
orderId: orderId,
productId: item.id,
product_name_snapshot: item.name,
quantity: item.quantity,
unit_price_snapshot: item.price,
line_total_amount: item.price * item.quantity,
},
});
}
// 3. Success
dispatch(clearCart());
setOrderSuccess(true);
window.scrollTo(0, 0);
} catch (error) {
console.error('Checkout error:', error);
alert('There was an error processing your order. Please try again.');
} finally {
setIsSubmitting(false);
}
};
if (orderSuccess) {
return (
<div className="pt-20">
<Head>
<title>{getPageTitle('Order Success')}</title>
</Head>
<ElCalenticoHeader />
<SectionMain>
<div className="max-w-2xl mx-auto text-center py-20 bg-white rounded-3xl shadow-sm border mt-10">
<div className="flex justify-center mb-8">
<div className="bg-green-100 text-green-600 p-6 rounded-full">
<BaseIcon path={mdiCartCheck} size={64} />
</div>
</div>
<h1 className="text-4xl font-black mb-6 text-gray-900">¡Pedido Realizado con Éxito!</h1>
<p className="text-gray-600 mb-10 text-xl max-w-lg mx-auto leading-relaxed">
Gracias por tu pedido. Lo hemos recibido y empezaremos a preparar tus favoritos de El Calentico de inmediato.
</p>
<BaseButton
label="Volver al Menú"
color="pavitra"
roundedFull
className="px-12 py-4 text-lg font-bold"
onClick={() => router.push('/')}
/>
</div>
</SectionMain>
<ElCalenticoFooter />
</div>
);
}
return (
<div className="pt-20 bg-gray-50 min-h-screen">
<Head>
<title>{getPageTitle('Checkout')}</title>
</Head>
<ElCalenticoHeader />
<SectionMain>
<SectionTitleLineWithButton icon={mdiTruckDelivery} title="Finalizar Pedido" main>
<BaseButton
icon={mdiChevronLeft}
label="Volver a la Tienda"
color="white"
roundedFull
onClick={() => router.push('/')}
small
/>
</SectionTitleLineWithButton>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
{/* Form */}
<div className="lg:col-span-2">
<CardBox isForm onSubmit={handleSubmit} className="shadow-sm border-0 rounded-3xl">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<FormField label="Nombre" help="Requerido">
<input
type="text"
name="firstName"
value={formData.firstName}
onChange={handleInputChange}
required
className="w-full rounded-xl border-gray-200 focus:border-orange-500 focus:ring-orange-500 transition-all"
/>
</FormField>
<FormField label="Apellidos" help="Requerido">
<input
type="text"
name="lastName"
value={formData.lastName}
onChange={handleInputChange}
required
className="w-full rounded-xl border-gray-200 focus:border-orange-500 focus:ring-orange-500 transition-all"
/>
</FormField>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mt-6">
<FormField label="Email" help="Requerido">
<input
type="email"
name="email"
value={formData.email}
onChange={handleInputChange}
required
className="w-full rounded-xl border-gray-200 focus:border-orange-500 focus:ring-orange-500 transition-all"
/>
</FormField>
<FormField label="Teléfono" help="Requerido">
<input
type="tel"
name="phone"
value={formData.phone}
onChange={handleInputChange}
required
className="w-full rounded-xl border-gray-200 focus:border-orange-500 focus:ring-orange-500 transition-all"
/>
</FormField>
</div>
<div className="mt-6">
<FormField label="Dirección de Entrega" help="Requerido">
<textarea
name="address"
value={formData.address}
onChange={handleInputChange}
required
className="w-full min-h-[120px] rounded-xl border-gray-200 focus:border-orange-500 focus:ring-orange-500 transition-all"
placeholder="Calle, número, piso, código postal..."
/>
</FormField>
</div>
<div className="mt-6">
<FormField label="Notas del Pedido" help="Opcional">
<textarea
name="notes"
value={formData.notes}
onChange={handleInputChange}
className="w-full min-h-[80px] rounded-xl border-gray-200 focus:border-orange-500 focus:ring-orange-500 transition-all"
placeholder="Instrucciones especiales para el repartidor..."
/>
</FormField>
</div>
<div className="mt-10 flex justify-end">
<BaseButton
type="submit"
color="pavitra"
roundedFull
label={isSubmitting ? 'Procesando...' : `Confirmar Pedido ($${subtotal.toFixed(2)})`}
disabled={isSubmitting || cartItems.length === 0}
className="w-full md:w-auto px-12 py-4 text-xl font-bold transition-transform hover:scale-105"
/>
</div>
</CardBox>
</div>
{/* Summary */}
<div className="lg:col-span-1">
<CardBox className="shadow-sm border-0 rounded-3xl sticky top-28">
<h2 className="text-2xl font-black mb-6 border-b pb-4 text-gray-800">Resumen del Pedido</h2>
<div className="space-y-6 max-h-[50vh] overflow-y-auto aside-scrollbars pr-2">
{cartItems.map((item) => (
<div key={item.id} className="flex justify-between items-start gap-4 group">
<div className="flex-grow">
<p className="font-bold text-gray-800 group-hover:text-orange-600 transition-colors">{item.name}</p>
<p className="text-sm text-gray-500 font-medium">Cant: {item.quantity} x ${item.price.toFixed(2)}</p>
</div>
<p className="font-black text-gray-900">${(item.price * item.quantity).toFixed(2)}</p>
</div>
))}
</div>
{cartItems.length === 0 && (
<p className="text-center text-gray-500 py-10 italic">Tu carrito está vacío.</p>
)}
<div className="mt-8 pt-6 border-t border-dashed border-gray-300">
<div className="flex justify-between items-center text-xl font-black">
<span className="text-gray-700">Total</span>
<span className="text-orange-600 text-3xl">${subtotal.toFixed(2)}</span>
</div>
</div>
<div className="mt-8 text-xs text-gray-400 bg-gray-50 p-4 rounded-2xl">
<p>Al realizar tu pedido, aceptas los Términos de Servicio y la Política de Privacidad de El Calentico.</p>
</div>
</CardBox>
</div>
</div>
</SectionMain>
<ElCalenticoFooter />
</div>
);
};
CheckoutPage.getLayout = function getLayout(page: ReactElement) {
return <LayoutGuest>{page}</LayoutGuest>;
};
export default CheckoutPage;

View File

@ -148,6 +148,20 @@ const Dashboard = () => {
</div>
{!!rolesWidgets.length && <hr className='my-6 text-pastelBrownTheme-mainBG ' />}
{hasPermission(currentUser, 'READ_ORDERS') && (
<Link href={'/orders/dashboard'}>
<div className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6 mb-6 bg-orange-50 dark:bg-orange-900 border-orange-200 dark:border-orange-800 cursor-pointer hover:shadow-lg transition-shadow duration-200`}>
<div className="flex justify-between items-center">
<div>
<h2 className="text-2xl font-bold text-orange-600 dark:text-orange-400">Order Management Dashboard</h2>
<p className="text-gray-600 dark:text-gray-300">View analytics, process incoming orders, and manage inventory.</p>
</div>
<BaseIcon path={icon.mdiMonitorDashboard} size={64} className="text-orange-500" />
</div>
</div>
</Link>
)}
<div id="dashboard" className='grid grid-cols-1 gap-6 lg:grid-cols-3 mb-6'>
@ -639,4 +653,4 @@ Dashboard.getLayout = function getLayout(page: ReactElement) {
return <LayoutAuthenticated>{page}</LayoutAuthenticated>
}
export default Dashboard
export default Dashboard

View File

@ -1,4 +1,4 @@
import React, { useEffect } from 'react';
import React, { useEffect, useState } from 'react';
import type { ReactElement } from 'react';
import Head from 'next/head';
import Link from 'next/link';
@ -8,208 +8,223 @@ import { getPageTitle } from '../config';
import { useAppSelector, useAppDispatch } from '../stores/hooks';
import { fetch as fetchProducts } from '../stores/products/productsSlice';
import { fetch as fetchCategories } from '../stores/product_categories/product_categoriesSlice';
import ImageField from '../components/ImageField';
import { mdiCartOutline, mdiArrowRight } from '@mdi/js';
import { mdiCartOutline, mdiArrowRight, mdiFire, mdiTruckFast, mdiFoodApple } from '@mdi/js';
import BaseIcon from '../components/BaseIcon';
import LoadingSpinner from '../components/LoadingSpinner';
import CartDrawer from '../components/CartDrawer';
import { addToCart, toggleCart } from '../stores/localCartSlice';
import ElCalenticoHeader from '../components/ElCalentico/Header';
import ElCalenticoFooter from '../components/ElCalentico/Footer';
export default function Home() {
const dispatch = useAppDispatch();
const { products, loading: productsLoading } = useAppSelector((state) => state.products);
const { product_categories, loading: categoriesLoading } = useAppSelector((state) => state.product_categories);
const { currentUser } = useAppSelector((state) => state.auth);
const { categories, loading: categoriesLoading } = useAppSelector((state) => state.product_categories);
const isCartOpen = useAppSelector((state) => state.localCart.isOpen);
const darkMode = useAppSelector((state) => state.style.darkMode);
const { items: cartItems } = useAppSelector((state) => state.localCart);
const cartCount = cartItems.reduce((sum, item) => sum + item.quantity, 0);
const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
useEffect(() => {
dispatch(fetchProducts({ query: '?limit=8' }));
dispatch(fetchCategories({ query: '' }));
dispatch(fetchProducts({}));
dispatch(fetchCategories({}));
}, [dispatch]);
const handleAddToCart = (product: any) => {
dispatch(addToCart({
id: product.id,
name: product.name,
price: product.price,
price: Number(product.price),
quantity: 1,
image: product.images ? product.images[0]?.url : null
image: product.image?.length > 0 ? product.image[0].publicUrl : null
}));
dispatch(toggleCart());
};
const heroImage = "https://images.pexels.com/photos/958545/pexels-photo-958545.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1";
const filteredProducts = selectedCategory
? products.filter((p: any) => p.categoryId === selectedCategory)
: products;
const featuredProducts = products.filter((p: any) => p.is_featured).slice(0, 4);
return (
<div className={`min-h-screen ${darkMode ? 'bg-dark-900 text-white' : 'bg-gray-50 text-gray-900'}`}>
<div className={`min-h-screen font-sans selection:bg-orange-600 selection:text-white ${darkMode ? 'bg-dark-900 text-gray-100' : 'bg-white text-gray-900'}`}>
<Head>
<title>{getPageTitle('El Calentico - Tu Tienda Virtual')}</title>
</Head>
<CartDrawer />
{/* Navigation / Header */}
<nav className={`sticky top-0 z-40 w-full border-b ${darkMode ? 'bg-dark-800 border-dark-700' : 'bg-white border-gray-200'} px-4 py-3 shadow-sm`}>
<div className="container mx-auto flex items-center justify-between">
<Link href="/" className="flex items-center gap-2">
<span className="text-2xl font-bold text-orange-600">El Calentico</span>
</Link>
<div className="flex items-center gap-4">
<Link href="/search" className="hidden md:block text-sm font-medium hover:text-orange-600 transition-colors">
Buscar
</Link>
{/* Cart Toggle Button */}
<button
onClick={() => dispatch(toggleCart())}
className="relative p-2 text-gray-600 hover:text-orange-600 transition-colors"
>
<BaseIcon path={mdiCartOutline} size={28} />
{cartCount > 0 && (
<span className="absolute top-0 right-0 bg-orange-600 text-white text-[10px] font-bold w-5 h-5 flex items-center justify-center rounded-full border-2 border-white">
{cartCount}
</span>
)}
</button>
{currentUser ? (
<Link href="/dashboard" className="text-sm font-medium px-4 py-2 rounded-full bg-orange-600 text-white hover:bg-orange-700 transition-colors">
Dashboard
</Link>
) : (
<div className="flex items-center gap-2">
<Link href="/login" className="hidden sm:block text-sm font-medium hover:text-orange-600 transition-colors">
Iniciar Sesión
</Link>
<Link href="/register" className="text-sm font-medium px-4 py-2 rounded-full bg-orange-600 text-white hover:bg-orange-700 transition-colors">
Registrarse
</Link>
</div>
)}
</div>
</div>
</nav>
<ElCalenticoHeader />
<CartDrawer isOpen={isCartOpen} onClose={() => dispatch(toggleCart())} />
{/* Hero Section */}
<section className="relative h-[500px] w-full overflow-hidden flex items-center">
<div className="absolute inset-0 z-0">
<img src={heroImage} alt="Food hero" className="w-full h-full object-cover" />
<div className="absolute inset-0 bg-black/40"></div>
<section className="relative pt-32 pb-20 lg:pt-48 lg:pb-32 overflow-hidden">
<div className="absolute top-0 left-1/2 -translate-x-1/2 w-full h-full -z-10 opacity-10">
<div className="absolute top-0 left-0 w-96 h-96 bg-orange-600 rounded-full blur-3xl -translate-x-1/2 -translate-y-1/2"></div>
<div className="absolute bottom-0 right-0 w-96 h-96 bg-yellow-400 rounded-full blur-3xl translate-x-1/2 translate-y-1/2"></div>
</div>
<div className="container mx-auto relative z-10 px-4">
<div className="max-w-2xl text-white">
<h1 className="text-5xl md:text-6xl font-extrabold mb-6 leading-tight">
Sabor y Frescura <br />
<span className="text-orange-400">Directo a tu Mesa</span>
</h1>
<p className="text-xl mb-8 text-gray-100">
Descubre la mejor selección de alimentos, bebidas y productos locales en El Calentico. Calidad garantizada en cada pedido.
</p>
<div className="flex gap-4">
<BaseButton
label="Comprar Ahora"
color="warning"
roundedFull
className="px-8 py-3 text-lg font-bold"
href="#products"
/>
<BaseButton
label="Ver Categorías"
color="white"
outline
roundedFull
className="px-8 py-3 text-lg font-bold"
href="#categories"
/>
<div className="container mx-auto px-4">
<div className="flex flex-col lg:flex-row items-center gap-12">
<div className="lg:w-1/2 text-center lg:text-left">
<div className="inline-flex items-center gap-2 bg-orange-100 text-orange-600 px-4 py-2 rounded-full mb-6 animate-fade-in">
<BaseIcon path={mdiFire} size={20} />
<span className="font-bold text-sm uppercase tracking-wider">¡Nuevas Ofertas Cada Día!</span>
</div>
<h1 className="text-6xl lg:text-8xl font-black leading-tight mb-8 tracking-tighter">
Frescura que <span className="text-orange-600">Alimenta</span> tu Vida.
</h1>
<p className="text-xl text-gray-600 dark:text-gray-400 mb-10 max-w-xl leading-relaxed">
Descubre la mejor selección de productos locales, snacks, bebidas y mucho más. Calidad garantizada en la puerta de tu casa en menos de 60 minutos.
</p>
<div className="flex flex-col sm:flex-row items-center justify-center lg:justify-start gap-4">
<BaseButton
label="Explorar Menú"
color="pavitra"
roundedFull
className="px-10 py-4 text-lg font-bold shadow-lg shadow-orange-600/30 transition-transform hover:scale-105"
onClick={() => document.getElementById('products')?.scrollIntoView({ behavior: 'smooth' })}
/>
<div className="flex items-center gap-4 text-gray-500 font-medium">
<div className="flex -space-x-3">
{[1,2,3,4].map(i => (
<div key={i} className="w-10 h-10 rounded-full border-2 border-white bg-gray-200 flex items-center justify-center text-xs font-bold overflow-hidden">
<img src={`https://i.pravatar.cc/100?u=${i}`} alt="user" className="w-full h-full object-cover" />
</div>
))}
</div>
<span>+2k clientes felices</span>
</div>
</div>
</div>
<div className="lg:w-1/2 relative">
<div className="relative z-10 animate-bounce-slow">
<img
src="https://images.pexels.com/photos/1132047/pexels-photo-1132047.jpeg?auto=compress&cs=tinysrgb&w=800"
alt="Fresh food basket"
className="rounded-[3rem] shadow-2xl rotate-3 hover:rotate-0 transition-transform duration-700"
/>
<div className="absolute -bottom-10 -left-10 bg-white dark:bg-dark-800 p-6 rounded-3xl shadow-xl animate-fade-in-up">
<div className="flex items-center gap-4">
<div className="bg-green-100 p-3 rounded-2xl">
<BaseIcon path={mdiTruckFast} size={32} className="text-green-600" />
</div>
<div>
<p className="font-black text-2xl text-gray-800 dark:text-white">60 min</p>
<p className="text-sm text-gray-500">Entrega promedio</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
{/* Categories Section */}
<section id="categories" className="py-16 bg-white dark:bg-dark-800">
<section id="categories" className={`py-24 ${darkMode ? 'bg-dark-800' : 'bg-gray-50'} rounded-[4rem]`}>
<div className="container mx-auto px-4">
<div className="flex justify-between items-end mb-10">
<div className="flex flex-col md:flex-row justify-between items-end mb-16 gap-6">
<div>
<h2 className="text-3xl font-bold mb-2">Categorías</h2>
<p className="text-gray-500">Explora nuestra variedad de productos</p>
<h2 className="text-4xl lg:text-5xl font-black mb-4 tracking-tight">Busca por Categoría</h2>
<p className="text-gray-500 text-lg max-w-md font-medium">Todo lo que necesitas, organizado para tu comodidad.</p>
</div>
<div className="flex gap-2">
<button
onClick={() => setSelectedCategory(null)}
className={`px-6 py-3 rounded-2xl font-bold transition-all ${!selectedCategory ? 'bg-orange-600 text-white shadow-lg' : 'bg-white text-gray-600 hover:bg-gray-100'}`}
>
Todos
</button>
{categoriesLoading ? (
<LoadingSpinner />
) : (
categories.slice(0, 5).map((cat: any) => (
<button
key={cat.id}
onClick={() => setSelectedCategory(cat.id)}
className={`px-6 py-3 rounded-2xl font-bold transition-all ${selectedCategory === cat.id ? 'bg-orange-600 text-white shadow-lg' : 'bg-white text-gray-600 hover:bg-gray-100'}`}
>
{cat.name}
</button>
))
)}
</div>
</div>
{categoriesLoading ? (
<div className="flex justify-center py-10"><LoadingSpinner /></div>
) : (
<div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
{product_categories?.map((cat: any) => (
<Link
key={cat.id}
href={`/search?category=${cat.id}`}
className={`group flex flex-col items-center p-6 rounded-2xl transition-all hover:shadow-lg ${darkMode ? 'bg-dark-700 border-dark-600 hover:bg-dark-600' : 'bg-gray-50 border-gray-100 hover:bg-orange-50 hover:border-orange-200'} border`}
>
<div className="w-16 h-16 bg-orange-100 rounded-full flex items-center justify-center mb-4 group-hover:scale-110 transition-transform">
<span className="text-2xl font-bold text-orange-600">{cat.name.charAt(0)}</span>
</div>
<span className="font-semibold text-center group-hover:text-orange-600">{cat.name}</span>
</Link>
))}
</div>
)}
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-6">
{categories.map((category: any) => (
<button
key={category.id}
onClick={() => setSelectedCategory(category.id)}
className={`group p-8 rounded-[2.5rem] transition-all duration-500 text-center flex flex-col items-center gap-4 ${
selectedCategory === category.id
? 'bg-orange-600 text-white shadow-2xl scale-105'
: 'bg-white dark:bg-dark-700 hover:shadow-xl hover:-translate-y-2'
}`}
>
<div className={`w-16 h-16 rounded-2xl flex items-center justify-center transition-colors ${selectedCategory === category.id ? 'bg-white/20' : 'bg-orange-100 group-hover:bg-orange-600 group-hover:text-white'}`}>
<BaseIcon path={mdiFoodApple} size={32} />
</div>
<span className="font-black text-lg tracking-tight">{category.name}</span>
</button>
))}
</div>
</div>
</section>
{/* Featured Products */}
<section id="products" className="py-16">
{/* Products Grid */}
<section id="products" className="py-24">
<div className="container mx-auto px-4">
<div className="flex justify-between items-end mb-10">
<div>
<h2 className="text-3xl font-bold mb-2">Productos Destacados</h2>
<p className="text-gray-500">Lo más buscado de esta semana</p>
</div>
<Link href="/search" className="text-orange-600 font-bold flex items-center gap-1 hover:underline">
Ver todos <BaseIcon path={mdiArrowRight} size={20} />
<div className="flex items-center justify-between mb-16">
<h2 className="text-4xl lg:text-5xl font-black tracking-tight">Nuestros Productos</h2>
<Link href="/search" className="text-orange-600 font-bold flex items-center gap-2 hover:gap-4 transition-all group">
Ver catálogo completo <BaseIcon path={mdiArrowRight} size={24} />
</Link>
</div>
{productsLoading ? (
<div className="flex justify-center py-10"><LoadingSpinner /></div>
<div className="py-20 flex justify-center"><LoadingSpinner /></div>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-8">
{products?.map((product: any) => (
<div key={product.id} className={`group flex flex-col overflow-hidden rounded-2xl shadow-sm border transition-all hover:shadow-xl ${darkMode ? 'bg-dark-800 border-dark-700' : 'bg-white border-gray-200'}`}>
<Link href={`/products/products-view/?id=${product.id}`} className="relative h-64 overflow-hidden">
<ImageField
image={product.images}
className="h-full w-full object-cover transition-transform duration-500 group-hover:scale-110"
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-10">
{filteredProducts.map((product: any) => (
<div
key={product.id}
className="group bg-white dark:bg-dark-800 rounded-[3rem] overflow-hidden shadow-sm hover:shadow-2xl transition-all duration-500 border border-gray-100 dark:border-dark-700"
>
<div className="h-64 overflow-hidden relative">
<img
src={product.image?.length > 0 ? product.image[0].publicUrl : 'https://images.pexels.com/photos/1132047/pexels-photo-1132047.jpeg?auto=compress&cs=tinysrgb&w=400'}
alt={product.name}
className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-700"
/>
{product.price < product.compare_at_price && (
<div className="absolute top-4 left-4 bg-red-600 text-white text-xs font-bold px-3 py-1 rounded-full">
OFERTA
{product.is_featured && (
<div className="absolute top-6 left-6 bg-orange-600 text-white text-xs font-black px-4 py-2 rounded-full uppercase tracking-widest shadow-lg">
Destacado
</div>
)}
</Link>
<div className="p-6 flex flex-col flex-grow">
<div className="text-xs text-gray-500 mb-2 uppercase tracking-wider font-semibold">
{product.category?.name || 'Producto'}
</div>
<div className="p-8">
<div className="mb-2">
{categories.find((c: any) => c.id === product.categoryId) && (
<span className="text-xs font-bold text-orange-600 uppercase tracking-widest bg-orange-100 px-3 py-1 rounded-lg">
{(categories.find((c: any) => c.id === product.categoryId) as any).name}
</span>
)}
</div>
<Link href={`/products/products-view/?id=${product.id}`}>
<h3 className="text-lg font-bold mb-2 group-hover:text-orange-600 transition-colors line-clamp-2">{product.name}</h3>
</Link>
<div className="mt-auto flex items-center justify-between">
<h3 className="text-2xl font-black mb-3 text-gray-800 dark:text-white group-hover:text-orange-600 transition-colors line-clamp-1">{product.name}</h3>
<p className="text-gray-500 dark:text-gray-400 text-sm mb-6 line-clamp-2 font-medium">{product.short_description}</p>
<div className="flex items-center justify-between">
<div className="flex flex-col">
{product.compare_at_price > 0 && (
<span className="text-sm text-gray-400 line-through">${product.compare_at_price}</span>
<span className="text-sm text-gray-400 line-through font-bold">${product.compare_at_price}</span>
)}
<span className="text-2xl font-extrabold text-orange-600">${product.price}</span>
<span className="text-3xl font-black text-gray-900 dark:text-white">${product.price}</span>
</div>
<button
onClick={() => handleAddToCart(product)}
className="p-3 bg-gray-100 hover:bg-orange-600 hover:text-white rounded-full transition-all duration-300 group/cart"
className="p-4 bg-gray-100 dark:bg-dark-700 hover:bg-orange-600 text-gray-900 dark:text-white hover:text-white rounded-full transition-all duration-300 group/cart shadow-sm hover:shadow-orange-600/30"
title="Añadir al carrito"
>
<BaseIcon path={mdiCartOutline} size={24} />
<BaseIcon path={mdiCartOutline} size={28} />
</button>
</div>
</div>
@ -221,60 +236,32 @@ export default function Home() {
</section>
{/* CTA Section */}
<section className="py-20 bg-orange-600 text-white">
<div className="container mx-auto px-4 text-center">
<h2 className="text-4xl font-bold mb-6">¿Listo para hacer tu primer pedido?</h2>
<p className="text-xl mb-10 max-w-2xl mx-auto opacity-90">
Únete a miles de clientes satisfechos que ya disfrutan de la frescura de El Calentico en sus hogares.
</p>
<BaseButton
label="Crear una Cuenta Gratis"
color="white"
roundedFull
className="px-10 py-4 text-lg font-bold text-orange-600"
href="/register"
/>
<section className="py-24">
<div className="container mx-auto px-4">
<div className="bg-orange-600 rounded-[4rem] p-12 lg:p-24 text-center text-white relative overflow-hidden shadow-2xl shadow-orange-600/40">
<div className="absolute top-0 right-0 w-64 h-64 bg-white/10 rounded-full blur-3xl -translate-y-1/2 translate-x-1/2"></div>
<div className="relative z-10">
<h2 className="text-5xl lg:text-6xl font-black mb-8 tracking-tighter">¿Listo para hacer tu primer pedido?</h2>
<p className="text-xl mb-12 max-w-2xl mx-auto opacity-90 leading-relaxed font-medium">
Únete a miles de clientes satisfechos que ya disfrutan de la frescura de El Calentico en sus hogares.
</p>
<BaseButton
label="Crear una Cuenta Gratis"
color="white"
roundedFull
className="px-12 py-5 text-xl font-bold text-orange-600 shadow-xl transition-transform hover:scale-105"
href="/register"
/>
</div>
</div>
</div>
</section>
{/* Footer */}
<footer className={`py-12 ${darkMode ? 'bg-dark-800 text-gray-400' : 'bg-gray-100 text-gray-600'}`}>
<div className="container mx-auto px-4">
<div className="grid grid-cols-1 md:grid-cols-4 gap-12 mb-12">
<div className="col-span-1 md:col-span-2">
<h3 className="text-2xl font-bold text-orange-600 mb-6">El Calentico</h3>
<p className="mb-6 max-w-md">
Tu tienda virtual de confianza para alimentos, bebidas y productos del día a día. Llevamos la mejor calidad directamente a tu puerta.
</p>
</div>
<div>
<h4 className="text-lg font-bold mb-6 text-gray-900 dark:text-white">Enlaces Rápidos</h4>
<ul className="space-y-4">
<li><Link href="/search" className="hover:text-orange-600 transition-colors">Productos</Link></li>
<li><Link href="#categories" className="hover:text-orange-600 transition-colors">Categorías</Link></li>
<li><Link href="/login" className="hover:text-orange-600 transition-colors">Mi Cuenta</Link></li>
</ul>
</div>
<div>
<h4 className="text-lg font-bold mb-6 text-gray-900 dark:text-white">Legal</h4>
<ul className="space-y-4">
<li><Link href="/privacy-policy" className="hover:text-orange-600 transition-colors">Privacidad</Link></li>
<li><Link href="/terms-of-use" className="hover:text-orange-600 transition-colors">Términos</Link></li>
</ul>
</div>
</div>
<div className="border-t border-gray-200 dark:border-dark-700 pt-8 flex flex-col md:flex-row justify-between items-center gap-4">
<p className="text-sm">© 2026 El Calentico. Todos los derechos reservados.</p>
<div className="flex gap-6">
{/* Social icons could go here */}
</div>
</div>
</div>
</footer>
<ElCalenticoFooter />
</div>
);
}
Home.getLayout = function getLayout(page: ReactElement) {
return <LayoutGuest>{page}</LayoutGuest>;
};
};

View File

@ -0,0 +1,164 @@
import * as icon from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement, useEffect, useState } from 'react';
import LayoutAuthenticated from '../../layouts/Authenticated';
import SectionMain from '../../components/SectionMain';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import BaseIcon from "../../components/BaseIcon";
import { getPageTitle } from '../../config';
import CardBox from '../../components/CardBox';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import axios from 'axios';
import KanbanBoard from '../../components/KanbanBoard/KanbanBoard';
import { deleteItem, update } from '../../stores/orders/ordersSlice';
import TableOrders from '../../components/Orders/TableOrders';
const OrderDashboard = () => {
const { currentUser } = useAppSelector((state) => state.auth);
const iconsColor = useAppSelector((state) => state.style.iconsColor);
const corners = useAppSelector((state) => state.style.corners);
const cardsStyle = useAppSelector((state) => state.style.cardsStyle);
const [stats, setStats] = useState({
totalRevenue: 0,
pendingOrders: 0,
totalOrders: 0,
processingOrders: 0
});
// Use these to avoid lint error for empty functions
const [filterItems, setFilterItems] = useState([]);
const kanbanColumns = [
{ id: 'pending', label: 'Pending' },
{ id: 'confirmed', label: 'Confirmed' },
{ id: 'processing', label: 'Processing' },
{ id: 'shipped', label: 'Shipped' },
{ id: 'delivered', label: 'Delivered' },
];
useEffect(() => {
const fetchStats = async () => {
try {
const response = await axios.get('/orders?limit=1000'); // Fetch enough for stats
const orders = response.data.rows || [];
const totalRevenue = orders
.filter(o => ['confirmed', 'processing', 'shipped', 'delivered'].includes(o.status))
.reduce((acc, o) => acc + (Number(o.total_amount) || 0), 0);
const pendingOrders = orders.filter(o => o.status === 'pending').length;
const processingOrders = orders.filter(o => o.status === 'processing').length;
setStats({
totalRevenue,
pendingOrders,
totalOrders: response.data.count || orders.length,
processingOrders
});
} catch (error) {
console.error('Error fetching order stats:', error);
}
};
if (currentUser) {
fetchStats();
}
}, [currentUser]);
return (
<>
<Head>
<title>{getPageTitle('Order Dashboard')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={icon.mdiReceiptTextCheck}
title="Order Dashboard"
main
>
{''}
</SectionTitleLineWithButton>
<div className="grid grid-cols-1 gap-6 lg:grid-cols-4 mb-6">
<CardBox className={`${cardsStyle}`}>
<div className="flex justify-between items-center">
<div>
<p className="text-gray-500 dark:text-gray-400">Total Revenue</p>
<h3 className="text-2xl font-bold">${stats.totalRevenue.toFixed(2)}</h3>
</div>
<BaseIcon path={icon.mdiCurrencyUsd} size={48} className="text-green-500" />
</div>
</CardBox>
<CardBox className={`${cardsStyle}`}>
<div className="flex justify-between items-center">
<div>
<p className="text-gray-500 dark:text-gray-400">Pending Orders</p>
<h3 className="text-2xl font-bold">{stats.pendingOrders}</h3>
</div>
<BaseIcon path={icon.mdiClockOutline} size={48} className="text-yellow-500" />
</div>
</CardBox>
<CardBox className={`${cardsStyle}`}>
<div className="flex justify-between items-center">
<div>
<p className="text-gray-500 dark:text-gray-400">Processing</p>
<h3 className="text-2xl font-bold">{stats.processingOrders}</h3>
</div>
<BaseIcon path={icon.mdiLoading} size={48} className="text-blue-500 animate-spin" />
</div>
</CardBox>
<CardBox className={`${cardsStyle}`}>
<div className="flex justify-between items-center">
<div>
<p className="text-gray-500 dark:text-gray-400">Total Orders</p>
<h3 className="text-2xl font-bold">{stats.totalOrders}</h3>
</div>
<BaseIcon path={icon.mdiPackageVariant} size={48} className="text-purple-500" />
</div>
</CardBox>
</div>
<SectionTitleLineWithButton icon={icon.mdiViewColumn} title="Order Processing (Kanban)">
{''}
</SectionTitleLineWithButton>
<div className="mb-6">
<KanbanBoard
columns={kanbanColumns}
entityName="orders"
columnFieldName="status"
filtersQuery=""
showFieldName="order_number"
deleteThunk={deleteItem}
updateThunk={update}
/>
</div>
<SectionTitleLineWithButton icon={icon.mdiHistory} title="Recent Orders">
{''}
</SectionTitleLineWithButton>
<TableOrders
filterItems={filterItems}
setFilterItems={setFilterItems}
filters={[]}
showGrid={true}
/>
</SectionMain>
</>
);
};
OrderDashboard.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'READ_ORDERS'}>
{page}
</LayoutAuthenticated>
);
};
export default OrderDashboard;

View File

@ -13,8 +13,15 @@ interface LocalCartState {
isOpen: boolean;
}
const getInitialItems = () => {
if (typeof window !== 'undefined') {
return JSON.parse(localStorage.getItem('cart') || '[]');
}
return [];
};
const initialState: LocalCartState = {
items: typeof window !== 'undefined' ? JSON.parse(localStorage.getItem('cart') || '[]') : [],
items: getInitialItems(),
isOpen: false,
};
@ -36,7 +43,7 @@ export const localCartSlice = createSlice({
localStorage.setItem('cart', JSON.stringify(state.items));
},
updateQuantity: (state, action: PayloadAction<{ id: string; quantity: number }>) => {
const item = state.items.find((item) => item.id === action.id);
const item = state.items.find((item) => item.id === action.payload.id);
if (item) {
item.quantity = Math.max(0, action.payload.quantity);
if (item.quantity === 0) {
@ -60,4 +67,4 @@ export const localCartSlice = createSlice({
export const { addToCart, removeFromCart, updateQuantity, clearCart, toggleCart, setCartOpen } = localCartSlice.actions;
export default localCartSlice.reducer;
export default localCartSlice.reducer;