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 { getSupplierSimpleList } from '#/api/erp/purchase/supplier';
import { getSimpleUserList } from '#/api/system/user';
import { getRangePickerDefaultProps } from '#/utils';
/** 表单的配置项 */
export function useFormSchema(): VbenFormSchema[] {
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: 'orderTime',
label: '订单时间',
component: 'DatePicker',
componentProps: {
placeholder: '选择订单时间',
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
valueFormat: 'x',
},
rules: 'required',
},
{
label: '供应商',
fieldName: 'supplierId',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择供应商',
@@ -45,35 +58,37 @@ export function useFormSchema(): VbenFormSchema[] {
value: 'id',
},
},
fieldName: 'supplierId',
label: '供应商',
rules: 'required',
},
{
component: 'DatePicker',
fieldName: 'purchaseUserId',
label: '创建人',
component: 'ApiSelect',
componentProps: {
placeholder: '选择订单时间',
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
valueFormat: 'x',
style: { width: '100%' },
placeholder: '选择创建人',
allowClear: true,
showSearch: true,
api: getSimpleUserList,
fieldNames: {
label: 'nickname',
value: 'id',
},
},
fieldName: 'orderTime',
label: '订单时间',
rules: 'required',
},
{
fieldName: 'remark',
label: '备注',
component: 'Textarea',
componentProps: {
placeholder: '请输入备注',
autoSize: { minRows: 2, maxRows: 4 },
class: 'w-full',
autoSize: { minRows: 1, maxRows: 1 },
disabled: formType === 'detail',
},
fieldName: 'remark',
label: '备注',
formItemClass: 'col-span-3',
formItemClass: 'col-span-2',
},
{
fieldName: 'fileUrl',
label: '附件',
component: 'FileUpload',
componentProps: {
maxNumber: 1,
@@ -89,56 +104,54 @@ export function useFormSchema(): 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',
},
{
fieldName: 'discountPercent',
label: '优惠率(%)',
component: 'InputNumber',
componentProps: {
placeholder: '请输入优惠率',
min: 0,
max: 100,
precision: 2,
style: { width: '100%' },
},
fieldName: 'discountPercent',
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: 'totalPrice',
label: '优惠后金额',
component: 'InputNumber',
componentProps: {
placeholder: '优惠后金额',
precision: 2,
formatter: erpPriceInputFormatter,
disabled: true,
style: { width: '100%' },
},
fieldName: 'totalPrice',
label: '优惠后金额',
},
{
fieldName: 'accountId',
label: '结算账户',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择结算账户',
@@ -150,15 +163,12 @@ export function useFormSchema(): VbenFormSchema[] {
value: 'id',
},
},
fieldName: 'accountId',
label: '结算账户',
},
{
component: 'InputNumber',
componentProps: {
placeholder: '请输入支付订金',
precision: 2,
style: { width: '100%' },
min: 0,
},
fieldName: 'depositPrice',
@@ -168,8 +178,8 @@ export function useFormSchema(): VbenFormSchema[] {
];
}
/** 采购订单项表格列定义 */
export function usePurchaseOrderItemTableColumns(): VxeTableGridOptions['columns'] {
/** 表单的明细表格列 */
export function useFormItemColumns(): VxeTableGridOptions['columns'] {
return [
{ type: 'seq', title: '序号', minWidth: 50, fixed: 'left' },
{
@@ -193,6 +203,12 @@ export function usePurchaseOrderItemTableColumns(): VxeTableGridOptions['columns
title: '单位',
minWidth: 80,
},
{
field: 'remark',
title: '备注',
minWidth: 150,
slots: { default: 'remark' },
},
{
field: 'count',
title: '数量',
@@ -214,7 +230,7 @@ export function usePurchaseOrderItemTableColumns(): VxeTableGridOptions['columns
{
field: 'taxPercent',
title: '税率(%)',
minWidth: 100,
minWidth: 105,
slots: { default: 'taxPercent' },
},
{
@@ -229,12 +245,6 @@ export function usePurchaseOrderItemTableColumns(): VxeTableGridOptions['columns
minWidth: 120,
formatter: 'formatAmount2',
},
{
field: 'remark',
title: '备注',
minWidth: 150,
slots: { default: 'remark' },
},
{
title: '操作',
width: 50,
@@ -254,7 +264,6 @@ export function useGridFormSchema(): VbenFormSchema[] {
componentProps: {
placeholder: '请输入订单单号',
allowClear: true,
disabled: true,
},
},
{
@@ -277,10 +286,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,
},
},
{
@@ -323,6 +330,29 @@ export function useGridFormSchema(): VbenFormSchema[] {
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',
label: '退货状态',
@@ -369,7 +399,7 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
field: 'orderTime',
title: '订单时间',
width: 160,
formatter: 'formatDateTime',
formatter: 'formatDate',
},
{
field: 'creatorName',

View File

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

View File

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

View File

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