快乐的昕的电脑
6 天以前 dceaef6216586bed2a22ac425c4ac07cb1136ae4
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
using Masuit.Tools;
using MES.Service.DB;
using MES.Service.Dto.webApi;
using MES.Service.Modes;
using SqlSugar;
using System.Data;
using System.Globalization;
using System.Security.AccessControl;
 
namespace MES.Service.service.BasicData;
/// <summary>
/// 采购订单
/// </summary>
public class MesRohInManager : Repository<MesRohIn>
{
    private readonly MesRohInDataManager rohInDataManager = new();
 
    // Save 方法用于保存单个 RohIn 记录,根据类型执行不同的操作
    public bool Save(RohIn rohIn)
    {
        var rohInErpRohIn = rohIn.ErpRohIn;
 
        var mesRohIn = GetMesRohIn(rohInErpRohIn);
        var mesRohInDatas =
            GetMesRohInDatas(rohIn.ErpRohinDatas, mesRohIn);
 
        //1    | 未实现     | 抛出异常
        //2    | 审核       | 调用 SaveOrUpdateData,正常插入/更新
        //3    | 反审核     | 调用 SaveOrUpdateData,BillNo 一定加后缀
        //4    | 手工同步   | 调用 SaveOrUpdateData,正常插入/更新
        //5    | 未注释     | 调用 SaveOrUpdateData,正常插入/更新
        return UseTransaction(db =>
        {
            return rohInErpRohIn.Type switch
            {
                "2" or "4" or "5" => SaveOrUpdateData(db, mesRohIn,
                    mesRohInDatas, rohInErpRohIn.Type)
                    ? 1
                    : 0,
                "3" => SaveOrUpdateData(db, mesRohIn,
                    mesRohInDatas, rohInErpRohIn.Type)
                    ? 1
                    : 0, //UpdateData(db, mesRohIn, mesRohInDatas) ? 1 : 0,//反审核不删除,做update。
                _ => throw new NotImplementedException(
                    $"type没有{rohInErpRohIn.Type}这个类型")
            };
        }) > 0;
    }
 
 
    // 更新数据的方法
    private bool UpdateData(SqlSugarScope db, MesRohIn mesRohIn,
        List<MesRohInData> mesRohInDatas)
    {
        var decimals = mesRohInDatas.Select(s => s.Guid).ToArray();
 
        var update = db.Deleteable<MesRohIn>()
            .Where(a => a.Guid == mesRohIn.Guid)
            .ExecuteCommand() > 0;
 
        var insertOrUpdate = db
            .Deleteable<MesRohInData>()
            .Where(s => decimals.Contains(s.Guid))
            .ExecuteCommand() > 0;
 
        if (update && insertOrUpdate) return true;
        throw new NotImplementedException("更新失败");
    }
 
    // 插入或更新数据的方法
    private bool SaveOrUpdateData(SqlSugarScope db, MesRohIn mesRohIn,List<MesRohInData> mesRohInDatas, string type)
    {
        ////传什么,c就改成什么
        //if (type == "3" || (mesRohIn.DocumentStatus != null && mesRohIn.DocumentStatus != "C"))//C表示已审核状态
        //{
        //    mesRohIn.BillNo = mesRohIn.BillNo + "F" + mesRohIn.EbelnK3id.ToString();
        //}
 
        //传什么,c就改成什么
        if (type == "3" || (mesRohIn.DocumentStatus != null && mesRohIn.DocumentStatus != "Y"))//Y表示已审核状态
        {
            mesRohIn.BillNo = mesRohIn.BillNo + "Y" + mesRohIn.EbelnK3id.ToString();
        }
 
        if (mesRohIn.Guid != null)
            db.Deleteable<MesRohIn>().Where(s => s.Guid == mesRohIn.Guid)
                .ExecuteCommand();
 
        if (mesRohInDatas.Count > 0)
            db.Deleteable<MesRohInData>()
                .Where(s => s.ErpId == mesRohIn.EbelnK3id).ExecuteCommand();
 
        var orUpdate = db.Insertable(mesRohIn)
            .IgnoreColumns(true).ExecuteCommand() > 0;
 
 
        var baOrUpdate = db.Insertable(mesRohInDatas).PageSize(1)
            .IgnoreColumnsNull()
            .ExecuteCommand() > 0;
 
        if (orUpdate && baOrUpdate) return true;
        throw new NotImplementedException("插入或更新失败");
    }
 
    // 批量保存记录的方法
    public bool SaveList(List<RohIn> rohIns)
    {
        var result = rohIns.Select(Save).ToList();
        return result.All(b => b);
    }
 
