/// <summary>
        /// Metodo para descartar algun documento de comunicacion de baja.
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="tipoContiene"></param>
        public void cs_pxDescartarDocumento(string Id, string tipoContiene)
        {
            //Solo se puede descartar aquellos documentos que no hayan tenido alguna respuesta de SUNAT
            clsEntityVoidedDocuments comunicacionbaja = new clsEntityVoidedDocuments(localbd).cs_fxObtenerUnoPorId(Id);

            if (comunicacionbaja.Cs_pr_EstadoSUNAT == "2")
            {
                List <clsEntityVoidedDocuments_VoidedDocumentsLine> comunicacionbaja_items = new clsEntityVoidedDocuments_VoidedDocumentsLine(localbd).cs_fxObtenerTodoPorCabeceraId(comunicacionbaja.Cs_pr_VoidedDocuments_Id);
                if (tipoContiene == "0")
                {
                    clsEntityDocument documento_principal;
                    foreach (var item in comunicacionbaja_items)
                    {
                        documento_principal = new clsEntityDocument(localbd).cs_fxObtenerUnoPorId(item.Cs_pr_IDDocumentoRelacionado);
                        documento_principal.Cs_pr_ComunicacionBaja = "";
                        documento_principal.cs_pxActualizar(false, false);
                    }
                }
                else if (tipoContiene == "1")
                {
                    clsEntityRetention documento_principal;
                    foreach (var item in comunicacionbaja_items)
                    {
                        documento_principal = new clsEntityRetention(localbd).cs_fxObtenerUnoPorId(item.Cs_pr_IDDocumentoRelacionado);
                        documento_principal.Cs_pr_Reversion = "";
                        documento_principal.cs_pxActualizar(false, false);
                    }
                }

                comunicacionbaja.cs_pxComunicacionBajaEliminar(Id);
            }
        }
 public frmComunicacionbajaVisorSUNAT(string id)
 {
     InitializeComponent();
     this.id  = id;
     cabecera = new clsEntityVoidedDocuments();
     cabecera.cs_fxObtenerUnoPorId(this.id);
 }
 private void MenuDescartar_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         ReporteDocumento item = (ReporteDocumento)dgComprobantes.SelectedItem;
         if (item != null)
         {
             clsEntityVoidedDocuments comunicacion = new clsEntityVoidedDocuments(localDB).cs_fxObtenerUnoPorId(item.ComunicacionBaja);
             if (comunicacion.Cs_pr_EstadoSUNAT == "2")
             {
                 if (System.Windows.Forms.MessageBox.Show("¿Está seguro que descartar este documento de la comunicacion de baja?", "¿Está seguro?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                 {
                     new clsEntityVoidedDocuments_VoidedDocumentsLine(localDB).cs_fxDescartarDocumento(item.Id, item.ComunicacionBaja, "0");
                 }
                 refrescarGrillaDocumentos(item.ComunicacionBaja);
             }
             else
             {
                 System.Windows.Forms.MessageBox.Show("No se puede quitar el documento de la comunicación de baja, esta ya tiene respuesta de Sunat.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Stop);
             }
         }
     }
     catch (Exception ex)
     {
         clsBaseLog.cs_pxRegistarAdd("motivo baja " + ex.ToString());
     }
 }
