public JsonResult GetProjectDim([FromBody] string ProjectNo)
        {
            ProjectListItemViewModel result = new ProjectListItemViewModel();

            List <NAVProjectsViewModel> navList = DBNAV2017Projects.GetAll(_config.NAVDatabaseName, _config.NAVCompanyName, ProjectNo).ToList();
            NAVProjectsViewModel        Project = navList.Where(x => x.No == ProjectNo).FirstOrDefault();

            if (Project != null)
            {
                result.ProjectNo                = ProjectNo;
                result.RegionCode               = Project.RegionCode != null ? Project.RegionCode : "";
                result.FunctionalAreaCode       = Project.AreaCode != null ? Project.AreaCode : "";
                result.ResponsabilityCenterCode = Project.CenterResponsibilityCode != null ? Project.CenterResponsibilityCode : "";
            }
            else
            {
                result.RegionCode               = "";
                result.FunctionalAreaCode       = "";
                result.ResponsabilityCenterCode = "";
            }

            return(Json(result));
        }
Exemplo n.º 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);
        }