enh
This commit is contained in:
parent
f24d2edb6f
commit
79aa6dba71
81 changed files with 228 additions and 2002 deletions
|
|
@ -18,13 +18,7 @@ import { UserIncidentsView } from "@/components/UserIncidentsView";
|
||||||
export default function OrderDetails() {
|
export default function OrderDetails() {
|
||||||
const { id } = useLocalSearchParams<{ id: string }>();
|
const { id } = useLocalSearchParams<{ id: string }>();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [generateCouponDialogOpen, setGenerateCouponDialogOpen] =
|
|
||||||
useState(false);
|
|
||||||
const [initiateRefundDialogOpen, setInitiateRefundDialogOpen] =
|
|
||||||
useState(false);
|
|
||||||
const [cancelDialogOpen, setCancelDialogOpen] = 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 [updatingItems, setUpdatingItems] = useState<Set<number>>(new Set());
|
||||||
|
|
||||||
const {
|
const {
|
||||||
|
|
@ -37,45 +31,6 @@ export default function OrderDetails() {
|
||||||
{ enabled: !!id }
|
{ 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({
|
const updateItemPackagingMutation = trpc.admin.order.updateOrderItemPackaging.useMutation({
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
// Refetch order details to get updated packaging status
|
// 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 subtotal = order.items.reduce((sum, item) => sum + item.amount, 0);
|
||||||
const discountAmount = order.discountAmount || 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) => {
|
const handlePackagingToggle = (itemId: number, field: 'isPackaged' | 'isPackageVerified', value: boolean) => {
|
||||||
// Add item to updating set to disable UI
|
// Add item to updating set to disable UI
|
||||||
setUpdatingItems(prev => new Set(prev).add(itemId));
|
setUpdatingItems(prev => new Set(prev).add(itemId));
|
||||||
|
|
@ -199,30 +125,7 @@ export default function OrderDetails() {
|
||||||
};
|
};
|
||||||
|
|
||||||
const statusStyle = getStatusColor(order.status);
|
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 (
|
return (
|
||||||
<AppContainer>
|
<AppContainer>
|
||||||
|
|
||||||
|
|
@ -652,121 +555,6 @@ export default function OrderDetails() {
|
||||||
</View>
|
</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>
|
||||||
<View style={tw`h-32`}></View>
|
<View style={tw`h-32`}></View>
|
||||||
|
|
||||||
|
|
@ -795,163 +583,6 @@ export default function OrderDetails() {
|
||||||
</TouchableOpacity>
|
</TouchableOpacity>
|
||||||
</View>
|
</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'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 */}
|
{/* Cancel Order Dialog */}
|
||||||
<CancelOrderDialog
|
<CancelOrderDialog
|
||||||
orderId={order.id}
|
orderId={order.id}
|
||||||
|
|
|
||||||
|
|
@ -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)}`}>
|
{/* <View style={tw`px-2.5 py-1 rounded-full ${getStatusColor(order.status)}`}>
|
||||||
<MyText style={tw`text-xs font-semibold capitalize`}>{order.status}</MyText>
|
<MyText style={tw`text-xs font-semibold capitalize`}>{order.status}</MyText>
|
||||||
</View> */}
|
</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`}>
|
<View style={tw`flex-row items-center gap-1`}>
|
||||||
<MyText style={tw`text-sm font-semibold text-gray-600`}>Packaged</MyText>
|
<MyText style={tw`text-sm font-semibold text-gray-600`}>Packaged</MyText>
|
||||||
<Checkbox
|
<Checkbox
|
||||||
|
|
|
||||||
|
|
@ -59,7 +59,7 @@ export default function CancelOrderDialog({ orderId, open, onClose, onSuccess }:
|
||||||
Cancel Order
|
Cancel Order
|
||||||
</MyText>
|
</MyText>
|
||||||
<MyText style={tw`text-gray-500 text-center mt-2 text-sm leading-5`}>
|
<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>
|
</MyText>
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -51,9 +51,6 @@ const slotOrder = (overrides: Record<string, unknown> = {}) => ({
|
||||||
status: 'pending',
|
status: 'pending',
|
||||||
isPackaged: false,
|
isPackaged: false,
|
||||||
isDelivered: false,
|
isDelivered: false,
|
||||||
isCod: true,
|
|
||||||
paymentMode: 'COD',
|
|
||||||
paymentStatus: 'cod',
|
|
||||||
slotId: 3,
|
slotId: 3,
|
||||||
adminNotes: 'fragile',
|
adminNotes: 'fragile',
|
||||||
userNotes: null,
|
userNotes: null,
|
||||||
|
|
|
||||||
|
|
@ -51,7 +51,6 @@ const makeOrder = (overrides: Record<string, unknown> = {}) => ({
|
||||||
status: 'pending',
|
status: 'pending',
|
||||||
isPackaged: false,
|
isPackaged: false,
|
||||||
isDelivered: false,
|
isDelivered: false,
|
||||||
isCod: true,
|
|
||||||
isFlashDelivery: false,
|
isFlashDelivery: false,
|
||||||
userNotes: null,
|
userNotes: null,
|
||||||
adminNotes: 'call before delivery',
|
adminNotes: 'call before delivery',
|
||||||
|
|
|
||||||
|
|
@ -2,11 +2,6 @@
|
||||||
* Order details (app/(drawer)/dashboard/manage-orders/order-details/[id].tsx) —
|
* Order details (app/(drawer)/dashboard/manage-orders/order-details/[id].tsx) —
|
||||||
* detail rendering, packaging toggles, delivery-charge removal, cancellation
|
* detail rendering, packaging toggles, delivery-charge removal, cancellation
|
||||||
* and navigation.
|
* 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())
|
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||||
|
|
@ -38,8 +33,6 @@ const makeDetails = (overrides: Record<string, unknown> = {}) => ({
|
||||||
phone: '9876543210',
|
phone: '9876543210',
|
||||||
},
|
},
|
||||||
slotInfo: { time: '2026-01-02T10:00:00.000Z', sequence: null },
|
slotInfo: { time: '2026-01-02T10:00:00.000Z', sequence: null },
|
||||||
isCod: false,
|
|
||||||
isOnlinePayment: true,
|
|
||||||
totalAmount: 500,
|
totalAmount: 500,
|
||||||
deliveryCharge: 20,
|
deliveryCharge: 20,
|
||||||
adminNotes: 'handle with care',
|
adminNotes: 'handle with care',
|
||||||
|
|
@ -61,19 +54,13 @@ const makeDetails = (overrides: Record<string, unknown> = {}) => ({
|
||||||
unit: 'kg',
|
unit: 'kg',
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
payment: null,
|
|
||||||
paymentInfo: null,
|
|
||||||
cancelReason: null,
|
cancelReason: null,
|
||||||
cancellationReviewed: false,
|
cancellationReviewed: false,
|
||||||
isRefundDone: false,
|
|
||||||
refundStatus: null,
|
|
||||||
refundAmount: null,
|
|
||||||
couponData: null,
|
couponData: null,
|
||||||
couponCode: null,
|
couponCode: null,
|
||||||
couponDescription: null,
|
couponDescription: null,
|
||||||
discountAmount: 0,
|
discountAmount: 0,
|
||||||
orderStatus: null,
|
orderStatus: null,
|
||||||
refundRecord: null,
|
|
||||||
isFlashDelivery: false,
|
isFlashDelivery: false,
|
||||||
...overrides,
|
...overrides,
|
||||||
})
|
})
|
||||||
|
|
@ -228,35 +215,6 @@ describe('Order details', () => {
|
||||||
expect(screen.getAllByText('-₹50').length).toBeGreaterThan(0)
|
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 () => {
|
it('navigates to user management from customer details', async () => {
|
||||||
renderDetails()
|
renderDetails()
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -49,7 +49,7 @@ export default function CancelOrderDialog({ orderId, open, onClose, onSuccess }:
|
||||||
Cancel Order
|
Cancel Order
|
||||||
</P>
|
</P>
|
||||||
<P className="text-gray-500 text-center mt-2 text-sm leading-5">
|
<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>
|
</P>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -34,13 +34,7 @@ export const Route = createFileRoute('/dashboard/orders/$id')({
|
||||||
function OrderDetails() {
|
function OrderDetails() {
|
||||||
const { id } = Route.useParams()
|
const { id } = Route.useParams()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const [generateCouponDialogOpen, setGenerateCouponDialogOpen] =
|
|
||||||
useState(false)
|
|
||||||
const [initiateRefundDialogOpen, setInitiateRefundDialogOpen] =
|
|
||||||
useState(false)
|
|
||||||
const [cancelDialogOpen, setCancelDialogOpen] = 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 [updatingItems, setUpdatingItems] = useState<Set<number>>(new Set())
|
||||||
|
|
||||||
const {
|
const {
|
||||||
|
|
@ -53,40 +47,6 @@ function OrderDetails() {
|
||||||
{ enabled: !!id }
|
{ 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({
|
const updateItemPackagingMutation = trpc.admin.order.updateOrderItemPackaging.useMutation({
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
// Refetch order details to get updated packaging status
|
// 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 subtotal = order.items.reduce((sum, item) => sum + item.amount, 0)
|
||||||
const discountAmount = order.discountAmount || 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) => {
|
const handlePackagingToggle = (itemId: number, field: 'isPackaged' | 'isPackageVerified', value: boolean) => {
|
||||||
// Add item to updating set to disable UI
|
// Add item to updating set to disable UI
|
||||||
setUpdatingItems((prev) => new Set(prev).add(itemId))
|
setUpdatingItems((prev) => new Set(prev).add(itemId))
|
||||||
|
|
@ -600,38 +531,6 @@ function OrderDetails() {
|
||||||
</div>
|
</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>
|
||||||
<div className="h-32" />
|
<div className="h-32" />
|
||||||
|
|
||||||
|
|
@ -657,161 +556,6 @@ function OrderDetails() {
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</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'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 */}
|
{/* Cancel Order Dialog */}
|
||||||
<CancelOrderDialog
|
<CancelOrderDialog
|
||||||
orderId={order.id}
|
orderId={order.id}
|
||||||
|
|
|
||||||
|
|
@ -117,9 +117,6 @@ export type {
|
||||||
UserSlotsResponse,
|
UserSlotsResponse,
|
||||||
UserSlotsWithProductsResponse,
|
UserSlotsWithProductsResponse,
|
||||||
UserSlotsListResponse,
|
UserSlotsListResponse,
|
||||||
UserPaymentOrderResponse,
|
|
||||||
UserPaymentVerifyResponse,
|
|
||||||
UserPaymentFailResponse,
|
|
||||||
UserAuthProfile,
|
UserAuthProfile,
|
||||||
UserAuthResponse,
|
UserAuthResponse,
|
||||||
UserAuthResult,
|
UserAuthResult,
|
||||||
|
|
@ -157,5 +154,4 @@ export type {
|
||||||
CartItem,
|
CartItem,
|
||||||
Order,
|
Order,
|
||||||
OrderItem,
|
OrderItem,
|
||||||
Payment,
|
|
||||||
} from '@packages/shared';
|
} from '@packages/shared';
|
||||||
|
|
|
||||||
|
|
@ -1,16 +1,6 @@
|
||||||
import { checkPendingPayments, checkRefundStatuses } from '@/src/jobs/payment-status-checker'
|
|
||||||
|
|
||||||
const runCombinedJob = async () => {
|
const runCombinedJob = async () => {
|
||||||
const start = Date.now();
|
const start = Date.now();
|
||||||
try {
|
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');
|
console.log('Combined job completed successfully');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error in combined job:', error);
|
console.error('Error in combined job:', error);
|
||||||
|
|
|
||||||
|
|
@ -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);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
@ -33,19 +33,12 @@ import type { KVNamespace } from '@cloudflare/workers-types'
|
||||||
//
|
//
|
||||||
// export const expoAccessToken = process.env.EXPO_ACCESS_TOKEN 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;
|
// 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 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
|
export const getOtpSenderAuthToken = () => getRuntimeEnv().OTP_SENDER_AUTH_TOKEN as string
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -106,6 +106,7 @@ export async function readEssentialConstsFromKv(boundId: number): Promise<Essent
|
||||||
console.error('readEssentialConstsFromKv failed:', error)
|
console.error('readEssentialConstsFromKv failed:', error)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.log('building consts')
|
||||||
const payload = await buildEssentialConsts(boundId)
|
const payload = await buildEssentialConsts(boundId)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
|
||||||
|
|
@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -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'}
|
${orderData.orderItems?.map((item: any) => ` • ${item.sku?.product?.name || 'Unknown'} x${item.quantity}`).join('\n') || ' N/A'}
|
||||||
|
|
||||||
💰 <b>Total:</b> ₹${orderData.totalAmount}
|
💰 <b>Total:</b> ₹${orderData.totalAmount}
|
||||||
💳 <b>Refund:</b> ${orderData.refundStatus === 'na' ? 'N/A (COD)' : orderData.refundStatus || 'Pending'}
|
|
||||||
|
|
||||||
❓ <b>Reason:</b> ${cancellationData.reason}
|
❓ <b>Reason:</b> ${cancellationData.reason}
|
||||||
👤 <b>Cancelled by:</b> ${cancellationData.cancelledBy === 'admin' ? 'Admin' : 'User'}
|
👤 <b>Cancelled by:</b> ${cancellationData.cancelledBy === 'admin' ? 'Admin' : 'User'}
|
||||||
|
|
@ -145,10 +144,7 @@ export const handleOrderCancelled = async (
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const refundStatus = orderData.refunds?.[0]?.refundStatus || 'pending'
|
const telegramMessage = formatCancellationMessage(orderData, cancellationData)
|
||||||
|
|
||||||
|
|
||||||
const telegramMessage = formatCancellationMessage({ ...orderData, refundStatus }, cancellationData)
|
|
||||||
await sendTelegramMessage(telegramMessage)
|
await sendTelegramMessage(telegramMessage)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to process cancellation message:', error)
|
console.error('Failed to process cancellation message:', error)
|
||||||
|
|
|
||||||
|
|
@ -36,7 +36,6 @@ export {
|
||||||
getUsersForCoupon,
|
getUsersForCoupon,
|
||||||
createCouponWithRelations,
|
createCouponWithRelations,
|
||||||
updateCouponWithRelations,
|
updateCouponWithRelations,
|
||||||
generateCancellationCoupon,
|
|
||||||
createReservedCoupon,
|
createReservedCoupon,
|
||||||
createCouponForUser,
|
createCouponForUser,
|
||||||
checkUsersExist,
|
checkUsersExist,
|
||||||
|
|
@ -167,13 +166,6 @@ export {
|
||||||
// User - Slots
|
// User - Slots
|
||||||
getUserActiveSlotsList,
|
getUserActiveSlotsList,
|
||||||
getUserProductAvailability,
|
getUserProductAvailability,
|
||||||
// User - Payments
|
|
||||||
getUserPaymentOrderById,
|
|
||||||
getUserPaymentByOrderId,
|
|
||||||
getUserPaymentByMerchantOrderId,
|
|
||||||
updateUserPaymentSuccess,
|
|
||||||
updateUserOrderPaymentStatus,
|
|
||||||
markUserPaymentFailed,
|
|
||||||
// User - Auth
|
// User - Auth
|
||||||
getUserAuthByEmail,
|
getUserAuthByEmail,
|
||||||
getUserAuthByMobile,
|
getUserAuthByMobile,
|
||||||
|
|
|
||||||
|
|
@ -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 { productRouter } from '@/src/trpc/apis/admin-apis/apis/product'
|
||||||
import { staffUserRouter } from '@/src/trpc/apis/admin-apis/apis/staff-user'
|
import { staffUserRouter } from '@/src/trpc/apis/admin-apis/apis/staff-user'
|
||||||
import { storeRouter } from '@/src/trpc/apis/admin-apis/apis/store'
|
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 { bannerRouter } from '@/src/trpc/apis/admin-apis/apis/banner'
|
||||||
import { userRouter } from '@/src/trpc/apis/admin-apis/apis/user'
|
import { userRouter } from '@/src/trpc/apis/admin-apis/apis/user'
|
||||||
import { regionRouter } from '@/src/trpc/apis/admin-apis/apis/region'
|
import { regionRouter } from '@/src/trpc/apis/admin-apis/apis/region'
|
||||||
|
|
@ -22,7 +21,6 @@ export const adminRouter = router({
|
||||||
product: productRouter,
|
product: productRouter,
|
||||||
staffUser: staffUserRouter,
|
staffUser: staffUserRouter,
|
||||||
store: storeRouter,
|
store: storeRouter,
|
||||||
payments: adminPaymentsRouter,
|
|
||||||
banner: bannerRouter,
|
banner: bannerRouter,
|
||||||
user: userRouter,
|
user: userRouter,
|
||||||
region: regionRouter,
|
region: regionRouter,
|
||||||
|
|
|
||||||
|
|
@ -11,13 +11,11 @@ import {
|
||||||
// Batch 2 - Transaction methods
|
// Batch 2 - Transaction methods
|
||||||
createCouponWithRelations,
|
createCouponWithRelations,
|
||||||
updateCouponWithRelations,
|
updateCouponWithRelations,
|
||||||
generateCancellationCoupon,
|
|
||||||
createReservedCoupon,
|
createReservedCoupon,
|
||||||
createCouponForUser,
|
createCouponForUser,
|
||||||
checkUsersExist,
|
checkUsersExist,
|
||||||
checkCouponExists,
|
checkCouponExists,
|
||||||
checkReservedCouponExists,
|
checkReservedCouponExists,
|
||||||
getOrderWithUser,
|
|
||||||
} from '@/src/dbService'
|
} from '@/src/dbService'
|
||||||
import type { Coupon, CouponFormInput, UserMiniInfo } from '@packages/shared'
|
import type { Coupon, CouponFormInput, UserMiniInfo } from '@packages/shared'
|
||||||
|
|
||||||
|
|
@ -227,57 +225,6 @@ export const couponRouter = router({
|
||||||
return { message: "Coupon invalidated successfully" };
|
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
|
getReservedCoupons: protectedProcedure
|
||||||
.input(z.object({
|
.input(z.object({
|
||||||
cursor: z.number().optional(),
|
cursor: z.number().optional(),
|
||||||
|
|
|
||||||
|
|
@ -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> {
|
export async function deleteOrderById(regionId: number, orderId: number): Promise<boolean> {
|
||||||
return await deleteOrderByIdInDb(regionId, orderId)
|
return await deleteOrderByIdInDb(regionId, orderId)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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 {}
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
@ -52,7 +52,6 @@ const placeOrderUtil = async (params: {
|
||||||
slotId: number | null;
|
slotId: number | null;
|
||||||
}>;
|
}>;
|
||||||
addressId: number;
|
addressId: number;
|
||||||
paymentMethod: "online" | "cod";
|
|
||||||
couponIds?: number[];
|
couponIds?: number[];
|
||||||
userNotes?: string;
|
userNotes?: string;
|
||||||
isFlash?: boolean;
|
isFlash?: boolean;
|
||||||
|
|
@ -61,7 +60,6 @@ const placeOrderUtil = async (params: {
|
||||||
userId,
|
userId,
|
||||||
selectedItems,
|
selectedItems,
|
||||||
addressId,
|
addressId,
|
||||||
paymentMethod,
|
|
||||||
couponIds,
|
couponIds,
|
||||||
userNotes,
|
userNotes,
|
||||||
} = params;
|
} = params;
|
||||||
|
|
@ -296,9 +294,6 @@ const placeOrderUtil = async (params: {
|
||||||
regionId: regionId,
|
regionId: regionId,
|
||||||
addressId,
|
addressId,
|
||||||
slotId: params.isFlash ? null : slotId,
|
slotId: params.isFlash ? null : slotId,
|
||||||
isCod: paymentMethod === "cod",
|
|
||||||
isOnlinePayment: paymentMethod === "online",
|
|
||||||
paymentInfoId: null,
|
|
||||||
totalAmount: finalOrderAmount.toString(),
|
totalAmount: finalOrderAmount.toString(),
|
||||||
deliveryCharge: orderDelivery.toString(),
|
deliveryCharge: orderDelivery.toString(),
|
||||||
discountAmount: orderDiscount.toString(),
|
discountAmount: orderDiscount.toString(),
|
||||||
|
|
@ -333,7 +328,6 @@ const placeOrderUtil = async (params: {
|
||||||
const orderStatusData: Omit<typeof orderStatus.$inferInsert, "id"> = {
|
const orderStatusData: Omit<typeof orderStatus.$inferInsert, "id"> = {
|
||||||
userId,
|
userId,
|
||||||
orderId: 0,
|
orderId: 0,
|
||||||
paymentStatus: paymentMethod === "cod" ? "cod" : "pending",
|
|
||||||
};
|
};
|
||||||
|
|
||||||
ordersData.push({ order, orderItems: orderItemsData, orderStatus: orderStatusData });
|
ordersData.push({ order, orderItems: orderItemsData, orderStatus: orderStatusData });
|
||||||
|
|
@ -343,7 +337,6 @@ const placeOrderUtil = async (params: {
|
||||||
const createdOrders = await placeUserOrderTransaction({
|
const createdOrders = await placeUserOrderTransaction({
|
||||||
userId,
|
userId,
|
||||||
ordersData,
|
ordersData,
|
||||||
paymentMethod,
|
|
||||||
totalWithDelivery,
|
totalWithDelivery,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -386,7 +379,6 @@ export const orderRouter = router({
|
||||||
addressId: z.number().int().positive(),
|
addressId: z.number().int().positive(),
|
||||||
regionId: z.number().int().positive(),
|
regionId: z.number().int().positive(),
|
||||||
boundId: z.number().int().positive().optional(),
|
boundId: z.number().int().positive().optional(),
|
||||||
paymentMethod: z.enum(["online", "cod"]),
|
|
||||||
couponIds: z.array(z.number().int().positive()).optional(),
|
couponIds: z.array(z.number().int().positive()).optional(),
|
||||||
userNotes: z.string().optional(),
|
userNotes: z.string().optional(),
|
||||||
isFlashDelivery: z.boolean().optional().default(false),
|
isFlashDelivery: z.boolean().optional().default(false),
|
||||||
|
|
@ -405,7 +397,6 @@ export const orderRouter = router({
|
||||||
addressId,
|
addressId,
|
||||||
regionId,
|
regionId,
|
||||||
boundId,
|
boundId,
|
||||||
paymentMethod,
|
|
||||||
couponIds,
|
couponIds,
|
||||||
userNotes,
|
userNotes,
|
||||||
isFlashDelivery,
|
isFlashDelivery,
|
||||||
|
|
@ -439,7 +430,6 @@ export const orderRouter = router({
|
||||||
boundId,
|
boundId,
|
||||||
selectedItems: processedItems,
|
selectedItems: processedItems,
|
||||||
addressId,
|
addressId,
|
||||||
paymentMethod,
|
|
||||||
couponIds,
|
couponIds,
|
||||||
userNotes,
|
userNotes,
|
||||||
isFlash: isFlashDelivery,
|
isFlash: isFlashDelivery,
|
||||||
|
|
@ -466,7 +456,6 @@ export const orderRouter = router({
|
||||||
const mappedOrders = await Promise.all(
|
const mappedOrders = await Promise.all(
|
||||||
userOrders.map(async (order) => {
|
userOrders.map(async (order) => {
|
||||||
const status = order.orderStatus[0];
|
const status = order.orderStatus[0];
|
||||||
const refund = order.refunds[0];
|
|
||||||
|
|
||||||
let deliveryStatus: DeliveryStatus;
|
let deliveryStatus: DeliveryStatus;
|
||||||
let orderStatus: OrderStatus;
|
let orderStatus: OrderStatus;
|
||||||
|
|
@ -489,13 +478,6 @@ export const orderRouter = router({
|
||||||
orderStatus = "success";
|
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(
|
const items = await Promise.all(
|
||||||
order.orderItems.map(async (item) => {
|
order.orderItems.map(async (item) => {
|
||||||
const signedImages = item.sku?.images
|
const signedImages = item.sku?.images
|
||||||
|
|
@ -527,12 +509,8 @@ export const orderRouter = router({
|
||||||
deliveryDate: order.slot?.deliveryTime.toISOString(),
|
deliveryDate: order.slot?.deliveryTime.toISOString(),
|
||||||
orderStatus,
|
orderStatus,
|
||||||
cancelReason: status?.cancelReason || null,
|
cancelReason: status?.cancelReason || null,
|
||||||
paymentMode,
|
|
||||||
totalAmount: Number(order.totalAmount),
|
totalAmount: Number(order.totalAmount),
|
||||||
deliveryCharge: Number(order.deliveryCharge),
|
deliveryCharge: Number(order.deliveryCharge),
|
||||||
paymentStatus,
|
|
||||||
refundStatus,
|
|
||||||
refundAmount,
|
|
||||||
userNotes: order.userNotes || null,
|
userNotes: order.userNotes || null,
|
||||||
items,
|
items,
|
||||||
isFlashDelivery: order.isFlashDelivery,
|
isFlashDelivery: order.isFlashDelivery,
|
||||||
|
|
@ -583,7 +561,6 @@ export const orderRouter = router({
|
||||||
}
|
}
|
||||||
|
|
||||||
const status = order.orderStatus[0];
|
const status = order.orderStatus[0];
|
||||||
const refund = order.refunds[0];
|
|
||||||
|
|
||||||
let deliveryStatus: DeliveryStatus;
|
let deliveryStatus: DeliveryStatus;
|
||||||
let orderStatusResult: OrderStatus;
|
let orderStatusResult: OrderStatus;
|
||||||
|
|
@ -606,13 +583,6 @@ export const orderRouter = router({
|
||||||
orderStatusResult = "success";
|
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(
|
const items = await Promise.all(
|
||||||
order.orderItems.map(async (item) => {
|
order.orderItems.map(async (item) => {
|
||||||
const signedImages = item.sku?.images
|
const signedImages = item.sku?.images
|
||||||
|
|
@ -645,10 +615,6 @@ export const orderRouter = router({
|
||||||
orderStatus: orderStatusResult,
|
orderStatus: orderStatusResult,
|
||||||
cancellationStatus: orderStatusResult,
|
cancellationStatus: orderStatusResult,
|
||||||
cancelReason: status?.cancelReason || null,
|
cancelReason: status?.cancelReason || null,
|
||||||
paymentMode,
|
|
||||||
paymentStatus,
|
|
||||||
refundStatus,
|
|
||||||
refundAmount,
|
|
||||||
userNotes: order.userNotes || null,
|
userNotes: order.userNotes || null,
|
||||||
items,
|
items,
|
||||||
couponCode: couponData?.couponCode || null,
|
couponCode: couponData?.couponCode || null,
|
||||||
|
|
@ -709,7 +675,7 @@ export const orderRouter = router({
|
||||||
throw new ApiError("Cannot cancel delivered order", 400);
|
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);
|
await clearFirstOrderIfMatches(userId, id);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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",
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
@ -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 { slotsRouter } from '@/src/trpc/apis/user-apis/apis/slots';
|
||||||
import { userRouter as userDataRouter } from '@/src/trpc/apis/user-apis/apis/user';
|
import { userRouter as userDataRouter } from '@/src/trpc/apis/user-apis/apis/user';
|
||||||
import { userCouponRouter } from '@/src/trpc/apis/user-apis/apis/coupon';
|
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';
|
import { fileUploadRouter } from '@/src/trpc/apis/user-apis/apis/file-upload';
|
||||||
|
|
||||||
export const userRouter = router({
|
export const userRouter = router({
|
||||||
|
|
@ -21,7 +20,6 @@ export const userRouter = router({
|
||||||
slots: slotsRouter,
|
slots: slotsRouter,
|
||||||
user: userDataRouter,
|
user: userDataRouter,
|
||||||
coupon: userCouponRouter,
|
coupon: userCouponRouter,
|
||||||
payment: paymentRouter,
|
|
||||||
fileUpload: fileUploadRouter,
|
fileUpload: fileUploadRouter,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -541,6 +541,5 @@ deprecated/out of scope.
|
||||||
|
|
||||||
## Out of scope (per request)
|
## Out of scope (per request)
|
||||||
|
|
||||||
Online payments (`user.payment.*`, `admin.payments.initiateRefund`), OTP
|
OTP (`sendOtp`/`verifyOtp`) and `deleteAccount` are deliberately untested and not
|
||||||
(`sendOtp`/`verifyOtp`) and `deleteAccount` are deliberately untested and not
|
listed here. Online payments were removed from the product (COD-only).
|
||||||
listed here.
|
|
||||||
|
|
|
||||||
|
|
@ -121,13 +121,11 @@ describe('admin ops', () => {
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId: slotA.slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId: slotA.slotId }],
|
||||||
addressId: address.addressId,
|
addressId: address.addressId,
|
||||||
regionId: 1,
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
|
||||||
}),
|
}),
|
||||||
user.user.order.placeOrder.mutate({
|
user.user.order.placeOrder.mutate({
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId: slotB.slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId: slotB.slotId }],
|
||||||
addressId: address.addressId,
|
addressId: address.addressId,
|
||||||
regionId: 1,
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
|
||||||
}),
|
}),
|
||||||
])
|
])
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -35,7 +35,6 @@ describe('admin order operations', () => {
|
||||||
const placed = await user.user.order.placeOrder.mutate({
|
const placed = await user.user.order.placeOrder.mutate({
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId,
|
addressId,
|
||||||
paymentMethod: 'cod',
|
|
||||||
})
|
})
|
||||||
orderId = placed.data[0].id
|
orderId = placed.data[0].id
|
||||||
})
|
})
|
||||||
|
|
@ -117,7 +116,6 @@ describe('admin order operations', () => {
|
||||||
const placed = await user.user.order.placeOrder.mutate({
|
const placed = await user.user.order.placeOrder.mutate({
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId,
|
addressId,
|
||||||
paymentMethod: 'cod',
|
|
||||||
})
|
})
|
||||||
const freshOrderId = placed.data[0].id
|
const freshOrderId = placed.data[0].id
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -45,7 +45,6 @@ describe('authorization matrix', () => {
|
||||||
const placed = await apiClient(userToken).user.order.placeOrder.mutate({
|
const placed = await apiClient(userToken).user.order.placeOrder.mutate({
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId,
|
addressId,
|
||||||
paymentMethod: 'cod',
|
|
||||||
})
|
})
|
||||||
orderId = placed.data[0].id
|
orderId = placed.data[0].id
|
||||||
})
|
})
|
||||||
|
|
@ -207,7 +206,6 @@ describe('authorization matrix', () => {
|
||||||
apiClient(staff.token).user.order.placeOrder.mutate({
|
apiClient(staff.token).user.order.placeOrder.mutate({
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId,
|
addressId,
|
||||||
paymentMethod: 'cod',
|
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
expect(error).toBeInstanceOf(Error)
|
expect(error).toBeInstanceOf(Error)
|
||||||
|
|
@ -245,7 +243,6 @@ describe('authorization matrix', () => {
|
||||||
const placed = await apiClient(fresh.token).user.order.placeOrder.mutate({
|
const placed = await apiClient(fresh.token).user.order.placeOrder.mutate({
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId: fresh.addressId,
|
addressId: fresh.addressId,
|
||||||
paymentMethod: 'cod',
|
|
||||||
})
|
})
|
||||||
|
|
||||||
const error = await captureError(() =>
|
const error = await captureError(() =>
|
||||||
|
|
|
||||||
|
|
@ -95,7 +95,6 @@ describe('coupon discount maths', () => {
|
||||||
selectedItems: items,
|
selectedItems: items,
|
||||||
addressId,
|
addressId,
|
||||||
regionId: 1,
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
|
||||||
...(couponId != null
|
...(couponId != null
|
||||||
? { couponIds: Array.isArray(couponId) ? couponId : [couponId] }
|
? { couponIds: Array.isArray(couponId) ? couponId : [couponId] }
|
||||||
: {}),
|
: {}),
|
||||||
|
|
|
||||||
|
|
@ -72,7 +72,6 @@ describe('coupon UX', () => {
|
||||||
selectedItems: [{ skuId, quantity, slotId }],
|
selectedItems: [{ skuId, quantity, slotId }],
|
||||||
addressId: user.addressId,
|
addressId: user.addressId,
|
||||||
regionId: 1,
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
|
||||||
...(couponId ? { couponIds: [couponId] } : {}),
|
...(couponId ? { couponIds: [couponId] } : {}),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -81,7 +81,6 @@ describe('coupon CRUD + apply', () => {
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId,
|
addressId,
|
||||||
regionId: 1,
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
|
||||||
couponIds: [couponId],
|
couponIds: [couponId],
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -105,7 +104,6 @@ describe('coupon CRUD + apply', () => {
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId,
|
addressId,
|
||||||
regionId: 1,
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
|
||||||
couponIds: [couponId],
|
couponIds: [couponId],
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -69,7 +69,6 @@ describe('misc procedures', () => {
|
||||||
selectedItems: [{ skuId: store.skuId, quantity: 1, slotId: slot.slotId }],
|
selectedItems: [{ skuId: store.skuId, quantity: 1, slotId: slot.slotId }],
|
||||||
addressId: orderAddressId,
|
addressId: orderAddressId,
|
||||||
regionId: 1,
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
|
||||||
})
|
})
|
||||||
|
|
||||||
const error = await captureError(() =>
|
const error = await captureError(() =>
|
||||||
|
|
|
||||||
|
|
@ -44,7 +44,6 @@ describe('placeOrder guards', () => {
|
||||||
apiClient().user.order.placeOrder.mutate({
|
apiClient().user.order.placeOrder.mutate({
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId,
|
addressId,
|
||||||
paymentMethod: 'cod',
|
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -56,7 +55,6 @@ describe('placeOrder guards', () => {
|
||||||
apiClient(userToken).user.order.placeOrder.mutate({
|
apiClient(userToken).user.order.placeOrder.mutate({
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId: 99_999_999,
|
addressId: 99_999_999,
|
||||||
paymentMethod: 'cod',
|
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -68,7 +66,6 @@ describe('placeOrder guards', () => {
|
||||||
apiClient(userToken).user.order.placeOrder.mutate({
|
apiClient(userToken).user.order.placeOrder.mutate({
|
||||||
selectedItems: [{ skuId: 99_999_999, quantity: 1, slotId }],
|
selectedItems: [{ skuId: 99_999_999, quantity: 1, slotId }],
|
||||||
addressId,
|
addressId,
|
||||||
paymentMethod: 'cod',
|
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -84,7 +81,6 @@ describe('placeOrder guards', () => {
|
||||||
const res = await apiClient(userToken).user.order.placeOrder.mutate({
|
const res = await apiClient(userToken).user.order.placeOrder.mutate({
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId: bogusSlotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId: bogusSlotId }],
|
||||||
addressId,
|
addressId,
|
||||||
paymentMethod: 'cod',
|
|
||||||
})
|
})
|
||||||
|
|
||||||
expect(res.success).toBe(true)
|
expect(res.success).toBe(true)
|
||||||
|
|
|
||||||
|
|
@ -38,7 +38,6 @@ describe('order flow: create an order, then read it back', () => {
|
||||||
const res = await apiClient(userToken).user.order.placeOrder.mutate({
|
const res = await apiClient(userToken).user.order.placeOrder.mutate({
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId,
|
addressId,
|
||||||
paymentMethod: 'cod',
|
|
||||||
})
|
})
|
||||||
|
|
||||||
expect(res.success).toBe(true)
|
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)
|
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')
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
/**
|
/**
|
||||||
* Order lifecycle gaps: coupon-usage rollback, first-order-only poisoning,
|
* Order lifecycle gaps: coupon-usage rollback, first-order-only poisoning,
|
||||||
* refund rows, cancel error swallowing and the (missing) status transition
|
* cancel error swallowing and the (missing) status transition guards.
|
||||||
* guards.
|
|
||||||
*
|
*
|
||||||
* Known bugs are pinned — see tests/BUGS.md.
|
* Known bugs are pinned — see tests/BUGS.md.
|
||||||
*/
|
*/
|
||||||
|
|
@ -43,7 +42,6 @@ describe('order lifecycle gaps', () => {
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId,
|
addressId,
|
||||||
regionId: 1,
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
|
||||||
...(couponId ? { couponIds: [couponId] } : {}),
|
...(couponId ? { couponIds: [couponId] } : {}),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -82,7 +80,6 @@ describe('order lifecycle gaps', () => {
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId: buyer.addressId,
|
addressId: buyer.addressId,
|
||||||
regionId: 1,
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
|
||||||
})
|
})
|
||||||
await apiClient(buyer.token).user.order.cancelOrder.mutate({
|
await apiClient(buyer.token).user.order.cancelOrder.mutate({
|
||||||
id: first.data[0].id,
|
id: first.data[0].id,
|
||||||
|
|
@ -95,7 +92,6 @@ describe('order lifecycle gaps', () => {
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId: buyer.addressId,
|
addressId: buyer.addressId,
|
||||||
regionId: 1,
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
|
||||||
couponIds: [coupon.id],
|
couponIds: [coupon.id],
|
||||||
})
|
})
|
||||||
expect(res.success).toBe(true)
|
expect(res.success).toBe(true)
|
||||||
|
|
@ -113,7 +109,6 @@ describe('order lifecycle gaps', () => {
|
||||||
],
|
],
|
||||||
addressId: buyer.addressId,
|
addressId: buyer.addressId,
|
||||||
regionId: 1,
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
|
||||||
couponIds: [coupon.id],
|
couponIds: [coupon.id],
|
||||||
})
|
})
|
||||||
expect(placed.data).toHaveLength(2)
|
expect(placed.data).toHaveLength(2)
|
||||||
|
|
@ -123,7 +118,6 @@ describe('order lifecycle gaps', () => {
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId: buyer.addressId,
|
addressId: buyer.addressId,
|
||||||
regionId: 1,
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
|
||||||
couponIds: [coupon.id],
|
couponIds: [coupon.id],
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -151,26 +145,12 @@ describe('order lifecycle gaps', () => {
|
||||||
const res = await apiClient(buyer.token).user.order.placeOrder.mutate({
|
const res = await apiClient(buyer.token).user.order.placeOrder.mutate({
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId: buyer.addressId,
|
addressId: buyer.addressId,
|
||||||
paymentMethod: 'cod',
|
|
||||||
couponIds: [coupon.id],
|
couponIds: [coupon.id],
|
||||||
})
|
})
|
||||||
|
|
||||||
expect(res.success).toBe(true)
|
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 () => {
|
it('pins: cancelling an already-cancelled order reports a generic message', async () => {
|
||||||
const placed = await place()
|
const placed = await place()
|
||||||
const orderId = placed.data[0].id
|
const orderId = placed.data[0].id
|
||||||
|
|
|
||||||
|
|
@ -27,7 +27,6 @@ describe('order lifecycle', () => {
|
||||||
const res = await apiClient(token).user.order.placeOrder.mutate({
|
const res = await apiClient(token).user.order.placeOrder.mutate({
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId,
|
addressId,
|
||||||
paymentMethod: 'cod',
|
|
||||||
})
|
})
|
||||||
orderId = res.data[0].id
|
orderId = res.data[0].id
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -49,7 +49,6 @@ describe('order rules', () => {
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId,
|
addressId,
|
||||||
regionId: 1,
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
|
||||||
})
|
})
|
||||||
|
|
||||||
expect(res.data[0].deliveryCharge).toBe(String(charge))
|
expect(res.data[0].deliveryCharge).toBe(String(charge))
|
||||||
|
|
@ -62,7 +61,6 @@ describe('order rules', () => {
|
||||||
selectedItems: [{ skuId, quantity, slotId }],
|
selectedItems: [{ skuId, quantity, slotId }],
|
||||||
addressId,
|
addressId,
|
||||||
regionId: 1,
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
|
||||||
})
|
})
|
||||||
|
|
||||||
expect(res.data[0].deliveryCharge).toBe('0')
|
expect(res.data[0].deliveryCharge).toBe('0')
|
||||||
|
|
@ -76,7 +74,6 @@ describe('order rules', () => {
|
||||||
],
|
],
|
||||||
addressId,
|
addressId,
|
||||||
regionId: 1,
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
|
||||||
})
|
})
|
||||||
|
|
||||||
expect(res.data).toHaveLength(2)
|
expect(res.data).toHaveLength(2)
|
||||||
|
|
@ -101,7 +98,6 @@ describe('order rules', () => {
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId,
|
addressId,
|
||||||
regionId: 1,
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
expect(error.message).toMatch(/capacity/i)
|
expect(error.message).toMatch(/capacity/i)
|
||||||
|
|
@ -124,7 +120,6 @@ describe('order rules', () => {
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId: null }],
|
selectedItems: [{ skuId, quantity: 1, slotId: null }],
|
||||||
addressId,
|
addressId,
|
||||||
regionId: 1,
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
|
||||||
isFlashDelivery: true,
|
isFlashDelivery: true,
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
|
|
@ -140,7 +135,6 @@ describe('order rules', () => {
|
||||||
selectedItems: [{ skuId, quantity: 0, slotId }],
|
selectedItems: [{ skuId, quantity: 0, slotId }],
|
||||||
addressId,
|
addressId,
|
||||||
regionId: 1,
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -60,7 +60,6 @@ describe('placeOrder edge cases', () => {
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId,
|
addressId,
|
||||||
regionId: 1,
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
|
||||||
...over,
|
...over,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -70,11 +70,6 @@ NOTIF_QUEUE_NAME = "notif-queue-dev"
|
||||||
ORDER_PLACED_QUEUE_NAME = "order-placed-queue-dev"
|
ORDER_PLACED_QUEUE_NAME = "order-placed-queue-dev"
|
||||||
ORDER_CANCELLED_QUEUE_NAME = "order-cancelled-queue-dev"
|
ORDER_CANCELLED_QUEUE_NAME = "order-cancelled-queue-dev"
|
||||||
DATABASE_URL = "postgresql://postgres:meatfarmer_master_password@57.128.212.174:7447/meatfarmer"
|
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_REGION = "apac"
|
||||||
S3_ACCESS_KEY_ID = "8fab47503efb9547b50e4fb317e35cc7"
|
S3_ACCESS_KEY_ID = "8fab47503efb9547b50e4fb317e35cc7"
|
||||||
S3_SECRET_ACCESS_KEY = "47c2eb5636843cf568dda7ad0959a3e42071303f26dbdff94bd45a3c33dcd950"
|
S3_SECRET_ACCESS_KEY = "47c2eb5636843cf568dda7ad0959a3e42071303f26dbdff94bd45a3c33dcd950"
|
||||||
|
|
@ -88,8 +83,6 @@ CLOUDFLARE_API_TOKEN = "N7jAg5X-RUj_fVfMW6zbfJ8qIYc81TSIKKlbZ6oh"
|
||||||
CLOUDFLARE_ZONE_ID = "edefbf750bfc3ff26ccd11e8e28dc8d7"
|
CLOUDFLARE_ZONE_ID = "edefbf750bfc3ff26ccd11e8e28dc8d7"
|
||||||
REDIS_URL = "redis://default:redis_shafi_password@57.128.212.174:6379"
|
REDIS_URL = "redis://default:redis_shafi_password@57.128.212.174:6379"
|
||||||
APP_URL = "https://ui.freshyo.in"
|
APP_URL = "https://ui.freshyo.in"
|
||||||
RAZORPAY_KEY = "rzp_test_RdCBBUJ56NLaJK"
|
|
||||||
RAZORPAY_SECRET = "namEwKBE1ypWxH0QDVg6fWOe"
|
|
||||||
OTP_SENDER_AUTH_TOKEN = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJDLTM5OENEMkJDRTM0MjQ4OCIsImlhdCI6MTc0Nzg0MTEwMywiZXhwIjoxOTA1NTIxMTAzfQ.IV64ofVKjcwveIanxu_P2XlACtPeA9sJQ74uM53osDeyUXsFv0rwkCl6NNBIX93s_wnh4MKITLbcF_ClwmFQ0A"
|
OTP_SENDER_AUTH_TOKEN = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJDLTM5OENEMkJDRTM0MjQ4OCIsImlhdCI6MTc0Nzg0MTEwMywiZXhwIjoxOTA1NTIxMTAzfQ.IV64ofVKjcwveIanxu_P2XlACtPeA9sJQ74uM53osDeyUXsFv0rwkCl6NNBIX93s_wnh4MKITLbcF_ClwmFQ0A"
|
||||||
MIN_ORDER_VALUE = "300"
|
MIN_ORDER_VALUE = "300"
|
||||||
DELIVERY_CHARGE = "20"
|
DELIVERY_CHARGE = "20"
|
||||||
|
|
|
||||||
|
|
@ -65,11 +65,6 @@ NOTIF_QUEUE_NAME = "notif-queue"
|
||||||
ORDER_PLACED_QUEUE_NAME = "order-placed-queue"
|
ORDER_PLACED_QUEUE_NAME = "order-placed-queue"
|
||||||
ORDER_CANCELLED_QUEUE_NAME = "order-cancelled-queue"
|
ORDER_CANCELLED_QUEUE_NAME = "order-cancelled-queue"
|
||||||
DATABASE_URL = "postgresql://postgres:meatfarmer_master_password@57.128.212.174:7447/meatfarmer"
|
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_REGION = "apac"
|
||||||
S3_ACCESS_KEY_ID = "8fab47503efb9547b50e4fb317e35cc7"
|
S3_ACCESS_KEY_ID = "8fab47503efb9547b50e4fb317e35cc7"
|
||||||
S3_SECRET_ACCESS_KEY = "47c2eb5636843cf568dda7ad0959a3e42071303f26dbdff94bd45a3c33dcd950"
|
S3_SECRET_ACCESS_KEY = "47c2eb5636843cf568dda7ad0959a3e42071303f26dbdff94bd45a3c33dcd950"
|
||||||
|
|
@ -83,8 +78,6 @@ CLOUDFLARE_API_TOKEN = "N7jAg5X-RUj_fVfMW6zbfJ8qIYc81TSIKKlbZ6oh"
|
||||||
CLOUDFLARE_ZONE_ID = "edefbf750bfc3ff26ccd11e8e28dc8d7"
|
CLOUDFLARE_ZONE_ID = "edefbf750bfc3ff26ccd11e8e28dc8d7"
|
||||||
REDIS_URL = "redis://default:redis_shafi_password@57.128.212.174:6379"
|
REDIS_URL = "redis://default:redis_shafi_password@57.128.212.174:6379"
|
||||||
APP_URL = "https://ui.freshyo.in"
|
APP_URL = "https://ui.freshyo.in"
|
||||||
RAZORPAY_KEY = "rzp_test_RdCBBUJ56NLaJK"
|
|
||||||
RAZORPAY_SECRET = "namEwKBE1ypWxH0QDVg6fWOe"
|
|
||||||
OTP_SENDER_AUTH_TOKEN = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJDLTM5OENEMkJDRTM0MjQ4OCIsImlhdCI6MTc0Nzg0MTEwMywiZXhwIjoxOTA1NTIxMTAzfQ.IV64ofVKjcwveIanxu_P2XlACtPeA9sJQ74uM53osDeyUXsFv0rwkCl6NNBIX93s_wnh4MKITLbcF_ClwmFQ0A"
|
OTP_SENDER_AUTH_TOKEN = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJDLTM5OENEMkJDRTM0MjQ4OCIsImlhdCI6MTc0Nzg0MTEwMywiZXhwIjoxOTA1NTIxMTAzfQ.IV64ofVKjcwveIanxu_P2XlACtPeA9sJQ74uM53osDeyUXsFv0rwkCl6NNBIX93s_wnh4MKITLbcF_ClwmFQ0A"
|
||||||
MIN_ORDER_VALUE = "300"
|
MIN_ORDER_VALUE = "300"
|
||||||
DELIVERY_CHARGE = "20"
|
DELIVERY_CHARGE = "20"
|
||||||
|
|
|
||||||
|
|
@ -191,24 +191,6 @@ export default function OrderDetails() {
|
||||||
|
|
||||||
{/* Main Info Card */}
|
{/* Main Info Card */}
|
||||||
<View style={tw`bg-white rounded-2xl p-5 mb-4 border border-slate-100`}>
|
<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() || "") && (
|
{(order.deliveryDate || order.isFlashDelivery) && ["delivered", "success"].includes(order.deliveryStatus?.toLowerCase() || "") && (
|
||||||
<View style={tw`flex-row items-center pt-4 border-t border-slate-50`}>
|
<View style={tw`flex-row items-center pt-4 border-t border-slate-50`}>
|
||||||
{order.isFlashDelivery ? (
|
{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`}>
|
<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-700 text-[10px] font-bold uppercase mb-2`}>Cancellation Reason</MyText>
|
||||||
<MyText style={tw`text-rose-900 text-sm font-medium`}>{order.cancelReason}</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>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@ import { View, FlatList, Alert, ActivityIndicator } from 'react-native';
|
||||||
import { Image } from 'expo-image';
|
import { Image } from 'expo-image';
|
||||||
import { MaterialIcons, Ionicons } from '@expo/vector-icons';
|
import { MaterialIcons, Ionicons } from '@expo/vector-icons';
|
||||||
import { useRouter } from 'expo-router';
|
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 { trpc } from '@/src/trpc-client';
|
||||||
import { orderStatusManipulator } from '@/src/lib/string-manipulators';
|
import { orderStatusManipulator } from '@/src/lib/string-manipulators';
|
||||||
|
|
@ -66,11 +66,8 @@ interface OrderItemProps {
|
||||||
item: Order;
|
item: Order;
|
||||||
index: number;
|
index: number;
|
||||||
getStatusColor: (status: string) => any;
|
getStatusColor: (status: string) => any;
|
||||||
getRefundStatusColor: (status: string) => any;
|
|
||||||
onPress: (orderId: number) => void;
|
onPress: (orderId: number) => void;
|
||||||
onRetryPayment: (orderId: number) => void;
|
|
||||||
onViewMoreItems: (orderId: number) => void;
|
onViewMoreItems: (orderId: number) => void;
|
||||||
isPaymentPending: boolean;
|
|
||||||
refetch: () => void;
|
refetch: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -78,11 +75,8 @@ const OrderItem: React.FC<OrderItemProps> = ({
|
||||||
item,
|
item,
|
||||||
index,
|
index,
|
||||||
getStatusColor,
|
getStatusColor,
|
||||||
getRefundStatusColor,
|
|
||||||
onPress,
|
onPress,
|
||||||
onRetryPayment,
|
|
||||||
onViewMoreItems,
|
onViewMoreItems,
|
||||||
isPaymentPending,
|
|
||||||
refetch
|
refetch
|
||||||
}) => {
|
}) => {
|
||||||
const mainStatus = getStatusColor(item.orderStatus);
|
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>
|
<MyText style={tw`text-xs text-rose-800 font-bold ml-2`}>Cancellation Details</MyText>
|
||||||
</View>
|
</View>
|
||||||
<MyText style={tw`text-xs text-rose-600 font-medium leading-relaxed`}>{item.cancelReason}</MyText>
|
<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>
|
</View>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|
@ -313,30 +291,10 @@ const OrderItem: React.FC<OrderItemProps> = ({
|
||||||
)}
|
)}
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
{(item.paymentMode === 'Online' && (item.paymentStatus === 'pending' || item.paymentStatus === 'failed')) ? (
|
<View style={tw`bg-brand600 px-5 py-3 rounded-2xl shadow-lg shadow-brand100 flex-row items-center`}>
|
||||||
<MyTouchableOpacity
|
<MyText style={tw`text-white font-bold text-sm mr-1`}>View Details</MyText>
|
||||||
onPress={(e) => {
|
<MaterialIcons name="arrow-forward" size={16} color="white" />
|
||||||
e.stopPropagation();
|
</View>
|
||||||
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>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
</MyTouchableOpacity>
|
</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
|
// Handle data accumulation for infinite scroll
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (ordersData?.data) {
|
if (ordersData?.data) {
|
||||||
|
|
@ -439,7 +372,6 @@ export default function MyOrders() {
|
||||||
|
|
||||||
const [dialogOpen, setDialogOpen] = useState<boolean>(false);
|
const [dialogOpen, setDialogOpen] = useState<boolean>(false);
|
||||||
const [dialogItems, setDialogItems] = useState<OrderItem[]>([]);
|
const [dialogItems, setDialogItems] = useState<OrderItem[]>([]);
|
||||||
const [retryOrderId, setRetryOrderId] = useState<number>(0);
|
|
||||||
|
|
||||||
const openDialog = useCallback((items: OrderItem[]) => {
|
const openDialog = useCallback((items: OrderItem[]) => {
|
||||||
setDialogItems(items);
|
setDialogItems(items);
|
||||||
|
|
@ -481,7 +413,6 @@ export default function MyOrders() {
|
||||||
label: 'Cancelled'
|
label: 'Cancelled'
|
||||||
};
|
};
|
||||||
case 'pending':
|
case 'pending':
|
||||||
case 'payment_pending':
|
|
||||||
return {
|
return {
|
||||||
bg: 'bg-amber-50',
|
bg: 'bg-amber-50',
|
||||||
text: 'text-amber-700',
|
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) {
|
if (isLoading && currentPage === 1) {
|
||||||
return (
|
return (
|
||||||
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
|
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
|
||||||
|
|
@ -584,11 +491,8 @@ export default function MyOrders() {
|
||||||
item={item}
|
item={item}
|
||||||
index={index}
|
index={index}
|
||||||
getStatusColor={getStatusColor}
|
getStatusColor={getStatusColor}
|
||||||
getRefundStatusColor={getRefundStatusColor}
|
|
||||||
onPress={(orderId) => router.push(`/(drawer)/(tabs)/me/my-orders/${orderId}`)}
|
onPress={(orderId) => router.push(`/(drawer)/(tabs)/me/my-orders/${orderId}`)}
|
||||||
onRetryPayment={handleRetryPayment}
|
|
||||||
onViewMoreItems={(orderId) => router.push(`/(drawer)/(tabs)/me/my-orders/${orderId}`)}
|
onViewMoreItems={(orderId) => router.push(`/(drawer)/(tabs)/me/my-orders/${orderId}`)}
|
||||||
isPaymentPending={createRazorpayOrderMutation.isPending}
|
|
||||||
refetch={refetch}
|
refetch={refetch}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
|
||||||
|
|
@ -53,7 +53,6 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
|
||||||
// Synchronous re-entrancy guard so a double-tap can't fire placeOrder twice
|
// Synchronous re-entrancy guard so a double-tap can't fire placeOrder twice
|
||||||
// (state-based isPending updates only after a re-render).
|
// (state-based isPending updates only after a re-render).
|
||||||
const submittingRef = useRef(false);
|
const submittingRef = useRef(false);
|
||||||
const [paymentMethod, setPaymentMethod] = useState<'online' | 'cod'>('cod');
|
|
||||||
const userNotes = useCheckoutStore((state) => state.userNotes);
|
const userNotes = useCheckoutStore((state) => state.userNotes);
|
||||||
|
|
||||||
// Helper function to clear cart and invalidate queries
|
// Helper function to clear cart and invalidate queries
|
||||||
|
|
@ -86,22 +85,18 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
|
||||||
// keep showing the pre-order list.
|
// keep showing the pre-order list.
|
||||||
utils.user.order.getOrders.invalidate();
|
utils.user.order.getOrders.invalidate();
|
||||||
|
|
||||||
if (!firstOrder.isCod) {
|
// Clear cart and navigate to success page. Prefer the amount the server
|
||||||
// createRazorpayOrderMutation.mutate({ orderId: firstOrder.id.toString() });
|
// actually stored across the (possibly split) orders over the local preview.
|
||||||
} else {
|
clearCartAndInvalidateQueries(isFlashDelivery ? 'flash' : 'regular');
|
||||||
// Clear cart and navigate to success page. Prefer the amount the server
|
const successPath = isFlashDelivery
|
||||||
// actually stored across the (possibly split) orders over the local preview.
|
? '/(drawer)/(tabs)/flash-delivery/order-success'
|
||||||
clearCartAndInvalidateQueries(isFlashDelivery ? 'flash' : 'regular');
|
: './order-success';
|
||||||
const successPath = isFlashDelivery
|
const serverTotal = orders.reduce(
|
||||||
? '/(drawer)/(tabs)/flash-delivery/order-success'
|
(sum, order) => sum + Number(order.totalAmount ?? 0),
|
||||||
: './order-success';
|
0
|
||||||
const serverTotal = orders.reduce(
|
);
|
||||||
(sum, order) => sum + Number(order.totalAmount ?? 0),
|
const successAmount = serverTotal > 0 ? serverTotal : finalTotalWithDelivery;
|
||||||
0
|
router.replace(`${successPath}?orderId=${firstOrder.id}&totalAmount=${successAmount}`);
|
||||||
);
|
|
||||||
const successAmount = serverTotal > 0 ? serverTotal : finalTotalWithDelivery;
|
|
||||||
router.replace(`${successPath}?orderId=${firstOrder.id}&totalAmount=${successAmount}`);
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
onError: (error: any) => {
|
onError: (error: any) => {
|
||||||
// The backend rejects a checkout whose address/SKUs belong to another
|
// 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 = () => {
|
const handlePlaceOrder = () => {
|
||||||
// Ignore re-entrant presses while a submit is already in flight.
|
// Ignore re-entrant presses while a submit is already in flight.
|
||||||
if (submittingRef.current || placeOrderMutation.isPending) return;
|
if (submittingRef.current || placeOrderMutation.isPending) return;
|
||||||
|
|
@ -189,7 +159,6 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
|
||||||
addressId: selectedAddress,
|
addressId: selectedAddress,
|
||||||
regionId: selectedRegionId,
|
regionId: selectedRegionId,
|
||||||
boundId: constsData?.boundId ?? activeBoundId ?? undefined,
|
boundId: constsData?.boundId ?? activeBoundId ?? undefined,
|
||||||
paymentMethod: paymentMethod,
|
|
||||||
couponIds: selectedCouponIds.length ? selectedCouponIds : undefined,
|
couponIds: selectedCouponIds.length ? selectedCouponIds : undefined,
|
||||||
userNotes: userNotes,
|
userNotes: userNotes,
|
||||||
isFlashDelivery: isFlashDelivery,
|
isFlashDelivery: isFlashDelivery,
|
||||||
|
|
@ -233,12 +202,11 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
|
||||||
</View>
|
</View>
|
||||||
</MyTouchableOpacity>
|
</MyTouchableOpacity>
|
||||||
|
|
||||||
<MyTouchableOpacity
|
<View
|
||||||
onPress={() => setPaymentMethod('cod')}
|
style={tw`flex-row items-center p-4 rounded-xl border border-brand500 bg-blue-50`}
|
||||||
style={tw`flex-row items-center p-4 rounded-xl border ${paymentMethod === 'cod' ? 'border-brand500 bg-blue-50' : 'border-gray-200'}`}
|
|
||||||
>
|
>
|
||||||
<View style={tw`w-5 h-5 rounded-full border-2 ${paymentMethod === 'cod' ? 'border-brand500' : 'border-gray-400'} items-center justify-center mr-3`}>
|
<View style={tw`w-5 h-5 rounded-full border-2 border-brand500 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-2.5 h-2.5 rounded-full bg-brand500`} />
|
||||||
</View>
|
</View>
|
||||||
<View style={tw`w-10 h-10 bg-green-50 rounded-full items-center justify-center mr-3`}>
|
<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" />
|
<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`font-bold text-gray-900`}>Cash on Delivery</MyText>
|
||||||
<MyText style={tw`text-xs text-gray-500`}>Pay when you receive</MyText>
|
<MyText style={tw`text-xs text-gray-500`}>Pay when you receive</MyText>
|
||||||
</View>
|
</View>
|
||||||
</MyTouchableOpacity>
|
</View>
|
||||||
|
|
||||||
<View style={tw`mt-3 flex-row items-center gap-4`}>
|
<View style={tw`mt-3 flex-row items-center gap-4`}>
|
||||||
<View style={tw`flex-row items-center`}>
|
<View style={tw`flex-row items-center`}>
|
||||||
|
|
|
||||||
|
|
@ -290,14 +290,13 @@ Cart: 2 x product 2 @ 215 = 430. Consts: freeDeliveryThreshold 249, deliveryChar
|
||||||
| 3 | navigates to addresses | push `…/me/addresses` |
|
| 3 | navigates to addresses | push `…/me/addresses` |
|
||||||
| 4 | logs out from the footer button | `logout` called |
|
| 4 | logs out from the footer button | `logout` called |
|
||||||
|
|
||||||
### `me-orders.test.tsx` — 5
|
### `me-orders.test.tsx` — 4
|
||||||
| # | Test | Asserts |
|
| # | Test | Asserts |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| 1 | renders the fetched orders | `user.order.getOrders` + row |
|
| 1 | renders the fetched orders | `user.order.getOrders` + row |
|
||||||
| 2 | navigates to the order detail when a row is pressed | push `…/my-orders/11` |
|
| 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` |
|
| 3 | shows the empty state and Start Shopping navigates home | push `…/home` |
|
||||||
| 4 | shows the error state and retries | error copy + `getOrders` re-requested |
|
| 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
|
### `order-detail.test.tsx` — 6
|
||||||
| # | Test | Asserts |
|
| # | Test | Asserts |
|
||||||
|
|
@ -613,7 +612,7 @@ the totals above but not yet in the per-suite tables below.
|
||||||
|
|
||||||
| Path | Purpose |
|
| 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/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/procedures.ts` | `expectProcedureCalled` / `procedureCalls` / `lastProcedureInput` (query + body inputs) |
|
||||||
| `tests/mocks/router.ts` | Mocked expo-router + `routerMock` spies + `searchParamsMock` |
|
| `tests/mocks/router.ts` | Mocked expo-router + `routerMock` spies + `searchParamsMock` |
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,7 @@ import { lastProcedureInput, expectProcedureCalled } from '../mocks/procedures'
|
||||||
import { routerMock } from '../mocks/router'
|
import { routerMock } from '../mocks/router'
|
||||||
import { Providers, renderWithProviders } from '../helpers/render'
|
import { Providers, renderWithProviders } from '../helpers/render'
|
||||||
|
|
||||||
const PLACE_ORDER_OK = { data: [{ id: 99, isCod: true }] }
|
const PLACE_ORDER_OK = { data: [{ id: 99 }] }
|
||||||
|
|
||||||
const baseProps = {
|
const baseProps = {
|
||||||
selectedAddress: 1,
|
selectedAddress: 1,
|
||||||
|
|
@ -140,7 +140,7 @@ describe('PaymentAndOrderComponent money', () => {
|
||||||
it('uses the server-stored order amount for the success URL when present', async () => {
|
it('uses the server-stored order amount for the success URL when present', async () => {
|
||||||
const api = setupApiMocks({
|
const api = setupApiMocks({
|
||||||
procedures: {
|
procedures: {
|
||||||
'user.order.placeOrder': { data: [{ id: 99, isCod: true, totalAmount: '400' }] },
|
'user.order.placeOrder': { data: [{ id: 99, totalAmount: '400' }] },
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -31,7 +31,7 @@ const baseProps = {
|
||||||
selectedCoupons: [],
|
selectedCoupons: [],
|
||||||
}
|
}
|
||||||
|
|
||||||
const PLACE_ORDER_OK = { data: [{ id: 99, isCod: true }] }
|
const PLACE_ORDER_OK = { data: [{ id: 99 }] }
|
||||||
|
|
||||||
const readCart = async (key: string) => {
|
const readCart = async (key: string) => {
|
||||||
const raw = await StorageServiceCasual.getItem(key)
|
const raw = await StorageServiceCasual.getItem(key)
|
||||||
|
|
@ -86,7 +86,6 @@ describe('PaymentAndOrderComponent', () => {
|
||||||
expect(lastProcedureInput(api.fetchMock, 'user.order.placeOrder')).toEqual({
|
expect(lastProcedureInput(api.fetchMock, 'user.order.placeOrder')).toEqual({
|
||||||
selectedItems: [{ skuId: 2, quantity: 1, slotId: 1849 }],
|
selectedItems: [{ skuId: 2, quantity: 1, slotId: 1849 }],
|
||||||
addressId: 1,
|
addressId: 1,
|
||||||
paymentMethod: 'cod',
|
|
||||||
couponIds: undefined,
|
couponIds: undefined,
|
||||||
userNotes: '',
|
userNotes: '',
|
||||||
isFlashDelivery: false,
|
isFlashDelivery: false,
|
||||||
|
|
|
||||||
|
|
@ -29,12 +29,8 @@ const baseOrder = (over: Record<string, unknown> = {}) => ({
|
||||||
orderStatus: 'confirmed',
|
orderStatus: 'confirmed',
|
||||||
deliveryDate: '2026-09-26T10:00:00.000Z',
|
deliveryDate: '2026-09-26T10:00:00.000Z',
|
||||||
cancelReason: null,
|
cancelReason: null,
|
||||||
paymentMode: 'cod',
|
|
||||||
totalAmount: 500,
|
totalAmount: 500,
|
||||||
deliveryCharge: 0,
|
deliveryCharge: 0,
|
||||||
paymentStatus: 'pending',
|
|
||||||
refundStatus: 'none',
|
|
||||||
refundAmount: null,
|
|
||||||
userNotes: null,
|
userNotes: null,
|
||||||
isFlashDelivery: false,
|
isFlashDelivery: false,
|
||||||
createdAt: '2026-09-25T10:00:00.000Z',
|
createdAt: '2026-09-25T10:00:00.000Z',
|
||||||
|
|
|
||||||
|
|
@ -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 }
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -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.
|
* 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 }],
|
selectedItems: [{ skuId: PRODUCT_ID, quantity: 2, slotId: SLOT_ID }],
|
||||||
addressId: 1,
|
addressId: 1,
|
||||||
couponIds: [COUPON_ID],
|
couponIds: [COUPON_ID],
|
||||||
paymentMethod: 'cod',
|
|
||||||
})
|
})
|
||||||
await waitFor(() =>
|
await waitFor(() =>
|
||||||
expect(routerMock.replace).toHaveBeenCalledWith(
|
expect(routerMock.replace).toHaveBeenCalledWith(
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
/**
|
/**
|
||||||
* My orders (app/(drawer)/(tabs)/me/my-orders/index.tsx).
|
* My orders (app/(drawer)/(tabs)/me/my-orders/index.tsx).
|
||||||
* Asserts user.order.getOrders, the loading/error/empty states, row navigation
|
* Asserts user.order.getOrders, the loading/error/empty states and row navigation.
|
||||||
* and the retry-payment -> user.payment.createRazorpayOrder path.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
||||||
|
|
@ -24,12 +23,8 @@ const ORDER = {
|
||||||
deliveryStatus: 'pending',
|
deliveryStatus: 'pending',
|
||||||
deliveryDate: '2026-09-26T10:00:00.000Z',
|
deliveryDate: '2026-09-26T10:00:00.000Z',
|
||||||
cancelReason: null,
|
cancelReason: null,
|
||||||
paymentMode: 'COD',
|
|
||||||
totalAmount: 500,
|
totalAmount: 500,
|
||||||
deliveryCharge: 15,
|
deliveryCharge: 15,
|
||||||
paymentStatus: 'pending',
|
|
||||||
refundStatus: 'not_applicable',
|
|
||||||
refundAmount: null,
|
|
||||||
userNotes: null,
|
userNotes: null,
|
||||||
isFlashDelivery: false,
|
isFlashDelivery: false,
|
||||||
createdAt: '2026-09-20T10:00:00.000Z',
|
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[]) => ({
|
const ordersResponse = (orders: unknown[]) => ({
|
||||||
data: orders,
|
data: orders,
|
||||||
pagination: { page: 1, pageSize: 10, totalCount: orders.length, totalPages: 1 },
|
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')
|
|
||||||
)
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -56,8 +56,6 @@ const ORDER = {
|
||||||
deliveryStatus: 'pending',
|
deliveryStatus: 'pending',
|
||||||
deliveryDate: '2026-09-26T10:00:00.000Z',
|
deliveryDate: '2026-09-26T10:00:00.000Z',
|
||||||
cancelReason: null,
|
cancelReason: null,
|
||||||
paymentMode: 'COD',
|
|
||||||
paymentStatus: 'pending',
|
|
||||||
orderAmount: 500,
|
orderAmount: 500,
|
||||||
discountAmount: 0,
|
discountAmount: 0,
|
||||||
deliveryCharge: 15,
|
deliveryCharge: 15,
|
||||||
|
|
@ -124,7 +122,7 @@ describe('mutation invalidation', () => {
|
||||||
const queryClient = createQueryClient()
|
const queryClient = createQueryClient()
|
||||||
const api = setupApiMocks({
|
const api = setupApiMocks({
|
||||||
orders: [],
|
orders: [],
|
||||||
procedures: { 'user.order.placeOrder': { data: [{ id: 99, isCod: true }] } },
|
procedures: { 'user.order.placeOrder': { data: [{ id: 99 }] } },
|
||||||
})
|
})
|
||||||
|
|
||||||
renderWithProviders(
|
renderWithProviders(
|
||||||
|
|
|
||||||
|
|
@ -26,8 +26,6 @@ const order = (over: Record<string, unknown> = {}) => ({
|
||||||
deliveryStatus: 'pending',
|
deliveryStatus: 'pending',
|
||||||
deliveryDate: '2026-09-26T10:00:00.000Z',
|
deliveryDate: '2026-09-26T10:00:00.000Z',
|
||||||
cancelReason: null,
|
cancelReason: null,
|
||||||
paymentMode: 'COD',
|
|
||||||
paymentStatus: 'pending',
|
|
||||||
orderAmount: 500,
|
orderAmount: 500,
|
||||||
discountAmount: 0,
|
discountAmount: 0,
|
||||||
deliveryCharge: 15,
|
deliveryCharge: 15,
|
||||||
|
|
|
||||||
|
|
@ -24,8 +24,6 @@ const ORDER = {
|
||||||
deliveryStatus: 'pending',
|
deliveryStatus: 'pending',
|
||||||
deliveryDate: '2026-09-26T10:00:00.000Z',
|
deliveryDate: '2026-09-26T10:00:00.000Z',
|
||||||
cancelReason: null,
|
cancelReason: null,
|
||||||
paymentMode: 'COD',
|
|
||||||
paymentStatus: 'pending',
|
|
||||||
orderAmount: 500,
|
orderAmount: 500,
|
||||||
discountAmount: 0,
|
discountAmount: 0,
|
||||||
deliveryCharge: 15,
|
deliveryCharge: 15,
|
||||||
|
|
|
||||||
|
|
@ -57,7 +57,6 @@ jest.mock('expo-updates', () => require('./mocks/native').updatesMock())
|
||||||
jest.mock('expo-linking', () => require('./mocks/native').linkingMock())
|
jest.mock('expo-linking', () => require('./mocks/native').linkingMock())
|
||||||
jest.mock('expo-location', () => require('./mocks/native').locationMock())
|
jest.mock('expo-location', () => require('./mocks/native').locationMock())
|
||||||
jest.mock('expo-notifications', () => require('./mocks/native').notificationsMock())
|
jest.mock('expo-notifications', () => require('./mocks/native').notificationsMock())
|
||||||
jest.mock('react-native-razorpay', () => require('./mocks/native').razorpayMock())
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* useHideTabNav / useAuthenticatedRoute use @react-navigation/native's
|
* useHideTabNav / useAuthenticatedRoute use @react-navigation/native's
|
||||||
|
|
|
||||||
|
|
@ -26,7 +26,6 @@ export function PaymentAndOrderComponent({
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
const [userNotes, setUserNotes] = useState('')
|
const [userNotes, setUserNotes] = useState('')
|
||||||
const [isLoading, setIsLoading] = useState(false)
|
const [isLoading, setIsLoading] = useState(false)
|
||||||
const [paymentMethod, setPaymentMethod] = useState<'online' | 'cod'>('cod')
|
|
||||||
|
|
||||||
const { data: productsData } = useAllProducts()
|
const { data: productsData } = useAllProducts()
|
||||||
const constsData = useRegionalConsts()
|
const constsData = useRegionalConsts()
|
||||||
|
|
@ -108,7 +107,6 @@ export function PaymentAndOrderComponent({
|
||||||
})),
|
})),
|
||||||
addressId: selectedAddress,
|
addressId: selectedAddress,
|
||||||
regionId: selectedRegionId,
|
regionId: selectedRegionId,
|
||||||
paymentMethod: paymentMethod,
|
|
||||||
userNotes: userNotes,
|
userNotes: userNotes,
|
||||||
isFlashDelivery: isFlashDelivery,
|
isFlashDelivery: isFlashDelivery,
|
||||||
}
|
}
|
||||||
|
|
@ -163,18 +161,9 @@ export function PaymentAndOrderComponent({
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Cash on Delivery */}
|
{/* Cash on Delivery */}
|
||||||
<div
|
<div className="flex items-center rounded-xl border border-brand-500 bg-blue-50 p-4 transition-all">
|
||||||
onClick={() => setPaymentMethod('cod')}
|
<div className="mr-3 flex h-5 w-5 items-center justify-center rounded-full border-2 border-brand-500">
|
||||||
className={`flex items-center rounded-xl border p-4 transition-all ${
|
<div className="h-2.5 w-2.5 rounded-full bg-brand-500" />
|
||||||
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>
|
</div>
|
||||||
<div className="mr-3 flex h-10 w-10 items-center justify-center rounded-full bg-green-50">
|
<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" />
|
<Banknote className="h-5 w-5 text-green-500" />
|
||||||
|
|
|
||||||
|
|
@ -98,7 +98,6 @@ function FlashCheckoutPage() {
|
||||||
})),
|
})),
|
||||||
addressId: selectedAddressId,
|
addressId: selectedAddressId,
|
||||||
regionId: selectedRegionId,
|
regionId: selectedRegionId,
|
||||||
paymentMethod: 'cod',
|
|
||||||
isFlashDelivery: true,
|
isFlashDelivery: true,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -98,7 +98,6 @@ function CheckoutPage() {
|
||||||
})),
|
})),
|
||||||
addressId: selectedAddressId,
|
addressId: selectedAddressId,
|
||||||
regionId: selectedRegionId,
|
regionId: selectedRegionId,
|
||||||
paymentMethod: 'cod',
|
|
||||||
isFlashDelivery: false,
|
isFlashDelivery: false,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -185,24 +185,6 @@ function OrderDetailPage() {
|
||||||
|
|
||||||
{/* Main Info Card */}
|
{/* Main Info Card */}
|
||||||
<div className="mb-4 rounded-2xl border border-slate-100 bg-white p-5">
|
<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) &&
|
{(order.deliveryDate || order.isFlashDelivery) &&
|
||||||
['delivered', 'success'].includes((order.deliveryStatus || '').toLowerCase()) && (
|
['delivered', 'success'].includes((order.deliveryStatus || '').toLowerCase()) && (
|
||||||
<div className="flex flex-row items-center border-t border-slate-50 pt-4">
|
<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">
|
<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="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>
|
<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>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -7,14 +7,6 @@ import { orderStatusManipulator } from '../lib/string-manipulators'
|
||||||
import dayjs from 'dayjs'
|
import dayjs from 'dayjs'
|
||||||
import { AlertCircle, Package, MapPin } from 'lucide-react'
|
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 })
|
export const Route = createFileRoute('/me/orders')({ component: OrdersPage })
|
||||||
|
|
||||||
const PAGE_SIZE = 10
|
const PAGE_SIZE = 10
|
||||||
|
|
@ -38,7 +30,6 @@ function getStatusStyle(status: string): StatusStyle {
|
||||||
case 'failed':
|
case 'failed':
|
||||||
return { bg: 'bg-rose-50', text: 'text-rose-700', iconColor: '#E11D48', icon: <span>✕</span>, label: 'Cancelled' }
|
return { bg: 'bg-rose-50', text: 'text-rose-700', iconColor: '#E11D48', icon: <span>✕</span>, label: 'Cancelled' }
|
||||||
case 'pending':
|
case 'pending':
|
||||||
case 'payment_pending':
|
|
||||||
return { bg: 'bg-amber-50', text: 'text-amber-700', iconColor: '#D97706', icon: <span>🕐</span>, label: 'Pending' }
|
return { bg: 'bg-amber-50', text: 'text-amber-700', iconColor: '#D97706', icon: <span>🕐</span>, label: 'Pending' }
|
||||||
case 'packaged':
|
case 'packaged':
|
||||||
return { bg: 'bg-brand-50', text: 'text-brand-700', iconColor: '#1570EF', icon: <span>📦</span>, label: '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({
|
function OrderCard({
|
||||||
item,
|
item,
|
||||||
getStatusStyle,
|
getStatusStyle,
|
||||||
getRefundStyle,
|
|
||||||
onPress,
|
onPress,
|
||||||
onViewMoreItems,
|
onViewMoreItems,
|
||||||
refetch,
|
refetch,
|
||||||
}: {
|
}: {
|
||||||
item: any
|
item: any
|
||||||
getStatusStyle: (s: string) => StatusStyle
|
getStatusStyle: (s: string) => StatusStyle
|
||||||
getRefundStyle: (s: string) => { bg: string; text: string; icon: React.ReactNode; color: string }
|
|
||||||
onPress: (orderId: number) => void
|
onPress: (orderId: number) => void
|
||||||
onViewMoreItems: (orderId: number) => void
|
onViewMoreItems: (orderId: number) => void
|
||||||
refetch: () => void
|
refetch: () => void
|
||||||
|
|
@ -276,22 +252,6 @@ function OrderCard({
|
||||||
<p className="ml-2 text-xs font-bold text-rose-800">Cancellation Details</p>
|
<p className="ml-2 text-xs font-bold text-rose-800">Cancellation Details</p>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs font-medium leading-relaxed text-rose-600">{item.cancelReason}</p>
|
<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>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|
@ -418,7 +378,6 @@ function OrdersPage() {
|
||||||
key={order.id}
|
key={order.id}
|
||||||
item={order}
|
item={order}
|
||||||
getStatusStyle={getStatusStyle}
|
getStatusStyle={getStatusStyle}
|
||||||
getRefundStyle={getRefundStyle}
|
|
||||||
onPress={(orderId) => navigate({ to: '/me/orders/$id', params: { id: String(orderId) } })}
|
onPress={(orderId) => navigate({ to: '/me/orders/$id', params: { id: String(orderId) } })}
|
||||||
onViewMoreItems={(orderId) =>
|
onViewMoreItems={(orderId) =>
|
||||||
navigate({ to: '/me/orders/$id', params: { id: String(orderId) } })
|
navigate({ to: '/me/orders/$id', params: { id: String(orderId) } })
|
||||||
|
|
|
||||||
127
change-log.txt
127
change-log.txt
|
|
@ -5649,3 +5649,130 @@ user-ui
|
||||||
Tests were not run (user runs the suite).
|
Tests were not run (user runs the suite).
|
||||||
5. The five scope-specific readers/writers (global/region/bound/legacy) and the
|
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.
|
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.
|
||||||
|
|
|
||||||
|
|
@ -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-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-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-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-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-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-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. |
|
| 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-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. |
|
| 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”;
|
Online payments were removed from the product: there is no gateway, no
|
||||||
`RazorpayPaymentService` methods are commented-out stubs. Do not report live
|
`payment_info` / `payments` / `refunds` table, no payment state on an order and
|
||||||
online payment/refund journeys as supported or passing today.
|
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 |
|
| 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-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 | 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-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. |
|
||||||
| 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. |
|
|
||||||
|
|
||||||
## P. Write-path integrity, atomicity and idempotency
|
## P. Write-path integrity, atomicity and idempotency
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -244,7 +244,7 @@ grep -rhoE "from ['\"][^'\"]+['\"]" app components ../../packages/ui/src \
|
||||||
```
|
```
|
||||||
|
|
||||||
In this repo **no custom native module is actually imported**:
|
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
|
`package.json` but never imported in source (Google login goes through
|
||||||
`expo-auth-session`), and `expo-notifications` is unused. Everything else is
|
`expo-auth-session`), and `expo-notifications` is unused. Everything else is
|
||||||
`expo-*` or JS-only. So both apps are Expo Go-safe.
|
`expo-*` or JS-only. So both apps are Expo Go-safe.
|
||||||
|
|
|
||||||
|
|
@ -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) |
|
| 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) |
|
| 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) |
|
| 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) |
|
| 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) |
|
| 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) |
|
| Conditional/legacy | [Vendor snippets](vendor-snippets.md), [Reviews](reviews.md), [Fallback/legacy pages](fallback-legacy-pages.md) |
|
||||||
|
|
|
||||||
|
|
@ -23,4 +23,4 @@ Scope: customer/admin cancellation, reason/actor/status, group usages, refund el
|
||||||
| CANCEL-17 | P1 | Cart after cancellation. | No unexpected automatic cart restoration/duplicate item unless explicit policy. |
|
| CANCEL-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. |
|
| 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.
|
||||||
|
|
|
||||||
|
|
@ -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-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. |
|
| 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.
|
||||||
|
|
|
||||||
|
|
@ -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.
|
|
||||||
|
|
@ -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-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-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-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. |
|
| 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.
|
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.
|
||||||
|
|
|
||||||
|
|
@ -22,11 +22,17 @@
|
||||||
-- * per-bound business keys -> `region_bound_consts`
|
-- * per-bound business keys -> `region_bound_consts`
|
||||||
-- (incl. `isFlashDeliveryEnabled`, which each bound switches independently)
|
-- (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:
|
-- Phases, kept in the original dependency order:
|
||||||
-- 1. regions / region_bounds / superadmins + seeds (from 0006)
|
-- 1. regions / region_bounds / superadmins + seeds (from 0006)
|
||||||
-- 2. region_id backfill + 31-table rebuild (from 0007)
|
-- 2. region_id backfill + 31-table rebuild (from 0007)
|
||||||
-- 3. global_consts / region_consts / region_bound_consts (from 0008+0009)
|
-- 3. global_consts / region_consts / region_bound_consts (from 0008+0009)
|
||||||
-- 4. coupon product targets -> `sku_ids` JSON arrays (from 0007_coupon_targets_json)
|
-- 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
|
-- Verified: applying this file to apps/backend/dumps/latest.sql yields the same
|
||||||
-- schema and the same rows as applying 0006..0009 in order.
|
-- 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).
|
-- violation).
|
||||||
--
|
--
|
||||||
-- Live-DB findings this is sized for:
|
-- 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,
|
-- * 5 orders whose address no longer exists (their dependents deleted too,
|
||||||
-- per product-owner decision; purchase history for these is dropped).
|
-- 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
|
-- Detach coupon usage / complaints / incidents from the orphan orders before
|
||||||
-- removing the orders themselves (columns are nullable; deleting usage rows
|
-- removing the orders themselves (columns are nullable; deleting usage rows
|
||||||
-- entirely would also lose coupon history tied to surviving behavior).
|
-- 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
|
UPDATE `user_incidents` SET `order_id` = NULL
|
||||||
WHERE `order_id` IN (SELECT `id` FROM `orders` WHERE `address_id` NOT IN (SELECT `id` FROM `addresses`));
|
WHERE `order_id` IN (SELECT `id` FROM `orders` WHERE `address_id` NOT IN (SELECT `id` FROM `addresses`));
|
||||||
--> statement-breakpoint
|
--> statement-breakpoint
|
||||||
-- Delete the orphan orders' remaining hard dependents (order_status / refunds
|
-- Delete the orphan orders' remaining hard dependents (their copies into the
|
||||||
-- included — their copies into the rebuilt tables would otherwise fail first).
|
-- 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 FROM `order_status` WHERE `order_id` IN (SELECT `id` FROM `orders` WHERE `address_id` NOT IN (SELECT `id` FROM `addresses`));
|
DELETE FROM `order_status` WHERE `order_id` IN (SELECT `id` FROM `orders` WHERE `address_id` NOT IN (SELECT `id` FROM `addresses`));
|
||||||
--> statement-breakpoint
|
--> statement-breakpoint
|
||||||
DELETE FROM `order_items` WHERE `order_id` IN (SELECT `id` FROM `orders` WHERE `address_id` NOT IN (SELECT `id` FROM `addresses`));
|
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,
|
`user_id` integer NOT NULL,
|
||||||
`address_id` integer NOT NULL,
|
`address_id` integer NOT NULL,
|
||||||
`slot_id` integer,
|
`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,
|
`total_amount` text NOT NULL,
|
||||||
`delivery_charge` text DEFAULT '0' NOT NULL,
|
`delivery_charge` text DEFAULT '0' NOT NULL,
|
||||||
`discount_amount` 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 (`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 (`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 (`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
|
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
|
||||||
);
|
);
|
||||||
--> statement-breakpoint
|
--> 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`)
|
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`,`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`;
|
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
|
--> statement-breakpoint
|
||||||
CREATE TABLE `__new_order_items` (
|
CREATE TABLE `__new_order_items` (
|
||||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||||
|
|
@ -517,47 +515,16 @@ CREATE TABLE `__new_order_status` (
|
||||||
`is_cancelled` integer DEFAULT false NOT NULL,
|
`is_cancelled` integer DEFAULT false NOT NULL,
|
||||||
`cancel_reason` text,
|
`cancel_reason` text,
|
||||||
`is_cancelled_by_admin` integer,
|
`is_cancelled_by_admin` integer,
|
||||||
`payment_state` text DEFAULT 'pending' NOT NULL,
|
|
||||||
`cancellation_user_notes` text,
|
`cancellation_user_notes` text,
|
||||||
`cancellation_admin_notes` text,
|
`cancellation_admin_notes` text,
|
||||||
`cancellation_reviewed` integer DEFAULT false NOT NULL,
|
`cancellation_reviewed` integer DEFAULT false NOT NULL,
|
||||||
`cancellation_reviewed_at` text,
|
`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 (`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
|
FOREIGN KEY (`order_id`) REFERENCES `__new_orders`(`id`) ON UPDATE no action ON DELETE no action
|
||||||
);
|
);
|
||||||
--> statement-breakpoint
|
--> statement-breakpoint
|
||||||
INSERT INTO `__new_refunds` (`id`,`order_id`,`refund_amount`,`refund_status`,`merchant_refund_id`,`refund_processed_at`,`created_at`)
|
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_id`,`refund_amount`,`refund_status`,`merchant_refund_id`,`refund_processed_at`,`created_at` FROM `refunds`;
|
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_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`;
|
|
||||||
--> statement-breakpoint
|
--> statement-breakpoint
|
||||||
CREATE TABLE `__new_coupon_usage` (
|
CREATE TABLE `__new_coupon_usage` (
|
||||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||||
|
|
@ -676,6 +643,24 @@ DROP TABLE `coupon_applicable_users`;
|
||||||
--> statement-breakpoint
|
--> statement-breakpoint
|
||||||
DROP TABLE `coupon_usage`;
|
DROP TABLE `coupon_usage`;
|
||||||
--> statement-breakpoint
|
--> 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`;
|
DROP TABLE `payments`;
|
||||||
--> statement-breakpoint
|
--> statement-breakpoint
|
||||||
DROP TABLE `refunds`;
|
DROP TABLE `refunds`;
|
||||||
|
|
@ -686,6 +671,9 @@ DROP TABLE `order_items`;
|
||||||
--> statement-breakpoint
|
--> statement-breakpoint
|
||||||
DROP TABLE `orders`;
|
DROP TABLE `orders`;
|
||||||
--> statement-breakpoint
|
--> 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`;
|
DROP TABLE `product_group_membership`;
|
||||||
--> statement-breakpoint
|
--> statement-breakpoint
|
||||||
DROP TABLE `product_tags`;
|
DROP TABLE `product_tags`;
|
||||||
|
|
@ -769,10 +757,6 @@ ALTER TABLE `__new_order_items` RENAME TO `order_items`;
|
||||||
--> statement-breakpoint
|
--> statement-breakpoint
|
||||||
ALTER TABLE `__new_order_status` RENAME TO `order_status`;
|
ALTER TABLE `__new_order_status` RENAME TO `order_status`;
|
||||||
--> statement-breakpoint
|
--> 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`;
|
ALTER TABLE `__new_coupon_usage` RENAME TO `coupon_usage`;
|
||||||
--> statement-breakpoint
|
--> statement-breakpoint
|
||||||
ALTER TABLE `__new_coupon_applicable_users` RENAME TO `coupon_applicable_users`;
|
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
|
--> statement-breakpoint
|
||||||
CREATE UNIQUE INDEX `unique_product_tag` ON `product_tags` (`product_id`,`tag_id`);
|
CREATE UNIQUE INDEX `unique_product_tag` ON `product_tags` (`product_id`,`tag_id`);
|
||||||
--> statement-breakpoint
|
--> 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`);
|
CREATE UNIQUE INDEX `unique_coupon_user` ON `coupon_applicable_users` (`coupon_id`,`user_id`);
|
||||||
--> statement-breakpoint
|
--> statement-breakpoint
|
||||||
CREATE UNIQUE INDEX `reserved_coupons_secret_code_unique` ON `reserved_coupons` (`secret_code`);
|
CREATE UNIQUE INDEX `reserved_coupons_secret_code_unique` ON `reserved_coupons` (`secret_code`);
|
||||||
|
|
|
||||||
|
|
@ -44,7 +44,6 @@ export {
|
||||||
getUsersForCoupon,
|
getUsersForCoupon,
|
||||||
createCouponWithRelations,
|
createCouponWithRelations,
|
||||||
updateCouponWithRelations,
|
updateCouponWithRelations,
|
||||||
generateCancellationCoupon,
|
|
||||||
createReservedCoupon,
|
createReservedCoupon,
|
||||||
createCouponForUser,
|
createCouponForUser,
|
||||||
checkUsersExist,
|
checkUsersExist,
|
||||||
|
|
@ -221,16 +220,6 @@ export {
|
||||||
getDeliverySlotById as getUserDeliverySlotById,
|
getDeliverySlotById as getUserDeliverySlotById,
|
||||||
} from './src/user-apis/slots'
|
} 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 {
|
export {
|
||||||
// User Auth
|
// User Auth
|
||||||
getUserByEmail as getUserAuthByEmail,
|
getUserByEmail as getUserAuthByEmail,
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { db } from '../db/db_index'
|
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 { eq, and, like, or, inArray, lt, desc, asc, sql, isNull } from 'drizzle-orm'
|
||||||
import type { Coupon, CouponFormInput, CouponValidationResult, UserMiniInfo } from '@packages/shared'
|
import type { Coupon, CouponFormInput, CouponValidationResult, UserMiniInfo } from '@packages/shared'
|
||||||
|
|
||||||
|
|
@ -293,55 +293,6 @@ export async function checkReservedCouponExists(secretCode: string): Promise<boo
|
||||||
return !!existing
|
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> {
|
export async function getOrderWithUser(regionId: number, orderId: number): Promise<any | null> {
|
||||||
return await db.query.orders.findFirst({
|
return await db.query.orders.findFirst({
|
||||||
where: and(
|
where: and(
|
||||||
|
|
|
||||||
|
|
@ -7,8 +7,6 @@ import {
|
||||||
orderItems,
|
orderItems,
|
||||||
orders,
|
orders,
|
||||||
orderStatus,
|
orderStatus,
|
||||||
payments,
|
|
||||||
refunds,
|
|
||||||
} from '../db/schema'
|
} from '../db/schema'
|
||||||
import { and, desc, eq, gt, inArray, lt, SQL } from 'drizzle-orm'
|
import { and, desc, eq, gt, inArray, lt, SQL } from 'drizzle-orm'
|
||||||
import { releaseCouponUsageIfGroupFullyCancelled } from '../user-apis/order'
|
import { releaseCouponUsageIfGroupFullyCancelled } from '../user-apis/order'
|
||||||
|
|
@ -24,9 +22,6 @@ import type {
|
||||||
AdminGetAllOrdersResultWithUserId,
|
AdminGetAllOrdersResultWithUserId,
|
||||||
AdminRebalanceSlotsResult,
|
AdminRebalanceSlotsResult,
|
||||||
AdminCancelOrderResult,
|
AdminCancelOrderResult,
|
||||||
AdminRefundRecord,
|
|
||||||
RefundStatus,
|
|
||||||
PaymentStatus,
|
|
||||||
GetAllOrdersInput,
|
GetAllOrdersInput,
|
||||||
} from '@packages/shared'
|
} from '@packages/shared'
|
||||||
import type { InferSelectModel } from 'drizzle-orm'
|
import type { InferSelectModel } from 'drizzle-orm'
|
||||||
|
|
@ -34,12 +29,6 @@ import { coerceDate } from '../lib/date'
|
||||||
import { marketStatsForRegion } from '../lib/market-stats'
|
import { marketStatsForRegion } from '../lib/market-stats'
|
||||||
import { composeSkuName, composeUnitNotation } from '../lib/sku-features'
|
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>
|
type OrderStatusRow = InferSelectModel<typeof orderStatus>
|
||||||
|
|
||||||
const mapOrderStatusRecord = (record: OrderStatusRow): AdminOrderStatusRecord => ({
|
const mapOrderStatusRecord = (record: OrderStatusRow): AdminOrderStatusRecord => ({
|
||||||
|
|
@ -52,12 +41,10 @@ const mapOrderStatusRecord = (record: OrderStatusRow): AdminOrderStatusRecord =>
|
||||||
isCancelled: record.isCancelled,
|
isCancelled: record.isCancelled,
|
||||||
cancelReason: record.cancelReason ?? null,
|
cancelReason: record.cancelReason ?? null,
|
||||||
isCancelledByAdmin: record.isCancelledByAdmin ?? null,
|
isCancelledByAdmin: record.isCancelledByAdmin ?? null,
|
||||||
paymentStatus: isPaymentStatus(record.paymentStatus) ? record.paymentStatus : 'pending',
|
|
||||||
cancellationUserNotes: record.cancellationUserNotes ?? null,
|
cancellationUserNotes: record.cancellationUserNotes ?? null,
|
||||||
cancellationAdminNotes: record.cancellationAdminNotes ?? null,
|
cancellationAdminNotes: record.cancellationAdminNotes ?? null,
|
||||||
cancellationReviewed: record.cancellationReviewed,
|
cancellationReviewed: record.cancellationReviewed,
|
||||||
cancellationReviewedAt: record.cancellationReviewedAt ?? null,
|
cancellationReviewedAt: record.cancellationReviewedAt ?? null,
|
||||||
refundCouponId: record.refundCouponId ?? null,
|
|
||||||
})
|
})
|
||||||
|
|
||||||
export async function updateOrderNotes(regionId: number, orderId: number, adminNotes: string | null): Promise<AdminOrderRow | 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,
|
orderStatus: true,
|
||||||
refunds: true,
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -194,22 +178,6 @@ export async function getOrderDetails(regionId: number, orderId: number): Promis
|
||||||
status = 'delivered'
|
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 {
|
return {
|
||||||
id: orderData.id,
|
id: orderData.id,
|
||||||
readableId: orderData.id,
|
readableId: orderData.id,
|
||||||
|
|
@ -231,8 +199,6 @@ export async function getOrderDetails(regionId: number, orderId: number): Promis
|
||||||
sequence: orderData.slot.deliverySequence,
|
sequence: orderData.slot.deliverySequence,
|
||||||
}
|
}
|
||||||
: null,
|
: null,
|
||||||
isCod: orderData.isCod,
|
|
||||||
isOnlinePayment: orderData.isOnlinePayment,
|
|
||||||
totalAmount:
|
totalAmount:
|
||||||
parseFloat(orderData.totalAmount?.toString() || '0') -
|
parseFloat(orderData.totalAmount?.toString() || '0') -
|
||||||
parseFloat(orderData.deliveryCharge?.toString() || '0'),
|
parseFloat(orderData.deliveryCharge?.toString() || '0'),
|
||||||
|
|
@ -259,33 +225,13 @@ export async function getOrderDetails(regionId: number, orderId: number): Promis
|
||||||
featureValue: f.featureValue,
|
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,
|
cancelReason: orderStatusRecord?.cancelReason || null,
|
||||||
cancellationReviewed: orderStatusRecord?.cancellationReviewed || false,
|
cancellationReviewed: orderStatusRecord?.cancellationReviewed || false,
|
||||||
isRefundDone: refundStatus === 'processed' || false,
|
|
||||||
refundStatus,
|
|
||||||
refundAmount: refund?.refundAmount
|
|
||||||
? parseFloat(refund.refundAmount.toString())
|
|
||||||
: null,
|
|
||||||
couponData,
|
couponData,
|
||||||
couponCode: couponData?.couponCode || null,
|
couponCode: couponData?.couponCode || null,
|
||||||
couponDescription: couponData?.couponDescription || null,
|
couponDescription: couponData?.couponDescription || null,
|
||||||
discountAmount: couponData?.discountAmount || null,
|
discountAmount: couponData?.discountAmount || null,
|
||||||
orderStatus: orderStatusRecord,
|
orderStatus: orderStatusRecord,
|
||||||
refundRecord,
|
|
||||||
isFlashDelivery: orderData.isFlashDelivery,
|
isFlashDelivery: orderData.isFlashDelivery,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -386,12 +332,7 @@ export async function getSlotOrders(regionId: number, slotId: string): Promise<A
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
const filteredOrders = slotOrders.filter((order: any) => {
|
const formattedOrders = slotOrders.map((order: any) => {
|
||||||
const statusRecord = order.orderStatus[0]
|
|
||||||
return order.isCod || (statusRecord && statusRecord.paymentStatus === 'success')
|
|
||||||
})
|
|
||||||
|
|
||||||
const formattedOrders = filteredOrders.map((order: any) => {
|
|
||||||
const statusRecord = order.orderStatus[0]
|
const statusRecord = order.orderStatus[0]
|
||||||
let status: 'pending' | 'delivered' | 'cancelled' = 'pending'
|
let status: 'pending' | 'delivered' | 'cancelled' = 'pending'
|
||||||
if (statusRecord?.isCancelled) {
|
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 {
|
return {
|
||||||
id: order.id,
|
id: order.id,
|
||||||
readableId: order.id,
|
readableId: order.id,
|
||||||
|
|
@ -435,11 +374,6 @@ export async function getSlotOrders(regionId: number, slotId: string): Promise<A
|
||||||
status,
|
status,
|
||||||
isPackaged: order.orderItems.every((item: any) => item.is_packaged) || false,
|
isPackaged: order.orderItems.every((item: any) => item.is_packaged) || false,
|
||||||
isDelivered: statusRecord?.isDelivered || false,
|
isDelivered: statusRecord?.isDelivered || false,
|
||||||
isCod: order.isCod,
|
|
||||||
paymentMode,
|
|
||||||
paymentStatus: isPaymentStatus(statusRecord?.paymentStatus || 'pending')
|
|
||||||
? statusRecord?.paymentStatus || 'pending'
|
|
||||||
: 'pending',
|
|
||||||
slotId: order.slotId,
|
slotId: order.slotId,
|
||||||
adminNotes: order.adminNotes,
|
adminNotes: order.adminNotes,
|
||||||
userNotes: order.userNotes,
|
userNotes: order.userNotes,
|
||||||
|
|
@ -545,12 +479,7 @@ export async function getAllOrders(regionId: number, input: GetAllOrdersInput):
|
||||||
const hasMore = allOrders.length > limit
|
const hasMore = allOrders.length > limit
|
||||||
const ordersToReturn = hasMore ? allOrders.slice(0, limit) : allOrders
|
const ordersToReturn = hasMore ? allOrders.slice(0, limit) : allOrders
|
||||||
|
|
||||||
const filteredOrders = ordersToReturn.filter((order: any) => {
|
const formattedOrders = ordersToReturn.map((order: any) => {
|
||||||
const statusRecord = order.orderStatus[0]
|
|
||||||
return order.isCod || (statusRecord && statusRecord.paymentStatus === 'success')
|
|
||||||
})
|
|
||||||
|
|
||||||
const formattedOrders = filteredOrders.map((order: any) => {
|
|
||||||
const statusRecord = order.orderStatus[0]
|
const statusRecord = order.orderStatus[0]
|
||||||
let status: 'pending' | 'delivered' | 'cancelled' = 'pending'
|
let status: 'pending' | 'delivered' | 'cancelled' = 'pending'
|
||||||
if (statusRecord?.isCancelled) {
|
if (statusRecord?.isCancelled) {
|
||||||
|
|
@ -599,7 +528,6 @@ export async function getAllOrders(regionId: number, input: GetAllOrdersInput):
|
||||||
status,
|
status,
|
||||||
isPackaged: order.orderItems.every((item: any) => item.is_packaged) || false,
|
isPackaged: order.orderItems.every((item: any) => item.is_packaged) || false,
|
||||||
isDelivered: statusRecord?.isDelivered || false,
|
isDelivered: statusRecord?.isDelivered || false,
|
||||||
isCod: order.isCod,
|
|
||||||
isFlashDelivery: order.isFlashDelivery,
|
isFlashDelivery: order.isFlashDelivery,
|
||||||
userNotes: order.userNotes,
|
userNotes: order.userNotes,
|
||||||
adminNotes: order.adminNotes,
|
adminNotes: order.adminNotes,
|
||||||
|
|
@ -749,13 +677,6 @@ export async function cancelOrder(regionId: number, orderId: number, reason: str
|
||||||
})
|
})
|
||||||
.where(eq(orderStatus.id, status.id))
|
.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)
|
await releaseCouponUsageIfGroupFullyCancelled(tx, order.id)
|
||||||
|
|
||||||
return { orderId: order.id, userId: order.userId }
|
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 db.transaction(async (tx) => {
|
||||||
await tx.delete(orderItems).where(eq(orderItems.orderId, orderId))
|
await tx.delete(orderItems).where(eq(orderItems.orderId, orderId))
|
||||||
await tx.delete(orderStatus).where(eq(orderStatus.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(couponUsage).where(eq(couponUsage.orderId, orderId))
|
||||||
await tx.delete(complaints).where(eq(complaints.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)))
|
await tx.delete(orders).where(and(eq(orders.id, orderId), eq(orders.regionId, regionId)))
|
||||||
|
|
|
||||||
|
|
@ -64,13 +64,11 @@ const timestampText = (name: string) =>
|
||||||
const staffRoleValues = ['super_admin', 'admin', 'marketer', 'delivery_staff'] as const
|
const staffRoleValues = ['super_admin', 'admin', 'marketer', 'delivery_staff'] as const
|
||||||
const staffPermissionValues = ['crud_product', 'make_coupon', 'crud_staff_users'] as const
|
const staffPermissionValues = ['crud_product', 'make_coupon', 'crud_staff_users'] as const
|
||||||
const uploadStatusValues = ['pending', 'claimed'] as const
|
const uploadStatusValues = ['pending', 'claimed'] as const
|
||||||
const paymentStatusValues = ['pending', 'success', 'cod', 'failed'] as const
|
|
||||||
const productTypeValues = ['item', 'combo'] as const
|
const productTypeValues = ['item', 'combo'] as const
|
||||||
|
|
||||||
export const staffRoleEnum = (name: string) => text(name, { enum: staffRoleValues })
|
export const staffRoleEnum = (name: string) => text(name, { enum: staffRoleValues })
|
||||||
export const staffPermissionEnum = (name: string) => text(name, { enum: staffPermissionValues })
|
export const staffPermissionEnum = (name: string) => text(name, { enum: staffPermissionValues })
|
||||||
export const uploadStatusEnum = (name: string) => text(name, { enum: uploadStatusValues })
|
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 productTypeEnum = (name: string) => text(name, { enum: productTypeValues })
|
||||||
|
|
||||||
export const users = sqliteTable('users', {
|
export const users = sqliteTable('users', {
|
||||||
|
|
@ -343,25 +341,12 @@ export const specialDeals = sqliteTable('special_deals', {
|
||||||
validTill: timestampText('valid_till').notNull(),
|
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', {
|
export const orders = sqliteTable('orders', {
|
||||||
id: integer().primaryKey({ autoIncrement: true }),
|
id: integer().primaryKey({ autoIncrement: true }),
|
||||||
regionId: integer('region_id').references(() => regions.id),
|
regionId: integer('region_id').references(() => regions.id),
|
||||||
userId: integer('user_id').notNull().references(() => users.id),
|
userId: integer('user_id').notNull().references(() => users.id),
|
||||||
addressId: integer('address_id').notNull().references(() => addresses.id),
|
addressId: integer('address_id').notNull().references(() => addresses.id),
|
||||||
slotId: integer('slot_id').references(() => deliverySlotInfo.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(),
|
totalAmount: numericText('total_amount').notNull(),
|
||||||
deliveryCharge: numericText('delivery_charge').notNull().default('0'),
|
deliveryCharge: numericText('delivery_charge').notNull().default('0'),
|
||||||
discountAmount: numericText('discount_amount').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),
|
isCancelled: integer('is_cancelled', { mode: 'boolean' }).notNull().default(false),
|
||||||
cancelReason: text('cancel_reason'),
|
cancelReason: text('cancel_reason'),
|
||||||
isCancelledByAdmin: integer('is_cancelled_by_admin', { mode: 'boolean' }),
|
isCancelledByAdmin: integer('is_cancelled_by_admin', { mode: 'boolean' }),
|
||||||
paymentStatus: paymentStatusEnum('payment_state').notNull().default('pending'),
|
|
||||||
cancellationUserNotes: text('cancellation_user_notes'),
|
cancellationUserNotes: text('cancellation_user_notes'),
|
||||||
cancellationAdminNotes: text('cancellation_admin_notes'),
|
cancellationAdminNotes: text('cancellation_admin_notes'),
|
||||||
cancellationReviewed: integer('cancellation_reviewed', { mode: 'boolean' }).notNull().default(false),
|
cancellationReviewed: integer('cancellation_reviewed', { mode: 'boolean' }).notNull().default(false),
|
||||||
cancellationReviewedAt: timestampText('cancellation_reviewed_at'),
|
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', {
|
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] }),
|
address: one(addresses, { fields: [orders.addressId], references: [addresses.id] }),
|
||||||
slot: one(deliverySlotInfo, { fields: [orders.slotId], references: [deliverySlotInfo.id] }),
|
slot: one(deliverySlotInfo, { fields: [orders.slotId], references: [deliverySlotInfo.id] }),
|
||||||
orderItems: many(orderItems),
|
orderItems: many(orderItems),
|
||||||
payment: one(payments),
|
|
||||||
paymentInfo: one(paymentInfoTable, { fields: [orders.paymentInfoId], references: [paymentInfoTable.id] }),
|
|
||||||
orderStatus: many(orderStatus),
|
orderStatus: many(orderStatus),
|
||||||
refunds: many(refunds),
|
|
||||||
couponUsages: many(couponUsage),
|
couponUsages: many(couponUsage),
|
||||||
userIncidents: many(userIncidents),
|
userIncidents: many(userIncidents),
|
||||||
}))
|
}))
|
||||||
|
|
@ -764,19 +724,6 @@ export const orderItemsRelations = relations(orderItems, ({ one }) => ({
|
||||||
export const orderStatusRelations = relations(orderStatus, ({ one }) => ({
|
export const orderStatusRelations = relations(orderStatus, ({ one }) => ({
|
||||||
order: one(orders, { fields: [orderStatus.orderId], references: [orders.id] }),
|
order: one(orders, { fields: [orderStatus.orderId], references: [orders.id] }),
|
||||||
user: one(users, { fields: [orderStatus.userId], references: [users.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 }) => ({
|
export const notificationsRelations = relations(notifications, ({ one }) => ({
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { db } from '../db/db_index'
|
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 { inArray } from 'drizzle-orm'
|
||||||
import { runBatched } from './run-batched'
|
import { runBatched } from './run-batched'
|
||||||
|
|
||||||
|
|
@ -23,19 +23,13 @@ export async function deleteOrdersWithRelations(orderIds: number[]): Promise<voi
|
||||||
// 2. Delete complaints related to these orders
|
// 2. Delete complaints related to these orders
|
||||||
await tx.delete(complaints).where(inArray(complaints.orderId, chunk))
|
await tx.delete(complaints).where(inArray(complaints.orderId, chunk))
|
||||||
|
|
||||||
// 3. Delete refunds
|
// 3. Delete order status records
|
||||||
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
|
|
||||||
await tx.delete(orderStatus).where(inArray(orderStatus.orderId, chunk))
|
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))
|
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))
|
await tx.delete(orders).where(inArray(orders.id, chunk))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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 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
|
export const otpSenderAuthToken = process.env.OTP_SENDER_AUTH_TOKEN as string
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -13,8 +13,6 @@ import {
|
||||||
orderItems,
|
orderItems,
|
||||||
orderStatus,
|
orderStatus,
|
||||||
orders,
|
orders,
|
||||||
payments,
|
|
||||||
refunds,
|
|
||||||
productReviews,
|
productReviews,
|
||||||
reservedCoupons,
|
reservedCoupons,
|
||||||
} from '../db/schema'
|
} from '../db/schema'
|
||||||
|
|
@ -221,8 +219,6 @@ export async function deleteUserAccount(userId: number) {
|
||||||
for (const order of userOrders) {
|
for (const order of userOrders) {
|
||||||
await tx.delete(orderItems).where(eq(orderItems.orderId, order.id))
|
await tx.delete(orderItems).where(eq(orderItems.orderId, order.id))
|
||||||
await tx.delete(orderStatus).where(eq(orderStatus.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(couponUsage).where(eq(couponUsage.orderId, order.id))
|
||||||
await tx.delete(complaints).where(eq(complaints.orderId, order.id))
|
await tx.delete(complaints).where(eq(complaints.orderId, order.id))
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -6,11 +6,9 @@ import {
|
||||||
addresses,
|
addresses,
|
||||||
productInfo,
|
productInfo,
|
||||||
productSkus,
|
productSkus,
|
||||||
paymentInfoTable,
|
|
||||||
coupons,
|
coupons,
|
||||||
couponUsage,
|
couponUsage,
|
||||||
cartItems,
|
cartItems,
|
||||||
refunds,
|
|
||||||
units,
|
units,
|
||||||
userDetails,
|
userDetails,
|
||||||
deliverySlotInfo,
|
deliverySlotInfo,
|
||||||
|
|
@ -41,8 +39,6 @@ export interface OrderWithRelations {
|
||||||
totalAmount: string
|
totalAmount: string
|
||||||
deliveryCharge: string
|
deliveryCharge: string
|
||||||
discountAmount: string
|
discountAmount: string
|
||||||
isCod: boolean
|
|
||||||
isOnlinePayment: boolean
|
|
||||||
isFlashDelivery: boolean
|
isFlashDelivery: boolean
|
||||||
userNotes: string | null
|
userNotes: string | null
|
||||||
orderGroupId: string | null
|
orderGroupId: string | null
|
||||||
|
|
@ -71,21 +67,12 @@ export interface OrderWithRelations {
|
||||||
slot: {
|
slot: {
|
||||||
deliveryTime: Date
|
deliveryTime: Date
|
||||||
} | null
|
} | null
|
||||||
paymentInfo: {
|
|
||||||
id: number
|
|
||||||
status: string
|
|
||||||
} | null
|
|
||||||
orderStatus: Array<{
|
orderStatus: Array<{
|
||||||
id: number
|
id: number
|
||||||
isCancelled: boolean
|
isCancelled: boolean
|
||||||
isDelivered: boolean
|
isDelivered: boolean
|
||||||
paymentStatus: string
|
|
||||||
cancelReason: string | null
|
cancelReason: string | null
|
||||||
}>
|
}>
|
||||||
refunds: Array<{
|
|
||||||
refundStatus: string
|
|
||||||
refundAmount: string | null
|
|
||||||
}>
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export type OrderDetailWithRelations = OrderWithRelations;
|
export type OrderDetailWithRelations = OrderWithRelations;
|
||||||
|
|
@ -337,29 +324,14 @@ export async function placeOrderTransaction(params: {
|
||||||
orderItems: Omit<typeof orderItems.$inferInsert, 'id'>[]
|
orderItems: Omit<typeof orderItems.$inferInsert, 'id'>[]
|
||||||
orderStatus: Omit<typeof orderStatus.$inferInsert, 'id'>
|
orderStatus: Omit<typeof orderStatus.$inferInsert, 'id'>
|
||||||
}>
|
}>
|
||||||
paymentMethod: 'online' | 'cod'
|
|
||||||
totalWithDelivery: number
|
totalWithDelivery: number
|
||||||
}): Promise<PlacedOrder[]> {
|
}): Promise<PlacedOrder[]> {
|
||||||
const { userId, ordersData, paymentMethod } = params
|
const { userId, ordersData } = params
|
||||||
|
|
||||||
return db.transaction(async (tx) => {
|
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'>[] =
|
const ordersToInsert: Omit<typeof orders.$inferInsert, 'id'>[] =
|
||||||
ordersData.map((od) => ({
|
ordersData.map((od) => ({
|
||||||
...od.order,
|
...od.order,
|
||||||
paymentInfoId: sharedPaymentInfoId,
|
|
||||||
}))
|
}))
|
||||||
|
|
||||||
const insertedOrders = await tx.insert(orders).values(ordersToInsert).returning()
|
const insertedOrders = await tx.insert(orders).values(ordersToInsert).returning()
|
||||||
|
|
@ -451,27 +423,14 @@ export async function getOrdersWithRelations(
|
||||||
deliveryTime: true,
|
deliveryTime: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
paymentInfo: {
|
|
||||||
columns: {
|
|
||||||
id: true,
|
|
||||||
status: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
orderStatus: {
|
orderStatus: {
|
||||||
columns: {
|
columns: {
|
||||||
id: true,
|
id: true,
|
||||||
isCancelled: true,
|
isCancelled: true,
|
||||||
isDelivered: true,
|
isDelivered: true,
|
||||||
paymentStatus: true,
|
|
||||||
cancelReason: true,
|
cancelReason: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
refunds: {
|
|
||||||
columns: {
|
|
||||||
refundStatus: true,
|
|
||||||
refundAmount: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
region: {
|
region: {
|
||||||
columns: {
|
columns: {
|
||||||
id: true,
|
id: true,
|
||||||
|
|
@ -572,34 +531,13 @@ export async function getOrderByIdWithRelations(
|
||||||
deliveryTime: true,
|
deliveryTime: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
paymentInfo: {
|
|
||||||
columns: {
|
|
||||||
id: true,
|
|
||||||
status: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
orderStatus: {
|
orderStatus: {
|
||||||
columns: {
|
columns: {
|
||||||
id: true,
|
id: true,
|
||||||
isCancelled: true,
|
isCancelled: true,
|
||||||
isDelivered: true,
|
isDelivered: true,
|
||||||
paymentStatus: true,
|
|
||||||
cancelReason: true,
|
cancelReason: true,
|
||||||
},
|
},
|
||||||
with: {
|
|
||||||
refundCoupon: {
|
|
||||||
columns: {
|
|
||||||
id: true,
|
|
||||||
couponCode: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
refunds: {
|
|
||||||
columns: {
|
|
||||||
refundStatus: true,
|
|
||||||
refundAmount: true,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
region: {
|
region: {
|
||||||
columns: {
|
columns: {
|
||||||
|
|
@ -741,8 +679,7 @@ export async function releaseCouponUsageIfGroupFullyCancelled(
|
||||||
export async function cancelOrderTransaction(
|
export async function cancelOrderTransaction(
|
||||||
orderId: number,
|
orderId: number,
|
||||||
statusId: number,
|
statusId: number,
|
||||||
reason: string,
|
reason: string
|
||||||
isCod: boolean
|
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
await db.transaction(async (tx) => {
|
await db.transaction(async (tx) => {
|
||||||
await tx
|
await tx
|
||||||
|
|
@ -755,13 +692,6 @@ export async function cancelOrderTransaction(
|
||||||
})
|
})
|
||||||
.where(eq(orderStatus.id, statusId))
|
.where(eq(orderStatus.id, statusId))
|
||||||
|
|
||||||
const refundStatus = isCod ? 'na' : 'pending'
|
|
||||||
|
|
||||||
await tx.insert(refunds).values({
|
|
||||||
orderId,
|
|
||||||
refundStatus,
|
|
||||||
})
|
|
||||||
|
|
||||||
await releaseCouponUsageIfGroupFullyCancelled(tx, orderId)
|
await releaseCouponUsageIfGroupFullyCancelled(tx, orderId)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
@ -854,11 +784,7 @@ export async function getOrdersByIdsWithFullData(
|
||||||
return orderChunks.flat() as unknown as OrderWithFullData[]
|
return orderChunks.flat() as unknown as OrderWithFullData[]
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface OrderWithCancellationData extends OrderWithFullData {
|
export type OrderWithCancellationData = OrderWithFullData
|
||||||
refunds: Array<{
|
|
||||||
refundStatus: string
|
|
||||||
}>
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getOrderByIdWithFullData(
|
export async function getOrderByIdWithFullData(
|
||||||
orderId: number
|
orderId: number
|
||||||
|
|
@ -894,11 +820,6 @@ export async function getOrderByIdWithFullData(
|
||||||
deliveryTime: true,
|
deliveryTime: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
refunds: {
|
|
||||||
columns: {
|
|
||||||
refundStatus: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
}) as Promise<OrderWithCancellationData | null>
|
}) as Promise<OrderWithCancellationData | null>
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,51 +0,0 @@
|
||||||
import { db } from '../db/db_index'
|
|
||||||
import { orders, payments, orderStatus } from '../db/schema'
|
|
||||||
import { eq } from 'drizzle-orm'
|
|
||||||
|
|
||||||
export async function getOrderById(orderId: number) {
|
|
||||||
return db.query.orders.findFirst({
|
|
||||||
where: eq(orders.id, orderId),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getPaymentByOrderId(orderId: number) {
|
|
||||||
return db.query.payments.findFirst({
|
|
||||||
where: eq(payments.orderId, orderId),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getPaymentByMerchantOrderId(merchantOrderId: string) {
|
|
||||||
return db.query.payments.findFirst({
|
|
||||||
where: eq(payments.merchantOrderId, merchantOrderId),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function updatePaymentSuccess(merchantOrderId: string, payload: unknown) {
|
|
||||||
const [updatedPayment] = await db
|
|
||||||
.update(payments)
|
|
||||||
.set({
|
|
||||||
status: 'success',
|
|
||||||
payload,
|
|
||||||
})
|
|
||||||
.where(eq(payments.merchantOrderId, merchantOrderId))
|
|
||||||
.returning({
|
|
||||||
id: payments.id,
|
|
||||||
orderId: payments.orderId,
|
|
||||||
})
|
|
||||||
|
|
||||||
return updatedPayment || null
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function updateOrderPaymentStatus(orderId: number, status: 'pending' | 'success' | 'cod' | 'failed') {
|
|
||||||
await db
|
|
||||||
.update(orderStatus)
|
|
||||||
.set({ paymentStatus: status })
|
|
||||||
.where(eq(orderStatus.orderId, orderId))
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function markPaymentFailed(paymentId: number) {
|
|
||||||
await db
|
|
||||||
.update(payments)
|
|
||||||
.set({ status: 'failed' })
|
|
||||||
.where(eq(payments.id, paymentId))
|
|
||||||
}
|
|
||||||
|
|
@ -43,10 +43,6 @@ export type AdminOrderRow = Omit<PlacedOrder, 'orderGroupId' | 'orderGroupPropor
|
||||||
orderGroupProportion: string | null
|
orderGroupProportion: string | null
|
||||||
}
|
}
|
||||||
|
|
||||||
export type PaymentStatus = 'pending' | 'success' | 'cod' | 'failed'
|
|
||||||
|
|
||||||
export type RefundStatus = 'success' | 'pending' | 'failed' | 'none' | 'na' | 'processed'
|
|
||||||
|
|
||||||
export interface AdminOrderStatusRecord {
|
export interface AdminOrderStatusRecord {
|
||||||
id: number;
|
id: number;
|
||||||
orderTime: Date;
|
orderTime: Date;
|
||||||
|
|
@ -57,22 +53,10 @@ export interface AdminOrderStatusRecord {
|
||||||
isCancelled: boolean;
|
isCancelled: boolean;
|
||||||
cancelReason: string | null;
|
cancelReason: string | null;
|
||||||
isCancelledByAdmin: boolean | null;
|
isCancelledByAdmin: boolean | null;
|
||||||
paymentStatus: PaymentStatus;
|
|
||||||
cancellationUserNotes: string | null;
|
cancellationUserNotes: string | null;
|
||||||
cancellationAdminNotes: string | null;
|
cancellationAdminNotes: string | null;
|
||||||
cancellationReviewed: boolean;
|
cancellationReviewed: boolean;
|
||||||
cancellationReviewedAt: Date | null;
|
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 {
|
export interface AdminOrderDetailsAddress {
|
||||||
|
|
@ -108,12 +92,6 @@ export interface AdminOrderDetailsItem extends AdminOrderItemCore {
|
||||||
unit?: string;
|
unit?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AdminOrderDetailsPayment {
|
|
||||||
status: string;
|
|
||||||
gateway: string;
|
|
||||||
merchantOrderId: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AdminOrderDetailsCouponData {
|
export interface AdminOrderDetailsCouponData {
|
||||||
couponCode: string;
|
couponCode: string;
|
||||||
couponDescription: string;
|
couponDescription: string;
|
||||||
|
|
@ -129,8 +107,6 @@ export interface AdminOrderDetails {
|
||||||
customerMobile: string | null;
|
customerMobile: string | null;
|
||||||
address: AdminOrderDetailsAddress;
|
address: AdminOrderDetailsAddress;
|
||||||
slotInfo: AdminOrderDetailsSlotInfo | null;
|
slotInfo: AdminOrderDetailsSlotInfo | null;
|
||||||
isCod: boolean;
|
|
||||||
isOnlinePayment: boolean;
|
|
||||||
totalAmount: number;
|
totalAmount: number;
|
||||||
deliveryCharge: number;
|
deliveryCharge: number;
|
||||||
adminNotes: string | null;
|
adminNotes: string | null;
|
||||||
|
|
@ -140,19 +116,13 @@ export interface AdminOrderDetails {
|
||||||
isPackaged: boolean;
|
isPackaged: boolean;
|
||||||
isDelivered: boolean;
|
isDelivered: boolean;
|
||||||
items: AdminOrderDetailsItem[];
|
items: AdminOrderDetailsItem[];
|
||||||
payment: AdminOrderDetailsPayment | null;
|
|
||||||
paymentInfo: AdminOrderDetailsPayment | null;
|
|
||||||
cancelReason: string | null;
|
cancelReason: string | null;
|
||||||
cancellationReviewed: boolean;
|
cancellationReviewed: boolean;
|
||||||
isRefundDone: boolean;
|
|
||||||
refundStatus: RefundStatus | null;
|
|
||||||
refundAmount: number | null;
|
|
||||||
couponData: AdminOrderDetailsCouponData | null;
|
couponData: AdminOrderDetailsCouponData | null;
|
||||||
couponCode: string | null;
|
couponCode: string | null;
|
||||||
couponDescription: string | null;
|
couponDescription: string | null;
|
||||||
discountAmount: number | null;
|
discountAmount: number | null;
|
||||||
orderStatus: AdminOrderStatusRecord | null;
|
orderStatus: AdminOrderStatusRecord | null;
|
||||||
refundRecord: AdminRefundRecord | null;
|
|
||||||
isFlashDelivery: boolean;
|
isFlashDelivery: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -190,9 +160,6 @@ export interface AdminSlotOrder {
|
||||||
status: 'pending' | 'delivered' | 'cancelled';
|
status: 'pending' | 'delivered' | 'cancelled';
|
||||||
isPackaged: boolean;
|
isPackaged: boolean;
|
||||||
isDelivered: boolean;
|
isDelivered: boolean;
|
||||||
isCod: boolean;
|
|
||||||
paymentMode: 'COD' | 'Online';
|
|
||||||
paymentStatus: PaymentStatus;
|
|
||||||
slotId: number | null;
|
slotId: number | null;
|
||||||
adminNotes: string | null;
|
adminNotes: string | null;
|
||||||
userNotes: string | null;
|
userNotes: string | null;
|
||||||
|
|
@ -227,7 +194,6 @@ export interface AdminOrderListItem {
|
||||||
status: 'pending' | 'delivered' | 'cancelled';
|
status: 'pending' | 'delivered' | 'cancelled';
|
||||||
isPackaged: boolean;
|
isPackaged: boolean;
|
||||||
isDelivered: boolean;
|
isDelivered: boolean;
|
||||||
isCod: boolean;
|
|
||||||
isFlashDelivery: boolean;
|
isFlashDelivery: boolean;
|
||||||
userNotes: string | null;
|
userNotes: string | null;
|
||||||
adminNotes: string | null;
|
adminNotes: string | null;
|
||||||
|
|
|
||||||
|
|
@ -14,9 +14,6 @@ export interface PlacedOrder {
|
||||||
slotId: number | null
|
slotId: number | null
|
||||||
totalAmount: string
|
totalAmount: string
|
||||||
deliveryCharge: string
|
deliveryCharge: string
|
||||||
isCod: boolean
|
|
||||||
isOnlinePayment: boolean
|
|
||||||
paymentInfoId: number | null
|
|
||||||
readableId: number
|
readableId: number
|
||||||
userNotes: string | null
|
userNotes: string | null
|
||||||
orderGroupId: string
|
orderGroupId: string
|
||||||
|
|
|
||||||
|
|
@ -116,15 +116,6 @@ export interface OrderItem {
|
||||||
is_package_verified: boolean;
|
is_package_verified: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Payment {
|
|
||||||
id: number;
|
|
||||||
orderId: number;
|
|
||||||
paymentStatus: string;
|
|
||||||
paymentMethod: string;
|
|
||||||
amount: string;
|
|
||||||
createdAt: Date;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface UserBannersResponse {
|
export interface UserBannersResponse {
|
||||||
banners: UserBanner[];
|
banners: UserBanner[];
|
||||||
}
|
}
|
||||||
|
|
@ -350,15 +341,6 @@ export interface UserSlotsWithProductsResponse extends UserSlotsResponse {
|
||||||
productAvailability: UserSlotAvailability[];
|
productAvailability: UserSlotAvailability[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UserPaymentOrderResponse {
|
|
||||||
razorpayOrderId: string | number;
|
|
||||||
key: string | undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type UserPaymentVerifyResponse = MessageResponse
|
|
||||||
|
|
||||||
export type UserPaymentFailResponse = MessageResponse
|
|
||||||
|
|
||||||
export interface UserAuthProfile {
|
export interface UserAuthProfile {
|
||||||
id: number;
|
id: number;
|
||||||
name?: string | null;
|
name?: string | null;
|
||||||
|
|
@ -515,12 +497,8 @@ export interface UserOrderSummary {
|
||||||
deliveryDate?: string;
|
deliveryDate?: string;
|
||||||
orderStatus: string;
|
orderStatus: string;
|
||||||
cancelReason: string | null;
|
cancelReason: string | null;
|
||||||
paymentMode: string;
|
|
||||||
totalAmount: number;
|
totalAmount: number;
|
||||||
deliveryCharge: number;
|
deliveryCharge: number;
|
||||||
paymentStatus: string;
|
|
||||||
refundStatus: string;
|
|
||||||
refundAmount: number | null;
|
|
||||||
userNotes: string | null;
|
userNotes: string | null;
|
||||||
items: UserOrderItemSummary[];
|
items: UserOrderItemSummary[];
|
||||||
isFlashDelivery: boolean;
|
isFlashDelivery: boolean;
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,6 @@ import { StorageService } from "./src/services/StorageService";
|
||||||
import {
|
import {
|
||||||
ROLE_NAMES,
|
ROLE_NAMES,
|
||||||
} from "./src/lib/constants";
|
} from "./src/lib/constants";
|
||||||
import { REFUND_STATUS } from "./src/lib/const-strs";
|
|
||||||
import { colors, colorsType } from "./src/lib/theme-colors";
|
import { colors, colorsType } from "./src/lib/theme-colors";
|
||||||
import { theme } from "./src/theme";
|
import { theme } from "./src/theme";
|
||||||
import MyButton from "./src/components/button";
|
import MyButton from "./src/components/button";
|
||||||
|
|
@ -78,7 +77,6 @@ export {
|
||||||
useDrawerTitle,
|
useDrawerTitle,
|
||||||
useMarkDataFetchers,
|
useMarkDataFetchers,
|
||||||
StorageServiceCasual,
|
StorageServiceCasual,
|
||||||
REFUND_STATUS,
|
|
||||||
DateTimePickerMod,
|
DateTimePickerMod,
|
||||||
RefreshProvider,
|
RefreshProvider,
|
||||||
useRefresh,
|
useRefresh,
|
||||||
|
|
|
||||||
|
|
@ -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 NOTIF_PERMISSION_DENIED = "Permission not granted to get push token for push notification!";
|
||||||
export const REFRESH_EVENT = 'refresh_event';
|
export const REFRESH_EVENT = 'refresh_event';
|
||||||
|
|
||||||
export const REFUND_STATUS = {
|
|
||||||
PENDING: 'pending',
|
|
||||||
NOT_APPLICABLE: 'na',
|
|
||||||
PROCESSING: 'initiated',
|
|
||||||
SUCCESS: 'success',
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
//copy pasted from backend
|
//copy pasted from backend
|
||||||
export const CAR_IMAGE_COMMENT = "car_body";
|
export const CAR_IMAGE_COMMENT = "car_body";
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue