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
//#region import
import { default as BaseController } from "../baseController";
import { Post } from "egg-shell-decorators";
import { SaleOrderPlan } from "../../entity/outbound/sale/saleOrderPlan";
// import { SaleOrderPlanDetail } from '../../entity/outbound/sale/saleOrderPlanDetail';
import * as path from "path";
import * as XLSX from "xlsx";
import moment = require("moment");
import { BaseStorage } from "../../entity/basicInfo/base/baseStorage";
import { BaseConsignor } from "../../entity/basicInfo/consignor/baseConsignor";
import { BaseProductInfo } from "../../entity/basicInfo/base/baseProductInfo";
import { In } from "typeorm";
import { FeeBaseOneCharge } from "../../entity/finance/base/feeBaseOneCharge";
import { SaleOrderPlanDetail } from "../../entity/outbound/sale/saleOrderPlanDetail";
import { SaleOrder } from "../../entity/outbound/sale/saleOrder";
import { SaleOrderList } from "../../entity/outbound/sale/saleOrderList";
// import { SysParamValue } from "../../entity/sys/core/sysParamValue";
// import { BaseExpressCorp } from "../../entity/basicInfo/base/baseExpressCorp";
//#endregion
 
/**
 * 出库 - 出库计划
 */
export default class OrderPlanController extends BaseController {
  //#region 转入到出库单
  @Post()
  public async toSaleOrder() {
    let { ctx } = this;
    let body = ctx.request.body;
    let userInfo = await ctx.helper.userInfo();
    let orderPlan_Id = body.orderPlan_Id;
 
    try {
      let orderPlanInfo = await this.dbRead.findOne(SaleOrderPlan, orderPlan_Id);
      //如果已转到出库单则跳出
      let count = await this.dbRead.count(SaleOrder, {
        userProduct_Id: userInfo.userProduct_Id,
        sourceId: "" + orderPlan_Id,
        storeOrderCode: orderPlanInfo.orderPlanCode
      });
      if (count > 0) {
        this.info.msg = "已转到出库单,不允许重复操作!";
        this.info.result = false;
        ctx.body = this.info;
        return;
      }
 
      // 根据主表ID获取明细集合
      let detailist = await this.dbRead.find(SaleOrderPlanDetail, {
        orderPlan_Id: orderPlan_Id
      });
      let groupList: Array<SaleOrderPlanDetail> = detailist.reduce(
        (all: Array<any>, next) => (all.some(item => item.storage_Id == next.storage_Id) ? all : [...all, next]),
        []
      );
      // 查询快递信息
      // let sysInfo = await this.dbRead.findOne(SysParamValue, {
      //   value02: "erp_expressCorp_Id",
      //   userProduct_Id: userInfo.userProduct_Id
      // });
      // if (!sysInfo) {
      //   this.info.result = false;
      //   this.info.msg = "请在参数设置里面中(基础参数设置 - ERP接口参数)设置默认快递公司";
      //   this.ctx.body = this.info;
      //   return;
      // }
      // let expressCorp_Id = parseInt(sysInfo.value03);
      // let exInfo = await this.dbRead.findOne(BaseExpressCorp, {
      //   expressCorp_Id: expressCorp_Id
      // });
      for (let item of groupList) {
        // 获取默认收费项
        let type = "出库单";
        let where =
          "userProduct_Id=:userProduct_Id and storage_Id=:storage_Id and consignor_Id=:consignor_Id and isDefault=1 and associatedTasks like :associatedTasks";
        let oneChargeList = await this.dbRead
          .createQueryBuilder(FeeBaseOneCharge, "t")
          .where(where, {
            userProduct_Id: userInfo.userProduct_Id,
            storage_Id: item.storage_Id,
            consignor_Id: orderPlanInfo.consignor_Id,
            isDefault: 1,
            associatedTasks: "%" + type + "%"
          })
          .take(10)
          .getMany();
        let feeItem_Ids = oneChargeList.map(item => item.feeItem_Id).join("/"); //设置默认收费项
 
        let orderCode = await ctx.service.common.getCodeRegular(112); //得到出库单自动编号
 
        let orderInfo = new SaleOrder();
        orderInfo = Object.assign(orderInfo, orderPlanInfo);
        orderInfo.orderCode = orderCode;
        orderInfo.orderType = "计划单转入";
        orderInfo.storeOrderCode = orderPlanInfo.orderPlanCode;
        orderInfo.storage_Id = item.storage_Id;
        orderInfo.storageName = item.storageName;
        orderInfo.sortingStatus = 1;
        orderInfo.statusID = 1;
        orderInfo.statusText = "待审核";
        orderInfo.auditing = 1;
        orderInfo.auditDate = null;
        orderInfo.auditor = null;
        orderInfo.auditRemark = null;
        orderInfo.telephone = orderPlanInfo.tel;
        orderInfo.postCode = orderPlanInfo.zip;
        orderInfo.enable = 1;
        orderInfo.sourceId = "" + orderPlanInfo.orderPlan_Id;
        orderInfo.feeItem_Ids = feeItem_Ids;
        // orderInfo.expressCorpType = exInfo.expressCorpType; // 快递类别
        //orderInfo.expressCorp_Id = exInfo.expressCorp_Id; // 快递ID
        //orderInfo.expressCorpName = exInfo.expressCorpName; // 快递名称
        // orderInfo.expressCode = exInfo.expressCorpCode; // 快递单号
        orderInfo.expandFields = orderPlanInfo.expandFields; // 扩展字段
        await this.setAccountInfo(orderInfo);
 
        let details = detailist.filter(d => d.storage_Id == item.storage_Id);
        // 重量、数量求和
        let total: any = details.reduce(
          (totalItem: any, currItem) => {
            totalItem.totalQuantityOrder += currItem.quantity;
            totalItem.totalWeight += currItem.totalWeight;
            totalItem.grandTotal += currItem.saleMoney;
            return totalItem;
          },
          { totalQuantityOrder: 0, totalWeight: 0, grandTotal: 0 }
        );
        orderInfo.totalQuantityOrder = total.totalQuantityOrder;
        orderInfo.totalWeight = total.totalWeight;
        orderInfo.grandTotal = total.grandTotal;
        await this.dbWrite.save(orderInfo);
        // 循环添加出库订单明细
        for (let detail of details) {
          let detailInfo = new SaleOrderList();
          detailInfo = Object.assign(detailInfo, detail);
          detailInfo.order_Id = orderInfo.order_Id;
          detailInfo.sortingStatus = 1;
          detailInfo.quantityOrder = detail.quantity;
          detailInfo.discountRate = 1;
          detailInfo.enable = 1;
          detailInfo.weight = detail.weight;
          detailInfo.totalWeight = detail.totalWeight;
          // detailInfo.originPlace = detail.originPlace;
          detailInfo.positionName = detail.positionName;
          detailInfo.singleSignCode = detail.singleSignCode;
          detailInfo.produceDate = detail.produceDate;
          detailInfo.batchNumber = detail.batchNumber;
          detailInfo.expandFields = detail.expandFields; // 扩展字段
          await this.setAccountInfo(detailInfo);
          await this.dbWrite.save(detailInfo);
        }
      }
 
      orderPlanInfo.statusID = 3;
      orderPlanInfo.statusText = "已转出库单";
      await this.dbWrite.save(orderPlanInfo);
 
      this.info.msg = "转入到出库单成功!";
      this.info.result = true;
    } catch (error) {
      this.info.result = false;
      this.info.msg = error.message;
    }
    ctx.body = this.info;
  }
  //#endregion
 