Exemple #4
0
        private void btnEnviarComunicacionbaja_Click(object sender, EventArgs e)
        {
            try
            {
                string ya_enviados        = String.Empty;
                string no_enviados_motivo = String.Empty;

                if (dgvComunicacionbaja.Rows.Count > 0)
                {
                    foreach (DataGridViewRow row in dgvComunicacionbaja.Rows)
                    {
                        if ((bool)row.Cells[1].Value == true)
                        {
                            if (row.Cells[6].Value.ToString().Trim() != "" || row.Cells[10].Value.ToString().Trim() != "")
                            {
                                ya_enviados += " -> " + row.Cells[2].Value.ToString() + " \n";
                            }
                            else
                            {
                                bool validar_motivos_baja = new clsEntityVoidedDocuments().cs_pxValidarMotivosDeBajaEnItems(row.Cells[0].Value.ToString());
                                if (validar_motivos_baja == true)
                                {
                                    if (new clsBaseSunat().cs_pxEnviarRA(row.Cells[0].Value.ToString()))
                                    {
                                        row.Cells[7].Value           = clsBaseUtil.cs_fxComprobantesEstadosSCC_descripcion(0).ToUpper();
                                        row.Cells[7].Style.ForeColor = Color.Green;
                                    }
                                }
                                else
                                {
                                    no_enviados_motivo += " -> " + row.Cells[2].Value.ToString() + " \n";
                                }
                            }
                        }
                    }
                    if (ya_enviados != "")
                    {
                        clsBaseMensaje.cs_pxMsg("Elementos ya enviados", "Los siguientes documentos ya fueron enviados anteriormente. \n" + ya_enviados);
                    }
                    if (no_enviados_motivo != "")
                    {
                        clsBaseMensaje.cs_pxMsg("Elementos no enviados", "Los siguientes documentos no fueron enviados. Verifique los motivos de baja en los items \n" + no_enviados_motivo);
                    }
                }
                cs_pxCargarDgvDocumentosBaja(dtpFechaInicio.Text.ToString(), dtpFechaFin.Text.ToString());
            }
            catch (Exception ex)
            {
                clsBaseMensaje.cs_pxMsgEr("ERR15", ex.Message);
            }
        }
        /// <summary>
        /// Genera un Documento de baja.
        /// </summary>
        /// <param name="Id">Id del documento.</param>
        /// <returns>NombreTributo del archivo generado.</returns>
        public string cs_pxGenerarResumenRA(string Id)
        {
            string archivo_nombre_XML        = string.Empty;
            string archivo_nombre_ZIP        = string.Empty;
            string archivo_nombre_directorio = string.Empty;
            string fila = string.Empty;

            try
            {
                clsEntityVoidedDocuments cabecera = new clsEntityVoidedDocuments(localDB);
                cabecera.cs_fxObtenerUnoPorId(Id);
                fila = new clsNegocioCEComunicacionBaja(localDB).cs_pxGenerarXMLAString(Id);

                #region Genera los nombres de archivo

                archivo_nombre_XML        = declarante.Cs_pr_Ruc + "-" + cabecera.Cs_tag_ID.Split('-')[0].Trim().ToString() + "-" + cabecera.Cs_tag_IssueDate.Replace("-", "") + "-" + cabecera.Cs_tag_ID.Split('-')[2].Trim().ToString() + ".xml";
                archivo_nombre_ZIP        = declarante.Cs_pr_Ruc + "-" + cabecera.Cs_tag_ID.Split('-')[0].Trim().ToString() + "-" + cabecera.Cs_tag_IssueDate.Replace("-", "") + "-" + cabecera.Cs_tag_ID.Split('-')[2].Trim().ToString() + ".zip";
                archivo_nombre_directorio = declarante.Cs_pr_Ruc + "-" + cabecera.Cs_tag_ID.Split('-')[0].Trim().ToString() + "-" + cabecera.Cs_tag_IssueDate.Replace("-", "") + "-" + cabecera.Cs_tag_ID.Split('-')[2].Trim().ToString();
                string comprobante_ruta        = new clsBaseConfiguracion().cs_prRutadocumentosenvio + "/";
                string comprobante_ruta_nombre = comprobante_ruta + archivo_nombre_directorio + "\\" + archivo_nombre_XML;
                if (File.Exists(comprobante_ruta_nombre))
                {
                    File.Delete(comprobante_ruta_nombre);
                }
                if (Directory.Exists(comprobante_ruta + archivo_nombre_directorio))
                {
                    var dir = new DirectoryInfo(comprobante_ruta + archivo_nombre_directorio); dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly; dir.Delete(true);
                }
                if (!Directory.Exists(comprobante_ruta + archivo_nombre_directorio))
                {
                    Directory.CreateDirectory(comprobante_ruta + archivo_nombre_directorio);
                }
                if (!File.Exists(comprobante_ruta_nombre))
                {
                    File.Create(comprobante_ruta_nombre).Close();
                }
                // StreamWriter sw1 = new StreamWriter(comprobante_ruta_nombre); sw1.WriteLine(fila); sw1.Close(); fila = string.Empty;
                StreamWriter  sw1 = new StreamWriter(File.Open(comprobante_ruta_nombre, FileMode.OpenOrCreate), Encoding.GetEncoding("ISO-8859-1")); sw1.WriteLine(fila); sw1.Close(); fila = string.Empty;
                DirectoryInfo x   = new DirectoryInfo(comprobante_ruta + archivo_nombre_directorio);
                cs_prComprimirZIP(x);
                #endregion
            }
            catch (Exception ex)
            {
                clsBaseLog.cs_pxRegistarAdd("clsNegocioCE cs_pxGenerarResumenRA" + ex.ToString());
            }

            return(archivo_nombre_ZIP);
        }
        private void frmVisorSUNAT_Load(object sender, EventArgs e)
        {
            clsEntityDeclarant       declarante = new clsEntityDeclarant().cs_pxObtenerUnoPorId(new clsBaseConfiguracion().Cs_pr_Declarant_Id);
            clsEntityVoidedDocuments rd         = new clsEntityVoidedDocuments().cs_fxObtenerUnoPorId(this.id);

            txtDocumento.Text    = rd.Cs_tag_ID;
            txtFechaemision.Text = rd.Cs_tag_IssueDate;
            txtRazonsocial.Text  = declarante.Cs_pr_RazonSocial;
            txtRuc.Text          = declarante.Cs_pr_Ruc;

            rbtEnvío.Checked = true;

            /*
             * txtDocumentotipo.Text = clsBaseUtil.cs_fxComprobantesElectronicos_descripcion(cabecera.Invoice_InvoiceTypeCode);
             * txtRuc.Text = cabecera.AccountingSupplierParty_CustomerAssignedAccountID;
             * txtFechaemision.Text = cabecera.Invoice_IssueDate;
             * txtRazonsocial.Text = cabecera.AccountingCustomerParty_Party_PartyLegalEntity_RegistrationName;
             * txtSerienumero.Text = cabecera.Invoice_ID;*/
            if (rd.Cs_pr_XML.Length <= 0)
            {
                rbtRecepción.Enabled = false;
                btnDescargarXML_Recepción.Enabled = false;
            }
        }
        //Evento de envio a sunat de la comunicacion de baja.
        private void btnSunat_Click(object sender, RoutedEventArgs e)
        {
            string comentario             = "";
            string procesados             = "";
            string ya_enviados            = "";
            string no_enviados_motivo     = "";
            int    cantidad_seleccionados = 0;

            try
            {
                List <ReporteResumen> seleccionados = new List <ReporteResumen>();
                //Recorrer la lista para obtener los seleccionados.
                foreach (var item in lista_reporte)
                {
                    if (item.Check == true)
                    {   //Si el item fue seleccionado
                        cantidad_seleccionados++;
                        if (item.Ticket != "" || item.Comentario != "")
                        {
                            ya_enviados += " -> " + item.Archivo + " \n";
                        }
                        else
                        {
                            bool validar_motivos_baja = new clsEntityVoidedDocuments(localDB).cs_pxValidarMotivosDeBajaEnItems(item.Id);
                            if (validar_motivos_baja == true)
                            {
                                seleccionados.Add(item);
                            }
                            else
                            {
                                no_enviados_motivo += " -> " + item.Archivo + " \n";
                            }
                        }
                    }
                }
                //SI existen documentos seleccionados.
                if (cantidad_seleccionados > 0)
                {
                    //Mostrar resumen de comprobantes procesados y no procesados.
                    comentario += ya_enviados + no_enviados_motivo;
                    if (comentario.Length > 0)
                    {
                        comentario = "";
                        if (ya_enviados.Length > 0)
                        {
                            comentario += "Ya enviadas:\n" + ya_enviados;
                        }
                        if (no_enviados_motivo.Length > 0)
                        {
                            comentario += "Sin motivos de baja" + no_enviados_motivo;
                        }
                        System.Windows.MessageBox.Show("Los siguientes resumen de reversiones no seran procesados.\n" + comentario, "Mensaje", MessageBoxButton.OK, MessageBoxImage.Information);
                    }

                    //Si existen items selccionados.
                    if (seleccionados.Count > 0)
                    {
                        //string resultado = string.Empty;
                        ProgressDialogResult result = ProgressWindow.Execute(VentanaPrincipal, "Procesando...", () => {
                            procesados = sendToSunat(seleccionados);
                        });

                        refrescarGrilla();
                    }
                    if (procesados.Length > 0)
                    {
                        CustomDialogWindow obj = new CustomDialogWindow();
                        obj.AdditionalDetailsText = "Los siguientes comprobantes fueron enviados correctamente:\n" + procesados;
                        obj.Buttons       = CustomDialogButtons.OK;
                        obj.Caption       = "Mensaje";
                        obj.DefaultButton = CustomDialogResults.OK;
                        // obj.FooterIcon = CustomDialogIcons.Shield;
                        // obj.FooterText = "This is a secure program";
                        obj.InstructionHeading = "Documentos enviados";
                        obj.InstructionIcon    = CustomDialogIcons.Information;
                        obj.InstructionText    = "Los documentos se enviaron correctamente a SUNAT.";
                        CustomDialogResults objResults = obj.Show();

                        // System.Windows.MessageBox.Show("Las siguientes comunicaciones de baja fueron procesadas correctamente.\n" + procesados, "Mensaje", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
                else
                {
                    System.Windows.MessageBox.Show("Seleccione los items a procesar.", "Mensaje", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                }
            }
            catch (Exception ex)
            {
                clsBaseMensaje.cs_pxMsgEr("ERR15", ex.Message);
                clsBaseLog.cs_pxRegistarAdd("EnvioRA" + ex.ToString());
            }
        }
Exemple #8
0
        private void cs_pxCargarGrid()
        {
            try
            {
                clsEntityDeclarant       declarante = new clsEntityDeclarant().cs_pxObtenerUnoPorId(new clsBaseConfiguracion().Cs_pr_Declarant_Id);
                clsEntityVoidedDocuments rd         = new clsEntityVoidedDocuments().cs_fxObtenerUnoPorId(id_comunicacionbaja);
                txtDocumento.Text    = rd.Cs_tag_ID;
                txtFechaemision.Text = rd.Cs_tag_IssueDate;
                txtRazonsocial.Text  = declarante.Cs_pr_RazonSocial;
                txtRuc.Text          = declarante.Cs_pr_Ruc;

                dgvComprobanteselectronicos.Rows.Clear();
                List <List <string> > registros = new clsEntityDocument().cs_pxObtenerDocumentosPorComunicacionBaja(id_comunicacionbaja);

                int numero_orden = 0;
                foreach (var item in registros)
                {
                    numero_orden++;
                    dgvComprobanteselectronicos.Rows.Add(
                        item[0].ToString().Trim(),                                                                                                                                   //ID
                        false,
                        numero_orden.ToString(),                                                                                                                                     //ID
                        clsBaseUtil.cs_fxComprobantesElectronicos_descripcion(item[3].Trim()),                                                                                       //Comprobantes
                        item[28].Trim(),                                                                                                                                             //Estado SCC
                        item[27].Trim(),                                                                                                                                             //Estado SUNAT
                        item[1].ToString().Trim(),                                                                                                                                   //Serie - número
                        item[2].ToString().Trim(),                                                                                                                                   //Fecha de emisión
                        item[21].ToString().Trim(),                                                                                                                                  //Ruc
                        item[23].ToString().Trim(),                                                                                                                                  //Razón social
                        item[28].ToString().Trim(),                                                                                                                                  //Razón social
                        item[27].ToString().Trim(),                                                                                                                                  //Razón social
                        item[35].ToString().Trim(),                                                                                                                                  //Fecha de envío
                        item[32].ToString().Trim(),                                                                                                                                  //Comentario de sunat
                        item[33].ToString().Trim(),                                                                                                                                  //Incluido en resumen diario
                        item[37].ToString().Trim(),                                                                                                                                  //Incluido en comunicación de baja
                        new clsEntityVoidedDocuments_VoidedDocumentsLine().cs_fxObtenerUnoPorDocumentoPrincipalYDocumentoRelacionado(item[0], item[37]).Cs_tag_VoidReasonDescription //Motivo de baja de comprobantes
                        );
                }

                foreach (DataGridViewRow row in dgvComprobanteselectronicos.Rows)
                {
                    switch (row.Cells[10].Value.ToString())
                    {
                    case "1":
                        row.Cells[4].Style.ForeColor = Color.Red;    //Pendiente (errores)
                        Seleccionar.ReadOnly         = false;
                        break;

                    case "2":
                        row.Cells[4].Style.ForeColor = Color.RoyalBlue;    //Pendiente (correcto)
                        break;

                    case "0":
                        row.Cells[4].Style.ForeColor = Color.Green;    //Enviado
                        break;
                    }
                    row.Cells[4].Value = clsBaseUtil.cs_fxComprobantesEstadosSCC_descripcion(Convert.ToInt16(row.Cells[10].Value)).ToUpper();
                    switch (row.Cells[11].Value.ToString())
                    {
                    case "0":
                        row.Cells[5].Style.ForeColor = Color.Green;    //Aceptado
                        break;

                    case "1":
                        row.Cells[5].Style.ForeColor = Color.Brown;    //Rechazado
                        break;

                    case "2":
                        row.Cells[5].Style.ForeColor = Color.Red;    //Sin respuesta
                        break;

                    case "3":
                        row.Cells[5].Style.ForeColor = Color.Salmon;    //Anulado
                        break;
                    }
                    row.Cells[5].Value = clsBaseUtil.cs_fxComprobantesEstadosSUNAT_descripcion(Convert.ToInt16(row.Cells[11].Value)).ToUpper();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        /*INICIO - Pequeña parte de Programacion orientada a Eventos*/

        //Cristhian|01/03/2018|FEI2-586

        /*Metodo creado para dar de baja los comprobantes electronicos que son enviados desde
         * el sistema DBF comercial, en este caso solo facturas.*/
        /*NUEVO INICIO*/
        /// <summary>
        /// Método para dar de baja al comprobante electronico
        /// </summary>
        /// <param name="Id_Documento"></param>
        /// <param name="tipoContenido"></param>
        /// <returns>mensaje</returns>
        public string cs_pxProcesarComunicacionBaja(string Id_Documento, string tipoContenido)
        {
            string mensaje = string.Empty;

            try
            {
                //Buscar grupos de fechas seleccionadas y por cada grupo debe crear un archivo de comunicación de baja.
                #region "AGRUPAR POR COMUNICACIÓN DE BAJA"
                List <string> grupo             = new List <string>(); //Crear grupos de fecha por IssueDate - FECHA DE EMISION
                List <string> docs_no_agregados = new List <string>(); //Lista de doccumentos no agregados

                //Si los comprobantes son facturas, notas de creddito o debito, el tipo de contenido sera 0.
                if (tipoContenido == "0")
                {
                    clsEntityDocument document = new clsEntityDocument(localDB).cs_fxObtenerUnoPorId(Id_Documento);
                    if (document.Cs_pr_ComunicacionBaja.Trim().Length <= 0)
                    {
                        //Verificar los 7 dias anteriores al dia de hoy para permitir agregar a resumen diario.
                        string fechaEmision = document.Cs_tag_IssueDate;
                        if (fechaEmision == DateTime.Now.ToString("yyyy-MM-dd") ||
                            fechaEmision == DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") ||
                            fechaEmision == DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd") ||
                            fechaEmision == DateTime.Now.AddDays(-3).ToString("yyyy-MM-dd") ||
                            fechaEmision == DateTime.Now.AddDays(-4).ToString("yyyy-MM-dd") ||
                            fechaEmision == DateTime.Now.AddDays(-5).ToString("yyyy-MM-dd") ||
                            fechaEmision == DateTime.Now.AddDays(-6).ToString("yyyy-MM-dd") ||
                            fechaEmision == DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd"))
                        {
                            int count = 0;
                            foreach (var item_grupo in grupo)
                            {
                                if (fechaEmision == item_grupo)
                                {
                                    count++;
                                }
                            }
                            if (count <= 0)    //Si no existe el elemento en la lista, que se agregue.
                            {
                                grupo.Add(fechaEmision);
                            }
                        }
                        else
                        {
                            docs_no_agregados.Add(document.Cs_tag_ID);
                        }
                    }
                }
                /*En caso sean de tipo contenido 1, es para los documentos de retención*/
                else if (tipoContenido == "1")
                {
                    //Cuando se agregan tipo de documentos retencion
                    clsEntityRetention document = new clsEntityRetention(localDB).cs_fxObtenerUnoPorId(Id_Documento);
                    if (document.Cs_pr_Reversion.Trim().Length <= 0)
                    {
                        //Asignar valor a fecha de emision.
                        string fechaEmision = document.Cs_tag_IssueDate;

                        int count = 0;
                        foreach (var item_grupo in grupo)
                        {
                            if (fechaEmision == item_grupo)
                            {
                                count++;
                            }
                        }
                        if (count <= 0)    //Si no existe el elemento en la lista, que se agregue.
                        {
                            grupo.Add(fechaEmision);
                        }
                    }
                }
                #endregion

                //Crear grupos de fecha por IssueDate - FechaEmision
                List <string>            doc_agregados = new List <string>();
                clsEntityVoidedDocuments comunicacion_baja;

                //Si existen documentos a dar de baja por grupos.
                foreach (var fecha_comunicacion in grupo)
                {
                    //Buscar comunicacion de baja existente.
                    string documento_baja_existente = new clsEntityVoidedDocuments(localDB).cs_pxObtenerDocumentoComuninicacionBajaExisente(fecha_comunicacion, tipoContenido);
                    if (documento_baja_existente != "")
                    {
                        //Si existe comunicacion de baja Agregar los comprobantes al que ya se encuentra creado.
                        bool agregado = new clsEntityVoidedDocuments(localDB).cs_pxComunicacionBajaActualizar(Id_Documento, documento_baja_existente, tipoContenido);
                        if (agregado == true)
                        {
                            //Si se han agregado los comprobantes actualizar el nombre de la comunicacion de baja en caso se este agregando a otro que se haya generado anteriormente.
                            comunicacion_baja = new clsEntityVoidedDocuments(localDB).cs_fxObtenerUnoPorId(documento_baja_existente);
                            comunicacion_baja.Cs_tag_IssueDate = DateTime.Now.ToString("yyyy-MM-dd");
                            string correlativo = comunicacion_baja.Cs_tag_ID.Split('-')[2];
                            if (tipoContenido == "0")
                            {    //Facturas y Notas
                                comunicacion_baja.Cs_tag_ID = "RA-" + comunicacion_baja.Cs_tag_IssueDate.Replace("-", "") + "-" + correlativo;
                            }
                            else if (tipoContenido == "1")
                            {    //Retencion
                                comunicacion_baja.Cs_tag_ID = "RR-" + comunicacion_baja.Cs_tag_IssueDate.Replace("-", "") + "-" + correlativo;
                            }
                            comunicacion_baja.cs_pxActualizar(false, false);
                            doc_agregados.Add(comunicacion_baja.Cs_tag_ID);
                        }
                    }
                    else
                    {
                        //Crear documento de comunicación de baja ya que no existe
                        string documento_nuevo_id = Guid.NewGuid().ToString();
                        clsEntityVoidedDocuments documento_nuevo = new clsEntityVoidedDocuments(localDB);
                        documento_nuevo.Cs_pr_VoidedDocuments_Id = documento_nuevo_id;
                        documento_nuevo.Cs_tag_ReferenceDate     = fecha_comunicacion;//DateTime.Now.ToString("yyyy-MM-dd");
                        documento_nuevo.Cs_tag_IssueDate         = DateTime.Now.ToString("yyyy-MM-dd");
                        if (tipoContenido == "0")
                        {
                            documento_nuevo.Cs_tag_ID = "RA-" + documento_nuevo.Cs_tag_IssueDate.Replace("-", "") + "-" + new clsEntityVoidedDocuments(localbd).cs_fxObtenerCorrelativo("0");
                        }
                        else if (tipoContenido == "1")
                        {
                            documento_nuevo.Cs_tag_ID = "RR-" + documento_nuevo.Cs_tag_IssueDate.Replace("-", "") + "-" + new clsEntityVoidedDocuments(localbd).cs_fxObtenerCorrelativo("1");
                        }
                        documento_nuevo.Cs_tag_AccountingSupplierParty_CustomerAssignedAccountID = declarante.Cs_pr_Ruc;
                        documento_nuevo.Cs_tag_AccountingSupplierParty_AdditionalAccountID       = "6";
                        documento_nuevo.Cs_tag_AccountingSupplierParty_Party_PartyLegalEntity_RegistrationName = declarante.Cs_pr_RazonSocial;
                        documento_nuevo.Cs_pr_Ticket               = "";
                        documento_nuevo.Cs_pr_EstadoSCC            = "2";
                        documento_nuevo.Cs_pr_EstadoSUNAT          = "2";
                        documento_nuevo.Cs_pr_ComentarioSUNAT      = "";
                        documento_nuevo.Cs_pr_XML                  = "";
                        documento_nuevo.Cs_pr_CDR                  = "";
                        documento_nuevo.Cs_pr_DocumentoRelacionado = "";
                        documento_nuevo.Cs_pr_TipoContenido        = tipoContenido;
                        string idRetorno = documento_nuevo.cs_pxInsertar(false, false);
                        clsEntityVoidedDocuments_VoidedDocumentsLine linea;

                        if (tipoContenido == "0")
                        {        //facturas boletas y notas
                            //Si la fecha de referencia del item es igual a la fecha de referencia de su grupo, agregar
                            clsEntityDocument documento = new clsEntityDocument(localDB).cs_fxObtenerUnoPorId(Id_Documento);
                            if (documento.Cs_tag_IssueDate == fecha_comunicacion)
                            {
                                linea = new clsEntityVoidedDocuments_VoidedDocumentsLine(localDB);
                                linea.Cs_pr_VoidedDocuments_VoidedDocumentsLine_Id = Guid.NewGuid().ToString();
                                linea.Cs_pr_VoidedDocuments_Id     = idRetorno;
                                linea.Cs_tag_LineID                = "";
                                linea.Cs_tag_DocumentTypeCode      = documento.Cs_tag_InvoiceTypeCode;
                                linea.Cs_tag_DocumentSerialID      = documento.Cs_tag_ID.Split('-')[0].ToString();
                                linea.Cs_tag_DocumentNumberID      = documento.Cs_tag_ID.Split('-')[1].ToString();
                                linea.Cs_tag_VoidReasonDescription = "";
                                linea.Cs_pr_IDDocumentoRelacionado = Id_Documento;
                                linea.cs_pxInsertar(false, true);
                                documento.Cs_pr_ComunicacionBaja = idRetorno;        //Relación de comunicación de baja.
                                documento.cs_pxActualizar(false, false);
                            }
                        }
                        else if (tipoContenido == "1")
                        {        //retencion
                                 //Si la fecha de referencia del item es igual a la fecha de referencia de su grupo, agregar
                            clsEntityRetention documento = new clsEntityRetention(localDB).cs_fxObtenerUnoPorId(Id_Documento);
                            if (documento.Cs_tag_IssueDate == fecha_comunicacion)
                            {
                                linea = new clsEntityVoidedDocuments_VoidedDocumentsLine(localDB);
                                linea.Cs_pr_VoidedDocuments_VoidedDocumentsLine_Id = Guid.NewGuid().ToString();
                                linea.Cs_pr_VoidedDocuments_Id     = idRetorno;
                                linea.Cs_tag_LineID                = "";
                                linea.Cs_tag_DocumentTypeCode      = "20";
                                linea.Cs_tag_DocumentSerialID      = documento.Cs_tag_Id.Split('-')[0].ToString();
                                linea.Cs_tag_DocumentNumberID      = documento.Cs_tag_Id.Split('-')[1].ToString();
                                linea.Cs_tag_VoidReasonDescription = "";
                                linea.Cs_pr_IDDocumentoRelacionado = Id_Documento;
                                linea.cs_pxInsertar(false, true);
                                documento.Cs_pr_Reversion = idRetorno;        //Relación de comunicación de baja.
                                documento.cs_pxActualizar(false, false);
                            }
                        }
                        doc_agregados.Add(documento_nuevo.Cs_tag_ID);
                    }
                    //1. Buscar un resumen diario con la fecha de referencia que sea la misma del documento a dar de baja.
                    //2. Si ya existe, actualizar.
                    //3. Si no existe, agregar.


                    /*Buscar algún documento que tenga estado "sin estado"
                     * SI ENCUENTRA
                     *  Actualizar los items no repetidos.
                     * NO
                     *  Agregar documento de comunicación de baja
                     *  Agregar los items. */
                    if (docs_no_agregados.Count > 0)
                    {
                        foreach (string doc in docs_no_agregados)
                        {
                            mensaje += doc + "\n";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                clsBaseLog.cs_pxRegistarAdd("Comunicación de Baja Factura DBF: " + ex.ToString());
            }

            return(mensaje);
        }
        /// <summary>
        /// Metodo para generar la cadena de xml.
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public override string cs_pxGenerarXMLAString(string Id)
        {
            string archivo_xml = string.Empty;
            clsEntityVoidedDocuments cabecera = new clsEntityVoidedDocuments(localbd).cs_fxObtenerUnoPorId(Id);
            List <clsEntityVoidedDocuments_VoidedDocumentsLine> detalle = new clsEntityVoidedDocuments_VoidedDocumentsLine(localbd).cs_fxObtenerTodoPorCabeceraId(cabecera.Cs_pr_VoidedDocuments_Id);
            string fila = "";
            string ei   = "    ";
            string ef   = "\n";

            fila += "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?>" + ef;
            fila += "<VoidedDocuments xmlns=\"urn:sunat:names:specification:ubl:peru:schema:xsd:VoidedDocuments-1\" xmlns:cac=\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\" xmlns:cbc=\"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\" xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\" xmlns:ext=\"urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2\" xmlns:sac=\"urn:sunat:names:specification:ubl:peru:schema:xsd:SunatAggregateComponents-1\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + ef;
            fila += ei + "<ext:UBLExtensions>" + ef;
            fila += ei + ei + "<ext:UBLExtension><ext:ExtensionContent></ext:ExtensionContent></ext:UBLExtension>" + ef;
            fila += ei + "</ext:UBLExtensions>" + ef;

            #region Información de cabecera
            fila += ei + "<cbc:UBLVersionID>2.0</cbc:UBLVersionID>" + ef;
            fila += ei + "<cbc:CustomizationID>1.0</cbc:CustomizationID>" + ef;
            fila += ei + "<cbc:ID>" + cabecera.Cs_tag_ID + "</cbc:ID>" + ef;
            fila += ei + "<cbc:ReferenceDate>" + cabecera.Cs_tag_ReferenceDate + "</cbc:ReferenceDate>" + ef;
            fila += ei + "<cbc:IssueDate>" + cabecera.Cs_tag_IssueDate + "</cbc:IssueDate>" + ef;
            #endregion

            #region Referencia de la firma digital
            fila += ei + "<cac:Signature>" + ef;
            fila += ei + ei + "<cbc:ID>SignatureSP</cbc:ID>" + ef;
            fila += ei + ei + "<cac:SignatoryParty>" + ef;
            fila += ei + ei + ei + "<cac:PartyIdentification>" + ef;
            fila += ei + ei + ei + ei + "<cbc:ID>" + declarante.Cs_pr_Ruc + "</cbc:ID>" + ef;
            fila += ei + ei + ei + "</cac:PartyIdentification>" + ef;
            //Jordy Amaro 14/11/16 FE-865
            //Agregado <!CDATA.
            fila += ei + ei + ei + "<cac:PartyName>" + ef;
            fila += ei + ei + ei + ei + "<cbc:Name><![CDATA[" + "RAZONSOCIALDECERTIFICADO" + "]]></cbc:Name>" + ef;
            fila += ei + ei + ei + "</cac:PartyName>" + ef;
            fila += ei + ei + "</cac:SignatoryParty>" + ef;

            fila += ei + ei + "<cac:DigitalSignatureAttachment>" + ef;
            fila += ei + ei + ei + "<cac:ExternalReference>" + ef;
            fila += ei + ei + ei + ei + "<cbc:URI>#SignatureSP</cbc:URI>" + ef;
            fila += ei + ei + ei + "</cac:ExternalReference>" + ef;
            fila += ei + ei + "</cac:DigitalSignatureAttachment>" + ef;
            fila += ei + "</cac:Signature>" + ef;
            #endregion

            #region Datos del emisor del documento
            fila += ei + "<cac:AccountingSupplierParty>" + ef;
            fila += ei + ei + "<cbc:CustomerAssignedAccountID>" + cabecera.Cs_tag_AccountingSupplierParty_CustomerAssignedAccountID + "</cbc:CustomerAssignedAccountID>" + ef;
            fila += ei + ei + "<cbc:AdditionalAccountID>" + cabecera.Cs_tag_AccountingSupplierParty_AdditionalAccountID + "</cbc:AdditionalAccountID>" + ef;
            if (cabecera.Cs_tag_AccountingSupplierParty_Party_PartyLegalEntity_RegistrationName.Trim().Length > 0)
            {
                //Jordy Amaro 08/11/16 FE-851
                //Agregado <!CDATA.
                fila += ei + ei + "<cac:Party>" + ef;
                fila += ei + ei + ei + "<cac:PartyLegalEntity>" + ef;
                fila += ei + ei + ei + ei + "<cbc:RegistrationName><![CDATA[" + cabecera.Cs_tag_AccountingSupplierParty_Party_PartyLegalEntity_RegistrationName + "]]></cbc:RegistrationName>" + ef;
                fila += ei + ei + ei + "</cac:PartyLegalEntity>" + ef;
                fila += ei + ei + "</cac:Party>" + ef;
            }
            fila += ei + "</cac:AccountingSupplierParty>" + ef;
            #endregion
            #region Lineas de detalle del documento
            Int32 linea_indice = 0;
            foreach (var linea in detalle)
            {
                linea_indice++;
                fila += ei + "<sac:VoidedDocumentsLine>" + ef;
                fila += ei + "<cbc:LineID>" + linea_indice + "</cbc:LineID>" + ef;
                fila += ei + "<cbc:DocumentTypeCode>" + linea.Cs_tag_DocumentTypeCode + "</cbc:DocumentTypeCode>" + ef;
                fila += ei + "<sac:DocumentSerialID>" + linea.Cs_tag_DocumentSerialID + "</sac:DocumentSerialID>" + ef;
                fila += ei + "<sac:DocumentNumberID>" + linea.Cs_tag_DocumentNumberID + "</sac:DocumentNumberID>" + ef;
                fila += ei + "<sac:VoidReasonDescription>" + linea.Cs_tag_VoidReasonDescription + "</sac:VoidReasonDescription>" + ef;
                fila += ei + "</sac:VoidedDocumentsLine>" + ef;
            }
            fila += "</VoidedDocuments>" + ef;

            try
            {
                string           pfxPath = declarante.Cs_pr_Rutacertificadodigital.Replace("\\\\", "\\");
                X509Certificate2 cert    = new X509Certificate2(File.ReadAllBytes(pfxPath), declarante.Cs_pr_Parafrasiscertificadodigital);

                //Cristhian|25/08/2017|FEI2-352

                /*Se agrega un metodo de busqueda para ubicar la razon social de la empresa
                 * ya no dependiendo de la ubicacion donde se encuentre, ahora se busca su
                 * etiqueta y se obtine el valor(la razon social)*/
                /*NUEVO INICIO*/
                string[] subject = cert.SubjectName.Name.Split(',');
                foreach (string item in subject)
                {
                    string[] subject_o = item.ToString().Split('=');
                    if (subject_o[0].Trim() == "O")
                    {
                        fila = fila.Replace("RAZONSOCIALDECERTIFICADO", subject_o[1].TrimStart());
                    }
                }
                /*NUEVO FIN*/

                XmlDocument documento = new XmlDocument();
                documento.PreserveWhitespace = false;
                documento.LoadXml(fila.Replace("\\\\", "\\"));
                archivo_xml = FirmarXml(documento, cert);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.ToString());
                clsBaseLog.cs_pxRegistarAdd("clsNegocioCEComunicacionBaja generarXML" + ex.ToString());
            }
            return(archivo_xml);

            #endregion
        }
        /// <summary>
        /// METODO PARA PROCESAR DOCUMENTOS A DAR DE BAJA FEI2-222 29-05-2017
        /// </summary>
        /// <param name="DocumentosADarDeBaja"></param>
        /// <param name="tipoContenido"></param>
        /// <returns></returns>
        public string cs_pxProcesarComunicacionBaja(List <string> DocumentosADarDeBaja, string tipoContenido)
        {
            string mensaje = string.Empty;

            try
            {
                //Buscar grupos de fechas seleccionadas y por cada grupo debe crear un archivo de comunicación de baja.
                #region "AGRUPAR POR COMUNICACIÓN DE BAJA"
                List <string> grupo             = new List <string>(); //Crear grupos de fecha por IssueDate - FECHA DE EMISION
                List <string> docs_no_agregados = new List <string>(); //Lista de doccumentos no agregados
                //Recorrer los documentos a dar de baja para agregar asu respectiva comunicacion de baja.
                foreach (var documento_id in DocumentosADarDeBaja)
                {
                    //Si los comprobantes son facturas notas y/o boletas.
                    if (tipoContenido == "0")
                    {
                        clsEntityDocument document = new clsEntityDocument(localbd).cs_fxObtenerUnoPorId(documento_id);
                        if (document.Cs_pr_ComunicacionBaja.Trim().Length <= 0)
                        {
                            //Verificar los 7 dias anteriores al dia de hoy para permitir agregar a resumen diario.
                            string fechaEmision = document.Cs_tag_IssueDate;
                            if (fechaEmision == DateTime.Now.ToString("yyyy-MM-dd") ||
                                fechaEmision == DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") ||
                                fechaEmision == DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd") ||
                                fechaEmision == DateTime.Now.AddDays(-3).ToString("yyyy-MM-dd") ||
                                fechaEmision == DateTime.Now.AddDays(-4).ToString("yyyy-MM-dd") ||
                                fechaEmision == DateTime.Now.AddDays(-5).ToString("yyyy-MM-dd") ||
                                fechaEmision == DateTime.Now.AddDays(-6).ToString("yyyy-MM-dd") ||
                                fechaEmision == DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd"))
                            {
                                int count = 0;
                                foreach (var item_grupo in grupo)
                                {
                                    if (fechaEmision == item_grupo)
                                    {
                                        count++;
                                    }
                                }
                                if (count <= 0)//Si no existe el elemento en la lista, que se agregue.
                                {
                                    grupo.Add(fechaEmision);
                                }
                            }
                            else
                            {
                                docs_no_agregados.Add(document.Cs_tag_ID);
                            }
                        }
                    }
                    else if (tipoContenido == "1")
                    {
                        //Cuando se agregan tipo de documentos retencion
                        clsEntityRetention document = new clsEntityRetention(localbd).cs_fxObtenerUnoPorId(documento_id);
                        if (document.Cs_pr_Reversion.Trim().Length <= 0)
                        {
                            //Asignar valor a fecha de emision.
                            string fechaEmision = document.Cs_tag_IssueDate;

                            int count = 0;
                            foreach (var item_grupo in grupo)
                            {
                                if (fechaEmision == item_grupo)
                                {
                                    count++;
                                }
                            }
                            if (count <= 0)//Si no existe el elemento en la lista, que se agregue.
                            {
                                grupo.Add(fechaEmision);
                            }
                        }
                    }
                }
                #endregion
                //Crear grupos de fecha por IssueDate - FechaEmision
                List <string>            doc_agregados = new List <string>();
                clsEntityVoidedDocuments comunicacion_baja;
                if (DocumentosADarDeBaja.Count > 0)
                {
                    //Si existen documentos a dar de baja por grupos.
                    foreach (var fecha_comunicacion in grupo)
                    {
                        //Buscar comunicacion de baja existente.
                        string documento_baja_existente = new clsEntityVoidedDocuments(localbd).cs_pxObtenerDocumentoComuninicacionBajaExisente(fecha_comunicacion, tipoContenido);
                        if (documento_baja_existente != "")
                        {
                            //Si existe comunicacion de baja Agregar los comprobantes al que ya se encuentra creado.
                            bool agregado = new clsEntityVoidedDocuments(localbd).cs_pxComunicacionBajaActualizar(DocumentosADarDeBaja, documento_baja_existente, tipoContenido);
                            if (agregado == true)
                            {
                                //Si se han agregado los comprobantes actualizar el nombre de la comunicacion de baja en caso se este agregando a otro que se haya generado anteriormente.
                                comunicacion_baja = new clsEntityVoidedDocuments(localbd).cs_fxObtenerUnoPorId(documento_baja_existente);
                                comunicacion_baja.Cs_tag_IssueDate = DateTime.Now.ToString("yyyy-MM-dd");
                                string correlativo = comunicacion_baja.Cs_tag_ID.Split('-')[2];
                                if (tipoContenido == "0")
                                {//Facturas Boletas y Notas
                                    comunicacion_baja.Cs_tag_ID = "RA-" + comunicacion_baja.Cs_tag_IssueDate.Replace("-", "") + "-" + correlativo;
                                }
                                else if (tipoContenido == "1")
                                {//Retencion
                                    comunicacion_baja.Cs_tag_ID = "RR-" + comunicacion_baja.Cs_tag_IssueDate.Replace("-", "") + "-" + correlativo;
                                }
                                comunicacion_baja.cs_pxActualizar(false, false);
                                doc_agregados.Add(comunicacion_baja.Cs_tag_ID);
                            }
                        }
                        else
                        {
                            //Crear documento de comunicación de baja ya que no existe
                            string documento_nuevo_id = Guid.NewGuid().ToString();
                            clsEntityVoidedDocuments documento_nuevo = new clsEntityVoidedDocuments(localbd);
                            documento_nuevo.Cs_pr_VoidedDocuments_Id = documento_nuevo_id;
                            documento_nuevo.Cs_tag_ReferenceDate     = fecha_comunicacion;//DateTime.Now.ToString("yyyy-MM-dd");
                            documento_nuevo.Cs_tag_IssueDate         = DateTime.Now.ToString("yyyy-MM-dd");
                            if (tipoContenido == "0")
                            {
                                documento_nuevo.Cs_tag_ID = "RA-" + documento_nuevo.Cs_tag_IssueDate.Replace("-", "") + "-" + new clsEntityVoidedDocuments(localbd).cs_fxObtenerCorrelativo("0");
                            }
                            else if (tipoContenido == "1")
                            {
                                documento_nuevo.Cs_tag_ID = "RR-" + documento_nuevo.Cs_tag_IssueDate.Replace("-", "") + "-" + new clsEntityVoidedDocuments(localbd).cs_fxObtenerCorrelativo("1");
                            }
                            documento_nuevo.Cs_tag_AccountingSupplierParty_CustomerAssignedAccountID = declarante.Cs_pr_Ruc;
                            documento_nuevo.Cs_tag_AccountingSupplierParty_AdditionalAccountID       = "6";
                            documento_nuevo.Cs_tag_AccountingSupplierParty_Party_PartyLegalEntity_RegistrationName = declarante.Cs_pr_RazonSocial;
                            documento_nuevo.Cs_pr_Ticket               = "";
                            documento_nuevo.Cs_pr_EstadoSCC            = "2";
                            documento_nuevo.Cs_pr_EstadoSUNAT          = "2";
                            documento_nuevo.Cs_pr_ComentarioSUNAT      = "";
                            documento_nuevo.Cs_pr_XML                  = "";
                            documento_nuevo.Cs_pr_CDR                  = "";
                            documento_nuevo.Cs_pr_DocumentoRelacionado = "";
                            documento_nuevo.Cs_pr_TipoContenido        = tipoContenido;
                            string idRetorno = documento_nuevo.cs_pxInsertar(false, false);
                            clsEntityVoidedDocuments_VoidedDocumentsLine linea;
                            //Amaro Quispe Jordy | 2017-07-05 | FEI2-220
                            //Se comento el codigo que agregaba los documentos enviados anteriormente.Por pedido de Tania.
                            //INI-MODIFICA-01

                            //Buscar el ultimo documento de comunicación de baja enviado con la fecha de referencia = fecha del grupo
                            //Si existe, adjuntar los items existentes a este nuevo documento

                            /*string id_comunicacion_de_baja_existente_para_adjuntar_registros_a_sustitutorio = new clsEntityVoidedDocuments(localbd).cs_pxObtenerDocumentoComuninicacionBajaExisente(fecha_comunicacion, true,tipoContenido);
                             * if (id_comunicacion_de_baja_existente_para_adjuntar_registros_a_sustitutorio != null && id_comunicacion_de_baja_existente_para_adjuntar_registros_a_sustitutorio.Trim().Length > 0)
                             * {
                             *  List<clsEntityVoidedDocuments_VoidedDocumentsLine> DocumentosDadosDeBajaConAnterioridad = new clsEntityVoidedDocuments_VoidedDocumentsLine(localbd).cs_fxObtenerTodoPorCabeceraId(id_comunicacion_de_baja_existente_para_adjuntar_registros_a_sustitutorio);
                             *  foreach (var itemx in DocumentosDadosDeBajaConAnterioridad)
                             *  {
                             *      if (tipoContenido == "0")
                             *      {
                             *          //facturas boletas y notas
                             *          clsEntityDocument documento = new clsEntityDocument(localbd).cs_fxObtenerUnoPorId(itemx.Cs_pr_IDDocumentoRelacionado);
                             *          //Agregar estos items y actualizar el id de comunicación de baja en el documento principal.
                             *          linea = new clsEntityVoidedDocuments_VoidedDocumentsLine(localbd);
                             *          linea.Cs_pr_VoidedDocuments_VoidedDocumentsLine_Id = Guid.NewGuid().ToString();
                             *          //linea.Cs_pr_VoidedDocuments_Id = itemx.Cs_pr_VoidedDocuments_Id;
                             *          //Jordy Amaro 09-12-16 FE-912
                             *          //CAMBIO DE ASOCIACION IDS
                             *          //Ini-Modifica
                             *          linea.Cs_pr_VoidedDocuments_Id = idRetorno;
                             *          //Fin-Modifica
                             *          linea.Cs_tag_LineID = itemx.Cs_tag_LineID;
                             *          linea.Cs_tag_DocumentTypeCode = itemx.Cs_tag_DocumentTypeCode;
                             *          linea.Cs_tag_DocumentSerialID = itemx.Cs_tag_DocumentSerialID;
                             *          linea.Cs_tag_DocumentNumberID = itemx.Cs_tag_DocumentNumberID;
                             *          linea.Cs_tag_VoidReasonDescription = itemx.Cs_tag_VoidReasonDescription;
                             *          linea.Cs_pr_IDDocumentoRelacionado = itemx.Cs_pr_IDDocumentoRelacionado;
                             *          linea.cs_pxInsertar(false, true);
                             *          documento.Cs_pr_ComunicacionBaja = idRetorno;//Relación de comunicación de baja.
                             *          documento.cs_pxActualizar(false, false);
                             *
                             *      }
                             *      else if (tipoContenido == "1")
                             *      {
                             *          //retencion
                             *          clsEntityRetention documento = new clsEntityRetention(localbd).cs_fxObtenerUnoPorId(itemx.Cs_pr_IDDocumentoRelacionado);
                             *          //Agregar estos items y actualizar el id de comunicación de baja en el documento principal.
                             *          linea = new clsEntityVoidedDocuments_VoidedDocumentsLine(localbd);
                             *          linea.Cs_pr_VoidedDocuments_VoidedDocumentsLine_Id = Guid.NewGuid().ToString();
                             *          //linea.Cs_pr_VoidedDocuments_Id = itemx.Cs_pr_VoidedDocuments_Id;
                             *          //Jordy Amaro 09-12-16 FE-912
                             *          //CAMBIO DE ASOCIACION IDS
                             *          //Ini-Modifica
                             *          linea.Cs_pr_VoidedDocuments_Id = idRetorno;
                             *          //Fin-Modifica
                             *          linea.Cs_tag_LineID = itemx.Cs_tag_LineID;
                             *          linea.Cs_tag_DocumentTypeCode = itemx.Cs_tag_DocumentTypeCode;
                             *          linea.Cs_tag_DocumentSerialID = itemx.Cs_tag_DocumentSerialID;
                             *          linea.Cs_tag_DocumentNumberID = itemx.Cs_tag_DocumentNumberID;
                             *          linea.Cs_tag_VoidReasonDescription = itemx.Cs_tag_VoidReasonDescription;
                             *          linea.Cs_pr_IDDocumentoRelacionado = itemx.Cs_pr_IDDocumentoRelacionado;
                             *          linea.cs_pxInsertar(false, true);
                             *          documento.Cs_pr_Reversion = idRetorno;//Relación de comunicación de baja reversion.
                             *          documento.cs_pxActualizar(false, false);
                             *
                             *      }
                             *
                             *  }
                             * }*/

                            //FIN-MODIFICA-01

                            //Recorrer los documentos a dar de Baja y  agregar las lineas.
                            foreach (var Item in DocumentosADarDeBaja)
                            {
                                if (tipoContenido == "0")
                                {//facturas boletas y notas
                                    //Si la fecha de referencia del item es igual a la fecha de referencia de su grupo, agregar
                                    clsEntityDocument documento = new clsEntityDocument(localbd).cs_fxObtenerUnoPorId(Item);
                                    if (documento.Cs_tag_IssueDate == fecha_comunicacion)
                                    {
                                        linea = new clsEntityVoidedDocuments_VoidedDocumentsLine(localbd);
                                        linea.Cs_pr_VoidedDocuments_VoidedDocumentsLine_Id = Guid.NewGuid().ToString();
                                        linea.Cs_pr_VoidedDocuments_Id     = idRetorno;
                                        linea.Cs_tag_LineID                = "";
                                        linea.Cs_tag_DocumentTypeCode      = documento.Cs_tag_InvoiceTypeCode;
                                        linea.Cs_tag_DocumentSerialID      = documento.Cs_tag_ID.Split('-')[0].ToString();
                                        linea.Cs_tag_DocumentNumberID      = documento.Cs_tag_ID.Split('-')[1].ToString();
                                        linea.Cs_tag_VoidReasonDescription = "";
                                        linea.Cs_pr_IDDocumentoRelacionado = Item;
                                        linea.cs_pxInsertar(false, true);
                                        documento.Cs_pr_ComunicacionBaja = idRetorno;//Relación de comunicación de baja.
                                        documento.cs_pxActualizar(false, false);
                                    }
                                }
                                else if (tipoContenido == "1")
                                {//retencion
                                 //Si la fecha de referencia del item es igual a la fecha de referencia de su grupo, agregar
                                    clsEntityRetention documento = new clsEntityRetention(localbd).cs_fxObtenerUnoPorId(Item);
                                    if (documento.Cs_tag_IssueDate == fecha_comunicacion)
                                    {
                                        linea = new clsEntityVoidedDocuments_VoidedDocumentsLine(localbd);
                                        linea.Cs_pr_VoidedDocuments_VoidedDocumentsLine_Id = Guid.NewGuid().ToString();
                                        linea.Cs_pr_VoidedDocuments_Id     = idRetorno;
                                        linea.Cs_tag_LineID                = "";
                                        linea.Cs_tag_DocumentTypeCode      = "20";
                                        linea.Cs_tag_DocumentSerialID      = documento.Cs_tag_Id.Split('-')[0].ToString();
                                        linea.Cs_tag_DocumentNumberID      = documento.Cs_tag_Id.Split('-')[1].ToString();
                                        linea.Cs_tag_VoidReasonDescription = "";
                                        linea.Cs_pr_IDDocumentoRelacionado = Item;
                                        linea.cs_pxInsertar(false, true);
                                        documento.Cs_pr_Reversion = idRetorno;//Relación de comunicación de baja.
                                        documento.cs_pxActualizar(false, false);
                                    }
                                }
                            }
                            doc_agregados.Add(documento_nuevo.Cs_tag_ID);
                        }
                    }
                    //1. Buscar un resumen diario con la fecha de referencia que sea la misma del documento a dar de baja.
                    //2. Si ya existe, actualizar.
                    //3. Si no existe, agregar.


                    /*Buscar algún documento que tenga estado "sin estado"
                     * SI ENCUENTRA
                     *  Actualizar los items no repetidos.
                     * NO
                     *  Agregar documento de comunicación de baja
                     *  Agregar los items. */
                    if (docs_no_agregados.Count > 0)
                    {
                        foreach (string doc in docs_no_agregados)
                        {
                            mensaje += doc + "\n";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                clsBaseLog.cs_pxRegistarAdd("procesarcomunicacion baja" + ex.ToString());
            }

            return(mensaje);
        }
Exemple #12
0
        private void cs_pxCargarDgvDocumentosBaja(string fechainicio, string fechafin)
        {
            try
            {
                DateTime finicio = Convert.ToDateTime(fechainicio);
                DateTime ffin    = Convert.ToDateTime(fechafin);
                dgvComunicacionbaja.Rows.Clear();
                List <List <string> > registros = new clsNegocioCEComunicacionBaja().cs_pxObtenerPorFiltroPrincipal(finicio.ToString("yyyy-MM-dd"), ffin.ToString("yyyy-MM-dd"));
                foreach (var item in registros)
                {
                    string Estado_SCC           = "";
                    bool   validar_motivos_baja = new clsEntityVoidedDocuments().cs_pxValidarMotivosDeBajaEnItems(item[0].Trim().ToString());
                    string ticket = item[7].ToString().Trim();
                    string comentario_desde_sunat = item[10].ToString().Trim();
                    string condicion_de_ticket    = "";
                    string fecha_emision          = "";
                    // string fecha_referencia = "";
                    // string fecha_comunicacion = "";

                    if (comentario_desde_sunat.Trim() == "")
                    {
                        condicion_de_ticket = "PENDIENTE DE RECEPCIÓN";
                    }
                    else
                    {
                        condicion_de_ticket = "RECIBIDO";
                    }

                    if (validar_motivos_baja == true && ticket == "")
                    {
                        Estado_SCC = "2";
                    }
                    if (validar_motivos_baja == false && ticket == "")
                    {
                        Estado_SCC = "1";
                    }
                    if (validar_motivos_baja == false && ticket != "")
                    {
                        Estado_SCC = "0";
                    }
                    if (validar_motivos_baja == true && ticket != "")
                    {
                        Estado_SCC = item[8].ToString().Trim();
                    }


                    if (Estado_SCC == "0")
                    {
                        fecha_emision = item[3].ToString();
                    }
                    else
                    {
                        fecha_emision = "";
                    }


                    dgvComunicacionbaja.Rows.Add(
                        item[0].ToString().Trim(),  //ID
                        false,                      //Seleccionar
                        item[1].Trim(),             //Código
                        item[2].Trim(),             //Fecha de comunicación
                        item[2].Trim(),             //Fecha de referencia (OCULTO HASTA QUE SE APRUEBE)
                        fecha_emision,              //Fecha de emision
                        item[7].Trim(),             //Ticket
                        "",                         //Estado SCC - Descripción
                        "",                         //Estado SUNAT - Descripción
                        condicion_de_ticket,        //Estado SUNAT RECEPCIÓN DE TICKET - Decripción
                        item[10].ToString().Trim(), //Comentario desde SUNAT
                        Estado_SCC,                 //Estado SCC
                        item[9].ToString().Trim()   //Estado SUNAT
                        );
                }

                foreach (DataGridViewRow row in dgvComunicacionbaja.Rows)
                {
                    string idice_ESCC         = row.Cells[11].Value.ToString();
                    string idice_ESUNAT       = row.Cells[12].Value.ToString();
                    int    i_scc_descipcion   = 7;
                    int    i_sunat_descipcion = 8;

                    switch (idice_ESCC)
                    {
                    case "1":
                        row.Cells[i_scc_descipcion].Style.ForeColor = Color.Red;    //Pendiente (errores)
                        Seleccionar.ReadOnly = false;
                        break;

                    case "2":
                        row.Cells[i_scc_descipcion].Style.ForeColor = Color.RoyalBlue;    //Pendiente (correcto)
                        break;

                    case "0":
                        row.Cells[i_scc_descipcion].Style.ForeColor = Color.Green;    //Enviado
                        break;
                    }
                    row.Cells[i_scc_descipcion].Value = clsBaseUtil.cs_fxComprobantesEstadosSCC_descripcion(Convert.ToInt16(idice_ESCC)).ToUpper();
                    switch (idice_ESUNAT)
                    {
                    case "0":
                        row.Cells[i_sunat_descipcion].Style.ForeColor = Color.Green;    //Aceptado
                        break;

                    case "1":
                        row.Cells[i_sunat_descipcion].Style.ForeColor = Color.Brown;    //Rechazado
                        break;

                    case "2":
                        row.Cells[i_sunat_descipcion].Style.ForeColor = Color.Red;    //Sin respuesta
                        break;

                    case "3":
                        row.Cells[i_sunat_descipcion].Style.ForeColor = Color.Salmon;    //Anulado
                        break;
                    }
                    row.Cells[i_sunat_descipcion].Value = clsBaseUtil.cs_fxComprobantesEstadosSUNAT_descripcion(Convert.ToInt16(idice_ESUNAT)).ToUpper();
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.ToString());
                throw;
            }
        }