feat:【antd】【erp 系统】purchase/return 重构 2/4

This commit is contained in:
YunaiV
2025-10-04 21:14:41 +08:00
parent 1350342715
commit 7d9b3f89fa
7 changed files with 653 additions and 674 deletions

View File

@@ -11,31 +11,55 @@ import { getProductSimpleList } from '#/api/erp/product/product';
import { getSupplierSimpleList } from '#/api/erp/purchase/supplier';
import { getWarehouseSimpleList } from '#/api/erp/stock/warehouse';
import { getSimpleUserList } from '#/api/system/user';
import { getRangePickerDefaultProps } from '#/utils';
/** 表单的配置项 */
export function useFormSchema(formType: string): VbenFormSchema[] {
return [
{
component: 'Input',
componentProps: {
style: { display: 'none' },
},
fieldName: 'id',
label: 'ID',
hideLabel: true,
formItemClass: 'hidden',
component: 'Input',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'no',
label: '退货单号',
component: 'Input',
componentProps: {
placeholder: '系统自动生成',
disabled: true,
},
fieldName: 'no',
label: '退货单号',
},
{
fieldName: 'returnTime',
label: '退货时间',
component: 'DatePicker',
componentProps: {
disabled: formType === 'detail',
placeholder: '选择退货时间',
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
valueFormat: 'x',
},
rules: 'required',
},
{
fieldName: 'orderNo',
label: '关联订单',
component: 'Input',
formItemClass: 'col-span-1',
rules: 'required',
componentProps: {
placeholder: '请选择关联订单',
disabled: formType === 'detail',
},
},
{
fieldName: 'supplierId',
label: '供应商',
component: 'ApiSelect',
componentProps: {
disabled: true,
@@ -48,53 +72,39 @@ export function useFormSchema(formType: string): VbenFormSchema[] {
value: 'id',
},
},
fieldName: 'supplierId',
label: '供应商',
rules: 'required',
},
{
fieldName: 'orderNo',
label: '关联订单',
component: 'Input',
formItemClass: 'col-span-1',
rules: 'required',
fieldName: 'purchaseUserId',
label: '采购人员',
component: 'ApiSelect',
componentProps: {
disabled: formType === 'detail',
placeholder: '请选择关联订单',
placeholder: '请选择采购人员',
allowClear: true,
showSearch: true,
api: getSimpleUserList,
fieldNames: {
label: 'nickname',
value: 'id',
},
},
},
{
component: 'DatePicker',
componentProps: {
disabled: formType === 'detail',
placeholder: '选择退货时间',
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
valueFormat: 'x',
style: { width: '100%' },
},
fieldName: 'returnTime',
label: '退货时间',
rules: 'required',
},
{
fieldName: 'remark',
label: '备注',
component: 'Textarea',
componentProps: {
placeholder: '请输入备注',
disabled: formType === 'detail',
autoSize: { minRows: 1, maxRows: 1 },
class: 'w-full',
disabled: formType === 'detail',
},
fieldName: 'remark',
label: '备注',
formItemClass: 'col-span-2',
},
{
fieldName: 'fileUrl',
label: '附件',
component: 'FileUpload',
componentProps: {
disabled: formType === 'detail',
maxNumber: 1,
maxSize: 10,
accept: [
@@ -108,69 +118,73 @@ export function useFormSchema(formType: string): VbenFormSchema[] {
'jpeg',
'png',
],
showDescription: true,
showDescription: formType !== 'detail',
disabled: formType === 'detail',
},
fieldName: 'fileUrl',
label: '附件',
formItemClass: 'col-span-3',
},
{
fieldName: 'product',
label: '产品清单',
fieldName: 'items',
label: '退货产品清单',
component: 'Input',
formItemClass: 'col-span-3',
},
{
component: 'InputNumber',
fieldName: 'discountPercent',
label: '优惠率(%)',
component: 'InputNumber',
componentProps: {
placeholder: '优惠率',
placeholder: '请输入优惠率',
min: 0,
max: 100,
disabled: true,
precision: 2,
style: { width: '100%' },
},
label: '优惠率(%)',
rules: z.number().min(0).optional(),
},
{
fieldName: 'discountPrice',
label: '退款优惠',
component: 'InputNumber',
componentProps: {
placeholder: '付款优惠',
precision: 2,
formatter: erpPriceInputFormatter,
disabled: true,
style: { width: '100%' },
},
fieldName: 'discountPrice',
label: '付款优惠',
},
{
fieldName: 'discountedPrice',
label: '优惠后金额',
component: 'InputNumber',
componentProps: {
placeholder: '优惠后金额',
precision: 2,
formatter: erpPriceInputFormatter,
disabled: true,
style: { width: '100%' },
},
fieldName: 'discountedPrice',
label: '优惠后金额',
dependencies: {
triggerFields: ['totalPrice', 'otherPrice'],
componentProps: (values) => {
const totalPrice = values.totalPrice || 0;
const otherPrice = values.otherPrice || 0;
values.discountedPrice = totalPrice - otherPrice;
return {};
},
},
},
{
fieldName: 'otherPrice',
label: '其他费用',
component: 'InputNumber',
componentProps: {
disabled: formType === 'detail',
placeholder: '请输入其他费用',
precision: 2,
formatter: erpPriceInputFormatter,
style: { width: '100%' },
},
fieldName: 'otherPrice',
label: '其他费用',
},
{
fieldName: 'accountId',
label: '结算账户',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择结算账户',
@@ -183,26 +197,25 @@ export function useFormSchema(formType: string): VbenFormSchema[] {
value: 'id',
},
},
fieldName: 'accountId',
label: '结算账户',
},
{
fieldName: 'totalPrice',
label: '应退金额',
component: 'InputNumber',
componentProps: {
precision: 2,
style: { width: '100%' },
disabled: true,
min: 0,
disabled: true,
},
fieldName: 'totalPrice',
label: '应退金额',
rules: z.number().min(0).optional(),
},
];
}
/** 采购订单项表格列定义 */
export function usePurchaseOrderItemTableColumns(): VxeTableGridOptions['columns'] {
/** 表单的明细表格列 */
export function useFormItemColumns(
formData?: any[],
): VxeTableGridOptions['columns'] {
return [
{ type: 'seq', title: '序号', minWidth: 50, fixed: 'left' },
{
@@ -219,7 +232,7 @@ export function usePurchaseOrderItemTableColumns(): VxeTableGridOptions['columns
},
{
field: 'stockCount',
title: '仓库库存',
title: '库存',
minWidth: 80,
},
{
@@ -232,15 +245,27 @@ export function usePurchaseOrderItemTableColumns(): VxeTableGridOptions['columns
title: '单位',
minWidth: 80,
},
{
field: 'remark',
title: '备注',
minWidth: 150,
slots: { default: 'remark' },
},
{
field: 'inCount',
title: '已入库数量',
title: '已入库',
formatter: 'formatAmount3',
minWidth: 120,
fixed: 'right',
visible: formData && formData[0]?.inCount !== undefined,
},
{
field: 'returnCount',
title: '已退货',
formatter: 'formatAmount3',
minWidth: 120,
fixed: 'right',
visible: formData && formData[0]?.returnCount !== undefined,
},
{
field: 'count',
@@ -267,7 +292,8 @@ export function usePurchaseOrderItemTableColumns(): VxeTableGridOptions['columns
fixed: 'right',
field: 'taxPercent',
title: '税率(%)',
minWidth: 100,
minWidth: 105,
slots: { default: 'taxPercent' },
},
{
fixed: 'right',
@@ -283,10 +309,16 @@ export function usePurchaseOrderItemTableColumns(): VxeTableGridOptions['columns
minWidth: 120,
formatter: 'formatAmount2',
},
{
title: '操作',
width: 50,
fixed: 'right',
slots: { default: 'actions' },
},
];
}
/** 采购退货列表的搜索表单 */
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
@@ -294,7 +326,7 @@ export function useGridFormSchema(): VbenFormSchema[] {
label: '退货单号',
component: 'Input',
componentProps: {
placeholder: '请输入入库单号',
placeholder: '请输入退货单号',
allowClear: true,
},
},
@@ -318,10 +350,8 @@ export function useGridFormSchema(): VbenFormSchema[] {
label: '退货时间',
component: 'RangePicker',
componentProps: {
placeholder: ['开始时间', '结束时间'],
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
valueFormat: 'YYYY-MM-DD HH:mm:ss',
...getRangePickerDefaultProps(),
allowClear: true,
},
},
{
@@ -386,18 +416,18 @@ export function useGridFormSchema(): VbenFormSchema[] {
{ label: '部分退款', value: 1 },
{ label: '全部退款', value: 2 },
],
placeholder: '请选择退状态',
placeholder: '请选择退状态',
allowClear: true,
},
},
{
fieldName: 'status',
label: '状态',
label: '审批状态',
component: 'Select',
componentProps: {
placeholder: '请选择状态',
allowClear: true,
options: getDictOptions(DICT_TYPE.ERP_AUDIT_STATUS, 'number'),
placeholder: '请选择审批状态',
allowClear: true,
},
},
{
@@ -412,7 +442,7 @@ export function useGridFormSchema(): VbenFormSchema[] {
];
}
/** 采购退货列表的字段 */
/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{
@@ -428,7 +458,7 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
},
{
field: 'productNames',
title: '产品信息',
title: '退货产品信息',
showOverflow: 'tooltip',
minWidth: 120,
},
@@ -441,7 +471,7 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
field: 'returnTime',
title: '退货时间',
width: 160,
formatter: 'formatDateTime',
formatter: 'formatDate',
},
{
field: 'creatorName',
@@ -467,16 +497,16 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
minWidth: 120,
},
{
field: 'noRefundPrice',
field: 'unRefundPrice',
title: '未退金额',
minWidth: 120,
formatter: ({ row }) => {
return `${erpNumberFormatter(row.totalPrice - row.refundPrice, 2)}`;
},
minWidth: 120,
},
{
field: 'status',
title: '状态',
title: '审批状态',
minWidth: 120,
cellRender: {
name: 'CellDict',
@@ -485,13 +515,13 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
},
{
title: '操作',
minWidth: 250,
width: 220,
fixed: 'right',
slots: { default: 'actions' },
},
];
}
/** 采购订单列表的搜索表单 */
/** 列表的搜索表单 */
export function useOrderGridFormSchema(): VbenFormSchema[] {
return [
{
@@ -501,7 +531,6 @@ export function useOrderGridFormSchema(): VbenFormSchema[] {
componentProps: {
placeholder: '请输入订单单号',
allowClear: true,
disabled: true,
},
},
{
@@ -524,16 +553,14 @@ export function useOrderGridFormSchema(): VbenFormSchema[] {
label: '订单时间',
component: 'RangePicker',
componentProps: {
placeholder: ['开始时间', '结束时间'],
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
valueFormat: 'YYYY-MM-DD HH:mm:ss',
...getRangePickerDefaultProps(),
allowClear: true,
},
},
];
}
/** 采购订单列表的字段 */
/** 列表的字段 */
export function useOrderGridColumns(): VxeTableGridOptions['columns'] {
return [
{
@@ -577,13 +604,13 @@ export function useOrderGridColumns(): VxeTableGridOptions['columns'] {
},
{
field: 'inCount',
title: '入库数量',
title: '入库数量',
formatter: 'formatAmount3',
minWidth: 120,
},
{
field: 'returnCount',
title: '退货数量',
title: '退货数量',
formatter: 'formatAmount3',
minWidth: 120,
},

View File

@@ -0,0 +1,233 @@
<script lang="ts" setup>
import type { ErpPurchaseOrderApi } from '#/api/erp/purchase/order';
import type { ErpPurchaseReturnApi } from '#/api/erp/purchase/return';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { message } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
import { getAccountSimpleList } from '#/api/erp/finance/account';
import {
createPurchaseReturn,
getPurchaseReturn,
updatePurchaseReturn,
} from '#/api/erp/purchase/return';
import { useFormSchema } from '../data';
import ItemForm from './item-form.vue';
import PurchaseOrderSelect from './purchase-order-select.vue';
const emit = defineEmits(['success']);
const formData = ref<
ErpPurchaseReturnApi.PurchaseReturn & {
accountId?: number;
discountPercent?: number;
fileUrl?: string;
order?: ErpPurchaseOrderApi.PurchaseOrder;
orderId?: number;
orderNo?: string;
supplierId?: number;
}
>({
id: undefined,
no: undefined,
accountId: undefined,
returnTime: undefined,
remark: undefined,
fileUrl: undefined,
discountPercent: 0,
supplierId: undefined,
discountPrice: 0,
totalPrice: 0,
otherPrice: 0,
items: [],
});
const formType = ref(''); // 表单类型:'create' | 'edit' | 'detail'
const itemFormRef = ref<InstanceType<typeof ItemForm>>();
/* eslint-disable unicorn/no-nested-ternary */
const getTitle = computed(() =>
formType.value === 'create'
? $t('ui.actionTitle.create', ['采购退货'])
: formType.value === 'edit'
? $t('ui.actionTitle.edit', ['采购退货'])
: '采购退货详情',
);
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
labelWidth: 120,
},
wrapperClass: 'grid-cols-3',
layout: 'vertical',
schema: useFormSchema(formType.value),
showDefaultActions: false,
handleValuesChange: (values, changedFields) => {
// 目的:同步到 item-form 组件,触发整体的价格计算
if (formData.value) {
if (changedFields.includes('otherPrice')) {
formData.value.otherPrice = values.otherPrice;
}
if (changedFields.includes('discountPercent')) {
formData.value.discountPercent = values.discountPercent;
}
}
},
});
/** 更新采购退货项 */
const handleUpdateItems = (
items: ErpPurchaseReturnApi.PurchaseReturnItem[],
) => {
formData.value.items = items;
formApi.setValues({
items,
});
};
/** 更新其他费用 */
const handleUpdateOtherPrice = (otherPrice: number) => {
formApi.setValues({
otherPrice,
});
};
/** 更新优惠金额 */
const handleUpdateDiscountPrice = (discountPrice: number) => {
formApi.setValues({
discountPrice,
});
};
/** 更新总金额 */
const handleUpdateTotalPrice = (totalPrice: number) => {
formApi.setValues({
totalPrice,
});
};
/** 选择采购订单 */
const handleUpdateOrder = (order: ErpPurchaseOrderApi.PurchaseOrder) => {
formData.value = {
...formData.value,
orderId: order.id,
orderNo: order.no!,
supplierId: order.supplierId!,
accountId: order.accountId!,
remark: order.remark!,
discountPercent: order.discountPercent!,
fileUrl: order.fileUrl!,
};
// 将订单项设置到退货单项
order.items!.forEach((item: any) => {
item.totalCount = item.count;
item.count = item.inCount - item.returnCount;
item.orderItemId = item.id;
item.id = undefined;
});
formData.value.items = order.items!.filter(
(item) => item.count && item.count > 0,
) as ErpPurchaseReturnApi.PurchaseReturnItem[];
formApi.setValues(formData.value, false);
};
/** 创建或更新采购退货 */
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
const { valid } = await formApi.validate();
if (!valid) {
return;
}
const itemFormInstance = Array.isArray(itemFormRef.value)
? itemFormRef.value[0]
: itemFormRef.value;
try {
itemFormInstance.validate();
} catch (error: any) {
message.error(error.message || '子表单验证失败');
return;
}
modalApi.lock();
// 提交表单
const data =
(await formApi.getValues()) as ErpPurchaseReturnApi.PurchaseReturn;
try {
await (formType.value === 'create'
? createPurchaseReturn(data)
: updatePurchaseReturn(data));
// 关闭并提示
await modalApi.close();
emit('success');
message.success($t('ui.actionMessage.operationSuccess'));
} finally {
modalApi.unlock();
}
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
formData.value = undefined;
return;
}
// 加载数据
const data = modalApi.getData<{ id?: number; type: string }>();
formType.value = data.type;
formApi.setDisabled(formType.value === 'detail');
formApi.updateSchema(useFormSchema(formType.value));
if (!data || !data.id) {
// 新增时,默认选中账户
const accountList = await getAccountSimpleList();
const defaultAccount = accountList.find((item) => item.defaultStatus);
if (defaultAccount) {
await formApi.setValues({ accountId: defaultAccount.id });
}
return;
}
modalApi.lock();
try {
formData.value = await getPurchaseReturn(data.id);
// 设置到 values
await formApi.setValues(formData.value, false);
} finally {
modalApi.unlock();
}
},
});
</script>
<template>
<Modal
:title="getTitle"
class="w-3/4"
:show-confirm-button="formType !== 'detail'"
>
<Form class="mx-3">
<template #items>
<ItemForm
ref="itemFormRef"
:items="formData?.items ?? []"
:disabled="formType === 'detail'"
:discount-percent="formData?.discountPercent ?? 0"
:other-price="formData?.otherPrice ?? 0"
@update:items="handleUpdateItems"
@update:discount-price="handleUpdateDiscountPrice"
@update:other-price="handleUpdateOtherPrice"
@update:total-price="handleUpdateTotalPrice"
/>
</template>
<template #orderNo>
<PurchaseOrderSelect
:order-no="formData?.orderNo"
@update:order="handleUpdateOrder"
/>
</template>
</Form>
</Modal>
</template>

