服务端的TigerApi 框架,基于.NET6 2024 版本
Rodney Chen
2024-12-06 9719a7f0ccbb70e4e51a93cbe1733d1424c16f6d
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
using Rhea.Common;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Tiger.IBusiness;
using Tiger.Model;
 
namespace Tiger.Business.WMS.Transaction
{
    /// <summary>
    /// 来料入库清点事务
    /// </summary>
    public class InReceipt : WMSTransactionBase, IInReceipt
    {
        public IInReceipt Init(string id, string userCode, string apiHost, string orgCode)
        {
            TransID = id;
            UserCode = userCode;
            ApiHost = apiHost;
            OrgCode = orgCode;
            Logger.Console.Info($"Start {this.GetType().Name} Transaction[ID: {TransID}]");
            return this;
        }
 
        #region Propertys & Variables
 
        public string UserCode { get; set; }
        public static long UserId { get; set; }
        public string VenderCode { get; set; }
        public string SecondVenderCode { get; set; }
        public string WarehouseCode { get; set; }
        public string WarehouseName { get; set; }
        public string OrgCode { get; set; }
        public string CustomsNo { get; set; }
        public Inventory inv { get; set; }
        public List<ParameterReturn> suppliers { get; set; }
 
        #endregion Propertys & Variables
 
        #region Functions
 
