private void BuildLotNumber()
 {
     lotNumber.Text = LotNumberParser.BuildLotNumber(new LotKeyImplementation
     {
         LotKey_DateCreated  = lotDatePicker.Value,
         LotKey_DateSequence = (int)lotDateSequence.Value,
         LotKey_LotTypeId    = (int)lotTypeId.Value
     }).ToString();
     SetQuery();
 }
Example #2
0
        private IEnumerable<tblBatchItem> CreateBatchItems(ProductionBatch batch, IDictionary<int, tblBOM> daBOMs)
        {
            var lotNumber = LotNumberParser.BuildLotNumber(batch);
            foreach(var pickedItem in batch.Production.PickedInventory.Items)
            {
                var availableQuantity = pickedItem.Quantity;
                var inventory = _unitOfWork.InventoryRepository.FindByKey(new InventoryKey(pickedItem));
                if(inventory != null)
                {
                    availableQuantity += inventory.Quantity;
                }
                var weight = pickedItem.PackagingProduct.Weight;
                var avaiableWeight = availableQuantity * weight;

                int? astaCalc = null;
                var asta = pickedItem.Lot.Attributes.FirstOrDefault(a => a.AttributeShortName == StaticAttributeNames.Asta.ShortName);
                if(asta != null)
                {
                    var productionDate = asta.AttributeDate;
                    if(batch.Production.Results != null)
                    {
                        productionDate = batch.Production.Results.ProductionEnd;
                    }
                    astaCalc = AstaCalculator.CalculateAsta(asta.AttributeValue, asta.AttributeDate, productionDate, DateTime.UtcNow);
                }

                yield return new tblBatchItem
                    {
                        EntryDate = pickedItem.PickedInventory.TimeStamp.ConvertUTCToLocal(),
                        Lot = LotNumberParser.BuildLotNumber(pickedItem),
                        TTypeID = (int?)TransType.Batching,
                        PkgID = int.Parse(pickedItem.Lot.LotTypeEnum == LotTypeEnum.Packaging ? pickedItem.Lot.PackagingLot.PackagingProduct.Product.ProductCode : pickedItem.PackagingProduct.Product.ProductCode),
                        Tote = pickedItem.ToteKey,
                        Quantity = pickedItem.Quantity,
                        NetWgt = (decimal?)weight,
                        TtlWgt = (decimal?)(pickedItem.Quantity * weight),
                        LocID = pickedItem.FromLocation.LocID.Value,
                        TrtmtID = pickedItem.TreatmentId,
                        EmployeeID = pickedItem.PickedInventory.EmployeeId,
                        NewLot = lotNumber,
                        BatchLot = lotNumber,
                        AstaCalc = astaCalc,
                        AvgAsta = asta == null ? null : (decimal?)asta.AttributeValue,
                        //ODetail = 
                        PackSchID = batch.PackSchedule.PackSchID,
                        AQ = availableQuantity,
                        AW = (decimal?)avaiableWeight,
                        LoBac = batch.Production.ResultingChileLot.AllAttributesAreLoBac,
                    
                        tblBOM = GetDaBOM(daBOMs, pickedItem)
                    };
            }
        }
Example #3
0
        private void SetPickedInventory(InventoryShipmentOrder newOrder, tblMove oldOrder, ref bool commitNewContext)
        {
            var MDetail            = OldContext.tblMoveDetails.Any() ? OldContext.tblMoveDetails.Max(m => m.MDetail).AddSeconds(1) : DateTime.UtcNow.ConvertUTCToLocal();
            var oldDetailsToRemove = oldOrder.tblMoveDetails.ToList();

            foreach (var newItem in newOrder.PickedInventory.Items)
            {
                var oldItem = oldDetailsToRemove.FirstOrDefault(d => d.MDetail == newItem.DetailID) ?? oldDetailsToRemove.FirstOrDefault();
                if (oldItem == null)
                {
                    oldItem = new tblMoveDetail
                    {
                        MDetail = MDetail
                    };
                    OldContext.tblMoveDetails.AddObject(oldItem);
                    MDetail = MDetail.AddSeconds(1);
                }
                else
                {
                    oldDetailsToRemove.Remove(oldItem);
                }

                oldItem.MoveNum         = newOrder.MoveNum.Value;
                oldItem.Lot             = LotNumberParser.BuildLotNumber(newItem);
                oldItem.TTypeID         = (int?)newOrder.OrderType.ToTransType();
                oldItem.PkgID           = OldContextHelper.GetPackaging(newItem.PackagingProduct).PkgID;
                oldItem.Quantity        = newItem.Quantity;
                oldItem.NetWgt          = (decimal?)newItem.PackagingProduct.Weight;
                oldItem.TtlWgt          = (decimal?)(newItem.Quantity * newItem.PackagingProduct.Weight);
                oldItem.LocID           = newItem.FromLocation.LocID.Value;
                oldItem.Move2           = newItem.CurrentLocation.LocID.Value;
                oldItem.TrtmtID         = OldContextHelper.GetTreatment(newItem).TrtmtID;
                oldItem.EmployeeID      = newOrder.PickedInventory.EmployeeId;
                oldItem.CustProductCode = newItem.CustomerProductCode;
                oldItem.CustLot         = newItem.CustomerLotCode;

                if (newItem.DetailID != oldItem.MDetail)
                {
                    commitNewContext = true;
                    newItem.DetailID = oldItem.MDetail;
                }
            }

            foreach (var o in oldDetailsToRemove)
            {
                OldContext.tblMoveDetails.DeleteObject(o);
            }
        }
        private void ParseLotNumber()
        {
            int lotNum;

            if (int.TryParse(lotNumber.Text, out lotNum))
            {
                LotKey lotKey;
                if (LotNumberParser.ParseLotNumber(lotNum, out lotKey))
                {
                    lotDatePicker.Value   = lotKey.LotKey_DateCreated;
                    lotDateSequence.Value = lotKey.LotKey_DateSequence;
                    lotTypeId.Value       = lotKey.LotKey_LotTypeId;
                }
                SetQuery();
            }
        }
Example #5
0
        public override void Synchronize(Func <LotKey> getInput)
        {
            if (getInput == null)
            {
                throw new ArgumentNullException("getInput");
            }
            var lotKey = getInput();

            var productionBatch = UnitOfWork.ProductionBatchRepository.FindByKey(lotKey,
                                                                                 b => b.PackSchedule.WorkType,
                                                                                 b => b.Production.PickedInventory.Items.Select(i => i.PackagingProduct.Product),
                                                                                 b => b.Production.PickedInventory.Items.Select(i => i.FromLocation),
                                                                                 b => b.Production.PickedInventory.Items.Select(i => i.Lot.Attributes),
                                                                                 b => b.Production.PickedInventory.Items.Select(i => i.Lot.PackagingLot.PackagingProduct.Product),
                                                                                 b => b.Production.Results,
                                                                                 b => b.Production.ResultingChileLot.Lot.Attributes.Select(a => a.AttributeName),
                                                                                 b => b.Production.ResultingChileLot.ChileProduct.Ingredients.Select(i => i.AdditiveType));

            if (productionBatch == null)
            {
                throw new Exception(string.Format("Could not find ProductionBatch[{0}] in new context.", lotKey.KeyValue));
            }

            var lotNumber = LotNumberParser.BuildLotNumber(productionBatch);
            var lotSelect = OldContext.tblLots
                            .Where(l => l.Lot == lotNumber)
                            .Select(l => new
            {
                Lot = l,
                l.tblBOMs,
                l.inputBatchItems,
                l.tblLotAttributeHistory
            })
                            .FirstOrDefault();

            if (lotSelect == null)
            {
                throw new Exception(string.Format("Could not find tblLot[{0}] in old context.", lotNumber));
            }

            new SyncProductionBatchPickedInventoryHelper(UnitOfWork, OldContext).SetBOMBatchItems(productionBatch, lotSelect.Lot);

            OldContext.SaveChanges();

            Console.WriteLine(ConsoleOutput.SetPickedItemsForLot, lotNumber);
        }
Example #6
0
            public void Resolved_defect_will_not_be_taken_into_account_for_LotStat_evaluation()
            {
                //Arrange
                tblLot oldLot;

                using (var oldContext = new RioAccessSQLEntities())
                {
                    oldLot = oldContext.tblLots.OrderByDescending(l => l.EntryDate).FirstOrDefault(l => l.LotStat == (int)LotStat.Asta);
                }

                if (oldLot == null)
                {
                    Assert.Inconclusive("Could not find valid tblLot record for testing.");
                }

                var lotKey = LotNumberParser.ParseLotNumber(oldLot.Lot);
                var newLot = RVCUnitOfWork.LotRepository.FindByKey(lotKey, l => l.Attributes);

                //Act
                var result = Service.SetLotAttributes(new SetLotAttributeParameters
                {
                    UserToken  = TestUser.UserName,
                    LotKey     = lotKey,
                    Attributes = newLot.Attributes.ToDictionary(a => a.ToAttributeNameKey().KeyValue, a => new AttributeValueParameters
                    {
                        AttributeInfo = new AttributeInfoParameters
                        {
                            Value = a.AttributeValue,
                            Date  = a.AttributeDate
                        },
                        Resolution = new DefectResolutionParameters
                        {
                            Description    = "Test!",
                            ResolutionType = ResolutionTypeEnum.AcceptedByUser
                        }
                    } as IAttributeValueParameters)
                });

                //Assert
                result.AssertSuccess();
                using (var oldContext = new RioAccessSQLEntities())
                {
                    var synchedLot = oldContext.tblLots.FirstOrDefault(l => l.Lot == oldLot.Lot);
                    Assert.AreNotEqual((int)LotStat.Asta, synchedLot.LotStat);
                }
            }
        protected override IEnumerable <Inventory> BirthRecords()
        {
            LoadCount.Reset();

            foreach (var inventoryByLot in SelectLotsToLoad())
            {
                var inventory = inventoryByLot.ToList();
                LoadCount.AddRead(EntityTypes.Inventory, (uint)inventory.Count);

                LotKey lotKey;
                if (!LotNumberParser.ParseLotNumber(inventoryByLot.Key, out lotKey))
                {
                    Log(new CallbackParameters(CallbackReason.InvalidLotNumber)
                    {
                        InventoryByLot = inventoryByLot
                    });
                    continue;
                }

                var lot = GetLot(lotKey);
                if (lot == null)
                {
                    Log(new CallbackParameters(CallbackReason.LotNotLoaded)
                    {
                        LotKey         = lotKey,
                        InventoryByLot = inventoryByLot
                    });
                    continue;
                }

                foreach (var inventoryItem in inventory)
                {
                    var newInventory = CreateInventory(inventoryItem, lot);
                    if (newInventory == null)
                    {
                        continue;
                    }

                    LoadCount.AddLoaded(EntityTypes.Inventory);
                    yield return(newInventory);
                }
            }

            LoadCount.LogResults(l => Log(new CallbackParameters(l)));
        }
