|
@@ -0,0 +1,76 @@
|
|
|
+'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 OrderService extends CrudService {
|
|
|
+ constructor(ctx) {
|
|
|
+ super(ctx, 'order');
|
|
|
+ this.orderModel = this.ctx.model.Trade.Order;
|
|
|
+ }
|
|
|
+
|
|
|
+ async allOrder(query = {}) {
|
|
|
+ const { skip, limit } = query;
|
|
|
+ const pipeline = [];
|
|
|
+ const step1 = [
|
|
|
+ { $addFields: { order_id: { $toString: '$_id' } } },
|
|
|
+ {
|
|
|
+ $lookup: {
|
|
|
+ from: 'orderDetail',
|
|
|
+ localField: 'order_id',
|
|
|
+ foreignField: 'order',
|
|
|
+ as: 'orderDetails',
|
|
|
+ },
|
|
|
+ },
|
|
|
+ ];
|
|
|
+ pipeline.push(...step1);
|
|
|
+ const step2 = [
|
|
|
+ {
|
|
|
+ $project: {
|
|
|
+ data: {
|
|
|
+ $cond: {
|
|
|
+ if: { $gt: [{ $size: '$orderDetails' }, 0 ] },
|
|
|
+ then: '$orderDetails',
|
|
|
+ else: '$$CURRENT',
|
|
|
+ },
|
|
|
+ },
|
|
|
+ },
|
|
|
+ },
|
|
|
+ ];
|
|
|
+ pipeline.push(...step2);
|
|
|
+ pipeline.push({ $unwind: '$data' });
|
|
|
+ pipeline.push({ $replaceRoot: { newRoot: '$data' } });
|
|
|
+ const qp = _.cloneDeep(pipeline);
|
|
|
+ qp.push({ $sort: { 'meta.createdAt': -1 } });
|
|
|
+ if (skip && limit) qp.push({ $skip: parseInt(skip) }, { $limit: parseInt(limit) });
|
|
|
+ const data = await this.orderModel.aggregate(qp);
|
|
|
+ const tr = await this.orderModel.aggregate([ ...pipeline, { $count: 'total' }]);
|
|
|
+ for (const i of data) {
|
|
|
+ const { pay, goods } = i;
|
|
|
+ if (pay) {
|
|
|
+ // 这个是order表的数据,需要用order的计算方式
|
|
|
+ const buy_num_total = goods.reduce(
|
|
|
+ (p, n) =>
|
|
|
+ this.ctx.plus(
|
|
|
+ p,
|
|
|
+ n.goods.reduce((np, ng) => this.ctx.plus(np, ng.buy_num), 0)
|
|
|
+ ),
|
|
|
+ 0
|
|
|
+ );
|
|
|
+ i.buy_num_total = buy_num_total;
|
|
|
+ i.real_pay = _.get(i, 'pay.pay_money');
|
|
|
+ } else {
|
|
|
+ // 是orderDetail表的数据,需要用orderDetail的计算方式
|
|
|
+ const real_pay = this.ctx.service.util.orderDetail.computedRealPay(i);
|
|
|
+ i.real_pay = real_pay;
|
|
|
+ i.buy_num_total = goods.reduce((p, n) => this.ctx.plus(p, n.buy_num), 0);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ const total = _.get(_.head(tr), 'total', 0);
|
|
|
+ return { data, total };
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+module.exports = OrderService;
|