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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
import { default as BaseController } from "../baseController";
import { Post } from "egg-shell-decorators";
import { TMSQuotation } from "../../entity/express/tms/tmsQuotation";
import * as XLSX from "xlsx";
import * as path from "path";
import { BaseProvider } from "../../entity/basicInfo/base/baseProvider";
import { isNumber } from "util";
import moment = require("moment");
import { TMSQuotationList } from "../../entity/express/tms/tmsQuotationList";
import { BaseProductInfo } from "../../entity/basicInfo/base/baseProductInfo";
import { PurchaseOrder } from "../../entity/inbound/purchase/purchaseOrder";
import { PurchaseOrderList } from "../../entity/inbound/purchase/purchaseOrderList";
// import { BaseConsignor } from "../../entity/basicInfo/consignor/baseConsignor";
// import { BaseStorage } from "../../entity/basicInfo/base/baseStorage";
import { Not } from "typeorm";
import { FeeBaseOneCharge } from "../../entity/finance/base/feeBaseOneCharge";
import { BaseConsignor } from "../../entity/basicInfo/consignor/baseConsignor";
 
/**
 * 收货 - 收货计划单
 */
export default class QuotationController extends BaseController {
  //#region 批量审核
  /**
   * 批量审核
   */
  @Post()
  public async multiConfirm() {
    let { ctx } = this;
    let body = ctx.request.body;
    let userInfo = await ctx.helper.userInfo();
 
    try {
      //#region 校验数据
      if (!body.selectIDs) {
        this.info.result = false;
        this.info.msg = "数据不存在";
        return this.info;
      }
      //#endregion
 
      //#region 审核
      await this.dbWrite
        .createQueryBuilder()
        .update(TMSQuotation)
        .set({
          quotationStatus: "已审核",
          auditor: userInfo.userTrueName,
          auditing: 2,
          auditDate: new Date()
        })
        .where("quotation_Id in(:...selectIDs)", { selectIDs: body.selectIDs.split(",") })
        .execute();
      this.info.result = true;
      this.info.msg = "审核成功";
      //#endregion
 
      ctx.body = this.info;
    } catch (ex) {
      this.info.result = false;
      this.info.msg = "错误信息:" + ex.message;
    }
    ctx.body = this.info;
  }
  //#endregion
 
