Option Explicit On Option Strict On Imports System.Data Imports System.IO Imports System.IO.Compression Imports System.Net.Http Imports System.Windows.Forms Imports ADSTimbrado Imports DocumentFormat.OpenXml.Spreadsheet Imports Extensiones Imports GemBox.Spreadsheet Imports iText.Barcodes.Dmcode Partial Class Ventas_FacturacionAcarreos Inherits ClsPaginas Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then txtFechaI.Text = NowADS.FirstDayOfMonth().ToShortDateString CargaDatos() End If If IfNull(Request("OP"), "").ToString = "File" Then DescargaArchivoDirecto(Request("File").ToString) End If End Sub Private Sub CargaDatos() Dim CveCliente As Integer = -1 If DdlClientes.SelectedValue.ToEntero() > 0 Then CveCliente = DdlClientes.SelectedValue.ToEntero() End If Using ObjVentas As New ClsVentas If ObjVentas.GetFacturacionAcarreos(-1, CveCliente, -1, DdlEstatus.SelectedValue.ToEntero(), txtFechaI.Text.ToDate, UsuarioActual.CveEmpresa) Then GvDatos.DataSource = ObjVentas.DtResultados End If End Using GvDatos.DataBind() UPDatos.Update() End Sub #Region "C A R G A R E X C E L " Private Sub BtnDescargarFormato_Click(sender As Object, e As EventArgs) Handles BtnDescargarFormato.Click Dim DtExcel As DataTable = New DataTable("Facturas") With DtExcel.Columns .Add(New DataColumn("Sucursal", GetType(String))) .Add(New DataColumn("RFC", GetType(String))) .Add(New DataColumn("Cantidad", GetType(Decimal))) .Add(New DataColumn("Folio", GetType(String))) .Add(New DataColumn("ProductoGeneral", GetType(String))) .Add(New DataColumn("Origen", GetType(String))) .Add(New DataColumn("Destino", GetType(String))) .Add(New DataColumn("FechaSalida", GetType(DateTime))) .Add(New DataColumn("FechaLlegada", GetType(DateTime))) .Add(New DataColumn("Unidad", GetType(String))) '.Add(New DataColumn("Chofer", GetType(String))) '.Add(New DataColumn("Remolque1", GetType(String))) '.Add(New DataColumn("Remolque2", GetType(String))) .Add(New DataColumn("Distancia", GetType(Decimal))) .Add(New DataColumn("HojaServicio", GetType(String))) End With SpreadsheetInfo.SetLicense(ModExtensiones.SerialGemBoxSpreadsheet) Dim FileExcel As New ExcelFile() Dim worksheet As ExcelWorksheet = FileExcel.Worksheets.Add(DtExcel.TableName) worksheet.InsertDataTable(DtExcel, New InsertDataTableOptions() With { .ColumnHeaders = True, .StartRow = 0, .StartColumn = 0 }) worksheet.Rows(0).Style.FillPattern.SetPattern(FillPatternStyle.Solid, SpreadsheetColor.FromArgb(75, 119, 190), SpreadsheetColor.FromArgb(255, 255, 255)) worksheet.Rows(0).Style.Font.Color = SpreadsheetColor.FromArgb(255, 255, 255) Dim columnCount As Integer = worksheet.CalculateMaxUsedColumns() For i As Integer = 0 To columnCount worksheet.Columns(i).AutoFit(1, worksheet.Rows(0), worksheet.Rows(worksheet.Rows.Count - 1)) Next FileExcel.Save(Response, "FormatoFacturas.xlsx", SaveOptions.XlsxDefault) End Sub Private Sub BtnCargaExcel_Click(sender As Object, e As EventArgs) Handles BtnCargaExcel.Click If TxtExcel.getfiles().Archivos.Count > 0 Then Dim file As Archivo = TxtExcel.getfiles().Archivos(0) Dim Directorio As String = AppDomain.CurrentDomain.BaseDirectory & file.path CargarArchivo(Directorio, file.filename) Else Alert("No existe el archivo. Favor de subir un archivo excel a la plataforma.", TipoMensaje.MsgError) End If End Sub Private Sub CargarArchivo(Ruta As String, FileName As String) SpreadsheetInfo.SetLicense(ModExtensiones.SerialGemBoxSpreadsheet) Dim dt As DataTable = Nothing Dim ErrorArchivo As Boolean = False Try dt = ReadExcelFile(Ruta + FileName, True) Catch ex As Exception ErrorArchivo = True OnError("Ocurrio un error al leer el archivo
" & ex.Message, ex) End Try If Not ErrorArchivo AndAlso dt IsNot Nothing Then dt.TableName = "Datos" Dim MsgFacturacionAcarreos As New StringBuilder() Dim RowsCargados As Integer = 0 Dim RowsNoCargados As Integer = 0 Dim ObjVentas As New ClsVentas ObjVentas.IniciaTransacSQL() Dim TieneError As Boolean = False Try If dt.Rows.Count = 0 Then TieneError = True MsgFacturacionAcarreos.Append("No hay datos para procesar") RowsNoCargados += 1 End If For Each row As DataRow In dt.Rows Dim FechaSalida As DateTime = MinFecha Dim FechaLlegada As DateTime = MinFecha If row("FechaSalida").ToString().ToDateTime() > FechaSalida Then FechaSalida = row("FechaSalida").ToString().ToDateTime().AddHours(9) End If If row("FechaLlegada").ToString().ToDateTime() > FechaLlegada Then FechaLlegada = row("FechaLlegada").ToString().ToDateTime().AddHours(14) End If Dim Folio, FolioAdicional, Remolque1, Remolque2 As String Dim dtu As DataRow = GlobalDTInvCamiones(UsuarioActual.CveEmpresa).FiltroPrimero($"Placa = '{row("Unidad")}'") If dtu IsNot Nothing Then 'Chofer = dtu("Chofer").ToString 'Configuracion = dtu("Configuracion").ToString Remolque1 = dtu("Remolque1").ToString Remolque2 = dtu("Remolque2").ToString Else Folio = "" : FolioAdicional = "" : Remolque1 = "" : Remolque2 = "" End If 'temporal Folio = row("Folio").ToString FolioAdicional = row("HojaServicio").ToString Dim msg As String = ObjVentas.AddFacturacionAcarreos(row("Sucursal").ToString(), row("RFC").ToString(), row("Cantidad").ToString().ToDecimal(), row("ProductoGeneral").ToString(), row("Origen").ToString(), row("Destino").ToString(), FechaSalida, FechaLlegada, row("Unidad").ToString(), Folio, FolioAdicional, Remolque1, Remolque2, row("Distancia").ToString().ToDecimal(), UsuarioActual.CveEmpresa) If msg = "Correcto" Then RowsCargados += 1 Else TieneError = True MsgFacturacionAcarreos.AppendFormat("Ocurrió un error al procesar la fila: {0}
{1}", row("NoExcel"), msg) RowsNoCargados += 1 Exit For End If Next Catch ex As Exception OnError("Ocurrió un error al cargar los datos.", ex) Finally Dim MensajeFinal As New StringBuilder() If RowsNoCargados = 0 AndAlso RowsCargados > 0 Then MensajeFinal.Append("Los datos se cargaron correctamente.