        /// <summary>
        /// 扫描物料并复核,如果物料已经完成移库则货架上亮灯提醒储位
        /// </summary>
        public async Task<ApiAction> ScanItem(BaseInput input)
        {
            var action = new ApiAction();
            try
            {
                if (string.IsNullOrEmpty(input.SN))
                {
                    action.IsSuccessed = false;
                    action.LocaleMsg = Biz.L("WMS.InReceipt.ScanItem.SnEmptyFailure", input.SN);
                    return action;
                }
 
                input.AuthOption.OrgCode = input.AuthOption.OrgCode.IsNullOrEmpty() ? input.AuthOption.CurOrg : input.AuthOption.OrgCode;
 
                #region 报关单号判断
 
                if (input.AuthOption.OrgCode == "YTXC" && string.IsNullOrWhiteSpace(CustomsNo))
                {
                    if (string.IsNullOrWhiteSpace(input.SN))
                    {
                        action.IsSuccessed = false;
                        action.LocaleMsg = Biz.L($"盐田据点请扫描报关单号二维码!");
                        return action;
                    }
                    var customsNo = input.SN.Replace(",", ",").Trim();
                    if (customsNo.Split(",").Length != 2)
                    {
                        action.IsSuccessed = false;
                        action.LocaleMsg = Biz.L($"报关单号格式错误,请确认格式是否为【报关单号,核算清单号】!");
                        return action;
                    }
                    CustomsNo = input.SN;
                    action.Data = new IncomingMatStorage
                    {
                        sn = CustomsNo,
                        IsCustomsNo = true
                    };
                    action.IsSuccessed = true;
                    action.LocaleMsg = Biz.L($"报关单号二维码扫描成功");
                    return action;
                }
 
                #endregion 报关单号判断
 
                //解析条码
                Result<Inventory> result = WMS_ITEM_Biz.WmsItem.Get(input.SN, input.AuthOption, false);
                if (result.Flag != Result.Flags.Success)
                {
                    action.IsSuccessed = false;
                    action.LocaleMsg = result.LocaleMsg;
                    return action;
                }
                inv = result.Data;
 
                #region 判断当前条码对应的SRM状态
 
                var srmData = Biz.Db.Queryable<BIZ_SRM_DLVY_SN, BIZ_SRM_DLVY>((a, b) => new object[]
                {
                    JoinType.Inner,a.DELIVERY_NO == b.DELIVERY_NO
                }).Where((a, b) => a.SMALL_SN == inv.Barcode.SN || a.OUTER_SN == inv.Barcode.SN)
                .Select((a, b) => new { a.DELIVERY_NO, b.STATUS }).First();
 
                if (srmData != null && srmData?.STATUS == 4)
                {
                    action.IsSuccessed = false;
                    action.LocaleMsg = Biz.L($"当前条码:{input.SN}\t对应的单据:{srmData?.DELIVERY_NO}\t状态已作废,拒绝作废");
                    return action;
                }
 
                #endregion 判断当前条码对应的SRM状态
 
                //#region 来料清点增加有效期管控
 
                //var VALIDITY_DAYS = inv.ItemInfo?.VALIDITY_DAYS;// 有效期
                //var DepositDays = inv.ItemInfo?.DepositDays;// 预存期
 
                //var codes = string.Empty;
                //var code2s = string.Empty;
                //foreach (var item in inv.Items)
                //{
                //    if (VALIDITY_DAYS != 0 && DepositDays != 0)
                //    {
                //        if (item.PROD_DATE.AddDays(VALIDITY_DAYS.ToDouble()).AddDays(item.PostponeDays.ToDouble()) < DateTime.Now)
                //        {
                //            codes += item.SN + ",";
                //            item.REMARK = "有效期超期";
                //            item.IsAllowOverdue = "N";
                //        }
                //        if (VALIDITY_DAYS - (DateTime.Now - item.PROD_DATE).Days < DepositDays)
                //        {
                //            code2s += item.SN + ",";
                //            item.REMARK = string.IsNullOrWhiteSpace(item.REMARK)? "预存期超期" : item.REMARK + ",预存期超期";
                //            item.IsAllowOverdue = "N";
                //        }
                //    }
                //}
 
                //if (!string.IsNullOrWhiteSpace(codes) || !string.IsNullOrWhiteSpace(code2s))
                //{
                //    action.IsSuccessed = false;
                //    action.LocaleMsg = Biz.L($"物料{inv.ItemInfo?.ITEM_CODE},条码:{codes}\t超有效期 {VALIDITY_DAYS},或条码{code2s}\t超预存期{DepositDays}");
 
                //    var DB = Biz.DataSource["WMS57"].Client;
                //    var ids = inv.Items.Where(i => i.IsAllowOverdue == "N").Select(i => i.ID).Distinct().ToList();// 获取所有需要更新的数据ID
                //    //DB.Updateable<WMS_ITEM>(i => new WMS_ITEM() { IsAllowOverdue = "N" ,REMARK = }).Where(i => ids.Contains(i.ID)).ExecuteCommand();
                //    DB.Updateable(inv.Items).ExecuteCommand();
                //    return action;
                //}
 
                //#endregion 来料清点增加有效期管控
 
                if (string.IsNullOrEmpty(inv.ItemInfo?.ITEM_CODE))
                {
                    action.IsSuccessed = false;
                    action.LocaleMsg = Biz.L("WMS.InReceipt.ScanItem.NotFound", inv.ItemInfo?.ITEM_CODE);
                    return action;
                }
 
                if (!inv.isExists)
                {
                    action.IsSuccessed = false;
                    action.LocaleMsg = Biz.L("条码[{0}]不存在于系统中", inv.SN); //Biz.L("WMS.InReceipt.ScanItem.NotExist", inv.SN); //条码[{0}]不存在于系统中
                    return action;
                }
                if (inv.CurPkg.AUTH_ORG != input.AuthOption.CurOrg)
                {
                    action.IsSuccessed = false;
                    action.LocaleMsg = Biz.L($"条码据点[{inv.CurPkg.AUTH_ORG}]和当前登录的据点[{input.AuthOption.CurOrg}]不一样,请重新选择据点");
                    return action;
                }
                //验证条码是否已做过清点
                var nLogs = Biz.Db.Queryable<BIZ_ERP_RECEIPT_SN>().Where(t => inv.Items.Select(q => q.SN).Contains(t.SN) && t.STATUS >= WMS_ITEM.STATUSs.Counted.GetValue()).Any();
                if (nLogs)
                {
                    action.IsSuccessed = false;
                    action.LocaleMsg = Biz.L("条码已清点", inv.SN); //Biz.L("WMS.CustSupChk.ScanItem.BarcodeCounted", inv.SN);
                    return action;
                }
                //物料验证
                if (inv.ItemInfo.IsNullOrEmpty() || inv.ItemInfo.IS_ACTIVE == "N")
                {
                    action.IsSuccessed = false;
                    action.LocaleMsg = Biz.L("WMS.ProdMReq.ScanItem.ItemCodeNotExistsOrNotActive", inv.ItemInfo.ITEM_CODE.IsNullOrEmpty(inv.Barcode.ItemCode));
                    return action;
                }
                //var srmEntity = Biz.Db.Queryable<BIZ_SRM_DLVY_SN>().Where(t => t.SMALL_BARCODE == inv.SN || t.BIG_BARCODE == inv.SN || t.OUTER_BARCODE == inv.SN).ToList();
                //if (srmEntity == null)
                //{
                //    action.IsSuccessed = false;
                //    action.LocaleMsg = Biz.L("WMS.InReceipt.ScanItem.NotExist", inv.SN); //条码[{0}]不存在于系统中
                //    return action;
                //}
 
                OrgCode = input.AuthOption.CurOrg;
 
                var ponoList = inv.Items.Select(x => x.SOURCE_ORDER).Distinct().ToList();
                var poList = Biz.Db.Queryable<BIZ_ERP_PO>().Where(t => ponoList.Contains(t.BILLCODE.ToUpper())).Select(x => x.BILLCODE).Distinct().ToList();
                if (ponoList.Count() != poList.Count)
                {
                    action.IsSuccessed = false;
                    action.LocaleMsg = Biz.L("送货单对应的采购单不存在", string.Join(",", ponoList.Except(poList))); //Biz.L("WMS.InReceipt.ScanItem.PoNotExist", string.Join(",", ponoList.Except(poList))); //送货单对应的采购单不存在
                    return action;
                }
 
                var model = new BIZ_ERP_CUSTOMS()
                {
                    AUTH_ORG = input.AuthOption.CurOrg,
                    CREATE_USER = UserCode,
                    OrderNo = UserCode,
                    Barcodes = inv.SN,
                    CustomsNo = CustomsNo.Replace(",", ",").Trim().Split(',')[0],
                    AccountingNo = CustomsNo.Replace(",", ",").Trim().Split(',')[1],
                    CountsType = BIZ_ERP_CUSTOMS.CountsEnum.Incoming
                };
 
                //循环包装下所有最小包装条码,批量清点
                List<BIZ_ERP_RECEIPT_SN> snList = new();
                foreach (var item in inv.Items)
                {
                    var scanResult = new BIZ_ERP_RECEIPT_SN
                    {
                        ID = Guid.NewGuid().ToString(),
                        SN = item.SN,
                        BILLCODE = UserCode,
                        ITEM_CODE = item.ITEM_CODE,
                        SCANQTY = item.QTY,
                        DATECODE = item.PROD_DATE,
                        CARTON = item.CARTON_NO,
                        PALLET = item.PALLET_NO,
                        SUPPLIERCODE = item.SUPP_CODE,
                        UNIT = item.UNIT,
                        STATUS = WMS_ITEM.STATUSs.Counted.GetValue(),
                        AUTH_ORG = OrgCode,
                        DELIVERY_NO = item.TRANS_NO,  //送货单据
                        BILLLINE = item.TRANS_LINE,
                        META_SN = input.SN,
                        //CREATE_USER = UserCode
                    };
                    snList.Add(scanResult);
                }
 
                //保存到数据库
                var db = Business.Biz.Db;
                var dbTran = db.UseTran(() =>
                {
                    var x = db.Storageable(snList, UserCode)
                           .SplitUpdate(x => x.Any(t => t.GHOST_ROW == false))
                           .WhereColumns(t => new { t.SN })
                           .SplitInsert(t => true)
                           .ToStorage();
                    x.AsInsertable.ExecuteCommand();
 
                    if (model != null)
                    {
                        db.Insertable(model).ExecuteCommand();
                    }
                });
                if (!dbTran.IsSuccess)
                {
                    Logger.Default.Fatal(dbTran.ErrorException, "Database transaction save exception");
                    this.Close(!dbTran.IsSuccess);
                    throw dbTran.ErrorException;
                }
 
                action.Data = snList;
                action.LocaleMsg = Biz.L("WMS.InReceipt.ScanItem.CountSuccess", input.SN);
            }
            catch (Exception ex)
            {
                //取消当前操作
 
                action.CatchExceptionWithLog(ex, $"扫描物料[{input.SN}]复核异常");
                action.LocaleMsg = Biz.L("WMS.InReceipt.ScanItem.ScanException", input.SN);
            }
            return await Task.FromResult(action);
        }
 