  //#region 批量导入
  /**
   * 批量导入入口,异步处理
   */
  @Post()
  async import() {
    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 userInfo = await ctx.helper.userInfo();
    let redis = ctx.app.redis.clients.get("common"); // 将消息放入redis缓存
    let fileUrl = body.fileUrl;
    redis.expire(body.key, 5 * 60);
    // let consioninfo = null;
    if (!body.key) {
      redis.rpush(body.key, "上传key不存在");
      return;
    }
    if (!fileUrl) {
      redis.rpush(body.key, "上传文件不存在");
      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格式
 
      //#region 验证数据正确性
      this.info.result = true;
      if (!dataList.length) {
        redis.rpush(body.key, "没有可导入的数据");
        return;
      }
 
      // 一码多品
      let SKU_BarcodeToMultiProduct = await ctx.service.common.getConfigBool("SKU_BarcodeToMultiProduct");
      // let consignorList = await this.dbRead.find(BaseConsignor, {
      //   userProduct_Id: userInfo.userProduct_Id,
      //   consignorName: In(dataList.map(item => "" + item["货主名称"]))
      // });
      // let storagelist = await this.dbRead.find(BaseStorage, {
      //   storageName: In(dataList.map(item => "" + item["仓库名称"])),
      //   userProduct_Id: userInfo.userProduct_Id
      // });
      let msg = "";
      let i = 0;
      for (let row of dataList) {
        i++;
        let productCode = "" + row["物料编号"];
        let prodInfo = null;
        if (SKU_BarcodeToMultiProduct) {
          prodInfo = await this.dbRead.findOne(BaseProductInfo, {
            productCode: productCode,
            userProduct_Id: userInfo.userProduct_Id
          });
        } else {
          prodInfo = await this.dbRead.findOne(BaseProductInfo, {
            productCode: productCode,
            userProduct_Id: userInfo.userProduct_Id
          });
        }
        // let prodInfo = await this.dbRead.findOne(BaseProductInfo, where);
        if (!prodInfo) {
          msg = `<span style='color:red;font-weight:bold;'>${i}、物料编号[${row["物料编号"]}]不存在,数据导入失败</span>`;
          redis.rpush(body.key, msg);
          this.info.result = false;
        }
        let produceDate = row["生产日期"];
        if (!produceDate) {
          if (!isNumber(produceDate)) {
            msg = `<span style='color:red;font-weight:bold;'>${i}"、产品编号[${productCode}]生产时间的格式不正确!</span>`;
            redis.rpush(body.key, msg);
            this.info.result = false;
          } else {
            row["生产日期"] = moment(new Date(1900, 0, produceDate - 1)).format("YYYY-MM-DD");
          }
        }
        let quantityOrder = row["生产数量"];
        if (quantityOrder && !isNumber(quantityOrder)) {
          msg = `<span style='color:red;font-weight:bold;'>${i}、产品编号[${productCode}]生产数量请输入正整数!</span>`;
          redis.rpush(body.key, msg);
        }
      }
      //#endregion
 
      // 校验不成功,不允许执行导入操作
      if (!this.info.result) {
        redis.rpush(body.key, `-1`); // 在消息里面插入-1表示结束
        return;
      }
 
      //#region 开始导入数据
      // 对单据进行分组
      let groupList = dataList.reduce(
        (all: Array<any>, next) =>
          // all.some(item => item["预计交货日期"] == next["预计交货日期"] && item["货主名称"] == next["货主名称"]) ? all : [...all, next],
          all.some(item => item["厂区名称"] == next["厂区名称"]) ? all : [...all, next],
        []
      );
 
      // 循环处理分组数据,groupList对应的是主表数据
      i = 0;
      let consign = await this.dbRead.findOne(BaseConsignor, {
        enable: 1,
        userProduct_Id: userInfo.userProduct_Id
      });
      for (let item of groupList) {
        i++;
        // 明细数据
 
        // let detailList = dataList.filter(row => row["预计到货时间"] === item["预计到货时间"] && row["货主名称"] === item["货主名称"]);
        let detailList = dataList.filter(row => row["厂区名称"] === item["厂区名称"]);
 
        // 判断是否存在多个集装箱号
        // let containerGroupList = detailList.reduce(
        //   (all: Array<any>, next) => (all.some(item => item["集装箱号"] == next["集装箱号"]) ? all : [...all, next]),
        //   []
        // );
        // if (containerGroupList.length > 1) {
        //   msg = `${i}、一条单据只能有一个集装箱号,目前存在${containerGroupList.length}个集装箱号`;
        //   redis.rpush(body.key, msg);
        //   this.info.result = false;
        //   redis.rpush(body.key, `-1`); // 在消息里面插入-1表示结束
        //   return;
        // }
 
        // let zbConsignor = await this.dbRead.findOne(BaseConsignor, {
        //   consignorName: item["货主名称"],
        //   userProduct_Id: userInfo.userProduct_Id
        // });
 
        redis.rpush(body.key, `${i}、第${i}行开始导入`);
        let quotationInfo = new TMSQuotation();
        let quotationCode = await ctx.service.common.getCodeRegular(334);
        quotationInfo.quotationCode = quotationCode;
        // quotationInfo.storage_Id = storagelist.storage_Id;
        // quotationInfo.storageName = storagelist.storageName;
        // quotationInfo.consignor_Id = zbConsignor.consignor_Id;
        // quotationInfo.consignorCode = zbConsignor.consignorCode;
        // quotationInfo.consignorName = zbConsignor.consignorName;
        // quotationInfo.arrivedDate = item["预计交货日期"];
        // quotationInfo.arrivedDate = item["预计到货时间"];
        quotationInfo.quotationType = "批量订单";
        quotationInfo.quotationStatus = "新建";
        // quotationInfo.containerNo = item["集装箱号"];
        quotationInfo.createDate = new Date();
        quotationInfo.createID = userInfo.user_Id;
        quotationInfo.creator = userInfo.userTrueName;
        quotationInfo.quotationType = item["厂区名称"];
        // quotationInfo.productionLineName = item["生产班线"];
        quotationInfo.consignorName = consign.consignorName;
        quotationInfo.consignor_Id = consign.consignor_Id;
        quotationInfo.consignorCode = consign.consignorCode;
 
        quotationInfo.platCorpName = userInfo.platCorpName;
        quotationInfo.platUserCode = userInfo.platUserCode;
        quotationInfo.platUserName = userInfo.platUserName;
        quotationInfo.platUser_Id = userInfo.platUser_Id;
        quotationInfo.userProductAlias = userInfo.userProductAlias;
        quotationInfo.userProductCode = userInfo.userProductCode;
        quotationInfo.userProduct_Id = userInfo.userProduct_Id;
        // 主表求和字段计算   quantityOrder
        let total: any = detailList.reduce(
          (totalItem: any, currItem) => {
            totalItem.totalQuantityOrder += currItem["生产数量"];
            totalItem.totalWeight += currItem["小计毛重"] || currItem["生产数量"] * currItem["单位毛重"];
            // totalItem.grandTotal += currItem["金额"];
 
            return totalItem;
          },
          { totalQuantityOrder: 0, totalWeight: 0 } // , grandTotal: 0
        );
        quotationInfo.totalQuantityOrder = total.totalQuantityOrder;
        quotationInfo.totalWeight = total.totalWeight;
        // quotationInfo.grandTotal = total.grandTotal;
        // 保存主表
        await this.dbWrite.insert(TMSQuotation, quotationInfo);
        let j = 0;
        // 处理明细,将明细挂载到主表下
        for (let detail of detailList) {
          j++;
          let detailInfo = new TMSQuotationList();
          let baseprodInfo = null;
          let productCode = "" + detail["物料编号"];
          if (SKU_BarcodeToMultiProduct) {
            baseprodInfo = await this.dbRead.findOne(BaseProductInfo, {
              productCode: productCode,
              userProduct_Id: userInfo.userProduct_Id
            });
          } else {
            baseprodInfo = await this.dbRead.findOne(BaseProductInfo, {
              productCode: productCode,
              userProduct_Id: userInfo.userProduct_Id
            });
          }
          // let storagelist = await this.dbRead.findOne(BaseStorage, {
          //   storageName: In(dataList.map(item => "" + item["仓库名称"])),
          //   userProduct_Id: userInfo.userProduct_Id
          // });
          // detailInfo.storageName = storagelist.storageName;
          // detailInfo.storage_Id = storagelist.storage_Id;
 
          //  prodInfo = await this.dbRead.findOne(BaseProductInfo, where);
          // 单位毛重 小计毛重都为空
          if (!detail["单位毛重"] && !detail["小计毛重"]) {
            detailInfo.weight = baseprodInfo.weight;
            detailInfo.totalWeight = baseprodInfo.weight * detail["生产数量"];
          }
          if (!detail["单位毛重"] && detail["小计毛重"]) {
            detailInfo.weight = detail["小计毛重"] / detail["生产数量"];
            detailInfo.totalWeight = detail["小计毛重"];
          }
          if (detail["单位毛重"] && !detail["小计毛重"]) {
            detailInfo.weight = detail["单位毛重"];
            detailInfo.totalWeight = detail["单位毛重"] * detail["生产数量"];
          }
          if (detail["单位毛重"] && detail["小计毛重"]) {
            detailInfo.weight = detail["单位毛重"];
            detailInfo.totalWeight = detail["小计毛重"];
          }
          detailInfo.productionLineName = detail["生产班线"];
          detailInfo.produceDate = detail["生产日期"];
          const currentDate = moment(new Date());
          detailInfo.batchNumber = currentDate.format("YYYYMMDD") + "-" + (j + 1);
          detailInfo.product_Id = baseprodInfo.product_Id;
          detailInfo.productCode = baseprodInfo.productCode;
          detailInfo.productModel = baseprodInfo.productModel;
          detailInfo.productName = baseprodInfo.productName;
          detailInfo.productSpec = baseprodInfo.productSpec;
          detailInfo.quantityOrder = detail["生产数量"];
          detailInfo.totalPackageQty = detail["生产数量"];
          detailInfo.salePrice = detail["单价"];
          detailInfo.rowTotal = detail["金额"];
          // detailInfo.weight = detail["单位毛重"] || baseprodInfo.weight;
          detailInfo.smallUnit = baseprodInfo.smallUnit;
          // detailInfo.totalWeight = detail["小计毛重"] || (detail["单位毛重"] || baseprodInfo.weight) * detail["数量"];
          detailInfo.originPlace = detail["原产地"];
          // detailInfo.weight = baseprodInfo.weight;
          detailInfo.createDate = new Date();
          detailInfo.creator = userInfo.userTrueName;
          detailInfo.createID = userInfo.user_Id;
 
          //建立关系
          detailInfo.tmsQuotation = quotationInfo;
          await this.dbWrite.insert(TMSQuotationList, detailInfo);
        }
        // 更新主表合计
        let sql = `
        update TMS_Quotation set
          totalWeight=(select sum(totalWeight) from TMS_QuotationList where quotation_Id=@0),
          grandTotal=(select sum(rowTotal) from TMS_QuotationList where quotation_Id=@0)
        where quotation_Id=@0;
        `;
        await this.dbWrite.query(sql, [quotationInfo.quotation_Id]);
        redis.rpush(body.key, `${i}、第${i}行导入成功`);
      }
      //#endregion
    } catch (e) {
      this.info.result = false;
      redis.rpush(body.key, `<font style="color:red;font-weight:bold;">解析出错" + ${e.toString()}</font>`);
    }
    redis.rpush(body.key, `-1`); // 在消息里面插入-1表示结束
  }
 
