331 lines
14 KiB
TypeScript
331 lines
14 KiB
TypeScript
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||
import {
|
||
ActivityIndicator,
|
||
Alert,
|
||
Linking,
|
||
Platform,
|
||
ScrollView,
|
||
StyleSheet,
|
||
Text,
|
||
TextInput,
|
||
TouchableOpacity,
|
||
View,
|
||
} from "react-native";
|
||
import { SafeAreaView } from "react-native-safe-area-context";
|
||
import { router, useFocusEffect, useLocalSearchParams } from "expo-router";
|
||
import { Ionicons } from "@expo/vector-icons";
|
||
import { moderateScale, verticalScale } from "react-native-size-matters";
|
||
import Constants from "expo-constants";
|
||
|
||
import { Colors } from "@/theme";
|
||
import { useAuthStore } from "@/store/auth.store";
|
||
import { calculateCart } from "@/features/commerce";
|
||
import type { CartCalculationResponse } from "@/features/commerce";
|
||
import PrimaryButton from "@/components/buttons/PrimaryButton";
|
||
|
||
function param(value: string | string[] | undefined): string {
|
||
return typeof value === "string" ? value : "";
|
||
}
|
||
|
||
function money(value: number, currency: string): string {
|
||
try {
|
||
return new Intl.NumberFormat("en-IN", {
|
||
style: "currency",
|
||
currency,
|
||
maximumFractionDigits: 2,
|
||
}).format(value);
|
||
} catch {
|
||
return `${currency} ${value.toFixed(2)}`;
|
||
}
|
||
}
|
||
|
||
function resolveStorefrontUrl(): string {
|
||
const envUrl = process.env.EXPO_PUBLIC_STOREFRONT_URL?.trim();
|
||
if (envUrl) return envUrl;
|
||
|
||
const apiUrl = process.env.EXPO_PUBLIC_API_URL ?? "";
|
||
if (apiUrl.startsWith("https://")) {
|
||
try {
|
||
const parsed = new URL(apiUrl);
|
||
if (!parsed.hostname.includes("localhost") && !parsed.hostname.includes("127.0.0.1")) {
|
||
return parsed.origin;
|
||
}
|
||
} catch {}
|
||
}
|
||
|
||
const hostUri = Constants.expoConfig?.hostUri;
|
||
const metroHost = hostUri?.split(":")[0];
|
||
if (metroHost && /^[0-9.]+$/.test(metroHost) && metroHost !== "127.0.0.1") {
|
||
return `http://${metroHost}:3000`;
|
||
}
|
||
|
||
if (Platform.OS === "web" && typeof window !== "undefined") {
|
||
return `${window.location.protocol}//${window.location.hostname}`;
|
||
}
|
||
|
||
const ipMatch = apiUrl.match(/http:\/\/([0-9.]+)/);
|
||
if (ipMatch?.[1]) return `http://${ipMatch[1]}:3000`;
|
||
|
||
return "http://localhost:3000";
|
||
}
|
||
|
||
export default function SubscriptionScreen() {
|
||
const params = useLocalSearchParams();
|
||
const accessToken = useAuthStore((state) => state.accessToken);
|
||
const access = useAuthStore((state) => state.access);
|
||
const refreshAccess = useAuthStore((state) => state.refreshAccess);
|
||
|
||
const moduleId = param(params.moduleId);
|
||
const moduleCode = param(params.moduleCode);
|
||
const title = param(params.title) || "Clinical Module";
|
||
const category = param(params.category);
|
||
const description = param(params.desc);
|
||
const planCode = param(params.planCode).trim().toUpperCase();
|
||
|
||
const [couponCode, setCouponCode] = useState("");
|
||
const [pricing, setPricing] = useState<CartCalculationResponse | null>(null);
|
||
const [loadingPricing, setLoadingPricing] = useState(false);
|
||
const [openingCheckout, setOpeningCheckout] = useState(false);
|
||
const [error, setError] = useState<string | null>(null);
|
||
|
||
const unlocked = useMemo(() => {
|
||
if (!accessToken) return false;
|
||
if (moduleCode && access?.unlocked_module_codes.includes(moduleCode)) return true;
|
||
return false;
|
||
}, [access, accessToken, moduleCode]);
|
||
|
||
const loadPricing = useCallback(async (coupon?: string) => {
|
||
if (!planCode) {
|
||
setPricing(null);
|
||
setError("This module does not have a commerce plan configured.");
|
||
return;
|
||
}
|
||
|
||
setLoadingPricing(true);
|
||
setError(null);
|
||
try {
|
||
const response = await calculateCart({
|
||
cart_item_codes: [planCode],
|
||
coupon_code: coupon?.trim() || null,
|
||
currency: "INR",
|
||
});
|
||
setPricing(response);
|
||
} catch (err: any) {
|
||
const detail = err?.response?.data?.detail;
|
||
setError(typeof detail === "string" ? detail : "Unable to load current subscription pricing.");
|
||
setPricing(null);
|
||
} finally {
|
||
setLoadingPricing(false);
|
||
}
|
||
}, [planCode]);
|
||
|
||
useEffect(() => {
|
||
void loadPricing();
|
||
}, [loadPricing]);
|
||
|
||
useFocusEffect(
|
||
useCallback(() => {
|
||
if (accessToken) {
|
||
void refreshAccess().catch((error) => console.warn("Unable to refresh subscription access:", error));
|
||
}
|
||
}, [accessToken, refreshAccess]),
|
||
);
|
||
|
||
const showAlert = (alertTitle: string, message: string, onConfirm?: () => void) => {
|
||
if (Platform.OS === "web") {
|
||
alert(`${alertTitle}\n\n${message}`);
|
||
onConfirm?.();
|
||
return;
|
||
}
|
||
Alert.alert(
|
||
alertTitle,
|
||
message,
|
||
onConfirm ? [{ text: "Cancel", style: "cancel" }, { text: "Continue", onPress: onConfirm }] : [{ text: "OK" }],
|
||
);
|
||
};
|
||
|
||
const handleCheckout = async () => {
|
||
if (!accessToken) {
|
||
router.push("/login");
|
||
return;
|
||
}
|
||
if (!planCode) {
|
||
showAlert("Subscription unavailable", "No access plan is configured for this module.");
|
||
return;
|
||
}
|
||
|
||
setOpeningCheckout(true);
|
||
try {
|
||
const storefrontUrl = resolveStorefrontUrl();
|
||
const query = new URLSearchParams();
|
||
query.set("token", accessToken);
|
||
query.set("planCode", planCode);
|
||
if (couponCode.trim()) query.set("couponCode", couponCode.trim().toUpperCase());
|
||
const apiUrl = process.env.EXPO_PUBLIC_API_URL;
|
||
if (apiUrl) query.set("apiUrl", apiUrl);
|
||
if (moduleId) query.set("moduleId", moduleId);
|
||
if (moduleCode) query.set("moduleCode", moduleCode);
|
||
|
||
const checkoutUrl = `${storefrontUrl}?${query.toString()}`;
|
||
showAlert(
|
||
"Complete payment",
|
||
"Checkout will open in the secure web storefront. Return to AcuPedia after payment; access will refresh automatically.",
|
||
() => { void Linking.openURL(checkoutUrl); },
|
||
);
|
||
} catch {
|
||
showAlert("Unable to open checkout", "Please try again.");
|
||
} finally {
|
||
setOpeningCheckout(false);
|
||
}
|
||
};
|
||
|
||
return (
|
||
<SafeAreaView style={styles.safeArea} edges={["top", "left", "right"]}>
|
||
<View style={styles.header}>
|
||
<TouchableOpacity onPress={() => router.back()} style={styles.backButton}>
|
||
<Ionicons name="chevron-back" size={24} color={Colors.textPrimary} />
|
||
</TouchableOpacity>
|
||
<Text style={styles.headerTitle}>Subscription</Text>
|
||
<View style={styles.placeholder} />
|
||
</View>
|
||
|
||
<ScrollView contentContainerStyle={styles.content} showsVerticalScrollIndicator={false}>
|
||
<View style={styles.iconContainer}>
|
||
<Ionicons name={unlocked ? "checkmark-circle-outline" : "card-outline"} size={58} color={Colors.primary} />
|
||
</View>
|
||
<Text style={styles.title}>{unlocked ? `${title} is unlocked` : `Unlock ${title}`}</Text>
|
||
<Text style={styles.subtitle}>
|
||
{unlocked
|
||
? "Your current entitlement already includes this module."
|
||
: "Pricing and discounts below are calculated by the current commerce API."}
|
||
</Text>
|
||
|
||
{(category || description) ? (
|
||
<View style={styles.infoBox}>
|
||
<Ionicons name="information-circle-outline" size={20} color={Colors.primary} />
|
||
<View style={styles.infoText}>
|
||
{category ? <Text style={styles.infoTitle}>{category}</Text> : null}
|
||
{description ? <Text style={styles.infoDescription}>{description}</Text> : null}
|
||
{planCode ? <Text style={styles.planCode}>Plan: {planCode}</Text> : null}
|
||
</View>
|
||
</View>
|
||
) : null}
|
||
|
||
{!unlocked ? (
|
||
<>
|
||
<View style={styles.pricingCard}>
|
||
{loadingPricing ? (
|
||
<View style={styles.loadingRow}>
|
||
<ActivityIndicator color={Colors.primary} />
|
||
<Text style={styles.loadingText}>Loading current pricing…</Text>
|
||
</View>
|
||
) : pricing ? (
|
||
<>
|
||
{pricing.cart_items.map((item) => (
|
||
<View key={item.code} style={styles.priceRow}>
|
||
<Text style={styles.priceLabel}>{item.name}</Text>
|
||
<Text style={styles.priceValue}>{money(item.price, pricing.currency)}</Text>
|
||
</View>
|
||
))}
|
||
<View style={styles.divider} />
|
||
<View style={styles.priceRow}><Text style={styles.secondaryLabel}>Subtotal</Text><Text style={styles.secondaryValue}>{money(pricing.base_subtotal, pricing.currency)}</Text></View>
|
||
{pricing.total_discounts > 0 ? <View style={styles.priceRow}><Text style={styles.discountLabel}>Discounts</Text><Text style={styles.discountValue}>− {money(pricing.total_discounts, pricing.currency)}</Text></View> : null}
|
||
{pricing.convenience_fee > 0 ? <View style={styles.priceRow}><Text style={styles.secondaryLabel}>Convenience fee</Text><Text style={styles.secondaryValue}>{money(pricing.convenience_fee, pricing.currency)}</Text></View> : null}
|
||
<View style={styles.priceRow}><Text style={styles.secondaryLabel}>GST</Text><Text style={styles.secondaryValue}>{money(pricing.gst_amount, pricing.currency)}</Text></View>
|
||
<View style={styles.divider} />
|
||
<View style={styles.priceRow}><Text style={styles.totalLabel}>Total</Text><Text style={styles.totalValue}>{money(pricing.grand_total, pricing.currency)}</Text></View>
|
||
{pricing.coupon_applied ? <Text style={styles.appliedText}>Coupon applied: {pricing.coupon_applied}</Text> : null}
|
||
</>
|
||
) : (
|
||
<Text style={styles.errorText}>{error ?? "Pricing is unavailable."}</Text>
|
||
)}
|
||
</View>
|
||
|
||
<View style={styles.couponRow}>
|
||
<TextInput
|
||
value={couponCode}
|
||
onChangeText={setCouponCode}
|
||
autoCapitalize="characters"
|
||
placeholder="Coupon code"
|
||
style={styles.couponInput}
|
||
/>
|
||
<TouchableOpacity
|
||
style={styles.applyButton}
|
||
onPress={() => void loadPricing(couponCode)}
|
||
disabled={loadingPricing}
|
||
>
|
||
<Text style={styles.applyText}>Apply</Text>
|
||
</TouchableOpacity>
|
||
</View>
|
||
|
||
{error && pricing ? <Text style={styles.inlineError}>{error}</Text> : null}
|
||
|
||
<View style={styles.buttonContainer}>
|
||
{openingCheckout ? <ActivityIndicator color={Colors.primary} /> : (
|
||
<PrimaryButton
|
||
title={accessToken ? "Continue to Checkout" : "Log In to Subscribe"}
|
||
onPress={() => void handleCheckout()}
|
||
disabled={loadingPricing || !planCode}
|
||
/>
|
||
)}
|
||
</View>
|
||
</>
|
||
) : (
|
||
<View style={styles.buttonContainer}>
|
||
<PrimaryButton title="Back to Modules" onPress={() => router.replace("/modules")} />
|
||
</View>
|
||
)}
|
||
</ScrollView>
|
||
</SafeAreaView>
|
||
);
|
||
}
|
||
|
||
const styles = StyleSheet.create({
|
||
safeArea: { flex: 1, backgroundColor: "#FFFFFF" },
|
||
header: {
|
||
minHeight: 64,
|
||
flexDirection: "row",
|
||
alignItems: "center",
|
||
justifyContent: "space-between",
|
||
paddingHorizontal: moderateScale(16),
|
||
paddingTop: Platform.OS === "web" ? 14 : moderateScale(8),
|
||
paddingBottom: moderateScale(8),
|
||
borderBottomWidth: 1,
|
||
borderBottomColor: "#ECECEC",
|
||
backgroundColor: "#FFFFFF",
|
||
},
|
||
backButton: { padding: 4 },
|
||
headerTitle: { fontSize: moderateScale(18), fontWeight: "700", color: Colors.textPrimary },
|
||
placeholder: { width: 32 },
|
||
content: { paddingHorizontal: moderateScale(24), paddingTop: verticalScale(28), paddingBottom: verticalScale(40) },
|
||
iconContainer: { alignItems: "center", marginBottom: verticalScale(16) },
|
||
title: { fontSize: moderateScale(24), fontWeight: "800", color: Colors.textPrimary, textAlign: "center" },
|
||
subtitle: { fontSize: moderateScale(14), color: Colors.textSecondary, textAlign: "center", lineHeight: 20, marginTop: verticalScale(8), marginBottom: verticalScale(22) },
|
||
infoBox: { flexDirection: "row", backgroundColor: "#EEF2FF", borderRadius: moderateScale(14), padding: moderateScale(14), marginBottom: verticalScale(18) },
|
||
infoText: { flex: 1, marginLeft: moderateScale(10) },
|
||
infoTitle: { fontSize: moderateScale(14), fontWeight: "700", color: Colors.textPrimary },
|
||
infoDescription: { marginTop: 3, fontSize: moderateScale(12), color: Colors.textSecondary, lineHeight: 18 },
|
||
planCode: { marginTop: 5, fontSize: moderateScale(11), color: Colors.primary, fontWeight: "600" },
|
||
pricingCard: { backgroundColor: "#FFFFFF", borderRadius: moderateScale(16), borderWidth: 1, borderColor: "#E5E7EB", padding: moderateScale(16) },
|
||
loadingRow: { flexDirection: "row", alignItems: "center", justifyContent: "center", paddingVertical: verticalScale(16) },
|
||
loadingText: { marginLeft: moderateScale(10), color: Colors.textSecondary, fontSize: moderateScale(13) },
|
||
priceRow: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", marginVertical: verticalScale(5) },
|
||
priceLabel: { flex: 1, fontSize: moderateScale(14), fontWeight: "700", color: Colors.textPrimary, marginRight: 10 },
|
||
priceValue: { fontSize: moderateScale(14), fontWeight: "700", color: Colors.textPrimary },
|
||
secondaryLabel: { fontSize: moderateScale(13), color: Colors.textSecondary },
|
||
secondaryValue: { fontSize: moderateScale(13), color: Colors.textPrimary },
|
||
discountLabel: { fontSize: moderateScale(13), color: "#15803D" },
|
||
discountValue: { fontSize: moderateScale(13), color: "#15803D", fontWeight: "600" },
|
||
totalLabel: { fontSize: moderateScale(15), fontWeight: "800", color: Colors.textPrimary },
|
||
totalValue: { fontSize: moderateScale(18), fontWeight: "800", color: Colors.primary },
|
||
divider: { height: 1, backgroundColor: "#ECECEC", marginVertical: verticalScale(8) },
|
||
appliedText: { marginTop: verticalScale(8), fontSize: moderateScale(12), color: "#15803D", fontWeight: "600" },
|
||
errorText: { fontSize: moderateScale(13), color: "#B91C1C", textAlign: "center", paddingVertical: verticalScale(14) },
|
||
couponRow: { flexDirection: "row", marginTop: verticalScale(14) },
|
||
couponInput: { flex: 1, minHeight: 46, backgroundColor: "#FFFFFF", borderWidth: 1, borderColor: "#D1D5DB", borderRadius: moderateScale(12), paddingHorizontal: moderateScale(12), color: Colors.textPrimary },
|
||
applyButton: { marginLeft: moderateScale(10), minWidth: 78, minHeight: 46, alignItems: "center", justifyContent: "center", backgroundColor: "#EEF2FF", borderRadius: moderateScale(12) },
|
||
applyText: { fontSize: moderateScale(13), fontWeight: "700", color: Colors.primary },
|
||
inlineError: { marginTop: verticalScale(8), fontSize: moderateScale(12), color: "#B91C1C" },
|
||
buttonContainer: { marginTop: verticalScale(24) },
|
||
});
|