order.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose-free/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. //
  7. class OrderService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'order');
  10. this.orderModel = this.ctx.model.Trade.Order;
  11. }
  12. async allOrder(query = {}) {
  13. const { skip, limit } = query;
  14. const pipeline = [];
  15. const step1 = [
  16. { $addFields: { order_id: { $toString: '$_id' } } },
  17. {
  18. $lookup: {
  19. from: 'orderDetail',
  20. localField: 'order_id',
  21. foreignField: 'order',
  22. as: 'orderDetails',
  23. },
  24. },
  25. ];
  26. pipeline.push(...step1);
  27. const step2 = [
  28. {
  29. $project: {
  30. data: {
  31. $cond: {
  32. if: { $gt: [{ $size: '$orderDetails' }, 0 ] },
  33. then: '$orderDetails',
  34. else: '$$CURRENT',
  35. },
  36. },
  37. },
  38. },
  39. ];
  40. pipeline.push(...step2);
  41. pipeline.push({ $unwind: '$data' });
  42. pipeline.push({ $replaceRoot: { newRoot: '$data' } });
  43. const qp = _.cloneDeep(pipeline);
  44. qp.push({ $sort: { 'meta.createdAt': -1 } });
  45. if (skip && limit) qp.push({ $skip: parseInt(skip) }, { $limit: parseInt(limit) });
  46. const data = await this.orderModel.aggregate(qp);
  47. const tr = await this.orderModel.aggregate([ ...pipeline, { $count: 'total' }]);
  48. for (const i of data) {
  49. const { pay, goods } = i;
  50. if (pay) {
  51. // 这个是order表的数据,需要用order的计算方式
  52. const buy_num_total = goods.reduce(
  53. (p, n) =>
  54. this.ctx.plus(
  55. p,
  56. n.goods.reduce((np, ng) => this.ctx.plus(np, ng.buy_num), 0)
  57. ),
  58. 0
  59. );
  60. i.buy_num_total = buy_num_total;
  61. i.real_pay = _.get(i, 'pay.pay_money');
  62. } else {
  63. // 是orderDetail表的数据,需要用orderDetail的计算方式
  64. const real_pay = this.ctx.service.util.orderDetail.computedRealPay(i);
  65. i.real_pay = real_pay;
  66. i.buy_num_total = goods.reduce((p, n) => this.ctx.plus(p, n.buy_num), 0);
  67. }
  68. }
  69. const total = _.get(_.head(tr), 'total', 0);
  70. return { data, total };
  71. }
  72. }
  73. module.exports = OrderService;