  //#endregion
 
  //#region 转到预到货单
  @Post()
  public async changePurchaseOrder() {
    let userInfo = await this.userInfo;
    try {
      if (!this.body.provider_Id) {
        this.info.result = false;
        this.info.msg = "请选择供应商";
        this.ctx.body = this.info;
        return;
      }
 
      // 是否开启唯一码
      let in_autoSingleSignCode = await this.ctx.service.common.getConfigBool("in_autoSingleSignCode");
 
      let quotationInfo = await this.dbRead.findOne(TMSQuotation, this.body.quotation_Id);
      let quotationDetails = await this.dbRead.find(TMSQuotationList, {
        quotation_Id: this.body.quotation_Id
      });
      let groupList = quotationDetails.reduce(
        (all: Array<any>, next) => (all.some(item => item.storage_Id == next.storage_Id) ? all : [...all, next]),
        []
      );
 
      for (let grounInfo of groupList) {
        let oldOrderInfo = await this.dbRead.findOne(PurchaseOrder, {
          sourceId: this.body.quotation_Id,
          storage_Id: grounInfo.storage_Id
        });
 
        // 获取默认收费项
        let type = "入库单";
        let where =
          "userProduct_Id=:userProduct_Id and storage_Id=:storage_Id and consignor_Id=:consignor_Id and isDefault=1 and associatedTasks like :associatedTasks";
        let oneChargeList = await this.dbRead
          .createQueryBuilder(FeeBaseOneCharge, "t")
          .where(where, {
            userProduct_Id: userInfo.userProduct_Id,
            storage_Id: grounInfo.storage_Id,
            consignor_Id: quotationInfo.consignor_Id,
            isDefault: 1,
            associatedTasks: "%" + type + "%"
          })
          .take(10)
          .getMany();
 
        if (oldOrderInfo != null) {
          this.info.result = false;
          this.info.msg = "该计划单转入过计划单了。";
          this.ctx.body = this.info;
          return;
        }
 
        let providerInfo = await this.dbRead.findOne(BaseProvider, this.body.provider_Id);
        let orderInfo = new PurchaseOrder();
        orderInfo.feeItem_Ids = oneChargeList.map(item => item.feeItem_Id).join("/"); //设置默认收费项
        orderInfo.orderCode = await this.ctx.service.common.getCodeRegular(102);
        orderInfo.orderType = "计划单转入";
        orderInfo.applyDate = new Date();
        orderInfo.consignorName = quotationInfo.consignorName;
        // orderInfo.dockCrossing = quotationInfo.dockCrossing;
        orderInfo.consignor_Id = quotationInfo.consignor_Id;
        orderInfo.consignorCode = quotationInfo.consignorCode;
        orderInfo.storage_Id = grounInfo.storage_Id;
        orderInfo.storageName = grounInfo.storageName; //仓库名称
        orderInfo.totalQuantity = quotationInfo.totalQuantityOrder;
        orderInfo.containerNo = quotationInfo.containerNo;
        // orderInfo.totalRateMoney = quotationInfo.grandTotal;
        orderInfo.userTrueName = userInfo.userTrueName;
        orderInfo.user_Id = userInfo.user_Id;
        orderInfo.dept_Id = userInfo.dept_Id;
        orderInfo.deptName = userInfo.deptName;
 
        // orderInfo.totalMoney = quotationInfo.grandTotal;
        orderInfo.totalWeight = quotationInfo.totalWeight;
        orderInfo.trackingNumber = quotationInfo.quotationCode; //BaseDataHelper.GetCodeRegular(334);
        orderInfo.remark = quotationInfo.remark;
        orderInfo.arrivedDate = quotationInfo.arrivedDate;
 
        orderInfo.providerCode = providerInfo.providerCode;
        orderInfo.providerShortName = providerInfo.providerShortName;
        orderInfo.provider_Id = providerInfo.provider_Id;
        if ((quotationInfo.quotationStatus = "新建")) {
          orderInfo.statusID = 1;
          orderInfo.statusText = "新建";
          orderInfo.auditing = 0;
        } else {
          orderInfo.statusID = 4;
          orderInfo.statusText = "在途中";
          orderInfo.auditing = 2;
        }
        orderInfo.sourceId = quotationInfo.quotation_Id;
        orderInfo.expandFields = quotationInfo.expandFields; // 带入扩展字段
        await this.setAccountInfo(orderInfo);
        await this.dbWrite.save(orderInfo);
 
        var billDetails = quotationDetails.filter(w => w.storage_Id == grounInfo.storage_Id);
        for (let qDetailInfo of billDetails) {
          let detailInfo = new PurchaseOrderList();
          detailInfo.order_Id = orderInfo.order_Id;
          detailInfo.product_Id = qDetailInfo.product_Id;
          detailInfo.productCode = qDetailInfo.productCode;
          detailInfo.productModel = qDetailInfo.productModel;
          detailInfo.productName = qDetailInfo.productName;
          detailInfo.productSpec = qDetailInfo.productSpec;
          detailInfo.quantity = qDetailInfo.quantityOrder;
          detailInfo.totalPackageQty = qDetailInfo.quantityOrder;
          detailInfo.smallUnit = qDetailInfo.smallUnit;
          detailInfo.purchasePrice = qDetailInfo.purchasePrice;
          detailInfo.purchaseMoney = qDetailInfo.rowTotal;
          if (in_autoSingleSignCode) {
            // 开启唯一码
            detailInfo.singleSignCode = this.ctx.service.common.getGUID();
          }
          let prodInfo = await this.dbRead.findOne(BaseProductInfo, detailInfo.product_Id);
          detailInfo.rate = prodInfo.rate || 0;
          detailInfo.ratePrice = detailInfo.purchasePrice * (1 + (prodInfo.rate || 0));
          detailInfo.taxAmount = qDetailInfo.rowTotal * (1 + (prodInfo.rate || 0));
          detailInfo.rateMoney = detailInfo.taxAmount;
 
          detailInfo.remark = qDetailInfo.remark;
          detailInfo.weight = qDetailInfo.weight;
          detailInfo.totalWeight = qDetailInfo.totalWeight;
          detailInfo.bigUnit = prodInfo.bigUnit;
          detailInfo.shelfLifeDay = prodInfo.shelfLifeDay;
          detailInfo.originPlace = qDetailInfo.originPlace;
          detailInfo.unitPackage = qDetailInfo.unitPackage;
          detailInfo.paiQty = Number(qDetailInfo.paiQty);
          detailInfo.produceDate = qDetailInfo.produceDate;
          detailInfo.expandFields = qDetailInfo.expandFields; // 带入扩展字段
          await this.dbWrite.save(detailInfo);
        }
        await this.dbWrite.update(TMSQuotation, quotationInfo.quotation_Id, {
          quotationStatus: "已转预到货单"
        });
      }
 
      this.info.result = true;
      this.info.msg = "转到预到货单成功。";
 
      this.ctx.body = this.info;
      return;
    } catch (ex) {
      this.info.result = false;
      this.info.msg = "错误信息:" + ex.message;
    }
    this.ctx.body = this.info;
    return;
  }
  //#endregion
 