Example #8
0
            public void Will_not_create_new_tblLotHistory_record_if_new_defect_does_not_result_in_a_LotStat_change()
            {
                //Arrange
                ChileLot chileLot;

                using (var oldContext = new RioAccessSQLEntities())
                {
                    chileLot = oldContext.tblLots
                               .Where(l => l.LotStat == (int)LotStat.See_Desc)
                               .Select(l => l.Lot)
                               .ToList()
                               .Select(l =>
                    {
                        var lotKey = LotNumberParser.ParseLotNumber(l);
                        var lot    = RVCUnitOfWork.ChileLotRepository.FindByKey(lotKey, c => c.Lot.LotDefects.Select(d => d.Resolution));
                        return(lot.Lot.QualityStatus == LotQualityStatus.Released ? lot : null);
                    })
                               .FirstOrDefault(c => c != null);
                }

                if (chileLot == null)
                {
                    throw new Exception("Could not find test ChileLot.");
                }
                var lotNumber = LotNumberBuilder.BuildLotNumber(chileLot);
                var expectedLotAttributeHistories = new RioAccessSQLEntities().tblLotAttributeHistories.Count(h => h.Lot == lotNumber);

                //Act
                var result = Service.CreateLotDefect(new CreateLotDefectParameters
                {
                    UserToken   = TestUser.UserName,
                    LotKey      = chileLot.ToLotKey(),
                    DefectType  = DefectTypeEnum.InHouseContamination,
                    Description = "unmapped defect"
                });
                var lotString = GetKeyFromConsoleString(ConsoleOutput.UpdatedLot);

                //Assert
                result.AssertSuccess();
                MockKillSwitch.Verify(k => k.Engage(), Times.Never());

                Assert.AreEqual(lotNumber, int.Parse(lotString));
                Assert.AreEqual(expectedLotAttributeHistories, new RioAccessSQLEntities().tblLotAttributeHistories.Count(h => h.Lot == lotNumber));
            }
Example #9
0
 private tblOutgoing CreateOutgoing(InventoryShipmentOrder order, PickedInventoryItem item, Location location, int quantity, bool forMove)
 {
     return(new tblOutgoing
     {
         EntryDate = DateTime.UtcNow.ConvertUTCToLocal().RoundMillisecondsForSQL(),
         Lot = LotNumberParser.BuildLotNumber(item),
         TTypeID = (int?)order.OrderType.ToTransType(),
         PkgID = OldContextHelper.GetPackaging(item.PackagingProduct).PkgID,
         Tote = item.ToteKey,
         Quantity = quantity,
         NetWgt = (decimal?)item.PackagingProduct.Weight,
         TtlWgt = (decimal?)(quantity * item.PackagingProduct.Weight),
         LocID = (int)location.LocID,
         TrtmtID = OldContextHelper.GetTreatment(item).TrtmtID,
         EmployeeID = order.EmployeeId,
         BOMID = 0,
         BatchLot = 0,
         MoveNum = forMove ? order.MoveNum : null,
         MDetail = forMove ? item.DetailID : null,
         OrderNum = !forMove ? order.MoveNum : null,
         ODetail = !forMove ? item.DetailID : null,
         CustProductCode = item.CustomerProductCode
     });
 }
Example #10
0
        private void SyncPickedItems(tblOrder tblOrder, SalesOrderItem orderItem, ref DateTime lastEntryDate, tblOrderDetail detail)
        {
            var stagedToDelete = detail.tblStagedFGs.ToDictionary(s => s.EntryDate);

            foreach (var picked in orderItem.PickedItems ?? new List <SalesOrderPickedItem>())
            {
                tblStagedFG staged;
                if (picked.PickedInventoryItem.DetailID != null && stagedToDelete.TryGetValue(picked.PickedInventoryItem.DetailID.Value, out staged))
                {
                    stagedToDelete.Remove(staged.EntryDate);
                }
                else
                {
                    lastEntryDate = lastEntryDate.AddSeconds(1);
                    staged        = new tblStagedFG
                    {
                        EntryDate = lastEntryDate,
                        s_GUID    = Guid.NewGuid()
                    };
                    detail.tblStagedFGs.Add(staged);
                    picked.PickedInventoryItem.DetailID = staged.EntryDate;
                    _commitNewContext = true;
                }

                var packaging = OldContextHelper.GetPackaging(picked.PickedInventoryItem.PackagingProduct);
                var treatment = OldContextHelper.GetTreatment(picked.PickedInventoryItem);

                staged.OrderNum        = tblOrder.OrderNum;
                staged.ODetail         = detail.ODetail;
                staged.Lot             = LotNumberParser.BuildLotNumber(picked.PickedInventoryItem);
                staged.TTypeID         = (int?)TransType.Batching; //To match logic found in Access (apnd_PickProdTemp) - RI 2016-3-15
                staged.PkgID           = packaging.PkgID;
                staged.Quantity        = picked.PickedInventoryItem.Quantity;
                staged.NetWgt          = packaging.NetWgt;
                staged.TtlWgt          = picked.PickedInventoryItem.Quantity * packaging.NetWgt;
                staged.LocID           = picked.PickedInventoryItem.CurrentLocation.LocID.Value;
                staged.TrtmtID         = treatment.TrtmtID;
                staged.EmployeeID      = picked.PickedInventoryItem.PickedInventory.EmployeeId;
                staged.CustProductCode = picked.PickedInventoryItem.CustomerProductCode;
                staged.CustLot         = picked.PickedInventoryItem.CustomerLotCode;

                staged.AstaCalc = null;
                var asta = picked.PickedInventoryItem.Lot.Attributes.FirstOrDefault(a => a.AttributeShortName == GlobalKeyHelpers.AstaAttributeNameKey.AttributeNameKey_ShortName);
                if (asta != null)
                {
                    var productionEnd = asta.AttributeDate;
                    if (picked.PickedInventoryItem.Lot.ChileLot != null && picked.PickedInventoryItem.Lot.ChileLot.Production != null && picked.PickedInventoryItem.Lot.ChileLot.Production.Results != null)
                    {
                        productionEnd = picked.PickedInventoryItem.Lot.ChileLot.Production.Results.ProductionEnd;
                    }
                    staged.AstaCalc = AstaCalculator.CalculateAsta(asta.AttributeValue, asta.AttributeDate, productionEnd, DateTime.UtcNow);
                }

                staged.LoBac = false;
                if (picked.PickedInventoryItem.Lot.ChileLot != null)
                {
                    staged.LoBac = picked.PickedInventoryItem.Lot.ChileLot.AllAttributesAreLoBac;
                }
            }

            foreach (var staged in stagedToDelete.Values)
            {
                OldContext.tblStagedFGs.DeleteObject(staged);
            }
        }
Example #11
0
        protected override IEnumerable <InstructionResult> BirthRecords()
        {
            _loadCount.Reset();
            var instructions = new HashSet <string>();

            foreach (var oldInstructionsByLot in SelectBatchInstructionsToLoad(OldContext).GroupBy(i => i.Lot))
            {
                var lastSequence = 0;
                foreach (var oldInstruction in oldInstructionsByLot.OrderBy(i => i.Step))
                {
                    _loadCount.AddRead(EntityTypes.Note);

                    if (string.IsNullOrWhiteSpace(oldInstruction.Action))
                    {
                        Log(new CallbackParameters(CallbackReason.EmptyAction)
                        {
                            Instruction = oldInstruction
                        });
                        continue;
                    }

                    var lotKey = LotNumberParser.ParseLotNumber(oldInstruction.Lot);
                    if (lotKey == null)
                    {
                        Log(new CallbackParameters(CallbackReason.InvalidLotKey)
                        {
                            Instruction = oldInstruction
                        });
                        continue;
                    }

                    var notebookKey = _newContextHelper.GetBatchInstructionNotebookKeyByLotKey(lotKey);
                    if (notebookKey == null)
                    {
                        Log(new CallbackParameters(CallbackReason.NotebookNotLoaded)
                        {
                            Instruction = oldInstruction
                        });
                        continue;
                    }

                    var         instruction    = new string(oldInstruction.Action.Take(Constants.StringLengths.InstructionText).ToArray());
                    Instruction newInstruction = null;
                    if (!instructions.Contains(instruction))
                    {
                        _loadCount.AddRead(EntityTypes.Instruction);
                        newInstruction = new Instruction
                        {
                            InstructionText = instruction,
                            InstructionType = InstructionType.ProductionBatchInstruction
                        };
                        instructions.Add(instruction);
                        _loadCount.AddLoaded(EntityTypes.Instruction);
                    }

                    var sequence = oldInstruction.Step.Value;
                    if (sequence <= lastSequence)
                    {
                        sequence = lastSequence + 1;
                    }
                    lastSequence = sequence;

                    var newNote = new Note
                    {
                        EmployeeId       = _newContextHelper.DefaultEmployee.EmployeeId,
                        TimeStamp        = oldInstruction.EntryDate.ConvertLocalToUTC(),
                        NotebookDate     = notebookKey.NotebookKey_Date,
                        NotebookSequence = notebookKey.NotebookKey_Sequence,
                        Sequence         = sequence,
                        Text             = oldInstruction.Action
                    };
                    SerializableBatchInstruction.DeserializeIntoNote(newNote, oldInstruction.Serialized);

                    _loadCount.AddLoaded(EntityTypes.Note);
                    yield return(new InstructionResult
                    {
                        Note = newNote,
                        Instruction = newInstruction
                    });
                }
            }

            _loadCount.LogResults(s => Log(new CallbackParameters(s)));
        }
Example #12
0
        protected override IEnumerable <ChileLotProduction> BirthRecords()
        {
            _loadCount.Reset();

            foreach (var lot in SelectMillAndWetdownToLoad(OldContext))
            {
                _loadCount.AddRead(EntityTypes.ChileLotProduction);

                LotKey lotKey;
                if (!LotNumberParser.ParseLotNumber(lot.Lot, out lotKey))
                {
                    Log(new CallbackParameters(CallbackReason.InvalidLotNumber)
                    {
                        Lot = lot
                    });
                    continue;
                }

                var chileLot = _newContextHelper.GetChileLotWithProduct(lotKey);
                if (chileLot == null)
                {
                    Log(new CallbackParameters(CallbackReason.ChileLotNotLoaded)
                    {
                        Lot    = lot,
                        LotKey = lotKey
                    });
                    continue;
                }

                bool     usedDefaultProductionLine;
                DateTime entryDate;
                var      productionResults = CreateLotProductionResults(chileLot, lot, out usedDefaultProductionLine, out entryDate);
                if (productionResults == null)
                {
                    continue;
                }

                var pickedInventory = CreatePickedInventory(entryDate, lot);
                if (pickedInventory == null)
                {
                    continue;
                }

                var production = new ChileLotProduction
                {
                    EmployeeId = productionResults.EmployeeId,
                    TimeStamp  = entryDate,

                    LotDateCreated  = chileLot.LotDateCreated,
                    LotDateSequence = chileLot.LotDateSequence,
                    LotTypeId       = chileLot.LotTypeId,

                    ProductionType             = ProductionType.MillAndWetdown,
                    PickedInventoryDateCreated = pickedInventory.DateCreated,
                    PickedInventorySequence    = pickedInventory.Sequence,

                    Results         = productionResults,
                    PickedInventory = pickedInventory,
                };

                if (usedDefaultProductionLine)
                {
                    Log(new CallbackParameters(CallbackReason.DefaultProductionLine)
                    {
                        Lot            = lot,
                        ProductionLine = production.Results.ProductionLineLocation
                    });
                }

                _loadCount.AddLoaded(EntityTypes.ChileLotProduction);
                _loadCount.AddLoaded(EntityTypes.PickedInventory);
                _loadCount.AddLoaded(EntityTypes.PickedInventoryItem, (uint)production.PickedInventory.Items.Count);
                _loadCount.AddLoaded(EntityTypes.LotProductionResults);
                _loadCount.AddLoaded(EntityTypes.LotProductionResultItem, (uint)production.Results.ResultItems.Count);

                yield return(production);
            }

            _loadCount.LogResults(l => Log(new CallbackParameters(l)));
        }
