예제 #1
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            clsEntityRetention cabecera = new clsEntityRetention(localDB);

            cabecera.cs_fxObtenerUnoPorId(IdComprobante);

            txtTipoComprobante.Text = "Comprobante de retención electrónico";
            txtRuc.Text             = cabecera.Cs_tag_ReceiveParty_PartyIdentification_Id;
            txtFechaEmision.Text    = cabecera.Cs_tag_IssueDate;
            txtRazonSocial.Text     = cabecera.Cs_tag_ReceiveParty_PartyLegalEntity_RegistrationName;
            txtSerieNumero.Text     = cabecera.Cs_tag_Id;

            List <clsEntityRetention_RetentionLine> registros = new clsEntityRetention_RetentionLine(localDB).cs_fxObtenerTodoPorCabeceraId(IdComprobante);

            if (registros.Count > 0)
            {
                foreach (var item in registros)
                {
                    item_lista = new clsEntityRetention_RetentionLine(localDB);
                    item_lista.Cs_tag_Id_SchemeId = clsBaseUtil.cs_fxComprobantesElectronicos_descripcion(item.Cs_tag_Id_SchemeId);
                    item_lista.Cs_tag_Id          = item.Cs_tag_Id;
                    item_lista.Cs_tag_IssueDate   = item.Cs_tag_IssueDate;
                    item_lista.Cs_tag_SUNATRetentionInformation_SUNATRetentionAmount = item.Cs_tag_SUNATRetentionInformation_SUNATRetentionAmount;
                    item_lista.Cs_tag_SUNATRetentionInformation_SUNATNetTotalPaid    = item.Cs_tag_SUNATRetentionInformation_SUNATNetTotalPaid;
                    lista_items.Add(item_lista);
                }
            }

            dgEmpresas.ItemsSource = lista_items;
        }
예제 #2
0
 private void btnXMLRecepcion_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         clsEntityRetention item = new clsEntityRetention(localDB).cs_fxObtenerUnoPorId(IdComprobante);
         if (item != null)
         {
             SaveFileDialog sfdDescargar = new SaveFileDialog();
             DialogResult   result       = sfdDescargar.ShowDialog();
             if (result == System.Windows.Forms.DialogResult.OK)
             {
                 string file = sfdDescargar.FileName;
                 if (file.Substring(file.Length - 4) != ".xml")
                 {
                     file = file + ".xml";
                 }
                 try
                 {
                     StreamWriter sw0 = new StreamWriter(file);
                     sw0.Write(item.Cs_pr_CDR);
                     sw0.Close();
                     System.Windows.Forms.MessageBox.Show("Se generó correctamente el archivo XML de recepcion en la ruta seleccionada.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                 }
                 catch (IOException)
                 {
                 }
             }
         }
     }
     catch (Exception ex)
     {
         clsBaseLog.cs_pxRegistarAdd("xml recep gen" + ex.ToString());
     }
 }
        /// <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);
            }
        }
예제 #4
0
 private void XMLRecepcion_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         ReporteRetention item = (ReporteRetention)dgComprobantesFactura.SelectedItem;
         if (item != null)
         {
             clsEntityRetention cabecera     = new clsEntityRetention(localDB).cs_fxObtenerUnoPorId(item.Id);
             SaveFileDialog     sfdDescargar = new SaveFileDialog();
             DialogResult       result       = sfdDescargar.ShowDialog();
             if (result == DialogResult.OK)
             {
                 string file = sfdDescargar.FileName;
                 if (file.Substring(file.Length - 4) != ".xml")
                 {
                     file = file + ".xml";
                 }
                 try
                 {
                     StreamWriter sw0 = new StreamWriter(file);
                     sw0.Write(cabecera.Cs_pr_CDR);
                     sw0.Close();
                 }
                 catch (IOException)
                 {
                 }
             }
         }
     }
     catch (Exception ex)
     {
         clsBaseLog.cs_pxRegistarAdd("xml recep gen" + ex.ToString());
     }
 }