  //#region app修改数据
  @Post()
  public async appUpdateQuotation() {
    let { ctx } = this;
    let body = ctx.request.body;
    let data = body.data;
    try {
      let quotation_Id = data.quotation_Id;
      let quotInfo = await this.dbRead.findOne(TMSQuotation, quotation_Id);
      if (!quotInfo) {
        quotInfo = new TMSQuotation(); // 新建单子
      }
      quotInfo = Object.assign(quotInfo, data);
      await this.setAccountInfo(quotInfo);
 
      await this.dbWrite.save(quotInfo);
 
      // 处理明细
      for (let detailInfo of data.TMS_QuotationList.rows) {
        let quotationList_Id = detailInfo.quotationList_Id;
        let detail = await this.dbRead.findOne(TMSQuotationList, quotationList_Id);
        if (!detail) {
          detail = new TMSQuotationList(); // 新建明细
          detailInfo.quotation_Id = quotInfo.quotation_Id;
        }
        detail.totalPackageQty = detailInfo.quantityOrder;
        detail = Object.assign(detail, detailInfo);
        await this.setAccountInfo(detail);
 
        await this.dbWrite.save(detail);
      }
      this.info.result = true;
      this.info.msg = "保存成功!";
 
      this.ctx.body = this.info;
      return;
    } catch (ex) {
      this.info.result = false;
      this.info.msg = "错误信息:" + ex.message;
    }
    this.ctx.body = this.info;
    return;
  }
  //#endregion
 
