schangxiang@126.com
2025-09-09 3d8966ba2c81e7e0365c8b123e861d18ee4f94f5
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
import { TMSWayBill } from "../../entity/express/tms/tmsWayBill";
import { TMSWayBillTracking } from "../../entity/express/tms/tmsWayBillTracking";
import BaseService from "../baseService";
import { TMSWayBillReceive } from "../../entity/express/tms/tmsWayBillReceive";
import moment = require("moment");
import { SaleOrder } from "../../entity/outbound/sale/saleOrder";
import { getConnection } from "typeorm";
 
/**
 * 运单轨迹帮助类
 */
export default class WayBillHelperService extends BaseService {
  //#region setStatusHistory
  /**
   * 操作新增运单追踪记录
   * @param wayInfo 运单信息
   * @param action 动作
   * @param toStatus 操作后状态
   * @param clientDesc 客户端描述
   * @param remark 备注
   */
  public async setStatusHistory(wayInfo: TMSWayBill, action: string, toStatus: string, clientDesc?: string, remark?: string) {
    let hisEntity = new TMSWayBillTracking();
    hisEntity.wayBill_Id = wayInfo.wayBill_Id;
    hisEntity.wayBillCode = wayInfo.wayBillCode;
    hisEntity.action = action;
    hisEntity.plateCode = wayInfo.plateCode;
    hisEntity.fromStatus = wayInfo.orderStatus;
    hisEntity.toStatus = toStatus;
    hisEntity.clientDesc = clientDesc;
    hisEntity.userProduct_Id = 1007;
    var userInfo = await this.ctx.helper.userInfo();
    hisEntity.creator = !userInfo ? "分拣机" : userInfo.userTrueName;
    hisEntity.createDate = new Date();
 
    hisEntity.remark = remark;
    try {
      await this.dbWrite.insert(TMSWayBillTracking, hisEntity);
      if (!hisEntity.userProduct_Id) {
        hisEntity.userProduct_Id = 1007;
        hisEntity.userProductCode = "100000001";
        hisEntity.userProductAlias = "WmsSaaS云仓系统";
        hisEntity.platUser_Id = 1;
        hisEntity.platCorpName = "澳德";
        hisEntity.platUserCode = "PT20180001";
        await this.dbWrite.update(TMSWayBillTracking, hisEntity.wayBillTracking_Id, hisEntity);
      }
    } catch (error) {
      console.log("运单轨迹生成失败:" + error.message);
    }
  }
 
  //#endregion
 
