diff --git a/apps/web-ui/src/routes/flash.checkout.tsx b/apps/web-ui/src/routes/flash.checkout.tsx
index 1928b52..89e7034 100644
--- a/apps/web-ui/src/routes/flash.checkout.tsx
+++ b/apps/web-ui/src/routes/flash.checkout.tsx
@@ -98,7 +98,6 @@ function FlashCheckoutPage() {
})),
addressId: selectedAddressId,
regionId: selectedRegionId,
- paymentMethod: 'cod',
isFlashDelivery: true,
})
}
diff --git a/apps/web-ui/src/routes/home.checkout.tsx b/apps/web-ui/src/routes/home.checkout.tsx
index bc1140f..1569fb6 100644
--- a/apps/web-ui/src/routes/home.checkout.tsx
+++ b/apps/web-ui/src/routes/home.checkout.tsx
@@ -98,7 +98,6 @@ function CheckoutPage() {
})),
addressId: selectedAddressId,
regionId: selectedRegionId,
- paymentMethod: 'cod',
isFlashDelivery: false,
})
}
diff --git a/apps/web-ui/src/routes/me.orders.$id.tsx b/apps/web-ui/src/routes/me.orders.$id.tsx
index 9d1008f..84055d4 100644
--- a/apps/web-ui/src/routes/me.orders.$id.tsx
+++ b/apps/web-ui/src/routes/me.orders.$id.tsx
@@ -185,24 +185,6 @@ function OrderDetailPage() {
{/* Main Info Card */}
-
-
-
-
-
-
-
Payment Method
-
- {order.paymentMode?.toUpperCase() === 'COD' ? 'Cash on Delivery' : order.paymentMode}
-
-
-
-
-
Status
-
{order.paymentStatus}
-
-
-
{(order.deliveryDate || order.isFlashDelivery) &&
['delivered', 'success'].includes((order.deliveryStatus || '').toLowerCase()) && (
@@ -290,12 +272,6 @@ function OrderDetailPage() {
Cancellation Reason
{order.cancelReason}
- {order.refundAmount && (
-
-
Refund Amount
-
₹{order.refundAmount}
-
- )}
)}
diff --git a/apps/web-ui/src/routes/me.orders.tsx b/apps/web-ui/src/routes/me.orders.tsx
index cb0448c..21de8e1 100644
--- a/apps/web-ui/src/routes/me.orders.tsx
+++ b/apps/web-ui/src/routes/me.orders.tsx
@@ -7,14 +7,6 @@ import { orderStatusManipulator } from '../lib/string-manipulators'
import dayjs from 'dayjs'
import { AlertCircle, Package, MapPin } from 'lucide-react'
-// Matches packages/ui (RN common-ui) REFUND_STATUS values used by user-ui.
-const REFUND_STATUS = {
- PENDING: 'pending',
- NOT_APPLICABLE: 'na',
- PROCESSING: 'initiated',
- SUCCESS: 'success',
-} as const
-
export const Route = createFileRoute('/me/orders')({ component: OrdersPage })
const PAGE_SIZE = 10
@@ -38,7 +30,6 @@ function getStatusStyle(status: string): StatusStyle {
case 'failed':
return { bg: 'bg-rose-50', text: 'text-rose-700', iconColor: '#E11D48', icon:
✕, label: 'Cancelled' }
case 'pending':
- case 'payment_pending':
return { bg: 'bg-amber-50', text: 'text-amber-700', iconColor: '#D97706', icon:
🕐, label: 'Pending' }
case 'packaged':
return { bg: 'bg-brand-50', text: 'text-brand-700', iconColor: '#1570EF', icon:
📦, label: 'Packaged' }
@@ -51,30 +42,15 @@ function getStatusStyle(status: string): StatusStyle {
}
}
-function getRefundStyle(status: string): { bg: string; text: string; icon: React.ReactNode; color: string } {
- switch (status) {
- case REFUND_STATUS.SUCCESS:
- return { bg: 'bg-emerald-50', text: 'text-emerald-700', icon:
✓, color: '#059669' }
- case REFUND_STATUS.PROCESSING:
- return { bg: 'bg-brand-50', text: 'text-brand-700', icon:
⟳, color: '#1570EF' }
- case REFUND_STATUS.PENDING:
- return { bg: 'bg-amber-50', text: 'text-amber-700', icon:
🕐, color: '#D97706' }
- default:
- return { bg: 'bg-slate-50', text: 'text-slate-700', icon:
i, color: '#64748B' }
- }
-}
-
function OrderCard({
item,
getStatusStyle,
- getRefundStyle,
onPress,
onViewMoreItems,
refetch,
}: {
item: any
getStatusStyle: (s: string) => StatusStyle
- getRefundStyle: (s: string) => { bg: string; text: string; icon: React.ReactNode; color: string }
onPress: (orderId: number) => void
onViewMoreItems: (orderId: number) => void
refetch: () => void
@@ -276,22 +252,6 @@ function OrderCard({
Cancellation Details
{item.cancelReason}
-
- {item.refundStatus && item.refundStatus !== REFUND_STATUS.NOT_APPLICABLE && (
-
-
Refund Status
-
-
- {getRefundStyle(item.refundStatus).icon}
-
-
- {item.refundStatus}
-
-
-
- )}
)}
@@ -418,7 +378,6 @@ function OrdersPage() {
key={order.id}
item={order}
getStatusStyle={getStatusStyle}
- getRefundStyle={getRefundStyle}
onPress={(orderId) => navigate({ to: '/me/orders/$id', params: { id: String(orderId) } })}
onViewMoreItems={(orderId) =>
navigate({ to: '/me/orders/$id', params: { id: String(orderId) } })
diff --git a/change-log.txt b/change-log.txt
index 7b86d54..9b5e368 100644
--- a/change-log.txt
+++ b/change-log.txt
@@ -5649,3 +5649,130 @@ user-ui
Tests were not run (user runs the suite).
5. The five scope-specific readers/writers (global/region/bound/legacy) and the
admin.region/superadmin.const routes are untouched; only the merged read/write pair is gone.
+
+2026-10-17 14:38:20 ALL APPS + DB: online payments removed end to end (COD-only). Folded into migration 0006.
+
+ Request: "I don't want anything related to online payments in the entire application. remove all those.
+ Except the Coming Soon on the checkout page, I want no trace of online payment. No db columns, tables.
+ No procedures, nothing." + decisions: drop is_cod, drop payment_state, remove refund coupons, remove
+ paymentMethod from placeOrder input, strip payment rows/labels from order history + admin screens,
+ KEEP the "Pay Online (Coming Soon)" card and KEEP the "UPI accepted during COD" line, make the schema
+ change inside 0006 (not a new 0007) with a labelled commented section, ignore db_helper_postgres.
+
+ DB (packages/db_helper_sqlite)
+ drizzle/0006_regions_and_superadmins.sql - new labelled Phase 7 section adding
+ DROP TABLE refunds / payments / payment_info; __new_orders loses is_cod, is_online_payment,
+ payment_info_id (+ its FK); __new_order_status loses payment_state, refund_coupon_id (+ coupons FK);
+ the __new_refunds / __new_payments blocks, their renames, old-table drops and the payments unique
+ index are removed; orphan payments/refunds cleanup removed (tables are dropped); header note added.
+ src/db/schema.ts - drop paymentInfoTable, payments, refunds + their relations, orders.payment/
+ paymentInfo/refunds, orderStatus.refundCoupon, orders isCod/isOnlinePayment/paymentInfoId columns,
+ orderStatus paymentStatus/refundCouponId, paymentStatusValues/paymentStatusEnum.
+ src/user-apis/order.ts - OrderWithRelations loses isCod/isOnlinePayment/paymentInfo/refunds/
+ paymentStatus; placeOrderTransaction loses the paymentMethod param + payment_info insert;
+ cancelOrderTransaction loses the isCod param + refunds insert.
+ src/user-apis/payments.ts, src/admin-apis/order.ts (payment/refund includes + AdminRefundRecord
+ mapping + payments delete), src/user-apis/auth.ts (payments delete), src/lib/delete-orders.ts
+ (payments/refunds deletes), src/admin-apis/coupon.ts (generateCancellationCoupon), src/index.ts +
+ apps/backend/src/sqliteImporter.ts exports, src/lib/env-exporter.ts (razorpay/phonepe).
+
+ Backend (apps/backend)
+ - DELETE src/trpc/apis/user-apis/apis/payments.ts + its mount; DELETE src/trpc/apis/admin-apis/apis/
+ payments.ts (initiateRefund) + its mount; DELETE src/lib/payments-utils.ts; DELETE
+ src/jobs/payment-status-checker.ts + its imports in jobs-index.
+ src/trpc/apis/user-apis/apis/order.ts - placeOrder input drops paymentMethod; no isCod/isOnlinePayment/
+ paymentStatus writes; getOrders/getOrderById mappers drop paymentMode/paymentStatus/refundStatus/
+ refundAmount; cancel drops the isCod arg.
+ src/lib/post-order-handler.ts - Telegram message drops the payment mode + Refund line.
+ src/lib/env-exporter.ts - remove getRazorpayId/getRazorpaySecret.
+ wrangler.dev.toml + wrangler.prod.toml - remove PHONE_PE_* and RAZORPAY_* vars.
+
+ Shared / common-ui
+ packages/shared/types/user.ts - remove Payment, UserPaymentOrderResponse/Verify/Fail and
+ UserOrderSummary paymentMode/paymentStatus/refundStatus/refundAmount.
+ packages/shared/types/admin.ts - remove PaymentStatus, RefundStatus, AdminRefundRecord and the
+ payment/refund/isCod fields on AdminOrderDetails, AdminOrderStatusRecord, AdminSlotOrder,
+ AdminOrderListItem. packages/shared/types/order.types.ts - PlacedOrder.isCod.
+ packages/ui/src/lib/const-strs.ts + index.ts - remove REFUND_STATUS(+ export); package.json - drop
+ react-native-razorpay + react-native-phonepe-pg (and @types in user-ui/admin-ui).
+
+ UIs
+ user-ui/components/PaymentAndOrderComponent.tsx - paymentMethod state, verify/markFailed mutations
+ and the !isCod branch removed (always navigates to success); KEEPS the disabled
+ "Pay Online (Coming Soon)" card and the "UPI accepted during COD" line; COD card static-selected.
+ user-ui my-orders/index.tsx - refund chip, Retry Payment button, razorpay mutations, payment_pending
+ status case removed. user-ui my-orders/[id].tsx - Payment Method / payment status / refund rows.
+ web-ui PaymentAndOrderComponent.tsx (same treatment), me.orders.tsx (refund chip, payment_pending),
+ me.orders..tsx (payment/refund rows), home.checkout.tsx + flash.checkout.tsx (drop paymentMethod).
+ admin-ui order-details/[id].tsx - refund dialog + initiateRefund mutation, Generate Refund Coupon,
+ hidden Refund/Cancellation Details block, payment rows; orders list commented isCod block.
+ admin-web dashboard.orders..tsx (same) + CancelOrderDialog copy mentioning a refund record.
+
+ Tests/docs/deps: backend api suites drop the paymentMethod param and the online-order test; user-ui +
+ admin-ui fixtures/tests updated; docs/test-cases/payments-refunds.md deleted with its references;
+ razorpay test mocks removed.
+
+ NOT touched: packages/db_helper_postgres (agreed), apps/backend/dumps/*.sql + migrated.sql (historical
+ snapshots), historical change-log entries. No migrations applied, no test suite run.
+
+2026-10-17 15:03:43 As-built notes for the online-payments removal (deltas + verification).
+
+ 0006 / migration
+ - The labelled Phase 5 comment block sits inside the existing leaf-first drop section:
+ `DROP TABLE payments` / `DROP TABLE refunds` stay where the original file had them
+ (before `orders`, they are its children) and `DROP TABLE payment_info` is added right
+ after `DROP TABLE orders` (it is the parent of the old orders.payment_info_id). Putting
+ all three at the very end, after the renames, breaks FK ordering - that was tried and
+ reverted.
+ - The rebuild definitions changed in place: __new_orders (columns + FK + INSERT list),
+ __new_order_status (payment_state / refund_coupon_id / coupons FK + INSERT list);
+ __new_refunds and __new_payments blocks, their renames, old-table drops and the
+ payments_merchant_order_id_unique index are gone; orphan payments/refunds DELETEs gone
+ (the tables are dropped); header phase list gained "5. online payments / refunds removed".
+ - Verified locally, not applied: chain 0000..0006 on a fresh sqlite3 DB, and 0006 against
+ apps/backend/dumps/latest.sql -> no payment/refund tables left, orders/order_status carry
+ no payment columns, row counts preserved (orders 2387, order_status 2381, order_items
+ 8334). Note: with `PRAGMA foreign_keys=ON` the ORIGINAL 0006 fails on that dump too
+ (pre-existing; D1's migration semantics differ per the file header) - the statement order
+ is identical apart from the removals, so nothing new is introduced. Apply with
+ `wrangler d1 migrations apply --local` first.
+
+ Design decisions as implemented
+ - keep the disabled "Pay Online (Coming Soon)" card (with "UPI, Cards, Netbanking") and the
+ "UPI accepted during COD" line; the COD card is now a static selected row (no state).
+ - order history + admin screens: payment/refund rows removed entirely (no static "COD" label).
+ - Terms & Conditions copy (user-ui + web-ui) is left untouched: its "Refund & Cancellation
+ Policy" section documents COD refunds (cash adjustment / replacement / store credit) and is
+ customer-facing legal text, not a gateway flow. CancelOrderDialog no longer claims a refund
+ record is created.
+ - removed tests: order-flow online-order case, order-lifecycle-gaps "writes a refund row for a
+ cancelled COD order", me-orders retry-payment case, admin-ui order-details refund-coupon case.
+ - composer/test fixtures: isCod/paymentMode/paymentStatus/refundStatus props stripped; the
+ payment-and-order tests still assert the Coming Soon card.
+
+ Cleanup / leftovers by design
+ - packages/db_helper_postgres, apps/backend/dumps/*.sql and apps/backend/migrated.sql keep
+ their old payment schema (historical snapshots, agreed out of scope).
+ - package.json deps removed (react-native-razorpay, @types/react-native-razorpay,
+ react-native-phonepe-pg) but the lockfile (bun.lock) still lists them; run `bun install`.
+ - packages/ui's own tsc is not a meaningful target (2665 pre-existing alias errors from app
+ files); the per-app tscs are clean.
+
+ Verification: apps/user-ui, web-ui, admin-ui, admin-web, superadmin-ui, fallback-ui,
+ packages/db_helper_sqlite and apps/backend (src) all typecheck clean. Backend tests typecheck:
+ the same 21 pre-existing errors (owner/createGroup, placeOrder calls missing regionId,
+ health.test cacheVersion) and none in the files touched here. Tests not run.
+
+2026-10-17 15:05:14 CORRECTION to the online-payments removal: npm deps kept, not removed.
+
+ User decision: the razorpay/phonepe packages are fine to stay in package.json.
+ Reverted only the dependency edits (the three files are byte-identical to HEAD again):
+ apps/user-ui/package.json react-native-razorpay (dep) + @types/react-native-razorpay (devDep)
+ apps/admin-ui/package.json @types/react-native-razorpay (devDep)
+ packages/ui/package.json react-native-phonepe-pg + react-native-razorpay
+ No code imports any of them, so nothing changes at runtime/build; no lockfile work is needed
+ any more (the earlier "run bun install" note in the 15:03:43 entry no longer applies).
+
+ Still removed (test scaffolding, not packages): the jest.mock('react-native-razorpay', ...)
+ registration in apps/user-ui/tests/setup.ts and razorpayMock() in tests/mocks/native.ts.
+ Say the word if those should come back too.
diff --git a/docs/e2e-sanity-test-plan.md b/docs/e2e-sanity-test-plan.md
index 8b974bc..8603e3d 100644
--- a/docs/e2e-sanity-test-plan.md
+++ b/docs/e2e-sanity-test-plan.md
@@ -275,9 +275,9 @@ regular/flash prices, and at least one two-slot cart. Equal fixture values can h
| OR-03 | Place order → edit instructions from customer order menu → admin refreshes; admin adds internal notes. | User notes propagate; admin notes remain correctly distinguished from customer instructions. The **customer** path rejects editing a delivered/cancelled order; the **admin** path may annotate delivered orders (business decision 2026-10-10). |
| OR-04 | Admin packages one item then all items, verifies packaging and marks Delivered → customer refreshes tracking. | Item and aggregate packaging state agree across admin lists/details; customer sees correct fulfillment/delivery status. |
| OR-05 | Admin reverses an accidental packaged/delivered toggle where supported → refresh both apps. | Supported reversal is consistent; forbidden transitions show clear errors. No cancelled order resurrected accidentally. |
-| OR-06 | Customer cancels pending COD order with reason → admin list/detail and vendor page refresh. | Cancelled status/reason/actor persist; cancelled order is not fulfillable or included in vendor production totals; COD refund is not shown as cash owed. |
+| OR-06 | Customer cancels pending COD order with reason → admin list/detail and vendor page refresh. | Cancelled status/reason/actor persist; cancelled order is not fulfillable or included in vendor production totals; no refund record or cash owed is shown (COD-only). |
| OR-07 | Admin cancels pending order with reason → customer history/detail and next-order glimpse refresh. | Cancellation is attributed to admin and visible to customer; next-order summary no longer treats it as upcoming. |
-| OR-08 | Try blank reason, second cancellation and cancellation after Delivered; cancel one of two slot suborders. | Invalid cancellations reject without duplicate refund records; other suborder stays intact. |
+| OR-08 | Try blank reason, second cancellation and cancellation after Delivered; cancel one of two slot suborders. | Invalid cancellations reject without creating any payment/refund record; other suborder stays intact. |
| OR-09 | Admin removes delivery charge from order → customer/admin details refresh. | Saved payable total and fee update together, exactly once; unrelated suborders stay unchanged. |
| OR-10 | Place order → admin changes prices → verify old order unchanged → run explicit Rebalance on chosen slot(s). | Normal catalog edits do not reprice historical orders. Explicit rebalance reprices **item prices only** and **freezes the historic delivery fee and the discount actually charged** (policy 2026-10-10); delivered/cancelled orders are skipped. After rebalancing each touched order still reconciles as `items(priced) − frozen discount + frozen fee = stored total`. |
| OR-11 | Create many A/B orders → exercise admin filters and pagination and customer My Orders pagination. | No missing/duplicate A orders due to B's high IDs; filters match actual statuses; customer sees own orders across regions with region labels. |
@@ -337,19 +337,18 @@ the present implementation.
| SEC-07 | Vendor request edits packaging using an unrelated item ID; expired snippet queries another slot; anonymous caller tries same mutation without valid snippet authority. | Vendor access is constrained to authorized snippet/region/items. A public vendor URL is not authority to edit every order item. |
| SEC-08 | Reuse revoked/deleted staff identity/token → attempt region-bound mutation; change staff region in superadmin then retry old session. | Access reflects current staff assignment/existence, not a stale token's region. |
-## O. Payment/refund readiness (not current COD sanity)
+## O. Payments (Cash on Delivery only)
-`PaymentAndOrderComponent` currently disables online payment as “Coming Soon”;
-`RazorpayPaymentService` methods are commented-out stubs. Do not report live
-online payment/refund journeys as supported or passing today.
+Online payments were removed from the product: there is no gateway, no
+`payment_info` / `payments` / `refunds` table, no payment state on an order and
+no refund flow. Checkout shows the disabled "Pay Online (Coming Soon)" card and
+a Cash-on-Delivery option; COD orders carry no payment record at all. Do not
+report any online payment, payment-status or refund journey as supported.
| ID | Steps / journey | Required result |
|---|---|---|
-| PAY-01 | Current customer Checkout attempts selecting online payment. | It remains clearly disabled; COD works without any gateway call. |
-| PAY-02 | Once implemented, single- and multi-slot sandbox online checkout → verify callback → inspect customer/admin orders. | Correct discounted group amount and INR minor units; one payment covers intended suborders, all become paid exactly once. |
-| PAY-03 | Sandbox declines/cancels/times out payment → retry, double callback and late success/webhook. | No duplicate payment/order, accurate pending/failed/success state, consistent cart and retry behavior. |
-| PAY-04 | Paid customer order cancellation → admin partial/full refund → gateway settles → customer views status; retry refund. | Amount never exceeds collected payment, authorization enforced and no duplicate refund; COD does not enter online-refund flow. |
-| PAY-05 | Forged signature, another customer's merchant order ID, duplicate callback and mismatched amount/currency. | Backend rejects forged/foreign payment, verifies authoritative ownership/amount and handles callbacks idempotently. |
+| PAY-01 | Customer Checkout looks at the payment section. | Online payment is clearly disabled ("Coming Soon"); COD is the only option and placing an order makes no gateway call. |
+| PAY-02 | Place a COD order from the app and from the web checkout, then inspect the order in admin/customer views. | Order is created with no payment/refund fields, no `paymentMethod` sent, and no payment row anywhere. |
## P. Write-path integrity, atomicity and idempotency
diff --git a/docs/maestro-mcp-agent-guidelines.md b/docs/maestro-mcp-agent-guidelines.md
index f262753..dbcb04d 100644
--- a/docs/maestro-mcp-agent-guidelines.md
+++ b/docs/maestro-mcp-agent-guidelines.md
@@ -244,7 +244,7 @@ grep -rhoE "from ['\"][^'\"]+['\"]" app components ../../packages/ui/src \
```
In this repo **no custom native module is actually imported**:
-`react-native-razorpay` and `@react-native-google-signin` are declared in
+`@react-native-google-signin` is declared in
`package.json` but never imported in source (Google login goes through
`expo-auth-session`), and `expo-notifications` is unused. Everything else is
`expo-*` or JS-only. So both apps are Expo Go-safe.
diff --git a/docs/test-cases/README.md b/docs/test-cases/README.md
index 03d0d4d..07bb14a 100644
--- a/docs/test-cases/README.md
+++ b/docs/test-cases/README.md
@@ -51,7 +51,7 @@ Use unique run prefixes. Do not delete regions for cleanup: region deletion is u
| Merchandising | [Catalog/search](catalog-search.md), [Tags/order](product-tags-ordering.md), [Groups](product-groups.md), [Banners](banners.md) |
| Purchasing | [Slots](scheduled-slots.md), [Cart](cart.md), [Addresses](addresses.md), [Checkout](checkout.md), [Pricing](pricing-delivery-fees.md), [Flash](flash-delivery.md) |
| Coupons | [Administration](coupon-management.md), [Eligibility/stacking](coupon-application.md), [Stacking & cart guards](coupon-stacking-and-cart-guards.md), [Reserved/cancellation coupons](reserved-coupons.md) |
-| Order operations | [Placement/history](orders.md), [Fulfillment](fulfillment.md), [Cancellation](cancellation.md), [Edits/rebalance](order-edits-rebalance.md), [Delivery sequence/maps](delivery-operations.md), [Payment/refund readiness](payments-refunds.md) |
+| Order operations | [Placement/history](orders.md), [Fulfillment](fulfillment.md), [Cancellation](cancellation.md), [Edits/rebalance](order-edits-rebalance.md), [Delivery sequence/maps](delivery-operations.md) |
| Support | [Complaints](complaints.md), [Customer operations/incidents](customer-management-incidents.md), [Notifications](notifications.md) |
| Infrastructure | [Uploads](uploads-images.md), [Cache publication](cache-publication.md), [Jobs/health](jobs-health.md), [Security](authorization-api-contracts.md), [Recovery/platform/accessibility](recovery-platform-accessibility.md) |
| Conditional/legacy | [Vendor snippets](vendor-snippets.md), [Reviews](reviews.md), [Fallback/legacy pages](fallback-legacy-pages.md) |
diff --git a/docs/test-cases/cancellation.md b/docs/test-cases/cancellation.md
index 25bfa67..339d32b 100644
--- a/docs/test-cases/cancellation.md
+++ b/docs/test-cases/cancellation.md
@@ -23,4 +23,4 @@ Scope: customer/admin cancellation, reason/actor/status, group usages, refund el
| CANCEL-17 | P1 | Cart after cancellation. | No unexpected automatic cart restoration/duplicate item unless explicit policy. |
| CANCEL-18 | P2 | Cancel confirmation/back/error dialog. | Cancel-dialog dismissal does not mutate; errors visible and loading clears. |
-Paid cancellation/refund cases are conditional; see [payments/refunds](payments-refunds.md). Order-group IDs and usage row counts are required evidence.
+Cancellation is COD-only: there is no online payment and no refund record. Order-group IDs and usage row counts are required evidence.
diff --git a/docs/test-cases/order-edits-rebalance.md b/docs/test-cases/order-edits-rebalance.md
index 321b3b3..5d70c56 100644
--- a/docs/test-cases/order-edits-rebalance.md
+++ b/docs/test-cases/order-edits-rebalance.md
@@ -23,4 +23,4 @@ Scope: customer updateUserNotes, admin notes/removeDeliveryCharge/rebalanceSlots
| EDIT-17 | P1 | Decimal prices/caps after rebalance. | Agreed rounding; sum/detail use stored discount, never recomputed coupon. |
| EDIT-18 | P2 | Notes/rebalance confirmation cancel and reopen detail. | No unsaved action; clear affected scope and refreshed result. |
-Paid-order adjustment/refund interaction needs approved policy before execution. Avoid rebalancing shared production-like fixtures.
+Order edits are COD-only (no online payment, no refunds). Avoid rebalancing shared production-like fixtures.
diff --git a/docs/test-cases/payments-refunds.md b/docs/test-cases/payments-refunds.md
deleted file mode 100644
index a062e1a..0000000
--- a/docs/test-cases/payments-refunds.md
+++ /dev/null
@@ -1,28 +0,0 @@
-# Payments and refunds — readiness and guarded current behavior
-
-**Status:** Current customer UI disables online payment; gateway service code includes stubs. Only PAYMENT-01–03 are current release checks. Remaining cases are conditional readiness/security coverage for an approved sandbox implementation, not supported happy paths today. Never charge or refund production money.
-
-| ID | Priority | Action / input | Expected result |
-|---|---|---|---|
-| PAYMENT-01 | P0 | Attempt online selection in current UI. | Clearly unavailable/Coming Soon; no misleading successful online checkout. |
-| PAYMENT-02 | P0 | Place COD single/split checkout. | No gateway call; COD status and group money correct. |
-| PAYMENT-03 | P0 | Call unfinished online API in approved isolated fixture. | No false paid state, charge or misleading merchant ID; unsupported path explicit. |
-| PAYMENT-04 | P0 | Once enabled, sandbox single/split order payment. | One authoritative group amount in INR minor units; intended siblings paid once. |
-| PAYMENT-05 | P0 | Create merchant payment for U2's/missing/cancelled order. | Ownership/legal-state denial; no merchant payment created. |
-| PAYMENT-06 | P1 | Recreate pending merchant payment/retry request. | Supported existing pending record reused; no duplicate gateway order. |
-| PAYMENT-07 | P0 | Forged/empty/malformed signature or mismatched IDs. | Verification denied; order remains unpaid. |
-| PAYMENT-08 | P0 | Valid callback for another customer's payment. | Ownership still enforced beyond signature validity. |
-| PAYMENT-09 | P0 | Amount/currency tampering and UI-supplied payable. | Gateway/server authoritative group amount verified. |
-| PAYMENT-10 | P0 | Duplicate callback, replay, success webhook after failure. | Approved monotonic/idempotent status, no duplicate fulfillment. |
-| PAYMENT-11 | P1 | Decline/cancel/timeout/background gateway flow. | Accurate pending/failed state; usable retry/cart and no false success route. |
-| PAYMENT-12 | P0 | Mark other user's/successful payment failed. | Ownership/legal transitions enforced; paid order not reverted arbitrarily. |
-| PAYMENT-13 | P1 | Gateway committed, DB update or response fails. | Reconciliation strategy; no repeated charge on blind retry. |
-| PAYMENT-14 | P0 | Refund authorized paid cancelled order partially/fully. | Never exceeds net collected amount; correct status and intended recipient. |
-| PAYMENT-15 | P0 | Refund COD/unpaid/foreign-region/foreign-user order. | Appropriate denial; no money transfer or false refund ledger. |
-| PAYMENT-16 | P0 | Repeat/concurrent refund and duplicate webhook. | Exactly one approved refund; cumulative amount ≤ collected. |
-| PAYMENT-17 | P1 | Refund pending/fails/settles late, then customer refreshes. | Accurate ledger/status; failure doesn't claim settled money. |
-| PAYMENT-18 | P1 | Partial split cancellation and fees/coupon allocations. | Approved refundable amount derives from persisted charges, not current promotions. |
-| PAYMENT-19 | P0 | Secrets/card/payment payload in logs/API. | Credentials redacted; only required nonsecret response fields. |
-| PAYMENT-20 | P1 | Zero-amount order and rounding edge. | Defined no-charge gateway path; no invalid minor-unit amount. |
-
-Record sandbox transaction IDs in private evidence only. Refund allocation, successful-payment reversal and group settlement policy require approval before execution.
diff --git a/docs/test-cases/pricing-delivery-fees.md b/docs/test-cases/pricing-delivery-fees.md
index 0f21520..778855c 100644
--- a/docs/test-cases/pricing-delivery-fees.md
+++ b/docs/test-cases/pricing-delivery-fees.md
@@ -24,7 +24,7 @@ Scope: shared cart-pricing helpers, authoritative order pricing, client previews
| MONEY-18 | P1 | Fully discounted goods with nonzero fee vs free fee. | Correct D or zero total; authoritative zero handled in success UI. |
| MONEY-19 | P0 | Catalog/coupon changes after order placed. | Stored discount/price/detail stable; no recomputation from edited coupon. |
| MONEY-20 | P1 | Missing/invalid market/config values, zero/null cap. | Clear validation/fallback; no NaN/Infinity/negative price. Zero-cap semantics explicitly approved. |
-| MONEY-21 | P0 | Cancel/refund/remove fee/rebalance after split order. | Derived monetary changes reconcile without duplicate fee or lost historic discount. |
+| MONEY-21 | P0 | Cancel/remove fee/rebalance after a split order. | Derived monetary changes reconcile without duplicate fee or lost historic discount. |
| MONEY-22 | P1 | Large supported quantity/price/cart size. | No overflow, precision loss beyond policy, or dropped discount allocations. |
Policies to resolve before numerical PASS: compound percentage basis, currency rounding and residual allocation, zero maxValue meaning. Sorting percentage coupons before flat coupons is required regardless of percentage basis.
diff --git a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql b/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql
index 1ee80af..6df2e7f 100644
--- a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql
+++ b/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql
@@ -22,11 +22,17 @@
-- * per-bound business keys -> `region_bound_consts`
-- (incl. `isFlashDeliveryEnabled`, which each bound switches independently)
--
+-- Also folds in the later removal of online payments (never applied on its own):
+-- the app is Cash-on-Delivery only, so `payment_info`, `payments` and `refunds`
+-- are dropped and the payment flags/columns disappear from `orders` and
+-- `order_status` (Phase 5).
+--
-- Phases, kept in the original dependency order:
-- 1. regions / region_bounds / superadmins + seeds (from 0006)
-- 2. region_id backfill + 31-table rebuild (from 0007)
-- 3. global_consts / region_consts / region_bound_consts (from 0008+0009)
-- 4. coupon product targets -> `sku_ids` JSON arrays (from 0007_coupon_targets_json)
+-- 5. online payments / refunds removed (COD only)
--
-- Verified: applying this file to apps/backend/dumps/latest.sql yields the same
-- schema and the same rows as applying 0006..0009 in order.
@@ -117,14 +123,12 @@ WHERE NOT EXISTS (SELECT 1 FROM `superadmins` WHERE `username` = 'superadmin');
-- violation).
--
-- Live-DB findings this is sized for:
--- * 11 payments rows whose order no longer exists (all payment rows).
-- * 5 orders whose address no longer exists (their dependents deleted too,
-- per product-owner decision; purchase history for these is dropped).
+-- (`payments` / `refunds` orphans are irrelevant now: both tables are dropped
+-- in Phase 5, and no order was ever placed as an online payment.)
-- =====================================================================
--- Orphan payments first (also removes payments of the orphan orders below).
-DELETE FROM `payments` WHERE `order_id` NOT IN (SELECT `id` FROM `orders`);
---> statement-breakpoint
-- Detach coupon usage / complaints / incidents from the orphan orders before
-- removing the orders themselves (columns are nullable; deleting usage rows
-- entirely would also lose coupon history tied to surviving behavior).
@@ -140,10 +144,8 @@ WHERE `order_id` IN (SELECT `id` FROM `orders` WHERE `address_id` NOT IN (SELECT
UPDATE `user_incidents` SET `order_id` = NULL
WHERE `order_id` IN (SELECT `id` FROM `orders` WHERE `address_id` NOT IN (SELECT `id` FROM `addresses`));
--> statement-breakpoint
--- Delete the orphan orders' remaining hard dependents (order_status / refunds
--- included — their copies into the rebuilt tables would otherwise fail first).
-DELETE FROM `refunds` WHERE `order_id` IN (SELECT `id` FROM `orders` WHERE `address_id` NOT IN (SELECT `id` FROM `addresses`));
---> statement-breakpoint
+-- Delete the orphan orders' remaining hard dependents (their copies into the
+-- rebuilt tables would otherwise fail first).
DELETE FROM `order_status` WHERE `order_id` IN (SELECT `id` FROM `orders` WHERE `address_id` NOT IN (SELECT `id` FROM `addresses`));
--> statement-breakpoint
DELETE FROM `order_items` WHERE `order_id` IN (SELECT `id` FROM `orders` WHERE `address_id` NOT IN (SELECT `id` FROM `addresses`));
@@ -465,9 +467,6 @@ CREATE TABLE `__new_orders` (
`user_id` integer NOT NULL,
`address_id` integer NOT NULL,
`slot_id` integer,
- `is_cod` integer DEFAULT false NOT NULL,
- `is_online_payment` integer DEFAULT false NOT NULL,
- `payment_info_id` integer,
`total_amount` text NOT NULL,
`delivery_charge` text DEFAULT '0' NOT NULL,
`discount_amount` text DEFAULT '0' NOT NULL,
@@ -483,12 +482,11 @@ CREATE TABLE `__new_orders` (
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action,
FOREIGN KEY (`address_id`) REFERENCES `__new_addresses`(`id`) ON UPDATE no action ON DELETE no action,
FOREIGN KEY (`slot_id`) REFERENCES `__new_delivery_slot_info`(`id`) ON UPDATE no action ON DELETE no action,
- FOREIGN KEY (`payment_info_id`) REFERENCES `payment_info`(`id`) ON UPDATE no action ON DELETE no action,
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
);
--> statement-breakpoint
-INSERT INTO `__new_orders` (`id`,`user_id`,`address_id`,`slot_id`,`is_cod`,`is_online_payment`,`payment_info_id`,`total_amount`,`delivery_charge`,`discount_amount`,`readable_id`,`admin_notes`,`user_notes`,`order_group_id`,`order_group_proportion`,`is_flash_delivery`,`created_at`,`delivered_at`,`region_id`)
-SELECT `id`,`user_id`,`address_id`,`slot_id`,`is_cod`,`is_online_payment`,`payment_info_id`,`total_amount`,`delivery_charge`,'0',`readable_id`,`admin_notes`,`user_notes`,`order_group_id`,`order_group_proportion`,`is_flash_delivery`,`created_at`,`delivered_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `orders`;
+INSERT INTO `__new_orders` (`id`,`user_id`,`address_id`,`slot_id`,`total_amount`,`delivery_charge`,`discount_amount`,`readable_id`,`admin_notes`,`user_notes`,`order_group_id`,`order_group_proportion`,`is_flash_delivery`,`created_at`,`delivered_at`,`region_id`)
+SELECT `id`,`user_id`,`address_id`,`slot_id`,`total_amount`,`delivery_charge`,'0',`readable_id`,`admin_notes`,`user_notes`,`order_group_id`,`order_group_proportion`,`is_flash_delivery`,`created_at`,`delivered_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `orders`;
--> statement-breakpoint
CREATE TABLE `__new_order_items` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
@@ -517,47 +515,16 @@ CREATE TABLE `__new_order_status` (
`is_cancelled` integer DEFAULT false NOT NULL,
`cancel_reason` text,
`is_cancelled_by_admin` integer,
- `payment_state` text DEFAULT 'pending' NOT NULL,
`cancellation_user_notes` text,
`cancellation_admin_notes` text,
`cancellation_reviewed` integer DEFAULT false NOT NULL,
`cancellation_reviewed_at` text,
- `refund_coupon_id` integer,
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE no action,
- FOREIGN KEY (`order_id`) REFERENCES `__new_orders`(`id`) ON UPDATE no action ON DELETE no action,
- FOREIGN KEY (`refund_coupon_id`) REFERENCES `__new_coupons`(`id`) ON UPDATE no action ON DELETE no action
-);
---> statement-breakpoint
-INSERT INTO `__new_order_status` (`id`,`order_time`,`user_id`,`order_id`,`is_packaged`,`is_delivered`,`is_cancelled`,`cancel_reason`,`is_cancelled_by_admin`,`payment_state`,`cancellation_user_notes`,`cancellation_admin_notes`,`cancellation_reviewed`,`cancellation_reviewed_at`,`refund_coupon_id`)
-SELECT `id`,`order_time`,`user_id`,`order_id`,`is_packaged`,`is_delivered`,`is_cancelled`,`cancel_reason`,`is_cancelled_by_admin`,`payment_state`,`cancellation_user_notes`,`cancellation_admin_notes`,`cancellation_reviewed`,`cancellation_reviewed_at`,`refund_coupon_id` FROM `order_status`;
---> statement-breakpoint
-CREATE TABLE `__new_refunds` (
- `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
- `order_id` integer NOT NULL,
- `refund_amount` text,
- `refund_status` text DEFAULT 'none',
- `merchant_refund_id` text,
- `refund_processed_at` text,
- `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
FOREIGN KEY (`order_id`) REFERENCES `__new_orders`(`id`) ON UPDATE no action ON DELETE no action
);
--> statement-breakpoint
-INSERT INTO `__new_refunds` (`id`,`order_id`,`refund_amount`,`refund_status`,`merchant_refund_id`,`refund_processed_at`,`created_at`)
-SELECT `id`,`order_id`,`refund_amount`,`refund_status`,`merchant_refund_id`,`refund_processed_at`,`created_at` FROM `refunds`;
---> statement-breakpoint
-CREATE TABLE `__new_payments` (
- `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
- `status` text NOT NULL,
- `gateway` text NOT NULL,
- `order_id` integer NOT NULL,
- `token` text,
- `merchant_order_id` text NOT NULL,
- `payload` text,
- FOREIGN KEY (`order_id`) REFERENCES `__new_orders`(`id`) ON UPDATE no action ON DELETE no action
-);
---> statement-breakpoint
-INSERT INTO `__new_payments` (`id`,`status`,`gateway`,`order_id`,`token`,`merchant_order_id`,`payload`)
-SELECT `id`,`status`,`gateway`,`order_id`,`token`,`merchant_order_id`,`payload` FROM `payments`;
+INSERT INTO `__new_order_status` (`id`,`order_time`,`user_id`,`order_id`,`is_packaged`,`is_delivered`,`is_cancelled`,`cancel_reason`,`is_cancelled_by_admin`,`cancellation_user_notes`,`cancellation_admin_notes`,`cancellation_reviewed`,`cancellation_reviewed_at`)
+SELECT `id`,`order_time`,`user_id`,`order_id`,`is_packaged`,`is_delivered`,`is_cancelled`,`cancel_reason`,`is_cancelled_by_admin`,`cancellation_user_notes`,`cancellation_admin_notes`,`cancellation_reviewed`,`cancellation_reviewed_at` FROM `order_status`;
--> statement-breakpoint
CREATE TABLE `__new_coupon_usage` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
@@ -676,6 +643,24 @@ DROP TABLE `coupon_applicable_users`;
--> statement-breakpoint
DROP TABLE `coupon_usage`;
--> statement-breakpoint
+-- =====================================================================
+-- Phase 5: online payments removed — the app is Cash on Delivery only.
+--
+-- The rebuilt `orders` above already omits `is_cod`, `is_online_payment` and
+-- `payment_info_id`, and the rebuilt `order_status` omits `payment_state` and
+-- `refund_coupon_id`. Here the three payment tables go: `payments`/`refunds`
+-- are children of `orders` and are dropped before it (leaf-first, like every
+-- other table in this section); `payment_info` is the parent of the old
+-- `orders.payment_info_id`, so it is dropped right after `orders`.
+--
+-- Nothing to migrate: no order was ever placed as an online payment (the
+-- checkout only ever offered the disabled "Coming Soon" option), and the only
+-- `refunds` rows were the 'na' rows written for cancelled COD orders. To confirm
+-- on a live DB before applying:
+-- SELECT COUNT(*) FROM `orders` WHERE `is_online_payment` = 1; -- expect 0
+-- SELECT COUNT(*) FROM `payments`; -- expect 0
+-- SELECT COUNT(*) FROM `refunds` WHERE `refund_status` <> 'na'; -- expect 0
+-- =====================================================================
DROP TABLE `payments`;
--> statement-breakpoint
DROP TABLE `refunds`;
@@ -686,6 +671,9 @@ DROP TABLE `order_items`;
--> statement-breakpoint
DROP TABLE `orders`;
--> statement-breakpoint
+-- `payment_info` (the old `orders.payment_info_id` parent) has no dependents left.
+DROP TABLE `payment_info`;
+--> statement-breakpoint
DROP TABLE `product_group_membership`;
--> statement-breakpoint
DROP TABLE `product_tags`;
@@ -769,10 +757,6 @@ ALTER TABLE `__new_order_items` RENAME TO `order_items`;
--> statement-breakpoint
ALTER TABLE `__new_order_status` RENAME TO `order_status`;
--> statement-breakpoint
-ALTER TABLE `__new_refunds` RENAME TO `refunds`;
---> statement-breakpoint
-ALTER TABLE `__new_payments` RENAME TO `payments`;
---> statement-breakpoint
ALTER TABLE `__new_coupon_usage` RENAME TO `coupon_usage`;
--> statement-breakpoint
ALTER TABLE `__new_coupon_applicable_users` RENAME TO `coupon_applicable_users`;
@@ -802,8 +786,6 @@ CREATE UNIQUE INDEX `unique_combo_sku_item` ON `product_combos` (`combo_sku_id`,
--> statement-breakpoint
CREATE UNIQUE INDEX `unique_product_tag` ON `product_tags` (`product_id`,`tag_id`);
--> statement-breakpoint
-CREATE UNIQUE INDEX `payments_merchant_order_id_unique` ON `payments` (`merchant_order_id`);
---> statement-breakpoint
CREATE UNIQUE INDEX `unique_coupon_user` ON `coupon_applicable_users` (`coupon_id`,`user_id`);
--> statement-breakpoint
CREATE UNIQUE INDEX `reserved_coupons_secret_code_unique` ON `reserved_coupons` (`secret_code`);
diff --git a/packages/db_helper_sqlite/index.ts b/packages/db_helper_sqlite/index.ts
index a7dddbe..3505282 100644
--- a/packages/db_helper_sqlite/index.ts
+++ b/packages/db_helper_sqlite/index.ts
@@ -44,7 +44,6 @@ export {
getUsersForCoupon,
createCouponWithRelations,
updateCouponWithRelations,
- generateCancellationCoupon,
createReservedCoupon,
createCouponForUser,
checkUsersExist,
@@ -221,16 +220,6 @@ export {
getDeliverySlotById as getUserDeliverySlotById,
} from './src/user-apis/slots'
-export {
- // User Payments
- getOrderById as getUserPaymentOrderById,
- getPaymentByOrderId as getUserPaymentByOrderId,
- getPaymentByMerchantOrderId as getUserPaymentByMerchantOrderId,
- updatePaymentSuccess as updateUserPaymentSuccess,
- updateOrderPaymentStatus as updateUserOrderPaymentStatus,
- markPaymentFailed as markUserPaymentFailed,
-} from './src/user-apis/payments'
-
export {
// User Auth
getUserByEmail as getUserAuthByEmail,
diff --git a/packages/db_helper_sqlite/src/admin-apis/coupon.ts b/packages/db_helper_sqlite/src/admin-apis/coupon.ts
index c9d2c6c..5bba738 100644
--- a/packages/db_helper_sqlite/src/admin-apis/coupon.ts
+++ b/packages/db_helper_sqlite/src/admin-apis/coupon.ts
@@ -1,5 +1,5 @@
import { db } from '../db/db_index'
-import { coupons, reservedCoupons, users, orders, orderStatus, couponApplicableUsers, productSkus } from '../db/schema'
+import { coupons, reservedCoupons, users, orders, couponApplicableUsers, productSkus } from '../db/schema'
import { eq, and, like, or, inArray, lt, desc, asc, sql, isNull } from 'drizzle-orm'
import type { Coupon, CouponFormInput, CouponValidationResult, UserMiniInfo } from '@packages/shared'
@@ -293,55 +293,6 @@ export async function checkReservedCouponExists(secretCode: string): Promise
{
- const order = await db.query.orders.findFirst({
- where: eq(orders.id, orderId),
- columns: { id: true, regionId: true },
- })
- if (!order) {
- throw new Error('Order not found')
- }
- if (order.regionId !== regionId) {
- throw new Error('Order belongs to a different region')
- }
-
- return await db.transaction(async (tx) => {
- const expiryDate = new Date()
- expiryDate.setDate(expiryDate.getDate() + 30)
-
- const [coupon] = await tx.insert(coupons).values({
- regionId,
- couponCode,
- isUserBased: true,
- flatDiscount: orderAmount.toString(),
- minOrder: orderAmount.toString(),
- maxValue: orderAmount.toString(),
- validTill: expiryDate,
- maxLimitForUser: 1,
- createdBy: staffUserId,
- isApplyForAll: false,
- }).returning()
-
- await tx.insert(couponApplicableUsers).values({
- couponId: coupon.id,
- userId,
- })
-
- await tx.update(orderStatus)
- .set({ refundCouponId: coupon.id })
- .where(eq(orderStatus.orderId, orderId))
-
- return coupon as Coupon
- })
-}
-
export async function getOrderWithUser(regionId: number, orderId: number): Promise {
return await db.query.orders.findFirst({
where: and(
diff --git a/packages/db_helper_sqlite/src/admin-apis/order.ts b/packages/db_helper_sqlite/src/admin-apis/order.ts
index a6ab52c..63e6368 100644
--- a/packages/db_helper_sqlite/src/admin-apis/order.ts
+++ b/packages/db_helper_sqlite/src/admin-apis/order.ts
@@ -7,8 +7,6 @@ import {
orderItems,
orders,
orderStatus,
- payments,
- refunds,
} from '../db/schema'
import { and, desc, eq, gt, inArray, lt, SQL } from 'drizzle-orm'
import { releaseCouponUsageIfGroupFullyCancelled } from '../user-apis/order'
@@ -24,9 +22,6 @@ import type {
AdminGetAllOrdersResultWithUserId,
AdminRebalanceSlotsResult,
AdminCancelOrderResult,
- AdminRefundRecord,
- RefundStatus,
- PaymentStatus,
GetAllOrdersInput,
} from '@packages/shared'
import type { InferSelectModel } from 'drizzle-orm'
@@ -34,12 +29,6 @@ import { coerceDate } from '../lib/date'
import { marketStatsForRegion } from '../lib/market-stats'
import { composeSkuName, composeUnitNotation } from '../lib/sku-features'
-const isPaymentStatus = (value: string): value is PaymentStatus =>
- value === 'pending' || value === 'success' || value === 'cod' || value === 'failed'
-
-const isRefundStatus = (value: string): value is RefundStatus =>
- value === 'success' || value === 'pending' || value === 'failed' || value === 'none' || value === 'na' || value === 'processed'
-
type OrderStatusRow = InferSelectModel
const mapOrderStatusRecord = (record: OrderStatusRow): AdminOrderStatusRecord => ({
@@ -52,12 +41,10 @@ const mapOrderStatusRecord = (record: OrderStatusRow): AdminOrderStatusRecord =>
isCancelled: record.isCancelled,
cancelReason: record.cancelReason ?? null,
isCancelledByAdmin: record.isCancelledByAdmin ?? null,
- paymentStatus: isPaymentStatus(record.paymentStatus) ? record.paymentStatus : 'pending',
cancellationUserNotes: record.cancellationUserNotes ?? null,
cancellationAdminNotes: record.cancellationAdminNotes ?? null,
cancellationReviewed: record.cancellationReviewed,
cancellationReviewedAt: record.cancellationReviewedAt ?? null,
- refundCouponId: record.refundCouponId ?? null,
})
export async function updateOrderNotes(regionId: number, orderId: number, adminNotes: string | null): Promise {
@@ -148,10 +135,7 @@ export async function getOrderDetails(regionId: number, orderId: number): Promis
},
},
},
- payment: true,
- paymentInfo: true,
orderStatus: true,
- refunds: true,
},
})
@@ -194,22 +178,6 @@ export async function getOrderDetails(regionId: number, orderId: number): Promis
status = 'delivered'
}
- const refund = orderData.refunds?.[0]
- const refundStatus = refund?.refundStatus && isRefundStatus(refund.refundStatus)
- ? refund.refundStatus
- : null
- const refundRecord: AdminRefundRecord | null = refund
- ? {
- id: refund.id,
- orderId: refund.orderId,
- refundAmount: refund.refundAmount,
- refundStatus,
- merchantRefundId: refund.merchantRefundId,
- refundProcessedAt: refund.refundProcessedAt,
- createdAt: refund.createdAt,
- }
- : null
-
return {
id: orderData.id,
readableId: orderData.id,
@@ -231,8 +199,6 @@ export async function getOrderDetails(regionId: number, orderId: number): Promis
sequence: orderData.slot.deliverySequence,
}
: null,
- isCod: orderData.isCod,
- isOnlinePayment: orderData.isOnlinePayment,
totalAmount:
parseFloat(orderData.totalAmount?.toString() || '0') -
parseFloat(orderData.deliveryCharge?.toString() || '0'),
@@ -259,33 +225,13 @@ export async function getOrderDetails(regionId: number, orderId: number): Promis
featureValue: f.featureValue,
})),
})),
- payment: orderData.payment
- ? {
- status: orderData.payment.status,
- gateway: orderData.payment.gateway,
- merchantOrderId: orderData.payment.merchantOrderId,
- }
- : null,
- paymentInfo: orderData.paymentInfo
- ? {
- status: orderData.paymentInfo.status,
- gateway: orderData.paymentInfo.gateway,
- merchantOrderId: orderData.paymentInfo.merchantOrderId,
- }
- : null,
cancelReason: orderStatusRecord?.cancelReason || null,
cancellationReviewed: orderStatusRecord?.cancellationReviewed || false,
- isRefundDone: refundStatus === 'processed' || false,
- refundStatus,
- refundAmount: refund?.refundAmount
- ? parseFloat(refund.refundAmount.toString())
- : null,
couponData,
couponCode: couponData?.couponCode || null,
couponDescription: couponData?.couponDescription || null,
discountAmount: couponData?.discountAmount || null,
orderStatus: orderStatusRecord,
- refundRecord,
isFlashDelivery: orderData.isFlashDelivery,
}
}
@@ -386,12 +332,7 @@ export async function getSlotOrders(regionId: number, slotId: string): Promise {
- const statusRecord = order.orderStatus[0]
- return order.isCod || (statusRecord && statusRecord.paymentStatus === 'success')
- })
-
- const formattedOrders = filteredOrders.map((order: any) => {
+ const formattedOrders = slotOrders.map((order: any) => {
const statusRecord = order.orderStatus[0]
let status: 'pending' | 'delivered' | 'cancelled' = 'pending'
if (statusRecord?.isCancelled) {
@@ -416,8 +357,6 @@ export async function getSlotOrders(regionId: number, slotId: string): Promise item.is_packaged) || false,
isDelivered: statusRecord?.isDelivered || false,
- isCod: order.isCod,
- paymentMode,
- paymentStatus: isPaymentStatus(statusRecord?.paymentStatus || 'pending')
- ? statusRecord?.paymentStatus || 'pending'
- : 'pending',
slotId: order.slotId,
adminNotes: order.adminNotes,
userNotes: order.userNotes,
@@ -545,12 +479,7 @@ export async function getAllOrders(regionId: number, input: GetAllOrdersInput):
const hasMore = allOrders.length > limit
const ordersToReturn = hasMore ? allOrders.slice(0, limit) : allOrders
- const filteredOrders = ordersToReturn.filter((order: any) => {
- const statusRecord = order.orderStatus[0]
- return order.isCod || (statusRecord && statusRecord.paymentStatus === 'success')
- })
-
- const formattedOrders = filteredOrders.map((order: any) => {
+ const formattedOrders = ordersToReturn.map((order: any) => {
const statusRecord = order.orderStatus[0]
let status: 'pending' | 'delivered' | 'cancelled' = 'pending'
if (statusRecord?.isCancelled) {
@@ -599,7 +528,6 @@ export async function getAllOrders(regionId: number, input: GetAllOrdersInput):
status,
isPackaged: order.orderItems.every((item: any) => item.is_packaged) || false,
isDelivered: statusRecord?.isDelivered || false,
- isCod: order.isCod,
isFlashDelivery: order.isFlashDelivery,
userNotes: order.userNotes,
adminNotes: order.adminNotes,
@@ -749,13 +677,6 @@ export async function cancelOrder(regionId: number, orderId: number, reason: str
})
.where(eq(orderStatus.id, status.id))
- const refundStatus = order.isCod ? 'na' : 'pending'
-
- await tx.insert(refunds).values({
- orderId: order.id,
- refundStatus,
- })
-
await releaseCouponUsageIfGroupFullyCancelled(tx, order.id)
return { orderId: order.id, userId: order.userId }
@@ -781,8 +702,6 @@ export async function deleteOrderById(regionId: number, orderId: number): Promis
await db.transaction(async (tx) => {
await tx.delete(orderItems).where(eq(orderItems.orderId, orderId))
await tx.delete(orderStatus).where(eq(orderStatus.orderId, orderId))
- await tx.delete(payments).where(eq(payments.orderId, orderId))
- await tx.delete(refunds).where(eq(refunds.orderId, orderId))
await tx.delete(couponUsage).where(eq(couponUsage.orderId, orderId))
await tx.delete(complaints).where(eq(complaints.orderId, orderId))
await tx.delete(orders).where(and(eq(orders.id, orderId), eq(orders.regionId, regionId)))
diff --git a/packages/db_helper_sqlite/src/db/schema.ts b/packages/db_helper_sqlite/src/db/schema.ts
index 9fd6c05..4e90249 100644
--- a/packages/db_helper_sqlite/src/db/schema.ts
+++ b/packages/db_helper_sqlite/src/db/schema.ts
@@ -64,13 +64,11 @@ const timestampText = (name: string) =>
const staffRoleValues = ['super_admin', 'admin', 'marketer', 'delivery_staff'] as const
const staffPermissionValues = ['crud_product', 'make_coupon', 'crud_staff_users'] as const
const uploadStatusValues = ['pending', 'claimed'] as const
-const paymentStatusValues = ['pending', 'success', 'cod', 'failed'] as const
const productTypeValues = ['item', 'combo'] as const
export const staffRoleEnum = (name: string) => text(name, { enum: staffRoleValues })
export const staffPermissionEnum = (name: string) => text(name, { enum: staffPermissionValues })
export const uploadStatusEnum = (name: string) => text(name, { enum: uploadStatusValues })
-export const paymentStatusEnum = (name: string) => text(name, { enum: paymentStatusValues })
export const productTypeEnum = (name: string) => text(name, { enum: productTypeValues })
export const users = sqliteTable('users', {
@@ -343,25 +341,12 @@ export const specialDeals = sqliteTable('special_deals', {
validTill: timestampText('valid_till').notNull(),
})
-export const paymentInfoTable = sqliteTable('payment_info', {
- id: integer().primaryKey({ autoIncrement: true }),
- status: text().notNull(),
- gateway: text().notNull(),
- orderId: text('order_id'),
- token: text('token'),
- merchantOrderId: text('merchant_order_id').notNull().unique(),
- payload: jsonText('payload'),
-})
-
export const orders = sqliteTable('orders', {
id: integer().primaryKey({ autoIncrement: true }),
regionId: integer('region_id').references(() => regions.id),
userId: integer('user_id').notNull().references(() => users.id),
addressId: integer('address_id').notNull().references(() => addresses.id),
slotId: integer('slot_id').references(() => deliverySlotInfo.id),
- isCod: integer('is_cod', { mode: 'boolean' }).notNull().default(false),
- isOnlinePayment: integer('is_online_payment', { mode: 'boolean' }).notNull().default(false),
- paymentInfoId: integer('payment_info_id').references(() => paymentInfoTable.id),
totalAmount: numericText('total_amount').notNull(),
deliveryCharge: numericText('delivery_charge').notNull().default('0'),
discountAmount: numericText('discount_amount').notNull().default('0'),
@@ -397,32 +382,10 @@ export const orderStatus = sqliteTable('order_status', {
isCancelled: integer('is_cancelled', { mode: 'boolean' }).notNull().default(false),
cancelReason: text('cancel_reason'),
isCancelledByAdmin: integer('is_cancelled_by_admin', { mode: 'boolean' }),
- paymentStatus: paymentStatusEnum('payment_state').notNull().default('pending'),
cancellationUserNotes: text('cancellation_user_notes'),
cancellationAdminNotes: text('cancellation_admin_notes'),
cancellationReviewed: integer('cancellation_reviewed', { mode: 'boolean' }).notNull().default(false),
cancellationReviewedAt: timestampText('cancellation_reviewed_at'),
- refundCouponId: integer('refund_coupon_id').references(() => coupons.id),
-})
-
-export const payments = sqliteTable('payments', {
- id: integer().primaryKey({ autoIncrement: true }),
- status: text().notNull(),
- gateway: text().notNull(),
- orderId: integer('order_id').notNull().references(() => orders.id),
- token: text('token'),
- merchantOrderId: text('merchant_order_id').notNull().unique(),
- payload: jsonText('payload'),
-})
-
-export const refunds = sqliteTable('refunds', {
- id: integer().primaryKey({ autoIncrement: true }),
- orderId: integer('order_id').notNull().references(() => orders.id),
- refundAmount: numericText('refund_amount'),
- refundStatus: text('refund_status').default('none'),
- merchantRefundId: text('merchant_refund_id'),
- refundProcessedAt: timestampText('refund_processed_at'),
- createdAt: timestampText('created_at').notNull().default(sql`CURRENT_TIMESTAMP`),
})
export const keyValStore = sqliteTable('key_val_store', {
@@ -748,10 +711,7 @@ export const ordersRelations = relations(orders, ({ one, many }) => ({
address: one(addresses, { fields: [orders.addressId], references: [addresses.id] }),
slot: one(deliverySlotInfo, { fields: [orders.slotId], references: [deliverySlotInfo.id] }),
orderItems: many(orderItems),
- payment: one(payments),
- paymentInfo: one(paymentInfoTable, { fields: [orders.paymentInfoId], references: [paymentInfoTable.id] }),
orderStatus: many(orderStatus),
- refunds: many(refunds),
couponUsages: many(couponUsage),
userIncidents: many(userIncidents),
}))
@@ -764,19 +724,6 @@ export const orderItemsRelations = relations(orderItems, ({ one }) => ({
export const orderStatusRelations = relations(orderStatus, ({ one }) => ({
order: one(orders, { fields: [orderStatus.orderId], references: [orders.id] }),
user: one(users, { fields: [orderStatus.userId], references: [users.id] }),
- refundCoupon: one(coupons, { fields: [orderStatus.refundCouponId], references: [coupons.id] }),
-}))
-
-export const paymentInfoRelations = relations(paymentInfoTable, ({ one }) => ({
- order: one(orders, { fields: [paymentInfoTable.id], references: [orders.paymentInfoId] }),
-}))
-
-export const paymentsRelations = relations(payments, ({ one }) => ({
- order: one(orders, { fields: [payments.orderId], references: [orders.id] }),
-}))
-
-export const refundsRelations = relations(refunds, ({ one }) => ({
- order: one(orders, { fields: [refunds.orderId], references: [orders.id] }),
}))
export const notificationsRelations = relations(notifications, ({ one }) => ({
diff --git a/packages/db_helper_sqlite/src/lib/delete-orders.ts b/packages/db_helper_sqlite/src/lib/delete-orders.ts
index f2595f4..35b9c3e 100644
--- a/packages/db_helper_sqlite/src/lib/delete-orders.ts
+++ b/packages/db_helper_sqlite/src/lib/delete-orders.ts
@@ -1,5 +1,5 @@
import { db } from '../db/db_index'
-import { orders, orderItems, orderStatus, payments, refunds, couponUsage, complaints } from '../db/schema'
+import { orders, orderItems, orderStatus, couponUsage, complaints } from '../db/schema'
import { inArray } from 'drizzle-orm'
import { runBatched } from './run-batched'
@@ -23,19 +23,13 @@ export async function deleteOrdersWithRelations(orderIds: number[]): Promise
- refunds: Array<{
- refundStatus: string
- refundAmount: string | null
- }>
}
export type OrderDetailWithRelations = OrderWithRelations;
@@ -337,29 +324,14 @@ export async function placeOrderTransaction(params: {
orderItems: Omit[]
orderStatus: Omit
}>
- paymentMethod: 'online' | 'cod'
totalWithDelivery: number
}): Promise {
- const { userId, ordersData, paymentMethod } = params
+ const { userId, ordersData } = params
return db.transaction(async (tx) => {
- let sharedPaymentInfoId: number | null = null
- if (paymentMethod === 'online') {
- const [paymentInfo] = await tx
- .insert(paymentInfoTable)
- .values({
- status: 'pending',
- gateway: 'razorpay',
- merchantOrderId: `multi_order_${Date.now()}`,
- })
- .returning()
- sharedPaymentInfoId = paymentInfo.id
- }
-
const ordersToInsert: Omit[] =
ordersData.map((od) => ({
...od.order,
- paymentInfoId: sharedPaymentInfoId,
}))
const insertedOrders = await tx.insert(orders).values(ordersToInsert).returning()
@@ -451,27 +423,14 @@ export async function getOrdersWithRelations(
deliveryTime: true,
},
},
- paymentInfo: {
- columns: {
- id: true,
- status: true,
- },
- },
orderStatus: {
columns: {
id: true,
isCancelled: true,
isDelivered: true,
- paymentStatus: true,
cancelReason: true,
},
},
- refunds: {
- columns: {
- refundStatus: true,
- refundAmount: true,
- },
- },
region: {
columns: {
id: true,
@@ -572,34 +531,13 @@ export async function getOrderByIdWithRelations(
deliveryTime: true,
},
},
- paymentInfo: {
- columns: {
- id: true,
- status: true,
- },
- },
orderStatus: {
columns: {
id: true,
isCancelled: true,
isDelivered: true,
- paymentStatus: true,
cancelReason: true,
},
- with: {
- refundCoupon: {
- columns: {
- id: true,
- couponCode: true,
- },
- },
- },
- },
- refunds: {
- columns: {
- refundStatus: true,
- refundAmount: true,
- },
},
region: {
columns: {
@@ -741,8 +679,7 @@ export async function releaseCouponUsageIfGroupFullyCancelled(
export async function cancelOrderTransaction(
orderId: number,
statusId: number,
- reason: string,
- isCod: boolean
+ reason: string
): Promise {
await db.transaction(async (tx) => {
await tx
@@ -755,13 +692,6 @@ export async function cancelOrderTransaction(
})
.where(eq(orderStatus.id, statusId))
- const refundStatus = isCod ? 'na' : 'pending'
-
- await tx.insert(refunds).values({
- orderId,
- refundStatus,
- })
-
await releaseCouponUsageIfGroupFullyCancelled(tx, orderId)
})
}
@@ -854,11 +784,7 @@ export async function getOrdersByIdsWithFullData(
return orderChunks.flat() as unknown as OrderWithFullData[]
}
-export interface OrderWithCancellationData extends OrderWithFullData {
- refunds: Array<{
- refundStatus: string
- }>
-}
+export type OrderWithCancellationData = OrderWithFullData
export async function getOrderByIdWithFullData(
orderId: number
@@ -894,11 +820,6 @@ export async function getOrderByIdWithFullData(
deliveryTime: true,
},
},
- refunds: {
- columns: {
- refundStatus: true,
- },
- },
},
}) as Promise
}
diff --git a/packages/db_helper_sqlite/src/user-apis/payments.ts b/packages/db_helper_sqlite/src/user-apis/payments.ts
deleted file mode 100644
index 5657bba..0000000
--- a/packages/db_helper_sqlite/src/user-apis/payments.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { db } from '../db/db_index'
-import { orders, payments, orderStatus } from '../db/schema'
-import { eq } from 'drizzle-orm'
-
-export async function getOrderById(orderId: number) {
- return db.query.orders.findFirst({
- where: eq(orders.id, orderId),
- })
-}
-
-export async function getPaymentByOrderId(orderId: number) {
- return db.query.payments.findFirst({
- where: eq(payments.orderId, orderId),
- })
-}
-
-export async function getPaymentByMerchantOrderId(merchantOrderId: string) {
- return db.query.payments.findFirst({
- where: eq(payments.merchantOrderId, merchantOrderId),
- })
-}
-
-export async function updatePaymentSuccess(merchantOrderId: string, payload: unknown) {
- const [updatedPayment] = await db
- .update(payments)
- .set({
- status: 'success',
- payload,
- })
- .where(eq(payments.merchantOrderId, merchantOrderId))
- .returning({
- id: payments.id,
- orderId: payments.orderId,
- })
-
- return updatedPayment || null
-}
-
-export async function updateOrderPaymentStatus(orderId: number, status: 'pending' | 'success' | 'cod' | 'failed') {
- await db
- .update(orderStatus)
- .set({ paymentStatus: status })
- .where(eq(orderStatus.orderId, orderId))
-}
-
-export async function markPaymentFailed(paymentId: number) {
- await db
- .update(payments)
- .set({ status: 'failed' })
- .where(eq(payments.id, paymentId))
-}
diff --git a/packages/shared/types/admin.ts b/packages/shared/types/admin.ts
index 3e1f42f..200f962 100644
--- a/packages/shared/types/admin.ts
+++ b/packages/shared/types/admin.ts
@@ -43,10 +43,6 @@ export type AdminOrderRow = Omit