web service econo

This commit is contained in:
2020-12-01 10:13:05 -07:00
parent 198151c5c2
commit a3c8a8872a
2 changed files with 481 additions and 56 deletions

View File

@@ -2135,6 +2135,71 @@ Public Class ClsProductosServicios
End Try End Try
Return Retorno Return Retorno
End Function End Function
Public Function GetProductosModificados(CveEmpresa As Integer, CvePrecioLista As Integer) As Boolean
Dim Retorno As Boolean = False
DataAdapter("PA_ProductosModificadosGet")
With SqlAdapter.SelectCommand.Parameters
.Add("@CveEmpresa", SqlDbType.Int).Value = CveEmpresa
.Add("@CvePrecioLista", SqlDbType.Int).Value = CvePrecioLista
End With
Try
SqlAdapter.Fill(Data)
Retorno = True
Catch ex As Exception
OnError("Ocurrió un error al obtener los productos modificados.", ex, SqlAdapter.SelectCommand.Parameters.ParametrosInfo())
End Try
Return Retorno
End Function
Public Function GetPreciosModificados(CveEmpresa As Integer, CvePrecioLista As Integer) As Boolean
Dim Retorno As Boolean = False
DataAdapter("PA_ProductosPreciosModificadosGet")
With SqlAdapter.SelectCommand.Parameters
.Add("@CveEmpresa", SqlDbType.Int).Value = CveEmpresa
.Add("@CvePrecioLista", SqlDbType.Int).Value = CvePrecioLista
End With
Try
SqlAdapter.Fill(Data)
Retorno = True
Catch ex As Exception
OnError("Ocurrió un error al obtener los precios modificados.", ex, SqlAdapter.SelectCommand.Parameters.ParametrosInfo())
End Try
Return Retorno
End Function
Public Function GetExistenciasEmpresa(Codigo As String, CveEmpresa As Integer) As Boolean
Dim Retorno As Boolean = False
DataAdapter("PA_ProductosExistenciasEmpresaGet")
With SqlAdapter.SelectCommand.Parameters
.Add("@Codigo", SqlDbType.VarChar).Value = Codigo
.Add("@CveEmpresa", SqlDbType.Int).Value = CveEmpresa
End With
Try
SqlAdapter.Fill(Data)
Retorno = True
Catch ex As Exception
OnError("Ocurrió un error al obtener las existencias.", ex, SqlAdapter.SelectCommand.Parameters.ParametrosInfo())
End Try
Return Retorno
End Function
Public Function GetVendedoresModificados(CveEmpresa As Integer) As Boolean
Dim Retorno As Boolean = False
DataAdapter("PA_VendedoresModificadosGet")
With SqlAdapter.SelectCommand.Parameters
.Add("@CveEmpresa", SqlDbType.Int).Value = CveEmpresa
End With
Try
SqlAdapter.Fill(Data)
Retorno = True
Catch ex As Exception
OnError("Ocurrió un error al obtener los vendedores.", ex, SqlAdapter.SelectCommand.Parameters.ParametrosInfo())
End Try
Return Retorno
End Function
End Class End Class

View File