  //#region app新增数据
  @Post()
  public async addQuotation() {
    let { ctx } = this;
    let body = ctx.request.body;
    let data = body.data;
    try {
      let quotInfo = new TMSQuotation();
      quotInfo.quotationCode = await ctx.service.common.getCodeRegular(301);
      quotInfo.quotationStatus = "新建";
      quotInfo.quotationType = data.quotationType;
      quotInfo.arrivedDate = data.arrivedDate;
      quotInfo.containerNo = data.containerNo;
      quotInfo.totalQuantityOrder = data.totalQuantityOrder;
      quotInfo.totalWeight = data.totalWeight;
      quotInfo.grandTotal = data.grandTotal;
      quotInfo.consignor_Id = data.consignor_Id;
      quotInfo.consignorCode = data.consignorCode;
      quotInfo.consignorName = data.consignorName;
      await this.setAccountInfo(quotInfo);
      await this.dbWrite.insert(TMSQuotation, quotInfo);
      // 处理明细
      for (let detailInfo of data.TMS_QuotationList.rows) {
        let detail = new TMSQuotationList(); // 新建明细
        detail.quotation_Id = quotInfo.quotation_Id;
        detail.product_Id = detailInfo.product_Id;
        detail.productName = detailInfo.productName;
        detail.productCode = detailInfo.productCode;
        detail.productModel = detailInfo.productModel;
        detail.productSpec = detailInfo.productSpec;
        detail.purchasePrice = detailInfo.purchasePrice;
        detail.quantityOrder = detailInfo.quantityOrder;
        detail.totalPackageQty = detailInfo.quantityOrder;
        detail.rowTotal = detailInfo.rowTotal;
        detail.weight = detailInfo.weight;
        detail.totalWeight = detailInfo.totalWeight;
        detail.storage_Id = detailInfo.storage_Id;
        detail.storageName = detailInfo.storageName;
        await this.dbWrite.save(TMSQuotationList, detail);
      }
      this.info.result = true;
      this.info.msg = "保存成功!";
 
      this.ctx.body = this.info;
      return;
    } catch (ex) {
      this.info.result = false;
      this.info.msg = "错误信息:" + ex.message;
    }
    this.ctx.body = this.info;
    return;
  }
  //#endregion
 
