This commit is contained in:
shafi54 2026-10-17 12:07:20 +05:30
parent f24d2edb6f
commit 79aa6dba71
81 changed files with 228 additions and 2002 deletions

View file

@ -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<Set<number>>(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 (
<AppContainer>
@ -652,121 +555,6 @@ export default function OrderDetails() {
</View>
)}
{/* Refund Coupon Section */}
{order.orderStatus?.refundCouponId && (
<View style={tw`bg-blue-50 p-5 rounded-2xl shadow-sm mb-4 border border-blue-100`}>
<MyText style={tw`text-lg font-bold text-blue-800 mb-3`}>
Refund Coupon
</MyText>
<View style={tw`bg-blue-100 p-4 rounded-xl border border-blue-200`}>
<View style={tw`flex-row items-center mb-2`}>
<MaterialIcons name="local-offer" size={20} color="#2563EB" />
<MyText style={tw`text-blue-800 font-bold ml-2`}>
{order.couponCode}
</MyText>
</View>
<MyText style={tw`text-blue-700 text-sm`}>
Generated refund coupon for order cancellation
</MyText>
<View style={tw`flex-row justify-between items-center mt-3`}>
<MyText style={tw`text-blue-600 font-medium`}>
Value:
</MyText>
<MyText style={tw`text-blue-800 font-bold text-lg`}>
₹{order.couponData?.discountAmount}
</MyText>
</View>
{/* <View style={tw`flex-row justify-between items-center mt-2`}>
<MyText style={tw`text-blue-600 font-medium`}>
Expires:
</MyText>
<MyText style={tw`text-blue-800 font-medium`}>
{order.couponData?.
? dayjs(order.orderStatus.refundCoupon.validTill).format("DD MMM YYYY")
: "N/A"}
</MyText>
</View> */}
</View>
</View>
)}
{/* 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 */}
{/*
<View
style={tw`bg-red-50 p-5 rounded-2xl border border-red-100 mb-4`}
>
<MyText style={tw`text-sm font-bold text-red-800 mb-3`}>
{order.status === "cancelled" ? "Cancellation Details" : "Refund Details"}
</MyText>
{order.status === "cancelled" && order.cancelReason && (
<View style={tw`mb-3`}>
<MyText
style={tw`text-xs text-red-600 uppercase font-bold mb-1`}
>
Cancellation Reason
</MyText>
<MyText style={tw`text-sm text-red-900`}>
{order.cancelReason}
</MyText>
</View>
)}
<View
style={tw`flex-row justify-between items-center bg-white/50 p-3 rounded-xl mb-4`}
>
<MyText style={tw`text-sm font-medium text-red-800`}>
Refund Status
</MyText>
<View style={tw`flex-row items-center`}>
<View
style={tw`w-2 h-2 rounded-full mr-2 ${getRefundDotColor(order.refundStatus)}`}
/>
<MyText
style={tw`text-sm font-bold ${getRefundTextColor(order.refundStatus)}`}
>
{getRefundStatusText(order.refundStatus)}
</MyText>
</View>
</View>
{order.refundRecord && (
<View
style={tw`flex-row justify-between items-center bg-white/50 p-3 rounded-xl mb-4`}
>
<MyText style={tw`text-sm font-medium text-red-800`}>
Refund Amount
</MyText>
<MyText style={tw`text-sm font-bold text-red-900`}>
₹{order.refundRecord.refundAmount}
</MyText>
</View>
)}
{(!Boolean(order.refundRecord)) && <View style={tw`flex-row gap-3 mt-2`}>
{!order.isCod && (<TouchableOpacity
style={tw`flex-1 bg-red-500 py-3 px-4 rounded-xl items-center flex-row justify-center shadow-sm`}
onPress={() => setInitiateRefundDialogOpen(true)}
>
<MaterialIcons name="payments" size={18} color="white" style={tw`mr-2`} />
<MyText style={tw`text-white font-bold text-sm`}>
Initiate Refund
</MyText>
</TouchableOpacity>
)}
<TouchableOpacity
style={tw`flex-1 bg-emerald-500 py-3 px-4 rounded-xl items-center flex-row justify-center shadow-sm`}
onPress={() => setGenerateCouponDialogOpen(true)}
>
<MaterialIcons name="local-offer" size={18} color="white" style={tw`mr-2`} />
<MyText style={tw`text-white font-bold text-sm`}>
Generate Refund Coupon
</MyText>
</TouchableOpacity>
</View>}
</View>
*/}
</View>
<View style={tw`h-32`}></View>
@ -795,163 +583,6 @@ export default function OrderDetails() {
</TouchableOpacity>
</View>
{/* Generate Coupon Dialog */}
<BottomDialog
open={generateCouponDialogOpen}
onClose={() => setGenerateCouponDialogOpen(false)}
>
<View style={tw`p-6`}>
<View style={tw`items-center mb-6`}>
<View style={tw`w-12 h-12 bg-emerald-100 rounded-full items-center justify-center mb-3`}>
<MaterialIcons name="local-offer" size={24} color="#10B981" />
</View>
<MyText style={tw`text-xl font-bold text-gray-900 text-center`}>
Generate Refund Coupon
</MyText>
<MyText style={tw`text-gray-500 text-center mt-2 text-sm leading-5`}>
Create a one-time use coupon for the customer equal to the order amount. Valid for 30 days.
</MyText>
</View>
<View style={tw`bg-amber-50 p-4 rounded-xl border border-amber-100 mb-6 flex-row items-start`}>
<MaterialIcons name="info-outline" size={20} color="#D97706" style={tw`mt-0.5`} />
<MyText style={tw`text-sm text-amber-800 ml-2 flex-1 leading-5`}>
This only works for online payment orders. COD orders cannot generate refund coupons.
</MyText>
</View>
<View style={tw`flex-row gap-3`}>
<TouchableOpacity
style={tw`flex-1 bg-gray-100 py-3.5 rounded-xl items-center`}
onPress={() => setGenerateCouponDialogOpen(false)}
>
<MyText style={tw`text-gray-700 font-bold`}>Cancel</MyText>
</TouchableOpacity>
<TouchableOpacity
style={tw`flex-1 bg-emerald-500 py-3.5 rounded-xl items-center shadow-sm`}
onPress={handleGenerateCoupon}
disabled={generateCouponMutation.isPending}
>
<MyText style={tw`text-white font-bold`}>
{generateCouponMutation.isPending
? "Generating..."
: "Generate Coupon"}
</MyText>
</TouchableOpacity>
</View>
</View>
</BottomDialog>
{/* Initiate Refund Dialog */}
<BottomDialog
open={initiateRefundDialogOpen}
onClose={() => setInitiateRefundDialogOpen(false)}
>
<View style={tw`p-6`}>
<View style={tw`items-center mb-6`}>
<View style={tw`w-12 h-12 bg-red-100 rounded-full items-center justify-center mb-3`}>
<MaterialIcons name="payments" size={24} color="#EF4444" />
</View>
<MyText style={tw`text-xl font-bold text-gray-900 text-center`}>
Initiate Refund
</MyText>
<MyText style={tw`text-gray-500 text-center mt-2 text-sm`}>
Process a refund directly to the customer&apos;s source account via Razorpay.
</MyText>
</View>
{/* Refund Type Selection */}
<View style={tw`mb-6`}>
<MyText style={tw`text-sm font-bold text-gray-900 mb-3 uppercase tracking-wide`}>
Refund Type
</MyText>
<View style={tw`flex-row gap-3`}>
<TouchableOpacity
style={tw`flex-1 p-4 rounded-xl border-2 ${refundType === "percent"
? "border-blue-500 bg-blue-50"
: "border-gray-100 bg-gray-50"
} items-center`}
onPress={() => setRefundType("percent")}
>
<MaterialIcons
name="percent"
size={24}
color={refundType === "percent" ? "#3B82F6" : "#9CA3AF"}
style={tw`mb-2`}
/>
<MyText
style={tw`text-sm font-bold ${refundType === "percent" ? "text-blue-700" : "text-gray-500"
}`}
>
Percentage
</MyText>
</TouchableOpacity>
<TouchableOpacity
style={tw`flex-1 p-4 rounded-xl border-2 ${refundType === "amount"
? "border-blue-500 bg-blue-50"
: "border-gray-100 bg-gray-50"
} items-center`}
onPress={() => setRefundType("amount")}
>
<MaterialIcons
name="attach-money"
size={24}
color={refundType === "amount" ? "#3B82F6" : "#9CA3AF"}
style={tw`mb-2`}
/>
<MyText
style={tw`text-sm font-bold ${refundType === "amount" ? "text-blue-700" : "text-gray-500"
}`}
>
Fixed Amount
</MyText>
</TouchableOpacity>
</View>
</View>
{/* Refund Value Input */}
<View style={tw`mb-6`}>
<MyTextInput
topLabel={`Refund ${refundType === "percent" ? "Percentage (%)" : "Amount (₹)"
}`}
value={refundValue}
onChangeText={setRefundValue}
keyboardType="numeric"
placeholder={refundType === "percent" ? "100" : "0.00"}
style={tw`bg-white`}
/>
</View>
<View style={tw`bg-amber-50 p-4 rounded-xl border border-amber-100 mb-6 flex-row items-start`}>
<MaterialIcons name="info-outline" size={20} color="#D97706" style={tw`mt-0.5`} />
<MyText style={tw`text-sm text-amber-800 ml-2 flex-1 leading-5`}>
For COD orders, refunds are processed immediately upon delivery confirmation.
</MyText>
</View>
<View style={tw`flex-row gap-3`}>
<TouchableOpacity
style={tw`flex-1 bg-gray-100 py-3.5 rounded-xl items-center`}
onPress={() => setInitiateRefundDialogOpen(false)}
>
<MyText style={tw`text-gray-700 font-bold`}>Cancel</MyText>
</TouchableOpacity>
<TouchableOpacity
style={tw`flex-1 bg-red-500 py-3.5 rounded-xl items-center shadow-sm`}
onPress={handleInitiateRefund}
disabled={initiateRefundMutation.isPending}
>
<MyText style={tw`text-white font-bold`}>
{initiateRefundMutation.isPending
? "Processing..."
: "Confirm Refund"}
</MyText>
</TouchableOpacity>
</View>
</View>
</BottomDialog>
{/* Cancel Order Dialog */}
<CancelOrderDialog
orderId={order.id}

View file

@ -206,11 +206,6 @@ const OrderItem = ({ order, refetch }: { order: OrderType; refetch: () => void }
{/* <View style={tw`px-2.5 py-1 rounded-full ${getStatusColor(order.status)}`}>
<MyText style={tw`text-xs font-semibold capitalize`}>{order.status}</MyText>
</View> */}
{/* {order.isCod && (
<View style={tw`px-2.5 py-1 rounded-full bg-blue-50 border border-blue-100`}>
<MyText style={tw`text-xs font-semibold text-blue-700`}>COD</MyText>
</View>
)} */}
<View style={tw`flex-row items-center gap-1`}>
<MyText style={tw`text-sm font-semibold text-gray-600`}>Packaged</MyText>
<Checkbox

View file

@ -59,7 +59,7 @@ export default function CancelOrderDialog({ orderId, open, onClose, onSuccess }:
Cancel Order
</MyText>
<MyText style={tw`text-gray-500 text-center mt-2 text-sm leading-5`}>
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.
</MyText>
</View>

View file

@ -51,9 +51,6 @@ const slotOrder = (overrides: Record<string, unknown> = {}) => ({
status: 'pending',
isPackaged: false,
isDelivered: false,
isCod: true,
paymentMode: 'COD',
paymentStatus: 'cod',
slotId: 3,
adminNotes: 'fragile',
userNotes: null,

View file

@ -51,7 +51,6 @@ const makeOrder = (overrides: Record<string, unknown> = {}) => ({
status: 'pending',
isPackaged: false,
isDelivered: false,
isCod: true,
isFlashDelivery: false,
userNotes: null,
adminNotes: 'call before delivery',

View file

@ -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<string, unknown> = {}) => ({
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<string, unknown> = {}) => ({
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()

View file

@ -49,7 +49,7 @@ export default function CancelOrderDialog({ orderId, open, onClose, onSuccess }:
Cancel Order
</P>
<P className="text-gray-500 text-center mt-2 text-sm leading-5">
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.
</P>
</div>

View file

@ -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<Set<number>>(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() {
</div>
)}
{/* Refund Coupon Section */}
{order.orderStatus?.refundCouponId && (
<div className="mb-4 rounded-2xl border border-blue-100 bg-blue-50 p-5 shadow-sm">
<MyText className="mb-3 block text-lg font-bold text-blue-800">
Refund Coupon
</MyText>
<div className="rounded-xl border border-blue-200 bg-blue-100 p-4">
<div className="mb-2 flex flex-row items-center">
<TicketPercent size={20} color="#2563EB" />
<MyText className="ml-2 font-bold text-blue-800">
{order.couponCode}
</MyText>
</div>
<MyText className="block text-sm text-blue-700">
Generated refund coupon for order cancellation
</MyText>
<div className="mt-3 flex flex-row items-center justify-between">
<MyText className="font-medium text-blue-600">
Value:
</MyText>
<MyText className="text-lg font-bold text-blue-800">
₹{order.couponData?.discountAmount}
</MyText>
</div>
</div>
</div>
)}
{/* 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 */}
</div>
<div className="h-32" />
@ -657,161 +556,6 @@ function OrderDetails() {
</button>
</div>
{/* Generate Coupon Dialog */}
<BottomDialog
open={generateCouponDialogOpen}
onClose={() => setGenerateCouponDialogOpen(false)}
>
<div className="p-6">
<div className="mb-6 items-center">
<span className="mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-full bg-emerald-100">
<TicketPercent size={24} color="#10B981" />
</span>
<MyText className="block text-center text-xl font-bold text-gray-900">
Generate Refund Coupon
</MyText>
<MyText className="mt-2 block text-center text-sm leading-5 text-gray-500">
Create a one-time use coupon for the customer equal to the order amount. Valid for 30 days.
</MyText>
</div>
<div className="mb-6 flex flex-row items-start rounded-xl border border-amber-100 bg-amber-50 p-4">
<Info size={20} color="#D97706" className="mt-0.5" />
<MyText className="ml-2 flex-1 text-sm leading-5 text-amber-800">
This only works for online payment orders. COD orders cannot generate refund coupons.
</MyText>
</div>
<div className="flex flex-row gap-3">
<button
className="flex-1 items-center rounded-xl bg-gray-100 py-3.5"
onClick={() => setGenerateCouponDialogOpen(false)}
>
<MyText className="font-bold text-gray-700">Cancel</MyText>
</button>
<button
className="flex-1 items-center rounded-xl bg-emerald-500 py-3.5 shadow-sm disabled:opacity-50"
onClick={handleGenerateCoupon}
disabled={generateCouponMutation.isPending}
>
<MyText className="font-bold text-white">
{generateCouponMutation.isPending
? 'Generating...'
: 'Generate Coupon'}
</MyText>
</button>
</div>
</div>
</BottomDialog>
{/* Initiate Refund Dialog */}
<BottomDialog
open={initiateRefundDialogOpen}
onClose={() => setInitiateRefundDialogOpen(false)}
>
<div className="p-6">
<div className="mb-6 items-center">
<span className="mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-full bg-red-100">
<Banknote size={24} color="#EF4444" />
</span>
<MyText className="block text-center text-xl font-bold text-gray-900">
Initiate Refund
</MyText>
<MyText className="mt-2 block text-center text-sm text-gray-500">
Process a refund directly to the customer&apos;s source account via Razorpay.
</MyText>
</div>
{/* Refund Type Selection */}
<div className="mb-6">
<MyText className="mb-3 block text-sm font-bold uppercase tracking-wide text-gray-900">
Refund Type
</MyText>
<div className="flex flex-row gap-3">
<button
className={`flex-1 items-center rounded-xl border-2 p-4 ${refundType === 'percent'
? 'border-blue-500 bg-blue-50'
: 'border-gray-100 bg-gray-50'
}`}
onClick={() => setRefundType('percent')}
>
<Percent
size={24}
color={refundType === 'percent' ? '#3B82F6' : '#9CA3AF'}
className="mb-2"
/>
<MyText
className={`text-sm font-bold ${refundType === 'percent' ? 'text-blue-700' : 'text-gray-500'
}`}
>
Percentage
</MyText>
</button>
<button
className={`flex-1 items-center rounded-xl border-2 p-4 ${refundType === 'amount'
? 'border-blue-500 bg-blue-50'
: 'border-gray-100 bg-gray-50'
}`}
onClick={() => setRefundType('amount')}
>
<Banknote
size={24}
color={refundType === 'amount' ? '#3B82F6' : '#9CA3AF'}
className="mb-2"
/>
<MyText
className={`text-sm font-bold ${refundType === 'amount' ? 'text-blue-700' : 'text-gray-500'
}`}
>
Fixed Amount
</MyText>
</button>
</div>
</div>
{/* Refund Value Input */}
<div className="mb-6">
<MyInput
topLabel={`Refund ${refundType === 'percent' ? 'Percentage (%)' : 'Amount (₹)'
}`}
value={refundValue}
onChange={(e) => setRefundValue(e.target.value)}
type="number"
placeholder={refundType === 'percent' ? '100' : '0.00'}
className="bg-white"
/>
</div>
<div className="mb-6 flex flex-row items-start rounded-xl border border-amber-100 bg-amber-50 p-4">
<Info size={20} color="#D97706" className="mt-0.5" />
<MyText className="ml-2 flex-1 text-sm leading-5 text-amber-800">
For COD orders, refunds are processed immediately upon delivery confirmation.
</MyText>
</div>
<div className="flex flex-row gap-3">
<button
className="flex-1 items-center rounded-xl bg-gray-100 py-3.5"
onClick={() => setInitiateRefundDialogOpen(false)}
>
<MyText className="font-bold text-gray-700">Cancel</MyText>
</button>
<button
className="flex-1 items-center rounded-xl bg-red-500 py-3.5 shadow-sm disabled:opacity-50"
onClick={handleInitiateRefund}
disabled={initiateRefundMutation.isPending}
>
<MyText className="font-bold text-white">
{initiateRefundMutation.isPending
? 'Processing...'
: 'Confirm Refund'}
</MyText>
</button>
</div>
</div>
</BottomDialog>
{/* Cancel Order Dialog */}
<CancelOrderDialog
orderId={order.id}

View file

@ -117,9 +117,6 @@ export type {
UserSlotsResponse,
UserSlotsWithProductsResponse,
UserSlotsListResponse,
UserPaymentOrderResponse,
UserPaymentVerifyResponse,
UserPaymentFailResponse,
UserAuthProfile,
UserAuthResponse,
UserAuthResult,
@ -157,5 +154,4 @@ export type {
CartItem,
Order,
OrderItem,
Payment,
} from '@packages/shared';

View file

@ -1,16 +1,6 @@
import { checkPendingPayments, checkRefundStatuses } from '@/src/jobs/payment-status-checker'
const runCombinedJob = async () => {
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);

View file

@ -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);
}
};

View file

@ -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

View file

@ -106,6 +106,7 @@ export async function readEssentialConstsFromKv(boundId: number): Promise<Essent
console.error('readEssentialConstsFromKv failed:', error)
}
console.log('building consts')
const payload = await buildEssentialConsts(boundId)
try {

View file

@ -1,54 +0,0 @@
// import Razorpay from "razorpay";
export class RazorpayPaymentService {
// private static instance = new Razorpay({
// key_id: razorpayId,
// key_secret: razorpaySecret,
// });
//
static async createOrder(orderId: number, amount: string) {
// Create Razorpay order
// const razorpayOrder = await this.instance.orders.create({
// amount: parseFloat(amount) * 100, // Convert to paisa
// currency: 'INR',
// receipt: `order_${orderId}`,
// notes: {
// customerOrderId: orderId.toString(),
// },
// });
//
// return razorpayOrder;
}
static async insertPaymentRecord(orderId: number, razorpayOrder: any, tx?: unknown) {
// Use transaction if provided, otherwise use db
// const dbInstance = tx || db;
//
// // Insert payment record
// const [payment] = await dbInstance
// .insert(payments)
// .values({
// status: 'pending',
// gateway: 'razorpay',
// orderId,
// token: orderId.toString(),
// merchantOrderId: razorpayOrder.id,
// payload: razorpayOrder,
// })
// .returning();
//
// return payment;
}
static async initiateRefund(paymentId: string, amount: number) {
// const refund = await this.instance.payments.refund(paymentId, {
// amount,
// });
// return refund;
}
static async fetchRefund(refundId: string) {
// const refund = await this.instance.refunds.fetch(refundId);
// return refund;
}
}

View file

@ -96,7 +96,6 @@ const formatCancellationMessage = (orderData: any, cancellationData: Cancellatio
${orderData.orderItems?.map((item: any) => ` • ${item.sku?.product?.name || 'Unknown'} x${item.quantity}`).join('\n') || ' N/A'}
💰 <b>Total:</b> ₹${orderData.totalAmount}
💳 <b>Refund:</b> ${orderData.refundStatus === 'na' ? 'N/A (COD)' : orderData.refundStatus || 'Pending'}
❓ <b>Reason:</b> ${cancellationData.reason}
👤 <b>Cancelled by:</b> ${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)

View file

@ -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,

View file

@ -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,

View file

@ -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<Coupon> => {
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(),

View file

@ -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<boolean> {
return await deleteOrderByIdInDb(regionId, orderId)
}

View file

@ -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 {}
}),
});

View file

@ -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<typeof orderStatus.$inferInsert, "id"> = {
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);

View file

@ -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<UserPaymentOrderResponse> => {
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<UserPaymentVerifyResponse> => {
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<UserPaymentFailResponse> => {
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",
}
}),
});

View file

@ -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,
});

View file

@ -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).

View file

@ -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',
}),
])