    // 将 ErpRohIn 对象转换为 MesRohIn 对象的方法
    private MesRohIn GetMesRohIn(ErpRohIn rohIn)
    {
        //根据单号+单别,获取对应的id
        var singleId = Db.Queryable<MesRohIn>()
            .Where(x => x.BillNo == rohIn.FBillNo && x.DocumentType == rohIn.FBillTypeID)
            .Select(x => x.EbelnK3id)
            .First();
 
        //如果没有则生成一个新的id
        if (singleId == null || string.IsNullOrWhiteSpace(singleId.ToString()))
        {
            rohIn.id = GenerateNewId().ToString();
            //rohIn.id = GenerateNewId().ToString("0");
        }
        else//如果有则使用已有的id
        {
            rohIn.id = singleId.ToString();
        }
 
        var eid = long.Parse(rohIn.id);
        var mesRohIn = new MesRohIn();
 
 
        var single = base.GetSingle(it => it.EbelnK3id == eid);
        if (single != null) mesRohIn.Guid = single.Guid;
 
        mesRohIn.EbelnK3id = eid;
        mesRohIn.BillNo = rohIn.FBillNo;
        mesRohIn.DocumentStatus = rohIn.FDocumentStatus;
        mesRohIn.DocumentType = rohIn.FBillTypeID;
        mesRohIn.BusinessType = rohIn.FBusinessType;
 
        if (rohIn.FDate != null)
            mesRohIn.PurchaseDate = DateTime.ParseExact(rohIn.FDate,
                "yyyy-MM-dd HH:mm:ss", null);
 
        //供应商编码转ID
        var mesRohInSupplier = Db.Queryable<MesSupplier>()
            .Where(x => x.SuppNo == rohIn.FSupplierId)
            .Select(x => x.Id.ToString())
            .First();
        if (!string.IsNullOrWhiteSpace(mesRohInSupplier))
        {
            mesRohIn.Supplier = mesRohInSupplier;
        }
        else if (!string.IsNullOrWhiteSpace(rohIn.FSupplierId))
        {
            mesRohIn.Supplier = rohIn.FSupplierId;
        }
        else
        {
            mesRohIn.Supplier = "0";
        }
        //mesRohIn.Supplier = rohIn.FSupplierId;
 
        mesRohIn.CloseStatus = rohIn.FCloseStatus;
        //mesRohIn.PurchaseOrg = rohIn.FPurchaseOrgId;
        mesRohIn.PurchaseOrg = string.IsNullOrEmpty(rohIn.FPurchaseOrgId) ? "1" : rohIn.FPurchaseOrgId;//采购组织
 
        //采购部门编码转ID
        var mesRohInPurchaseDept = Db.Queryable<SysDepartment>()
            .Where(x => x.Departmentcode == rohIn.FPurchaseDeptId)
            .Select(x => x.Departmentid.ToString())
            .First();
        if (!string.IsNullOrWhiteSpace(mesRohInPurchaseDept))
        {
            mesRohIn.PurchaseDept = mesRohInPurchaseDept;
        }
        else if (!string.IsNullOrWhiteSpace(rohIn.FPurchaseDeptId))
        {
            mesRohIn.PurchaseDept = rohIn.FPurchaseDeptId;
        }
        else
        {
            mesRohIn.PurchaseDept = "0";
        }
        //mesRohIn.PurchaseDept = rohIn.FPurchaseDeptId;
 
        mesRohIn.PurchaseGroup = rohIn.FPurchaserGroupId;
        mesRohIn.Purchaser = rohIn.FPurchaserId;
        mesRohIn.SettlementParty = rohIn.FSettleId;
        mesRohIn.PaymentParty = rohIn.FChargeId;
        mesRohIn.Email = rohIn.FProviderEMail;
        mesRohIn.Remarks = rohIn.Remarks;
        mesRohIn.CancellationStatus = rohIn.FCancelStatus;
        mesRohIn.CancellationPerson = rohIn.FCancellerId;
 
        if (rohIn.FCancelDate != null)
            if (!mesRohIn.CancellationPerson.IsNullOrEmpty())
                mesRohIn.CancellationDate =
                    DateTime.ParseExact(rohIn.FCancelDate,
                        "yyyy-MM-dd HH:mm:ss", null);
 
        mesRohIn.CreateBy = rohIn.FCreatorId;
 
        if (rohIn.FCreateDate != null)
            mesRohIn.CreateDate = DateTime.ParseExact(rohIn.FCreateDate,
                "yyyy-MM-dd HH:mm:ss", null);
 
        mesRohIn.LastupdateBy = rohIn.FModifierId;
 
        if (rohIn.FModifyDate != null)
            mesRohIn.LastupdateDate = DateTime.ParseExact(rohIn.FModifyDate,
                "yyyy-MM-dd HH:mm:ss", null);
 
        mesRohIn.ErpCheckBy = rohIn.FApproverId;
        mesRohIn.ErpCheckDate = rohIn.FApproveDate;
        mesRohIn.Changereason = rohIn.FChangeReason;
        mesRohIn.Prearrivaldate = rohIn.Prearrivaldate != null
            ? DateTime.ParseExact(rohIn.Prearrivaldate,
                "yyyy-MM-dd HH:mm:ss", null)
            : null;
 
        mesRohIn.ReceiveOrgId = rohIn.FReceiveOrgId;
        mesRohIn.ProviderId = rohIn.FProviderId;
 
        mesRohIn.Anred = rohIn.FTContact;
        mesRohIn.Telf1 = rohIn.Fmobilephone;
        mesRohIn.FixedTelephone = rohIn.FixedTelephone;
        mesRohIn.Address = rohIn.FProviderAddress;//供货方地址
        mesRohIn.SynchronousDate = DateTime.Now;
 
        mesRohIn.Remark2= rohIn.F_UNW_GYSLXR;// 供应商联系人
        mesRohIn.Remark3= rohIn.F_UNW_LXRDH;// 联系人电话
        mesRohIn.Remark4 = rohIn.FProviderJob;// 职务
        mesRohIn.Remark5 = rohIn.FProviderPhone;// 手机
 
        mesRohIn.QtyAcceptance = rohIn.FACCTYPE;//验收方式
        mesRohIn.QualityReq = rohIn.F_UNW_Remarks_zlyq;//质量要求
        mesRohIn.TransportMethod = rohIn.F_UNW_Text_ysfs;//运输方式
        mesRohIn.Remarks = rohIn.F_UNW_BZ;//备注
        mesRohIn.FixtureMoldProcurement = rohIn.F_UNW_Combo_zjmj;//治具丶模具加工及采购
        mesRohIn.urgent_material = rohIn.FUrgent_Material;//急料
 
        return mesRohIn;
    }
 