Example #13
0
        private IEnumerable <PickedInventoryItem> CreatePickedInventoryItems(IPickedInventoryKey pickedInventoryKey, IEnumerable <OutgoingDTO> outgoings)
        {
            var pickedItemSequence = 0;

            foreach (var outgoing in outgoings)
            {
                _loadCount.AddRead(EntityTypes.PickedInventoryItem);

                LotKey lotKey;
                if (!LotNumberParser.ParseLotNumber(outgoing.Lot, out lotKey))
                {
                    Log(new CallbackParameters(CallbackReason.OutgoingInvalidLotNumber)
                    {
                        Outgoing = outgoing
                    });
                    continue;
                }

                if (!_newContextHelper.LotLoaded(lotKey))
                {
                    Log(new CallbackParameters(CallbackReason.OutgoingLotNotLoaded)
                    {
                        Outgoing = outgoing
                    });
                    continue;
                }

                var packagingProduct = outgoing.PTypeID == (int?)LotTypeEnum.Packaging ? _newContextHelper.NoPackagingProduct : _newContextHelper.GetPackagingProduct(outgoing.PkgID);
                if (packagingProduct == null)
                {
                    Log(new CallbackParameters(CallbackReason.OutgoingPackagingNotLoaded)
                    {
                        Outgoing = outgoing
                    });
                    continue;
                }

                var warehouseLocation = _newContextHelper.GetLocation(outgoing.LocID);
                if (warehouseLocation == null)
                {
                    Log(new CallbackParameters(CallbackReason.OutgoingWarehouseLocationNotLoaded)
                    {
                        Outgoing = outgoing
                    });
                    continue;
                }

                var treatment = _newContextHelper.GetInventoryTreatment(outgoing.TrtmtID);
                if (treatment == null)
                {
                    Log(new CallbackParameters(CallbackReason.OutgoingTreatmentNotLoaded)
                    {
                        Outgoing = outgoing
                    });
                    continue;
                }

                yield return(new PickedInventoryItem
                {
                    DateCreated = pickedInventoryKey.PickedInventoryKey_DateCreated,
                    Sequence = pickedInventoryKey.PickedInventoryKey_Sequence,
                    ItemSequence = ++pickedItemSequence,

                    LotDateCreated = lotKey.LotKey_DateCreated,
                    LotDateSequence = lotKey.LotKey_DateSequence,
                    LotTypeId = lotKey.LotKey_LotTypeId,

                    PackagingProductId = packagingProduct.Id,
                    FromLocationId = warehouseLocation.Id,
                    TreatmentId = treatment.Id,
                    CurrentLocationId = warehouseLocation.Id,
                    ToteKey = outgoing.Tote ?? "",
                    Quantity = (int)(outgoing.Quantity ?? 0),
                    CustomerProductCode = outgoing.CustProductCode
                });
            }
        }
        private IEnumerable <InventoryAdjustmentItem> GetAdjustmentItems(InventoryAdjustment newAdjustment, IEnumerable <OutgoingDTO> outgoings)
        {
            var adjustmentSequence = 1;

            foreach (var outgoing in outgoings)
            {
                _loadCount.AddRead(EntityTypes.InventoryAdjustmentItem);

                LotKey lotKey;
                if (!LotNumberParser.ParseLotNumber(outgoing.Lot, out lotKey))
                {
                    Log(new CallbackParameters(CallbackReason.InvalidLotNumber)
                    {
                        Outgoing = outgoing
                    });
                    continue;
                }

                if (!_newContextHelper.LotLoaded(lotKey))
                {
                    Log(new CallbackParameters(CallbackReason.LotNotLoaded)
                    {
                        Outgoing = outgoing
                    });
                    continue;
                }

                var packagingProduct = _newContextHelper.GetPackagingProduct(outgoing.PkgID);
                if (packagingProduct == null)
                {
                    Log(new CallbackParameters(CallbackReason.PackagingNotLoaded)
                    {
                        Outgoing = outgoing
                    });
                    continue;
                }

                var warehouseLocation = _newContextHelper.GetLocation(outgoing.LocID);
                if (warehouseLocation == null)
                {
                    Log(new CallbackParameters(CallbackReason.WarehouseLocationNotLoaded)
                    {
                        Outgoing = outgoing
                    });
                    continue;
                }

                var inventoryTreatment = _newContextHelper.GetInventoryTreatment(outgoing.TrtmtID);
                if (inventoryTreatment == null)
                {
                    Log(new CallbackParameters(CallbackReason.TreatmentNotLoaded)
                    {
                        Outgoing = outgoing
                    });
                    continue;
                }

                var adjustmentItem = new InventoryAdjustmentItem
                {
                    AdjustmentDate = newAdjustment.AdjustmentDate,
                    Sequence       = newAdjustment.Sequence,
                    ItemSequence   = adjustmentSequence++,

                    TimeStamp  = newAdjustment.TimeStamp,
                    EmployeeId = newAdjustment.EmployeeId,

                    QuantityAdjustment = (int)-outgoing.Quantity,
                    LotDateCreated     = lotKey.LotKey_DateCreated,
                    LotDateSequence    = lotKey.LotKey_DateSequence,
                    LotTypeId          = lotKey.LotKey_LotTypeId,
                    PackagingProductId = packagingProduct.Id,
                    LocationId         = warehouseLocation.Id,
                    TreatmentId        = inventoryTreatment.Id,
                    ToteKey            = outgoing.Tote ?? " "
                };

                yield return(adjustmentItem);
            }
        }
        private InventoryTransaction Process(TransactionDTO transaction)
        {
            var employeeId = _newContextHelper.DefaultEmployee.EmployeeId;

            if (transaction.EmployeeID == null)
            {
                Log(new CallbackParameters(CallbackReason.NullEmployeeID)
                {
                    Transaction = transaction
                });
            }
            else
            {
                employeeId = transaction.EmployeeID.Value;
            }

            LotKey lotKey;

            if (!LotNumberParser.ParseLotNumber(transaction.Lot, out lotKey))
            {
                Log(new CallbackParameters(CallbackReason.CannotParseLotNumber)
                {
                    Transaction = transaction
                });
                return(null);
            }

            if (!_newContextHelper.LotLoaded(lotKey))
            {
                Log(new CallbackParameters(CallbackReason.LotNotLoaded)
                {
                    Transaction = transaction
                });
                return(null);
            }

            LotKey newLotKey = null;

            if (transaction.NewLot != null)
            {
                if (!LotNumberParser.ParseLotNumber(transaction.NewLot.Value, out newLotKey))
                {
                    Log(new CallbackParameters(CallbackReason.CannotParseDestLotNumber)
                    {
                        Transaction = transaction
                    });
                    return(null);
                }

                if (!_newContextHelper.LotLoaded(newLotKey))
                {
                    Log(new CallbackParameters(CallbackReason.DestLotNotLoaded)
                    {
                        Transaction = transaction
                    });
                    return(null);
                }
            }

            PackagingProduct packaging;

            if (_newContextHelper.GetPackagingLotWithProduct(lotKey) != null)
            {
                packaging = _newContextHelper.NoPackagingProduct;
            }
            else
            {
                packaging = _newContextHelper.GetPackagingProduct(transaction.PkgID);
                if (packaging == null)
                {
                    Log(new CallbackParameters(CallbackReason.PackagingNotLoaded)
                    {
                        Transaction = transaction
                    });
                    return(null);
                }
            }

            var location = _newContextHelper.GetLocation(transaction.LocID);

            if (location == null)
            {
                Log(new CallbackParameters(CallbackReason.LocationNotLoaded)
                {
                    Transaction = transaction
                });
                return(null);
            }

            var treatment = _newContextHelper.GetInventoryTreatment(transaction.TrtmtID);

            if (treatment == null)
            {
                Log(new CallbackParameters(CallbackReason.TreatmentNotLoaded)
                {
                    Transaction = transaction
                });
                return(null);
            }

            var date = transaction.EntryDate.Date;

            return(SetTransactionType(new InventoryTransaction
            {
                DateCreated = date,
                Sequence = GetSequence(date),

                TimeStamp = transaction.EntryDate.ConvertLocalToUTC(),
                EmployeeId = employeeId,

                SourceLotDateCreated = lotKey.LotKey_DateCreated,
                SourceLotDateSequence = lotKey.LotKey_DateSequence,
                SourceLotTypeId = lotKey.LotKey_LotTypeId,

                PackagingProductId = packaging.Id,
                LocationId = location.Id,
                TreatmentId = treatment.Id,
                ToteKey = transaction.Tote ?? "",
                Quantity = (int)(transaction.Quantity ?? 0),

                DestinationLotDateCreated = newLotKey != null ? newLotKey.LotKey_DateCreated : (DateTime?)null,
                DestinationLotDateSequence = newLotKey != null ? newLotKey.LotKey_DateSequence : (int?)null,
                DestinationLotTypeId = newLotKey != null ? newLotKey.LotKey_LotTypeId : (int?)null
            }, transaction));
        }
        private IEnumerable<PickedInventoryItem> CreatePickedInventoryItemsFromMoveDetails(IPickedInventoryKey pickedInventoryKey, MovementOrderDTO order, ShipmentStatus shipmentStatus)
        {
            var sequence = 0;

            var moveDetails = order.tblMoveDetails.ToList();
            foreach(var moveDetail in moveDetails)
            {
                LoadCount.AddRead(EntityTypes.PickedInventoryItem);

                var lotKey = LotNumberParser.ParseLotNumber(moveDetail.Lot);
                if(lotKey == null)
                {
                    Log(new CallbackParameters(CallbackReason.MoveDetailInvalidLotNumber)
                    {
                        MoveDetail = moveDetail
                    });
                    continue;
                }

                if(!NewContextHelper.LotLoaded(lotKey))
                {
                    Log(new CallbackParameters(CallbackReason.MoveDetailLotNotLoaded)
                    {
                        MoveDetail = moveDetail
                    });
                    continue;
                }

                var packaging = moveDetail.PType == (int?)LotTypeEnum.Packaging ? NewContextHelper.NoPackagingProduct : NewContextHelper.GetPackagingProduct(moveDetail.PkgID);
                if(packaging == null)
                {
                    Log(new CallbackParameters(CallbackReason.MoveDetailPackagingNotLoaded)
                    {
                        MoveDetail = moveDetail
                    });
                    continue;
                }

                var pickedLocation = NewContextHelper.GetLocation(moveDetail.LocID);
                if(pickedLocation == null)
                {
                    pickedLocation = NewContextHelper.UnknownFacilityLocation;
                    if(pickedLocation == null)
                    {
                        Log(new CallbackParameters(CallbackReason.MoveDetailUnknownWarehouseLocationNotLoaded)
                        {
                            MoveDetail = moveDetail
                        });
                        continue;
                    }

                    Log(new CallbackParameters(CallbackReason.MoveDetailDefaultUnknownWarehouseLocation)
                    {
                        MoveDetail = moveDetail,
                        Location = pickedLocation
                    });
                }

                var currentLocation = shipmentStatus == ShipmentStatus.Shipped ? NewContextHelper.GetLocation(moveDetail.Move2) ?? pickedLocation : pickedLocation;

                var treatment = NewContextHelper.GetInventoryTreatment(moveDetail.TrtmtID);
                if(treatment == null)
                {
                    Log(new CallbackParameters(CallbackReason.MoveDetailTreatmentNotLoaded)
                    {
                        MoveDetail = moveDetail
                    });
                    continue;
                }

                const string tote = "";

                yield return new PickedInventoryItem
                {
                    DateCreated = pickedInventoryKey.PickedInventoryKey_DateCreated,
                    Sequence = pickedInventoryKey.PickedInventoryKey_Sequence,
                    ItemSequence = ++sequence,
                    DetailID = moveDetail.MDetail,

                    LotDateCreated = lotKey.LotKey_DateCreated,
                    LotDateSequence = lotKey.LotKey_DateSequence,
                    LotTypeId = lotKey.LotKey_LotTypeId,
                    PackagingProductId = packaging.Id,
                    TreatmentId = treatment.Id,
                    ToteKey = tote,
                    Quantity = (int)moveDetail.Quantity,
                    FromLocationId = pickedLocation.Id,
                    CurrentLocationId = currentLocation.Id,
                    CustomerLotCode = moveDetail.CustLot,
                    CustomerProductCode = moveDetail.CustProductCode
                };
            }
        }