View file

@ -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

View file

@ -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(() =>

View file

@ -95,7 +95,6 @@ describe('coupon discount maths', () => {
selectedItems: items,
addressId,
regionId: 1,
paymentMethod: 'cod',
...(couponId != null
? { couponIds: Array.isArray(couponId) ? couponId : [couponId] }
: {}),

View file

@ -72,7 +72,6 @@ describe('coupon UX', () => {
selectedItems: [{ skuId, quantity, slotId }],
addressId: user.addressId,
regionId: 1,
paymentMethod: 'cod',
...(couponId ? { couponIds: [couponId] } : {}),
})

View file

@ -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],
})
)

View file

@ -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(() =>

View file

@ -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)

View file

@ -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')
})
})

View file

@ -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

View file

@ -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
})

View file

@ -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',
})
)

View file

@ -60,7 +60,6 @@ describe('placeOrder edge cases', () => {
selectedItems: [{ skuId, quantity: 1, slotId }],
addressId,
regionId: 1,
paymentMethod: 'cod',
...over,
})

View file

@ -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"

View file

@ -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"

View file

@ -191,24 +191,6 @@ export default function OrderDetails() {
{/* Main Info Card */}
<View style={tw`bg-white rounded-2xl p-5 mb-4 border border-slate-100`}>
<View style={tw`flex-row items-center justify-between mb-4`}>
<View style={tw`flex-row items-center`}>
<View style={tw`w-10 h-10 rounded-full bg-slate-50 items-center justify-center mr-3`}>
<MaterialIcons name="payments" size={20} color="#64748B" />
</View>
<View>
<MyText style={tw`text-slate-400 text-[10px] font-bold uppercase`}>Payment Method</MyText>
<MyText style={tw`text-slate-900 font-bold`}>
{order.paymentMode?.toUpperCase() === "COD" ? "Cash on Delivery" : order.paymentMode}
</MyText>
</View>
</View>
<View style={tw`items-end`}>
<MyText style={tw`text-slate-400 text-[10px] font-bold uppercase`}>Status</MyText>
<MyText style={tw`text-slate-900 font-bold capitalize`}>{order.paymentStatus}</MyText>
</View>
</View>
{(order.deliveryDate || order.isFlashDelivery) && ["delivered", "success"].includes(order.deliveryStatus?.toLowerCase() || "") && (
<View style={tw`flex-row items-center pt-4 border-t border-slate-50`}>
{order.isFlashDelivery ? (
@ -301,12 +283,6 @@ export default function OrderDetails() {
<View style={tw`bg-rose-50 border border-rose-100 rounded-2xl p-5 mb-4`}>
<MyText style={tw`text-rose-700 text-[10px] font-bold uppercase mb-2`}>Cancellation Reason</MyText>
<MyText style={tw`text-rose-900 text-sm font-medium`}>{order.cancelReason}</MyText>
{order.refundAmount && (
<View style={tw`mt-3 pt-3 border-t border-rose-200/50 flex-row justify-between items-center`}>
<MyText style={tw`text-rose-700 text-xs`}>Refund Amount</MyText>
<MyText style={tw`text-rose-900 font-bold text-base`}>₹{order.refundAmount}</MyText>
</View>
)}
</View>
)}

View file

@ -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<OrderItemProps> = ({
item,
index,
getStatusColor,
getRefundStatusColor,
onPress,
onRetryPayment,
onViewMoreItems,
isPaymentPending,
refetch
}) => {
const mainStatus = getStatusColor(item.orderStatus);
@ -275,22 +269,6 @@ const OrderItem: React.FC<OrderItemProps> = ({
<MyText style={tw`text-xs text-rose-800 font-bold ml-2`}>Cancellation Details</MyText>
</View>
<MyText style={tw`text-xs text-rose-600 font-medium leading-relaxed`}>{item.cancelReason}</MyText>
{item.refundStatus && item.refundStatus !== REFUND_STATUS.NOT_APPLICABLE && (
<View style={tw`mt-3 pt-3 border-t border-rose-100 flex-row justify-between items-center`}>
<MyText style={tw`text-[10px] font-bold text-rose-700 uppercase`}>Refund Status</MyText>
<View style={tw`flex-row items-center px-2 py-1 bg-white rounded-lg border border-rose-200`}>
<MaterialIcons
name={getRefundStatusColor(item.refundStatus).icon as any}
size={12}
color={getRefundStatusColor(item.refundStatus).color}
/>
<MyText style={[tw`text-[10px] font-bold ml-1.5 uppercase`, { color: getRefundStatusColor(item.refundStatus).color }]}>
{item.refundStatus}
</MyText>
</View>
</View>
)}
</View>
)}
@ -313,30 +291,10 @@ const OrderItem: React.FC<OrderItemProps> = ({
)}
</View>
{(item.paymentMode === 'Online' && (item.paymentStatus === 'pending' || item.paymentStatus === 'failed')) ? (
<MyTouchableOpacity
onPress={(e) => {
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 ? (
<ActivityIndicator size="small" color="white" />
) : (
<>
<MaterialIcons name="payment" size={18} color="white" />
<MyText style={tw`text-white font-bold text-sm ml-2`}>Retry Payment</MyText>
</>
)}
</MyTouchableOpacity>
) : (
<View style={tw`bg-brand600 px-5 py-3 rounded-2xl shadow-lg shadow-brand100 flex-row items-center`}>
<MyText style={tw`text-white font-bold text-sm mr-1`}>View Details</MyText>
<MaterialIcons name="arrow-forward" size={16} color="white" />
</View>
)}
<View style={tw`bg-brand600 px-5 py-3 rounded-2xl shadow-lg shadow-brand100 flex-row items-center`}>
<MyText style={tw`text-white font-bold text-sm mr-1`}>View Details</MyText>
<MaterialIcons name="arrow-forward" size={16} color="white" />
</View>
</View>
</View>
</MyTouchableOpacity>
@ -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<boolean>(false);
const [dialogItems, setDialogItems] = useState<OrderItem[]>([]);
const [retryOrderId, setRetryOrderId] = useState<number>(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 (
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
@ -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}
/>
)}

View file

@ -53,7 +53,6 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
// 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<PaymentAndOrderProps> = ({
// 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<PaymentAndOrderProps> = ({
},
});
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<PaymentAndOrderProps> = ({
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<PaymentAndOrderProps> = ({
</View>
</MyTouchableOpacity>
<MyTouchableOpacity
onPress={() => setPaymentMethod('cod')}
style={tw`flex-row items-center p-4 rounded-xl border ${paymentMethod === 'cod' ? 'border-brand500 bg-blue-50' : 'border-gray-200'}`}
<View
style={tw`flex-row items-center p-4 rounded-xl border border-brand500 bg-blue-50`}
>
<View style={tw`w-5 h-5 rounded-full border-2 ${paymentMethod === 'cod' ? 'border-brand500' : 'border-gray-400'} items-center justify-center mr-3`}>
{paymentMethod === 'cod' && <View style={tw`w-2.5 h-2.5 rounded-full bg-brand500`} />}
<View style={tw`w-5 h-5 rounded-full border-2 border-brand500 items-center justify-center mr-3`}>
<View style={tw`w-2.5 h-2.5 rounded-full bg-brand500`} />
</View>
<View style={tw`w-10 h-10 bg-green-50 rounded-full items-center justify-center mr-3`}>
<FontAwesome5 name="rupee-sign" size={20} color="#10B981" />
@ -247,7 +215,7 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
<MyText style={tw`font-bold text-gray-900`}>Cash on Delivery</MyText>
<MyText style={tw`text-xs text-gray-500`}>Pay when you receive</MyText>
</View>
</MyTouchableOpacity>
</View>
<View style={tw`mt-3 flex-row items-center gap-4`}>
<View style={tw`flex-row items-center`}>

View file

@ -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` |

View file

@ -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' }] },
},
})

View file

@ -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,

View file

@ -29,12 +29,8 @@ const baseOrder = (over: Record<string, unknown> = {}) => ({
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',

View file

@ -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 }
}

View file

@ -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(

View file

@ -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(<MyOrders />, { 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')
)
})
})

View file

@ -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(

View file

@ -26,8 +26,6 @@ const order = (over: Record<string, unknown> = {}) => ({
deliveryStatus: 'pending',
deliveryDate: '2026-09-26T10:00:00.000Z',
cancelReason: null,
paymentMode: 'COD',
paymentStatus: 'pending',
orderAmount: 500,
discountAmount: 0,
deliveryCharge: 15,

View file

@ -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,

View file

@ -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

View file

@ -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({
</div>
{/* Cash on Delivery */}
<div
onClick={() => setPaymentMethod('cod')}
className={`flex items-center rounded-xl border p-4 transition-all ${
paymentMethod === 'cod' ? 'border-brand-500 bg-blue-50' : 'border-gray-200'
}`}
>
<div
className={`mr-3 flex h-5 w-5 items-center justify-center rounded-full border-2 ${
paymentMethod === 'cod' ? 'border-brand-500' : 'border-gray-400'
}`}
>
{paymentMethod === 'cod' && <div className="h-2.5 w-2.5 rounded-full bg-brand-500" />}
<div className="flex items-center rounded-xl border border-brand-500 bg-blue-50 p-4 transition-all">
<div className="mr-3 flex h-5 w-5 items-center justify-center rounded-full border-2 border-brand-500">
<div className="h-2.5 w-2.5 rounded-full bg-brand-500" />
</div>
<div className="mr-3 flex h-10 w-10 items-center justify-center rounded-full bg-green-50">
<Banknote className="h-5 w-5 text-green-500" />

View file

@ -98,7 +98,6 @@ function FlashCheckoutPage() {
})),
addressId: selectedAddressId,
regionId: selectedRegionId,
paymentMethod: 'cod',
isFlashDelivery: true,
})
}

View file

@ -98,7 +98,6 @@ function CheckoutPage() {
})),
addressId: selectedAddressId,
regionId: selectedRegionId,
paymentMethod: 'cod',
isFlashDelivery: false,
})
}

View file

@ -185,24 +185,6 @@ function OrderDetailPage() {
{/* Main Info Card */}
<div className="mb-4 rounded-2xl border border-slate-100 bg-white p-5">
<div className="mb-4 flex flex-row items-center justify-between">
<div className="flex flex-row items-center">
<div className="mr-3 flex h-10 w-10 items-center justify-center rounded-full bg-slate-50">
<CreditCard className="h-5 w-5 text-slate-500" />
</div>
<div>
<p className="text-[10px] font-bold uppercase text-slate-400">Payment Method</p>
<p className="font-bold text-slate-900">
{order.paymentMode?.toUpperCase() === 'COD' ? 'Cash on Delivery' : order.paymentMode}
</p>
</div>
</div>
<div className="items-end text-right">
<p className="text-[10px] font-bold uppercase text-slate-400">Status</p>
<p className="font-bold capitalize text-slate-900">{order.paymentStatus}</p>
</div>
</div>
{(order.deliveryDate || order.isFlashDelivery) &&
['delivered', 'success'].includes((order.deliveryStatus || '').toLowerCase()) && (
<div className="flex flex-row items-center border-t border-slate-50 pt-4">
@ -290,12 +272,6 @@ function OrderDetailPage() {
<div className="mb-4 rounded-2xl border border-rose-100 bg-rose-50 p-5">
<p className="mb-2 text-[10px] font-bold uppercase text-rose-700">Cancellation Reason</p>
<p className="text-sm font-medium text-rose-900">{order.cancelReason}</p>
{order.refundAmount && (
<div className="mt-3 flex flex-row items-center justify-between border-t border-rose-200/50 pt-3">
<p className="text-xs text-rose-700">Refund Amount</p>
<p className="text-base font-bold text-rose-900">₹{order.refundAmount}</p>
</div>
)}
</div>
)}

View file

@ -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: <span>✕</span>, label: 'Cancelled' }
case 'pending':
case 'payment_pending':
return { bg: 'bg-amber-50', text: 'text-amber-700', iconColor: '#D97706', icon: <span>🕐</span>, label: 'Pending' }
case 'packaged':
return { bg: 'bg-brand-50', text: 'text-brand-700', iconColor: '#1570EF', icon: <span>📦</span>, 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: <span>✓</span>, color: '#059669' }
case REFUND_STATUS.PROCESSING:
return { bg: 'bg-brand-50', text: 'text-brand-700', icon: <span>⟳</span>, color: '#1570EF' }
case REFUND_STATUS.PENDING:
return { bg: 'bg-amber-50', text: 'text-amber-700', icon: <span>🕐</span>, color: '#D97706' }
default:
return { bg: 'bg-slate-50', text: 'text-slate-700', icon: <span>i</span>, 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({
<p className="ml-2 text-xs font-bold text-rose-800">Cancellation Details</p>
</div>
<p className="text-xs font-medium leading-relaxed text-rose-600">{item.cancelReason}</p>
{item.refundStatus && item.refundStatus !== REFUND_STATUS.NOT_APPLICABLE && (
<div className="mt-3 flex flex-row items-center justify-between border-t border-rose-100 pt-3">
<p className="text-[10px] font-bold uppercase text-rose-700">Refund Status</p>
<span className={`flex flex-row items-center rounded-lg border border-rose-200 bg-white px-2 py-1 ${getRefundStyle(item.refundStatus).bg}`}>
<span className="mr-1.5 text-[12px]" style={{ color: getRefundStyle(item.refundStatus).color }}>
{getRefundStyle(item.refundStatus).icon}
</span>
<span
className={`text-[10px] font-bold uppercase ${getRefundStyle(item.refundStatus).text}`}
>
{item.refundStatus}
</span>
</span>
</div>
)}
</div>
)}
@ -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) } })

View file

@ -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.

View file

@ -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

View file

@ -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.

View file

@ -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) |

View file

@ -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.

View file

@ -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.

View file

@ -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.

View file

@ -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.

View file

@ -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`);

View file

@ -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,

View file

@ -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<boo
return !!existing
}
export async function generateCancellationCoupon(
orderId: number,
staffUserId: number,
userId: number,
orderAmount: number,
couponCode: string,
regionId: number
): Promise<Coupon> {
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<any | null> {
return await db.query.orders.findFirst({
where: and(

View file

@ -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<typeof orderStatus>
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<AdminOrderRow | null> {
@ -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<A
},
})
const filteredOrders = slotOrders.filter((order: any) => {
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<A
})),
}))
const paymentMode: 'COD' | 'Online' = order.isCod ? 'COD' : 'Online'
return {
id: order.id,
readableId: order.id,
@ -435,11 +374,6 @@ export async function getSlotOrders(regionId: number, slotId: string): Promise<A
status,
isPackaged: order.orderItems.every((item: any) => 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)))

View file

@ -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<unknown>('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<unknown>('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 }) => ({

View file

@ -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<voi
// 2. Delete complaints related to these orders
await tx.delete(complaints).where(inArray(complaints.orderId, chunk))
// 3. Delete refunds
await tx.delete(refunds).where(inArray(refunds.orderId, chunk))
// 4. Delete payments
await tx.delete(payments).where(inArray(payments.orderId, chunk))
// 5. Delete order status records
// 3. Delete order status records
await tx.delete(orderStatus).where(inArray(orderStatus.orderId, chunk))
// 6. Delete order items
// 4. Delete order items
await tx.delete(orderItems).where(inArray(orderItems.orderId, chunk))
// 7. Finally delete the orders themselves
// 5. Finally delete the orders themselves
await tx.delete(orders).where(inArray(orders.id, chunk))
})
}

