Files
SIG/Ventas/RepConciliacionEmitidosSat.aspx.cs
JORGE LUIS CAUDILLO ESPARZA 0ca4b4fc8c
2020-01-14 15:26:51 -07:00

801 lines
36 KiB
C#

using Microsoft.Reporting.WebForms;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using Extensiones;
using System.Data;
using System.Text;
using ADSistemaLibrary.SatXml;
//using ADS_CFDI_SAT;
public partial class Ventas_RepConciliacionEmitidosSat : ClsPaginas
{
#region "Propiedades"
const string rqFechaInicio = "FechaInicio";
const string rqFechaFin = "FechaFin";
const string rqRegistroEn = "RegistroEn";
public string RfechaI
{
get
{
return ViewState["RfechaI"].ToString();
}
set { ViewState["RfechaI"] = value; }
}
public string RfechaF
{
get
{
return ViewState["RfechaF"].ToString();
}
set { ViewState["RfechaF"] = value; }
}
public object CurrentRow
{
get
{
return ViewState["CurrentRow"];
}
set { ViewState["CurrentRow"] = value; }
}
public int RegistroEn
{
get
{
if (ViewState["RegistroEn"] != null)
{
return ViewState["RegistroEn"].ToString().ToEntero();
}
else
{
return 0;
}
}
set { ViewState["RegistroEn"] = value; }
}
private StringBuilder strErrores;
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string path;
if (Request["op"] != null && Request["op"].ToString().Length > 0)
{
try
{
if (System.IO.File.Exists((path = string.Format("{0}\\{1}", UsuarioActual.Empresa.Ruta.Trim(), Extensiones.ModExtensiones.Decripta(Request["op"].ToString()).Trim()).Replace("/", "\\"))))
{
System.IO.FileInfo archivo = new System.IO.FileInfo(path);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ContentType = "text/plain";
HttpContext.Current.Response.AppendHeader("Content-disposition", string.Format("attachment; filename={0}", archivo.Name));
HttpContext.Current.Response.AddHeader("Content-Length", archivo.Length.ToString());
HttpContext.Current.Response.TransmitFile(path);
HttpContext.Current.Response.End();
}
else
{
RegistraScript("window.close()");
}
}
catch (Exception ex)
{
Extensiones.ModExtensiones.GuardaLog(ex.ToString());
RegistraScript("window.close()");
}
}
fillrequestfields();
DdlSubProyectoDatos.DataSource = get_GlobalDTSubProyectosUsuarios(UsuarioActual.CveUsuario, -1, UsuarioActual.CveEmpresa, -1, 1).FiltraParametros("EsSucursal = True ");
DdlSubProyectoDatos.DataBind();
DdlClasificacion.DataSource = get_GlobalDTClasificaciones(UsuarioActual.CveEmpresa, UsoClasificacion: 1).FiltraParametros(" Codigo = '' OR Codigo IS NULL ", Orderby: "Clasificacion");
DdlClasificacion.DataBind();
CargaConciliacionemitidasSATGet();
int CveClasificacion = DdlClasificacion.SelectedValue.ToEntero();
if (UsuarioActual.Empresa.Funcionalidad(141).ToString() == "1")
{
DdlPS.setEsWebService(true);
DdlPS.ddlWS.Attributes.Add("data-cveclasificacion", CveClasificacion.ToString());
DdlPS.ddlWS.Attributes.Add("data-pagina", "ventas/ventas");
DdlPS.ddlWS.Attributes.Add("data-Estatus", "1");
}
else
{
DdlPS.setEsWebService(false);
DdlPS.ddl.DataSource = get_GlobalDTPSSimplificado(UsuarioActual.CveEmpresa, CveClasificacion: CveClasificacion, Estatus: 1, AplicaParaVenta: 1);
DdlPS.ddl.DataBind();
}
}
}
private void downfile(string path)
{
}
public void fillrequestfields()
{
DateTime fecha;
DateTime fechaInicio = DateTime.Now;
DateTime fechaFin = DateTime.Now;
RegistroEn = -1;
if (fechaInicio.Day < 5) { fechaInicio = fechaInicio.AddMonths(-1); }
fechaInicio = fechaInicio.AddDays(1 - fechaInicio.Day);
fechaFin = fechaInicio.AddYears(1).AddDays(-1);
if (Request[rqRegistroEn] != null) { RegistroEn = Request[rqRegistroEn].ToEntero(); }
if (Request[rqFechaInicio] != null) { DateTime.TryParse(Request[rqFechaInicio], out fecha); fechaInicio = fecha.Year > 1900 ? fecha : fechaInicio; }
if (Request[rqFechaFin] != null) { DateTime.TryParse(Request[rqFechaFin], out fecha); fechaFin = fecha.Year > 1900 ? fecha : fechaFin; }
txtFechaI.Text = string.Format("{0:dd/MM/yyyy}", fechaInicio);
txtFechaF.Text = string.Format("{0:dd/MM/yyyy}", fechaFin);
ddlRegistroen.SelectedValueExist(RegistroEn);
}
protected void CargaRepConciliacionSatGET()
{
string RtipoDocto;
RtipoDocto = "I";
RfechaI = txtFechaI.Text.Length > 0 ? txtFechaI.Text.ToDateTime().ToString("yyyy/MM/dd") : "";
RfechaF = txtFechaF.Text.Length > 0 ? string.Format("{0:yyyy/MM/dd}", txtFechaF.Text.ToDateTime()) : "";
RegistroEn = ddlRegistroen.SelectedValue.ToEntero();
using (ClsGenerales ObjRepC = new ClsGenerales())
{
if (ObjRepC.RepConciliacionSatDetalleGET(UsuarioActual.CveEmpresa, RtipoDocto, RfechaI, RfechaF, RegistroEn))
{
Ltlsinregistrar.Text = $"{ObjRepC.DtResultados.COUNT("FolioFiscal", "CveVenta IS NULL")}";
ltlTotal.Text = $"{ObjRepC.DtResultados.Rows.Count}";
}
GVConciliacionemitidasSAT.DataSource = ObjRepC.DtResultados;
ObjRepC.Dispose();
}
GVConciliacionemitidasSAT.DataBind();
UpDatosReporte.Update();
}
protected void CargaConciliacionemitidasSATGet()
{
CargaRepConciliacionSatGET();
//ClsVentas ObjV = new ClsVentas();
//ObjV.ConciliacionemitidasSATGet(UsuarioActual.CveEmpresa);
//GVConciliacionemitidasSAT.DataSource = ObjV.DtResultados.FiltraParametros("", "CveVenta");
//Ltlsinregistrar.Text = $"{ObjV.DtResultados.COUNT("FolioFiscal","CveVenta IS NULL")}";
//ltlTotal.Text = $"{ObjV.DtResultados.Rows.Count}";
//ObjV.Dispose();
//GVConciliacionemitidasSAT.DataBind();
//UpDatosReporte.Update();
}
private void registrarventa(GridViewRow gvrow)
{
{
string ruta = string.Format("{0}\\{1}", UsuarioActual.Empresa.Ruta.Trim(), gvrow.DataKey("RutaXml").Trim()).Replace("/", "\\"); //gvrow.DataKey("RutaXml");
//Alert(ruta);
//return false;
strErrores = new StringBuilder();
XmlSatCFDI objxml = null;
Modelos.Factura objfact = null;
bool continuar = true;
objxml = XmlSatCFDI.readXML(ruta);
continuar = continuar && (objxml != null);
if (continuar)
{
objfact = GetFacturaFromXML(objxml);
}
continuar = continuar && (objfact != null);
if (continuar)
{
// Dim As New (ObjVentas.IniciaTransacSQL())
// Dim As = Nothing
// Dim MensajeAlert = New StringBuilder
ClsVentas ObjVentas = new ClsVentas();
ClsInventarios ObjInventario = new ClsInventarios(ObjVentas.IniciaTransacSQL());
ClsContabilidad ObjConta = new ClsContabilidad(ObjVentas.IniciaTransacSQL());
ClsContratos ObjContr = new ClsContratos(ObjVentas.IniciaTransacSQL());
ClsOS ObjOS = new ClsOS(ObjVentas.IniciaTransacSQL());
ClsBancos ObjBancos = new ClsBancos(ObjVentas.IniciaTransacSQL());
ClsClientes ObjClientes = new ClsClientes(ObjVentas.IniciaTransacSQL());
ClsOIEventos ObjEventos = new ClsOIEventos(ObjVentas.IniciaTransacSQL());
ClsCGame ObjCGame = new ClsCGame(ObjVentas.IniciaTransacSQL());
ClsEdocumentacion ObjDocCliente = new ClsEdocumentacion(ObjVentas.IniciaTransacSQL());
ClsAcumuladores ObjAcum = new ClsAcumuladores(ObjVentas.IniciaTransacSQL());
ClsContPAQi ObjContPaq = null;
//StringBuilder MensajeAlert = new StringBuilder() ;
DataTable DtDetalle = objfact.DtDetalle;
try
{
objfact.GuardarVenta(ref objfact, ref ObjVentas, ref ObjConta, ref ObjInventario, ref ObjContr, ref DtDetalle, objfact.CveNCaVincular, ref ObjContPaq, ref ObjBancos, ref ObjOS, ref ObjEventos, ref ObjCGame, ref ObjClientes, ObjAcum: ObjAcum);
}
catch (Exception e)
{
objfact.CveVenta = -1;
e.ToString().GuardaLog();
strErrores.AppendLine("<br/>");
strErrores.AppendLine(e.ToString());
}
if (ObjVentas.UpdateEstatusFactura(3, objxml.complemento.UUID, "", DateTime.ParseExact(objxml.comprobante.Fecha.Replace("T", " "), "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture), ObjVentas.CveVenta, CvePAC: 4))
if (objfact.CveVenta > 0 && objfact.ErrorList.Count == 0)
{
ObjVentas.Commit();
}
else
{
foreach (string item in objfact.ErrorList)
{
strErrores.AppendLine("<br/>");
strErrores.AppendLine(item);
}
objfact.CveVenta = -1;
ObjVentas.RollBack();
}
ObjVentas.Dispose();
ObjConta.Dispose();
ObjInventario.Dispose();
ObjCGame.Dispose();
ObjContr.Dispose();
ObjDocCliente.Dispose();
ObjClientes.Dispose();
ObjAcum.Dispose();
}
if (objfact != null && objfact.CveVenta > 0)
{
CargaConciliacionemitidasSATGet();
Alert($"se ha agregado la factura correctamente.<br/> <a href=\"/Ventas/Ventas.aspx?CveVenta={objfact.CveVenta}\" > Ver Factura </a>", ModExtensiones.TipoMensaje.ToastInformacion, timeout: 25);
}
else { continuar = false; }
if (!continuar)
{
Alert($"no se pudo agregar la factura {strErrores.ToString()}", ModExtensiones.TipoMensaje.MsgAdvertencia);
}
}
}
protected void LnkRegistrar_Click(object sender, EventArgs e)
{
GridViewRow gvrow = (GridViewRow)(((LinkButton)sender).NamingContainer);
CurrentRow = gvrow;
RegistraScript("$('#DModalDefaults').modal();");
//registrarventa(gvrow);
//string ruta = gvrow.DataKey("RutaXml");
//strErrores = new StringBuilder();
//XmlSatCFDI objxml = null;
//Modelos.Factura objfact = null;
//bool continuar = true;
//objxml = XmlSatCFDI.readXML(ruta);
//continuar = continuar && (objxml != null);
//if (continuar)
//{
// objfact = GetFacturaFromXML(objxml);
//}
//continuar = continuar && (objfact != null);
//if (continuar)
//{
// // Dim As New (ObjVentas.IniciaTransacSQL())
// // Dim As = Nothing
// // Dim MensajeAlert = New StringBuilder
// ClsVentas ObjVentas = new ClsVentas();
// ClsInventarios ObjInventario = new ClsInventarios(ObjVentas.IniciaTransacSQL());
// ClsContabilidad ObjConta = new ClsContabilidad(ObjVentas.IniciaTransacSQL());
// ClsContratos ObjContr = new ClsContratos(ObjVentas.IniciaTransacSQL());
// ClsOS ObjOS = new ClsOS(ObjVentas.IniciaTransacSQL());
// ClsBancos ObjBancos = new ClsBancos(ObjVentas.IniciaTransacSQL());
// ClsClientes ObjClientes = new ClsClientes(ObjVentas.IniciaTransacSQL());
// ClsOIEventos ObjEventos = new ClsOIEventos(ObjVentas.IniciaTransacSQL());
// ClsCGame ObjCGame = new ClsCGame(ObjVentas.IniciaTransacSQL());
// ClsEdocumentacion ObjDocCliente = new ClsEdocumentacion(ObjVentas.IniciaTransacSQL());
// ClsAcumuladores ObjAcum = new ClsAcumuladores(ObjVentas.IniciaTransacSQL());
// ClsContPAQi ObjContPaq = null;
// //StringBuilder MensajeAlert = new StringBuilder() ;
// try
// {
// objfact.GuardarVenta(ref objfact, ref ObjVentas, ref ObjConta, ref ObjInventario, ref ObjContr, ref objfact.DtDetalle, objfact.CveNCaVincular, ref ObjContPaq, ref ObjBancos, ref ObjOS, ref ObjEventos, ref ObjCGame, ref ObjClientes, ObjAcum: ObjAcum);
// }
// catch (Exception )
// {
// objfact.CveVenta = -1;
// }
// if (ObjVentas.UpdateEstatusFactura(3, objxml.complemento.UUID, "", DateTime.ParseExact(objxml.comprobante.Fecha.Replace("T", " "), "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture), ObjVentas.CveVenta, CvePAC: 4))
// if (objfact.CveVenta > 0 && objfact.ErrorList.Count == 0)
// {
// ObjVentas.Commit();
// }
// else
// {
// foreach (string item in objfact.ErrorList)
// {
// strErrores.AppendLine("<br/>");
// strErrores.AppendLine(item);
// }
// objfact.CveVenta = -1;
// ObjVentas.RollBack();
// }
// ObjVentas.Dispose();
// ObjConta.Dispose();
// ObjInventario.Dispose();
// ObjCGame.Dispose();
// ObjContr.Dispose();
// ObjDocCliente.Dispose();
// ObjClientes.Dispose();
// ObjAcum.Dispose();
//}
//if (objfact != null && objfact.CveVenta > 0)
//{
// CargaConciliacionemitidasSATGet();
// Alert($"se ha agregado la factura correctamente.<br/> <a href=\"/Ventas/Ventas.aspx?CveVenta={objfact.CveVenta}\" > Ver Factura </a>", ModExtensiones.TipoMensaje.ToastInformacion,timeout:25);
//}
//else { continuar = false; }
//if (!continuar)
//{
// Alert($"no se pudo agregar la factura {strErrores.ToString()}", ModExtensiones.TipoMensaje.MsgAdvertencia);
//}
}
protected Modelos.Factura GetFacturaFromXML(XmlSatCFDI objxml)
{
int CvePsReconstruccion = DdlPS.SelectedValue.ToEntero();
int CveSubProyectoReconstruccion = DdlSubProyectoDatos.SelectedValue.ToEntero();
//Modelos.Factura.MMensajeFactura resp;
string Moneda = objxml.comprobante.Moneda;
if (objxml.comprobante.Version == "3.2")
{
switch (Moneda)
{
case "Peso Mexicano": Moneda = "MXN"; break;
case "Dolar Americano": Moneda = "USD"; break;
}
}
string formadepago = objxml.comprobante.FormaPago;
string metododepago = objxml.comprobante.MetodoPago;
if (objxml.comprobante.Version == "3.2")
{
switch (objxml.comprobante.MetodoPago)//si es correcto estan invertidos
{
case "TRANSFERENCIA ELECTRONICA": formadepago = "03"; break;
default: formadepago = objxml.comprobante.MetodoPago; break;
}
}
if (objxml.comprobante.Version == "3.2")
{
switch (objxml.comprobante.FormaPago)//si es correcto estan invertidos
{
case "PAGO EN UNA SOLA EXHIBICION": metododepago = "PUE"; break;
default: metododepago = objxml.comprobante.FormaPago; break;
}
}
Modelos.Factura objfact = new Modelos.Factura(UsuarioActual)
{
TipoMensajeRespuesta = Modelos.TipoMensajeRespuesta.TextoLimpio,//?que es esto
CveUsuario = UsuarioActual.CveUsuario,
CveEmpresa = UsuarioActual.CveEmpresa,
FolioFiscal = objxml.complemento.UUID,
Serie = objxml.comprobante.Serie,
Folio = objxml.comprobante.Folio.ToEntero(),//Nota en el sat puede ser un string
Version = objxml.comprobante.Version,
TipoCambio = objxml.comprobante.TipoCambio,
//ConvertirPesos =false,//?para que sirve
MonedaSAT = objxml.comprobante.Moneda,
CveMoneda = GlobalDTMonedas.FiltroPrimeroValor("CveMoneda", $" AbreviaturaSAT= '{Moneda}' ").ToEntero(),
Moneda = GlobalDTMonedas.FiltroPrimeroValor("Moneda", $" AbreviaturaSAT= '{Moneda}' "),
TipoDocto = objxml.comprobante.TipoDeComprobanteSIG,
RefDocto = "",
CveMesa = -1,
Fecha = DateTime.ParseExact(objxml.comprobante.Fecha, "yyyy-MM-ddTHH:mm:ss", System.Globalization.CultureInfo.InvariantCulture),
CvePrePoliza = -1,
FechaPago = DateTime.Now,
MotivoDescuento = "",
FechaEjecucion = DateTime.Now,
UsuarioCreo = UsuarioActual.Usuario,
CveCondicionEntrega = -1,
CondicionEntrega = "",
NumeroCuenta = "",
CondicionesPago = 0,
FormaPago = 0,
PedidoContrato = "",
NumeroContrato = "",
DescripcionContrato = "",
CveCorte = -1,
TipoDocumento = objxml.comprobante.TipoDeComprobanteTexto,
Alfa1 = "",
Alfa2 = "",
Alfa3 = "",
CveContrato = -1
};
DataRow dr = get_GlobalDTSubProyectos(-1, -1, UsuarioActual.CveEmpresa, 1).FiltroPrimero(string.Format("Serie='{0}'", objfact.Serie));
if (dr == null) { dr = get_GlobalDTSubProyectos(-1, CveSubProyectoReconstruccion, UsuarioActual.CveEmpresa, 1).Rows[0]; }
if (dr != null)
{
objfact.CveSubProyecto = dr["CveSubProyecto"].ToString().ToEntero();
objfact.CveSubProyectoCobranza = dr["CveSubProyecto"].ToString().ToEntero();
objfact.CveSubProyectoEjecucion = dr["CveSubProyecto"].ToString().ToEntero();
objfact.SubProyecto = new Modelos.SubProyectoModel(dr);
objfact.SubProyectoMatriz = new Modelos.SubProyectoModel(get_GlobalDTSubProyectos(-1, CveSubProyecto: -1, CveEmpresa: UsuarioActual.CveEmpresa).FiltroPrimero("TipoSucursal=1"));
}
using (ClsClientes objClientes = new ClsClientes())
{
if (objClientes.GetClientes(-1, "-1", "-1", "-1", objxml.receptor.Rfc, "-1", "-1", -1, UsuarioActual.CveEmpresa, -1, TipoCliente: -1) && objClientes.DtResultados.Rows.Count > 0)
{
DataRow drCliente = objClientes.DtResultados.Rows[0];
objfact.CveCliente = drCliente["CveCliente"].ToString().ToEntero();
objfact.SetCliente();
}
}
objfact.CveAlmacen = -1;
objfact.CveFormaPago33 = GlobalDTVtaFormaPago.FiltroPrimeroValor("CveFormaPago", $"ClaveFormaPagoSAT = '{formadepago}'").ToEntero();
objfact.FormaPagoSAT33 = objxml.comprobante.FormaPago;
objfact.FormaPago33 = objxml.comprobante.FormaPagoTexto;
objfact.CveMetodoPago33 = GlobalDTVtaMetodoPago.FiltroPrimeroValor("CveMetodoPago", $" ClaveMetodoPagoSAT = '{metododepago}'").ToEntero();
objfact.CveMetodoPago = GlobalDTVtaMetodoPago.FiltroPrimeroValor("CveMetodoPago", $" ClaveMetodoPagoSAT = '{metododepago}'").ToEntero();
objfact.ClaveMetodoPagoSAT = objxml.comprobante.MetodoPago;
objfact.MetodoPago33 = objxml.comprobante.MetodoPagoTexto;
objfact.CveUsoCFDI = get_GlobalDTSATUsosCFDI(-1).FiltroPrimeroValor("CveUsoCFDI", $"UsoCFDI = '{objxml.receptor.UsoCFDI}'").ToEntero();
objfact.UsoCFDI = objxml.receptor.UsoCFDITexto;
objfact.ClaveUsoCFDI = objxml.receptor.UsoCFDI;
objfact.CveClienteSucursal = -1;
objfact.DtDetalle = CreaDTDetalle(UsuarioActual, objxml.conceptos, objfact.CveSubProyecto, CvePsReconstruccion, objxml);
objfact.TipoCambioDolares = objxml.comprobante.TipoCambio;
objfact.SubTotal = objxml.comprobante.SubTotal;
objfact.Descuento = objxml.comprobante.Descuento;
objfact.Amortizacion = 0;
objfact.IVA = objxml.Impuestos.Where(x => (x.Impuesto == "002" || x.Impuesto == "IVA") && x.Tipo == "Traslados").Sum(item => item.Importe);
objfact.RetIVA = objxml.Impuestos.Where(x => (x.Impuesto == "002" || x.Impuesto == "IVA") && x.Tipo == "Retenciones").Sum(item => item.Importe);
objfact.RetISR = objxml.Impuestos.Where(x => (x.Impuesto == "001" || x.Impuesto == "ISR") && x.Tipo == "Retenciones").Sum(item => item.Importe);
objfact.IEPS = objxml.Impuestos.Where(x => (x.Impuesto == "003" || x.Impuesto == "IEPS")).Sum(item => item.Importe);
objfact.Total = objxml.comprobante.Total;
objfact.TotalOtrosConceptos = 0;
objfact.Observaciones = "";
objfact.OrdenCompra = "";
objfact.PedidoContrato = "";
objfact.ObservacionesAlmacen = "";
if (strErrores.Length > 0)
{
objfact = null;
}
return objfact;
}
private DataTable CreaDTDetalle(Usuario UsuarioActual, List<CFDIConcepto> conceptos, int CveSubProyecto, int CvePsReconstruccion, XmlSatCFDI objxml)
{
bool continuar = true;
var TmpDT = new DataTable();
#region TmpDT Fields
TmpDT.Columns.Add("CveVenta", typeof(int));
TmpDT.Columns.Add("Consec", typeof(int));
TmpDT.Columns.Add("Cantidad", typeof(decimal));
TmpDT.Columns.Add("Codigo", typeof(string));
TmpDT.Columns.Add("CveUM", typeof(int));
TmpDT.Columns.Add("UM", typeof(string));
TmpDT.Columns.Add("SATClaveUM", typeof(string));
TmpDT.Columns.Add("CveClasificacion", typeof(int));
TmpDT.Columns.Add("Clasificacion", typeof(string));
TmpDT.Columns.Add("CvePS", typeof(int));
TmpDT.Columns.Add("PS", typeof(string));
TmpDT.Columns.Add("CodigoPS", typeof(string));
TmpDT.Columns.Add("SATClaveProdServ", typeof(string));
TmpDT.Columns.Add("NoIdentificacion", typeof(string));
TmpDT.Columns.Add("CveTipoPS", typeof(int));
TmpDT.Columns.Add("CveTipoInvPS", typeof(int));
TmpDT.Columns.Add("SerieLote", typeof(string));
TmpDT.Columns.Add("CuentaPredial", typeof(string));
TmpDT.Columns.Add("Obs", typeof(string));
TmpDT.Columns.Add("TiempoEntrega", typeof(string));
TmpDT.Columns.Add("PU", typeof(decimal));
TmpDT.Columns.Add("IVA", typeof(decimal));
TmpDT.Columns.Add("ImporteIVA", typeof(decimal));
TmpDT.Columns.Add("PorcentajeIVA", typeof(decimal));
TmpDT.Columns.Add("ImporteRetIVA", typeof(decimal));
TmpDT.Columns.Add("ImporteRetISR", typeof(decimal));
TmpDT.Columns.Add("PorcentajeRetIVA", typeof(decimal));
TmpDT.Columns.Add("PorcentajeRetISR", typeof(decimal));
TmpDT.Columns.Add("ImporteIEPS", typeof(decimal));
TmpDT.Columns.Add("IEPS", typeof(decimal));
TmpDT.Columns.Add("PorcentajeIEPS", typeof(decimal));
TmpDT.Columns.Add("Descuento", typeof(decimal));
TmpDT.Columns.Add("TipoDescuento", typeof(int));
TmpDT.Columns.Add("TotalImporte", typeof(decimal));
TmpDT.Columns.Add("Total", typeof(decimal));
// Para uso del módulo contable
TmpDT.Columns.Add("AsientoContableVentas", typeof(int));
TmpDT.Columns.Add("IdCtaContVentas", typeof(int));
TmpDT.Columns.Add("AplicaParaConcepto", typeof(bool));
TmpDT.Columns.Add("CveProyecto", typeof(int));
TmpDT.Columns.Add("Proyecto", typeof(string));
TmpDT.Columns.Add("CveSubProyecto", typeof(int));
TmpDT.Columns.Add("SubProyecto", typeof(string));
// TipoDescuento: 1 = Descuento * PU; 2 = Descuento por Total del concepto
TmpDT.Columns.Add("CvePresupuestoIngreso", typeof(int));
TmpDT.Columns.Add("CveFuenteRecaudacion", typeof(int));
// Contratos
TmpDT.Columns.Add("CveContratoDetalle", typeof(int));
// Remisiones a Facturas
TmpDT.Columns.Add("CveVentaDetalle", typeof(int));
TmpDT.Columns.Add("CveVentaDetalleRemision", typeof(int));
TmpDT.Columns.Add("CveVentaDetalleCotizacion", typeof(int));
// Pedido2 a Facturas
TmpDT.Columns.Add("CveVentaDetallePedido2", typeof(int));
TmpDT.Columns.Add("Origen", typeof(int));
// Ordenes Servicio
TmpDT.Columns.Add("CveOS", typeof(int));
TmpDT.Columns.Add("CveOSDetalle", typeof(int));
TmpDT.Columns.Add("SeFacturara", typeof(int));
TmpDT.Columns.Add("Folio", typeof(int));
TmpDT.Columns.Add("Estatus", typeof(string));
// Ordenamiento
TmpDT.Columns.Add("Orden", typeof(int));
TmpDT.Columns.Add("TipoDocto", typeof(string));
// OC
TmpDT.Columns.Add("CveOrdenCompraDetalle", typeof(int));
TmpDT.Columns.Add("EntregaDirecta", typeof(int));
TmpDT.Columns.Add("CveMovimientoDetallePedido", typeof(int));
TmpDT.Columns.Add("CantidadFacturadaRem", typeof(decimal));
TmpDT.Columns.Add("CantidadFacturadaCot", typeof(decimal));
TmpDT.Columns.Add("CantidadInventario", typeof(decimal));
TmpDT.Columns.Add("ClaveSATFraccionArancelaria", typeof(string));
TmpDT.Columns.Add("ClaveSATUnidadAduana", typeof(string));
TmpDT.Columns.Add("ClaveSATFraccionArancelariaDescripcion", typeof(string));
TmpDT.Columns.Add("ClaveSATUnidadAduanaDescripcion", typeof(string));
TmpDT.Columns.Add("CveTamaño", typeof(int));
#endregion
foreach (CFDIConcepto item in conceptos)
{
DataRow DrPS = null;// get_GlobalDTPS(UsuarioActual.CveEmpresa).FiltroPrimero(string.Format("PS ={0}",item.Descripcion));
DataRow DrSubProyecto = null;
DataRow DrUmSat = null;
DataRow DrUm = null;
if (continuar)
{
using (ClsProductosServicios obj = new ClsProductosServicios())
{
if (obj.GetPS(-1, -1, UsuarioActual.CveEmpresa, PS: item.Descripcion) && obj.DtResultados.Rows.Count > 0)
{
DrPS = obj.DtResultados.Rows[0];
}
else if (obj.GetPS(CvePsReconstruccion, -1, UsuarioActual.CveEmpresa) && obj.DtResultados.Rows.Count > 0)
{
DrPS = obj.DtResultados.Rows[0];
}
}
DrSubProyecto = get_GlobalDTSubProyectos(-1, CveSubProyecto, UsuarioActual.CveEmpresa).Rows[0];
if (objxml.comprobante.Version == "3.2")
{
item.ClaveUnidad = item.Unidad;
switch (item.ClaveUnidad)
{
case "TON": item.ClaveUnidad = "A75"; break;
case "No aplica": item.ClaveUnidad = "ACT"; break;
case "LITROS": item.ClaveUnidad = "E32"; break;
case "M3-KM": item.ClaveUnidad = "M73"; break;
}
}
DrUmSat = GlobalDTPSATUM.FiltroPrimero(string.Format("SATClaveUnidadMedida='{0}'", item.ClaveUnidad));
}
if (continuar && DrUmSat == null) { continuar = false; strErrores.AppendLine($"No se encontro la unidad de medida en el catalogo del sat '{item.ClaveUnidad}', favor de contactar a soporte tecnico."); }
if (continuar)
{
DrUm = get_GlobalDTUnidadesMedida(UsuarioActual.CveEmpresa).FiltroPrimero(string.Format("CveUnidadMedidaSAT={0}", DrUmSat["CveSATUnidadMedida"]));
}
if (continuar && DrUm == null) { continuar = false; strErrores.AppendLine($"No se encontro la unidad de medida relacionada a la clave del sat '{item.ClaveUnidad}', favor de asignarla en el catalogo de unidad de medida."); }
if (continuar)
{
//no se encontro una undidad de medida para
DataRow Row = TmpDT.NewRow();
Row["CveProyecto"] = DrSubProyecto["CveProyecto"].ToString().ToEntero();
Row["Proyecto"] = DrSubProyecto["Proyecto"].ToString();
Row["CveSubProyecto"] = CveSubProyecto;
Row["SubProyecto"] = DrSubProyecto["SubProyecto"].ToString();
Row["SerieLote"] = "";
Row["TiempoEntrega"] = "";
Row["Orden"] = TmpDT.Rows.Count + 1;
Row["Cantidad"] = item.Cantidad;
Row["CveUM"] = DrUm["CveUnidadMedida"];
Row["UM"] = DrUm["UnidadMedida"];
Row["CveClasificacion"] = DrPS["CveClasificacion"];
Row["Clasificacion"] = DrPS["Clasificacion"];
Row["CvePS"] = DrPS["CvePS"];
Row["Obs"] = item.Descripcion;
//TotalCalculableImpuestos = (Cantidad * PU) - Descuento;
Row["PU"] = item.ValorUnitario;
Row["Codigo"] = DrPS["Codigo"];
Row["NoIdentificacion"] = DrPS["Codigo"];
Row["ClaveSATFraccionArancelaria"] = DrPS["ClaveSATFraccionArancelaria"];
Row["ClaveSATUnidadAduana"] = DrPS["ClaveSATUnidadAduana"];
Row["ClaveSATFraccionArancelariaDescripcion"] = DrPS["ClaveSATFraccionArancelariaDescripcion"];
Row["ClaveSATUnidadAduanaDescripcion"] = DrPS["ClaveSATUnidadAduanaDescripcion"];
Row["Consec"] = TmpDT.Rows.Count + 1;
Row["PS"] = item.Descripcion;
Row["CodigoPS"] = DrPS["PSCodigo"].ToString();
Row["CveTipoPS"] = DrPS["CveTipoPS"];
Row["CveTipoInvPS"] = DrPS["Inv_CveMetodoInventario"];
Row["CveTamaño"] = DrPS["CveTamaño"];
CFDIConceptoImpuesto impuesto = item.Impuestos.FirstOrDefault(x => x.Impuesto == "002" && x.Tipo == "Traslado");
decimal sumaimpuesto = 0;
decimal PorcentajeIVA = 0;
if (impuesto != null)
{
decimal decimpuesto = 0;
decimal.TryParse(impuesto.TasaOCuota, out decimpuesto);
PorcentajeIVA = decimpuesto / 100;
Row["PorcentajeIVA"] = PorcentajeIVA;
Row["ImporteIVA"] = impuesto.Importe;// impuesto.Importe;//Math.Round(item.Importe * (decimpuesto/100), 2);
sumaimpuesto += impuesto.Importe;
}
else
{
Row["PorcentajeIVA"] = 0;
Row["ImporteIVA"] = 0;
if (objxml.comprobante.Version == "3.2")
{
if (item.Importe > 0)
{
PorcentajeIVA = .16M;
Row["PorcentajeIVA"] = PorcentajeIVA;
Row["ImporteIVA"] = item.Importe * PorcentajeIVA;//Math.Round(((item.Importe / (1 + PorcentajeIVA))*.16M),2);
}
}
}
Row["IVA"] = Row["ImporteIVA"];
impuesto = item.Impuestos.FirstOrDefault(x => x.Impuesto == "003" && x.Tipo == "Traslado");
if (impuesto != null)
{
decimal decimpuesto = 0;
decimal.TryParse(impuesto.TasaOCuota, out decimpuesto);
Row["PorcentajeIEPS"] = decimpuesto / 100;
Row["ImporteIEPS"] = impuesto.Importe;
Row["IEPS"] = impuesto.Importe;
sumaimpuesto += impuesto.Importe;
}
else
{
Row["PorcentajeIEPS"] = 0;
Row["ImporteIEPS"] = 0;
Row["IEPS"] = 0;
}
impuesto = item.Impuestos.FirstOrDefault(x => x.Impuesto == "001" && x.Tipo == "Retencion");
if (impuesto != null)
{
decimal decimpuesto = 0;
decimal.TryParse(impuesto.TasaOCuota, out decimpuesto);
Row["PorcentajeRetISR"] = decimpuesto / 100;
Row["ImporteRetISR"] = impuesto.Importe;
sumaimpuesto -= impuesto.Importe;
}
else
{
Row["ImporteRetISR"] = 0;
Row["PorcentajeRetISR"] = 0;
}
impuesto = item.Impuestos.FirstOrDefault(x => x.Impuesto == "002" && x.Tipo == "Retencion");
if (impuesto != null)
{
decimal decimpuesto = 0;
decimal.TryParse(impuesto.TasaOCuota, out decimpuesto);
Row["PorcentajeRetIVA"] = decimpuesto / 100;
Row["ImporteRetIVA"] = impuesto.Importe;
sumaimpuesto -= impuesto.Importe;
}
else
{
Row["ImporteRetIVA"] = 0;
Row["PorcentajeRetIVA"] = 0;
}
Row["Descuento"] = item.Descuento;
Row["TipoDescuento"] = "2";
//Row["Total"] = item.Importe - sumaimpuesto;
Row["Total"] = item.Importe / (1 + PorcentajeIVA);
Row["TotalImporte"] = item.Importe;
Row["SATClaveProdServ"] = item.ClaveProdServ;
Row["SATClaveUM"] = item.ClaveUnidad;
Row["EntregaDirecta"] = "-1";
// Contratos
Row["CveContratoDetalle"] = -1;
Row["CveVentaDetalle"] = -1;
Row["CveMovimientoDetallePedido"] = -1;
Row["CveOrdenCompraDetalle"] = -1;
Row["CveVentaDetalleRemision"] = -1;
Row["CveVentaDetalleCotizacion"] = -1;
Row["CveVentaDetallePedido2"] = -1;
Row["CuentaPredial"] = item.CuentaPredial;
TmpDT.Rows.Add(Row);
}
}
return TmpDT;
}
protected void LnkAceptarDefault_Click(object sender, EventArgs e)
{
RegistraScript("$('#DModalDefaults').modal('hide');");
registrarventa((GridViewRow)CurrentRow);
//foreach (GridViewRow gvrow in GVConciliacionemitidasSAT.Rows)
//{
// registrarventa(gvrow);
//}
}
protected void BtnConsultar_Click(object sender, EventArgs e)
{
CargaRepConciliacionSatGET();
}
protected void GVConciliacionemitidasSAT_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string navurl = "";
if (e.Row.DBCampo("Tipo") == "1")
{
string RutaXml = e.Row.DBCampo("RutaXml");
//if (RutaXml.IndexOf("Empresas")>0)
//{
// RutaXml = RutaXml.Substring(RutaXml.IndexOf("Empresas"));
//}
navurl = string.Format("RepConciliacionEmitidosSat.aspx?op={0}", Extensiones.ModExtensiones.Encripta(e.Row.DataKey("RutaXml")));
}
else
{
navurl = string.Format("/Compras/PopUpVerFactura.aspx?P={0}", Extensiones.ModExtensiones.Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", e.Row.DBCampo("CveVenta"), "XML", e.Row.DBCampo("SerieFolio"), e.Row.DBCampo("TipoDocto"))));
}
e.Row.FCHyperLink("HypXml").NavigateUrl = navurl;
}
//String.Format("/Compras/PopUpVerFactura.aspx?P={0}", Encripta(String.Format("OP=FactVta&CVEVENTA={0}&EXT={1}&SERIEFOLIO={2}&TIPODOCTO={3}", CveVenta, "XML", DbRowVenta("SerieFolio"), DbRowVenta("TipoDocto"))))
}
}