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
//#region import
import BaseApiService from "../baseApiService";
import { ResultInfo } from "../../public/commonInterface";
import moment = require("moment");
import * as crypto from "crypto";
import xml2js = require("xml2js");
import { ExpressYTOrder } from "../../entity/express/yuantong/expressYTOrder";
import { ExpressYTBaseInfo } from "../../entity/express/yuantong/expressYTBaseInfo";
import { ExpressYTOrderList } from "../../entity/express/yuantong/expressYTOrderList";
import { ExpressYTOrderRoute } from "../../entity/express/yuantong/expressYTOrderRoute";
import { SaleOrder } from '../../entity/outbound/sale/saleOrder';
 
//#endregion
 
/**
 * 运单轨迹帮助类
 */
export default class YuantongHelperService extends BaseApiService {
  //#region 圆通推送运单 pushOrderbyYT
  public async pushOrderbyYT(orderId): Promise<ResultInfo> {
    let { ctx } = this;
    let info: ResultInfo = {
      result: false,
      msg: undefined
    };
    try {
      let orderInfo = await this.dbRead.findOne(ExpressYTOrder, {
        yTOrder_Id: orderId
      });
      var pushNum = 0;
      if (orderInfo.pushNum) {
        pushNum = orderInfo.pushNum;
      }
      if (pushNum >= 5) {
        info.result = false;
        info.msg = "订单[" + orderInfo.orderCode + "]推送次数超过5次,无法推送!";
        return info;
      }
      pushNum = pushNum + 1;
      //获得账户信息
      // if (!orderInfo.interfaceAccount_Id) {
      //   info.result = false;
      //   info.msg = "订单[" + orderInfo.orderCode + "]位置接口账号,无法推送!";
      //   return info;
      // }
      let baseInfo = await this.dbRead.findOne(ExpressYTBaseInfo, {
        userProduct_Id: orderInfo.userProduct_Id,
        apiName: '圆通电子面单接口'
      });
      var yT_WebService = baseInfo.apiUrl;
      var clientId = baseInfo.clientId;
      var partnerID = baseInfo.partnerID;
      var type = baseInfo.type;
      let orderList = await this.dbRead
        .createQueryBuilder(ExpressYTOrderList, "t")
        .where(`yTOrder_Id=:yTOrder_Id`, {
          yTOrder_Id: orderId
        })
        .getMany();
      var items = "";
      var special = 0;
      for (let list of orderList) {
        special = parseInt(list.special);
        items +=
          " <item>" +
          "            <itemName>" +
          list.itemName +
          "</itemName>" +
          "            <number>" +
          list.number +
          "</number>" +
          "            <itemValue>" +
          list.itemValue +
          "</itemValue>" +
          "        </item>";
      }
      //发货人市区
      var sendercity = "";
      if (orderInfo.sendercity) {
        sendercity = orderInfo.sendercity;
      }
      if (orderInfo.sendercounty) {
        if (sendercity) {
          sendercity += ",";
        }
        sendercity += orderInfo.sendercounty;
      }
 
      //收货人市区
      var city = "";
      if (orderInfo.city) {
        city = orderInfo.city;
      }
      if (orderInfo.county) {
        if (city) city += ",";
        city += orderInfo.county;
      }
 
      var xmlBuilder =
        "<RequestOrder>" +
        "    <clientID>" +
        clientId +
        "</clientID>" +
        "    <logisticProviderID>YTO</logisticProviderID>" +
        "    <customerId>" +
        clientId +
        "</customerId>" +
        "    <txLogisticID>" +
        orderInfo.orderCode +
        "</txLogisticID>" +
        "    <tradeNo></tradeNo>" +
        "    <mailNo></mailNo>" +
        "    <totalServiceFee>" +
        orderInfo.totalServiceFee +
        "</totalServiceFee>" +
        "    <codSplitFee>" +
        orderInfo.codSplitFee +
        "</codSplitFee>" +
        "    <orderType>" +
        orderInfo.orderType +
        "</orderType>" +
        "    <serviceType>" +
        orderInfo.serviceType +
        "</serviceType>" +
        "    <flag>" +
        orderInfo.flag +
        "</flag>" +
        "    <sendStartTime>" +
        orderInfo.sendEndTime +
        "</sendStartTime>" +
        "    <sendEndTime>" +
        orderInfo.sendEndTime +
        "</sendEndTime>" +
        "    <goodsValue>" +
        orderInfo.goodsValue +
        "</goodsValue>" +
        "    <insuranceValue>" +
        orderInfo.itemsWeight +
        "</insuranceValue>" +
        "    <special>" +
        special +
        "</special>" +
        "    <remark>" +
        orderInfo.remark +
        "</remark>" +
        "    <type>" +
        orderInfo.type +
        "</type>" +
        "    <totalValue>" +
        orderInfo.totalValue +
        "</totalValue>" +
        "    <itemsWeight>" +
        orderInfo.itemsWeight +
        "</itemsWeight>" +
        "    <sender>" +
        "        <name>" +
        orderInfo.sendername +
        "</name>" +
        "        <postCode>" +
        orderInfo.senderpostCode +
        "</postCode>" +
        "        <phone>" +
        orderInfo.senderphone +
        "</phone>" +
        "        <mobile>" +
        orderInfo.sendermobile +
        "</mobile>" +
        "        <prov>" +
        orderInfo.senderprov +
        "</prov>" +
        "        <city>" +
        sendercity +
        "</city>" +
        "        <address>" +
        orderInfo.senderaddress +
        "</address>" +
        "    </sender>" +
        "    <receiver>" +
        "        <name>" +
        orderInfo.name +
        "</name>" +
        "        <postCode>" +
        orderInfo.postCode +
        "</postCode>" +
        "        <phone>" +
        orderInfo.phone +
        "</phone>" +
        "        <mobile>" +
        orderInfo.mobile +
        "</mobile>" +
        "        <prov>" +
        orderInfo.prov +
        "</prov>" +
        "        <city>" +
        city +
        "</city>" +
        "        <address>" +
        orderInfo.address +
        "</address>" +
        "    </receiver>" +
        "    <items>" +
        items +
        "    </items>" +
        "</RequestOrder>";
      xmlBuilder = xmlBuilder.replace("&", "&amp;");
      // var orderMsg = "";
      var md5 = crypto.createHash("md5");
      var data_digest = md5.update(xmlBuilder + partnerID, "utf8").digest("base64");
      let result = await this.ctx.curl(yT_WebService, {
        method: "POST",
        contentType: "application/x-www-form-urlencoded;charset=utf-8",
        data: {
          logistics_interface: xmlBuilder,
          data_digest: data_digest,
          clientId: clientId,
          type: type
        }
      });
      // result.data="";
      let data = Buffer.from(result.data).toString();
      ctx.logger.info("圆通获取单号xml返回信息-=======" + data);
      //xml解析器
      var xmlParser = new xml2js.Parser();
      var success = "";
      var mailNo = "";
      var shortAddress = "";
      var errorStr = "";
      var errorcode = "";
      await xmlParser.parseString(data, function (err, result) {
        ctx.logger.info("圆通获取单号返回信息error-=======" + err);
        ctx.logger.info("圆通获取单号返回信息josnResult-=======" + JSON.stringify(result));
        success = result.Response.success[0];
        if (success == "true") {
          mailNo = result.Response.mailNo[0];
          shortAddress = result.Response.distributeInfo[0].shortAddress[0];
        } else {
          errorStr = result.Response.reason[0];
          errorcode = result.Response.code[0];
        }
      });
      if (success == "true") {
        await this.dbWrite
          .createQueryBuilder(ExpressYTOrder, "t")
          .update()
          .set({
            trackingNumber: mailNo,
            mailNo: mailNo,
            bigPen: shortAddress,
            pushDate: new Date(),
            interfaceStatusID: 3,
            interfaceStatusText: "推送成功"
          })
          .where(`yTOrder_Id=:yTOrder_Id`, {
            yTOrder_Id: orderInfo.yTOrder_Id
          })
          .execute();
        // 更新销售单
        await this.dbWrite
          .createQueryBuilder(SaleOrder, "t")
          .update()
          .set({
            expressCode: mailNo,
            bigPen: shortAddress
          })
          .where(`order_Id=:order_Id and expressCode is null  and expressCorpType=:expressCorpType`, {
            order_Id: orderInfo.order_Id,
            expressCorpType: 5
          })
          .execute();
        let where = "order_Id=:order_Id";
        var saleOrderInfo = await this.dbRead
          .createQueryBuilder(SaleOrder, "t")
          .where(where, {
            order_Id: orderInfo.order_Id
          })
          .getOne();
        // 记录销售单轨迹
        if (saleOrderInfo) {
          await ctx.service.outbound.orderHelper.setStatusHistory(saleOrderInfo.order_Id, saleOrderInfo.statusID, saleOrderInfo.statusID, "获取圆通快递单号", "快递单号:" + mailNo);
        }
        // await this.dbWrite
        //   .createQueryBuilder(TMSWayBill, "t")
        //   .update()
        //   .set({
        //     expressCode: mailNo,
        //     bigPen: shortAddress
        //   })
        //   .where(`wayBill_Id=:wayBill_Id and expressCode is null `, {
        //     wayBill_Id: orderInfo.order_Id
        //   })
        //   .execute();
 
        // let where = "wayBill_Id=:wayBill_Id";
        // var tmsWayBillInfo = await this.dbRead
        //   .createQueryBuilder(TMSWayBill, "t")
        //   .where(where, {
        //     wayBill_Id: orderInfo.order_Id
        //   })
        //   .getOne();
        // if (tmsWayBillInfo) {
        //   await ctx.service.tms.wayBillHelper.setStatusHistory(tmsWayBillInfo, "获取快递号", "圆通单号" + mailNo);
        // }
        info.msg = "订单[" + orderInfo.orderCode + "]推送结果为成功。";
        info.result = true;
      } else {
        info.result = false;
        var orderMsg = "错误信息:" + errorStr + ",错误编号为" + errorcode;
        info.msg = "订单[" + orderInfo.orderCode + "]获取结果:" + orderMsg;
        await this.dbWrite
          .createQueryBuilder(ExpressYTOrder, "t")
          .update()
          .set({
            pushNum: pushNum,
            remark: orderMsg
          })
          .where(`yTOrder_Id=:yTOrder_Id`, {
            yTOrder_Id: orderInfo.yTOrder_Id
          })
          .execute();
      }
    } catch (error) {
      info.msg = error.message;
      info.result = false;
    }
    return info;
  }
  //    #endregion
 