        // <summary>
        /// 生成物料入库单据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ApiAction> SubmitInvBill()
        {
            var action = new ApiAction();
            bool isIQCOk = true;
            try
            {
                //获取当前用户所有已清点、未制单的条码数据
                var nScannedBarcodes = Biz.Db.Queryable<BIZ_ERP_RECEIPT_SN>().Where(t =>
                       t.STATUS == WMS_ITEM.STATUSs.Counted.GetValue()
                       && t.BILLCODE == UserCode
                       && t.AUTH_ORG == OrgCode).ToList();
                if (!nScannedBarcodes.Any())
                {
                    action.IsSuccessed = false;
                    action.LocaleMsg = Biz.L("没有可以提交的清点数据"); //Biz.L("WMS.InReceipt.ScanItem.NotDataToSubmit");  //$"没有可以提交的清点数据";
                    return action;
                }
 
                var sns = nScannedBarcodes.Select(i => i.SN).Distinct().ToList();
                var customsData = Biz.Db.Queryable<BIZ_ERP_CUSTOMS>().Where(i => sns.Contains(i.Barcodes.Substring(1))).First();
 
                // 查找送货单列表
                var dlvys = nScannedBarcodes.Select(x => x.DELIVERY_NO).Distinct().ToList();
                //所有送货单
                var srmDlvys = Biz.Db.Queryable<BIZ_SRM_DLVY>().Where(x => dlvys.Contains(x.DELIVERY_NO)).IncludesAllFirstLayer().ToList();
 
                //查询是否清点完成
                if (srmDlvys.Sum(s => s.SnList.Sum(q => q.QTY)) != nScannedBarcodes.Sum(s => s.SCANQTY))
                {
                    #region 获取单号明细
 
                    var orderList = new List<string>();
                    var srmDlvyCount = srmDlvys.Select(i => i.DELIVERY_NO).Distinct().ToList();
                    for (int i = 0; i < srmDlvyCount.Count(); i++)
                    {
                        var orderno = srmDlvyCount[i];
                        var srmCount = srmDlvys.Where(i => i.DELIVERY_NO == orderno).Sum(i => i.SnList.Sum(m => m.QTY));// 单号数量
                        var scanCount = nScannedBarcodes.Where(i => i.DELIVERY_NO == orderno).Sum(i => i.SCANQTY);
                        if (srmCount != scanCount)
                        {
                            orderList.Add(orderno);
                        }
                    }
 
                    #endregion 获取单号明细
 
                    action.IsSuccessed = false;
                    //action.LocaleMsg = Biz.L("清点数量不对");// Biz.L("WMS.InReceipt.ScanItem.CheckingDataToSubmit");  //$"清点数量不对";
                    action.LocaleMsg = Biz.L($"{string.Join(",", orderList)}该送货单未清点完成有送货单号");
                    return action;
                }
                // 查询条码清点表所有仓库代码
                //var nWarehouseCodes = nScannedBarcodes.Select(x => x.WarehouseCode).Distinct().ToList();
 
                ////新建单据
                //Result ruleResult = Cache.CodeRule["R001"].Generate("RE");
                //if (!ruleResult.IsSuccessed)
                //{
                //    throw new Exception(ruleResult.ExceptionMsg.Message);
                //}
                //var billcode = ruleResult.Data.ToString();
                //var nBillHeader = new BIZ_ERP_RECEIPT
                //{
                //    BILLCODE = billcode,
                //    BILLDATE = DateTime.Now.Date,
                //    //WAREHOUSECODE = WarehouseCode,
                //    STATUS = BIZ_ERP_RECEIPT.STATUSs.WORKING.GetValue(),
                //    //SUPPLIERCODE = nScannedBarcodes[0].SUPPLIERCODE,
                //    AUTH_ORG = OrgCode
                //};
 
                List<BIZ_ERP_RECEIPT_DTL> detailList = new List<BIZ_ERP_RECEIPT_DTL>();
                List<BIZ_ERP_IQC> iqcHeaders = new List<BIZ_ERP_IQC>();
                List<WMS_ITEM_HIS> ItemHistorys = new List<WMS_ITEM_HIS>();
                List<WMS_ITEM_PKG> ItemPkgs = new List<WMS_ITEM_PKG>();
                List<BIZ_ERP_RECEIPT> nBillHeaders = new List<BIZ_ERP_RECEIPT>();
 
                List<WMS_ITEM> items = Biz.Db.Queryable<WMS_ITEM>().Where(x => dlvys.Contains(x.TRANS_NO)).ToList();
                List<Result<BIZ_SRM_DLVY>> res = srmDlvys.OrderBy(o => o.DELIVERY_NO).Select(q => new Result<BIZ_SRM_DLVY>(Result.Flags.Success, q)).ToList();
 
                // 按照送货单列表处理单据明细
                foreach (var resDtl in res)
                {
                    //新建单据
                    Result ruleResult = Cache.CodeRule["R001"].Generate("RE");
                    if (!ruleResult.IsSuccessed)
                    {
                        throw new Exception(ruleResult.ExceptionMsg.Message);
                    }
                    List<BIZ_ERP_IQC> iqcHeaders_n = new List<BIZ_ERP_IQC>();
                    var billcode = ruleResult.Data.ToString();
                    var nBillHeader = new BIZ_ERP_RECEIPT
                    {
                        BILLCODE = billcode,
                        BILLDATE = DateTime.Now.Date,
                        //WAREHOUSECODE = WarehouseCode,
                        DELIVERY_NO = resDtl.Data.DELIVERY_NO,
                        STATUS = BIZ_ERP_RECEIPT.STATUSs.WORKING.GetValue(),
                        //SUPPLIERCODE = nScannedBarcodes[0].SUPPLIERCODE,
                        AUTH_ORG = OrgCode
                    };
                    nBillHeaders.Add(nBillHeader);
                    var supplyCode = "";
                    List<Detail> details = new List<Detail>();
                    //创建收货单明细
                    nBillHeader.SUPPLIERCODE = resDtl.Data.SUPP_CODE;
                    foreach (var item in resDtl.Data.Dtls.OrderBy(o => o.PO_LINE_NO))
                    {
                        //供应商代码
                        supplyCode = resDtl.Data.SUPP_CODE;
                        //插入单据明细行
                        if (!detailList.Where(x => x.BILLLINE == item.PO_LINE_NO.ToString() && x.BILLCODE == billcode).Any())
                        {
                            detailList.Add(new BIZ_ERP_RECEIPT_DTL
                            {
                                WAREHOUSECODE = WarehouseCode,
                                BILLCODE = billcode,
                                BILLID = Guid.NewGuid().ToString("N"),
                                BILLLINE = item.PO_LINE_NO.ToString(),
                                LINESTATUS = BIZ_ERP_RECEIPT.STATUSs.WORKING.GetValue(),
                                ITEM_CODE = item.ITEM_CODE,
                                UNITCODE = item.UNIT,
                                QTYPASS = 0,
                                INSTOCKQTY = 0,
                                RETURNQTY = 0,
                                PRINTQTY = 0,
                                ISGIVEAWAY = false,
                                SOURCETYPE = nameof(BIZ_SRM_DLVY),
                                SOURCECODE = item.DELIVERY_NO,
                                SOURCELINE = item.PO_LINE_NO.ToString(),
                                AUTH_ORG = OrgCode,
                                QTY = item.QTY
                            });
 
                            Result iqcResult = Cache.CodeRule["IQC001"].Generate("IQC");
                            if (!iqcResult.IsSuccessed)
                            {
                                throw new Exception(iqcResult.ExceptionMsg.Message);
                            }
                            var iqc = new BIZ_ERP_IQC
                            {
                                BILLCODE = iqcResult.Data.ToString(),
                                SOURCETYPE = (int)BIZ_ERP_IQC.BillType.CustSupplyInStock,
                                SOURCECODE = billcode,
                                SOURCELINE = item.PO_LINE_NO.ToString(),
                                PONO = item.ERP_PO_NO,
                                POLINE = item.LINE_NO.ToString(),
                                MEASURE = "Y",
                                AUTH_ORG = OrgCode,
                                QCTIMES = 0,
                                QCSTATUS = (int)BIZ_ERP_IQC.QCSTATUSs.Finished, /*(int)IqcManagementSides.QCStatus.UnFinish,*/
                                QCRESULT = (int)BIZ_ERP_IQC.QCRESULTs.Wait,
                                QCREVIEW = (int)BIZ_ERP_IQC.QCReview.UnReview,
                                QCLEVEL = 11,
                                ITEM_CODE = item.ITEM_CODE,
                                RECEIVEQTY = item.QTY
                                //ReceiveQty = detail.Qty,
                            };
                            //保存数据库
                            //iqcHeaders.Add(iqc);
                            //推送检单
                            iqcHeaders_n.Add(iqc);
                        }
                        //到货明细
                        if (!details.Where(x => x.pmdtseq == item.PO_LINE_NO.ToString()).Any())
                        {
                            details.Add(new Detail
                            {
                                pmdtseq = item.PO_LINE_NO.ToString(),
                                pmdt001 = item.ERP_PO_NO, //lineNumber
                                pmdt002 = item.LINE_NO.ToString(), //itemNumber
                                pmdt003 = "1",
                                pmdt004 = item.BATCH_NUMBER,
                                pmdt006 = item.ITEM_CODE, //"K7015AA016141",
                                                          //pmdt018 = "创米科技",
                                pmdt020 = item.QTY.ToString(),  //"100.00000",
                                pmdtud011 = "0"
                            });
                        }
                    }
                    //更新SN单号和状态
                    var snList = nScannedBarcodes.Where(x => x.DELIVERY_NO == resDtl.Data.DELIVERY_NO).ToList();
                    if (snList != null)
                    {
                        foreach (var ent in snList)
                        {
                            ent.BILLCODE = billcode;
                            ent.STATUS = WMS_ITEM.STATUSs.WaitTest.GetValue();
                        }
                    }
                    //更新库存表
                    foreach (var wi in items.Where(x => x.TRANS_NO == resDtl.Data.DELIVERY_NO))
                    {
                        wi.STATUS = WMS_ITEM.STATUSs.WaitTest.GetValue();
                        wi.TRANS_CODE = nameof(BIZ_ERP_RECEIPT);
                        wi.TRANS_NO = billcode;
                        wi.SOURCE_CODE = nameof(resDtl.Data);
                        wi.SOURCE_ORDER = resDtl.Data.DELIVERY_NO;
                        wi.AUTH_ORG = OrgCode;
 
                        WMS_ITEM_HIS his = new WMS_ITEM_HIS(wi, $"自购来料清点,到货单[{billcode}],送货单[{resDtl.Data.DELIVERY_NO}]");
                        ItemHistorys.Add(his);
                    }
 
                    //调用T100接口生成到货单
                    var ret = ErpT100.GenerateCustReceipt(new CustReceiptInputParameter
                    {
                        parameter = new Parameter<Detail>
                        {
                            pmds000 = "1",
                            pmdsdocno = "3438",
                            pmdsdocdt = DateTime.Now.ToString("yyyy-MM-dd"), //"2023-04-26", //当天时间
                            pmds002 = UserCode == "admin" ? "00000" : UserCode, //用户ID
                            pmds003 = "",
                            pmds007 = supplyCode, //"C0006", //供应商代码
                            pmdsud003 = customsData.CustomsNo, // 报关单号
                            pmdsud004 = customsData.AccountingNo,// 核放清单号
                            pmds010 = resDtl.Data.DELIVERY_NO, //"测试客供料无采购收货", //送货单号
                                                               //pmdsud001 = SecondVenderCode, //"CM017", //二级供应编号
                            detail = details,
                        },
                        datakey = new Datakey
                        {
                            EntId = "88",
                            CompanyId = OrgCode
                        }
                    });
                    if (ret.payload.std_data.execution.code == "0") //成功
                    {
                        nBillHeader.ERP_BILL_CODE = ret.payload.std_data.parameter.docno;
                        action.Message += $"{action.Message.IsNullOrEmpty("", ";")}{ret.payload.std_data.execution.description},返回的收货单号:[{ret.payload.std_data.parameter.docno}]";
 
                        #region 生成送检单
 
                        foreach (var item in iqcHeaders_n)
                        {
                            var retIns = ErpT100.GenerateInspection(new InsInputParameter
                            {
                                parameter = new InsParameter
                                {
                                    pmdsdocno = ret.payload.std_data.parameter.docno,
                                    pmdsdocdt = DateTime.Now.ToString("yyyy-MM-dd"),
                                    pmdtseq = item.SOURCELINE.ToString(),
                                    pmdt020 = item.RECEIVEQTY.ToString(),
                                    qcbadocno = "3701",
                                },
                                datakey = new Datakey
                                {
                                    EntId = "88",
                                    CompanyId = OrgCode
                                }
                            });
                            isIQCOk &= retIns.payload.std_data.execution.code == "0";
                            if (retIns.payload.std_data.execution.code != "0")
                            {
                                action.IsSuccessed = false;
                                action.Message += $"返回到货单[{ret.payload.std_data.parameter.docno}],当前用户[{UserCode}],送货单号[{resDtl.Data.DELIVERY_NO}],到货单号[{billcode}],返回的信息:{retIns.payload.std_data.execution.description}";
                            }
                            else
                            {
                                var receipDtl = detailList.Where(q => q.BILLCODE == item.SOURCECODE && q.BILLLINE == item.SOURCELINE).FirstOrDefault();
                                if (!receipDtl.IsNullOrEmpty())
                                {
                                    receipDtl.ERP_BILL_CODE = retIns.payload.std_data.parameter.docno;
                                }
                                item.ERP_BILL_CODE = retIns.payload.std_data.parameter.docno;
                                //保存数据库
                                iqcHeaders.Add(item);
                                action.Message += $"到货单[{ret.payload.std_data.parameter.docno}],当前用户[{UserCode}],返回的信息:{retIns.payload.std_data.execution.description}"; ;
                            }
                        }
 
                        #endregion 生成送检单
                    }
                    else //失败
                    {
                        //if (ret.payload.std_data.execution.code != "wms100")
                        //{
                        action.IsSuccessed = false;
                        action.Message += $"当前用户[{UserCode}],返回的信息:{ret.payload.std_data.execution.description}";
                        resDtl.Flag = Result.Flags.Failed;
                        //}
                        //else
                        //{
                        //    foreach (var item in nScannedBarcodes)
                        //    {
                        //        item.STATUS = 30;
                        //    }
                        //    foreach (var item in items)
                        //    {
                        //        item.STATUS = 30;
                        //        item.TRANS_NO = billcode;
                        //    }
                        //    foreach (var item in ItemHistorys)
                        //    {
                        //        item.STATUS = 30;
                        //    }
                        //    foreach (var item in detailList)
                        //    {
                        //        item.ERP_BILL_CODE = ret.payload.std_data.parameter.docno;
                        //    }
                        //}
 
                        //resDtl.Message += $"当前用户[{UserCode}],送货单号[{resDtl.Data.DELIVERY_NO}],到货单号[{billcode}],返回的信息:{ret.payload.std_data.execution.description}";
                        //return action;
                    }
                }
                //保存到数据库
                var db = Business.Biz.Db;
                var dbTran = db.UseTran(() =>
                {
                    // 插入单据表头
                    nBillHeaders = nBillHeaders.Where(q => res.Any(s => s.Flag == Result.Flags.Success && s.Data.DELIVERY_NO == q.DELIVERY_NO)).ToList();
                    db.Insertable(nBillHeaders, UserCode).ExecuteCommand();
                    Logger.Interface.Info($"入库单{nBillHeaders.Select(q => q.BILLCODE).ToList()}保存成功");
                    detailList = detailList.Where(q => res.Any(s => s.Flag == Result.Flags.Success && s.Data.DELIVERY_NO == q.SOURCECODE)).ToList();
                    db.Insertable(detailList, UserCode).ExecuteCommand();
 
                    nScannedBarcodes = nScannedBarcodes.Where(q => res.Any(s => s.Flag == Result.Flags.Success && s.Data.DELIVERY_NO == q.DELIVERY_NO)).ToList();
                    db.Updateable(nScannedBarcodes, UserCode).UpdateColumns(x => new { x.UPDATE_USER, x.UPDATE_TIME, x.BILLCODE, x.STATUS }).ExecuteCommand();
                    Logger.Interface.Info($"入库单条码{nScannedBarcodes.Select(q => q.SN).ToList()}保存成功");
                    //if (isIQCOk)
                    {
                        iqcHeaders = iqcHeaders.Where(s => res.Any(q => q.IsSuccessed && q.Data.Dtls.Any(d => d.ERP_PO_NO == s.PONO && d.PO_LINE_NO.ToString() == s.SOURCELINE))).ToList();
                        db.Insertable(iqcHeaders, UserCode).ExecuteCommand();
                        action.Message += $"{action.Message.IsNullOrEmpty("", ";")}生成采购收货单和送检单成功";
                    }
                    items = items.Where(q => res.Any(s => s.Flag == Result.Flags.Success && s.Data.DELIVERY_NO == q.SOURCE_ORDER)).ToList();
                    db.Updateable(items, UserCode).UpdateColumns(x => new { x.UPDATE_USER, x.UPDATE_TIME, x.STATUS, x.TRANS_CODE, x.TRANS_NO, x.TRANS_LINE, x.SOURCE_CODE, x.SOURCE_ORDER }).ExecuteCommand();
                    ItemHistorys = ItemHistorys.Where(q => res.Any(s => s.Flag == Result.Flags.Success && s.Data.DELIVERY_NO == q.SOURCE_ORDER)).ToList();
                    db.Insertable(ItemHistorys, UserCode).ExecuteCommand();
                });
                if (!dbTran.IsSuccess)
                {
                    Logger.Default.Fatal(dbTran.ErrorException, "Database transaction save exception");
                    this.Close(!dbTran.IsSuccess);
                    throw dbTran.ErrorException;
                }
            }
            catch (System.Exception ex)
            {
                return action.CatchExceptionWithLog(ex, Biz.L("系统异常"));
            }
            return action;
        }
 
