Exemplo n.º 1
0
        public void TestMethod1()
        {
            /*var res = ArticuloLogica.Instancia.ingresarBodega(1, "Bodega San Pedro", "123");
            var result = ArticuloLogica.Instancia.obtenerBodegas(1);
            var result = ArticuloLogica.Instancia.ingresarArticulo(1, "100213", "Lápices Mongol", "unidad", "Son chinos", Convert.FromBase64String(""), 1);*/
            //var res = ArticuloLogica.Instancia.obtenerArticulosBodega("Bodega San Pedro");
            var orden = new Documento() {
                Fecha1= System.DateTime.Now,
                IdSocio = 2,
                TipoDocumento = 1,
                TotalAI = 1300
            };
            var detalle = new DocumentoDetalle(){
                NumeroDocumento = 22,
                IdArticulo = 1,
                Cantidad = 10,
                Descripcion = "Lapices Mongol",
                IdBodega = 1,
                Impuesto = 13,
                Precio = 130,
                TipoDocumento = 1

            };
            Email email = new Email();
            email.EnviarCorreo("*****@*****.**", orden, detalle);
        }
Exemplo n.º 2
0
        private async void dgvDocumentos_DoubleClick(object sender, EventArgs e)
        {
            DocumentoDetalle doc = dgvDocumentos.SelectedRows[0].DataBoundItem as DocumentoDetalle;


            if (doc.TipoDocumento == "RS")
            {
                IServiceAlmacen service = new ServiceAlmacen();

                var response = await service.DocumentoGetByTipoNumeroSedeAsync("RS", Convert.ToInt16(doc.NroDocumento), doc.Sede.Id_Sede);

                if (response.IsValid)
                {
                    Usuario usuarioCreador = new Usuario();
                    rptConsultaSalida.Visible = true;
                    rptConsultaSalida.BringToFront();
                    btnCloseReport.Visible = true;
                    btnCloseReport.Parent  = rptConsultaSalida;
                    btnCloseReport.BringToFront();
                    documento = response.Value;

                    var responseUsuario = service.UsuarioGetByUser(documento.UsuarioCreacion);
                    usuarioCreador = responseUsuario.Value;
                    string nombreUsuario = usuarioCreador.Nombres + " " + usuarioCreador.Apellidos;

                    rptConsultaSalida.ProcessingMode = ProcessingMode.Local;
                    rptConsultaSalida.LocalReport.DataSources.Clear();
                    ReportDataSource Reporte = new ReportDataSource("DataSet1", documento.Documento_Articulo);
                    rptConsultaSalida.LocalReport.DataSources.Add(Reporte);

                    List <ReportParameter> parametros = new List <ReportParameter>();
                    parametros.Add(new ReportParameter("nombreSede", "" + documento.Sede.NombreSede));
                    parametros.Add(new ReportParameter("nombreDocumento", "RS-" + documento.Sede.Codigo + "-" + documento.NroDocumento.ToString("0000000")));
                    parametros.Add(new ReportParameter("nombreUsuario", nombreUsuario));
                    parametros.Add(new ReportParameter("fechaCreacion", "" + documento.FechaCreacion));
                    //Añado parametros al reportviewer
                    this.rptConsultaSalida.LocalReport.SetParameters(parametros);

                    rptConsultaSalida.RefreshReport();
                    rptConsultaSalida.Focus();
                }
                else
                {
                    MessageBox.Show(response.ErrorMensaje);
                }
            }
            else if (doc.TipoDocumento == "PR")
            {
                IServiceAlmacen service = new ServiceAlmacen();

                var response = await service.DocumentoGetByTipoPresupuestoAsync(doc.TipoDocumento, doc.TipoPresupuesto, Convert.ToInt16(doc.NroDocumento));

                if (response.IsValid)
                {
                    Usuario usuarioCreador = new Usuario();
                    rptPresupuesto.Visible = true;
                    rptPresupuesto.BringToFront();
                    btnCloseReport.Visible = true;
                    btnCloseReport.Parent  = rptPresupuesto;
                    btnCloseReport.BringToFront();
                    documento = response.Value;

                    var responseUsuario = service.UsuarioGetByUser(documento.UsuarioCreacion);
                    usuarioCreador = responseUsuario.Value;
                    string nombreUsuario = usuarioCreador.Nombres + " " + usuarioCreador.Apellidos;

                    rptPresupuesto.ProcessingMode = ProcessingMode.Local;
                    rptPresupuesto.LocalReport.DataSources.Clear();
                    ReportDataSource Reporte = new ReportDataSource("DataSet1", documento.Documento_Articulo);
                    rptPresupuesto.LocalReport.DataSources.Add(Reporte);
                    ReportDataSource Reporte2 = new ReportDataSource("DataSet2", documento.Documento_Articulo);
                    rptPresupuesto.LocalReport.DataSources.Add(Reporte2);
                    string moneda = "";
                    string estado = "";
                    if (documento.Moneda == "S")
                    {
                        moneda = "S/. ";
                    }
                    else
                    {
                        moneda = "US$ ";
                    }
                    if (documento.Estado == "A")
                    {
                        estado = "PENDIENTE";
                    }
                    else if (documento.Estado == "P")
                    {
                        estado = "PROCESADO";
                    }
                    else
                    {
                        estado = "ANULADO";
                    }
                    List <ReportParameter> parametros = new List <ReportParameter>();
                    parametros.Add(new ReportParameter("nombreDocumento", "N° PR - " + documento.TipoPresupuesto + " - " + documento.NroDocumento.ToString("0000000")));
                    parametros.Add(new ReportParameter("nombreUsuario", nombreUsuario));
                    parametros.Add(new ReportParameter("fechaCreacion", documento.FechaCreacion.ToString("hh:mm:ss - MM/dd/yyyy ")));
                    parametros.Add(new ReportParameter("moneda", moneda));
                    parametros.Add(new ReportParameter("estado", estado));

                    this.rptPresupuesto.LocalReport.SetParameters(parametros);
                    rptPresupuesto.RefreshReport();
                    rptPresupuesto.Focus();
                }
                else
                {
                    MessageBox.Show(response.ErrorMensaje);
                }
            }
            else if (doc.TipoDocumento == "OC")
            {
                IServiceAlmacen service = new ServiceAlmacen();

                var response = await service.DocumentoGetByTipoPresupuestoAsync(doc.TipoDocumento, doc.TipoPresupuesto, Convert.ToInt16(doc.NroDocumento));

                if (response.IsValid)
                {
                    Documento presupuesto    = new Documento();
                    Usuario   usuarioCreador = new Usuario();
                    rptOdenCompra.Visible = true;
                    btnCloseReport.Parent = rptOdenCompra;
                    btnCloseReport.BringToFront();
                    rptOdenCompra.BringToFront();
                    btnCloseReport.Visible = true;

                    documento = response.Value;
                    var responsePresupuesto = service.DocumentoGetById(documento.Id_DocumentoOrigen);
                    var responseUsuario     = service.UsuarioGetByUser(documento.UsuarioCreacion);

                    presupuesto    = responsePresupuesto.Value;
                    usuarioCreador = responseUsuario.Value;

                    rptOdenCompra.ProcessingMode = ProcessingMode.Local;
                    rptOdenCompra.LocalReport.DataSources.Clear();
                    ReportDataSource Reporte = new ReportDataSource("DataSet1", documento.Documento_Articulo);
                    rptOdenCompra.LocalReport.DataSources.Add(Reporte);
                    string estado = "";
                    if (documento.Estado == "A")
                    {
                        estado = "GENERADO";
                    }
                    else
                    {
                        estado = "ANULADO";
                    }
                    List <ReportParameter> parametros = new List <ReportParameter>();
                    string nroOrden = "N° OC - " + documento.TipoPresupuesto + " - " + documento.NroDocumento.ToString("0000000");
                    //string nombres = Session.CurrentSession.Usuario.Nombres + " " + Session.CurrentSession.Usuario.Apellidos;
                    string nombres = usuarioCreador.Nombres + " " + usuarioCreador.Apellidos;
                    string fecha   = documento.FechaCreacion.ToString("hh:mm:ss - MM/dd/yyyy ");
                    string est     = estado;
                    string moneda  = string.Empty;
                    if (presupuesto.Moneda == "S")
                    {
                        moneda = "S/. ";
                    }
                    else
                    {
                        moneda = "US$ ";
                    }
                    string nroPrespuesto    = "N° PR - " + presupuesto.TipoPresupuesto + " - " + presupuesto.NroDocumento.ToString("0000000");
                    string totalPresupuesto = moneda + string.Format("{0:0.0000}", documento.MontoDisponible);
                    string totalOrdenCompra = moneda + string.Format("{0:0.0000}", documento.MontoTotal);
                    string montoDisponible  = moneda + string.Format("{0:0.0000}", documento.MontoDisponible - documento.MontoTotal);
                    parametros.Add(new ReportParameter("nroOrdenCompra", nroOrden));
                    parametros.Add(new ReportParameter("nombre", nombres));
                    parametros.Add(new ReportParameter("fechaCreacion", fecha));
                    parametros.Add(new ReportParameter("estado", est));
                    parametros.Add(new ReportParameter("nroPresupuesto", nroPrespuesto));
                    parametros.Add(new ReportParameter("totalPresupuesto", totalPresupuesto));
                    parametros.Add(new ReportParameter("totalOrdenCompra", totalOrdenCompra));
                    parametros.Add(new ReportParameter("montoDisponible", montoDisponible));
                    this.rptOdenCompra.LocalReport.SetParameters(parametros);
                    rptOdenCompra.RefreshReport();
                    rptOdenCompra.Focus();
                }
                else
                {
                    MessageBox.Show(response.ErrorMensaje);
                }
            }
        }
