Пример #1
0
        public RequisitionViewModel ValidateRequisition(RequisitionViewModel requisition)
        {
            requisition.eReasonCode = 99;
            requisition.eMessage    = "Ocorreu um erro na Validação da Requisição.";

            try
            {
                if (requisition != null)
                {
                    if (requisition.State == RequisitionStates.Approved)
                    {
                        if (requisition.Lines != null && requisition.Lines.Count > 0)
                        {
                            var linesToValidate = requisition.Lines
                                                  .Where(x => x.QuantityRequired != null && x.QuantityRequired.HasValue && x.QuantityRequired.Value > 0)
                                                  .ToList();

                            if (linesToValidate != null && linesToValidate.Count > 0)
                            {
                                linesToValidate.ForEach(item =>
                                {
                                    item.QuantityToProvide = item.QuantityRequired; // QuantidadeADisponibilizar = QuantidadeRequerida
                                    item.UpdateUser        = this.changedByUserName;
                                    item.UpdateDateTime    = DateTime.Now;

                                    if (DBRequestLine.Update(item.ParseToDB()) == null)
                                    {
                                        requisition.eReasonCode = 2;
                                        requisition.eMessage    = "Ocorreu um erro ao atualizar as linhas na Validação da Requisição.";
                                    }
                                });

                                if (requisition.eReasonCode == 99)
                                {
                                    requisition.State = RequisitionStates.Validated;
                                    requisition.ResponsibleValidation = this.changedByUserName;
                                    requisition.ValidationDate        = DateTime.Now;
                                    requisition.UpdateUser            = this.changedByUserName;

                                    var updatedReq = DBRequest.UpdateHeaderAndLines(requisition.ParseToDB(), true);
                                    if (updatedReq != null)
                                    {
                                        requisition             = updatedReq.ParseToViewModel();
                                        requisition.eReasonCode = 1;
                                        requisition.eMessage    = "Requisição validada com sucesso.";
                                    }
                                    else
                                    {
                                        requisition.eReasonCode = 3;
                                        requisition.eMessage    = "Ocorreu um erro ao validar a requisição.";
                                    }
                                }
                            }
                            else
                            {
                                requisition.eReasonCode = 4;
                                requisition.eMessage    = "Não existem linhas com Qt. Requerida superior a zero.";
                            }
                        }
                        else
                        {
                            requisition.eReasonCode = 5;
                            requisition.eMessage    = "Não existem linhas para validar na Requisição.";
                        }
                    }
                    else
                    {
                        requisition.eReasonCode = 6;
                        requisition.eMessage    = "A Requisição não está no estado Aprovado.";
                    }
                }
                else
                {
                    requisition = new RequisitionViewModel()
                    {
                        eReasonCode = 7,
                        eMessage    = "Erro na obtenção da Requisição.",
                    };
                }
            }
            catch
            {
                requisition.eReasonCode = 99;
                requisition.eMessage    = "Ocorreu um erro na Validação da Requisição.";
            };

            return(requisition);
        }
