Files
SupplierSystem/src/components/Layout.tsx
T
Ubuntu de14fb01f0
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
feat: 供应商系统 2026-11 阶段成果(分公司模板/真还原预览、商品远程搜索、主系统联调、加工幂等修复)
- 分公司类型模板:超管配置隐藏路由/菜单 + 中文文案覆盖,仅对挂类型的分公司生效(后端 service/routes、前端 Provider/守卫/配置页)
- 超管模板 iframe 真还原预览:28 个业务页注册、白名单点选编辑、空/示例数据 fixture、白名单漂移检测工具
- 商品/SKU 下拉远程搜索:服务端关键词搜索 + 前端 useRemoteOptionSearch/SearchableSelect 接入(订单/采购/商品等页)
- 主系统联调:子系统主动解绑主系统授权(幂等重试/本地兜底)、追加修改 price_amend 视图代理与 amend-price 转发
- 修复:仓内加工重复建单幂等(已完成需求单 guard、order 任务一商品一单 guard)
- 修复:出入库记录只取前 100 条 → 服务端分页 + 真实总数
- 其它:库存/订单若干修复、分公司管理响应式布局、i18n 文案、设计文档与回归测试
2026-11-07 20:10:48 +08:00

482 lines
21 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import React, { useState, useEffect, useMemo, useCallback, useRef } from 'react';
import { Outlet, NavLink, useLocation } from 'react-router-dom';
import {
PanelLeftOpen,
ChevronRight,
Menu,
} from 'lucide-react';
import { BrandLogo } from './BrandLogo';
import { useAuth } from '../hooks/useAuth';
import { useOperatingBranch } from '../hooks/useOperatingBranch';
import { useMenuLayout, useVisibleMenuItems } from '../hooks/useMenuLayout';
import { useNavBadgeCounts } from '../hooks/useNavBadgeCounts';
import { withNavBadgeDays } from '../utils/navPendingIntent';
import { NavBadge } from './NavBadge';
import { supabase } from '../supabase/client';
import { NotificationBell } from './NotificationBell';
import { OrderEntryIntakeFab } from './OrderEntryIntakeFab';
import { UserAccountMenu } from './UserAccountMenu';
import { MenuNavIcon } from './MenuNavIcon';
import { ThemeSwitcher } from './ThemeSwitcher';
import { notify } from '../utils/notify';
import type { RuntimeMenuItem } from '../utils/menuLayout';
import { filterRuntimeMenuByAccess } from '../utils/menuAccessFilter';
import { useRoleLabels } from '../hooks/useRoleLabels';
import { isPlatformBranchCode, resolveOperatingBranchCode } from '../utils/platformBranch';
import {
collectMenuLeafPaths,
findActiveMenuChild,
isActiveInMenuGroup,
isMenuChildActive,
isStandaloneMenuActive,
shouldExpandMenuGroup,
} from '../utils/sidebarMenuMatch';
import { useI18n } from '../i18n/I18nProvider';
import { formatHeaderDate, formatHeaderTime } from '../i18n/format';
import { translateRuntimeMenuTree } from '../i18n/translateMenu';
import { HiddenRouteGuard } from './HiddenRouteGuard';
/** 侧栏二级菜单展开高度(含间距),避免固定 500px 截断长列表 */
function getSubmenuMaxHeight(childCount: number, expanded: boolean): string {
if (!expanded || childCount <= 0) return '0px';
const rowHeight = 38;
return `${childCount * rowHeight + 12}px`;
}
const COLLAPSED_GROUPS_STORAGE_KEY = 'sidebar-collapsed-menu-groups';
function readCollapsedMenuGroups(): Set<string> {
if (typeof window === 'undefined') return new Set();
try {
const raw = sessionStorage.getItem(COLLAPSED_GROUPS_STORAGE_KEY);
if (!raw) return new Set();
const parsed = JSON.parse(raw);
return new Set(Array.isArray(parsed) ? parsed.filter((v) => typeof v === 'string') : []);
} catch {
return new Set();
}
}
function writeCollapsedMenuGroups(groups: Set<string>) {
if (typeof window === 'undefined') return;
sessionStorage.setItem(COLLAPSED_GROUPS_STORAGE_KEY, JSON.stringify([...groups]));
}
export const Layout: React.FC = () => {
const { profile, hasPermission, hasRole } = useAuth();
const { t, locale } = useI18n();
// 角色标签统一口径(含自建角色),与账号菜单/操作日志/角色权限页一致
const { roleLabel: resolveRoleLabel } = useRoleLabels();
const { operatingBranchCode, setOperatingBranch } = useOperatingBranch();
const { loading: menuLoading } = useMenuLayout();
/** 渲染期投影(hidden 不烤进缓存):侧栏只消费投影结果(设计 §9.3) */
const menuItems = useVisibleMenuItems();
const [sidebarOpen, setSidebarOpen] = useState(true);
/** 小屏抽屉式侧栏开关(lg 以下生效) */
const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
const [expandedMenus, setExpandedMenus] = useState<string[]>([]);
/** 用户手动折叠的菜单组(点击分组标题收起),跨路由保持 */
const [userCollapsedGroups, setUserCollapsedGroups] = useState<Set<string>>(
() => readCollapsedMenuGroups()
);
const [branchOptions, setBranchOptions] = useState<Array<{ branch_code: string; branch_name: string }>>([]);
const [currentTime, setCurrentTime] = useState(() => new Date());
const location = useLocation();
const isSuperAdmin = hasRole('super_admin');
const outletKey = isSuperAdmin
? (operatingBranchCode || profile?.branch_code || 'no-branch')
: (profile?.branch_code || 'default');
const { counts: navBadgeCounts, days: navBadgeDays } = useNavBadgeCounts('days', outletKey, location.pathname);
useEffect(() => {
const timer = window.setInterval(() => setCurrentTime(new Date()), 30_000);
return () => window.clearInterval(timer);
}, []);
const persistCollapsedGroups = useCallback((groups: Set<string>) => {
writeCollapsedMenuGroups(groups);
}, []);
const markGroupCollapsed = useCallback((path: string) => {
setUserCollapsedGroups((prev) => {
if (prev.has(path)) return prev;
const next = new Set(prev).add(path);
persistCollapsedGroups(next);
return next;
});
}, [persistCollapsedGroups]);
const markGroupExpanded = useCallback((path: string) => {
setUserCollapsedGroups((prev) => {
if (!prev.has(path)) return prev;
const next = new Set(prev);
next.delete(path);
persistCollapsedGroups(next);
return next;
});
}, [persistCollapsedGroups]);
const toggleMenu = (path: string, currentlyOpen: boolean) => {
if (currentlyOpen) {
setExpandedMenus((prev) => prev.filter((p) => p !== path));
markGroupCollapsed(path);
return;
}
setExpandedMenus((prev) => (prev.includes(path) ? prev : [...prev, path]));
markGroupExpanded(path);
};
const isMenuExpanded = (path: string) => expandedMenus.includes(path);
const filterMenuItems = useCallback(
(items: RuntimeMenuItem[]) => filterRuntimeMenuByAccess(items, hasPermission, hasRole),
[hasPermission, hasRole]
);
const visibleMenuItems = useMemo(
() => translateRuntimeMenuTree(filterMenuItems(menuItems), t, locale),
[menuItems, filterMenuItems, t, locale]
);
const allMenuLeafPaths = useMemo(
() => collectMenuLeafPaths(visibleMenuItems),
[visibleMenuItems]
);
useEffect(() => {
setMobileSidebarOpen(false);
}, [location.pathname]);
const prevPathnameRef = useRef(location.pathname);
const isInitialNavEffectRef = useRef(true);
useEffect(() => {
if (menuLoading) return;
const shouldResetCollapsed =
isInitialNavEffectRef.current || prevPathnameRef.current !== location.pathname;
isInitialNavEffectRef.current = false;
prevPathnameRef.current = location.pathname;
if (!shouldResetCollapsed) return;
const activeGroupPaths = visibleMenuItems
.filter(
(item) =>
Boolean(item.children?.length) &&
findActiveMenuChild(location.pathname, item.children!, allMenuLeafPaths)
)
.map((item) => item.path);
setUserCollapsedGroups((prev) => {
let next: Set<string> | null = null;
for (const path of activeGroupPaths) {
if (!prev.has(path)) continue;
next = next ?? new Set(prev);
next.delete(path);
}
if (!next) return prev;
persistCollapsedGroups(next);
return next;
});
setExpandedMenus(activeGroupPaths);
}, [location.pathname, menuLoading, visibleMenuItems, allMenuLeafPaths, persistCollapsedGroups]);
useEffect(() => {
if (!profile?.must_change_password || !profile.id) return;
const key = `password-change-tip:${profile.id}`;
if (sessionStorage.getItem(key)) return;
sessionStorage.setItem(key, '1');
notify.warning('当前账号仍在使用初始密码或重置密码,建议尽快在右上角账号菜单中修改密码。');
}, [profile?.id, profile?.must_change_password]);
useEffect(() => {
if (!isSuperAdmin) return;
let active = true;
void (async () => {
const { data, error } = await supabase
.from('branches')
.select('branch_code, branch_name')
.eq('status', 1)
.order('branch_code');
if (!active || error) return;
const rows = data || [];
setBranchOptions(rows);
// 仅首次加载时自动选择业务分公司,后续尊重用户手动选择(含基础平台)
if (!operatingBranchCode) {
const resolved = resolveOperatingBranchCode(operatingBranchCode, rows);
if (resolved) {
setOperatingBranch(resolved);
}
}
})();
return () => {
active = false;
};
}, [isSuperAdmin, operatingBranchCode, setOperatingBranch]);
const operatingBranchName =
branchOptions.find((b) => b.branch_code === operatingBranchCode)?.branch_name || operatingBranchCode;
const primaryRole = profile?.roles?.[0];
const roleLabel = primaryRole ? resolveRoleLabel(primaryRole) : t('layout.unknownRole');
return (
<div className="app-shell app-foreground min-h-screen flex">
{/* Mobile drawer backdrop */}
{mobileSidebarOpen && (
<div
className="fixed inset-0 bg-black/40 z-40 lg:hidden"
onClick={() => setMobileSidebarOpen(false)}
aria-hidden="true"
/>
)}
{/* Sidebar */}
<aside
className={`app-sidebar fixed left-0 top-0 h-full backdrop-blur-xl border-r transition-all duration-300 z-50 flex flex-col ${
sidebarOpen || mobileSidebarOpen ? 'w-[260px]' : 'sidebar-collapsed-new'
} ${mobileSidebarOpen ? 'max-lg:translate-x-0' : 'max-lg:-translate-x-full'}`}
style={{ background: 'var(--app-sidebar-bg)' }}
>
{/* Logo Area */}
<div className="h-16 flex items-center gap-3 px-5 border-b shrink-0" style={{ borderColor: 'var(--app-sidebar-border)' }}>
<div className="w-[38px] h-[38px] flex items-center justify-center shrink-0">
<BrandLogo />
</div>
<div className="sidebar-hide-collapsed overflow-hidden whitespace-nowrap transition-all duration-250">
<span className="app-foreground block text-[15px] font-semibold leading-tight tracking-tight">
{t('login.brandTitle')}
</span>
<span className="app-foreground-muted -mt-0.5 block text-[11px] tracking-wide">{t('login.brandSubtitle')}</span>
</div>
</div>
{/* Navigation */}
<nav className="flex-1 overflow-y-auto overflow-x-hidden py-3 px-2.5 scrollbar-thin" style={{ scrollbarWidth: 'thin', scrollbarColor: 'rgba(148,163,184,0.3) transparent' }}>
{menuLoading ? (
<div className="px-1 py-1 space-y-2" aria-busy="true" aria-label={t('common.loading')}>
{Array.from({ length: 6 }).map((_, index) => (
<div
key={index}
className="app-table-head h-9 animate-pulse rounded-lg"
/>
))}
</div>
) : (
visibleMenuItems.map((item) => {
const hasChildren = item.children && item.children.length > 0;
const activeChild = hasChildren
? findActiveMenuChild(location.pathname, item.children!, allMenuLeafPaths)
: undefined;
const userCollapsed = userCollapsedGroups.has(item.path);
const submenuOpen = shouldExpandMenuGroup({
hasActiveChild: Boolean(activeChild),
userCollapsed,
userExpanded: isMenuExpanded(item.path),
});
const visibleChildren = submenuOpen ? item.children : [];
const isActive = hasChildren
? isActiveInMenuGroup(location.pathname, item.children!, allMenuLeafPaths)
: isStandaloneMenuActive(location.pathname, item.path);
const groupBadgeCount = (item.children || []).reduce(
(sum, child) => sum + (Number(navBadgeCounts[child.menuKey || '']) || 0),
0
);
return (
<div key={`${item.path}:${item.label}`} className="nav-group-container">
{hasChildren ? (
<>
<button
type="button"
onClick={() => toggleMenu(item.path, submenuOpen)}
aria-expanded={submenuOpen}
aria-controls={`submenu-${item.path.replace(/[^a-zA-Z0-9_-]/g, '-')}`}
title={item.label}
className={`nav-group-label w-full flex items-center gap-2 rounded-lg cursor-pointer ${
isActive ? 'app-foreground' : ''
}`}
>
<MenuNavIcon icon={item.icon} iconSvg={item.iconSvg} className="nav-group-icon" />
<span className="flex-1 text-left truncate">{item.label}</span>
<NavBadge count={!submenuOpen ? groupBadgeCount : 0} />
<ChevronRight
className="group-chevron-icon shrink-0"
style={{
transform: submenuOpen ? 'rotate(90deg)' : 'rotate(0deg)',
transition: 'transform 0.25s cubic-bezier(0.4, 0, 0.2, 1)',
}}
/>
</button>
<div
id={`submenu-${item.path.replace(/[^a-zA-Z0-9_-]/g, '-')}`}
className={`nav-items-list ${!submenuOpen ? 'collapsed-parent' : ''}`}
style={{
maxHeight: getSubmenuMaxHeight(visibleChildren?.length ?? 0, submenuOpen),
opacity: submenuOpen ? 1 : 0,
paddingTop: submenuOpen ? undefined : '0',
paddingBottom: submenuOpen ? undefined : '0',
pointerEvents: submenuOpen ? 'auto' : 'none',
}}
>
{visibleChildren?.map((child) => (
<NavLink
key={child.path}
to={withNavBadgeDays(child.path, child.menuKey ? navBadgeCounts[child.menuKey] : 0, navBadgeDays)}
end
className={() =>
`subnav-item ${
isMenuChildActive(
location.pathname,
child.path,
item.children!,
allMenuLeafPaths
)
? 'active'
: ''
}`
}
>
<span>{child.label}</span>
<NavBadge count={child.menuKey ? navBadgeCounts[child.menuKey] : 0} />
</NavLink>
))}
</div>
</>
) : (
<NavLink
to={withNavBadgeDays(
item.path,
item.menuKey ? navBadgeCounts[item.menuKey] : 0,
navBadgeDays
)}
end
className={({ isActive: navActive }) =>
`nav-item ${navActive ? 'active' : ''}`
}
>
{(item.icon || item.iconSvg) && (
<MenuNavIcon icon={item.icon} iconSvg={item.iconSvg} className="nav-icon" />
)}
<span className="nav-item-text sidebar-hide-collapsed">{item.label}</span>
<NavBadge count={item.menuKey ? navBadgeCounts[item.menuKey] : 0} />
</NavLink>
)}
</div>
);
})
)}
</nav>
{/* Sidebar Footer - Collapse Button */}
<div className="sidebar-footer">
<button
type="button"
onClick={() => setSidebarOpen(!sidebarOpen)}
className="sidebar-collapse-btn"
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ transition: 'transform 0.3s ease', transform: sidebarOpen ? 'rotate(0deg)' : 'rotate(180deg)' }}>
<polyline points="11 17 6 12 11 7"/><polyline points="18 17 13 12 18 7"/>
</svg>
<span className="sidebar-hide-collapsed">{sidebarOpen ? '收起侧栏' : ''}</span>
</button>
</div>
</aside>
{/* Main Content:min-w-0 避免宽表把 flex 主栏撑出整页横滚 */}
<div className={`flex-1 min-w-0 transition-all duration-300 ml-0 ${sidebarOpen ? 'lg:ml-[260px]' : 'lg:ml-[72px]'}`}>
{/* Header */}
<header className="app-header h-14 backdrop-blur-xl border-b flex items-center justify-between px-4 sm:px-7 sticky top-0 z-40" style={{ background: 'var(--app-header-bg)', borderColor: 'var(--app-header-border)' }}>
<div className="flex items-center gap-4">
<button
type="button"
onClick={() => setMobileSidebarOpen(true)}
title="打开导航"
aria-label="打开导航"
className="app-nav-idle lg:hidden p-2 rounded-xl transition-colors duration-150"
>
<Menu className="app-foreground-muted w-4 h-4" />
</button>
{!sidebarOpen && (
<button
type="button"
onClick={() => setSidebarOpen(true)}
title="展开导航"
aria-label="展开导航"
className="app-nav-idle hidden lg:block p-2 rounded-xl transition-colors duration-150"
>
<PanelLeftOpen className="app-foreground-muted w-4 h-4" />
</button>
)}
<div className="flex items-center gap-2">
<span className="app-foreground-muted text-xs">当前角色</span>
<span className="command-role-chip px-2.5 py-1 text-xs font-medium rounded-md border">
{roleLabel}
</span>
{profile?.branch_name && !isSuperAdmin && (
<span className="command-role-chip px-2.5 py-1 text-xs font-medium rounded-md border">
{profile.branch_name}
</span>
)}
{isSuperAdmin && (
<label className="app-foreground-muted flex items-center gap-2 text-xs">
<span>{t('layout.operatingBranch')}</span>
<select
value={operatingBranchCode || ''}
onChange={(e) => setOperatingBranch(e.target.value || null)}
className="app-status-warning app-focus-ring rounded-full border px-2.5 py-1 text-xs font-medium outline-none focus:ring-2"
aria-label={t('layout.pickBranch')}
>
{!operatingBranchCode && <option value="">{t('layout.pleaseSelect')}</option>}
{branchOptions.map((branch) => (
<option key={branch.branch_code} value={branch.branch_code}>
{branch.branch_name}
{isPlatformBranchCode(branch.branch_code) ? t('layout.platformConfig') : ''}
</option>
))}
</select>
</label>
)}
{isSuperAdmin && operatingBranchCode && !branchOptions.length && (
<span className="app-status-warning rounded-full border px-2.5 py-1 text-xs font-medium">
{operatingBranchName}
</span>
)}
</div>
</div>
<div className="flex items-center gap-3">
<div className="hidden xl:flex flex-col items-end border-r pr-3" style={{ borderColor: 'var(--app-header-border)' }}>
<span className="font-mono text-sm font-semibold tracking-[0.12em] command-accent">
{formatHeaderTime(currentTime, locale)}
</span>
<span className="app-foreground-muted text-[10px]">
{formatHeaderDate(currentTime, locale)}
</span>
</div>
<ThemeSwitcher />
<NotificationBell />
<UserAccountMenu />
</div>
</header>
{/* Page Content */}
<main className="p-4 sm:p-7 min-h-[calc(100vh-56px)] min-w-0 overflow-x-hidden">
{isSuperAdmin && !operatingBranchCode ? (
<div className="app-foreground-muted flex min-h-[40vh] items-center justify-center text-sm">
{t('layout.initBranch')}
</div>
) : (
<HiddenRouteGuard>
<Outlet key={outletKey} />
</HiddenRouteGuard>
)}
</main>
</div>
<OrderEntryIntakeFab />
</div>
);
};