index.tsx 6.47 KB
import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { UAlert, UButton, UCard, UResult, UUpload, useUMessage } from '@uj/ui';
import { DataTable, SearchForm, type FieldSchema, type RowActionSchema } from '@/components';
import { pointsApi, type WriteOffOrder } from '@/api';
import { PP } from '@/permissions/codes';
import { usePointsAccess } from '@/features/shared/access';
import { SETTLE_STATUS, withAll } from '@/features/shared/dictionaries';
import { compactParams, errorMessage, expandDateRanges } from '@/features/shared/format';
import { isExcel, readLegacyFile, sizeError } from '@/features/shared/files';
import { firstPage, useExport, useList, usePageClamp, useRefresh } from '@/features/shared/queries';
import { PageShell } from '@/features/shared/PageShell';
import { goTo } from '@/features/shared/navigate';
import { useConfirmAction } from '@/features/shared/useConfirmAction';
import { buildOrderColumns } from './tools/columns';

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

/** 核销日期在表单里是一个区间,提交前展开成接口的起止两个字段(老 getParams 的等价物)。 */
const DATE_RANGES = [
  { from: 'verificationTimeStr', start: 'verificationStartTime', end: 'verificationEndTime' },
];

const FIELDS: FieldSchema<Record<string, unknown>>[] = [
  {
    name: 'bizRelName',
    label: '项目名称',
    type: 'input',
    placeholder: '请输入项目名称',
    inputProps: { maxLength: 100 },
  },
  {
    name: 'merchantName',
    label: '商户名称',
    type: 'input',
    placeholder: '请输入商户名称',
    inputProps: { maxLength: 100 },
  },
  { name: 'settlementStatus', label: '结算状态', type: 'select', options: withAll(SETTLE_STATUS) },
  { name: 'verificationTimeStr', label: '核销日期', type: 'dateRange' },
];

export default function OrderList() {
  const { can } = usePointsAccess();
  const message = useUMessage();
  const allowed = can(PP.ORDER_VIEW);
  const [filters, setFilters] = useState<Record<string, unknown>>({});
  const [page, setPage] = useState(firstPage);
  const refresh = useRefresh([...SCOPE]);
  const list = useList<WriteOffOrder>({
    scope: [...SCOPE],
    filters,
    page,
    fetcher: pointsApi.pageOrders,
    enabled: allowed,
  });
  usePageClamp(list.total, page, setPage);
  const exportAction = useExport(pointsApi.exportOrders);
  const settle = useConfirmAction(refresh);
  const importAction = useMutation({
    mutationFn: async (file: File) => {
      const tooLarge = sizeError(file);
      if (tooLarge) throw new Error(tooLarge);
      if (!isExcel(file.name)) throw new Error('请选择 .xls 或 .xlsx 文件');
      const payload = await readLegacyFile(file);
      if (!payload) throw new Error('文件读取失败,请重新选择');
      return pointsApi.importSettlement(payload);
    },
    onSuccess: async () => {
      void message.success('导入成功,结算状态已更新');
      await refresh();
    },
    onError: (error) => void message.error(errorMessage(error)),
  });

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

  const columns = buildOrderColumns();
  const rowActions: RowActionSchema<WriteOffOrder>[] = [
    { label: '查看', onClick: (row) => goTo(`order/${row.id}`) },
    {
      label: (row) => (Number(row.settlementStatus) === 1 ? '取消结算' : '去结算'),
      visible: () => can(PP.ORDER_SETTLE),
      onClick: (row) =>
        settle.confirm({
          title: Number(row.settlementStatus) === 1 ? '取消结算' : '结算',
          content: `确定要${Number(row.settlementStatus) === 1 ? '取消结算' : '把该笔核销订单标记为已结算'}吗?`,
          run: () =>
            pointsApi.settle({
              id: row.id,
              settlementStatus: Number(row.settlementStatus) === 1 ? 0 : 1,
            }),
        }),
    },
  ];

  return (
    <PageShell
      fill
      title="积分核销订单"
      description="按项目与商户查询核销记录,逐笔结算或取消结算,也可用表格批量导入结算结果。"
      actions={
        <>
          {can(PP.ORDER_IMPORT) && (
            <UUpload
              accept=".xls,.xlsx"
              showUploadList={false}
              maxCount={1}
              disabled={importAction.isPending}
              beforeUpload={(file) => {
                importAction.mutate(file);
                return false;
              }}
            >
              <UButton loading={importAction.isPending}>批量结算导入</UButton>
            </UUpload>
          )}
          {can(PP.ORDER_EXPORT) && (
            <UButton
              loading={exportAction.isPending}
              onClick={() => exportAction.mutate({ ...filters })}
            >
              导出
            </UButton>
          )}
        </>
      }
    >
      <UCard className="uj-filter-card" size="small">
        <SearchForm
          fields={FIELDS}
          initialValues={{ bizRelName: '', merchantName: '', settlementStatus: '' }}
          onSearch={(values) => {
            setFilters(compactParams(expandDateRanges({ ...values }, DATE_RANGES)));
            setPage(firstPage);
          }}
          onReset={() => {
            setFilters({});
            setPage(firstPage);
          }}
        />
      </UCard>
      {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>
        <DataTable<WriteOffOrder>
          columns={columns}
          rowKey="id"
          fillHeight
          actionColumnWidth={150}
          dataSource={list.records}
          loading={list.query.isPending || list.query.isFetching}
          rowActions={rowActions}
          toolbarTitle={`共 ${list.total} 条核销记录`}
          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>
      {settle.modal}
    </PageShell>
  );
}