") End If If RowsNoCargados > 0 Then MensajeFinal.Append(MsgFacturacionAcarreos.ToString()) End If If TieneError Then ObjVentas.RollBack() Alert(MensajeFinal.ToString(), TipoMensaje.MsgError) Else ObjVentas.Commit() Alert(MensajeFinal.ToString()) End If ObjVentas.Dispose() End Try CargaDatos() End If End Sub #End Region Protected Sub GvDatos_RowDataBound(sender As Object, e As GridViewRowEventArgs) If e.Row.RowType = DataControlRowType.DataRow Then If e.Row.DBCampo("SerieFolio").Length > 0 Then e.Row.FCCheckBox("chk").Visible = False End If End If End Sub Protected Sub LnkFacturarSeleccionados_Click(sender As Object, e As EventArgs) If GvDatos.Rows.Cast(Of GridViewRow)().Count(Function(gvr) gvr.FCCheckBox("chk").Checked) <= 0 Then Alert($"Debe seleccionar un acarreo para facturar", TipoMensaje.MsgAdvertencia) Exit Sub End If Dim msg As New StringBuilder() Dim msgDescarga As New StringBuilder() Dim NumFacturasGeneradas As Integer = 0 Dim NumFacturasTimbradas As Integer = 0 Dim Archivo As String = "" Dim NombreArchivo As String = String.Format("Acarreos{0}{1}.zip", NowADS().ToString("yyyyMMddhhmmss"), UsuarioActual.CveUsuario.ToString) Dim ArchivoDestino As String = String.Format("{0}Temp/{1}", UsuarioActual.Empresa.Ruta, NombreArchivo) Dim HuboInexistentes As Boolean = False Dim archiveZip As ZipArchive = ZipFile.Open(ArchivoDestino, ZipArchiveMode.Create) Dim dtt As New DataTable dtt.Columns.Add("Cantidad", GetType(String)) dtt.Columns.Add("Boleta", GetType(String)) dtt.Columns.Add("HojaServicio", GetType(String)) dtt.Columns.Add("SerieFolio", GetType(String)) For Each GvRow As GridViewRow In GvDatos.Rows If GvRow.RowType = DataControlRowType.DataRow Then If GvRow.FCCheckBox("chk").Checked Then Dim CveCliente As Integer = GvRow.DataKey("CveCliente").ToEntero() Dim CveSubProyecto As Integer = GvRow.DataKey("CveSubProyecto").ToEntero() Dim CveMoneda As Integer = 1 Dim CvePS As Integer = GvRow.DataKey("CvePSGeneral").ToEntero() Dim Cantidad As Decimal = GvRow.DataKey("Cantidad").ToDecimal() Dim PU As Decimal = -1 Dim Descuento As Decimal = 0 Dim Obs As String = $"DE ACARREO DE MINERAL DE HIERRO AQUILA SINALOA, MÉXICO, FOLIO: { GvRow.DataKey("Folio")} HOJA DE SERVICIO: {GvRow.DataKey("FolioAdicional")}" Dim CvePSMercancia As Integer = GvRow.DataKey("CvePSRelacionado").ToEntero() Dim ObjFactura As Modelos.Factura = Modelos.Factura.CrearVentaNueva(UsuarioActual, CveSubProyecto, CveCliente, CveMoneda) ObjFactura.EmitirCartaPorte = True ObjFactura.CveFacturacionAcarreo = GvRow.DataKey("CveFacturacionAcarreo").ToEntero() ObjFactura.AgregarPS(CvePS, Cantidad, PU, Descuento, Obs) ObjFactura.DtMercancias = CreaDTMercancias(CvePSMercancia, Cantidad) ObjFactura.CalculaTotales() ObjFactura.PreparaTimbre() Dim resp As Modelos.Factura.MMensajeFactura = ObjFactura.EmitirFactura(Timbrar:=True, Modulo:="FacturacionAcarreos") For Each m As String In resp.Mensajes msg.AppendFormat("{0}
", m) Next If Not resp.TieneError Then If resp.SerieFolio <> String.Empty Then msgDescarga.AppendFormat("{0},", resp.SerieFolio) Dim drr As DataRow = dtt.NewRow drr("Cantidad") = GvRow.DataKey("Cantidad") drr("Boleta") = GvRow.DataKey("Folio") drr("HojaServicio") = GvRow.DataKey("FolioAdicional") drr("SerieFolio") = resp.SerieFolio dtt.Rows.Add(drr) DescargarFactura(resp.CveVenta, UsuarioActual.CveEmpresa, UsuarioActual.CveUsuario) Archivo = String.Format("{0}PDF/ING/{1}.pdf", UsuarioActual.Empresa.Ruta.Replace("\", "/"), resp.SerieFolio) If File.Exists(Archivo) Then archiveZip.CreateEntryFromFile(Archivo, resp.SerieFolio & ".pdf") End If Archivo = String.Format("{0}XML/ING/{1}.xml", UsuarioActual.Empresa.Ruta.Replace("\", "/"), resp.SerieFolio) If File.Exists(Archivo) Then archiveZip.CreateEntryFromFile(Archivo, resp.SerieFolio & ".xml") End If End If End If If resp.CveVenta > 0 AndAlso Not resp.TieneError Then NumFacturasGeneradas += 1 If resp.SeTimbro Then NumFacturasTimbradas += 1 End If End If End If End If Next archiveZip.Dispose() If NumFacturasGeneradas > 0 Then Dim stt As String = $"Se generaron {NumFacturasGeneradas} y se timbraron {NumFacturasTimbradas} facturas.
" Dim nombreexcel As String = "AcarreosListado.xlsx" Dim rutaexcel As String = UsuarioActual.Empresa.Ruta & "\Temp\" & nombreexcel GemBox.Spreadsheet.SpreadsheetInfo.SetLicense(ModExtensiones.SerialGemBoxSpreadsheet) Dim workbook As New ExcelFile() Dim worksheet As ExcelWorksheet = workbook.Worksheets.Add("Acarreos") worksheet.InsertDataTable(dtt, New InsertDataTableOptions() With {.ColumnHeaders = True}) workbook.Save(rutaexcel) If msgDescarga.Length > 0 Then stt += String.Format("Descarga xml/pdf", NombreArchivo) End If stt += String.Format("
Descarga excel", nombreexcel) Alert(stt, TipoMensaje.MsgInformacion) Else Alert($"No se pudieron generar facturas.
" + msg.ToString(), TipoMensaje.MsgError) End If CargaDatos() End Sub Protected Sub LnkEliminarSeleccionados_Click(sender As Object, e As EventArgs) If GvDatos.Rows.Cast(Of GridViewRow)().Count(Function(gvr) gvr.FCCheckBox("chk").Checked) <= 0 Then Alert($"Debe seleccionar un acarreo para eliminar", TipoMensaje.MsgAdvertencia) Exit Sub End If Dim msg As New StringBuilder() Dim TieneError As Boolean = False Dim ObjVentas As New ClsVentas ObjVentas.IniciaTransacSQL() Try For Each GvRow As GridViewRow In GvDatos.Rows If GvRow.RowType = DataControlRowType.DataRow Then If GvRow.FCCheckBox("chk").Checked Then If Not ObjVentas.RemoveFacturacionAcarreo(GvRow.DataKey("CveFacturacionAcarreo").ToEntero(), UsuarioActual.CveEmpresa) Then TieneError = True Exit For End If End If End If Next Catch ex As Exception TieneError = True End Try If TieneError Then ObjVentas.RollBack() Alert("Ocurrió un error al eliminar los registros.", TipoMensaje.MsgError) Else ObjVentas.Commit() Alert("Los registros se eliminaron correctamente.", TipoMensaje.MsgInformacion) End If ObjVentas.Dispose() CargaDatos() End Sub Private Function CreaDTMercancias(CvePS As Integer, Cantidad As Decimal) As DataTable Dim DtMercancias As New DataTable() DtMercancias.Columns.Add(New DataColumn("Consec", GetType(Integer))) DtMercancias.Columns.Add(New DataColumn("Cantidad", GetType(Decimal))) DtMercancias.Columns.Add(New DataColumn("CvePS", GetType(Integer))) DtMercancias.Columns.Add(New DataColumn("CveUnidadMedida", GetType(Integer))) DtMercancias.Columns.Add(New DataColumn("CodigoPS", GetType(String))) Dim DrPS As DataRow = GlobalDTPSSimplificado(CveEmpresa:=UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("") If DrPS Is Nothing Then Alert("No se encontró la mercancía", TipoMensaje.MsgAdvertencia) Return Nothing End If Dim NewRow As DataRow = DtMercancias.NewRow NewRow("Consec") = DtMercancias.MAX("Consec").ToEntero() + 1 NewRow("Cantidad") = Cantidad NewRow("CvePS") = DrPS("CvePS") NewRow("CveUnidadMedida") = DrPS("CveUnidadMedida") NewRow("CodigoPS") = DrPS("PSCodigo") DtMercancias.Rows.Add(NewRow) Return DtMercancias End Function Protected Sub BtnConsultar_Click(sender As Object, e As EventArgs) CargaDatos() End Sub Private Sub ImgExcel_Click(sender As Object, e As EventArgs) Handles ImgExcel.Click GvDatos.Columns(0).Visible = False GvDatos.ExportToExcel("Acarreos_" & NowADS().ToShortDateString & ".xls") GvDatos.Columns(0).Visible = True End Sub Private Function DescargarFactura(CveVenta As Integer, CveEmpresa As Integer, CveUsuarioCreo As Integer, Optional GetBytes As Boolean = True, Optional Regenerar As Boolean = False, Optional strURLHOST As String = "") As Byte() If String.IsNullOrEmpty(strURLHOST) Then strURLHOST = String.Format("{0}://{1}:{2}", HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Host, HttpContext.Current.Request.Url.Port) End If Dim Url As New Uri(String.Format("{0}/Compras/PopUpVerFactura.aspx?P={1}", strURLHOST, Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1&GUARDAR=1®ENERAR={1}", CveVenta, If(Regenerar, "1", "0"))))) Dim File As Byte() = Nothing Try Using httpClient As New HttpClient() httpClient.Timeout = New TimeSpan(0, 2, 0) Using request As New HttpRequestMessage(HttpMethod.Get, Url) request.Headers.Add("ADSToken", Encripta(String.Format("CVEEMPRESA={0}&TICKS={1}&CveUsuario={2}", CveEmpresa, DateTime.UtcNow.Ticks, CveUsuarioCreo))) Dim response As HttpResponseMessage = httpClient.SendAsync(request).Result If GetBytes AndAlso 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 DescargaArchivoDirecto(NombreArchivo As String) If NombreArchivo <> "" Then NombreArchivo = String.Format("{0}Temp\{1}", UsuarioActual.Empresa.Ruta, NombreArchivo) Dim Archivo As New System.IO.FileInfo(NombreArchivo) If Archivo.Exists Then HttpContext.Current.Response.Clear() HttpContext.Current.Response.ClearContent() HttpContext.Current.Response.ContentType = "application/zip" HttpContext.Current.Response.AppendHeader("Content-disposition", String.Format("attachment; filename={0}", Archivo.Name)) HttpContext.Current.Response.TransmitFile(NombreArchivo) HttpContext.Current.Response.Flush() HttpContext.Current.Response.End() End If Archivo = Nothing End If End Sub End Class