  //#region getWayBillInfo
  public async getWayBillInfo(wayBillCode: string, addQingGuan?: boolean) {
    let { ctx } = this;
    try {
      let waybill = await this.dbRead.findOne(TMSWayBill, { wayBillCode: wayBillCode });
      if (!waybill) {
        waybill = await this.dbRead.findOne(TMSWayBill, { expressCode: wayBillCode });
      }
      if (!waybill) {
        waybill = await this.dbRead.findOne(TMSWayBill, { customerOrderNo: wayBillCode });
      }
      // if (!waybill) {
      //   this.info.result = false;
      //   this.info.msg = "运单号不存在";
      //   return this.info;
      // }
 
      let wayBillReceive = await this.dbRead.findOne(TMSWayBillReceive, {
        where: { wayBillCode: wayBillCode }
      });
      if (waybill || wayBillReceive) {
        let remark: string | undefined;
        //#region 及时获新对应快递单号路由
        if (waybill && waybill.expressCode && waybill.orderStatus === "清关中") {
          try {
            wayBillCode = waybill.wayBillCode;
            var result = await this.service.tms.routerHelper.getRouter(waybill, true, addQingGuan);
            // await this.ctx.helper.sleep(1500); //暂停1.5秒,用于数据同步
            remark = result.msg;
            if (this.service.tms.routerHelper.isQianShou(result.msg)) {
              this.dbWrite.update(TMSWayBill, waybill.wayBill_Id, { orderStatus: "已签收" });
              waybill.orderStatus = "已签收";
              ctx.service.tms.wayBillHelper.setStatusHistory(waybill, "快递轨迹", "已签收");
            }
          } catch (error) {
            remark = error.message;
          }
        }
        if (waybill && waybill.orderStatus === "已签收") {
          let sql = `UPDATE dbo.TMS_RouterTask SET OrderStatus='已签收'
                                    WHERE WayBillCode ='${wayBillCode}'`;
          await this.dbWrite.query(sql);
        }
        //#endregion
 
        //#region 获得路由组合
        var expressCode = waybill != null ? waybill.expressCode : wayBillCode;
        var expressCorpName = waybill != null ? waybill.expressCorpName : "";
        let sql = `
                    SELECT clientDesc, MAX(t.createDate) AS  createDate, statusType
                    FROM
                    (
                        SELECT (
                            CASE 
                                WHEN R.clientDesc='清关中' OR  CHARINDEX('身份证', R.clientDesc)>0
                                THEN R.clientDesc + '-' + convert(nvarchar(16), R.createDate, 121)
                                ELSE R.clientDesc
                            END
                        ) as clientDesc, R.createDate, '内部' AS statusType
                        FROM dbo.TMS_WayBillTracking R with(nolock)
                        WHERE R.wayBillCode='${wayBillCode}' And clientDesc IS NOT NULL
                        UNION ALL`;
        if (expressCorpName == "EMS标准") {
          sql += ` SELECT  accept_address as AcceptAddress, accept_time AS  AcceptTime, '快递' AS statusType
                        FROM dbo.ExpressEMS_OrderRoute R with(nolock)
                        WHERE R.mailno='${expressCode}'`;
        } else if (expressCorpName === "顺丰快递" || expressCorpName === "泉州顺丰") {
          sql += ` SELECT accept_address as AcceptAddress, accept_time AS  AcceptTime, '快递' AS statusType
                        FROM dbo.ExpressSF_OrderRoute R with(nolock)
                        WHERE R.mailno='${expressCode}' `;
        } else if (
          expressCorpName === "福州EMS" ||
          expressCorpName === "邮政小包" ||
          expressCorpName === "广州EMS" ||
          expressCorpName === "厦门EMS"
        ) {
          sql += ` SELECT  AcceptAddress as AcceptAddress, AcceptTime AS  AcceptTime, '快递' AS statusType
                        FROM dbo.ExpressKD100_OrderRoute R with(nolock)
                        WHERE R.TrackNo='${expressCode}' `;
        } else if (expressCorpName === "圆通") {
          sql += ` SELECT  accept_address as AcceptAddress, accept_time AS  AcceptTime, '快递' AS statusType
                        FROM dbo.ExpressYT_OrderRoute R with(nolock)
                        WHERE R.mailNo='${expressCode}' `;
        } else if (expressCorpName == "陆地港圆通" || expressCorpName == "陆地港顺丰") {
          sql += ` SELECT  acceptAddress as AcceptAddress, acceptTime AS  AcceptTime, '快递' AS StatusType
            FROM dbo.ExpressQZPort_OrderRoute R with(nolock)
            WHERE R.mailNo='${waybill.expressCode}'`;
        } else {
          // sql += ` SELECT AcceptAddress, AcceptTime, '快递' AS statusType
          //   FROM dbo.vExpress_OrderRoute R with(nolock)
          //   WHERE R.ExpressCode='${expressCode}'`;
          sql += ` SELECT  AcceptAddress as AcceptAddress, AcceptTime AS  AcceptTime, '快递' AS statusType
                        FROM dbo.ExpressKD100_OrderRoute R with(nolock)
                        WHERE R.TrackNo='${expressCode}' `;
        }
 
        sql += `) t
                    GROUP BY t.clientDesc, statusType
                `;
        let hisList = await this.dbRead.query(sql);
 
        interface ItemType {
          toStatus: string;
          statusType: string;
          createDate: Date;
        }
        let historylist: ItemType[] = [];
        for (let row of hisList) {
          let obj: ItemType = {
            toStatus: "",
            statusType: "",
            createDate: new Date()
          };
          obj.toStatus = row.clientDesc;
          obj.statusType = row.statusType;
          obj.createDate = new Date(row.createDate);
 
          if (obj.toStatus) {
            historylist.push(obj);
            if (
              (obj.toStatus === "包裹已理货完毕,等待安排航司收货" || obj.toStatus === "出库扫描完毕,等待发往机场") &&
              obj.createDate &&
              !hisList.find(item => item.clientDesc === "已退货")
            ) {
              // 组板后1or2小时显示
              let moment = require("moment");
              let end = moment(new Date());
              let start = moment(new Date(obj.createDate));
              let span = moment.duration(end - start, "ms");
              let hours = span.get("hours");
              if (hours >= 1) {
                var obj1: ItemType = {
                  toStatus: "包裹已到达机场等待发运",
                  createDate: moment(obj.createDate).add(1, "hours"),
                  statusType: "内部"
                };
                historylist.push(obj1);
              }
            }
          }
        }
        //#endregion
 
        //#region 整理数据
        if (waybill == null) {
          waybill = new TMSWayBill();
          if (wayBillReceive) {
            Object.assign(waybill, wayBillReceive);
          }
        }
 
        historylist = historylist.sort(function (item1, item2) {
          return item1.createDate > item2.createDate ? -1 : 1;
        });
        var qingGuanList = historylist.filter(w => {
          return w.toStatus.indexOf("清关中") >= 0;
        });
        for (let qingGuanInfo of qingGuanList) {
          // 有快递轨迹不在显示清关中
          var prev = historylist.find(w => {
            return w.statusType === "快递" && w.createDate < qingGuanInfo.createDate;
          });
          if (prev) {
            var curr = historylist.find(f => {
              return f.toStatus === qingGuanInfo.toStatus;
            });
            if (curr) {
              curr.statusType = "不显示";
            }
          }
        }
        historylist = historylist.filter(w => {
          return w.statusType !== "不显示";
        });
        //#endregion
 
        //#region 返回数据
        this.info.result = true;
        this.info.data = {
          statusCode: 0,
          state: null,
          dynamic: null,
          msg: null,
          wbInfo: {
            wayBillCode: waybill.wayBillCode,
            portName: waybill.portName,
            expressCorpName: waybill.expressCorpName,
            voyageCode: waybill.voyageCode,
            plateCode: waybill.plateCode,
            weight: waybill.weight,
            grandTotal: waybill.grandTotal,
            storageName: waybill.storageName,
            orderType: waybill.orderType,
            orderStatus: waybill.orderStatus,
            // consigneeName: waybill.consigneeName,
            // consigneeMobile: waybill.consigneeMobile,
            // consigneeIdcard: waybill.consigneeIdcard,
            consigneePostCode: waybill.consigneePostCode,
            provinceName: waybill.provinceName,
            cityName: waybill.cityName,
            regionName: waybill.regionName,
            // consigneeAddress: waybill.consigneeAddress,
            makeWay: waybill.makeWay,
            expressCode: waybill.expressCode,
            actualWeight: waybill.actualWeight,
            grossWeight: waybill.grossWeight,
            totalQuantityOrder: waybill.totalQuantityOrder
          },
          hisList: historylist.map(s => {
            let createDate = moment(s.createDate);
            return {
              toStatus: s.toStatus,
              createDate: createDate.format("YYYY-MM-DD HH:mm:ss")
            };
          }),
          remark: remark
        };
        //#endregion
      } else {
        await this.getHis(wayBillCode);
      }
    } catch (ex) {
      this.info.result = false;
      this.info.msg = ex.message;
    }
    return this.info;
  }
 
