This commit is contained in:
shafi54 2026-02-21 18:13:46 +05:30
parent b2a35176dd
commit a875e63751
16 changed files with 3958 additions and 38 deletions

View file

@ -82,6 +82,16 @@ export default function OrderDetails() {
},
});
const removeDeliveryChargeMutation = trpc.admin.order.removeDeliveryCharge.useMutation({
onSuccess: () => {
Alert.alert("Success", "Delivery charge has been removed");
refetch();
},
onError: (error: any) => {
Alert.alert("Error", error.message || "Failed to remove delivery charge");
},
});
if (isLoading) {
return (
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
@ -508,6 +518,40 @@ export default function OrderDetails() {
-{discountAmount}
</MyText>
</View>
)}
{order.deliveryCharge > 0 && (
<View style={tw`flex-row justify-between items-center mb-2`}>
<View style={tw`flex-row items-center`}>
<MyText style={tw`text-gray-600 font-medium`}>
Delivery Charge
</MyText>
<TouchableOpacity
onPress={() => {
Alert.alert(
'Remove Delivery Cost',
'Are you sure you want to remove the delivery cost from this order?',
[
{ text: 'Cancel', style: 'cancel' },
{
text: 'Remove',
style: 'destructive',
onPress: () => removeDeliveryChargeMutation.mutate({ orderId: order.id }),
},
]
);
}}
disabled={removeDeliveryChargeMutation.isPending}
style={tw`ml-2 px-2 py-1 bg-red-100 rounded-md`}
>
<MyText style={tw`text-xs font-bold text-red-600`}>
{removeDeliveryChargeMutation.isPending ? 'Removing...' : 'Remove'}
</MyText>
</TouchableOpacity>
</View>
<MyText style={tw`text-gray-600 font-medium`}>
{order.deliveryCharge}
</MyText>
</View>
)}
<View style={tw`flex-row justify-between items-center pt-2 border-t border-gray-200`}>
<View style={tw`flex-row items-center`}>

View file

@ -1,7 +1,7 @@
import React, { useState } from 'react';
import { MaterialCommunityIcons, Entypo } from '@expo/vector-icons';
import { View, TouchableOpacity, FlatList, Alert } from 'react-native';
import { AppContainer, MyText, tw, MyFlatList , BottomDialog, MyTouchableOpacity } from 'common-ui';
import { View, TouchableOpacity, FlatList, Alert, ActivityIndicator } from 'react-native';
import { AppContainer, MyText, tw, MyFlatList , BottomDialog, MyTouchableOpacity, Checkbox } from 'common-ui';
import { trpc } from '@/src/trpc-client';
import { useRouter } from 'expo-router';
import dayjs from 'dayjs';
@ -12,6 +12,7 @@ interface SlotItemProps {
router: any;
setDialogProducts: React.Dispatch<React.SetStateAction<any[]>>;
setDialogOpen: React.Dispatch<React.SetStateAction<boolean>>;
refetch: () => void;
}
const SlotItemComponent: React.FC<SlotItemProps> = ({
@ -19,6 +20,7 @@ const SlotItemComponent: React.FC<SlotItemProps> = ({
router,
setDialogProducts,
setDialogOpen,
refetch,
}) => {
const [menuOpen, setMenuOpen] = useState(false);
const slotProducts = slot.products?.map((p: any) => p.name).filter(Boolean) || [];
@ -28,6 +30,29 @@ const SlotItemComponent: React.FC<SlotItemProps> = ({
const statusColor = isActive ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700';
const statusText = isActive ? 'Active' : 'Inactive';
const updateSlotCapacity = trpc.admin.slots.updateSlotCapacity.useMutation();
const handleCapacityToggle = () => {
updateSlotCapacity.mutate(
{ slotId: slot.id, isCapacityFull: !slot.isCapacityFull },
{
onSuccess: () => {
setMenuOpen(false);
refetch();
Alert.alert(
'Success',
slot.isCapacityFull
? 'Slot capacity reset. It will now be visible to users.'
: 'Slot marked as full capacity. It will be hidden from users.'
);
},
onError: (error: any) => {
Alert.alert('Error', error.message || 'Failed to update slot capacity');
},
}
);
};
return (
<TouchableOpacity
onPress={() => router.push(`/(drawer)/slots/slot-details?slotId=${slot.id}`)}
@ -58,6 +83,11 @@ const SlotItemComponent: React.FC<SlotItemProps> = ({
<View style={tw`px-3 py-1 rounded-full ${statusColor.split(' ')[0]}`}>
<MyText style={tw`text-xs font-bold ${statusColor.split(' ')[1]}`}>{statusText}</MyText>
</View>
{slot.isCapacityFull && (
<View style={tw`px-2 py-1 rounded-full bg-red-500 ml-2`}>
<MyText style={tw`text-xs font-bold text-white`}>FULL</MyText>
</View>
)}
<TouchableOpacity
onPress={() => setMenuOpen(true)}
style={tw`ml-2 p-1`}
@ -72,6 +102,48 @@ const SlotItemComponent: React.FC<SlotItemProps> = ({
<BottomDialog open={menuOpen} onClose={() => setMenuOpen(false)}>
<View style={tw`p-4`}>
<MyText style={tw`text-lg font-bold mb-4`}>Slot #{slot.id} Actions</MyText>
{/* Capacity Toggle */}
<TouchableOpacity
onPress={handleCapacityToggle}
disabled={updateSlotCapacity.isPending}
style={tw`py-4 border-b border-gray-200`}
>
<View style={tw`flex-row items-center justify-between`}>
<View style={tw`flex-row items-center flex-1`}>
{updateSlotCapacity.isPending ? (
<ActivityIndicator size="small" color="#EF4444" style={tw`mr-3`} />
) : (
<MaterialCommunityIcons
name={slot.isCapacityFull ? "package-variant-closed" : "package-variant"}
size={20}
color={slot.isCapacityFull ? "#EF4444" : "#4B5563"}
style={tw`mr-3`}
/>
)}
<View>
<MyText style={tw`text-base text-gray-800`}>Mark as Full Capacity</MyText>
<MyText style={tw`text-xs text-gray-500 mt-0.5`}>
{slot.isCapacityFull
? "Slot is hidden from users"
: "Hidden from users when full"}
</MyText>
</View>
</View>
{updateSlotCapacity.isPending ? (
<ActivityIndicator size="small" color="#EF4444" />
) : (
<Checkbox
checked={slot.isCapacityFull}
onPress={handleCapacityToggle}
size={22}
fillColor="#EF4444"
checkColor="#FFFFFF"
/>
)}
</View>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
setMenuOpen(false);
@ -193,6 +265,7 @@ export default function Slots() {
router={router}
setDialogProducts={setDialogProducts}
setDialogOpen={setDialogOpen}
refetch={refetch}
/>
)}
contentContainerStyle={tw`p-4`}

View file

@ -0,0 +1 @@
ALTER TABLE "mf"."delivery_slot_info" ADD COLUMN "is_capacity_full" boolean DEFAULT false NOT NULL;

File diff suppressed because it is too large Load diff

View file

@ -519,6 +519,13 @@
"when": 1770561175889,
"tag": "0073_faithful_gravity",
"breakpoints": true
},
{
"idx": 74,
"version": "7",
"when": 1771674555093,
"tag": "0074_outgoing_black_cat",
"breakpoints": true
}
]
}

View file

@ -192,6 +192,7 @@ export const deliverySlotInfo = mf.table('delivery_slot_info', {
freezeTime: timestamp('freeze_time').notNull(),
isActive: boolean('is_active').notNull().default(true),
isFlash: boolean('is_flash').notNull().default(false),
isCapacityFull: boolean('is_capacity_full').notNull().default(false),
deliverySequence: jsonb('delivery_sequence').$defaultFn(() => {}),
groupIds: jsonb('group_ids').$defaultFn(() => []),
});

View file

@ -21,7 +21,7 @@ interface Product {
productQuantity: number;
isFlashAvailable: boolean;
flashPrice: string | null;
deliverySlots: Array<{ id: number; deliveryTime: Date; freezeTime: Date }>;
deliverySlots: Array<{ id: number; deliveryTime: Date; freezeTime: Date; isCapacityFull: boolean }>;
specialDeals: Array<{ quantity: string; price: string; validTill: Date }>;
productTags: string[];
}
@ -57,19 +57,21 @@ export async function initializeProducts(): Promise<void> {
});
const storeMap = new Map(allStores.map(s => [s.id, s]));
// Fetch all delivery slots
// Fetch all delivery slots (excluding full capacity slots)
const allDeliverySlots = await db
.select({
productId: productSlots.productId,
id: deliverySlotInfo.id,
deliveryTime: deliverySlotInfo.deliveryTime,
freezeTime: deliverySlotInfo.freezeTime,
isCapacityFull: deliverySlotInfo.isCapacityFull,
})
.from(productSlots)
.innerJoin(deliverySlotInfo, eq(productSlots.slotId, deliverySlotInfo.id))
.where(
and(
eq(deliverySlotInfo.isActive, true),
eq(deliverySlotInfo.isCapacityFull, false),
gt(deliverySlotInfo.deliveryTime, sql`NOW()`)
)
);
@ -132,7 +134,7 @@ export async function initializeProducts(): Promise<void> {
productQuantity: product.productQuantity,
isFlashAvailable: product.isFlashAvailable,
flashPrice: product.flashPrice?.toString() || null,
deliverySlots: deliverySlots.map(s => ({ id: s.id, deliveryTime: s.deliveryTime, freezeTime: s.freezeTime })),
deliverySlots: deliverySlots.map(s => ({ id: s.id, deliveryTime: s.deliveryTime, freezeTime: s.freezeTime, isCapacityFull: s.isCapacityFull })),
specialDeals: specialDeals.map(d => ({ quantity: d.quantity.toString(), price: d.price.toString(), validTill: d.validTill })),
productTags: productTags,
};

View file

@ -11,6 +11,7 @@ interface SlotWithProducts {
deliveryTime: Date;
freezeTime: Date;
isActive: boolean;
isCapacityFull: boolean;
products: Array<{
id: number;
name: string;
@ -30,6 +31,7 @@ interface SlotInfo {
id: number;
deliveryTime: Date;
freezeTime: Date;
isCapacityFull: boolean;
}
export async function initializeSlotStore(): Promise<void> {
@ -80,6 +82,7 @@ export async function initializeSlotStore(): Promise<void> {
deliveryTime: slot.deliveryTime,
freezeTime: slot.freezeTime,
isActive: slot.isActive,
isCapacityFull: slot.isCapacityFull,
products: await Promise.all(
slot.productSlots.map(async (productSlot) => ({
id: productSlot.product.id,
@ -118,6 +121,7 @@ export async function initializeSlotStore(): Promise<void> {
id: slot.id,
deliveryTime: slot.deliveryTime,
freezeTime: slot.freezeTime,
isCapacityFull: slot.isCapacityFull,
});
}
}
@ -225,7 +229,9 @@ export async function getMultipleProductsSlots(productIds: number[]): Promise<Re
for (let i = 0; i < productIds.length; i++) {
const data = productsData[i];
if (data) {
result[productIds[i]] = JSON.parse(data) as SlotInfo[];
const slots = JSON.parse(data) as SlotInfo[];
// Filter out slots that are at full capacity
result[productIds[i]] = slots.filter(slot => !slot.isCapacityFull);
}
}

View file

@ -325,7 +325,8 @@ export const orderRouter = router({
: null,
isCod: orderData.isCod,
isOnlinePayment: orderData.isOnlinePayment,
totalAmount: orderData.totalAmount,
totalAmount: parseFloat(orderData.totalAmount?.toString() || '0') - parseFloat(orderData.deliveryCharge?.toString() || '0'),
deliveryCharge: parseFloat(orderData.deliveryCharge?.toString() || '0'),
adminNotes: orderData.adminNotes,
userNotes: orderData.userNotes,
createdAt: orderData.createdAt,
@ -460,6 +461,34 @@ export const orderRouter = router({
return { success: true };
}),
removeDeliveryCharge: protectedProcedure
.input(z.object({ orderId: z.number() }))
.mutation(async ({ input }) => {
const { orderId } = input;
const order = await db.query.orders.findFirst({
where: eq(orders.id, orderId),
});
if (!order) {
throw new Error('Order not found');
}
const currentDeliveryCharge = parseFloat(order.deliveryCharge?.toString() || '0');
const currentTotalAmount = parseFloat(order.totalAmount?.toString() || '0');
const newTotalAmount = currentTotalAmount - currentDeliveryCharge;
await db
.update(orders)
.set({
deliveryCharge: '0',
totalAmount: newTotalAmount.toString()
})
.where(eq(orders.id, orderId));
return { success: true, message: 'Delivery charge removed' };
}),
getSlotOrders: protectedProcedure
.input(getSlotOrdersSchema)
.query(async ({ input }) => {

View file

@ -574,4 +574,36 @@ export const slotsRouter = router({
message: "Delivery sequence updated successfully",
};
}),
updateSlotCapacity: protectedProcedure
.input(z.object({
slotId: z.number(),
isCapacityFull: z.boolean(),
}))
.mutation(async ({ input, ctx }) => {
if (!ctx.staffUser?.id) {
throw new TRPCError({ code: "UNAUTHORIZED", message: "Access denied" });
}
const { slotId, isCapacityFull } = input;
const [updatedSlot] = await db
.update(deliverySlotInfo)
.set({ isCapacityFull })
.where(eq(deliverySlotInfo.id, slotId))
.returning();
if (!updatedSlot) {
throw new ApiError("Slot not found", 404);
}
// Reinitialize stores to reflect changes
await initializeAllStores();
return {
success: true,
slot: updatedSlot,
message: `Slot ${isCapacityFull ? 'marked as full capacity' : 'capacity reset'}`,
};
}),
});

View file

@ -17,6 +17,7 @@ export const getNextDeliveryDate = async (productId: number): Promise<Date | nul
and(
eq(productSlots.productId, productId),
eq(deliverySlotInfo.isActive, true),
eq(deliverySlotInfo.isCapacityFull, false),
gt(deliverySlotInfo.deliveryTime, sql`NOW()`)
)
)

View file

@ -27,6 +27,7 @@ import { RazorpayPaymentService } from "../../lib/payments-utils";
import { getNextDeliveryDate } from "../common-apis/common";
import { CONST_KEYS, getConstant, getConstants } from "../../lib/const-store";
import { publishFormattedOrder, publishCancellation } from "../../lib/post-order-handler";
import { getSlotById } from "../../stores/slot-store";
const validateAndGetCoupon = async (
@ -404,6 +405,17 @@ export const orderRouter = router({
}
}
// Check if any selected slot is at full capacity (only for regular delivery)
if (!isFlashDelivery) {
const slotIds = [...new Set(selectedItems.filter(i => i.slotId !== null).map(i => i.slotId as number))];
for (const slotId of slotIds) {
const slot = await getSlotById(slotId);
if (slot?.isCapacityFull) {
throw new ApiError("Selected delivery slot is at full capacity. Please choose another slot.", 403);
}
}
}
let processedItems = selectedItems;
// Handle flash delivery slot resolution

View file

@ -47,10 +47,10 @@ export const productRouter = router({
const cachedProduct = await getProductByIdFromCache(productId);
if (cachedProduct) {
// Filter delivery slots to only include those with future freeze times
// Filter delivery slots to only include those with future freeze times and not at full capacity
const currentTime = new Date();
const filteredSlots = cachedProduct.deliverySlots.filter(slot =>
dayjs(slot.freezeTime).isAfter(currentTime)
dayjs(slot.freezeTime).isAfter(currentTime) && !slot.isCapacityFull
);
return {
@ -107,6 +107,7 @@ export const productRouter = router({
and(
eq(productSlots.productId, productId),
eq(deliverySlotInfo.isActive, true),
eq(deliverySlotInfo.isCapacityFull, false),
gt(deliverySlotInfo.deliveryTime, sql`NOW()`),
gt(deliverySlotInfo.freezeTime, sql`NOW()`)
)

View file

@ -48,7 +48,7 @@ export const slotsRouter = router({
const allSlots = await getAllSlotsFromCache();
const currentTime = new Date();
const validSlots = allSlots
.filter((slot) => dayjs(slot.freezeTime).isAfter(currentTime))
.filter((slot) => dayjs(slot.freezeTime).isAfter(currentTime) && !slot.isCapacityFull)
.sort((a, b) => dayjs(a.deliveryTime).valueOf() - dayjs(b.deliveryTime).valueOf());
return {

View file

@ -11,6 +11,19 @@ import { useGetEssentialConsts } from '@/src/api-hooks/essential-consts.api';
import dayjs from 'dayjs';
import { SafeAreaView } from 'react-native-safe-area-context';
const formatTimeRange = (deliveryTime: string) => {
const time = dayjs(deliveryTime);
const endTime = time.add(1, 'hour');
const startPeriod = time.format('A');
const endPeriod = endTime.format('A');
if (startPeriod === endPeriod) {
return `${time.format('h')}-${endTime.format('h')} ${startPeriod}`;
} else {
return `${time.format('h:mm')} ${startPeriod} - ${endTime.format('h:mm')} ${endPeriod}`;
}
};
export default function AddToCartDialog() {
const router = useRouter();
const { addedToCartProduct, clearAddedToCartProduct } = useCartStore();
@ -158,7 +171,7 @@ export default function AddToCartDialog() {
<MaterialIcons name="local-shipping" size={20} color="#3B82F6" style={tw`mt-0.5`} />
<View style={tw`ml-3 flex-1`}>
<MyText style={tw`text-gray-900 font-bold text-base`}>
{dayjs(slot.deliveryTime).format('ddd, DD MMM • h:mm A')}
{dayjs(slot.deliveryTime).format('ddd, DD MMM • ')}{formatTimeRange(slot.deliveryTime)}
</MyText>
</View>
{selectedSlotId === slot.id ? (

View file

@ -63,7 +63,7 @@ const isDevMode = Constants.executionEnvironment !== "standalone";
// const BASE_API_URL = API_URL;
// const BASE_API_URL = 'http://10.0.2.2:4000';
// const BASE_API_URL = 'http://192.168.100.101:4000';
const BASE_API_URL = 'http://192.168.1.6:4000';
const BASE_API_URL = 'http://192.168.100.105:4000';
// let BASE_API_URL = "https://mf.freshyo.in";
// let BASE_API_URL = 'http://192.168.100.104:4000';
// let BASE_API_URL = 'http://192.168.29.176:4000';