222
schangxiang@126.com
2025-06-13 6a8393408d8cefcea02b7a598967de8dc1e565c2
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
//#region import
import BaseApiService from "../baseApiService";
import { ResultInfo } from "../../public/commonInterface";
import moment = require("moment");
import * as crypto from "crypto";
// import { In } from "typeorm";
import { ExpressSFOrderList } from '../../entity/express/sf/expressSFOrderList';
import { ExpressSFOrder } from '../../entity/express/sf/expressSFOrder';
import { TMSWayBill } from '../../entity/express/tms/tmsWayBill';
import { ExpressSFBaseInfo } from '../../entity/express/sf/expressSFBaseInfo';
import xml2js = require('xml2js');
import { ExpressSFOrderRoute } from '../../entity/express/sf/expressSFOrderRoute';
// import moment = require("moment");
 
//#endregion
 
/**
 * 顺丰接口帮助类
 */
export default class shunfengHelperService extends BaseApiService {
 
  //#region 北京顺丰通过宏远获取快递单号
  public async pushOrderByHY(orderId, typeID): Promise<ResultInfo> {
    let { ctx } = this;
    let info: ResultInfo = {
      result: false,
      msg: undefined
    };
    try {
      // let expressList = await this.dbRead.find(ExpressSFOrderList, {
      //   sFOrder_Id: In(orderId)
      // });
      let expressList = await this.dbRead
        .createQueryBuilder(ExpressSFOrderList, "t")
        .where(`sFOrder_Id=:sFOrder_Id`, {
          sFOrder_Id: orderId
        })
        .getMany();
      var hYOrderList = [];
      for (let item of expressList) {
        if (item.name && item.name.length > 20) {
          item.name = item.name.substring(0, 20);
        }
        var hYOrderListInfo = {
          name: item.name,
          amount: item.amount,
          count: item.count,
          weight: item.weight
        };
        hYOrderList.push(hYOrderListInfo);
      }
      let orderInfo = await this.dbRead.findOne(ExpressSFOrder, {
        sFOrder_Id: orderId
      });
      if (!orderInfo.pushNum) {
        orderInfo.pushNum = 1;
      }
      else {
        orderInfo.pushNum = orderInfo.pushNum + 1;
      }
      await this.dbWrite.update(ExpressSFOrder, orderInfo.sFOrder_Id, {
        pushNum: orderInfo.pushNum
      });
 
      if (orderInfo.pushNum <= 5 || typeID == 1) {
        var hYOrderInfo = {
          logisticProviderID: "SF",
          ordernoOid: orderInfo.orderCode,
          shipper: orderInfo.j_contact,
          shippercity: orderInfo.j_city,
          shippercountry: "142",
          shipperaddress: orderInfo.j_address,
          shippertelephone: orderInfo.j_mobile,
          consignee: orderInfo.d_contact,
          consigneeprovince: orderInfo.d_province,
          consigneecity: orderInfo.d_city,
          consigneedistrict: orderInfo.d_county,
          consigneedeliver: orderInfo.d_address,
          consigneecountry: "142",
          consigneestreet: orderInfo.d_address,
          consigneetelephone: orderInfo.d_mobile,
          paymethod: "1",
          cargototalweight: orderInfo.cargo_total_weight,
          cargo: hYOrderList
        };
        var hyInfo = null;
        hyInfo = await ctx.service.express.hongyuanHelper.pushOrder(hYOrderInfo);
        ctx.logger.info("北京顺丰推送:单号" + orderInfo.orderCode + "/结果:" + hyInfo.msg + "/时间:" + moment(new Date()).format("YYYY-MM-DD HH:mm:ss"));
        if (hyInfo.result) {
          await this.dbWrite.createQueryBuilder(ExpressSFOrder, "t")
            .update()
            .set({
              mailno: hyInfo.data.logisticsno,
              interfaceStatusID: "3",
              interfaceStatusText: "宏远推送成功",
              bigPen: hyInfo.data.shortaddress
 
            })
            .where(
              `sFOrder_Id=:sFOrder_Id`,
              {
                sFOrder_Id: orderInfo.sFOrder_Id
              }
            ).execute();
          await this.dbWrite.createQueryBuilder(TMSWayBill, "t")
            .update()
            .set({
              expressCode: hyInfo.data.logisticsno,
              bigPen: hyInfo.data.shortaddress
 
            })
            .where(
              `wayBill_Id=:wayBill_Id and expressCode is null  and expressCorpType='2'`,
              {
                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, "获取快递号", "北京顺丰单号" + hyInfo.data.logisticsno);
          }
        }
        else {
          await this.dbWrite.createQueryBuilder(ExpressSFOrder, "t")
            .update()
            .set({
              remark: hyInfo.msg
            })
            .where(
              `sFOrder_Id=:sFOrder_Id`,
              {
                sFOrder_Id: orderInfo.sFOrder_Id
              }
            ).execute();
        }
        info.msg = hyInfo.msg;
        info.result = hyInfo.result;
      } else {
        info.result = false;
        info.msg = "推送失败次数超过5次,单据已失效请重新生成。";
      }
    } catch (error) {
      info.msg = error.message;
      info.result = false;
    }
    return info;
  }
 