  //#region 出库单数据导入
  @Post()
  public async importExcel() {
    setTimeout(async () => {
      await this.importExcelWork();
    }, 0);
 
    this.info.result = true;
    this.ctx.body = this.info;
  }
 
  private async importExcelWork() {
    let { ctx } = this;
    let body = ctx.request.body;
    let startDate = new Date();
    let fileUrl = body.fileUrl;
    let userInfo = await ctx.helper.userInfo();
    let storage = null;
    let consignor = null;
    let productlist = null;
    if (!fileUrl) {
      this.setMsg(`上传文件不存在`, "red");
      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格式
      this.info.result = true;
      if (!dataList.length) {
        this.setMsg(`没有可导入的数据`, "red");
        return;
      }
      // 省
      // let provinceCityInfo = null;
      // let cityInfo = null;
      // let parentInfo = null;
 
      // 仓库
      storage = await this.dbRead.findOne(BaseStorage, {
        userProduct_Id: userInfo.userProduct_Id,
        storageName: "立体库"
      });
 
      // 全部货主信息
      consignor = await this.dbRead.find(BaseConsignor, {
        userProduct_Id: userInfo.userProduct_Id,
        consignorName: "广州西门子"
      });
 
      // 所有物料
      productlist = await this.dbRead.find(BaseProductInfo, {
        userProduct_Id: userInfo.userProduct_Id,
        productCode: In(dataList.map(item => "" + item["物料编号"]))
      });
      // 省市区
      // let cityList = await this.dbRead.find(BaseCity);
 
      // 记录已经验证过的物料,不在读取数据库
      let index = 0;
      for (let item of dataList) {
        let _index = index + 1;
        if (_index % 20 === 1) {
          this.setMsg(`第${_index}行开始校验`, "blue");
        }
        if (!item["物料编号"] || !item["计划数量"]) {
          this.setMsg(`${_index}、[物料编号、计划数量]数据不能为空`, "red");
        }
        // let isstorage = storage.find(row => row.storageName == item["所属仓库"]);
        // if (!isstorage) {
        //   this.setMsg(`${_index}、${item["所属仓库"]}所属仓库不存在`, "red");
        // }
        // let isConsiglist = consignorList.find(row => row.consignorName == item["货主名称"]);
        // if (!isConsiglist) {
        //   this.setMsg(`${_index}、${item["货主名称"]}货主名称不存在`, "red");
        // }
        let isproductlist = productlist.find(row => row.productCode == item["物料编号"]);
        if (!isproductlist) {
          this.setMsg(`${_index}、${item["物料编号"]}物料编号不存在`, "red");
        }
        // if (item["省"]) {
        //   provinceCityInfo = cityList.find(row => row.cityName == item["省"] && row.parentId === 0);
        //   if (!provinceCityInfo) {
        //     this.setMsg(`${_index}、${item["省"]},省不存在`, "red");
        //   }
        // }
        // if (item["市"]) {
        //   cityInfo = cityList.find(row => row.cityName === item["市"] && row.parentId === provinceCityInfo.city_Id);
        //   if (!cityInfo) {
        //     this.setMsg(`${_index}、${item["市"]},市不存在`, "red");
        //   }
        // }
        // if (item["区"]) {
        //   parentInfo = cityList.find(row => row.cityName === item["区"] && row.parentId === cityInfo.city_Id);
        //   if (!parentInfo) {
        //     this.setMsg(`${_index}、${item["区"]},市不存在`, "red");
        //   }
        // }
        index++;
      }
 
      if (this.isMsgError) {
        this.setMsg(`导入数据有错误,请处理好重新导入`, "red");
        this.setMsg("-1");
        return;
      }
 
      // //订单分组
      // let orderGroupList = dataList.reduce(
      //   (all: Array<any>, next) => (all.some(item => item["货主名称"] == next["货主名称"]) ? all : [...all, next]),
      //   []
      // );
 
      let groupIndex = 0;
      for (let orderitem of dataList) {
        groupIndex++;
        let orderPlanCode = await ctx.service.common.getCodeRegular(302);
        if (groupIndex % 20 === 1) {
          this.setMsg(`${groupIndex}/${dataList.length}单、${orderPlanCode}订单开始导入`, "blue");
        }
        let orderPlanInfo = new SaleOrderPlan();
        // #region 创建主表数据
        let consign = consignor;
        orderPlanInfo.orderPlanCode = orderPlanCode;
        orderPlanInfo.consignorName = consign.consignorName;
        orderPlanInfo.consignor_Id = consign.consignor_Id;
        orderPlanInfo.consignorCode = consign.consignorCode;
        orderPlanInfo.statusText = "新建";
        orderPlanInfo.storage_Id = storage.storage_Id;
        orderPlanInfo.storageName = storage.storageName;
        orderPlanInfo.orderType = orderitem["单据类型"];
        if (orderitem["计划日期"]) {
          orderPlanInfo.chanceDate = moment(new Date(1900, 0, orderitem["计划日期"] - 1)).toDate();
        }
        orderPlanInfo.destinationName = orderitem["目的地"];
        orderPlanInfo.createID = userInfo.user_Id;
        orderPlanInfo.creator = userInfo.userTrueName;
        orderPlanInfo.createDate = new Date();
        await this.setAccountInfo(orderPlanInfo);
        await this.dbWrite.save(SaleOrderPlan, orderPlanInfo);
        //#region 明细数据
        let PlanDetail = new SaleOrderPlanDetail();
        let product = await this.dbRead.findOne(BaseProductInfo, {
          productCode: "" + orderitem["物料编号"],
          userProduct_Id: userInfo.userProduct_Id
        });
        PlanDetail.product_Id = product.product_Id;
        PlanDetail.productCode = product.productCode;
        PlanDetail.productModel = product.productModel;
        PlanDetail.productName = product.productName;
        PlanDetail.productSpec = product.productSpec;
        PlanDetail.smallUnit = product.smallUnit;
        // 单位重量  小计重量都为空
 
        PlanDetail.weight = product.weight;
        PlanDetail.totalWeight = orderitem["计划数量"] * product.weight;
        PlanDetail.storage_Id = storage.storage_Id;
        PlanDetail.storageName = storage.storageName;
        PlanDetail.quantity = orderitem["计划数量"];
        PlanDetail.createDate = new Date();
        PlanDetail.creator = userInfo.userTrueName;
        PlanDetail.createID = userInfo.user_Id;
        //建立关系
        PlanDetail.saleOrderPlan = orderPlanInfo;
        await this.dbWrite.insert(SaleOrderPlanDetail, PlanDetail);
        // 更新主表合计
        let sql = `
        update Sale_OrderPlan set
          totalWeight=(select sum(totalWeight) from Sale_OrderPlanDetail where orderPlan_Id=@0),
          totalQuantity=(select sum(quantity) from Sale_OrderPlanDetail where orderPlan_Id=@0)
        where orderPlan_Id=@0;
        `;
        await this.dbWrite.query(sql, [orderPlanInfo.orderPlan_Id]);
      }
      //#endregion
      let endDate = moment(Date.now());
      let totalSeconds = endDate.diff(startDate, "seconds");
      let msg = `导入完成,共耗时${totalSeconds}秒`;
      this.setMsg(msg);
    } catch (ex) {
      this.setMsg("出现异常:" + ex.message, "red");
    }
    this.setMsg("-1");
  }
  //#endregion
 
