UpstreamSendWorkOrder.cs 23 KB
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
using Hh.Mes.Common.log;
using Hh.Mes.Pojo.System;
using Hh.Mes.POJO.ApiEntity;
using Hh.Mes.POJO.Entity;
using Hh.Mes.POJO.EnumEntitys;
using Hh.Mes.POJO.Response;
using Hh.Mes.POJO.WebEntity.api;
using Hh.Mes.POJO.WebEntity.bus;
using Hh.Mes.Service.Logs;
using Hh.Mes.Service.WebService.Wo;
using System;
using System.Collections.Generic;
using System.Linq;
using Ubiety.Dns.Core;
using static Microsoft.AspNetCore.Hosting.Internal.HostingApplication;

namespace Hh.Mes.Service.ApiService
{
    public partial class UpstreamService
    {
        #region 属性
        /// <summary>
        /// 产品表
        /// </summary>
        private base_product_header ProductHeader { get; set; }

        /// <summary>
        /// 工作中心映射华恒线体code
        /// </summary>
        private string LineCode { get; set; }

        /// <summary>
        /// 工艺路线
        /// </summary>
        private base_process_route_head ProcessHead { get; set; }

        private List<base_process_route_detail> ProcessBody { get; set; }

        private ResponseUpstream<string> responseOrder { get; set; }

        private MomWorkOrderHead entity { get; set; }
        #endregion

        public dynamic SendWorkOrder(MomWorkOrderHead entity)
        {
            return ExceptionsHelp.Instance.ExecuteT(() =>
            {
                var plmeid = entity == null ? "" : entity.plmeid;
                responseOrder = new ResponseUpstream<string>(plmeid);
                if (!typeValidation(entity.type, responseOrder).Status) return responseOrder;

                if (entity == null) return responseOrder.ResponseError("【上位系统】订单下发:工单数据为空,请检查!");

                this.entity = entity;
                //校验
                responseOrder = HandleAcceptOrderBefore();
                if (!responseOrder.Status)
                {
                    QueueInterLog.GetInstance.EnqueueInterLog(null, null, EnumLog.MOM订单下发失败.ToString(), responseOrder.Message, 0, user: "AOP", sysTitle: EnumLog.MOM业务问题.ToString());
                    return responseOrder;
                }
                //生成订单数据
                var orderDataResult = HandleAcceptOrderData();
                //新增订单请求记录
                AddWorkOrderLog(entity);
                //保存数据
                var saveResult = SaveHandleAcceptOrderData(orderDataResult.Item1, orderDataResult.Item2, orderDataResult.Item3, orderDataResult.Item4, orderDataResult.Item5, orderDataResult.Item6);

                var materCodes = entity.details?.Where(x => string.IsNullOrWhiteSpace(x.mater_code)).Select(x => x.station_code).ToList();
                //如果MOM下发的数据“工位编码”为空,则记录日志
                if (saveResult.Status && materCodes.Any())
                {
                    var errorMsg = $"【MOM--生产订单下发】对{nameof(entity.plmeid)}为“{entity.plmeid}”的工序任务执行“{entity.type}”操作时,物料编码为[{string.Join(",", materCodes)}]的工位编码值为空!";
                    QueueInterLog.GetInstance.EnqueueInterLog(null, null, EnumLog.MOM订单下发失败.ToString(), errorMsg, 0, user: "AOP", sysTitle: EnumLog.MOM业务问题.ToString());
                    Log4NetHelper.Instance.Warning(errorMsg);
                }
                return saveResult;
            });
        }

        /// <summary>
        /// 新增订单请求记录
        /// </summary>
        /// <param name="entity"></param>
        private void AddWorkOrderLog(MomWorkOrderHead entity)
        {
            var head = new api_workOrder_head
            {
                keys = Guid.NewGuid(),
                workOrderCode = entity.pro_order_code,
                plmeId = entity.plmeid,
                productCode = entity.product_code,
                productName = entity.product_name,
                planCode = entity.plan_code,
                unitCode = entity.unit_code,
                lineCode = entity.line_code,
                orderType = entity.order_type,
                playdate = entity.playdate,
                enddate = entity.enddate,
                num = entity.num,
                factoryCode = entity.factory,
                edition = entity.edition,
                ylzd2 = entity.ylzd2,
                createTime = DateTime.Now,
                type = entity.type,
                createBy = SystemVariable.DefaultCreated
            };
            List<api_workOrder_detail> details = new List<api_workOrder_detail>();
            foreach (var item in entity.details)
            {
                details.Add(new api_workOrder_detail
                {
                    headKeys = head.keys,
                    planCode = item.plan_code,
                    stationCode = item.station_code,
                    materialCode = item.mater_code,
                    materialName = item.mater_name,
                    qty = item.qty,
                    whCode = item.wh_code,
                    procedCode = item.proced_code,
                    ylzd3 = item.ylzd3,
                    ylzd4 = item.ylzd4,
                    createTime = DateTime.Now,
                    createBy = SystemVariable.DefaultCreated
                });
            }
            Context.Insertable(head).AddQueue();
            Context.Insertable(details).AddQueue();
        }

