From 39ff6741a9d08470079add7ff4d5a09acb59a6b0 Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Sun, 6 Dec 2026 00:05:41 -0500 Subject: [PATCH 01/10] feat(receipts): scoped revocable receipt capabilities and idempotent email acceptance --- .github/workflows/worker-e2e.yml | 2 +- apps/api/migrations/0048_receipt_shares.sql | 12 +++ apps/api/src/index.ts | 3 + apps/api/src/receipt-shares.ts | 86 +++++++++++++++++++ apps/web/e2e-worker/receipt-shares.spec.ts | 18 ++++ apps/web/src/api/live.ts | 6 ++ apps/web/src/features/register/Receipt.tsx | 2 + .../src/features/register/SharedReceipt.tsx | 23 +++++ apps/web/src/main.tsx | 6 +- .../register-m6-private-receipt-links.md | 5 ++ tests/route-policy.mjs | 4 +- tests/verify-route-policy.mjs | 4 +- 12 files changed, 164 insertions(+), 7 deletions(-) create mode 100644 apps/api/migrations/0048_receipt_shares.sql create mode 100644 apps/api/src/receipt-shares.ts create mode 100644 apps/web/e2e-worker/receipt-shares.spec.ts create mode 100644 apps/web/src/features/register/SharedReceipt.tsx create mode 100644 docs/operations/register-m6-private-receipt-links.md diff --git a/.github/workflows/worker-e2e.yml b/.github/workflows/worker-e2e.yml index d90752b9..d929692b 100644 --- a/.github/workflows/worker-e2e.yml +++ b/.github/workflows/worker-e2e.yml @@ -16,7 +16,7 @@ jobs: strategy: fail-fast: false matrix: - suite: [merchant, contracts, recovery, integrity, roles, transfers, auth, money, woo, offline, cash-integrity, ops-load, catalog-import] + suite: [merchant, contracts, recovery, integrity, roles, transfers, auth, money, woo, offline, cash-integrity, ops-load, catalog-import, receipt-shares] timeout-minutes: 20 steps: - uses: actions/checkout@v4 diff --git a/apps/api/migrations/0048_receipt_shares.sql b/apps/api/migrations/0048_receipt_shares.sql new file mode 100644 index 00000000..5dc248a5 --- /dev/null +++ b/apps/api/migrations/0048_receipt_shares.sql @@ -0,0 +1,12 @@ +-- Phase M: public receipt capabilities. Separate from Phase N's 0038–0044 inventory migrations. +CREATE TABLE receipt_shares ( + id TEXT PRIMARY KEY, organization_id TEXT NOT NULL REFERENCES organizations(id), order_id TEXT NOT NULL REFERENCES orders(id), + actor_id TEXT NOT NULL REFERENCES users(id), token_hash TEXT NOT NULL UNIQUE, kind TEXT NOT NULL CHECK(kind IN ('standard','gift')), + snapshot_json TEXT NOT NULL, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, revoked_at INTEGER +); +CREATE INDEX receipt_shares_order_idx ON receipt_shares(organization_id,order_id,expires_at); +CREATE TABLE receipt_share_deliveries ( + id TEXT PRIMARY KEY, share_id TEXT NOT NULL REFERENCES receipt_shares(id), recipient_hash TEXT NOT NULL, + payload_hash TEXT NOT NULL, created_at INTEGER NOT NULL, accepted_at INTEGER, provider_id TEXT, + UNIQUE(share_id,recipient_hash) +); diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index 87f4d445..80b96c0f 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -9,6 +9,7 @@ import billing from './billing'; import media from './media'; import purchasing from './purchasing'; import offlineRecovery from './offline-recovery'; +import {receiptShares,publicReceipts} from './receipt-shares'; import {sweepWoo} from './woo-runner'; const app = new Hono(); @@ -33,6 +34,7 @@ app.get('/api/v1/meta',c=>c.json({data:{service:'storefront',version:'0.2.0',sta app.route('/api/v1',auth); app.route('/api/v1',webhook); +app.route('/api/v1',publicReceipts); // Protect catalog and commerce routes independently, even if auth module changes. const commerce=new Hono(); commerce.use('*',authenticated); @@ -43,6 +45,7 @@ commerce.route('/',billing); commerce.route('/',media); commerce.route('/',purchasing); commerce.route('/',offlineRecovery); +commerce.route('/',receiptShares); app.route('/api/v1',commerce); app.onError((error,c)=>{ diff --git a/apps/api/src/receipt-shares.ts b/apps/api/src/receipt-shares.ts new file mode 100644 index 00000000..1db8cea9 --- /dev/null +++ b/apps/api/src/receipt-shares.ts @@ -0,0 +1,86 @@ +import {Hono} from 'hono'; +import {z} from 'zod'; +import type {AppEnv,ApiContext} from './types'; +import {asData,fail,jsonBody,now,parseBody,requirePermission} from './types'; +import {pepper,sha256,throttle} from './security'; +export const receiptShares=new Hono(); +export const publicReceipts=new Hono(); +const uuid=z.string().uuid(); +const hex=(b:ArrayBuffer)=>Array.from(new Uint8Array(b),x=>x.toString(16).padStart(2,'0')).join(''); +async function tokenFor(c:ApiContext,id:string,organizationId:string){ + const enc=new TextEncoder(),key=await crypto.subtle.importKey('raw',enc.encode(pepper(c)),{name:'HMAC',hash:'SHA-256'},false,['sign']); + return hex(await crypto.subtle.sign('HMAC',key,enc.encode('storefront-receipt-share-v1:'+organizationId+':'+id))); +} +type Share={id:string;organizationId:string;orderId:string;actorId:string;kind:string;snapshotJson:string;expiresAt:number;revokedAt:number|null}; +const shareColumns='id,organization_id AS organizationId,order_id AS orderId,actor_id AS actorId,kind,snapshot_json AS snapshotJson,expires_at AS expiresAt,revoked_at AS revokedAt'; +async function authorizedOrder(c:ApiContext,p:ReturnType,orderId:string){ + const order=await c.env.DB.prepare(`SELECT o.id,o.cashier_id AS cashierId,o.order_number AS number,o.status,o.currency,o.created_at AS createdAt, + o.subtotal_minor AS subtotalMinor,o.discount_minor AS discountMinor,o.tax_minor AS taxMinor,o.rounding_minor AS roundingMinor,o.total_minor AS totalMinor, + st.name AS storeName,org.name AS organizationName + FROM orders o JOIN stores st ON st.id=o.store_id AND st.organization_id=o.organization_id JOIN organizations org ON org.id=o.organization_id + WHERE o.id=? AND o.organization_id=?`).bind(orderId,p.organizationId).first<{id:string;cashierId:string;number:string|null;status:string;currency:string;createdAt:number;subtotalMinor:number;discountMinor:number;taxMinor:number;roundingMinor:number;totalMinor:number;storeName:string;organizationName:string}>(); + if(!order||p.role==='cashier'&&order.cashierId!==p.userId)fail('NOT_FOUND','Receipt not found.',404); + if(!['completed','partially_returned','returned'].includes(order!.status))fail('RECEIPT_NOT_FINAL','Only recorded sales can be shared.',409); + return order!; +} +async function findShare(c:ApiContext,organizationId:string,orderId:string,id:string){ + return c.env.DB.prepare('SELECT '+shareColumns+' FROM receipt_shares WHERE id=? AND organization_id=? AND order_id=?').bind(id,organizationId,orderId).first(); +} +const active=(s:Share|null):s is Share=>!!s&&!s.revokedAt&&s.expiresAt>now(); +receiptShares.post('/orders/:id/receipt-shares',async c=>{ + const p=requirePermission(c,'sales:create'),orderId=c.req.param('id'),body=parseBody(await jsonBody(c),z.object({id:uuid,kind:z.enum(['standard','gift'])})); + const order=await authorizedOrder(c,p,orderId); + let row=await findShare(c,p.organizationId,orderId,body.id); + if(!row){ + await throttle(c,'receipt-share-create',p.organizationId,100); + const items=await c.env.DB.prepare(`SELECT name_snapshot AS name,oi.quantity,oi.unit_price_minor AS unitPriceMinor,oi.discount_minor AS discountMinor,oi.tax_minor AS taxMinor, + oi.total_minor AS totalMinor,COALESCE(rq.quantity,0) AS returnedQuantity FROM order_items oi + LEFT JOIN returned_quantities rq ON rq.order_item_id=oi.id WHERE oi.order_id=? ORDER BY oi.id`).bind(order.id).all>(); + const snapshot={kind:body.kind,number:order.number??'Receipt',store:order.storeName,merchant:order.organizationName,createdAt:order.createdAt,issuedAt:now(), + status:order.status,lines:items.results.map(x=>({name:x.name,quantity:x.quantity,returnedQuantity:x.returnedQuantity,...(body.kind==='standard'?{unitPriceMinor:x.unitPriceMinor,discountMinor:x.discountMinor,taxMinor:x.taxMinor,totalMinor:x.totalMinor}:{})})), + ...(body.kind==='standard'?{currency:order.currency,subtotalMinor:order.subtotalMinor,discountMinor:order.discountMinor,taxMinor:order.taxMinor,roundingMinor:order.roundingMinor,totalMinor:order.totalMinor}:{})}; + const token=await tokenFor(c,body.id,p.organizationId),hash=await sha256(token),created=now(); + await c.env.DB.prepare('INSERT OR IGNORE INTO receipt_shares(id,organization_id,order_id,actor_id,token_hash,kind,snapshot_json,created_at,expires_at) VALUES(?,?,?,?,?,?,?,?,?)').bind(body.id,p.organizationId,orderId,p.userId,hash,body.kind,JSON.stringify(snapshot),created,created+7*86400).run(); + row=await findShare(c,p.organizationId,orderId,body.id); + } + if(!row||row.kind!==body.kind||row.actorId!==p.userId)fail('RECEIPT_SHARE_CONFLICT','Link reference is already in use.',409); + if(!active(row))fail('RECEIPT_SHARE_EXPIRED','This link is expired or revoked. Create a new link.',409); + return c.json(asData({id:row.id,token:await tokenFor(c,row.id,p.organizationId),expiresAt:row.expiresAt})); +}); +receiptShares.post('/orders/:id/receipt-shares/revoke',async c=>{ + const p=requirePermission(c,'sales:create'),orderId=c.req.param('id');await authorizedOrder(c,p,orderId); + const result=await c.env.DB.prepare('UPDATE receipt_shares SET revoked_at=? WHERE organization_id=? AND order_id=? AND revoked_at IS NULL').bind(now(),p.organizationId,orderId).run(); + return c.json(asData({revoked:result.meta.changes??0})); +}); +publicReceipts.post('/receipt-shares/redeem',async c=>{ + const body=parseBody(await jsonBody(c),z.object({token:z.string().regex(/^[a-f0-9]{64}$/)})); + const row=await c.env.DB.prepare('SELECT snapshot_json AS snapshotJson FROM receipt_shares WHERE token_hash=? AND revoked_at IS NULL AND expires_at>?').bind(await sha256(body.token),now()).first<{snapshotJson:string}>(); + if(!row)fail('NOT_FOUND','Receipt link is invalid, expired or revoked.',404); + c.header('Referrer-Policy','no-referrer');c.header('X-Robots-Tag','noindex, nofollow, noarchive'); + return c.json(asData(JSON.parse(row!.snapshotJson))); +}); +receiptShares.post('/orders/:id/receipt-shares/email',async c=>{ + const p=requirePermission(c,'sales:create'),orderId=c.req.param('id'),body=parseBody(await jsonBody(c),z.object({shareId:uuid,email:z.string().trim().email().max(254)})); + await authorizedOrder(c,p,orderId); + const row=await findShare(c,p.organizationId,orderId,body.shareId); + if(!active(row))fail('NOT_FOUND','Receipt link is invalid, expired or revoked.',404); + if(!c.env.RESEND_API_KEY||!c.env.EMAIL_FROM||!c.env.APP_BASE_URL?.startsWith('https://'))fail('MAIL_NOT_CONFIGURED','Receipt email is not configured.',503); + const recipient=body.email,recipientHash=await sha256(pepper(c)+':receipt-email:'+recipient.toLowerCase()); + const url=new URL('/shared-receipt',c.env.APP_BASE_URL);url.hash=await tokenFor(c,row!.id,p.organizationId); + const payload={from:c.env.EMAIL_FROM,to:[recipient],subject:'Your Storefront receipt',text:'Your requested receipt is available for seven days from creation.\n\n'+url.href+'\n\nIf you did not request this receipt, ignore this email.'}; + const payloadHash=await sha256(JSON.stringify(payload)),deliveryKey=await sha256('receipt-delivery:'+p.organizationId+':'+row!.id+':'+recipientHash); + const find=()=>c.env.DB.prepare('SELECT payload_hash AS payloadHash,created_at AS createdAt,accepted_at AS acceptedAt FROM receipt_share_deliveries WHERE id=?').bind(deliveryKey).first<{payloadHash:string;createdAt:number;acceptedAt:number|null}>(); + let prior=await find(); + if(!prior){await throttle(c,'receipt-email',p.organizationId,30);await c.env.DB.prepare('INSERT OR IGNORE INTO receipt_share_deliveries(id,share_id,recipient_hash,payload_hash,created_at) VALUES(?,?,?,?,?)').bind(deliveryKey,row!.id,recipientHash,payloadHash,now()).run();prior=await find();} + if(!prior||prior.payloadHash!==payloadHash)fail('MAIL_REFERENCE_CONFLICT','Delivery details changed. Review the original delivery.',409); + if(prior.acceptedAt)return c.json(asData({status:'accepted',alreadyAccepted:true})); + // Provider deduplication is only guaranteed for 24h. Do not blindly resend an ambiguous attempt after 23h. + if(now()-prior.createdAt>=23*3600)fail('MAIL_REVIEW_REQUIRED','Original email acceptance is unknown. Check provider logs before creating another link.',409); + let response:Response; + try{response=await fetch('https://api.resend.com/emails',{method:'POST',headers:{Authorization:'Bearer '+c.env.RESEND_API_KEY,'Content-Type':'application/json','Idempotency-Key':'storefront-receipt/'+deliveryKey},body:JSON.stringify(payload),signal:AbortSignal.timeout(10000)});}catch{return fail('MAIL_UNCONFIRMED','Email acceptance is unknown. Retry the same link and recipient.',503);} + if(!response.ok)fail('MAIL_UNCONFIRMED','Email acceptance is not confirmed. Retry the same link and recipient or review provider logs.',503); + const accepted=await response.json().catch(()=>null) as {id?:string}|null; + if(!accepted?.id)fail('MAIL_UNCONFIRMED','Email acceptance is not confirmed. Retry the same link and recipient.',503); + await c.env.DB.prepare('UPDATE receipt_share_deliveries SET accepted_at=?,provider_id=? WHERE id=? AND accepted_at IS NULL').bind(now(),accepted!.id,deliveryKey).run(); + return c.json(asData({status:'accepted',alreadyAccepted:false})); +}); diff --git a/apps/web/e2e-worker/receipt-shares.spec.ts b/apps/web/e2e-worker/receipt-shares.spec.ts new file mode 100644 index 00000000..3ea4f9cd --- /dev/null +++ b/apps/web/e2e-worker/receipt-shares.spec.ts @@ -0,0 +1,18 @@ +import {expect,test,request as newRequest} from '@playwright/test'; +import {registerMerchant,createStockedVariant,openRegister,checkoutPayload,post} from './support'; +test('private receipt capabilities are scoped, redacted, idempotent and revocable',async({request})=>{ + const m=await registerMerchant(request,'Receipt Sharing');const v=await createStockedVariant(request,m,2),shift=await openRegister(request,m); + const body=checkoutPayload(shift,v),sale=await post<{data:{id:string}}>(request,'/checkout',body,m,201,body.idempotencyKey),path='/orders/'+sale.data.id+'/receipt-shares'; + type S={data:{id:string;token:string;expiresAt:number}}; + const shareBody={id:crypto.randomUUID(),kind:'gift'},a=await post(request,path,shareBody,m,200),b=await post(request,path,shareBody,m,200); + expect(a.data).toEqual(b.data); + const guest=await newRequest.newContext({baseURL:'http://127.0.0.1:8787'}); + try{ + const result=await guest.post('/api/v1/receipt-shares/redeem',{data:{token:a.data.token}});expect(result.status()).toBe(200); + const snapshot=(await result.json()).data;expect(snapshot.kind).toBe('gift');expect(snapshot.lines).toHaveLength(1); + expect(JSON.stringify(snapshot)).not.toMatch(/Minor|customer|cashier|reference|actorId|organizationId|variantId/); + const standard=await post(request,path,{id:crypto.randomUUID(),kind:'standard'},m,200); + const std=await guest.post('/api/v1/receipt-shares/redeem',{data:{token:standard.data.token}});expect(std.status()).toBe(200);expect((await std.json()).data.totalMinor).toBe(2500); + await post(request,path+'/revoke',{},m,200);expect((await guest.post('/api/v1/receipt-shares/redeem',{data:{token:a.data.token}})).status()).toBe(404); + }finally{await guest.dispose();} +}); diff --git a/apps/web/src/api/live.ts b/apps/web/src/api/live.ts index 470f5353..a969b90f 100644 --- a/apps/web/src/api/live.ts +++ b/apps/web/src/api/live.ts @@ -84,6 +84,12 @@ export async function fetchCheckoutQuote(body:CheckoutQuoteRequest,signal?:Abort return one('/api/v1/checkout/quote',{method:'POST',json:body,signal}); } +export const receiptShareApi={ + create:(orderId:string,body:{id:string;kind:'standard'|'gift'})=>one<{id:string;token:string;expiresAt:number}>('/api/v1/orders/'+encodeURIComponent(orderId)+'/receipt-shares',{method:'POST',json:body}), + revoke:(orderId:string)=>one<{revoked:number}>('/api/v1/orders/'+encodeURIComponent(orderId)+'/receipt-shares/revoke',{method:'POST',json:{}}), + email:(orderId:string,body:{shareId:string;email:string})=>one<{status:'accepted';alreadyAccepted:boolean}>('/api/v1/orders/'+encodeURIComponent(orderId)+'/receipt-shares/email',{method:'POST',json:body}), +}; + export const liveApi: Api = { mode: 'live', me: async () => adoptMe(await one('/api/v1/auth/me')), diff --git a/apps/web/src/features/register/Receipt.tsx b/apps/web/src/features/register/Receipt.tsx index 0a811703..5d5a9fad 100644 --- a/apps/web/src/features/register/Receipt.tsx +++ b/apps/web/src/features/register/Receipt.tsx @@ -8,6 +8,7 @@ import { useSession } from '../../state/session'; import { useLineLabels } from '../../lib/useLineLabels'; import { usePrefs } from '../../state/prefs'; import { printEscPosReceipt } from '../../lib/printer'; +import { ReceiptShareControls } from './SharedReceipt'; export type Paper = 'thermal' | 'a4'; const PAPER_KEY = 'storefront-paper'; @@ -116,6 +117,7 @@ export function ReceiptActions({ receipt, provisionalLabel }: { receipt: Receipt } catch { /* user cancelled share */ } }}>{typeof navigator.share === 'function' ? 'Share' : 'Copy text'} + {canShare&&!demo?:null} ); diff --git a/apps/web/src/features/register/SharedReceipt.tsx b/apps/web/src/features/register/SharedReceipt.tsx new file mode 100644 index 00000000..8b3c43e6 --- /dev/null +++ b/apps/web/src/features/register/SharedReceipt.tsx @@ -0,0 +1,23 @@ +import {useEffect,useRef,useState} from 'react'; +import {Banner,Button,Checkbox,Field,Input} from '@storefront/ui'; +import {receiptShareApi} from '../../api/live'; +import {formatMoney} from '../../lib/money'; +import {describeError} from '../../lib/errors'; +type Share={id:string;token:string;expiresAt:number}; +type Snapshot={kind:'standard'|'gift';number:string;merchant:string;store:string;createdAt:number;issuedAt:number;status:string;currency?:string;subtotalMinor?:number;discountMinor?:number;taxMinor?:number;roundingMinor?:number;totalMinor?:number;lines:Array<{name:string;quantity:number;returnedQuantity:number;unitPriceMinor?:number;totalMinor?:number}>}; +export function ReceiptShareControls({orderId,gift}:{orderId:string;gift:boolean}){ + const [open,setOpen]=useState(false),[share,setShare]=useState(null),[busy,setBusy]=useState(false),[email,setEmail]=useState(''),[consent,setConsent]=useState(false),[message,setMessage]=useState(''),[error,setError]=useState(''); + const key=useRef(crypto.randomUUID()),working=useRef(false); + async function perform(task:()=>Promise){if(working.current)return;working.current=true;setBusy(true);setError('');setMessage('');try{await task();}catch(e){setError(describeError(e).message);}finally{working.current=false;setBusy(false);}} + const link=share?new URL('/shared-receipt#'+share.token,window.location.origin).href:''; + return
{open?<>Share only with the intended recipient. Anyone holding the link can read it for seven days. No customer identity, cost or payment reference is included.{error?{error}:null}{message?:null} + {!share?:<>Expires {new Date(share.expiresAt*1000).toLocaleString()}{setEmail(e.target.value);setConsent(false);}} disabled={busy}/>setConsent(e.target.checked)} disabled={busy} label="Customer requested this receipt at this address"/>} + :null}
; +} +export function SharedReceiptScreen(){ + const [data,setData]=useState(null),[error,setError]=useState(''),[loading,setLoading]=useState(true); + useEffect(()=>{const token=window.location.hash.slice(1),controller=new AbortController();if(!/^[a-f0-9]{64}$/.test(token)){setError('This receipt link is invalid.');setLoading(false);return;} + void fetch('/api/v1/receipt-shares/redeem',{method:'POST',credentials:'omit',cache:'no-store',headers:{'Content-Type':'application/json'},body:JSON.stringify({token}),signal:controller.signal}).then(async r=>{if(!r.ok)throw Error('Receipt is unavailable, expired or revoked.');const json=await r.json() as {data:Snapshot};if(!controller.signal.aborted)setData(json.data);}).catch(e=>{if(!controller.signal.aborted)setError(e instanceof Error?e.message:'Receipt unavailable.');}).finally(()=>{if(!controller.signal.aborted)setLoading(false);});return()=>controller.abort();},[]); + const fmt=(n:number|undefined)=>formatMoney(n??0,data?.currency??'INR'); + return

{data?.kind==='gift'?'Gift receipt':'Shared receipt'}

{loading?

Loading receipt…

:error?

{error}

:data?

{data.merchant}

{data.store} · {data.number}

{new Date(data.createdAt*1000).toLocaleString()} · {data.status.replace('_',' ')}

    {data.lines.map((l,i)=>
  • {l.quantity} × {l.name}{l.returnedQuantity?' ('+l.returnedQuantity+' returned)':''}{data.kind==='standard'?{fmt(l.totalMinor)}:null}
  • )}
{data.kind==='standard'?<>

Subtotal: {fmt(data.subtotalMinor)} · Tax: {fmt(data.taxMinor)}

Discount: {fmt(data.discountMinor)} · Rounding: {fmt(data.roundingMinor)}

Total {fmt(data.totalMinor)}

:null}Snapshot issued {new Date(data.issuedAt*1000).toLocaleString()}. For later returns or an official tax invoice, contact the merchant.
:null}
; +} diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx index 2c554d08..5fe3bd0a 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -8,6 +8,7 @@ import './app.css'; import './polish.css'; import { App } from './App'; import { CustomerDisplayScreen } from './features/register/CustomerDisplay'; +import { SharedReceiptScreen } from './features/register/SharedReceipt'; import { SessionProvider } from './state/session'; import { StorefrontApiError } from './lib/api'; import { applyTheme, usePrefs } from './state/prefs'; @@ -28,8 +29,9 @@ window.matchMedia?.('(prefers-color-scheme: dark)').addEventListener('change', ( const node = document.getElementById('root'); if (!node) throw new Error('Missing application root'); const displayOnly=window.location.pathname==='/customer-display'; +const receiptOnly=window.location.pathname==='/shared-receipt'; createRoot(node).render( - displayOnly ? : + receiptOnly ? : displayOnly ? : @@ -43,4 +45,4 @@ createRoot(node).render( , ); -if(!displayOnly)registerServiceWorker(); +if(!displayOnly&&!receiptOnly)registerServiceWorker(); diff --git a/docs/operations/register-m6-private-receipt-links.md b/docs/operations/register-m6-private-receipt-links.md new file mode 100644 index 00000000..84fe1446 --- /dev/null +++ b/docs/operations/register-m6-private-receipt-links.md @@ -0,0 +1,5 @@ +# M6.2 — Private receipt capabilities and explicit email delivery + +Customer-requested receipt links are seven-day bearer capabilities stored by hash, with immutable allowlisted snapshots. Gift links omit all monetary data. Standard links omit customer identifiers, costs, payment references and operator data. Tokens travel in URL fragments and are redeemed through a no-store POST without merchant authentication. Revoke all links from the original order. Cashiers may share only their own orders. No demo or provisional sales can create live links. + +Email delivery requires explicit customer request and configured Resend credentials. A durable per-link/recipient delivery record retains the same provider idempotency key. Acceptance is not delivery; ambiguous attempts are retriable only within a conservative 23-hour window (Resend guarantees key retention for 24 hours). No recipient plaintext is persisted. Provider tests and protected migration/physical staging acceptance are required; do not enable live sending until acceptance. Migration 0048 is deliberately outside the outstanding Phase N inventory migration range. diff --git a/tests/route-policy.mjs b/tests/route-policy.mjs index 319dadd6..a1a23a70 100644 --- a/tests/route-policy.mjs +++ b/tests/route-policy.mjs @@ -9,7 +9,7 @@ export const routePolicy=Object.fromEntries(Object.entries({ public:[ 'POST /auth/register','POST /auth/login','POST /auth/verification/resend', 'POST /auth/verify-email','POST /auth/forgot-password','POST /auth/reset-password', - 'POST /auth/invitations/accept','POST /webhooks/woocommerce/:connectionId' + 'POST /auth/invitations/accept','POST /webhooks/woocommerce/:connectionId','POST /receipt-shares/redeem' ], session:[ 'GET /auth/me','POST /auth/logout','POST /auth/select-organization', @@ -33,7 +33,7 @@ export const routePolicy=Object.fromEntries(Object.entries({ 'POST /inventory/adjustments','POST /inventory/revalue','PATCH /inventory/threshold','POST /inventory/transfers','POST /inventory/transfers/:id/receive', 'POST /suppliers','PATCH /suppliers/:id','POST /purchase-orders','POST /purchase-orders/:id/receive' ], - 'sales:create':['POST /checkout','POST /checkout/quote','GET /customers','POST /customers','GET /customers/:id'], + 'sales:create':['POST /checkout','POST /checkout/quote','POST /orders/:id/receipt-shares','POST /orders/:id/receipt-shares/revoke','POST /orders/:id/receipt-shares/email','GET /customers','POST /customers','GET /customers/:id'], 'sales:read':['PATCH /customers/:id','GET /orders','GET /orders/:id','GET /orders/:id/receipt'], 'sales:refund':['POST /orders/:id/returns','POST /offline-recovery/reviews'], 'register:open':['GET /register-sessions','POST /register-sessions/open','GET /register-sessions/active','POST /register-sessions/:id/drawer-open'], diff --git a/tests/verify-route-policy.mjs b/tests/verify-route-policy.mjs index 4c65bae6..ce8e4e71 100644 --- a/tests/verify-route-policy.mjs +++ b/tests/verify-route-policy.mjs @@ -3,11 +3,11 @@ import {fileURLToPath} from 'node:url'; import {dirname,join} from 'node:path'; import {routePolicy} from './route-policy.mjs'; const root=join(dirname(fileURLToPath(import.meta.url)),'..'); -const modules=['auth','catalog','sales','purchasing','woocommerce','media','billing','offline-recovery']; +const modules=['auth','catalog','sales','purchasing','woocommerce','media','billing','offline-recovery','receipt-shares']; const declared=new Set(); for(const file of modules){ const source=readFileSync(join(root,'apps/api/src',file+'.ts'),'utf8'); - const regex=/\b(?:auth|catalog|sales|purchasing|woo|webhook|media|billing|recovery)\.(get|post|patch|put|delete)\('([^']+)'/g; + const regex=/\b(?:auth|catalog|sales|purchasing|woo|webhook|media|billing|recovery|receiptShares|publicReceipts)\.(get|post|patch|put|delete)\('([^']+)'/g; const routes=[...source.matchAll(regex)]; for(const [i,match] of routes.entries()){ const key=match[1].toUpperCase()+' '+match[2]; From e725567b1dc71053e7cae7b541eef334fea64105 Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Sun, 6 Dec 2026 00:10:32 -0500 Subject: [PATCH 02/10] feat(display): authenticated remote pairing and verified sale presentation --- .github/workflows/worker-e2e.yml | 2 +- apps/api/migrations/0050_remote_display.sql | 7 +++ apps/api/src/display-pairs.ts | 61 +++++++++++++++++++ apps/api/src/index.ts | 3 + apps/web/e2e-worker/display-pairs.spec.ts | 18 ++++++ apps/web/src/api/live.ts | 5 ++ .../src/features/register/CustomerDisplay.tsx | 24 +++++--- apps/web/src/features/register/PayDialog.tsx | 6 +- apps/web/src/features/register/Register.tsx | 5 +- .../src/features/register/RemoteDisplay.tsx | 16 +++++ .../src/features/register/display-model.ts | 4 +- docs/operations/register-m5-remote-display.md | 3 + tests/route-policy.mjs | 4 +- tests/verify-route-policy.mjs | 4 +- 14 files changed, 144 insertions(+), 18 deletions(-) create mode 100644 apps/api/migrations/0050_remote_display.sql create mode 100644 apps/api/src/display-pairs.ts create mode 100644 apps/web/e2e-worker/display-pairs.spec.ts create mode 100644 apps/web/src/features/register/RemoteDisplay.tsx create mode 100644 docs/operations/register-m5-remote-display.md diff --git a/.github/workflows/worker-e2e.yml b/.github/workflows/worker-e2e.yml index 54cc9796..feed4ec5 100644 --- a/.github/workflows/worker-e2e.yml +++ b/.github/workflows/worker-e2e.yml @@ -16,7 +16,7 @@ jobs: strategy: fail-fast: false matrix: - suite: [merchant, contracts, recovery, integrity, roles, transfers, auth, money, woo, offline, cash-integrity, ops-load, catalog-import, register-catalog] + suite: [merchant, contracts, recovery, integrity, roles, transfers, auth, money, woo, offline, cash-integrity, ops-load, catalog-import, register-catalog, display-pairs] timeout-minutes: 20 steps: - uses: actions/checkout@v4 diff --git a/apps/api/migrations/0050_remote_display.sql b/apps/api/migrations/0050_remote_display.sql new file mode 100644 index 00000000..dc287552 --- /dev/null +++ b/apps/api/migrations/0050_remote_display.sql @@ -0,0 +1,7 @@ +CREATE TABLE display_pairs ( + id TEXT PRIMARY KEY, organization_id TEXT NOT NULL REFERENCES organizations(id), shift_id TEXT NOT NULL REFERENCES register_sessions(id), + actor_id TEXT NOT NULL REFERENCES users(id), auth_session_id TEXT NOT NULL REFERENCES auth_sessions(id), + token_hash TEXT NOT NULL UNIQUE, snapshot_json TEXT, updated_at INTEGER, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, revoked_at INTEGER +); +CREATE INDEX display_pairs_scope_idx ON display_pairs(organization_id,shift_id,actor_id,expires_at); +CREATE INDEX display_pairs_expiry_idx ON display_pairs(expires_at); diff --git a/apps/api/src/display-pairs.ts b/apps/api/src/display-pairs.ts new file mode 100644 index 00000000..57d14ab1 --- /dev/null +++ b/apps/api/src/display-pairs.ts @@ -0,0 +1,61 @@ +import {Hono} from 'hono'; +import {z} from 'zod'; +import type {AppEnv} from './types'; +import {apiId,asData,fail,jsonBody,now,parseBody,requirePermission} from './types'; +import {sha256,throttle} from './security'; +export const displayPairs=new Hono(); +export const publicDisplays=new Hono(); +const uuid=z.string().uuid(); +const idle={v:1,kind:'snapshot',demo:false,active:false,items:[],total:''}; +displayPairs.post('/display-pairs',async c=>{ + const p=requirePermission(c,'register:open'),body=parseBody(await jsonBody(c),z.object({shiftId:uuid})); + const shift=await c.env.DB.prepare('SELECT id FROM register_sessions WHERE id=? AND organization_id=? AND closed_at IS NULL').bind(body.shiftId,p.organizationId).first(); + if(!shift)fail('NOT_FOUND','Open shift not found.',404); + await throttle(c,'display-pair-create',p.organizationId+':'+p.userId,20); + const token=Array.from(crypto.getRandomValues(new Uint8Array(32)),v=>v.toString(16).padStart(2,'0')).join(''),id=apiId(),created=now(),expiresAt=created+7200; + await c.env.DB.batch([ + c.env.DB.prepare('DELETE FROM display_pairs WHERE organization_id=? AND expires_at{ + const p=requirePermission(c,'register:open'),id=c.req.param('id'),body=parseBody(await jsonBody(c),publishSchema); + const row=await c.env.DB.prepare(`SELECT d.shift_id AS shiftId FROM display_pairs d JOIN register_sessions s ON s.id=d.shift_id AND s.organization_id=d.organization_id + WHERE d.id=? AND d.organization_id=? AND d.actor_id=? AND d.auth_session_id=? AND d.revoked_at IS NULL AND d.expires_at>? AND s.closed_at IS NULL`).bind(id,p.organizationId,p.userId,p.sessionId,now()).first<{shiftId:string}>(); + if(!row)fail('NOT_FOUND','Pairing expired or revoked.',404); + let snapshot:unknown=idle; + if(body.state==='cart')snapshot={v:1,kind:'snapshot',demo:false,active:true,items:body.items,total:body.total}; + if(body.state==='confirmed'){ + const order=await c.env.DB.prepare("SELECT total_minor AS totalMinor,currency FROM orders WHERE id=? AND organization_id=? AND register_session_id=? AND cashier_id=? AND status='completed'").bind(body.orderId,p.organizationId,row!.shiftId,p.userId).first<{totalMinor:number;currency:string}>(); + if(!order)fail('NOT_FOUND','Confirmed sale not found for this register operator.',404); + const fmt=new Intl.NumberFormat('en',{style:'currency',currency:order!.currency}); + snapshot={v:1,kind:'confirmed',demo:false,total:fmt.format(order!.totalMinor/10**(fmt.resolvedOptions().maximumFractionDigits??2))}; + } + const result=await c.env.DB.prepare(`UPDATE display_pairs SET snapshot_json=?,updated_at=? WHERE id=? AND organization_id=? AND actor_id=? AND auth_session_id=? AND revoked_at IS NULL AND expires_at>? + AND EXISTS(SELECT 1 FROM register_sessions s WHERE s.id=display_pairs.shift_id AND s.organization_id=display_pairs.organization_id AND s.closed_at IS NULL)`).bind(JSON.stringify(snapshot),now(),id,p.organizationId,p.userId,p.sessionId,now()).run(); + if(!result.meta.changes)fail('NOT_FOUND','Pairing ended.',404); + return c.json(asData({updated:true})); +}); +displayPairs.post('/display-pairs/:id/revoke',async c=>{ + const p=requirePermission(c,'register:open'); + await c.env.DB.prepare('UPDATE display_pairs SET revoked_at=?,snapshot_json=NULL WHERE id=? AND organization_id=? AND actor_id=? AND auth_session_id=? AND revoked_at IS NULL').bind(now(),c.req.param('id'),p.organizationId,p.userId,p.sessionId).run(); + return c.json(asData({revoked:true})); +}); +publicDisplays.post('/display-pairs/view',async c=>{ + const body=parseBody(await jsonBody(c),z.object({token:z.string().regex(/^[a-f0-9]{64}$/)})); + const row=await c.env.DB.prepare(`SELECT d.snapshot_json AS snapshotJson,d.updated_at AS updatedAt FROM display_pairs d + JOIN register_sessions s ON s.id=d.shift_id AND s.organization_id=d.organization_id + JOIN auth_sessions a ON a.id=d.auth_session_id AND a.organization_id=d.organization_id AND a.user_id=d.actor_id + JOIN memberships m ON m.organization_id=d.organization_id AND m.user_id=d.actor_id + WHERE d.token_hash=? AND d.expires_at>? AND d.revoked_at IS NULL AND s.closed_at IS NULL AND a.revoked_at IS NULL AND a.expires_at>? AND m.status='active' AND m.role IN ('owner','manager','cashier')`).bind(await sha256(body.token),now(),now()).first<{snapshotJson:string|null;updatedAt:number|null}>(); + if(!row)fail('NOT_FOUND','Display pairing unavailable.',404); + c.header('X-Robots-Tag','noindex, nofollow, noarchive'); + return c.json(asData(row!.snapshotJson&&row!.updatedAt&&now()-row!.updatedAt<12?JSON.parse(row!.snapshotJson):idle)); +}); diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index 87f4d445..c2e261ef 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -9,6 +9,7 @@ import billing from './billing'; import media from './media'; import purchasing from './purchasing'; import offlineRecovery from './offline-recovery'; +import {displayPairs,publicDisplays} from './display-pairs'; import {sweepWoo} from './woo-runner'; const app = new Hono(); @@ -33,6 +34,7 @@ app.get('/api/v1/meta',c=>c.json({data:{service:'storefront',version:'0.2.0',sta app.route('/api/v1',auth); app.route('/api/v1',webhook); +app.route('/api/v1',publicDisplays); // Protect catalog and commerce routes independently, even if auth module changes. const commerce=new Hono(); commerce.use('*',authenticated); @@ -43,6 +45,7 @@ commerce.route('/',billing); commerce.route('/',media); commerce.route('/',purchasing); commerce.route('/',offlineRecovery); +commerce.route('/',displayPairs); app.route('/api/v1',commerce); app.onError((error,c)=>{ diff --git a/apps/web/e2e-worker/display-pairs.spec.ts b/apps/web/e2e-worker/display-pairs.spec.ts new file mode 100644 index 00000000..1b5f0345 --- /dev/null +++ b/apps/web/e2e-worker/display-pairs.spec.ts @@ -0,0 +1,18 @@ +import {expect,test,request as newRequest} from '@playwright/test'; +import {registerMerchant,createStockedVariant,openRegister,checkoutPayload,post} from './support'; +test('remote display shares only scoped snapshots and verified sale totals; revoke blanks viewer',async({request})=>{ + const m=await registerMerchant(request,'Display Pair'),v=await createStockedVariant(request,m,2),shift=await openRegister(request,m); + const pair=await post<{data:{id:string;token:string}}>(request,'/display-pairs',{shiftId:shift},m,201),path='/display-pairs/'+pair.data.id; + const guest=await newRequest.newContext({baseURL:'http://localhost:8787'}); + try{ + const read=()=>guest.post('/api/v1/display-pairs/view',{data:{token:pair.data.token}}); + expect((await (await read()).json()).data.active).toBe(false); + await post(request,path+'/publish',{state:'cart',items:[{name:'Item',quantity:2,customerName:'PRIVATE'}],total:'INR 50.00',reference:'PRIVATE'},m,200); + const cart=(await (await read()).json()).data;expect(cart.items).toEqual([{name:'Item',quantity:2}]);expect(JSON.stringify(cart)).not.toContain('PRIVATE'); + await post(request,path+'/publish',{state:'confirmed',orderId:crypto.randomUUID()},m,404); + const body=checkoutPayload(shift,v),sale=await post<{data:{id:string}}>(request,'/checkout',body,m,201,body.idempotencyKey); + await post(request,path+'/publish',{state:'confirmed',orderId:sale.data.id,total:'FAKE'},m,200); + const confirmed=(await (await read()).json()).data;expect(confirmed.kind).toBe('confirmed');expect(confirmed.total).not.toContain('FAKE'); + await post(request,path+'/revoke',{},m,200);expect((await read()).status()).toBe(404); + }finally{await guest.dispose();} +}); diff --git a/apps/web/src/api/live.ts b/apps/web/src/api/live.ts index 562bc2ff..3ad64796 100644 --- a/apps/web/src/api/live.ts +++ b/apps/web/src/api/live.ts @@ -84,6 +84,11 @@ export async function fetchCheckoutQuote(body:CheckoutQuoteRequest,signal?:Abort return one('/api/v1/checkout/quote',{method:'POST',json:body,signal}); } +export const remoteDisplayApi={ + create:(shiftId:string)=>one<{id:string;token:string;expiresAt:number}>('/api/v1/display-pairs',{method:'POST',json:{shiftId}}), + publish:(id:string,body:unknown)=>one<{updated:boolean}>('/api/v1/display-pairs/'+encodeURIComponent(id)+'/publish',{method:'POST',json:body}), + revoke:(id:string)=>one<{revoked:boolean}>('/api/v1/display-pairs/'+encodeURIComponent(id)+'/revoke',{method:'POST',json:{}}), +}; export const liveApi: Api = { mode: 'live', me: async () => adoptMe(await one('/api/v1/auth/me')), diff --git a/apps/web/src/features/register/CustomerDisplay.tsx b/apps/web/src/features/register/CustomerDisplay.tsx index 1d5be33d..b065922c 100644 --- a/apps/web/src/features/register/CustomerDisplay.tsx +++ b/apps/web/src/features/register/CustomerDisplay.tsx @@ -1,18 +1,19 @@ import {useEffect,useRef,useState} from 'react'; import {Monitor} from 'lucide-react'; import {Button,useToast} from '@storefront/ui'; -import {displayChannel,displaySnapshot,parseDisplayMessage,type DisplaySnapshot} from './display-model'; +import {displayChannel,displaySnapshot,parseDisplayMessage,type DisplayMessage} from './display-model'; +import {RemoteDisplayControl} from './RemoteDisplay'; import './customer-display.css'; type Connection={channel:BroadcastChannel;popup:Window;timer:number}; function disconnect(c:Connection){window.clearInterval(c.timer);try{c.channel.postMessage({v:1,kind:'end'});}catch{}c.channel.close();try{c.popup.close();}catch{}} /** Local second monitor only. No tenant API, session tokens, customer identity or payment data are transmitted. */ -export function CustomerDisplayControl({active,lines,total,demo}:{active:boolean;lines:readonly {name:string;quantity:number}[];total:string;demo:boolean}){ +export function CustomerDisplayControl({active,lines,total,demo,shiftId,confirmed}:{active:boolean;lines:readonly {name:string;quantity:number}[];total:string;demo:boolean;shiftId?:string;confirmed?:{orderId:string;total:string}|null}){ const toast=useToast();const connection=useRef(null);const [connected,setConnected]=useState(false); - const latest=useRef(displaySnapshot(active,lines,total,demo));latest.current=displaySnapshot(active,lines,total,demo); + const latest=useRef(displaySnapshot(active,lines,total,demo));latest.current=confirmed?{v:1,kind:'confirmed',demo,total:confirmed.total}:displaySnapshot(active,lines,total,demo); function stop(){if(connection.current)disconnect(connection.current);connection.current=null;setConnected(false);} useEffect(()=>()=>{if(connection.current)disconnect(connection.current);connection.current=null;},[]); - useEffect(()=>{try{connection.current?.channel.postMessage(latest.current);}catch{}},[active,lines,total,demo]); + useEffect(()=>{try{connection.current?.channel.postMessage(latest.current);}catch{}},[active,lines,total,demo,confirmed]); function open(){ if(connection.current)return; if(typeof BroadcastChannel==='undefined'||!window.isSecureContext){toast.show('Customer display needs a supported browser in a secure context.','danger');return;} @@ -28,17 +29,24 @@ export function CustomerDisplayControl({active,lines,total,demo}:{active:boolean },750); connection.current={channel,popup,timer};setConnected(true); } - return ; + return <>{!demo&&shiftId?:null}; } export function CustomerDisplayScreen(){ - const [snapshot,setSnapshot]=useState(null); + const [snapshot,setSnapshot]=useState|null>(null); useEffect(()=>{ - const name=displayChannel(window.location.hash.slice(1));if(!name||typeof BroadcastChannel==='undefined')return; + const hash=window.location.hash.slice(1); + if(/^remote\.[a-f0-9]{64}$/.test(hash)){ + let live=true,busy=false;let controller:AbortController|null=null; + const poll=async()=>{if(busy||!live)return;busy=true;controller=new AbortController();const timeout=window.setTimeout(()=>controller?.abort(),4000); + try{const r=await fetch('/api/v1/display-pairs/view',{method:'POST',credentials:'omit',cache:'no-store',headers:{'Content-Type':'application/json'},body:JSON.stringify({token:hash.slice(7)}),signal:controller.signal});if(!r.ok)throw Error('Display unavailable');const m=parseDisplayMessage((await r.json()).data);if(live)setSnapshot(m&&m.kind!=='end'?m:null);}catch{if(live)setSnapshot(null);}finally{window.clearTimeout(timeout);busy=false;}}; + void poll();const timer=window.setInterval(()=>void poll(),2000);return()=>{live=false;controller?.abort();window.clearInterval(timer);}; + } + const name=displayChannel(hash);if(!name||typeof BroadcastChannel==='undefined')return; const channel=new BroadcastChannel(name);let last=0; channel.onmessage=e=>{const m=parseDisplayMessage(e.data);if(!m)return;if(m.kind==='end'){last=0;setSnapshot(null);channel.close();return;}last=Date.now();setSnapshot(m);}; const timer=window.setInterval(()=>{if(Date.now()-last>5000)setSnapshot(null);},1000); return ()=>{window.clearInterval(timer);channel.close();}; },[]); return
STOREFRONT

Customer display

{snapshot?.demo?

DEMO — sample data only

:null}
- {snapshot?.active?
    {snapshot.items.map((item,i)=>
  • {item.name}{item.quantity} ×
  • )}
Estimated total{snapshot.total}Final amount confirmed at checkout.
:

{snapshot?'Please follow the cashier’s instructions.':'Waiting for the register connection.'}

}
; + {snapshot?.kind==='confirmed'?
Payment recorded{snapshot.total}Thank you for shopping with us.
:snapshot?.kind==='snapshot'&&snapshot.active?
    {snapshot.items.map((item,i)=>
  • {item.name}{item.quantity} ×
  • )}
Estimated total{snapshot.total}Final amount confirmed at checkout.
:

{snapshot?'Please follow the cashier’s instructions.':'Waiting for the register connection.'}

}; } diff --git a/apps/web/src/features/register/PayDialog.tsx b/apps/web/src/features/register/PayDialog.tsx index c70d323c..a0290707 100644 --- a/apps/web/src/features/register/PayDialog.tsx +++ b/apps/web/src/features/register/PayDialog.tsx @@ -43,9 +43,9 @@ export function cashSuggestions(totalMinor: number, currency: string, locale: st type SplitDraft = { id: string; method: TenderMethod; amountText: string; reference: string }; -export function PayDialog({ open, onClose, cart, scope, sessionId, onFinished, onSessionClosed, onStockConflict }: { +export function PayDialog({ open, onClose, cart, scope, sessionId, onFinished, onSessionClosed, onStockConflict, onConfirmed }: { open: boolean; onClose: () => void; cart: CartState; scope: Required; sessionId: string; - onFinished: () => void; onSessionClosed: () => void; onStockConflict: (details: unknown) => void; + onConfirmed?: (receipt:Receipt)=>void; onFinished: () => void; onSessionClosed: () => void; onStockConflict: (details: unknown) => void; }) { const { api, me, mode, accountId, organizationId, offlineSession } = useSession(); const browserOnline = useConnectivity((s) => s.browserOnline); @@ -238,6 +238,7 @@ export function PayDialog({ open, onClose, cart, scope, sessionId, onFinished, o if (res.kind === 'confirmed') { setReceipt(res.receipt); setPhase('receipt'); + onConfirmed?.(res.receipt); void qc.invalidateQueries({ queryKey: ['inventory'] }); void qc.invalidateQueries({ queryKey: ['orders'] }); void qc.invalidateQueries({ queryKey: ['report'] }); @@ -285,6 +286,7 @@ export function PayDialog({ open, onClose, cart, scope, sessionId, onFinished, o if (res.outcome === 'confirmed') { setReceipt(res.receipt); setPhase('receipt'); + onConfirmed?.(res.receipt); void qc.invalidateQueries({ queryKey: ['inventory'] }); void qc.invalidateQueries({ queryKey: ['orders'] }); } else if (res.outcome === 'busy') { diff --git a/apps/web/src/features/register/Register.tsx b/apps/web/src/features/register/Register.tsx index 3ed6be1e..28a516fc 100644 --- a/apps/web/src/features/register/Register.tsx +++ b/apps/web/src/features/register/Register.tsx @@ -217,6 +217,7 @@ function RegisterWorkspace() { const [locked, setLocked] = useState(false); const [cartOpen, setCartOpen] = useState(false); const [receipt, setReceipt] = useState(null); + const [displaySale,setDisplaySale]=useState<{orderId:string;total:string}|null>(null); const [stockConflict, setStockConflict] = useState(null); const modalBusy=draftMoving||payOpen||clearOpen||closeOpen||cashOpen||drawerOpen||reportSessionId!==null||historyOpen||locked||heldOpen||receipt!==null||stockConflict!==null; const nextScope=ready&&session&&!modalBusy?key:null; @@ -271,7 +272,7 @@ function RegisterWorkspace() { onKeyDown={(e) => { if (e.key === 'Enter'&&!e.nativeEvent.isComposing&&!e.repeat) { e.preventDefault(); if (search.trim()) void handleCode(search, scanOnly?undefined:uniqueNameMatch(onlyFavorites ? catalog.filter(item=>favorites.ids.includes(item.variantId)) : category ? catalog.filter(item => item.categoryId === category) : catalog, search)); } if (e.key === 'Escape') {setSearch('');setScanOnly(false);} }} /> - + {can('sales:refund') ? Returns : null} @@ -334,7 +335,7 @@ function RegisterWorkspace() { - {scope ? setPayOpen(false)} cart={cart} scope={scope} sessionId={session.id} + {scope ? {setDisplaySale(null);setPayOpen(false);}} cart={cart} scope={scope} sessionId={session.id} onConfirmed={r=>{if(mounted.current&&useCart.getState().scopeKey===key)setDisplaySale({orderId:r.order.id,total:fmt(r.order.totalMinor)});}} onFinished={() => { if(!mounted.current||useCart.getState().scopeKey!==key)return;cart.clear(); void deleteCurrentCart(scope).catch(()=>toast.show('Completed sale recorded; local cart cleanup failed. Do not reload until storage is available.','danger')); setCartOpen(false); setSearch(''); window.setTimeout(() => searchRef.current?.focus(), 50); }} onSessionClosed={() => { void qc.invalidateQueries({ queryKey: ['session', validRegisterId] }); setPayOpen(false); toast.show('This shift was closed. Open a new shift to keep selling — your cart is saved.', 'danger'); }} onStockConflict={(d) => { setStockConflict(d ?? []); void qc.invalidateQueries({ queryKey: ['inventory'] }); }} /> : null} diff --git a/apps/web/src/features/register/RemoteDisplay.tsx b/apps/web/src/features/register/RemoteDisplay.tsx new file mode 100644 index 00000000..8adff93c --- /dev/null +++ b/apps/web/src/features/register/RemoteDisplay.tsx @@ -0,0 +1,16 @@ +import {useEffect,useRef,useState} from 'react'; +import {Banner,Button,Dialog,Field,Input} from '@storefront/ui'; +import {remoteDisplayApi} from '../../api/live'; +import {describeError} from '../../lib/errors'; +type Pair={id:string;token:string;expiresAt:number}; +export function RemoteDisplayControl({shiftId,active,lines,total,confirmed}:{shiftId:string;active:boolean;lines:readonly {name:string;quantity:number}[];total:string;confirmed?:{orderId:string;total:string}|null}){ + const [pair,setPair]=useState(null),[open,setOpen]=useState(false),[error,setError]=useState(''),[busy,setBusy]=useState(false),[copied,setCopied]=useState(false); + const current=useRef(null),creating=useRef(false),mounted=useRef(false); + const latest=useRef(null);latest.current=confirmed?{state:'confirmed',orderId:confirmed.orderId}:active?{state:'cart',items:lines.slice(0,50).map(l=>({name:l.name.slice(0,180),quantity:l.quantity})),total:total.slice(0,80)}:{state:'idle'}; + useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;const old=current.current;current.current=null;if(old)void remoteDisplayApi.revoke(old.id).catch(()=>undefined);};},[]); + useEffect(()=>{if(!pair)return;let alive=true,sending=false;const tick=async()=>{if(!alive||sending)return;if(Date.now()>=pair.expiresAt*1000){setPair(null);current.current=null;return;}sending=true;try{await remoteDisplayApi.publish(pair.id,latest.current);if(alive)setError('');}catch(e){if(alive)setError(describeError(e).message);}finally{sending=false;}};void tick();const timer=window.setInterval(()=>void tick(),3000);return()=>{alive=false;window.clearInterval(timer);};},[pair]); + async function create(){if(creating.current)return;creating.current=true;setBusy(true);setError('');try{const p=await remoteDisplayApi.create(shiftId);if(!mounted.current){void remoteDisplayApi.revoke(p.id).catch(()=>undefined);return;}current.current=p;setPair(p);}catch(e){setError(describeError(e).message);}finally{creating.current=false;setBusy(false);}} + async function stop(){if(!pair)return;setBusy(true);try{await remoteDisplayApi.revoke(pair.id);current.current=null;setPair(null);setError('');}catch(e){setError(describeError(e).message);}finally{setBusy(false);}} + const url=pair?new URL('/customer-display#remote.'+pair.token,window.location.origin).href:''; + return <>setOpen(false)} title="Remote customer display" footer={}>

Open this private two-hour pairing link on a separate customer-facing tablet or screen. Only item names, quantities and totals are shared. Disconnect to revoke the link.

{error?{error} The display blanks when updates stop.:null}{pair?<>:}
; +} diff --git a/apps/web/src/features/register/display-model.ts b/apps/web/src/features/register/display-model.ts index a41f1772..39106792 100644 --- a/apps/web/src/features/register/display-model.ts +++ b/apps/web/src/features/register/display-model.ts @@ -1,5 +1,6 @@ export type DisplaySnapshot={v:1;kind:'snapshot';demo:boolean;active:boolean;items:{name:string;quantity:number}[];total:string}; -export type DisplayMessage=DisplaySnapshot|{v:1;kind:'end'}; +export type DisplayConfirmed={v:1;kind:'confirmed';demo:boolean;total:string}; +export type DisplayMessage=DisplaySnapshot|DisplayConfirmed|{v:1;kind:'end'}; const tokenPattern=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; export function displayChannel(token:string){return tokenPattern.test(token)?'storefront-display-v1:'+token:null;} export function displaySnapshot(active:boolean,lines:readonly {name:string;quantity:number}[],total:string,demo:boolean):DisplaySnapshot{ @@ -9,6 +10,7 @@ export function parseDisplayMessage(value:unknown):DisplayMessage|null{ if(!value||typeof value!=='object')return null; const m=value as Partial&{kind?:string}; if(m.v!==1)return null; + if((value as {kind?:string}).kind==='confirmed')return typeof m.demo==='boolean'&&typeof m.total==='string'&&m.total.length<=80?{v:1,kind:'confirmed',demo:m.demo,total:m.total}:null; if((value as {kind?:string}).kind==='end')return {v:1,kind:'end'}; if(m.kind!=='snapshot'||typeof m.demo!=='boolean'||typeof m.active!=='boolean'||typeof m.total!=='string'||m.total.length>80||!Array.isArray(m.items)||m.items.length>50)return null; if(m.items.some(l=>!l||typeof l.name!=='string'||l.name.length>180||!Number.isSafeInteger(l.quantity)||l.quantity<1||l.quantity>100000))return null; diff --git a/docs/operations/register-m5-remote-display.md b/docs/operations/register-m5-remote-display.md new file mode 100644 index 00000000..4224d05e --- /dev/null +++ b/docs/operations/register-m5-remote-display.md @@ -0,0 +1,3 @@ +# M5.2 — remote customer display + +Two-hour revocable bearer pairings support a separate screen or tablet. Register publish requires the original authenticated operator, auth session, active shift and organization. The display endpoint exposes only a whitelisted cart estimate or an authoritative completed-order total. It never exposes customer details, payment references, session credentials or internal IDs. Invalidated shifts, expired auth sessions, revoked pairings and stale heartbeats blank the viewer. Local BroadcastChannel display remains available without network. Physical device pairing and load acceptance remain mandatory. Migration 0050 uses a distinct range from the outstanding inventory PRs. diff --git a/tests/route-policy.mjs b/tests/route-policy.mjs index 319dadd6..24744b78 100644 --- a/tests/route-policy.mjs +++ b/tests/route-policy.mjs @@ -9,7 +9,7 @@ export const routePolicy=Object.fromEntries(Object.entries({ public:[ 'POST /auth/register','POST /auth/login','POST /auth/verification/resend', 'POST /auth/verify-email','POST /auth/forgot-password','POST /auth/reset-password', - 'POST /auth/invitations/accept','POST /webhooks/woocommerce/:connectionId' + 'POST /auth/invitations/accept','POST /webhooks/woocommerce/:connectionId','POST /display-pairs/view' ], session:[ 'GET /auth/me','POST /auth/logout','POST /auth/select-organization', @@ -36,7 +36,7 @@ export const routePolicy=Object.fromEntries(Object.entries({ 'sales:create':['POST /checkout','POST /checkout/quote','GET /customers','POST /customers','GET /customers/:id'], 'sales:read':['PATCH /customers/:id','GET /orders','GET /orders/:id','GET /orders/:id/receipt'], 'sales:refund':['POST /orders/:id/returns','POST /offline-recovery/reviews'], - 'register:open':['GET /register-sessions','POST /register-sessions/open','GET /register-sessions/active','POST /register-sessions/:id/drawer-open'], + 'register:open':['GET /register-sessions','POST /register-sessions/open','GET /register-sessions/active','POST /register-sessions/:id/drawer-open','POST /display-pairs','POST /display-pairs/:id/publish','POST /display-pairs/:id/revoke'], 'register:close':[ 'GET /register-sessions/:id/summary','GET /register-sessions/:id/cash-movements','POST /register-sessions/:id/cash-movements', 'POST /register-sessions/:id/close' diff --git a/tests/verify-route-policy.mjs b/tests/verify-route-policy.mjs index 4c65bae6..b15610ae 100644 --- a/tests/verify-route-policy.mjs +++ b/tests/verify-route-policy.mjs @@ -3,11 +3,11 @@ import {fileURLToPath} from 'node:url'; import {dirname,join} from 'node:path'; import {routePolicy} from './route-policy.mjs'; const root=join(dirname(fileURLToPath(import.meta.url)),'..'); -const modules=['auth','catalog','sales','purchasing','woocommerce','media','billing','offline-recovery']; +const modules=['auth','catalog','sales','purchasing','woocommerce','media','billing','offline-recovery','display-pairs']; const declared=new Set(); for(const file of modules){ const source=readFileSync(join(root,'apps/api/src',file+'.ts'),'utf8'); - const regex=/\b(?:auth|catalog|sales|purchasing|woo|webhook|media|billing|recovery)\.(get|post|patch|put|delete)\('([^']+)'/g; + const regex=/\b(?:auth|catalog|sales|purchasing|woo|webhook|media|billing|recovery|displayPairs|publicDisplays)\.(get|post|patch|put|delete)\('([^']+)'/g; const routes=[...source.matchAll(regex)]; for(const [i,match] of routes.entries()){ const key=match[1].toUpperCase()+' '+match[2]; From da2314c64919bb46877056e193292d2e1f4dff64 Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Sun, 6 Dec 2026 00:17:43 -0500 Subject: [PATCH 03/10] fix(receipts): resume active link across reload and verify complete migration suffix --- apps/api/migrations/0038_receipt_shares.sql | 1 + apps/api/src/receipt-shares.ts | 9 +++++++-- apps/web/e2e-worker/receipt-shares.spec.ts | 1 + apps/web/src/features/register/SharedReceipt.tsx | 2 +- tests/staging-l1.test.mjs | 11 +++++++---- 5 files changed, 17 insertions(+), 7 deletions(-) diff --git a/apps/api/migrations/0038_receipt_shares.sql b/apps/api/migrations/0038_receipt_shares.sql index f6e8847f..cf03bce4 100644 --- a/apps/api/migrations/0038_receipt_shares.sql +++ b/apps/api/migrations/0038_receipt_shares.sql @@ -4,6 +4,7 @@ CREATE TABLE receipt_shares ( actor_id TEXT NOT NULL REFERENCES users(id), token_hash TEXT NOT NULL UNIQUE, kind TEXT NOT NULL CHECK(kind IN ('standard','gift')), snapshot_json TEXT NOT NULL, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, revoked_at INTEGER ); +CREATE UNIQUE INDEX receipt_shares_active_kind_idx ON receipt_shares(organization_id,order_id,actor_id,kind) WHERE revoked_at IS NULL; CREATE INDEX receipt_shares_order_idx ON receipt_shares(organization_id,order_id,expires_at); CREATE TABLE receipt_share_deliveries ( id TEXT PRIMARY KEY, share_id TEXT NOT NULL REFERENCES receipt_shares(id), recipient_hash TEXT NOT NULL, diff --git a/apps/api/src/receipt-shares.ts b/apps/api/src/receipt-shares.ts index 1db8cea9..40eaa217 100644 --- a/apps/api/src/receipt-shares.ts +++ b/apps/api/src/receipt-shares.ts @@ -31,6 +31,8 @@ receiptShares.post('/orders/:id/receipt-shares',async c=>{ const p=requirePermission(c,'sales:create'),orderId=c.req.param('id'),body=parseBody(await jsonBody(c),z.object({id:uuid,kind:z.enum(['standard','gift'])})); const order=await authorizedOrder(c,p,orderId); let row=await findShare(c,p.organizationId,orderId,body.id); + const findActive=()=>c.env.DB.prepare('SELECT '+shareColumns+' FROM receipt_shares WHERE organization_id=? AND order_id=? AND actor_id=? AND kind=? AND revoked_at IS NULL AND expires_at>?').bind(p.organizationId,orderId,p.userId,body.kind,now()).first(); + if(!row)row=await findActive(); if(!row){ await throttle(c,'receipt-share-create',p.organizationId,100); const items=await c.env.DB.prepare(`SELECT name_snapshot AS name,oi.quantity,oi.unit_price_minor AS unitPriceMinor,oi.discount_minor AS discountMinor,oi.tax_minor AS taxMinor, @@ -40,8 +42,11 @@ receiptShares.post('/orders/:id/receipt-shares',async c=>{ status:order.status,lines:items.results.map(x=>({name:x.name,quantity:x.quantity,returnedQuantity:x.returnedQuantity,...(body.kind==='standard'?{unitPriceMinor:x.unitPriceMinor,discountMinor:x.discountMinor,taxMinor:x.taxMinor,totalMinor:x.totalMinor}:{})})), ...(body.kind==='standard'?{currency:order.currency,subtotalMinor:order.subtotalMinor,discountMinor:order.discountMinor,taxMinor:order.taxMinor,roundingMinor:order.roundingMinor,totalMinor:order.totalMinor}:{})}; const token=await tokenFor(c,body.id,p.organizationId),hash=await sha256(token),created=now(); - await c.env.DB.prepare('INSERT OR IGNORE INTO receipt_shares(id,organization_id,order_id,actor_id,token_hash,kind,snapshot_json,created_at,expires_at) VALUES(?,?,?,?,?,?,?,?,?)').bind(body.id,p.organizationId,orderId,p.userId,hash,body.kind,JSON.stringify(snapshot),created,created+7*86400).run(); - row=await findShare(c,p.organizationId,orderId,body.id); + await c.env.DB.batch([ + c.env.DB.prepare('UPDATE receipt_shares SET revoked_at=? WHERE organization_id=? AND order_id=? AND actor_id=? AND kind=? AND revoked_at IS NULL AND expires_at<=?').bind(created,p.organizationId,orderId,p.userId,body.kind,created), + c.env.DB.prepare('INSERT OR IGNORE INTO receipt_shares(id,organization_id,order_id,actor_id,token_hash,kind,snapshot_json,created_at,expires_at) VALUES(?,?,?,?,?,?,?,?,?)').bind(body.id,p.organizationId,orderId,p.userId,hash,body.kind,JSON.stringify(snapshot),created,created+7*86400) + ]); + row=await findShare(c,p.organizationId,orderId,body.id)??await findActive(); } if(!row||row.kind!==body.kind||row.actorId!==p.userId)fail('RECEIPT_SHARE_CONFLICT','Link reference is already in use.',409); if(!active(row))fail('RECEIPT_SHARE_EXPIRED','This link is expired or revoked. Create a new link.',409); diff --git a/apps/web/e2e-worker/receipt-shares.spec.ts b/apps/web/e2e-worker/receipt-shares.spec.ts index 3ea4f9cd..2120f06a 100644 --- a/apps/web/e2e-worker/receipt-shares.spec.ts +++ b/apps/web/e2e-worker/receipt-shares.spec.ts @@ -6,6 +6,7 @@ test('private receipt capabilities are scoped, redacted, idempotent and revocabl type S={data:{id:string;token:string;expiresAt:number}}; const shareBody={id:crypto.randomUUID(),kind:'gift'},a=await post(request,path,shareBody,m,200),b=await post(request,path,shareBody,m,200); expect(a.data).toEqual(b.data); + const reopened=await post(request,path,{id:crypto.randomUUID(),kind:'gift'},m,200);expect(reopened.data).toEqual(a.data); const guest=await newRequest.newContext({baseURL:'http://127.0.0.1:8787'}); try{ const result=await guest.post('/api/v1/receipt-shares/redeem',{data:{token:a.data.token}});expect(result.status()).toBe(200); diff --git a/apps/web/src/features/register/SharedReceipt.tsx b/apps/web/src/features/register/SharedReceipt.tsx index 8b3c43e6..046332d3 100644 --- a/apps/web/src/features/register/SharedReceipt.tsx +++ b/apps/web/src/features/register/SharedReceipt.tsx @@ -11,7 +11,7 @@ export function ReceiptShareControls({orderId,gift}:{orderId:string;gift:boolean async function perform(task:()=>Promise){if(working.current)return;working.current=true;setBusy(true);setError('');setMessage('');try{await task();}catch(e){setError(describeError(e).message);}finally{working.current=false;setBusy(false);}} const link=share?new URL('/shared-receipt#'+share.token,window.location.origin).href:''; return
{open?<>Share only with the intended recipient. Anyone holding the link can read it for seven days. No customer identity, cost or payment reference is included.{error?{error}:null}{message?:null} - {!share?:<>Expires {new Date(share.expiresAt*1000).toLocaleString()}{setEmail(e.target.value);setConsent(false);}} disabled={busy}/>setConsent(e.target.checked)} disabled={busy} label="Customer requested this receipt at this address"/>} + {!share?:<>Expires {new Date(share.expiresAt*1000).toLocaleString()}{setEmail(e.target.value);setConsent(false);}} disabled={busy}/>setConsent(e.target.checked)} disabled={busy} label="Customer requested this receipt at this address"/>} :null}
; } export function SharedReceiptScreen(){ diff --git a/tests/staging-l1.test.mjs b/tests/staging-l1.test.mjs index caf2e837..386202b7 100644 --- a/tests/staging-l1.test.mjs +++ b/tests/staging-l1.test.mjs @@ -9,12 +9,14 @@ const history=(length=28)=>JSON.stringify([{success:true,results: const response=(value)=>JSON.stringify([{success:true,results:[{violations:value}]}]); const clean=()=>Object.fromEntries(CHECKS.map(c=>[c.id,response(0)])); -test('L1 matches migration prefix and reports nine pending hashed migrations',()=>{ +test('L1 matches the historical 0028 prefix and reports every appended hashed migration',()=>{ const p=migrationBaseline(history()); assert.equal(p.appliedCount,28); - assert.equal(p.pending.length,9); + assert.equal(p.pending.length,inventory().length-28); + assert.deepEqual(p.pending.map(x=>x.name),inventory().slice(28).map(x=>x.name)); assert.equal(p.pending[0].name,'0029_pos_core_settings.sql'); - assert.equal(p.pending.at(-1).name,'0037_variant_scan_codes.sql'); + assert.equal(p.pending[8].name,'0037_variant_scan_codes.sql'); + assert.equal(p.pending.at(-1).name,inventory().at(-1).name); assert.ok(p.pending.every(x=>/^[a-f0-9]{64}$/.test(x.sha256))); }); test('audit uses only fixed SELECT/CTE statements and never returns records or merchant identifiers',()=>{ @@ -28,7 +30,8 @@ test('audit uses only fixed SELECT/CTE statements and never returns records or m } const result=audit(history(),clean(),SHA); assert.equal(result.decision,'DATA_PREFLIGHT_CLEAN'); - assert.equal(result.schema.pending.length,9); + assert.equal(result.schema.pending.length,inventory().length-28); + assert.deepEqual(result.schema.pending.map(x=>x.name),inventory().slice(28).map(x=>x.name)); assert.equal(result.summary.failed_blockers,0); assert.equal(result.summary.review_required,0); assert.equal(result.mutation_performed,false); From 98f228c47acb6d4fcbc5dfc606e085c6d957a5cc Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Sun, 6 Dec 2026 00:20:41 -0500 Subject: [PATCH 04/10] feat(returns): exact original-tender allocation and atomic refund payout ledger --- .github/workflows/worker-e2e.yml | 2 +- apps/api/migrations/0040_refund_payouts.sql | 53 ++++++++++++++ apps/api/src/sales.ts | 70 +++++++++++++++---- apps/api/src/types.ts | 3 + apps/web/e2e-worker/refund-payouts.spec.ts | 19 +++++ apps/web/src/api/live.ts | 5 +- apps/web/src/api/types.ts | 3 + apps/web/src/features/merchant/Orders.tsx | 20 ++++-- .../register-m3-original-tenders.md | 3 + packages/db/src/schema.ts | 5 ++ packages/domain/src/refund.test.ts | 23 +++++- packages/domain/src/refund.ts | 26 +++++++ tests/route-policy.mjs | 2 +- tests/staging-aggregate.sql | 4 +- tests/staging-post-migration.sql | 2 + 15 files changed, 216 insertions(+), 24 deletions(-) create mode 100644 apps/api/migrations/0040_refund_payouts.sql create mode 100644 apps/web/e2e-worker/refund-payouts.spec.ts create mode 100644 docs/operations/register-m3-original-tenders.md diff --git a/.github/workflows/worker-e2e.yml b/.github/workflows/worker-e2e.yml index e3997021..a5466491 100644 --- a/.github/workflows/worker-e2e.yml +++ b/.github/workflows/worker-e2e.yml @@ -16,7 +16,7 @@ jobs: strategy: fail-fast: false matrix: - suite: [merchant, contracts, recovery, integrity, roles, transfers, auth, money, woo, offline, cash-integrity, ops-load, catalog-import, register-catalog, return-recovery, receipt-shares, display-pairs] + suite: [merchant, contracts, recovery, integrity, roles, transfers, auth, money, woo, offline, cash-integrity, ops-load, catalog-import, register-catalog, return-recovery, receipt-shares, display-pairs, refund-payouts] timeout-minutes: 20 steps: - uses: actions/checkout@v4 diff --git a/apps/api/migrations/0040_refund_payouts.sql b/apps/api/migrations/0040_refund_payouts.sql new file mode 100644 index 00000000..eee86d29 --- /dev/null +++ b/apps/api/migrations/0040_refund_payouts.sql @@ -0,0 +1,53 @@ +-- Original tender payout ledger. Existing single-method refunds are backfilled. +ALTER TABLE refunds ADD COLUMN rounding_minor INTEGER NOT NULL DEFAULT 0; +CREATE TABLE refund_payouts ( + refund_id TEXT NOT NULL REFERENCES refunds(id), + method TEXT NOT NULL CHECK(method IN ('cash','external_card','manual_upi')), + amount_minor INTEGER NOT NULL CHECK(amount_minor>=0), + PRIMARY KEY(refund_id,method) +); +INSERT INTO refund_payouts(refund_id,method,amount_minor) SELECT id,method,amount_minor FROM refunds; +DROP TRIGGER IF EXISTS cash_refund_register_guard; +DROP TRIGGER IF EXISTS cash_refund_drawer_guard; +DROP TRIGGER IF EXISTS cash_movement_drawer_guard; +CREATE TRIGGER refund_payment_cap BEFORE INSERT ON refunds BEGIN + SELECT RAISE(ABORT,'REFUND_PAYMENT_CAP') WHERE NOT EXISTS(SELECT 1 FROM orders o WHERE o.id=NEW.order_id AND o.organization_id=NEW.organization_id + AND NEW.amount_minor+COALESCE((SELECT SUM(r.amount_minor) FROM refunds r WHERE r.organization_id=NEW.organization_id AND r.order_id=NEW.order_id),0)<=o.total_minor); +END; +CREATE TRIGGER refund_payout_guard BEFORE INSERT ON refund_payouts BEGIN + SELECT RAISE(ABORT,'REFUND_PAYOUT_MISMATCH') WHERE NOT EXISTS(SELECT 1 FROM refunds r WHERE r.id=NEW.refund_id AND NEW.amount_minor+COALESCE((SELECT SUM(rp.amount_minor) FROM refund_payouts rp WHERE rp.refund_id=r.id),0)<=r.amount_minor AND (r.method='original' OR r.method=NEW.method)); + SELECT RAISE(ABORT,'REFUND_PAYOUT_CAP') WHERE EXISTS(SELECT 1 FROM refunds r WHERE r.id=NEW.refund_id AND r.method='original' + AND NEW.amount_minor+COALESCE((SELECT SUM(rp.amount_minor) FROM refund_payouts rp JOIN refunds prior ON prior.id=rp.refund_id WHERE prior.organization_id=r.organization_id AND prior.order_id=r.order_id AND rp.method=NEW.method),0)>COALESCE((SELECT SUM(p.amount_minor) FROM order_payments p WHERE p.order_id=r.order_id AND p.method=NEW.method),0)); +END; +CREATE TRIGGER refund_cash_payout_guard BEFORE INSERT ON refund_payouts WHEN NEW.method='cash' BEGIN + SELECT RAISE(ABORT,'REFUND_REGISTER_REQUIRED') WHERE NOT EXISTS( + SELECT 1 FROM refunds rf JOIN orders o ON o.id=rf.order_id AND o.organization_id=rf.organization_id JOIN register_sessions s ON s.id=rf.cash_session_id AND s.organization_id=rf.organization_id + JOIN registers r ON r.id=s.register_id AND r.organization_id=s.organization_id + WHERE rf.id=NEW.refund_id AND s.closed_at IS NULL AND r.store_id=o.store_id); + SELECT RAISE(ABORT,'INSUFFICIENT_DRAWER_CASH') WHERE EXISTS( + SELECT 1 FROM refunds f JOIN register_sessions rs ON rs.id=f.cash_session_id AND rs.organization_id=f.organization_id WHERE f.id=NEW.refund_id AND + NEW.amount_minor>rs.opening_cash_minor + +COALESCE((SELECT SUM(pay.amount_minor) FROM order_payments pay JOIN orders o ON o.id=pay.order_id WHERE o.organization_id=rs.organization_id AND o.register_session_id=rs.id AND o.status IN ('completed','partially_returned','returned') AND pay.method='cash'),0) + +COALESCE((SELECT SUM(cm.amount_minor) FROM cash_movements cm WHERE cm.organization_id=rs.organization_id AND cm.register_session_id=rs.id),0) + -COALESCE((SELECT SUM(rp.amount_minor) FROM refund_payouts rp JOIN refunds rf ON rf.id=rp.refund_id JOIN orders o ON o.id=rf.order_id WHERE rf.organization_id=rs.organization_id AND rp.method='cash' AND (rf.cash_session_id=rs.id OR (rf.cash_session_id IS NULL AND o.register_session_id=rs.id))),0)); +END; +CREATE TRIGGER refund_legacy_payout AFTER INSERT ON refunds WHEN NEW.method<>'original' BEGIN + INSERT INTO refund_payouts(refund_id,method,amount_minor) VALUES(NEW.id,NEW.method,NEW.amount_minor); +END; +CREATE TRIGGER refund_payout_completion BEFORE INSERT ON refund_request_keys BEGIN + SELECT RAISE(ABORT,'REFUND_PAYOUT_MISMATCH') WHERE NOT EXISTS( + SELECT 1 FROM refunds r WHERE r.id=NEW.refund_id AND r.organization_id=NEW.organization_id AND r.order_id=NEW.order_id + AND COALESCE((SELECT SUM(rp.amount_minor) FROM refund_payouts rp WHERE rp.refund_id=r.id),0)=r.amount_minor + AND COALESCE((SELECT SUM(ri.amount_minor) FROM refund_items ri WHERE ri.refund_id=r.id),0)+r.rounding_minor=r.amount_minor); +END; +CREATE TRIGGER refund_payout_no_update BEFORE UPDATE ON refund_payouts BEGIN SELECT RAISE(ABORT,'REFUND_PAYOUT_IMMUTABLE'); END; +CREATE TRIGGER refund_payout_no_delete BEFORE DELETE ON refund_payouts BEGIN SELECT RAISE(ABORT,'REFUND_PAYOUT_IMMUTABLE'); END; +CREATE TRIGGER cash_movement_drawer_guard BEFORE INSERT ON cash_movements WHEN NEW.amount_minor<0 BEGIN + SELECT RAISE(ABORT,'INSUFFICIENT_DRAWER_CASH') WHERE NEW.amount_minor+COALESCE(( + SELECT rs.opening_cash_minor + +COALESCE((SELECT SUM(pay.amount_minor) FROM order_payments pay JOIN orders o ON o.id=pay.order_id WHERE o.organization_id=rs.organization_id AND o.register_session_id=rs.id AND o.status IN ('completed','partially_returned','returned') AND pay.method='cash'),0) + +COALESCE((SELECT SUM(cm.amount_minor) FROM cash_movements cm WHERE cm.organization_id=rs.organization_id AND cm.register_session_id=rs.id),0) + -COALESCE((SELECT SUM(rp.amount_minor) FROM refund_payouts rp JOIN refunds rf ON rf.id=rp.refund_id JOIN orders o ON o.id=rf.order_id WHERE rf.organization_id=rs.organization_id AND rp.method='cash' AND (rf.cash_session_id=rs.id OR (rf.cash_session_id IS NULL AND o.register_session_id=rs.id))),0) + FROM register_sessions rs WHERE rs.id=NEW.register_session_id AND rs.organization_id=NEW.organization_id + ),0)<0; +END; diff --git a/apps/api/src/sales.ts b/apps/api/src/sales.ts index eafb9b1f..14ef1c2d 100644 --- a/apps/api/src/sales.ts +++ b/apps/api/src/sales.ts @@ -3,6 +3,9 @@ import { z } from 'zod'; import { allocateCogsOutflow, allocateRefundLine, + refundPayableAmount, + allocateOriginalTenderRefund, + type RefundPayout, allocateReturnCogs, calculateMarginBps, fiscalYearCode, @@ -24,8 +27,8 @@ const expectedCashSql = `(SELECT rs.opening_cash_minor AND o.status IN ('completed','partially_returned','returned') AND pay.method='cash'),0) + COALESCE((SELECT SUM(cm.amount_minor) FROM cash_movements cm WHERE cm.organization_id=rs.organization_id AND cm.register_session_id=rs.id),0) - - COALESCE((SELECT SUM(rf.amount_minor) FROM refunds rf JOIN orders o ON o.id=rf.order_id - WHERE rf.organization_id=rs.organization_id AND rf.method='cash' + - COALESCE((SELECT SUM(rp.amount_minor) FROM refund_payouts rp JOIN refunds rf ON rf.id=rp.refund_id JOIN orders o ON o.id=rf.order_id + WHERE rf.organization_id=rs.organization_id AND rp.method='cash' AND (rf.cash_session_id=rs.id OR (rf.cash_session_id IS NULL AND o.register_session_id=rs.id))),0) FROM register_sessions rs WHERE rs.id=register_sessions.id)`; @@ -183,7 +186,7 @@ sales.get('/register-sessions/:id/summary', async c => { .bind(p.organizationId, sessionId).first<{ movementCount: number; amountMinor: number; cashInMinor: number; cashOutMinor: number; }>(); - const refunds = await c.env.DB.prepare(`SELECT COALESCE(SUM(rf.amount_minor),0) AS amountMinor FROM refunds rf JOIN orders o ON o.id=rf.order_id WHERE rf.organization_id=? AND (rf.cash_session_id=? OR (rf.cash_session_id IS NULL AND o.register_session_id=?)) AND rf.method='cash'`).bind(p.organizationId, sessionId, sessionId).first<{ amountMinor: number }>(); + const refunds = await c.env.DB.prepare(`SELECT COALESCE(SUM(rp.amount_minor),0) AS amountMinor FROM refund_payouts rp JOIN refunds rf ON rf.id=rp.refund_id JOIN orders o ON o.id=rf.order_id WHERE rf.organization_id=? AND (rf.cash_session_id=? OR (rf.cash_session_id IS NULL AND o.register_session_id=?)) AND rp.method='cash'`).bind(p.organizationId, sessionId, sessionId).first<{ amountMinor: number }>(); const audit = await c.env.DB.prepare(`SELECT COUNT(*) AS closeAuditCount FROM audit_log WHERE organization_id=? AND action='register.closed' AND target_id=?`) .bind(p.organizationId, sessionId).first<{ closeAuditCount: number }>(); @@ -690,7 +693,41 @@ sales.get('/orders/:id/receipt', async c => { if (p.role === 'cashier' && order.cashierId !== p.userId) fail('FORBIDDEN', 'Cashiers can print only their own receipts.', 403); const store = await c.env.DB.prepare('SELECT name,address FROM stores WHERE id=? AND organization_id=?').bind(order.storeId, p.organizationId).first(); const organization = await c.env.DB.prepare('SELECT name,currency,receipt_header AS receiptHeader,receipt_footer AS receiptFooter,tax_id AS taxId FROM organizations WHERE id=?').bind(p.organizationId).first(); - return c.json(asData({ organization, store, order })); + return c.json(asData({ organization, store, order:stripOrderCosts(order,p.role) })); +}); + +const returnItemsSchema=z.array(z.object({orderItemId:id,quantity:z.number().int().positive().max(100000),restock:z.boolean().default(false)})).min(1).max(100); +const payoutSchema=z.object({method:z.enum(['cash','external_card','manual_upi']),amountMinor:minor}); +async function returnPayable(c:ApiContext,order:Awaited>,items:z.infer,original:boolean){ + if(!['completed','partially_returned'].includes(order.status))fail('ORDER_NOT_REFUNDABLE','Order is not eligible for another refund.',409); + if(new Set(items.map(x=>x.orderItemId)).size!==items.length)fail('DUPLICATE_RETURN_LINE','A return item cannot be repeated.',422); + const lines=order.items as Record[],byId=new Map(lines.map(l=>[String(l.id),l])),quantities=new Map(items.map(l=>[l.orderItemId,l.quantity])); + let rawMinor=0; + for(const item of items){ + const line=byId.get(item.orderItemId);if(!line)fail('NOT_FOUND','Order item not found.',404); + const before=Number(line!.returnedQuantity??0),sold=Number(line!.quantity); + if(before+item.quantity>sold)fail('REFUND_QUANTITY_EXCEEDED','Refund exceeds the purchased quantity.',409); + rawMinor+=allocateRefundLine({quantity:sold,totalMinor:Number(line!.totalMinor),taxMinor:Number(line!.taxMinor)},before,item.quantity).amountMinor; + if(!Number.isSafeInteger(rawMinor))fail('AMOUNT_OVERFLOW','Refund exceeds supported currency precision.',422); + } + const fullyReturned=lines.every(l=>Number(l.returnedQuantity??0)+(quantities.get(String(l.id))??0)===Number(l.quantity)); + const p=principal(c),history=await c.env.DB.prepare('SELECT COALESCE(SUM(amount_minor),0) AS amount FROM refunds WHERE organization_id=? AND order_id=?').bind(p.organizationId,order.id).first<{amount:number}>(); + let amountMinor:number; + try{amountMinor=refundPayableAmount(rawMinor,Number(order.totalMinor),Number(history?.amount??0),fullyReturned);}catch{return fail('REFUND_HISTORY_INVALID','Prior refunds exceed the original payment; manager reconciliation is required.',409);} + let payouts:RefundPayout[]=[]; + if(original){ + const already=await c.env.DB.prepare('SELECT rp.method,SUM(rp.amount_minor) AS amountMinor FROM refund_payouts rp JOIN refunds rf ON rf.id=rp.refund_id WHERE rf.organization_id=? AND rf.order_id=? GROUP BY rp.method').bind(p.organizationId,order.id).all(); + const paid=(order.payments as Record[]).map(p=>({method:p.method as RefundPayout['method'],amountMinor:Number(p.amountMinor)})); + try{payouts=allocateOriginalTenderRefund(amountMinor,paid,already.results);}catch{return fail('REFUND_TENDER_CAPACITY','Original tender balances cannot cover this refund; manager reconciliation is required.',409);} + } + return {amountMinor,roundingMinor:amountMinor-rawMinor,payouts}; +} +sales.post('/orders/:id/return-quote',async c=>{ + const p=requirePermission(c,'sales:refund'),body=parseBody(await jsonBody(c),z.object({items:returnItemsSchema})); + const order=await loadOrder(c,c.req.param('id')); + // loadOrder and role guard bind the quote to the current business. + void p; + return c.json(asData(await returnPayable(c,order,body.items,true))); }); sales.post('/orders/:id/returns', async c => { @@ -699,15 +736,16 @@ sales.post('/orders/:id/returns', async c => { idempotencyKey: id, registerSessionId: id.optional(), overrideToken: z.string().min(16).max(256).optional(), reason: z.string().trim().min(3).max(250), - method: z.enum(['cash', 'external_card', 'manual_upi']), attestedByCashier: z.boolean().optional(), - items: z.array(z.object({ orderItemId: id, quantity: z.number().int().positive(), restock: z.boolean().default(false) })).min(1).max(100), + method: z.enum(['cash', 'external_card', 'manual_upi','original']), attestedByCashier: z.boolean().optional(), + expectedRefundMinor:minor.optional(),expectedPayouts:z.array(payoutSchema).max(3).optional(), + items:returnItemsSchema, }); const body = parseBody(await jsonBody(c), schema); if (c.req.header('Idempotency-Key') !== body.idempotencyKey) fail('IDEMPOTENCY_REQUIRED', 'Refund requires matching Idempotency-Key header and body.', 422); if (body.method === 'cash' && !body.registerSessionId) fail('REFUND_REGISTER_REQUIRED', 'An open register session is required for a cash refund.', 422); - if (body.method !== 'cash' && body.attestedByCashier !== true) + if (body.method !== 'cash' && body.method !== 'original' && body.attestedByCashier !== true) fail('ATTESTATION_REQUIRED', 'External card and UPI refunds require explicit cashier attestation.', 422); if (new Set(body.items.map(i => i.orderItemId)).size !== body.items.length) fail('DUPLICATE_RETURN_LINE', 'A return item cannot be repeated.', 422); @@ -766,16 +804,24 @@ sales.post('/orders/:id/returns', async c => { fail('AMOUNT_OVERFLOW', 'Refund exceeds supported currency precision.', 422); allocations.push({ item: line, quantity: requested.quantity, before, restock: requested.restock, ...allocation!, cogsMinor }); } + const payable=await returnPayable(c,order,body.items,body.method==='original'); + if(body.method==='original'&&(body.expectedRefundMinor===undefined||!body.expectedPayouts||body.expectedRefundMinor!==payable.amountMinor||JSON.stringify(body.expectedPayouts)!==JSON.stringify(payable.payouts)))fail('REFUND_QUOTE_CHANGED','Refund quote changed. Reconcile any payout already made before retrying.',409); + const payouts:RefundPayout[]=body.method==='original'?payable.payouts:[{method:body.method,amountMinor:payable.amountMinor}]; + const hasCash=payouts.some(p=>p.method==='cash'&&p.amountMinor>0); + if(hasCash&&!body.registerSessionId)fail('REFUND_REGISTER_REQUIRED','An open register session is required for a cash refund.',422); + if(payouts.some(p=>p.method!=='cash'&&p.amountMinor>0)&&body.attestedByCashier!==true)fail('ATTESTATION_REQUIRED','External refunds require explicit cashier attestation.',422); + totalMinor=payable.amountMinor; const response = asData({ - id: refundId, orderId: order.id, amountMinor: totalMinor, + id: refundId, orderId: order.id, amountMinor: totalMinor, payouts,roundingMinor:payable.roundingMinor, taxMinor: taxRefundMinor, method: body.method, refundVerification: 'cashier_attested', - cashSessionId: body.method === 'cash' ? body.registerSessionId : null, createdAt: timestamp, + cashSessionId: hasCash||body.method==='cash' ? body.registerSessionId : null, createdAt: timestamp, }); stmts.push(c.env.DB.prepare('INSERT INTO checkout_key_fences(organization_id,request_key,kind,created_at) VALUES(?,?,?,?)').bind(p.organizationId,fenceKey,'checkout',timestamp)); stmts.push(c.env.DB.prepare( - 'INSERT INTO refunds(id,organization_id,order_id,actor_id,amount_minor,reason,method,cash_session_id,cogs_reversed_minor,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)' + 'INSERT INTO refunds(id,organization_id,order_id,actor_id,amount_minor,reason,method,cash_session_id,cogs_reversed_minor,created_at,rounding_minor) VALUES(?,?,?,?,?,?,?,?,?,?,?)' ).bind(refundId, p.organizationId, order.id, p.userId, totalMinor, body.reason, body.method, - body.method === 'cash' ? body.registerSessionId! : null, cogsReversedMinor, timestamp)); + hasCash||body.method==='cash' ? body.registerSessionId! : null, cogsReversedMinor, timestamp,payable.roundingMinor)); + if(body.method==='original')for(const payout of payouts)stmts.push(c.env.DB.prepare('INSERT INTO refund_payouts(refund_id,method,amount_minor) VALUES(?,?,?)').bind(refundId,payout.method,payout.amountMinor)); for (const entry of allocations) { stmts.push(c.env.DB.prepare( 'INSERT INTO refund_items(id,refund_id,order_item_id,quantity,amount_minor,tax_minor,restock,returned_before,cogs_minor) VALUES(?,?,?,?,?,?,?,?,?)' @@ -803,7 +849,7 @@ sales.post('/orders/:id/returns', async c => { stmts.push(c.env.DB.prepare( 'INSERT INTO audit_log(id,organization_id,actor_id,action,target_id,detail_json,created_at) VALUES(?,?,?,?,?,?,?)' ).bind(apiId(), p.organizationId, p.userId, 'sale.refunded', order.id, - JSON.stringify({ refundId, amountMinor: totalMinor, taxMinor: taxRefundMinor, verification: 'cashier_attested', overrideActorId: override?.managerId ?? null }), timestamp)); + JSON.stringify({ refundId, amountMinor: totalMinor, taxMinor: taxRefundMinor, payouts,roundingMinor:payable.roundingMinor,verification: 'cashier_attested', overrideActorId: override?.managerId ?? null }), timestamp)); if (override) stmts.push(c.env.DB.prepare('UPDATE override_tokens SET used_at=? WHERE id=?').bind(timestamp, override.id)); try { await c.env.DB.batch(stmts); } catch (err) { const competing = await loadPrior(); diff --git a/apps/api/src/types.ts b/apps/api/src/types.ts index a12cbfae..0db7ea0b 100644 --- a/apps/api/src/types.ts +++ b/apps/api/src/types.ts @@ -56,6 +56,9 @@ export function sqlError(error:unknown):never { if(raw.includes('INSUFFICIENT_DRAWER_CASH'))return fail('INSUFFICIENT_DRAWER_CASH','This cash payout exceeds the current recorded drawer balance. Review cash movements or add an authorized float before continuing.',409); if(raw.includes('SESSION_CLOSED'))return fail('SESSION_CLOSED','Register has already closed.',409); if(raw.includes('REFUND_REGISTER_REQUIRED'))return fail('REFUND_REGISTER_REQUIRED','Cash refunds require an open register in the order store.',409); + if(raw.includes('REFUND_PAYMENT_CAP'))return fail('REFUND_PAYMENT_CAP','Refund would exceed the original recorded payment.',409); + if(raw.includes('REFUND_PAYOUT_CAP'))return fail('REFUND_TENDER_CAPACITY','Original tender balance changed. Reconcile the original payout before retrying.',409); + if(raw.includes('REFUND_PAYOUT_MISMATCH'))return fail('REFUND_QUOTE_CHANGED','Refund allocation changed; no return was committed.',409); if(raw.includes('REFUND_STALE'))return fail('REFUND_STALE','Refund quantities changed during processing; review and retry.',409); if(raw.includes('REFUND_QUANTITY_EXCEEDED')) return fail('REFUND_QUANTITY_EXCEEDED','Refund quantity exceeds purchased quantity.',409); if(raw.includes('REFUND_ORDER_MISMATCH')) return fail('REFUND_ORDER_MISMATCH','Refund line belongs to another order.',409); diff --git a/apps/web/e2e-worker/refund-payouts.spec.ts b/apps/web/e2e-worker/refund-payouts.spec.ts new file mode 100644 index 00000000..3dab91d8 --- /dev/null +++ b/apps/web/e2e-worker/refund-payouts.spec.ts @@ -0,0 +1,19 @@ +import {expect,test} from '@playwright/test'; +import {registerMerchant,createStockedVariant,openRegister,post,get} from './support'; +test('split refunds allocate exact original tender balances and cash drawer, with same-key recovery',async({request})=>{ + const m=await registerMerchant(request,'Original Tender Refund'),v=await createStockedVariant(request,m,2),shift=await openRegister(request,m,0); + const saleKey=crypto.randomUUID(),sale=await post<{data:{id:string}}>(request,'/checkout',{registerSessionId:shift,idempotencyKey:saleKey,lines:[{variantId:v,quantity:2}],tenders:[{method:'cash',amountMinor:2000},{method:'external_card',amountMinor:3000,attestedByCashier:true}]},m,201,saleKey); + const path='/orders/'+sale.data.id,order=await get<{data:{items:Array<{id:string}>}}>(request,path); + const items=[{orderItemId:order.data.items[0]!.id,quantity:1,restock:true}]; + type Q={data:{amountMinor:number;payouts:Array<{method:string;amountMinor:number}>}}; + const quote=await post(request,path+'/return-quote',{items},m,200); + expect(quote.data).toMatchObject({amountMinor:2500,payouts:[{method:'cash',amountMinor:1000},{method:'external_card',amountMinor:1500}]}); + const key=crypto.randomUUID(),body={idempotencyKey:key,method:'original',registerSessionId:shift,reason:'Split tender return',attestedByCashier:true,expectedRefundMinor:quote.data.amountMinor,expectedPayouts:quote.data.payouts,items}; + const wrong=await post<{error:{code:string}}>(request,path+'/returns',{...body,expectedRefundMinor:2501},m,409,key);expect(wrong.error.code).toBe('REFUND_QUOTE_CHANGED'); + const a=await post(request,path+'/returns',body,m,201,key),b=await post(request,path+'/returns',body,m,200,key);expect(a.data).toEqual(b.data); + expect((await get<{data:{expectedCashMinor:number;cashRefundMinor:number}}>(request,'/register-sessions/'+shift+'/summary')).data).toMatchObject({expectedCashMinor:1000,cashRefundMinor:1000}); + const remaining=await post(request,path+'/return-quote',{items},m,200);expect(remaining.data.payouts).toEqual(quote.data.payouts); + const key2=crypto.randomUUID();await post(request,path+'/returns',{...body,idempotencyKey:key2,expectedRefundMinor:remaining.data.amountMinor,expectedPayouts:remaining.data.payouts},m,201,key2); + expect((await get<{data:{expectedCashMinor:number;cashRefundMinor:number}}>(request,'/register-sessions/'+shift+'/summary')).data).toMatchObject({expectedCashMinor:0,cashRefundMinor:2000}); + expect((await get<{data:{refundedMinor:number}}>(request,'/reports/summary')).data.refundedMinor).toBe(5000); +}); diff --git a/apps/web/src/api/live.ts b/apps/web/src/api/live.ts index 8d10bdf6..247907a2 100644 --- a/apps/web/src/api/live.ts +++ b/apps/web/src/api/live.ts @@ -586,7 +586,7 @@ export const liveApi: Api = { method: 'POST', idempotencyKey: body.idempotencyKey, json: { idempotencyKey: body.idempotencyKey, registerSessionId: body.registerSessionId, overrideToken: body.overrideToken, - reason: body.reason, method: body.refundTender, attestedByCashier: body.attestedByCashier, + reason: body.reason, method: body.expectedPayouts?'original':body.refundTender, attestedByCashier: body.attestedByCashier,expectedRefundMinor:body.expectedRefundMinor,expectedPayouts:body.expectedPayouts, items: body.lines.map((line) => ({ orderItemId: line.orderLineId, quantity: line.quantity, restock: line.restock ?? body.restock })), }, }); @@ -706,6 +706,9 @@ export type OfflineRecoveryReview = { resolution: 'cash_refunded' | 'cash_not_taken' | 'handled_in_another_order'; note: string; orderId?: string; }; +export function fetchReturnQuote(orderId:string,items:{orderItemId:string;quantity:number;restock:boolean}[],signal?:AbortSignal){ + return one('/api/v1/orders/'+encodeURIComponent(orderId)+'/return-quote',{method:'POST',json:{items},signal}); +} export async function reviewReturn(orderId:string,body:{idempotencyKey:string;resolution:'payout_not_made'|'payout_reconciled_outside_storefront';note:string}){ return one<{id:string;alreadyReviewed:boolean}>('/api/v1/orders/'+encodeURIComponent(orderId)+'/return-reviews',{method:'POST',idempotencyKey:body.idempotencyKey,json:body}); } diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts index 79031a00..fa54f064 100644 --- a/apps/web/src/api/types.ts +++ b/apps/web/src/api/types.ts @@ -105,7 +105,10 @@ export type ReturnBody = { idempotencyKey: Id; registerSessionId?: Id; overrideToken?: string; attestedByCashier?: boolean; reason: string; restock: boolean; lines: { orderLineId: Id; quantity: number; restock?: boolean }[]; refundTender: TenderMethod; + expectedRefundMinor?:Money; + expectedPayouts?:{method:TenderMethod;amountMinor:Money}[]; }; +export type ReturnQuote={amountMinor:Money;roundingMinor:Money;payouts:{method:TenderMethod;amountMinor:Money}[]}; export type ReportSummary = { currency: string; grossSalesMinor: Money; netSalesMinor: Money; orderCount: number; averageOrderMinor: Money; refundsMinor: Money; taxMinor: Money; netTaxMinor?: Money; netRevenueExclTaxMinor?: Money; diff --git a/apps/web/src/features/merchant/Orders.tsx b/apps/web/src/features/merchant/Orders.tsx index 33d25dae..e753054f 100644 --- a/apps/web/src/features/merchant/Orders.tsx +++ b/apps/web/src/features/merchant/Orders.tsx @@ -16,7 +16,7 @@ import { ReceiptActions } from '../register/Receipt'; import { useLineLabels } from '../../lib/useLineLabels'; import { offlineDB, pendingReturnKey, listPendingReturns, putPendingReturn, finishPendingReturn, useLiveQuery, type PendingReturn } from '../../lib/offline-db'; import { StorefrontApiError } from '../../lib/api'; -import { reviewReturn } from '../../api/live'; +import { fetchReturnQuote,reviewReturn } from '../../api/live'; export const statusTone = (s: Order['status']): Tone => s === 'completed' ? 'success' : s === 'partially_returned' ? 'warn' : s === 'returned' || s === 'voided' ? 'danger' : 'info'; const statusLabel = (s: Order['status']) => s.replace('_', ' '); @@ -102,6 +102,12 @@ function ReturnDialog({ order, open, onClose, pending }: { order: Order; open: b const selected = order.lines.filter((l) => (qty[l.id] ?? 0) > 0); const refundEstimate = selected.reduce((a, l) => a + Math.round(l.totalMinor * (qty[l.id] ?? 0) / l.quantity), 0); const recovering=!!pending||unknown; + const quoteItems=selected.map(l=>({orderItemId:l.id,quantity:qty[l.id]!,restock:dispositions[l.id]??restock})); + const quoteQ=useQuery({queryKey:['return-quote',accountId,organizationId,order.id,quoteItems],enabled:open&&mode==='live'&&!recovering&&!done&&!offlineSession&"eItems.length>0,queryFn:({signal})=>fetchReturnQuote(order.id,quoteItems,signal),retry:false,staleTime:0,gcTime:0,refetchOnWindowFocus:false}); + const quote=quoteQ.data,quoteReady=mode==='demo'||!!quote&&!quoteQ.isFetching&&!quoteQ.isError; + const needsCash=mode==='demo'?tender==='cash':!!quote?.payouts.some(p=>p.method==='cash'); + const needsAttestation=mode==='demo'?tender!=='cash':!!quote?.payouts.some(p=>p.method!=='cash'); + useEffect(()=>setManuallyConfirmed(false),[quoteQ.dataUpdatedAt]); const mutation = useMutation({ mutationFn: async () => { if(mode==='live'){ @@ -118,15 +124,16 @@ function ReturnDialog({ order, open, onClose, pending }: { order: Order; open: b } if(pending||unknown||saved.current)throw new StorefrontApiError('RETURN_ALREADY_RECOVERED','Original refund is no longer pending. Reload the order before any new return.',409); } + if(!quoteReady||mode==='live'&&!quote)throw Error('Verify the original-tender quote first.'); let registerSessionId = cashShiftId; - if (tender === 'cash' && !registerSessionId) { + if (needsCash && !registerSessionId) { if (!workspace.registerId) throw new Error('Select a register and open a shift before refunding cash.'); const active = await api.activeSession(workspace.registerId); if (!active) throw new Error('Open a register shift before issuing a cash refund.'); registerSessionId = active.id; setCashShiftId(registerSessionId); } - const body:ReturnBody={idempotencyKey:key,registerSessionId:registerSessionId??undefined,reason,restock,refundTender:tender,attestedByCashier:tender==='cash'?undefined:manuallyConfirmed,lines:selected.map(l=>({orderLineId:l.id,quantity:qty[l.id]!,restock:dispositions[l.id]??restock}))}; + const body:ReturnBody={idempotencyKey:key,registerSessionId:registerSessionId??undefined,reason,restock,refundTender:tender,attestedByCashier:needsAttestation?manuallyConfirmed:undefined,lines:quoteItems,...(mode==='live'&"e?{expectedRefundMinor:quote.amountMinor,expectedPayouts:quote.payouts}:{})}; if(mode==='live'){ const row=await putPendingReturn({accountId,organizationId},order,body);saved.current=row; const result=await api.returnOrder(order.id,body); @@ -151,7 +158,7 @@ function ReturnDialog({ order, open, onClose, pending }: { order: Order; open: b },onSuccess:()=>{setReviewed(true);setDone(true);setUnknown(false);setReviewOpen(false);},onError:e=>setError(describeError(e))}); return ( Done : <>}> + footer={done ? : <>}> {done ? {reviewed?'The original reference is fenced. This review made no stock or money changes.':'The order status and stock have been updated.'} : (
{error ? {error.message} : null} @@ -162,9 +169,10 @@ function ReturnDialog({ order, open, onClose, pending }: { order: Order; open: b setQty({ ...qty, [l.id]: Math.max(0, Math.min(remaining(l), Math.floor(Number(e.target.value) || 0))) })} style={{ width: 100 }} />{(qty[l.id]??0)>0?setDispositions(d=>({...d,[l.id]:e.target.checked}))} label={`Restock ${l.name}`} disabled={recovering||mutation.isPending}/>:null}))}
- + {mode==='demo'?:Original payment methods (server allocated)}
- {tender !== 'cash' ? setManuallyConfirmed(event.target.checked)} disabled={recovering||mutation.isPending} label="I confirm this card/UPI refund was completed outside Storefront. Storefront does not transfer or verify the money." /> : null} + {mode==='live'&&!recovering&&selected.length>0?<>{quoteQ.isError?void quoteQ.refetch()}>Retry quote}>{describeError(quoteQ.error).message}:!quoteReady?

Verifying refund amount and original tender balances…

:quote?
    {quote.payouts.map(p=>
  • {tenderLabel[p.method]}{fmt(p.amountMinor)}
  • )}{quote.roundingMinor!==0?
  • Rounding adjustment{fmt(quote.roundingMinor)}
  • :null}
  • Total refund{fmt(quote.amountMinor)}
External refunds must be completed and attested manually. Do not pay out again if recovery is required.
:null}:null} + {needsAttestation ? setManuallyConfirmed(event.target.checked)} disabled={recovering||mutation.isPending} label="I confirm this card/UPI refund was completed outside Storefront. Storefront does not transfer or verify the money." /> : null} {setRestock(e.target.checked);setDispositions({});}} label="Return items to stock (uncheck for damaged goods)" disabled={recovering||mutation.isPending} />
)} diff --git a/docs/operations/register-m3-original-tenders.md b/docs/operations/register-m3-original-tenders.md new file mode 100644 index 00000000..70d8f7ef --- /dev/null +++ b/docs/operations/register-m3-original-tenders.md @@ -0,0 +1,3 @@ +# M3.2 — original tender refund allocation + +The live return screen requests an exact server quote for selected line quantities. Returns allocate against the remaining original cash/card/UPI balances using integer minor-unit arithmetic; the commit asserts the exact quote and records one refund with distinct payout rows. The final refund settles the actual amount paid, including cash-rounding differences. Existing single-method journals remain compatible and are backfilled. Drawer liquidity, same-store open shift, cumulative tender/total caps, item quantity/COGS and payout completeness are transactionally guarded. External payouts remain cashier-attested; no gateway transfer is implied. Manager reconciliation and same-reference recovery remain mandatory after uncertain outcomes. No migration may be applied to staging without the protected migration workflow. Atomic exchanges still require a separate linked sale/return transaction design. diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index 16b3e30c..d1e811e2 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -299,9 +299,14 @@ export const refunds = sqliteTable('refunds', { method: text('method').notNull(), cashSessionId: text('cash_session_id').references(() => registerSessions.id), cogsReversedMinor: integer('cogs_reversed_minor').notNull().default(0), + roundingMinor:integer('rounding_minor').notNull().default(0), createdAt: integer('created_at').notNull(), }, (t) => [index('refunds_order_idx').on(t.organizationId, t.orderId)]); +export const refundPayouts = sqliteTable('refund_payouts', { + refundId:text('refund_id').notNull().references(()=>refunds.id),method:text('method').notNull(),amountMinor:integer('amount_minor').notNull(), +},t=>[primaryKey({columns:[t.refundId,t.method]})]); + export const refundItems = sqliteTable('refund_items', { id: text('id').primaryKey(), refundId: text('refund_id').notNull().references(() => refunds.id), diff --git a/packages/domain/src/refund.test.ts b/packages/domain/src/refund.test.ts index b510bb4a..c090c63e 100644 --- a/packages/domain/src/refund.test.ts +++ b/packages/domain/src/refund.test.ts @@ -1,5 +1,5 @@ import {describe,it,expect} from 'vitest'; -import {allocateRefundLine,prorateCumulativeMinor} from './refund'; +import {allocateRefundLine,prorateCumulativeMinor,refundPayableAmount,allocateOriginalTenderRefund} from './refund'; describe('exact cumulative minor-unit refunds',()=>{ it('allocates 100 minor units across three 1-unit partial refunds without drift',()=>{ const orig={quantity:3,totalMinor:100,taxMinor:18}; @@ -19,3 +19,24 @@ describe('exact cumulative minor-unit refunds',()=>{ expect(()=>prorateCumulativeMinor(100,3,4)).toThrow(); }); }); + +describe('refund payout allocation',()=>{ + it('settles exact paid total including both directions of cash rounding',()=>{ + expect(refundPayableAmount(101,100,0,true)).toBe(100); + expect(refundPayableAmount(99,100,0,true)).toBe(100); + expect(refundPayableAmount(50,99,50,false)).toBe(49); + expect(()=>refundPayableAmount(10,100,101,true)).toThrow('REFUND_HISTORY_EXCEEDS_PAYMENT'); + }); + it('allocates original methods without exceeding their remaining balances',()=>{ + const paid=[{method:'cash' as const,amountMinor:2000},{method:'external_card' as const,amountMinor:3000}]; + const first=allocateOriginalTenderRefund(2500,paid,[]); + expect(first).toEqual([{method:'cash',amountMinor:1000},{method:'external_card',amountMinor:1500}]); + expect(allocateOriginalTenderRefund(2500,paid,first)).toEqual(first); + expect(allocateOriginalTenderRefund(0,paid,first)).toEqual([]); + expect(()=>allocateOriginalTenderRefund(2501,paid,first)).toThrow('REFUND_TENDER_CAPACITY'); + }); + it('uses exact integer allocation with large amounts',()=>{ + const paid=[{method:'cash' as const,amountMinor:Number.MAX_SAFE_INTEGER-1},{method:'manual_upi' as const,amountMinor:1}]; + expect(allocateOriginalTenderRefund(Number.MAX_SAFE_INTEGER,paid,[])).toEqual(paid); + }); +}); diff --git a/packages/domain/src/refund.ts b/packages/domain/src/refund.ts index a41fab84..5ed875ba 100644 --- a/packages/domain/src/refund.ts +++ b/packages/domain/src/refund.ts @@ -26,3 +26,29 @@ export function allocateRefundLine( prorateCumulativeMinor(original.taxMinor,original.quantity,returnedBefore), }; } + +export type RefundTenderMethod='cash'|'external_card'|'manual_upi'; +export type RefundPayout={method:RefundTenderMethod;amountMinor:number}; +export function refundPayableAmount(rawMinor:number,paidMinor:number,alreadyRefundedMinor:number,fullyReturned:boolean):number{ + for(const n of [rawMinor,paidMinor,alreadyRefundedMinor])if(!Number.isSafeInteger(n)||n<0)throw RangeError('invalid refund amount'); + if(alreadyRefundedMinor>paidMinor)throw RangeError('REFUND_HISTORY_EXCEEDS_PAYMENT'); + const remaining=paidMinor-alreadyRefundedMinor; + return fullyReturned?remaining:Math.min(rawMinor,remaining); +} +/** Allocate against original payment methods, never above each remaining tender balance. */ +export function allocateOriginalTenderRefund(amountMinor:number,paid:readonly RefundPayout[],refunded:readonly RefundPayout[]):RefundPayout[]{ + if(!Number.isSafeInteger(amountMinor)||amountMinor<0)throw RangeError('invalid refund amount'); + const methods:RefundTenderMethod[]=['cash','external_card','manual_upi']; + for(const p of [...paid,...refunded])if(!methods.includes(p.method)||!Number.isSafeInteger(p.amountMinor)||p.amountMinor<0)throw RangeError('invalid tender balance'); + const available=methods.map(method=>({method,capacity:paid.filter(p=>p.method===method).reduce((s,p)=>s+BigInt(p.amountMinor),0n)-refunded.filter(p=>p.method===method).reduce((s,p)=>s+BigInt(p.amountMinor),0n)})).map(p=>({...p,capacity:p.capacity>0n?p.capacity:0n})); + const total=available.reduce((s,p)=>s+p.capacity,0n),target=BigInt(amountMinor); + if(target>total)throw RangeError('REFUND_TENDER_CAPACITY'); + if(!target)return []; + const parts=available.map(p=>({...p,amount:target*p.capacity/total,remainder:target*p.capacity%total})); + let left=target-parts.reduce((s,p)=>s+p.amount,0n); + for(const p of [...parts].sort((a,b)=>a.remainder>b.remainder?-1:a.remainder0n&&p.amountp.amount>0n).map(p=>({method:p.method,amountMinor:Number(p.amount)})); +} diff --git a/tests/route-policy.mjs b/tests/route-policy.mjs index 3dc21dec..519ecad4 100644 --- a/tests/route-policy.mjs +++ b/tests/route-policy.mjs @@ -35,7 +35,7 @@ export const routePolicy=Object.fromEntries(Object.entries({ ], 'sales:create':['POST /checkout','POST /checkout/quote','POST /orders/:id/receipt-shares','POST /orders/:id/receipt-shares/revoke','POST /orders/:id/receipt-shares/email','GET /customers','POST /customers','GET /customers/:id'], 'sales:read':['PATCH /customers/:id','GET /orders','GET /orders/:id','GET /orders/:id/receipt'], - 'sales:refund':['POST /orders/:id/returns','POST /orders/:id/return-reviews','POST /offline-recovery/reviews'], + 'sales:refund':['POST /orders/:id/returns','POST /orders/:id/return-quote','POST /orders/:id/return-reviews','POST /offline-recovery/reviews'], 'register:open':['GET /register-sessions','POST /register-sessions/open','GET /register-sessions/active','POST /register-sessions/:id/drawer-open','POST /display-pairs','POST /display-pairs/:id/publish','POST /display-pairs/:id/revoke'], 'register:close':[ 'GET /register-sessions/:id/summary','GET /register-sessions/:id/cash-movements','POST /register-sessions/:id/cash-movements', diff --git a/tests/staging-aggregate.sql b/tests/staging-aggregate.sql index dc64fdc1..c3d1c4d7 100644 --- a/tests/staging-aggregate.sql +++ b/tests/staging-aggregate.sql @@ -23,9 +23,9 @@ SELECT AND o.status IN ('completed','partially_returned','returned') AND p.method='cash'),0) + COALESCE((SELECT SUM(c.amount_minor) FROM cash_movements c WHERE c.organization_id=r.organization_id AND c.register_session_id=r.id),0) - - COALESCE((SELECT SUM(f.amount_minor) FROM refunds f + - COALESCE((SELECT SUM(rp.amount_minor) FROM refund_payouts rp JOIN refunds f ON f.id=rp.refund_id JOIN orders o ON o.id=f.order_id - WHERE f.organization_id=r.organization_id AND f.method='cash' + WHERE f.organization_id=r.organization_id AND rp.method='cash' AND (f.cash_session_id=r.id OR (f.cash_session_id IS NULL AND o.register_session_id=r.id))),0) ) diff --git a/tests/staging-post-migration.sql b/tests/staging-post-migration.sql index fe7203f9..7e7052df 100644 --- a/tests/staging-post-migration.sql +++ b/tests/staging-post-migration.sql @@ -20,4 +20,6 @@ SELECT CASE WHEN EXISTS ( SELECT 1 FROM variant_scan_codes GROUP BY organization_id,scan_key HAVING COUNT(DISTINCT variant_id)>1 ) OR EXISTS ( SELECT 1 FROM stock_balances b JOIN variants v ON v.id=b.variant_id AND v.organization_id=b.organization_id WHERE v.track_stock=0 AND b.quantity<>0 +) OR EXISTS ( + SELECT 1 FROM refunds r LEFT JOIN refund_payouts rp ON rp.refund_id=r.id GROUP BY r.id HAVING COALESCE(SUM(rp.amount_minor),0)<>r.amount_minor ) THEN 1 ELSE 0 END AS violations; From 4c28a651bd6bbe3ae1a178cdf98bbfa47f98bfde Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Sun, 6 Dec 2026 00:24:51 -0500 Subject: [PATCH 05/10] Fix return request line mapping and rehearse all pending migrations --- apps/web/src/features/merchant/Orders.tsx | 2 +- tests/test_d1_restore_drill.py | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/apps/web/src/features/merchant/Orders.tsx b/apps/web/src/features/merchant/Orders.tsx index e753054f..af0e3801 100644 --- a/apps/web/src/features/merchant/Orders.tsx +++ b/apps/web/src/features/merchant/Orders.tsx @@ -133,7 +133,7 @@ function ReturnDialog({ order, open, onClose, pending }: { order: Order; open: b registerSessionId = active.id; setCashShiftId(registerSessionId); } - const body:ReturnBody={idempotencyKey:key,registerSessionId:registerSessionId??undefined,reason,restock,refundTender:tender,attestedByCashier:needsAttestation?manuallyConfirmed:undefined,lines:quoteItems,...(mode==='live'&"e?{expectedRefundMinor:quote.amountMinor,expectedPayouts:quote.payouts}:{})}; + const body:ReturnBody={idempotencyKey:key,registerSessionId:registerSessionId??undefined,reason,restock,refundTender:tender,attestedByCashier:needsAttestation?manuallyConfirmed:undefined,lines:quoteItems.map(({orderItemId,...line})=>({orderLineId:orderItemId,...line})),...(mode==='live'&"e?{expectedRefundMinor:quote.amountMinor,expectedPayouts:quote.payouts}:{})}; if(mode==='live'){ const row=await putPendingReturn({accountId,organizationId},order,body);saved.current=row; const result=await api.returnOrder(order.id,body); diff --git a/tests/test_d1_restore_drill.py b/tests/test_d1_restore_drill.py index a948b826..994ea00b 100644 --- a/tests/test_d1_restore_drill.py +++ b/tests/test_d1_restore_drill.py @@ -105,13 +105,13 @@ def test_corrupt_sql_fails(self): module.run(self.sql) class PopulatedUpgradeTests(unittest.TestCase): - def test_real_0028_to_0037_with_stock_and_barcode(self): + def test_real_0028_to_current_with_stock_and_barcode(self): import json migrations=sorted(pathlib.Path('apps/api/migrations').glob('*.sql')) before=[p for p in migrations if int(p.name[:4])<=28] - pending=[p for p in migrations if 28 Date: Sun, 6 Dec 2026 00:33:31 -0500 Subject: [PATCH 06/10] Prepare sale and return without posting; commit exchanges atomically with paired recovery fences --- .github/workflows/worker-e2e.yml | 2 +- apps/api/migrations/0041_atomic_exchanges.sql | 26 ++++ apps/api/src/sales.ts | 121 ++++++++++++++++-- apps/web/e2e-worker/exchanges.spec.ts | 24 ++++ .../register-m3-atomic-exchanges.md | 2 + tests/route-policy.mjs | 4 +- 6 files changed, 162 insertions(+), 17 deletions(-) create mode 100644 apps/api/migrations/0041_atomic_exchanges.sql create mode 100644 apps/web/e2e-worker/exchanges.spec.ts create mode 100644 docs/operations/register-m3-atomic-exchanges.md diff --git a/.github/workflows/worker-e2e.yml b/.github/workflows/worker-e2e.yml index a5466491..d109794d 100644 --- a/.github/workflows/worker-e2e.yml +++ b/.github/workflows/worker-e2e.yml @@ -16,7 +16,7 @@ jobs: strategy: fail-fast: false matrix: - suite: [merchant, contracts, recovery, integrity, roles, transfers, auth, money, woo, offline, cash-integrity, ops-load, catalog-import, register-catalog, return-recovery, receipt-shares, display-pairs, refund-payouts] + suite: [merchant, contracts, recovery, integrity, roles, transfers, auth, money, woo, offline, cash-integrity, ops-load, catalog-import, register-catalog, return-recovery, receipt-shares, display-pairs, refund-payouts, exchanges] timeout-minutes: 20 steps: - uses: actions/checkout@v4 diff --git a/apps/api/migrations/0041_atomic_exchanges.sql b/apps/api/migrations/0041_atomic_exchanges.sql new file mode 100644 index 00000000..69ced131 --- /dev/null +++ b/apps/api/migrations/0041_atomic_exchanges.sql @@ -0,0 +1,26 @@ +-- Atomic exchange link; the existing checkout and refund fences guard both legs. +CREATE TABLE exchanges ( + id TEXT PRIMARY KEY, + organization_id TEXT NOT NULL REFERENCES organizations(id), + original_order_id TEXT NOT NULL REFERENCES orders(id), + replacement_order_id TEXT NOT NULL UNIQUE REFERENCES orders(id), + refund_id TEXT NOT NULL UNIQUE REFERENCES refunds(id), + actor_id TEXT NOT NULL REFERENCES users(id), + request_key TEXT NOT NULL, + request_hash TEXT NOT NULL, + response_json TEXT NOT NULL, + created_at INTEGER NOT NULL, + UNIQUE(organization_id,request_key), + CHECK(original_order_id<>replacement_order_id) +); +CREATE INDEX exchanges_original_idx ON exchanges(organization_id,original_order_id); +CREATE TRIGGER exchange_link_guard BEFORE INSERT ON exchanges BEGIN + SELECT RAISE(ABORT,'EXCHANGE_SCOPE_MISMATCH') WHERE NOT EXISTS( + SELECT 1 FROM orders orig JOIN orders repl ON repl.id=NEW.replacement_order_id AND repl.organization_id=orig.organization_id AND repl.store_id=orig.store_id AND repl.currency=orig.currency + JOIN refunds f ON f.id=NEW.refund_id AND f.organization_id=orig.organization_id AND f.order_id=orig.id + JOIN idempotency_keys ck ON ck.organization_id=orig.organization_id AND ck.key=NEW.request_key AND json_extract(ck.response,'$.data.id')=repl.id + JOIN refund_request_keys rk ON rk.organization_id=orig.organization_id AND rk.key=NEW.request_key AND rk.refund_id=f.id + WHERE orig.id=NEW.original_order_id AND orig.organization_id=NEW.organization_id); +END; +CREATE TRIGGER exchange_no_update BEFORE UPDATE ON exchanges BEGIN SELECT RAISE(ABORT,'EXCHANGE_IMMUTABLE'); END; +CREATE TRIGGER exchange_no_delete BEFORE DELETE ON exchanges BEGIN SELECT RAISE(ABORT,'EXCHANGE_IMMUTABLE'); END; diff --git a/apps/api/src/sales.ts b/apps/api/src/sales.ts index 14ef1c2d..562b1497 100644 --- a/apps/api/src/sales.ts +++ b/apps/api/src/sales.ts @@ -13,7 +13,7 @@ import { quoteSale, type SaleVariant, } from '@storefront/domain'; -import { checkoutRequestSchema, checkoutQuoteRequestSchema, type CheckoutQuoteRequest } from '@storefront/contracts'; +import { checkoutRequestSchema, checkoutQuoteRequestSchema, type CheckoutQuoteRequest, type CheckoutRequest } from '@storefront/contracts'; import type { AppEnv, ApiContext } from './types'; import { asData, apiId, now, fail, jsonBody, pageLimit, parseBody, principal, requirePermission, sqlError } from './types'; import { pepper, sha256 } from './security'; @@ -415,11 +415,8 @@ sales.post('/checkout/quote',async c=>{ return c.json(asData({quoteToken:expiresAt+'.'+sig,expiresAt,currency:quote!.currency,cashRoundingMinor:rounding,...quote!.totals,lines:quote!.lines.map(l=>({variantId:l.variantId,quantity:l.quantity,unitPriceMinor:l.unitPriceMinor,discountMinor:l.discountMinor,taxMinor:l.taxMinor,taxMode:l.taxMode,totalMinor:l.totalMinor}))})); }); -sales.post('/checkout', async c => { +async function prepareCheckout(c:ApiContext,body:CheckoutRequest){ const p = requirePermission(c,'sales:create'); - const body = parseBody(await jsonBody(c), checkoutRequestSchema); - if (c.req.header('Idempotency-Key') !== body.idempotencyKey) - fail('IDEMPOTENCY_REQUIRED', 'Idempotency-Key header must match request body.', 422); const tenders = body.tenders ?? [body.tender!]; for (const t of tenders) { if (t.method !== 'cash' && t.attestedByCashier !== true) @@ -433,7 +430,7 @@ sales.post('/checkout', async c => { .bind(p.organizationId, body.idempotencyKey).first<{ hash: string; response: string }>(); if (prior) { if (prior.hash !== hash) fail('DUPLICATE_IDEMPOTENCY_CONFLICT', 'The idempotency key was used for another request.', 409); - return c.json(JSON.parse(prior.response)); + return {kind:'replay' as const,response:JSON.parse(prior.response)}; } const hasDiscount = body.lines.some(line => (line.discountMinor ?? 0) > 0); let override: { id: string; managerId: string } | null = null; @@ -554,6 +551,16 @@ sales.post('/checkout', async c => { statements.push(c.env.DB.prepare('INSERT INTO audit_log(id,organization_id,actor_id,action,target_id,detail_json,created_at) VALUES(?,?,?,?,?,?,?)') .bind(apiId(), p.organizationId, p.userId, 'sale.discount_overridden', orderId, JSON.stringify({ managerId: override.managerId, discountMinor: quote!.totals.discountMinor }), timestamp)); } + return {kind:'plan' as const,p,session,hash,statements,orderId,responsePayload,responseEnvelope,payments:quote!.appliedPayments}; +} + +sales.post('/checkout',async c=>{ + requirePermission(c,'sales:create'); + const body=parseBody(await jsonBody(c),checkoutRequestSchema); + if(c.req.header('Idempotency-Key')!==body.idempotencyKey)fail('IDEMPOTENCY_REQUIRED','Idempotency-Key header must match request body.',422); + const prepared=await prepareCheckout(c,body); + if(prepared.kind==='replay')return c.json(prepared.response); + const {p,session,hash,statements,orderId,responsePayload,responseEnvelope}=prepared; try { await c.env.DB.batch(statements); } catch (err) { const competing = await c.env.DB.prepare('SELECT request_hash AS hash,response FROM idempotency_keys WHERE organization_id=? AND key=?') .bind(p.organizationId, body.idempotencyKey).first<{ hash: string; response: string }>(); @@ -730,19 +737,16 @@ sales.post('/orders/:id/return-quote',async c=>{ return c.json(asData(await returnPayable(c,order,body.items,true))); }); -sales.post('/orders/:id/returns', async c => { - const actor = principal(c), orderId = c.req.param('id'); - const schema = z.object({ +const returnRequestSchema=z.object({ idempotencyKey: id, registerSessionId: id.optional(), overrideToken: z.string().min(16).max(256).optional(), reason: z.string().trim().min(3).max(250), method: z.enum(['cash', 'external_card', 'manual_upi','original']), attestedByCashier: z.boolean().optional(), expectedRefundMinor:minor.optional(),expectedPayouts:z.array(payoutSchema).max(3).optional(), items:returnItemsSchema, - }); - const body = parseBody(await jsonBody(c), schema); - if (c.req.header('Idempotency-Key') !== body.idempotencyKey) - fail('IDEMPOTENCY_REQUIRED', 'Refund requires matching Idempotency-Key header and body.', 422); +}); +async function prepareReturn(c:ApiContext,orderId:string,body:z.infer){ + const actor=principal(c); if (body.method === 'cash' && !body.registerSessionId) fail('REFUND_REGISTER_REQUIRED', 'An open register session is required for a cash refund.', 422); if (body.method !== 'cash' && body.method !== 'original' && body.attestedByCashier !== true) @@ -767,7 +771,7 @@ sales.post('/orders/:id/returns', async c => { } else { requirePermission(c,'sales:refund'); } - return c.json(JSON.parse(previous.response)); + return {kind:'replay' as const,response:JSON.parse(previous.response)}; } let override: { id: string; managerId: string } | null = null; if (actor.role === 'cashier' && body.overrideToken) { @@ -851,6 +855,16 @@ sales.post('/orders/:id/returns', async c => { ).bind(apiId(), p.organizationId, p.userId, 'sale.refunded', order.id, JSON.stringify({ refundId, amountMinor: totalMinor, taxMinor: taxRefundMinor, payouts,roundingMinor:payable.roundingMinor,verification: 'cashier_attested', overrideActorId: override?.managerId ?? null }), timestamp)); if (override) stmts.push(c.env.DB.prepare('UPDATE override_tokens SET used_at=? WHERE id=?').bind(timestamp, override.id)); + return {kind:'plan' as const,p,order,refundId,response,stmts,hash,loadPrior,fenceKey,payouts}; +} + +sales.post('/orders/:id/returns',async c=>{ + if(principal(c).role!=='cashier')requirePermission(c,'sales:refund'); + const body=parseBody(await jsonBody(c),returnRequestSchema); + if(c.req.header('Idempotency-Key')!==body.idempotencyKey)fail('IDEMPOTENCY_REQUIRED','Refund requires matching Idempotency-Key header and body.',422); + const prepared=await prepareReturn(c,c.req.param('id'),body); + if(prepared.kind==='replay')return c.json(prepared.response); + const {p,response,stmts,hash,loadPrior,fenceKey}=prepared; try { await c.env.DB.batch(stmts); } catch (err) { const competing = await loadPrior(); if (competing) { @@ -894,6 +908,85 @@ sales.post('/orders/:id/return-reviews',async c=>{ return c.json(asData({id:reviewId,alreadyReviewed:false}),201); }); + +const exchangeSchema=z.object({ + idempotencyKey:id,items:returnItemsSchema,reason:z.string().trim().min(3).max(250), + expectedRefundMinor:minor,expectedPayouts:z.array(payoutSchema).max(3), + replacement:checkoutRequestSchema,settlementConfirmed:z.literal(true),externalSettlementAttested:z.boolean().optional() +}); +sales.post('/orders/:id/exchanges',async c=>{ + const p=requirePermission(c,'sales:refund');requirePermission(c,'sales:create'); + const orderId=c.req.param('id'),body=parseBody(await jsonBody(c),exchangeSchema); + if(c.req.header('Idempotency-Key')!==body.idempotencyKey||body.replacement.idempotencyKey!==body.idempotencyKey) + fail('IDEMPOTENCY_REQUIRED','Exchange and replacement quote must use the same immutable request reference.',422); + const hash=await sha256(JSON.stringify({orderId,...body})); + const load=()=>c.env.DB.prepare('SELECT request_hash AS hash,response_json AS response FROM exchanges WHERE organization_id=? AND request_key=?').bind(p.organizationId,body.idempotencyKey).first<{hash:string;response:string}>(); + const replay=await load(); + if(replay){if(replay.hash!==hash)fail('DUPLICATE_IDEMPOTENCY_CONFLICT','Exchange reference already used with different details.',409);return c.json(JSON.parse(replay.response));} + if(!body.replacement.quoteToken||body.replacement.expectedPayableMinor===undefined)fail('EXCHANGE_QUOTE_REQUIRED','A signed replacement quote is required.',422); + if(body.items.length+body.replacement.lines.length>50)fail('EXCHANGE_TOO_LARGE','An exchange can contain at most 50 total return and replacement lines.',422); + const replacement=await prepareCheckout(c,body.replacement); + if(replacement.kind==='replay')fail('EXCHANGE_REFERENCE_USED','Replacement reference has already been used outside this exchange.',409); + const returned=await prepareReturn(c,orderId,{ + idempotencyKey:body.idempotencyKey,registerSessionId:body.replacement.registerSessionId,reason:body.reason,method:'original', + items:body.items,expectedRefundMinor:body.expectedRefundMinor,expectedPayouts:body.expectedPayouts,attestedByCashier:body.externalSettlementAttested + }); + if(returned.kind==='replay')fail('EXCHANGE_REFERENCE_USED','Return reference has already been used outside this exchange.',409); + if(replacement.session.storeId!==returned.order.storeId||replacement.responsePayload.currency!==returned.order.currency) + fail('EXCHANGE_SCOPE_MISMATCH','Replacement must use an open register at the original store and the same currency.',409); + if(replacement.payments.some(t=>t.changeMinor>0))fail('EXCHANGE_CHANGE_NOT_ALLOWED','Use exact replacement payment amounts. Cash difference is settled separately.',422); + if((replacement.payments.some(t=>t.method!=='cash'&&t.amountMinor>0)||returned.payouts.some(t=>t.method!=='cash'&&t.amountMinor>0))&&body.externalSettlementAttested!==true) + fail('ATTESTATION_REQUIRED','Confirm the actual external refunds and replacement charges; Storefront does not move money.',422); + const exchangeId=apiId(),timestamp=now(); + const cashNetMinor=replacement.payments.filter(t=>t.method==='cash').reduce((a,t)=>a+t.amountMinor,0)-returned.payouts.filter(t=>t.method==='cash').reduce((a,t)=>a+t.amountMinor,0); + const payload=asData({id:exchangeId,originalOrderId:orderId,refund:returned.response.data,replacement:replacement.responsePayload,cashNetMinor,createdAt:timestamp}); + try{ + // Sale first, then refund: the drawer guard observes the exact net cash effect + // of the two recorded gross legs. Neither can commit alone. + await c.env.DB.batch([...replacement.statements,...returned.stmts, + c.env.DB.prepare(`INSERT INTO exchanges(id,organization_id,original_order_id,replacement_order_id,refund_id,actor_id,request_key,request_hash,response_json,created_at) + VALUES(?,?,?,?,?,?,?,?,json_set(?,'$.data.replacement.orderNumber',(SELECT order_number FROM orders WHERE id=?)),?)`) + .bind(exchangeId,p.organizationId,orderId,replacement.orderId,returned.refundId,p.userId,body.idempotencyKey,hash,JSON.stringify(payload),replacement.orderId,timestamp), + c.env.DB.prepare('INSERT INTO audit_log(id,organization_id,actor_id,action,target_id,detail_json,created_at) VALUES(?,?,?,?,?,?,?)') + .bind(apiId(),p.organizationId,p.userId,'sale.exchanged',exchangeId,JSON.stringify({originalOrderId:orderId,replacementOrderId:replacement.orderId,refundId:returned.refundId,cashNetMinor}),timestamp) + ]); + }catch(err){ + const concurrent=await load();if(concurrent){if(concurrent.hash!==hash)fail('DUPLICATE_IDEMPOTENCY_CONFLICT','Exchange reference already used.',409);return c.json(JSON.parse(concurrent.response));} + sqlError(err); + } + const committed=await load();if(!committed)fail('EXCHANGE_RESULT_UNAVAILABLE','Exchange outcome unavailable; retry this exact request.',503); + return c.json(JSON.parse(committed.response),201); +}); +sales.get('/orders/:id/exchanges',async c=>{ + const p=requirePermission(c,'sales:read'),orderId=c.req.param('id');await loadOrder(c,orderId); + const rows=await c.env.DB.prepare(`SELECT e.id,e.original_order_id AS originalOrderId,e.replacement_order_id AS replacementOrderId,e.refund_id AS refundId,e.created_at AS createdAt, + orig.order_number AS originalOrderNumber,repl.order_number AS replacementOrderNumber + FROM exchanges e JOIN orders orig ON orig.id=e.original_order_id AND orig.organization_id=e.organization_id JOIN orders repl ON repl.id=e.replacement_order_id AND repl.organization_id=e.organization_id + WHERE e.organization_id=? AND (e.original_order_id=? OR e.replacement_order_id=?) ORDER BY e.created_at DESC LIMIT 100`).bind(p.organizationId,orderId,orderId).all(); + return c.json(asData(rows.results)); +}); +sales.post('/orders/:id/exchange-reviews',async c=>{ + const p=requirePermission(c,'sales:refund');requirePermission(c,'sales:create'); + const orderId=c.req.param('id'),body=parseBody(await jsonBody(c),z.object({idempotencyKey:id,resolution:z.enum(['settlement_not_made','settlement_reconciled_outside_storefront']),note:z.string().trim().min(12).max(600)})); + if(c.req.header('Idempotency-Key')!==body.idempotencyKey)fail('IDEMPOTENCY_REQUIRED','Use the original exchange reference.',422); + await loadOrder(c,orderId); + const key=body.idempotencyKey,refundKey='refund:'+key,detail=JSON.stringify({orderId,...body}); + const findCommitted=()=>c.env.DB.prepare('SELECT 1 AS found FROM idempotency_keys WHERE organization_id=? AND key=? UNION ALL SELECT 1 FROM refund_request_keys WHERE organization_id=? AND key=? LIMIT 1').bind(p.organizationId,key,p.organizationId,key).first(); + const findReview=()=>c.env.DB.prepare("SELECT id,detail_json AS detail FROM audit_log WHERE organization_id=? AND action='exchange.recovery_reviewed' AND target_id=? LIMIT 1").bind(p.organizationId,key).first<{id:string;detail:string}>(); + if(await findCommitted())fail('EXCHANGE_ALREADY_RECORDED','A transaction leg exists. Recover and reconcile it; do not abandon the reference.',409); + const prior=await findReview();if(prior){if(prior.detail!==detail)fail('RECOVERY_REVIEW_CONFLICT','Exchange reference reviewed differently.',409);return c.json(asData({id:prior.id,alreadyReviewed:true}));} + const reviewId=apiId(),timestamp=now(); + try{await c.env.DB.batch([ + c.env.DB.prepare("INSERT INTO checkout_key_fences(organization_id,request_key,kind,created_at) VALUES(?,?,'review',?)").bind(p.organizationId,key,timestamp), + c.env.DB.prepare("INSERT INTO checkout_key_fences(organization_id,request_key,kind,created_at) VALUES(?,?,'review',?)").bind(p.organizationId,refundKey,timestamp), + c.env.DB.prepare('INSERT INTO audit_log(id,organization_id,actor_id,action,target_id,detail_json,created_at) VALUES(?,?,?,?,?,?,?)').bind(reviewId,p.organizationId,p.userId,'exchange.recovery_reviewed',key,detail,timestamp) + ]);}catch(err){ + if(await findCommitted())fail('EXCHANGE_ALREADY_RECORDED','A transaction leg exists. Recover the original reference.',409); + const again=await findReview();if(again&&again.detail===detail)return c.json(asData({id:again.id,alreadyReviewed:true}));sqlError(err); + } + return c.json(asData({id:reviewId,alreadyReviewed:false}),201); +}); + sales.get('/reports/summary', async c => { const p = requirePermission(c,'reports:read'), storeId = c.req.query('storeId') ?? ''; const from = Number(c.req.query('from') ?? 0), to = Number(c.req.query('to') ?? now() + 1); diff --git a/apps/web/e2e-worker/exchanges.spec.ts b/apps/web/e2e-worker/exchanges.spec.ts new file mode 100644 index 00000000..86434f15 --- /dev/null +++ b/apps/web/e2e-worker/exchanges.spec.ts @@ -0,0 +1,24 @@ +import {expect,test} from '@playwright/test'; +import {registerMerchant,createStockedVariant,openRegister,post,get,checkoutPayload} from './support'; +test('exchange commits linked sale and refund exactly once and rolls back stale or fenced attempts',async({request})=>{ + const m=await registerMerchant(request,'Atomic Exchange'),orig=await createStockedVariant(request,m,2),next=await createStockedVariant(request,m,2),shift=await openRegister(request,m,0); + const sold=checkoutPayload(shift,orig,2),sale=await post<{data:{id:string}}>(request,'/checkout',sold,m,201,sold.idempotencyKey),path='/orders/'+sale.data.id; + const order=await get<{data:{items:Array<{id:string}>}}>(request,path),items=[{orderItemId:order.data.items[0]!.id,quantity:1,restock:true}]; + const q=await post<{data:{amountMinor:number;payouts:unknown[]}}>(request,path+'/return-quote',{items},m,200); + const key=crypto.randomUUID(),lines=[{variantId:next,quantity:1}],quote=await post<{data:{quoteToken:string;totalMinor:number}}>(request,'/checkout/quote',{idempotencyKey:key,registerSessionId:shift,lines},m,200); + const body={idempotencyKey:key,items,reason:'Size exchange',expectedRefundMinor:q.data.amountMinor,expectedPayouts:q.data.payouts,settlementConfirmed:true,replacement:{idempotencyKey:key,registerSessionId:shift,lines,quoteToken:quote.data.quoteToken,expectedPayableMinor:quote.data.totalMinor,tender:{method:'cash',amountMinor:quote.data.totalMinor}}}; + await post(request,path+'/exchanges',{...body,expectedRefundMinor:q.data.amountMinor+1},m,409,key); + expect((await get<{data:{orderCount:number;refundedMinor:number}}>(request,'/reports/summary')).data).toMatchObject({orderCount:1,refundedMinor:0}); + type E={data:{id:string;replacement:{id:string;orderNumber:string};refund:{id:string};cashNetMinor:number}}; + const a=await post(request,path+'/exchanges',body,m,201,key),b=await post(request,path+'/exchanges',body,m,200,key); + expect(a.data).toEqual(b.data);expect(a.data.cashNetMinor).toBe(0);expect(a.data.replacement.orderNumber).not.toBe(''); + expect((await get<{data:unknown[]}>(request,path+'/exchanges')).data).toHaveLength(1); + expect((await get<{data:unknown[]}>(request,'/orders/'+a.data.replacement.id+'/exchanges')).data).toHaveLength(1); + expect((await get<{data:{orderCount:number;refundedMinor:number}}>(request,'/reports/summary')).data).toMatchObject({orderCount:2,refundedMinor:2500}); + expect((await get<{data:{expectedCashMinor:number}}>(request,'/register-sessions/'+shift+'/summary')).data.expectedCashMinor).toBe(5000); + const key2=crypto.randomUUID(),q2=await post<{data:{quoteToken:string;totalMinor:number}}>(request,'/checkout/quote',{idempotencyKey:key2,registerSessionId:shift,lines},m,200); + const second={...body,idempotencyKey:key2,replacement:{...body.replacement,idempotencyKey:key2,quoteToken:q2.data.quoteToken}}; + await post(request,path+'/exchange-reviews',{idempotencyKey:key2,resolution:'settlement_not_made',note:'Verified with operator that settlement was not made.'},m,201,key2); + await post(request,path+'/exchanges',second,m,409,key2); + expect((await get<{data:{orderCount:number;refundedMinor:number}}>(request,'/reports/summary')).data).toMatchObject({orderCount:2,refundedMinor:2500}); +}); diff --git a/docs/operations/register-m3-atomic-exchanges.md b/docs/operations/register-m3-atomic-exchanges.md new file mode 100644 index 00000000..d32a4ebf --- /dev/null +++ b/docs/operations/register-m3-atomic-exchanges.md @@ -0,0 +1,2 @@ +# M3 atomic exchange transaction +Manager-authorized same-store, same-currency exchanges use the existing signed replacement quote and original-tender refund quote. The sale and refund are prepared without posting, then committed in a single D1 batch along with the immutable exchange link and audit event. Cash is settled as the difference between gross sale and gross refund; external card/UPI refund and replacement charge must actually be performed and attested separately. No provider payment is initiated. Replacement stock must already be available, including if the returned SKU is also selected. The existing price, inventory, COGS, refund quantity, drawer and request fences remain active. Recovery replays the whole request, not either leg. Review fences both keys if both settlement legs have been reconciled; cannot review a committed leg. Requires cashier UI/recovery acceptance, mixed-tender and fault/concurrency tests, and the protected migration gate before activation. diff --git a/tests/route-policy.mjs b/tests/route-policy.mjs index 519ecad4..4027a2b0 100644 --- a/tests/route-policy.mjs +++ b/tests/route-policy.mjs @@ -34,8 +34,8 @@ export const routePolicy=Object.fromEntries(Object.entries({ 'POST /suppliers','PATCH /suppliers/:id','POST /purchase-orders','POST /purchase-orders/:id/receive' ], 'sales:create':['POST /checkout','POST /checkout/quote','POST /orders/:id/receipt-shares','POST /orders/:id/receipt-shares/revoke','POST /orders/:id/receipt-shares/email','GET /customers','POST /customers','GET /customers/:id'], - 'sales:read':['PATCH /customers/:id','GET /orders','GET /orders/:id','GET /orders/:id/receipt'], - 'sales:refund':['POST /orders/:id/returns','POST /orders/:id/return-quote','POST /orders/:id/return-reviews','POST /offline-recovery/reviews'], + 'sales:read':['PATCH /customers/:id','GET /orders','GET /orders/:id','GET /orders/:id/receipt','GET /orders/:id/exchanges'], + 'sales:refund':['POST /orders/:id/returns','POST /orders/:id/return-quote','POST /orders/:id/return-reviews','POST /orders/:id/exchanges','POST /orders/:id/exchange-reviews','POST /offline-recovery/reviews'], 'register:open':['GET /register-sessions','POST /register-sessions/open','GET /register-sessions/active','POST /register-sessions/:id/drawer-open','POST /display-pairs','POST /display-pairs/:id/publish','POST /display-pairs/:id/revoke'], 'register:close':[ 'GET /register-sessions/:id/summary','GET /register-sessions/:id/cash-movements','POST /register-sessions/:id/cash-movements', From 2c64facbddd658e8eeb8a2645ee461ece6342b5f Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Sun, 6 Dec 2026 00:39:48 -0500 Subject: [PATCH 07/10] Exercise prepared exchange reload and lost-response replay in real browser --- .github/workflows/worker-e2e.yml | 2 +- apps/web/e2e-worker/exchanges-ui.spec.ts | 37 ++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 apps/web/e2e-worker/exchanges-ui.spec.ts diff --git a/.github/workflows/worker-e2e.yml b/.github/workflows/worker-e2e.yml index d109794d..df954905 100644 --- a/.github/workflows/worker-e2e.yml +++ b/.github/workflows/worker-e2e.yml @@ -16,7 +16,7 @@ jobs: strategy: fail-fast: false matrix: - suite: [merchant, contracts, recovery, integrity, roles, transfers, auth, money, woo, offline, cash-integrity, ops-load, catalog-import, register-catalog, return-recovery, receipt-shares, display-pairs, refund-payouts, exchanges] + suite: [merchant, contracts, recovery, integrity, roles, transfers, auth, money, woo, offline, cash-integrity, ops-load, catalog-import, register-catalog, return-recovery, receipt-shares, display-pairs, refund-payouts, exchanges, exchanges-ui] timeout-minutes: 20 steps: - uses: actions/checkout@v4 diff --git a/apps/web/e2e-worker/exchanges-ui.spec.ts b/apps/web/e2e-worker/exchanges-ui.spec.ts new file mode 100644 index 00000000..c51f3f99 --- /dev/null +++ b/apps/web/e2e-worker/exchanges-ui.spec.ts @@ -0,0 +1,37 @@ +import {expect,test} from '@playwright/test'; +import {registerMerchant,createStockedVariant,openRegister,checkoutPayload,post,get} from './support'; +test('prepared exchange survives reload; lost committed response replays one immutable exchange',async({page})=>{ + const m=await registerMerchant(page.request,'Exchange Browser Recovery'),orig=await createStockedVariant(page.request,m,1); + const replacement=await post<{data:{variantId:string}}>(page.request,'/products',{name:'Replacement Shirt',sku:'REPL-'+crypto.randomUUID().slice(0,8),priceMinor:2500,currency:'INR',taxRateBps:0},m); + await post(page.request,'/inventory/adjustments',{storeId:m.storeId,variantId:replacement.data.variantId,delta:1,reason:'Exchange test stock'},m); + const shift=await openRegister(page.request,m,0),sold=checkoutPayload(shift,orig),sale=await post<{data:{id:string}}>(page.request,'/checkout',sold,m,201,sold.idempotencyKey); + await page.goto('/pos');await expect(page.getByRole('button',{name:/Replacement Shirt/})).toBeVisible(); + await page.goto('/orders/'+sale.data.id);await page.getByRole('button',{name:'Exchange items',exact:true}).click(); + await page.getByLabel(/Return quantity/).fill('1'); + await page.getByLabel('Search replacement products').fill('Replacement Shirt'); + await page.getByRole('dialog').getByRole('button',{name:'Add',exact:true}).click(); + await page.getByRole('button',{name:'Verify exchange amounts'}).click(); + await page.getByRole('button',{name:'Save settlement intent'}).click(); + await expect(page.getByText('Settlement intent saved',{exact:true})).toBeVisible(); + await page.reload();await page.getByRole('button',{name:'Recover exchange',exact:true}).click(); + await expect(page.getByRole('button',{name:'Confirm settlement and record exchange'})).toBeDisabled(); + const refs:string[]=[];let aborted=false; + await page.route('**/api/v1/orders/*/exchanges',async route=>{ + if(route.request().method()!=='POST'){await route.continue();return;} + refs.push(route.request().headers()['idempotency-key']??''); + if(!aborted){aborted=true;const committed=await route.fetch();expect(committed.status()).toBe(201);await route.abort('failed');} + else await route.continue(); + }); + await page.getByRole('checkbox',{name:/I verified the exact net cash/}).check(); + await page.getByRole('button',{name:'Confirm settlement and record exchange'}).click(); + await expect(page.getByText('Saved confirmation — do not settle again',{exact:true})).toBeVisible(); + await expect.poll(()=>refs.length).toBe(1); + await expect.poll(async()=>(await get<{data:{orderCount:number}}>(page.request,'/reports/summary')).data.orderCount).toBe(2); + await page.reload();await page.getByRole('button',{name:'Recover exchange',exact:true}).click(); + await page.getByRole('button',{name:'Retry exact exchange'}).click(); + await expect(page.getByText('Exchange recorded atomically',{exact:true})).toBeVisible(); + expect(refs).toHaveLength(2);expect(new Set(refs).size).toBe(1);expect(refs[0]).toBeTruthy(); + const summary=await get<{data:{orderCount:number;refundedMinor:number}}>(page.request,'/reports/summary'); + expect(summary.data).toMatchObject({orderCount:2,refundedMinor:2500}); + expect((await get<{data:unknown[]}>(page.request,'/orders/'+sale.data.id+'/exchanges')).data).toHaveLength(1); +}); From 4e109387f8db9987cd8329b146eb137c536bc394 Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Sun, 6 Dec 2026 00:40:33 -0500 Subject: [PATCH 08/10] Supply required search icon in exchange product picker --- apps/web/src/features/merchant/ExchangeDialog.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/web/src/features/merchant/ExchangeDialog.tsx b/apps/web/src/features/merchant/ExchangeDialog.tsx index 950ad335..63930b4b 100644 --- a/apps/web/src/features/merchant/ExchangeDialog.tsx +++ b/apps/web/src/features/merchant/ExchangeDialog.tsx @@ -1,6 +1,7 @@ import {useEffect,useState} from 'react'; import {useMutation,useQueryClient} from '@tanstack/react-query'; import {Link} from 'react-router'; +import {Search} from 'lucide-react'; import {Banner,Button,Checkbox,Dialog,Field,Input,Panel,Select,SearchInput} from '@storefront/ui'; import {roundCashMinor} from '@storefront/domain'; import type {CheckoutQuote} from '@storefront/contracts'; @@ -107,7 +108,7 @@ export function ExchangeDialog({order,open,onClose,pending}:{order:Order;open:bo {corrupt?Do not settle again. Contact an authorized manager with the original reference.:null} {!row?<>Replacement items must already be in stock. The system records the return and replacement together; it does not initiate card or UPI transfers.
    {order.lines.map(l=>{const remaining=l.quantity-(l.returnedQuantity??0);return
  • {l.name}{remaining} returnable
    setQty(prev=>({...prev,[l.id]:Math.max(0,Math.min(remaining,Math.floor(Number(e.target.value)||0)))}))}/>{(qty[l.id]??0)>0?setRestock(prev=>({...prev,[l.id]:e.target.checked}))}/>:null}
  • ;})}
- setSearch(e.target.value)} disabled={locked}/>{!locked&&search.trim().length>=2?
    {(products.data??[]).slice(0,20).map(p=>
  • {p.name} · {p.sku}
  • )}
:null} + } aria-label="Search replacement products" placeholder="Search name, SKU or barcode" value={search} onChange={e=>setSearch(e.target.value)} disabled={locked}/>{!locked&&search.trim().length>=2?
    {(products.data??[]).slice(0,20).map(p=>
  • {p.name} · {p.sku}
  • )}
:null}
    {selected.map(p=>
  • {p.name}setSelected(prev=>prev.map(x=>x.variantId===p.variantId?{...x,quantity:Math.max(1,Math.min(100000,Math.floor(Number(e.target.value)||1)))}:x))}/>
  • )}
{products.isError?Product search unavailable. Reconnect and try again.:null}
setReason(e.target.value)}/> From 6d53e71c7b832a7a8220bcde983499bd01e554f8 Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Sun, 6 Dec 2026 00:41:40 -0500 Subject: [PATCH 09/10] Fence entire refund snapshot to prevent cross-line rounding races --- apps/api/src/sales.ts | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/apps/api/src/sales.ts b/apps/api/src/sales.ts index 562b1497..2cb8db78 100644 --- a/apps/api/src/sales.ts +++ b/apps/api/src/sales.ts @@ -727,14 +727,15 @@ async function returnPayable(c:ApiContext,order:Awaited[]).map(p=>({method:p.method as RefundPayout['method'],amountMinor:Number(p.amountMinor)})); try{payouts=allocateOriginalTenderRefund(amountMinor,paid,already.results);}catch{return fail('REFUND_TENDER_CAPACITY','Original tender balances cannot cover this refund; manager reconciliation is required.',409);} } - return {amountMinor,roundingMinor:amountMinor-rawMinor,payouts}; + return {amountMinor,roundingMinor:amountMinor-rawMinor,payouts,priorRefundMinor:Number(history?.amount??0)}; } sales.post('/orders/:id/return-quote',async c=>{ const p=requirePermission(c,'sales:refund'),body=parseBody(await jsonBody(c),z.object({items:returnItemsSchema})); const order=await loadOrder(c,c.req.param('id')); // loadOrder and role guard bind the quote to the current business. void p; - return c.json(asData(await returnPayable(c,order,body.items,true))); + const {amountMinor,roundingMinor,payouts}=await returnPayable(c,order,body.items,true); + return c.json(asData({amountMinor,roundingMinor,payouts})); }); const returnRequestSchema=z.object({ @@ -820,7 +821,17 @@ async function prepareReturn(c:ApiContext,orderId:string,body:z.infer({id,quantity}))),order.id,timestamp)); stmts.push(c.env.DB.prepare( 'INSERT INTO refunds(id,organization_id,order_id,actor_id,amount_minor,reason,method,cash_session_id,cogs_reversed_minor,created_at,rounding_minor) VALUES(?,?,?,?,?,?,?,?,?,?,?)' ).bind(refundId, p.organizationId, order.id, p.userId, totalMinor, body.reason, body.method, @@ -873,6 +884,7 @@ sales.post('/orders/:id/returns',async c=>{ } const fenced=await c.env.DB.prepare('SELECT kind FROM checkout_key_fences WHERE organization_id=? AND request_key=?').bind(p.organizationId,fenceKey).first<{kind:string}>(); if(fenced?.kind==='review')fail('REFUND_ALREADY_REVIEWED','This refund was reconciled by a manager. Do not repeat the payout.',409); + if(String(err).includes('CHECK constraint failed')&&String(err).includes('kind'))fail('REFUND_STALE','Another return changed the original order. Reconcile any payout before retrying.',409); sqlError(err); } return c.json(response, 201); From 8387a7b9832cb4d2d524509c4f76c119eecfc7ba Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Sun, 6 Dec 2026 00:42:34 -0500 Subject: [PATCH 10/10] Cover disjoint concurrent final-refund rounding on real D1 --- apps/web/e2e-worker/refund-payouts.spec.ts | 25 ++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/apps/web/e2e-worker/refund-payouts.spec.ts b/apps/web/e2e-worker/refund-payouts.spec.ts index 3dab91d8..92a11f4f 100644 --- a/apps/web/e2e-worker/refund-payouts.spec.ts +++ b/apps/web/e2e-worker/refund-payouts.spec.ts @@ -17,3 +17,28 @@ test('split refunds allocate exact original tender balances and cash drawer, wit expect((await get<{data:{expectedCashMinor:number;cashRefundMinor:number}}>(request,'/register-sessions/'+shift+'/summary')).data).toMatchObject({expectedCashMinor:0,cashRefundMinor:2000}); expect((await get<{data:{refundedMinor:number}}>(request,'/reports/summary')).data.refundedMinor).toBe(5000); }); + +test('disjoint concurrent refunds cannot lose the final cash-rounding adjustment',async({request})=>{ + const m=await registerMerchant(request,'Concurrent Rounded Returns'); + const setting=await request.patch('/api/v1/organization',{data:{cashRoundingMinor:5},headers:{'x-csrf-token':m.csrfToken}});expect(setting.status()).toBe(200); + const variants:string[]=[]; + for(const price of [2501,2502]){ + const p=await post<{data:{variantId:string}}>(request,'/products',{name:'Rounded test '+price,sku:'ROUND-'+crypto.randomUUID().slice(0,8),priceMinor:price,currency:'INR',taxRateBps:0},m); + variants.push(p.data.variantId);await post(request,'/inventory/adjustments',{storeId:m.storeId,variantId:p.data.variantId,delta:1,reason:'Rounding fixture'},m); + } + const shift=await openRegister(request,m,0),key=crypto.randomUUID(); + const sale=await post<{data:{id:string;totalMinor:number}}>(request,'/checkout',{idempotencyKey:key,registerSessionId:shift,lines:variants.map(variantId=>({variantId,quantity:1})),tender:{method:'cash',amountMinor:5005}},m,201,key); + expect(sale.data.totalMinor).toBe(5005); + const path='/orders/'+sale.data.id,order=await get<{data:{items:{id:string}[]}}>(request,path); + const entries=order.data.items.map(l=>[{orderItemId:l.id,quantity:1,restock:true}]); + type Q={data:{amountMinor:number;payouts:{method:string;amountMinor:number}[]}}; + const quotes=await Promise.all(entries.map(items=>post(request,path+'/return-quote',{items},m,200))); + const bodies=entries.map((items,i)=>({idempotencyKey:crypto.randomUUID(),registerSessionId:shift,method:'original',reason:'Concurrent rounded return',items,expectedRefundMinor:quotes[i]!.data.amountMinor,expectedPayouts:quotes[i]!.data.payouts})); + const attempts=await Promise.all(bodies.map(body=>request.post('/api/v1'+path+'/returns',{data:body,headers:{'x-csrf-token':m.csrfToken,'idempotency-key':body.idempotencyKey}}))); + expect(attempts.map(x=>x.status()).sort()).toEqual([201,409]); + const rejected=attempts.findIndex(x=>x.status()===409),remaining=entries[rejected]!; + const fresh=await post(request,path+'/return-quote',{items:remaining},m,200),retryKey=crypto.randomUUID(); + await post(request,path+'/returns',{...bodies[rejected],idempotencyKey:retryKey,expectedRefundMinor:fresh.data.amountMinor,expectedPayouts:fresh.data.payouts},m,201,retryKey); + expect((await get<{data:{refundedMinor:number}}>(request,'/reports/summary')).data.refundedMinor).toBe(5005); + expect((await get<{data:{expectedCashMinor:number;cashRefundMinor:number}}>(request,'/register-sessions/'+shift+'/summary')).data).toMatchObject({expectedCashMinor:0,cashRefundMinor:5005}); +});