View File

@@ -0,0 +1,293 @@
<script lang="ts" setup>
import type { ErpPurchaseReturnApi } from '#/api/erp/purchase/return';
import { computed, nextTick, onMounted, ref, watch } from 'vue';
import {
erpCountInputFormatter,
erpPriceInputFormatter,
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 { getWarehouseStockCount } from '#/api/erp/stock/stock';
import { getWarehouseSimpleList } from '#/api/erp/stock/warehouse';
import { useFormItemColumns } from '../data';
interface Props {
items?: ErpPurchaseReturnApi.PurchaseReturnItem[];
disabled?: boolean;
discountPercent?: number;
otherPrice?: number;
}
const props = withDefaults(defineProps<Props>(), {
items: () => [],
disabled: false,
discountPercent: 0,
otherPrice: 0,
});
const emit = defineEmits([
'update:items',
'update:discount-price',
'update:other-price',
'update:total-price',
]);
const tableData = ref<ErpPurchaseReturnApi.PurchaseReturnItem[]>([]); // 表格数据
const productOptions = ref<any[]>([]); // 产品下拉选项
const warehouseOptions = 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({
gridOptions: {
columns: useFormItemColumns(tableData.value),
data: tableData.value,
minHeight: 250,
autoResize: true,
border: true,
rowConfig: {
keyField: 'row_id',
isHover: true,
},
pagerConfig: {
enabled: false,
},
toolbarConfig: {
enabled: false,
},
},
});
/** 监听外部传入的列数据 */
watch(
() => props.items,
async (items) => {
if (!items) {
return;
}
items.forEach((item) => initRow(item));
tableData.value = [...items];
await nextTick(); // 特殊:保证 gridApi 已经初始化
await gridApi.grid.reloadData(tableData.value);
// 更新表格列配置(目的:已入库、已退货动态列)
const columns = useFormItemColumns(tableData.value);
await gridApi.grid.reloadColumn(columns);
},
{
immediate: true,
},
);
/** 计算 discountPrice、otherPrice、totalPrice 价格 */
watch(
() => [tableData.value, props.discountPercent, props.otherPrice],
() => {
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 discountedPrice = totalPrice - discountPrice!;
const finalTotalPrice = discountedPrice + (props.otherPrice || 0);
// 通知父组件更新
emit('update:discount-price', discountPrice);
emit('update:other-price', props.otherPrice || 0);
emit('update:total-price', finalTotalPrice);
},
{ deep: true },
);
/** 处理删除 */
function handleDelete(row: ErpPurchaseReturnApi.PurchaseReturnItem) {
const index = tableData.value.findIndex((item) => item.id === row.id);
if (index !== -1) {
tableData.value.splice(index, 1);
}
// 通知父组件更新
emit('update:items', [...tableData.value]);
}
/** 处理仓库变更 */
const handleWarehouseChange = async (row: ErpPurchaseReturnApi.PurchaseReturnItem) => {
const stockCount = await getWarehouseStockCount({
productId: row.productId!,
warehouseId: row.warehouseId!,
});
row.stockCount = stockCount || 0;
handleRowChange(row);
};
/** 处理行数据变更 */
function handleRowChange(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 initRow = (row: ErpPurchaseReturnApi.PurchaseReturnItem): void => {
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;
}
};
/** 表单校验 */
function validate() {
for (let i = 0; i < tableData.value.length; i++) {
const item = tableData.value[i];
if (item) {
if (!item.warehouseId) {
throw new Error(`${i + 1} 行:仓库不能为空`);
}
if (!item.count || item.count <= 0) {
throw new Error(`${i + 1} 行:产品数量不能为空`);
}
}
}
}
defineExpose({
validate,
});
/** 初始化 */
onMounted(async () => {
productOptions.value = await getProductSimpleList();
warehouseOptions.value = await getWarehouseSimpleList();
});
</script>
<template>
<Grid class="w-full">
<template #warehouseId="{ row }">
<Select
v-model:value="row.warehouseId"
:options="warehouseOptions"
:field-names="{ label: 'name', value: 'id' }"
placeholder="请选择仓库"
:disabled="disabled"
show-search
class="w-full"
@change="handleWarehouseChange(row)"
/>
</template>
<template #productId="{ row }">
<Select
disabled
v-model:value="row.productId"
:options="productOptions"
:field-names="{ label: 'name', value: 'id' }"
class="w-full"
placeholder="请选择产品"
show-search
/>
</template>
<template #count="{ row }">
<InputNumber
v-if="!disabled"
v-model:value="row.count"
:min="0"
:precision="2"
@change="handleRowChange(row)"
/>
<span v-else>{{ row.count || '-' }}</span>
</template>
<template #productPrice="{ row }">
<InputNumber
disabled
v-model:value="row.productPrice"
:min="0"
:precision="2"
@change="handleRowChange(row)"
/>
</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 }">
<InputNumber
v-if="!disabled"
v-model:value="row.taxPercent"
:min="0"
:max="100"
:precision="2"
@change="handleRowChange(row)"
/>
<span v-else>{{ row.taxPercent || '-' }}</span>
</template>
<template #actions="{ row }">
<TableAction
v-if="!disabled"
:actions="[
{
label: '删除',
type: 'link',
danger: true,
popConfirm: {
title: '确认删除该产品吗?',
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</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>
</template>
</Grid>
</template>

View File

@@ -7,7 +7,7 @@ import { IconifyIcon } from '@vben/icons';
import { Input, message, Modal } from 'ant-design-vue';
import SelectPurchaseOrderGrid from './select-purchase-order-grid.vue';
import PurchaseOrderGrid from './purchase-order-grid.vue';
const props = defineProps({
orderNo: {
@@ -65,6 +65,6 @@ const handleOk = () => {
:show-confirm-button="true"
@ok="handleOk"
>
<SelectPurchaseOrderGrid @select-row="handleSelectOrder" />
<PurchaseOrderGrid @select-row="handleSelectOrder" />
</Modal>
</template>

View File

@@ -1,313 +0,0 @@
<script lang="ts" setup>
import type { ErpPurchaseOrderApi } from '#/api/erp/purchase/order';
import type { ErpPurchaseReturnApi } from '#/api/erp/purchase/return';
import { computed, nextTick, ref, watch } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { message } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
import {
createPurchaseReturn,
getPurchaseReturn,
updatePurchaseReturn,
} from '#/api/erp/purchase/return';
import { useFormSchema } from '../data';
import PurchaseReturnItemForm from './purchase-return-item-form.vue';
import SelectPurchaseOrderForm from './select-purchase-order-form.vue';
const emit = defineEmits(['success']);
const formData = ref<
ErpPurchaseReturnApi.PurchaseReturn & {
accountId?: number;
discountedPrice?: number;
discountPercent?: number;
fileUrl?: string;
orderId?: number;
orderNo?: string;
supplierId?: number;
}
>({
id: undefined,
no: undefined,
accountId: undefined,
returnTime: undefined,
remark: undefined,
fileUrl: undefined,
discountPercent: 0,
supplierId: undefined,
discountPrice: 0,
totalPrice: 0,
otherPrice: 0,
discountedPrice: 0,
items: [],
});
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(formType.value),
showDefaultActions: false,
handleValuesChange: (values, changedFields) => {
if (formData.value && changedFields.includes('otherPrice')) {
formData.value.otherPrice = values.otherPrice;
formData.value.totalPrice =
(formData.value.discountedPrice || 0) +
(formData.value.otherPrice || 0);
formApi.setValues(formData.value, false);
}
},
});
// TODO @XuZhiqiang注释风格 /** */
// 更新采购退货项
const handleUpdateItems = async (
items: ErpPurchaseReturnApi.PurchaseReturnItem[],
) => {
if (formData.value) {
const data =
(await formApi.getValues()) as ErpPurchaseReturnApi.PurchaseReturn;
formData.value = { ...data, items };
await formApi.setValues(formData.value, false);
}
};
// 选择采购订单
const handleUpdateOrder = (order: ErpPurchaseOrderApi.PurchaseOrder) => {
formData.value = {
...formData.value,
orderId: order.id,
orderNo: order.no!,
supplierId: order.supplierId!,
accountId: order.accountId!,
remark: order.remark!,
discountPercent: order.discountPercent!,
fileUrl: order.fileUrl!,
};
// 将订单项设置到入库单项
order.items!.forEach((item: any) => {
item.totalCount = item.count;
item.count = item.inCount - item.returnCount;
item.orderItemId = item.id;
item.id = undefined;
});
formData.value.items = order.items!.filter(
(item) => item.count && item.count > 0,
) as ErpPurchaseReturnApi.PurchaseReturnItem[];
formApi.setValues(formData.value, false);
};
watch(
() => formData.value.items!,
(newItems: ErpPurchaseReturnApi.PurchaseReturnItem[]) => {
if (newItems && newItems.length > 0) {
// 计算每个产品的总价、税额和总价
newItems.forEach((item) => {
item.totalProductPrice = (item.productPrice || 0) * (item.count || 0);
item.taxPrice =
(item.totalProductPrice || 0) * ((item.taxPercent || 0) / 100);
item.totalPrice = (item.totalProductPrice || 0) + (item.taxPrice || 0);
});
// 计算总价
formData.value.totalPrice = newItems.reduce((sum, item) => {
return sum + (item.totalProductPrice || 0) + (item.taxPrice || 0);
}, 0);
} else {
formData.value.totalPrice = 0;
}
// 优惠金额
formData.value.discountPrice =
((formData.value.totalPrice || 0) *
(formData.value.discountPercent || 0)) /
100;
// 优惠后价格
formData.value.discountedPrice =
formData.value.totalPrice - formData.value.discountPrice;
// 计算最终价格(包含其他费用)
formData.value.totalPrice =
formData.value.discountedPrice + (formData.value.otherPrice || 0);
formApi.setValues(formData.value, false);
},
{ immediate: true },
);
/** 创建或更新采购退货 */
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: any) {
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: ErpPurchaseReturnApi.PurchaseReturn = await formApi.getValues();
data.items = formData.value?.items?.map((item) => ({
...item,
// 解决新增采购退货报错
id: undefined,
}));
try {
await (formType.value === 'create'
? createPurchaseReturn(data)
: updatePurchaseReturn(data));
// 关闭并提示
await modalApi.close();
emit('success');
message.success(formType.value === 'create' ? '新增成功' : '更新成功');
} finally {
modalApi.unlock();
}
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
formData.value = {
id: undefined,
no: undefined,
accountId: undefined,
returnTime: undefined,
remark: undefined,
fileUrl: undefined,
discountPercent: 0,
supplierId: undefined,
discountPrice: 0,
totalPrice: 0,
otherPrice: 0,
items: [],
};
formApi.setValues(formData.value, false);
return;
}
// 加载数据
const data = modalApi.getData<{ id?: number; type: string }>();
if (!data) {
return;
}
formType.value = data.type;
formApi.updateSchema(useFormSchema(formType.value));
if (!data.id) {
// 初始化空的表单数据
formData.value = {
id: undefined,
no: undefined,
accountId: undefined,
returnTime: undefined,
remark: undefined,
fileUrl: undefined,
discountPercent: 0,
supplierId: undefined,
discountPrice: 0,
totalPrice: 0,
otherPrice: 0,
items: [],
} as unknown as ErpPurchaseReturnApi.PurchaseReturn;
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 getPurchaseReturn(data.id);
// 设置到 values
await formApi.setValues(formData.value, false);
// 初始化子表单
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-2/3"
:closable="true"
:mask-closable="true"
:show-confirm-button="formType !== 'detail'"
>
<Form class="mx-3">
<template #product="slotProps">
<PurchaseReturnItemForm
v-bind="slotProps"
ref="itemFormRef"
class="w-full"
:items="formData?.items ?? []"
:disabled="formType === 'detail'"
@update:items="handleUpdateItems"
/>
</template>
<template #orderNo="slotProps">
<SelectPurchaseOrderForm
v-bind="slotProps"
:order-no="formData?.orderNo"
@update:order="handleUpdateOrder"
/>
</template>
</Form>
</Modal>
</template>

View File

@@ -1,261 +0,0 @@
<script lang="ts" setup>
import type { ErpPurchaseReturnApi } from '#/api/erp/purchase/return';
import { nextTick, onMounted, ref, watch } from 'vue';
import { erpPriceMultiply } from '@vben/utils';
import { InputNumber, Select } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getProductSimpleList } from '#/api/erp/product/product';
import { getWarehouseStockCount } from '#/api/erp/stock/stock';
import { getWarehouseSimpleList } from '#/api/erp/stock/warehouse';
import { usePurchaseOrderItemTableColumns } from '../data';
const props = withDefaults(defineProps<Props>(), {
items: () => [],
disabled: false,
});
const emit = defineEmits(['update:items', 'update:totalPrice']);
interface Props {
items?: ErpPurchaseReturnApi.PurchaseReturnItem[];
disabled?: boolean;
}
const tableData = ref<ErpPurchaseReturnApi.PurchaseReturnItem[]>([]);
const productOptions = ref<any[]>([]);
const warehouseOptions = ref<any[]>([]);
/** 表格配置 */
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions: {
editConfig: {
trigger: 'click',
mode: 'cell',
},
columns: usePurchaseOrderItemTableColumns(),
data: tableData.value,
border: true,
showOverflow: true,
autoResize: true,
minHeight: 150,
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();
await gridApi.grid.reloadData(tableData.value);
},
{
immediate: true,
},
);
/** 初始化 */
onMounted(async () => {
productOptions.value = await getProductSimpleList();
warehouseOptions.value = await getWarehouseSimpleList();
});
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);
}
const handleWarehouseChange = async (
row: ErpPurchaseReturnApi.PurchaseReturnItem,
) => {
const warehouseId = row.warehouseId;
const stockCount = await getWarehouseStockCount({
productId: row.productId!,
warehouseId: warehouseId!,
});
row.stockCount = stockCount || 0;
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;
} => {
const count = tableData.value.reduce(
(sum, item) => sum + (item.count || 0),
0,
);
const totalProductPrice = tableData.value.reduce(
(sum, item) => sum + (item.totalProductPrice || 0),
0,
);
const taxPrice = tableData.value.reduce(
(sum, item) => sum + (item.taxPrice || 0),
0,
);
const totalPrice = tableData.value.reduce(
(sum, item) => sum + (item.totalPrice || 0),
0,
);
return {
productName: '合计',
count,
totalProductPrice,
taxPrice,
totalPrice,
};
};
const validate = async (): Promise<boolean> => {
try {
for (let i = 0; i < tableData.value.length; i++) {
const item = tableData.value[i];
if (item) {
if (!item.warehouseId) {
throw new Error(`${i + 1} 行:仓库不能为空`);
}
if (!item.count || item.count <= 0) {
throw new Error(`${i + 1} 行:产品数量不能为空`);
}
}
}
return true;
} catch (error) {
console.error('验证失败:', error);
throw error;
}
};
const getData = (): ErpPurchaseReturnApi.PurchaseReturnItem[] =>
tableData.value;
const init = (
items: ErpPurchaseReturnApi.PurchaseReturnItem[] | 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;
})
: [];
// TODO @XuZhiqiang: await 风格;
nextTick(() => {
gridApi.grid.reloadData(tableData.value);
});
};
defineExpose({
validate,
getData,
init,
});
</script>
<template>
<Grid class="w-full">
<template #warehouseId="{ row }">
<Select
v-model:value="row.warehouseId"
:options="warehouseOptions"
:field-names="{ label: 'name', value: 'id' }"
placeholder="请选择仓库"
:disabled="disabled"
show-search
class="w-full"
@change="handleWarehouseChange(row)"
/>
</template>
<template #productId="{ row }">
<Select
disabled
v-model:value="row.productId"
:options="productOptions"
:field-names="{ label: 'name', value: 'id' }"
style="width: 100%"
placeholder="请选择产品"
show-search
/>
</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
disabled
v-model:value="row.productPrice"
:min="0"
:precision="2"
@change="handlePriceChange(row)"
/>
</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>
</template>
</Grid>
</template>