        /// <summary>
        /// 订单下发接受数据处理 校验
        /// </summary>
        public ResponseUpstream<string> HandleAcceptOrderBefore()
        {
            #region 空值检查

            if (string.IsNullOrWhiteSpace(entity.pro_order_code))
            {
                responseOrder.ResponseError($"【上位系统】订单下发:【plmeid】[{entity.plmeid}]订单号【pro_order_code】不能为空值,请检查!");
                return responseOrder;
            }
            if (string.IsNullOrWhiteSpace(entity.plan_code))
            {
                responseOrder.ResponseError($"【上位系统】订单下发:【plmeid】[{entity.plmeid}]生产计划号【plan_code】不能为空值,请检查!");
                return responseOrder;
            }
            if (string.IsNullOrWhiteSpace(entity.product_code))
            {
                responseOrder.ResponseError($"【上位系统】订单下发:【plmeid】[{entity.plmeid}]产品编码【product_code】不能为空值,请检查!");
                return responseOrder;
            }
            if (string.IsNullOrEmpty(entity.factory))
            {
                responseOrder.ResponseError($"【上位系统】订单下发:【plmeid】[{entity.plmeid}]工厂编码【factory】不能为空值,请检查!");
                return responseOrder;
            }
            if (string.IsNullOrEmpty(entity.line_code))
            {
                responseOrder.ResponseError($"【上位系统】订单下发:【plmeid】[{entity.plmeid}]产线编码【line_code】不能为空值,请检查!");
                return responseOrder;
            }
            if (entity.details.Any(x => string.IsNullOrWhiteSpace(x.mater_code)))
            {
                responseOrder.ResponseError($"【上位系统】订单下发:【plmeid】[{entity.plmeid}]物料编码【mater_code】不能为空值,请检查!");
                return responseOrder;
            }
            #endregion

            #region 生产订单的产品号要先存在工艺路线的产品表中
            ProductHeader = base.Context.Queryable<base_product_header>().First(x => x.productCode == entity.product_code && x.isDelete == AddOrUpdateFlag);
            if (ProductHeader == null)
            {
                responseOrder.ResponseError($"【上位系统】【plmeid】[{entity.plmeid}]工艺路线产品表【产品编码productCode】[{entity.product_code}]不存在,请【上位系统】先发送工艺线路基础数据!");
                return responseOrder;
            }
            #endregion

            #region 线体映射
            var line = base.Context.Queryable<base_line>().First(x => x.otherCode == entity.line_code);
            if (line == null || string.IsNullOrEmpty(line.lineCode))
            {
                responseOrder.ResponseError($"订单下发:【plmeid】[{entity.plmeid}]没有查询到线体【line_code】和华恒线体一致的数据,请通知管理员在【工厂模型->线体设置】维护外部编码!");
                return responseOrder;
            }
            LineCode = line.lineCode;
            #endregion

            #region 生产订单查询工艺路线基础信息
            //去除厂线筛选 ProcessHead = base.Context.Queryable<base_process_route_head>().First(x => x.lineCode == LineCode && x.productHeaderCode == MomEntity.product_code && x.edition == MomEntity.edition && x.isDelete == AddOrUpdateFlag);
            ProcessHead = base.Context.Queryable<base_process_route_head>().First(x => x.productHeaderCode == entity.product_code && x.edition == entity.edition && x.isDelete == AddOrUpdateFlag);
            if (ProcessHead == null || string.IsNullOrEmpty(ProcessHead.lineCode))
            {
                responseOrder.ResponseError($"【上位系统】订单下发:【plmeid】[{entity.plmeid}]没有查询到工艺路线【lineCode】【{LineCode}】【processCode】【{entity.product_code}】对应的工艺路线,请先发送工艺路线接口数据!");
                return responseOrder;
            }
            #endregion

            #region 生产订单数据
            foreach (var item in entity.details)
            {
                var isExt = base.Context.Queryable<base_material>().Any(x => x.materialCode == item.mater_code && x.isDelete == AddOrUpdateFlag);
                if (isExt) continue;
                responseOrder.ResponseError($"【上位系统】订单下发:【plmeid】[{entity.plmeid}]没有查询到物料主数据【mater_code】【{item.mater_code}】对应的信息,请先发送物料主数据接口数据!");
                return responseOrder;
            }
            #endregion

            return responseOrder;
        }

