Files
tehran_taj/apps/user-app-v2/src/router/index.ts
T
s.esmaeiliandClaude Opus 5 89e2d7937e feat(apps): tell a guest why they were bounced to the login page (D3)
A guest tapping a personal page — orders, transactions, profile,
favourites, complete-profile — was redirected in silence, so they landed
on the login box with nothing explaining what happened. Legacy showed
«ابتدا وارد شوید» (henza_pwa/src/router/index.ts:259).

The message is now shown in both apps. The destination deliberately
stays the target's /login?redirect=…, which legacy did not have: legacy
sent the guest to home and lost where they were going, while here
signing in returns them to the page they asked for. The owner chose that
trade-off, so it is logged as «عمداً تکرار نشد — D3/الف» rather than
quietly left as a divergence. The guard also keys off meta.requiresAuth
instead of legacy's hand-kept list of five route names, so the two
sales-expert pages are covered too.

Legacy's isLoaded router guard is NOT ported, and the reasoning is
written into both apps' configStore beside the line that says so: it
guarded legacy's one big bootstrap request, which this target does not
have, so it would guard nothing and only add a bounce — a shared product
link would open home instead of the product. That is porting the
breakage, not the behaviour (D4).

Route analytics is deferred at the owner's request; its design is parked
in docs/PHASE2-D3-PLAN.md so it need not be re-derived, along with the
two reference defects not to copy (log/create was unauthenticated and
accepted any title; log/update was a GET that wrote) and the open
retention and IP questions.

Seven of D3's ten items turned out to be built already — all five
screens in both apps, the sts_verify_step_two guard, v2's cart ceiling —
verified in the code rather than from the checkmarks.

Neither app has a test runner: verified with vue-tsc -b on both (clean)
plus confirming the toast can actually appear, not merely compile —
toast.info exists and <ToastHost /> is mounted in each App.vue.

اپ: وقتی بدون ورود صفحه شخصی را باز کنید، پیام «ابتدا وارد شوید» نشان داده می‌شود.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-12 10:40:22 +03:30

209 lines
9.8 KiB
TypeScript

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);
}
});