!181 feat(@vben/web-antd): erp-优化采购订单功能

Merge pull request !181 from 陈賝/dev
pull/183/MERGE
xingyu 2025-07-28 10:04:42 +00:00 committed by Gitee
commit 0694eb2b29
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
6 changed files with 1309 additions and 32 deletions

View File

@ -3,25 +3,64 @@ import type { PageParam, PageResult } from '@vben/request';
import { requestClient } from '#/api/request';
export namespace ErpPurchaseOrderApi {
/** ERP 采购订单项信息 */
export interface PurchaseOrderItem {
id?: number; // 订单项编号
orderId?: number; // 采购订单编号
productId?: number; // 产品编号
productName?: string; // 产品名称
productBarCode?: string; // 产品条码
productUnitId?: number; // 产品单位编号
productUnitName?: string; // 产品单位名称
productPrice?: number; // 产品单价,单位:元
totalProductPrice?: number; // 产品总价,单位:元
count?: number; // 数量
totalPrice?: number; // 总价,单位:元
taxPercent?: number; // 税率,百分比
taxPrice?: number; // 税额,单位:元
totalTaxPrice?: number; // 含税总价,单位:元
remark?: string; // 备注
stockCount?: number; // 库存数量(显示字段)
}
/** ERP 采购订单信息 */
export interface PurchaseOrder {
id?: number; // 订单工单编号
no: string; // 采购订单号
supplierId: number; // 供应商编号
orderTime: Date; // 订单时间
totalCount: number; // 合计数量
totalPrice: number; // 合计金额,单位:元
status: number; // 状态
remark: string; // 备注
inCount: number; // 采购入库数量
returnCount: number; // 采购退货数量
no?: string; // 采购订单号
supplierId?: number; // 供应商编号
supplierName?: string; // 供应商名称
orderTime?: Date | string; // 订单时间
totalCount?: number; // 合计数量
totalPrice?: number; // 合计金额,单位:元
totalProductPrice?: number; // 产品金额,单位:元
discountPercent?: number; // 优惠率,百分比
discountPrice?: number; // 优惠金额,单位:元
depositPrice?: number; // 定金金额,单位:元
accountId?: number; // 结算账户编号
status?: number; // 状态
remark?: string; // 备注
fileUrl?: string; // 附件地址
inCount?: number; // 采购入库数量
returnCount?: number; // 采购退货数量
inStatus?: number; // 入库状态
returnStatus?: number; // 退货状态
productNames?: string; // 产品名称列表
creatorName?: string; // 创建人名称
createTime?: Date; // 创建时间
items?: PurchaseOrderItem[]; // 订单项列表
}
/** 采购订单分页查询参数 */
export interface PurchaseOrderPageParam extends PageParam {
no?: string;
supplierId?: number;
productId?: number;
orderTime?: string[];
status?: number;
remark?: string;
creator?: string;
inStatus?: number;
returnStatus?: number;
}
}
@ -60,7 +99,12 @@ export function updatePurchaseOrderStatus(id: number, status: number) {
}
/** 删除采购订单 */
export function deletePurchaseOrder(ids: number[]) {
export function deletePurchaseOrder(id: number) {
return requestClient.delete(`/erp/purchase-order/delete?id=${id}`);
}
/** 批量删除采购订单 */
export function deletePurchaseOrderList(ids: number[]) {
return requestClient.delete('/erp/purchase-order/delete', {
params: { ids: ids.join(',') },
});

View File

@ -66,7 +66,7 @@ function handleUpdateValue(row: any) {
} else {
tableData.value[index] = row;
}
emit('update:products', tableData.value);
emit('update:products', [...tableData.value]);
}
/** 表格配置 */

View File

@ -0,0 +1,427 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import { erpPriceInputFormatter } from '@vben/utils';
import { z } from '#/adapter/form';
import { getAccountSimpleList } from '#/api/erp/finance/account';
import { getProductSimpleList } from '#/api/erp/product/product';
import { getSupplierSimpleList } from '#/api/erp/purchase/supplier';
import { getSimpleUserList } from '#/api/system/user';
import { DICT_TYPE, getDictOptions } from '#/utils';
/** 表单的配置项 */
export function useFormSchema(): VbenFormSchema[] {
return [
{
component: 'Input',
componentProps: {
style: { display: 'none' },
},
fieldName: 'id',
label: 'ID',
hideLabel: true,
formItemClass: 'hidden',
},
{
component: 'Input',
componentProps: {
placeholder: '系统自动生成',
disabled: true,
},
fieldName: 'no',
label: '订单单号',
},
{
component: 'ApiSelect',
componentProps: {
placeholder: '请选择供应商',
allowClear: true,
showSearch: true,
api: getSupplierSimpleList,
fieldNames: {
label: 'name',
value: 'id',
},
},
fieldName: 'supplierId',
label: '供应商',
rules: 'required',
},
{
component: 'DatePicker',
componentProps: {
placeholder: '选择订单时间',
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
valueFormat: 'x',
style: { width: '100%' },
},
fieldName: 'orderTime',
label: '订单时间',
rules: 'required',
},
{
component: 'Textarea',
componentProps: {
placeholder: '请输入备注',
autoSize: { minRows: 2, maxRows: 4 },
class: 'w-full',
},
fieldName: 'remark',
label: '备注',
formItemClass: 'col-span-3',
},
{
component: 'FileUpload',
componentProps: {
maxNumber: 1,
maxSize: 10,
accept: [
'pdf',
'doc',
'docx',
'xls',
'xlsx',
'txt',
'jpg',
'jpeg',
'png',
],
showDescription: true,
},
fieldName: 'fileUrl',
label: '附件',
formItemClass: 'col-span-3',
},
{
fieldName: 'product',
label: '产品清单',
component: 'Input',
formItemClass: 'col-span-3',
},
{
component: 'InputNumber',
componentProps: {
placeholder: '请输入优惠率',
min: 0,
max: 100,
precision: 2,
style: { width: '100%' },
},
fieldName: 'discountPercent',
label: '优惠率(%)',
rules: z.number().min(0).optional(),
},
{
component: 'InputNumber',
componentProps: {
placeholder: '付款优惠',
precision: 2,
formatter: erpPriceInputFormatter,
disabled: true,
style: { width: '100%' },
},
fieldName: 'discountPrice',
label: '付款优惠',
},
{
component: 'InputNumber',
componentProps: {
placeholder: '优惠后金额',
precision: 2,
formatter: erpPriceInputFormatter,
disabled: true,
style: { width: '100%' },
},
fieldName: 'totalPrice',
label: '优惠后金额',
},
{
component: 'ApiSelect',
componentProps: {
placeholder: '请选择结算账户',
allowClear: true,
showSearch: true,
api: getAccountSimpleList,
fieldNames: {
label: 'name',
value: 'id',
},
},
fieldName: 'accountId',
label: '结算账户',
},
{
component: 'InputNumber',
componentProps: {
placeholder: '请输入支付订金',
precision: 2,
style: { width: '100%' },
min: 0,
},
fieldName: 'depositPrice',
label: '支付订金',
rules: z.number().min(0).optional(),
},
];
}
/** 采购订单项表格列定义 */
export function usePurchaseOrderItemTableColumns(): VxeTableGridOptions['columns'] {
return [
{ type: 'seq', title: '序号', minWidth: 50, fixed: 'left' },
{
field: 'productId',
title: '产品名称',
minWidth: 200,
slots: { default: 'productId' },
},
{
field: 'stockCount',
title: '库存',
minWidth: 80,
},
{
field: 'productBarCode',
title: '条码',
minWidth: 120,
},
{
field: 'productUnitName',
title: '单位',
minWidth: 80,
},
{
field: 'count',
title: '数量',
minWidth: 120,
slots: { default: 'count' },
},
{
field: 'productPrice',
title: '产品单价',
minWidth: 120,
slots: { default: 'productPrice' },
},
{
field: 'totalProductPrice',
title: '金额',
minWidth: 120,
formatter: 'formatAmount2',
},
{
field: 'taxPercent',
title: '税率(%)',
minWidth: 100,
slots: { default: 'taxPercent' },
},
{
field: 'taxPrice',
title: '税额',
minWidth: 120,
formatter: 'formatAmount2',
},
{
field: 'totalPrice',
title: '税额合计',
minWidth: 120,
formatter: 'formatAmount2',
},
{
field: 'remark',
title: '备注',
minWidth: 150,
slots: { default: 'remark' },
},
{
title: '操作',
width: 50,
fixed: 'right',
slots: { default: 'actions' },
},
];
}
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'no',
label: '订单单号',
component: 'Input',
componentProps: {
placeholder: '请输入订单单号',
allowClear: true,
disabled: true,
},
},
{
fieldName: 'productId',
label: '产品',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择产品',
allowClear: true,
showSearch: true,
api: getProductSimpleList,
fieldNames: {
label: 'name',
value: 'id',
},
},
},
{
fieldName: 'orderTime',
label: '订单时间',
component: 'RangePicker',
componentProps: {
placeholder: ['开始时间', '结束时间'],
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
valueFormat: 'YYYY-MM-DD HH:mm:ss',
},
},
{
fieldName: 'supplierId',
label: '供应商',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择供应商',
allowClear: true,
showSearch: true,
api: getSupplierSimpleList,
fieldNames: {
label: 'name',
value: 'id',
},
},
},
{
fieldName: 'creator',
label: '创建人',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择创建人',
allowClear: true,
showSearch: true,
api: getSimpleUserList,
fieldNames: {
label: 'nickname',
value: 'id',
},
},
},
{
fieldName: 'status',
label: '状态',
component: 'Select',
componentProps: {
options: getDictOptions(DICT_TYPE.ERP_AUDIT_STATUS, 'number'),
placeholder: '请选择状态',
allowClear: true,
},
},
{
fieldName: 'returnStatus',
label: '退货状态',
component: 'Select',
componentProps: {
options: [
{ label: '未退货', value: 0 },
{ label: '部分退货', value: 1 },
{ label: '全部退货', value: 2 },
],
placeholder: '请选择退货状态',
allowClear: true,
},
},
];
}
/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{
type: 'checkbox',
width: 50,
fixed: 'left',
},
{
field: 'no',
title: '订单单号',
width: 200,
fixed: 'left',
},
{
field: 'productNames',
title: '产品信息',
showOverflow: 'tooltip',
minWidth: 120,
},
{
field: 'supplierName',
title: '供应商',
minWidth: 120,
},
{
field: 'orderTime',
title: '订单时间',
width: 160,
formatter: 'formatDateTime',
},
{
field: 'creatorName',
title: '创建人',
minWidth: 120,
},
{
field: 'totalCount',
title: '总数量',
minWidth: 120,
},
{
field: 'inCount',
title: '入库数量',
minWidth: 120,
},
{
field: 'returnCount',
title: '退货数量',
minWidth: 120,
},
{
field: 'totalProductPrice',
title: '金额合计',
formatter: 'formatNumber',
minWidth: 120,
},
{
field: 'totalPrice',
title: '含税金额',
formatter: 'formatNumber',
minWidth: 120,
},
{
field: 'depositPrice',
title: '支付订金',
formatter: 'formatNumber',
minWidth: 120,
},
{
field: 'status',
title: '状态',
minWidth: 120,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.ERP_AUDIT_STATUS },
},
},
{
title: '操作',
width: 220,
fixed: 'right',
slots: { default: 'actions' },
},
];
}

