9984 lines
468 KiB
VB.net
9984 lines
468 KiB
VB.net
Option Strict On
|
|
Option Explicit On
|
|
|
|
Imports System.Data
|
|
Imports System.Diagnostics
|
|
Imports System.Globalization
|
|
Imports System.IO
|
|
Imports System.IO.Compression
|
|
Imports System.Net.Http
|
|
Imports System.Net.Http.Headers
|
|
Imports System.Threading
|
|
Imports System.Threading.Tasks
|
|
Imports System.Windows.Forms.VisualStyles.VisualStyleElement
|
|
Imports System.Xml
|
|
Imports ADSistemaLibrary.SatXml
|
|
Imports ADSistemaLibrary.SatXml.XmlSatCFDI
|
|
Imports Extensiones
|
|
Imports Microsoft.Reporting.WebForms
|
|
Imports Newtonsoft.Json.Linq
|
|
Imports ClsPaginas
|
|
Imports ADS.eFacturas
|
|
'Imports Telerik.Web.UI.Widgets
|
|
'Imports DocumentFormat.OpenXml.Drawing.Diagrams
|
|
Imports SharpCompress.Archive.Rar
|
|
Imports SharpCompress.Common
|
|
Imports SharpCompress.Reader
|
|
Imports Telerik.Web.UI
|
|
|
|
|
|
'Imports Telerik.Web.UI
|
|
|
|
|
|
|
|
|
|
Partial Class Compras_eFacturas
|
|
Inherits ClsPaginas
|
|
|
|
#Region "Propiedades"
|
|
'CFDi
|
|
Private _Folio As String
|
|
Private Property SeriePago As String
|
|
Set(value As String)
|
|
ViewState("SeriePago") = value
|
|
End Set
|
|
Get
|
|
Return ViewState("SeriePago").ToString
|
|
End Get
|
|
End Property
|
|
Private Property FolioPago As String
|
|
Set(value As String)
|
|
ViewState("FolioPago") = value
|
|
End Set
|
|
Get
|
|
Return ViewState("FolioPago").ToString
|
|
End Get
|
|
End Property
|
|
Private Property Destino As String
|
|
Set(value As String)
|
|
ViewState("Destino") = value
|
|
End Set
|
|
Get
|
|
Return ViewState("Destino").ToString
|
|
End Get
|
|
End Property
|
|
Private Property CveFactura As Integer
|
|
Set(value As Integer)
|
|
ViewState("CveFactura") = value
|
|
End Set
|
|
Get
|
|
Return CInt(ViewState("CveFactura"))
|
|
End Get
|
|
End Property
|
|
Private Property CveFacturaPago As Integer
|
|
Set(value As Integer)
|
|
ViewState("CveFacturaPago") = value
|
|
End Set
|
|
Get
|
|
Return CInt(ViewState("CveFacturaPago"))
|
|
End Get
|
|
End Property
|
|
Private Property CveProveedor As Integer
|
|
Set(value As Integer)
|
|
ViewState("CveProveedor") = value
|
|
End Set
|
|
Get
|
|
Return CInt(ViewState("CveProveedor"))
|
|
End Get
|
|
End Property
|
|
Private Property Folio1 As String
|
|
Set(value As String)
|
|
ViewState("Folio1") = value
|
|
End Set
|
|
Get
|
|
Return (ViewState("Folio1")).ToString
|
|
End Get
|
|
End Property
|
|
Private Property Proveedor As String
|
|
Set(value As String)
|
|
ViewState("Proveedor") = value
|
|
End Set
|
|
Get
|
|
Return (ViewState("Proveedor")).ToString
|
|
End Get
|
|
End Property
|
|
|
|
Private Property Ejecutable As String
|
|
Set(value As String)
|
|
ViewState("Ejecutable") = value
|
|
End Set
|
|
Get
|
|
Return ViewState("Ejecutable").ToString
|
|
End Get
|
|
End Property
|
|
|
|
Private Property ChecandoCorreo As Boolean
|
|
Set(value As Boolean)
|
|
ViewState("ChecandoCorreo") = value
|
|
End Set
|
|
Get
|
|
Return CType(ViewState("ChecandoCorreo"), Boolean)
|
|
End Get
|
|
End Property
|
|
|
|
Private DTConceptos As DataTable
|
|
Private Property Folio() As String
|
|
Get
|
|
Return _Folio
|
|
End Get
|
|
Set
|
|
_Folio = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private Property Serie() As String
|
|
|
|
Get
|
|
If m_Serie Is Nothing Then
|
|
Return ""
|
|
Else
|
|
Return m_Serie
|
|
End If
|
|
|
|
|
|
End Get
|
|
Set
|
|
m_Serie = Value
|
|
End Set
|
|
End Property
|
|
Private m_Serie As String
|
|
|
|
Private _fecha As String
|
|
Private Property fecha() As String
|
|
Get
|
|
Return _fecha
|
|
End Get
|
|
Set
|
|
_fecha = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _tipoDeComprobante As String
|
|
Private Property tipoDeComprobante() As String
|
|
Get
|
|
Return _tipoDeComprobante
|
|
End Get
|
|
Set
|
|
_tipoDeComprobante = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _formaDePago As String
|
|
Private Property formaDePago() As String
|
|
Get
|
|
Return _formaDePago
|
|
End Get
|
|
Set
|
|
_formaDePago = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _subTotal As String
|
|
Private Property subTotal() As String
|
|
Get
|
|
Return _subTotal
|
|
End Get
|
|
Set
|
|
_subTotal = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _descuento As String
|
|
Private Property descuento() As String
|
|
Get
|
|
Return _descuento
|
|
End Get
|
|
Set
|
|
_descuento = Value
|
|
End Set
|
|
End Property
|
|
Private _total As String
|
|
Private Property total() As String
|
|
Get
|
|
Return _total
|
|
End Get
|
|
Set
|
|
_total = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _moneda As String
|
|
Private Property moneda() As String
|
|
Get
|
|
Return _moneda
|
|
End Get
|
|
Set
|
|
_moneda = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _metodoDePago As String
|
|
Private Property metodoDePago() As String
|
|
Get
|
|
Return _metodoDePago
|
|
End Get
|
|
Set
|
|
_metodoDePago = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _condicionesDePago As String
|
|
Private Property condicionesDePago() As String
|
|
Get
|
|
Return _condicionesDePago
|
|
End Get
|
|
Set
|
|
_condicionesDePago = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _LugarExpedicion As String
|
|
Private Property LugarExpedicion() As String
|
|
Get
|
|
Return _LugarExpedicion
|
|
End Get
|
|
Set
|
|
_LugarExpedicion = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _NumCtaPagoNumCtaPago As String
|
|
Private Property NumCtaPagoNumCtaPago() As String
|
|
Get
|
|
Return _NumCtaPagoNumCtaPago
|
|
End Get
|
|
Set
|
|
_NumCtaPagoNumCtaPago = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _noCertificado As String
|
|
Private Property noCertificado() As String
|
|
Get
|
|
Return _noCertificado
|
|
End Get
|
|
Set
|
|
_noCertificado = Value
|
|
End Set
|
|
End Property
|
|
|
|
''Emisor
|
|
Private _EmiRFC As String
|
|
Private Property EmiRFC() As String
|
|
Get
|
|
Return _EmiRFC
|
|
End Get
|
|
Set
|
|
_EmiRFC = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _EmiNombre As String
|
|
Private Property EmiNombre() As String
|
|
Get
|
|
Return _EmiNombre
|
|
End Get
|
|
Set
|
|
_EmiNombre = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _DomFisCalle As String
|
|
Private Property DomFisCalle() As String
|
|
Get
|
|
Return _DomFisCalle
|
|
End Get
|
|
Set
|
|
_DomFisCalle = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _DomFisNoExt As String
|
|
Private Property DomFisNoExt() As String
|
|
Get
|
|
Return _DomFisNoExt
|
|
End Get
|
|
Set
|
|
_DomFisNoExt = Value
|
|
End Set
|
|
End Property
|
|
'Dim _DomFisNoInt As String
|
|
|
|
Private _DomFisCol As String
|
|
Private Property DomFisCol() As String
|
|
Get
|
|
Return _DomFisCol
|
|
End Get
|
|
Set
|
|
_DomFisCol = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _DomFisCP As String
|
|
Private Property DomFisCP() As String
|
|
Get
|
|
Return _DomFisCP
|
|
End Get
|
|
Set
|
|
_DomFisCP = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _DomFisMun As String
|
|
Private Property DomFisMun() As String
|
|
Get
|
|
Return _DomFisMun
|
|
End Get
|
|
Set
|
|
_DomFisMun = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _DomFisLoc As String
|
|
Private Property DomFisLoc() As String
|
|
Get
|
|
Return _DomFisLoc
|
|
End Get
|
|
Set
|
|
_DomFisLoc = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _DomFisEst As String
|
|
Private Property DomFisEst() As String
|
|
Get
|
|
Return _DomFisEst
|
|
End Get
|
|
Set
|
|
_DomFisEst = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _DomFisPais As String
|
|
Private Property DomFisPais() As String
|
|
Get
|
|
Return _DomFisPais
|
|
End Get
|
|
Set
|
|
_DomFisPais = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _ExpEnCalle As String
|
|
Private Property ExpEnCalle() As String
|
|
Get
|
|
Return _ExpEnCalle
|
|
End Get
|
|
Set
|
|
_ExpEnCalle = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _ExpEnNoExt As String
|
|
Private Property ExpEnNoExt() As String
|
|
Get
|
|
Return _ExpEnNoExt
|
|
End Get
|
|
Set
|
|
_ExpEnNoExt = Value
|
|
End Set
|
|
End Property
|
|
|
|
|
|
Private ExpEnCol As String
|
|
|
|
Private _ExpEnCP As String
|
|
Private Property ExpEnCP() As String
|
|
Get
|
|
Return _ExpEnCP
|
|
End Get
|
|
Set
|
|
_ExpEnCP = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _ExpEnMun As String
|
|
Private Property ExpEnMun() As String
|
|
Get
|
|
Return _ExpEnMun
|
|
End Get
|
|
Set
|
|
_ExpEnMun = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _ExpEnLoc As String
|
|
Private Property ExpEnLoc() As String
|
|
Get
|
|
Return _ExpEnLoc
|
|
End Get
|
|
Set
|
|
_ExpEnLoc = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _ExpEnEst As String
|
|
Private Property ExpEnEst() As String
|
|
Get
|
|
Return _ExpEnEst
|
|
End Get
|
|
Set
|
|
_ExpEnEst = Value
|
|
End Set
|
|
End Property
|
|
Private _ExpEnPais As String
|
|
Private Property ExpEnPais() As String
|
|
Get
|
|
Return _ExpEnPais
|
|
End Get
|
|
Set
|
|
_ExpEnPais = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _Regimen As String
|
|
Private Property Regimen() As String
|
|
Get
|
|
Return _Regimen
|
|
End Get
|
|
Set
|
|
_Regimen = Value
|
|
End Set
|
|
End Property
|
|
|
|
''Receptor
|
|
Private _RecRfc As String
|
|
Private Property RecRfc() As String
|
|
Get
|
|
Return _RecRfc
|
|
End Get
|
|
Set
|
|
_RecRfc = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _RecNombre As String
|
|
Private Property RecNombre() As String
|
|
Get
|
|
Return _RecNombre
|
|
End Get
|
|
Set
|
|
_RecNombre = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _DomRecCalle As String
|
|
Private Property DomRecCalle() As String
|
|
Get
|
|
Return _DomRecCalle
|
|
End Get
|
|
Set
|
|
_DomRecCalle = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _DomRecFisNoExt As String
|
|
Private Property DomRecFisNoExt() As String
|
|
Get
|
|
Return _DomRecFisNoExt
|
|
End Get
|
|
Set
|
|
_DomRecFisNoExt = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _DomRecFisNoInt As String
|
|
Private Property DomRecFisNoInt() As String
|
|
Get
|
|
Return _DomRecFisNoInt
|
|
End Get
|
|
Set
|
|
_DomRecFisNoInt = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _DomRecCol As String
|
|
Private Property DomRecCol() As String
|
|
Get
|
|
Return _DomRecCol
|
|
End Get
|
|
Set
|
|
_DomRecCol = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _DomRecCP As String
|
|
Private Property DomRecCP() As String
|
|
Get
|
|
Return _DomRecCP
|
|
End Get
|
|
Set
|
|
_DomRecCP = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _DomRecMun As String
|
|
Private Property DomRecMun() As String
|
|
Get
|
|
Return _DomRecMun
|
|
End Get
|
|
Set
|
|
_DomRecMun = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _DomRecLoc As String
|
|
Private Property DomRecLoc() As String
|
|
Get
|
|
Return _DomRecLoc
|
|
End Get
|
|
Set
|
|
_DomRecLoc = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _DomRecEst As String
|
|
Private Property DomRecEst() As String
|
|
Get
|
|
Return _DomRecEst
|
|
End Get
|
|
Set
|
|
_DomRecEst = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _DomRecPais As String
|
|
Private Property DomRecPais() As String
|
|
Get
|
|
Return _DomRecPais
|
|
End Get
|
|
Set
|
|
_DomRecPais = Value
|
|
End Set
|
|
End Property
|
|
|
|
'IVA
|
|
Private _TrasladoIVA As Double
|
|
Private Property TrasladoIVA() As Double
|
|
Get
|
|
Return _TrasladoIVA
|
|
End Get
|
|
Set
|
|
_TrasladoIVA = Value
|
|
End Set
|
|
End Property
|
|
|
|
'TFD
|
|
Private _TFDUUID As String
|
|
Private Property TFDUUID() As String
|
|
Get
|
|
Return _TFDUUID
|
|
End Get
|
|
Set
|
|
_TFDUUID = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _TFDFechaTimbrado As String
|
|
Private Property TFDFechaTimbrado() As String
|
|
Get
|
|
Return _TFDFechaTimbrado
|
|
End Get
|
|
Set
|
|
_TFDFechaTimbrado = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _TFDSelloCFD As String
|
|
Private Property TFDSelloCFD() As String
|
|
Get
|
|
Return _TFDSelloCFD
|
|
End Get
|
|
Set
|
|
_TFDSelloCFD = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _TFDNoCertSAT As String
|
|
Private Property TFDNoCertSAT() As String
|
|
Get
|
|
Return _TFDNoCertSAT
|
|
End Get
|
|
Set
|
|
_TFDNoCertSAT = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private _TFDSelloSAT As String
|
|
Private Property TFDSelloSAT() As String
|
|
Get
|
|
Return _TFDSelloSAT
|
|
End Get
|
|
Set
|
|
_TFDSelloSAT = Value
|
|
End Set
|
|
End Property
|
|
|
|
|
|
|
|
Property DTGVPagosVinculacion As DataTable
|
|
|
|
Get
|
|
If ViewState("DTGVPagosVinculacion") Is Nothing Then
|
|
Return New DataTable
|
|
Else
|
|
Return DirectCast(ViewState("DTGVPagosVinculacion"), DataTable)
|
|
End If
|
|
End Get
|
|
Set(value As DataTable)
|
|
ViewState("DTGVPagosVinculacion") = value
|
|
End Set
|
|
End Property
|
|
|
|
|
|
|
|
Private Property CurretUUIDPagoVincular As String
|
|
|
|
Get
|
|
If ViewState("CurretUUIDPagoVincular") Is Nothing Then
|
|
Return "-1"
|
|
Else
|
|
Return ViewState("CurretUUIDPagoVincular").ToString
|
|
End If
|
|
|
|
End Get
|
|
Set(value As String)
|
|
ViewState("CurretUUIDPagoVincular") = value
|
|
End Set
|
|
|
|
End Property
|
|
|
|
|
|
Private Property XMLNodosPagosModalCount As Integer
|
|
Get
|
|
If ViewState("XMLNodosPagosModalCount") Is Nothing Then
|
|
Return -1
|
|
Else
|
|
Return ViewState("XMLNodosPagosModalCount").ToString.ToEntero
|
|
End If
|
|
End Get
|
|
Set(value As Integer)
|
|
ViewState("XMLNodosPagosModalCount") = value
|
|
End Set
|
|
End Property
|
|
|
|
|
|
Private Property MontoPago As Decimal
|
|
Get
|
|
If ViewState("MontoPago") Is Nothing Then
|
|
Return 0
|
|
Else
|
|
Return (ViewState("MontoPago")).ToString.ToDecimal
|
|
End If
|
|
End Get
|
|
|
|
Set(value As Decimal)
|
|
ViewState("MontoPago") = value
|
|
End Set
|
|
|
|
End Property
|
|
|
|
Private Property CveFacturaComplementoTraslado As Integer
|
|
Get
|
|
If ViewState("CveFacturaComplementoTraslado") Is Nothing Then
|
|
Return -1
|
|
Else
|
|
Return ViewState("CveFacturaComplementoTraslado").ToString.ToEntero
|
|
End If
|
|
End Get
|
|
Set(value As Integer)
|
|
ViewState("CveFacturaComplementoTraslado") = value
|
|
End Set
|
|
End Property
|
|
|
|
|
|
|
|
Private Property ComprasEnComplemento As Integer
|
|
Get
|
|
If ViewState("ComprasEnComplemento") Is Nothing Then
|
|
Return -1
|
|
Else
|
|
Return ViewState("ComprasEnComplemento").ToString.ToEntero
|
|
End If
|
|
End Get
|
|
Set(value As Integer)
|
|
ViewState("ComprasEnComplemento") = value
|
|
End Set
|
|
End Property
|
|
|
|
Private Property SeVinculoConComprasFaltantes As Boolean
|
|
Get
|
|
If ViewState("SeVinculoConComprasFaltantes") Is Nothing Then
|
|
Return False
|
|
Else
|
|
Return Boolean.Parse(ViewState("SeVinculoConComprasFaltantes").ToString)
|
|
End If
|
|
End Get
|
|
Set(value As Boolean)
|
|
ViewState("SeVinculoConComprasFaltantes") = value
|
|
End Set
|
|
End Property
|
|
|
|
|
|
|
|
|
|
Property DTTraslados As DataTable
|
|
Get
|
|
If ViewState("DTTraslados") Is Nothing Then
|
|
Return New DataTable
|
|
Else
|
|
Return DirectCast(ViewState("DTTraslados"), DataTable)
|
|
End If
|
|
End Get
|
|
Set(value As DataTable)
|
|
ViewState("DTTraslados") = value
|
|
End Set
|
|
End Property
|
|
Private Property EsGrupoDiaz As Boolean
|
|
Get
|
|
If ViewState("EsGrupoDiaz") Is Nothing Then
|
|
ViewState("EsGrupoDiaz") = False
|
|
End If
|
|
Return CType(ViewState("EsGrupoDiaz"), Boolean)
|
|
End Get
|
|
Set(value As Boolean)
|
|
ViewState("EsGrupoDiaz") = value
|
|
End Set
|
|
End Property
|
|
|
|
|
|
#End Region
|
|
|
|
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
|
|
If Not Page.IsPostBack Then
|
|
|
|
'EsGrupoDiaz = False ' If(UsuarioActual.Empresa.Funcionalidad(382) = "1", True, False)
|
|
|
|
ChecandoCorreo = False
|
|
|
|
ViewState("Orden") = String.Empty
|
|
txtFechaI.Text = NowADS().AddMonths(-1).FirstDayOfMonth().ToShortDateString ' String.Format("01/01/{0}", If(NowADS().Month > 6, NowADS().Year, NowADS().Year - 1))
|
|
|
|
txtFechaF.Text = NowADS().ToShortDateString 'txtFechaI.Text.ToDate.AddMonths(1).AddDays(-1).ToShortDateString
|
|
|
|
Destino = String.Format("{0}Compras\", UsuarioActual.Empresa.Ruta)
|
|
Ejecutable = "F:\Proyectos\wwwSIG\Utilerias\ADSUtilerias.exe"
|
|
Form.DefaultButton = BtnConsultar.UniqueID
|
|
|
|
DdlResponsable.DataSource = GlobalDTUsuarioResponsable(UsuarioActual.CveEmpresa)
|
|
DdlResponsable.DataBind()
|
|
DdlResponsable.Items.Insert(0, New ListItem("Todos", "-1"))
|
|
|
|
DdlClasificacionProv.DataSource = GlobalDTProveedorClasificacion(UsuarioActual.CveEmpresa)
|
|
DdlClasificacionProv.DataBind()
|
|
DdlClasificacionProv.Items.Insert(0, New ListItem("Todos", "-1"))
|
|
|
|
TxtFechaBitInicio.Text = NowADS().ToString("dd/MM/yyyy")
|
|
TxtFechaBitFin.Text = NowADS().ToString("dd/MM/yyyy")
|
|
|
|
TxtFolio.Focus()
|
|
|
|
If UsuarioActual.Sesion("eFact-Proveedor").ToString <> "" Then TxtProveedor.Text = UsuarioActual.Sesion("eFact-Proveedor").ToString.Trim
|
|
If UsuarioActual.Sesion("eFact-FI").ToString <> "" Then txtFechaI.Text = UsuarioActual.Sesion("eFact-FI").ToString.Trim
|
|
If UsuarioActual.Sesion("eFact-FF").ToString <> "" Then txtFechaF.Text = UsuarioActual.Sesion("eFact-FF").ToString.Trim
|
|
If UsuarioActual.TienePermisoProceso(81) Then 'permiso puede eliminar factura de listado
|
|
GvD.Columns(14).Visible = True
|
|
GvD.Columns(15).Visible = True
|
|
GVSolicitudesPendientes.Columns(8).Visible = True
|
|
End If
|
|
If UsuarioActual.TienePermisoProceso(206) Then GvD.Columns(13).Visible = False
|
|
If UsuarioActual.Empresa.Funcionalidad(156) = "1" Then GvD.Columns(7).Visible = True
|
|
|
|
If (UsuarioActual.CveEmpresa.Contiene(13, 83) AndAlso UsuarioActual.CveRol = 1) Or EsGrupoDiaz Then
|
|
LnkRegistarFactura.Visible = True
|
|
End If
|
|
|
|
CargaGvBitacora()
|
|
CargaDatos(NowADS())
|
|
MostrarSolcitudesSAT()
|
|
|
|
'CARGA REGISTRO DE FACTURA
|
|
If EsGrupoDiaz Then
|
|
CargaClasificacionesComprobaciones()
|
|
CargaClasificaciones()
|
|
CargaPS(-1)
|
|
CargaPersoanlCajaChica()
|
|
CargaPersonalViaticos()
|
|
CargaDdlRetIVA()
|
|
CargaDdlRetISR()
|
|
End If
|
|
|
|
|
|
Dim LblSubProyectoTemp As New Label
|
|
CargarCentrosDeCosto(Nothing, DdlSubProyecto, Nothing, LblSubProyectoTemp, "Seleccione")
|
|
LblSubProyecto.InnerText = $"{LblSubProyectoTemp.Text}:"
|
|
End If
|
|
removeasincevent()
|
|
End Sub
|
|
|
|
Protected Sub BtnConsultar_Click(sender As Object, e As System.EventArgs) Handles BtnConsultar.Click
|
|
CargaDatos(NowADS())
|
|
End Sub
|
|
|
|
Private Sub CargaDatos(NowEmpresa As DateTime)
|
|
|
|
DTTraslados = New DataTable
|
|
|
|
Dim Folio, RFC, Proveedor As String
|
|
Folio = If(TxtFolio.Text.Trim.Length > 0, String.Format("%{0}%", TxtFolio.Text.Trim.ToUpper), "-1")
|
|
RFC = "-1" 'If(TxtRFC.Text.Trim.Length > 0, TxtRFC.Text.Trim, "-1")
|
|
Proveedor = If(TxtProveedor.Text.Trim.Length > 0, String.Format("%{0}%", TxtProveedor.Text.Trim.ToUpper.Replace(" ", "%")), "-1")
|
|
|
|
UsuarioActual.Sesion("eFact-Proveedor") = TxtProveedor.Text.Trim
|
|
If Folio = "" Then UsuarioActual.Sesion("eFact-FI") = txtFechaI.Text
|
|
If Folio = "" Then UsuarioActual.Sesion("eFact-FF") = txtFechaF.Text
|
|
Dim FechaI, FechaF As Date
|
|
FechaI = txtFechaI.Text.ToDate
|
|
FechaF = txtFechaF.Text.ToDate
|
|
If Folio <> "-1" Then
|
|
FechaI = MinFecha
|
|
FechaF = MaxFecha
|
|
txtFechaI.Text = MinFecha.ToString
|
|
txtFechaF.Text = NowEmpresa.ToShortDateString
|
|
End If
|
|
|
|
Dim DtPagos As DataTable = Nothing
|
|
'Dim DTTrasaldos As DataTable = Nothing
|
|
|
|
Dim ObjDatos As New ClsCompras
|
|
If ObjDatos.GetFacturas(-1, Folio, FechaI, FechaF, RFC, Proveedor, DdlValidado.SelectedValue.ToEntero, DdlResponsable.SelectedValue.ToEntero, DdlClasificacionProv.SelectedValue.ToEntero, DdlCveTipoProveedor.SelectedValue.ToEntero, DdlTipoComprobante.SelectedValue.ToString, UsuarioActual.CveEmpresa) Then
|
|
|
|
If ObjDatos.DtResultados.Rows.Count > 0 Then
|
|
|
|
GvD.DataSource = ObjDatos.DtResultados.FiltraParametros("TipoComprobante <> 'P' and TipoComprobante <> 'T' ") '.AsEnumerable().Take(100).CopyToDataTable()
|
|
DtPagos = ObjDatos.DtResultados.FiltraParametros("TipoComprobante = 'P'")
|
|
|
|
|
|
End If
|
|
End If
|
|
LblRegistros.Text = String.Format("{0} Registros", ObjDatos.DtResultados.FiltraParametros("TipoComprobante <> 'P' and TipoComprobante <> 'T' ").Rows.Count.ToString("N0"))
|
|
LblTotalPagos.Text = String.Format("{0} Pagos", ObjDatos.DtResultados.FiltraParametros("TipoComprobante = 'P'").Rows.Count.ToString("N0"))
|
|
|
|
If UsuarioActual.Empresa.Funcionalidad(161) = "1" Then
|
|
TabTraslados.Visible = True
|
|
'If ObjDatos.GetFacturas(-1, Folio, FechaI, FechaF, RFC, Proveedor, DdlValidado.SelectedValue.ToEntero, DdlResponsable.SelectedValue.ToEntero, DdlClasificacionProv.SelectedValue.ToEntero, DdlCveTipoProveedor.SelectedValue.ToEntero, DdlTipoComprobante.SelectedValue.ToString, UsuarioActual.CveEmpresa, Opcion:=2) Then
|
|
|
|
' If ObjDatos.DtResultados.Rows.Count > 0 Then
|
|
' DTTraslados = ObjDatos.DtResultados.FiltraParametros("TipoComprobante = 'T'")
|
|
' End If
|
|
|
|
'End If
|
|
DTTraslados = ObjDatos.DtResultados.FiltraParametros("TipoComprobante = 'T'")
|
|
End If
|
|
LblTotalTraslados.Text = String.Format("{0} Traslados", ObjDatos.DtResultados.FiltraParametros("TipoComprobante = 'T'").Rows.Count.ToString("N0"))
|
|
|
|
If DtPagos IsNot Nothing AndAlso DtPagos.Rows.Count > 0 Then
|
|
GvPagos.DataSource = DtPagos
|
|
End If
|
|
|
|
If DTTraslados IsNot Nothing AndAlso DTTraslados.Rows.Count > 0 Then
|
|
GvTraslados.DataSource = DTTraslados
|
|
End If
|
|
|
|
ObjDatos.Dispose()
|
|
|
|
GvD.DataBind()
|
|
GvPagos.DataBind()
|
|
GvTraslados.DataBind()
|
|
|
|
UpPagos.Update()
|
|
UpDatos.Update()
|
|
UpTraslados.Update()
|
|
UPRegistros.Update()
|
|
|
|
End Sub
|
|
|
|
Protected Sub LnkExportar_Click(sender As Object, e As EventArgs) Handles LnkExportar.Click
|
|
GenerarPDF(NowADS(), "Excel")
|
|
End Sub
|
|
|
|
Protected Sub ImgRefresh_Click(sender As Object, e As EventArgs) Handles ImgRefresh.Click
|
|
|
|
If VerificaCorreo() Then
|
|
CargaDatos(NowADS())
|
|
End If
|
|
|
|
End Sub
|
|
|
|
Private Function VerificaCorreo(Optional ValidaRowCount As Boolean = False) As Boolean
|
|
Dim Retorno As Boolean = False
|
|
|
|
Dim ObjProcess As Process = Nothing
|
|
Dim Mensajes As String = ""
|
|
Dim error1 As Boolean = False
|
|
Dim CountProcesados As Integer = 0
|
|
|
|
Try
|
|
ObjProcess = New Process()
|
|
ObjProcess.StartInfo.RedirectStandardOutput = True
|
|
ObjProcess.StartInfo.FileName = Ejecutable
|
|
ObjProcess.StartInfo.Arguments = $"--mod eFacturas --e {UsuarioActual.CveEmpresa} --c "
|
|
ObjProcess.StartInfo.UseShellExecute = False
|
|
ObjProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal
|
|
ObjProcess.Start()
|
|
|
|
|
|
Dim myStreamReader As StreamReader = ObjProcess.StandardOutput
|
|
|
|
'Read the standard output of the spawned process.
|
|
Mensajes = myStreamReader.ReadLine()
|
|
If Mensajes.Length > 0 Then
|
|
|
|
Dim msgs As String() = Mensajes.Split("|"c)
|
|
Dim NFacturas As Integer = 0
|
|
|
|
If msgs.Length >= 2 Then
|
|
Try
|
|
NFacturas = msgs(0).ToEntero
|
|
CountProcesados = msgs(0).ToEntero
|
|
Mensajes = $"La actualización se realizó correctamente. <br> Facturas agregadas: { NFacturas }"
|
|
Catch ex As Exception
|
|
NFacturas = 0
|
|
Mensajes = "La actualización se realizó correctamente"
|
|
End Try
|
|
Else
|
|
Mensajes = "La actualización se realizó correctamente"
|
|
End If
|
|
|
|
LnkNoRecibidas_Click(LnkNoRecibias, EventArgs.Empty, ValidaRowCount:=ValidaRowCount)
|
|
|
|
'Else
|
|
' Dim Str As New StringBuilder
|
|
' Dim conta As Integer = 1
|
|
' Str.Append("Se encontraron las siguientes facturas con problema:<br/> <table width='750px'><tr class='Titulos'><td>Serie</td><td>Folio</td><td>Fecha</td><td>Proveedor</td><td>Importe</td><td>Motivo</td></tr>")
|
|
' Dim ARR As String() = Mensajes.Split("&"c)
|
|
' Dim ArrDetalle As String()
|
|
' For Each d As String In ARR
|
|
' Str.Append("<tr>")
|
|
' ArrDetalle = d.Split("|"c)
|
|
' For Each det As String In ArrDetalle
|
|
' Str.AppendFormat("<td class='{0}'>{1}</td>", If(conta Mod 2 = 0, "TextoAlterno", "Texto"), det)
|
|
' Next
|
|
' Str.Append("</tr>")
|
|
' conta += 1
|
|
' Next
|
|
' Str.Append("</table>")
|
|
' Mensajes = Str.ToString
|
|
End If
|
|
ObjProcess.WaitForExit()
|
|
ObjProcess.Close()
|
|
Retorno = True
|
|
Catch ex As Exception
|
|
error1 = True
|
|
OnError("Ocurrió un error al ejecutar el actualizador.", ex)
|
|
End Try
|
|
|
|
|
|
LblFacturasProcesadasCount.Text = "Procesados:" & CountProcesados
|
|
RegistraScript("$('#ModalBitacoraEfacturas').modal()")
|
|
CargaDatosBitacora()
|
|
|
|
'If Not error1 Then Alert(Mensajes, TipoMensaje.MsgInformacion)
|
|
|
|
|
|
Return Retorno
|
|
End Function
|
|
|
|
Protected Sub BtnBuscarBitacora_Click(sender As Object, e As EventArgs) Handles BtnBuscarBitacora.Click
|
|
CargaDatosBitacora()
|
|
End Sub
|
|
|
|
|
|
Protected Sub LnkBitacoraFacturas_Click(sender As Object, e As EventArgs)
|
|
|
|
RegistraScript("$('#ModalBitacoraEfacturas').modal()")
|
|
CargaDatosBitacora()
|
|
End Sub
|
|
|
|
|
|
Private Sub CargaDatosBitacora()
|
|
|
|
LblFacturasProcesadasCount.Text = ""
|
|
|
|
Dim ObjCompras As New ClsCompras
|
|
|
|
If ObjCompras.GetFacturasBitacoraGet(TxtFechaBitInicio.Text.ToDate, TxtFechaBitFin.Text.ToDate, UsuarioActual.CveEmpresa) Then
|
|
GvBitacoraEfacturas.DataSource = ObjCompras.DtResultados
|
|
Else
|
|
GvBitacoraEfacturas.DataSource = Nothing
|
|
End If
|
|
|
|
ObjCompras.Dispose()
|
|
GvBitacoraEfacturas.DataBind()
|
|
UpModalBitacoraEfacturas.Update()
|
|
|
|
End Sub
|
|
|
|
#Region "G V D A T O S"
|
|
Protected Sub GvDatos_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvD.RowDataBound
|
|
|
|
If e.Row.RowType = DataControlRowType.Header Then
|
|
e.Row.Cells(5).Attributes.Add("data-tipodato", "numeric")
|
|
End If
|
|
|
|
If e.Row.RowType = DataControlRowType.DataRow Then
|
|
e.Row.FindControl("lnkRegenerarPDF").Visible = True ' (UsuarioActual.CveRol = 1)
|
|
'e.Row.FindControl("lnkDownPdf").Visible = (UsuarioActual.CveRol = 1)
|
|
'e.Row.FindControl("lnkXML").Visible = (UsuarioActual.CveRol = 1)
|
|
Select Case e.Row.DBCampo("TipoComprobante")
|
|
Case "I"
|
|
e.Row.FCLabel("LtTipoComprobante").Text = "Ingreso"
|
|
e.Row.FCLabel("LtTipoComprobante").CssClass = "label label-sm label-success"
|
|
e.Row.FCLabel("LtTipoComprobante").Attributes.Add("data-toggle", "tooltip")
|
|
e.Row.FCLabel("LtTipoComprobante").Attributes.Add("title", "Ingreso")
|
|
Case "E"
|
|
e.Row.FCLabel("LtTipoComprobante").Text = "Egreso"
|
|
e.Row.FCLabel("LtTipoComprobante").CssClass = "label label-sm label-warning"
|
|
e.Row.FCLabel("LtTipoComprobante").Attributes.Add("data-toggle", "tooltip") '
|
|
e.Row.FCLabel("LtTipoComprobante").Attributes.Add("title", "Egreso")
|
|
Case "P"
|
|
e.Row.FCLabel("LtTipoComprobante").Text = "Pago"
|
|
e.Row.FCLabel("LtTipoComprobante").CssClass = "label label-sm label-primary"
|
|
e.Row.FCLabel("LtTipoComprobante").Attributes.Add("data-toggle", "tooltip")
|
|
e.Row.FCLabel("LtTipoComprobante").Attributes.Add("title", "Complemento Pago")
|
|
|
|
End Select
|
|
|
|
e.Row.Cells(3).Attributes.Add("data-order", e.Row.DBCampo("FechaFactura").ToDate.Ticks.ToString)
|
|
|
|
'e.Row.Cells(4).Attributes.Add("data-order", Convert.ToInt64(e.Row.DBCampo("Total").ToDecimal).ToString.PadLeft(10, "0"c))
|
|
|
|
If File.Exists(String.Format("{0}{1}\{2}", Destino, e.Row.DBCampo("RFCDe"), e.Row.DBCampo("XML"))) Then
|
|
e.Row.FCLiteral("LtlXML").Text = String.Format("<a class=""Texto"" href=""/Compras/PopUpVerFactura.aspx?RFC={0}&File={1}"">Ver</a>", HttpUtility.UrlEncode(e.Row.DBCampo("RFCDe")), HttpUtility.UrlEncode(e.Row.DBCampo("XML")))
|
|
If e.Row.DBCampo("TipoComprobante") = "P" Then
|
|
e.Row.FCLinkButton("LnkAgregarPago").Visible = True
|
|
End If
|
|
Else
|
|
e.Row.FCLiteral("LtlXML").Text = "N/D"
|
|
If e.Row.DBCampo("TipoComprobante") = "P" Then
|
|
e.Row.FCLinkButton("LnkAgregarPago").Visible = False
|
|
End If
|
|
End If
|
|
|
|
If File.Exists(String.Format("{0}{1}/{2}", Destino, e.Row.DBCampo("RFCDe"), e.Row.DBCampo("PDF"))) Then
|
|
e.Row.FCLiteral("LtlPDF").Text = String.Format("<a class=""Texto"" href=""/Compras/PopUpVerFactura.aspx?RFC={0}&File={1}"">Ver</a>", HttpUtility.UrlEncode(e.Row.DBCampo("RFCDe")), HttpUtility.UrlEncode(e.Row.DBCampo("PDF")))
|
|
Else
|
|
e.Row.FCLiteral("LtlPDF").Text = "N/D"
|
|
End If
|
|
|
|
If e.Row.DBCampo("FueValidado").Contiene("1", "2", "3") Then
|
|
e.Row.FCLinkButton("ImgValidarCFDi").Visible = False
|
|
e.Row.FCLiteral("LtlValidado").Visible = True
|
|
If e.Row.DBCampo("FueValidado") = "2" Then
|
|
e.Row.FCLiteral("LtlValidado").Text = "Cancelada"
|
|
e.Row.ForeColor = System.Drawing.Color.Red
|
|
e.Row.FCHyperLink("HplProveedor").ForeColor = System.Drawing.Color.Red
|
|
ElseIf e.Row.DBCampo("FueValidado") = "3" Then
|
|
e.Row.FCLiteral("LtlValidado").Text = "Omitida"
|
|
e.Row.ForeColor = System.Drawing.Color.Gray
|
|
e.Row.FCHyperLink("HplProveedor").ForeColor = System.Drawing.Color.Gray
|
|
End If
|
|
Else
|
|
If e.Row.DBCampo("TipoFactura") = "CFD" Then
|
|
e.Row.FCLinkButton("ImgValidarCFDi").CommandName = "ValidarCFD"
|
|
e.Row.FCLinkButton("ImgValidarCFDi").OnClientClick = "return confirm('La factura se validó en el sitio del SAT de comprobantes fiscales?');"
|
|
End If
|
|
e.Row.FCLinkButton("ImgValidarCFDi").Visible = True
|
|
e.Row.FCLiteral("LtlValidado").Visible = False
|
|
|
|
End If
|
|
If e.Row.DBCampo("CveCompra") <> "" Then
|
|
e.Row.FCLiteral("LtlFolio").Text = String.Format("<a class=""Texto"" style=""cursor:pointer;text-decoration: underline;"" href='/Compras/Compras.aspx?CveCompra={0}' target='_blank' rel='opener' );"">{1}</a>", e.Row.DBCampo("CveCompra"), e.Row.DBCampo("SerieFolio")) '1\Compras\GAPC480413QL3\A-69.xml
|
|
e.Row.FCLinkButton("imgD").Visible = False
|
|
End If
|
|
|
|
If e.Row.DBCampo("CveProveedor") = "" Then
|
|
e.Row.FCHyperLink("HplProv").Visible = True
|
|
e.Row.FCHyperLink("HplProv").NavigateUrl = String.Format("/Compras/Proveedores.aspx?CveFactura={0}", e.Row.DBCampo("CveFactura"))
|
|
|
|
Else
|
|
|
|
Dim BloquePorComplemento As Integer = e.Row.DataKey("BloquePorComplemento").ToEntero
|
|
|
|
e.Row.FCHyperLink("HplProveedor").NavigateUrl = String.Format("/Compras/Proveedores.aspx?CveProveedor={0}", e.Row.DBCampo("CveProveedor"))
|
|
|
|
If e.Row.DBCampo("CveCompra") = "" AndAlso (e.Row.DBCampo("FueValidado") = "1" OrElse UsuarioActual.Empresa.Funcionalidad(529) = "1") Then ' OrElse UsuarioActual.CveEmpresa = 66
|
|
|
|
If e.Row.DBCampo("TipoComprobante") = "P" Then
|
|
e.Row.FCHyperLink("HplAgregar").Visible = False
|
|
Else
|
|
e.Row.FCHyperLink("HplAgregar").NavigateUrl = String.Format("/Compras/Compras.aspx?CveFactura={0}&RFC={1}", e.Row.DBCampo("CveFactura"), e.Row.DBCampo("RFCDe"))
|
|
|
|
If BloquePorComplemento > 0 Then
|
|
e.Row.FCHyperLink("HplAgregar").Enabled = False
|
|
e.Row.FCHyperLink("HplAgregar").Attributes.Add("title", "Bloqueo por complemento")
|
|
End If
|
|
|
|
End If
|
|
|
|
Else
|
|
e.Row.FCHyperLink("HplAgregar").Visible = False
|
|
End If
|
|
End If
|
|
|
|
If e.Row.RowState = DataControlRowState.Edit OrElse e.Row.RowState = 5 Then
|
|
End If
|
|
|
|
|
|
If Not e.Row.DataKey("CveProveedor").ToEntero > 0 Then
|
|
e.Row.FCCheckBox("chkRegistraFactura").Visible = False
|
|
End If
|
|
|
|
If UsuarioActual.CveEmpresa.Contiene(13, 83) AndAlso UsuarioActual.CveUsuario <> 1803 Then
|
|
Dim Fecha28Dic As Date = New Date(2024, 12, 28)
|
|
If NowADS() >= Fecha28Dic AndAlso e.Row.DBCampo("FechaFactura").ToDate.Year < 2025 Then
|
|
e.Row.FCHyperLink("HplAgregar").Visible = False
|
|
End If
|
|
End If
|
|
|
|
End If
|
|
End Sub
|
|
Protected Sub GvDatos_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GvD.RowUpdating
|
|
Dim ObjDatos As New ClsCompras
|
|
Dim FueValidado As Integer = 0
|
|
If GvD.Rows(e.RowIndex).FCCheckBox("ChkFueValidado").Checked Then FueValidado = 1
|
|
If ObjDatos.UpdateEstatus(FueValidado, GvD.DataKeys(e.RowIndex).Value.ToString.ToEntero, UsuarioActual.CveEmpresa) Then
|
|
GvD.EditIndex = -1
|
|
BtnConsultar_Click(sender, e)
|
|
End If
|
|
ObjDatos.Dispose()
|
|
|
|
|
|
CargaDatos(NowADS())
|
|
End Sub
|
|
Protected Sub GvDatos_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GvD.RowCancelingEdit
|
|
GvD.EditIndex = -1
|
|
CargaDatos(NowADS())
|
|
End Sub
|
|
|
|
|
|
Protected Sub imgD_Click(sender As Object, e As EventArgs)
|
|
Dim gvRow As GridViewRow = DirectCast((DirectCast(sender, LinkButton)).NamingContainer, GridViewRow)
|
|
CveFactura = gvRow.DataKey("CveFactura").ToString.ToEntero
|
|
Folio1 = gvRow.DataKey("SerieFolio").ToString
|
|
Proveedor = gvRow.DataKey("NombreProveedor").ToString
|
|
TxtDescripcion.Text = ""
|
|
RegistraScript("$('#divDescripcion').modal()")
|
|
UpDescripcion.Update()
|
|
End Sub
|
|
|
|
Protected Sub GvDatos_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GvD.RowEditing
|
|
GvD.EditIndex = e.NewEditIndex
|
|
CargaDatos(NowADS())
|
|
End Sub
|
|
|
|
Protected Sub GvDatos_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GvD.RowCommand
|
|
Dim ImgBtn As LinkButton = DirectCast(e.CommandSource, LinkButton)
|
|
Dim GvRow As GridViewRow = DirectCast(ImgBtn.BindingContainer, GridViewRow)
|
|
Dim ObjDatos As New ClsCompras
|
|
Dim Correcto As Boolean = False
|
|
|
|
Select Case e.CommandName
|
|
Case "ValidarCFDi"
|
|
Dim ObjValidacion As New ClsValidaCFDi(GvRow.DataKey("UUID"), GvRow.DataKey("RFCDe"), GvRow.DataKey("RFCPara"), GvRow.DataKey("Total").ToDecimal)
|
|
If ObjValidacion.EsValida > 0 Then
|
|
If ObjValidacion.EsValida = 2 Then
|
|
Alert("La factura está cancelada ante el SAT.", TipoMensaje.MsgInformacion)
|
|
End If
|
|
Correcto = ObjDatos.UpdateEstatus(ObjValidacion.EsValida, GvRow.DataKey("CveFactura").ToEntero, UsuarioActual.CveEmpresa)
|
|
Else
|
|
Alert("La Factura no se pudo validar.", TipoMensaje.MsgAdvertencia)
|
|
End If
|
|
ObjValidacion.Dispose()
|
|
Case "ValidarCFD"
|
|
Correcto = ObjDatos.UpdateEstatus(1, GvRow.DataKey("CveFactura").ToEntero, UsuarioActual.CveEmpresa)
|
|
|
|
Case "Omitir"
|
|
Correcto = ObjDatos.UpdateEstatus(3, GvRow.DataKey("CveFactura").ToEntero, UsuarioActual.CveEmpresa)
|
|
End Select
|
|
|
|
ObjDatos.Dispose()
|
|
If Correcto Then
|
|
CargaDatos(NowADS())
|
|
End If
|
|
|
|
End Sub
|
|
#End Region
|
|
|
|
#Region "G V P A G O S"
|
|
Protected Sub GvPagos_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvPagos.RowDataBound
|
|
If e.Row.RowType = DataControlRowType.DataRow Then
|
|
|
|
If e.Row.DBCampo("TipoComprobante") = "P" Then
|
|
e.Row.FCLabel("LtTipoComprobante").Text = "Pago"
|
|
e.Row.FCLabel("LtTipoComprobante").CssClass = "label label-sm label-primary"
|
|
e.Row.FCLabel("LtTipoComprobante").Attributes.Add("data-toggle", "tooltip")
|
|
e.Row.FCLabel("LtTipoComprobante").Attributes.Add("title", "Complemento Pago")
|
|
End If
|
|
|
|
e.Row.Cells(2).Attributes.Add("data-order", e.Row.DBCampo("FechaFactura").ToDate.Ticks.ToString)
|
|
|
|
Dim RutaXML As String = String.Format("{0}{1}\{2}", Destino, e.Row.DBCampo("RFCDe"), e.Row.DBCampo("XML"))
|
|
|
|
If File.Exists(String.Format("{0}{1}\{2}", Destino, e.Row.DBCampo("RFCDe"), e.Row.DBCampo("XML"))) Then
|
|
e.Row.FCLiteral("LtlXML").Text = String.Format("<a class=""Texto"" href=""/Compras/PopUpVerFactura.aspx?RFC={0}&File={1}"">Ver</a>", HttpUtility.UrlEncode(e.Row.DBCampo("RFCDe")), HttpUtility.UrlEncode(e.Row.DBCampo("XML")))
|
|
If e.Row.DBCampo("TipoComprobante") = "P" And e.Row.DBCampo("FueValidado") = "1" Then
|
|
e.Row.FCLinkButton("LnkAgregarPagoP").Visible = True
|
|
End If
|
|
Else
|
|
e.Row.FCLiteral("LtlXML").Text = "N/D" ' String.Format("{0}{1}\{2}", Destino, e.Row.DBCampo("RFCDe"), e.Row.DBCampo("XML")) '
|
|
If e.Row.DBCampo("TipoComprobante") = "P" Then
|
|
e.Row.FCLinkButton("LnkAgregarPagoP").Visible = False
|
|
End If
|
|
End If
|
|
|
|
If File.Exists(String.Format("{0}{1}/{2}", Destino, e.Row.DBCampo("RFCDe"), e.Row.DBCampo("PDF"))) Then
|
|
e.Row.FCLiteral("LtlPDF").Text = String.Format("<a class=""Texto"" href=""/Compras/PopUpVerFactura.aspx?RFC={0}&File={1}"">Ver</a>", HttpUtility.UrlEncode(e.Row.DBCampo("RFCDe")), HttpUtility.UrlEncode(e.Row.DBCampo("PDF")))
|
|
Else
|
|
e.Row.FCLiteral("LtlPDF").Text = "N/D" ' String.Format("{0}{1}/{2}", Destino, e.Row.DBCampo("RFCDe"), e.Row.DBCampo("PDF"))
|
|
End If
|
|
|
|
If e.Row.DBCampo("FueValidado").Contiene("1", "2", "3") Then
|
|
e.Row.FCLinkButton("ImgValidarCFDi").Visible = False
|
|
e.Row.FCLiteral("LtlValidado").Visible = True
|
|
If e.Row.DBCampo("FueValidado") = "2" Then
|
|
e.Row.FCLiteral("LtlValidado").Text = "Cancelada"
|
|
e.Row.ForeColor = System.Drawing.Color.Red
|
|
e.Row.FCHyperLink("HplProveedor").ForeColor = System.Drawing.Color.Red
|
|
ElseIf e.Row.DBCampo("FueValidado") = "3" Then
|
|
e.Row.FCLiteral("LtlValidado").Text = "Omitida"
|
|
e.Row.ForeColor = System.Drawing.Color.Gray
|
|
e.Row.FCHyperLink("HplProveedor").ForeColor = System.Drawing.Color.Gray
|
|
End If
|
|
Else
|
|
If e.Row.DBCampo("TipoFactura") = "CFD" Then
|
|
e.Row.FCLinkButton("ImgValidarCFDi").CommandName = "ValidarCFD"
|
|
e.Row.FCLinkButton("ImgValidarCFDi").OnClientClick = "return confirm('La factura se validó en el sitio del SAT de comprobantes fiscales?');"
|
|
End If
|
|
e.Row.FCLinkButton("ImgValidarCFDi").Visible = True
|
|
e.Row.FCLiteral("LtlValidado").Visible = False
|
|
|
|
End If
|
|
If e.Row.DBCampo("CveCompra") <> "" Then
|
|
e.Row.FCLiteral("LtlFolio").Text = String.Format("<a class=""Texto"" style=""cursor:pointer;text-decoration: underline;"" href='/Compras/Compras.aspx?CveCompra={0}' target='_blank' rel='opener');"">{1}</a>", e.Row.DBCampo("CveCompra"), e.Row.DBCampo("SerieFolio")) '1\Compras\GAPC480413QL3\A-69.xml
|
|
End If
|
|
|
|
If e.Row.DBCampo("CveProveedor") = "" Then
|
|
e.Row.FCHyperLink("HplProv").Visible = True
|
|
e.Row.FCHyperLink("HplProv").NavigateUrl = String.Format("/Compras/Proveedores.aspx?CveFactura={0}", e.Row.DBCampo("CveFactura"))
|
|
|
|
Else
|
|
e.Row.FCHyperLink("HplProveedor").NavigateUrl = String.Format("/Compras/Proveedores.aspx?CveProveedor={0}", e.Row.DBCampo("CveProveedor"))
|
|
|
|
If e.Row.DBCampo("CveCompra") = "" AndAlso (e.Row.DBCampo("FueValidado") = "1") Then ' OrElse UsuarioActual.CveEmpresa = 66
|
|
'
|
|
If e.Row.DBCampo("TipoComprobante") = "P" Then
|
|
e.Row.FCHyperLink("HplAgregarP").Visible = False
|
|
Else
|
|
e.Row.FCHyperLink("HplAgregarP").NavigateUrl = String.Format("/Compras/Compras.aspx?CveFactura={0}&RFC={1}", e.Row.DBCampo("CveFactura"), e.Row.DBCampo("RFCDe"))
|
|
End If
|
|
|
|
|
|
Else
|
|
'si ya tiene cvecompra es que ya está validada
|
|
e.Row.FCHyperLink("HplAgregarP").Visible = False
|
|
End If
|
|
|
|
End If
|
|
|
|
|
|
Dim CveComplementoPagoCompra As Integer = e.Row.DataKey("CveComplementoPagoCompra").ToString.ToEntero
|
|
|
|
|
|
If CveComplementoPagoCompra > 0 Then
|
|
e.Row.FCLinkButton("LnkAgregarPagoP").CssClass = "btn btn-sm green"
|
|
e.Row.FCLinkButton("LnkAgregarPagoP").Text = "<i class='fa fa-info' ></i>"
|
|
'e.Row.FCLinkButton("LnkAgregarPagoP").ToolTip = "Ver vinculación"
|
|
e.Row.FCLinkButton("LnkAgregarPagoP").Attributes.Add("Title", "Ver vinculación")
|
|
Else
|
|
e.Row.FCLinkButton("LnkAgregarPagoP").CssClass = "btn btn-sm blue"
|
|
e.Row.FCLinkButton("LnkAgregarPagoP").Text = "<i class='fa fa-check'></i>"
|
|
'e.Row.FCLinkButton("LnkAgregarPagoP").ToolTip = "Vincular Pago"
|
|
e.Row.FCLinkButton("LnkAgregarPagoP").Attributes.Add("Title", "Vincular Pago")
|
|
End If
|
|
|
|
End If
|
|
End Sub
|
|
Protected Sub GvPagos_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GvPagos.RowUpdating
|
|
Dim ObjDatos As New ClsCompras
|
|
Dim FueValidado As Integer = 0
|
|
If GvPagos.Rows(e.RowIndex).FCCheckBox("ChkFueValidado").Checked Then FueValidado = 1
|
|
If ObjDatos.UpdateEstatus(FueValidado, GvD.DataKeys(e.RowIndex).Value.ToString.ToEntero, UsuarioActual.CveEmpresa) Then
|
|
GvPagos.EditIndex = -1
|
|
End If
|
|
ObjDatos.Dispose()
|
|
CargaDatos(NowADS())
|
|
End Sub
|
|
Protected Sub GvPagos_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GvPagos.RowCancelingEdit
|
|
GvPagos.EditIndex = -1
|
|
CargaDatos(NowADS())
|
|
End Sub
|
|
Protected Sub GvPagos_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GvPagos.RowEditing
|
|
GvPagos.EditIndex = e.NewEditIndex
|
|
CargaDatos(NowADS())
|
|
End Sub
|
|
Protected Sub imgDP_Click(sender As Object, e As EventArgs)
|
|
Dim gvRow As GridViewRow = DirectCast((DirectCast(sender, LinkButton)).NamingContainer, GridViewRow)
|
|
CveFactura = gvRow.DataKey("CveFactura").ToString.ToEntero
|
|
Folio1 = gvRow.DataKey("SerieFolio").ToString
|
|
Proveedor = gvRow.DataKey("NombreProveedor").ToString
|
|
TxtDescripcion.Text = ""
|
|
RegistraScript("$('#divDescripcionPago').modal()")
|
|
UpDescripcionPago.Update()
|
|
End Sub
|
|
|
|
Protected Sub GvPagos_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GvPagos.RowCommand
|
|
Dim ImgBtn As LinkButton = DirectCast(e.CommandSource, LinkButton)
|
|
Dim GvRow As GridViewRow = DirectCast(ImgBtn.BindingContainer, GridViewRow)
|
|
Dim ObjDatos As New ClsCompras
|
|
Dim Correcto As Boolean = False
|
|
|
|
Select Case e.CommandName
|
|
Case "ValidarCFDi"
|
|
Dim ObjValidacion As New ClsValidaCFDi(GvRow.DataKey("UUID"), GvRow.DataKey("RFCDe"), GvRow.DataKey("RFCPara"), 0)
|
|
If ObjValidacion.EsValida > 0 Then
|
|
If ObjValidacion.EsValida = 2 Then
|
|
Alert("La factura está cancelada ante el SAT.", TipoMensaje.MsgInformacion)
|
|
End If
|
|
Correcto = ObjDatos.UpdateEstatus(ObjValidacion.EsValida, GvRow.DataKey("CveFactura").ToEntero, UsuarioActual.CveEmpresa)
|
|
Else
|
|
Alert("La Factura no se pudo validar.", TipoMensaje.MsgAdvertencia)
|
|
End If
|
|
ObjValidacion.Dispose()
|
|
Case "ValidarCFD"
|
|
Correcto = ObjDatos.UpdateEstatus(1, GvRow.DataKey("CveFactura").ToEntero, UsuarioActual.CveEmpresa)
|
|
|
|
Case "Omitir"
|
|
Correcto = ObjDatos.UpdateEstatus(3, GvRow.DataKey("CveFactura").ToEntero, UsuarioActual.CveEmpresa)
|
|
End Select
|
|
|
|
ObjDatos.Dispose()
|
|
If Correcto Then
|
|
CargaDatos(NowADS())
|
|
End If
|
|
End Sub
|
|
#End Region
|
|
Protected Sub ImgCFDiMasivo_Click(sender As Object, e As EventArgs) Handles LnkCFDiMasivo.Click
|
|
|
|
Dim ErrorTrans As Boolean = False
|
|
If Tab.ActiveTabIndex = 0 Then
|
|
For Each GvRow As GridViewRow In GvD.Rows
|
|
If GvRow.DataKey("TipoFactura") = "CFDi" AndAlso GvRow.DataKey("FueValidado").Contiene("0", "1") Then
|
|
Dim ObjValidacion As New ClsValidaCFDi(GvRow.DataKey("UUID"), GvRow.DataKey("RFCDe"), GvRow.DataKey("RFCPara"), GvRow.DataKey("Total").ToDecimal)
|
|
If ObjValidacion.EsValida > 0 Then
|
|
Dim ObjDatos As New ClsCompras
|
|
If Not ObjDatos.UpdateEstatus(ObjValidacion.EsValida, GvRow.DataKey("CveFactura").ToEntero, UsuarioActual.CveEmpresa) Then
|
|
ErrorTrans = True
|
|
End If
|
|
ObjDatos.Dispose()
|
|
End If
|
|
ObjValidacion.Dispose()
|
|
End If
|
|
Next
|
|
ElseIf Tab.ActiveTabIndex = 1 Then
|
|
For Each GvRow As GridViewRow In GvPagos.Rows
|
|
If GvRow.DataKey("TipoFactura") = "CFDi" AndAlso GvRow.DataKey("FueValidado").Contiene("0", "1") Then
|
|
Dim ObjValidacion As New ClsValidaCFDi(GvRow.DataKey("UUID"), GvRow.DataKey("RFCDe"), GvRow.DataKey("RFCPara"), 0)
|
|
If ObjValidacion.EsValida > 0 Then
|
|
Dim ObjDatos As New ClsCompras
|
|
If Not ObjDatos.UpdateEstatus(ObjValidacion.EsValida, GvRow.DataKey("CveFactura").ToEntero, UsuarioActual.CveEmpresa) Then
|
|
ErrorTrans = True
|
|
End If
|
|
ObjDatos.Dispose()
|
|
End If
|
|
ObjValidacion.Dispose()
|
|
End If
|
|
Next
|
|
End If
|
|
If Not ErrorTrans Then
|
|
|
|
Alert("La verificación masiva ha terminado", TipoMensaje.MsgInformacion)
|
|
CargaDatos(NowADS())
|
|
|
|
End If
|
|
|
|
End Sub
|
|
Protected Sub LnkNoRecibidas_Click(sender As Object, e As EventArgs, Optional ValidaRowCount As Boolean = False) Handles LnkNoRecibias.Click
|
|
Dim DtNoRecibidas As New DataTable
|
|
Dim Ruta As String = String.Format("{0}Compras\NoRecibidas-{1}.xml", UsuarioActual.Empresa.Ruta, UsuarioActual.CveEmpresa)
|
|
Dim Str As New StringBuilder
|
|
If IO.File.Exists(Ruta) Then
|
|
DtNoRecibidas.ReadXml(Ruta)
|
|
|
|
Dim conta As Integer = 1
|
|
Str.Append("Se procesó la información con la siguiente información:<br/> <table width='900px'><tr class='Titulos'><td>Serie</td><td>Folio</td><td>Fecha</td><td>Proveedor</td><td>Importe</td><td>Motivo</td><td>Correo</td><td>F. Recepción</td></tr>")
|
|
|
|
For Each dr As DataRow In DtNoRecibidas.FiltraParametros("", "Fecha DESC").Rows
|
|
|
|
Str.AppendFormat("<tr class='{0}'>", If(conta Mod 2 = 0, "TextoAlterno", "Texto"))
|
|
|
|
Str.AppendFormat("<td style='width:100px'>{0}</td>", dr("Serie"))
|
|
Str.AppendFormat("<td style='width:80px'>{0}</td>", dr("Folio"))
|
|
Str.AppendFormat("<td style='width:400px'>{0}</td>", If(dr("Fecha").ToString <> "", dr("Fecha").ToString.ToDate.ToShortDateString, ""))
|
|
Str.AppendFormat("<td style='width:80px'>{0}</td>", dr("Proveedor"))
|
|
Str.AppendFormat("<td style='width:40px'>{0}</td>", dr("Importe").ToString.ToDouble.FormatoNumero)
|
|
Str.AppendFormat("<td style='width:40px'>{0}</td>", dr("Motivo"))
|
|
Str.AppendFormat("<td style='width:500px'>{0}</td>", If(dr("Correo").ToString.Length > 20, dr("Correo").ToString.Substring(0, 20), dr("Correo").ToString()))
|
|
Str.AppendFormat("<td style='width:80px'>{0}</td>", dr("FechaRecepcion").ToString.ToDate.ToShortDateString)
|
|
|
|
Str.Append("</tr>")
|
|
conta += 1
|
|
Next
|
|
Str.Append("</table>")
|
|
Else
|
|
Str.Append("No se encontraron facturas pendientes de recibir.")
|
|
End If
|
|
|
|
If ValidaRowCount Then 'si las facturas no recividas son matores a cero se muestra el mensaje
|
|
If DtNoRecibidas.Rows.Count > 0 Then
|
|
Alert(Str.ToString, TipoMensaje.MsgInformacion)
|
|
End If
|
|
Else
|
|
Alert(Str.ToString, TipoMensaje.MsgInformacion)
|
|
End If
|
|
|
|
DtNoRecibidas.Dispose()
|
|
|
|
CargaDatos(NowADS())
|
|
End Sub
|
|
|
|
#Region "G E N E R A P D F "
|
|
Private Sub GenerarPDF(Fecha As DateTime, Optional Tipo As String = "PDF")
|
|
Dim ObjDatos As New ClsCompras
|
|
Dim FechaI As String = txtFechaI.Text
|
|
Dim FechaF As String = txtFechaF.Text
|
|
If txtFechaI.Text = "" Then FechaI = "-1"
|
|
If txtFechaF.Text = "" Then FechaF = "-1"
|
|
Dim Folio As String = If(TxtFolio.Text.Trim.Length > 0, String.Format("%{0}%", TxtFolio.Text.Trim.ToUpper), "-1")
|
|
Dim Proveedor As String = If(TxtProveedor.Text.Trim.Length > 0, String.Format("%{0}%", TxtProveedor.Text.Trim.ToUpper.Replace(" ", "%")), "-1")
|
|
Dim dt As DataTable = Nothing
|
|
|
|
If ObjDatos.GetFacturas(-1, Folio, txtFechaI.Text.Trim.ToDate, txtFechaF.Text.Trim.ToDate, "-1", Proveedor, DdlValidado.SelectedValue.ToEntero, DdlResponsable.SelectedValue.ToEntero, DdlClasificacionProv.SelectedValue.ToEntero, DdlCveTipoProveedor.SelectedValue.ToEntero, DdlTipoComprobante.SelectedValue.ToString, UsuarioActual.CveEmpresa) Then
|
|
|
|
If Tab.ActiveTabIndex = 0 Then
|
|
dt = ObjDatos.DtResultados.FiltraParametros("TipoComprobante <> 'P'")
|
|
Else
|
|
dt = ObjDatos.DtResultados.FiltraParametros("TipoComprobante = 'P' ")
|
|
End If
|
|
|
|
|
|
Else
|
|
Alert("No hay datos consultados", TipoMensaje.MsgAdvertencia)
|
|
End If
|
|
ObjDatos.Dispose()
|
|
|
|
If dt IsNot Nothing Then
|
|
|
|
Dim Imagen As New System.IO.FileInfo($"{UsuarioActual.Empresa.Ruta}/Logo.png")
|
|
|
|
|
|
Dim params As New List(Of ReportParameter)
|
|
params.Add(New ReportParameter("NombreEmpresa", UsuarioActual.Empresa.Empresa))
|
|
params.Add(New ReportParameter("FechaInicio", FechaI))
|
|
params.Add(New ReportParameter("FechaFin", FechaF))
|
|
params.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Nombre))
|
|
params.Add(New ReportParameter("FechaImpresion", Fecha.ToDateTime.ToShortDateString))
|
|
|
|
If Imagen.Exists Then
|
|
params.Add(New ReportParameter("LogoPath", $"file//:{Imagen.FullName}"))
|
|
Else
|
|
params.Add(New ReportParameter("LogoPath", ""))
|
|
End If
|
|
|
|
|
|
If Tab.ActiveTabIndex = 2 Then
|
|
|
|
ImprimirPDF("Empresas/Grales/Formatos/RepFacturas.rdlc", DTTraslados, params, $"FacturasBuzon_{Fecha.ToString("yyyyMMyyddmmss")}", Tipo)
|
|
Else
|
|
ImprimirPDF("Empresas/Grales/Formatos/RepFacturas.rdlc", dt, params, $"FacturasBuzon_{Fecha.ToString("yyyyMMyyddmmss")}", Tipo)
|
|
End If
|
|
|
|
|
|
End If
|
|
|
|
End Sub
|
|
Protected Sub LnkPdf_Click(sender As Object, e As EventArgs) Handles LnkPdf.Click
|
|
GenerarPDF(NowADS())
|
|
End Sub
|
|
#End Region
|
|
|
|
#Region "S U B I R - F A C T U R A S - M A S I V A M E N T E"
|
|
Private Sub LnkSubirFacturas_Click(sender As Object, e As EventArgs) Handles LnkSubirFacturas.Click
|
|
RegistraScript(String.Format("$('#{0}').modal();", "ModalFacturas"))
|
|
End Sub
|
|
Private Sub BtnSubirFacturas_Click(sender As Object, e As EventArgs) Handles BtnSubirFacturas.Click
|
|
|
|
'If UsuarioActual.Empresa.SendMail.Trim.Length = 0 Then
|
|
' Alert("La Empresa no tiene configurado el envió de correo.", TipoMensaje.MsgAdvertencia)
|
|
' Exit Sub
|
|
'End If
|
|
|
|
Dim ListComprimidos As New List(Of String)
|
|
Dim ListXML As New List(Of String)
|
|
Dim ListPDF As New List(Of String)
|
|
|
|
Dim FileExtension As String = "-1"
|
|
Dim filesgral As List(Of Archivo) = Anexo.getfiles().Archivos
|
|
Dim filemove As String = ""
|
|
|
|
For Each fileItem As Archivo In filesgral
|
|
FileExtension = IO.Path.GetExtension(String.Format("{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, fileItem.filename)).Replace(".", "")
|
|
filemove = fileItem.filename
|
|
|
|
If filemove <> "" Then
|
|
filemove.FilesMove("", String.Format("{0}Temp\Facturas", UsuarioActual.Empresa.Ruta), ConcatenarDirectorioBase:=False, Sobreescribir:=True)
|
|
If FileExtension.ToUpper = "RAR" Or FileExtension.ToUpper = "ZIP" Then
|
|
ListComprimidos.Add(String.Format("{0}Temp\Facturas\{1}", UsuarioActual.Empresa.Ruta, filemove))
|
|
End If
|
|
|
|
End If
|
|
Next
|
|
|
|
|
|
For Each fileItem As Archivo In filesgral
|
|
FileExtension = IO.Path.GetExtension(String.Format("{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, fileItem.filename)).Replace(".", "")
|
|
filemove = fileItem.filename
|
|
|
|
If filemove <> "" AndAlso (FileExtension.ToUpper() <> "ZIP" And FileExtension.ToUpper() <> "RAR") Then
|
|
|
|
'filemove.FilesMove("", String.Format("{0}Temp\Facturas", UsuarioActual.Empresa.Ruta), ConcatenarDirectorioBase:=False, Sobreescribir:=True)
|
|
|
|
If FileExtension.ToUpper = "XML" Then
|
|
ListXML.Add(String.Format("{0}Temp\Facturas\{1}", UsuarioActual.Empresa.Ruta, filemove))
|
|
End If
|
|
|
|
If FileExtension.ToUpper = "PDF" Then
|
|
ListPDF.Add(String.Format("{0}Temp\Facturas\{1}", UsuarioActual.Empresa.Ruta, filemove))
|
|
End If
|
|
|
|
End If
|
|
Next
|
|
|
|
|
|
SubirFacturas(ListComprimidos, ListXML, ListPDF)
|
|
|
|
RegistraScript(String.Format("$('#{0}').modal('hide');", "ModalFacturas"))
|
|
|
|
RegistraScript("$('#ModalBitacoraEfacturas').modal()")
|
|
|
|
End Sub
|
|
|
|
Private Sub SubirFacturas(ByRef ListComprimidos As List(Of String), ByRef ListXML As List(Of String), ByRef ListPDF As List(Of String), Optional Validada As Integer = 0)
|
|
Dim DTLOG As New DataTable
|
|
DTLOG.Columns.Add("Serie", GetType(String))
|
|
DTLOG.Columns.Add("Folio", GetType(String))
|
|
DTLOG.Columns.Add("Fecha", GetType(Date))
|
|
DTLOG.Columns.Add("Proveedor", GetType(String))
|
|
DTLOG.Columns.Add("Importe", GetType(Decimal))
|
|
DTLOG.Columns.Add("Motivo", GetType(String))
|
|
DTLOG.Columns.Add("RFCde", GetType(String))
|
|
DTLOG.Columns.Add("Estatus", GetType(Integer))
|
|
DTLOG.Columns.Add("Tipo", GetType(String))
|
|
|
|
|
|
'Serie Folio Fecha Proveedor Importe Motivo
|
|
|
|
Dim sw As New Diagnostics.Stopwatch
|
|
Dim swmili As Long = 0
|
|
Dim swTiempo As New StringBuilder
|
|
sw.Start()
|
|
|
|
For Each comprmido As String In ListComprimidos
|
|
|
|
Dim FiInfo As New FileInfo(comprmido)
|
|
|
|
Try
|
|
Using stream As Stream = System.IO.File.OpenRead(FiInfo.FullName)
|
|
Try
|
|
Dim reader = ReaderFactory.Open(stream)
|
|
|
|
Dim Multiparte As Boolean = False
|
|
If Path.GetExtension(FiInfo.FullName.ToUpper()) = ".RAR" And FiInfo.FullName.ToUpper().Contains(".PART") Then
|
|
'SI ES .RAR, PUEDE SER MULTI PART Y PUEDE TRONAR
|
|
Using archive As RarArchive = RarArchive.Open(FiInfo.FullName)
|
|
If archive.IsMultipartVolume() Then
|
|
Multiparte = True
|
|
End If
|
|
End Using
|
|
End If
|
|
|
|
Dim PdfList As New List(Of String)
|
|
If Not Multiparte Then
|
|
'puede tronar si el archivo es multiparte
|
|
While reader.MoveToNextEntry()
|
|
If Not reader.Entry.IsDirectory Then
|
|
'Si es un archivo XML, lo leo y lo guardo
|
|
|
|
Dim nombreArchivo As String = ""
|
|
|
|
If reader.Entry.FilePath.Contains("/") Then
|
|
nombreArchivo = reader.Entry.FilePath.Substring(reader.Entry.FilePath.LastIndexOf("/") + 1)
|
|
Else
|
|
nombreArchivo = reader.Entry.FilePath
|
|
End If
|
|
|
|
If Path.GetExtension(reader.Entry.FilePath.ToUpper()) = ".XML" Then
|
|
reader.WriteEntryToDirectory(String.Format("{0}Temp\Facturas", UsuarioActual.Empresa.Ruta), ExtractOptions.None Or ExtractOptions.Overwrite)
|
|
ListXML.Add(String.Format("{0}Temp\Facturas\{1}", UsuarioActual.Empresa.Ruta, nombreArchivo))
|
|
End If
|
|
If Path.GetExtension(reader.Entry.FilePath.ToUpper()) = ".PDF" Then
|
|
'este sale de un error al leer el pdf, como lo estoy recorriendo de una vez lo guardo y lo vinculo, si la coincidencia es por nombre o número de folio
|
|
'string RFCEmisor = BuscaFactura(System.IO.Path.GetFileNameWithoutExtension(reader.Entry.FilePath).ToUpper(), Arreglo, True);
|
|
'if (!string.IsNullOrEmpty(RFCEmisor))
|
|
' {
|
|
'If Not Directory.Exists(String.Format("{0}{1}", Temporal, RFCEmisor)) Then Directory.CreateDirectory(String.Format("{0}{1}", Temporal, RFCEmisor))
|
|
|
|
'reader.WriteEntryToDirectory(String.Format("{0}{1}", Temporal, ""), ExtractOptions.None Or ExtractOptions.Overwrite)
|
|
reader.WriteEntryToDirectory(String.Format("{0}{1}", String.Format("{0}Temp\Facturas", UsuarioActual.Empresa.Ruta), ""), ExtractOptions.None Or ExtractOptions.Overwrite)
|
|
ListPDF.Add(String.Format("{0}Temp\Facturas\{1}", UsuarioActual.Empresa.Ruta, nombreArchivo))
|
|
|
|
End If
|
|
End If
|
|
End While
|
|
End If
|
|
Catch ex As Exception
|
|
GuardaLogAD("'ERROR :" & ex.Message, eFacturasLog)
|
|
End Try
|
|
End Using
|
|
Catch ex As Exception
|
|
If UsuarioActual.CveRol = 1 Then
|
|
Alert($"Error al procesar archivo: {FiInfo.FullName} Error:{ex.Message} stackTrace: {ex.StackTrace}", TipoMensaje.MsgAdvertencia)
|
|
GuardaLogAD($"Error al procesar archivo: {FiInfo.FullName} Error:{ex.Message} stackTrace: {ex.StackTrace}")
|
|
Else
|
|
Alert("Se presento un error al procesar las solcictudes. comuniquese con soporte tecnico.", TipoMensaje.MsgAdvertencia)
|
|
GuardaLogAD($"Error al procesar archivo: {FiInfo.FullName} Error:{ex.Message} stackTrace: {ex.StackTrace}")
|
|
End If
|
|
|
|
Exit Sub
|
|
End Try
|
|
|
|
|
|
|
|
Next
|
|
|
|
|
|
Anexo.Text = ""
|
|
UPAddFacturas.Update()
|
|
|
|
For Each filePathXML As String In ListXML
|
|
|
|
Dim rowLog As DataRow = DTLOG.NewRow
|
|
rowLog("Serie") = ""
|
|
rowLog("Folio") = ""
|
|
rowLog("Fecha") = NowADS()
|
|
rowLog("Proveedor") = ""
|
|
rowLog("Importe") = 0
|
|
rowLog("Motivo") = ""
|
|
rowLog("RFCde") = ""
|
|
rowLog("Estatus") = 0
|
|
rowLog("Tipo") = ""
|
|
|
|
|
|
Dim fInfoXML As New FileInfo(filePathXML)
|
|
|
|
Dim RutaPDF As String = ""
|
|
|
|
For Each filePathPDF As String In ListPDF
|
|
|
|
Dim fInfoPDF As New FileInfo(filePathPDF)
|
|
|
|
|
|
Dim fxml As String = fInfoXML.Name.ToUpper().Replace(".XML", "")
|
|
Dim fpdf As String = fInfoPDF.Name.ToUpper().Replace(".PDF", "")
|
|
Dim fpdfSplit As String() = fpdf.Split("-"c)
|
|
|
|
If fpdfSplit.Length >= 2 AndAlso fpdfSplit(0).Length = 18 Then
|
|
fpdf = fpdf.Replace($"{fpdfSplit(0)}-", "")
|
|
End If
|
|
|
|
If fxml.Contains(fpdf) Or (ListXML.Count = 1 And ListPDF.Count = 1) Then
|
|
RutaPDF = fInfoPDF.FullName
|
|
Exit For
|
|
End If
|
|
|
|
Next
|
|
|
|
If File.Exists(filePathXML) Then
|
|
Dim a As New ComprobanteFactura(eFacturasLog)
|
|
Dim FF As Factura = a.CargaComprobanteXML(File.ReadAllText(filePathXML), UsuarioActual.Empresa.Ruta, UsuarioActual.Empresa.RFC, UsuarioActual.CveEmpresa, True, rowLog, NombreArchivo:=fInfoXML.Name, Validada:=Validada)
|
|
|
|
If FF IsNot Nothing AndAlso FF.CveFactura > 0 Then
|
|
|
|
If RutaPDF = "" Then
|
|
Dim Hilo As New System.Threading.Thread(Sub() ProcesarPDF(UsuarioActual, a, FF))
|
|
Hilo.Start()
|
|
Else
|
|
Dim PDfDestino As String = $"{UsuarioActual.Empresa.Ruta}\Compras\{FF.EmisorRFC}\{FF.CveFactura}.PDF"
|
|
If File.Exists(RutaPDF) Then
|
|
If File.Exists(PDfDestino) Then
|
|
File.Delete(PDfDestino)
|
|
End If
|
|
File.Move(RutaPDF, PDfDestino)
|
|
End If
|
|
End If
|
|
|
|
End If
|
|
End If
|
|
|
|
DTLOG.Rows.Add(rowLog)
|
|
|
|
Next
|
|
|
|
sw.Stop()
|
|
swTiempo.AppendFormat("Fill ClsSisMail.ArchivoMail: ({0}) {1} ", sw.ElapsedMilliseconds - swmili, sw.ElapsedMilliseconds)
|
|
swmili = sw.ElapsedMilliseconds
|
|
sw.Start()
|
|
|
|
|
|
sw.Stop()
|
|
swTiempo.AppendFormat("BorrarInicio: ({0}) {1} ", sw.ElapsedMilliseconds - swmili, sw.ElapsedMilliseconds)
|
|
swmili = sw.ElapsedMilliseconds
|
|
sw.Start()
|
|
|
|
|
|
For Each s As String In ListXML
|
|
Try
|
|
File.Delete(s)
|
|
Catch ex As Exception
|
|
End Try
|
|
Next
|
|
|
|
For Each s As String In ListComprimidos
|
|
Try
|
|
File.Delete(s)
|
|
GuardaLogAD("")
|
|
Catch ex As Exception
|
|
End Try
|
|
Next
|
|
|
|
sw.Stop()
|
|
swTiempo.AppendFormat("BorrarEnd: ({0}) {1} ", sw.ElapsedMilliseconds - swmili, sw.ElapsedMilliseconds)
|
|
swmili = sw.ElapsedMilliseconds
|
|
|
|
GuardaLogefacturas(swTiempo.ToString())
|
|
|
|
mesajeFaturasSubidas(DTLOG)
|
|
|
|
|
|
CargaDatosBitacora()
|
|
|
|
'Alert(String.Format("Se cargaron {0} Facturas", Arreglo.Count), TipoMensaje.MsgInformacion)
|
|
End Sub
|
|
|
|
Private Sub ProcesarPDF(UsuarioActual As Usuario, a As ComprobanteFactura, FF As Factura)
|
|
a.GeneraPDF(UsuarioActual, UsuarioActual.Empresa.Ruta, FF, UsuarioActual.Empresa.Ruta, True)
|
|
End Sub
|
|
|
|
Private Sub mesajeFaturasSubidas(DTLOG As DataTable)
|
|
|
|
|
|
Dim Str As New StringBuilder
|
|
|
|
|
|
Dim conta As Integer = 1
|
|
Str.Append("Se procesó la información con la siguiente información:<br/> <table width='900px'><tr class='Titulos'><td>Serie</td><td>Folio</td><td width='100px'>Fecha</td><td width='250px'>Proveedor</td><td>Importe</td><td width='250px'>Motivo</td></tr>")
|
|
Dim objCompra As New ClsCompras
|
|
|
|
For Each dr As DataRow In DTLOG.Rows
|
|
|
|
Str.AppendFormat("<tr class='{0}'>", If(conta Mod 2 = 0, "TextoAlterno", "Texto"))
|
|
|
|
Str.AppendFormat("<td style='width:100px'>{0}</td>", dr("Serie"))
|
|
Str.AppendFormat("<td style='width:80px'>{0}</td>", dr("Folio"))
|
|
Str.AppendFormat("<td style='width:400px'>{0}</td>", If(dr("Fecha").ToString <> "", dr("Fecha").ToString.ToDate.ToShortDateString, ""))
|
|
Str.AppendFormat("<td style='width:80px'>{0}</td>", dr("Proveedor"))
|
|
Str.AppendFormat("<td style='width:40px'>{0}</td>", dr("Importe").ToString.ToDecimal.FormatoNumero)
|
|
Str.AppendFormat("<td style='width:40px'>{0}</td>", dr("Motivo"))
|
|
Str.Append("</tr>")
|
|
conta += 1
|
|
|
|
objCompra.AddBitacoraFactura(dr("Serie").ToString, dr("Folio").ToString, dr("RFCde").ToString, dr("Motivo").ToString, dr("Estatus").ToString.ToEntero, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, "Modulo eFacturas",
|
|
dr("Proveedor").ToString, dr("Importe").ToString.ToDecimal, dr("Tipo").ToString)
|
|
Next
|
|
|
|
'RFCde,Estatus,Tipo
|
|
|
|
objCompra.Dispose()
|
|
|
|
If DTLOG.Rows.Count > 0 Then 'si las facturas no recividas son matores a cero se muestra el mensaje
|
|
Alert(Str.ToString, TipoMensaje.MsgInformacion)
|
|
End If
|
|
|
|
|
|
End Sub
|
|
|
|
Public Sub GuardaLogefacturas(Str As String)
|
|
Dim ArchivoW As StreamWriter
|
|
Dim strLineaTMP As String
|
|
|
|
' strLineaTMP = Chr(13) & Chr(10) & Day(NowADS()) & "/" & Month(NowADS()) & "/" & Year(NowADS()) & " " & Hour(NowADS()) & ":" & Minuto & ". " & Str & Chr(13) & Chr(10)
|
|
strLineaTMP = String.Format("{0}{1}Log: {2}{3}:{4}", Chr(13), Chr(10), Str, NowADS().ToShortDateString, NowADS().ToShortTimeString)
|
|
Try
|
|
ArchivoW = New StreamWriter(String.Format("{0}\Logefacturas.txt", ModExtensiones.DirectorioBaseEmpresas), True, System.Text.Encoding.UTF8)
|
|
Catch ex As UnauthorizedAccessException
|
|
'Alert("No hay permisos para guardar en el Log.", Extensiones.TipoMensaje.MsgError)
|
|
Exit Sub
|
|
Catch ex As Exception
|
|
Exit Sub
|
|
End Try
|
|
|
|
Try
|
|
ArchivoW.WriteLine(strLineaTMP)
|
|
Catch
|
|
End Try
|
|
|
|
ArchivoW.Close()
|
|
ArchivoW.Dispose()
|
|
End Sub
|
|
'Private Function AgregaFactura(Fact As Modelos.eFactura) As String
|
|
' Dim Retorno As String = ""
|
|
' Dim Correcto As Boolean = False
|
|
|
|
' If Fact.Version = "3.2" Then Fact.TipodeComprobante = Fact.TipodeComprobante.Substring(0, 1)
|
|
|
|
|
|
' Dim ObjDatos As New ClsCompras
|
|
' ObjDatos.IniciaTransacSQL()
|
|
' ObjDatos.CveFactura = 0
|
|
' Dim Ret As Integer = ObjDatos.AddFactura(Fact.Serie, Fact.Folio, Convert.ToDateTime(Fact.Fecha), Fact.EmisorNombre, Fact.EmisorRFC, Fact.subTotal,
|
|
' Fact.TrasladoIVA, Fact.Total, Fact.TFDUUID, Fact.ReceptorRFC, Fact.ArchivoXML, Fact.ArchivoPDF,
|
|
' Fact.Version, Fact.Descuento, Fact.Moneda, Fact.TipodeComprobante, Fact.TipoCambio, Fact.Validada,
|
|
' Fact.CveEmpresa, Fact.sUPPrefijo)
|
|
|
|
' If Ret >= 0 Then
|
|
' If Not Directory.Exists(Destino + Fact.EmisorRFC) Then
|
|
' Directory.CreateDirectory(Destino + Fact.EmisorRFC)
|
|
' End If
|
|
' 'Try
|
|
' ' If File.Exists(Destino & Retorno.EmisorRFC & "\" & NombreArchivo) Then File.Delete(Destino & Retorno.EmisorRFC & "\" & NombreArchivo)
|
|
' ' File.Move(Temporal & NombreArchivo, Destino & Retorno.EmisorRFC & "\" & NombreArchivo)
|
|
|
|
' 'Catch ex As IOException
|
|
' ' GuardaLog("'ERROR :" & ex.Message)
|
|
' 'End Try
|
|
|
|
' Select Case Ret
|
|
' Case 0
|
|
|
|
' Correcto = True
|
|
' Dim RRutaDestino As String = String.Format("{0}{1}\{2}.xml", Destino, Fact.EmisorRFC, ObjDatos.CveFactura)
|
|
' 'ModExtensiones.GuardaLog(String.Format(" '--------{0} Compra ya insertada : {1}{2} - {3}", ContadorGeneral, Fact.Serie, Fact.Folio, RRutaDestino))
|
|
|
|
' If Not File.Exists(RRutaDestino) Then
|
|
' File.Move(String.Format("{0}Temp\{1}", AppDomain.CurrentDomain.BaseDirectory, Fact.ArchivoXML), RRutaDestino)
|
|
' ObjDatos.UpdateArchivo(ObjDatos.CveFactura, "XML")
|
|
' ModExtensiones.GuardaLog(" '--------XML Actualizado ")
|
|
' End If
|
|
|
|
' Correcto = True
|
|
' Exit Select
|
|
' Case 1
|
|
' 'muevo el archivo y lo renombro
|
|
' Dim StrMover As String = ""
|
|
' Try
|
|
' File.Move(String.Format("{0}\{1}", Fact.DirectorioTemporal, Fact.ArchivoXML), String.Format("{0}{1}\{2}.xml", Destino, Fact.EmisorRFC, ObjDatos.CveFactura))
|
|
' File.Move(String.Format("{0}\{1}", Fact.DirectorioTemporal, Fact.ArchivoPDF), String.Format("{0}{1}\{2}.pdf", Destino, Fact.EmisorRFC, ObjDatos.CveFactura))
|
|
' ModExtensiones.GuardaLog(" '++++++++ Archivo :" + String.Format("{0}\{1}", Fact.DirectorioTemporal, Fact.ArchivoXML) + " - " + String.Format("{0}{1}\{2}.xml", Destino, Fact.EmisorRFC, ObjDatos.CveFactura))
|
|
' ModExtensiones.GuardaLog(" '++++++++ Archivo :" + String.Format("{0}\{1}", Fact.DirectorioTemporal, Fact.ArchivoPDF) + " - " + String.Format("{0}{1}\{2}.pdf", Destino, Fact.EmisorRFC, ObjDatos.CveFactura))
|
|
' 'si se movieron los dos archivos, los marca como correcto
|
|
' If File.Exists(String.Format("{0}{1}\{2}.xml", Destino, Fact.EmisorRFC, ObjDatos.CveFactura)) AndAlso File.Exists(String.Format("{0}{1}\{2}.pdf", Destino, Fact.EmisorRFC, ObjDatos.CveFactura)) Then
|
|
' Correcto = True
|
|
' End If
|
|
' Catch ex As Exception
|
|
' StrMover = ex.Message
|
|
' End Try
|
|
|
|
|
|
' ModExtensiones.GuardaLog(Convert.ToString(" '++++++++ Compra Insertada :" + Fact.Serie + Fact.Folio + " - Correcto:" + (If(Correcto, "Si", "No" + " Obs: "))) & StrMover)
|
|
' Exit Select
|
|
' End Select
|
|
' End If
|
|
' If Correcto Then
|
|
' ObjDatos.Commit()
|
|
' 'ya se insertó o está insertada
|
|
' Dim Idioma As New CultureInfo("es-MX")
|
|
' 'regreso el format 2014-07 Julio
|
|
' Retorno = Fact.Fecha.ToDate().ToString("yyyy-MM MMMM", Idioma)
|
|
' Else
|
|
' ObjDatos.RollBack()
|
|
' End If
|
|
' ObjDatos.Dispose()
|
|
|
|
' Return Retorno
|
|
|
|
'End Function
|
|
Private Sub CargarFacturas(PathArchivo As String, NombreArchivo As String)
|
|
Dim RFC As String = CargaEmisordeXML(String.Format("{0}", PathArchivo), "RFC", UsuarioActual.Empresa.RFC)
|
|
If RFC IsNot Nothing Then
|
|
If NombreArchivo <> "" Then
|
|
DirectoryExistsCreate(String.Format("{0}Compras", UsuarioActual.Empresa.Ruta))
|
|
DirectoryExistsCreate(String.Format("{0}Compras\{1}", UsuarioActual.Empresa.Ruta, RFC.ToUpper))
|
|
|
|
Try
|
|
File.Move(PathArchivo, String.Format("{0}Compras\{1}\{2}", UsuarioActual.Empresa.Ruta, RFC.ToUpper, NombreArchivo))
|
|
Catch ex As Exception
|
|
Alert("Error")
|
|
End Try
|
|
|
|
'NombreArchivo.FilesMove(NombreArchivo, String.Format("Empresas\{0}\Compras\{1}", UsuarioActual.CveEmpresa, RFC.ToUpper))
|
|
End If
|
|
End If
|
|
End Sub
|
|
Private Sub DescomprimeFacturas(PathArchivo As String, Directorio As String)
|
|
If Not Directory.Exists(Directorio) Then
|
|
Directory.CreateDirectory(Directorio)
|
|
End If
|
|
Using archive As ZipArchive = ZipFile.OpenRead(String.Format("{0}", PathArchivo))
|
|
|
|
For Each entry As ZipArchiveEntry In archive.Entries
|
|
If entry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) Then
|
|
|
|
'If File.Exists(String.Format("{0}Empresas\{1}\Temp\{2}\{3}", ModExtensiones.DirectorioBaseEmpresas, UsuarioActual.CveEmpresa, Directorio, entry.Name)) Then
|
|
' File.Delete(String.Format("{0}Empresas\{1}\Temp\{2}\{3}", ModExtensiones.DirectorioBaseEmpresas, UsuarioActual.CveEmpresa, Directorio, entry.Name))
|
|
'End If
|
|
|
|
'entry.ExtractToFile(String.Format("{0}Empresas\{1}\Temp\{2}\{3}", ModExtensiones.DirectorioBaseEmpresas, UsuarioActual.CveEmpresa, Directorio, entry.Name))
|
|
|
|
If File.Exists(String.Format("{0}\{1}", Directorio, entry.Name)) Then
|
|
File.Delete(String.Format("{0}\{1}", Directorio, entry.Name))
|
|
End If
|
|
|
|
entry.ExtractToFile(String.Format("{0}\{1}", Directorio, entry.Name))
|
|
|
|
End If
|
|
Next
|
|
|
|
End Using
|
|
End Sub
|
|
|
|
|
|
Public Shared Function CargaEmisordeXML(ArchivoXML As String, CampoXML As String, RFCEmpresaActual As String) As String
|
|
Dim Valor As [String] = Nothing
|
|
|
|
If File.Exists(ArchivoXML) Then
|
|
Dim NombreArchivo As String = Path.GetFileName(ArchivoXML)
|
|
Dim invalidChars As Char() = Path.GetInvalidFileNameChars()
|
|
Dim invalidString As String = Regex.Escape(New String(invalidChars))
|
|
Dim NombreValido As String = Regex.Replace(NombreArchivo, (Convert.ToString("[") & invalidString) + "]", "")
|
|
|
|
Try
|
|
Dim XmlDoc As New XmlDocument()
|
|
XmlDoc.Load(ArchivoXML)
|
|
Dim nodo As XmlNode = XmlDoc.DocumentElement.ChildNodes(0)
|
|
Dim node As XmlNode
|
|
Dim cfdVer As String = "http://www.sat.gob.mx/cfd/3"
|
|
Dim RfcXML As String = ""
|
|
Dim Prefijo As String = If(XmlDoc.DocumentElement.Prefix = "", "cfd", XmlDoc.DocumentElement.Prefix)
|
|
Dim namespaces As New XmlNamespaceManager(XmlDoc.NameTable)
|
|
|
|
If Not Prefijo.ToLower().Equals("cfdi") Then
|
|
cfdVer = "http://www.sat.gob.mx/cfd/2"
|
|
End If
|
|
namespaces.AddNamespace(Prefijo, cfdVer)
|
|
namespaces.AddNamespace("aerolineas", "http://www.sat.gob.mx/aerolineas")
|
|
namespaces.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital")
|
|
namespaces.AddNamespace("implocal", "http://www.sat.gob.mx/implocal")
|
|
namespaces.AddNamespace("registrofiscal", "http://www.sat.gob.mx/registrofiscal")
|
|
|
|
node = XmlDoc.SelectSingleNode([String].Format("//{0}:Receptor", Prefijo), namespaces)
|
|
If node IsNot Nothing Then
|
|
RfcXML = ValorXML(node, "RFC")
|
|
End If
|
|
If RfcXML = RFCEmpresaActual Then
|
|
Valor = ValorXML(nodo, CampoXML)
|
|
|
|
|
|
End If
|
|
Catch exx As XmlException
|
|
Valor = Nothing
|
|
'Using file__1 As New System.IO.StreamWriter([String].Format("{0}\UtileriasLOG.txt", Path.GetDirectoryName(Application.StartupPath)), True, System.Text.Encoding.UTF8)
|
|
' file__1.WriteLine("{NowADS()}: {exx.Message}")
|
|
' file__1.Close()
|
|
' file__1.Dispose()
|
|
'End Using
|
|
End Try
|
|
End If
|
|
Return Valor
|
|
End Function
|
|
Private Shared Function ValorXML(n As XmlNode, Campo As String, Optional retorno As [String] = "") As String
|
|
If n Is Nothing Then
|
|
Return retorno
|
|
End If
|
|
|
|
Dim o As XmlNode = n.Attributes.Cast(Of XmlAttribute)().SingleOrDefault(Function(a) String.Compare(a.Name, Campo, StringComparison.CurrentCultureIgnoreCase) = 0)
|
|
If o Is Nothing Then
|
|
Return retorno
|
|
Else
|
|
Return o.Value
|
|
End If
|
|
|
|
End Function
|
|
Private Function CargaDatosXML(XMLDoc As XmlDocument) As Modelos.eFactura
|
|
Dim nodo As XmlNode = XMLDoc.DocumentElement
|
|
|
|
If nodo.ChildNodes.Count = 2 Then
|
|
nodo = nodo.ChildNodes(1)
|
|
End If
|
|
|
|
Dim Fact As Modelos.eFactura = Nothing
|
|
Dim node As XmlNode = Nothing
|
|
Dim RFC As String = ""
|
|
|
|
Dim Prefijo As String = If(String.IsNullOrEmpty(XMLDoc.DocumentElement.Prefix), "cfd", XMLDoc.DocumentElement.Prefix)
|
|
Dim cfdVer As String = "http://www.sat.gob.mx/cfd/3"
|
|
Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable)
|
|
|
|
If Prefijo.ToLower() <> "cfdi" Then
|
|
cfdVer = "http://www.sat.gob.mx/cfd/2"
|
|
End If
|
|
namespaces.AddNamespace(Prefijo, cfdVer)
|
|
namespaces.AddNamespace("aerolineas", "http://www.sat.gob.mx/aerolineas")
|
|
namespaces.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital")
|
|
namespaces.AddNamespace("implocal", "http://www.sat.gob.mx/implocal")
|
|
namespaces.AddNamespace("registrofiscal", "http://www.sat.gob.mx/registrofiscal")
|
|
|
|
node = XMLDoc.SelectSingleNode(String.Format("//{0}:Receptor", Prefijo), namespaces)
|
|
'AndAlso node.ChildNodes.Count > 0
|
|
If node IsNot Nothing Then
|
|
RFC = ValorXML(node, "RFC")
|
|
End If
|
|
|
|
'solo si el rfc receptor es el mismo al de la empresa seleccionada
|
|
|
|
If RFC = UsuarioActual.Empresa.RFC AndAlso Convert.ToDateTime(ValorXML(nodo, "fecha")).Year >= 2013 Then
|
|
Fact = New Modelos.eFactura()
|
|
|
|
'Fact.CveEmpresa = CveEmpresa
|
|
Fact.Serie = ValorXML(nodo, "serie")
|
|
If Not String.IsNullOrEmpty(Fact.Serie) Then
|
|
Fact.Serie = Fact.Serie
|
|
End If
|
|
|
|
Fact.Version = ValorXML(nodo, "version").Replace("..", ".")
|
|
Fact.Folio = ValorXML(nodo, "folio").TrimStart("0"c)
|
|
Fact.Fecha = ValorXML(nodo, "fecha")
|
|
Fact.subTotal = Convert.ToDouble(ValorXML(nodo, "subTotal").Replace("..", "."))
|
|
Fact.Total = Convert.ToDouble(ValorXML(nodo, "total"))
|
|
Fact.Moneda = ValorXML(nodo, "Moneda")
|
|
Fact.TipodeComprobante = ValorXML(nodo, "tipoDeComprobante")
|
|
Fact.TipoCambio = Convert.ToDouble(ValorXML(nodo, "TipoCambio", "1.0"))
|
|
Fact.Descuento = Convert.ToDouble(ValorXML(nodo, "descuento", "0"))
|
|
Fact.CveEmpresa = UsuarioActual.CveEmpresa
|
|
|
|
Fact.sUPPrefijo = Prefijo
|
|
|
|
node = XMLDoc.SelectSingleNode(String.Format("//{0}:Emisor", Prefijo), namespaces)
|
|
|
|
If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then
|
|
Fact.EmisorRFC = ValorXML(node, "RFC")
|
|
Fact.EmisorNombre = ValorXML(node, "nombre")
|
|
End If
|
|
node = XMLDoc.SelectSingleNode(String.Format("//{0}:Receptor", Prefijo), namespaces)
|
|
' AndAlso node.ChildNodes.Count > 0
|
|
If node IsNot Nothing Then
|
|
Fact.ReceptorRFC = ValorXML(node, "RFC")
|
|
End If
|
|
|
|
node = XMLDoc.SelectSingleNode(String.Format("//{0}:Impuestos", Prefijo), namespaces)
|
|
|
|
If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then
|
|
Dim nodeRetenciones As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Retencion", Prefijo), namespaces)
|
|
|
|
Fact.TotalRetenciones = Convert.ToDouble(ValorXML(node, "totalImpuestosRetenidos", "0"))
|
|
|
|
For Each retencion As XmlNode In nodeRetenciones
|
|
If retencion.Attributes.GetNamedItem("impuesto").Value = "IVA" Then
|
|
Fact.RetencionIVA += Convert.ToDouble(retencion.Attributes.GetNamedItem("importe").Value)
|
|
End If
|
|
If retencion.Attributes.GetNamedItem("impuesto").Value = "ISR" Then
|
|
Fact.RetencionISR += Convert.ToDouble(retencion.Attributes.GetNamedItem("importe").Value)
|
|
' Do something.
|
|
End If
|
|
Next
|
|
Fact.SumaTotalRetenciones += Fact.RetencionIVA
|
|
Fact.SumaTotalRetenciones += Fact.RetencionISR
|
|
|
|
Fact.TotalTraslados = Convert.ToDouble(ValorXML(node, "totalImpuestosTrasladados", "0"))
|
|
|
|
'Dim o As XmlNode = traslado.Attributes.Cast(Of XmlAttribute)().SingleOrDefault(Function(a) String.Compare(a.Name, "impuesto", StringComparison.CurrentCultureIgnoreCase) = 0)
|
|
Dim nodeTraslados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Traslado", Prefijo), namespaces)
|
|
|
|
For Each traslado As XmlNode In nodeTraslados
|
|
' If traslado.Attributes.GetNamedItem("impuesto").Value = "IVA"
|
|
Dim impuesto As XmlNode = traslado.Attributes.Cast(Of XmlAttribute)().SingleOrDefault(Function(a) String.Compare(a.Name, "impuesto", StringComparison.CurrentCultureIgnoreCase) = 0)
|
|
If impuesto.Value = "IVA" Then
|
|
|
|
Dim ImporteTRaslado As XmlNode = traslado.Attributes.Cast(Of XmlAttribute)().SingleOrDefault(Function(a) String.Compare(a.Name, "Importe", StringComparison.CurrentCultureIgnoreCase) = 0)
|
|
Fact.TrasladoIVA += Convert.ToDouble(ImporteTRaslado.Value)
|
|
'If traslado.Attributes("impuesto").Value = "ISR" Then
|
|
' TrasladoISR = traslado.Attributes("importe").Value
|
|
'End If
|
|
' Do something.
|
|
End If
|
|
Next
|
|
Fact.SumaTotalTraslados += Fact.TrasladoIVA
|
|
End If
|
|
|
|
|
|
Dim nodeComp As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Complemento", Prefijo), namespaces)
|
|
Dim FacturaMisCuentasSAT As Boolean = False
|
|
|
|
|
|
If nodeComp IsNot Nothing AndAlso nodeComp.ChildNodes.Count > 0 Then
|
|
Dim nodeTFD As XmlNode = nodeComp.SelectSingleNode(String.Format("//{0}:TimbreFiscalDigital", "tfd"), namespaces)
|
|
|
|
Fact.TFDUUID = ValorXML(nodeTFD, "UUID", "")
|
|
|
|
Dim nodeRF As XmlNode = nodeComp.SelectSingleNode(String.Format("//{0}:CFDIRegistroFiscal ", "registrofiscal"), namespaces)
|
|
If nodeRF IsNot Nothing Then
|
|
Fact.Folio = ValorXML(nodeRF, "folio").TrimStart("0"c)
|
|
FacturaMisCuentasSAT = True
|
|
|
|
End If
|
|
Else
|
|
Fact.TFDUUID = ""
|
|
If String.IsNullOrEmpty(Fact.TFDUUID) AndAlso Fact.sUPPrefijo.ToLower() = "cfdi" Then
|
|
'Mensajes.AppendFormat("{0}|{1}|{2}|{3}|{4}|{5}{6}&", ValorXML(nodo, "serie"), ValorXML(nodo, "folio"), ValorXML(nodo, "fecha").ToDate().ToShortDateString(), Fact.EmisorNombre, ValorXML(nodo, "total").ToDouble().FormatoNumero(),
|
|
'"Factura no timbrada correctamente.", "")
|
|
'CargaMensaje(ValorXML(nodo, "serie"), ValorXML(nodo, "folio"), ValorXML(nodo, "fecha").ToDate(), Fact.EmisorNombre, ValorXML(nodo, "total").ToDouble(), "Factura no timbrada correctamente.",
|
|
'"", NowADS())
|
|
End If
|
|
|
|
'limpio los valores porque realmente no es una factura
|
|
|
|
Fact = Nothing
|
|
End If
|
|
'verifico si el metodo de pago esta dentro de la opcion valida
|
|
|
|
|
|
If Convert.ToDateTime(ValorXML(nodo, "fecha")) >= ("2016/07/15").ToDate() Then
|
|
Dim CasoPermitido As Boolean = False
|
|
'If CveEmpresa.Contiene(72, 80) AndAlso ValorXML(nodo, "MetododePago").ToUpper().PadRight(13, " "c).Substring(0, 13) = "TRANSFERENCIA" Then
|
|
' CasoPermitido = True
|
|
'End If
|
|
|
|
'If CveEmpresa = 5 OrElse FacturaMisCuentasSAT Then
|
|
' CasoPermitido = True
|
|
'End If
|
|
|
|
If Not CasoPermitido Then
|
|
If (Not (ValorXML(nodo, "MetododePago").ToUpper().PadLeft(2, "0"c).Substring(0, 2).Contiene("01", "02", "03", "04", "05", "06",
|
|
"07", "08", "09", "10", "11", "12",
|
|
"13", "14", "15", "16", "17", "28",
|
|
"98", "99", "NA") OrElse ValorXML(nodo, "MetododePago").ToUpper().Contiene("NO APLICA", "N/A", "N.A.", "NO IDENTIFICADO"))) Then
|
|
Dim node2 As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Emisor", Prefijo), namespaces)
|
|
Dim Nombre As String = ""
|
|
|
|
If node2 IsNot Nothing AndAlso node2.ChildNodes.Count > 0 Then
|
|
Nombre = ValorXML(node2, "nombre")
|
|
End If
|
|
|
|
'CargaMensaje(ValorXML(nodo, "serie"), ValorXML(nodo, "folio"), ValorXML(nodo, "fecha").ToDate(), ValorXML(node2, "nombre"), ValorXML(nodo, "total").ToDouble(), "Método de Pago Incorrecto:" + ValorXML(nodo, "MetododePago"),
|
|
'CorreoActual, FechaRecepcionCorreo)
|
|
|
|
Return Nothing
|
|
End If
|
|
|
|
|
|
End If
|
|
|
|
'faltan leer los impuestos locales
|
|
'node = XMLDoc.SelectSingleNode(String.Format("//{0}:ImpuestosLocales", "implocal"), namespaces)
|
|
'If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then
|
|
' Dim nodeRetenciones As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Retencion", Prefijo), namespaces)
|
|
|
|
' Fact.TotalRetenciones = ValorXML(node, "totalImpuestosRetenidos", "0").ToDouble
|
|
|
|
' For Each retencion As XmlNode In nodeRetenciones
|
|
' If retencion.Attributes("impuesto").Value = "IVA" Then
|
|
' Fact.RetencionIVA += retencion.Attributes("importe").Value.ToDouble
|
|
' End If
|
|
' If retencion.Attributes("impuesto").Value = "ISR" Then
|
|
' Fact.RetencionISR += retencion.Attributes("importe").Value.ToDouble
|
|
' End If
|
|
' ' Do something.
|
|
' Next
|
|
' Fact.SumaTotalRetenciones += Fact.RetencionIVA
|
|
' Fact.SumaTotalRetenciones += Fact.RetencionISR
|
|
|
|
' Fact.TotalTraslados = ValorXML(node, "totalImpuestosTrasladados", "0").ToDouble
|
|
|
|
' Dim nodeTraslados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Traslado", Prefijo), namespaces)
|
|
' For Each traslado As XmlNode In nodeTraslados
|
|
' If traslado.Attributes("impuesto").Value = "IVA" Then
|
|
' Fact.TrasladoIVA += traslado.Attributes("importe").Value.ToDouble
|
|
' End If
|
|
' 'If traslado.Attributes("impuesto").Value = "ISR" Then
|
|
' ' TrasladoISR = traslado.Attributes("importe").Value
|
|
' 'End If
|
|
' ' Do something.
|
|
' Next
|
|
' Fact.SumaTotalTraslados += Fact.TrasladoIVA
|
|
'End If
|
|
|
|
|
|
End If
|
|
Else
|
|
'ModExtensiones.GuardaLog((Convert.ToString("'*******RFC incorrecto RFC Emp:") & RFC) + " RFC Fact: " + RFCReceptor)
|
|
'obtengo los datos del xml, para
|
|
|
|
Dim node2 As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Emisor", Prefijo), namespaces)
|
|
|
|
|
|
'If node2 IsNot Nothing AndAlso node2.ChildNodes.Count > 0 Then
|
|
' Mensajes.AppendFormat("{0}|{1}|{2}|{3}|{4}|{5}{6}&", ValorXML(nodo, "serie"), ValorXML(nodo, "folio"), ValorXML(nodo, "fecha").ToDate().ToShortDateString(), ValorXML(node2, "nombre"), ValorXML(nodo, "total").ToDouble().FormatoNumero(),
|
|
' "RFC Incorrecto:", RFC)
|
|
' CargaMensaje(ValorXML(nodo, "serie"), ValorXML(nodo, "folio"), ValorXML(nodo, "fecha").ToDate(), ValorXML(node2, "nombre"), ValorXML(nodo, "total").ToDouble(), Convert.ToString("RFC Incorrecto:") & RFC,
|
|
' CorreoActual, FechaRecepcionCorreo)
|
|
'Else
|
|
' CargaMensaje("", "", "01/01/2000".ToDate(), "", 0.0, Convert.ToString("RFC Incorrecto:") & RFC,
|
|
' CorreoActual, FechaRecepcionCorreo)
|
|
|
|
|
|
'End If
|
|
End If
|
|
|
|
Return Fact
|
|
End Function
|
|
|
|
Private Sub CargaImpuestosXML(XMLDoc As XmlDocument)
|
|
Dim Prefijo As String = If(String.IsNullOrEmpty(XMLDoc.DocumentElement.Prefix), "cfd", XMLDoc.DocumentElement.Prefix)
|
|
Dim cfdVer As String = "http://www.sat.gob.mx/cfd/3"
|
|
Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable)
|
|
|
|
If Prefijo.ToLower() <> "cfdi" Then
|
|
cfdVer = "http://www.sat.gob.mx/cfd/2"
|
|
End If
|
|
namespaces.AddNamespace(Prefijo, cfdVer)
|
|
namespaces.AddNamespace("aerolineas", "http://www.sat.gob.mx/aerolineas")
|
|
namespaces.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital")
|
|
namespaces.AddNamespace("implocal", "http://www.sat.gob.mx/implocal")
|
|
namespaces.AddNamespace("registrofiscal", "http://www.sat.gob.mx/registrofiscal")
|
|
|
|
TrasladoIVA = 0
|
|
'_TrasladoIVA = XMLDoc.DocumentElement.ChildNodes(3).Attributes("totalImpuestosTrasladados").Value
|
|
|
|
Dim nodeTraslados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Traslado", Prefijo), namespaces)
|
|
For Each traslado As XmlNode In nodeTraslados
|
|
If traslado.Attributes.GetNamedItem("impuesto").Value = "IVA" Then
|
|
TrasladoIVA += traslado.Attributes.GetNamedItem("importe").Value.ToDouble()
|
|
|
|
End If
|
|
Next
|
|
|
|
Dim nodeComp As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Complemento", Prefijo), namespaces)
|
|
|
|
|
|
If nodeComp IsNot Nothing AndAlso nodeComp.ChildNodes.Count > 0 Then
|
|
Dim nodeTFD As XmlNode = nodeComp.SelectSingleNode(String.Format("//{0}:TimbreFiscalDigital", "tfd"), namespaces)
|
|
|
|
_TFDUUID = ValorXML(nodeTFD, "UUID", "")
|
|
_TFDFechaTimbrado = ValorXML(nodeTFD, "FechaTimbrado", "")
|
|
_TFDSelloCFD = ValorXML(nodeTFD, "selloCFD", "")
|
|
_TFDNoCertSAT = ValorXML(nodeTFD, "noCertificadoSAT", "")
|
|
_TFDSelloSAT = ValorXML(nodeTFD, "selloSAT", "")
|
|
|
|
Dim nodeRF As XmlNode = nodeComp.SelectSingleNode(String.Format("//{0}:CFDIRegistroFiscal ", "registrofiscal"), namespaces)
|
|
If nodeRF IsNot Nothing Then
|
|
_Folio = ValorXML(nodeRF, "folio").TrimStart("0"c)
|
|
|
|
|
|
End If
|
|
End If
|
|
|
|
End Sub
|
|
Private Shared Sub CargaTFD(XMLDoc As XmlDocument)
|
|
'_TFDUUID = XMLDoc.DocumentElement("cfdi:Complemento").FirstChild.Attributes("UUID").InnerText
|
|
'_TFDFechaTimbrado = XMLDoc.DocumentElement("cfdi:Complemento").FirstChild.Attributes("FechaTimbrado").InnerText
|
|
'_TFDSelloCFD = XMLDoc.DocumentElement("cfdi:Complemento").FirstChild.Attributes("selloCFD").InnerText
|
|
'_TFDNoCertSAT = XMLDoc.DocumentElement("cfdi:Complemento").FirstChild.Attributes("noCertificadoSAT").InnerText
|
|
'_TFDSelloSAT = XMLDoc.DocumentElement("cfdi:Complemento").FirstChild.Attributes("selloSAT").InnerText
|
|
End Sub
|
|
Public Function GeneraPDF(UsuarioActual As Usuario, Ruta As String, Fact As Modelos.eFactura) As Boolean
|
|
Dim RutaXML As String = String.Empty
|
|
Dim RutaPDF As String = String.Empty
|
|
Dim Retorno As Boolean = False
|
|
Try
|
|
|
|
Dim XMLDoc As New XmlDocument()
|
|
Dim TmpArchivoPDF As String = String.Format("{0}{1}-ttt.pdf", Ruta, Path.GetFileNameWithoutExtension(Fact.ArchivoXML))
|
|
Dim TmpArchivoQR As String = String.Format("{0}{1}-ttt.jpg", Ruta, Path.GetFileNameWithoutExtension(Fact.ArchivoXML))
|
|
Dim ArchivoXML As String = String.Format("{0}{1}", Ruta, Fact.ArchivoXML)
|
|
|
|
' If Not File.Exists(TmpArchivoPDF) Then
|
|
XMLDoc.Load(ArchivoXML)
|
|
CreaDTConceptos()
|
|
CargaComprobanteXML(XMLDoc)
|
|
CargaEmisorXML(XMLDoc)
|
|
CargaReceptorXML(XMLDoc)
|
|
CargaConceptosXML(XMLDoc)
|
|
CargaImpuestosXML(XMLDoc)
|
|
CargaTFD(XMLDoc)
|
|
|
|
Dim dtotal As Decimal = (If(total.ToDecimal() <= 0.0D, 0.0001D, total.ToDecimal()))
|
|
ClsPaginas.GeneraQRSAT(EmiRFC, RecRfc, dtotal, TFDUUID, RutaGuardado:=TmpArchivoQR)
|
|
|
|
If System.IO.File.Exists(TmpArchivoQR) Then
|
|
'Dim ArchivoBaseXLS As String = String.Format("{0}FacturaPDF.xlsm", Ruta.Replace("Temp", "Compras"))
|
|
If GeneraPDFNew(TmpArchivoPDF, TFDUUID, subTotal, descuento, total, TrasladoIVA.ToString(),
|
|
moneda, formaDePago, TFDNoCertSAT, TFDFechaTimbrado.ToDate(), noCertificado, DTConceptos,
|
|
TFDSelloCFD, TFDSelloSAT, TmpArchivoQR, Serie + Folio, tipoDeComprobante, "",
|
|
RecRfc, RecNombre, DomRecCalle, DomRecCol, DomRecFisNoExt, DomRecFisNoInt,
|
|
DomRecCP, DomRecMun, DomRecEst, Regimen, condicionesDePago, metodoDePago,
|
|
NumCtaPagoNumCtaPago, fecha.ToDate()) Then
|
|
Fact.ArchivoPDF = Path.GetFileName(TmpArchivoPDF)
|
|
|
|
Retorno = True
|
|
End If
|
|
|
|
File.Delete(TmpArchivoQR)
|
|
|
|
RutaPDF = TmpArchivoPDF
|
|
Else
|
|
Retorno = False
|
|
End If
|
|
'Else
|
|
'RutaPDF = TmpArchivoPDF
|
|
'End If
|
|
|
|
|
|
|
|
If DTConceptos IsNot Nothing Then
|
|
DTConceptos.Dispose()
|
|
End If
|
|
Catch ex As Exception
|
|
ModExtensiones.GuardaLog("11189" + ex.Message)
|
|
End Try
|
|
|
|
|
|
Return Retorno
|
|
End Function
|
|
Private Sub CargaComprobanteXML(XMLDoc As XmlDocument)
|
|
Dim nodo As XmlNode = XMLDoc.DocumentElement
|
|
Serie = ValorXML(nodo, "serie", "")
|
|
_Folio = ValorXML(nodo, "folio", "")
|
|
_fecha = ValorXML(nodo, "fecha", "")
|
|
_tipoDeComprobante = ValorXML(nodo, "tipoDeComprobante", "")
|
|
_formaDePago = ValorXML(nodo, "formaDePago", "")
|
|
_subTotal = ValorXML(nodo, "subTotal", "0")
|
|
_descuento = ValorXML(nodo, "descuento", "0")
|
|
_total = ValorXML(nodo, "total", "0")
|
|
_moneda = ValorXML(nodo, "Moneda")
|
|
_metodoDePago = ValorXML(nodo, "metodoDePago", "")
|
|
_condicionesDePago = ValorXML(nodo, "condicionesDePago", "")
|
|
_LugarExpedicion = ValorXML(nodo, "LugarExpedicion", "")
|
|
_NumCtaPagoNumCtaPago = ValorXML(nodo, "NumCtaPago", "")
|
|
|
|
|
|
_noCertificado = XMLDoc.DocumentElement.Attributes.GetNamedItem("noCertificado").Value
|
|
End Sub
|
|
Private Sub CargaEmisorXML(XMLDoc As XmlDocument)
|
|
Dim nodo As XmlNode = XMLDoc.DocumentElement.ChildNodes(0)
|
|
_EmiRFC = ValorXML(nodo, "rfc", "")
|
|
_EmiNombre = ValorXML(nodo, "nombre", "")
|
|
|
|
nodo = XMLDoc.DocumentElement.ChildNodes(0).ChildNodes(0)
|
|
_DomFisCalle = ValorXML(nodo, "calle", "")
|
|
_DomFisNoExt = ValorXML(nodo, "noExterior", "")
|
|
'LblDomFisNoInt.Text = XMLDoc.DocumentElement.ChildNodes(0).ChildNodes(0).Attributes("noInterior").Value
|
|
_DomFisCol = ValorXML(nodo, "colonia", "")
|
|
_DomFisCP = ValorXML(nodo, "codigoPostal", "")
|
|
_DomFisMun = ValorXML(nodo, "municipio", "")
|
|
_DomFisLoc = ValorXML(nodo, "localidad", "")
|
|
_DomFisEst = ValorXML(nodo, "estado", "")
|
|
_DomFisPais = ValorXML(nodo, "pais", "")
|
|
|
|
nodo = XMLDoc.DocumentElement.ChildNodes(0).ChildNodes(1)
|
|
_ExpEnCalle = ValorXML(nodo, "calle", "")
|
|
_ExpEnNoExt = ValorXML(nodo, "noExterior", "")
|
|
'LblExpEnNoInt.Text = XMLDoc.DocumentElement.ChildNodes(0).ChildNodes(1).Attributes("noInterior").Value
|
|
ExpEnCol = ValorXML(nodo, "colonia", "")
|
|
_ExpEnCP = ValorXML(nodo, "codigoPostal", "")
|
|
_ExpEnMun = ValorXML(nodo, "municipio", "")
|
|
_ExpEnLoc = ValorXML(nodo, "localidad", "")
|
|
_ExpEnEst = ValorXML(nodo, "estado", "")
|
|
_ExpEnPais = ValorXML(nodo, "pais", "")
|
|
|
|
nodo = XMLDoc.DocumentElement.ChildNodes(0).ChildNodes(2)
|
|
_Regimen = ValorXML(nodo, "Regimen", "")
|
|
End Sub
|
|
Private Sub CargaReceptorXML(XMLDoc As XmlDocument)
|
|
Dim nodo As XmlNode = XMLDoc.DocumentElement.ChildNodes(1)
|
|
_RecRfc = ValorXML(nodo, "rfc", "")
|
|
_RecNombre = ValorXML(nodo, "nombre", "")
|
|
|
|
nodo = XMLDoc.DocumentElement.ChildNodes(1).ChildNodes(0)
|
|
|
|
_DomRecCalle = ValorXML(nodo, "calle", "")
|
|
_DomRecFisNoExt = ValorXML(nodo, "noExterior", "")
|
|
_DomRecFisNoInt = ValorXML(nodo, "noInterior", "")
|
|
_DomRecCol = ValorXML(nodo, "colonia", "")
|
|
_DomRecCP = ValorXML(nodo, "codigoPostal", "")
|
|
_DomRecMun = ValorXML(nodo, "municipio", "")
|
|
_DomRecLoc = ValorXML(nodo, "localidad", "")
|
|
_DomRecEst = ValorXML(nodo, "estado", "")
|
|
_DomRecPais = ValorXML(nodo, "pais", "")
|
|
End Sub
|
|
Private Sub CargaConceptosXML(XMLDoc As XmlDocument)
|
|
Dim i As Integer = 0
|
|
'Dim SB As New StringBuilder()
|
|
'SB.Append("<table border=""1"">")
|
|
'SB.AppendLine("<tr><td>cantidad</td><td>descripcion</td><td>valorUnitario</td><td>importe</td><td>unidad</td></tr>")
|
|
Dim nodo As XmlNode = Nothing
|
|
For i = 0 To XMLDoc.DocumentElement.ChildNodes(2).ChildNodes.Count - 1
|
|
nodo = XMLDoc.DocumentElement.ChildNodes(2).ChildNodes(i)
|
|
'SB.Append("<tr>")
|
|
'SB.Append("<td>" & XMLDoc.DocumentElement.ChildNodes(2).ChildNodes(i).Attributes("cantidad").Value & "</td>")
|
|
'SB.Append("<td>" & XMLDoc.DocumentElement.ChildNodes(2).ChildNodes(i).Attributes("descripcion").Value & "</td>")
|
|
'SB.Append("<td>" & XMLDoc.DocumentElement.ChildNodes(2).ChildNodes(i).Attributes("valorUnitario").Value & "</td>")
|
|
'SB.Append("<td>" & XMLDoc.DocumentElement.ChildNodes(2).ChildNodes(i).Attributes("importe").Value & "</td>")
|
|
'SB.Append("<td>" & XMLDoc.DocumentElement.ChildNodes(2).ChildNodes(i).Attributes("unidad").Value & "</td>")
|
|
'SB.Append("</tr>")
|
|
|
|
AddPS(nodo.Attributes.GetNamedItem("cantidad").Value.ToDouble(), nodo.Attributes.GetNamedItem("unidad").Value, nodo.Attributes.GetNamedItem("descripcion").Value, nodo.Attributes.GetNamedItem("valorUnitario").Value.ToDouble(), 0, nodo.Attributes.GetNamedItem("importe").Value.ToDouble())
|
|
Next
|
|
'SB.Append("</table>")
|
|
'If i > 0 Then Response.Write(SB.ToString)
|
|
'SB.Clear()
|
|
End Sub
|
|
Private Sub AddPS(Cantidad As Double, UM As String, PS As String, PU As Double, IVA As Double, Optional Total As Double = 0)
|
|
If PS <> "IVA" Then
|
|
Dim Row As DataRow = Nothing
|
|
Row = DTConceptos.NewRow()
|
|
Row("Consec") = DTConceptos.Rows.Count + 1
|
|
Row("Cantidad") = Cantidad
|
|
Row("UM") = UM
|
|
Row("PS") = PS
|
|
Row("PU") = PU
|
|
Row("IVA") = IVA
|
|
Row("Total") = If(Total > 0, Total, (Cantidad * PU))
|
|
DTConceptos.Rows.Add(Row)
|
|
End If
|
|
End Sub
|
|
Private Function GeneraPDFNew(TmpArchivoPDF As String, FolioFiscal As String, SubTotal As String, Descuento As String, Total As String, IVA As String,
|
|
Moneda As String, FormaDePago As String, NoSerieCertificado As String, FechaCertificacion As DateTime, NoSerieCertificadoContribuyente As String, DTConceptos As DataTable,
|
|
SelloCFDi As String, SelloSAT As String, CBB As String, Folio As String, TipodeComprobante As String, CadenaOriginalCFD As String,
|
|
RFC As String, Cliente As String, Direccion As String, Colonia As String, NoExt As String, NoInt As String,
|
|
CP As String, Ciudad As String, Estado As String, Regimen As String, CondicionPago As String, MetodoPago As String,
|
|
NumCtaPago As String, fecha As System.DateTime) As Boolean
|
|
Dim Retorno As Boolean = False
|
|
Dim NombreArchivo As String = TmpArchivoPDF
|
|
Dim CadenaOriginal As String = (Convert.ToString((Convert.ToString((Convert.ToString("||1.0|") & FolioFiscal) + "|" + FechaCertificacion.ToString("yyyy-MM-dd") + "T" + FechaCertificacion.ToString("HH:mm:ss") + "|") & SelloCFDi) + "|") & NoSerieCertificado) + "||"
|
|
Dim RutaFormato As String = String.Format("{0}Empresas\Grales\Formatos\CFDI.rdlc", ModExtensiones.DirectorioBaseEmpresas)
|
|
'Dim ArchivoTempXLS As String = String.Format("{0}\GenSis{1}-{2}", Path.GetDirectoryName(ArchivoBaseXLS), NowADS().Ticks, Path.GetFileName(ArchivoBaseXLS))
|
|
|
|
Dim Fiscal As String = String.Format("Domicilio Fiscal {0}{1} {2}{0}Col.{3}{0}CP. {4} {5},{6},{7}", vbCr, DomFisCalle, DomFisNoExt, DomFisCol, DomFisCP,
|
|
DomFisMun, DomFisEst, DomFisPais)
|
|
Try
|
|
Dim parametros As New List(Of ReportParameter)()
|
|
'params.Add(New ReportParameter("ArchivoBaseXLS", ArchivoBaseXLS))
|
|
'params.Add(New ReportParameter("TmpArchivoPDF", TmpArchivoPDF))
|
|
parametros.Add(New ReportParameter("FolioFiscal", FolioFiscal))
|
|
parametros.Add(New ReportParameter("SubTotal", SubTotal.FormatoNumero()))
|
|
parametros.Add(New ReportParameter("Descuento", Descuento.FormatoNumero()))
|
|
parametros.Add(New ReportParameter("Total", Total.FormatoNumero()))
|
|
parametros.Add(New ReportParameter("IVA", IVA.FormatoNumero()))
|
|
parametros.Add(New ReportParameter("Moneda", Moneda))
|
|
parametros.Add(New ReportParameter("FormaDePago", FormaDePago))
|
|
parametros.Add(New ReportParameter("NoSerieCertificado", NoSerieCertificado))
|
|
parametros.Add(New ReportParameter("FechaCertificacion", FechaCertificacion.ToString("yyyy-MM-dd") + "T" + FechaCertificacion.ToString("HH:mm:ss")))
|
|
parametros.Add(New ReportParameter("NoSerieCertificadoContribuyente", NoSerieCertificadoContribuyente))
|
|
parametros.Add(New ReportParameter("SelloCFDi", SelloCFDi))
|
|
parametros.Add(New ReportParameter("SelloSAT", SelloSAT))
|
|
parametros.Add(New ReportParameter("CBB", String.Format("file:///{0}", CBB)))
|
|
parametros.Add(New ReportParameter("Folio", Folio))
|
|
parametros.Add(New ReportParameter("TipodeComprobante", TipodeComprobante.ToUpper()))
|
|
parametros.Add(New ReportParameter("CadenaOriginalCFD", CadenaOriginalCFD))
|
|
parametros.Add(New ReportParameter("RFC", RFC))
|
|
parametros.Add(New ReportParameter("Cliente", Cliente))
|
|
parametros.Add(New ReportParameter("Direccion", Direccion))
|
|
parametros.Add(New ReportParameter("Colonia", Colonia))
|
|
parametros.Add(New ReportParameter("NoExt", NoExt))
|
|
parametros.Add(New ReportParameter("NoInt", NoInt))
|
|
parametros.Add(New ReportParameter("CP", CP))
|
|
parametros.Add(New ReportParameter("Ciudad", Ciudad))
|
|
parametros.Add(New ReportParameter("Estado", Estado))
|
|
parametros.Add(New ReportParameter("Regimen", Regimen))
|
|
parametros.Add(New ReportParameter("CondicionPago", CondicionPago))
|
|
parametros.Add(New ReportParameter("MetodoPago", MetodoPago))
|
|
parametros.Add(New ReportParameter("NumCtaPago", NumCtaPago))
|
|
parametros.Add(New ReportParameter("fecha", fecha.ToString("yyyy-MM-dd") + "T" + fecha.ToString("HH:mm:ss")))
|
|
parametros.Add(New ReportParameter("Fiscal", Fiscal))
|
|
parametros.Add(New ReportParameter("EmiNombre", EmiNombre))
|
|
parametros.Add(New ReportParameter("EmiRFC", EmiRFC))
|
|
parametros.Add(New ReportParameter("NoSerieCertificado", NoSerieCertificado))
|
|
parametros.Add(New ReportParameter("TotalLetra", Total.ToDecimal.Texto2Letras(CveMoneda:=If(Moneda = "MXN", 1, If(Moneda = "USD", 2, 3)))))
|
|
parametros.Add(New ReportParameter("Empresa", UsuarioActual.Empresa.Empresa))
|
|
|
|
'params.Add(New ReportParameter("DTConceptos", DTConceptos))
|
|
|
|
Dim rds As New ReportDataSource()
|
|
rds.Name = "DsOC"
|
|
rds.Value = DTConceptos
|
|
Dim Archivo As New System.IO.FileInfo(RutaFormato)
|
|
|
|
If Archivo.Exists Then
|
|
Dim MR As New ReportViewer()
|
|
MR.LocalReport.DataSources.Add(rds)
|
|
MR.LocalReport.ReportPath = RutaFormato
|
|
MR.ProcessingMode = ProcessingMode.Local
|
|
MR.LocalReport.EnableExternalImages = True
|
|
MR.LocalReport.SetParameters(parametros)
|
|
MR.LocalReport.Refresh()
|
|
|
|
|
|
Dim warnings As Warning() = Nothing
|
|
Dim streamids As String() = Nothing
|
|
Dim mimeType As String = Nothing
|
|
Dim encoding As String = Nothing
|
|
Dim extension As String = Nothing
|
|
Dim bytes As Byte() = Nothing
|
|
bytes = MR.LocalReport.Render("PDF", Nothing, mimeType, encoding, extension, streamids,
|
|
warnings)
|
|
|
|
Using fs As New FileStream(NombreArchivo, FileMode.Create)
|
|
fs.Write(bytes, 0, bytes.Length)
|
|
fs.Close()
|
|
End Using
|
|
Retorno = True
|
|
Else
|
|
ModExtensiones.GuardaLog(String.Format("No existe formato Base"))
|
|
|
|
|
|
End If
|
|
Catch ex As Exception
|
|
ModExtensiones.GuardaLog(String.Format("Ocurrio un Error al generar el reporte RLDC"))
|
|
Retorno = False
|
|
End Try
|
|
Return Retorno
|
|
End Function
|
|
Private Sub CreaDTConceptos()
|
|
DTConceptos = New DataTable()
|
|
DTConceptos.Columns.Add("Consec", GetType(Integer))
|
|
DTConceptos.Columns.Add("Cantidad", GetType(Double))
|
|
DTConceptos.Columns.Add("UM", GetType(String))
|
|
DTConceptos.Columns.Add("PS", GetType(String))
|
|
DTConceptos.Columns.Add("PU", GetType(Double))
|
|
DTConceptos.Columns.Add("IVA", GetType(Double))
|
|
DTConceptos.Columns.Add("Total", GetType(Double))
|
|
End Sub
|
|
#End Region
|
|
|
|
|
|
|
|
#Region "Sat descargamasiva"
|
|
Private Sub cargasolicitudes()
|
|
|
|
LnkverificarSolicitudes.Visible = False
|
|
|
|
Using nom As ClsNominas = New ClsNominas()
|
|
|
|
If nom.SolicitudesGet(-1, UsuarioActual.CveEmpresa, CveTipoSolicitud:=2, Estatus:=0, Top:=50) Then
|
|
GVSolicitudesPendientes.DataSource = nom.DtResultados
|
|
|
|
If nom.DtResultados.Rows.Count > 0 Then
|
|
LnkverificarSolicitudes.Visible = True
|
|
End If
|
|
|
|
GVSolicitudesPendientes.DataBind()
|
|
End If
|
|
|
|
'If nom.SolicitudesGet(1611, UsuarioActual.CveEmpresa, CveTipoSolicitud:=2, Estatus:=-1, Top:=50) Then
|
|
' GVSolicitudesPendientes.DataSource = nom.DtResultados
|
|
|
|
' If nom.DtResultados.Rows.Count > 0 Then
|
|
' LnkverificarSolicitudes.Visible = True
|
|
' End If
|
|
|
|
' GVSolicitudesPendientes.DataBind()
|
|
'End If
|
|
|
|
|
|
If nom.SolicitudesGet(-1, UsuarioActual.CveEmpresa, CveTipoSolicitud:=2, Estatus:=1, Top:=50) Then
|
|
GVSolicitudesHistorial.DataSource = nom.DtResultados
|
|
GVSolicitudesHistorial.DataBind()
|
|
End If
|
|
End Using
|
|
|
|
UPModalViewSolicitudes.Update()
|
|
|
|
|
|
End Sub
|
|
Protected Sub LnkShowSolicitudes_Click(ByVal sender As Object, ByVal e As EventArgs)
|
|
|
|
TabPanel.ActiveTabIndex = 0
|
|
cargasolicitudes()
|
|
RegistraScript("$('#ModalViewSolicitudes').modal();")
|
|
|
|
End Sub
|
|
|
|
'Protected Sub LnkSolicitarSat_Click(ByVal sender As Object, ByVal e As EventArgs)
|
|
' 'Dim idSolicitudCFDI As Integer = 0
|
|
' 'Dim idSolicitudMetadata As Integer = 0
|
|
' 'Dim estatus As Integer = 0
|
|
' 'Dim observaciones As String = ""
|
|
' 'Dim fechaInicio As DateTime = txtFechaIAdd.Text.ToDateTime()
|
|
' 'Dim fechaFin As DateTime = txtFechaFAdd.Text.ToDateTime()
|
|
' 'Dim cveUsuarioIng As Integer = UsuarioActual.CveUsuario
|
|
' 'Dim cveEmpresa As Integer = UsuarioActual.CveEmpresa
|
|
' 'Dim Continuar As Boolean = False
|
|
|
|
' 'Using nom As ClsNominas = New ClsNominas()
|
|
' ' Continuar = nom.SolicitudesAdd(idSolicitudCFDI, idSolicitudMetadata, estatus, observaciones, fechaInicio, fechaFin, cveUsuarioIng, cveEmpresa, 2)
|
|
' ' Dim api = New GeneralesAPIeFacturas()
|
|
' ' api.GeneraSolicitud()
|
|
' ' api.VerificaSolicitudesNominas()
|
|
' 'End Using
|
|
|
|
' 'If Continuar Then
|
|
' ' txtFechaIAdd.Text = ""
|
|
' ' txtFechaFAdd.Text = ""
|
|
' ' RegistraScript("$('#DModalSolicitudesNominas').modal('hide');")
|
|
' ' cargasolicitudes()
|
|
' ' Alert("se a envia la solicitud al sat, le enviaremos un correo en cuanto tengamos una respuesta", ModExtensiones.TipoMensaje.ToastInformacion)
|
|
' 'End If
|
|
|
|
' Dim idSolicitudCFDI As Integer = 0
|
|
' Dim idSolicitudMetadata As Integer = 0
|
|
' Dim estatus As Integer = 0
|
|
' Dim observaciones As String = ""
|
|
' Dim fechaInicio As DateTime = txtFechaIAdd.Text.ToDateTime()
|
|
' Dim fechaFin As DateTime = txtFechaFAdd.Text.ToDateTime()
|
|
' Dim cveUsuarioIng As Integer = UsuarioActual.CveUsuario
|
|
' Dim cveEmpresa As Integer = UsuarioActual.CveEmpresa
|
|
' Dim Continuar As Boolean = False
|
|
|
|
' Using nom As ClsNominas = New ClsNominas()
|
|
' Continuar = nom.SolicitudesAdd(idSolicitudCFDI, idSolicitudMetadata, estatus, observaciones, fechaInicio, fechaFin, cveUsuarioIng, cveEmpresa, CveTipoSolicitud:=3)
|
|
' End Using
|
|
|
|
' If Continuar Then
|
|
' Dim sbResultado As StringBuilder = New StringBuilder()
|
|
' Dim api = New GeneralesAPIeFacturas()
|
|
' Dim ObjApiSolicitud As JToken = CType(api.GeneraSolicitud(UsuarioActual.CveEmpresa, 3), JToken)
|
|
' Dim resultSolicitud As List(Of String) = New List(Of String)()
|
|
' Dim resultVerificacion As List(Of String) = New List(Of String)()
|
|
' Dim ResultadoVerificaionOK = False
|
|
' Dim SeVerifico = False
|
|
' Dim TipoMensaje = ModExtensiones.TipoMensaje.MsgInformacion
|
|
' Dim ResultadoSolicitudOK = False
|
|
|
|
' If Not (ObjApiSolicitud Is Nothing) Then
|
|
' resultSolicitud = ObjApiSolicitud.[Select](Function(token) token.Values().Aggregate(Function(i, j) $"{i}|{j}").Value(Of String)()).ToList()
|
|
' ResultadoSolicitudOK = Boolean.Parse(resultSolicitud(0))
|
|
' Else
|
|
' TipoMensaje = ModExtensiones.TipoMensaje.MsgAdvertencia
|
|
' End If
|
|
|
|
' If ResultadoSolicitudOK Then
|
|
' Dim ObjApiVerificacion As JToken = CType(api.VerificaSolicitudesNominas(UsuarioActual.CveEmpresa, 3), JToken)
|
|
|
|
' If Not (ObjApiVerificacion Is Nothing) Then
|
|
' resultVerificacion = ObjApiVerificacion.[Select](Function(token) token.Values().Aggregate(Function(i, j) $"{i}|{j}").Value(Of String)()).ToList()
|
|
' ResultadoVerificaionOK = Boolean.Parse(resultVerificacion(0))
|
|
' SeVerifico = True
|
|
' Else
|
|
' TipoMensaje = ModExtensiones.TipoMensaje.MsgAdvertencia
|
|
' End If
|
|
' End If
|
|
|
|
' If resultSolicitud.Count = 4 Then
|
|
|
|
' If ResultadoSolicitudOK Then
|
|
|
|
' If resultSolicitud(1).ToString().Trim().Length > 0 Then
|
|
' sbResultado.Append($"{resultSolicitud(1)}<br/>")
|
|
' Else
|
|
' sbResultado.Append($"Solicitud Generada Correctamente")
|
|
' sbResultado.Append($"Se presento un error al verificar las solicitudes <br/> {resultSolicitud(1)} <br>")
|
|
' End If
|
|
' Else
|
|
' sbResultado.Append($"{resultSolicitud(1)}")
|
|
' TipoMensaje = ModExtensiones.TipoMensaje.MsgAdvertencia
|
|
' End If
|
|
' Else
|
|
' sbResultado.AppendLine("Se presento un error al generar la solicitud (API) <br/>")
|
|
' TipoMensaje = ModExtensiones.TipoMensaje.MsgAdvertencia
|
|
' End If
|
|
|
|
' If SeVerifico AndAlso resultVerificacion.Count = 4 Then
|
|
|
|
' If ResultadoVerificaionOK Then
|
|
' sbResultado.Append($"{resultVerificacion(1)}<br>")
|
|
' Else
|
|
' sbResultado.Append($"Se presento un error al verificar las solicitudes {resultVerificacion(1)}<br>")
|
|
' TipoMensaje = ModExtensiones.TipoMensaje.MsgAdvertencia
|
|
' End If
|
|
' Else
|
|
' sbResultado.AppendLine("Se presento un error al verificar las solicitudes (API) <br/>")
|
|
' TipoMensaje = ModExtensiones.TipoMensaje.MsgAdvertencia
|
|
' End If
|
|
|
|
' Alert(sbResultado.ToString(), TipoMensaje)
|
|
' End If
|
|
|
|
' If Continuar Then
|
|
' txtFechaIAdd.Text = ""
|
|
' txtFechaFAdd.Text = ""
|
|
' RegistraScript("$('#ModalViewSolicitudes').modal('hide');")
|
|
' cargasolicitudes()
|
|
' End If
|
|
|
|
'End Sub
|
|
|
|
Protected Sub LnkSolicitarSat_Click(ByVal sender As Object, ByVal e As EventArgs)
|
|
|
|
|
|
|
|
Dim sbResultado As StringBuilder = New StringBuilder()
|
|
Dim idSolicitudCFDI As Integer = 0
|
|
Dim idSolicitudMetadata As Integer = 0
|
|
Dim estatus As Integer = 0
|
|
Dim observaciones As String = ""
|
|
Dim fechaInicio As DateTime = txtFechaIAdd.Text.ToDateTime()
|
|
Dim fechaFin As DateTime = txtFechaFAdd.Text.ToDateTime()
|
|
Dim cveUsuarioIng As Integer = UsuarioActual.CveUsuario
|
|
Dim cveEmpresa As Integer = UsuarioActual.CveEmpresa
|
|
Dim CveSolicitudAgregada As Integer = -1
|
|
Dim Folio As Integer = -1
|
|
|
|
Using nom As ClsNominas = New ClsNominas()
|
|
Dim CveTipoSolicitud As Integer = If(ChkMetaDatos.Checked, 202, 2)
|
|
CveSolicitudAgregada = nom.SolicitudesAdd2(idSolicitudCFDI, idSolicitudMetadata, estatus, observaciones, fechaInicio, fechaFin, cveUsuarioIng, cveEmpresa, CveTipoSolicitud:=CveTipoSolicitud)
|
|
|
|
If CveSolicitudAgregada > 0 Then
|
|
Folio = nom.FolioSolicitud
|
|
End If
|
|
End Using
|
|
|
|
If CveSolicitudAgregada > 0 Then
|
|
Dim api As New GeneralesAPIeFacturas()
|
|
Dim ObjApiSolicitud As JToken = CType(api.GeneraSolicitud(UsuarioActual.CveEmpresa, 2, CveSolicitudAgregada), JToken)
|
|
Dim resultSolicitud As List(Of String) = New List(Of String)()
|
|
Dim resultVerificacion As List(Of String) = New List(Of String)()
|
|
Dim TipoMensaje As ModExtensiones.TipoMensaje = ModExtensiones.TipoMensaje.MsgInformacion
|
|
Dim ResultadoSolicitudOK As Boolean = False
|
|
|
|
If Not (ObjApiSolicitud Is Nothing) Then
|
|
resultSolicitud = ObjApiSolicitud.[Select](Function(token) token.Values().Aggregate(Function(i, j) $"{i}|{j}").Value(Of String)()).ToList()
|
|
ResultadoSolicitudOK = Boolean.Parse(resultSolicitud(0))
|
|
Else
|
|
TipoMensaje = ModExtensiones.TipoMensaje.MsgAdvertencia
|
|
End If
|
|
|
|
If ResultadoSolicitudOK Then
|
|
sbResultado.Append($"Solicitud registrada. {resultSolicitud(1)}<br> Folio: {Folio}")
|
|
Else
|
|
|
|
If ObjApiSolicitud IsNot Nothing AndAlso resultSolicitud.Count = 4 Then
|
|
sbResultado.Append($"Solicitud registrada, pendiente de verificar en SAT <br> Folio: {Folio} <br>({resultSolicitud(1)})<br>")
|
|
Else
|
|
sbResultado.Append($"Solicitud registrada, pendiente de verificar en SAT <br> Folio: {Folio}")
|
|
End If
|
|
|
|
TipoMensaje = ModExtensiones.TipoMensaje.MsgAdvertencia
|
|
End If
|
|
|
|
Alert(sbResultado.ToString(), TipoMensaje)
|
|
Else
|
|
Alert("No se puedo registrar la solictud".ToString(), ModExtensiones.TipoMensaje.MsgAdvertencia)
|
|
End If
|
|
|
|
If CveSolicitudAgregada > 0 Then
|
|
txtFechaIAdd.Text = ""
|
|
txtFechaFAdd.Text = ""
|
|
ChkMetaDatos.Checked = False
|
|
RegistraScript("$('#ModalAgregarSolicitud').modal('hide');")
|
|
cargasolicitudes()
|
|
End If
|
|
End Sub
|
|
|
|
'Protected Sub LnkverificarSolicitudes_Click(ByVal sender As Object, ByVal e As EventArgs)
|
|
|
|
|
|
|
|
|
|
' Dim sbResultado As StringBuilder = New StringBuilder()
|
|
' Dim api = New GeneralesAPIeFacturas()
|
|
' Dim ObjApiSolicitud As JToken = CType(api.GeneraSolicitud(UsuarioActual.CveEmpresa, 3), JToken)
|
|
' Dim resultSolicitud As List(Of String) = New List(Of String)()
|
|
' Dim resultVerificacion As List(Of String) = New List(Of String)()
|
|
' Dim ResultadoVerificaionOK = False
|
|
' Dim SeVerifico = False
|
|
' Dim TipoMensaje = ModExtensiones.TipoMensaje.MsgInformacion
|
|
' Dim ResultadoSolicitudOK = False
|
|
|
|
' If Not (ObjApiSolicitud Is Nothing) Then
|
|
' resultSolicitud = ObjApiSolicitud.[Select](Function(token) token.Values().Aggregate(Function(i, j) $"{i}|{j}").Value(Of String)()).ToList()
|
|
' ResultadoSolicitudOK = Boolean.Parse(resultSolicitud(0))
|
|
' Else
|
|
' TipoMensaje = ModExtensiones.TipoMensaje.MsgAdvertencia
|
|
' End If
|
|
|
|
' If ResultadoSolicitudOK Then
|
|
' Dim ObjApiVerificacion As JToken = CType(api.VerificaSolicitudesNominas(UsuarioActual.CveEmpresa, 3), JToken)
|
|
|
|
' If Not (ObjApiVerificacion Is Nothing) Then
|
|
' resultVerificacion = ObjApiVerificacion.[Select](Function(token) token.Values().Aggregate(Function(i, j) $"{i}|{j}").Value(Of String)()).ToList()
|
|
' ResultadoVerificaionOK = Boolean.Parse(resultVerificacion(0))
|
|
' SeVerifico = True
|
|
' Else
|
|
' TipoMensaje = ModExtensiones.TipoMensaje.MsgAdvertencia
|
|
' End If
|
|
' End If
|
|
|
|
' If resultSolicitud.Count = 4 Then
|
|
|
|
' If ResultadoSolicitudOK Then
|
|
|
|
' If resultSolicitud(2).ToString().Trim().Length > 0 Then
|
|
' sbResultado.Append($"{resultSolicitud(2)}<br/>")
|
|
' Else
|
|
' sbResultado.Append($"Solicitud Generada Correctamente")
|
|
' sbResultado.Append($"Se presento un error al verificar las solicitudes <br/> {resultSolicitud(1)} <br>")
|
|
' End If
|
|
' Else
|
|
' sbResultado.Append($"{resultSolicitud(1)}")
|
|
' TipoMensaje = ModExtensiones.TipoMensaje.MsgAdvertencia
|
|
' End If
|
|
' Else
|
|
' sbResultado.AppendLine("Se presento un error al generar la solicitud (API) <br/>")
|
|
' TipoMensaje = ModExtensiones.TipoMensaje.MsgAdvertencia
|
|
' End If
|
|
|
|
' If SeVerifico AndAlso resultVerificacion.Count = 4 Then
|
|
|
|
' If ResultadoVerificaionOK Then
|
|
' sbResultado.Append($"{resultVerificacion(1)}<br>")
|
|
' Else
|
|
' sbResultado.Append($"Se presento un error al verificar las solicitudes {resultVerificacion(1)}<br>")
|
|
' TipoMensaje = ModExtensiones.TipoMensaje.MsgAdvertencia
|
|
' End If
|
|
' Else
|
|
' sbResultado.AppendLine("Se presento un error al verificar las solicitudes (API) <br/>")
|
|
' TipoMensaje = ModExtensiones.TipoMensaje.MsgAdvertencia
|
|
' End If
|
|
|
|
' Alert(sbResultado.ToString(), TipoMensaje)
|
|
' cargasolicitudes()
|
|
|
|
|
|
|
|
'End Sub
|
|
|
|
|
|
Protected Sub LnkverificarSolicitudes_Click(ByVal sender As Object, ByVal e As EventArgs)
|
|
Try
|
|
Dim sbResultado As StringBuilder = New StringBuilder()
|
|
Dim sbArchivosFaltantes As New StringBuilder()
|
|
|
|
Dim TipoMensaje As ModExtensiones.TipoMensaje = ModExtensiones.TipoMensaje.MsgInformacion
|
|
|
|
|
|
|
|
For Each GvRow As GridViewRow In GVSolicitudesPendientes.Rows
|
|
|
|
Dim ListComprimidos As New List(Of String)
|
|
Dim ListXML As New List(Of String)
|
|
Dim ListPDF As New List(Of String)
|
|
|
|
Dim CveSolicitudActual As Integer = GvRow.DataKey("CveSolicitud").ToEntero()
|
|
Dim idSolicitud As String = GvRow.DataKey("idSolicitud").Trim()
|
|
Dim CveTipoSolicitud As Integer = GvRow.DataKey("CveTipoSolicitud").ToEntero()
|
|
Dim Folio As Integer = GvRow.DataKey("Folio").ToEntero()
|
|
Dim CveSolicitudDetalle As Integer = GvRow.DataKey("CveSolicitudDetalle").ToEntero()
|
|
|
|
Dim resultSolicitud As List(Of String) = New List(Of String)()
|
|
Dim resultVerificacion As List(Of String) = New List(Of String)()
|
|
Dim ResultadoVerificaionOK As Boolean = False
|
|
Dim SeVerifico As Boolean = False
|
|
|
|
Dim ResultadoSolicitudOK As Boolean = False
|
|
Dim api As New GeneralesAPIeFacturas(If(EsProduccion, "http://localhost:4001/", "http://localhost:60281/"))
|
|
|
|
|
|
Dim Verificar As Boolean = True
|
|
|
|
If idSolicitud.Length = 0 Then
|
|
Dim ObjApiSolicitud As JToken = CType(api.GeneraSolicitud(UsuarioActual.CveEmpresa, CveTipoSolicitud, CveSolicitudActual), JToken)
|
|
|
|
If Not (ObjApiSolicitud Is Nothing) Then
|
|
resultSolicitud = ObjApiSolicitud.[Select](Function(token) token.Values().Aggregate(Function(i, j) $"{i}|{j}").Value(Of String)()).ToList()
|
|
ResultadoSolicitudOK = Boolean.Parse(resultSolicitud(0))
|
|
|
|
Try
|
|
sbResultado.Append($"Solicitud {Folio} { resultSolicitud(1)}.<br>")
|
|
|
|
If resultSolicitud(1).Contains("No se Generaron solicitudes al SAT") Then
|
|
Verificar = False
|
|
Else
|
|
Verificar = True
|
|
End If
|
|
Catch ex As Exception
|
|
sbResultado.Append($"Solicitud {Folio} solicitada a SAT.<br>")
|
|
Verificar = False
|
|
End Try
|
|
|
|
|
|
Else
|
|
TipoMensaje = ModExtensiones.TipoMensaje.MsgAdvertencia
|
|
End If
|
|
Else
|
|
resultSolicitud = New List(Of String)()
|
|
resultSolicitud.Add("true")
|
|
resultSolicitud.Add("")
|
|
resultSolicitud.Add("")
|
|
resultSolicitud.Add("")
|
|
ResultadoSolicitudOK = True
|
|
Verificar = True
|
|
End If
|
|
|
|
If ResultadoSolicitudOK And Verificar Then
|
|
|
|
If EsProduccion Then
|
|
Dim ObjApiVerificacion As JToken = CType(api.VerificaSolicitudesNominas(UsuarioActual.CveEmpresa, CveTipoSolicitud, CveSolicitudActual), JToken)
|
|
|
|
If Not (ObjApiVerificacion Is Nothing) Then
|
|
resultVerificacion = ObjApiVerificacion.[Select](Function(token) token.Values().Aggregate(Function(i, j) $"{i}|{j}").Value(Of String)()).ToList()
|
|
|
|
ResultadoVerificaionOK = Boolean.Parse(resultVerificacion(0))
|
|
SeVerifico = True
|
|
Else
|
|
TipoMensaje = ModExtensiones.TipoMensaje.MsgAdvertencia
|
|
End If
|
|
Else
|
|
ResultadoVerificaionOK = True
|
|
SeVerifico = True
|
|
End If
|
|
|
|
Dim Archivo = New FileInfo(String.Format("{0}DescargasSATXML\Compras\{1}.zip", UsuarioActual.Empresa.Ruta, CveSolicitudDetalle))
|
|
Dim fileName = Archivo.Name
|
|
Dim filemove = Archivo.FullName
|
|
|
|
If ResultadoVerificaionOK AndAlso Archivo.Exists Then
|
|
Try
|
|
'COPIAR ARCHIVO A LA CARPETA DE PROCESAMIENTO DE FACTURAS, SE ELIMINARAN ESOS ARCHIVOS TEMPORALES
|
|
Dim destFile = String.Format("{0}Temp\Facturas\{1}", UsuarioActual.Empresa.Ruta, fileName)
|
|
File.Copy(filemove, destFile, overwrite:=True)
|
|
|
|
If File.Exists(destFile) Then
|
|
ListComprimidos.Add(destFile)
|
|
'GuardaLogAD($"eFacturas Solicitudes SAT Archivo copiado a {destFile}")
|
|
Else
|
|
sbArchivosFaltantes.AppendFormat("<br/> Folio: {0} Archivo: {1}", Folio, fileName)
|
|
End If
|
|
|
|
Catch ex As Exception
|
|
ex.ToString().GuardaLog()
|
|
sbArchivosFaltantes.AppendFormat("<br/> Folio: {0} Archivo: {1}. Error al procesar", Folio, fileName)
|
|
End Try
|
|
|
|
End If
|
|
|
|
Else
|
|
|
|
If resultSolicitud.Count >= 4 Then
|
|
sbResultado.Append($"({resultSolicitud(1)})<br> Folio:{Folio} <br> ")
|
|
Else
|
|
sbResultado.Append($"Solicitud pendiente de verificar en SAT <br> Folio:{Folio} <br>")
|
|
End If
|
|
|
|
TipoMensaje = ModExtensiones.TipoMensaje.MsgAdvertencia
|
|
End If
|
|
|
|
If SeVerifico Then
|
|
SubirFacturas(ListComprimidos, ListXML, ListPDF, Validada:=1)
|
|
End If
|
|
|
|
'If UsuarioActual.CveRol = 1 Then
|
|
' Alert($"SeVerifico {SeVerifico.ToString} resultVerificacion.Count {resultVerificacion.Count }")
|
|
'End If
|
|
|
|
If Verificar Then
|
|
If SeVerifico AndAlso resultVerificacion.Count >= 4 Then
|
|
|
|
If ResultadoVerificaionOK Then
|
|
sbResultado.Append($"Solicitud procesadaFolio: {Folio} <br> {resultVerificacion(1)}")
|
|
Else
|
|
sbResultado.Append($"Solicitud no verificada <br> Folio: {Folio}{resultVerificacion(1)}.<br>")
|
|
TipoMensaje = ModExtensiones.TipoMensaje.MsgAdvertencia
|
|
End If
|
|
Else
|
|
sbResultado.Append($"Se presento un error al verificar la solicitud Folio: {Folio}. <br>")
|
|
TipoMensaje = ModExtensiones.TipoMensaje.MsgAdvertencia
|
|
End If
|
|
End If
|
|
|
|
|
|
Next
|
|
|
|
Alert(sbResultado.ToString(), TipoMensaje)
|
|
|
|
If sbArchivosFaltantes.Length > 0 Then
|
|
Alert($"No se pudieron procesar los siguientes folios. {sbArchivosFaltantes.ToString()}", TipoMensaje.MsgError)
|
|
End If
|
|
|
|
cargasolicitudes()
|
|
Catch ex As Exception
|
|
Alert(ex.StackTrace)
|
|
End Try
|
|
End Sub
|
|
|
|
|
|
Protected Sub LnkAgregarSolictud_Click(ByVal sender As Object, ByVal e As EventArgs)
|
|
txtFechaIAdd.Text = ""
|
|
txtFechaFAdd.Text = ""
|
|
ChkMetaDatos.Checked = False
|
|
UPModalViewSolicitudesAgregar.Update()
|
|
RegistraScript("$('#ModalAgregarSolicitud').modal('show');")
|
|
End Sub
|
|
|
|
Protected Sub GVSolicitudesHistorial_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
|
|
If e.Row.RowType = DataControlRowType.DataRow Then
|
|
|
|
|
|
If e.Row.DataKey("ArchivoXML").Length > 0 Then
|
|
Dim UrlDescarga As String = $"{UsuarioActual.Empresa.Ruta}DescargasSATXML\\Compras\\{e.Row.DataKey("CveSolicitudDetalle")}.zip"
|
|
|
|
If System.IO.File.Exists(UrlDescarga) Then
|
|
Dim LnkDescargaXML As LinkButton = e.Row.FCLinkButton("LnkDescargaXML")
|
|
ScriptManager.GetCurrent(Me).RegisterPostBackControl(LnkDescargaXML)
|
|
LnkDescargaXML.Visible = True
|
|
Else
|
|
Dim UrlDescarga2 As String = $"{UsuarioActual.Empresa.Ruta}NomXMLSAT\\Descargas\\{e.Row.DataKey("ArchivoXML")}"
|
|
If System.IO.File.Exists(UrlDescarga2) Then
|
|
Dim LnkDescargaXML As LinkButton = e.Row.FCLinkButton("LnkDescargaXML")
|
|
ScriptManager.GetCurrent(Me).RegisterPostBackControl(LnkDescargaXML)
|
|
LnkDescargaXML.Visible = True
|
|
End If
|
|
End If
|
|
End If
|
|
|
|
Dim lblobservaciones As Label = e.Row.FCLabel("lblobservaciones")
|
|
Dim lBLTipoDescarga As Label = e.Row.FCLabel("lBLTipoDescarga")
|
|
|
|
lblobservaciones.Attributes.Add("data-html", "true")
|
|
lblobservaciones.Attributes.Add("data-toggle", "tooltip")
|
|
lblobservaciones.Attributes.Add("data-placement", "top")
|
|
lblobservaciones.Attributes.Add("title", e.Row.DataKey("Observaciones"))
|
|
lBLTipoDescarga.Attributes.Add("data-html", "true")
|
|
lBLTipoDescarga.Attributes.Add("data-toggle", "tooltip")
|
|
lBLTipoDescarga.Attributes.Add("data-placement", "top")
|
|
lBLTipoDescarga.Attributes.Add("title", e.Row.DataKey("TipoDescargaStr"))
|
|
|
|
End If
|
|
End Sub
|
|
|
|
|
|
Protected Sub LnkDescargaXML_Click(ByVal sender As Object, ByVal e As EventArgs)
|
|
Dim GvRow As GridViewRow = CType((CType(sender, LinkButton)).NamingContainer, GridViewRow)
|
|
Dim UrlDescarga As String = $"{UsuarioActual.Empresa.Ruta}DescargasSATXML\\Compras\\{GvRow.DataKey("CveSolicitudDetalle")}.zip"
|
|
Dim Archivo As New System.IO.FileInfo(UrlDescarga)
|
|
|
|
If Not Archivo.Exists Then
|
|
Dim UrlDescarga2 As String = $"{UsuarioActual.Empresa.Ruta}NomXMLSAT\\Descargas\\{GvRow.DataKey("ArchivoXML")}"
|
|
Archivo = New System.IO.FileInfo(UrlDescarga2)
|
|
End If
|
|
|
|
If Archivo.Exists Then
|
|
Response.Clear()
|
|
Response.AddHeader("Content-Disposition", "attachment; filename=" & Archivo.Name)
|
|
Response.AddHeader("Content-Length", Archivo.Length.ToString())
|
|
Response.ContentType = "text/octet-stream"
|
|
Response.Flush()
|
|
Response.TransmitFile(Archivo.FullName)
|
|
Response.[End]()
|
|
End If
|
|
|
|
End Sub
|
|
|
|
Private Sub MostrarSolcitudesSAT()
|
|
|
|
LnkShowSolicitudes.Visible = False
|
|
|
|
If UsuarioActual.Empresa.FielPFX.Trim.Length > 0 Then
|
|
Dim ArchivoCertificado As String = $"{UsuarioActual.Empresa.Ruta}Certificados\{UsuarioActual.Empresa.FielPFX}"
|
|
If File.Exists(ArchivoCertificado) Then
|
|
LnkShowSolicitudes.Visible = True
|
|
End If
|
|
End If
|
|
|
|
End Sub
|
|
|
|
|
|
#End Region
|
|
|
|
|
|
|
|
|
|
#Region "D E S C A R G A R - F A C T U R A "
|
|
'Protected Sub lbDescargar_Click(sender As Object, e As EventArgs) Handles lbDescargar.Click
|
|
|
|
' Dim Retorno As Boolean = False
|
|
|
|
' Dim ObjProcess As Process = Nothing
|
|
' Dim Mensajes As String = ""
|
|
' Dim error1 As Boolean = False
|
|
' Dim CountProcesados As Integer = 0
|
|
|
|
|
|
|
|
' Try
|
|
' ObjProcess = New Process()
|
|
' ObjProcess.StartInfo.RedirectStandardOutput = True
|
|
' ObjProcess.StartInfo.FileName = Ejecutable
|
|
' ObjProcess.StartInfo.Arguments = $"--mod dsat2 --cveemp {UsuarioActual.CveEmpresa} --rfc {UsuarioActual.Empresa.RFC} --ciec {UsuarioActual.Empresa.CIEC} --razon {UsuarioActual.Empresa.Empresa} --fi {txtFechaI.Text} --ff {txtFechaF.Text}"
|
|
' ObjProcess.StartInfo.UseShellExecute = False
|
|
' ObjProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal
|
|
' ObjProcess.Start()
|
|
|
|
|
|
' Dim myStreamReader As StreamReader = ObjProcess.StandardOutput
|
|
|
|
' 'Read the standard output of the spawned process.
|
|
' Mensajes = myStreamReader.ReadLine()
|
|
' If Mensajes.Length > 0 Then
|
|
|
|
' Dim msgs As String() = Mensajes.Split("|"c)
|
|
' Dim NFacturas As Integer = 0
|
|
|
|
' If msgs.Length >= 2 Then
|
|
' Try
|
|
' NFacturas = msgs(0).ToEntero
|
|
' CountProcesados = msgs(0).ToEntero
|
|
' Mensajes = $"La actualización se realizó correctamente. <br> Facturas agregadas: { NFacturas }"
|
|
' Catch ex As Exception
|
|
' NFacturas = 0
|
|
' Mensajes = "La actualización se realizó correctamente"
|
|
' End Try
|
|
' Else
|
|
' Mensajes = "La descarga se realizó correctamente"
|
|
' End If
|
|
' End If
|
|
' ObjProcess.WaitForExit()
|
|
' ObjProcess.Close()
|
|
' Retorno = True
|
|
' Catch ex As Exception
|
|
' error1 = True
|
|
' OnError("Ocurrió un error al ejecutar el actualizador.", ex)
|
|
' End Try
|
|
|
|
' If Retorno Then CargaDatos()
|
|
|
|
|
|
|
|
|
|
|
|
'End Sub
|
|
|
|
|
|
'Private Sub ProcesaBuzon()
|
|
' Dim ObjProcess As Process = Nothing
|
|
' Dim Mensajes As String = ""
|
|
' Dim EjecutableUtilerias = Path.Combine(ModExtensiones.DirectorioBaseEmpresas, "Utilerias\ADSUtilerias.exe")
|
|
' Dim Folder = Path.Combine(ModExtensiones.DirectorioBaseEmpresas, "Empresas\")
|
|
' Dim error1 As Boolean = False
|
|
' Dim en As New CultureInfo("en-US")
|
|
' Dim fechai = txtFechaI.Text.Trim.ToDate.ToString("d", en)
|
|
' Dim fechaf = txtFechaF.Text.Trim.ToDate.ToString("d", en)
|
|
' Dim Salida As String = ""
|
|
' Try
|
|
' ObjProcess = New Process()
|
|
' ObjProcess.StartInfo.RedirectStandardOutput = True
|
|
' ObjProcess.StartInfo.FileName = EjecutableUtilerias
|
|
' ObjProcess.StartInfo.Verb = "runas"
|
|
' ObjProcess.StartInfo.Arguments = $"--mod dsat --e {UsuarioActual.CveEmpresa} --op 1 --fd {Folder} --fi {fechai} --ff {fechaf}"
|
|
' ObjProcess.StartInfo.UseShellExecute = False
|
|
' ObjProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal
|
|
' ObjProcess.Start()
|
|
' Salida = ObjProcess.StandardOutput.ReadToEnd()
|
|
' ObjProcess.WaitForExit()
|
|
' ObjProcess.Close()
|
|
' Catch ex As Exception
|
|
' error1 = True
|
|
' OnError("Ocurrió un error al ejecutar el actualizador.", ex)
|
|
' End Try
|
|
'End Sub
|
|
|
|
#End Region
|
|
|
|
#Region "B I T A C O R A"
|
|
Private Sub CargaGvBitacora()
|
|
Dim ObjGral As New ClsGenerales
|
|
If ObjGral.GetHistorialBitacoraRemoveGet("Compras", UsuarioActual.CveEmpresa) Then
|
|
GvBitacora.DataSource = ObjGral.DtResultados
|
|
ObjGral.Dispose()
|
|
End If
|
|
GvBitacora.DataBind()
|
|
End Sub
|
|
|
|
Private Sub BtnRemove_Click(sender As Object, e As EventArgs) Handles BtnRemove.Click
|
|
Dim Borrar As Boolean = False
|
|
If Not TxtDescripcion.Text = "" Then
|
|
Dim ObjGral As New ClsGenerales
|
|
If ObjGral.AddHistorialBitacora(Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, "", "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, 1, TxtDescripcion.Text, "Compras", Folio1 + " / " + Proveedor) Then
|
|
Borrar = True
|
|
End If
|
|
ObjGral.Dispose()
|
|
If Borrar = True Then
|
|
Dim ObjCompras As New ClsCompras
|
|
If ObjCompras.DeleteFactura(CveFactura, UsuarioActual.CveEmpresa) Then
|
|
GvD.EditIndex = -1
|
|
RegistraScript(String.Format("$('#{0}').modal('hide');", "divDescripcion"))
|
|
Alert("La factura se eliminó correctamente.", TipoMensaje.MsgInformacion)
|
|
CargaDatos(NowADS())
|
|
UpBitacora.Update()
|
|
End If
|
|
|
|
ObjCompras.Dispose()
|
|
|
|
End If
|
|
End If
|
|
CargaGvBitacora()
|
|
UpBitacora.Update()
|
|
End Sub
|
|
Private Sub BtnEliminarPago_Click(sender As Object, e As EventArgs) Handles BtnEliminarPago.Click
|
|
Dim Borrar As Boolean = False
|
|
If Not TxtDescripcion.Text = "" Then
|
|
Dim ObjGral As New ClsGenerales
|
|
If ObjGral.AddHistorialBitacora(Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, "", "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, 1, TxtDescripcion.Text, "Compras", Folio1 + " / " + Proveedor) Then
|
|
Borrar = True
|
|
End If
|
|
ObjGral.Dispose()
|
|
If Borrar = True Then
|
|
Dim ObjCompras As New ClsCompras
|
|
If ObjCompras.DeleteFactura(CveFactura, UsuarioActual.CveEmpresa) Then
|
|
GvPagos.EditIndex = -1
|
|
RegistraScript("$('#divDescripcionPago').modal('hide');")
|
|
Alert("La factura se eliminó correctamente.", TipoMensaje.MsgInformacion)
|
|
CargaDatos(NowADS())
|
|
UpBitacora.Update()
|
|
End If
|
|
|
|
ObjCompras.Dispose()
|
|
End If
|
|
End If
|
|
CargaGvBitacora()
|
|
UpBitacora.Update()
|
|
End Sub
|
|
|
|
Private Sub BtnMostrar_Click(sender As Object, e As EventArgs) Handles BtnMostrar.Click
|
|
GvBitacora.Visible = True
|
|
BtnOcultar.Visible = True
|
|
BtnMostrar.Visible = False
|
|
UpBitacora.Update()
|
|
End Sub
|
|
|
|
Private Sub BtnOcultar_Click(sender As Object, e As EventArgs) Handles BtnOcultar.Click
|
|
GvBitacora.Visible = False
|
|
BtnOcultar.Visible = False
|
|
BtnMostrar.Visible = True
|
|
UpBitacora.Update()
|
|
End Sub
|
|
|
|
#End Region
|
|
|
|
|
|
Property MSGComplemento As String
|
|
Get
|
|
If ViewState("MSGComplemento") Is Nothing Then
|
|
Return ""
|
|
Else
|
|
Return ViewState("MSGComplemento").ToString
|
|
End If
|
|
End Get
|
|
Set(value As String)
|
|
ViewState("MSGComplemento") = value
|
|
End Set
|
|
End Property
|
|
|
|
Property ViculacionConPUE As Boolean
|
|
Get
|
|
If ViewState("ViculacionConPUE") Is Nothing Then
|
|
Return False
|
|
Else
|
|
Return Boolean.Parse(ViewState("ViculacionConPUE").ToString)
|
|
End If
|
|
End Get
|
|
Set(value As Boolean)
|
|
ViewState("ViculacionConPUE") = value
|
|
End Set
|
|
End Property
|
|
|
|
|
|
Property ListaComprasPUE As List(Of Integer)
|
|
Get
|
|
If ViewState("ListaComprasPUE") Is Nothing Then
|
|
Return New List(Of Integer)
|
|
Else
|
|
Return DirectCast(ViewState("ListaComprasPUE"), List(Of Integer))
|
|
End If
|
|
End Get
|
|
Set(value As List(Of Integer))
|
|
ViewState("ListaComprasPUE") = value
|
|
End Set
|
|
End Property
|
|
|
|
|
|
Property ComplementoConPUE As String
|
|
Get
|
|
If ViewState("ComplementoConPUE") Is Nothing Then
|
|
Return ""
|
|
Else
|
|
Return ViewState("ComplementoConPUE").ToString
|
|
End If
|
|
End Get
|
|
Set(value As String)
|
|
ViewState("ComplementoConPUE") = value
|
|
End Set
|
|
End Property
|
|
|
|
Property DT_ComprasSinIE As DataTable
|
|
Get
|
|
If ViewState("DT_ComprasSinIE") Is Nothing Then
|
|
Return New DataTable
|
|
Else
|
|
Return DirectCast(ViewState("DT_ComprasSinIE"), DataTable)
|
|
End If
|
|
End Get
|
|
Set(value As DataTable)
|
|
ViewState("DT_ComprasSinIE") = value
|
|
End Set
|
|
End Property
|
|
|
|
|
|
|
|
'Property ComplementoComprasSinIE As String
|
|
' Get
|
|
' If ViewState("ComplementoComprasSinIE") Is Nothing Then
|
|
' Return ""
|
|
' Else
|
|
' Return ViewState("ComplementoComprasSinIE").ToString
|
|
' End If
|
|
' End Get
|
|
' Set(value As String)
|
|
' ViewState("ComplementoComprasSinIE") = value
|
|
' End Set
|
|
'End Property
|
|
|
|
|
|
|
|
#Region "V I N C U L A R P A G O"
|
|
|
|
Protected Sub LnkAgregarPago_Click(sender As Object, e As EventArgs)
|
|
SeVinculoConComprasFaltantes = False
|
|
Dim sbSinIE As New StringBuilder
|
|
Dim TieneCompras As Boolean = False
|
|
HdnCveIE.Value = ""
|
|
MSGComplemento = ""
|
|
ViculacionConPUE = False
|
|
ListaComprasPUE.Clear()
|
|
ComplementoConPUE = ""
|
|
DT_ComprasSinIE = New DataTable
|
|
Dim ListaComprasPUEInterna As New List(Of Integer)
|
|
Dim gvRow As GridViewRow = DirectCast((DirectCast(sender, LinkButton)).NamingContainer, GridViewRow)
|
|
|
|
Dim CveFacturaComplemento As Integer = gvRow.DataKey("CveFactura").ToString.ToEntero
|
|
Dim CveComplementoPagoCompra As Integer = gvRow.DataKey("CveComplementoPagoCompra").ToString.ToEntero
|
|
Dim SerieFolioIE As String = ""
|
|
Dim UUIDPago As String = ""
|
|
'Dim ImportePago As Decimal = 0
|
|
Dim StrUUID As New StringBuilder
|
|
Dim Monto As Decimal = 0
|
|
Dim nodePagos As XmlNode = Nothing
|
|
Dim nodePagos2 As XmlNode = Nothing
|
|
Dim nodeComp As XmlNode = Nothing
|
|
Dim nodeaGral As XmlNode = Nothing
|
|
Dim nodeTFD As XmlNode = Nothing
|
|
Dim ImporteIES As Double = 0
|
|
Dim DiferenciaImportes As Double = 0
|
|
Dim TextoDiferenciaImporte As String = ""
|
|
Dim FechaPago As Date
|
|
Dim PagosCantidad As Integer = 0
|
|
|
|
Dim UUIDDuplicados As String = ""
|
|
Dim ListaUUIDDuplicados As New List(Of String)
|
|
|
|
DTGVPagosVinculacion = New DataTable
|
|
MontoPago = 0D
|
|
ComprasEnComplemento = 0
|
|
|
|
XMLNodosPagosModalCount = 0
|
|
|
|
Dim XMLDoc As New XmlDocument
|
|
Dim Archivo As String = String.Format("{0}Compras\{1}\{2}", UsuarioActual.Empresa.Ruta, gvRow.DataKey("RFCDe"), gvRow.DataKey("XML"))
|
|
|
|
Dim Prefijo As String = ""
|
|
Dim DTDocumentosRelacionados As New DataTable
|
|
DTDocumentosRelacionados.Columns.Add("Serie")
|
|
DTDocumentosRelacionados.Columns.Add("SerieFolio")
|
|
|
|
DTDocumentosRelacionados.Columns.Add("IdDocumento")
|
|
DTDocumentosRelacionados.Columns.Add("Folio", GetType(Integer))
|
|
DTDocumentosRelacionados.Columns.Add("MonedaDR")
|
|
DTDocumentosRelacionados.Columns.Add("MetodoDePagoDR")
|
|
DTDocumentosRelacionados.Columns.Add("ImpPagado", GetType(Decimal))
|
|
|
|
DTDocumentosRelacionados.Columns.Add("CveFactura", GetType(Integer))
|
|
DTDocumentosRelacionados.Columns.Add("CveCompra", GetType(Integer))
|
|
DTDocumentosRelacionados.Columns.Add("CveIE", GetType(Integer))
|
|
DTDocumentosRelacionados.Columns.Add("Fecha", GetType(Date))
|
|
|
|
DTDocumentosRelacionados.Columns.Add("FolioPago")
|
|
DTDocumentosRelacionados.Columns.Add("ImportePago", GetType(Decimal))
|
|
DTDocumentosRelacionados.Columns.Add("FechaPago", GetType(Date))
|
|
DTDocumentosRelacionados.Columns.Add("CveMetodoPago", GetType(Integer))
|
|
DTDocumentosRelacionados.Columns.Add("SerieFolioCompra")
|
|
DTDocumentosRelacionados.Columns.Add("CvePrePolizaDetalle", GetType(Integer))
|
|
DTDocumentosRelacionados.Columns.Add("Tipo", GetType(String))
|
|
DTDocumentosRelacionados.Columns.Add("Manual", GetType(Boolean))
|
|
|
|
|
|
Dim TieneRegistros As Boolean = False
|
|
If IO.File.Exists(Archivo) Then
|
|
|
|
Dim SXML As String = File.ReadAllText(Archivo).Replace(vbLf, " ").Replace(vbCrLf, " ")
|
|
SXML = SXML.Replace("o;?", "")
|
|
SXML = SXML.Trim((Convert.ToChar(0)))
|
|
|
|
XMLDoc.LoadXml(SXML)
|
|
|
|
Dim Xml As New StringBuilder
|
|
Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable)
|
|
Dim RootDocumento As XmlElement = XMLDoc.DocumentElement
|
|
Dim VersionCFDI As String = ValorXML(RootDocumento, "version")
|
|
|
|
If VersionCFDI = "3.3" Then
|
|
Prefijo = "pago10"
|
|
namespaces.AddNamespace("pago10", "http://www.sat.gob.mx/Pagos")
|
|
namespaces.AddNamespace(XMLDoc.DocumentElement.Prefix, "http://www.sat.gob.mx/cfd/3")
|
|
ElseIf VersionCFDI = "4.0" Then
|
|
Prefijo = "pago20"
|
|
namespaces.AddNamespace("pago20", "http://www.sat.gob.mx/Pagos20")
|
|
namespaces.AddNamespace(XMLDoc.DocumentElement.Prefix, "http://www.sat.gob.mx/cfd/4")
|
|
End If
|
|
namespaces.AddNamespace("aerolineas", "http://www.sat.gob.mx/aerolineas")
|
|
namespaces.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital")
|
|
nodeComp = XMLDoc.SelectSingleNode(String.Format("//{0}:Complemento", XMLDoc.DocumentElement.Prefix), namespaces)
|
|
nodeaGral = XMLDoc.SelectSingleNode(String.Format("//{0}:Comprobante", XMLDoc.DocumentElement.Prefix), namespaces)
|
|
nodeTFD = nodeComp.SelectSingleNode(String.Format("//{0}:TimbreFiscalDigital", "tfd"), namespaces)
|
|
nodeComp = XMLDoc.SelectSingleNode(String.Format("//{0}:Complemento", XMLDoc.DocumentElement.Prefix), namespaces)
|
|
nodePagos = nodeComp.SelectSingleNode(String.Format("//{0}:Pagos/{0}:Pago", Prefijo), namespaces)
|
|
nodePagos2 = nodeComp.SelectSingleNode(String.Format("//{0}:Pagos", Prefijo), namespaces)
|
|
SeriePago = ValorXML(nodeaGral, "Serie")
|
|
FolioPago = ValorXML(nodeaGral, "Folio")
|
|
UUIDPago = ValorXML(nodeTFD, "UUID")
|
|
LblUUID.Text = UUIDPago
|
|
|
|
Dim nodePagosN As XmlNodeList
|
|
nodePagosN = nodeComp.SelectNodes(String.Format("//{0}:Pagos", Prefijo), namespaces)
|
|
|
|
For Each NodosPagos As XmlNode In nodePagosN
|
|
For Each innernode As XmlNode In NodosPagos
|
|
|
|
FechaPago = ValorXML(innernode, "FechaPago").ToDate
|
|
PagosCantidad = PagosCantidad + 1
|
|
|
|
For Each node As XmlNode In innernode
|
|
|
|
Dim Nrow As DataRow = DTDocumentosRelacionados.NewRow
|
|
|
|
Nrow("Serie") = ValorXML(node, "Serie")
|
|
Nrow("Folio") = ValorXML(node, "Folio").ToEntero
|
|
Nrow("SerieFolio") = ValorXML(node, "Serie") & "-" & ValorXML(node, "Folio").ToEntero
|
|
Nrow("IdDocumento") = ValorXML(node, "IdDocumento")
|
|
Nrow("MonedaDR") = ValorXML(node, "MonedaDR")
|
|
Nrow("MetodoDePagoDR") = ValorXML(node, "MetodoDePagoDR")
|
|
|
|
Monto = Monto + ValorXML(node, "ImpPagado").ToDecimal
|
|
|
|
Nrow("ImpPagado") = ValorXML(node, "ImpPagado").ToDecimal
|
|
Nrow("Fecha") = FechaPago
|
|
|
|
Nrow("Tipo") = "17"
|
|
Nrow("Manual") = False
|
|
|
|
DTDocumentosRelacionados.Rows.Add(Nrow)
|
|
StrUUID.AppendFormat("'{0}',", ValorXML(node, "IdDocumento").Replace("'", ""))
|
|
|
|
XMLNodosPagosModalCount = XMLNodosPagosModalCount + 1
|
|
|
|
Next
|
|
Next
|
|
Next
|
|
|
|
Dim UUIDDuplicadosEnu = From row In DTDocumentosRelacionados.AsEnumerable()
|
|
Let IdDocumento = row.Field(Of String)("IdDocumento")
|
|
Group row By IdDocumento Into IdDocumentos = Group
|
|
Where IdDocumentos.Count() > 1
|
|
Select IdDocumentos
|
|
|
|
For Each UUIDDuplicadosRows In UUIDDuplicadosEnu
|
|
For Each row In UUIDDuplicadosRows
|
|
If Not ListaUUIDDuplicados.Contains(row.Field(Of String)("IdDocumento")) Then
|
|
UUIDDuplicados = $"{UUIDDuplicados} {If(ListaUUIDDuplicados.Count > 0, "<br>", "") } {row.Field(Of String)("IdDocumento")}"
|
|
ListaUUIDDuplicados.Add(row.Field(Of String)("IdDocumento"))
|
|
End If
|
|
Next
|
|
Next
|
|
|
|
MontoPago = Monto
|
|
|
|
Dim NodosPagosString As String = Regex.Replace(nodePagos2.InnerXml, $"{Prefijo}:", "", RegexOptions.IgnoreCase)
|
|
|
|
Dim ObjCompraFolios As New ClsCompras
|
|
If ObjCompraFolios.GetCompararComplementoPago(gvRow.DataKey("CveProveedor").ToEntero, Monto, NodosPagosString, UsuarioActual.CveEmpresa, OP:=If(CveComplementoPagoCompra > 0, 2, 1), CveFactura:=CveFacturaComplemento) Then
|
|
'
|
|
'.GetCompararComplementoPago(gvRow.DataKey("CveProveedor").ToEntero, Monto, nodePagos2.InnerXml.Replace("pago10:", ""), UsuarioActual.CveEmpresa) Then
|
|
If ObjCompraFolios.DtResultados.Rows.Count > 0 Then
|
|
For Each drow As DataRow In ObjCompraFolios.DtResultados.Rows
|
|
|
|
For Each dRow2 As DataRow In DTDocumentosRelacionados.Rows
|
|
|
|
If dRow2("IdDocumento").ToString.ToUpper = drow("IdDocumento").ToString.ToUpper Then
|
|
|
|
dRow2("CveCompra") = drow("CveCompra").ToString.ToEntero
|
|
dRow2("CveFactura") = drow("CveFactura").ToString.ToEntero
|
|
dRow2("CveMetodoPago") = drow("CveMetodoPago").ToString.ToEntero
|
|
dRow2("SerieFolioCompra") = drow("SerieFolioCompra").ToString
|
|
Try
|
|
|
|
If drow("CveIE").ToString.ToEntero > 0 Then
|
|
dRow2("CveIE") = drow("CveIE").ToString.ToEntero
|
|
dRow2("ImportePago") = drow("Importe").ToString.ToDecimal
|
|
|
|
dRow2("FolioPago") = drow("FolioIE")
|
|
dRow2("FechaPago") = drow("FechaDocumento")
|
|
dRow2("CvePrePolizaDetalle") = drow("CvePrePolizaDetalle").ToString
|
|
|
|
End If
|
|
|
|
Catch ex As Exception
|
|
dRow2("CvePrePolizaDetalle") = 0
|
|
End Try
|
|
End If
|
|
Next
|
|
Next
|
|
End If
|
|
End If
|
|
|
|
|
|
ObjCompraFolios.Dispose()
|
|
DTDocumentosRelacionados = DTDocumentosRelacionados.FiltraParametros(" LEN(IdDocumento) > 0 ")
|
|
GVPDocumentosRelacionadosPagos.DataSource = DTDocumentosRelacionados
|
|
GVPDocumentosRelacionadosPagos.DataBind()
|
|
|
|
DTGVPagosVinculacion = DTDocumentosRelacionados
|
|
|
|
BtnVincularPago.Visible = False
|
|
If DTDocumentosRelacionados.Rows.Count > 0 Then
|
|
SerieFolioIE = DTDocumentosRelacionados.Rows(0)("SerieFolio").ToString
|
|
'DivVincularPagoManualmente.Visible = False
|
|
BtnVincularPago.Visible = True
|
|
TieneRegistros = True
|
|
Else
|
|
'DivVincularPagoManualmente.Visible = True
|
|
BtnVincularPago.Visible = False
|
|
End If
|
|
|
|
ComprasEnComplemento = DTGVPagosVinculacion.COUNT("CveCompra", " CveCompra > 0")
|
|
|
|
|
|
|
|
If DTDocumentosRelacionados.MAX("CveCompra").ToString.ToEntero > 0 Then
|
|
TieneCompras = True
|
|
Else
|
|
TieneCompras = False
|
|
End If
|
|
|
|
|
|
|
|
For Each dRow2 As DataRow In DTDocumentosRelacionados.Rows
|
|
If dRow2("CveMetodoPago").ToString.ToEntero > 0 Then
|
|
If dRow2("CveMetodoPago").ToString.ToEntero = 1 Then
|
|
MSGComplemento = MSGComplemento & $" Compra {dRow2("SerieFolioCompra").ToString } bloqueado Tipo ""PUE"". "
|
|
|
|
ListaComprasPUEInterna.Add(dRow2("CveCompra").ToString.ToEntero)
|
|
|
|
ComplementoConPUE = $"{SeriePago}-{FolioPago}"
|
|
|
|
End If
|
|
End If
|
|
Next
|
|
|
|
|
|
DT_ComprasSinIE.Columns.Add("CveCompra", GetType(Integer))
|
|
DT_ComprasSinIE.Columns.Add("CveFactura", GetType(Integer))
|
|
DT_ComprasSinIE.Columns.Add("SerieFolioPago")
|
|
DT_ComprasSinIE.Columns.Add("SerieFolioCompra")
|
|
|
|
For Each dRow As DataRow In DTDocumentosRelacionados.Rows
|
|
|
|
Dim nRow As DataRow = DT_ComprasSinIE.NewRow
|
|
nRow("CveCompra") = dRow("CveCompra").ToString.ToEntero
|
|
' nRow("CveFactura") = dRow("CveFactura").ToString.ToEntero
|
|
nRow("SerieFolioPago") = $"{SeriePago}-{FolioPago}"
|
|
nRow("SerieFolioCompra") = dRow("SerieFolioCompra").ToString
|
|
|
|
DT_ComprasSinIE.Rows.Add(nRow)
|
|
|
|
Next
|
|
|
|
|
|
|
|
Else
|
|
Alert("Ocurrió un error al cargar los archivos de complementos pago", TipoMensaje.MsgError)
|
|
End If
|
|
|
|
CveFacturaPago = gvRow.DataKey("CveFactura").ToEntero
|
|
CveProveedor = gvRow.DataKey("CveProveedor").ToEntero
|
|
Dim ObjCompras As New ClsCompras
|
|
|
|
|
|
|
|
|
|
'If ObjCompras.GetCompararComplementoPago(gvRow.DataKey("CveProveedor").ToEntero, Monto, nodePagos2.InnerXml.Replace("pago10:", "").Replace("pagos10:", ""), UsuarioActual.CveEmpresa) Then
|
|
' GvVincularPago.DataSource = ObjCompras.DtResultados
|
|
|
|
' If ObjCompras.DtResultados.Rows.Count > 0 Then
|
|
' SerieFolioIE = ObjCompras.DtResultados.Rows(0)("SerieFolio").ToString
|
|
' DivVincularPagoManualmente.Visible = False
|
|
' BtnVincularPago.Visible = True
|
|
' TieneRegistros = True
|
|
' Else
|
|
' DivVincularPagoManualmente.Visible = True
|
|
' BtnVincularPago.Visible = False
|
|
' End If
|
|
' 'ImportePago = ObjCompras.DtResultados.SUMD("Monto")
|
|
'Else
|
|
' DivVincularPagoManualmente.Visible = False
|
|
' BtnVincularPago.Visible = False
|
|
'End If
|
|
|
|
For Each GvRowF As GridViewRow In GVPDocumentosRelacionadosPagos.Rows
|
|
|
|
Dim FechaDocumento As Date = GvRowF.DataKey("FechaPago").ToString.ToDate
|
|
Dim FechaDoRecibo As Date = GvRowF.DataKey("Fecha").ToString.ToDate
|
|
Dim CveIEDocumento As Integer = GvRowF.DataKey("CveIE").ToEntero
|
|
|
|
If CveIEDocumento > 0 And FechaDocumento > New Date(1, 1, 1) Then
|
|
Dim FT1 As Date = FechaDocumento
|
|
|
|
If FechaDocumento <> New Date(1, 1, 1) Then
|
|
FT1 = FechaDocumento.AddDays(-6)
|
|
End If
|
|
|
|
Dim FT2 As Date = FechaDocumento.AddDays(7)
|
|
|
|
If Not (FechaDoRecibo >= FT1 And FechaDoRecibo < FT2) Then
|
|
|
|
If TieneRegistros AndAlso UsuarioActual.TienePermisoProceso(286) Then
|
|
'DivVincularPagoManualmente.Visible = True
|
|
End If
|
|
|
|
MSGComplemento = MSGComplemento & " Existen mas de 3 días de diferencia entre la fecha del documento y la fecha de complemento. "
|
|
|
|
Exit For
|
|
End If
|
|
End If
|
|
Next
|
|
|
|
|
|
|
|
|
|
If MSGComplemento.Trim.Length > 0 Then
|
|
' BtnVincularPago.Visible = False
|
|
ViculacionConPUE = True
|
|
End If
|
|
|
|
|
|
'saco la información de lo vinculado en el ie
|
|
'ImporteIES = ObjCompras.DtResultados.FiltraParametros("CveIE > 0").SUM("Importe")
|
|
ImporteIES = DTDocumentosRelacionados.FiltraParametros("CveIE > 0").SUM("ImportePago")
|
|
|
|
|
|
DiferenciaImportes = Monto - ImporteIES
|
|
ObjCompras.Dispose()
|
|
|
|
|
|
If TieneCompras Then
|
|
If ImporteIES > 0 Then
|
|
If Math.Abs(DiferenciaImportes) > 5 Then
|
|
TextoDiferenciaImporte = $"<b> - IE ${ImporteIES.FormatoNumero}</b> <div style='color:red'><strong>Diferencia { DiferenciaImportes.FormatoNumero() }</strong></div>"
|
|
BtnVincularPago.Visible = False
|
|
MSGComplemento = MSGComplemento & $" Existe una diferencia mayor a $5.00 ({Math.Abs(DiferenciaImportes).ToString("###,###,###.00")})"
|
|
|
|
If TieneRegistros AndAlso UsuarioActual.TienePermisoProceso(286) Then
|
|
'DivVincularPagoManualmente.Visible = True
|
|
End If
|
|
End If
|
|
Else
|
|
TextoDiferenciaImporte = $"No se encontraron pagos "
|
|
BtnVincularPago.Visible = False
|
|
MSGComplemento = MSGComplemento & $" No se encontraron pagos "
|
|
If TieneRegistros AndAlso UsuarioActual.TienePermisoProceso(286) Then
|
|
' DivVincularPagoManualmente.Visible = True
|
|
End If
|
|
End If
|
|
Else
|
|
BtnVincularPago.Visible = False
|
|
MSGComplemento = MSGComplemento & $"No se encontraron compras relacionadas"
|
|
'DivVincularPagoManualmente.Visible = False
|
|
End If
|
|
|
|
|
|
|
|
|
|
|
|
|
|
LblSerieFolioPago.Text = $"{SeriePago}-{FolioPago}"
|
|
LblImportePago.Text = Monto.ToString("###,###,###.00") 'ImportePago.FormatoNumero
|
|
LblPagosCantidad.Text = PagosCantidad.ToString
|
|
LblImporteIE.Text = ImporteIES.FormatoNumero
|
|
LblDiferencia.Text = If(DiferenciaImportes <> 0 And ImporteIES > 0, DiferenciaImportes.FormatoNumero, "")
|
|
|
|
|
|
If MSGComplemento.Trim.Length > 0 And CveComplementoPagoCompra <= 0 Or ListaUUIDDuplicados.Count > 0 And CveComplementoPagoCompra <= 0 Then
|
|
|
|
If ListaUUIDDuplicados.Count > 0 Then
|
|
|
|
LblMensajeComlementoError.Text = $"Las siguientes UUID se encuentran duplicadas:<br>{UUIDDuplicados}<br>{MSGComplemento}"
|
|
'<hr style='border: 0; height: 1px; background-image: linear-gradient(to right, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.75), rgba(0, 0, 0, 0));' />
|
|
DVMensajecomplementoError.Visible = True
|
|
|
|
Else
|
|
LblMensajeComlementoError.Text = MSGComplemento
|
|
DVMensajecomplementoError.Visible = True
|
|
End If
|
|
|
|
|
|
|
|
Else
|
|
LblMensajeComlementoError.Text = ""
|
|
DVMensajecomplementoError.Visible = False
|
|
' DivVincularPagoManualmente.Visible = False
|
|
End If
|
|
|
|
|
|
GvVincularPago.DataBind()
|
|
|
|
|
|
|
|
ListaComprasPUE = ListaComprasPUEInterna
|
|
|
|
|
|
'If DivVincularPagoManualmente.Visible Then
|
|
|
|
' For Each GvRowValidaCompra As GridViewRow In GVPDocumentosRelacionadosPagos.Rows
|
|
' If GvRowValidaCompra.DataKey("CveCompra").ToEntero > 0 Then
|
|
' DivVincularPagoManualmente.Visible = True
|
|
' Exit For
|
|
' Else
|
|
' DivVincularPagoManualmente.Visible = False
|
|
' End If
|
|
' Next
|
|
|
|
'End If
|
|
|
|
BtnVincularPago.Attributes.Add("data-toggle", "")
|
|
BtnVincularPago.Attributes.Add("data-popout", "")
|
|
BtnVincularPago.Attributes.Add("data-original-title", "")
|
|
BtnVincularPago.Attributes.Add("data-btn-ok-label", "")
|
|
|
|
If UsuarioActual.TienePermisoProceso(332) And (BtnVincularPago.Visible = False Or BtnVincularPago.Enabled = False) Then
|
|
|
|
Dim FaltanCompras As Boolean = False
|
|
For Each GvRowVal As GridViewRow In GVPDocumentosRelacionadosPagos.Rows
|
|
If GvRowVal.DataKey("CveCompra").ToEntero > 0 Then
|
|
FaltanCompras = True
|
|
Exit For
|
|
End If
|
|
Next
|
|
|
|
If FaltanCompras Then
|
|
|
|
For Each GvRowVal As GridViewRow In GVPDocumentosRelacionadosPagos.Rows
|
|
If GvRowVal.DataKey("CveIE").ToEntero > 0 Then
|
|
|
|
BtnVincularPago.Enabled = True
|
|
BtnVincularPago.Visible = True
|
|
|
|
BtnVincularPago.Attributes.Add("data-toggle", "confirmation")
|
|
BtnVincularPago.Attributes.Add("data-popout", "true")
|
|
BtnVincularPago.Attributes.Add("data-original-title", "Se realizará la vinculación sin tener compras previamente registradas")
|
|
BtnVincularPago.Attributes.Add("data-btn-ok-label", "Si")
|
|
|
|
SeVinculoConComprasFaltantes = True
|
|
Exit For
|
|
End If
|
|
Next
|
|
|
|
End If
|
|
End If
|
|
|
|
|
|
|
|
If CveComplementoPagoCompra > 0 Then
|
|
DVMensajecomplementoVinculado.Visible = True
|
|
BtnVincularPago.Visible = False
|
|
Else
|
|
DVMensajecomplementoVinculado.Visible = False
|
|
End If
|
|
|
|
|
|
UpVincularPago.Update()
|
|
|
|
|
|
RegistraScript("$('#ModalVincularPago').modal('show')", "VincularPagoModalShow")
|
|
End Sub
|
|
|
|
Private Sub BtnVincularPago_Click(sender As Object, e As EventArgs) Handles BtnVincularPago.Click
|
|
|
|
|
|
|
|
'VERIFICA QUE HALLA UN PAGO
|
|
'Dim Contador = 0
|
|
'For Each Gv As GridViewRow In GvVincularPago.Rows
|
|
' If Gv.FCCheckBox("ChkVincularPago").Checked Then
|
|
' Contador = 1
|
|
' Exit For
|
|
' End If
|
|
'Next
|
|
'If Contador = 0 Then
|
|
' Alert("Tiene que seleccionar algun pago. Por favor verifique y vuelta a intentar.", TipoMensaje.MsgAdvertencia)
|
|
' Exit Sub
|
|
'End If
|
|
|
|
Dim TieneError As Boolean = False
|
|
Dim ObjCompra As New ClsCompras
|
|
ObjCompra.IniciaTransacSQL()
|
|
|
|
For Each Gv As GridViewRow In GVPDocumentosRelacionadosPagos.Rows
|
|
|
|
If Gv.DataKey("CveCompra").ToEntero > 0 And Gv.DataKey("CveIE").ToEntero > 0 Then
|
|
|
|
If Not ObjCompra.AddComplementoPago(Gv.DataKey("CveIE").ToEntero, Gv.DataKey("CveCompra").ToEntero, Gv.DataKey("ImpPagado").ToDecimal, Gv.DataKey("CvePrePolizaDetalle").ToEntero, CveFacturaPago) > 0 Then
|
|
TieneError = True
|
|
Exit For
|
|
End If
|
|
|
|
End If
|
|
|
|
' If HdnCveIE.Value.ToEntero > 0 Then
|
|
' If Gv.DataKey("CveCompra").ToEntero > 0 And Gv.FCLabel("LblCveIE").Text.ToEntero > 0 Then
|
|
|
|
' If Not ObjCompra.AddComplementoPago(Gv.FCLabel("LblCveIE").Text.ToEntero, Gv.DataKey("CveCompra").ToEntero, Gv.DataKey("ImpPagado").ToDecimal, Gv.FCLabel("LblCvePrePolizaDetalle").Text.ToEntero, CveFacturaPago) > 0 Then
|
|
' TieneError = True
|
|
' Exit For
|
|
' End If
|
|
|
|
' End If
|
|
'Else
|
|
' If Gv.DataKey("CveCompra").ToEntero > 0 Then
|
|
|
|
' If Not ObjCompra.AddComplementoPago(Gv.DataKey("CveIE").ToEntero, Gv.DataKey("CveCompra").ToEntero, Gv.DataKey("ImpPagado").ToDecimal, Gv.DataKey("CvePrePolizaDetalle").ToEntero, CveFacturaPago) > 0 Then
|
|
' TieneError = True
|
|
' Exit For
|
|
' End If
|
|
|
|
' End If
|
|
'End If
|
|
Next
|
|
|
|
|
|
|
|
If Not TieneError AndAlso Not ObjCompra.AddVincularPago(CveFacturaPago) Then
|
|
TieneError = True
|
|
End If
|
|
|
|
If Not TieneError Then
|
|
|
|
Dim objEventos As New ClsOIEventos(ObjCompra.IniciaTransacSQL)
|
|
|
|
If ViculacionConPUE Then
|
|
For Each CveCompraVinculada As Integer In ListaComprasPUE
|
|
objEventos.AddEventoBitacora($"Complemento { ComplementoConPUE } vinculado manualmente (Compra PUE) ", "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCompra:=CveCompraVinculada)
|
|
Next
|
|
End If
|
|
|
|
For Each Gv As GridViewRow In GVPDocumentosRelacionadosPagos.Rows
|
|
If Boolean.Parse(Gv.DataKey("Manual").ToString) Then
|
|
objEventos.AddEventoBitacora($"Complemento { LblSerieFolioPago.Text} vinculado manualmente a compra {Gv.DataKey("SerieFolio").ToString} y Pago { Gv.DataKey("FolioPago").ToString }", "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCompra:=Gv.DataKey("CveCompra").ToString.ToEntero)
|
|
End If
|
|
Next
|
|
|
|
'If HdnCveIE.Value.ToEntero > 0 Then
|
|
|
|
' For Each dRow As DataRow In DT_ComprasSinIE.Rows
|
|
' objEventos.AddEventoBitacora($"Complemento { dRow("SerieFolioPago").ToString } vinculado manualmente a compra {dRow("SerieFolioCompra").ToString}", "", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCompra:=dRow("CveCompra").ToString.ToEntero)
|
|
' Next
|
|
|
|
'End If
|
|
|
|
|
|
|
|
ObjCompra.Commit()
|
|
|
|
HdnCveIE.Value = ""
|
|
|
|
Alert("El pago fue vinculado correctamente", TipoMensaje.MsgInformacion)
|
|
RegistraScript("$('#ModalVincularPago').modal('hide')", "VincularPagoModalHide")
|
|
CargaDatos(NowADS())
|
|
Else
|
|
ObjCompra.RollBack()
|
|
Alert("Ocurrió un error al vincular el pago. Por favor verifique y vuelva a intentar", TipoMensaje.MsgError)
|
|
End If
|
|
ObjCompra.Dispose()
|
|
|
|
|
|
End Sub
|
|
|
|
Protected Sub ChkVincularPago_CheckedChanged(sender As Object, e As EventArgs)
|
|
|
|
For Each Gvr As GridViewRow In GvVincularPago.Rows
|
|
Gvr.FCCheckBox("ChkVincularPago").Checked = False
|
|
Next
|
|
|
|
CType(sender, CheckBox).Checked = True
|
|
End Sub
|
|
|
|
Protected Sub BtnVincularManualmente_Click(sender As Object, e As EventArgs)
|
|
|
|
|
|
If HdnCveIE.Value <> "-1" AndAlso IsNumeric(HdnCveIE.Value) AndAlso HdnCveIE.Value.ToEntero > 0 Then
|
|
'VincularComplementoManualGV(HdnCveIE.Value.ToEntero)
|
|
|
|
For Each dRow As DataRow In DTGVPagosVinculacion.Rows
|
|
|
|
If HdnIdDocumento.Value = dRow("IdDocumento").ToString Then 'And dRow("CveIE").ToString.ToEntero <= 0
|
|
|
|
dRow("CveIE") = HdnCveIE.Value.ToEntero
|
|
|
|
Dim ObjIE As New ClsBancos()
|
|
|
|
Dim ObjCompras As New ClsCompras
|
|
|
|
If ObjCompras.GetCompararComplementoPago(CveProveedor, -1, "", UsuarioActual.CveEmpresa, HdnCveIE.Value.ToEntero) Then
|
|
|
|
|
|
Dim CompraEncontrada As Boolean = False
|
|
|
|
|
|
For Each drowComparar As DataRow In ObjCompras.DtResultados.Rows
|
|
|
|
If drowComparar("CveCompraPrePoliza").ToString.ToEntero > 0 AndAlso (dRow("CveCompra").ToString.ToEntero = drowComparar("CveCompraPrePoliza").ToString.ToEntero) Then
|
|
dRow("FolioPago") = drowComparar("FolioIE")
|
|
dRow("ImportePago") = dRow("ImpPagado")
|
|
dRow("FechaPago") = drowComparar("Fecha").ToString.ToDate
|
|
dRow("CvePrePolizaDetalle") = drowComparar("CvePrePolizaDetalle").ToString.ToEntero
|
|
dRow("Tipo") = "E"
|
|
dRow("Manual") = True
|
|
CompraEncontrada = True
|
|
Exit For
|
|
End If
|
|
|
|
Next
|
|
|
|
|
|
If Not CompraEncontrada Then
|
|
|
|
Try
|
|
dRow("FolioPago") = ObjCompras.DtResultados(0)("FolioIE")
|
|
dRow("ImportePago") = dRow("ImpPagado")
|
|
dRow("FechaPago") = ObjCompras.DtResultados(0)("Fecha").ToString.ToDate
|
|
dRow("CvePrePolizaDetalle") = ObjCompras.DtResultados(0)("CvePrePolizaDetalle").ToString.ToEntero
|
|
dRow("Tipo") = "E"
|
|
dRow("Manual") = True
|
|
Catch ex As Exception
|
|
|
|
End Try
|
|
|
|
End If
|
|
|
|
|
|
|
|
End If
|
|
ObjCompras.Dispose()
|
|
|
|
ObjIE.Dispose()
|
|
|
|
End If
|
|
Next
|
|
End If
|
|
|
|
DTGVPagosVinculacion.AcceptChanges()
|
|
|
|
HdnIdDocumento.Value = "-1"
|
|
|
|
GVPDocumentosRelacionadosPagos.DataSource = DTGVPagosVinculacion
|
|
GVPDocumentosRelacionadosPagos.DataBind()
|
|
|
|
UpVincularPago.Update()
|
|
CurretUUIDPagoVincular = ""
|
|
|
|
ValidaTablaDeVinculacion()
|
|
|
|
|
|
End Sub
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Private Function ValidaTablaDeVinculacion() As Boolean
|
|
|
|
Dim ResPuesta As Boolean = False
|
|
Dim Vinculados As Integer = 0
|
|
Dim TodoVinculado As Boolean = False
|
|
|
|
Dim Diferencia As Boolean = If(Math.Abs(DTGVPagosVinculacion.SUM("ImpPagado") - DTGVPagosVinculacion.SUM("ImportePago")) > 0.1D, True, False)
|
|
Dim VinculacionManual As Boolean = If(DTGVPagosVinculacion.FiltraParametros("Manual = 1").Rows.Count > 0, True, False)
|
|
|
|
Dim PermisoVinculacionDiferencia As Boolean = UsuarioActual.TienePermisoProceso(286)
|
|
Dim PermisoVinculacionManual As Boolean = UsuarioActual.TienePermisoProceso(286)
|
|
|
|
Dim MontoSuma As Decimal = DTGVPagosVinculacion.SUM("ImportePago").ToString.ToDecimal
|
|
|
|
For Each dRow As DataRow In DTGVPagosVinculacion.Rows
|
|
If dRow("CveIE").ToString.ToEntero > 0 Then
|
|
Vinculados = Vinculados + 1
|
|
End If
|
|
Next
|
|
|
|
|
|
'If XMLNodosPagosModalCount = Vinculados Then
|
|
If ComprasEnComplemento = Vinculados And ComprasEnComplemento > 0 Then '
|
|
TodoVinculado = True
|
|
End If
|
|
|
|
|
|
If TodoVinculado Then
|
|
|
|
If Diferencia Then
|
|
If PermisoVinculacionDiferencia Then
|
|
If VinculacionManual Then
|
|
If PermisoVinculacionManual Then
|
|
ResPuesta = True
|
|
Else
|
|
ResPuesta = False
|
|
End If
|
|
Else
|
|
ResPuesta = True
|
|
End If
|
|
Else
|
|
ResPuesta = False
|
|
End If
|
|
Else
|
|
|
|
If VinculacionManual Then
|
|
If PermisoVinculacionManual Then
|
|
ResPuesta = True
|
|
Else
|
|
ResPuesta = False
|
|
End If
|
|
Else
|
|
ResPuesta = True
|
|
End If
|
|
|
|
End If
|
|
|
|
Else
|
|
ResPuesta = False
|
|
End If
|
|
|
|
|
|
If Not MontoSuma = MontoPago And ResPuesta Then
|
|
|
|
If Not PermisoVinculacionDiferencia Then
|
|
ResPuesta = False
|
|
End If
|
|
|
|
End If
|
|
|
|
|
|
If ResPuesta Then
|
|
BtnVincularPago.Visible = True
|
|
Else
|
|
BtnVincularPago.Visible = False
|
|
End If
|
|
|
|
UpVincularPago.Update()
|
|
|
|
Return ResPuesta
|
|
|
|
End Function
|
|
|
|
|
|
Private Sub GVPDocumentosRelacionadosPagos_RowCreated(sender As Object, e As GridViewRowEventArgs) Handles GVPDocumentosRelacionadosPagos.RowCreated
|
|
|
|
If e.Row.RowType = DataControlRowType.Header Then
|
|
Dim HeaderGrid As GridView = DirectCast(sender, GridView)
|
|
Dim HeaderGridRow As New GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert)
|
|
Dim HeaderCell As New TableCell
|
|
|
|
HeaderCell.Text = "Documentos Relacionados"
|
|
HeaderCell.ColumnSpan = 9
|
|
HeaderCell.Attributes.Add("style", "border-top: 1px solid #ddd; vertical-align: top; background-color: #DDD; color: #333333;font-family: 'Open Sans', sans-serif;font-size: 12px; text-align:center!important; font-weight: bold;")
|
|
HeaderGridRow.Cells.Add(HeaderCell)
|
|
GVPDocumentosRelacionadosPagos.Controls(0).Controls.AddAt(0, HeaderGridRow)
|
|
|
|
End If
|
|
|
|
End Sub
|
|
|
|
Private Sub GVPDocumentosRelacionadosPagos_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GVPDocumentosRelacionadosPagos.RowDataBound
|
|
|
|
If e.Row.RowType = DataControlRowType.DataRow Then
|
|
|
|
If e.Row.DataKey("CveFactura").ToEntero > 0 Then
|
|
|
|
If e.Row.DataKey("CveCompra").ToEntero > 0 Then
|
|
e.Row.Cells(4).Text = "<i class='fa success fa-check-circle' aria-hidden='true'></i>"
|
|
e.Row.ToolTip = "Compra registrada"
|
|
e.Row.Cells(4).ForeColor = Drawing.Color.Green
|
|
|
|
|
|
If e.Row.DataKey("CveIE").ToEntero <= 0 Or Boolean.Parse(e.Row.DataKey("Manual")) = True Then
|
|
|
|
e.Row.Cells(6).Controls.Clear()
|
|
Dim LiteralVincular As New Literal
|
|
If UsuarioActual.TienePermisoProceso(286) Then ' permiso vinculación manual
|
|
LiteralVincular.Text = $"<a title='Vinculación manual' onclick="" { $"$('#HdnIdDocumento').val('{ e.Row.DataKey("IdDocumento") }');AbrirVentana('/Bancos/PopUpBuscarIE.aspx?OPCION=Complementos',800,600,'N');" }"" ><i class='fa fa-external-link' aria-hidden='true'></i></a>"
|
|
Else
|
|
LiteralVincular.Text = "-"
|
|
End If
|
|
e.Row.Cells(6).Controls.Add(LiteralVincular)
|
|
End If
|
|
|
|
Else
|
|
e.Row.Cells(4).Text = "<i class='fa fa-check-circle' aria-hidden='true'></i>"
|
|
e.Row.ToolTip = "Factura recibida sin registrar"
|
|
End If
|
|
|
|
Else
|
|
e.Row.Cells(4).Text = "<i class='fa red fa-ban' aria-hidden='true'></i>"
|
|
e.Row.ToolTip = "No se encontro el Folio Fiscal en el sistema"
|
|
e.Row.Cells(4).ForeColor = Drawing.Color.Red
|
|
End If
|
|
End If
|
|
|
|
End Sub
|
|
|
|
#End Region
|
|
|
|
Public Sub ImprimirPDFXML(NombreArchivo As String, rutaxml As String)
|
|
Dim objxml As ADSistemaLibrary.SatXml.XmlSatCFDI = ADSistemaLibrary.SatXml.XmlSatCFDI.readXML(rutaxml)
|
|
|
|
Dim rutaReporte As String = String.Format("{0}{1}", ModExtensiones.DirectorioBaseEmpresas, "\Empresas\Grales\Formatos\CFDIV3.rdlc")
|
|
Dim cQr As Byte() = ClsPaginas.GeneraQRSAT(objxml.emisor.Rfc, objxml.receptor.Rfc, objxml.comprobante.Total, objxml.complemento.UUID)
|
|
Dim parametros As List(Of ReportParameter) = New List(Of ReportParameter)()
|
|
parametros.Add(New ReportParameter("comprobante_Certificado", objxml.comprobante.Certificado))
|
|
parametros.Add(New ReportParameter("comprobante_CondicionesDePago", objxml.comprobante.CondicionesDePago))
|
|
parametros.Add(New ReportParameter("comprobante_Confirmacion", objxml.comprobante.Confirmacion))
|
|
parametros.Add(New ReportParameter("comprobante_Fecha", objxml.comprobante.Fecha))
|
|
parametros.Add(New ReportParameter("comprobante_Serie", objxml.comprobante.Serie))
|
|
parametros.Add(New ReportParameter("comprobante_Folio", objxml.comprobante.Folio))
|
|
parametros.Add(New ReportParameter("comprobante_Descuento", objxml.comprobante.Descuento.ToString("N2")))
|
|
parametros.Add(New ReportParameter("comprobante_SubTotal", objxml.comprobante.SubTotal.ToString("N2")))
|
|
parametros.Add(New ReportParameter("comprobante_Total", objxml.comprobante.Total.ToString("N2")))
|
|
parametros.Add(New ReportParameter("comprobante_Version", objxml.comprobante.Version))
|
|
parametros.Add(New ReportParameter("comprobante_TipoDeComprobante", objxml.comprobante.TipoDeComprobanteTexto))
|
|
parametros.Add(New ReportParameter("comprobante_FormaPago", objxml.comprobante.FormaPagoTexto))
|
|
parametros.Add(New ReportParameter("comprobante_LugarExpedicion", objxml.comprobante.LugarExpedicion))
|
|
parametros.Add(New ReportParameter("comprobante_NoCertificado", objxml.comprobante.NoCertificado))
|
|
parametros.Add(New ReportParameter("comprobante_Sello", objxml.comprobante.Sello))
|
|
parametros.Add(New ReportParameter("comprobante_Moneda", objxml.comprobante.Moneda))
|
|
parametros.Add(New ReportParameter("comprobante_TipoCambio", objxml.comprobante.TipoCambio.ToString("N2")))
|
|
parametros.Add(New ReportParameter("comprobante_MetodoPago", objxml.comprobante.MetodoPagoTexto))
|
|
parametros.Add(New ReportParameter("emisor_Rfc", objxml.emisor.Rfc))
|
|
parametros.Add(New ReportParameter("emisor_Nombre", objxml.emisor.Nombre))
|
|
parametros.Add(New ReportParameter("emisor_RegimenFiscal", objxml.emisor.RegimenFiscalTexto))
|
|
parametros.Add(New ReportParameter("receptor_Rfc", objxml.receptor.Rfc))
|
|
parametros.Add(New ReportParameter("receptor_Nombre", objxml.receptor.Nombre))
|
|
parametros.Add(New ReportParameter("receptor_NumRegIdTrib", objxml.receptor.NumRegIdTrib))
|
|
parametros.Add(New ReportParameter("receptor_ResidenciaFiscal", objxml.receptor.ResidenciaFiscal))
|
|
parametros.Add(New ReportParameter("receptor_UsoCFDI", objxml.receptor.UsoCFDITexto))
|
|
parametros.Add(New ReportParameter("complemento_FechaTimbrado", objxml.complemento.FechaTimbrado))
|
|
parametros.Add(New ReportParameter("complemento_NoCertificadoSAT", objxml.complemento.NoCertificadoSAT))
|
|
parametros.Add(New ReportParameter("complemento_RfcProvCertif", objxml.complemento.RfcProvCertif))
|
|
parametros.Add(New ReportParameter("complemento_SelloCFD", objxml.complemento.SelloCFD))
|
|
parametros.Add(New ReportParameter("complemento_SelloSAT", objxml.complemento.SelloSAT))
|
|
parametros.Add(New ReportParameter("complemento_UUID", objxml.complemento.UUID))
|
|
parametros.Add(New ReportParameter("complemento_CadenaOriginal", objxml.complemento.CadenaOriginal))
|
|
|
|
Using MR As ReportViewer = New ReportViewer()
|
|
Dim rdsTotales As ReportDataSource = New ReportDataSource()
|
|
|
|
|
|
Dim ltotales As List(Of utilValores) = New List(Of utilValores)()
|
|
ltotales.Add(New utilValores("Subtotal", objxml.comprobante.SubTotal.ToString("N2")))
|
|
|
|
If objxml.comprobante.Descuento > 0 Then
|
|
ltotales.Add(New utilValores("Descuento", objxml.comprobante.Descuento.ToString("N2")))
|
|
End If
|
|
|
|
For Each item As ADSistemaLibrary.SatXml.CFDIImpuesto In objxml.Impuestos
|
|
|
|
If item.Importe > 0 Then
|
|
Dim TasaOCuota As Decimal = 0
|
|
Decimal.TryParse(item.TasaOCuota, TasaOCuota)
|
|
ltotales.Add(New utilValores($"Impuestos {item.Tipo} {item.ImpuestoTexto} {(If(item.TipoFactor = "Tasa", (TasaOCuota * 100).ToString("N4"), item.TasaOCuota))} {(If(item.TipoFactor = "Tasa", "%", ""))}", item.Importe.ToString("N2")))
|
|
End If
|
|
Next
|
|
|
|
ltotales.Add(New utilValores("Total", objxml.comprobante.Total.ToString("N2")))
|
|
rdsTotales.Name = "dsTotales"
|
|
rdsTotales.Value = ltotales
|
|
MR.LocalReport.DataSources.Add(rdsTotales)
|
|
Dim rds2 As ReportDataSource = New ReportDataSource()
|
|
Dim limagenes As List(Of utilImage) = New List(Of utilImage)()
|
|
limagenes.Add(New utilImage(cQr))
|
|
rds2.Name = "dsImagenes"
|
|
rds2.Value = limagenes
|
|
MR.LocalReport.DataSources.Add(rds2)
|
|
Dim rdsrelacionados As ReportDataSource = New ReportDataSource()
|
|
rdsrelacionados.Name = "dsRelacionados"
|
|
rdsrelacionados.Value = objxml.cFDIRelacionados
|
|
MR.LocalReport.DataSources.Add(rdsrelacionados)
|
|
Dim rds1 As ReportDataSource = New ReportDataSource()
|
|
rds1.Name = "dsConceptos"
|
|
rds1.Value = objxml.GetConceptosforpdf()
|
|
MR.LocalReport.DataSources.Add(rds1)
|
|
MR.LocalReport.ReportPath = rutaReporte
|
|
MR.ProcessingMode = ProcessingMode.Local
|
|
MR.LocalReport.EnableExternalImages = True
|
|
MR.LocalReport.SetParameters(parametros)
|
|
MR.LocalReport.Refresh()
|
|
Dim warnings As Warning() = Nothing
|
|
Dim streamids As String() = Nothing
|
|
Dim mimeType As String = Nothing
|
|
Dim encoding As String = Nothing
|
|
Dim extension As String = Nothing
|
|
Dim bytes As Byte() = Nothing
|
|
bytes = MR.LocalReport.Render("PDF", Nothing, mimeType, encoding, extension, streamids, warnings)
|
|
|
|
Using fs As FileStream = New FileStream(NombreArchivo, FileMode.Create)
|
|
fs.Write(bytes, 0, bytes.Length)
|
|
fs.Close()
|
|
End Using
|
|
End Using
|
|
End Sub
|
|
Protected Sub lnkRegenerarPDF_Click(sender As Object, e As EventArgs)
|
|
Dim gvrow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
|
|
Dim strRFCde As String = gvrow.DataKey("RFCde")
|
|
Dim strXml As String
|
|
Dim strPDF As String
|
|
Dim dirbase As String = String.Format("{0}{1}{2}\", UsuarioActual.Empresa.Ruta, "Compras\", strRFCde)
|
|
If Directory.Exists(dirbase) Then
|
|
strXml = String.Format("{0}{1}", dirbase, gvrow.DataKey("XML"))
|
|
strPDF = String.Format("{0}{1}", dirbase, gvrow.DataKey("PDF"))
|
|
If File.Exists(strXml) Then
|
|
ImprimirPDFXML(strPDF, strXml)
|
|
Alert("el pdf se regenero satisfactoriamente.")
|
|
Else
|
|
Alert($"No se encontro el xml favor de contactar a soporte tecnico{strXml.Replace("\", "/")}")
|
|
End If
|
|
Else
|
|
Alert($"No se encontro el xml favor de contactar a soporte tecnico{dirbase.Replace("\", "/")}")
|
|
End If
|
|
',PDF
|
|
'
|
|
'ImprimirPDFXML("C:\Generar PFX\405504.pdf", "C:\Generar PFX\405504.xml")
|
|
End Sub
|
|
Private Sub removeasincevent()
|
|
|
|
'For Each GvRow As GridViewRow In GvD.Rows
|
|
' Dim lnkDownPdf As LinkButton = GvRow.FCLinkButton("lnkDownPdf")
|
|
' Dim lnkXML As LinkButton = GvRow.FCLinkButton("lnkXML")
|
|
' If lnkDownPdf.Visible Then
|
|
|
|
' ScriptManager.GetCurrent(Me).RegisterPostBackControl(lnkDownPdf)
|
|
' End If
|
|
' If lnkXML.Visible Then
|
|
' ScriptManager.GetCurrent(Me).RegisterPostBackControl(lnkXML)
|
|
' End If
|
|
'Next
|
|
End Sub
|
|
Protected Sub lnkDownPdf_Click(sender As Object, e As EventArgs)
|
|
Dim gvrow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
|
|
Dim strRFCde As String = gvrow.DataKey("RFCde")
|
|
Dim strPDF As String
|
|
Dim dirbase As String = String.Format("{0}{1}{2}\", UsuarioActual.Empresa.Ruta, "Compras\", strRFCde)
|
|
strPDF = String.Format("{0}{1}", dirbase, gvrow.DataKey("PDF"))
|
|
If File.Exists(strPDF) Then
|
|
Dim file As New System.IO.FileInfo(strPDF)
|
|
Dim mimeType As String = "text/plain"
|
|
Try
|
|
mimeType = MimeMapping.GetMimeMapping(strPDF)
|
|
Catch ex As Exception
|
|
End Try
|
|
Response.Clear()
|
|
Response.ClearHeaders()
|
|
Response.ClearContent()
|
|
Response.AddHeader("Content-Disposition", $"attachment; filename= {Uri.EscapeDataString(file.Name)}")
|
|
Response.AddHeader("Content-Length", file.Length.ToString())
|
|
Response.ContentType = mimeType
|
|
Response.Flush()
|
|
Response.TransmitFile(file.FullName)
|
|
Response.End()
|
|
End If
|
|
End Sub
|
|
Protected Sub lnkXML_Click(sender As Object, e As EventArgs)
|
|
Dim gvrow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
|
|
Dim strRFCde As String = gvrow.DataKey("RFCde")
|
|
Dim strXml As String
|
|
Dim dirbase As String = String.Format("{0}{1}{2}\", UsuarioActual.Empresa.Ruta, "Compras\", strRFCde)
|
|
strXml = String.Format("{0}{1}", dirbase, gvrow.DataKey("XML"))
|
|
If File.Exists(strXml) Then
|
|
Dim file As New System.IO.FileInfo(strXml)
|
|
Dim mimeType As String = "text/plain"
|
|
Try
|
|
mimeType = MimeMapping.GetMimeMapping(strXml)
|
|
Catch ex As Exception
|
|
End Try
|
|
Response.Clear()
|
|
Response.ClearHeaders()
|
|
Response.ClearContent()
|
|
Response.AddHeader("Content-Disposition", $"attachment; filename= {Uri.EscapeDataString(file.Name)}")
|
|
Response.AddHeader("Content-Length", file.Length.ToString())
|
|
Response.ContentType = mimeType
|
|
Response.Flush()
|
|
Response.TransmitFile(file.FullName)
|
|
Response.End()
|
|
End If
|
|
End Sub
|
|
Protected Sub LnkRegenerarPdfnew_Click(sender As Object, e As EventArgs)
|
|
Dim gvrow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
|
|
Dim objxml As ADSistemaLibrary.SatXml.XmlSatCFDI = ADSistemaLibrary.SatXml.XmlSatCFDI.readXML(String.Format("{0}{1}\{2}", Destino, gvrow.DataKey("RFCDe"), gvrow.DataKey("XML")))
|
|
|
|
|
|
Dim XmlRutaArchivo As String = File.ReadAllText(String.Format("{0}{1}\{2}", Destino, gvrow.DataKey("RFCDe"), gvrow.DataKey("XML")))
|
|
Dim PDFRutaArchivo As String = String.Format("{0}{1}\{2}", Destino, gvrow.DataKey("RFCDe"), gvrow.DataKey("PDF"))
|
|
Dim RutaRDLC As String = String.Format("{0}{1}", DirectorioBaseEmpresas, "Empresas\Grales\Formatos\ReciboDePagoGOPDF.rdlc")
|
|
Dim Respuesta As Boolean = False
|
|
|
|
Dim Inicio As DateTime = NowADS()
|
|
Dim goPdf As GoPdf.GoPdf = New GoPdf.GoPdf()
|
|
Dim logotipo As Byte() = Nothing
|
|
|
|
Try
|
|
Dim result As Byte() = goPdf.ExportarPdf(XmlRutaArchivo, logotipo, "", RutaRDLC, New GoPdf.Modelos.DatosAdicionales() With {
|
|
.DomicilioReceptor = ""
|
|
})
|
|
Dim Fin As DateTime = NowADS()
|
|
|
|
If result IsNot Nothing Then
|
|
File.WriteAllBytes(PDFRutaArchivo, result)
|
|
Respuesta = True
|
|
Alert($"PDF Generado")
|
|
Else
|
|
Alert($"PDF Error se genero nulo", TipoMensaje.MsgAdvertencia)
|
|
End If
|
|
|
|
CargaDatos(NowADS())
|
|
|
|
Catch ex As Exception
|
|
Alert($"PDF Error {ex.Message} -- > {ex.StackTrace}", TipoMensaje.MsgAdvertencia)
|
|
End Try
|
|
|
|
|
|
|
|
|
|
|
|
'If Not IsNothing(objxml) Then
|
|
' Dim rutaReporte As String = String.Format("{0}{1}", ModExtensiones.DirectorioBaseEmpresas, "\Empresas\Grales\Formatos\CFDIV3.rdlc")
|
|
' If Not IsNothing(objxml.complemento.Pagos) Then
|
|
' rutaReporte = String.Format("{0}{1}", ModExtensiones.DirectorioBaseEmpresas, "\Empresas\Grales\Formatos\CFDIV3Pago.rdlc")
|
|
' End If
|
|
' Dim NombreArchivo As String = String.Format("{0}{1}\{2}", Destino, gvrow.DataKey("RFCDe"), gvrow.DataKey("PDF"))
|
|
|
|
|
|
' Dim QR As ClbNegBICFDv3_2.ClsNegCBBGenerar = New ClbNegBICFDv3_2.ClsNegCBBGenerar()
|
|
' Dim cQr As Byte() = QR.GenerarCBBBytes(objxml.emisor.Rfc, objxml.receptor.Rfc, If(IsNothing(objxml.complemento.Pagos), objxml.comprobante.Total, objxml.complemento.Pagos.Monto), objxml.complemento.UUID)
|
|
' Dim parametros As List(Of ReportParameter) = New List(Of ReportParameter)()
|
|
' parametros.Add(New ReportParameter("comprobante_Certificado", objxml.comprobante.Certificado))
|
|
' parametros.Add(New ReportParameter("comprobante_CondicionesDePago", objxml.comprobante.CondicionesDePago))
|
|
' parametros.Add(New ReportParameter("comprobante_Confirmacion", objxml.comprobante.Confirmacion))
|
|
' parametros.Add(New ReportParameter("comprobante_Fecha", objxml.comprobante.Fecha))
|
|
' parametros.Add(New ReportParameter("comprobante_Serie", objxml.comprobante.Serie))
|
|
' parametros.Add(New ReportParameter("comprobante_Folio", objxml.comprobante.Folio))
|
|
' parametros.Add(New ReportParameter("comprobante_Descuento", objxml.comprobante.Descuento.ToString("N2")))
|
|
' parametros.Add(New ReportParameter("comprobante_SubTotal", objxml.comprobante.SubTotal.ToString("N2")))
|
|
' parametros.Add(New ReportParameter("comprobante_Total", objxml.comprobante.Total.ToString("N2")))
|
|
' parametros.Add(New ReportParameter("comprobante_Version", objxml.comprobante.Version))
|
|
' parametros.Add(New ReportParameter("comprobante_TipoDeComprobante", objxml.comprobante.TipoDeComprobanteTexto))
|
|
' parametros.Add(New ReportParameter("comprobante_FormaPago", objxml.comprobante.FormaPagoTexto))
|
|
' parametros.Add(New ReportParameter("comprobante_LugarExpedicion", objxml.comprobante.LugarExpedicion))
|
|
' parametros.Add(New ReportParameter("comprobante_NoCertificado", objxml.comprobante.NoCertificado))
|
|
' parametros.Add(New ReportParameter("comprobante_Sello", objxml.comprobante.Sello))
|
|
' parametros.Add(New ReportParameter("comprobante_Moneda", objxml.comprobante.Moneda))
|
|
' parametros.Add(New ReportParameter("comprobante_TipoCambio", objxml.comprobante.TipoCambio.ToString("N2")))
|
|
' parametros.Add(New ReportParameter("comprobante_MetodoPago", objxml.comprobante.MetodoPagoTexto))
|
|
' parametros.Add(New ReportParameter("emisor_Rfc", objxml.emisor.Rfc))
|
|
' parametros.Add(New ReportParameter("emisor_Nombre", objxml.emisor.Nombre))
|
|
' parametros.Add(New ReportParameter("emisor_RegimenFiscal", objxml.emisor.RegimenFiscalTexto))
|
|
' parametros.Add(New ReportParameter("receptor_Rfc", objxml.receptor.Rfc))
|
|
' parametros.Add(New ReportParameter("receptor_Nombre", objxml.receptor.Nombre))
|
|
' parametros.Add(New ReportParameter("receptor_NumRegIdTrib", objxml.receptor.NumRegIdTrib))
|
|
' parametros.Add(New ReportParameter("receptor_ResidenciaFiscal", objxml.receptor.ResidenciaFiscal))
|
|
' parametros.Add(New ReportParameter("receptor_UsoCFDI", objxml.receptor.UsoCFDITexto))
|
|
' parametros.Add(New ReportParameter("complemento_FechaTimbrado", objxml.complemento.FechaTimbrado))
|
|
' parametros.Add(New ReportParameter("complemento_NoCertificadoSAT", objxml.complemento.NoCertificadoSAT))
|
|
' parametros.Add(New ReportParameter("complemento_RfcProvCertif", objxml.complemento.RfcProvCertif))
|
|
' parametros.Add(New ReportParameter("complemento_SelloCFD", objxml.complemento.SelloCFD))
|
|
' parametros.Add(New ReportParameter("complemento_SelloSAT", objxml.complemento.SelloSAT))
|
|
' parametros.Add(New ReportParameter("complemento_UUID", objxml.complemento.UUID))
|
|
' parametros.Add(New ReportParameter("complemento_CadenaOriginal", objxml.complemento.CadenaOriginal))
|
|
' If Not IsNothing(objxml.complemento.Pagos) Then
|
|
' parametros.Add(New ReportParameter("CPFechaPago", objxml.complemento.Pagos.FechaPago))
|
|
' parametros.Add(New ReportParameter("CPFormaDePagoP", objxml.complemento.Pagos.FormaDePagoP))
|
|
' parametros.Add(New ReportParameter("CPFormaDePagoPText", objxml.complemento.Pagos.FormaDePagoPText))
|
|
' parametros.Add(New ReportParameter("CPMonedaP", objxml.complemento.Pagos.MonedaP))
|
|
' parametros.Add(New ReportParameter("CPMonto", objxml.complemento.Pagos.Monto.ToString()))
|
|
' parametros.Add(New ReportParameter("CPTipoCambioP", objxml.complemento.Pagos.TipoCambioP.ToString()))
|
|
' parametros.Add(New ReportParameter("CPNumOperacion", objxml.complemento.Pagos.NumOperacion))
|
|
' parametros.Add(New ReportParameter("CPNomBancoOrdExt", objxml.complemento.Pagos.NomBancoOrdExt))
|
|
' parametros.Add(New ReportParameter("CPRfcEmisorCtaOrd", objxml.complemento.Pagos.RfcEmisorCtaOrd))
|
|
' parametros.Add(New ReportParameter("CPCtaOrdenante", objxml.complemento.Pagos.CtaOrdenante))
|
|
' parametros.Add(New ReportParameter("CPRfcEmisorCtaBen", objxml.complemento.Pagos.RfcEmisorCtaBen))
|
|
' parametros.Add(New ReportParameter("CPCtaBeneficiario", objxml.complemento.Pagos.CtaBeneficiario))
|
|
|
|
' End If
|
|
' Using MR As ReportViewer = New ReportViewer()
|
|
' Dim rdsTotales As ReportDataSource = New ReportDataSource()
|
|
' Dim ltotales As List(Of utilValores) = New List(Of utilValores)()
|
|
' ltotales.Add(New utilValores("Subtotal", objxml.comprobante.SubTotal.ToString("N2")))
|
|
|
|
' If objxml.comprobante.Descuento > 0 Then
|
|
' ltotales.Add(New utilValores("Descuento", objxml.comprobante.Descuento.ToString("N2")))
|
|
' End If
|
|
|
|
' For Each item As CFDIImpuesto In objxml.Impuestos
|
|
|
|
' If item.Importe > 0 Then
|
|
' Dim TasaOCuota As Decimal = 0
|
|
' Decimal.TryParse(item.TasaOCuota, TasaOCuota)
|
|
' ltotales.Add(New utilValores($"Impuestos {item.Tipo} {item.ImpuestoTexto} {(If(item.TipoFactor = "Tasa", (TasaOCuota * 100).ToString("N4"), item.TasaOCuota))} {(If(item.TipoFactor = "Tasa", "%", ""))}", item.Importe.ToString("N2")))
|
|
' End If
|
|
' Next
|
|
|
|
' ltotales.Add(New utilValores("Total", objxml.comprobante.Total.ToString("N2")))
|
|
' rdsTotales.Name = "dsTotales"
|
|
' rdsTotales.Value = ltotales
|
|
' MR.LocalReport.DataSources.Add(rdsTotales)
|
|
' Dim rds2 As ReportDataSource = New ReportDataSource()
|
|
' Dim limagenes As List(Of utilImage) = New List(Of utilImage)()
|
|
' limagenes.Add(New utilImage(cQr))
|
|
' rds2.Name = "dsImagenes"
|
|
' rds2.Value = limagenes
|
|
' MR.LocalReport.DataSources.Add(rds2)
|
|
' Dim rdsrelacionados As ReportDataSource = New ReportDataSource()
|
|
' rdsrelacionados.Name = "dsRelacionados"
|
|
' rdsrelacionados.Value = objxml.cFDIRelacionados
|
|
' MR.LocalReport.DataSources.Add(rdsrelacionados)
|
|
' Dim rds1 As ReportDataSource = New ReportDataSource()
|
|
' rds1.Name = "dsConceptos"
|
|
' rds1.Value = objxml.GetConceptosforpdf()
|
|
' MR.LocalReport.DataSources.Add(rds1)
|
|
|
|
' If Not IsNothing(objxml.complemento.Pagos) Then
|
|
|
|
' Dim rdsp As ReportDataSource = New ReportDataSource()
|
|
' rdsp.Name = "dsPagos"
|
|
' rdsp.Value = objxml.complemento.Pagos.doctosRelacionados
|
|
' MR.LocalReport.DataSources.Add(rdsp)
|
|
' End If
|
|
|
|
' MR.LocalReport.ReportPath = rutaReporte
|
|
' MR.ProcessingMode = ProcessingMode.Local
|
|
' MR.LocalReport.EnableExternalImages = True
|
|
' MR.LocalReport.SetParameters(parametros)
|
|
' MR.LocalReport.Refresh()
|
|
' Dim warnings As Warning() = Nothing
|
|
' Dim streamids As String() = Nothing
|
|
' Dim mimeType As String = Nothing
|
|
' Dim encoding As String = Nothing
|
|
' Dim extension As String = Nothing
|
|
' Dim bytes As Byte() = Nothing
|
|
' bytes = MR.LocalReport.Render("PDF", Nothing, mimeType, encoding, extension, streamids, warnings)
|
|
|
|
' Using fs As FileStream = New FileStream(NombreArchivo, FileMode.Create)
|
|
' fs.Write(bytes, 0, bytes.Length)
|
|
' fs.Close()
|
|
' End Using
|
|
' End Using
|
|
' Alert("PDF Generado!")
|
|
'Else
|
|
' Alert("no se pudo procesar el archivo xml")
|
|
'End If
|
|
|
|
|
|
End Sub
|
|
Private Sub VinculacionMasivaComplementos()
|
|
|
|
Dim CountVinculados As Integer = 0
|
|
Dim ValidadoSAT As Boolean = False
|
|
Dim VinculacionValida As Boolean = False
|
|
|
|
For Each gvRow As GridViewRow In GvPagos.Rows
|
|
|
|
Dim DTDocumentosRelacionados As New DataTable
|
|
Dim DTVinculacion As New DataTable
|
|
|
|
Dim ObjValidacion As New ClsValidaCFDi(gvRow.DataKey("UUID"), gvRow.DataKey("RFCDe"), gvRow.DataKey("RFCPara"), 0)
|
|
|
|
If ObjValidacion.EsValida > 0 Then
|
|
|
|
If ObjValidacion.EsValida = 2 Then
|
|
ValidadoSAT = False
|
|
Else
|
|
Dim ObjDatos As New ClsCompras
|
|
ValidadoSAT = ObjDatos.UpdateEstatus(ObjValidacion.EsValida, gvRow.DataKey("CveFactura").ToEntero, UsuarioActual.CveEmpresa)
|
|
ObjDatos.Dispose()
|
|
End If
|
|
|
|
Else
|
|
ValidadoSAT = False
|
|
End If
|
|
ObjValidacion.Dispose()
|
|
|
|
If Not ValidadoSAT Then
|
|
Continue For
|
|
End If
|
|
|
|
Dim sbSinIE As New StringBuilder
|
|
|
|
HdnCveIE.Value = ""
|
|
MSGComplemento = ""
|
|
ViculacionConPUE = False
|
|
ListaComprasPUE.Clear()
|
|
ComplementoConPUE = ""
|
|
|
|
DT_ComprasSinIE = New DataTable
|
|
|
|
Dim ListaComprasPUEInterna As New List(Of Integer)
|
|
|
|
Dim CveComplementoPagoCompra As Integer = gvRow.DataKey("CveComplementoPagoCompra").ToString.ToEntero
|
|
|
|
If CveComplementoPagoCompra > 0 Then
|
|
Continue For
|
|
End If
|
|
|
|
Dim SerieFolioIE As String = ""
|
|
Dim UUIDPago As String = ""
|
|
'Dim ImportePago As Decimal = 0
|
|
Dim StrUUID As New StringBuilder
|
|
Dim Monto As Decimal = 0
|
|
Dim nodePagos As XmlNode = Nothing
|
|
Dim nodePagos2 As XmlNode = Nothing
|
|
Dim nodeComp As XmlNode = Nothing
|
|
Dim nodeaGral As XmlNode = Nothing
|
|
Dim nodeTFD As XmlNode = Nothing
|
|
Dim ImporteIES As Double = 0
|
|
Dim DiferenciaImportes As Double = 0
|
|
Dim TextoDiferenciaImporte As String = ""
|
|
Dim FechaPago As Date
|
|
Dim PagosCantidad As Integer = 0
|
|
|
|
|
|
|
|
Dim XMLDoc As New XmlDocument
|
|
Dim Archivo As String = String.Format("{0}Compras\{1}\{2}", UsuarioActual.Empresa.Ruta, gvRow.DataKey("RFCDe"), gvRow.DataKey("XML"))
|
|
If IO.File.Exists(Archivo) Then
|
|
|
|
|
|
Dim SXML As String = File.ReadAllText(Archivo).Replace(vbLf, " ").Replace(vbCrLf, " ")
|
|
SXML = SXML.Replace("o;?", "")
|
|
SXML = SXML.Trim((Convert.ToChar(0)))
|
|
|
|
XMLDoc.LoadXml(SXML)
|
|
|
|
Dim Xml As New StringBuilder
|
|
Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable)
|
|
|
|
namespaces.AddNamespace(XMLDoc.DocumentElement.Prefix, "http://www.sat.gob.mx/cfd/3")
|
|
namespaces.AddNamespace("aerolineas", "http://www.sat.gob.mx/aerolineas")
|
|
namespaces.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital")
|
|
namespaces.AddNamespace("pago10", "http://www.sat.gob.mx/Pagos")
|
|
nodeComp = XMLDoc.SelectSingleNode(String.Format("//{0}:Complemento", XMLDoc.DocumentElement.Prefix), namespaces)
|
|
|
|
nodeaGral = XMLDoc.SelectSingleNode(String.Format("//{0}:Comprobante", XMLDoc.DocumentElement.Prefix), namespaces)
|
|
|
|
nodeTFD = nodeComp.SelectSingleNode(String.Format("//{0}:TimbreFiscalDigital", "tfd"), namespaces)
|
|
nodePagos = nodeComp.SelectSingleNode(String.Format("//{0}:Pagos/{0}:Pago", "pago10"), namespaces)
|
|
nodePagos2 = nodeComp.SelectSingleNode(String.Format("//{0}:Pagos", "pago10"), namespaces)
|
|
'Monto = ValorXML(nodePagos, "Monto").ToDecimal
|
|
|
|
Dim nodePago As XmlNodeList = nodePagos.SelectNodes(String.Format("//{0}:DoctoRelacionado", "pago10"), namespaces)
|
|
|
|
SeriePago = ValorXML(nodeaGral, "Serie")
|
|
FolioPago = ValorXML(nodeaGral, "Folio")
|
|
|
|
UUIDPago = ValorXML(nodeTFD, "UUID")
|
|
LblUUID.Text = UUIDPago
|
|
|
|
|
|
DTDocumentosRelacionados.Columns.Add("Serie")
|
|
DTDocumentosRelacionados.Columns.Add("SerieFolio")
|
|
|
|
DTDocumentosRelacionados.Columns.Add("IdDocumento")
|
|
DTDocumentosRelacionados.Columns.Add("Folio", GetType(Integer))
|
|
DTDocumentosRelacionados.Columns.Add("MonedaDR")
|
|
DTDocumentosRelacionados.Columns.Add("MetodoDePagoDR")
|
|
DTDocumentosRelacionados.Columns.Add("ImpPagado", GetType(Decimal))
|
|
|
|
DTDocumentosRelacionados.Columns.Add("CveFactura", GetType(Integer))
|
|
DTDocumentosRelacionados.Columns.Add("CveCompra", GetType(Integer))
|
|
DTDocumentosRelacionados.Columns.Add("CveIE", GetType(Integer))
|
|
DTDocumentosRelacionados.Columns.Add("Fecha", GetType(Date))
|
|
|
|
DTDocumentosRelacionados.Columns.Add("FolioPago")
|
|
DTDocumentosRelacionados.Columns.Add("ImportePago", GetType(Decimal))
|
|
DTDocumentosRelacionados.Columns.Add("FechaPago", GetType(Date))
|
|
DTDocumentosRelacionados.Columns.Add("CveMetodoPago", GetType(Integer))
|
|
DTDocumentosRelacionados.Columns.Add("SerieFolioCompra")
|
|
|
|
|
|
|
|
Dim nodePagosN As XmlNodeList
|
|
nodePagosN = nodeComp.SelectNodes(String.Format("//{0}:Pagos", "pago10"), namespaces)
|
|
|
|
|
|
|
|
For Each NodosPagos As XmlNode In nodePagosN
|
|
For Each innernode As XmlNode In NodosPagos
|
|
|
|
FechaPago = ValorXML(innernode, "FechaPago").ToDate
|
|
PagosCantidad = PagosCantidad + 1
|
|
|
|
For Each node As XmlNode In innernode
|
|
|
|
Dim Nrow As DataRow = DTDocumentosRelacionados.NewRow
|
|
|
|
Nrow("Serie") = ValorXML(node, "Serie")
|
|
Nrow("Folio") = ValorXML(node, "Folio").ToEntero
|
|
Nrow("SerieFolio") = ValorXML(node, "Serie") & "-" & ValorXML(node, "Folio").ToEntero
|
|
Nrow("IdDocumento") = ValorXML(node, "IdDocumento")
|
|
Nrow("MonedaDR") = ValorXML(node, "MonedaDR")
|
|
Nrow("MetodoDePagoDR") = ValorXML(node, "MetodoDePagoDR")
|
|
|
|
Monto = Monto + ValorXML(node, "ImpPagado").ToDecimal
|
|
|
|
Nrow("ImpPagado") = ValorXML(node, "ImpPagado").ToDecimal
|
|
Nrow("Fecha") = FechaPago
|
|
|
|
DTDocumentosRelacionados.Rows.Add(Nrow)
|
|
StrUUID.AppendFormat("'{0}',", ValorXML(node, "IdDocumento").Replace("'", ""))
|
|
Next
|
|
|
|
Next
|
|
Next
|
|
|
|
|
|
|
|
Dim ObjCompraFolios As New ClsCompras
|
|
If ObjCompraFolios.GetCompararComplementoPago(gvRow.DataKey("CveProveedor").ToEntero, Monto, nodePagos2.InnerXml.Replace("pago10:", ""), UsuarioActual.CveEmpresa, OP:=2) Then
|
|
'
|
|
'.GetCompararComplementoPago(gvRow.DataKey("CveProveedor").ToEntero, Monto, nodePagos2.InnerXml.Replace("pago10:", ""), UsuarioActual.CveEmpresa) Then
|
|
If ObjCompraFolios.DtResultados.Rows.Count > 0 Then
|
|
For Each drow As DataRow In ObjCompraFolios.DtResultados.Rows
|
|
|
|
For Each dRow2 As DataRow In DTDocumentosRelacionados.Rows
|
|
|
|
If dRow2("IdDocumento").ToString.ToUpper = drow("IdDocumento").ToString.ToUpper Then
|
|
|
|
dRow2("CveCompra") = drow("CveCompra").ToString.ToEntero
|
|
dRow2("CveFactura") = drow("CveFactura").ToString.ToEntero
|
|
dRow2("CveMetodoPago") = drow("CveMetodoPago").ToString.ToEntero
|
|
dRow2("SerieFolioCompra") = drow("SerieFolioCompra").ToString
|
|
|
|
|
|
If drow("CveIE").ToString.ToEntero > 0 Then
|
|
|
|
dRow2("CveIE") = drow("CveIE").ToString.ToEntero
|
|
dRow2("ImportePago") = drow("Importe").ToString.ToDecimal
|
|
|
|
|
|
End If
|
|
|
|
dRow2("FolioPago") = drow("FolioIE")
|
|
dRow2("FechaPago") = drow("FechaDocumento")
|
|
|
|
|
|
|
|
|
|
End If
|
|
Next
|
|
Next
|
|
End If
|
|
End If
|
|
|
|
ObjCompraFolios.Dispose()
|
|
|
|
'GVPDocumentosRelacionadosPagos.DataSource = DTDocumentosRelacionados
|
|
'GVPDocumentosRelacionadosPagos.DataBind()
|
|
|
|
|
|
For Each dRow2 As DataRow In DTDocumentosRelacionados.Rows
|
|
If dRow2("CveMetodoPago").ToString.ToEntero > 0 Then
|
|
If dRow2("CveMetodoPago").ToString.ToEntero = 1 Then
|
|
MSGComplemento = MSGComplemento & $" Compra {dRow2("SerieFolioCompra").ToString } bloqueado Tipo ""PUE"". "
|
|
|
|
ListaComprasPUEInterna.Add(dRow2("CveCompra").ToString.ToEntero)
|
|
|
|
ComplementoConPUE = $"{SeriePago}-{FolioPago}"
|
|
|
|
End If
|
|
End If
|
|
Next
|
|
|
|
|
|
DT_ComprasSinIE.Columns.Add("CveCompra", GetType(Integer))
|
|
DT_ComprasSinIE.Columns.Add("CveFactura", GetType(Integer))
|
|
DT_ComprasSinIE.Columns.Add("SerieFolioPago")
|
|
DT_ComprasSinIE.Columns.Add("SerieFolioCompra")
|
|
|
|
For Each dRow As DataRow In DTDocumentosRelacionados.Rows
|
|
Dim nRow As DataRow = DT_ComprasSinIE.NewRow
|
|
nRow("CveCompra") = dRow("CveCompra").ToString.ToEntero
|
|
' nRow("CveFactura") = dRow("CveFactura").ToString.ToEntero
|
|
nRow("SerieFolioPago") = $"{SeriePago}-{FolioPago}"
|
|
nRow("SerieFolioCompra") = dRow("SerieFolioCompra").ToString
|
|
|
|
DT_ComprasSinIE.Rows.Add(nRow)
|
|
|
|
|
|
Next
|
|
|
|
|
|
|
|
Else
|
|
VinculacionValida = False
|
|
End If
|
|
|
|
CveFacturaPago = gvRow.DataKey("CveFactura").ToEntero
|
|
CveProveedor = gvRow.DataKey("CveProveedor").ToEntero
|
|
Dim ObjCompras As New ClsCompras
|
|
|
|
|
|
Dim TieneRegistros As Boolean = False
|
|
|
|
If ObjCompras.GetCompararComplementoPago(gvRow.DataKey("CveProveedor").ToEntero, Monto, nodePagos2.InnerXml.Replace("pago10:", ""), UsuarioActual.CveEmpresa) Then
|
|
' GvVincularPago.DataSource = ObjCompras.DtResultados
|
|
DTVinculacion = ObjCompras.DtResultados
|
|
If ObjCompras.DtResultados.Rows.Count > 0 Then
|
|
SerieFolioIE = ObjCompras.DtResultados.Rows(0)("SerieFolio").ToString
|
|
'DivVincularPagoManualmente.Visible = False
|
|
VinculacionValida = True
|
|
TieneRegistros = True
|
|
Else
|
|
'DivVincularPagoManualmente.Visible = True
|
|
VinculacionValida = False
|
|
End If
|
|
'ImportePago = ObjCompras.DtResultados.SUMD("Monto")
|
|
Else
|
|
'DivVincularPagoManualmente.Visible = False
|
|
VinculacionValida = False
|
|
End If
|
|
|
|
|
|
For Each dRow As DataRow In DTDocumentosRelacionados.Rows
|
|
|
|
Dim FechaDocumento As Date = dRow("FechaPago").ToString.ToDate
|
|
Dim FechaDoRecibo As Date = dRow("Fecha").ToString.ToDate
|
|
Dim CveIEDocumento As Integer = dRow("CveIE").ToString.ToEntero
|
|
|
|
If CveIEDocumento > 0 And FechaDocumento > New Date(1, 1, 1) Then
|
|
|
|
Dim FT1 As Date = FechaDocumento
|
|
|
|
If FechaDocumento <> New Date(1, 1, 1) Then
|
|
FT1 = FechaDocumento.AddDays(-6)
|
|
End If
|
|
|
|
Dim FT2 As Date = FechaDocumento.AddDays(7)
|
|
|
|
If Not (FechaDoRecibo >= FT1 And FechaDoRecibo < FT2) Then
|
|
|
|
VinculacionValida = False
|
|
'MSGComplemento = MSGComplemento & " Existen mas de 3 días de diferencia entre la fecha del documento y la fecha de complemento. "
|
|
Exit For
|
|
|
|
End If
|
|
|
|
End If
|
|
|
|
Next
|
|
|
|
ObjCompras.Dispose()
|
|
|
|
If VinculacionValida Then
|
|
|
|
Dim TieneError As Boolean = False
|
|
Dim ObjCompra As New ClsCompras
|
|
ObjCompra.IniciaTransacSQL()
|
|
|
|
|
|
For Each DTRow As DataRow In DTVinculacion.Rows
|
|
|
|
If Not ObjCompra.AddComplementoPago(DTRow("CveIE").ToString.ToEntero, DTRow("CveCompra").ToString.ToEntero, DTRow("Monto").ToString.ToDecimal, DTRow("CvePrePolizaDetalle").ToString.ToEntero, CveFacturaPago) > 0 Then
|
|
TieneError = True
|
|
End If
|
|
|
|
|
|
Next
|
|
|
|
If Not TieneError AndAlso Not ObjCompra.AddVincularPago(CveFacturaPago) Then
|
|
TieneError = True
|
|
Else
|
|
CountVinculados = CountVinculados + 1
|
|
End If
|
|
|
|
|
|
If Not TieneError Then
|
|
ObjCompra.Commit()
|
|
Else
|
|
ObjCompra.RollBack()
|
|
End If
|
|
|
|
ObjCompra.Dispose()
|
|
End If
|
|
Next
|
|
|
|
|
|
If CountVinculados > 0 Then
|
|
|
|
Alert($"Se vincularon {CountVinculados} complementos")
|
|
CargaDatos(NowADS())
|
|
|
|
End If
|
|
|
|
|
|
|
|
End Sub
|
|
Protected Sub LnkVinculacionMasivaComplementos_Click(sender As Object, e As EventArgs)
|
|
VinculacionMasivaComplementos()
|
|
End Sub
|
|
|
|
#Region "TRASLADOS"
|
|
|
|
|
|
Protected Sub GvTraslados_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvTraslados.RowDataBound
|
|
|
|
If e.Row.RowType = DataControlRowType.DataRow Then
|
|
|
|
If e.Row.DBCampo("TipoComprobante") = "T" Then
|
|
e.Row.FCLabel("LtTipoComprobante").Text = "Traslado"
|
|
e.Row.FCLabel("LtTipoComprobante").CssClass = "label label-sm label-primary"
|
|
e.Row.FCLabel("LtTipoComprobante").Attributes.Add("data-toggle", "tooltip")
|
|
e.Row.FCLabel("LtTipoComprobante").Attributes.Add("title", "Traslado")
|
|
End If
|
|
|
|
e.Row.Cells(2).Attributes.Add("data-order", e.Row.DBCampo("FechaFactura").ToDate.Ticks.ToString)
|
|
|
|
Dim RutaXML As String = String.Format("{0}{1}\{2}", Destino, e.Row.DBCampo("RFCDe"), e.Row.DBCampo("XML"))
|
|
|
|
If File.Exists(String.Format("{0}{1}\{2}", Destino, e.Row.DBCampo("RFCDe"), e.Row.DBCampo("XML"))) Then
|
|
e.Row.FCLiteral("LtlXML").Text = String.Format("<a class=""Texto"" href=""/Compras/PopUpVerFactura.aspx?RFC={0}&File={1}"">Ver</a>", HttpUtility.UrlEncode(e.Row.DBCampo("RFCDe")), HttpUtility.UrlEncode(e.Row.DBCampo("XML")))
|
|
If e.Row.DBCampo("TipoComprobante") = "T" And e.Row.DBCampo("FueValidado") = "1" Then
|
|
' e.Row.FCLinkButton("LnkAgregarTraslado").Visible = True
|
|
e.Row.FCHyperLink("HplAgregar").NavigateUrl = String.Format("/Compras/Compras.aspx?CveFactura={0}&RFC={1}", e.Row.DBCampo("CveFactura"), e.Row.DBCampo("RFCDe"))
|
|
|
|
|
|
End If
|
|
Else
|
|
e.Row.FCLiteral("LtlXML").Text = "N/D" ' String.Format("{0}{1}\{2}", Destino, e.Row.DBCampo("RFCDe"), e.Row.DBCampo("XML")) '
|
|
If e.Row.DBCampo("TipoComprobante") = "T" Then
|
|
e.Row.FCLinkButton("LnkAgregarTraslado").Visible = False
|
|
End If
|
|
End If
|
|
|
|
If File.Exists(String.Format("{0}{1}/{2}", Destino, e.Row.DBCampo("RFCDe"), e.Row.DBCampo("PDF"))) Then
|
|
e.Row.FCLiteral("LtlPDF").Text = String.Format("<a class=""Texto"" href=""/Compras/PopUpVerFactura.aspx?RFC={0}&File={1}"">Ver</a>", HttpUtility.UrlEncode(e.Row.DBCampo("RFCDe")), HttpUtility.UrlEncode(e.Row.DBCampo("PDF")))
|
|
Else
|
|
e.Row.FCLiteral("LtlPDF").Text = "N/D" ' String.Format("{0}{1}/{2}", Destino, e.Row.DBCampo("RFCDe"), e.Row.DBCampo("PDF"))
|
|
End If
|
|
|
|
If e.Row.DBCampo("FueValidado").Contiene("1", "2", "3") Then
|
|
e.Row.FCLinkButton("ImgValidarCFDi").Visible = False
|
|
e.Row.FCLiteral("LtlValidado").Visible = True
|
|
If e.Row.DBCampo("FueValidado") = "2" Then
|
|
e.Row.FCLiteral("LtlValidado").Text = "Cancelada"
|
|
e.Row.ForeColor = Drawing.Color.Red
|
|
e.Row.FCHyperLink("HplProveedor").ForeColor = Drawing.Color.Red
|
|
ElseIf e.Row.DBCampo("FueValidado") = "3" Then
|
|
e.Row.FCLiteral("LtlValidado").Text = "Omitida"
|
|
e.Row.ForeColor = Drawing.Color.Gray
|
|
e.Row.FCHyperLink("HplProveedor").ForeColor = Drawing.Color.Gray
|
|
End If
|
|
Else
|
|
If e.Row.DBCampo("TipoFactura") = "CFD" Then
|
|
e.Row.FCLinkButton("ImgValidarCFDi").CommandName = "ValidarCFD"
|
|
e.Row.FCLinkButton("ImgValidarCFDi").OnClientClick = "return confirm('La factura se validó en el sitio del SAT de comprobantes fiscales?');"
|
|
End If
|
|
e.Row.FCLinkButton("ImgValidarCFDi").Visible = True
|
|
e.Row.FCLiteral("LtlValidado").Visible = False
|
|
|
|
End If
|
|
If e.Row.DBCampo("CveCompra") <> "" Then
|
|
e.Row.FCLiteral("LtlFolio").Text = String.Format("<a class=""Texto"" style=""cursor:pointer;text-decoration: underline;"" href='/Compras/Compras.aspx?CveCompra={0}' target='_blank' rel='opener');"">{1}</a>", e.Row.DBCampo("CveCompra"), e.Row.DBCampo("SerieFolio")) '1\Compras\GAPC480413QL3\A-69.xml
|
|
End If
|
|
|
|
If e.Row.DBCampo("CveProveedor") = "" Then
|
|
e.Row.FCHyperLink("HplProv").Visible = True
|
|
e.Row.FCHyperLink("HplProv").NavigateUrl = String.Format("/Compras/Proveedores.aspx?CveFactura={0}", e.Row.DBCampo("CveFactura"))
|
|
|
|
Else
|
|
e.Row.FCHyperLink("HplProveedor").NavigateUrl = String.Format("/Compras/Proveedores.aspx?CveProveedor={0}", e.Row.DBCampo("CveProveedor"))
|
|
|
|
If e.Row.DBCampo("CveCompra") = "" AndAlso (e.Row.DBCampo("FueValidado") = "1") Then
|
|
e.Row.FCHyperLink("HplAgregarT").Visible = False
|
|
Else
|
|
e.Row.FCHyperLink("HplAgregarT").Visible = False
|
|
End If
|
|
|
|
End If
|
|
|
|
|
|
'Dim CveComplementoTraslado As Integer = e.Row.DataKey("CveComplementoTraslado").ToString.ToEntero
|
|
|
|
|
|
'If CveComplementoTraslado > 0 Then
|
|
' e.Row.FCLinkButton("LnkAgregarTraslado").CssClass = "btn btn-sm green"
|
|
' e.Row.FCLinkButton("LnkAgregarTraslado").Text = "<i class='fa fa-info' ></i>"
|
|
' e.Row.FCLinkButton("LnkAgregarTraslado").Attributes.Add("Title", "Ver vinculación")
|
|
'Else
|
|
' e.Row.FCLinkButton("LnkAgregarTraslado").CssClass = "btn btn-sm blue"
|
|
' e.Row.FCLinkButton("LnkAgregarTraslado").Text = "<i class='fa fa-check'></i>"
|
|
' e.Row.FCLinkButton("LnkAgregarTraslado").Attributes.Add("Title", "Vincular Traslado")
|
|
'End If
|
|
|
|
End If
|
|
|
|
End Sub
|
|
|
|
Protected Sub GvTraslados_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GvTraslados.RowCommand
|
|
Dim ImgBtn As LinkButton = DirectCast(e.CommandSource, LinkButton)
|
|
Dim GvRow As GridViewRow = DirectCast(ImgBtn.BindingContainer, GridViewRow)
|
|
Dim ObjDatos As New ClsCompras
|
|
Dim Correcto As Boolean = False
|
|
|
|
Select Case e.CommandName
|
|
Case "ValidarCFDi"
|
|
Dim ObjValidacion As New ClsValidaCFDi(GvRow.DataKey("UUID"), GvRow.DataKey("RFCDe"), GvRow.DataKey("RFCPara"), 0)
|
|
If ObjValidacion.EsValida > 0 Then
|
|
If ObjValidacion.EsValida = 2 Then
|
|
Alert("La factura está cancelada ante el SAT.", TipoMensaje.MsgInformacion)
|
|
End If
|
|
Correcto = ObjDatos.UpdateEstatus(ObjValidacion.EsValida, GvRow.DataKey("CveFactura").ToEntero, UsuarioActual.CveEmpresa)
|
|
Else
|
|
Alert("La Factura no se pudo validar.", TipoMensaje.MsgAdvertencia)
|
|
End If
|
|
ObjValidacion.Dispose()
|
|
Case "ValidarCFD"
|
|
Correcto = ObjDatos.UpdateEstatus(1, GvRow.DataKey("CveFactura").ToEntero, UsuarioActual.CveEmpresa)
|
|
|
|
Case "Omitir"
|
|
Correcto = ObjDatos.UpdateEstatus(3, GvRow.DataKey("CveFactura").ToEntero, UsuarioActual.CveEmpresa)
|
|
End Select
|
|
|
|
ObjDatos.Dispose()
|
|
If Correcto Then
|
|
CargaDatos(NowADS())
|
|
End If
|
|
End Sub
|
|
|
|
Protected Sub LnkAgregarTraslado_Click(sender As Object, e As EventArgs)
|
|
|
|
Dim gvRow As GridViewRow = DirectCast((DirectCast(sender, LinkButton)).NamingContainer, GridViewRow)
|
|
Dim CveComplementoTraslado As Integer = gvRow.DataKey("CveComplementoTraslado").ToEntero
|
|
CveFacturaComplementoTraslado = gvRow.DataKey("CveFactura").ToEntero
|
|
Dim SerieFolioTraslado As String = gvRow.DataKey("SerieFolio").ToString
|
|
LnkVincularTraslado.Visible = False
|
|
|
|
|
|
If CveComplementoTraslado > 0 Then
|
|
DvMomdalVincualarTrasladoBusqueda.Visible = False
|
|
DvModalVincularTrasladoVinculado.Visible = True
|
|
LtlModalVincularTrasaldoTitulo.Text = "Traslado Vinculado"
|
|
LnkModalModalVincularTrasaldoFolio.Text = gvRow.DataKey("SerieFolioVinculado")
|
|
LnkModalModalVincularTrasaldoFolio.NavigateUrl = $"~/Compras/Compras.aspx?CveCompra={gvRow.DataKey("CveCompraTraslado")}"
|
|
|
|
|
|
Else
|
|
DvMomdalVincualarTrasladoBusqueda.Visible = True
|
|
DvModalVincularTrasladoVinculado.Visible = False
|
|
LtlModalVincularTrasaldoTitulo.Text = "Vincular Traslado"
|
|
End If
|
|
|
|
UpModalVincularTraslado.Update()
|
|
RegistraScript("$('#DvModalVincularTrasaldo').modal('show');")
|
|
|
|
End Sub
|
|
Protected Sub BtnCargaCompraComplementoTraslado_Click(sender As Object, e As EventArgs)
|
|
|
|
|
|
|
|
If HdnCveCompraComplementoTraslado.Value.ToString.ToEntero > 0 Then
|
|
|
|
LnkVincularTraslado.Visible = True
|
|
LnkModalModalVincularTrasaldoFolio.Text = HdnFolioCompraComplementoTraslado.Value.ToString
|
|
LnkModalModalVincularTrasaldoFolio.NavigateUrl = $"~/Compras/Compras.aspx?CveCompra={HdnCveCompraComplementoTraslado.Value.ToString}"
|
|
DvModalVincularTrasladoVinculado.Visible = True
|
|
|
|
|
|
Else
|
|
LnkVincularTraslado.Visible = False
|
|
LnkModalModalVincularTrasaldoFolio.Text = ""
|
|
LnkModalModalVincularTrasaldoFolio.NavigateUrl = ""
|
|
DvModalVincularTrasladoVinculado.Visible = False
|
|
LnkVincularTraslado.Visible = False
|
|
End If
|
|
|
|
|
|
UpModalVincularTraslado.Update()
|
|
|
|
End Sub
|
|
|
|
Protected Sub LnkVincularTraslado_Click(sender As Object, e As EventArgs)
|
|
|
|
Dim ProcesoOk As Boolean = False
|
|
|
|
|
|
|
|
If HdnCveCompraComplementoTraslado.Value.ToString.ToEntero > 0 Then
|
|
Dim objCompras As New ClsCompras
|
|
|
|
If objCompras.AddComplementoTraslado(CveFacturaComplementoTraslado, HdnCveCompraComplementoTraslado.Value.ToString.ToEntero, UsuarioActual.CveUsuario) Then
|
|
ProcesoOk = True
|
|
End If
|
|
objCompras.Dispose()
|
|
End If
|
|
|
|
If ProcesoOk Then
|
|
RegistraScript("$('#DvModalVincularTrasaldo').modal('hide');")
|
|
CargaDatos(NowADS())
|
|
Alert("Traslado Vinculado correctamente.")
|
|
End If
|
|
|
|
|
|
End Sub
|
|
|
|
|
|
|
|
#End Region
|
|
|
|
Protected Sub LnkModalPersonalizar_Click(sender As Object, e As EventArgs)
|
|
|
|
GvD.Columns(12).Visible = ChkModalPersonalzarFolioFiscal.Checked
|
|
GvPagos.Columns(9).Visible = ChkModalPersonalzarFolioFiscal.Checked
|
|
GvTraslados.Columns(9).Visible = ChkModalPersonalzarFolioFiscal.Checked
|
|
|
|
|
|
UpDatos.Update()
|
|
UpPagos.Update()
|
|
UpTraslados.Update()
|
|
|
|
RegistraScript("$('#DvmodalPersonalizar').modal('hide');")
|
|
End Sub
|
|
|
|
Protected Sub LnkPersonalizar_Click(sender As Object, e As EventArgs)
|
|
|
|
RegistraScript("$('#DvmodalPersonalizar').modal('show');")
|
|
|
|
End Sub
|
|
|
|
Protected Sub LnkRemoveSolicitud_Click(sender As Object, e As EventArgs)
|
|
|
|
Dim gvRow As GridViewRow = DirectCast((DirectCast(sender, LinkButton)).NamingContainer, GridViewRow)
|
|
Dim ProcesoOk As Boolean = False
|
|
|
|
Dim CveSolicitud As Integer = gvRow.DataKey("CveSolicitud").ToEntero
|
|
Dim Folio As Integer = gvRow.DataKey("Folio").ToEntero
|
|
|
|
Using nom As ClsNominas = New ClsNominas()
|
|
ProcesoOk = nom.SolicitudesCancelar(CveSolicitud, UsuarioActual.CveEmpresa, UsuarioActual.CveUsuario)
|
|
End Using
|
|
|
|
If ProcesoOk Then
|
|
Alert($"Solicitud {Folio} cancelada correctamente.")
|
|
cargasolicitudes()
|
|
End If
|
|
|
|
End Sub
|
|
|
|
|
|
#Region "REGISTRO DE FACTURAS"
|
|
|
|
Private Property DTClasificacionesComprobaciones As DataTable
|
|
Get
|
|
|
|
If ViewState("DTClasificacionesComprobaciones") Is Nothing Then
|
|
Return New DataTable
|
|
Else
|
|
Return DirectCast(ViewState("DTClasificacionesComprobaciones"), DataTable)
|
|
End If
|
|
|
|
End Get
|
|
Set(value As DataTable)
|
|
ViewState("DTClasificacionesComprobaciones") = value
|
|
End Set
|
|
End Property
|
|
|
|
|
|
Private Property EstaAsociadoACajaChica() As Boolean
|
|
Get
|
|
Return If(IsNothing(ViewState("EstaAsociadoACajaChica")), False, CBool(ViewState("EstaAsociadoACajaChica")))
|
|
End Get
|
|
Set
|
|
ViewState("EstaAsociadoACajaChica") = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private Property EstaAsociadoAPersonal() As Boolean
|
|
Get
|
|
Return If(IsNothing(ViewState("EstaAsociadoAPersonal")), False, CBool(ViewState("EstaAsociadoAPersonal")))
|
|
End Get
|
|
Set
|
|
ViewState("EstaAsociadoAPersonal") = Value
|
|
End Set
|
|
End Property
|
|
|
|
Private Property CveMoneda As Integer
|
|
Get
|
|
Return ViewState("CveMoneda").ToString.ToEntero
|
|
End Get
|
|
Set(value As Integer)
|
|
ViewState("CveMoneda") = value
|
|
End Set
|
|
End Property
|
|
|
|
Public ReadOnly Property eFacturasLog As String
|
|
Get
|
|
Return "eFacturasLog"
|
|
End Get
|
|
|
|
End Property
|
|
|
|
|
|
Private Sub CargaClasificacionesComprobaciones()
|
|
|
|
If UsuarioActual.TienePermisoProceso(300) Or UsuarioActual.TienePermisoProceso(301) Then
|
|
|
|
Dim ObjClasificaciones As New ClsClasificaciones()
|
|
|
|
If ObjClasificaciones.GetClasificacionesComprobaciones(UsuarioActual.CveEmpresa) Then
|
|
|
|
If UsuarioActual.TienePermisoProceso(300) And UsuarioActual.TienePermisoProceso(301) Then
|
|
DTClasificacionesComprobaciones = ObjClasificaciones.DtResultados
|
|
Else
|
|
|
|
If UsuarioActual.TienePermisoProceso(300) Then 'TipoComprobacion = 1 Biaticos
|
|
DTClasificacionesComprobaciones = ObjClasificaciones.DtResultados.FiltraParametros("TipoComprobacion = 1")
|
|
ElseIf UsuarioActual.TienePermisoProceso(301) Then 'TipoComprobacion = 2 Comprobaciones
|
|
DTClasificacionesComprobaciones = ObjClasificaciones.DtResultados.FiltraParametros("TipoComprobacion = 2")
|
|
End If
|
|
End If
|
|
End If
|
|
ObjClasificaciones.Dispose()
|
|
End If
|
|
|
|
End Sub
|
|
|
|
Private Sub CargaClasificaciones()
|
|
'DdlClasificacion.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltraParametros("", Orderby:="Clasificacion")
|
|
'DdlClasificacion.DataBind()
|
|
End Sub
|
|
|
|
Private Sub CargaPS(CveClasificacion As Integer)
|
|
|
|
DdlPS.setEsWebService(UsuarioActual.Empresa.Funcionalidad(105) = "1")
|
|
|
|
If UsuarioActual.Empresa.Funcionalidad(105) = "1" Then
|
|
'DdlPS.ddlWS.Attributes.Add("data-cveclasificacion", DdlClasificacion.SelectedValue)
|
|
DdlPS.ddlWS.Attributes.Add("data-cveclasificacion", "-1")
|
|
DdlPS.SelectedText = ""
|
|
DdlPS.SelectedValue = "-1"
|
|
Else
|
|
DdlPS.ddl.Items.Clear()
|
|
|
|
'DdlPS.ddl.DataSource = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa, CveClasificacion:=CveClasificacion)
|
|
|
|
If UsuarioActual.TienePermisoProceso(300) Or UsuarioActual.TienePermisoProceso(301) Then
|
|
|
|
Dim DTTemp As New DataTable
|
|
DTTemp.Columns.Add("CvePS", GetType(Integer))
|
|
DTTemp.Columns.Add("PSCodigo", GetType(String))
|
|
DTTemp.Columns.Add("CveClasificacion", GetType(Integer))
|
|
|
|
For Each dRow As DataRow In GlobalDTPSSimplificado(UsuarioActual.CveEmpresa).Rows
|
|
For Each drowCla As DataRow In DTClasificacionesComprobaciones.Rows
|
|
|
|
If drowCla("CveClasificacion").ToString.ToEntero = dRow("CveClasificacion").ToString.ToEntero Then
|
|
|
|
Dim InRow As DataRow = DTTemp.NewRow
|
|
InRow("CvePS") = dRow("CvePS").ToString.ToEntero
|
|
InRow("PSCodigo") = dRow("PSCodigo").ToString
|
|
InRow("CveClasificacion") = dRow("CveClasificacion").ToString.ToEntero
|
|
DTTemp.Rows.Add(InRow)
|
|
|
|
End If
|
|
Next
|
|
Next
|
|
|
|
|
|
DdlPS.DataSource = If(CveClasificacion > 0, DTTemp.FiltraParametros($"CveClasificacion = {CveClasificacion}"), DTTemp)
|
|
|
|
Else
|
|
DdlPS.DataSource = If(CveClasificacion > 0, GlobalDTPSSimplificado(UsuarioActual.CveEmpresa).FiltraParametros($"CveClasificacion = {CveClasificacion}"), GlobalDTPSSimplificado(UsuarioActual.CveEmpresa))
|
|
End If
|
|
|
|
DdlPS.ddl.DataBind()
|
|
DdlPS.ddl.Items.Insert(0, New ListItem("Seleccione el Producto", "-1"))
|
|
End If
|
|
|
|
|
|
|
|
End Sub
|
|
|
|
|
|
Protected Sub RBLContado_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RBLContado.SelectedIndexChanged
|
|
|
|
CargaContado()
|
|
End Sub
|
|
|
|
Private Sub CargaContado()
|
|
|
|
|
|
DivPersonalReembolso.Visible = False
|
|
DivCuentaCajaChicaReembolso.Visible = False
|
|
|
|
|
|
Select Case RBLContado.SelectedValue
|
|
|
|
Case "2" ' F y E
|
|
DivPersonalReembolso.Visible = True
|
|
RfvTxtNumeroReembolso.Enabled = True
|
|
|
|
Case "6" ' Caja Chica
|
|
DivCuentaCajaChicaReembolso.Visible = True
|
|
RfvTxtNumeroReembolso.Enabled = True
|
|
|
|
End Select
|
|
|
|
UpRegistroFacturas.Update()
|
|
|
|
End Sub
|
|
|
|
Private Sub CargaPersoanlCajaChica()
|
|
Dim dt As DataTable = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa)
|
|
dt = dt.FiltraParametros(String.Format("CveTipoCuenta = 1"))
|
|
DdlCuentaCajaChicaReembolso.DataSource = dt
|
|
DdlCuentaCajaChicaReembolso.DataBind()
|
|
End Sub
|
|
|
|
Private Sub CargaPersonalViaticos()
|
|
Dim dtpersonal As DataTable = GlobalDTRHPersonal(UsuarioActual.CveEmpresa)
|
|
DdlPersonalReembolso.DataSource = dtpersonal.FiltraParametros("CveEstatusPersonal = 1")
|
|
DdlPersonalReembolso.DataBind()
|
|
End Sub
|
|
|
|
Private Sub CargaDdlRetIVA()
|
|
DdlRetIVAConcepto.Items.Insert(0, New ListItem("Honorarios/Serv. Prof.", "1"))
|
|
DdlRetIVAConcepto.Items.Add(New ListItem("Arrendamiento", "4"))
|
|
DdlRetIVAConcepto.Items.Insert(0, New ListItem("Fletes P.F.", "2"))
|
|
DdlRetIVAConcepto.Items.Add(New ListItem("Resico", "5"))
|
|
DdlRetIVAConcepto.Items.Add(New ListItem("General", "6"))
|
|
End Sub
|
|
|
|
|
|
Private Sub CargaDdlRetISR()
|
|
DdlRetISRConcepto.Items.Insert(0, New ListItem("Honorarios", "1"))
|
|
DdlRetISRConcepto.Items.Insert(1, New ListItem("Arrendamiento", "2"))
|
|
DdlRetISRConcepto.Items.Insert(1, New ListItem("Resico", "3"))
|
|
End Sub
|
|
|
|
|
|
|
|
Protected Sub DdlPersonal2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlPersonalReembolso.SelectedIndexChanged
|
|
ViewState("CvePersonal") = DdlPersonalReembolso.SelectedValue
|
|
If DdlPersonalReembolso.SelectedValue.ToEntero > 0 Then
|
|
EstaAsociadoAPersonal = True
|
|
End If
|
|
End Sub
|
|
Protected Sub DdlCajaChica2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DdlCuentaCajaChicaReembolso.SelectedIndexChanged
|
|
Dim dr As DataRow = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero("CveCuenta = " & DdlCuentaCajaChicaReembolso.SelectedValue)
|
|
|
|
If dr IsNot Nothing Then
|
|
CveMoneda = dr("CveMoneda").ToString.ToEntero
|
|
EstaAsociadoACajaChica = True
|
|
End If
|
|
ViewState("CveCajaChica") = DdlCuentaCajaChicaReembolso.SelectedValue
|
|
End Sub
|
|
|
|
#End Region
|
|
|
|
Protected Sub LnkRegistarFactura_Click(sender As Object, e As EventArgs)
|
|
DivRegistraFacturas.Visible = True
|
|
GvD.Columns(0).Visible = True
|
|
|
|
UpRegistroFacturas.Update()
|
|
UpDatos.Update()
|
|
End Sub
|
|
|
|
Protected Sub BtnGuardarFacturas_Click(sender As Object, e As EventArgs)
|
|
|
|
Dim ErrorProceso As Boolean = False
|
|
Dim Contador As Integer = 0
|
|
Dim ErrorProcesoStr As String = ""
|
|
|
|
If Not DdlPS.SelectedValue.ToEntero > 0 Then
|
|
Alert("Debe seleccionar un producto", TipoMensaje.MsgAdvertencia)
|
|
Exit Sub
|
|
End If
|
|
|
|
For Each GvRow As GridViewRow In GvD.Rows
|
|
If GvRow.FCCheckBox("chkRegistraFactura").Checked Then
|
|
|
|
Dim CFDIXmlPath As String = $"{UsuarioActual.Empresa.Ruta}Compras\{GvRow.DataKey("RFCDe")}\{GvRow.DataKey("XML")}"
|
|
If Not File.Exists(CFDIXmlPath) Then
|
|
ErrorProceso = True
|
|
Exit For
|
|
End If
|
|
|
|
Dim CompraActual As New ClsCompraManager(CFDIXmlPath, ClsCompraManager.EnumCargaCompra.DesdeArchivo, GlobalDTTiposGastos(UsuarioActual.CveEmpresa), UsuarioActual)
|
|
|
|
CompraActual.CveFactura = GvRow.DataKey("CveFactura").ToEntero
|
|
CompraActual.CveProveedor = GvRow.DataKey("CveProveedor").ToEntero
|
|
CompraActual.CveTipoProveedor = GvRow.DataKey("CveTipoProveedor").ToEntero
|
|
CompraActual.CveTipoConceptoProveedor = GvRow.DataKey("CveTipoProveedor").ToEntero
|
|
CompraActual.TipoCompra = ClsCompraManager.EnumTipoCompra.Sin_definir
|
|
CompraActual.IEPSGasto = True
|
|
CompraActual.Descripcion = TxtDescripcionCompra.Text.Trim
|
|
CompraActual.NombreProveedor = GvRow.DataKey("NombreProveedor")
|
|
|
|
Dim CvePersonal As Integer = -1 'DdlPersonalReembolso.SelectedValue.ToEntero
|
|
Dim CveCajachica As Integer = -1 'DdlCuentaCajaChicaReembolso.SelectedValue.ToEntero
|
|
|
|
If RBLContado.SelectedValue.ToEntero = 6 Then
|
|
CveCajachica = DdlCuentaCajaChicaReembolso.SelectedValue.ToEntero
|
|
Else
|
|
CvePersonal = DdlPersonalReembolso.SelectedValue.ToEntero
|
|
End If
|
|
|
|
CompraActual.ConfiguraRegistroRapidoReembolso(DdlPS.SelectedValue.ToEntero, DdlSubProyecto.SelectedValue.ToEntero, CveCajachica, CvePersonal,
|
|
DdlRetIVAConcepto.SelectedValue.ToEntero, DdlRetISRConcepto.SelectedValue.ToEntero, NumeroReembolso:=TxtNumeroReembolso.Text)
|
|
If CompraActual.AddCompra() Then
|
|
Contador = Contador + 1
|
|
Else
|
|
ErrorProceso = True
|
|
ErrorProcesoStr = CompraActual.MensajeError
|
|
Exit For
|
|
End If
|
|
End If
|
|
Next
|
|
|
|
If Not ErrorProceso Then
|
|
CargaDatos(NowADS())
|
|
If Contador > 0 Then
|
|
Alert($"Se registraron {Contador} Compras")
|
|
End If
|
|
Else
|
|
Alert($"Se registraron {Contador} Compras. error {ErrorProcesoStr}", TipoMensaje.MsgAdvertencia)
|
|
End If
|
|
|
|
End Sub
|
|
|
|
End Class
|
|
|
|
|
|
|
|
Public Class ClsCompraManager
|
|
|
|
Enum EnumCargaCompra
|
|
DesdeXML
|
|
DesdeArchivo
|
|
End Enum
|
|
Public Enum EnumCFDIVersion
|
|
v32
|
|
V33
|
|
V40
|
|
End Enum
|
|
|
|
Public Enum EnumTipoCompra
|
|
Sin_definir = -1
|
|
Gasto_con_almacen = 10
|
|
Activo_Fijo = 1
|
|
'Costo_Indirecto = 2
|
|
Almacen = 3
|
|
Almacen_con_costo_indirecto = 8
|
|
Costo_Indirecto = 4
|
|
Importación = 5
|
|
NC_Con_Productos = 6
|
|
Apoyo_Logístico = 9
|
|
NC_Por_Devolución = 11
|
|
Garantia = 12
|
|
End Enum
|
|
|
|
|
|
Public Enum EnumModalidadAccionPS
|
|
Agregar
|
|
Actualizar
|
|
End Enum
|
|
|
|
Public Property CveCompra As Integer = -1
|
|
Public Property CveProveedor As Integer
|
|
Public Property CveTipoConceptoProveedor As Integer
|
|
Public Property CveMoneda As Integer
|
|
Public Property Fecha As Date
|
|
Public ReadOnly Property SerieFolio As String
|
|
Get
|
|
If Serie.Length > 0 Then
|
|
Return $"{Serie}-{Folio}"
|
|
Else
|
|
Return $"{Folio}"
|
|
End If
|
|
End Get
|
|
End Property
|
|
|
|
Public Property Serie As String = ""
|
|
Public Property Folio As String = ""
|
|
Public Property FolioSecundario As String = ""
|
|
Public Property Descripcion As String = ""
|
|
Public Property CFDIVersion As EnumCFDIVersion = EnumCFDIVersion.V40
|
|
Public Property ProveedorNombre As String = ""
|
|
Public Property EsImportacion As Boolean = False
|
|
Public Property TC As Decimal = 1
|
|
Public Property SubTotal As Decimal = 0D
|
|
Public Property SubTotal2 As Decimal = 0D
|
|
Public Property Descuento As Decimal = 0D
|
|
Public Property Total As Decimal = 0D
|
|
Public Property Moneda As String = ""
|
|
Public Property TipoComprobante As String
|
|
Public Property TipoCambio As Decimal = 1
|
|
Public Property CompraNoDeducible As Integer = 0
|
|
Public Property IVA As Decimal = 0D
|
|
Public Property IVADeducible As Decimal = 0D
|
|
Public Property IVANoDeducible As Decimal = 0
|
|
Public Property IEPS As Decimal = 0D
|
|
Public Property RetIVA As Decimal = 0D
|
|
Public Property RetISR As Decimal = 0D
|
|
Public Property PorcentajeIVA As Decimal = 0
|
|
Public Property PorcentajeISR As Decimal = 0
|
|
Public Property CveRetIVAConcepto As Integer = -1
|
|
Public Property CveRetISRConcepto As Integer = -1
|
|
Public Property CveSubProyecto As Integer = -1
|
|
Public Property UsuarioActual As Usuario
|
|
Public ReadOnly Property ConceptoPrePolizaIVA As ConceptosRetenciones
|
|
Get
|
|
Dim Ret As New ConceptosRetenciones
|
|
If EsImportacion Then
|
|
Ret.CveConceptoAcreditable = 288
|
|
Ret.CveConceptoxAcreditar = 287
|
|
Else
|
|
Ret.CveConceptoAcreditable = 19
|
|
Ret.CveConceptoxAcreditar = 14
|
|
End If
|
|
Return Ret
|
|
End Get
|
|
End Property
|
|
Public ReadOnly Property ConceptoPrePolizaRetIVA As ConceptosRetenciones
|
|
Get
|
|
Dim Ret As New ConceptosRetenciones
|
|
Dim Funcionalidad, FuncionalidadxAcred As Integer
|
|
If CveRetIVAConcepto = 1 Then
|
|
Funcionalidad = 308 : FuncionalidadxAcred = 307
|
|
Ret.CveConceptoAcreditable = 22
|
|
Ret.CveConceptoxAcreditar = 15
|
|
ElseIf CveRetIVAConcepto = 2 Then
|
|
Funcionalidad = 310 : FuncionalidadxAcred = 309
|
|
Ret.CveConceptoAcreditable = 184
|
|
Ret.CveConceptoxAcreditar = 183
|
|
ElseIf CveRetIVAConcepto = 3 Then
|
|
Funcionalidad = 312 : FuncionalidadxAcred = 311
|
|
Ret.CveConceptoAcreditable = 186
|
|
Ret.CveConceptoxAcreditar = 185
|
|
ElseIf CveRetIVAConcepto = 4 Then
|
|
Funcionalidad = 314 : FuncionalidadxAcred = 313
|
|
Ret.CveConceptoAcreditable = 249
|
|
Ret.CveConceptoxAcreditar = 248
|
|
ElseIf CveRetIVAConcepto = 5 Then
|
|
Funcionalidad = 578 : FuncionalidadxAcred = 578
|
|
Ret.CveConceptoAcreditable = 286
|
|
Ret.CveConceptoxAcreditar = 285
|
|
ElseIf CveRetIVAConcepto = 6 Then
|
|
Funcionalidad = 578 : FuncionalidadxAcred = 578
|
|
Ret.CveConceptoAcreditable = 333
|
|
Ret.CveConceptoxAcreditar = 334
|
|
End If
|
|
Return Ret
|
|
End Get
|
|
End Property
|
|
Public ReadOnly Property ConceptoPrePolizaRetISR As ConceptosRetenciones
|
|
Get
|
|
Dim Ret As New ConceptosRetenciones
|
|
Dim Funcionalidad, FuncionalidadxAcred As Integer
|
|
If CveRetISRConcepto = 1 Then
|
|
Funcionalidad = 316 : FuncionalidadxAcred = 315
|
|
Ret.CveConceptoAcreditable = 23
|
|
Ret.CveConceptoxAcreditar = 16
|
|
ElseIf CveRetISRConcepto = 2 Then
|
|
Funcionalidad = 318 : FuncionalidadxAcred = 317
|
|
Ret.CveConceptoAcreditable = 244
|
|
Ret.CveConceptoxAcreditar = 243
|
|
ElseIf CveRetISRConcepto = 3 Then
|
|
Funcionalidad = 349 : FuncionalidadxAcred = 348
|
|
Ret.CveConceptoAcreditable = 328
|
|
Ret.CveConceptoxAcreditar = 327
|
|
End If
|
|
Return Ret
|
|
End Get
|
|
End Property
|
|
|
|
Public Property CveMetodoPago As Integer
|
|
Public Property MetodoPago As String
|
|
Public Property DocumentosRelacionadosUUIDSList As List(Of String) = New List(Of String)
|
|
Public ReadOnly Property DocumentosRelacionadosUUIDSString As String
|
|
Get
|
|
Return GeneraStringDoctosRelacionados()
|
|
End Get
|
|
End Property
|
|
|
|
Public Property DocumentosRelacionadosAnticiposUUIDList As List(Of String) = New List(Of String)
|
|
Public Property TieneAnticiposXML As Boolean = False
|
|
Public Property EmisorRFC As String
|
|
Public Property ReceptorRFC As String
|
|
Public Property UUID As String = ""
|
|
Public Property TotalRetenciones As Decimal = 0D
|
|
Public Property RetencionIVA As Decimal = 0D
|
|
Public Property RetencionISR As Decimal = 0D
|
|
Public Property SumaTotalRetenciones As Decimal = 0D
|
|
Public Property TotalTraslados As Decimal = 0D
|
|
Public Property TrasladoIVA As Decimal = 0D
|
|
Public Property TrasladoIEPS As Decimal = 0D
|
|
Public Property SumaTotalTraslados As Decimal = 0D
|
|
Public Property OtrosImpuestos As Decimal = 0D
|
|
Private Property OtrosImpuestosRetenciones As Decimal = 0D
|
|
Public Property Amortizacion As Decimal = 0D
|
|
Public Property FechaPago As Date 'FIX ME corregir usando fecha interna calculada por los dias de credito del proveedor
|
|
Public Property AplicaNotaCredito As Boolean = False
|
|
Public Property XMlStr As String
|
|
Public Property XMLCargaExistosa As Boolean = True
|
|
Public Property Observaciones As String = ""
|
|
Public Property CveEstatusFactura As Integer = 1
|
|
Public Property CvePrePoliza As Integer = -1
|
|
Public Property Redondeo As Decimal = 0
|
|
Public Property IdPoliza As Integer = -1
|
|
Public Property CveCajaChica As Integer = -1
|
|
Public Property CvePersonal As Integer = -1
|
|
Public Property NumeroReembolso As String = ""
|
|
Public Property CveProveedorSucursal As Integer = -1
|
|
Public Property AplicoPromocion As Boolean = False
|
|
Public Property CveConceptoContableAlmacen As Integer = -1
|
|
Public Property NoDeducible As Integer = 0
|
|
Public Property CveTipoCompra As Integer = 1
|
|
Public Property TotalOriginal As Decimal = 0D
|
|
Public Property CveTipoConcepto As Integer = 1 'FIX ME Esto tiene que ver con el CveTipoProveedor 1 y 3 es CveTipoConcepto 1 y 2 es CveTipoConcepto 2
|
|
Public Property CveSubProyectoPrincipal As Integer = -1
|
|
Public Property CveFactura As Integer = -1
|
|
Public Property CveFolioGarantia As Integer = -1
|
|
Public Property TmpDT As DataTable = New DataTable
|
|
Public Property SubTotalConceptos As Decimal = 0D
|
|
|
|
Private Errores As StringBuilder = New StringBuilder
|
|
|
|
Public ReadOnly Property MensajeError As String
|
|
Get
|
|
Return Errores.ToString()
|
|
End Get
|
|
End Property
|
|
|
|
Public Property CompraSaldo As Decimal = 0D
|
|
Public Property SubTotalOriginal As Decimal = 0D
|
|
Public Property SubTotal2Original As Double = 0D
|
|
Public Property IVAOriginal As Decimal = 0D
|
|
Public Property RetIVAOriginal As Decimal = 0D
|
|
Public Property RetISROriginal As Decimal = 0D
|
|
Public Property Proyecto As String = ""
|
|
Public Property CveProyecto As Integer = -1
|
|
Public Property SubProyecto As String = ""
|
|
Public Property TipoCompra As EnumTipoCompra = EnumTipoCompra.Sin_definir
|
|
Private Property DTTiposGastos() As DataTable
|
|
Public Property CveTipoProveedor As Integer = -1
|
|
Public Property IEPSGasto As Boolean = False
|
|
Public Property OtrosImpuestosGasto As Boolean = False
|
|
Public Property OCVinculada As Boolean = False
|
|
Public Property NumNoDed As Integer = 0
|
|
Public Property CveTipoPoliza As Integer = -1
|
|
Public Property NombreProveedor As Object
|
|
Public Property CveCreditoDetalle As Integer = -1
|
|
Public Property CveIE As Integer = -1
|
|
Public Property CveCompraAmortizacion As Integer = -1
|
|
|
|
Public Sub New(XmlFuente As String, OpcionCarga As EnumCargaCompra, DTTiposGastos As DataTable, UsuarioActual As Usuario)
|
|
|
|
Errores = New StringBuilder
|
|
|
|
Me.DTTiposGastos = DTTiposGastos
|
|
Me.UsuarioActual = UsuarioActual
|
|
|
|
If OpcionCarga = EnumCargaCompra.DesdeArchivo Then
|
|
CargaDesdeArchivo(XmlFuente)
|
|
Else
|
|
CargaDesdeString(XmlFuente)
|
|
End If
|
|
|
|
End Sub
|
|
|
|
Private Sub CargaDesdeArchivo(XmlFuenteRuta As String)
|
|
|
|
Dim XMLDoc As New XmlDocument
|
|
|
|
If IO.File.Exists(XmlFuenteRuta) Then
|
|
XMlStr = File.ReadAllText(XmlFuenteRuta).Replace("<br>", "").Replace("<", "").Replace("o;?", "")
|
|
Try
|
|
XMLDoc.LoadXml(XMlStr)
|
|
XMLCargaExistosa = True
|
|
Catch ex As Exception
|
|
Try
|
|
Dim oReader As New StreamReader(XmlFuenteRuta, Encoding.GetEncoding("ISO-8859-1"))
|
|
XMLDoc.Load(oReader)
|
|
oReader.Dispose()
|
|
XMLCargaExistosa = True
|
|
Catch ex2 As Exception
|
|
GuardaLog("Error al intentar leer el XML del SAT. Error:" & ex2.ToString())
|
|
Errores.AppendLine("Error al intentar leer el XML. Error:" & ex2.ToString())
|
|
XMLCargaExistosa = False
|
|
End Try
|
|
End Try
|
|
End If
|
|
|
|
If XMLCargaExistosa Then
|
|
CargaComprobanteXML(XMLDoc)
|
|
End If
|
|
|
|
End Sub
|
|
Private Sub CargaDesdeString(XmlFuente As String)
|
|
XMlStr = XmlFuente.Replace("<br>", "").Replace("<", "").Replace("o;?", "")
|
|
Dim XMLDoc As New XmlDocument
|
|
Try
|
|
XMLDoc.LoadXml(XMlStr)
|
|
XMLCargaExistosa = True
|
|
Catch ex As Exception
|
|
GuardaLog("Error al intentar leer . Error:" & ex.ToString())
|
|
Errores.AppendLine("Error al intentar leer el XML. Error:" & ex.ToString())
|
|
XMLCargaExistosa = False
|
|
End Try
|
|
|
|
If XMLCargaExistosa Then
|
|
CargaComprobanteXML(XMLDoc)
|
|
End If
|
|
|
|
End Sub
|
|
|
|
Private Sub CargaComprobanteXML(XMLDoc As XmlDocument)
|
|
Dim nodo As XmlNode = XMLDoc.DocumentElement
|
|
|
|
Serie = ValorXML(nodo, "serie")
|
|
|
|
Dim StrCFDIVerion As String = ValorXML(nodo, "version")
|
|
|
|
If StrCFDIVerion = "3.2" Then
|
|
CFDIVersion = EnumCFDIVersion.v32
|
|
ElseIf StrCFDIVerion = "3.3" Then
|
|
CFDIVersion = EnumCFDIVersion.V33
|
|
ElseIf StrCFDIVerion = "4.0" Then
|
|
CFDIVersion = EnumCFDIVersion.V40
|
|
Else
|
|
GuardaLog($"CFDI Versión {StrCFDIVerion} no soportada")
|
|
Errores.AppendLine($"CFDI Versión {StrCFDIVerion} no soportada")
|
|
XMLCargaExistosa = False
|
|
Exit Sub
|
|
End If
|
|
|
|
Folio = ValorXML(nodo, "folio")
|
|
Fecha = ValorXML(nodo, "fecha").ToDate
|
|
SubTotal = ValorXML(nodo, "subTotal").ToDecimal
|
|
Total = ValorXML(nodo, "total").ToDecimal
|
|
Descuento = ValorXML(nodo, "descuento").ToDecimal
|
|
Moneda = ValorXML(nodo, "Moneda")
|
|
|
|
CveMoneda = GlobalDTMonedas().FiltroPrimeroValor("CveMoneda", $" AbreviaturaSAT = '{Moneda}' ").ToEntero
|
|
If Not CveMoneda > 0 Then
|
|
GuardaLog($"Moneda {Moneda} no se obtuvo la clabe")
|
|
Errores.AppendLine($"Moneda {Moneda} no se obtuvo la clabe")
|
|
XMLCargaExistosa = False
|
|
Exit Sub
|
|
End If
|
|
|
|
TipoComprobante = ValorXML(nodo, "tipoDeComprobante")
|
|
TipoCambio = ValorXML(nodo, "TipoCambio", "1").ToDecimal
|
|
|
|
If CFDIVersion = EnumCFDIVersion.V33 Or CFDIVersion = EnumCFDIVersion.V40 Then
|
|
Dim drm As DataRow = GlobalDTVtaMetodoPago.FiltroPrimero(String.Format("ClaveMetodoPagoSAT = '{0}'", ValorXML(nodo, "MetodoPago")))
|
|
If drm IsNot Nothing Then
|
|
CveMetodoPago = drm("CveMetodoPago").ToString.ToEntero
|
|
MetodoPago = drm("MetodoPagoSAT").ToString
|
|
End If
|
|
End If
|
|
|
|
Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable)
|
|
Dim Prefijo As String = If(XMLDoc.DocumentElement.Prefix = "", "cfd", XMLDoc.DocumentElement.Prefix)
|
|
Dim cfdVer As String = ""
|
|
|
|
If CFDIVersion = EnumCFDIVersion.v32 Then
|
|
Prefijo = "cfd"
|
|
cfdVer = "http://www.sat.gob.mx/cfd/2"
|
|
ElseIf CFDIVersion = EnumCFDIVersion.V33 Then
|
|
cfdVer = "http://www.sat.gob.mx/cfd/3"
|
|
Else ' se considera que es la version 4.0
|
|
cfdVer = "http://www.sat.gob.mx/cfd/4"
|
|
End If
|
|
namespaces.AddNamespace(Prefijo, cfdVer)
|
|
namespaces.AddNamespace("aerolineas", "http://www.sat.gob.mx/aerolineas")
|
|
namespaces.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital")
|
|
namespaces.AddNamespace("implocal", "http://www.sat.gob.mx/implocal")
|
|
namespaces.AddNamespace("registrofiscal", "http://www.sat.gob.mx/registrofiscal")
|
|
|
|
If TipoComprobante.ToUpper = "E" AndAlso (CFDIVersion = EnumCFDIVersion.V33 OrElse CFDIVersion = EnumCFDIVersion.V40) Then
|
|
Dim UUIDS As String = ""
|
|
|
|
Dim UUIDSLista As New List(Of String)
|
|
Dim nodeCFDIRelacionados As XmlNode
|
|
nodeCFDIRelacionados = XMLDoc.SelectSingleNode(String.Format("//{0}:CfdiRelacionados", Prefijo), namespaces)
|
|
|
|
If nodeCFDIRelacionados IsNot Nothing Then
|
|
For Each CFDIRelacionados As XmlNode In nodeCFDIRelacionados
|
|
UUIDSLista.Add("" & CFDIRelacionados.Attributes("UUID").Value.ToString & "")
|
|
Next
|
|
End If
|
|
DocumentosRelacionadosUUIDSList = UUIDSLista
|
|
|
|
End If
|
|
|
|
Dim node As XmlNode
|
|
node = XMLDoc.SelectSingleNode(String.Format("//{0}:Emisor", Prefijo), namespaces)
|
|
|
|
If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then
|
|
EmisorRFC = ValorXML(node, "RFC")
|
|
End If
|
|
|
|
node = XMLDoc.SelectSingleNode(String.Format("//{0}:Receptor", Prefijo), namespaces)
|
|
|
|
If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then
|
|
ReceptorRFC = ValorXML(node, "RFC")
|
|
End If
|
|
|
|
If UsuarioActual.CveEmpresa.Contiene(119, 7) Then
|
|
node = XMLDoc.SelectSingleNode(String.Format("//{0}:CfdiRelacionados", Prefijo), namespaces)
|
|
If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then
|
|
If ValorXML(node, "TipoRelacion").ToString.Contiene("07") Then
|
|
Dim nodeDocumentosRelacionados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:CfdiRelacionado", Prefijo), namespaces)
|
|
For Each documento As XmlNode In nodeDocumentosRelacionados
|
|
If documento.Attributes("UUID").Value <> "" Then
|
|
DocumentosRelacionadosAnticiposUUIDList.Add(documento.Attributes("UUID").Value)
|
|
End If
|
|
TieneAnticiposXML = True
|
|
Next
|
|
End If
|
|
End If
|
|
End If
|
|
|
|
node = XMLDoc.SelectSingleNode(String.Format("//{0}:Impuestos", Prefijo), namespaces)
|
|
If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then
|
|
Dim nodeRetenciones As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Comprobante/{0}:Impuestos/{0}:Retenciones/{0}:Retencion", Prefijo), namespaces)
|
|
|
|
TotalRetenciones = ValorXML(node, "totalImpuestosRetenidos", "0").ToDecimal
|
|
|
|
If CFDIVersion = EnumCFDIVersion.V33 OrElse CFDIVersion = EnumCFDIVersion.V40 Then
|
|
|
|
For Each retencion As XmlNode In nodeRetenciones
|
|
If retencion.Attributes("Impuesto").Value = "002" Then RetencionIVA += retencion.Attributes("Importe").Value.ToDecimal
|
|
If retencion.Attributes("Impuesto").Value = "001" Then RetencionISR += retencion.Attributes("Importe").Value.ToDecimal
|
|
Next
|
|
|
|
Else
|
|
|
|
For Each retencion As XmlNode In nodeRetenciones
|
|
If retencion.Attributes("impuesto").Value = "IVA" Then RetencionIVA += retencion.Attributes("importe").Value.ToDecimal
|
|
If retencion.Attributes("impuesto").Value = "ISR" Then RetencionISR += retencion.Attributes("importe").Value.ToDecimal
|
|
Next
|
|
End If
|
|
SumaTotalRetenciones += RetencionIVA
|
|
SumaTotalRetenciones += RetencionISR
|
|
|
|
TotalTraslados = ValorXML(node, "totalImpuestosTrasladados", "0").ToDecimal
|
|
Dim nodeTraslados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Comprobante/{0}:Impuestos/{0}:Traslados/{0}:Traslado", Prefijo), namespaces)
|
|
|
|
If CFDIVersion = EnumCFDIVersion.V33 OrElse CFDIVersion = EnumCFDIVersion.V40 Then
|
|
|
|
For Each traslado As XmlNode In nodeTraslados
|
|
|
|
If traslado.Attributes("Importe") IsNot Nothing Then
|
|
If traslado.Attributes("Impuesto").Value = "002" Then TrasladoIVA += traslado.Attributes("Importe").Value.ToDecimal
|
|
If traslado.Attributes("Impuesto").Value = "003" Then TrasladoIEPS += traslado.Attributes("Importe").Value.ToDecimal
|
|
End If
|
|
Next
|
|
Else
|
|
|
|
For Each traslado As XmlNode In nodeTraslados
|
|
If traslado.Attributes("Importe") IsNot Nothing Then
|
|
If traslado.Attributes("impuesto").Value = "IVA" Then TrasladoIVA += traslado.Attributes("importe").Value.ToDecimal
|
|
|
|
If traslado.Attributes("impuesto").Value = "IEPS" Then TrasladoIEPS += traslado.Attributes("importe").Value.ToDecimal
|
|
End If
|
|
Next
|
|
End If
|
|
|
|
SumaTotalTraslados += TrasladoIVA
|
|
SumaTotalTraslados += TrasladoIEPS
|
|
End If
|
|
|
|
Dim nodeComp As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Complemento", Prefijo), namespaces)
|
|
If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then
|
|
|
|
Dim nodeTFD As XmlNode = nodeComp.SelectSingleNode(String.Format("//{0}:TimbreFiscalDigital", "tfd"), namespaces)
|
|
|
|
UUID = ValorXML(nodeTFD, "UUID", "")
|
|
|
|
Dim nodeRF As XmlNode = nodeComp.SelectSingleNode(String.Format("//{0}:CFDIRegistroFiscal ", "registrofiscal"), namespaces)
|
|
If nodeRF IsNot Nothing Then
|
|
Folio = ValorXML(nodeRF, "folio").TrimStart("0"c)
|
|
End If
|
|
|
|
node = node.SelectSingleNode(String.Format("//{0}:ImpuestosLocales", "implocal"), namespaces)
|
|
|
|
If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then
|
|
OtrosImpuestos = ValorXML(node, "TotaldeTraslados", "0").ToDecimal
|
|
'2022.06.04-- se quitan los datos de retenciones de impuestos locales, generan conflicto. RMF
|
|
'OtrosImpuestosRetenciones = ValorXML(node, "TotaldeRetenciones", "0").ToDecimal
|
|
End If
|
|
End If
|
|
|
|
|
|
If XMLCargaExistosa Then
|
|
If Not ValidateUUID(UUID) Then
|
|
GuardaLog($"UUID Invalido {UUID} .")
|
|
Errores.AppendLine($"UUID Invalido {UUID} .")
|
|
XMLCargaExistosa = False
|
|
End If
|
|
End If
|
|
|
|
|
|
#Region "DETALLES"
|
|
|
|
Dim ObjeFacturas As New ClsCompras
|
|
Dim AjustaUltimoConcepto As Boolean = False
|
|
|
|
Dim nodeconceptos As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Conceptos", Prefijo), namespaces)
|
|
Dim XML As String = Replace(nodeconceptos.OuterXml, "<cfdi:", "<")
|
|
XML = XML.Replace("</cfdi:", "</")
|
|
XML = XML.Replace("xmlns:cfdi=""http://www.sat.gob.mx/cfd/3""", "")
|
|
XML = XML.Replace("xmlns:cfdi=""http://www.sat.gob.mx/cfd/4""", "")
|
|
XML = XML.Replace(""", "") 'comillas
|
|
XML = System.Web.HttpUtility.HtmlDecode(XML.ToString)
|
|
XML = XML.Replace(Chr(13), "") 'salto de linea
|
|
XML = XML.Replace(Chr(10), "")
|
|
XML = XML.Replace("<br />", "") 'salto de linea html
|
|
XML = XML.Replace("<br>", "")
|
|
XML = XML.Replace("<", "")
|
|
|
|
XML = XML.Replace("&", "") 'adicional, si hay otros
|
|
|
|
If ObjeFacturas.GetFacturasComparacionXML(StrCFDIVerion, XML, UsuarioActual.CveEmpresa) Then
|
|
TmpDT = ObjeFacturas.DtResultados
|
|
TmpDT.Columns.Add("CveSATPSActualizado")
|
|
SubTotalConceptos = TmpDT.SUMD("Total").RoundSQL
|
|
|
|
If Not TmpDT.Columns.Contains("Amortizacion") Then
|
|
TmpDT.Columns.Add("Amortizacion", GetType(Decimal))
|
|
End If
|
|
'VALIDA QUE EL XML SI VIENE CON EL CODIGO SAT 01010101
|
|
Dim ProductosCodigoSATNoPermitidos As New StringBuilder("")
|
|
For Each drr As DataRow In TmpDT.FiltraParametros("ClaveProdServ = '01010101'").Rows
|
|
ProductosCodigoSATNoPermitidos.AppendFormat("{0}</br>", drr("PS"))
|
|
Next
|
|
|
|
If ProductosCodigoSATNoPermitidos.ToString.Length > 0 Then
|
|
Errores.AppendLine($"El comprobante contiene productos con código SAT '01010101', revise los productos:</br></br>{ProductosCodigoSATNoPermitidos.ToString}")
|
|
|
|
End If
|
|
Else
|
|
GuardaLog($"Error al cargar detalles GetFacturasComparacionXML.")
|
|
Errores.AppendLine($"Error al cargar detalles GetFacturasComparacionXML.")
|
|
XMLCargaExistosa = False
|
|
End If
|
|
|
|
ObjeFacturas.Dispose()
|
|
|
|
If CFDIVersion = EnumCFDIVersion.V33 OrElse CFDIVersion = EnumCFDIVersion.V40 Then
|
|
If Not TmpDT.Columns.Contains("Amortizacion") Then
|
|
TmpDT.Columns.Add("Amortizacion", GetType(Decimal))
|
|
End If
|
|
TmpDT.AcceptChanges()
|
|
ValidacionesTotalesXml()
|
|
End If
|
|
|
|
Me.PorcentajeIVA = TmpDT.MAX("IVAPorcentaje").ToDecimal
|
|
|
|
#End Region
|
|
End Sub
|
|
|
|
Public Function ConfiguraRegistroRapidoReembolso(CvePS As Integer, CveSubProyecto As Integer, CveCajaChica As Integer, CvePersonal As Integer, CveRetIVAConcepto As Integer, CveRetISRConcepto As Integer, NumeroReembolso As String) As Boolean
|
|
|
|
Dim respuesta As Boolean = True
|
|
Me.CveSubProyecto = CveSubProyecto
|
|
Me.CveSubProyectoPrincipal = CveSubProyecto
|
|
Me.CveCajaChica = CveCajaChica
|
|
Me.CvePersonal = CvePersonal
|
|
Me.CveRetIVAConcepto = CveRetIVAConcepto
|
|
Me.CveRetISRConcepto = CveRetISRConcepto
|
|
Me.CveTipoPoliza = 3
|
|
Me.NumeroReembolso = NumeroReembolso
|
|
|
|
Dim dRowSubProyecto As DataRow = GlobalDTSubProyectos(UsuarioActual.CveEmpresa, CveSubProyecto:=CveSubProyecto).FiltroPrimero("")
|
|
|
|
If dRowSubProyecto IsNot Nothing Then
|
|
Me.Proyecto = dRowSubProyecto("Proyecto").ToString
|
|
Me.CveProyecto = (dRowSubProyecto("CveProyecto").ToString).ToEntero
|
|
Me.SubProyecto = dRowSubProyecto("SubProyecto").ToString
|
|
Else
|
|
Errores.AppendLine($"Error al cargar el Sub Proyecto CveSubProyecto: {CveSubProyecto}")
|
|
Return False
|
|
End If
|
|
|
|
Dim DTIndex As DataTable = TmpDT.FiltraParametros("", DistinctColumns:={"Consec"})
|
|
|
|
For Each dRowIndex As DataRow In DTIndex.Rows
|
|
If Not UpdatePSReembolso(dRowIndex("Consec").ToString.ToEntero, CvePS) Then
|
|
respuesta = False
|
|
End If
|
|
Next
|
|
|
|
If respuesta AndAlso IEPS > 0 Then
|
|
If Not AgregaIEPSReembolso(CvePS:=CvePS) Then
|
|
respuesta = False
|
|
Else
|
|
IEPS = 0
|
|
End If
|
|
End If
|
|
|
|
If Not AjustesValidacion() Then
|
|
respuesta = False
|
|
End If
|
|
|
|
Return respuesta
|
|
|
|
End Function
|
|
|
|
Private Function AjustesValidacion() As Boolean
|
|
Dim respuesta As Boolean = True
|
|
'VALIDA IMPORTES
|
|
If Not ValidaTotalesGuardar() Then
|
|
respuesta = False
|
|
End If
|
|
|
|
If Not AjustaCombustibles() Then
|
|
respuesta = False
|
|
End If
|
|
|
|
If Not AjustaIVA() Then
|
|
respuesta = False
|
|
End If
|
|
|
|
If Not AjustaRetIVA() Then
|
|
respuesta = False
|
|
End If
|
|
|
|
If Not AjustaRetISR() Then
|
|
respuesta = False
|
|
End If
|
|
|
|
Return respuesta
|
|
|
|
End Function
|
|
|
|
Private Function ValidaTotalesGuardar() As Boolean
|
|
Dim EsValido As Boolean = True
|
|
|
|
'VALIDA IMPORTES
|
|
'VALIDA TOTAL CON LOS IMPORTES TOTALES
|
|
Dim TempSubTotal, TempDescuentos, TempIVA, TempSubTotal2, TempRetIVA, TempRetISR, TempTotal, DifTotales, TempIEPS As Decimal
|
|
|
|
Dim Amortizacion As Decimal = 0
|
|
Dim TieneAmortizacion As Boolean = False
|
|
If DocumentosRelacionadosAnticiposUUIDList IsNot Nothing AndAlso DocumentosRelacionadosAnticiposUUIDList.Count > 0 Then 'Fix me
|
|
' AndAlso ArrAnticipos IsNot Nothing AndAlso ArrAnticipos.Count > 0 Then
|
|
'TieneAmortizacion = True
|
|
End If
|
|
|
|
'If CveCompra < 0 AndAlso Not TieneAmortizacion Then
|
|
' LblAmortizacion.Text = "0.00"
|
|
'End If
|
|
|
|
'If UsuarioActual.CveEmpresa = 119 AndAlso TieneAmortizacion Then
|
|
' Amortizacion = LblAmortizacion.Text.Trim.ToDecimal
|
|
' TxtSubTotal.Text = (TxtSubTotal.Text.ToDouble + Amortizacion).ToString
|
|
'End If
|
|
|
|
|
|
TempSubTotal = SubTotal
|
|
SubTotalOriginal = SubTotal
|
|
SubTotal2Original = SubTotal2
|
|
TempDescuentos = Descuento + Amortizacion
|
|
TempSubTotal2 = TempSubTotal - TempDescuentos
|
|
TempIVA = IVA
|
|
TempIEPS = IEPS
|
|
TempRetIVA = RetIVA
|
|
TempRetISR = RetISR
|
|
TempTotal = Math.Round(TempSubTotal2 + TempIVA + TempIEPS - TempRetIVA - TempRetISR + OtrosImpuestos - Amortizacion, 2)
|
|
DifTotales = Total - TempTotal
|
|
Dim DiferenciaPermitida As Decimal = 0.6D
|
|
|
|
If Math.Abs(DifTotales) > DiferenciaPermitida Then
|
|
Errores.AppendLine($"Los importes de los conceptos (Productos/Servicios) no cuadran con el total. Por favor verifique y vuelva a intentar.[{Math.Abs(DifTotales) - DiferenciaPermitida}]")
|
|
EsValido = False
|
|
ElseIf DifTotales <> 0 Then
|
|
SubTotal2 = (SubTotal2 + DifTotales)
|
|
SubTotal = (SubTotal + DifTotales)
|
|
SubTotalOriginal = SubTotal
|
|
SubTotal2Original = SubTotal2
|
|
End If
|
|
|
|
Dim DiferenciaSubtotales As Decimal = 0
|
|
If CveCompra > 0 Or CveFactura > 0 Or OCVinculada Then
|
|
|
|
If SubTotalOriginal = Nothing Then
|
|
SubTotalOriginal = 0
|
|
End If
|
|
|
|
If SubTotal2Original = Nothing Then
|
|
SubTotal2Original = 0
|
|
End If
|
|
|
|
DiferenciaSubtotales = SubTotal2Original.ToString.ToDecimal - TmpDT.SUM("Total").ToString.ToDecimal
|
|
'[IPP] PARCHE: Factura TELMEX para APH 12/ENERO/2018
|
|
If CveFactura = 286290 Then
|
|
DiferenciaSubtotales += Descuento
|
|
End If
|
|
If Math.Abs(DiferenciaSubtotales) > 1 And Not CompraNoDeducible = 1 Then 'EsNoDeducible
|
|
Errores.AppendLine("Los importes de los conceptos (Productos/Servicios) no cuadran con el total. Por favor verifique y vuelva a intentar.")
|
|
EsValido = False
|
|
Else
|
|
AjustaImporteUltimoConcepto(DiferenciaSubtotales)
|
|
End If
|
|
Else
|
|
DiferenciaSubtotales = (SubTotal2 - TmpDT.SUMD("Total")).ToString.ToDecimal
|
|
If Math.Abs(DiferenciaSubtotales) > 1 Then
|
|
Errores.AppendLine("Los importes de los conceptos (Productos/Servicios) no cuadran con el total. Por favor verifique y vuelva a intentar.")
|
|
EsValido = False
|
|
Else
|
|
AjustaImporteUltimoConcepto(DiferenciaSubtotales)
|
|
End If
|
|
End If
|
|
|
|
Return EsValido
|
|
End Function
|
|
|
|
|
|
|
|
Private Function AjustaCombustibles() As Boolean
|
|
|
|
Dim Respuesta As Boolean = False
|
|
|
|
Dim IVADetalles As Decimal = TmpDT.SUMD("IVA", " IVA > 0 ")
|
|
Dim DiferenciaIVas As Decimal = IVA - IVADetalles
|
|
|
|
|
|
If Not TmpDT.Columns.Contains("AplicaIEPS") Then
|
|
TmpDT.Columns.Add(New DataColumn("AplicaIEPS", GetType(Boolean)))
|
|
End If
|
|
|
|
If Not TmpDT.Columns.Contains("IEPSGrabaIVA") Then
|
|
TmpDT.Columns.Add(New DataColumn("IEPSGrabaIVA", GetType(Boolean)))
|
|
End If
|
|
|
|
For Each dRow As DataRow In TmpDT.Rows
|
|
Dim DttPS As DataTable = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=dRow("CvePS").ToString.ToEntero)
|
|
If DttPS IsNot Nothing AndAlso DttPS.Rows.Count > 0 Then
|
|
Dim DrPS As DataRow = DttPS.Rows(0)
|
|
dRow("AplicaIEPS") = Boolean.Parse(DrPS("AplicaIEPS").ToString)
|
|
dRow("IEPSGrabaIVA") = Boolean.Parse(DrPS("IEPSGrabaIVA").ToString)
|
|
Else
|
|
dRow("AplicaIEPS") = False
|
|
dRow("IEPSGrabaIVA") = False
|
|
End If
|
|
Next
|
|
|
|
Dim DTConsulta As New DataTable
|
|
DTConsulta = TmpDT.FiltraParametros(" AplicaIEPS = 'True' AND IEPSGrabaIVA = 'False' AND IVA > 0 ")
|
|
|
|
If DTConsulta.Rows.Count > 0 Then
|
|
|
|
Dim IndiceContador As Integer = 0
|
|
Dim IndiceUltimo As Integer = 0
|
|
Dim CantidadRegistroConIVA As Decimal
|
|
|
|
For Each dRow As DataRow In TmpDT.Rows
|
|
If Boolean.Parse(dRow("AplicaIEPS").ToString) And Boolean.Parse(dRow("IEPSGrabaIVA").ToString) = False And dRow("IVA").ToString.ToDecimal > 0 Then
|
|
IndiceUltimo = IndiceContador
|
|
CantidadRegistroConIVA = CantidadRegistroConIVA + 1
|
|
End If
|
|
IndiceContador = IndiceContador + 1
|
|
Next
|
|
|
|
IVADetalles = TmpDT.SUMD("IVA", " IVA > 0 ")
|
|
DiferenciaIVas = IVA - IVADetalles
|
|
|
|
If Math.Abs(DiferenciaIVas) > 0.01D Then
|
|
|
|
If (TmpDT.Rows(IndiceUltimo)("IVA").ToString.ToDecimal + DiferenciaIVas) < 0 Then
|
|
|
|
Dim AjusteteDividido As Decimal = Math.Abs(DiferenciaIVas) / CantidadRegistroConIVA
|
|
|
|
For Each dRow As DataRow In TmpDT.Rows
|
|
If Boolean.Parse(dRow("AplicaIEPS").ToString) And Boolean.Parse(dRow("IEPSGrabaIVA").ToString) = False And dRow("IVA").ToString.ToDecimal > 0 Then
|
|
dRow("IVA") = dRow("IVA").ToString.ToDecimal - AjusteteDividido
|
|
End If
|
|
Next
|
|
Else
|
|
TmpDT.Rows(IndiceUltimo)("IVA") = TmpDT.Rows(IndiceUltimo)("IVA").ToString.ToDecimal + DiferenciaIVas
|
|
End If
|
|
TmpDT.AcceptChanges()
|
|
End If
|
|
|
|
End If
|
|
|
|
'Revalidacion de ajuste
|
|
IVADetalles = TmpDT.SUMD("IVA", " IVA > 0 ")
|
|
DiferenciaIVas = IVA - IVADetalles
|
|
|
|
If Math.Abs(DiferenciaIVas) > 0.01D Then
|
|
Respuesta = False
|
|
If IVADetalles > 0 Then
|
|
|
|
For Each dRow As DataRow In TmpDT.Rows
|
|
If dRow("IVA").ToString.ToDecimal > 0 Then
|
|
dRow("IVA") = dRow("IVA").ToString.ToDecimal + DiferenciaIVas
|
|
TmpDT.AcceptChanges()
|
|
Respuesta = True
|
|
Exit For
|
|
End If
|
|
Next
|
|
Else
|
|
Alert("Los productos especificados en el listado no tienen asignado impuesto IVA, favor de realizar la corrección en el producto que aplique el impuesto.", TipoMensaje.MsgAdvertencia)
|
|
Respuesta = False
|
|
End If
|
|
Else
|
|
Respuesta = True
|
|
End If
|
|
|
|
If Respuesta Then
|
|
|
|
Dim IEPSPSDetalles As Decimal = TmpDT.SUMD("IEPSPS", " IEPSPS > 0 ")
|
|
Dim DiferenciaIEPSPS As Decimal = IEPS - IEPSPSDetalles
|
|
|
|
Dim DTConsultaIEPSPS As New DataTable
|
|
DTConsultaIEPSPS = TmpDT.FiltraParametros(" AplicaIEPS = 'True'")
|
|
Dim IndiceContador As Integer = 0
|
|
Dim IndicePrimero As Integer = 0
|
|
|
|
For Each dRow As DataRow In TmpDT.Rows
|
|
If Boolean.Parse(dRow("AplicaIEPS").ToString) And dRow("IEPSPS").ToString.ToDecimal > 0 Then
|
|
IndicePrimero = IndiceContador
|
|
Exit For
|
|
End If
|
|
IndiceContador = IndiceContador + 1
|
|
Next
|
|
If DiferenciaIEPSPS.RoundSQL(2) <> 0 Then
|
|
|
|
TmpDT.Rows(IndicePrimero)("IEPSPS") = TmpDT.Rows(IndicePrimero)("IEPSPS").ToString.ToDecimal + DiferenciaIEPSPS
|
|
TmpDT.AcceptChanges()
|
|
End If
|
|
|
|
For Each dRow As DataRow In TmpDT.Rows
|
|
If dRow("IEPSPSPorcentaje").ToString.ToDecimal > 0 AndAlso dRow("IEPSPS").ToString.ToDecimal = 0 Then
|
|
dRow("IEPSPSPorcentaje") = 0
|
|
End If
|
|
Next
|
|
TmpDT.AcceptChanges()
|
|
End If
|
|
|
|
Return Respuesta
|
|
|
|
End Function
|
|
|
|
|
|
Private Function AjustaIVA() As Boolean
|
|
|
|
Dim Respuesta As Boolean = False
|
|
|
|
Dim IVADetalles As Decimal = TmpDT.SUMD("IVA", " IVA > 0 ")
|
|
Dim DiferenciaIVas As Decimal = IVA - IVADetalles
|
|
|
|
If Math.Abs(DiferenciaIVas) > 0 Then
|
|
If Math.Abs(DiferenciaIVas) <= 0.05 Then
|
|
|
|
Dim DTConsulta As New DataTable
|
|
DTConsulta = TmpDT.FiltraParametros(" IVA > 0 ")
|
|
|
|
If DTConsulta.Rows.Count > 0 Then
|
|
|
|
Dim IndiceContador As Integer = 0
|
|
Dim IndiceUltimo As Integer = 0
|
|
Dim CantidadRegistroConIVA As Decimal
|
|
|
|
For Each dRow As DataRow In TmpDT.Rows
|
|
If dRow("IVA").ToString.ToDecimal > 0 Then
|
|
IndiceUltimo = IndiceContador
|
|
CantidadRegistroConIVA = CantidadRegistroConIVA + 1
|
|
End If
|
|
IndiceContador = IndiceContador + 1
|
|
Next
|
|
|
|
IVADetalles = TmpDT.SUMD("IVA", " IVA > 0 ")
|
|
DiferenciaIVas = IVA - IVADetalles
|
|
|
|
If Math.Abs(DiferenciaIVas) > 0.0D Then
|
|
|
|
If (TmpDT.Rows(IndiceUltimo)("IVA").ToString.ToDecimal + DiferenciaIVas) < 0 Then
|
|
|
|
Dim AjusteteDividido As Decimal = Math.Abs(DiferenciaIVas) / CantidadRegistroConIVA
|
|
|
|
For Each dRow As DataRow In TmpDT.Rows
|
|
dRow("IVA") = dRow("IVA").ToString.ToDecimal - AjusteteDividido
|
|
Next
|
|
Else
|
|
TmpDT.Rows(IndiceUltimo)("IVA") = TmpDT.Rows(IndiceUltimo)("IVA").ToString.ToDecimal + DiferenciaIVas
|
|
End If
|
|
TmpDT.AcceptChanges()
|
|
End If
|
|
End If
|
|
|
|
'Revalidacion de ajuste
|
|
IVADetalles = TmpDT.SUMD("IVA", " IVA > 0 ")
|
|
DiferenciaIVas = IVA - IVADetalles
|
|
|
|
If Math.Abs(DiferenciaIVas) > 0.01D Then
|
|
Respuesta = False
|
|
If IVADetalles > 0 Then
|
|
|
|
For Each dRow As DataRow In TmpDT.Rows
|
|
If dRow("IVA").ToString.ToDecimal > 0 Then
|
|
dRow("IVA") = dRow("IVA").ToString.ToDecimal + DiferenciaIVas
|
|
TmpDT.AcceptChanges()
|
|
Respuesta = True
|
|
Exit For
|
|
End If
|
|
Next
|
|
|
|
Else
|
|
Errores.AppendLine("Los productos especificados en el listado no tienen asignado impuesto IVA, favor de realizar la corrección en el producto que aplique el impuesto.")
|
|
Respuesta = False
|
|
End If
|
|
Else
|
|
Respuesta = True
|
|
End If
|
|
|
|
Else
|
|
Errores.AppendLine($"existe una diferencia de {DiferenciaIVas} entre el IVA de la compra y los detalles.")
|
|
Respuesta = False
|
|
End If
|
|
Else
|
|
Respuesta = True
|
|
End If
|
|
|
|
Return Respuesta
|
|
|
|
End Function
|
|
|
|
Private Function AjustaRetIVA() As Boolean
|
|
|
|
Dim Respuesta As Boolean = False
|
|
|
|
Dim RetIVADetalles As Decimal = TmpDT.SUMD("RetIVA", " RetIVA > 0 ")
|
|
Dim DiferenciaRetIVA As Decimal = RetIVA - RetIVADetalles
|
|
|
|
If Math.Abs(DiferenciaRetIVA) > 0 Then
|
|
If Math.Abs(DiferenciaRetIVA) <= 0.05 Then
|
|
|
|
Dim DTConsulta As New DataTable
|
|
DTConsulta = TmpDT.FiltraParametros(" RetIVA > 0 ")
|
|
|
|
If DTConsulta.Rows.Count > 0 Then
|
|
|
|
Dim IndiceContador As Integer = 0
|
|
Dim IndiceUltimo As Integer = 0
|
|
Dim CantidadRegistroConRetIVA As Decimal
|
|
|
|
For Each dRow As DataRow In TmpDT.Rows
|
|
If dRow("RetIVA").ToString.ToDecimal > 0 Then
|
|
IndiceUltimo = IndiceContador
|
|
CantidadRegistroConRetIVA = CantidadRegistroConRetIVA + 1
|
|
End If
|
|
IndiceContador = IndiceContador + 1
|
|
Next
|
|
|
|
RetIVADetalles = TmpDT.SUMD("RetIVA", " RetIVA > 0 ")
|
|
DiferenciaRetIVA = RetIVA - RetIVADetalles
|
|
|
|
If Math.Abs(DiferenciaRetIVA) > 0.0D Then
|
|
|
|
If (TmpDT.Rows(IndiceUltimo)("RetIVA").ToString.ToDecimal + DiferenciaRetIVA) < 0 Then
|
|
|
|
Dim AjusteteDividido As Decimal = Math.Abs(DiferenciaRetIVA) / CantidadRegistroConRetIVA
|
|
|
|
For Each dRow As DataRow In TmpDT.Rows
|
|
dRow("RetIVA") = dRow("RetIVA").ToString.ToDecimal - AjusteteDividido
|
|
Next
|
|
|
|
Else
|
|
TmpDT.Rows(IndiceUltimo)("RetIVA") = TmpDT.Rows(IndiceUltimo)("RetIVA").ToString.ToDecimal + DiferenciaRetIVA
|
|
End If
|
|
|
|
TmpDT.AcceptChanges()
|
|
|
|
End If
|
|
|
|
End If
|
|
|
|
'Revalidacion de ajuste
|
|
RetIVADetalles = TmpDT.SUMD("RetIVA", " RetIVA > 0 ")
|
|
DiferenciaRetIVA = RetIVA - RetIVADetalles
|
|
|
|
If Math.Abs(DiferenciaRetIVA) > 0.01D Then
|
|
Respuesta = False
|
|
If RetIVADetalles > 0 Then
|
|
|
|
For Each dRow As DataRow In TmpDT.Rows
|
|
If dRow("RetIVA").ToString.ToDecimal > 0 Then
|
|
dRow("RetIVA") = dRow("RetIVA").ToString.ToDecimal + DiferenciaRetIVA
|
|
TmpDT.AcceptChanges()
|
|
Respuesta = True
|
|
Exit For
|
|
End If
|
|
Next
|
|
|
|
Else
|
|
Errores.AppendLine("Los productos especificados en el listado no tienen asignado impuesto RetIVA, favor de realizar la corrección en el producto que aplique el impuesto.")
|
|
Respuesta = False
|
|
End If
|
|
Else
|
|
Respuesta = True
|
|
End If
|
|
|
|
Else
|
|
Errores.AppendLine($"existe una diferencia de {DiferenciaRetIVA} entre el RetIVA de la compra y los detalles.")
|
|
End If
|
|
Else
|
|
Respuesta = True
|
|
|
|
End If
|
|
|
|
Return Respuesta
|
|
|
|
End Function
|
|
|
|
Private Function AjustaRetISR() As Boolean
|
|
|
|
Dim Respuesta As Boolean = False
|
|
|
|
Dim RetISRDetalles As Decimal = TmpDT.SUMD("RetISR", " RetISR > 0 ")
|
|
Dim DiferenciaRetISR As Decimal = RetISR - RetISRDetalles
|
|
|
|
If Math.Abs(DiferenciaRetISR) > 0 Then
|
|
If Math.Abs(DiferenciaRetISR) <= 0.05 Then
|
|
|
|
Dim DTConsulta As New DataTable
|
|
DTConsulta = TmpDT.FiltraParametros(" RetISR > 0 ")
|
|
|
|
If DTConsulta.Rows.Count > 0 Then
|
|
|
|
Dim IndiceContador As Integer = 0
|
|
Dim IndiceUltimo As Integer = 0
|
|
Dim CantidadRegistroConRetISR As Decimal
|
|
|
|
For Each dRow As DataRow In TmpDT.Rows
|
|
If dRow("RetISR").ToString.ToDecimal > 0 Then
|
|
IndiceUltimo = IndiceContador
|
|
CantidadRegistroConRetISR = CantidadRegistroConRetISR + 1
|
|
End If
|
|
IndiceContador = IndiceContador + 1
|
|
Next
|
|
|
|
RetISRDetalles = TmpDT.SUMD("RetISR", " RetISR > 0 ")
|
|
DiferenciaRetISR = RetISR - RetISRDetalles
|
|
|
|
If Math.Abs(DiferenciaRetISR) > 0.0D Then
|
|
|
|
If (TmpDT.Rows(IndiceUltimo)("RetISR").ToString.ToDecimal + DiferenciaRetISR) < 0 Then
|
|
|
|
Dim AjusteteDividido As Decimal = Math.Abs(DiferenciaRetISR) / CantidadRegistroConRetISR
|
|
|
|
For Each dRow As DataRow In TmpDT.Rows
|
|
dRow("RetISR") = dRow("RetISR").ToString.ToDecimal - AjusteteDividido
|
|
Next
|
|
|
|
Else
|
|
TmpDT.Rows(IndiceUltimo)("RetISR") = TmpDT.Rows(IndiceUltimo)("RetISR").ToString.ToDecimal + DiferenciaRetISR
|
|
End If
|
|
|
|
TmpDT.AcceptChanges()
|
|
|
|
End If
|
|
|
|
End If
|
|
|
|
'Revalidacion de ajuste
|
|
RetISRDetalles = TmpDT.SUMD("RetISR", " RetISR > 0 ")
|
|
DiferenciaRetISR = RetISR - RetISRDetalles
|
|
|
|
If Math.Abs(DiferenciaRetISR) > 0.01D Then
|
|
Respuesta = False
|
|
If RetISRDetalles > 0 Then
|
|
|
|
For Each dRow As DataRow In TmpDT.Rows
|
|
If dRow("RetISR").ToString.ToDecimal > 0 Then
|
|
dRow("RetISR") = dRow("RetISR").ToString.ToDecimal + DiferenciaRetISR
|
|
TmpDT.AcceptChanges()
|
|
Respuesta = True
|
|
Exit For
|
|
End If
|
|
Next
|
|
|
|
Else
|
|
Errores.AppendLine("Los productos especificados en el listado no tienen asignado impuesto RetISR, favor de realizar la corrección en el producto que aplique el impuesto.")
|
|
Respuesta = False
|
|
End If
|
|
Else
|
|
Respuesta = True
|
|
End If
|
|
|
|
Else
|
|
Errores.AppendLine($"existe una diferencia de {DiferenciaRetISR} entre el RetISR de la compra y los detalles.")
|
|
Respuesta = False
|
|
End If
|
|
Else
|
|
Respuesta = True
|
|
End If
|
|
|
|
Return Respuesta
|
|
|
|
End Function
|
|
|
|
Private Function AgregaIEPSReembolso(CvePS As Integer) As Boolean
|
|
|
|
Dim respuesta As Boolean = True
|
|
|
|
If IEPSGasto Or OtrosImpuestosGasto Then
|
|
|
|
'AGREGA IEPS COMO CONCEPTO
|
|
If IEPSGasto Then
|
|
AgregarConceptoIEPS(TrasladoIEPS, CvePS)
|
|
For Each Dr As DataRow In TmpDT.Rows
|
|
Dr("IEPSPS") = 0
|
|
Dr("IEPSPSPorcentaje") = 0
|
|
Next
|
|
TmpDT.AcceptChanges()
|
|
End If
|
|
'AGREGA OTROS IMPUESTOS COMO CONCEPTO
|
|
If OtrosImpuestosGasto Then
|
|
AgregarConceptoIEPS(OtrosImpuestos, CvePS)
|
|
End If
|
|
Else
|
|
respuesta = False
|
|
Errores.AppendLine("Debe seleccionar al menos un impuesto. ")
|
|
End If
|
|
CalculaTotales()
|
|
|
|
Return respuesta
|
|
|
|
End Function
|
|
|
|
|
|
Private Sub AgregarConceptoIEPS(IEPS As Decimal, CvePS1 As Integer)
|
|
Dim SubTotalR As Decimal = TmpDT.SUM("Total").ToString.ToDecimal
|
|
|
|
Dim PSS As DataTable = GlobalDTPS(UsuarioActual.CveEmpresa).FiltraParametros(String.Format("CvePS = {0} ", CvePS1), "PS")
|
|
Dim PSS2 As DataTable = TmpDT.FiltraParametros(String.Format("CvePS = {0} ", CvePS1), "PS")
|
|
|
|
If PSS.Rows.Count > 0 Or PSS2.Rows.Count > 0 Then
|
|
Dim CveUM As Integer = 0
|
|
Dim UM As String = ""
|
|
Dim CveClasificacion As Integer = 0
|
|
Dim Clasificacion As String = ""
|
|
Dim CvePS As Integer = 0
|
|
Dim PS As String = ""
|
|
Dim CveTipoPS As Integer = 0
|
|
|
|
If PSS.Rows.Count > 0 Then
|
|
CveUM = PSS.Rows(0)("CveUM").ToString.ToEntero
|
|
UM = PSS.Rows(0)("UnidadMedida").ToString
|
|
CveClasificacion = PSS.Rows(0)("CveClasificacion").ToString.ToEntero
|
|
Clasificacion = PSS.Rows(0)("Clasificacion").ToString
|
|
CvePS = PSS.Rows(0)("CvePS").ToString.ToEntero
|
|
PS = PSS.Rows(0)("PS").ToString
|
|
CveTipoPS = PSS.Rows(0)("CveTipoPS").ToString.ToEntero
|
|
End If
|
|
|
|
Dim Cantidad As Decimal = 1
|
|
Dim CveSubProyectoContrato As String = "-1"
|
|
Dim CveProyecto As String = "-1"
|
|
Dim SubProyecto As String = "SE"
|
|
Dim Proyecto As String = "SE"
|
|
Dim Obs As String = ""
|
|
Dim PU As Decimal = IEPS
|
|
Dim Total As Decimal = Cantidad * PU
|
|
Dim IVA As Decimal = 0
|
|
Dim Descuento As Decimal = 0
|
|
|
|
If PSS2.Rows.Count > 0 Then
|
|
CveUM = PSS2.Rows(0)("CveUM").ToString.ToEntero
|
|
UM = PSS2.Rows(0)("UM").ToString
|
|
CveClasificacion = PSS2.Rows(0)("CveClasificacion").ToString.ToEntero
|
|
Clasificacion = PSS2.Rows(0)("Clasificacion").ToString
|
|
CvePS = PSS2.Rows(0)("CvePS").ToString.ToEntero
|
|
PS = PSS2.Rows(0)("PS").ToString
|
|
CveTipoPS = PSS2.Rows(0)("CveTipoPS").ToString.ToEntero
|
|
|
|
CveSubProyectoContrato = PSS2.Rows(0)("CveSubProyecto").ToString
|
|
CveProyecto = PSS2.Rows(0)("CveProyecto").ToString
|
|
SubProyecto = PSS2.Rows(0)("SubProyecto").ToString
|
|
Proyecto = PSS2.Rows(0)("Proyecto").ToString
|
|
Obs = PSS2.Rows(0)("Obs").ToString
|
|
|
|
Dim CveTipoGasto As Integer = PSS2.Rows(0)("CveTipoGasto").ToString.ToEntero
|
|
Dim TipoGasto As String = PSS2.Rows(0)("TipoGasto").ToString
|
|
|
|
AddPS(Cantidad, CveUM, UM, CveClasificacion, Clasificacion, CvePS, PS, CveTipoPS, CveSubProyectoContrato, SubProyecto, Proyecto, CveProyecto, Obs, PU, Total, IVA, 0, 0, 0, 0, Descuento, TCalculaTotales:=False, CveTipoGasto:=CveTipoGasto,
|
|
TipoGasto:=TipoGasto, ModalidadAccionPS:=EnumModalidadAccionPS.Agregar)
|
|
|
|
Else
|
|
AddPS(Cantidad, CveUM, UM, CveClasificacion, Clasificacion, CvePS, PS, CveTipoPS, CveSubProyectoContrato, SubProyecto, Proyecto, CveProyecto, Obs, PU, Total, IVA, 0, 0, 0, 0, Descuento, TCalculaTotales:=False)
|
|
End If
|
|
End If
|
|
|
|
Dim SubTotalIEPS As Decimal = TmpDT.SUMD("Total")
|
|
|
|
Me.SubTotal = Math.Round(SubTotalIEPS, 2)
|
|
Me.SubTotalConceptos = Math.Round(SubTotalIEPS, 2)
|
|
|
|
PSS.Dispose()
|
|
End Sub
|
|
|
|
Private Function AddPS(Cantidad As Decimal, CveUM As Integer, UM As String, CveClasificacion As Integer, Clasificacion As String, CvePS As Integer, PS As String, CveTipoPS As Integer, CveSubProyectoContrato As String, SubProyecto As String, Proyecto As String, CveProyecto As String,
|
|
Obs As String, PU As Decimal, Total As Decimal, IVA As Decimal, RetIVA As Decimal, RetISR As Decimal, IEPSPS As Decimal, IEPSPSIVA As Decimal, Descuento As Decimal, Optional CveOrdenCompraDetalle As Integer = -1, Optional TCalculaTotales As Boolean = True,
|
|
Optional PSCodigo As String = "-", Optional PSDescripcion As String = "-", Optional CantidadF As Double = -1, Optional EntregaDirecta As Integer = -1, Optional OtrosGastos As Decimal = 0,
|
|
Optional CveSATPS As Integer = -1, Optional CargaXml As Boolean = False, Optional CveTipoGasto As Integer = -1, Optional TipoGasto As String = "", Optional PorcentajeIVA As Decimal = 0,
|
|
Optional PorcentajeIEPS As Decimal = 0, Optional PorcentajeRetIVA As Decimal = 0, Optional PorcentajeRetISR As Decimal = 0, Optional NoDeducible As Boolean = False, Optional CveContratoDetalle As Integer = -1, Optional CveCultivoCuadroDetalle As Integer = -1,
|
|
Optional CveSATPSActualizado As Boolean = False, Optional TemporadaCuadro As String = "", Optional ModalidadAccionPS As EnumModalidadAccionPS = EnumModalidadAccionPS.Agregar, Optional Con As Integer = -1,
|
|
Optional CveProgramaOperativo As Integer = -1, Optional CveUnidadAdministrativa As Integer = -1, Optional CveFuenteFinanciamiento As Integer = -1, Optional CveTipoGastoAC As Integer = -1, Optional CveClasificacionOG As Integer = -1) As Integer
|
|
|
|
Dim Row As DataRow = Nothing
|
|
|
|
Row = TmpDT.NewRow()
|
|
Dim Retorno As Integer = 0
|
|
Dim CveContrato As Integer = -1
|
|
Dim CveSubProyecto As Integer = -1
|
|
Dim Valores As String()
|
|
|
|
''CONTRATOS
|
|
If CveSubProyectoContrato.Contains("|"c) Then
|
|
Valores = CveSubProyectoContrato.Split("|"c)
|
|
CveContrato = Valores(1).ToEntero
|
|
CveSubProyecto = Valores(0).ToEntero
|
|
Else
|
|
CveSubProyecto = CveSubProyectoContrato.ToEntero
|
|
End If
|
|
|
|
'DR PS
|
|
Dim DrPS As DataRow = Nothing
|
|
If CvePS > 0 Then
|
|
DrPS = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).Rows(0)
|
|
End If
|
|
|
|
If DrPS IsNot Nothing Then
|
|
Row("PSCodigo") = If(PSCodigo = "", DrPS("PSCodigo").ToString, PSCodigo)
|
|
Row("CveMetodoInventario") = DrPS("Inv_CveMetodoInventario").ToString.ToEntero
|
|
|
|
If CveTipoCompra = EnumTipoCompra.Garantia AndAlso DrPS("AplicaSerie").ToString = "True" Then
|
|
Row("CveMetodoInventario") = "1"
|
|
End If
|
|
|
|
Else
|
|
Row("PSCodigo") = PSCodigo
|
|
Row("CveMetodoInventario") = 0
|
|
End If
|
|
|
|
If ModalidadAccionPS = EnumModalidadAccionPS.Actualizar Then
|
|
Row("Consec") = Con
|
|
Else
|
|
Row("Consec") = TmpDT.Rows.Count + 1
|
|
End If
|
|
|
|
If (CFDIVersion = EnumCFDIVersion.V33 Or CFDIVersion = EnumCFDIVersion.V40) And CveSATPS > 0 Then
|
|
Dim DrPSSAT As DataRow = Nothing
|
|
If CargaXml Then
|
|
DrPSSAT = GlobalDTPSATPS("-1", CveSATPS.ToString).FiltroPrimero("")
|
|
Else
|
|
DrPSSAT = GlobalDTPSATPS("-1", CveSATPS.ToString).FiltroPrimero("")
|
|
End If
|
|
If DrPSSAT IsNot Nothing Then
|
|
Row("SATClaveProductoServicio") = DrPSSAT("SATClaveProductoServicio").ToString
|
|
Row("CveSATPS") = DrPSSAT("CveSATPS").ToString
|
|
If CveSATPSActualizado Then
|
|
Row("CveSATPSActualizado") = 1
|
|
Else
|
|
Row("CveSATPSActualizado") = 0
|
|
End If
|
|
End If
|
|
End If
|
|
|
|
Try
|
|
If (DrPS("CvePSCargo").ToString <> "") Then 'si es un producto de usado. que se registre contablemente como alamcen(como producto)
|
|
CveTipoPS = 2
|
|
End If
|
|
Catch ex As Exception
|
|
|
|
End Try
|
|
|
|
Dim DecimalesPermitidos As Integer = 6
|
|
|
|
Row("CveConcepto") = TmpDT.Rows.Count + 1
|
|
Row("Cantidad") = Math.Round(Cantidad, DecimalesPermitidos)
|
|
Row("CantidadF") = If(CantidadF = -1, Math.Round(Cantidad, DecimalesPermitidos), Math.Round(CantidadF, DecimalesPermitidos))
|
|
Row("CveUM") = CveUM
|
|
Row("UM") = UM
|
|
Row("CveClasificacion") = CveClasificacion
|
|
Row("CveClasificacionActualizar") = CveClasificacion
|
|
Row("Clasificacion") = Clasificacion
|
|
Row("CvePS") = CvePS
|
|
Row("PS") = PS
|
|
Row("CveTipoPS") = CveTipoPS
|
|
|
|
Row("PSDescripcion") = PSDescripcion
|
|
Row("CveSubProyecto") = CveSubProyecto.ToEntero
|
|
Row("CveProyecto") = CveProyecto.ToEntero
|
|
Row("CveContrato") = CveContrato.ToEntero
|
|
Row("SubProyecto") = If(SubProyecto = "Seleccione", "Sin Sub Proyecto", SubProyecto)
|
|
Row("Proyecto") = If(Proyecto = "Seleccione", "Sin Proyecto", Proyecto)
|
|
Row("CveActivoFijo") = -1
|
|
Row("Obs") = Obs
|
|
Row("CveActivoFijo") = -1
|
|
Row("CodAF") = "-1"
|
|
Row("TipoAF") = -1
|
|
Row("CveOrdenCompraDetalle") = CveOrdenCompraDetalle
|
|
Row("EntregaDirecta") = EntregaDirecta
|
|
|
|
Row("NoDeducible") = NoDeducible
|
|
|
|
|
|
Total = Math.Round(PU, DecimalesPermitidos) * Cantidad - Descuento
|
|
Row("PU") = Math.Round(PU, DecimalesPermitidos)
|
|
If CargaXml And (CFDIVersion = EnumCFDIVersion.V33 Or CFDIVersion = EnumCFDIVersion.V40) Then
|
|
|
|
If CveFactura > 0 And IVA = 0 Then
|
|
Row("IVA") = 0
|
|
Row("IVAPorcentaje") = 0
|
|
Else
|
|
Row("IVA") = Math.Round(IVA, DecimalesPermitidos)
|
|
Row("IVAPorcentaje") = PorcentajeIVA
|
|
End If
|
|
|
|
Row("RetIVA") = Math.Round(RetIVA, DecimalesPermitidos)
|
|
Row("RetIVAPorcentaje") = PorcentajeRetIVA
|
|
Row("RetISR") = Math.Round(RetISR, DecimalesPermitidos)
|
|
Row("RetISRPorcentaje") = PorcentajeRetISR
|
|
Row("IEPSPS") = Math.Round(IEPSPS, DecimalesPermitidos)
|
|
Row("IEPSPSPorcentaje") = PorcentajeIEPS
|
|
Else
|
|
'If DdlIVA.SelectedValue.ToDouble = 0 Then Row("IVA") = 0 Else Row("IVA") = Math.Round(IVA * Total, DecimalesPermitidos)
|
|
|
|
If CveFactura > 0 And IVA = 0 Then
|
|
Row("IVA") = 0
|
|
Row("IVAPorcentaje") = 0
|
|
Else
|
|
Row("IVA") = (IVA * Total).RoundSQL
|
|
Row("IVAPorcentaje") = IVA
|
|
End If
|
|
|
|
Row("RetIVA") = (RetIVA * Total).RoundSQL
|
|
Row("RetIVAPorcentaje") = RetIVA
|
|
Row("RetISR") = (RetISR * Total).RoundSQL
|
|
Row("RetISRPorcentaje") = RetISR
|
|
Row("IEPSPS") = (IEPSPS * Total).RoundSQL
|
|
Row("IEPSPSPorcentaje") = IEPSPS
|
|
End If
|
|
|
|
Row("ImporteConImpuestos") = (Row("Cantidad").ToString.ToDecimal * Row("PU").ToString.ToDecimal) + Row("IVA").ToString.ToDecimal + Row("IEPSPS").ToString.ToDecimal - (Row("RetIVA").ToString.ToDecimal + Row("RetISR").ToString.ToDecimal)
|
|
Row("ImporteSinImpuestos") = Row("Cantidad").ToString.ToDecimal * Row("PU").ToString.ToDecimal
|
|
|
|
Row("IEPSPSIVA") = Math.Round(IEPSPSIVA * Total, DecimalesPermitidos)
|
|
Row("IEPSPSIVAPorcentaje") = IEPSPSIVA
|
|
Row("Descuento") = Math.Round(Descuento, DecimalesPermitidos)
|
|
Row("OtrosGastos") = Math.Round(OtrosGastos, DecimalesPermitidos)
|
|
Row("Total") = Math.Round(Total, DecimalesPermitidos)
|
|
|
|
Row("CveTipoGasto") = CveTipoGasto
|
|
Row("TipoGasto") = If(CveTipoGasto > 0, TipoGasto, "")
|
|
|
|
Row("CveContratoDetalle") = CveContratoDetalle
|
|
|
|
Row("CveCultivoCuadroDetalle") = CveCultivoCuadroDetalle
|
|
Row("TemporadaCuadro") = TemporadaCuadro
|
|
|
|
If UsuarioActual.Empresa.UsaAC Then
|
|
Row("CveProgramaOperativo") = CveProgramaOperativo
|
|
Row("CveUnidadAdministrativa") = CveUnidadAdministrativa
|
|
Row("CveFuenteFinanciamiento") = CveFuenteFinanciamiento
|
|
Row("CveTipoGastoAC") = CveTipoGastoAC
|
|
Row("CveClasificacionOG") = CveClasificacionOG
|
|
End If
|
|
'Esta parte es para validar cuando la factura tenga ieps en o se asignara el ieps como una partida ya no se considere
|
|
If (CveFactura > 0 Or CveCompra > 0) And IEPS = 0 Then
|
|
Row("IEPSPS") = 0
|
|
Row("IEPSPSPorcentaje") = 0
|
|
End If
|
|
TmpDT.Rows.Add(Row)
|
|
TmpDT.Rows.IndexOf(Row)
|
|
|
|
If TCalculaTotales Then
|
|
CalculaTotales(True)
|
|
End If
|
|
|
|
Return Retorno
|
|
End Function
|
|
|
|
Private Sub CalculaTotales(Optional CalculaIVA As Boolean = False, Optional EsNoDeducible As Boolean = False)
|
|
'VARIABLES DE CALCULO
|
|
Dim LocalSubTotal, LocalDescuentos, LocalAmortizacion, LocalIVA, LocalSubTotal2, LocalRetIVA, LocalRetISR, LocalIEPSPS, LocalTotal, LocalSubTotalIVA, LocalSubTotalIEPSIVA As Decimal
|
|
|
|
'HACEMOS CALCULOS
|
|
LocalSubTotalIVA = TmpDT.SUMD("IVA")
|
|
LocalSubTotalIEPSIVA = TmpDT.SUMD("IEPSPSIVA")
|
|
LocalSubTotal = (TmpDT.SUMD("Total") + TmpDT.SUMD("Descuento")).RoundSQL(8)
|
|
LocalRetIVA = TmpDT.SUMD("RetIVA")
|
|
LocalRetISR = TmpDT.SUMD("RetISR")
|
|
LocalIEPSPS = TmpDT.SUMD("IEPSPS")
|
|
|
|
If CveCompra > 0 AndAlso CveFactura > 0 Then
|
|
LocalIVA = IVA
|
|
Else
|
|
LocalIVA = If(TmpDT.SUM("IVA") > 0, LocalSubTotalIVA + LocalSubTotalIEPSIVA, 0)
|
|
End If
|
|
|
|
LocalDescuentos = TmpDT.SUMD("Descuento")
|
|
|
|
If Not CveCompra > 0 Then
|
|
LocalAmortizacion = Me.Amortizacion
|
|
End If
|
|
|
|
'RETENCIONES
|
|
Dim Retenciones As Decimal = 0
|
|
Retenciones = LocalRetIVA
|
|
Retenciones += LocalRetISR
|
|
|
|
|
|
LocalSubTotal2 = LocalSubTotal - LocalDescuentos
|
|
LocalTotal = LocalSubTotal2 + LocalIVA + LocalIEPSPS - Retenciones
|
|
|
|
'ASIGNAMOS VALORES A VISTA
|
|
If CveCompra > 0 Or CveFactura > 0 Or Me.OCVinculada Then
|
|
SubTotal = LocalSubTotal
|
|
SubTotal2 = LocalSubTotal2
|
|
Descuento = LocalDescuentos
|
|
|
|
If EsNoDeducible Then
|
|
IVA = LocalIVA
|
|
RetIVA = LocalRetIVA
|
|
RetISR = LocalRetISR
|
|
IEPS = LocalIEPSPS
|
|
End If
|
|
|
|
Total = LocalTotal
|
|
Else
|
|
SubTotal = LocalSubTotal
|
|
SubTotal2 = LocalSubTotal2
|
|
IVA = LocalIVA
|
|
Descuento = LocalDescuentos
|
|
RetIVA = LocalRetIVA
|
|
RetISR = LocalRetISR
|
|
IEPS = LocalIEPSPS
|
|
Total = LocalTotal
|
|
'VALORES PROPIEDAD
|
|
CompraSaldo = LocalTotal
|
|
|
|
End If
|
|
Me.NumNoDed = TmpDT.COUNT("CvePS", "NoDeducible = True ")
|
|
|
|
End Sub
|
|
|
|
Private Function UpdatePSReembolso(Index As Integer, CvePS As Integer) As Boolean
|
|
|
|
Dim Respuesta As Boolean = True
|
|
|
|
Dim DrPS As DataRow = Nothing
|
|
Try
|
|
DrPS = TmpDT.Select($"Consec = {Index}")(0)
|
|
If DrPS Is Nothing Then
|
|
Errores.AppendLine($"No se encontrol el producto con index {Index}")
|
|
Return False
|
|
End If
|
|
Catch ex As Exception
|
|
Errores.AppendLine($"No se encontrol el producto con index {Index}")
|
|
Return False
|
|
End Try
|
|
|
|
'DATOS GENERALES
|
|
DrPS("Obs") = ""
|
|
DrPS("Proyecto") = Proyecto
|
|
DrPS("CveProyecto") = CveProyecto
|
|
DrPS("SubProyecto") = SubProyecto
|
|
DrPS("CveSubProyecto") = CveSubProyecto
|
|
DrPS("CveContratoDetalle") = -1
|
|
|
|
'IMPORTES - [CANTIDAD Y PRECIO]
|
|
Dim Cantidad As Double = DrPS("Cantidad").ToString.ToDouble
|
|
Dim PU As Double = DrPS("PU").ToString.ToDouble
|
|
Dim Descuento As Double = DrPS("Descuento").ToString.ToDouble
|
|
Dim Total As Double = (Cantidad * PU) - Descuento
|
|
DrPS("NoDeducible") = NoDeducible
|
|
|
|
Dim PSRow As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("")
|
|
If PSRow IsNot Nothing Then
|
|
Dim CveTipoPS As Integer = PSRow("CveTipoPS").ToString.ToEntero
|
|
If PSRow("CvePSCargo").ToString <> "" Then 'si es un producto de usado. que se registre contablemente como alamcen(como producto)
|
|
CveTipoPS = 2
|
|
End If
|
|
|
|
DrPS("CveClasificacion") = PSRow("CveClasificacion").ToString
|
|
DrPS("Clasificacion") = PSRow("Clasificacion").ToString
|
|
DrPS("CvePS") = CvePS
|
|
DrPS("PS") = PSRow("PS").ToString
|
|
DrPS("CveTipoPS") = CveTipoPS
|
|
DrPS("CveSATPS") = PSRow("CveSATPS").ToString.ToEntero
|
|
DrPS("SATClaveProductoServicio") = PSRow("SATClaveProductoServicio").ToString
|
|
DrPS("CveSATPSActualizado") = 0
|
|
|
|
DrPS("CveUM") = PSRow("CveUnidadMedida").ToString.ToEntero
|
|
DrPS("UM") = PSRow("UnidadMedida").ToString
|
|
|
|
Dim DrTipoGasto As DataRow = Me.DTTiposGastos.FiltroPrimero("")
|
|
|
|
If DrTipoGasto Is Nothing Then
|
|
DrPS("CveTipoGasto") = -1
|
|
DrPS("TipoGasto") = ""
|
|
Else
|
|
DrPS("CveTipoGasto") = DrTipoGasto("CveTipoGasto")
|
|
DrPS("TipoGasto") = DrTipoGasto("TipoGasto")
|
|
End If
|
|
|
|
|
|
|
|
If UsuarioActual.Empresa.Funcionalidad(562).ToEntero > 0 Then
|
|
DrPS("AplicaCostoIndirecto") = "0"
|
|
End If
|
|
|
|
DrPS("CveCultivoCuadroDetalle") = -1
|
|
DrPS("TemporadaCuadro") = ""
|
|
|
|
Else
|
|
Errores.AppendLine($"No se encontrol el producto con CvePS {CvePS}")
|
|
Respuesta = False
|
|
End If
|
|
TmpDT.AcceptChanges()
|
|
Return Respuesta
|
|
End Function
|
|
|
|
Private Sub ValidacionesTotalesXml()
|
|
|
|
If Not TmpDT.Columns.Contains("Amortizacion") Then
|
|
TmpDT.Columns.Add("Amortizacion", GetType(Decimal))
|
|
End If
|
|
|
|
Dim Msg As String = ""
|
|
Dim SubtotalTemp As Decimal = TmpDT.SUMD("Total") + Math.Round(TmpDT.SUM("Descuento") + Math.Round(TmpDT.SUM("Amortizacion")), 2)
|
|
Dim DescuentosTemp As Decimal = TmpDT.SUMD("Descuento")
|
|
Dim Subtotal2Temp As Decimal = TmpDT.SUMD("Total")
|
|
Dim IVATemp As Decimal = TmpDT.SUMD("IVA")
|
|
Dim IEPSTemp As Decimal = TmpDT.SUMD("IEPSPS")
|
|
Dim RetIVATemp As Decimal = TmpDT.SUMD("RetIVA")
|
|
Dim RetISRTemp As Decimal = TmpDT.SUMD("RetISR")
|
|
Dim TotalTemp As Decimal = Subtotal2Temp - RetIVATemp - RetISRTemp + Math.Round(IVATemp, 6) + IEPSTemp + OtrosImpuestos - OtrosImpuestosRetenciones
|
|
|
|
If Math.Abs(Math.Round(DescuentosTemp, 6) - Math.Round(Descuento, 6)) > 0.01 Then
|
|
Msg &= String.Format("- Los descuentos del detalle no coinciden con el descuento general <br>")
|
|
End If
|
|
|
|
If Math.Abs(Math.Round(IVATemp, 6) - Math.Round(TrasladoIVA, 6)) > 0.01 Then
|
|
Msg &= String.Format("- Los IVAS del detalle no coinciden con el IVA general <br>")
|
|
End If
|
|
|
|
If Math.Abs(Math.Round(IEPSTemp, 6) - Math.Round(TrasladoIEPS, 6)) > 0.01 Then
|
|
Msg &= String.Format("- Los IEPS del detalle no coinciden con el IEPS general <br>")
|
|
End If
|
|
|
|
If Math.Abs(Math.Round(RetIVATemp, 6) - Math.Round(RetencionIVA, 6)) > 0.01 Then
|
|
Msg &= String.Format("- Los RetIVA del detalle no coinciden con el RetIVA general <br>")
|
|
End If
|
|
|
|
If Math.Abs(Math.Round(RetISRTemp, 6) - Math.Round(RetencionISR, 6)) > 0.01 Then
|
|
Msg &= String.Format("- Las RetISR del detalle no coinciden con el RetIVA general <br>")
|
|
End If
|
|
|
|
If Math.Abs(Math.Round(TotalTemp, 2) - Math.Round(Total, 2)) > 0.01 Then
|
|
Msg &= String.Format("- El total generado por los detalles no coincide con el total general <br> ({0}-{1})", Math.Round(TotalTemp, 2), Math.Round(Total, 2))
|
|
End If
|
|
|
|
If Msg <> "" Then
|
|
Errores.AppendLine($" El comprobante XML presenta las siguientes inconsistencias:{Msg}. ")
|
|
Else
|
|
|
|
DescuentosTemp = Descuento
|
|
IVATemp = TrasladoIVA
|
|
TotalTemp = Total
|
|
RetIVATemp = RetencionIVA
|
|
RetISRTemp = RetencionISR
|
|
IEPSTemp = TrasladoIEPS
|
|
End If
|
|
|
|
Me.SubTotal = SubtotalTemp
|
|
Me.Descuento = DescuentosTemp
|
|
Me.SubTotal2 = Subtotal2Temp
|
|
Me.IVA = IVATemp
|
|
Me.Total = TotalTemp
|
|
Me.RetIVA = RetIVATemp
|
|
Me.RetISR = RetISRTemp
|
|
Me.IEPS = IEPSTemp
|
|
CompraSaldo = TotalTemp
|
|
|
|
AsignaValoresOriginales(SubtotalTemp, Subtotal2Temp, IVATemp, RetIVATemp, RetISRTemp, Total)
|
|
|
|
End Sub
|
|
|
|
Private Sub AsignaValoresOriginales(SubTotal As Decimal, SubTotal2 As Double, IVA As Decimal, RetIVA As Decimal, RetISR As Decimal, Total As Decimal)
|
|
SubTotalOriginal = SubTotal
|
|
SubTotal2Original = SubTotal2
|
|
IVAOriginal = IVA
|
|
RetIVAOriginal = RetIVA
|
|
RetISROriginal = RetISR
|
|
TotalOriginal = Total
|
|
End Sub
|
|
|
|
Private Sub AjustaImporteUltimoConcepto(ImporteAjuste As Decimal, Optional EsCarga As Boolean = False)
|
|
|
|
If ImporteAjuste = 0 Then Exit Sub
|
|
|
|
Dim Amortizacion As Decimal = 0
|
|
|
|
If TmpDT.Rows.Count > 0 Then ' si hay movimientos y si esta afectando al total, que se haga el ajuste
|
|
Dim Indice As Integer = If(TmpDT.Rows(TmpDT.Rows.Count - 1)("CvePS").ToString = UsuarioActual.Empresa.Funcionalidad(112).ToString, TmpDT.Rows.Count - 2, TmpDT.Rows.Count - 1)
|
|
Dim tPU As Decimal
|
|
|
|
If TmpDT.Rows(Indice)("Cantidad").ToString.ToDecimal > 0 Then
|
|
tPU = ImporteAjuste / TmpDT.Rows(Indice)("Cantidad").ToString.ToDecimal
|
|
Else
|
|
tPU = 0
|
|
End If
|
|
|
|
If TmpDT.Rows(Indice)("PU").ToString.ToDecimal + tPU < 0 Then 'si es negativo, que tome el dato anterior
|
|
Indice = Indice - 1
|
|
If TmpDT.Rows(Indice)("Cantidad").ToString.ToDecimal > 0 Then
|
|
tPU = ImporteAjuste / TmpDT.Rows(Indice)("Cantidad").ToString.ToDecimal
|
|
Else
|
|
tPU = 0
|
|
End If
|
|
End If
|
|
|
|
TmpDT.Rows(Indice)("PU") = TmpDT.Rows(Indice)("PU").ToString.ToDecimal + tPU
|
|
TmpDT.Rows(Indice)("Total") = TmpDT.Rows(Indice)("Total").ToString.ToDecimal + ImporteAjuste
|
|
TmpDT.Rows(Indice)("IEPSPS") = (TmpDT.Rows(Indice)("Total").ToString.ToDecimal() * TmpDT.Rows(Indice)("IEPSPSPorcentaje").ToString.ToDecimal()).RoundAD(2)
|
|
TmpDT.Rows(Indice)("IVA") = (TmpDT.Rows(Indice)("PU").ToString.ToDecimal * TmpDT.Rows(Indice)("Cantidad").ToString.ToDecimal - TmpDT.Rows(Indice)("Descuento").ToString.ToDecimal) * TmpDT.Rows(Indice)("IVAPorcentaje").ToString.ToDecimal
|
|
TmpDT.AcceptChanges()
|
|
End If
|
|
|
|
SubTotal = TmpDT.SUMD("Total")
|
|
If Not EsCarga Then
|
|
Descuento = TmpDT.SUMD("Descuento")
|
|
End If
|
|
|
|
SubTotalConceptos = SubTotal
|
|
|
|
End Sub
|
|
|
|
Public Function ValidateUUID(ByVal uuid As String) As Boolean
|
|
Dim pattern As String = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
|
|
Dim regex As New Regex(pattern)
|
|
Return regex.IsMatch(uuid)
|
|
End Function
|
|
Private Function GeneraStringDoctosRelacionados() As String
|
|
|
|
Dim DoctosRelacionados As String = "-1"
|
|
Dim listaUUIDSRelacionados As New List(Of String)
|
|
|
|
If DocumentosRelacionadosUUIDSList.Count > 0 Then
|
|
For Each s As String In DocumentosRelacionadosUUIDSList
|
|
If s.Trim.Length > 0 Then
|
|
listaUUIDSRelacionados.Add(s.Trim)
|
|
End If
|
|
Next
|
|
End If
|
|
|
|
If listaUUIDSRelacionados.Count > 0 Then
|
|
DoctosRelacionados = String.Join(",", listaUUIDSRelacionados.ToArray())
|
|
End If
|
|
|
|
Return DoctosRelacionados
|
|
End Function
|
|
Private Function ValorXML(n As XmlNode, Campo As String, Optional Retorno As String = "") As String
|
|
Dim o As XmlNode = n.Attributes.Cast(Of XmlAttribute)().SingleOrDefault(Function(a) String.Compare(a.Name, Campo, True) = 0)
|
|
If o Is Nothing Then
|
|
Return Retorno
|
|
Else
|
|
Return o.Value
|
|
End If
|
|
End Function
|
|
|
|
Public Function AddCompra() As Boolean
|
|
|
|
If Not AjustesValidacion() Then Return False
|
|
|
|
Dim respuesta As Boolean = True
|
|
Dim ObjCompras As New ClsCompras
|
|
Dim ObjConta As New ClsContabilidad(ObjCompras.IniciaTransacSQL())
|
|
|
|
If Not AddPrepolizaCabecera(ObjConta) Then
|
|
respuesta = False
|
|
End If
|
|
|
|
If respuesta AndAlso ObjCompras.AddCompra(If(Me.TipoComprobante = "I", "Fac", "NC"), Me.Descripcion, Me.Serie, Me.Folio, Me.FolioSecundario, Me.CveProveedor, Me.SubTotal, Me.Descuento,
|
|
Me.Amortizacion, Me.IVA, Me.RetIVA, Me.RetISR, Me.IEPS, Me.OtrosImpuestos,
|
|
Me.Redondeo, Me.Total, Me.Fecha, Me.CveMoneda, Me.TipoCambio, If(Me.FechaPago = Nothing, Me.Fecha, Me.FechaPago), Me.AplicaNotaCredito, Me.Observaciones, Me.CveEstatusFactura,
|
|
Me.CvePrePoliza, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, Me.IdPoliza, CveCajaChica:=Me.CveCajaChica, CvePersonal:=Me.CvePersonal, NumeroReembolso:=Me.NumeroReembolso, CveProveedorSucursal:=Me.CveProveedorSucursal,
|
|
AplicoPromocion:=Me.AplicoPromocion, PorcentajeIVA:=Me.PorcentajeIVA, CveMetodoPago:=Me.CveMetodoPago, CveRetIVAConcepto:=Me.CveRetIVAConcepto,
|
|
CveConceptoContableAlmacen:=Me.CveConceptoContableAlmacen,
|
|
CveRetISRConcepto:=Me.CveRetISRConcepto, NoDeducible:=Me.NoDeducible, CveTipoCompra:=Me.CveTipoCompra, TotalOriginal:=Me.TotalOriginal, CveTipoConcepto:=Me.CveTipoConcepto,
|
|
EsImportacion:=Me.EsImportacion, CveFactura:=Me.CveFactura, CveSubProyecto:=Me.CveSubProyectoPrincipal, DoctosRelacionados:=Me.DocumentosRelacionadosUUIDSString, CveFolioGarantia:=Me.CveFolioGarantia) Then
|
|
Me.CveCompra = ObjCompras.CveCompra
|
|
Else
|
|
respuesta = False
|
|
End If
|
|
|
|
If respuesta AndAlso Me.CveCompra > 0 Then
|
|
|
|
For Each Row As DataRow In Me.TmpDT.Rows
|
|
|
|
Dim TipoRecepcion As Integer = -1
|
|
Dim Referencia As String = ""
|
|
Dim EsNoDeducible As Boolean = False
|
|
Dim CveAF As Integer = If(Row("CveActivoFijo").ToString.ToEntero > 0 AndAlso Row("TipoAF").ToString.ToEntero = 1, Row("CveActivoFijo").ToString.ToEntero, -1)
|
|
Dim CveAFC As Integer = If(Row("CveActivoFijo").ToString.ToEntero > 0 AndAlso Row("TipoAF").ToString.ToEntero = 2, Row("CveActivoFijo").ToString.ToEntero, -1)
|
|
|
|
If Not ObjCompras.AddCompraDetalle(Me.CveCompra, Row("CveUM").ToString.ToEntero, Row("CvePS").ToString.ToEntero, Row("CveSubProyecto").ToString.ToEntero, -1, CveAF,
|
|
Row("Cantidad").ToString.ToDecimal, Row("PU").ToString.ToDecimal, Row("IVA").ToString.ToDecimal, Row("Total").ToString.ToDecimal, Row("Descuento").ToString.ToDecimal,
|
|
Row("Obs").ToString, Row("CveOrdenCompraDetalle").ToString.ToEntero, TipoRecepcion, Row("CveContrato").ToString.ToEntero, Row("CvePresupuestoEgreso").ToString.ToEntero,
|
|
AplicaCostoIndirecto:=Row("AplicaCostoIndirecto").ToString.ToEntero, EstatusAlmacen:=Row("EntregaDirecta").ToString.ToEntero, CvePersonal:=CvePersonal,
|
|
CveTipoGasto:=Row("CveTipoGasto").ToString.ToEntero, AF_Medida:=Row("AFMedida").ToString.ToEntero, AF_TipoMantenimiento:=Row("AFTipoMantenimiento").ToString.ToEntero, Referencia:=Referencia, OtrosGastos:=Row("OtrosGastos").ToString.ToDecimal,
|
|
RetIVA:=Row("RetIVA").ToString.ToDecimal, RetISR:=Row("RetISR").ToString.ToDecimal, IEPSPS:=Row("IEPSPS").ToString.ToDecimal.RoundSQL, IEPSPSIVA:=Row("IEPSPSIVA").ToString.ToDecimal,
|
|
IVAPorcentaje:=Row("IVAPorcentaje").ToString.ToDecimal, RetIVAPorcentaje:=Row("RetIVAPorcentaje").ToString.ToDecimal, RetISRPorcentaje:=Row("RetISRPorcentaje").ToString.ToDecimal,
|
|
IEPSPSPorcentaje:=Row("IEPSPSPorcentaje").ToString.ToDecimal, IEPSPSIVAPorcentaje:=Row("IEPSPSIVAPorcentaje").ToString.ToDecimal, NoDeducible:=If((Row("NoDeducible").ToString().ToUpper().Contiene("TRUE", "1")) AndAlso EsNoDeducible, True, False),
|
|
CveContratoDetalle:=Row("CveContratoDetalle").ToString.ToEntero, CveCultivoCuadroDetalle:=Row("CveCultivoCuadroDetalle").ToString.ToEntero, CveActivoFijoCompra:=CveAFC) Then
|
|
|
|
respuesta = False
|
|
Exit For
|
|
End If
|
|
Next
|
|
End If
|
|
|
|
If respuesta Then
|
|
If Not AddPrePolizaDetalles(ObjConta) Then respuesta = False
|
|
End If
|
|
|
|
If respuesta AndAlso ObjConta.ValidacionesPrePoliza(CvePrePoliza, UsuarioActual, 4) Then
|
|
If ObjConta.ValorPolizaDescuadre > 0 Then
|
|
Errores.AppendLine($"eFacturas/Compras-Guardar | Error{ObjConta.MensajePolizaDescuadre} Diferencia{ObjConta.ValorDiferencia} | CvePrePoliza:{CvePrePoliza}.")
|
|
GuardaLogAD($"eFacturas/Compras-Guardar | Error{ObjConta.MensajePolizaDescuadre} Diferencia{ObjConta.ValorDiferencia} | CvePrePoliza:{CvePrePoliza}", "LogPrePolizas")
|
|
respuesta = False
|
|
End If
|
|
End If
|
|
|
|
If respuesta Then
|
|
If Not ObjCompras.UpdateCompraFactura(Me.CveCompra, Me.CveFactura, Me.Serie, Me.Folio) Then respuesta = False
|
|
End If
|
|
|
|
If respuesta Then
|
|
ObjCompras.Commit()
|
|
Else
|
|
ObjCompras.RollBack()
|
|
End If
|
|
|
|
ObjCompras.Dispose()
|
|
ObjConta.Dispose()
|
|
|
|
Return respuesta
|
|
End Function
|
|
|
|
Private Function AddPrepolizaCabecera(ByRef ObjConta As ClsContabilidad) As Boolean
|
|
|
|
Dim respuesta As Boolean = False
|
|
Dim ConceptoPoliza As String = String.Format("{0} - {1} - {2}", NombreProveedor, SerieFolio, "")
|
|
Me.CvePrePoliza = ObjConta.AddPrePolizas("eFacturas/Registrar", 1, Me.Total, Me.Total, Me.CveMoneda, Me.Fecha, ConceptoPoliza, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, 0, "", CveTipoPoliza:=Me.CveTipoPoliza)
|
|
respuesta = If(Me.CvePrePoliza > 0, True, False)
|
|
|
|
Return respuesta
|
|
End Function
|
|
|
|
Private Function AddPrePolizaDetalles(ByRef ObjConta As ClsContabilidad) As Boolean
|
|
Dim respuesta As Boolean = True
|
|
Dim Concepto As String = $"{Me.NombreProveedor} {Me.SerieFolio}"
|
|
Dim Referencia As String = Me.SerieFolio
|
|
Dim importeMovimiento As Decimal
|
|
Dim importeMN As Decimal
|
|
'6
|
|
For Each RowDetalle As DataRow In TmpDT.FiltraParametros("ISNULL(TipoAF,0) <> 2", "", {"CveClasificacion", "CveSubProyecto"}).Rows
|
|
|
|
importeMovimiento = TmpDT.SUMD("Total", $" CveClasificacion = {RowDetalle("CveClasificacion").ToString} AND CveSubProyecto = {RowDetalle("CveSubProyecto").ToString}")
|
|
importeMN = (importeMovimiento * Me.TipoCambio).RoundSQL
|
|
|
|
If importeMN <> 0 Then
|
|
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMovimiento, importeMN, 6, Referencia, Concepto, CveCompra:=CveCompra, CveProveedor:=Me.CveProveedor, CveIE:=Me.CveIE, CvePersonal:=CvePersonal, CveCreditoDetalle:=Me.CveCreditoDetalle, ImporteME:=If(TipoCambio = 1, 0, importeMovimiento), TipoCambio:=TipoCambio,
|
|
CveClasificacion:=RowDetalle("CveClasificacion").ToString().ToEntero(), CveSubProyecto:=RowDetalle("CveSubProyecto").ToString().ToEntero(), Contabilizable:=True) Then
|
|
respuesta = False
|
|
Exit For
|
|
End If
|
|
End If
|
|
Next
|
|
'14
|
|
If respuesta AndAlso Me.IVA > 0 Then
|
|
importeMovimiento = Me.IVA
|
|
importeMN = (importeMovimiento * Me.TipoCambio).RoundSQL
|
|
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importeMovimiento, importeMN, 14, Referencia, Concepto, CveCompra:=CveCompra, CveSubProyecto:=Me.CveSubProyectoPrincipal, CveProveedor:=Me.CveProveedor, CveIE:=Me.CveIE, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteME:=If(Me.TipoCambio = 1, 0, importeMovimiento), TipoCambio:=Me.TipoCambio, PorcentajeImpuesto:=Me.PorcentajeIVA, Contabilizable:=True) Then
|
|
respuesta = False
|
|
End If
|
|
End If
|
|
'25
|
|
If respuesta AndAlso Me.IEPS > 0 Then
|
|
importeMovimiento = Me.IEPS
|
|
importeMN = (importeMovimiento * Me.TipoCambio).RoundSQL
|
|
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importeMovimiento, importeMN, 25, Referencia, Concepto, CveCompra:=CveCompra, CveSubProyecto:=Me.CveSubProyectoPrincipal, CveProveedor:=Me.CveProveedor, CveIE:=Me.CveIE, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteME:=If(Me.TipoCambio = 1, 0, importeMovimiento), TipoCambio:=Me.TipoCambio, PorcentajeImpuesto:=0, Contabilizable:=True) Then
|
|
respuesta = False
|
|
End If
|
|
End If
|
|
'
|
|
If respuesta AndAlso Me.RetIVA > 0 Then
|
|
importeMovimiento = Me.RetIVA
|
|
importeMN = (importeMovimiento * Me.TipoCambio).RoundSQL
|
|
Dim ret As ConceptosRetenciones = ConceptoPrePolizaRetIVA
|
|
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importeMovimiento, importeMN, ret.CveConceptoxAcreditar, Referencia, Concepto, CveCompra:=CveCompra, CveSubProyecto:=Me.CveSubProyectoPrincipal, CveProveedor:=Me.CveProveedor, CveIE:=Me.CveIE, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteME:=If(Me.TipoCambio = 1, 0, importeMovimiento), TipoCambio:=Me.TipoCambio, PorcentajeImpuesto:=0, Contabilizable:=True) Then
|
|
respuesta = False
|
|
End If
|
|
End If
|
|
'
|
|
If respuesta AndAlso Me.RetISR > 0 Then
|
|
importeMovimiento = Me.RetISR
|
|
importeMN = (importeMovimiento * Me.TipoCambio).RoundSQL
|
|
Dim ret As ConceptosRetenciones = ConceptoPrePolizaRetISR
|
|
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importeMovimiento, importeMN, ret.CveConceptoxAcreditar, Referencia, Concepto, CveCompra:=CveCompra, CveSubProyecto:=Me.CveSubProyectoPrincipal, CveProveedor:=Me.CveProveedor, CveIE:=Me.CveIE, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteME:=If(Me.TipoCambio = 1, 0, importeMovimiento), TipoCambio:=Me.TipoCambio, PorcentajeImpuesto:=0, Contabilizable:=True) Then
|
|
respuesta = False
|
|
End If
|
|
End If
|
|
'5
|
|
If respuesta Then
|
|
importeMovimiento = Me.Total
|
|
importeMN = (importeMovimiento * Me.TipoCambio).RoundSQL
|
|
Dim ConPreP As ConceptosTipoSaldo = ObtenerCveConceptoPrePoliza(1, Me.CveMoneda, False, Me.CveTipoConceptoProveedor)
|
|
Dim ImporteME As Decimal = importeMovimiento
|
|
Dim UsaComplementaria As Boolean = True
|
|
If Me.CveMoneda > 1 Then ImporteME = importeMovimiento
|
|
|
|
If UsuarioActual.CveEmpresa.Contiene(13, 83) Then 'caso excepcional de complementarias
|
|
UsaComplementaria = False
|
|
importeMN = importeMovimiento * Me.TipoCambio
|
|
Else
|
|
importeMN = importeMovimiento
|
|
End If
|
|
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importeMovimiento, importeMN, ConPreP.CveConcepto, Referencia, Concepto, CveCompra:=CveCompra, CveSubProyecto:=Me.CveSubProyectoPrincipal, CveProveedor:=Me.CveProveedor, CveIE:=Me.CveIE, CvePersonal:=CvePersonal, CveCreditoDetalle:=CveCreditoDetalle, ImporteME:=If(Me.TipoCambio = 1, 0, importeMovimiento), TipoCambio:=Me.TipoCambio, PorcentajeImpuesto:=0, Contabilizable:=True) Then
|
|
respuesta = False
|
|
End If
|
|
If respuesta AndAlso Me.CveMoneda > 1 AndAlso UsaComplementaria Then
|
|
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importeMovimiento, (importeMovimiento * Me.TipoCambio - importeMovimiento).RoundSQL, ConPreP.CveConceptoComplementario, Referencia, Concepto, CveCompra:=Me.CveCompra, CveProveedor:=Me.CveProveedor, CveIE:=Me.CveIE, CvePersonal:=Me.CvePersonal, CveCompraAmortizacion:=Me.CveCompraAmortizacion, TipoCambio:=Me.TipoCambio, TipoCambioPago:=1, ImporteME:=ImporteME, CveSubProyecto:=Me.CveSubProyecto) Then
|
|
respuesta = False
|
|
End If
|
|
End If
|
|
End If
|
|
|
|
Return respuesta
|
|
End Function
|
|
|
|
End Class
|
|
|
|
|
|
|
|
Namespace ADS.eFacturas
|
|
Public Class Factura
|
|
|
|
Public Property CveFactura As Integer = -1
|
|
Public Property RespuestaInsert As Integer = -1
|
|
|
|
Friend noCertificado As String = ""
|
|
Public Property CveEmpresa As Integer
|
|
Public Property Version As String
|
|
Public Property Serie As String
|
|
Public Property Folio As String
|
|
Public Property Fecha As Date
|
|
Public Property SubTotal As Decimal
|
|
Public Property Total As Decimal
|
|
Public Property Moneda As String
|
|
Public Property CveMoneda As Integer
|
|
Public Property TipoComprobante As String
|
|
Public Property Descuento As Decimal
|
|
Public Property TipoCambio As Decimal
|
|
Public Property MetododePago As String = ""
|
|
Public Property EmisorRFC As String
|
|
Public Property EmisorNombre As String
|
|
Public Property EmisorRegimenFiscal As String
|
|
Public Property ReceptorRFC As String
|
|
Public Property ReceptorNombre As String
|
|
Public Property ReceptorUsoCFDI As String
|
|
Public Property TotalRetenciones As Decimal
|
|
Public Property SumaTotalRetenciones As Decimal
|
|
Public Property TotalTraslados As Decimal
|
|
Public Property SumaTotalTraslados As Decimal
|
|
Public Property TrasladoIVA As Decimal
|
|
Public Property TrasladoIEPS As Decimal
|
|
Public Property TrasladoISR As Decimal
|
|
Public Property RetencionIVA As Decimal
|
|
Public Property RetencionISR As Decimal
|
|
Public Property sUPPrefijo As String
|
|
Public Property UUID As String
|
|
Public Property Validada As Integer = 0
|
|
Public Property ArchivoXML As String
|
|
Public Property ArchivoPDF As String
|
|
Public Property Pagos As New List(Of Pago)
|
|
Public Property IEPS As Decimal
|
|
Public Property TFDFechaTimbrado As String
|
|
Public Property TFDSelloCFD As String
|
|
Public Property TFDNoCertSAT As String
|
|
Public Property TFDSelloSAT As String
|
|
Public Property FormaDePago As String
|
|
Public Property DTConceptos As DataTable
|
|
Public Property EmiRFC As String
|
|
Public Property EmiNombre As String
|
|
Public Property DomFisCalle As String
|
|
Public Property DomFisNoExt As String
|
|
Public Property DomFisCol As String
|
|
Public Property DomFisCP As String
|
|
Public Property DomFisMun As String
|
|
Public Property DomFisLoc As String
|
|
Public Property DomFisEst As String
|
|
Public Property DomFisPais As String
|
|
Public Property ExpEnCalle As String
|
|
Public Property ExpEnNoExt As String
|
|
Public Property ExpEnCol As String
|
|
Public Property ExpEnCP As String
|
|
Public Property ExpEnMun As String
|
|
Public Property ExpEnLoc As String
|
|
Public Property ExpEnEst As String
|
|
Public Property ExpEnPais As String
|
|
Public Property Regimen As String
|
|
Public Property RecRfc As String
|
|
Public Property RecNombre As String
|
|
Public Property DomRecCalle As String
|
|
Public Property DomRecFisNoExt As String
|
|
Public Property DomRecFisNoInt As String
|
|
Public Property DomRecCol As String
|
|
Public Property DomRecCP As String
|
|
Public Property DomRecMun As String
|
|
Public Property DomRecLoc As String
|
|
Public Property DomRecEst As String
|
|
Public Property DomRecPais As String
|
|
Public Property condicionesDePago As String
|
|
Public Property NumCtaPagoNumCtaPago As String
|
|
|
|
|
|
Public ReadOnly Property DtPagos As DataTable
|
|
Get
|
|
|
|
If Pagos.Count > 0 Then
|
|
|
|
Dim query = From p In Me.Pagos Select New With {.FechaPago = p.FechaPago, .FormaDePagoP = p.FormaDePagoP, .MonedaP = p.MonedaP, .ImportePago = p.Monto}
|
|
Dim DtPagosNew As DataTable = ModExtensiones.CopyToDataTable(query, True)
|
|
DtPagosNew.TableName = "DsPagos"
|
|
Return DtPagosNew
|
|
Else
|
|
Dim DtPagosNew As New DataTable
|
|
DtPagosNew.TableName = "DsPagos"
|
|
Return DtPagosNew
|
|
End If
|
|
|
|
End Get
|
|
End Property
|
|
|
|
Public ReadOnly Property DtDocumentosR As DataTable
|
|
Get
|
|
If Pagos.Count > 0 Then
|
|
|
|
Dim DtDocumentosRNew As DataTable = ModExtensiones.CopyToDataTable(Pagos(0).Documentos, True)
|
|
DtDocumentosRNew.TableName = "DsDocRelacionados"
|
|
Return DtDocumentosRNew
|
|
|
|
Else
|
|
Dim DtDocumentosRNew As New DataTable
|
|
DtDocumentosRNew.TableName = "DsDocRelacionados"
|
|
Return DtDocumentosRNew
|
|
|
|
End If
|
|
End Get
|
|
End Property
|
|
|
|
Private Sub CreaDTConceptos()
|
|
DTConceptos = New DataTable()
|
|
DTConceptos.Columns.Add("Consec", GetType(Integer))
|
|
DTConceptos.Columns.Add("Cantidad", GetType(Double))
|
|
DTConceptos.Columns.Add("UM", GetType(String))
|
|
DTConceptos.Columns.Add("PS", GetType(String))
|
|
DTConceptos.Columns.Add("PU", GetType(Double))
|
|
DTConceptos.Columns.Add("IVA", GetType(Double))
|
|
DTConceptos.Columns.Add("Total", GetType(Double))
|
|
End Sub
|
|
|
|
Public Sub New()
|
|
CreaDTConceptos()
|
|
End Sub
|
|
|
|
Public Sub AddPS(ByVal Cantidad As Double, ByVal UM As String, ByVal PS As String, ByVal PU As Double, ByVal IVA As Double, Optional ByVal Total As Double = 0)
|
|
If PS <> "IVA" Then
|
|
Dim Row As DataRow = Nothing
|
|
Row = DTConceptos.NewRow()
|
|
Row("Consec") = DTConceptos.Rows.Count + 1
|
|
Row("Cantidad") = Cantidad
|
|
Row("UM") = UM
|
|
Row("PS") = PS
|
|
Row("PU") = PU
|
|
Row("IVA") = IVA
|
|
Row("Total") = If(Total > 0, Total, (Cantidad * PU))
|
|
DTConceptos.Rows.Add(Row)
|
|
End If
|
|
End Sub
|
|
|
|
End Class
|
|
|
|
Public Class Pago
|
|
Public Property FechaPago As DateTime
|
|
Public Property FormaDePagoP As String
|
|
Public Property MonedaP As String
|
|
Public Property Monto As Decimal
|
|
Public Property Documentos As List(Of DoctoRelacionado)
|
|
End Class
|
|
|
|
Public Class DoctoRelacionado
|
|
Public Property Serie As String
|
|
Public Property Folio As String
|
|
Public Property ImportePago As Decimal
|
|
Public Property ImpSaldoAnt As Decimal
|
|
Public Property ImpSaldoInsoluto As Decimal
|
|
Public Property idDocumento As String
|
|
Public Property MonedaDR As String
|
|
Public Property MetodoDePagoDR As String
|
|
Public Property NumParcialidad As String
|
|
|
|
End Class
|
|
|
|
Public Class ComprobanteFactura
|
|
Public Property ArchivoLog As String
|
|
|
|
Public Sub New(NombreArchivoLog As String)
|
|
ArchivoLog = NombreArchivoLog
|
|
End Sub
|
|
|
|
Public Property Pagos As List(Of Pago)
|
|
Public Property XMLNodosPagos As String
|
|
Public Property XMLNodosPagosCount As Integer
|
|
Private Function CargaFactVersion33(CveEmpresa As Integer, ByRef node As XmlNode, ByRef nodo As XmlNode, ByRef XMLDoc As XmlDocument, ByVal Prefijo As String, ByRef namespaces As XmlNamespaceManager, ByVal VersionCFDI As String) As Factura
|
|
Dim Fact = New Factura()
|
|
Fact.Version = VersionCFDI
|
|
Fact.CveEmpresa = CveEmpresa
|
|
Fact.Serie = CaratecteresvalidosFolio(ValorXML(nodo, "serie"))
|
|
If Not String.IsNullOrEmpty(Fact.Serie) Then Fact.Serie = Fact.Serie
|
|
Fact.Folio = ValorXML(nodo, "folio").TrimStart("0"c)
|
|
Fact.Fecha = ValorXML(nodo, "fecha").ToDateTime
|
|
Fact.SubTotal = ValorXML(nodo, "subTotal").Replace("..", ".").ToDecimal
|
|
Fact.Total = ValorXML(nodo, "total").ToDecimal
|
|
Fact.Moneda = ValorXML(nodo, "Moneda")
|
|
Fact.MetododePago = ValorXML(nodo, "MetododePago")
|
|
Fact.TipoComprobante = ValorXML(nodo, "tipoDeComprobante")
|
|
Fact.TipoCambio = ValorXML(nodo, "TipoCambio", "1.0").ToDecimal
|
|
If Fact.TipoCambio < 1 Then Fact.TipoCambio = 1
|
|
|
|
If Fact.TipoComprobante = "P" Then
|
|
Dim PagoPrefix As String = ""
|
|
|
|
If VersionCFDI = "3.3" Then
|
|
PagoPrefix = "pago10"
|
|
namespaces.AddNamespace("pago10", "http://www.sat.gob.mx/Pagos")
|
|
ElseIf VersionCFDI = "4.0" Then
|
|
PagoPrefix = "pago20"
|
|
namespaces.AddNamespace("pago20", "http://www.sat.gob.mx/Pagos20")
|
|
End If
|
|
|
|
Dim NodoComplementos As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Complemento", Prefijo), namespaces)
|
|
Dim nodePagos As XmlNode = NodoComplementos.SelectSingleNode($"//{PagoPrefix}:Pagos", namespaces)
|
|
|
|
For Each nPago As XmlNode In nodePagos.ChildNodes
|
|
Fact.Total = ValorXML(nPago, "Monto").ToDecimal
|
|
If VersionCFDI = "4.0" And nPago.LocalName.ToUpper() = "TOTALES" Then
|
|
Continue For
|
|
Else
|
|
Exit For
|
|
End If
|
|
Next
|
|
End If
|
|
|
|
Fact.sUPPrefijo = Prefijo
|
|
node = XMLDoc.SelectSingleNode(String.Format("//{0}:Emisor", Prefijo), namespaces)
|
|
|
|
If node IsNot Nothing AndAlso node.Attributes.Count > 0 Then
|
|
Fact.EmisorRFC = ValorXML(node, "RFC").Trim()
|
|
Fact.EmisorNombre = ValorXML(node, "nombre")
|
|
End If
|
|
|
|
node = XMLDoc.SelectSingleNode(String.Format("//{0}:Receptor", Prefijo), namespaces)
|
|
|
|
If node IsNot Nothing Then
|
|
Fact.ReceptorRFC = ValorXML(node, "RFC").Trim()
|
|
End If
|
|
|
|
If XMLDoc.HasChildNodes Then
|
|
node = XMLDoc.ChildNodes(0).ChildNodes.Cast(Of XmlNode)().Where(Function(n, b) n.Name.Equals(String.Format("{0}:Impuestos", Prefijo), StringComparison.OrdinalIgnoreCase)).FirstOrDefault()
|
|
|
|
If XMLDoc.ChildNodes.Count > 1 Then
|
|
node = XMLDoc.ChildNodes(1).ChildNodes.Cast(Of XmlNode)().Where(Function(n, b) n.Name.Equals(String.Format("{0}:Impuestos", Prefijo), StringComparison.OrdinalIgnoreCase)).FirstOrDefault()
|
|
End If
|
|
End If
|
|
|
|
If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then
|
|
|
|
Try
|
|
Dim nodeRetenciones = node.ChildNodes.Cast(Of XmlNode)().Where(Function(n, b) n.Name.Equals(String.Format("{0}:Retenciones", Prefijo), StringComparison.OrdinalIgnoreCase))
|
|
Fact.TotalRetenciones = ValorXML(node, "totalImpuestosRetenidos", "0").ToDecimal
|
|
|
|
Try
|
|
Dim retenciones = nodeRetenciones.FirstOrDefault().ChildNodes
|
|
|
|
For Each retencion As XmlNode In retenciones
|
|
Dim TipoImpuesto As String = ValorXML(retencion, "impuesto")
|
|
Dim importe As Decimal = ValorXML(retencion, "importe").ToDecimal
|
|
|
|
If TipoImpuesto = "002" Then
|
|
Fact.RetencionIVA += importe
|
|
End If
|
|
|
|
If TipoImpuesto = "001" Then
|
|
Fact.RetencionISR += importe
|
|
End If
|
|
Next
|
|
|
|
Catch ex As Exception
|
|
End Try
|
|
|
|
Fact.SumaTotalRetenciones += Fact.RetencionIVA
|
|
Fact.SumaTotalRetenciones += Fact.RetencionISR
|
|
Fact.TotalTraslados = ValorXML(node, "totalImpuestosTrasladados", "0").ToDecimal
|
|
Dim nodeTraslados = node.ChildNodes.Cast(Of XmlNode)().Where(Function(n, b) n.Name.Equals(String.Format("{0}:Traslados", Prefijo), StringComparison.OrdinalIgnoreCase))
|
|
Dim traslados = nodeTraslados.FirstOrDefault().ChildNodes
|
|
|
|
For Each traslado As XmlNode In traslados
|
|
Dim TipoImpuesto As String = ValorXML(traslado, "impuesto")
|
|
Dim importe As Decimal = ValorXML(traslado, "importe").ToDecimal()
|
|
|
|
If TipoImpuesto = "003" Then
|
|
Fact.TrasladoIEPS += importe
|
|
End If
|
|
|
|
If TipoImpuesto = "002" Then
|
|
Fact.TrasladoIVA += importe
|
|
End If
|
|
|
|
If TipoImpuesto = "001" Then
|
|
Fact.TrasladoISR += importe
|
|
End If
|
|
Next
|
|
|
|
Fact.SumaTotalTraslados += Fact.TrasladoIVA + Fact.TrasladoIEPS
|
|
Catch ex As Exception
|
|
ex.ToString().GuardaLogAD(ArchivoLog)
|
|
End Try
|
|
End If
|
|
|
|
Dim nodeComp As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Complemento", Prefijo), namespaces)
|
|
|
|
If nodeComp IsNot Nothing AndAlso nodeComp.ChildNodes.Count > 0 Then
|
|
Dim nodeTFD As XmlNode = nodeComp.SelectSingleNode(String.Format("//{0}:TimbreFiscalDigital", "tfd"), namespaces)
|
|
Fact.UUID = ValorXML(nodeTFD, "UUID", "")
|
|
Dim nodeRF As XmlNode = nodeComp.SelectSingleNode(String.Format("//{0}:CFDIRegistroFiscal ", "registrofiscal"), namespaces)
|
|
|
|
If nodeRF IsNot Nothing Then
|
|
Fact.Folio = ValorXML(nodeRF, "folio").TrimStart("0"c)
|
|
End If
|
|
Else
|
|
Fact.UUID = ""
|
|
|
|
If String.IsNullOrEmpty(Fact.UUID) AndAlso Fact.sUPPrefijo.ToLower() = "cfdi" Then
|
|
'Mensajes.AppendFormat("{0}|{1}|{2}|{3}|{4}|{5}{6}&", ValorXML(nodo, "serie"), ValorXML(nodo, "folio"), ValorXML(nodo, "fecha").ToDate().ToShortDateString(), Fact.EmisorNombre, ValorXML(nodo, "total").ToDouble().FormatoNumero(), "Factura no timbrada correctamente.", "")
|
|
'CargaMensaje(ValorXML(nodo, "serie"), ValorXML(nodo, "folio"), ValorXML(nodo, "fecha").ToDate(), Fact.EmisorNombre, ValorXML(nodo, "total").ToDouble(), "Factura no timbrada correctamente.", CorreoActual, DateTime.Now, _EmiRFC, 0)
|
|
End If
|
|
|
|
Fact = Nothing
|
|
End If
|
|
|
|
If Fact.TipoComprobante = "P" Then
|
|
CargaPagos(XMLDoc)
|
|
End If
|
|
|
|
Return Fact
|
|
End Function
|
|
|
|
Private Sub CargaPagos(ByVal XMLDoc As XmlDocument)
|
|
Dim nodo = XMLDoc.DocumentElement
|
|
Dim Prefijo As String = If(String.IsNullOrEmpty(XMLDoc.DocumentElement.Prefix), "cfd", XMLDoc.DocumentElement.Prefix)
|
|
Dim cfdVer As String = "http://www.sat.gob.mx/cfd/3"
|
|
Dim namespaces As XmlNamespaceManager = New XmlNamespaceManager(XMLDoc.NameTable)
|
|
Dim Version = ValorXML(nodo, "version").Replace("..", ".")
|
|
Dim PrefijoPagos As String = ""
|
|
If Prefijo.ToLower() <> "cfdi" Then cfdVer = "http://www.sat.gob.mx/cfd/2"
|
|
|
|
If Version = "3.3" Then
|
|
PrefijoPagos = "pago10"
|
|
namespaces.AddNamespace(PrefijoPagos, "http://www.sat.gob.mx/Pagos")
|
|
Prefijo = "cfdi"
|
|
cfdVer = "http://www.sat.gob.mx/cfd/3"
|
|
namespaces.AddNamespace(Prefijo, cfdVer)
|
|
ElseIf Version = "4.0" Then
|
|
PrefijoPagos = "pago20"
|
|
namespaces.AddNamespace(PrefijoPagos, "http://www.sat.gob.mx/Pagos20")
|
|
Prefijo = "cfdi"
|
|
cfdVer = "http://www.sat.gob.mx/cfd/4"
|
|
namespaces.AddNamespace(Prefijo, cfdVer)
|
|
Else
|
|
End If
|
|
|
|
Dim nodeComp As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Complemento", Prefijo), namespaces)
|
|
|
|
If Version = "3.2" Then
|
|
ElseIf Version = "3.3" OrElse Version = "4.0" Then
|
|
|
|
If nodeComp IsNot Nothing AndAlso nodeComp.ChildNodes.Count > 0 Then
|
|
Dim NodosNodePagos As XmlNodeList = nodeComp.SelectNodes($"//{PrefijoPagos}:Pago", namespaces)
|
|
|
|
If NodosNodePagos IsNot Nothing Then
|
|
|
|
Try
|
|
Dim nodePagos As XmlNode = nodeComp.SelectSingleNode($"//{PrefijoPagos}:Pagos", namespaces)
|
|
|
|
If Version = "3.3" Then
|
|
XMLNodosPagos = nodePagos.InnerXml.Replace("pago10:", "").Replace("pagos10:", "").Replace(PrefijoPagos & ":", "")
|
|
Else
|
|
XMLNodosPagos = nodePagos.InnerXml.Replace("pago20:", "").Replace("pagos20:", "").Replace(PrefijoPagos & ":", "")
|
|
End If
|
|
|
|
Catch ex As Exception
|
|
ModExtensiones.GuardaLogAD(ex.ToString(), ArchivoLog)
|
|
End Try
|
|
End If
|
|
|
|
Dim Pagos = New List(Of Pago)()
|
|
Dim FechaPago As Date
|
|
For Each nodePago As XmlNode In NodosNodePagos
|
|
|
|
Try
|
|
FechaPago = ValorXML(nodePago, "FechaPago").ToDate()
|
|
Catch e As Exception
|
|
End Try
|
|
|
|
Dim pago = New Pago()
|
|
pago.FechaPago = FechaPago
|
|
pago.FormaDePagoP = ValorXML(nodePago, "FormaDePagoP").ToString()
|
|
pago.MonedaP = ValorXML(nodePago, "MonedaP").ToString()
|
|
pago.Monto = ValorXML(nodePago, "Monto").ToString().ToDecimal()
|
|
Dim docs = New List(Of DoctoRelacionado)()
|
|
Dim NodosPagosRelacionados As XmlNodeList = nodePago.SelectNodes($"//{PrefijoPagos}:DoctoRelacionado", namespaces)
|
|
|
|
For Each docto As XmlNode In NodosPagosRelacionados
|
|
Dim idDoc = ValorXML(docto, "idDocumento")
|
|
Dim ImportePago = ValorXML(docto, "ImpPagado").ToDecimal()
|
|
Dim serie = ValorXML(docto, "Serie")
|
|
Dim Folio = ValorXML(docto, "Folio")
|
|
Dim MonedaDR = ValorXML(docto, "MonedaDR")
|
|
Dim MetodoDePagoDR = ValorXML(docto, "MetodoDePagoDR")
|
|
Dim NumParcialidad = ValorXML(docto, "NumParcialidad")
|
|
Dim ImpSaldoInsoluto = ValorXML(docto, "ImpSaldoInsoluto").ToDecimal()
|
|
Dim ImpSaldoAnt = ValorXML(docto, "ImpSaldoAnt").ToDecimal()
|
|
docs.Add(New DoctoRelacionado() With {
|
|
.idDocumento = idDoc,
|
|
.ImportePago = ImportePago,
|
|
.Serie = serie,
|
|
.Folio = Folio,
|
|
.MonedaDR = MonedaDR,
|
|
.MetodoDePagoDR = MetodoDePagoDR,
|
|
.NumParcialidad = NumParcialidad,
|
|
.ImpSaldoAnt = ImpSaldoAnt,
|
|
.ImpSaldoInsoluto = ImpSaldoInsoluto
|
|
})
|
|
Next
|
|
|
|
pago.Documentos = docs
|
|
Pagos.Add(pago)
|
|
Next
|
|
|
|
Me.Pagos = Pagos
|
|
End If
|
|
End If
|
|
End Sub
|
|
Private Function ValorXML(n As XmlNode, Campo As String, Optional Retorno As String = "") As String
|
|
Dim o As XmlNode = n.Attributes.Cast(Of XmlAttribute)().SingleOrDefault(Function(a) String.Compare(a.Name, Campo, True) = 0)
|
|
If o Is Nothing Then
|
|
Return Retorno
|
|
Else
|
|
Return o.Value
|
|
End If
|
|
End Function
|
|
Private Function CaratecteresvalidosFolio(ByVal Folio As String) As String
|
|
Dim Respuesta As String = ""
|
|
|
|
'For Each c As Char In Folio.ToArray()
|
|
|
|
' If (c >= 48 AndAlso c <= 57) OrElse (c >= 65 AndAlso c <= 90) OrElse (c >= 97 AndAlso c <= 122) Then
|
|
' Respuesta += c
|
|
' End If
|
|
'Next
|
|
Return Respuesta
|
|
End Function
|
|
|
|
'Private Sub CargaDesdeString(StrFuente As String)
|
|
' Dim XMLCargaExistosa As Boolean = False
|
|
' Dim XMlStr As String = StrFuente.Replace("<br>", "").Replace("<", "").Replace("o;?", "")
|
|
' Dim XMLDoc As New XmlDocument
|
|
' Try
|
|
' XMLDoc.LoadXml(XMlStr)
|
|
' XMLCargaExistosa = True
|
|
' Catch ex As Exception
|
|
' GuardaLog("Error al intentar leer . Error:" & ex.ToString())
|
|
' 'Errores.AppendLine("Error al intentar leer el XML. Error:" & ex.ToString())
|
|
' XMLCargaExistosa = False
|
|
' End Try
|
|
|
|
' If XMLCargaExistosa Then
|
|
' CargaComprobanteXML(XMLDoc)
|
|
' End If
|
|
|
|
'End Sub
|
|
Public Function CargaComprobanteXML(StrFuente As String, DirectorioEmpresa As String, RFCEmpresa As String, CveEmpresa As Integer, Registrar As Boolean, ByRef rowLog As DataRow, NombreArchivo As String, Optional Validada As Integer = 0) As Factura
|
|
|
|
|
|
Dim SeValido As Boolean = False
|
|
Dim XMLCargaExistosa As Boolean = False
|
|
Dim XMlStr As String = StrFuente.Replace("<br>", "").Replace("<", "").Replace("o;?", "")
|
|
Dim XMLDoc As New XmlDocument
|
|
|
|
Try
|
|
XMLDoc.LoadXml(XMlStr)
|
|
XMLCargaExistosa = True
|
|
Catch ex As Exception
|
|
GuardaLogAD("Error al intentar leer . Error:" & ex.ToString(), ArchivoLog)
|
|
'Errores.AppendLine("Error al intentar leer el XML. Error:" & ex.ToString())
|
|
XMLCargaExistosa = False
|
|
End Try
|
|
|
|
If Not XMLCargaExistosa Then
|
|
rowLog("Motivo") = $"Error extructura XML archivo {NombreArchivo}"
|
|
Return Nothing
|
|
End If
|
|
|
|
Dim nodo As XmlNode = XMLDoc.DocumentElement
|
|
Dim Fact As Factura = New Factura()
|
|
Fact.Serie = ValorXML(nodo, "serie")
|
|
|
|
Dim StrCFDIVersion As String = ValorXML(nodo, "version")
|
|
|
|
Fact.Version = StrCFDIVersion
|
|
|
|
Fact.Folio = ValorXML(nodo, "folio")
|
|
Fact.Fecha = ValorXML(nodo, "fecha").ToDate
|
|
Fact.SubTotal = ValorXML(nodo, "subTotal").ToDecimal
|
|
Fact.Total = ValorXML(nodo, "total").ToDecimal
|
|
Fact.Descuento = ValorXML(nodo, "descuento").ToDecimal
|
|
Fact.Moneda = ValorXML(nodo, "Moneda")
|
|
Fact.CveMoneda = ClsPaginas.GlobalDTMonedas().FiltroPrimeroValor("CveMoneda", $" AbreviaturaSAT = '{Fact.Moneda}' ").ToEntero
|
|
Fact.TipoComprobante = ValorXML(nodo, "tipoDeComprobante")
|
|
Fact.TipoCambio = ValorXML(nodo, "TipoCambio", "1").ToDecimal
|
|
Fact.noCertificado = ValorXML(nodo, "NoCertificado")
|
|
Fact.FormaDePago = ValorXML(nodo, "formaDePago")
|
|
Fact.condicionesDePago = ValorXML(nodo, "condicionesDePago", "")
|
|
Fact.NumCtaPagoNumCtaPago = ValorXML(nodo, "NumCtaPago", "")
|
|
|
|
If Fact.Version = "3.3" Or Fact.Version = "4.0" Then
|
|
Dim drm As DataRow = ClsPaginas.GlobalDTVtaMetodoPago.FiltroPrimero(String.Format("ClaveMetodoPagoSAT = '{0}'", ValorXML(nodo, "MetodoPago")))
|
|
If drm IsNot Nothing Then
|
|
Fact.MetododePago = drm("MetodoPagoSAT").ToString
|
|
End If
|
|
End If
|
|
|
|
Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable)
|
|
Dim Prefijo As String = If(XMLDoc.DocumentElement.Prefix = "", "cfd", XMLDoc.DocumentElement.Prefix)
|
|
Dim cfdVer As String = ""
|
|
|
|
If StrCFDIVersion = "3.2" Then
|
|
Prefijo = "cfd"
|
|
cfdVer = "http://www.sat.gob.mx/cfd/2"
|
|
ElseIf StrCFDIVersion = "3.3" Then
|
|
cfdVer = "http://www.sat.gob.mx/cfd/3"
|
|
Else ' se considera que es la version 4.0
|
|
cfdVer = "http://www.sat.gob.mx/cfd/4"
|
|
End If
|
|
|
|
namespaces.AddNamespace(Prefijo, cfdVer)
|
|
namespaces.AddNamespace("aerolineas", "http://www.sat.gob.mx/aerolineas")
|
|
namespaces.AddNamespace("tfd", "http://www.sat.gob.mx/TimbreFiscalDigital")
|
|
namespaces.AddNamespace("implocal", "http://www.sat.gob.mx/implocal")
|
|
namespaces.AddNamespace("registrofiscal", "http://www.sat.gob.mx/registrofiscal")
|
|
|
|
Fact.sUPPrefijo = Prefijo
|
|
|
|
If StrCFDIVersion = "3.2" Then
|
|
|
|
For i As Integer = 0 To XMLDoc.DocumentElement.ChildNodes(2).ChildNodes.Count - 1
|
|
nodo = XMLDoc.DocumentElement.ChildNodes(2).ChildNodes(i)
|
|
Fact.AddPS(Convert.ToDouble(nodo.Attributes.GetNamedItem("cantidad").Value), nodo.Attributes.GetNamedItem("unidad").Value, nodo.Attributes.GetNamedItem("descripcion").Value, Convert.ToDouble(nodo.Attributes.GetNamedItem("valorUnitario").Value), 0, Convert.ToDouble(nodo.Attributes.GetNamedItem("importe").Value))
|
|
Next
|
|
|
|
Try
|
|
|
|
Dim nodosEmisor = XMLDoc.DocumentElement.ChildNodes.Cast(Of XmlNode)().FirstOrDefault(Function(n) n.Name.Equals("cfdi:Emisor", StringComparison.OrdinalIgnoreCase))
|
|
|
|
Dim nodoEmisor As XmlNode = nodosEmisor
|
|
|
|
Fact.EmiRFC = ValorXML(nodoEmisor, "rfc", "")
|
|
Fact.EmiNombre = ValorXML(nodoEmisor, "nombre", "")
|
|
|
|
nodoEmisor = nodosEmisor.ChildNodes(0)
|
|
Fact.DomFisCalle = ValorXML(nodoEmisor, "calle", "")
|
|
Fact.DomFisNoExt = ValorXML(nodoEmisor, "noExterior", "")
|
|
Fact.DomFisCol = ValorXML(nodoEmisor, "colonia", "")
|
|
Fact.DomFisCP = ValorXML(nodoEmisor, "codigoPostal", "")
|
|
Fact.DomFisMun = ValorXML(nodoEmisor, "municipio", "")
|
|
Fact.DomFisLoc = ValorXML(nodoEmisor, "localidad", "")
|
|
Fact.DomFisEst = ValorXML(nodoEmisor, "estado", "")
|
|
Fact.DomFisPais = ValorXML(nodoEmisor, "pais", "")
|
|
|
|
nodoEmisor = nodosEmisor.ChildNodes(1)
|
|
Fact.ExpEnCalle = ValorXML(nodoEmisor, "calle", "")
|
|
Fact.ExpEnNoExt = ValorXML(nodoEmisor, "noExterior", "")
|
|
Fact.ExpEnCol = ValorXML(nodoEmisor, "colonia", "")
|
|
Fact.ExpEnCP = ValorXML(nodoEmisor, "codigoPostal", "")
|
|
Fact.ExpEnMun = ValorXML(nodoEmisor, "municipio", "")
|
|
Fact.ExpEnLoc = ValorXML(nodoEmisor, "localidad", "")
|
|
Fact.ExpEnEst = ValorXML(nodoEmisor, "estado", "")
|
|
Fact.ExpEnPais = ValorXML(nodoEmisor, "pais", "")
|
|
|
|
nodoEmisor = nodoEmisor.ChildNodes(2)
|
|
Fact.Regimen = ValorXML(nodo, "Regimen", "")
|
|
Catch ex As Exception
|
|
Throw New Exception($"Error CargaEmisorXML - {ex.Message} - {ex.StackTrace}")
|
|
End Try
|
|
|
|
Try
|
|
Dim nodosReceptor = XMLDoc.DocumentElement.ChildNodes.Cast(Of XmlNode)().FirstOrDefault(Function(n) n.Name.Equals("cfdi:Receptor", StringComparison.OrdinalIgnoreCase))
|
|
|
|
Dim nodoReceptor As XmlNode = nodosReceptor
|
|
Fact.RecRfc = ValorXML(nodoReceptor, "rfc", "")
|
|
Fact.RecNombre = ValorXML(nodoReceptor, "nombre", "")
|
|
|
|
nodoReceptor = nodosReceptor.ChildNodes(0)
|
|
Fact.DomRecCalle = ValorXML(nodoReceptor, "calle", "")
|
|
Fact.DomRecFisNoExt = ValorXML(nodoReceptor, "noExterior", "")
|
|
Fact.DomRecFisNoInt = ValorXML(nodoReceptor, "noInterior", "")
|
|
Fact.DomRecCol = ValorXML(nodoReceptor, "colonia", "")
|
|
Fact.DomRecCP = ValorXML(nodoReceptor, "codigoPostal", "")
|
|
Fact.DomRecMun = ValorXML(nodoReceptor, "municipio", "")
|
|
Fact.DomRecLoc = ValorXML(nodoReceptor, "localidad", "")
|
|
Fact.DomRecEst = ValorXML(nodoReceptor, "estado", "")
|
|
Fact.DomRecPais = ValorXML(nodoReceptor, "pais", "")
|
|
Catch ex As Exception
|
|
Throw New Exception($"Error CargaReceptorXML - {ex.Message} - {ex.StackTrace}")
|
|
End Try
|
|
|
|
|
|
ElseIf StrCFDIVersion = "3.3" OrElse StrCFDIVersion = "4.0" Then
|
|
Try
|
|
Dim nodos = XMLDoc.DocumentElement.ChildNodes.Cast(Of XmlNode)().Where(Function(n) n.Name.Equals("cfdi:Conceptos", StringComparison.OrdinalIgnoreCase)).FirstOrDefault().ChildNodes
|
|
|
|
For Each item As XmlNode In nodos
|
|
Dim cantidad = Convert.ToDouble(item.Attributes.Cast(Of XmlAttribute)().Where(Function(n) n.Name.Equals("cantidad", StringComparison.OrdinalIgnoreCase)).FirstOrDefault().Value)
|
|
Dim unidad = item.Attributes.Cast(Of XmlAttribute)().Where(Function(n) n.Name.Equals("ClaveUnidad", StringComparison.OrdinalIgnoreCase)).FirstOrDefault().Value
|
|
Dim descripcion = item.Attributes.Cast(Of XmlAttribute)().Where(Function(n) n.Name.Equals("descripcion", StringComparison.OrdinalIgnoreCase)).FirstOrDefault().Value
|
|
Dim valorUnitario = Convert.ToDouble(item.Attributes.Cast(Of XmlAttribute)().Where(Function(n) n.Name.Equals("valorUnitario", StringComparison.OrdinalIgnoreCase)).FirstOrDefault().Value)
|
|
Dim importe = Convert.ToDouble(item.Attributes.Cast(Of XmlAttribute)().Where(Function(n) n.Name.Equals("importe", StringComparison.OrdinalIgnoreCase)).FirstOrDefault().Value)
|
|
|
|
Fact.AddPS(cantidad, unidad, descripcion, valorUnitario, 0, importe)
|
|
Next
|
|
Catch ex As Exception
|
|
Throw New Exception($"Error CargaConceptosXML - {ex.Message} - {ex.StackTrace}")
|
|
End Try
|
|
End If
|
|
|
|
|
|
|
|
If Fact.TipoComprobante.ToUpper = "E" AndAlso (Fact.Version.Contiene("3.3", "4.0")) Then
|
|
Dim UUIDS As String = ""
|
|
|
|
Dim UUIDSLista As New List(Of String)
|
|
Dim nodeCFDIRelacionados As XmlNode
|
|
nodeCFDIRelacionados = XMLDoc.SelectSingleNode(String.Format("//{0}:CfdiRelacionados", Prefijo), namespaces)
|
|
|
|
If nodeCFDIRelacionados IsNot Nothing Then
|
|
For Each CFDIRelacionados As XmlNode In nodeCFDIRelacionados
|
|
UUIDSLista.Add("" & CFDIRelacionados.Attributes("UUID").Value.ToString & "")
|
|
Next
|
|
End If
|
|
End If
|
|
|
|
Dim node As XmlNode
|
|
node = XMLDoc.SelectSingleNode(String.Format("//{0}:Emisor", Prefijo), namespaces)
|
|
|
|
If node IsNot Nothing Then
|
|
Fact.EmisorRFC = ValorXML(node, "RFC")
|
|
Fact.EmisorNombre = ValorXML(node, "Nombre")
|
|
End If
|
|
|
|
node = XMLDoc.SelectSingleNode(String.Format("//{0}:Receptor", Prefijo), namespaces)
|
|
|
|
If node IsNot Nothing Then
|
|
Fact.ReceptorRFC = ValorXML(node, "RFC")
|
|
End If
|
|
|
|
node = XMLDoc.SelectSingleNode(String.Format("//{0}:Impuestos", Prefijo), namespaces)
|
|
If node IsNot Nothing AndAlso node.ChildNodes.Count > 0 Then
|
|
Dim nodeRetenciones As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Comprobante/{0}:Impuestos/{0}:Retenciones/{0}:Retencion", Prefijo), namespaces)
|
|
|
|
If Fact.Version.Contiene("3.3", "4.0") Then
|
|
|
|
For Each retencion As XmlNode In nodeRetenciones
|
|
If retencion.Attributes("Impuesto").Value = "002" Then Fact.RetencionIVA += retencion.Attributes("Importe").Value.ToDecimal
|
|
If retencion.Attributes("Impuesto").Value = "001" Then Fact.RetencionISR += retencion.Attributes("Importe").Value.ToDecimal
|
|
Next
|
|
|
|
Else
|
|
|
|
For Each retencion As XmlNode In nodeRetenciones
|
|
If retencion.Attributes("impuesto").Value = "IVA" Then Fact.RetencionIVA += retencion.Attributes("importe").Value.ToDecimal
|
|
If retencion.Attributes("impuesto").Value = "ISR" Then Fact.RetencionISR += retencion.Attributes("importe").Value.ToDecimal
|
|
Next
|
|
End If
|
|
|
|
Dim nodeTraslados As XmlNodeList = XMLDoc.SelectNodes(String.Format("//{0}:Comprobante/{0}:Impuestos/{0}:Traslados/{0}:Traslado", Prefijo), namespaces)
|
|
|
|
If Fact.Version.Contiene("3.3", "4.0") Then
|
|
|
|
For Each traslado As XmlNode In nodeTraslados
|
|
|
|
If traslado.Attributes("Importe") IsNot Nothing Then
|
|
If traslado.Attributes("Impuesto").Value = "002" Then Fact.TrasladoIVA += traslado.Attributes("Importe").Value.ToDecimal
|
|
If traslado.Attributes("Impuesto").Value = "003" Then Fact.TrasladoIEPS += traslado.Attributes("Importe").Value.ToDecimal
|
|
End If
|
|
Next
|
|
Else
|
|
|
|
For Each traslado As XmlNode In nodeTraslados
|
|
If traslado.Attributes("Importe") IsNot Nothing Then
|
|
If traslado.Attributes("impuesto").Value = "IVA" Then Fact.TrasladoIVA += traslado.Attributes("importe").Value.ToDecimal
|
|
|
|
If traslado.Attributes("impuesto").Value = "IEPS" Then Fact.TrasladoIEPS += traslado.Attributes("importe").Value.ToDecimal
|
|
End If
|
|
Next
|
|
End If
|
|
|
|
End If
|
|
|
|
Dim nodeComp As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Complemento", Prefijo), namespaces)
|
|
If nodeComp IsNot Nothing AndAlso nodeComp.ChildNodes.Count > 0 Then
|
|
|
|
Dim nodeTFD As XmlNode = nodeComp.SelectSingleNode(String.Format("//{0}:TimbreFiscalDigital", "tfd"), namespaces)
|
|
Fact.UUID = ValorXML(nodeTFD, "UUID", "")
|
|
|
|
Dim nodeRF As XmlNode = nodeComp.SelectSingleNode(String.Format("//{0}:CFDIRegistroFiscal ", "registrofiscal"), namespaces)
|
|
If nodeRF IsNot Nothing Then
|
|
Fact.Folio = ValorXML(nodeRF, "folio").TrimStart("0"c)
|
|
End If
|
|
End If
|
|
|
|
If Fact.TipoComprobante = "P" Then
|
|
CargaPagos(XMLDoc, Fact)
|
|
End If
|
|
|
|
rowLog("Serie") = Fact.Serie
|
|
rowLog("Folio") = Fact.Folio
|
|
rowLog("Fecha") = Fact.Fecha
|
|
rowLog("Proveedor") = Fact.EmisorNombre
|
|
rowLog("Importe") = Fact.Total
|
|
rowLog("Motivo") = ""
|
|
|
|
rowLog("RFCde") = Fact.EmisorRFC
|
|
rowLog("Estatus") = 0
|
|
rowLog("Tipo") = Fact.TipoComprobante
|
|
|
|
|
|
|
|
If Registrar Then
|
|
|
|
If Fact.ReceptorRFC = RFCEmpresa Then
|
|
|
|
Fact.Validada = Validada
|
|
|
|
Dim ObjCompra As New ClsCompras
|
|
Dim Correcto As Boolean = False
|
|
|
|
ObjCompra.IniciaTransacSQL()
|
|
|
|
Fact.RespuestaInsert = ObjCompra.AddFactura(Fact.Serie, Fact.Folio, Fact.Fecha, Fact.EmisorNombre, Fact.EmisorRFC, Fact.SubTotal, Fact.TrasladoIVA, Fact.Total, Fact.UUID, Fact.ReceptorRFC, "", "", Fact.Version, Fact.Descuento, Fact.TipoCambio, Fact.Validada, CveEmpresa, Fact.sUPPrefijo, Fact.TipoComprobante, Fact.Moneda, Fact.MetododePago, 3, Fact.Version, Fact.IEPS, Fact.RetencionIVA, Fact.RetencionISR)
|
|
|
|
If Fact.RespuestaInsert >= 0 Then
|
|
|
|
rowLog("Estatus") = 1
|
|
|
|
Dim Destino As String = $"{DirectorioEmpresa}\Compras\"
|
|
|
|
Try
|
|
If Not Directory.Exists(Destino & Fact.EmisorRFC) Then
|
|
Directory.CreateDirectory(Destino & Fact.EmisorRFC)
|
|
End If
|
|
|
|
Select Case Fact.RespuestaInsert
|
|
Case 0
|
|
Dim RRutaDestino As String = String.Format("{0}{1}\{2}.xml", Destino, Fact.EmisorRFC, ObjCompra.CveFactura)
|
|
ModExtensiones.GuardaLogAD(String.Format(" '--------{0} Compra ya insertada : {1}{2} - {3}", 1, Fact.Serie, Fact.Folio, RRutaDestino), ArchivoLog)
|
|
|
|
File.WriteAllText(RRutaDestino, StrFuente, UTF8Encoding.UTF8)
|
|
'ObjCompra.UpdateArchivo(ObjCompra.CveFactura, "XML")
|
|
ModExtensiones.GuardaLogAD(" '--------XML Actualizado ", ArchivoLog)
|
|
rowLog("Motivo") = $"Ya registrado {Fact.Serie}-{Fact.Folio} se actualiza XML."
|
|
|
|
Correcto = True
|
|
Exit Select
|
|
|
|
Case 1
|
|
|
|
Dim StrMover As String = ""
|
|
Try
|
|
File.WriteAllText(String.Format("{0}{1}\{2}.xml", Destino, Fact.EmisorRFC, ObjCompra.CveFactura), StrFuente, UTF8Encoding.UTF8)
|
|
' ObjCompra.UpdateArchivo(ObjCompra.CveFactura, "XML")
|
|
ModExtensiones.GuardaLogAD($" '-------- XML Guardado Factura: {Fact.Serie}-{Fact.Folio} UUID: {Fact.UUID} , RFC Emisor: {Fact.EmisorRFC}", ArchivoLog)
|
|
|
|
' Si se movieron los dos archivos, los marca como correcto
|
|
If File.Exists(String.Format("{0}{1}\{2}.xml", Destino, Fact.EmisorRFC, ObjCompra.CveFactura)) Then
|
|
Correcto = True
|
|
Else
|
|
Correcto = False
|
|
End If
|
|
|
|
ModExtensiones.GuardaLogAD(" '++++++++ Compra Insertada :" & Fact.Serie & Fact.Folio & " - Correcto:" & If(Correcto, "Si", "No" & " Obs: "), ArchivoLog)
|
|
rowLog("Motivo") = $"Agregado {Fact.Serie}-{Fact.Folio}"
|
|
|
|
Catch ex As Exception
|
|
StrMover = ex.Message
|
|
Correcto = False
|
|
ModExtensiones.GuardaLogAD(" '++++++++ Compra no Insertada :" & Fact.Serie & Fact.Folio & " - Correcto:" & If(Correcto, "Si", "No" & " Obs: ") & StrMover, ArchivoLog)
|
|
rowLog("Motivo") = $"Error al agregar {Fact.Serie}-{Fact.Folio}"
|
|
End Try
|
|
|
|
Exit Select
|
|
End Select
|
|
|
|
Catch ex As Exception
|
|
Correcto = True
|
|
GuardaLogAD(ex.ToString(), ArchivoLog)
|
|
End Try
|
|
|
|
|
|
ElseIf Fact.RespuestaInsert = 0 AndAlso Fact.CveFactura > 0 Then
|
|
'FIXME OIC
|
|
Else
|
|
rowLog("Motivo") = $"RFC ""{Fact.ReceptorRFC}"" Error al insertar"
|
|
End If
|
|
|
|
|
|
If Correcto Then
|
|
ObjCompra.Commit()
|
|
Fact.CveFactura = ObjCompra.CveFactura
|
|
Fact.ArchivoXML = $"{ObjCompra.CveFactura}.xml"
|
|
Else
|
|
ObjCompra.RollBack()
|
|
End If
|
|
|
|
ObjCompra.Dispose()
|
|
|
|
Else
|
|
ModExtensiones.GuardaLogAD($" '++++++++ Compra RFC Distinto RFC Empresa: {RFCEmpresa}, RFC XML: {Fact.ReceptorRFC} ", ArchivoLog)
|
|
rowLog("Motivo") = "RFC Distinto"
|
|
rowLog("Motivo") = $"RFC ""{Fact.ReceptorRFC}"" Incorrecto"
|
|
End If
|
|
|
|
End If
|
|
|
|
|
|
Return Fact
|
|
End Function
|
|
|
|
|
|
|
|
|
|
|
|
Public Function GeneraPDF(UsuarioActual As Usuario, ByVal Ruta As String, ByVal Fact As Factura, DirectorioEmpresa As String, Guardar As Boolean) As Boolean
|
|
Dim RutaXML As String = String.Empty
|
|
Dim RutaPDF As String = String.Empty
|
|
Dim Retorno As Boolean = False
|
|
Try
|
|
Dim XMLDoc As New XmlDocument()
|
|
Dim TmpArchivoPDF As String = $"{Ruta}\Temp\Facturas\{Path.GetFileNameWithoutExtension(Fact.ArchivoXML)}-ttt.pdf"
|
|
Dim TmpArchivoQR As String = $"{Ruta}\Temp\Facturas\{Path.GetFileNameWithoutExtension(Fact.ArchivoXML)}-ttt.jpg"
|
|
Dim ArchivoXML As String = String.Format("{0}\Compras\{2}\{1}", DirectorioEmpresa, Fact.ArchivoXML, Fact.EmisorRFC)
|
|
Dim ArchivoPDF As String = String.Format("{0}\Compras\{2}\{1}.pdf", DirectorioEmpresa, Fact.CveFactura, Fact.EmisorRFC)
|
|
Dim dtotal As Decimal = If(Fact.Total <= 0.0D, 0.0001D, Fact.Total)
|
|
Dim cfdi As New RVCFDI33.GeneraCFDI()
|
|
|
|
Try
|
|
Dim b As Byte() = cfdi.ConvertirQrCode(String.Format("?re={0}&rr={1}&tt={2}&id={3}", Fact.EmisorRFC, Fact.ReceptorRFC, String.Format("{0,12:F6}", dtotal).Trim(), Fact.UUID))
|
|
File.WriteAllBytes(TmpArchivoQR, b)
|
|
Catch ex As Exception
|
|
ModExtensiones.GuardaLogAD(ex.Message, ArchivoLog)
|
|
End Try
|
|
|
|
If System.IO.File.Exists(TmpArchivoQR) Then
|
|
Dim TipoDocto As String = ""
|
|
If Fact.Version = "3.3" Or Fact.Version = "4.0" Then
|
|
Select Case Fact.TipoComprobante
|
|
Case "I"
|
|
TipoDocto = "Ing"
|
|
Case "E"
|
|
TipoDocto = "Egs"
|
|
Case "P"
|
|
TipoDocto = "Pag"
|
|
Case "T"
|
|
TipoDocto = "Tra"
|
|
Case Else
|
|
End Select
|
|
Else
|
|
TipoDocto = Fact.TipoComprobante
|
|
End If
|
|
|
|
'Dim DtPagos As DataTable = Nothing
|
|
'Dim DtDocumentosR As DataTable = Nothing
|
|
|
|
If Fact.TipoComprobante.Contiene("P", "T") Then
|
|
ModExtensiones.GuardaLogAD(String.Format(" '--------PDF Generar Tipo {0}", Fact.TipoComprobante), ArchivoLog)
|
|
Retorno = GenGoPdf(ArchivoXML, TmpArchivoPDF, DirectorioEmpresas)
|
|
Fact.ArchivoPDF = Path.GetFileName(TmpArchivoPDF)
|
|
|
|
Try
|
|
If Guardar Then
|
|
If File.Exists(ArchivoPDF) Then
|
|
File.Delete(ArchivoPDF)
|
|
End If
|
|
File.Move(TmpArchivoPDF, ArchivoPDF)
|
|
End If
|
|
Retorno = True
|
|
Catch ex As Exception
|
|
Retorno = False
|
|
End Try
|
|
|
|
Else
|
|
|
|
If (Fact.Version = "3.3" Or Fact.Version = "4.0") Then
|
|
Dim cxml As XmlSatCFDI = XmlSatCFDI.readXML(ArchivoXML, ArchivoLog)
|
|
ModExtensiones.GuardaLogAD(String.Format(" *********** UUID : {0} ***********", cxml.complemento.UUID), ArchivoLog)
|
|
cxml.ImprimirPDF(UsuarioActual, TmpArchivoPDF, DirectorioEmpresa, Fact.TipoComprobante)
|
|
Fact.ArchivoPDF = Path.GetFileName(TmpArchivoPDF)
|
|
|
|
Try
|
|
If Guardar Then
|
|
If File.Exists(ArchivoPDF) Then
|
|
File.Delete(ArchivoPDF)
|
|
End If
|
|
File.Move(TmpArchivoPDF, ArchivoPDF)
|
|
End If
|
|
Retorno = True
|
|
Catch ex As Exception
|
|
Retorno = False
|
|
End Try
|
|
|
|
Else
|
|
ModExtensiones.GuardaLogAD(String.Format(" *********** TFDUUID : {0} ***********", Fact.UUID), ArchivoLog)
|
|
Dim DomFiscal As String = String.Format("Domicilio Fiscal {0}{1} {2}{0}Col.{3}{0}CP. {4} {5},{6},{7}", vbCr, Fact.DomFisCalle, Fact.DomFisNoExt, Fact.DomFisCol, Fact.DomFisCP, Fact.DomFisMun, Fact.DomFisEst, Fact.DomFisPais)
|
|
|
|
If GeneraPDFNew(UsuarioActual, TmpArchivoPDF, Fact.UUID, Fact.SubTotal, Fact.Descuento, Fact.Total, Fact.TrasladoIVA.FormatoNumero(), Fact.Moneda, Fact.FormaDePago, Fact.TFDNoCertSAT, Fact.TFDFechaTimbrado.ToDate(), Fact.noCertificado,
|
|
Fact.DTConceptos, Fact.TFDSelloCFD, Fact.TFDSelloSAT, TmpArchivoQR, Fact.Serie + Fact.Folio, Fact.TipoComprobante, "", Fact.ReceptorRFC, Fact.RecNombre, Fact.DomRecCalle, Fact.DomRecCol, Fact.DomRecFisNoExt,
|
|
Fact.DomRecFisNoInt, Fact.DomRecCP, Fact.DomRecMun, Fact.DomRecEst, Fact.Regimen, Fact.condicionesDePago, Fact.MetododePago, Fact.NumCtaPagoNumCtaPago, DateTime.Now, Fact.DtPagos, Fact.DtDocumentosR, Fact.RetencionIVA,
|
|
Fact.RetencionISR, Fact.EmiNombre, Fact.EmiRFC, Fact.ReceptorNombre, DirectorioEmpresa, DomFiscal) Then
|
|
|
|
Fact.ArchivoPDF = Path.GetFileName(TmpArchivoPDF)
|
|
Retorno = True
|
|
|
|
If Guardar Then
|
|
|
|
End If
|
|
|
|
End If
|
|
|
|
|
|
|
|
End If
|
|
|
|
File.Delete(TmpArchivoQR)
|
|
|
|
End If
|
|
|
|
RutaPDF = TmpArchivoPDF
|
|
Else
|
|
Retorno = False
|
|
|
|
End If
|
|
'If DTConceptos IsNot Nothing Then DTConceptos.Dispose()
|
|
Catch ex As Exception
|
|
Dim MensajeError As String = "***********Ocurrio un error al generar el pdf: " & ex.Message & ""
|
|
|
|
If ex.InnerException Is Nothing Then
|
|
MensajeError &= "."
|
|
Else
|
|
MensajeError &= " - " & ex.InnerException.ToString()
|
|
End If
|
|
|
|
ModExtensiones.GuardaLogAD(MensajeError, ArchivoLog)
|
|
End Try
|
|
Return Retorno
|
|
End Function
|
|
|
|
|
|
Private Function GeneraPDFNew(UsuarioActual As Usuario, ByVal TmpArchivoPDF As String, ByVal FolioFiscal As String, ByVal SubTotal As Decimal, ByVal Descuento As Decimal, ByVal Total As Decimal, ByVal IVA As String, ByVal Moneda As String, ByVal FormaDePago As String,
|
|
ByVal NoSerieCertificado As String, ByVal FechaCertificacion As DateTime, ByVal NoSerieCertificadoContribuyente As String, ByVal DTConceptos As DataTable, ByVal SelloCFDi As String, ByVal SelloSAT As String,
|
|
ByVal CBB As String, ByVal Folio As String, ByVal TipodeComprobante As String, ByVal CadenaOriginalCFD As String, ByVal RFC As String, ByVal Cliente As String, ByVal Direccion As String, ByVal Colonia As String,
|
|
ByVal NoExt As String, ByVal NoInt As String, ByVal CP As String, ByVal Ciudad As String, ByVal Estado As String, ByVal Regimen As String, ByVal CondicionPago As String, ByVal MetodoPago As String, ByVal NumCtaPago As String,
|
|
ByVal fecha As DateTime, Optional ByVal DtPagos As DataTable = Nothing, Optional ByVal DtRelacionados As DataTable = Nothing, Optional ByVal RetIVA As Double = 0, Optional ByVal RetISR As Double = 0,
|
|
Optional EmiNombre As String = "", Optional EmiRFC As String = "", Optional NombreEmpresa As String = "", Optional DirectorioEmpresa As String = "", Optional DomFiscal As String = "") As Boolean
|
|
|
|
|
|
Dim RutaRDLC As String = If(TipodeComprobante = "Pag", "Grales\Formatos\CFDIPago.rdlc", "Grales\Formatos\CFDI.rdlc")
|
|
|
|
Dim Retorno As Boolean = False
|
|
Dim NombreArchivo As String = TmpArchivoPDF
|
|
Dim CadenaOriginal As String = "||1.0|" & FolioFiscal & "|" & FechaCertificacion.ToString("yyyy-MM-dd") & "T" & FechaCertificacion.ToString("HH:mm:ss") & "|" & SelloCFDi & "|" & NoSerieCertificado & "||"
|
|
Dim RutaFormato As String = RutaRDLC
|
|
|
|
|
|
Try
|
|
Dim Archivo As New System.IO.FileInfo(RutaFormato)
|
|
|
|
If Archivo.Exists Then
|
|
Dim parametros As New List(Of ReportParameter)()
|
|
parametros.Add(New ReportParameter("FolioFiscal", FolioFiscal))
|
|
parametros.Add(New ReportParameter("SubTotal", SubTotal.FormatoNumero()))
|
|
parametros.Add(New ReportParameter("Descuento", Descuento.FormatoNumero()))
|
|
parametros.Add(New ReportParameter("Total", Total.FormatoNumero()))
|
|
parametros.Add(New ReportParameter("IVA", IVA.FormatoNumero()))
|
|
parametros.Add(New ReportParameter("RetIVA", RetIVA.FormatoNumero()))
|
|
parametros.Add(New ReportParameter("RetISR", RetISR.FormatoNumero()))
|
|
parametros.Add(New ReportParameter("Moneda", Moneda))
|
|
parametros.Add(New ReportParameter("FormaDePago", FormaDePago))
|
|
parametros.Add(New ReportParameter("NoSerieCertificado", NoSerieCertificado))
|
|
parametros.Add(New ReportParameter("FechaCertificacion", FechaCertificacion.ToString("yyyy-MM-dd") & "T" & FechaCertificacion.ToString("HH:mm:ss")))
|
|
parametros.Add(New ReportParameter("NoSerieCertificadoContribuyente", NoSerieCertificadoContribuyente))
|
|
parametros.Add(New ReportParameter("SelloCFDi", SelloCFDi))
|
|
parametros.Add(New ReportParameter("SelloSAT", SelloSAT))
|
|
parametros.Add(New ReportParameter("CBB", String.Format("file:///{0}", CBB)))
|
|
parametros.Add(New ReportParameter("Folio", Folio))
|
|
parametros.Add(New ReportParameter("TipodeComprobante", TipodeComprobante.ToUpper()))
|
|
parametros.Add(New ReportParameter("CadenaOriginalCFD", CadenaOriginalCFD))
|
|
parametros.Add(New ReportParameter("RFC", RFC))
|
|
parametros.Add(New ReportParameter("Cliente", Cliente))
|
|
parametros.Add(New ReportParameter("Direccion", Direccion))
|
|
parametros.Add(New ReportParameter("Colonia", Colonia))
|
|
parametros.Add(New ReportParameter("NoExt", NoExt))
|
|
parametros.Add(New ReportParameter("NoInt", NoInt))
|
|
parametros.Add(New ReportParameter("CP", CP))
|
|
parametros.Add(New ReportParameter("Ciudad", Ciudad))
|
|
parametros.Add(New ReportParameter("Estado", Estado))
|
|
parametros.Add(New ReportParameter("Regimen", Regimen))
|
|
parametros.Add(New ReportParameter("CondicionPago", CondicionPago))
|
|
parametros.Add(New ReportParameter("MetodoPago", MetodoPago))
|
|
parametros.Add(New ReportParameter("NumCtaPago", NumCtaPago))
|
|
parametros.Add(New ReportParameter("fecha", fecha.ToString("yyyy-MM-dd") & "T" & fecha.ToString("HH:mm:ss")))
|
|
parametros.Add(New ReportParameter("Fiscal", DomFiscal))
|
|
parametros.Add(New ReportParameter("EmiNombre", EmiNombre))
|
|
parametros.Add(New ReportParameter("EmiRFC", EmiRFC))
|
|
parametros.Add(New ReportParameter("TotalLetra", ModExtensiones.Texto2Letras(Total)))
|
|
parametros.Add(New ReportParameter("Empresa", NombreEmpresa))
|
|
|
|
|
|
Dim listaDs As New List(Of ReportDataSource)
|
|
|
|
Dim rds1 As New ReportDataSource()
|
|
rds1.Name = "DsOC"
|
|
rds1.Value = DTConceptos
|
|
|
|
'MR.LocalReport.DataSources.Add(rds1)
|
|
listaDs.Add(rds1)
|
|
|
|
If DtPagos IsNot Nothing Then
|
|
Dim rds2 As New ReportDataSource()
|
|
rds2.Name = "DsPago"
|
|
rds2.Value = DtPagos
|
|
'MR.LocalReport.DataSources.Add(rds2)
|
|
listaDs.Add(rds2)
|
|
End If
|
|
|
|
If DtRelacionados IsNot Nothing Then
|
|
Dim rds3 As New ReportDataSource()
|
|
rds3.Name = "DsDocRelacionados"
|
|
rds3.Value = DtRelacionados
|
|
'MR.LocalReport.DataSources.Add(rds3)
|
|
listaDs.Add(rds3)
|
|
End If
|
|
|
|
|
|
Dim bytes As Byte() = Nothing
|
|
|
|
bytes = StreamPDF(UsuarioActual, RutaRDLC, listaDs, parametros, NombreArchivo:=NombreArchivo, Formato:="PDF")
|
|
If bytes IsNot Nothing Then
|
|
Using fs As New FileStream(NombreArchivo, FileMode.Create)
|
|
fs.Write(bytes, 0, bytes.Length)
|
|
fs.Close()
|
|
End Using
|
|
Retorno = True
|
|
Else
|
|
Retorno = False
|
|
End If
|
|
Else
|
|
ModExtensiones.GuardaLogAD("ERROR: No existe Formato Base", ArchivoLog)
|
|
End If
|
|
Catch ex As Exception
|
|
ModExtensiones.GuardaLogAD(String.Format("Ocurrio un Error al generar el reporte RLDC :" & ex.ToString()), ArchivoLog)
|
|
Retorno = False
|
|
End Try
|
|
Return Retorno
|
|
End Function
|
|
|
|
|
|
Private Sub CargaPagos(ByVal XMLDoc As XmlDocument, ByRef Fact As Factura)
|
|
|
|
Fact.Pagos.Clear()
|
|
|
|
Dim nodo = XMLDoc.DocumentElement
|
|
|
|
Dim Prefijo As String = If(String.IsNullOrEmpty(XMLDoc.DocumentElement.Prefix), "cfd", XMLDoc.DocumentElement.Prefix)
|
|
Dim cfdVer As String = "http://www.sat.gob.mx/cfd/3"
|
|
Dim namespaces As New XmlNamespaceManager(XMLDoc.NameTable)
|
|
|
|
Dim Version As String = ValorXML(nodo, "version").Replace("..", ".")
|
|
Dim PrefijoPagos As String = ""
|
|
|
|
If Prefijo.ToLower() <> "cfdi" Then
|
|
cfdVer = "http://www.sat.gob.mx/cfd/2"
|
|
End If
|
|
|
|
If Version = "3.3" Then
|
|
PrefijoPagos = "pago10"
|
|
namespaces.AddNamespace(PrefijoPagos, "http://www.sat.gob.mx/Pagos")
|
|
Prefijo = "cfdi"
|
|
cfdVer = "http://www.sat.gob.mx/cfd/3"
|
|
namespaces.AddNamespace(Prefijo, cfdVer)
|
|
ElseIf Version = "4.0" Then
|
|
PrefijoPagos = "pago20"
|
|
namespaces.AddNamespace(PrefijoPagos, "http://www.sat.gob.mx/Pagos20")
|
|
Prefijo = "cfdi"
|
|
cfdVer = "http://www.sat.gob.mx/cfd/4"
|
|
namespaces.AddNamespace(Prefijo, cfdVer)
|
|
End If
|
|
|
|
Dim nodeComp As XmlNode = XMLDoc.SelectSingleNode(String.Format("//{0}:Complemento", Prefijo), namespaces)
|
|
|
|
If Version = "3.3" OrElse Version = "4.0" Then
|
|
If nodeComp IsNot Nothing AndAlso nodeComp.ChildNodes.Count > 0 Then
|
|
Dim NodosNodePagos As XmlNodeList = nodeComp.SelectNodes($"//{PrefijoPagos}:Pago", namespaces)
|
|
|
|
If NodosNodePagos IsNot Nothing Then
|
|
Try
|
|
Dim nodePagos As XmlNode = nodeComp.SelectSingleNode($"//{PrefijoPagos}:Pagos", namespaces)
|
|
If Version = "3.3" Then
|
|
XMLNodosPagos = nodePagos.InnerXml.Replace("pago10:", "").Replace("pagos10:", "").Replace(PrefijoPagos & ":", "")
|
|
Else
|
|
XMLNodosPagos = nodePagos.InnerXml.Replace("pago20:", "").Replace("pagos20:", "").Replace(PrefijoPagos & ":", "")
|
|
End If
|
|
Catch ex As Exception
|
|
ModExtensiones.GuardaLogAD(ex.ToString(), ArchivoLog)
|
|
End Try
|
|
End If
|
|
|
|
Dim Pagos As New List(Of Pago)()
|
|
For Each nodePago As XmlNode In NodosNodePagos
|
|
Dim FechaPago As DateTime = DateTime.Now
|
|
Try
|
|
FechaPago = ValorXML(nodePago, "FechaPago").ToDate()
|
|
Catch e As Exception
|
|
End Try
|
|
|
|
Dim pago As New Pago()
|
|
pago.FechaPago = FechaPago
|
|
pago.FormaDePagoP = ValorXML(nodePago, "FormaDePagoP").ToString()
|
|
pago.MonedaP = ValorXML(nodePago, "MonedaP").ToString()
|
|
pago.Monto = ValorXML(nodePago, "Monto").ToString().ToDecimal()
|
|
|
|
Dim docs As New List(Of DoctoRelacionado)()
|
|
Dim NodosPagosRelacionados As XmlNodeList = nodePago.SelectNodes($"//{PrefijoPagos}:DoctoRelacionado", namespaces)
|
|
|
|
For Each docto As XmlNode In NodosPagosRelacionados
|
|
Dim idDoc = ValorXML(docto, "idDocumento")
|
|
Dim ImportePago = ValorXML(docto, "ImpPagado").ToDecimal()
|
|
Dim serie = ValorXML(docto, "Serie")
|
|
Dim Folio = ValorXML(docto, "Folio")
|
|
Dim MonedaDR = ValorXML(docto, "MonedaDR")
|
|
Dim MetodoDePagoDR = ValorXML(docto, "MetodoDePagoDR")
|
|
Dim NumParcialidad = ValorXML(docto, "NumParcialidad")
|
|
Dim ImpSaldoInsoluto = ValorXML(docto, "ImpSaldoInsoluto").ToDecimal()
|
|
Dim ImpSaldoAnt = ValorXML(docto, "ImpSaldoAnt").ToDecimal()
|
|
docs.Add(New DoctoRelacionado() With {
|
|
.idDocumento = idDoc,
|
|
.ImportePago = ImportePago,
|
|
.Serie = serie,
|
|
.Folio = Folio,
|
|
.MonedaDR = MonedaDR,
|
|
.MetodoDePagoDR = MetodoDePagoDR,
|
|
.NumParcialidad = NumParcialidad,
|
|
.ImpSaldoAnt = ImpSaldoAnt,
|
|
.ImpSaldoInsoluto = ImpSaldoInsoluto
|
|
})
|
|
Next
|
|
|
|
pago.Documentos = docs
|
|
Pagos.Add(pago)
|
|
Next
|
|
Fact.Pagos = Pagos
|
|
End If
|
|
End If
|
|
End Sub
|
|
|
|
|
|
Private Function GenGoPdf(ByVal XmlRutaArchivo As String, ByVal PDFRutaArchivo As String, DirectorioEmpresa As String) As Boolean
|
|
ModExtensiones.GuardaLogAD(" '--------PDF GenGoPdf Inicia ", ArchivoLog)
|
|
|
|
Dim Respuesta As Boolean = False
|
|
Dim RutaRDLC As String = $"{DirectorioEmpresa}\Grales\Formatos\ReciboDePagoGOPDF.rdlc" 'String.Format("{0}{1}", Extensiones.ApplicationParameter.RutaArchivos, "Empresas\Grales\Formatos\ReciboDePagoGOPDF.rdlc")
|
|
|
|
Dim Inicio As DateTime = DateTime.Now
|
|
Dim goPdf As New GoPdf.GoPdf()
|
|
Dim logotipo As Byte() = Nothing 'File.ReadAllBytes(@"C:\inetpub\WWWSIGGit\Empresas\119\Logo.jpg")
|
|
|
|
Try
|
|
Dim XmlString As String = File.ReadAllText(XmlRutaArchivo)
|
|
Dim result As Byte() = goPdf.ExportarPdf(XmlString, logotipo, "", RutaRDLC, New GoPdf.Modelos.DatosAdicionales() With {.DomicilioReceptor = ""})
|
|
|
|
Dim Fin As DateTime = DateTime.Now
|
|
If result IsNot Nothing Then
|
|
File.WriteAllBytes(PDFRutaArchivo, result)
|
|
Respuesta = True
|
|
ModExtensiones.GuardaLogAD($" '--------PDF GenGoPdf Generado", ArchivoLog)
|
|
Else
|
|
ModExtensiones.GuardaLogAD($" '--------PDF GenGoPdf Error se genero nulo \n RDLC: {RutaRDLC} Ruta Xml: {XmlRutaArchivo} Ruta PDF: {PDFRutaArchivo} \n MensajeError: {goPdf.MensajeError} CodigoError :{goPdf.CodigoError}", ArchivoLog)
|
|
End If
|
|
Catch ex As Exception
|
|
ModExtensiones.GuardaLogAD($" '--------PDF GenGoPdf Error {ex.Message} -- > {ex.StackTrace} \n RDLC: {RutaRDLC} Ruta Xml: {XmlRutaArchivo} Ruta PDF: {PDFRutaArchivo}", ArchivoLog)
|
|
End Try
|
|
|
|
ModExtensiones.GuardaLogAD(" '--------PDF GenGoPdf Finaliza ", ArchivoLog)
|
|
Return Respuesta
|
|
End Function
|
|
|
|
|
|
Public Function StreamPDF(UsuarioActual As Usuario, RutaReporte As String, DataSource As List(Of ReportDataSource), Parametros As List(Of ReportParameter), Optional NombreArchivo As String = "Reporte", Optional Formato As String = "PDF", Optional MR As ReportViewer = Nothing, Optional SubReportData As Modelos.MSubReportData = Nothing) As Byte()
|
|
'limpio ReportViwer
|
|
Dim sw As Stopwatch = Stopwatch.StartNew()
|
|
|
|
|
|
Dim Bytes As Byte() = Nothing
|
|
Dim CveUsuario As Integer = 0
|
|
Dim CveEmpresa As Integer = 0
|
|
Dim RutaEmpresa As String = ""
|
|
If UsuarioActual IsNot Nothing Then
|
|
CveUsuario = UsuarioActual.CveUsuario
|
|
CveEmpresa = UsuarioActual.CveEmpresa
|
|
RutaEmpresa = UsuarioActual.Empresa.Ruta
|
|
End If
|
|
|
|
Dim bdir As String = If(RutaReporte.Contains("Empresas"), ModExtensiones.DirectorioBaseEmpresas, AppDomain.CurrentDomain.BaseDirectory)
|
|
'TOMAR LA RUTA BASE PARA EL DIRECTORIO DE LA EMPRESA
|
|
If Not String.IsNullOrEmpty(RutaEmpresa) AndAlso Not RutaReporte.Contains("Grales") AndAlso Not RutaReporte.Contains("Contabilidad/Reportes/") AndAlso Not RutaReporte.Contains("Contabilidad/Reportes/") AndAlso Not RutaReporte.Contains("AC/Reportes/") Then
|
|
bdir = RutaEmpresa.Replace($"{CveEmpresa}/", "")
|
|
End If
|
|
RutaReporte.Replace("/", "\")
|
|
If Not RutaReporte.ToUpper().StartsWith(bdir.ToUpper()) Then
|
|
RutaReporte = String.Format("{0}{1}", bdir, RutaReporte)
|
|
End If
|
|
If EsProduccion Then
|
|
Dim wsreport As New WSRDLC2.WebServiceSoapClient
|
|
Dim params As New List(Of WSRDLC2.ReportParameter)
|
|
Dim reportobjects As New List(Of WSRDLC2.ReportObjects)
|
|
Dim jsonData As String = Nothing
|
|
If SubReportData IsNot Nothing Then
|
|
jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(SubReportData)
|
|
End If
|
|
Dim ds As New DataSet
|
|
For Each rpds As ReportDataSource In DataSource
|
|
If rpds.Value IsNot Nothing Then
|
|
If rpds.Value.GetType().ToString() = "System.Data.DataTable" Then
|
|
Dim dt As DataTable = DirectCast(rpds.Value, Data.DataTable)
|
|
dt = dt.Copy()
|
|
dt.TableName = rpds.Name
|
|
ds.Tables.Add(dt)
|
|
Else
|
|
Dim ojext As New WSRDLC2.ReportObjects
|
|
ojext.Name = rpds.Name
|
|
ojext.Value = rpds.Value
|
|
reportobjects.Add(ojext)
|
|
End If
|
|
Else
|
|
Dim dt As DataTable = New DataTable()
|
|
dt.TableName = If(String.IsNullOrEmpty(rpds.Name), "DataTable1", rpds.Name)
|
|
ds.Tables.Add(dt)
|
|
End If
|
|
Next
|
|
For Each rpds As ReportParameter In Parametros
|
|
Dim param As New WSRDLC2.ReportParameter
|
|
param.Name = rpds.Name
|
|
'SI ES TEXTO, QUITAR TABS Y OTROS ESPACIOS QUE DEN PROBLEMAS AL MANDAR LA PETICION
|
|
If rpds IsNot Nothing AndAlso rpds.Values IsNot Nothing AndAlso rpds.Values.Count > 0 AndAlso rpds.Values(0) IsNot Nothing AndAlso rpds.Values(0).GetType() = GetType(String) Then
|
|
param.Values = {rpds.Values(0).Replace(vbVerticalTab, "")}
|
|
Else
|
|
param.Values = {rpds.Values(0)}
|
|
End If
|
|
params.Add(param)
|
|
Next
|
|
Bytes = wsreport.StreamNEWPDFBytes(RutaReporte, ds, reportobjects.ToArray(), params.ToArray(), NombreArchivo, Formato, CveEmpresa, CveUsuario, jsonData)
|
|
wsreport = Nothing
|
|
params = Nothing
|
|
ds.Dispose() : ds = Nothing
|
|
Else
|
|
If IsNothing(MR) Then MR = New ReportViewer
|
|
Try
|
|
' MasterReporteador.LocalReport.DataSources.Clear()
|
|
For Each RDS As ReportDataSource In DataSource
|
|
MR.LocalReport.DataSources.Add(RDS)
|
|
Next
|
|
MR.LocalReport.ReportPath = RutaReporte
|
|
MR.ProcessingMode = ProcessingMode.Local
|
|
MR.LocalReport.EnableExternalImages = True
|
|
MR.LocalReport.SetParameters(Parametros)
|
|
MR.LocalReport.Refresh()
|
|
Dim Warnings As Warning() = Nothing
|
|
Dim StreamIds As String() = Nothing
|
|
Dim MimeType As String = Nothing
|
|
Dim Encoding As String = Nothing
|
|
Dim Extension As String = Nothing
|
|
Bytes = MR.LocalReport.Render(Formato, Nothing, MimeType, Encoding, Extension, StreamIds, Warnings)
|
|
Catch ex As Microsoft.Reporting.WebForms.ScriptManagerNotFoundException
|
|
GuardaLog($"Error: { If(ex.InnerException.Message IsNot Nothing, ex.InnerException.Message, ex.Message) } | Descripcion: {If(ex.InnerException IsNot Nothing AndAlso ex.InnerException.InnerException IsNot Nothing AndAlso ex.InnerException.InnerException.Message IsNot Nothing, ex.InnerException.InnerException.Message, If(ex.InnerException IsNot Nothing AndAlso ex.InnerException.Message IsNot Nothing, ex.InnerException.Message, "Sin descripcion"))} - Ruta {RutaReporte}")
|
|
'HAY QUE VALIDAR QUE LOS OBJETOS QUE SE USAN PARA GUARDAR LOG EXISTEN!!! IPP 14 AGOSTO 2017
|
|
'GuardaLog($"Error: {ex.InnerException.Message} | Descripcion: {If(ex.InnerException.InnerException IsNot Nothing, ex.InnerException.InnerException.Message, "Sin descripcion")} - Ruta {RutaReporte}")
|
|
Catch ex As Exception
|
|
GuardaLog($"Error: { If(ex.InnerException.Message IsNot Nothing, ex.InnerException.Message, ex.Message) } | Descripcion: {If(ex.InnerException IsNot Nothing AndAlso ex.InnerException.InnerException IsNot Nothing AndAlso ex.InnerException.InnerException.Message IsNot Nothing, ex.InnerException.InnerException.Message, If(ex.InnerException IsNot Nothing AndAlso ex.InnerException.Message IsNot Nothing, ex.InnerException.Message, "Sin descripcion"))} - Ruta {RutaReporte}")
|
|
'HAY QUE VALIDAR QUE LOS OBJETOS QUE SE USAN PARA GUARDAR LOG EXISTEN!!! IPP 14 AGOSTO 2017
|
|
'GuardaLog($"Error {ex.InnerException.Message} | Descripcion: {If(ex.InnerException.InnerException IsNot Nothing, ex.InnerException.InnerException.Message, "Sin descripcion")} - Ruta {RutaReporte}")
|
|
End Try
|
|
Try
|
|
MR.Dispose()
|
|
Catch ex As Exception
|
|
GuardaLog($"Error: { ex.ToString() }")
|
|
End Try
|
|
MR = Nothing
|
|
|
|
End If
|
|
sw.Stop()
|
|
If sw.Elapsed.TotalSeconds > 5 Then
|
|
GuardaLog($"Reporte:{RutaReporte} | Tiempo Renderizado Milisegundos: {sw.ElapsedMilliseconds},Total Segundos: {sw.Elapsed.TotalSeconds} ")
|
|
End If
|
|
Return Bytes
|
|
End Function
|
|
|
|
End Class
|
|
|
|
|
|
|
|
''' <summary>
|
|
''' Clase para contener los valores de un xml CFDI cambio norma
|
|
''' </summary>
|
|
Public Class XmlSatCFDI
|
|
Public Sub New(NombreArchivoLog As String)
|
|
comprobante = New CFDIComprobante()
|
|
emisor = New CFDIEmisor()
|
|
receptor = New CFDIReceptor()
|
|
complemento = New CFDIComplemento()
|
|
cFDIRelacionados = New List(Of CFDIRelacionado)()
|
|
conceptos = New List(Of CFDIConcepto)()
|
|
Impuestos = New List(Of CFDIImpuesto)()
|
|
ArchivoLog = NombreArchivoLog
|
|
End Sub
|
|
|
|
Public comprobante As CFDIComprobante
|
|
Public emisor As CFDIEmisor
|
|
Public receptor As CFDIReceptor
|
|
Public complemento As CFDIComplemento
|
|
Public cFDIRelacionados As List(Of CFDIRelacionado)
|
|
Public conceptos As List(Of CFDIConcepto)
|
|
Public Impuestos As List(Of CFDIImpuesto)
|
|
Public Property ArchivoLog As String = "Log"
|
|
|
|
Public Function GetConceptosforpdf() As List(Of CFDIConcepto_I)
|
|
Dim lcon As New List(Of CFDIConcepto_I)()
|
|
If conceptos IsNot Nothing Then
|
|
Dim _orden As Integer = 0
|
|
For Each item As CFDIConcepto In conceptos
|
|
_orden += 1
|
|
Dim con As New CFDIConcepto_I With {
|
|
.tipo = 1,
|
|
.orden = _orden,
|
|
.ClaveProdServ = item.ClaveProdServ,
|
|
.NoIdentificacion = item.NoIdentificacion,
|
|
.Cantidad = item.Cantidad,
|
|
.ClaveUnidad = item.ClaveUnidad,
|
|
.Unidad = item.Unidad,
|
|
.ValorUnitario = item.ValorUnitario,
|
|
.Importe = item.Importe,
|
|
.Descuento = item.Descuento,
|
|
.NumeroPedimento = item.NumeroPedimento,
|
|
.CuentaPredial = item.CuentaPredial,
|
|
.Descripcion = item.Descripcion
|
|
}
|
|
Dim index As Integer = 0
|
|
For Each Imp As CFDIConceptoImpuesto In item.Impuestos
|
|
index += 1
|
|
If index > 1 Then
|
|
lcon.Add(con)
|
|
con = New CFDIConcepto_I With {
|
|
.tipo = 2,
|
|
.orden = _orden
|
|
}
|
|
End If
|
|
|
|
con.Impuesto = Imp.ImpuestoTexto
|
|
con.Impuesto_Tipo = Imp.Tipo
|
|
con.Impuesto_Base = Imp.Base
|
|
con.Impuesto_TipoFactor = Imp.TipoFactor
|
|
con.Impuesto_TasaOCuota = Imp.TasaOCuota
|
|
con.Impuesto_Importe = Imp.Importe
|
|
Next
|
|
lcon.Add(con)
|
|
Next
|
|
End If
|
|
|
|
Return lcon
|
|
End Function
|
|
|
|
Public Shared Function readXML(fileUrl As String, NombreArchivoLog As String) As XmlSatCFDI
|
|
Dim xmlCFDI As New XmlSatCFDI(NombreArchivoLog)
|
|
Dim canread As Boolean = True
|
|
' Keys
|
|
Dim keyComprobante As String = "cfdi:Comprobante"
|
|
Dim keyCfdiRelacionados As String = "cfdi:CfdiRelacionados"
|
|
Dim keyEmisor As String = "cfdi:Emisor"
|
|
Dim keyReceptor As String = "cfdi:Receptor"
|
|
Dim keyConceptos As String = "cfdi:Conceptos"
|
|
Dim keyImpuestos As String = "cfdi:Impuestos"
|
|
Dim keyComplemento As String = "cfdi:Complemento"
|
|
' Endkeys
|
|
Dim PrimerNivel As String() = {keyCfdiRelacionados, keyEmisor, keyReceptor, keyConceptos, keyImpuestos, keyComplemento}
|
|
|
|
' (canread = xtr.Read()) para evitar ciclos infinitos, todos los .Read() los guardo en la variable Canread y en los while reviso primero esta variable
|
|
If File.Exists(fileUrl) Then
|
|
Dim settings As New XmlReaderSettings()
|
|
settings.ConformanceLevel = ConformanceLevel.Fragment
|
|
settings.IgnoreWhitespace = True
|
|
settings.IgnoreComments = True
|
|
Using xtr As XmlReader = XmlReader.Create(fileUrl, settings)
|
|
While (InlineAssignHelper.Assign(canread, xtr.Read())) AndAlso Not (xtr.NodeType = XmlNodeType.Element AndAlso xtr.Name = keyComprobante)
|
|
'if (xtr.NodeType != XmlNodeType.Element) { while (xtr.Read() && xtr.NodeType != XmlNodeType.Element) { } }
|
|
End While
|
|
If xtr.NodeType = XmlNodeType.Element AndAlso xtr.Name = keyComprobante Then
|
|
Dim Nivel As Integer = xtr.Depth
|
|
Dim cont As Boolean = xtr.MoveToFirstAttribute()
|
|
While cont
|
|
Select Case xtr.Name.ToUpper()
|
|
Case "XMLNS:CFDI"
|
|
xmlCFDI.comprobante.xmlns_cfdi = xtr.Value
|
|
Case "XMLNS:XSI"
|
|
xmlCFDI.comprobante.xmlns_xsi = xtr.Value
|
|
Case "XSI:SCHEMALOCATION"
|
|
xmlCFDI.comprobante.xsi_schemaLocation = xtr.Value
|
|
Case "VERSION"
|
|
xmlCFDI.comprobante.Version = xtr.Value
|
|
Case "SERIE"
|
|
xmlCFDI.comprobante.Serie = xtr.Value
|
|
Case "FOLIO"
|
|
xmlCFDI.comprobante.Folio = xtr.Value
|
|
Case "FECHA"
|
|
xmlCFDI.comprobante.Fecha = xtr.Value
|
|
Case "MONEDA"
|
|
xmlCFDI.comprobante.Moneda = xtr.Value
|
|
Case "SUBTOTAL"
|
|
Dim SubTotal As Decimal = 0
|
|
Decimal.TryParse(xtr.Value, SubTotal)
|
|
xmlCFDI.comprobante.SubTotal = SubTotal
|
|
Case "TOTAL"
|
|
Dim Total As Decimal = 0
|
|
Decimal.TryParse(xtr.Value, Total)
|
|
xmlCFDI.comprobante.Total = Total
|
|
Case "DESCUENTO"
|
|
Dim Descuento As Decimal = 0
|
|
Decimal.TryParse(xtr.Value, Descuento)
|
|
xmlCFDI.comprobante.Descuento = Descuento
|
|
Case "TIPOCAMBIO"
|
|
Dim TipoCambio As Decimal = 0
|
|
Decimal.TryParse(xtr.Value, TipoCambio)
|
|
xmlCFDI.comprobante.TipoCambio = TipoCambio
|
|
Case "TIPODECOMPROBANTE"
|
|
xmlCFDI.comprobante.TipoDeComprobante = xtr.Value
|
|
Case "FORMAPAGO", "FORMADEPAGO"
|
|
xmlCFDI.comprobante.FormaPago = xtr.Value
|
|
Case "METODOPAGO", "METODODEPAGO"
|
|
xmlCFDI.comprobante.MetodoPago = xtr.Value
|
|
Case "CONDICIONESDEPAGO"
|
|
xmlCFDI.comprobante.CondicionesDePago = xtr.Value
|
|
Case "LUGAREXPEDICION"
|
|
xmlCFDI.comprobante.LugarExpedicion = xtr.Value
|
|
Case "CONFIRMACION"
|
|
xmlCFDI.comprobante.Confirmacion = xtr.Value
|
|
Case "NOCERTIFICADO"
|
|
xmlCFDI.comprobante.NoCertificado = xtr.Value
|
|
Case "SELLO"
|
|
xmlCFDI.comprobante.Sello = xtr.Value
|
|
Case "CERTIFICADO"
|
|
xmlCFDI.comprobante.Certificado = xtr.Value
|
|
End Select
|
|
cont = xtr.MoveToNextAttribute()
|
|
End While
|
|
|
|
cont = xtr.MoveToFirstAttribute()
|
|
While InlineAssignHelper.Assign(canread, xtr.Read()) AndAlso xtr.NodeType <> XmlNodeType.Element
|
|
End While
|
|
|
|
While canread AndAlso xtr.Depth > Nivel
|
|
If PrimerNivel.Contains(xtr.Name) Then
|
|
If xtr.NodeType = XmlNodeType.Element AndAlso xtr.Name = keyCfdiRelacionados Then
|
|
Dim cDepth As Integer = xtr.Depth
|
|
|
|
Dim TipoRelacion As String = Nothing
|
|
cont = xtr.MoveToFirstAttribute()
|
|
While cont
|
|
If xtr.Name.ToUpper() = "TIPORELACION" Then
|
|
TipoRelacion = xtr.Value
|
|
End If
|
|
cont = xtr.MoveToNextAttribute()
|
|
End While
|
|
|
|
While InlineAssignHelper.Assign(canread, xtr.Read()) AndAlso xtr.NodeType <> XmlNodeType.Element
|
|
End While
|
|
|
|
While canread AndAlso xtr.Depth > cDepth
|
|
If xtr.Name = "cfdi:CfdiRelacionado" Then
|
|
Dim cfdir As New CFDIRelacionado()
|
|
cfdir.TipoRelacion = TipoRelacion
|
|
cfdir.UUID = xtr.GetAttribute("UUID")
|
|
xmlCFDI.cFDIRelacionados.Add(cfdir)
|
|
End If
|
|
While InlineAssignHelper.Assign(canread, xtr.Read()) AndAlso xtr.NodeType <> XmlNodeType.Element
|
|
End While
|
|
End While
|
|
|
|
End If
|
|
|
|
If xtr.NodeType = XmlNodeType.Element AndAlso xtr.Name = keyEmisor Then
|
|
Dim curentNivel As Integer = xtr.Depth
|
|
cont = xtr.MoveToFirstAttribute()
|
|
While cont
|
|
Select Case xtr.Name.ToUpper()
|
|
Case "REGIMENFISCAL"
|
|
xmlCFDI.emisor.RegimenFiscal = xtr.Value
|
|
Case "NOMBRE"
|
|
xmlCFDI.emisor.Nombre = xtr.Value
|
|
Case "RFC"
|
|
xmlCFDI.emisor.Rfc = xtr.Value
|
|
End Select
|
|
cont = xtr.MoveToNextAttribute()
|
|
End While
|
|
|
|
While InlineAssignHelper.Assign(canread, xtr.Read()) AndAlso Not (xtr.NodeType = XmlNodeType.Element AndAlso curentNivel >= xtr.Depth)
|
|
End While 'continua hasta que no tenga nodos y (el nodo sea tipo elemento y este en el mismo nivel)
|
|
End If
|
|
|
|
If xtr.NodeType = XmlNodeType.Element AndAlso xtr.Name = keyReceptor Then
|
|
Dim curentNivel As Integer = xtr.Depth
|
|
cont = xtr.MoveToFirstAttribute()
|
|
While cont
|
|
Select Case xtr.Name.ToUpper()
|
|
Case "RFC"
|
|
xmlCFDI.receptor.Rfc = xtr.Value
|
|
Case "NOMBRE"
|
|
xmlCFDI.receptor.Nombre = xtr.Value
|
|
Case "RESIDENCIAFISCAL"
|
|
xmlCFDI.receptor.ResidenciaFiscal = xtr.Value
|
|
Case "NUMREGIDTRIB"
|
|
xmlCFDI.receptor.NumRegIdTrib = xtr.Value
|
|
Case "USOCFDI"
|
|
xmlCFDI.receptor.UsoCFDI = xtr.Value
|
|
End Select
|
|
cont = xtr.MoveToNextAttribute()
|
|
End While
|
|
|
|
While InlineAssignHelper.Assign(canread, xtr.Read()) AndAlso Not (xtr.NodeType = XmlNodeType.Element AndAlso curentNivel >= xtr.Depth)
|
|
End While 'continua hasta que no tenga nodos y (el nodo sea tipo elemento y este en el mismo nivel)
|
|
End If
|
|
|
|
If xtr.NodeType = XmlNodeType.Element AndAlso xtr.Name = keyConceptos Then
|
|
Dim cDepth As Integer = xtr.Depth
|
|
While InlineAssignHelper.Assign(canread, xtr.Read()) AndAlso xtr.NodeType <> XmlNodeType.Element
|
|
End While
|
|
|
|
While canread AndAlso xtr.Depth > cDepth
|
|
If xtr.Name = "cfdi:Concepto" Then
|
|
Dim cDepthb As Integer = xtr.Depth
|
|
Dim concepto As New CFDIConcepto()
|
|
|
|
cont = xtr.MoveToFirstAttribute()
|
|
While cont
|
|
Select Case xtr.Name.ToUpper()
|
|
Case "CLAVEPRODSERV"
|
|
concepto.ClaveProdServ = xtr.Value
|
|
Case "NOIDENTIFICACION"
|
|
concepto.NoIdentificacion = xtr.Value
|
|
Case "CANTIDAD"
|
|
concepto.Cantidad = xtr.Value
|
|
Case "CLAVEUNIDAD"
|
|
concepto.ClaveUnidad = xtr.Value
|
|
Case "UNIDAD"
|
|
concepto.Unidad = xtr.Value
|
|
Case "VALORUNITARIO"
|
|
Dim ValorUnitario As Decimal = 0
|
|
Decimal.TryParse(xtr.Value, ValorUnitario)
|
|
concepto.ValorUnitario = ValorUnitario
|
|
Case "IMPORTE"
|
|
Dim Importe As Decimal = 0
|
|
Decimal.TryParse(xtr.Value, Importe)
|
|
concepto.Importe = Importe
|
|
Case "DESCUENTO"
|
|
Dim DDescuento As Decimal = 0
|
|
Decimal.TryParse(xtr.Value, DDescuento)
|
|
concepto.Descuento = DDescuento
|
|
Case "DESCRIPCION"
|
|
concepto.Descripcion = xtr.Value
|
|
End Select
|
|
cont = xtr.MoveToNextAttribute()
|
|
End While
|
|
|
|
xtr.MoveToFirstAttribute()
|
|
While InlineAssignHelper.Assign(canread, xtr.Read()) AndAlso xtr.NodeType <> XmlNodeType.Element
|
|
End While
|
|
|
|
While canread AndAlso xtr.Depth > cDepthb
|
|
If xtr.NodeType = XmlNodeType.Element AndAlso xtr.Name = "cfdi:Impuestos" Then
|
|
Dim cDepthc As Integer = xtr.Depth
|
|
While InlineAssignHelper.Assign(canread, xtr.Read()) AndAlso xtr.NodeType <> XmlNodeType.Element
|
|
End While
|
|
|
|
While canread AndAlso xtr.Depth > cDepthc
|
|
If xtr.Name = "cfdi:Traslado" OrElse xtr.Name = "cfdi:Retencion" Then
|
|
Dim impuesto As New CFDIConceptoImpuesto()
|
|
impuesto.Impuesto = xtr.GetAttribute("Impuesto")
|
|
impuesto.Tipo = xtr.LocalName
|
|
Dim Base As Decimal = 0
|
|
Decimal.TryParse(xtr.GetAttribute("Base"), Base)
|
|
impuesto.Base = Base
|
|
impuesto.TipoFactor = xtr.GetAttribute("TipoFactor")
|
|
Dim tasaOCuota As Decimal = 0
|
|
Decimal.TryParse(xtr.GetAttribute("TasaOCuota"), tasaOCuota)
|
|
impuesto.TasaOCuota = If(impuesto.TipoFactor = "Tasa", (tasaOCuota * 100).ToString("N4"), xtr.GetAttribute("TasaOCuota"))
|
|
Dim ImImporte As Decimal = 0
|
|
Decimal.TryParse(xtr.GetAttribute("Importe"), ImImporte)
|
|
impuesto.Importe = ImImporte
|
|
|
|
concepto.Impuestos.Add(impuesto)
|
|
End If
|
|
While InlineAssignHelper.Assign(canread, xtr.Read()) AndAlso xtr.NodeType <> XmlNodeType.Element
|
|
End While
|
|
End While
|
|
Else
|
|
Dim rednew As Boolean = True
|
|
If xtr.NodeType = XmlNodeType.Element AndAlso xtr.Name = "cfdi:InformacionAduanera" Then
|
|
concepto.NumeroPedimento = xtr.GetAttribute("NumeroPedimento")
|
|
rednew = False
|
|
While InlineAssignHelper.Assign(canread, xtr.Read()) AndAlso xtr.NodeType <> XmlNodeType.Element
|
|
End While
|
|
End If
|
|
If xtr.NodeType = XmlNodeType.Element AndAlso xtr.Name = "cfdi:CuentaPredial" Then
|
|
concepto.CuentaPredial = xtr.GetAttribute("CuentaPredial")
|
|
rednew = False
|
|
While InlineAssignHelper.Assign(canread, xtr.Read()) AndAlso xtr.NodeType <> XmlNodeType.Element
|
|
End While
|
|
End If
|
|
If rednew Then
|
|
While InlineAssignHelper.Assign(canread, xtr.Read()) AndAlso xtr.NodeType <> XmlNodeType.Element
|
|
End While
|
|
End If
|
|
End If
|
|
End While
|
|
|
|
xmlCFDI.conceptos.Add(concepto)
|
|
End If
|
|
End While
|
|
End If
|
|
|
|
If xtr.NodeType = XmlNodeType.Element AndAlso xtr.Name = keyImpuestos Then
|
|
Dim cDepth As Integer = xtr.Depth
|
|
While InlineAssignHelper.Assign(canread, xtr.Read()) AndAlso xtr.NodeType <> XmlNodeType.Element
|
|
End While
|
|
|
|
While canread AndAlso xtr.Depth > cDepth
|
|
Dim impuest As New CFDIImpuesto()
|
|
If (xtr.Name = "cfdi:Traslado" OrElse xtr.Name = "cfdi:Retencion") AndAlso xmlCFDI.comprobante.Version IsNot Nothing Then
|
|
impuest.Tipo = If(xtr.LocalName = "Traslado", "Traslados", If(xtr.LocalName = "Retencion", "Retenciones", ""))
|
|
impuest.Impuesto = If(xmlCFDI.comprobante.Version = "3.3" OrElse xmlCFDI.comprobante.Version = "4.0", xtr.GetAttribute("Impuesto"), xtr.GetAttribute("impuesto"))
|
|
impuest.TipoFactor = xtr.GetAttribute("TipoFactor")
|
|
impuest.TasaOCuota = If(xmlCFDI.comprobante.Version = "3.3" OrElse xmlCFDI.comprobante.Version = "4.0", xtr.GetAttribute("TasaOCuota"), xtr.GetAttribute("tasa"))
|
|
Dim ImImporte As Decimal = 0
|
|
Decimal.TryParse(If(xmlCFDI.comprobante.Version = "3.3" OrElse xmlCFDI.comprobante.Version = "4.0", xtr.GetAttribute("Importe"), xtr.GetAttribute("importe")), ImImporte)
|
|
impuest.Importe = ImImporte
|
|
xmlCFDI.Impuestos.Add(impuest)
|
|
End If
|
|
While InlineAssignHelper.Assign(canread, xtr.Read()) AndAlso xtr.NodeType <> XmlNodeType.Element
|
|
End While
|
|
End While
|
|
End If
|
|
|
|
If xtr.NodeType = XmlNodeType.Element AndAlso xtr.Name = keyComplemento Then
|
|
Dim cDepth As Integer = xtr.Depth
|
|
While InlineAssignHelper.Assign(canread, xtr.Read()) AndAlso xtr.NodeType <> XmlNodeType.Element
|
|
End While
|
|
|
|
While canread AndAlso xtr.Depth > cDepth
|
|
If xtr.NodeType = XmlNodeType.Element AndAlso xtr.LocalName = "TimbreFiscalDigital" AndAlso xmlCFDI.comprobante.Version IsNot Nothing Then
|
|
xmlCFDI.complemento.xmlns_tfd = xtr.GetAttribute("xmlns:tfd")
|
|
xmlCFDI.complemento.xsi_schemaLocation = xtr.GetAttribute("xsi:schemaLocation")
|
|
xmlCFDI.complemento.Version = xtr.GetAttribute("Version")
|
|
xmlCFDI.complemento.UUID = xtr.GetAttribute("UUID")
|
|
xmlCFDI.complemento.FechaTimbrado = xtr.GetAttribute("FechaTimbrado")
|
|
xmlCFDI.complemento.RfcProvCertif = xtr.GetAttribute("RfcProvCertif")
|
|
xmlCFDI.complemento.SelloCFD = If(xmlCFDI.comprobante.Version = "3.3" OrElse xmlCFDI.comprobante.Version = "4.0", xtr.GetAttribute("SelloCFD"), xtr.GetAttribute("selloCFD"))
|
|
xmlCFDI.complemento.NoCertificadoSAT = If(xmlCFDI.comprobante.Version = "3.3", xtr.GetAttribute("NoCertificadoSAT"), xtr.GetAttribute("noCertificadoSAT"))
|
|
xmlCFDI.complemento.SelloSAT = If(xmlCFDI.comprobante.Version = "3.3" OrElse xmlCFDI.comprobante.Version = "4.0", xtr.GetAttribute("SelloSAT"), xtr.GetAttribute("selloSAT"))
|
|
End If
|
|
|
|
If xtr.NodeType = XmlNodeType.Element AndAlso xtr.LocalName = "Pagos" AndAlso xmlCFDI.comprobante.Version IsNot Nothing Then
|
|
While InlineAssignHelper.Assign(canread, xtr.Read()) AndAlso xtr.NodeType <> XmlNodeType.Element
|
|
End While
|
|
|
|
xmlCFDI.complemento.Pagos = New CFDIPago()
|
|
Dim depthpagos As Integer = xtr.Depth
|
|
Dim conts As Boolean = xtr.MoveToFirstAttribute()
|
|
While conts
|
|
Dim Base As Decimal = 0
|
|
Select Case xtr.Name.ToUpper()
|
|
Case "FECHAPAGO"
|
|
xmlCFDI.complemento.Pagos.FechaPago = xtr.Value
|
|
Case "FORMADEPAGOP"
|
|
xmlCFDI.complemento.Pagos.FormaDePagoP = xtr.Value
|
|
Case "FORMADEPAGOPTEXT"
|
|
xmlCFDI.complemento.Pagos.FormaDePagoPText = xtr.Value
|
|
Case "MONEDAP"
|
|
xmlCFDI.complemento.Pagos.MonedaP = xtr.Value
|
|
Case "MONTO"
|
|
Decimal.TryParse(xtr.Value, Base)
|
|
xmlCFDI.complemento.Pagos.Monto = Base
|
|
Case "TIPOCAMBIOP"
|
|
Decimal.TryParse(xtr.Value, Base)
|
|
xmlCFDI.complemento.Pagos.TipoCambioP = Base
|
|
Case "NUMOPERACION"
|
|
xmlCFDI.complemento.Pagos.NumOperacion = xtr.Value
|
|
Case "NOMBANCOORDEXT"
|
|
xmlCFDI.complemento.Pagos.NomBancoOrdExt = xtr.Value
|
|
Case "RFCEMISORCTAORD"
|
|
xmlCFDI.complemento.Pagos.RfcEmisorCtaOrd = xtr.Value
|
|
Case "CTAORDENANTE"
|
|
xmlCFDI.complemento.Pagos.CtaOrdenante = xtr.Value
|
|
Case "RFCEMISORCTABEN"
|
|
xmlCFDI.complemento.Pagos.RfcEmisorCtaBen = xtr.Value
|
|
Case "CTABENEFICIARIO"
|
|
xmlCFDI.complemento.Pagos.CtaBeneficiario = xtr.Value
|
|
End Select
|
|
conts = xtr.MoveToNextAttribute()
|
|
End While
|
|
|
|
conts = xtr.MoveToFirstAttribute()
|
|
While InlineAssignHelper.Assign(canread, xtr.Read()) AndAlso xtr.NodeType <> XmlNodeType.Element
|
|
End While
|
|
|
|
While canread AndAlso xtr.Depth > depthpagos
|
|
Dim objpago As New CFDIPagoDoctoRelacionado()
|
|
conts = xtr.MoveToFirstAttribute()
|
|
While conts
|
|
Dim Basep As Decimal = 0
|
|
Select Case xtr.Name.ToUpper()
|
|
Case "IDDOCUMENTO"
|
|
objpago.IdDocumento = xtr.Value
|
|
Case "SERIE"
|
|
objpago.Serie = xtr.Value
|
|
Case "FOLIO"
|
|
objpago.Folio = xtr.Value
|
|
Case "MONEDADR"
|
|
objpago.MonedaDR = xtr.Value
|
|
Case "METODODEPAGODR"
|
|
objpago.MetodoDePagoDR = xtr.Value
|
|
Case "NUMPARCIALIDAD"
|
|
objpago.NumParcialidad = xtr.Value
|
|
Case "IMPSALDOANT"
|
|
Decimal.TryParse(xtr.Value, Basep)
|
|
objpago.ImpSaldoAnt = Basep
|
|
Case "IMPPAGADO"
|
|
Decimal.TryParse(xtr.Value, Basep)
|
|
objpago.ImpPagado = Basep
|
|
Case "IMPSALDOINSOLUTO"
|
|
Decimal.TryParse(xtr.Value, Basep)
|
|
objpago.ImpSaldoInsoluto = Basep
|
|
End Select
|
|
conts = xtr.MoveToNextAttribute()
|
|
End While
|
|
|
|
conts = xtr.MoveToFirstAttribute()
|
|
xmlCFDI.complemento.Pagos.doctosRelacionados.Add(objpago)
|
|
While InlineAssignHelper.Assign(canread, xtr.Read()) AndAlso xtr.NodeType <> XmlNodeType.Element
|
|
End While
|
|
End While
|
|
Else
|
|
While InlineAssignHelper.Assign(canread, xtr.Read()) AndAlso xtr.NodeType <> XmlNodeType.Element
|
|
End While
|
|
End If
|
|
End While
|
|
End If
|
|
Else
|
|
'si no entro en ninguna de los anteriores no se debe ciclar
|
|
While InlineAssignHelper.Assign(canread, xtr.Read()) AndAlso xtr.NodeType <> XmlNodeType.Element
|
|
End While
|
|
End If
|
|
End While
|
|
End If
|
|
End Using
|
|
End If
|
|
|
|
If xmlCFDI.comprobante.Version = "4.0" OrElse xmlCFDI.comprobante.Version = "3.3" OrElse xmlCFDI.comprobante.Version = "3.2" Then
|
|
Return xmlCFDI
|
|
Else
|
|
Return Nothing
|
|
End If
|
|
End Function
|
|
|
|
Public Sub ImprimirPDF(UsuarioActual As Usuario, NombreArchivo As String, DirectorioEmpresa As String, TipodeComprobante As String)
|
|
Dim objxml As XmlSatCFDI = Me
|
|
|
|
Dim rutaReporte As String = $"{DirectorioEmpresas}{If(TipodeComprobante = "Pag", "Grales\Formatos\CFDIV3Pago.rdlc", "Grales\Formatos\CFDIV3.rdlc")}"
|
|
|
|
'Dim rutaReporte As String = If(TipodeComprobante = "Pag", "Grales\Formatos\CFDIV3Pago.rdlc", "Grales\Formatos\CFDIV3.rdlc")
|
|
|
|
|
|
Dim cQr As Byte() = Nothing
|
|
Try
|
|
Dim cfdi As New RVCFDI33.GeneraCFDI()
|
|
cQr = cfdi.ConvertirQrCode($"?re={objxml.emisor.Rfc}&rr={objxml.receptor.Rfc}&tt={(If(objxml.complemento.Pagos Is Nothing, objxml.comprobante.Total, objxml.complemento.Pagos.Monto))}&id={objxml.complemento.UUID}")
|
|
Catch exQR As Exception
|
|
ModExtensiones.GuardaLogAD("Error al generar QR - " & exQR.Message & " - " & exQR.StackTrace.ToString(), ArchivoLog)
|
|
End Try
|
|
|
|
Dim parametros As New List(Of ReportParameter)()
|
|
' Comprobante
|
|
parametros.Add(New ReportParameter("comprobante_Certificado", objxml.comprobante.Certificado))
|
|
parametros.Add(New ReportParameter("comprobante_CondicionesDePago", objxml.comprobante.CondicionesDePago))
|
|
parametros.Add(New ReportParameter("comprobante_Confirmacion", objxml.comprobante.Confirmacion))
|
|
parametros.Add(New ReportParameter("comprobante_Fecha", objxml.comprobante.Fecha))
|
|
parametros.Add(New ReportParameter("comprobante_Serie", objxml.comprobante.Serie))
|
|
parametros.Add(New ReportParameter("comprobante_Folio", objxml.comprobante.Folio))
|
|
parametros.Add(New ReportParameter("comprobante_Descuento", objxml.comprobante.Descuento.ToString("N2")))
|
|
parametros.Add(New ReportParameter("comprobante_SubTotal", objxml.comprobante.SubTotal.ToString("N2")))
|
|
parametros.Add(New ReportParameter("comprobante_Total", objxml.comprobante.Total.ToString("N2")))
|
|
parametros.Add(New ReportParameter("comprobante_Version", objxml.comprobante.Version))
|
|
parametros.Add(New ReportParameter("comprobante_TipoDeComprobante", objxml.comprobante.TipoDeComprobanteTexto))
|
|
parametros.Add(New ReportParameter("comprobante_FormaPago", objxml.comprobante.FormaPagoTexto))
|
|
parametros.Add(New ReportParameter("comprobante_LugarExpedicion", objxml.comprobante.LugarExpedicion))
|
|
parametros.Add(New ReportParameter("comprobante_NoCertificado", objxml.comprobante.NoCertificado))
|
|
parametros.Add(New ReportParameter("comprobante_Sello", objxml.comprobante.Sello))
|
|
parametros.Add(New ReportParameter("comprobante_Moneda", objxml.comprobante.Moneda))
|
|
parametros.Add(New ReportParameter("comprobante_TipoCambio", objxml.comprobante.TipoCambio.ToString("N2")))
|
|
parametros.Add(New ReportParameter("comprobante_MetodoPago", objxml.comprobante.MetodoPagoTexto))
|
|
' Emisor
|
|
parametros.Add(New ReportParameter("emisor_Rfc", objxml.emisor.Rfc))
|
|
parametros.Add(New ReportParameter("emisor_Nombre", objxml.emisor.Nombre))
|
|
parametros.Add(New ReportParameter("emisor_RegimenFiscal", objxml.emisor.RegimenFiscalTexto))
|
|
' Receptor
|
|
parametros.Add(New ReportParameter("receptor_Rfc", objxml.receptor.Rfc))
|
|
parametros.Add(New ReportParameter("receptor_Nombre", objxml.receptor.Nombre))
|
|
parametros.Add(New ReportParameter("receptor_NumRegIdTrib", objxml.receptor.NumRegIdTrib))
|
|
parametros.Add(New ReportParameter("receptor_ResidenciaFiscal", objxml.receptor.ResidenciaFiscal))
|
|
parametros.Add(New ReportParameter("receptor_UsoCFDI", objxml.receptor.UsoCFDITexto))
|
|
' Complemento
|
|
parametros.Add(New ReportParameter("complemento_FechaTimbrado", objxml.complemento.FechaTimbrado))
|
|
parametros.Add(New ReportParameter("complemento_NoCertificadoSAT", objxml.complemento.NoCertificadoSAT))
|
|
parametros.Add(New ReportParameter("complemento_RfcProvCertif", objxml.complemento.RfcProvCertif))
|
|
parametros.Add(New ReportParameter("complemento_SelloCFD", objxml.complemento.SelloCFD))
|
|
parametros.Add(New ReportParameter("complemento_SelloSAT", objxml.complemento.SelloSAT))
|
|
parametros.Add(New ReportParameter("complemento_UUID", objxml.complemento.UUID))
|
|
parametros.Add(New ReportParameter("complemento_CadenaOriginal", objxml.complemento.CadenaOriginal))
|
|
' Pagos
|
|
If objxml.complemento.Pagos IsNot Nothing Then
|
|
parametros.Add(New ReportParameter("CPFechaPago", objxml.complemento.Pagos.FechaPago))
|
|
parametros.Add(New ReportParameter("CPFormaDePagoP", objxml.complemento.Pagos.FormaDePagoP))
|
|
parametros.Add(New ReportParameter("CPFormaDePagoPText", objxml.complemento.Pagos.FormaDePagoPText))
|
|
parametros.Add(New ReportParameter("CPMonedaP", objxml.complemento.Pagos.MonedaP))
|
|
parametros.Add(New ReportParameter("CPMonto", objxml.complemento.Pagos.Monto.ToString()))
|
|
parametros.Add(New ReportParameter("CPTipoCambioP", objxml.complemento.Pagos.TipoCambioP.ToString()))
|
|
parametros.Add(New ReportParameter("CPNumOperacion", objxml.complemento.Pagos.NumOperacion))
|
|
parametros.Add(New ReportParameter("CPNomBancoOrdExt", objxml.complemento.Pagos.NomBancoOrdExt))
|
|
parametros.Add(New ReportParameter("CPRfcEmisorCtaOrd", objxml.complemento.Pagos.RfcEmisorCtaOrd))
|
|
parametros.Add(New ReportParameter("CPCtaOrdenante", objxml.complemento.Pagos.CtaOrdenante))
|
|
parametros.Add(New ReportParameter("CPRfcEmisorCtaBen", objxml.complemento.Pagos.RfcEmisorCtaBen))
|
|
parametros.Add(New ReportParameter("CPCtaBeneficiario", objxml.complemento.Pagos.CtaBeneficiario))
|
|
End If
|
|
|
|
Try
|
|
Dim listaDS As New List(Of ReportDataSource)
|
|
Dim rdsTotales As New ReportDataSource()
|
|
'Dim ltotales As New List(Of utilValores)()
|
|
|
|
Dim DTTotales As New DataTable
|
|
DTTotales.TableName = "DTTotales"
|
|
DTTotales.Columns.Add("Nombre")
|
|
DTTotales.Columns.Add("Valor")
|
|
|
|
Dim nRowSubtotales As DataRow = DTTotales.NewRow
|
|
nRowSubtotales("Nombre") = "Subtotal"
|
|
nRowSubtotales("Valor") = objxml.comprobante.SubTotal.ToString("N2")
|
|
DTTotales.Rows.Add(nRowSubtotales)
|
|
|
|
If objxml.comprobante.Descuento > 0 Then
|
|
Dim nRowDescuento As DataRow = DTTotales.NewRow
|
|
nRowDescuento("Nombre") = "Descuento"
|
|
nRowDescuento("Valor") = objxml.comprobante.Descuento.ToString("N2")
|
|
DTTotales.Rows.Add(nRowDescuento)
|
|
End If
|
|
|
|
For Each item As CFDIImpuesto In objxml.Impuestos
|
|
Dim nRow As DataRow = DTTotales.NewRow
|
|
If item.Importe > 0 Then
|
|
Dim TasaOCuota As Decimal = 0
|
|
Decimal.TryParse(item.TasaOCuota, TasaOCuota)
|
|
nRow("Nombre") = $"Impuestos {item.Tipo} {item.ImpuestoTexto} {(If(item.TipoFactor = "Tasa", (TasaOCuota * 100).ToString("N4"), item.TasaOCuota))} {(If(item.TipoFactor = "Tasa", "%", ""))}"
|
|
nRow("Valor") = item.Importe.ToString("N2")
|
|
DTTotales.Rows.Add(nRow)
|
|
|
|
End If
|
|
Next
|
|
|
|
Dim nRowTotal As DataRow = DTTotales.NewRow
|
|
nRowTotal("Nombre") = "Subtotal"
|
|
nRowTotal("Valor") = objxml.comprobante.Total.ToString("N2")
|
|
DTTotales.Rows.Add(nRowTotal)
|
|
|
|
rdsTotales.Name = "dsTotales"
|
|
rdsTotales.Value = DTTotales 'ltotales.ToDataTable
|
|
listaDS.Add(rdsTotales)
|
|
|
|
|
|
Dim dtByte As New DataTable()
|
|
dtByte.Columns.Add("ImagenByte", GetType(Byte()))
|
|
dtByte.TableName = "dtImagenes"
|
|
Dim nrowByteArray As DataRow = dtByte.NewRow
|
|
nrowByteArray("ImagenByte") = cQr
|
|
dtByte.Rows.Add(nrowByteArray)
|
|
|
|
'byteArrayList.Add(cQr)
|
|
Dim rds2 As New ReportDataSource()
|
|
'Dim limagenes As New List(Of utilImage)()
|
|
'limagenes.Add(New utilImage(cQr))
|
|
rds2.Name = "dsImagenes"
|
|
rds2.Value = dtByte
|
|
listaDS.Add(rds2)
|
|
|
|
|
|
Dim dtRelacionados As New DataTable
|
|
dtRelacionados.TableName = "dtRelacionados"
|
|
dtRelacionados.Columns.Add("TipoRelacion")
|
|
dtRelacionados.Columns.Add("TipoRelacionTexto")
|
|
dtRelacionados.Columns.Add("UUID")
|
|
|
|
|
|
For Each relaciondo As CFDIRelacionado In objxml.cFDIRelacionados
|
|
Dim CFDIRelacionadoRow As DataRow = dtRelacionados.NewRow
|
|
CFDIRelacionadoRow("TipoRelacion") = relaciondo.TipoRelacion
|
|
CFDIRelacionadoRow("TipoRelacionTexto") = relaciondo.TipoRelacionTexto
|
|
CFDIRelacionadoRow("UUID") = relaciondo.UUID
|
|
dtRelacionados.Rows.Add(CFDIRelacionadoRow)
|
|
Next
|
|
|
|
Dim rdsrelacionados As New ReportDataSource()
|
|
rdsrelacionados.Name = "dsRelacionados"
|
|
rdsrelacionados.Value = dtRelacionados 'objxml.cFDIRelacionados
|
|
listaDS.Add(rdsrelacionados)
|
|
|
|
|
|
|
|
Dim dtConceptos As New DataTable
|
|
dtConceptos.TableName = "dtConceptos"
|
|
dtConceptos.Columns.Add("tipo", GetType(Integer))
|
|
dtConceptos.Columns.Add("orden", GetType(Integer))
|
|
dtConceptos.Columns.Add("ClaveProdServ", GetType(String))
|
|
dtConceptos.Columns.Add("NoIdentificacion", GetType(String))
|
|
dtConceptos.Columns.Add("Cantidad", GetType(String)) ' Nota: Se asume que es cadena, cambiar si necesario
|
|
dtConceptos.Columns.Add("ClaveUnidad", GetType(String))
|
|
dtConceptos.Columns.Add("Unidad", GetType(String))
|
|
dtConceptos.Columns.Add("ValorUnitario", GetType(Decimal))
|
|
dtConceptos.Columns.Add("Importe", GetType(Decimal))
|
|
dtConceptos.Columns.Add("Descuento", GetType(Decimal))
|
|
dtConceptos.Columns.Add("NumeroPedimento", GetType(String))
|
|
dtConceptos.Columns.Add("CuentaPredial", GetType(String))
|
|
dtConceptos.Columns.Add("Descripcion", GetType(String))
|
|
dtConceptos.Columns.Add("Impuesto", GetType(String))
|
|
dtConceptos.Columns.Add("Impuesto_Tipo", GetType(String))
|
|
dtConceptos.Columns.Add("Impuesto_Base", GetType(Decimal))
|
|
dtConceptos.Columns.Add("Impuesto_TipoFactor", GetType(String))
|
|
dtConceptos.Columns.Add("Impuesto_TasaOCuota", GetType(String))
|
|
dtConceptos.Columns.Add("Impuesto_Importe", GetType(Decimal))
|
|
|
|
For Each concepto As CFDIConcepto_I In objxml.GetConceptosforpdf()
|
|
Dim CFDIRelacionadoRow As DataRow = dtConceptos.NewRow
|
|
|
|
CFDIRelacionadoRow("tipo") = concepto.tipo
|
|
CFDIRelacionadoRow("orden") = concepto.orden
|
|
CFDIRelacionadoRow("ClaveProdServ") = concepto.ClaveProdServ
|
|
CFDIRelacionadoRow("NoIdentificacion") = concepto.NoIdentificacion
|
|
CFDIRelacionadoRow("Cantidad") = concepto.Cantidad
|
|
CFDIRelacionadoRow("ClaveUnidad") = concepto.ClaveUnidad
|
|
CFDIRelacionadoRow("Unidad") = concepto.Unidad
|
|
CFDIRelacionadoRow("ValorUnitario") = concepto.ValorUnitario
|
|
CFDIRelacionadoRow("Importe") = concepto.Importe
|
|
CFDIRelacionadoRow("Descuento") = concepto.Descuento
|
|
CFDIRelacionadoRow("NumeroPedimento") = concepto.NumeroPedimento
|
|
CFDIRelacionadoRow("CuentaPredial") = concepto.CuentaPredial
|
|
CFDIRelacionadoRow("Descripcion") = concepto.Descripcion
|
|
CFDIRelacionadoRow("Impuesto") = concepto.Impuesto
|
|
CFDIRelacionadoRow("Impuesto_Tipo") = concepto.Impuesto_Tipo
|
|
CFDIRelacionadoRow("Impuesto_Base") = concepto.Impuesto_Base
|
|
CFDIRelacionadoRow("Impuesto_TipoFactor") = concepto.Impuesto_TipoFactor
|
|
CFDIRelacionadoRow("Impuesto_TasaOCuota") = If(concepto.Impuesto_TasaOCuota Is Nothing, "", concepto.Impuesto_TasaOCuota)
|
|
CFDIRelacionadoRow("Impuesto_Importe") = If(concepto.Impuesto_Importe > 0, concepto.Impuesto_Importe, 0)
|
|
|
|
dtConceptos.Rows.Add(CFDIRelacionadoRow)
|
|
Next
|
|
|
|
|
|
|
|
Dim rds1 As New ReportDataSource()
|
|
rds1.Name = "dsConceptos"
|
|
rds1.Value = dtConceptos 'objxml.GetConceptosforpdf()
|
|
listaDS.Add(rds1)
|
|
|
|
|
|
If objxml.complemento.Pagos IsNot Nothing Then
|
|
|
|
' Crear un nuevo DataTable y agregar las columnas correspondientes
|
|
Dim DTdoctosRelacionados As New DataTable()
|
|
DTdoctosRelacionados.TableName = "dtDocumentos"
|
|
|
|
' Agregar todas las columnas respetando los tipos de datos
|
|
DTdoctosRelacionados.Columns.Add("IdDocumento", GetType(String))
|
|
DTdoctosRelacionados.Columns.Add("Serie", GetType(String))
|
|
DTdoctosRelacionados.Columns.Add("Folio", GetType(String))
|
|
DTdoctosRelacionados.Columns.Add("MonedaDR", GetType(String))
|
|
DTdoctosRelacionados.Columns.Add("MetodoDePagoDR", GetType(String))
|
|
DTdoctosRelacionados.Columns.Add("NumParcialidad", GetType(String))
|
|
DTdoctosRelacionados.Columns.Add("ImpSaldoAnt", GetType(Decimal))
|
|
DTdoctosRelacionados.Columns.Add("ImpPagado", GetType(Decimal))
|
|
DTdoctosRelacionados.Columns.Add("ImpSaldoInsoluto", GetType(Decimal))
|
|
|
|
' Llenar el DataTable con los valores de la lista de documentos
|
|
For Each doctosRelacionado As CFDIPagoDoctoRelacionado In objxml.complemento.Pagos.doctosRelacionados
|
|
Dim nRowdoctosRelacionados As DataRow = DTdoctosRelacionados.NewRow()
|
|
|
|
' Asignar valores a cada columna desde las propiedades del objeto documento
|
|
nRowdoctosRelacionados("IdDocumento") = doctosRelacionado.IdDocumento
|
|
nRowdoctosRelacionados("Serie") = doctosRelacionado.Serie
|
|
nRowdoctosRelacionados("Folio") = doctosRelacionado.Folio
|
|
nRowdoctosRelacionados("MonedaDR") = doctosRelacionado.MonedaDR
|
|
nRowdoctosRelacionados("MetodoDePagoDR") = doctosRelacionado.MetodoDePagoDR
|
|
nRowdoctosRelacionados("NumParcialidad") = doctosRelacionado.NumParcialidad
|
|
nRowdoctosRelacionados("ImpSaldoAnt") = doctosRelacionado.ImpSaldoAnt
|
|
nRowdoctosRelacionados("ImpPagado") = doctosRelacionado.ImpPagado
|
|
nRowdoctosRelacionados("ImpSaldoInsoluto") = doctosRelacionado.ImpSaldoInsoluto
|
|
|
|
' Agregar la fila al DataTable
|
|
DTdoctosRelacionados.Rows.Add(nRowdoctosRelacionados)
|
|
Next
|
|
|
|
Dim rdsp As New ReportDataSource()
|
|
rdsp.Name = "dsPagos"
|
|
rdsp.Value = DTdoctosRelacionados ' objxml.complemento.Pagos.doctosRelacionados
|
|
listaDS.Add(rdsp)
|
|
|
|
|
|
End If
|
|
|
|
|
|
'Dim bytes As Byte() = Nothing
|
|
'bytes = MR.LocalReport.Render("PDF", Nothing, mimeType, encoding, extension, streamids, warnings)
|
|
Dim bytes As Byte() = Nothing
|
|
bytes = StreamPDF(UsuarioActual, rutaReporte, listaDs, parametros, NombreArchivo:=NombreArchivo, Formato:="PDF")
|
|
|
|
If bytes IsNot Nothing Then
|
|
Using fs As New FileStream(NombreArchivo, FileMode.Create)
|
|
fs.Write(bytes, 0, bytes.Length)
|
|
fs.Close()
|
|
End Using
|
|
End If
|
|
|
|
Catch ex As Exception
|
|
ex.ToString().GuardaLogAD()
|
|
End Try
|
|
|
|
End Sub
|
|
|
|
Public Class utilValores
|
|
|
|
Public Sub New()
|
|
' Constructor sin parámetros
|
|
End Sub
|
|
|
|
Public Sub New(nombre As String, valor As String)
|
|
Me.Nombre = nombre
|
|
Me.Valor = valor
|
|
End Sub
|
|
Public Property Nombre As String
|
|
Public Property Valor As String
|
|
End Class
|
|
|
|
Public Class utilImage
|
|
Public Sub New(imagenByte As Byte())
|
|
Me.ImagenByte = imagenByte
|
|
End Sub
|
|
Public Property ImagenByte As Byte()
|
|
End Class
|
|
|
|
Public Function StreamPDF(UsuarioActual As Usuario, RutaReporte As String, DataSource As List(Of ReportDataSource), Parametros As List(Of ReportParameter), Optional NombreArchivo As String = "Reporte", Optional Formato As String = "PDF", Optional MR As ReportViewer = Nothing, Optional SubReportData As Modelos.MSubReportData = Nothing) As Byte()
|
|
'limpio ReportViwer
|
|
Dim sw As Stopwatch = Stopwatch.StartNew()
|
|
|
|
|
|
Dim Bytes As Byte() = Nothing
|
|
Dim CveUsuario As Integer = 0
|
|
Dim CveEmpresa As Integer = 0
|
|
Dim RutaEmpresa As String = ""
|
|
If UsuarioActual IsNot Nothing Then
|
|
CveUsuario = UsuarioActual.CveUsuario
|
|
CveEmpresa = UsuarioActual.CveEmpresa
|
|
RutaEmpresa = UsuarioActual.Empresa.Ruta
|
|
End If
|
|
|
|
Dim bdir As String = If(RutaReporte.Contains("Empresas"), ModExtensiones.DirectorioBaseEmpresas, AppDomain.CurrentDomain.BaseDirectory)
|
|
'TOMAR LA RUTA BASE PARA EL DIRECTORIO DE LA EMPRESA
|
|
If Not String.IsNullOrEmpty(RutaEmpresa) AndAlso Not RutaReporte.Contains("Grales") AndAlso Not RutaReporte.Contains("Contabilidad/Reportes/") AndAlso Not RutaReporte.Contains("Contabilidad/Reportes/") AndAlso Not RutaReporte.Contains("AC/Reportes/") Then
|
|
bdir = RutaEmpresa.Replace($"{CveEmpresa}/", "")
|
|
End If
|
|
RutaReporte.Replace("/", "\")
|
|
If Not RutaReporte.ToUpper().StartsWith(bdir.ToUpper()) Then
|
|
RutaReporte = String.Format("{0}{1}", bdir, RutaReporte)
|
|
End If
|
|
If EsProduccion Then
|
|
Dim wsreport As New WSRDLC2.WebServiceSoapClient
|
|
Dim params As New List(Of WSRDLC2.ReportParameter)
|
|
Dim reportobjects As New List(Of WSRDLC2.ReportObjects)
|
|
Dim jsonData As String = Nothing
|
|
If SubReportData IsNot Nothing Then
|
|
jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(SubReportData)
|
|
End If
|
|
Dim ds As New DataSet
|
|
For Each rpds As ReportDataSource In DataSource
|
|
If rpds.Value IsNot Nothing Then
|
|
If rpds.Value.GetType().ToString() = "System.Data.DataTable" Then
|
|
Dim dt As DataTable = DirectCast(rpds.Value, Data.DataTable)
|
|
dt = dt.Copy()
|
|
dt.TableName = rpds.Name
|
|
ds.Tables.Add(dt)
|
|
Else
|
|
Dim ojext As New WSRDLC2.ReportObjects
|
|
ojext.Name = rpds.Name
|
|
ojext.Value = rpds.Value
|
|
reportobjects.Add(ojext)
|
|
End If
|
|
Else
|
|
Dim dt As DataTable = New DataTable()
|
|
dt.TableName = If(String.IsNullOrEmpty(rpds.Name), "DataTable1", rpds.Name)
|
|
ds.Tables.Add(dt)
|
|
End If
|
|
Next
|
|
For Each rpds As ReportParameter In Parametros
|
|
Dim param As New WSRDLC2.ReportParameter
|
|
param.Name = rpds.Name
|
|
'SI ES TEXTO, QUITAR TABS Y OTROS ESPACIOS QUE DEN PROBLEMAS AL MANDAR LA PETICION
|
|
If rpds IsNot Nothing AndAlso rpds.Values IsNot Nothing AndAlso rpds.Values.Count > 0 AndAlso rpds.Values(0) IsNot Nothing AndAlso rpds.Values(0).GetType() = GetType(String) Then
|
|
param.Values = {rpds.Values(0).Replace(vbVerticalTab, "")}
|
|
Else
|
|
param.Values = {rpds.Values(0)}
|
|
End If
|
|
params.Add(param)
|
|
Next
|
|
Bytes = wsreport.StreamNEWPDFBytes(RutaReporte, ds, reportobjects.ToArray(), params.ToArray(), NombreArchivo, Formato, CveEmpresa, CveUsuario, jsonData)
|
|
wsreport = Nothing
|
|
params = Nothing
|
|
ds.Dispose() : ds = Nothing
|
|
Else
|
|
If IsNothing(MR) Then MR = New ReportViewer
|
|
Try
|
|
' MasterReporteador.LocalReport.DataSources.Clear()
|
|
For Each RDS As ReportDataSource In DataSource
|
|
MR.LocalReport.DataSources.Add(RDS)
|
|
Next
|
|
MR.LocalReport.ReportPath = RutaReporte
|
|
MR.ProcessingMode = ProcessingMode.Local
|
|
MR.LocalReport.EnableExternalImages = True
|
|
MR.LocalReport.SetParameters(Parametros)
|
|
MR.LocalReport.Refresh()
|
|
Dim Warnings As Warning() = Nothing
|
|
Dim StreamIds As String() = Nothing
|
|
Dim MimeType As String = Nothing
|
|
Dim Encoding As String = Nothing
|
|
Dim Extension As String = Nothing
|
|
Bytes = MR.LocalReport.Render(Formato, Nothing, MimeType, Encoding, Extension, StreamIds, Warnings)
|
|
Catch ex As Microsoft.Reporting.WebForms.ScriptManagerNotFoundException
|
|
GuardaLog($"Error: { If(ex.InnerException.Message IsNot Nothing, ex.InnerException.Message, ex.Message) } | Descripcion: {If(ex.InnerException IsNot Nothing AndAlso ex.InnerException.InnerException IsNot Nothing AndAlso ex.InnerException.InnerException.Message IsNot Nothing, ex.InnerException.InnerException.Message, If(ex.InnerException IsNot Nothing AndAlso ex.InnerException.Message IsNot Nothing, ex.InnerException.Message, "Sin descripcion"))} - Ruta {RutaReporte}")
|
|
'HAY QUE VALIDAR QUE LOS OBJETOS QUE SE USAN PARA GUARDAR LOG EXISTEN!!! IPP 14 AGOSTO 2017
|
|
'GuardaLog($"Error: {ex.InnerException.Message} | Descripcion: {If(ex.InnerException.InnerException IsNot Nothing, ex.InnerException.InnerException.Message, "Sin descripcion")} - Ruta {RutaReporte}")
|
|
Catch ex As Exception
|
|
GuardaLog($"Error: { If(ex.InnerException.Message IsNot Nothing, ex.InnerException.Message, ex.Message) } | Descripcion: {If(ex.InnerException IsNot Nothing AndAlso ex.InnerException.InnerException IsNot Nothing AndAlso ex.InnerException.InnerException.Message IsNot Nothing, ex.InnerException.InnerException.Message, If(ex.InnerException IsNot Nothing AndAlso ex.InnerException.Message IsNot Nothing, ex.InnerException.Message, "Sin descripcion"))} - Ruta {RutaReporte}")
|
|
'HAY QUE VALIDAR QUE LOS OBJETOS QUE SE USAN PARA GUARDAR LOG EXISTEN!!! IPP 14 AGOSTO 2017
|
|
'GuardaLog($"Error {ex.InnerException.Message} | Descripcion: {If(ex.InnerException.InnerException IsNot Nothing, ex.InnerException.InnerException.Message, "Sin descripcion")} - Ruta {RutaReporte}")
|
|
End Try
|
|
|
|
Try
|
|
MR.Dispose()
|
|
Catch ex As Exception
|
|
GuardaLog($"Error: { ex.ToString() }")
|
|
End Try
|
|
|
|
MR = Nothing
|
|
|
|
End If
|
|
sw.Stop()
|
|
If sw.Elapsed.TotalSeconds > 5 Then
|
|
GuardaLog($"Reporte:{RutaReporte} | Tiempo Renderizado Milisegundos: {sw.ElapsedMilliseconds},Total Segundos: {sw.Elapsed.TotalSeconds} ")
|
|
End If
|
|
Return Bytes
|
|
End Function
|
|
End Class
|
|
|
|
Public Module InlineAssignHelper
|
|
Public Function Assign(Of T)(ByRef target As T, value As T) As T
|
|
target = value
|
|
Return value
|
|
End Function
|
|
End Module
|
|
|
|
#Region "impresion nd"
|
|
Public Class CFDIComprobante
|
|
Public Property xmlns_cfdi As String
|
|
Public Property xmlns_xsi As String
|
|
Public Property xsi_schemaLocation As String
|
|
Public Property Version As String
|
|
Public Property Serie As String
|
|
Public Property Folio As String
|
|
Public Property Fecha As String
|
|
Public Property Moneda As String
|
|
Public Property SubTotal As Decimal
|
|
Public Property Total As Decimal
|
|
Public Property Descuento As Decimal
|
|
Public Property TipoCambio As Decimal
|
|
Public Property TipoDeComprobante As String
|
|
Public ReadOnly Property TipoDeComprobanteTexto As String
|
|
Get
|
|
Dim retorno As String = ""
|
|
If Version = "3.3" OrElse Version = "4.0" Then
|
|
Select Case TipoDeComprobante
|
|
Case "I"
|
|
retorno = "Ingreso"
|
|
Case "E"
|
|
retorno = "Egreso"
|
|
Case "P"
|
|
retorno = "Pago"
|
|
Case "T"
|
|
retorno = "Traslado"
|
|
Case "N"
|
|
retorno = "Nómina"
|
|
Case Else
|
|
retorno = TipoDeComprobante
|
|
End Select
|
|
End If
|
|
If Version = "3.2" Then
|
|
Select Case TipoDeComprobante
|
|
Case "ingreso"
|
|
retorno = "Ing"
|
|
Case "egreso"
|
|
retorno = "Egs"
|
|
Case "P"
|
|
retorno = "PA"
|
|
Case Else
|
|
retorno = TipoDeComprobante
|
|
End Select
|
|
Else
|
|
retorno = TipoDeComprobante
|
|
End If
|
|
Return retorno
|
|
End Get
|
|
End Property
|
|
Public ReadOnly Property TipoDeComprobanteSIG As String
|
|
Get
|
|
Dim retorno As String = ""
|
|
If Version = "3.3" OrElse Version = "4.0" Then
|
|
Select Case TipoDeComprobante
|
|
Case "I"
|
|
retorno = "Ing"
|
|
Case "E"
|
|
retorno = "Egs"
|
|
Case "P"
|
|
retorno = "PA"
|
|
Case Else
|
|
retorno = TipoDeComprobante
|
|
End Select
|
|
End If
|
|
If Version = "3.2" Then
|
|
Select Case TipoDeComprobante
|
|
Case "ingreso"
|
|
retorno = "Ing"
|
|
Case "egreso"
|
|
retorno = "Egs"
|
|
Case "P"
|
|
retorno = "PA"
|
|
Case Else
|
|
retorno = TipoDeComprobante
|
|
End Select
|
|
Else
|
|
retorno = TipoDeComprobante
|
|
End If
|
|
Return retorno
|
|
End Get
|
|
End Property
|
|
Public Property FormaPago As String
|
|
Public ReadOnly Property FormaPagoTexto As String
|
|
Get
|
|
Dim retorno As String = ""
|
|
Select Case FormaPago
|
|
Case "01"
|
|
retorno = "Efectivo"
|
|
Case "02"
|
|
retorno = "Cheque nominativo"
|
|
Case "03"
|
|
retorno = "Transferencia electrónica de fondos"
|
|
Case "04"
|
|
retorno = "Tarjeta de crédito"
|
|
Case "05"
|
|
retorno = "Monedero electrónico"
|
|
Case "06"
|
|
retorno = "Dinero electrónico"
|
|
Case "08"
|
|
retorno = "Vales de despensa"
|
|
Case "12"
|
|
retorno = "Dación en pago"
|
|
Case "13"
|
|
retorno = "Pago por subrogación"
|
|
Case "14"
|
|
retorno = "Pago por consignación"
|
|
Case "15"
|
|
retorno = "Condonación"
|
|
Case "17"
|
|
retorno = "Compensación"
|
|
Case "23"
|
|
retorno = "Novación"
|
|
Case "24"
|
|
retorno = "Confusión"
|
|
Case "25"
|
|
retorno = "Remisión de deuda"
|
|
Case "26"
|
|
retorno = "Prescripción o caducidad"
|
|
Case "27"
|
|
retorno = "A satisfacción del acreedor"
|
|
Case "28"
|
|
retorno = "Tarjeta de débito"
|
|
Case "29"
|
|
retorno = "Tarjeta de servicios"
|
|
Case "30"
|
|
retorno = "Aplicación de anticipos"
|
|
Case "31"
|
|
retorno = "Intermediario pagos"
|
|
Case "99"
|
|
retorno = "Por definir"
|
|
Case Else
|
|
retorno = FormaPago
|
|
End Select
|
|
Return retorno
|
|
End Get
|
|
End Property
|
|
Public Property MetodoPago As String
|
|
Public ReadOnly Property MetodoPagoTexto As String
|
|
Get
|
|
Dim retorno As String = ""
|
|
Select Case MetodoPago
|
|
Case "PUE"
|
|
retorno = "Pago en una sola exhibición"
|
|
Case "PPD"
|
|
retorno = "Pago en parcialidades o diferido"
|
|
Case Else
|
|
retorno = MetodoPago
|
|
End Select
|
|
Return retorno
|
|
End Get
|
|
End Property
|
|
Public Property CondicionesDePago As String
|
|
Public Property LugarExpedicion As String
|
|
Public Property Confirmacion As String
|
|
Public Property NoCertificado As String
|
|
Public Property Sello As String
|
|
Public Property Certificado As String
|
|
End Class
|
|
|
|
Public Class CFDIEmisor
|
|
Public Property RegimenFiscal As String
|
|
Public ReadOnly Property RegimenFiscalTexto As String
|
|
Get
|
|
Dim retorno As String = ""
|
|
Select Case RegimenFiscal
|
|
Case "601"
|
|
retorno = "General de Ley Personas Morales"
|
|
Case "603"
|
|
retorno = "Personas Morales con Fines no Lucrativos"
|
|
Case "605"
|
|
retorno = "Sueldos y Salarios e Ingresos Asimilados a Salarios"
|
|
Case "606"
|
|
retorno = "Arrendamiento"
|
|
Case "608"
|
|
retorno = "Demás ingresos"
|
|
Case "609"
|
|
retorno = "Consolidación"
|
|
Case "610"
|
|
retorno = "Residentes en el Extranjero sin Establecimiento Permanente en México"
|
|
Case "611"
|
|
retorno = "Ingresos por Dividendos (socios y accionistas)"
|
|
Case "612"
|
|
retorno = "Personas Físicas con Actividades Empresariales y Profesionales"
|
|
Case "614"
|
|
retorno = "Ingresos por intereses"
|
|
Case "616"
|
|
retorno = "Sin obligaciones fiscales"
|
|
Case "620"
|
|
retorno = "Sociedades Cooperativas de Producción que optan por diferir sus ingresos"
|
|
Case "621"
|
|
retorno = "Incorporación Fiscal"
|
|
Case "622"
|
|
retorno = "Actividades Agrícolas, Ganaderas, Silvícolas y Pesqueras"
|
|
Case "623"
|
|
retorno = "Opcional para Grupos de Sociedades"
|
|
Case "624"
|
|
retorno = "Coordinados"
|
|
Case "628"
|
|
retorno = "Hidrocarburos"
|
|
Case "607"
|
|
retorno = "Régimen de Enajenación o Adquisición de Bienes"
|
|
Case "629"
|
|
retorno = "De los Regímenes Fiscales Preferentes y de las Empresas Multinacionales"
|
|
Case "630"
|
|
retorno = "Enajenación de acciones en bolsa de valores"
|
|
Case "615"
|
|
retorno = "Régimen de los ingresos por obtención de premios"
|
|
End Select
|
|
Return retorno
|
|
End Get
|
|
End Property
|
|
Public Property Nombre As String
|
|
Public Property Rfc As String
|
|
End Class
|
|
|
|
Public Class CFDIReceptor
|
|
Public Property Rfc As String
|
|
Public Property Nombre As String
|
|
Public Property ResidenciaFiscal As String
|
|
Public Property NumRegIdTrib As String
|
|
Public Property UsoCFDI As String
|
|
Public ReadOnly Property UsoCFDITexto As String
|
|
Get
|
|
Dim retorno As String = "N/A"
|
|
Select Case UsoCFDI
|
|
Case "G01"
|
|
retorno = "Adquisición de mercancías"
|
|
Case "G02"
|
|
retorno = "Devoluciones, descuentos o bonificaciones"
|
|
Case "G03"
|
|
retorno = "Gastos en general"
|
|
Case "I01"
|
|
retorno = "Construcciones"
|
|
Case "I02"
|
|
retorno = "Mobiliario y equipo de oficina por inversiones"
|
|
Case "I03"
|
|
retorno = "Equipo de transporte"
|
|
Case "I04"
|
|
retorno = "Equipo de cómputo y accesorios"
|
|
Case "I05"
|
|
retorno = "Dados, troqueles, moldes, matrices y herramental"
|
|
Case "I06"
|
|
retorno = "Comunicaciones telefónicas"
|
|
Case "I07"
|
|
retorno = "Comunicaciones satelitales"
|
|
Case "I08"
|
|
retorno = "Otra maquinaria y equipo"
|
|
Case "D01"
|
|
retorno = "Honorarios médicos, dentales y gastos hospitalarios."
|
|
Case "D02"
|
|
retorno = "Gastos médicos por incapacidad o discapacidad"
|
|
Case "D03"
|
|
retorno = "Gastos funerales."
|
|
Case "D04"
|
|
retorno = "Donativos."
|
|
Case "D05"
|
|
retorno = "Intereses reales efectivamente pagados por créditos hipotecarios (casa habitación)."
|
|
Case "D06"
|
|
retorno = "Aportaciones voluntarias al SAR."
|
|
Case "D07"
|
|
retorno = "Primas por seguros de gastos médicos."
|
|
Case "D08"
|
|
retorno = "Gastos de transportación escolar obligatoria."
|
|
Case "D09"
|
|
retorno = "Depósitos en cuentas para el ahorro, primas que tengan como base planes de pensiones."
|
|
Case "D10"
|
|
retorno = "Pagos por servicios educativos (colegiaturas)"
|
|
Case "P01"
|
|
retorno = "Por definir"
|
|
Case Else
|
|
retorno = UsoCFDI
|
|
End Select
|
|
Return retorno
|
|
End Get
|
|
End Property
|
|
End Class
|
|
|
|
Public Class CFDIComplemento
|
|
Public Property xmlns_tfd As String
|
|
Public Property xsi_schemaLocation As String
|
|
Public Property Version As String
|
|
Public Property UUID As String
|
|
Public Property FechaTimbrado As String
|
|
Public Property RfcProvCertif As String
|
|
Public Property SelloCFD As String
|
|
Public Property NoCertificadoSAT As String
|
|
Public Property SelloSAT As String
|
|
Public Property Pagos As CFDIPago
|
|
|
|
Public ReadOnly Property CadenaOriginal As String
|
|
Get
|
|
Return $"||{Version}|{UUID}|{FechaTimbrado}|{RfcProvCertif}|{SelloCFD}|{NoCertificadoSAT}||"
|
|
End Get
|
|
End Property
|
|
End Class
|
|
|
|
Public Class CFDIPago
|
|
Public Sub New()
|
|
doctosRelacionados = New List(Of CFDIPagoDoctoRelacionado)()
|
|
End Sub
|
|
|
|
Public Property FechaPago As String
|
|
Public Property FormaDePagoP As String
|
|
Public Property FormaDePagoPText As String
|
|
Public Property MonedaP As String
|
|
Public Property Monto As Decimal
|
|
Public Property TipoCambioP As Decimal
|
|
Public Property NumOperacion As String
|
|
Public Property NomBancoOrdExt As String
|
|
Public Property RfcEmisorCtaOrd As String
|
|
Public Property CtaOrdenante As String
|
|
Public Property RfcEmisorCtaBen As String
|
|
Public Property CtaBeneficiario As String
|
|
Public Property doctosRelacionados As List(Of CFDIPagoDoctoRelacionado)
|
|
End Class
|
|
|
|
Public Class CFDIPagoDoctoRelacionado
|
|
Public Property IdDocumento As String
|
|
Public Property Serie As String
|
|
Public Property Folio As String
|
|
Public Property MonedaDR As String
|
|
Public Property MetodoDePagoDR As String
|
|
Public Property NumParcialidad As String
|
|
Public Property ImpSaldoAnt As Decimal
|
|
Public Property ImpPagado As Decimal
|
|
Public Property ImpSaldoInsoluto As Decimal
|
|
End Class
|
|
|
|
Public Class CFDIRelacionado
|
|
Public Property TipoRelacion As String
|
|
Public ReadOnly Property TipoRelacionTexto As String
|
|
Get
|
|
Dim retorno As String = ""
|
|
Select Case TipoRelacion
|
|
Case "01"
|
|
retorno = "Nota de crédito de los documentos relacionados"
|
|
Case "02"
|
|
retorno = "Nota de débito de los documentos relacionados"
|
|
Case "03"
|
|
retorno = "Devolución de mercancía sobre facturas o traslados previos"
|
|
Case "04"
|
|
retorno = "Sustitución de los CFDI previos"
|
|
Case "05"
|
|
retorno = "Traslados de mercancías facturados previamente"
|
|
Case "06"
|
|
retorno = "Factura generada por los traslados previos"
|
|
Case "07"
|
|
retorno = "CFDI por aplicación de anticipo"
|
|
Case Else
|
|
retorno = "Por definir"
|
|
End Select
|
|
Return retorno
|
|
End Get
|
|
End Property
|
|
Public Property UUID As String
|
|
End Class
|
|
|
|
Public Class CFDIConcepto
|
|
Public Sub New()
|
|
Impuestos = New List(Of CFDIConceptoImpuesto)()
|
|
End Sub
|
|
|
|
Public Property ClaveProdServ As String
|
|
Public Property NoIdentificacion As String
|
|
Public Property Cantidad As String
|
|
Public Property ClaveUnidad As String
|
|
Public Property Unidad As String
|
|
Public Property ValorUnitario As Decimal
|
|
Public Property Importe As Decimal
|
|
Public Property Descuento As Decimal
|
|
Public Property NumeroPedimento As String
|
|
Public Property CuentaPredial As String
|
|
Public Property Descripcion As String
|
|
Public Property Impuestos As List(Of CFDIConceptoImpuesto)
|
|
End Class
|
|
|
|
Public Class CFDIConceptoImpuesto
|
|
Public Property Impuesto As String
|
|
Public ReadOnly Property ImpuestoTexto As String
|
|
Get
|
|
Dim retorno As String = ""
|
|
Select Case Impuesto
|
|
Case "001"
|
|
retorno = "ISR"
|
|
Case "002"
|
|
retorno = "IVA"
|
|
Case "003"
|
|
retorno = "IEPS"
|
|
End Select
|
|
Return retorno
|
|
End Get
|
|
End Property
|
|
Public Property Tipo As String
|
|
Public Property Base As Decimal
|
|
Public Property TipoFactor As String
|
|
Public Property TasaOCuota As String
|
|
Public Property Importe As Decimal
|
|
End Class
|
|
|
|
Public Class CFDIImpuesto
|
|
Public Property Tipo As String
|
|
Public Property Impuesto As String
|
|
Public ReadOnly Property ImpuestoTexto As String
|
|
Get
|
|
Dim retorno As String = ""
|
|
Select Case Impuesto
|
|
Case "001"
|
|
retorno = "ISR"
|
|
Case "002"
|
|
retorno = "IVA"
|
|
Case "003"
|
|
retorno = "IEPS"
|
|
End Select
|
|
Return retorno
|
|
End Get
|
|
End Property
|
|
Public Property TipoFactor As String
|
|
Public Property TasaOCuota As String
|
|
Public Property Importe As Decimal
|
|
End Class
|
|
|
|
Public Class CFDIConcepto_I
|
|
Public Property tipo As Integer
|
|
Public Property orden As Integer
|
|
Public Property ClaveProdServ As String
|
|
Public Property NoIdentificacion As String
|
|
Public Property Cantidad As String
|
|
Public Property ClaveUnidad As String
|
|
Public Property Unidad As String
|
|
Public Property ValorUnitario As Decimal
|
|
Public Property Importe As Decimal
|
|
Public Property Descuento As Decimal
|
|
Public Property NumeroPedimento As String
|
|
Public Property CuentaPredial As String
|
|
Public Property Descripcion As String
|
|
Public Property Impuesto As String
|
|
Public Property Impuesto_Tipo As String
|
|
Public Property Impuesto_Base As Decimal
|
|
Public Property Impuesto_TipoFactor As String
|
|
Public Property Impuesto_TasaOCuota As String
|
|
Public Property Impuesto_Importe As Decimal
|
|
End Class
|
|
|
|
#End Region
|
|
|
|
End Namespace
|
|
|
|
Public Class GeneralesAPIeFacturas
|
|
|
|
Inherits ADSNetLibraryzdE.HelpersE.ConexionesE.SIGAPIE.BaseSIGAPIeFacturas
|
|
|
|
Public Sub New(ByVal Optional domainApi As String = "http://localhost:4001/", ByVal Optional token As String = "")
|
|
MyBase.New(domainApi, token)
|
|
End Sub
|
|
|
|
Public Function GeneraSolicitud(CveEmpresa As Integer, CveTipoSolicitud As Integer, CveSolicitud As Integer) As Object
|
|
Return getData(Of Object)($"GeneraSolicitud/{CveEmpresa}/{CveTipoSolicitud}/{CveSolicitud}", Nothing, ADSNetLibraryzdE.HelpersE.ConexionesE.SIGAPIE.requestMethod.[GET], False)
|
|
End Function
|
|
|
|
Public Function VerificaSolicitudesNominas(CveEmpresa As Integer, CveTipoSolicitud As Integer, CveSolicitud As Integer) As Object
|
|
Return getData(Of Object)($"VerificaSolicitudesNominas/{CveEmpresa}/{CveTipoSolicitud}/{CveSolicitud}", Nothing, ADSNetLibraryzdE.HelpersE.ConexionesE.SIGAPIE.requestMethod.[GET], False)
|
|
End Function
|
|
|
|
Public Function CancelarSolicitud(CveEmpresa As Integer, CveSolicitud As Integer, CveUsuario As Integer) As Object
|
|
Return getData(Of Object)($"CancelarSolicitud/{CveEmpresa}/{CveSolicitud}/{CveUsuario}", Nothing, ADSNetLibraryzdE.HelpersE.ConexionesE.SIGAPIE.requestMethod.[GET], False)
|
|
End Function
|
|
|
|
|
|
End Class
|
|
|
|
|
|
Namespace ADSNetLibraryzdE.HelpersE.ConexionesE.SIGAPIE
|
|
Public Enum requestMethod
|
|
POST = 1
|
|
[GET] = 2
|
|
End Enum
|
|
|
|
Public Class BaseSIGAPIeFacturas
|
|
Private Const tituloLog As String = "ADSNetLibrary.Helpers.Conexiones.SIGAPI"
|
|
Public domainApi As String
|
|
Public authorization As String
|
|
Protected RouteController As String = ""
|
|
Protected FullRoute As String = ""
|
|
|
|
Public Function GetRoutbyclass() As String
|
|
Dim classname As String = Me.[GetType]().Name
|
|
Return classname.Substring(0, classname.Length - 12)
|
|
End Function
|
|
|
|
Public Function GetRoute(ByVal path As String) As String
|
|
If String.IsNullOrEmpty(FullRoute) Then
|
|
Return String.Format("api/{0}/{1}", (If(String.IsNullOrEmpty(RouteController), GetRoutbyclass(), RouteController)), path)
|
|
Else
|
|
Return String.Format("{0}{1}", FullRoute, path)
|
|
End If
|
|
End Function
|
|
|
|
Public Sub New(ByVal domainApi As String, ByVal Optional authorization As String = Nothing, ByVal Optional fullRoute As String = Nothing)
|
|
If String.IsNullOrEmpty(domainApi) Then
|
|
domainApi = "http://localhost:4001/"
|
|
End If
|
|
|
|
Me.authorization = authorization
|
|
Me.domainApi = domainApi
|
|
Me.FullRoute = fullRoute
|
|
End Sub
|
|
|
|
Public Async Function getDataAsync(Of T As {Class, New})(ByVal path As String, ByVal requestobject As Object, ByVal Optional reqmet As requestMethod = requestMethod.POST, ByVal Optional needauthorization As Boolean = True, ByVal Optional isfullpath As Boolean = False) As Task(Of T)
|
|
Dim objreturn As T = Nothing
|
|
|
|
Using client As HttpClient = New HttpClient()
|
|
client.BaseAddress = New Uri(domainApi)
|
|
client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
|
|
|
|
If needauthorization Then
|
|
client.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Bearer", authorization)
|
|
End If
|
|
|
|
client.Timeout = TimeSpan.FromMinutes(15)
|
|
Dim response As HttpResponseMessage = New HttpResponseMessage()
|
|
Dim strjsonreq As String = Newtonsoft.Json.JsonConvert.SerializeObject(requestobject)
|
|
Dim content As StringContent = New StringContent(strjsonreq, Encoding.UTF8, "application/json")
|
|
Dim route As String = If(isfullpath, path, GetRoute(path))
|
|
|
|
Try
|
|
|
|
Select Case reqmet
|
|
Case requestMethod.POST
|
|
response = Await client.PostAsync(route, content)
|
|
Case requestMethod.[GET]
|
|
response = Await client.GetAsync(route)
|
|
End Select
|
|
|
|
If response.IsSuccessStatusCode Then
|
|
Dim jsondata As String = Await response.Content.ReadAsStringAsync()
|
|
Dim settings As Newtonsoft.Json.JsonSerializerSettings = New Newtonsoft.Json.JsonSerializerSettings With {
|
|
.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
|
|
.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore
|
|
}
|
|
objreturn = Newtonsoft.Json.JsonConvert.DeserializeObject(Of T)(jsondata, settings)
|
|
Else
|
|
End If
|
|
|
|
Catch e As Exception
|
|
End Try
|
|
End Using
|
|
|
|
Return objreturn
|
|
End Function
|
|
|
|
Public Function getData(Of T As {Class, New})(ByVal path As String, ByVal requestobject As Object, ByVal Optional reqmet As requestMethod = requestMethod.POST, ByVal Optional needauthorization As Boolean = True, ByVal Optional isfullpath As Boolean = False) As T
|
|
Return AsyncHelper.RunSync(Of T)(Function() getDataAsync(Of T)(path, requestobject, reqmet, needauthorization, isfullpath))
|
|
End Function
|
|
End Class
|
|
|
|
Friend Module AsyncHelper
|
|
Private ReadOnly _myTaskFactory As TaskFactory = New TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.[Default])
|
|
|
|
Function RunSync(Of TResult)(ByVal func As Func(Of Task(Of TResult))) As TResult
|
|
|
|
'Return AsyncHelper._myTaskFactory.StartNew(Of Task(Of TResult))(func).Unwrap(Of TResult)().GetAwaiter().GetResult()
|
|
Return AsyncHelper._myTaskFactory.StartNew(Of Task(Of TResult))(func).Unwrap().GetAwaiter().GetResult()
|
|
|
|
|
|
|
|
End Function
|
|
|
|
Sub RunSync(ByVal func As Func(Of Task))
|
|
AsyncHelper._myTaskFactory.StartNew(Of Task)(func).Unwrap().GetAwaiter().GetResult()
|
|
End Sub
|
|
End Module
|
|
End Namespace
|
|
|