View file

@ -28,19 +28,6 @@ export const redisUrl = process.env.REDIS_URL as string
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

View file

@ -13,8 +13,6 @@ import {
orderItems,
orderStatus,
orders,
payments,
refunds,
productReviews,
reservedCoupons,
} from '../db/schema'
@ -221,8 +219,6 @@ export async function deleteUserAccount(userId: number) {
for (const order of userOrders) {
await tx.delete(orderItems).where(eq(orderItems.orderId, order.id))
await tx.delete(orderStatus).where(eq(orderStatus.orderId, order.id))
await tx.delete(payments).where(eq(payments.orderId, order.id))
await tx.delete(refunds).where(eq(refunds.orderId, order.id))
await tx.delete(couponUsage).where(eq(couponUsage.orderId, order.id))
await tx.delete(complaints).where(eq(complaints.orderId, order.id))
}

View file

@ -6,11 +6,9 @@ import {
addresses,
productInfo,
productSkus,
paymentInfoTable,
coupons,
couponUsage,
cartItems,
refunds,
units,
userDetails,
deliverySlotInfo,
@ -41,8 +39,6 @@ export interface OrderWithRelations {
totalAmount: string
deliveryCharge: string
discountAmount: string
isCod: boolean
isOnlinePayment: boolean
isFlashDelivery: boolean
userNotes: string | null
orderGroupId: string | null
@ -71,21 +67,12 @@ export interface OrderWithRelations {
slot: {
deliveryTime: Date
} | null
paymentInfo: {
id: number
status: string
} | null
orderStatus: Array<{
id: number
isCancelled: boolean
isDelivered: boolean
paymentStatus: string
cancelReason: string | null
}>
refunds: Array<{
refundStatus: string
refundAmount: string | null
}>
}
export type OrderDetailWithRelations = OrderWithRelations;
@ -337,29 +324,14 @@ export async function placeOrderTransaction(params: {
orderItems: Omit<typeof orderItems.$inferInsert, 'id'>[]
orderStatus: Omit<typeof orderStatus.$inferInsert, 'id'>
}>
paymentMethod: 'online' | 'cod'
totalWithDelivery: number
}): Promise<PlacedOrder[]> {
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<typeof orders.$inferInsert, 'id'>[] =
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<void> {
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<OrderWithCancellationData | null>
}

View file

@ -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))
}