  //#endregion
 
  private async getHis(wayBillCode: string) {
    let conn = getConnection("mssql-his");
    let manager = conn.manager;
 
    let waybill = await manager.findOne(TMSWayBill, {
      where: [{ wayBillCode: wayBillCode }, { customerOrderNo: wayBillCode }, { expressCode: wayBillCode }]
    });
    if (!waybill) {
      this.info.result = false;
      this.info.msg = "运单不存在";
      return;
    }
 
    let wayBillReceive = await manager.findOne(TMSWayBillReceive, {
      where: { wayBillCode: wayBillCode }
    });
 
    //#region 获得路由组合
    var expressCode = waybill != null ? waybill.expressCode : wayBillCode;
    var expressCorpName = waybill != null ? waybill.expressCorpName : "";
    let sql = `
                    SELECT clientDesc, MAX(t.createDate) AS  createDate, statusType
                    FROM
                    (
                        SELECT (
                            CASE 
                                WHEN R.clientDesc='清关中' OR  CHARINDEX('身份证', R.clientDesc)>0
                                THEN R.clientDesc + '-' + convert(nvarchar(16), R.createDate, 121)
                                ELSE R.clientDesc
                            END
                        ) as clientDesc, R.createDate, '内部' AS statusType
                        FROM dbo.TMS_WayBillTracking R with(nolock)
                        WHERE R.wayBillCode='${wayBillCode}' And clientDesc IS NOT NULL
                        UNION ALL`;
    if (expressCorpName == "EMS标准") {
      sql += ` SELECT  accept_address as AcceptAddress, accept_time AS  AcceptTime, '快递' AS statusType
                        FROM dbo.ExpressEMS_OrderRoute R with(nolock)
                        WHERE R.mailno='${expressCode}'`;
    } else if (expressCorpName === "顺丰快递" || expressCorpName === "泉州顺丰") {
      sql += ` SELECT accept_address as AcceptAddress, accept_time AS  AcceptTime, '快递' AS statusType
                        FROM dbo.ExpressSF_OrderRoute R with(nolock)
                        WHERE R.mailno='${expressCode}' `;
    } else if (expressCorpName === "福州EMS" || expressCorpName === "邮政小包") {
      sql += ` SELECT  AcceptAddress as AcceptAddress, AcceptTime AS  AcceptTime, '快递' AS statusType
                        FROM dbo.ExpressKD100_OrderRoute R with(nolock)
                        WHERE R.TrackNo='${expressCode}' `;
    } else if (expressCorpName === "圆通") {
      sql += ` SELECT  accept_address as AcceptAddress, accept_time AS  AcceptTime, '快递' AS statusType
                        FROM dbo.ExpressYT_OrderRoute R with(nolock)
                        WHERE R.mailNo='${expressCode}' `;
    } else {
      // sql += ` SELECT AcceptAddress, AcceptTime, '快递' AS statusType
      //   FROM dbo.vExpress_OrderRoute R with(nolock)
      //   WHERE R.ExpressCode='${expressCode}'`;
      sql += ` SELECT  AcceptAddress as AcceptAddress, AcceptTime AS  AcceptTime, '快递' AS statusType
                        FROM dbo.ExpressKD100_OrderRoute R with(nolock)
                        WHERE R.TrackNo='${expressCode}' `;
    }
 
    sql += `) t
                    GROUP BY t.clientDesc, statusType
        `;
    let hisList = await manager.query(sql);
 
    interface ItemType {
      toStatus: string;
      statusType: string;
      createDate: Date;
    }
    let historylist: ItemType[] = [];
    for (let row of hisList) {
      let obj: ItemType = {
        toStatus: "",
        statusType: "",
        createDate: new Date()
      };
      obj.toStatus = row.clientDesc;
      obj.statusType = row.statusType;
      obj.createDate = new Date(row.createDate);
 
      if (obj.toStatus) {
        historylist.push(obj);
        if (
          (obj.toStatus === "包裹已理货完毕,等待安排航司收货" || obj.toStatus === "出库扫描完毕,等待发往机场") &&
          obj.createDate &&
          !hisList.find(item => item.clientDesc === "已退货")
        ) {
          // 组板后1or2小时显示
          let moment = require("moment");
          let end = moment(new Date());
          let start = moment(new Date(obj.createDate));
          let span = moment.duration(end - start, "ms");
          let hours = span.get("hours");
          if (hours >= 1) {
            var obj1: ItemType = {
              toStatus: "包裹已到达机场等待发运",
              createDate: moment(obj.createDate).add(1, "hours"),
              statusType: "内部"
            };
            historylist.push(obj1);
          }
        }
      }
    }
    //#endregion
 
    //#region 整理数据
    if (waybill == null) {
      waybill = new TMSWayBill();
      if (wayBillReceive) {
        Object.assign(waybill, wayBillReceive);
      }
    }
 
    historylist = historylist.sort(function (item1, item2) {
      return item1.createDate > item2.createDate ? -1 : 1;
    });
    var qingGuanList = historylist.filter(w => {
      return w.toStatus.indexOf("清关中") >= 0;
    });
    for (let qingGuanInfo of qingGuanList) {
      // 有快递轨迹不在显示清关中
      var prev = historylist.find(w => {
        return w.statusType === "快递" && w.createDate < qingGuanInfo.createDate;
      });
      if (prev) {
        var curr = historylist.find(f => {
          return f.toStatus === qingGuanInfo.toStatus;
        });
        if (curr) {
          curr.statusType = "不显示";
        }
      }
    }
    historylist = historylist.filter(w => {
      return w.statusType !== "不显示";
    });
    //#endregion
 
    //#region 返回数据
    this.info.result = true;
    this.info.data = {
      statusCode: 0,
      state: null,
      dynamic: null,
      msg: null,
      wbInfo: {
        wayBillCode: waybill.wayBillCode,
        portName: waybill.portName,
        expressCorpName: waybill.expressCorpName,
        voyageCode: waybill.voyageCode,
        plateCode: waybill.plateCode,
        weight: waybill.weight,
        grandTotal: waybill.grandTotal,
        storageName: waybill.storageName,
        orderType: waybill.orderType,
        orderStatus: waybill.orderStatus,
        // consigneeName: waybill.consigneeName,
        // consigneeMobile: waybill.consigneeMobile,
        // consigneeIdcard: waybill.consigneeIdcard,
        consigneePostCode: waybill.consigneePostCode,
        provinceName: waybill.provinceName,
        cityName: waybill.cityName,
        regionName: waybill.regionName,
        // consigneeAddress: waybill.consigneeAddress,
        makeWay: waybill.makeWay,
        expressCode: waybill.expressCode,
        actualWeight: waybill.actualWeight,
        grossWeight: waybill.grossWeight,
        totalQuantityOrder: waybill.totalQuantityOrder
      },
      hisList: historylist.map(s => {
        let createDate = moment(s.createDate);
        return {
          toStatus: s.toStatus,
          createDate: createDate.format("YYYY-MM-DD HH:mm:ss")
        };
      }),
      remark: null
    };
    //#endregion
  }
 
