采购单优化

This commit is contained in:
liu
2026-08-12 17:10:05 +08:00
parent dadfdc1511
commit ef0d394f4f
8 changed files with 359 additions and 155 deletions
+192 -116
View File
@@ -1,17 +1,20 @@
import React, { useRef, useState } from 'react';
import React, { useEffect, useRef, useState } from 'react';
import {
Button,
Descriptions,
Drawer,
Dropdown,
Form,
Input,
InputNumber,
message,
Modal,
Popconfirm,
Select,
Table,
Tag,
Typography,
} from 'antd';
import { CheckOutlined, DownloadOutlined } from '@ant-design/icons';
import { CheckOutlined, EditOutlined } from '@ant-design/icons';
import type { TableProps } from 'antd';
import XinTable from '@/components/XinTable';
import type {
@@ -26,21 +29,31 @@ import type {
} from '@/domain/iPurchaseOrder.ts';
import { PURCHASE_STATUS_MAP } from '@/domain/iPurchaseOrder.ts';
import {
exportPurchase,
getPurchaseDetail,
updatePurchaseRow,
} from '@/api/purchase/order.ts';
import { Update } from '@/api/common/table.ts';
import { getSupplierOptions } from '@/api/customer/supplier.ts';
import type ISupplier from '@/domain/iSupplier.ts';
import AuthButton from '@/components/AuthButton';
const { Title, Text } = Typography;
/** 行草稿:成本/称重 + 各门店单元格数量 */
interface RowDraft {
cost_price?: number;
weight?: number;
cells: Record<number, number>;
/** 行修改表单:品名/供应商/包规/单位/成本 */
interface RowEditForm {
product_name: string;
supplier_id?: number;
product_spec: string;
unit: string;
cost_price: number;
}
/** 单价 = 成本 / 包规数值(包规解析不出正数时按 1 处理,与后端同口径) */
const calcUnitCost = (cost: number, spec: string): number => {
const pack = parseFloat(spec);
return Number.isFinite(pack) && pack > 0 ? cost / pack : cost;
};
/**
* 采购单管理(C1 在门店订单页合并生成 / C2-C3 导出 / C4 明细矩阵修改)
* 采购单无独立明细表,明细直接溯源门店订货明细:商品行 × 门店列
@@ -52,16 +65,24 @@ const PurchaseOrderPage: React.FC = () => {
const [detailOpen, setDetailOpen] = useState(false);
const [detail, setDetail] = useState<IPurchaseDetail | null>(null);
const [detailLoading, setDetailLoading] = useState(false);
const [drafts, setDrafts] = useState<Record<number, RowDraft>>({});
const [savingProductId, setSavingProductId] = useState<number | null>(null);
const [completing, setCompleting] = useState(false);
// 行修改弹窗
const [editingRow, setEditingRow] = useState<IPurchaseDetailRow | null>(null);
const [rowSaving, setRowSaving] = useState(false);
const [syncTarget, setSyncTarget] = useState<'purchase' | 'product'>('purchase');
const [editForm] = Form.useForm<RowEditForm>();
const [suppliers, setSuppliers] = useState<ISupplier[]>([]);
useEffect(() => {
getSupplierOptions().then((res) => setSuppliers(res.data.data ?? []));
}, []);
const loadDetail = async (id: number) => {
setDetailLoading(true);
try {
const res = await getPurchaseDetail(id);
setDetail(res.data.data ?? null);
setDrafts({});
} finally {
setDetailLoading(false);
}
@@ -72,65 +93,39 @@ const PurchaseOrderPage: React.FC = () => {
await loadDetail(id);
};
const getDraft = (productId: number): RowDraft => drafts[productId] ?? { cells: {} };
const patchDraft = (productId: number, patch: Partial<RowDraft>) => {
setDrafts((prev) => {
const current = prev[productId] ?? { cells: {} };
return {
...prev,
[productId]: { ...current, ...patch, cells: { ...current.cells, ...patch.cells } },
};
const openEdit = (row: IPurchaseDetailRow) => {
setEditingRow(row);
editForm.setFieldsValue({
product_name: row.product_name,
supplier_id: row.supplier_id > 0 ? row.supplier_id : undefined,
product_spec: row.product_spec,
unit: row.unit,
cost_price: Number(row.cost_price),
});
};
/** 草稿成本(未修改取原值) */
const draftCost = (row: IPurchaseDetailRow): number =>
getDraft(row.product_id).cost_price ?? row.cost_price;
const isRowDirty = (row: IPurchaseDetailRow): boolean => {
// const draft = getDraft(row.product_id);
// if (draft.cost_price !== undefined && draft.cost_price !== row.cost_price) {
// return true;
// }
// if (draft.weight !== undefined && draft.weight !== row.weight) {
// return true;
// }
// return row.cells.some(
// (cell) => draft.cells[cell.order_item_id] !== undefined
// && draft.cells[cell.order_item_id] !== cell.quantity,
// );
};
/** 保存一行:先落各门店单元格数量,再落行级成本/称重,最后刷新 */
const saveRow = async (row: IPurchaseDetailRow) => {
if (!detail || !isRowDirty(row)) {
/** 提交行修改:同步该商品全部订货明细;syncTarget=product 时追加同步商品档案 */
const handleEditSave = async (values: RowEditForm) => {
if (!detail || !editingRow) {
return;
}
const draft = getDraft(row.product_id);
setSavingProductId(row.product_id);
setRowSaving(true);
try {
// for (const cell of row.cells) {
// const qty = draft.cells[cell.order_item_id];
// if (qty !== undefined && qty !== cell.quantity) {
// await updatePurchaseCell(cell.order_item_id, { quantity: qty });
// }
// }
// const rowPatch: { cost_price?: number; weight?: number } = {};
// if (draft.cost_price !== undefined && draft.cost_price !== row.cost_price) {
// rowPatch.cost_price = draft.cost_price;
// }
// if (draft.weight !== undefined && draft.weight !== row.weight) {
// rowPatch.weight = draft.weight;
// }
// if (Object.keys(rowPatch).length > 0) {
// await updatePurchaseRow(detail.purchase.id!, row.product_id, rowPatch);
// }
message.success('已保存并同步订货明细');
const res = await updatePurchaseRow(detail.purchase.id!, editingRow.product_id, {
...values,
supplier_id: values.supplier_id ?? 0,
sync_product: syncTarget === 'product',
});
message.success(
syncTarget === 'product'
? `已同步 ${res.data.data?.count ?? 0} 条订货明细,并更新商品档案`
: `已同步 ${res.data.data?.count ?? 0} 条订货明细`,
);
setEditingRow(null);
await loadDetail(detail.purchase.id!);
await tableRef.current?.reload();
} finally {
setSavingProductId(null);
setRowSaving(false);
}
};
@@ -149,7 +144,7 @@ const PurchaseOrderPage: React.FC = () => {
}
};
/** 明细矩阵列:品名/供应商/包规/单位/成本/单价 + 每门店一(数量/金额+ 合计 + 操作 */
/** 明细矩阵列:品名/供应商/单价/包规/单位/成本 + 每门店一(数量)+ 合计 + 操作 */
const buildItemColumns = (): TableProps<IPurchaseDetailRow>['columns'] => {
const fixed: NonNullable<TableProps<IPurchaseDetailRow>['columns']> = [
{ title: '品名', dataIndex: 'product_name', width: 120, align: 'center' },
@@ -163,27 +158,23 @@ const PurchaseOrderPage: React.FC = () => {
{
title: '单价',
key: 'unit_cost',
width: 80,
width: 90,
align: 'center',
render: (_, row) => `¥${(Number(row.cost_price) / Number(row.product_spec)).toFixed(2)}`,
render: (_, row) => `¥${calcUnitCost(Number(row.cost_price), row.product_spec ?? '').toFixed(2)}`,
},
{ title: '包规', dataIndex: 'product_spec', align: 'center', width: 90, render: (v) => v || '-' },
{ title: '单位', dataIndex: 'unit', width: 70, align: 'center', render: (v) => v || '-' },
{ title: '成本', dataIndex: 'cost_price', width: 110, align: 'center', render: (v) => v || '-' }
{ title: '成本', dataIndex: 'cost_price', width: 90, align: 'center', render: (v) => `¥${Number(v).toFixed(2)}` },
];
const storeColumns = (detail?.stores ?? []).map((store) => ({
title: store.name,
title: <span className={'text-[red]'}>{store.name}</span>,
key: `store-${store.id}`,
width: 100,
align: 'center' as const,
render: (_: unknown, row: IPurchaseDetailRow) => {
const cell = row.cells[store.id];
if (!cell) {
return <Text type="secondary">-</Text>;
}
return (
<Text>{ row.cells[store.id] }</Text>
);
const quantity = row.cells[store.id];
return quantity !== undefined ? <Text>{quantity}</Text> : <Text type="secondary">-</Text>;
},
}));
@@ -193,21 +184,21 @@ const PurchaseOrderPage: React.FC = () => {
key: 'total_quantity',
width: 90,
align: 'center',
render: (_, row) => Object.values(row.cells).reduce((a, b) => a + b, 0),
render: (_, row) => <Text strong>{row.quantity}</Text>,
},
{
title: '操作',
key: 'action',
width: 80,
width: 90,
fixed: 'right',
align: 'center',
render: (_, row) => (
<AuthButton auth="purchase.order.update">
<Button
size="small"
type="link"
disabled={!isRowDirty(row)}
loading={savingProductId === row.product_id}
onClick={() => saveRow(row)}
icon={<EditOutlined />}
onClick={() => openEdit(row)}
>
</Button>
@@ -219,6 +210,39 @@ const PurchaseOrderPage: React.FC = () => {
return [...fixed, ...storeColumns, ...tail];
};
/** 底部统计行:按门店统计金额(Σ 门店数量 × 行单价)+ 合计 */
const renderSummary = () => {
const stores = detail?.stores ?? [];
const items = detail?.items ?? [];
const storeTotals = stores.map((store) =>
items.reduce(
(sum, row) => sum + (row.cells[store.id] ?? 0) * Number(row.cost_price),
0,
),
);
const totalQuantity = items.reduce((sum, row) => sum + Number(row.quantity), 0);
const totalAmount = storeTotals.reduce((sum, amount) => sum + amount, 0);
return (
<Table.Summary.Row>
<Table.Summary.Cell index={0} colSpan={6} align="center">
<Text strong></Text>
</Table.Summary.Cell>
{storeTotals.map((amount, index) => (
<Table.Summary.Cell key={stores[index].id} index={6 + index} align="center">
<Text strong>¥{amount.toFixed(2)}</Text>
</Table.Summary.Cell>
))}
<Table.Summary.Cell index={6 + stores.length} align="center">
<Text strong>{totalQuantity}</Text>
</Table.Summary.Cell>
<Table.Summary.Cell index={7 + stores.length} align="center">
<Text strong>¥{totalAmount.toFixed(2)}</Text>
</Table.Summary.Cell>
</Table.Summary.Row>
);
};
const columns: XinTableColumn<IPurchaseOrder>[] = [
{
title: '采购单号',
@@ -286,21 +310,7 @@ const PurchaseOrderPage: React.FC = () => {
const operateRender: XinTableProps<IPurchaseOrder>['operateRender'] = (record) => [
<Button key="detail" size="small" onClick={() => openDetail(record.id!)}>
</Button>,
<AuthButton key="export" auth="purchase.order.export">
<Dropdown
menu={{
items: [
{ key: 'all-xlsx', label: '全品类 Excel', onClick: () => exportPurchase(record.id!, 'all', 'xlsx') },
{ key: 'all-pdf', label: '全品类 PDF', onClick: () => exportPurchase(record.id!, 'all', 'pdf') },
{ key: 'category-xlsx', label: '蔬果分类 Excel', onClick: () => exportPurchase(record.id!, 'category', 'xlsx') },
{ key: 'category-pdf', label: '蔬果分类 PDF', onClick: () => exportPurchase(record.id!, 'category', 'pdf') },
],
}}
>
<Button size="small" icon={<DownloadOutlined />} />
</Dropdown>
</AuthButton>,
</Button>
];
const tableProps: XinTableProps<IPurchaseOrder> = {
@@ -318,7 +328,7 @@ const PurchaseOrderPage: React.FC = () => {
<div className="mb-5">
<Title level={3}></Title>
<Text type="secondary">
× //
</Text>
</div>
<XinTable<IPurchaseOrder> {...tableProps} />
@@ -330,25 +340,22 @@ const PurchaseOrderPage: React.FC = () => {
onClose={() => setDetailOpen(false)}
size={1200}
loading={detailLoading}
extra={detail?.purchase.status === 0 && (
<AuthButton auth="purchase.order.update">
<Popconfirm title="确认标记该采购单为已完成?" onConfirm={handleComplete}>
<Button size="small" icon={<CheckOutlined />} loading={completing}>
</Button>
</Popconfirm>
</AuthButton>
)}
>
{detail ? (
{detail && (
<>
<Descriptions
column={3}
size="small"
bordered
extra={
detail.purchase.status === 0 ? (
<AuthButton auth="purchase.order.update">
<Popconfirm title="确认标记该采购单为已完成?" onConfirm={handleComplete}>
<Button size="small" icon={<CheckOutlined />} loading={completing}>
</Button>
</Popconfirm>
</AuthButton>
) : undefined
}
>
<Title level={5} className="mt-5! mb-3!">
</Title>
<Descriptions column={3} size="small" bordered>
<Descriptions.Item label="采购日期">{detail.purchase.purchase_date}</Descriptions.Item>
<Descriptions.Item label="状态">
<Tag color={PURCHASE_STATUS_MAP[detail.purchase.status ?? 0]?.color}>
@@ -363,9 +370,9 @@ const PurchaseOrderPage: React.FC = () => {
<Descriptions.Item label="总重量">{detail.purchase.total_weight}</Descriptions.Item>
</Descriptions>
<div className="my-2 text-gray-500">
= ÷ = × &gt;0 ×
</div>
<Title level={5} className="mt-5! mb-3!">
</Title>
<Table<IPurchaseDetailRow>
rowKey="product_id"
size="small"
@@ -374,10 +381,79 @@ const PurchaseOrderPage: React.FC = () => {
dataSource={detail.items}
pagination={false}
scroll={{ x: 'max-content' }}
summary={renderSummary}
/>
</>
) : null}
)}
</Drawer>
{/* 行修改:品名/供应商/包规/单位/成本,同步采购单明细 / 追加同步商品档案 */}
<Modal
title={editingRow ? `修改「${editingRow.product_name}` : '修改明细行'}
open={editingRow !== null}
onCancel={() => setEditingRow(null)}
destroyOnHidden
footer={[
<Button key="cancel" onClick={() => setEditingRow(null)}>
</Button>,
<Button
key="product"
loading={rowSaving && syncTarget === 'product'}
onClick={() => {
setSyncTarget('product');
editForm.submit();
}}
>
</Button>,
<Button
key="purchase"
type="primary"
loading={rowSaving && syncTarget === 'purchase'}
onClick={() => {
setSyncTarget('purchase');
editForm.submit();
}}
>
</Button>,
]}
>
<div className="py-2 text-gray-500">
</div>
<Form form={editForm} layout="vertical" onFinish={handleEditSave}>
<Form.Item
label="品名"
name="product_name"
rules={[{ required: true, message: '请输入品名' }, { max: 100 }]}
>
<Input maxLength={100} />
</Form.Item>
<Form.Item label="供应商" name="supplier_id">
<Select
allowClear
showSearch={{ optionFilterProp: 'label' }}
placeholder="选择供应商"
options={suppliers.map((s) => ({ value: s.id, label: s.name }))}
/>
</Form.Item>
<Form.Item label="包规" name="product_spec" rules={[{ max: 100 }]}>
<Input maxLength={100} placeholder="如:10斤/箱" />
</Form.Item>
<Form.Item label="单位" name="unit" rules={[{ max: 20 }]}>
<Input maxLength={20} placeholder="如:斤" />
</Form.Item>
<Form.Item
label="成本"
name="cost_price"
rules={[{ required: true, message: '请输入成本' }]}
>
<InputNumber min={0} precision={2} prefix="¥" className="w-full" />
</Form.Item>
</Form>
</Modal>
</>
);
};