Compare commits

...

1 Commits

Author SHA1 Message Date
Flatlogic Bot
6665c5048a veg 2026-03-26 17:06:10 +00:00
8 changed files with 1738 additions and 169 deletions

View File

@ -103,6 +103,11 @@ router.post('/', wrapAsync(async (req, res) => {
res.status(200).send(payload);
}));
router.post('/checkout', wrapAsync(async (req, res) => {
const payload = await OrdersService.checkout(req.body.data, req.currentUser);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/budgets/bulk-import:

View File

@ -1,15 +1,23 @@
const db = require('../db/models');
const OrdersDBApi = require('../db/api/orders');
const processFile = require("../middlewares/upload");
const Order_itemsDBApi = require('../db/api/order_items');
const AddressesDBApi = require('../db/api/addresses');
const PaymentsDBApi = require('../db/api/payments');
const Inventory_adjustmentsDBApi = require('../db/api/inventory_adjustments');
const processFile = require('../middlewares/upload');
const ValidationError = require('./notifications/errors/validation');
const csv = require('csv-parser');
const axios = require('axios');
const config = require('../config');
const stream = require('stream');
const { Op } = db.Sequelize;
const roundCurrency = (value) => Number(Number(value || 0).toFixed(2));
const badRequest = (message) => {
const error = new Error(message);
error.code = 400;
return error;
};
module.exports = class OrdersService {
static async create(data, currentUser) {
@ -28,9 +36,285 @@ module.exports = class OrdersService {
await transaction.rollback();
throw error;
}
};
}
static async bulkImport(req, res, sendInvitationEmails = true, host) {
static async checkout(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
if (!currentUser?.id) {
throw badRequest('You must be signed in to place an order.');
}
const fulfillmentMethod = data?.fulfillment_method;
if (!['delivery', 'pickup'].includes(fulfillmentMethod)) {
throw badRequest('Choose delivery or pickup before placing your order.');
}
const rawItems = Array.isArray(data?.items) ? data.items : [];
const aggregatedItems = rawItems.reduce((accumulator, item) => {
const productId = item?.productId;
const quantity = Number(item?.quantity || 0);
if (!productId || quantity <= 0) {
return accumulator;
}
accumulator[productId] = (accumulator[productId] || 0) + quantity;
return accumulator;
}, {});
const items = Object.entries(aggregatedItems).map(([productId, quantity]) => ({
productId,
quantity,
}));
if (!items.length) {
throw badRequest('Add at least one vegetable to your cart before checkout.');
}
const productIds = items.map((item) => item.productId);
const products = await db.products.findAll({
where: {
id: {
[Op.in]: productIds,
},
is_active: true,
},
transaction,
});
if (products.length !== productIds.length) {
throw badRequest('Some vegetables are no longer available. Refresh the catalog and try again.');
}
const productMap = new Map(products.map((product) => [product.id, product]));
let deliverySlot = null;
if (!data?.delivery_slotId) {
throw badRequest('Choose a delivery or pickup slot before placing your order.');
}
deliverySlot = await db.delivery_slots.findOne({
where: {
id: data.delivery_slotId,
is_active: true,
},
transaction,
});
if (!deliverySlot) {
throw badRequest('The selected slot is unavailable. Please choose another slot.');
}
if (deliverySlot.slot_type !== fulfillmentMethod) {
throw badRequest('The selected slot does not match your fulfillment method.');
}
if (
deliverySlot.capacity !== null
&& deliverySlot.capacity !== undefined
&& Number(deliverySlot.reserved_count || 0) >= Number(deliverySlot.capacity)
) {
throw badRequest('That slot is full. Please choose a different time.');
}
let deliveryAddress = null;
if (fulfillmentMethod === 'delivery') {
if (data?.delivery_addressId) {
deliveryAddress = await db.addresses.findOne({
where: {
id: data.delivery_addressId,
userId: currentUser.id,
},
transaction,
});
if (!deliveryAddress) {
throw badRequest('We could not find the selected delivery address.');
}
} else {
const addressInput = data?.delivery_address || {};
const requiredFields = ['recipient_name', 'phone', 'line1', 'city', 'state', 'postal_code', 'country'];
const hasMissingFields = requiredFields.some((field) => !addressInput[field]);
if (hasMissingFields) {
throw badRequest('Complete the delivery address before placing your order.');
}
deliveryAddress = await AddressesDBApi.create(
{
address_type: 'delivery',
label: addressInput.label || 'Fresh delivery',
recipient_name: addressInput.recipient_name,
phone: addressInput.phone,
line1: addressInput.line1,
line2: addressInput.line2 || null,
city: addressInput.city,
state: addressInput.state,
postal_code: addressInput.postal_code,
country: addressInput.country,
is_default: false,
user: currentUser.id,
},
{
currentUser,
transaction,
},
);
}
}
const paymentProvider = data?.payment_provider
|| (fulfillmentMethod === 'delivery' ? 'cash_on_delivery' : 'cash_on_pickup');
if (!['cash_on_delivery', 'cash_on_pickup'].includes(paymentProvider)) {
throw badRequest('This first checkout supports pay on delivery or pay on pickup only.');
}
const lineItems = items.map((item) => {
const product = productMap.get(item.productId);
const quantity = Number(item.quantity);
const stockQuantity = Number(product.stock_quantity || 0);
if (stockQuantity < quantity) {
throw badRequest(`${product.name} only has ${stockQuantity} left in stock.`);
}
const unitPrice = roundCurrency(product.price);
const lineSubtotal = roundCurrency(unitPrice * quantity);
const lineTax = product.is_taxable
? roundCurrency(lineSubtotal * Number(product.tax_rate || 0))
: 0;
const lineTotal = roundCurrency(lineSubtotal + lineTax);
return {
product,
quantity,
unitPrice,
lineSubtotal,
lineTax,
lineTotal,
};
});
const subtotalAmount = roundCurrency(
lineItems.reduce((sum, item) => sum + item.lineSubtotal, 0),
);
const taxAmount = roundCurrency(
lineItems.reduce((sum, item) => sum + item.lineTax, 0),
);
const deliveryFee = fulfillmentMethod === 'delivery' ? 4.99 : 0;
const totalAmount = roundCurrency(subtotalAmount + taxAmount + deliveryFee);
const orderNumber = `VEG-${new Date().toISOString().replace(/\D/g, '').slice(0, 12)}-${Math.floor(100 + Math.random() * 900)}`;
const order = await OrdersDBApi.create(
{
order_number: orderNumber,
status: 'processing',
fulfillment_method: fulfillmentMethod,
subtotal_amount: subtotalAmount,
discount_amount: 0,
tax_amount: taxAmount,
delivery_fee: deliveryFee,
total_amount: totalAmount,
payment_status: 'unpaid',
customer_note: data?.customer_note || null,
placed_at: new Date(),
user: currentUser.id,
delivery_slot: deliverySlot.id,
delivery_address: deliveryAddress?.id || null,
billing_address: deliveryAddress?.id || null,
},
{
currentUser,
transaction,
},
);
for (const item of lineItems) {
await Order_itemsDBApi.create(
{
order: order.id,
product: item.product.id,
product_name: item.product.name,
product_sku: item.product.sku,
unit: item.product.unit,
unit_size: item.product.unit_size,
quantity: item.quantity,
unit_price: item.unitPrice,
line_subtotal: item.lineSubtotal,
line_tax: item.lineTax,
line_total: item.lineTotal,
},
{
currentUser,
transaction,
},
);
const nextStockQuantity = Number(item.product.stock_quantity || 0) - item.quantity;
await item.product.update(
{
stock_quantity: nextStockQuantity,
updatedById: currentUser.id,
},
{
transaction,
},
);
await Inventory_adjustmentsDBApi.create(
{
product: item.product.id,
reason: 'sale',
quantity_change: -item.quantity,
note: `Order ${orderNumber}`,
effective_at: new Date(),
},
{
currentUser,
transaction,
},
);
}
await deliverySlot.update(
{
reserved_count: Number(deliverySlot.reserved_count || 0) + 1,
updatedById: currentUser.id,
},
{
transaction,
},
);
await PaymentsDBApi.create(
{
order: order.id,
provider: paymentProvider,
status: 'initiated',
amount: totalAmount,
currency: 'USD',
provider_reference: orderNumber,
},
{
currentUser,
transaction,
},
);
await transaction.commit();
return OrdersDBApi.findBy({ id: order.id });
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async bulkImport(req, res) {
const transaction = await db.sequelize.transaction();
try {
@ -38,7 +322,7 @@ module.exports = class OrdersService {
const bufferStream = new stream.PassThrough();
const results = [];
await bufferStream.end(Buffer.from(req.file.buffer, "utf-8")); // convert Buffer to Stream
await bufferStream.end(Buffer.from(req.file.buffer, 'utf-8'));
await new Promise((resolve, reject) => {
bufferStream
@ -49,13 +333,13 @@ module.exports = class OrdersService {
resolve();
})
.on('error', (error) => reject(error));
})
});
await OrdersDBApi.bulkImport(results, {
transaction,
ignoreDuplicates: true,
validate: true,
currentUser: req.currentUser
transaction,
ignoreDuplicates: true,
validate: true,
currentUser: req.currentUser,
});
await transaction.commit();
@ -68,9 +352,9 @@ module.exports = class OrdersService {
static async update(data, id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
let orders = await OrdersDBApi.findBy(
{id},
{transaction},
const orders = await OrdersDBApi.findBy(
{ id },
{ transaction },
);
if (!orders) {
@ -90,12 +374,11 @@ module.exports = class OrdersService {
await transaction.commit();
return updatedOrders;
} catch (error) {
await transaction.rollback();
throw error;
}
};
}
static async deleteByIds(ids, currentUser) {
const transaction = await db.sequelize.transaction();
@ -131,8 +414,4 @@ module.exports = class OrdersService {
throw error;
}
}
};

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'

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'

View File

@ -8,6 +8,14 @@ const menuAside: MenuAsideItem[] = [
label: 'Dashboard',
},
{
href: '/shop',
label: 'Storefront',
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
icon: 'mdiStorefrontOutline' in icon ? icon['mdiStorefrontOutline' as keyof typeof icon] : icon.mdiCart ?? icon.mdiTable,
},
{
href: '/users/users-list',
label: 'Users',

View File

@ -1,166 +1,219 @@
import React, { useEffect, useState } from 'react';
import {
mdiArrowRight,
mdiBasketOutline,
mdiCarrot,
mdiCheckCircleOutline,
mdiClockOutline,
mdiLeaf,
mdiShieldCheckOutline,
mdiStorefrontOutline,
mdiTruckFastOutline,
} from '@mdi/js';
import type { ReactElement } from 'react';
import Head from 'next/head';
import Link from 'next/link';
import React from 'react';
import BaseButton from '../components/BaseButton';
import BaseIcon from '../components/BaseIcon';
import CardBox from '../components/CardBox';
import SectionFullScreen from '../components/SectionFullScreen';
import LayoutGuest from '../layouts/Guest';
import BaseDivider from '../components/BaseDivider';
import BaseButtons from '../components/BaseButtons';
import { getPageTitle } from '../config';
import { useAppSelector } from '../stores/hooks';
import CardBoxComponentTitle from "../components/CardBoxComponentTitle";
import { getPexelsImage, getPexelsVideo } from '../helpers/pexels';
const featureCards = [
{
icon: mdiCarrot,
title: 'Vegetable catalog',
description: 'Highlight your freshest produce with prices, units, stock visibility, and featured seasonal picks.',
},
{
icon: mdiBasketOutline,
title: 'Quick basket flow',
description: 'Let customers build a basket, review totals instantly, and move into checkout without friction.',
},
{
icon: mdiClockOutline,
title: 'Delivery or pickup',
description: 'Offer scheduled delivery or pickup windows so shoppers can choose how they receive fresh produce.',
},
];
export default function Starter() {
const [illustrationImage, setIllustrationImage] = useState({
src: undefined,
photographer: undefined,
photographer_url: undefined,
})
const [illustrationVideo, setIllustrationVideo] = useState({video_files: []})
const [contentType, setContentType] = useState('image');
const [contentPosition, setContentPosition] = useState('background');
const textColor = useAppSelector((state) => state.style.linkColor);
const title = 'Veggie Shop'
// Fetch Pexels image/video
useEffect(() => {
async function fetchData() {
const image = await getPexelsImage();
const video = await getPexelsVideo();
setIllustrationImage(image);
setIllustrationVideo(video);
}
fetchData();
}, []);
const imageBlock = (image) => (
<div
className='hidden md:flex flex-col justify-end relative flex-grow-0 flex-shrink-0 w-1/3'
style={{
backgroundImage: `${
image
? `url(${image?.src?.original})`
: 'linear-gradient(rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5))'
}`,
backgroundSize: 'cover',
backgroundPosition: 'left center',
backgroundRepeat: 'no-repeat',
}}
>
<div className='flex justify-center w-full bg-blue-300/20'>
<a
className='text-[8px]'
href={image?.photographer_url}
target='_blank'
rel='noreferrer'
>
Photo by {image?.photographer} on Pexels
</a>
</div>
</div>
);
const videoBlock = (video) => {
if (video?.video_files?.length > 0) {
return (
<div className='hidden md:flex flex-col justify-end relative flex-grow-0 flex-shrink-0 w-1/3'>
<video
className='absolute top-0 left-0 w-full h-full object-cover'
autoPlay
loop
muted
>
<source src={video?.video_files[0]?.link} type='video/mp4'/>
Your browser does not support the video tag.
</video>
<div className='flex justify-center w-full bg-blue-300/20 z-10'>
<a
className='text-[8px]'
href={video?.user?.url}
target='_blank'
rel='noreferrer'
>
Video by {video.user.name} on Pexels
</a>
</div>
</div>)
}
};
const workflowSteps = [
{
icon: mdiLeaf,
title: 'Browse the produce',
description: 'Search the catalog, scan categories, and discover featured vegetables with clear pricing.',
},
{
icon: mdiTruckFastOutline,
title: 'Choose fulfillment',
description: 'Select delivery or pickup, reserve a time slot, and add any order notes.',
},
{
icon: mdiCheckCircleOutline,
title: 'Place and track',
description: 'Confirm the order, create the payment placeholder, and jump straight into order details.',
},
];
export default function HomePage() {
return (
<div
style={
contentPosition === 'background'
? {
backgroundImage: `${
illustrationImage
? `url(${illustrationImage.src?.original})`
: 'linear-gradient(rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5))'
}`,
backgroundSize: 'cover',
backgroundPosition: 'left center',
backgroundRepeat: 'no-repeat',
}
: {}
}
>
<>
<Head>
<title>{getPageTitle('Starter Page')}</title>
<title>{getPageTitle('Fresh vegetable storefront')}</title>
</Head>
<SectionFullScreen bg='violet'>
<div
className={`flex ${
contentPosition === 'right' ? 'flex-row-reverse' : 'flex-row'
} min-h-screen w-full`}
>
{contentType === 'image' && contentPosition !== 'background'
? imageBlock(illustrationImage)
: null}
{contentType === 'video' && contentPosition !== 'background'
? videoBlock(illustrationVideo)
: null}
<div className='flex items-center justify-center flex-col space-y-4 w-full lg:w-full'>
<CardBox className='w-full md:w-3/5 lg:w-2/3'>
<CardBoxComponentTitle title="Welcome to your Veggie Shop app!"/>
<div className="space-y-3">
<p className='text-center text-gray-500'>This is a React.js/Node.js app generated by the <a className={`${textColor}`} href="https://flatlogic.com/generator">Flatlogic Web App Generator</a></p>
<p className='text-center text-gray-500'>For guides and documentation please check
your local README.md and the <a className={`${textColor}`} href="https://flatlogic.com/documentation">Flatlogic documentation</a></p>
<div className="min-h-screen bg-[#F7FAF4] text-slate-900">
<header className="border-b border-emerald-100/80 bg-white/80 backdrop-blur">
<div className="mx-auto flex max-w-7xl items-center justify-between gap-4 px-6 py-4">
<Link href="/" className="flex items-center gap-3 text-slate-900">
<span className="inline-flex h-11 w-11 items-center justify-center rounded-2xl bg-gradient-to-br from-emerald-500 to-lime-500 text-white shadow-lg shadow-emerald-200">
<BaseIcon path={mdiCarrot} size={22} />
</span>
<span>
<span className="block text-xs font-semibold uppercase tracking-[0.24em] text-emerald-700">Veggie Shop</span>
<span className="block text-lg font-semibold">Fresh produce, modern ordering</span>
</span>
</Link>
<nav className="flex items-center gap-3">
<Link href="/login" className="text-sm font-semibold text-emerald-700 transition hover:text-emerald-800">
Login
</Link>
<BaseButton href="/dashboard" color="whiteDark" outline label="Admin interface" />
<BaseButton href="/shop" color="success" label="Open storefront" icon={mdiArrowRight} />
</nav>
</div>
</header>
<main>
<section className="mx-auto grid max-w-7xl gap-8 px-6 py-12 lg:grid-cols-[1.15fr_0.85fr] lg:items-center lg:py-20">
<div className="space-y-6">
<div className="inline-flex items-center gap-2 rounded-full border border-emerald-200 bg-white px-4 py-1 text-xs font-semibold uppercase tracking-[0.2em] text-emerald-700 shadow-sm">
<BaseIcon path={mdiLeaf} size={16} /> Fresh, clean, and ready for local produce commerce
</div>
<div className="space-y-4">
<h1 className="max-w-3xl text-5xl font-bold tracking-tight text-slate-950 md:text-6xl">
Sell vegetables online with a storefront that feels fresh from the first click.
</h1>
<p className="max-w-2xl text-base leading-7 text-slate-600 md:text-lg">
This first MVP slice gives you a modern vegetable catalog, a basket-to-checkout journey, and a real admin-backed order flow with delivery or pickup scheduling.
</p>
</div>
<div className="flex flex-wrap gap-3">
<BaseButton href="/shop" color="success" label="Start ordering" icon={mdiBasketOutline} />
<BaseButton href="/login" color="whiteDark" outline label="Login" />
<BaseButton href="/dashboard" color="info" label="View admin" />
</div>
<div className="grid gap-3 sm:grid-cols-3">
<div className="rounded-[1.5rem] border border-emerald-100 bg-white px-4 py-4 shadow-sm shadow-emerald-100/70">
<p className="text-xs font-semibold uppercase tracking-[0.2em] text-emerald-700">Catalog</p>
<p className="mt-2 text-sm text-slate-600">Seasonal produce cards with search, categories, and stock cues.</p>
</div>
<div className="rounded-[1.5rem] border border-emerald-100 bg-white px-4 py-4 shadow-sm shadow-emerald-100/70">
<p className="text-xs font-semibold uppercase tracking-[0.2em] text-emerald-700">Checkout</p>
<p className="mt-2 text-sm text-slate-600">Delivery or pickup slot selection with a fast, clear basket summary.</p>
</div>
<div className="rounded-[1.5rem] border border-emerald-100 bg-white px-4 py-4 shadow-sm shadow-emerald-100/70">
<p className="text-xs font-semibold uppercase tracking-[0.2em] text-emerald-700">Operations</p>
<p className="mt-2 text-sm text-slate-600">Real orders, payment placeholders, and inventory updates for admins.</p>
</div>
</div>
</div>
<BaseButtons>
<BaseButton
href='/login'
label='Login'
color='info'
className='w-full'
/>
</BaseButtons>
</CardBox>
</div>
</div>
</SectionFullScreen>
<div className='bg-black text-white flex flex-col text-center justify-center md:flex-row'>
<p className='py-6 text-sm'>© 2026 <span>{title}</span>. All rights reserved</p>
<Link className='py-6 ml-4 text-sm' href='/privacy-policy/'>
Privacy Policy
</Link>
</div>
<CardBox className="overflow-hidden border-0 bg-transparent shadow-none">
<div className="rounded-[2rem] bg-gradient-to-br from-slate-950 via-emerald-950 to-emerald-700 p-6 text-white shadow-2xl shadow-emerald-200/80">
<div className="grid gap-4">
<div className="rounded-[1.5rem] border border-white/10 bg-white/10 p-5 backdrop-blur">
<div className="flex items-center justify-between">
<div>
<p className="text-xs uppercase tracking-[0.2em] text-emerald-100">Today&apos;s storefront</p>
<h2 className="mt-2 text-2xl font-semibold">Simple, modern, and ready to iterate</h2>
</div>
<span className="rounded-full bg-lime-300/20 px-3 py-1 text-xs font-semibold uppercase tracking-[0.2em] text-lime-100">MVP</span>
</div>
<div className="mt-5 grid gap-3 text-sm text-emerald-50/90">
<div className="flex items-start gap-3 rounded-2xl bg-black/10 px-4 py-3">
<BaseIcon path={mdiStorefrontOutline} size={18} className="mt-0.5" /> Public landing page with direct access to login, admin, and storefront.
</div>
<div className="flex items-start gap-3 rounded-2xl bg-black/10 px-4 py-3">
<BaseIcon path={mdiBasketOutline} size={18} className="mt-0.5" /> Authenticated storefront for browsing, basket building, and checkout.
</div>
<div className="flex items-start gap-3 rounded-2xl bg-black/10 px-4 py-3">
<BaseIcon path={mdiShieldCheckOutline} size={18} className="mt-0.5" /> Orders connect back to the admin interface you already have.
</div>
</div>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<div className="rounded-[1.5rem] bg-white px-5 py-4 text-slate-900 shadow-sm">
<p className="text-xs font-semibold uppercase tracking-[0.2em] text-emerald-700">Brand feel</p>
<p className="mt-2 text-sm text-slate-600">Fresh greens, soft neutrals, rounded cards, and airy spacing for a clean produce-first experience.</p>
</div>
<div className="rounded-[1.5rem] bg-white px-5 py-4 text-slate-900 shadow-sm">
<p className="text-xs font-semibold uppercase tracking-[0.2em] text-emerald-700">Admin ready</p>
<p className="mt-2 text-sm text-slate-600">Use the generated CRUD screens to add products, prices, slots, and manage incoming orders.</p>
</div>
</div>
</div>
</div>
</CardBox>
</section>
</div>
<section className="mx-auto max-w-7xl px-6 py-6">
<div className="grid gap-4 md:grid-cols-3">
{featureCards.map((feature) => (
<CardBox key={feature.title} className="border border-emerald-100 bg-white/90 shadow-sm shadow-emerald-100/60">
<div className="space-y-3">
<span className="inline-flex h-12 w-12 items-center justify-center rounded-2xl bg-emerald-50 text-emerald-700">
<BaseIcon path={feature.icon} size={22} />
</span>
<div>
<h3 className="text-xl font-semibold text-slate-900">{feature.title}</h3>
<p className="mt-2 text-sm leading-6 text-slate-600">{feature.description}</p>
</div>
</div>
</CardBox>
))}
</div>
</section>
<section className="mx-auto max-w-7xl px-6 py-10">
<div className="rounded-[2rem] border border-emerald-100 bg-white px-6 py-8 shadow-lg shadow-emerald-100/60">
<div className="max-w-2xl">
<p className="text-xs font-semibold uppercase tracking-[0.2em] text-emerald-700">First customer journey</p>
<h2 className="mt-2 text-3xl font-semibold text-slate-950">A thin slice that already feels like a real vegetable shop</h2>
<p className="mt-3 text-sm leading-6 text-slate-600">
Instead of shipping only a landing page, the first delivery connects browsing, checkout, confirmation, and order review into one usable loop.
</p>
</div>
<div className="mt-8 grid gap-4 lg:grid-cols-3">
{workflowSteps.map((step, index) => (
<div key={step.title} className="rounded-[1.5rem] bg-[#F7FAF4] px-5 py-5">
<div className="inline-flex items-center gap-2 rounded-full bg-white px-3 py-1 text-xs font-semibold uppercase tracking-[0.18em] text-emerald-700 shadow-sm">
<BaseIcon path={step.icon} size={16} /> Step {index + 1}
</div>
<h3 className="mt-4 text-xl font-semibold text-slate-900">{step.title}</h3>
<p className="mt-2 text-sm leading-6 text-slate-600">{step.description}</p>
</div>
))}
</div>
</div>
</section>
</main>
<footer className="border-t border-emerald-100 bg-white/70">
<div className="mx-auto flex max-w-7xl flex-col gap-4 px-6 py-6 text-sm text-slate-600 md:flex-row md:items-center md:justify-between">
<p>© 2026 Veggie Shop. Fresh vegetables with a clean modern buying flow.</p>
<div className="flex items-center gap-4">
<Link href="/privacy-policy" className="hover:text-emerald-700">Privacy Policy</Link>
<Link href="/terms-of-use" className="hover:text-emerald-700">Terms of Use</Link>
<Link href="/login" className="font-semibold text-emerald-700 hover:text-emerald-800">Login</Link>
</div>
</div>
</footer>
</div>
</>
);
}
Starter.getLayout = function getLayout(page: ReactElement) {
HomePage.getLayout = function getLayout(page: ReactElement) {
return <LayoutGuest>{page}</LayoutGuest>;
};

866
frontend/src/pages/shop.tsx Normal file
View File

@ -0,0 +1,866 @@
import {
mdiArrowRight,
mdiBasketOutline,
mdiCarrot,
mdiCashFast,
mdiCheckCircleOutline,
mdiClockOutline,
mdiLeaf,
mdiMapMarkerOutline,
mdiMinus,
mdiPlus,
mdiSprout,
mdiStorefrontOutline,
mdiTruckFastOutline,
} from '@mdi/js';
import Head from 'next/head';
import Link from 'next/link';
import React, { ReactElement, useEffect, useMemo, useState } from 'react';
import axios from 'axios';
import BaseButton from '../components/BaseButton';
import BaseIcon from '../components/BaseIcon';
import CardBox from '../components/CardBox';
import LoadingSpinner from '../components/LoadingSpinner';
import SectionMain from '../components/SectionMain';
import LayoutAuthenticated from '../layouts/Authenticated';
import { getPageTitle } from '../config';
import { hasPermission } from '../helpers/userPermissions';
import { useAppSelector } from '../stores/hooks';
type Category = {
id: string;
name: string;
};
type Product = {
id: string;
name: string;
short_description?: string | null;
description?: string | null;
unit?: string | null;
unit_size?: number | string | null;
price?: number | string | null;
compare_at_price?: number | string | null;
tax_rate?: number | string | null;
is_taxable?: boolean;
stock_quantity?: number | null;
is_active?: boolean;
is_featured?: boolean;
category?: Category | null;
};
type DeliverySlot = {
id: string;
name: string;
slot_type: 'delivery' | 'pickup';
starts_at?: string | null;
ends_at?: string | null;
capacity?: number | null;
reserved_count?: number | null;
notes?: string | null;
is_active?: boolean;
};
type Address = {
id: string;
label?: string | null;
recipient_name?: string | null;
phone?: string | null;
line1?: string | null;
line2?: string | null;
city?: string | null;
state?: string | null;
postal_code?: string | null;
country?: string | null;
};
type Order = {
id: string;
order_number?: string | null;
status?: string | null;
fulfillment_method?: 'delivery' | 'pickup' | null;
total_amount?: number | string | null;
placed_at?: string | null;
delivery_slot?: DeliverySlot | null;
delivery_address?: Address | null;
};
type CheckoutOrder = Order & {
order_items_order?: Array<{
id: string;
product_name?: string | null;
quantity?: number | null;
line_total?: number | string | null;
}>;
};
type NewAddressForm = {
label: string;
recipient_name: string;
phone: string;
line1: string;
line2: string;
city: string;
state: string;
postal_code: string;
country: string;
};
const currencyFormatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
});
const formatCurrency = (value: number | string | null | undefined) => {
const parsed = Number(value || 0);
return currencyFormatter.format(Number.isNaN(parsed) ? 0 : parsed);
};
const formatSlotWindow = (slot: DeliverySlot) => {
if (!slot.starts_at) {
return 'Time to be confirmed';
}
const start = new Date(slot.starts_at);
const end = slot.ends_at ? new Date(slot.ends_at) : null;
const base = start.toLocaleDateString('en-US', {
weekday: 'short',
month: 'short',
day: 'numeric',
});
const time = start.toLocaleTimeString('en-US', {
hour: 'numeric',
minute: '2-digit',
});
if (!end) {
return `${base} · ${time}`;
}
return `${base} · ${time}${end.toLocaleTimeString('en-US', {
hour: 'numeric',
minute: '2-digit',
})}`;
};
const formatAddress = (address: Address) => {
return [
address.line1,
address.line2,
[address.city, address.state].filter(Boolean).join(', '),
address.postal_code,
address.country,
]
.filter(Boolean)
.join(' · ');
};
const initialAddressForm = {
label: 'Fresh delivery',
recipient_name: '',
phone: '',
line1: '',
line2: '',
city: '',
state: '',
postal_code: '',
country: 'USA',
};
const StorefrontPage = () => {
const { currentUser } = useAppSelector((state) => state.auth);
const corners = useAppSelector((state) => state.style.corners);
const focusRingColor = useAppSelector((state) => state.style.focusRingColor);
const textSecondary = useAppSelector((state) => state.style.textSecondary);
const [products, setProducts] = useState<Product[]>([]);
const [deliverySlots, setDeliverySlots] = useState<DeliverySlot[]>([]);
const [addresses, setAddresses] = useState<Address[]>([]);
const [recentOrders, setRecentOrders] = useState<Order[]>([]);
const [cart, setCart] = useState<Record<string, number>>({});
const [search, setSearch] = useState('');
const [selectedCategory, setSelectedCategory] = useState('all');
const [fulfillmentMethod, setFulfillmentMethod] = useState<'delivery' | 'pickup'>('delivery');
const [selectedSlotId, setSelectedSlotId] = useState('');
const [selectedAddressId, setSelectedAddressId] = useState('new');
const [customerNote, setCustomerNote] = useState('');
const [newAddress, setNewAddress] = useState<NewAddressForm>(initialAddressForm);
const [loading, setLoading] = useState(true);
const [isSubmitting, setIsSubmitting] = useState(false);
const [loadError, setLoadError] = useState('');
const [submitError, setSubmitError] = useState('');
const [successOrder, setSuccessOrder] = useState<CheckoutOrder | null>(null);
const hasReadProducts = hasPermission(currentUser, 'READ_PRODUCTS');
const hasReadOrders = hasPermission(currentUser, 'READ_ORDERS');
const hasReadAddresses = hasPermission(currentUser, 'READ_ADDRESSES');
const hasReadSlots = hasPermission(currentUser, 'READ_DELIVERY_SLOTS');
const canCheckout = hasPermission(currentUser, 'CREATE_ORDERS');
useEffect(() => {
if (!currentUser) {
return;
}
setNewAddress((previous) => ({
...previous,
recipient_name: previous.recipient_name || [currentUser.firstName, currentUser.lastName].filter(Boolean).join(' '),
phone: previous.phone || currentUser.phoneNumber || '',
}));
}, [currentUser]);
const loadStorefront = React.useCallback(async () => {
if (!currentUser?.id || !hasReadProducts) {
setLoading(false);
return;
}
setLoading(true);
setLoadError('');
try {
const requests = [
axios.get('/products', { params: { limit: 24, page: 0 } }),
hasReadSlots ? axios.get('/delivery_slots', { params: { limit: 100, page: 0 } }) : Promise.resolve({ data: { rows: [] } }),
hasReadAddresses ? axios.get('/addresses', { params: { limit: 100, page: 0, user: currentUser.id } }) : Promise.resolve({ data: { rows: [] } }),
hasReadOrders ? axios.get('/orders', { params: { limit: 4, page: 0, user: currentUser.id } }) : Promise.resolve({ data: { rows: [] } }),
];
const [productsResponse, slotsResponse, addressesResponse, ordersResponse] = await Promise.all(requests);
setProducts(Array.isArray(productsResponse.data?.rows) ? productsResponse.data.rows : []);
setDeliverySlots(
(Array.isArray(slotsResponse.data?.rows) ? slotsResponse.data.rows : []).filter((slot: DeliverySlot) => slot.is_active !== false),
);
const fetchedAddresses = Array.isArray(addressesResponse.data?.rows) ? addressesResponse.data.rows : [];
setAddresses(fetchedAddresses);
setSelectedAddressId((previous) => (previous === 'new' ? 'new' : previous || (fetchedAddresses[0]?.id || 'new')));
setRecentOrders(Array.isArray(ordersResponse.data?.rows) ? ordersResponse.data.rows : []);
} catch (error) {
if (axios.isAxiosError(error)) {
setLoadError(error.response?.data || error.message || 'We could not load the storefront.');
} else {
setLoadError('We could not load the storefront.');
}
} finally {
setLoading(false);
}
}, [currentUser?.id, hasReadAddresses, hasReadOrders, hasReadProducts, hasReadSlots]);
useEffect(() => {
loadStorefront();
}, [loadStorefront]);
const categories = useMemo(() => {
const seen = new Map<string, Category>();
products.forEach((product) => {
if (product.category?.id && product.category?.name) {
seen.set(product.category.id, product.category);
}
});
return Array.from(seen.values()).sort((left, right) => left.name.localeCompare(right.name));
}, [products]);
const filteredProducts = useMemo(() => {
const needle = search.trim().toLowerCase();
return products
.filter((product) => product.is_active !== false)
.filter((product) => {
if (selectedCategory === 'all') {
return true;
}
return product.category?.id === selectedCategory;
})
.filter((product) => {
if (!needle) {
return true;
}
return [product.name, product.short_description, product.description, product.category?.name]
.filter(Boolean)
.some((value) => String(value).toLowerCase().includes(needle));
})
.sort((left, right) => Number(Boolean(right.is_featured)) - Number(Boolean(left.is_featured)));
}, [products, search, selectedCategory]);
const selectedSlots = useMemo(() => {
return deliverySlots.filter((slot) => slot.slot_type === fulfillmentMethod);
}, [deliverySlots, fulfillmentMethod]);
useEffect(() => {
if (!selectedSlots.length) {
setSelectedSlotId('');
return;
}
if (!selectedSlots.some((slot) => slot.id === selectedSlotId)) {
setSelectedSlotId(selectedSlots[0].id);
}
}, [selectedSlotId, selectedSlots]);
const cartItems = useMemo(() => {
return Object.entries(cart)
.map(([productId, quantity]) => {
const product = products.find((item) => item.id === productId);
if (!product || quantity <= 0) {
return null;
}
return {
...product,
quantity,
};
})
.filter(Boolean) as Array<Product & { quantity: number }>;
}, [cart, products]);
const pricing = useMemo(() => {
const subtotal = cartItems.reduce((sum, item) => sum + Number(item.price || 0) * item.quantity, 0);
const tax = cartItems.reduce((sum, item) => {
if (!item.is_taxable) {
return sum;
}
return sum + Number(item.price || 0) * item.quantity * Number(item.tax_rate || 0);
}, 0);
const deliveryFee = fulfillmentMethod === 'delivery' && cartItems.length ? 4.99 : 0;
const total = subtotal + tax + deliveryFee;
return {
subtotal,
tax,
deliveryFee,
total,
};
}, [cartItems, fulfillmentMethod]);
const addToCart = (productId: string, amount = 1) => {
setCart((previous) => {
const currentQuantity = previous[productId] || 0;
const product = products.find((item) => item.id === productId);
const maxQuantity = Number(product?.stock_quantity || 0);
const nextQuantity = Math.min(Math.max(currentQuantity + amount, 0), maxQuantity);
if (!nextQuantity) {
const nextCart = { ...previous };
delete nextCart[productId];
return nextCart;
}
return {
...previous,
[productId]: nextQuantity,
};
});
};
const handleCheckout = async () => {
setSubmitError('');
setSuccessOrder(null);
if (!cartItems.length) {
setSubmitError('Add vegetables to the basket before placing your order.');
return;
}
if (!selectedSlotId) {
setSubmitError(`Choose a ${fulfillmentMethod} slot to continue.`);
return;
}
if (fulfillmentMethod === 'delivery' && selectedAddressId === 'new') {
const requiredFields: Array<keyof NewAddressForm> = ['recipient_name', 'phone', 'line1', 'city', 'state', 'postal_code', 'country'];
const missingField = requiredFields.find((field) => !newAddress[field]?.trim());
if (missingField) {
setSubmitError('Complete the delivery address before placing your order.');
return;
}
}
setIsSubmitting(true);
try {
const payload = {
fulfillment_method: fulfillmentMethod,
delivery_slotId: selectedSlotId,
payment_provider: fulfillmentMethod === 'delivery' ? 'cash_on_delivery' : 'cash_on_pickup',
customer_note: customerNote,
items: cartItems.map((item) => ({
productId: item.id,
quantity: item.quantity,
})),
...(fulfillmentMethod === 'delivery'
? selectedAddressId !== 'new'
? { delivery_addressId: selectedAddressId }
: { delivery_address: newAddress }
: {}),
};
const response = await axios.post('/orders/checkout', { data: payload });
const order = response.data as CheckoutOrder;
setSuccessOrder(order);
setCart({});
setCustomerNote('');
setSelectedAddressId(order.delivery_address?.id || (addresses[0]?.id ? addresses[0].id : 'new'));
await loadStorefront();
} catch (error) {
if (axios.isAxiosError(error)) {
setSubmitError(error.response?.data || error.message || 'Your order could not be placed.');
} else {
setSubmitError('Your order could not be placed.');
}
} finally {
setIsSubmitting(false);
}
};
const inputClassName = `w-full border border-gray-200 bg-white/80 px-3 py-2 text-sm text-gray-900 shadow-sm ${corners} ${focusRingColor}`;
if (!hasReadProducts) {
return (
<>
<Head>
<title>{getPageTitle('Storefront')}</title>
</Head>
<SectionMain>
<CardBox className="border-emerald-100 bg-white/90">
<div className="space-y-3">
<div className="inline-flex h-12 w-12 items-center justify-center rounded-2xl bg-emerald-100 text-emerald-700">
<BaseIcon path={mdiStorefrontOutline} size={26} />
</div>
<h1 className="text-2xl font-semibold text-gray-900">Storefront access is not enabled for this role</h1>
<p className="text-sm text-gray-600">
Ask an administrator to grant product and order permissions so you can browse vegetables and place orders.
</p>
<BaseButton href="/dashboard" color="info" label="Back to dashboard" />
</div>
</CardBox>
</SectionMain>
</>
);
}
return (
<>
<Head>
<title>{getPageTitle('Storefront')}</title>
</Head>
<SectionMain>
<section className="mb-8 overflow-hidden rounded-[2rem] bg-gradient-to-br from-emerald-600 via-green-600 to-lime-500 text-white shadow-xl shadow-emerald-200/70">
<div className="grid gap-6 px-6 py-8 md:px-8 lg:grid-cols-[1.4fr_0.9fr] lg:items-center lg:px-10 lg:py-10">
<div className="space-y-5">
<div className="inline-flex items-center gap-2 rounded-full border border-white/20 bg-white/10 px-4 py-1 text-xs font-semibold uppercase tracking-[0.18em] text-emerald-50">
<BaseIcon path={mdiLeaf} size={16} /> Fresh, local, and easy to order
</div>
<div className="space-y-3">
<h1 className="max-w-2xl text-4xl font-bold tracking-tight md:text-5xl">Build a beautiful first-order flow for your vegetable shop.</h1>
<p className="max-w-2xl text-sm leading-6 text-emerald-50/90 md:text-base">
Browse your active products, curate a basket, choose delivery or pickup, and place an order in one polished flow.
</p>
</div>
<div className="flex flex-wrap gap-3 text-sm">
<div className="inline-flex items-center gap-2 rounded-2xl bg-white/10 px-4 py-2 backdrop-blur">
<BaseIcon path={mdiCarrot} size={18} /> {products.filter((product) => product.is_active !== false).length} active vegetables
</div>
<div className="inline-flex items-center gap-2 rounded-2xl bg-white/10 px-4 py-2 backdrop-blur">
<BaseIcon path={fulfillmentMethod === 'delivery' ? mdiTruckFastOutline : mdiStorefrontOutline} size={18} /> {fulfillmentMethod === 'delivery' ? 'Delivery ready' : 'Pickup ready'}
</div>
<div className="inline-flex items-center gap-2 rounded-2xl bg-white/10 px-4 py-2 backdrop-blur">
<BaseIcon path={mdiCashFast} size={18} /> Pay on {fulfillmentMethod}
</div>
</div>
</div>
<div className="grid gap-4 rounded-[1.75rem] border border-white/15 bg-white/10 p-5 backdrop-blur">
<div>
<p className="text-xs uppercase tracking-[0.24em] text-emerald-100">How the MVP works</p>
<h2 className="mt-2 text-2xl font-semibold">Catalog basket checkout order detail</h2>
</div>
<div className="grid gap-3 text-sm text-emerald-50/90">
<div className="flex items-start gap-3 rounded-2xl bg-black/10 px-4 py-3">
<BaseIcon path={mdiBasketOutline} size={18} className="mt-0.5" /> Add produce to a live basket with instant totals.
</div>
<div className="flex items-start gap-3 rounded-2xl bg-black/10 px-4 py-3">
<BaseIcon path={mdiClockOutline} size={18} className="mt-0.5" /> Reserve a delivery or pickup slot right in checkout.
</div>
<div className="flex items-start gap-3 rounded-2xl bg-black/10 px-4 py-3">
<BaseIcon path={mdiCheckCircleOutline} size={18} className="mt-0.5" /> Generate a real order, payment stub, and stock adjustment.
</div>
</div>
</div>
</div>
</section>
{loading ? (
<CardBox className="min-h-[20rem] justify-center">
<LoadingSpinner />
</CardBox>
) : (
<div className="grid gap-6 xl:grid-cols-[1.4fr_0.95fr]">
<div className="space-y-6">
<CardBox className="border-emerald-100 bg-white/90">
<div className="grid gap-4 lg:grid-cols-[1.3fr_1fr]">
<div>
<label className="mb-2 block text-xs font-semibold uppercase tracking-[0.2em] text-emerald-700">Search vegetables</label>
<input
className={inputClassName}
value={search}
onChange={(event) => setSearch(event.target.value)}
placeholder="Search carrots, basil, spinach…"
/>
</div>
<div>
<label className="mb-2 block text-xs font-semibold uppercase tracking-[0.2em] text-emerald-700">Category</label>
<div className="flex flex-wrap gap-2">
<button
type="button"
onClick={() => setSelectedCategory('all')}
className={`rounded-full px-4 py-2 text-sm font-medium transition ${selectedCategory === 'all' ? 'bg-emerald-600 text-white shadow-lg shadow-emerald-100' : 'bg-emerald-50 text-emerald-700 hover:bg-emerald-100'}`}
>
All produce
</button>
{categories.map((category) => (
<button
key={category.id}
type="button"
onClick={() => setSelectedCategory(category.id)}
className={`rounded-full px-4 py-2 text-sm font-medium transition ${selectedCategory === category.id ? 'bg-emerald-600 text-white shadow-lg shadow-emerald-100' : 'bg-emerald-50 text-emerald-700 hover:bg-emerald-100'}`}
>
{category.name}
</button>
))}
</div>
</div>
</div>
</CardBox>
{loadError ? (
<CardBox className="border border-rose-200 bg-rose-50">
<div className="space-y-2">
<h2 className="text-lg font-semibold text-rose-800">Storefront unavailable</h2>
<p className="text-sm text-rose-700">{loadError}</p>
</div>
</CardBox>
) : null}
<div className="grid gap-4 md:grid-cols-2">
{filteredProducts.map((product) => {
const inCart = cart[product.id] || 0;
const stock = Number(product.stock_quantity || 0);
const isSoldOut = stock <= 0;
return (
<CardBox key={product.id} className="border border-emerald-100 bg-white/90 shadow-sm shadow-emerald-100/60">
<div className="flex h-full flex-col gap-5">
<div className="flex items-start justify-between gap-4">
<div className="space-y-2">
<div className="inline-flex items-center gap-2 rounded-full bg-emerald-50 px-3 py-1 text-xs font-semibold text-emerald-700">
<BaseIcon path={mdiSprout} size={14} />
{product.category?.name || 'Seasonal pick'}
</div>
<div>
<h2 className="text-xl font-semibold text-gray-900">{product.name}</h2>
<p className={`mt-1 text-sm ${textSecondary || 'text-gray-500'}`}>
{product.short_description || product.description || 'Fresh produce, ready to order.'}
</p>
</div>
</div>
{product.is_featured ? (
<div className="rounded-full bg-lime-100 px-3 py-1 text-xs font-semibold uppercase tracking-wide text-lime-700">Featured</div>
) : null}
</div>
<div className="grid grid-cols-2 gap-3 text-sm">
<div className="rounded-2xl bg-gray-50 px-4 py-3">
<p className="text-xs uppercase tracking-wide text-gray-500">Price</p>
<p className="mt-1 text-lg font-semibold text-gray-900">{formatCurrency(product.price)}</p>
</div>
<div className="rounded-2xl bg-gray-50 px-4 py-3">
<p className="text-xs uppercase tracking-wide text-gray-500">Unit</p>
<p className="mt-1 text-lg font-semibold text-gray-900">
{product.unit_size ? `${product.unit_size} ` : ''}
{product.unit || 'each'}
</p>
</div>
</div>
<div className="mt-auto flex items-center justify-between gap-4 rounded-2xl border border-emerald-100 bg-emerald-50/70 px-4 py-3">
<div>
<p className="text-xs uppercase tracking-wide text-emerald-700">Stock</p>
<p className="font-semibold text-emerald-900">{isSoldOut ? 'Sold out' : `${stock} available`}</p>
</div>
<div className="flex items-center gap-2">
{inCart ? (
<div className="inline-flex items-center gap-2 rounded-full border border-emerald-200 bg-white px-2 py-1 shadow-sm">
<button type="button" aria-label={`Decrease ${product.name}`} onClick={() => addToCart(product.id, -1)} className="rounded-full p-1 text-emerald-700 transition hover:bg-emerald-50">
<BaseIcon path={mdiMinus} size={14} />
</button>
<span className="min-w-6 text-center text-sm font-semibold text-emerald-900">{inCart}</span>
<button type="button" aria-label={`Increase ${product.name}`} onClick={() => addToCart(product.id, 1)} className="rounded-full p-1 text-emerald-700 transition hover:bg-emerald-50" disabled={inCart >= stock}>
<BaseIcon path={mdiPlus} size={14} />
</button>
</div>
) : null}
<BaseButton
color="success"
label={isSoldOut ? 'Sold out' : inCart ? 'Add more' : 'Add to basket'}
icon={mdiBasketOutline}
disabled={isSoldOut}
onClick={() => addToCart(product.id, 1)}
/>
</div>
</div>
</div>
</CardBox>
);
})}
</div>
{!filteredProducts.length ? (
<CardBox className="border-dashed border-emerald-200 bg-white/80">
<div className="space-y-2 py-6 text-center">
<h2 className="text-lg font-semibold text-gray-900">No vegetables match this view yet</h2>
<p className="text-sm text-gray-500">Try a different search, or add fresh products in the admin catalog.</p>
<div className="flex justify-center">
<BaseButton href="/products/products-new" color="info" label="Add a product" />
</div>
</div>
</CardBox>
) : null}
<CardBox className="border-emerald-100 bg-white/90">
<div className="flex items-center justify-between gap-4">
<div>
<p className="text-xs font-semibold uppercase tracking-[0.2em] text-emerald-700">Recent orders</p>
<h2 className="mt-1 text-2xl font-semibold text-gray-900">Track the latest checkout outcomes</h2>
</div>
<BaseButton href="/orders/orders-list" color="info" label="Admin orders" icon={mdiArrowRight} />
</div>
<div className="mt-5 grid gap-4 md:grid-cols-2">
{recentOrders.map((order) => (
<div key={order.id} className="rounded-[1.5rem] border border-gray-100 bg-gray-50 p-4 shadow-sm">
<div className="flex items-start justify-between gap-4">
<div>
<p className="text-xs font-semibold uppercase tracking-[0.16em] text-emerald-700">{order.order_number || 'Draft order'}</p>
<h3 className="mt-1 text-lg font-semibold text-gray-900">{formatCurrency(order.total_amount)}</h3>
</div>
<div className="rounded-full bg-white px-3 py-1 text-xs font-semibold capitalize text-gray-700 shadow-sm">
{String(order.status || 'processing').replace(/_/g, ' ')}
</div>
</div>
<div className="mt-4 space-y-2 text-sm text-gray-600">
<div className="flex items-center gap-2">
<BaseIcon path={order.fulfillment_method === 'delivery' ? mdiTruckFastOutline : mdiStorefrontOutline} size={16} className="text-emerald-600" />
<span className="capitalize">{order.fulfillment_method || 'pickup'}</span>
</div>
{order.delivery_slot ? (
<div className="flex items-start gap-2">
<BaseIcon path={mdiClockOutline} size={16} className="mt-0.5 text-emerald-600" />
<span>{formatSlotWindow(order.delivery_slot)}</span>
</div>
) : null}
</div>
<div className="mt-4">
<Link href={`/shop/orders/${order.id}`} className="inline-flex items-center gap-2 text-sm font-semibold text-emerald-700 hover:text-emerald-800">
View order details <BaseIcon path={mdiArrowRight} size={16} />
</Link>
</div>
</div>
))}
</div>
{!recentOrders.length ? (
<div className="mt-5 rounded-[1.5rem] border border-dashed border-emerald-200 bg-emerald-50/50 px-5 py-6 text-sm text-emerald-800">
No orders yet. Place the first test order from the basket and it will appear here instantly.
</div>
) : null}
</CardBox>
</div>
<div className="space-y-6">
<CardBox className="sticky top-20 border-emerald-100 bg-white/95 shadow-lg shadow-emerald-100/60">
<div className="space-y-6">
<div className="flex items-start justify-between gap-4">
<div>
<p className="text-xs font-semibold uppercase tracking-[0.2em] text-emerald-700">Basket & checkout</p>
<h2 className="mt-1 text-2xl font-semibold text-gray-900">Finish the first order journey</h2>
</div>
<div className="rounded-full bg-emerald-100 px-3 py-1 text-sm font-semibold text-emerald-800">
{cartItems.reduce((sum, item) => sum + item.quantity, 0)} items
</div>
</div>
<div className="grid grid-cols-2 gap-3">
{(['delivery', 'pickup'] as const).map((option) => (
<button
key={option}
type="button"
onClick={() => setFulfillmentMethod(option)}
className={`rounded-[1.35rem] border px-4 py-3 text-left transition ${fulfillmentMethod === option ? 'border-emerald-500 bg-emerald-50 text-emerald-900 shadow-md shadow-emerald-100' : 'border-gray-200 bg-white text-gray-700 hover:border-emerald-200 hover:bg-emerald-50/50'}`}
>
<div className="flex items-center gap-2 text-sm font-semibold capitalize">
<BaseIcon path={option === 'delivery' ? mdiTruckFastOutline : mdiStorefrontOutline} size={18} /> {option}
</div>
<p className="mt-2 text-xs text-gray-500">{option === 'delivery' ? 'Drop-off with cash on delivery' : 'Scheduled farm pickup with cash on pickup'}</p>
</button>
))}
</div>
<div>
<label className="mb-2 block text-xs font-semibold uppercase tracking-[0.2em] text-emerald-700">{fulfillmentMethod} slot</label>
<select className={inputClassName} value={selectedSlotId} onChange={(event) => setSelectedSlotId(event.target.value)}>
<option value="">Choose a slot</option>
{selectedSlots.map((slot) => (
<option key={slot.id} value={slot.id}>{slot.name} · {formatSlotWindow(slot)}</option>
))}
</select>
{!selectedSlots.length ? (
<p className="mt-2 text-sm text-amber-700">Add a {fulfillmentMethod} slot in admin before accepting this order type.</p>
) : null}
</div>
{fulfillmentMethod === 'delivery' ? (
<div className="space-y-3 rounded-[1.5rem] border border-emerald-100 bg-emerald-50/50 p-4">
<div className="flex items-center gap-2 text-sm font-semibold text-emerald-900">
<BaseIcon path={mdiMapMarkerOutline} size={18} /> Delivery address
</div>
{addresses.map((address) => (
<label key={address.id} className={`flex cursor-pointer gap-3 rounded-2xl border px-4 py-3 text-sm transition ${selectedAddressId === address.id ? 'border-emerald-500 bg-white shadow-sm' : 'border-emerald-100 bg-white/70 hover:border-emerald-200'}`}>
<input type="radio" checked={selectedAddressId === address.id} onChange={() => setSelectedAddressId(address.id)} />
<div>
<p className="font-semibold text-gray-900">{address.label || address.recipient_name || 'Saved address'}</p>
<p className="mt-1 text-gray-600">{formatAddress(address)}</p>
</div>
</label>
))}
<label className={`flex cursor-pointer gap-3 rounded-2xl border px-4 py-3 text-sm transition ${selectedAddressId === 'new' ? 'border-emerald-500 bg-white shadow-sm' : 'border-emerald-100 bg-white/70 hover:border-emerald-200'}`}>
<input type="radio" checked={selectedAddressId === 'new'} onChange={() => setSelectedAddressId('new')} />
<div>
<p className="font-semibold text-gray-900">New address</p>
<p className="mt-1 text-gray-600">Create a fresh delivery destination while checking out.</p>
</div>
</label>
{selectedAddressId === 'new' ? (
<div className="grid gap-3 md:grid-cols-2">
<input className={inputClassName} placeholder="Label" value={newAddress.label} onChange={(event) => setNewAddress((previous) => ({ ...previous, label: event.target.value }))} />
<input className={inputClassName} placeholder="Recipient name" value={newAddress.recipient_name} onChange={(event) => setNewAddress((previous) => ({ ...previous, recipient_name: event.target.value }))} />
<input className={inputClassName} placeholder="Phone" value={newAddress.phone} onChange={(event) => setNewAddress((previous) => ({ ...previous, phone: event.target.value }))} />
<input className={inputClassName} placeholder="Line 1" value={newAddress.line1} onChange={(event) => setNewAddress((previous) => ({ ...previous, line1: event.target.value }))} />
<input className={inputClassName} placeholder="Line 2" value={newAddress.line2} onChange={(event) => setNewAddress((previous) => ({ ...previous, line2: event.target.value }))} />
<input className={inputClassName} placeholder="City" value={newAddress.city} onChange={(event) => setNewAddress((previous) => ({ ...previous, city: event.target.value }))} />
<input className={inputClassName} placeholder="State" value={newAddress.state} onChange={(event) => setNewAddress((previous) => ({ ...previous, state: event.target.value }))} />
<input className={inputClassName} placeholder="Postal code" value={newAddress.postal_code} onChange={(event) => setNewAddress((previous) => ({ ...previous, postal_code: event.target.value }))} />
<input className={`md:col-span-2 ${inputClassName}`} placeholder="Country" value={newAddress.country} onChange={(event) => setNewAddress((previous) => ({ ...previous, country: event.target.value }))} />
</div>
) : null}
</div>
) : (
<div className="rounded-[1.5rem] border border-amber-200 bg-amber-50 px-4 py-4 text-sm text-amber-900">
Pickup orders skip the address step and create a cash-on-pickup payment stub automatically.
</div>
)}
<div>
<label className="mb-2 block text-xs font-semibold uppercase tracking-[0.2em] text-emerald-700">Order note</label>
<textarea className={`${inputClassName} min-h-28`} value={customerNote} onChange={(event) => setCustomerNote(event.target.value)} placeholder="Gate code, ripeness preferences, or pickup instructions" />
</div>
<div className="space-y-3 rounded-[1.5rem] border border-gray-100 bg-gray-50 p-4">
{cartItems.map((item) => (
<div key={item.id} className="flex items-center justify-between gap-3 rounded-2xl bg-white px-4 py-3 shadow-sm">
<div>
<p className="font-semibold text-gray-900">{item.name}</p>
<p className="text-xs text-gray-500">{formatCurrency(item.price)} each</p>
</div>
<div className="flex items-center gap-2">
<div className="inline-flex items-center gap-2 rounded-full border border-emerald-200 px-2 py-1">
<button type="button" onClick={() => addToCart(item.id, -1)} className="rounded-full p-1 text-emerald-700 hover:bg-emerald-50">
<BaseIcon path={mdiMinus} size={14} />
</button>
<span className="min-w-6 text-center text-sm font-semibold text-emerald-900">{item.quantity}</span>
<button type="button" onClick={() => addToCart(item.id, 1)} className="rounded-full p-1 text-emerald-700 hover:bg-emerald-50" disabled={item.quantity >= Number(item.stock_quantity || 0)}>
<BaseIcon path={mdiPlus} size={14} />
</button>
</div>
<span className="min-w-20 text-right text-sm font-semibold text-gray-900">{formatCurrency(Number(item.price || 0) * item.quantity)}</span>
</div>
</div>
))}
{!cartItems.length ? (
<div className="rounded-2xl border border-dashed border-gray-200 bg-white px-4 py-6 text-center text-sm text-gray-500">
Your basket is empty. Add a few vegetables from the catalog to unlock checkout.
</div>
) : null}
</div>
<div className="space-y-2 rounded-[1.5rem] bg-gray-950 px-5 py-4 text-white shadow-xl shadow-gray-200">
<div className="flex items-center justify-between text-sm text-white/80">
<span>Subtotal</span>
<span>{formatCurrency(pricing.subtotal)}</span>
</div>
<div className="flex items-center justify-between text-sm text-white/80">
<span>Tax</span>
<span>{formatCurrency(pricing.tax)}</span>
</div>
<div className="flex items-center justify-between text-sm text-white/80">
<span>{fulfillmentMethod === 'delivery' ? 'Delivery fee' : 'Pickup fee'}</span>
<span>{formatCurrency(pricing.deliveryFee)}</span>
</div>
<div className="mt-3 flex items-center justify-between border-t border-white/10 pt-3 text-lg font-semibold">
<span>Total</span>
<span>{formatCurrency(pricing.total)}</span>
</div>
</div>
{submitError ? (
<div className="rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">
{submitError}
</div>
) : null}
{successOrder ? (
<div className="rounded-[1.5rem] border border-emerald-200 bg-emerald-50 px-4 py-4 text-sm text-emerald-900">
<div className="flex items-start gap-3">
<div className="rounded-full bg-white p-2 text-emerald-600 shadow-sm">
<BaseIcon path={mdiCheckCircleOutline} size={18} />
</div>
<div className="space-y-2">
<p className="font-semibold">Order {successOrder.order_number} placed successfully.</p>
<p>Your basket has been converted into a real order with payment tracking and stock adjustments.</p>
<div className="flex flex-wrap gap-3 pt-1">
<BaseButton href={`/shop/orders/${successOrder.id}`} color="success" label="View order detail" />
<BaseButton href="/orders/orders-list" color="whiteDark" outline label="Open admin orders" />
</div>
</div>
</div>
</div>
) : null}
<BaseButton
color="success"
label={isSubmitting ? 'Placing order…' : canCheckout ? 'Place order' : 'Checkout unavailable'}
icon={mdiCheckCircleOutline}
className="w-full justify-center py-3 text-base font-semibold"
disabled={isSubmitting || !canCheckout}
onClick={handleCheckout}
/>
</div>
</CardBox>
</div>
</div>
)}
</SectionMain>
</>
);
};
StorefrontPage.getLayout = function getLayout(page: ReactElement) {
return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
};
export default StorefrontPage;

View File

@ -0,0 +1,360 @@
import {
mdiArrowLeft,
mdiCheckCircleOutline,
mdiClockOutline,
mdiCreditCardOutline,
mdiMapMarkerOutline,
mdiReceiptText,
mdiStorefrontOutline,
mdiTruckFastOutline,
} from '@mdi/js';
import Head from 'next/head';
import Link from 'next/link';
import { useRouter } from 'next/router';
import React, { ReactElement, useEffect, useMemo, useState } from 'react';
import axios from 'axios';
import BaseButton from '../../../components/BaseButton';
import BaseIcon from '../../../components/BaseIcon';
import CardBox from '../../../components/CardBox';
import LoadingSpinner from '../../../components/LoadingSpinner';
import SectionMain from '../../../components/SectionMain';
import LayoutAuthenticated from '../../../layouts/Authenticated';
import { getPageTitle } from '../../../config';
type DeliverySlot = {
name?: string | null;
starts_at?: string | null;
ends_at?: string | null;
slot_type?: 'delivery' | 'pickup' | null;
};
type Address = {
label?: string | null;
recipient_name?: string | null;
phone?: string | null;
line1?: string | null;
line2?: string | null;
city?: string | null;
state?: string | null;
postal_code?: string | null;
country?: string | null;
};
type OrderItem = {
id: string;
product_name?: string | null;
quantity?: number | null;
unit?: string | null;
unit_size?: number | string | null;
unit_price?: number | string | null;
line_total?: number | string | null;
};
type Payment = {
id: string;
provider?: string | null;
status?: string | null;
amount?: number | string | null;
currency?: string | null;
};
type OrderDetail = {
id: string;
order_number?: string | null;
status?: string | null;
fulfillment_method?: 'delivery' | 'pickup' | null;
subtotal_amount?: number | string | null;
tax_amount?: number | string | null;
delivery_fee?: number | string | null;
total_amount?: number | string | null;
payment_status?: string | null;
customer_note?: string | null;
placed_at?: string | null;
delivery_slot?: DeliverySlot | null;
delivery_address?: Address | null;
order_items_order?: OrderItem[];
payments_order?: Payment[];
};
const currencyFormatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
});
const formatCurrency = (value: number | string | null | undefined) => {
const parsed = Number(value || 0);
return currencyFormatter.format(Number.isNaN(parsed) ? 0 : parsed);
};
const formatDateTime = (value?: string | null) => {
if (!value) {
return 'Not scheduled yet';
}
return new Date(value).toLocaleString('en-US', {
weekday: 'short',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: '2-digit',
});
};
const formatAddress = (address?: Address | null) => {
if (!address) {
return 'No address attached';
}
return [
address.label,
address.recipient_name,
address.phone,
address.line1,
address.line2,
[address.city, address.state].filter(Boolean).join(', '),
address.postal_code,
address.country,
]
.filter(Boolean)
.join(' · ');
};
const ShopOrderDetailPage = () => {
const router = useRouter();
const { orderId } = router.query;
const [order, setOrder] = useState<OrderDetail | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
useEffect(() => {
if (!orderId || typeof orderId !== 'string') {
return;
}
const fetchOrder = async () => {
setLoading(true);
setError('');
try {
const response = await axios.get(`/orders/${orderId}`);
setOrder(response.data);
} catch (fetchError) {
if (axios.isAxiosError(fetchError)) {
setError(fetchError.response?.data || fetchError.message || 'Unable to load this order.');
} else {
setError('Unable to load this order.');
}
} finally {
setLoading(false);
}
};
fetchOrder();
}, [orderId]);
const payment = useMemo(() => order?.payments_order?.[0] || null, [order]);
return (
<>
<Head>
<title>{getPageTitle(order?.order_number || 'Order detail')}</title>
</Head>
<SectionMain>
<div className="mb-6 flex flex-wrap items-center justify-between gap-3">
<BaseButton href="/shop" color="whiteDark" outline icon={mdiArrowLeft} label="Back to storefront" />
<Link href="/orders/orders-list" className="text-sm font-semibold text-emerald-700 hover:text-emerald-800">
Open admin order list
</Link>
</div>
{loading ? (
<CardBox className="min-h-[18rem] justify-center">
<LoadingSpinner />
</CardBox>
) : error ? (
<CardBox className="border border-rose-200 bg-rose-50">
<div className="space-y-2">
<h1 className="text-2xl font-semibold text-rose-800">We couldn&apos;t load this order</h1>
<p className="text-sm text-rose-700">{error}</p>
</div>
</CardBox>
) : !order ? (
<CardBox className="border border-gray-200 bg-white/90">
<div className="space-y-2">
<h1 className="text-2xl font-semibold text-gray-900">Order not found</h1>
<p className="text-sm text-gray-600">Try returning to the storefront and placing a fresh order.</p>
</div>
</CardBox>
) : (
<div className="space-y-6">
<section className="overflow-hidden rounded-[2rem] bg-gradient-to-br from-gray-950 via-emerald-950 to-emerald-700 text-white shadow-xl shadow-emerald-100/70">
<div className="grid gap-6 px-6 py-8 md:px-8 lg:grid-cols-[1.2fr_0.8fr] lg:items-center lg:px-10 lg:py-10">
<div className="space-y-4">
<div className="inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/10 px-4 py-1 text-xs font-semibold uppercase tracking-[0.18em] text-emerald-50">
<BaseIcon path={mdiReceiptText} size={16} /> Order detail
</div>
<div>
<p className="text-sm text-emerald-100">{order.order_number}</p>
<h1 className="mt-2 text-4xl font-bold tracking-tight md:text-5xl">{formatCurrency(order.total_amount)}</h1>
<p className="mt-3 max-w-2xl text-sm leading-6 text-emerald-50/90">
This order was placed on {formatDateTime(order.placed_at)} and is currently {String(order.status || 'processing').replace(/_/g, ' ')}.
</p>
</div>
</div>
<div className="grid gap-3 rounded-[1.75rem] border border-white/10 bg-white/10 p-5 backdrop-blur">
<div className="flex items-center gap-3 rounded-2xl bg-black/10 px-4 py-3">
<BaseIcon path={order.fulfillment_method === 'delivery' ? mdiTruckFastOutline : mdiStorefrontOutline} size={18} />
<div>
<p className="text-xs uppercase tracking-[0.14em] text-emerald-100">Fulfillment</p>
<p className="font-semibold capitalize">{order.fulfillment_method || 'pickup'}</p>
</div>
</div>
<div className="flex items-center gap-3 rounded-2xl bg-black/10 px-4 py-3">
<BaseIcon path={mdiClockOutline} size={18} />
<div>
<p className="text-xs uppercase tracking-[0.14em] text-emerald-100">Slot</p>
<p className="font-semibold">{order.delivery_slot?.name || 'Time pending'}</p>
<p className="text-sm text-emerald-100">{formatDateTime(order.delivery_slot?.starts_at)}</p>
</div>
</div>
<div className="flex items-center gap-3 rounded-2xl bg-black/10 px-4 py-3">
<BaseIcon path={mdiCheckCircleOutline} size={18} />
<div>
<p className="text-xs uppercase tracking-[0.14em] text-emerald-100">Payment status</p>
<p className="font-semibold capitalize">{String(order.payment_status || 'unpaid').replace(/_/g, ' ')}</p>
</div>
</div>
</div>
</div>
</section>
<div className="grid gap-6 xl:grid-cols-[1.2fr_0.8fr]">
<CardBox className="border-emerald-100 bg-white/90">
<div className="space-y-4">
<div>
<p className="text-xs font-semibold uppercase tracking-[0.2em] text-emerald-700">Line items</p>
<h2 className="mt-1 text-2xl font-semibold text-gray-900">What&apos;s in the order</h2>
</div>
<div className="space-y-3">
{order.order_items_order?.map((item) => (
<div key={item.id} className="flex flex-wrap items-center justify-between gap-4 rounded-[1.5rem] border border-gray-100 bg-gray-50 px-5 py-4 shadow-sm">
<div>
<p className="font-semibold text-gray-900">{item.product_name}</p>
<p className="text-sm text-gray-500">
{item.quantity} × {formatCurrency(item.unit_price)}
{item.unit ? ` · ${item.unit_size || ''} ${item.unit}` : ''}
</p>
</div>
<p className="text-lg font-semibold text-gray-900">{formatCurrency(item.line_total)}</p>
</div>
))}
</div>
{!order.order_items_order?.length ? (
<div className="rounded-[1.5rem] border border-dashed border-gray-200 bg-gray-50 px-5 py-6 text-sm text-gray-500">
This order does not have any line items yet.
</div>
) : null}
</div>
</CardBox>
<div className="space-y-6">
<CardBox className="border-emerald-100 bg-white/90">
<div className="space-y-3">
<div>
<p className="text-xs font-semibold uppercase tracking-[0.2em] text-emerald-700">Summary</p>
<h2 className="mt-1 text-2xl font-semibold text-gray-900">Charges & notes</h2>
</div>
<div className="space-y-2 rounded-[1.5rem] bg-gray-950 px-5 py-4 text-white">
<div className="flex items-center justify-between text-sm text-white/80">
<span>Subtotal</span>
<span>{formatCurrency(order.subtotal_amount)}</span>
</div>
<div className="flex items-center justify-between text-sm text-white/80">
<span>Tax</span>
<span>{formatCurrency(order.tax_amount)}</span>
</div>
<div className="flex items-center justify-between text-sm text-white/80">
<span>Delivery fee</span>
<span>{formatCurrency(order.delivery_fee)}</span>
</div>
<div className="flex items-center justify-between border-t border-white/10 pt-3 text-lg font-semibold">
<span>Total</span>
<span>{formatCurrency(order.total_amount)}</span>
</div>
</div>
{order.customer_note ? (
<div className="rounded-[1.5rem] border border-emerald-100 bg-emerald-50 px-4 py-4 text-sm text-emerald-900">
<p className="font-semibold">Customer note</p>
<p className="mt-2">{order.customer_note}</p>
</div>
) : null}
</div>
</CardBox>
<CardBox className="border-emerald-100 bg-white/90">
<div className="space-y-4">
<div>
<p className="text-xs font-semibold uppercase tracking-[0.2em] text-emerald-700">Fulfillment</p>
<h2 className="mt-1 text-2xl font-semibold text-gray-900">Delivery or pickup details</h2>
</div>
<div className="space-y-3 text-sm text-gray-600">
<div className="flex items-start gap-3 rounded-2xl bg-gray-50 px-4 py-4">
<BaseIcon path={mdiClockOutline} size={18} className="mt-0.5 text-emerald-600" />
<div>
<p className="font-semibold text-gray-900">{order.delivery_slot?.name || 'Slot pending'}</p>
<p>{formatDateTime(order.delivery_slot?.starts_at)}</p>
</div>
</div>
{order.fulfillment_method === 'delivery' ? (
<div className="flex items-start gap-3 rounded-2xl bg-gray-50 px-4 py-4">
<BaseIcon path={mdiMapMarkerOutline} size={18} className="mt-0.5 text-emerald-600" />
<div>
<p className="font-semibold text-gray-900">Delivery address</p>
<p>{formatAddress(order.delivery_address)}</p>
</div>
</div>
) : (
<div className="flex items-start gap-3 rounded-2xl bg-amber-50 px-4 py-4 text-amber-900">
<BaseIcon path={mdiStorefrontOutline} size={18} className="mt-0.5" />
<div>
<p className="font-semibold">Pickup order</p>
<p>Collect this order during the reserved pickup window and mark payment on arrival.</p>
</div>
</div>
)}
</div>
</div>
</CardBox>
<CardBox className="border-emerald-100 bg-white/90">
<div className="space-y-4">
<div>
<p className="text-xs font-semibold uppercase tracking-[0.2em] text-emerald-700">Payment</p>
<h2 className="mt-1 text-2xl font-semibold text-gray-900">Recorded checkout payment</h2>
</div>
<div className="rounded-[1.5rem] border border-gray-100 bg-gray-50 px-4 py-4 text-sm text-gray-600">
<div className="flex items-start gap-3">
<BaseIcon path={mdiCreditCardOutline} size={18} className="mt-0.5 text-emerald-600" />
<div>
<p className="font-semibold text-gray-900">{payment?.provider ? String(payment.provider).replace(/_/g, ' ') : 'Payment placeholder'}</p>
<p className="mt-1">Status: {payment?.status ? String(payment.status).replace(/_/g, ' ') : 'initiated'}</p>
<p className="mt-1">Amount: {formatCurrency(payment?.amount || order.total_amount)} {payment?.currency || 'USD'}</p>
</div>
</div>
</div>
</div>
</CardBox>
</div>
</div>
</div>
)}
</SectionMain>
</>
);
};
ShopOrderDetailPage.getLayout = function getLayout(page: ReactElement) {
return <LayoutAuthenticated permission="READ_ORDERS">{page}</LayoutAuthenticated>;
};
export default ShopOrderDetailPage;