import { createRouter, createWebHistory } from 'vue-router'; import { useSessionStore } from '../stores/session'; import { useNavStore } from '../stores/navStore'; import { useTransitionStore } from '../stores/transitionStore'; import { api } from '../api/client'; import { useCachedReads } from '../api/cachedReads'; import { toast } from '../composables/useToast'; // Legacy lazy-loaded every route component (`component: () => import(...)`) so // the initial bundle only carries the entry route. Matched here. export const router = createRouter({ history: createWebHistory(), // Ported from legacy router/index.ts:225-237 — restore saved scroll on // back/forward, otherwise jump to top on every navigation. scrollBehavior(_to, _from, savedPosition) { if (savedPosition) return savedPosition; return { top: 0 }; }, routes: [ // legacy's actual home route is /home (name: 'home'), not '/' — matched here. { path: '/home', name: 'home', component: () => import('../views/HomeView.vue') }, { path: '/product/:id', name: 'singleProduct', component: () => import('../components/product/SingleProduct.vue'), props: true, meta: { layout: 'FullPage' }, }, { path: '/newest', name: 'newestProduct', component: () => import('../views/NewestView.vue'), meta: { layout: 'FullPage' } }, { path: '/cart', name: 'cart', component: () => import('../views/CartView.vue') }, { path: '/login', name: 'login', component: () => import('../views/user/LoginRegisterView.vue'), meta: { layout: 'FullPage' } }, { path: '/auth/iam/callback', name: 'iamCallback', component: () => import('../views/user/IamCallback.vue'), meta: { layout: 'FullPage' } }, { path: '/user', name: 'userPage::hasSubRoute', component: () => import('../views/user/DashboardView.vue') }, { path: '/orders', name: 'ordersList', component: () => import('../views/user/OrdersView.vue'), meta: { requiresAuth: true } }, { path: '/transactions', name: 'transactionsList', component: () => import('../views/user/TransactionsView.vue'), meta: { requiresAuth: true }, }, { path: '/profile', name: 'profileData', component: () => import('../views/user/ProfileView.vue'), meta: { requiresAuth: true } }, { path: '/favorites', name: 'favoritesList', component: () => import('../views/user/FavoritesView.vue'), meta: { requiresAuth: true } }, // Theme + reduced motion. Device preferences, so no requiresAuth. { path: '/settings/appearance', name: 'appearanceSettings', component: () => import('../views/user/AppearanceView.vue') }, // D21 — the sales expert's two screens. Reference paths and names kept // (henza_pwa router/index.ts:171-188). requiresExpert is enforced by the // guard below AND by the server, which scopes both endpoints on the // AdminUser id in the token and answers 403 for anyone else. { path: '/ChildOrder', name: 'ChildOrder', component: () => import('../views/expert/ChildOrdersView.vue'), meta: { title: 'سفارش مشتریان', layout: 'FullPage', requiresAuth: true, requiresExpert: true }, }, { path: '/customerChoice', name: 'customerChoice', component: () => import('../views/expert/CustomerChoiceView.vue'), meta: { title: 'انتخاب مشتری', layout: 'FullPage', requiresAuth: true, requiresExpert: true }, }, // Reference path and name kept (henza_pwa router/index.ts:208-215). The // guard below mirrors the reference's: once the documents are in, the page // redirects home (henza_pwa router/index.ts:266). { path: '/complete_profile', name: 'completeProfile', component: () => import('../views/user/CompleteProfileView.vue'), meta: { title: 'تکمیل پروفایل', layout: 'FullPage', requiresAuth: true, requiresIncompleteProfile: true }, }, // D24 — the account statement. Reference paths and names kept // (henza_pwa router/index.ts:163-165, :191-193). The detail route opens // the same page on its second tab, as the reference did. { path: '/report', name: 'report', component: () => import('../views/report/ReportView.vue'), meta: { title: 'گزارش', layout: 'FullPage', requiresAuth: true }, }, { path: '/report/detail', name: 'reportDetail', component: () => import('../views/report/ReportView.vue'), meta: { title: 'جزئیات حساب', layout: 'FullPage', requiresAuth: true }, }, { path: '/notifications', name: 'notifications', component: () => import('../views/user/NotificationsView.vue') }, { path: '/search', name: 'search', component: () => import('../views/search/SearchView.vue') }, { path: '/collection/:id?', name: 'collection', component: () => import('../views/search/CollectionView.vue') }, // legacy redirects any unmatched path (including '/') to the home route by name. { path: '/', redirect: { name: 'home' } }, { path: '/:pathMatch(.*)*', redirect: { name: 'home' } }, ], }); // Ported from legacy's main router guard: redirects an already-logged-in // user away from /login, and blocks unauthenticated access to routes that // require a session (legacy blocked ordersList/transactionsList/profileData/ // favoritesList/completeProfile the same way). // هر بارگذاری کامل صفحه یک بار بررسی می‌شود. پرچم sessionStorage فقط // همان برگشتِ بی‌صدا از IAM را متوقف می‌کند تا صفحهٔ ورود در حلقه نیفتد. let silentSsoAttempted = false; function skipSilentSso(): boolean { if (sessionStorage.getItem('gb_iam_sso_skip') === '1') { sessionStorage.removeItem('gb_iam_sso_skip'); silentSsoAttempted = true; return true; } return silentSsoAttempted; } router.beforeEach(async (to) => { const session = useSessionStore(); const nav = useNavStore(); if (!session.isLoggedIn && to.name !== 'iamCallback' && !skipSilentSso()) { silentSsoAttempted = true; sessionStorage.removeItem('gb_iam_sso_checked'); try { const started = await api.ssoStart(); if (started.enabled && started.authorize_url) { if (to.fullPath.startsWith('/') && !to.fullPath.startsWith('//')) { sessionStorage.setItem('gb_iam_return', to.fullPath); } window.location.assign(started.authorize_url); return false; } } catch { // سامانه هویت خاموش است یا در دسترس نیست } } if (to.name === 'login' && session.isLoggedIn) { return { name: 'home' }; } // D3 — see the same guard in user-app's router for the full reasoning. // Legacy showed the guest «ابتدا وارد شوید» (henza_pwa/src/router/index.ts:259) // and the target redirected silently. The owner kept the target's `redirect` // so signing in returns the guest to the page they wanted, which legacy did // not do — «عمداً تکرار نشد — D3/الف». if (to.meta.requiresAuth && !session.isLoggedIn) { toast.info('ابتدا وارد شوید'); return { name: 'login', query: { redirect: to.fullPath } }; } // D21 — an ordinary customer typing the URL is sent back to their // dashboard. This is convenience, not security: the server refuses both // expert endpoints for a non-expert token regardless of what the app does. if (to.meta.requiresExpert && !session.isSalesExpert) { return { name: 'userPage::hasSubRoute' }; } // Ported from henza_pwa router/index.ts:266 — once the documents are in, // /complete_profile is not reachable any more and redirects home. The // reference read its cached store; this asks the server (through the shared // short-lived cache), so a profile completed on another device is respected too. A failed lookup lets the // navigation through: the page itself is harmless, and the server is the // one that decides whether the write is allowed. if (to.meta.requiresIncompleteProfile && session.isLoggedIn) { try { const me = await useCachedReads().me(); if (me.verificationStep === 'VERIFIED' || me.verificationStep === 'STEP_TWO_SUBMITTED') { return { name: 'home' }; } } catch { // fall through } } // legacy router/index.ts:268-270 — the product page slides down into view. if (to.name === 'singleProduct') nav.setPgaTransition('slideDown'); else nav.setPgaTransition(undefined); }); // Ported from legacy router/index.ts:273-286. // // setActiveLink moves the bottom-nav GSAP notch + bubble to the current tab, // and this hook is its ONLY caller in the whole app — that part is live. // // The transitionFlag cycling below used to replay AppHeader's "shutter" enter // animation. AppHeader was deleted when every screen moved to the redesigned // components/ui/PageBar.vue, and nothing reads transitionFlag any more, so // that half is currently inert. It is left in place rather than ripped out // because transitionStore is still the shared home for this kind of // page-transition state; flagged here so the next reader doesn't assume it // still drives a visible animation. router.afterEach((to) => { const nav = useNavStore(); const transition = useTransitionStore(); transition.setTransitionFlag(false); transition.setTransitionEnded(false); setTimeout(() => { transition.setTransitionFlag(true); }, 100); // Unconditional on both branches: this hook is the single source of truth for // tab-bar visibility. A screen may hide the bar for its own reasons while it // is open (SearchView does, for its filter sheet), and this is what clears // that override on the way out — the old `if (!nav.showNav)` guard made the // same write, just phrased as if something else might own the flag. const route = nav.navBarRoutes.find((x) => to.name === x.name); if (route) { nav.setActiveLink(route.index); nav.setNavVisibility(true); } else { nav.setNavVisibility(false); } });