diff --git a/apps/admin-ui/app/(drawer)/dashboard/manage-orders/order-details/[id].tsx b/apps/admin-ui/app/(drawer)/dashboard/manage-orders/order-details/[id].tsx index 67d766b..85a9111 100644 --- a/apps/admin-ui/app/(drawer)/dashboard/manage-orders/order-details/[id].tsx +++ b/apps/admin-ui/app/(drawer)/dashboard/manage-orders/order-details/[id].tsx @@ -18,13 +18,7 @@ import { UserIncidentsView } from "@/components/UserIncidentsView"; export default function OrderDetails() { const { id } = useLocalSearchParams<{ id: string }>(); const router = useRouter(); - const [generateCouponDialogOpen, setGenerateCouponDialogOpen] = - useState(false); - const [initiateRefundDialogOpen, setInitiateRefundDialogOpen] = - useState(false); const [cancelDialogOpen, setCancelDialogOpen] = useState(false); - const [refundType, setRefundType] = useState<"percent" | "amount">("percent"); - const [refundValue, setRefundValue] = useState("100"); const [updatingItems, setUpdatingItems] = useState>(new Set()); const { @@ -37,45 +31,6 @@ export default function OrderDetails() { { enabled: !!id } ); - const generateCouponMutation = - trpc.admin.coupon.generateCancellationCoupon.useMutation({ - onSuccess: (coupon) => { - Alert.alert( - "Success", - `Refund coupon generated successfully!\n\nCode: ${coupon.couponCode - }\nValue: ₹${coupon.flatDiscount}\nExpires: ${coupon.validTill - ? new Date(coupon.validTill).toLocaleDateString() - : "N/A" - }` - ); - refetch(); - setGenerateCouponDialogOpen(false); - }, - onError: (error: any) => { - Alert.alert( - "Error", - error.message || "Failed to generate refund coupon" - ); - }, - }); - - const initiateRefundMutation = trpc.admin.payments.initiateRefund.useMutation( - { - onSuccess: (result) => { - Alert.alert( - "Success", - `Refund initiated successfully!\n\nAmount: ` - // `Refund initiated successfully!\n\nAmount: ₹${result.amount}\nStatus: ${result.status}` - ); - refetch(); - setInitiateRefundDialogOpen(false); - }, - onError: (error: any) => { - Alert.alert("Error", error.message || "Failed to initiate refund"); - }, - } - ); - const updateItemPackagingMutation = trpc.admin.order.updateOrderItemPackaging.useMutation({ onSuccess: () => { // Refetch order details to get updated packaging status @@ -136,35 +91,6 @@ export default function OrderDetails() { const subtotal = order.items.reduce((sum, item) => sum + item.amount, 0); const discountAmount = order.discountAmount || 0; - const handleGenerateCoupon = () => { - generateCouponMutation.mutate({ orderId: order.id }); - }; - - const handleInitiateRefund = () => { - const value = parseFloat(refundValue); - if (isNaN(value) || value <= 0) { - Alert.alert("Error", "Please enter a valid refund value"); - return; - } - - const mutationData: any = { - orderId: order.id, - }; - - if (refundType === "percent") { - if (value > 100) { - Alert.alert("Error", "Refund percentage cannot exceed 100%"); - return; - } - mutationData.refundPercent = value; - } else { - mutationData.refundAmount = value; - } - - initiateRefundMutation.mutate(mutationData); - setInitiateRefundDialogOpen(false); - }; - const handlePackagingToggle = (itemId: number, field: 'isPackaged' | 'isPackageVerified', value: boolean) => { // Add item to updating set to disable UI setUpdatingItems(prev => new Set(prev).add(itemId)); @@ -199,30 +125,7 @@ export default function OrderDetails() { }; const statusStyle = getStatusColor(order.status); - const showRefundOptions = true; - const getRefundDotColor = (status: string) => { - if (status === 'success') return 'bg-green-500'; - else if (status === 'pending') return 'bg-yellow-500'; - else if (status === 'failed') return 'bg-red-500'; - else return 'bg-gray-500'; - }; - - const getRefundTextColor = (status: string) => { - if (status === 'success' || status === 'na') return 'text-green-700'; - else if (status === 'pending') return 'text-yellow-700'; - else if (status === 'failed') return 'text-red-700'; - else return 'text-gray-700'; - }; - - const getRefundStatusText = (status: string) => { - if (status === 'success' || status === 'na') return 'Completed'; - else if (status === 'pending') return 'Pending'; - else if (status === 'failed') return 'Failed'; - else if (status === 'none') return 'Not Initiated'; - else if (status === 'na') return 'Not Applicable'; - else return 'Unknown'; - }; return ( @@ -652,121 +555,6 @@ export default function OrderDetails() { )} - {/* Refund Coupon Section */} - {order.orderStatus?.refundCouponId && ( - - - Refund Coupon - - - - - - {order.couponCode} - - - - Generated refund coupon for order cancellation - - - - Value: - - - ₹{order.couponData?.discountAmount} - - - {/* - - Expires: - - - {order.couponData?. - ? dayjs(order.orderStatus.refundCoupon.validTill).format("DD MMM YYYY") - : "N/A"} - - */} - - - )} - - {/* TEMPORARILY HIDDEN: Refund Details Section */} - {/* WARNING: This section contains functional refund and cancellation management features */} - {/* DO NOT REMOVE - This is temporarily commented out for UI simplification */} - {/* When ready to re-enable, simply uncomment the entire block below */} - {/* - - - {order.status === "cancelled" ? "Cancellation Details" : "Refund Details"} - - {order.status === "cancelled" && order.cancelReason && ( - - - Cancellation Reason - - - {order.cancelReason} - - - )} - - - Refund Status - - - - - {getRefundStatusText(order.refundStatus)} - - - - {order.refundRecord && ( - - - Refund Amount - - - ₹{order.refundRecord.refundAmount} - - - )} - - {(!Boolean(order.refundRecord)) && - {!order.isCod && ( setInitiateRefundDialogOpen(true)} - > - - - Initiate Refund - - - )} - setGenerateCouponDialogOpen(true)} - > - - - Generate Refund Coupon - - - } - - - */} @@ -795,163 +583,6 @@ export default function OrderDetails() { - {/* Generate Coupon Dialog */} - setGenerateCouponDialogOpen(false)} - > - - - - - - - Generate Refund Coupon - - - Create a one-time use coupon for the customer equal to the order amount. Valid for 30 days. - - - - - - - This only works for online payment orders. COD orders cannot generate refund coupons. - - - - - setGenerateCouponDialogOpen(false)} - > - Cancel - - - - {generateCouponMutation.isPending - ? "Generating..." - : "Generate Coupon"} - - - - - - - {/* Initiate Refund Dialog */} - setInitiateRefundDialogOpen(false)} - > - - - - - - - Initiate Refund - - - Process a refund directly to the customer's source account via Razorpay. - - - - {/* Refund Type Selection */} - - - Refund Type - - - setRefundType("percent")} - > - - - Percentage - - - - setRefundType("amount")} - > - - - Fixed Amount - - - - - - {/* Refund Value Input */} - - - - - - - - For COD orders, refunds are processed immediately upon delivery confirmation. - - - - - setInitiateRefundDialogOpen(false)} - > - Cancel - - - - {initiateRefundMutation.isPending - ? "Processing..." - : "Confirm Refund"} - - - - - - {/* Cancel Order Dialog */} void } {/* {order.status} */} - {/* {order.isCod && ( - - COD - - )} */} Packaged - This will cancel the order and mark it as cancelled by admin. A refund record will be created. + This will cancel the order and mark it as cancelled by admin. diff --git a/apps/admin-ui/tests/screens/delivery-sequences.test.tsx b/apps/admin-ui/tests/screens/delivery-sequences.test.tsx index 8170457..d7feb61 100644 --- a/apps/admin-ui/tests/screens/delivery-sequences.test.tsx +++ b/apps/admin-ui/tests/screens/delivery-sequences.test.tsx @@ -51,9 +51,6 @@ const slotOrder = (overrides: Record = {}) => ({ status: 'pending', isPackaged: false, isDelivered: false, - isCod: true, - paymentMode: 'COD', - paymentStatus: 'cod', slotId: 3, adminNotes: 'fragile', userNotes: null, diff --git a/apps/admin-ui/tests/screens/manage-orders-orders.test.tsx b/apps/admin-ui/tests/screens/manage-orders-orders.test.tsx index d298881..979210e 100644 --- a/apps/admin-ui/tests/screens/manage-orders-orders.test.tsx +++ b/apps/admin-ui/tests/screens/manage-orders-orders.test.tsx @@ -51,7 +51,6 @@ const makeOrder = (overrides: Record = {}) => ({ status: 'pending', isPackaged: false, isDelivered: false, - isCod: true, isFlashDelivery: false, userNotes: null, adminNotes: 'call before delivery', diff --git a/apps/admin-ui/tests/screens/order-details.test.tsx b/apps/admin-ui/tests/screens/order-details.test.tsx index dc67889..bf058b2 100644 --- a/apps/admin-ui/tests/screens/order-details.test.tsx +++ b/apps/admin-ui/tests/screens/order-details.test.tsx @@ -2,11 +2,6 @@ * Order details (app/(drawer)/dashboard/manage-orders/order-details/[id].tsx) — * detail rendering, packaging toggles, delivery-charge removal, cancellation * and navigation. - * - * NOTE: the "Initiate Refund" / "Generate Refund Coupon" action block is - * commented out in the source (lines ~697-769) and the state setters that open - * those dialogs are never invoked, so those two mutations are not reachable - * through the UI and cannot be integration-tested. */ jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) @@ -38,8 +33,6 @@ const makeDetails = (overrides: Record = {}) => ({ phone: '9876543210', }, slotInfo: { time: '2026-01-02T10:00:00.000Z', sequence: null }, - isCod: false, - isOnlinePayment: true, totalAmount: 500, deliveryCharge: 20, adminNotes: 'handle with care', @@ -61,19 +54,13 @@ const makeDetails = (overrides: Record = {}) => ({ unit: 'kg', }, ], - payment: null, - paymentInfo: null, cancelReason: null, cancellationReviewed: false, - isRefundDone: false, - refundStatus: null, - refundAmount: null, couponData: null, couponCode: null, couponDescription: null, discountAmount: 0, orderStatus: null, - refundRecord: null, isFlashDelivery: false, ...overrides, }) @@ -228,35 +215,6 @@ describe('Order details', () => { expect(screen.getAllByText('-₹50').length).toBeGreaterThan(0) }) - it('renders the refund coupon block when one exists', async () => { - renderDetails({ - 'admin.order.getOrderDetails': makeDetails({ - couponCode: 'REF10', - couponData: { couponCode: 'REF10', couponDescription: '', discountAmount: 100 }, - orderStatus: { - id: 1, - orderTime: '2026-01-01T10:00:00.000Z', - userId: 5, - orderId: 11, - isPackaged: false, - isDelivered: false, - isCancelled: true, - cancelReason: 'x', - isCancelledByAdmin: true, - paymentStatus: 'success', - cancellationUserNotes: null, - cancellationAdminNotes: null, - cancellationReviewed: false, - cancellationReviewedAt: null, - refundCouponId: 9, - }, - }), - }) - - await waitFor(() => expect(screen.getByText('Refund Coupon')).toBeVisible()) - expect(screen.getByText('₹100')).toBeVisible() - }) - it('navigates to user management from customer details', async () => { renderDetails() diff --git a/apps/admin-web/src/components/CancelOrderDialog.tsx b/apps/admin-web/src/components/CancelOrderDialog.tsx index e6e4b89..3721bb1 100644 --- a/apps/admin-web/src/components/CancelOrderDialog.tsx +++ b/apps/admin-web/src/components/CancelOrderDialog.tsx @@ -49,7 +49,7 @@ export default function CancelOrderDialog({ orderId, open, onClose, onSuccess }: Cancel Order

- This will cancel the order and mark it as cancelled by admin. A refund record will be created. + This will cancel the order and mark it as cancelled by admin.

diff --git a/apps/admin-web/src/routes/dashboard.orders.$id.tsx b/apps/admin-web/src/routes/dashboard.orders.$id.tsx index 7aa3a26..0957d30 100644 --- a/apps/admin-web/src/routes/dashboard.orders.$id.tsx +++ b/apps/admin-web/src/routes/dashboard.orders.$id.tsx @@ -34,13 +34,7 @@ export const Route = createFileRoute('/dashboard/orders/$id')({ function OrderDetails() { const { id } = Route.useParams() const navigate = useNavigate() - const [generateCouponDialogOpen, setGenerateCouponDialogOpen] = - useState(false) - const [initiateRefundDialogOpen, setInitiateRefundDialogOpen] = - useState(false) const [cancelDialogOpen, setCancelDialogOpen] = useState(false) - const [refundType, setRefundType] = useState<'percent' | 'amount'>('percent') - const [refundValue, setRefundValue] = useState('100') const [updatingItems, setUpdatingItems] = useState>(new Set()) const { @@ -53,40 +47,6 @@ function OrderDetails() { { enabled: !!id } ) - const generateCouponMutation = - trpc.admin.coupon.generateCancellationCoupon.useMutation({ - onSuccess: (coupon) => { - window.alert( - `Success: Refund coupon generated successfully!\n\nCode: ${coupon.couponCode - }\nValue: ₹${coupon.flatDiscount}\nExpires: ${coupon.validTill - ? new Date(coupon.validTill).toLocaleDateString() - : 'N/A' - }` - ) - setGenerateCouponDialogOpen(false) - }, - onError: (error: any) => { - ErrorToast( - error.message || 'Failed to generate refund coupon' - ) - }, - }) - - const initiateRefundMutation = trpc.admin.payments.initiateRefund.useMutation( - { - onSuccess: () => { - window.alert( - 'Success: Refund initiated successfully!\n\nAmount: ' - // `Refund initiated successfully!\n\nAmount: ₹${result.amount}\nStatus: ${result.status}` - ) - setInitiateRefundDialogOpen(false) - }, - onError: (error: any) => { - ErrorToast(error.message || 'Failed to initiate refund') - }, - } - ) - const updateItemPackagingMutation = trpc.admin.order.updateOrderItemPackaging.useMutation({ onSuccess: () => { // Refetch order details to get updated packaging status @@ -145,35 +105,6 @@ function OrderDetails() { const subtotal = order.items.reduce((sum, item) => sum + item.amount, 0) const discountAmount = order.discountAmount || 0 - const handleGenerateCoupon = () => { - generateCouponMutation.mutate({ orderId: order.id }) - } - - const handleInitiateRefund = () => { - const value = parseFloat(refundValue) - if (isNaN(value) || value <= 0) { - ErrorToast('Please enter a valid refund value') - return - } - - const mutationData: any = { - orderId: order.id, - } - - if (refundType === 'percent') { - if (value > 100) { - ErrorToast('Refund percentage cannot exceed 100%') - return - } - mutationData.refundPercent = value - } else { - mutationData.refundAmount = value - } - - initiateRefundMutation.mutate(mutationData) - setInitiateRefundDialogOpen(false) - } - const handlePackagingToggle = (itemId: number, field: 'isPackaged' | 'isPackageVerified', value: boolean) => { // Add item to updating set to disable UI setUpdatingItems((prev) => new Set(prev).add(itemId)) @@ -600,38 +531,6 @@ function OrderDetails() { )} - {/* Refund Coupon Section */} - {order.orderStatus?.refundCouponId && ( -
- - Refund Coupon - -
-
- - - {order.couponCode} - -
- - Generated refund coupon for order cancellation - -
- - Value: - - - ₹{order.couponData?.discountAmount} - -
-
-
- )} - - {/* TEMPORARILY HIDDEN: Refund Details Section */} - {/* WARNING: This section contains functional refund and cancellation management features */} - {/* DO NOT REMOVE - This is temporarily commented out for UI simplification */} - {/* When ready to re-enable, simply uncomment the entire block below */}
@@ -657,161 +556,6 @@ function OrderDetails() {
- {/* Generate Coupon Dialog */} - setGenerateCouponDialogOpen(false)} - > -
-
- - - - - Generate Refund Coupon - - - Create a one-time use coupon for the customer equal to the order amount. Valid for 30 days. - -
- -
- - - This only works for online payment orders. COD orders cannot generate refund coupons. - -
- -
- - -
-
-
- - {/* Initiate Refund Dialog */} - setInitiateRefundDialogOpen(false)} - > -
-
- - - - - Initiate Refund - - - Process a refund directly to the customer's source account via Razorpay. - -
- - {/* Refund Type Selection */} -
- - Refund Type - -
- - - -
-
- - {/* Refund Value Input */} -
- setRefundValue(e.target.value)} - type="number" - placeholder={refundType === 'percent' ? '100' : '0.00'} - className="bg-white" - /> -
- -
- - - For COD orders, refunds are processed immediately upon delivery confirmation. - -
- -
- - -
-
-
- {/* Cancel Order Dialog */} { const start = Date.now(); try { - console.log('Starting combined job: payments and refunds check'); - - // Run payment check - // await checkPendingPayments(); - - // Run refund check - // await checkRefundStatuses(); - console.log('Combined job completed successfully'); } catch (error) { console.error('Error in combined job:', error); diff --git a/apps/backend/src/jobs/payment-status-checker.ts b/apps/backend/src/jobs/payment-status-checker.ts deleted file mode 100644 index aa67fec..0000000 --- a/apps/backend/src/jobs/payment-status-checker.ts +++ /dev/null @@ -1,35 +0,0 @@ - -interface PendingPaymentRecord { - payment: any; - order: any; - slot: any; -} - -export const createPaymentNotification = (record: PendingPaymentRecord) => { - // Construct message from record data - const message = `Payment pending for order ORD${record.order.id}. Please complete before orders close time.`; - - // TODO: Implement notification sending logic using record.order.userId, record.order.id, message - console.log(`Sending notification to user ${record.order.userId} for order ${record.order.id}: ${message}`); -}; - -export const checkRefundStatuses = async () => { - try { - // TODO: Reimplement with helpers from @/src/dbService - // This function checks Razorpay refund status and updates database - // Requires: getPendingRefunds(), updateRefundStatus() - } catch (error) { - console.error('Error in checkRefundStatuses:', error); - } -}; - -export const checkPendingPayments = async () => { - try { - // TODO: Reimplement with helpers from @/src/dbService - // This function finds pending payments and sends notifications - // Requires: getPendingPaymentsWithOrders() - } catch (error) { - console.error('Error checking pending payments:', error); - } -}; - diff --git a/apps/backend/src/lib/env-exporter.ts b/apps/backend/src/lib/env-exporter.ts index bc8e852..0f58368 100755 --- a/apps/backend/src/lib/env-exporter.ts +++ b/apps/backend/src/lib/env-exporter.ts @@ -33,19 +33,12 @@ import type { KVNamespace } from '@cloudflare/workers-types' // // export const expoAccessToken = process.env.EXPO_ACCESS_TOKEN as string; // -// export const phonePeBaseUrl = process.env.PHONE_PE_BASE_URL as string; // -// export const phonePeClientId = process.env.PHONE_PE_CLIENT_ID as string; // -// export const phonePeClientVersion = Number(process.env.PHONE_PE_CLIENT_VERSION as string); // -// export const phonePeClientSecret = process.env.PHONE_PE_CLIENT_SECRET as string; // -// export const phonePeMerchantId = process.env.PHONE_PE_MERCHANT_ID as string; // -// export const razorpayId = process.env.RAZORPAY_KEY as string; // -// export const razorpaySecret = process.env.RAZORPAY_SECRET as string; // // export const otpSenderAuthToken = process.env.OTP_SENDER_AUTH_TOKEN as string; // @@ -90,9 +83,6 @@ export const getCloudflareZoneId = () => getRuntimeEnv().CLOUDFLARE_ZONE_ID as s export const getS3Url = () => getRuntimeEnv().S3_URL as string -export const getRazorpayId = () => getRuntimeEnv().RAZORPAY_KEY as string - -export const getRazorpaySecret = () => getRuntimeEnv().RAZORPAY_SECRET as string export const getOtpSenderAuthToken = () => getRuntimeEnv().OTP_SENDER_AUTH_TOKEN as string diff --git a/apps/backend/src/lib/gen-store.ts b/apps/backend/src/lib/gen-store.ts index bb874c4..a75bcfe 100644 --- a/apps/backend/src/lib/gen-store.ts +++ b/apps/backend/src/lib/gen-store.ts @@ -106,6 +106,7 @@ export async function readEssentialConstsFromKv(boundId: number): Promise ` • ${item.sku?.product?.name || 'Unknown'} x${item.quantity}`).join('\n') || ' N/A'} 💰 Total: ₹${orderData.totalAmount} -💳 Refund: ${orderData.refundStatus === 'na' ? 'N/A (COD)' : orderData.refundStatus || 'Pending'} ❓ Reason: ${cancellationData.reason} 👤 Cancelled by: ${cancellationData.cancelledBy === 'admin' ? 'Admin' : 'User'} @@ -145,10 +144,7 @@ export const handleOrderCancelled = async ( return } - const refundStatus = orderData.refunds?.[0]?.refundStatus || 'pending' - - - const telegramMessage = formatCancellationMessage({ ...orderData, refundStatus }, cancellationData) + const telegramMessage = formatCancellationMessage(orderData, cancellationData) await sendTelegramMessage(telegramMessage) } catch (error) { console.error('Failed to process cancellation message:', error) diff --git a/apps/backend/src/sqliteImporter.ts b/apps/backend/src/sqliteImporter.ts index fa49b79..57a8b09 100644 --- a/apps/backend/src/sqliteImporter.ts +++ b/apps/backend/src/sqliteImporter.ts @@ -36,7 +36,6 @@ export { getUsersForCoupon, createCouponWithRelations, updateCouponWithRelations, - generateCancellationCoupon, createReservedCoupon, createCouponForUser, checkUsersExist, @@ -167,13 +166,6 @@ export { // User - Slots getUserActiveSlotsList, getUserProductAvailability, - // User - Payments - getUserPaymentOrderById, - getUserPaymentByOrderId, - getUserPaymentByMerchantOrderId, - updateUserPaymentSuccess, - updateUserOrderPaymentStatus, - markUserPaymentFailed, // User - Auth getUserAuthByEmail, getUserAuthByMobile, diff --git a/apps/backend/src/trpc/apis/admin-apis/apis/admin-trpc-index.ts b/apps/backend/src/trpc/apis/admin-apis/apis/admin-trpc-index.ts index cecfe9a..97b9d70 100644 --- a/apps/backend/src/trpc/apis/admin-apis/apis/admin-trpc-index.ts +++ b/apps/backend/src/trpc/apis/admin-apis/apis/admin-trpc-index.ts @@ -8,7 +8,6 @@ import { slotsRouter } from '@/src/trpc/apis/admin-apis/apis/slots' import { productRouter } from '@/src/trpc/apis/admin-apis/apis/product' import { staffUserRouter } from '@/src/trpc/apis/admin-apis/apis/staff-user' import { storeRouter } from '@/src/trpc/apis/admin-apis/apis/store' -import { adminPaymentsRouter } from '@/src/trpc/apis/admin-apis/apis/payments' import { bannerRouter } from '@/src/trpc/apis/admin-apis/apis/banner' import { userRouter } from '@/src/trpc/apis/admin-apis/apis/user' import { regionRouter } from '@/src/trpc/apis/admin-apis/apis/region' @@ -22,7 +21,6 @@ export const adminRouter = router({ product: productRouter, staffUser: staffUserRouter, store: storeRouter, - payments: adminPaymentsRouter, banner: bannerRouter, user: userRouter, region: regionRouter, diff --git a/apps/backend/src/trpc/apis/admin-apis/apis/coupon.ts b/apps/backend/src/trpc/apis/admin-apis/apis/coupon.ts index 813d211..bbb1654 100644 --- a/apps/backend/src/trpc/apis/admin-apis/apis/coupon.ts +++ b/apps/backend/src/trpc/apis/admin-apis/apis/coupon.ts @@ -11,13 +11,11 @@ import { // Batch 2 - Transaction methods createCouponWithRelations, updateCouponWithRelations, - generateCancellationCoupon, createReservedCoupon, createCouponForUser, checkUsersExist, checkCouponExists, checkReservedCouponExists, - getOrderWithUser, } from '@/src/dbService' import type { Coupon, CouponFormInput, UserMiniInfo } from '@packages/shared' @@ -227,57 +225,6 @@ export const couponRouter = router({ return { message: "Coupon invalidated successfully" }; }), - generateCancellationCoupon: protectedProcedure - .input( - z.object({ - orderId: z.number(), - }) - ) - .mutation(async ({ input, ctx }): Promise => { - const { orderId } = input; - - // Get staff user ID from auth middleware - const staffUserId = ctx.staffUser?.id; - if (!staffUserId) { - throw new Error("Unauthorized"); - } - - // Using dbService helper (new implementation) - const order = await getOrderWithUser(ctx.staffUser!.regionId, orderId); - - if (!order) { - throw new Error("Order not found"); - } - - if (!order.user) { - throw new Error("User not found for this order"); - } - - // Generate coupon code: first 3 letters of user name or mobile + orderId - const userNamePrefix = (order.user.name || order.user.mobile || 'USR').substring(0, 3).toUpperCase(); - const couponCode = `${userNamePrefix}${orderId}`; - - // Check if coupon code already exists - const codeExists = await checkCouponExists(couponCode); - if (codeExists) { - throw new Error("Coupon code already exists"); - } - - // Get order total amount - const orderAmount = parseFloat(order.totalAmount); - - const coupon = await generateCancellationCoupon( - orderId, - staffUserId, - order.userId, - orderAmount, - couponCode, - order.regionId - ); - - return coupon; - }), - getReservedCoupons: protectedProcedure .input(z.object({ cursor: z.number().optional(), diff --git a/apps/backend/src/trpc/apis/admin-apis/apis/order.ts b/apps/backend/src/trpc/apis/admin-apis/apis/order.ts index 2903f99..94460f3 100644 --- a/apps/backend/src/trpc/apis/admin-apis/apis/order.ts +++ b/apps/backend/src/trpc/apis/admin-apis/apis/order.ts @@ -300,8 +300,6 @@ export const orderRouter = router({ }), }); -// {"id": "order_Rhh00qJNdjUp8o", "notes": {"retry": "true", "customerOrderId": "14"}, "amount": 21000, "entity": "order", "status": "created", "receipt": "order_14_retry", "attempts": 0, "currency": "INR", "offer_id": null, "signature": "6df20655021f1d6841340f2a2ef2ef9378cb3d43495ab09e85f08aea1a851583", "amount_due": 21000, "created_at": 1763575791, "payment_id": "pay_Rhh15cLL28YM7j", "amount_paid": 0} - export async function deleteOrderById(regionId: number, orderId: number): Promise { return await deleteOrderByIdInDb(regionId, orderId) } diff --git a/apps/backend/src/trpc/apis/admin-apis/apis/payments.ts b/apps/backend/src/trpc/apis/admin-apis/apis/payments.ts deleted file mode 100644 index 886fa40..0000000 --- a/apps/backend/src/trpc/apis/admin-apis/apis/payments.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { router, protectedProcedure } from "@/src/trpc/trpc-index" -import { z } from "zod"; - -const initiateRefundSchema = z - .object({ - orderId: z.number(), - refundPercent: z.number().min(0).max(100).optional(), - refundAmount: z.number().min(0).optional(), - }) - .refine( - (data) => { - const hasPercent = data.refundPercent !== undefined; - const hasAmount = data.refundAmount !== undefined; - return (hasPercent && !hasAmount) || (!hasPercent && hasAmount); - }, - { - message: - "Provide either refundPercent or refundAmount, not both or neither", - } - ); - -export const adminPaymentsRouter = router({ - initiateRefund: protectedProcedure - .input(initiateRefundSchema) - .mutation(async ({ input }) => { - return {} - }), -}); diff --git a/apps/backend/src/trpc/apis/user-apis/apis/order.ts b/apps/backend/src/trpc/apis/user-apis/apis/order.ts index 948200d..da59274 100644 --- a/apps/backend/src/trpc/apis/user-apis/apis/order.ts +++ b/apps/backend/src/trpc/apis/user-apis/apis/order.ts @@ -52,7 +52,6 @@ const placeOrderUtil = async (params: { slotId: number | null; }>; addressId: number; - paymentMethod: "online" | "cod"; couponIds?: number[]; userNotes?: string; isFlash?: boolean; @@ -61,7 +60,6 @@ const placeOrderUtil = async (params: { userId, selectedItems, addressId, - paymentMethod, couponIds, userNotes, } = params; @@ -296,9 +294,6 @@ const placeOrderUtil = async (params: { regionId: regionId, addressId, slotId: params.isFlash ? null : slotId, - isCod: paymentMethod === "cod", - isOnlinePayment: paymentMethod === "online", - paymentInfoId: null, totalAmount: finalOrderAmount.toString(), deliveryCharge: orderDelivery.toString(), discountAmount: orderDiscount.toString(), @@ -333,7 +328,6 @@ const placeOrderUtil = async (params: { const orderStatusData: Omit = { userId, orderId: 0, - paymentStatus: paymentMethod === "cod" ? "cod" : "pending", }; ordersData.push({ order, orderItems: orderItemsData, orderStatus: orderStatusData }); @@ -343,7 +337,6 @@ const placeOrderUtil = async (params: { const createdOrders = await placeUserOrderTransaction({ userId, ordersData, - paymentMethod, totalWithDelivery, }); @@ -386,7 +379,6 @@ export const orderRouter = router({ addressId: z.number().int().positive(), regionId: z.number().int().positive(), boundId: z.number().int().positive().optional(), - paymentMethod: z.enum(["online", "cod"]), couponIds: z.array(z.number().int().positive()).optional(), userNotes: z.string().optional(), isFlashDelivery: z.boolean().optional().default(false), @@ -405,7 +397,6 @@ export const orderRouter = router({ addressId, regionId, boundId, - paymentMethod, couponIds, userNotes, isFlashDelivery, @@ -439,7 +430,6 @@ export const orderRouter = router({ boundId, selectedItems: processedItems, addressId, - paymentMethod, couponIds, userNotes, isFlash: isFlashDelivery, @@ -466,7 +456,6 @@ export const orderRouter = router({ const mappedOrders = await Promise.all( userOrders.map(async (order) => { const status = order.orderStatus[0]; - const refund = order.refunds[0]; let deliveryStatus: DeliveryStatus; let orderStatus: OrderStatus; @@ -489,13 +478,6 @@ export const orderRouter = router({ orderStatus = "success"; } - const paymentMode = order.isCod ? "CoD" : "Online"; - const paymentStatus = status?.paymentStatus || "pending"; - const refundStatus = refund?.refundStatus || "none"; - const refundAmount = refund?.refundAmount - ? parseFloat(refund.refundAmount.toString()) - : null; - const items = await Promise.all( order.orderItems.map(async (item) => { const signedImages = item.sku?.images @@ -527,12 +509,8 @@ export const orderRouter = router({ deliveryDate: order.slot?.deliveryTime.toISOString(), orderStatus, cancelReason: status?.cancelReason || null, - paymentMode, totalAmount: Number(order.totalAmount), deliveryCharge: Number(order.deliveryCharge), - paymentStatus, - refundStatus, - refundAmount, userNotes: order.userNotes || null, items, isFlashDelivery: order.isFlashDelivery, @@ -583,7 +561,6 @@ export const orderRouter = router({ } const status = order.orderStatus[0]; - const refund = order.refunds[0]; let deliveryStatus: DeliveryStatus; let orderStatusResult: OrderStatus; @@ -606,13 +583,6 @@ export const orderRouter = router({ orderStatusResult = "success"; } - const paymentMode = order.isCod ? "CoD" : "Online"; - const paymentStatus = status?.paymentStatus || "pending"; - const refundStatus = refund?.refundStatus || "none"; - const refundAmount = refund?.refundAmount - ? parseFloat(refund.refundAmount.toString()) - : null; - const items = await Promise.all( order.orderItems.map(async (item) => { const signedImages = item.sku?.images @@ -645,10 +615,6 @@ export const orderRouter = router({ orderStatus: orderStatusResult, cancellationStatus: orderStatusResult, cancelReason: status?.cancelReason || null, - paymentMode, - paymentStatus, - refundStatus, - refundAmount, userNotes: order.userNotes || null, items, couponCode: couponData?.couponCode || null, @@ -709,7 +675,7 @@ export const orderRouter = router({ throw new ApiError("Cannot cancel delivered order", 400); } - await cancelUserOrderTransaction(id, status.id, reason, order.isCod); + await cancelUserOrderTransaction(id, status.id, reason); await clearFirstOrderIfMatches(userId, id); diff --git a/apps/backend/src/trpc/apis/user-apis/apis/payments.ts b/apps/backend/src/trpc/apis/user-apis/apis/payments.ts deleted file mode 100644 index c88eea6..0000000 --- a/apps/backend/src/trpc/apis/user-apis/apis/payments.ts +++ /dev/null @@ -1,153 +0,0 @@ - -import { router, protectedProcedure } from '@/src/trpc/trpc-index' -import { z } from 'zod' -import { ApiError } from '@/src/lib/api-error' -import { getRazorpayId, getRazorpaySecret } from "@/src/lib/env-exporter" -import { RazorpayPaymentService } from "@/src/lib/payments-utils" -import { - getUserPaymentOrderById as getUserPaymentOrderByIdInDb, - getUserPaymentByOrderId as getUserPaymentByOrderIdInDb, - getUserPaymentByMerchantOrderId as getUserPaymentByMerchantOrderIdInDb, - updateUserPaymentSuccess as updateUserPaymentSuccessInDb, - updateUserOrderPaymentStatus as updateUserOrderPaymentStatusInDb, - markUserPaymentFailed as markUserPaymentFailedInDb, -} from '@/src/dbService' -import type { - UserPaymentOrderResponse, - UserPaymentVerifyResponse, - UserPaymentFailResponse, -} from '@packages/shared' - -export const paymentRouter = router({ - createRazorpayOrder: protectedProcedure //either create a new payment order or return the existing one - .input(z.object({ - orderId: z.string(), - })) - .mutation(async ({ input, ctx }): Promise => { - const userId = ctx.user.userId; - const { orderId } = input; - - const order = await getUserPaymentOrderByIdInDb(parseInt(orderId)) - - if (!order) { - throw new ApiError("Order not found", 404) - } - - if (order.userId !== userId) { - throw new ApiError("Order does not belong to user", 403) - } - - // Check for existing pending payment - const existingPayment = await getUserPaymentByOrderIdInDb(parseInt(orderId)) - - if (existingPayment && existingPayment.status === 'pending') { - return { - razorpayOrderId: existingPayment.merchantOrderId, - key: getRazorpayId(), - }; - } - - // Create Razorpay order and insert payment record - if (order.totalAmount === null) { - throw new ApiError('Order total is missing', 400) - } - const razorpayOrder = await RazorpayPaymentService.createOrder(parseInt(orderId), order.totalAmount); - await RazorpayPaymentService.insertPaymentRecord(parseInt(orderId), razorpayOrder); - - return { - razorpayOrderId: 0, - key: getRazorpayId(), - } - }), - - verifyPayment: protectedProcedure - .input(z.object({ - razorpay_payment_id: z.string(), - razorpay_order_id: z.string(), - razorpay_signature: z.string(), - })) - .mutation(async ({ input, ctx }): Promise => { - const { razorpay_payment_id, razorpay_order_id, razorpay_signature } = input; - - // Verify signature - const encoder = new TextEncoder() - const key = await crypto.subtle.importKey( - 'raw', - encoder.encode(getRazorpaySecret()), - { name: 'HMAC', hash: 'SHA-256' }, - false, - ['sign'] - ) - const signature = await crypto.subtle.sign( - 'HMAC', - key, - encoder.encode(`${razorpay_order_id}|${razorpay_payment_id}`) - ) - const expectedSignature = Array.from(new Uint8Array(signature)) - .map((byte) => byte.toString(16).padStart(2, '0')) - .join('') - - if (expectedSignature !== razorpay_signature) { - throw new ApiError("Invalid payment signature", 400); - } - - // Get current payment record - const currentPayment = await getUserPaymentByMerchantOrderIdInDb(razorpay_order_id) - - if (!currentPayment) { - throw new ApiError("Payment record not found", 404); - } - - // Update payment status and payload - const updatedPayload = { - ...((currentPayment.payload as any) || {}), - payment_id: razorpay_payment_id, - signature: razorpay_signature, - }; - - const updatedPayment = await updateUserPaymentSuccessInDb(razorpay_order_id, updatedPayload) - - if (!updatedPayment) { - throw new ApiError("Payment record not found", 404) - } - - await updateUserOrderPaymentStatusInDb(updatedPayment.orderId, 'success') - - return { - success: true, - message: "Payment verified successfully", - } - }), - - markPaymentFailed: protectedProcedure - .input(z.object({ - merchantOrderId: z.string(), - })) - .mutation(async ({ input, ctx }): Promise => { - const userId = ctx.user.userId; - const { merchantOrderId } = input; - - // Find payment by merchantOrderId - const payment = await getUserPaymentByMerchantOrderIdInDb(merchantOrderId) - - if (!payment) { - throw new ApiError("Payment not found", 404); - } - - // Check if payment belongs to user's order - const order = await getUserPaymentOrderByIdInDb(payment.orderId) - - if (!order || order.userId !== userId) { - throw new ApiError("Payment does not belong to user", 403); - } - - // Update payment status to failed - await markUserPaymentFailedInDb(payment.id) - - return { - success: true, - message: "Payment marked as failed", - } - }), - -}); diff --git a/apps/backend/src/trpc/apis/user-apis/apis/user-trpc-index.ts b/apps/backend/src/trpc/apis/user-apis/apis/user-trpc-index.ts index bb1d70a..426eae2 100644 --- a/apps/backend/src/trpc/apis/user-apis/apis/user-trpc-index.ts +++ b/apps/backend/src/trpc/apis/user-apis/apis/user-trpc-index.ts @@ -8,7 +8,6 @@ import { productRouter } from '@/src/trpc/apis/user-apis/apis/product'; import { slotsRouter } from '@/src/trpc/apis/user-apis/apis/slots'; import { userRouter as userDataRouter } from '@/src/trpc/apis/user-apis/apis/user'; import { userCouponRouter } from '@/src/trpc/apis/user-apis/apis/coupon'; -import { paymentRouter } from '@/src/trpc/apis/user-apis/apis/payments'; import { fileUploadRouter } from '@/src/trpc/apis/user-apis/apis/file-upload'; export const userRouter = router({ @@ -21,7 +20,6 @@ export const userRouter = router({ slots: slotsRouter, user: userDataRouter, coupon: userCouponRouter, - payment: paymentRouter, fileUpload: fileUploadRouter, }); diff --git a/apps/backend/tests/BUGS.md b/apps/backend/tests/BUGS.md index 6b48620..44e0f11 100644 --- a/apps/backend/tests/BUGS.md +++ b/apps/backend/tests/BUGS.md @@ -541,6 +541,5 @@ deprecated/out of scope. ## Out of scope (per request) -Online payments (`user.payment.*`, `admin.payments.initiateRefund`), OTP -(`sendOtp`/`verifyOtp`) and `deleteAccount` are deliberately untested and not -listed here. +OTP (`sendOtp`/`verifyOtp`) and `deleteAccount` are deliberately untested and not +listed here. Online payments were removed from the product (COD-only). diff --git a/apps/backend/tests/api/admin-ops.test.ts b/apps/backend/tests/api/admin-ops.test.ts index 7152fe9..6528167 100644 --- a/apps/backend/tests/api/admin-ops.test.ts +++ b/apps/backend/tests/api/admin-ops.test.ts @@ -121,13 +121,11 @@ describe('admin ops', () => { selectedItems: [{ skuId, quantity: 1, slotId: slotA.slotId }], addressId: address.addressId, regionId: 1, - paymentMethod: 'cod', }), user.user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity: 1, slotId: slotB.slotId }], addressId: address.addressId, regionId: 1, - paymentMethod: 'cod', }), ]) diff --git a/apps/backend/tests/api/admin-orders.test.ts b/apps/backend/tests/api/admin-orders.test.ts index e4c3c79..913c488 100644 --- a/apps/backend/tests/api/admin-orders.test.ts +++ b/apps/backend/tests/api/admin-orders.test.ts @@ -35,7 +35,6 @@ describe('admin order operations', () => { const placed = await user.user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity: 1, slotId }], addressId, - paymentMethod: 'cod', }) orderId = placed.data[0].id }) @@ -117,7 +116,6 @@ describe('admin order operations', () => { const placed = await user.user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity: 1, slotId }], addressId, - paymentMethod: 'cod', }) const freshOrderId = placed.data[0].id diff --git a/apps/backend/tests/api/authorization-matrix.test.ts b/apps/backend/tests/api/authorization-matrix.test.ts index c7a6d8f..2ae4090 100644 --- a/apps/backend/tests/api/authorization-matrix.test.ts +++ b/apps/backend/tests/api/authorization-matrix.test.ts @@ -45,7 +45,6 @@ describe('authorization matrix', () => { const placed = await apiClient(userToken).user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity: 1, slotId }], addressId, - paymentMethod: 'cod', }) orderId = placed.data[0].id }) @@ -207,7 +206,6 @@ describe('authorization matrix', () => { apiClient(staff.token).user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity: 1, slotId }], addressId, - paymentMethod: 'cod', }) ) expect(error).toBeInstanceOf(Error) @@ -245,7 +243,6 @@ describe('authorization matrix', () => { const placed = await apiClient(fresh.token).user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity: 1, slotId }], addressId: fresh.addressId, - paymentMethod: 'cod', }) const error = await captureError(() => diff --git a/apps/backend/tests/api/coupon-math.test.ts b/apps/backend/tests/api/coupon-math.test.ts index b3d1e66..5265ad7 100644 --- a/apps/backend/tests/api/coupon-math.test.ts +++ b/apps/backend/tests/api/coupon-math.test.ts @@ -95,7 +95,6 @@ describe('coupon discount maths', () => { selectedItems: items, addressId, regionId: 1, - paymentMethod: 'cod', ...(couponId != null ? { couponIds: Array.isArray(couponId) ? couponId : [couponId] } : {}), diff --git a/apps/backend/tests/api/coupon-ux.test.ts b/apps/backend/tests/api/coupon-ux.test.ts index 91ce8d1..494fd8a 100644 --- a/apps/backend/tests/api/coupon-ux.test.ts +++ b/apps/backend/tests/api/coupon-ux.test.ts @@ -72,7 +72,6 @@ describe('coupon UX', () => { selectedItems: [{ skuId, quantity, slotId }], addressId: user.addressId, regionId: 1, - paymentMethod: 'cod', ...(couponId ? { couponIds: [couponId] } : {}), }) diff --git a/apps/backend/tests/api/coupons.test.ts b/apps/backend/tests/api/coupons.test.ts index 5e36c8f..f4cebd0 100644 --- a/apps/backend/tests/api/coupons.test.ts +++ b/apps/backend/tests/api/coupons.test.ts @@ -81,7 +81,6 @@ describe('coupon CRUD + apply', () => { selectedItems: [{ skuId, quantity: 1, slotId }], addressId, regionId: 1, - paymentMethod: 'cod', couponIds: [couponId], }) @@ -105,7 +104,6 @@ describe('coupon CRUD + apply', () => { selectedItems: [{ skuId, quantity: 1, slotId }], addressId, regionId: 1, - paymentMethod: 'cod', couponIds: [couponId], }) ) diff --git a/apps/backend/tests/api/misc-procedures.test.ts b/apps/backend/tests/api/misc-procedures.test.ts index 714c2de..d6f591c 100644 --- a/apps/backend/tests/api/misc-procedures.test.ts +++ b/apps/backend/tests/api/misc-procedures.test.ts @@ -69,7 +69,6 @@ describe('misc procedures', () => { selectedItems: [{ skuId: store.skuId, quantity: 1, slotId: slot.slotId }], addressId: orderAddressId, regionId: 1, - paymentMethod: 'cod', }) const error = await captureError(() => diff --git a/apps/backend/tests/api/order-edge-cases.test.ts b/apps/backend/tests/api/order-edge-cases.test.ts index b5ac5fc..724ddc6 100644 --- a/apps/backend/tests/api/order-edge-cases.test.ts +++ b/apps/backend/tests/api/order-edge-cases.test.ts @@ -44,7 +44,6 @@ describe('placeOrder guards', () => { apiClient().user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity: 1, slotId }], addressId, - paymentMethod: 'cod', }) ) @@ -56,7 +55,6 @@ describe('placeOrder guards', () => { apiClient(userToken).user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity: 1, slotId }], addressId: 99_999_999, - paymentMethod: 'cod', }) ) @@ -68,7 +66,6 @@ describe('placeOrder guards', () => { apiClient(userToken).user.order.placeOrder.mutate({ selectedItems: [{ skuId: 99_999_999, quantity: 1, slotId }], addressId, - paymentMethod: 'cod', }) ) @@ -84,7 +81,6 @@ describe('placeOrder guards', () => { const res = await apiClient(userToken).user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity: 1, slotId: bogusSlotId }], addressId, - paymentMethod: 'cod', }) expect(res.success).toBe(true) diff --git a/apps/backend/tests/api/order-flow.test.ts b/apps/backend/tests/api/order-flow.test.ts index 8f134bd..efc6c96 100644 --- a/apps/backend/tests/api/order-flow.test.ts +++ b/apps/backend/tests/api/order-flow.test.ts @@ -38,7 +38,6 @@ describe('order flow: create an order, then read it back', () => { const res = await apiClient(userToken).user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity: 1, slotId }], addressId, - paymentMethod: 'cod', }) expect(res.success).toBe(true) @@ -78,19 +77,4 @@ describe('order flow: create an order, then read it back', () => { expect(detail.items[0].amount).toBeGreaterThan(0) }) - it('places an online order with a pending payment', async () => { - const res = await apiClient(userToken).user.order.placeOrder.mutate({ - selectedItems: [{ skuId, quantity: 1, slotId }], - addressId, - paymentMethod: 'online', - }) - - const orderId = res.data[0].id - const detail = await apiClient(userToken).user.order.getOrderById.query({ - orderId: String(orderId), - }) - - expect(detail.paymentMode).toBe('Online') - expect(detail.paymentStatus).toBe('pending') - }) }) diff --git a/apps/backend/tests/api/order-lifecycle-gaps.test.ts b/apps/backend/tests/api/order-lifecycle-gaps.test.ts index 22d3d77..d3a4d93 100644 --- a/apps/backend/tests/api/order-lifecycle-gaps.test.ts +++ b/apps/backend/tests/api/order-lifecycle-gaps.test.ts @@ -1,7 +1,6 @@ /** * Order lifecycle gaps: coupon-usage rollback, first-order-only poisoning, - * refund rows, cancel error swallowing and the (missing) status transition - * guards. + * cancel error swallowing and the (missing) status transition guards. * * Known bugs are pinned — see tests/BUGS.md. */ @@ -43,7 +42,6 @@ describe('order lifecycle gaps', () => { selectedItems: [{ skuId, quantity: 1, slotId }], addressId, regionId: 1, - paymentMethod: 'cod', ...(couponId ? { couponIds: [couponId] } : {}), }) @@ -82,7 +80,6 @@ describe('order lifecycle gaps', () => { selectedItems: [{ skuId, quantity: 1, slotId }], addressId: buyer.addressId, regionId: 1, - paymentMethod: 'cod', }) await apiClient(buyer.token).user.order.cancelOrder.mutate({ id: first.data[0].id, @@ -95,7 +92,6 @@ describe('order lifecycle gaps', () => { selectedItems: [{ skuId, quantity: 1, slotId }], addressId: buyer.addressId, regionId: 1, - paymentMethod: 'cod', couponIds: [coupon.id], }) expect(res.success).toBe(true) @@ -113,7 +109,6 @@ describe('order lifecycle gaps', () => { ], addressId: buyer.addressId, regionId: 1, - paymentMethod: 'cod', couponIds: [coupon.id], }) expect(placed.data).toHaveLength(2) @@ -123,7 +118,6 @@ describe('order lifecycle gaps', () => { selectedItems: [{ skuId, quantity: 1, slotId }], addressId: buyer.addressId, regionId: 1, - paymentMethod: 'cod', couponIds: [coupon.id], }) @@ -151,26 +145,12 @@ describe('order lifecycle gaps', () => { const res = await apiClient(buyer.token).user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity: 1, slotId }], addressId: buyer.addressId, - paymentMethod: 'cod', couponIds: [coupon.id], }) expect(res.success).toBe(true) }) - it('writes a refund row for a cancelled COD order', async () => { - const placed = await place() - const orderId = placed.data[0].id - - await cancel(orderId) - - const detail = await apiClient(userToken).user.order.getOrderById.query({ - orderId: String(orderId), - }) - // COD cancellations record refundStatus 'na'. - expect(detail.refundStatus).toBe('na') - }) - it('pins: cancelling an already-cancelled order reports a generic message', async () => { const placed = await place() const orderId = placed.data[0].id diff --git a/apps/backend/tests/api/order-lifecycle.test.ts b/apps/backend/tests/api/order-lifecycle.test.ts index b7262b6..3a43db9 100644 --- a/apps/backend/tests/api/order-lifecycle.test.ts +++ b/apps/backend/tests/api/order-lifecycle.test.ts @@ -27,7 +27,6 @@ describe('order lifecycle', () => { const res = await apiClient(token).user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity: 1, slotId }], addressId, - paymentMethod: 'cod', }) orderId = res.data[0].id }) diff --git a/apps/backend/tests/api/order-rules.test.ts b/apps/backend/tests/api/order-rules.test.ts index b0ac300..1e5e883 100644 --- a/apps/backend/tests/api/order-rules.test.ts +++ b/apps/backend/tests/api/order-rules.test.ts @@ -49,7 +49,6 @@ describe('order rules', () => { selectedItems: [{ skuId, quantity: 1, slotId }], addressId, regionId: 1, - paymentMethod: 'cod', }) expect(res.data[0].deliveryCharge).toBe(String(charge)) @@ -62,7 +61,6 @@ describe('order rules', () => { selectedItems: [{ skuId, quantity, slotId }], addressId, regionId: 1, - paymentMethod: 'cod', }) expect(res.data[0].deliveryCharge).toBe('0') @@ -76,7 +74,6 @@ describe('order rules', () => { ], addressId, regionId: 1, - paymentMethod: 'cod', }) expect(res.data).toHaveLength(2) @@ -101,7 +98,6 @@ describe('order rules', () => { selectedItems: [{ skuId, quantity: 1, slotId }], addressId, regionId: 1, - paymentMethod: 'cod', }) ) expect(error.message).toMatch(/capacity/i) @@ -124,7 +120,6 @@ describe('order rules', () => { selectedItems: [{ skuId, quantity: 1, slotId: null }], addressId, regionId: 1, - paymentMethod: 'cod', isFlashDelivery: true, }) ) @@ -140,7 +135,6 @@ describe('order rules', () => { selectedItems: [{ skuId, quantity: 0, slotId }], addressId, regionId: 1, - paymentMethod: 'cod', }) ) diff --git a/apps/backend/tests/api/place-order-edge-cases.test.ts b/apps/backend/tests/api/place-order-edge-cases.test.ts index a65238e..430dcc0 100644 --- a/apps/backend/tests/api/place-order-edge-cases.test.ts +++ b/apps/backend/tests/api/place-order-edge-cases.test.ts @@ -60,7 +60,6 @@ describe('placeOrder edge cases', () => { selectedItems: [{ skuId, quantity: 1, slotId }], addressId, regionId: 1, - paymentMethod: 'cod', ...over, }) diff --git a/apps/backend/wrangler.dev.toml b/apps/backend/wrangler.dev.toml index e9276ce..6206d2d 100644 --- a/apps/backend/wrangler.dev.toml +++ b/apps/backend/wrangler.dev.toml @@ -70,11 +70,6 @@ NOTIF_QUEUE_NAME = "notif-queue-dev" ORDER_PLACED_QUEUE_NAME = "order-placed-queue-dev" ORDER_CANCELLED_QUEUE_NAME = "order-cancelled-queue-dev" DATABASE_URL = "postgresql://postgres:meatfarmer_master_password@57.128.212.174:7447/meatfarmer" -PHONE_PE_BASE_URL = "https://api-preprod.phonepe.com/" -PHONE_PE_CLIENT_ID = "TEST-M23F2IGP34ZAR_25090" -PHONE_PE_CLIENT_VERSION = "1" -PHONE_PE_CLIENT_SECRET = "MTU1MmIzOTgtM2Q0Mi00N2M5LTkyMWUtNzBiMjdmYzVmZWUy" -PHONE_PE_MERCHANT_ID = "M23F2IGP34ZAR" S3_REGION = "apac" S3_ACCESS_KEY_ID = "8fab47503efb9547b50e4fb317e35cc7" S3_SECRET_ACCESS_KEY = "47c2eb5636843cf568dda7ad0959a3e42071303f26dbdff94bd45a3c33dcd950" @@ -88,8 +83,6 @@ CLOUDFLARE_API_TOKEN = "N7jAg5X-RUj_fVfMW6zbfJ8qIYc81TSIKKlbZ6oh" CLOUDFLARE_ZONE_ID = "edefbf750bfc3ff26ccd11e8e28dc8d7" REDIS_URL = "redis://default:redis_shafi_password@57.128.212.174:6379" APP_URL = "https://ui.freshyo.in" -RAZORPAY_KEY = "rzp_test_RdCBBUJ56NLaJK" -RAZORPAY_SECRET = "namEwKBE1ypWxH0QDVg6fWOe" OTP_SENDER_AUTH_TOKEN = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJDLTM5OENEMkJDRTM0MjQ4OCIsImlhdCI6MTc0Nzg0MTEwMywiZXhwIjoxOTA1NTIxMTAzfQ.IV64ofVKjcwveIanxu_P2XlACtPeA9sJQ74uM53osDeyUXsFv0rwkCl6NNBIX93s_wnh4MKITLbcF_ClwmFQ0A" MIN_ORDER_VALUE = "300" DELIVERY_CHARGE = "20" diff --git a/apps/backend/wrangler.prod.toml b/apps/backend/wrangler.prod.toml index 66576ca..dec3c51 100644 --- a/apps/backend/wrangler.prod.toml +++ b/apps/backend/wrangler.prod.toml @@ -65,11 +65,6 @@ NOTIF_QUEUE_NAME = "notif-queue" ORDER_PLACED_QUEUE_NAME = "order-placed-queue" ORDER_CANCELLED_QUEUE_NAME = "order-cancelled-queue" DATABASE_URL = "postgresql://postgres:meatfarmer_master_password@57.128.212.174:7447/meatfarmer" -PHONE_PE_BASE_URL = "https://api-preprod.phonepe.com/" -PHONE_PE_CLIENT_ID = "TEST-M23F2IGP34ZAR_25090" -PHONE_PE_CLIENT_VERSION = "1" -PHONE_PE_CLIENT_SECRET = "MTU1MmIzOTgtM2Q0Mi00N2M5LTkyMWUtNzBiMjdmYzVmZWUy" -PHONE_PE_MERCHANT_ID = "M23F2IGP34ZAR" S3_REGION = "apac" S3_ACCESS_KEY_ID = "8fab47503efb9547b50e4fb317e35cc7" S3_SECRET_ACCESS_KEY = "47c2eb5636843cf568dda7ad0959a3e42071303f26dbdff94bd45a3c33dcd950" @@ -83,8 +78,6 @@ CLOUDFLARE_API_TOKEN = "N7jAg5X-RUj_fVfMW6zbfJ8qIYc81TSIKKlbZ6oh" CLOUDFLARE_ZONE_ID = "edefbf750bfc3ff26ccd11e8e28dc8d7" REDIS_URL = "redis://default:redis_shafi_password@57.128.212.174:6379" APP_URL = "https://ui.freshyo.in" -RAZORPAY_KEY = "rzp_test_RdCBBUJ56NLaJK" -RAZORPAY_SECRET = "namEwKBE1ypWxH0QDVg6fWOe" OTP_SENDER_AUTH_TOKEN = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJDLTM5OENEMkJDRTM0MjQ4OCIsImlhdCI6MTc0Nzg0MTEwMywiZXhwIjoxOTA1NTIxMTAzfQ.IV64ofVKjcwveIanxu_P2XlACtPeA9sJQ74uM53osDeyUXsFv0rwkCl6NNBIX93s_wnh4MKITLbcF_ClwmFQ0A" MIN_ORDER_VALUE = "300" DELIVERY_CHARGE = "20" diff --git a/apps/user-ui/app/(drawer)/(tabs)/me/my-orders/[id].tsx b/apps/user-ui/app/(drawer)/(tabs)/me/my-orders/[id].tsx index 1bcdd51..33774a7 100644 --- a/apps/user-ui/app/(drawer)/(tabs)/me/my-orders/[id].tsx +++ b/apps/user-ui/app/(drawer)/(tabs)/me/my-orders/[id].tsx @@ -191,24 +191,6 @@ export default function OrderDetails() { {/* 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() || "") && ( {order.isFlashDelivery ? ( @@ -301,12 +283,6 @@ export default function OrderDetails() { Cancellation Reason {order.cancelReason} - {order.refundAmount && ( - - Refund Amount - ₹{order.refundAmount} - - )} )} diff --git a/apps/user-ui/app/(drawer)/(tabs)/me/my-orders/index.tsx b/apps/user-ui/app/(drawer)/(tabs)/me/my-orders/index.tsx index 82988c9..1e70b0d 100755 --- a/apps/user-ui/app/(drawer)/(tabs)/me/my-orders/index.tsx +++ b/apps/user-ui/app/(drawer)/(tabs)/me/my-orders/index.tsx @@ -3,7 +3,7 @@ import { View, FlatList, Alert, ActivityIndicator } from 'react-native'; import { Image } from 'expo-image'; import { MaterialIcons, Ionicons } from '@expo/vector-icons'; import { useRouter } from 'expo-router'; -import { tw, useManualRefresh, MyText, MyFlatList, useMarkDataFetchers, REFUND_STATUS, MyTouchableOpacity, theme } from 'common-ui'; +import { tw, useManualRefresh, MyText, MyFlatList, useMarkDataFetchers, MyTouchableOpacity, theme } from 'common-ui'; import { trpc } from '@/src/trpc-client'; import { orderStatusManipulator } from '@/src/lib/string-manipulators'; @@ -66,11 +66,8 @@ interface OrderItemProps { item: Order; index: number; getStatusColor: (status: string) => any; - getRefundStatusColor: (status: string) => any; onPress: (orderId: number) => void; - onRetryPayment: (orderId: number) => void; onViewMoreItems: (orderId: number) => void; - isPaymentPending: boolean; refetch: () => void; } @@ -78,11 +75,8 @@ const OrderItem: React.FC = ({ item, index, getStatusColor, - getRefundStatusColor, onPress, - onRetryPayment, onViewMoreItems, - isPaymentPending, refetch }) => { const mainStatus = getStatusColor(item.orderStatus); @@ -275,22 +269,6 @@ const OrderItem: React.FC = ({ Cancellation Details {item.cancelReason} - - {item.refundStatus && item.refundStatus !== REFUND_STATUS.NOT_APPLICABLE && ( - - Refund Status - - - - {item.refundStatus} - - - - )} )} @@ -313,30 +291,10 @@ const OrderItem: React.FC = ({ )} - {(item.paymentMode === 'Online' && (item.paymentStatus === 'pending' || item.paymentStatus === 'failed')) ? ( - { - e.stopPropagation(); - onRetryPayment(item.id); - }} - disabled={isPaymentPending} - style={tw`bg-rose-600 px-6 py-3 rounded-2xl shadow-lg shadow-rose-200 flex-row items-center`} - > - {isPaymentPending ? ( - - ) : ( - <> - - Retry Payment - - )} - - ) : ( - - View Details - - - )} + + View Details + + @@ -365,31 +323,6 @@ export default function MyOrders() { - const createRazorpayOrderMutation = trpc.user.payment.createRazorpayOrder.useMutation({ - onSuccess: (paymentData) => { - const order = allOrders.find(o => o.id === retryOrderId); - if (order) { - const totalAmount = order.items.reduce((sum, p) => sum + p.amount, 0); - // initiateRazorpayPayment(paymentData.razorpayOrderId, paymentData.key, totalAmount); - } - }, - onError: (error: any) => { - Alert.alert('Error', error.message || 'Failed to create payment order'); - }, - }); - - const verifyPaymentMutation = trpc.user.payment.verifyPayment.useMutation({ - onSuccess: () => { - refetch(); - // Refresh the NextOrderGlimpse observer too. - utils.user.order.getOrders.invalidate(); - Alert.alert('Success', 'Payment completed successfully'); - }, - onError: (error: any) => { - Alert.alert('Error', error.message || 'Payment verification failed'); - refetch(); - }, - }); // Handle data accumulation for infinite scroll useEffect(() => { if (ordersData?.data) { @@ -439,7 +372,6 @@ export default function MyOrders() { const [dialogOpen, setDialogOpen] = useState(false); const [dialogItems, setDialogItems] = useState([]); - const [retryOrderId, setRetryOrderId] = useState(0); const openDialog = useCallback((items: OrderItem[]) => { setDialogItems(items); @@ -481,7 +413,6 @@ export default function MyOrders() { label: 'Cancelled' }; case 'pending': - case 'payment_pending': return { bg: 'bg-amber-50', text: 'text-amber-700', @@ -522,30 +453,6 @@ export default function MyOrders() { } }; - const getRefundStatusColor = (status: string) => { - switch (status) { - case REFUND_STATUS.SUCCESS: - return { bg: 'bg-emerald-50', text: 'text-emerald-700', icon: 'check-circle', color: '#059669', border: 'border-emerald-100' }; - case REFUND_STATUS.PROCESSING: - return { bg: 'bg-brand50', text: 'text-brand700', icon: 'refresh', color: '#1570EF', border: 'border-brand100' }; - case REFUND_STATUS.PENDING: - return { bg: 'bg-amber-50', text: 'text-amber-700', icon: 'schedule', color: '#D97706', border: 'border-amber-100' }; - case REFUND_STATUS.NOT_APPLICABLE: - return { bg: 'bg-slate-50', text: 'text-slate-700', icon: 'info', color: '#64748B', border: 'border-slate-100' }; - default: - return { bg: 'bg-slate-50', text: 'text-slate-700', icon: 'info', color: '#64748B', border: 'border-slate-100' }; - } - }; - - - - - - const handleRetryPayment = (orderId: number) => { - setRetryOrderId(orderId); - createRazorpayOrderMutation.mutate({ orderId: orderId.toString() }); - }; - if (isLoading && currentPage === 1) { return ( @@ -584,11 +491,8 @@ export default function MyOrders() { item={item} index={index} getStatusColor={getStatusColor} - getRefundStatusColor={getRefundStatusColor} onPress={(orderId) => router.push(`/(drawer)/(tabs)/me/my-orders/${orderId}`)} - onRetryPayment={handleRetryPayment} onViewMoreItems={(orderId) => router.push(`/(drawer)/(tabs)/me/my-orders/${orderId}`)} - isPaymentPending={createRazorpayOrderMutation.isPending} refetch={refetch} /> )} diff --git a/apps/user-ui/components/PaymentAndOrderComponent.tsx b/apps/user-ui/components/PaymentAndOrderComponent.tsx index 75782b8..e0100ad 100644 --- a/apps/user-ui/components/PaymentAndOrderComponent.tsx +++ b/apps/user-ui/components/PaymentAndOrderComponent.tsx @@ -53,7 +53,6 @@ const PaymentAndOrderComponent: React.FC = ({ // Synchronous re-entrancy guard so a double-tap can't fire placeOrder twice // (state-based isPending updates only after a re-render). const submittingRef = useRef(false); - const [paymentMethod, setPaymentMethod] = useState<'online' | 'cod'>('cod'); const userNotes = useCheckoutStore((state) => state.userNotes); // Helper function to clear cart and invalidate queries @@ -86,22 +85,18 @@ const PaymentAndOrderComponent: React.FC = ({ // keep showing the pre-order list. utils.user.order.getOrders.invalidate(); - if (!firstOrder.isCod) { - // createRazorpayOrderMutation.mutate({ orderId: firstOrder.id.toString() }); - } else { - // Clear cart and navigate to success page. Prefer the amount the server - // actually stored across the (possibly split) orders over the local preview. - clearCartAndInvalidateQueries(isFlashDelivery ? 'flash' : 'regular'); - const successPath = isFlashDelivery - ? '/(drawer)/(tabs)/flash-delivery/order-success' - : './order-success'; - const serverTotal = orders.reduce( - (sum, order) => sum + Number(order.totalAmount ?? 0), - 0 - ); - const successAmount = serverTotal > 0 ? serverTotal : finalTotalWithDelivery; - router.replace(`${successPath}?orderId=${firstOrder.id}&totalAmount=${successAmount}`); - } + // Clear cart and navigate to success page. Prefer the amount the server + // actually stored across the (possibly split) orders over the local preview. + clearCartAndInvalidateQueries(isFlashDelivery ? 'flash' : 'regular'); + const successPath = isFlashDelivery + ? '/(drawer)/(tabs)/flash-delivery/order-success' + : './order-success'; + const serverTotal = orders.reduce( + (sum, order) => sum + Number(order.totalAmount ?? 0), + 0 + ); + const successAmount = serverTotal > 0 ? serverTotal : finalTotalWithDelivery; + router.replace(`${successPath}?orderId=${firstOrder.id}&totalAmount=${successAmount}`); }, onError: (error: any) => { // The backend rejects a checkout whose address/SKUs belong to another @@ -118,31 +113,6 @@ const PaymentAndOrderComponent: React.FC = ({ }, }); - const verifyPaymentMutation = trpc.user.payment.verifyPayment.useMutation({ - onSuccess: () => { - const orders = placeOrderMutation.data?.data || []; - const firstOrder = orders[0]; - utils.user.order.getOrders.invalidate(); - // Clear cart and navigate to success page, using the server-stored amount. - clearCartAndInvalidateQueries(isFlashDelivery ? 'flash' : 'regular'); - const successPath = isFlashDelivery - ? '/(drawer)/(tabs)/flash-delivery/order-success' - : './order-success'; - const serverTotal = orders.reduce( - (sum, order) => sum + Number(order.totalAmount ?? 0), - 0 - ); - const successAmount = serverTotal > 0 ? serverTotal : finalTotalWithDelivery; - router.replace(`${successPath}?orderId=${firstOrder?.id}&totalAmount=${successAmount}`); - }, - onError: (error: any) => { - Alert.alert('Error', error.message || 'Payment verification failed'); - }, - }); - - const markPaymentFailedMutation = trpc.user.payment.markPaymentFailed.useMutation(); - - const handlePlaceOrder = () => { // Ignore re-entrant presses while a submit is already in flight. if (submittingRef.current || placeOrderMutation.isPending) return; @@ -189,7 +159,6 @@ const PaymentAndOrderComponent: React.FC = ({ addressId: selectedAddress, regionId: selectedRegionId, boundId: constsData?.boundId ?? activeBoundId ?? undefined, - paymentMethod: paymentMethod, couponIds: selectedCouponIds.length ? selectedCouponIds : undefined, userNotes: userNotes, isFlashDelivery: isFlashDelivery, @@ -233,12 +202,11 @@ const PaymentAndOrderComponent: React.FC = ({ - setPaymentMethod('cod')} - style={tw`flex-row items-center p-4 rounded-xl border ${paymentMethod === 'cod' ? 'border-brand500 bg-blue-50' : 'border-gray-200'}`} + - - {paymentMethod === 'cod' && } + + @@ -247,7 +215,7 @@ const PaymentAndOrderComponent: React.FC = ({ Cash on Delivery Pay when you receive - + diff --git a/apps/user-ui/test-case-info.md b/apps/user-ui/test-case-info.md index f4a41bc..b3f16ef 100644 --- a/apps/user-ui/test-case-info.md +++ b/apps/user-ui/test-case-info.md @@ -290,14 +290,13 @@ Cart: 2 x product 2 @ 215 = 430. Consts: freeDeliveryThreshold 249, deliveryChar | 3 | navigates to addresses | push `…/me/addresses` | | 4 | logs out from the footer button | `logout` called | -### `me-orders.test.tsx` — 5 +### `me-orders.test.tsx` — 4 | # | Test | Asserts | | --- | --- | --- | | 1 | renders the fetched orders | `user.order.getOrders` + row | | 2 | navigates to the order detail when a row is pressed | push `…/my-orders/11` | | 3 | shows the empty state and Start Shopping navigates home | push `…/home` | | 4 | shows the error state and retries | error copy + `getOrders` re-requested | -| 5 | retries payment through user.payment.createRazorpayOrder | procedure called | ### `order-detail.test.tsx` — 6 | # | Test | Asserts | @@ -613,7 +612,7 @@ the totals above but not yet in the per-suite tables below. | Path | Purpose | | --- | --- | -| `tests/setup.ts` | Global stubs: axios, native modules (webview/updates/linking/location/notifications/razorpay/secure-store), `@react-navigation/native` focus, auth, storage, refresh hooks; frozen clock | +| `tests/setup.ts` | Global stubs: axios, native modules (webview/updates/linking/location/notifications/secure-store), `@react-navigation/native` focus, auth, storage, refresh hooks; frozen clock | | `tests/mocks/api.ts` | axios CDN + tRPC stubs; `setupApiMocks({ procedures, products, stores, storeProducts, consts, orders, fail*, pending* })` | | `tests/mocks/procedures.ts` | `expectProcedureCalled` / `procedureCalls` / `lastProcedureInput` (query + body inputs) | | `tests/mocks/router.ts` | Mocked expo-router + `routerMock` spies + `searchParamsMock` | diff --git a/apps/user-ui/tests/components/payment-and-order-money.test.tsx b/apps/user-ui/tests/components/payment-and-order-money.test.tsx index 3e75d0f..a039070 100644 --- a/apps/user-ui/tests/components/payment-and-order-money.test.tsx +++ b/apps/user-ui/tests/components/payment-and-order-money.test.tsx @@ -21,7 +21,7 @@ import { lastProcedureInput, expectProcedureCalled } from '../mocks/procedures' import { routerMock } from '../mocks/router' import { Providers, renderWithProviders } from '../helpers/render' -const PLACE_ORDER_OK = { data: [{ id: 99, isCod: true }] } +const PLACE_ORDER_OK = { data: [{ id: 99 }] } const baseProps = { selectedAddress: 1, @@ -140,7 +140,7 @@ describe('PaymentAndOrderComponent money', () => { it('uses the server-stored order amount for the success URL when present', async () => { const api = setupApiMocks({ procedures: { - 'user.order.placeOrder': { data: [{ id: 99, isCod: true, totalAmount: '400' }] }, + 'user.order.placeOrder': { data: [{ id: 99, totalAmount: '400' }] }, }, }) diff --git a/apps/user-ui/tests/components/payment-and-order.test.tsx b/apps/user-ui/tests/components/payment-and-order.test.tsx index 131cb53..6daba6c 100644 --- a/apps/user-ui/tests/components/payment-and-order.test.tsx +++ b/apps/user-ui/tests/components/payment-and-order.test.tsx @@ -31,7 +31,7 @@ const baseProps = { selectedCoupons: [], } -const PLACE_ORDER_OK = { data: [{ id: 99, isCod: true }] } +const PLACE_ORDER_OK = { data: [{ id: 99 }] } const readCart = async (key: string) => { const raw = await StorageServiceCasual.getItem(key) @@ -86,7 +86,6 @@ describe('PaymentAndOrderComponent', () => { expect(lastProcedureInput(api.fetchMock, 'user.order.placeOrder')).toEqual({ selectedItems: [{ skuId: 2, quantity: 1, slotId: 1849 }], addressId: 1, - paymentMethod: 'cod', couponIds: undefined, userNotes: '', isFlashDelivery: false, diff --git a/apps/user-ui/tests/home-page/next-order-glimpse.test.tsx b/apps/user-ui/tests/home-page/next-order-glimpse.test.tsx index 6aada1d..2d47ef8 100644 --- a/apps/user-ui/tests/home-page/next-order-glimpse.test.tsx +++ b/apps/user-ui/tests/home-page/next-order-glimpse.test.tsx @@ -29,12 +29,8 @@ const baseOrder = (over: Record = {}) => ({ orderStatus: 'confirmed', deliveryDate: '2026-09-26T10:00:00.000Z', cancelReason: null, - paymentMode: 'cod', totalAmount: 500, deliveryCharge: 0, - paymentStatus: 'pending', - refundStatus: 'none', - refundAmount: null, userNotes: null, isFlashDelivery: false, createdAt: '2026-09-25T10:00:00.000Z', diff --git a/apps/user-ui/tests/mocks/native.ts b/apps/user-ui/tests/mocks/native.ts index 235bf98..829548b 100644 --- a/apps/user-ui/tests/mocks/native.ts +++ b/apps/user-ui/tests/mocks/native.ts @@ -107,16 +107,3 @@ export function secureStoreMock() { }), } } - -/** react-native-razorpay: Checkout.open resolves with a success payload. */ -export function razorpayMock() { - class Checkout { - static open = jest.fn(async () => ({ - razorpay_payment_id: 'pay_test', - razorpay_order_id: 'order_test', - razorpay_signature: 'sig_test', - })) - } - - return { __esModule: true, default: Checkout } -} diff --git a/apps/user-ui/tests/screens/checkout-coupons.test.tsx b/apps/user-ui/tests/screens/checkout-coupons.test.tsx index 8f6c476..987e0da 100644 --- a/apps/user-ui/tests/screens/checkout-coupons.test.tsx +++ b/apps/user-ui/tests/screens/checkout-coupons.test.tsx @@ -59,7 +59,7 @@ const ADDRESSES = { ], } -const PLACE_ORDER_OK = { data: [{ id: 99, isCod: true }] } +const PLACE_ORDER_OK = { data: [{ id: 99 }] } /** * Mount checkout with one line (2 x 215) and the given eligible coupons. @@ -237,7 +237,6 @@ describe('Checkout coupon discount calculation', () => { selectedItems: [{ skuId: PRODUCT_ID, quantity: 2, slotId: SLOT_ID }], addressId: 1, couponIds: [COUPON_ID], - paymentMethod: 'cod', }) await waitFor(() => expect(routerMock.replace).toHaveBeenCalledWith( diff --git a/apps/user-ui/tests/screens/me-orders.test.tsx b/apps/user-ui/tests/screens/me-orders.test.tsx index c721bdd..49b1ea8 100644 --- a/apps/user-ui/tests/screens/me-orders.test.tsx +++ b/apps/user-ui/tests/screens/me-orders.test.tsx @@ -1,7 +1,6 @@ /** * My orders (app/(drawer)/(tabs)/me/my-orders/index.tsx). - * Asserts user.order.getOrders, the loading/error/empty states, row navigation - * and the retry-payment -> user.payment.createRazorpayOrder path. + * Asserts user.order.getOrders, the loading/error/empty states and row navigation. */ jest.mock('expo-router', () => require('../mocks/router').expoRouterMock()) @@ -24,12 +23,8 @@ const ORDER = { deliveryStatus: 'pending', deliveryDate: '2026-09-26T10:00:00.000Z', cancelReason: null, - paymentMode: 'COD', totalAmount: 500, deliveryCharge: 15, - paymentStatus: 'pending', - refundStatus: 'not_applicable', - refundAmount: null, userNotes: null, isFlashDelivery: false, createdAt: '2026-09-20T10:00:00.000Z', @@ -38,14 +33,6 @@ const ORDER = { ], } -const ONLINE_PENDING_ORDER = { - ...ORDER, - id: 12, - orderId: 'ORD-12', - paymentMode: 'Online', - paymentStatus: 'pending', -} - const ordersResponse = (orders: unknown[]) => ({ data: orders, pagination: { page: 1, pageSize: 10, totalCount: orders.length, totalPages: 1 }, @@ -110,23 +97,4 @@ describe('My orders', () => { ) }) - it('retries payment through user.payment.createRazorpayOrder', async () => { - const api = setupApiMocks({ - procedures: { - 'user.order.getOrders': ordersResponse([ONLINE_PENDING_ORDER]), - 'user.payment.createRazorpayOrder': { key: 'rzp', razorpayOrderId: 'o1' }, - }, - }) - renderWithProviders(, { centralStores: false }) - - await waitFor(() => expect(screen.getByText('Retry Payment')).toBeVisible()) - // onPress calls e.stopPropagation(), so a synthetic event is required. - fireEvent.press(screen.getByText('Retry Payment'), { - stopPropagation: jest.fn(), - }) - - await waitFor(() => - expectProcedureCalled(api.fetchMock, 'user.payment.createRazorpayOrder') - ) - }) }) diff --git a/apps/user-ui/tests/screens/mutation-invalidation.test.tsx b/apps/user-ui/tests/screens/mutation-invalidation.test.tsx index bd0966e..126c39a 100644 --- a/apps/user-ui/tests/screens/mutation-invalidation.test.tsx +++ b/apps/user-ui/tests/screens/mutation-invalidation.test.tsx @@ -56,8 +56,6 @@ const ORDER = { deliveryStatus: 'pending', deliveryDate: '2026-09-26T10:00:00.000Z', cancelReason: null, - paymentMode: 'COD', - paymentStatus: 'pending', orderAmount: 500, discountAmount: 0, deliveryCharge: 15, @@ -124,7 +122,7 @@ describe('mutation invalidation', () => { const queryClient = createQueryClient() const api = setupApiMocks({ orders: [], - procedures: { 'user.order.placeOrder': { data: [{ id: 99, isCod: true }] } }, + procedures: { 'user.order.placeOrder': { data: [{ id: 99 }] } }, }) renderWithProviders( diff --git a/apps/user-ui/tests/screens/order-amounts.test.tsx b/apps/user-ui/tests/screens/order-amounts.test.tsx index f017f74..40386d2 100644 --- a/apps/user-ui/tests/screens/order-amounts.test.tsx +++ b/apps/user-ui/tests/screens/order-amounts.test.tsx @@ -26,8 +26,6 @@ const order = (over: Record = {}) => ({ deliveryStatus: 'pending', deliveryDate: '2026-09-26T10:00:00.000Z', cancelReason: null, - paymentMode: 'COD', - paymentStatus: 'pending', orderAmount: 500, discountAmount: 0, deliveryCharge: 15, diff --git a/apps/user-ui/tests/screens/order-detail.test.tsx b/apps/user-ui/tests/screens/order-detail.test.tsx index cf48f39..a9e534e 100644 --- a/apps/user-ui/tests/screens/order-detail.test.tsx +++ b/apps/user-ui/tests/screens/order-detail.test.tsx @@ -24,8 +24,6 @@ const ORDER = { deliveryStatus: 'pending', deliveryDate: '2026-09-26T10:00:00.000Z', cancelReason: null, - paymentMode: 'COD', - paymentStatus: 'pending', orderAmount: 500, discountAmount: 0, deliveryCharge: 15, diff --git a/apps/user-ui/tests/setup.ts b/apps/user-ui/tests/setup.ts index fb05426..60ba61a 100644 --- a/apps/user-ui/tests/setup.ts +++ b/apps/user-ui/tests/setup.ts @@ -57,7 +57,6 @@ jest.mock('expo-updates', () => require('./mocks/native').updatesMock()) jest.mock('expo-linking', () => require('./mocks/native').linkingMock()) jest.mock('expo-location', () => require('./mocks/native').locationMock()) jest.mock('expo-notifications', () => require('./mocks/native').notificationsMock()) -jest.mock('react-native-razorpay', () => require('./mocks/native').razorpayMock()) /** * useHideTabNav / useAuthenticatedRoute use @react-navigation/native's diff --git a/apps/web-ui/src/components/PaymentAndOrderComponent.tsx b/apps/web-ui/src/components/PaymentAndOrderComponent.tsx index 5661763..ecd9dd7 100644 --- a/apps/web-ui/src/components/PaymentAndOrderComponent.tsx +++ b/apps/web-ui/src/components/PaymentAndOrderComponent.tsx @@ -26,7 +26,6 @@ export function PaymentAndOrderComponent({ const queryClient = useQueryClient() const [userNotes, setUserNotes] = useState('') const [isLoading, setIsLoading] = useState(false) - const [paymentMethod, setPaymentMethod] = useState<'online' | 'cod'>('cod') const { data: productsData } = useAllProducts() const constsData = useRegionalConsts() @@ -108,7 +107,6 @@ export function PaymentAndOrderComponent({ })), addressId: selectedAddress, regionId: selectedRegionId, - paymentMethod: paymentMethod, userNotes: userNotes, isFlashDelivery: isFlashDelivery, } @@ -163,18 +161,9 @@ export function PaymentAndOrderComponent({ {/* Cash on Delivery */} -
setPaymentMethod('cod')} - className={`flex items-center rounded-xl border p-4 transition-all ${ - paymentMethod === 'cod' ? 'border-brand-500 bg-blue-50' : 'border-gray-200' - }`} - > -
- {paymentMethod === 'cod' &&
} +
+
+
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