diff --git a/.gitignore b/.gitignore index a3e8e0702..91e872bbf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,270 +1,5 @@ -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. -web.config -Log.txt -LogMail.txt -LogPenske.txt -LogTimbrado.txt -[Mm]enu/ -[Tt]emp/ -[Ee]mpresas/ -# User-specific files -*.suo -*.user -*.userosscache -*.sln.docstates - -# User-specific files (MonoDevelop/Xamarin Studio) -*.userprefs - -# Build results -[Dd]ebug/ -[Dd]ebugPublic/ -[Rr]elease/ -[Rr]eleases/ -x64/ -x86/ -bld/ -[Bb]in/ -[Oo]bj/ -[Ll]og/ - -# Visual Studio 2015 cache/options directory -.vs/ -# Uncomment if you have tasks that create the project's static files in wwwroot -#wwwroot/ - -# MSTest test Results -[Tt]est[Rr]esult*/ -[Bb]uild[Ll]og.* - -# NUNIT -*.VisualState.xml -TestResult.xml - -# Build Results of an ATL Project -[Dd]ebugPS/ -[Rr]eleasePS/ -dlldata.c - -# DNX -project.lock.json -project.fragment.lock.json -artifacts/ - -*_i.c -*_p.c -*_i.h -*.ilk -*.meta -*.obj -*.pch -*.pdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.tmp_proj -*.log -*.vspscc -*.vssscc -.builds -*.pidb -*.svclog -*.scc - -# Chutzpah Test files -_Chutzpah* - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opendb -*.opensdf -*.sdf -*.cachefile -*.VC.db -*.VC.VC.opendb - -# Visual Studio profiler -*.psess -*.vsp -*.vspx -*.sap - -# TFS 2012 Local Workspace -$tf/ - -# Guidance Automation Toolkit -*.gpState - -# ReSharper is a .NET coding add-in -_ReSharper*/ -*.[Rr]e[Ss]harper -*.DotSettings.user - -# JustCode is a .NET coding add-in -.JustCode - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# NCrunch -_NCrunch_* -.*crunch*.local.xml -nCrunchTemp_* - -# MightyMoose -*.mm.* -AutoTest.Net/ - -# Web workbench (sass) -.sass-cache/ - -# Installshield output folder -[Ee]xpress/ - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish/ - -# Publish Web Output -*.[Pp]ublish.xml -*.azurePubxml -# TODO: Comment the next line if you want to checkin your web deploy settings -# but database connection strings (with potential passwords) will be unencrypted -#*.pubxml -*.publishproj - -# Microsoft Azure Web App publish settings. Comment the next line if you want to -# checkin your Azure Web App publish settings, but sensitive information contained -# in these scripts will be unencrypted -PublishScripts/ - -# NuGet Packages -*.nupkg -# The packages folder can be ignored because of Package Restore -**/packages/* -# except build/, which is used as an MSBuild target. -!**/packages/build/ -# Uncomment if necessary however generally it will be regenerated when needed -#!**/packages/repositories.config -# NuGet v3's project.json files produces more ignoreable files -*.nuget.props -*.nuget.targets - -# Microsoft Azure Build Output -csx/ -*.build.csdef - -# Microsoft Azure Emulator -ecf/ -rcf/ - -# Windows Store app package directories and files -AppPackages/ -BundleArtifacts/ -Package.StoreAssociation.xml -_pkginfo.txt - -# Visual Studio cache files -# files ending in .cache can be ignored -*.[Cc]ache -# but keep track of directories ending in .cache -!*.[Cc]ache/ - -# Others -ClientBin/ -~$* -*~ -*.dbmdl -*.dbproj.schemaview -*.jfm -*.pfx -*.publishsettings -node_modules/ -orleans.codegen.cs - -# Since there are multiple workflows, uncomment next line to ignore bower_components -# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) -#bower_components/ - -# RIA/Silverlight projects -Generated_Code/ - -# Backup & report files from converting an old project file -# to a newer Visual Studio version. Backup files are not needed, -# because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML -UpgradeLog*.htm - -# SQL Server files -*.mdf -*.ldf - -# Business Intelligence projects -*.rdl.data -*.bim.layout -*.bim_*.settings - -# Microsoft Fakes -FakesAssemblies/ - -# GhostDoc plugin setting file -*.GhostDoc.xml - -# Node.js Tools for Visual Studio -.ntvs_analysis.dat - -# Visual Studio 6 build log -*.plg - -# Visual Studio 6 workspace options file -*.opt - -# Visual Studio LightSwitch build output -**/*.HTMLClient/GeneratedArtifacts -**/*.DesktopClient/GeneratedArtifacts -**/*.DesktopClient/ModelManifest.xml -**/*.Server/GeneratedArtifacts -**/*.Server/ModelManifest.xml -_Pvt_Extensions - -# Paket dependency manager -.paket/paket.exe -paket-files/ - -# FAKE - F# Make -.fake/ - -# JetBrains Rider -.idea/ -*.sln.iml -*.sln - -# CodeRush -.cr/ - -# Python Tools for Visual Studio (PTVS) -__pycache__/ -*.pyc -/Utilerias +################################################################################ +# Este archivo .gitignore ha sido creado automáticamente por Microsoft(R) Visual Studio. +################################################################################ + +/Empresas diff --git a/App_Code/ClsVentas.vb b/App_Code/ClsVentas.vb index 448b3e53a..c74d9d6a6 100644 --- a/App_Code/ClsVentas.vb +++ b/App_Code/ClsVentas.vb @@ -568,6 +568,26 @@ Public Class ClsVentas Return Retorno End Function + Public Function UpdateVentaRealizarDevolucion(CveVenta As Integer, RealizarDevolucion As Boolean, CveAlmacenDevolucion As Integer) As Boolean + Dim Retorno As Boolean = False + + DataAdapter("PA_VentasRealizarDevolucionUpdate") + + With SqlAdapter.SelectCommand.Parameters + .Add("@CveVenta", SqlDbType.Int).Value = CveVenta + .Add("@RealizarDevolucion", SqlDbType.Bit).Value = RealizarDevolucion + .Add("@CveAlmacenDevolucion", SqlDbType.Int).Value = CveAlmacenDevolucion + End With + + Try + SqlAdapter.Fill(Data) + Retorno = True + Catch ex As Exception + OnError("Ocurrió un error al actualizar el estatus de devolución.", ex, SqlAdapter.SelectCommand.Parameters.ParametrosInfo) + End Try + + Return Retorno + End Function Public Function UpdateEstatusRefacturacion(CveVenta As Integer, CveEstatusRefacturacion As Integer) As Boolean Dim Retorno As Boolean = False @@ -835,6 +855,20 @@ Public Class ClsVentas Return Retorno End Function + Public Function GetRemisionesXCancelar(CveVenta As Integer) As Boolean + Dim Retorno As Boolean = False + DataAdapter("PA_Vta_RemisionesXCancelarGet") + With SqlAdapter.SelectCommand.Parameters + .Add("@CveVenta", SqlDbType.Int).Value = CveVenta + End With + Try + SqlAdapter.Fill(Data) + Retorno = True + Catch ex As Exception + OnError("Ocurrió un error al agregar las remisiones x cancelar.", ex, SqlAdapter.SelectCommand.Parameters.ParametrosInfo) + End Try + Return Retorno + End Function Public Function AddRemisionesXCancelar(CveVenta As Integer, CveVentaRemision As Integer) As Boolean Dim Retorno As Boolean = False DataAdapter("PA_Vta_RemisionesXCancelarAdd") diff --git a/App_Code/Modelos.vb b/App_Code/Modelos.vb index 58a1b50f4..3269c0f62 100644 --- a/App_Code/Modelos.vb +++ b/App_Code/Modelos.vb @@ -285,9 +285,9 @@ Namespace Modelos Public Property CveProveedor As Integer Public Property CveMoneda As Integer - End Class - - + End Class + + #Region " OBJETOS Ventas" Public Enum TipoMensajeRespuesta TextoLimpio = 0 @@ -316,7 +316,7 @@ Namespace Modelos Public Sub New(ObjsClsPaginas As ClsPaginas, Optional Row As Data.DataRow = Nothing) If Row IsNot Nothing Then - SetValues(Row) + setValues(Row) Else IniciaValores() End If @@ -330,7 +330,7 @@ Namespace Modelos Dim ObjVentas As New ClsVentas() If ObjVentas.GetVenta(CveVenta, CveEmpresa) Then If ObjVentas.DtResultados IsNot Nothing AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then - SetValues(ObjVentas.DtResultados.Rows(0)) + setValues(ObjVentas.DtResultados.Rows(0)) SetMetodoPago(ObjsClsPaginas) SetMoneda(ObjsClsPaginas) End If @@ -344,7 +344,7 @@ Namespace Modelos Me.RemisionesLista = New List(Of Integer) Me.ListaMensajes = New List(Of String) If Row IsNot Nothing Then - SetValues(Row) + setValues(Row) Else IniciaValores() End If @@ -361,13 +361,13 @@ Namespace Modelos Me.RemisionesLista = New List(Of Integer) Me.ListaMensajes = New List(Of String) If Row IsNot Nothing Then - SetValues(Row) + setValues(Row) Else IniciaValores() End If Timbre = New CFDITimbre End Sub - Public Sub New(UsuarioActual As Usuario, CveVenta As Integer, CveEmpresa As Integer, DirectorioServidor As String) + Public Sub New(UsuarioActual As Usuario, CveVenta As Integer, CveEmpresa As Integer, Optional DirectorioServidor As String = "") Me.UsuarioActual = UsuarioActual Me.CveVenta = CveVenta Me.CveEmpresa = CveEmpresa @@ -375,10 +375,11 @@ Namespace Modelos Me.RemisionesLista = New List(Of Integer) Me.ListaMensajes = New List(Of String) Me.FolioFiscal = "" + IniciaValores() Dim ObjVentas As New ClsVentas() If ObjVentas.GetVenta(CveVenta, CveEmpresa) Then If ObjVentas.DtResultados IsNot Nothing AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then - SetValues(ObjVentas.DtResultados.Rows(0)) + setValues(ObjVentas.DtResultados.Rows(0)) SetMetodoPago() SetMoneda() SetSubProyecto() @@ -389,7 +390,11 @@ Namespace Modelos If ObjVentas.GetVentaDetalle(CveVenta) Then Me.DtDetalle = ObjVentas.DtResultados.Copy() End If - ObjVentas.Dispose() + ObjVentas.Dispose() + IniciaValoresVentas() + If String.IsNullOrEmpty(DirectorioServidor) Then + DirectorioServidor = HttpContext.Current.Server.MapPath("/") + End If Me.DirectorioServidor = DirectorioServidor Timbre = New CFDITimbre End Sub @@ -439,6 +444,43 @@ Namespace Modelos Me.IEPS = 0 Me.CveAlmacenTraspasoOrigen = 0 End Sub + Private Sub IniciaValoresVentas() + If CveVenta > 0 AndAlso CveEmpresa > 0 Then + Me.DtAnticipos = New DataTable() + Dim ObjVentas As New ClsVentas + 'CARGA PROMOCIONES + If ObjVentas.GetPromocionesPS(-1, Me.Fecha, Me.CveSubProyecto, CveCliente, Me.CveVendedor, Me.CveEmpresa) Then + Me.DtPromociones = ObjVentas.DtResultados.Copy() + End If + 'CARGA FIRMAS + If ObjVentas.GetVentasFirmas(CveVenta) Then + If ObjVentas.DtResultados.Rows.Count > 0 Then + DtFirmas = ObjVentas.DtResultados.Copy() + End If + End If + ObjVentas.Dispose() + Me.DtPagos = New DataTable() + Me.DtRemisiones = New DataTable() + Me.DtInventario = New DataTable() + Me.DtRemisionesPS = New DataTable() + Me.DtPedidos2 = New DataTable() + Me.DtPedidos2PS = New DataTable() + Me.DTOrdenesCompraPS = New DataTable() + Me.DtCotizacionesPS = New DataTable() + Me.DtDocumentacionCliente = New DataTable() + Me.DtContratosSerieDetalle = New DataTable() + Me.DtRemConceptosSurtidos = New DataTable() + Me.DtImpuestosLocales = New DataTable() + Me.DtOtrosConceptos = New DataTable() + Me.CveContratoSecciones = "" + 'Me.DtInventario = DtDetalle.FiltraParametros("CveTipoPS = 2") + + If Me.RealizarDevolucionAlmacen Then + Me.CveAlmacenDevolucion = Me.CveAlmacenDevolucionVenta + End If + + End If + End Sub Public Class MMensajeFactura Sub New() CveVenta = -1 @@ -942,8 +984,8 @@ Namespace Modelos Return Retorno - End Function - + End Function + #Region " GUARDAR - VENTA, PREPOLIZAS, INV, NC , ESTIMACIONES, AC, NOTA DE CRÉDITO " Private Function RegistrarNCAmortizacion(ObjVentas As ClsVentas, ObjConta As ClsContabilidad, ObjInventario As ClsInventarios, ObjContr As ClsContratos, ObjContPaq As ClsContPAQi, ByVal factura As Modelos.Factura, ObjBancos As ClsBancos, TmpDTconceptos As DataTable, ByRef ObjEventos As ClsOIEventos) As Boolean Dim ProcesoCorrecto As Boolean = True @@ -1742,7 +1784,9 @@ Namespace Modelos End If End If End Sub - Private Function ProcesoPrepolizas(ObjFactura As Factura, ByRef ObjConta As ClsContabilidad, CveIE As Integer, TmpDTDetalle As DataTable, ByRef objContPaqi As ClsContPAQi, Optional ValorMultiplicador As Integer = 1, ByRef Optional ObjBancos As ClsBancos = Nothing, ByRef Optional ObjVentas As ClsVentas = Nothing, ByRef Optional ObjEventos As ClsOIEventos = Nothing) As Boolean + Private Function ProcesoPrepolizas(ObjFactura As Factura, ByRef ObjConta As ClsContabilidad, CveIE As Integer, TmpDTDetalle As DataTable, ByRef objContPaqi As ClsContPAQi, + Optional ValorMultiplicador As Integer = 1, ByRef Optional ObjBancos As ClsBancos = Nothing, ByRef Optional ObjVentas As ClsVentas = Nothing, ByRef Optional ObjEventos As ClsOIEventos = Nothing, + Optional ByRef DtRemisionesRelacionadas As DataTable = Nothing, Optional SeCancelaRemisionProceso As Boolean = False, Optional CancelarRemisiones As Boolean = False, Optional ListaRemisionesCancelar As List(Of Integer) = Nothing) As Boolean Dim ErrorPrepoliza As Boolean = False Try @@ -1793,12 +1837,22 @@ Namespace Modelos Dim CveSubProyectoVenta = ObjFactura.CveSubProyecto Dim CveSubProyectoContabilizar As Integer Dim IdCtaIVAXTrasladar As Integer = 0 - Dim IdCtaIVATrasladado As Integer = 0 - - If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=ObjFactura.DtDetalle.MAX("PorcentajeIVA").ToDouble).Rows.Count > 0 Then - IdCtaIVAXTrasladar = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=ObjFactura.DtDetalle.MAX("PorcentajeIVA").ToDouble).Rows(0)("IdCtaIVAXTrasladar").ToString.ToEntero - IdCtaIVAXTrasladar = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=ObjFactura.DtDetalle.MAX("PorcentajeIVA").ToDouble).Rows(0)("IdCtaIVAXTrasladar").ToString.ToEntero + Dim IdCtaIVATrasladado As Integer = 0 + Dim CveCuentaIVAxTrasladar As Integer = 0 + Dim CveCuentaIVATrasladado As Integer = 0 + Dim SeContabiliza As Boolean = True + + If (UsuarioActual.Empresa.Funcionalidad(343) = "1" AndAlso ObjFactura.TipoDocto = "Ant") Then + SeContabiliza = False End If + + If GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=ObjFactura.DtDetalle.MAX("PorcentajeIVA").ToDouble).Rows.Count > 0 Then + IdCtaIVAXTrasladar = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=DtDetalle.MAX("PorcentajeIVA").ToDouble).Rows(0)("IdCtaIVAXTrasladar").ToString.ToEntero + CveCuentaIVAxTrasladar = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=DtDetalle.MAX("PorcentajeIVA").ToDouble).Rows(0)("CveCuentaIVAXTrasladar").ToString.ToEntero + IdCtaIVATrasladado = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=DtDetalle.MAX("PorcentajeIVA").ToDouble).Rows(0)("IdCtaIVATrasladado").ToString.ToEntero + CveCuentaIVATrasladado = GlobalDTClasificacionPorcentaje(UsuarioActual.CveEmpresa, PorcentajeIVA:=DtDetalle.MAX("PorcentajeIVA").ToDouble).Rows(0)("CveCuentaIVATrasladado").ToString.ToEntero + End If + Dim UsaComplementariaClientes As Boolean = False If UsuarioActual.CveEmpresa.Contiene(1, 119) Then UsaComplementariaClientes = True @@ -1817,74 +1871,77 @@ Namespace Modelos Select Case ConceptoContable - Case 1 'Cliente - If Not ObjFactura.TipoDocto.Contiene("Egs", "Rem") Then - importeMovimiento = ((ObjFactura.Total - ObjFactura.TotalOtrosConceptos) * ValorMultiplicador) - importeMX = (importeMovimiento * tipoCambio * Multiplicador) - FechaMovimiento = ObjFactura.FechaPago - CveSubProyectoContabilizar = CveSubProyectoVenta - If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" - - If tipoCambio = 1 Then - IdCtaContable = ObjFactura.Cliente.IdCtaContClientes - CveCuenta = ObjFactura.Cliente.CveCuentaClientes - Else - IdCtaContable = ObjFactura.Cliente.IdCtaContComplementaria - CveCuenta = ObjFactura.Cliente.CveCuentaComplementaria - If importeMovimiento <> 0 AndAlso (IdCtaContable > 0 Or CveCuenta > 0 Or UsuarioActual.CveEmpresa = 119) Then - importeMX = importeMovimiento - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, 0, Referencia, 203, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, - CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), - TipoCambio:=tipoCambio, CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar) Then - ErrorPrepoliza = True - End If - End If - - IdCtaContable = ObjFactura.Cliente.IdCtaContMonedaExtranjera - CveCuenta = ObjFactura.Cliente.CveCuentaMonedaExtranjera - End If - IdCtaContableCliente = IdCtaContable - CveCuentaCliente = CveCuenta + Case 1 'Cliente + If Not ObjFactura.TipoDocto.Contiene("Egs", "Rem") Then + importeMovimiento = (ObjFactura.Total - TotalOtrosConceptos) * ValorMultiplicador + importeMX = importeMovimiento * tipoCambio * Multiplicador + FechaMovimiento = ObjFactura.FechaPago + CveSubProyectoContabilizar = CveSubProyectoVenta + + If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" + + If tipoCambio = 1 Then + IdCtaContable = ObjFactura.Cliente.IdCtaContClientes + CveCuenta = ObjFactura.Cliente.CveCuentaClientes + Else + IdCtaContable = ObjFactura.Cliente.IdCtaContComplementaria + CveCuenta = 0 + + If importeMovimiento <> 0 AndAlso (IdCtaContable > 0 Or CveCuenta > 0 Or UsaComplementariaClientes) Then + importeMX = importeMovimiento + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, 0, Referencia, 203, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=Math.Round(importeMovimiento * tipoCambio - importeMovimiento, 2, MidpointRounding.AwayFromZero), ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), TipoCambio:=tipoCambio, CveCuenta:=CveCuenta, CveSubProyecto:=CveSubProyectoContabilizar, Contabilizable:=SeContabiliza) Then + ErrorPrepoliza = True + End If + End If + + IdCtaContable = ObjFactura.Cliente.IdCtaContMonedaExtranjera + CveCuenta = ObjFactura.Cliente.CveCuentaMonedaExtranjera + End If + + IdCtaContableCliente = IdCtaContable + CveCuentaCliente = CveCuenta End If - Case 3 'Cliente - - If ObjFactura.TipoDocto = "Ant" Then - importeMovimiento = (ObjFactura.SubTotal * ValorMultiplicador) - importeMX = importeMovimiento * tipoCambio * Multiplicador - FechaMovimiento = ObjFactura.FechaPago - IdCtaContable = ObjFactura.Cliente.IdCtaContAnticipos - CveCuenta = ObjFactura.Cliente.CveCuentaAnticipos - CveSubProyectoContabilizar = CveSubProyectoVenta - If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" + Case 3 'Cliente + + If ObjFactura.TipoDocto = "Ant" Then + ConceptoContable = If(UsuarioActual.CveEmpresa.Contiene(1, 119), 95, ConceptoContable) + importeMovimiento = ObjFactura.SubTotal * ValorMultiplicador + importeMX = importeMovimiento * tipoCambio * Multiplicador + FechaMovimiento = ObjFactura.FechaPago + IdCtaContable = ObjFactura.Cliente.IdCtaContAnticipos + CveCuenta = ObjFactura.Cliente.CveCuentaAnticipos + CveSubProyectoContabilizar = CveSubProyectoVenta + If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" End If + Case 190 'Remisión del cliente - If ObjFactura.TipoDocto = "Rem" Then - importeMovimiento = ((ObjFactura.Total - TotalOtrosConceptos) * ValorMultiplicador) - importeMX = importeMovimiento * tipoCambio * Multiplicador - FechaMovimiento = ObjFactura.FechaPago - CveSubProyectoContabilizar = CveSubProyectoVenta - If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" - - If tipoCambio = 1 Then - IdCtaContable = ObjFactura.Cliente.IdCtaContClientes - CveCuenta = ObjFactura.Cliente.CveCuentaClientes - Else - IdCtaContable = ObjFactura.Cliente.IdCtaContMonedaExtranjera - CveCuenta = ObjFactura.Cliente.CveCuentaMonedaExtranjera - End If - IdCtaContableCliente = IdCtaContable - CveCuentaCliente = CveCuenta - - If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, 190, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=False, CveSubProyecto:=CveSubProyectoContabilizar) Then - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 193, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=False, CveSubProyecto:=CveSubProyectoContabilizar) Then - ErrorPrepoliza = True - End If - Else - ErrorPrepoliza = True - End If - + If ObjFactura.TipoDocto = "Rem" Then + importeMovimiento = (ObjFactura.Total - TotalOtrosConceptos) * ValorMultiplicador + importeMX = importeMovimiento * tipoCambio * Multiplicador + FechaMovimiento = ObjFactura.FechaPago + CveSubProyectoContabilizar = CveSubProyectoVenta + If tipoCambio > 1 Then Concepto += $" TC:{tipoCambio} ${importeMovimiento.FormatoNumero(2)}" + + If tipoCambio = 1 Then + IdCtaContable = ObjFactura.Cliente.IdCtaContClientes + CveCuenta = ObjFactura.Cliente.CveCuentaClientes + Else + IdCtaContable = ObjFactura.Cliente.IdCtaContMonedaExtranjera + CveCuenta = ObjFactura.Cliente.CveCuentaMonedaExtranjera + End If + IdCtaContableCliente = IdCtaContable + CveCuentaCliente = CveCuenta + + If ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, 190, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=False, CveSubProyecto:=CveSubProyectoContabilizar) Then + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 193, Concepto, FechaMovimiento, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=ObjFactura.CveCliente, CveIE:=CveIE, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta, Contabilizable:=False, CveSubProyecto:=CveSubProyectoContabilizar) Then + ErrorPrepoliza = True + End If + Else + ErrorPrepoliza = True + End If + importeMovimiento = 0 ObjFactura.SeGuardoPrePoliza = True End If @@ -2569,104 +2626,102 @@ Namespace Modelos End If - Case 30 'PAGO - BANCOS - If DtPagos IsNot Nothing AndAlso DtPagos.Rows.Count > 0 Then - - For Each DrPago As DataRow In DtPagos.Rows - CveIEPago = -1 - - FolioIE = -1 - FolioIE = ObjBancos.GetNextFolio(DrPago("CveCuenta").ToString.ToEntero, DrPago("CveTipoMovimiento").ToString.ToEntero) - If Not FolioIE > 0 Then - ErrorPrepoliza = True - Exit For - End If - - CveIEPago = ObjBancos.AddBancos_IE(DrPago("CveCuenta").ToString.ToEntero, DrPago("CveTipoMovimiento").ToString.ToEntero, Fecha, FolioIE.ToString, String.Format("PAGO: {0}", ObjFactura.Folio), DrPago("Importe").ToString.ToDouble, ObjFactura.CveMoneda, tipoCambio, DrPago("Observaciones").ToString, "", False, False, -1, ObjFactura.CvePrePoliza, "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCorte:=CveCorte) - - If CveIEPago > 0 Then - - importeMovimiento = (DrPago("Importe").ToString.ToDecimal * ValorMultiplicador) - importeMX = importeMovimiento * tipoCambio * Multiplicador - IdCtaContable = 0 - CveCuenta = 0 - CveSubProyectoContabilizar = CveSubProyectoVenta - Dim PorcentajeImpuestoPago As Decimal = TmpDTDetalle.MAX("PorcentajeIVA").ToDecimal - - - If GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows.Count = 1 Then - IdCtaContable = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows(0)("IdCtaContable").ToString.ToEntero - CveCuenta = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows(0)("IdCtaContableSIG").ToString.ToEntero - End If - - If IdCtaContable <= 0 Then - CuentasContablesInvalidas.AppendFormat("
{0}", GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows(0)("NumCuentaMoneda").ToString.ToEntero) - idCuentaContabilizacion = 0 - End If - - If CveCuenta <= 0 Then - CuentasContablesInvalidasSIG.AppendFormat("
{0}", GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows(0)("NumCuentaMoneda").ToString.ToEntero) - CveCuentaContabilizacion = 0 - End If - - 'BANCOS - Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 30, ObjFactura.Cliente.Nombre, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString) - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, Fecha, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta) Then - ErrorPrepoliza = True - Exit For - End If - - 'CLIENTES - Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 2, ObjFactura.Cliente.Nombre, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString) - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 2, Concepto, Fecha, IdCtaContableCliente, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuentaCliente, CveSubProyecto:=CveSubProyectoContabilizar) Then - ErrorPrepoliza = True - Exit For - End If - - 'IVA X TRASLADAR - Dim IdCtaContableIVAXTrasladar As Integer = 0 - IdCtaContableIVAXTrasladar = If(IdCtaIVAXTrasladar > 0, IdCtaIVAXTrasladar, UsuarioActual.Empresa.IdCuentaIVAxTrasladar) - Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 13, ObjFactura.Cliente.Nombre, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString) - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, (importeMovimiento * ObjFactura.IVA) / ObjFactura.Total, Referencia, 13, Concepto, Fecha, IdCtaContableIVAXTrasladar, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.IVA) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=UsuarioActual.Empresa.CveCuentaIVAxTrasladar, CveSubProyecto:=CveSubProyectoContabilizar, PorcentajeImpuesto:=PorcentajeImpuestoPago) Then - ErrorPrepoliza = True - Exit For - End If - - 'IVA PAGADO - Dim IdCtaContableIVATrasladado As Integer = 0 - IdCtaContableIVATrasladado = If(IdCtaIVATrasladado > 0, IdCtaIVATrasladado, UsuarioActual.Empresa.IdCuentaIVATrasladado) - Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 61, ObjFactura.Cliente.Nombre, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString) - If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, (importeMovimiento * ObjFactura.IVA) / ObjFactura.Total, Referencia, 61, Concepto, Fecha, IdCtaContableIVATrasladado, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.IVA) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=UsuarioActual.Empresa.CveCuentaIVATrasladado, CveSubProyecto:=CveSubProyectoContabilizar, PorcentajeImpuesto:=PorcentajeImpuestoPago) Then - ErrorPrepoliza = True - Exit For - End If - - 'IEPS X TRASLADAR - Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 38, ObjFactura.Cliente.Nombre, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString) - If ObjFactura.IEPS > 0 AndAlso Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, (importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total, Referencia, 38, Concepto, Fecha, UsuarioActual.Empresa.IdCuentaIEPSxTrasladar, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=UsuarioActual.Empresa.CveCuentaIEPSxTrasladar, CveSubProyecto:=CveSubProyectoContabilizar) Then - ErrorPrepoliza = True - Exit For - End If - - 'IEPS PAGADO - Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 39, ObjFactura.Cliente.Nombre, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString) - If ObjFactura.IEPS > 0 AndAlso Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, (importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total, Referencia, 39, Concepto, Fecha, UsuarioActual.Empresa.IdCuentaIEPSTrasladado, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=UsuarioActual.Empresa.CveCuentaIEPSTrasladado, CveSubProyecto:=CveSubProyectoContabilizar) Then - ErrorPrepoliza = True - Exit For - End If - - - Else - ErrorPrepoliza = True - Exit For - End If - - Next - - importeMovimiento = 0 + Case 30 'PAGO - BANCOS + If DtPagos IsNot Nothing AndAlso DtPagos.Rows.Count > 0 Then + + For Each DrPago As DataRow In DtPagos.Rows + CveIEPago = -1 + + FolioIE = -1 + FolioIE = ObjBancos.GetNextFolio(DrPago("CveCuenta").ToString.ToEntero, DrPago("CveTipoMovimiento").ToString.ToEntero) + If Not FolioIE > 0 Then + ErrorPrepoliza = True + Exit For + End If + + CveIEPago = ObjBancos.AddBancos_IE(DrPago("CveCuenta").ToString.ToEntero, DrPago("CveTipoMovimiento").ToString.ToEntero, Fecha, FolioIE.ToString, String.Format("PAGO: {0}", ObjFactura.Folio), DrPago("Importe").ToString.ToDouble, ObjFactura.CveMoneda, tipoCambio, DrPago("Observaciones").ToString, "", False, False, -1, ObjFactura.CvePrePoliza, "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveCorte:=CveCorte) + + If CveIEPago > 0 Then + + importeMovimiento = DrPago("Importe").ToString.ToDecimal * ValorMultiplicador + importeMX = importeMovimiento * tipoCambio * Multiplicador + IdCtaContable = 0 + CveCuenta = 0 + CveSubProyectoContabilizar = CveSubProyectoVenta + Dim PorcentajeImpuestoPago As Decimal = TmpDTDetalle.MAX("PorcentajeIVA").ToDecimal + + + If GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows.Count = 1 Then + IdCtaContable = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows(0)("IdCtaContable").ToString.ToEntero + CveCuenta = GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows(0)("IdCtaContableSIG").ToString.ToEntero + End If + + If IdCtaContable <= 0 Then + CuentasContablesInvalidas.AppendFormat("
{0}", GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows(0)("NumCuentaMoneda").ToString.ToEntero) + idCuentaContabilizacion = 0 + End If + + If CveCuenta <= 0 Then + CuentasContablesInvalidasSIG.AppendFormat("
{0}", GlobalDTBancosCuentas(UsuarioActual.CveUsuario, DrPago("CveCuenta").ToString.ToEntero).Rows(0)("NumCuentaMoneda").ToString.ToEntero) + CveCuentaContabilizacion = 0 + End If + + 'BANCOS + Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 30, ObjFactura.Cliente.Nombre, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString) + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, importeMovimiento, Referencia, ConceptoContable, Concepto, Fecha, IdCtaContable, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuenta) Then + ErrorPrepoliza = True + Exit For + End If + + 'CLIENTES + Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 2, ObjFactura.Cliente.Nombre, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString) + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, importeMovimiento, Referencia, 2, Concepto, Fecha, IdCtaContableCliente, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=importeMX, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuentaCliente, CveSubProyecto:=CveSubProyectoContabilizar) Then + ErrorPrepoliza = True + Exit For + End If + + 'IVA X TRASLADAR + IdCtaIVAXTrasladar = If(IdCtaIVAXTrasladar > 0, IdCtaIVAXTrasladar, UsuarioActual.Empresa.IdCuentaIVAxTrasladar) + CveCuentaIVAxTrasladar = If(CveCuentaIVAxTrasladar > 0, CveCuentaIVAxTrasladar, UsuarioActual.Empresa.CveCuentaIVAxTrasladar) + Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 13, ObjFactura.Cliente.Nombre, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString) + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, (importeMovimiento * ObjFactura.IVA) / ObjFactura.Total, Referencia, 13, Concepto, Fecha, IdCtaIVAXTrasladar, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.IVA) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuentaIVAxTrasladar, CveSubProyecto:=CveSubProyectoContabilizar, PorcentajeImpuesto:=PorcentajeImpuestoPago) Then + ErrorPrepoliza = True + Exit For + End If + + 'IVA PAGADO + IdCtaIVATrasladado = If(IdCtaIVATrasladado > 0, IdCtaIVATrasladado, UsuarioActual.Empresa.IdCuentaIVATrasladado) + CveCuentaIVATrasladado = If(CveCuentaIVATrasladado > 0, CveCuentaIVATrasladado, UsuarioActual.Empresa.CveCuentaIVATrasladado) + Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 61, ObjFactura.Cliente.Nombre, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString) + If Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, (importeMovimiento * ObjFactura.IVA) / ObjFactura.Total, Referencia, 61, Concepto, Fecha, IdCtaIVATrasladado, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.IVA) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=CveCuentaIVATrasladado, CveSubProyecto:=CveSubProyectoContabilizar, PorcentajeImpuesto:=PorcentajeImpuestoPago) Then + ErrorPrepoliza = True + Exit For + End If + + 'IEPS X TRASLADAR + Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 38, ObjFactura.Cliente.Nombre, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString) + If ObjFactura.IEPS > 0 AndAlso Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, TipoMovimiento, (importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total, Referencia, 38, Concepto, Fecha, UsuarioActual.Empresa.IdCuentaIEPSxTrasladar, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=UsuarioActual.Empresa.CveCuentaIEPSxTrasladar, CveSubProyecto:=CveSubProyectoContabilizar) Then + ErrorPrepoliza = True + Exit For + End If + + 'IEPS PAGADO + Concepto = ObjConta.ObtenerConceptoEmpresa(UsuarioActual.CveEmpresa, 39, ObjFactura.Cliente.Nombre, $"{ObjFactura.Serie}-{ObjFactura.Folio}", FolioIE.ToString) + If ObjFactura.IEPS > 0 AndAlso Not ObjConta.AddPrePolizasDetalle(ObjFactura.CvePrePoliza, Not TipoMovimiento, (importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total, Referencia, 39, Concepto, Fecha, UsuarioActual.Empresa.IdCuentaIEPSTrasladado, -1, CveVenta:=ObjFactura.CveVenta, CveCliente:=CveCliente, CveIE:=CveIEPago, ImporteMX:=((importeMovimiento * ObjFactura.IEPS) / ObjFactura.Total) * tipoCambio * Multiplicador, ImporteME:=If(tipoCambio = 1, 0, importeMovimiento), CveCuenta:=UsuarioActual.Empresa.CveCuentaIEPSTrasladado, CveSubProyecto:=CveSubProyectoContabilizar) Then + ErrorPrepoliza = True + Exit For + End If + + Else + ErrorPrepoliza = True + Exit For + End If + + Next + + importeMovimiento = 0 End If - End Select If importeMovimiento <> 0 And Not ErrorPrepoliza Then @@ -2697,44 +2752,52 @@ Namespace Modelos End If + If DtRemisionesRelacionadas Is Nothing Then + If ObjVentas.GetRemisionesRelacionadas(ObjFactura.CveVenta, ObjFactura.TipoDocto) AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then + DtRemisionesRelacionadas = ObjVentas.DtResultados.Copy() + End If + End If + 'Si es Facturacion de una remision cancelamos, traspasamos saldos y agregamos evento a la bitacora - If RemisionesLista.Count > 0 Then - For Each CveRemision As Integer In RemisionesLista - If Not ObjConta.TraspasarSaldosRemision(CveRemision, ObjFactura.CvePrePoliza, ObjFactura.CveVenta) Then + If DtRemisionesRelacionadas IsNot Nothing AndAlso DtRemisionesRelacionadas.Rows.Count > 0 Then + For Each Row As DataRow In DtRemisionesRelacionadas.Rows + + If Not ObjConta.TraspasarSaldosRemision(Row("CveVenta").ToString().ToEntero(), ObjFactura.CvePrePoliza, ObjFactura.CveVenta) Then ErrorPrepoliza = True End If 'Factura - If Not ObjEventos.AddEventoBitacora($"Sustituye a: Folio Factura", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=ObjFactura.CveVenta) Then + If Not ObjEventos.AddEventoBitacora($"Sustituye a: Folio Factura", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=ObjFactura.CveVenta) Then ErrorPrepoliza = True End If 'Remision - If Not ObjEventos.AddEventoBitacora($"Refacturacion en: {ObjFactura.Folio}", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveRemision) Then + If Not ObjEventos.AddEventoBitacora($"Refacturacion en: {ObjFactura.Folio}", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=Row("CveVenta").ToString().ToEntero()) Then ErrorPrepoliza = True End If If ErrorPrepoliza Then Exit For End If - Next - End If - - 'REGRESA SALDO A LAS REMISIONES QUE SE FACTURARON EN EL INGRESO QUE SE ESTA CANCELANDO - If ObjFactura.TipoDocto = "Ing" And ValorMultiplicador = -1 AndAlso NuevaFactura <> 1 Then ' se debe de excluir cuando es refacturación - If ObjVentas.GetRemisionesRelacionadas(ObjFactura.CveVenta, ObjFactura.TipoDocto) AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then - For Each Dr As DataRow In ObjVentas.DtResultados.Rows - If Not ObjConta.TraspasarSaldosRemision(Dr("CveVenta").ToString.ToEntero, ObjFactura.CvePrePoliza, ObjFactura.CveVenta, 1) Then - ErrorPrepoliza = True - End If - - 'Remision - If Not ObjEventos.AddEventoBitacora($"Facturación cancelada en: {ObjFactura.Folio}", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=Dr("CveVenta").ToString.ToEntero) Then - ErrorPrepoliza = True - End If - - Next + Next + + 'REGRESA SALDO A LAS REMISIONES QUE SE FACTURARON EN EL INGRESO QUE SE ESTA CANCELANDO + If ObjFactura.TipoDocto = "Ing" And ValorMultiplicador = -1 AndAlso NuevaFactura <> 1 AndAlso Not SeCancelaRemisionProceso Then ' se debe de excluir cuando es refacturación + For Each Dr As DataRow In DtRemisionesRelacionadas.Rows + + Dim DebeCancelar As Boolean = CancelarRemisiones AndAlso ListaRemisionesCancelar.Any(Function(CveRemision) CveRemision = Dr("CveVenta").ToString.ToEntero()) + + If Not DebeCancelar Then + If Not ObjConta.TraspasarSaldosRemision(Dr("CveVenta").ToString.ToEntero, ObjFactura.CvePrePoliza, ObjFactura.CveVenta, 1) Then + ErrorPrepoliza = True + End If + If Not ObjEventos.AddEventoBitacora($"Facturación cancelada en: {ObjFactura.Folio}", "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=Dr("CveVenta").ToString.ToEntero) Then + ErrorPrepoliza = True + End If + End If + Next End If + End If @@ -3231,7 +3294,7 @@ Namespace Modelos If factura.TipoDocto.Contiene("Ing", "Egs", "OP", "Com") Then 'Dim ObjAC As New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL() - Dim IDPoliza As Integer = -1 ' GenerarPolizaAC(ObjAC, Me) + Dim IDPoliza As Integer = GenerarPolizaAC(factura, ObjAC) If IDPoliza > 0 Then @@ -3253,7 +3316,7 @@ Namespace Modelos Private Function GuardarVentaImpuestosLocales(factura As Modelos.Factura, ObjVentas As ClsVentas, ObjConta As ClsContabilidad, Optional ValorMultiplicador As Integer = 1) As Boolean Dim ErrorPrepoliza As Boolean = False - If DtImpuestosLocales IsNot Nothing AndAlso factura.CvePrePoliza > 0 AndAlso Not factura.TipoDocto.Contiene("Cot", "Rem") Then + If factura.DtImpuestosLocales IsNot Nothing AndAlso factura.CvePrePoliza > 0 AndAlso Not factura.TipoDocto.Contiene("Cot", "Rem") Then Dim Importe As Decimal Dim IdCtaContable, CveCuenta As Integer @@ -3261,7 +3324,7 @@ Namespace Modelos Dim tipoCambio As Decimal Dim CveSubProyectoContabilizar As Integer = factura.CveSubProyecto - For Each RowIL As DataRow In DtImpuestosLocales.Rows + For Each RowIL As DataRow In factura.DtImpuestosLocales.Rows If RowIL("TipoImpuesto").ToString.ToEntero > 0 Then Importe = RowIL("Importe").ToString.ToDecimal * ValorMultiplicador @@ -3417,321 +3480,977 @@ Namespace Modelos End If End Function - Private Function DecodeBase64(ByVal strXMLCodificado As String) As String + Private Shared Function DecodeBase64(ByVal strXMLCodificado As String) As String Try Dim decbuff As Byte() = Convert.FromBase64String(strXMLCodificado) Return System.Text.Encoding.UTF8.GetString(decbuff) Catch Return "" End Try - End Function - Public Function CancelarDocumento() As MMensajeFactura - Dim Retorno As New MMensajeFactura() - Retorno.CveVenta = CveVenta - Retorno.CveEstatus = Me.CveEstatus - Retorno.TieneError = False - - - If CveVenta <= 0 Then - Retorno.Mensajes.Add("Se debe asingar una CveVenta") - Retorno.TieneError = True - Return Retorno - End If - - 'CARGA REMISIONES DE LA VENTA DEVUELTA - Dim DtDevRem As New DataTable - Dim ObjInventarioTemporal As New ClsInventarios() - If ObjInventarioTemporal.GetDevolucionRemisionesCanceladas(CveVenta) Then - DtDevRem = ObjInventarioTemporal.DtResultados.FiltraParametros("CantidadSurtida > 0") - Else - Retorno.Mensajes.Add("Ocurrió un error al verificar los movimientos de almacén relacionados al documento.") - ObjInventarioTemporal.Dispose() - Retorno.TieneError = True - Return Retorno - End If - ObjInventarioTemporal.Dispose() - - If (DtInventario IsNot Nothing AndAlso DtInventario.Rows.Count > 0 AndAlso EsDevolucionVenta.Contiene(0, 1)) Then ' [COMENTADO IPP 3 Agosto 2017] | AndAlso Not (DdlTipoComprobante.SelectedValue.Contiene("Rem", "DPe")) | REMISION YA SE DEBE HACER POR EL PROCESO DE DEVOLUCION DE ALMACEN - Retorno.Mensajes.Add("La factura no se puede cancelar debido a que tiene movimientos de inventario.") - Retorno.TieneError = True - Return Retorno - End If - - Dim CancelacionFecha As Date - Dim CancelacionAcuse As String = "" - Dim MensajeError As String = "" - Dim ObjCancelacion As New Timbrado - Dim TotalT As Decimal = Total - Dim RFCReceptor As String = Me.Cliente.RFC - Dim CvePACCancelacion As Integer = Me.UsuarioActual.Empresa.CvePAC - Dim CveEstatus As Integer = 4 - Dim IDPoliza As Integer = -1 - Dim CvePrePoliza As Integer - Dim CvePlantillaPoliza As Integer - Dim ErrorCancelar As Boolean = False - - Dim Continuar As Boolean = False - Dim ContinuarCancelacion As Boolean = False - Dim ObtenerAcuse As Boolean = False - Dim RequiereAceptacion As Boolean = False - Try - If FolioFiscal <> "" Then - If Me.TipoDocto.Contiene("Ing", "Ant", "Dev", "Egs") Then - - Dim Vigencia = Timbrado.VerificarVigenciaSAT(FolioFiscal, UsuarioActual.Empresa.RFC, RFCReceptor, TotalT.ToString(), UsuarioActual.Empresa.FacturaProduccion) - If Vigencia IsNot Nothing Then - If Vigencia.EsCancelable.ToUpper() = "NO CANCELABLE" Then - Retorno.Mensajes.Add("Esta factura no es cancelable.") - Retorno.TieneError = True - Return Retorno - End If - If Vigencia.Estado.ToUpper().Contains("CANCELADO") Then - ContinuarCancelacion = False - ObtenerAcuse = True - Dim solicitud = New WSGF.Service1SoapClient() - Dim acuse = solicitud.GetAcuse(UsuarioActual.Empresa.RFC, "rene.molina@adsistemas.mx", "rene2018", FolioFiscal) - - If acuse.Estado = 0 Then - Dim xmlAcuse = New System.Xml.XmlDocument() - xmlAcuse.LoadXml(DecodeBase64(acuse.CfdiB64)) - CancelacionAcuse = xmlAcuse.GetElementsByTagName("SignatureValue")(0).InnerText - CancelacionFecha = xmlAcuse.SelectSingleNode("Acuse").Attributes("Fecha").Value.ToDate() - CveEstatus = 5 - Else - CancelacionFecha = Now.Date - CancelacionAcuse = "" - CveEstatus = 4 - End If - ElseIf Vigencia.Estado.ToUpper().Contains("VIGENTE") Then - - If Vigencia.EstatusCancelacion.ToUpper() = "EN PROCESO" Then - CveEstatus = 20 - ContinuarCancelacion = False - ElseIf Vigencia.EsCancelable.ToUpper() = "CANCELABLE CON ACEPTACIÓN" Then - CveEstatus = 20 - ContinuarCancelacion = True - RequiereAceptacion = True - ElseIf Vigencia.EsCancelable.ToUpper() = "CANCELABLE SIN ACEPTACIÓN" Then - ContinuarCancelacion = True - End If - - Else - If Vigencia.EsCancelable.ToUpper() = "CANCELABLE SIN ACEPTACIÓN" Then - ContinuarCancelacion = True - Else - Retorno.Mensajes.Add("La factura no se puede cancelar debido a que no se encontro su estatus en el SAT.") - Retorno.TieneError = True - Return Retorno - End If - End If - Else - Alert("No se pudo comprobar la vigencia de la factura.", TipoMensaje.MsgAdvertencia) - End If - - If Not ObtenerAcuse Then - If ContinuarCancelacion Then - If ObjCancelacion.CFDICancelar(UsuarioActual.Empresa, FolioFiscal, TotalT, RFCReceptor, UsuarioActual.Empresa.RFC, CvePACCancelacion) Then - 'Generamos el acuse y mandamos mail de con el acuse de cancelación - DF 13/01/2017 - If RequiereAceptacion Then - CancelacionFecha = Now.Date - CancelacionAcuse = "" - CveEstatus = 20 - Else - CancelacionFecha = ObjCancelacion.CancelacionFecha - CancelacionAcuse = ObjCancelacion.CancelacionAcuse - CveEstatus = 5 - End If - Else - Retorno.Mensajes.Add("La factura no se pudo cancelar ante el SAT") - Retorno.TieneError = True - Return Retorno - End If - Else - CancelacionFecha = Now.Date - CancelacionAcuse = "" - End If - End If - Else - CancelacionFecha = Now.Date - CancelacionAcuse = "" - End If - Else - CancelacionFecha = Now.Date - CancelacionAcuse = "" - End If - Catch ex As Exception - MensajeError = "Ocurrió un Error al Cancelar la factura con los servicios del SAT." - GuardaLog($"{MensajeError} - Error:{ex.Message}") - Alert(MensajeError, TipoMensaje.MsgError) - Retorno.TieneError = True - End Try - - Dim ObjVentas As New ClsVentas() : ObjVentas.IniciaTransacSQL() - Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL()) - Dim ObjBancos As New ClsBancos(ObjVentas.IniciaTransacSQL()) - Dim ObjInventario As New ClsInventarios(ObjVentas.IniciaTransacSQL()) - Dim ObjContrato As New ClsContratos(ObjVentas.IniciaTransacSQL()) - Dim ObjEventos As New ClsOIEventos(ObjVentas.IniciaTransacSQL()) - Dim ObjAC As ClsContPAQi = Nothing - - If UsuarioActual.Empresa.UsaAC Then - ObjAC = New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL() - End If - - Try - If Me.TipoDocto.Contiene("Egs", "Dev") Then - CvePlantillaPoliza = 7 - ElseIf Me.TipoDocto.Contiene("Ing", "Rem", "Ant") Then - CvePlantillaPoliza = 4 - Else - CvePlantillaPoliza = 4 - End If - - If (Me.Saldo > 0 AndAlso CveEstatus.Contiene(4, 5)) OrElse CvePlantillaPoliza = 7 Then - 'RMF. 2018.08.08 cuando se cancela, la póliza debe de ser de diario - CvePrePoliza = ObjConta.AddPrePolizas("Ventas/CancelarDocumento", CvePlantillaPoliza, Me.Total, Me.Total, Me.CveMoneda, Now, Me.Cliente.Nombre, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoPoliza:=3) - Me.CvePrePoliza = CvePrePoliza - - 'CANCELAR PAGOS - If Me.TipoDocto.Contiene("Egs", "Dev") Then - If Not ErrorCancelar Then - If Not ObjConta.PrePolizasCancelarPagos(CveDevolucion, CvePrePoliza) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al generar la prepoliza de cancelación de pago." - End If - End If - End If - - 'CANCELA PREPOLIZA - If Not ErrorCancelar Then - ErrorCancelar = ProcesoPrepolizas(Me, ObjConta, -1, DtDetalle, ObjAC, -1, ObjBancos, ObjVentas, ObjEventos) - MensajeError = "Ocurrió un error al generar la prepoliza de cancelación." - End If - - 'CANCELA IMPUESTOS LOCALES - If Not ErrorCancelar Then - ErrorCancelar = GuardarVentaImpuestosLocales(Me, ObjVentas, ObjConta, -1) - MensajeError = "Ocurrió un error al cancelar los impuestos locales." - End If - End If - - 'CANCELA CONTRATOS - If Not ErrorCancelar Then - ErrorList = New List(Of String) - If Me.CveContrato > 0 AndAlso Me.TipoDocto.Contiene("Ing", "Ant") Then - GuardarContratoAvanceEstimaciones(ObjContrato, ErrorList, -1, True) - ErrorCancelar = ErrorList.Count > 0 - MensajeError = "Ocurrió un error al cancelar las estimaciones del contrato." - ElseIf Me.CveContrato > 0 AndAlso Me.TipoDocto.Contiene("Egs", "Dev") Then - GuardarContratoAvanceEstimaciones(ObjContrato, ErrorList, 1, True) - ErrorCancelar = ErrorList.Count > 0 - MensajeError = "Ocurrió un error al cancelar los avances del contrato." - End If - End If - - - 'DESVINCULA REMISIONES PREDECESORAS - If Not ErrorCancelar Then - If Me.TipoDocto.Contiene("Ing", "Ant") Then - If Not ObjVentas.LiberarRemisionesFacturadas(CveVenta) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al desvincular las remisiones." - End If - End If - End If - - 'DESVINCULA COTIZACIONES PREDECESORAS - If Not ErrorCancelar Then - If Me.TipoDocto.Contiene("Ing", "Ant", "Rem") Then - If Not ObjVentas.LiberarCotizacionesFacturadas(CveVenta) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al desvincular las cotizaciones." - End If - End If - End If - - 'DESVINCULA PEDIDOS2 PREDECESORES - If Not ErrorCancelar Then - If Me.TipoDocto.Contiene("Ing", "Ant", "Rem") Then - If Not ObjVentas.LiberarPedidos2Facturados(CveVenta) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al desvincular los pedidos." - End If - End If - End If - - 'DESVINCULA OCs PREDECESORAS - If Not ErrorCancelar Then - If Me.TipoDocto = "Ing" Then - If Not ObjVentas.LiberarOCFacturadas(CveVenta) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al desvincular las Ordenes de Compra." - End If - End If - End If - - 'ELIMINA LAS VENTAS DETALLE DE LA DEVOLUCION - If Not ErrorCancelar Then - If Me.TipoDocto = "Dev" Then - If Not ObjVentas.RemoveVentaDetalleDevolucion(CveVenta) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al eliminar las ventas detalle devolución." - End If - End If - End If - - 'POLIZA DE CANCELACION - If Not ErrorCancelar Then - 'If UsuarioActual.Empresa.UsaAC Then - ' IDPoliza = GenerarPolizaAC(ObjAC, True) - ' If IDPoliza <= 0 Then - ' ErrorCancelar = True - ' MensajeError = "Ocurrió un error al generar la poliza de cancelación." - ' End If - 'End If - End If - - 'ACTUALIZA ESTATUS - If Not ErrorCancelar Then - Select Case Me.TipoDocto - Case "Rem" - CveEstatus = 12 - Case "Com" - CveEstatus = 9 - End Select - - If Not ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, CancelacionAcuse, CancelacionFecha, CveVenta, IDPoliza, CvePAC:=CvePACCancelacion) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al guardar el estatus de cancelación." - End If - End If - - If Not ErrorCancelar Then - ObjVentas.Commit() - If ObjAC IsNot Nothing Then ObjAC.Commit() - Me.CveEstatus = CveEstatus - Retorno.CveEstatus = CveEstatus - Retorno.Mensajes.Add("La factura se cancelo correctamente") - Else - Retorno.Mensajes.Add(MensajeError) - ObjVentas.RollBack() - If ObjAC IsNot Nothing Then ObjAC.RollBack() - End If - Catch ex As Exception - GuardaLog(ex.ToString()) - ObjVentas.RollBack() - If ObjAC IsNot Nothing Then ObjAC.RollBack() - Finally - - ObjVentas.Dispose() - ObjBancos.Dispose() - ObjInventario.Dispose() - ObjContrato.Dispose() - ObjConta.Dispose() - If ObjAC IsNot Nothing Then ObjAC.Dispose() - Retorno.TieneError = ErrorCancelar - End Try - Return Retorno + End Function + Public Class MCancelacionVentaMensaje + Public Property HuboError As Boolean = False + Public Property TipoMensaje As TipoMensaje + Public Property Mensaje As String + Public Property CveEstatus As Integer + End Class + ''' + ''' Ejecuta los procesos pendientes para concluir la cancelacion de la factura + ''' + ''' + ''' + ''' + ''' + Public Function EjecutarCancelacionPendiente(CveEstatus As Integer, FechaCancelacion As DateTime, AcuseCancelacion As String) As MCancelacionVentaMensaje + Dim ListaRemisionesCancelar As New List(Of Integer) + Dim ObjVentas As New ClsVentas() + If ObjVentas.GetRemisionesXCancelar(Me.CveVenta) Then + For Each Row As DataRow In ObjVentas.DtResultados.Rows + ListaRemisionesCancelar.Add(Row("CveVentaRemision").ToString().ToEntero()) + Next + End If + ObjVentas.Dispose() + + + Return CancelarVenta(Me, Me.UsuarioActual, RealizarDevolucionAlmacen:=Me.RealizarDevolucionAlmacen, ListaRemisionesCancelar:=ListaRemisionesCancelar, CveEstatusFacturaAsignado:=CveEstatus, FechaCancelacion:=FechaCancelacion.ToString("dd/MM/yyyy hh:mm:ss"), AcuseCancelacion:=AcuseCancelacion) + End Function + ''' + ''' Cancela la factura para poder realizar la refacturacion + ''' + ''' + Public Function CancelarPorRefacturacion() As MCancelacionVentaMensaje + Return CancelarVenta(Me, Me.UsuarioActual, EsRefacturacion:=True) + End Function + ''' + ''' Cancela la factura y realiza las operaciones correspondientes + ''' + ''' + ''' + ''' + Public Function CancelarFactura(RealizarDevolucionAlmacen As Boolean, Optional ListaRemisionesCancelar As List(Of Integer) = Nothing) As MCancelacionVentaMensaje + Return CancelarVenta(Me, Me.UsuarioActual, RealizarDevolucionAlmacen:=RealizarDevolucionAlmacen, ListaRemisionesCancelar:=ListaRemisionesCancelar) + End Function + + Private Function CancelarVenta(ObjFactura As Modelos.Factura, UsuarioActual As Usuario, Optional EsRefacturacion As Boolean = False, Optional RealizarDevolucionAlmacen As Boolean = False, + Optional ListaRemisionesCancelar As List(Of Integer) = Nothing, Optional CveEstatusFacturaAsignado As Integer = -1, + Optional FechaCancelacion As String = "-1", Optional AcuseCancelacion As String = "") As MCancelacionVentaMensaje + Dim Retorno As New MCancelacionVentaMensaje() + Dim ErrorList As New List(Of String) + + Dim CveVenta As Integer = ObjFactura.CveVenta + + Dim EsRemisionFacturada As Boolean = False + Dim TieneRemisionesRelacionadas As Boolean = False + Dim CancelarRemisiones As Boolean = ListaRemisionesCancelar IsNot Nothing AndAlso ListaRemisionesCancelar.Count > 0 + + Dim TieneAlmacen As Boolean = False + + 'VALIDA QUE LA FACTURA NO TENGA PAGOS + If ObjFactura.TipoDocto.Contiene("Ing", "Rem") AndAlso ObjFactura.Pagado > 0 Then + Retorno.Mensaje = "La factura no se puede cancelar debido a que tiene pagos vinculados." + Retorno.TipoMensaje = TipoMensaje.MsgAdvertencia + + Return Retorno + End If + + Dim ObjInv As New ClsInventarios + If ObjInv.GetInv_Mov(CveVenta, UsuarioActual.CveEmpresa) Then + TieneAlmacen = ObjInv.DtResultados.Rows.Count > 0 + End If + ObjInv.Dispose() + + 'CARGA AS NOTAS DE CREDITO VINCULADAS + Dim DTDocumentosRelacionados As New DataTable + If ObjFactura.TipoDocto.Contiene("Ing", "Ant", "Rem") Then + Dim ObjVentasAntNC As New ClsVentas + If ObjVentasAntNC.GetVentasAntNC(ObjFactura.CveVenta, -1) Then + DTDocumentosRelacionados = ObjVentasAntNC.DtResultados.Copy() + End If + ObjVentasAntNC.Dispose() + End If + + 'LA VALIDACION DE SALDOS CUANDO ES REFACTURACION SE HACE ANTES ASI QUE SI ES REFACTURACION IGNORAMOS ESTA CONDICION, SI ES ANTICIPO VERIFICA QUE NO ESTÉ APLICADO + If ObjFactura.TipoDocto = "Ant" AndAlso ObjFactura.Pagado > 0 AndAlso DTDocumentosRelacionados.Rows.Count > 0 Then + Retorno.Mensaje = "La factura no se puede cancelar debido a que tiene pagos vinculados." + Retorno.TipoMensaje = TipoMensaje.MsgAdvertencia + + Return Retorno + End If + + 'SI LA REMISION ESTA FACTURADA NO SE PUEDE CANCELAR + If ObjFactura.TipoDocto = "Rem" Then + Dim ObjV As New ClsVentas + If ObjV.VerificarRemisionFacturada(ObjFactura.CveVenta) Then + EsRemisionFacturada = ObjV.DtResultados.Rows.Count > 0 + End If + ObjV.Dispose() + + If EsRemisionFacturada Then + Retorno.Mensaje = "La factura no se puede cancelar debido a que tiene pagos vinculados." + Retorno.TipoMensaje = TipoMensaje.MsgAdvertencia + + Return Retorno + End If + + End If + + 'CARGA REMISIONES DE LA VENTA DEVUELTA + Dim DtDevRem As New DataTable + If Not EsRefacturacion Then + Dim ObjInventarioTemporal As New ClsInventarios() + If ObjInventarioTemporal.GetDevolucionRemisionesCanceladas(ObjFactura.CveVenta) Then + DtDevRem = ObjInventarioTemporal.DtResultados + Else + ObjInventarioTemporal.Dispose() + + Retorno.Mensaje = "Ocurrió un error al verificar los movimientos de almacén relacionados al documento." + Retorno.TipoMensaje = TipoMensaje.MsgAdvertencia + + Return Retorno + End If + ObjInventarioTemporal.Dispose() + End If + + 'CARGA REMISIONES + Dim DtRemisionesRelacionadas As New DataTable() + Dim ObjVentasRem As New ClsVentas + If ObjVentasRem.GetRemisionesRelacionadas(ObjFactura.CveVenta, ObjFactura.TipoDocto) Then + DtRemisionesRelacionadas = ObjVentasRem.DtResultados.Copy() + TieneRemisionesRelacionadas = DtRemisionesRelacionadas.Rows.Count > 0 + End If + ObjVentasRem.Dispose() + + 'SI ES REMISION PARA CANCELARLA NO DEBE TENER NINGUNA FACTURADA RELACIONADA + If ObjFactura.TipoDocto.Contiene("Rem") And DtRemisionesRelacionadas.Rows.Count > 0 Then + Retorno.Mensaje = "La remision no debe tener ninguna factura relacionada para poder cancelarla." + Retorno.TipoMensaje = TipoMensaje.MsgAdvertencia + + Return Retorno + End If + + 'CUANDO SE CANCELA, Y TIENE RELACIONADA UNA REMISIÓN, Y ESTA NO SE CANCELARÁ. DEBE DE HACER EN AUTOMÁTICO LOS MOVIMIENTOS AL ALMACEN DE ENTREGA POR ADELANTADO + Dim RevivirRemisiones = Not EsRefacturacion AndAlso ((TieneRemisionesRelacionadas AndAlso ListaRemisionesCancelar Is Nothing) OrElse (DtRemisionesRelacionadas.Rows.Count > ListaRemisionesCancelar.Count)) + + 'REMISION YA SE DEBE HACER POR EL PROCESO DE DEVOLUCION DE ALMACEN + If Not EsRefacturacion AndAlso (ObjFactura.SaldoAlmacen > 0 AndAlso ObjFactura.EsDevolucionVenta.Contiene(0, 1)) AndAlso Not RealizarDevolucionAlmacen And RevivirRemisiones = False Then + + Retorno.Mensaje = "La factura no se puede cancelar debido a que tiene movimientos de inventario." + Retorno.TipoMensaje = TipoMensaje.MsgAdvertencia + + Return Retorno + End If + + + Dim CancelacionFecha As Date + Dim FolioFiscal As String = ObjFactura.FolioFiscal + Dim CancelacionAcuse As String = "" + Dim MensajeError As String = "" + Dim ObjCancelacion As New Timbrado + Dim TotalT As Decimal = ObjFactura.Total + Dim RFCReceptor As String = ObjFactura.Cliente.RFC + Dim CvePACCancelacion As Integer = ObjFactura.CvePAC + Dim CveEstatus As Integer = 4 + Dim IDPoliza As Integer = -1 + Dim CvePrePoliza As Integer + Dim CvePlantillaPoliza As Integer + Dim ErrorCancelar As Boolean = False + + Dim Continuar As Boolean = False + Dim ContinuarCancelacion As Boolean = False + Dim ObtenerAcuse As Boolean = False + Dim RequiereAceptacion As Boolean = False + Dim Mensaje As String = "" + + If CveEstatusFacturaAsignado <= 0 Then + Try + If ObjFactura.FolioFiscal <> "" Then + If ObjFactura.TipoDocto.Contiene("Ing", "Ant", "Dev", "Egs") Then + + Dim Vigencia = Timbrado.VerificarVigenciaSAT(FolioFiscal, UsuarioActual.Empresa.RFC, RFCReceptor, TotalT.ToString(), UsuarioActual.Empresa.FacturaProduccion) + + If Vigencia IsNot Nothing Then + If Vigencia.EsCancelable.ToUpper() = "NO CANCELABLE" Then + Retorno.Mensaje = "Esta factura no es cancelable." + Retorno.TipoMensaje = TipoMensaje.MsgAdvertencia + + Return Retorno + End If + If Vigencia.Estado.ToUpper().Contains("CANCELADO") Then + ContinuarCancelacion = False + ObtenerAcuse = True + Dim solicitud = New WSGF.Service1SoapClient() + Dim acuse = solicitud.GetAcuse(UsuarioActual.Empresa.RFC, "rene.molina@adsistemas.mx", "rene2018", FolioFiscal) + + If acuse.Estado = 0 Then + Dim xmlAcuse = New System.Xml.XmlDocument() + xmlAcuse.LoadXml(DecodeBase64(acuse.CfdiB64)) + CancelacionAcuse = xmlAcuse.GetElementsByTagName("SignatureValue")(0).InnerText + CancelacionFecha = xmlAcuse.SelectSingleNode("Acuse").Attributes("Fecha").Value.ToDate() + CveEstatus = 5 + Else + CancelacionFecha = Now.Date + CancelacionAcuse = "" + CveEstatus = 5 + End If + + ElseIf Vigencia.Estado.ToUpper().Contains("VIGENTE") Then + + If Vigencia.EstatusCancelacion.ToUpper() = "EN PROCESO" Then + CveEstatus = 20 + ContinuarCancelacion = False + ElseIf Vigencia.EsCancelable.ToUpper() = "CANCELABLE CON ACEPTACIÓN" Then + CveEstatus = 20 + ContinuarCancelacion = True + RequiereAceptacion = True + ElseIf Vigencia.EsCancelable.ToUpper() = "CANCELABLE SIN ACEPTACIÓN" Then + ContinuarCancelacion = True + CveEstatus = 5 + End If + + Else + If Vigencia.EsCancelable.ToUpper() = "CANCELABLE SIN ACEPTACIÓN" Then + ContinuarCancelacion = True + CveEstatus = 5 + Else + CveEstatus = 20 + ContinuarCancelacion = False + CancelacionFecha = Now.Date + CancelacionAcuse = "" + End If + End If + Else + Retorno.Mensaje = "No se pudo comprobar la vigencia de la factura." + Retorno.TipoMensaje = TipoMensaje.MsgAdvertencia + + Return Retorno + End If + + If Not ObtenerAcuse Then + If ContinuarCancelacion Then + If ObjCancelacion.CFDICancelar(UsuarioActual.Empresa, FolioFiscal, TotalT, RFCReceptor, UsuarioActual.Empresa.RFC, CvePACCancelacion) Then + 'GENERAMOS EL ACUSE Y MANDAMOS MAIL DE CON EL ACUSE DE CANCELACIÓN + If RequiereAceptacion Then + CancelacionFecha = Now.Date + CancelacionAcuse = "" + CveEstatus = 20 + + Else + CancelacionFecha = ObjCancelacion.CancelacionFecha + CancelacionAcuse = ObjCancelacion.CancelacionAcuse + CveEstatus = 5 + End If + Else + Retorno.Mensaje = "La factura no se pudo cancelar ante el SAT." + Retorno.TipoMensaje = TipoMensaje.MsgError + + Return Retorno + End If + Else + CancelacionFecha = Now.Date + CancelacionAcuse = "" + End If + End If + Else + CancelacionFecha = Now.Date + CancelacionAcuse = "" + End If + Else + CancelacionFecha = Now.Date + CancelacionAcuse = "" + End If + Catch ex As Exception + MensajeError = "Ocurrió un Error al Cancelar la factura con los servicios del SAT." + ModExtensiones.GuardaLog($"{MensajeError} - Error:{ex.Message}") + + Retorno.Mensaje = MensajeError + Retorno.TipoMensaje = TipoMensaje.MsgAdvertencia + Retorno.HuboError = True + + Return Retorno + End Try + Else + CveEstatus = CveEstatusFacturaAsignado + CancelacionFecha = FechaCancelacion.ToDateTime() + CancelacionAcuse = AcuseCancelacion + End If + + 'SI ES CANCELACION EN PROCESO CANCELA EL PROCESO DE LAS REMISIONES + Dim SeCancelaRemisionProceso = (CveEstatus = 20 AndAlso TieneRemisionesRelacionadas AndAlso CancelarRemisiones) + + Retorno.CveEstatus = CveEstatus + + Dim ObjVentas As New ClsVentas() : ObjVentas.IniciaTransacSQL() + Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL()) + Dim ObjBancos As New ClsBancos(ObjVentas.IniciaTransacSQL()) + Dim ObjInventario As New ClsInventarios(ObjVentas.IniciaTransacSQL()) + Dim ObjContrato As New ClsContratos(ObjVentas.IniciaTransacSQL()) + Dim ObjEventos As New ClsOIEventos(ObjVentas.IniciaTransacSQL()) + Dim ObjAC As ClsContPAQi = Nothing + If UsuarioActual.Empresa.UsaAC Then + ObjAC = New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL() + End If + + + Try + If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then + CvePlantillaPoliza = 7 + ElseIf ObjFactura.TipoDocto.Contiene("Ing", "Rem", "Ant") Then + CvePlantillaPoliza = 4 + Else + CvePlantillaPoliza = 4 + End If + + 'CUANDO LA CANCELACION ESTA EN PROCESO NO DEBE REALIZAR NADA DE ESTE PROCESO + If (((ObjFactura.Saldo > 0 AndAlso (CveEstatus > 0 AndAlso CveEstatus <> 20)) OrElse (ObjFactura.Total = 0 AndAlso UsuarioActual.CveEmpresa.Contiene(72) AndAlso ObjFactura.TipoDocto.Contiene("Ing"))) AndAlso CveEstatus.Contiene(4, 5)) OrElse CvePlantillaPoliza = 7 Then + + 'CUANDO SE CANCELA, LA PÓLIZA DEBE DE SER DE DIARIO + CvePrePoliza = ObjConta.AddPrePolizas("Modelos/CancelarDocumento", CvePlantillaPoliza, ObjFactura.Total, ObjFactura.Total, ObjFactura.CveMoneda, Now, ObjFactura.Cliente.Nombre, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoPoliza:=3) + ObjFactura.CvePrePoliza = CvePrePoliza + + 'CANCELAR PAGOS + If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then + If Not ErrorCancelar Then + If Not ObjConta.PrePolizasCancelarPagos(ObjFactura.CveDevolucion, CvePrePoliza) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al generar la prepoliza de cancelación de pago." + End If + End If + End If + + 'CANCELA PREPOLIZA + If Not ErrorCancelar Then + ErrorCancelar = ProcesoPrepolizas(ObjFactura, ObjConta, -1, ObjFactura.DtDetalle, ObjAC, -1, ObjBancos, ObjVentas, ObjEventos, DtRemisionesRelacionadas:=DtRemisionesRelacionadas, + SeCancelaRemisionProceso:=SeCancelaRemisionProceso, CancelarRemisiones:=CancelarRemisiones, ListaRemisionesCancelar:=ListaRemisionesCancelar) + MensajeError = "Ocurrió un error al generar la prepoliza de cancelación." + End If + + 'CANCELA IMPUESTOS LOCALES + If Not ErrorCancelar Then + ErrorCancelar = GuardarVentaImpuestosLocales(ObjFactura, ObjVentas, ObjConta, -1) + MensajeError = "Ocurrió un error al cancelar los impuestos locales." + End If + + End If + + 'CUANDO LA CANCELACION ESTA EN PROCESO NO DEBE REALIZAR NADA DE ESTE PROCESO + If Not EsRefacturacion AndAlso (CveEstatus > 0 AndAlso CveEstatus <> 20) Then + + 'DEVOLUCION DE ALMACEN + If Not ErrorCancelar AndAlso TieneAlmacen Then + Dim TieneSalida As Boolean = False + Dim DtDatos As New DataTable + Dim DtExistencias As New DataTable + + 'CUANDO SE VAYA A REALIZAR LA DEVOLUCION AQUI DEBE MARCALA PARA NO SOLICITARLA DE NUEVO, SI NO LA SOLICITARA + If ObjFactura.EsDevolucionVenta = 0 Then + Dim EstatusDevolucion = 1 + If Not ObjVentas.UpdateVentasDevolucionAlmacen(EstatusDevolucion, CveVenta) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al solicitar la devolucion de almacen." + End If + End If + + If Not ErrorCancelar AndAlso ObjInventario.EntregaAlmacenGet(CveVenta) Then + If ObjInventario.DtResultados IsNot Nothing AndAlso ObjInventario.DtResultados.Rows.Count > 0 Then + DtDatos = ObjInventario.DtResultados + DtDatos.Columns.Add("Consec", GetType(Integer)) + DtDatos.Columns.Add("CantidadGV", GetType(Double)) + DtDatos.Columns.Add("CantidadTraspaso", GetType(Double)) + Dim Index = 1 + For Each Dr As DataRow In DtDatos.Rows + Dr("Consec") = Index + Dr("CantidadGV") = Dr("CantidadF") + Index += 1 + Next + + If DtDatos IsNot Nothing AndAlso DtDatos.Rows.Count > 0 AndAlso ObjInventario.DtResultados.Rows(0)("CveVentaPadre").ToString.ToEntero > 0 Then + Dim Filtro As String + Select Case ObjInventario.DtResultados.Rows(0)("TipoDocto").ToString + Case "Ing", "Ped" + Filtro = "CveConcepto = 3" + Case "Dev" + Filtro = "CveConcepto = 3" + Case Else + Filtro = "CveConcepto = 9" + End Select + + If ObjInventario.GetInv_Mov(ObjInventario.DtResultados.Rows(0)("CveVentaPadre").ToString.ToEntero, UsuarioActual.CveEmpresa) Then + DtExistencias = ObjInventario.DtResultados.FiltraParametros($"CvePS Is Not NULL AND {Filtro}") + + If DtExistencias.Rows.Count > 0 Then + TieneSalida = True + End If + + Else + ErrorCancelar = True + MensajeError = "Ocurrió un error al cargar los datos de devolución. Por favor vuelva a intentar." + End If + End If + + End If + End If + + If Not ErrorCancelar AndAlso TieneSalida Then + + + Dim DtTraspasos As New DataTable + DtTraspasos.Columns.Add("CveAlmacen", GetType(Integer)) + DtTraspasos.Columns.Add("Almacen", GetType(String)) + DtTraspasos.Columns.Add("CveMovimientoSalida", GetType(Integer)) + DtTraspasos.Columns.Add("FolioSalida", GetType(Integer)) + DtTraspasos.Columns.Add("CveMovimientoEntrada", GetType(Integer)) + DtTraspasos.Columns.Add("FolioEntrada", GetType(Integer)) + + Dim ConceptoMovimiento = 18 'DEVOLUCION DEL CLIENTE + Dim CveMovimiento As Integer = 0 + Dim Folio As Integer = 0 + Dim CantidadPendiente As Decimal = 0 + + If Not ErrorCancelar AndAlso RealizarDevolucionAlmacen Then + Dim CveAlmacenDevolucion = ObjFactura.CveAlmacenDevolucion + + CveMovimiento = ObjInventario.AddMovimiento(CveAlmacenDevolucion, ConceptoMovimiento, 1, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, CveVenta, -1, -1, Observaciones:="", Guia:="", CveContrato:=CveContrato, CveAlmacenDestino:=-1) + Folio = ObjInventario.Folio + + 'SALIDA DE ALMACEN - SALIDA POR TRASPASO CUANDO ES REMISION - DEVOLUCION (SI ES TRASPASO Y TIENE CONTRATO NO HACE DEVOLUCIóN) + If CveMovimiento > 0 Then + + 'ES EL MOVIMIENTO PRINCIPAL + CantidadPendiente = 0 + For Each Dr As DataRow In DtDatos.Rows + CantidadPendiente = Dr("CantidadGV").ToString.ToDecimal - Dr("CantidadTraspaso").ToString.ToDecimal + If CantidadPendiente > 0 Then + Dim PU As Decimal = 0 + + If DtExistencias IsNot Nothing Then + PU = DtExistencias.FiltroPrimeroValor("PU", $"CvePS = {Dr("CvePS")} AND CveUM = {Dr("CveUM").ToString.ToEntero}").ToString.ToDecimal + End If + + If Not ObjInventario.AddMovimientoDetalle(CveMovimiento, CantidadPendiente, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, PU, -1, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al procesar los conceptos de salida. Por favor vuelva a intentar." + Exit For + End If + + End If + Next + Else + MensajeError = "Ocurrió un error al agregar el movimiento" + ErrorCancelar = True + End If + + 'GENERA PREPOLIZA DEL MOVIMIENTO DE DEVOLUCION + If Not ErrorCancelar Then + Dim DtCostos As DataTable = Nothing + Dim ValorInventario As Decimal = 0 + If ObjInventario.GetMovimientosDetalle(CveMovimiento, UsuarioActual.CveEmpresa) Then + DtCostos = ObjInventario.DtResultados + + Dim tmpCostos As DataTable = DtCostos.FiltraParametros("", "", {"CveClasificacion"}) + Dim IdCtaContableAlmacen As Integer = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContable", $"CveAlmacen = {CveAlmacenDevolucion}").ToEntero + Dim CveCuentaAlmacen As Integer = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContableSIG", $"CveAlmacen = {CveAlmacenDevolucion}").ToEntero + Dim IdCtaContable As Integer = 0 + Dim CveCuenta As Integer = 0 + If tmpCostos.Rows.Count > 0 Then + + If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then + Dim Fecha As Date = Now + Dim CveCliente As Integer = ObjVentas.DtResultados(0)("CveCliente").ToString.ToEntero + Dim ClienteNombre As String = ObjVentas.DtResultados(0)("ClienteNombre").ToString + Dim SerieFolio As String = ObjVentas.DtResultados(0)("SerieFolio").ToString + Dim TotalCosto As Decimal = DtCostos.SUMD("Total").RoundSQL() + Dim TotalCostoAcumulado As Decimal = 0 + Dim cont As Integer = 1 + + Dim CvePrePolizaDev As Integer = ObjConta.AddPrePolizas("Inventario/RecepcionEntrega", 4, TotalCosto, TotalCosto, 1, Fecha, ClienteNombre, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) + 'SE AGREGA MOVIMIENTO SEPARADO POR LA CUENTA DE VENTAS (ER) + For Each RowInv As DataRow In tmpCostos.Rows + ValorInventario = DtCostos.SUMD("Total", $"CveClasificacion = {RowInv("CveClasificacion")}").RoundSQL() + TotalCostoAcumulado += ValorInventario + + 'CUANDO ES EL ÚLTIMO MOVIMIENTO Y HAY DIFERENCIAS EN LOS IMPORTES + If cont = DtCostos.Rows.Count AndAlso TotalCosto <> TotalCostoAcumulado Then + ValorInventario = ValorInventario + (TotalCosto - TotalCostoAcumulado) + End If + + IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaCostos", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero + CveCuenta = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaCostosSIG", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero + + If Not ErrorCancelar Then + If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaDev, False, -1 * ValorInventario, SerieFolio, 69, SerieFolio, Fecha, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveMovimientoAlmacen:=CveMovimiento, CveSubProyecto:=ObjFactura.CveSubProyecto, ImporteMX:=-1 * ValorInventario, CveCuenta:=CveCuenta, CveClasificacion:=RowInv("CveClasificacion").ToString.ToEntero) Then + ErrorCancelar = True + End If + End If + + cont += 1 + Next + + If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaDev, True, -1 * TotalCosto, SerieFolio, 68, SerieFolio, Fecha, IdCtaContableAlmacen, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveMovimientoAlmacen:=CveMovimiento, CveSubProyecto:=ObjFactura.CveSubProyecto, ImporteMX:=-1 * TotalCosto, CveCuenta:=CveCuentaAlmacen) Then + ErrorCancelar = True + End If + + 'AUTOCONTA - EL MOVIMIENTO 1 ES EL DE VENTA + + Dim AutoConta As Boolean = UsuarioActual.Empresa.Funcionalidad(200) = "1" + + If UsuarioActual.CveEmpresa = 119 AndAlso ObjFactura.TipoDocto = "Ant" Then + AutoConta = False + End If + + If AutoConta And Not ErrorCancelar Then + Dim ObjContPaq = New ClsContPAQi(UsuarioActual.Empresa) + + If IdCtaContable > 0 Then + If Not ObjConta.ContabilizarPrePoliza(CvePrePolizaDev, UsuarioActual.CveUsuario, UsuarioActual.Empresa, ObjConta:=ObjContPaq) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al contabilizar la prepoliza." + End If + Else + Alert(String.Format("No se puede contabilizar ya que falta asignación de las cuentas contables"), TipoMensaje.MsgAdvertencia) + End If + + ObjContPaq.Dispose() + End If + + Else + ErrorCancelar = True + MensajeError = "Ocurrió un Error al ingresar las prepolizas" + End If + + End If + End If + End If + + 'If Not ErrorCancelar AndAlso RevivirRemisiones Then + ' If Not GeneraMovimientosApartados(ObjInventario, DtTraspasos) Then + ' ErrorCancelar = True + ' MensajeError = "Ocurrió un error al guardar los movimientos de control de apartados" + ' End If + 'End If + + 'DEVOLUCION REMISION - REGRESA LAS EXISTENCIAS A ENTREGA POR ADELANTADO SI LA FACTURA VIENE DE REMISION + If Not ErrorCancelar AndAlso RevivirRemisiones Then + If Not GeneraMovimientosEntregaPorAdelantadoRemision(CveMovimiento, ObjVentas, ObjInventario, DtDevRem, ListaRemisionesCancelar) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al generar los movimientos de devolución a remisión" + End If + End If + + If Not ErrorCancelar Then + 'QUEMA DEVOLUCION | QUEMA = LA QUITA DE PENDIENTE POR RECIBIR (DEVOLVER) + If CveMovimiento > 0 AndAlso RealizarDevolucionAlmacen Then + If Not ErrorCancelar Then + If Not ObjVentas.UpdateVentasDevolucionAlmacen(2, CveVenta) Then + MensajeError = "Ocurrió un error al hacer la devolucion. Por favor vuelva a intentar." + ErrorCancelar = True + End If + End If + + 'AGREGA BITACORA A VENTA + If Not ErrorCancelar Then + Dim MensajeBitacora = "Devuelta" + If Not ObjEventos.AddEventoBitacora(String.Format("Venta {2} en Folio: {1}", CveMovimiento, Folio, MensajeBitacora), "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then + ErrorCancelar = True + End If + End If + End If + End If + + End If + End If + End If + + 'CANCELA CONTRATOS + If Not ErrorCancelar Then + If ObjFactura.CveContrato > 0 AndAlso ObjFactura.TipoDocto.Contiene("Ing", "Ant") Then + ObjFactura.GuardarContratoAvanceEstimaciones(ObjContrato, ErrorList, -1, True) + ErrorCancelar = ErrorList.Count > 0 + MensajeError = "Ocurrió un error al cancelar las estimaciones del contrato." + ElseIf ObjFactura.CveContrato > 0 AndAlso ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then + ObjFactura.GuardarContratoAvanceEstimaciones(ObjContrato, ErrorList, 1, True) + ErrorCancelar = ErrorList.Count > 0 + MensajeError = "Ocurrió un error al cancelar los avances del contrato." + End If + End If + + 'DESVINCULA COTIZACIONES FACTURADAS + If Not ErrorCancelar Then + If ObjFactura.TipoDocto.Contiene("Ing", "Ant", "Rem") Then + If Not ObjVentas.LiberarCotizacionesFacturadas(CveVenta) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al desvincular las cotizaciones." + End If + End If + End If + + 'DESVINCULA PEDIDOS2 PREDECESORES + If Not ErrorCancelar Then + If ObjFactura.TipoDocto.Contiene("Ing", "Ant", "Rem") Then + If Not ObjVentas.LiberarPedidos2Facturados(CveVenta) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al desvincular los pedidos." + End If + End If + End If + + 'DESVINCULA OCs PREDECESORAS + If Not ErrorCancelar Then + If ObjFactura.TipoDocto = "Ing" Then + If Not ObjVentas.LiberarOCFacturadas(CveVenta) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al desvincular las Ordenes de Compra." + End If + End If + End If + + 'ELIMINA LAS VENTAS DETALLE DE LA DEVOLUCION + If Not ErrorCancelar Then + If ObjFactura.TipoDocto = "Dev" Then + If Not ObjVentas.RemoveVentaDetalleDevolucion(CveVenta) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al eliminar las ventas detalle devolución." + End If + End If + End If + + 'POLIZA DE CANCELACION + If Not ErrorCancelar Then + If UsuarioActual.Empresa.UsaAC Then + IDPoliza = GenerarPolizaAC(ObjFactura, ObjAC, True) + If IDPoliza <= 0 Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al generar la poliza de cancelación." + End If + End If + End If + + 'DESVINCULA REMISIONES PREDECESORAS + If Not ErrorCancelar Then + If ObjFactura.TipoDocto.Contiene("Ing", "Ant") AndAlso RevivirRemisiones Then + For Each Row As DataRow In DtRemisionesRelacionadas.Rows + Dim PuedeLiberar As Boolean = (ListaRemisionesCancelar Is Nothing) OrElse (Not ListaRemisionesCancelar.Any(Function(CveRemisionCancelar) CveRemisionCancelar = Row("CveVenta").ToString().ToEntero())) + If PuedeLiberar Then + If Not ObjVentas.LiberarRemisionesFacturadas(CveVenta, Row("CveVenta").ToString().ToEntero()) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al desvincular las remisiones." + End If + End If + Next + End If + End If + + Else + 'MARCA LA VENTA PARA REALIZAR LA DEVOLUCION POSTERIORMENTE + If Not ErrorCancelar Then + If RealizarDevolucionAlmacen AndAlso CveAlmacenDevolucion > 0 Then + If Not ObjVentas.UpdateVentaRealizarDevolucion(CveVenta, RealizarDevolucionAlmacen, CveAlmacenDevolucion) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al marcar la venta para devolución" + End If + End If + End If + + End If + + Dim CveEstatusRefacturacion As Integer = 0 + 'ACTUALIZA ESTATUS + If Not ErrorCancelar Then + Select Case ObjFactura.TipoDocto + Case "Rem" + CveEstatus = 12 + Case "Com" + CveEstatus = 9 + End Select + '0 Sin Refacturacion, 1 Refacturacion en Proceso, 3. Refacturación en proceso sin aceptación + If EsRefacturacion Then + If CveEstatus = 5 Then + CveEstatusRefacturacion = 3 ' refacturación en proceso sin autorización de cancelación + Else + CveEstatusRefacturacion = 1 ' refacturación en proceso con autorización de cancelación + End If + End If + + + If Not ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, CancelacionAcuse, CancelacionFecha, CveVenta, IDPoliza, CvePAC:=CvePACCancelacion, CveEstatusRefacturacion:=CveEstatusRefacturacion, + CveUsuarioCambiaEstatus:=UsuarioActual.CveUsuario, FechaCambioEstatus:=Now.ToString("yyyy-MM-dd hh:mm:ss.mmm")) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al guardar el estatus de cancelación." + End If + + If CancelarRemisiones Then + If SeCancelaRemisionProceso Then + For Each CveRemisionCancelar In ListaRemisionesCancelar + If Not ObjVentas.AddRemisionesXCancelar(CveVenta, CveRemisionCancelar) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al guardar la remisión x cancelar." + End If + Next + + If Not ObjVentas.UpdateCancelaRemision(CveVenta, SeCancelaRemisionProceso) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al actualizar que la remision sea cancelable." + End If + + Else + + For Each CveRemisionCancelar In ListaRemisionesCancelar + If Not ObjVentas.UpdateEstatusFactura(12, "", "", CancelacionFecha, CveRemisionCancelar) Then + ErrorCancelar = True + MensajeError = "Ocurrió un error al guardar el estatus de cancelación de la remisión." + End If + Next + + End If + End If + + End If + + Catch ex As Exception + ErrorCancelar = True + MensajeError = "Ocurrió un error al cancelar el documento" + OnError("Ocurrió un error al cancelar el documento", ex) + Finally + If Not ErrorCancelar Then + ObjVentas.Commit() + If ObjAC IsNot Nothing Then ObjAC.Commit() + + If CveEstatus = 5 Then + Dim MensajeAlert As New StringBuilder + MensajeAlert.Append("El Documento se canceló correctamente.") + MensajeAlert.Append($"
Imprimir Acuse") + MensajeAlert.Append("

¿Desea enviar el Acuse de Cancelación al Cliente?") + + Retorno.Mensaje = MensajeAlert.ToString + Retorno.HuboError = False + Retorno.TipoMensaje = TipoMensaje.MsgConfirmacion + + Else + If Not EsRefacturacion Then + Retorno.Mensaje = "El documento se canceló exitosamente" + Retorno.HuboError = False + Retorno.TipoMensaje = TipoMensaje.MsgInformacion + End If + End If + + Me.CveEstatus = CveEstatus + Else + ObjVentas.RollBack() + If ObjAC IsNot Nothing Then ObjAC.RollBack() + + Retorno.Mensaje = MensajeError + Retorno.HuboError = True + Retorno.TipoMensaje = TipoMensaje.MsgError + + End If + + Retorno.CveEstatus = CveEstatus + + ObjVentas.Dispose() + ObjBancos.Dispose() + ObjInventario.Dispose() + ObjContrato.Dispose() + ObjConta.Dispose() + If ObjAC IsNot Nothing Then ObjAC.Dispose() + End Try + + Return Retorno + End Function + Private Function GeneraMovimientosEntregaPorAdelantadoRemision(CveMovimiento As Integer, ByRef ObjVentas As ClsVentas, ByRef ObjInventario As ClsInventarios, ByRef DtDevRem As DataTable, ByRef ListaRemisionesCancelar As List(Of Integer)) As Boolean + Dim ErrorCancelar As Boolean = False + + Dim DtMovtosDev As New DataTable + Dim CveAlmacenTraspasoDestinoDevRem = -1 + + Dim CveVentaDetalleRem = -1 + Dim CantidadDevolver As Decimal = 0 + Dim CantidadRem As Decimal = 0 + Dim CveMovimientoSalidaDevRem As Integer = 0 + Dim FolioMovimientoSalidaDevRem As Integer = 0 + Dim CveMovimientoEntradaDevRem As Integer = 0 + Dim FolioMovimientoEntradaDevRem As Integer = 0 + + 'CARGA REMISIONES DE LA VENTA DEVUELTA + If ObjInventario.GetDevolucionRemisionesFacturadas(CveVenta) Then + DtDevRem = ObjInventario.DtResultados.FiltraParametros("CantidadAlmacen > 0") + Else + ErrorCancelar = True + End If + + 'CARGA CONCEPTOS DEVUELTOS EN LA VENTA + If ObjInventario.GetMovimientosDetalle(CveMovimiento, UsuarioActual.CveEmpresa) Then + DtMovtosDev = ObjInventario.DtResultados + Else + ErrorCancelar = True + End If + + If Not ErrorCancelar Then + If DtDevRem.Rows.Count > 0 And DtMovtosDev.Rows.Count > 0 Then + + For Each DrMovtos As DataRow In DtDevRem.FiltraParametros("", "CveRem", {"CveRem", "CveAlmacenTraspasoDestino"}).Rows + + 'CHECO SI NO SE VA A CANCELAR + Dim SeCancela As Boolean = (ListaRemisionesCancelar IsNot Nothing) AndAlso (ListaRemisionesCancelar.Any(Function(CveRemisionCancelar) CveRemisionCancelar = DrMovtos("CveRem").ToString.ToEntero())) + + If Not SeCancela Then + + CveAlmacenTraspasoDestinoDevRem = DrMovtos("CveAlmacenTraspasoDestino").ToString.ToEntero + + If Not CveAlmacenTraspasoDestinoDevRem > 0 Then + ErrorCancelar = True + Exit For + End If + + 'SALIDA GENERAL + CveMovimientoSalidaDevRem = ObjInventario.AddMovimiento(CveAlmacenDevolucion, 8, 1, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, DrMovtos("CveRem").ToString.ToEntero, -1, -1, Observaciones:="", Guia:="", CveContrato:=CveContrato, CveMovimientoRelacionado:=CveMovimiento, CveAlmacenDestino:=CveAlmacenTraspasoDestinoDevRem) + FolioMovimientoSalidaDevRem = ObjInventario.Folio + + 'ENTRADA ADELANTADO + CveMovimientoEntradaDevRem = ObjInventario.AddMovimiento(CveAlmacenTraspasoDestinoDevRem, 9, 1, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, DrMovtos("CveRem").ToString.ToEntero, -1, -1, Observaciones:="", Guia:="", CveContrato:=CveContrato, CveMovimientoRelacionado:=CveMovimientoSalidaDevRem, CveAlmacenDestino:=CveAlmacenDevolucion) + FolioMovimientoEntradaDevRem = ObjInventario.Folio + + If Not (CveMovimientoSalidaDevRem > 0 And CveMovimientoEntradaDevRem > 0) Then + ErrorCancelar = True + Exit For + End If + + 'SALIDA POR TRAPASO DE GENERAL + For Each DrRem As DataRow In DtDevRem.FiltraParametros($"CveRem = {DrMovtos("CveRem")}").Rows + CveVentaDetalleRem = DrRem("CveVentaDetalleRem").ToString.ToEntero + CantidadRem = DrRem("CantidadFacturada").ToString.ToDecimal + + If Not CveVentaDetalleRem > 0 Then + ErrorCancelar = True + Exit For + End If + + For Each Dr As DataRow In DtMovtosDev.FiltraParametros($"CveVentaDetalle = {DrRem("CveVentaDetalle").ToString.ToEntero}").Rows + If Not ObjInventario.AddMovimientoDetalle(CveMovimientoSalidaDevRem, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDouble, Dr("CveAF").ToString.ToEntero, -1, Dr("SerieLote").ToString, CveVentaDetalle:=CveVentaDetalleRem, Lote:=Dr("Lote").ToString, Batch:=Dr("Batch").ToString) Then + ErrorCancelar = True + Exit For + End If + Next + + If ErrorCancelar Then + Exit For + End If + Next + + If ErrorCancelar Then + Exit For + End If + + 'ENTRADA POR TRAPASO A ENTREGA POR ADELANTADO + If ObjInventario.GetMovimientosDetalle(CveMovimientoSalidaDevRem, UsuarioActual.CveEmpresa) Then + For Each Dr As DataRow In ObjInventario.DtResultados.Rows + If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntradaDevRem, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDecimal, Dr("CveAF").ToString.ToEntero, -1, Dr("SerieLote").ToString, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero, Lote:=Dr("Lote").ToString, Batch:=Dr("Batch").ToString) Then + ErrorCancelar = True + Exit For + End If + Next + + If ErrorCancelar Then + Exit For + End If + + Else + ErrorCancelar = True + Exit For + End If + + + If Not ObjVentas.UpdateVentasDevolucionAlmacen(0, DrMovtos("CveRem").ToString.ToEntero) Then + ErrorCancelar = True + Exit For + End If + + End If + + Next + End If + End If + + Return Not ErrorCancelar + End Function + + Private Function GeneraMovimientosApartados(ByRef ObjInventario As ClsInventarios, ByRef DtTraspasos As DataTable) As Boolean + Dim ErrorCancelar As Boolean = False + If Not ErrorCancelar Then + If ObjInventario.VentasAlmacenApartadosGet(CveVenta) Then + + Dim DtTempApartados = ObjInventario.DtResultados.FiltraParametros("CveTipoAlmacen = 9", "CveAlmacen") + Dim CveMovimientoSalidaApartado = -1 + Dim CveAlmacenApartado = -1 + Dim CveAlmacenOrigen = CveAlmacenDevolucion + Dim FolioSalida As Integer = 0, FolioEntrada = 0, CveMovimientoSalida = 0, CveMovimientoEntradaApartado = 0 + + For Each Dr As DataRow In DtTempApartados.Rows + + If CveMovimientoSalidaApartado = -1 Or CveAlmacenApartado <> Dr("CveAlmacen").ToString.ToEntero Then + CveMovimientoSalidaApartado = ObjInventario.AddMovimiento(CveAlmacenOrigen, 8, 1, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, CveVenta, -1, -1, Observaciones:="", Guia:="", CveContrato:=CveContrato, CveVendedor:=1, CveCliente:=CveCliente, CveAlmacenDestino:=Dr("CveAlmacen").ToString.ToEntero) + FolioSalida = ObjInventario.Folio + CveAlmacenApartado = Dr("CveAlmacen").ToString.ToEntero + + Dim DrMovto = DtTraspasos.NewRow + DrMovto("Almacen") = Dr("Almacen").ToString.ToEntero + DrMovto("CveAlmacen") = Dr("CveAlmacen").ToString.ToEntero + DrMovto("CveMovimientoSalida") = CveMovimientoSalidaApartado + DrMovto("FolioSalida") = FolioSalida + DtTraspasos.Rows.Add(DrMovto) + End If + + If Not CveMovimientoSalidaApartado > 0 Then + ErrorCancelar = True + Exit For + End If + + If Not ObjInventario.AddMovimientoDetalle(CveMovimientoSalidaApartado, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDecimal, Dr("CveAF").ToString.ToEntero, -1, Dr("SerieLote").ToString, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero, Lote:=Dr("Lote").ToString, Batch:=Dr("Batch").ToString) Then + ErrorCancelar = True + Exit For + End If + Next + + If Not ErrorCancelar Then + For Each Dr1 As DataRow In DtTraspasos.Rows + CveMovimientoSalida = Dr1("CveMovimientoSalida").ToString.ToEntero + + CveMovimientoEntradaApartado = ObjInventario.AddMovimiento(Dr1("CveAlmacen").ToString.ToEntero, 9, 1, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, CveVenta, -1, -1, Observaciones:="", CveAlmacenDestino:=CveAlmacenDevolucion, CveMovimientoRelacionado:=CveMovimientoSalida, Guia:="", CveContrato:=CveContrato, CveVendedor:=-1, CveCliente:=CveCliente) + FolioEntrada = ObjInventario.Folio + + If Not CveMovimientoEntradaApartado > 0 Then + ErrorCancelar = True + Exit For + End If + + Dr1("CveMovimientoEntrada") = CveMovimientoEntradaApartado + Dr1("FolioEntrada") = FolioEntrada + + If ObjInventario.GetMovimientosDetalle(CveMovimientoSalida, UsuarioActual.CveEmpresa) Then + For Each Dr As DataRow In ObjInventario.DtResultados.Rows + If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntradaApartado, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDecimal, Dr("CveAF").ToString.ToEntero, -1, Dr("SerieLote").ToString, CveMovimientoDetalleEntrada:=Dr("CveMovimientoDetalle").ToString.ToEntero, Lote:=Dr("Lote").ToString, Batch:=Dr("Batch").ToString) Then + ErrorCancelar = True + Exit For + End If + Next + End If + + If ErrorCancelar Then Exit For + Next + End If + Else + ErrorCancelar = True + End If + End If + + Return Not ErrorCancelar + End Function + + + Public Function CancelarDocumento() As MMensajeFactura + Dim Retorno As New MMensajeFactura() + + CancelarVenta(Me, UsuarioActual) + + Return Retorno End Function Protected Function CancelarFactura(ByRef ObjVentas As ClsVentas, ByRef ObjConta As ClsContabilidad, ByRef ObjAC As ClsContPAQi, ByRef ObjBancos As ClsBancos) As Boolean @@ -3800,11 +4519,11 @@ Namespace Modelos If ObjCancelacion.CFDICancelar(UsuarioActual.Empresa, FolioFiscal, Total, RFCReceptor, UsuarioActual.Empresa.RFC) Then 'falta verificar traer el acuse y reenviarlo If UsuarioActual.Empresa.UsaAC Then - 'IDPoliza = GenerarPolizaAC(ObjAC, True) - 'If IDPoliza <= 0 Then - ' Mensaje = "No se pudo generar la poliza" - ' ErrorCancelar = True - 'End If + IDPoliza = GenerarPolizaAC(Me, ObjAC, True) + If IDPoliza <= 0 Then + Mensaje = "No se pudo generar la poliza" + ErrorCancelar = True + End If End If If Not ErrorCancelar Then @@ -3835,168 +4554,117 @@ Namespace Modelos End If Return ProcesoCorrecto - End Function - + End Function + Private Function GenerarPolizaAC(ObjFactura As Modelos.Factura, ObjAC As ClsContPAQi, Optional CancelacionIngreso As Boolean = False) As Integer + Dim Retorno As Integer = 0 + Dim IDPoliza As Integer = 0 + + Dim ErrorAC As Boolean = False + 'Dim ObjAC As New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL() + Dim Fecha As Date = ObjFactura.Fecha + Dim Concepto As String = String.Format("GD {0}", ObjFactura.Cliente.Nombre) + Dim Paridad As Integer = 1 + Dim TipoMovto As Boolean = False + + If CancelacionIngreso Then + Concepto = String.Format("Cancelación GD {0}", ObjFactura.Cliente.Nombre) + Paridad = -1 + TipoMovto = True + End If + + Dim TipoPoliza = If(ObjFactura.TipoDocto = "OP" Or ObjFactura.TipoDocto = "Com", 3, 1) + + IDPoliza = ObjAC.AddPoliza(TipoPoliza, Concepto, ObjFactura.Total * 2, ObjFactura.Total * 2, UsuarioActual.CveUsuario, Fecha) + Dim dr As DataRow + + Dim CtaCliente As Integer = ObjFactura.Cliente.IdCtaContClientes + Dim CtaISSSTESON As Integer = 643 + Dim CtaISPT As Integer = 1745 + + + If IDPoliza > 0 Then + + 'Orden de PAGO + If ObjFactura.TipoDocto = "OP" Then + 'ORDEN DE PAGO + If ObjFactura.Num3 = 1 Then + 'ISSSTESON + + If ObjAC.AddMovimiento(IDPoliza, CtaCliente, False, Paridad * ObjFactura.Total, "", Concepto, 0, Fecha, "") Then + If Not ObjAC.AddMovimiento(IDPoliza, CtaISSSTESON, True, Paridad * ObjFactura.Total, "", Concepto, 0, Fecha, "") Then + ErrorAC = True + End If + Else + ErrorAC = True + End If + + Else + 'ISPT + + If ObjAC.AddMovimiento(IDPoliza, CtaCliente, False, Paridad * ObjFactura.Total, "", Concepto, 0, Fecha, "") Then + If Not ObjAC.AddMovimiento(IDPoliza, CtaISPT, True, Paridad * ObjFactura.Total, "", Concepto, 0, Fecha, "") Then + ErrorAC = True + End If + Else + ErrorAC = True + End If + End If + + ' NORMAL + Else + Dim DTPresupuestoIngresos As New DataTable + Dim AC As New ClsAC + If AC.GetPresupuestoIngresos(-1, Now.Year, True, UsuarioActual.CveEmpresa) Then + DTPresupuestoIngresos = AC.DtResultados.Copy() + End If + AC.Dispose() + + For Each grp As DataRow In DtDetalleAC.Rows + dr = DTPresupuestoIngresos.FiltroPrimero(String.Format("CvePresupuestoIngreso = {0}", grp("CvePresupuestoIngreso"))) + Concepto = String.Format("{0} - {1}: {2}", ObjFactura.Cliente.Nombre, ObjFactura.TipoDocumento, ObjFactura.Folio) + + If ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaPorEjecutar").ToString.ToEntero, False, Paridad * grp("TotalImporte").ToString().ToDouble(), "", Concepto, 0, Fecha, "") Then + If ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaDevengado").ToString.ToEntero, True, Paridad * grp("TotalImporte").ToString().ToDouble(), "", Concepto, 0, Fecha, "") Then + 'CARGO la deuda del cliente + If ObjAC.AddMovimiento(IDPoliza, CtaCliente, TipoMovto, grp("TotalImporte").ToString().ToDouble(), "", Concepto, 0, Fecha, "") Then + 'abono, + If Not ObjAC.AddMovimiento(IDPoliza, dr("IdCuentaMatriz").ToString.ToEntero, Not TipoMovto, grp("TotalImporte").ToString().ToDouble(), "", Concepto, 0, Fecha, "") Then + ErrorAC = True + End If + Else + ErrorAC = True + End If + Else + ErrorAC = True + End If + Else + ErrorAC = True + End If + Next + End If + + Else + ErrorAC = True + End If + + If Not ErrorAC Then + ObjAC.AjustaPoliza(IDPoliza) + + Retorno = IDPoliza + Else + Retorno = -1 + 'Alert("Error al Agregar la Póliza de AC.", TipoMensaje.MsgError) + End If + + Return Retorno + + End Function + #End Region - - -#Region "Claves" - - Public Property CveVenta As Integer - Public Property CveEmpresa As Integer - Public Property CveSucursal As Integer 'sucursal de la empresa que factura - Public Property CveSubProyecto As Integer - Public Property CveAlmacenRecepcionUsados As Integer = -1 - Public Property CveDireccionEnvio As Integer - Public Property RefacturacionGeneroNC As Boolean = False - 'Public Property Sucursal As SucursalModel - Public Property SubProyecto As Modelos.SubProyectoModel - - Public DtDetalle As Data.DataTable - Public DtAjustes As Data.DataTable - Public DtRecepcionUsados As Data.DataTable - Public DtVentasNC As Data.DataTable - Public DtDeduccion As Data.DataTable - Public DtFirmas As Data.DataTable - Public DtDesgloseImpuestos As Data.DataTable - Public DtDocumentosRelacionados As Data.DataTable - Public DtNCVinculadas As Data.DataTable - - Public DtAnticipos As Data.DataTable - Public DtPromociones As Data.DataTable - Public DtImpuestosLocales As Data.DataTable - Public DtPagos As Data.DataTable - Public DtRemisionesPS As Data.DataTable - Public DtRemisiones As Data.DataTable - Public DtPedidos2 As Data.DataTable - Public DtPedidos2PS As Data.DataTable - Public DTOrdenesCompraPS As Data.DataTable - Public DtCotizacionesPS As Data.DataTable - Public DtDocumentacionCliente As Data.DataTable - Public DtContratosSerieDetalle As Data.DataTable - Public DtOtrosConceptos As Data.DataTable - Public DtInventario As Data.DataTable - Public DtRemConceptosSurtidos As Data.DataTable - Public Property UsadosBonificacion As List(Of Integer) - Public Property TipoBonificacion As Integer = 0 - Public Property Timbre As CFDITimbre - Public Property CveCliente As Integer - Public Property Cliente As Modelos.ClienteModel - Public Property SubProyectoMatriz As Modelos.SubProyectoModel - - Public Sub SetSubProyecto() - If CveSubProyecto > 0 Then - SubProyecto = New Modelos.SubProyectoModel(GlobalDTSubProyectos(-1).FiltroPrimero($"CveSubProyecto = {CveSubProyecto}")) - End If - End Sub - Public Sub SetSubProyectoMatriz() - Dim Row As Data.DataRow = GlobalDTSubProyectos(-1, CveSubProyecto:=-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero("TipoSucursal=1") - If Not IsNothing(Row) Then - SubProyectoMatriz = New Modelos.SubProyectoModel(Row) - End If - End Sub - Public Sub SetCliente() - If CveCliente > 0 Then - Cliente = New Modelos.ClienteModel(CveCliente, CveEmpresa) - End If - End Sub - Public Sub SetMoneda() - If CveMoneda > 0 Then - Dim dr As DataRow = GlobalDTMonedas.FiltroPrimero(String.Format("CveMoneda ={0}", CveMoneda)) - If Not IsNothing(dr) Then - Moneda = dr("Moneda").ToString() - MonedaSAT = dr("AbreviaturaSAT").ToString() - MonedaAbreviatura = dr("Abreviatura").ToString() - End If - End If - End Sub - Public Sub SetMetodoPago() - If CveMetodoPago > 0 AndAlso Not IsNothing(GlobalDTMetodosPago.FiltroPrimero(String.Format(" CveMetodoPago ={0}", CveMetodoPago))) Then - MetodoPago = GlobalDTMetodosPago.FiltroPrimero(String.Format(" CveMetodoPago ={0}", CveMetodoPago))("MetodoPago").ToString() - ClaveMetodoPagoSAT = GlobalDTMetodosPago.FiltroPrimero(String.Format(" CveMetodoPago ={0}", CveMetodoPago))("ClaveSAT").ToString() - End If - End Sub - Public Sub SetMoneda(ObjClsPaginas As ClsPaginas) - If Not IsNothing(ObjClsPaginas) Then - Dim dr As DataRow = ObjClsPaginas.GlobalDTMonedas.FiltroPrimero(String.Format("CveMoneda ={0}", CveMoneda)) - If Not IsNothing(dr) Then - Moneda = dr("Moneda").ToString() - MonedaSAT = dr("AbreviaturaSAT").ToString() - MonedaAbreviatura = dr("Abreviatura").ToString() - End If - End If - End Sub - Public Sub SetMetodoPago(ObjClsPaginas As ClsPaginas) - If Not IsNothing(ObjClsPaginas) Then - If Not IsNothing(ObjClsPaginas.GlobalDTMetodosPago.FiltroPrimero(String.Format(" CveMetodoPago ={0}", CveMetodoPago))) Then - MetodoPago = ObjClsPaginas.GlobalDTMetodosPago.FiltroPrimero(String.Format(" CveMetodoPago ={0}", CveMetodoPago))("MetodoPago").ToString() - ClaveMetodoPagoSAT = ObjClsPaginas.GlobalDTMetodosPago.FiltroPrimero(String.Format(" CveMetodoPago ={0}", CveMetodoPago))("ClaveSAT").ToString() - End If - End If - End Sub - Public Sub SetSubProyecto(obj As ClsPaginas) - If CveSubProyecto > 0 AndAlso Not IsNothing(obj) Then - SubProyecto = New Modelos.SubProyectoModel(obj.GlobalDTSubProyectos(-1).FiltroPrimero($"CveSubProyecto = {CveSubProyecto}")) - End If - End Sub - Public Sub SetSubProyectoMatriz(obj As ClsPaginas) - If Not IsNothing(obj) Then - Dim Row As Data.DataRow = obj.GlobalDTSubProyectos(-1, CveSubProyecto:=-1, CveEmpresa:=obj.UsuarioActual.CveEmpresa).FiltroPrimero("TipoSucursal=1") - If Not IsNothing(Row) Then - SubProyectoMatriz = New Modelos.SubProyectoModel(Row) - End If - End If - End Sub - - Public Property CveClienteSucursal As Integer - Public Property ClienteSucursal As Modelos.SucursalModel - Public Property EnviarA As Modelos.EnviarAModel - Public Property NumeroContrato As String - Public Property PedidoContrato As String - Public Property OrdenCompra As String = "-1" - Public Property CveMetodoPago As Integer - Public Property MetodoPago As String - Public Property ClaveMetodoPagoSAT As String - Public Property CveMetodoPago33 As Integer - Public Property MetodoPago33 As String - Public Property CveFormaPago33 As Integer - Public Property MetodoPagoSAT33 As String - Public Property FormaPago33 As String - Public Property FormaPagoSAT33 As String - Public Property UsoCFDI As String = "" - Public Property CveUsoCFDI As Integer - Public Property ClaveUsoCFDI As String = "" - Public Property CveTipoRelacion As Integer = -1 - Public Property CveEstatusFactura As Integer - Public Property CveVendedor As Integer - Public Property VendedorCodigo As String - Public Property CveSucursalEjecucion As Integer - Public Property FechaEjecucion As Date - Public Property CveSucursalCobranza As Integer - - Public Property CveSubProyectoCobranza As Integer - Public Property CveSubProyectoEjecucion As Integer - Public Property CveOS As Integer - Public Property CveContrato As Integer - Public Property CveVentaPadre As Integer - Public Property CvePrePoliza As Integer - Public Property Entrega As String - Public Property TiempoEntrega As String - Public Property Vigencia As Date - Public Property TipoEstatus As Integer - Public Property CveCondicionEntrega As Integer - Public Property CondicionEntrega As String - - Public Property TipoRelacion As String - Public Property UUIDRelacionados As List(Of String) - - - Public Property CveVentaRelacion As Integer = -1 - Public Property ImporteRelacion As Decimal - - -#End Region - 'Ventas + + +#Region "P R O P I E D A D E S" + Public Property NuevaFactura As Integer Public Property EnviarCorreo As Boolean = False Public Property ErrorList As List(Of String) @@ -4041,10 +4709,55 @@ Namespace Modelos Public Property CvePSAmortizacion As Integer Public Property SaldoVentaDevolucion As Decimal Public Property Saldo As Decimal + Public Property SaldoAlmacen As Decimal + Public Property CvePAC As Integer Public Property CveAnticipo As Integer Public Property RemisionesLista As List(Of Integer) Public Property CveAlmacen As Integer + Public Property CveAlmacenDevolucion As Integer + Public Property CveVenta As Integer + Public Property CveEmpresa As Integer + Public Property CveSucursal As Integer 'sucursal de la empresa que factura + Public Property CveSubProyecto As Integer + Public Property CveAlmacenRecepcionUsados As Integer = -1 + Public Property CveDireccionEnvio As Integer + Public Property RefacturacionGeneroNC As Boolean = False + Public Property Pagado As Decimal + 'Public Property Sucursal As SucursalModel + Public Property SubProyecto As Modelos.SubProyectoModel + Public DtDetalle As Data.DataTable + Public DtDetalleAC As Data.DataTable + Public DtAjustes As Data.DataTable + Public DtRecepcionUsados As Data.DataTable + Public DtVentasNC As Data.DataTable + Public DtDeduccion As Data.DataTable + Public DtFirmas As Data.DataTable + Public DtDesgloseImpuestos As Data.DataTable + Public DtDocumentosRelacionados As Data.DataTable + Public DtNCVinculadas As Data.DataTable + + Public DtAnticipos As Data.DataTable + Public DtPromociones As Data.DataTable + Public DtImpuestosLocales As Data.DataTable + Public DtPagos As Data.DataTable + Public DtRemisionesPS As Data.DataTable + Public DtRemisiones As Data.DataTable + Public DtPedidos2 As Data.DataTable + Public DtPedidos2PS As Data.DataTable + Public DTOrdenesCompraPS As Data.DataTable + Public DtCotizacionesPS As Data.DataTable + Public DtDocumentacionCliente As Data.DataTable + Public DtContratosSerieDetalle As Data.DataTable + Public DtOtrosConceptos As Data.DataTable + Public DtInventario As Data.DataTable + Public DtRemConceptosSurtidos As Data.DataTable + Public Property UsadosBonificacion As List(Of Integer) + Public Property TipoBonificacion As Integer = 0 + Public Property Timbre As CFDITimbre + Public Property CveCliente As Integer + Public Property Cliente As Modelos.ClienteModel + Public Property SubProyectoMatriz As Modelos.SubProyectoModel 'CFDi Public Property Version As String @@ -4071,7 +4784,8 @@ Namespace Modelos Public Property SeTimbro As String Public Property TipoDocto As String Public Property RefDocto As String - + Public Property RealizarDevolucionAlmacen As Boolean + Public Property CveAlmacenDevolucionVenta As Integer Public Property TipoDocumento As String @@ -4205,9 +4919,9 @@ Namespace Modelos End Get End Property - Public Property MotivoDescuento As String - - + Public Property MotivoDescuento As String + + #Region "Totales" Public Property SubTotal As Decimal Public Property Descuento As Decimal @@ -4220,10 +4934,10 @@ Namespace Modelos Public Property IEPS As Decimal Public Property Total As Decimal - Public Property Otros As Decimal - + Public Property Otros As Decimal + #Region "Totales por Tipo de cambio" - + Public ReadOnly Property SubTotalTC As Decimal Get If ConvertirPesos Then @@ -4305,7 +5019,7 @@ Namespace Modelos Return Otros End If End Get - End Property + End Property #End Region #End Region Public Property AtencionA As String @@ -4354,10 +5068,124 @@ Namespace Modelos Public Property ComplementoINE As Modelos.ComplementoINE Public Property FordGSDB As String = "" Public Property FordASN As String = "" - Public Property FemsaFactura As Modelos.FemsaFactura + Public Property FemsaFactura As Modelos.FemsaFactura + + Public Sub SetSubProyecto() + If CveSubProyecto > 0 Then + SubProyecto = New Modelos.SubProyectoModel(GlobalDTSubProyectos(-1).FiltroPrimero($"CveSubProyecto = {CveSubProyecto}")) + End If + End Sub + Public Sub SetSubProyectoMatriz() + Dim Row As Data.DataRow = GlobalDTSubProyectos(-1, CveSubProyecto:=-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero("TipoSucursal=1") + If Not IsNothing(Row) Then + SubProyectoMatriz = New Modelos.SubProyectoModel(Row) + End If + End Sub + Public Sub SetCliente() + If CveCliente > 0 Then + Cliente = New Modelos.ClienteModel(CveCliente, CveEmpresa) + End If + End Sub + Public Sub SetMoneda() + If CveMoneda > 0 Then + Dim dr As DataRow = GlobalDTMonedas.FiltroPrimero(String.Format("CveMoneda ={0}", CveMoneda)) + If Not IsNothing(dr) Then + Moneda = dr("Moneda").ToString() + MonedaSAT = dr("AbreviaturaSAT").ToString() + MonedaAbreviatura = dr("Abreviatura").ToString() + End If + End If + End Sub + Public Sub SetMetodoPago() + If CveMetodoPago > 0 AndAlso Not IsNothing(GlobalDTMetodosPago.FiltroPrimero(String.Format(" CveMetodoPago ={0}", CveMetodoPago))) Then + MetodoPago = GlobalDTMetodosPago.FiltroPrimero(String.Format(" CveMetodoPago ={0}", CveMetodoPago))("MetodoPago").ToString() + ClaveMetodoPagoSAT = GlobalDTMetodosPago.FiltroPrimero(String.Format(" CveMetodoPago ={0}", CveMetodoPago))("ClaveSAT").ToString() + End If + End Sub + Public Sub SetMoneda(ObjClsPaginas As ClsPaginas) + If Not IsNothing(ObjClsPaginas) Then + Dim dr As DataRow = ObjClsPaginas.GlobalDTMonedas.FiltroPrimero(String.Format("CveMoneda ={0}", CveMoneda)) + If Not IsNothing(dr) Then + Moneda = dr("Moneda").ToString() + MonedaSAT = dr("AbreviaturaSAT").ToString() + MonedaAbreviatura = dr("Abreviatura").ToString() + End If + End If + End Sub + Public Sub SetMetodoPago(ObjClsPaginas As ClsPaginas) + If Not IsNothing(ObjClsPaginas) Then + If Not IsNothing(ObjClsPaginas.GlobalDTMetodosPago.FiltroPrimero(String.Format(" CveMetodoPago ={0}", CveMetodoPago))) Then + MetodoPago = ObjClsPaginas.GlobalDTMetodosPago.FiltroPrimero(String.Format(" CveMetodoPago ={0}", CveMetodoPago))("MetodoPago").ToString() + ClaveMetodoPagoSAT = ObjClsPaginas.GlobalDTMetodosPago.FiltroPrimero(String.Format(" CveMetodoPago ={0}", CveMetodoPago))("ClaveSAT").ToString() + End If + End If + End Sub + Public Sub SetSubProyecto(obj As ClsPaginas) + If CveSubProyecto > 0 AndAlso Not IsNothing(obj) Then + SubProyecto = New Modelos.SubProyectoModel(obj.GlobalDTSubProyectos(-1).FiltroPrimero($"CveSubProyecto = {CveSubProyecto}")) + End If + End Sub + Public Sub SetSubProyectoMatriz(obj As ClsPaginas) + If Not IsNothing(obj) Then + Dim Row As Data.DataRow = obj.GlobalDTSubProyectos(-1, CveSubProyecto:=-1, CveEmpresa:=obj.UsuarioActual.CveEmpresa).FiltroPrimero("TipoSucursal=1") + If Not IsNothing(Row) Then + SubProyectoMatriz = New Modelos.SubProyectoModel(Row) + End If + End If + End Sub + Public Property CveClienteSucursal As Integer + Public Property ClienteSucursal As Modelos.SucursalModel + Public Property EnviarA As Modelos.EnviarAModel + Public Property NumeroContrato As String + Public Property PedidoContrato As String + Public Property OrdenCompra As String = "-1" + Public Property CveMetodoPago As Integer + Public Property MetodoPago As String + Public Property ClaveMetodoPagoSAT As String + Public Property CveMetodoPago33 As Integer + Public Property MetodoPago33 As String + Public Property CveFormaPago33 As Integer + Public Property MetodoPagoSAT33 As String + Public Property FormaPago33 As String + Public Property FormaPagoSAT33 As String + Public Property UsoCFDI As String = "" + Public Property CveUsoCFDI As Integer + Public Property ClaveUsoCFDI As String = "" + Public Property CveTipoRelacion As Integer = -1 + Public Property CveEstatusFactura As Integer + Public Property CveVendedor As Integer + Public Property VendedorCodigo As String + Public Property CveSucursalEjecucion As Integer + Public Property FechaEjecucion As Date + Public Property CveSucursalCobranza As Integer + + Public Property CveSubProyectoCobranza As Integer + Public Property CveSubProyectoEjecucion As Integer + Public Property CveOS As Integer + Public Property CveContrato As Integer + Public Property CveVentaPadre As Integer + Public Property CvePrePoliza As Integer + Public Property Entrega As String + Public Property TiempoEntrega As String + Public Property Vigencia As Date + Public Property TipoEstatus As Integer + Public Property CveCondicionEntrega As Integer + Public Property CondicionEntrega As String + + Public Property TipoRelacion As String + Public Property UUIDRelacionados As List(Of String) + + + Public Property CveVentaRelacion As Integer = -1 + Public Property ImporteRelacion As Decimal + + +#End Region + + #Region "IDisposable Support" - 'Atributos de la clase + 'Atributos de la clase Private disposedValue As Boolean = False ' IDisposable @@ -4398,9 +5226,9 @@ Namespace Modelos ' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above. Dispose(True) GC.SuppressFinalize(Me) - End Sub + End Sub #End Region - + #Region "G L O B A L - D T" Public Property GlobalTipoCambio(Optional Fecha As Date = MinFecha) As Double Get @@ -4585,10 +5413,10 @@ Namespace Modelos Set(value As DataTable) HttpContext.Current.Application("GlobalDTPSATPS") = value End Set - End Property - + End Property + #Region "GLOBALES DE SAT COMERCIO EXTERIOR" - + Property GlobalDTClavePedimento() As DataTable Get GlobalDTClavePedimento = DirectCast(HttpContext.Current.Application("GlobalDTClavePedimento"), DataTable) @@ -4698,10 +5526,10 @@ Namespace Modelos Set(value As DataTable) HttpContext.Current.Application("GlobalDTColonia") = value End Set - End Property - + End Property + #End Region - + Property GlobalDTPSATUM() As DataTable Get GlobalDTPSATUM = DirectCast(HttpContext.Current.Application("GlobalDTPSATUM"), DataTable) @@ -5886,9 +6714,9 @@ Namespace Modelos Set(value As DataTable) HttpContext.Current.Application("GlobalDTVtaCobranzaEstatus") = value End Set - End Property - - + End Property + + #Region "***********************************************************************DT EVENTOS****************************************************************************************" Property GlobalDTTiposEventos() As DataTable Get @@ -5924,9 +6752,9 @@ Namespace Modelos Set(value As DataTable) HttpContext.Current.Application("GlobalDTOIEstatusEventos") = value End Set - End Property + End Property #End Region - + #Region " **********************************************************************DT PROSPECTOS*************************************************************************************" Property GlobalDTProspectosCaracteristicasClasificaciones() As DataTable Get @@ -5967,9 +6795,9 @@ Namespace Modelos Set(value As DataTable) HttpContext.Current.Application("GlobalDTProspectosCaracteristicasOpciones") = value End Set - End Property + End Property #End Region - + #Region "***********************************************************************DT ACTIVOS FIJOS**********************************************************************************" Property GlobalDTActivoFijos(CveEmpresa As Integer, Optional CveSubTipoActivoFijo As Integer = -1, Optional CveActivoFijo As Integer = -1) As DataTable Get @@ -6062,10 +6890,10 @@ Namespace Modelos Set(value As DataTable) HttpContext.Current.Application("GlobalDTTipoActivoFijo") = value End Set - End Property - + End Property + #End Region - + #Region "***********************************************************************DT GENERALES**************************************************************************************" Property GlobalDTGralPaises() As DataTable Get @@ -6153,10 +6981,10 @@ Namespace Modelos Set(value As DataTable) HttpContext.Current.Application("GlobalDTGralColectivas") = value End Set - End Property - + End Property + #End Region - + #Region "***********************************************************************DT PROSPECTOS*************************************************************************************" Property GlobalDTProspectosSupervisores(CveEmpresa As Integer) As DataTable Get @@ -6365,8 +7193,8 @@ Namespace Modelos Set(value As DataTable) HttpContext.Current.Application("GlobalDTProspectosTipos") = value End Set - End Property - + End Property + #Region " DT PROSPECTOS SOLICITUDES" Property GlobalDTProspectosSolicitudes(CveEmpresa As Integer) As DataTable Get @@ -6433,15 +7261,15 @@ Namespace Modelos Set(value As DataTable) HttpContext.Current.Application("GlobalDTProspectosSolicitudesApoyos") = value End Set - End Property - + End Property + #End Region #End Region - + #Region "**********************************************DT AMORTIZACIÓN CONTABLE PLAN DE DESARROLLO********************************************************************************" - + #Region "***********************************************************************DT AMORTIZACIÓN CONTABLE*********************************************************************************************" - + Property GlobalDTAC_RubrosIngreso() As DataTable Get GlobalDTAC_RubrosIngreso = DirectCast(HttpContext.Current.Application("GlobalDTAC_RubrosIngreso"), DataTable) @@ -6697,11 +7525,11 @@ Namespace Modelos Set(value As DataTable) HttpContext.Current.Application("GlobalDTAC_MatrizEgresos") = value End Set - End Property - - + End Property + + #End Region - + Property GlobalDTAC_PD_EjeRector(CveEmpresa As Integer) As DataTable Get If CveEmpresa <> -1 Then @@ -6780,9 +7608,9 @@ Namespace Modelos Set(value As DataTable) HttpContext.Current.Application("GlobalDTAC_PD_Metas") = value End Set - End Property + End Property #End Region - + #Region "***********************************************************************GLOBAL DT ORDENES DE COMPRA***********************************************************************" Property GlobalDTOCEstatus(CveEmpresa As Integer) As DataTable Get @@ -6819,11 +7647,11 @@ Namespace Modelos Set(value As DataTable) HttpContext.Current.Application("GlobalDTOCEstatusUsuarios") = value End Set - End Property - - + End Property + + #End Region - + #Region "F I N A N Z A S " Property GlobalDTFinan_RazonesFinancieras() As DataTable Get @@ -6832,10 +7660,10 @@ Namespace Modelos Set(value As DataTable) HttpContext.Current.Application("GlobalDTFinan_RazonesFinancieras") = value End Set - End Property + End Property #End Region - - + + #Region "***********************************************************************GLOBAL DT CONTABILIDAD****************************************************************************" Property GlobalDTContaPlantillasPolizas(CveEmpresa As Integer, Optional TipoPlantilla As Integer = -1) As DataTable Get @@ -6889,9 +7717,9 @@ Namespace Modelos Set(value As DataTable) HttpContext.Current.Application("GlobalDTContaConceptosContables") = value End Set - End Property + End Property #End Region - + #Region "**********************************************************************GLOBAL DT RH (RECURSOS HUMANOS)********************************************************************" Property GlobalDTAsistenciaDetalle() As DataTable Get @@ -7043,13 +7871,13 @@ Namespace Modelos Set(value As DataTable) HttpContext.Current.Application("GlobalDTTipoBuzon") = value End Set - End Property + End Property #End Region - + #Region "*********** D T - C O M B U S T I B L E S ***********" - - - + + + Property GlobalDTCombustibles(CveEmpresa As Integer) As DataTable Get If CveEmpresa <> -1 Then @@ -7088,11 +7916,11 @@ Namespace Modelos Set(ByVal value As DataTable) HttpContext.Current.Application("GlobalDTCombustiblesTipos") = value End Set - End Property + End Property #End Region - + #Region "*********** D T - M A N T E N I M I E N T O S ***********" - + Property GlobalDTMantenimientosTipos() As DataTable Get GlobalDTMantenimientosTipos = DirectCast(HttpContext.Current.Application("GlobalDTMantenimientosTipos"), DataTable) @@ -7131,13 +7959,13 @@ Namespace Modelos HttpContext.Current.Application("GlobalDTMantenimientosTipos") = value End Set - End Property - + End Property + #End Region - - + + #Region "*********** D T - T A L L E R E S ***********" - + Property GlobalDTTalleresTipos() As DataTable Get GlobalDTTalleresTipos = DirectCast(HttpContext.Current.Application("GlobalDTTalleresTipos"), DataTable) @@ -7154,12 +7982,12 @@ Namespace Modelos Set(value As DataTable) HttpContext.Current.Application("GlobalDTTalleres") = value End Set - End Property - + End Property + #End Region - + #Region "*********** D T - D I S T R I B U I D O R E S ***********" - + Property GlobalDTDistribuidoresTipos() As DataTable Get GlobalDTDistribuidoresTipos = DirectCast(HttpContext.Current.Application("GlobalDTDistribuidoresTipos"), DataTable) @@ -7176,11 +8004,11 @@ Namespace Modelos Set(value As DataTable) HttpContext.Current.Application("GlobalDTDistribuidores") = value End Set - End Property - + End Property + #End Region - - + + Property GlobalDTOIRevision(CveEmpresa As Integer) As DataTable Get If CveEmpresa <> -1 Then @@ -7242,27 +8070,27 @@ Namespace Modelos Set(value As DataTable) HttpContext.Current.Application("GlobalDTPaqueteriaGuiaTipos") = value End Set - End Property + End Property Property GlobalDTClasificacionPorcentaje(CveEmpresa As Integer, Optional CveClasicacionPorcentaje As Integer = -1, Optional CveClasicacion As Integer = -1, - Optional PorcentajeIVA As Double = -1) As DataTable - - Get - Dim Str As StringBuilder = New StringBuilder() - If CveEmpresa <> -1 Or CveClasicacionPorcentaje <> -1 Or CveClasicacion <> -1 Or PorcentajeIVA <> -1 Then - If CveEmpresa <> -1 Then Str.AppendFormat("CveEmpresa = {0}", CveEmpresa) - If CveClasicacionPorcentaje <> -1 Then Str.AppendFormat(" {0} CveClasicacionPorcentaje = {1}", If(Str.Length > 0, "AND", ""), CveClasicacionPorcentaje) - If CveClasicacion <> -1 Then Str.AppendFormat(" {0} CveClasicacion = {1}", If(Str.Length > 0, "AND", ""), CveClasicacion) - If PorcentajeIVA <> -1 Then Str.AppendFormat(" {0} PorcentajeIVA = {1}", If(Str.Length > 0, "AND", ""), PorcentajeIVA) - Dim Dv As New DataView(DirectCast(HttpContext.Current.Application("GlobalDTClasificacionPorcentaje"), DataTable), Str.ToString, "", DataViewRowState.CurrentRows) - GlobalDTClasificacionPorcentaje = Dv.ToTable - Dv.Dispose() - Else - GlobalDTClasificacionPorcentaje = DirectCast(HttpContext.Current.Application("GlobalDTClasificacionPorcentaje"), DataTable) - End If - End Get - Set(value As DataTable) - HttpContext.Current.Application("GlobalDTClasificacionPorcentaje") = value - End Set + Optional PorcentajeIVA As Double = -1) As DataTable + + Get + Dim Str As StringBuilder = New StringBuilder() + If CveEmpresa <> -1 Or CveClasicacionPorcentaje <> -1 Or CveClasicacion <> -1 Or PorcentajeIVA <> -1 Then + If CveEmpresa <> -1 Then Str.AppendFormat("CveEmpresa = {0}", CveEmpresa) + If CveClasicacionPorcentaje <> -1 Then Str.AppendFormat(" {0} CveClasicacionPorcentaje = {1}", If(Str.Length > 0, "AND", ""), CveClasicacionPorcentaje) + If CveClasicacion <> -1 Then Str.AppendFormat(" {0} CveClasicacion = {1}", If(Str.Length > 0, "AND", ""), CveClasicacion) + If PorcentajeIVA <> -1 Then Str.AppendFormat(" {0} PorcentajeIVA = {1}", If(Str.Length > 0, "AND", ""), PorcentajeIVA) + Dim Dv As New DataView(DirectCast(HttpContext.Current.Application("GlobalDTClasificacionPorcentaje"), DataTable), Str.ToString, "", DataViewRowState.CurrentRows) + GlobalDTClasificacionPorcentaje = Dv.ToTable + Dv.Dispose() + Else + GlobalDTClasificacionPorcentaje = DirectCast(HttpContext.Current.Application("GlobalDTClasificacionPorcentaje"), DataTable) + End If + End Get + Set(value As DataTable) + HttpContext.Current.Application("GlobalDTClasificacionPorcentaje") = value + End Set End Property Property GlobalDTPaqueterias() As DataTable Get @@ -7274,9 +8102,9 @@ Namespace Modelos End Property Public Property CveContratoSecciones As String - Public Property CveEstatus As Integer + Public Property CveEstatus As Integer #End Region - + End Class @@ -7294,7 +8122,7 @@ Namespace Modelos MyBase.New() End Sub Public Sub New(Row As System.Data.DataRow) - SetValues(Row) + setValues(Row) End Sub Public Property AplicaFEMSA As Boolean = False 'AplicaFEMSA @@ -7341,7 +8169,7 @@ Namespace Modelos End Sub Public Sub New(Row As System.Data.DataRow) SetDefaultValues() - SetValues(Row) + setValues(Row) End Sub Public ReadOnly Property LugarExp As String @@ -7468,13 +8296,13 @@ Namespace Modelos End Sub Public Sub New(Row As Data.DataRow) SetDefaultValues() - SetValues(Row) + setValues(Row) End Sub Public Sub New(CveCliente As Integer, CveEmpresa As Integer) SetDefaultValues() Dim ObjCliente As New ClsClientes() If ObjCliente.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, CveEmpresa, -1, TipoCliente:=-1) AndAlso ObjCliente.DtResultados.Rows.Count > 0 Then - SetValues(ObjCliente.DtResultados.Rows(0)) + setValues(ObjCliente.DtResultados.Rows(0)) End If ObjCliente.Dispose() End Sub @@ -7581,7 +8409,7 @@ Namespace Modelos End Sub Public Sub New(Row As System.Data.DataRow) SetDefaultValues() - SetValues(Row) + setValues(Row) End Sub Public ReadOnly Property LugarExp As String @@ -7602,12 +8430,12 @@ Namespace Modelos Public Property EnvioPedidoContrato As String Public Property EnvioCP As String Public Property EnvioTel As String - End Class - + End Class + #End Region - + #Region "Personal" - + Public Class RH_PersonalRequerido Public Sub New() CveRequerimiento = -1 @@ -7631,11 +8459,11 @@ Namespace Modelos Public Property Usuario As String Public Property CveEmpresa As Integer - End Class + End Class #End Region - + #Region "E FACTURAS" - Public Class eFactura + Public Class eFactura #Region "Propiedades" Public Property CveEmpresa() As Integer Get @@ -7911,326 +8739,326 @@ Namespace Modelos m_DirectorioTemporal = Value End Set End Property - Private m_DirectorioTemporal As String + Private m_DirectorioTemporal As String #End Region - End Class - - - ' Public Class ClsValidaCFDi - ' Implements IDisposable - - '#Region "Campos" - ' 'Campos - ' Private LFolioFiscal As String - ' Private LRFCEmisor As String - ' Private LRFCReceptor As String - ' ' Para detectar llamadas redundantes - ' Private disposedValue As Boolean = False - '#End Region - - '#Region "Propiedades" - ' 'Propiedades - ' Public Property EsValida() As Integer - ' Get - ' Return m_EsValida - ' End Get - ' Set - ' m_EsValida = Value - ' End Set - ' End Property - ' Private m_EsValida As Integer - ' Public Property Efecto() As String - ' Get - ' Return m_Efecto - ' End Get - ' Set - ' m_Efecto = Value - ' End Set - ' End Property - ' Private m_Efecto As String - ' Public Property FechaEmision() As String - ' Get - ' Return m_FechaEmision - ' End Get - ' Set - ' m_FechaEmision = Value - ' End Set - ' End Property - ' Private m_FechaEmision As String - ' Public Property FolioFiscal() As String - ' Get - ' Return m_FolioFiscal - ' End Get - ' Set - ' m_FolioFiscal = Value - ' End Set - ' End Property - ' Private m_FolioFiscal As String - ' Public Property Estado() As String - ' Get - ' Return m_Estado - ' End Get - ' Set - ' m_Estado = Value - ' End Set - ' End Property - ' Private m_Estado As String - ' Public Property RFCEmisor() As String - ' Get - ' Return m_RFCEmisor - ' End Get - ' Set - ' m_RFCEmisor = Value - ' End Set - ' End Property - ' Private m_RFCEmisor As String - ' Public Property Emisor() As String - ' Get - ' Return m_Emisor - ' End Get - ' Set - ' m_Emisor = Value - ' End Set - ' End Property - ' Private m_Emisor As String - ' Public Property RFCReceptor() As String - ' Get - ' Return m_RFCReceptor - ' End Get - ' Set - ' m_RFCReceptor = Value - ' End Set - ' End Property - ' Private m_RFCReceptor As String - ' Public Property Receptor() As String - ' Get - ' Return m_Receptor - ' End Get - ' Set - ' m_Receptor = Value - ' End Set - ' End Property - ' Private m_Receptor As String - ' Public Property RFCPAC() As String - ' Get - ' Return m_RFCPAC - ' End Get - ' Set - ' m_RFCPAC = Value - ' End Set - ' End Property - ' Private m_RFCPAC As String - ' Public Property FechaCertificacion() As String - ' Get - ' Return m_FechaCertificacion - ' End Get - ' Set - ' m_FechaCertificacion = Value - ' End Set - ' End Property - ' Private m_FechaCertificacion As String - ' Public Property Monto() As Double - ' Get - ' Return m_Monto - ' End Get - ' Set - ' m_Monto = Value - ' End Set - ' End Property - ' Private m_Monto As Double - ' Public Property FechaCancelacion() As String - ' Get - ' Return m_FechaCancelacion - ' End Get - ' Set - ' m_FechaCancelacion = Value - ' End Set - ' End Property - ' Private m_FechaCancelacion As String - ' Public Property ResponseHTML() As String - ' Get - ' Return m_ResponseHTML - ' End Get - ' Set - ' m_ResponseHTML = Value - ' End Set - ' End Property - ' Private m_ResponseHTML As String - '#End Region - - - ' 'Public Sub New() - ' 'End Sub - - ' 'Public Sub New(FolioFiscal As String, RFCEmisor As String, RFCReceptor As String, MontoTotal As Double, Fecha As String) - ' ' Me.LFolioFiscal = FolioFiscal - ' ' Me.LRFCEmisor = RFCEmisor - ' ' Me.LRFCReceptor = RFCReceptor - ' ' Verificar() - ' ' ' valida que este vigente y que el total coincida entre el xml y la pagina - ' ' If EsValida = 1 AndAlso Math.Abs(Me.Monto - MontoTotal) <0.01 AndAlso Me.FechaEmision= Fecha Then - ' ' EsValida = 1 - ' ' End If - ' 'End Sub - - ' 'Public Function Verificar(FolioFiscal As String, RFCEmisor As String, RFCReceptor As String, MontoTotal As Double, Fecha As System.DateTime) As Integer - ' ' Me.LFolioFiscal = FolioFiscal - ' ' Me.LRFCEmisor = RFCEmisor - ' ' Me.LRFCReceptor = RFCReceptor - ' ' Verificar() - ' ' ' valida que este vigente y que el total coincida entre el xml y la pagina - ' ' If EsValida = 1 AndAlso Math.Abs(Me.Monto - MontoTotal) < 0.01 AndAlso Me.FechaEmision.ToDate() = Fecha Then - ' ' EsValida = 1 - ' ' End If - ' ' Return Me.EsValida - ' 'End Function - - ' 'Private Sub Verificar() - - ' ' Try - ' ' Dim URL As String = "https://verificacfdi.facturaelectronica.sat.gob.mx/" - ' ' Dim Captcha As String = "86347" - ' ' Dim PostData As String = String.Format("ctl00%24ScriptManager1=ctl00%24MainContent%24UpnlBusqueda%7Cctl00%24MainContent%24BtnBusqueda&__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=4XIkDFIZJUcFomimZq9eTLrdtnhIAGlsq6y0rtQuJT37JwifEc%2FW5maVQfV4be%2B4NQhS%2F%2FyWBSZzL5CyT1G1n7QcKgYNWEBpVwB63yZO4GEPtkhlMnxHIX%2BVxggo%2Fer8r5tKDnW%2FvXWy0%2BZTkT0xTcXs7bDk%2F9J3p8kUPusbOcuaNmov7RxCXqW5%2F2DKoYrkc0Jn4A6N0ndsdtjVuD3fH8wGQ5kaKpMxmr6Nyr4mO98kc%2Bbd8AkKR458juZEzpgmmifqg61Ho7LLzuq02TCN3jDbPH4MQ79m8mh%2BYDxeZi%2BVG%2FbOjGECspr6aKxLT0zuzlQX5ZWVKenYv1Ei0YQkfhrmsNWqUwBWUAFeZwziDX2d0HNp&__VIEWSTATEGENERATOR=CA0B0334&__VIEWSTATEENCRYPTED=&ctl00%24MainContent%24TxtUUID={0}&ctl00%24MainContent%24TxtRfcEmisor={1}&ctl00%24MainContent%24TxtRfcReceptor={2}&ctl00%24MainContent%24TxTCaptchaNumbers={3}&__ASYNCPOST=true&ctl00%24MainContent%24BtnBusqueda=Verificar%20CFDI", LFolioFiscal, LRFCEmisor, LRFCReceptor, Captcha) - ' ' Dim Encoding As Encoding = Encoding.UTF8 - ' ' Dim Data As Byte() = Encoding.GetBytes(PostData) - ' ' Dim Request As HttpWebRequest = Nothing - - ' ' Request = DirectCast(WebRequest.Create(URL), HttpWebRequest) - ' ' Request.Method = "POST" - ' ' Request.Accept = "*/*" - ' ' Request.Headers.Add("X-Requested-With", "XMLHttpRequest") - ' ' Request.Headers.Add("X-MicrosoftAjax", "Delta=true") - ' ' Request.ContentType = "application/x-www-form-urlencoded; charset=utf-8" - ' ' Request.Referer = "https://verificacfdi.facturaelectronica.sat.gob.mx/" - ' ' Request.Headers.Add("Accept-Language", "es-mx") - ' ' Request.Headers.Add("Accept-Encoding", "gzip, deflate") - ' ' Request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; WOW64; Trident/5.0)" - ' ' Request.Host = "verificacfdi.facturaelectronica.sat.gob.mx" - ' ' Request.Headers.Add("Pragma", "no-cache") - ' ' Request.ServicePoint.Expect100Continue = False - ' ' Request.KeepAlive = True - ' ' Request.ContentLength = Data.Length - - ' ' Dim OutStream As Stream = Request.GetRequestStream() - ' ' OutStream.Write(Data, 0, Data.Length) - ' ' OutStream.Close() - ' ' Dim Response = DirectCast(Request.GetResponse(), HttpWebResponse) - - ' ' Dim InStream As Stream = Nothing - ' ' Select Case Response.ContentEncoding.ToUpperInvariant() - ' ' Case "GZIP" - ' ' InStream = New GZipStream(Response.GetResponseStream(), CompressionMode.Decompress) - ' ' Exit Select - ' ' Case "DEFLATE" - ' ' InStream = New DeflateStream(Response.GetResponseStream(), CompressionMode.Decompress) - ' ' Exit Select - ' ' Case Else - ' ' InStream = Response.GetResponseStream() - ' ' Exit Select - ' ' End Select - - ' ' Dim SR As New StreamReader(InStream, Encoding) - ' ' Dim DataBack As String = SR.ReadToEnd() - - ' ' ProcesarDatos(DataBack) - ' ' Catch ex As Exception - ' ' ModExtensiones.GuardaLog("'ERROR : No se pudo Validar la factura:" + ex.Message) - ' ' End Try - ' 'End Sub - - ' 'Private Sub ProcesarDatos(HTML As String) - ' ' Dim tValida As Integer = -1 - ' ' EsValida = 0 - ' ' ' No tiene Error - ' ' If (HTML.Contains("El Comprobante NO se encuentra registrado")) Then - ' ' HTML = "No se encontró el CFDi" - ' ' 'Se validó - ' ' tValida = 0 - ' ' Else - ' ' Dim i As Integer = HTML.IndexOf("
") - - ' ' If i >= 0 Then - ' ' HTML = HTML.Substring(i) - ' ' HTML = HTML.Substring(0, HTML.IndexOf("
")) - ' ' HTML = HTML.Replace(" ", " ") - ' ' tValida = 1 - ' ' Me.ResponseHTML = HTML - - ' ' End If - ' ' End If - - ' ' 'Cargo estructura de la clase - ' ' If tValida = 1 Then - ' ' Me.Efecto = ExtraeDatos(HTML, "ctl00_MainContent_LblEfectoComprobante"">", 10) - ' ' Me.FechaEmision = ExtraeDatos(HTML, "ctl00_MainContent_LblFechaEmision"">", 19) - ' ' Me.FolioFiscal = ExtraeDatos(HTML, "ctl00_MainContent_LblUuid"">", 40) - ' ' Me.Estado = ExtraeDatos(HTML, "ctl00_MainContent_LblEstado"">", 15) - ' ' Me.RFCEmisor = ExtraeDatos(HTML, "ctl00_MainContent_LblRfcEmisor"">", 13) - ' ' Me.Emisor = ExtraeDatos(HTML, "ctl00_MainContent_LblNombreEmisor"">", 200) - ' ' Me.RFCReceptor = ExtraeDatos(HTML, "ctl00_MainContent_LblRfcReceptor"">", 13) - ' ' Me.Receptor = ExtraeDatos(HTML, "ctl00_MainContent_LblNombreReceptor"">", 200) - ' ' Me.RFCPAC = ExtraeDatos(HTML, "ctl00_MainContent_LblRfcPac"">", 13) - ' ' Me.FechaCertificacion = ExtraeDatos(HTML, "ctl00_MainContent_LblFechaCertificacion"">", 19) - ' ' Me.Monto = ExtraeDatos(HTML, "ctl00_MainContent_LblMonto"">", 15).ToDouble() - ' ' Me.FechaCancelacion = ExtraeDatos(HTML, "ctl00_MainContent_LblFechaCancelacion"">", 19) - ' ' If Estado.ToLower() = "vigente" Then - ' ' EsValida = 1 - ' ' End If - - ' ' If Estado.ToLower() = "cancelado" Then - ' ' EsValida = 2 - ' ' End If - ' ' End If - ' 'End Sub - - ' 'Private Function ExtraeDatos(HTML As String, Container As String, MaxLength As Integer) As String - ' ' Dim DataBack As String = String.Empty - ' ' 'Código HTML: $ = '$', : = ':' - ' ' For i As Integer = 0 To HTML.IndexOf(Container) + MaxLength - ' ' If HTML.Substring(HTML.IndexOf(Container) + Container.Length - 1, i).Trim().EndsWith("") Then - ' ' DataBack = HTML.Substring(HTML.IndexOf(Container) + Container.Length, i - 1).Replace("", "").Trim().Replace("$", "").Replace(":", ":").Replace("/", "/") - ' ' ' TODO: might not be correct. Was : Exit For - ' ' Exit For - ' ' Else - ' ' i = i + 1 - ' ' End If - ' ' Next - - ' ' Return DataBack.Trim() - ' 'End Function - - '#Region " IDisposable Support " - ' ' IDisposable - ' Protected Overridable Sub Dispose(disposing As Boolean) - ' If Not disposedValue Then - ' ' TODO: Liberar otro estado (objetos administrados). - ' If disposing Then - - ' ' TODO: Liberar su propio estado (objetos no administrados). - ' ' TODO: Establecer campos grandes como Null. - ' End If - ' End If - ' disposedValue = True - ' End Sub - - ' ' Visual Basic agregó este código para implementar correctamente el modelo descartable. - ' Public Sub Dispose() - ' ' No cambie este código. Coloque el código de limpieza en Dispose (ByVal que se dispone como Boolean). - ' Dispose(True) - ' GC.SuppressFinalize(Me) - ' End Sub - - ' Private Sub IDisposable_Dispose() Implements IDisposable.Dispose - ' Throw New NotImplementedException() - ' End Sub - '#End Region - - ' End Class - + End Class + + + ' Public Class ClsValidaCFDi + ' Implements IDisposable + + '#Region "Campos" + ' 'Campos + ' Private LFolioFiscal As String + ' Private LRFCEmisor As String + ' Private LRFCReceptor As String + ' ' Para detectar llamadas redundantes + ' Private disposedValue As Boolean = False + '#End Region + + '#Region "Propiedades" + ' 'Propiedades + ' Public Property EsValida() As Integer + ' Get + ' Return m_EsValida + ' End Get + ' Set + ' m_EsValida = Value + ' End Set + ' End Property + ' Private m_EsValida As Integer + ' Public Property Efecto() As String + ' Get + ' Return m_Efecto + ' End Get + ' Set + ' m_Efecto = Value + ' End Set + ' End Property + ' Private m_Efecto As String + ' Public Property FechaEmision() As String + ' Get + ' Return m_FechaEmision + ' End Get + ' Set + ' m_FechaEmision = Value + ' End Set + ' End Property + ' Private m_FechaEmision As String + ' Public Property FolioFiscal() As String + ' Get + ' Return m_FolioFiscal + ' End Get + ' Set + ' m_FolioFiscal = Value + ' End Set + ' End Property + ' Private m_FolioFiscal As String + ' Public Property Estado() As String + ' Get + ' Return m_Estado + ' End Get + ' Set + ' m_Estado = Value + ' End Set + ' End Property + ' Private m_Estado As String + ' Public Property RFCEmisor() As String + ' Get + ' Return m_RFCEmisor + ' End Get + ' Set + ' m_RFCEmisor = Value + ' End Set + ' End Property + ' Private m_RFCEmisor As String + ' Public Property Emisor() As String + ' Get + ' Return m_Emisor + ' End Get + ' Set + ' m_Emisor = Value + ' End Set + ' End Property + ' Private m_Emisor As String + ' Public Property RFCReceptor() As String + ' Get + ' Return m_RFCReceptor + ' End Get + ' Set + ' m_RFCReceptor = Value + ' End Set + ' End Property + ' Private m_RFCReceptor As String + ' Public Property Receptor() As String + ' Get + ' Return m_Receptor + ' End Get + ' Set + ' m_Receptor = Value + ' End Set + ' End Property + ' Private m_Receptor As String + ' Public Property RFCPAC() As String + ' Get + ' Return m_RFCPAC + ' End Get + ' Set + ' m_RFCPAC = Value + ' End Set + ' End Property + ' Private m_RFCPAC As String + ' Public Property FechaCertificacion() As String + ' Get + ' Return m_FechaCertificacion + ' End Get + ' Set + ' m_FechaCertificacion = Value + ' End Set + ' End Property + ' Private m_FechaCertificacion As String + ' Public Property Monto() As Double + ' Get + ' Return m_Monto + ' End Get + ' Set + ' m_Monto = Value + ' End Set + ' End Property + ' Private m_Monto As Double + ' Public Property FechaCancelacion() As String + ' Get + ' Return m_FechaCancelacion + ' End Get + ' Set + ' m_FechaCancelacion = Value + ' End Set + ' End Property + ' Private m_FechaCancelacion As String + ' Public Property ResponseHTML() As String + ' Get + ' Return m_ResponseHTML + ' End Get + ' Set + ' m_ResponseHTML = Value + ' End Set + ' End Property + ' Private m_ResponseHTML As String + '#End Region + + + ' 'Public Sub New() + ' 'End Sub + + ' 'Public Sub New(FolioFiscal As String, RFCEmisor As String, RFCReceptor As String, MontoTotal As Double, Fecha As String) + ' ' Me.LFolioFiscal = FolioFiscal + ' ' Me.LRFCEmisor = RFCEmisor + ' ' Me.LRFCReceptor = RFCReceptor + ' ' Verificar() + ' ' ' valida que este vigente y que el total coincida entre el xml y la pagina + ' ' If EsValida = 1 AndAlso Math.Abs(Me.Monto - MontoTotal) <0.01 AndAlso Me.FechaEmision= Fecha Then + ' ' EsValida = 1 + ' ' End If + ' 'End Sub + + ' 'Public Function Verificar(FolioFiscal As String, RFCEmisor As String, RFCReceptor As String, MontoTotal As Double, Fecha As System.DateTime) As Integer + ' ' Me.LFolioFiscal = FolioFiscal + ' ' Me.LRFCEmisor = RFCEmisor + ' ' Me.LRFCReceptor = RFCReceptor + ' ' Verificar() + ' ' ' valida que este vigente y que el total coincida entre el xml y la pagina + ' ' If EsValida = 1 AndAlso Math.Abs(Me.Monto - MontoTotal) < 0.01 AndAlso Me.FechaEmision.ToDate() = Fecha Then + ' ' EsValida = 1 + ' ' End If + ' ' Return Me.EsValida + ' 'End Function + + ' 'Private Sub Verificar() + + ' ' Try + ' ' Dim URL As String = "https://verificacfdi.facturaelectronica.sat.gob.mx/" + ' ' Dim Captcha As String = "86347" + ' ' Dim PostData As String = String.Format("ctl00%24ScriptManager1=ctl00%24MainContent%24UpnlBusqueda%7Cctl00%24MainContent%24BtnBusqueda&__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=4XIkDFIZJUcFomimZq9eTLrdtnhIAGlsq6y0rtQuJT37JwifEc%2FW5maVQfV4be%2B4NQhS%2F%2FyWBSZzL5CyT1G1n7QcKgYNWEBpVwB63yZO4GEPtkhlMnxHIX%2BVxggo%2Fer8r5tKDnW%2FvXWy0%2BZTkT0xTcXs7bDk%2F9J3p8kUPusbOcuaNmov7RxCXqW5%2F2DKoYrkc0Jn4A6N0ndsdtjVuD3fH8wGQ5kaKpMxmr6Nyr4mO98kc%2Bbd8AkKR458juZEzpgmmifqg61Ho7LLzuq02TCN3jDbPH4MQ79m8mh%2BYDxeZi%2BVG%2FbOjGECspr6aKxLT0zuzlQX5ZWVKenYv1Ei0YQkfhrmsNWqUwBWUAFeZwziDX2d0HNp&__VIEWSTATEGENERATOR=CA0B0334&__VIEWSTATEENCRYPTED=&ctl00%24MainContent%24TxtUUID={0}&ctl00%24MainContent%24TxtRfcEmisor={1}&ctl00%24MainContent%24TxtRfcReceptor={2}&ctl00%24MainContent%24TxTCaptchaNumbers={3}&__ASYNCPOST=true&ctl00%24MainContent%24BtnBusqueda=Verificar%20CFDI", LFolioFiscal, LRFCEmisor, LRFCReceptor, Captcha) + ' ' Dim Encoding As Encoding = Encoding.UTF8 + ' ' Dim Data As Byte() = Encoding.GetBytes(PostData) + ' ' Dim Request As HttpWebRequest = Nothing + + ' ' Request = DirectCast(WebRequest.Create(URL), HttpWebRequest) + ' ' Request.Method = "POST" + ' ' Request.Accept = "*/*" + ' ' Request.Headers.Add("X-Requested-With", "XMLHttpRequest") + ' ' Request.Headers.Add("X-MicrosoftAjax", "Delta=true") + ' ' Request.ContentType = "application/x-www-form-urlencoded; charset=utf-8" + ' ' Request.Referer = "https://verificacfdi.facturaelectronica.sat.gob.mx/" + ' ' Request.Headers.Add("Accept-Language", "es-mx") + ' ' Request.Headers.Add("Accept-Encoding", "gzip, deflate") + ' ' Request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; WOW64; Trident/5.0)" + ' ' Request.Host = "verificacfdi.facturaelectronica.sat.gob.mx" + ' ' Request.Headers.Add("Pragma", "no-cache") + ' ' Request.ServicePoint.Expect100Continue = False + ' ' Request.KeepAlive = True + ' ' Request.ContentLength = Data.Length + + ' ' Dim OutStream As Stream = Request.GetRequestStream() + ' ' OutStream.Write(Data, 0, Data.Length) + ' ' OutStream.Close() + ' ' Dim Response = DirectCast(Request.GetResponse(), HttpWebResponse) + + ' ' Dim InStream As Stream = Nothing + ' ' Select Case Response.ContentEncoding.ToUpperInvariant() + ' ' Case "GZIP" + ' ' InStream = New GZipStream(Response.GetResponseStream(), CompressionMode.Decompress) + ' ' Exit Select + ' ' Case "DEFLATE" + ' ' InStream = New DeflateStream(Response.GetResponseStream(), CompressionMode.Decompress) + ' ' Exit Select + ' ' Case Else + ' ' InStream = Response.GetResponseStream() + ' ' Exit Select + ' ' End Select + + ' ' Dim SR As New StreamReader(InStream, Encoding) + ' ' Dim DataBack As String = SR.ReadToEnd() + + ' ' ProcesarDatos(DataBack) + ' ' Catch ex As Exception + ' ' ModExtensiones.GuardaLog("'ERROR : No se pudo Validar la factura:" + ex.Message) + ' ' End Try + ' 'End Sub + + ' 'Private Sub ProcesarDatos(HTML As String) + ' ' Dim tValida As Integer = -1 + ' ' EsValida = 0 + ' ' ' No tiene Error + ' ' If (HTML.Contains("El Comprobante NO se encuentra registrado")) Then + ' ' HTML = "No se encontró el CFDi" + ' ' 'Se validó + ' ' tValida = 0 + ' ' Else + ' ' Dim i As Integer = HTML.IndexOf("
") + + ' ' If i >= 0 Then + ' ' HTML = HTML.Substring(i) + ' ' HTML = HTML.Substring(0, HTML.IndexOf("
")) + ' ' HTML = HTML.Replace(" ", " ") + ' ' tValida = 1 + ' ' Me.ResponseHTML = HTML + + ' ' End If + ' ' End If + + ' ' 'Cargo estructura de la clase + ' ' If tValida = 1 Then + ' ' Me.Efecto = ExtraeDatos(HTML, "ctl00_MainContent_LblEfectoComprobante"">", 10) + ' ' Me.FechaEmision = ExtraeDatos(HTML, "ctl00_MainContent_LblFechaEmision"">", 19) + ' ' Me.FolioFiscal = ExtraeDatos(HTML, "ctl00_MainContent_LblUuid"">", 40) + ' ' Me.Estado = ExtraeDatos(HTML, "ctl00_MainContent_LblEstado"">", 15) + ' ' Me.RFCEmisor = ExtraeDatos(HTML, "ctl00_MainContent_LblRfcEmisor"">", 13) + ' ' Me.Emisor = ExtraeDatos(HTML, "ctl00_MainContent_LblNombreEmisor"">", 200) + ' ' Me.RFCReceptor = ExtraeDatos(HTML, "ctl00_MainContent_LblRfcReceptor"">", 13) + ' ' Me.Receptor = ExtraeDatos(HTML, "ctl00_MainContent_LblNombreReceptor"">", 200) + ' ' Me.RFCPAC = ExtraeDatos(HTML, "ctl00_MainContent_LblRfcPac"">", 13) + ' ' Me.FechaCertificacion = ExtraeDatos(HTML, "ctl00_MainContent_LblFechaCertificacion"">", 19) + ' ' Me.Monto = ExtraeDatos(HTML, "ctl00_MainContent_LblMonto"">", 15).ToDouble() + ' ' Me.FechaCancelacion = ExtraeDatos(HTML, "ctl00_MainContent_LblFechaCancelacion"">", 19) + ' ' If Estado.ToLower() = "vigente" Then + ' ' EsValida = 1 + ' ' End If + + ' ' If Estado.ToLower() = "cancelado" Then + ' ' EsValida = 2 + ' ' End If + ' ' End If + ' 'End Sub + + ' 'Private Function ExtraeDatos(HTML As String, Container As String, MaxLength As Integer) As String + ' ' Dim DataBack As String = String.Empty + ' ' 'Código HTML: $ = '$', : = ':' + ' ' For i As Integer = 0 To HTML.IndexOf(Container) + MaxLength + ' ' If HTML.Substring(HTML.IndexOf(Container) + Container.Length - 1, i).Trim().EndsWith("") Then + ' ' DataBack = HTML.Substring(HTML.IndexOf(Container) + Container.Length, i - 1).Replace("", "").Trim().Replace("$", "").Replace(":", ":").Replace("/", "/") + ' ' ' TODO: might not be correct. Was : Exit For + ' ' Exit For + ' ' Else + ' ' i = i + 1 + ' ' End If + ' ' Next + + ' ' Return DataBack.Trim() + ' 'End Function + + '#Region " IDisposable Support " + ' ' IDisposable + ' Protected Overridable Sub Dispose(disposing As Boolean) + ' If Not disposedValue Then + ' ' TODO: Liberar otro estado (objetos administrados). + ' If disposing Then + + ' ' TODO: Liberar su propio estado (objetos no administrados). + ' ' TODO: Establecer campos grandes como Null. + ' End If + ' End If + ' disposedValue = True + ' End Sub + + ' ' Visual Basic agregó este código para implementar correctamente el modelo descartable. + ' Public Sub Dispose() + ' ' No cambie este código. Coloque el código de limpieza en Dispose (ByVal que se dispone como Boolean). + ' Dispose(True) + ' GC.SuppressFinalize(Me) + ' End Sub + + ' Private Sub IDisposable_Dispose() Implements IDisposable.Dispose + ' Throw New NotImplementedException() + ' End Sub + '#End Region + + ' End Class + #End Region - + #Region "A P L I C A C I O N E S" - + Public Class MCliente Public Property CveCliente As Integer Public Property Nombre As String @@ -8534,7 +9362,7 @@ Namespace Modelos Public Property RequiereAFInsumo As Boolean Public Property RequierePersonal As Boolean Public Property EsAcumulador As Boolean - End Class - + End Class + #End Region End Namespace \ No newline at end of file diff --git a/Ventas/RepCancelacionesPorRespuesta.aspx.cs b/Ventas/RepCancelacionesPorRespuesta.aspx.cs index cd394656f..f67b8188a 100644 --- a/Ventas/RepCancelacionesPorRespuesta.aspx.cs +++ b/Ventas/RepCancelacionesPorRespuesta.aspx.cs @@ -89,7 +89,8 @@ public partial class Ventas_RepCancelacionesPorRespuesta : ClsPaginas { var resp = Timbrado.VerificarVigenciaSAT(uuid, UsuarioActual.Empresa.RFC, receptor, total, UsuarioActual.Empresa.FacturaProduccion); if (resp != null) - { + { + if (resp.Estado == null) { sb.Append("No se pudo comprobar el estado de la factura. El servicio del sat no esta disponible"); @@ -100,51 +101,60 @@ public partial class Ventas_RepCancelacionesPorRespuesta : ClsPaginas sb.AppendFormat("Codigo Estado: {0}
", resp.CodigoEstatus); sb.AppendFormat("Estado: {0}
", resp.Estado); sb.AppendFormat("Es Cancelable: {0}
", string.IsNullOrEmpty(resp.EsCancelable) ? "Desconocido" : resp.EsCancelable); - sb.AppendFormat("Estatus de Cancelación: {0}

", string.IsNullOrEmpty(resp.EsCancelable) ? "Desconocido" : resp.EstatusCancelacion); - - if ((resp.EsCancelable.ToUpper() == "NO CANCELABLE")) - { - sb.Append("Esta factura no es cancelable."); - return sb.ToString(); + sb.AppendFormat("Estatus de Cancelación: {0}

", string.IsNullOrEmpty(resp.EsCancelable) ? "Desconocido" : resp.EstatusCancelacion); + + var FueCancelado = CancelarDocumento(CveVenta, CveEstatus, CveCliente, Folio, uuid, CancelacionAcuse, CancelacionFecha, TipoDocto, total.ToDouble(), UsuarioActual.Empresa.CvePAC).Mensaje; + + sb.AppendFormat("{0}
", FueCancelado); + if (CveEstatus.Contiene(4, 5) && EsRefacturacion) + { + Response.Redirect(string.Format("Ventas.aspx?CveDevolucion={0}&NuevaFactura=1", CveVenta)); } - if (resp.Estado.ToUpper().Trim() == "CANCELADO" || resp.EstatusCancelacion.ToUpper() == "PLAZO VENCIDO") - { - CveEstatus = 5; - var solicitud = new WSGF.Service1SoapClient(); - var acuse = solicitud.GetAcuse(emisor, "rene.molina@adsistemas.mx", "rene2018", uuid); + //if ((resp.EsCancelable.ToUpper() == "NO CANCELABLE")) + //{ + // sb.Append("Esta factura no es cancelable."); + // return sb.ToString(); + //} - if (acuse.Estado == 0) - { - var xmlAcuse = new System.Xml.XmlDocument(); - xmlAcuse.LoadXml(DecodeBase64(acuse.CfdiB64)); + //if (resp.Estado.ToUpper().Trim() == "CANCELADO" || resp.EstatusCancelacion.ToUpper() == "PLAZO VENCIDO") + //{ + // CveEstatus = 5; + // var solicitud = new WSGF.Service1SoapClient(); + // var acuse = solicitud.GetAcuse(emisor, "rene.molina@adsistemas.mx", "rene2018", uuid); - CancelacionAcuse = xmlAcuse.GetElementsByTagName("SignatureValue")[0].InnerText; - CancelacionFecha = xmlAcuse.SelectSingleNode("Acuse").Attributes["Fecha"].Value.ToDate(); - } + // if (acuse.Estado == 0) + // { + // var xmlAcuse = new System.Xml.XmlDocument(); + // xmlAcuse.LoadXml(DecodeBase64(acuse.CfdiB64)); - var FueCancelado = CancelarDocumento(CveVenta, CveEstatus, CveCliente, Folio, uuid, CancelacionAcuse, CancelacionFecha, TipoDocto, total.ToDouble(), UsuarioActual.Empresa.CvePAC); - sb.AppendFormat("{0}
", FueCancelado); - if (CveEstatus.Contiene(4, 5) && EsRefacturacion) - { - Response.Redirect(string.Format("Ventas.aspx?CveDevolucion={0}&NuevaFactura=1", CveVenta)); - } - } - else if (resp.EstatusCancelacion.ToUpper() == "SOLICITUD RECHAZADA") - { - //ASIGNAMOS ESTATUS EMITIDA - CveEstatus = 3; - var ObjVentas = new ClsVentas(); - if (ObjVentas.UpdateEstatusVenta(CveVenta, CveEstatus, UsuarioActual.CveEmpresa)) - { - sb.Append("El estatus de la factura fue cambiado a 'Emitida'."); - } - else - { - sb.Append("Ocurrió un error al cambiar el estatus de la factura."); - } - ObjVentas.Dispose(); - } + // CancelacionAcuse = xmlAcuse.GetElementsByTagName("SignatureValue")[0].InnerText; + // CancelacionFecha = xmlAcuse.SelectSingleNode("Acuse").Attributes["Fecha"].Value.ToDate(); + // } + + // var FueCancelado = CancelarDocumento(CveVenta, CveEstatus, CveCliente, Folio, uuid, CancelacionAcuse, CancelacionFecha, TipoDocto, total.ToDouble(), UsuarioActual.Empresa.CvePAC).Mensaje; + + // sb.AppendFormat("{0}
", FueCancelado); + // if (CveEstatus.Contiene(4, 5) && EsRefacturacion) + // { + // Response.Redirect(string.Format("Ventas.aspx?CveDevolucion={0}&NuevaFactura=1", CveVenta)); + // } + //} + //else if (resp.EstatusCancelacion.ToUpper() == "SOLICITUD RECHAZADA") + //{ + // //ASIGNAMOS ESTATUS EMITIDA + // CveEstatus = 3; + // var ObjVentas = new ClsVentas(); + // if (ObjVentas.UpdateEstatusVenta(CveVenta, CveEstatus, UsuarioActual.CveEmpresa)) + // { + // sb.Append("El estatus de la factura fue cambiado a 'Emitida'."); + // } + // else + // { + // sb.Append("Ocurrió un error al cambiar el estatus de la factura."); + // } + // ObjVentas.Dispose(); + //} } else { @@ -160,137 +170,11 @@ public partial class Ventas_RepCancelacionesPorRespuesta : ClsPaginas return sb.ToString(); } - private string CancelarDocumento(int CveVenta, int CveEstatus, int CveCliente, string Folio, string FolioFiscal, string CancelacionAcuse, DateTime CancelacionFecha, string TipoComprobante, double Total, int CvePACCancelacion) + private Modelos.Factura.MCancelacionVentaMensaje CancelarDocumento(int CveVenta, int CveEstatus, int CveCliente, string Folio, string FolioFiscal, string CancelacionAcuse, DateTime CancelacionFecha, string TipoComprobante, double Total, int CvePACCancelacion) { - string Mensaje = ""; - ClsVentas ObjVentas = new ClsVentas(); - ClsOIEventos ObjEventos = new ClsOIEventos(ObjVentas.IniciaTransacSQL()); - ClsContabilidad ObjConta = new ClsContabilidad(ObjVentas.IniciaTransacSQL()); - ClsContPAQi ObjContPaq = null; - - try - { - if (UsuarioActual.Empresa.UsaAC || UsuarioActual.Empresa.Funcionalidad(200) == "1") - { - ObjContPaq = new ClsContPAQi(UsuarioActual.Empresa); - ObjContPaq.IniciaTransacSQL(); - } - bool ErrorCancelar = false; - var ErrorList = new List(); - - int IDPoliza = -1; - int CvePrePolizaCancelacion = -1; - - // CANCELA PREPOLIZA - ErrorCancelar = !ObjVentas.ProcesoPrepolizasCancelacion(CveVenta, UsuarioActual.CveUsuario); - - if (ErrorCancelar) - { - Mensaje = "Ocurrió un error al generar la prepoliza de cancelación."; - } - else - { - if (ObjVentas.DtResultados.Rows.Count > 0) - { - CvePrePolizaCancelacion = ObjVentas.DtResultados.FiltroPrimeroValor("CvePrepolizaCancelacion").ToEntero(); - if (CvePrePolizaCancelacion <= 0) - { - ErrorCancelar = true; - Mensaje = "Ocurrió un error al generar la prepoliza de cancelación."; - } - } - else - { - ErrorCancelar = true; - Mensaje = "Ocurrió un error al generar la prepoliza de cancelación."; - } - } - - // POLIZA DE CANCELACION - if (!ErrorCancelar) - { - if (UsuarioActual.Empresa.UsaAC) - { - IDPoliza = GenerarPolizaAC(ObjContPaq, CveVenta, Folio, CveCliente, TipoComprobante, DateTime.Now, true); - if ((IDPoliza <= 0)) - { - ErrorCancelar = true; - Mensaje = "Ocurrió un error al generar la poliza de cancelación."; - } - } - } - - //AUTO CONTABILIDAD - if (!ErrorCancelar) - { - if (UsuarioActual.Empresa.Funcionalidad(200) == "1" & !ErrorCancelar && CvePrePolizaCancelacion > 0) - { - if (!ObjConta.ContabilizarPrePoliza(CvePrePolizaCancelacion, UsuarioActual.CveUsuario, UsuarioActual.Empresa, ObjConta: ObjContPaq)) - { - ErrorCancelar = true; - Mensaje = "Ocurrió un error al contabilizar. Favor de ponerse en contacto con Soporte Técnico"; - } - } - } - - // ACTUALIZA ESTATUS - if (!ErrorCancelar) - { - switch (TipoComprobante) - { - case "Rem": - CveEstatus = 12; - break; - case "Com": - CveEstatus = 9; - break; - } - if (!ObjVentas.UpdateCancelaVenta(CveVenta, CancelacionFecha, CancelacionAcuse, UsuarioActual.CveEmpresa, CvePACCancelacion)) - { - ErrorCancelar = true; - Mensaje = "Ocurrió un error al guardar el estatus de cancelación."; - } - } - - if (!ErrorCancelar) - { - if (ObjContPaq != null) - { - ObjContPaq.Commit(); - } - ObjVentas.Commit(); - Mensaje = "El Documento se canceló correctamente"; - } - else - { - if (ObjContPaq != null) - { - ObjContPaq.RollBack(); - } - ObjVentas.RollBack(); - } - } - catch (Exception ex) - { - ObjVentas.RollBack(); - if (ObjContPaq != null) - { - ObjContPaq.RollBack(); - } - Mensaje = "Ocurrió un error al cancelar la factura"; - this.OnError(Mensaje, ex); - } - finally - { - ObjVentas.Dispose(); - ObjEventos.Dispose(); - ObjConta.Dispose(); - if (ObjContPaq != null) - { - ObjContPaq.Dispose(); - } - } - return Mensaje; + var factura = new Modelos.Factura(UsuarioActual, CveVenta, UsuarioActual.CveEmpresa); + var retorno = factura.EjecutarCancelacionPendiente(CveEstatus, CancelacionFecha, CancelacionAcuse); + return retorno; } private int GenerarPolizaAC(ClsContPAQi ObjAC, int CveVenta, string Folio, int CveCliente, string TipoComprobante, DateTime Fecha, bool CancelacionIngreso = false) diff --git a/Ventas/RepVentaDetalle.aspx.vb b/Ventas/RepVentaDetalle.aspx.vb index 09571d5be..9ae1ecc1e 100644 --- a/Ventas/RepVentaDetalle.aspx.vb +++ b/Ventas/RepVentaDetalle.aspx.vb @@ -7,9 +7,10 @@ Imports Microsoft.Reporting.WebForms Imports System.IO Imports System.IO.Compression Imports System.Net - +Imports System.Net.Http + Partial Class RepVentaDetalle - Inherits ClsPaginas + Inherits ClsPaginas #Region "P R O P I E D A D E S" Private Property CveProyecto As Integer Get @@ -88,10 +89,10 @@ Partial Class RepVentaDetalle Set(value As DataTable) ViewState("DtColor") = value End Set - End Property - + End Property + #End Region - 'pRivate ReadOnly Property ColumnasVisibles As + 'pRivate ReadOnly Property ColumnasVisibles As Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load If Not IsPostBack Then If UsuarioActual.CveEmpresa = 2 AndAlso UsuarioActual.CveUsuario.Contiene(77, 21) Then Response.Redirect("/Inicio.aspx") @@ -233,8 +234,8 @@ Partial Class RepVentaDetalle DdlVendedor.Enabled = False End If - End Sub - + End Sub + #Region "CARGA COMBOS" Private Sub CargaGrupo() DdlGrupo.Items.Insert(0, New ListItem("Año", "1")) @@ -386,9 +387,9 @@ Partial Class RepVentaDetalle DdlSubProyecto.DataSource = GlobalDTSubProyectos(DdlProyecto.SelectedValue.ToEntero, CveEmpresa:=UsuarioActual.CveEmpresa) DdlSubProyecto.DataBind() 'DdlSubProyecto.Items.Insert(0, New ListItem("Todos", "-1")) - End Sub + End Sub #End Region - + #Region "SELECTED INDEX CHANGE" Protected Sub DdlTipoComprobante_SelectedIndexChanged(sender As Object, e As EventArgs) CargaEstatus() @@ -416,10 +417,10 @@ Partial Class RepVentaDetalle 'DdlClientes.DataSource = GlobalDTCliente(UsuarioActual.CveEmpresa, -1).FiltraParametros($"CveClienteClasificacion = {DdlClienteClasificacion.SelectedValue.ToEntero} OR {DdlClienteClasificacion.SelectedValue.ToEntero} = -1") 'DdlClientes.DataBind() 'DdlClientes.ddl.Items.Insert(0, New ListItem("Todos", "-1")) - End Sub - + End Sub + #End Region - + #Region "CONSULTAR" Protected Sub BtnConsultar_Click(sender As Object, e As System.EventArgs) Handles BtnConsultar.Click CargaDatos() @@ -470,12 +471,12 @@ Partial Class RepVentaDetalle ObjVentas.Dispose() GvDatos.DataBind() GvVsh.DataBind() - End Sub - + End Sub + #End Region - + #Region "GRIDVIEW" - + Private Function AddRows(ByRef DT As DataTable) As DataTable Dim i As Integer = 0 Dim Ultima As String = String.Empty @@ -589,11 +590,11 @@ Partial Class RepVentaDetalle e.Row.Cells(7).HorizontalAlign = HorizontalAlign.Right End If - End Sub + End Sub #End Region - + #Region "PERSONALIZAR COLUMNAS" - + Protected Sub BtnPersonalizar_Click(sender As Object, e As System.EventArgs) Handles BtnPersonalizar.Click If ChkFolio.Checked Then @@ -777,10 +778,10 @@ Partial Class RepVentaDetalle ImgExcelPersonalizado.Visible = False End If UPDatos.Update() - End Sub - + End Sub + #End Region - + #Region "IMPRESIONES" Protected Sub ImgExcel_Click(sender As Object, e As EventArgs) Handles ImgExcel.Click 'GvDatos.ExportToExcel("DetalleVentas_" & Now.ToShortDateString) @@ -872,7 +873,28 @@ Partial Class RepVentaDetalle Response.AddHeader("content-Disposition", "attachment; filename=ReporteVentasPDF.zip") Response.ContentType = "application/zip" Response.End() - End Sub + End Sub + Private Function DescargarFactura(CveVenta As Integer, CveEmpresa As Integer) As Byte() + Dim Url = New Uri(String.Format("{0}Compras/PopUpVerFactura.aspx?P={1}", ClsPaginas.UrlSitio, Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1&GUARDAR=1", CveVenta)))) + Dim File As Byte() = Nothing + Try + Using httpClient = New HttpClient() + httpClient.Timeout = New TimeSpan(0, 15, 0) + Using request = New HttpRequestMessage(HttpMethod.Get, Url) + request.Headers.Add("ADSToken", Encripta(String.Format("CVEEMPRESA={0}&TICKS={1}", CveEmpresa, DateTime.UtcNow.Ticks))) + Dim response = httpClient.SendAsync(request).Result + If response.StatusCode = Net.HttpStatusCode.OK Then + File = response.Content.ReadAsByteArrayAsync().Result + End If + End Using + End Using + Catch ex As Exception + File = Nothing + OnError("Ocurrió un error al descargar la factura", ex) + End Try + + Return File + End Function Private Sub BtnDescargarXML_Click(sender As Object, e As EventArgs) Handles BtnDescargarXML.Click Dim pathXML As String @@ -972,132 +994,134 @@ Partial Class RepVentaDetalle GenerarPDF() End Sub - Private Sub GenerarFacturaVentaDEV(CveVenta As Integer) - Dim ObjVentas As New ClsVentas - Dim Vta As Modelos.Factura = Nothing - - Dim TmpDTImpuestos = New DataTable - TmpDTImpuestos.Columns.Add("ImpuestoLocal", GetType(String)) - TmpDTImpuestos.Columns.Add("Importe", GetType(Double)) - TmpDTImpuestos.Columns.Add("Orden", GetType(Integer)) - - If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then - Dim dtVentas As DataTable = ObjVentas.DtResultados - - ' se rellenan los campos de la factura - Vta = ObjVentas.DtResultados.Rows(0).DataRowToObject(Of Modelos.Factura) - - Vta.MonedaAbreviatura = dtVentas(0)("Abreviatura").ToString - 'se rellena la sucursal - Vta.Cliente.Sucursal = ObjVentas.DtResultados.Rows(0).DataRowToObject(Of Modelos.SucursalModel).ToString - Vta.Cliente = New Modelos.ClienteModel - Vta.Cliente.Nombre = dtVentas(0)("ClienteNombre").ToString - Vta.Cliente.Telefono = dtVentas(0)("Telefono").ToString - Vta.Cliente.Direccion = dtVentas(0)("ClienteDireccion").ToString - Vta.Cliente.CP = dtVentas(0)("CPCliente").ToString - Vta.Cliente.Ciudad = dtVentas(0)("ClienteCiudad").ToString - Vta.Cliente.Localidad = dtVentas(0)("ClienteLocalidad").ToString - Vta.Cliente.Estado = dtVentas(0)("ClienteEstado").ToString - Vta.Cliente.Pais = dtVentas(0)("ClientePais").ToString - Vta.Cliente.RFC = dtVentas(0)("ClienteRFC").ToString - Vta.Cliente.Colonia = dtVentas(0)("ColoniaCliente").ToString - Vta.AtencionA = dtVentas(0)("AtencionA").ToString - Vta.Cliente.NoExt = dtVentas(0)("ClienteNoExt").ToString - Vta.Cliente.NoInt = dtVentas(0)("ClienteNoInt").ToString - Vta.Cliente.Codigo = dtVentas(0)("ClienteCodigo").ToString - Vta.Cliente.Mail = dtVentas(0)("Mail").ToString - Vta.RefDocto = dtVentas(0)("Ref").ToString - Vta.CveVenta = dtVentas(0)("CveVenta").ToString.ToEntero - - - Vta.ClienteSucursal = New Modelos.SucursalModel - Vta.ClienteSucursal.Direccion = dtVentas(0)("SucClienteDireccion").ToString - Vta.ClienteSucursal.NoExt = dtVentas(0)("SucClienteNoExt").ToString - Vta.ClienteSucursal.NoInt = dtVentas(0)("SucClienteNoInt").ToString - Vta.ClienteSucursal.Colonia = dtVentas(0)("SucClienteColonia").ToString - Vta.ClienteSucursal.CP = dtVentas(0)("SucClienteCP").ToString - Vta.ClienteSucursal.Municipio = dtVentas(0)("SucClienteCiudad").ToString - Vta.ClienteSucursal.Estado = dtVentas(0)("SucClienteEstado").ToString - Vta.ClienteSucursal.Pais = dtVentas(0)("SucClientePais").ToString - Vta.ClienteSucursal.Localidad = dtVentas(0)("SucClienteLocalidad").ToString - Vta.ClienteSucursal.CorreoSucursal = dtVentas(0)("SucClienteCorreo").ToString - Vta.ClienteSucursal.TelefonoSucursal = dtVentas(0)("SucClienteTelefono").ToString - Vta.ClienteSucursal.Sucursal = dtVentas(0)("SucursalCliente").ToString - - Vta.EnviarA = New Modelos.EnviarAModel - Vta.EnviarA.CveDireccionEnvio = dtVentas(0)("CveDireccionEnvio").ToString.ToEntero - Vta.EnviarA.EnvioDireccion = dtVentas(0)("EnvioDireccion").ToString - Vta.EnviarA.EnvioColonia = dtVentas(0)("EnvioColonia").ToString - Vta.EnviarA.EnvioCiudad = dtVentas(0)("EnvioCiudad").ToString - Vta.EnviarA.EnvioEstado = dtVentas(0)("EnvioEstado").ToString - Vta.EnviarA.EnvioCP = dtVentas(0)("EnvioCP").ToString - - Dim DR As DataRow = TmpDTImpuestos.NewRow() - If UsuarioActual.CveEmpresa.Contiene(1, 5, 15, 17, 72, 66, 79, 81, 109, 110, 111, 76) Then - If dtVentas(0)("SubTotal").ToString.ToDouble <> 0 Then DR("ImpuestoLocal") = "Subtotal" : DR("Importe") = dtVentas(0)("SubTotal").ToString.ToDouble : DR("Orden") = 10 : TmpDTImpuestos.Rows.Add(DR) - DR = TmpDTImpuestos.NewRow() - If dtVentas(0)("Descuento").ToString.ToDouble <> 0 Then DR("ImpuestoLocal") = "Descuentos" : DR("Importe") = dtVentas(0)("Descuento").ToString.ToDouble : DR("Orden") = 20 : TmpDTImpuestos.Rows.Add(DR) - DR = TmpDTImpuestos.NewRow() - If dtVentas(0)("Amortizacion").ToString.ToDouble <> 0 Then DR("ImpuestoLocal") = "Amort.Ant" : DR("Importe") = dtVentas(0)("Amortizacion").ToString.ToDouble : DR("Orden") = 30 : TmpDTImpuestos.Rows.Add(DR) - DR = TmpDTImpuestos.NewRow() - If dtVentas(0)("SubTotal").ToString.ToDouble <> (dtVentas(0)("SubTotal").ToString.ToDouble - dtVentas(0)("Descuento").ToString.ToDouble - dtVentas(0)("Amortizacion").ToString.ToDouble) Then DR("ImpuestoLocal") = "SubTotal2" : DR("Importe") = (dtVentas(0)("SubTotal").ToString.ToDouble - dtVentas(0)("Descuento").ToString.ToDouble - dtVentas(0)("Amortizacion").ToString.ToDouble) : DR("Orden") = 40 : TmpDTImpuestos.Rows.Add(DR) - DR = TmpDTImpuestos.NewRow() - If dtVentas(0)("IVA").ToString.ToDouble <> 0 Then DR("ImpuestoLocal") = "IVA" : DR("Importe") = dtVentas(0)("IVA").ToString.ToDouble : DR("Orden") = 50 : TmpDTImpuestos.Rows.Add(DR) - - 'solo para eclipse, que muesre un subtotal debajo de IVA - If UsuarioActual.CveEmpresa = 15 Then DR = TmpDTImpuestos.NewRow() : DR("ImpuestoLocal") = "Subtotal2" : DR("Importe") = (dtVentas(0)("SubTotal").ToString.ToDouble - dtVentas(0)("Descuento").ToString.ToDouble - dtVentas(0)("Amortizacion").ToString.ToDouble) + dtVentas(0)("IVA").ToString.ToDouble : DR("Orden") = 51 : TmpDTImpuestos.Rows.Add(DR) - DR = TmpDTImpuestos.NewRow() - If dtVentas(0)("RetIVA").ToString.ToDouble <> 0 Then DR("ImpuestoLocal") = "Ret.IVA" : DR("Importe") = dtVentas(0)("RetIVA").ToString.ToDouble : DR("Orden") = 60 : TmpDTImpuestos.Rows.Add(DR) - DR = TmpDTImpuestos.NewRow() - If dtVentas(0)("RetISR").ToString.ToDouble <> 0 Then DR("ImpuestoLocal") = "Ret.ISR" : DR("Importe") = dtVentas(0)("RetISR").ToString.ToDouble : DR("Orden") = 70 : TmpDTImpuestos.Rows.Add(DR) - DR = TmpDTImpuestos.NewRow() - If dtVentas(0)("Total").ToString.ToDouble <> 0 Then DR("ImpuestoLocal") = "Total" : DR("Importe") = dtVentas(0)("Total").ToString.ToDouble : DR("Orden") = 1000 : TmpDTImpuestos.Rows.Add(DR) - DR = TmpDTImpuestos.NewRow() - End If - - If ObjVentas.GetVentaDetalle(CveVenta) Then 'Obtenemos el Detalle de la Oorden de Compra - Vta.DtDetalle = ObjVentas.DtResultados - End If - - If ObjVentas.GetVentaImpuestosLocales(CveVenta) Then - If UsuarioActual.CveEmpresa.Contiene(1, 5, 15, 17, 72, 66, 79, 81, 109, 110, 111, 76) Then - Dim dtImpuesto As DataTable = ObjVentas.DtResultados - If dtImpuesto.Rows.Count > 0 Then - For Each Row As DataRow In dtImpuesto.Rows - Dim Orden = 80 - If Row("Importe").ToString.ToDouble <> 0 Then - DR("ImpuestoLocal") = Row("ImpuestoLocal").ToString - DR("Importe") = Row("Importe").ToString.ToDouble - DR("Orden") = Orden - TmpDTImpuestos.Rows.Add(DR) - DR = TmpDTImpuestos.NewRow() - Orden = Orden + 1 - End If - Next - End If - Vta.DtDeduccion = TmpDTImpuestos.FiltraParametros("", Orderby:="Orden ASC") - Else - Vta.DtDeduccion = ObjVentas.DtResultados - End If - End If - - If ObjVentas.GetVentasFirmas(CveVenta) Then - Vta.DtFirmas = ObjVentas.DtResultados - End If - End If - ObjVentas.Dispose() - - If Not IsNothing(Vta) Then - PdfFactura(Vta) - Vta = Nothing - End If - - End Sub - + Private Sub GenerarFacturaVentaDEV(CveVenta As Integer) + + DescargarFactura(CveVenta, UsuarioActual.CveEmpresa) + 'Dim ObjVentas As New ClsVentas + 'Dim Vta As Modelos.Factura = Nothing + + 'Dim TmpDTImpuestos = New DataTable + 'TmpDTImpuestos.Columns.Add("ImpuestoLocal", GetType(String)) + 'TmpDTImpuestos.Columns.Add("Importe", GetType(Double)) + 'TmpDTImpuestos.Columns.Add("Orden", GetType(Integer)) + + 'If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) AndAlso ObjVentas.DtResultados.Rows.Count > 0 Then + ' Dim dtVentas As DataTable = ObjVentas.DtResultados + + ' ' se rellenan los campos de la factura + ' Vta = New Modelos.Factura(UsuarioActual, CveVenta, UsuarioActual.CveEmpresa, Server.MapPath("/")) + + ' Vta.MonedaAbreviatura = dtVentas(0)("Abreviatura").ToString + ' 'se rellena la sucursal + ' Vta.Cliente.Sucursal = New Modelos.ClienteModel(dtVentas(0)("CveCliente").ToString.ToEntero, UsuarioActual.CveEmpresa) + ' Vta.Cliente = New Modelos.ClienteModel + ' Vta.Cliente.Nombre = dtVentas(0)("ClienteNombre").ToString + ' Vta.Cliente.Telefono = dtVentas(0)("Telefono").ToString + ' Vta.Cliente.Direccion = dtVentas(0)("ClienteDireccion").ToString + ' Vta.Cliente.CP = dtVentas(0)("CPCliente").ToString + ' Vta.Cliente.Ciudad = dtVentas(0)("ClienteCiudad").ToString + ' Vta.Cliente.Localidad = dtVentas(0)("ClienteLocalidad").ToString + ' Vta.Cliente.Estado = dtVentas(0)("ClienteEstado").ToString + ' Vta.Cliente.Pais = dtVentas(0)("ClientePais").ToString + ' Vta.Cliente.RFC = dtVentas(0)("ClienteRFC").ToString + ' Vta.Cliente.Colonia = dtVentas(0)("ColoniaCliente").ToString + ' Vta.AtencionA = dtVentas(0)("AtencionA").ToString + ' Vta.Cliente.NoExt = dtVentas(0)("ClienteNoExt").ToString + ' Vta.Cliente.NoInt = dtVentas(0)("ClienteNoInt").ToString + ' Vta.Cliente.Codigo = dtVentas(0)("ClienteCodigo").ToString + ' Vta.Cliente.Mail = dtVentas(0)("Mail").ToString + ' Vta.RefDocto = dtVentas(0)("Ref").ToString + ' Vta.CveVenta = dtVentas(0)("CveVenta").ToString.ToEntero + + + ' Vta.ClienteSucursal = New Modelos.SucursalModel + ' Vta.ClienteSucursal.Direccion = dtVentas(0)("SucClienteDireccion").ToString + ' Vta.ClienteSucursal.NoExt = dtVentas(0)("SucClienteNoExt").ToString + ' Vta.ClienteSucursal.NoInt = dtVentas(0)("SucClienteNoInt").ToString + ' Vta.ClienteSucursal.Colonia = dtVentas(0)("SucClienteColonia").ToString + ' Vta.ClienteSucursal.CP = dtVentas(0)("SucClienteCP").ToString + ' Vta.ClienteSucursal.Municipio = dtVentas(0)("SucClienteCiudad").ToString + ' Vta.ClienteSucursal.Estado = dtVentas(0)("SucClienteEstado").ToString + ' Vta.ClienteSucursal.Pais = dtVentas(0)("SucClientePais").ToString + ' Vta.ClienteSucursal.Localidad = dtVentas(0)("SucClienteLocalidad").ToString + ' Vta.ClienteSucursal.CorreoSucursal = dtVentas(0)("SucClienteCorreo").ToString + ' Vta.ClienteSucursal.TelefonoSucursal = dtVentas(0)("SucClienteTelefono").ToString + ' Vta.ClienteSucursal.Sucursal = dtVentas(0)("SucursalCliente").ToString + + ' Vta.EnviarA = New Modelos.EnviarAModel + ' Vta.EnviarA.CveDireccionEnvio = dtVentas(0)("CveDireccionEnvio").ToString.ToEntero + ' Vta.EnviarA.EnvioDireccion = dtVentas(0)("EnvioDireccion").ToString + ' Vta.EnviarA.EnvioColonia = dtVentas(0)("EnvioColonia").ToString + ' Vta.EnviarA.EnvioCiudad = dtVentas(0)("EnvioCiudad").ToString + ' Vta.EnviarA.EnvioEstado = dtVentas(0)("EnvioEstado").ToString + ' Vta.EnviarA.EnvioCP = dtVentas(0)("EnvioCP").ToString + + ' Dim DR As DataRow = TmpDTImpuestos.NewRow() + ' If UsuarioActual.CveEmpresa.Contiene(1, 5, 15, 17, 72, 66, 79, 81, 109, 110, 111, 76) Then + ' If dtVentas(0)("SubTotal").ToString.ToDouble <> 0 Then DR("ImpuestoLocal") = "Subtotal" : DR("Importe") = dtVentas(0)("SubTotal").ToString.ToDouble : DR("Orden") = 10 : TmpDTImpuestos.Rows.Add(DR) + ' DR = TmpDTImpuestos.NewRow() + ' If dtVentas(0)("Descuento").ToString.ToDouble <> 0 Then DR("ImpuestoLocal") = "Descuentos" : DR("Importe") = dtVentas(0)("Descuento").ToString.ToDouble : DR("Orden") = 20 : TmpDTImpuestos.Rows.Add(DR) + ' DR = TmpDTImpuestos.NewRow() + ' If dtVentas(0)("Amortizacion").ToString.ToDouble <> 0 Then DR("ImpuestoLocal") = "Amort.Ant" : DR("Importe") = dtVentas(0)("Amortizacion").ToString.ToDouble : DR("Orden") = 30 : TmpDTImpuestos.Rows.Add(DR) + ' DR = TmpDTImpuestos.NewRow() + ' If dtVentas(0)("SubTotal").ToString.ToDouble <> (dtVentas(0)("SubTotal").ToString.ToDouble - dtVentas(0)("Descuento").ToString.ToDouble - dtVentas(0)("Amortizacion").ToString.ToDouble) Then DR("ImpuestoLocal") = "SubTotal2" : DR("Importe") = (dtVentas(0)("SubTotal").ToString.ToDouble - dtVentas(0)("Descuento").ToString.ToDouble - dtVentas(0)("Amortizacion").ToString.ToDouble) : DR("Orden") = 40 : TmpDTImpuestos.Rows.Add(DR) + ' DR = TmpDTImpuestos.NewRow() + ' If dtVentas(0)("IVA").ToString.ToDouble <> 0 Then DR("ImpuestoLocal") = "IVA" : DR("Importe") = dtVentas(0)("IVA").ToString.ToDouble : DR("Orden") = 50 : TmpDTImpuestos.Rows.Add(DR) + + ' 'solo para eclipse, que muesre un subtotal debajo de IVA + ' If UsuarioActual.CveEmpresa = 15 Then DR = TmpDTImpuestos.NewRow() : DR("ImpuestoLocal") = "Subtotal2" : DR("Importe") = (dtVentas(0)("SubTotal").ToString.ToDouble - dtVentas(0)("Descuento").ToString.ToDouble - dtVentas(0)("Amortizacion").ToString.ToDouble) + dtVentas(0)("IVA").ToString.ToDouble : DR("Orden") = 51 : TmpDTImpuestos.Rows.Add(DR) + ' DR = TmpDTImpuestos.NewRow() + ' If dtVentas(0)("RetIVA").ToString.ToDouble <> 0 Then DR("ImpuestoLocal") = "Ret.IVA" : DR("Importe") = dtVentas(0)("RetIVA").ToString.ToDouble : DR("Orden") = 60 : TmpDTImpuestos.Rows.Add(DR) + ' DR = TmpDTImpuestos.NewRow() + ' If dtVentas(0)("RetISR").ToString.ToDouble <> 0 Then DR("ImpuestoLocal") = "Ret.ISR" : DR("Importe") = dtVentas(0)("RetISR").ToString.ToDouble : DR("Orden") = 70 : TmpDTImpuestos.Rows.Add(DR) + ' DR = TmpDTImpuestos.NewRow() + ' If dtVentas(0)("Total").ToString.ToDouble <> 0 Then DR("ImpuestoLocal") = "Total" : DR("Importe") = dtVentas(0)("Total").ToString.ToDouble : DR("Orden") = 1000 : TmpDTImpuestos.Rows.Add(DR) + ' DR = TmpDTImpuestos.NewRow() + ' End If + + ' If ObjVentas.GetVentaDetalle(CveVenta) Then 'Obtenemos el Detalle de la Oorden de Compra + ' Vta.DtDetalle = ObjVentas.DtResultados + ' End If + + ' If ObjVentas.GetVentaImpuestosLocales(CveVenta) Then + ' If UsuarioActual.CveEmpresa.Contiene(1, 5, 15, 17, 72, 66, 79, 81, 109, 110, 111, 76) Then + ' Dim dtImpuesto As DataTable = ObjVentas.DtResultados + ' If dtImpuesto.Rows.Count > 0 Then + ' For Each Row As DataRow In dtImpuesto.Rows + ' Dim Orden = 80 + ' If Row("Importe").ToString.ToDouble <> 0 Then + ' DR("ImpuestoLocal") = Row("ImpuestoLocal").ToString + ' DR("Importe") = Row("Importe").ToString.ToDouble + ' DR("Orden") = Orden + ' TmpDTImpuestos.Rows.Add(DR) + ' DR = TmpDTImpuestos.NewRow() + ' Orden = Orden + 1 + ' End If + ' Next + ' End If + ' Vta.DtDeduccion = TmpDTImpuestos.FiltraParametros("", Orderby:="Orden ASC") + ' Else + ' Vta.DtDeduccion = ObjVentas.DtResultados + ' End If + ' End If + + ' If ObjVentas.GetVentasFirmas(CveVenta) Then + ' Vta.DtFirmas = ObjVentas.DtResultados + ' End If + 'End If + 'ObjVentas.Dispose() + + 'If Not IsNothing(Vta) Then + ' PdfFactura(Vta) + ' Vta = Nothing + 'End If + + End Sub + #End Region - + #Region "GRAFICA" - + Private Sub CreaDataTableColor() DtColor = New DataTable DtColor.Columns.Add("Color") @@ -1228,9 +1252,9 @@ Partial Class RepVentaDetalle Protected Sub DdlVer_SelectedIndexChanged(sender As Object, e As EventArgs) CambioGrafica() - End Sub - + End Sub + #End Region - - + + End Class diff --git a/Ventas/Ventas.aspx.vb b/Ventas/Ventas.aspx.vb index f4a9a4008..5dc02ad0f 100644 --- a/Ventas/Ventas.aspx.vb +++ b/Ventas/Ventas.aspx.vb @@ -7262,7 +7262,13 @@ Partial Class Ventas Private Sub CreaObjetosVenta(Optional VistaPrevia As Boolean = False) - ObjFactura = New Modelos.Factura + + If Me.CveVenta > 0 Then + ObjFactura = New Modelos.Factura(UsuarioActual, CveVenta, UsuarioActual.CveEmpresa) + Else + ObjFactura = New Modelos.Factura + End If + ObjFactura.Version = "3.3" ObjFactura.CveUsuario = UsuarioActual.CveUsuario @@ -17061,6 +17067,8 @@ Partial Class Ventas TxtPrecio.Text = GvRow.FCLiteral("LtlPU").Text RegistraScript("Recalcula();") LbAgregar_Click(Nothing, Nothing) + Else + DdlPS_SelectedIndexChanged(Nothing, Nothing) End If End Sub Protected Sub OrdenarGvPS(ByVal sender As Object, ByVal e As EventArgs) @@ -17347,874 +17355,40 @@ Partial Class Ventas CancelarRefacturada() End If - 'La validacion de saldos cuando es refacturacion se hace antes asi que si es refacturacion ignoramos esta condicion, si es Anticipo verifica que no esté aplicado - If DdlTipoComprobante.SelectedValue = "Ant" AndAlso (HdnPagado.Value.ToDecimal > 0 Or GvAntNC.Rows.Count > 0) Then - Alert("La factura no se puede cancelar debido a que tiene pagos vinculados.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - 'La validacion de saldos cuando es refacturacion se hace antes asi que si es refacturacion ignoramos esta condicion - If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Rem") AndAlso HdnPagado.Value.ToDecimal > 0 Then - Alert("La factura no se puede cancelar debido a que tiene pagos vinculados.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - - 'Si la remision esta facturada no se puede cancelar - If DdlTipoComprobante.SelectedValue = "Rem" Then - Dim ObjV As New ClsVentas - If ObjV.VerificarRemisionFacturada(CveVenta) Then - If ObjV.DtResultados.Rows.Count > 0 Then - Alert("La remisión no se puede cancelar debido a que ya esta vinculada a una factura.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - End If - ObjV.Dispose() - End If - - 'CARGA REMISIONES DE LA VENTA DEVUELTA - Dim DtDevRem As New DataTable - If Not EsRefacturacion Then - Dim ObjInventarioTemporal As New ClsInventarios() - If ObjInventarioTemporal.GetDevolucionRemisionesCanceladas(CveVenta) Then - DtDevRem = ObjInventarioTemporal.DtResultados - Else - Alert("Ocurrió un error al verificar los movimientos de almacén relacionados al documento.", TipoMensaje.MsgError) - ObjInventarioTemporal.Dispose() - Exit Sub - End If - ObjInventarioTemporal.Dispose() - End If - - '[IPP] FALTA TERMINAR 27/Noviembre/2018 - '' si tiene movimientos en almacen que se hallan surtido en el documento actual, y sigue sin ser marcado como devuelto - 'If (GvInv.Rows.Count > 0 AndAlso DevolucionAlmacen.Contiene(0, 1)) And DtDevRem.COUNT("CantidadSurtida", "ISNULL(CveRem,0) = 0") > 0 Then ' [COMENTADO IPP 3 Agosto 2017] | AndAlso Not (DdlTipoComprobante.SelectedValue.Contiene("Rem", "DPe")) | REMISION YA SE DEBE HACER POR EL PROCESO DE DEVOLUCION DE ALMACEN - ' Alert("La factura no se puede cancelar debido a que tiene movimientos de inventario.", TipoMensaje.MsgAdvertencia) - ' Exit Sub - 'End If - - Dim ReviveRemision As Boolean = False - 'RMF. ANOTACION. cuando se cancela, y tiene relacionada una remisión, y esta no se cancelará. debe de hacer en automático los movimientos al almacen de entrega por adelantado - If Not EsRefacturacion AndAlso ChkCanRem.Visible AndAlso ChkCanRem.Checked = False Then - ReviveRemision = True - End If - If Not EsRefacturacion AndAlso (VentaSaldoAlmacen > 0 AndAlso DevolucionAlmacen.Contiene(0, 1)) AndAlso Not ChkDevAlm.Checked And ReviveRemision = False Then ' [COMENTADO IPP 3 Agosto 2017] | AndAlso Not (DdlTipoComprobante.SelectedValue.Contiene("Rem", "DPe")) | REMISION YA SE DEBE HACER POR EL PROCESO DE DEVOLUCION DE ALMACEN - Alert("La factura no se puede cancelar debido a que tiene movimientos de inventario.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - Dim CancelacionFecha As Date - Dim CancelacionAcuse As String = "" - Dim MensajeError As String = "" - Dim ObjCancelacion As New Timbrado - Dim TotalT As Decimal = TxtTotal.Text.ToDecimal - Dim RFCReceptor As String = LblRFC.Text.Trim - Dim CvePACCancelacion As Integer = CvePAC - Dim CveEstatus As Integer = 4 - Dim IDPoliza As Integer = -1 - Dim CvePrePoliza As Integer - Dim CvePlantillaPoliza As Integer - Dim ErrorCancelar As Boolean = False - - Dim Continuar As Boolean = False - Dim ContinuarCancelacion As Boolean = False - Dim ObtenerAcuse As Boolean = False - Dim RequiereAceptacion As Boolean = False - Dim Mensaje As String = "" - Try - If FolioFiscal <> "" Then - If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Dev", "Egs") Then - - Dim Vigencia = Timbrado.VerificarVigenciaSAT(FolioFiscal, UsuarioActual.Empresa.RFC, RFCReceptor, TotalT.ToString(), UsuarioActual.Empresa.FacturaProduccion) - If Vigencia IsNot Nothing Then - If Vigencia.EsCancelable.ToUpper() = "NO CANCELABLE" Then - Alert("Esta factura no es cancelable.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - If Vigencia.Estado.ToUpper().Contains("CANCELADO") Then - ContinuarCancelacion = False - ObtenerAcuse = True - Dim solicitud = New WSGF.Service1SoapClient() - Dim acuse = solicitud.GetAcuse(UsuarioActual.Empresa.RFC, "rene.molina@adsistemas.mx", "rene2018", FolioFiscal) - - If acuse.Estado = 0 Then - Dim xmlAcuse = New System.Xml.XmlDocument() - xmlAcuse.LoadXml(DecodeBase64(acuse.CfdiB64)) - CancelacionAcuse = xmlAcuse.GetElementsByTagName("SignatureValue")(0).InnerText - CancelacionFecha = xmlAcuse.SelectSingleNode("Acuse").Attributes("Fecha").Value.ToDate() - CveEstatus = 5 - Else - CancelacionFecha = Now.Date - CancelacionAcuse = "" - CveEstatus = 5 - End If - - ElseIf Vigencia.Estado.ToUpper().Contains("VIGENTE") Then - - If Vigencia.EstatusCancelacion.ToUpper() = "EN PROCESO" Then - CveEstatus = 20 - ContinuarCancelacion = False - If ChkCanRem.Checked Then SeCancelaRemisionProceso = True - ElseIf Vigencia.EsCancelable.ToUpper() = "CANCELABLE CON ACEPTACIÓN" Then - CveEstatus = 20 - ContinuarCancelacion = True - RequiereAceptacion = True - If ChkCanRem.Checked Then SeCancelaRemisionProceso = True - ElseIf Vigencia.EsCancelable.ToUpper() = "CANCELABLE SIN ACEPTACIÓN" Then - ContinuarCancelacion = True - CveEstatus = 5 - End If - - Else - If Vigencia.EsCancelable.ToUpper() = "CANCELABLE SIN ACEPTACIÓN" Then - ContinuarCancelacion = True - CveEstatus = 5 - Else - 'Alert("La factura no se puede cancelar debido a que no se encontro su estatus en el SAT.", TipoMensaje.MsgAdvertencia) - 'Exit Sub - CveEstatus = 20 - ContinuarCancelacion = False - CancelacionFecha = Now.Date - CancelacionAcuse = "" - If ChkCanRem.Checked Then SeCancelaRemisionProceso = True - End If - End If - Else - Alert("No se pudo comprobar la vigencia de la factura.", TipoMensaje.MsgAdvertencia) - Exit Sub - End If - - If Not ObtenerAcuse Then - If ContinuarCancelacion Then - If ObjCancelacion.CFDICancelar(UsuarioActual.Empresa, FolioFiscal, TotalT, RFCReceptor, UsuarioActual.Empresa.RFC, CvePACCancelacion) Then - 'Generamos el acuse y mandamos mail de con el acuse de cancelación - DF 13/01/2017 - If RequiereAceptacion Then - CancelacionFecha = Now.Date - CancelacionAcuse = "" - CveEstatus = 20 - If ChkCanRem.Checked Then SeCancelaRemisionProceso = True - Else - CancelacionFecha = ObjCancelacion.CancelacionFecha - CancelacionAcuse = ObjCancelacion.CancelacionAcuse - CveEstatus = 5 - End If - Else - Alert("La factura no se pudo cancelar ante el SAT", TipoMensaje.MsgError) - Exit Sub - End If - Else - CancelacionFecha = Now.Date - CancelacionAcuse = "" - End If - End If - Else - CancelacionFecha = Now.Date - CancelacionAcuse = "" - End If - Else - CancelacionFecha = Now.Date - CancelacionAcuse = "" - End If - Catch ex As Exception - MensajeError = "Ocurrió un Error al Cancelar la factura con los servicios del SAT." - GuardaLog($"{MensajeError} - Error:{ex.Message}") - Alert(MensajeError, TipoMensaje.MsgError) - Exit Sub - End Try - - Dim ObjVentas As New ClsVentas() : ObjVentas.IniciaTransacSQL() - Dim ObjConta As New ClsContabilidad(ObjVentas.IniciaTransacSQL()) - Dim ObjBancos As New ClsBancos(ObjVentas.IniciaTransacSQL()) - Dim ObjInventario As New ClsInventarios(ObjVentas.IniciaTransacSQL()) - Dim ObjContrato As New ClsContratos(ObjVentas.IniciaTransacSQL()) - Dim ObjEventos As New ClsOIEventos(ObjVentas.IniciaTransacSQL()) - Dim ObjAC As ClsContPAQi = Nothing - If UsuarioActual.Empresa.UsaAC Then - ObjAC = New ClsContPAQi(UsuarioActual.Empresa) : ObjAC.IniciaTransacSQL() - End If CreaObjetosVenta() + Dim resp As Modelos.Factura.MCancelacionVentaMensaje = Nothing - ObjFactura.CveVenta = CveVenta - If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then - CvePlantillaPoliza = 7 - ElseIf ObjFactura.TipoDocto.Contiene("Ing", "Rem", "Ant") Then - CvePlantillaPoliza = 4 - Else - CvePlantillaPoliza = 4 - End If + If ObjFactura IsNot Nothing AndAlso ObjFactura.CveVenta > 0 Then - If ((HplSaldoAuxiliar.Text.ToDecimal > 0 OrElse (TxtTotal.Text.ToDecimal = 0 AndAlso UsuarioActual.CveEmpresa.Contiene(72) AndAlso ObjFactura.TipoDocto.Contiene("Ing"))) AndAlso CveEstatus.Contiene(4, 5)) OrElse CvePlantillaPoliza = 7 Then - 'RMF. 2018.08.08 cuando se cancela, la póliza debe de ser de diario - CvePrePoliza = ObjConta.AddPrePolizas("Ventas/CancelarDocumento", CvePlantillaPoliza, TxtTotal.Text.ToDouble, TxtTotal.Text.ToDouble, DdlMoneda.SelectedValue.ToEntero, Now, NombreCliente, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoPoliza:=3) - ObjFactura.CvePrePoliza = CvePrePoliza - - 'CANCELAR PAGOS - If ObjFactura.TipoDocto.Contiene("Egs", "Dev") Then - If Not ErrorCancelar Then - If Not ObjConta.PrePolizasCancelarPagos(CveDevolucion, CvePrePoliza) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al generar la prepoliza de cancelación de pago." - End If - End If - End If - - 'CANCELA PREPOLIZA - If Not ErrorCancelar Then - ErrorCancelar = ProcesoPrepolizas(ObjConta, ObjFactura, -1, TmpDT, ObjAC, -1, ObjBancos, ObjVentas, ObjEventos) - MensajeError = "Ocurrió un error al generar la prepoliza de cancelación." - End If - - 'CANCELA IMPUESTOS LOCALES - If Not ErrorCancelar Then - ErrorCancelar = GuardarVentaImpuestosLocales(ObjVentas, ObjConta, ObjFactura, -1) - MensajeError = "Ocurrió un error al cancelar los impuestos locales." - End If - End If - - 'CANCELA CONTRATOS - If Not EsRefacturacion Then - If Not ErrorCancelar Then - ErrorList = New List(Of String) - If ObjFactura.CveContrato > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant") Then - GuardarContratoAvanceEstimaciones(ObjContrato, ObjFactura, ErrorList, -1, True) - ErrorCancelar = ErrorList.Count > 0 - MensajeError = "Ocurrió un error al cancelar las estimaciones del contrato." - ElseIf ObjFactura.CveContrato > 0 AndAlso DdlTipoComprobante.SelectedValue.Contiene("Egs", "Dev") Then - GuardarContratoAvanceEstimaciones(ObjContrato, ObjFactura, ErrorList, 1, True) - ErrorCancelar = ErrorList.Count > 0 - MensajeError = "Ocurrió un error al cancelar los avances del contrato." - End If - End If - End If - - - 'DESVINCULA COTIZACIONES PREDECESORAS - If Not EsRefacturacion Then - If Not ErrorCancelar Then - If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem") Then - If Not ObjVentas.LiberarCotizacionesFacturadas(CveVenta) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al desvincular las cotizaciones." - End If - End If - End If - End If - - 'DESVINCULA PEDIDOS2 PREDECESORES - If Not EsRefacturacion Then - If Not ErrorCancelar Then - If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant", "Rem") Then - If Not ObjVentas.LiberarPedidos2Facturados(CveVenta) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al desvincular los pedidos." - End If - End If - End If - End If - - - 'DESVINCULA OCs PREDECESORAS - If Not EsRefacturacion Then - If Not ErrorCancelar Then - If DdlTipoComprobante.SelectedValue = "Ing" Then - If Not ObjVentas.LiberarOCFacturadas(CveVenta) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al desvincular las Ordenes de Compra." - End If - End If - End If - End If - - 'ELIMINA LAS VENTAS DETALLE DE LA DEVOLUCION - If Not EsRefacturacion Then - If Not ErrorCancelar Then - If DdlTipoComprobante.SelectedValue = "Dev" Then - If Not ObjVentas.RemoveVentaDetalleDevolucion(CveVenta) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al eliminar las ventas detalle devolución." - End If - End If - End If - End If - 'POLIZA DE CANCELACION - If Not EsRefacturacion Then - If Not ErrorCancelar Then - If UsuarioActual.Empresa.UsaAC Then - IDPoliza = GenerarPolizaAC(ObjAC, True) - If IDPoliza <= 0 Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al generar la poliza de cancelación." - End If - End If - End If - End If - - 'DEVOLUCION DE ALMACEN - If ChkDevAlm.Checked Or ReviveRemision Then - Dim TieneSalida As Boolean = False - Dim DtDatos As New DataTable - Dim DtExistencias As New DataTable - - If DevolucionAlmacen = 0 Then - Dim EstatusDevolucion = 1 - If Not ObjVentas.UpdateVentasDevolucionAlmacen(EstatusDevolucion, CveVenta) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al solicitar la devolucion de almacen." - End If - End If - - If Not ErrorCancelar AndAlso ObjInventario.EntregaAlmacenGet(CveVenta) Then - If ObjInventario.DtResultados IsNot Nothing AndAlso ObjInventario.DtResultados.Rows.Count > 0 Then - DtDatos = ObjInventario.DtResultados - DtDatos.Columns.Add("Consec", GetType(Integer)) - DtDatos.Columns.Add("CantidadGV", GetType(Double)) - DtDatos.Columns.Add("CantidadTraspaso", GetType(Double)) - Dim Index = 1 - For Each Dr As DataRow In DtDatos.Rows - Dr("Consec") = Index - Dr("CantidadGV") = Dr("CantidadF") - Index += 1 - Next - - If DtDatos IsNot Nothing AndAlso DtDatos.Rows.Count > 0 AndAlso ObjInventario.DtResultados.Rows(0)("CveVentaPadre").ToString.ToEntero > 0 Then - Dim Filtro As String '= If(ObjInventario.DtResultados.Rows(0)("TipoDocto").ToString.Contiene({"Ing", "Dev", "Ped"}), "CveConcepto = 3", "CveConcepto = 9") - Select Case ObjInventario.DtResultados.Rows(0)("TipoDocto").ToString - Case "Ing", "Ped" - Filtro = "CveConcepto = 3" - Case "Dev" - Filtro = "CveConcepto = 3" - Case Else - Filtro = "CveConcepto = 9" - End Select - If ObjInventario.GetInv_Mov(ObjInventario.DtResultados.Rows(0)("CveVentaPadre").ToString.ToEntero, UsuarioActual.CveEmpresa) Then - DtExistencias = ObjInventario.DtResultados.FiltraParametros($"CvePS Is Not NULL AND {Filtro}") - - If DtExistencias.Rows.Count > 0 Then - TieneSalida = True - End If - - Else - ErrorCancelar = True - MensajeError = "Ocurrió un error al cargar los datos de devolución. Por favor vuelva a intentar." - End If - End If - End If - End If - - If Not ErrorCancelar AndAlso TieneSalida Then - Dim DtDatosDetalle As New DataTable - DtDatosDetalle.Columns.Add("CveVentaDetalle", GetType(Integer)) - DtDatosDetalle.Columns.Add("Consec", GetType(Integer)) - DtDatosDetalle.Columns.Add("ConsecId", GetType(Integer)) - DtDatosDetalle.Columns.Add("CvePS", GetType(Integer)) - DtDatosDetalle.Columns.Add("PS", GetType(String)) - DtDatosDetalle.Columns.Add("CveUM", GetType(Integer)) - DtDatosDetalle.Columns.Add("SerieLote", GetType(String)) - DtDatosDetalle.Columns.Add("FechaCaducidad", GetType(String)) - DtDatosDetalle.Columns.Add("FueTraspaso", GetType(Integer)) - - Dim DtDatosDetalleLote As New DataTable - DtDatosDetalleLote.Columns.Add("CveVentaDetalle", GetType(Integer)) - DtDatosDetalleLote.Columns.Add("Consec", GetType(Integer)) - DtDatosDetalleLote.Columns.Add("ConsecId", GetType(Integer)) - DtDatosDetalleLote.Columns.Add("Cantidad", GetType(Double)) - DtDatosDetalleLote.Columns.Add("CvePS", GetType(Integer)) - DtDatosDetalleLote.Columns.Add("PS", GetType(String)) - DtDatosDetalleLote.Columns.Add("CveUM", GetType(Integer)) - DtDatosDetalleLote.Columns.Add("Lote", GetType(String)) - DtDatosDetalleLote.Columns.Add("Batch", GetType(String)) - DtDatosDetalleLote.Columns.Add("FechaCaducidad", GetType(String)) - DtDatosDetalleLote.Columns.Add("FueTraspaso", GetType(Integer)) - - Dim DtTraspasos As New DataTable - DtTraspasos.Columns.Add("CveAlmacen", GetType(Integer)) - DtTraspasos.Columns.Add("Almacen", GetType(String)) - DtTraspasos.Columns.Add("CveMovimientoSalida", GetType(Integer)) - DtTraspasos.Columns.Add("FolioSalida", GetType(Integer)) - DtTraspasos.Columns.Add("CveMovimientoEntrada", GetType(Integer)) - DtTraspasos.Columns.Add("FolioEntrada", GetType(Integer)) - - Dim ConceptoMovimiento = 18 - Dim CveMovimiento As Integer = 0 - Dim Folio As Integer = 0 - Dim CantidadPendiente As Decimal = 0 - Dim DtDetalle As New DataTable - Dim DtDetalleLote As New DataTable - - CveMovimiento = ObjInventario.AddMovimiento(CveAlmacenDevolucion, ConceptoMovimiento, 1, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, CveVenta, -1, -1, Observaciones:="", Guia:="", CveContrato:=CveContrato, CveAlmacenDestino:=-1) - Folio = ObjInventario.Folio - - 'SALIDA DE ALMACEN - SALIDA POR TRASPASO CUANDO ES REMISION - DEVOLUCION (SI ES TRASPASO Y TIENE CONTRATO NO HACE DEVOLUCIóN) - 'If Not (CveContrato > 0 And CveAlmacenTraspasoDestino > 0) Then - If CveMovimiento > 0 Then - - 'ES EL MOVIMIENTO PRINCIPAL - CantidadPendiente = 0 - For Each Dr As DataRow In DtDatos.Rows - CantidadPendiente = Dr("CantidadGV").ToString.ToDecimal - Dr("CantidadTraspaso").ToString.ToDecimal - If CantidadPendiente > 0 Then - Dim PU As Decimal = 0 - - 'SI FUE POR SERIELOTE - DtDetalle = DtDatosDetalle.FiltraParametros(String.Format("ConsecId = {0} AND FueTraspaso IS NULL", Dr("Consec"))) - DtDetalleLote = DtDatosDetalleLote.FiltraParametros(String.Format("ConsecId = {0} AND FueTraspaso IS NULL", Dr("Consec"))) - If DtDetalle.Rows.Count > 0 Then - For Each Dr1 As DataRow In DtDetalle.Rows - If DtExistencias IsNot Nothing Then - PU = DtExistencias.FiltroPrimeroValor("PU", $"CvePS = {Dr("CvePS")} AND CveUM = {Dr("CveUM").ToString.ToEntero} AND SerieLote = '{Dr1("SerieLote").ToString}'").ToString.ToDecimal - End If - - If Not ObjInventario.AddMovimientoDetalle(CveMovimiento, 1, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, PU, -1, SerieLote:=Dr1("SerieLote").ToString, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al procesar los conceptos con serie. Por favor vuelva a intentar." - Exit For - End If - Next - ElseIf DtDetalleLote.Rows.Count > 0 Then - For Each Dr1 As DataRow In DtDetalleLote.Rows - If DtExistencias IsNot Nothing Then - PU = DtExistencias.FiltroPrimeroValor("PU", $"CvePS = {Dr("CvePS")} AND CveUM = {Dr("CveUM").ToString.ToEntero} AND SerieLote = '{Dr1("SerieLote").ToString}'").ToString.ToDecimal - End If - - If Not ObjInventario.AddMovimientoDetalle(CveMovimiento, Dr1("Cantidad").ToString.ToDouble, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, PU, -1, Lote:=Dr1("Lote").ToString, Batch:=Dr1("Batch").ToString, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al procesar los conceptos con serie. Por favor vuelva a intentar." - Exit For - End If - Next - Else - If DtExistencias IsNot Nothing Then - PU = DtExistencias.FiltroPrimeroValor("PU", $"CvePS = {Dr("CvePS")} AND CveUM = {Dr("CveUM").ToString.ToEntero}").ToString.ToDecimal - End If - - If Not ObjInventario.AddMovimientoDetalle(CveMovimiento, CantidadPendiente, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, PU, -1, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al procesar los conceptos de salida. Por favor vuelva a intentar." - Exit For - End If - End If - - End If - Next - Else - ErrorCancelar = True - End If - - If Not ErrorCancelar Then - Dim DtCostos As DataTable = Nothing - Dim ValorInventario As Decimal = 0 - If ObjInventario.GetMovimientosDetalle(CveMovimiento, UsuarioActual.CveEmpresa) Then - DtCostos = ObjInventario.DtResultados - - Dim tmpCostos As DataTable = DtCostos.FiltraParametros("", "", {"CveClasificacion"}) - Dim IdCtaContableAlmacen As Integer = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContable", $"CveAlmacen = {CveAlmacenDevolucion}").ToEntero - Dim CveCuentaAlmacen As Integer = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCtaContableSIG", $"CveAlmacen = {CveAlmacenDevolucion}").ToEntero - Dim IdCtaContable As Integer = 0 - Dim CveCuenta As Integer = 0 - If tmpCostos.Rows.Count > 0 Then - - - If ObjVentas.GetVenta(CveVenta, UsuarioActual.CveEmpresa) Then - Dim Fecha As Date = Now - Dim CveCliente As Integer = ObjVentas.DtResultados(0)("CveCliente").ToString.ToEntero - Dim ClienteNombre As String = ObjVentas.DtResultados(0)("ClienteNombre").ToString - Dim SerieFolio As String = ObjVentas.DtResultados(0)("SerieFolio").ToString - Dim TotalCosto As Decimal = DtCostos.SUMD("Total").RoundSQL() - Dim TotalCostoAcumulado As Decimal = 0 - Dim cont As Integer = 1 - - Dim CvePrePolizaDev As Integer = ObjConta.AddPrePolizas("Inventario/RecepcionEntrega", 4, TotalCosto, TotalCosto, 1, Fecha, ClienteNombre, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa) - 'Se agrega movimiento separado por la cuenta de ventas (ER) - For Each RowInv As DataRow In tmpCostos.Rows - ValorInventario = DtCostos.SUMD("Total", $"CveClasificacion = {RowInv("CveClasificacion")}").RoundSQL() - TotalCostoAcumulado += ValorInventario - - 'cuando es el último movimiento y hay diferencias en los importes - If cont = DtCostos.Rows.Count AndAlso TotalCosto <> TotalCostoAcumulado Then - ValorInventario = ValorInventario + (TotalCosto - TotalCostoAcumulado) - End If - - 'Concepto = String.Format("{0} - {1}", Row2("Clasificacion").ToString, Row2("SubProyecto").ToString) - IdCtaContable = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaCostos", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero - CveCuenta = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltroPrimeroValor("IdCuentaCostosSIG", $"CveClasificacion = {RowInv("CveClasificacion")}").ToEntero - - If Not ErrorCancelar Then - If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaDev, False, -1 * ValorInventario, SerieFolio, 69, SerieFolio, Fecha, IdCtaContable, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveMovimientoAlmacen:=CveMovimiento, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, ImporteMX:=-1 * ValorInventario, CveCuenta:=CveCuenta, CveClasificacion:=RowInv("CveClasificacion").ToString.ToEntero) Then - ErrorCancelar = True - End If - End If - - cont += 1 - Next - - If Not ObjConta.AddPrePolizasDetalle(CvePrePolizaDev, True, -1 * TotalCosto, SerieFolio, 68, SerieFolio, Fecha, IdCtaContableAlmacen, -1, CveVenta:=CveVenta, CveCliente:=CveCliente, CveMovimientoAlmacen:=CveMovimiento, CveSubProyecto:=DdlSubProyectoDatos.SelectedValue.ToEntero, ImporteMX:=-1 * TotalCosto, CveCuenta:=CveCuentaAlmacen) Then - ErrorCancelar = True - End If - - 'AutoConta - El movimiento 1 es el de Venta - - Dim AutoConta As Boolean = UsuarioActual.Empresa.Funcionalidad(200) = "1" - - If UsuarioActual.CveEmpresa = 119 AndAlso DdlTipoComprobante.SelectedValue = "Ant" Then - AutoConta = False - End If - - If AutoConta And Not ErrorCancelar Then - Dim ObjContPaq = New ClsContPAQi(UsuarioActual.Empresa) - - If IdCtaContable > 0 Then - If Not ObjConta.ContabilizarPrePoliza(CvePrePolizaDev, UsuarioActual.CveUsuario, UsuarioActual.Empresa, ObjConta:=ObjContPaq) Then - Alert("Ocurrio un Error al contabilizar, pongase en contacto con Soporte Técnico") - End If - Else - Alert(String.Format("No se puede contabilizar ya que falta asignación de las cuentas contables"), TipoMensaje.MsgAdvertencia) - End If - - ObjContPaq.Dispose() - End If - - Else - ErrorCancelar = True - MensajeError = "Ocurrió un Error al ingresar las prepolizas" - End If - - End If - End If - End If - - If Not ErrorCancelar Then - If ObjInventario.VentasAlmacenApartadosGet(CveVenta) Then - - Dim DtTempApartados = ObjInventario.DtResultados.FiltraParametros("CveTipoAlmacen = 9", "CveAlmacen") - Dim CveMovimientoSalidaApartado = -1 - Dim CveAlmacenApartado = -1 - Dim CveAlmacenOrigen = CveAlmacenDevolucion - Dim FolioSalida As Integer = 0, FolioEntrada = 0, CveMovimientoSalida = 0, CveMovimientoEntradaApartado = 0 - - For Each Dr As DataRow In DtTempApartados.Rows - - If CveMovimientoSalidaApartado = -1 Or CveAlmacenApartado <> Dr("CveAlmacen").ToString.ToEntero Then - CveMovimientoSalidaApartado = ObjInventario.AddMovimiento(CveAlmacenOrigen, 8, 1, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, CveVenta, -1, -1, Observaciones:="", Guia:="", CveContrato:=CveContrato, CveVendedor:=1, CveCliente:=CveCliente, CveAlmacenDestino:=Dr("CveAlmacen").ToString.ToEntero) - FolioSalida = ObjInventario.Folio - CveAlmacenApartado = Dr("CveAlmacen").ToString.ToEntero - - Dim DrMovto = DtTraspasos.NewRow - DrMovto("Almacen") = Dr("Almacen").ToString.ToEntero - DrMovto("CveAlmacen") = Dr("CveAlmacen").ToString.ToEntero - DrMovto("CveMovimientoSalida") = CveMovimientoSalidaApartado - DrMovto("FolioSalida") = FolioSalida - DtTraspasos.Rows.Add(DrMovto) - End If - - If Not CveMovimientoSalidaApartado > 0 Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al guardar los movimientos de control de apartados" - Exit For - End If - - If Not ObjInventario.AddMovimientoDetalle(CveMovimientoSalidaApartado, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDecimal, Dr("CveAF").ToString.ToEntero, -1, Dr("SerieLote").ToString, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero, Lote:=Dr("Lote").ToString, Batch:=Dr("Batch").ToString) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al guardar los movimientos de control de apartados" - Exit For - End If - Next - - If Not ErrorCancelar Then - For Each Dr1 As DataRow In DtTraspasos.Rows - CveMovimientoSalida = Dr1("CveMovimientoSalida").ToString.ToEntero - - CveMovimientoEntradaApartado = ObjInventario.AddMovimiento(Dr1("CveAlmacen").ToString.ToEntero, 9, 1, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, CveVenta, -1, -1, Observaciones:="", CveAlmacenDestino:=CveAlmacenDevolucion, CveMovimientoRelacionado:=CveMovimientoSalida, Guia:="", CveContrato:=CveContrato, CveVendedor:=-1, CveCliente:=CveCliente) - FolioEntrada = ObjInventario.Folio - - If Not CveMovimientoEntradaApartado > 0 Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al procesar los movimientos de traspaso de apartado. Por favor vuelva a intentar." - Exit For - End If - - Dr1("CveMovimientoEntrada") = CveMovimientoEntradaApartado - Dr1("FolioEntrada") = FolioEntrada - - If ObjInventario.GetMovimientosDetalle(CveMovimientoSalida, UsuarioActual.CveEmpresa) Then - For Each Dr As DataRow In ObjInventario.DtResultados.Rows - If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntradaApartado, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDecimal, Dr("CveAF").ToString.ToEntero, -1, Dr("SerieLote").ToString, CveMovimientoDetalleEntrada:=Dr("CveMovimientoDetalle").ToString.ToEntero, Lote:=Dr("Lote").ToString, Batch:=Dr("Batch").ToString) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al procesar los conceptos de traspaso de apartado. Por favor vuelva a intentar." - Exit For - End If - Next - End If - - If ErrorCancelar Then Exit For - Next - End If - - End If - End If - - 'DEVOLUCION REMISION - REGRESA LAS EXISTENCIAS A ENTREGA POR ADELANTADO SI LA FACTURA VIENE DE REMISION - If Not ErrorCancelar Then - Dim DtMovtosDev As New DataTable - Dim CveAlmacenTraspasoDestinoDevRem = -1 - - Dim CveVentaDetalleRem = -1 - Dim CantidadDevolver As Decimal = 0 - Dim CantidadRem As Decimal = 0 - Dim CveMovimientoSalidaDevRem As Integer = 0 - Dim FolioMovimientoSalidaDevRem As Integer = 0 - Dim CveMovimientoEntradaDevRem As Integer = 0 - Dim FolioMovimientoEntradaDevRem As Integer = 0 - - 'CARGA REMISIONES DE LA VENTA DEVUELTA - If ObjInventario.GetDevolucionRemisionesFacturadas(CveVenta) Then - DtDevRem = ObjInventario.DtResultados.FiltraParametros("CantidadAlmacen > 0") - Else - ErrorCancelar = True - End If - - 'CARGA CONCEPTOS DEVUELTOS EN LA VENTA - If ObjInventario.GetMovimientosDetalle(CveMovimiento, UsuarioActual.CveEmpresa) Then - DtMovtosDev = ObjInventario.DtResultados - Else - ErrorCancelar = True - End If - - If Not ErrorCancelar Then - If DtDevRem.Rows.Count > 0 And DtMovtosDev.Rows.Count > 0 Then - - For Each DrMovtos As DataRow In DtDevRem.FiltraParametros("", "CveRem", {"CveRem", "CveAlmacenTraspasoDestino"}).Rows - - 'CHECO SI NO SE VA A CANCELAR - Dim SeCancela As Boolean = False - If ChkCanRem.Checked Then - For Each Gvr As GridViewRow In GvCancelarRemisiones.Rows - If Gvr.FCCheckBox("ChkCancelarRemision").Checked AndAlso DrMovtos("CveRem").ToString.ToEntero = Gvr.DataKey("CveVenta").ToString.ToEntero Then - SeCancela = True - Exit For - End If - Next - End If - - If Not SeCancela Then - - CveAlmacenTraspasoDestinoDevRem = DrMovtos("CveAlmacenTraspasoDestino").ToString.ToEntero - If Not CveAlmacenTraspasoDestinoDevRem > 0 Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al obtener el almacén de devolucion de remisión." - Exit For - End If - - 'SALIDA GENERAL - CveMovimientoSalidaDevRem = ObjInventario.AddMovimiento(CveAlmacenDevolucion, 8, 1, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, DrMovtos("CveRem").ToString.ToEntero, -1, -1, Observaciones:="", Guia:="", CveContrato:=CveContrato, CveMovimientoRelacionado:=CveMovimiento, CveAlmacenDestino:=CveAlmacenTraspasoDestinoDevRem) - FolioMovimientoSalidaDevRem = ObjInventario.Folio - - 'ENTRADA ADELANTADO - CveMovimientoEntradaDevRem = ObjInventario.AddMovimiento(CveAlmacenTraspasoDestinoDevRem, 9, 1, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, DrMovtos("CveRem").ToString.ToEntero, -1, -1, Observaciones:="", Guia:="", CveContrato:=CveContrato, CveMovimientoRelacionado:=CveMovimientoSalidaDevRem, CveAlmacenDestino:=CveAlmacenDevolucion) - FolioMovimientoEntradaDevRem = ObjInventario.Folio - - If Not (CveMovimientoSalidaDevRem > 0 And CveMovimientoEntradaDevRem > 0) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al generar los movimientos de devolución a remisión." - Exit For - End If - - - 'SALIDA POR TRAPASO DE GENERAL - For Each DrRem As DataRow In DtDevRem.FiltraParametros($"CveRem = {DrMovtos("CveRem")}").Rows - CveVentaDetalleRem = DrRem("CveVentaDetalleRem").ToString.ToEntero - CantidadRem = DrRem("CantidadFacturada").ToString.ToDecimal - 'CantidadDevolver = DtMovtosDev.FiltroPrimeroValor("Cantidad", $"CveVentaDetalle = {DrRem("CveVentaDetalle").ToString.ToEntero}").ToDouble - 'If (Dr("Cantidad").ToString.ToDouble > CantidadRem, CantidadRem, Dr("Cantidad").ToString.ToDouble) Then - - If Not CveVentaDetalleRem > 0 Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al obtener la relación de la venta con la remisión." - Exit For - End If - - For Each Dr As DataRow In DtMovtosDev.FiltraParametros($"CveVentaDetalle = {DrRem("CveVentaDetalle").ToString.ToEntero}").Rows - If Not ObjInventario.AddMovimientoDetalle(CveMovimientoSalidaDevRem, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDouble, Dr("CveAF").ToString.ToEntero, -1, Dr("SerieLote").ToString, CveVentaDetalle:=CveVentaDetalleRem, Lote:=Dr("Lote").ToString, Batch:=Dr("Batch").ToString) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al guardar los movimientos de salida de traspaso de devolucion de remisión." - Exit For - End If - Next - - If ErrorCancelar Then - Exit For - End If - Next - - If ErrorCancelar Then - Exit For - End If - - 'ENTRADA POR TRAPASO A ENTREGA POR ADELANTADO - If ObjInventario.GetMovimientosDetalle(CveMovimientoSalidaDevRem, UsuarioActual.CveEmpresa) Then - For Each Dr As DataRow In ObjInventario.DtResultados.Rows - If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntradaDevRem, Dr("Cantidad").ToString.ToDecimal, Dr("CveUM").ToString.ToEntero, Dr("CvePS").ToString.ToEntero, Dr("PU").ToString.ToDecimal, Dr("CveAF").ToString.ToEntero, -1, Dr("SerieLote").ToString, CveVentaDetalle:=Dr("CveVentaDetalle").ToString.ToEntero, Lote:=Dr("Lote").ToString, Batch:=Dr("Batch").ToString) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al guardar los movimientos de entrada de traspaso de devolucion de remisión." - Exit For - End If - Next - - If ErrorCancelar Then - Exit For - End If - - Else - ErrorCancelar = True - MensajeError = "Ocurrió un error al obtener los detalles de la devolución de almacén" - Exit For - End If - - - If Not ObjVentas.UpdateVentasDevolucionAlmacen(0, DrMovtos("CveRem").ToString.ToEntero) Then - MensajeError = "Ocurrió un error al hacer la devolucion hacia la remision. Por favor vuelva a intentar." - ErrorCancelar = True - Exit For - End If - - End If - - Next - End If - Else - MensajeError = "Ocurrió un error al hacer la devolucion a remisión. Por favor vuelva a intentar." - ErrorCancelar = True - End If - - End If - - If Not ErrorCancelar Then - 'QUEMA DEVOLUCION | QUEMA = LA QUITA DE PENDIENTE POR RECIBIR (DEVOLVER) - If Not ErrorCancelar Then - If Not ObjVentas.UpdateVentasDevolucionAlmacen(2, CveVenta) Then - MensajeError = "Ocurrió un error al hacer la devolucion. Por favor vuelva a intentar." - ErrorCancelar = True - End If - End If - - 'AGREGA BITACORA A VENTA - If Not ErrorCancelar Then - Dim MensajeBitacora = "Devuelta" - If Not ObjEventos.AddEventoBitacora(String.Format("Venta {2} en Folio: {1}", CveMovimiento, Folio, MensajeBitacora), "-1", UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveVenta:=CveVenta) Then - ErrorCancelar = True - End If - End If - End If - - End If - End If - - 'DESVINCULA REMISIONES PREDECESORAS - If Not EsRefacturacion Then - If Not ErrorCancelar Then - If DdlTipoComprobante.SelectedValue.Contiene("Ing", "Ant") Then - If Not ChkCanRem.Checked Then - If Not ObjVentas.LiberarRemisionesFacturadas(CveVenta) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al desvincular las remisiones." - End If - Else - For Each Gvr As GridViewRow In GvCancelarRemisiones.Rows - If Not Gvr.FCCheckBox("ChkCancelarRemision").Checked Then - If Not ObjVentas.LiberarRemisionesFacturadas(CveVenta, Gvr.DataKey("CveVenta").ToEntero) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al desvincular las remisiones." - End If - End If - Next - End If - End If - End If - End If - - - 'ACTUALIZA ESTATUS - If Not ErrorCancelar Then - Select Case DdlTipoComprobante.SelectedValue - Case "Rem" - CveEstatus = 12 - Case "Com" - CveEstatus = 9 - End Select - '0 Sin Refacturacion, 1 Refacturacion en Proceso, 3. Refacturación en proceso sin aceptación - Me.CveEstatusRefacturacion = 0 If EsRefacturacion Then - If CveEstatus = 5 Then - CveEstatusRefacturacion = 3 ' refacturación en proceso sin autorización de cancelación - Else - CveEstatusRefacturacion = 1 ' refacturación en proceso con autorización de cancelación - End If - End If - - - If Not ObjVentas.UpdateEstatusFactura(CveEstatus, FolioFiscal, CancelacionAcuse, CancelacionFecha, CveVenta, IDPoliza, CvePAC:=CvePACCancelacion, CveEstatusRefacturacion:=CveEstatusRefacturacion, - CveUsuarioCambiaEstatus:=UsuarioActual.CveUsuario, FechaCambioEstatus:=Now.ToString("yyyy-MM-dd hh:mm:ss.mmm")) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al guardar el estatus de cancelación." - End If - - If ChkCanRem.Checked Then - For Each Gvr As GridViewRow In GvCancelarRemisiones.Rows - If Gvr.FCCheckBox("ChkCancelarRemision").Checked Then - If Not SeCancelaRemisionProceso Then - If Not ObjVentas.UpdateEstatusFactura(12, "", "", CancelacionFecha, Gvr.DataKey("CveVenta").ToEntero) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al guardar el estatus de cancelación de la remisión." - End If - Else - If Not ObjVentas.AddRemisionesXCancelar(CveVenta, Gvr.DataKey("CveVenta").ToEntero) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al guardar la remisión x cancelar." - End If - End If - End If - Next - End If - If SeCancelaRemisionProceso Then - If Not ObjVentas.UpdateCancelaRemision(CveVenta, SeCancelaRemisionProceso) Then - ErrorCancelar = True - MensajeError = "Ocurrió un error al actualizar que la remision sea cancelable." - End If - End If - End If - - If Not ErrorCancelar Then - ObjVentas.Commit() - - If CveEstatus = 5 Then - Dim MensajeAlert As New StringBuilder - MensajeAlert.Append("El Documento se canceló correctamente.") - MensajeAlert.Append($"
Imprimir Acuse") - MensajeAlert.Append("

¿Desea enviar el Acuse de Cancelación al Cliente?") - Alert(MensajeAlert.ToString, TipoMensaje.MsgConfirmacion, JSBtnAceptar:="BtnEnviarMailCancelacion();", TextoConfirmacion:="    Si    ", TextoCancelacion:="    No    ") - + resp = ObjFactura.CancelarPorRefacturacion() Else - If Not EsRefacturacion Then - Alert("El documento se canceló exitosamente.", TipoMensaje.MsgInformacion, JSBtnAceptar:="BtnRefrescarPagina();") - Else - Response.Redirect($"/Ventas/RepCancelacionesPorRespuesta.aspx?CveVenta={Me.CveVenta}") + Dim ListaRemisionesCancelar As New List(Of Integer) + If ChkCanRem.Checked Then + For Each Gvr As GridViewRow In GvCancelarRemisiones.Rows + If Gvr.FCCheckBox("ChkCancelarRemision").Checked Then + ListaRemisionesCancelar.Add(Gvr.DataKey("CveVenta").ToEntero) + End If + Next End If + + If ChkDevAlm.Checked Then + ObjFactura.CveAlmacenDevolucion = CveAlmacenDevolucion + End If + + resp = ObjFactura.CancelarFactura(ChkDevAlm.Checked, ListaRemisionesCancelar) End If - Me.CveEstatus = CveEstatus - If CveEstatus = 5 Then LbCancelarDocumento.Enabled = False - If ObjAC IsNot Nothing Then ObjAC.Commit() - Else - Alert(MensajeError, TipoMensaje.MsgError) - ObjVentas.RollBack() - If ObjAC IsNot Nothing Then ObjAC.RollBack() - End If + If resp.CveEstatus = 5 Then + Alert(resp.Mensaje, resp.TipoMensaje, JSBtnAceptar:="BtnEnviarMailCancelacion();", TextoConfirmacion:="    Si    ", TextoCancelacion:="    No    ") + Else + Alert(resp.Mensaje, resp.TipoMensaje, JSBtnAceptar:="BtnRefrescarPagina();") + End If - ObjVentas.Dispose() - ObjBancos.Dispose() - ObjInventario.Dispose() - ObjContrato.Dispose() - ObjConta.Dispose() - If ObjAC IsNot Nothing Then ObjAC.Dispose() + ObjFactura.CveAlmacen = -1 + Else + Alert("Ocurrió un error al generar la cancelación", TipoMensaje.MsgError) + End If UpEstatus.Update()