ApprovalDetailPresentation.tsx 13.5 KB
import { CheckOutlined, CloseOutlined, MinusOutlined } from '@ant-design/icons';
import { UButton } from '@uj/ui';
import type { StoreApprovalLog, StoreListingDetail } from '@/api';
import { STORE_STATUS, type StoreStatus } from '@/config/storeStatus';
import type { StoreDictionaries } from './dictionaries';
import { dictionaryLabel, formatDateTime, formatMoney } from './formatters';
import './approvalDetail.css';

const EMPTY = '—';
const ACTION_LABELS: Record<string, string> = {
  SUBMIT: '提交',
  PASS: '通过',
  BATCH_PASS: '批量通过',
  REJECT: '打回',
  REVOKE: '撤回',
  REVOKED: '撤回',
  RESUBMIT: '重新提交',
  VOID: '作废',
  APPROVE: '通过',
};
const ROLE_LABELS: Record<string, string> = {
  YJ_BUSINESS_MGR: '优加商务经理',
  YJ_BIZ_MGR: '优加商务经理',
  YJ_FINANCE_MGR: '优加财务经理',
  ONLINE_OPS: '线上运营',
  SYS_ADMIN: '系统管理员',
};
const PASS_ACTIONS = new Set(['PASS', 'BATCH_PASS', 'APPROVE']);

type StageState = 'done' | 'current' | 'rejected' | 'waiting' | 'stopped';
interface FlowStage {
  key: string;
  title: string;
  state: StageState;
  number: number;
  actor?: string | null;
  time?: string | null;
  caption?: string;
}

function labelFrom(labels: Record<string, string>, value?: string | null): string {
  return value && Object.hasOwn(labels, value) ? labels[value] : value || EMPTY;
}

function statusLabel(status?: string | null): string {
  if (status === 'DRAFT') return '草稿';
  return status && Object.hasOwn(STORE_STATUS, status)
    ? STORE_STATUS[status as StoreStatus].label
    : status || EMPTY;
}

function categoryCount(detail: StoreListingDetail): string {
  if (
    typeof detail.categoryCount === 'number' &&
    Number.isSafeInteger(detail.categoryCount) &&
    detail.categoryCount >= 0
  ) {
    return `${detail.categoryCount} 个`;
  }
  if (!detail.items) return EMPTY;
  const categories = detail.items
    .map((item) => item.productCategory?.trim())
    .filter((category): category is string => !!category);
  return `${new Set(categories).size} 个`;
}

function timeToMinute(value?: string | null): string {
  const formatted = formatDateTime(value);
  return /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}/.test(formatted) ? formatted.slice(0, 16) : formatted;
}

function approvalRoles(detail: StoreListingDetail): string[] {
  return detail.totalLevel === 1 ? ['优加财务经理'] : ['优加商务经理', '优加财务经理'];
}

function currentLevel(detail: StoreListingDetail): number {
  return detail.totalLevel !== 1 && detail.currentLevel === 2 ? 2 : 1;
}

function orderedLogs(detail: StoreListingDetail): StoreApprovalLog[] {
  return [...(detail.approvalLogs || [])].sort((a, b) =>
    (a.operateTime || '').localeCompare(b.operateTime || ''),
  );
}

function ApprovalStatus({ detail }: { detail: StoreListingDetail }) {
  const tone =
    detail.status === 'APPROVED'
      ? 'approved'
      : detail.status === 'PENDING'
        ? 'pending'
        : detail.status === 'REJECTED'
          ? 'rejected'
          : 'neutral';
  return (
    <span className={`approval-detail-status approval-detail-status--${tone}`}>
      <span aria-hidden="true" className="approval-detail-status__dot" />
      {detail.statusLabel?.trim() || statusLabel(detail.status)}
    </span>
  );
}

function StageIcon({ state, number }: { state: StageState; number?: number }) {
  if (number !== undefined) return <>{number}</>;
  if (state === 'rejected') return <CloseOutlined />;
  if (state === 'stopped') return <MinusOutlined />;
  return <CheckOutlined />;
}

