feat:【antd】【erp 系统】purchase/order 重构 1/4

This commit is contained in:
YunaiV
2025-10-04 19:18:22 +08:00
parent 7250934a41
commit 5e13d28d46
4 changed files with 294 additions and 382 deletions

View File

@@ -10,30 +10,43 @@ import { getAccountSimpleList } from '#/api/erp/finance/account';
import { getProductSimpleList } from '#/api/erp/product/product'; import { getProductSimpleList } from '#/api/erp/product/product';
import { getSupplierSimpleList } from '#/api/erp/purchase/supplier'; import { getSupplierSimpleList } from '#/api/erp/purchase/supplier';
import { getSimpleUserList } from '#/api/system/user'; import { getSimpleUserList } from '#/api/system/user';
import { getRangePickerDefaultProps } from '#/utils';
/** 表单的配置项 */ /** 表单的配置项 */
export function useFormSchema(): VbenFormSchema[] { export function useFormSchema(formType: string): VbenFormSchema[] {
return [ return [
{ {
component: 'Input',
componentProps: {
style: { display: 'none' },
},
fieldName: 'id', fieldName: 'id',
label: 'ID', component: 'Input',
hideLabel: true, dependencies: {
formItemClass: 'hidden', triggerFields: [''],
show: () => false,
},
}, },
{ {
fieldName: 'no',
label: '订单单号',
component: 'Input', component: 'Input',
componentProps: { componentProps: {
placeholder: '系统自动生成', placeholder: '系统自动生成',
disabled: true, disabled: true,
}, },
fieldName: 'no',
label: '订单单号',
}, },
{ {
fieldName: 'orderTime',
label: '订单时间',
component: 'DatePicker',
componentProps: {
placeholder: '选择订单时间',
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
valueFormat: 'x',
},
rules: 'required',
},
{
label: '供应商',
fieldName: 'supplierId',
component: 'ApiSelect', component: 'ApiSelect',
componentProps: { componentProps: {
placeholder: '请选择供应商', placeholder: '请选择供应商',
@@ -45,35 +58,37 @@ export function useFormSchema(): VbenFormSchema[] {
value: 'id', value: 'id',
}, },
}, },
fieldName: 'supplierId',
label: '供应商',
rules: 'required', rules: 'required',
}, },
{ {
component: 'DatePicker', fieldName: 'purchaseUserId',
label: '创建人',
component: 'ApiSelect',
componentProps: { componentProps: {
placeholder: '选择订单时间', placeholder: '选择创建人',
showTime: true, allowClear: true,
format: 'YYYY-MM-DD HH:mm:ss', showSearch: true,
valueFormat: 'x', api: getSimpleUserList,
style: { width: '100%' }, fieldNames: {
label: 'nickname',
value: 'id',
},
}, },
fieldName: 'orderTime',
label: '订单时间',
rules: 'required',
}, },
{ {
fieldName: 'remark',
label: '备注',
component: 'Textarea', component: 'Textarea',
componentProps: { componentProps: {
placeholder: '请输入备注', placeholder: '请输入备注',
autoSize: { minRows: 2, maxRows: 4 }, autoSize: { minRows: 1, maxRows: 1 },
class: 'w-full', disabled: formType === 'detail',
}, },
fieldName: 'remark', formItemClass: 'col-span-2',
label: '备注',
formItemClass: 'col-span-3',
}, },
{ {
fieldName: 'fileUrl',
label: '附件',
component: 'FileUpload', component: 'FileUpload',
componentProps: { componentProps: {
maxNumber: 1, maxNumber: 1,
@@ -89,56 +104,54 @@ export function useFormSchema(): VbenFormSchema[] {
'jpeg', 'jpeg',
'png', 'png',
], ],
showDescription: true, showDescription: formType !== 'detail',
disabled: formType === 'detail',
}, },
fieldName: 'fileUrl',
label: '附件',
formItemClass: 'col-span-3', formItemClass: 'col-span-3',
}, },
{ {
fieldName: 'product', fieldName: 'items',
label: '产品清单', label: '采购产品清单',
component: 'Input', component: 'Input',
formItemClass: 'col-span-3', formItemClass: 'col-span-3',
}, },
{ {
fieldName: 'discountPercent',
label: '优惠率(%)',
component: 'InputNumber', component: 'InputNumber',
componentProps: { componentProps: {
placeholder: '请输入优惠率', placeholder: '请输入优惠率',
min: 0, min: 0,
max: 100, max: 100,
precision: 2, precision: 2,
style: { width: '100%' },
}, },
fieldName: 'discountPercent',
label: '优惠率(%)',
rules: z.number().min(0).optional(), rules: z.number().min(0).optional(),
}, },
{ {
fieldName: 'discountPrice',
label: '付款优惠',
component: 'InputNumber', component: 'InputNumber',
componentProps: { componentProps: {
placeholder: '付款优惠', placeholder: '付款优惠',
precision: 2, precision: 2,
formatter: erpPriceInputFormatter, formatter: erpPriceInputFormatter,
disabled: true, disabled: true,
style: { width: '100%' },
}, },
fieldName: 'discountPrice',
label: '付款优惠',
}, },
{ {
fieldName: 'totalPrice',
label: '优惠后金额',
component: 'InputNumber', component: 'InputNumber',
componentProps: { componentProps: {
placeholder: '优惠后金额', placeholder: '优惠后金额',
precision: 2, precision: 2,
formatter: erpPriceInputFormatter, formatter: erpPriceInputFormatter,
disabled: true, disabled: true,
style: { width: '100%' },
}, },
fieldName: 'totalPrice',
label: '优惠后金额',
}, },
{ {
fieldName: 'accountId',
label: '结算账户',
component: 'ApiSelect', component: 'ApiSelect',
componentProps: { componentProps: {
placeholder: '请选择结算账户', placeholder: '请选择结算账户',
@@ -150,15 +163,12 @@ export function useFormSchema(): VbenFormSchema[] {
value: 'id', value: 'id',
}, },
}, },
fieldName: 'accountId',
label: '结算账户',
}, },
{ {
component: 'InputNumber', component: 'InputNumber',
componentProps: { componentProps: {
placeholder: '请输入支付订金', placeholder: '请输入支付订金',
precision: 2, precision: 2,
style: { width: '100%' },
min: 0, min: 0,
}, },
fieldName: 'depositPrice', fieldName: 'depositPrice',
@@ -168,8 +178,8 @@ export function useFormSchema(): VbenFormSchema[] {
]; ];
} }
/** 采购订单项表格列定义 */ /** 表单的明细表格列 */
export function usePurchaseOrderItemTableColumns(): VxeTableGridOptions['columns'] { export function useFormItemColumns(): VxeTableGridOptions['columns'] {
return [ return [
{ type: 'seq', title: '序号', minWidth: 50, fixed: 'left' }, { type: 'seq', title: '序号', minWidth: 50, fixed: 'left' },
{ {
@@ -193,6 +203,12 @@ export function usePurchaseOrderItemTableColumns(): VxeTableGridOptions['columns
title: '单位', title: '单位',
minWidth: 80, minWidth: 80,
}, },
{
field: 'remark',
title: '备注',
minWidth: 150,
slots: { default: 'remark' },
},
{ {
field: 'count', field: 'count',
title: '数量', title: '数量',
@@ -214,7 +230,7 @@ export function usePurchaseOrderItemTableColumns(): VxeTableGridOptions['columns
{ {
field: 'taxPercent', field: 'taxPercent',
title: '税率(%)', title: '税率(%)',
minWidth: 100, minWidth: 105,
slots: { default: 'taxPercent' }, slots: { default: 'taxPercent' },
}, },
{ {
@@ -229,12 +245,6 @@ export function usePurchaseOrderItemTableColumns(): VxeTableGridOptions['columns
minWidth: 120, minWidth: 120,
formatter: 'formatAmount2', formatter: 'formatAmount2',
}, },
{
field: 'remark',
title: '备注',
minWidth: 150,
slots: { default: 'remark' },
},
{ {
title: '操作', title: '操作',
width: 50, width: 50,
@@ -254,7 +264,6 @@ export function useGridFormSchema(): VbenFormSchema[] {
componentProps: { componentProps: {
placeholder: '请输入订单单号', placeholder: '请输入订单单号',
allowClear: true, allowClear: true,
disabled: true,
}, },
}, },
{ {
@@ -277,10 +286,8 @@ export function useGridFormSchema(): VbenFormSchema[] {
label: '订单时间', label: '订单时间',
component: 'RangePicker', component: 'RangePicker',
componentProps: { componentProps: {
placeholder: ['开始时间', '结束时间'], ...getRangePickerDefaultProps(),
showTime: true, allowClear: true,
format: 'YYYY-MM-DD HH:mm:ss',
valueFormat: 'YYYY-MM-DD HH:mm:ss',
}, },
}, },
{ {
@@ -323,6 +330,29 @@ export function useGridFormSchema(): VbenFormSchema[] {
allowClear: true, allowClear: true,
}, },
}, },
{
fieldName: 'remark',
label: '备注',
component: 'Input',
componentProps: {
placeholder: '请输入备注',
allowClear: true,
},
},
{
fieldName: 'inStatus',
label: '入库状态',
component: 'Select',
componentProps: {
options: [
{ label: '未入库', value: 0 },
{ label: '部分入库', value: 1 },
{ label: '全部入库', value: 2 },
],
placeholder: '请选择入库状态',
allowClear: true,
},
},
{ {
fieldName: 'returnStatus', fieldName: 'returnStatus',
label: '退货状态', label: '退货状态',
@@ -369,7 +399,7 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
field: 'orderTime', field: 'orderTime',
title: '订单时间', title: '订单时间',
width: 160, width: 160,
formatter: 'formatDateTime', formatter: 'formatDate',
}, },
{ {
field: 'creatorName', field: 'creatorName',

View File

@@ -12,7 +12,6 @@ import { message } from 'ant-design-vue';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table'; import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { import {
deletePurchaseOrder, deletePurchaseOrder,
deletePurchaseOrderList,
exportPurchaseOrder, exportPurchaseOrder,
getPurchaseOrderPage, getPurchaseOrderPage,
updatePurchaseOrderStatus, updatePurchaseOrderStatus,
@@ -20,77 +19,70 @@ import {
import { $t } from '#/locales'; import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data'; import { useGridColumns, useGridFormSchema } from './data';
import PurchaseOrderForm from './modules/form.vue'; import Form from './modules/form.vue';
/** ERP 采购订单列表 */ /** ERP 采购订单列表 */
defineOptions({ name: 'ErpPurchaseOrder' }); defineOptions({ name: 'ErpPurchaseOrder' });
const [FormModal, formModalApi] = useVbenModal({ const [FormModal, formModalApi] = useVbenModal({
connectedComponent: PurchaseOrderForm, connectedComponent: Form,
destroyOnClose: true, destroyOnClose: true,
}); });
/** 刷新表格 */ /** 刷新表格 */
function onRefresh() { function handleRefresh() {
gridApi.query(); gridApi.query();
} }
/** 详情 */ /** 导出表格 */
function handleDetail(row: ErpPurchaseOrderApi.PurchaseOrder) { async function handleExport() {
formModalApi.setData({ type: 'detail', id: row.id }).open(); const data = await exportPurchaseOrder(await gridApi.formApi.getValues());
downloadFileFromBlobPart({ fileName: '采购订单.xls', source: data });
} }
/** 新增 */ /** 新增采购订单 */
function handleCreate() { function handleCreate() {
formModalApi.setData({ type: 'create' }).open(); formModalApi.setData({ type: 'create' }).open();
} }
/** 编辑 */ /** 编辑采购订单 */
function handleEdit(row: ErpPurchaseOrderApi.PurchaseOrder) { function handleEdit(row: ErpPurchaseOrderApi.PurchaseOrder) {
formModalApi.setData({ type: 'edit', id: row.id }).open(); formModalApi.setData({ type: 'edit', id: row.id }).open();
} }
/** 删除 */ /** 删除采购订单 */
async function handleDelete(row: ErpPurchaseOrderApi.PurchaseOrder) { async function handleDelete(ids: number[]) {
const hideLoading = message.loading({ const hideLoading = message.loading({
content: $t('ui.actionMessage.deleting'), content: $t('ui.actionMessage.deleting'),
duration: 0, duration: 0,
key: 'action_process_msg',
}); });
try { try {
if (row.id) await deletePurchaseOrder(row.id); await deletePurchaseOrder(ids);
message.success({ message.success($t('ui.actionMessage.deleteSuccess'));
content: $t('ui.actionMessage.deleteSuccess'), handleRefresh();
key: 'action_process_msg',
});
onRefresh();
} finally { } finally {
hideLoading(); hideLoading();
} }
} }
/** 批量删除 */ /** 审批/反审批操作 */
// TODO @nehc handleBatchDelete 是不是和别的模块,一个风格 async function handleUpdateStatus(
async function handleBatchDelete() { row: ErpPurchaseOrderApi.PurchaseOrder,
status: number,
) {
const hideLoading = message.loading({ const hideLoading = message.loading({
content: $t('ui.actionMessage.deleting'), content: `确定${status === 20 ? '审批' : '反审批'}该订单吗?`,
duration: 0, duration: 0,
key: 'action_process_msg',
}); });
try { try {
await deletePurchaseOrderList(checkedIds.value); await updatePurchaseOrderStatus(row.id!, status);
checkedIds.value = []; message.success(`${status === 20 ? '审批' : '反审批'}成功`);
message.success({ handleRefresh();
content: $t('ui.actionMessage.deleteSuccess'),
key: 'action_process_msg',
});
onRefresh();
} finally { } finally {
hideLoading(); hideLoading();
} }
} }
// TODO @Xuzhiqiang批量删除待实现
const checkedIds = ref<number[]>([]); const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({ function handleRowCheckboxChange({
records, records,
@@ -100,37 +92,9 @@ function handleRowCheckboxChange({
checkedIds.value = records.map((item) => item.id!); checkedIds.value = records.map((item) => item.id!);
} }
/** 审批/反审批操作 */ /** 查看详情 */
function handleUpdateStatus( function handleDetail(row: ErpPurchaseOrderApi.PurchaseOrder) {
row: ErpPurchaseOrderApi.PurchaseOrder, formModalApi.setData({ type: 'detail', id: row.id }).open();
status: number,
) {
// TODO @nehc 是不是和别的模块,类似的 status 处理一个风格
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() {
const data = await exportPurchaseOrder(await gridApi.formApi.getValues());
downloadFileFromBlobPart({ fileName: '采购订单.xls', source: data });
} }
const [Grid, gridApi] = useVbenVxeGrid({ const [Grid, gridApi] = useVbenVxeGrid({
@@ -177,8 +141,7 @@ const [Grid, gridApi] = useVbenVxeGrid({
/> />
</template> </template>
<FormModal @success="onRefresh" /> <FormModal @success="handleRefresh" />
<Grid table-title="采购订单列表"> <Grid table-title="采购订单列表">
<template #toolbar-tools> <template #toolbar-tools>
<TableAction <TableAction
@@ -206,7 +169,7 @@ const [Grid, gridApi] = useVbenVxeGrid({
auth: ['erp:purchase-order:delete'], auth: ['erp:purchase-order:delete'],
popConfirm: { popConfirm: {
title: `是否删除所选中数据?`, title: `是否删除所选中数据?`,
confirm: handleBatchDelete, confirm: handleDelete.bind(null, checkedIds),
}, },
}, },
]" ]"
@@ -230,8 +193,6 @@ const [Grid, gridApi] = useVbenVxeGrid({
ifShow: () => row.status !== 20, ifShow: () => row.status !== 20,
onClick: handleEdit.bind(null, row), onClick: handleEdit.bind(null, row),
}, },
]"
:drop-down-actions="[
{ {
label: row.status === 10 ? '审批' : '反审批', label: row.status === 10 ? '审批' : '反审批',
type: 'link', type: 'link',
@@ -251,10 +212,9 @@ const [Grid, gridApi] = useVbenVxeGrid({
danger: true, danger: true,
color: 'error', color: 'error',
auth: ['erp:purchase-order:delete'], auth: ['erp:purchase-order:delete'],
onClick: handleDelete.bind(null, row),
popConfirm: { popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.no]), title: $t('ui.actionMessage.deleteConfirm', [row.no]),
confirm: handleDelete.bind(null, row), confirm: handleDelete.bind(null, [row.id!]),
}, },
}, },
]" ]"

View File

@@ -1,32 +1,37 @@
<script lang="ts" setup> <script lang="ts" setup>
import type { ErpPurchaseOrderApi } from '#/api/erp/purchase/order'; import type { ErpPurchaseOrderApi } from '#/api/erp/purchase/order';
import { computed, nextTick, ref } from 'vue'; import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui'; import { useVbenModal } from '@vben/common-ui';
import { message } from 'ant-design-vue'; import { message } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form'; import { useVbenForm } from '#/adapter/form';
import { getAccountSimpleList } from '#/api/erp/finance/account';
import { import {
createPurchaseOrder, createPurchaseOrder,
getPurchaseOrder, getPurchaseOrder,
updatePurchaseOrder, updatePurchaseOrder,
} from '#/api/erp/purchase/order'; } from '#/api/erp/purchase/order';
import { $t } from '#/locales';
import { useFormSchema } from '../data'; import { useFormSchema } from '../data';
import PurchaseOrderItemForm from './purchase-order-item-form.vue'; import PurchaseOrderItemForm from './item-form.vue';
const emit = defineEmits(['success']); const emit = defineEmits(['success']);
const formData = ref<ErpPurchaseOrderApi.PurchaseOrder>(); const formData = ref<ErpPurchaseOrderApi.PurchaseOrder>();
const formType = ref(''); const formType = ref(''); // 表单类型:'create' | 'edit' | 'detail'
const itemFormRef = ref(); const itemFormRef = ref<InstanceType<typeof PurchaseOrderItemForm>>();
const getTitle = computed(() => { /* eslint-disable unicorn/no-nested-ternary */
if (formType.value === 'create') return '添加采购订单'; const getTitle = computed(() =>
if (formType.value === 'update') return '编辑采购订单'; formType.value === 'create'
return '采购订单详情'; ? $t('ui.actionTitle.create', ['采购订单'])
}); : formType.value === 'update'
? $t('ui.actionTitle.edit', ['采购订单'])
: '采购订单详情',
);
const [Form, formApi] = useVbenForm({ const [Form, formApi] = useVbenForm({
commonConfig: { commonConfig: {
@@ -37,38 +42,37 @@ const [Form, formApi] = useVbenForm({
}, },
wrapperClass: 'grid-cols-3', wrapperClass: 'grid-cols-3',
layout: 'vertical', layout: 'vertical',
schema: useFormSchema(), schema: useFormSchema(formType.value),
showDefaultActions: false, showDefaultActions: false,
handleValuesChange: (values, changedFields) => { handleValuesChange: (values, changedFields) => {
// 目的:同步到 item-form 组件,触发整体的价格计算
if (formData.value && changedFields.includes('discountPercent')) { if (formData.value && changedFields.includes('discountPercent')) {
formData.value.discountPercent = values.discountPercent; formData.value.discountPercent = values.discountPercent;
} }
}, },
}); });
/** 更新采购订单项 */
const handleUpdateItems = (items: ErpPurchaseOrderApi.PurchaseOrderItem[]) => { const handleUpdateItems = (items: ErpPurchaseOrderApi.PurchaseOrderItem[]) => {
formData.value = modalApi.getData<ErpPurchaseOrderApi.PurchaseOrder>(); formData.value = modalApi.getData<ErpPurchaseOrderApi.PurchaseOrder>();
if (formData.value) { formData.value.items = items;
formData.value.items = items; formApi.setValues({
} items,
});
}; };
/** 更新优惠金额 */
const handleUpdateDiscountPrice = (discountPrice: number) => { const handleUpdateDiscountPrice = (discountPrice: number) => {
if (formData.value) { formApi.setValues({
formData.value.discountPrice = discountPrice; discountPrice,
formApi.setValues({ });
discountPrice: formData.value.discountPrice,
});
}
}; };
/** 更新总金额 */
const handleUpdateTotalPrice = (totalPrice: number) => { const handleUpdateTotalPrice = (totalPrice: number) => {
if (formData.value) { formApi.setValues({
formData.value.totalPrice = totalPrice; totalPrice,
formApi.setValues({ });
totalPrice: formData.value.totalPrice,
});
}
}; };
/** 创建或更新采购订单 */ /** 创建或更新采购订单 */
@@ -78,31 +82,13 @@ const [Modal, modalApi] = useVbenModal({
if (!valid) { if (!valid) {
return; return;
} }
await nextTick();
// TODO @nehc应该不会不存在直接校验简洁一点另外可以看看别的模块主子表的处理哈
const itemFormInstance = Array.isArray(itemFormRef.value) const itemFormInstance = Array.isArray(itemFormRef.value)
? itemFormRef.value[0] ? itemFormRef.value[0]
: itemFormRef.value; : itemFormRef.value;
if (itemFormInstance && typeof itemFormInstance.validate === 'function') { try {
try { itemFormInstance.validate();
const isValid = await itemFormInstance.validate(); } catch (error: any) {
if (!isValid) { message.error(error.message || '子表单验证失败');
message.error('子表单验证失败');
return;
}
} catch (error: any) {
message.error(error.message || '子表单验证失败');
return;
}
} else {
message.error('子表单验证方法不存在');
return;
}
// 验证产品清单不能为空
if (!formData.value?.items || formData.value.items.length === 0) {
message.error('产品清单不能为空,请至少添加一个产品');
return; return;
} }
@@ -126,7 +112,7 @@ const [Modal, modalApi] = useVbenModal({
// 关闭并提示 // 关闭并提示
await modalApi.close(); await modalApi.close();
emit('success'); emit('success');
message.success(formType.value === 'create' ? '新增成功' : '更新成功'); message.success($t('ui.actionMessage.operationSuccess'));
} finally { } finally {
modalApi.unlock(); modalApi.unlock();
} }
@@ -138,62 +124,41 @@ const [Modal, modalApi] = useVbenModal({
} }
// 加载数据 // 加载数据
const data = modalApi.getData<{ id?: number; type: string }>(); const data = modalApi.getData<{ id?: number; type: string }>();
if (!data) {
return;
}
formType.value = data.type; formType.value = data.type;
formApi.setDisabled(formType.value === 'detail');
if (!data.id) { formApi.updateSchema(useFormSchema(formType.value));
// 初始化空的表单数据 if (!data || !data.id) {
formData.value = { items: [] } as ErpPurchaseOrderApi.PurchaseOrder; // 新增时,默认选中账户
await nextTick(); const accountList = await getAccountSimpleList();
// TODO @nehc看看有没办法简化 const defaultAccount = accountList.find((item) => item.defaultStatus);
const itemFormInstance = Array.isArray(itemFormRef.value) if (defaultAccount) {
? itemFormRef.value[0] await formApi.setValues({ accountId: defaultAccount.id });
: itemFormRef.value;
if (itemFormInstance && typeof itemFormInstance.init === 'function') {
itemFormInstance.init([]);
} }
return; return;
} }
modalApi.lock(); modalApi.lock();
try { try {
formData.value = await getPurchaseOrder(data.id); formData.value = await getPurchaseOrder(data.id);
// 设置到 values // 设置到 values
await formApi.setValues(formData.value); 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 { } finally {
modalApi.unlock(); modalApi.unlock();
} }
}, },
}); });
defineExpose({ modalApi });
</script> </script>
<template> <template>
<Modal <Modal
v-bind="$attrs" v-bind="$attrs"
:title="getTitle" :title="getTitle"
class="w-1/2" class="w-3/4"
:closable="true"
:mask-closable="true"
:show-confirm-button="formType !== 'detail'" :show-confirm-button="formType !== 'detail'"
> >
<Form class="mx-3"> <Form class="mx-3">
<template #product="slotProps"> <template #items>
<PurchaseOrderItemForm <PurchaseOrderItemForm
v-bind="slotProps"
ref="itemFormRef" ref="itemFormRef"
class="w-full"
:items="formData?.items ?? []" :items="formData?.items ?? []"
:disabled="formType === 'detail'" :disabled="formType === 'detail'"
:discount-percent="formData?.discountPercent ?? 0" :discount-percent="formData?.discountPercent ?? 0"

View File

@@ -1,10 +1,14 @@
<script lang="ts" setup> <script lang="ts" setup>
// TODO @nehc erp import type { ErpProductApi } from '#/api/erp/product/product';
import type { ErpPurchaseOrderApi } from '#/api/erp/purchase/order'; import type { ErpPurchaseOrderApi } from '#/api/erp/purchase/order';
import { nextTick, onMounted, ref, watch } from 'vue'; import { computed, nextTick, onMounted, ref, watch } from 'vue';
import { erpPriceMultiply } from '@vben/utils'; import {
erpCountInputFormatter,
erpPriceInputFormatter,
erpPriceMultiply,
} from '@vben/utils';
import { Input, InputNumber, Select } from 'ant-design-vue'; import { Input, InputNumber, Select } from 'ant-design-vue';
@@ -12,7 +16,13 @@ import { TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { getProductSimpleList } from '#/api/erp/product/product'; import { getProductSimpleList } from '#/api/erp/product/product';
import { getStockCount } from '#/api/erp/stock/stock'; import { getStockCount } from '#/api/erp/stock/stock';
import { usePurchaseOrderItemTableColumns } from '../data'; import { useFormItemColumns } from '../data';
interface Props {
items?: ErpPurchaseOrderApi.PurchaseOrderItem[];
disabled?: boolean;
discountPercent?: number;
}
const props = withDefaults(defineProps<Props>(), { const props = withDefaults(defineProps<Props>(), {
items: () => [], items: () => [],
@@ -26,32 +36,39 @@ const emit = defineEmits([
'update:total-price', 'update:total-price',
]); ]);
// TODO @nehc: const tableData = ref<ErpPurchaseOrderApi.PurchaseOrderItem[]>([]); //
interface Props { const productOptions = ref<ErpProductApi.Product[]>([]); //
items?: ErpPurchaseOrderApi.PurchaseOrderItem[];
disabled?: boolean;
discountPercent?: number;
}
const tableData = ref<ErpPurchaseOrderApi.PurchaseOrderItem[]>([]); /** 获取表格合计数据 */
const productOptions = ref<any[]>([]); const summaries = computed(() => {
return {
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 [Grid, gridApi] = useVbenVxeGrid({ const [Grid, gridApi] = useVbenVxeGrid({
gridOptions: { gridOptions: {
editConfig: { columns: useFormItemColumns(),
trigger: 'click',
mode: 'cell',
},
columns: usePurchaseOrderItemTableColumns(),
data: tableData.value, data: tableData.value,
border: true,
showOverflow: true,
autoResize: true,
minHeight: 250, minHeight: 250,
keepSource: true, autoResize: true,
border: true,
rowConfig: { rowConfig: {
keyField: 'id', keyField: 'row_id',
isHover: true,
}, },
pagerConfig: { pagerConfig: {
enabled: false, enabled: false,
@@ -69,9 +86,9 @@ watch(
if (!items) { if (!items) {
return; return;
} }
await nextTick(); items.forEach((item) => initRow(item));
tableData.value = [...items]; tableData.value = [...items];
await nextTick(); await nextTick(); // gridApi
await gridApi.grid.reloadData(tableData.value); await gridApi.grid.reloadData(tableData.value);
}, },
{ {
@@ -95,81 +112,63 @@ watch(
? 0 ? 0
: erpPriceMultiply(totalPrice, props.discountPercent / 100); : erpPriceMultiply(totalPrice, props.discountPercent / 100);
const finalTotalPrice = totalPrice - discountPrice!; const finalTotalPrice = totalPrice - discountPrice!;
//
//
emit('update:discount-price', discountPrice); emit('update:discount-price', discountPrice);
emit('update:total-price', finalTotalPrice); emit('update:total-price', finalTotalPrice);
}, },
{ deep: true }, { deep: true },
); );
/** 初始化 */ /** 处理新增 */
onMounted(async () => {
productOptions.value = await getProductSimpleList();
});
function handleAdd() { function handleAdd() {
const newRow = { const newRow = {
id: undefined,
productId: undefined, productId: undefined,
productName: '', productUnitName: undefined, //
productUnitId: undefined, productBarCode: undefined, //
productUnitName: '', productPrice: undefined,
productBarCode: '', stockCount: undefined,
count: 1, count: 1,
productPrice: 0, totalProductPrice: undefined,
totalProductPrice: 0,
taxPercent: 0, taxPercent: 0,
taxPrice: 0, taxPrice: undefined,
totalPrice: 0, totalPrice: undefined,
stockCount: 0, remark: undefined,
remark: '',
}; };
// TODO @nehc
tableData.value.push(newRow); tableData.value.push(newRow);
gridApi.grid.insertAt(newRow, -1); //
emit('update:items', [...tableData.value]); emit('update:items', [...tableData.value]);
} }
/** 处理删除 */
function handleDelete(row: ErpPurchaseOrderApi.PurchaseOrderItem) { function handleDelete(row: ErpPurchaseOrderApi.PurchaseOrderItem) {
gridApi.grid.remove(row);
const index = tableData.value.findIndex((item) => item.id === row.id); const index = tableData.value.findIndex((item) => item.id === row.id);
if (index !== -1) { if (index !== -1) {
tableData.value.splice(index, 1); tableData.value.splice(index, 1);
} }
//
emit('update:items', [...tableData.value]); emit('update:items', [...tableData.value]);
} }
/** 处理产品变更 */
async function handleProductChange(productId: any, row: any) { async function handleProductChange(productId: any, row: any) {
const product = productOptions.value.find((p) => p.id === productId); const product = productOptions.value.find((p) => p.id === productId);
if (!product) { if (!product) {
return; return;
} }
const stockCount = await getStockCount(productId);
row.productId = productId; row.productId = productId;
row.productUnitId = product.unitId; row.productUnitId = product.unitId;
row.productBarCode = product.barCode; row.productBarCode = product.barCode;
row.productUnitName = product.unitName; row.productUnitName = product.unitName;
row.productName = product.name; row.productName = product.name;
row.stockCount = stockCount || 0; row.stockCount = (await getStockCount(productId)) || 0;
row.productPrice = product.purchasePrice; row.productPrice = product.purchasePrice || 0;
row.count = row.count || 1; row.count = row.count || 1;
handleRowChange(row);
handlePriceChange(row);
} }
function handlePriceChange(row: any) { /** 处理行数据变更 */
if (row.productPrice && row.count) { function handleRowChange(row: any) {
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); const index = tableData.value.findIndex((item) => item.id === row.id);
if (index === -1) { if (index === -1) {
tableData.value.push(row); tableData.value.push(row);
@@ -179,85 +178,45 @@ function handleUpdateValue(row: any) {
emit('update:items', [...tableData.value]); emit('update:items', [...tableData.value]);
} }
const getSummaries = (): { /** 初始化行数据 */
count: number; const initRow = (row: ErpPurchaseOrderApi.PurchaseOrderItem): void => {
productName: string; if (row.productPrice && row.count) {
taxPrice: number; row.totalProductPrice = erpPriceMultiply(row.productPrice, row.count) ?? 0;
totalPrice: number; row.taxPrice =
totalProductPrice: number; erpPriceMultiply(row.totalProductPrice, (row.taxPercent || 0) / 100) ?? 0;
} => { row.totalPrice = row.totalProductPrice + row.taxPrice;
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 = ( function validate() {
items: ErpPurchaseOrderApi.PurchaseOrderItem[] | undefined, for (let i = 0; i < tableData.value.length; i++) {
): void => { const item = tableData.value[i];
tableData.value = if (item) {
items && items.length > 0 if (!item.productId) {
? items.map((item) => { throw new Error(`${i + 1} 行:产品不能为空`);
const newItem = { ...item }; }
if (newItem.productPrice && newItem.count) { if (!item.count || item.count <= 0) {
newItem.totalProductPrice = throw new Error(`${i + 1} 行:产品数量不能为空`);
erpPriceMultiply(newItem.productPrice, newItem.count) ?? 0; }
newItem.taxPrice = if (!item.productPrice || item.productPrice <= 0) {
erpPriceMultiply( throw new Error(`${i + 1} 行:产品单价不能为空`);
newItem.totalProductPrice, }
(newItem.taxPercent || 0) / 100, }
) ?? 0; }
newItem.totalPrice = newItem.totalProductPrice + newItem.taxPrice; }
}
return newItem;
})
: [];
// TODO @XuZhiqiang: await
nextTick(() => {
gridApi.grid.reloadData(tableData.value);
});
};
defineExpose({ defineExpose({
validate, validate,
getData, });
init,
/** 初始化 */
onMounted(async () => {
productOptions.value = await getProductSimpleList();
//
if (tableData.value.length === 0) {
handleAdd();
}
}); });
</script> </script>
@@ -269,36 +228,37 @@ defineExpose({
v-model:value="row.productId" v-model:value="row.productId"
:options="productOptions" :options="productOptions"
:field-names="{ label: 'name', value: 'id' }" :field-names="{ label: 'name', value: 'id' }"
style="width: 100%" class="w-full"
placeholder="请选择产品" placeholder="请选择产品"
show-search show-search
@change="handleProductChange($event, row)" @change="handleProductChange($event, row)"
/> />
<span v-else>{{ row.productName || '-' }}</span> <span v-else>{{ row.productName || '-' }}</span>
</template> </template>
<template #count="{ row }"> <template #count="{ row }">
<InputNumber <InputNumber
v-if="!disabled" v-if="!disabled"
v-model:value="row.count" v-model:value="row.count"
:min="0" :min="0"
:precision="2" :precision="3"
@change="handlePriceChange(row)" @change="handleRowChange(row)"
/> />
<span v-else>{{ row.count || '-' }}</span> <span v-else>{{ row.count || '-' }}</span>
</template> </template>
<template #productPrice="{ row }"> <template #productPrice="{ row }">
<InputNumber <InputNumber
v-if="!disabled" v-if="!disabled"
v-model:value="row.productPrice" v-model:value="row.productPrice"
:min="0" :min="0"
:precision="2" :precision="2"
@change="handlePriceChange(row)" @change="handleRowChange(row)"
/> />
<span v-else>{{ row.productPrice || '-' }}</span> <span v-else>{{ row.productPrice || '-' }}</span>
</template> </template>
<template #remark="{ row }">
<Input v-if="!disabled" v-model:value="row.remark" class="w-full" />
<span v-else>{{ row.remark || '-' }}</span>
</template>
<template #taxPercent="{ row }"> <template #taxPercent="{ row }">
<InputNumber <InputNumber
v-if="!disabled" v-if="!disabled"
@@ -306,42 +266,10 @@ defineExpose({
:min="0" :min="0"
:max="100" :max="100"
:precision="2" :precision="2"
@change="handlePriceChange(row)" @change="handleRowChange(row)"
/> />
<span v-else>{{ row.taxPercent || '-' }}</span> <span v-else>{{ row.taxPercent || '-' }}</span>
</template> </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 }"> <template #actions="{ row }">
<TableAction <TableAction
v-if="!disabled" v-if="!disabled"
@@ -358,5 +286,34 @@ defineExpose({
]" ]"
/> />
</template> </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>数量{{ erpCountInputFormatter(summaries.count) }}</span>
<span>
金额{{ erpPriceInputFormatter(summaries.totalProductPrice) }}
</span>
<span>税额{{ erpPriceInputFormatter(summaries.taxPrice) }}</span>
<span>
税额合计{{ erpPriceInputFormatter(summaries.totalPrice) }}
</span>
</div>
</div>
</div>
<TableAction
v-if="!disabled"
class="mt-2 flex justify-center"
:actions="[
{
label: '添加采购产品',
type: 'default',
onClick: handleAdd,
},
]"
/>
</template>
</Grid> </Grid>
</template> </template>