/** * Post-order self-serve issue resolution, cent-conserving partial line-item * refunds, out-of-stock substitution deltas, and buyer abuse risk scoring. */ import { refundTaxDelta } from './refund-allocation' export type OrderIssueCategory = | 'missing_item' | 'wrong_item' | 'damaged_in_transit' | 'cold_or_late' | 'never_delivered' | 'out_of_stock_removed' export type IssueFaultParty = 'merchant' | 'courier' | 'platform' export interface AffectedOrderLine { orderItemId: number lineSubtotalCents: number affectedQuantity: number orderedQuantity: number } export interface PartialRefundInput { category: OrderIssueCategory orderSubtotalCents: number orderTaxCents: number orderDeliveryFeeCents: number orderServiceFeeCents: number orderTotalCents: number previouslyRefundedSubtotalCents?: number previouslyRefundedTotalCents?: number affectedLines: AffectedOrderLine[] includeDeliveryFee?: boolean } export interface PartialRefundCalculation { itemRefundCents: number taxRefundCents: number feeRefundCents: number totalRefundCents: number faultParty: IssueFaultParty capped: boolean } export function faultPartyForIssue(category: OrderIssueCategory): IssueFaultParty { switch (category) { case 'missing_item': case 'wrong_item': case 'out_of_stock_removed': return 'merchant' case 'damaged_in_transit': case 'never_delivered': return 'courier' case 'cold_or_late': return 'platform' } } /** * Compute an exact, cent-conserving partial refund for one or more affected * order lines, including proportional tax via cumulative rounding (`refundTaxDelta`) * so multiple partial refunds never exceed the original charge. */ export function calculateLineItemRefund(input: PartialRefundInput): PartialRefundCalculation { const prevSubtotal = Math.max(0, Math.round(input.previouslyRefundedSubtotalCents ?? 0)) const prevTotal = Math.max(0, Math.round(input.previouslyRefundedTotalCents ?? 0)) const remainingTotal = Math.max(0, Math.round(input.orderTotalCents) - prevTotal) let itemRefundCents = 0 for (const line of input.affectedLines) { if (line.orderedQuantity <= 0 || line.affectedQuantity <= 0 || line.lineSubtotalCents <= 0) continue const qty = Math.min(line.affectedQuantity, line.orderedQuantity) itemRefundCents += Math.round((line.lineSubtotalCents * qty) / line.orderedQuantity) } const remainingSubtotal = Math.max(0, Math.round(input.orderSubtotalCents) - prevSubtotal) itemRefundCents = Math.min(itemRefundCents, remainingSubtotal) const taxRefundCents = input.orderSubtotalCents > 0 && itemRefundCents > 0 ? refundTaxDelta(prevSubtotal, itemRefundCents, Math.round(input.orderSubtotalCents), Math.round(input.orderTaxCents)) : 0 const feeRefundCents = (input.includeDeliveryFee || input.category === 'never_delivered') ? Math.max(0, Math.round(input.orderDeliveryFeeCents)) + (input.category === 'never_delivered' ? Math.max(0, Math.round(input.orderServiceFeeCents)) : 0) : 0 const rawTotal = itemRefundCents + taxRefundCents + feeRefundCents const totalRefundCents = Math.min(remainingTotal, rawTotal) return { itemRefundCents, taxRefundCents, feeRefundCents, totalRefundCents, faultParty: faultPartyForIssue(input.category), capped: rawTotal > remainingTotal, } } export interface BuyerIssueHistory { completedOrderCount: number recentIssueCount30d: number lifetimeIssueCount: number requestedRefundCents: number hasPhotoEvidence: boolean } export interface BuyerIssueRiskAssessment { decision: 'auto_approve' | 'credit_only' | 'manual_review' riskScore: number reasons: string[] } /** * Evaluate whether a self-serve post-order claim should be auto-refunded, * issued as instant store credit, or routed to operations review. */ export function evaluateBuyerIssueRisk(history: BuyerIssueHistory): BuyerIssueRiskAssessment { let riskScore = 0 const reasons: string[] = [] if (history.recentIssueCount30d >= 3) { riskScore += 55 reasons.push('high_30d_claim_velocity') } else if (history.recentIssueCount30d >= 2) { riskScore += 25 reasons.push('elevated_30d_claim_velocity') } const ratio = history.completedOrderCount > 0 ? history.lifetimeIssueCount / history.completedOrderCount : history.lifetimeIssueCount if (history.completedOrderCount >= 3 && ratio > 0.35) { riskScore += 40 reasons.push('high_lifetime_claim_ratio') } if (history.requestedRefundCents >= 5000) { riskScore += 30 reasons.push('high_value_claim') } else if (history.requestedRefundCents >= 2500) { riskScore += 15 reasons.push('medium_value_claim') } if (history.hasPhotoEvidence) riskScore = Math.max(0, riskScore - 20) if (riskScore >= 55) return { decision: 'manual_review', riskScore, reasons } if (riskScore >= 30) return { decision: 'credit_only', riskScore, reasons } return { decision: 'auto_approve', riskScore, reasons } } /** * Compute price difference in minor units when a kitchen proposes substituting * an out-of-stock item with a replacement (or removing it when replacement is null). */ export function calculateSubstitutionDelta( originalLineCents: number, replacementLineCents: number | null, ): { deltaCents: number, action: 'refund' | 'charge' | 'even' } { const next = replacementLineCents === null ? 0 : Math.max(0, Math.round(replacementLineCents)) const orig = Math.max(0, Math.round(originalLineCents)) const deltaCents = next - orig return { deltaCents, action: deltaCents < 0 ? 'refund' : deltaCents > 0 ? 'charge' : 'even', } }