Compare commits

...

1 Commits

Author SHA1 Message Date
mihir 21b328e141 feat: cash on delivery and manual UPI checkout
continuous-integration/drone/push Build is passing Details
Checkout asks for a payment method. UPI orders show the payable total, UPI ID, QR image and a UTR form. Order pages show status history with tracking notes; staff can confirm UPI payment, record shipment and mark delivery. Confirmed orders can still be cancelled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 15:32:19 +05:30
7 changed files with 251 additions and 23 deletions

View File

@ -1 +1,5 @@
VITE_ORGANIZATION_ID= VITE_ORGANIZATION_ID=
# Manual UPI payments shown on the order page (QR image goes in public/upi-qr.png)
VITE_UPI_ID=
VITE_UPI_NAME=Mani Candles

View File

@ -36,3 +36,16 @@ See [delivery phases](docs/PHASES.md) and [UAT evidence](docs/UAT-RESULTS.md).
Phase 2 commands: `npm run check` runs lint, strict types, contract/component/workflow tests and the measured production build. Dependency security is checked with `npm audit --audit-level=high` in CI. See [Phase 2 evidence](docs/UAT-PHASE2.md) and [release checklist](docs/RELEASE-CHECKLIST.md). Phase 2 commands: `npm run check` runs lint, strict types, contract/component/workflow tests and the measured production build. Dependency security is checked with `npm audit --audit-level=high` in CI. See [Phase 2 evidence](docs/UAT-PHASE2.md) and [release checklist](docs/RELEASE-CHECKLIST.md).
Set the backend RECOVERY_URL to your HTTPS frontend /reset-password route. Pending checkout and stock commands survive navigation within an active session; reload discards local credentials and intents. If interrupted, check orders/ledger before starting a new command. Set the backend RECOVERY_URL to your HTTPS frontend /reset-password route. Pending checkout and stock commands survive navigation within an active session; reload discards local credentials and intents. If interrupted, check orders/ledger before starting a new command.
## Cash on delivery and UPI
Checkout requires a payment method. Cash on delivery confirms the order at once. UPI orders wait up to 48 hours: the order page shows the exact payable total, the UPI ID and QR code, and a form for the customer's UTR. Staff confirm the payment, then record shipment (courier and tracking note, shown to the customer) and delivery under Admin orders.
Set these at build time (for example in `.env.production.local`, which is not committed):
```sh
VITE_UPI_ID=yourname@bank
VITE_UPI_NAME=Mani Candles
```
Put the QR image for that UPI ID at `public/upi-qr.png` before building. Without `VITE_UPI_ID` the order page asks the customer to contact you instead. Tax and shipping must be configured as an active pricing policy, or paid checkout is refused.

View File

@ -38,4 +38,4 @@ Record the active and previous build/commit release IDs before rollout. The SSH
## Operational limits ## Operational limits
Pending intents exist only within the active browser session; reloading signs out and discards them. After interruption, inspect orders or the stock ledger before beginning a new intent. The backend currently has no live gateway/carrier or contact delivery; customer self-registration is available. Staff catalog/role writes follow the backend's existing concurrency policy; coordinate overlapping administration edits. Never reinterpret finalized merchandise as proof of payment or fulfillment. Pending intents exist only within the active browser session; reloading signs out and discards them. After interruption, inspect orders or the stock ledger before beginning a new intent. The backend currently has no live payment gateway, carrier integration or contact delivery; cash on delivery and manually confirmed UPI are available; customer self-registration is available. Staff catalog/role writes follow the backend's existing concurrency policy; coordinate overlapping administration edits. Never reinterpret finalized merchandise as proof of payment or fulfillment.

View File

