Initial import of weiyuan frontend

This commit is contained in:
qiubaishen
2026-10-15 16:33:46 +08:00
commit d8f3aee261
774 changed files with 374914 additions and 0 deletions
+776
View File
@@ -0,0 +1,776 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useContext, useEffect, useRef, useState } from 'react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import {
Button,
Form,
Input,
AutoComplete,
Toast,
Banner,
Avatar,
Spin,
Checkbox,
Modal,
} from '@douyinfe/semi-ui';
import { API } from '../../helpers/api';
import { showError, getLogo, getSystemName } from '../../helpers';
import {
setUserData,
savePostLoginRedirect,
consumePostLoginRedirect,
} from '../../helpers/data';
import { updateAPI } from '../../helpers/api';
import { finishLogin } from '../../helpers/loginFlow';
import { UserContext } from '../../context/User';
import { StatusContext } from '../../context/Status';
import GlassCard from '../../components/auth/GlassCard';
import AuthCardHeader from '../../components/auth/AuthCardHeader';
import AuthLoginTabs from '../../components/auth/AuthLoginTabs';
import AuthBackground from '../../components/common/AuthBackground';
const LAST_ORG_KEY = 'org_login_last';
// 企业登录页(PR6b):先输企业标识 -> 展示企业品牌与登录方式 -> 密码登录 -> 首登改密。
const OrgLogin = () => {
const { t } = useTranslation();
const navigate = useNavigate();
const { slug } = useParams();
// ?org=<code> 预填企业(企业注册成功后「立即登录」等入口带入),与 slug 一样自动直达 Step2;
// ?login=<登录名> 一并预填 Step2 登录名,用户只需输入密码
const [searchParams, setSearchParams] = useSearchParams();
const orgParam = (searchParams.get('org') || '').trim();
const loginParam = (searchParams.get('login') || '').trim();
const [, userDispatch] = useContext(UserContext);
const [statusState] = useContext(StatusContext);
const statusLoaded = statusState?.status !== undefined;
const selfUseModeEnabled = !!statusState?.status?.self_use_mode_enabled;
const selfRegisterEnabled = !!statusState?.status?.org_self_register;
const directLoginEnabled = !!statusState?.status?.org_direct_login;
// 免企业标识直登(方案 §12):'direct'=账号直登(默认),'identifier'=企业标识登录(原流程/回退)
const [loginMode, setLoginMode] = useState('direct');
const [directForm, setDirectForm] = useState({ login_name: '', password: '' });
const [multiMatch, setMultiMatch] = useState(null); // { orgs:[{index,org_id,name,logo}], ticket, password }
// 带入 Step2 初值的登录名,避免重复输入:来自 ?login= 预填(注册成功直达)或直登回退时已输的登录名
const [pendingLoginName, setPendingLoginName] = useState(loginParam);
// 实际生效模式:系统未开直登则始终走企业标识
const effectiveMode = directLoginEnabled ? loginMode : 'identifier';
const logo = getLogo();
const systemName = getSystemName();
// 上次登录企业 {identifier, name, login_name, remember_login_name}:本机记忆,仅读一次。
// 始终读取:企业自动直达由 slug 优先(见下方 effect),但登录名回填对 slug 短链流程同样生效。
const [savedOrg] = useState(() => {
try {
return JSON.parse(localStorage.getItem(LAST_ORG_KEY) || 'null');
} catch {
return null; // 忽略损坏的本地存储
}
});
const [step, setStep] = useState(1); // 1=企业标识 2=登录 3=首登改密
const [identifier, setIdentifier] = useState(
slug || orgParam ? '' : savedOrg?.identifier || '',
);
const [orgInfo, setOrgInfo] = useState(null);
const [loading, setLoading] = useState(false);
// slug(品牌短链 /org/:slug/login)、?org= 预填或本机记忆的企业存在时,自动查企业并直达 Step2,期间展示加载态
const [bootstrapping, setBootstrapping] = useState(
Boolean(slug || orgParam || savedOrg?.identifier),
);
const [creds, setCreds] = useState({ login_name: '', password: '' });
const [loginUser, setLoginUser] = useState(null);
// 记住登录名(可选):沿用上次显式选择;无记录(含本功能上线前的老记忆)默认开启。共享设备可手动取消。
const [rememberLoginName, setRememberLoginName] = useState(
() => savedOrg?.remember_login_name ?? true,
);
const [capsOn, setCapsOn] = useState(false); // 密码框大写锁定提示
const autoLookedUpSlug = useRef(null); // 记录已自动直达过的 slug,避免重复请求
const autoLookedUpParam = useRef(false); // ?org= 预填仅自动直达一次
const autoLookedUpSaved = useRef(false); // 记忆企业仅自动直达一次
// 企业名称联想(仅对开启「允许被搜索」的企业生效)
const [suggestOptions, setSuggestOptions] = useState([]);
const suggestTimer = useRef(null); // 防抖计时器
const suggestSeq = useRef(0); // 请求序号,防止慢响应覆盖新输入(竞态)
// 高亮命中片段:把 name 中匹配 keyword 的子串用品牌色包裹(大小写不敏感)。
const highlightMatch = (name, keyword) => {
const kw = (keyword || '').trim();
if (!kw) return name;
const idx = name.toLowerCase().indexOf(kw.toLowerCase());
if (idx < 0) return name;
return (
<>
{name.slice(0, idx)}
<span className='text-brand font-medium'>
{name.slice(idx, idx + kw.length)}
</span>
{name.slice(idx + kw.length)}
</>
);
};
// 名称联想搜索:250ms 防抖 + 竞态防护;<2 字符不请求。
const handleSuggestSearch = (value) => {
const kw = (value || '').trim();
if (suggestTimer.current) clearTimeout(suggestTimer.current);
if (kw.length < 2) {
setSuggestOptions([]);
return;
}
suggestTimer.current = setTimeout(async () => {
const seq = ++suggestSeq.current;
try {
const res = await API.get(
`/api/org/login/suggest?q=${encodeURIComponent(kw)}`,
);
if (seq !== suggestSeq.current) return; // 已有更新的请求,丢弃本次结果
const items = res.data?.data?.items || [];
setSuggestOptions(
items.map((it) => ({
value: it.code, // 选中后用 code 精确直达
label: it.name,
name: it.name,
logo: it.logo,
})),
);
} catch {
if (seq === suggestSeq.current) setSuggestOptions([]);
}
}, 250);
};
// 仅当当前企业即上次记住的企业时,才回填登录名(切换企业后不串号)。
const rememberedLoginName =
savedOrg && identifier.trim() === savedOrg.identifier
? savedOrg.login_name || ''
: '';
// Step2 登录名初值(记忆 > ?login=/直登回退带入);有初值时焦点直接给密码框
const prefilledLoginName = rememberedLoginName || pendingLoginName;
// 大写锁定检测:密码框 keydown/keyup 时更新提示。
const handleCapsLock = (e) => {
if (typeof e.getModifierState === 'function') {
setCapsOn(e.getModifierState('CapsLock'));
}
};
// 查企业。idArg 仅在自动直达时传入字符串;来自 onClick/onEnterPress 的事件对象一律忽略,改读输入框。
const lookupOrg = async (idArg) => {
const id = (typeof idArg === 'string' ? idArg : identifier).trim();
if (!id) {
Toast.warning(t('请输入企业标识'));
return;
}
if (loading) return; // 防抖:避免回车连按重复请求
setLoading(true);
try {
const res = await API.get(
`/api/org/login/options?org=${encodeURIComponent(id)}`,
);
if (res.data.success && res.data.data?.available) {
const info = res.data.data;
if (!(info.login_methods || []).includes('password')) {
Toast.warning(t('该企业未开启密码登录'));
return;
}
setOrgInfo(info);
setStep(2);
} else {
showError(t('企业不存在或不可登录,请联系企业管理员'));
}
} catch (err) {
if (!err?.isAxiosError) {
showError(err.message);
}
} finally {
setLoading(false);
}
};
// 与 /login 对齐的入口参数处理:?redirect= 写回本地存储(新标签页打开也能回跳),
// ?expired=true 提示会话过期后从 URL 清除(避免刷新重复提示)。
useEffect(() => {
const redirect = searchParams.get('redirect');
if (redirect) {
savePostLoginRedirect(redirect);
}
if (searchParams.get('expired')) {
showError(t('未登录或登录已过期,请重新登录'));
const nextParams = new URLSearchParams(searchParams);
nextParams.delete('expired');
setSearchParams(nextParams, { replace: true });
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
if (!slug || autoLookedUpSlug.current === slug) return;
autoLookedUpSlug.current = slug; // 防 StrictMode 双触发 / slug 变更时才重查
setLoginMode('identifier'); // 品牌短链指向特定企业,走企业标识模式更自然
setIdentifier(slug);
// 自动直达:成功进 step2,失败回落 step1(输入框已预填,可直接重试)
lookupOrg(slug).finally(() => setBootstrapping(false));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [slug]);
// ?org= 预填(企业注册成功「立即登录」等入口带入企业代码):与 slug 同样自动直达 Step2,
// 失败回落 Step1(输入框已预填,可直接重试)。
useEffect(() => {
if (slug || !orgParam || autoLookedUpParam.current) return;
autoLookedUpParam.current = true;
setLoginMode('identifier'); // 预填指向特定企业,走企业标识模式
setIdentifier(orgParam);
lookupOrg(orgParam).finally(() => setBootstrapping(false));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// 无 slug / ?org= 但本机记忆了上次企业:自动查企业并直达 Step2,老用户只需输登录名+密码。
// 安全模型与品牌短链一致(企业上下文来自本机记忆,非跨企业探测);失败回落 Step1(输入框已预填,可改填或切换企业)。
useEffect(() => {
if (slug || orgParam || autoLookedUpSaved.current || !savedOrg?.identifier)
return;
autoLookedUpSaved.current = true;
lookupOrg(savedOrg.identifier).finally(() => setBootstrapping(false));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// 登录成功后的统一收尾(企业标识登录 / 直登 / 直登选择 共用):写本机态、首登改密或进入工作台。
const applyLoginSuccess = async (data, loginName, password) => {
localStorage.setItem('current_org_id', String(data.current_org_id));
setCreds({ login_name: loginName, password });
setLoginUser(data.user);
if (data.must_change_password) {
setUserData(data.user);
updateAPI();
setCapsOn(false);
setStep(3);
Toast.info(t('首次登录,请修改初始密码'));
} else {
await finishLogin({
data: data.user,
userDispatch,
navigate,
t,
// 消费被保护页跳来时保存的回跳地址(尊重深链意图,同时避免残留值
// 影响之后的个人登录);无保存值则进企业工作台
redirectOverride: consumePostLoginRedirect('/org/workbench'),
});
}
};
// 免企业标识直登:输登录名+密码 → 唯一命中直达 / 多命中选择 / 高碰撞名回退到企业标识。
const doDirectLogin = async () => {
const login_name = directForm.login_name.trim();
const password = directForm.password;
if (!login_name || !password) {
Toast.warning(t('请输入登录名和密码'));
return;
}
if (loading) return;
setLoading(true);
try {
const res = await API.post('/api/org/login/direct', { login_name, password });
if (res.data.success) {
const data = res.data.data;
if (data.need_org_hint) {
setPendingLoginName(login_name); // 带入 Step2,免重复输入
setLoginMode('identifier');
Toast.info(t('该账号需补充企业名称或代码后登录'));
return;
}
if (data.multi) {
setMultiMatch({ orgs: data.orgs || [], ticket: data.ticket, password });
return;
}
await applyLoginSuccess(data, login_name, password);
} else {
showError(res.data.message);
}
} catch (err) {
if (!err?.isAxiosError) showError(err.message);
} finally {
setLoading(false);
}
};
// 多命中时选择企业完成登录。
const doDirectSelect = async (index) => {
if (!multiMatch || loading) return;
setLoading(true);
try {
const res = await API.post('/api/org/login/direct/select', {
ticket: multiMatch.ticket,
index,
});
if (res.data.success) {
const ln = directForm.login_name.trim();
const pwd = multiMatch.password;
setMultiMatch(null);
await applyLoginSuccess(res.data.data, ln, pwd);
} else {
showError(res.data.message);
}
} catch (err) {
if (!err?.isAxiosError) showError(err.message);
} finally {
setLoading(false);
}
};
const doLogin = async (values) => {
setLoading(true);
try {
const res = await API.post('/api/org/login', {
org_identifier: identifier.trim(),
login_name: values.login_name,
password: values.password,
});
if (res.data.success) {
const data = res.data.data;
// 记住本次企业用于自动直达;勾选「记住登录名」时一并存登录名(均不含密码)。
try {
localStorage.setItem(
LAST_ORG_KEY,
JSON.stringify({
identifier: identifier.trim(),
name: orgInfo?.org_name || identifier.trim(),
remember_login_name: rememberLoginName,
login_name: rememberLoginName ? values.login_name : undefined,
}),
);
} catch {
// 忽略写入失败
}
await applyLoginSuccess(data, values.login_name, values.password);
} else {
showError(res.data.message);
}
} catch (err) {
if (!err?.isAxiosError) {
showError(err.message);
}
} finally {
setLoading(false);
}
};
const doChangePassword = async (values) => {
if (values.new_password !== values.confirm_password) {
Toast.warning(t('两次输入的新密码不一致'));
return;
}
// 与后端一致的长度校验(8-20 位),避免无谓往返
if (values.new_password.length < 8 || values.new_password.length > 20) {
Toast.warning(t('新密码长度需为 8-20 位'));
return;
}
setLoading(true);
try {
const res = await API.post('/api/org/account/change-initial-password', {
old_password: creds.password,
new_password: values.new_password,
});
if (res.data.success) {
Toast.success(t('密码已修改'));
await finishLogin({
data: loginUser,
userDispatch,
navigate,
t,
successMessage: '',
// 首登改密路径同样消费保存的回跳地址,默认进企业工作台
redirectOverride: consumePostLoginRedirect('/org/workbench'),
});
} else {
showError(res.data.message);
}
} catch (err) {
if (!err?.isAxiosError) {
showError(err.message);
}
} finally {
setLoading(false);
}
};
return (
<div
className='relative overflow-hidden flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8'
// 抵扣 PageLayout 跑马灯占位高度,保证占位+容器恰为一屏,避免幽灵滚动
style={{ minHeight: 'calc(100vh - var(--content-top-offset, 0px))' }}
>
<AuthBackground />
<style>{`
@keyframes orgStepEnter {
from { opacity: 0; transform: translateY(6px); }
to { opacity: 1; transform: translateY(0); }
}
.org-step-enter { animation: orgStepEnter 0.35s ease-out; }
@media (prefers-reduced-motion: reduce) { .org-step-enter { animation: none; } }
`}</style>
<div className='w-full max-w-md z-10 flex flex-col items-center'>
{/* 与其余认证页一致:状态加载完成且非自用模式才展示「个人/企业」切换 */}
{statusLoaded && !selfUseModeEnabled && (
<div className='w-full max-w-sm mb-4'>
<AuthLoginTabs active='enterprise' />
</div>
)}
<GlassCard>
<AuthCardHeader
wrapperClassName='mb-6'
logo={logo}
logoNode={
orgInfo?.logo ? (
<Avatar
src={orgInfo.logo}
shape='square'
className='h-10 w-10 rounded-lg'
/>
) : undefined
}
title={
step === 1
? t('企业登录')
: orgInfo?.org_name || systemName || t('企业登录')
}
subtitle={
step === 1 ? t('使用企业托管账号登录') : t('企业托管账号登录')
}
/>
{bootstrapping ? (
<div
className='flex flex-col items-center justify-center gap-3 py-8'
role='status'
aria-live='polite'
>
<Spin size='large' />
<span className='text-gray-500 dark:text-gray-400 text-xs'>
{t('正在加载企业信息…')}
</span>
</div>
) : (
<div key={step} className='org-step-enter auth-glass-form'>
{step === 1 && (
<div className='flex flex-col gap-4'>
{effectiveMode === 'direct' ? (
<>
{/* 账号直登:输登录名 + 密码,系统自动定位企业(方案 §12) */}
<Input
value={directForm.login_name}
onChange={(v) =>
setDirectForm({ ...directForm, login_name: v })
}
placeholder={t('登录名')}
size='large'
autoFocus
/>
<Input
value={directForm.password}
onChange={(v) =>
setDirectForm({ ...directForm, password: v })
}
mode='password'
placeholder={t('密码')}
size='large'
onKeyDown={handleCapsLock}
onKeyUp={handleCapsLock}
onEnterPress={doDirectLogin}
/>
{capsOn && (
<div className='text-xs text-amber-500 -mt-1'>
{t('大写锁定已开启')}
</div>
)}
<Button
theme='solid'
size='large'
block
loading={loading}
disabled={
!directForm.login_name.trim() || !directForm.password
}
onClick={doDirectLogin}
>
{t('登录')}
</Button>
<Button
theme='borderless'
size='large'
block
className='!text-gray-500'
onClick={() => setLoginMode('identifier')}
>
{t('用企业名称/代码登录')}
</Button>
</>
) : (
<>
<AutoComplete
value={identifier}
data={suggestOptions}
onChange={(v) =>
setIdentifier(typeof v === 'string' ? v : '')
}
onSearch={handleSuggestSearch}
onSelect={(code) => {
setIdentifier(code);
lookupOrg(code); // 选中候选:用 code 精确直达 Step2
}}
onEnterPress={lookupOrg} // 未选候选时按当前输入精确解析
placeholder={t('输入企业名称、企业代码或登录短链')}
emptyContent={null}
renderItem={(item) => (
<div className='flex items-center gap-2 py-0.5'>
{item.logo ? (
<Avatar
src={item.logo}
shape='square'
className='h-6 w-6 rounded'
/>
) : (
<div className='h-6 w-6 rounded bg-gray-100 dark:bg-white/10' />
)}
<span className='truncate'>
{highlightMatch(item.name, identifier)}
</span>
</div>
)}
style={{ width: '100%' }}
size='large'
autoFocus
/>
<Button
theme='solid'
size='large'
block
loading={loading}
disabled={!identifier.trim()}
onClick={lookupOrg}
>
{t('下一步')}
</Button>
{directLoginEnabled && (
<Button
theme='borderless'
size='large'
block
className='!text-gray-500'
onClick={() => setLoginMode('direct')}
>
{t('用账号直接登录')}
</Button>
)}
</>
)}
{selfRegisterEnabled && (
<>
<div className='mt-1 flex items-center gap-3 text-xs text-gray-400'>
<span className='h-px flex-1 bg-gray-200 dark:bg-white/10' />
<span>{t('还没有企业?')}</span>
<span className='h-px flex-1 bg-gray-200 dark:bg-white/10' />
</div>
<Button
theme='borderless'
size='large'
block
className='!text-brand'
onClick={() => navigate('/org/register')}
>
{t('注册企业')}
</Button>
</>
)}
</div>
)}
{step === 2 && (
<Form
onSubmit={doLogin}
initValues={{ login_name: prefilledLoginName }}
>
<Form.Input
field='login_name'
label={t('企业内登录名')}
size='large'
autoFocus={!prefilledLoginName}
autoComplete='username'
rules={[{ required: true, message: t('请输入登录名') }]}
/>
<Form.Input
field='password'
label={t('密码')}
mode='password'
size='large'
autoFocus={Boolean(prefilledLoginName)}
autoComplete='current-password'
onKeyDown={handleCapsLock}
onKeyUp={handleCapsLock}
rules={[{ required: true, message: t('请输入密码') }]}
/>
{capsOn && (
<div className='text-xs text-amber-500 -mt-1 mb-1'>
{t('大写锁定已开启')}
</div>
)}
<div className='flex items-center justify-between'>
<Checkbox
checked={rememberLoginName}
onChange={(e) => setRememberLoginName(e.target.checked)}
>
<span className='text-xs text-gray-500 dark:text-gray-400'>
{t('记住登录名')}
</span>
</Checkbox>
<span className='text-xs text-gray-400 dark:text-gray-500'>
{t('忘记密码?请联系企业管理员重置')}
</span>
</div>
<Button
theme='solid'
size='large'
block
htmlType='submit'
loading={loading}
style={{ marginTop: 16 }}
>
{t('登录')}
</Button>
<Button
theme='borderless'
size='large'
block
disabled={loading}
style={{ marginTop: 8 }}
onClick={() => {
setStep(1);
setOrgInfo(null);
setIdentifier(''); // 主动切换企业时清空,便于输入另一家
setCapsOn(false);
}}
>
{t('切换企业')}
</Button>
</Form>
)}
{step === 3 && (
<Form onSubmit={doChangePassword}>
<Banner
type='warning'
closeIcon={null}
description={t('首次登录需修改初始密码后方可使用。')}
className='mb-3'
/>
<Form.Input
field='new_password'
label={t('新密码(8-20 位)')}
mode='password'
size='large'
autoFocus
autoComplete='new-password'
onKeyDown={handleCapsLock}
onKeyUp={handleCapsLock}
validate={(value) => {
if (!value) return t('请输入新密码');
if (value.length < 8 || value.length > 20)
return t('新密码长度需为 8-20 位');
return '';
}}
/>
<Form.Input
field='confirm_password'
label={t('确认新密码')}
mode='password'
size='large'
autoComplete='new-password'
onKeyDown={handleCapsLock}
onKeyUp={handleCapsLock}
validate={(value, values) => {
if (!value) return t('请再次输入新密码');
if (value !== values.new_password)
return t('两次输入的新密码不一致');
return '';
}}
/>
{capsOn && (
<div className='text-xs text-amber-500 -mt-1 mb-1'>
{t('大写锁定已开启')}
</div>
)}
<Button
theme='solid'
size='large'
block
htmlType='submit'
loading={loading}
style={{ marginTop: 16 }}
>
{t('修改并进入')}
</Button>
</Form>
)}
</div>
)}
</GlassCard>
</div>
{/* 免企业标识直登:命中多个企业时的选择框(方案 §12.3) */}
<Modal
title={t('选择要进入的企业')}
visible={!!multiMatch}
onCancel={() => setMultiMatch(null)}
footer={null}
centered
>
<div className='flex flex-col gap-2'>
<p className='text-sm text-gray-500 dark:text-gray-400 mb-1'>
{t('你的账号在以下企业中均可登录,请选择进入哪一个:')}
</p>
{(multiMatch?.orgs || []).map((o) => (
<button
key={o.index}
type='button'
disabled={loading}
onClick={() => doDirectSelect(o.index)}
className='flex items-center gap-3 w-full p-3 rounded-xl border border-gray-200/80 dark:border-white/10 hover:bg-gray-50 dark:hover:bg-white/[0.06] transition-all text-left disabled:opacity-50'
>
{o.logo ? (
<Avatar src={o.logo} shape='square' className='h-8 w-8 rounded-lg' />
) : (
<div className='h-8 w-8 rounded-lg bg-gray-100 dark:bg-white/10' />
)}
<span className='truncate font-medium text-gray-800 dark:text-gray-100'>
{o.name}
</span>
</button>
))}
</div>
</Modal>
</div>
);
};
export default OrgLogin;