@@ -2,8 +2,9 @@
Imports System Imports System
Imports System.Web Imports System.Web
Imports System.Data Imports System.Data
Imports System.Net.Http Imports System.Net.Http
Imports System.Net
Imports Newtonsoft.Json Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq Imports Newtonsoft.Json.Linq
Imports Extensiones Imports Extensiones
@@ -28,8 +29,27 @@ Public Class E141 : Implements IHttpHandler
End If End If
End Get End Get
End Property 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 Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "application/json"
Dim retorno As String = "no se encontro la variable" Dim retorno As String = "no se encontro la variable"
Try Try
Dim Params = If(context.Request("P") = Nothing, "", context.Request("P").ToString()) Dim Params = If(context.Request("P") = Nothing, "", context.Request("P").ToString())
@@ -43,57 +63,395 @@ Public Class E141 : Implements IHttpHandler
End If End If
End If End If
Dim Metodo = If(context.Request("Metodo") = Nothing, "", context.Request("Metodo").ToString())
If Metodo = "CrearActualizarProductos" Then
retorno = CrearActualizarProductos()
End If
If Metodo = "ActualizarPrecios" Then
retorno = ActualizarPrecios()
End If
If Metodo = "ActualizarExistencias" Then
retorno = ActualizarExistencias()
End If
If Metodo = "ActualizarVendedores" Then
retorno = ActualizarVendedores()
End If
If Metodo = "GetExistencia" Then
Dim Codigo = If(context.Request("Sku") = Nothing, "", context.Request("Sku").ToString())
retorno = GetExistencia(context, Codigo)
End If
Catch ex As Exception Catch ex As Exception
retorno = ex.ToString() retorno = ex.ToString()
ex.GuardaLog(ex.ToString()) ex.GuardaLog(ex.ToString())
context.Response.Write(retorno)
End Try End Try
context.Response.Write(retorno)
End Sub End Sub
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
'Private Function DescargarFactura(CveVenta As Integer) As Byte() Return JsonConvert.SerializeObject(respuesta)
' Dim Url = New Uri(String.Format("{0}Compras/PopUpVerFactura.aspx?P={1}", ClsPaginas.UrlSitio, Encripta(String.Format("OP=VTA&CVEVENTA={0}&PAG=1&GUARDAR=0", CveVenta)))) End If
' 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}&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
Private Function DescargarFactura(FilePDF As String) As Byte() Dim unauthorized As Boolean = True
Dim Url = New Uri(String.Format("{0}Compras/PopUpVerFactura.aspx?TipoDocto=Ing&File={1}&TipoArchivo=PDF", "http://localhost/", FilePDF))
Dim File As Byte() = Nothing Dim authHeader = context.Request.Headers("Authorization")
Try If authHeader IsNot Nothing Then
Using httpClient = New HttpClient() Dim basicAuth As String = authHeader.Replace("Basic ", "")
httpClient.Timeout = New TimeSpan(0, 1, 0)
Using request = New HttpRequestMessage(HttpMethod.Get, Url) Dim usernamePasswordArray = Encoding.UTF8.GetString(Convert.FromBase64String(basicAuth)).Split(":"c)
request.Headers.Add("ADSToken", Encripta(String.Format("CVEEMPRESA={0}&TICKS={1}&CVEUSUARIO=100", CveEmpresa, DateTime.UtcNow.Ticks)))
Dim response = httpClient.SendAsync(request).Result Dim userName = usernamePasswordArray(0)
If response.StatusCode = Net.HttpStatusCode.OK Then Dim password = usernamePasswordArray(1)
File = response.Content.ReadAsByteArrayAsync().Result unauthorized = Not (userName = Me.UsuarioWSE141 AndAlso password = Me.PasswordWSE141)
End If
End Using Else
End Using respuesta.message = "el usuario y/o contraseña son requeridos"
Catch ex As Exception respuesta.isSuccess = False
File = Nothing 'context.Response.StatusCode = 401
OnError("Ocurrió un error al descargar la factura", ex)
End Try Return JsonConvert.SerializeObject(respuesta)
End If
Return File
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
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.products = ArrayPS
respuesta.isSuccess = True
respuesta.message = "La existencia se obtuvo correctamente"
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()
Using request = New HttpRequestMessage(HttpMethod.Post, New Uri(url))
request.Headers.Add("token", "$2y$10$LGqtRWUloKQmAt.jcUldc.PmS5LJ6l.WU2w1G4PBOTLMVKZRNQFPS")
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", "$2y$10$LGqtRWUloKQmAt.jcUldc.PmS5LJ6l.WU2w1G4PBOTLMVKZRNQFPS")
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
' var httpWebRequest = (httpWebRequest)WebRequest.Create("http://url");
'httpWebRequest.ContentType = "application/json";
'httpWebRequest.Method = "POST";
'Using (var streamWriter = New StreamWriter(httpWebRequest.GetRequestStream()))
'{
' String json = "{\"user\":\"test\"," +
' "\"password\":\"bla\"}";
' streamWriter.Write(json);
'}
'var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
'Using (var streamReader = New StreamReader(httpResponse.GetResponseStream()))
'{
' var result = StreamReader.ReadToEnd();
'}
#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() As String
Return EnviarInformacion2("https://services.fidelityapps/api/services/products/import", GetProductosModificados())
End Function
Private Function GetProductosModificados() As String
Dim Retorno As String = "{}"
Dim DtPS As DataTable = Nothing
Using ObjPS As New ClsProductosServicios
'OBTERNER PRECIOS DE PUBLICO GENERAL
If ObjPS.GetProductosModificados(CveEmpresa, 44) Then
DtPS = ObjPS.DtResultados.Copy()
End If
End Using
If DtPS IsNot Nothing Then
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
Retorno = New JObject(New JProperty("products", ArrayPS)).ToString()
End If
Return Retorno
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() As String
Return EnviarInformacion("https://services.fidelityapps/api/services/products/price-import", GetPreciosModificados())
End Function
Private Function GetPreciosModificados() As String
Dim Retorno As String = "{}"
Dim DtPS As DataTable = Nothing
Using ObjPS As New ClsProductosServicios
'OBTERNER PRECIOS DE PUBLICO GENERAL
If ObjPS.GetPreciosModificados(CveEmpresa, 44) Then
DtPS = ObjPS.DtResultados.Copy()
End If
End Using
If DtPS IsNot Nothing Then
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
Retorno = New JObject(New JProperty("products", ArrayPS)).ToString()
End If
Return Retorno
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("https://services.fidelityapps/api/services/products/stock", GetPSExistencias())
End Function
Private Function GetPSExistencias() As String
Dim Retorno As String = "{}"
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
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"))
)
ArrayPS.Add(producto)
Next
Retorno = New JObject(New JProperty("stock", ArrayPS)).ToString()
End If
Return Retorno
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() As String
Return EnviarInformacion("https://services.fidelityapps/api/v1/sellers/import", GetVendedores())
End Function
Private Function GetVendedores() As String
Dim Retorno As String = "{}"
Dim DtVendedores As DataTable = Nothing
Using ObjPS As New ClsProductosServicios
'OBTERNER PRECIOS DE PUBLICO GENERAL
If ObjPS.GetVendedoresModificados(CveEmpresa) 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
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
Retorno = New JObject(New JProperty("sellers", ArrayVendedores)).ToString()
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 End Function
Public Sub ImprimirbytesPDF(ByVal context As HttpContext, bytes As Byte(), NombreArchivo As String) Public Sub ImprimirbytesPDF(ByVal context As HttpContext, bytes As Byte(), NombreArchivo As String)
@@ -118,18 +476,20 @@ Public Class E141 : Implements IHttpHandler
End Try End Try
End Sub End Sub
Private Function Parametros(Cadena As String) As Hashtable #End Region
Dim P1() As String = Cadena.Split("&"c)
Dim Tmp As String Private Function Parametros(Cadena As String) As Hashtable
Dim P2() As String Dim P1() As String = Cadena.Split("&"c)
Dim Tmp As String
Dim URLParametros As New Hashtable Dim P2() As String
For Each Tmp In P1 Dim URLParametros As New Hashtable
P2 = Tmp.Replace("%26%", "&").Split("="c)
URLParametros.Add(P2(0).ToString.ToUpper, P2(1)) For Each Tmp In P1
Next P2 = Tmp.Replace("%26%", "&").Split("="c)
Return URLParametros URLParametros.Add(P2(0).ToString.ToUpper, P2(1))
Next
Return URLParametros
End Function End Function
End Class End Class