Compare commits

...

2 commits

Author SHA1 Message Date
shafi54
df114be912 enh 2026-01-31 16:51:09 +05:30
shafi54
a16e50c6a5 enh 2026-01-31 15:57:02 +05:30
32 changed files with 262 additions and 79 deletions

View file

@ -1,11 +1,13 @@
import './notif-job'; import './notif-job';
import { initializeAllStores } from '../stores/store-initializer'; import { initializeAllStores } from '../stores/store-initializer';
import { startOrderHandler, publishOrder } from './post-order-handler';
/** /**
* Initialize all application services * Initialize all application services
* This function handles initialization of: * This function handles initialization of:
* - Role Manager (fetches and caches all roles) * - Role Manager (fetches and caches all roles)
* - Const Store (syncs constants from DB to Redis) * - Const Store (syncs constants from DB to Redis)
* - Post Order Handler (Redis Pub/Sub subscriber)
* - Other services can be added here in the future * - Other services can be added here in the future
*/ */
export const initFunc = async (): Promise<void> => { export const initFunc = async (): Promise<void> => {
@ -18,6 +20,25 @@ export const initFunc = async (): Promise<void> => {
// Notification queue and worker are initialized via import // Notification queue and worker are initialized via import
console.log('Notification queue and worker initialized'); 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'); console.log('Application initialization completed successfully');
} catch (error) { } catch (error) {
console.error('Application initialization failed:', error); console.error('Application initialization failed:', error);

View file

@ -0,0 +1,146 @@
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,6 +3,7 @@ import { redisUrl } from './env-exporter';
class RedisClient { class RedisClient {
private client: RedisClientType; private client: RedisClientType;
private subscriberClient: RedisClientType | null = null;
private isConnected: boolean = false; private isConnected: boolean = false;
constructor() { constructor() {
@ -71,10 +72,48 @@ class RedisClient {
return await this.client.MGET(keys); 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 { disconnect(): void {
if (this.isConnected) { if (this.isConnected) {
this.client.disconnect(); this.client.disconnect();
} }
if (this.subscriberClient) {
this.subscriberClient.disconnect();
}
} }
get isClientConnected(): boolean { get isClientConnected(): boolean {

View file

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

View file

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

View file

@ -17,7 +17,6 @@ function Register() {
await register(formData); await register(formData);
// Auth context will handle navigation on successful registration // Auth context will handle navigation on successful registration
} catch (error: any) { } catch (error: any) {
console.error('Registration error:', error);
Alert.alert( Alert.alert(
'Registration Failed', 'Registration Failed',
error.message || 'Failed to create account. Please try again.' 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() { export default function About() {
const openLink = (url: string) => { const openLink = (url: string) => {
Linking.openURL(url).catch((err) => console.error("Couldn't load page", err)); Linking.openURL(url).catch((err) => {});
}; };
return ( return (

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -49,9 +49,6 @@ const HealthTestWrapper: React.FC<HealthTestWrapperProps> = ({ children }) => {
} }
}, [versionFromBackend]); }, [versionFromBackend]);
// Log app version
console.log('App Version:', Constants.expoConfig?.version);
console.log('Backend Version:', versionFromBackend);
if (isLoading) { if (isLoading) {
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`}>

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -50,7 +50,6 @@ const moveDirectories = async (userInput) => {
if (userInput === "y") { if (userInput === "y") {
// Create the app-example directory // Create the app-example directory
await fs.promises.mkdir(exampleDirPath, { recursive: true }); await fs.promises.mkdir(exampleDirPath, { recursive: true });
console.log(`📁 /${exampleDir} directory created.`);
} }
// Move old directories to new app-example directory or delete them // Move old directories to new app-example directory or delete them
@ -60,41 +59,25 @@ const moveDirectories = async (userInput) => {
if (userInput === "y") { if (userInput === "y") {
const newDirPath = path.join(root, exampleDir, dir); const newDirPath = path.join(root, exampleDir, dir);
await fs.promises.rename(oldDirPath, newDirPath); await fs.promises.rename(oldDirPath, newDirPath);
console.log(`➡️ /${dir} moved to /${exampleDir}/${dir}.`);
} else { } else {
await fs.promises.rm(oldDirPath, { recursive: true, force: true }); 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 // Create new /app directory
const newAppDirPath = path.join(root, newAppDir); const newAppDirPath = path.join(root, newAppDir);
await fs.promises.mkdir(newAppDirPath, { recursive: true }); await fs.promises.mkdir(newAppDirPath, { recursive: true });
console.log("\n📁 New /app directory created.");
// Create index.tsx // Create index.tsx
const indexPath = path.join(newAppDirPath, "index.tsx"); const indexPath = path.join(newAppDirPath, "index.tsx");
await fs.promises.writeFile(indexPath, indexContent); await fs.promises.writeFile(indexPath, indexContent);
console.log("📄 app/index.tsx created.");
// Create _layout.tsx // Create _layout.tsx
const layoutPath = path.join(newAppDirPath, "_layout.tsx"); const layoutPath = path.join(newAppDirPath, "_layout.tsx");
await fs.promises.writeFile(layoutPath, layoutContent); 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) { } catch (error) {
console.error(`❌ Error during script execution: ${error.message}`); // Error during script execution
} }
}; };
@ -105,7 +88,6 @@ rl.question(
if (userInput === "y" || userInput === "n") { if (userInput === "y" || userInput === "n") {
moveDirectories(userInput).finally(() => rl.close()); moveDirectories(userInput).finally(() => rl.close());
} else { } else {
console.log("❌ Invalid input. Please enter 'Y' or 'N'.");
rl.close(); rl.close();
} }
} }

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -63,7 +63,7 @@ const isDevMode = Constants.executionEnvironment !== "standalone";
// const BASE_API_URL = API_URL; // const BASE_API_URL = API_URL;
// const BASE_API_URL = 'http://10.0.2.2:4000'; // 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.100.101:4000';
// const BASE_API_URL = 'http://192.168.1.14:4000'; // const BASE_API_URL = 'http://192.168.1.7:4000';
let BASE_API_URL = "https://mf.freshyo.in"; 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.100.103:4000';
// let BASE_API_URL = 'http://192.168.29.176:4000'; // let BASE_API_URL = 'http://192.168.29.176:4000';