예제 #5
0
        private void btnDescartar_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //Verificar si hay elementos seleccionados
                List <ReporteRetention> seleccionados = new List <ReporteRetention>();
                foreach (var item in lista_reporte)
                {
                    if (item.Check == true)
                    {
                        seleccionados.Add(item);
                    }
                }

                if (seleccionados.Count > 0)
                {
                    if (System.Windows.Forms.MessageBox.Show("¿Está seguro que desea descartar los documentos seleccionados?\nEstos documentos serán eliminados completamente de la base de datos.", "¿Está seguro?", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        string mensaje = string.Empty;
                        foreach (ReporteRetention row in seleccionados)
                        {
                            bool resultado = new clsEntityRetention(localDB).cs_pxEliminarDocumento(row.Id);
                            if (resultado == true)
                            {
                                mensaje += row.SerieNumero + "\n";
                            }
                        }

                        if (mensaje.Length > 0)
                        {
                            CustomDialogWindow obj = new CustomDialogWindow();
                            obj.AdditionalDetailsText = "Los comprobantes son:\n" + mensaje;
                            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 eliminados";
                            obj.InstructionIcon    = CustomDialogIcons.Information;
                            obj.InstructionText    = "Los documentos se eliminaron correctamente de la base de datos.";
                            CustomDialogResults objResults = obj.Show();
                            // System.Windows.Forms.MessageBox.Show("Los siguientes documentos se eliminaron correctamente de la base de datos.\n"+mensaje,"Mensaje",MessageBoxButtons.OK,MessageBoxIcon.Information);
                        }
                        refrescarGrilla();
                    }
                }
            }
            catch (Exception ex)
            {
                clsBaseLog.cs_pxRegistarAdd("delete factura" + ex.ToString());
                //clsBaseMensaje.cs_pxMsgEr("ERR15", ex.Message);
            }
        }
