Files
SIG/Ventas/CatPS.aspx.vb

472 lines
20 KiB
VB.net

Option Explicit On
Option Strict On
Imports System.Data
Imports Extensiones
Imports GemBox.Spreadsheet
Partial Class CatPS
Inherits ClsPaginas
Private Property DtDatos As DataTable
Get
DtDatos = DirectCast(ViewState("DtDatos"), DataTable)
End Get
Set(ByVal value As DataTable)
ViewState("DtDatos") = value
End Set
End Property
Private Property AplicaVenta As Boolean
Get
AplicaVenta = DirectCast(ViewState("AplicaVenta"), Boolean)
End Get
Set(ByVal value As Boolean)
ViewState("AplicaVenta") = value
End Set
End Property
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
AplicaVenta = False
ViewState("Orden") = ""
CargaClasificaciones()
CargaGvBitacora()
If UsuarioActual.Empresa.Funcionalidad(132) = "1" Then
DivCBarras1.Visible = True
DivCBarras2.Visible = True
TxtCodigoBarras.Focus()
End If
If UsuarioActual.TienePermisoProceso(122) Then
LBAgregarPS.Visible = False
End If
If UsuarioActual.CveEmpresa = 119 Then
DdlEstado.SelectedValue = "-1"
End If
If UsuarioActual.Empresa.Funcionalidad(563) <> "" AndAlso Not UsuarioActual.TienePermisoProceso(122) Then
LnkExcelPSAdicional.Visible = True
End If
End If
End Sub
Public Sub CargaClasificaciones()
Ddlclasificacion.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa).FiltraParametros(String.Format(" (UsoClasificacion = {0} OR {0} = -1)", DdlTipoClasificacion.SelectedValue))
Ddlclasificacion.DataBind()
Ddlclasificacion.Items.Insert(0, New ListItem("Todos", "-1"))
DdlMarcas.DataSource = GlobalDTGralMarcas(UsuarioActual.CveEmpresa)
DdlMarcas.DataBind()
DdlMarcas.Items.Insert(0, New ListItem("Todos", "-1"))
End Sub
Public Sub CargaDatos()
Dim Codigo As String = ""
Dim Nombre As String = ""
Dim CodigoBarras As String = ""
If TxtCodigo.Text.Trim = "" Then Codigo = "-1" Else Codigo = TxtCodigo.Text.ToUpper.Trim
If TxtCodigoBarras.Text.Trim = "" Then CodigoBarras = "-1" Else CodigoBarras = TxtCodigoBarras.Text.Trim
If TxtNombre.Text.Trim = "" Then Nombre = "-1" Else Nombre = TxtNombre.Text.ToUpper.Trim
Dim ObjPS As New ClsProductosServicios
If ObjPS.GetPSLite(Ddlclasificacion.SelectedValue.ToEntero, UsuarioActual.Empresa.CveEmpresa, Codigo, CodigoBarras, Nombre,
pAplicaParaVenta:=DdlAplicaVenta.SelectedValue.ToEntero,
pEstado:=DdlEstado.SelectedValue.ToEntero,
CveTipoPS:=DdlCveTipoPS.SelectedValue.ToEntero,
UsoClasificacion:=DdlTipoClasificacion.SelectedValue.ToEntero,
CveMarca:=DdlMarcas.SelectedValue.ToEntero) Then
DtDatos = ObjPS.DtResultados
GvDatos.DataSource = DtDatos
Else
DtDatos = Nothing
'Me.GvDatos.DataSource = Nothing
End If
ObjPS.Dispose()
GvDatos.DataBind()
GvDatos.UseAccessibleHeader = True
End Sub
Protected Sub BtnFiltrar_Click(sender As Object, e As EventArgs)
CargaDatos()
OrdenaDatos()
UPDatos.Update()
End Sub
Protected Sub DdlTipoClasificacion_SelectedIndexChanged(sender As Object, e As EventArgs)
CargaClasificaciones()
End Sub
#Region "G V D A T O S"
Protected Sub GvDatos_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvDatos.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.DBCampo("Estado") = "Activo" Then
e.Row.FCLabel("LblEstado").CssClass = "label label-success"
Else
e.Row.FCLabel("LblEstado").CssClass = "label label-danger"
End If
End If
End Sub
#End Region
#Region "P E R S O N A L I Z A R G V"
Private Sub BtnPersonalizar_Click(sender As Object, e As EventArgs) Handles BtnPersonalizar.Click
If ChkAplicaVenta.Checked Then
GvDatos.Columns(6).Visible = True
AplicaVenta = True
Else
GvDatos.Columns(6).Visible = False
AplicaVenta = False
End If
GvDatos.Columns(10).Visible = ChkProductosServiciosSAT.Checked
GvDatos.Columns(11).Visible = ChkClasificacion2.Checked
GvDatos.Columns(12).Visible = ChkMarca.Checked
GvDatos.Columns(13).Visible = ChkVentaMinima.Checked
GvDatos.Columns(14).Visible = ChkCodigoBarras.Checked
GvDatos.Columns(15).Visible = ChkNumParte.Checked
GvDatos.Columns(16).Visible = ChkCompuesto.Checked
GvDatos.Columns(17).Visible = ChkRSCO.Checked
If ChkAplicaVenta.Checked OrElse
ChkProductosServiciosSAT.Checked OrElse
ChkAplicaVenta.Checked OrElse
ChkClasificacion2.Checked OrElse
ChkMarca.Checked OrElse
ChkVentaMinima.Checked OrElse
ChkCodigoBarras.Checked OrElse
ChkCompuesto.Checked OrElse
ChkRSCO.Checked Then
LBExcelPersonalizado.Visible = True
End If
CargaDatos()
OrdenaDatos()
UPDatos.Update()
UppExcelPers.Update()
End Sub
#End Region
#Region "O R D E N A M I E N T O"
Private Sub OrdenaDatos()
If (GvDatos.Rows.Count > 0) Then
GvDatos.UseAccessibleHeader = True
GvDatos.HeaderRow.TableSection = TableRowSection.TableHeader
RegistraScript("OrdenarGV();")
'$('#GvD').DataTable({paging:false, 'scrollY':'300px', 'scrollCollapse': true, searching:false, info:false });
End If
End Sub
'Protected Sub LbOrden_Click(ByVal sender As Object, ByVal e As EventArgs)
' Dim Orden As String = ""
' Dim Campo As String = ""
' Dim Literal As Literal = Nothing
' Const OrdenInicial As String = ""
' Dim Arg(2) As String
' Arg = CType(sender, LinkButton).CommandArgument().ToString.Split(";"c)
' Campo = Arg(0)
' Literal = CType(CType(sender, LinkButton).NamingContainer.FindControl("Img" & Campo.Replace(",", "_")), Literal)
' If ViewState(String.Format("O{0}", Campo)) IsNot Nothing AndAlso ViewState(String.Format("O{0}", Campo)).ToString = String.Format("{0} DESC", Campo) Then
' ViewState(String.Format("O{0}", Campo)) = String.Format("{0} ASC", Campo)
' Literal.Text = String.Format("<i class='fa fa-sort-asc' style='color:#999' ></i>")
' Else
' ViewState(String.Format("O{0}", Campo)) = String.Format("{0} DESC", Campo)
' Literal.Text = String.Format("<i class='fa fa-sort-desc' style='color:#999' ></i>")
' End If
' Orden = OrdenInicial & ViewState(String.Format("O{0}", Campo)).ToString
' ViewState("Orden") = Orden
' CargaGrid(Orden)
'End Sub
'Private Sub CargaGrid(Orden As String)
' If Orden <> String.Empty Then
' Dim DV As New DataView(CType(ViewState("DTPS"), DataTable), "", Orden, DataViewRowState.CurrentRows)
' GvDatos.DataSource = DV.ToTable().FiltraParametros("RowNum <= 500")
' DV.Dispose()
' Else
' GvDatos.DataSource = CType(ViewState("DTPS"), DataTable).FiltraParametros("RowNum <= 500")
' End If
' GvDatos.DataBind()
'End Sub
#End Region
#Region "Bitacora"
Private Sub CargaGvBitacora()
Dim ObjGral As New ClsGenerales
If ObjGral.GetHistorialBitacoraRemoveGet("PS", UsuarioActual.CveEmpresa) Then
GvBitacora.DataSource = ObjGral.DtResultados
ObjGral.Dispose()
End If
GvBitacora.DataBind()
End Sub
Private Sub BtnMostrar_Click(sender As Object, e As EventArgs) Handles BtnMostrar.Click
GvBitacora.Visible = True
BtnOcultar.Visible = True
BtnMostrar.Visible = False
UpBitacora.Update()
End Sub
Private Sub BtnOcultar_Click(sender As Object, e As EventArgs) Handles BtnOcultar.Click
GvBitacora.Visible = False
BtnOcultar.Visible = False
BtnMostrar.Visible = True
UpBitacora.Update()
End Sub
Private Sub LbImprimirProductos_Click(sender As Object, e As EventArgs) Handles LbImprimirProductos.Click
Dim ObjPS As New ClsProductosServicios
If ObjPS.GetProductosServiciosSinSAT(RBLOpcion.SelectedValue.ToEntero, UsuarioActual.CveEmpresa) Then
If ObjPS.DtResultados.Rows.Count > 0 Then
GvProductos.DataSource = ObjPS.DtResultados
GvProductos.DataBind()
GvProductos.ExportToExcelX("Reporte de Producto")
Else
Alert("Todos los productos tienen Asignada Clave Producto Servicio SAT.", TipoMensaje.MsgInformacion)
End If
End If
ObjPS.Dispose()
End Sub
#End Region
#Region " IMPRESION "
Protected Sub LBExcel_Click(sender As Object, e As EventArgs) Handles LBExcel.Click
If Not IsNothing(DtDatos) Then
ImprimirReporte("EXCEL")
Else
CargaDatos()
If IsNothing(DtDatos) Then
Alert("No se encontró información para el reporte.", TipoMensaje.MsgAdvertencia)
Else
ImprimirReporte("EXCEL")
End If
End If
End Sub
Protected Sub LBImprimir_Click(sender As Object, e As EventArgs) Handles LBImprimir.Click
If Not IsNothing(DtDatos) Then
ImprimirReporte()
Else
CargaDatos()
If IsNothing(DtDatos) Then
Alert("No se encontró información para el reporte.", TipoMensaje.MsgAdvertencia)
Else
ImprimirReporte()
End If
End If
End Sub
Private Sub ImprimirReporte(Optional Formato As String = "PDF")
Dim Archivo As New System.IO.FileInfo(String.Format("{0}Empresas/Grales/Formatos/CatPS.rpt", UsuarioActual.Empresa.Ruta))
Dim Imagen As New System.IO.FileInfo($"{UsuarioActual.Empresa.Ruta}/Logo.png")
'Dim logouri = String.Format("{0}://{1}:{2}/Empresas/{3}/Logo.png", Request.Url.Scheme, Request.Url.Host, Request.Url.Port, UsuarioActual.CveEmpresa)
Dim lista As New List(Of CrystalParametro)
lista.Add(New CrystalParametro("Empresa", UsuarioActual.Empresa.Empresa))
lista.Add(New CrystalParametro("UsuarioImprimio", UsuarioActual.Usuario))
lista.Add(New CrystalParametro("AplicaVenta", AplicaVenta.ToString))
'lista.Add(New CrystalParametro("LogoPath", If(Imagen.Exists, $"file://{Imagen.FullName}", "")))
If Imagen.Exists Then
lista.Add(New CrystalParametro("LogoPath", $"file://{Imagen.FullName}"))
Else
lista.Add(New CrystalParametro("LogoPath", ""))
End If
If Archivo.Exists Then
ImprimirbytesPDF(ImprimirPDFCrystal(Archivo.FullName, DtDatos, lista, "Productos y Servicios", Formato), "Productos y Servicios", Formato)
Else
Dim Ruta As String = ModExtensiones.DirectorioBaseEmpresas + $"Empresas\Grales\Formatos\CatPS.rpt"
ImprimirbytesPDF(ImprimirPDFCrystal(Ruta, DtDatos, lista, "Productos y Servicios", Formato), "Productos y Servicios", Formato)
End If
End Sub
Protected Sub LBExcelPersonalizado_Click(Sender As Object, e As EventArgs) Handles LBExcelPersonalizado.Click
ExportToExcelGembox(GvDatos, "Catálogo de Productos y Servicios", UsuarioActual, "Catálogo de Productos y Servicios")
End Sub
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
End Sub
#End Region
#Region "P R O D U C T O S A D I C I O N A L E S"
Private Function GuardarProductosEquivalenteEnFranquicia(ObjPS As ClsProductosServicios, CodigoPS As String, PSAdicional As String, Cantidad As Decimal, Opcion As Integer) As String
Dim Retorno As String = ""
If UsuarioActual.Empresa.Funcionalidad(563) <> "" Then
Dim StrEmpresas As String = UsuarioActual.CveEmpresa & "," & UsuarioActual.Empresa.Funcionalidad(563) ' agregamos la empresa actual
Dim EmpresasFranquicia As List(Of Integer) = StrEmpresas.Split(","c).ToList().ConvertAll(Function(x) Convert.ToInt32(x))
For Each Franquicia As Integer In EmpresasFranquicia
Dim CvePSPagina As Integer = GlobalDTPSSimplificado(Franquicia, Codigo:=CodigoPS.ToUpper).FiltroPrimeroValor("CvePS", "").ToEntero
Dim CvePSAdicional As Integer
If Opcion = 1 Then CvePSAdicional = GlobalDTPSSimplificado(Franquicia, Codigo:=PSAdicional.ToUpper).FiltroPrimeroValor("CvePS", "").ToEntero
If CvePSPagina <= 0 Then
Return String.Format("El producto:{0} no existe en la franquicia: '{1}'", CodigoPS, GlobalDTEmpresas(Franquicia).FiltroPrimeroValor("Empresa"))
End If
If CvePSAdicional <= 0 AndAlso Opcion = 1 Then
Return String.Format("El producto adicional: {0} no existe en la franquicia: '{1}'", PSAdicional, GlobalDTEmpresas(Franquicia).FiltroPrimeroValor("Empresa"))
End If
If Opcion = 1 Then
If Not ObjPS.AddPSAdicionales(CvePSPagina, CvePSAdicional, Cantidad, 1) Then
Return String.Format("No se registró el producto adicional:{0} no existe en la franquicia: '{1}'", CodigoPS, GlobalDTEmpresas(Franquicia).FiltroPrimeroValor("Empresa"))
End If
End If
If Opcion = 2 Then
If Not ObjPS.RemovePSAdicionales(CvePSPagina, -1) Then
Return "No se pudo eliminar"
End If
End If
Next
End If
Return ""
End Function
Private Sub LnkExcelPSAdicional_Click(sender As Object, e As EventArgs) Handles LnkExcelPSAdicional.Click
RegistraScript(String.Format("$('#{0}').modal();", "DivCargaExcelPSAdicionales"))
End Sub
Protected Sub BtnDescargar_Click(sender As Object, e As EventArgs) Handles BtnDescargarPSAdicional.Click
GemBox.Spreadsheet.SpreadsheetInfo.SetLicense(ModExtensiones.SerialGemBoxSpreadsheet)
Dim workbook As New GemBox.Spreadsheet.ExcelFile()
Dim worksheet As ExcelWorksheet = workbook.Worksheets.Add("Productos")
Dim DtExcel As New DataTable
DtExcel.Columns.Add("CodigoProducto", GetType(String))
DtExcel.Columns.Add("CodigoProductoAdicional", GetType(String))
DtExcel.Columns.Add("CantidadFija", GetType(String))
worksheet.InsertDataTable(DtExcel, New GemBox.Spreadsheet.InsertDataTableOptions() With
{
.ColumnHeaders = True,
.StartRow = 0,
.StartColumn = 0
})
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
workbook.Save(Response, $"CargaProductos.xlsx", GemBox.Spreadsheet.SaveOptions.XlsxDefault)
End Sub
Protected Sub BtnCargaExcel_Click(sender As Object, e As EventArgs) Handles BtnCargaExcelPSAdicional.Click
If TxtExcel.getfiles().Archivos.Count > 0 Then
Dim file As Archivo = TxtExcel.getfiles().Archivos(0)
Dim Directorio As String = Server.MapPath("~") & file.path
Dim Tipo As String = If(file.Extension.Contiene("xlsx", "xlsx", "xlsm", "xlsb"), "EXCEL", "CSV")
CargaArchivoPSAdicional(Directorio, file.filename, Tipo)
Else
Alert("No existe el archivo.Favor de subir un archivo csv o excel a la plataforma", TipoMensaje.MsgError)
End If
End Sub
Private Sub CargaArchivoPSAdicional(Ruta As String, FileName As String, Tipo As String)
Dim dt As New DataTable
Dim ErrorArchivo As Boolean = False
Dim ErrorExcel As Boolean = False
dt = ReadExcelFile(Ruta + FileName, True, 0).FiltraParametros("CodigoProducto <> ''")
If Not ErrorArchivo Then
If Not dt.Columns(0).ColumnName.ToUpper = "CODIGOPRODUCTO" Then
Alert("El nombre de la primera columna debe ser 'ConceptoAdministrativo'. Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
If Not dt.Columns(1).ColumnName.ToUpper = "CODIGOPRODUCTOADICIONAL" Then
Alert("El nombre de la segunda columna debe ser 'Cuenta'.Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
End If
If Not ErrorArchivo Then
Try
Dim ContadorRegistros As Integer = 0
Dim ObjPS As ClsProductosServicios
Dim dtPS As DataTable = dt.FiltraParametros("", DistinctColumns:={"CodigoProducto"})
Dim strNoCargados As New StringBuilder
'antes de iniciar la carga se limpiarán los asignados, se filtran por codigops
For Each Row As DataRow In dtPS.Rows
ObjPS = New ClsProductosServicios
ObjPS.IniciaTransacSQL()
ErrorExcel = False
Dim msgg As String = GuardarProductosEquivalenteEnFranquicia(ObjPS, Row("CodigoProducto").ToString.Trim, "", 0, 2)
If msgg = "" Then ''eliminar los ps
For Each dr As DataRow In dt.FiltraParametros($"CodigoProducto='{ Row("CodigoProducto").ToString.Trim}'").Rows
Dim CodigoPS As String = dr("CodigoProducto").ToString.Trim
Dim CodigoPSAdicional As String = dr("CodigoProductoAdicional").ToString.Trim
Dim Cantidad As Integer = dr("CantidadFija").ToString.ToEntero
msgg = GuardarProductosEquivalenteEnFranquicia(ObjPS, CodigoPS, CodigoPSAdicional, Cantidad, 1)
If msgg <> "" Then
ErrorExcel = True
strNoCargados.AppendFormat(" {0} <br/>", msgg)
Exit For
End If
ContadorRegistros = ContadorRegistros + 1
Next
Else
ErrorExcel = True
strNoCargados.AppendFormat(" {0} <br/> ", msgg)
End If
If Not ErrorExcel Then
ObjPS.Commit()
Else
ObjPS.RollBack()
End If
ObjPS.Dispose()
Next
If ContadorRegistros > 1 Then
Dim StrEmpresas As String = UsuarioActual.Empresa.Funcionalidad(563) & "," & UsuarioActual.CveEmpresa ' agregamos la empresa actual
Dim EmpresasFranquicia As List(Of Integer) = StrEmpresas.Split(","c).ToList().ConvertAll(Function(x) Convert.ToInt32(x))
'regenerar el global de cada empresa
For Each Franquicia As Integer In EmpresasFranquicia
GlobalDTPSAdicionales(-1, Franquicia) = Nothing
Next
End If
Alert($"{ContadorRegistros} Registros aplicados.<br/>{If(strNoCargados.Length > 0, strNoCargados.ToString, "")}")
Catch ex As Exception
Alert("No se pudo cargar el excel", TipoMensaje.MsgAdvertencia)
GuardaLog(ex.Message)
End Try
End If
End Sub
#End Region
End Class