741 lines
35 KiB
Plaintext
741 lines
35 KiB
Plaintext
<%@ WebHandler Language="VB" Class="E119" %>
|
|
|
|
Option Strict On
|
|
Option Explicit On
|
|
|
|
Imports System.Data
|
|
Imports System.IO
|
|
Imports Newtonsoft.Json
|
|
Imports Newtonsoft.Json.Linq
|
|
Imports Extensiones
|
|
|
|
Public Class E119 : Implements IHttpHandler, System.Web.SessionState.IRequiresSessionState
|
|
|
|
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
|
|
Get
|
|
Return False
|
|
End Get
|
|
End Property
|
|
|
|
Private ReadOnly Property CveEmpresa As Integer = 119
|
|
Private ReadOnly Property CveUsuario As Integer = 100
|
|
Private ReadOnly Property NombreCadena As String = "Conexion"
|
|
|
|
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 UsuarioWSE119 As String
|
|
Get
|
|
If IsNothing(System.Configuration.ConfigurationManager.AppSettings("UsuarioWSE119")) Then
|
|
Return ""
|
|
Else
|
|
Return System.Configuration.ConfigurationManager.AppSettings("UsuarioWSE119").ToString()
|
|
End If
|
|
End Get
|
|
End Property
|
|
Public ReadOnly Property PasswordWSE119 As String
|
|
Get
|
|
If IsNothing(System.Configuration.ConfigurationManager.AppSettings("PasswordWSE119")) Then
|
|
Return ""
|
|
Else
|
|
Return System.Configuration.ConfigurationManager.AppSettings("PasswordWSE119").ToString()
|
|
End If
|
|
End Get
|
|
End Property
|
|
|
|
|
|
#Region "V A L I D A - D A T O S"
|
|
Private Function ValidaUsuarioSistema(CveUsuario As Integer, CveEmpresa As Integer) As Usuario
|
|
Dim UsuarioActual As Usuario = Nothing
|
|
Dim NombreCadena As String = ClsPaginas.GlobalNombreCadenaConexion(CveEmpresa)
|
|
Dim ObjUsuarios As New ClsSisUsuarioAutenticacion(NombreCadena:=NombreCadena)
|
|
UsuarioActual = ObjUsuarios.GetUsuarioDetalle(100, CveEmpresa)
|
|
If UsuarioActual IsNot Nothing Then
|
|
HttpContext.Current.Session("UsuarioSIG") = UsuarioActual
|
|
'CreaObjetoEmpresa(UsuarioActual)
|
|
End If
|
|
ObjUsuarios.Dispose()
|
|
|
|
Return UsuarioActual
|
|
End Function
|
|
|
|
'Private Sub CreaObjetoEmpresa(ByRef UsuarioActual As Usuario)
|
|
' Dim ObjEmpresa As New ClsSisEmpresas()
|
|
' If ObjEmpresa.GetEmpresas(UsuarioActual.CveEmpresa, "-1", "-1", "-1", "-1") Then
|
|
' If ObjEmpresa.GetEmpresasFuncionalidades(UsuarioActual.CveEmpresa) Then
|
|
' Dim dttmp As Data.DataTable = ObjEmpresa.DtResultados
|
|
|
|
' Dim EmpresasFuncionalidades As New HybridDictionary
|
|
' For Each Row As Data.DataRow In dttmp.Rows
|
|
' EmpresasFuncionalidades.Add(Convert.ToInt32(Row("CveFuncionalidad")), Row("Valor").ToString)
|
|
' Next
|
|
' ObjEmpresa.Empresa.SetFuncionalidades(EmpresasFuncionalidades)
|
|
' End If
|
|
|
|
' UsuarioActual.Empresa = ObjEmpresa.Empresa
|
|
|
|
' End If
|
|
' ObjEmpresa.Dispose()
|
|
'End Sub
|
|
#End Region
|
|
|
|
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
|
|
Dim retorno As String = ""
|
|
Dim MsgLog As New StringBuilder
|
|
MsgLog.AppendLine("Inicia Petición.")
|
|
Try
|
|
Dim Metodo As String = If(context.Request("Metodo") = Nothing, "", context.Request("Metodo").ToString())
|
|
MsgLog.AppendLine(Metodo)
|
|
If Metodo = "BASF_POG40" Then
|
|
context.Response.ContentType = "application/json"
|
|
Dim Auth As AuthMessage = ValidarSolicitud(context)
|
|
|
|
If Auth.IsSuccess Then
|
|
retorno = ConsultaDatos(context)
|
|
Else
|
|
context.Response.StatusCode = Auth.StatusCode
|
|
retorno = JsonConvert.SerializeObject(Auth.ErrorMessage)
|
|
End If
|
|
|
|
End If
|
|
|
|
If Metodo = "ConsultarProductos" Then
|
|
context.Response.ContentType = "application/json"
|
|
Dim Auth As AuthMessage = ValidarSolicitud(context)
|
|
|
|
If Auth.IsSuccess Then
|
|
retorno = ConsultaProductos(context)
|
|
Else
|
|
context.Response.StatusCode = Auth.StatusCode
|
|
retorno = JsonConvert.SerializeObject(Auth.ErrorMessage)
|
|
End If
|
|
End If
|
|
|
|
If Metodo = "ConsultarClasificaciones" Then
|
|
context.Response.ContentType = "application/json"
|
|
Dim Auth As AuthMessage = ValidarSolicitud(context)
|
|
|
|
If Auth.IsSuccess Then
|
|
retorno = ConsultaClasificaciones(context)
|
|
Else
|
|
context.Response.StatusCode = Auth.StatusCode
|
|
retorno = JsonConvert.SerializeObject(Auth.ErrorMessage)
|
|
End If
|
|
End If
|
|
|
|
If Metodo = "RegistraRemision" Then
|
|
|
|
context.Response.ContentType = "application/json"
|
|
Dim Auth As AuthMessage = ValidarSolicitud(context)
|
|
MsgLog.AppendLine("Validado:" & Auth.IsSuccess)
|
|
If Auth.IsSuccess Then
|
|
retorno = RegistraRemision(context, MsgLog)
|
|
Else
|
|
context.Response.StatusCode = Auth.StatusCode
|
|
retorno = JsonConvert.SerializeObject(Auth.ErrorMessage)
|
|
End If
|
|
End If
|
|
|
|
context.Response.Write(retorno)
|
|
|
|
Catch ex As Exception
|
|
context.Response.ContentType = "text/html"
|
|
MsgLog.AppendLine("Error de procesamiento:" & ex.Message)
|
|
|
|
Dim respuesta As New AuthMessage
|
|
respuesta.ErrorMessage = New ResponseMsgError() With {.message = "La solicitud no se pudo procesar."}
|
|
respuesta.IsSuccess = False
|
|
respuesta.StatusCode = 200
|
|
retorno = JsonConvert.SerializeObject(respuesta.ErrorMessage)
|
|
context.Response.Write(retorno)
|
|
|
|
End Try
|
|
MsgLog.ToString.GuardaLogAD("LogE119")
|
|
End Sub
|
|
|
|
Private Function ValidarSolicitud(ByVal context As HttpContext) As AuthMessage
|
|
Dim unauthorized As Boolean = True
|
|
Dim respuesta As New AuthMessage
|
|
|
|
Dim authHeader As String = context.Request.Headers("Authorization")
|
|
If authHeader IsNot Nothing Then
|
|
Dim basicAuth As String = authHeader.Replace("Basic ", "")
|
|
|
|
Dim usernamePasswordArray As String() = Encoding.UTF8.GetString(Convert.FromBase64String(basicAuth)).Split(":"c)
|
|
|
|
Dim userName As String = usernamePasswordArray(0)
|
|
Dim password As String = usernamePasswordArray(1)
|
|
unauthorized = Not (userName = Me.UsuarioWSE119 AndAlso password = Me.PasswordWSE119)
|
|
|
|
Else
|
|
respuesta.ErrorMessage = New ResponseMsgError() With {.message = "el usuario y/o contraseña son requeridos"}
|
|
respuesta.IsSuccess = False
|
|
respuesta.StatusCode = 200
|
|
|
|
Return respuesta
|
|
End If
|
|
|
|
If unauthorized Then
|
|
respuesta.ErrorMessage = New ResponseMsgError() With {.message = "el usuario y/o contraseña no son validos"}
|
|
respuesta.IsSuccess = False
|
|
respuesta.StatusCode = 200
|
|
|
|
Return respuesta
|
|
Else
|
|
respuesta.ErrorMessage = Nothing
|
|
respuesta.IsSuccess = True
|
|
respuesta.StatusCode = 200
|
|
|
|
Return respuesta
|
|
End If
|
|
|
|
End Function
|
|
|
|
|
|
Private Function ConsultaDatos(ByVal context As HttpContext) As String
|
|
Dim Respuesta As New ResponseMsg
|
|
Dim RespuestaError As New ResponseMsgError
|
|
Dim TieneError As Boolean = False
|
|
|
|
Dim strFecha As String = If(context.Request("Fecha") = Nothing, "", context.Request("Fecha").ToString())
|
|
|
|
If String.IsNullOrEmpty(strFecha) Then
|
|
RespuestaError.message = "Debe especificar una fecha"
|
|
context.Response.StatusCode = 200
|
|
Return JsonConvert.SerializeObject(RespuestaError)
|
|
End If
|
|
|
|
If Not IsDate(strFecha) Then
|
|
RespuestaError.message = "La fecha no tiene el formato correcto"
|
|
context.Response.StatusCode = 200
|
|
Return JsonConvert.SerializeObject(RespuestaError)
|
|
End If
|
|
|
|
Dim Fecha As DateTime = strFecha.ToDateTime()
|
|
Dim Facturas As JArray = Nothing
|
|
Dim Stock As JArray = Nothing
|
|
|
|
If Fecha > MinFecha Then
|
|
Using ObjInventario As New ClsInventarios
|
|
If ObjInventario.GetJAM_BASF_POG(Fecha) AndAlso ObjInventario.DataSetResultados IsNot Nothing Then
|
|
Facturas = JArray.Parse(ObjInventario.DataSetResultados.Tables(0).DataTableToJSONIPP())
|
|
Stock = JArray.Parse(ObjInventario.DataSetResultados.Tables(1).DataTableToJSONIPP())
|
|
Else
|
|
RespuestaError.message = "no se pudo obtener los datos"
|
|
TieneError = True
|
|
End If
|
|
End Using
|
|
Dim Msg As String = "Información día " & Fecha.ToShortDateString & If(RespuestaError.message <> "", " Error: " & RespuestaError.message, "")
|
|
Msg.GuardaLogAD("LogE119")
|
|
Else
|
|
RespuestaError.message = "la fecha no es leida correctamente"
|
|
TieneError = True
|
|
End If
|
|
|
|
If TieneError Then
|
|
context.Response.StatusCode = 200
|
|
Return JsonConvert.SerializeObject(RespuestaError)
|
|
Else
|
|
context.Response.StatusCode = 200
|
|
Try
|
|
Respuesta.data = New JObject(New JProperty("Facturas", Facturas), New JProperty("Stock", Stock))
|
|
Respuesta.message = "Los datos se obtuvieron correctamente"
|
|
Return JsonConvert.SerializeObject(Respuesta)
|
|
Catch ex As Exception
|
|
RespuestaError.message = "Ocurrió un error al generar la petición"
|
|
Return JsonConvert.SerializeObject(RespuestaError)
|
|
End Try
|
|
|
|
End If
|
|
End Function
|
|
|
|
Private Function ConsultaProductos(ByVal context As HttpContext) As String
|
|
Dim Respuesta As New ResponseMsg
|
|
Dim RespuestaError As New ResponseMsgError
|
|
Dim TieneError As Boolean = False
|
|
|
|
Dim CveClasificacion As String = If(context.Request("CveClasificacion") = Nothing, "", context.Request("CveClasificacion").ToString())
|
|
|
|
If String.IsNullOrEmpty(CveClasificacion) Then
|
|
CveClasificacion = "-1"
|
|
End If
|
|
|
|
Dim Productos As JArray = Nothing
|
|
Dim Usuario As Usuario = ValidaUsuarioSistema(100, CveEmpresa)
|
|
Using ObjInventario As New ClsInventarios
|
|
If ObjInventario.GetJAM_APIs(1, CveClasificacion:=CveClasificacion.ToEntero()) AndAlso ObjInventario.DtResultados IsNot Nothing Then
|
|
Productos = JArray.Parse(ObjInventario.DtResultados.FiltroPrimeroValor("JsonTexto"))
|
|
Else
|
|
RespuestaError.message = "no se pudo obtener los datos"
|
|
TieneError = True
|
|
End If
|
|
End Using
|
|
|
|
Dim Msg As String = "Información día " & ClsPaginas.NowADS().ToShortDateString & If(RespuestaError.message <> "", " Error: " & RespuestaError.message, "")
|
|
Msg.GuardaLogAD("LogE119")
|
|
|
|
If TieneError Then
|
|
context.Response.StatusCode = 200
|
|
Return JsonConvert.SerializeObject(RespuestaError)
|
|
Else
|
|
context.Response.StatusCode = 200
|
|
Try
|
|
Respuesta.data = New JObject(New JProperty("Productos", Productos))
|
|
Respuesta.message = "Los datos se obtuvieron correctamente"
|
|
Return JsonConvert.SerializeObject(Respuesta)
|
|
Catch ex As Exception
|
|
RespuestaError.message = "Ocurrió un error al generar la petición"
|
|
Return JsonConvert.SerializeObject(RespuestaError)
|
|
End Try
|
|
End If
|
|
End Function
|
|
|
|
Private Function ConsultaClasificaciones(ByVal context As HttpContext) As String
|
|
Dim Respuesta As New ResponseMsg
|
|
Dim RespuestaError As New ResponseMsgError
|
|
Dim TieneError As Boolean = False
|
|
|
|
Dim Clasificaciones As JArray = Nothing
|
|
Dim Usuario As Usuario = ValidaUsuarioSistema(100, CveEmpresa)
|
|
|
|
Try
|
|
'Clasificaciones = JArray.Parse(ClsPaginas.GlobalDTClasificaciones(CveEmpresa).FiltraParametros("", DistinctColumns:={"CveClasificacion", "Clasificacion"}).DataTableToJSONIPP())
|
|
Using ObjInventario As New ClsInventarios
|
|
If ObjInventario.GetJAM_APIs(2, CveClasificacion:=-1) AndAlso ObjInventario.DtResultados IsNot Nothing Then
|
|
Clasificaciones = JArray.Parse(ObjInventario.DtResultados.DataTableToJSONIPP())
|
|
Else
|
|
RespuestaError.message = "no se pudo obtener los datos"
|
|
TieneError = True
|
|
End If
|
|
End Using
|
|
Catch ex As Exception
|
|
RespuestaError.message = "no se pudo obtener los datos"
|
|
TieneError = True
|
|
End Try
|
|
|
|
Dim Msg As String = "Información día " & ClsPaginas.NowADS().ToShortDateString & If(RespuestaError.message <> "", " Error: " & RespuestaError.message, "")
|
|
Msg.GuardaLogAD("LogE119")
|
|
|
|
If TieneError Then
|
|
context.Response.StatusCode = 200
|
|
Return JsonConvert.SerializeObject(RespuestaError)
|
|
Else
|
|
context.Response.StatusCode = 200
|
|
Try
|
|
Respuesta.data = New JObject(New JProperty("Clasificaciones", Clasificaciones))
|
|
Respuesta.message = "Los datos se obtuvieron correctamente"
|
|
Return JsonConvert.SerializeObject(Respuesta)
|
|
Catch ex As Exception
|
|
RespuestaError.message = "Ocurrió un error al generar la petición"
|
|
Return JsonConvert.SerializeObject(RespuestaError)
|
|
End Try
|
|
End If
|
|
End Function
|
|
|
|
Private Function RegistraRemision(ByVal context As HttpContext, ByRef MsgLog As StringBuilder) As String
|
|
|
|
Dim TieneError As Boolean = False
|
|
Dim JsonRequest As JObject = Nothing
|
|
Dim Respuesta As New ResponseMsg
|
|
Dim RespuestaError As New ResponseMsgError
|
|
|
|
Try
|
|
MsgLog.AppendLine("1.0 Registra")
|
|
If context.Request.InputStream IsNot Nothing Then
|
|
Using reader As New StreamReader(context.Request.InputStream)
|
|
Dim json As String = reader.ReadToEnd
|
|
json = json.TrimStart("["c).TrimEnd("]"c) 'quito corchetes que están conteniendo el json, elimino al inicio y al final
|
|
If Not String.IsNullOrEmpty(json) Then
|
|
JsonRequest = JObject.Parse(json)
|
|
If JsonRequest Is Nothing Then
|
|
TieneError = True
|
|
End If
|
|
Else
|
|
TieneError = True
|
|
End If
|
|
MsgLog.AppendLine("json:" & json)
|
|
End Using
|
|
End If
|
|
|
|
MsgLog.AppendLine("1.1 accedido")
|
|
If TieneError Then
|
|
RespuestaError.message = "No se pudo procesar la solicitud - Formato mal formado (1.1)"
|
|
context.Response.StatusCode = 200
|
|
Return JsonConvert.SerializeObject(RespuestaError)
|
|
End If
|
|
|
|
If Not TieneError Then
|
|
Dim Usuario As Usuario = ValidaUsuarioSistema(100, CveEmpresa)
|
|
Dim ObjFactura As Modelos.Factura = Nothing
|
|
Dim Resp As New Modelos.Factura.MMensajeFactura
|
|
If Usuario IsNot Nothing Then
|
|
MsgLog.AppendLine("1.1 Validado")
|
|
Dim ObjClientes As New ClsClientes()
|
|
Dim ObjInventario As New ClsInventarios(ObjClientes.IniciaTransacSQL())
|
|
Dim CveSubProyecto, CveCliente, CveMoneda, CvePS As Integer
|
|
Dim Cantidad, PU, Descuento As Decimal
|
|
Dim CveDireccionEnvio As Integer = 0
|
|
Dim Obs As String = ""
|
|
Dim IdEcommerce As Integer = 0
|
|
CveSubProyecto = 12659 ' fijo Ecommerce
|
|
CveCliente = 0
|
|
CveMoneda = 1
|
|
Descuento = 0
|
|
MsgLog.AppendLine("1.3 billing")
|
|
Dim RFC As String = ""
|
|
Dim NombreCliente As String = ""
|
|
Dim RegimenCliente As String = ""
|
|
Dim UsoCFDI As String = ""
|
|
Dim CveUsoCFDI As Integer = -1
|
|
IdEcommerce = JsonRequest("wp_sale_id").ToEntero
|
|
Dim Registrada As Boolean = False
|
|
If IdEcommerce > 0 Then
|
|
Dim objVenta As New ClsVentas
|
|
If objVenta.GetVentaTerminal(IdEcommerce, MinFecha, CveSubProyecto, CveEmpresa) Then
|
|
Dim dr As DataRow = objVenta.DtResultados.FiltroPrimero("")
|
|
If dr IsNot Nothing Then
|
|
|
|
Dim data As New JArray
|
|
Dim objSucursal As New JObject(
|
|
New JProperty("Cve", dr("CveVenta")),
|
|
New JProperty("SerieFolio", dr("SerieFolio"))
|
|
)
|
|
data.Add(objSucursal)
|
|
Respuesta.status = "error"
|
|
Respuesta.data = data
|
|
Respuesta.message = "Folio registrado previamente."
|
|
MsgLog.AppendLine("Folio registrado previamente.")
|
|
Registrada = True
|
|
End If
|
|
End If
|
|
objVenta.Dispose()
|
|
End If
|
|
|
|
If Registrada Then
|
|
context.Response.StatusCode = 200
|
|
Return JsonConvert.SerializeObject(Respuesta)
|
|
End If
|
|
|
|
Dim bill As JToken = Nothing
|
|
If JsonRequest("billing") IsNot Nothing AndAlso JsonRequest("rfc_info") IsNot Nothing AndAlso JsonRequest("rfc_info").Count > 0 Then
|
|
Dim billrfc As JToken
|
|
|
|
If JsonRequest("rfc_info").Type = JTokenType.Array Then billrfc = JsonRequest("rfc_info").First Else billrfc = JsonRequest("rfc_info")
|
|
If JsonRequest("billing").Type = JTokenType.Array Then bill = JsonRequest("billing").First Else bill = JsonRequest("billing")
|
|
|
|
RFC = billrfc("rfc_client").ToString()
|
|
RegimenCliente = billrfc("regimen_client").ToString()
|
|
UsoCFDI = billrfc("cfdi").ToString()
|
|
NombreCliente = bill("first_name").ToString() & " " & bill("last_name").ToString()
|
|
'si vienen vacío toman datos predeterminados
|
|
If RFC = "" Then RFC = "XAXX010101000"
|
|
If RegimenCliente = "" Then RegimenCliente = "616"
|
|
If UsoCFDI = "" Then UsoCFDI = "S01"
|
|
|
|
If Not String.IsNullOrEmpty(UsoCFDI) Then
|
|
CveUsoCFDI = ClsPaginas.GlobalDTSATUsosCFDI().FiltroPrimeroValor("CveUsoCFDI", $"UsoCFDI = '{UsoCFDI.Trim}'").ToEntero()
|
|
End If
|
|
Else
|
|
TieneError = True
|
|
Resp.Mensajes.Add("no existe cliente definido")
|
|
End If
|
|
|
|
If Not TieneError Then
|
|
'BUSCAR SI ESTÁ REGISTRADO EL CLIENTE
|
|
If ObjClientes.GetClientes(-1, "-1", "-1", "-1", RFC, "-1", "-1", -1, CveEmpresa, 1, TipoCliente:=-1, TopSelect:=1) Then
|
|
If ObjClientes.DtResultados.Rows.Count > 0 Then
|
|
'Resp.TieneError = False
|
|
CveCliente = ObjClientes.CveCliente
|
|
'Resp.Mensajes.Add("El RFC ya existe en el sistema")
|
|
End If
|
|
End If
|
|
MsgLog.AppendLine("1.4 verificar cliente.")
|
|
|
|
If CveCliente = 0 Then
|
|
' 'DATOS DE BILLING
|
|
MsgLog.AppendLine("1.5 crear cliente")
|
|
If bill IsNot Nothing Then
|
|
Dim CveEstado As Integer = -1
|
|
Dim CveRegimenFiscal As Integer = -1
|
|
|
|
Dim Direccion As String = If(bill("address_1") Is Nothing, "", bill("address_1").ToString())
|
|
Dim NumExt As String = ""
|
|
Dim NumInt As String = ""
|
|
Dim Colonia As String = ""
|
|
Dim Ciudad As String = If(bill("city") Is Nothing, "", bill("city").ToString())
|
|
Dim Localidad As String = If(bill("city") Is Nothing, "", bill("city").ToString())
|
|
Dim CP As String = If(bill("postcode") Is Nothing, "", bill("postcode").ToString())
|
|
Dim Telefono As String = If(bill("phone") Is Nothing, "", bill("phone").ToString())
|
|
Dim Correo As String = If(bill("email") Is Nothing, "", bill("email").ToString())
|
|
Dim Estado As String = If(bill("state") Is Nothing, "", bill("state").ToString())
|
|
If Not String.IsNullOrEmpty(Estado) Then
|
|
CveEstado = ClsPaginas.GlobalDTGralEstados("MEX").FiltroPrimeroValor("CveEstado", $"NombreEstado = '{Estado.Trim}'").ToEntero()
|
|
If CveEstado <= 0 Then 'SI NO ENCUENTRA EL ESTADO INGRESA EL DE SONORA
|
|
CveEstado = 26
|
|
End If
|
|
Else
|
|
CveEstado = 26
|
|
End If
|
|
If Not String.IsNullOrEmpty(RegimenCliente) Then
|
|
CveRegimenFiscal = ClsPaginas.GlobalDTRegimenesFiscales().FiltroPrimeroValor("CveRegimenFiscal", $"CodigoRegimenFiscal = '{RegimenCliente.Trim}'").ToEntero()
|
|
End If
|
|
|
|
If ObjClientes.AgregarClienteNoFrecuente(NombreCliente, Direccion, NumExt, NumInt, Colonia, Localidad, Ciudad, CveEstado, RFC, CP, Telefono, Correo, CveSubProyecto, CveUsuario, CveEmpresa, "", -1, -1, CveRegimenFiscal:=CveRegimenFiscal, CveUsoCFDI:=CveUsoCFDI) Then
|
|
If ObjClientes.DtResultados.Rows.Count > 0 Then
|
|
CveCliente = ObjClientes.DtResultados(0)("CveCliente").ToString().ToEntero()
|
|
MsgLog.AppendLine("1.5.5 cliente creado")
|
|
End If
|
|
End If
|
|
Else
|
|
MsgLog.AppendLine("1.5.9 sin datos cliente")
|
|
TieneError = True
|
|
Resp.Mensajes.Add("no existen datos del cliente.")
|
|
End If
|
|
|
|
End If
|
|
If JsonRequest("shipping") IsNot Nothing AndAlso Not TieneError Then
|
|
Dim jship As JToken
|
|
If JsonRequest("shipping").Type = JTokenType.Array Then jship = JsonRequest("shipping").First Else jship = JsonRequest("shipping")
|
|
Dim CveEstado As Integer = -1
|
|
Dim Direccion As String = If(jship("address_1") Is Nothing, "", jship("address_1").ToString())
|
|
Dim NumExt As String = ""
|
|
Dim NumInt As String = ""
|
|
Dim Colonia As String = ""
|
|
Dim Ciudad As String = If(jship("city") Is Nothing, "", jship("city").ToString())
|
|
Dim Localidad As String = If(jship("city") Is Nothing, "", jship("city").ToString())
|
|
Dim CP As String = If(jship("postcode") Is Nothing, "", jship("postcode").ToString())
|
|
Dim Telefono As String = If(jship("phone") Is Nothing, "", jship("phone").ToString())
|
|
Dim Correo As String = If(jship("email") Is Nothing, "", jship("email").ToString())
|
|
Dim Estado As String = If(jship("state") Is Nothing, "", jship("state").ToString())
|
|
If Not String.IsNullOrEmpty(Estado) Then
|
|
CveEstado = ClsPaginas.GlobalDTGralEstados("MEX").FiltroPrimeroValor("CveEstado", $"NombreEstado = '{Estado.Trim}'").ToEntero()
|
|
If CveEstado <= 0 Then 'SI NO ENCUENTRA EL ESTADO INGRESA EL DE SONORA
|
|
CveEstado = 26
|
|
End If
|
|
Else
|
|
CveEstado = 26
|
|
End If
|
|
|
|
If ObjClientes.DireccionEnvioGet(-1, CveCliente, -1) Then
|
|
Dim dtt As DataTable = ObjClientes.DtResultados
|
|
If dtt IsNot Nothing AndAlso dtt.Rows.Count > 0 Then
|
|
dtt = dtt.FiltraParametros($"EnvioDireccion = '{Direccion}' and EnvioCP = '{CP}'")
|
|
If dtt.Rows.Count > 0 Then
|
|
CveDireccionEnvio = dtt.FiltroPrimeroValor("CveDireccionEnvio").ToEntero
|
|
End If
|
|
Else
|
|
CveDireccionEnvio = ObjClientes.DireccionEnvioAdd(CveCliente, Direccion, NumExt, NumInt, Colonia, Ciudad, Estado, CP, "", 100, 1)
|
|
End If
|
|
End If
|
|
Else
|
|
MsgLog.AppendLine("1.5.9 sin datos cliente")
|
|
TieneError = True
|
|
Resp.Mensajes.Add("no existen datos del cliente")
|
|
End If
|
|
|
|
MsgLog.AppendLine("1.6 inicio generar venta")
|
|
ObjFactura = Modelos.Factura.CrearVentaNueva(Usuario, CveSubProyecto, CveCliente, CveMoneda, "Rem")
|
|
ObjFactura.AtencionA = NombreCliente
|
|
MsgLog.AppendFormat("1.6.0 objeto creado {0}", If(ObjFactura IsNot Nothing, "si", "no"))
|
|
|
|
If JsonRequest("shipping_lines") IsNot Nothing Then
|
|
Dim jshiplines As JToken
|
|
If JsonRequest("shipping_lines").Type = JTokenType.Array Then jshiplines = JsonRequest("shipping_lines").First Else jshiplines = JsonRequest("shipping_lines")
|
|
|
|
'shiping_lines/ method_id: free_shipping/local_pickup
|
|
Dim Entrega As String = If(jshiplines("method_id") Is Nothing, "", jshiplines("method_id").ToString())
|
|
ObjFactura.Alfa1 = Entrega
|
|
End If
|
|
|
|
ObjFactura.CveDireccionEnvio = CveDireccionEnvio
|
|
ObjFactura.CveVentaTerminal = IdEcommerce
|
|
ObjFactura.CveUsoCFDI = CveUsoCFDI
|
|
|
|
If JsonRequest("line_items") IsNot Nothing Then
|
|
Dim ListaPS As JArray = JArray.Parse(JsonRequest("line_items").ToString())
|
|
Dim Consec As Integer = 1
|
|
MsgLog.AppendLine("1.6.1 recorrer ps")
|
|
For Each JsonPS As JObject In ListaPS
|
|
Cantidad = JsonPS("quantity").ToString.ToDecimal()
|
|
PU = JsonPS("price").ToString.ToDecimal()
|
|
CvePS = ClsPaginas.GlobalDTPSSimplificado(CveEmpresa, Codigo:=JsonPS("sku").ToString()).FiltroPrimeroValor("CvePS").ToEntero()
|
|
|
|
ObjFactura.AgregarPS(CvePS, Cantidad, PU, Descuento, Obs, CveSubProyecto:=CveSubProyecto)
|
|
MsgLog.AppendLine("1.6.1 agregar ps a venta")
|
|
''VALIDAR QUE SEA EL MISMO PRODUCTO
|
|
If CvePS <= 0 Then
|
|
TieneError = True
|
|
'Retorno.Mensajes.Add(String.Format("No se encontró el producto: {0}", JsonPS("name").ToString()))
|
|
Exit For
|
|
End If
|
|
Consec += 1
|
|
Next
|
|
ObjFactura.CalculaTotales()
|
|
Else
|
|
ObjFactura = Nothing
|
|
TieneError = True
|
|
Resp.Mensajes.Add("no existen productos definidos")
|
|
End If
|
|
|
|
If ObjFactura IsNot Nothing AndAlso Not TieneError Then
|
|
MsgLog.AppendLine("1.7 agregar la remision")
|
|
Resp = ObjFactura.EmitirFactura(False, Transac:=ObjClientes.IniciaTransacSQL())
|
|
|
|
If Resp.CveVenta > 0 Then
|
|
MsgLog.AppendLine("2.0 remisión registrada")
|
|
Dim data As New JArray
|
|
Dim objSucursal As New JObject(
|
|
New JProperty("Cve", Resp.CveVenta),
|
|
New JProperty("SerieFolio", Resp.SerieFolio)
|
|
)
|
|
data.Add(objSucursal)
|
|
Respuesta.status = "success"
|
|
Respuesta.data = data
|
|
Else
|
|
MsgLog.AppendLine("1.8 error al agregar la remision.")
|
|
TieneError = True
|
|
End If
|
|
|
|
If TieneError Then
|
|
Dim sb As New StringBuilder()
|
|
For Each msg As String In Resp.Mensajes
|
|
sb.AppendFormat("{0}. ", msg)
|
|
Next
|
|
RespuestaError.message = sb.ToString()
|
|
End If
|
|
Else
|
|
TieneError = True
|
|
Dim sb As New StringBuilder()
|
|
For Each msg As String In Resp.Mensajes
|
|
sb.AppendFormat("{0}. ", msg)
|
|
Next
|
|
RespuestaError.message = sb.ToString()
|
|
End If
|
|
End If
|
|
|
|
If TieneError Then
|
|
ObjClientes.RollBack()
|
|
ObjClientes.Dispose()
|
|
ObjInventario.Dispose()
|
|
Dim sb As New StringBuilder()
|
|
For Each msg As String In Resp.Mensajes
|
|
sb.AppendFormat("{0}. ", msg)
|
|
Next
|
|
RespuestaError.message = sb.ToString()
|
|
|
|
MsgLog.Append("99.0 ocurrió un error en el proceso")
|
|
Else
|
|
MsgLog.Append("4.0 proceso terminado")
|
|
MsgLog.AppendFormat("Folio:{0} Estatus:", Resp.SerieFolio, Respuesta.status)
|
|
ObjClientes.Commit()
|
|
ObjClientes.Dispose()
|
|
ObjInventario.Dispose()
|
|
End If
|
|
If ObjFactura IsNot Nothing Then ObjFactura.Dispose()
|
|
End If
|
|
End If
|
|
|
|
Catch ex As Exception
|
|
TieneError = True
|
|
Finally
|
|
'MsgLog.ToString.GuardaLogAD("LogE119")
|
|
End Try
|
|
|
|
If TieneError Then
|
|
context.Response.StatusCode = 200
|
|
Return JsonConvert.SerializeObject(RespuestaError)
|
|
Else
|
|
context.Response.StatusCode = 200
|
|
Return JsonConvert.SerializeObject(Respuesta)
|
|
End If
|
|
End Function
|
|
|
|
Private Class ResponseMsg
|
|
Sub New()
|
|
status = "success"
|
|
End Sub
|
|
Public Property status As String
|
|
Public Property data As Object
|
|
Public Property message As String
|
|
End Class
|
|
|
|
Private Class ResponseMsgError
|
|
Sub New()
|
|
status = "error"
|
|
End Sub
|
|
Public Property status As String
|
|
Public Property message As String
|
|
End Class
|
|
|
|
Private Class AuthMessage
|
|
Public Property IsSuccess As Boolean
|
|
Public Property ErrorMessage As ResponseMsgError
|
|
Public Property StatusCode As Integer
|
|
End Class
|
|
|
|
'Private Function ActualizarExistenciasJson(Todos As Boolean) As String
|
|
' Dim payload = New JObject()
|
|
|
|
' Dim CountPeticiones As Integer = 0, CountPeticionesExitosas As Integer = 0
|
|
|
|
' Dim DtPS As DataTable = Nothing
|
|
' Using ObjPS As New ClsProductosServicios
|
|
' If ObjPS.GetExistenciasEmpresa("-1", CveEmpresa) Then
|
|
' DtPS = ObjPS.DtResultados.Copy()
|
|
' End If
|
|
' End Using
|
|
|
|
' If DtPS IsNot Nothing Then
|
|
' payload.Add(New JProperty("stock", GenerarPayloadExistencias(DtPS)))
|
|
' End If
|
|
|
|
' Return payload.ToString()
|
|
'End Function
|
|
|
|
|
|
|
|
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 As JToken = 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
|
|
|
|
End Class |