  //#endregion
 
  //#region 泉州顺丰通过丰桥获取快递单号
  public async pushOrderbyFQ(orderId): Promise<ResultInfo> {
    let { ctx } = this;
    let info: ResultInfo = {
      result: false,
      msg: undefined
    };
    try {
      let orderInfo = await this.dbRead.findOne(ExpressSFOrder, {
        sFOrder_Id: orderId
      });
      if (orderInfo.expressCorpName != "泉州顺丰") {
        info.result = false;
        info.msg = "只有泉州顺丰才可以通过丰桥推送订单。";
        return info;
      }
      var name = "";
      let orderlistInfo = await this.dbRead.findOne(ExpressSFOrderList, {
        sFOrder_Id: orderId
      });
      if (orderlistInfo) {
        name = orderlistInfo.name.replace("+", "").replace("%", "").replace("*", "").replace("\"", "").replace("'", "");
      }
      if (orderInfo.j_address) {
        orderInfo.j_address = orderInfo.j_address.replace("\"", "");
      }
      if (orderInfo.d_address) {
        orderInfo.d_address = orderInfo.d_address.replace("\"", "");
      }
      let sfBaseInfo = await this.dbRead.findOne(ExpressSFBaseInfo, {
        baseInfo_Id: 20000
      });
      var xml = '<?xml version="1.0" encoding="utf-8"?><Request service="OrderService" lang="cn_ZH"><Head>' +
        sfBaseInfo.clientCode + '</Head><Body><Order orderid = "' +
        orderInfo.orderCode + '" express_type = "208" j_province ="' +
        orderInfo.j_province + '" j_city="' + orderInfo.j_city + '" j_county="' +
        orderInfo.j_county + '" j_company ="' + orderInfo.j_company + '" j_contact="' +
        orderInfo.j_contact + '" j_tel="' + orderInfo.j_tel + '" j_address="' +
        orderInfo.j_address + '" d_province="' + orderInfo.d_province + '" d_city="' +
        orderInfo.d_city + '" d_county="' + orderInfo.d_county + '" d_company="' +
        orderInfo.d_company + '" d_contact="' + orderInfo.d_contact + '" d_tel="' +
        orderInfo.d_tel + '" d_address="' + orderInfo.d_address + '" parcel_quantity="1" cargo_total_weight= "1" custid="' +
        sfBaseInfo.custid + '"  routelabelService="1"  routelabelForReturn="1"><Cargo name = "' +
        name + '" /></Order></Body></Request>';
      xml.replace("&", "").replace("+", "").replace("*", "");
      ctx.logger.info("丰桥获取单号xml获取信息-=======" + xml);
      var checkword = sfBaseInfo.verifyCode;
      var md5 = crypto.createHash("md5");
      var verifyCode = md5.update(xml + checkword, 'utf8').digest("base64");
      // var verifyCode = new Buffer(str).toString('base64');
      var requestUrl = sfBaseInfo.apiUrl;//地址    
      // let data = ;
      let result = await this.ctx.curl(requestUrl, {
        method: "POST",
        contentType: "application/x-www-form-urlencoded;charset=utf-8",
        data: {
          xml: xml,
          verifyCode: verifyCode
        }
      });
      // result.data="";
      let data = Buffer.from(result.data).toString();
      ctx.logger.info("丰桥获取单号xml返回信息-=======" + data);
      //xml解析器
      var xmlParser = new xml2js.Parser();
      var head = "";
      var updateInfo = null;
      var errorStr = "";
      var errorcode = "";
      await xmlParser.parseString(data, function (err, result) {
        ctx.logger.info("丰桥获取单号返回信息error-=======" + err);
        ctx.logger.info("丰桥获取单号返回信息josnResult-=======" + JSON.stringify(result));
        head = result.Response.Head[0];
        if (head == "OK") {
          var mailno = result.Response.Body[0].OrderResponse[0].$.mailno;
          var destcode = result.Response.Body[0].OrderResponse[0].$.destcode;
          var codingMapping = result.Response.Body[0].OrderResponse[0].rls_info[0].rls_detail[0].$.codingMapping;
          var codingMappingOut = result.Response.Body[0].OrderResponse[0].rls_info[0].rls_detail[0].$.codingMappingOut;
          var abFlag = result.Response.Body[0].OrderResponse[0].rls_info[0].rls_detail[0].$.abFlag;
          var pro_code = result.Response.Body[0].OrderResponse[0].rls_info[0].rls_detail[0].$.proCode;
          updateInfo = { mailno: mailno, interfaceStatusID: "3", interfaceStatusText: "丰桥推送成功", bigPen: destcode, codingMapping: null, codingMappingOut: null, abFlag: null, pro_code: null };
          if (codingMapping) {
            updateInfo.codingMapping = codingMapping;
          }
          if (codingMappingOut) {
            updateInfo.codingMappingOut = codingMappingOut;
          }
          if (abFlag) {
            updateInfo.abFlag = abFlag;
          }
          if (pro_code) {
            updateInfo.pro_code = pro_code;
          }
        }
        else {
          errorStr = result.Response.ERROR[0]._;
          errorcode = result.Response.ERROR[0].$.code;
        }
      });
      if (head == "OK") {
        await this.dbWrite.createQueryBuilder(ExpressSFOrder, "t")
          .update()
          .set(updateInfo)
          .where(
            `sFOrder_Id=:sFOrder_Id`,
            {
              sFOrder_Id: orderInfo.sFOrder_Id
            }
          ).execute();
        await this.dbWrite.createQueryBuilder(TMSWayBill, "t")
          .update()
          .set({
            expressCode: updateInfo.mailno,
            bigPen: updateInfo.destcode
 
          })
          .where(
            `wayBill_Id=:wayBill_Id and expressCode is null  and expressCorpType='19'`,
            {
              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, "获取快递号", "泉州顺丰单号" + updateInfo.mailno);
        }
 
        info.msg = "订单[" + tmsWayBillInfo.wayBillCode + "]推送结果为成功。";
        info.result = true;
 
      }
      else {
        info.result = false;
        var orderMsg = "错误信息:" + errorStr + ",错误编号为" + errorcode;
        info.msg = "订单[" + orderInfo.orderCode + "]获取结果:" + orderMsg;
        if (orderMsg.indexOf("重复下单") > 0) {
          info = await this.getOrderbyFQ(orderInfo.sFOrder_Id);
        }
      }
    } catch (error) {
      info.msg = error.message;
      info.result = false;
    }
    return info;
  }
  //#endregion
 
