Compare commits

...

17 Commits

Author SHA1 Message Date
Urvish Prajapati 3dbbe11dfa feat(docker): add production docker setup and container git metadata tracking
- Copy .git_store_info into container to identify running branch and commit
- Ignore generated .git_*_info in .gitignore
- Add production multi-stage Dockerfile and Nginx reverse proxy configuration
2026-10-13 11:28:02 +05:30
Amit Salunke 75acd1de92 Merge pull request 'Issue 8 (web): dynamically reflect updated module categories on storefront' (#46) from fix-module-category-reflection into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-store-ui/pulls/46
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-10 11:08:53 +00:00
ShivaniKhaire 870b3062d6 fix: dynamically reflect updated module categories on storefront 2026-10-09 16:37:07 +05:30
Amit Salunke f6ca709225 Merge pull request 'fix(auth): disallow emojis in password' (#41) from fix/disallow-emoji-in-password into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-store-ui/pulls/41
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-09 04:57:12 +00:00
Amit Salunke 26419ba194 Merge pull request 'Issue 21: Fix enforce email format validation and prevent silent form submission blocking' (#24) from fix/issue-21-email-format-validation into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-store-ui/pulls/24
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-09 04:56:31 +00:00
Amit Salunke e8997cc922 Merge pull request 'Issue 15 : fix ensure dynamic currency price display and prevent stale cart calculations' (#22) from fix/issue-15-usd-cart-calculation into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-store-ui/pulls/22
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-09 04:46:42 +00:00
Amit Salunke f6f1ad1d45 Merge pull request 'issue 12 : fix back navigation library' (#19) from fix/issue-12-back-navigation-library into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-store-ui/pulls/19
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-09 04:46:13 +00:00
Amit Salunke 829f58cc23 Merge pull request 'build(store): add production Dockerfile and Nginx reverse proxy configuration' (#2) from standalone-dockerfile into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-store-ui/pulls/2
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-09 04:45:16 +00:00
ShivaniKhaire 9218d038ae fix(auth): disallow emojis in password 2026-10-08 16:44:57 +05:30
ShivaniKhaire d3098cfdbf Merge main into fix/issue-21-email-format-validation 2026-10-07 14:23:22 +05:30
ShivaniKhaire d0e6d880e1 Merge origin/main and resolve conflict in src/App.tsx 2026-10-07 13:35:50 +05:30
ShivaniKhaire 720a9b165c Merge main into fix/issue-12-back-navigation-library 2026-10-07 13:16:36 +05:30
ShivaniKhaire b1f9c45d46 fix(auth): enforce email format validation and prevent silent form submission blocking 2026-10-05 17:36:32 +05:30
ShivaniKhaire 341eb64079 fix(cart): ensure dynamic currency price display and prevent stale cart calculations 2026-10-05 15:46:35 +05:30
ShivaniKhaire 537e92cced refactor(navigation): make mobile deep link navigation completely generic and dynamic (#12) 2026-10-05 14:37:11 +05:30
ShivaniKhaire 3f536986de fix(checkout): redirect back navigation to library after module purchase (#12) 2026-10-05 14:23:21 +05:30
Urvish Prajapati eab1709d14 build(store): add production Dockerfile and Nginx reverse proxy configuration
- Add multi-stage Node build and Nginx Alpine runtime Dockerfile supporting VITE_BASE_PATH
- Configure nginx.conf to serve storefront under /store/ subpath with SPA routing and API reverse proxy
- Add .dockerignore to optimize container build context
2026-09-17 14:24:15 +05:30
9 changed files with 373 additions and 41 deletions

8
.dockerignore Normal file
View File

@ -0,0 +1,8 @@
node_modules
dist
.git
.env
.env.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

4
.gitignore vendored
View File

@ -27,3 +27,7 @@ dist-ssr
.env .env
.env.* .env.*
!.env.example !.env.example
# Generated Git Info
.git_*_info

37
Dockerfile Normal file
View File

@ -0,0 +1,37 @@
# ============================================================
# Panacea Storefront — Frontend Dockerfile
# Multi-stage: Node 22 build → Nginx alpine runtime
# ============================================================
FROM node:22-alpine AS builder
WORKDIR /app
# Copy package files and install dependencies
COPY package.json package-lock.json ./
RUN npm ci
# Copy store frontend source files
COPY . ./
ARG VITE_API_BASE=""
ENV VITE_API_BASE=${VITE_API_BASE}
ARG VITE_BASE_PATH="/store/"
ENV VITE_BASE_PATH=${VITE_BASE_PATH}
RUN npm run build
FROM nginx:1.27-alpine AS runtime
RUN rm /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=builder /app/dist /usr/share/nginx/html
# Copy git info metadata if generated on host
COPY .git_store_info* /app/.git_store_info
RUN ln -sf /usr/share/nginx/html /usr/share/nginx/html/store
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

56
nginx.conf Normal file
View File

@ -0,0 +1,56 @@
# ============================================================
# Panacea Storefront — Nginx Configuration (Port 3000)
# Serves storefront static files at /store + reverse proxies /api
# ============================================================
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml text/javascript image/svg+xml;
gzip_min_length 256;
# Reverse proxy — Route /api requests to FastAPI backend
location /api/ {
proxy_pass http://backend:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_connect_timeout 60s;
proxy_send_timeout 120s;
proxy_read_timeout 120s;
}
# Handle /store subpath
location ^~ /store {
rewrite ^/store/?(.*)$ /$1 break;
try_files $uri $uri/ /index.html;
add_header Cache-Control "no-cache, no-store, must-revalidate";
add_header Pragma "no-cache";
add_header Expires 0;
}
# Root fallback
location / {
try_files $uri $uri/ /index.html;
add_header Cache-Control "no-cache, no-store, must-revalidate";
add_header Pragma "no-cache";
add_header Expires 0;
}
# Cache static assets
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
}

View File

@ -19,6 +19,7 @@ import { AuthModal } from './components/auth/AuthModal';
import { ProfileDrawer } from './components/auth/ProfileDrawer'; import { ProfileDrawer } from './components/auth/ProfileDrawer';
import { PaymentSuccessModal } from './components/checkout/PaymentSuccessModal'; import { PaymentSuccessModal } from './components/checkout/PaymentSuccessModal';
import { PasswordUpdatedModal } from './components/auth/PasswordUpdatedModal'; import { PasswordUpdatedModal } from './components/auth/PasswordUpdatedModal';
import { openMobileApp, DEFAULT_RETURN_ROUTE } from './utils/navigation';
const getInitialTab = (): 'storefront' | 'subscriptions' => { const getInitialTab = (): 'storefront' | 'subscriptions' => {
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
@ -43,14 +44,6 @@ export default function App() {
} }
}; };
useEffect(() => {
const handlePopState = () => {
setActiveTab(getInitialTab());
};
window.addEventListener('popstate', handlePopState);
return () => window.removeEventListener('popstate', handlePopState);
}, []);
const [currency, setCurrency] = useState<Currency>('INR'); const [currency, setCurrency] = useState<Currency>('INR');
// Auth state // Auth state
@ -106,6 +99,29 @@ export default function App() {
// Active payment state // Active payment state
const [verificationResult, setVerificationResult] = useState<VerificationResult | null>(null); const [verificationResult, setVerificationResult] = useState<VerificationResult | null>(null);
const [razorpayKeyId, setRazorpayKeyId] = useState<string>(''); const [razorpayKeyId, setRazorpayKeyId] = useState<string>('');
const [returnRoute, setReturnRoute] = useState<string>(DEFAULT_RETURN_ROUTE);
const [appScheme, setAppScheme] = useState<string | undefined>(undefined);
// Handle browser back button navigation
useEffect(() => {
const handlePopState = () => {
// If purchase was completed and user presses the Back button,
// redirect them to the mobile app's All Modules / Library instead of Subscription page
if (verificationResult && verificationResult.status === 'success') {
const isMobile = /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
if (isMobile) {
openMobileApp({ route: returnRoute, schemes: appScheme ? [appScheme] : undefined });
} else {
switchTab('subscriptions');
setVerificationResult(null);
}
return;
}
setActiveTab(getInitialTab());
};
window.addEventListener('popstate', handlePopState);
return () => window.removeEventListener('popstate', handlePopState);
}, [verificationResult, returnRoute, appScheme]);
// Profile Update & Drawer State // Profile Update & Drawer State
const [showProfileDrawer, setShowProfileDrawer] = useState<boolean>(false); const [showProfileDrawer, setShowProfileDrawer] = useState<boolean>(false);
@ -130,6 +146,67 @@ export default function App() {
} }
}; };
// Dynamic Curriculum Modules with Live Categories
const [curriculumModules, setCurriculumModules] = useState<ModuleItem[]>(CURRICULUM_MODULES);
const fetchModuleCategories = async () => {
try {
const res = await axios.get(`${API_BASE}/api/contents/modules`);
const apiModules: any[] = res.data?.modules || [];
if (apiModules.length > 0) {
const normalizeCategory = (cat?: string) => {
if (!cat) return null;
const c = cat.toLowerCase();
if (c === 'point' || c === 'points') return 'Points';
if (c === 'pattern' || c === 'patterns') return 'Pattern';
if (c === 'nutrition') return 'Nutrition';
if (c === 'therapeutics' || c === 'therapeutic') return 'Therapeutics';
return cat;
};
setCurriculumModules((prev) =>
prev.map((item) => {
const matched = apiModules.find((m) => {
const mCode = (m.code || '').toLowerCase();
const iCode = (item.code || '').toLowerCase();
if (mCode && iCode && mCode === iCode) return true;
const slug = (m.slug || '').toLowerCase();
const mName = (m.name || '').toLowerCase();
const iName = item.name.toLowerCase();
const cleanI = iName.replace('points:', '').replace('therapeutics:', '').split('(')[0].trim();
const cleanM = mName.replace('points:', '').replace('therapeutics:', '').split('(')[0].trim();
if (cleanI.includes('acu') && cleanM.includes('acupuncture') && !cleanI.includes('scalp') && !cleanI.includes('ear')) return true;
if (cleanI.includes('scalp') && cleanM.includes('scalp')) return true;
if (cleanI.includes('ear') && (cleanM.includes('ear') || slug.includes('auriculo'))) return true;
if (cleanI.includes('gyneco') && slug.includes('gyneco')) return true;
if (cleanI.includes('eight') && slug.includes('eight')) return true;
if (cleanI.includes('zang') && slug.includes('tcm-pattern')) return true;
if (cleanI.includes('qi') && slug.includes('qi')) return true;
if (cleanI.includes('pathogenic') && slug.includes('pathogenic')) return true;
if (cleanI.includes('six') && slug.includes('six')) return true;
if (cleanI.includes('four') && slug.includes('four')) return true;
if (cleanI.includes('three') && slug.includes('three')) return true;
if (cleanI.includes('five') && slug.includes('five')) return true;
if (cleanI.includes('food') && slug.includes('nutrition')) return true;
return false;
});
const updatedCat = normalizeCategory(matched?.metadata?.category || matched?.category);
if (updatedCat) {
return { ...item, category: updatedCat };
}
return item;
})
);
}
} catch (err) {
console.error('Failed to load module categories:', err);
}
};
const getLivePlan = (code: string) => { const getLivePlan = (code: string) => {
return publicPlans.find(p => p.code === code || p.base_code === code); return publicPlans.find(p => p.code === code || p.base_code === code);
}; };
@ -157,6 +234,15 @@ export default function App() {
const params = new URLSearchParams(window.location.search); const params = new URLSearchParams(window.location.search);
const urlToken = params.get('token'); const urlToken = params.get('token');
const urlPlanCode = params.get('planCode'); const urlPlanCode = params.get('planCode');
const urlReturnRoute = params.get('returnRoute') || params.get('redirectPath') || params.get('redirect');
const urlScheme = params.get('scheme');
if (urlReturnRoute) {
setReturnRoute(urlReturnRoute);
}
if (urlScheme) {
setAppScheme(urlScheme);
}
let activeToken = userToken; let activeToken = userToken;
@ -168,7 +254,7 @@ export default function App() {
} }
if (urlPlanCode) { if (urlPlanCode) {
const targetModule = CURRICULUM_MODULES.find(m => m.code === urlPlanCode); const targetModule = curriculumModules.find(m => m.code === urlPlanCode);
if (targetModule) { if (targetModule) {
setCart([targetModule]); setCart([targetModule]);
setShowLockedByCategory(prev => ({ setShowLockedByCategory(prev => ({
@ -193,6 +279,7 @@ export default function App() {
}); });
fetchPublicPlans(); fetchPublicPlans();
fetchModuleCategories();
if (activeToken && !urlToken) { if (activeToken && !urlToken) {
fetchUserProfile(activeToken); fetchUserProfile(activeToken);
@ -304,6 +391,33 @@ export default function App() {
setAuthLoading(true); setAuthLoading(true);
setAuthError(null); setAuthError(null);
const trimmedEmail = authEmail.trim();
if (!trimmedEmail) {
setAuthError('Email address is required.');
setAuthLoading(false);
return;
}
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(trimmedEmail)) {
setAuthError('Please enter a valid email address.');
setAuthLoading(false);
return;
}
if (!authPassword) {
setAuthError('Password is required.');
setAuthLoading(false);
return;
}
if (authMode === 'register' && !authDisplayName.trim()) {
setAuthError('Display name is required.');
setAuthLoading(false);
return;
}
if (authMode === 'register' && authPhone && authPhone.trim()) { if (authMode === 'register' && authPhone && authPhone.trim()) {
const phoneError = validatePhoneNumber(authPhone, authDialCode, authCountry); const phoneError = validatePhoneNumber(authPhone, authDialCode, authCountry);
if (phoneError) { if (phoneError) {
@ -331,20 +445,26 @@ export default function App() {
setAuthLoading(false); setAuthLoading(false);
return; return;
} }
if (!/[^A-Za-z0-9\s]/.test(authPassword)) { if (/\p{Extended_Pictographic}/u.test(authPassword)) {
setAuthError('Password must not contain emojis.');
setAuthLoading(false);
return;
}
if (!/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?`~]/.test(authPassword)) {
setAuthError('Password must contain at least one special character.'); setAuthError('Password must contain at least one special character.');
setAuthLoading(false); setAuthLoading(false);
return; return;
} }
} }
const fullPhone = authPhone ? `${authDialCode}${authPhone}` : undefined; const fullPhone = authPhone ? `${authDialCode}${authPhone}` : undefined;
const payload = authMode === 'login' const payload = authMode === 'login'
? { email: authEmail, password: authPassword } ? { email: trimmedEmail, password: authPassword }
: { : {
email: authEmail, email: trimmedEmail,
password: authPassword, password: authPassword,
full_name: authDisplayName || undefined, full_name: authDisplayName.trim() || undefined,
phone_number: fullPhone, phone_number: fullPhone,
country: authCountry country: authCountry
}; };
@ -428,9 +548,23 @@ export default function App() {
setAuthError(null); setAuthError(null);
setResetSuccessMessage(null); setResetSuccessMessage(null);
const trimmedEmail = authEmail.trim();
if (!trimmedEmail) {
setAuthError('Email address is required.');
setAuthLoading(false);
return;
}
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(trimmedEmail)) {
setAuthError('Please enter a valid email address.');
setAuthLoading(false);
return;
}
try { try {
const res = await axios.post(`${API_BASE}/api/auth/forgot-password`, { const res = await axios.post(`${API_BASE}/api/auth/forgot-password`, {
email: authEmail email: trimmedEmail
}); });
setResetSuccessMessage(res.data.message || 'Verification code sent to your email.'); setResetSuccessMessage(res.data.message || 'Verification code sent to your email.');
setResetStep('verify'); setResetStep('verify');
@ -495,6 +629,22 @@ export default function App() {
} }
}; };
// Keep cart items dynamic prices updated when publicPlans are loaded
useEffect(() => {
if (publicPlans.length > 0 && cart.length > 0) {
setCart(prev =>
prev.map(item => {
const live = getModulePrice(item);
return {
...item,
priceInr: live.priceInr,
priceUsd: live.priceUsd,
};
})
);
}
}, [publicPlans]);
const calculatePricing = async () => { const calculatePricing = async () => {
setLoadingPricing(true); setLoadingPricing(true);
try { try {
@ -512,11 +662,15 @@ export default function App() {
setPricingCalc(calcData); setPricingCalc(calcData);
} catch (err: any) { } catch (err: any) {
console.error('Pricing engine calculation error:', err); console.error('Pricing engine calculation error:', err);
if (appliedCoupon) {
const errorMsg = err.response?.data?.detail || 'Invalid or expired coupon code.'; const errorMsg = err.response?.data?.detail || 'Invalid or expired coupon code.';
setPricingCalc((prev: any) => ({ setPricingCalc((prev: any) => ({
...(prev || {}), ...(prev || {}),
coupon_error: errorMsg coupon_error: errorMsg,
})); }));
} else {
setPricingCalc(null);
}
} finally { } finally {
setLoadingPricing(false); setLoadingPricing(false);
} }
@ -742,7 +896,13 @@ export default function App() {
message: verifyRes.data.message || 'Payment verified successfully and module entitlements unlocked!' message: verifyRes.data.message || 'Payment verified successfully and module entitlements unlocked!'
}); });
// If on mobile browser, automatically attempt to redirect to mobile app after successful payment
// Push a history state so that pressing browser/device Back button will be intercepted
// by popstate and redirected to All Modules / Library instead of returning to the Subscription page
if (typeof window !== 'undefined') {
window.history.pushState({ paymentCompleted: true }, document.title, window.location.href);
}
if (/Android|iPhone|iPad|iPod/i.test(navigator.userAgent)) { if (/Android|iPhone|iPad|iPod/i.test(navigator.userAgent)) {
setTimeout(() => { setTimeout(() => {
if (/Android/i.test(navigator.userAgent)) { if (/Android/i.test(navigator.userAgent)) {
@ -847,7 +1007,7 @@ export default function App() {
<div className="grid grid-cols-1 xl:grid-cols-3 gap-6 xl:gap-8"> <div className="grid grid-cols-1 xl:grid-cols-3 gap-6 xl:gap-8">
{/* 📦 Catalog Section */} {/* 📦 Catalog Section */}
<CatalogSection <CatalogSection
curriculumModules={CURRICULUM_MODULES} curriculumModules={curriculumModules}
publicPlans={publicPlans} publicPlans={publicPlans}
cart={cart} cart={cart}
currency={currency} currency={currency}
@ -905,7 +1065,7 @@ export default function App() {
setShowAuthModal(true); setShowAuthModal(true);
}} }}
onSwitchTab={switchTab} onSwitchTab={switchTab}
curriculumModules={CURRICULUM_MODULES} curriculumModules={curriculumModules}
/> />
)} )}
@ -957,6 +1117,8 @@ export default function App() {
loggedInUser={loggedInUser} loggedInUser={loggedInUser}
onDownloadInvoice={handleDownloadCheckoutInvoice} onDownloadInvoice={handleDownloadCheckoutInvoice}
downloadingInvoice={downloadingModalInvoice} downloadingInvoice={downloadingModalInvoice}
returnRoute={returnRoute}
appScheme={appScheme}
/> />
)} )}
@ -993,7 +1155,7 @@ export default function App() {
setShowProfileDrawer(false); setShowProfileDrawer(false);
switchTab('storefront'); switchTab('storefront');
}} }}
curriculumModules={CURRICULUM_MODULES} curriculumModules={curriculumModules}
/> />
{/* 🔐 Password Updated Success Modal */} {/* 🔐 Password Updated Success Modal */}

View File

@ -134,7 +134,7 @@ export const AuthModal: React.FC<AuthModalProps> = ({
{/* Forgot Password Flow */} {/* Forgot Password Flow */}
{authMode === 'forgot' ? ( {authMode === 'forgot' ? (
resetStep === 'request' ? ( resetStep === 'request' ? (
<form onSubmit={onForgotPasswordRequest} className="space-y-4 text-left"> <form onSubmit={onForgotPasswordRequest} noValidate className="space-y-4 text-left">
<div className="space-y-1.5"> <div className="space-y-1.5">
<label className="text-[10px] uppercase font-black tracking-wider text-slate-500"> <label className="text-[10px] uppercase font-black tracking-wider text-slate-500">
Registered Email Address Registered Email Address
@ -171,7 +171,7 @@ export const AuthModal: React.FC<AuthModalProps> = ({
</div> </div>
</form> </form>
) : ( ) : (
<form onSubmit={onResetPasswordSubmit} className="space-y-4 text-left"> <form onSubmit={onResetPasswordSubmit} noValidate className="space-y-4 text-left">
<div className="space-y-1.5"> <div className="space-y-1.5">
<label className="text-[10px] uppercase font-black tracking-wider text-slate-500"> <label className="text-[10px] uppercase font-black tracking-wider text-slate-500">
6-Digit Verification Code (OTP) 6-Digit Verification Code (OTP)
@ -249,7 +249,7 @@ export const AuthModal: React.FC<AuthModalProps> = ({
) )
) : ( ) : (
/* Standard Login & Register Form */ /* Standard Login & Register Form */
<form onSubmit={onAuthSubmit} className="space-y-4 text-left"> <form onSubmit={onAuthSubmit} noValidate className="space-y-4 text-left">
{/* Common: Email */} {/* Common: Email */}
<div className="space-y-1.5"> <div className="space-y-1.5">
<label className="text-[10px] uppercase font-black tracking-wider text-slate-500"> <label className="text-[10px] uppercase font-black tracking-wider text-slate-500">

View File

@ -102,11 +102,16 @@ export const CartDrawer: React.FC<CartDrawerProps> = ({
</div> </div>
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<span className="text-xs font-bold text-indigo-600"> <span className="text-xs font-bold text-indigo-600">
{currency === 'INR' {(() => {
? `₹${item.priceInr}` const calculatedItem = pricingCalc?.currency === currency
: currency === 'EUR' ? pricingCalc?.cart_items?.find((ci: any) => ci.code === item.code)
? `€${item.priceEur}` : null;
: `$${item.priceUsd}`} const price = calculatedItem
? calculatedItem.price
: (currency === 'INR' ? item.priceInr : currency === 'EUR' ? item.priceEur : item.priceUsd);
const symbol = currency === 'INR' ? '₹' : currency === 'EUR' ? '€' : '$';
return `${symbol}${price}`;
})()}
</span> </span>
<button <button
onClick={() => toggleCartItem(item)} onClick={() => toggleCartItem(item)}
@ -173,7 +178,13 @@ export const CartDrawer: React.FC<CartDrawerProps> = ({
)} )}
{/* Checkout Summary Calculations */} {/* Checkout Summary Calculations */}
{pricingCalc && cart.length > 0 && ( {loadingPricing && (!pricingCalc || pricingCalc.currency !== currency) && (
<div className="flex items-center justify-center p-6 bg-slate-50 border border-slate-200/60 rounded-2xl gap-2 text-xs font-semibold text-slate-500">
<RefreshCw className="h-4 w-4 animate-spin text-indigo-600" />
<span>Calculating {currency} pricing...</span>
</div>
)}
{pricingCalc && pricingCalc.currency === currency && cart.length > 0 && (
<div className="space-y-3 bg-slate-50 border border-slate-200/60 p-4 rounded-2xl"> <div className="space-y-3 bg-slate-50 border border-slate-200/60 p-4 rounded-2xl">
<div className="flex justify-between text-xs text-slate-600 font-bold"> <div className="flex justify-between text-xs text-slate-600 font-bold">
<span>Base Subtotal</span> <span>Base Subtotal</span>

View File

@ -1,6 +1,7 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
import { XCircle, CheckCircle, Check, Download, RefreshCw, Smartphone } from 'lucide-react'; import { XCircle, CheckCircle, Check, Download, RefreshCw, Smartphone } from 'lucide-react';
import type { VerificationResult, UserProfile } from '../../types'; import type { VerificationResult, UserProfile } from '../../types';
import { openMobileApp, getAppDeepLinkUrls } from '../../utils/navigation';
interface PaymentSuccessModalProps { interface PaymentSuccessModalProps {
verificationResult: VerificationResult; verificationResult: VerificationResult;
@ -8,6 +9,8 @@ interface PaymentSuccessModalProps {
loggedInUser: UserProfile | null; loggedInUser: UserProfile | null;
onDownloadInvoice: (paymentId: string, invoiceUrl?: string) => void; onDownloadInvoice: (paymentId: string, invoiceUrl?: string) => void;
downloadingInvoice: boolean; downloadingInvoice: boolean;
returnRoute?: string;
appScheme?: string;
} }
export const PaymentSuccessModal: React.FC<PaymentSuccessModalProps> = ({ export const PaymentSuccessModal: React.FC<PaymentSuccessModalProps> = ({
@ -16,6 +19,8 @@ export const PaymentSuccessModal: React.FC<PaymentSuccessModalProps> = ({
loggedInUser, loggedInUser,
onDownloadInvoice, onDownloadInvoice,
downloadingInvoice, downloadingInvoice,
returnRoute,
appScheme,
}) => { }) => {
const [desktopNotice, setDesktopNotice] = useState(false); const [desktopNotice, setDesktopNotice] = useState(false);
@ -211,15 +216,18 @@ export const PaymentSuccessModal: React.FC<PaymentSuccessModalProps> = ({
</button> </button>
)} )}
{/* Open in App Button */}
{/* Open in App Button */} {/* Open in App Button */}
<a <a
href="acupedia://" href={getAppDeepLinkUrls({ route: returnRoute, schemes: appScheme ? [appScheme] : undefined })[0]}
id="open-in-app-btn" onClick={(e) => {
onClick={handleOpenApp} e.preventDefault();
openMobileApp({ route: returnRoute, schemes: appScheme ? [appScheme] : undefined });
}}
className="w-full h-9 bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs rounded-lg transition-all duration-300 flex items-center justify-center gap-2 shadow-md shadow-emerald-600/10 no-underline decoration-0 cursor-pointer" className="w-full h-9 bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs rounded-lg transition-all duration-300 flex items-center justify-center gap-2 shadow-md shadow-emerald-600/10 no-underline decoration-0 cursor-pointer"
> >
<Smartphone className="h-3.5 w-3.5 text-emerald-200" /> <Smartphone className="h-3.5 w-3.5 text-emerald-200" />
Open in App Open in App / Library
</a> </a>
{desktopNotice && ( {desktopNotice && (

46
src/utils/navigation.ts Normal file
View File

@ -0,0 +1,46 @@
/**
* Generic Navigation & Deep-Linking Utility for Acupedia Storefront
*/
export const DEFAULT_APP_SCHEMES = ['acupedia', 'myapp'];
export const DEFAULT_RETURN_ROUTE = 'modules';
export interface MobileAppLaunchOptions {
route?: string;
schemes?: string[];
delayBetweenFallbacks?: number;
}
/**
* Cleanly format route for custom URI scheme (e.g. "/modules" -> "modules")
*/
export function formatDeepLinkRoute(route?: string): string {
if (!route) return DEFAULT_RETURN_ROUTE;
return route.replace(/^\/+/, '').trim() || DEFAULT_RETURN_ROUTE;
}
/**
* Generate full deep-link URLs for supported schemes
*/
export function getAppDeepLinkUrls(options: MobileAppLaunchOptions = {}): string[] {
const route = formatDeepLinkRoute(options.route);
const schemes = options.schemes && options.schemes.length > 0 ? options.schemes : DEFAULT_APP_SCHEMES;
return schemes.map((scheme) => `${scheme}://${route}`);
}
/**
* Generic function to launch the mobile app with progressive fallback across supported schemes
*/
export function openMobileApp(options: MobileAppLaunchOptions = {}): void {
const urls = getAppDeepLinkUrls(options);
if (urls.length === 0) return;
const [primaryUrl, ...fallbackUrls] = urls;
window.location.href = primaryUrl;
fallbackUrls.forEach((url, idx) => {
setTimeout(() => {
window.location.href = url;
}, (idx + 1) * (options.delayBetweenFallbacks || 500));
});
}