View File

@ -1,34 +1,270 @@
<script lang="ts" setup>
import { DocAlert, Page } from '@vben/common-ui';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { ErpPurchaseOrderApi } from '#/api/erp/purchase/order';
import { Button } from 'ant-design-vue';
import { ref } from 'vue';
import { DocAlert, Page, useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart, isEmpty } from '@vben/utils';
import { message } from 'ant-design-vue';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deletePurchaseOrder,
deletePurchaseOrderList,
exportPurchaseOrder,
getPurchaseOrderPage,
updatePurchaseOrderStatus,
} from '#/api/erp/purchase/order';
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
import PurchaseOrderForm from './modules/form.vue';
/** ERP 采购订单列表 */
defineOptions({ name: 'ErpPurchaseOrder' });
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: PurchaseOrderForm,
destroyOnClose: true,
});
/** 刷新表格 */
function onRefresh() {
gridApi.query();
}
const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
records,
}: {
records: ErpPurchaseOrderApi.PurchaseOrder[];
}) {
checkedIds.value = records.map((item) => item.id);
}
/** 详情 */
function handleDetail(row: ErpPurchaseOrderApi.PurchaseOrder) {
formModalApi.setData({ type: 'detail', id: row.id }).open();
}
/** 新增 */
function handleCreate() {
formModalApi.setData({ type: 'create' }).open();
}
/** 编辑 */
function handleEdit(row: ErpPurchaseOrderApi.PurchaseOrder) {
formModalApi.setData({ type: 'edit', id: row.id }).open();
}
/** 删除 */
async function handleDelete(row: ErpPurchaseOrderApi.PurchaseOrder) {
const hideLoading = message.loading({
content: $t('ui.actionMessage.deleting'),
duration: 0,
key: 'action_process_msg',
});
try {
if (row.id) await deletePurchaseOrder(row.id);
message.success({
content: $t('ui.actionMessage.deleteSuccess'),
key: 'action_process_msg',
});
onRefresh();
} catch {
//
} finally {
hideLoading();
}
}
/** 批量删除 */
async function handleBatchDelete() {
const hideLoading = message.loading({
content: $t('ui.actionMessage.deleting'),
duration: 0,
key: 'action_process_msg',
});
try {
await deletePurchaseOrderList(checkedIds.value);
message.success({
content: $t('ui.actionMessage.deleteSuccess'),
key: 'action_process_msg',
});
onRefresh();
} catch {
//
} finally {
hideLoading();
}
}
/** 审批/反审批操作 */
function handleUpdateStatus(
row: ErpPurchaseOrderApi.PurchaseOrder,
status: number,
) {
const hideLoading = message.loading({
content: `确定${status === 20 ? '审批' : '反审批'}该订单吗?`,
duration: 0,
key: 'action_process_msg',
});
updatePurchaseOrderStatus(row.id, status)
.then(() => {
message.success({
content: `${status === 20 ? '审批' : '反审批'}成功`,
key: 'action_process_msg',
});
onRefresh();
})
.catch(() => {
//
})
.finally(() => {
hideLoading();
});
}
/** 导出 */
async function handleExport() {
try {
const formValues = gridApi.getFormData();
const data = await exportPurchaseOrder(formValues);
downloadFileFromBlobPart({ fileName: '采购订单.xls', source: data });
} catch {
//
}
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
},
gridOptions: {
columns: useGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getPurchaseOrderPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<ErpPurchaseOrderApi.PurchaseOrder>,
gridEvents: {
checkboxAll: handleRowCheckboxChange,
checkboxChange: handleRowCheckboxChange,
},
});
</script>
<template>
<Page>
<Page auto-content-height>
<template #doc>
<DocAlert
title="【采购】采购订单、入库、退货"
url="https://doc.iocoder.cn/erp/purchase/"
/>
</template>
<Button
danger
type="link"
target="_blank"
href="https://github.com/yudaocode/yudao-ui-admin-vue3"
>
该功能支持 Vue3 + element-plus 版本
</Button>
<br />
<Button
type="link"
target="_blank"
href="https://github.com/yudaocode/yudao-ui-admin-vue3/blob/master/src/views/erp/purchase/order/index"
>
可参考
https://github.com/yudaocode/yudao-ui-admin-vue3/blob/master/src/views/erp/purchase/order/index
代码pull request 贡献给我们
</Button>
<FormModal @success="onRefresh" />
<Grid table-title="">
<template #toolbar-tools>
<TableAction
:actions="[
{
label: $t('ui.actionTitle.create', ['采购订单']),
type: 'primary',
icon: ACTION_ICON.ADD,
auth: ['erp:purchase-order:create'],
onClick: handleCreate,
},
{
label: $t('ui.actionTitle.export'),
type: 'primary',
icon: ACTION_ICON.DOWNLOAD,
auth: ['erp:purchase-order:export'],
onClick: handleExport,
},
{
label: '批量删除',
type: 'primary',
danger: true,
disabled: isEmpty(checkedIds),
icon: ACTION_ICON.DELETE,
auth: ['erp:purchase-order:delete'],
popConfirm: {
title: `是否删除所选中数据?`,
confirm: handleBatchDelete,
},
},
]"
/>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.detail'),
type: 'link',
icon: ACTION_ICON.VIEW,
auth: ['erp:purchase-order:query'],
onClick: handleDetail.bind(null, row),
},
{
label: $t('common.edit'),
type: 'link',
icon: ACTION_ICON.EDIT,
auth: ['erp:purchase-order:update'],
ifShow: () => row.status !== 20,
onClick: handleEdit.bind(null, row),
},
]"
:drop-down-actions="[
{
label: row.status === 10 ? '审批' : '反审批',
type: 'link',
auth: ['erp:purchase-order:update-status'],
popConfirm: {
title: `确认${row.status === 10 ? '审批' : '反审批'}${row.no}吗?`,
confirm: handleUpdateStatus.bind(
null,
row,
row.status === 10 ? 20 : 10,
),
},
},
{
label: $t('common.delete'),
type: 'link',
danger: true,
color: 'error',
auth: ['erp:purchase-order:delete'],
onClick: handleDelete.bind(null, row),
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.no]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</Page>
</template>