  //#region 泉州顺丰通过丰桥获取订单信息
  public async getOrderbyFQ(orderId): Promise<ResultInfo> {
    let { ctx } = this;
    let info: ResultInfo = {
      result: false,
      msg: undefined
    };
    try {
      let orderInfo = await this.dbRead.findOne(ExpressSFOrder, {
        sFOrder_Id: orderId
      });
      if (orderInfo.expressCorpName != "泉州顺丰") {
        info.result = false;
        info.msg = "只有泉州顺丰才可以通过丰桥获取订单信息。";
        return info;
      }
      let sfBaseInfo = await this.dbRead.findOne(ExpressSFBaseInfo, {
        baseInfo_Id: 20000
      });
      var xml = '<?xml version="1.0" encoding="utf-8"?><Request service = "OrderSearchService" lang="zh-CN"><Head>' + sfBaseInfo.clientCode + '</Head><Body><OrderSearch orderid="' + orderInfo.orderCode + '" search_type= "1"/></Body></Request>';
      ctx.logger.info("丰桥查询快递单号xml获取信息-=======" + xml);
      var checkword = sfBaseInfo.verifyCode;
      var md5 = crypto.createHash("md5");
      var verifyCode = md5.update(xml + checkword, 'utf8').digest("base64");
      var requestUrl = sfBaseInfo.apiUrl;//地址
      let result = await this.ctx.curl(requestUrl, {
        method: "POST",
        contentType: "application/x-www-form-urlencoded;charset=utf-8",
        data: {
          xml: xml,
          verifyCode: verifyCode
        }
      });
      // result.data="";
      let data = Buffer.from(result.data).toString();
      ctx.logger.info("丰桥查询快递单号xml返回信息-=======" + data);
      //xml解析器
      var xmlParser = new xml2js.Parser();
      var head = "";
      var mailno = "";
      var destcode = "";
      var errorStr = "";
      var errorcode = "";
      await xmlParser.parseString(data, function (err, result) {
        ctx.logger.info("丰桥查询快递单号error-=======" + err);
        ctx.logger.info("丰桥查询快递单号josnResult-=======" + JSON.stringify(result));
        head = result.Response.Head[0];
        if (head == "OK") {
          mailno = result.Response.Body[0].OrderResponse[0].$.mailno;
          destcode = result.Response.Body[0].OrderResponse[0].$.destcode;
        }
        else {
          errorStr = result.Response.ERROR[0]._;
          errorcode = result.Response.ERROR[0].$.code;
        }
      });
      if (head == "OK") {
        await this.dbWrite.createQueryBuilder(ExpressSFOrder, "t")
          .update()
          .set({ mailno: mailno, interfaceStatusID: "3", interfaceStatusText: "丰桥推送成功", bigPen: destcode })
          .where(
            `sFOrder_Id=:sFOrder_Id`,
            {
              sFOrder_Id: orderInfo.sFOrder_Id
            }
          ).execute();
        await this.dbWrite.createQueryBuilder(TMSWayBill, "t")
          .update()
          .set({
            expressCode: mailno,
            bigPen: destcode
          })
          .where(
            `wayBill_Id=:wayBill_Id and expressCode is null  and expressCorpType='19'`,
            {
              wayBill_Id: orderInfo.order_Id
            }
          ).execute();
        info.msg = "订单[" + orderInfo.orderCode + "]推送结果为成功。";
        info.result = true;
      } else {
        info.result = false;
        var orderMsg = "错误信息:" + errorStr + ",错误编号为" + errorcode;
        info.msg = "订单[" + orderInfo.orderCode + "]获取结果:" + orderMsg;
      }
 
    } catch (error) {
      info.msg = error.message;
      info.result = false;
    }
    return info;
  }
  //#endregion
 
