WithdrawList.tsx 19.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { DownOutlined } from '@ant-design/icons';
import { UAlert, UButton, UCard, UDropdown, UResult, useUMessage } from '@uj/ui';
import {
  ConfirmModal,
  DataTable,
  SearchForm,
  type DataTableRowSelection,
  type RowActionSchema,
} from '@/components';
import { withdrawApi, type WithdrawRow } from '@/api';
import { PP } from '@/permissions/codes';
import { usePointsAccess } from '@/features/shared/access';
import { centsToYuan } from '@/features/shared/format';
import {
  entityOptions,
  useChannelTree,
  useTagTree,
  useWithdrawMerchants,
  useBrands,
  useProvinces,
} from '@/features/shared/options';
import {
  firstPage,
  useActionMessage,
  useExport,
  useList,
  usePageClamp,
  useRefresh,
} from '@/features/shared/queries';
import { buildTransferFields, toTransferParams } from './tools/fields';
import {
  REJECTABLE,
  STATUS_REQUIREMENT,
  wrongStatusRows,
  type BatchAction,
} from './tools/status-rules';
import { buildTransferColumns } from './tools/columns';
import { SettleAmountDialog, SettleAmountStrip } from './components/SettleAmountPanel';
import { AuditDialog, type AuditKind } from './components/AuditDialog';
import { PayDialog } from './components/PayDialog';
import { ImportDialog } from './components/ImportDialog';
import { IdCardDialog } from './components/IdCardDialog';
import { AgreementDialog } from './components/AgreementDialog';
import { BatchTagDialog } from './components/BatchTagDialog';
import { CustomTagDrawer } from './components/CustomTagDrawer';
import { TransferDetailDialog } from './components/TransferDetailDialog';

const SCOPE = ['points', 'transfers'] as const;

/** 下拉触发按钮的箭头:悬浮展开时向下→向上翻转,收起还原。 */
function menuArrowIcon(open: boolean) {
  return (
    <DownOutlined
      style={{ transform: open ? 'rotate(180deg)' : undefined, transition: 'transform 0.2s ease' }}
    />
  );
}

type AuditAsk = { kind: AuditKind; ids: string[] };
type PayAsk = {
  scope: 'batch' | 'all';
  ids: string[];
  payMoney: string;
  transferType?: string;
  mode?: string;
};
type BatchAsk = { all: boolean; text: string };

/**
 * 提现列表:筛选 + 累计结算金额 + 一张 31 列的宽表,外加老系统那七组动作。
 *
 * 动作分三类,与老系统一一对应:
 *  按勾选(批量审核/付款/驳回/生成批次)、按查询条件(一键审核/一键付款)、逐行(审核/驳回/付款/查看);
 *  「全部生成批次」不带条件,处理的是后端那批未处理记录。
 */