        /// <summary>
        /// 生成数据
        /// </summary>
        /// <returns></returns>
        private ValueTuple<bus_workOrder_head, List<bus_workOrder_detail>, List<bus_workOrder_detail_material>, List<base_inventory>, List<bus_workOrder_material_use_log>, List<bus_workReport_materialUselog_eqProcessTem_rel>> HandleAcceptOrderData()
        {
            var busWorkOrderHead = new bus_workOrder_head();
            var busWorkOrderDetailList = new List<bus_workOrder_detail>();
            var busWorkOrderDetailMaterialList = new List<bus_workOrder_detail_material>();
            var inventoryList = new List<base_inventory>();
            var materialUseLogList = new List<bus_workOrder_material_use_log>();
            var materialUselogEqProcessTemRel = new List<bus_workReport_materialUselog_eqProcessTem_rel>();

            #region  生成工序任务头 bus_workOrder_head
            busWorkOrderHead = new bus_workOrder_head
            {
                keys = Guid.NewGuid(),
                plmeId = entity.plmeid,
                workOrderCode = entity.pro_order_code,
                planCode = entity.plan_code,
                otherOrderCode = entity.plan_code,

                productHeaderCode = entity.product_code,
                processHeadKeys = ProductHeader.processHeadKeys,
                processCode = ProductHeader.processCode,
                lineCode = LineCode,
                planStartTime = entity.playdate,
                planEndTime = entity.enddate,
 
                state = (int)EnumOrderHeadStatus.初始化,
                isDelete = AddOrUpdateFlag,
                createTime = DateTime.Now,
                createBy = SystemVariable.DefaultCreated
            };
            #endregion

            #region  生成工序任务明细 busWorkOrderDetailList
            ProcessBody = Context.Queryable<base_process_route_detail>().Where(x => x.headkeys == ProcessHead.keys && x.isDelete==1).OrderBy(t => t.oprSequence).ToList();
            foreach (var item in ProcessBody)
            {
                var busWorkOrderDetail = new bus_workOrder_detail
                {
                    headKeys = busWorkOrderHead.keys,
                    bodyKeys = Guid.NewGuid(),
                    productHeaderCode = busWorkOrderHead.productHeaderCode,
                    workOrderCode = busWorkOrderHead.workOrderCode,
                    lineCode = item.LineCode,
                    serialNumber = item.oprSequence,
                    oprSequenceCode = item.oprSequenceCode,
                    oprSequenceName = item.oprSequenceName,
                    workCenterCode = item.workCenterCode,
                    planStartTime = item.oprPlanEndTime == null ? busWorkOrderHead.planStartTime : item.oprPlanStartTime,
                    planEndTime = item.oprPlanEndTime == null ? busWorkOrderHead.planEndTime : item.oprPlanEndTime,
                    isDelete = AddOrUpdateFlag,
                    state = (int)EnumOrderBodyStatus.初始化,
                    workReportStatus = (int)EnumWorkReportStatus.未报工,
                    createTime = DateTime.Now,
                    createBy = SystemVariable.DefaultCreated
                };
                busWorkOrderDetailList.Add(busWorkOrderDetail);
            }
            // 设置工序任务头的当前工序,为第一个工序任务明细的工序
            if (busWorkOrderDetailList.Count > 0)
            {
                busWorkOrderHead.nowOprSequenceCode = busWorkOrderDetailList[0].oprSequenceCode;
            }
            #endregion

            #region  生成工序任务明细需求物料 busWorkOrderDetailMaterialList
            foreach (var item in entity.details)
            {
                var busWorkOrderDetail = busWorkOrderDetailList.FirstOrDefault(t => t.workCenterCode == item.station_code);
                if (busWorkOrderDetail == null)
                {
                    continue;
                }
                var busWorkOrderDetailMaterial = new bus_workOrder_detail_material
                {
                    headKey = busWorkOrderHead.keys,
                    bodyKey = busWorkOrderDetail?.bodyKeys,
                    productCode = busWorkOrderHead.productHeaderCode,
                    materialCode = item.mater_code,
                    materialName = item.mater_name,
                    workOrderCode = busWorkOrderHead.workOrderCode,

                    num = item.qty,
                    wh_code = item.wh_code,
                    lineCode = busWorkOrderHead.lineCode,
                    workCenterCode = item.station_code,
                    isDelete = AddOrUpdateFlag,
                    createTime = DateTime.Now,
                    createBy = SystemVariable.DefaultCreated
                };
                busWorkOrderDetailMaterialList.Add(busWorkOrderDetailMaterial);
            }
            #endregion

            #region  生成库存实体 inventoryList、物料消耗明细 bus_workOrder_material_use_log、工序明细和物料使用记录关系表 bus_workReport_materialUselog_eqProcessTem_rel
            //库存信息
            foreach (var item in busWorkOrderDetailMaterialList)
            {
                var busWorkOrderDetail = busWorkOrderDetailList.FirstOrDefault(t => t.bodyKeys == item.bodyKey);
                var inventory = new base_inventory
                {
                    headKey = busWorkOrderHead.keys,
                    oprSequenceCode = busWorkOrderDetail?.oprSequenceCode,
                    workOrderCode = busWorkOrderHead.workOrderCode,
                    lineCode = busWorkOrderHead.lineCode,
                    whCode = item.wh_code,
                    status = InventoryStatus.discussed.ToString(),
                    useState = 0,
                    materialCode = item.materialCode,
                    quantityRequired = item.num,
                    quantityReceived = 0,
                    qty = 0,
                    consumedQuantity = 0,
                    createTime = DateTime.Now,
                    createBy = SystemVariable.DefaultCreated
                };
                inventoryList.Add(inventory);

                #region 生成物料使用记录
                var material = Context.Queryable<base_material>().First(x => x.materialCode == item.materialCode);
                var materialUselog = new bus_workOrder_material_use_log
                {
                    keys = Guid.NewGuid(),
                    productHeaderCode = busWorkOrderHead.productHeaderCode,
                    lineCode = busWorkOrderHead.lineCode,
                    materialCode = item.materialCode,
                    materialName = item.materialName,
                    qyt = item.num,
                    employ = (int)EnumUseLog.未使用,
                    crux = material?.crux,
                    workOrderCode = busWorkOrderHead.workOrderCode,
                    oprSequenceCode = busWorkOrderDetail.oprSequenceCode,
                    oprSequenceName = busWorkOrderDetail.oprSequenceName,
                    stationCode = busWorkOrderDetail.stationCode,
                    equipmentCode = busWorkOrderDetail.equipmentCode,
                    review_code = item.materialCode,
                    isDelete = AddOrUpdateFlag,
                    createTime = DateTime.Now,
                    createBy = SystemVariable.DefaultCreated
                };
                materialUseLogList.Add(materialUselog);
                #endregion

                #region 工序明细和物料使用记录关系表 bus_workReport_materialUselog_eqProcessTem_rel

                var materialUselogEqProcessTemRelItem = new bus_workReport_materialUselog_eqProcessTem_rel
                {
                    bodyKeys = item.bodyKey == null ? Guid.Empty : Guid.Parse(item.bodyKey.ToString()),
                    materialUseLogKeys = materialUselog.keys,
                    createTime = DateTime.Now,
                    createBy = SystemVariable.DefaultCreated
                };
                materialUselogEqProcessTemRel.Add(materialUselogEqProcessTemRelItem);
                #endregion
            }
            #endregion
            return (busWorkOrderHead, busWorkOrderDetailList, busWorkOrderDetailMaterialList, inventoryList, materialUseLogList, materialUselogEqProcessTemRel);
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        private ResponseUpstream<string> SaveHandleAcceptOrderData(bus_workOrder_head busWorkOrderHead, List<bus_workOrder_detail> busWorkOrderDetailList
            , List<bus_workOrder_detail_material> busWorkOrderDetailMaterial, List<base_inventory> inventoryList, List<bus_workOrder_material_use_log> materialUseLogList, List<bus_workReport_materialUselog_eqProcessTem_rel> materialUselogEqProcessTemRel)
        {
            int resultCount = 0;
            if (busWorkOrderDetailList == null || busWorkOrderDetailList.Count == 0)
            {
                responseOrder.ResponseError($"【上位系统】订单下发:【plmeid】[{entity.plmeid}]工序任务明细生成失败,请确认请先发送工艺路线接口数据,反复出现请联系管理员!");
                return responseOrder;
            }

            //if (busWorkOrderDetailList.Count != ProcessBody.Count)
            //{
            //    responseOrder.ResponseError($"【上位系统】订单下发:工艺路线工序【{ProcessBody.Count}】和订单接口数据工序【{busWorkOrderDetailList.Count}】不一致,反复出现请联系管理员!");
            //    return responseOrder;
            //}

            //新增
            if (entity.type == EnumAction.I.ToString())
            {
                if (Context.Queryable<bus_workOrder_head>().Any(t => t.plmeId == entity.plmeid && t.isDelete == AddOrUpdateFlag))
                {
                    responseOrder.ResponseError($"【上位系统】订单信息【plmeid】[{entity.plmeid}]已存在,请勿重复添加!");
                    return responseOrder;
                }

                Context.Insertable(busWorkOrderHead).AddQueue();
                Context.Insertable(busWorkOrderDetailList).AddQueue();
                Context.Insertable(busWorkOrderDetailMaterial).AddQueue();
                Context.Insertable(inventoryList).AddQueue();

                Context.Insertable(materialUseLogList).AddQueue();
                Context.Insertable(materialUselogEqProcessTemRel).AddQueue();
            }
            //更新
            else if (entity.type == EnumAction.U.ToString())
            {
                var head = Context.Queryable<bus_workOrder_head>().First(t => t.plmeId == entity.plmeid && t.isDelete == AddOrUpdateFlag);
                if (head == null)
                {
                    responseOrder.ResponseError($"【上位系统】订单信息更新【plmeid】[{entity.plmeid}],订单不存在或已删除!");
                    return responseOrder;
                }
                else if (head.state != (int)EnumOrderHeadStatus.初始化)
                {
                    responseOrder.ResponseError($"【上位系统】订单信息更新【plmeid】[{entity.plmeid}],只能更新“初始化”状态的订单!");
                    return responseOrder;
                }
                busWorkOrderHead.keys = head.keys;
                busWorkOrderHead.updateTime = DateTime.Now;
                busWorkOrderDetailList.ForEach(x =>
                {
                    x.headKeys = head.keys;
                    x.updateTime = DateTime.Now;
                });
                busWorkOrderDetailMaterial.ForEach(x =>
                {
                    x.headKey = head.keys;
                    x.updateTime = DateTime.Now;
                });

                Context.Updateable(busWorkOrderHead)
                       .IgnoreColumns(x => new { x.createBy, x.createTime, x.keys })
                       .WhereColumns(x => x.keys).AddQueue();
                Context.Updateable(busWorkOrderDetailList)
                       .IgnoreColumns(x => new { x.createBy, x.createTime, x.bodyKeys, x.headKeys })
                       .WhereColumns(x => new { x.headKeys, x.oprSequenceCode }).AddQueue();
                Context.Updateable(busWorkOrderDetailMaterial)
                       .IgnoreColumns(x => new { x.createBy, x.createTime, x.bodyKey, x.headKey })
                       .WhereColumns(x => new { x.headKey, x.workCenterCode }).AddQueue();
                Context.Updateable(inventoryList)
                       .UpdateColumns(x => new { x.updateBy, x.updateTime, x, x.quantityRequired })
                       .WhereColumns(x => new { x.headKey, x.oprSequenceCode, x.materialCode }).AddQueue();
            }

            resultCount = ExecuteQueues(base.Context);
            return (ResponseUpstream<string>)(resultCount > 0 ? responseOrder.ResponseSuccess() : responseOrder.ResponseError());
        }

        private string GetIndexString(int sequenceIndex)
        {
            string strIndex = sequenceIndex.ToString();
            while (strIndex.Length < 4)
            {
                strIndex = "0" + strIndex;
            }
            return strIndex;
        }
    }
}