  //#region app修改数据
  @Post()
  public async appUpdateOrderPlan() {
    let { ctx } = this;
    let body = ctx.request.body;
    let data = body.data;
    try {
      let orderPlan_Id = data.orderPlan_Id;
      let planInfo = await this.dbRead.findOne(SaleOrderPlan, orderPlan_Id);
      if (!planInfo) {
        planInfo = new SaleOrderPlan(); // 新建单子
      }
      planInfo = Object.assign(planInfo, data);
      await this.setAccountInfo(planInfo);
      await this.dbWrite.save(planInfo);
 
      // 处理明细
      for (let detailInfo of data.Sale_OrderPlanDetail.rows) {
        let orderDetail_Id = detailInfo.orderDetail_Id;
        let detail = await this.dbRead.findOne(SaleOrderPlanDetail, orderDetail_Id);
        if (!detail) {
          detail = new SaleOrderPlanDetail(); // 新建明细
          detailInfo.orderPlan_Id = planInfo.orderPlan_Id;
        }
        detail = Object.assign(detail, detailInfo);
        await this.setAccountInfo(detail);
        await this.dbWrite.save(detail);
      }
      this.info.result = true;
      this.info.msg = "保存成功!";
 
      this.ctx.body = this.info;
      return;
    } catch (ex) {
      this.info.result = false;
      this.info.msg = "错误信息:" + ex.message;
    }
    this.ctx.body = this.info;
    return;
  }
  //#endregion
 