export function ApprovalDetailHeader({
  detail,
  spec,
  onClose,
}: {
  detail: StoreListingDetail;
  spec?: StoreDictionaries;
  onClose: () => void;
}) {
  const money = formatMoney(detail.costTotal);
  const total = money === EMPTY ? EMPTY : `${money.replace(/^¥/, '').replace(/\.00$/, '')} 元`;
  return (
    <section className="approval-detail-header" aria-label="审批概览">
      <div className="approval-detail-header__top">
        <div className="approval-detail-header__identity">
          <ApprovalStatus detail={detail} />
          <h2>{detail.storeName?.trim() || EMPTY}</h2>
        </div>
        <UButton
          type="text"
          className="approval-detail-header__close"
          aria-label="关闭"
          icon={<CloseOutlined />}
          onClick={onClose}
        />
      </div>
      <dl className="approval-detail-meta">
        <div>
          <dt>门店商户号</dt>
          <dd>{detail.merchantNo?.trim() || EMPTY}</dd>
        </div>
        <div>
          <dt>业务场景</dt>
          <dd>{dictionaryLabel(spec?.businessScenes, detail.businessScene)}</dd>
        </div>
        <div>
          <dt>产品分类</dt>
          <dd>{categoryCount(detail)}</dd>
        </div>
        <div>
          <dt>运营成本合计</dt>
          <dd>{total}</dd>
        </div>
        <div>
          <dt>提交人</dt>
          <dd>
            {detail.submitUserName?.trim() || EMPTY}
            <span className="approval-detail-meta__time"> · {timeToMinute(detail.submitTime)}</span>
          </dd>
        </div>
      </dl>
    </section>
  );
}

export function ApprovalStages({ detail }: { detail: StoreListingDetail }) {
  const roles = approvalRoles(detail);
  const level = currentLevel(detail);
  const approved = detail.status === 'APPROVED';
  const pending = detail.status === 'PENDING';
  const rejected = detail.status === 'REJECTED';
  const stopped = detail.status === 'REVOKED' || detail.status === 'VOID';
  const logs = orderedLogs(detail).reverse();
  const stages: FlowStage[] = [
    {
      key: 'submit',
      title: '提交',
      number: 1,
      state: 'done',
      actor: detail.submitUserName || EMPTY,
      time: detail.submitTime,
    },
    ...roles.map((title, index): FlowStage => {
      const passedLog = logs.find(
        (log) =>
          PASS_ACTIONS.has(log.action || '') && labelFrom(ROLE_LABELS, log.operatorRole) === title,
      );
      const done =
        approved || ((pending || rejected) && index + 1 < level) || (stopped && !!passedLog);
      const active = index + 1 === level;
      const state: StageState = done
        ? 'done'
        : rejected && active
          ? 'rejected'
          : pending && active
            ? 'current'
            : stopped
              ? 'stopped'
              : 'waiting';
      return {
        key: title,
        title,
        number: index + 2,
        state,
        actor: done ? passedLog?.operatorName : undefined,
        time: done ? passedLog?.operateTime : undefined,
        caption:
          state === 'current'
            ? '当前审批节点'
            : state === 'rejected'
              ? '已打回'
              : state === 'stopped'
                ? '已停止'
                : undefined,
      };
    }),
    {
      key: 'effective',
      title: '生效',
      number: roles.length + 2,
      state: approved ? 'done' : stopped ? 'stopped' : 'waiting',
      time: approved ? (detail.effectiveTime ?? detail.approveTime) : undefined,
      caption: approved ? undefined : stopped || rejected ? '未生效' : '写入门店列表',
    },
  ];

  return (
    <section className="approval-detail-flow" aria-label="审批流程">
      <div className="approval-detail-flow__heading">
        <h3>审批流程</h3>
        <span>{roles.length === 1 ? '单级审批' : '两级审批'}</span>
      </div>
      <ol className="approval-detail-flow__nodes">
        {stages.map((stage) => (
          <li
            key={stage.key}
            className={`approval-detail-flow__node approval-detail-flow__node--${stage.state}`}
          >
            <span className="approval-detail-flow__icon" aria-hidden="true">
              <StageIcon state={stage.state} number={stage.number} />
            </span>
            <strong>{stage.title}</strong>
            {stage.caption && (
              <span className="approval-detail-flow__caption">{stage.caption}</span>
            )}
            {stage.actor && <span className="approval-detail-flow__caption">{stage.actor}</span>}
            {stage.time && (
              <span className="approval-detail-flow__time">
                {stage.key === 'effective' ? formatDateTime(stage.time) : timeToMinute(stage.time)}
              </span>
            )}
          </li>
        ))}
      </ol>
    </section>
  );
}

function logState(log: StoreApprovalLog): StageState {
  if (log.action === 'REJECT') return 'rejected';
  if (['REVOKE', 'REVOKED', 'VOID'].includes(log.action || '')) return 'stopped';
  if (PASS_ACTIONS.has(log.action || '') || ['SUBMIT', 'RESUBMIT'].includes(log.action || ''))
    return 'done';
  return 'waiting';
}

