示例#1
0
        public async Task <ActionResult <JournalEntryConfiguration> > Insert([FromBody] JournalEntryConfiguration _JournalEntryConfiguration)
        {
            JournalEntryConfiguration _JournalEntryConfigurationq = new JournalEntryConfiguration();

            try
            {
                _JournalEntryConfigurationq = _JournalEntryConfiguration;
                _context.JournalEntryConfiguration.Add(_JournalEntryConfigurationq);

                foreach (var item in _JournalEntryConfigurationq.JournalEntryConfigurationLine)
                {
                    item.JournalEntryConfigurationId = _JournalEntryConfigurationq.JournalEntryConfigurationId;
                    _context.JournalEntryConfigurationLine.Add(item);
                }

                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(_JournalEntryConfigurationq)));
        }
示例#2
0
        public async Task <IActionResult> GetJournalEntryConfigurationById(Int64 JournalEntryConfigurationId)
        {
            JournalEntryConfiguration Items = new JournalEntryConfiguration();

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


            return(await Task.Run(() => Ok(Items)));
        }
示例#3
0
        public async Task <ActionResult <JournalEntryConfiguration> > Update([FromBody] JournalEntryConfiguration _JournalEntryConfiguration)
        {
            JournalEntryConfiguration _JournalEntryConfigurationq = new JournalEntryConfiguration();

            try
            {
                _JournalEntryConfigurationq = await(from c in _context.JournalEntryConfiguration
                                                    .Where(q => q.JournalEntryConfigurationId == _JournalEntryConfiguration.JournalEntryConfigurationId)
                                                    select c
                                                    ).FirstOrDefaultAsync();

                _context.Entry(_JournalEntryConfigurationq).CurrentValues.SetValues((_JournalEntryConfiguration));


                foreach (var item in _JournalEntryConfiguration.JournalEntryConfigurationLine)
                {
                    item.JournalEntryConfigurationId = _JournalEntryConfigurationq.JournalEntryConfigurationId;

                    JournalEntryConfigurationLine data = await _context.JournalEntryConfigurationLine
                                                         .Where(q => q.JournalEntryConfigurationLineId == item.JournalEntryConfigurationLineId).FirstOrDefaultAsync();

                    if (data == null)
                    {
                        _context.JournalEntryConfigurationLine.Add(item);
                    }
                    else
                    {
                        _context.Entry(data).CurrentValues.SetValues((item));
                    }
                }



                //_context.JournalEntryConfiguration.Update(_JournalEntryConfigurationq);
                await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError($"Ocurrio un error: { ex.ToString() }");
                return(await Task.Run(() => BadRequest($"Ocurrio un error:{ex.Message}")));
            }

            return(await Task.Run(() => Ok(_JournalEntryConfigurationq)));
        }