View File

@ -0,0 +1,358 @@
<script lang="ts" setup>
import type { ErpPurchaseOrderApi } from '#/api/erp/purchase/order';
import { nextTick, onMounted, ref, watch } from 'vue';
import { erpPriceMultiply } from '@vben/utils';
import { Input, InputNumber, Select } from 'ant-design-vue';
import { TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { getProductSimpleList } from '#/api/erp/product/product';
import { getStockCount } from '#/api/erp/stock/stock';
import { usePurchaseOrderItemTableColumns } from '../data';
const props = withDefaults(defineProps<Props>(), {
items: () => [],
disabled: false,
discountPercent: 0,
});
const emit = defineEmits([
'update:items',
'update:discount-price',
'update:total-price',
]);
interface Props {
items?: ErpPurchaseOrderApi.PurchaseOrderItem[];
disabled?: boolean;
discountPercent?: number;
}
const tableData = ref<ErpPurchaseOrderApi.PurchaseOrderItem[]>([]);
const productOptions = ref<any[]>([]);
/** 表格配置 */
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions: {
editConfig: {
trigger: 'click',
mode: 'cell',
},
columns: usePurchaseOrderItemTableColumns(),
data: tableData.value,
border: true,
showOverflow: true,
autoResize: true,
minHeight: 250,
keepSource: true,
rowConfig: {
keyField: 'id',
},
pagerConfig: {
enabled: false,
},
toolbarConfig: {
enabled: false,
},
},
});
/** 监听外部传入的列数据 */
watch(
() => props.items,
async (items) => {
if (!items) {
return;
}
await nextTick();
tableData.value = [...items];
await nextTick();
gridApi.grid.reloadData(tableData.value);
},
{
immediate: true,
},
);
/** 计算 discountPrice、totalPrice 价格 */
watch(
() => [tableData.value, props.discountPercent],
() => {
if (!tableData.value || tableData.value.length === 0) {
return;
}
const totalPrice = tableData.value.reduce(
(prev, curr) => prev + (curr.totalPrice || 0),
0,
);
const discountPrice =
props.discountPercent === null
? 0
: erpPriceMultiply(totalPrice, props.discountPercent / 100);
const finalTotalPrice = totalPrice - discountPrice;
//
emit('update:discount-price', discountPrice);
emit('update:total-price', finalTotalPrice);
},
{ deep: true },
);
/** 初始化 */
onMounted(async () => {
productOptions.value = await getProductSimpleList();
});
function handleAdd() {
const newRow = {
productId: null,
productName: '',
productUnitId: null,
productUnitName: '',
productBarCode: '',
count: 1,
productPrice: 0,
totalProductPrice: 0,
taxPercent: 0,
taxPrice: 0,
totalPrice: 0,
stockCount: 0,
remark: '',
};
tableData.value.push(newRow);
gridApi.grid.insertAt(newRow, -1);
emit('update:items', [...tableData.value]);
}
function handleDelete(row: ErpPurchaseOrderApi.PurchaseOrderItem) {
gridApi.grid.remove(row);
const index = tableData.value.findIndex((item) => item.id === row.id);
if (index !== -1) {
tableData.value.splice(index, 1);
}
emit('update:items', [...tableData.value]);
}
async function handleProductChange(productId: any, row: any) {
const product = productOptions.value.find((p) => p.id === productId);
if (!product) {
return;
}
const stockCount = await getStockCount(productId);
row.productId = productId;
row.productUnitId = product.unitId;
row.productBarCode = product.barCode;
row.productUnitName = product.unitName;
row.productName = product.name;
row.stockCount = stockCount || 0;
row.productPrice = product.purchasePrice;
row.count = row.count || 1;
handlePriceChange(row);
}
function handlePriceChange(row: any) {
if (row.productPrice && row.count) {
row.totalProductPrice = erpPriceMultiply(row.productPrice, row.count) ?? 0;
row.taxPrice =
erpPriceMultiply(row.totalProductPrice, (row.taxPercent || 0) / 100) ?? 0;
row.totalPrice = row.totalProductPrice + row.taxPrice;
}
handleUpdateValue(row);
}
function handleUpdateValue(row: any) {
const index = tableData.value.findIndex((item) => item.id === row.id);
if (index === -1) {
tableData.value.push(row);
} else {
tableData.value[index] = row;
}
emit('update:items', [...tableData.value]);
}
const getSummaries = (): {
count: number;
productName: string;
taxPrice: number;
totalPrice: number;
totalProductPrice: number;
} => {
return {
productName: '合计',
count: tableData.value.reduce((sum, item) => sum + (item.count || 0), 0),
totalProductPrice: tableData.value.reduce(
(sum, item) => sum + (item.totalProductPrice || 0),
0,
),
taxPrice: tableData.value.reduce(
(sum, item) => sum + (item.taxPrice || 0),
0,
),
totalPrice: tableData.value.reduce(
(sum, item) => sum + (item.totalPrice || 0),
0,
),
};
};
const validate = async (): Promise<boolean> => {
try {
for (let i = 0; i < tableData.value.length; i++) {
const item = tableData.value[i];
if (item) {
if (!item.productId) {
throw new Error(`${i + 1} 行:产品不能为空`);
}
if (!item.count || item.count <= 0) {
throw new Error(`${i + 1} 行:产品数量不能为空`);
}
if (!item.productPrice || item.productPrice <= 0) {
throw new Error(`${i + 1} 行:产品单价不能为空`);
}
}
}
return true;
} catch (error) {
console.error('验证失败:', error);
throw error;
}
};
const getData = (): ErpPurchaseOrderApi.PurchaseOrderItem[] => tableData.value;
const init = (
items: ErpPurchaseOrderApi.PurchaseOrderItem[] | undefined,
): void => {
tableData.value =
items && items.length > 0
? items.map((item) => {
const newItem = { ...item };
if (newItem.productPrice && newItem.count) {
newItem.totalProductPrice =
erpPriceMultiply(newItem.productPrice, newItem.count) ?? 0;
newItem.taxPrice =
erpPriceMultiply(
newItem.totalProductPrice,
(newItem.taxPercent || 0) / 100,
) ?? 0;
newItem.totalPrice = newItem.totalProductPrice + newItem.taxPrice;
}
return newItem;
})
: [];
nextTick(() => {
gridApi.grid.reloadData(tableData.value);
});
};
defineExpose({
validate,
getData,
init,
});
</script>
<template>
<Grid class="w-full">
<template #productId="{ row }">
<Select
v-if="!disabled"
v-model:value="row.productId"
:options="productOptions"
:field-names="{ label: 'name', value: 'id' }"
style="width: 100%"
placeholder="请选择产品"
show-search
@change="handleProductChange($event, row)"
/>
<span v-else>{{ row.productName || '-' }}</span>
</template>
<template #count="{ row }">
<InputNumber
v-if="!disabled"
v-model:value="row.count"
:min="0"
:precision="2"
@change="handlePriceChange(row)"
/>
<span v-else>{{ row.count || '-' }}</span>
</template>
<template #productPrice="{ row }">
<InputNumber
v-if="!disabled"
v-model:value="row.productPrice"
:min="0"
:precision="2"
@change="handlePriceChange(row)"
/>
<span v-else>{{ row.productPrice || '-' }}</span>
</template>
<template #taxPercent="{ row }">
<InputNumber
v-if="!disabled"
v-model:value="row.taxPercent"
:min="0"
:max="100"
:precision="2"
@change="handlePriceChange(row)"
/>
<span v-else>{{ row.taxPercent || '-' }}</span>
</template>
<template #remark="{ row }">
<Input v-if="!disabled" v-model:value="row.remark" class="w-full" />
<span v-else>{{ row.remark || '-' }}</span>
</template>
<template #bottom>
<div class="border-border bg-muted mt-2 rounded border p-2">
<div class="text-muted-foreground flex justify-between text-sm">
<span class="text-foreground font-medium">合计</span>
<div class="flex space-x-4">
<span>数量{{ getSummaries().count }}</span>
<span>金额{{ getSummaries().totalProductPrice }}</span>
<span>税额{{ getSummaries().taxPrice }}</span>
<span>税额合计{{ getSummaries().totalPrice }}</span>
</div>
</div>
</div>
<TableAction
v-if="!disabled"
class="mt-4 flex justify-center"
:actions="[
{
label: '添加产品',
type: 'default',
onClick: handleAdd,
},
]"
/>
</template>
<template #actions="{ row }">
<TableAction
v-if="!disabled"
:actions="[
{
label: '删除',
type: 'link',
danger: true,
popConfirm: {
title: '确认删除该产品吗?',
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</template>

View File

@ -0,0 +1,212 @@
<script lang="ts" setup>
import type { ErpPurchaseOrderApi } from '#/api/erp/purchase/order';
import { computed, nextTick, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { message } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
import {
createPurchaseOrder,
getPurchaseOrder,
updatePurchaseOrder,
} from '#/api/erp/purchase/order';
import { useFormSchema } from '../data';
import PurchaseOrderItemForm from './PurchaseOrderItemForm.vue';
const emit = defineEmits(['success']);
const formData = ref<ErpPurchaseOrderApi.PurchaseOrder>();
const formType = ref('');
const itemFormRef = ref();
const getTitle = computed(() => {
if (formType.value === 'create') return '添加采购订单';
if (formType.value === 'update') return '编辑采购订单';
return '采购订单详情';
});
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
labelWidth: 120,
},
wrapperClass: 'grid-cols-3',
layout: 'vertical',
schema: useFormSchema(),
showDefaultActions: false,
handleValuesChange: (values, changedFields) => {
if (formData.value && changedFields.includes('discountPercent')) {
formData.value.discountPercent = values.discountPercent;
}
},
});
const handleUpdateItems = (items: ErpPurchaseOrderApi.PurchaseOrderItem[]) => {
formData.value = modalApi.getData<ErpPurchaseOrderApi.PurchaseOrder>();
if (formData.value) {
formData.value.items = items;
}
};
const handleUpdateDiscountPrice = (discountPrice: number) => {
if (formData.value) {
formData.value.discountPrice = discountPrice;
formApi.setValues({
discountPrice: formData.value.discountPrice,
});
}
};
const handleUpdateTotalPrice = (totalPrice: number) => {
if (formData.value) {
formData.value.totalPrice = totalPrice;
formApi.setValues({
totalPrice: formData.value.totalPrice,
});
}
};
/**
* 创建或更新采购订单
*/
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
const { valid } = await formApi.validate();
if (!valid) {
return;
}
await nextTick();
const itemFormInstance = Array.isArray(itemFormRef.value)
? itemFormRef.value[0]
: itemFormRef.value;
if (itemFormInstance && typeof itemFormInstance.validate === 'function') {
try {
const isValid = await itemFormInstance.validate();
if (!isValid) {
message.error('子表单验证失败');
return;
}
} catch (error) {
message.error(error.message || '子表单验证失败');
return;
}
} else {
message.error('子表单验证方法不存在');
return;
}
//
if (!formData.value?.items || formData.value.items.length === 0) {
message.error('产品清单不能为空,请至少添加一个产品');
return;
}
modalApi.lock();
//
const data =
(await formApi.getValues()) as ErpPurchaseOrderApi.PurchaseOrder;
data.items = formData.value?.items;
//
if (data.fileUrl && Array.isArray(data.fileUrl)) {
data.fileUrl = data.fileUrl.length > 0 ? data.fileUrl[0] : '';
}
try {
await (formType.value === 'create'
? createPurchaseOrder(data)
: updatePurchaseOrder(data));
//
await modalApi.close();
emit('success');
message.success(formType.value === 'create' ? '新增成功' : '更新成功');
} finally {
modalApi.unlock();
}
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
formData.value = undefined;
return;
}
//
const data = modalApi.getData<{ id?: number; type: string }>();
if (!data) {
return;
}
formType.value = data.type;
if (!data.id) {
//
formData.value = { items: [] } as ErpPurchaseOrderApi.PurchaseOrder;
await nextTick();
const itemFormInstance = Array.isArray(itemFormRef.value)
? itemFormRef.value[0]
: itemFormRef.value;
if (itemFormInstance && typeof itemFormInstance.init === 'function') {
itemFormInstance.init([]);
}
return;
}
modalApi.lock();
try {
formData.value = await getPurchaseOrder(data.id);
// URLFileUpload
if (
formData.value.fileUrl &&
typeof formData.value.fileUrl === 'string'
) {
formData.value.fileUrl = formData.value.fileUrl
? [formData.value.fileUrl]
: [];
}
// values
await formApi.setValues(formData.value);
//
await nextTick();
const itemFormInstance = Array.isArray(itemFormRef.value)
? itemFormRef.value[0]
: itemFormRef.value;
if (itemFormInstance && typeof itemFormInstance.init === 'function') {
itemFormInstance.init(formData.value.items || []);
}
} finally {
modalApi.unlock();
}
},
});
defineExpose({ modalApi });
</script>
<template>
<Modal
v-bind="$attrs"
:title="getTitle"
class="w-1/2"
:closable="true"
:mask-closable="true"
:show-confirm-button="formType !== 'detail'"
>
<Form class="mx-3">
<template #product="slotProps">
<PurchaseOrderItemForm
v-bind="slotProps"
ref="itemFormRef"
class="w-full"
:items="formData?.items ?? []"
:disabled="formType === 'detail'"
:discount-percent="formData?.discountPercent ?? 0"
@update:items="handleUpdateItems"
@update:discount-price="handleUpdateDiscountPrice"
@update:total-price="handleUpdateTotalPrice"
/>
</template>
</Form>
</Modal>
</template>