From ba23af807675e2904c34a007105570092121e70a Mon Sep 17 00:00:00 2001 From: Urvish Date: Wed, 28 Oct 2026 16:23:33 +0530 Subject: [PATCH] feat: add in-app environment switcher and update bundle id to com.renown.mobile.acupedia - Add in-app environment switcher (Prod, QA, .env) on Login and Settings - Trigger auto-logout and clear query cache on environment change - Dynamically inject active baseURL into Axios and media resolver - Update bundle identifier in app.json to com.renown.mobile.acupedia --- app.json | 4 +- src/api/client.ts | 47 ++- src/app/subscription/index.tsx | 4 + src/components/EnvironmentSelectorModal.tsx | 371 +++++++++++++++++++ src/config/environments.ts | 43 +++ src/features/auth/components/LoginHeader.tsx | 109 ++++-- src/features/content/media/media-source.ts | 3 +- src/screens/settings/SettingsScreen.tsx | 26 +- src/store/environment.store.ts | 117 ++++++ 9 files changed, 695 insertions(+), 29 deletions(-) create mode 100644 src/components/EnvironmentSelectorModal.tsx create mode 100644 src/config/environments.ts create mode 100644 src/store/environment.store.ts diff --git a/app.json b/app.json index 4840b6e..922ea66 100644 --- a/app.json +++ b/app.json @@ -8,7 +8,7 @@ "scheme": "acupedia", "userInterfaceStyle": "automatic", "ios": { - "bundleIdentifier": "com.renownent.mobile.acupedia", + "bundleIdentifier": "com.renown.mobile.acupedia", "supportsTablet": true, "infoPlist": { "NSAppTransportSecurity": { @@ -24,7 +24,7 @@ "monochromeImage": "./assets/images/android-icon-monochrome.png" }, "predictiveBackGestureEnabled": false, - "package": "com.renownent.mobile.acupedia", + "package": "com.renown.mobile.acupedia", "allowBackup": false }, "web": { diff --git a/src/api/client.ts b/src/api/client.ts index e8f8280..30cd74f 100644 --- a/src/api/client.ts +++ b/src/api/client.ts @@ -2,7 +2,48 @@ import axios, { AxiosHeaders } from "axios"; import { getApiAccessToken } from "@/api/access-token"; import { normalizeApiError } from "@/api/error-utils"; import { notifyUnauthorized } from "@/api/session-events"; -const apiClient=axios.create({baseURL:process.env.EXPO_PUBLIC_API_URL ?? process.env.EXPO_PUBLIC_API_BASE_URL ?? "http://localhost:8000/api",timeout:30000,headers:{"Content-Type":"application/json",Accept:"application/json","Bypass-Tunnel-Reminder":"true"}}); -apiClient.interceptors.request.use((config)=>{const token=getApiAccessToken(); if(token){const headers=AxiosHeaders.from(config.headers); headers.set("Authorization",`Bearer ${token}`); config.headers=headers;} return config;},(error)=>Promise.reject(normalizeApiError(error))); -apiClient.interceptors.response.use((response)=>response,(error:unknown)=>{const apiError=normalizeApiError(error); const requestHeaders=axios.isAxiosError(error)?AxiosHeaders.from(error.config?.headers):null; const hadBearerToken=Boolean(requestHeaders?.get("Authorization")?.toString().startsWith("Bearer ")); if(hadBearerToken && apiError.status===401) notifyUnauthorized(); return Promise.reject(apiError);}); +import { getActiveApiUrl } from "@/store/environment.store"; + +const apiClient = axios.create({ + baseURL: getActiveApiUrl(), + timeout: 30000, + headers: { + "Content-Type": "application/json", + Accept: "application/json", + "Bypass-Tunnel-Reminder": "true", + }, +}); + +apiClient.interceptors.request.use( + (config) => { + const activeBaseUrl = getActiveApiUrl(); + if (activeBaseUrl) { + config.baseURL = activeBaseUrl; + } + const token = getApiAccessToken(); + if (token) { + const headers = AxiosHeaders.from(config.headers); + headers.set("Authorization", `Bearer ${token}`); + config.headers = headers; + } + return config; + }, + (error) => Promise.reject(normalizeApiError(error)) +); + +apiClient.interceptors.response.use( + (response) => response, + (error: unknown) => { + const apiError = normalizeApiError(error); + const requestHeaders = axios.isAxiosError(error) + ? AxiosHeaders.from(error.config?.headers) + : null; + const hadBearerToken = Boolean( + requestHeaders?.get("Authorization")?.toString().startsWith("Bearer ") + ); + if (hadBearerToken && apiError.status === 401) notifyUnauthorized(); + return Promise.reject(apiError); + } +); + export default apiClient; diff --git a/src/app/subscription/index.tsx b/src/app/subscription/index.tsx index 58ebf86..4f2bb44 100644 --- a/src/app/subscription/index.tsx +++ b/src/app/subscription/index.tsx @@ -19,6 +19,7 @@ import Constants from "expo-constants"; import { Colors } from "@/theme"; import { useAuthStore } from "@/store/auth.store"; +import { getActiveStorefrontUrl } from "@/store/environment.store"; import PrimaryButton from "@/components/buttons/PrimaryButton"; function param(value: string | string[] | undefined): string { @@ -26,6 +27,9 @@ function param(value: string | string[] | undefined): string { } function resolveStorefrontUrl(): string { + const dynamicUrl = getActiveStorefrontUrl(); + if (dynamicUrl) return dynamicUrl; + const envUrl = process.env.EXPO_PUBLIC_STOREFRONT_URL?.trim(); if (envUrl) return envUrl; diff --git a/src/components/EnvironmentSelectorModal.tsx b/src/components/EnvironmentSelectorModal.tsx new file mode 100644 index 0000000..2f26804 --- /dev/null +++ b/src/components/EnvironmentSelectorModal.tsx @@ -0,0 +1,371 @@ +import React from "react"; +import { + Alert, + Modal, + Platform, + Pressable, + StyleSheet, + Text, + TouchableOpacity, + View, +} from "react-native"; +import { Ionicons } from "@expo/vector-icons"; +import { useRouter } from "expo-router"; +import { moderateScale, scale, verticalScale } from "react-native-size-matters"; + +import { + DEFAULT_ENV_LABEL, + ENABLE_ENV_SWITCHER, + ENVIRONMENTS, + EnvironmentKey, +} from "@/config/environments"; +import { useEnvironmentStore } from "@/store/environment.store"; +import { Colors } from "@/theme"; + +interface EnvironmentSelectorModalProps { + visible: boolean; + onClose: () => void; +} + +export default function EnvironmentSelectorModal({ + visible, + onClose, +}: EnvironmentSelectorModalProps) { + const router = useRouter(); + const currentEnv = useEnvironmentStore((state) => state.currentEnv); + const switchEnvironment = useEnvironmentStore( + (state) => state.switchEnvironment + ); + + if (!ENABLE_ENV_SWITCHER) { + return null; + } + + const handleSelectEnvironment = (key: EnvironmentKey) => { + if (key === currentEnv) { + onClose(); + return; + } + + const targetLabel = + key === "default" ? DEFAULT_ENV_LABEL : ENVIRONMENTS[key].label; + + const executeSwitch = async () => { + onClose(); + try { + await switchEnvironment(key); + // Navigate cleanly to Login screen after logout + router.replace("/login"); + Alert.alert( + "Environment Switched", + `Active backend is now: ${targetLabel}` + ); + } catch (err) { + console.error("Failed to switch environment:", err); + } + }; + + if (Platform.OS === "web") { + const confirmed = window.confirm( + `Switching to "${targetLabel}" will log you out and reload data. Continue?` + ); + if (confirmed) { + executeSwitch(); + } + } else { + Alert.alert( + "Switch Environment", + `Switching to "${targetLabel}" will log you out and reset cached data. Are you sure?`, + [ + { text: "Cancel", style: "cancel" }, + { + text: "Switch & Logout", + style: "destructive", + onPress: executeSwitch, + }, + ], + { cancelable: true } + ); + } + }; + + const options: { + key: EnvironmentKey; + label: string; + url: string; + badge: string; + badgeColor: string; + }[] = [ + { + key: "prod", + label: ENVIRONMENTS.prod.label, + url: ENVIRONMENTS.prod.apiUrl, + badge: "PROD", + badgeColor: "#10B981", // Emerald green + }, + { + key: "qa", + label: ENVIRONMENTS.qa.label, + url: ENVIRONMENTS.qa.apiUrl, + badge: "QA", + badgeColor: "#F59E0B", // Amber + }, + { + key: "default", + label: DEFAULT_ENV_LABEL, + url: "Uses build / .env defaults", + badge: "ENV", + badgeColor: "#6B7280", // Gray + }, + ]; + + return ( + + + e.stopPropagation()} + > + {/* Header */} + + + + + + + Select Environment + + Switch server for testing + + + + + + + + + {/* Options */} + + {options.map((opt) => { + const isSelected = currentEnv === opt.key; + return ( + handleSelectEnvironment(opt.key)} + style={[ + styles.optionItem, + isSelected && styles.optionItemSelected, + ]} + > + + + + {opt.label} + + + {opt.badge} + + + + {opt.url} + + + + + {isSelected && } + + + ); + })} + + + {/* Notice */} + + + + Switching environment logs out the user and clears cache. + + + + + + ); +} + +const styles = StyleSheet.create({ + backdrop: { + flex: 1, + backgroundColor: "rgba(0, 0, 0, 0.5)", + justifyContent: "center", + alignItems: "center", + paddingHorizontal: scale(20), + }, + modalCard: { + width: "100%", + maxWidth: scale(380), + backgroundColor: "#FFFFFF", + borderRadius: moderateScale(16), + padding: scale(20), + shadowColor: "#000", + shadowOffset: { width: 0, height: 4 }, + shadowOpacity: 0.15, + shadowRadius: 12, + elevation: 8, + }, + header: { + flexDirection: "row", + alignItems: "center", + justifyContent: "space-between", + marginBottom: verticalScale(16), + }, + headerLeft: { + flexDirection: "row", + alignItems: "center", + gap: scale(10), + }, + iconCircle: { + width: scale(38), + height: scale(38), + borderRadius: scale(19), + backgroundColor: "#EFF6FF", + justifyContent: "center", + alignItems: "center", + }, + title: { + fontSize: moderateScale(17), + fontWeight: "700", + color: "#0F172A", + }, + subtitle: { + fontSize: moderateScale(12), + color: "#64748B", + marginTop: verticalScale(2), + }, + closeBtn: { + padding: scale(4), + }, + optionsList: { + gap: verticalScale(10), + marginBottom: verticalScale(14), + }, + optionItem: { + flexDirection: "row", + alignItems: "center", + justifyContent: "space-between", + padding: scale(14), + borderRadius: moderateScale(12), + borderWidth: 1.5, + borderColor: "#E2E8F0", + backgroundColor: "#F8FAFC", + }, + optionItemSelected: { + borderColor: Colors.primary || "#2563EB", + backgroundColor: "#EFF6FF", + }, + optionContent: { + flex: 1, + marginRight: scale(10), + }, + optionTitleRow: { + flexDirection: "row", + alignItems: "center", + gap: scale(8), + }, + optionLabel: { + fontSize: moderateScale(14), + fontWeight: "600", + color: "#1E293B", + }, + optionLabelSelected: { + color: Colors.primary || "#2563EB", + fontWeight: "700", + }, + badge: { + paddingHorizontal: scale(6), + paddingVertical: verticalScale(2), + borderRadius: moderateScale(4), + }, + badgeText: { + fontSize: moderateScale(10), + fontWeight: "700", + color: "#FFFFFF", + }, + optionUrl: { + fontSize: moderateScale(11), + color: "#64748B", + marginTop: verticalScale(4), + }, + radioCircle: { + width: scale(20), + height: scale(20), + borderRadius: scale(10), + borderWidth: 2, + borderColor: "#CBD5E1", + justifyContent: "center", + alignItems: "center", + }, + radioCircleSelected: { + borderColor: Colors.primary || "#2563EB", + }, + radioDot: { + width: scale(10), + height: scale(10), + borderRadius: scale(5), + backgroundColor: Colors.primary || "#2563EB", + }, + noticeBox: { + flexDirection: "row", + alignItems: "center", + gap: scale(6), + backgroundColor: "#F1F5F9", + padding: scale(10), + borderRadius: moderateScale(8), + }, + noticeText: { + fontSize: moderateScale(11), + color: "#64748B", + flex: 1, + }, +}); + diff --git a/src/config/environments.ts b/src/config/environments.ts new file mode 100644 index 0000000..7eb101f --- /dev/null +++ b/src/config/environments.ts @@ -0,0 +1,43 @@ +/** + * Environment configuration for Acupedia Mobile. + * + * Set ENABLE_ENV_SWITCHER = false (or comment out) to completely disable + * the environment switcher UI for production App Store / Google Play builds. + */ +export const ENABLE_ENV_SWITCHER = true; + +export type EnvironmentKey = "default" | "prod" | "qa"; + +export interface EnvironmentConfig { + key: EnvironmentKey; + label: string; + badge: string; + apiUrl: string; + storefrontUrl: string; + mediaBaseUrl: string; + description: string; +} + +export const ENVIRONMENTS: Record<"prod" | "qa", EnvironmentConfig> = { + prod: { + key: "prod", + label: "Production", + badge: "PROD", + apiUrl: "https://api.acupedia.in/api", + storefrontUrl: "https://acupedia.in/store", + mediaBaseUrl: "https://api.acupedia.in", + description: "Official live server (api.acupedia.in)", + }, + qa: { + key: "qa", + label: "QA / Staging", + badge: "QA", + apiUrl: "https://qa-api.acupedia.in/api", + storefrontUrl: "https://qa.acupedia.in/store", + mediaBaseUrl: "https://qa-api.acupedia.in", + description: "Testing & QA server (qa-api.acupedia.in)", + }, +}; + +export const DEFAULT_ENV_LABEL = "Default (.env)"; + diff --git a/src/features/auth/components/LoginHeader.tsx b/src/features/auth/components/LoginHeader.tsx index f8f92bd..4538c8a 100644 --- a/src/features/auth/components/LoginHeader.tsx +++ b/src/features/auth/components/LoginHeader.tsx @@ -1,39 +1,74 @@ -import React from "react"; -import { Pressable, StyleSheet, Text, View } from "react-native"; +import React, { useState } from "react"; +import { Pressable, StyleSheet, Text, TouchableOpacity, View } from "react-native"; import { Ionicons } from "@expo/vector-icons"; import { useRouter } from "expo-router"; - -import { AuthColors } from "../constants/colors"; import { moderateScale, scale, verticalScale, } from "react-native-size-matters"; + +import { AuthColors } from "../constants/colors"; +import { ENABLE_ENV_SWITCHER } from "@/config/environments"; +import { useEnvironmentStore } from "@/store/environment.store"; +import EnvironmentSelectorModal from "@/components/EnvironmentSelectorModal"; + export default function LoginHeader() { const router = useRouter(); + const [modalVisible, setModalVisible] = useState(false); + const activeConfig = useEnvironmentStore((state) => state.getActiveConfig()); + + const badgeColor = + activeConfig.key === "prod" + ? "#10B981" + : activeConfig.key === "qa" + ? "#F59E0B" + : "#6B7280"; return ( - router.back()} - style={styles.backButton} - > - - + + router.back()} + style={styles.backButton} + > + + + + {ENABLE_ENV_SWITCHER && ( + setModalVisible(true)} + activeOpacity={0.7} + > + + {activeConfig.badge} + + + )} + Welcome Back! - - - Login to continue - + Login to continue + + {ENABLE_ENV_SWITCHER && ( + setModalVisible(false)} + /> + )} ); } @@ -44,11 +79,41 @@ const styles = StyleSheet.create({ marginBottom: verticalScale(32), }, + topRow: { + flexDirection: "row", + alignItems: "center", + justifyContent: "space-between", + marginBottom: verticalScale(28), + }, + backButton: { width: scale(40), height: scale(40), justifyContent: "center", - marginBottom: verticalScale(28), + }, + + envPill: { + flexDirection: "row", + alignItems: "center", + gap: scale(5), + paddingHorizontal: scale(10), + paddingVertical: verticalScale(5), + backgroundColor: "#F1F5F9", + borderRadius: moderateScale(16), + borderWidth: 1, + borderColor: "#E2E8F0", + }, + + envDot: { + width: scale(7), + height: scale(7), + borderRadius: scale(3.5), + }, + + envPillText: { + fontSize: moderateScale(11), + fontWeight: "700", + color: "#334155", }, textContainer: { @@ -66,4 +131,4 @@ const styles = StyleSheet.create({ color: AuthColors.textSecondary, fontWeight: "500", }, -}); \ No newline at end of file +}); diff --git a/src/features/content/media/media-source.ts b/src/features/content/media/media-source.ts index cda8d78..b257fc5 100644 --- a/src/features/content/media/media-source.ts +++ b/src/features/content/media/media-source.ts @@ -1,5 +1,6 @@ import type { ImageSource } from "expo-image"; import type { ContentMediaItem } from "../types/media.types"; +import { getActiveMediaBaseUrl } from "@/store/environment.store"; /** * Resolve the final media URI using only primitive fields. @@ -18,7 +19,7 @@ export function resolveMediaUri( return directUrl; } - const mediaBaseUrl = (process.env.EXPO_PUBLIC_MEDIA_BASE_URL ?? "") + const mediaBaseUrl = (getActiveMediaBaseUrl() || (process.env.EXPO_PUBLIC_MEDIA_BASE_URL ?? "")) .trim() .replace(/\/+$/, ""); diff --git a/src/screens/settings/SettingsScreen.tsx b/src/screens/settings/SettingsScreen.tsx index 61a7d42..20ac161 100644 --- a/src/screens/settings/SettingsScreen.tsx +++ b/src/screens/settings/SettingsScreen.tsx @@ -1,4 +1,4 @@ -import React from "react"; +import React, { useState } from "react"; import { Alert, Platform, @@ -22,8 +22,13 @@ import { import { SettingsItem } from "@/features/settings/types"; import { useAuthStore } from "@/store/auth.store"; import { useSettingsStore } from "@/store/settings.store"; +import { ENABLE_ENV_SWITCHER } from "@/config/environments"; +import { useEnvironmentStore } from "@/store/environment.store"; +import EnvironmentSelectorModal from "@/components/EnvironmentSelectorModal"; export default function SettingsScreen() { + const [envModalVisible, setEnvModalVisible] = useState(false); + const activeConfig = useEnvironmentStore((state) => state.getActiveConfig()); const user = useAuthStore((state) => state.user); const logout = useAuthStore((state) => state.logout); @@ -68,6 +73,18 @@ export default function SettingsScreen() { ] : []), ...PREFERENCE_SETTINGS, + ...(ENABLE_ENV_SWITCHER + ? [ + { + id: "server-environment", + title: "Server Environment", + subtitle: `${activeConfig.label} (${activeConfig.badge})`, + icon: "server-outline" as const, + value: activeConfig.badge, + onPress: () => setEnvModalVisible(true), + }, + ] + : []), ]; const handleLogout = () => { @@ -129,6 +146,13 @@ export default function SettingsScreen() { + + {ENABLE_ENV_SWITCHER && ( + setEnvModalVisible(false)} + /> + )} ); } diff --git a/src/store/environment.store.ts b/src/store/environment.store.ts new file mode 100644 index 0000000..bbd94e7 --- /dev/null +++ b/src/store/environment.store.ts @@ -0,0 +1,117 @@ +import AsyncStorage from "@react-native-async-storage/async-storage"; +import { create } from "zustand"; +import { createJSONStorage, persist } from "zustand/middleware"; + +import { + DEFAULT_ENV_LABEL, + ENABLE_ENV_SWITCHER, + ENVIRONMENTS, + EnvironmentConfig, + EnvironmentKey, +} from "@/config/environments"; +import { clearApiAccessToken } from "@/api/access-token"; +import { queryClient } from "@/lib/query/query-client"; +import { useAuthStore } from "@/store/auth.store"; + +interface EnvironmentStore { + currentEnv: EnvironmentKey; + setEnvironment: (env: EnvironmentKey) => void; + getActiveConfig: () => { + key: EnvironmentKey; + label: string; + badge: string; + apiUrl: string; + storefrontUrl: string; + mediaBaseUrl: string; + }; + getApiUrl: () => string; + getStorefrontUrl: () => string; + getMediaBaseUrl: () => string; + switchEnvironment: (env: EnvironmentKey) => Promise; +} + +const getDefaultApiUrl = () => + process.env.EXPO_PUBLIC_API_URL ?? + process.env.EXPO_PUBLIC_API_BASE_URL ?? + "http://localhost:8000/api"; + +const getDefaultStorefrontUrl = () => + process.env.EXPO_PUBLIC_STOREFRONT_URL?.trim() ?? "https://acupedia.in/store"; + +const getDefaultMediaBaseUrl = () => + process.env.EXPO_PUBLIC_MEDIA_BASE_URL?.trim() ?? ""; + +export const useEnvironmentStore = create()( + persist( + (set, get) => ({ + currentEnv: "default", + + setEnvironment: (currentEnv: EnvironmentKey) => set({ currentEnv }), + + getActiveConfig: () => { + const { currentEnv } = get(); + if (!ENABLE_ENV_SWITCHER || currentEnv === "default") { + return { + key: "default" as EnvironmentKey, + label: DEFAULT_ENV_LABEL, + badge: "DEFAULT", + apiUrl: getDefaultApiUrl(), + storefrontUrl: getDefaultStorefrontUrl(), + mediaBaseUrl: getDefaultMediaBaseUrl(), + }; + } + + const preset = ENVIRONMENTS[currentEnv]; + return { + key: preset.key, + label: preset.label, + badge: preset.badge, + apiUrl: preset.apiUrl, + storefrontUrl: preset.storefrontUrl, + mediaBaseUrl: preset.mediaBaseUrl, + }; + }, + + getApiUrl: () => { + return get().getActiveConfig().apiUrl; + }, + + getStorefrontUrl: () => { + return get().getActiveConfig().storefrontUrl; + }, + + getMediaBaseUrl: () => { + return get().getActiveConfig().mediaBaseUrl; + }, + + switchEnvironment: async (env: EnvironmentKey) => { + set({ currentEnv: env }); + + // 1. Wipe current auth session across memory and storage + clearApiAccessToken(); + await useAuthStore.getState().logout(); + + // 2. Clear query caches so no stale data from old env is retained + queryClient.clear(); + }, + }), + { + name: "acupedia-environment-storage", + storage: createJSONStorage(() => AsyncStorage), + partialize: (state) => ({ currentEnv: state.currentEnv }), + } + ) +); + +export function getActiveApiUrl(): string { + return useEnvironmentStore.getState().getApiUrl(); +} + +export function getActiveStorefrontUrl(): string { + return useEnvironmentStore.getState().getStorefrontUrl(); +} + +export function getActiveMediaBaseUrl(): string { + return useEnvironmentStore.getState().getMediaBaseUrl(); +} + -- 2.34.1