public async Task <ActionResult <ElementoConfiguracion> > Delete(Int64 Id, ElementoConfiguracion _ElementoConfiguracionP)
        {
            ElementoConfiguracion _ElementoConfiguracion = _ElementoConfiguracionP;

            try
            {
                string     baseadress = config.Value.urlbase;
                HttpClient _client    = new HttpClient();

                _client.DefaultRequestHeaders.Add("Authorization", "Bearer " + HttpContext.Session.GetString("token"));
                var result = await _client.PostAsJsonAsync(baseadress + "api/ElementoConfiguracion/Delete", _ElementoConfiguracion);

                string valorrespuesta = "";
                if (result.IsSuccessStatusCode)
                {
                    valorrespuesta         = await(result.Content.ReadAsStringAsync());
                    _ElementoConfiguracion = JsonConvert.DeserializeObject <ElementoConfiguracion>(valorrespuesta);
                }
            }
            catch (Exception ex)
            {
                return(BadRequest($"Ocurrio un error{ex.Message}"));
            }

            return(new ObjectResult(new DataSourceResult {
                Data = new[] { _ElementoConfiguracion }, Total = 1
            }));
        }
        public async Task <ActionResult <ElementoConfiguracion> > Insert(ElementoConfiguracion _ElementoConfiguracion)
        {
            try
            {
                // TODO: Add insert logic here
                string     baseadress = config.Value.urlbase;
                HttpClient _client    = new HttpClient();
                _client.DefaultRequestHeaders.Add("Authorization", "Bearer " + HttpContext.Session.GetString("token"));
                _ElementoConfiguracion.UsuarioCreacion     = HttpContext.Session.GetString("user");
                _ElementoConfiguracion.UsuarioModificacion = HttpContext.Session.GetString("user");
                var result = await _client.PostAsJsonAsync(baseadress + "api/ElementoConfiguracion/Insert", _ElementoConfiguracion);

                string valorrespuesta = "";
                if (result.IsSuccessStatusCode)
                {
                    valorrespuesta         = await(result.Content.ReadAsStringAsync());
                    _ElementoConfiguracion = JsonConvert.DeserializeObject <ElementoConfiguracion>(valorrespuesta);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Ocurrio un error: { ex.ToString() }");
                return(BadRequest($"Ocurrio un error{ex.Message}"));
            }

            return(new ObjectResult(new DataSourceResult {
                Data = new[] { _ElementoConfiguracion }, Total = 1
            }));
        }
        public async Task <ActionResult <ElementoConfiguracion> > SaveElementoConfiguracion([FromBody] ElementoConfiguracionDTO _ElementoConfiguracionS)
        {
            ElementoConfiguracion _ElementoConfiguracion = _ElementoConfiguracionS;

            try
            {
                ElementoConfiguracion _listElementoConfiguracion = new ElementoConfiguracion();
                string     baseadress = config.Value.urlbase;
                HttpClient _client    = new HttpClient();
                _client.DefaultRequestHeaders.Add("Authorization", "Bearer " + HttpContext.Session.GetString("token"));
                var result = await _client.GetAsync(baseadress + "api/ElementoConfiguracion/GetElementoConfiguracionById/" + _ElementoConfiguracion.Id);

                string valorrespuesta = "";
                _ElementoConfiguracion.FechaModificacion   = DateTime.Now;
                _ElementoConfiguracion.UsuarioModificacion = HttpContext.Session.GetString("user");

                if (result.IsSuccessStatusCode)
                {
                    valorrespuesta         = await(result.Content.ReadAsStringAsync());
                    _ElementoConfiguracion = JsonConvert.DeserializeObject <ElementoConfiguracionDTO>(valorrespuesta);
                }

                if (_ElementoConfiguracion == null)
                {
                    _ElementoConfiguracion = new Models.ElementoConfiguracion();
                }

                if (_ElementoConfiguracionS.Id == 0)
                {
                    _ElementoConfiguracionS.FechaCreacion   = DateTime.Now;
                    _ElementoConfiguracionS.UsuarioCreacion = HttpContext.Session.GetString("user");

                    //if (_ElementoConfiguracionS.Estado == "Activo")
                    //{
                    //    _ElementoConfiguracionS.Estado = "A";
                    //}
                    //else {
                    //    _ElementoConfiguracionS.Estado = "I";

                    //}

                    var insertresult = await Insert(_ElementoConfiguracionS);
                }
                else
                {
                    _ElementoConfiguracionS.UsuarioCreacion = _ElementoConfiguracion.UsuarioCreacion;
                    _ElementoConfiguracionS.FechaCreacion   = _ElementoConfiguracion.FechaCreacion;
                    var updateresult = await Update(_ElementoConfiguracion.Id, _ElementoConfiguracionS);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Ocurrio un error: { ex.ToString() }");
                throw ex;
            }

            return(Json(_ElementoConfiguracion));
        }
        public async Task <ActionResult> GetElementoConfiguracionByName(String ElementoConfiguracionName)
        {
            try
            {
                ElementoConfiguracion Items = await _context.ElementoConfiguracion.Where(q => q.Nombre == ElementoConfiguracionName).FirstOrDefaultAsync();

                return(await Task.Run(() => Ok(Items)));
            }
            catch (Exception ex)
            {
                _logger.LogError($"Ocurrio un error: { ex.ToString() }");
                return(BadRequest($"Ocurrio un error:{ex.Message}"));
            }
        }
        public async Task <IActionResult> GetElementoConfiguracionById(Int64 Id)
        {
            ElementoConfiguracion Items = new ElementoConfiguracion();

            try
            {
                Items = await _context.ElementoConfiguracion.Where(q => q.Id == Id).FirstOrDefaultAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError($"Ocurrio un error: { ex.ToString() }");
                return(BadRequest($"Ocurrio un error:{ex.Message}"));
            }

            return(await Task.Run(() => Ok(Items)));
        }
        public async Task <ActionResult <ElementoConfiguracion> > Insert([FromBody] ElementoConfiguracion _ElementoConfiguracion)
        {
            ElementoConfiguracion _ElementoConfiguracionq = new ElementoConfiguracion();

            try
            {
                _ElementoConfiguracionq = _ElementoConfiguracion;
                _context.ElementoConfiguracion.Add(_ElementoConfiguracionq);
                await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError($"Ocurrio un error: { ex.ToString() }");
                return(BadRequest($"Ocurrio un error:{ex.Message}"));
            }

            return(Ok(_ElementoConfiguracionq));
        }
Beispiel #7
0
        private async Task <int> GetCaracteresMinimos()
        {
            int maxaccess = 0;

            try
            {
                var        config      = Configuration.GetSection("AppSettings").Get <MyConfig>();
                string     baseadress  = config.urlbase;
                HttpClient _client     = new HttpClient();
                var        resultlogin = await _client.PostAsJsonAsync(baseadress + "api/cuenta/login", new UserInfo { Email = config.UserEmail, Password = config.UserPassword });

                if (resultlogin.IsSuccessStatusCode)
                {
                    string    webtoken   = await(resultlogin.Content.ReadAsStringAsync());
                    UserToken _userToken = JsonConvert.DeserializeObject <UserToken>(webtoken);
                    _client.DefaultRequestHeaders.Add("Authorization", "Bearer " + _userToken.Token);
                    var result = await _client.GetAsync(baseadress + "api/ElementoConfiguracion/GetElementoConfiguracionById/" + 21);

                    //string valorrespuesta = "";
                    if (result.IsSuccessStatusCode)
                    {
                        string res = await result.Content.ReadAsStringAsync();

                        ElementoConfiguracion _elc = JsonConvert.DeserializeObject <ElementoConfiguracion>(res);
                        if (_elc == null)
                        {
                            _elc = new ElementoConfiguracion {
                                Valordecimal = 0
                            };
                        }
                        maxaccess = Convert.ToInt32(_elc.Valordecimal);
                    }
                }
            }
            catch (Exception ex)
            {
                maxaccess = 0;
            }


            return(maxaccess);
        }
        public async Task <IActionResult> Delete([FromBody] ElementoConfiguracion _ElementoConfiguracion)
        {
            ElementoConfiguracion _ElementoConfiguracionq = new ElementoConfiguracion();

            try
            {
                _ElementoConfiguracionq = _context.ElementoConfiguracion
                                          .Where(x => x.Id == (Int64)_ElementoConfiguracion.Id)
                                          .FirstOrDefault();

                _context.ElementoConfiguracion.Remove(_ElementoConfiguracionq);
                await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError($"Ocurrio un error: { ex.ToString() }");
                return(BadRequest($"Ocurrio un error:{ex.Message}"));
            }

            return(await Task.Run(() => Ok(_ElementoConfiguracionq)));
        }
        public async Task <ActionResult <ElementoConfiguracion> > Update([FromBody] ElementoConfiguracion _ElementoConfiguracion)
        {
            ElementoConfiguracion _ElementoConfiguracionq = _ElementoConfiguracion;

            try
            {
                _ElementoConfiguracionq = await(from c in _context.ElementoConfiguracion
                                                .Where(q => q.Id == _ElementoConfiguracion.Id)
                                                select c
                                                ).FirstOrDefaultAsync();

                _context.Entry(_ElementoConfiguracionq).CurrentValues.SetValues((_ElementoConfiguracion));

                //_context.ElementoConfiguracion.Update(_ElementoConfiguracionq);
                await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError($"Ocurrio un error: { ex.ToString() }");
                return(BadRequest($"Ocurrio un error:{ex.Message}"));
            }

            return(await Task.Run(() => Ok(_ElementoConfiguracionq)));
        }
Beispiel #10
0
        public async Task <ActionResult <Invoice> > InsertConAlarma([FromBody] Invoice _Invoice)
        {
            Invoice _Invoiceq = new Invoice();
            ElementoConfiguracion _elemento = new ElementoConfiguracion();
            bool GenerateAlert = false;

            try
            {
                using (var transaction = _context.Database.BeginTransaction())
                {
                    try
                    {
                        _Invoiceq = _Invoice;

                        Invoice _invoice = await _context.Invoice.Where(q => q.BranchId == _Invoice.BranchId)
                                           .Where(q => q.IdPuntoEmision == _Invoice.IdPuntoEmision)
                                           .FirstOrDefaultAsync();

                        if (_invoice != null)
                        {
                            _Invoiceq.NumeroDEI = _context.Invoice.Where(q => q.BranchId == _Invoice.BranchId)
                                                  .Where(q => q.IdPuntoEmision == _Invoice.IdPuntoEmision).Max(q => q.NumeroDEI);
                        }

                        _Invoiceq.NumeroDEI += 1;


                        //  Int64 puntoemision = _context.Users.Where(q=>q.Email==_Invoiceq.UsuarioCreacion).Select(q=>q.)

                        Int64 IdCai = await _context.NumeracionSAR
                                      .Where(q => q.BranchId == _Invoiceq.BranchId)
                                      .Where(q => q.IdPuntoEmision == _Invoiceq.IdPuntoEmision)
                                      .Where(q => q.Estado == "Activo").Select(q => q.IdCAI).FirstOrDefaultAsync();


                        if (IdCai == 0)
                        {
                            return(BadRequest("No existe un CAI activo para el punto de emisión"));
                        }

                        //_Invoiceq.Sucursal = await _context.Branch.Where(q => q.BranchId == _Invoice.BranchId).Select(q => q.BranchCode).FirstOrDefaultAsync();
                        //  _Invoiceq.Caja = await _context.PuntoEmision.Where(q=>q.IdPuntoEmision== _Invoice.IdPuntoEmision).Select(q => q.PuntoEmisionCod).FirstOrDefaultAsync();
                        _Invoiceq.CAI = await _context.CAI.Where(q => q.IdCAI == IdCai).Select(q => q._cai).FirstOrDefaultAsync();

                        Numalet let;
                        let = new Numalet();
                        let.SeparadorDecimalSalida = "Lempiras";
                        let.MascaraSalidaDecimal   = "00/100 ";
                        let.ApocoparUnoParteEntera = true;
                        _Invoiceq.TotalLetras      = let.ToCustomCardinal((_Invoiceq.Total)).ToUpper();

                        _context.Invoice.Add(_Invoiceq);

                        _elemento = await _context.ElementoConfiguracion.Where(q => q.Id == 76).FirstOrDefaultAsync();

                        if (_elemento != null)
                        {
                            if (_Invoiceq.CurrencyId == 1)
                            {
                                if (_Invoiceq.Total > _elemento.Valordecimal)
                                {
                                    GenerateAlert = true;
                                }
                            }
                            else
                            {
                                ExchangeRate rate = new ExchangeRate();
                                rate = await _context.ExchangeRate.Where(q => q.DayofRate == _Invoiceq.InvoiceDate && q.CurrencyId == _Invoiceq.CurrencyId).FirstOrDefaultAsync();

                                if (rate != null)
                                {
                                    if (((double)rate.ExchangeRateValue * _Invoiceq.Total) > _elemento.Valordecimal)
                                    {
                                        GenerateAlert = true;
                                    }
                                }
                            }
                        }

                        if (GenerateAlert)
                        {
                            //se agrega la alerta
                            Alert _alert = new Alert();
                            _alert.DocumentId          = _invoice.InvoiceId;
                            _alert.DocumentName        = "FACTURA";
                            _alert.AlertName           = "Sancionados";
                            _alert.Code                = "PERSON004";
                            _alert.ActionTakenId       = 0;
                            _alert.ActionTakenName     = "";
                            _alert.IdEstado            = 0;
                            _alert.SujetaARos          = false;
                            _alert.FalsoPositivo       = false;
                            _alert.CloseDate           = DateTime.MinValue;
                            _alert.DescriptionAlert    = _invoice.InvoiceId.ToString() + " / " + _invoice.CustomerName + " / " + _invoice.Total.ToString();
                            _alert.FechaCreacion       = DateTime.Now;
                            _alert.FechaModificacion   = DateTime.Now;
                            _alert.UsuarioCreacion     = _invoice.UsuarioCreacion;
                            _alert.UsuarioModificacion = _invoice.UsuarioModificacion;
                            _context.Alert.Add(_alert);

                            //se agrega la informacion a la tabla InvoiceTransReport
                            InvoiceTransReport _report = new InvoiceTransReport();
                            _report.Amount              = _invoice.Total;
                            _report.CustomerId          = _invoice.CustomerId;
                            _report.InvoiceDate         = _invoice.InvoiceDate;
                            _report.FechaCreacion       = DateTime.Now;
                            _report.FechaModificacion   = DateTime.Now;
                            _report.UsuarioCreacion     = _invoice.UsuarioCreacion;
                            _report.UsuarioModificacion = _invoice.UsuarioModificacion;
                            _context.InvoiceTransReport.Add(_report);
                        }
                        //await _context.SaveChangesAsync();
                        foreach (var item in _Invoice.InvoiceLine)
                        {
                            item.InvoiceId = _Invoiceq.InvoiceId;
                            _context.InvoiceLine.Add(item);
                        }

                        await _context.SaveChangesAsync();

                        JournalEntryConfiguration _journalentryconfiguration = await(_context.JournalEntryConfiguration
                                                                                     .Where(q => q.TransactionId == 1)
                                                                                     .Where(q => q.BranchId == _Invoiceq.BranchId)
                                                                                     .Where(q => q.EstadoName == "Activo")
                                                                                     .Include(q => q.JournalEntryConfigurationLine)
                                                                                     ).FirstOrDefaultAsync();

                        BitacoraWrite _writejec = new BitacoraWrite(_context, new Bitacora
                        {
                            IdOperacion  = _Invoice.CustomerId,
                            DocType      = "JournalEntryConfiguration",
                            ClaseInicial =
                                Newtonsoft.Json.JsonConvert.SerializeObject(_journalentryconfiguration, new JsonSerializerSettings {
                                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                            }),
                            ResultadoSerializado = Newtonsoft.Json.JsonConvert.SerializeObject(_journalentryconfiguration, new JsonSerializerSettings {
                                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                            }),
                            Accion              = "InsertInvoice",
                            FechaCreacion       = DateTime.Now,
                            FechaModificacion   = DateTime.Now,
                            UsuarioCreacion     = _Invoice.UsuarioCreacion,
                            UsuarioModificacion = _Invoice.UsuarioModificacion,
                            UsuarioEjecucion    = _Invoice.UsuarioModificacion,
                        });

                        // await _context.SaveChangesAsync();

                        double sumacreditos = 0, sumadebitos = 0;
                        if (_journalentryconfiguration != null)
                        {
                            //Crear el asiento contable configurado
                            //.............................///////
                            JournalEntry _je = new JournalEntry
                            {
                                Date               = _Invoiceq.InvoiceDate,
                                Memo               = "Factura de ventas",
                                DatePosted         = _Invoiceq.InvoiceDate,
                                ModifiedDate       = DateTime.Now,
                                CreatedDate        = DateTime.Now,
                                ModifiedUser       = _Invoiceq.UsuarioModificacion,
                                CreatedUser        = _Invoiceq.UsuarioCreacion,
                                DocumentId         = _Invoiceq.InvoiceId,
                                TypeOfAdjustmentId = 65,
                                VoucherType        = 1,
                            };



                            foreach (var item in _journalentryconfiguration.JournalEntryConfigurationLine)
                            {
                                InvoiceLine _iline = new InvoiceLine();
                                _iline = _Invoiceq.InvoiceLine.Where(q => q.SubProductId == item.SubProductId).FirstOrDefault();
                                if (_iline != null || item.SubProductName.ToUpper().Contains(("Impuesto").ToUpper()))
                                {
                                    if (!item.AccountName.ToUpper().Contains(("Impuestos sobre ventas").ToUpper()) &&
                                        !item.AccountName.ToUpper().Contains(("Sobre Servicios Diversos").ToUpper()))
                                    {
                                        _iline.AccountId   = Convert.ToInt32(item.AccountId);
                                        _iline.AccountName = item.AccountName;
                                        _context.Entry(_iline).CurrentValues.SetValues((_iline));

                                        _je.JournalEntryLines.Add(new JournalEntryLine
                                        {
                                            AccountId    = Convert.ToInt32(item.AccountId),
                                            AccountName  = item.AccountName,
                                            Description  = item.AccountName,
                                            Credit       = item.DebitCredit == "Credito" ? _iline.SubTotal : 0,
                                            Debit        = item.DebitCredit == "Debito" ? _iline.SubTotal : 0,
                                            CreatedDate  = DateTime.Now,
                                            ModifiedDate = DateTime.Now,
                                            CreatedUser  = _Invoiceq.UsuarioCreacion,
                                            ModifiedUser = _Invoiceq.UsuarioModificacion,
                                            Memo         = "",
                                        });

                                        sumacreditos += item.DebitCredit == "Credito" ? _iline.SubTotal : 0;
                                        sumadebitos  += item.DebitCredit == "Debito" ? _iline.SubTotal : 0;
                                    }
                                    else
                                    {
                                        _je.JournalEntryLines.Add(new JournalEntryLine
                                        {
                                            AccountId    = Convert.ToInt32(item.AccountId),
                                            AccountName  = item.AccountName,
                                            Description  = item.AccountName,
                                            Credit       = item.DebitCredit == "Credito" ? _Invoiceq.Tax + _Invoiceq.Tax18 : 0,
                                            Debit        = item.DebitCredit == "Debito" ? _Invoiceq.Tax + _Invoiceq.Tax18 : 0,
                                            CreatedDate  = DateTime.Now,
                                            ModifiedDate = DateTime.Now,
                                            CreatedUser  = _Invoiceq.UsuarioCreacion,
                                            ModifiedUser = _Invoiceq.UsuarioModificacion,
                                            Memo         = "",
                                        });

                                        sumacreditos += item.DebitCredit == "Credito" ? _Invoiceq.Tax + _Invoiceq.Tax18 : 0;
                                        sumadebitos  += item.DebitCredit == "Debito" ? _Invoiceq.Tax + _Invoiceq.Tax18 : 0;
                                    }
                                }

                                // _context.JournalEntryLine.Add(_je);
                            }


                            if (sumacreditos != sumadebitos)
                            {
                                transaction.Rollback();
                                _logger.LogError($"Ocurrio un error: No coinciden debitos :{sumadebitos} y creditos{sumacreditos}");
                                return(BadRequest($"Ocurrio un error: No coinciden debitos :{sumadebitos} y creditos{sumacreditos}"));
                            }

                            _je.TotalCredit = sumacreditos;
                            _je.TotalDebit  = sumadebitos;
                            _context.JournalEntry.Add(_je);

                            await _context.SaveChangesAsync();
                        }

                        BitacoraWrite _write = new BitacoraWrite(_context, new Bitacora
                        {
                            IdOperacion  = _Invoice.CustomerId,
                            DocType      = "Invoice",
                            ClaseInicial =
                                Newtonsoft.Json.JsonConvert.SerializeObject(_Invoice, new JsonSerializerSettings {
                                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                            }),
                            ResultadoSerializado = Newtonsoft.Json.JsonConvert.SerializeObject(_Invoice, new JsonSerializerSettings {
                                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                            }),
                            Accion              = "Insert",
                            FechaCreacion       = DateTime.Now,
                            FechaModificacion   = DateTime.Now,
                            UsuarioCreacion     = _Invoice.UsuarioCreacion,
                            UsuarioModificacion = _Invoice.UsuarioModificacion,
                            UsuarioEjecucion    = _Invoice.UsuarioModificacion,
                        });



                        await _context.SaveChangesAsync();

                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        _logger.LogError($"Ocurrio un error: { ex.ToString() }");
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Ocurrio un error: { ex.ToString() }");
                return(BadRequest($"Ocurrio un error:{ex.Message}"));
            }

            return(await Task.Run(() => Ok(_Invoiceq)));
        }