  //#region 扫描成功出库成功后,生成揽收信息
  public async createWayBillReceive(expressCode: string, weight: number) {
    let { ctx } = this;
    let userInfo = await this.ctx.helper.userInfo();
 
    var orderInfo = await this.dbRead
      .createQueryBuilder(SaleOrder, "t")
      .where("expressCode=:orderCode OR orderCode=:orderCode", {
        orderCode: expressCode
      })
      .getOne();
    if (orderInfo.orderType === "仓配订单") {
      let orderCode = orderInfo.orderCode;
      if (orderCode) {
        console.log(orderCode + "开始更新重量=" + weight);
        //#region 将输入的重量更新到对应运单的包裹毛重中
        var dataInfo = await this.dbRead.findOne(TMSWayBill, {
          wayBillCode: orderCode
        });
        if (dataInfo != null) {
          await this.dbWrite.update(TMSWayBill, dataInfo.wayBill_Id, {
            grossWeight: weight
          });
 
          console.log(orderCode + "运单更新成功重量=" + weight);
        }
        console.log(orderCode + "结束更新重量=" + weight);
        //#endregion
 
        //根据运单号去揽收表查询是否存在,存在则不进行下面操作
        var wayBillReceive = await this.dbRead.findOne(TMSWayBillReceive, {
          wayBillCode: orderCode
        });
        if (wayBillReceive == null) {
          //#region 揽收记录不存在此运单号的信息时操作
          if (dataInfo != null) {
            //修改运单揽收状态
            await this.dbWrite.update(
              TMSWayBill,
              {
                wayBillCode: orderCode
              },
              {
                collectStatus: "已揽收"
              }
            );
          }
 
          //增加一条揽收记录
          let receive = new TMSWayBillReceive();
          receive.wayBillCode = dataInfo.wayBillCode;
          receive.consignor_Id = dataInfo.consignor_Id;
          receive.consignorName = dataInfo.consignorName;
          receive.consignorCode = dataInfo.consignorCode;
          receive.collectStatus = "已揽收";
          receive.user_Id = userInfo.platUser_Id;
          receive.userTrueName = userInfo.platUserName;
          receive.createID = userInfo.platUser_Id;
          receive.creator = userInfo.platUserName;
          receive.createDate = new Date();
          receive.storageName = dataInfo.storageName;
          receive.storage_Id = dataInfo.storage_Id;
          await this.setAccountInfo(receive);
 
          await this.dbWrite.save(receive);
          await ctx.service.tms.wayBillHelper.setStatusHistory(dataInfo, "打包完成", "打包完成", "包裹已配货,打包完毕");
          //#endregion
        } else {
          //#region 揽收记录存在此运单号的信息时操作
          if (dataInfo != null) {
            //修改运单揽收状态
            await this.dbWrite.update(
              TMSWayBill,
              {
                wayBillCode: orderCode
              },
              {
                collectStatus: "已揽收"
              }
            );
          }
          //揽收表存在信息则修改揽收表的信息
          wayBillReceive.consignor_Id = dataInfo.consignor_Id;
          wayBillReceive.consignorName = dataInfo.consignorName;
          wayBillReceive.consignorCode = dataInfo.consignorCode;
          wayBillReceive.collectStatus = "已揽收";
          wayBillReceive.modifyID = userInfo.platUser_Id;
          wayBillReceive.modifier = userInfo.platUserName;
          wayBillReceive.modifyDate = new Date();
          wayBillReceive.user_Id = wayBillReceive.modifyID;
          wayBillReceive.userTrueName = wayBillReceive.modifier;
          wayBillReceive.storageName = dataInfo.storageName;
          wayBillReceive.storage_Id = dataInfo.storage_Id;
          await this.dbWrite.save(wayBillReceive);
          await ctx.service.tms.wayBillHelper.setStatusHistory(dataInfo, "打包完成", "打包完成", "包裹打包完毕,仓库已揽收");
          //#endregion
        }
      }
    }
  }
  //#endregion
}