        /// <summary>
        /// 删除当前用户的已扫记录(缓存表)
        /// </summary>
        /// <returns></returns>
        public async Task<ApiAction> DeleteAllScannedBarcode()
        {
            var action = new ApiAction();
            try
            {
                await Biz.Db.Deleteable<BIZ_ERP_RECEIPT_SN>(x =>
                     x.STATUS == WMS_ITEM.STATUSs.Counted.GetValue()
                    && x.BILLCODE == UserCode).ExecuteCommandAsync();
            }
            catch (System.Exception ex)
            {
            }
            return action;
        }
 
        /// <summary>
        /// 删除当前用户的已扫单个记录
        /// </summary>
        /// <returns></returns>
        public async Task<ApiAction> DeleteScannedBarcode(CustSupplyInInput input)
        {
            var action = new ApiAction();
            try
            {
                if (WarehouseCode.IsNullOrEmpty())
                {
                    action.IsSuccessed = false;
                    action.Message = $"空,无法删除已清点条码";
                    return action;
                }
                else
                {
                    await Biz.Db.Deleteable<BIZ_ERP_RECEIPT_SN>(x => x.SN == input.SN).ExecuteCommandAsync();
                }
            }
            catch (System.Exception ex)
            {
            }
            return action;
        }
 
        /// <summary>
        ///  获取已清点的物料汇总
        /// </summary>
        /// <returns></returns>
        public async Task<PageAble<BIZ_ERP_RECEIPT_SN>> GetScannedMaterialSummarys()
        {
            var query = Biz.Db.Queryable<BIZ_ERP_RECEIPT_SN>()
                .Where(t => t.STATUS == WMS_ITEM.STATUSs.Counted.GetValue()
                    && t.BILLCODE == UserCode
                    && t.AUTH_ORG == OrgCode)
                .ToList();
            return await Task.FromResult(new PageAble<BIZ_ERP_RECEIPT_SN>()
            {
                data = query,
                totals = query.Count(),
            });
        }
 
