Compare commits
No commits in common. "feat/offline-payments" and "main" have entirely different histories.
feat/offli
...
main
|
|
@ -1,5 +1 @@
|
|||
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
|
||||
|
|
|
|||
13
README.md
13
README.md
|
|
@ -36,16 +36,3 @@ 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).
|
||||
|
||||
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.
|
||||
|
|
|
|||
|
|
@ -38,4 +38,4 @@ Record the active and previous build/commit release IDs before rollout. The SSH
|
|||
|
||||
## 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 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.
|
||||
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.
|
||||
|
|
|
|||
|
|
@ -55,14 +55,8 @@ export const checkoutInput = z
|
|||
addressId: uuid,
|
||||
idempotencyKey: uuid,
|
||||
couponCode: couponCode.optional(),
|
||||
paymentMethod: z.enum(["COD", "UPI_MANUAL"]).optional(),
|
||||
})
|
||||
.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 function checkoutIntent(
|
||||
input: Omit<CheckoutIntent, "idempotencyKey">,
|
||||
|
|
@ -86,15 +80,7 @@ export function moneyTotal(lines: { price: string; quantity: number }[]) {
|
|||
}
|
||||
export const orderSummary = z.object({
|
||||
id: uuid,
|
||||
status: z.enum([
|
||||
"PENDING_PAYMENT",
|
||||
"CONFIRMED",
|
||||
"SHIPPED",
|
||||
"DELIVERED",
|
||||
"CANCELLED",
|
||||
"EXPIRED",
|
||||
]),
|
||||
paymentMethod: z.enum(["COD", "UPI_MANUAL"]).nullable().default(null),
|
||||
status: z.enum(["PENDING_PAYMENT", "CANCELLED", "EXPIRED"]),
|
||||
currency,
|
||||
merchandiseTotal: decimal,
|
||||
createdAt: z.string(),
|
||||
|
|
@ -108,15 +94,6 @@ export const order = orderSummary.extend({
|
|||
shippingTotal: decimal.nullable(),
|
||||
payableTotal: decimal.nullable(),
|
||||
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(),
|
||||
lines: z.array(
|
||||
z.object({
|
||||
|
|
|
|||
|
|
@ -33,7 +33,6 @@ function Cart() {
|
|||
[error, setError] = useState<unknown>(null),
|
||||
[addressId, setAddressId] = useState(""),
|
||||
[coupon, setCoupon] = useState(""),
|
||||
[paymentMethod, setPaymentMethod] = useState<"COD" | "UPI_MANUAL" | "">(""),
|
||||
[uncertain, setUncertain] = useState(Boolean(attempt.current)),
|
||||
[review, setReview] = useState(false);
|
||||
const [reviewedVersion, setReviewedVersion] = useState<number | null>(null);
|
||||
|
|
@ -87,7 +86,6 @@ function Cart() {
|
|||
cartVersion: reviewedVersion,
|
||||
addressId,
|
||||
couponCode: coupon.trim() ? coupon : undefined,
|
||||
paymentMethod: paymentMethod || undefined,
|
||||
},
|
||||
crypto.randomUUID(),
|
||||
);
|
||||
|
|
@ -248,33 +246,15 @@ function Cart() {
|
|||
inputProps={{ maxLength: 40 }}
|
||||
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>
|
||||
<Alert severity="warning">
|
||||
Payment collection is unavailable. Creating an order reserves stock;
|
||||
it does not charge you or confirm fulfillment.
|
||||
</Alert>
|
||||
{uncertain ? (
|
||||
<>
|
||||
<Alert severity="warning">
|
||||
|
|
@ -296,9 +276,8 @@ function Cart() {
|
|||
) : review ? (
|
||||
<>
|
||||
<p>
|
||||
Review the selected address, coupon, payment method and cart
|
||||
quantities above. Confirm to place the order at the current
|
||||
server prices, including tax and shipping.
|
||||
Review the selected address, coupon and cart quantities above.
|
||||
Confirm to create a pending order using the current server prices.
|
||||
</p>
|
||||
<Button disabled={busy} onClick={() => setReview(false)}>
|
||||
Back to editing
|
||||
|
|
@ -316,7 +295,6 @@ function Cart() {
|
|||
disabled={
|
||||
busy ||
|
||||
!addressId ||
|
||||
!paymentMethod ||
|
||||
!query.data?.lines.length ||
|
||||
query.isFetching ||
|
||||
addresses.isFetching ||
|
||||
|
|
|
|||
|
|
@ -1,20 +1,10 @@
|
|||
import { useEffect, useState } from "react";
|
||||
import { z } from "zod";
|
||||
import Alert from "@mui/material/Alert";
|
||||
import {
|
||||
order,
|
||||
orderSummary,
|
||||
money,
|
||||
paymentReference,
|
||||
uuid,
|
||||
type Order,
|
||||
} from "@/lib/commerce";
|
||||
import { order, orderSummary, money, uuid } from "@/lib/commerce";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { WorkspaceShell } from "@/components/WorkspaceShell";
|
||||
import {
|
||||
ActionForm,
|
||||
Field,
|
||||
readText,
|
||||
Pager,
|
||||
Panel,
|
||||
QueryView,
|
||||
|
|
@ -49,7 +39,7 @@ function OrderList({ admin }: { admin: boolean }) {
|
|||
<WorkspaceLink href={`${path}/${item.id}`}>
|
||||
{item.id}
|
||||
</WorkspaceLink>,
|
||||
statusLabel[item.status] ?? item.status,
|
||||
item.status,
|
||||
`${item.currency} ${money(item.merchandiseTotal)}`,
|
||||
new Date(item.createdAt).toLocaleString(),
|
||||
])}
|
||||
|
|
@ -61,82 +51,6 @@ function OrderList({ admin }: { admin: boolean }) {
|
|||
</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 }) {
|
||||
const { request, can } = usePlatform(),
|
||||
path = `${admin ? "/admin/orders" : "/orders"}/${id}`,
|
||||
|
|
@ -158,19 +72,9 @@ function OrderDetail({ admin, id }: { admin: boolean; id: string }) {
|
|||
{(item) => (
|
||||
<>
|
||||
<p className="workspace-id">
|
||||
Order {item.id} · {statusLabel[item.status] ?? item.status}
|
||||
Order {item.id} · {item.status}
|
||||
</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>
|
||||
)}
|
||||
<p>Hold expires: {new Date(item.expiresAt).toLocaleString()}</p>
|
||||
<Table
|
||||
head={["Candle", "SKU", "Quantity", "Unit price", "Line total"]}
|
||||
rowKeys={item.lines.map((line) => line.variantId)}
|
||||
|
|
@ -214,34 +118,12 @@ function OrderDetail({ admin, id }: { admin: boolean; id: string }) {
|
|||
: `${item.currency} ${money(item.payableTotal)}`}
|
||||
</dd>
|
||||
</dl>
|
||||
{item.pricingStatus === "UNFINALIZED" && (
|
||||
<Alert severity="info">Tax and shipping have not been finalized.</Alert>
|
||||
)}
|
||||
{!admin && item.status === "PENDING_PAYMENT" && item.paymentMethod === "UPI_MANUAL" && (
|
||||
<UpiPayment item={item} onReported={() => query.refetch()} />
|
||||
)}
|
||||
{!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()} />
|
||||
)}
|
||||
<Alert severity="info">
|
||||
{item.pricingStatus === "UNFINALIZED"
|
||||
? "Tax and shipping have not been finalized. "
|
||||
: "Tax may already be included in merchandise prices. "}
|
||||
Payment collection is unavailable.
|
||||
</Alert>
|
||||
<h3>Delivery snapshot</h3>
|
||||
<p>
|
||||
{item.address.recipient}
|
||||
|
|
@ -253,11 +135,11 @@ function OrderDetail({ admin, id }: { admin: boolean; id: string }) {
|
|||
<br />
|
||||
{item.address.countryCode} · {item.address.phone}
|
||||
</p>
|
||||
{(item.status === "PENDING_PAYMENT" || item.status === "CONFIRMED") &&
|
||||
{item.status === "PENDING_PAYMENT" &&
|
||||
(!admin || can("orders.manage")) && (
|
||||
<ConfirmAction
|
||||
label="Cancel order"
|
||||
message="Cancel this order? Its stock is returned. Cancellation does not rebuild your cart or refund a UPI payment automatically."
|
||||
message="Cancel this order and release its stock holds? Cancellation does not rebuild your cart."
|
||||
onConfirm={async () => {
|
||||
await request(`${path}/cancel`, order, { method: "POST" });
|
||||
await query.refetch();
|
||||
|
|
|
|||
|
|
@ -970,8 +970,6 @@ test("uncertain checkout replays identical input after the cart version changes"
|
|||
await screen.findByText("Test candle · Small");
|
||||
await user.click(screen.getByRole("combobox", { name: "Delivery address" }));
|
||||
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: "Confirm order" }));
|
||||
await screen.findByRole("button", { name: "Retry original checkout" });
|
||||
|
|
@ -985,7 +983,7 @@ test("uncertain checkout replays identical input after the cart version changes"
|
|||
);
|
||||
await waitFor(() => expect(attempts).toHaveLength(2));
|
||||
expect(attempts[1]).toEqual(attempts[0]);
|
||||
expect(attempts[0]).toMatchObject({ cartVersion: 0, addressId: id, paymentMethod: "COD" });
|
||||
expect(attempts[0]).toMatchObject({ cartVersion: 0, addressId: id });
|
||||
await waitFor(() => expect(location.pathname).toBe(`/orders/${id}`));
|
||||
});
|
||||
|
||||
|
|
@ -1013,8 +1011,6 @@ test("a changed cart invalidates checkout review instead of adopting a new versi
|
|||
await screen.findByText("Test candle · Small");
|
||||
await user.click(screen.getByRole("combobox", { name: "Delivery address" }));
|
||||
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" }));
|
||||
changed = true;
|
||||
await act(() => h.client.invalidateQueries({ queryKey: ["private"] }));
|
||||
|
|
@ -1059,52 +1055,8 @@ test("unfinalized order charges are never shown as zero or payable", async () =>
|
|||
harness(<OrdersPage id={id} />);
|
||||
const user = userEvent.setup();
|
||||
await user.click(screen.getByText("Test login"));
|
||||
await screen.findByText(/Order .*Awaiting payment/);
|
||||
await screen.findByText(/Order .*PENDING_PAYMENT/);
|
||||
expect(screen.getAllByText("Unfinalized")).toHaveLength(3);
|
||||
expect(screen.queryByRole("button", { name: /pay now/i })).toBeNull();
|
||||
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();
|
||||
expect(screen.getByText(/Payment collection is unavailable/)).toBeTruthy();
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in New Issue