333
schangxiang@126.com
2025-09-19 18966e02fb573c7e2bb0c6426ed792b38b910940
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
//#region import
import BaseController from "../../baseController";
import { Post } from "egg-shell-decorators";
import * as XLSX from "xlsx";
import * as path from "path";
import { BaseConsignor } from "../../../entity/basicInfo/consignor/baseConsignor";
import { BaseStorage } from "../../../entity/basicInfo/base/baseStorage";
import { BaseProvider } from "../../../entity/basicInfo/base/baseProvider";
import { isNumber } from "util";
import { TMSQuotation } from "../../../entity/express/tms/tmsQuotation";
import { TMSQuotationList } from "../../../entity/express/tms/tmsQuotationList";
import { BaseProductInfo } from "../../../entity/basicInfo/base/baseProductInfo";
import moment = require("moment");
//#endregion
 
/**
 * 基础信息 - 口岸
 */
export default class QuotationController extends BaseController {
  //#region 根据物料号和生产日期查批次
  /**
   * 根据物料号和生产日期查批次
   */
  @Post()
  public async getBatchNumber() {
    let { ctx } = this;
    let body = ctx.body;
    let userInfo = await ctx.helper.userInfo();
    let userProduct_Id = userInfo.userProduct_Id;
    // if (!body.id) {
    //   this.info.result = false;
    //   this.info.msg = "ID查询条件不存在";
    //   ctx.body = this.info;
    //   return;
    // }
    var time = moment(body.time).format("YYYY-MM-DD");
    try {
      let dataInfo = await this.dbRead.findOne(TMSQuotationList, {
        select: ["batchNumber"],
        where: {
          productCode: body.code,
          produceDate: time,
          userProduct_Id: userProduct_Id
        }
      });
 
      this.info.result = true;
      this.info.data = dataInfo;
    } catch (error) {
      this.info.result = false;
      this.info.data = error.message;
    }
    ctx.body = this.info;
  }
  //#endregion
 
