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
import BaseService from "./baseService";
import { BaseProductInfo } from "../entity/basicInfo/base/baseProductInfo";
import { TMSWayBill } from "../entity/express/tms/tmsWayBill";
import { TMSIdCard } from "../entity/express/tms/tmsIdCard";
import moment = require("moment");
import { TMSWayBillList } from "../entity/express/tms/tmsWayBillList";
 
/**
 * 作业任务服务
 */
export default class TaskService extends BaseService {
  //#region redisInitProduct 初始化物料信息
  /**
   * redisInitProduct 初始化物料信息
   */
  public async redisInitProduct() {
    let { ctx } = this;
    let redis = ctx.app.redis.clients.get("product");
    var clear = ctx.request.query.clear;
    //初始化Redis
    if (clear == "1") {
      await redis.flushdb();
      clear = "全部清除缓存并重新缓存";
    } else {
      clear = "只追加缓存";
    }
 
    // 更新点击量
    var sql = `UPDATE dbo.Base_ProductInfo SET ClickCount=(SELECT COUNT(1) FROM dbo.TMS_WayBillList 
                WHERE ProductCode=dbo.Base_ProductInfo.ProductCode)
      `;
    await this.dbWrite.query(sql);
    var dataList = await this.dbWrite.find(BaseProductInfo, {
      select: [
        "product_Id",
        "productCode",
        "productModel",
        "productName",
        "consignor_Id",
        "consignorCode",
        "consignorName",
        "brand_Id",
        "brandName",
        "type_Id",
        "typeName",
        "productSpec",
        "weight",
        "netWeight",
        "salePrice",
        "smallUnit",
        "clickCount",
        "relationCode2",
        "relationCode3",
        "relationCode4"
      ]
    });
    for (var item of dataList) {
      item.clickCount = parseInt("" + item.clickCount) || 0;
      let data = JSON.stringify(item);
      redis.set(item.productCode.toLocaleLowerCase(), data);
      redis.set(item.productModel.toLocaleLowerCase(), data);
      redis.set(item.productName.toLocaleLowerCase(), data);
      if (item.relationCode2) {
        redis.set(item.relationCode2.toLocaleLowerCase(), data);
      }
      if (item.relationCode3) {
        redis.set(item.relationCode3.toLocaleLowerCase(), data);
      }
      if (item.relationCode4) {
        redis.set(item.relationCode4.toLocaleLowerCase(), data);
      }
    }
 
    this.info.result = true;
    this.info.msg = "执行完成," + clear;
    return this.info;
  }
  //#endregion
 
  //#region 运单收货人电话更新到身份证库中
  /**
   * 运单收货人电话更新到身份证库中
   */
  public async updateIdCardTel() {
    let log = this.ctx.getLogger("taskLogger");
    log.info(`更新手机号到身份证库开始`);
    try {
      let where = `exists
      (
        Select 1 from TMS_WayBillReceive Where WayBillCode=t.WayBillCode And ConsigneeIdcard IS NOT NULL AND CollectStatus='已揽收' And 
        CreateDate>=DATEADD(DAY, -5, GETDATE())
      )`;
      //where = "wayBillCode='2002505096'";
      where = `
        NOT EXISTS(SELECT 1 FROM dbo.TMS_IdCard C WHERE C.Mobile=t.ConsigneeMobile OR C.Mobile2=t.ConsigneeMobile 
        OR C.Mobile3=t.ConsigneeMobile)
        and t.ConsigneeMobile IS NOT NULL
        and ConsigneeIdcard is NOT NULL
      `;
      let wayBillList = await this.dbRead
        .createQueryBuilder(TMSWayBill, "t")
        .select(["wayBillCode", "orderStatus", "consigneeName", "consigneeMobile", "consigneeIdcard"])
        .where(where)
        .getRawMany();
      for (let wayBillInfo of wayBillList) {
        //#region 身份证处理
        let _idCard = await this.dbRead.findOne(TMSIdCard, {
          idCardCode: wayBillInfo.consigneeIdcard
        });
        let mobile = wayBillInfo.consigneeMobile;
        log.info(`${wayBillInfo.wayBillCode}更新手机号${mobile}到身份证库${wayBillInfo.consigneeIdcard}中开始`);
        if (_idCard) {
          // 手机号已存在不再更新
          if (_idCard.mobile === mobile || _idCard.mobile2 === mobile || _idCard.mobile3 === mobile) {
            log.info(`${wayBillInfo.wayBillCode}更新手机号${mobile}到身份证库${wayBillInfo.consigneeIdcard}中已存在`);
            continue;
          }
 
          if (!_idCard.mobile) {
            // 第一个手机为空先更新到第一个手机号
            _idCard.mobile = mobile;
            log.info(`${wayBillInfo.wayBillCode}更新手机号${mobile}到身份证库${wayBillInfo.consigneeIdcard}中第1个字段`);
          } else if (!_idCard.mobile2) {
            // 第2个手机为空更新到第2个手机号
            _idCard.mobile2 = mobile;
            log.info(`${wayBillInfo.wayBillCode}更新手机号${mobile}到身份证库${wayBillInfo.consigneeIdcard}中第2个字段`);
          } else if (!_idCard.mobile3 != mobile) {
            // 第3个手机为空更新到第3个手机号
            _idCard.mobile3 = mobile;
            log.info(`${wayBillInfo.wayBillCode}更新手机号${mobile}到身份证库${wayBillInfo.consigneeIdcard}中第3个字段`);
          }
          await this.dbWrite.save(_idCard);
        }
      }
      let msg = `更新手机号到身份证库结束`;
      log.info(msg);
      this.info.result = true;
      this.info.msg = msg;
      //#endregion
    } catch (error) {
      let msg = `更新手机号到身份证库失败:${error.message}`;
      this.info.result = false;
      this.info.msg = msg;
      log.info(msg);
    }
 
    return this.info;
  }
  //#endregion
 
