diff --git a/.github/workflows/worker-e2e.yml b/.github/workflows/worker-e2e.yml index a546649..df95490 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, exchanges-ui] 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 0000000..69ced13 --- /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 14ef1c2..2cb8db7 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 }>(); @@ -720,29 +727,27 @@ 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})); }); -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 +772,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) { @@ -816,7 +821,17 @@ sales.post('/orders/:id/returns', async c => { taxMinor: taxRefundMinor, method: body.method, refundVerification: 'cashier_attested', 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)); + // Guard the whole original-order refund snapshot, not just the selected items. + // Otherwise concurrent disjoint returns can both miss the final rounding adjustment. + stmts.push(c.env.DB.prepare(`INSERT INTO checkout_key_fences(organization_id,request_key,kind,created_at) + VALUES(?,?,CASE WHEN EXISTS(SELECT 1 FROM orders WHERE id=? AND organization_id=? AND status IN ('completed','partially_returned')) + AND COALESCE((SELECT SUM(amount_minor) FROM refunds WHERE order_id=? AND organization_id=?),0)=? + AND NOT EXISTS(SELECT 1 FROM json_each(?) j WHERE NOT EXISTS( + SELECT 1 FROM order_items oi LEFT JOIN returned_quantities rq ON rq.order_item_id=oi.id + WHERE oi.order_id=? AND oi.id=json_extract(j.value,'$.id') AND COALESCE(rq.quantity,0)=json_extract(j.value,'$.quantity'))) + THEN 'checkout' ELSE 'stale_refund' END,?)`) + .bind(p.organizationId,fenceKey,order.id,p.organizationId,order.id,p.organizationId,payable.priorRefundMinor, + JSON.stringify([...returned].map(([id,quantity])=>({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, @@ -851,6 +866,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) { @@ -859,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); @@ -894,6 +920,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-ui.spec.ts b/apps/web/e2e-worker/exchanges-ui.spec.ts new file mode 100644 index 0000000..c51f3f9 --- /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); +}); diff --git a/apps/web/e2e-worker/exchanges.spec.ts b/apps/web/e2e-worker/exchanges.spec.ts new file mode 100644 index 0000000..7469526 --- /dev/null +++ b/apps/web/e2e-worker/exchanges.spec.ts @@ -0,0 +1,39 @@ +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}); +}); + +test('cash drawer rejection rolls back the replacement sale, refund and inventory together',async({request})=>{ + const m=await registerMerchant(request,'Exchange Batch Rollback'),orig=await createStockedVariant(request,m,1),next=await createStockedVariant(request,m,1),old=await openRegister(request,m,0); + const sold=checkoutPayload(old,orig),sale=await post<{data:{id:string}}>(request,'/checkout',sold,m,201,sold.idempotencyKey); + const closeKey=crypto.randomUUID();await post(request,'/register-sessions/'+old+'/close',{closingCashMinor:2500,idempotencyKey:closeKey},m,200,closeKey); + const shift=await openRegister(request,m,0),path='/orders/'+sale.data.id,order=await get<{data:{items:{id:string}[]}}>(request,path); + const items=[{orderItemId:order.data.items[0]!.id,quantity:1,restock:true}],refund=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:'Return for replacement',expectedRefundMinor:refund.data.amountMinor,expectedPayouts:refund.data.payouts,settlementConfirmed:true,externalSettlementAttested:true,replacement:{idempotencyKey:key,registerSessionId:shift,lines,quoteToken:quote.data.quoteToken,expectedPayableMinor:quote.data.totalMinor,tender:{method:'external_card',amountMinor:quote.data.totalMinor,attestedByCashier:true}}}; + await post(request,path+'/exchanges',body,m,409,key); + expect((await get<{data:{orderCount:number;refundedMinor:number}}>(request,'/reports/summary')).data).toMatchObject({orderCount:1,refundedMinor:0}); + const inventory=(await get<{data:{variantId:string;quantity:number}[]}>(request,'/inventory?storeId='+m.storeId)).data; + expect(inventory.find(x=>x.variantId===orig)?.quantity).toBe(0);expect(inventory.find(x=>x.variantId===next)?.quantity).toBe(1); + expect((await get<{data:unknown[]}>(request,path+'/exchanges')).data).toHaveLength(0); +}); diff --git a/apps/web/e2e-worker/refund-payouts.spec.ts b/apps/web/e2e-worker/refund-payouts.spec.ts index 3dab91d..92a11f4 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}); +}); diff --git a/apps/web/src/api/live.ts b/apps/web/src/api/live.ts index 247907a..e2ebe19 100644 --- a/apps/web/src/api/live.ts +++ b/apps/web/src/api/live.ts @@ -718,3 +718,16 @@ export const offlineRecoveryApi = { one<{ id: string; resolution: string; alreadyReviewed: boolean }>( '/api/v1/offline-recovery/reviews', { method: 'POST', json: body }), }; + +export type ExchangeRequest={ + idempotencyKey:string;items:{orderItemId:string;quantity:number;restock:boolean}[];reason:string; + expectedRefundMinor:number;expectedPayouts:import('./types').ReturnQuote['payouts']; + replacement:import('@storefront/contracts').CheckoutRequest;settlementConfirmed:true;externalSettlementAttested?:boolean; +}; +export type ExchangeResult={id:string;originalOrderId:string;replacement:{id:string;orderNumber:string;totalMinor:number};refund:{id:string;amountMinor:number};cashNetMinor:number}; +export type ExchangeLink={id:string;originalOrderId:string;replacementOrderId:string;originalOrderNumber:string;replacementOrderNumber:string;refundId:string;createdAt:number}; +export const exchangeApi={ + commit:(orderId:string,body:ExchangeRequest)=>one('/api/v1/orders/'+encodeURIComponent(orderId)+'/exchanges',{method:'POST',idempotencyKey:body.idempotencyKey,json:body}), + links:(orderId:string)=>one('/api/v1/orders/'+encodeURIComponent(orderId)+'/exchanges'), + review:(orderId:string,body:{idempotencyKey:string;resolution:'settlement_not_made'|'settlement_reconciled_outside_storefront';note:string})=>one<{id:string;alreadyReviewed:boolean}>('/api/v1/orders/'+encodeURIComponent(orderId)+'/exchange-reviews',{method:'POST',idempotencyKey:body.idempotencyKey,json:body}), +}; diff --git a/apps/web/src/features/merchant/ExchangeDialog.tsx b/apps/web/src/features/merchant/ExchangeDialog.tsx new file mode 100644 index 0000000..63930b4 --- /dev/null +++ b/apps/web/src/features/merchant/ExchangeDialog.tsx @@ -0,0 +1,123 @@ +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'; +import type {Order,ReturnQuote,TenderMethod} from '../../api'; +import {exchangeApi,fetchCheckoutQuote,fetchReturnQuote,type ExchangeRequest,type ExchangeResult} from '../../api/live'; +import {useSession} from '../../state/session'; +import {useMoney} from '../../components/useMoney'; +import {parseMajor} from '../../lib/money'; +import {newId} from '../../lib/format'; +import {describeError,type FriendlyError} from '../../lib/errors'; +import {offlineDB,pendingReturnKey,putPendingReturn,finishPendingReturn,type PendingReturn} from '../../lib/offline-db'; +import {tenderLabel} from '../../lib/receipt-text'; +import {useRemoteCatalog,type Sellable} from '../register/catalog'; +type SavedExchange={operation:'exchange';idempotencyKey:string;status:'prepared'|'confirmed';request:ExchangeRequest;labels:{name:string;quantity:number}[]}; +export function isPendingExchange(row:PendingReturn|null):boolean{ + if(!row)return false;try{return JSON.parse(row.bodyJson)?.operation==='exchange';}catch{return false;} +} +function decode(row:PendingReturn):SavedExchange{ + const body=JSON.parse(row.bodyJson) as SavedExchange; + if(body.operation!=='exchange'||body.idempotencyKey!==row.idempotencyKey||body.request?.idempotencyKey!==row.idempotencyKey||body.request.replacement?.idempotencyKey!==row.idempotencyKey||!['prepared','confirmed'].includes(body.status))throw Error('Saved exchange is inconsistent. Do not settle again.'); + return body; +} +type Verified={key:string;shift:string;refund:ReturnQuote;replacement:CheckoutQuote;items:ExchangeRequest['items'];lines:ExchangeRequest['replacement']['lines']}; +const methods=['cash','external_card','manual_upi'] as const; +function paymentPlan(q:CheckoutQuote,mode:TenderMethod|'split',cardText:string,upiText:string,currency:string,locale:string){ + let card=0,upi=0,cash=0; + if(mode==='split'){ + const a=cardText.trim()?parseMajor(cardText,currency,locale):0,b=upiText.trim()?parseMajor(upiText,currency,locale):0; + if(a===null||b===null||!Number.isSafeInteger(a+b)||a+b>q.totalMinor)return null; + card=a;upi=b;const raw=q.totalMinor-card-upi;cash=roundCashMinor(raw,q.cashRoundingMinor); + if(raw>0&&cash===0&&card+upi>0)return null; + }else if(mode==='cash')cash=roundCashMinor(q.totalMinor,q.cashRoundingMinor); + else if(mode==='external_card')card=q.totalMinor;else upi=q.totalMinor; + const amounts={cash,external_card:card,manual_upi:upi}; + const tenders=methods.filter(m=>amounts[m]>0).map(method=>({method,amountMinor:amounts[method],...(method==='cash'?{}:{attestedByCashier:true})})); + if(!tenders.length)tenders.push({method:'cash',amountMinor:0}); + const total=cash+card+upi;return Number.isSafeInteger(total)?{tenders,total,cash}:null; +} +export function ExchangeDialog({order,open,onClose,pending}:{order:Order;open:boolean;onClose:()=>void;pending:PendingReturn|null}){ + const {api,accountId,organizationId,workspace,mode,offlineSession}=useSession(),{fmt,currency,locale}=useMoney(),qc=useQueryClient(); + const [qty,setQty]=useState>({}),[restock,setRestock]=useState>({}),[reason,setReason]=useState('Size or product exchange'); + const [selected,setSelected]=useState<(Sellable&{quantity:number})[]>([]),[search,setSearch]=useState(''); + const [verified,setVerified]=useState(null),[method,setMethod]=useState('cash'),[card,setCard]=useState(''),[upi,setUpi]=useState(''); + const [local,setLocal]=useState(null),[confirmed,setConfirmed]=useState(false),[result,setResult]=useState(null),[reviewed,setReviewed]=useState(false); + const [error,setError]=useState(null),[reviewOpen,setReviewOpen]=useState(false),[reviewNote,setReviewNote]=useState(''),[resolution,setResolution]=useState<'settlement_not_made'|'settlement_reconciled_outside_storefront'>('settlement_not_made'); + const [clock,setClock]=useState(Date.now()); + useEffect(()=>{if(open){setQty({});setRestock({});setReason('Size or product exchange');setSelected([]);setSearch('');setVerified(null);setMethod('cash');setCard('');setUpi('');setLocal(null);setConfirmed(false);setResult(null);setReviewed(false);setError(null);setReviewOpen(false);setReviewNote('');setResolution('settlement_not_made');setClock(Date.now());}},[open,order.id]); + useEffect(()=>{if(!open)return;const t=window.setInterval(()=>setClock(Date.now()),1000);return()=>window.clearInterval(t);},[open]); + const row=local??pending; + let saved:SavedExchange|null=null;let corrupt=false; + if(row)try{saved=decode(row);}catch{corrupt=true;} + const scope=workspace.storeId?{accountId,organizationId,storeId:workspace.storeId}:null; + const products=useRemoteCatalog(scope,search,null,open&&mode==='live'&&!offlineSession&&!row&&!verified&&workspace.storeId===order.storeId); + const items=order.lines.filter(l=>(qty[l.id]??0)>0).map(l=>({orderItemId:l.id,quantity:qty[l.id]!,restock:restock[l.id]??true})); + const plan=verified?paymentPlan(verified.replacement,method,card,upi,currency,locale):null; + const expired=!!verified&&verified.replacement.expiresAt*1000<=clock; + const validateOperator=async()=>{if(mode!=='live'||offlineSession)throw Error('Reconnect and sign in before settling an exchange.');const me=await api.me();if(me.user.id!==accountId||me.organization?.id!==organizationId)throw Error('Sign in to the original business and operator.');}; + const invalidate=()=>{for(const key of [['order',order.id],['orders'],['inventory'],['report'],['exchanges',order.id]])void qc.invalidateQueries({queryKey:key});}; + const quoteMutation=useMutation({mutationFn:async()=>{ + await validateOperator();if(workspace.storeId!==order.storeId||!workspace.registerId)throw Error('Select a register in the original store.'); + const shift=await api.activeSession(workspace.registerId);if(!shift||shift.storeId!==order.storeId)throw Error('Open a shift at the original store.'); + const key=newId(),lines=selected.map(p=>({variantId:p.variantId,quantity:p.quantity})); + const [refund,replacement]=await Promise.all([fetchReturnQuote(order.id,items),fetchCheckoutQuote({registerSessionId:shift.id,idempotencyKey:key,lines,...(order.customerId?{customerId:order.customerId}:{})})]); + if(replacement.currency!==order.currency)throw Error('Replacement currency must match the original sale.'); + return {key,shift:shift.id,refund,replacement,items,lines} satisfies Verified; + },onSuccess:q=>{setVerified(q);setError(null);setClock(Date.now());},onError:e=>setError(describeError(e))}); + const prepare=useMutation({mutationFn:async()=>{ + if(!verified||!plan||verified.replacement.expiresAt*1000<=Date.now())throw Error('Verify a fresh quote before preparing settlement.'); + await validateOperator(); + const request:ExchangeRequest={idempotencyKey:verified.key,items:verified.items,reason:reason.trim(),expectedRefundMinor:verified.refund.amountMinor,expectedPayouts:verified.refund.payouts,settlementConfirmed:true,externalSettlementAttested:true, + replacement:{idempotencyKey:verified.key,registerSessionId:verified.shift,lines:verified.lines,quoteToken:verified.replacement.quoteToken,expectedPayableMinor:plan.total,tenders:plan.tenders,...(order.customerId?{customerId:order.customerId}:{})}}; + const body:SavedExchange={operation:'exchange',idempotencyKey:verified.key,status:'prepared',request,labels:selected.map(p=>({name:p.name,quantity:p.quantity}))}; + const stored=await putPendingReturn({accountId,organizationId},order,body);setLocal(stored);return stored; + },onSuccess:()=>{setConfirmed(false);setError(null);},onError:e=>setError(describeError(e))}); + const commit=useMutation({mutationFn:async()=>{ + await validateOperator();const key=pendingReturnKey(accountId,organizationId,order.id); + const exact=await offlineDB.transaction('rw',offlineDB.pendingReturns,async()=>{ + const current=await offlineDB.pendingReturns.get(key);if(!current)throw Error('Saved exchange is no longer pending. Reload the order.'); + const body=decode(current); + if(body.status==='confirmed')return current; + if(!confirmed)throw Error('Confirm the actual settlement first.'); + const updated={...current,bodyJson:JSON.stringify({...body,status:'confirmed'})}; + await offlineDB.pendingReturns.put(updated);return updated; + }); + setLocal(exact);const posted=await exchangeApi.commit(order.id,decode(exact).request); + await finishPendingReturn(exact).catch(()=>undefined);return posted; + },onSuccess:r=>{setResult(r);setError(null);invalidate();},onError:e=>setError(describeError(e))}); + const review=useMutation({mutationFn:async()=>{ + await validateOperator();const current=await offlineDB.pendingReturns.get(pendingReturnKey(accountId,organizationId,order.id));if(!current)throw Error('Saved exchange not found.'); + const body=decode(current);await exchangeApi.review(order.id,{idempotencyKey:body.idempotencyKey,resolution,note:reviewNote.trim()});await finishPendingReturn(current); + },onSuccess:()=>{setReviewed(true);setError(null);invalidate();},onError:e=>setError(describeError(e))}); + const busy=quoteMutation.isPending||prepare.isPending||commit.isPending||review.isPending,done=!!result||reviewed; + const locked=!!row||!!verified||busy; + function add(p:Sellable){setSelected(prev=>prev.some(x=>x.variantId===p.variantId)?prev.map(x=>x.variantId===p.variantId?{...x,quantity:Math.min(100000,x.quantity+1)}:x):[...prev,{...p,quantity:1}]);} + const savedTenders=saved?.request.replacement.tenders??(saved?.request.replacement.tender?[saved.request.replacement.tender]:[]); + const payouts=saved?.request.expectedPayouts??verified?.refund.payouts??[]; + const replacementTenders=saved?savedTenders:plan?.tenders??[]; + const netCash=replacementTenders.filter(t=>t.method==='cash').reduce((a,t)=>a+t.amountMinor,0)-payouts.filter(t=>t.method==='cash').reduce((a,t)=>a+t.amountMinor,0); + const external=payouts.some(t=>t.method!=='cash'&&t.amountMinor>0)||replacementTenders.some(t=>t.method!=='cash'&&t.amountMinor>0); + return {!done&&!row&&!verified?:null}{!done&&!row&&verified?:null}{!done&&saved&&!reviewOpen?:null}}> + {done?{result?<>

Both the original return and replacement sale are recorded.

Open replacement {result.replacement.orderNumber}:'Both transaction references are permanently fenced. No sale or refund was recorded by this review.'}
:
+ {error?{error.message}:null} + {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}
  • ;})}
