Files
SIG/Ashx/E141.ashx

1051 lines
41 KiB
Plaintext

<%@ WebHandler Language="VB" Class="E141" %>
Option Strict On
Option Explicit On
Imports System.Data
Imports System.IO
Imports System.Net.Http
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Imports Extensiones
Public Class E141 : Implements IHttpHandler
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
Private ReadOnly Property CveEmpresa As Integer = 141
Public ReadOnly Property EsProduccion As Boolean
Get
If IsNothing(System.Configuration.ConfigurationManager.AppSettings("EsProduccion")) Then
Return False
Else
Return (System.Configuration.ConfigurationManager.AppSettings("EsProduccion").ToString() = "1")
End If
End Get
End Property
Public ReadOnly Property UsuarioWSE141 As String
Get
If IsNothing(System.Configuration.ConfigurationManager.AppSettings("UsuarioWSE141")) Then
Return ""
Else
Return System.Configuration.ConfigurationManager.AppSettings("UsuarioWSE141").ToString()
End If
End Get
End Property
Public ReadOnly Property PasswordWSE141 As String
Get
If IsNothing(System.Configuration.ConfigurationManager.AppSettings("PasswordWSE141")) Then
Return ""
Else
Return System.Configuration.ConfigurationManager.AppSettings("PasswordWSE141").ToString()
End If
End Get
End Property
Public ReadOnly Property TokenAutorizacion As String
Get
If EsProduccion Then
Return "$2y$10$EZlXnFrhUc4aRVwjy5/v0.3JPdFNjyeANDc64YXJ5eHD8pMsv93Q."
Else
Return "$2y$10$8Mk3YeIkJESilIwD.U5dG.SsA4JloycJKbaGls8TNEw/AKBE1qane"
End If
End Get
End Property
Public ReadOnly Property URLBase As String
Get
If EsProduccion Then
Return "https://services.fidelityapps.mx/"
Else
Return "https://econollantas-pruebas.fidelityapps.mx/"
End If
End Get
End Property
#Region "GLOBAL DT"
Public Property GlobalDTSubProyectos(CveProyecto As Integer, Optional CveSubProyecto As Integer = -1, Optional CveEmpresa As Integer = -1, Optional Estatus As Integer = 1) As DataTable
Get
Dim AppNombre As String = String.Format("GlobalDTSubProyectos-{0}", CveEmpresa)
'sino existe, recarga los datos
If DirectCast(HttpContext.Current.Application(AppNombre), DataTable) Is Nothing Or (DirectCast(HttpContext.Current.Application(AppNombre), DataTable) IsNot Nothing AndAlso DirectCast(HttpContext.Current.Application(AppNombre), DataTable).Rows.Count = 0) Then
Dim P As New ClsSubProyectos
If P.GetSubProyectos(CveEmpresa:=CveEmpresa) Then HttpContext.Current.Application(AppNombre) = P.DtResultados
P.Dispose()
End If
If CveProyecto <> -1 OrElse CveSubProyecto <> -1 OrElse CveEmpresa <> -1 OrElse Estatus <> -1 Then
Dim StrSQL As New StringBuilder
If CveProyecto <> -1 Then StrSQL.AppendFormat(" AND CveProyecto = {0}", CveProyecto)
If CveSubProyecto <> -1 Then StrSQL.AppendFormat(" AND CveSubProyecto = {0}", CveSubProyecto)
If Estatus <> -1 Then StrSQL.AppendFormat(" AND CveEstatus = {0}", Estatus)
If CveEmpresa <> -1 Then StrSQL.AppendFormat(" AND CveEmpresa = {0}", CveEmpresa)
Dim Dv As New DataView(DirectCast(HttpContext.Current.Application(AppNombre), DataTable), StrSQL.ToString.Trim.TrimStart("A"c, "N"c, "D"c), "", DataViewRowState.CurrentRows)
GlobalDTSubProyectos = Dv.ToTable
Dv.Dispose()
Else
GlobalDTSubProyectos = DirectCast(HttpContext.Current.Application(AppNombre), DataTable)
End If
End Get
Set(ByVal value As DataTable)
Dim AppNombre As String = String.Format("GlobalDTSubProyectos-{0}", CveEmpresa)
HttpContext.Current.Application(AppNombre) = value
End Set
End Property
#End Region
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim retorno As String = ""
Try
Dim Params = If(context.Request("P") = Nothing, "", context.Request("P").ToString())
'DESCARGA DEL PDF
If Not String.IsNullOrEmpty(Params) Then
Dim UrlParametros As Hashtable = Parametros(Decripta(Params))
Dim File As String = UrlParametros("FILE").ToString()
If Not String.IsNullOrEmpty(File) Then
ImprimirbytesPDF(context, DescargarFactura(File), File)
End If
Else
Dim Metodo = If(context.Request("Metodo") = Nothing, "", context.Request("Metodo").ToString())
'OBTENER EXISTENCIAS
If Metodo = "GetExistencia" Then
context.Response.ContentType = "application/json"
Dim Codigo = If(context.Request("Sku") = Nothing, "", context.Request("Sku").ToString())
retorno = GetExistencia(context, Codigo)
ElseIf Metodo = "ConsultarRFC" Then
context.Response.ContentType = "application/json"
Dim Auth = ValidarSolicitud(context)
If Auth.IsSucces Then
retorno = ConsultaRFC(context)
Else
retorno = JsonConvert.SerializeObject(Auth.ErrorMessage)
End If
ElseIf Metodo = "ValidarCarrito" Then
context.Response.ContentType = "application/json"
Dim Auth = ValidarSolicitud(context)
If Auth.IsSucces Then
retorno = ValidarCarrito(context)
Else
retorno = JsonConvert.SerializeObject(Auth.ErrorMessage)
End If
ElseIf Metodo = "RegistrarPedido" Then
context.Response.ContentType = "application/json"
Dim Auth = ValidarSolicitud(context)
If Auth.IsSucces Then
retorno = RegistrarPedido(context)
Else
retorno = JsonConvert.SerializeObject(Auth.ErrorMessage)
End If
ElseIf Metodo = "RegistrarCotizacion" Then
context.Response.ContentType = "application/json"
Dim Auth = ValidarSolicitud(context)
If Auth.IsSucces Then
retorno = RegistrarCotizacion(context)
Else
retorno = JsonConvert.SerializeObject(Auth.ErrorMessage)
End If
ElseIf Metodo = "GetSucursales" Then
context.Response.ContentType = "application/json"
Dim Auth = ValidarSolicitud(context)
If Auth.IsSucces Then
retorno = GetSucursales(context)
Else
retorno = JsonConvert.SerializeObject(Auth.ErrorMessage)
End If
context.Response.StatusCode = Auth.StatusCode
Else
context.Response.ContentType = "text/html"
If Not String.IsNullOrEmpty(Metodo) Then
Dim FiltrarTodos = If(context.Request("FiltrarTodos") = Nothing, "", context.Request("FiltrarTodos").ToString())
Dim respuesta As Boolean = False
'TAREAS PROGRAMADAS
Select Case Metodo
Case "CrearActualizarProductos"
respuesta = CrearActualizarProductos(If(FiltrarTodos = "1", True, False))
Case "ActualizarPrecios"
respuesta = ActualizarPrecios(If(FiltrarTodos = "1", True, False))
Case "ActualizarExistencias"
respuesta = ActualizarExistencias()
Case "ActualizarVendedores"
respuesta = ActualizarVendedores(If(FiltrarTodos = "1", True, False))
End Select
If respuesta Then
retorno = "True"
Else
retorno = "False"
End If
End If
End If
context.Response.Write(retorno)
End If
Catch ex As Exception
context.Response.ContentType = "text/html"
retorno = ex.ToString()
ex.GuardaLog(ex.ToString())
context.Response.Write(retorno)
End Try
End Sub
Private Function ValidarSolicitud(ByVal context As HttpContext) As AuthMessage
Dim unauthorized As Boolean = True
Dim respuesta As New AuthMessage
Dim authHeader = context.Request.Headers("Authorization")
If authHeader IsNot Nothing Then
Dim basicAuth As String = authHeader.Replace("Basic ", "")
Dim usernamePasswordArray = Encoding.UTF8.GetString(Convert.FromBase64String(basicAuth)).Split(":"c)
Dim userName = usernamePasswordArray(0)
Dim password = usernamePasswordArray(1)
unauthorized = Not (userName = Me.UsuarioWSE141 AndAlso password = Me.PasswordWSE141)
Else
respuesta.ErrorMessage = New FidelityAppsResponseError() With {.message = "el usuario y/o contraseña son requeridos"}
respuesta.IsSucces = False
respuesta.StatusCode = 401
Return respuesta
End If
If unauthorized Then
respuesta.ErrorMessage = New FidelityAppsResponseError() With {.message = "el usuario y/o contraseña no son validos"}
respuesta.IsSucces = False
respuesta.StatusCode = 401
Return respuesta
Else
respuesta.ErrorMessage = Nothing
respuesta.IsSucces = True
respuesta.StatusCode = 200
Return respuesta
End If
End Function
Private Function ConsultaRFC(ByVal context As HttpContext) As String
Dim Respuesta As New FidelityAppsResponse
Dim RespuestaError As New FidelityAppsResponseError
Dim TieneError As Boolean = False
Dim JsonRequest As JObject = Nothing
If context.Request.InputStream IsNot Nothing Then
Using reader As New StreamReader(context.Request.InputStream)
Dim json = reader.ReadToEnd
If Not String.IsNullOrEmpty(json) Then
JsonRequest = JObject.Parse(json)
If JsonRequest Is Nothing Then
TieneError = True
End If
End If
End Using
End If
If Not TieneError AndAlso Not String.IsNullOrEmpty(JsonRequest("rfc").ToString().Trim()) Then
Dim data As New JArray
Dim Nombre As String = "-1"
Dim Codigo As String = "-1"
Dim NombreCorto As String = "-1"
Dim RFC As String = JsonRequest("rfc").ToString()
Dim Telefono As String = "-1"
Dim Mail As String = "-1"
Dim DtSucursales As DataTable = Nothing
Using ObjClientes As New ClsClientes
If ObjClientes.GetListaSucursales(RFC, CveEmpresa) Then
DtSucursales = ObjClientes.DtResultados.Copy()
End If
End Using
If DtSucursales IsNot Nothing Then
Try
For Each Row As DataRow In DtSucursales.Rows
Dim objSucursal As New JObject(
New JProperty("Id", Row("CveCliente")),
New JProperty("rfc", Row("RFC")),
New JProperty("name", Row("SucursalCliente")),
New JProperty("phone", Row("Telefono")),
New JProperty("email", Row("Correo")),
New JProperty("address", Row("Direccion")),
New JProperty("int_number", Row("NoInt")),
New JProperty("ext_number", Row("NoExt")),
New JProperty("street", Row("Direccion")),
New JProperty("between_streets", ""),
New JProperty("city", Row("Localidad")),
New JProperty("state", Row("Estado")),
New JProperty("zip_code", Row("CP")),
New JProperty("reference", ""),
New JProperty("Branch_office_code", ""),
New JProperty("Branch_office_name", ""),
New JProperty("Branch_office_id", "")
)
data.Add(objSucursal)
Next
Catch ex As Exception
TieneError = True
RespuestaError.message = "Ocurrió un error al obtener la sucursales"
End Try
DtSucursales.Dispose()
Else
TieneError = True
End If
If data.Count > 0 Then
Respuesta.data = data
End If
End If
If TieneError Then
Return JsonConvert.SerializeObject(RespuestaError)
Else
Return JsonConvert.SerializeObject(Respuesta)
End If
End Function
Private Function ValidarCarrito(ByVal context As HttpContext) As String
Dim Respuesta As New FidelityAppsResponse
Dim RespuestaError As New FidelityAppsResponseError
Dim TieneError As Boolean = False
If TieneError Then
Return JsonConvert.SerializeObject(RespuestaError)
Else
Return JsonConvert.SerializeObject(Respuesta)
End If
End Function
Private Function RegistrarPedido(ByVal context As HttpContext) As String
Dim Respuesta As New FidelityAppsResponse
Dim RespuestaError As New FidelityAppsResponseError
Dim TieneError As Boolean = False
If TieneError Then
Return JsonConvert.SerializeObject(RespuestaError)
Else
Return JsonConvert.SerializeObject(Respuesta)
End If
End Function
Private Function RegistrarCotizacion(ByVal context As HttpContext) As String
Dim Respuesta As New FidelityAppsResponse
Dim RespuestaError As New FidelityAppsResponseError
Dim TieneError As Boolean = False
If TieneError Then
Return JsonConvert.SerializeObject(RespuestaError)
Else
Return JsonConvert.SerializeObject(Respuesta)
End If
End Function
Private Function GetSucursales(ByVal context As HttpContext) As String
Dim Respuesta As New FidelityAppsResponse
Dim RespuestaError As New FidelityAppsResponseError
Dim TieneError As Boolean = False
Dim data As New JArray
Dim DtSucursales As DataTable = GlobalDTSubProyectos(-1, CveEmpresa:=CveEmpresa).FiltraParametros("EsSucursal = True")
If DtSucursales IsNot Nothing Then
Try
For Each Row As DataRow In DtSucursales.Rows
Dim objSucursal As New JObject(
New JProperty("code", Row("CveSubProyecto")),
New JProperty("name", Row("SubProyecto")),
New JProperty("street", Row("Calle")),
New JProperty("no_ext", Row("NoExt")),
New JProperty("no_int", Row("NoInt")),
New JProperty("zip", Row("CP")),
New JProperty("neighborhood", Row("Colonia")),
New JProperty("city", Row("Municipio")),
New JProperty("phone", Row("Telefono")),
New JProperty("email", Row("Correo")),
New JProperty("geo_lat", ""),
New JProperty("geo_lng", ""),
New JProperty("image", "")
)
data.Add(objSucursal)
Next
Catch ex As Exception
TieneError = True
RespuestaError.message = "Ocurrió un error al obtener la sucursales"
End Try
DtSucursales.Dispose()
Else
TieneError = True
End If
If data.Count > 0 Then
Respuesta.data = data
End If
If TieneError Then
Return JsonConvert.SerializeObject(RespuestaError)
Else
Return JsonConvert.SerializeObject(Respuesta)
End If
End Function
Private Function GetExistencia(ByVal context As HttpContext, Codigo As String) As String
Dim respuesta = New With {.isSuccess = False, .message = "", .products = New JArray}
If String.IsNullOrEmpty(Codigo) OrElse Codigo = "-1" Then
respuesta.message = "el parametro 'Sku' es invalido"
Respuesta.isSuccess = False
Return JsonConvert.SerializeObject(respuesta)
End If
Dim unauthorized As Boolean = True
Dim authHeader = context.Request.Headers("Authorization")
If authHeader IsNot Nothing Then
Dim basicAuth As String = authHeader.Replace("Basic ", "")
Dim usernamePasswordArray = Encoding.UTF8.GetString(Convert.FromBase64String(basicAuth)).Split(":"c)
Dim userName = usernamePasswordArray(0)
Dim password = usernamePasswordArray(1)
unauthorized = Not (userName = Me.UsuarioWSE141 AndAlso password = Me.PasswordWSE141)
Else
respuesta.message = "el usuario y/o contraseña son requeridos"
respuesta.isSuccess = False
'context.Response.StatusCode = 401
Return JsonConvert.SerializeObject(respuesta)
End If
If unauthorized Then
respuesta.message = "el usuario y/o contraseña no son validos"
respuesta.isSuccess = False
'context.Response.StatusCode = 401
Return JsonConvert.SerializeObject(respuesta)
End If
Using ObjPS As New ClsProductosServicios()
If ObjPS.GetExistenciasEmpresa(Codigo, CveEmpresa) Then
Dim ArrayPS As New JArray
If ObjPS.DtResultados.Rows.Count > 0 Then
For Each RowPS As DataRow In ObjPS.DtResultados.Rows
Dim producto As New JObject(
New JProperty("sku", RowPS("Codigo")),
New JProperty("stock", RowPS("Existencia"))
)
ArrayPS.Add(producto)
Next
respuesta.isSuccess = True
respuesta.message = "La existencia se obtuvo correctamente"
Else
respuesta.isSuccess = True
respuesta.message = "No se encontro ningun producto"
End If
respuesta.products = ArrayPS
Else
respuesta.isSuccess = False
respuesta.message = "Ocurrió un error al obtener la existencia"
End If
End Using
Return JsonConvert.SerializeObject(respuesta)
End Function
Private Function EnviarInformacion(url As String, payload As String) As String
Dim Retorno As String = "{}"
Try
Using httpClient = New HttpClient()
httpClient.Timeout = New TimeSpan(0, 5, 0)
Using request = New HttpRequestMessage(HttpMethod.Post, New Uri(url))
request.Headers.Add("X-PUBLIC-AUTH", TokenAutorizacion)
Using content = New StringContent(payload, Encoding.UTF8, "application/json")
request.Content = content
Dim response = httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).Result
If response.StatusCode = Net.HttpStatusCode.OK Then
Retorno = response.Content.ReadAsStringAsync().Result
End If
End Using
End Using
End Using
Catch ex As Exception
Retorno = New JObject(New JProperty("Error", ex.ToString())).ToString()
OnError("Ocurrió un error al enviar la informacion", ex)
End Try
Return Retorno
End Function
'Private Function EnviarInformacion2(url As String, payload As String) As String
' Dim Retorno As String = "{}"
' Try
' Dim Request As WebRequest = WebRequest.Create(url)
' Request.Method = "post"
' Request.ContentType = "application/json"
' Request.Headers.Add("token", TokenAutorizacion)
' Dim byteArray As Byte() = Encoding.UTF8.GetBytes(payload)
' Request.ContentLength = byteArray.Length
' Using dataStream As Stream = Request.GetRequestStream()
' dataStream.Write(byteArray, 0, byteArray.Length)
' Using tResponse As WebResponse = Request.GetResponse()
' Using dataStreamResponse As Stream = tResponse.GetResponseStream()
' Using tReader As New StreamReader(dataStreamResponse)
' Retorno = tReader.ReadToEnd()
' End Using
' End Using
' End Using
' End Using
' Catch ex As Exception
' Retorno = New JObject(New JProperty("Error", ex.ToString())).ToString()
' OnError("Ocurrió un error al enviar la informacion", ex)
' End Try
' Return Retorno
'End Function
#Region "C R E A C I Ó N / A C T U A L I Z A C I Ó N - P R O D U C T O S"
Private Function CrearActualizarProductos(Todos As Boolean) As Boolean
Dim Retorno As Boolean = False
Dim CountPeticiones As Integer = 0, CountPeticionesExitosas As Integer = 0
Dim DtPS As DataTable = Nothing
Using ObjPS As New ClsProductosServicios
'OBTERNER PRECIOS DE PUBLICO GENERAL
If ObjPS.GetProductosModificados(CveEmpresa, 44, If(Todos, -1, 1)) Then
DtPS = ObjPS.DtResultados.Copy()
End If
End Using
If DtPS IsNot Nothing Then
If DtPS.Rows.Count > 0 AndAlso DtPS.Rows.Count = 1 Then
Dim Dt As DataTable = DtPS.FiltraPorIndices(0, 0)
Dim payload = New JObject()
payload.Add(New JProperty("products", GenerarPayloadProductos(Dt)))
Dim resp = EnviarInformacion($"{Me.URLBase}api/services/products/import", payload.ToString())
CountPeticiones += 1
If IsValidJson(resp) Then
Dim respuesta = JObject.Parse(resp)
If respuesta("status").ToString() = "success" Then
CountPeticionesExitosas += 1
End If
End If
Else
Dim TotalIndex As Integer = DtPS.Rows.Count - 1
Dim TotaRegistrosPorPeticion As Integer = 500
Dim PrevIndex As Integer = 0
Dim CurrentIndex As Integer = 0
While PrevIndex < TotalIndex
CurrentIndex += TotaRegistrosPorPeticion
If CurrentIndex > TotalIndex Then
CurrentIndex = TotalIndex
End If
Dim Dt As DataTable = DtPS.FiltraPorIndices(PrevIndex, CurrentIndex)
Dim payload = New JObject()
'If Not EsProduccion Then
' payload.Add(New JProperty("deleteNotIncluded", True))
'End If
payload.Add(New JProperty("products", GenerarPayloadProductos(Dt)))
PrevIndex = CurrentIndex
Dim resp = EnviarInformacion($"{Me.URLBase}api/services/products/import", payload.ToString())
CountPeticiones += 1
If IsValidJson(resp) Then
Dim respuesta = JObject.Parse(resp)
If respuesta("status").ToString() = "success" Then
CountPeticionesExitosas += 1
End If
End If
Threading.Thread.Sleep(3000)
End While
End If
End If
If CountPeticionesExitosas = CountPeticiones Then
Retorno = True
End If
Return Retorno
End Function
Private Function GenerarPayloadProductos(DtPS As DataTable) As JArray
Dim ArrayPS As New JArray
For Each RowPS As DataRow In DtPS.Rows
Dim PSData As String() = RowPS("PS").ToString().Split(" ".ToCharArray())
Dim Measurement As String = "", Size As String = "", alt_code As String = ""
If PSData.Length > 0 Then
Measurement = PSData(0)
End If
If PSData.Length > 1 Then
Size = PSData(1)
End If
alt_code = String.Concat(Measurement, Size)
Dim producto As New JObject(
New JProperty("clasificacion", RowPS("Clasificacion")),
New JProperty("category", "Prod"),
New JProperty("pza", RowPS("Unidad")),
New JProperty("sku", RowPS("Codigo")),
New JProperty("name", RowPS("PS")),
New JProperty("measurement", Measurement),
New JProperty("size", Size),
New JProperty("brand", RowPS("Marca")),
New JProperty("price", RowPS("Precio")),
New JProperty("active", RowPS("Estado")),
New JProperty("user", RowPS("UsuarioModifico")),
New JProperty("alt_code", alt_code),
New JProperty("short_description", ""),
New JProperty("description", ""),
New JProperty("currency", 1),
New JProperty("promo_price", RowPS("PrecioPromocion"))
)
ArrayPS.Add(producto)
Next
Return ArrayPS
End Function
#End Region
#Region "A C T U A L I Z A R - P R E C I O S"
'Private Function ActualizarPrecios(Todos As Boolean) As String
' Return EnviarInformacion($"{Me.URLBase}api/services/products/price-import", GetPreciosModificados(Todos))
'End Function
Private Function ActualizarPrecios(Todos As Boolean) As Boolean
Dim Retorno As Boolean = False
Dim CountPeticiones As Integer = 0, CountPeticionesExitosas As Integer = 0
Dim DtPS As DataTable = Nothing
Using ObjPS As New ClsProductosServicios
'OBTERNER PRECIOS DE PUBLICO GENERAL
If ObjPS.GetPreciosModificados(CveEmpresa, 44, If(Todos, -1, 1)) Then
DtPS = ObjPS.DtResultados.Copy()
End If
End Using
If DtPS IsNot Nothing Then
If DtPS.Rows.Count > 0 AndAlso DtPS.Rows.Count = 1 Then
Dim Dt As DataTable = DtPS.FiltraPorIndices(0, 0)
Dim payload = New JObject()
payload.Add(New JProperty("products", GenerarPayloadPrecios(Dt)))
Dim resp = EnviarInformacion($"{Me.URLBase}api/services/products/price-import", payload.ToString())
CountPeticiones += 1
If IsValidJson(resp) Then
Dim respuesta = JObject.Parse(resp)
If respuesta("status").ToString() = "success" Then
CountPeticionesExitosas += 1
End If
End If
Else
Dim TotalIndex As Integer = DtPS.Rows.Count - 1
Dim TotaRegistrosPorPeticion As Integer = 500
Dim PrevIndex As Integer = 0
Dim CurrentIndex As Integer = 0
While PrevIndex < TotalIndex
CurrentIndex += TotaRegistrosPorPeticion
If CurrentIndex > TotalIndex Then
CurrentIndex = TotalIndex
End If
Dim Dt As DataTable = DtPS.FiltraPorIndices(PrevIndex, CurrentIndex)
Dim payload = New JObject()
payload.Add(New JProperty("products", GenerarPayloadPrecios(Dt)))
PrevIndex = CurrentIndex
Dim resp = EnviarInformacion($"{Me.URLBase}api/services/products/price-import", payload.ToString())
CountPeticiones += 1
If IsValidJson(resp) Then
Dim respuesta = JObject.Parse(resp)
If respuesta("status").ToString() = "success" Then
CountPeticionesExitosas += 1
End If
End If
Threading.Thread.Sleep(3000)
End While
End If
End If
Return Retorno
End Function
Private Function GenerarPayloadPrecios(DtPS As DataTable) As JArray
Dim ArrayPS As New JArray
For Each RowPS As DataRow In DtPS.Rows
Dim producto As New JObject(
New JProperty("sku", RowPS("Codigo")),
New JProperty("price", RowPS("Precio")),
New JProperty("promo_price", RowPS("PrecioPromocion"))
)
ArrayPS.Add(producto)
Next
Return ArrayPS
End Function
#End Region
#Region "A C T U A L I Z A R - E X I S T E N C I A S"
'Private Function ActualizarExistencias() As String
' Return EnviarInformacion($"{Me.URLBase}api/services/products/stock", GetPSExistencias())
'End Function
Private Function ActualizarExistencias() As Boolean
Dim Retorno As Boolean = False
Dim CountPeticiones As Integer = 0, CountPeticionesExitosas As Integer = 0
Dim DtPS As DataTable = Nothing
Using ObjPS As New ClsProductosServicios
'OBTERNER PRECIOS DE PUBLICO GENERAL
If ObjPS.GetExistenciasEmpresa("-1", CveEmpresa) Then
DtPS = ObjPS.DtResultados.Copy()
End If
End Using
If DtPS IsNot Nothing Then
If DtPS.Rows.Count > 0 AndAlso DtPS.Rows.Count = 1 Then
Dim Dt As DataTable = DtPS.FiltraPorIndices(0, 0)
Dim payload = New JObject()
payload.Add(New JProperty("stock", GenerarPayloadExistencias(Dt)))
Dim resp = EnviarInformacion($"{Me.URLBase}api/services/products/stock", payload.ToString())
CountPeticiones += 1
If IsValidJson(resp) Then
Dim respuesta = JObject.Parse(resp)
If respuesta("status").ToString() = "success" Then
CountPeticionesExitosas += 1
End If
End If
Else
Dim TotalIndex As Integer = DtPS.Rows.Count - 1
Dim TotaRegistrosPorPeticion As Integer = 500
Dim PrevIndex As Integer = 0
Dim CurrentIndex As Integer = 0
While PrevIndex < TotalIndex
CurrentIndex += TotaRegistrosPorPeticion
If CurrentIndex > TotalIndex Then
CurrentIndex = TotalIndex
End If
Dim Dt As DataTable = DtPS.FiltraPorIndices(PrevIndex, CurrentIndex)
Dim payload = New JObject()
payload.Add(New JProperty("stock", GenerarPayloadExistencias(Dt)))
PrevIndex = CurrentIndex
Dim resp = EnviarInformacion($"{Me.URLBase}api/services/products/stock", payload.ToString())
CountPeticiones += 1
If IsValidJson(resp) Then
Dim respuesta = JObject.Parse(resp)
If respuesta("status").ToString() = "success" Then
CountPeticionesExitosas += 1
End If
End If
Threading.Thread.Sleep(3000)
End While
End If
End If
If CountPeticionesExitosas = CountPeticiones Then
Retorno = True
End If
Return Retorno
End Function
Private Function GenerarPayloadExistencias(DtPS As DataTable) As JArray
Dim ArrayPS As New JArray
For Each RowPS As DataRow In DtPS.Rows
Dim producto As New JObject(
New JProperty("sku", RowPS("Codigo")),
New JProperty("branch_office_code", "01"),
New JProperty("stock", RowPS("Existencia").ToString())
)
ArrayPS.Add(producto)
Next
Return ArrayPS
End Function
#End Region
#Region "A C T U A L I Z A R - E X I S T E N C I A S"
Private Function ActualizarVendedores(Todos As Boolean) As Boolean
Dim Retorno As Boolean = False
Dim CountPeticiones As Integer = 0, CountPeticionesExitosas As Integer = 0
Dim DtVendedores As DataTable = Nothing
Using ObjPS As New ClsProductosServicios
'OBTERNER PRECIOS DE PUBLICO GENERAL
If ObjPS.GetVendedoresModificados(CveEmpresa, If(Todos, -1, 1)) Then
DtVendedores = ObjPS.DtResultados.Copy()
End If
End Using
If DtVendedores IsNot Nothing Then
Dim ArrayVendedores As New JArray
For Each RowVendedor As DataRow In DtVendedores.Rows
Dim VendedorData As String() = RowVendedor("Vendedor").ToString().Split(" ".ToCharArray())
Dim Nombre As String = "", Apellido As String = ""
Select Case VendedorData.Length
Case 1
Nombre = VendedorData(0)
Case 2
Nombre = VendedorData(1)
Apellido = VendedorData(0)
Case 3
Nombre = VendedorData(2)
Apellido = String.Concat(VendedorData(0), " ", VendedorData(1))
Case 4
Nombre = String.Concat(VendedorData(2), " ", VendedorData(3))
Apellido = String.Concat(VendedorData(0), " ", VendedorData(1))
End Select
If VendedorData.Length > 4 Then
Nombre = String.Concat(VendedorData(VendedorData.Length - 2), " ", VendedorData(VendedorData.Length - 1))
Apellido = String.Concat(VendedorData(0), " ", VendedorData(1))
End If
Dim vendedor As New JObject(
New JProperty("email", RowVendedor("Correo")),
New JProperty("password", RowVendedor("Correo")),
New JProperty("name", Nombre),
New JProperty("last_name", Apellido),
New JProperty("type_seller", "Administrador"),
New JProperty("state", RowVendedor("Estado")),
New JProperty("city", RowVendedor("Municipio")),
New JProperty("age", 0),
New JProperty("gender", 0),
New JProperty("address", ""),
New JProperty("code", "")
)
ArrayVendedores.Add(vendedor)
Next
Dim payload = New JObject(New JProperty("sellers", ArrayVendedores)).ToString()
Dim resp = EnviarInformacion($"{Me.URLBase}api/v1/sellers/import", payload)
CountPeticiones += 1
If IsValidJson(resp) Then
Dim respuesta = JObject.Parse(resp)
If respuesta("status").ToString() = "success" Then
CountPeticionesExitosas += 1
End If
End If
End If
Return Retorno
End Function
#End Region
#Region "D E S C A R G A - P D F"
Private Function DescargarFactura(FilePDF As String) As Byte()
Dim Url = New Uri(String.Format("{0}Compras/PopUpVerFactura.aspx?TipoDocto=Ing&File={1}&TipoArchivo=PDF", "http://localhost/", FilePDF))
Dim File As Byte() = Nothing
Try
Using httpClient = New HttpClient()
httpClient.Timeout = New TimeSpan(0, 1, 0)
Using request = New HttpRequestMessage(HttpMethod.Get, Url)
request.Headers.Add("ADSToken", Encripta(String.Format("CVEEMPRESA={0}&TICKS={1}&CVEUSUARIO=100", 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
Public Sub ImprimirbytesPDF(ByVal context As HttpContext, bytes As Byte(), NombreArchivo As String)
'limpio ReportViwer
Dim mimeType As String = Nothing
Dim extension As String = Nothing
Try
bytes = bytes
context.Response.Buffer = True
context.Response.Clear()
context.Response.ContentType = mimeType
context.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", NombreArchivo))
context.Response.BinaryWrite(bytes) ' create the file
context.Response.Flush() ' send it to the client to download
context.Response.SuppressContent = True
context.ApplicationInstance.CompleteRequest()
context.Response.End()
Catch ex As Exception
End Try
End Sub
#End Region
Private Function Parametros(Cadena As String) As Hashtable
Dim P1() As String = Cadena.Split("&"c)
Dim Tmp As String
Dim P2() As String
Dim URLParametros As New Hashtable
For Each Tmp In P1
P2 = Tmp.Replace("%26%", "&").Split("="c)
URLParametros.Add(P2(0).ToString.ToUpper, P2(1))
Next
Return URLParametros
End Function
Private Shared Function IsValidJson(ByVal strInput As String) As Boolean
If String.IsNullOrWhiteSpace(strInput) Then
Return False
End If
strInput = strInput.Trim()
If (strInput.StartsWith("{") AndAlso strInput.EndsWith("}")) OrElse (strInput.StartsWith("[") AndAlso strInput.EndsWith("]")) Then
Try
Dim obj = JToken.Parse(strInput)
Return True
Catch jex As JsonReaderException
Console.WriteLine(jex.Message)
Return False
Catch ex As Exception
Console.WriteLine(ex.ToString())
Return False
End Try
Else
Return False
End If
End Function
Private Class FidelityAppsResponse
Public Property status As String
Public Property data As Object
End Class
Private Class FidelityAppsResponseError
Sub New()
status = "error"
End Sub
Public Property status As String
Public Property message As String
End Class
Private Class AuthMessage
Public Property IsSucces As Boolean
Public Property ErrorMessage As FidelityAppsResponseError
Public Property StatusCode As Integer
End Class
End Class