export default function WithdrawList() {
  const { can } = usePointsAccess();
  const message = useUMessage();
  const allowed = can(PP.WITHDRAW_VIEW);
  const notices = useActionMessage();
  const [filters, setFilters] = useState<Record<string, unknown>>({});
  const [page, setPage] = useState(firstPage);
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [selectedRows, setSelectedRows] = useState<WithdrawRow[]>([]);
  const [audit, setAudit] = useState<AuditAsk>();
  const [pay, setPay] = useState<PayAsk>();
  const [pendingPay, setPendingPay] = useState<PayAsk>();
  // 两个下拉的展开态只用于箭头翻转指示。
  const [batchMenuOpen, setBatchMenuOpen] = useState(false);
  const [allMenuOpen, setAllMenuOpen] = useState(false);
  const [batch, setBatch] = useState<BatchAsk>();
  const [detailId, setDetailId] = useState<string>();
  const [idCardRow, setIdCardRow] = useState<WithdrawRow>();
  const [agreement, setAgreement] = useState('');
  const [tagging, setTagging] = useState(false);
  const [tagDrawer, setTagDrawer] = useState(false);
  const [importing, setImporting] = useState(false);
  const [moreAmounts, setMoreAmounts] = useState(false);

  const channels = useChannelTree(allowed);
  const merchants = useWithdrawMerchants(allowed);
  const brands = useBrands(allowed);
  const provinces = useProvinces(allowed);
  const tags = useTagTree(allowed);
  const refresh = useRefresh([...SCOPE]);
  const list = useList<WithdrawRow>({
    scope: [...SCOPE],
    filters,
    page,
    fetcher: withdrawApi.pageTransfers,
    enabled: allowed,
  });
  usePageClamp(list.total, page, setPage);
  const amounts = useQuery({
    queryKey: ['points', 'settle-amount', filters],
    queryFn: () => withdrawApi.settleAmount(filters),
    enabled: allowed,
  });
  const exportAction = useExport(withdrawApi.exportTransfers);

  const fields = useMemo(
    () =>
      buildTransferFields({
        channels: channels.options,
        entities: entityOptions(
          channels.nodes,
          filters.channel === undefined ? undefined : String(filters.channel),
        ),
        merchants: merchants.options,
        brands: brands.options,
        provinces: provinces.options,
        tags: tags.paths,
      }),
    [
      brands.options,
      channels.nodes,
      channels.options,
      filters.channel,
      merchants.options,
      provinces.options,
      tags.paths,
    ],
  );

  const columns = useMemo(
    () =>
      buildTransferColumns(channels.nodes, {
        onIdCard: (row) => setIdCardRow(row),
        onAgreement: (url) => setAgreement(url),
      }),
    [channels.nodes],
  );

  /** 勾选与批量动作在老系统里同一段代码两用,这里也保持「一个入口、两种范围」。 */
  const clearSelection = () => {
    setSelectedIds([]);
    setSelectedRows([]);
  };
  const done = async () => {
    clearSelection();
    await refresh();
    void amounts.refetch();
  };

  /** 后端只回「这批能不能审 / 能不能付」;为 false 就是所选记录状态不对,老系统在这里直接拦住。 */
  const checkAmount = async (index: 0 | 1, scope: 'batch' | 'all'): Promise<string | undefined> => {
    const action: BatchAction = index === 0 ? 'approve' : 'pay';
    const key = index === 0 ? 'canApprove' : 'canPay';
    const rejectText = `请选择${STATUS_REQUIREMENT[action]}的提现记录`;
    if (scope === 'batch' && !selectedIds.length) {
      message.error(rejectText);
      return;
    }
    const params =
      scope === 'batch' ? { ids: selectedIds, [key]: false } : { ...filters, [key]: false };
    const result =
      scope === 'batch'
        ? await withdrawApi.sumPayAmount(params)
        : await withdrawApi.sumAllPayAmount(params);
    if (!result?.[key]) {
      // 勾选的行就在本地列表里,能点名就点名;一键(按查询条件)没有行数据,只能给老文案。
      const bad = scope === 'batch' ? wrongStatusRows(action, selectedRows) : '';
      message.error(bad ? `${bad} 不是${STATUS_REQUIREMENT[action]}状态` : rejectText);
      return;
    }
    return centsToYuan(result.payAmount);
  };

  /** 付款前确认所选记录同一种提现类型(渠道候选按类型与方式取)。 */
  const openPay = async (scope: 'batch' | 'all', payMoney: string) => {
    const ids = scope === 'batch' ? selectedIds : [];
    try {
      const checked = await withdrawApi.checkTransferType(
        scope === 'batch' ? { ids } : { ...filters },
      );
      const ask: PayAsk = {
        scope,
        ids,
        payMoney,
        transferType:
          checked?.transferType === undefined ? undefined : String(checked.transferType),
        mode: checked?.mode === undefined ? undefined : String(checked.mode),
      };
      // 一键付款按查询条件校验限制门店,批量与逐行看勾选出来的数据。
      const limited =
        scope === 'batch'
          ? selectedRows.some((row) => row.limitStoreFlag === 'Y')
          : Boolean(await withdrawApi.checkAllPayLimitStore(filters));
      if (limited) setPendingPay(ask);
      else setPay(ask);
    } catch (error) {
      notices.fail(error);
    }
  };

  const rowPay = (row: WithdrawRow) => {
    const ask: PayAsk = {
      scope: 'batch',
      ids: [row.id],
      payMoney: centsToYuan(row.payAmount, '0.00'),
      transferType: row.transferType === undefined ? undefined : String(row.transferType),
      mode: row.mode === undefined ? undefined : String(row.mode),
    };
    if (row.limitStoreFlag === 'Y') setPendingPay(ask);
    else setPay(ask);
  };

  /** 批量与一键两个下拉共用一张表:0 审核、1 付款、2 驳回、3 生成批次(一键只有前两项)。 */
  const runAction = async (index: 0 | 1 | 2 | 3, scope: 'batch' | 'all') => {
    try {
      if (index === 0) {
        if (scope === 'batch') {
          if (!selectedIds.length) {
            message.error(`请选择${STATUS_REQUIREMENT.approve}的提现记录`);
            return;
          }
          if (await checkAmount(0, 'batch')) setAudit({ kind: 'approve', ids: selectedIds });
        } else if (await checkAmount(0, 'all')) {
          setAudit({ kind: 'allApprove', ids: [] });
        }
        return;
      }
      if (index === 1) {
        const payMoney = await checkAmount(1, scope);
        if (payMoney !== undefined) await openPay(scope, payMoney);
        return;
      }
      if (index === 2) {
        if (!selectedIds.length) {
          message.error('请选择需要批量驳回的【积分提现】记录');
          return;
        }
        const badReject = wrongStatusRows('reject', selectedRows);
        if (badReject) {
          message.error(`${badReject} 不是${STATUS_REQUIREMENT.reject}状态`);
          return;
        }
        setAudit({ kind: 'batchReject', ids: selectedIds });
        return;
      }
      if (!selectedIds.length) {
        message.error('请选择需要生成批次的【积分提现】记录');
        return;
      }
      await askBatch(false);
    } catch (error) {
      notices.fail(error);
    }
  };

  /** 生成批次弹窗的文案来自统计接口:全部与批量两套说法照抄老系统。 */
  const askBatch = async (all: boolean) => {
    if (!all && !selectedIds.length) {
      message.error('请选择需要生成批次的【积分提现】记录');
      return;
    }
    const count = await withdrawApi.generateBatchCount(
      all ? { type: 2 } : { type: 1, ids: selectedIds },
    );
    const total = count?.numberOfRecord ?? 0;
    const money = count?.paymentTotal ?? 0;
    setBatch({
      all,
      text: all
        ? `当前共 ${total}条未处理【积分提现】记录,付款金额共 ${money}元,是否确认生成批次?`
        : `将对您选择的 ${total} 条【积分提现】记录生成批次,付款金额共 ${money} 元。`,
    });
  };

  const runBatch = async () => {
    try {
      await withdrawApi.generateBatch(batch?.all ? { type: 2 } : { type: 1, ids: selectedIds });
      notices.success();
      setBatch(undefined);
      await done();
    } catch (error) {
      notices.fail(error);
    }
  };

  if (!allowed) {
    return (
      <UResult status="403" title="无积分提现访问权限" subTitle="请联系管理员确认账号权限。" />
    );
  }

  const rowActions: RowActionSchema<WithdrawRow>[] = [
    {
      label: '查看',
      onClick: (row) => setDetailId(row.id),
    },
    {
      label: '审核',
      // 权限走适配层的三态闸门,因此不用 RowActionSchema.permission(那条路要求后端已下发 points:*)。
      visible: (row) =>
        can(PP.WITHDRAW_APPROVE) && Number(row.status) === 0 && Number(row.transferType) !== 0,
      onClick: (row) => setAudit({ kind: 'approve', ids: [row.id] }),
    },
    {
      label: '驳回',
      danger: true,
      visible: (row) => can(PP.WITHDRAW_REJECT) && REJECTABLE.has(String(row.status ?? '')),
      onClick: (row) => setAudit({ kind: 'reject', ids: [row.id] }),
    },
    {
      label: '付款',
      visible: (row) =>
        can(PP.WITHDRAW_PAY) &&
        (Number(row.status) === 1 || Number(row.status) === 6) &&
        Number(row.transferType) !== 0,
      onClick: (row) => rowPay(row),
    },
  ];

  const selection: DataTableRowSelection<WithdrawRow> = {
    selectedRowKeys: selectedIds,
    disabled: list.query.isFetching,
    // 后端 id 实际是 number(老系统自增主键),但本页把它当 string 用:
    // 这里绝不能 keys.map(String) —— 那样 selectedRowKeys 会变成字符串、而 antd 用行 id(number)
    // 比对,'123' === 123 永假,复选框就永远勾不上。统一交给 rowKey 返回 String(id) 来归一,
    // 这里原样存 antd 给的 key 即可(它已基于 rowKey 的值,即 string 化后的 id)。
    onChange: (keys, rows) => {
      setSelectedIds(keys as string[]);
      setSelectedRows(rows);
    },
  };

  return (
    <>
      <UCard className="uj-filter-card" size="small">
        <SearchForm
          fields={fields}
          initialValues={{
            outSettleOrderId: '',
            customerName: '',
            customerPhone: '',
            name: '',
            status: '',
            channel: '',
            paymentEntityCode: '',
            transferType: '',
            mode: '',
            withdrawalSource: '',
            realityMerchantName: '',
            limitStoreFlagQuery: '',
            transferOutTagIdQuery: '',
            pointsPeriodType: '',
          }}
          onSearch={(values) => {
            setFilters(toTransferParams(values));
            setPage(firstPage);
            clearSelection();
          }}
          onReset={() => {
            setFilters({});
            setPage(firstPage);
            clearSelection();
          }}
        />
      </UCard>
      <SettleAmountStrip
        amounts={amounts.data}
        error={amounts.isError ? amounts.error : undefined}
        onRetry={() => void amounts.refetch()}
        onOpenAll={() => setMoreAmounts(true)}
      />
      {list.query.isError ? (
        <UAlert
          type="error"
          showIcon
          title="提现记录加载失败"
          description={list.error}
          action={
            <UButton type="link" onClick={() => void list.query.refetch()}>
              重试
            </UButton>
          }
        />
      ) : null}
      <UCard size="small" fill>
        <div className="uj-table-toolbar">
          <div className="uj-table-toolbar__title">共 {list.total} 条提现记录</div>
          <div className="uj-table-toolbar__actions">
            {can(PP.WITHDRAW_BATCH) ? (
              <UButton onClick={() => void askBatch(true)}>全部生成批次</UButton>
            ) : null}
            {can([PP.WITHDRAW_APPROVE, PP.WITHDRAW_PAY, PP.WITHDRAW_REJECT, PP.WITHDRAW_BATCH]) ? (
              <UDropdown
                open={batchMenuOpen}
                onOpenChange={setBatchMenuOpen}
                menu={{
                  items: [
                    { key: '0', label: '批量审核' },
                    { key: '1', label: '批量付款' },
                    { key: '2', label: '批量驳回' },
                    { key: '3', label: '批量生成批次' },
                  ],
                  onClick: ({ key }) => void runAction(Number(key) as 0 | 1 | 2 | 3, 'batch'),
                }}
              >
                <UButton icon={menuArrowIcon(batchMenuOpen)} iconPlacement="end">
                  批量操作
                </UButton>
              </UDropdown>
            ) : null}
            {can([PP.WITHDRAW_APPROVE, PP.WITHDRAW_PAY]) ? (
              <UDropdown
                open={allMenuOpen}
                onOpenChange={setAllMenuOpen}
                menu={{
                  items: [
                    { key: '0', label: '一键审核' },
                    { key: '1', label: '一键付款' },
                  ],
                  onClick: ({ key }) => void runAction(Number(key) as 0 | 1, 'all'),
                }}
              >
                <UButton icon={menuArrowIcon(allMenuOpen)} iconPlacement="end">
                  一键操作
                </UButton>
              </UDropdown>
            ) : null}
            {can(PP.WITHDRAW_TAG) ? (
              <UButton
                onClick={() => {
                  if (!selectedIds.length) {
                    message.warning('请选择要标签的明细');
                    return;
                  }
                  setTagging(true);
                }}
              >
                标签标注
              </UButton>
            ) : null}
            {can(PP.WITHDRAW_TAG) ? (
              <UButton onClick={() => setTagDrawer(true)}>自定义标签</UButton>
            ) : null}
            {can(PP.WITHDRAW_IMPORT) ? (
              <UButton onClick={() => setImporting(true)}>提现导入</UButton>
            ) : null}
            {can(PP.WITHDRAW_EXPORT) ? (
              <UButton
                loading={exportAction.isPending}
                onClick={() => exportAction.mutate({ ...filters })}
              >
                导出
              </UButton>
            ) : null}
          </div>
        </div>
        <DataTable<WithdrawRow>
          columns={columns}
          // rowKey 归一为字符串:后端 id 实际是 number,统一 String(id) 后,选中键(也是基于 rowKey)
          // 与行 id 同为 string,selectedRowKeys 才能命中;同时提交给后端的 ids 保持 string 不变。
          rowKey={(row: WithdrawRow) => String(row.id)}
          rowSelection={selection}
          fillHeight
          actionColumnWidth={180}
          dataSource={list.records}
          loading={list.query.isPending || list.query.isFetching}
          rowActions={rowActions}
          pagination={{
            current: page.current,
            pageSize: page.size,
            total: list.total,
            showSizeChanger: true,
            pageSizeOptions: [10, 20, 50, 100],
            showTotal: (total) => `共 ${total} 条`,
            onChange: (current, size) =>
              setPage({ current: size === page.size ? current : 1, size }),
          }}
        />
      </UCard>

      <AuditDialog
        open={!!audit}
        kind={audit?.kind ?? 'approve'}
        ids={audit?.ids ?? []}
        filters={filters}
        onClose={() => setAudit(undefined)}
        onSuccess={() => {
          setAudit(undefined);
          void done();
        }}
      />
      <PayDialog
        open={!!pay}
        scope={pay?.scope ?? 'batch'}
        ids={pay?.ids ?? selectedIds}
        filters={filters}
        payMoney={pay?.payMoney ?? ''}
        transferType={pay?.transferType}
        mode={pay?.mode}
        onClose={() => setPay(undefined)}
        onSuccess={() => {
          setPay(undefined);
          void done();
        }}
      />
      <ConfirmModal
        open={!!pendingPay}
        title="二次确认"
        content="注意:所选数据中包含限制门店的订单,是否付款?"
        confirmLoading={false}
        onCancel={() => setPendingPay(undefined)}
        onConfirm={() => {
          setPay(pendingPay);
          setPendingPay(undefined);
        }}
      />
      <ConfirmModal
        open={!!batch}
        title={batch?.all ? '全部生成批次提示' : '生成批次提示'}
        content={batch?.text}
        onCancel={() => setBatch(undefined)}
        onConfirm={() => void runBatch()}
      />
      <TransferDetailDialog
        open={!!detailId}
        id={detailId}
        onClose={() => setDetailId(undefined)}
      />
      <IdCardDialog open={!!idCardRow} row={idCardRow} onClose={() => setIdCardRow(undefined)} />
      <AgreementDialog open={!!agreement} url={agreement} onClose={() => setAgreement('')} />
      <SettleAmountDialog
        open={moreAmounts}
        amounts={amounts.data}
        onClose={() => setMoreAmounts(false)}
      />
      <BatchTagDialog
        open={tagging}
        ids={selectedIds}
        onClose={() => setTagging(false)}
        onSuccess={() => {
          setTagging(false);
          void done();
        }}
      />
      <CustomTagDrawer
        open={tagDrawer}
        onClose={() => {
          setTagDrawer(false);
          void tags.refetch();
          setFilters({});
          setPage(firstPage);
        }}
      />
      <ImportDialog
        open={importing}
        onSuccess={() => void done()}
        onClose={() => setImporting(false)}
      />
    </>
  );
}