  //#region app批量审核
  /**
   * app批量审核
   */
  @Post()
  public async submitAuditing() {
    let { ctx } = this;
    let body = ctx.request.body;
    let userInfo = await ctx.helper.userInfo();
    try {
      // 校验数据
      let quotation_Id = body.quotation_Id;
      let dataInfo = await this.dbRead.findOne(TMSQuotation, quotation_Id);
      if (dataInfo.quotationStatus !== "新建") {
        this.info.result = false;
        this.info.msg = "只有新建的单子才允许审核";
        return this.info;
      }
      await this.dbWrite.update(
        TMSQuotation,
        {
          quotation_Id: dataInfo.quotation_Id,
          userProduct_Id: userInfo.userProduct_Id
        },
        {
          quotationStatus: "已审核",
          auditing: 2,
          auditor: userInfo.userTrueName,
          auditDate: new Date()
        }
      );
      this.info.result = true;
      this.info.msg = "审核成功";
      ctx.body = this.info;
    } catch (ex) {
      this.info.result = false;
      this.info.msg = "错误信息:" + ex.message;
    }
    ctx.body = this.info;
  }
  //#endregion
 
  //#region 判断集装箱号
  /**
   * 判断集装箱号
   */
  @Post()
  public async getExistContainNo() {
    let { ctx } = this;
    let body = ctx.request.body;
    let userInfo = await ctx.helper.userInfo();
    let quotation_Id = body.quotation_Id || 0;
    let containerNo = body.containerNo;
    try {
      if (containerNo) {
        let dataInfo = await this.dbRead.findOne(TMSQuotation, {
          userProduct_Id: userInfo.userProduct_Id,
          containerNo: containerNo,
          quotation_Id: Not(quotation_Id) // 排查自己
        });
        this.info.result = !!dataInfo; // 存在
      } else {
        this.info.result = false; // 集装箱号为空时不需要判断,直接返回false
      }
    } catch (ex) {
      this.info.result = false;
      this.info.msg = "错误信息:" + ex.message;
    }
    ctx.body = this.info;
  }
  //#endregion
 