Example #17
0
        private void SetTblSampleDetails(tblSample tblSample, SampleOrder sampleOrder, ref bool commitNewContext)
        {
            var existingDetails = tblSample.tblSampleDetails.ToDictionary(n => n.SampleDetailID);
            var sampleDetailId = OldContext.tblSampleDetails.Select(n => n.SampleDetailID).DefaultIfEmpty(DateTime.Now.RoundMillisecondsForSQL()).Max();
            var custSpecId = OldContext.tblSampleCustSpecs.Select(n => n.CustSpecID).DefaultIfEmpty(DateTime.Now.RoundMillisecondsForSQL()).Max();
            var rvcMatchId = OldContext.tblSampleRVCMatches.Select(n => n.RVCMatchID).DefaultIfEmpty(DateTime.Now.RoundMillisecondsForSQL()).Max();
            foreach(var item in sampleOrder.Items)
            {
                tblSampleDetail detail = null;
                if(item.SampleDetailID != null && existingDetails.TryGetValue(item.SampleDetailID.Value, out detail))
                {
                    existingDetails.Remove(detail.SampleDetailID);
                }

                if(detail == null)
                {
                    commitNewContext = true;
                    sampleDetailId = sampleDetailId.AddSeconds(1);
                    detail = new tblSampleDetail
                        {
                            SampleDetailID = sampleDetailId,
                            SampleID = tblSample.SampleID,
                            s_GUID = Guid.NewGuid()
                        };
                    OldContext.tblSampleDetails.AddObject(detail);
                    item.SampleDetailID = detail.SampleDetailID;
                }

                detail.ProdID = item.Product == null ? (int?) null : int.Parse(item.Product.ProductCode);
                detail.Lot = item.Lot == null ? (int?) null : LotNumberParser.BuildLotNumber(item.Lot);
                detail.Qty = item.Quantity;
                detail.Desc = item.Description;
                detail.SampleMatch = item.CustomerProductName;

                if(item.Spec == null)
                {
                    DeleteTblSampleCustSpecs(detail);
                }
                else
                {
                    var spec = detail.tblSampleCustSpecs.FirstOrDefault(s => s.CustSpecID == item.Spec.CustSpecID);
                    if(spec == null)
                    {
                        commitNewContext = true;
                        custSpecId = custSpecId.AddSeconds(1);
                        spec = new tblSampleCustSpec
                            {
                                CustSpecID = custSpecId,
                                SampleDetailID = detail.SampleDetailID
                            };
                        OldContext.tblSampleCustSpecs.AddObject(spec);
                        item.Spec.CustSpecID = spec.CustSpecID;
                    }

                    SetSpec(spec, item.Spec);
                }

                if(item.Match == null)
                {
                    DeleteTblSampleRVCMatches(detail);
                }
                else
                {
                    var match = detail.tblSampleRVCMatches.FirstOrDefault(s => s.RVCMatchID == item.Match.RVCMatchID);
                    if(match == null)
                    {
                        commitNewContext = true;
                        rvcMatchId = rvcMatchId.AddSeconds(1);
                        match = new tblSampleRVCMatch
                            {
                                RVCMatchID = rvcMatchId,
                                SampleDetailID = detail.SampleDetailID
                            };
                        OldContext.tblSampleRVCMatches.AddObject(match);
                        item.Match.RVCMatchID = match.RVCMatchID;
                    }

                    SetMatch(match, item.Match);
                }
            }

            foreach(var detail in existingDetails)
            {
                DeleteTblSampleDetail(detail.Value);
            }
        }
        protected override IEnumerable <LotResults> BirthRecords()
        {
            _loadCount.Reset();
            var lotKeys = new Dictionary <LotKey, int>();

            foreach (var lot in SelectLotsToLoad(OldContext))
            {
                _loadCount.AddRead(EntityTypes.Lot);

                LotKey lotKey;
                if (!LotNumberParser.ParseLotNumber(lot.Lot, out lotKey))
                {
                    Log(new CallbackParameters(lot, CallbackReason.InvalidLotNumber));
                    continue;
                }

                if (_newContextHelper.LotLoaded(lotKey))
                {
                    continue;
                }

                if (lotKeys.ContainsKey(lotKey))
                {
                    Log(new CallbackParameters(lot, CallbackReason.DuplicateLotNumber)
                    {
                        ExistingLotNumber = lotKeys[lotKey]
                    });
                    continue;
                }
                lotKeys.Add(lotKey, lot.Lot);

                if (lot.EntryDate == null)
                {
                    Log(new CallbackParameters(lot, CallbackReason.EntryDateNull));
                    continue;
                }

                if (lot.tblProduct == null)
                {
                    Log(new CallbackParameters(lot, CallbackReason.NullProductReference));
                    continue;
                }

                var lotType = lotKey.LotKey_LotTypeId.ToLotType();
                if (lotType == null)
                {
                    Log(new CallbackParameters(lot, CallbackReason.InvalidLotType)
                    {
                        LotKey = lotKey
                    });
                    continue;
                }

                var deserialized      = SerializableLot.Deserialize(lot.Serialized);
                var packagingReceived = GetPackagingReceived(lot, deserialized);
                if (packagingReceived == null)
                {
                    continue;
                }

                Models.Company vendor = null;
                if (!string.IsNullOrWhiteSpace(lot.Company_IA))
                {
                    vendor = _newContextHelper.GetCompany(lot.Company_IA);
                    if (vendor == null)
                    {
                        Log(new CallbackParameters(lot, CallbackReason.CompanyNotLoaded));
                    }
                }

                var newLot = new Lot
                {
                    LotDateCreated  = lotKey.LotKey_DateCreated,
                    LotDateSequence = lotKey.LotKey_DateSequence,
                    LotTypeId       = lotKey.LotKey_LotTypeId,

                    EmployeeId = lot.DeterminedEmployeeId != null ? lot.DeterminedEmployeeId.Value : _newContextHelper.DefaultEmployee.EmployeeId,
                    TimeStamp  = lot.DeterminedTimestamp.ConvertLocalToUTC() ?? lotKey.LotKey_DateCreated,

                    ReceivedPackagingProductId = packagingReceived.PackagingProductKey_ProductId,
                    VendorId = vendor == null ? (int?)null : vendor.Id,

                    PurchaseOrderNumber = lot.PurchOrder,
                    ShipperNumber       = lot.ShipperNum,

                    Notes = lot.Notes
                };

                LotResults results = null;
                switch (lotType.Value.ToProductType())
                {
                case ProductTypeEnum.Additive: results = GetAdditiveLotResults(lot, newLot); break;

                case ProductTypeEnum.Chile: results = GetChileLotResults(lot, newLot, deserialized); break;

                case ProductTypeEnum.Packaging: results = GetPackagingLotResults(lot, newLot); break;
                }

                if (results != null)
                {
                    _loadCount.AddLoaded(EntityTypes.Lot);

                    if (results.ChileLot != null)
                    {
                        _loadCount.AddLoaded(EntityTypes.ChileLot);
                        _loadCount.AddLoaded(EntityTypes.LotAttribute, (uint)results.ChileLot.Lot.Attributes.Count);
                        _loadCount.AddLoaded(EntityTypes.LotDefect, (uint)(results.ChileLot.Lot.LotDefects == null ? 0 : results.ChileLot.Lot.LotDefects.Count));
                        _loadCount.AddLoaded(EntityTypes.LotDefectResolution, (uint)(results.ChileLot.Lot.LotDefects == null ? 0 : results.ChileLot.Lot.LotDefects.Count(d => d.Resolution != null)));
                        _loadCount.AddLoaded(EntityTypes.LotAttributeDefect, (uint)(results.LotAttributeDefects == null ? 0 : results.LotAttributeDefects.Count));
                    }

                    if (results.AdditiveLot != null)
                    {
                        _loadCount.AddLoaded(EntityTypes.AdditiveLot);
                        _loadCount.AddLoaded(EntityTypes.LotAttribute, (uint)results.AdditiveLot.Lot.Attributes.Count);
                    }

                    _loadCount.AddLoaded(EntityTypes.PackagingLot, (uint)(results.PackagingLot != null ? 1 : 0));

                    yield return(results);
                }
            }

            _loadCount.LogResults(l => Log(new CallbackParameters(l)));
        }
        protected override IEnumerable <LotHistory> BirthRecords()
        {
            _loadCount.Reset();

            foreach (var lot in SelectRecords(OldContext))
            {
                LotKey lotKey;
                if (!LotNumberParser.ParseLotNumber(lot.Lot, out lotKey))
                {
                    Log(new CallbackParameters(CallbackReason.InvalidLotNumber)
                    {
                        Lot = lot
                    });
                    continue;
                }

                if (!_newContextHelper.LotLoaded(lotKey))
                {
                    Log(new CallbackParameters(CallbackReason.LotNotLoaded)
                    {
                        Lot = lot
                    });
                    continue;
                }

                var sequence        = 0;
                var computedHistory = lot.History.Where(h => h.TestDate == null).OrderBy(h => h.ArchiveDate).FirstOrDefault();

                DateTime?lotHistoryTimeStamp = null;
                foreach (var history in lot.History.OrderBy(h => h.ArchiveDate))
                {
                    _loadCount.AddRead(EntityTypes.LotAttributeHistory);

                    if (history.EmployeeID == null)
                    {
                        Log(new CallbackParameters(CallbackReason.EmployeeIDIsNull)
                        {
                            History = history
                        });
                    }
                    var employeeId = history.TesterID ?? history.EmployeeID ?? _newContextHelper.DefaultEmployee.EmployeeId;

                    string holdDescription;
                    var    hold = LotHelper.GetHoldStatus((LotStat?)history.LotStat, out holdDescription);

                    var serializedData = new SerializedLotHistory
                    {
                        TimeStamp        = lotHistoryTimeStamp ?? history.EntryDate.ConvertLocalToUTC() ?? lotKey.LotKey_DateCreated,
                        QualityStatus    = DetermineLotQualityStatus((LotStat?)history.LotStat),
                        ProductionStatus = LotProductionStatus.Produced,
                        Hold             = hold,
                        HoldDescription  = holdDescription,
                        LoBac            = history.LoBac,

                        Attributes = history.GetAttributes(computedHistory)
                                     .Where(a => a.Value != null)
                                     .Select(attribute => new SerializedLotHistoryAttribute
                        {
                            AttributeShortName = attribute.AttributeNameKey,
                            AttributeValue     = (double)attribute.Value,
                            AttributeDate      = (history.TestDate ?? history.ArchiveDate).Date,
                            Computed           = attribute.Computed
                        }).ToList()
                    };

                    yield return(new LotHistory
                    {
                        LotTypeId = lotKey.LotKey_LotTypeId,
                        LotDateCreated = lotKey.LotKey_DateCreated,
                        LotDateSequence = lotKey.LotKey_DateSequence,
                        Sequence = sequence++,

                        TimeStamp = (lotHistoryTimeStamp = history.ArchiveDate.ConvertLocalToUTC()).Value,
                        EmployeeId = employeeId,

                        Serialized = JsonConvert.SerializeObject(serializedData)
                    });

                    _loadCount.AddLoaded(EntityTypes.LotAttributeHistory);
                }
            }

            _loadCount.LogResults(l => Log(new CallbackParameters(l)));
        }