  //#region app新增数据
  @Post()
  public async addOrderPlan() {
    let { ctx } = this;
    let body = ctx.request.body;
    let data = body.data;
    let userInfo = await this.userInfo;
 
    try {
      // 记录数据到mongodb日志中
      let db = this.app.mongodb;
      let collection = db.collection("wms_app");
      let mongoData: any = {
        title: "小程序-新增出库计划",
        userInfo: userInfo,
        data: data,
        createDate: new Date()
      };
      await collection.insert(mongoData);
    } catch {}
 
    try {
      let planInfo = new SaleOrderPlan();
      planInfo.orderPlanCode = await ctx.service.common.getCodeRegular(302);
      planInfo.statusText = "新建";
      planInfo.chanceDate = data.chanceDate;
      planInfo.containerNo = data.containerNo;
      planInfo.totalQuantity = data.totalQuantity;
      planInfo.totalWeight = data.totalWeight;
      planInfo.totalMoney = data.totalMoney;
      planInfo.consignor_Id = data.consignor_Id;
      planInfo.consignorCode = data.consignorCode;
      planInfo.consignorName = data.consignorName;
      planInfo.client_Id = 0;
      planInfo.clientCode = "";
      planInfo.clientShortName = "";
      planInfo.user_Id = userInfo.user_Id;
      planInfo.userTrueName = userInfo.userTrueName;
      planInfo.source = "小程序申请";
      await this.setAccountInfo(planInfo);
      await this.dbWrite.insert(SaleOrderPlan, planInfo);
      // 处理明细
      for (let detailInfo of data.Sale_OrderPlanDetail.rows) {
        let detail = new SaleOrderPlanDetail(); // 新建明细
        detail.orderPlan_Id = planInfo.orderPlan_Id;
        detail.product_Id = detailInfo.product_Id;
        detail.productName = detailInfo.productName;
        detail.productCode = detailInfo.productCode;
        detail.productModel = detailInfo.productModel;
        detail.productSpec = detailInfo.productSpec;
        detail.quantity = Number(detailInfo.quantity);
        detail.salePrice = Number(detailInfo.salePrice);
        detail.saleMoney = Number(detailInfo.saleMoney);
        detail.weight = Number(detailInfo.weight);
        detail.totalWeight = Number(detailInfo.totalWeight);
        detail.storage_Id = detailInfo.storage_Id;
        detail.storageName = detailInfo.storageName;
        detail.validQuantity = detailInfo.validQuantity;
        await this.dbWrite.save(SaleOrderPlanDetail, detail);
      }
      this.info.result = true;
      this.info.msg = "保存成功!";
 
      this.ctx.body = this.info;
      return;
    } catch (ex) {
      this.info.result = false;
      this.info.msg = "错误信息:" + ex.message;
    }
    this.ctx.body = this.info;
    return;
  }
  //#endregion
 
  //#region app提交审核
  @Post()
  public async submitAuditing() {
    let { ctx } = this;
    let body = ctx.request.body;
    let orderPlan_Id = body.orderPlan_Id;
    let userInfo = await ctx.helper.userInfo();
    try {
      let planInfo = await this.dbRead.findOne(SaleOrderPlan, orderPlan_Id);
      if (planInfo.statusText !== "新建") {
        this.info.result = false;
        this.info.msg = "只有新建的单子才允许审核";
        return this.info;
      }
      await this.dbWrite.update(
        SaleOrderPlan,
        {
          orderPlan_Id: planInfo.orderPlan_Id,
          userProduct_Id: userInfo.userProduct_Id
        },
        {
          statusText: "审核成功",
          auditing: 2,
          auditor: userInfo.userTrueName,
          auditDate: new Date()
        }
      );
      this.info.result = true;
      this.info.msg = "审核成功!";
 
      this.ctx.body = this.info;
      return;
    } catch (ex) {
      this.info.result = false;
      this.info.msg = "错误信息:" + ex.message;
    }
    this.ctx.body = this.info;
    return;
  }
  //#endregion
}