@ -55,8 +55,14 @@ export const checkoutInput = z
addressId: uuid, addressId: uuid,
idempotencyKey: uuid, idempotencyKey: uuid,
couponCode: couponCode.optional(), couponCode: couponCode.optional(),
paymentMethod: z.enum(["COD", "UPI_MANUAL"]).optional(),
}) })
.strict(); .strict();
export const paymentReference = z
.string()
.trim()
.toUpperCase()
.regex(/^[A-Z0-9]{6,40}$/, "Enter the 6–40 letter or digit UPI reference (UTR).");
export type CheckoutIntent = z.infer<typeof checkoutInput>; export type CheckoutIntent = z.infer<typeof checkoutInput>;
export function checkoutIntent( export function checkoutIntent(
input: Omit<CheckoutIntent, "idempotencyKey">, input: Omit<CheckoutIntent, "idempotencyKey">,
@ -80,7 +86,15 @@ export function moneyTotal(lines: { price: string; quantity: number }[]) {
} }
export const orderSummary = z.object({ export const orderSummary = z.object({
id: uuid, id: uuid,
status: z.enum(["PENDING_PAYMENT", "CANCELLED", "EXPIRED"]), status: z.enum([
"PENDING_PAYMENT",
"CONFIRMED",
"SHIPPED",
"DELIVERED",
"CANCELLED",
"EXPIRED",
]),
paymentMethod: z.enum(["COD", "UPI_MANUAL"]).nullable().default(null),
currency, currency,
merchandiseTotal: decimal, merchandiseTotal: decimal,
createdAt: z.string(), createdAt: z.string(),
@ -94,6 +108,15 @@ export const order = orderSummary.extend({
shippingTotal: decimal.nullable(), shippingTotal: decimal.nullable(),
payableTotal: decimal.nullable(), payableTotal: decimal.nullable(),
paymentAvailable: z.literal(false), paymentAvailable: z.literal(false),
history: z
.array(
z.object({
status: z.string(),
note: z.string(),
createdAt: z.string(),
}),
)
.default([]),
address: addressInput.omit({ isDefault: true }).strip(), address: addressInput.omit({ isDefault: true }).strip(),
lines: z.array( lines: z.array(
z.object({ z.object({

View File

@ -33,6 +33,7 @@ function Cart() {
[error, setError] = useState<unknown>(null), [error, setError] = useState<unknown>(null),
[addressId, setAddressId] = useState(""), [addressId, setAddressId] = useState(""),
[coupon, setCoupon] = useState(""), [coupon, setCoupon] = useState(""),
[paymentMethod, setPaymentMethod] = useState<"COD" | "UPI_MANUAL" | "">(""),
[uncertain, setUncertain] = useState(Boolean(attempt.current)), [uncertain, setUncertain] = useState(Boolean(attempt.current)),
[review, setReview] = useState(false); [review, setReview] = useState(false);
const [reviewedVersion, setReviewedVersion] = useState<number | null>(null); const [reviewedVersion, setReviewedVersion] = useState<number | null>(null);
@ -86,6 +87,7 @@ function Cart() {
cartVersion: reviewedVersion, cartVersion: reviewedVersion,
addressId, addressId,
couponCode: coupon.trim() ? coupon : undefined, couponCode: coupon.trim() ? coupon : undefined,
paymentMethod: paymentMethod || undefined,
}, },
crypto.randomUUID(), crypto.randomUUID(),
); );
@ -246,15 +248,33 @@ function Cart() {
inputProps={{ maxLength: 40 }} inputProps={{ maxLength: 40 }}
disabled={busy || uncertain || review} disabled={busy || uncertain || review}
/> />
<TextField
select
required
label="Payment method"
fullWidth
value={paymentMethod}
onChange={(e) => {
setPaymentMethod(e.target.value as "COD" | "UPI_MANUAL");
setReview(false);
}}
disabled={busy || uncertain || review}
helperText={
paymentMethod === "UPI_MANUAL"
? "After placing the order you will see the exact amount and our UPI QR code."
: paymentMethod === "COD"
? "Pay the courier in cash or UPI when your order arrives."
: undefined
}
>
<MenuItem value="COD">Cash on delivery</MenuItem>
<MenuItem value="UPI_MANUAL">Pay now by UPI (QR code)</MenuItem>
</TextField>
</> </>
)} )}
</> </>
)} )}
</QueryView> </QueryView>
<Alert severity="warning">
Payment collection is unavailable. Creating an order reserves stock;
it does not charge you or confirm fulfillment.
</Alert>
{uncertain ? ( {uncertain ? (
<> <>
<Alert severity="warning"> <Alert severity="warning">
@ -276,8 +296,9 @@ function Cart() {
) : review ? ( ) : review ? (
<> <>
<p> <p>
Review the selected address, coupon and cart quantities above. Review the selected address, coupon, payment method and cart
Confirm to create a pending order using the current server prices. quantities above. Confirm to place the order at the current
server prices, including tax and shipping.
</p> </p>
<Button disabled={busy} onClick={() => setReview(false)}> <Button disabled={busy} onClick={() => setReview(false)}>
Back to editing Back to editing
@ -295,6 +316,7 @@ function Cart() {
disabled={ disabled={
busy || busy ||
!addressId || !addressId ||
!paymentMethod ||
!query.data?.lines.length || !query.data?.lines.length ||
query.isFetching || query.isFetching ||
addresses.isFetching || addresses.isFetching ||

View File

@ -1,10 +1,20 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { z } from "zod"; import { z } from "zod";
import Alert from "@mui/material/Alert"; import Alert from "@mui/material/Alert";
import { order, orderSummary, money, uuid } from "@/lib/commerce"; import {
order,
orderSummary,
money,
paymentReference,
uuid,
type Order,
} from "@/lib/commerce";
import { usePlatform } from "@/lib/platform"; import { usePlatform } from "@/lib/platform";
import { WorkspaceShell } from "@/components/WorkspaceShell"; import { WorkspaceShell } from "@/components/WorkspaceShell";
import { import {
ActionForm,
Field,
readText,
Pager, Pager,
Panel, Panel,
QueryView, QueryView,
@ -39,7 +49,7 @@ function OrderList({ admin }: { admin: boolean }) {
<WorkspaceLink href={`${path}/${item.id}`}> <WorkspaceLink href={`${path}/${item.id}`}>
{item.id} {item.id}
</WorkspaceLink>, </WorkspaceLink>,
item.status, statusLabel[item.status] ?? item.status,
`${item.currency} ${money(item.merchandiseTotal)}`, `${item.currency} ${money(item.merchandiseTotal)}`,
new Date(item.createdAt).toLocaleString(), new Date(item.createdAt).toLocaleString(),
])} ])}
@ -51,6 +61,82 @@ function OrderList({ admin }: { admin: boolean }) {
</Panel> </Panel>
); );
} }
const statusLabel: Record<string, string> = {
PENDING_PAYMENT: "Awaiting payment",
CONFIRMED: "Confirmed",
SHIPPED: "Shipped",
DELIVERED: "Delivered",
CANCELLED: "Cancelled",
EXPIRED: "Expired",
};
function UpiPayment({ item, onReported }: { item: Order; onReported: () => Promise<unknown> }) {
const { request } = usePlatform();
const upiId: string = import.meta.env.VITE_UPI_ID || "";
const upiName: string = import.meta.env.VITE_UPI_NAME || "Mani Candles";
const amount = item.payableTotal ? money(item.payableTotal) : null;
const link = upiId && amount
? `upi://pay?${new URLSearchParams({ pa: upiId, pn: upiName, am: amount, cu: item.currency, tn: `Order ${item.id.slice(0, 8)}` })}`
: "";
return (
<section aria-labelledby="upi-heading">
<h3 id="upi-heading">Pay by UPI</h3>
{!upiId || !amount ? (
<Alert severity="info">UPI details are not configured yet. Please contact us to pay for this order.</Alert>
) : (
<>
<p>
Pay exactly <strong>{item.currency} {amount}</strong> to <strong>{upiId}</strong> ({upiName})
before {new Date(item.expiresAt).toLocaleString()}.
</p>
<img
style={{ display: "block", margin: "1rem 0" }}
src="/upi-qr.png"
alt={`UPI QR code for ${upiId}`}
width={220}
height={220}
onError={(event) => { event.currentTarget.hidden = true; }}
/>
<p><a href={link}><u>Open in a UPI app</u></a></p>
</>
)}
<ActionForm
label="Send payment reference"
read={(data) => ({ reference: paymentReference.parse(readText(data, "reference")) })}
submit={async (body) => {
await request(`/orders/${item.id}/payment-reference`, order, { method: "POST", body });
await onReported();
}}
>
<Field name="reference" label="UPI transaction reference (UTR)" maxLength={40}
helper="Find the 12-digit UTR or reference number in your UPI app after paying." />
</ActionForm>
</section>
);
}
function StaffActions({ item, path, onChange }: { item: Order; path: string; onChange: () => Promise<unknown> }) {
const { request } = usePlatform();
const post = async (action: string, body?: unknown) => {
await request(`${path}/${action}`, order, { method: "POST", body });
await onChange();
};
if (item.status === "PENDING_PAYMENT" && item.paymentMethod === "UPI_MANUAL")
return (
<ConfirmAction
label="Confirm UPI payment"
message={`Confirm that ${item.currency} ${item.payableTotal ? money(item.payableTotal) : ""} arrived in the bank account with the reference shown in the history? This deducts stock.`}
onConfirm={() => post("confirm")}
/>
);
if (item.status === "CONFIRMED")
return (
<ActionForm label="Mark shipped" read={(data) => ({ note: readText(data, "note") })} submit={(body) => post("ship", body)}>
<Field name="note" label="Courier and tracking number" maxLength={200} helper="Shown to the customer, for example: Delhivery AWB 1234567890." />
</ActionForm>
);
if (item.status === "SHIPPED")
return <ConfirmAction label="Mark delivered" message="Mark this order as delivered?" onConfirm={() => post("deliver")} />;
return null;
}
function OrderDetail({ admin, id }: { admin: boolean; id: string }) { function OrderDetail({ admin, id }: { admin: boolean; id: string }) {
const { request, can } = usePlatform(), const { request, can } = usePlatform(),
path = `${admin ? "/admin/orders" : "/orders"}/${id}`, path = `${admin ? "/admin/orders" : "/orders"}/${id}`,
@ -72,9 +158,19 @@ function OrderDetail({ admin, id }: { admin: boolean; id: string }) {
{(item) => ( {(item) => (
<> <>
<p className="workspace-id"> <p className="workspace-id">
Order {item.id} · {item.status} Order {item.id} · {statusLabel[item.status] ?? item.status}
</p> </p>
<p>Hold expires: {new Date(item.expiresAt).toLocaleString()}</p> <p>
Payment:{" "}
{item.paymentMethod === "COD"
? "Cash on delivery"
: item.paymentMethod === "UPI_MANUAL"
? "UPI"
: "Not selected"}
</p>
{item.status === "PENDING_PAYMENT" && (
<p>Stock held until: {new Date(item.expiresAt).toLocaleString()}</p>
)}
<Table <Table
head={["Candle", "SKU", "Quantity", "Unit price", "Line total"]} head={["Candle", "SKU", "Quantity", "Unit price", "Line total"]}
rowKeys={item.lines.map((line) => line.variantId)} rowKeys={item.lines.map((line) => line.variantId)}
@ -118,12 +214,34 @@ function OrderDetail({ admin, id }: { admin: boolean; id: string }) {
: `${item.currency} ${money(item.payableTotal)}`} : `${item.currency} ${money(item.payableTotal)}`}
</dd> </dd>
</dl> </dl>
<Alert severity="info"> {item.pricingStatus === "UNFINALIZED" && (
{item.pricingStatus === "UNFINALIZED" <Alert severity="info">Tax and shipping have not been finalized.</Alert>
? "Tax and shipping have not been finalized. " )}
: "Tax may already be included in merchandise prices. "} {!admin && item.status === "PENDING_PAYMENT" && item.paymentMethod === "UPI_MANUAL" && (
Payment collection is unavailable. <UpiPayment item={item} onReported={() => query.refetch()} />
</Alert> )}
{!admin && item.status === "CONFIRMED" && item.paymentMethod === "COD" && (
<Alert severity="info">
Please keep {item.currency} {item.payableTotal ? money(item.payableTotal) : ""} ready for the courier.
</Alert>
)}
{item.history.length > 0 && (
<>
<h3>Order updates</h3>
<Table
head={["When", "Status", "Details"]}
rowKeys={item.history.map((event, index) => `${index}-${event.createdAt}`)}
rows={item.history.map((event) => [
new Date(event.createdAt).toLocaleString(),
statusLabel[event.status] ?? event.status,
event.note || "—",
])}
/>
</>
)}
{admin && can("orders.manage") && (
<StaffActions item={item} path={path} onChange={() => query.refetch()} />
)}
<h3>Delivery snapshot</h3> <h3>Delivery snapshot</h3>
<p> <p>
{item.address.recipient} {item.address.recipient}
@ -135,11 +253,11 @@ function OrderDetail({ admin, id }: { admin: boolean; id: string }) {
<br /> <br />
{item.address.countryCode} · {item.address.phone} {item.address.countryCode} · {item.address.phone}
</p> </p>
{item.status === "PENDING_PAYMENT" && {(item.status === "PENDING_PAYMENT" || item.status === "CONFIRMED") &&
(!admin || can("orders.manage")) && ( (!admin || can("orders.manage")) && (
<ConfirmAction <ConfirmAction
label="Cancel order" label="Cancel order"
message="Cancel this order and release its stock holds? Cancellation does not rebuild your cart." message="Cancel this order? Its stock is returned. Cancellation does not rebuild your cart or refund a UPI payment automatically."
onConfirm={async () => { onConfirm={async () => {
await request(`${path}/cancel`, order, { method: "POST" }); await request(`${path}/cancel`, order, { method: "POST" });
await query.refetch(); await query.refetch();

View File

@ -970,6 +970,8 @@ test("uncertain checkout replays identical input after the cart version changes"
await screen.findByText("Test candle · Small"); await screen.findByText("Test candle · Small");
await user.click(screen.getByRole("combobox", { name: "Delivery address" })); await user.click(screen.getByRole("combobox", { name: "Delivery address" }));
await user.click(await screen.findByRole("option")); await user.click(await screen.findByRole("option"));
await user.click(screen.getByRole("combobox", { name: /Payment method/ }));
await user.click(await screen.findByRole("option", { name: "Cash on delivery" }));
await user.click(screen.getByRole("button", { name: "Review checkout" })); await user.click(screen.getByRole("button", { name: "Review checkout" }));
await user.click(screen.getByRole("button", { name: "Confirm order" })); await user.click(screen.getByRole("button", { name: "Confirm order" }));
await screen.findByRole("button", { name: "Retry original checkout" }); await screen.findByRole("button", { name: "Retry original checkout" });
@ -983,7 +985,7 @@ test("uncertain checkout replays identical input after the cart version changes"
); );
await waitFor(() => expect(attempts).toHaveLength(2)); await waitFor(() => expect(attempts).toHaveLength(2));
expect(attempts[1]).toEqual(attempts[0]); expect(attempts[1]).toEqual(attempts[0]);
expect(attempts[0]).toMatchObject({ cartVersion: 0, addressId: id }); expect(attempts[0]).toMatchObject({ cartVersion: 0, addressId: id, paymentMethod: "COD" });
await waitFor(() => expect(location.pathname).toBe(`/orders/${id}`)); await waitFor(() => expect(location.pathname).toBe(`/orders/${id}`));
}); });
@ -1011,6 +1013,8 @@ test("a changed cart invalidates checkout review instead of adopting a new versi
await screen.findByText("Test candle · Small"); await screen.findByText("Test candle · Small");
await user.click(screen.getByRole("combobox", { name: "Delivery address" })); await user.click(screen.getByRole("combobox", { name: "Delivery address" }));
await user.click(await screen.findByRole("option")); await user.click(await screen.findByRole("option"));
await user.click(screen.getByRole("combobox", { name: /Payment method/ }));
await user.click(await screen.findByRole("option", { name: "Cash on delivery" }));
await user.click(screen.getByRole("button", { name: "Review checkout" })); await user.click(screen.getByRole("button", { name: "Review checkout" }));
changed = true; changed = true;
await act(() => h.client.invalidateQueries({ queryKey: ["private"] })); await act(() => h.client.invalidateQueries({ queryKey: ["private"] }));
@ -1055,8 +1059,52 @@ test("unfinalized order charges are never shown as zero or payable", async () =>
harness(<OrdersPage id={id} />); harness(<OrdersPage id={id} />);
const user = userEvent.setup(); const user = userEvent.setup();
await user.click(screen.getByText("Test login")); await user.click(screen.getByText("Test login"));
await screen.findByText(/Order .*PENDING_PAYMENT/); await screen.findByText(/Order .*Awaiting payment/);
expect(screen.getAllByText("Unfinalized")).toHaveLength(3); expect(screen.getAllByText("Unfinalized")).toHaveLength(3);
expect(screen.queryByRole("button", { name: /pay now/i })).toBeNull(); expect(screen.queryByRole("button", { name: /pay now/i })).toBeNull();
expect(screen.getByText(/Payment collection is unavailable/)).toBeTruthy(); expect(screen.getByText(/Tax and shipping have not been finalized/)).toBeTruthy();
});
test("a UPI order shows the payable amount and reports the customer's UTR", async () => {
vi.stubEnv("VITE_UPI_ID", "mani@upi");
const upiOrder = { ...order, paymentMethod: "UPI_MANUAL", pricingStatus: "FINALIZED", taxTotal: "1.80", shippingTotal: "50", payableTotal: "61.80", history: [] };
const bodies: unknown[] = [];
vi.stubGlobal("fetch", vi.fn(async (url: string, options?: RequestInit) => {
if (url.endsWith("/auth/login")) return json(session);
if (url.endsWith("/auth/me")) return json(me);
if (url.endsWith("/payment-reference")) {
bodies.push(JSON.parse(String(options?.body)));
return json({ ...upiOrder, history: [{ status: "PENDING_PAYMENT", note: "UPI reference UTR123456789", createdAt: new Date().toISOString() }] });
}
return json(upiOrder);
}));
harness(<OrdersPage id={id} />);
const user = userEvent.setup();
await user.click(screen.getByText("Test login"));
expect((await screen.findByText(/Pay exactly/)).textContent).toContain("INR 61.80");
fireEvent.change(screen.getByRole("textbox", { name: /UPI transaction reference/ }), { target: { value: " utr123456789 " } });
await user.click(screen.getByRole("button", { name: "Send payment reference" }));
await waitFor(() => expect(bodies).toEqual([{ reference: "UTR123456789" }]));
vi.unstubAllEnvs();
});
test("staff record shipment with a courier note on a confirmed order", async () => {
const confirmed = { ...order, status: "CONFIRMED", paymentMethod: "COD", history: [] };
const calls: [string, unknown][] = [];
vi.stubGlobal("fetch", vi.fn(async (url: string, options?: RequestInit) => {
if (url.endsWith("/auth/login")) return json(session);
if (url.endsWith("/auth/me")) return json({ ...me, permissions: ["orders.read", "orders.manage"] });
if (options?.method === "POST") {
calls.push([url, JSON.parse(String(options.body))]);
return json({ ...confirmed, status: "SHIPPED" });
}
return json(confirmed);
}));
harness(<OrdersPage admin id={id} />);
const user = userEvent.setup();
await user.click(screen.getByText("Test login"));
fireEvent.change(await screen.findByRole("textbox", { name: /Courier and tracking number/ }), { target: { value: "Delhivery AWB 42" } });
await user.click(screen.getByRole("button", { name: "Mark shipped" }));
await waitFor(() => expect(calls).toEqual([[`/api/v1/admin/orders/${id}/ship`, { note: "Delhivery AWB 42" }]]));
expect(screen.queryByRole("button", { name: "Confirm UPI payment" })).toBeNull();
}); });