Files
SIG/Ventas/ActualizarPrecios.aspx.vb

591 lines
24 KiB
VB.net

Option Explicit On
Option Strict On
Imports Extensiones
Imports System.Data
Imports GemBox.Spreadsheet
Partial Class Ventas_ActualizarPrecios
Inherits ClsPaginas
Private Property DtSubProyectos As DataTable
Get
Return If(IsNothing(ViewState("DtSubProyectos")), Nothing, CType(ViewState("DtSubProyectos"), DataTable))
End Get
Set(value As DataTable)
ViewState("DtSubProyectos") = value
End Set
End Property
Private Property CveSucursal As Integer
Get
If ViewState("CveSucursal") Is Nothing Then
Return -1
Else
Return ViewState("CveSucursal").ToString.ToEntero
End If
End Get
Set(value As Integer)
ViewState("CveSucursal") = value
End Set
End Property
Private Property CvePS As Integer
Get
If ViewState("CvePS") Is Nothing Then
Return -1
Else
Return ViewState("CvePS").ToString.ToEntero
End If
End Get
Set(value As Integer)
ViewState("CvePS") = value
End Set
End Property
Private Property PS As String
Get
If ViewState("PS") Is Nothing Then
Return ""
Else
Return ViewState("PS").ToString
End If
End Get
Set(value As String)
ViewState("PS") = value
End Set
End Property
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
CargaCombos()
End If
End Sub
Public Sub CargaCombos()
CargaDDlClasif()
CargaPS()
CargaPreciosLista()
CargaProveedores()
CargarMarcas()
CargarModelos()
End Sub
Public Sub CargaDDlClasif()
DDlClasificacion.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa)
DDlClasificacion.DataBind()
DDlClasificacion.Items.Insert(0, New ListItem("Todos", "-1"))
End Sub
Public Sub CargaPreciosLista()
DdlPrecioLista.Items.Clear()
If UsuarioActual.Empresa.Funcionalidad(404).ToEntero > 0 Then 'si manneja precios de lista
Dim ObjVta As New ClsVentas
Dim primerItem As String = ""
If ObjVta.GetPrecioListas(UsuarioActual.CveEmpresa) Then
DdlPrecioLista.DataSource = ObjVta.DtResultados.Copy()
DdlPrecioListaCarga.DataSource = ObjVta.DtResultados.Copy()
primerItem = ObjVta.DtResultados.FiltroPrimeroValor("CvePrecioLista")
End If
ObjVta.Dispose()
DdlPrecioLista.DataBind()
DdlPrecioListaCarga.DataBind()
If (DdlPrecioLista.Items.Count = 1) Then
DdlPrecioLista.Items.FindByValue(primerItem).Selected = True
End If
Else
DdlPrecioLista.Items.Insert(0, New ListItem("Sin Precio Lista", "-2"))
DdlPrecioListaCarga.Items.Insert(0, New ListItem("Sin Precio Lista", "-2"))
End If
End Sub
Public Sub CargaPS()
'FUNCIONALIDAD 105
If UsuarioActual.Empresa.Funcionalidad(105) = "1" Then
DDlPs.setEsWebService(True)
Else
DDlPs.setEsWebService(False)
'FUNCIONALIDAD DE COMPUESTO
If UsuarioActual.Empresa.Funcionalidad(143) = "1" Then
DDlPs.ddl.DataTextField = "PSCodigoCompuesto"
End If
DDlPs.DataSource = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa)
DDlPs.DataBind()
DDlPs.ddl.Items.Insert(0, New ListItem("Todos", "-1"))
End If
End Sub
Private Sub CargaProveedores()
If UsuarioActual.Empresa.Funcionalidad(524) <> "" Then
DdlProveedor.setEsWebService(True)
DivProveedorCompra.Visible = True
LblProveedorCompra.Visible = True
End If
End Sub
Protected Sub CargarMarcas()
If UsuarioActual.Empresa.Funcionalidad(130) = "1" Then
Dim ObjMarcas As New ClsProductosServicios
If ObjMarcas.GetMarcas(UsuarioActual.CveEmpresa) Then
DdlMarca.DataSource = ObjMarcas.DtResultados.Copy
End If
ObjMarcas.Dispose()
DdlMarca.DataBind()
LblMarca.Visible = True
DdlMarca.Visible = True
End If
DdlMarca.Items.Insert(0, New ListItem("Todos", "-1"))
End Sub
Private Sub CargarModelos()
If UsuarioActual.Empresa.Funcionalidad(558).ToString = "1" Then
lblModelo.visible = True
DdlModelo.Visible = True
Dim ObjGeneral As New ClsGenerales
If ObjGeneral.GetModelos(UsuarioActual.CveEmpresa) Then
DdlModelo.DataSource = ObjGeneral.DtResultados
End If
ObjGeneral.Dispose()
DdlModelo.DataBind()
End If
DdlModelo.Items.Insert(0, New ListItem("Seleccione", "-1"))
End Sub
Protected Sub BtnConsultar_Click(sender As Object, e As EventArgs)
Dim objPS As New ClsProductosServicios
Dim CveProveedor As Integer = -1
Dim CvePS As Integer = -1
Dim Marcas As String = If(DdlMarca.GetSelectedValuesM = "", "-1", DdlMarca.GetSelectedValuesM)
If DDlPs.SelectedValue.ToEntero > 0 Then
CvePS = DDlPs.SelectedValue.ToEntero
End If
If DdlProveedor.txtValue.Value.ToEntero > 0 Then
CveProveedor = DdlProveedor.txtValue.Value.ToEntero
End If
If objPS.GetPSPreciosLista(UsuarioActual.CveEmpresa, DdlPrecioLista.SelectedValue.ToEntero, DDlClasificacion.SelectedValue.ToEntero, CvePS,
CveProveedor:=CveProveedor, Estado:=DdlEstado.SelectedValue.ToEntero, Marcas:=Marcas, CveModelo:=DdlModelo.SelectedValue.ToEntero) Then
GVPrecios.DataSource = objPS.DtResultados
End If
objPS.Dispose()
dvDatos.Visible = True
GVPrecios.DataBind()
UpDescargar.Update()
UpDatos.Update()
End Sub
Protected Sub DDlClasificacion_SelectedIndexChanged(sender As Object, e As EventArgs)
CargaPS()
UpEncabezado.Update()
End Sub
Protected Sub RblTipo_SelectedIndexChanged(sender As Object, e As EventArgs)
If RblTipo.SelectedValue = "Imp" Then
ImporteFijo.Visible = True
Else
ImporteFijo.Visible = False
End If
UPPrecioLista.Update()
End Sub
Protected Sub BtnGuardar_Click(sender As Object, e As EventArgs) Handles BtnGuardar.Click
If RblTipo.SelectedIndex = 1 And TxtPorcentaje.Text.ToDecimal = 0 Then
Alert("Se debe de especificar un porcentaje.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
Dim Correcto As Boolean = False
Dim TieneError As Boolean = False
'Dim Importe As Decimal = If(TxtImporte.Text = "", -1, TxtImporte.Text.ToDecimal)
Dim Porcentaje As Decimal = If(TxtPorcentaje.Text = "", -1, TxtPorcentaje.Text.ToDecimal)
Dim ObjPS As New ClsProductosServicios
ObjPS.IniciaTransacSQL()
For Each row As GridViewRow In GVPrecios.Rows
If row.FCCheckBox("chkPS").Checked Then
Correcto = ObjPS.UpdatePSPreciosLista(row.FCTextBox("TxtPrecio").Text.ToDecimal, DdlPrecioLista.SelectedValue.ToEntero, Porcentaje, row.DataKey("CvePS").ToEntero, UsuarioActual.CveUsuario, DateTime.Now, If(RblTipo.SelectedValue = "Imp", True, False), PrecioMinimo:=row.FCTextBox("TxtPrecioMinimo").Text.ToDecimal)
If Correcto Then
TieneError = ActualizarPreciosFranquicia(ObjPS, row.DataKey("Codigo"), row.DataKey("PS"), row.FCTextBox("TxtPrecio").Text.ToDecimal, row.FCTextBox("TxtPrecioMinimo").Text.ToDecimal, DdlPrecioLista.SelectedItem.Text)
Else
Exit Sub
End If
End If
Next
If Correcto AndAlso Not TieneError Then
Alert("Los Precios de lista de los Productos/Servicios se actualizaron correctamente")
End If
If TieneError Then
ObjPS.RollBack()
Else
ObjPS.Commit()
End If
ObjPS.Dispose()
BtnConsultar_Click(Nothing, Nothing)
RegistraScript("$('#divAgregar').modal('hide')")
TxtImporte.Text = ""
TxtPrecio.Text = ""
TxtPorcentaje.Text = ""
End Sub
#Region "MODAL PRECIOS MINIMOS"
Public Sub LnkPrecioMinActual_Click(sender As Object, e As EventArgs)
Dim GvRow As GridViewRow = DirectCast(DirectCast(sender, LinkButton).NamingContainer, GridViewRow)
CvePS = GvRow.DataKey("CvePS").ToEntero
PS = GvRow.DataKey("PS").ToString
TxtAplicarPrecio.Text = ""
CargaDatosModalPreciosMinimos()
RegistraScript("$('#ModalActualizaPrecios').modal({ backdrop: 'static', keyboard: false}); $('#ChkSeleccionarTodos').find('input[type=checkbox]').prop('checked', false);")
End Sub
Protected Sub LnkModalGuardarPreciosMinimos_Click(sender As Object, e As EventArgs)
ProcesaPreciosSucursales()
CargaDatosModalPreciosMinimos()
End Sub
Private Sub CargaDatosModalPreciosMinimos()
Dim ObjPS As New ClsProductosServicios
If ObjPS.GetPSSucursales(CvePS, UsuarioActual.CveEmpresa) Then
gvSucursal.DataSource = ObjPS.DtResultados
End If
ObjPS.Dispose()
gvSucursal.DataBind()
LtlModalTitleUpModalTitulo.Text = PS
UpModalActualizaPrecios.Update()
UpModalTitulo.Update()
End Sub
Private Sub ProcesaPreciosSucursales()
Dim ObjProductosServicios As New ClsProductosServicios()
For i As Integer = 0 To gvSucursal.Rows.Count - 1
If gvSucursal.Rows(i).FCCheckBox("chkSucursal").Checked Then
If gvSucursal.Rows(i).FCHiddenField("hdnEnBD").Value.ToEntero = 1 Then
ObjProductosServicios.UpdatePSSucursales(CvePS, -1, gvSucursal.Rows(i).FCTextBox("TxtMinimo").Text.ToDouble, -1, UsuarioActual.CveUsuario, gvSucursal.Rows(i).DataKey("CveSubProyecto").ToEntero, PrecioMinimo:=gvSucursal.Rows(i).FCTextBox("TxtPrecioMinimo").Text.ToDecimal)
Else
ObjProductosServicios.AddPSSucursales(CvePS, Nothing, gvSucursal.Rows(i).FCTextBox("TxtMinimo").Text.ToDouble, -1, UsuarioActual.CveUsuario, gvSucursal.Rows(i).DataKey("CveSubProyecto").ToEntero, PrecioMinimo:=gvSucursal.Rows(i).FCTextBox("TxtPrecioMinimo").Text.ToDecimal)
End If
End If
Next
ObjProductosServicios.Dispose()
End Sub
#End Region
#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 = (From row As GridViewRow In GVPrecios.Rows.Cast(Of GridViewRow)
Where row.RowType = DataControlRowType.DataRow
Select New With
{
.Codigo = row.DataKey("Codigo"),
.PS = row.DataKey("PS"),
.Precio = row.FCTextBox("TxtPrecio").Text.ToDecimal()
}).QueryToDataTable(True)
If DtExcel.Rows.Count < 1 Then
Alert("No hay resutados en la busqueda.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
If DdlPrecioLista.SelectedItem IsNot Nothing Then
Dim worksheetName As String = DdlPrecioLista.SelectedItem.Text
Const invalidCharsRegex As String = "[/\\*'?[\]:]+"
Const maxLength As Integer = 31
Dim safeName As String = Regex.Replace(worksheetName, invalidCharsRegex, " ").Replace(" ", " ").Trim()
If String.IsNullOrEmpty(safeName) Then
safeName = "Precios" ' cannot be empty
ElseIf safeName.Length > maxLength Then
safeName = safeName.Substring(0, maxLength)
End If
DtExcel.TableName = safeName
Else
DtExcel.TableName = "Precios"
End If
DtExcel.Columns("Codigo").ColumnName = "Código"
DtExcel.Columns("PS").ColumnName = "Producto / Servicio"
SpreadsheetInfo.SetLicense(ModExtensiones.SerialGemBoxSpreadsheet)
Dim FileExcel As New ExcelFile()
Dim worksheet = 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 = worksheet.CalculateMaxUsedColumns()
For i = 0 To columnCount
worksheet.Columns(i).AutoFit(1, worksheet.Rows(0), worksheet.Rows(worksheet.Rows.Count - 1))
Next
'worksheet.Cells.Style.Locked = False
'worksheet.Cells.Style.FormulaHidden = False
'worksheet.Columns(0).Cells.Style.Locked = True
'worksheet.Protected = True
'Dim protectionSettings = worksheet.ProtectionSettings
'protectionSettings.AllowDeletingColumns = False
'protectionSettings.AllowDeletingRows = True
'protectionSettings.AllowEditingObjects = True
'protectionSettings.AllowEditingScenarios = True
'protectionSettings.AllowFormattingCells = True
'protectionSettings.AllowFormattingColumns = True
'protectionSettings.AllowFormattingRows = True
'protectionSettings.AllowInsertingColumns = False
'protectionSettings.AllowInsertingRows = True
'protectionSettings.AllowSelectingLockedCells = True
'protectionSettings.AllowSelectingUnlockedCells = True
'protectionSettings.AllowSelectingUnlockedCells = True
'protectionSettings.AllowSorting = True
'protectionSettings.AllowUsingAutoFilter = True
'protectionSettings.AllowUsingPivotTableReports = True
'protectionSettings.SetPassword(ModExtensiones.IMEI)
FileExcel.Save(Response, "Precios.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.patch
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 Tipo As String = "EXCEL"
Dim dt As DataTable = Nothing
Dim ErrorArchivo = False
Try
dt = ReadExcelFile(Ruta + FileName, True)
Catch ex As Exception
ErrorArchivo = True
OnError("Ocurrio un error al leer el archivo <br/>" & ex.Message, ex)
End Try
If Not ErrorArchivo AndAlso dt IsNot Nothing Then
If DdlPrecioListaCarga.SelectedValue.ToEntero() = -1 Then
Alert("Debe Seleccionar la lista de precios a cargar. Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
If Not dt.Columns(0).ColumnName = "Código" Then
Alert("El nombre de la tercera columna debe ser 'Codigo'. Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
If Not dt.Columns(1).ColumnName = "Producto / Servicio" Then
Alert("El nombre de la cuarta columna debe ser 'Producto / Servicio'. Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
If Not dt.Columns(2).ColumnName = "Precio" Then
Alert("El nombre de la sexta columna debe ser 'Precio'. Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
dt.TableName = "Datos"
Dim ProductosNoCargados As New StringBuilder()
Dim RowsCargados As Integer = 0
Dim RowsNoCargados As Integer = 0
Dim ObjPS As New ClsProductosServicios
'ObjPS.IniciaTransacSQL()
Try
Dim DtPS As DataTable = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa)
For Each row As DataRow In dt.Rows
Dim Correcto As Boolean = False
Dim TieneError As Boolean = False
Dim CvePS As Integer = DtPS.FiltroPrimeroValor("CvePS", String.Format("Codigo='{0}' AND CveEmpresa={1}", row(0).ToString(), UsuarioActual.CveEmpresa)).ToEntero
Dim CvePrecioLista As Integer = DdlPrecioListaCarga.SelectedValue.ToEntero()
Dim PrecioNuevo As Decimal = row("Precio").ToString().ToDecimal()
Dim Porcentaje As Decimal = -1
If CvePS > 0 AndAlso CvePrecioLista > 0 Then
Correcto = ObjPS.UpdatePSPreciosLista(PrecioNuevo, CvePrecioLista, Porcentaje, CvePS, UsuarioActual.CveUsuario, DateTime.Now, True)
If Correcto Then
RowsCargados += 1
TieneError = ActualizarPreciosFranquicia(ObjPS, row(0).ToString(), row(1).ToString(), PrecioNuevo, 0, DdlPrecioListaCarga.SelectedItem.Text)
End If
Else
If CvePS > 0 AndAlso CvePrecioLista = -2 Then
Correcto = ObjPS.UpdatePSPrecios(PrecioNuevo, CvePrecioLista, Porcentaje, CvePS, UsuarioActual.CveUsuario, DateTime.Now, True)
If Correcto Then
RowsCargados += 1
End If
Else
Correcto = False
End If
End If
If Not Correcto Then
ProductosNoCargados.AppendFormat("{0},", row("Producto / Servicio").ToString())
RowsNoCargados += 1
End If
Next
Catch ex As Exception
OnError("Ocurrió un error al cargar los precios.", ex)
Finally
Dim MensajeFinal As New StringBuilder()
If RowsNoCargados = 0 AndAlso RowsCargados > 0 Then
MensajeFinal.Append("Los precios de los Productos/Servicios se cargaron correctamente. <br/><br/>")
End If
If RowsCargados > 0 Then
MensajeFinal.Append("Se actualizaron <b>" & RowsCargados & "</b> Productos o Servicios correctamente.")
End If
If RowsNoCargados > 0 Then
MensajeFinal.Append("No se pudieron actualizar <b>" & RowsNoCargados & "</b> Productos/Servicios. <br/>Los siguientes Productos o Servicios no se pudieron actualizar: " & ProductosNoCargados.ToString())
End If
Alert(MensajeFinal.ToString())
ObjPS.Dispose()
End Try
'If RowNoEncontrados.Length > 0 Then
' Alert("Los siguientes Productos o Servicios no se encontraron en la Base de Datos.<\BR>" & RowNoEncontrados, TipoMensaje.MsgAdvertencia)
'Else
' Alert("Se Cargaron " & NumRow & " Productos o Servicios correctamente.")
'End If
End If
End Sub
Private Function ReadExcelFile(ByVal flatFilePath As String, ByVal firstRowHasHeaders As Boolean) As DataTable
SpreadsheetInfo.SetLicense(ModExtensiones.SerialGemBoxSpreadsheet)
Dim excelFile As ExcelFile = ExcelFile.Load(flatFilePath)
Dim unnamed As Integer = 0
Dim cols As Integer
Dim columns As String()
Dim curRow As Integer = 0
Dim curCol As Integer = 0
Dim dataTable As DataTable = New DataTable()
Dim worksheet As ExcelWorksheet = excelFile.Worksheets(0)
For cols = 0 To worksheet.Rows(0).AllocatedCells.Count - 1
If firstRowHasHeaders Then
If worksheet.Rows(0).Cells(cols).Value IsNot Nothing Then
dataTable.Columns.Add(worksheet.Rows(0).Cells(cols).Value.ToString())
Else
dataTable.Columns.Add("Unnamed Column " & (System.Threading.Interlocked.Increment(unnamed)))
End If
curRow = 1
Else
dataTable.Columns.Add("Column " & (cols + 1))
End If
Next
While curRow < worksheet.Rows.Count
columns = New String(cols - 1) {}
For curCol = 0 To cols - 1
If worksheet.Rows(curRow).Cells(curCol).Value Is Nothing Then
columns(curCol) = ""
Else
columns(curCol) = worksheet.Rows(curRow).Cells(curCol).Value.ToString()
End If
Next
dataTable.Rows.Add(columns)
curRow += 1
End While
Return dataTable
End Function
#End Region
Protected Sub gvSucursal_RowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.FCTextBox("TxtPrecioMinimo").Attributes.Add("onKeyUp", String.Format("FncSeleccionaChk({0});", e.Row.FCCheckBox("chkSucursal").ClientID))
End If
End Sub
Private Function ActualizarPreciosFranquicia(ObjPS As ClsProductosServicios, Codigo As String, PS As String, Precio As Decimal, PrecioMinimo As Decimal, PrecioLista As String) As Boolean
Dim FranquiciasStr As String = UsuarioActual.Empresa.Funcionalidad(563)
Dim StrMsg As New StringBuilder
Dim StrMsgError As New StringBuilder
If FranquiciasStr <> "" Then
Dim Franquicias = FranquiciasStr.Split(","c)
Dim Porcentaje As Decimal = If(TxtPorcentaje.Text = "", -1, TxtPorcentaje.Text.ToDecimal)
For Each Franquicia In Franquicias
Dim CveFranquicia As Integer = Franquicia.ToEntero
Dim CvePS As Integer = GlobalDTPS(CveFranquicia, Codigo:=Codigo.ToUpper).FiltroPrimeroValor("CvePS", "").ToEntero
Dim CvePrecioLisa As Integer = GlobalDTPrecioListas(CveFranquicia).FiltroPrimeroValor("CvePrecioLista", String.Format("PrecioLista = '{0}'", PrecioLista)).ToEntero
If CvePS <= 0 Then
Dim EmpresaFranquicia As String = GlobalDTEmpresas(CveEmpresa:=CveFranquicia).FiltroPrimeroValor("Empresa")
StrMsg.AppendFormat("El producto '{0}' no se encuentra en la Franquicia '{1}' <br/>", PS, EmpresaFranquicia)
End If
'If CvePrecioLisa <= 0 Then
' Dim EmpresaFranquicia As String = GlobalDTEmpresas(CveEmpresa:=CveFranquicia).FiltroPrimeroValor("Empresa")
' StrMsg.AppendFormat("El precio lista '{0}' no existe en la Franquicia '{1}'<br/>", DdlPrecioLista.SelectedItem.Text, EmpresaFranquicia)
'End If
If CvePrecioLisa > 0 AndAlso CvePS > 0 AndAlso Not ObjPS.UpdatePSPreciosLista(Precio, CvePrecioLisa, Porcentaje, CvePS, UsuarioActual.CveUsuario, DateTime.Now, If(RblTipo.SelectedValue = "Imp", True, False), PrecioMinimo:=PrecioMinimo) Then
StrMsgError.AppendFormat("No se pudo actualizar el producto")
End If
Next
End If
If StrMsgError.ToString = "" Then
If StrMsg.ToString <> "" Then
Alert(StrMsg.ToString, TipoMensaje.MsgAdvertencia)
End If
Return False
Else
Return True
End If
End Function
End Class