示例#4
0
        public async Task <IActionResult> Delete([FromBody] JournalEntryConfiguration _JournalEntryConfiguration)
        {
            JournalEntryConfiguration _JournalEntryConfigurationq = new JournalEntryConfiguration();

            try
            {
                _JournalEntryConfigurationq = _context.JournalEntryConfiguration
                                              .Where(x => x.JournalEntryConfigurationId == (Int64)_JournalEntryConfiguration.JournalEntryConfigurationId)
                                              .FirstOrDefault();

                _context.JournalEntryConfiguration.Remove(_JournalEntryConfigurationq);
                await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError($"Ocurrio un error: { ex.ToString() }");
                return(await Task.Run(() => BadRequest($"Ocurrio un error:{ex.Message}")));
            }

            return(await Task.Run(() => Ok(_JournalEntryConfigurationq)));
        }
        public async Task <ActionResult <InsurancePolicy> > AjusteDiferencialCambiario([FromBody] InsurancePolicy _InsurancePolicy)
        {
            InsurancePolicy InsurancePolicyq = _InsurancePolicy;
            InsurancePolicy _Original;

            try
            {
                using (var transaction = _context.Database.BeginTransaction())
                {
                    try
                    {
                        _Original = await _context.InsurancePolicy.Where(q => q.InsurancePolicyId == _InsurancePolicy.InsurancePolicyId).FirstOrDefaultAsync();

                        InsurancePolicyq = await(from c in _context.InsurancePolicy
                                                 .Where(q => q.InsurancePolicyId == _InsurancePolicy.InsurancePolicyId)
                                                 select c
                                                 ).FirstOrDefaultAsync();

                        _context.Entry(InsurancePolicyq).CurrentValues.SetValues((_InsurancePolicy));

                        await _context.SaveChangesAsync();

                        BitacoraWrite _write = new BitacoraWrite(_context, new Bitacora
                        {
                            IdOperacion  = InsurancePolicyq.InsurancePolicyId,
                            DocType      = "InsurancePolicy",
                            ClaseInicial =
                                Newtonsoft.Json.JsonConvert.SerializeObject(InsurancePolicyq, new JsonSerializerSettings {
                                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                            }),
                            Accion              = "AjusteDiferencialCambiario",
                            FechaCreacion       = DateTime.Now,
                            FechaModificacion   = DateTime.Now,
                            UsuarioCreacion     = InsurancePolicyq.UsuarioCreacion,
                            UsuarioModificacion = InsurancePolicyq.UsuarioModificacion,
                            UsuarioEjecucion    = InsurancePolicyq.UsuarioModificacion,
                        });

                        await _context.SaveChangesAsync();

                        transaction.Commit();

                        if (_Original != null)
                        {
                            if (_Original.LpsAmount != _InsurancePolicy.LpsAmount || _Original.DollarAmount != _InsurancePolicy.DollarAmount)
                            {
                                JournalEntryConfiguration _journalentryconfiguration = await(_context.JournalEntryConfiguration
                                                                                             .Where(q => q.TransactionId == 1)
                                                                                             //.Where(q => q.BranchId == InsurancePolicyq.BranchId)
                                                                                             .Where(q => q.EstadoName == "Activo")
                                                                                             .Include(q => q.JournalEntryConfigurationLine)
                                                                                             ).FirstOrDefaultAsync();

                                BitacoraWrite _writejec = new BitacoraWrite(_context, new Bitacora
                                {
                                    IdOperacion  = InsurancePolicyq.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              = "AjusteDiferencialCambiario",
                                    FechaCreacion       = DateTime.Now,
                                    FechaModificacion   = DateTime.Now,
                                    UsuarioCreacion     = InsurancePolicyq.UsuarioCreacion,
                                    UsuarioModificacion = InsurancePolicyq.UsuarioModificacion,
                                    UsuarioEjecucion    = InsurancePolicyq.UsuarioModificacion,
                                });

                                // await _context.SaveChangesAsync();

                                double sumacreditos = 0, sumadebitos = 0;
                                if (_journalentryconfiguration != null)
                                {
                                    //Crear el asiento contable configurado
                                    //.............................///////
                                    JournalEntry _je = new JournalEntry
                                    {
                                        Date               = InsurancePolicyq.PolicyDate,
                                        Memo               = "Contra Partidad de Poliza: Ajuste por diferencial cambiario",
                                        DatePosted         = InsurancePolicyq.PolicyDate,
                                        ModifiedDate       = DateTime.Now,
                                        CreatedDate        = DateTime.Now,
                                        ModifiedUser       = InsurancePolicyq.UsuarioModificacion,
                                        CreatedUser        = InsurancePolicyq.UsuarioCreacion,
                                        DocumentId         = InsurancePolicyq.InsurancePolicyId,
                                        TypeOfAdjustmentId = 65,
                                        VoucherType        = 1,
                                    };



                                    foreach (var item in _journalentryconfiguration.JournalEntryConfigurationLine)
                                    {
                                        _je.JournalEntryLines.Add(new JournalEntryLine
                                        {
                                            AccountId    = Convert.ToInt32(item.AccountId),
                                            AccountName  = item.AccountName,
                                            Description  = item.AccountName,
                                            Debit        = item.DebitCredit == "Credito" ? (InsurancePolicyq.LpsAmount > 0 ? InsurancePolicyq.LpsAmount : InsurancePolicyq.DollarAmount) : 0,
                                            Credit       = item.DebitCredit == "Debito" ? (InsurancePolicyq.LpsAmount > 0 ? InsurancePolicyq.LpsAmount : InsurancePolicyq.DollarAmount) : 0,
                                            CreatedDate  = DateTime.Now,
                                            ModifiedDate = DateTime.Now,
                                            CreatedUser  = InsurancePolicyq.UsuarioCreacion,
                                            ModifiedUser = InsurancePolicyq.UsuarioModificacion,
                                            Memo         = "",
                                        });

                                        sumacreditos += item.DebitCredit == "Debito" ? (InsurancePolicyq.LpsAmount > 0 ? InsurancePolicyq.LpsAmount : InsurancePolicyq.DollarAmount) : 0;
                                        sumadebitos  += item.DebitCredit == "Credito" ? (InsurancePolicyq.LpsAmount > 0 ? InsurancePolicyq.LpsAmount : InsurancePolicyq.DollarAmount) : 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();
                                }

                                _write = new BitacoraWrite(_context, new Bitacora
                                {
                                    IdOperacion  = InsurancePolicyq.InsurancePolicyId,
                                    DocType      = "InsurancePolicy",
                                    ClaseInicial =
                                        Newtonsoft.Json.JsonConvert.SerializeObject(InsurancePolicyq, new JsonSerializerSettings {
                                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                                    }),
                                    Accion              = "AjusteDiferencialCambiario",
                                    FechaCreacion       = DateTime.Now,
                                    FechaModificacion   = DateTime.Now,
                                    UsuarioCreacion     = InsurancePolicyq.UsuarioCreacion,
                                    UsuarioModificacion = InsurancePolicyq.UsuarioModificacion,
                                    UsuarioEjecucion    = InsurancePolicyq.UsuarioModificacion,
                                });

                                await _context.SaveChangesAsync();
                            }
                        }
                    }
                    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(InsurancePolicyq)));
        }
示例#6
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)));
        }
        public async Task <IActionResult> EjecutarCierreContable([FromBody] BitacoraCierreContable pBitacoraCierre)
        {
            using (var transaction = _context.Database.BeginTransaction())
            {
                try
                {
                    BitacoraCierreContable existeCierre = await _context.BitacoraCierreContable.Where(b => b.FechaCierre.Date == pBitacoraCierre.FechaCierre.Date).FirstOrDefaultAsync();

                    if (existeCierre != null)
                    {
                        return(await Task.Run(() => BadRequest("Ya existe un Cierre Contable para esta Fecha")));
                    }
                    BitacoraCierreContable cierre = new BitacoraCierreContable
                    {
                        FechaCierre         = pBitacoraCierre.FechaCierre.Date,
                        FechaCreacion       = DateTime.Now,
                        Estatus             = "PENDIENTE",
                        EstatusId           = 1,
                        UsuarioCreacion     = User.Claims.FirstOrDefault().Value.ToString(),
                        UsuarioModificacion = User.Claims.FirstOrDefault().Value.ToString(),
                        FechaModificacion   = DateTime.Now,
                    };
                    _context.BitacoraCierreContable.Add(cierre);

                    //Paso 1
                    BitacoraCierreProcesos proceso1 = new BitacoraCierreProcesos
                    {
                        IdBitacoraCierre = cierre.Id,
                        //IdProceso = 1,
                        Estatus             = "PENDIENTE",
                        Proceso             = "HISTORICOS",
                        PasoCierre          = 1,
                        UsuarioCreacion     = User.Claims.FirstOrDefault().Value.ToString(),
                        UsuarioModificacion = User.Claims.FirstOrDefault().Value.ToString(),
                        FechaModificacion   = DateTime.Now,
                        FechaCierre         = DateTime.Now,
                        FechaCreacion       = DateTime.Now,
                    };
                    //Paso2
                    BitacoraCierreProcesos proceso2 = new BitacoraCierreProcesos
                    {
                        IdBitacoraCierre = cierre.Id,
                        //IdProceso = 1,
                        Estatus             = "PENDIENTE",
                        Proceso             = "VALOR MAXIMO CERTIFICADO DE DEPOSITO",
                        PasoCierre          = 2,
                        UsuarioCreacion     = User.Claims.FirstOrDefault().Value.ToString(),
                        UsuarioModificacion = User.Claims.FirstOrDefault().Value.ToString(),
                        FechaModificacion   = DateTime.Now,
                        FechaCierre         = DateTime.Now,
                        FechaCreacion       = DateTime.Now,
                    };

                    //Paso3
                    BitacoraCierreProcesos proceso3 = new BitacoraCierreProcesos
                    {
                        IdBitacoraCierre = cierre.Id,
                        //IdProceso = 1,
                        Estatus             = "PENDIENTE",
                        Proceso             = "POLIZAS DE SEGURO VENCIDAS",
                        PasoCierre          = 3,
                        UsuarioCreacion     = User.Claims.FirstOrDefault().Value.ToString(),
                        UsuarioModificacion = User.Claims.FirstOrDefault().Value.ToString(),
                        FechaModificacion   = DateTime.Now,
                        FechaCierre         = DateTime.Now,
                        FechaCreacion       = DateTime.Now,
                    };
                    _context.BitacoraCierreProceso.Add(proceso1);
                    _context.BitacoraCierreProceso.Add(proceso2);
                    _context.BitacoraCierreProceso.Add(proceso3);

                    List <InsurancePolicy> insurancePolicies = _context.InsurancePolicy.Where(i => i.PolicyDueDate < DateTime.Now).ToList();

                    double SumaPolizas = _context.InsurancePolicy.Where(i => i.PolicyDueDate < DateTime.Now).ToList().
                                         Sum(s => s.LpsAmount);

                    if (insurancePolicies.Count > 0)
                    {
                        foreach (var item in insurancePolicies)
                        {
                            item.Status = "INACTIVA";
                        }
                        _context.InsurancePolicy.UpdateRange(insurancePolicies);
                        proceso3.Estatus = "FINALIZADO";

                        if (SumaPolizas > 0)
                        {
                            TiposDocumento            tipoDocumento = _context.TiposDocumento.Where(d => d.Descripcion == "Polizas").FirstOrDefault();
                            JournalEntryConfiguration _journalentryconfiguration = await(_context.JournalEntryConfiguration
                                                                                         .Where(q => q.TransactionId == tipoDocumento.IdTipoDocumento)
                                                                                         //.Where(q => q.BranchId == _Invoiceq.BranchId)
                                                                                         .Where(q => q.EstadoName == "Activo")
                                                                                         .Include(q => q.JournalEntryConfigurationLine)
                                                                                         ).FirstOrDefaultAsync();


                            double sumacreditos = 0, sumadebitos = 0;
                            if (_journalentryconfiguration != null)
                            {
                                //Crear el asiento contable configurado
                                //.............................///////
                                JournalEntry _je = new JournalEntry
                                {
                                    Date               = pBitacoraCierre.FechaCierre,
                                    Memo               = "Vecimiento de Polizas",
                                    DatePosted         = pBitacoraCierre.FechaCierre,
                                    ModifiedDate       = DateTime.Now,
                                    CreatedDate        = DateTime.Now,
                                    ModifiedUser       = pBitacoraCierre.UsuarioCreacion,
                                    CreatedUser        = pBitacoraCierre.UsuarioCreacion,
                                    DocumentId         = pBitacoraCierre.Id,
                                    TypeOfAdjustmentId = 65,
                                    VoucherType        = Convert.ToInt32(tipoDocumento.IdTipoDocumento),
                                };



                                foreach (var item in _journalentryconfiguration.JournalEntryConfigurationLine)
                                {
                                    _je.JournalEntryLines.Add(new JournalEntryLine
                                    {
                                        AccountId    = Convert.ToInt32(item.AccountId),
                                        AccountName  = item.AccountName,
                                        Description  = item.AccountName,
                                        Credit       = item.DebitCredit == "Credito" ? SumaPolizas : 0,
                                        Debit        = item.DebitCredit == "Debito" ? SumaPolizas : 0,
                                        CreatedDate  = DateTime.Now,
                                        ModifiedDate = DateTime.Now,
                                        CreatedUser  = pBitacoraCierre.UsuarioCreacion,
                                        ModifiedUser = pBitacoraCierre.UsuarioModificacion,
                                        Memo         = "",
                                    });

                                    // sumacreditos += item.DebitCredit == "Credito" ? _Invoiceq.Tax + _Invoiceq.Tax18 : 0;
                                    //sumadebitos += item.DebitCredit == "Debito" ? _Invoiceq.Tax + _Invoiceq.Tax18 : 0;
                                }
                            }
                        }
                    }
                    else
                    {
                        proceso3.Estatus = "FINALIZADO";
                        //proceso3.Mensaje = "FINALIZADO No se encontraron Polizas Vencidas";
                    }

                    /////////////Fin del Paso 3

                    _context.SaveChanges();

                    //List< BitacoraCierreProcesos> spCierre = await _context.BitacoraCierreProceso.FromSql("Cierres @p0, @p1, @p2", pBitacoraCierre.FechaCierre, cierre.Id).ToListAsync();
                    _context.Database.ExecuteSqlCommand("Cierres @p0, @p1", pBitacoraCierre.FechaCierre, cierre.Id);

                    transaction.Commit();
                    return(await Task.Run(() => Ok()));
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    return(await Task.Run(() => BadRequest(ex.Message)));
                }
            }
        }
        public async Task <ActionResult <GoodsReceived> > Insert([FromBody] GoodsReceivedDTO _GoodsReceived)
        {
            GoodsReceived _GoodsReceivedq = new GoodsReceived();

            try
            {
                using (var transaction = _context.Database.BeginTransaction())
                {
                    try
                    {
                        _GoodsReceivedq = _GoodsReceived;

                        BoletaDeSalida _boletadesalida = new BoletaDeSalida
                        {
                            BranchId            = _GoodsReceived.BranchId,
                            BranchName          = _GoodsReceived.BranchName,
                            CustomerId          = _GoodsReceived.CustomerId,
                            CustomerName        = _GoodsReceived.CustomerName,
                            DocumentDate        = _GoodsReceived.DocumentDate,
                            FechaCreacion       = DateTime.Now,
                            FechaModificacion   = DateTime.Now,
                            Marca               = _GoodsReceived.Marca,
                            Placa               = _GoodsReceived.Placa,
                            Motorista           = _GoodsReceived.Name,
                            Quantity            = _GoodsReceived._GoodsReceivedLine.Select(q => q.QuantitySacos).Sum(),
                            SubProductId        = _GoodsReceivedq._GoodsReceivedLine[0].SubProductId,
                            SubProductName      = _GoodsReceivedq._GoodsReceivedLine[0].SubProductName,
                            CargadoId           = 14,
                            Cargadoname         = "Vacío",
                            UsuarioCreacion     = _GoodsReceived.UsuarioCreacion,
                            UsuarioModificacion = _GoodsReceived.UsuarioModificacion,
                            UnitOfMeasureId     = _GoodsReceivedq._GoodsReceivedLine[0].UnitOfMeasureId,
                            UnitOfMeasureName   = _GoodsReceivedq._GoodsReceivedLine[0].UnitOfMeasureName,
                            WeightBallot        = _GoodsReceivedq.WeightBallot,
                            VigilanteId         = _GoodsReceivedq.VigilanteId,
                            Vigilante           = _GoodsReceivedq.VigilanteName,
                        };

                        _context.BoletaDeSalida.Add(_boletadesalida);
                        await _context.SaveChangesAsync();


                        _GoodsReceivedq.ExitTicket = _boletadesalida.BoletaDeSalidaId;

                        _context.GoodsReceived.Add(_GoodsReceivedq);
                        // await _context.SaveChangesAsync();

                        foreach (var item in _GoodsReceivedq._GoodsReceivedLine)
                        {
                            item.GoodsReceivedId = _GoodsReceivedq.GoodsReceivedId;


                            Kardex _kardexmax = await(from c in _context.Kardex
                                                      .OrderByDescending(q => q.DocumentDate)
                                                      // .Take(1)
                                                      join d in _context.KardexLine on c.KardexId equals d.KardexId
                                                      where c.CustomerId == _GoodsReceivedq.CustomerId && d.SubProducId == item.SubProductId &&
                                                      c.DocumentName != "CD" && d.WareHouseId == item.WareHouseId
                                                      select c
                                                      ).FirstOrDefaultAsync();

                            //Kardex _kardexmax = await (from kdx in _context.Kardex
                            //            .Where(q => q.CustomerId == _GoodsReceivedq.CustomerId)
                            //            from kdxline in _context.KardexLine
                            //                .Where(q => q.KardexId == kdx.KardexId)
                            //                .Where(o => o.SubProducId == item.SubProductId)
                            //                //.Where(q=>q.BranchId ==  _GoodsReceivedq.BranchId)
                            //                //.Where(q => q.WareHouseId == _GoodsReceivedq.WarehouseId)
                            //                .OrderByDescending(o => o.DocumentDate).Take(1)
                            //            select kdx).FirstOrDefaultAsync();

                            if (_kardexmax == null)
                            {
                                _kardexmax = new Kardex();
                            }


                            KardexLine _KardexLine = await _context.KardexLine
                                                     .Where(q => q.KardexId == _kardexmax.KardexId)
                                                     .Where(q => q.SubProducId == item.SubProductId)
                                                     .Where(q => q.WareHouseId == item.WareHouseId)
                                                     .Where(q => q.BranchId == _GoodsReceivedq.BranchId)
                                                     .OrderByDescending(q => q.KardexLineId)
                                                     .Take(1)
                                                     .FirstOrDefaultAsync();

                            if (_KardexLine == null)
                            {
                                _KardexLine = new KardexLine();
                            }

                            SubProduct _subproduct = await(from c in _context.SubProduct
                                                           .Where(q => q.SubproductId == item.SubProductId)
                                                           select c
                                                           ).FirstOrDefaultAsync();
                            if (_subproduct.ProductTypeId == 3)
                            {
                                //Alert AlertP = new Alert();
                                Alert Alerta = new Alert();
                                Alerta.DocumentId          = item.SubProductId;
                                Alerta.DocumentName        = "LISTA PROHIBIDA";
                                Alerta.AlertName           = "Productos";
                                Alerta.Code                = "PRODUCT01";
                                Alerta.DescriptionAlert    = "Lista de producto Prohibida";
                                Alerta.FechaCreacion       = Convert.ToDateTime(item.FechaCreacion);
                                Alerta.FechaModificacion   = Convert.ToDateTime(item.FechaModificacion);
                                Alerta.UsuarioCreacion     = item.UsuarioCreacion;
                                Alerta.UsuarioModificacion = item.UsuarioModificacion;
                                // var AlertaP = await InsertAlert(Alerta);
                                _context.Alert.Add(Alerta);
                                //await _context.SaveChangesAsync();

                                BitacoraWrite _writealert = new BitacoraWrite(_context, new Bitacora
                                {
                                    IdOperacion  = Alerta.AlertId,
                                    DocType      = "Alert",
                                    ClaseInicial =
                                        Newtonsoft.Json.JsonConvert.SerializeObject(Alerta, new JsonSerializerSettings {
                                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                                    }),
                                    Accion              = "Insertar",
                                    FechaCreacion       = DateTime.Now,
                                    FechaModificacion   = DateTime.Now,
                                    UsuarioCreacion     = Alerta.UsuarioCreacion,
                                    UsuarioModificacion = Alerta.UsuarioModificacion,
                                    UsuarioEjecucion    = Alerta.UsuarioModificacion,
                                });

                                // await _context.SaveChangesAsync();
                            }

                            _context.GoodsReceivedLine.Add(item);

                            item.Total = item.Quantity + _KardexLine.Total;


                            _GoodsReceived.Kardex._KardexLine.Add(new KardexLine
                            {
                                DocumentDate      = _GoodsReceivedq.DocumentDate,
                                ProducId          = item.ProducId,
                                ProductName       = item.ProductName,
                                SubProducId       = item.SubProductId,
                                SubProductName    = item.SubProductName,
                                QuantityEntry     = item.Quantity,
                                QuantityOut       = 0,
                                QuantityEntryBags = item.QuantitySacos,
                                BranchId          = _GoodsReceivedq.BranchId,
                                BranchName        = _GoodsReceivedq.BranchName,
                                WareHouseId       = item.WareHouseId,
                                WareHouseName     = item.WareHouseName,
                                UnitOfMeasureId   = item.UnitOfMeasureId,
                                UnitOfMeasureName = item.UnitOfMeasureName,
                                TypeOperationId   = 1,
                                TypeOperationName = "Entrada",
                                Total             = item.Total,
                                TotalBags         = item.QuantitySacos + _KardexLine.TotalBags,
                                QuantityEntryCD   = item.Quantity - (item.Quantity * _subproduct.Merma),
                                TotalCD           = _KardexLine.TotalCD + (item.Quantity - (item.Quantity * _subproduct.Merma)),
                            });
                        }//Fin Foreach

                        await _context.SaveChangesAsync();

                        _GoodsReceived.Kardex.DocType           = 0;
                        _GoodsReceived.Kardex.DocName           = "ReciboMercaderia/GoodsReceived";
                        _GoodsReceived.Kardex.DocumentDate      = _GoodsReceivedq.DocumentDate;
                        _GoodsReceived.Kardex.FechaCreacion     = DateTime.Now;
                        _GoodsReceived.Kardex.FechaModificacion = DateTime.Now;
                        _GoodsReceived.Kardex.TypeOperationId   = 1;
                        _GoodsReceived.Kardex.TypeOperationName = "Entrada";
                        _GoodsReceived.Kardex.KardexDate        = DateTime.Now;
                        _GoodsReceived.Kardex.DocumentName      = "RM";

                        _GoodsReceived.Kardex.CustomerId          = _GoodsReceivedq.CustomerId;
                        _GoodsReceived.Kardex.CustomerName        = _GoodsReceivedq.CustomerName;
                        _GoodsReceived.Kardex.CurrencyId          = _GoodsReceivedq.CurrencyId;
                        _GoodsReceived.Kardex.CurrencyName        = _GoodsReceivedq.CurrencyName;
                        _GoodsReceived.Kardex.DocumentId          = _GoodsReceivedq.GoodsReceivedId;
                        _GoodsReceived.Kardex.UsuarioCreacion     = _GoodsReceivedq.UsuarioCreacion;
                        _GoodsReceived.Kardex.UsuarioModificacion = _GoodsReceivedq.UsuarioModificacion;



                        if (_GoodsReceived.ControlId > 0)
                        {
                            _context.Kardex.Add(_GoodsReceived.Kardex);
                        }

                        await _context.SaveChangesAsync();

                        foreach (var item in _GoodsReceivedq._GoodsReceivedLine)
                        {
                            if (item.ControlPalletsId == null)
                            {
                                item.ControlPalletsId = 0;
                            }
                            ControlPallets _ControlPalletsq = await _context.ControlPallets.Where(q => q.ControlPalletsId == item.ControlPalletsId)
                                                              .FirstOrDefaultAsync();

                            if (_ControlPalletsq != null)
                            {
                                _ControlPalletsq.QQPesoBruto = _GoodsReceivedq.PesoBruto;
                                _ControlPalletsq.QQPesoNeto  = _GoodsReceivedq.PesoNeto;
                                _ControlPalletsq.QQPesoFinal = _GoodsReceivedq.PesoNeto2;

                                _context.Entry(_ControlPalletsq).CurrentValues.SetValues((_ControlPalletsq));
                            }
                        }

                        await _context.SaveChangesAsync();

                        BoletaDeSalida _bol = await _context.BoletaDeSalida
                                              .Where(q => q.BoletaDeSalidaId == _boletadesalida.BoletaDeSalidaId).FirstOrDefaultAsync();

                        _bol.GoodsReceivedId = _GoodsReceivedq.GoodsReceivedId;
                        _context.Entry(_bol).CurrentValues.SetValues((_bol));

                        await _context.SaveChangesAsync();

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

                        BitacoraWrite _writejec = new BitacoraWrite(_context, new Bitacora
                        {
                            IdOperacion  = _GoodsReceived.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              = "InsertGoodsReceived",
                            FechaCreacion       = DateTime.Now,
                            FechaModificacion   = DateTime.Now,
                            UsuarioCreacion     = _GoodsReceived.UsuarioCreacion,
                            UsuarioModificacion = _GoodsReceived.UsuarioModificacion,
                            UsuarioEjecucion    = _GoodsReceived.UsuarioModificacion,
                        });

                        // await _context.SaveChangesAsync();

                        double sumacreditos = 0, sumadebitos = 0;
                        if (_journalentryconfiguration != null)
                        {
                            //Crear el asiento contable configurado
                            //.............................///////
                            JournalEntry _je = new JournalEntry
                            {
                                Date         = _GoodsReceivedq.OrderDate,
                                Memo         = "Bienes Recibidos",
                                DatePosted   = _GoodsReceivedq.OrderDate,
                                ModifiedDate = DateTime.Now,
                                CreatedDate  = DateTime.Now,
                                ModifiedUser = _GoodsReceivedq.UsuarioModificacion,
                                CreatedUser  = _GoodsReceivedq.UsuarioCreacion,
                                DocumentId   = _GoodsReceivedq.GoodsReceivedId,
                            };



                            foreach (var item in _journalentryconfiguration.JournalEntryConfigurationLine)
                            {
                                GoodsReceivedLine _iline = new GoodsReceivedLine();
                                _iline = _GoodsReceivedq._GoodsReceivedLine.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()))
                                    {
                                        _je.JournalEntryLines.Add(new JournalEntryLine
                                        {
                                            AccountId    = Convert.ToInt32(item.AccountId),
                                            Description  = item.AccountName,
                                            Credit       = item.DebitCredit == "Credito" ? _iline.Total : 0,
                                            Debit        = item.DebitCredit == "Debito" ? _iline.Total : 0,
                                            CreatedDate  = DateTime.Now,
                                            ModifiedDate = DateTime.Now,
                                            CreatedUser  = _GoodsReceivedq.UsuarioCreacion,
                                            ModifiedUser = _GoodsReceivedq.UsuarioModificacion,
                                            Memo         = "",
                                        });

                                        sumacreditos += item.DebitCredit == "Credito" ? _iline.Total : 0;
                                        sumadebitos  += item.DebitCredit == "Debito" ? _iline.Total : 0;
                                    }
                                    else
                                    {
                                        _je.JournalEntryLines.Add(new JournalEntryLine
                                        {
                                            AccountId    = Convert.ToInt32(item.AccountId),
                                            Description  = item.AccountName,
                                            CreatedDate  = DateTime.Now,
                                            ModifiedDate = DateTime.Now,
                                            CreatedUser  = _GoodsReceivedq.UsuarioCreacion,
                                            ModifiedUser = _GoodsReceivedq.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  = _GoodsReceivedq.GoodsReceivedId,
                            DocType      = "GoodsReceived",
                            ClaseInicial =
                                Newtonsoft.Json.JsonConvert.SerializeObject(_GoodsReceivedq, new JsonSerializerSettings {
                                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                            }),
                            ResultadoSerializado = Newtonsoft.Json.JsonConvert.SerializeObject(_GoodsReceivedq, new JsonSerializerSettings {
                                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                            }),
                            Accion              = "Insert",
                            FechaCreacion       = DateTime.Now,
                            FechaModificacion   = DateTime.Now,
                            UsuarioCreacion     = _GoodsReceivedq.UsuarioCreacion,
                            UsuarioModificacion = _GoodsReceivedq.UsuarioModificacion,
                            UsuarioEjecucion    = _GoodsReceivedq.UsuarioModificacion,
                        });

                        await _context.SaveChangesAsync();


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

            return(await Task.Run(() => Ok(_GoodsReceivedq)));
        }
        public async Task <ActionResult <GarantiaBancaria> > Insert([FromBody] GarantiaBancaria _GarantiaBancaria)
        {
            GarantiaBancaria _GarantiaBancariaq = new GarantiaBancaria();

            try
            {
                using (var transaction = _context.Database.BeginTransaction())
                {
                    try
                    {
                        _GarantiaBancariaq = _GarantiaBancaria;
                        _context.GarantiaBancaria.Add(_GarantiaBancariaq);
                        await _context.SaveChangesAsync();

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

                        BitacoraWrite _writejec = new BitacoraWrite(_context, new Bitacora
                        {
                            IdOperacion  = _GarantiaBancaria.Id,
                            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              = "InsertGarantiaBancaria",
                            FechaCreacion       = DateTime.Now,
                            FechaModificacion   = DateTime.Now,
                            UsuarioCreacion     = _GarantiaBancaria.UsuarioCreacion,
                            UsuarioModificacion = _GarantiaBancaria.UsuarioModificacion,
                            UsuarioEjecucion    = _GarantiaBancaria.UsuarioModificacion,
                        });

                        // await _context.SaveChangesAsync();

                        double sumacreditos = 0, sumadebitos = 0;
                        if (_journalentryconfiguration != null)
                        {
                            //Crear el asiento contable configurado
                            //.............................///////
                            JournalEntry _je = new JournalEntry
                            {
                                Date               = _GarantiaBancariaq.FechaCreacion,
                                Memo               = "Partidad Ingreso de Garantia Bancaria",
                                DatePosted         = _GarantiaBancariaq.FechaCreacion,
                                ModifiedDate       = DateTime.Now,
                                CreatedDate        = DateTime.Now,
                                ModifiedUser       = _GarantiaBancariaq.UsuarioModificacion,
                                CreatedUser        = _GarantiaBancariaq.UsuarioCreacion,
                                DocumentId         = _GarantiaBancariaq.Id,
                                TypeOfAdjustmentId = 65,
                                VoucherType        = 1,
                            };



                            foreach (var item in _journalentryconfiguration.JournalEntryConfigurationLine)
                            {
                                _je.JournalEntryLines.Add(new JournalEntryLine
                                {
                                    AccountId    = Convert.ToInt32(item.AccountId),
                                    AccountName  = item.AccountName,
                                    Description  = item.AccountName,
                                    Credit       = item.DebitCredit == "Credito" ? _GarantiaBancariaq.Monto : 0,
                                    Debit        = item.DebitCredit == "Debito" ? _GarantiaBancariaq.Monto : 0,
                                    CreatedDate  = DateTime.Now,
                                    ModifiedDate = DateTime.Now,
                                    CreatedUser  = _GarantiaBancariaq.UsuarioCreacion,
                                    ModifiedUser = _GarantiaBancariaq.UsuarioModificacion,
                                    Memo         = "",
                                });

                                sumacreditos += item.DebitCredit == "Credito" ? _GarantiaBancariaq.Monto : 0;
                                sumadebitos  += item.DebitCredit == "Debito" ? _GarantiaBancariaq.Monto : 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  = _GarantiaBancariaq.Id,
                            DocType      = "GarantiaBancaria",
                            ClaseInicial =
                                Newtonsoft.Json.JsonConvert.SerializeObject(_GarantiaBancariaq, new JsonSerializerSettings {
                                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                            }),
                            Accion              = "Insertar",
                            FechaCreacion       = DateTime.Now,
                            FechaModificacion   = DateTime.Now,
                            UsuarioCreacion     = _GarantiaBancariaq.UsuarioCreacion,
                            UsuarioModificacion = _GarantiaBancariaq.UsuarioModificacion,
                            UsuarioEjecucion    = _GarantiaBancariaq.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(_GarantiaBancariaq)));
        }