Merge pull request 'feat: add in-app environment switcher and update bundle id to com.renown.mobile.acupedia' (#90) from env-switch into main

Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/90
Reviewed-by: Amit Salunke <amit@noreply.localhost>
This commit is contained in:
Amit Salunke 2026-10-29 07:00:41 +00:00
commit 349946f0c1
9 changed files with 695 additions and 29 deletions

View File

@ -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": {

View File

@ -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;

View File

@ -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;

View File

@ -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 (
<Modal
visible={visible}
transparent
animationType="fade"
onRequestClose={onClose}
>
<Pressable style={styles.backdrop} onPress={onClose}>
<Pressable
style={styles.modalCard}
onPress={(e) => e.stopPropagation()}
>
{/* Header */}
<View style={styles.header}>
<View style={styles.headerLeft}>
<View style={styles.iconCircle}>
<Ionicons
name="server-outline"
size={moderateScale(20)}
color={Colors.primary || "#2563EB"}
/>
</View>
<View>
<Text style={styles.title}>Select Environment</Text>
<Text style={styles.subtitle}>
Switch server for testing
</Text>
</View>
</View>
<TouchableOpacity
onPress={onClose}
hitSlop={12}
style={styles.closeBtn}
>
<Ionicons
name="close"
size={moderateScale(22)}
color="#64748B"
/>
</TouchableOpacity>
</View>
{/* Options */}
<View style={styles.optionsList}>
{options.map((opt) => {
const isSelected = currentEnv === opt.key;
return (
<TouchableOpacity
key={opt.key}
activeOpacity={0.7}
onPress={() => handleSelectEnvironment(opt.key)}
style={[
styles.optionItem,
isSelected && styles.optionItemSelected,
]}
>
<View style={styles.optionContent}>
<View style={styles.optionTitleRow}>
<Text
style={[
styles.optionLabel,
isSelected && styles.optionLabelSelected,
]}
>
{opt.label}
</Text>
<View
style={[
styles.badge,
{ backgroundColor: opt.badgeColor },
]}
>
<Text style={styles.badgeText}>{opt.badge}</Text>
</View>
</View>
<Text
style={styles.optionUrl}
numberOfLines={1}
ellipsizeMode="tail"
>
{opt.url}
</Text>
</View>
<View
style={[
styles.radioCircle,
isSelected && styles.radioCircleSelected,
]}
>
{isSelected && <View style={styles.radioDot} />}
</View>
</TouchableOpacity>
);
})}
</View>
{/* Notice */}
<View style={styles.noticeBox}>
<Ionicons
name="information-circle-outline"
size={moderateScale(16)}
color="#64748B"
/>
<Text style={styles.noticeText}>
Switching environment logs out the user and clears cache.
</Text>
</View>
</Pressable>
</Pressable>
</Modal>
);
}
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,
},
});

View File

@ -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)";

View File

@ -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 (
<View style={styles.container}>
<Pressable
accessibilityRole="button"
accessibilityLabel="Go Back"
hitSlop={10}
onPress={() => router.back()}
style={styles.backButton}
>
<Ionicons
name="arrow-back"
size={moderateScale(24)}
/>
</Pressable>
<View style={styles.topRow}>
<Pressable
accessibilityRole="button"
accessibilityLabel="Go Back"
hitSlop={10}
onPress={() => router.back()}
style={styles.backButton}
>
<Ionicons
name="arrow-back"
size={moderateScale(24)}
/>
</Pressable>
{ENABLE_ENV_SWITCHER && (
<TouchableOpacity
style={styles.envPill}
onPress={() => setModalVisible(true)}
activeOpacity={0.7}
>
<View style={[styles.envDot, { backgroundColor: badgeColor }]} />
<Text style={styles.envPillText}>{activeConfig.badge}</Text>
<Ionicons
name="chevron-down"
size={moderateScale(12)}
color="#64748B"
/>
</TouchableOpacity>
)}
</View>
<View style={styles.textContainer}>
<Text style={styles.title}>Welcome Back!</Text>
<Text style={styles.subtitle}>
Login to continue
</Text>
<Text style={styles.subtitle}>Login to continue</Text>
</View>
{ENABLE_ENV_SWITCHER && (
<EnvironmentSelectorModal
visible={modalVisible}
onClose={() => setModalVisible(false)}
/>
)}
</View>
);
}
@ -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",
},
});
});

View File

@ -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(/\/+$/, "");

View File

@ -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() {
<LogoutButton onPress={handleLogout} />
</View>
</ScrollView>
{ENABLE_ENV_SWITCHER && (
<EnvironmentSelectorModal
visible={envModalVisible}
onClose={() => setEnvModalVisible(false)}
/>
)}
</SafeAreaView>
);
}

View File

@ -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<void>;
}
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<EnvironmentStore>()(
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();
}