  //#region 圆通运单获取路由 getRouteByYT
  public async getRouteByYT(orderId): Promise<ResultInfo> {
    let { ctx } = this;
    let info: ResultInfo = {
      result: false,
      msg: undefined
    };
    try {
      let orderInfo = await this.dbRead.findOne(ExpressYTOrder, {
        yTOrder_Id: orderId
      });
      let baseInfo = await this.dbRead.findOne(ExpressYTBaseInfo, {
        userProduct_Id: orderInfo.userProduct_Id,
        apiName: '圆通走件流程查询接口'
      });
      // var yT_WebService = "http://MarketingInterface.yto.net.cn"; //请求地址
      var yT_WebService = baseInfo.apiUrl; //请求地址
      // var user_id = "AUOD2144"; //用户在开放平台注册时填写的客户标识
      var app_key = baseInfo.app_key; //分配给用户的app_key  "sF1Jzn"
      var user_id = baseInfo.clientId; //用户在开放平台注册时填写的客户标识
      //var app_key = baseInfo.partnerID; //分配给用户的app_key
      var method = "yto.Marketing.WaybillTrace"; //分配给用户的方法名
      var timestamp = moment(new Date()).format("YYYY-MM-DD HH:mm:ss"); //时间戳,格式为yyyy-MM-dd HH:mm:ss,例如2012-06-20 11:00:00
      var v = "1.01"; //API协议的版本号
      var format = "XML";
      //var secret_Key = "ntdyg2"; //由开放平台分配给用户的Secret_Key,生成签名时使用
      var secret_Key = baseInfo.partnerID; //由开放平台分配给用户的Secret_Key,生成签名时使用
      var num = "1.0";
      var formatInfo =
        '<?xml version="' +
        num +
        '"?>' +
        "<ufinterface>" +
        "<Result>" +
        "<WaybillCode>" +
        "<Number>" +
        orderInfo.trackingNumber +
        "</Number>" +
        "</WaybillCode>" +
        "</Result>" +
        "</ufinterface>";
      var xml =
        secret_Key +
        "app_key" +
        app_key +
        "format" +
        format +
        "method" +
        method +
        "timestamp" +
        timestamp +
        "user_id" +
        user_id +
        "v" +
        v +
        "";
      var md5 = crypto.createHash("md5");
      var sign = md5
        .update(xml)
        .digest("hex")
        .toUpperCase();
      let result = await this.ctx.curl(yT_WebService, {
        method: "POST",
        contentType: "application/x-www-form-urlencoded;charset=utf-8",
        data: {
          sign: sign,
          app_key: app_key,
          format: format,
          method: method,
          timestamp: timestamp,
          user_id: user_id,
          v: v,
          param: formatInfo
        }
      });
      let data = Buffer.from(result.data).toString();
      ctx.logger.info("圆通获取单号xml返回信息-=======" + data);
      //  data = "<?xml version='1.0'?><ufinterface> <Result> <WaybillProcessInfo> <Waybill_No>500121003301</Waybill_No> <Upload_Time>2015/5/5 19:34:55</Upload_Time> <ProcessInfo>北京市海淀区中关村公司 已揽收</ProcessInfo> </WaybillProcessInfo> <WaybillProcessInfo> <Waybill_No>500121003301</Waybill_No> <Upload_Time>2015/5/5 20:13:20</Upload_Time> <ProcessInfo>北京市海淀区中关村公司 已打包,发往下一站 济南转运中心</ProcessInfo> </WaybillProcessInfo> <WaybillProcessInfo> <Waybill_No>500121003301</Waybill_No> <Upload_Time>2015/5/6 10:21:10</Upload_Time> <ProcessInfo>济南转运中心公司 已发出,下一站 山东省济南市千佛山</ProcessInfo> </WaybillProcessInfo> <WaybillProcessInfo> <Waybill_No>500121003301</Waybill_No> <Upload_Time>2015/5/6 13:36:31</Upload_Time> <ProcessInfo>快件到达 山东省济南市千佛山公司</ProcessInfo> </WaybillProcessInfo> <WaybillProcessInfo> <Waybill_No>500121003301</Waybill_No> <Upload_Time>2015/5/6 13:41:55</Upload_Time> <ProcessInfo>山东省济南市千佛山公司 派件人: ***** 派件中 派件员电话1234567891</ProcessInfo> </WaybillProcessInfo> </Result> </ufinterface>";
      var xmlParser = new xml2js.Parser();
      var errorStr = "";
      var success = true;
      var nodeList = [];
      await xmlParser.parseString(data, function (err, result) {
        ctx.logger.info("圆通查询路由error-=======" + err);
        ctx.logger.info("圆通查询路由josnResult-=======" + JSON.stringify(result));
        var successStr = "";
        if (result.Response) {
          successStr = result.Response.Success[0];
        }
        if (successStr == "false") {
          success = false;
          errorStr = result.Response.reason[0];
        } else {
          success = true;
          if (result.ufinterface) {
            nodeList = result.ufinterface.Result[0].WaybillProcessInfo;
          }
          else {
            success = false;
            errorStr = "查询结果为空。";
          }
        }
      });
      var lastMsg = "";
      if (success) {
        var ytOrderRouteInfo = await this.dbRead.findOne(ExpressYTOrderRoute, {
          where: { mailno: orderInfo.trackingNumber },
          order: { orderRoute_Id: "DESC" }
        });
        for (var item of nodeList) {
          var accept_time = item.Upload_Time[0];
          var remark = item.ProcessInfo[0];
          var mailno = item.Waybill_No[0];
          var accept_timeDate = moment(accept_time);
          if (lastMsg.indexOf("已签收") < 0) {
            lastMsg = remark;
          }
          if (ytOrderRouteInfo && accept_timeDate <= moment(ytOrderRouteInfo.accept_time)) {
            continue;
          }
          let routeInfo = new ExpressYTOrderRoute();
          routeInfo.mailNo = mailno;
          routeInfo.accept_time = moment(accept_time).toDate();
          routeInfo.accept_address = remark;
          routeInfo.yTOrder_Id = orderInfo.yTOrder_Id;
          routeInfo.order_Id = orderInfo.order_Id;
          await this.dbWrite.insert(ExpressYTOrderRoute, routeInfo);
        }
        info.msg = lastMsg;
        info.result = true;
      } else {
        info.result = false;
        var orderMsg = "错误信息:" + errorStr;
        info.msg = "订单[" + orderInfo.orderCode + "]获取结果:" + orderMsg;
      }
    } catch (error) {
      info.msg = error.message;
      info.result = false;
    }
    return info;
  }
  //    #endregion
}