wangzhibo
6 天以前 7dcc2997614f849258091f5d66e648317a40d323
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { Init, Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Equal, In, Repository } from 'typeorm';
import { OrderGoodsEntity } from '../entity/goods';
import BigNumber from 'bignumber.js';
import { GoodsSpecService } from '../../goods/service/spec';
 
/**
 * 订单商品
 */
@Provide()
export class OrderGoodsService extends BaseService {
  @InjectEntityModel(OrderGoodsEntity)
  orderGoodsEntity: Repository<OrderGoodsEntity>;
 
  @Inject()
  goodsSpecService: GoodsSpecService;
 
  @Init()
  async init() {
    await super.init();
    this.setEntity(this.orderGoodsEntity);
  }
 
  /**
   * 保存
   * @param orderId
   * @param goodsList
   */
  async save(orderId: number, goodsList: OrderGoodsEntity[]) {
    await this.orderGoodsEntity.save(
      goodsList.map(item => {
        item.orderId = orderId;
        return item;
      })
    );
  }
 
  /**
   * 获得总价
   * @param goodsList
   */
  async getTotalPrice(goodsList: OrderGoodsEntity[]) {
    let totalPrice = new BigNumber(0);
    for (const goods of goodsList) {
      totalPrice = totalPrice.plus(goods.price * goods.count);
    }
    return totalPrice.toNumber();
  }
 
  /**
   * 通过订单ID获取商品
   * @param orderId
   */
  async getByOrderId(orderId: number) {
    return await this.orderGoodsEntity.findBy({ orderId: Equal(orderId) });
  }
 
  /**
   * 通过订单ID获取商品
   * @param orderId
   */
  async getByOrderIds(orderIds: number[]) {
    return await this.orderGoodsEntity.findBy({ orderId: In(orderIds) });
  }
 
  // 更新库存
  async updateStock(
    goodsList: OrderGoodsEntity[],
    type: 'add' | 'sub' = 'sub'
  ) {
    for (const goods of goodsList) {
      await this.goodsSpecService.updateStock(
        goods.spec.id,
        type == 'add' ? goods.count : -goods.count
      );
    }
  }
}