using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.ServiceModel; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Extensiones; using static Extensiones.ModExtensiones; public partial class Ventas_RepCancelacionesPorRespuesta : ClsPaginas { private DataTable DtVentas { get { return (ViewState["DtVentas"] == null) ? null : (DataTable)ViewState["DtVentas"]; } set { ViewState["DtVentas"] = value; } } private int CveVenta { get { return (ViewState["CveVenta"] == null) ? -1 : ViewState["CveVenta"].ToString().ToEntero(); } set { ViewState["CveVenta"] = value; } } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { CargaDatos(); } } private void CargaDatos() { if (Request["CveVenta"] != null) { this.CveVenta = Request["CveVenta"].ToString().ToEntero(); } var ObjVentas = new ClsVentas(); if (ObjVentas.GetVentas(UsuarioActual.CveEmpresa, "-1", "-1", -1, "-1", -1, -1, -2, -1, "-1", "-1", "-1", CveUsuarioConsulta: UsuarioActual.CveUsuario)) { if (CveVenta > 0) { DtVentas = ObjVentas.DtResultados.FiltraParametros($"CveVenta={CveVenta}"); } else { DtVentas = ObjVentas.DtResultados.Copy(); } } ObjVentas.Dispose(); GvDatos.DataSource = DtVentas.FiltraParametros("CveEstatusFactura = 20 AND CveEstatusRefacturacion = 0"); var DtRefacturar = DtVentas.FiltraParametros("CveEstatusRefacturacion IN (1,3)"); if (DtRefacturar.Rows.Count > 0) { DivRefacturar.Visible = true; GvRefacturaciones.DataSource = DtRefacturar; GvRefacturaciones.DataBind(); } GvDatos.DataBind(); UPDatos.Update(); } protected void BtnValidar_Click(object sender, EventArgs e) { GridViewRow GvRow = (GridViewRow)(((LinkButton)sender).NamingContainer); int CveVenta = GvRow.DataKey("CveVenta").ToEntero(); int CveCliente = GvRow.DataKey("CveCliente").ToEntero(); string Total = GvRow.DataKey("Total"); string SubTotal = GvRow.DataKey("SubTotal"); string Uuid = GvRow.DataKey("FolioFiscal"); string RFCCliente = GvRow.DataKey("RFCCliente"); string Folio = GvRow.DataKey("Folio"); string TipoDocto = GvRow.DataKey("TipoDocto"); string Nombre = GvRow.DataKey("Nombre"); if (CveVenta > 0) { Alert(VerificarVigenciaSAT(CveVenta, CveCliente, Folio, TipoDocto, Uuid, UsuarioActual.Empresa.RFC, RFCCliente, Total)); } CargaDatos(); } protected void BtnValidarRefacturacion_Click(object sender, EventArgs e) { GridViewRow GvRow = (GridViewRow)(((LinkButton)sender).NamingContainer); int CveVenta = GvRow.DataKey("CveVenta").ToEntero(); int CveCliente = GvRow.DataKey("CveCliente").ToEntero(); string Total = GvRow.DataKey("Total"); string SubTotal = GvRow.DataKey("SubTotal"); string Uuid = GvRow.DataKey("FolioFiscal"); string RFCCliente = GvRow.DataKey("RFCCliente"); string Folio = GvRow.DataKey("Folio"); string TipoDocto = GvRow.DataKey("TipoDocto"); string Nombre = GvRow.DataKey("Nombre"); if (CveVenta > 0) { Alert(VerificarVigenciaSAT(CveVenta, CveCliente, Folio, TipoDocto, Uuid, UsuarioActual.Empresa.RFC, RFCCliente, Total, true)); } CargaDatos(); } private string VerificarVigenciaSAT(int CveVenta, int CveCliente, string Folio, string TipoDocto, string uuid, string emisor, string receptor, string total, bool EsRefacturacion = false) { var sb = new StringBuilder(); var CancelacionAcuse = ""; var CancelacionFecha = DateTime.Now; int CveEstatus = 4; try { var resp = Timbrado.VerificarVigenciaSAT(uuid, UsuarioActual.Empresa.RFC, receptor, total, UsuarioActual.Empresa.FacturaProduccion); if (resp != null) { if (resp.Estado == null) { sb.Append("No se pudo comprobar el estado de la factura. El servicio del sat no esta disponible"); return sb.ToString(); } sb.AppendFormat("Folio Fiscal: {0}
", uuid); sb.AppendFormat("Codigo Estado: {0}
", resp.CodigoEstatus); sb.AppendFormat("Estado: {0}
", resp.Estado); sb.AppendFormat("Es Cancelable: {0}
", string.IsNullOrEmpty(resp.EsCancelable) ? "Desconocido" : resp.EsCancelable); sb.AppendFormat("Estatus de Cancelación: {0}

", string.IsNullOrEmpty(resp.EsCancelable) ? "Desconocido" : resp.EstatusCancelacion); if (!UsuarioActual.Empresa.FacturaProduccion && (string.IsNullOrEmpty(uuid) || uuid.Contains("test"))) { var FueCancelado = CancelarDocumento(CveVenta, CveEstatus, CveCliente, Folio, uuid, CancelacionAcuse, CancelacionFecha, TipoDocto, total.ToDouble(), UsuarioActual.Empresa.CvePAC).Mensaje; sb.AppendFormat("{0}
", FueCancelado); if (CveEstatus.Contiene(4, 5) && EsRefacturacion) { Response.Redirect(string.Format("Ventas.aspx?CveDevolucion={0}&NuevaFactura=1", CveVenta)); } } else { if ((resp.EsCancelable.ToUpper() == "NO CANCELABLE")) { sb.Append("Esta factura no es cancelable."); return sb.ToString(); } if (resp.Estado.ToUpper().Trim() == "CANCELADO" || resp.EstatusCancelacion.ToUpper() == "PLAZO VENCIDO") { CveEstatus = 5; var solicitud = new WSGF.Service1SoapClient(); var acuse = solicitud.GetAcuse(emisor, "rene.molina@adsistemas.mx", "rene2018", uuid); if (acuse.Estado == 0) { var xmlAcuse = new System.Xml.XmlDocument(); xmlAcuse.LoadXml(DecodeBase64(acuse.CfdiB64)); CancelacionAcuse = xmlAcuse.GetElementsByTagName("SignatureValue")[0].InnerText; CancelacionFecha = xmlAcuse.SelectSingleNode("Acuse").Attributes["Fecha"].Value.ToDate(); } var FueCancelado = CancelarDocumento(CveVenta, CveEstatus, CveCliente, Folio, uuid, CancelacionAcuse, CancelacionFecha, TipoDocto, total.ToDouble(), UsuarioActual.Empresa.CvePAC, EsRefacturacion: EsRefacturacion).Mensaje; sb.AppendFormat("{0}
", FueCancelado); if (CveEstatus.Contiene(4, 5) && EsRefacturacion) { Response.Redirect(string.Format("Ventas.aspx?CveDevolucion={0}&NuevaFactura=1", CveVenta)); } } else if (resp.EstatusCancelacion.ToUpper() == "SOLICITUD RECHAZADA") { //ASIGNAMOS ESTATUS EMITIDA CveEstatus = 3; var ObjVentas = new ClsVentas(); if (ObjVentas.UpdateEstatusVenta(CveVenta, CveEstatus, UsuarioActual.CveEmpresa)) { sb.Append("El estatus de la factura fue cambiado a 'Emitida'."); } else { sb.Append("Ocurrió un error al cambiar el estatus de la factura."); } ObjVentas.Dispose(); } } } else { sb.Append("No se pudo comprobar la vigencia de la factura."); return sb.ToString(); } } catch (Exception ex) { sb.Append("Error al consumir el servicio: " + ex.Message); return sb.ToString(); } return sb.ToString(); } private Modelos.Factura.MCancelacionVentaMensaje CancelarDocumento(int CveVenta, int CveEstatus, int CveCliente, string Folio, string FolioFiscal, string CancelacionAcuse, DateTime CancelacionFecha, string TipoComprobante, double Total, int CvePACCancelacion, bool EsRefacturacion = false) { Modelos.Factura.MCancelacionVentaMensaje retorno = null; var factura = new Modelos.Factura(UsuarioActual, CveVenta, UsuarioActual.CveEmpresa); if (EsRefacturacion) { retorno = factura.CancelarPorRefacturacion(); } else { retorno = factura.EjecutarCancelacionPendiente(CveEstatus, CancelacionFecha, CancelacionAcuse); } return retorno; } //private int GenerarPolizaAC(ClsContPAQi ObjAC, int CveVenta, string Folio, int CveCliente, string TipoComprobante, DateTime Fecha, bool CancelacionIngreso = false) //{ // int CtaCliente = 0; // int OrdenPago = 0; // string NombreCliente = ""; // var ObjClientes = new ClsClientes(); // if (ObjClientes.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa)) // { // CtaCliente = ObjClientes.IdCtaContClientes; // NombreCliente = ObjClientes.NombreComercial; // } // ObjClientes.Dispose(); // var ObjVentas = new ClsVentas(); // if (ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa)) // { // if (ObjVentas.DtResultados.Rows.Count > 0) // { // OrdenPago = ObjVentas.DtResultados.Rows[0]["Num3"].ToEntero(); // } // } // int Retorno = 0; // int IDPoliza = 0; // bool ErrorAC = false; // string Concepto = string.Format("GD {0}", NombreCliente); // int Paridad = 1; // bool TipoMovto = false; // if (CancelacionIngreso) // { // Concepto = string.Format("Cancelación GD {0}", NombreCliente); // Paridad = -1; // TipoMovto = true; // } // var TipoPoliza = TipoComprobante.Contiene("OP", "Com") ? 3 : 1; // DataRow dr = null; // int CtaISSSTESON = 643; // int CtaISPT = 1745; // var AC = new ClsAC(); // //var ObjAC = new ClsContPAQi(UsuarioActual.Empresa); // //ObjAC.IniciaTransacSQL(); // IDPoliza = ObjAC.AddPoliza(TipoPoliza, Concepto, 0, 0, UsuarioActual.CveUsuario, Fecha); // if (IDPoliza > 0) // { // if (TipoComprobante == "OP") // { // //Orden de PAGO // if (OrdenPago == 1) // { // //ISSSTESON // if (ObjAC.AddMovimiento(IDPoliza, CtaCliente, false, (Paridad * 0d), "", Concepto, 0, Fecha, "")) // { // if (!ObjAC.AddMovimiento(IDPoliza, CtaISSSTESON, true, (Paridad * 0d), "", Concepto, 0, Fecha, "")) // { // ErrorAC = true; // } // } // else // { // ErrorAC = true; // } // } // else // { // //ISPT // if (ObjAC.AddMovimiento(IDPoliza, CtaCliente, false, (Paridad * 0d), "", Concepto, 0, Fecha, "")) // { // if (!ObjAC.AddMovimiento(IDPoliza, CtaISPT, true, (Paridad * 0d), "", Concepto, 0, Fecha, "")) // { // ErrorAC = true; // } // } // else // { // ErrorAC = true; // } // } // } // else // { // //NORMAL // DataTable Detalles = null; // DataTable DTPresupuestoIngresos = null; // if (ObjVentas.GetVentaDetalle(CveVenta)) // { // Detalles = ObjVentas.DtResultados.Copy(); // } // if (AC.GetPresupuestoIngresos(-1, DateTime.Now.Year, true, UsuarioActual.CveEmpresa)) // { // DTPresupuestoIngresos = AC.DtResultados.Copy(); // } // if (Detalles != null && DTPresupuestoIngresos != null) // { // var query = from gvr in Detalles.AsEnumerable() // group gvr by gvr["CvePresupuestoIngreso"].ToString().ToEntero() into g // select new { TotalImporte = g.Sum((x) => x["Total"].ToString().ToDouble()), CvePresupuestoIngreso = g.Key }; // foreach (var item in query) // { // dr = DTPresupuestoIngresos.FiltroPrimero(string.Format("CvePresupuestoIngreso = {0}", item.CvePresupuestoIngreso)); // if (dr != null) // { // Concepto = string.Format("{0} - {1}: {2}", NombreCliente, TipoComprobante, Folio); // if (ObjAC.AddMovimiento(IDPoliza, dr["IdCuentaPorEjecutar"].ToString().ToEntero(), false, (Paridad * item.TotalImporte), "", Concepto, 0, Fecha, "")) // { // if (ObjAC.AddMovimiento(IDPoliza, dr["IdCuentaDevengado"].ToString().ToEntero(), true, (Paridad * item.TotalImporte), "", Concepto, 0, Fecha, "")) // { // // CARGO la deuda del cliente // if (ObjAC.AddMovimiento(IDPoliza, CtaCliente, TipoMovto, item.TotalImporte, "", Concepto, 0, Fecha, "")) // { // // abono, // if (!ObjAC.AddMovimiento(IDPoliza, dr["IdCuentaMatriz"].ToString().ToEntero(), !TipoMovto, item.TotalImporte, "", Concepto, 0, Fecha, "")) // { // ErrorAC = true; // break; // } // } // else // { // ErrorAC = true; // break; // } // } // else // { // ErrorAC = true; // break; // } // } // else // { // ErrorAC = true; // break; // } // } // else // { // ErrorAC = true; // break; // } // } // } // else // { // ErrorAC = true; // } // } // } // else // { // ErrorAC = true; // } // if (!ErrorAC) // { // ObjAC.AjustaPoliza(IDPoliza); // Retorno = IDPoliza; // } // else // { // Alert("Error al Agregar la Póliza de AC.", TipoMensaje.MsgError); // } // AC.Dispose(); // ObjVentas.Dispose(); // return Retorno; //} private string DecodeBase64(string strXMLCodificado) { try { byte[] decbuff = Convert.FromBase64String(strXMLCodificado); return System.Text.Encoding.UTF8.GetString(decbuff); } catch { return ""; } } protected void LnkValidar_Click(object sender, EventArgs e) { if (DtVentas != null) { var sb = new StringBuilder(); foreach (DataRow Row in DtVentas.Rows) { int CveVenta = Row["CveVenta"].ToEntero(); string Total = Row["Total"].ToString(); string SubTotal = Row["SubTotal"].ToString(); string Uuid = Row["FolioFiscal"].ToString(); string RFCCliente = Row["RFCCliente"].ToString(); string Folio = Row["Folio"].ToString(); string TipoDocto = Row["TipoDocto"].ToString(); string Nombre = Row["Nombre"].ToString(); int CveCliente = Row["CveCliente"].ToEntero(); if (CveVenta > 0) { sb.AppendFormat("{0}
", VerificarVigenciaSAT(CveVenta, CveCliente, Folio, TipoDocto, Uuid, UsuarioActual.Empresa.RFC, RFCCliente, SubTotal)); } } Alert(sb.ToString()); } CargaDatos(); } protected void GvDatos_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { if (e.Row.DBCampo("PuedeRefacturar").ToString().ToEntero() == 0) { e.Row.Cells[8].Text = ""; } } } }