Пример #2
0
        public RequisitionViewModel CreatePurchaseOrderFor(RequisitionViewModel requisition)
        {
            if (requisition != null && requisition.Lines != null && requisition.Lines.Count > 0)
            {
                if (string.IsNullOrEmpty(requisition.ReceivedDate))
                {
                    requisition.eReasonCode = 4;
                    requisition.eMessage    = "É obrigatório o preenchimento do campo Data Receção no Geral.";
                    return(requisition);
                }

                //use for database update later
                var requisitionLines = requisition.Lines;

                requisitionLines.RemoveAll(x => x.CriarNotaEncomenda == null || x.CriarNotaEncomenda == false);
                requisitionLines.RemoveAll(x => x.CreatedOrderNo != "" && x.CreatedOrderNo != null);
                //FIM

                if (requisitionLines.Any(x => string.IsNullOrEmpty(x.SupplierNo) || !x.UnitCost.HasValue || x.UnitCost.Value == 0))
                {
                    throw new Exception("É obrigatório o preenchimento do fornecedor e do custo unitário nas linhas");
                }


                List <PurchOrderDTO> purchOrders = new List <PurchOrderDTO>();
                List <DBNAV2017SupplierProductRef.SuppliersProductsRefs> supplierProductRef = new List <DBNAV2017SupplierProductRef.SuppliersProductsRefs>();

                try
                {
                    purchOrders = requisitionLines.GroupBy(x =>
                                                           x.SupplierNo,
                                                           x => x,
                                                           (key, items) => new PurchOrderDTO
                    {
                        SupplierId               = key,
                        RequisitionId            = requisition.RequisitionNo,
                        CenterResponsibilityCode = requisition.CenterResponsibilityCode,
                        FunctionalAreaCode       = requisition.FunctionalAreaCode,
                        RegionCode               = requisition.RegionCode,
                        LocalMarketRegion        = requisition.LocalMarketRegion,
                        InAdvance          = requisition.InAdvance.HasValue ? requisition.InAdvance.Value : false,
                        PricesIncludingVAT = requisition.PricesIncludingVAT.HasValue ? requisition.PricesIncludingVAT.Value : false,
                        LocationCode       = requisition.LocalCode,
                        Purchaser_Code     = requisition.NumeroMecanografico,


                        Lines = items.Select(line => new PurchOrderLineDTO()
                        {
                            LineId                   = line.LineNo,
                            Type                     = line.Type,
                            Code                     = line.Code,
                            Description              = line.Description,
                            Description2             = line.Description2,
                            ProjectNo                = line.ProjectNo,
                            QuantityRequired         = line.QuantityRequired,
                            UnitCost                 = line.UnitCost,
                            LocationCode             = line.LocalCode,
                            OpenOrderNo              = line.OpenOrderNo,
                            OpenOrderLineNo          = line.OpenOrderLineNo,
                            CenterResponsibilityCode = line.CenterResponsibilityCode,
                            FunctionalAreaCode       = line.FunctionalAreaCode,
                            RegionCode               = line.RegionCode,
                            UnitMeasureCode          = line.UnitMeasureCode,
                            VATBusinessPostingGroup  = line.VATBusinessPostingGroup,
                            VATProductPostingGroup   = line.VATProductPostingGroup,
                            DiscountPercentage       = line.DiscountPercentage.HasValue ? line.DiscountPercentage.Value : 0,
                        })
                                .ToList()
                    })
                                  .ToList();

                    supplierProductRef = DBNAV2017SupplierProductRef.GetSuplierProductRefsForRequisition(_config.NAVDatabaseName, _config.NAVCompanyName, requisition.RequisitionNo);
                }
                catch
                {
                    throw new Exception("Ocorreu um erro ao agrupar as linhas.");
                }

                if (purchOrders.Count() > 0)
                {
                    purchOrders.ForEach(purchOrder =>
                    {
                        try
                        {
                            purchOrder.Lines.ForEach(line =>
                                                     line.SupplierProductCode = supplierProductRef
                                                                                .Where(x => x.ProductId == line.Code &&
                                                                                       x.SupplierNo == purchOrder.SupplierId &&
                                                                                       x.UnitOfMeasureCode == line.UnitMeasureCode)
                                                                                .FirstOrDefault()
                                                                                ?.SupplierProductId
                                                     );

                            //Novo código que adiciona + linhas mas só para requisições do tipo nutrição
                            if (requisition.RequestNutrition == true)
                            {
                                string codFornecedor = purchOrder.SupplierId;
                                List <ConfigLinhasEncFornecedor> LinhasEncFornecedor = DBConfigLinhasEncFornecedor.GetAll().Where(x => x.VendorNo == codFornecedor).ToList();

                                if (LinhasEncFornecedor != null && LinhasEncFornecedor.Count > 0)
                                {
                                    foreach (ConfigLinhasEncFornecedor linha in LinhasEncFornecedor)
                                    {
                                        string ProjectNo                = string.Empty;
                                        string RegionCode               = string.Empty;
                                        string FunctionalAreaCode       = string.Empty;
                                        string CenterResponsibilityCode = string.Empty;
                                        string ArmazemCompraDireta      = string.Empty;

                                        Configuração Config = DBConfigurations.GetById(1);
                                        if (Config != null)
                                        {
                                            ArmazemCompraDireta = Config.ArmazemCompraDireta;
                                        }

                                        UnidadesProdutivas UnidProd = DBProductivityUnits.GetAll().Where(x => x.NºCliente == codFornecedor).FirstOrDefault();
                                        if (UnidProd != null)
                                        {
                                            ProjectNo = UnidProd.ProjetoMatSubsidiárias;
                                        }

                                        if (!string.IsNullOrEmpty(ProjectNo))
                                        {
                                            NAVProjectsViewModel Project = DBNAV2017Projects.GetAll(_config.NAVDatabaseName, _config.NAVCompanyName, ProjectNo).FirstOrDefault();
                                            if (Project != null)
                                            {
                                                RegionCode               = Project.RegionCode;
                                                FunctionalAreaCode       = Project.AreaCode;
                                                CenterResponsibilityCode = Project.CenterResponsibilityCode;
                                            }
                                        }

                                        PurchOrderLineDTO purchOrderLine = new PurchOrderLineDTO()
                                        {
                                            LineId                   = null,
                                            Type                     = 2, //PRODUTO
                                            Code                     = linha.No,
                                            Description              = linha.Description,
                                            Description2             = linha.Description2,
                                            ProjectNo                = ProjectNo,
                                            QuantityRequired         = linha.Quantity,
                                            UnitCost                 = linha.Valor,
                                            LocationCode             = ArmazemCompraDireta,
                                            OpenOrderNo              = "",   //line.OpenOrderNo,
                                            OpenOrderLineNo          = null, //line.OpenOrderLineNo,
                                            CenterResponsibilityCode = CenterResponsibilityCode,
                                            FunctionalAreaCode       = FunctionalAreaCode,
                                            RegionCode               = RegionCode,
                                            UnitMeasureCode          = linha.UnitOfMeasure,
                                            VATBusinessPostingGroup  = "", //line.VATBusinessPostingGroup,
                                            VATProductPostingGroup   = "", //line.VATProductPostingGroup,
                                            DiscountPercentage       = 0   //line.DiscountPercentage.HasValue ? line.DiscountPercentage.Value : 0,
                                        };
                                        purchOrder.Lines.Add(purchOrderLine);
                                    }
                                }
                            }

                            //var result = CreateNAVPurchaseOrderFor(purchOrder, Convert.ToDateTime(requisition.ReceivedDate), requisition.Comments);
                            var result = CreateNAVPurchaseOrderFor(purchOrder, Convert.ToDateTime(requisition.ReceivedDate));
                            if (result.CompletedSuccessfully)
                            {
                                //Update req
                                requisition.OrderNo = result.ResultValue;

                                //Update Requisition Lines
                                requisition.Lines.ForEach(line =>
                                {
                                    if (line.SupplierNo == purchOrder.SupplierId)
                                    {
                                        line.CreatedOrderNo = result.ResultValue;
                                        line.UpdateUser     = this.changedByUserName;
                                    }
                                });
                                //Commit to DB
                                var updatedReq = DBRequest.Update(requisition.ParseToDB(), true);
                                //bool linesUpdated = DBRequestLine.Update(requisition.Lines.ParseToDB());
                                //if (linesUpdated)
                                if (updatedReq != null)
                                {
                                    requisition.eMessages.Add(new TraceInformation(TraceType.Success, "Criada encomenda para o fornecedor núm. " + purchOrder.SupplierId + "; "));
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            requisition.eMessages.Add(new TraceInformation(TraceType.Error, "Ocorreu um erro ao criar encomenda para o fornecedor núm. " + purchOrder.SupplierId + ": " + ex.Message));
                            //requisition.eMessages.Add(new TraceInformation(TraceType.Exception, purchOrder.SupplierId + " " + ex.Message));
                        }
                    });

                    if (requisition.eMessages.Any(x => x.Type == TraceType.Success))
                    {
                        //Refresh lines - Get from db
                        var updatedLines = DBRequestLine.GetByRequisitionId(requisition.RequisitionNo);
                        if (updatedLines != null)
                        {
                            requisition.Lines = updatedLines.ParseToViewModel();
                        }
                    }

                    if (requisition.eMessages.Any(x => x.Type == TraceType.Error))
                    {
                        requisition.eReasonCode = 2;
                        requisition.eMessage    = "Ocorram erros ao criar encomenda de compra.";
                    }
                    else
                    {
                        requisition.eReasonCode = 1;
                        requisition.eMessage    = "Encomenda de compra criada com sucesso.";
                    }
                }
                else
                {
                    requisition.eReasonCode = 3;
                    requisition.eMessage    = "Não existem linhas que cumpram os requisitos de criação de encomenda.";
                }
            }
            return(requisition);
        }