export function ApprovalAuditTrail({
  detail,
  pendingHours,
}: {
  detail: StoreListingDetail;
  spec?: StoreDictionaries;
  pendingHours?: number | null;
}) {
  const logs = orderedLogs(detail);
  const roles = approvalRoles(detail);
  const level = currentLevel(detail);
  const pending = detail.status === 'PENDING';
  const approved = detail.status === 'APPROVED';
  const showHours =
    typeof pendingHours === 'number' && Number.isFinite(pendingHours) && pendingHours >= 0;
  const futureCaption = level === roles.length ? '通过后即可生效' : '全部审批节点通过后自动生效';

  return (
    <section className="approval-detail-audit" aria-label="审批留痕列表">
      {!logs.length && <p className="approval-detail-audit__empty">暂无审批留痕</p>}
      {logs.map((log, index) => {
        const state = logState(log);
        return (
          <article key={`${log.logId ?? 'log'}-${index}`} className="approval-detail-chaincard">
            <span
              className={`approval-detail-chaincard__icon approval-detail-chaincard__icon--${state}`}
              aria-hidden="true"
            >
              <StageIcon state={state} />
            </span>
            <div className="approval-detail-chaincard__content">
              <div className="approval-detail-chaincard__title">
                <strong>{labelFrom(ACTION_LABELS, log.action)}</strong> ·{' '}
                <span>{log.operatorName || EMPTY}</span>({labelFrom(ROLE_LABELS, log.operatorRole)}
                )
              </div>
              <div className="approval-detail-chaincard__meta">
                <span>{formatDateTime(log.operateTime)}</span>
                <span>
                  {statusLabel(log.preStatus)} → {statusLabel(log.postStatus)}
                </span>
                {log.operateIp && <span>IP:{log.operateIp}</span>}
              </div>
              {log.reason && <p className="approval-detail-chaincard__reason">{log.reason}</p>}
            </div>
          </article>
        );
      })}
      {pending && (
        <>
          <article className="approval-detail-chaincard" aria-label="当前审批节点">
            <span
              className="approval-detail-chaincard__icon approval-detail-chaincard__icon--current"
              aria-hidden="true"
            >
              {level}
            </span>
            <div className="approval-detail-chaincard__content">
              <div className="approval-detail-chaincard__title">
                {roles[level - 1]} ·{' '}
                {roles.length === 1 ? '唯一审批节点' : `第 ${level} 级审批节点`}(当前节点)
              </div>
              <div className="approval-detail-chaincard__meta">
                <span>待审批</span>
                {showHours && <span>已停留{pendingHours}小时</span>}
                <span>{futureCaption}</span>
              </div>
            </div>
          </article>
          {roles.slice(level).map((role, index) => (
            <article key={role} className="approval-detail-chaincard" aria-label="后续审批节点">
              <span
                className="approval-detail-chaincard__icon approval-detail-chaincard__icon--waiting"
                aria-hidden="true"
              >
                {level + index + 1}
              </span>
              <div className="approval-detail-chaincard__content">
                <div className="approval-detail-chaincard__title">
                  {role} · 第 {level + index + 1} 级审批节点(待流转)
                </div>
                <div className="approval-detail-chaincard__meta">待前序节点通过</div>
              </div>
            </article>
          ))}
          <article className="approval-detail-chaincard" aria-label="待生效节点">
            <span
              className="approval-detail-chaincard__icon approval-detail-chaincard__icon--waiting"
              aria-hidden="true"
            >
              <CheckOutlined />
            </span>
            <div className="approval-detail-chaincard__content">
              <div className="approval-detail-chaincard__title">生效 · 写入门店列表</div>
              <div className="approval-detail-chaincard__meta">{futureCaption}</div>
            </div>
          </article>
        </>
      )}
      {approved && (
        <article className="approval-detail-chaincard" aria-label="已生效节点">
          <span
            className="approval-detail-chaincard__icon approval-detail-chaincard__icon--done"
            aria-hidden="true"
          >
            <CheckOutlined />
          </span>
          <div className="approval-detail-chaincard__content">
            <div className="approval-detail-chaincard__title">生效 · 已写入门店列表</div>
            <div className="approval-detail-chaincard__meta">
              生效时间:{timeToMinute(detail.effectiveTime ?? detail.approveTime)}
            </div>
          </div>
        </article>
      )}
    </section>
  );
}