feat:【antd】【erp 系统】sale/return 重构初始化

This commit is contained in:
YunaiV
2025-10-04 15:16:51 +08:00
parent 480ed5c83d
commit f63cb9ed2f
9 changed files with 800 additions and 845 deletions

View File

@@ -11,44 +11,39 @@ import { getProductSimpleList } from '#/api/erp/product/product';
import { getCustomerSimpleList } from '#/api/erp/sale/customer';
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: '退货单号',
},
{
component: 'ApiSelect',
fieldName: 'returnTime',
label: '退货时间',
component: 'DatePicker',
componentProps: {
disabled: true,
placeholder: '选择客户',
allowClear: true,
showSearch: true,
api: getCustomerSimpleList,
fieldNames: {
label: 'name',
value: 'id',
},
disabled: formType === 'detail',
placeholder: '选择退货时间',
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
valueFormat: 'x',
},
fieldName: 'customerId',
label: '客户',
rules: 'required',
},
{
@@ -63,35 +58,53 @@ export function useFormSchema(formType: string): VbenFormSchema[] {
},
},
{
component: 'DatePicker',
fieldName: 'customerId',
label: '客户',
component: 'ApiSelect',
componentProps: {
disabled: formType === 'detail',
placeholder: '选择退货时间',
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
valueFormat: 'x',
style: { width: '100%' },
disabled: true,
placeholder: '选择客户',
allowClear: true,
showSearch: true,
api: getCustomerSimpleList,
fieldNames: {
label: 'name',
value: 'id',
},
},
fieldName: 'returnTime',
label: '退货时间',
rules: 'required',
},
{
fieldName: 'saleUserId',
label: '销售人员',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择销售人员',
allowClear: true,
showSearch: true,
api: getSimpleUserList,
fieldNames: {
label: 'nickname',
value: 'id',
},
},
},
{
fieldName: 'remark',
label: '备注',
component: 'Textarea',
componentProps: {
placeholder: '请输入备注',
disabled: formType === 'detail',
autoSize: { minRows: 1, maxRows: 1 },
class: 'w-full',
disabled: formType === 'detail',
},
fieldName: 'remark',
formItemClass: 'col-span-2',
label: '备注',
},
{
fieldName: 'fileUrl',
label: '附件',
component: 'FileUpload',
componentProps: {
disabled: formType === 'detail',
maxNumber: 1,
maxSize: 10,
accept: [
@@ -105,69 +118,65 @@ 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',
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: '优惠后金额',
},
{
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: '请选择结算账户',
@@ -180,26 +189,23 @@ 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 useSaleReturnItemTableColumns(): VxeTableGridOptions['columns'] {
/** 表单的明细表格列 */
export function useFormItemColumns(): VxeTableGridOptions['columns'] {
return [
{ type: 'seq', title: '序号', minWidth: 50, fixed: 'left' },
{
@@ -216,7 +222,7 @@ export function useSaleReturnItemTableColumns(): VxeTableGridOptions['columns']
},
{
field: 'stockCount',
title: '仓库库存',
title: '库存',
minWidth: 80,
},
{
@@ -229,6 +235,12 @@ export function useSaleReturnItemTableColumns(): VxeTableGridOptions['columns']
title: '单位',
minWidth: 80,
},
{
field: 'remark',
title: '备注',
minWidth: 150,
slots: { default: 'remark' },
},
{
field: 'totalCount',
title: '原数量',
@@ -266,7 +278,8 @@ export function useSaleReturnItemTableColumns(): VxeTableGridOptions['columns']
fixed: 'right',
field: 'taxPercent',
title: '税率(%)',
minWidth: 100,
minWidth: 105,
slots: { default: 'taxPercent' },
},
{
fixed: 'right',
@@ -282,6 +295,12 @@ export function useSaleReturnItemTableColumns(): VxeTableGridOptions['columns']
minWidth: 120,
formatter: 'formatAmount2',
},
{
title: '操作',
width: 50,
fixed: 'right',
slots: { default: 'actions' },
},
];
}
@@ -317,10 +336,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,
},
},
{
@@ -378,26 +395,26 @@ export function useGridFormSchema(): VbenFormSchema[] {
},
{
fieldName: 'refundStatus',
label: '退状态',
label: '退状态',
component: 'Select',
componentProps: {
options: [
{ label: '未退', value: 0 },
{ label: '部分退', value: 1 },
{ label: '全部退', value: 2 },
{ label: '未退', value: 0 },
{ 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,
},
},
{
@@ -456,7 +473,7 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
},
{
field: 'totalPrice',
title: '应退金额',
title: '应金额',
formatter: 'formatAmount2',
minWidth: 120,
},
@@ -476,7 +493,7 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
},
{
field: 'status',
title: '状态',
title: '审批状态',
minWidth: 120,
cellRender: {
name: 'CellDict',
@@ -485,12 +502,13 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
},
{
title: '操作',
minWidth: 250,
width: 220,
fixed: 'right',
slots: { default: 'actions' },
},
];
}
/** 列表的搜索表单 */
export function useOrderGridFormSchema(): VbenFormSchema[] {
return [
@@ -501,7 +519,6 @@ export function useOrderGridFormSchema(): VbenFormSchema[] {
componentProps: {
placeholder: '请输入订单单号',
allowClear: true,
disabled: true,
},
},
{
@@ -524,10 +541,8 @@ 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,
},
},
];

View File

@@ -19,7 +19,7 @@ import {
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
import SaleReturnForm from './modules/sale-return-form.vue';
import SaleReturnForm from './modules/form.vue';
/** ERP 销售退货列表 */
defineOptions({ name: 'ErpSaleReturn' });
@@ -30,11 +30,59 @@ const [FormModal, formModalApi] = useVbenModal({
});
/** 刷新表格 */
function onRefresh() {
function handleRefresh() {
gridApi.query();
}
// TODO @Xuzhiqiang批量删除待实现
/** 导出表格 */
async function handleExport() {
const data = await exportSaleReturn(await gridApi.formApi.getValues());
downloadFileFromBlobPart({ fileName: '销售退货.xls', source: data });
}
/** 新增销售退货 */
function handleCreate() {
formModalApi.setData({ type: 'create' }).open();
}
/** 编辑销售退货 */
function handleEdit(row: ErpSaleReturnApi.SaleReturn) {
formModalApi.setData({ type: 'edit', id: row.id }).open();
}
/** 删除销售退货 */
async function handleDelete(ids: number[]) {
const hideLoading = message.loading({
content: $t('ui.actionMessage.deleting'),
duration: 0,
});
try {
await deleteSaleReturn(ids);
message.success($t('ui.actionMessage.deleteSuccess'));
handleRefresh();
} finally {
hideLoading();
}
}
/** 审批/反审批操作 */
async function handleUpdateStatus(
row: ErpSaleReturnApi.SaleReturn,
status: number,
) {
const hideLoading = message.loading({
content: `确定${status === 20 ? '审批' : '反审批'}该订单吗?`,
duration: 0,
});
try {
await updateSaleReturnStatus(row.id!, status);
message.success(`${status === 20 ? '审批' : '反审批'}成功`);
handleRefresh();
} finally {
hideLoading();
}
}
const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
records,
@@ -44,69 +92,11 @@ function handleRowCheckboxChange({
checkedIds.value = records.map((item) => item.id!);
}
/** 详情 */
/** 查看详情 */
function handleDetail(row: ErpSaleReturnApi.SaleReturn) {
formModalApi.setData({ type: 'detail', id: row.id }).open();
}
/** 新增 */
function handleCreate() {
formModalApi.setData({ type: 'create' }).open();
}
/** 编辑 */
function handleEdit(row: ErpSaleReturnApi.SaleReturn) {
formModalApi.setData({ type: 'update', id: row.id }).open();
}
/** 删除 */
async function handleDelete(ids: number[]) {
const hideLoading = message.loading({
content: $t('ui.actionMessage.deleting'),
duration: 0,
key: 'action_process_msg',
});
try {
await deleteSaleReturn(ids);
message.success({
content: $t('ui.actionMessage.deleteSuccess'),
key: 'action_process_msg',
});
onRefresh();
} finally {
hideLoading();
}
}
/** 审批/反审批操作 */
function handleUpdateStatus(row: ErpSaleReturnApi.SaleReturn, status: number) {
const hideLoading = message.loading({
content: `确定${status === 20 ? '审批' : '反审批'}该订单吗?`,
duration: 0,
key: 'action_process_msg',
});
updateSaleReturnStatus({ id: row.id!, status })
.then(() => {
message.success({
content: `${status === 20 ? '审批' : '反审批'}成功`,
key: 'action_process_msg',
});
onRefresh();
})
.catch(() => {
// 处理错误
})
.finally(() => {
hideLoading();
});
}
/** 导出 */
async function handleExport() {
const data = await exportSaleReturn(await gridApi.formApi.getValues());
downloadFileFromBlobPart({ fileName: '销售退货.xls', source: data });
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
@@ -150,8 +140,8 @@ const [Grid, gridApi] = useVbenVxeGrid({
url="https://doc.iocoder.cn/erp/sale/"
/>
</template>
<FormModal @success="onRefresh" />
<FormModal @success="handleRefresh" />
<Grid table-title="销售退货列表">
<template #toolbar-tools>
<TableAction
@@ -178,11 +168,8 @@ const [Grid, gridApi] = useVbenVxeGrid({
icon: ACTION_ICON.DELETE,
auth: ['erp:sale-return:delete'],
popConfirm: {
disabled: isEmpty(checkedIds),
title: `是否删除所选中数据?`,
confirm: () => {
handleDelete(checkedIds);
},
confirm: handleDelete.bind(null, checkedIds),
},
},
]"
@@ -227,7 +214,7 @@ const [Grid, gridApi] = useVbenVxeGrid({
auth: ['erp:sale-return:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.no]),
confirm: () => handleDelete([row.id!]),
confirm: handleDelete.bind(null, [row.id!]),
},
},
]"

View File

@@ -0,0 +1,238 @@
<script lang="ts" setup>
import type { ErpSaleOrderApi } from '#/api/erp/sale/order';
import type { ErpSaleReturnApi } from '#/api/erp/sale/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 {
createSaleReturn,
getSaleReturn,
updateSaleReturn,
} from '#/api/erp/sale/return';
import { useFormSchema } from '../data';
import ItemForm from './item-form.vue';
import SaleOrderSelect from './sale-order-select.vue';
const emit = defineEmits(['success']);
const formData = ref<
ErpSaleReturnApi.SaleReturn & {
accountId?: number;
customerId?: number;
discountedPrice?: number;
discountPercent?: number;
fileUrl?: string;
order?: ErpSaleOrderApi.SaleOrder;
orderId?: number;
orderNo?: string;
}
>({
id: undefined,
no: undefined,
accountId: undefined,
returnTime: undefined,
remark: undefined,
fileUrl: undefined,
discountPercent: 0,
customerId: undefined,
discountPrice: 0,
totalPrice: 0,
otherPrice: 0,
discountedPrice: 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: ErpSaleReturnApi.SaleReturnItem[]) => {
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: ErpSaleOrderApi.SaleOrder) => {
formData.value = {
...formData.value,
orderId: order.id,
orderNo: order.no!,
customerId: order.customerId!,
accountId: order.accountId!,
remark: order.remark!,
discountPercent: order.discountPercent!,
fileUrl: order.fileUrl!,
};
// 将订单项设置到退货单项
order.items!.forEach((item: any) => {
item.totalCount = item.count;
item.count = item.totalCount - item.returnCount;
item.orderItemId = item.id;
item.id = undefined;
});
formData.value.items = order.items!.filter(
(item) => item.count && item.count > 0,
) as ErpSaleReturnApi.SaleReturnItem[];
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 ErpSaleReturnApi.SaleReturn;
try {
await (formType.value === 'create'
? createSaleReturn(data)
: updateSaleReturn(data));
// 关闭并提示
await modalApi.close();
emit('success');
message.success($t('ui.actionMessage.operationSuccess'));
} 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,
customerId: undefined,
discountPrice: 0,
totalPrice: 0,
otherPrice: 0,
items: [],
};
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) {
return;
}
modalApi.lock();
try {
formData.value = await getSaleReturn(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>
<SaleOrderSelect
:order-no="formData?.orderNo"
@update:order="handleUpdateOrder"
/>
</template>
</Form>
</Modal>
</template>

View File

@@ -0,0 +1,291 @@
<script lang="ts" setup>
import type { ErpSaleReturnApi } from '#/api/erp/sale/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?: ErpSaleReturnApi.SaleReturnItem[];
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<ErpSaleReturnApi.SaleReturnItem[]>([]); // 表格数据
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(),
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);
},
{
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: ErpSaleReturnApi.SaleReturnItem) {
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: ErpSaleReturnApi.SaleReturnItem) => {
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: ErpSaleReturnApi.SaleReturnItem): 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-if="!disabled"
v-model:value="row.warehouseId"
:options="warehouseOptions"
:field-names="{ label: 'name', value: 'id' }"
class="w-full"
placeholder="请选择仓库"
show-search
@change="handleWarehouseChange(row)"
/>
<span v-else>{{ row.warehouseName || '-' }}</span>
</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

@@ -0,0 +1,117 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { ErpSaleOrderApi } from '#/api/erp/sale/order';
import { ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { Input, message, Modal } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getSaleOrderPage } from '#/api/erp/sale/order';
import { useOrderGridColumns, useOrderGridFormSchema } from '../data';
defineProps({
orderNo: {
type: String,
default: () => undefined,
},
disabled: {
type: Boolean,
default: false,
},
});
const emit = defineEmits<{
'update:order': [order: ErpSaleOrderApi.SaleOrder];
}>();
const order = ref<ErpSaleOrderApi.SaleOrder>(); // 选择的销售订单
const open = ref<boolean>(false); // 选择销售订单弹窗是否打开
/** 表格配置 */
const [Grid] = useVbenVxeGrid({
formOptions: {
schema: useOrderGridFormSchema(),
},
gridOptions: {
columns: useOrderGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getSaleOrderPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
returnEnable: true,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
radioConfig: {
trigger: 'row',
highlight: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<ErpSaleOrderApi.SaleOrder>,
gridEvents: {
radioChange: ({ row }: { row: ErpSaleOrderApi.SaleOrder }) => {
handleSelectOrder(row);
},
},
});
/** 选择销售订单 */
function handleSelectOrder(selectOrder: ErpSaleOrderApi.SaleOrder) {
order.value = selectOrder;
}
/** 确认选择销售订单 */
const handleOk = () => {
if (!order.value) {
message.warning('请选择一个销售订单');
return;
}
emit('update:order', order.value);
open.value = false;
};
</script>
<template>
<Input
readonly
:value="orderNo"
:disabled="disabled"
@click="() => !disabled && (open = true)"
>
<template #addonAfter>
<div>
<IconifyIcon
class="h-full w-6 cursor-pointer"
icon="ant-design:setting-outlined"
:style="{ cursor: disabled ? 'not-allowed' : 'pointer' }"
@click="() => !disabled && (open = true)"
/>
</div>
</template>
</Input>
<Modal
class="!w-[50vw]"
v-model:open="open"
title="选择关联订单"
@ok="handleOk"
>
<Grid class="max-h-[600px]" table-title="销售订单列表(仅展示可退货)" />
</Modal>
</template>

View File

@@ -1,312 +0,0 @@
<script lang="ts" setup>
import type { ErpSaleOrderApi } from '#/api/erp/sale/order';
import type { ErpSaleReturnApi } from '#/api/erp/sale/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 {
createSaleReturn,
getSaleReturn,
updateSaleReturn,
} from '#/api/erp/sale/return';
import { useFormSchema } from '../data';
import SaleReturnItemForm from './sale-return-item-form.vue';
import SelectSaleOrderForm from './select-sale-order-form.vue';
const emit = defineEmits(['success']);
const formData = ref<
ErpSaleReturnApi.SaleReturn & {
accountId?: number;
customerId?: number;
discountedPrice?: number;
discountPercent?: number;
fileUrl?: string;
order?: ErpSaleOrderApi.SaleOrder;
orderId?: number;
orderNo?: string;
}
>({
id: undefined,
no: undefined,
accountId: undefined,
returnTime: undefined,
remark: undefined,
fileUrl: undefined,
discountPercent: 0,
customerId: 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);
}
},
});
/** 更新销售退货项 */
const handleUpdateItems = async (items: ErpSaleReturnApi.SaleReturnItem[]) => {
if (formData.value) {
const data = await formApi.getValues();
formData.value = { ...data, items };
await formApi.setValues(formData.value, false);
}
};
/** 选择采购订单 */
const handleUpdateOrder = (order: ErpSaleOrderApi.SaleOrder) => {
formData.value = {
...formData.value,
orderId: order.id,
orderNo: order.no!,
customerId: order.customerId!,
accountId: order.accountId!,
remark: order.remark!,
discountPercent: order.discountPercent!,
fileUrl: order.fileUrl!,
};
// 将订单项设置到入库单项
order.items!.forEach((item: any) => {
item.totalCount = item.count;
item.count = item.totalCount - item.returnCount;
item.orderItemId = item.id;
item.id = undefined;
});
formData.value.items = order.items!.filter(
(item) => item.count && item.count > 0,
) as ErpSaleReturnApi.SaleReturnItem[];
formApi.setValues(formData.value, false);
};
watch(
() => formData.value.items!,
(newItems: ErpSaleReturnApi.SaleReturnItem[]) => {
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 = (await formApi.getValues()) as ErpSaleReturnApi.SaleReturn;
data.items = formData.value?.items?.map((item) => ({
...item,
// 解决新增销售退货报错
id: undefined,
}));
try {
await (formType.value === 'create'
? createSaleReturn(data)
: updateSaleReturn(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,
customerId: undefined,
discountPrice: 0,
totalPrice: 0,
otherPrice: 0,
items: [],
};
await 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,
customerId: undefined,
discountPrice: 0,
totalPrice: 0,
otherPrice: 0,
items: [],
} as unknown as ErpSaleReturnApi.SaleReturn;
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 getSaleReturn(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">
<SaleReturnItemForm
v-bind="slotProps"
ref="itemFormRef"
class="w-full"
:items="formData?.items ?? []"
:disabled="formType === 'detail'"
@update:items="handleUpdateItems"
/>
</template>
<template #orderNo="slotProps">
<SelectSaleOrderForm
v-bind="slotProps"
:order-no="formData?.orderNo"
@update:order="handleUpdateOrder"
/>
</template>
</Form>
</Modal>
</template>

View File

@@ -1,256 +0,0 @@
<script lang="ts" setup>
import type { ErpSaleOutApi } from '#/api/erp/sale/out';
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 { useSaleReturnItemTableColumns } from '../data';
const props = withDefaults(defineProps<Props>(), {
items: () => [],
disabled: false,
});
const emit = defineEmits(['update:items', 'update:totalPrice']);
interface Props {
items?: ErpSaleOutApi.SaleOutItem[];
disabled?: boolean;
}
const tableData = ref<ErpSaleOutApi.SaleOutItem[]>([]);
const productOptions = ref<any[]>([]);
const warehouseOptions = ref<any[]>([]);
/** 表格配置 */
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions: {
editConfig: {
trigger: 'click',
mode: 'cell',
},
columns: useSaleReturnItemTableColumns(),
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,
},
);
/** 初始化 */
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: ErpSaleOutApi.SaleOutItem) => {
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 = (): ErpSaleOutApi.SaleOutItem[] => tableData.value;
const init = (items: ErpSaleOutApi.SaleOutItem[] | 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>

View File

@@ -1,70 +0,0 @@
<script lang="ts" setup>
import type { ErpSaleOrderApi } from '#/api/erp/sale/order';
import { ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { Input, message, Modal } from 'ant-design-vue';
import SelectSaleOrderGrid from './select-sale-order-grid.vue';
defineProps({
orderNo: {
type: String,
default: () => undefined,
},
disabled: {
type: Boolean,
default: false,
},
});
const emit = defineEmits<{
'update:order': [order: ErpSaleOrderApi.SaleOrder];
}>();
const order = ref<ErpSaleOrderApi.SaleOrder>();
const open = ref<boolean>(false);
const handleSelectOrder = (selectOrder: ErpSaleOrderApi.SaleOrder) => {
order.value = selectOrder;
};
const handleOk = () => {
if (!order.value) {
message.warning('请选择一个采购订单');
return;
}
emit('update:order', order.value);
open.value = false;
};
</script>
<template>
<Input
v-bind="$attrs"
readonly
:value="orderNo"
:disabled="disabled"
@click="() => !disabled && (open = true)"
>
<template #addonAfter>
<div>
<IconifyIcon
class="h-full w-6 cursor-pointer"
icon="ant-design:setting-outlined"
:style="{ cursor: disabled ? 'not-allowed' : 'pointer' }"
@click="() => !disabled && (open = true)"
/>
</div>
</template>
</Input>
<Modal
v-model:open="open"
title="选择关联订单"
class="!w-[50vw]"
:show-confirm-button="true"
@ok="handleOk"
>
<SelectSaleOrderGrid @select-row="handleSelectOrder" />
</Modal>
</template>

View File

@@ -1,55 +0,0 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { ErpSaleOrderApi } from '#/api/erp/sale/order';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getSaleOrderPage } from '#/api/erp/sale/order';
import { useOrderGridColumns, useOrderGridFormSchema } from '../data';
const emit = defineEmits(['selectRow']);
const [Grid] = useVbenVxeGrid({
formOptions: {
schema: useOrderGridFormSchema(),
},
gridOptions: {
columns: useOrderGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getSaleOrderPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
returnEnable: true,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
radioConfig: {
trigger: 'row',
highlight: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<ErpSaleOrderApi.SaleOrder>,
gridEvents: {
radioChange: ({ row }: { row: ErpSaleOrderApi.SaleOrder }) => {
emit('selectRow', row);
},
},
});
</script>
<template>
<Grid class="max-h-[600px]" table-title="销售订单列表(仅展示可退货)" />
</template>