+ } 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)}/> + {verified?<>{expired?Do not settle. Refresh the quote first.:null}{method==='split'?<>setCard(e.target.value)}/>setUpi(e.target.value)}/>Cash is the rounded remainder.:null}{!plan?The payment allocation must cover the exact quote.:null}:null}:null} + {(saved||verified&&plan)?
    {payouts.map(p=>
  • Original refund · {tenderLabel[p.method]}{fmt(p.amountMinor)}
  • )}{replacementTenders.map(t=>
  • Replacement payment · {tenderLabel[t.method]}{fmt(t.amountMinor)}
  • )}
  • {netCash>0?'Collect net cash':netCash<0?'Pay out net cash':'No cash movement'}{fmt(Math.abs(netCash))}
{external?Complete each external refund and replacement charge separately on the terminal or UPI app; never treat them as verified by Storefront.:null}
:null} + {saved?<>Reference {saved.idempotencyKey}. {saved.status==='confirmed'?'Retry posts only this exact exchange. Do not repeat any money movement.':'Before confirming, verify the actual settlement against the amounts above. If uncertain, use manager reconciliation. Do not repeat payment or payout.'} + {saved.status==='prepared'?<>{Number(saved.request.replacement.quoteToken?.split('.')[0]??0)*1000<=clock?Do not initiate settlement now. If money moved, reconcile the original reference; do not create another exchange.:null}setConfirmed(e.target.checked)} label="I verified the exact net cash and any separate external refund/charge shown above were settled (or no money was due)."/>:null} + + {reviewOpen?<>Use only after verifying neither leg is committed and both external/cash settlement effects have been reconciled. This review does not move money.setReviewNote(e.target.value)}/>:null}:null} +
} +
; +} diff --git a/apps/web/src/features/merchant/Orders.tsx b/apps/web/src/features/merchant/Orders.tsx index af0e380..72ad565 100644 --- a/apps/web/src/features/merchant/Orders.tsx +++ b/apps/web/src/features/merchant/Orders.tsx @@ -16,7 +16,8 @@ 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 { fetchReturnQuote,reviewReturn } from '../../api/live'; +import { fetchReturnQuote,reviewReturn,exchangeApi } from '../../api/live'; +import { ExchangeDialog,isPendingExchange } from './ExchangeDialog'; 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('_', ' '); @@ -43,7 +44,7 @@ export function Orders() { return (
- {can('sales:refund')&&pending.length>0?
    {pending.map(row=>
  • Recover {row.orderNumber}
  • )}
Do not pay out again. Recover the original request.
:null} + {can('sales:refund')&&pending.length>0?
    {pending.map(row=>
  • Recover {row.orderNumber}
  • )}
Do not pay out again. Recover the original request.
:null} {lookup ? Search by receipt number or customer, open the sale and choose “Return items”. : null}
@@ -116,6 +117,7 @@ function ReturnDialog({ order, open, onClose, pending }: { order: Order; open: b if(verified.user.id!==accountId||verified.organization?.id!==organizationId)throw new StorefrontApiError('REFUND_SCOPE_CHANGED','Sign in to the original business and operator.',403); const existing=await offlineDB.pendingReturns.get(pendingReturnKey(accountId,organizationId,order.id)); if(existing){ + if(isPendingExchange(existing))throw Error('Recover the saved exchange before starting a refund.'); saved.current=existing;setUnknown(true); const original=JSON.parse(existing.bodyJson) as ReturnBody; if(original.idempotencyKey!==existing.idempotencyKey)throw new StorefrontApiError('RETURN_JOURNAL_CORRUPT','Saved refund reference is inconsistent. Do not issue another refund.',409); @@ -190,6 +192,9 @@ export function OrderDetail() { const receipt = useQuery({ queryKey: ['receipt', id, order.data?.status, order.data?.payments.length], enabled: false, queryFn: () => api.getReceipt(id) }); const [rcpt, setRcpt] = useState(false); const [ret, setRet] = useState(false); + const [exchange,setExchange]=useState(false); + const exchangePending=isPendingExchange(pending); + const links=useQuery({queryKey:['exchanges',id],queryFn:()=>exchangeApi.links(id),enabled:mode==='live'&&can('sales:read')&&!!id,retry:false}); const labelOf = useLineLabels(order.data?.lines ?? []); return ( @@ -201,7 +206,7 @@ export function OrderDetail() { <> {statusLabel(o.status)} {o.customerName ? `· ${o.customerName}` : '· Walk-in customer'}{o.cashier ? ` · cashier ${o.cashier}` : ''}} actions={<> - {can('sales:refund') ? : null}} /> + {can('sales:refund')&&!exchangePending ? : null}{mode==='live'&&can('sales:refund')&&can('sales:create')&&(!pending||exchangePending)?:null}} /> {receipt.isError ? : null}
@@ -217,7 +222,9 @@ export function OrderDetail() {
    {o.payments.map((p) =>
  • {p.amountMinor < 0 ? 'Refund · ' : ''}{tenderLabel[p.method]}{p.reference ? Ref: {p.reference} : null}{p.confirmedBy === 'cashier' && p.method !== 'cash' ? Confirmed manually by cashier : null}{fmt(p.amountMinor)}
  • )}
- setRet(false)} /> + {links.data?.length?
    {links.data.map(e=>
  • {e.originalOrderId===o.id?'Replacement sale':'Original sale'}{e.originalOrderId===o.id?e.replacementOrderNumber:e.originalOrderNumber}
  • )}
:null} + setRet(false)} /> + setExchange(false)} /> setRcpt(false)} title="Receipt" footer={}>{receipt.data ? : null} ); diff --git a/docs/operations/register-m3-atomic-exchanges.md b/docs/operations/register-m3-atomic-exchanges.md new file mode 100644 index 0000000..e33f78e --- /dev/null +++ b/docs/operations/register-m3-atomic-exchanges.md @@ -0,0 +1,4 @@ +# 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. + +Cashier workflow uses the existing account/org/order-scoped durable journal: verified quote → saved settlement intent → explicit verified settlement → atomic post. Prepared intents cannot post without attestation; confirmed intents replay unchanged after reload. Manager reviews fence both legs. Orders display linked replacements and original receipts. Requires real-browser UI, reload, mixed-tender and hardware acceptance before release. diff --git a/tests/route-policy.mjs b/tests/route-policy.mjs index 519ecad..4027a2b 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',