feat(checkout): let the admin choose the details asked at checkout
The admin enables or disables each option (phone, address, Snapchat, Instagram, Telegram, SimpleX, WhatsApp, Signal, notes, preferred time) from a new "Checkout fields" page; the customer's name is always asked. Backend - checkoutfields module: single-row settings (CHECK id = 1), public GET and admin GET/PUT. - orders: answers stored as JSONB (contacts, info_sup); the customer phone moves from customer_phone to contacts.phone (migration 000034 copies existing values before dropping the column). - Orders are validated against the live settings: disabled options and unknown keys are dropped, enabled phone/address are required, and format, length and control characters are checked. - The Telegram notification includes the answers. Frontend - Checkout form generated from the enabled options; admin settings page; answers shown in the order list and detail. - API calls live in src/api (checkoutFields.ts, orders.ts); ApiError keeps the response body so the rejected field can be reported. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
178652ef14
commit
f9bfdc9d3c
@@ -13,6 +13,7 @@ import AppearanceSettingsPage from "./features/admin/AppearanceSettingsPage";
|
||||
import UsersPage from "./features/admin/UsersPage";
|
||||
import CategoriesPage from "./features/admin/CategoriesPage";
|
||||
import UnitsPage from "./features/admin/UnitsPage";
|
||||
import CheckoutFieldsPage from "./features/admin/CheckoutFieldsPage";
|
||||
import ProductsPage from "./features/admin/ProductsPage";
|
||||
import ProductEditPage from "./features/admin/ProductEditPage";
|
||||
import OrdersPage from "./features/admin/OrdersPage";
|
||||
@@ -74,6 +75,7 @@ export default function App() {
|
||||
<Route path="products/:id" element={<ProductEditPage />} />
|
||||
<Route path="orders" element={<OrdersPage />} />
|
||||
<Route path="orders/:id" element={<OrderDetailPage />} />
|
||||
<Route path="checkout-fields" element={<CheckoutFieldsPage />} />
|
||||
<Route path="notifications/telegram" element={<TelegramSettingsPage />} />
|
||||
<Route path="contact-links" element={<ContactLinksPage />} />
|
||||
<Route path="customer-accounts" element={<CustomerAccountsPage />} />
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { apiFetch } from "./client";
|
||||
|
||||
// Options the admin can ask the customer for at checkout (the customer's
|
||||
// name is always asked and is not an option). Mirrors the JSON keys of the
|
||||
// backend's checkoutfields module.
|
||||
export const CHECKOUT_OPTION_KEYS = [
|
||||
"phone",
|
||||
"address",
|
||||
"snap",
|
||||
"insta",
|
||||
"telegram",
|
||||
"simplex",
|
||||
"whatsapp",
|
||||
"signal",
|
||||
"notes",
|
||||
"hour",
|
||||
] as const;
|
||||
|
||||
export type CheckoutOptionKey = (typeof CHECKOUT_OPTION_KEYS)[number];
|
||||
export type CheckoutOptions = Record<CheckoutOptionKey, boolean>;
|
||||
|
||||
// Public: the storefront reads this to know which fields to show.
|
||||
export function getCheckoutOptions(): Promise<CheckoutOptions> {
|
||||
return apiFetch<CheckoutOptions>("/api/checkout-fields");
|
||||
}
|
||||
|
||||
export function getAdminCheckoutOptions(): Promise<CheckoutOptions> {
|
||||
return apiFetch<CheckoutOptions>("/api/admin/checkout-fields");
|
||||
}
|
||||
|
||||
// Replaces every option at once.
|
||||
export function updateCheckoutOptions(options: CheckoutOptions): Promise<CheckoutOptions> {
|
||||
return apiFetch<CheckoutOptions>("/api/admin/checkout-fields", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(options),
|
||||
});
|
||||
}
|
||||
@@ -1,8 +1,12 @@
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
constructor(message: string, status: number) {
|
||||
// Parsed JSON error body, when the server sent one (e.g. the offending
|
||||
// field and reason of a rejected checkout).
|
||||
body?: unknown;
|
||||
constructor(message: string, status: number, body?: unknown) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
this.body = body;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,13 +61,15 @@ function createAuthClient(refreshPath: string, noRetryPaths: string[]): AuthClie
|
||||
|
||||
if (!res.ok) {
|
||||
let message = `Request failed with status ${res.status}`;
|
||||
let body: unknown;
|
||||
try {
|
||||
const body = (await res.json()) as { error?: string };
|
||||
if (body?.error) message = body.error;
|
||||
const parsed = (await res.json()) as { error?: string };
|
||||
body = parsed;
|
||||
if (parsed?.error) message = parsed.error;
|
||||
} catch {
|
||||
// response had no JSON body
|
||||
}
|
||||
throw new ApiError(message, res.status);
|
||||
throw new ApiError(message, res.status, body);
|
||||
}
|
||||
|
||||
// Some endpoints reply 201/200 with no body at all (e.g. attaching a
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { apiFetch, customerApiFetch } from "./client";
|
||||
import type { Order } from "./types";
|
||||
|
||||
export interface CreateOrderInput {
|
||||
customer_name: string;
|
||||
contacts: Record<string, string>;
|
||||
info_sup: Record<string, string>;
|
||||
notes: string;
|
||||
items: { product_id: string; price_tier_id: string; multiplier: number }[];
|
||||
}
|
||||
|
||||
// customerApiFetch attaches the logged-in customer's bearer token so the
|
||||
// backend's customer/verification gates can authenticate the request.
|
||||
export function createOrder(input: CreateOrderInput): Promise<Order> {
|
||||
return customerApiFetch<Order>("/api/orders", { method: "POST", body: JSON.stringify(input) });
|
||||
}
|
||||
|
||||
export async function listAdminOrders(): Promise<Order[]> {
|
||||
const data = await apiFetch<{ orders: Order[] }>("/api/admin/orders");
|
||||
return data.orders;
|
||||
}
|
||||
|
||||
export function getAdminOrder(id: string): Promise<Order> {
|
||||
return apiFetch<Order>(`/api/admin/orders/${id}`);
|
||||
}
|
||||
@@ -127,8 +127,11 @@ export interface OrderItem {
|
||||
export interface Order {
|
||||
id: string;
|
||||
customer_name: string;
|
||||
customer_email: string;
|
||||
customer_phone: string;
|
||||
// Answers to the checkout options the admin enabled (see
|
||||
// api/checkoutFields.ts): phone and messengers in `contacts`, address and
|
||||
// preferred hour in `info_sup`.
|
||||
contacts?: Record<string, string>;
|
||||
info_sup?: Record<string, string>;
|
||||
total_cents: number;
|
||||
notes: string;
|
||||
items?: OrderItem[];
|
||||
|
||||
@@ -28,7 +28,10 @@ const NAV_SECTIONS: { titleKey: MessageKey; items: { to: string; labelKey: Messa
|
||||
},
|
||||
{
|
||||
titleKey: "layout.admin.nav.sales",
|
||||
items: [{ to: "/admin/orders", labelKey: "layout.admin.nav.orders" }],
|
||||
items: [
|
||||
{ to: "/admin/orders", labelKey: "layout.admin.nav.orders" },
|
||||
{ to: "/admin/checkout-fields", labelKey: "layout.admin.nav.checkoutFields" },
|
||||
],
|
||||
},
|
||||
{
|
||||
titleKey: "layout.admin.nav.communication",
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import {
|
||||
getAdminCheckoutOptions,
|
||||
updateCheckoutOptions,
|
||||
type CheckoutOptions,
|
||||
} from "../../api/checkoutFields";
|
||||
import { useI18n } from "../../i18n/LanguageContext";
|
||||
import { useToast } from "../../ui/ToastContext";
|
||||
import { CHECKOUT_FIELDS } from "../checkout/fields";
|
||||
|
||||
// Lets the admin choose which details the customer must give when ordering.
|
||||
// The customer's name is always asked, so it is not listed here.
|
||||
export default function CheckoutFieldsPage() {
|
||||
const { t } = useI18n();
|
||||
const toast = useToast();
|
||||
const [options, setOptions] = useState<CheckoutOptions | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
getAdminCheckoutOptions()
|
||||
.then(setOptions)
|
||||
.catch(() => setError(t("admin.checkoutFields.loadError")))
|
||||
.finally(() => setLoading(false));
|
||||
}, [t]);
|
||||
|
||||
async function handleSubmit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!options) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
setOptions(await updateCheckoutOptions(options));
|
||||
toast.success(t("admin.checkoutFields.saved"));
|
||||
} catch {
|
||||
toast.error(t("admin.checkoutFields.saveError"));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) return <div className="page-loading">{t("common.loading")}</div>;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1>{t("admin.checkoutFields.title")}</h1>
|
||||
{error && <div className="alert alert-error">{error}</div>}
|
||||
{options && (
|
||||
<div className="panel">
|
||||
<p style={{ color: "var(--color-text-muted)" }}>{t("admin.checkoutFields.hint")}</p>
|
||||
<form onSubmit={handleSubmit}>
|
||||
{CHECKOUT_FIELDS.map((field) => (
|
||||
<div className="field field-inline" key={field.key}>
|
||||
<input
|
||||
id={`option-${field.key}`}
|
||||
type="checkbox"
|
||||
checked={options[field.key]}
|
||||
onChange={(e) => setOptions({ ...options, [field.key]: e.target.checked })}
|
||||
/>
|
||||
<label htmlFor={`option-${field.key}`}>
|
||||
{t(field.labelKey)}
|
||||
{field.required && (
|
||||
<span style={{ color: "var(--color-text-muted)", fontSize: "0.85rem" }}>
|
||||
{" "}
|
||||
— {t("admin.checkoutFields.requiredWhenEnabled")}
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
</div>
|
||||
))}
|
||||
<div className="form-actions">
|
||||
<button type="submit" className="btn btn-primary" disabled={saving}>
|
||||
{saving ? t("common.saving") : t("common.save")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link, useParams } from "react-router-dom";
|
||||
import { apiFetch } from "../../api/client";
|
||||
import { getAdminOrder } from "../../api/orders";
|
||||
import { formatCents, type Order } from "../../api/types";
|
||||
import { useI18n } from "../../i18n/LanguageContext";
|
||||
import { CHECKOUT_FIELDS } from "../checkout/fields";
|
||||
|
||||
export default function OrderDetailPage() {
|
||||
const { t } = useI18n();
|
||||
@@ -13,7 +14,7 @@ export default function OrderDetailPage() {
|
||||
|
||||
function load() {
|
||||
setLoading(true);
|
||||
apiFetch<Order>(`/api/admin/orders/${id}`)
|
||||
getAdminOrder(id!)
|
||||
.then(setOrder)
|
||||
.catch(() => setLoadError(t("admin.orderDetail.loadError")))
|
||||
.finally(() => setLoading(false));
|
||||
@@ -24,6 +25,18 @@ export default function OrderDetailPage() {
|
||||
if (loading) return <div className="page-loading">{t("common.loading")}</div>;
|
||||
if (!order) return <div className="alert alert-error">{t("admin.orderDetail.notFound")}</div>;
|
||||
|
||||
// Answers to the options enabled when the order was placed, in the same
|
||||
// order as the checkout form. Keys the form no longer knows are shown raw
|
||||
// rather than dropped.
|
||||
const stored = { ...order.contacts, ...order.info_sup };
|
||||
const known = new Set<string>(CHECKOUT_FIELDS.map((f) => f.key));
|
||||
const answers = [
|
||||
...CHECKOUT_FIELDS.filter((f) => stored[f.key]).map((f) => ({ key: f.key, label: t(f.labelKey), value: stored[f.key] })),
|
||||
...Object.entries(stored)
|
||||
.filter(([k, v]) => v && !known.has(k))
|
||||
.map(([k, v]) => ({ key: k, label: k, value: v })),
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<p>
|
||||
@@ -34,10 +47,17 @@ export default function OrderDetailPage() {
|
||||
|
||||
<div className="panel">
|
||||
<h2>{t("admin.orderDetail.customerTitle")}</h2>
|
||||
<p>
|
||||
{order.customer_name} — {order.customer_email}
|
||||
{order.customer_phone && ` — ${order.customer_phone}`}
|
||||
</p>
|
||||
<p>{order.customer_name}</p>
|
||||
{answers.length > 0 && (
|
||||
<dl style={{ margin: 0 }}>
|
||||
{answers.map((a) => (
|
||||
<div key={a.key} style={{ display: "flex", gap: "0.5rem" }}>
|
||||
<dt style={{ color: "var(--color-text-muted)" }}>{a.label} :</dt>
|
||||
<dd style={{ margin: 0, whiteSpace: "pre-line" }}>{a.value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
)}
|
||||
{order.notes && (
|
||||
<p style={{ color: "var(--color-text-muted)" }}>
|
||||
{t("admin.orderDetail.notes")} {order.notes}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { apiFetch } from "../../api/client";
|
||||
import { listAdminOrders } from "../../api/orders";
|
||||
import { formatCents, type Order } from "../../api/types";
|
||||
import { useI18n } from "../../i18n/LanguageContext";
|
||||
|
||||
@@ -12,8 +12,8 @@ export default function OrdersPage() {
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true);
|
||||
apiFetch<{ orders: Order[] }>("/api/admin/orders")
|
||||
.then((data) => setOrders(data.orders))
|
||||
listAdminOrders()
|
||||
.then(setOrders)
|
||||
.catch(() => setError(t("admin.orders.loadError")))
|
||||
.finally(() => setLoading(false));
|
||||
}, [t]);
|
||||
@@ -30,7 +30,7 @@ export default function OrdersPage() {
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{t("admin.orders.colCustomer")}</th>
|
||||
<th>{t("admin.orders.colEmail")}</th>
|
||||
<th>{t("admin.orders.colPhone")}</th>
|
||||
<th>{t("admin.orders.colTotal")}</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
@@ -39,7 +39,7 @@ export default function OrdersPage() {
|
||||
{orders.map((o) => (
|
||||
<tr key={o.id}>
|
||||
<td>{o.customer_name}</td>
|
||||
<td>{o.customer_email}</td>
|
||||
<td>{o.contacts?.phone ?? ""}</td>
|
||||
<td>{formatCents(o.total_cents)}</td>
|
||||
<td>
|
||||
<Link className="btn" to={`/admin/orders/${o.id}`}>
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { CheckoutOptionKey } from "../../api/checkoutFields";
|
||||
import type { MessageKey } from "../../i18n/messages";
|
||||
|
||||
// Where a checkout answer is sent (and stored): `contacts` holds the phone
|
||||
// and messengers, `info_sup` the address and preferred hour, `notes` the
|
||||
// free-text note. Same split as the backend's orders module.
|
||||
export type CheckoutTarget = "contacts" | "info_sup" | "notes";
|
||||
|
||||
export interface CheckoutFieldDef {
|
||||
key: CheckoutOptionKey;
|
||||
target: CheckoutTarget;
|
||||
input: "tel" | "text" | "textarea" | "time";
|
||||
// The backend refuses an enabled option left empty only for these two.
|
||||
required: boolean;
|
||||
maxLength: number;
|
||||
labelKey: MessageKey;
|
||||
}
|
||||
|
||||
// Order = display order on the checkout form and in the admin settings.
|
||||
export const CHECKOUT_FIELDS: CheckoutFieldDef[] = [
|
||||
{ key: "phone", target: "contacts", input: "tel", required: true, maxLength: 30, labelKey: "checkout.field.phone" },
|
||||
{ key: "address", target: "info_sup", input: "textarea", required: true, maxLength: 300, labelKey: "checkout.field.address" },
|
||||
{ key: "hour", target: "info_sup", input: "time", required: false, maxLength: 5, labelKey: "checkout.field.hour" },
|
||||
{ key: "snap", target: "contacts", input: "text", required: false, maxLength: 100, labelKey: "checkout.field.snap" },
|
||||
{ key: "insta", target: "contacts", input: "text", required: false, maxLength: 100, labelKey: "checkout.field.insta" },
|
||||
{ key: "telegram", target: "contacts", input: "text", required: false, maxLength: 100, labelKey: "checkout.field.telegram" },
|
||||
{ key: "simplex", target: "contacts", input: "text", required: false, maxLength: 100, labelKey: "checkout.field.simplex" },
|
||||
{ key: "whatsapp", target: "contacts", input: "text", required: false, maxLength: 100, labelKey: "checkout.field.whatsapp" },
|
||||
{ key: "signal", target: "contacts", input: "text", required: false, maxLength: 100, labelKey: "checkout.field.signal" },
|
||||
{ key: "notes", target: "notes", input: "textarea", required: false, maxLength: 1000, labelKey: "checkout.field.notes" },
|
||||
];
|
||||
|
||||
// Reasons the backend can give for a rejected field.
|
||||
export const CHECKOUT_REASON_KEYS: Record<string, MessageKey> = {
|
||||
required: "checkout.reason.required",
|
||||
too_long: "checkout.reason.tooLong",
|
||||
invalid_format: "checkout.reason.invalidFormat",
|
||||
invalid_characters: "checkout.reason.invalidCharacters",
|
||||
too_many_fields: "checkout.reason.tooManyFields",
|
||||
};
|
||||
@@ -1,12 +1,23 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { Link, useNavigate } from "react-router-dom";
|
||||
import { ApiError, customerApiFetch } from "../../api/client";
|
||||
import type { Order } from "../../api/types";
|
||||
import { ApiError } from "../../api/client";
|
||||
import { createOrder } from "../../api/orders";
|
||||
import { useCart } from "./CartContext";
|
||||
import { useCustomerAuth } from "./CustomerAuthContext";
|
||||
import { useSiteSettings } from "./SiteSettingsContext";
|
||||
import { useCheckoutOptions } from "./useCheckoutOptions";
|
||||
import { CHECKOUT_FIELDS, CHECKOUT_REASON_KEYS } from "../checkout/fields";
|
||||
import { useI18n } from "../../i18n/LanguageContext";
|
||||
|
||||
// The backend answers 400 {error: "invalid field", field, reason} for a
|
||||
// refused checkout answer.
|
||||
function rejectedField(err: unknown): { field: string; reason: string } | null {
|
||||
if (!(err instanceof ApiError) || err.status !== 400) return null;
|
||||
const body = err.body as { field?: unknown; reason?: unknown } | undefined;
|
||||
if (typeof body?.field !== "string" || typeof body?.reason !== "string") return null;
|
||||
return { field: body.field, reason: body.reason };
|
||||
}
|
||||
|
||||
export default function CheckoutPage() {
|
||||
const { t } = useI18n();
|
||||
const { items, totalCents, clear } = useCart();
|
||||
@@ -14,10 +25,11 @@ export default function CheckoutPage() {
|
||||
const site = useSiteSettings();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { options } = useCheckoutOptions();
|
||||
|
||||
const [name, setName] = useState("");
|
||||
const [email, setEmail] = useState("");
|
||||
const [phone, setPhone] = useState("");
|
||||
const [notes, setNotes] = useState("");
|
||||
// One answer per enabled option, keyed by option key (phone, address, ...).
|
||||
const [answers, setAnswers] = useState<Record<string, string>>({});
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
@@ -62,27 +74,41 @@ export default function CheckoutPage() {
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
// customerApiFetch attaches the logged-in customer's bearer token
|
||||
// (when there is one) so RequireCustomer/RequireApprovedVerification
|
||||
// can authenticate the request; guests simply send no token.
|
||||
const order = await customerApiFetch<Order>("/api/orders", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
customer_name: name,
|
||||
customer_email: email,
|
||||
customer_phone: phone,
|
||||
notes,
|
||||
items: items.map((item) => ({
|
||||
product_id: item.productId,
|
||||
price_tier_id: item.priceTierId,
|
||||
multiplier: item.multiplier,
|
||||
})),
|
||||
}),
|
||||
// Only the options the admin enabled are sent; the server re-checks
|
||||
// them against the real settings and ignores anything else.
|
||||
const contacts: Record<string, string> = {};
|
||||
const infoSup: Record<string, string> = {};
|
||||
let notes = "";
|
||||
for (const field of CHECKOUT_FIELDS) {
|
||||
if (!options?.[field.key]) continue;
|
||||
const value = (answers[field.key] ?? "").trim();
|
||||
if (field.target === "contacts") contacts[field.key] = value;
|
||||
else if (field.target === "info_sup") infoSup[field.key] = value;
|
||||
else notes = value;
|
||||
}
|
||||
|
||||
const order = await createOrder({
|
||||
customer_name: name,
|
||||
contacts,
|
||||
info_sup: infoSup,
|
||||
notes,
|
||||
items: items.map((item) => ({
|
||||
product_id: item.productId,
|
||||
price_tier_id: item.priceTierId,
|
||||
multiplier: item.multiplier,
|
||||
})),
|
||||
});
|
||||
clear();
|
||||
navigate("/order-confirmation", { state: { order } });
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && (err.status === 403 || err.status === 401)) {
|
||||
const rejected = rejectedField(err);
|
||||
if (rejected) {
|
||||
// The server named the field it refused: say which one and why.
|
||||
const def = CHECKOUT_FIELDS.find((f) => f.key === rejected.field);
|
||||
const field = def ? t(def.labelKey) : rejected.field === "customer_name" ? t("storefront.checkout.fullName") : rejected.field;
|
||||
const reasonKey = CHECKOUT_REASON_KEYS[rejected.reason];
|
||||
setError(t("storefront.checkout.invalidField", { field, reason: reasonKey ? t(reasonKey) : rejected.reason }));
|
||||
} else if (err instanceof ApiError && (err.status === 403 || err.status === 401)) {
|
||||
// Surface the backend's own message: it explains *why* checkout is
|
||||
// blocked (e.g. "ordering requires a customer account, which is
|
||||
// currently disabled" or "identity verification must be approved
|
||||
@@ -106,29 +132,41 @@ export default function CheckoutPage() {
|
||||
<label htmlFor="name">{t("storefront.checkout.fullName")}</label>
|
||||
<input id="name" value={name} onChange={(e) => setName(e.target.value)} required />
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="checkout-email">{t("storefront.checkout.email")}</label>
|
||||
<input
|
||||
id="checkout-email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="phone">{t("storefront.checkout.phone")}</label>
|
||||
<input id="phone" value={phone} onChange={(e) => setPhone(e.target.value)} />
|
||||
</div>
|
||||
<div className="field">
|
||||
<label htmlFor="notes">{t("storefront.checkout.notes")}</label>
|
||||
<textarea id="notes" rows={3} value={notes} onChange={(e) => setNotes(e.target.value)} />
|
||||
</div>
|
||||
{options &&
|
||||
CHECKOUT_FIELDS.filter((field) => options[field.key]).map((field) => {
|
||||
const id = `checkout-${field.key}`;
|
||||
const value = answers[field.key] ?? "";
|
||||
const onChange = (v: string) => setAnswers((prev) => ({ ...prev, [field.key]: v }));
|
||||
return (
|
||||
<div className="field" key={field.key}>
|
||||
<label htmlFor={id}>{t(field.labelKey)}</label>
|
||||
{field.input === "textarea" ? (
|
||||
<textarea
|
||||
id={id}
|
||||
rows={3}
|
||||
value={value}
|
||||
maxLength={field.maxLength}
|
||||
required={field.required}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
id={id}
|
||||
type={field.input}
|
||||
value={value}
|
||||
maxLength={field.maxLength}
|
||||
required={field.required}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<p>
|
||||
<strong>{t("storefront.checkout.total", { amount: (totalCents / 100).toFixed(2) })}</strong>
|
||||
</p>
|
||||
<div className="form-actions">
|
||||
<button type="submit" className="btn btn-primary" disabled={submitting}>
|
||||
<button type="submit" className="btn btn-primary" disabled={submitting || !options}>
|
||||
{submitting ? t("storefront.checkout.submitting") : t("storefront.checkout.submit")}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { getCheckoutOptions, type CheckoutOptions } from "../../api/checkoutFields";
|
||||
|
||||
// Same as the migration's defaults: if the settings cannot be read the form
|
||||
// still asks for the essentials, and the server stays the source of truth
|
||||
// (it validates every order against the real settings).
|
||||
const FALLBACK: CheckoutOptions = {
|
||||
phone: true,
|
||||
address: true,
|
||||
snap: false,
|
||||
insta: false,
|
||||
telegram: false,
|
||||
simplex: false,
|
||||
whatsapp: false,
|
||||
signal: false,
|
||||
notes: false,
|
||||
hour: false,
|
||||
};
|
||||
|
||||
// Not cached on purpose: the admin can change the options at any time and a
|
||||
// checkout should reflect them on the next visit.
|
||||
export function useCheckoutOptions(): { options: CheckoutOptions | null } {
|
||||
const [options, setOptions] = useState<CheckoutOptions | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
getCheckoutOptions()
|
||||
.then(setOptions)
|
||||
.catch(() => setOptions(FALLBACK));
|
||||
}, []);
|
||||
|
||||
return { options };
|
||||
}
|
||||
@@ -250,7 +250,7 @@ export const messages = {
|
||||
"admin.orders.title": { en: "Orders", fr: "Commandes", es: "Pedidos", de: "Bestellungen" },
|
||||
"admin.orders.loadError": { en: "Failed to load orders.", fr: "Échec du chargement des commandes.", es: "No se pudieron cargar los pedidos.", de: "Bestellungen konnten nicht geladen werden." },
|
||||
"admin.orders.colCustomer": { en: "Customer", fr: "Client", es: "Cliente", de: "Kunde" },
|
||||
"admin.orders.colEmail": { en: "Email", fr: "E-mail", es: "Correo electrónico", de: "E-Mail" },
|
||||
"admin.orders.colPhone": { en: "Phone", fr: "Téléphone", es: "Teléfono", de: "Telefon" },
|
||||
"admin.orders.colTotal": { en: "Total", fr: "Total", es: "Total", de: "Gesamt" },
|
||||
"admin.orders.view": { en: "View", fr: "Voir", es: "Ver", de: "Ansehen" },
|
||||
|
||||
@@ -385,6 +385,29 @@ export const messages = {
|
||||
"storefront.cart.total": { en: "Total: {{amount}}", fr: "Total : {{amount}}", es: "Total: {{amount}}", de: "Gesamt: {{amount}}" },
|
||||
"storefront.cart.checkout": { en: "Checkout", fr: "Commander", es: "Pagar", de: "Zur Kasse" },
|
||||
|
||||
"layout.admin.nav.checkoutFields": { en: "Checkout fields", fr: "Champs de commande", es: "Campos del pedido", de: "Bestellfelder" },
|
||||
"admin.checkoutFields.title": { en: "Checkout fields", fr: "Champs de commande", es: "Campos del pedido", de: "Bestellfelder" },
|
||||
"admin.checkoutFields.hint": { en: "Choose what the customer has to provide when ordering. The customer's name is always asked.", fr: "Choisissez ce que le client doit renseigner à la commande. Le nom du client est toujours demandé.", es: "Elige qué debe indicar el cliente al pedir. El nombre del cliente siempre se solicita.", de: "Wählen Sie, was der Kunde bei der Bestellung angeben muss. Der Name des Kunden wird immer abgefragt." },
|
||||
"admin.checkoutFields.requiredWhenEnabled": { en: "required when enabled", fr: "obligatoire si activé", es: "obligatorio si se activa", de: "Pflichtfeld, wenn aktiviert" },
|
||||
"admin.checkoutFields.loadError": { en: "Failed to load the checkout fields.", fr: "Échec du chargement des champs de commande.", es: "No se pudieron cargar los campos del pedido.", de: "Bestellfelder konnten nicht geladen werden." },
|
||||
"admin.checkoutFields.saved": { en: "Checkout fields saved.", fr: "Champs de commande enregistrés.", es: "Campos del pedido guardados.", de: "Bestellfelder gespeichert." },
|
||||
"admin.checkoutFields.saveError": { en: "Failed to save the checkout fields.", fr: "Échec de l'enregistrement des champs de commande.", es: "No se pudieron guardar los campos del pedido.", de: "Bestellfelder konnten nicht gespeichert werden." },
|
||||
"checkout.field.phone": { en: "Phone", fr: "Téléphone", es: "Teléfono", de: "Telefon" },
|
||||
"checkout.field.address": { en: "Address", fr: "Adresse", es: "Dirección", de: "Adresse" },
|
||||
"checkout.field.hour": { en: "Preferred time", fr: "Heure souhaitée", es: "Hora preferida", de: "Gewünschte Uhrzeit" },
|
||||
"checkout.field.snap": { en: "Snapchat", fr: "Snapchat", es: "Snapchat", de: "Snapchat" },
|
||||
"checkout.field.insta": { en: "Instagram", fr: "Instagram", es: "Instagram", de: "Instagram" },
|
||||
"checkout.field.telegram": { en: "Telegram", fr: "Telegram", es: "Telegram", de: "Telegram" },
|
||||
"checkout.field.simplex": { en: "SimpleX", fr: "SimpleX", es: "SimpleX", de: "SimpleX" },
|
||||
"checkout.field.whatsapp": { en: "WhatsApp", fr: "WhatsApp", es: "WhatsApp", de: "WhatsApp" },
|
||||
"checkout.field.signal": { en: "Signal", fr: "Signal", es: "Signal", de: "Signal" },
|
||||
"checkout.field.notes": { en: "Notes", fr: "Notes", es: "Notas", de: "Notizen" },
|
||||
"checkout.reason.required": { en: "required", fr: "obligatoire", es: "obligatorio", de: "erforderlich" },
|
||||
"checkout.reason.tooLong": { en: "too long", fr: "trop long", es: "demasiado largo", de: "zu lang" },
|
||||
"checkout.reason.invalidFormat": { en: "invalid format", fr: "format invalide", es: "formato no válido", de: "ungültiges Format" },
|
||||
"checkout.reason.invalidCharacters": { en: "invalid characters", fr: "caractères invalides", es: "caracteres no válidos", de: "ungültige Zeichen" },
|
||||
"checkout.reason.tooManyFields": { en: "too many fields", fr: "trop de champs", es: "demasiados campos", de: "zu viele Felder" },
|
||||
"storefront.checkout.invalidField": { en: "Invalid information: {{field}} ({{reason}}).", fr: "Information invalide : {{field}} ({{reason}}).", es: "Información no válida: {{field}} ({{reason}}).", de: "Ungültige Angabe: {{field}} ({{reason}})." },
|
||||
// --- storefront checkout ---
|
||||
"storefront.checkout.title": { en: "Checkout", fr: "Commande", es: "Pago", de: "Kasse" },
|
||||
"storefront.checkout.emptyCart": { en: "Your cart is empty.", fr: "Votre panier est vide.", es: "Tu carrito está vacío.", de: "Dein Warenkorb ist leer." },
|
||||
@@ -394,7 +417,6 @@ export const messages = {
|
||||
"storefront.checkout.loginRequiredLink": { en: "Sign in or create one", fr: "Connectez-vous ou créez-en un", es: "Inicia sesión o crea una", de: "Anmelden oder eins erstellen" },
|
||||
"storefront.checkout.loginRequiredSuffix": { en: ", then come back to checkout.", fr: ", puis revenez commander.", es: ", y luego vuelve a pagar.", de: ", und kehre dann zur Kasse zurück." },
|
||||
"storefront.checkout.fullName": { en: "Full name", fr: "Nom complet", es: "Nombre completo", de: "Vollständiger Name" },
|
||||
"storefront.checkout.email": { en: "Email", fr: "E-mail", es: "Correo electrónico", de: "E-Mail" },
|
||||
"storefront.checkout.phone": { en: "Phone", fr: "Téléphone", es: "Teléfono", de: "Telefon" },
|
||||
"storefront.checkout.notes": { en: "Notes", fr: "Notes", es: "Notas", de: "Notizen" },
|
||||
"storefront.checkout.total": { en: "Total: {{amount}}", fr: "Total : {{amount}}", es: "Total: {{amount}}", de: "Gesamt: {{amount}}" },
|
||||
|
||||
Reference in New Issue
Block a user