  //#region 泉州顺丰通过丰桥获取路由信息
  public async getRouteByFQ(orderId): Promise<ResultInfo> {
    let { ctx } = this;
    let info: ResultInfo = {
      result: false,
      msg: undefined
    };
    try {
      let orderInfo = await this.dbRead.findOne(ExpressSFOrder, {
        sFOrder_Id: orderId
      });
      if (orderInfo.expressCorpName != "泉州顺丰") {
        info.result = false;
        info.msg = "错误信息:只有泉州顺丰才可以通过丰桥获取路由轨迹。";
        return info;
      }
      if (!orderInfo.mailno) {
        info.result = false;
        info.msg = "错误信息:未获取快递单号不允许获取路由轨迹。";
        return info;
      }
      let sfBaseInfo = await this.dbRead.findOne(ExpressSFBaseInfo, {
        baseInfo_Id: 20000
      });
      var xml = '<?xml version="1.0" encoding="utf-8"?><Request service="RouteService" lang="zh-CN"><Head>' + sfBaseInfo.clientCode + '</Head><Body><RouteRequest tracking_type="2" method_type="1" tracking_number="' + orderInfo.orderCode + '" /></Body></Request>';
      ctx.logger.info("丰桥查询路由xml获取信息-=======" + xml);
      var checkword = sfBaseInfo.verifyCode;
      var md5 = crypto.createHash("md5");
      var verifyCode = md5.update(xml + checkword, 'utf8').digest("base64");
      var requestUrl = sfBaseInfo.apiUrl;//地址
      let result = await this.ctx.curl(requestUrl, {
        method: "POST",
        contentType: "application/x-www-form-urlencoded;charset=utf-8",
        data: {
          xml: xml,
          verifyCode: verifyCode
        }
      });
      // result.data="";
      let data = Buffer.from(result.data).toString();
      ctx.logger.info("丰桥查询路由xml返回信息-=======" + data);
 
      // data = '<Response service="RouteService"><Head>OK</Head><Body><RouteResponse mailno="444003077898"> <Route accept_time="2015-01-04 10:11:26" accept_address="深圳"  remark="已收件" opcode="50"/><Route accept_time="2015-01-05 17:41:50" remark="此件签单返还的单号为 123638813180" opcode="922"/></RouteResponse><RouteResponse mailno="444003077899"> <Route accept_time="2015-01-04 10:11:26" accept_address="深圳" remark="已收件" opcode="50"/></RouteResponse></Body></Response>'
      var head = "";
      var errorStr = "";
      var errorcode = "";
      var mailno = "";
      var nodeList = null;
      var lastMsg = "";
      //xml解析器
      var xmlParser = new xml2js.Parser();
      await xmlParser.parseString(data, function (err, result) {
        ctx.logger.info("丰桥查询路由error-=======" + err);
        ctx.logger.info("丰桥查询路由josnResult-=======" + JSON.stringify(result));
        head = result.Response.Head[0];
        if (head == "OK") {
          mailno = result.Response.Body[0].RouteResponse[0].$.mailno;
          nodeList = result.Response.Body[0].RouteResponse[0].Route;
        }
        else {
          errorStr = result.Response.ERROR[0]._;
          errorcode = result.Response.ERROR[0].$.code;
        }
      });
      if (head == "OK") {
        var sfOrderInfo = await this.dbRead.findOne(ExpressSFOrderRoute, {
          where: { sFOrder_Id: orderInfo.sFOrder_Id },
          order: { accept_time: "DESC" }
        });
        for (var item of nodeList) {
          var accept_time = item.$.accept_time;
          var remark = item.$.remark;
          lastMsg = remark;
          var accept_timeDate = moment(accept_time);
          if (sfOrderInfo && accept_timeDate <= moment(sfOrderInfo.accept_time)) {
            continue;
          }
          let routeInfo = new ExpressSFOrderRoute();
          routeInfo.mailno = mailno;
          routeInfo.accept_time = moment(accept_time).toDate();
          routeInfo.accept_address = remark;
          routeInfo.sFOrder_Id = orderInfo.sFOrder_Id;
          routeInfo.order_Id = orderInfo.order_Id;
          await this.dbWrite.insert(ExpressSFOrderRoute, routeInfo);
        }
        info.msg = lastMsg;
        info.result = true;
      }
      else {
        info.result = false;
        var orderMsg = "错误信息:" + errorStr + ",错误编号为" + errorcode;
        info.msg = "订单[" + orderInfo.orderCode + "]获取结果:" + orderMsg;
      }
 
 
    } catch (error) {
      info.msg = error.message;
      info.result = false;
    }
    return info;
  }
  //#endregion
}