  //#region 获取计划进3天的明细
  /**
   * 获取计划进3天的明细
   */
  @Post()
  public async getDetails() {
    let { ctx } = this;
    let body = ctx.request.body;
 
    let whereStr = "1=1"; // 不筛选空器具
    var where: any = {};
    // 关键词查询条件
    if (body.name) {
      let name = this.ctx.helper.sqlSecurity(body.name);
      whereStr += ` AND (productName LIKE '%' + :name + '%' OR productCode LIKE '%' + :name + '%')`;
      where.name = name;
    }
    // 种类编号
    if (body.plateTypeCode) {
      whereStr += ` AND datediff(day,produceDate,getdate())<= 2 and datediff(day,produceDate,getdate())>= 0 AND plateTypeCode=:plateTypeCode AND QuotationListStatus is null`;
 
      // 根据计划明细中的生产日期,只获取当天的物料
      if (this.body.onlyShowPlan) {
        whereStr += ` AND Quotation_Id in(select Quotation_Id from Tms_Quotation where quotationType=:quotationType)`;
      }
      let quotationType = body.quotationType || "";
      where.quotationType = quotationType.replace("入库", "");
      where.plateTypeCode = body.plateTypeCode;
    }
 
    try {
      let builder = this.dbRead
        .createQueryBuilder(TMSQuotationList, "t")
        .innerJoin(BaseProductInfo, "p", "p.product_Id=t.product_Id")
        .where(whereStr, where)
        .select([
          "t.quotationList_Id as quotationList_Id",
          "t.quotation_Id as quotation_Id",
          "t.product_Id as product_Id",
          "t.productCode as productCode",
          "t.productModel as productModel",
          "t.productName as productName",
          "t.produceDate as produceDate",
          "p.orderType as orderType",
          "p.packingQuantity as packingQuantity",
          "p.plateCode as plateCode",
          "p.plate_Id as plate_Id",
          "p.destination_Id as destination_Id",
          "p.destinationName as destinationName",
          "p.plateTypeCode as plateTypeCode"
        ]);
      builder.take(200);
      let dataList = [];
      if (body.appendField === "*") {
        dataList = await builder.getMany();
      } else {
        dataList = await builder.getRawMany();
      }
 
      this.info.result = true;
      this.info.data = dataList;
    } catch (ex) {
      this.info.result = false;
      this.info.msg = "错误信息:" + ex.message;
    }
    ctx.body = this.info;
  }
  //#endregion
}