  //#region 导入excel importExel
  /**
   * 导入Excel
   */
  @Post()
  public async importExel() {
    setTimeout(async () => {
      await this.importWork();
    }, 0);
 
    this.info.result = true;
    this.ctx.body = this.info;
  }
  private async importWork() {
    let { ctx } = this;
    let body = ctx.request.body;
    let redis = ctx.app.redis.clients.get("common"); // 将消息放入redis缓存
    let fileUrl = body.url;
    let userInfo = await ctx.helper.userInfo();
 
    redis.expire(body.key, 5 * 60);
    if (!fileUrl) {
      this.setMsg("上传文件不存在", "red");
      return;
    }
    try {
      let rootPath = path.resolve(); // 获得根目录
      let filePath = rootPath + path.sep + fileUrl.replace(/\//gi, path.sep); // 上传文件路径
      var workbook = XLSX.readFile(filePath); //整个 excel 文档
      var sheetNames = workbook.SheetNames; //获取所有工作薄名
      var sheet1 = workbook.Sheets[sheetNames[0]]; //根据工作薄名获取工作薄
      let dataList = XLSX.utils.sheet_to_json(sheet1); // 获得当前sheet表单数据转为json格式
      // let isSuccess = true;
      let provider = null;
 
      //#region 验证数据正确性
      this.info.result = true;
      if (!dataList.length) {
        this.setMsg("没有可导入的数据", "red");
        return;
      }
      // 一码多品
      let consignor = await this.dbRead.findOne(BaseConsignor, body.consignor_Id);
      let storage = await this.dbRead.findOne(BaseStorage, {
        storageName: body.storageName,
        userProduct_Id: userInfo.userProduct_Id
      });
      // let msgList = dataList.map(async (item, index) => {
      let index = 0;
      let msgList = [];
      this.isMsgError = false;
      for (let item of dataList) {
        index++;
        if (!item["供应商简称"] || !item["数量"] || !item["单位毛重"] || !item["物料条码"] || !item["订单类型"]) {
          // isSuccess = false;
          this.setMsg(index + "、标黄部分数据不能为空", "red");
        }
        let where = "productCode= :productCode and productModel =:productModel";
 
        let productInfo = await this.dbRead
          .createQueryBuilder(BaseProductInfo, "t")
          .where(where, {
            productCode: "" + item["物料编号"],
            productModel: "" + item["物料条码"]
          })
          .getOne();
        if (!productInfo) {
          this.setMsg(index + `、物料[${item["物料编号"]}]不存在,数据导入失败`, "red");
        }
 
        provider = await this.dbRead.findOne(BaseProvider, {
          providerShortName: item["供应商简称"]
        });
        if (!provider) {
          this.setMsg(index + `、供应商[${item["供应商简称"]}]不存在,数据导入失败`, "red");
        }
        //判断时间的格式是否输入正确
        let arrivedDate = item["预计到货时间"];
        if (arrivedDate) {
          if (!isNumber(arrivedDate)) {
            this.setMsg(index + `、物料编号[${item["物料编号"]}]预计到货时间的格式不正确!`, "red");
          } else {
            item["预计到货时间"] = moment(new Date(1900, 0, arrivedDate - 1)).format("YYYY-MM-DD");
          }
        }
 
        // let produceDate = item["生产日期"];
        // if (produceDate && !isNumber(produceDate)) {
        //   this.setMsg(index + `、物料编号[${item["物料编号"]}]生产时间的格式不正确!`, "red");
        // }
 
        let produceDate = item["生产日期"];
        if (produceDate) {
          if (!isNumber(produceDate)) {
            this.setMsg(index + `、物料编号[${item["物料编号"]}]生产时间的格式不正确!`, "red");
          } else {
            item["生产日期"] = moment(new Date(1900, 0, produceDate - 1)).format("YYYY-MM-DD");
          }
        }
 
        let quantityOrder = item["数量"];
        if (!quantityOrder && !isNumber(quantityOrder)) {
          this.setMsg(index + `、物料编号[${item["物料编号"]}]数量请输入正整数!`, "red");
        }
 
        index++;
      }
 
      // 校验失败返回
      if (this.isMsgError) {
        this.setMsg("-1");
        return;
      }
 
      msgList = msgList.filter(msg => msg);
 
      if (msgList.length) {
        this.info.result = false;
        this.info.msg = msgList.join("");
        // return;
        ctx.body = this.info;
      }
      // 分组
      let groupList = dataList.reduce(
        (all: Array<any>, next) =>
          all.some(
            item => item["预计到货时间"] == next["预计到货时间"] && item["供应商简称"] == next["供应商简称"] && item["订单类型"] == next["订单类型"]
          )
            ? all
            : [...all, next],
        []
      );
 
      for (let quotaitem of groupList) {
        let quotInfo = new TMSQuotation();
        //处理主表
        let orderCode = await ctx.service.common.getCodeRegular(334);
        quotInfo.quotationCode = orderCode;
        quotInfo.consignor_Id = consignor.consignor_Id;
        quotInfo.consignorCode = consignor.consignorCode;
        quotInfo.consignorName = consignor.consignorName;
        quotInfo.arrivedDate = quotaitem["预计到货时间"];
        quotInfo.storage_Id = storage.storage_Id;
        quotInfo.storageName = storage.storageName;
        quotInfo.quotationType = quotaitem["订单类型"];
        quotInfo.quotationStatus = "新建";
        quotInfo.remark = null;
        quotInfo.createID = userInfo.consignor_Id;
        quotInfo.creator = userInfo.consignorName;
        quotInfo.createDate = new Date();
 
        await this.setAccountInfo(quotInfo);
        //明细数据
        var billDetails = dataList.filter(w => w["预计到货时间"] == quotaitem["预计到货时间"] && w["供应商简称"] == quotaitem["供应商简称"]);
        // 主表求和字段计算
        let total: any = billDetails.reduce(
          (totalItem: any, currItem) => {
            totalItem.totalQuantityOrder += parseFloat(currItem["数量"] != null ? currItem["数量"] : 0);
            totalItem.totalWeight += parseFloat(currItem["数量"]) * parseFloat(currItem["单位毛重"] != null ? currItem["单位毛重"] : 0);
            totalItem.grandTotal += parseFloat(currItem["金额"] != null ? currItem["金额"] : 0);
 
            return totalItem;
          },
          { totalQuantityOrder: 0, totalWeight: 0, grandTotal: 0 }
        );
        quotInfo.totalQuantityOrder = total.totalQuantityOrder;
        quotInfo.totalWeight = total.totalWeight;
        quotInfo.grandTotal = total.grandTotal;
        await this.dbWrite.save(quotInfo);
        // let quotation = await this.dbRead.findOne(TMSQuotation, {
        //   quotationCode: orderCode
        // });
 
        index = 0;
        for (let item of billDetails) {
          index++;
          //添加到TMS_WayBillList表
          var rowTotal = (item["单价"] != null ? item["单价"] : 0) * item["数量"];
          var totalWeight = item["单位毛重"] * item["数量"];
 
          // let where;
          // if (SKU_BarcodeToMultiProduct) {
          //   where = "ProductCode=N'" + item["物料编号"] + "'";
          // } else {
          //   where = "ProductCode=N'" + item["物料编号"] + "'  and  ProductModel=N'" + item["物料条码"] + "'";
          // }
          // let sql = "select * from Base_ProductInfo where " + where;
          // let productInfo = await this.dbRead.query(sql);
          let where = "productCode= :productCode and productModel =:productModel";
 
          let productInfo = await this.dbRead
            .createQueryBuilder(BaseProductInfo, "t")
            .where(where, {
              productCode: "" + item["物料编号"],
              productModel: "" + item["物料条码"]
            })
            .getOne();
 
          let listInfo = new TMSQuotationList();
          if (!item["单位"]) {
            listInfo.smallUnit = productInfo.smallUnit;
          } else {
            listInfo.smallUnit = item["单位"];
          }
          listInfo.quotation_Id = quotInfo.quotation_Id;
          listInfo.product_Id = productInfo.product_Id;
          listInfo.productName = productInfo.productName;
          listInfo.productCode = productInfo.productCode;
          listInfo.productModel = productInfo.productModel;
          listInfo.productSpec = productInfo.productSpec;
          listInfo.quantityOrder = item["数量"];
          listInfo.salePrice = productInfo.salePrice != null ? productInfo.salePrice : 0;
          listInfo.rowTotal = rowTotal;
          listInfo.batchNumber = item["批次号"] != null ? item["批次号"] : null;
          listInfo.totalWeight = totalWeight;
          listInfo.weight = item["单位毛重"];
          listInfo.createDate = new Date();
          listInfo.creator = userInfo.userTrueName;
          listInfo.createID = userInfo.user_Id;
          await this.dbWrite.save(listInfo);
          this.setMsg(index + `、物料编号[${productInfo.productModel}]导入成功`);
        }
      }
      this.info.result = true;
    } catch (ex) {
      this.setMsg("出现异常:" + ex.message, "red");
    }
    this.setMsg("-1");
  }
  //#endregion
}