Example #20
0
        private IEnumerable <PickedInventoryItem> CreatePickedInventoryItems(PickedInventory pickedInventory, IEnumerable <tblBatchItemDTO> batchItems)
        {
            var itemSequence = 1;

            foreach (var batchItem in batchItems)
            {
                _loadCount.AddRead(EntityTypes.PickedInventoryItem);

                LotKey lotKey;
                if (!LotNumberParser.ParseLotNumber(batchItem.Lot, out lotKey))
                {
                    Log(new CallbackParameters(CallbackReason.BatchItemInvalidLotNumber)
                    {
                        BatchItem = batchItem
                    });
                    continue;
                }

                if (!_newContextHelper.LotLoaded(lotKey))
                {
                    Log(new CallbackParameters(CallbackReason.BatchItemLotNotLoaded)
                    {
                        BatchItem = batchItem
                    });
                    continue;
                }

                var packaging = batchItem.PTypeID == (int?)LotTypeEnum.Packaging ? _newContextHelper.NoPackagingProduct : _newContextHelper.GetPackagingProduct(batchItem.PkgID);
                if (packaging == null)
                {
                    Log(new CallbackParameters(CallbackReason.BatchItemPackagingNotLoaded)
                    {
                        BatchItem = batchItem
                    });
                    continue;
                }

                var treatment = _newContextHelper.GetInventoryTreatment(batchItem.TrtmtID);
                if (treatment == null)
                {
                    Log(new CallbackParameters(CallbackReason.BatchItemTreatmentNotLoaded)
                    {
                        BatchItem = batchItem
                    });
                    continue;
                }

                int?currentLocationId  = null;
                var productionLocation = _newContextHelper.GetProductionLocation(batchItem.tblLocation);
                if (productionLocation != null)
                {
                    currentLocationId = productionLocation.Id;
                }
                else
                {
                    var warehouseLocation = _newContextHelper.GetLocation(batchItem.LocID);
                    if (warehouseLocation != null)
                    {
                        currentLocationId = warehouseLocation.Id;
                    }
                }

                if (currentLocationId == null)
                {
                    Log(new CallbackParameters(CallbackReason.BatchItemCurrentLocationCouldnotBeDetermined)
                    {
                        BatchItem = batchItem
                    });
                    continue;
                }

                int?warehouseLocationId;
                var warehouseLocationResult = _pickedInventoryItemLocationHelper.DeterminePickedFromLocation(batchItem, out warehouseLocationId);
                if (warehouseLocationResult == PickedInventoryItemLocationHelper.Result.UnableToDetermine)
                {
                    Log(new CallbackParameters(CallbackReason.BatchItemDefaultPickedLocation)
                    {
                        BatchItem = batchItem
                    });
                    warehouseLocationId = _newContextHelper.UnknownFacilityLocation.Id;
                }

                if (warehouseLocationId == null)
                {
                    Log(new CallbackParameters(CallbackReason.BatchItemPickedLocationNotDetermined)
                    {
                        BatchItem = batchItem
                    });
                    continue;
                }

                yield return(new PickedInventoryItem
                {
                    DateCreated = pickedInventory.DateCreated,
                    Sequence = pickedInventory.Sequence,
                    ItemSequence = itemSequence,

                    LotDateCreated = lotKey.LotKey_DateCreated,
                    LotDateSequence = lotKey.LotKey_DateSequence,
                    LotTypeId = lotKey.LotKey_LotTypeId,

                    PackagingProductId = packaging.Id,
                    FromLocationId = warehouseLocationId.Value,
                    TreatmentId = treatment.Id,
                    CurrentLocationId = currentLocationId.Value,
                    ToteKey = new string((batchItem.Tote ?? "").Take(Constants.StringLengths.ToteKeyLength).ToArray()),
                    Quantity = (int)(batchItem.Quantity ?? 0)
                });

                itemSequence += 1;
            }
        }
Example #21
0
        private Results LoadAllowances(int lotNumber, SerializableLot deserializedLot)
        {
            var results = new Results();
            var lotKey  = LotNumberParser.ParseLotNumber(lotNumber);

            foreach (var customer in deserializedLot.CustomerAllowances ?? new List <SerializableLot.CustomerAllowance>())
            {
                var company = _newContextHelper.GetCompany(customer.CompanyName, CompanyType.Customer);
                if (company == null)
                {
                    Log(new CallbackParameters(lotNumber, CallbackReason.CustomerNotLoaded)
                    {
                        CustomerAllowance = customer
                    });
                }
                else
                {
                    results.CustomerAllowances.Add(new LotCustomerAllowance
                    {
                        LotDateCreated  = lotKey.LotKey_DateCreated,
                        LotDateSequence = lotKey.LotKey_DateSequence,
                        LotTypeId       = lotKey.LotKey_LotTypeId,
                        CustomerId      = company.Id
                    });
                }
            }

            foreach (var contract in deserializedLot.ContractAllowances ?? new List <SerializableLot.ContractAllowance>())
            {
                var contractKey = _newContextHelper.GetContractKey(contract.ContractId);
                if (contractKey == null)
                {
                    Log(new CallbackParameters(lotNumber, CallbackReason.ContractNotLoaded)
                    {
                        ContractAllowance = contract
                    });
                }
                else
                {
                    results.ContractAllowances.Add(new LotContractAllowance
                    {
                        LotDateCreated   = lotKey.LotKey_DateCreated,
                        LotDateSequence  = lotKey.LotKey_DateSequence,
                        LotTypeId        = lotKey.LotKey_LotTypeId,
                        ContractYear     = contractKey.ContractKey_Year,
                        ContractSequence = contractKey.ContractKey_Sequence
                    });
                }
            }

            foreach (var customerOrder in deserializedLot.CustomerOrderAllowances ?? new List <SerializableLot.CustomerOrderAllowance>())
            {
                var order = _newContextHelper.GetInventoryShipmentOrder(customerOrder.OrderNum, InventoryShipmentOrderTypeEnum.SalesOrder);
                if (order == null)
                {
                    Log(new CallbackParameters(lotNumber, CallbackReason.SalesOrderNotLoaded)
                    {
                        CustomerOrderAllowance = customerOrder
                    });
                }
                else
                {
                    results.CustomerOrderAllowances.Add(new LotSalesOrderAllowance
                    {
                        LotDateCreated        = lotKey.LotKey_DateCreated,
                        LotDateSequence       = lotKey.LotKey_DateSequence,
                        LotTypeId             = lotKey.LotKey_LotTypeId,
                        SalesOrderDateCreated = order.DateCreated,
                        SalesOrderSequence    = order.Sequence
                    });
                }
            }

            return(results);
        }
        private bool ProcessSerializedPackSchedule(PackSchedule packSchedule, PackScheduleDTO oldPackSchedule, out bool isSerialized)
        {
            isSerialized = true;
            int?pkgID;

            if (!SerializablePackSchedule.DeserializeIntoPackSchedule(packSchedule, oldPackSchedule.Serialized, out pkgID))
            {
                isSerialized = false;
                return(false);
            }

            int?batchTypeId;

            if (oldPackSchedule.BatchLots != null && oldPackSchedule.BatchLots.Any())
            {
                batchTypeId = GetSingleBatchTypeID(oldPackSchedule);
                if (batchTypeId == null)
                {
                    Log(new CallbackParameters(CallbackReason.NoSingleBatchType)
                    {
                        PackSchedule = oldPackSchedule
                    });
                    return(false);
                }
            }
            else
            {
                batchTypeId = oldPackSchedule.BatchTypeID.Value;
            }
            packSchedule.WorkTypeId = WorkTypeFactory.BuildWorkTypeFromBatchTypeID(batchTypeId.Value).Id;

            var packagingProduct = _newContextHelper.GetPackagingProduct(pkgID);

            if (packagingProduct != null)
            {
                packSchedule.PackagingProductId = packagingProduct.Id;
            }
            else if (!SetDeterminedPackaging(packSchedule, oldPackSchedule))
            {
                return(false);
            }


            var productionBatches = packSchedule.ProductionBatches.ToList();

            productionBatches.RemoveAll(batch =>
            {
                var lotKey    = new LotKey(batch);
                var lotNumber = LotNumberParser.BuildLotNumber(lotKey);

                List <DateTime?> ids;
                if (_batchItemPackSchIds.TryGetValue(lotNumber, out ids))
                {
                    if (ids.Any())
                    {
                        if (ids.Any(i => i != oldPackSchedule.PackSchID))
                        {
                            Log(new CallbackParameters(CallbackReason.MismatchedBatchItemPackSchID)
                            {
                                PackSchedule = oldPackSchedule,
                                BatchNumber  = lotNumber
                            });
                        }
                        return(true);
                    }
                }

                _loadCount.AddRead(EntityTypes.ProductionBatch);
                _loadCount.AddRead(EntityTypes.Notebook);
                _loadCount.AddRead(EntityTypes.PickedInventory);
                _loadCount.AddRead(EntityTypes.ChileLot);
                _loadCount.AddRead(EntityTypes.Lot);

                if (!_newContextHelper.LotLoaded(lotKey))
                {
                    Log(new CallbackParameters(CallbackReason.BatchLotNotLoaded)
                    {
                        PackSchedule = oldPackSchedule,
                        LotKey       = lotKey
                    });
                    return(true);
                }

                var dateCreated = batch.LotDateCreated.Date;
                var sequence    = PickedInventoryKeyHelper.Singleton.GetNextSequence(dateCreated);

                batch.Production.PickedInventoryDateCreated = batch.Production.PickedInventory.DateCreated = dateCreated;
                batch.Production.PickedInventorySequence    = batch.Production.PickedInventory.Sequence = sequence;

                var notebook = _notebookFactory.BirthNext(batch.TimeStamp);
                batch.InstructionNotebook            = notebook;
                batch.InstructionNotebookDateCreated = notebook.Date;
                batch.InstructionNotebookSequence    = notebook.Sequence;

                var deserializedProduction = _serializedData.GetDeserialized <SerializableEmployeeIdentifiable>(SerializableType.ChileLotProduction, lotNumber.ToString());
                if (deserializedProduction != null)
                {
                    batch.Production.EmployeeId = deserializedProduction.EmployeeKey.EmployeeKeyId;
                    batch.Production.TimeStamp  = deserializedProduction.TimeStamp;
                }

                return(false);
            });
            packSchedule.ProductionBatches = productionBatches;

            return(true);
        }