        /// <summary>
        /// 查询物料对应的条码
        /// </summary>
        /// <param name="MaterialCode"></param>
        /// <returns></returns>
        public async Task<PageAble<Model.Minsun.CustSupplyCheckDetail>> GetScannedMaterialDetailBarcodes(string MaterialCode)
        {
            var query = await Biz.Db.Queryable<BIZ_ERP_RECEIPT_SN, BAS_ITEM>((t, m) =>
                                    new JoinQueryInfos(
                                        JoinType.Left, t.ITEM_CODE == m.ITEM_CODE
                                        ))
                .Where((t, m) => t.CREATE_USER == UserCode
                    //&& t.WAREHOUSECODE.ToUpper() == WarehouseCode.ToUpper()
                    && t.STATUS == WMS_ITEM.STATUSs.Counted.GetValue()
                    && t.ITEM_CODE.ToUpper() == MaterialCode.ToUpper()
                    && t.BILLCODE == UserCode
                    && t.AUTH_ORG == OrgCode)
                .Select((t, m) => new Model.Minsun.CustSupplyCheckDetail
                {
                    Barcode = t.SN,
                    BarcodeQty = t.SCANQTY,
                    Unit = m.UNIT
                })
                .ToListAsync();
            return new PageAble<Model.Minsun.CustSupplyCheckDetail>()
            {
                data = query,
                totals = query.Count(),
            };
        }
 
        #endregion Functions
 
        public override bool Close(bool needSaveHistoryLog = false)
        {
            //保存操作日志
 
            this.IsFinished = true;
            return IsFinished ? base.Close(needSaveHistoryLog) : IsFinished;
        }
    }//endClass
}