    // 将 ErpRohinData 对象转换为 MesRohInData 对象的方法
    private List<MesRohInData> GetMesRohInDatas(List<ErpRohinData> erpRohinDatas, MesRohIn mesRohIn)
    {
        return erpRohinDatas.Select(s =>
        {
            var entity = new MesRohInData
            {
                EbelnK3id = Convert.ToDecimal(s.id),
                ErpId = Convert.ToDecimal(mesRohIn.EbelnK3id),//使用主表的EbelnK3id作为子表的ErpId
                BillNo = s.FBillNo,
                ItemId = s.FMaterialId,
                PurchaseUnit = s.FUnitId,
                PurchaseQty = Convert.ToDecimal(s.FQty),
                InventoryUnit = s.FStockUnitID,
                PricingUnit = s.FPriceUnitId,
                PricingQty = Convert.ToDecimal(s.FPriceUnitQty),
                DeliveryDate = s.FDeliveryDate != null
                    ? DateTime.ParseExact(s.FDeliveryDate,
                        "yyyy-MM-dd HH:mm:ss", null)
                    : null,
                EarliestDeliveryDate = s.FDeliveryEarlyDate != null
                    ? DateTime.ParseExact(s.FDeliveryEarlyDate,
                        "yyyy-MM-dd HH:mm:ss", null)
                    : null,
                LatestDeliveryDate = s.FDeliveryLastDate != null
                    ? DateTime.ParseExact(s.FDeliveryLastDate,
                        "yyyy-MM-dd HH:mm:ss", null)
                    : null,
                IsGift = s.FGiveAway,
                Remarks = s.FEntryNote,
                SupplierItemCode = s.FSupMatId,
                SupplierItemName = s.FSupMatName,
                OutsourcingOrderId = s.FSUBREQBILLNO,
                BatchNumber = s.FLot,
                BusinessClose = s.FMRPCloseStatus,
                BusinessFreeze = s.FMRPFreezeStatus,
                Freezer = s.FFreezerId,
                FreezeTime = !string.IsNullOrEmpty(s.FFreezeDate)
                            && DateTime.TryParseExact(s.FFreezeDate,
                                new[] { "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd" },  // 支持多种格式
                                CultureInfo.InvariantCulture,
                                DateTimeStyles.None,
                                out var parsedDate)
                            && parsedDate > new DateTime(1900, 1, 1)
                                ? parsedDate
                                : (DateTime?)null,
                BusinessTerminate = s.FMRPTerminateStatus,
                Terminator = s.FTerminaterId,
                TerminateTime = s.FTerminateDate != null
                    ? DateTime.ParseExact(s.FTerminateDate,
                        "yyyy-MM-dd HH:mm:ss", null)
                    : null,
                TotalReceivedQty = Convert.ToDecimal(s.FReceiveQty), //累计收料数
                RemainingReceivedQty =
                    Convert.ToDecimal(s.FRemainReceiveQty),
                TotalStoredQty = Convert.ToDecimal(s.FStockInQty), //累计入库数
                RemainingStoredQty = Convert.ToDecimal(s.FRemainStockINQty),
                TotalReturnedQty = Convert.ToDecimal(s.FMrbQty),
                ReturnableReceivedQty =
                    Convert.ToDecimal(s.FCHECKRETQTY), //收料可退数
                ReturnableStoredQty = Convert.ToDecimal(s.FSTOCKRETQTY), //库存可退数
                SourceDocumentType = s.FBillTypeID,//采购单别
                SourceDocumentId = s.FSrcBillNo,
                DemandTrackingId = s.FReqTraceNo,
                PlanTrackingId = s.FMtoNo,
                ChangeFlag = s.FChangeFlag,
                DemandSource = s.FDEMANDTYPE,
                DemandDocumentId = s.FDEMANDBILLNO,
                OrderLineId = s.FDEMANDBILLENTRYSEQ,
                DemandOrg = s.FRequireOrgId,
                ReceivingOrg = s.FReceiveOrgId,
                SettlementOrg = s.FEntrySettleOrgId,
                PurchaseOrderLineNumber = s.FSEQ,
                Demand = s.FRequireOrgId,
                Receiving = s.FReceiveOrgId,
                Settlement = s.FSETTLEORGID,
                DemandDepartment = s.FRequireDeptId,
                ReceivingDepartment = s.FReceiveDeptId,
 
                Remark5 = s.FUrgent_Material, //急料
                SalesOrderId = s.F_UNW_Text_xsddh
            };
 
            //采购单位编码转ID
            var entityPurchaseUnit = Db.Queryable<MesUnit>()
                .Where(x => x.Fnumber == s.FUnitId)
                .Select(x => x.Id.ToString())
                .First();
            if (!string.IsNullOrWhiteSpace(entityPurchaseUnit))
            {
                entity.PurchaseUnit = entityPurchaseUnit;
            }
            else if (!string.IsNullOrWhiteSpace(s.FUnitId))
            {
                entity.PurchaseUnit = s.FUnitId;
            }
            else
            {
                entity.PurchaseUnit = "0";
            }
 
            //计价单位编码转ID
            var entityPricingUnit = Db.Queryable<MesUnit>()
                .Where(x => x.Fnumber == s.FPriceUnitId)
                .Select(x => x.Id.ToString())
                .First();
            if (!string.IsNullOrWhiteSpace(entityPricingUnit))
            {
                entity.PricingUnit = entityPricingUnit;
            }
            else if (!string.IsNullOrWhiteSpace(s.FPriceUnitId))
            {
                entity.PricingUnit = s.FPriceUnitId;
            }
            else
            {
                entity.PricingUnit = "0";
            }
 
            //物料编码转ID
            var entityItemId = Db.Queryable<MesItems>()
                .Where(x => x.ItemNo == s.FMaterialId)
                .Select(x => x.Id.ToString())
                .First();
            if (!string.IsNullOrWhiteSpace(entityItemId))
            {
                entity.ItemId = entityItemId;
            }
            else if (!string.IsNullOrWhiteSpace(s.FMaterialId))
            {
                entity.ItemId = s.FMaterialId;
            }
            else
            {
                entity.ItemId = "0";
            }
 
            if (s.FFreezeDate != null)
                if (!s.FFreezerId.IsNullOrEmpty())
                    entity.FreezeTime =
                        DateTime.ParseExact(s.FFreezeDate,
                            "yyyy-MM-dd HH:mm:ss", null);
 
            if (s.FTerminateDate != null)
                if (!s.FTerminaterId.IsNullOrEmpty())
                    entity.TerminateTime =
                        DateTime.ParseExact(s.FTerminateDate,
                            "yyyy-MM-dd HH:mm:ss", null);
 
            //根据单号+单别+行号,获取对应的id
            var singleId = Db.Queryable<MesRohInData>()
            .Where(x => x.BillNo == s.FBillNo && x.SourceDocumentType == s.FBillTypeID && x.OrderLineId == s.FDEMANDBILLENTRYSEQ)
            .Select(x => x.EbelnK3id)
            .First();
 
            if (singleId == null)//如果没有则生成一个新的id
            {
                //entity.EbelnK3id = GenerateNewId2().ToString();
                entity.EbelnK3id = GenerateNewId2();
            }
            else//如果有则使用已有的id
            {
                //entity.EbelnK3id = singleId.EbelnK3id;
                entity.EbelnK3id = singleId;
            }
 
            //查询EbelnK3id对应的Guid,赋值给entity.Guid。实现主键复用
            var single = rohInDataManager.GetSingle(it =>it.EbelnK3id == entity.EbelnK3id);
            if (single != null) entity.Guid = single.Guid;
 
            return entity;
        }).ToList();
    }
 
