import { formatIdReference } from '../../helpers/safeDisplay';
import { useFilterSearch } from '../../hooks/common/useFilterSearch';
import { useFilteredTableRows } from '../../hooks/common/useFilteredTableRows';
import { ConsoleCollectionSearch } from '@/components/console/ConsoleCollection';
import {
ConsoleFilterField,
ConsoleFilterGrid,
} from '@/components/console/ConsolePrimitives';
import React, {
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
} from 'react';
import { useLocation, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Button, Empty, Layout, Spin, Tag, Typography } from 'antd';
// 存量 Semi 契约(受控值 onChange(value)、visible、empty、Tabs.TabPane 等)与控制台
// 作用域(ConsoleCard / ConsoleModal / ConsoleTable / ConsoleTabs / ConsoleAlert)由适配层统一映射。
import {
Alert,
Card,
Input,
Modal,
Select,
Table,
Tabs,
TextArea,
} from '@/components/ui';
import {
ArrowLeft as ActionArrowLeft,
Download,
Search,
RefreshCw as ActionRefresh,
} from '@/components/common/icons/ActionIcons';
import {
Bell,
ChevronRight,
CircleDollarSign,
FileText,
Home,
ScrollText,
TrendingUp,
Users,
} from 'lucide-react';
import { BillingColumns, AdjustmentColumns } from './operations';
import { commissionLabel } from './labels';
import { PARTNER_NAVIGATION, partnerView } from './partnerNavigation';
import './partnerPortal.css';
import OrgPageHeader from '../Organization/components/OrgPageHeader';
import OrgModal from '../Organization/components/OrgModal';
import { useCommissionThemeStyle } from './commissionTheme';
const { Content } = Layout;
const { Title, Text } = Typography;
const PROTECTED = ['protected', 'protected_extended', 'pending_conversion'];
const NAV_ICONS = {
overview: Home,
customers: Users,
estimate: TrendingUp,
bills: FileText,
rules: ScrollText,
};
const NAVIGATION = PARTNER_NAVIGATION.map((item) => ({
...item,
icon: NAV_ICONS[item.key],
}));
const protectionUntil = (row) =>
Number(row.extended_until || row.protected_until || 0);
function Metric({ label, value, note, primary = false }) {
return (
{label}
{value}
{note &&
{note}
}
);
}
export default function PartnerPortal({
fetchJSON,
mutateJSON,
money,
date,
formatDateTime,
exportDetails,
TierSummary,
PaymentTable,
tag,
embedded = false,
}) {
const themeStyle = useCommissionThemeStyle();
const PartnerModal = embedded ? OrgModal : Modal;
const { t } = useTranslation();
const location = useLocation();
const [searchParams, setSearchParams] = useSearchParams();
const [localActive, setLocalActive] = useState('overview');
const active = embedded ? partnerView(location.search) : localActive;
const internalSearch = useRef(null);
const setActive = (key) => {
if (!embedded) {
setLocalActive(key);
return;
}
if (active === key) return;
const next = new URLSearchParams(searchParams);
next.set('view', key);
internalSearch.current = `?${next}`;
setSearchParams(next);
};
const [loading, setLoading] = useState(true);
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState('');
const [data, setData] = useState({
rows: [],
realtime: [],
customers: [],
summary: {},
});
const [selected, setSelected] = useState(null);
const [details, setDetails] = useState({
items: [],
adjustments: [],
payments: [],
});
const [detailLoading, setDetailLoading] = useState(false);
const [mutationLoading, setMutationLoading] = useState(false);
const [exportingId, setExportingId] = useState(null);
const [action, setAction] = useState(null);
const [reason, setReason] = useState('');
const [actionError, setActionError] = useState('');
const [query, setQuery] = useState('');
const [customerQuery, setCustomerQuery] = useState('');
const [customerStatus, setCustomerStatus] = useState('all');
const [billMonth, setBillMonth] = useState('all');
const [billStatus, setBillStatus] = useState('all');
const [appliedDetail, setAppliedDetail] = useState('');
const [appliedCustomer, setAppliedCustomer] = useState({
keyword: '',
status: 'all',
});
const [appliedBill, setAppliedBill] = useState({
month: 'all',
status: 'all',
});
const detailSearch = useFilterSearch(() =>
setAppliedDetail(query.toLowerCase()),
);
const customerSearch = useFilterSearch(() =>
setAppliedCustomer({
keyword: customerQuery.toLowerCase(),
status: customerStatus,
}),
);
const billSearch = useFilterSearch(() =>
setAppliedBill({ month: billMonth, status: billStatus }),
);
const [billPage, setBillPage] = useState(1);
const [customerPage, setCustomerPage] = useState(1);
const [detailPage, setDetailPage] = useState(1);
const loadVersion = useRef(0);
const detailVersion = useRef(0);
const selectedId = useRef(null);
const mounted = useRef(true);
const mutationBusy = useRef(false);
// Sidebar links and browser history must dismiss old details/confirmations.
// Internal overview -> statement navigation preserves the detail being opened.
useLayoutEffect(() => {
if (!embedded) return;
const internal = internalSearch.current === location.search;
internalSearch.current = null;
if (internal) return;
detailVersion.current++;
selectedId.current = null;
setSelected(null);
setDetailLoading(false);
setAction(null);
setActionError('');
}, [embedded, location.key, location.search]);
const { rows, realtime, customers, summary } = data;
const { items, adjustments, payments } = details;
const load = useCallback(async () => {
const version = ++loadVersion.current;
setLoading(true);
setError('');
try {
const [statements, estimate, assignments, overview] = await Promise.all([
fetchJSON('/api/partner/v2/statements'),
fetchJSON('/api/partner/v2/realtime'),
fetchJSON('/api/partner/v2/assignments'),
fetchJSON('/api/partner/v2/summary'),
]);
if (mounted.current && version === loadVersion.current) {
setData({
rows: statements,
realtime: estimate,
customers: assignments,
summary: overview,
});
setLoaded(true);
}
} catch (err) {
if (mounted.current && version === loadVersion.current)
setError(err.message);
} finally {
if (mounted.current && version === loadVersion.current) setLoading(false);
}
}, [fetchJSON]);
const invalidateRequests = useCallback(() => {
loadVersion.current++;
detailVersion.current++;
}, []);
useEffect(() => {
mounted.current = true;
load();
return () => {
mounted.current = false;
invalidateRequests();
};
}, [load, invalidateRequests]);
const readDetail = useCallback(
async (id) => {
const [statement, statementItems, changes, paymentRows] =
await Promise.all([
fetchJSON(`/api/partner/v2/statements/${id}`),
fetchJSON(`/api/partner/v2/statements/${id}/items`),
fetchJSON(`/api/partner/v2/statements/${id}/adjustments`),
fetchJSON(`/api/partner/v2/statements/${id}/payments`),
]);
return {
statement,
items: statementItems,
adjustments: changes,
payments: paymentRows,
};
},
[fetchJSON],
);
const navigate = (key) => {
if (mutationBusy.current) return;
detailVersion.current++;
selectedId.current = null;
setSelected(null);
setDetailLoading(false);
setActive(key);
setAction(null);
setActionError('');
};
const open = async (row, nextAction = null) => {
if (mutationBusy.current) return;
const version = ++detailVersion.current;
selectedId.current = row.id;
setActive('bills');
setSelected(row);
setDetails({ items: [], adjustments: [], payments: [] });
setDetailLoading(true);
setError('');
setQuery('');
detailSearch.cancelPendingSearch();
setQuery('');
setAppliedDetail('');
setDetailPage(1);
setAction(null);
setReason('');
setActionError('');
try {
const result = await readDetail(row.id);
if (!mounted.current || version !== detailVersion.current) return;
setSelected(result.statement);
setDetails(result);
if (nextAction && result.statement.status === 'pending_confirmation')
setAction(nextAction);
} catch (err) {
if (!mounted.current || version !== detailVersion.current) return;
selectedId.current = null;
setSelected(null);
setError(err.message);
} finally {
if (mounted.current && version === detailVersion.current)
setDetailLoading(false);
}
};
const transition = async () => {
if (
!mounted.current ||
mutationBusy.current ||
!selected ||
selected.status !== 'pending_confirmation' ||
!action
)
return;
if (action === 'reject' && !reason.trim()) {
setActionError(t('请填写驳回原因'));
return;
}
const id = selected.id;
mutationBusy.current = true;
setMutationLoading(true);
setActionError('');
let committed = false;
try {
await mutateJSON('post', `/api/partner/v2/statements/${id}/transition`, {
to: action === 'reject' ? 'checking' : 'confirmed',
reason: reason.trim(),
});
committed = true;
if (!mounted.current) return;
setAction(null);
setReason('');
// Invalidate any detail request made before the mutation committed.
const version = ++detailVersion.current;
setDetailLoading(true);
await Promise.all([
load(),
readDetail(id).then((result) => {
if (
mounted.current &&
version === detailVersion.current &&
selectedId.current === id
) {
setSelected(result.statement);
setDetails(result);
}
}),
]);
} catch (err) {
if (mounted.current) {
setActionError(err.message);
setError(err.message);
if (committed) {
detailVersion.current++;
selectedId.current = null;
setSelected(null);
}
}
} finally {
mutationBusy.current = false;
if (mounted.current) {
setMutationLoading(false);
setDetailLoading(false);
}
}
};
const exportStatement = async (row) => {
if (exportingId !== null || mutationBusy.current) return;
setExportingId(row.id);
setError('');
try {
const result = await readDetail(row.id);
if (mounted.current)
exportDetails(result.items, result.adjustments, result.statement, t);
} catch (err) {
if (mounted.current) setError(err.message);
} finally {
if (mounted.current) setExportingId(null);
}
};
const totals = useMemo(
() =>
realtime.reduce(
(sum, row) => ({
sales: sum.sales + Number(row.base_amount_uyuan || 0),
commission: sum.commission + Number(row.estimated_uyuan || 0),
count: sum.count + Number(row.detail_count || 0),
}),
{ sales: 0, commission: 0, count: 0 },
),
[realtime],
);
const pending = rows.filter((row) => row.status === 'pending_confirmation');
const formalCount = customers.filter((row) => row.status === 'formal').length;
const protectedCount = customers.filter((row) =>
PROTECTED.includes(row.status),
).length;
const earliestDeadline = pending.reduce((min, row) => {
const value = Number(row.confirmation_deadline || 0);
return value > 0 && (!min || value < min) ? value : min;
}, 0);
const currentMonth =
realtime[0]?.statement_month ||
`${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}`;
const currentStatements = rows.filter(
(row) => row.statement_month === currentMonth,
);
const matchesDetail = useCallback(
(item) =>
!appliedDetail ||
[
item.customer_name,
item.model_name,
item.billing_record_id,
item.tier_key,
].some((value) =>
String(value || '')
.toLowerCase()
.includes(appliedDetail),
),
[appliedDetail],
);
const detailItems = useFilteredTableRows(items, matchesDetail);
const matchesCustomer = useCallback(
(row) =>
(appliedCustomer.status === 'all' ||
row.status === appliedCustomer.status) &&
(!appliedCustomer.keyword ||
[row.customer_name, row.subject_name, row.subject_id].some((value) =>
String(value || '')
.toLowerCase()
.includes(appliedCustomer.keyword),
)),
[appliedCustomer],
);
const visibleCustomers = useFilteredTableRows(customers, matchesCustomer);
const matchesBill = useCallback(
(row) =>
(appliedBill.month === 'all' ||
row.statement_month === appliedBill.month) &&
(appliedBill.status === 'all' || row.status === appliedBill.status),
[appliedBill],
);
const visibleBills = useFilteredTableRows(rows, matchesBill);
const adjustmentImpact = adjustments
.filter((row) => row.status !== 'voided')
.reduce(
(sum, row) =>
sum +
Number(
row.commission_impact_uyuan ??
(row.type === 'commission_amount' ? row.amount_uyuan : 0),
),
0,
);
const recentMonths = useMemo(() => {
const months = new Map();
for (const row of rows)
months.set(
row.statement_month,
(months.get(row.statement_month) || 0) +
Number(row.estimated_uyuan || 0),
);
return Array.from(months, ([month, amount]) => ({ month, amount }))
.sort((a, b) => a.month.localeCompare(b.month))
.slice(-6);
}, [rows]);
const chartMax = Math.max(
1,
...recentMonths.map((row) => Math.abs(row.amount)),
);
const expiringCustomers = customers.filter(
(row) =>
PROTECTED.includes(row.status) &&
protectionUntil(row) > Date.now() / 1000 &&
protectionUntil(row) < Date.now() / 1000 + 7 * 86400,
);
const agreementExpiring =
summary.agreement_expires_at > Date.now() / 1000 &&
summary.agreement_expires_at < Date.now() / 1000 + 30 * 86400;
const pageTitle = selected
? '提成账单详情'
: NAVIGATION.find((item) => item.key === active).label;
const subtitles = {
overview: '本月数据为实时预估,以正式提成账单为准',
customers: '仅展示归属于您的客户及状态,不提供编辑功能',
estimate: '预估数据不含后续人工调整,实际以正式提成账单为准',
bills: '查看月度提成账单,并在线确认或驳回;确认后由平台办理后续结算',
rules: '查看分佣计算与结算规则;具体合作条款以签署协议为准',
};
const billColumns = [
{
title: t('账单号'),
dataIndex: 'id',
render: (value) => #{value},
},
{ title: t('账期'), dataIndex: 'statement_month' },
{
title: t('应计提成'),
dataIndex: 'estimated_uyuan',
render: money,
align: 'right',
},
{
title: t('手续费'),
dataIndex: 'fee_uyuan',
render: money,
align: 'right',
},
{
title: t('应付提成'),
dataIndex: 'payable_uyuan',
render: (value) => {money(value)},
align: 'right',
},
{
title: t('状态'),
render: (_, row) =>
row.status === 'checking' && row.rejected_at ? (
{t('已驳回,平台核对中')}
) : (
tag(row.status)
),
},
{
title: t('确认截止'),
dataIndex: 'confirmation_deadline',
render: (value, row) =>
row.status === 'pending_confirmation' ? formatDateTime(value) : '—',
},
{
title: t('操作'),
width: 230,
render: (_, row) => (
{row.status === 'pending_confirmation' && (
<>
>
)}
),
},
];
const refreshButton = (
}
disabled={mutationLoading || detailLoading}
loading={loading}
onClick={() => {
load();
if (selected) open(selected);
}}
>
{t('刷新')}
);
const renderBills = () => (
<>
{
billSearch.cancelPendingSearch();
setAppliedBill({ month: 'all', status: 'all' });
setBillMonth('all');
setBillStatus('all');
setBillPage(1);
}}
onSearch={billSearch.submitSearch}
>
{t('共 {{count}} 张账单', { count: visibleBills.length })}
{refreshButton}
0 || billPage > 1
? {
pageSize: 10,
current: billPage,
onPageChange: setBillPage,
preservePage: true,
}
: false
}
scroll={{ x: 1120 }}
empty={
}
/>
{t(
'待确认账单请在确认截止日期前确认或驳回;截止日前无反馈,系统视同确认。驳回后由平台核对修正,重新出账后请再次确认。',
)}
>
);
const renderDetail = () => (
<>
{t('账单号')}:#{selected.id} · {t('账期')}:
{selected.statement_month}
{tag(selected.status)}
{selected.confirmation_deadline > 0 && (
{t('确认截止')}:{formatDateTime(selected.confirmation_deadline)}
)}
{selected.confirmation_method && (
{t(
selected.confirmation_method === 'timeout'
? '逾期视同确认'
: '伙伴确认',
)}
)}
{selected.status === 'checking' && (
{t('已驳回,平台核对中,重新出账后可确认修正后的账单。')}
{selected.rejection_reason && (
{t('驳回原因')}:{selected.rejection_reason}
)}
>
}
/>
)}
{selected.status === 'completed' && (
)}
sum + Number(row.base_amount_uyuan || 0),
0,
),
)
}
/>
{detailLoading ? (
) : (
<>
{t('按档位与消费场景汇总')}
{t('调整单净提成影响')}:{money(adjustmentImpact)} ·{' '}
{t('已计入应计提成')}
{t('上期结转扣减')}:{money(selected.carry_in_uyuan)} ·{' '}
{t('下期结转扣减')}:{money(selected.carry_out_uyuan)} ·{' '}
{t('舍入尾差')}:{money(selected.rounding_uyuan)}
{
detailSearch.cancelPendingSearch();
setQuery('');
setAppliedDetail('');
setDetailPage(1);
}}
onSearch={detailSearch.submitSearch}
>
}
value={query}
onChange={detailSearch.changeFilter(setQuery)}
placeholder={t('搜索客户、模型、计费记录或档位')}
showClear
/>
0 || detailPage > 1
? {
preservePage: true,
pageSize: 10,
current: detailPage,
onPageChange: setDetailPage,
}
: false
}
empty={
}
/>
{t(
'调整单独立于模型调用消耗记录展示;提成金额调整不改变有效销售额。',
)}
0 ? { pageSize: 10 } : false}
empty={
}
/>
>
)}
>
);
const renderOverview = () => (
<>
{t('欢迎使用合作分佣工作台')} · {t('伙伴状态')}:
{commissionLabel(t, 'status', summary.partner_status)}
{summary.agreement_expires_at > 0 && (
<>
{' '}
· {t('协议有效期至')} {date(summary.agreement_expires_at)}
>
)}
{' · '}
{t('如有疑问请联系平台运营。')}
{t('近 6 个账期提成')}
{t('正式账单应计提成')}
{recentMonths.length ? (
{recentMonths.map((row) => (
{money(row.amount)}
{row.month}
))}
) : (
)}
{t('提醒')}
{rows
.filter((row) =>
['pending_confirmation', 'confirmed', 'checking'].includes(
row.status,
),
)
.slice(0, 5)
.map((row) => (
))}
{expiringCustomers.map((row) => (
))}
{agreementExpiring && (
{t('合作协议临近到期')}
{date(summary.agreement_expires_at)}
)}
{!rows.some((row) =>
['pending_confirmation', 'confirmed', 'checking'].includes(
row.status,
),
) &&
!expiringCustomers.length &&
!agreementExpiring && (
)}
>
);
const renderCustomers = () => (
<>
{
customerSearch.cancelPendingSearch();
setAppliedCustomer({ keyword: '', status: 'all' });
setCustomerQuery('');
setCustomerStatus('all');
setCustomerPage(1);
}}
onSearch={customerSearch.submitSearch}
>
}
value={customerQuery}
onChange={customerSearch.changeFilter(setCustomerQuery)}
showClear
placeholder={t('搜索客户名称或编号')}
/>
{t('共 {{count}} 条归属记录', { count: visibleCustomers.length })}
{refreshButton}
0 || customerPage > 1
? {
preservePage: true,
pageSize: 10,
current: customerPage,
onPageChange: setCustomerPage,
}
: false
}
scroll={{ x: 1100 }}
empty={
}
columns={[
{
title: t('客户'),
render: (_, row) => (
{row.customer_name ||
row.subject_name ||
`${commissionLabel(t, 'subjectType', row.subject_type)} ${formatIdReference(row.subject_id)}`}
),
},
{
title: t('类型'),
dataIndex: 'subject_type',
render: (value) => commissionLabel(t, 'subjectType', value),
},
{ title: t('归属状态'), dataIndex: 'status', render: tag },
{
title: t('正式归属起点'),
dataIndex: 'formal_at',
render: formatDateTime,
},
{ title: t('保护期开始'), dataIndex: 'started_at', render: date },
{
title: t('保护期至'),
render: (_, row) => date(protectionUntil(row)),
},
{
title: t('保护期剩余天数'),
render: (_, row) =>
PROTECTED.includes(row.status)
? Math.max(
0,
Math.ceil(
(protectionUntil(row) - Date.now() / 1000) / 86400,
),
)
: '—',
},
{
title: t('归属结束'),
dataIndex: 'ended_at',
render: formatDateTime,
},
]}
/>
>
);
const renderEstimate = () => (
<>
{summary.partner_status === 'terminated' ? (
) : (
<>
{t('本月预估汇总')}
{t('按账期汇总')}
}
columns={[
{ title: t('账期'), dataIndex: 'statement_month' },
{ title: t('计费明细笔数'), dataIndex: 'detail_count' },
{
title: t('有效销售额'),
dataIndex: 'base_amount_uyuan',
render: money,
align: 'right',
},
{
title: t('预估提成'),
dataIndex: 'estimated_uyuan',
render: money,
align: 'right',
},
]}
/>
{t(
'单笔消耗及档位比例可在正式账单详情中核对。预估汇总不代表已正式出账。',
)}
{currentStatements.map((row) => (
))}
>
)}
>
);
const renderRules = () => (
{t('分佣计算规则')}
{t('分佣档位与比例')}
{t(
'默认等级跟随渠道档位;优惠等级的正常钱包消费使用等级绑定档位,替代、不叠加。0% 不回退;缺少等级绑定档位时阻断计提与出账。',
)}
{t('历史快照')}
{t(
'历史明细按计费时的等级、档位和比例快照展示,不能用当前等级重算历史。具体比例请在正式账单的档位汇总与单笔明细中核对。',
)}
{t('调整与结转')}
{t(
'人工调整单独列示,并计入应计提成和本期应付。账单详情同时展示手续费、上期结转扣减、下期结转扣减与舍入尾差。',
)}
{t('客户归属与结算')}
-
{t(
'客户保护期默认 90 天,可延期 1 次,最长 60 天。实际保护期限以我的客户页面为准。',
)}
-
{t(
'保护期内签约,或首次充值并产生付费消耗,经平台确认后转为正式归属。',
)}
- {t('实时预估仅供参考,最终金额以正式提成账单为准。')}
-
{t(
'正式账单请在确认截止日期前确认或驳回;逾期无反馈视同确认。驳回需填写原因,平台修正并重新出账后再次确认。',
)}
-
{t(
'确认后由平台办理后续结算;企业伙伴按协议办理开票,个人伙伴以账单中列示的手续费为准。0 元应付账单确认后可直接完成。',
)}
-
{t(
'转移或终止后的客户消费不在伙伴可见范围内;历史正式账单仍可查看。',
)}
);
return (
{!embedded && (
)}
{selected && (
}
disabled={mutationLoading}
onClick={() => navigate('bills')}
>
{t('返回我的提成')}
)}
{embedded ? (
{t(subtitles[active])}
{['overview', 'estimate'].includes(active) &&
summary.updated_at
? ` · ${t('数据更新时间')}:${formatDateTime(summary.updated_at)}`
: ''}
>
)
}
/>
) : (
{t(pageTitle)}
)}
{!embedded && (
{selected
? `${t('账单号')} ${formatIdReference(selected.id)} · ${selected.statement_month}`
: t(subtitles[active])}
{!selected &&
['overview', 'estimate'].includes(active) &&
summary.updated_at
? ` · ${t('数据更新时间')}:${formatDateTime(summary.updated_at)}`
: ''}
)}
{selected && (
<>
}
disabled={detailLoading || mutationLoading}
onClick={() =>
exportDetails(items, adjustments, selected, t)
}
>
{t('导出明细')}
{selected.status === 'pending_confirmation' && (
<>
>
)}
>
)}
{(selected ||
!loaded ||
!['bills', 'customers'].includes(active)) &&
refreshButton}
{error && }
{loading && !selected ? (
) : !loaded && !selected ? (
) : selected ? (
renderDetail()
) : active === 'overview' ? (
renderOverview()
) : active === 'customers' ? (
renderCustomers()
) : active === 'estimate' ? (
renderEstimate()
) : active === 'bills' ? (
renderBills()
) : (
renderRules()
)}
{
if (!mutationLoading) setAction(null);
}}
onOk={transition}
okButtonProps={{ disabled: action === 'reject' && !reason.trim() }}
cancelButtonProps={{ disabled: mutationLoading }}
okText={t(action === 'reject' ? '提交驳回' : '确认无误')}
cancelText={t('取消')}
>
{actionError && (
)}
{action === 'reject' ? (
<>
>
) : (
<>
{t('本期应付提成')} {money(selected?.payable_uyuan)}。
{t('确认后账单不可再驳回,平台将办理后续结算。')}
>
}
/>
{t(
Number(selected?.payable_uyuan) === 0
? '本期为 0 元账单,确认后直接完成。'
: '请确认销售额、应计提成、手续费及本期应付金额均已核对。确认后账单金额锁定。',
)}
>
)}
);
}