Files
monkey-ai-web/src/pages/OrgRegister/index.jsx
T
2026-11-19 10:48:17 +08:00

371 lines
13 KiB
React
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.
/*
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, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Form, Button, Toast, Banner } from '@/components/ui';
import Turnstile from 'react-turnstile';
import { API } from '../../helpers/api';
import { showError, getLogo, getSystemName } from '../../helpers';
import { StatusContext } from '../../context/Status';
import OrgCredentialResult from '../../components/auth/OrgCredentialResult';
import GlassCard from '../../components/auth/GlassCard';
import AuthCardHeader from '../../components/auth/AuthCardHeader';
import AuthLoginTabs from '../../components/auth/AuthLoginTabs';
import AuthDivider from '../../components/auth/AuthDivider';
import AuthBackground from '../../components/common/AuthBackground';
import {
LOGIN_NAME_PATTERN,
isReservedLoginName,
} from '../../helpers/orgLoginName';
/**
* 企业自助注册页(原 OrgRegisterModal 弹窗升级而来)。
* 与 /login、/register、/org/login 共用同一套认证页布局(背景 + 个人/企业切换 + 玻璃卡片),
* 拥有独立 URL 便于直达与分享;注册成功后在本页展示一次性凭证,
* 「立即登录」经 /org/login?org=<code> 预填企业代码直达登录第二步。
*/
const OrgRegister = () => {
const { t } = useTranslation();
const navigate = useNavigate();
const [statusState] = useContext(StatusContext);
const status = statusState?.status || {};
const statusLoaded = statusState?.status !== undefined;
const selfRegisterEnabled = !!status.org_self_register;
const emailVerifyEnabled = !!status.email_verification;
const turnstileEnabled = !!status.turnstile_check;
const turnstileSiteKey = status.turnstile_site_key || '';
const logo = getLogo();
const systemName = getSystemName();
const [values, setValues] = useState({});
const formApi = useRef(null);
const [submitting, setSubmitting] = useState(false);
const [turnstileToken, setTurnstileToken] = useState('');
const [codeLoading, setCodeLoading] = useState(false);
const [countdown, setCountdown] = useState(0);
const [result, setResult] = useState(null); // 注册成功后的一次性凭证
const startCountdown = () => {
setCountdown(30);
const timer = setInterval(() => {
setCountdown((c) => {
if (c <= 1) {
clearInterval(timer);
return 0;
}
return c - 1;
});
}, 1000);
};
const sendCode = async () => {
// 先就地校验联系邮箱(必填 + 格式),未通过时由输入框下方提示
try {
await formApi.current?.validate(['contact_email']);
} catch {
return;
}
const email = (values.contact_email || '').trim();
if (!email) {
Toast.warning(t('请先输入联系邮箱'));
return;
}
if (turnstileEnabled && !turnstileToken) {
Toast.info(t('请稍候,正在进行人机校验'));
return;
}
setCodeLoading(true);
try {
// 企业注册专用发码:不校验邮箱是否已被个人账号占用(联系邮箱非登录名)
const res = await API.get(
`/api/org/register/verification?email=${encodeURIComponent(email)}&turnstile=${turnstileToken}`,
);
if (res.data.success) {
Toast.success(t('验证码已发送,请查收邮箱'));
startCountdown();
} else {
showError(res.data.message);
}
} catch (err) {
if (!err?.isAxiosError) showError(err.message);
} finally {
setCodeLoading(false);
}
};
const handleSubmit = async () => {
let formValues = values;
try {
formValues = await formApi.current?.validate();
} catch {
return; // 校验不通过,Form 已高亮
}
if (turnstileEnabled && !turnstileToken) {
Toast.info(t('请稍候,正在进行人机校验'));
return;
}
setSubmitting(true);
try {
const res = await API.post(
`/api/org/register?turnstile=${turnstileToken}`,
{
name: (formValues.name || '').trim(),
owner_login_name: (formValues.owner_login_name || '').trim(),
owner_display_name: (formValues.owner_display_name || '').trim(),
contact_name: (formValues.contact_name || '').trim(),
contact_email: (formValues.contact_email || '').trim(),
contact_phone: (formValues.contact_phone || '').trim(),
verify_code: (formValues.verify_code || '').trim(),
},
);
if (res.data.success) {
setResult(res.data.data); // 展示一次性凭证
} else {
showError(res.data.message);
}
} catch (err) {
if (!err?.isAxiosError) showError(err.message);
} finally {
setSubmitting(false);
}
};
const renderSkeleton = () => (
<GlassCard withCornerHalos={false} withAurora={false}>
<div className='flex flex-col items-center justify-center mb-5'>
<div className='w-14 h-14 rounded-xl bg-gray-200/60 dark:bg-white/10 animate-pulse mb-3' />
<div className='w-24 h-5 rounded bg-gray-200/60 dark:bg-white/10 animate-pulse mb-1' />
<div className='w-32 h-3 rounded bg-gray-100/80 dark:bg-white/5 animate-pulse' />
</div>
<div className='space-y-2'>
<div className='w-full h-10 rounded-xl bg-gray-200/60 dark:bg-white/10 animate-pulse' />
<div className='w-full h-10 rounded-xl bg-gray-200/60 dark:bg-white/10 animate-pulse' />
<div className='w-full h-10 rounded-xl bg-gray-200/60 dark:bg-white/10 animate-pulse' />
</div>
</GlassCard>
);
// 平台未开放自助注册:直达此 URL 时给出说明并引导回企业登录
const renderDisabled = () => (
<GlassCard>
<AuthCardHeader
wrapperClassName='mb-6'
logo={logo}
title={systemName || t('注册企业')}
subtitle={t('企业注册')}
/>
<Banner
type='info'
closeIcon={null}
description={t('当前未开放企业自助注册,请联系平台管理员开通企业。')}
className='auth-login-banner'
/>
<Button theme='solid' block onClick={() => navigate('/org/login')}>
{t('返回企业登录')}
</Button>
</GlassCard>
);
const renderForm = () => (
<GlassCard>
{/* key 随表单/凭证两态切换,触发与企业登录页一致的步骤过渡动画 */}
<div key={result ? 'result' : 'form'} className='org-step-enter'>
<AuthCardHeader
wrapperClassName='mb-6'
logo={logo}
title={result ? t('企业注册成功') : t('注册企业')}
subtitle={
result ? t('请妥善保存以下凭证') : t('为你的团队开通企业空间')
}
/>
{result ? (
<OrgCredentialResult
creds={result}
onLogin={() =>
// 带上企业代码与登录名直达登录第二步,用户只需输入初始密码
navigate(
`/org/login?org=${encodeURIComponent(result.org_code)}&login=${encodeURIComponent(result.owner_login_name || '')}`,
)
}
/>
) : (
<>
<Form
className='auth-login-form'
getFormApi={(api) => (formApi.current = api)}
onValueChange={(v) => setValues(v)}
>
<Form.Input
field='name'
label={t('企业名称')}
placeholder={t('请输入企业名称(登录时可用于搜索定位)')}
rules={[{ required: true, message: t('请输入企业名称') }]}
/>
<Form.Input
field='owner_login_name'
label={t('管理员登录名')}
placeholder={t('请设置管理员登录名,如 zhang.san')}
extraText={t(
'登录企业空间使用的管理员账号名,注册后不可修改;请勿使用 admin、root 等通用名',
)}
rules={[
{ required: true, message: t('请输入管理员登录名') },
{
pattern: LOGIN_NAME_PATTERN,
message: t(
'登录名需为 3-32 位,以字母开头,仅可包含字母、数字、下划线、点或短横线',
),
},
{
validator: (rule, value) => !isReservedLoginName(value),
message: t('该登录名为系统保留名称,请换一个登录名'),
},
]}
/>
<Form.Input
field='owner_display_name'
label={t('管理员显示名')}
placeholder={t('选填')}
/>
<Form.Input
field='contact_name'
label={t('联系人')}
placeholder={t('选填')}
/>
<Form.Input
field='contact_email'
label={t('联系邮箱')}
placeholder={t('用于接收通知')}
rules={[
...(emailVerifyEnabled
? [{ required: true, message: t('请输入联系邮箱') }]
: []),
// 格式校验:选填时为空不报错,有值时需为合法邮箱
{
type: 'email',
transform: (v) => v?.trim(),
message: t('邮箱格式不正确'),
},
]}
trigger='blur'
suffix={
emailVerifyEnabled ? (
<Button
size='small'
onClick={sendCode}
loading={codeLoading}
disabled={countdown > 0}
>
{countdown > 0
? `${t('重新发送')} (${countdown})`
: t('获取验证码')}
</Button>
) : undefined
}
/>
{emailVerifyEnabled && (
<Form.Input
field='verify_code'
label={t('邮箱验证码')}
placeholder={t('请输入验证码')}
rules={[{ required: true, message: t('请输入邮箱验证码') }]}
/>
)}
<Form.Input
field='contact_phone'
label={t('联系电话')}
placeholder={t('选填')}
/>
</Form>
<div className='auth-login-actions'>
<Button
theme='solid'
block
className='auth-login-submit'
loading={submitting}
onClick={handleSubmit}
>
{t('提交注册')}
</Button>
</div>
<AuthDivider>{t('已有企业?')}</AuthDivider>
<Button
theme='borderless'
block
className='!text-brand'
onClick={() => navigate('/org/login')}
>
{t('去登录')}
</Button>
</>
)}
</div>
</GlassCard>
);
return (
<div
className='auth-login-page 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 && !status.self_use_mode_enabled && !result && (
<div className='w-full max-w-sm mb-4'>
<AuthLoginTabs mode='register' active='enterprise' />
</div>
)}
{!statusLoaded
? renderSkeleton()
: selfRegisterEnabled
? renderForm()
: renderDisabled()}
{turnstileEnabled && !result && (
<div className='flex justify-center mt-6'>
<Turnstile
sitekey={turnstileSiteKey}
onVerify={(token) => setTurnstileToken(token)}
/>
</div>
)}
</div>
</div>
);
};
export default OrgRegister;