    /// <summary>
    /// 生成新的主表ID,确保不重复
    /// </summary>
    private decimal GenerateNewId()
    {
        // 处理空表的情况,从1开始
        var maxId = Db.Queryable<MesRohIn>().Max(x => (decimal?)x.EbelnK3id) ?? 0;
        var newId = maxId + 1;
 
        // 双重检查,确保生成的ID不存在
        while (Db.Queryable<MesRohIn>().Where(x => x.EbelnK3id == newId).Any())
        {
            newId++;
        }
 
        return newId;
    }
 
    /// <summary>
    /// 生成新的子表ID,通过数据库序列获取唯一ID
    /// </summary>
    private decimal GenerateNewId2()
    {
        try
        {
            // 替换为:
            var sequenceValueObj = Db.Ado.GetScalar("SELECT NEXT VALUE FOR MES_ROH_IN_DATA_seq");
            var sequenceValue = Convert.ToDecimal(sequenceValueObj);
            // 验证序列值是否有效
            if (sequenceValue <= 0)
            {
                throw new InvalidOperationException($"数据库序列 MES_ROH_IN_DATA_seq 返回了无效的值: {sequenceValue}");
            }
 
            return sequenceValue;
        }
        catch (Exception ex)
        {
            // 记录异常信息
            Console.WriteLine($"调用数据库序列 MES_ROH_IN_DATA_seq 失败: {ex.Message}");
 
            // 向上层抛出明确的异常信息
            throw new InvalidOperationException($"生成子表ID失败,无法获取数据库序列值: {ex.Message}", ex);
        }
    }
 