Exemplo n.º 3
0
        private void btnCondSal2_Click(object sender, EventArgs e)
        {
            DocumentoDetalle det = dgvDocumentos.SelectedRows[0].DataBoundItem as DocumentoDetalle;



            switch (det.TipoDocumento)
            {
            case "RS":
                try
                {
                    if (det.Estado == "A")
                    {
                        DialogResult dialog = MessageBox.Show("¿Seguro de eliminar el registro de salida RS-" + det.Sede.Codigo + "-" + det.NroDocumento.ToString("00000000") + "\n Esta operación no se podra revertir", "Advertencia", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (DialogResult.Yes == dialog)
                        {
                            IServiceAlmacen service     = new ServiceAlmacen();
                            var             responseDoc = service.DocumentoGetByTipoNumeroSede(det.TipoDocumento, det.NroDocumento, det.Sede.Id_Sede);
                            documento = responseDoc.Value;
                            documento.UsuarioModificacion = Session.CurrentSession.Usuario.Usuario1;
                            var response = service.DocumentoAnular(documento);
                            if (response.IsValid)
                            {
                                MessageBox.Show("Documento anulado correctamente", "Aviso");
                                rptConsultaSalida.Clear();
                                loadDocumento();
                            }
                            else
                            {
                                MessageBox.Show(response.ErrorMensaje, "No se anulo el documento", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("El documento se encuentra anulado", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Ocurrio un error " + ex.Message, "Aviso");
                }
                break;

            case "PR":
                try
                {
                    if (det.Estado == "A" || det.Estado == "P")
                    {
                        DialogResult dialog = MessageBox.Show("¿Seguro de eliminar el presupuesto N° PR - " + det.TipoPresupuesto + " - " + det.NroDocumento.ToString("0000000") + "\n Esta operación no se podra revertir", "Advertencia", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (DialogResult.Yes == dialog)
                        {
                            IServiceAlmacen service     = new ServiceAlmacen();
                            var             responseDoc = service.DocumentoGetByTipoPresupuesto(det.TipoDocumento, det.TipoPresupuesto, det.NroDocumento);
                            documento = responseDoc.Value;
                            documento.UsuarioModificacion = Session.CurrentSession.Usuario.Usuario1;
                            var response = service.DocumentoAnular(documento);
                            if (response.IsValid)
                            {
                                MessageBox.Show("Documento anulado correctamente", "Aviso");
                                loadDocumento();
                            }
                            else
                            {
                                MessageBox.Show(response.ErrorMensaje, "No se anulo el documento", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("El documento se encuentra anulado", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Ocurrio un error " + ex.Message, "Aviso");
                }
                break;

            case "OC":
                try
                {
                    if (det.Estado == "A")
                    {
                        DialogResult dialog = MessageBox.Show("¿Seguro de eliminar la orden de compra N° OC -" + det.TipoPresupuesto + " - " + det.NroDocumento.ToString("000000") + "\n Esta operación no se podra revertir", "Advertencia", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (DialogResult.Yes == dialog)
                        {
                            IServiceAlmacen service     = new ServiceAlmacen();
                            var             responseDoc = service.DocumentoGetByTipoPresupuesto(det.TipoDocumento, det.TipoPresupuesto, det.NroDocumento);
                            documento = responseDoc.Value;
                            documento.UsuarioModificacion = Session.CurrentSession.Usuario.Usuario1;
                            var response = service.DocumentoAnular(documento);
                            if (response.IsValid)
                            {
                                MessageBox.Show("Documento anulado correctamente", "Aviso");
                                loadDocumento();
                            }
                            else
                            {
                                MessageBox.Show(response.ErrorMensaje, "No se anulo el documento", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Ocurrio un error " + ex.Message, "Aviso");
                }
                break;
            }
        }
Exemplo n.º 4
0
        public async void loadDocumento()
        {
            DateTime fechaInicio = dtpFechaInicio.Value.Date;
            DateTime fechaFin    = dtpFechaFin.Value.Date.AddDays(1);
            int      nroDocumento;

            if (!txtNumd.Text.Trim().Equals(String.Empty))
            {
                nroDocumento = Convert.ToInt16(txtNumd.Text);
            }
            else
            {
                nroDocumento = 0;
            }
            string estado = "";

            switch (cboEstado.SelectedIndex)
            {
            case 0: estado = "T"; break;

            case 1: estado = "A"; break;

            case 2: estado = "I"; break;
            }

            if (valor == "TODOS")
            {
                string          tipoDocumento = valor;
                IServiceAlmacen service       = new ServiceAlmacen();
                var             response      = await service.DocumentoGetAllReport(tipoDocumento, estado, fechaInicio, fechaFin, nroDocumento);

                List <Documento>        listaDocumento = response.Value;
                List <DocumentoDetalle> listaDetalles  = new List <DocumentoDetalle>();
                foreach (Documento d in listaDocumento)
                {
                    DocumentoDetalle det = new DocumentoDetalle(d);
                    listaDetalles.Add(det);
                }
                dgvDocumentos.DataSource = listaDetalles;
            }
            else if (valor == "PR")
            {
                string tipoDocumento = valor;
                string tipoPre       = "";
                if ((string)cboTipoPre.SelectedItem == "VAR")
                {
                    tipoPre = "VAR";
                }
                if ((string)cboTipoPre.SelectedItem == "PLA")
                {
                    tipoPre = "PLA";
                }
                if ((string)cboTipoPre.SelectedItem == "LAB")
                {
                    tipoPre = "LAB";
                }
                IServiceAlmacen service  = new ServiceAlmacen();
                var             response = await service.DocumentoGetAllReport(tipoDocumento, estado, fechaInicio, fechaFin, nroDocumento, tipoPre);

                if (response.IsValid)
                {
                    List <Documento>        listaDocumento = response.Value;
                    List <DocumentoDetalle> listaDetalles  = new List <DocumentoDetalle>();
                    foreach (Documento d in listaDocumento)
                    {
                        DocumentoDetalle det = new DocumentoDetalle(d);
                        listaDetalles.Add(det);
                    }
                    dgvDocumentos.DataSource = listaDetalles;
                }
                else
                {
                    MessageBox.Show(response.ErrorMensaje);
                }
            }
            else if (valor == "RS")
            {
                string          tipoDocumento = "RS";
                Sede            sede          = cboSede.SelectedItem as Sede;
                IServiceAlmacen service       = new ServiceAlmacen();
                var             response      = await service.DocumentoGetAllReport(tipoDocumento, estado, fechaInicio, fechaFin, nroDocumento, "", sede);

                List <Documento>        listaDocumento = response.Value;
                List <DocumentoDetalle> listaDetalles  = new List <DocumentoDetalle>();
                foreach (Documento d in listaDocumento)
                {
                    DocumentoDetalle det = new DocumentoDetalle(d);
                    listaDetalles.Add(det);
                }
                dgvDocumentos.DataSource = listaDetalles;
            }
            else if (valor == "OD")
            {
                string tipoDocumento = "OC";
                string tipoPre       = string.Empty;
                if ((string)cboTipoPre.SelectedItem == "VAR")
                {
                    tipoPre = "VAR";
                }
                if ((string)cboTipoPre.SelectedItem == "PLA")
                {
                    tipoPre = "PLA";
                }
                if ((string)cboTipoPre.SelectedItem == "LAB")
                {
                    tipoPre = "LAB";
                }

                IServiceAlmacen service  = new ServiceAlmacen();
                var             response = await service.DocumentoGetAllReport(tipoDocumento, estado, fechaInicio, fechaFin, nroDocumento, tipoPre);

                if (response.IsValid)
                {
                    List <Documento>        listaDocumento = response.Value;
                    List <DocumentoDetalle> listaDetalles  = new List <DocumentoDetalle>();
                    foreach (Documento d in listaDocumento)
                    {
                        DocumentoDetalle det = new DocumentoDetalle(d);
                        listaDetalles.Add(det);
                    }
                    dgvDocumentos.DataSource = listaDetalles;
                }
                else
                {
                    MessageBox.Show(response.ErrorMensaje);
                }
            }
        }
        public void InterfaceFaturamento()
        {
            HttpClient client  = new HttpClient();
            ClsDal     context = new ClsDal();

            try
            {
                CultureInfo usCulture = new CultureInfo("en-US");

                byte tipoVenda = 0;

                bool temImposto;
                bool setPosted = Convert.ToBoolean(ConfigurationManager.AppSettings["setPosted"].ToString());
                bool notaCredito;

                string uriAddress        = ConfigurationManager.AppSettings["uriBase"].ToString();
                string mediaType         = ConfigurationManager.AppSettings["mediaType"].ToString();
                string apiKey            = ConfigurationManager.AppSettings["apiKey"].ToString();
                string metodoTransaction = "";
                string metodoOrder       = "";
                string itemServico       = "";
                string tipoTransacao     = "";
                string clienteNacional   = "";
                string prefixoSerie;
                string keyVessel;
                string keyRebaje;
                string idAlternativo  = "";
                string codigoArticulo = "";

                int codigoDocumento;
                int numeroLinha;
                int qtdDias    = 0;
                int page       = 1;
                int totalPages = 0;

                decimal montoDTR       = 0;
                decimal totalRegistros = 0;
                decimal somaDesconto;
                decimal somaValorIGV;
                decimal somaFatura;
                decimal valorBruto;

                List <string> lstTransactionId = new List <string>();

                List <StructCompanies> lstCompanies = new List <StructCompanies>();

                client.BaseAddress = new System.Uri(uriAddress);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(mediaType));
                client.DefaultRequestHeaders.Add("API-Key", apiKey);

                try
                {
                    montoDTR = Convert.ToDecimal(ConfigurationManager.AppSettings["montoDTR"].ToString().Replace(",", "."), usCulture);
                }
                catch
                {
                    montoDTR = 0;
                }

                GetCompanies(lstCompanies, client);

                metodoTransaction = $"api/v1/Jobs/Transactions/Details?page={page}&posted=false";
                JObject jobjTransaction = JObject.Parse(GetSyncApi(metodoTransaction, client));
                totalRegistros = Convert.ToInt32(jobjTransaction["Data"]["TotalCount"].ToString());
                totalPages     = (int)Decimal.Ceiling(totalRegistros / 100);
                do
                {
                    dynamic dynTransactions = (JArray)jobjTransaction["Data"]["Page"];
                    foreach (var iTransactions in dynTransactions)
                    {
                        List <StrucImposto> lstImposto = new List <StrucImposto>();

                        tipoTransacao = iTransactions.TransactionType.Name.ToString().ToUpper();
                        if (tipoTransacao != "COMISIONES")
                        {
                            Documento documento = new Documento();
                            Hashtable htOrder   = new Hashtable();

                            somaDesconto    = 0;
                            somaValorIGV    = 0;
                            somaFatura      = 0;
                            codigoDocumento = 0;
                            numeroLinha     = 0;
                            tipoVenda       = 0;
                            valorBruto      = 0;
                            temImposto      = false;
                            prefixoSerie    = "";

                            StructCompanies companies = lstCompanies.Find(x => x.AccountNumber == iTransactions.AccountNumber.ToString());
                            if (!String.IsNullOrEmpty(companies.AccountNumber))
                            {
                                documento.DireccionCliente       = companies.Address;
                                documento.NumeroDocumentoCliente = companies.CCIDF;
                                documento.CodigoDocumentoCliente = Convert.ToInt32(companies.CodDoc01);
                                documento.EmailCliente           = companies.Email;
                                clienteNacional = companies.Ruc01;
                                if (String.IsNullOrEmpty(clienteNacional))
                                {
                                    clienteNacional = "";
                                }
                            }

                            if (!String.IsNullOrEmpty(iTransactions.Order.ToString()))
                            {
                                metodoOrder = $"api/v1/Jobs/Orders/FindOrders?page=1&OrderNumber={iTransactions.Order.OrderNumber.ToString()}";
                                GetOrderUserDefined(metodoOrder, client, htOrder);
                                if (!String.IsNullOrEmpty((string)htOrder["BEN01"]))
                                {
                                    StructCompanies idCompany = lstCompanies.Find(x => x.Id == (string)htOrder["BEN01"]);
                                    documento.NombreSolidario = idCompany.Name;
                                }
                                else
                                {
                                    documento.NombreSolidario = null;
                                }
                                documento.TRB    = Math.Abs(Convert.ToDecimal(htOrder["TRB01"]));
                                documento.Eslora = Math.Abs(Convert.ToDecimal(htOrder["ESL01"]));
                            }

                            documento.IdHelm            = iTransactions.Id.ToString();
                            documento.NombreCliente     = iTransactions.AccountName.ToString();
                            documento.CodigoMoneda      = Convert.ToInt32(iTransactions.CurrencyType.ExternalSystemCode.ToString());
                            documento.TransaccionHelm   = iTransactions.TransactionNumber.ToString();
                            documento.SerieReferencia   = iTransactions.Area.ExternalSystemCode.ToString();
                            documento.FechaEmision      = Convert.ToDateTime(iTransactions.TransactionDate.ToString());
                            documento.SerieReferencia2  = null;
                            documento.NumeroReferencia2 = null;

                            notaCredito = iTransactions.TransactionNumber.ToString().Contains("RV");

                            if (!String.IsNullOrEmpty(iTransactions.Order.ToString()))
                            {
                                documento.OrdenCompra = iTransactions.Order.OrderNumber.ToString();
                                documento.NombreNave  = $"{iTransactions.Order.ShipName.ToString()}-{iTransactions.Order.VoyageNumber.ToString()}";
                            }

                            documento.Observaciones = iTransactions.Note.ToString();

                            if (!string.IsNullOrEmpty(iTransactions.DueDate.ToString()))
                            {
                                documento.FechaVencimiento = Convert.ToDateTime(iTransactions.DueDate.ToString());
                            }

                            if (!string.IsNullOrEmpty(iTransactions.ExchangeRate.ToString()))
                            {
                                documento.TipoCambio = Convert.ToDecimal(iTransactions.ExchangeRate.ToString());
                            }

                            if (!string.IsNullOrEmpty(iTransactions.AccountingTerm.ToString()))
                            {
                                documento.FormaPago = iTransactions.AccountingTerm.ExternalSystemCode.ToString();
                            }

                            try
                            {
                                qtdDias             = Convert.ToInt32(iTransactions.AccountingTerm.NumberOfDays.ToString());
                                documento.FormaPago = "CE0" + iTransactions.AccountingTerm.NumberOfDays.ToString();
                            }
                            catch
                            {
                                documento.FormaPago = "CE000";
                            }

                            Dictionary <string, StructDetalle> dicDetalle   = new Dictionary <string, StructDetalle>();
                            Dictionary <string, decimal>       dicDescuento = new Dictionary <string, decimal>();
                            Dictionary <string, decimal>       dicRebaje    = new Dictionary <string, decimal>();
                            decimal valorDescontos = 0;
                            decimal valorRibajes   = 0;

                            dynamic dynTransactionsLines = iTransactions.TransactionLines.Children();
                            foreach (var iTransactionsLines in dynTransactionsLines)
                            {
                                StructDetalle stuDetalle = new StructDetalle();
                                StrucImposto  stuImposto = new StrucImposto();

                                idAlternativo  = "";
                                codigoArticulo = "";
                                keyRebaje      = "";
                                keyVessel      = "";

                                itemServico = iTransactionsLines.DetailDescription.ToString().ToUpper();
                                if (itemServico.Contains("REBAJE"))
                                {
                                    dynamic dynAccountingCodes = iTransactionsLines.RevenueAllocations[0].AccountingCodes.Children();
                                    foreach (var iAccountingCodes in dynAccountingCodes)
                                    {
                                        if ((iAccountingCodes.ReferenceType.ToString().ToUpper() == "VESSEL") ||
                                            (iAccountingCodes.ReferenceType.ToString().ToUpper() == "RESOURCE"))
                                        {
                                            keyVessel = iAccountingCodes.EntityName.ToString();
                                            break;
                                        }
                                    }

                                    keyRebaje = itemServico.Replace(".", "");
                                    if (dicRebaje.ContainsKey(keyRebaje + keyVessel))
                                    {
                                        valorRibajes  = Math.Abs(dicRebaje[keyRebaje + keyVessel]);
                                        valorRibajes += Math.Abs(Convert.ToDecimal(iTransactionsLines.Amount.ToString()));
                                        dicRebaje.Remove(keyRebaje + keyVessel);
                                        dicRebaje.Add(keyRebaje + keyVessel, valorRibajes * -1);
                                    }
                                    else
                                    {
                                        dicRebaje.Add(keyRebaje + keyVessel,
                                                      Convert.ToDecimal(iTransactionsLines.Amount.ToString()));
                                    }
                                }
                                else if (itemServico.Contains("IMPUESTO") || itemServico.Contains("TAX") || itemServico.Contains("DESCUENTO") || itemServico.Contains("DISCOUNT"))
                                {
                                    if (itemServico.Contains("DESCUENTO") || itemServico.Contains("DISCOUNT"))
                                    {
                                        if (String.IsNullOrEmpty(iTransactionsLines.RevenueAllocations[0].ReferenceTransactionLineId.ToString()))
                                        {
                                            idAlternativo = iTransactionsLines.RevenueAllocations[0].Id.ToString();
                                        }
                                        else
                                        {
                                            idAlternativo = iTransactionsLines.RevenueAllocations[0].ReferenceTransactionLineId.ToString();
                                        }
                                        if (dicDescuento.ContainsKey(idAlternativo))
                                        {
                                            valorDescontos  = Math.Abs(dicDescuento[idAlternativo]);
                                            valorDescontos += Math.Abs(Convert.ToDecimal(iTransactionsLines.Amount.ToString()));
                                            dicDescuento.Remove(idAlternativo);
                                            dicDescuento.Add(idAlternativo,
                                                             valorDescontos * -1);
                                        }
                                        else
                                        {
                                            dicDescuento.Add(idAlternativo,
                                                             Convert.ToDecimal(iTransactionsLines.Amount.ToString()));
                                        }
                                    }
                                    else
                                    {
                                        dynamic dynAccountingCodes = iTransactionsLines.RevenueAllocations[0].AccountingCodes.Children();
                                        foreach (var iAccountingCodes in dynAccountingCodes)
                                        {
                                            if ((iAccountingCodes.ReferenceType.ToString().ToUpper() == "VESSEL") ||
                                                (iAccountingCodes.ReferenceType.ToString().ToUpper() == "RESOURCE"))
                                            {
                                                keyVessel = iAccountingCodes.EntityName.ToString();
                                                break;
                                            }
                                        }

                                        stuImposto.Id         = iTransactionsLines.Id.ToString();
                                        stuImposto.Descricao  = itemServico;
                                        stuImposto.Taxa       = Convert.ToDecimal(iTransactionsLines.Rate.ToString());
                                        stuImposto.Remolcador = keyVessel;
                                        lstImposto.Add(stuImposto);
                                        temImposto = true;
                                    }
                                }
                                else
                                {
                                    stuDetalle.NombreArticulo = iTransactionsLines.DetailDescription.ToString();
                                    stuDetalle.Cantidad       = Math.Abs(Convert.ToDecimal(iTransactionsLines.Quantity.ToString()));
                                    stuDetalle.PrecioUnitario = Math.Abs(Convert.ToDecimal(iTransactionsLines.Rate.ToString()));
                                    stuDetalle.SubTotal       = Math.Abs(Convert.ToDecimal(iTransactionsLines.Amount.ToString()));

                                    dynamic dynTransactionsLinesRevenueAllocations = iTransactionsLines.RevenueAllocations[0].AccountingCodes.Children();
                                    foreach (var item in dynTransactionsLinesRevenueAllocations)
                                    {
                                        if ((item.AccountingCode.ToString().ToUpper() == "BV") && (codigoDocumento == 0))
                                        {
                                            codigoDocumento = 191;
                                            prefixoSerie    = "B";
                                        }
                                        else if ((item.AccountingCode.ToString().ToUpper() == "FAC") && (codigoDocumento == 0))
                                        {
                                            codigoDocumento = 184;
                                            prefixoSerie    = "F";
                                        }

                                        if ((String.IsNullOrEmpty(codigoArticulo)) &&
                                            (item.AccountingCode.ToString().ToUpper() != "FAC") &&
                                            (item.AccountingCode.ToString().ToUpper() != "BV"))
                                        {
                                            codigoArticulo = item.AccountingCode.ToString();
                                        }

                                        if ((item.ReferenceType.ToString().ToUpper() == "VESSEL") ||
                                            (item.ReferenceType.ToString().ToUpper() == "RESOURCE"))
                                        {
                                            stuDetalle.Remolcador = item.EntityName.ToString();
                                        }
                                    }

                                    stuDetalle.CodigoArticulo = codigoArticulo;

                                    dicDetalle.Add(iTransactionsLines.Id.ToString(), stuDetalle);
                                }
                            }

                            foreach (KeyValuePair <string, StructDetalle> item in dicDetalle)
                            {
                                DocumentoDetalle documentoDetalhe      = new DocumentoDetalle();
                                string           servicoImposto        = "";
                                string           servicoRedutorImposto = "";
                                decimal          redutorImposto        = 0;

                                numeroLinha                    += 1;
                                documentoDetalhe.IdHelm         = iTransactions.Id.ToString();
                                documentoDetalhe.ItemDetalle    = numeroLinha;
                                documentoDetalhe.NombreArticulo = item.Value.NombreArticulo;
                                documentoDetalhe.Cantidad       = item.Value.Cantidad;
                                documentoDetalhe.PrecioUnitario = item.Value.PrecioUnitario;
                                documentoDetalhe.CodigoArticulo = item.Value.CodigoArticulo;
                                documentoDetalhe.EsDescuento    = false;
                                documentoDetalhe.MontoIGV       = 0;
                                documentoDetalhe.Descuento      = 0;
                                documentoDetalhe.TipoPrecio     = 2;

                                if (temImposto)
                                {
                                    StrucImposto imposto = lstImposto.Find(x => (x.Descricao == "IMPUESTO " + item.Value.NombreArticulo.ToUpper()) && (x.Remolcador == item.Value.Remolcador));
                                    if (!String.IsNullOrEmpty(imposto.Id))
                                    {
                                        documentoDetalhe.MontoIGV = Math.Round(Math.Abs(item.Value.SubTotal) * Math.Abs(imposto.Taxa), 5);
                                        somaValorIGV += documentoDetalhe.MontoIGV.Value;
                                        documentoDetalhe.TipoPrecio = 1;
                                    }
                                    else
                                    {
                                        foreach (var i in lstImposto)
                                        {
                                            servicoImposto = i.Descricao.Replace("IMPUESTO ", "").Trim();
                                            if (item.Value.NombreArticulo.ToUpper().Contains(servicoImposto))
                                            {
                                                if ((item.Value.NombreArticulo.ToUpper().Contains(servicoImposto)) &&
                                                    (item.Value.Remolcador == i.Remolcador))
                                                {
                                                    if (dicRebaje.Count > 0)
                                                    {
                                                        servicoRedutorImposto = "REBAJE IMPUESTO POR DESCUENTO " + servicoImposto + i.Remolcador;
                                                        if (dicRebaje.ContainsKey(servicoRedutorImposto))
                                                        {
                                                            redutorImposto = Math.Abs(dicRebaje[servicoRedutorImposto]);
                                                        }
                                                    }
                                                    documentoDetalhe.MontoIGV = (Math.Round(Math.Abs(item.Value.SubTotal) * Math.Abs(i.Taxa), 5)) - redutorImposto;
                                                    somaValorIGV += documentoDetalhe.MontoIGV.Value;
                                                    documentoDetalhe.TipoPrecio = 1;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }

                                if (dicDescuento.Count > 0)
                                {
                                    if (dicDescuento.ContainsKey(item.Key))
                                    {
                                        documentoDetalhe.Descuento = Math.Abs(dicDescuento[item.Key]);
                                        somaDesconto += Math.Abs(dicDescuento[item.Key]);
                                        documentoDetalhe.EsDescuento = true;
                                    }
                                }

                                documentoDetalhe.MontoBruto                 = Math.Abs(item.Value.SubTotal);
                                documentoDetalhe.SubTotal                   = Math.Abs(item.Value.SubTotal);
                                documentoDetalhe.NombreUnidadMedida         = "Unidad";
                                documentoDetalhe.SiglaUnidadMedida          = "UN";
                                documentoDetalhe.UnidadMedidaSunat          = "ZZ";
                                documentoDetalhe.MontoMinimoConsumidorFinal = 0;
                                documentoDetalhe.MontoISC                   = 0;
                                documentoDetalhe.TasaISC                      = 0;
                                documentoDetalhe.TipoISC                      = 0;
                                documentoDetalhe.TipoPercepcion               = 0;
                                documentoDetalhe.ImportePercepcion            = 0;
                                documentoDetalhe.PorcentajePercepcionArticulo = 0;
                                documentoDetalhe.PorcentajePercepcionVenta    = 0;

                                somaFatura += documentoDetalhe.MontoBruto.Value - documentoDetalhe.Descuento.Value;
                                valorBruto += documentoDetalhe.MontoBruto.Value;

                                context.IncluirDocumentoDetalle(documentoDetalhe);
                            }

                            if (somaValorIGV == 0)
                            {
                                documento.MontoInafecto = Math.Abs(valorBruto);
                                documento.MontoAfecto   = 0;
                            }
                            else
                            {
                                documento.MontoAfecto   = Math.Abs(valorBruto) - Math.Abs(somaDesconto);
                                documento.MontoInafecto = 0;
                            }

                            if (!notaCredito)
                            {
                                if (codigoDocumento == 0)
                                {
                                    switch (tipoTransacao)
                                    {
                                    case "FACTURA":
                                        codigoDocumento = 184;
                                        prefixoSerie    = "F";
                                        break;

                                    case "NOTA CREDITO":
                                        codigoDocumento = 15;
                                        prefixoSerie    = "NC";
                                        break;

                                    case "NOTA CREDITO ELECTRONICA":
                                        codigoDocumento = 186;
                                        prefixoSerie    = "NC";
                                        break;

                                    case "NOTA DEBITO":
                                        codigoDocumento = 16;
                                        prefixoSerie    = "ND";
                                        break;

                                    case "NOTA DEBITO ELECTRONICA":
                                        codigoDocumento = 187;
                                        prefixoSerie    = "ND";
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                codigoDocumento = 186;
                                prefixoSerie    = "NC";
                            }

                            if ((codigoDocumento == 184) && (clienteNacional.ToUpper() == "NO"))
                            {
                                tipoVenda = 3;
                            }
                            else if ((codigoDocumento == 184) || (codigoDocumento == 191))
                            {
                                tipoVenda = 1;
                            }
                            else
                            {
                                tipoVenda = 2;
                            }

                            documento.CodigoDocumento = codigoDocumento;
                            documento.MontoIGV        = Math.Abs(somaValorIGV);
                            documento.TotalDescuento  = Math.Abs(somaDesconto);
                            documento.DescuentoGlobal = Math.Abs(somaDesconto);
                            documento.MontoTotal      = Math.Abs(somaFatura) + Math.Abs(somaValorIGV);
                            documento.MontoISC        = 0;
                            documento.MontoExonerado  = 0;
                            documento.MontoDonacion   = 0;
                            documento.MontoRegalo     = 0;

                            if (iTransactions.Area.Name.ToString().ToUpper() == "TALARA")
                            {
                                documento.Serie = prefixoSerie + "002";
                            }
                            else
                            {
                                documento.Serie = prefixoSerie + "001";
                            }

                            documento.TipoIGV                = 2;
                            documento.AfectoDetraccion       = false;
                            documento.ClienteConsumidorFinal = 1;
                            documento.TipoAgenteTributario   = 0;
                            documento.Estado            = true;
                            documento.FechaHoraCreacion = DateTime.Now;
                            documento.FlagSunat         = false;
                            documento.FlagFE            = false;
                            documento.TipoVenta         = tipoVenda;
                            documento.FechaVencimiento  = documento.FechaEmision.Value.AddDays(qtdDias);
                            if (montoDTR != -1)
                            {
                                if ((clienteNacional.ToUpper() == "SÍ") &&
                                    (documento.MontoIGV.Value > 0) &&
                                    (documento.MontoTotal.Value > montoDTR))
                                {
                                    documento.CodigoDetraccion     = "037";
                                    documento.PorcentajeDetraccion = 12;
                                    documento.GlosaDetraccion      = "OPERACION SUJETA A SPOT";
                                    documento.AfectoDetraccion     = true;
                                }
                            }

                            context.PreencherNumeroSequencial(documento);
                            context.IncluirDocumento(documento);
                            context.Persistir();

                            lstTransactionId.Add(iTransactions.Id.ToString());
                        }
                    }
                    page++;

                    if (page <= totalPages)
                    {
                        metodoTransaction = $"api/v1/Jobs/Transactions/Details?page={page}&posted=false";
                        jobjTransaction   = JObject.Parse(GetSyncApi(metodoTransaction, client));
                    }
                } while (page <= totalPages);

                if (setPosted)
                {
                    SetPostedTransaction(client, lstTransactionId);
                }
            }
            catch (Exception ex)
            {
                _error.AppendLine($"Erro genérico: {ex.Message}");
                _error.AppendLine("");
                if (ex.InnerException != null)
                {
                    _error.AppendLine("Erro detalhado: " + ex.InnerException.ToString());
                }
                _error.AppendLine("Erro stacktrace: " + ex.StackTrace.ToString());
                _error.AppendLine("");
            }
            finally
            {
                client.Dispose();
            }

            Error = _error.ToString();
        }
        private static void verificarCantidadStock(int Bodega, int Articulo, int IdEmpresa)
        {
            Documento DocumentoOrden = new Documento();
            DocumentoDetalle DetalleDocumento = new DocumentoDetalle();
                try
                {
                    //lectorSQL = AccesoDatosCV.verificarCantidadArticulo(Bodega, Articulo, IdEmpresa, (int)datosActuales.Get("idmoneda"), (int)datosActuales.Get("socio"));

                        DataAccess da = new DataAccess();
                        DataSet lectorSQL2 = da.ExecuteQuery("SP_VERIFICAR_CANTIDAD_ARTICULO", new List<SqlParameter>()
                        {
                            new SqlParameter("@IdBodega",Bodega),
                            new SqlParameter("@IdArticulo",Articulo),
                            new SqlParameter("@IdEmpresa",IdEmpresa),
                            new SqlParameter("@IdMoneda",(int)datosActuales.Get("idmoneda")),
                            new SqlParameter("@IdSocio",(int)datosActuales.Get("socio"))

                        });

                        if (lectorSQL2.Tables.Count == 6)
                        {
                            DocumentoOrden.TipoDocumento = OrdenCompra;
                            DetalleDocumento.NumeroDocumento = (int)lectorSQL2.Tables[5].Rows[0].ItemArray[0];
                            DocumentoOrden.Fecha1 = (DateTime)lectorSQL2.Tables[5].Rows[0].ItemArray[1];
                            DocumentoOrden.TotalAI = (Decimal)lectorSQL2.Tables[5].Rows[0].ItemArray[5];
                            DetalleDocumento.Descripcion = (String)lectorSQL2.Tables[5].Rows[0].ItemArray[2];
                            DetalleDocumento.Cantidad = (int)lectorSQL2.Tables[5].Rows[0].ItemArray[3];
                            DetalleDocumento.Precio = (Decimal)lectorSQL2.Tables[5].Rows[0].ItemArray[4];
                            Email email = new Email();
                            email.EnviarCorreo((String)lectorSQL2.Tables[5].Rows[0].ItemArray[6], DocumentoOrden, DetalleDocumento);

                        }
                        else
                            banderaError = 1;

                }
                catch (Exception ex) { return; }
        }
        public static BaseResponse ProcessBill(ref BillEntity pBill, CreditOrDebitNoteEntity pDocumentReference)
        {
            BaseResponse vResponse = new BaseResponse {
                IsSuccessful = false
            };

            pBill.Status = BillStatus.Error.ToString();
            try
            {
                var vServicioBLL         = new ServicioBLL();
                var vDocumentoEncabezado = new DocumentoEncabezado();
                var vUsuarioHacienda     = new UsuarioHacienda();
                var vListaMedioPago      = new List <DocumentoMedioPago>();
                var vDetalleDocumento    = new List <DocumentoDetalle>();

                //Encabezado
                vDocumentoEncabezado.Clave                     = pBill.DocumentKey;
                vDocumentoEncabezado.TipoCambio                = 1.00;
                vDocumentoEncabezado.Fecha                     = DateTime.Now;
                vDocumentoEncabezado.Moneda                    = "CRC";
                vDocumentoEncabezado.CondicionVenta            = pBill.SellCondition;
                vDocumentoEncabezado.PlazoCredito              = string.IsNullOrEmpty(pBill.CreditTerm)?"0": pBill.CreditTerm;
                vDocumentoEncabezado.NormativaFechaResolucion  = "20-02-2017 13:22:22";
                vDocumentoEncabezado.NormativaNumeroResolucion = "DGT-R-48-2016";
                vDocumentoEncabezado.Observacion               = string.IsNullOrEmpty(pBill.Observation) ? string.Empty: pBill.Observation;
                vDocumentoEncabezado.SubTotal                  = Convert.ToDouble(pBill.SubTotalProducts);
                vDocumentoEncabezado.Descuento                 = Convert.ToDouble(pBill.DiscountAmount);
                vDocumentoEncabezado.Impuesto                  = Convert.ToDouble(pBill.TaxesToPay);
                vDocumentoEncabezado.DocumentoConsecutivo      = pBill.ConsecutiveNumber + "";

                //Emisor
                vDocumentoEncabezado.Emisor.Identificacion     = pBill.User.UserLegalNumber;
                vDocumentoEncabezado.Emisor.IdentificacionTipo = pBill.User.IdentificationType;
                vDocumentoEncabezado.Emisor.Direccion          = pBill.User.LocationDescription;
                vDocumentoEncabezado.Emisor.CodigoPais         = "506";
                vDocumentoEncabezado.Emisor.Provincia          = pBill.User.ProvinciaCode;
                vDocumentoEncabezado.Emisor.Canton             = pBill.User.CantonCode;
                vDocumentoEncabezado.Emisor.Distrito           = pBill.User.DistritoCode;
                vDocumentoEncabezado.Emisor.Barrio             = pBill.User.BarrioCode;
                vDocumentoEncabezado.Emisor.Nombre             = pBill.User.Name;
                vDocumentoEncabezado.Emisor.NombreComercial    = string.IsNullOrEmpty(pBill.User.ComercialName)? string.Empty: pBill.User.ComercialName;
                vDocumentoEncabezado.Emisor.Telefono           = pBill.User.PhoneNumber;
                vDocumentoEncabezado.Emisor.Fax   = "00000000";
                vDocumentoEncabezado.Emisor.Email = pBill.User.Email;

                //Receptor
                vDocumentoEncabezado.Receptor.IdentificacionExtranjero = pBill.Client.ForeignIdentification;
                vDocumentoEncabezado.Receptor.Identificacion           = pBill.Client.ClientLegalNumber;
                vDocumentoEncabezado.Receptor.IdentificacionTipo       = pBill.Client.IdentificationType;
                vDocumentoEncabezado.Receptor.Direccion       = pBill.Client.LocationDescription;
                vDocumentoEncabezado.Receptor.CodigoPais      = "506";
                vDocumentoEncabezado.Receptor.Provincia       = pBill.Client.ProvinciaCode;
                vDocumentoEncabezado.Receptor.Canton          = pBill.Client.CantonCode;
                vDocumentoEncabezado.Receptor.Distrito        = pBill.Client.DistritoCode;
                vDocumentoEncabezado.Receptor.Barrio          = pBill.Client.BarrioCode;
                vDocumentoEncabezado.Receptor.Nombre          = pBill.Client.Name;
                vDocumentoEncabezado.Receptor.NombreComercial = pBill.Client.ComercialName;
                vDocumentoEncabezado.Receptor.Telefono        = pBill.Client.PhoneNumber;
                vDocumentoEncabezado.Receptor.Fax             = "00000000";
                vDocumentoEncabezado.Receptor.Email           = pBill.Client.Email;

                //Medio de Pago
                var vMedioDePago = new DocumentoMedioPago();
                vMedioDePago.Codigo = pBill.PaymentMethod;
                vListaMedioPago.Add(vMedioDePago);
                vDocumentoEncabezado.MedioPago = vListaMedioPago;

                var vListaProductos = JsonConvert.DeserializeObject <Client>(pBill.SoldProductsJSON);
                foreach (var vProducto in vListaProductos.ClientProducts)
                {
                    if (vProducto.ProductQuantity > 0)
                    {
                        //Detalle del Producto
                        decimal vProductTotal = vProducto.Price * vProducto.ProductQuantity;
                        var     vLinea        = new DocumentoDetalle();
                        vLinea.Cantidad              = vProducto.ProductQuantity;
                        vLinea.Nombre                = vProducto.Name;
                        vLinea.Descripcion           = vProducto.Description;
                        vLinea.Codigo                = vProducto.ProductCode;
                        vLinea.Tipo                  = vProducto.ProductType;
                        vLinea.Unidad                = vProducto.MeasurementUnit;
                        vLinea.UnidadMedidaComercial = string.IsNullOrEmpty(vProducto.MeasurementUnitType)?string.Empty: vProducto.MeasurementUnitType;
                        vLinea.EsProducto            = true;
                        vLinea.Precio                = Convert.ToDouble(vProducto.Price);
                        vLinea.Descuento             = Convert.ToDouble((vProductTotal / 100) * pBill.Client.DefaultDiscountPercentage);
                        vLinea.DescuentoDescripcion  = string.IsNullOrEmpty(pBill.DiscountNature) ? string.Empty : pBill.DiscountNature;
                        if (pBill.Client.DefaultTaxesPercentage > 0)
                        {
                            // Impuestos
                            var vLineaListaImpuesto = new List <DocumentoDetalleImpuesto>();
                            var vLineaImpuesto      = new DocumentoDetalleImpuesto();
                            vLineaImpuesto.Tipo   = pBill.TaxCode;
                            vLineaImpuesto.Tarifa = Convert.ToDouble(pBill.Client.DefaultTaxesPercentage);
                            vLineaImpuesto.Monto  =
                                Convert.ToDouble(((vProductTotal - Convert.ToDecimal(vLinea.Descuento)) / 100) * pBill.Client.DefaultTaxesPercentage);
                            vLineaListaImpuesto.Add(vLineaImpuesto);
                            // Se agrega el impuesto a Lista
                            vLinea.DocumentoDetalleImpuesto = vLineaListaImpuesto;
                        }

                        // Se agrega el Producto completo a todos los demas
                        vDetalleDocumento.Add(vLinea);
                    }
                    else
                    {
                        // El producto no tiene ninguna cantidad a facturar
                    }
                }

                //Se agrega referencia si es que existe
                if (pDocumentReference != null)
                {
                    var vReferenceList = new List <DocumentoReferencia>();
                    var vReferenceDoc  = new DocumentoReferencia();

                    vReferenceDoc.Codigo       = pDocumentReference.ReferenceCode;
                    vReferenceDoc.FechaEmision = pDocumentReference.EmissionDate;
                    vReferenceDoc.Numero       = pDocumentReference.DocuementKey;
                    vReferenceDoc.Razon        = pDocumentReference.ReasonDescription;
                    vReferenceDoc.TipoDoc      = HaciendaTransactionType.Factura_Electronica;

                    vReferenceList.Add(vReferenceDoc);
                    vDocumentoEncabezado.Referencia = vReferenceList;
                }

                // Se agrega el Segmento de todos los productos
                vDocumentoEncabezado.DocumentoDetalle = vDetalleDocumento;

                // Datos de Hacienda
                vUsuarioHacienda.username                     = pBill.Client.User.HaciendaUsername;
                vUsuarioHacienda.password                     = pBill.Client.User.HaciendaPassword;
                vUsuarioHacienda.Pin                          = pBill.Client.User.HaciendaCryptographicPIN;
                vUsuarioHacienda.Certificado                  = pBill.Client.User.HaciendaCryptographicFile;
                vUsuarioHacienda.modalidadProduccion          = false;
                vUsuarioHacienda.urlhaciendaAuthApiDesarrollo = UrlhaciendaAuthApiDesarrollo;
                vUsuarioHacienda.urlhaciendaAuthApiProduccion = UrlhaciendaAuthApiProduccion;
                vUsuarioHacienda.urlhaciendaApiDesarrollo     = UrlhaciendaApiDesarrollo;
                vUsuarioHacienda.urlhaciendaApiProduccion     = UrlhaciendaApiProduccion;

                var vReply = vServicioBLL.fGenerarDocumento(vDocumentoEncabezado, vUsuarioHacienda, MaxRetryCount);
                if (vReply != null)
                {
                    // try to save the Sended XML always
                    if (!string.IsNullOrEmpty(vReply.xmlDocumento))
                    {
                        pBill.XMLSendedToHacienda = vReply.xmlDocumento;
                    }

                    if (!string.IsNullOrEmpty(vReply.xmlRespuesta))
                    {
                        Regex  vRegex = new Regex("<DetalleMensaje>(.+)</DetalleMensaje>");
                        string msgWithoutChangeLines = Regex.Replace(vReply.xmlRespuesta, "\r\n?|\n", "");
                        var    vMatch = vRegex.Match(msgWithoutChangeLines);
                        if (vMatch.Success)
                        {
                            pBill.SystemMesagges = vReply.estado + "-" + vReply.msg + vMatch.Value;
                        }
                        else
                        {
                            pBill.SystemMesagges = vReply.estado + "-" + vReply.msg;
                        }
                    }
                    else
                    {
                        pBill.SystemMesagges = vReply.estado + "-" + vReply.msg +
                                               string.Format("| REASON GET: {0} | REASON POST: {1}", vReply.reasonPhraseGETHacienda, vReply.reasonPhrasePOSTHacienda);
                    }


                    if (vReply.ok)
                    {
                        if (!string.IsNullOrEmpty(vReply.xmlRespuesta))
                        {
                            pBill.XMLReceivedFromHacienda = vReply.xmlRespuesta;
                        }
                        switch (vReply.estado)
                        {
                        case BillStatusHacienda.Aceptada:
                            pBill.Status           = BillStatus.Done.ToString();
                            vResponse.IsSuccessful = true;
                            break;

                        case BillStatusHacienda.Rechazada:
                            pBill.Status           = BillStatus.Rejected.ToString();
                            vResponse.IsSuccessful = false;
                            break;

                        case BillStatusHacienda.Procesando:
                            pBill.Status           = BillStatus.Processing.ToString();
                            vResponse.IsSuccessful = false;
                            break;

                        default:
                            pBill.Status           = BillStatus.Error.ToString();
                            vResponse.IsSuccessful = false;
                            break;
                        }

                        if (string.IsNullOrEmpty(pBill.SystemMesagges))
                        {
                            pBill.SystemMesagges = pBill.Status + vReply.msg;
                        }
                        vResponse.UserMessage = pBill.SystemMesagges;
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(pBill.Status))
                        {
                            pBill.Status = BillStatus.Error.ToString();
                        }
                        if (string.IsNullOrEmpty(pBill.SystemMesagges))
                        {
                            pBill.SystemMesagges = "Error." + "La respuesta no fue positiva:" + vReply.msg;
                        }


                        if (string.IsNullOrEmpty(vReply.statusCodePOSTHacienda) || !vReply.statusCodePOSTHacienda.Equals(AcceptedHTTPCode))
                        {
                            if (!string.IsNullOrEmpty(vReply.msg) && vReply.msg.Contains("ya fue recibido anteriormente"))
                            {
                                pBill.Status = BillStatus.Processing.ToString();
                            }
                            else
                            {
                                pBill.Status = BillStatus.Error.ToString();
                            }
                        }
                        else
                        {
                            pBill.Status = BillStatus.Processing.ToString();
                        }
                        pBill.ReasonPhraseGETHacienda  = vReply.reasonPhraseGETHacienda;
                        pBill.ReasonPhrasePOSTHacienda = vReply.reasonPhrasePOSTHacienda;

                        pBill.StatusCodeGETHacienda  = vReply.statusCodeGETHacienda;
                        pBill.StatusCodePOSTHacienda = vReply.statusCodePOSTHacienda;

                        vResponse.IsSuccessful = false;
                        vResponse.UserMessage  = pBill.SystemMesagges;
                    }
                }
                else
                {
                    pBill.SystemMesagges  = "No se recibio respuesta de hacienda";
                    vResponse.UserMessage = "Error." + "No se recibio respuesta de hacienda";
                    pBill.Status          = BillStatus.Error.ToString();
                }

                pBill.HaciendaFailCounter++;
            }
            catch (Exception ex)
            {
                vResponse.UserMessage      = ex.Message;
                vResponse.TechnicalMessage = ex.ToString();
                vResponse.IsSuccessful     = false;
            }

            return(vResponse);
        }