View file

@ -43,10 +43,6 @@ export type AdminOrderRow = Omit<PlacedOrder, 'orderGroupId' | 'orderGroupPropor
orderGroupProportion: string | null
}
export type PaymentStatus = 'pending' | 'success' | 'cod' | 'failed'
export type RefundStatus = 'success' | 'pending' | 'failed' | 'none' | 'na' | 'processed'
export interface AdminOrderStatusRecord {
id: number;
orderTime: Date;
@ -57,22 +53,10 @@ export interface AdminOrderStatusRecord {
isCancelled: boolean;
cancelReason: string | null;
isCancelledByAdmin: boolean | null;
paymentStatus: PaymentStatus;
cancellationUserNotes: string | null;
cancellationAdminNotes: string | null;
cancellationReviewed: boolean;
cancellationReviewedAt: Date | null;
refundCouponId: number | null;
}
export interface AdminRefundRecord {
id: number;
orderId: number;
refundAmount: string | null;
refundStatus: RefundStatus | null;
merchantRefundId: string | null;
refundProcessedAt: Date | null;
createdAt: Date;
}
export interface AdminOrderDetailsAddress {
@ -108,12 +92,6 @@ export interface AdminOrderDetailsItem extends AdminOrderItemCore {
unit?: string;
}
export interface AdminOrderDetailsPayment {
status: string;
gateway: string;
merchantOrderId: string;
}
export interface AdminOrderDetailsCouponData {
couponCode: string;
couponDescription: string;
@ -129,8 +107,6 @@ export interface AdminOrderDetails {
customerMobile: string | null;
address: AdminOrderDetailsAddress;
slotInfo: AdminOrderDetailsSlotInfo | null;
isCod: boolean;
isOnlinePayment: boolean;
totalAmount: number;
deliveryCharge: number;
adminNotes: string | null;
@ -140,19 +116,13 @@ export interface AdminOrderDetails {
isPackaged: boolean;
isDelivered: boolean;
items: AdminOrderDetailsItem[];
payment: AdminOrderDetailsPayment | null;
paymentInfo: AdminOrderDetailsPayment | null;
cancelReason: string | null;
cancellationReviewed: boolean;
isRefundDone: boolean;
refundStatus: RefundStatus | null;
refundAmount: number | null;
couponData: AdminOrderDetailsCouponData | null;
couponCode: string | null;
couponDescription: string | null;
discountAmount: number | null;
orderStatus: AdminOrderStatusRecord | null;
refundRecord: AdminRefundRecord | null;
isFlashDelivery: boolean;
}
@ -190,9 +160,6 @@ export interface AdminSlotOrder {
status: 'pending' | 'delivered' | 'cancelled';
isPackaged: boolean;
isDelivered: boolean;
isCod: boolean;
paymentMode: 'COD' | 'Online';
paymentStatus: PaymentStatus;
slotId: number | null;
adminNotes: string | null;
userNotes: string | null;
@ -227,7 +194,6 @@ export interface AdminOrderListItem {
status: 'pending' | 'delivered' | 'cancelled';
isPackaged: boolean;
isDelivered: boolean;
isCod: boolean;
isFlashDelivery: boolean;
userNotes: string | null;
adminNotes: string | null;

View file

@ -14,9 +14,6 @@ export interface PlacedOrder {
slotId: number | null
totalAmount: string
deliveryCharge: string
isCod: boolean
isOnlinePayment: boolean
paymentInfoId: number | null
readableId: number
userNotes: string | null
orderGroupId: string

View file

@ -116,15 +116,6 @@ export interface OrderItem {
is_package_verified: boolean;
}
export interface Payment {
id: number;
orderId: number;
paymentStatus: string;
paymentMethod: string;
amount: string;
createdAt: Date;
}
export interface UserBannersResponse {
banners: UserBanner[];
}
@ -350,15 +341,6 @@ export interface UserSlotsWithProductsResponse extends UserSlotsResponse {
productAvailability: UserSlotAvailability[];
}
export interface UserPaymentOrderResponse {
razorpayOrderId: string | number;
key: string | undefined;
}
export type UserPaymentVerifyResponse = MessageResponse
export type UserPaymentFailResponse = MessageResponse
export interface UserAuthProfile {
id: number;
name?: string | null;
@ -515,12 +497,8 @@ export interface UserOrderSummary {
deliveryDate?: string;
orderStatus: string;
cancelReason: string | null;
paymentMode: string;
totalAmount: number;
deliveryCharge: number;
paymentStatus: string;
refundStatus: string;
refundAmount: number | null;
userNotes: string | null;
items: UserOrderItemSummary[];
isFlashDelivery: boolean;

View file

@ -4,7 +4,6 @@ import { StorageService } from "./src/services/StorageService";
import {
ROLE_NAMES,
} from "./src/lib/constants";
import { REFUND_STATUS } from "./src/lib/const-strs";
import { colors, colorsType } from "./src/lib/theme-colors";
import { theme } from "./src/theme";
import MyButton from "./src/components/button";
@ -78,7 +77,6 @@ export {
useDrawerTitle,
useMarkDataFetchers,
StorageServiceCasual,
REFUND_STATUS,
DateTimePickerMod,
RefreshProvider,
useRefresh,

View file

@ -5,14 +5,6 @@ export const SESSION_EXPIRED_MSG = 'session_expired';
export const NOTIF_PERMISSION_DENIED = "Permission not granted to get push token for push notification!";
export const REFRESH_EVENT = 'refresh_event';
export const REFUND_STATUS = {
PENDING: 'pending',
NOT_APPLICABLE: 'na',
PROCESSING: 'initiated',
SUCCESS: 'success',
};
//copy pasted from backend
export const CAR_IMAGE_COMMENT = "car_body";