Example #23
0
        protected override IEnumerable <ProductionBatch> BirthRecords()
        {
            _loadCount.Reset();
            var processedLotKeys = new Dictionary <LotKey, int>();

            foreach (var packSchedule in SelectProductionBatchesToLoad(OldContext))
            {
                var packSchId = packSchedule.PackSchID;
                var employeeIdentifiableByLot = GetEmployeeIdentifiableByLot(packSchedule);

                foreach (var oldBatch in packSchedule.ProductionBatches)
                {
                    _loadCount.AddRead(EntityTypes.ProductionBatch);

                    var invalidBatchItems = oldBatch.BatchItems.Where(b => b.PackSchID == null).ToList();
                    if (invalidBatchItems.Any())
                    {
                        invalidBatchItems.ForEach(b => Log(new CallbackParameters(CallbackReason.NullPackSchID)
                        {
                            BatchItem = b
                        }));
                        continue;
                    }

                    invalidBatchItems = oldBatch.BatchItems.Where(b => b.NewLot == null).ToList();
                    if (invalidBatchItems.Any())
                    {
                        invalidBatchItems.ForEach(b => Log(new CallbackParameters(CallbackReason.NullNewLot)
                        {
                            BatchItem = b
                        }));
                        continue;
                    }

                    invalidBatchItems = oldBatch.BatchItems.Where(b => b.ResultLot == null).ToList();
                    if (invalidBatchItems.Any())
                    {
                        invalidBatchItems.ForEach(b => Log(new CallbackParameters(CallbackReason.NullResultLot)
                        {
                            BatchItem = b
                        }));
                        continue;
                    }

                    LotKey lotKey;
                    if (!LotNumberParser.ParseLotNumber(oldBatch.ResultLot.Lot, out lotKey))
                    {
                        Log(new CallbackParameters(CallbackReason.InvalidLotNumber)
                        {
                            Batch = oldBatch
                        });
                        continue;
                    }

                    int previousLotNumber;
                    if (processedLotKeys.TryGetValue(lotKey, out previousLotNumber))
                    {
                        Log(new CallbackParameters(CallbackReason.LotAlreadyProcessed)
                        {
                            Batch = oldBatch
                        });
                        continue;
                    }
                    processedLotKeys.Add(lotKey, oldBatch.ResultLot.Lot);

                    var newPackSchedule = _newContextHelper.GetPackSchedule(packSchId);
                    if (newPackSchedule == null)
                    {
                        Log(new CallbackParameters(CallbackReason.PackScheduleNotLoaded)
                        {
                            Batch        = oldBatch,
                            PackSchedule = packSchId
                        });
                        continue;
                    }

                    Tuple <DateTime, int> employeeIdentifiable;
                    if (!employeeIdentifiableByLot.TryGetValue(oldBatch.ResultLot.Lot, out employeeIdentifiable))
                    {
                        employeeIdentifiable = new Tuple <DateTime, int>(oldBatch.ResultLot.EntryDate.Value, oldBatch.ResultLot.EmployeeID.Value);
                    }

                    var chileLotProduction = CreateChileLotProduction(lotKey, oldBatch, newPackSchedule, employeeIdentifiable.Item1, employeeIdentifiable.Item2);
                    if (chileLotProduction == null)
                    {
                        continue;
                    }

                    var productionHasBeenCompleted = false;
                    if (oldBatch.ResultLot != null)
                    {
                        productionHasBeenCompleted = oldBatch.ResultLot.BatchStatID == (int)BatchStatID.Produced;
                    }

                    _loadCount.AddRead(EntityTypes.ProductionBatchInstructionNotebook);
                    var notebook = _notebookFactory.BirthNext(oldBatch.ResultLot.EntryDate.Value, oldBatch.ResultLot.EmployeeID.Value);

                    var productionBatch = new ProductionBatch
                    {
                        TimeStamp  = employeeIdentifiable.Item1,
                        EmployeeId = employeeIdentifiable.Item2,

                        LotDateCreated  = chileLotProduction.LotDateCreated,
                        LotDateSequence = chileLotProduction.LotDateSequence,
                        LotTypeId       = chileLotProduction.LotTypeId,

                        PackScheduleDateCreated = newPackSchedule.DateCreated,
                        PackScheduleSequence    = newPackSchedule.SequentialNumber,

                        InstructionNotebookDateCreated = notebook.Date,
                        InstructionNotebookSequence    = notebook.Sequence,

                        ProductionHasBeenCompleted = productionHasBeenCompleted,

                        TargetParameters = new ProductionBatchTargetParameters(oldBatch.ResultLot),

                        Production          = chileLotProduction,
                        InstructionNotebook = notebook
                    };

                    _loadCount.AddLoaded(EntityTypes.ChileLotProduction);
                    _loadCount.AddLoaded(EntityTypes.ProductionBatch);
                    if (productionBatch.Production.Results != null)
                    {
                        _loadCount.AddLoaded(EntityTypes.LotProductionResults);
                        _loadCount.AddLoaded(EntityTypes.LotProductionResultItem, (uint)productionBatch.Production.Results.ResultItems.Count);
                    }
                    _loadCount.AddLoaded(EntityTypes.PickedInventory);
                    _loadCount.AddLoaded(EntityTypes.PickedInventoryItem, (uint)productionBatch.Production.PickedInventory.Items.Count);
                    _loadCount.AddLoaded(EntityTypes.ProductionBatchInstructionNotebook);

                    yield return(productionBatch);
                }
            }

            _loadCount.LogResults(l => Log(new CallbackParameters(l)));
        }
        protected override IEnumerable <ChileMaterialsReceived> BirthRecords()
        {
            _loadCount.Reset();

            var dataSource = OldContext.CreateObjectSet <tblIncoming>()
                             .Include(i => i.tblLot, i => i.tblPackaging, i => i.tblVariety)
                             .Where(i => i.TTypeID == (int?)TransType.DeHy || i.TTypeID == (int?)TransType.Other)
                             .GroupBy(i => i.Lot).ToList();

            foreach (var tblIncomings in dataSource)
            {
                _loadCount.AddRead(EntityTypes.ChileMaterialsReceived);

                var oldLot    = tblIncomings.First().tblLot;
                var transType = tblIncomings.Select(i => i.TTypeID).Distinct().Single().ToTransType();

                LotKey lotKey;
                if (!LotNumberParser.ParseLotNumber(tblIncomings.Key, out lotKey))
                {
                    Log(new CallbackParameters(CallbackReason.InvalidLotNumber)
                    {
                        Lot = oldLot
                    });
                    continue;
                }

                var employeeId = oldLot.EmployeeID ?? _newContextHelper.DefaultEmployee.EmployeeId;
                if (oldLot.EmployeeID == null)
                {
                    Log(new CallbackParameters(CallbackReason.DefaultEmployee)
                    {
                        Lot        = oldLot,
                        EmployeeId = employeeId
                    });
                }

                if (oldLot.EntryDate == null)
                {
                    Log(new CallbackParameters(CallbackReason.NullEntryDate)
                    {
                        Lot = oldLot
                    });
                    continue;
                }
                var entryDate = oldLot.EntryDate.Value.ConvertLocalToUTC();

                var supplierNames = tblIncomings.Select(i => i.Company_IA).Distinct().ToList();
                if (supplierNames.Count != 1)
                {
                    Log(new CallbackParameters(CallbackReason.NoSingleSupplierName)
                    {
                        Lot = oldLot
                    });
                    continue;
                }
                var supplierName = (supplierNames.Single() ?? "").Trim();
                if (string.IsNullOrEmpty(supplierName))
                {
                    var locales = tblIncomings.Select(l => l.DehyLocale).Where(l => !string.IsNullOrEmpty(l)).Distinct().ToList();
                    if (locales.Count == 1)
                    {
                        supplierName = locales.Single();
                        Log(new CallbackParameters(CallbackReason.UsedDehyLocaleAsDehydrator)
                        {
                            Lot        = oldLot,
                            DehyLocale = supplierName
                        });
                    }
                }

                var supplier = _newContextHelper.GetCompany(supplierName, CompanyType.Dehydrator, CompanyType.Supplier);
                if (supplier == null)
                {
                    Log(new CallbackParameters(CallbackReason.SupplierNotLoaded)
                    {
                        Lot            = oldLot,
                        DehydratorName = supplierName
                    });
                    continue;
                }

                var chileLot = _newContextHelper.GetChileLotWithProduct(lotKey);
                if (chileLot == null)
                {
                    Log(new CallbackParameters(CallbackReason.ChileLotNotLoaded)
                    {
                        Lot = oldLot
                    });
                    continue;
                }

                var treatmentIds = tblIncomings.Select(i => i.TrtmtID).Distinct().ToList();
                if (treatmentIds.Count != 1)
                {
                    Log(new CallbackParameters(CallbackReason.NoSingleTrmtID)
                    {
                        Lot = oldLot,
                    });
                    continue;
                }
                var treatmentId = treatmentIds.Single();

                var treatment = _newContextHelper.GetInventoryTreatment(treatmentId);
                if (treatment == null)
                {
                    Log(new CallbackParameters(CallbackReason.TreatmentNotLoaded)
                    {
                        Lot    = oldLot,
                        TrmtID = treatmentId
                    });
                }

                var newItems     = new List <ChileMaterialsReceivedItem>();
                var itemSequence = 1;

                var oldItemGroups = tblIncomings.GroupBy(i => new ChileMaterialsItemReceivedKeys(i), new ChileMaterialsItemReceivedKeysEqualityComparer());
                foreach (var oldItems in oldItemGroups)
                {
                    var newItem = CreateItemReceived(oldItems, lotKey, itemSequence);
                    if (newItem != null)
                    {
                        newItems.Add(newItem);
                        ++itemSequence;
                    }
                }

                _loadCount.AddLoaded(EntityTypes.ChileMaterialsReceived);
                _loadCount.AddLoaded(EntityTypes.ChileMaterialsReceivedItem, (uint)newItems.Count);

                yield return(new ChileMaterialsReceived
                {
                    ChileMaterialsReceivedType = transType == TransType.DeHy ? ChileMaterialsReceivedType.Dehydrated : ChileMaterialsReceivedType.Other,
                    EmployeeId = employeeId,
                    TimeStamp = entryDate,

                    LotDateCreated = chileLot.LotDateCreated,
                    LotDateSequence = chileLot.LotDateSequence,
                    LotTypeId = chileLot.LotTypeId,

                    LoadNumber = oldLot.LoadNum,
                    DateReceived = chileLot.LotDateCreated,

                    ChileProductId = chileLot.ChileProductId,
                    SupplierId = supplier.Id,
                    TreatmentId = treatment.Id,

                    Items = newItems
                });
            }

            _loadCount.LogResults(l => Log(new CallbackParameters(l)));
        }
