Compare commits

..

No commits in common. "df114be9128f176f653359b475f3b7437a55d1a1" and "88985c95723477a516df8a3e86be9fd365803b64" have entirely different histories.

32 changed files with 79 additions and 262 deletions

View file

@ -1,13 +1,11 @@
import './notif-job';
import { initializeAllStores } from '../stores/store-initializer';
import { startOrderHandler, publishOrder } from './post-order-handler';
/**
* Initialize all application services
* This function handles initialization of:
* - Role Manager (fetches and caches all roles)
* - Const Store (syncs constants from DB to Redis)
* - Post Order Handler (Redis Pub/Sub subscriber)
* - Other services can be added here in the future
*/
export const initFunc = async (): Promise<void> => {
@ -20,25 +18,6 @@ export const initFunc = async (): Promise<void> => {
// Notification queue and worker are initialized via import
console.log('Notification queue and worker initialized');
// Start post order handler (Redis Pub/Sub subscriber)
await startOrderHandler();
// Wait a moment for subscription to be ready, then publish demo order
// setTimeout(async () => {
// console.log('Publishing demo order for testing...');
// await publishOrder({
// orders: [{
// deliveryTime: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(), // Tomorrow
// orderPlaceTime: new Date().toISOString(),
// totalAmount: 550,
// orderItems: [
// { productName: "Chicken Breast", quantity: 2 },
// { productName: "Mutton Curry Cut", quantity: 1 },
// ],
// }],
// });
// }, 20000);
console.log('Application initialization completed successfully');
} catch (error) {
console.error('Application initialization failed:', error);

View file

@ -1,146 +0,0 @@
import redisClient from './redis-client';
import { sendTelegramMessage } from './telegram-service';
const ORDER_CHANNEL = 'orders:placed';
interface SimplifiedOrderItem {
productName: string;
quantity: number;
}
interface SimplifiedOrder {
deliveryTime: string;
orderPlaceTime: string;
totalAmount: number;
orderItems: SimplifiedOrderItem[];
}
interface FormattedOrderData {
orders: SimplifiedOrder[];
}
/**
* Format order details for Telegram message
* @param orderData The order data to format
* @returns Formatted message string
*/
const formatOrderMessage = (orderData: FormattedOrderData): string => {
let message = '🛒 <b>New Order Placed</b>\n\n';
orderData.orders.forEach((order, index) => {
if (orderData.orders.length > 1) {
message += `<b>Order ${index + 1}</b>\n`;
}
message += '📦 <b>Items:</b>\n';
order.orderItems.forEach(item => {
message += `${item.productName} x${item.quantity}\n`;
});
message += `\n💰 <b>Total:</b> ₹${order.totalAmount}\n`;
message += `🚚 <b>Delivery:</b> ${new Date(order.deliveryTime).toLocaleString()}\n`;
message += `⏰ <b>Ordered:</b> ${new Date(order.orderPlaceTime).toLocaleString()}\n`;
if (index < orderData.orders.length - 1) {
message += '\n---\n\n';
}
});
return message;
};
/**
* Start the post order handler
* Subscribes to the orders:placed channel and sends to Telegram
*/
export const startOrderHandler = async (): Promise<void> => {
try {
console.log('Starting post order handler...');
await redisClient.subscribe(ORDER_CHANNEL, async (message: string) => {
try {
const orderDetails = JSON.parse(message);
console.log('New order received, sending to Telegram...');
const telegramMessage = formatOrderMessage(orderDetails);
await sendTelegramMessage(telegramMessage);
} catch (error) {
console.error('Failed to process order message:', error);
// Still try to send raw message to Telegram if parsing fails
await sendTelegramMessage(`⚠️ Error parsing order: ${message}`);
}
});
console.log('Post order handler started successfully');
} catch (error) {
console.error('Failed to start post order handler:', error);
throw error;
}
};
/**
* Stop the post order handler
*/
export const stopOrderHandler = async (): Promise<void> => {
try {
await redisClient.unsubscribe(ORDER_CHANNEL);
console.log('Post order handler stopped');
} catch (error) {
console.error('Error stopping post order handler:', error);
}
};
/**
* Publish order details to the queue
* @param orderDetails Full order details to publish
*/
export const publishOrder = async (orderDetails: FormattedOrderData): Promise<boolean> => {
try {
const message = JSON.stringify(orderDetails);
await redisClient.publish(ORDER_CHANNEL, message);
return true;
} catch (error) {
console.error('Failed to publish order:', error);
return false;
}
};
/**
* Mould raw order data into simplified format and publish
* @param createdOrders Array of created orders from the database
* @param ordersBySlot Map of slotId to items with product info
* @returns Promise<boolean> indicating success or failure
*/
export const publishFormattedOrder = async (
createdOrders: any[],
ordersBySlot: Map<number | null, any[]>
): Promise<boolean> => {
try {
const simplifiedOrders: SimplifiedOrder[] = createdOrders.map(order => {
// Get items for this order from ordersBySlot
const slotItems = ordersBySlot.get(order.slotId) || [];
// Map items to simplified format
const orderItems: SimplifiedOrderItem[] = slotItems.map(item => ({
productName: item.product?.name || 'Unknown Product',
quantity: item.quantity,
}));
return {
deliveryTime: order.slot?.deliveryTime?.toISOString() || order.deliveryDate?.toISOString() || new Date().toISOString(),
orderPlaceTime: order.createdAt?.toISOString() || new Date().toISOString(),
totalAmount: parseFloat(order.totalAmount?.toString() || '0'),
orderItems,
};
});
const formattedData: FormattedOrderData = {
orders: simplifiedOrders,
};
return await publishOrder(formattedData);
} catch (error) {
console.error('Failed to format and publish order:', error);
return false;
}
};

View file

@ -3,7 +3,6 @@ import { redisUrl } from './env-exporter';
class RedisClient {
private client: RedisClientType;
private subscriberClient: RedisClientType | null = null;
private isConnected: boolean = false;
constructor() {
@ -72,48 +71,10 @@ class RedisClient {
return await this.client.MGET(keys);
}
// Publish message to a channel
async publish(channel: string, message: string): Promise<number> {
return await this.client.publish(channel, message);
}
// Subscribe to a channel with callback
async subscribe(channel: string, callback: (message: string) => void): Promise<void> {
if (!this.subscriberClient) {
this.subscriberClient = createClient({
url: redisUrl,
});
this.subscriberClient.on('error', (err) => {
console.error('Redis Subscriber Error:', err);
});
this.subscriberClient.on('connect', () => {
console.log('Redis Subscriber Connected');
});
await this.subscriberClient.connect();
}
await this.subscriberClient.subscribe(channel, callback);
console.log(`Subscribed to channel: ${channel}`);
}
// Unsubscribe from a channel
async unsubscribe(channel: string): Promise<void> {
if (this.subscriberClient) {
await this.subscriberClient.unsubscribe(channel);
console.log(`Unsubscribed from channel: ${channel}`);
}
}
disconnect(): void {
if (this.isConnected) {
this.client.disconnect();
}
if (this.subscriberClient) {
this.subscriberClient.disconnect();
}
}
get isClientConnected(): boolean {
@ -124,4 +85,4 @@ class RedisClient {
const redisClient = new RedisClient();
export default redisClient;
export { RedisClient };
export { RedisClient };

View file

@ -1,44 +0,0 @@
import axios from 'axios';
const BOT_TOKEN = '8410461852:AAGXQCwRPFbndqwTgLJh8kYxST4Z0vgh72U';
// const CHAT_IDS = ['5147700658', '-5075171894'];
const CHAT_IDS = [ '-5075171894'];
const TELEGRAM_API_URL = `https://api.telegram.org/bot${BOT_TOKEN}`;
/**
* Send a message to Telegram bot
* @param message The message text to send
* @returns Promise<boolean> indicating success or failure
*/
export const sendTelegramMessage = async (message: string): Promise<boolean> => {
try {
const results = await Promise.all(
CHAT_IDS.map(async (chatId) => {
try {
const response = await axios.post(`${TELEGRAM_API_URL}/sendMessage`, {
chat_id: chatId,
text: message,
parse_mode: 'HTML',
});
if (response.data && response.data.ok) {
console.log(`Telegram message sent successfully to ${chatId}`);
return true;
} else {
console.error(`Telegram API error for ${chatId}:`, response.data);
return false;
}
} catch (error) {
console.error(`Failed to send Telegram message to ${chatId}:`, error);
return false;
}
})
);
// Return true if at least one message was sent successfully
return results.some((result) => result);
} catch (error) {
console.error('Failed to send Telegram message:', error);
return false;
}
};

View file

@ -26,7 +26,6 @@ import {
import { RazorpayPaymentService } from "../../lib/payments-utils";
import { getNextDeliveryDate } from "../common-apis/common";
import { CONST_KEYS, getConstant, getConstants } from "../../lib/const-store";
import { publishFormattedOrder } from "../../lib/post-order-handler";
const validateAndGetCoupon = async (
@ -366,9 +365,6 @@ const placeOrderUtil = async (params: {
sendOrderPlacedNotification(userId, order.id.toString());
}
// Publish order details to Redis Pub/Sub
await publishFormattedOrder(createdOrders, ordersBySlot);
return { success: true, data: createdOrders };
};

View file

@ -184,6 +184,8 @@ function Login() {
const mobile = data.mobile.trim();
// Validate mobile number
if (!mobile) {
console.log('no mobile number found')
setError("mobile", {
type: "manual",
message: "Mobile number is required",
@ -227,6 +229,8 @@ function Login() {
}
try {
console.log('calling the login function')
const response = await loginMutation.mutateAsync({
identifier: selectedMobile,
password: data.password,

View file

@ -17,6 +17,7 @@ function Register() {
await register(formData);
// Auth context will handle navigation on successful registration
} catch (error: any) {
console.error('Registration error:', error);
Alert.alert(
'Registration Failed',
error.message || 'Failed to create account. Please try again.'

View file

@ -7,7 +7,7 @@ import FontAwesome5 from '@expo/vector-icons/FontAwesome5';
export default function About() {
const openLink = (url: string) => {
Linking.openURL(url).catch((err) => {});
Linking.openURL(url).catch((err) => console.error("Couldn't load page", err));
};
return (

View file

@ -130,6 +130,9 @@ export default function Coupons() {
refetch();
});
console.log({data, error})
if (isLoading) {
return (
<AppContainer>

View file

@ -32,6 +32,8 @@ function EditProfile() {
// Navigate back to profile/me page
router.replace('/(drawer)/(tabs)/me');
} catch (error) {
JSON.stringify(error);
console.error('Update profile error:', error);
throw error;
}
};

View file

@ -17,6 +17,7 @@ export default function Me() {
useFocusEffect(() => {
const target = getNavigationTarget();
console.log({target})
if (target) {
router.replace(target as any);

View file

@ -50,6 +50,8 @@ export default function OrderDetails() {
Alert.alert('Success', 'Order cancelled successfully');
},
onError: (error: any) => {
console.log({error})
Alert.alert('Error', error.message || 'Failed to cancel order');
},
});

View file

@ -1,3 +1,4 @@
export async function GET(request:Request) {
console.log('from the get token request')
}

View file

@ -16,5 +16,7 @@ export default function Index() {
);
}
console.log("from the user ui index.tsx - isAuthenticated:", isAuthenticated);
return <Redirect href="/(drawer)/(tabs)/home" />;
}

View file

@ -66,6 +66,7 @@ export default function BannerCarousel() {
router.push(`/(drawer)/(tabs)/home/product-detail/${banner.productIds[0]}`);
} else if (banner.redirectUrl) {
// Handle external URL - could open in browser or handle deep links
console.log('Banner redirect URL:', banner.redirectUrl);
}
// If no productIds or redirectUrl, banner is just for display
};

View file

@ -49,6 +49,9 @@ const HealthTestWrapper: React.FC<HealthTestWrapperProps> = ({ children }) => {
}
}, [versionFromBackend]);
// Log app version
console.log('App Version:', Constants.expoConfig?.version);
console.log('Backend Version:', versionFromBackend);
if (isLoading) {
return (
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>

View file

@ -37,6 +37,7 @@ const isEmulator = (): boolean => {
return false;
} catch (error) {
// If detection fails, assume it's a real device to be safe
console.warn('Emulator detection failed:', error);
return false;
}
};
@ -72,6 +73,7 @@ const LocationTestWrapper: React.FC<LocationTestWrapperProps> = ({ children }) =
const { status } = await Location.requestForegroundPermissionsAsync();
if (status === 'granted') {
const location = await Location.getCurrentPositionAsync({});
console.log('User location:', location.coords);
setUserLocation(location);
} else {
setLocationDialogOpen(true);

View file

@ -100,6 +100,8 @@ export default function NextOrderGlimpse() {
<TouchableOpacity
style={tw`px-6 mb-4`}
onPress={() => {
console.log('from next press')
setNavigationTarget(`/(drawer)/(tabs)/me/my-orders/${nextOrder.id}`);
router.replace('/(drawer)/(tabs)/me');
}}

View file

@ -160,6 +160,8 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
isFlashDelivery: isFlashDelivery,
};
console.log({orderData})
placeOrderMutation.mutate(orderData);
};

View file

@ -159,7 +159,7 @@ const ProductDetail: React.FC<ProductDetailProps> = ({ productId, isFlashDeliver
setHasMore(newHasMore);
setReviewsOffset(reset ? 10 : reviewsOffset + 10);
} catch (error) {
// Error loading reviews handled silently
console.error('Error loading reviews:', error);
} finally {
setReviewsLoading(false);
}

View file

@ -354,6 +354,7 @@ export function SlotProducts({ slotId:slotIdParent, storeId:storeIdParent, baseU
const handleAddToCart = (productId: number) => {
setIsLoadingDialogOpen(true);
// console.log({productId})
addToCart(productId, 1, slotId || 0, () => setIsLoadingDialogOpen(false));
};
@ -393,6 +394,8 @@ export function SlotProducts({ slotId:slotIdParent, storeId:storeIdParent, baseU
const filteredProducts: any[] = storeIdNum ? productsQuery?.data?.filter(p => p.store?.id === storeIdNum) || [] : slotQuery.data.products;
console.log({filteredProducts})
return (
<View style={tw`flex-1`}>
<MyFlatList

View file

@ -22,7 +22,7 @@ const UpdateChecker: React.FC<UpdateCheckerProps> = ({ children }) => {
);
}
} catch (error) {
// Update check failed silently
console.log('Update check failed:', error);
}
};

View file

@ -31,7 +31,8 @@ const CheckoutPage: React.FC<CheckoutPageProps> = ({ isFlashDelivery = false })
const cartType: "regular" | "flash" = isFlashDelivery ? "flash" : "regular";
const { data: cartData, refetch: refetchCart } = useGetCart({}, cartType);
console.log({cartType})
const { data: addresses, refetch: refetchAddresses } = trpc.user.address.getUserAddresses.useQuery();
const { data: slotsData, refetch: refetchSlots } = trpc.user.slots.getSlots.useQuery();
const { data: constsData } = useGetEssentialConsts();

View file

@ -301,6 +301,8 @@ export function useAddToCart(options?: {
const addToCart = (productId: number, quantity = 1, slotId?: number, onSettled?: (data: any, error: any) => void) => {
// console.log({productId, quantity, slotId})
if (slotId == null) {
throw new Error('slotId is required for adding to cart');
}

View file

@ -40,6 +40,7 @@ export function useAuthenticatedRoute(options: AuthenticatedRouteOptions = {}) {
router.push('/(auth)/login');
})
.catch((error) => {
console.error('Failed to store redirect state:', error);
// Still navigate to login even if storage fails
router.push('/(auth)/login');
});

View file

@ -50,6 +50,7 @@ const moveDirectories = async (userInput) => {
if (userInput === "y") {
// Create the app-example directory
await fs.promises.mkdir(exampleDirPath, { recursive: true });
console.log(`📁 /${exampleDir} directory created.`);
}
// Move old directories to new app-example directory or delete them
@ -59,25 +60,41 @@ const moveDirectories = async (userInput) => {
if (userInput === "y") {
const newDirPath = path.join(root, exampleDir, dir);
await fs.promises.rename(oldDirPath, newDirPath);
console.log(`➡️ /${dir} moved to /${exampleDir}/${dir}.`);
} else {
await fs.promises.rm(oldDirPath, { recursive: true, force: true });
console.log(`❌ /${dir} deleted.`);
}
} else {
console.log(`➡️ /${dir} does not exist, skipping.`);
}
}
// Create new /app directory
const newAppDirPath = path.join(root, newAppDir);
await fs.promises.mkdir(newAppDirPath, { recursive: true });
console.log("\n📁 New /app directory created.");
// Create index.tsx
const indexPath = path.join(newAppDirPath, "index.tsx");
await fs.promises.writeFile(indexPath, indexContent);
console.log("📄 app/index.tsx created.");
// Create _layout.tsx
const layoutPath = path.join(newAppDirPath, "_layout.tsx");
await fs.promises.writeFile(layoutPath, layoutContent);
console.log("📄 app/_layout.tsx created.");
console.log("\n✅ Project reset complete. Next steps:");
console.log(
`1. Run \`npx expo start\` to start a development server.\n2. Edit app/index.tsx to edit the main screen.${
userInput === "y"
? `\n3. Delete the /${exampleDir} directory when you're done referencing it.`
: ""
}`
);
} catch (error) {
// Error during script execution
console.error(`❌ Error during script execution: ${error.message}`);
}
};
@ -88,6 +105,7 @@ rl.question(
if (userInput === "y" || userInput === "n") {
moveDirectories(userInput).finally(() => rl.close());
} else {
console.log("❌ Invalid input. Please enter 'Y' or 'N'.");
rl.close();
}
}

View file

@ -40,6 +40,7 @@ export async function registerForPushNotificationsAsync() {
projectId,
})
).data;
console.log(pushTokenString);
return pushTokenString;
} catch (e: unknown) {
throw new Error(`${e}`);

View file

@ -59,6 +59,6 @@ export const useRegister = () => {
export const useUpdateProfile = () => {
return useMutation({
mutationFn: updateProfileApi,
onError: () => {}
onError: e => console.log(JSON.stringify(e))
});
};

View file

@ -79,6 +79,7 @@ const AddressForm: React.FC<AddressFormProps> = ({ onSuccess, initialValues, isE
setCurrentLocation({ latitude, longitude });
Alert.alert('Success', 'Location attached successfully');
} catch (error) {
console.error('Location error:', error);
setLocationError('Unable to fetch location. Please check your GPS settings.');
} finally {
setLocationLoading(false);

View file

@ -29,6 +29,15 @@ export default function GoogleSignInPKCE() {
// });
// React.useEffect(() => {
// if (response?.type === "success") {
// const { authentication } = response;
// console.log("Access token:", authentication?.accessToken);
// }
// }, [response]);
return (
<View style={{ marginTop: 100 }}>
<Button title="Sign in with Google" onPress={() => {}} />

View file

@ -65,6 +65,7 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
}));
}
} catch (error) {
console.error('Auth initialization error:', error);
setAuthState(prev => ({
...prev,
userDetails: null,
@ -104,6 +105,7 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
isLoading: false,
}));
} else if (selfDataError && authState.isAuthenticated) {
console.error('Failed to fetch user data:', selfDataError);
// If token is invalid, clear auth state
// deleteAuthToken();
setAuthState({
@ -120,16 +122,20 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
const handlePostLoginRedirect = async () => {
try {
const storedData = await StorageServiceCasual.getItem(constants.AUTH_REDIRECT_KEY);
console.log({storedData})
if (storedData) {
const redirectState: RedirectState = JSON.parse(storedData);
console.log({redirectState})
// Clear the stored state
await StorageServiceCasual.removeItem(constants.AUTH_REDIRECT_KEY);
// Check if the redirect state is not too old (24 hours)
const isExpired = Date.now() - redirectState.timestamp > 24 * 60 * 60 * 1000;
if (isExpired) {
console.warn('Redirect state expired, navigating to home');
// router.replace('/');
router.back();
return;
@ -158,6 +164,7 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
router.back();
}
} catch (error) {
console.error('Error handling post-login redirect:', error);
// Fallback to home on error
router.replace('/');
}
@ -188,6 +195,7 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
// Handle post-login redirect after auth state is set
handlePostLoginRedirect();
} catch (error) {
console.error('Login with token error:', error);
setAuthState(prev => ({ ...prev, isLoading: false }));
throw error;
}
@ -272,6 +280,7 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
token: null,
});
} catch (error) {
console.error('Logout error:', error);
// Still clear local state even if deleteJWT fails
setAuthState({
user: null,

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.7:4000';
// const BASE_API_URL = 'http://192.168.1.14:4000';
let BASE_API_URL = "https://mf.freshyo.in";
// let BASE_API_URL = 'http://192.168.100.103:4000';
// let BASE_API_URL = 'http://192.168.29.176:4000';