'use strict'; const { CrudService } = require('naf-framework-mongoose-free/lib/service'); const { BusinessError, ErrorCode } = require('naf-core').Error; const _ = require('lodash'); const assert = require('assert'); // class OrderDetailService extends CrudService { constructor(ctx) { super(ctx, 'orderdetail'); this.model = this.ctx.model.Trade.OrderDetail; this.orderModel = this.ctx.model.Trade.Order; } /** * 创建:用户支付完成后的订单 * @param {Object} body 请求参数体 * @param body.order_id 下单的id * @param {Transaction} tran 数据库事务实例 */ async create({ order_id }, tran) { assert(order_id, '缺少支付订单信息'); // if (!tran) throw new BusinessError(ErrorCode.DATA_INVALID, '支付成功添加积分:缺少事务参数'); const order = await this.orderModel.findById(order_id); if (!order) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到支付订单的数据'); const { customer, address, goods, no, status, buy_time, pay } = order; if (status === '0') throw new BusinessError(ErrorCode.DATA_INVALID, '订单未支付'); const orderDetailData = { customer, address, order: order_id, buy_time, pay_time: _.get(pay, 'pay_time'), status }; // 补全 shop, goods, total_detail TODO: 补全 discount; // const arr = []; let noTimes = 1; for (const s of goods) { const shop = _.get(s, 'shop'); const goodsList = _.get(s, 'goods', []); const detailNo = `${no}-${noTimes}`; const total_detail = this.getTotalDetail(goodsList); noTimes++; const obj = { ...orderDetailData, shop, goods: goodsList, no: detailNo, total_detail }; tran.insert('OrderDetail', obj); // arr.push(obj); } // await this.model.insertMany(arr); } /** * 计算某店铺的金额总计 * TODO: 缺少优惠计算部分 * @param {Array} goodsList 商品规格列表 */ getTotalDetail(goodsList) { const goods_total = _.floor( goodsList.reduce((p, n) => p + (parseFloat(n.sell_money) || 0), 0), 2 ); const freight_total = _.floor( goodsList.reduce((p, n) => p + (parseFloat(n.freight) || 0), 0), 2 ); return { goods_total, freight_total }; } } module.exports = OrderDetailService;