!220 【antd】ERP、PAY 迁移彻底完成

Merge pull request !220 from 芋道源码/dev
This commit is contained in:
芋道源码
2025-10-06 12:48:00 +00:00
committed by Gitee
237 changed files with 12465 additions and 10534 deletions

View File

@@ -332,22 +332,22 @@ setupVbenVxeTable({
},
});
// add by 星语:数量格式化,例如说:金额
vxeUI.formats.add('formatNumber', {
// add by 星语:数量格式化,保留 3 位
vxeUI.formats.add('formatAmount3', {
tableCellFormatMethod({ cellValue }) {
return erpCountInputFormatter(cellValue);
},
});
// add by 星语:数量格式化,保留 2 位
vxeUI.formats.add('formatAmount2', {
tableCellFormatMethod({ cellValue }, digits = 2) {
return `${erpNumberFormatter(cellValue, digits)}`;
return `${erpNumberFormatter(cellValue, digits)}`;
},
});
vxeUI.formats.add('formatFenToYuanAmount', {
tableCellFormatMethod({ cellValue }, digits = 2) {
return `${erpNumberFormatter(fenToYuan(cellValue), digits)}`;
return `${erpNumberFormatter(fenToYuan(cellValue), digits)}`;
},
});
},

View File

@@ -3,34 +3,57 @@ import type { PageParam, PageResult } from '@vben/request';
import { requestClient } from '#/api/request';
namespace ErpFinancePaymentApi {
/** 付款单项 */
export interface FinancePaymentItem {
id?: number;
row_id?: number; // 前端使用的临时ID
bizId: number; // 业务ID
bizType: number; // 业务类型
bizNo: string; // 业务编号
totalPrice: number; // 应付金额
paidPrice: number; // 已付金额
paymentPrice: number; // 本次付款
remark?: string; // 备注
}
/** 付款单信息 */
export interface FinancePayment {
id?: number; // 付款单编号
no: string; // 付款单号
supplierId: number; // 供应商编号
supplierName?: string; // 供应商名称
paymentTime: Date; // 付款时间
totalPrice: number; // 合计金额,单位:元
discountPrice: number; // 优惠金额
paymentPrice: number; // 实际付款金额
status: number; // 状态
remark: string; // 备注
fileUrl?: string; // 附件
accountId?: number; // 付款账户
accountName?: string; // 账户名称
financeUserId?: number; // 财务人员
financeUserName?: string; // 财务人员姓名
creator?: string; // 创建人
creatorName?: string; // 创建人姓名
items?: FinancePaymentItem[]; // 付款明细
bizNo?: string; // 业务单号
}
/** 付款单分页查询参数 */
export interface FinancePaymentPageParams extends PageParam {
no?: string;
paymentTime?: [string, string];
supplierId?: number;
creator?: string;
financeUserId?: number;
accountId?: number;
status?: number;
}
/** 付款单状态更新参数 */
export interface FinancePaymentStatusParams {
id: number;
status: number;
remark?: string;
bizNo?: string;
}
}
/**
* 查询付款单分页
*/
/** 查询付款单分页 */
export function getFinancePaymentPage(
params: ErpFinancePaymentApi.FinancePaymentPageParams,
) {
@@ -42,47 +65,35 @@ export function getFinancePaymentPage(
);
}
/**
* 查询付款单详情
*/
/** 查询付款单详情 */
export function getFinancePayment(id: number) {
return requestClient.get<ErpFinancePaymentApi.FinancePayment>(
`/erp/finance-payment/get?id=${id}`,
);
}
/**
* 新增付款单
*/
/** 新增付款单 */
export function createFinancePayment(
data: ErpFinancePaymentApi.FinancePayment,
) {
return requestClient.post('/erp/finance-payment/create', data);
}
/**
* 修改付款单
*/
/** 修改付款单 */
export function updateFinancePayment(
data: ErpFinancePaymentApi.FinancePayment,
) {
return requestClient.put('/erp/finance-payment/update', data);
}
/**
* 更新付款单的状态
*/
export function updateFinancePaymentStatus(
params: ErpFinancePaymentApi.FinancePaymentStatusParams,
) {
/** 更新付款单的状态 */
export function updateFinancePaymentStatus(id: number, status: number) {
return requestClient.put('/erp/finance-payment/update-status', null, {
params,
params: { id, status },
});
}
/**
* 删除付款单
*/
/** 删除付款单 */
export function deleteFinancePayment(ids: number[]) {
return requestClient.delete('/erp/finance-payment/delete', {
params: {
@@ -91,9 +102,7 @@ export function deleteFinancePayment(ids: number[]) {
});
}
/**
* 导出付款单 Excel
*/
/** 导出付款单 Excel */
export function exportFinancePayment(
params: ErpFinancePaymentApi.FinancePaymentPageParams,
) {

View File

@@ -3,34 +3,57 @@ import type { PageParam, PageResult } from '@vben/request';
import { requestClient } from '#/api/request';
namespace ErpFinanceReceiptApi {
/** 收款单项 */
export interface FinanceReceiptItem {
id?: number;
row_id?: number; // 前端使用的临时ID
bizId: number; // 业务ID
bizType: number; // 业务类型
bizNo: string; // 业务编号
totalPrice: number; // 应收金额
receiptedPrice: number; // 已收金额
receiptPrice: number; // 本次收款
remark?: string; // 备注
}
/** 收款单信息 */
export interface FinanceReceipt {
id?: number; // 收款单编号
no: string; // 收款单号
customerId: number; // 客户编号
customerName?: string; // 客户名称
receiptTime: Date; // 收款时间
totalPrice: number; // 合计金额,单位:元
discountPrice: number; // 优惠金额
receiptPrice: number; // 实际收款金额
status: number; // 状态
remark: string; // 备注
fileUrl?: string; // 附件
accountId?: number; // 收款账户
accountName?: string; // 账户名称
financeUserId?: number; // 财务人员
financeUserName?: string; // 财务人员姓名
creator?: string; // 创建人
creatorName?: string; // 创建人姓名
items?: FinanceReceiptItem[]; // 收款明细
bizNo?: string; // 业务单号
}
/** 收款单分页查询参数 */
export interface FinanceReceiptPageParams extends PageParam {
no?: string;
receiptTime?: [string, string];
customerId?: number;
creator?: string;
financeUserId?: number;
accountId?: number;
status?: number;
}
/** 收款单状态更新参数 */
export interface FinanceReceiptStatusParams {
id: number;
status: number;
remark?: string;
bizNo?: string;
}
}
/**
* 查询收款单分页
*/
/** 查询收款单分页 */
export function getFinanceReceiptPage(
params: ErpFinanceReceiptApi.FinanceReceiptPageParams,
) {
@@ -42,47 +65,35 @@ export function getFinanceReceiptPage(
);
}
/**
* 查询收款单详情
*/
/** 查询收款单详情 */
export function getFinanceReceipt(id: number) {
return requestClient.get<ErpFinanceReceiptApi.FinanceReceipt>(
`/erp/finance-receipt/get?id=${id}`,
);
}
/**
* 新增收款单
*/
/** 新增收款单 */
export function createFinanceReceipt(
data: ErpFinanceReceiptApi.FinanceReceipt,
) {
return requestClient.post('/erp/finance-receipt/create', data);
}
/**
* 修改收款单
*/
/** 修改收款单 */
export function updateFinanceReceipt(
data: ErpFinanceReceiptApi.FinanceReceipt,
) {
return requestClient.put('/erp/finance-receipt/update', data);
}
/**
* 更新收款单的状态
*/
export function updateFinanceReceiptStatus(
params: ErpFinanceReceiptApi.FinanceReceiptStatusParams,
) {
/** 更新收款单的状态 */
export function updateFinanceReceiptStatus(id: number, status: number) {
return requestClient.put('/erp/finance-receipt/update-status', null, {
params,
params: { id, status },
});
}
/**
* 删除收款单
*/
/** 删除收款单 */
export function deleteFinanceReceipt(ids: number[]) {
return requestClient.delete('/erp/finance-receipt/delete', {
params: {
@@ -91,9 +102,7 @@ export function deleteFinanceReceipt(ids: number[]) {
});
}
/**
* 导出收款单 Excel
*/
/** 导出收款单 Excel */
export function exportFinanceReceipt(
params: ErpFinanceReceiptApi.FinanceReceiptPageParams,
) {

View File

@@ -14,9 +14,10 @@ export namespace ErpProductCategoryApi {
}
/** 查询产品分类列表 */
export function getProductCategoryList() {
export function getProductCategoryList(params?: any) {
return requestClient.get<ErpProductCategoryApi.ProductCategory[]>(
'/erp/product-category/list',
{ params },
);
}

View File

@@ -49,13 +49,6 @@ export namespace ErpPurchaseInApi {
supplierId?: number;
status?: number;
}
// TODO @nehcupdatePurchaseInStatus 是不是需要?
/** 采购入库状态更新参数 */
export interface PurchaseInStatusParams {
id: number;
status: number;
}
}
/**

View File

@@ -100,12 +100,7 @@ export function updatePurchaseOrderStatus(id: number, status: number) {
}
/** 删除采购订单 */
export function deletePurchaseOrder(id: number) {
return requestClient.delete(`/erp/purchase-order/delete?id=${id}`);
}
/** 批量删除采购订单 */
export function deletePurchaseOrderList(ids: number[]) {
export function deletePurchaseOrder(ids: number[]) {
return requestClient.delete('/erp/purchase-order/delete', {
params: { ids: ids.join(',') },
});

View File

@@ -96,11 +96,9 @@ export function updatePurchaseReturn(
/**
* 更新采购退货的状态
*/
export function updatePurchaseReturnStatus(
params: ErpPurchaseReturnApi.PurchaseReturnStatusParams,
) {
export function updatePurchaseReturnStatus(id: number, status: number) {
return requestClient.put('/erp/purchase-return/update-status', null, {
params,
params: { id, status },
});
}

View File

@@ -24,6 +24,7 @@ export namespace ErpSaleOrderApi {
depositPrice?: number; // 定金金额,单位:元
items?: SaleOrderItem[]; // 销售订单产品明细列表
}
export interface SaleOrderItem {
id?: number; // 订单项编号
orderId?: number; // 采购订单编号
@@ -66,6 +67,13 @@ export function getSaleOrder(id: number) {
);
}
/** 查询销售订单项列表 */
export function getSaleOrderItemListByOrderId(orderId: number) {
return requestClient.get<ErpSaleOrderApi.SaleOrderItem[]>(
`/erp/sale-order/item/list-by-order-id?orderId=${orderId}`,
);
}
/** 新增销售订单 */
export function createSaleOrder(data: ErpSaleOrderApi.SaleOrder) {
return requestClient.post('/erp/sale-order/create', data);

View File

@@ -23,6 +23,7 @@ export namespace ErpSaleOutApi {
fileUrl?: string; // 附件地址
items?: SaleOutItem[];
}
export interface SaleOutItem {
count?: number;
id?: number;
@@ -49,17 +50,9 @@ export namespace ErpSaleOutApi {
customerId?: number;
status?: number;
}
/** 销售出库状态更新参数 */
export interface SaleOutStatusParams {
id: number;
status: number;
}
}
/**
* 查询销售出库分页
*/
/** 查询销售出库分页 */
export function getSaleOutPage(params: ErpSaleOutApi.SaleOutPageParams) {
return requestClient.get<PageResult<ErpSaleOutApi.SaleOut>>(
'/erp/sale-out/page',
@@ -69,39 +62,29 @@ export function getSaleOutPage(params: ErpSaleOutApi.SaleOutPageParams) {
);
}
/**
* 查询销售出库详情
*/
/** 查询销售出库详情 */
export function getSaleOut(id: number) {
return requestClient.get<ErpSaleOutApi.SaleOut>(`/erp/sale-out/get?id=${id}`);
}
/**
* 新增销售出库
*/
/** 新增销售出库 */
export function createSaleOut(data: ErpSaleOutApi.SaleOut) {
return requestClient.post('/erp/sale-out/create', data);
}
/**
* 修改销售出库
*/
/** 修改销售出库 */
export function updateSaleOut(data: ErpSaleOutApi.SaleOut) {
return requestClient.put('/erp/sale-out/update', data);
}
/**
* 更新销售出库的状态
*/
export function updateSaleOutStatus(params: ErpSaleOutApi.SaleOutStatusParams) {
/** 更新销售出库的状态 */
export function updateSaleOutStatus(id: number, status: number) {
return requestClient.put('/erp/sale-out/update-status', null, {
params,
params: { id, status },
});
}
/**
* 删除销售出库
*/
/** 删除销售出库 */
export function deleteSaleOut(ids: number[]) {
return requestClient.delete('/erp/sale-out/delete', {
params: {
@@ -110,9 +93,7 @@ export function deleteSaleOut(ids: number[]) {
});
}
/**
* 导出销售出库 Excel
*/
/** 导出销售出库 Excel */
export function exportSaleOut(params: ErpSaleOutApi.SaleOutPageParams) {
return requestClient.download('/erp/sale-out/export-excel', {
params,

View File

@@ -22,6 +22,7 @@ export namespace ErpSaleReturnApi {
fileUrl?: string; // 附件地址
items?: SaleReturnItem[];
}
export interface SaleReturnItem {
count?: number;
id?: number;
@@ -48,12 +49,6 @@ export namespace ErpSaleReturnApi {
customerId?: number;
status?: number;
}
/** 销售退货状态更新参数 */
export interface SaleReturnStatusParams {
id: number;
status: number;
}
}
/**
@@ -96,11 +91,9 @@ export function updateSaleReturn(data: ErpSaleReturnApi.SaleReturn) {
/**
* 更新销售退货的状态
*/
export function updateSaleReturnStatus(
params: ErpSaleReturnApi.SaleReturnStatusParams,
) {
export function updateSaleReturnStatus(id: number, status: number) {
return requestClient.put('/erp/sale-return/update-status', null, {
params,
params: { id, status },
});
}

View File

@@ -17,6 +17,7 @@ export namespace ErpStockCheckApi {
creatorName?: string; // 创建人
items?: StockCheckItem[]; // 盘点产品清单
}
export interface StockCheckItem {
id?: number; // 编号
warehouseId?: number; // 仓库编号
@@ -38,12 +39,6 @@ export namespace ErpStockCheckApi {
no?: string;
status?: number;
}
/** 库存盘点单状态更新参数 */
export interface StockCheckStatusParams {
id: number;
status: number;
}
}
/**
@@ -86,11 +81,9 @@ export function updateStockCheck(data: ErpStockCheckApi.StockCheck) {
/**
* 更新库存盘点单的状态
*/
export function updateStockCheckStatus(
params: ErpStockCheckApi.StockCheckStatusParams,
) {
export function updateStockCheckStatus(id: number, status: number) {
return requestClient.put('/erp/stock-check/update-status', null, {
params,
params: { id, status },
});
}

View File

@@ -42,12 +42,6 @@ export namespace ErpStockInApi {
supplierId?: number;
status?: number;
}
/** 其它入库单状态更新参数 */
export interface StockInStatusParams {
id: number;
status: number;
}
}
/**
@@ -86,9 +80,9 @@ export function updateStockIn(data: ErpStockInApi.StockIn) {
/**
* 更新其它入库单的状态
*/
export function updateStockInStatus(params: ErpStockInApi.StockInStatusParams) {
export function updateStockInStatus(id: number, status: number) {
return requestClient.put('/erp/stock-in/update-status', null, {
params,
params: { id, status },
});
}

View File

@@ -43,13 +43,6 @@ export namespace ErpStockMoveApi {
status?: number;
}
/** 库存调拨单状态更新参数 */
export interface StockMoveStatusParams {
id: number;
status: number;
}
}
/**
* 查询库存调拨单分页
*/
@@ -88,11 +81,9 @@ export function updateStockMove(data: ErpStockMoveApi.StockMove) {
/**
* 更新库存调拨单的状态
*/
export function updateStockMoveStatus(
params: ErpStockMoveApi.StockMoveStatusParams,
) {
export function updateStockMoveStatus(id: number, status: number) {
return requestClient.put('/erp/stock-move/update-status', null, {
params,
params: { id, status },
});
}

View File

@@ -39,12 +39,6 @@ export namespace ErpStockOutApi {
customerId?: number;
status?: number;
}
/** 其它出库单状态更新参数 */
export interface StockOutStatusParams {
id: number;
status: number;
}
}
/**
@@ -85,11 +79,9 @@ export function updateStockOut(data: ErpStockOutApi.StockOut) {
/**
* 更新其它出库单的状态
*/
export function updateStockOutStatus(
params: ErpStockOutApi.StockOutStatusParams,
) {
export function updateStockOutStatus(id: number, status: number) {
return requestClient.put('/erp/stock-out/update-status', null, {
params,
params: { id, status },
});
}

View File

@@ -16,7 +16,7 @@ export namespace PayAppApi {
merchantId: number;
merchantName: string;
createTime?: Date;
channelCodes: string[];
channelCodes?: string[];
}
/** 更新状态请求 */
@@ -25,20 +25,16 @@ export namespace PayAppApi {
status: number;
}
export interface AppPageReq extends PageParam {
export interface AppPageReqVO extends PageParam {
name?: string;
appKey?: string;
status?: number;
remark?: string;
payNotifyUrl?: string;
refundNotifyUrl?: string;
transferNotifyUrl?: string;
merchantName?: string;
createTime?: Date[];
}
}
/** 查询支付应用列表 */
export function getAppPage(params: PayAppApi.AppPageReq) {
export function getAppPage(params: PayAppApi.AppPageReqVO) {
return requestClient.get<PageResult<PayAppApi.App>>('/pay/app/page', {
params,
});
@@ -60,7 +56,7 @@ export function updateApp(data: PayAppApi.App) {
}
/** 修改支付应用状态 */
export function changeAppStatus(data: PayAppApi.UpdateStatusReq) {
export function updateAppStatus(data: PayAppApi.UpdateStatusReq) {
return requestClient.put('/pay/app/update-status', data);
}

View File

@@ -20,7 +20,7 @@ export namespace DemoOrderApi {
createTime?: Date;
}
export interface OrderPageReq extends PageParam {
export interface OrderPageReqVO extends PageParam {
spuId?: number;
createTime?: Date[];
}
@@ -32,7 +32,7 @@ export function createDemoOrder(data: DemoOrderApi.Order) {
}
/** 获得示例订单分页 */
export function getDemoOrderPage(params: DemoOrderApi.OrderPageReq) {
export function getDemoOrderPage(params: DemoOrderApi.OrderPageReqVO) {
return requestClient.get<PageResult<DemoOrderApi.Order>>(
'/pay/demo-order/page',
{

View File

@@ -1,15 +1,52 @@
import type { PageParam } from '@vben/request';
import type { PageParam, PageResult } from '@vben/request';
import { requestClient } from '#/api/request';
export namespace PayNotifyApi {
/** 支付通知任务 */
export interface NotifyTask {
id: number;
appId: number;
appName: string;
type: number;
dataId: number;
status: number;
merchantOrderId: string;
merchantRefundId?: string;
merchantTransferId?: string;
lastExecuteTime: Date;
nextNotifyTime: Date;
notifyTimes: number;
maxNotifyTimes: number;
createTime: Date;
updateTime: Date;
logs?: any[];
}
/** 支付通知任务分页请求 */
export interface NotifyTaskPageReqVO extends PageParam {
appId?: number;
type?: number;
dataId?: number;
status?: number;
merchantOrderId?: string;
merchantRefundId?: string;
merchantTransferId?: string;
createTime?: Date[];
}
}
/** 获得支付通知明细 */
export function getNotifyTaskDetail(id: number) {
return requestClient.get(`/pay/notify/get-detail?id=${id}`);
}
/** 获得支付通知分页 */
export function getNotifyTaskPage(params: PageParam) {
return requestClient.get('/pay/notify/page', {
params,
});
export function getNotifyTaskPage(params: PayNotifyApi.NotifyTaskPageReqVO) {
return requestClient.get<PageResult<PayNotifyApi.NotifyTask>>(
'/pay/notify/page',
{
params,
},
);
}

View File

@@ -40,60 +40,19 @@ export namespace PayOrderApi {
}
/** 支付订单分页请求 */
export interface OrderPageReq extends PageParam {
merchantId?: number;
export interface OrderPageReqVO extends PageParam {
appId?: number;
channelId?: number;
channelCode?: string;
merchantOrderId?: string;
subject?: string;
body?: string;
notifyUrl?: string;
notifyStatus?: number;
amount?: number;
channelFeeRate?: number;
channelFeeAmount?: number;
status?: number;
expireTime?: Date[];
successTime?: Date[];
notifyTime?: Date[];
successExtensionId?: number;
refundStatus?: number;
refundTimes?: number;
channelUserId?: string;
channelOrderNo?: string;
createTime?: Date[];
}
/** 支付订单导出请求 */
export interface OrderExportReq {
merchantId?: number;
appId?: number;
channelId?: number;
channelCode?: string;
merchantOrderId?: string;
subject?: string;
body?: string;
notifyUrl?: string;
notifyStatus?: number;
amount?: number;
channelFeeRate?: number;
channelFeeAmount?: number;
no?: string;
status?: number;
expireTime?: Date[];
successTime?: Date[];
notifyTime?: Date[];
successExtensionId?: number;
refundStatus?: number;
refundTimes?: number;
channelUserId?: string;
channelOrderNo?: string;
createTime?: Date[];
}
}
/** 查询支付订单列表 */
export function getOrderPage(params: PayOrderApi.OrderPageReq) {
export function getOrderPage(params: PayOrderApi.OrderPageReqVO) {
return requestClient.get<PageResult<PayOrderApi.Order>>('/pay/order/page', {
params,
});
@@ -120,6 +79,6 @@ export function submitOrder(data: any) {
}
/** 导出支付订单 */
export function exportOrder(params: PayOrderApi.OrderExportReq) {
export function exportOrder(params: any) {
return requestClient.download('/pay/order/export-excel', { params });
}

View File

@@ -14,9 +14,12 @@ export namespace PayRefundApi {
tradeNo: string;
merchantOrderId: string;
merchantRefundNo: string;
merchantRefundId: string;
notifyUrl: string;
notifyStatus: number;
status: number;
payPrice: number;
refundPrice: number;
type: number;
payAmount: number;
refundAmount: number;
@@ -35,36 +38,7 @@ export namespace PayRefundApi {
}
/** 退款订单分页请求 */
export interface RefundPageReq extends PageParam {
merchantId?: number;
appId?: number;
channelId?: number;
channelCode?: string;
orderId?: string;
tradeNo?: string;
merchantOrderId?: string;
merchantRefundNo?: string;
notifyUrl?: string;
notifyStatus?: number;
status?: number;
type?: number;
payAmount?: number;
refundAmount?: number;
reason?: string;
userIp?: string;
channelOrderNo?: string;
channelRefundNo?: string;
channelErrorCode?: string;
channelErrorMsg?: string;
channelExtras?: string;
expireTime?: Date[];
successTime?: Date[];
notifyTime?: Date[];
createTime?: Date[];
}
/** 退款订单导出请求 */
export interface RefundExportReq {
export interface RefundPageReqVO extends PageParam {
merchantId?: number;
appId?: number;
channelId?: number;
@@ -94,7 +68,7 @@ export namespace PayRefundApi {
}
/** 查询退款订单列表 */
export function getRefundPage(params: PayRefundApi.RefundPageReq) {
export function getRefundPage(params: PayRefundApi.RefundPageReqVO) {
return requestClient.get<PageResult<PayRefundApi.Refund>>(
'/pay/refund/page',
{
@@ -108,22 +82,7 @@ export function getRefund(id: number) {
return requestClient.get<PayRefundApi.Refund>(`/pay/refund/get?id=${id}`);
}
/** 创建退款订单 */
export function createRefund(data: PayRefundApi.Refund) {
return requestClient.post('/pay/refund/create', data);
}
/** 更新退款订单 */
export function updateRefund(data: PayRefundApi.Refund) {
return requestClient.put('/pay/refund/update', data);
}
/** 删除退款订单 */
export function deleteRefund(id: number) {
return requestClient.delete(`/pay/refund/delete?id=${id}`);
}
/** 导出退款订单 */
export function exportRefund(params: PayRefundApi.RefundExportReq) {
export function exportRefund(params: any) {
return requestClient.download('/pay/refund/export-excel', { params });
}

View File

@@ -6,37 +6,42 @@ export namespace PayTransferApi {
/** 转账单信息 */
export interface Transfer {
id: number;
no: string;
appId: number;
appName: string;
channelId: number;
channelCode: string;
merchantTransferId: string;
type: number;
channelTransferNo: string;
price: number;
subject: string;
userName: string;
alipayLogonId: string;
openid: string;
userAccount: string;
userIp: string;
status: number;
successTime: Date;
createTime: Date;
updateTime: Date;
notifyUrl: string;
channelNotifyData: string;
}
/** 转账单分页请求 */
export interface TransferPageReq extends PageParam {
export interface TransferPageReqVO extends PageParam {
no?: string;
appId?: number;
channelId?: number;
channelCode?: string;
merchantTransferId?: string;
type?: number;
price?: number;
subject?: string;
userName?: string;
merchantOrderId?: string;
status?: number;
userName?: string;
userAccount?: string;
channelTransferNo?: string;
createTime?: Date[];
}
}
/** 查询转账单列表 */
export function getTransferPage(params: PayTransferApi.TransferPageReq) {
export function getTransferPage(params: PayTransferApi.TransferPageReqVO) {
return requestClient.get<PageResult<PayTransferApi.Transfer>>(
'/pay/transfer/page',
{

View File

@@ -20,7 +20,7 @@ export namespace PayWalletApi {
}
/** 钱包分页请求 */
export interface WalletPageReq extends PageParam {
export interface WalletPageReqVO extends PageParam {
userId?: number;
userType?: number;
balance?: number;
@@ -38,7 +38,7 @@ export function getWallet(params: PayWalletApi.PayWalletUserReq) {
}
/** 查询会员钱包列表 */
export function getWalletPage(params: PayWalletApi.WalletPageReq) {
export function getWalletPage(params: PayWalletApi.WalletPageReqVO) {
return requestClient.get<PageResult<PayWalletApi.Wallet>>(
'/pay/wallet/page',
{

View File

@@ -4,7 +4,7 @@ import { requestClient } from '#/api/request';
export namespace WalletRechargePackageApi {
/** 充值套餐信息 */
export interface Package {
export interface WalletRechargePackage {
id?: number;
name: string;
payPrice: number;
@@ -14,33 +14,36 @@ export namespace WalletRechargePackageApi {
}
/** 查询充值套餐列表 */
export function getPackagePage(params: PageParam) {
return requestClient.get<PageResult<WalletRechargePackageApi.Package>>(
'/pay/wallet-recharge-package/page',
{
params,
},
);
export function getWalletRechargePackagePage(params: PageParam) {
return requestClient.get<
PageResult<WalletRechargePackageApi.WalletRechargePackage>
>('/pay/wallet-recharge-package/page', {
params,
});
}
/** 查询充值套餐详情 */
export function getPackage(id: number) {
return requestClient.get<WalletRechargePackageApi.Package>(
export function getWalletRechargePackage(id: number) {
return requestClient.get<WalletRechargePackageApi.WalletRechargePackage>(
`/pay/wallet-recharge-package/get?id=${id}`,
);
}
/** 新增充值套餐 */
export function createPackage(data: WalletRechargePackageApi.Package) {
export function createWalletRechargePackage(
data: WalletRechargePackageApi.WalletRechargePackage,
) {
return requestClient.post('/pay/wallet-recharge-package/create', data);
}
/** 修改充值套餐 */
export function updatePackage(data: WalletRechargePackageApi.Package) {
export function updateWalletRechargePackage(
data: WalletRechargePackageApi.WalletRechargePackage,
) {
return requestClient.put('/pay/wallet-recharge-package/update', data);
}
/** 删除充值套餐 */
export function deletePackage(id: number) {
export function deleteWalletRechargePackage(id: number) {
return requestClient.delete(`/pay/wallet-recharge-package/delete?id=${id}`);
}

View File

@@ -1,5 +1,4 @@
<script setup lang="ts">
// TODO @xingyu这个组件只有 pay 在用,和现有的 file-upload 和 image-upload 有点不一致。是不是可以考虑移除,只在 pay 那搞个复用的组件;
import type { InputProps, TextAreaProps } from 'ant-design-vue';
import type { FileUploadProps } from './typing';
@@ -61,8 +60,8 @@ const fileUploadProps = computed(() => {
<template>
<Row>
<Col :span="18">
<Input v-if="inputType === 'input'" v-bind="inputProps" />
<Textarea v-else :row="4" v-bind="textareaProps" />
<Input readonly v-if="inputType === 'input'" v-bind="inputProps" />
<Textarea readonly v-else :row="4" v-bind="textareaProps" />
</Col>
<Col :span="6">
<FileUpload

View File

@@ -43,7 +43,7 @@ export function useDetailListColumns(
{
field: 'count',
title: '数量',
formatter: 'formatNumber',
formatter: 'formatAmount3',
},
{
field: 'totalPrice',

View File

@@ -1,13 +1,9 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import { h } from 'vue';
import { CommonStatusEnum, DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { Tag } from 'ant-design-vue';
import { z } from '#/adapter/form';
/** 新增/修改的表单 */
@@ -49,7 +45,6 @@ export function useFormSchema(): VbenFormSchema[] {
componentProps: {
placeholder: '请输入排序',
precision: 0,
class: 'w-full',
},
rules: 'required',
defaultValue: 0,
@@ -86,11 +81,14 @@ export function useFormSchema(): VbenFormSchema[] {
fieldName: 'remark',
label: '备注',
component: 'Textarea',
componentProps: {
placeholder: '请输入备注',
rows: 3,
},
},
];
}
// TODO @xuzhiqiang搜索的是不是缺了placeholder
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
@@ -98,42 +96,65 @@ export function useGridFormSchema(): VbenFormSchema[] {
fieldName: 'name',
label: '名称',
component: 'Input',
componentProps: {
placeholder: '请输入名称',
allowClear: true,
},
},
{
fieldName: 'no',
label: '编码',
component: 'Input',
componentProps: {
placeholder: '请输入编码',
allowClear: true,
},
},
{
fieldName: 'remark',
label: '备注',
component: 'Input',
componentProps: {
placeholder: '请输入备注',
allowClear: true,
},
},
];
}
/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
export function useGridColumns<T = ErpAccountApi.Account>(
onDefaultStatusChange?: (
newStatus: boolean,
row: T,
) => PromiseLike<boolean | undefined>,
): VxeTableGridOptions['columns'] {
return [
{
field: 'name',
title: '名称',
minWidth: 150,
},
{
field: 'no',
title: '编码',
minWidth: 120,
},
{
field: 'remark',
title: '备注',
minWidth: 150,
showOverflow: 'tooltip',
},
{
field: 'sort',
title: '排序',
minWidth: 80,
},
{
field: 'status',
title: '状态',
minWidth: 100,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.COMMON_STATUS },
@@ -142,22 +163,20 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
{
field: 'defaultStatus',
title: '是否默认',
slots: {
default: ({ row }) => {
return h(
Tag,
{
class: 'mr-1',
color: row.defaultStatus ? 'blue' : 'red',
},
() => (row.defaultStatus ? '是' : '否'),
);
minWidth: 100,
cellRender: {
attrs: { beforeChange: onDefaultStatusChange },
name: 'CellSwitch',
props: {
checkedValue: true,
unCheckedValue: false,
},
},
},
{
field: 'createTime',
title: '创建时间',
minWidth: 180,
formatter: 'formatDateTime',
},
{

View File

@@ -2,7 +2,7 @@
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { ErpAccountApi } from '#/api/erp/finance/account';
import { DocAlert, Page, useVbenModal } from '@vben/common-ui';
import { confirm, DocAlert, Page, useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart } from '@vben/utils';
import { message } from 'ant-design-vue';
@@ -12,6 +12,7 @@ import {
deleteAccount,
exportAccount,
getAccountPage,
updateAccountDefaultStatus,
} from '#/api/erp/finance/account';
import { $t } from '#/locales';
@@ -24,7 +25,7 @@ const [FormModal, formModalApi] = useVbenModal({
});
/** 刷新表格 */
function onRefresh() {
function handleRefresh() {
gridApi.query();
}
@@ -52,21 +53,41 @@ async function handleDelete(row: ErpAccountApi.Account) {
});
try {
await deleteAccount(row.id as number);
message.success({
content: $t('ui.actionMessage.deleteSuccess', [row.name]),
});
onRefresh();
message.success($t('ui.actionMessage.deleteSuccess', [row.name]));
handleRefresh();
} finally {
hideLoading();
}
}
/** 修改默认状态 */
async function handleDefaultStatusChange(
newStatus: boolean,
row: ErpAccountApi.Account,
): Promise<boolean | undefined> {
return new Promise((resolve, reject) => {
const text = newStatus ? '设置' : '取消';
confirm({
content: `确认要${text}"${row.name}"默认吗?`,
})
.then(async () => {
// 更新默认状态
await updateAccountDefaultStatus(row.id!, newStatus);
message.success(`${text}默认成功`);
resolve(true);
})
.catch(() => {
reject(new Error('取消操作'));
});
});
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
},
gridOptions: {
columns: useGridColumns(),
columns: useGridColumns(handleDefaultStatusChange),
height: 'auto',
keepSource: true,
proxyConfig: {
@@ -100,7 +121,8 @@ const [Grid, gridApi] = useVbenVxeGrid({
url="https://doc.iocoder.cn/sale/finance-payment-receipt/"
/>
</template>
<FormModal @success="onRefresh" />
<FormModal @success="handleRefresh" />
<Grid table-title="结算账户列表">
<template #toolbar-tools>
<TableAction

View File

@@ -30,8 +30,9 @@ const [Form, formApi] = useVbenForm({
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 80,
},
wrapperClass: 'grid-cols-1',
layout: 'horizontal',
schema: useFormSchema(),
showDefaultActions: false,
@@ -79,7 +80,7 @@ const [Modal, modalApi] = useVbenModal({
</script>
<template>
<Modal class="w-2/5" :title="getTitle">
<Modal class="w-1/3" :title="getTitle">
<Form class="mx-4" />
</Modal>
</template>

View File

@@ -0,0 +1,597 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { erpPriceInputFormatter } from '@vben/utils';
import { getAccountSimpleList } from '#/api/erp/finance/account';
import { getSupplierSimpleList } from '#/api/erp/purchase/supplier';
import { getSimpleUserList } from '#/api/system/user';
import { getRangePickerDefaultProps } from '#/utils';
/** 表单的配置项 */
export function useFormSchema(formType: string): VbenFormSchema[] {
return [
{
fieldName: 'id',
component: 'Input',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'no',
label: '付款单号',
component: 'Input',
componentProps: {
placeholder: '系统自动生成',
disabled: true,
},
},
{
fieldName: 'paymentTime',
label: '付款时间',
component: 'DatePicker',
componentProps: {
disabled: formType === 'detail',
placeholder: '选择付款时间',
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
valueFormat: 'x',
},
rules: 'required',
},
{
fieldName: 'supplierId',
label: '供应商',
component: 'ApiSelect',
componentProps: {
disabled: formType === 'detail',
placeholder: '请选择供应商',
allowClear: true,
showSearch: true,
api: getSupplierSimpleList,
fieldNames: {
label: 'name',
value: 'id',
},
},
rules: 'required',
},
{
fieldName: 'financeUserId',
label: '财务人员',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择财务人员',
allowClear: true,
showSearch: true,
api: getSimpleUserList,
fieldNames: {
label: 'nickname',
value: 'id',
},
},
},
{
fieldName: 'remark',
label: '备注',
component: 'Textarea',
componentProps: {
placeholder: '请输入备注',
autoSize: { minRows: 1, maxRows: 1 },
disabled: formType === 'detail',
},
formItemClass: 'col-span-2',
},
{
fieldName: 'fileUrl',
label: '附件',
component: 'FileUpload',
componentProps: {
maxNumber: 1,
maxSize: 10,
accept: [
'pdf',
'doc',
'docx',
'xls',
'xlsx',
'txt',
'jpg',
'jpeg',
'png',
],
showDescription: formType !== 'detail',
disabled: formType === 'detail',
},
formItemClass: 'col-span-3',
},
{
fieldName: 'items',
label: '采购入库、退货单',
component: 'Input',
formItemClass: 'col-span-3',
},
{
fieldName: 'accountId',
label: '付款账户',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择付款账户',
allowClear: true,
showSearch: true,
api: getAccountSimpleList,
fieldNames: {
label: 'name',
value: 'id',
},
},
},
{
fieldName: 'totalPrice',
label: '合计付款',
component: 'InputNumber',
componentProps: {
placeholder: '合计付款',
precision: 2,
formatter: erpPriceInputFormatter,
disabled: true,
},
},
{
fieldName: 'discountPrice',
label: '优惠金额',
component: 'InputNumber',
componentProps: {
disabled: formType === 'detail',
placeholder: '请输入优惠金额',
precision: 2,
formatter: erpPriceInputFormatter,
},
},
{
fieldName: 'paymentPrice',
label: '实际付款',
component: 'InputNumber',
componentProps: {
placeholder: '实际付款',
precision: 2,
formatter: erpPriceInputFormatter,
disabled: true,
},
dependencies: {
triggerFields: ['totalPrice', 'discountPrice'],
componentProps: (values) => {
const totalPrice = values.totalPrice || 0;
const discountPrice = values.discountPrice || 0;
values.paymentPrice = totalPrice - discountPrice;
return {};
},
},
},
];
}
/** 表单的明细表格列 */
export function useFormItemColumns(): VxeTableGridOptions['columns'] {
return [
{ type: 'seq', title: '序号', minWidth: 50, fixed: 'left' },
{
field: 'bizNo',
title: '采购单据编号',
minWidth: 200,
},
{
field: 'totalPrice',
title: '应付金额',
minWidth: 100,
formatter: 'formatAmount2',
},
{
field: 'paidPrice',
title: '已付金额',
minWidth: 100,
formatter: 'formatAmount2',
},
{
field: 'paymentPrice',
title: '本次付款',
minWidth: 115,
fixed: 'right',
slots: { default: 'paymentPrice' },
},
{
field: 'remark',
title: '备注',
minWidth: 150,
slots: { default: 'remark' },
},
{
title: '操作',
width: 50,
fixed: 'right',
slots: { default: 'actions' },
},
];
}
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'no',
label: '付款单号',
component: 'Input',
componentProps: {
placeholder: '请输入付款单号',
allowClear: true,
},
},
{
fieldName: 'paymentTime',
label: '付款时间',
component: 'RangePicker',
componentProps: {
...getRangePickerDefaultProps(),
allowClear: true,
},
},
{
fieldName: 'supplierId',
label: '供应商',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择供应商',
allowClear: true,
showSearch: true,
api: getSupplierSimpleList,
fieldNames: {
label: 'name',
value: 'id',
},
},
},
{
fieldName: 'creator',
label: '创建人',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择创建人',
allowClear: true,
showSearch: true,
api: getSimpleUserList,
fieldNames: {
label: 'nickname',
value: 'id',
},
},
},
{
fieldName: 'financeUserId',
label: '财务人员',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择财务人员',
allowClear: true,
showSearch: true,
api: getSimpleUserList,
fieldNames: {
label: 'nickname',
value: 'id',
},
},
},
{
fieldName: 'accountId',
label: '付款账户',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择付款账户',
allowClear: true,
showSearch: true,
api: getAccountSimpleList,
fieldNames: {
label: 'name',
value: 'id',
},
},
},
{
fieldName: 'status',
label: '状态',
component: 'Select',
componentProps: {
options: getDictOptions(DICT_TYPE.ERP_AUDIT_STATUS, 'number'),
placeholder: '请选择状态',
allowClear: true,
},
},
{
fieldName: 'remark',
label: '备注',
component: 'Input',
componentProps: {
placeholder: '请输入备注',
allowClear: true,
},
},
{
fieldName: 'bizNo',
label: '采购单号',
component: 'Input',
componentProps: {
placeholder: '请输入采购单号',
allowClear: true,
},
},
];
}
/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{
type: 'checkbox',
width: 50,
fixed: 'left',
},
{
field: 'no',
title: '付款单号',
width: 180,
fixed: 'left',
},
{
field: 'supplierName',
title: '供应商',
minWidth: 120,
},
{
field: 'paymentTime',
title: '付款时间',
width: 160,
formatter: 'formatDate',
},
{
field: 'creatorName',
title: '创建人',
minWidth: 120,
},
{
field: 'financeUserName',
title: '财务人员',
minWidth: 120,
},
{
field: 'accountName',
title: '付款账户',
minWidth: 120,
},
{
field: 'totalPrice',
title: '合计付款',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'discountPrice',
title: '优惠金额',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'paymentPrice',
title: '实际付款',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'status',
title: '状态',
minWidth: 90,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.ERP_AUDIT_STATUS },
},
},
{
title: '操作',
width: 220,
fixed: 'right',
slots: { default: 'actions' },
},
];
}
/** 采购入库单选择表单的配置项 */
export function usePurchaseInGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'no',
label: '入库单号',
component: 'Input',
componentProps: {
placeholder: '请输入入库单号',
allowClear: true,
},
},
{
fieldName: 'supplierId',
label: '供应商',
component: 'Input',
componentProps: {
disabled: true,
placeholder: '已自动选择供应商',
},
},
{
fieldName: 'paymentStatus',
label: '付款状态',
component: 'Select',
componentProps: {
options: [
{ label: '未付款', value: 0 },
{ label: '部分付款', value: 1 },
{ label: '全部付款', value: 2 },
],
placeholder: '请选择付款状态',
allowClear: true,
},
},
];
}
/** 采购入库单选择列表的字段 */
export function usePurchaseInGridColumns(): VxeTableGridOptions['columns'] {
return [
{
type: 'checkbox',
width: 50,
fixed: 'left',
},
{
field: 'no',
title: '入库单号',
width: 200,
fixed: 'left',
},
{
field: 'supplierName',
title: '供应商',
minWidth: 120,
},
{
field: 'inTime',
title: '入库时间',
width: 160,
formatter: 'formatDate',
},
{
field: 'totalPrice',
title: '应付金额',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'paymentPrice',
title: '已付金额',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'unPaymentPrice',
title: '未付金额',
formatter: ({ row }) => {
return erpPriceInputFormatter(row.totalPrice - row.paymentPrice || 0);
},
minWidth: 120,
},
{
field: 'status',
title: '状态',
minWidth: 100,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.ERP_AUDIT_STATUS },
},
},
];
}
/** 采购退货单选择表单的配置项 */
export function useSaleReturnGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'no',
label: '退货单号',
component: 'Input',
componentProps: {
placeholder: '请输入退货单号',
allowClear: true,
},
},
{
fieldName: 'supplierId',
label: '供应商',
component: 'Input',
componentProps: {
disabled: true,
placeholder: '已自动选择供应商',
},
},
{
fieldName: 'refundStatus',
label: '退款状态',
component: 'Select',
componentProps: {
options: [
{ label: '未退款', value: 0 },
{ label: '部分退款', value: 1 },
{ label: '全部退款', value: 2 },
],
placeholder: '请选择退款状态',
allowClear: true,
},
},
];
}
/** 采购退货单选择列表的字段 */
export function useSaleReturnGridColumns(): VxeTableGridOptions['columns'] {
return [
{
type: 'checkbox',
width: 50,
fixed: 'left',
},
{
field: 'no',
title: '退货单号',
width: 200,
fixed: 'left',
},
{
field: 'supplierName',
title: '供应商',
minWidth: 120,
},
{
field: 'returnTime',
title: '退货时间',
width: 160,
formatter: 'formatDate',
},
{
field: 'totalPrice',
title: '应退金额',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'refundPrice',
title: '已退金额',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'unRefundPrice',
title: '未退金额',
formatter: ({ row }) => {
return erpPriceInputFormatter(row.totalPrice - row.refundPrice || 0);
},
minWidth: 120,
},
{
field: 'status',
title: '状态',
minWidth: 100,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.ERP_AUDIT_STATUS },
},
},
];
}

View File

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

View File

@@ -0,0 +1,194 @@
<script lang="ts" setup>
import type { ErpFinancePaymentApi } from '#/api/erp/finance/payment';
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 {
createFinancePayment,
getFinancePayment,
updateFinancePayment,
} from '#/api/erp/finance/payment';
import { useFormSchema } from '../data';
import ItemForm from './item-form.vue';
const emit = defineEmits(['success']);
const formData = ref<
ErpFinancePaymentApi.FinancePayment & {
fileUrl?: string;
}
>({
id: undefined,
no: undefined,
supplierId: undefined,
accountId: undefined,
financeUserId: undefined,
paymentTime: undefined,
remark: undefined,
fileUrl: undefined,
totalPrice: 0,
discountPrice: 0,
paymentPrice: 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) => {
if (formData.value) {
if (changedFields.includes('supplierId')) {
formData.value.supplierId = values.supplierId;
}
// 目的:同步到 item-form 组件,触发整体的价格计算
if (changedFields.includes('discountPrice')) {
formData.value.discountPrice = values.discountPrice;
formData.value.paymentPrice =
formData.value.totalPrice - values.discountPrice;
formApi.setValues({
paymentPrice: formData.value.paymentPrice,
});
}
}
},
});
/** 更新付款项 */
const handleUpdateItems = (
items: ErpFinancePaymentApi.FinancePaymentItem[],
) => {
formData.value.items = items;
formApi.setValues({
items,
});
};
/** 更新总金额 */
const handleUpdateTotalPrice = (totalPrice: number) => {
formData.value.totalPrice = totalPrice;
formApi.setValues({
totalPrice: formData.value.totalPrice,
});
};
/** 更新付款金额 */
const handleUpdatePaymentPrice = (paymentPrice: number) => {
formData.value.paymentPrice = paymentPrice;
formApi.setValues({
paymentPrice: formData.value.paymentPrice,
});
};
/** 创建或更新付款单 */
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 ErpFinancePaymentApi.FinancePayment;
try {
await (formType.value === 'create'
? createFinancePayment(data)
: updateFinancePayment(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 getFinancePayment(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 ?? []"
:supplier-id="formData?.supplierId"
:disabled="formType === 'detail'"
:discount-price="formData?.discountPrice ?? 0"
@update:items="handleUpdateItems"
@update:total-price="handleUpdateTotalPrice"
@update:payment-price="handleUpdatePaymentPrice"
/>
</template>
</Form>
</Modal>
</template>

View File

@@ -0,0 +1,292 @@
<script lang="ts" setup>
import type { ErpFinancePaymentApi } from '#/api/erp/finance/payment';
import type { ErpPurchaseInApi } from '#/api/erp/purchase/in';
import type { ErpPurchaseReturnApi } from '#/api/erp/purchase/return';
import { computed, nextTick, ref, watch } from 'vue';
import { ErpBizType } from '@vben/constants';
import { erpPriceInputFormatter } from '@vben/utils';
import { Input, InputNumber, message } from 'ant-design-vue';
import { TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { useFormItemColumns } from '../data';
import PurchaseInSelect from './purchase-in-select.vue';
import SaleReturnSelect from './sale-return-select.vue';
interface Props {
items?: ErpFinancePaymentApi.FinancePaymentItem[];
supplierId?: number;
disabled?: boolean;
discountPrice?: number;
}
const props = withDefaults(defineProps<Props>(), {
items: () => [],
supplierId: undefined,
disabled: false,
discountPrice: 0,
});
const emit = defineEmits([
'update:items',
'update:total-price',
'update:payment-price',
]);
const tableData = ref<ErpFinancePaymentApi.FinancePaymentItem[]>([]); // 表格数据
/** 获取表格合计数据 */
const summaries = computed(() => {
return {
totalPrice: tableData.value.reduce(
(sum, item) => sum + (item.totalPrice || 0),
0,
),
paidPrice: tableData.value.reduce(
(sum, item) => sum + (item.paidPrice || 0),
0,
),
paymentPrice: tableData.value.reduce(
(sum, item) => sum + (item.paymentPrice || 0),
0,
),
};
});
/** 表格配置 */
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions: {
columns: useFormItemColumns(),
data: tableData.value,
minHeight: 250,
autoResize: true,
border: true,
rowConfig: {
keyField: 'seq',
isHover: true,
},
pagerConfig: {
enabled: false,
},
toolbarConfig: {
enabled: false,
},
},
});
/** 监听外部传入的列数据 */
watch(
() => props.items,
async (items) => {
if (!items) {
return;
}
tableData.value = [...items];
await nextTick(); // 特殊:保证 gridApi 已经初始化
await gridApi.grid.reloadData(tableData.value);
},
{
immediate: true,
},
);
/** 计算 totalPrice、paymentPrice 价格 */
watch(
() => [tableData.value, props.discountPrice],
() => {
if (!tableData.value || tableData.value.length === 0) {
return;
}
const totalPrice = tableData.value.reduce(
(prev, curr) => prev + (curr.totalPrice || 0),
0,
);
const paymentPrice = tableData.value.reduce(
(prev, curr) => prev + (curr.paymentPrice || 0),
0,
);
const finalPaymentPrice = paymentPrice - (props.discountPrice || 0);
// 通知父组件更新
emit('update:total-price', totalPrice);
emit('update:payment-price', finalPaymentPrice);
},
{ deep: true },
);
/** 添加采购入库单 */
const purchaseInSelectRef = ref();
const handleOpenPurchaseIn = () => {
if (!props.supplierId) {
message.error('请选择供应商');
return;
}
purchaseInSelectRef.value?.open(props.supplierId);
};
const handleAddPurchaseIn = (rows: ErpPurchaseInApi.PurchaseIn[]) => {
rows.forEach((row) => {
const newItem: ErpFinancePaymentApi.FinancePaymentItem = {
bizId: row.id,
bizType: ErpBizType.PURCHASE_IN,
bizNo: row.no,
totalPrice: row.totalPrice,
paidPrice: row.paymentPrice,
paymentPrice: row.totalPrice - row.paymentPrice,
remark: undefined,
};
tableData.value.push(newItem);
});
emit('update:items', [...tableData.value]);
};
/** 添加采购退货单 */
const saleReturnSelectRef = ref();
const handleOpenSaleReturn = () => {
if (!props.supplierId) {
message.error('请选择供应商');
return;
}
saleReturnSelectRef.value?.open(props.supplierId);
};
const handleAddSaleReturn = (rows: ErpPurchaseReturnApi.PurchaseReturn[]) => {
rows.forEach((row) => {
const newItem: ErpFinancePaymentApi.FinancePaymentItem = {
bizId: row.id,
bizType: ErpBizType.PURCHASE_RETURN,
bizNo: row.no,
totalPrice: -row.totalPrice,
paidPrice: -row.refundPrice,
paymentPrice: -row.totalPrice + row.refundPrice,
remark: undefined,
};
tableData.value.push(newItem);
});
emit('update:items', [...tableData.value]);
};
/** 删除行 */
const handleDelete = async (row: any) => {
const index = tableData.value.findIndex(
(item) => item.bizId === row.bizId && item.bizType === row.bizType,
);
if (index !== -1) {
tableData.value.splice(index, 1);
}
// 通知父组件更新
emit('update:items', [...tableData.value]);
};
/** 处理行数据变更 */
const handleRowChange = (row: any) => {
const index = tableData.value.findIndex(
(item) => item.bizId === row.bizId && item.bizType === row.bizType,
);
if (index === -1) {
tableData.value.push(row);
} else {
tableData.value[index] = row;
}
emit('update:items', [...tableData.value]);
};
/** 表单校验 */
const validate = () => {
// 检查是否有明细
if (tableData.value.length === 0) {
throw new Error('请添加付款明细');
}
// 检查每行的付款金额
for (let i = 0; i < tableData.value.length; i++) {
const item = tableData.value[i];
if (!item.paymentPrice || item.paymentPrice <= 0) {
throw new Error(`${i + 1}本次付款必须大于0`);
}
}
};
defineExpose({ validate });
</script>
<template>
<Grid class="w-full">
<template #paymentPrice="{ row }">
<InputNumber
v-model:value="row.paymentPrice"
:precision="2"
:disabled="disabled"
:formatter="erpPriceInputFormatter"
placeholder="请输入本次付款"
@change="handleRowChange(row)"
/>
</template>
<template #remark="{ row }">
<Input
v-model:value="row.remark"
:disabled="disabled"
placeholder="请输入备注"
@change="handleRowChange(row)"
/>
</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>
合计付款{{ erpPriceInputFormatter(summaries.totalPrice) }}
</span>
<span>
已付金额{{ erpPriceInputFormatter(summaries.paidPrice) }}
</span>
<span>
本次付款
{{ erpPriceInputFormatter(summaries.paymentPrice) }}
</span>
</div>
</div>
</div>
<TableAction
v-if="!disabled"
class="mt-2 flex justify-center"
:actions="[
{
label: '添加采购入库单',
type: 'default',
onClick: handleOpenPurchaseIn,
},
{
label: '添加采购退货单',
type: 'default',
onClick: handleOpenSaleReturn,
},
]"
/>
</template>
</Grid>
<!-- 采购入库单选择组件 -->
<PurchaseInSelect ref="purchaseInSelectRef" @success="handleAddPurchaseIn" />
<!-- 采购退货单选择组件 -->
<SaleReturnSelect ref="saleReturnSelectRef" @success="handleAddSaleReturn" />
</template>

View File

@@ -0,0 +1,108 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { ErpPurchaseInApi } from '#/api/erp/purchase/in';
import { ref } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getPurchaseInPage } from '#/api/erp/purchase/in';
import { usePurchaseInGridColumns, usePurchaseInGridFormSchema } from '../data';
const emit = defineEmits<{
success: [rows: ErpPurchaseInApi.PurchaseIn[]];
}>();
const supplierId = ref<number>(); // 供应商ID
const open = ref<boolean>(false); // 弹窗是否打开
const selectedRows = ref<ErpPurchaseInApi.PurchaseIn[]>([]); // 选中的行
/** 表格配置 */
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: usePurchaseInGridFormSchema(),
},
gridOptions: {
columns: usePurchaseInGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getPurchaseInPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
supplierId: supplierId.value,
paymentEnable: true, // 只查询可付款的
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
checkboxConfig: {
highlight: true,
range: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<ErpPurchaseInApi.PurchaseIn>,
gridEvents: {
checkboxChange: ({
records,
}: {
records: ErpPurchaseInApi.PurchaseIn[];
}) => {
selectedRows.value = records;
},
checkboxAll: ({ records }: { records: ErpPurchaseInApi.PurchaseIn[] }) => {
selectedRows.value = records;
},
},
});
/** 打开弹窗 */
const openModal = (id: number) => {
// 重置数据
supplierId.value = id;
open.value = true;
selectedRows.value = [];
// 查询列表
gridApi.formApi?.resetForm();
gridApi.formApi?.setValues({ supplierId: id });
gridApi.query();
};
/** 确认选择采购入库单 */
const handleOk = () => {
if (selectedRows.value.length === 0) {
message.warning('请选择要添加的采购入库单');
return;
}
emit('success', selectedRows.value);
open.value = false;
};
defineExpose({ open: openModal });
</script>
<template>
<Modal
class="!w-[50vw]"
v-model:open="open"
title="选择采购入库单"
@ok="handleOk"
>
<Grid
class="max-h-[600px]"
table-title="采购入库单列表(仅展示可付款的单据)"
/>
</Modal>
</template>

View File

@@ -0,0 +1,112 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { ErpPurchaseReturnApi } from '#/api/erp/purchase/return';
import { ref } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getPurchaseReturnPage } from '#/api/erp/purchase/return';
import { useSaleReturnGridColumns, useSaleReturnGridFormSchema } from '../data';
const emit = defineEmits<{
success: [rows: ErpPurchaseReturnApi.PurchaseReturn[]];
}>();
const supplierId = ref<number>(); // 供应商ID
const open = ref<boolean>(false); // 弹窗是否打开
const selectedRows = ref<ErpPurchaseReturnApi.PurchaseReturn[]>([]); // 选中的行
/** 表格配置 */
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useSaleReturnGridFormSchema(),
},
gridOptions: {
columns: useSaleReturnGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getPurchaseReturnPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
supplierId: supplierId.value,
refundEnable: true, // 只查询可退款的
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
checkboxConfig: {
highlight: true,
range: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<ErpPurchaseReturnApi.PurchaseReturn>,
gridEvents: {
checkboxChange: ({
records,
}: {
records: ErpPurchaseReturnApi.PurchaseReturn[];
}) => {
selectedRows.value = records;
},
checkboxAll: ({
records,
}: {
records: ErpPurchaseReturnApi.PurchaseReturn[];
}) => {
selectedRows.value = records;
},
},
});
/** 打开弹窗 */
const openModal = (id: number) => {
// 重置数据
supplierId.value = id;
open.value = true;
selectedRows.value = [];
// 查询列表
gridApi.formApi?.resetForm();
gridApi.formApi?.setValues({ supplierId: id });
gridApi.query();
};
/** 确认选择 */
const handleOk = () => {
if (selectedRows.value.length === 0) {
message.warning('请选择要添加的采购退货单');
return;
}
emit('success', selectedRows.value);
open.value = false;
};
defineExpose({ open: openModal });
</script>
<template>
<Modal
class="!w-[50vw]"
v-model:open="open"
title="选择采购退货单"
@ok="handleOk"
>
<Grid
class="max-h-[600px]"
table-title="采购退货单列表(仅展示需退款的单据)"
/>
</Modal>
</template>

View File

@@ -0,0 +1,597 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { erpPriceInputFormatter } from '@vben/utils';
import { getAccountSimpleList } from '#/api/erp/finance/account';
import { getCustomerSimpleList } from '#/api/erp/sale/customer';
import { getSimpleUserList } from '#/api/system/user';
import { getRangePickerDefaultProps } from '#/utils';
/** 表单的配置项 */
export function useFormSchema(formType: string): VbenFormSchema[] {
return [
{
fieldName: 'id',
component: 'Input',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'no',
label: '收款单号',
component: 'Input',
componentProps: {
placeholder: '系统自动生成',
disabled: true,
},
},
{
fieldName: 'receiptTime',
label: '收款时间',
component: 'DatePicker',
componentProps: {
disabled: formType === 'detail',
placeholder: '选择收款时间',
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
valueFormat: 'x',
},
rules: 'required',
},
{
fieldName: 'customerId',
label: '客户',
component: 'ApiSelect',
componentProps: {
disabled: formType === 'detail',
placeholder: '请选择客户',
allowClear: true,
showSearch: true,
api: getCustomerSimpleList,
fieldNames: {
label: 'name',
value: 'id',
},
},
rules: 'required',
},
{
fieldName: 'financeUserId',
label: '财务人员',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择财务人员',
allowClear: true,
showSearch: true,
api: getSimpleUserList,
fieldNames: {
label: 'nickname',
value: 'id',
},
},
},
{
fieldName: 'remark',
label: '备注',
component: 'Textarea',
componentProps: {
placeholder: '请输入备注',
autoSize: { minRows: 1, maxRows: 1 },
disabled: formType === 'detail',
},
formItemClass: 'col-span-2',
},
{
fieldName: 'fileUrl',
label: '附件',
component: 'FileUpload',
componentProps: {
maxNumber: 1,
maxSize: 10,
accept: [
'pdf',
'doc',
'docx',
'xls',
'xlsx',
'txt',
'jpg',
'jpeg',
'png',
],
showDescription: formType !== 'detail',
disabled: formType === 'detail',
},
formItemClass: 'col-span-3',
},
{
fieldName: 'items',
label: '销售出库、退货单',
component: 'Input',
formItemClass: 'col-span-3',
},
{
fieldName: 'accountId',
label: '收款账户',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择收款账户',
allowClear: true,
showSearch: true,
api: getAccountSimpleList,
fieldNames: {
label: 'name',
value: 'id',
},
},
},
{
fieldName: 'totalPrice',
label: '合计收款',
component: 'InputNumber',
componentProps: {
placeholder: '合计收款',
precision: 2,
formatter: erpPriceInputFormatter,
disabled: true,
},
},
{
fieldName: 'discountPrice',
label: '优惠金额',
component: 'InputNumber',
componentProps: {
disabled: formType === 'detail',
placeholder: '请输入优惠金额',
precision: 2,
formatter: erpPriceInputFormatter,
},
},
{
fieldName: 'receiptPrice',
label: '实际收款',
component: 'InputNumber',
componentProps: {
placeholder: '实际收款',
precision: 2,
formatter: erpPriceInputFormatter,
disabled: true,
},
dependencies: {
triggerFields: ['totalPrice', 'discountPrice'],
componentProps: (values) => {
const totalPrice = values.totalPrice || 0;
const discountPrice = values.discountPrice || 0;
values.receiptPrice = totalPrice - discountPrice;
return {};
},
},
},
];
}
/** 表单的明细表格列 */
export function useFormItemColumns(): VxeTableGridOptions['columns'] {
return [
{ type: 'seq', title: '序号', minWidth: 50, fixed: 'left' },
{
field: 'bizNo',
title: '销售单据编号',
minWidth: 200,
},
{
field: 'totalPrice',
title: '应收金额',
minWidth: 100,
formatter: 'formatAmount2',
},
{
field: 'receiptedPrice',
title: '已收金额',
minWidth: 100,
formatter: 'formatAmount2',
},
{
field: 'receiptPrice',
title: '本次收款',
minWidth: 115,
fixed: 'right',
slots: { default: 'receiptPrice' },
},
{
field: 'remark',
title: '备注',
minWidth: 150,
slots: { default: 'remark' },
},
{
title: '操作',
width: 50,
fixed: 'right',
slots: { default: 'actions' },
},
];
}
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'no',
label: '收款单号',
component: 'Input',
componentProps: {
placeholder: '请输入收款单号',
allowClear: true,
},
},
{
fieldName: 'receiptTime',
label: '收款时间',
component: 'RangePicker',
componentProps: {
...getRangePickerDefaultProps(),
allowClear: true,
},
},
{
fieldName: 'customerId',
label: '客户',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择客户',
allowClear: true,
showSearch: true,
api: getCustomerSimpleList,
fieldNames: {
label: 'name',
value: 'id',
},
},
},
{
fieldName: 'creator',
label: '创建人',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择创建人',
allowClear: true,
showSearch: true,
api: getSimpleUserList,
fieldNames: {
label: 'nickname',
value: 'id',
},
},
},
{
fieldName: 'financeUserId',
label: '财务人员',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择财务人员',
allowClear: true,
showSearch: true,
api: getSimpleUserList,
fieldNames: {
label: 'nickname',
value: 'id',
},
},
},
{
fieldName: 'accountId',
label: '收款账户',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择收款账户',
allowClear: true,
showSearch: true,
api: getAccountSimpleList,
fieldNames: {
label: 'name',
value: 'id',
},
},
},
{
fieldName: 'status',
label: '状态',
component: 'Select',
componentProps: {
options: getDictOptions(DICT_TYPE.ERP_AUDIT_STATUS, 'number'),
placeholder: '请选择状态',
allowClear: true,
},
},
{
fieldName: 'remark',
label: '备注',
component: 'Input',
componentProps: {
placeholder: '请输入备注',
allowClear: true,
},
},
{
fieldName: 'bizNo',
label: '销售单号',
component: 'Input',
componentProps: {
placeholder: '请输入销售单号',
allowClear: true,
},
},
];
}
/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{
type: 'checkbox',
width: 50,
fixed: 'left',
},
{
field: 'no',
title: '收款单号',
width: 180,
fixed: 'left',
},
{
field: 'customerName',
title: '客户',
minWidth: 120,
},
{
field: 'receiptTime',
title: '收款时间',
width: 160,
formatter: 'formatDate',
},
{
field: 'creatorName',
title: '创建人',
minWidth: 120,
},
{
field: 'financeUserName',
title: '财务人员',
minWidth: 120,
},
{
field: 'accountName',
title: '收款账户',
minWidth: 120,
},
{
field: 'totalPrice',
title: '合计收款',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'discountPrice',
title: '优惠金额',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'receiptPrice',
title: '实际收款',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'status',
title: '状态',
minWidth: 90,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.ERP_AUDIT_STATUS },
},
},
{
title: '操作',
width: 220,
fixed: 'right',
slots: { default: 'actions' },
},
];
}
/** 销售出库单选择表单的配置项 */
export function useSaleOutGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'no',
label: '出库单号',
component: 'Input',
componentProps: {
placeholder: '请输入出库单号',
allowClear: true,
},
},
{
fieldName: 'customerId',
label: '客户',
component: 'Input',
componentProps: {
disabled: true,
placeholder: '已自动选择客户',
},
},
{
fieldName: 'receiptStatus',
label: '收款状态',
component: 'Select',
componentProps: {
options: [
{ label: '未收款', value: 0 },
{ label: '部分收款', value: 1 },
{ label: '全部收款', value: 2 },
],
placeholder: '请选择收款状态',
allowClear: true,
},
},
];
}
/** 销售出库单选择列表的字段 */
export function useSaleOutGridColumns(): VxeTableGridOptions['columns'] {
return [
{
type: 'checkbox',
width: 50,
fixed: 'left',
},
{
field: 'no',
title: '出库单号',
width: 200,
fixed: 'left',
},
{
field: 'customerName',
title: '客户',
minWidth: 120,
},
{
field: 'outTime',
title: '出库时间',
width: 160,
formatter: 'formatDate',
},
{
field: 'totalPrice',
title: '应收金额',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'receiptPrice',
title: '已收金额',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'unReceiptPrice',
title: '未收金额',
formatter: ({ row }) => {
return erpPriceInputFormatter(row.totalPrice - row.receiptPrice || 0);
},
minWidth: 120,
},
{
field: 'status',
title: '状态',
minWidth: 100,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.ERP_AUDIT_STATUS },
},
},
];
}
/** 销售退货单选择表单的配置项 */
export function useSaleReturnGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'no',
label: '退货单号',
component: 'Input',
componentProps: {
placeholder: '请输入退货单号',
allowClear: true,
},
},
{
fieldName: 'customerId',
label: '客户',
component: 'Input',
componentProps: {
disabled: true,
placeholder: '已自动选择客户',
},
},
{
fieldName: 'refundStatus',
label: '退款状态',
component: 'Select',
componentProps: {
options: [
{ label: '未退款', value: 0 },
{ label: '部分退款', value: 1 },
{ label: '全部退款', value: 2 },
],
placeholder: '请选择退款状态',
allowClear: true,
},
},
];
}
/** 销售退货单选择列表的字段 */
export function useSaleReturnGridColumns(): VxeTableGridOptions['columns'] {
return [
{
type: 'checkbox',
width: 50,
fixed: 'left',
},
{
field: 'no',
title: '退货单号',
width: 200,
fixed: 'left',
},
{
field: 'customerName',
title: '客户',
minWidth: 120,
},
{
field: 'returnTime',
title: '退货时间',
width: 160,
formatter: 'formatDate',
},
{
field: 'totalPrice',
title: '应退金额',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'refundPrice',
title: '已退金额',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'unRefundPrice',
title: '未退金额',
formatter: ({ row }) => {
return erpPriceInputFormatter(row.totalPrice - row.refundPrice || 0);
},
minWidth: 120,
},
{
field: 'status',
title: '状态',
minWidth: 100,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.ERP_AUDIT_STATUS },
},
},
];
}

View File

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

View File

@@ -0,0 +1,194 @@
<script lang="ts" setup>
import type { ErpFinanceReceiptApi } from '#/api/erp/finance/receipt';
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 {
createFinanceReceipt,
getFinanceReceipt,
updateFinanceReceipt,
} from '#/api/erp/finance/receipt';
import { useFormSchema } from '../data';
import ItemForm from './item-form.vue';
const emit = defineEmits(['success']);
const formData = ref<
ErpFinanceReceiptApi.FinanceReceipt & {
fileUrl?: string;
}
>({
id: undefined,
no: undefined,
customerId: undefined,
accountId: undefined,
financeUserId: undefined,
receiptTime: undefined,
remark: undefined,
fileUrl: undefined,
totalPrice: 0,
discountPrice: 0,
receiptPrice: 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) => {
if (formData.value) {
if (changedFields.includes('customerId')) {
formData.value.customerId = values.customerId;
}
// 目的:同步到 item-form 组件,触发整体的价格计算
if (changedFields.includes('discountPrice')) {
formData.value.discountPrice = values.discountPrice;
formData.value.receiptPrice =
formData.value.totalPrice - values.discountPrice;
formApi.setValues({
receiptPrice: formData.value.receiptPrice,
});
}
}
},
});
/** 更新收款项 */
const handleUpdateItems = (
items: ErpFinanceReceiptApi.FinanceReceiptItem[],
) => {
formData.value.items = items;
formApi.setValues({
items,
});
};
/** 更新总金额 */
const handleUpdateTotalPrice = (totalPrice: number) => {
formData.value.totalPrice = totalPrice;
formApi.setValues({
totalPrice: formData.value.totalPrice,
});
};
/** 更新收款金额 */
const handleUpdateReceiptPrice = (receiptPrice: number) => {
formData.value.receiptPrice = receiptPrice;
formApi.setValues({
receiptPrice: formData.value.receiptPrice,
});
};
/** 创建或更新收款单 */
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 ErpFinanceReceiptApi.FinanceReceipt;
try {
await (formType.value === 'create'
? createFinanceReceipt(data)
: updateFinanceReceipt(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 getFinanceReceipt(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 ?? []"
:customer-id="formData?.customerId"
:disabled="formType === 'detail'"
:discount-price="formData?.discountPrice ?? 0"
@update:items="handleUpdateItems"
@update:total-price="handleUpdateTotalPrice"
@update:receipt-price="handleUpdateReceiptPrice"
/>
</template>
</Form>
</Modal>
</template>

View File

@@ -0,0 +1,292 @@
<script lang="ts" setup>
import type { ErpFinanceReceiptApi } from '#/api/erp/finance/receipt';
import type { ErpSaleOutApi } from '#/api/erp/sale/out';
import type { ErpSaleReturnApi } from '#/api/erp/sale/return';
import { computed, nextTick, ref, watch } from 'vue';
import { ErpBizType } from '@vben/constants';
import { erpPriceInputFormatter } from '@vben/utils';
import { Input, InputNumber, message } from 'ant-design-vue';
import { TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { useFormItemColumns } from '../data';
import SaleOutSelect from './sale-out-select.vue';
import SaleReturnSelect from './sale-return-select.vue';
interface Props {
items?: ErpFinanceReceiptApi.FinanceReceiptItem[];
customerId?: number;
disabled?: boolean;
discountPrice?: number;
}
const props = withDefaults(defineProps<Props>(), {
items: () => [],
customerId: undefined,
disabled: false,
discountPrice: 0,
});
const emit = defineEmits([
'update:items',
'update:total-price',
'update:receipt-price',
]);
const tableData = ref<ErpFinanceReceiptApi.FinanceReceiptItem[]>([]); // 表格数据
/** 获取表格合计数据 */
const summaries = computed(() => {
return {
totalPrice: tableData.value.reduce(
(sum, item) => sum + (item.totalPrice || 0),
0,
),
receiptedPrice: tableData.value.reduce(
(sum, item) => sum + (item.receiptedPrice || 0),
0,
),
receiptPrice: tableData.value.reduce(
(sum, item) => sum + (item.receiptPrice || 0),
0,
),
};
});
/** 表格配置 */
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions: {
columns: useFormItemColumns(),
data: tableData.value,
minHeight: 250,
autoResize: true,
border: true,
rowConfig: {
keyField: 'seq',
isHover: true,
},
pagerConfig: {
enabled: false,
},
toolbarConfig: {
enabled: false,
},
},
});
/** 监听外部传入的列数据 */
watch(
() => props.items,
async (items) => {
if (!items) {
return;
}
tableData.value = [...items];
await nextTick(); // 特殊:保证 gridApi 已经初始化
await gridApi.grid.reloadData(tableData.value);
},
{
immediate: true,
},
);
/** 计算 totalPrice、receiptPrice 价格 */
watch(
() => [tableData.value, props.discountPrice],
() => {
if (!tableData.value || tableData.value.length === 0) {
return;
}
const totalPrice = tableData.value.reduce(
(prev, curr) => prev + (curr.totalPrice || 0),
0,
);
const receiptPrice = tableData.value.reduce(
(prev, curr) => prev + (curr.receiptPrice || 0),
0,
);
const finalReceiptPrice = receiptPrice - (props.discountPrice || 0);
// 通知父组件更新
emit('update:total-price', totalPrice);
emit('update:receipt-price', finalReceiptPrice);
},
{ deep: true },
);
/** 添加销售出库单 */
const saleOutSelectRef = ref();
const handleOpenSaleOut = () => {
if (!props.customerId) {
message.error('请选择客户');
return;
}
saleOutSelectRef.value?.open(props.customerId);
};
const handleAddSaleOut = (rows: ErpSaleOutApi.SaleOut[]) => {
rows.forEach((row) => {
const newItem: ErpFinanceReceiptApi.FinanceReceiptItem = {
bizId: row.id,
bizType: ErpBizType.SALE_OUT,
bizNo: row.no,
totalPrice: row.totalPrice,
receiptedPrice: row.receiptPrice,
receiptPrice: row.totalPrice - row.receiptPrice,
remark: undefined,
};
tableData.value.push(newItem);
});
emit('update:items', [...tableData.value]);
};
/** 添加销售退货单 */
const saleReturnSelectRef = ref();
const handleOpenSaleReturn = () => {
if (!props.customerId) {
message.error('请选择客户');
return;
}
saleReturnSelectRef.value?.open(props.customerId);
};
const handleAddSaleReturn = (rows: ErpSaleReturnApi.SaleReturn[]) => {
rows.forEach((row) => {
const newItem: ErpFinanceReceiptApi.FinanceReceiptItem = {
bizId: row.id,
bizType: ErpBizType.SALE_RETURN,
bizNo: row.no,
totalPrice: -row.totalPrice,
receiptedPrice: -row.refundPrice,
receiptPrice: -row.totalPrice + row.refundPrice,
remark: undefined,
};
tableData.value.push(newItem);
});
emit('update:items', [...tableData.value]);
};
/** 删除行 */
const handleDelete = async (row: any) => {
const index = tableData.value.findIndex(
(item) => item.bizId === row.bizId && item.bizType === row.bizType,
);
if (index !== -1) {
tableData.value.splice(index, 1);
}
// 通知父组件更新
emit('update:items', [...tableData.value]);
};
/** 处理行数据变更 */
const handleRowChange = (row: any) => {
const index = tableData.value.findIndex(
(item) => item.bizId === row.bizId && item.bizType === row.bizType,
);
if (index === -1) {
tableData.value.push(row);
} else {
tableData.value[index] = row;
}
emit('update:items', [...tableData.value]);
};
/** 表单校验 */
const validate = () => {
// 检查是否有明细
if (tableData.value.length === 0) {
throw new Error('请添加收款明细');
}
// 检查每行的收款金额
for (let i = 0; i < tableData.value.length; i++) {
const item = tableData.value[i];
if (!item.receiptPrice || item.receiptPrice <= 0) {
throw new Error(`${i + 1}本次收款必须大于0`);
}
}
};
defineExpose({ validate });
</script>
<template>
<Grid class="w-full">
<template #receiptPrice="{ row }">
<InputNumber
v-model:value="row.receiptPrice"
:precision="2"
:disabled="disabled"
:formatter="erpPriceInputFormatter"
placeholder="请输入本次收款"
@change="handleRowChange(row)"
/>
</template>
<template #remark="{ row }">
<Input
v-model:value="row.remark"
:disabled="disabled"
placeholder="请输入备注"
@change="handleRowChange(row)"
/>
</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>
合计收款{{ erpPriceInputFormatter(summaries.totalPrice) }}
</span>
<span>
已收金额{{ erpPriceInputFormatter(summaries.receiptedPrice) }}
</span>
<span>
本次收款
{{ erpPriceInputFormatter(summaries.receiptPrice) }}
</span>
</div>
</div>
</div>
<TableAction
v-if="!disabled"
class="mt-2 flex justify-center"
:actions="[
{
label: '添加销售出库单',
type: 'default',
onClick: handleOpenSaleOut,
},
{
label: '添加销售退货单',
type: 'default',
onClick: handleOpenSaleReturn,
},
]"
/>
</template>
</Grid>
<!-- 销售出库单选择组件 -->
<SaleOutSelect ref="saleOutSelectRef" @success="handleAddSaleOut" />
<!-- 销售退货单选择组件 -->
<SaleReturnSelect ref="saleReturnSelectRef" @success="handleAddSaleReturn" />
</template>

View File

@@ -0,0 +1,104 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { ErpSaleOutApi } from '#/api/erp/sale/out';
import { ref } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getSaleOutPage } from '#/api/erp/sale/out';
import { useSaleOutGridColumns, useSaleOutGridFormSchema } from '../data';
const emit = defineEmits<{
success: [rows: ErpSaleOutApi.SaleOut[]];
}>();
const customerId = ref<number>(); // 客户ID
const open = ref<boolean>(false); // 弹窗是否打开
const selectedRows = ref<ErpSaleOutApi.SaleOut[]>([]); // 选中的行
/** 表格配置 */
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useSaleOutGridFormSchema(),
},
gridOptions: {
columns: useSaleOutGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getSaleOutPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
customerId: customerId.value,
receiptEnable: true, // 只查询可收款的
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
checkboxConfig: {
highlight: true,
range: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<ErpSaleOutApi.SaleOut>,
gridEvents: {
checkboxChange: ({ records }: { records: ErpSaleOutApi.SaleOut[] }) => {
selectedRows.value = records;
},
checkboxAll: ({ records }: { records: ErpSaleOutApi.SaleOut[] }) => {
selectedRows.value = records;
},
},
});
/** 打开弹窗 */
const openModal = (id: number) => {
// 重置数据
customerId.value = id;
open.value = true;
selectedRows.value = [];
// 查询列表
gridApi.formApi?.resetForm();
gridApi.formApi?.setValues({ customerId: id });
gridApi.query();
};
/** 确认选择销售出库单 */
const handleOk = () => {
if (selectedRows.value.length === 0) {
message.warning('请选择要添加的销售出库单');
return;
}
emit('success', selectedRows.value);
open.value = false;
};
defineExpose({ open: openModal });
</script>
<template>
<Modal
class="!w-[50vw]"
v-model:open="open"
title="选择销售出库单"
@ok="handleOk"
>
<Grid
class="max-h-[600px]"
table-title="销售出库单列表(仅展示可收款的单据)"
/>
</Modal>
</template>

View File

@@ -0,0 +1,108 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { ErpSaleReturnApi } from '#/api/erp/sale/return';
import { ref } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getSaleReturnPage } from '#/api/erp/sale/return';
import { useSaleReturnGridColumns, useSaleReturnGridFormSchema } from '../data';
const emit = defineEmits<{
success: [rows: ErpSaleReturnApi.SaleReturn[]];
}>();
const customerId = ref<number>(); // 客户ID
const open = ref<boolean>(false); // 弹窗是否打开
const selectedRows = ref<ErpSaleReturnApi.SaleReturn[]>([]); // 选中的行
/** 表格配置 */
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useSaleReturnGridFormSchema(),
},
gridOptions: {
columns: useSaleReturnGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getSaleReturnPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
customerId: customerId.value,
refundEnable: true, // 只查询可退款的
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
checkboxConfig: {
highlight: true,
range: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<ErpSaleReturnApi.SaleReturn>,
gridEvents: {
checkboxChange: ({
records,
}: {
records: ErpSaleReturnApi.SaleReturn[];
}) => {
selectedRows.value = records;
},
checkboxAll: ({ records }: { records: ErpSaleReturnApi.SaleReturn[] }) => {
selectedRows.value = records;
},
},
});
/** 打开弹窗 */
const openModal = (id: number) => {
// 重置数据
customerId.value = id;
open.value = true;
selectedRows.value = [];
// 查询列表
gridApi.formApi?.resetForm();
gridApi.formApi?.setValues({ customerId: id });
gridApi.query();
};
/** 确认选择销售退货单 */
const handleOk = () => {
if (selectedRows.value.length === 0) {
message.warning('请选择要添加的销售退货单');
return;
}
emit('success', selectedRows.value);
open.value = false;
};
defineExpose({ open: openModal });
</script>
<template>
<Modal
class="!w-[50vw]"
v-model:open="open"
title="选择销售退货单"
@ok="handleOk"
>
<Grid
class="max-h-[600px]"
table-title="销售退货单列表(仅展示可退款的单据)"
/>
</Modal>
</template>

View File

@@ -5,8 +5,8 @@ import { DocAlert, Page } from '@vben/common-ui';
import { Col, Row, Spin } from 'ant-design-vue';
import SummaryCard from './components/SummaryCard.vue';
import TimeSummaryChart from './components/TimeSummaryChart.vue';
import SummaryCard from './modules/SummaryCard.vue';
import TimeSummaryChart from './modules/TimeSummaryChart.vue';
/** ERP首页 */
defineOptions({ name: 'ErpHome' });

View File

@@ -32,7 +32,6 @@ const props = withDefaults(defineProps<Props>(), {
});
/** 概览数据 */
// TODO @nehc 8 4
const overviewItems = computed<AnalysisOverviewItem[]>(() => [
{
icon: SvgCardIcon,

View File

@@ -123,11 +123,9 @@ watch(
if (!val || val.length === 0) {
return;
}
//
const xAxisData = val.map((item) => item.time);
const seriesData = val.map((item) => item.price);
const options = {
...lineChartOptions,
xAxis: {
@@ -141,7 +139,6 @@ watch(
},
],
};
renderEcharts(options);
},
{ immediate: true },
@@ -151,14 +148,6 @@ watch(
onMounted(() => {
initData();
});
/** 暴露数据给父组件使用 */
defineExpose({
saleSummary,
purchaseSummary,
saleTimeSummaryList,
purchaseTimeSummaryList,
});
</script>
<template>

View File

@@ -58,7 +58,7 @@ export function useFormSchema(): VbenFormSchema[] {
componentProps: {
placeholder: '请输入分类编码',
},
rules: z.string().regex(/^[A-Z]+$/, '分类编码必须为大写字母'),
rules: 'required',
},
{
fieldName: 'sort',
@@ -71,7 +71,6 @@ export function useFormSchema(): VbenFormSchema[] {
},
rules: 'required',
},
{
fieldName: 'status',
label: '状态',
@@ -86,6 +85,31 @@ export function useFormSchema(): VbenFormSchema[] {
];
}
/** 查询表单 */
export function useQueryFormSchema(): VbenFormSchema[] {
return [
{
component: 'Input',
fieldName: 'name',
label: '分类名称',
componentProps: {
placeholder: '请输入分类名称',
allowClear: true,
},
},
{
component: 'Select',
fieldName: 'status',
label: '开启状态',
componentProps: {
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
placeholder: '请选择开启状态',
allowClear: true,
},
},
];
}
/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions<ErpProductCategoryApi.ProductCategory>['columns'] {
return [

View File

@@ -5,17 +5,19 @@ import type { ErpProductCategoryApi } from '#/api/erp/product/category';
import { ref } from 'vue';
import { DocAlert, Page, useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart } from '@vben/utils';
import { message } from 'ant-design-vue';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteProductCategory,
exportProductCategory,
getProductCategoryList,
} from '#/api/erp/product/category';
import { $t } from '#/locales';
import { useGridColumns } from './data';
import { useGridColumns, useQueryFormSchema } from './data';
import Form from './modules/form.vue';
const [FormModal, formModalApi] = useVbenModal({
@@ -25,16 +27,22 @@ const [FormModal, formModalApi] = useVbenModal({
/** 切换树形展开/收缩状态 */
const isExpanded = ref(true);
function toggleExpand() {
function handleExpand() {
isExpanded.value = !isExpanded.value;
gridApi.grid.setAllTreeExpand(isExpanded.value);
}
/** 刷新表格 */
function onRefresh() {
function handleRefresh() {
gridApi.query();
}
/** 导出表格 */
async function handleExport() {
const data = await exportProductCategory(await gridApi.formApi.getValues());
downloadFileFromBlobPart({ fileName: '产品分类.xls', source: data });
}
/** 创建分类 */
function handleCreate() {
formModalApi.setData(null).open();
@@ -58,29 +66,30 @@ async function handleDelete(row: ErpProductCategoryApi.ProductCategory) {
});
try {
await deleteProductCategory(row.id as number);
message.success({
content: $t('ui.actionMessage.deleteSuccess', [row.name]),
});
onRefresh();
message.success($t('ui.actionMessage.deleteSuccess', [row.name]));
handleRefresh();
} finally {
hideLoading();
}
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useQueryFormSchema(),
},
gridOptions: {
columns: useGridColumns(),
height: 'auto',
proxyConfig: {
ajax: {
query: async () => {
return await getProductCategoryList();
},
},
},
pagerConfig: {
enabled: false,
},
proxyConfig: {
ajax: {
query: async (_, formValues) => {
return await getProductCategoryList(formValues);
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
@@ -90,11 +99,11 @@ const [Grid, gridApi] = useVbenVxeGrid({
search: true,
},
treeConfig: {
transform: true,
rowField: 'id',
parentField: 'parentId',
rowField: 'id',
transform: true,
expandAll: true,
accordion: false,
reserve: true,
},
} as VxeTableGridOptions<ErpProductCategoryApi.ProductCategory>,
});
@@ -108,7 +117,8 @@ const [Grid, gridApi] = useVbenVxeGrid({
url="https://doc.iocoder.cn/erp/product/"
/>
</template>
<FormModal @success="onRefresh" />
<FormModal @success="handleRefresh" />
<Grid table-title="产品分类列表">
<template #toolbar-tools>
<TableAction
@@ -120,10 +130,17 @@ const [Grid, gridApi] = useVbenVxeGrid({
auth: ['erp:product-category:create'],
onClick: handleCreate,
},
{
label: $t('ui.actionTitle.export'),
type: 'primary',
icon: ACTION_ICON.DOWNLOAD,
auth: ['erp:product-category:export'],
onClick: handleExport,
},
{
label: isExpanded ? '收缩' : '展开',
type: 'primary',
onClick: toggleExpand,
onClick: handleExpand,
},
]"
/>
@@ -151,7 +168,7 @@ const [Grid, gridApi] = useVbenVxeGrid({
danger: true,
icon: ACTION_ICON.DELETE,
auth: ['erp:product-category:delete'],
ifShow: !(row.children && row.children.length > 0),
disabled: row.children && row.children.length > 0,
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.name]),
confirm: handleDelete.bind(null, row),

View File

@@ -66,21 +66,20 @@ const [Modal, modalApi] = useVbenModal({
return;
}
// 加载数据
let data = modalApi.getData<ErpProductCategoryApi.ProductCategory>();
if (!data) {
const data = modalApi.getData<ErpProductCategoryApi.ProductCategory>();
if (!data || !data.id) {
// 设置上级
await formApi.setValues(data);
return;
}
if (data.id) {
modalApi.lock();
try {
data = await getProductCategory(data.id);
} finally {
modalApi.unlock();
}
modalApi.lock();
try {
formData.value = await getProductCategory(data.id);
// 设置到 values
await formApi.setValues(formData.value);
} finally {
modalApi.unlock();
}
// 设置到 values
formData.value = data;
await formApi.setValues(formData.value);
},
});
</script>

View File

@@ -3,7 +3,6 @@ import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import { CommonStatusEnum, DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { handleTree } from '@vben/utils';
import { z } from '#/adapter/form';
import { getProductCategorySimpleList } from '#/api/erp/product/category';
@@ -109,6 +108,9 @@ export function useFormSchema(): VbenFormSchema[] {
component: 'InputNumber',
componentProps: {
placeholder: '请输入采购价格,单位:元',
precision: 2,
min: 0,
step: 0.01,
},
},
{
@@ -117,6 +119,9 @@ export function useFormSchema(): VbenFormSchema[] {
component: 'InputNumber',
componentProps: {
placeholder: '请输入销售价格,单位:元',
precision: 2,
min: 0,
step: 0.01,
},
},
{
@@ -125,12 +130,18 @@ export function useFormSchema(): VbenFormSchema[] {
component: 'InputNumber',
componentProps: {
placeholder: '请输入最低价格,单位:元',
precision: 2,
min: 0,
step: 0.01,
},
},
{
fieldName: 'remark',
label: '备注',
component: 'Textarea',
componentProps: {
placeholder: '请输入备注',
},
},
];
}
@@ -142,6 +153,10 @@ export function useGridFormSchema(): VbenFormSchema[] {
fieldName: 'name',
label: '名称',
component: 'Input',
componentProps: {
placeholder: '请输入名称',
allowClear: true,
},
},
{
fieldName: 'categoryId',
@@ -169,38 +184,50 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
{
field: 'barCode',
title: '条码',
minWidth: 120,
},
{
field: 'name',
title: '名称',
minWidth: 200,
},
{
field: 'standard',
title: '规格',
minWidth: 100,
},
{
field: 'categoryName',
title: '分类',
minWidth: 120,
},
{
field: 'unitName',
title: '单位',
minWidth: 100,
},
{
field: 'purchasePrice',
title: '采购价格',
minWidth: 100,
formatter: 'formatAmount2',
},
{
field: 'salePrice',
title: '销售价格',
minWidth: 100,
formatter: 'formatAmount2',
},
{
field: 'minPrice',
title: '最低价格',
minWidth: 100,
formatter: 'formatAmount2',
},
{
field: 'status',
title: '状态',
minWidth: 100,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.COMMON_STATUS },
@@ -209,6 +236,7 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
{
field: 'createTime',
title: '创建时间',
minWidth: 180,
formatter: 'formatDateTime',
},
{

View File

@@ -24,7 +24,7 @@ const [FormModal, formModalApi] = useVbenModal({
});
/** 刷新表格 */
function onRefresh() {
function handleRefresh() {
gridApi.query();
}
@@ -52,10 +52,8 @@ async function handleDelete(row: ErpProductApi.Product) {
});
try {
await deleteProduct(row.id as number);
message.success({
content: $t('ui.actionMessage.deleteSuccess', [row.name]),
});
onRefresh();
message.success($t('ui.actionMessage.deleteSuccess', [row.name]));
handleRefresh();
} finally {
hideLoading();
}
@@ -100,7 +98,8 @@ const [Grid, gridApi] = useVbenVxeGrid({
url="https://doc.iocoder.cn/erp/product/"
/>
</template>
<FormModal @success="onRefresh" />
<FormModal @success="handleRefresh" />
<Grid table-title="产品列表">
<template #toolbar-tools>
<TableAction

View File

@@ -79,7 +79,7 @@ const [Modal, modalApi] = useVbenModal({
</script>
<template>
<Modal class="w-2/5" :title="getTitle">
<Modal :title="getTitle" class="w-1/2">
<Form class="mx-4" />
</Modal>
</template>

View File

@@ -22,6 +22,9 @@ export function useFormSchema(): VbenFormSchema[] {
fieldName: 'name',
label: '单位名称',
rules: 'required',
componentProps: {
placeholder: '请输入单位名称',
},
},
{
fieldName: 'status',
@@ -44,12 +47,17 @@ export function useGridFormSchema(): VbenFormSchema[] {
fieldName: 'name',
label: '单位名称',
component: 'Input',
componentProps: {
placeholder: '请输入单位名称',
allowClear: true,
},
},
{
fieldName: 'status',
label: '单位状态',
component: 'Select',
componentProps: {
placeholder: '请选择单位状态',
allowClear: true,
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
},
@@ -63,14 +71,17 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
{
field: 'id',
title: '单位编号',
minWidth: 100,
},
{
field: 'name',
title: '单位名称',
minWidth: 200,
},
{
field: 'status',
title: '单位状态',
minWidth: 100,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.COMMON_STATUS },
@@ -79,6 +90,7 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
{
field: 'createTime',
title: '创建时间',
minWidth: 180,
formatter: 'formatDateTime',
},
{

View File

@@ -24,7 +24,7 @@ const [FormModal, formModalApi] = useVbenModal({
});
/** 刷新表格 */
function onRefresh() {
function handleRefresh() {
gridApi.query();
}
@@ -52,10 +52,8 @@ async function handleDelete(row: ErpProductUnitApi.ProductUnit) {
});
try {
await deleteProductUnit(row.id as number);
message.success({
content: $t('ui.actionMessage.deleteSuccess', [row.name]),
});
onRefresh();
message.success($t('ui.actionMessage.deleteSuccess', [row.name]));
handleRefresh();
} finally {
hideLoading();
}
@@ -100,7 +98,7 @@ const [Grid, gridApi] = useVbenVxeGrid({
url="https://doc.iocoder.cn/erp/product/"
/>
</template>
<FormModal @success="onRefresh" />
<FormModal @success="handleRefresh" />
<Grid table-title="产品单位列表">
<template #toolbar-tools>
<TableAction

View File

@@ -82,7 +82,7 @@ const [Modal, modalApi] = useVbenModal({
</script>
<template>
<Modal class="w-2/5" :title="getTitle">
<Modal :title="getTitle" class="w-1/2">
<Form class="mx-4" />
</Modal>
</template>

View File

@@ -3,7 +3,7 @@ import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { erpPriceInputFormatter } from '@vben/utils';
import { erpNumberFormatter, erpPriceInputFormatter } from '@vben/utils';
import { z } from '#/adapter/form';
import { getAccountSimpleList } from '#/api/erp/finance/account';
@@ -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: 'inTime',
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,24 @@ export function useFormSchema(formType: string): VbenFormSchema[] {
value: 'id',
},
},
fieldName: 'supplierId',
label: '供应商',
rules: 'required',
},
{
fieldName: 'orderNo',
label: '关联订单',
component: 'Input',
formItemClass: 'col-span-1',
componentProps: {
disabled: formType === 'detail',
placeholder: '请选择关联订单',
},
rules: 'required',
},
{
component: 'DatePicker',
componentProps: {
disabled: formType === 'detail',
placeholder: '选择订单时间',
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
valueFormat: 'x',
style: { width: '100%' },
},
fieldName: 'inTime',
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,73 +103,77 @@ 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: '请选择结算账户',
disabled: true,
allowClear: true,
showSearch: true,
api: getAccountSimpleList,
@@ -183,26 +182,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 +217,7 @@ export function usePurchaseOrderItemTableColumns(): VxeTableGridOptions['columns
},
{
field: 'stockCount',
title: '仓库库存',
title: '库存',
minWidth: 80,
},
{
@@ -232,15 +230,27 @@ export function usePurchaseOrderItemTableColumns(): VxeTableGridOptions['columns
title: '单位',
minWidth: 80,
},
{
field: 'remark',
title: '备注',
minWidth: 150,
slots: { default: 'remark' },
},
{
field: 'totalCount',
title: '原数量',
formatter: 'formatAmount3',
minWidth: 120,
fixed: 'right',
visible: formData && formData[0]?.inCount !== undefined,
},
{
field: 'inCount',
title: '已入库数量',
title: '已入库',
formatter: 'formatAmount3',
minWidth: 120,
fixed: 'right',
visible: formData && formData[0]?.returnCount !== undefined,
},
{
field: 'count',
@@ -267,7 +277,8 @@ export function usePurchaseOrderItemTableColumns(): VxeTableGridOptions['columns
fixed: 'right',
field: 'taxPercent',
title: '税率(%)',
minWidth: 100,
minWidth: 105,
slots: { default: 'taxPercent' },
},
{
fixed: 'right',
@@ -283,6 +294,12 @@ export function usePurchaseOrderItemTableColumns(): VxeTableGridOptions['columns
minWidth: 120,
formatter: 'formatAmount2',
},
{
title: '操作',
width: 50,
fixed: 'right',
slots: { default: 'actions' },
},
];
}
@@ -318,10 +335,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,
},
},
{
@@ -350,7 +365,6 @@ export function useGridFormSchema(): VbenFormSchema[] {
api: getWarehouseSimpleList,
labelField: 'name',
valueField: 'id',
filterOption: false,
},
},
{
@@ -377,6 +391,21 @@ export function useGridFormSchema(): VbenFormSchema[] {
allowClear: true,
},
},
{
fieldName: 'accountId',
label: '结算账户',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择结算账户',
allowClear: true,
showSearch: true,
api: getAccountSimpleList,
fieldNames: {
label: 'name',
value: 'id',
},
},
},
{
fieldName: 'paymentStatus',
label: '付款状态',
@@ -387,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,
},
},
{
@@ -442,7 +471,7 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
field: 'inTime',
title: '入库时间',
width: 160,
formatter: 'formatDateTime',
formatter: 'formatDate',
},
{
field: 'creatorName',
@@ -452,23 +481,32 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
{
field: 'totalCount',
title: '总数量',
formatter: 'formatAmount3',
minWidth: 120,
},
{
field: 'totalPrice',
title: '应付金额',
formatter: 'formatNumber',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'paymentPrice',
title: '已付金额',
formatter: 'formatNumber',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'unPaymentPrice',
title: '未付金额',
formatter: ({ row }) => {
return `${erpNumberFormatter(row.totalPrice - row.paymentPrice, 2)}`;
},
minWidth: 120,
},
{
field: 'status',
title: '状态',
title: '审批状态',
minWidth: 120,
cellRender: {
name: 'CellDict',
@@ -477,12 +515,13 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
},
{
title: '操作',
minWidth: 250,
width: 220,
fixed: 'right',
slots: { default: 'actions' },
},
];
}
/** 列表的搜索表单 */
export function useOrderGridFormSchema(): VbenFormSchema[] {
return [
@@ -493,7 +532,6 @@ export function useOrderGridFormSchema(): VbenFormSchema[] {
componentProps: {
placeholder: '请输入订单单号',
allowClear: true,
disabled: true,
},
},
{
@@ -516,10 +554,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,
},
},
];
@@ -564,23 +600,25 @@ export function useOrderGridColumns(): VxeTableGridOptions['columns'] {
{
field: 'totalCount',
title: '总数量',
formatter: 'formatAmount3',
minWidth: 120,
},
{
field: 'inCount',
title: '入库数量',
formatter: 'formatAmount3',
minWidth: 120,
},
{
field: 'totalProductPrice',
title: '金额合计',
formatter: 'formatNumber',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'totalPrice',
title: '含税金额',
formatter: 'formatNumber',
formatter: 'formatAmount2',
minWidth: 120,
},
];

View File

@@ -19,87 +19,82 @@ import {
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
import PurchaseInForm from './modules/purchase-in-form.vue';
import Form from './modules/form.vue';
/** ERP 采购入库列表 */
defineOptions({ name: 'ErpPurchaseIn' });
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: PurchaseInForm,
connectedComponent: Form,
destroyOnClose: true,
});
/** 刷新表格 */
function onRefresh() {
function handleRefresh() {
gridApi.query();
}
// TODO @Xuzhiqiang批量删除待实现
const checkedIds = ref<number[]>([]);
/** 详情 */
function handleDetail(row: ErpPurchaseInApi.PurchaseIn) {
formModalApi.setData({ type: 'detail', id: row.id }).open();
/** 导出表格 */
async function handleExport() {
const data = await exportPurchaseIn(await gridApi.formApi.getValues());
downloadFileFromBlobPart({ fileName: '采购入库.xls', source: data });
}
/** 新增 */
/** 新增采购入库 */
function handleCreate() {
formModalApi.setData({ type: 'create' }).open();
}
/** 编辑 */
/** 编辑采购入库 */
function handleEdit(row: ErpPurchaseInApi.PurchaseIn) {
formModalApi.setData({ type: 'edit', 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 deletePurchaseIn(ids);
message.success({
content: $t('ui.actionMessage.deleteSuccess'),
key: 'action_process_msg',
});
onRefresh();
} catch {
// 处理错误
message.success($t('ui.actionMessage.deleteSuccess'));
handleRefresh();
} finally {
hideLoading();
}
}
/** 审批/反审批操作 */
function handleUpdateStatus(row: ErpPurchaseInApi.PurchaseIn, status: number) {
async function handleUpdateStatus(
row: ErpPurchaseInApi.PurchaseIn,
status: number,
) {
const hideLoading = message.loading({
content: `确定${status === 20 ? '审批' : '反审批'}该订单吗?`,
duration: 0,
key: 'action_process_msg',
});
updatePurchaseInStatus(row.id!, status)
.then(() => {
message.success({
content: `${status === 20 ? '审批' : '反审批'}成功`,
key: 'action_process_msg',
});
onRefresh();
})
.catch(() => {
// 处理错误
})
.finally(() => {
hideLoading();
});
try {
await updatePurchaseInStatus(row.id!, status);
message.success(`${status === 20 ? '审批' : '反审批'}成功`);
handleRefresh();
} finally {
hideLoading();
}
}
/** 导出 */
async function handleExport() {
const data = await exportPurchaseIn(await gridApi.formApi.getValues());
downloadFileFromBlobPart({ fileName: '采购入库.xls', source: data });
const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
records,
}: {
records: ErpPurchaseInApi.PurchaseIn[];
}) {
checkedIds.value = records.map((item) => item.id!);
}
/** 查看详情 */
function handleDetail(row: ErpPurchaseInApi.PurchaseIn) {
formModalApi.setData({ type: 'detail', id: row.id }).open();
}
const [Grid, gridApi] = useVbenVxeGrid({
@@ -130,6 +125,10 @@ const [Grid, gridApi] = useVbenVxeGrid({
search: true,
},
} as VxeTableGridOptions<ErpPurchaseInApi.PurchaseIn>,
gridEvents: {
checkboxAll: handleRowCheckboxChange,
checkboxChange: handleRowCheckboxChange,
},
});
</script>
@@ -141,8 +140,8 @@ const [Grid, gridApi] = useVbenVxeGrid({
url="https://doc.iocoder.cn/erp/purchase/"
/>
</template>
<FormModal @success="onRefresh" />
<FormModal @success="handleRefresh" />
<Grid table-title="采购入库列表">
<template #toolbar-tools>
<TableAction
@@ -170,14 +169,7 @@ const [Grid, gridApi] = useVbenVxeGrid({
auth: ['erp:purchase-in:delete'],
popConfirm: {
title: `是否删除所选中数据?`,
confirm: () => {
const checkboxRecords = gridApi.grid.getCheckboxRecords();
if (checkboxRecords.length === 0) {
message.warning('请选择要删除的数据');
return;
}
handleDelete(checkboxRecords.map((item) => item.id!));
},
confirm: handleDelete.bind(null, checkedIds),
},
},
]"
@@ -222,7 +214,7 @@ const [Grid, gridApi] = useVbenVxeGrid({
auth: ['erp:purchase-in:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.no]),
confirm: () => handleDelete([row.id!]),
confirm: handleDelete.bind(null, [row.id!]),
},
},
]"

View File

@@ -0,0 +1,230 @@
<script lang="ts" setup>
import type { ErpPurchaseInApi } from '#/api/erp/purchase/in';
import type { ErpPurchaseOrderApi } from '#/api/erp/purchase/order';
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 {
createPurchaseIn,
getPurchaseIn,
updatePurchaseIn,
} from '#/api/erp/purchase/in';
import { useFormSchema } from '../data';
import ItemForm from './item-form.vue';
import PurchaseOrderSelect from './purchase-order-select.vue';
const emit = defineEmits(['success']);
const formData = ref<
ErpPurchaseInApi.PurchaseIn & {
accountId?: number;
customerId?: number;
discountPercent?: number;
fileUrl?: string;
order?: ErpPurchaseOrderApi.PurchaseOrder;
orderId?: number;
orderNo?: string;
}
>({
id: undefined,
no: undefined,
accountId: undefined,
inTime: 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: ErpPurchaseInApi.PurchaseInItem[]) => {
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.totalCount - item.inCount;
item.orderItemId = item.id;
item.id = undefined;
});
formData.value.items = order.items!.filter(
(item) => item.count && item.count > 0,
) as ErpPurchaseInApi.PurchaseInItem[];
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 ErpPurchaseInApi.PurchaseIn;
try {
await (formType.value === 'create'
? createPurchaseIn(data)
: updatePurchaseIn(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 getPurchaseIn(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,294 @@
<script lang="ts" setup>
import type { ErpPurchaseInApi } from '#/api/erp/purchase/in';
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?: ErpPurchaseInApi.PurchaseInItem[];
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<ErpPurchaseInApi.PurchaseInItem[]>([]); // 表格数据
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: 'seq',
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: ErpPurchaseInApi.PurchaseInItem) {
const index = tableData.value.findIndex((item) => item.seq === row.seq);
if (index !== -1) {
tableData.value.splice(index, 1);
}
// 通知父组件更新
emit('update:items', [...tableData.value]);
}
/** 处理仓库变更 */
const handleWarehouseChange = async (row: ErpPurchaseInApi.PurchaseInItem) => {
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.seq === row.seq);
if (index === -1) {
tableData.value.push(row);
} else {
tableData.value[index] = row;
}
emit('update:items', [...tableData.value]);
}
/** 初始化行数据 */
const initRow = (row: ErpPurchaseInApi.PurchaseInItem): 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>{{ erpCountInputFormatter(row.count) || '-' }}</span>
</template>
<template #productPrice="{ row }">
<InputNumber
v-if="!disabled"
v-model:value="row.productPrice"
:min="0"
:precision="2"
@change="handleRowChange(row)"
/>
<span v-else>{{ erpPriceInputFormatter(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"
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

@@ -1,311 +0,0 @@
<script lang="ts" setup>
import type { ErpPurchaseInApi } from '#/api/erp/purchase/in';
import type { ErpPurchaseOrderApi } from '#/api/erp/purchase/order';
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 {
createPurchaseIn,
getPurchaseIn,
updatePurchaseIn,
} from '#/api/erp/purchase/in';
import { useFormSchema } from '../data';
import PurchaseInItemForm from './purchase-in-item-form.vue';
import SelectPurchaseOrderForm from './select-purchase-order-form.vue';
const emit = defineEmits(['success']);
const formData = ref<
ErpPurchaseInApi.PurchaseIn & {
accountId?: number;
discountedPrice?: number;
discountPercent?: number;
fileUrl?: string;
order?: ErpPurchaseOrderApi.PurchaseOrder;
orderId?: number;
orderNo?: string;
supplierId?: number;
}
>({
id: undefined,
no: undefined,
accountId: undefined,
inTime: 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: ErpPurchaseInApi.PurchaseInItem[]) => {
if (formData.value) {
const data = await formApi.getValues();
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.totalCount - item.inCount;
item.orderItemId = item.id;
item.id = undefined;
});
formData.value.items = order.items!.filter(
(item) => item.count && item.count > 0,
) as ErpPurchaseInApi.PurchaseInItem[];
formApi.setValues(formData.value, false);
};
watch(
() => formData.value.items!,
(newItems: ErpPurchaseInApi.PurchaseInItem[]) => {
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 ErpPurchaseInApi.PurchaseIn;
data.items = formData.value?.items?.map((item) => ({
...item,
// 解决新增采购入库报错
id: undefined,
}));
try {
await (formType.value === 'create'
? createPurchaseIn(data)
: updatePurchaseIn(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,
inTime: undefined,
remark: undefined,
fileUrl: undefined,
discountPercent: 0,
supplierId: 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,
inTime: undefined,
remark: undefined,
fileUrl: undefined,
discountPercent: 0,
supplierId: undefined,
discountPrice: 0,
totalPrice: 0,
otherPrice: 0,
items: [],
} as unknown as ErpPurchaseInApi.PurchaseIn;
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 getPurchaseIn(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">
<PurchaseInItemForm
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,256 +0,0 @@
<script lang="ts" setup>
import type { ErpPurchaseInApi } from '#/api/erp/purchase/in';
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?: ErpPurchaseInApi.PurchaseInItem[];
disabled?: boolean;
}
const tableData = ref<ErpPurchaseInApi.PurchaseInItem[]>([]);
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: 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: ErpPurchaseInApi.PurchaseInItem) => {
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 = (): ErpPurchaseInApi.PurchaseInItem[] => tableData.value;
const init = (items: ErpPurchaseInApi.PurchaseInItem[] | 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

@@ -0,0 +1,117 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { ErpPurchaseOrderApi } from '#/api/erp/purchase/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 { getPurchaseOrderPage } from '#/api/erp/purchase/order';
import { useOrderGridColumns, useOrderGridFormSchema } from '../data';
defineProps({
orderNo: {
type: String,
default: () => undefined,
},
disabled: {
type: Boolean,
default: false,
},
});
const emit = defineEmits<{
'update:order': [order: ErpPurchaseOrderApi.PurchaseOrder];
}>();
const order = ref<ErpPurchaseOrderApi.PurchaseOrder>(); // 选择的采购订单
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 getPurchaseOrderPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
inEnable: true,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
radioConfig: {
trigger: 'row',
highlight: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<ErpPurchaseOrderApi.PurchaseOrder>,
gridEvents: {
radioChange: ({ row }: { row: ErpPurchaseOrderApi.PurchaseOrder }) => {
handleSelectOrder(row);
},
},
});
/** 选择采购订单 */
function handleSelectOrder(selectOrder: ErpPurchaseOrderApi.PurchaseOrder) {
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,70 +0,0 @@
<script lang="ts" setup>
import type { ErpPurchaseOrderApi } from '#/api/erp/purchase/order';
import { ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { Input, message, Modal } from 'ant-design-vue';
import SelectPurchaseOrderGrid from './select-purchase-order-grid.vue';
const props = defineProps({
orderNo: {
type: String,
default: () => undefined,
},
disabled: {
type: Boolean,
default: false,
},
});
const emit = defineEmits<{
'update:order': [order: ErpPurchaseOrderApi.PurchaseOrder];
}>();
const order = ref<ErpPurchaseOrderApi.PurchaseOrder>();
const open = ref<boolean>(false);
const handleSelectOrder = (selectOrder: ErpPurchaseOrderApi.PurchaseOrder) => {
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: props.disabled ? 'not-allowed' : 'pointer' }"
@click="() => !props.disabled && (open = true)"
/>
</div>
</template>
</Input>
<Modal
v-model:open="open"
title="选择关联订单"
class="!w-[50vw]"
:show-confirm-button="true"
@ok="handleOk"
>
<SelectPurchaseOrderGrid @select-row="handleSelectOrder" />
</Modal>
</template>

View File

@@ -1,55 +0,0 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { ErpPurchaseOrderApi } from '#/api/erp/purchase/order';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getPurchaseOrderPage } from '#/api/erp/purchase/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 getPurchaseOrderPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
inEnable: true,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
radioConfig: {
trigger: 'row',
highlight: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<ErpPurchaseOrderApi.PurchaseOrder>,
gridEvents: {
radioChange: ({ row }: { row: ErpPurchaseOrderApi.PurchaseOrder }) => {
emit('selectRow', row);
},
},
});
</script>
<template>
<Grid class="max-h-[600px]" table-title="采购订单列表(仅展示可入库)" />
</template>

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,22 @@ export function useFormSchema(): VbenFormSchema[] {
value: 'id',
},
},
fieldName: 'supplierId',
label: '供应商',
rules: 'required',
},
{
component: 'DatePicker',
componentProps: {
placeholder: '选择订单时间',
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
valueFormat: 'x',
style: { width: '100%' },
},
fieldName: 'orderTime',
label: '订单时间',
rules: 'required',
},
{
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 +89,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 +148,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 +163,8 @@ export function useFormSchema(): VbenFormSchema[] {
];
}
/** 采购订单项表格列定义 */
export function usePurchaseOrderItemTableColumns(): VxeTableGridOptions['columns'] {
/** 表单的明细表格列 */
export function useFormItemColumns(): VxeTableGridOptions['columns'] {
return [
{ type: 'seq', title: '序号', minWidth: 50, fixed: 'left' },
{
@@ -193,48 +188,54 @@ export function usePurchaseOrderItemTableColumns(): VxeTableGridOptions['columns
title: '单位',
minWidth: 80,
},
{
field: 'remark',
title: '备注',
minWidth: 150,
slots: { default: 'remark' },
},
{
field: 'count',
title: '数量',
minWidth: 120,
fixed: 'right',
slots: { default: 'count' },
},
{
field: 'productPrice',
title: '产品单价',
minWidth: 120,
fixed: 'right',
slots: { default: 'productPrice' },
},
{
field: 'totalProductPrice',
title: '金额',
minWidth: 120,
fixed: 'right',
formatter: 'formatAmount2',
},
{
field: 'taxPercent',
title: '税率(%)',
minWidth: 100,
minWidth: 105,
fixed: 'right',
slots: { default: 'taxPercent' },
},
{
field: 'taxPrice',
title: '税额',
minWidth: 120,
fixed: 'right',
formatter: 'formatAmount2',
},
{
field: 'totalPrice',
title: '税额合计',
minWidth: 120,
fixed: 'right',
formatter: 'formatAmount2',
},
{
field: 'remark',
title: '备注',
minWidth: 150,
slots: { default: 'remark' },
},
{
title: '操作',
width: 50,
@@ -254,7 +255,6 @@ export function useGridFormSchema(): VbenFormSchema[] {
componentProps: {
placeholder: '请输入订单单号',
allowClear: true,
disabled: true,
},
},
{
@@ -277,10 +277,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 +321,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 +390,7 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
field: 'orderTime',
title: '订单时间',
width: 160,
formatter: 'formatDateTime',
formatter: 'formatDate',
},
{
field: 'creatorName',
@@ -379,34 +400,37 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
{
field: 'totalCount',
title: '总数量',
formatter: 'formatAmount3',
minWidth: 120,
},
{
field: 'inCount',
title: '入库数量',
formatter: 'formatAmount3',
minWidth: 120,
},
{
field: 'returnCount',
title: '退货数量',
formatter: 'formatAmount3',
minWidth: 120,
},
{
field: 'totalProductPrice',
title: '金额合计',
formatter: 'formatNumber',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'totalPrice',
title: '含税金额',
formatter: 'formatNumber',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'depositPrice',
title: '支付订金',
formatter: 'formatNumber',
formatter: 'formatAmount2',
minWidth: 120,
},
{

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,81 +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();
} catch {
// 处理错误
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();
} catch {
// 处理错误
await updatePurchaseOrderStatus(row.id!, status);
message.success(`${status === 20 ? '审批' : '反审批'}成功`);
handleRefresh();
} finally {
hideLoading();
}
}
// TODO @Xuzhiqiang批量删除待实现
const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
records,
@@ -104,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({
@@ -181,8 +141,7 @@ const [Grid, gridApi] = useVbenVxeGrid({
/>
</template>
<FormModal @success="onRefresh" />
<FormModal @success="handleRefresh" />
<Grid table-title="采购订单列表">
<template #toolbar-tools>
<TableAction
@@ -210,7 +169,7 @@ const [Grid, gridApi] = useVbenVxeGrid({
auth: ['erp:purchase-order:delete'],
popConfirm: {
title: `是否删除所选中数据?`,
confirm: handleBatchDelete,
confirm: handleDelete.bind(null, checkedIds),
},
},
]"
@@ -234,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',
@@ -255,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,40 @@ 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: 'seq',
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,82 +112,64 @@ 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);
const index = tableData.value.findIndex((item) => item.seq === row.seq);
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) {
const index = tableData.value.findIndex((item) => item.id === row.id);
/** 处理行数据变更 */
function handleRowChange(row: any) {
const index = tableData.value.findIndex((item) => item.seq === row.seq);
if (index === -1) {
tableData.value.push(row);
} else {
@@ -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>
@@ -265,40 +224,39 @@ defineExpose({
<Grid class="w-full">
<template #productId="{ row }">
<Select
v-if="!disabled"
v-model:value="row.productId"
:options="productOptions"
:field-names="{ label: 'name', value: 'id' }"
style="width: 100%"
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>
<span v-else>{{ erpCountInputFormatter(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>
<span v-else>{{ erpPriceInputFormatter(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 +264,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 +284,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>

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,24 @@ export function useFormSchema(formType: string): VbenFormSchema[] {
value: 'id',
},
},
fieldName: 'supplierId',
label: '供应商',
rules: 'required',
},
{
fieldName: 'orderNo',
label: '关联订单',
component: 'Input',
formItemClass: 'col-span-1',
rules: 'required',
componentProps: {
disabled: formType === 'detail',
placeholder: '请选择关联订单',
},
},
{
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,73 +103,76 @@ 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: '请选择结算账户',
disabled: true,
allowClear: true,
showSearch: true,
api: getAccountSimpleList,
@@ -183,26 +181,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,8 +216,9 @@ export function usePurchaseOrderItemTableColumns(): VxeTableGridOptions['columns
},
{
field: 'stockCount',
title: '仓库库存',
title: '库存',
minWidth: 80,
formatter: 'formatAmount3',
},
{
field: 'productBarCode',
@@ -232,15 +230,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 +277,8 @@ export function usePurchaseOrderItemTableColumns(): VxeTableGridOptions['columns
fixed: 'right',
field: 'taxPercent',
title: '税率(%)',
minWidth: 100,
minWidth: 105,
slots: { default: 'taxPercent' },
},
{
fixed: 'right',
@@ -283,10 +294,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 +311,7 @@ export function useGridFormSchema(): VbenFormSchema[] {
label: '退货单号',
component: 'Input',
componentProps: {
placeholder: '请输入入库单号',
placeholder: '请输入退货单号',
allowClear: true,
},
},
@@ -318,10 +335,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,
},
},
{
@@ -350,7 +365,6 @@ export function useGridFormSchema(): VbenFormSchema[] {
api: getWarehouseSimpleList,
labelField: 'name',
valueField: 'id',
filterOption: false,
},
},
{
@@ -387,18 +401,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,
},
},
{
@@ -413,7 +427,7 @@ export function useGridFormSchema(): VbenFormSchema[] {
];
}
/** 采购退货列表的字段 */
/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{
@@ -429,7 +443,7 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
},
{
field: 'productNames',
title: '产品信息',
title: '退货产品信息',
showOverflow: 'tooltip',
minWidth: 120,
},
@@ -442,7 +456,7 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
field: 'returnTime',
title: '退货时间',
width: 160,
formatter: 'formatDateTime',
formatter: 'formatDate',
},
{
field: 'creatorName',
@@ -452,6 +466,7 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
{
field: 'totalCount',
title: '总数量',
formatter: 'formatAmount3',
minWidth: 120,
},
{
@@ -467,16 +482,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 +500,13 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
},
{
title: '操作',
minWidth: 250,
width: 220,
fixed: 'right',
slots: { default: 'actions' },
},
];
}
/** 采购订单列表的搜索表单 */
/** 列表的搜索表单 */
export function useOrderGridFormSchema(): VbenFormSchema[] {
return [
{
@@ -501,7 +516,6 @@ export function useOrderGridFormSchema(): VbenFormSchema[] {
componentProps: {
placeholder: '请输入订单单号',
allowClear: true,
disabled: true,
},
},
{
@@ -524,16 +538,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 [
{
@@ -572,28 +584,31 @@ export function useOrderGridColumns(): VxeTableGridOptions['columns'] {
{
field: 'totalCount',
title: '总数量',
formatter: 'formatAmount3',
minWidth: 120,
},
{
field: 'inCount',
title: '入库数量',
title: '入库数量',
formatter: 'formatAmount3',
minWidth: 120,
},
{
field: 'returnCount',
title: '退货数量',
title: '退货数量',
formatter: 'formatAmount3',
minWidth: 120,
},
{
field: 'totalProductPrice',
title: '金额合计',
formatter: 'formatNumber',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'totalPrice',
title: '含税金额',
formatter: 'formatNumber',
formatter: 'formatAmount2',
minWidth: 120,
},
];

View File

@@ -19,55 +19,55 @@ import {
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
import PurchaseInForm from './modules/purchase-return-form.vue';
import Form from './modules/form.vue';
/** ERP 采购入库列表 */
defineOptions({ name: 'ErpPurchaseIn' });
/** ERP 采购退货列表 */
defineOptions({ name: 'ErpPurchaseReturn' });
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: PurchaseInForm,
connectedComponent: Form,
destroyOnClose: true,
});
/** 刷新表格 */
function onRefresh() {
function handleRefresh() {
gridApi.query();
}
// TODO @Xuzhiqiang批量删除待实现
const checkedIds = ref<number[]>([]);
/** 详情 */
function handleDetail(row: ErpPurchaseReturnApi.PurchaseReturn) {
formModalApi.setData({ type: 'detail', id: row.id }).open();
function handleRowCheckboxChange({
records,
}: {
records: ErpPurchaseReturnApi.PurchaseReturn[];
}) {
checkedIds.value = records.map((item) => item.id!);
}
/** 新增 */
/** 新增采购退货 */
function handleCreate() {
formModalApi.setData({ type: 'create' }).open();
}
/** 编辑 */
/** 编辑采购退货 */
function handleEdit(row: ErpPurchaseReturnApi.PurchaseReturn) {
formModalApi.setData({ type: 'edit', id: row.id }).open();
}
/** 删除 */
/** 查看详情 */
function handleDetail(row: ErpPurchaseReturnApi.PurchaseReturn) {
formModalApi.setData({ type: 'detail', 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 deletePurchaseReturn(ids);
message.success({
content: $t('ui.actionMessage.deleteSuccess'),
key: 'action_process_msg',
});
onRefresh();
} catch {
// 处理错误
message.success($t('ui.actionMessage.deleteSuccess'));
handleRefresh();
} finally {
hideLoading();
}
@@ -81,23 +81,17 @@ async function handleUpdateStatus(
const hideLoading = message.loading({
content: `确定${status === 20 ? '审批' : '反审批'}该订单吗?`,
duration: 0,
key: 'action_process_msg',
});
try {
await updatePurchaseReturnStatus({ id: row.id!, status });
message.success({
content: `${status === 20 ? '审批' : '反审批'}成功`,
key: 'action_process_msg',
});
onRefresh();
} catch {
// 处理错误
await updatePurchaseReturnStatus(row.id!, status);
message.success(`${status === 20 ? '审批' : '反审批'}成功`);
handleRefresh();
} finally {
hideLoading();
}
}
/** 导出 */
/** 导出表格 */
async function handleExport() {
const data = await exportPurchaseReturn(await gridApi.formApi.getValues());
downloadFileFromBlobPart({ fileName: '采购退货.xls', source: data });
@@ -131,6 +125,10 @@ const [Grid, gridApi] = useVbenVxeGrid({
search: true,
},
} as VxeTableGridOptions<ErpPurchaseReturnApi.PurchaseReturn>,
gridEvents: {
checkboxAll: handleRowCheckboxChange,
checkboxChange: handleRowCheckboxChange,
},
});
</script>
@@ -142,7 +140,7 @@ const [Grid, gridApi] = useVbenVxeGrid({
url="https://doc.iocoder.cn/erp/purchase/"
/>
</template>
<FormModal @success="onRefresh" />
<FormModal @success="handleRefresh" />
<Grid table-title="采购退货列表">
<template #toolbar-tools>
@@ -171,14 +169,7 @@ const [Grid, gridApi] = useVbenVxeGrid({
auth: ['erp:purchase-return:delete'],
popConfirm: {
title: `是否删除所选中数据?`,
confirm: () => {
const checkboxRecords = gridApi.grid.getCheckboxRecords();
if (checkboxRecords.length === 0) {
message.warning('请选择要删除的数据');
return;
}
handleDelete(checkboxRecords.map((item) => item.id!));
},
confirm: handleDelete.bind(null, checkedIds),
},
},
]"

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,296 @@
<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: 'seq',
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.seq === row.seq);
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.seq === row.seq);
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>{{ erpCountInputFormatter(row.count) || '-' }}</span>
</template>
<template #productPrice="{ row }">
<InputNumber
v-if="!disabled"
v-model:value="row.productPrice"
:min="0"
:precision="2"
@change="handleRowChange(row)"
/>
<span v-else>{{ erpPriceInputFormatter(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"
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 { ErpPurchaseOrderApi } from '#/api/erp/purchase/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 { getPurchaseOrderPage } from '#/api/erp/purchase/order';
import { useOrderGridColumns, useOrderGridFormSchema } from '../data';
defineProps({
orderNo: {
type: String,
default: () => undefined,
},
disabled: {
type: Boolean,
default: false,
},
});
const emit = defineEmits<{
'update:order': [order: ErpPurchaseOrderApi.PurchaseOrder];
}>();
const order = ref<ErpPurchaseOrderApi.PurchaseOrder>(); // 选择的采购订单
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 getPurchaseOrderPage({
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<ErpPurchaseOrderApi.PurchaseOrder>,
gridEvents: {
radioChange: ({ row }: { row: ErpPurchaseOrderApi.PurchaseOrder }) => {
handleSelectOrder(row);
},
},
});
/** 选择采购订单 */
function handleSelectOrder(selectOrder: ErpPurchaseOrderApi.PurchaseOrder) {
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,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>

View File

@@ -1,70 +0,0 @@
<script lang="ts" setup>
import type { ErpPurchaseOrderApi } from '#/api/erp/purchase/order';
import { ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { Input, message, Modal } from 'ant-design-vue';
import SelectPurchaseOrderGrid from './select-purchase-order-grid.vue';
const props = defineProps({
orderNo: {
type: String,
default: () => undefined,
},
disabled: {
type: Boolean,
default: false,
},
});
const emit = defineEmits<{
'update:order': [order: ErpPurchaseOrderApi.PurchaseOrder];
}>();
const order = ref<ErpPurchaseOrderApi.PurchaseOrder>();
const open = ref<boolean>(false);
const handleSelectOrder = (selectOrder: ErpPurchaseOrderApi.PurchaseOrder) => {
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: props.disabled ? 'not-allowed' : 'pointer' }"
@click="() => !props.disabled && (open = true)"
/>
</div>
</template>
</Input>
<Modal
v-model:open="open"
title="选择关联订单"
class="!w-[50vw]"
:show-confirm-button="true"
@ok="handleOk"
>
<SelectPurchaseOrderGrid @select-row="handleSelectOrder" />
</Modal>
</template>

View File

@@ -1,55 +0,0 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { ErpPurchaseOrderApi } from '#/api/erp/purchase/order';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getPurchaseOrderPage } from '#/api/erp/purchase/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 getPurchaseOrderPage({
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<ErpPurchaseOrderApi.PurchaseOrder>,
gridEvents: {
radioChange: ({ row }: { row: ErpPurchaseOrderApi.PurchaseOrder }) => {
emit('selectRow', row);
},
},
});
</script>
<template>
<Grid class="max-h-[600px]" table-title="采购订单列表(仅展示可退货)" />
</template>

View File

@@ -1,9 +1,11 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import { DICT_TYPE } from '@vben/constants';
import { CommonStatusEnum, DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { z } from '#/adapter/form';
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
return [
@@ -19,10 +21,10 @@ export function useFormSchema(): VbenFormSchema[] {
fieldName: 'name',
label: '供应商名称',
component: 'Input',
rules: 'required',
componentProps: {
placeholder: '请输入供应商名称',
},
rules: 'required',
},
{
fieldName: 'contact',
@@ -70,9 +72,10 @@ export function useFormSchema(): VbenFormSchema[] {
component: 'RadioGroup',
componentProps: {
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
buttonStyle: 'solid',
optionType: 'button',
},
rules: 'required',
defaultValue: 0,
rules: z.number().default(CommonStatusEnum.ENABLE),
},
{
fieldName: 'sort',
@@ -80,11 +83,8 @@ export function useFormSchema(): VbenFormSchema[] {
component: 'InputNumber',
componentProps: {
placeholder: '请输入排序',
precision: 0,
class: 'w-full',
},
rules: 'required',
defaultValue: 0,
},
{
fieldName: 'taxNo',
@@ -102,7 +102,6 @@ export function useFormSchema(): VbenFormSchema[] {
placeholder: '请输入税率',
min: 0,
precision: 2,
class: 'w-full',
},
},
{
@@ -206,7 +205,7 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
{
field: 'status',
title: '状态',
width: 100,
minWidth: 100,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.COMMON_STATUS },
@@ -215,7 +214,7 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
{
field: 'sort',
title: '排序',
width: 80,
minWidth: 80,
},
{
field: 'remark',
@@ -224,10 +223,9 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
showOverflow: 'tooltip',
},
{
field: 'actions',
title: '操作',
width: 130,
fixed: 'right',
width: 160,
slots: { default: 'actions' },
},
];

View File

@@ -22,18 +22,18 @@ import SupplierForm from './modules/form.vue';
defineOptions({ name: 'ErpSupplier' });
/** 刷新表格 */
function onRefresh() {
function handleRefresh() {
gridApi.query();
}
/** 添加供应商 */
/** 创建供应商 */
function handleCreate() {
formModalApi.setData({ type: 'create' }).open();
formModalApi.setData(null).open();
}
/** 编辑供应商 */
function handleEdit(row: ErpSupplierApi.Supplier) {
formModalApi.setData({ type: 'update', id: row.id }).open();
formModalApi.setData(row).open();
}
/** 删除供应商 */
@@ -44,11 +44,9 @@ async function handleDelete(row: ErpSupplierApi.Supplier) {
});
try {
await deleteSupplier(row.id!);
message.success({
content: $t('ui.actionMessage.deleteSuccess', [row.name]),
});
onRefresh();
} catch {
message.success($t('ui.actionMessage.deleteSuccess', [row.name]));
handleRefresh();
} finally {
hideLoading();
}
}
@@ -85,6 +83,7 @@ const [Grid, gridApi] = useVbenVxeGrid({
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
@@ -103,7 +102,7 @@ const [Grid, gridApi] = useVbenVxeGrid({
/>
</template>
<FormModal @success="onRefresh" />
<FormModal @success="handleRefresh" />
<Grid table-title="供应商列表">
<template #toolbar-tools>
<TableAction
@@ -130,14 +129,14 @@ const [Grid, gridApi] = useVbenVxeGrid({
<TableAction
:actions="[
{
label: '编辑',
label: $t('common.edit'),
type: 'link',
icon: ACTION_ICON.EDIT,
auth: ['erp:supplier:update'],
onClick: handleEdit.bind(null, row),
},
{
label: '删除',
label: $t('common.delete'),
type: 'link',
danger: true,
icon: ACTION_ICON.DELETE,

View File

@@ -1,7 +1,7 @@
<script lang="ts" setup>
import type { ErpSupplierApi } from '#/api/erp/purchase/supplier';
import { ref } from 'vue';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
@@ -18,9 +18,12 @@ import { $t } from '#/locales';
import { useFormSchema } from '../data';
const emit = defineEmits(['success']);
const formType = ref<'create' | 'update'>('create');
const supplierId = ref<number>();
const formData = ref<ErpSupplierApi.Supplier>();
const getTitle = computed(() => {
return formData.value?.id
? $t('ui.actionTitle.edit', ['供应商'])
: $t('ui.actionTitle.create', ['供应商']);
});
const [Form, formApi] = useVbenForm({
commonConfig: {
@@ -45,39 +48,30 @@ const [Modal, modalApi] = useVbenModal({
// 提交表单
const data = (await formApi.getValues()) as ErpSupplierApi.Supplier;
try {
if (formType.value === 'create') {
await createSupplier(data);
message.success($t('ui.actionMessage.createSuccess'));
} else {
await updateSupplier(data);
message.success($t('ui.actionMessage.updateSuccess'));
}
await (formData.value?.id ? updateSupplier(data) : createSupplier(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: 'create' | 'update' }>();
if (!data) {
const data = modalApi.getData<ErpSupplierApi.Supplier>();
if (!data || !data.id) {
return;
}
formType.value = data.type;
supplierId.value = data.id;
modalApi.lock();
try {
if (data.type === 'update' && data.id) {
// 编辑模式,加载数据
const supplierData = await getSupplier(data.id);
await formApi.setValues(supplierData);
}
formData.value = await getSupplier(data.id);
// 设置到 values
await formApi.setValues(formData.value);
} finally {
modalApi.unlock();
}
@@ -90,10 +84,7 @@ defineExpose({
</script>
<template>
<Modal
:title="formType === 'create' ? '新增供应商' : '编辑供应商'"
class="w-3/5"
>
<Modal :title="getTitle" class="w-1/2">
<Form class="mx-4" />
</Modal>
</template>

View File

@@ -20,10 +20,10 @@ export function useFormSchema(): VbenFormSchema[] {
{
component: 'Input',
fieldName: 'name',
label: '名称',
label: '客户名称',
rules: 'required',
componentProps: {
placeholder: '请输入名称',
placeholder: '请输入客户名称',
},
},
{
@@ -84,10 +84,8 @@ export function useFormSchema(): VbenFormSchema[] {
componentProps: {
placeholder: '请输入排序',
precision: 0,
class: 'w-full',
},
rules: 'required',
defaultValue: 0,
},
{
fieldName: 'taxNo',
@@ -103,11 +101,9 @@ export function useFormSchema(): VbenFormSchema[] {
component: 'InputNumber',
componentProps: {
placeholder: '请输入税率',
precision: 0,
class: 'w-full',
precision: 2,
},
rules: z.number().min(0).max(100).default(0).optional(),
defaultValue: 0,
rules: z.number().min(0).max(100).optional(),
},
{
fieldName: 'bankName',
@@ -139,30 +135,42 @@ export function useFormSchema(): VbenFormSchema[] {
component: 'Textarea',
componentProps: {
placeholder: '请输入备注',
rows: 1,
rows: 3,
},
formItemClass: 'col-span-2',
},
];
}
/** 列表的搜索表单 */
// TODO @XuZhiqiangplaceholder
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'name',
label: '名称',
label: '客户名称',
component: 'Input',
componentProps: {
placeholder: '请输入客户名称',
allowClear: true,
},
},
{
fieldName: 'mobile',
label: '手机号码',
component: 'Input',
componentProps: {
placeholder: '请输入手机号码',
allowClear: true,
},
},
{
fieldName: 'email',
label: '邮箱',
component: 'Input',
componentProps: {
placeholder: '请输入邮箱',
allowClear: true,
},
},
];
}
@@ -172,39 +180,53 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{
field: 'name',
title: '名称',
title: '客户名称',
minWidth: 150,
},
{
field: 'contact',
title: '联系人',
minWidth: 120,
},
{
field: 'mobile',
title: '手机号码',
minWidth: 130,
},
{
field: 'telephone',
title: '联系电话',
minWidth: 130,
},
{
field: 'email',
title: '邮箱',
},
{
field: 'taxNo',
title: '纳税人识别号',
title: '电子邮箱',
minWidth: 180,
},
{
field: 'status',
title: '状态',
minWidth: 100,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.COMMON_STATUS },
},
},
{
field: 'sort',
title: '排序',
minWidth: 80,
},
{
field: 'remark',
title: '备注',
minWidth: 150,
showOverflow: 'tooltip',
},
{
field: 'createTime',
title: '创建时间',
minWidth: 180,
formatter: 'formatDateTime',
},
{

View File

@@ -24,7 +24,7 @@ const [FormModal, formModalApi] = useVbenModal({
});
/** 刷新表格 */
function onRefresh() {
function handleRefresh() {
gridApi.query();
}
@@ -52,10 +52,8 @@ async function handleDelete(row: ErpCustomerApi.Customer) {
});
try {
await deleteCustomer(row.id as number);
message.success({
content: $t('ui.actionMessage.deleteSuccess', [row.name]),
});
onRefresh();
message.success($t('ui.actionMessage.deleteSuccess', [row.name]));
handleRefresh();
} finally {
hideLoading();
}
@@ -100,7 +98,7 @@ 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

View File

@@ -30,6 +30,7 @@ const [Form, formApi] = useVbenForm({
componentProps: {
class: 'w-full',
},
labelWidth: 90,
},
wrapperClass: 'grid-cols-2',
layout: 'horizontal',
@@ -79,7 +80,7 @@ const [Modal, modalApi] = useVbenModal({
</script>
<template>
<Modal class="w-2/5" :title="getTitle">
<Modal class="w-1/2" :title="getTitle">
<Form class="mx-4" />
</Modal>
</template>

View File

@@ -10,44 +10,43 @@ import { getAccountSimpleList } from '#/api/erp/finance/account';
import { getProductSimpleList } from '#/api/erp/product/product';
import { getCustomerSimpleList } from '#/api/erp/sale/customer';
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',
style: { width: '100%' },
},
fieldName: 'orderTime',
label: '订单时间',
rules: 'required',
},
{
label: '客户',
fieldName: 'customerId',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择客户',
@@ -59,16 +58,14 @@ export function useFormSchema(): VbenFormSchema[] {
value: 'id',
},
},
fieldName: 'customerId',
label: '客户',
rules: 'required',
},
{
fieldName: 'saleUserId',
label: '创建人',
label: '销售人员',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择创建人',
placeholder: '请选择销售人员',
allowClear: true,
showSearch: true,
api: getSimpleUserList,
@@ -79,15 +76,19 @@ export function useFormSchema(): VbenFormSchema[] {
},
},
{
fieldName: 'remark',
label: '备注',
component: 'Textarea',
componentProps: {
placeholder: '请输入备注',
autoSize: { minRows: 1, maxRows: 1 },
disabled: formType === 'detail',
},
fieldName: 'remark',
label: '备注',
formItemClass: 'col-span-2',
},
{
fieldName: 'fileUrl',
label: '附件',
component: 'FileUpload',
componentProps: {
maxNumber: 1,
@@ -103,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: '请选择结算账户',
@@ -164,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',
@@ -182,8 +178,8 @@ export function useFormSchema(): VbenFormSchema[] {
];
}
/** 采购订单项表格列定义 */
export function useSaleOrderItemTableColumns(): VxeTableGridOptions['columns'] {
/** 表单的明细表格列 */
export function useFormItemColumns(): VxeTableGridOptions['columns'] {
return [
{ type: 'seq', title: '序号', minWidth: 50, fixed: 'left' },
{
@@ -196,6 +192,7 @@ export function useSaleOrderItemTableColumns(): VxeTableGridOptions['columns'] {
field: 'stockCount',
title: '库存',
minWidth: 80,
formatter: 'formatAmount3',
},
{
field: 'productBarCode',
@@ -207,48 +204,54 @@ export function useSaleOrderItemTableColumns(): VxeTableGridOptions['columns'] {
title: '单位',
minWidth: 80,
},
{
field: 'remark',
title: '备注',
minWidth: 150,
slots: { default: 'remark' },
},
{
field: 'count',
title: '数量',
minWidth: 120,
fixed: 'right',
slots: { default: 'count' },
},
{
field: 'productPrice',
title: '产品单价',
minWidth: 120,
fixed: 'right',
slots: { default: 'productPrice' },
},
{
field: 'totalProductPrice',
title: '金额',
minWidth: 120,
fixed: 'right',
formatter: 'formatAmount2',
},
{
field: 'taxPercent',
title: '税率(%)',
minWidth: 100,
minWidth: 105,
fixed: 'right',
slots: { default: 'taxPercent' },
},
{
field: 'taxPrice',
title: '税额',
minWidth: 120,
fixed: 'right',
formatter: 'formatAmount2',
},
{
field: 'totalPrice',
title: '税额合计',
minWidth: 120,
fixed: 'right',
formatter: 'formatAmount2',
},
{
field: 'remark',
title: '备注',
minWidth: 150,
slots: { default: 'remark' },
},
{
title: '操作',
width: 50,
@@ -290,10 +293,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,
},
},
{
@@ -336,6 +337,15 @@ export function useGridFormSchema(): VbenFormSchema[] {
allowClear: true,
},
},
{
fieldName: 'remark',
label: '备注',
component: 'Input',
componentProps: {
placeholder: '请输入备注',
allowClear: true,
},
},
{
fieldName: 'outStatus',
label: '出库状态',
@@ -406,34 +416,37 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
{
field: 'totalCount',
title: '总数量',
formatter: 'formatAmount3',
minWidth: 120,
},
{
field: 'outCount',
title: '出库数量',
formatter: 'formatAmount3',
minWidth: 120,
},
{
field: 'returnCount',
title: '退货数量',
formatter: 'formatAmount3',
minWidth: 120,
},
{
field: 'totalProductPrice',
title: '金额合计',
formatter: 'formatNumber',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'totalPrice',
title: '含税金额',
formatter: 'formatNumber',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'depositPrice',
title: '收取订金',
formatter: 'formatNumber',
formatter: 'formatAmount2',
minWidth: 120,
},
{

View File

@@ -19,21 +19,70 @@ import {
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
import SaleOrderForm from './modules/form.vue';
import Form from './modules/form.vue';
/** ERP 销售订单列表 */
defineOptions({ name: 'ErpSaleOrder' });
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: SaleOrderForm,
connectedComponent: Form,
destroyOnClose: true,
});
/** 刷新表格 */
function onRefresh() {
function handleRefresh() {
gridApi.query();
}
/** 导出表格 */
async function handleExport() {
const data = await exportSaleOrder(await gridApi.formApi.getValues());
downloadFileFromBlobPart({ fileName: '销售订单.xls', source: data });
}
/** 新增销售订单 */
function handleCreate() {
formModalApi.setData({ type: 'create' }).open();
}
/** 编辑销售订单 */
function handleEdit(row: ErpSaleOrderApi.SaleOrder) {
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 deleteSaleOrder(ids);
message.success($t('ui.actionMessage.deleteSuccess'));
handleRefresh();
} finally {
hideLoading();
}
}
/** 审批/反审批操作 */
async function handleUpdateStatus(
row: ErpSaleOrderApi.SaleOrder,
status: number,
) {
const hideLoading = message.loading({
content: `确定${status === 20 ? '审批' : '反审批'}该订单吗?`,
duration: 0,
});
try {
await updateSaleOrderStatus(row.id!, status);
message.success(`${status === 20 ? '审批' : '反审批'}成功`);
handleRefresh();
} finally {
hideLoading();
}
}
const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
records,
@@ -43,71 +92,11 @@ function handleRowCheckboxChange({
checkedIds.value = records.map((item) => item.id!);
}
/** 详情 */
/** 查看详情 */
function handleDetail(row: ErpSaleOrderApi.SaleOrder) {
formModalApi.setData({ type: 'detail', id: row.id }).open();
}
/** 新增 */
function handleCreate() {
formModalApi.setData({ type: 'create' }).open();
}
/** 编辑 */
function handleEdit(row: ErpSaleOrderApi.SaleOrder) {
formModalApi.setData({ type: 'edit', 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 deleteSaleOrder(ids);
message.success({
content: $t('ui.actionMessage.deleteSuccess'),
key: 'action_process_msg',
});
onRefresh();
} catch {
// 处理错误
} finally {
hideLoading();
}
}
/** 审批/反审批操作 */
function handleUpdateStatus(row: ErpSaleOrderApi.SaleOrder, status: number) {
const hideLoading = message.loading({
content: `确定${status === 20 ? '审批' : '反审批'}该订单吗?`,
duration: 0,
key: 'action_process_msg',
});
updateSaleOrderStatus(row.id!, status)
.then(() => {
message.success({
content: `${status === 20 ? '审批' : '反审批'}成功`,
key: 'action_process_msg',
});
onRefresh();
})
.catch(() => {
// 处理错误
})
.finally(() => {
hideLoading();
});
}
/** 导出 */
async function handleExport() {
const data = await exportSaleOrder(await gridApi.formApi.getValues());
downloadFileFromBlobPart({ fileName: '销售订单.xls', source: data });
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
@@ -151,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

View File

@@ -1,32 +1,37 @@
<script lang="ts" setup>
import type { ErpSaleOrderApi } from '#/api/erp/sale/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 {
createSaleOrder,
getSaleOrder,
updateSaleOrder,
} from '#/api/erp/sale/order';
import { $t } from '#/locales';
import { useFormSchema } from '../data';
import SaleOrderItemForm from './sale-order-item-form.vue';
import ItemForm from './item-form.vue';
const emit = defineEmits(['success']);
const formData = ref<ErpSaleOrderApi.SaleOrder>();
const formType = ref('');
const itemFormRef = ref();
const formType = ref(''); // 表单类型:'create' | 'edit' | 'detail'
const itemFormRef = ref<InstanceType<typeof ItemForm>>();
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 === 'edit'
? $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: ErpSaleOrderApi.SaleOrderItem[]) => {
formData.value = modalApi.getData<ErpSaleOrderApi.SaleOrder>();
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,45 +82,19 @@ const [Modal, modalApi] = useVbenModal({
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('产品清单不能为空,请至少添加一个产品');
try {
itemFormInstance.validate();
} catch (error: any) {
message.error(error.message || '子表单验证失败');
return;
}
modalApi.lock();
// 提交表单
const data = (await formApi.getValues()) as ErpSaleOrderApi.SaleOrder;
data.items = formData.value?.items?.map((item) => ({
...item,
// 解决新增销售订单报错
id: undefined,
}));
// 将文件数组转换为字符串
if (data.fileUrl && Array.isArray(data.fileUrl)) {
data.fileUrl = data.fileUrl.length > 0 ? data.fileUrl[0] : '';
}
try {
await (formType.value === 'create'
? createSaleOrder(data)
@@ -124,7 +102,7 @@ const [Modal, modalApi] = useVbenModal({
// 关闭并提示
await modalApi.close();
emit('success');
message.success(formType.value === 'create' ? '新增成功' : '更新成功');
message.success($t('ui.actionMessage.operationSuccess'));
} finally {
modalApi.unlock();
}
@@ -136,61 +114,40 @@ 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 unknown as ErpSaleOrderApi.SaleOrder;
await nextTick();
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 getSaleOrder(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">
<SaleOrderItemForm
v-bind="slotProps"
<template #items>
<ItemForm
ref="itemFormRef"
class="w-full"
:items="formData?.items ?? []"
:disabled="formType === 'detail'"
:discount-percent="formData?.discountPercent ?? 0"

View File

@@ -1,9 +1,14 @@
<script lang="ts" setup>
import type { ErpProductApi } from '#/api/erp/product/product';
import type { ErpSaleOrderApi } from '#/api/erp/sale/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';
@@ -11,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 { useSaleOrderItemTableColumns } from '../data';
import { useFormItemColumns } from '../data';
interface Props {
items?: ErpSaleOrderApi.SaleOrderItem[];
disabled?: boolean;
discountPercent?: number;
}
const props = withDefaults(defineProps<Props>(), {
items: () => [],
@@ -25,31 +36,39 @@ const emit = defineEmits([
'update:total-price',
]);
interface Props {
items?: ErpSaleOrderApi.SaleOrderItem[];
disabled?: boolean;
discountPercent?: number;
}
const tableData = ref<ErpSaleOrderApi.SaleOrderItem[]>([]); //
const productOptions = ref<ErpProductApi.Product[]>([]); //
const tableData = ref<ErpSaleOrderApi.SaleOrderItem[]>([]);
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: useSaleOrderItemTableColumns(),
columns: useFormItemColumns(),
data: tableData.value,
border: true,
showOverflow: true,
autoResize: true,
minHeight: 250,
keepSource: true,
autoResize: true,
border: true,
rowConfig: {
keyField: 'id',
keyField: 'seq',
isHover: true,
},
pagerConfig: {
enabled: false,
@@ -67,10 +86,10 @@ watch(
if (!items) {
return;
}
await nextTick();
items.forEach((item) => initRow(item));
tableData.value = [...items];
await nextTick();
gridApi.grid.reloadData(tableData.value);
await nextTick(); // gridApi
await gridApi.grid.reloadData(tableData.value);
},
{
immediate: true,
@@ -93,81 +112,64 @@ 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,
};
tableData.value.push(newRow);
gridApi.grid.insertAt(newRow, -1);
//
emit('update:items', [...tableData.value]);
}
/** 处理删除 */
function handleDelete(row: ErpSaleOrderApi.SaleOrderItem) {
gridApi.grid.remove(row);
const index = tableData.value.findIndex((item) => item.id === row.id);
const index = tableData.value.findIndex((item) => item.seq === row.seq);
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.stockCount = (await getStockCount(productId)) || 0;
row.productPrice = product.salePrice || 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) {
const index = tableData.value.findIndex((item) => item.id === row.id);
/** 处理行数据变更 */
function handleRowChange(row: any) {
const index = tableData.value.findIndex((item) => item.seq === row.seq);
if (index === -1) {
tableData.value.push(row);
} else {
@@ -176,83 +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: ErpSaleOrderApi.SaleOrderItem): 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 = (): ErpSaleOrderApi.SaleOrderItem[] => tableData.value;
const init = (items: ErpSaleOrderApi.SaleOrderItem[] | 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>
@@ -260,40 +224,39 @@ defineExpose({
<Grid class="w-full">
<template #productId="{ row }">
<Select
v-if="!disabled"
v-model:value="row.productId"
:options="productOptions"
:field-names="{ label: 'name', value: 'id' }"
style="width: 100%"
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>
<span v-else>{{ erpCountInputFormatter(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>
<span v-else>{{ erpPriceInputFormatter(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"
@@ -301,42 +264,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"
@@ -353,5 +284,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>

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: 'outTime',
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: 'outTime',
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,74 @@ 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: '请选择结算账户',
@@ -180,26 +198,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 useSaleOutItemTableColumns(): VxeTableGridOptions['columns'] {
/** 表单的明细表格列 */
export function useFormItemColumns(
formData?: any[],
): VxeTableGridOptions['columns'] {
return [
{ type: 'seq', title: '序号', minWidth: 50, fixed: 'left' },
{
@@ -216,8 +233,9 @@ export function useSaleOutItemTableColumns(): VxeTableGridOptions['columns'] {
},
{
field: 'stockCount',
title: '仓库库存',
title: '库存',
minWidth: 80,
formatter: 'formatAmount3',
},
{
field: 'productBarCode',
@@ -229,15 +247,27 @@ export function useSaleOutItemTableColumns(): VxeTableGridOptions['columns'] {
title: '单位',
minWidth: 80,
},
{
field: 'remark',
title: '备注',
minWidth: 150,
slots: { default: 'remark' },
},
{
field: 'totalCount',
title: '原数量',
formatter: 'formatAmount3',
minWidth: 120,
fixed: 'right',
visible: formData && formData[0]?.outCount !== undefined,
},
{
field: 'outCount',
title: '已出库数量',
title: '已出库',
formatter: 'formatAmount3',
minWidth: 120,
fixed: 'right',
visible: formData && formData[0]?.returnCount !== undefined,
},
{
field: 'count',
@@ -264,7 +294,8 @@ export function useSaleOutItemTableColumns(): VxeTableGridOptions['columns'] {
fixed: 'right',
field: 'taxPercent',
title: '税率(%)',
minWidth: 100,
minWidth: 105,
slots: { default: 'taxPercent' },
},
{
fixed: 'right',
@@ -280,6 +311,12 @@ export function useSaleOutItemTableColumns(): VxeTableGridOptions['columns'] {
minWidth: 120,
formatter: 'formatAmount2',
},
{
title: '操作',
width: 50,
fixed: 'right',
slots: { default: 'actions' },
},
];
}
@@ -315,10 +352,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,
},
},
{
@@ -347,7 +382,6 @@ export function useGridFormSchema(): VbenFormSchema[] {
api: getWarehouseSimpleList,
labelField: 'name',
valueField: 'id',
filterOption: false,
},
},
{
@@ -390,12 +424,12 @@ export function useGridFormSchema(): VbenFormSchema[] {
},
{
fieldName: 'status',
label: '状态',
label: '审批状态',
component: 'Select',
componentProps: {
placeholder: '请选择状态',
allowClear: true,
options: getDictOptions(DICT_TYPE.ERP_AUDIT_STATUS, 'number'),
placeholder: '请选择审批状态',
allowClear: true,
},
},
{
@@ -449,18 +483,19 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
{
field: 'totalCount',
title: '总数量',
formatter: 'formatAmount3',
minWidth: 120,
},
{
field: 'totalPrice',
title: '应收金额',
formatter: 'formatNumber',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'receiptPrice',
title: '已收金额',
formatter: 'formatNumber',
formatter: 'formatAmount2',
minWidth: 120,
},
{
@@ -473,7 +508,7 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
},
{
field: 'status',
title: '状态',
title: '审批状态',
minWidth: 120,
cellRender: {
name: 'CellDict',
@@ -482,12 +517,13 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
},
{
title: '操作',
minWidth: 250,
width: 220,
fixed: 'right',
slots: { default: 'actions' },
},
];
}
/** 列表的搜索表单 */
export function useOrderGridFormSchema(): VbenFormSchema[] {
return [
@@ -498,7 +534,6 @@ export function useOrderGridFormSchema(): VbenFormSchema[] {
componentProps: {
placeholder: '请输入订单单号',
allowClear: true,
disabled: true,
},
},
{
@@ -521,10 +556,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,
},
},
];
@@ -569,23 +602,25 @@ export function useOrderGridColumns(): VxeTableGridOptions['columns'] {
{
field: 'totalCount',
title: '总数量',
formatter: 'formatAmount3',
minWidth: 120,
},
{
field: 'outCount',
title: '出库数量',
formatter: 'formatAmount3',
minWidth: 120,
},
{
field: 'totalProductPrice',
title: '金额合计',
formatter: 'formatNumber',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'totalPrice',
title: '含税金额',
formatter: 'formatNumber',
formatter: 'formatAmount2',
minWidth: 120,
},
];

View File

@@ -19,22 +19,67 @@ import {
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
import SaleOutForm from './modules/sale-out-form.vue';
import Form from './modules/form.vue';
/** ERP 销售出库列表 */
defineOptions({ name: 'ErpSaleOut' });
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: SaleOutForm,
connectedComponent: Form,
destroyOnClose: true,
});
/** 刷新表格 */
function onRefresh() {
function handleRefresh() {
gridApi.query();
}
// TODO @Xuzhiqiang批量删除待实现
/** 导出表格 */
async function handleExport() {
const data = await exportSaleOut(await gridApi.formApi.getValues());
downloadFileFromBlobPart({ fileName: '销售出库.xls', source: data });
}
/** 新增销售出库 */
function handleCreate() {
formModalApi.setData({ type: 'create' }).open();
}
/** 编辑销售出库 */
function handleEdit(row: ErpSaleOutApi.SaleOut) {
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 deleteSaleOut(ids);
message.success($t('ui.actionMessage.deleteSuccess'));
handleRefresh();
} finally {
hideLoading();
}
}
/** 审批/反审批操作 */
async function handleUpdateStatus(row: ErpSaleOutApi.SaleOut, status: number) {
const hideLoading = message.loading({
content: `确定${status === 20 ? '审批' : '反审批'}该订单吗?`,
duration: 0,
});
try {
await updateSaleOutStatus(row.id!, status);
message.success(`${status === 20 ? '审批' : '反审批'}成功`);
handleRefresh();
} finally {
hideLoading();
}
}
const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
records,
@@ -44,71 +89,11 @@ function handleRowCheckboxChange({
checkedIds.value = records.map((item) => item.id!);
}
/** 详情 */
/** 查看详情 */
function handleDetail(row: ErpSaleOutApi.SaleOut) {
formModalApi.setData({ type: 'detail', id: row.id }).open();
}
/** 新增 */
function handleCreate() {
formModalApi.setData({ type: 'create' }).open();
}
/** 编辑 */
function handleEdit(row: ErpSaleOutApi.SaleOut) {
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 deleteSaleOut(ids);
message.success({
content: $t('ui.actionMessage.deleteSuccess'),
key: 'action_process_msg',
});
onRefresh();
} catch {
// 处理错误
} finally {
hideLoading();
}
}
/** 审批/反审批操作 */
function handleUpdateStatus(row: ErpSaleOutApi.SaleOut, status: number) {
const hideLoading = message.loading({
content: `确定${status === 20 ? '审批' : '反审批'}该订单吗?`,
duration: 0,
key: 'action_process_msg',
});
updateSaleOutStatus({ id: row.id!, status })
.then(() => {
message.success({
content: `${status === 20 ? '审批' : '反审批'}成功`,
key: 'action_process_msg',
});
onRefresh();
})
.catch(() => {
// 处理错误
})
.finally(() => {
hideLoading();
});
}
/** 导出 */
async function handleExport() {
const data = await exportSaleOut(await gridApi.formApi.getValues());
downloadFileFromBlobPart({ fileName: '销售出库.xls', source: data });
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
@@ -152,8 +137,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
@@ -180,11 +165,8 @@ const [Grid, gridApi] = useVbenVxeGrid({
icon: ACTION_ICON.DELETE,
auth: ['erp:sale-out:delete'],
popConfirm: {
disabled: isEmpty(checkedIds),
title: `是否删除所选中数据?`,
confirm: () => {
handleDelete(checkedIds);
},
confirm: handleDelete.bind(null, checkedIds),
},
},
]"
@@ -229,7 +211,7 @@ const [Grid, gridApi] = useVbenVxeGrid({
auth: ['erp:sale-out:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.no]),
confirm: () => handleDelete([row.id!]),
confirm: handleDelete.bind(null, [row.id!]),
},
},
]"

View File

@@ -0,0 +1,226 @@
<script lang="ts" setup>
import type { ErpSaleOrderApi } from '#/api/erp/sale/order';
import type { ErpSaleOutApi } from '#/api/erp/sale/out';
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 { createSaleOut, getSaleOut, updateSaleOut } from '#/api/erp/sale/out';
import { useFormSchema } from '../data';
import ItemForm from './item-form.vue';
import SaleOrderSelect from './sale-order-select.vue';
const emit = defineEmits(['success']);
const formData = ref<
ErpSaleOutApi.SaleOut & {
accountId?: number;
customerId?: number;
discountPercent?: number;
fileUrl?: string;
order?: ErpSaleOrderApi.SaleOrder;
orderId?: number;
orderNo?: string;
}
>({
id: undefined,
no: undefined,
accountId: undefined,
outTime: undefined,
remark: undefined,
fileUrl: undefined,
discountPercent: 0,
customerId: 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: ErpSaleOutApi.SaleOutItem[]) => {
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.outCount;
item.orderItemId = item.id;
item.id = undefined;
});
formData.value.items = order.items!.filter(
(item) => item.count && item.count > 0,
) as ErpSaleOutApi.SaleOutItem[];
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 ErpSaleOutApi.SaleOut;
try {
await (formType.value === 'create'
? createSaleOut(data)
: updateSaleOut(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 getSaleOut(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,294 @@
<script lang="ts" setup>
import type { ErpSaleOutApi } from '#/api/erp/sale/out';
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?: ErpSaleOutApi.SaleOutItem[];
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<ErpSaleOutApi.SaleOutItem[]>([]); // 表格数据
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: 'seq',
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: ErpSaleOutApi.SaleOutItem) {
const index = tableData.value.findIndex((item) => item.seq === row.seq);
if (index !== -1) {
tableData.value.splice(index, 1);
}
// 通知父组件更新
emit('update:items', [...tableData.value]);
}
/** 处理仓库变更 */
const handleWarehouseChange = async (row: ErpSaleOutApi.SaleOutItem) => {
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.seq === row.seq);
if (index === -1) {
tableData.value.push(row);
} else {
tableData.value[index] = row;
}
emit('update:items', [...tableData.value]);
}
/** 初始化行数据 */
const initRow = (row: ErpSaleOutApi.SaleOutItem): 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>{{ erpCountInputFormatter(row.count) || '-' }}</span>
</template>
<template #productPrice="{ row }">
<InputNumber
v-if="!disabled"
v-model:value="row.productPrice"
:min="0"
:precision="2"
@change="handleRowChange(row)"
/>
<span v-else>{{ erpPriceInputFormatter(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"
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,
outEnable: 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,308 +0,0 @@
<script lang="ts" setup>
import type { ErpSaleOrderApi } from '#/api/erp/sale/order';
import type { ErpSaleOutApi } from '#/api/erp/sale/out';
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 { createSaleOut, getSaleOut, updateSaleOut } from '#/api/erp/sale/out';
import { useFormSchema } from '../data';
import SaleOutItemForm from './sale-out-item-form.vue';
import SelectSaleOrderForm from './select-sale-order-form.vue';
const emit = defineEmits(['success']);
const formData = ref<
ErpSaleOutApi.SaleOut & {
accountId?: number;
customerId?: number;
discountedPrice?: number;
discountPercent?: number;
fileUrl?: string;
order?: ErpSaleOrderApi.SaleOrder;
orderId?: number;
orderNo?: string;
}
>({
id: undefined,
no: undefined,
accountId: undefined,
outTime: 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: ErpSaleOutApi.SaleOutItem[]) => {
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.outCount;
item.orderItemId = item.id;
item.id = undefined;
});
formData.value.items = order.items!.filter(
(item) => item.count && item.count > 0,
) as ErpSaleOutApi.SaleOutItem[];
formApi.setValues(formData.value, false);
};
watch(
() => formData.value.items!,
(newItems: ErpSaleOutApi.SaleOutItem[]) => {
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 ErpSaleOutApi.SaleOut;
data.items = formData.value?.items?.map((item) => ({
...item,
// 解决新增销售出库报错
id: undefined,
}));
try {
await (formType.value === 'create'
? createSaleOut(data)
: updateSaleOut(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,
outTime: 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,
outTime: undefined,
remark: undefined,
fileUrl: undefined,
discountPercent: 0,
customerId: undefined,
discountPrice: 0,
totalPrice: 0,
otherPrice: 0,
items: [],
} as unknown as ErpSaleOutApi.SaleOut;
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 getSaleOut(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">
<SaleOutItemForm
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 { useSaleOutItemTableColumns } 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: useSaleOutItemTableColumns(),
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,
outEnable: 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>

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,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: '请选择结算账户',
@@ -180,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 useSaleReturnItemTableColumns(): VxeTableGridOptions['columns'] {
/** 表单的明细表格列 */
export function useFormItemColumns(
formData?: any[],
): VxeTableGridOptions['columns'] {
return [
{ type: 'seq', title: '序号', minWidth: 50, fixed: 'left' },
{
@@ -216,8 +232,9 @@ export function useSaleReturnItemTableColumns(): VxeTableGridOptions['columns']
},
{
field: 'stockCount',
title: '仓库库存',
title: '库存',
minWidth: 80,
formatter: 'formatAmount3',
},
{
field: 'productBarCode',
@@ -229,15 +246,27 @@ export function useSaleReturnItemTableColumns(): VxeTableGridOptions['columns']
title: '单位',
minWidth: 80,
},
{
field: 'remark',
title: '备注',
minWidth: 150,
slots: { default: 'remark' },
},
{
field: 'totalCount',
title: '原数量',
title: '已出库',
formatter: 'formatAmount3',
minWidth: 120,
fixed: 'right',
visible: formData && formData[0]?.outCount !== undefined,
},
{
field: 'returnCount',
title: '已退货数量',
title: '已退货',
formatter: 'formatAmount3',
minWidth: 120,
fixed: 'right',
visible: formData && formData[0]?.returnCount !== undefined,
},
{
field: 'count',
@@ -264,7 +293,8 @@ export function useSaleReturnItemTableColumns(): VxeTableGridOptions['columns']
fixed: 'right',
field: 'taxPercent',
title: '税率(%)',
minWidth: 100,
minWidth: 105,
slots: { default: 'taxPercent' },
},
{
fixed: 'right',
@@ -280,6 +310,12 @@ export function useSaleReturnItemTableColumns(): VxeTableGridOptions['columns']
minWidth: 120,
formatter: 'formatAmount2',
},
{
title: '操作',
width: 50,
fixed: 'right',
slots: { default: 'actions' },
},
];
}
@@ -315,10 +351,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,
},
},
{
@@ -347,7 +381,6 @@ export function useGridFormSchema(): VbenFormSchema[] {
api: getWarehouseSimpleList,
labelField: 'name',
valueField: 'id',
filterOption: false,
},
},
{
@@ -376,26 +409,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,
},
},
{
@@ -426,7 +459,7 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
},
{
field: 'productNames',
title: '产品信息',
title: '退货产品信息',
showOverflow: 'tooltip',
minWidth: 120,
},
@@ -449,18 +482,19 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
{
field: 'totalCount',
title: '总数量',
formatter: 'formatAmount3',
minWidth: 120,
},
{
field: 'totalPrice',
title: '应退金额',
formatter: 'formatNumber',
title: '应金额',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'refundPrice',
title: '已退金额',
formatter: 'formatNumber',
formatter: 'formatAmount2',
minWidth: 120,
},
{
@@ -473,7 +507,7 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
},
{
field: 'status',
title: '状态',
title: '审批状态',
minWidth: 120,
cellRender: {
name: 'CellDict',
@@ -482,12 +516,13 @@ export function useGridColumns(): VxeTableGridOptions['columns'] {
},
{
title: '操作',
minWidth: 250,
width: 220,
fixed: 'right',
slots: { default: 'actions' },
},
];
}
/** 列表的搜索表单 */
export function useOrderGridFormSchema(): VbenFormSchema[] {
return [
@@ -498,7 +533,6 @@ export function useOrderGridFormSchema(): VbenFormSchema[] {
componentProps: {
placeholder: '请输入订单单号',
allowClear: true,
disabled: true,
},
},
{
@@ -521,10 +555,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,
},
},
];
@@ -569,23 +601,25 @@ export function useOrderGridColumns(): VxeTableGridOptions['columns'] {
{
field: 'totalCount',
title: '总数量',
formatter: 'formatAmount3',
minWidth: 120,
},
{
field: 'returnCount',
title: '已退货数量',
formatter: 'formatAmount3',
minWidth: 120,
},
{
field: 'totalProductPrice',
title: '金额合计',
formatter: 'formatNumber',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'totalPrice',
title: '含税金额',
formatter: 'formatNumber',
formatter: 'formatAmount2',
minWidth: 120,
},
];

View File

@@ -19,22 +19,70 @@ import {
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
import SaleReturnForm from './modules/sale-return-form.vue';
import Form from './modules/form.vue';
/** ERP 销售退货列表 */
defineOptions({ name: 'ErpSaleReturn' });
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: SaleReturnForm,
connectedComponent: Form,
destroyOnClose: true,
});
/** 刷新表格 */
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,71 +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();
} catch {
// 处理错误
} 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(),
@@ -152,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
@@ -180,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),
},
},
]"
@@ -229,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,230 @@
<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 { getAccountSimpleList } from '#/api/erp/finance/account';
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;
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,
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 = 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 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,294 @@
<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(tableData.value),
data: tableData.value,
minHeight: 250,
autoResize: true,
border: true,
rowConfig: {
keyField: 'seq',
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: ErpSaleReturnApi.SaleReturnItem) {
const index = tableData.value.findIndex((item) => item.seq === row.seq);
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.seq === row.seq);
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-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>{{ erpCountInputFormatter(row.count) || '-' }}</span>
</template>
<template #productPrice="{ row }">
<InputNumber
v-if="!disabled"
v-model:value="row.productPrice"
:min="0"
:precision="2"
@change="handleRowChange(row)"
/>
<span v-else>{{ erpPriceInputFormatter(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"
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>

Some files were not shown because too many files have changed in this diff Show More