Example #25
0
        private void LoadDetails(SampleOrder sampleOrder, tblSampleDTO tblSample)
        {
            var items        = new List <SampleOrderItem>();
            var itemSequence = 1;

            foreach (var tblSampleDetail in tblSample.tblSampleDetails)
            {
                LoadCount.AddRead(EntityType.SampleOrderItem);

                var product = _newContextHelper.GetProduct(tblSampleDetail.ProdID);
                if (product == null && tblSampleDetail.ProdID != null)
                {
                    Log(new CallbackParameters(CallbackReason.tblSampleDetail_MissingProduct)
                    {
                        tblSampleDetail = tblSampleDetail
                    });
                    continue;
                }

                LotKey lotKey = null;
                if (tblSampleDetail.Lot != null)
                {
                    lotKey = LotNumberParser.ParseLotNumber(tblSampleDetail.Lot.Value);
                    if (lotKey == null)
                    {
                        Log(new CallbackParameters(CallbackReason.tblSampleDetail_InvalidLotNumber)
                        {
                            tblSampleDetail = tblSampleDetail
                        });
                        continue;
                    }

                    if (!_newContextHelper.LotLoaded(lotKey))
                    {
                        Log(new CallbackParameters(CallbackReason.tblSampleDetail_MissingLot)
                        {
                            tblSampleDetail = tblSampleDetail
                        });
                        continue;
                    }
                }

                var sampleOrderItem = new SampleOrderItem
                {
                    SampleOrderYear     = sampleOrder.Year,
                    SampleOrderSequence = sampleOrder.Sequence,
                    ItemSequence        = itemSequence++,

                    ProductId = product == null ? (int?)null : product.ProductKey.ProductKey_ProductId,

                    LotDateCreated  = lotKey == null ? (DateTime?)null : lotKey.LotKey_DateCreated,
                    LotDateSequence = lotKey == null ? (int?)null : lotKey.LotKey_DateSequence,
                    LotTypeId       = lotKey == null ? (int?)null : lotKey.LotKey_LotTypeId,

                    Quantity            = (int)(tblSampleDetail.Qty ?? 0),
                    Description         = tblSampleDetail.Desc,
                    CustomerProductName = tblSampleDetail.SampleMatch,

                    SampleDetailID = tblSampleDetail.SampleDetailID,
                };

                LoadItemSpec(tblSampleDetail.tblSampleCustSpec, sampleOrderItem);
                LoadItemMatch(tblSampleDetail.tblSampleRVCMatch, sampleOrderItem);

                items.Add(sampleOrderItem);
            }

            sampleOrder.Items = items;
        }
        private SalesOrderLoad SetItems(SalesOrderLoad order, tblOrderDTO oldOrder)
        {
            var orderItemSequence  = 0;
            var pickedItemSequence = 0;

            order.SalesOrderItems       = new List <SalesOrderItem>();
            order.SalesOrderPickedItems = new List <SalesOrderPickedItem>();

            var latestStaged = oldOrder.tblOrderDetails.SelectMany(d => d.tblStagedFGs)
                               .OrderByDescending(s => s.EntryDate)
                               .FirstOrDefault();

            if (latestStaged != null)
            {
                order.InventoryShipmentOrder.PickedInventory.TimeStamp = latestStaged.EntryDate.ConvertLocalToUTC();
                if (latestStaged.EmployeeID != null)
                {
                    order.InventoryShipmentOrder.PickedInventory.EmployeeId = latestStaged.EmployeeID.Value;
                }
            }

            foreach (var detail in oldOrder.tblOrderDetails)
            {
                LoadCount.AddRead(EntityType.SalesOrderItem);

                var product = _newContextHelper.GetProduct(detail.ProdID);
                if (product == null)
                {
                    Log(new CallbackParameters(CallbackReason.DetailProductNotFound)
                    {
                        Order  = oldOrder,
                        Detail = detail
                    });
                    continue;
                }

                var packaging = _newContextHelper.GetPackagingProduct(detail.PkgID);
                if (packaging == null)
                {
                    Log(new CallbackParameters(CallbackReason.DetailPackagingNotFound)
                    {
                        Order  = oldOrder,
                        Detail = detail
                    });
                    continue;
                }

                var treatment = _newContextHelper.NoTreatment;
                if (detail.TrtmtID != null)
                {
                    treatment = _newContextHelper.GetInventoryTreatment(detail.TrtmtID.Value);
                    if (treatment == null)
                    {
                        Log(new CallbackParameters(CallbackReason.DetailTreatmentNotFound)
                        {
                            Order  = oldOrder,
                            Detail = detail
                        });
                        continue;
                    }
                }

                IContractItemKey contractItemKey = null;
                if (detail.KDetailID != null)
                {
                    contractItemKey = _newContextHelper.GetContractItemKey(detail.KDetailID);
                    if (contractItemKey == null)
                    {
                        Log(new CallbackParameters(CallbackReason.ContractItemNotFound)
                        {
                            Order  = oldOrder,
                            Detail = detail
                        });
                        continue;
                    }
                }

                order.SalesOrderItems.Add(new SalesOrderItem
                {
                    ItemSequence         = orderItemSequence,
                    ContractYear         = contractItemKey == null ? (int?)null : contractItemKey.ContractKey_Year,
                    ContractSequence     = contractItemKey == null ? (int?)null : contractItemKey.ContractKey_Sequence,
                    ContractItemSequence = contractItemKey == null ? (int?)null : contractItemKey.ContractItemKey_Sequence,
                    PriceBase            = (double)(detail.Price ?? 0),
                    PriceFreight         = (double)(detail.FreightP ?? 0),
                    PriceTreatment       = (double)(detail.TrtnmntP ?? 0),
                    PriceWarehouse       = (double)(detail.WHCostP ?? 0),
                    PriceRebate          = (double)(detail.Rebate ?? 0),
                    ODetail = detail.ODetail,

                    InventoryPickOrderItem = new InventoryPickOrderItem
                    {
                        ItemSequence        = orderItemSequence,
                        ProductId           = product.ProductKey.ProductKey_ProductId,
                        PackagingProductId  = packaging.Id,
                        TreatmentId         = treatment.Id,
                        Quantity            = (int)(detail.Quantity ?? 0),
                        CustomerLotCode     = detail.CustLot,
                        CustomerProductCode = detail.CustProductCode,
                    }
                });

                foreach (var staged in detail.tblStagedFGs)
                {
                    LoadCount.AddRead(EntityType.SalesOrderPickedItem);

                    LotKey lotKey;
                    if (!LotNumberParser.ParseLotNumber(staged.Lot, out lotKey))
                    {
                        Log(new CallbackParameters(CallbackReason.StagedInvalidLotNumber)
                        {
                            Order  = oldOrder,
                            Staged = staged
                        });
                        continue;
                    }

                    packaging = _newContextHelper.GetPackagingProduct(staged.PkgID);
                    if (packaging == null)
                    {
                        Log(new CallbackParameters(CallbackReason.StagedPackagingNotFound)
                        {
                            Order  = oldOrder,
                            Staged = staged
                        });
                        continue;
                    }

                    var currentLocation = _newContextHelper.GetLocation(staged.LocID);
                    if (currentLocation == null)
                    {
                        Log(new CallbackParameters(CallbackReason.StagedLocationNotFound)
                        {
                            Order  = oldOrder,
                            Staged = staged
                        });
                        continue;
                    }

                    var fromLocation = detail.tblOutgoing.Any() ? DeterminePickedFromLocation(detail, staged) : currentLocation;
                    if (fromLocation == null)
                    {
                        Log(new CallbackParameters(CallbackReason.UndeterminedPickedFromLocation)
                        {
                            Order  = oldOrder,
                            Staged = staged
                        });
                        continue;
                    }

                    treatment = _newContextHelper.GetInventoryTreatment(staged.TrtmtID);
                    if (treatment == null)
                    {
                        Log(new CallbackParameters(CallbackReason.StagedTreatmentNotFound)
                        {
                            Order  = oldOrder,
                            Staged = staged
                        });
                        continue;
                    }

                    order.SalesOrderPickedItems.Add(new SalesOrderPickedItem
                    {
                        ItemSequence      = pickedItemSequence,
                        OrderItemSequence = orderItemSequence,

                        PickedInventoryItem = new PickedInventoryItem
                        {
                            DetailID        = staged.EntryDate,
                            ItemSequence    = pickedItemSequence,
                            LotDateCreated  = lotKey.LotKey_DateCreated,
                            LotDateSequence = lotKey.LotKey_DateSequence,
                            LotTypeId       = lotKey.LotKey_LotTypeId,

                            Quantity           = (int)(staged.Quantity ?? 0),
                            PackagingProductId = packaging.Id,
                            FromLocationId     = fromLocation.Id,
                            CurrentLocationId  = currentLocation.Id,
                            TreatmentId        = treatment.Id,
                            ToteKey            = "",

                            CustomerLotCode     = staged.CustLot,
                            CustomerProductCode = staged.CustProductCode
                        }
                    });
                    pickedItemSequence++;
                }
                orderItemSequence++;
            }

            return(order);
        }