  //#region checkWayBill
  public async checkWayBill() {
    let startDate = new Date();
    let isExistModify = false;
    let db = this.app.mongodb;
    let collWayBill = db.collection("tmsWayBill");
    let collWayBillCheck = db.collection("tmsWayBillCheck");
 
    //#region 校验订单,将不正确的订单明细矫正过来
    try {
      let currDate = moment(new Date()).add("M", -5).format("YYYY-MM-DD HH:mm:ss");
      let wayBillList = await collWayBill
        .find({
          state: "审核成功",
          finished: null,
          createDate: { $lt: currDate } // 查找5分钟前的数据
        })
        .limit(50)
        .toArray();
      for (let wayInfo of wayBillList) {
        let msgList = [];
        let wayBillCode = wayInfo.wayBillUploadInfo.wayBillCode;
        if (!wayBillCode) {
          collWayBill.update(
            {
              _id: wayInfo._id
            },
            {
              $set: {
                finished: "已验证,单号不存在"
              }
            }
          );
          continue;
        }
        let _wayBillInfo = await this.dbRead.findOne(TMSWayBill, {
          wayBillCode: wayBillCode
        });
        if (_wayBillInfo != null) {
          let _detailList = await this.dbRead.find(TMSWayBillList, {
            wayBill_Id: _wayBillInfo.wayBill_Id
          });
 
          // 明细不存在的
          for (let a of _detailList) {
            let exist = wayInfo.wayBillDetails.some(y => y.productCode == a.productCode && y.quantityOrder == a.quantityOrder);
            if (!exist) {
              msgList.push(wayBillCode + ":多余明细,条码" + a.productModel);
              this.dbWrite.delete(TMSWayBillList, a.wayBillList_Id);
              isExistModify = true;
            }
          }
 
          // 未增加的
          for (let a of wayInfo.wayBillDetails) {
            if (!a.productCode) {
              msgList.push(wayBillCode + ":新增明细,条码不存在");
              continue;
            }
 
            let exist = _detailList.some(y => y.productCode == a.productCode && y.quantityOrder == a.quantityOrder);
            if (!exist) {
              //查询物料信息
              let dataInfo = await this.dbRead.findOne(BaseProductInfo, {
                where: [
                  {
                    productCode: a.productCode
                  },
                  { productModel: a.productCode }
                ]
              });
 
              //添加到TMS_WayBillList表
              let listInfo = new TMSWayBillList();
              listInfo.wayBill_Id = _wayBillInfo.wayBill_Id;
              listInfo.product_Id = dataInfo.product_Id;
              listInfo.productName = dataInfo.productName;
              listInfo.productCode = dataInfo.productCode;
              listInfo.productModel = dataInfo.productModel;
              listInfo.productSpec = dataInfo.productSpec;
              listInfo.quantityOrder = a.quantityOrder;
              listInfo.smallUnit = a.smallUnit;
              listInfo.salePrice = a.salePrice || 0;
              listInfo.rowTotal = a.quantityOrder * (a.salePrice || 0);
              listInfo.weight = a.weight;
              listInfo.grossWeight = a.weight + 0.1; //以前是加100
              await this.dbWrite.insert(TMSWayBillList, listInfo);
              msgList.push(wayBillCode + ":新增明细,条码" + dataInfo.productModel);
 
              isExistModify = true;
            }
          }
 
          if (isExistModify) {
            let sql = `UPDATE dbo.TMS_WayBill 
                        SET TotalQuantityOrder=(SELECT SUM(L.quantityOrder) FROM dbo.TMS_WayBillList L WHERE L.wayBill_Id=TMS_WayBill.wayBill_Id)
            WHERE TMS_WayBill.wayBill_Id=${_wayBillInfo.wayBill_Id}`;
            await this.dbWrite.query(sql);
            msgList.push(wayBillCode + ":重新修改数量");
          }
        } else {
          msgList.push(wayBillCode + ":在系统中不存在");
        }
 
        collWayBill.update(
          {
            _id: wayInfo._id
          },
          {
            $set: {
              finished: "已验证"
            }
          }
        );
 
        // 记录日志
        if (msgList.length) {
          await collWayBillCheck.insertOne({
            wayBillCode: wayBillCode,
            createDate: new Date(),
            msgList: msgList
          });
        }
      }
      let seconds = moment(new Date()).diff(startDate, "seconds");
      let msg = "重新校验运单共执行:" + wayBillList.length + ",执行时长(s):" + seconds;
      this.info.result = true;
      this.info.msg = msg;
    } catch (ex) {
      let msg = "重新校验运单共执行失败:" + ex.message;
      this.info.result = false;
      this.info.msg = msg;
    }
    //#endregion
    return this.info;
  }
  //#endregion
}