예제 #6
0
        private void btnXMLEnvio_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                clsEntityRetention item = new clsEntityRetention(localDB).cs_fxObtenerUnoPorId(IdComprobante);
                if (item != null)
                {
                    SaveFileDialog sfdDescargar = new SaveFileDialog();
                    sfdDescargar.FileName = item.Cs_tag_Id;
                    DialogResult result = sfdDescargar.ShowDialog();
                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        string file = sfdDescargar.FileName;
                        if (file.Substring(file.Length - 4) != ".xml")
                        {
                            file = file + ".xml";
                        }
                        try
                        {
                            string xml = string.Empty;

                            if (item.Cs_pr_XML.Trim().Length > 0)
                            {
                                xml = item.Cs_pr_XML;
                            }
                            else
                            {
                                xml = new clsNegocioCERetention(localDB).cs_pxGenerarXMLAString(item.Cs_pr_Retention_id);
                            }
                            StreamWriter sw0 = new StreamWriter(file);
                            sw0.Write(xml);
                            sw0.Close();
                            System.Windows.Forms.MessageBox.Show("Se generó correctamente el archivo XML de envío en la ruta seleccionada.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        catch (Exception ex)
                        {
                            clsBaseLog.cs_pxRegistarAdd("generar xml envio " + ex.ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                clsBaseLog.cs_pxRegistarAdd("xml envio gen " + ex.ToString());
            }
        }
예제 #7
0
        public string cs_pxGenerarRetention(string Id)
        {
            string archivo_nombre_XML = string.Empty, archivo_nombre_ZIP = string.Empty, archivo_nombre_directorio = string.Empty;

            try
            {
                clsEntityRetention RetentionDocument = new clsEntityRetention(localDB).cs_fxObtenerUnoPorId(Id);
                if (RetentionDocument.Cs_pr_EstadoSUNAT != "1")
                {
                    string fila = string.Empty; fila = new clsNegocioCERetention(localDB).cs_pxGenerarXMLAString(Id);
                    #region Genera el nombre de archivo
                    archivo_nombre_XML        = declarante.Cs_pr_Ruc + "-" + "20" + "-" + RetentionDocument.Cs_tag_Id.ToString() + ".xml";
                    archivo_nombre_ZIP        = declarante.Cs_pr_Ruc + "-" + "20" + "-" + RetentionDocument.Cs_tag_Id.ToString() + ".zip";
                    archivo_nombre_directorio = declarante.Cs_pr_Ruc + "-" + "20" + "-" + RetentionDocument.Cs_tag_Id.ToString();
                    string documento_ruta = new clsBaseConfiguracion().cs_prRutadocumentosenvio + "/", documento_ruta_nombre = documento_ruta + archivo_nombre_directorio + "\\" + archivo_nombre_XML;
                    if (File.Exists(documento_ruta_nombre))
                    {
                        File.Delete(documento_ruta_nombre);
                    }
                    if (Directory.Exists(documento_ruta + archivo_nombre_directorio))
                    {
                        var dir = new DirectoryInfo(documento_ruta + archivo_nombre_directorio); dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly; dir.Delete(true);
                    }
                    if (!Directory.Exists(documento_ruta + archivo_nombre_directorio))
                    {
                        Directory.CreateDirectory(documento_ruta + archivo_nombre_directorio);
                    }
                    if (!File.Exists(documento_ruta_nombre))
                    {
                        File.Create(documento_ruta_nombre).Close();
                    }
                    // StreamWriter sw1 = new StreamWriter(documento_ruta_nombre); sw1.WriteLine(fila); sw1.Close(); fila = string.Empty;
                    StreamWriter  sw1 = new StreamWriter(File.Open(documento_ruta_nombre, FileMode.OpenOrCreate), Encoding.GetEncoding("ISO-8859-1")); sw1.WriteLine(fila); sw1.Close(); fila = string.Empty;
                    DirectoryInfo x   = new DirectoryInfo(documento_ruta + archivo_nombre_directorio);
                    cs_prComprimirZIP(x);
                    #endregion
                }
                return(archivo_nombre_ZIP);
            }
            catch (Exception ex)
            {
                clsBaseLog.cs_pxRegistarAdd("clsNegocioCE cs_pxGenerarRetention " + ex.ToString());
                return(null);
            }
        }
        /// <summary>
        /// Obtiene el estado del conprobante en SUNAT para los comprobantes de retencion(ACEPTADO, RECHAZADO, SIN ESTADO, ANULADO)
        /// </summary>
        /// <param name="Id">Id del comprobante</param>
        /// <returns></returns>
        public string cs_fxEstadoSUNATRetention(string Id)
        {
            clsEntityRetention cabecera = new clsEntityRetention(localDB).cs_fxObtenerUnoPorId(Id);

            return(clsBaseUtil.cs_fxComprobantesEstadosSUNAT_descripcion(Convert.ToInt32(cabecera.Cs_pr_EstadoSUNAT.Trim())));
        }
예제 #9
0
        private void btnRepresentacionImpresa_Click(object sender, RoutedEventArgs e)
        {
            //Descargar representacion impresa.
            try
            {
                clsEntityDeclarant declarante       = new clsEntityDeclarant().cs_pxObtenerUnoPorId(localDB.Cs_pr_Declarant_Id);
                string             currentDirectory = Environment.CurrentDirectory;
                string             pathImage        = currentDirectory + "\\" + declarante.Cs_pr_Ruc + "\\logo.png";
                string             pathDatos        = currentDirectory + "\\" + declarante.Cs_pr_Ruc + "\\informacionImpreso.txt";
                if (File.Exists(pathImage) && File.Exists(pathDatos))
                {
                    StreamReader readDatos    = new StreamReader(pathDatos);
                    string       datosImpresa = readDatos.ReadToEnd();
                    readDatos.Close();

                    clsEntityRetention cabecera = new clsEntityRetention(localDB);
                    cabecera.cs_fxObtenerUnoPorId(IdComprobante);
                    if (cabecera != null)
                    {
                        string[] partes = cabecera.Cs_tag_Id.Split('-');

                        System.Windows.Forms.SaveFileDialog sfdDescargar = new System.Windows.Forms.SaveFileDialog();
                        sfdDescargar.FileName = cabecera.Cs_tag_PartyIdentification_Id + "_" + partes[0] + "_" + partes[1] + ".pdf";
                        DialogResult result = sfdDescargar.ShowDialog();
                        if (result == System.Windows.Forms.DialogResult.OK)
                        {
                            string fileName = sfdDescargar.FileName;
                            if (fileName.Substring(fileName.Length - 4) != ".pdf")
                            {
                                fileName = fileName + ".pdf";
                            }

                            bool procesado = false;
                            if (cabecera.Cs_pr_XML.Trim() != "")
                            {
                                procesado = RepresentacionImpresa.getRepresentacionImpresaRetencion(fileName, cabecera, cabecera.Cs_pr_XML, datosImpresa, pathImage, localDB);
                            }
                            else
                            {
                                //generar xml
                                string xml = string.Empty;

                                xml = new clsNegocioCERetention(localDB).cs_pxGenerarXMLAString(cabecera.Cs_pr_Retention_id);

                                procesado = RepresentacionImpresa.getRepresentacionImpresaRetencion(fileName, cabecera, xml, datosImpresa, pathImage, localDB);
                            }

                            if (procesado)
                            {
                                System.Diagnostics.Process.Start(fileName);
                            }
                            else
                            {
                                System.Windows.Forms.MessageBox.Show("Ha ocurrido un error al procesar la representacion impresa.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("No se encuentra la imagen del logo y/o la información para la representacion impresa. Verifique la existencia de la imagen 'logo.png' y el archivo 'informacionImpreso.txt'  en la ruta de instalación.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                clsBaseLog.cs_pxRegistarAdd("pdf repimpresa" + ex.ToString());
            }
        }
예제 #10
0
        public override string cs_pxGenerarXMLAString(string Id)
        {
            string archivo_xml = string.Empty;

            try
            {
                clsEntityRetention RetentionDocument = new clsEntityRetention(localbd).cs_fxObtenerUnoPorId(Id);
                List <clsEntityRetention_RetentionLine> RetentionLine = new clsEntityRetention_RetentionLine(localbd).cs_fxObtenerTodoPorCabeceraId(Id);

                string fila = "";
                string ei   = "    ";
                string ef   = "\n";

                fila += "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?>" + ef;
                fila += "<Retention " + ef + ef;
                #region Cabecera
                fila += ei + "xmlns=\"urn:sunat:names:specification:ubl:peru:schema:xsd:Retention-1\"" + ef;
                fila += ei + "xmlns:cac=\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\"" + ef;
                fila += ei + "xmlns:cbc=\"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\"" + ef;
                fila += ei + "xmlns:ccts=\"urn:un:unece:uncefact:documentation:2\"" + ef;
                fila += ei + "xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"" + ef;
                fila += ei + "xmlns:ext=\"urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2\"" + ef;
                fila += ei + "xmlns:qdt=\"urn:oasis:names:specification:ubl:schema:xsd:QualifiedDatatypes-2\"" + ef;
                fila += ei + "xmlns:sac=\"urn:sunat:names:specification:ubl:peru:schema:xsd:SunatAggregateComponents-1\"" + ef;
                fila += ei + "xmlns:udt=\"urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2\"" + ef;
                fila += ei + "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;
                #endregion
                fila += ei + "<cbc:UBLVersionID>2.0</cbc:UBLVersionID>" + ef;
                fila += ei + "<cbc:CustomizationID>1.0</cbc:CustomizationID>" + ef;

                #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;

                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
                fila += ei + "<cbc:ID>" + RetentionDocument.Cs_tag_Id + "</cbc:ID>" + ef;
                fila += ei + "<cbc:IssueDate>" + RetentionDocument.Cs_tag_IssueDate + "</cbc:IssueDate>" + ef;
                #region Datos del emisor del documento
                fila += ei + "<cac:AgentParty>" + ef;
                fila += ei + ei + "<cac:PartyIdentification>" + ef;
                fila += ei + ei + ei + "<cbc:ID schemeID=\"" + RetentionDocument.Cs_tag_PartyIdentificacion_SchemeId + "\">" + RetentionDocument.Cs_tag_PartyIdentification_Id + "</cbc:ID>" + ef;
                fila += ei + ei + "</cac:PartyIdentification>" + ef;

                if (RetentionDocument.Cs_tag_PartyName != "")
                {
                    fila += ei + ei + "<cac:PartyName>" + ef;
                    fila += ei + ei + ei + "<cbc:Name><![CDATA[" + RetentionDocument.Cs_tag_PartyName + "]]></cbc:Name>" + ef;
                    fila += ei + ei + "</cac:PartyName>" + ef;
                }

                if (RetentionDocument.Cs_tag_PostalAddress_Id != "" || RetentionDocument.Cs_tag_PostalAddress_StreetName != "" || RetentionDocument.Cs_tag_PostalAddress_CitySubdivisionName != "" || RetentionDocument.Cs_tag_PostalAddress_CityName != "" || RetentionDocument.Cs_tag_PostalAddress_CountrySubEntity != "" || RetentionDocument.Cs_tag_PostalAddress_District != "" || RetentionDocument.Cs_tag_PostalAddress_Country_IdentificationCode != "")
                {
                    fila += ei + ei + "<cac:PostalAddress>" + ef;
                    if (RetentionDocument.Cs_tag_PostalAddress_Id != "")
                    {
                        fila += ei + ei + ei + "<cbc:ID>" + RetentionDocument.Cs_tag_PostalAddress_Id + "</cbc:ID>" + ef;
                    }
                    if (RetentionDocument.Cs_tag_PostalAddress_StreetName != "")
                    {
                        fila += ei + ei + ei + "<cbc:StreetName>" + RetentionDocument.Cs_tag_PostalAddress_StreetName + "</cbc:StreetName>" + ef;
                    }
                    if (RetentionDocument.Cs_tag_PostalAddress_CitySubdivisionName != "")
                    {
                        fila += ei + ei + ei + "<cbc:CitySubdivisionName>" + RetentionDocument.Cs_tag_PostalAddress_CitySubdivisionName + "</cbc:CitySubdivisionName>" + ef;
                    }
                    if (RetentionDocument.Cs_tag_PostalAddress_CityName != "")
                    {
                        fila += ei + ei + ei + "<cbc:CityName>" + RetentionDocument.Cs_tag_PostalAddress_CityName + "</cbc:CityName>" + ef;
                    }
                    if (RetentionDocument.Cs_tag_PostalAddress_CountrySubEntity != "")
                    {
                        fila += ei + ei + ei + "<cbc:CountrySubentity>" + RetentionDocument.Cs_tag_PostalAddress_CountrySubEntity + "</cbc:CountrySubentity>" + ef;
                    }
                    if (RetentionDocument.Cs_tag_PostalAddress_District != "")
                    {
                        fila += ei + ei + ei + "<cbc:District>" + RetentionDocument.Cs_tag_PostalAddress_District + "</cbc:District>" + ef;
                    }

                    if (RetentionDocument.Cs_tag_PostalAddress_Country_IdentificationCode != "")
                    {
                        fila += ei + ei + ei + "<cac:Country>" + ef;
                        fila += ei + ei + ei + ei + "<cbc:IdentificationCode>" + RetentionDocument.Cs_tag_PostalAddress_Country_IdentificationCode + "</cbc:IdentificationCode>" + ef;
                        fila += ei + ei + ei + "</cac:Country>" + ef;
                    }
                    fila += ei + ei + "</cac:PostalAddress>" + ef;
                }

                fila += ei + ei + "<cac:PartyLegalEntity>" + ef;
                fila += ei + ei + ei + "<cbc:RegistrationName><![CDATA[" + RetentionDocument.Cs_tag_PartyLegalEntity_RegistrationName + "]]></cbc:RegistrationName>" + ef;
                fila += ei + ei + "</cac:PartyLegalEntity>" + ef;
                fila += ei + "</cac:AgentParty>" + ef;
                #endregion

                #region Info  Proveedor
                fila += ei + "<cac:ReceiverParty>" + ef;
                fila += ei + ei + "<cac:PartyIdentification>" + ef;
                fila += ei + ei + ei + "<cbc:ID schemeID=\"" + RetentionDocument.Cs_tag_ReceiveParty_PartyIdentification_SchemeId + "\">" + RetentionDocument.Cs_tag_ReceiveParty_PartyIdentification_Id + "</cbc:ID>" + ef;
                fila += ei + ei + "</cac:PartyIdentification>" + ef;
                if (RetentionDocument.Cs_tag_ReceiveParty_PartyName_Name != "")
                {
                    fila += ei + ei + "<cac:PartyName>" + ef;
                    fila += ei + ei + ei + "<cbc:Name><![CDATA[" + RetentionDocument.Cs_tag_ReceiveParty_PartyName_Name + "]]></cbc:Name>" + ef;
                    fila += ei + ei + "</cac:PartyName>" + ef;
                }

                if (RetentionDocument.Cs_tag_ReceiveParty_PostalAddress_Id != "" || RetentionDocument.Cs_tag_ReceiveParty_PostalAddress_StreetName != "" || RetentionDocument.Cs_tag_ReceiveParty_PostalAddress_CitySubdivisionName != "" || RetentionDocument.Cs_tag_ReceiveParty_PostalAddress_CityName != "" || RetentionDocument.Cs_tag_ReceiveParty_PostalAddress_CountrySubentity != "" || RetentionDocument.Cs_tag_ReceiveParty_PostalAddress_District != "" || RetentionDocument.Cs_tag_ReceiveParty_PostalAddress_Country_IdentificationCode != "")
                {
                    fila += ei + ei + "<cac:PostalAddress>" + ef;
                    if (RetentionDocument.Cs_tag_ReceiveParty_PostalAddress_Id != "")
                    {
                        fila += ei + ei + ei + "<cbc:ID>" + RetentionDocument.Cs_tag_ReceiveParty_PostalAddress_Id + "</cbc:ID>" + ef;
                    }
                    if (RetentionDocument.Cs_tag_ReceiveParty_PostalAddress_StreetName != "")
                    {
                        fila += ei + ei + ei + "<cbc:StreetName>" + RetentionDocument.Cs_tag_ReceiveParty_PostalAddress_StreetName + "</cbc:StreetName>" + ef;
                    }
                    if (RetentionDocument.Cs_tag_ReceiveParty_PostalAddress_CitySubdivisionName != "")
                    {
                        fila += ei + ei + ei + "<cbc:CitySubdivisionName>" + RetentionDocument.Cs_tag_ReceiveParty_PostalAddress_CitySubdivisionName + "</cbc:CitySubdivisionName>" + ef;
                    }
                    if (RetentionDocument.Cs_tag_ReceiveParty_PostalAddress_CityName != "")
                    {
                        fila += ei + ei + ei + "<cbc:CityName>" + RetentionDocument.Cs_tag_ReceiveParty_PostalAddress_CityName + "</cbc:CityName>" + ef;
                    }
                    if (RetentionDocument.Cs_tag_ReceiveParty_PostalAddress_CountrySubentity != "")
                    {
                        fila += ei + ei + ei + "<cbc:CountrySubentity>" + RetentionDocument.Cs_tag_ReceiveParty_PostalAddress_CountrySubentity + "</cbc:CountrySubentity>" + ef;
                    }
                    if (RetentionDocument.Cs_tag_ReceiveParty_PostalAddress_District != "")
                    {
                        fila += ei + ei + ei + "<cbc:District>" + RetentionDocument.Cs_tag_ReceiveParty_PostalAddress_District + "</cbc:District>" + ef;
                    }
                    if (RetentionDocument.Cs_tag_ReceiveParty_PostalAddress_Country_IdentificationCode != "")
                    {
                        fila += ei + ei + ei + "<cac:Country>" + ef;
                        fila += ei + ei + ei + ei + "<cbc:IdentificationCode>" + RetentionDocument.Cs_tag_ReceiveParty_PostalAddress_Country_IdentificationCode + "</cbc:IdentificationCode>" + ef;
                        fila += ei + ei + ei + "</cac:Country>" + ef;
                    }
                    fila += ei + ei + "</cac:PostalAddress>" + ef;
                }

                fila += ei + ei + "<cac:PartyLegalEntity>" + ef;
                fila += ei + ei + ei + "<cbc:RegistrationName><![CDATA[" + RetentionDocument.Cs_tag_ReceiveParty_PartyLegalEntity_RegistrationName + "]]></cbc:RegistrationName>" + ef;
                fila += ei + ei + "</cac:PartyLegalEntity>" + ef;
                fila += ei + "</cac:ReceiverParty>" + ef;
                #endregion

                fila += ei + "<sac:SUNATRetentionSystemCode>" + RetentionDocument.Cs_tag_SUNATRetentionSystemCode + "</sac:SUNATRetentionSystemCode>" + ef;
                fila += ei + "<sac:SUNATRetentionPercent>" + RetentionDocument.Cs_tag_SUNATRetentionPercent + "</sac:SUNATRetentionPercent>" + ef;

                //Cristhian|17/10/2017|FEI2-362

                /*Preparar un compilado Aparte, donde este cerrado la etiqueta cbc:Note eso con la finalidad de validar si SUNAT ya
                 * permite en BETA realizar este tipo de pruebas. Se decidio que, para este tipo de documento, esta etiqueta ya no se
                 * usa (es obsoleto)*/
                /*INICIO MODIFICAIóN*/
                //if (RetentionDocument.Cs_tag_Note != "")
                //{
                //    fila += ei + "<cbc:Note>" + RetentionDocument.Cs_tag_Note + "</cbc:Note>" + ef;
                //fila += ei + "<cbc:Note>"  + "</cbc:Note>" + ef;
                //}
                //else
                //{
                //    fila += ei + "<cbc:Note/>" + ef;
                //}
                /*FIN MODIFICACIóN*/

                fila += ei + "<cbc:TotalInvoiceAmount currencyID=\"" + RetentionDocument.Cs_tag_TotalInvoiceAmount_CurrencyId + "\">" + RetentionDocument.Cs_tag_TotalInvoiceAmount + "</cbc:TotalInvoiceAmount>" + ef;
                fila += ei + "<sac:SUNATTotalPaid currencyID=\"" + RetentionDocument.Cs_tag_TotalPaid_CurrencyId + "\">" + RetentionDocument.Cs_tag_TotalPaid + "</sac:SUNATTotalPaid>" + ef;

                #region Items
                if (RetentionLine != null && RetentionLine.Count > 0)
                {
                    try
                    {
                        foreach (var RetentionLine_item in RetentionLine)
                        {
                            fila += ei + "<sac:SUNATRetentionDocumentReference>" + ef;
                            fila += ei + ei + "<cbc:ID schemeID=\"" + RetentionLine_item.Cs_tag_Id_SchemeId + "\">" + RetentionLine_item.Cs_tag_Id + "</cbc:ID>" + ef;
                            fila += ei + ei + "<cbc:IssueDate>" + RetentionLine_item.Cs_tag_IssueDate + "</cbc:IssueDate>" + ef;
                            fila += ei + ei + "<cbc:TotalInvoiceAmount currencyID=\"" + RetentionLine_item.Cs_tag_TotalInvoiceAmount_CurrencyId + "\">" + RetentionLine_item.Cs_tag_TotalInvoiceAmount + "</cbc:TotalInvoiceAmount>" + ef;
                            fila += ei + ei + "<cac:Payment>" + ef;
                            //Cristhian|02/03/2018|CPD-853
                            /*Si es nota de credito no se debe enviar esta parte del codigo en el documento XML*/
                            /*NUEVO INICIO*/
                            /*Para detectar si es nota de credito en percepcion, el comercial enviara el caracter X*/
                            if (RetentionLine_item.Cs_tag_Payment_Id != "X")
                            {
                                /*Se añadira esta parte de codigo si esque el Cs_tag_Payment_Id es diferente de X */
                                fila += ei + ei + ei + "<cbc:ID>" + RetentionLine_item.Cs_tag_Payment_Id + "</cbc:ID>" + ef;
                                fila += ei + ei + ei + "<cbc:PaidAmount currencyID=\"" + RetentionLine_item.Cs_tag_Payment_PaidAmount_CurrencyId + "\">" + RetentionLine_item.Cs_tag_Payment_PaidAmount + "</cbc:PaidAmount>" + ef;
                                fila += ei + ei + ei + "<cbc:PaidDate>" + RetentionLine_item.Cs_tag_Payment_PaidDate + "</cbc:PaidDate>" + ef;
                            }
                            /*NUEVO FIN*/
                            fila += ei + ei + "</cac:Payment>" + ef;
                            fila += ei + ei + "<sac:SUNATRetentionInformation>" + ef;
                            fila += ei + ei + ei + "<sac:SUNATRetentionAmount currencyID=\"" + RetentionLine_item.Cs_tag_SUNATRetentionInformation_SUNATRetentionAmount_CurrencyId + "\">" + RetentionLine_item.Cs_tag_SUNATRetentionInformation_SUNATRetentionAmount + "</sac:SUNATRetentionAmount>" + ef;
                            fila += ei + ei + ei + "<sac:SUNATRetentionDate>" + RetentionLine_item.Cs_tag_SUNATRetentionInformation_SUNATRetentionDate + "</sac:SUNATRetentionDate>" + ef;
                            fila += ei + ei + ei + "<sac:SUNATNetTotalPaid currencyID=\"" + RetentionLine_item.Cs_tag_SUNATRetentionInformation_SUNATNetTotalPaid_CurrencyId + "\">" + RetentionLine_item.Cs_tag_SUNATRetentionInformation_SUNATNetTotalPaid + "</sac:SUNATNetTotalPaid>" + ef;

                            //Tipo de Cambio -  Moneda
                            if (RetentionLine_item.Cs_tag_SUNATRetentionInformation_ExchangeRate_CalculationRate != "" || RetentionLine_item.Cs_tag_SUNATRetentionInformation_ExchangeRate_Date != "" || RetentionLine_item.Cs_tag_SUNATRetentionInformation_ExchangeRate_SourceCurrencyCode != "" || RetentionLine_item.Cs_tag_SUNATRetentionInformation_ExchangeRate_TargetCurrencyCode != "")
                            {
                                fila += ei + ei + ei + "<cac:ExchangeRate>" + ef;
                                if (RetentionLine_item.Cs_tag_SUNATRetentionInformation_ExchangeRate_SourceCurrencyCode != "")
                                {
                                    fila += ei + ei + ei + ei + "<cbc:SourceCurrencyCode>" + RetentionLine_item.Cs_tag_SUNATRetentionInformation_ExchangeRate_SourceCurrencyCode + "</cbc:SourceCurrencyCode>" + ef;
                                }
                                if (RetentionLine_item.Cs_tag_SUNATRetentionInformation_ExchangeRate_TargetCurrencyCode != "")
                                {
                                    fila += ei + ei + ei + ei + "<cbc:TargetCurrencyCode>" + RetentionLine_item.Cs_tag_SUNATRetentionInformation_ExchangeRate_TargetCurrencyCode + "</cbc:TargetCurrencyCode>" + ef;
                                }
                                if (RetentionLine_item.Cs_tag_SUNATRetentionInformation_ExchangeRate_CalculationRate != "")
                                {
                                    fila += ei + ei + ei + ei + "<cbc:CalculationRate>" + RetentionLine_item.Cs_tag_SUNATRetentionInformation_ExchangeRate_CalculationRate + "</cbc:CalculationRate>" + ef;
                                }
                                if (RetentionLine_item.Cs_tag_SUNATRetentionInformation_ExchangeRate_Date != "")
                                {
                                    fila += ei + ei + ei + ei + "<cbc:Date>" + RetentionLine_item.Cs_tag_SUNATRetentionInformation_ExchangeRate_Date + "</cbc:Date>" + ef;
                                }

                                fila += ei + ei + ei + "</cac:ExchangeRate>" + ef;
                            }
                            //////////
                            fila += ei + ei + "</sac:SUNATRetentionInformation>" + ef;
                            fila += ei + "</sac:SUNATRetentionDocumentReference>" + ef;
                        }
                    }
                    catch (Exception ex)
                    {
                        clsBaseLog.cs_pxRegistarAdd("Error al crear detalle de Retencion" + ex.ToString());
                    }
                }

                #endregion
                fila += "</Retention>" + ef;

                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("clsNegocioCERetention generarxml" + ex.ToString());
            }
            return(archivo_xml);
        }
        /*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 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);
        }
예제 #13
0
        private void btnEnviars_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 1; i <= 5; i++)
            {
                clsEntityRetention per = new clsEntityRetention(localDB);
                per.Cs_pr_Retention_id = Guid.NewGuid().ToString();
                per.Cs_tag_Id          = "R001-123" + i;
                per.Cs_tag_IssueDate   = "2017-03-17";
                per.Cs_tag_PartyIdentificacion_SchemeId = "6";
                per.Cs_tag_PartyIdentification_Id       = "20100113612";
                per.Cs_tag_PartyName                                             = "Kg laboratorios";
                per.Cs_tag_PostalAddress_Id                                      = "150114";
                per.Cs_tag_PostalAddress_StreetName                              = "olivos";
                per.Cs_tag_PostalAddress_CitySubdivisionName                     = "Urb santa felicia";
                per.Cs_tag_PostalAddress_CityName                                = "Lima";
                per.Cs_tag_PostalAddress_CountrySubEntity                        = "Lima";
                per.Cs_tag_PostalAddress_District                                = "La molina";
                per.Cs_tag_PostalAddress_Country_IdentificationCode              = "PE";
                per.Cs_tag_PartyLegalEntity_RegistrationName                     = "KG Asociados Sac";
                per.Cs_tag_ReceiveParty_PartyIdentification_SchemeId             = "6";
                per.Cs_tag_ReceiveParty_PartyIdentification_Id                   = "20546772439";
                per.Cs_tag_ReceiveParty_PartyName_Name                           = "Cia de consultoria";
                per.Cs_tag_ReceiveParty_PostalAddress_Id                         = "150122";
                per.Cs_tag_ReceiveParty_PostalAddress_StreetName                 = "Olaya";
                per.Cs_tag_ReceiveParty_PostalAddress_CitySubdivisionName        = "URB santa Rosa";
                per.Cs_tag_ReceiveParty_PostalAddress_CityName                   = "Lima";
                per.Cs_tag_ReceiveParty_PostalAddress_CountrySubentity           = "Lima";
                per.Cs_tag_ReceiveParty_PostalAddress_District                   = "Miaflores";
                per.Cs_tag_ReceiveParty_PostalAddress_Country_IdentificationCode = "PE";
                per.Cs_tag_ReceiveParty_PartyLegalEntity_RegistrationName        = "Cia de consultoria";
                per.Cs_tag_SUNATRetentionSystemCode                              = "01";
                per.Cs_tag_SUNATRetentionPercent                                 = "3.00";
                per.Cs_tag_Note = "nota";
                per.Cs_tag_TotalInvoiceAmount_CurrencyId = "PEN";
                per.Cs_tag_TotalInvoiceAmount            = "35.40";
                per.Cs_tag_TotalPaid_CurrencyId          = "PEN";
                per.Cs_tag_TotalPaid  = "1144.60";
                per.Cs_pr_EstadoSCC   = "2";
                per.Cs_pr_EstadoSUNAT = "2";
                string idRetorno = per.cs_pxInsertar(true, false);

                clsEntityRetention_RetentionLine linea = new clsEntityRetention_RetentionLine(localDB);
                linea.Cs_pr_Retention_RetentionLine_Id = Guid.NewGuid().ToString();
                linea.Cs_pr_Retention_Id = idRetorno;
                linea.Cs_tag_Id_SchemeId = "01";
                linea.Cs_tag_Id          = "F001-540" + i;
                linea.Cs_tag_IssueDate   = "2016-09-15";
                linea.Cs_tag_TotalInvoiceAmount_CurrencyId = "USD";
                linea.Cs_tag_TotalInvoiceAmount            = "1180.00";
                linea.Cs_tag_Payment_PaidDate = "2016-09-15";
                linea.Cs_tag_Payment_Id       = "1";
                linea.Cs_tag_Payment_PaidAmount_CurrencyId = "USD";
                linea.Cs_tag_Payment_PaidAmount            = "1180.00";
                linea.Cs_tag_SUNATRetentionInformation_SUNATRetentionAmount_CurrencyId = "PEN";
                linea.Cs_tag_SUNATRetentionInformation_SUNATRetentionAmount            = "35.40";
                linea.Cs_tag_SUNATRetentionInformation_SUNATRetentionDate              = "2016-09-15";
                linea.Cs_tag_SUNATRetentionInformation_SUNATNetTotalPaid_CurrencyId    = "PEN";
                linea.Cs_tag_SUNATRetentionInformation_SUNATNetTotalPaid               = "1140.60";
                linea.Cs_tag_SUNATRetentionInformation_ExchangeRate_SourceCurrencyCode = "USD";
                linea.Cs_tag_SUNATRetentionInformation_ExchangeRate_TargetCurrencyCode = "PEN";
                linea.Cs_tag_SUNATRetentionInformation_ExchangeRate_CalculationRate    = "3.00";
                linea.Cs_tag_SUNATRetentionInformation_ExchangeRate_Date               = "2016-09-15";
                linea.cs_pxInsertar(true, true);
            }


            /*clsEntityRetention ret = new clsEntityRetention(localDB).cs_fxObtenerUnoPorId(idRetorno);
             * System.Windows.Forms.MessageBox.Show(ret.Cs_pr_Retention_id);*/
        }