Example #27
0
            public void Update()
            {
                //Arrange
                var sampleOrder = RVCUnitOfWork
                                  .SampleOrderRepository.Filter(s => s.SampleID != null && s.Items.Count(i => i.SampleDetailID != null) > 1, i => i.Items)
                                  .OrderByDescending(s => s.Year)
                                  .FirstOrDefault();

                if (sampleOrder == null)
                {
                    Assert.Inconclusive("No suitable SampleOrder to test.");
                }

                var chileProduct = RVCUnitOfWork.ChileProductRepository.Filter(c => true, c => c.Product).FirstOrDefault();

                if (chileProduct == null)
                {
                    Assert.Inconclusive("No ChileProdut to test.");
                }

                var chileLot = RVCUnitOfWork.ChileLotRepository.Filter(c => true).FirstOrDefault();

                if (chileLot == null)
                {
                    Assert.Inconclusive("No ChileLot to test.");
                }

                var parameters = new SetSampleOrderParameters
                {
                    SampleOrderKey = sampleOrder.ToSampleOrderKey(),
                    UserToken      = TestUser.UserName,
                    PrintNotes     = ": D",
                    DateReceived   = new DateTime(2016, 1, 1),
                    DateDue        = new DateTime(2016, 1, 2),
                    Items          = new List <ISampleOrderItemParameters>
                    {
                        new SampleOrderItemParameters
                        {
                            SampleOrderItemKey = sampleOrder.Items.First().ToSampleOrderItemKey(),
                            ProductKey         = chileProduct.ToChileProductKey(),
                            LotKey             = chileLot.ToLotKey(),
                            Quantity           = 321,
                            Description        = "updated this item"
                        }
                    }
                };

                //Act
                var result = Service.SetSampleOrder(parameters);

                result.AssertSuccess();
                var resultString = GetKeyFromConsoleString(ConsoleOutput.SynchedTblSample);

                //Assert
                MockKillSwitch.Verify(k => k.Engage(), Times.Never());

                var sampleId = int.Parse(resultString);

                Assert.AreEqual(sampleOrder.SampleID, sampleId);
                using (var oldContext = new RioAccessSQLEntities())
                {
                    var tblSample = oldContext.tblSamples
                                    .Include(s => s.tblSampleDetails)
                                    .FirstOrDefault(s => s.SampleID == sampleId);
                    Assert.AreEqual(parameters.PrintNotes, tblSample.Notes2Print);

                    var expectedItem = parameters.Items.Single();
                    var resultItem   = tblSample.tblSampleDetails.Single();
                    Assert.AreEqual(expectedItem.Quantity, resultItem.Qty);
                    Assert.AreEqual(expectedItem.Description, resultItem.Desc);
                    Assert.AreEqual(chileProduct.Product.ProductCode, resultItem.ProdID.ToString());
                    Assert.AreEqual(LotNumberParser.BuildLotNumber(chileLot), resultItem.Lot);
                }
            }
Example #28
0
            public void Creates_LotKey_as_expected()
            {
                //Arrange
                var oldContext = new RioAccessSQLEntities();
                var helper     = new OldContextHelper(oldContext);
                var packagings = TestHelper.Context.PackagingProducts.Select(p => new
                {
                    Packaging = p,
                    p.Product
                }).ToList();
                tblPackaging tblPackaging;
                var          packaging = packagings.FirstOrDefault(p => helper.GetProductFromPackagingId(p.Product.ProductCode, out tblPackaging) == null);

                if (packaging == null)
                {
                    Assert.Inconclusive("No suitable Packaging product for testing.");
                }

                var location    = RVCUnitOfWork.LocationRepository.Filter(l => l.LocID != null).First();
                var lotDate     = DateTime.Now.Date;
                var lotSequence = 42;

                var parameters = new ReceiveInventoryParameters
                {
                    UserToken            = TestUser.UserName,
                    LotType              = LotTypeEnum.Additive,
                    LotDate              = lotDate,
                    LotSequence          = lotSequence,
                    ProductKey           = new ProductKey((IProductKey)RVCUnitOfWork.AdditiveProductRepository.All().First()),
                    PackagingReceivedKey = new PackagingProductKey(packaging.Packaging),
                    Items = new List <ReceiveInventoryItemParameters>
                    {
                        new ReceiveInventoryItemParameters
                        {
                            Quantity             = 1,
                            PackagingProductKey  = new PackagingProductKey(packaging.Packaging),
                            WarehouseLocationKey = new LocationKey(location),
                            TreatmentKey         = new InventoryTreatmentKey(RVCUnitOfWork.InventoryTreatmentRepository.All().First()),
                            ToteKey = ""
                        },
                    }
                };

                //Act
                var result = Service.ReceiveInventory(parameters);

                result.AssertSuccess();

                var lotString = GetKeyFromConsoleString(ConsoleOutput.ReceivedInventory);

                MockKillSwitch.Verify(k => k.Engage(), Times.Never());

                var newLot = int.Parse(lotString);
                var lotKey = LotNumberParser.ParseLotNumber(newLot);

                Assert.AreEqual((int)LotTypeEnum.Additive, lotKey.LotKey_LotTypeId);
                Assert.AreEqual(lotDate, lotKey.LotKey_DateCreated);
                Assert.AreEqual(lotSequence, lotKey.LotKey_DateSequence);

                var tblLot = oldContext.tblLots.FirstOrDefault(a => a.Lot == newLot);

                Assert.IsNotNull(tblLot);

                Assert.IsNotNull(oldContext.tblPackagings.Single(p => p.Packaging == packaging.Product.Name));
            }
        private IEnumerable <PickedInventoryItem> CreatePickedInventoryItems(IPickedInventoryKey pickedInventoryKey, tblRinconDTO rincon)
        {
            var sequence = 0;

            foreach (var detail in rincon.tblRinconDetails)
            {
                _loadCount.AddRead(EntityTypes.PickedInventoryItem);

                LotKey lotKey;
                if (!LotNumberParser.ParseLotNumber(detail.Lot, out lotKey))
                {
                    Log(new CallbackParameters(CallbackReason.InvalidLotKey)
                    {
                        Detail = detail
                    });
                    continue;
                }

                if (!_newContextHelper.LotLoaded(lotKey))
                {
                    Log(new CallbackParameters(CallbackReason.LotNotLoaded)
                    {
                        Detail = detail
                    });
                    continue;
                }

                var packagingProduct = detail.PTypeID == (int?)LotTypeEnum.Packaging ? _newContextHelper.NoPackagingProduct : _newContextHelper.GetPackagingProduct(detail.PkgID);
                if (packagingProduct == null)
                {
                    Log(new CallbackParameters(CallbackReason.PackagingNotLoaded)
                    {
                        Detail = detail
                    });
                    continue;
                }

                var fromWarehouseLocation = _newContextHelper.GetLocation(detail.CurrLocID);
                if (fromWarehouseLocation == null)
                {
                    Log(new CallbackParameters(CallbackReason.FromWarehouseLocationNotLoaded)
                    {
                        Detail = detail
                    });
                    continue;
                }

                var treatment = _newContextHelper.GetInventoryTreatment(detail.TrtmtID);
                if (treatment == null)
                {
                    Log(new CallbackParameters(CallbackReason.TreatmentNotLoaded)
                    {
                        Detail = detail
                    });
                    continue;
                }

                var destinationLocation = _newContextHelper.GetLocation(detail.DestLocID);
                if (destinationLocation == null)
                {
                    Log(new CallbackParameters(CallbackReason.DestinationLocationNotLoaded)
                    {
                        Detail = detail
                    });
                    continue;
                }

                if (detail.Quantity == null)
                {
                    Log(new CallbackParameters(CallbackReason.MissingQuantity)
                    {
                        Detail = detail
                    });
                    continue;
                }

                yield return(new PickedInventoryItem
                {
                    DateCreated = pickedInventoryKey.PickedInventoryKey_DateCreated,
                    Sequence = pickedInventoryKey.PickedInventoryKey_Sequence,
                    ItemSequence = ++sequence,

                    LotDateCreated = lotKey.LotKey_DateCreated,
                    LotDateSequence = lotKey.LotKey_DateSequence,
                    LotTypeId = lotKey.LotKey_LotTypeId,

                    PackagingProductId = packagingProduct.Id,
                    FromLocationId = fromWarehouseLocation.Id,
                    TreatmentId = treatment.Id,
                    CurrentLocationId = destinationLocation.Id,
                    ToteKey = "",
                    Quantity = (int)detail.Quantity
                });
            }
        }
Example #30
0
        private void SetSchedule(tblProductionSchedule oldProductionSchedule, ProductionSchedule productionSchedule, int lineNumber)
        {
            if (oldProductionSchedule == null)
            {
                OldContext.tblProductionSchedules.AddObject(oldProductionSchedule = new tblProductionSchedule
                {
                    ProductionDate = productionSchedule.ProductionDate,
                    LineNumber     = lineNumber,
                    tblProductionScheduleGroups = new EntityCollection <tblProductionScheduleGroup>()
                });
            }

            oldProductionSchedule.DateCreated = productionSchedule.TimeStamp.ConvertUTCToLocal();
            oldProductionSchedule.CreatedBy   = productionSchedule.EmployeeId;

            var oldGroups = oldProductionSchedule.tblProductionScheduleGroups.ToDictionary(g => g.PSNum);

            foreach (var item in productionSchedule.ScheduledItems)
            {
                tblProductionScheduleGroup oldGroup;
                if (oldGroups.TryGetValue(item.PackSchedule.PSNum.Value, out oldGroup))
                {
                    oldGroups.Remove(item.PackSchedule.PSNum.Value);
                }
                else
                {
                    OldContext.tblProductionScheduleGroups.AddObject(oldGroup = new tblProductionScheduleGroup
                    {
                        ProductionDate             = oldProductionSchedule.ProductionDate,
                        LineNumber                 = oldProductionSchedule.LineNumber,
                        PSNum                      = item.PackSchedule.PSNum.Value,
                        tblProductionScheduleItems = new EntityCollection <tblProductionScheduleItem>()
                    });
                }

                oldGroup.Index                   = item.Index;
                oldGroup.Instructions            = item.PackSchedule.SummaryOfWork;
                oldGroup.FlushBefore             = item.FlushBefore;
                oldGroup.FlushBeforeInstructions = item.FlushBeforeInstructions;
                oldGroup.FlushAfter              = item.FlushAfter;
                oldGroup.FlushAfterInstructions  = item.FlushAfterInstructions;

                var oldItems = oldGroup.tblProductionScheduleItems.ToDictionary(i => i.LotNumber);
                foreach (var batch in item.PackSchedule.ProductionBatches
                         .Where(b => !b.ProductionHasBeenCompleted)
                         .OrderBy(b => b.LotTypeId)
                         .ThenBy(b => b.LotDateCreated)
                         .ThenBy(b => b.LotDateSequence))
                {
                    var lotNumber = LotNumberParser.BuildLotNumber(batch);

                    tblProductionScheduleItem oldItem;
                    if (oldItems.TryGetValue(lotNumber, out oldItem))
                    {
                        oldItems.Remove(lotNumber);
                    }
                    else
                    {
                        OldContext.tblProductionScheduleItems.AddObject(oldItem = new tblProductionScheduleItem
                        {
                            ProductionDate = oldGroup.ProductionDate,
                            LineNumber     = oldGroup.LineNumber,
                            PSNum          = oldGroup.PSNum,
                            LotNumber      = lotNumber
                        });
                    }
                    oldItem.BatchNumber = batch.LotDateSequence;
                }

                foreach (var oldItem in oldItems.Values)
                {
                    OldContext.tblProductionScheduleItems.DeleteObject(oldItem);
                }
            }

            foreach (var oldGroup in oldGroups.Values)
            {
                foreach (var oldItem in oldGroup.tblProductionScheduleItems)
                {
                    OldContext.tblProductionScheduleItems.DeleteObject(oldItem);
                }
                OldContext.tblProductionScheduleGroups.DeleteObject(oldGroup);
            }
        }