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
import BaseController from "../../baseController";
import { Post } from "egg-shell-decorators";
import * as XLSX from "xlsx";
import * as path from "path";
import { BaseProductInfo } from "../../../entity/basicInfo/base/baseProductInfo";
import { BaseCity } from "../../../entity/basicInfo/base/baseCity";
import { TMSWayBill } from "../../../entity/express/tms/tmsWayBill";
import { TMSWayBillReceive } from "../../../entity/express/tms/tmsWayBillReceive";
import { TMSWayBillList } from "../../../entity/express/tms/tmsWayBillList";
 
/**
 * 基础信息 - 口岸
 */
export default class PortController extends BaseController {
  //#region 导入excel importExel
  /// <summary>
  /// 导入Excel
  /// </summary>
  /// <returns></returns>
  @Post()
  public async importExel() {
    setTimeout(async () => {
      await this.importWork();
    }, 0);
 
    this.info.result = true;
    this.ctx.body = this.info;
  }
  public async importWork() {
    let { ctx } = this;
    let body = ctx.request.body;
    let redis = ctx.app.redis.clients.get("common"); // 将消息放入redis缓存
    let fileUrl = body.url;
    let userInfo = await ctx.helper.userInfo();
    let provinceCityInfo = null;
    let base_ProductInfo = null;
    redis.expire(body.key, 5 * 60);
    if (!body.key) {
      this.setMsg(body.key, "上传key不存在");
      return;
    }
    let msg = "";
    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 验证数据正确性
      if (!dataList.length) {
        redis.rpush(body.key, "没有可导入的数据");
        return;
      }
      this.isMsgError = false;
      let msgList = [];
      let i = 0;
      // let index = 0;
      for (let item of dataList) {
        // let _index = index + 1;
        i++;
        this.setMsg(`${i}、开始验证...`);
        let consigneeMobile = item["*收货人手机号码"];
        if (!item["*订单号"]) {
          this.setMsg(`${i}、第${i + 1}运单号不能为空`, "red");
        }
        if (!item["*收货人"]) {
          this.setMsg(`${i}、第${i + 1}收货人不能为空`, "red");
        }
        if (!item["*省"]) {
          this.setMsg(`${i}、第${i + 1}省不能为空`, "red");
        } else {
          provinceCityInfo = await this.dbRead.findOne(BaseCity, {
            cityName: item["*省"],
            parentId: 0
          });
          if (!provinceCityInfo) {
            this.setMsg(`${i}、第${i + 1}省无法识别`, "red");
          }
        }
        // var provinvce = item["*省"] + item["*市"] + item["*区"];
        // if (!item["*收货人详细地址"].startsWith(provinvce)) {
        //   if (msg) msg += ",";
        //   msg += item["*订单号"] + "省市区和地址开头的省市区不匹配;";
        // }
        if (!item["*市"]) {
          this.setMsg(`${i}、第${i + 1}市不能为空`, "red");
        } else {
          if (provinceCityInfo) {
            let cityInfo = await this.dbRead.findOne(BaseCity, {
              cityName: item["*市"],
              parentId: provinceCityInfo.city_Id
            });
            if (!cityInfo) {
              this.setMsg(`${i}、第${i + 1}下未找到市`, "red");
            }
          }
        }
        if (!["*区"]) {
          this.setMsg(`${i}、第${i + 1}区不能为空`, "red");
        }
        if (!item["*收货人详细地址"]) {
          this.setMsg(`${i}、第${i + 1}收货人详细地址不能为空`, "red");
        }
        if (!item["*收货人手机号码"]) {
          this.setMsg(`${i}、第${i + 1}收货人手机号码不能为空`, "red");
        } else {
          let strPatern = /^1\d{10}$/gi;
          var re = new RegExp(strPatern);
          var strPatern2 = /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/;
          var st = new RegExp(strPatern2);
          if (!re.test(consigneeMobile) && !st.test(consigneeMobile)) {
            this.setMsg(`${i}、第${i + 1}电话格式不正确`, "red");
          }
        }
        if (!item["*包裹毛重"]) {
          this.setMsg(`${i}、第${i + 1}收包裹毛重不能为空`, "red");
        }
        if (item["是否仓配"]) {
          item["运单类型"] = item["是否仓配"] == "Y" ? "仓配" : "直邮";
        }
        if (!item["*物品名称"]) {
          this.setMsg(`${i}、第${i + 1}物品名称不能为空`, "red");
        }
        if (!item["*物品条形码"]) {
          this.setMsg(`${i}、第${i + 1}物品条形码不能为空`, "red");
        }
        if (item["客户订单号"]) {
          let khorder = await this.dbRead.findOne(TMSWayBill, {
            customerOrderNo: "" + item["客户订单号"]
          });
          if (khorder) {
            this.setMsg(`${i}、第${i + 1}客户订单号不能重复`, "red");
          }
        }
        if (!item["*物品数量"]) {
          this.setMsg(`${i}、第${i + 1}物品数量不能为空`, "red");
        }
        let data = await this.dbRead.findOne(TMSWayBill, {
          wayBillCode: "" + item["*订单号"]
        });
        if (data) {
          this.setMsg(i + `、运单[${item["*订单号"]}]系统已经存在,不允许重复录入`, "red");
        }
        let receiveInfo = await this.dbRead.findOne(TMSWayBillReceive, {
          wayBillCode: "" + item["*订单号"]
        });
        if (receiveInfo && receiveInfo.consignor_Id != userInfo.consignor_Id && receiveInfo.consignor_Id != 0) {
          this.setMsg(`${i}、第${i + 1}运单揽收货主名称和上传货主名称不一致`, "red");
        }
        //身份证如果填写必须为18位
        if (item["收货人身份证号码"] && item["收货人身份证号码"].toString().length != 18) {
          this.setMsg(`${i}、第${i + 1}身份证信息为18位`, "red");
        }
        base_ProductInfo = await this.dbRead.findOne(BaseProductInfo, {
          userProduct_Id: userInfo.userProduct_Id,
          productModel: "" + item["*物品条形码"]
        });
        if (!base_ProductInfo) {
          this.setMsg(`${i}、第${i + 1}未找到该条形码的物料,该物料是否审核成功`, "red");
        }
      }
      if (this.isMsgError) {
        this.setMsg("-1");
        return;
      }
      //  else {
      //   this.info.result = true;
      // }
 
      // if (this.info.result == true) {
      msgList = msgList.filter(msg => msg);
 
      if (msgList.length) {
        this.info.result = false;
        this.info.msg = msgList.join("");
        return;
      }
 
      // 分组
      let groupList = dataList.reduce((all: Array<any>, next) => (all.some(item => item["*订单号"] == next["*订单号"]) ? all : [...all, next]), []);
 
      //存在的运单号
      var existBillCodes = groupList.map(item => item.wayBillCode);
      // 运单号分组
      let index = 0;
      for (let wayBillItem of groupList) {
        index += 1;
        if (wayBillItem["运单类型"] == null) {
          wayBillItem["运单类型"] = "直邮";
        }
 
        //查询运单号是否已揽收
        var collectStatus = "";
        let receiveInfo = await this.dbRead.findOne(TMSWayBillReceive, {
          wayBillCode: "" + wayBillItem["*订单号"]
        });
        if (receiveInfo && receiveInfo.collectStatus == "已揽收") {
          collectStatus = receiveInfo.collectStatus;
        }
 
        //处理主表
        let wayBillInfo = new TMSWayBill();
        wayBillInfo.consignorName = this.body.consignorName;
        wayBillInfo.consignorCode = this.body.consignorCode;
        wayBillInfo.consignor_Id = this.body.consignor_Id;
        //wayBillCode = BaseDataHelper.GetCodeRegular(499);
        wayBillInfo.wayBillCode = wayBillItem["*订单号"].toString();
        wayBillInfo.makeWay = "OMS导入";
        wayBillInfo.consigneeName = wayBillItem["*收货人"];
        wayBillInfo.provinceName = wayBillItem["*省"];
        wayBillInfo.province_Id = wayBillItem["省ID"];
        // wayBillInfo.orderType = wayBillItem["是否仓配"] == "Y" ? "仓配" : "直邮"; wayBillItem["运单类型"]
        wayBillInfo.orderType = wayBillItem["运单类型"];
        wayBillInfo.cityName = wayBillItem["*市"];
        wayBillInfo.city_Id = wayBillItem["市ID"];
        wayBillInfo.regionName = wayBillItem["*区"];
        wayBillInfo.region_Id = wayBillItem["区ID"];
        wayBillInfo.consigneeAddress = wayBillItem["*收货人详细地址"];
        wayBillInfo.consigneePostCode = wayBillItem["收货人邮编"];
        wayBillInfo.consigneeMobile = wayBillItem["*收货人手机号码"];
        wayBillInfo.consigneeIdcard = wayBillItem["收货人身份证号码"];
        wayBillInfo.isStoreMate = wayBillItem["是否仓配"] == "Y" ? 1 : 0;
        wayBillInfo.remark = wayBillItem["备注信息"];
        wayBillInfo.billingName = wayBillItem["发货人姓名"];
        wayBillInfo.billingMobile = wayBillItem["发货人电话"];
        wayBillInfo.billingAddress = wayBillItem["发货人详细地址"];
        wayBillInfo.customerOrderNo = wayBillItem["客户订单号"];
        wayBillInfo.expressCorp_Id = this.body.expressCorp_Id;
        wayBillInfo.expressCorpName = this.body.expressCorpName;
        wayBillInfo.port_Id = this.body.port_Id;
        wayBillInfo.portName = this.body.portName;
        wayBillInfo.orderStatus = "新建";
        wayBillInfo.collectStatus = collectStatus;
        wayBillInfo.storageName = this.body.storageName;
        wayBillInfo.storage_Id = this.body.storage_Id;
        wayBillInfo.createDate = new Date();
        await this.setAccountInfo(wayBillInfo);
 
        // 获得当前运单下明细
        var billDetails = dataList.filter(w => w["*订单号"] == wayBillItem["*订单号"]);
        // 主表求和字段计算
        let total: any = billDetails.reduce(
          (totalItem: any, currItem) => {
            totalItem.totalQuantityOrder += parseFloat(currItem["*物品数量"]);
            totalItem.grandTotal = +parseFloat(currItem["*物品数量"]) * parseFloat(base_ProductInfo.salePrice);
 
            return totalItem;
          },
          { totalQuantityOrder: 0, grandTotal: 0 }
        );
 
        wayBillInfo.grossWeight = wayBillItem["*包裹毛重"];
        wayBillInfo.totalQuantityOrder = total.totalQuantityOrder;
        wayBillInfo.grandTotal = total.grandTotal;
 
        // 揽收身份证不为空,以揽收为准
        if (receiveInfo && receiveInfo.consigneeName && receiveInfo.consigneeIdcard) {
          wayBillInfo.consigneeName = receiveInfo.consigneeName;
          wayBillInfo.consigneeIdcard = receiveInfo.consigneeIdcard;
        }
 
        // 保存
        // await this.dbWrite.save(TMSWayBill, wayBillInfo);
        await this.dbWrite.insert(TMSWayBill, wayBillInfo);
        this.ctx.logger.info(wayBillInfo.wayBillCode + " 主表导入成功");
 
        let wayBill_Id = await this.dbRead.findOne(TMSWayBill, {
          select: ["wayBill_Id"],
          where: {
            wayBillCode: wayBillInfo.wayBillCode
          }
        });
 
        if (!wayBill_Id) {
          this.ctx.logger.info(wayBillInfo.wayBillCode + " 导入新增后查询结果是空的");
        } else {
          if (wayBillInfo.wayBill_Id != wayBill_Id.wayBill_Id) {
            this.ctx.logger.info(wayBillInfo.wayBillCode + " 保存ID错乱" + wayBillInfo.wayBill_Id + ", 实际为:" + wayBill_Id);
          } else {
            this.ctx.logger.info(wayBillInfo.wayBillCode + " 保存ID" + wayBillInfo.wayBill_Id + ", 实际为:" + wayBill_Id);
          }
        }
 
        for (let item of billDetails) {
          //添加到TMS_WayBillList表
          var prodInfo = await this.dbRead.findOne(BaseProductInfo, {
            productModel: "" + item["*物品条形码"]
          });
          let listInfo = new TMSWayBillList();
          (listInfo.wayBill_Id = wayBillInfo.wayBill_Id),
            (listInfo.product_Id = prodInfo.product_Id),
            (listInfo.productName = prodInfo.productName),
            (listInfo.productCode = prodInfo.productCode),
            (listInfo.productModel = prodInfo.productModel),
            (listInfo.productSpec = prodInfo.productSpec),
            (listInfo.quantityOrder = item["*物品数量"]),
            (listInfo.smallUnit = prodInfo.smallUnit),
            (listInfo.salePrice = prodInfo.salePrice != null ? prodInfo.salePrice : 0),
            (listInfo.rowTotal = item["*物品数量"] * (prodInfo.salePrice != null ? prodInfo.salePrice : 0));
 
          // TMS_WayBillListRepository.Instance.Add(listInfo);
          await this.dbWrite.insert(TMSWayBillList, listInfo);
          //  msg += "导入成功";
 
          // this.setMsg(index + `物品条形码[${prodInfo.productModel}]导入成功`);
          this.ctx.logger.info(wayBillInfo.wayBillCode + ", " + prodInfo.productModel + " 明细导入成功");
 
          listInfo.creator = "批量导入";
          try {
            //将数据保存至MongoDB
            let db = this.app.mongodb;
            let collection = db.collection("wayBillImport");
            //将数据保存至MongoDB
            await collection.insert(listInfo);
          } catch (ex) {
            this.ctx.logger.info("明细导入将数据保存至MongoDB错误:" + ex.message);
          }
        }
        msg = "第" + index + `行,订单[${wayBillItem["*订单号"]}]导入成功`;
        this.setMsg(msg, "blue");
        //添加运单追踪记录
        await this.ctx.service.tms.wayBillHelper.setStatusHistory(wayBillInfo, "导入", "导入新建");
      }
 
      this.info.result = true;
      if (existBillCodes.length >= 2) {
        msg = ",<font color='red'>其中【" + existBillCodes.join(",") + "】已经存在未执行重复导入</font>";
      }
      // this.info.msg = "导入成功!";
      // } else {
      //   this.info.msg = msg;
      //   this.info.result = false;
      // }
    } catch (ex) {
      let msg = "出现异常:" + ex.message;
      this.info.result = false;
      this.info.msg = msg;
    }
    this.setMsg("-1");
    // this.ctx.body = this.info;
  }
 
  //#endregion
}