    /// <summary>
    /// 整单删除,调用存储过程
    /// </summary>
    /// <param name="billNo">单号</param>
    /// <returns>被删除的单号</returns>
    public (int outSum, string outMsg) Delete(string FBillNo, string FBillTypeID)
    {
        var outMsg = string.Empty;
        var outSum = 0;
 
        var parameters = new List<SugarParameter>
    {
        new SugarParameter("@FBillNo", FBillNo),
        new SugarParameter("@FBillTypeID", FBillTypeID),
        new SugarParameter("@outMsg", outMsg, typeof(string), ParameterDirection.Output, 2500),
        new SugarParameter("@outSum", outSum, typeof(int), ParameterDirection.Output)
    };
 
        Db.Ado.UseStoredProcedure().ExecuteCommand("ERP_DeleteMesRohInByBillNo", parameters);
 
        outMsg = parameters[2].Value?.ToString() ?? "";
        outSum = parameters[3].Value != null ? Convert.ToInt32(parameters[2].Value) : -1;
 
        return (outSum, outMsg);
    }
 
 
    // 整单删除
    //private bool Delete(SqlSugarScope db, MesRohIn mesRohIn,List<MesRohInData> mesRohInDatas)
    //{
    //    if (mesRohIn.Guid != null)
    //        db.Deleteable<MesRohIn>().Where(s => s.Guid == mesRohIn.Guid)
    //            .ExecuteCommand();
 
    //    if (mesRohInDatas.Count > 0)
    //        db.Deleteable<MesRohInData>()
    //            .Where(s => s.ErpId == mesRohIn.EbelnK3id).ExecuteCommand();
 
    //    var orUpdate = db.Insertable(mesRohIn)
    //        .IgnoreColumns(true).ExecuteCommand() > 0;
 
 
    //    var baOrUpdate = db.Insertable(mesRohInDatas).PageSize(1)
    //        .IgnoreColumnsNull()
    //        .ExecuteCommand() > 0;
 
    //    if (orUpdate && baOrUpdate) return true;
    //    throw new NotImplementedException("删除");
    //}
}