2463 lines
112 KiB
Plaintext
2463 lines
112 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
|
|
Return "$2y$10$LGqtRWUloKQmAt.jcUldc.PmS5LJ6l.WU2w1G4PBOTLMVKZRNQFPS"
|
|
End Get
|
|
End Property
|
|
|
|
Public ReadOnly Property URLBase As String
|
|
Get
|
|
Return "https://services.fidelityapps.mx/"
|
|
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
|
|
|
|
ReadOnly Property GlobalDTPS(CveEmpresa As Integer, Optional CvePS As Integer = -1, Optional SATClavePS As String = "-1", Optional AplicaParaVenta As Integer = -1, Optional Estatus As Integer = -1, Optional Codigo As String = "-1") As DataTable
|
|
Get
|
|
Dim ObjPS As New ClsProductosServicios
|
|
|
|
If ObjPS.GetPS(CvePS, -1, CveEmpresa, Codigo:=Codigo, SATClavePS:=SATClavePS, pAplicaParaVenta:=AplicaParaVenta, pEstado:=Estatus) Then
|
|
GlobalDTPS = ObjPS.DtResultados
|
|
Else
|
|
GlobalDTPS = Nothing
|
|
End If
|
|
|
|
ObjPS.Dispose()
|
|
End Get
|
|
End Property
|
|
|
|
Public Property GlobalDTPSSimplificado(Optional CveClasificacion As Integer = -1, Optional Codigo As String = "-1", Optional Estatus As Integer = 1, Optional AplicaParaVenta As Integer = -1, Optional CvePS As Integer = -1) As DataTable
|
|
Get
|
|
Dim AppNombre As String = String.Format("GlobalDTPSSimplificado-{0}", CveEmpresa)
|
|
If CveEmpresa <> -1 Then
|
|
'sino existe, recarga los datos
|
|
If HttpContext.Current.Application(AppNombre) Is Nothing Then
|
|
Dim ObjPS As New ClsProductosServicios
|
|
If ObjPS.GetPSSimplificado(CveEmpresa) Then HttpContext.Current.Application(AppNombre) = ObjPS.DtResultados.AsEnumerable()
|
|
ObjPS.Dispose()
|
|
|
|
End If
|
|
|
|
|
|
Dim Cons = DirectCast(HttpContext.Current.Application(AppNombre), EnumerableRowCollection(Of DataRow))
|
|
|
|
Cons = Cons.Where((Function(a) Convert.ToInt32(a!CveEmpresa) = CveEmpresa))
|
|
If CveClasificacion >= 0 Then Cons = Cons.Where((Function(a) Convert.ToInt32(a!CveClasificacion) = CveClasificacion))
|
|
Codigo = Codigo.ToUpper()
|
|
If Codigo <> "-1" Then Cons = Cons.Where((Function(a) Convert.ToString(a!Codigo).ToUpper() = Codigo))
|
|
If Estatus >= 0 Then Cons = Cons.Where((Function(a) Convert.ToInt32(a!CveEstado) = Estatus))
|
|
If AplicaParaVenta >= 0 Then Cons = Cons.Where((Function(a) Convert.ToInt32(a!AplicaParaVenta) = AplicaParaVenta))
|
|
If CvePS >= 0 Then Cons = Cons.Where((Function(a) Convert.ToInt32(a!CvePS) = CvePS))
|
|
|
|
Try
|
|
GlobalDTPSSimplificado = Cons.OrderBy(Function(a) a!PSCodigo).CopyToDataTable
|
|
Catch ex As Exception
|
|
GlobalDTPSSimplificado = New DataTable
|
|
End Try
|
|
|
|
Else
|
|
GlobalDTPSSimplificado = DirectCast(HttpContext.Current.Application(AppNombre), EnumerableRowCollection(Of DataRow)).CopyToDataTable
|
|
End If
|
|
End Get
|
|
Set(value As DataTable)
|
|
Dim AppNombre As String = String.Format("GlobalDTPSSimplificado-{0}", CveEmpresa)
|
|
HttpContext.Current.Application(AppNombre) = value
|
|
End Set
|
|
End Property
|
|
|
|
Property GlobalDTMonedas() As DataTable
|
|
Get
|
|
GlobalDTMonedas = DirectCast(HttpContext.Current.Application("GlobalDTMonedas"), DataTable)
|
|
End Get
|
|
Set(value As DataTable)
|
|
HttpContext.Current.Application("GlobalDTMonedas") = value
|
|
End Set
|
|
End Property
|
|
|
|
Public Property GlobalDTVtaFormaPago() As DataTable
|
|
Get
|
|
GlobalDTVtaFormaPago = DirectCast(HttpContext.Current.Application("GlobalDTVtaFormaPago"), DataTable)
|
|
End Get
|
|
Set(value As DataTable)
|
|
HttpContext.Current.Application("GlobalDTVtaFormaPago") = value
|
|
End Set
|
|
End Property
|
|
|
|
Property GlobalDTVtaMetodoPago() As DataTable
|
|
Get
|
|
GlobalDTVtaMetodoPago = DirectCast(HttpContext.Current.Application("GlobalDTVtaMetodoPago"), DataTable)
|
|
End Get
|
|
Set(value As DataTable)
|
|
HttpContext.Current.Application("GlobalDTVtaMetodoPago") = value
|
|
End Set
|
|
End Property
|
|
|
|
Property GlobalDTSATUsosCFDI(Optional EsPersonaFisica As Integer = -1) As DataTable
|
|
Get
|
|
If EsPersonaFisica <> -1 Then
|
|
Dim Tipo As String = ""
|
|
If EsPersonaFisica = 1 Then Tipo = "AplicaPersonaFisica = 1" Else Tipo = "AplicaPersonaMoral = 1"
|
|
|
|
Dim Dv As New DataView(DirectCast(HttpContext.Current.Application("GlobalDTSATUsosCFDI"), DataTable), Tipo, " UsoCFDIDescripcion", DataViewRowState.CurrentRows)
|
|
GlobalDTSATUsosCFDI = Dv.ToTable
|
|
Dv.Dispose()
|
|
Else
|
|
GlobalDTSATUsosCFDI = DirectCast(HttpContext.Current.Application("GlobalDTSATUsosCFDI"), DataTable)
|
|
End If
|
|
|
|
End Get
|
|
Set(ByVal value As DataTable)
|
|
HttpContext.Current.Application("GlobalDTSATUsosCFDI") = value
|
|
End Set
|
|
End Property
|
|
|
|
Property GlobalDTAlmacen(CveEmpresa As Integer, Optional CveTipoAlmacen As Integer = -1, Optional CveEstatus As Integer = 1, Optional CveAlmacen As Integer = -1) As DataTable
|
|
Get
|
|
Dim AppNombre As String = String.Format("GlobalDTAlmacen-{0}", CveEmpresa)
|
|
'sino existe, recarga los datos
|
|
If HttpContext.Current.Application(AppNombre) Is Nothing Then
|
|
Dim ObjUsr As New ClsInventarios
|
|
If ObjUsr.GetAlmacenes(-1, -1, CveEmpresa, -1) Then HttpContext.Current.Application(AppNombre) = ObjUsr.DtResultados
|
|
ObjUsr.Dispose()
|
|
End If
|
|
|
|
Dim Str As New StringBuilder
|
|
Str.Append("1=1 AND ")
|
|
If CveEmpresa <> -1 Then Str.AppendFormat(" CveEmpresa = {0} ", CveEmpresa)
|
|
If CveTipoAlmacen > 0 Then Str.AppendFormat("AND CveTipoAlmacen = {0}", CveTipoAlmacen)
|
|
If CveEstatus > 0 Then Str.AppendFormat("AND CveEstatus = {0}", CveEstatus)
|
|
If CveAlmacen > 0 Then Str.AppendFormat("AND CveAlmacen = {0}", CveAlmacen)
|
|
|
|
Dim Dv As New DataView(DirectCast(HttpContext.Current.Application(AppNombre), DataTable), Str.ToString, "", DataViewRowState.CurrentRows)
|
|
GlobalDTAlmacen = Dv.ToTable
|
|
Dv.Dispose()
|
|
End Get
|
|
Set(value As DataTable)
|
|
Dim AppNombre As String = String.Format("GlobalDTAlmacen-{0}", CveEmpresa)
|
|
HttpContext.Current.Application(AppNombre) = value
|
|
End Set
|
|
'Get
|
|
|
|
' Dim Str As New StringBuilder
|
|
' Str.Append("1=1 AND ")
|
|
' If CveEmpresa <> -1 Then Str.AppendFormat(" CveEmpresa = {0} ", CveEmpresa)
|
|
' If CveTipoAlmacen > 0 Then Str.AppendFormat("AND CveTipoAlmacen = {0}", CveTipoAlmacen)
|
|
' If CveEstatus > 0 Then Str.AppendFormat("AND CveEstatus = {0}", CveEstatus)
|
|
' If CveAlmacen > 0 Then Str.AppendFormat("AND CveAlmacen = {0}", CveAlmacen)
|
|
|
|
' Dim Dv As New DataView(DirectCast(Application("GlobalDTAlmacen"), DataTable), Str.ToString, "", DataViewRowState.CurrentRows)
|
|
' GlobalDTAlmacen = Dv.ToTable
|
|
' Dv.Dispose()
|
|
|
|
'End Get
|
|
'Set(value As DataTable)
|
|
' Application("GlobalDTAlmacen") = value
|
|
'End Set
|
|
End Property
|
|
|
|
Property GlobalDTEstado(ClaveSATPais As String) As DataTable
|
|
Get
|
|
If HttpContext.Current.Application("GlobalDTEstado") Is Nothing Then
|
|
Dim ObjGrales As New ClsGenerales
|
|
If ObjGrales.GetSATEstado("-1") Then HttpContext.Current.Application("GlobalDTEstado") = ObjGrales.DtResultados Else HttpContext.Current.Application("GlobalDTEstado") = Nothing
|
|
ObjGrales.Dispose()
|
|
End If
|
|
|
|
If ClaveSATPais <> "-1" Then
|
|
Dim Dv As New DataView(DirectCast(HttpContext.Current.Application("GlobalDTEstado"), DataTable), String.Format("ClaveSATPais = '{0}'", ClaveSATPais), "", DataViewRowState.CurrentRows)
|
|
GlobalDTEstado = Dv.ToTable
|
|
Dv.Dispose()
|
|
Else
|
|
GlobalDTEstado = DirectCast(HttpContext.Current.Application("GlobalDTEstado"), DataTable)
|
|
End If
|
|
|
|
End Get
|
|
Set(value As DataTable)
|
|
HttpContext.Current.Application("GlobalDTEstado") = value
|
|
End Set
|
|
End Property
|
|
#End Region
|
|
|
|
#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 ObjUsuarios As New ClsSisUsuarios
|
|
If ObjUsuarios.GetUsuarios(CveUsuario) Then
|
|
If ObjUsuarios.DtResultados.Rows.Count > 0 Then
|
|
Dim Usuario = ObjUsuarios.DtResultados.Rows(0)("Usuario").ToString()
|
|
Dim Contrasenia = ObjUsuarios.DtResultados.Rows(0)("Contraseña").ToString()
|
|
UsuarioActual = ObjUsuarios.ValidaUsuario(Usuario, Contrasenia, IMEI, CveEmpresa)
|
|
UsuarioActual.CveEmpresa = CveEmpresa
|
|
CreaObjetoEmpresa(UsuarioActual)
|
|
End If
|
|
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 = ""
|
|
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
|
|
context.Response.StatusCode = Auth.StatusCode
|
|
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
|
|
context.Response.StatusCode = Auth.StatusCode
|
|
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
|
|
context.Response.StatusCode = Auth.StatusCode
|
|
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
|
|
context.Response.StatusCode = Auth.StatusCode
|
|
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
|
|
context.Response.StatusCode = Auth.StatusCode
|
|
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))
|
|
If respuesta Then
|
|
retorno = "True"
|
|
Else
|
|
retorno = "False"
|
|
End If
|
|
Case "CrearActualizarProductosJson"
|
|
retorno = CrearActualizarProductosJson(If(FiltrarTodos = "1", True, False))
|
|
Case "ActualizarPrecios"
|
|
respuesta = ActualizarPrecios(If(FiltrarTodos = "1", True, False))
|
|
If respuesta Then
|
|
retorno = "True"
|
|
Else
|
|
retorno = "False"
|
|
End If
|
|
Case "ActualizarPreciosJson"
|
|
retorno = ActualizarPreciosJson(If(FiltrarTodos = "1", True, False))
|
|
Case "ActualizarExistencias"
|
|
respuesta = ActualizarExistencias()
|
|
If respuesta Then
|
|
retorno = "True"
|
|
Else
|
|
retorno = "False"
|
|
End If
|
|
Case "ActualizarExistenciasJson"
|
|
retorno = ActualizarExistenciasJson(If(FiltrarTodos = "1", True, False))
|
|
Case "ActualizarVendedores"
|
|
respuesta = ActualizarVendedores(If(FiltrarTodos = "1", True, False))
|
|
If respuesta Then
|
|
retorno = "True"
|
|
Else
|
|
retorno = "False"
|
|
End If
|
|
End Select
|
|
|
|
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 = 200
|
|
|
|
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 = 200
|
|
|
|
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 TieneError Then
|
|
RespuestaError.message = "Ocurrió un error al obtener el cuerpo de los parametros"
|
|
context.Response.StatusCode = 200
|
|
Return JsonConvert.SerializeObject(RespuestaError)
|
|
End If
|
|
|
|
If Not TieneError AndAlso Not String.IsNullOrEmpty(If(JsonRequest("rfc") Is Nothing, "", 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
|
|
|
|
Respuesta.data = data
|
|
Else
|
|
If String.IsNullOrEmpty(If(JsonRequest("rfc") Is Nothing, "", JsonRequest("rfc").ToString().Trim())) Then
|
|
TieneError = True
|
|
RespuestaError.message = "Debe ingresar un RFC"
|
|
End If
|
|
End If
|
|
|
|
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 Function ValidarCarrito(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 TieneError Then
|
|
RespuestaError.message = "Ocurrió un error al obtener el cuerpo de los parametros"
|
|
context.Response.StatusCode = 200
|
|
Return JsonConvert.SerializeObject(RespuestaError)
|
|
End If
|
|
|
|
Dim data As New JArray
|
|
Dim DtSucursalesExistencias As DataTable = Nothing
|
|
|
|
Using ObjInv As New ClsInventarios
|
|
If ObjInv.GetExistenciasSucursales(JsonRequest("products").ToString(), CveEmpresa) Then
|
|
DtSucursalesExistencias = ObjInv.DtResultados.Copy()
|
|
End If
|
|
End Using
|
|
|
|
If DtSucursalesExistencias IsNot Nothing Then
|
|
Try
|
|
For Each Row As DataRow In DtSucursalesExistencias.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
|
|
|
|
If DtSucursalesExistencias.Rows.Count = 0 Then
|
|
Respuesta.message = "No se encontraron resultados"
|
|
End If
|
|
|
|
Catch ex As Exception
|
|
TieneError = True
|
|
RespuestaError.message = "Ocurrió un error al obtener la sucursales"
|
|
End Try
|
|
DtSucursalesExistencias.Dispose()
|
|
Else
|
|
TieneError = True
|
|
End If
|
|
|
|
Respuesta.data = data
|
|
|
|
If TieneError Then
|
|
context.Response.StatusCode = 200
|
|
Return JsonConvert.SerializeObject(RespuestaError)
|
|
Else
|
|
context.Response.StatusCode = 200
|
|
Return JsonConvert.SerializeObject(Respuesta)
|
|
End If
|
|
End Function
|
|
|
|
#Region "R E G I S T R O - V E N T A "
|
|
Private Function RegistrarPedido(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 TieneError Then
|
|
RespuestaError.message = "Ocurrió un error al obtener el cuerpo de los parametros"
|
|
context.Response.StatusCode = 200
|
|
Return JsonConvert.SerializeObject(RespuestaError)
|
|
End If
|
|
|
|
If Not TieneError Then
|
|
Dim Usuario As Usuario = ValidaUsuarioSistema(100, CveEmpresa)
|
|
If Usuario IsNot Nothing Then
|
|
Dim Resp As New Modelos.Factura.MMensajeFactura
|
|
Dim ObjFactura As Modelos.Factura = Nothing
|
|
Dim DebeTimbrar As Boolean = False
|
|
|
|
Dim ObjClientes As New ClsClientes()
|
|
Dim ObjInventario As New ClsInventarios(ObjClientes.IniciaTransacSQL())
|
|
|
|
Try
|
|
Dim timbrar_request As String = If(JsonRequest("timbrar") Is Nothing, "", JsonRequest("timbrar").ToString())
|
|
|
|
If Not String.IsNullOrEmpty(timbrar_request) Then
|
|
DebeTimbrar = CBool(timbrar_request)
|
|
Else
|
|
DebeTimbrar = False
|
|
End If
|
|
|
|
ObjFactura = CreaFactura(ObjInventario, ObjClientes, "Ing", Resp, JsonRequest, Usuario)
|
|
|
|
If ObjFactura IsNot Nothing Then
|
|
Resp = ObjFactura.EmitirFactura(False, Transac:=ObjClientes.IniciaTransacSQL())
|
|
|
|
If Resp.CveVenta > 0 Then
|
|
Respuesta.status = "success"
|
|
Respuesta.data = Resp.SerieFolio
|
|
Else
|
|
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
|
|
|
|
Catch ex As Exception
|
|
TieneError = True
|
|
End Try
|
|
|
|
If TieneError Then
|
|
ObjClientes.RollBack()
|
|
ObjClientes.Dispose()
|
|
ObjInventario.Dispose()
|
|
Else
|
|
ObjClientes.Commit()
|
|
ObjClientes.Dispose()
|
|
ObjInventario.Dispose()
|
|
|
|
If DebeTimbrar Then
|
|
Dim SeTimbro As Boolean = ObjFactura.TimbrarFactura()
|
|
If SeTimbro Then
|
|
Respuesta.message = "La factura se creó correctamente"
|
|
Else
|
|
Respuesta.message = "La factura se creó pero no se pudo emitir. favor de comunicarse con soporte tecnico."
|
|
End If
|
|
Else
|
|
Respuesta.message = "La factura se creó correctamente."
|
|
End If
|
|
End If
|
|
|
|
If ObjFactura IsNot Nothing Then
|
|
ObjFactura.Dispose()
|
|
End If
|
|
|
|
Else
|
|
TieneError = True
|
|
RespuestaError.message = "No hay un usuario disponible"
|
|
End If
|
|
|
|
End If
|
|
|
|
If TieneError Then
|
|
context.Response.StatusCode = 200
|
|
Return JsonConvert.SerializeObject(RespuestaError)
|
|
Else
|
|
context.Response.StatusCode = 200
|
|
Return JsonConvert.SerializeObject(Respuesta)
|
|
End If
|
|
End Function
|
|
|
|
|
|
#Region "D E F I N I R - O B J E T O S"
|
|
Private Function CrearCliente(TipoDocto As String, ObjClientes As ClsClientes, ByRef Resp As Modelos.Factura.MMensajeFactura, JsonRequest As JObject, UsuarioActual As Usuario) As Integer
|
|
Dim CveCliente As Integer = -1
|
|
|
|
Dim CveSubProyecto As Integer = JsonRequest("branch_office_id").ToEntero()
|
|
|
|
|
|
Dim Nombre As String = ""
|
|
Dim Direccion As String = ""
|
|
Dim NumExt As String = ""
|
|
Dim NumInt As String = ""
|
|
Dim Colonia As String = ""
|
|
Dim Localidad As String = ""
|
|
Dim Ciudad As String = ""
|
|
Dim Estado As String = ""
|
|
Dim RFC As String = ""
|
|
Dim CP As String = ""
|
|
Dim Telefono As String = ""
|
|
Dim Correo As String = ""
|
|
|
|
'DATOS DE CONTACTO
|
|
Dim contact_name As String = If(JsonRequest("contact_name") Is Nothing, "", JsonRequest("contact_name").ToString())
|
|
Dim contact_address As String = If(JsonRequest("contact_address") Is Nothing, "", JsonRequest("contact_address").ToString())
|
|
Dim contact_ext_number As String = If(JsonRequest("contact_ext_number") Is Nothing, "", JsonRequest("contact_ext_number").ToString())
|
|
Dim contact_int_number As String = If(JsonRequest("contact_int_number") Is Nothing, "", JsonRequest("contact_int_number").ToString())
|
|
Dim contact_neighborhood As String = If(JsonRequest("contact_neighborhood") Is Nothing, "", JsonRequest("contact_neighborhood").ToString())
|
|
Dim contact_city As String = If(JsonRequest("contact_city") Is Nothing, "", JsonRequest("contact_city").ToString())
|
|
Dim contact_zip_code As String = If(JsonRequest("contact_zip_code") Is Nothing, "", JsonRequest("contact_zip_code").ToString())
|
|
Dim contact_phone As String = If(JsonRequest("contact_phone") Is Nothing, "", JsonRequest("contact_phone").ToString())
|
|
Dim contact_email As String = If(JsonRequest("contact_email") Is Nothing, "", JsonRequest("contact_email").ToString())
|
|
Dim contact_state As String = If(JsonRequest("contact_state") Is Nothing, "", JsonRequest("contact_state").ToString())
|
|
|
|
'DATOS DE FACTURACION
|
|
Dim invoice_rfc As String = If(JsonRequest("invoice_rfc") Is Nothing, "", JsonRequest("invoice_rfc").ToString())
|
|
Dim invoice_name As String = If(JsonRequest("invoice_name") Is Nothing, "", JsonRequest("invoice_name").ToString())
|
|
Dim invoice_address As String = If(JsonRequest("invoice_address") Is Nothing, "", JsonRequest("invoice_address").ToString())
|
|
Dim invoice_city As String = If(JsonRequest("invoice_city") Is Nothing, "", JsonRequest("invoice_city").ToString())
|
|
Dim invoice_state As String = If(JsonRequest("invoice_state") Is Nothing, "", JsonRequest("invoice_state").ToString())
|
|
Dim invoice_email As String = If(JsonRequest("invoice_email") Is Nothing, "", JsonRequest("invoice_email").ToString())
|
|
Dim invoice_phone As String = If(JsonRequest("invoice_phone") Is Nothing, "", JsonRequest("invoice_phone").ToString())
|
|
|
|
Dim CveEstado As Integer = -1
|
|
|
|
If TipoDocto = "Ing" Then
|
|
RFC = If(Not String.IsNullOrEmpty(invoice_rfc), invoice_rfc, "XAXX010101000")
|
|
Nombre = If(Not String.IsNullOrEmpty(invoice_name), invoice_name, contact_name)
|
|
Direccion = If(Not String.IsNullOrEmpty(invoice_address), invoice_address, contact_address)
|
|
'SI LA DIRECCION ES LA MISMA QUE LA DE CONTACTO
|
|
If Direccion = contact_address Then
|
|
NumExt = If(Not String.IsNullOrEmpty(contact_ext_number), contact_ext_number, "")
|
|
NumInt = If(Not String.IsNullOrEmpty(contact_int_number), contact_int_number, "")
|
|
Colonia = If(Not String.IsNullOrEmpty(contact_neighborhood), contact_neighborhood, "")
|
|
End If
|
|
Ciudad = If(Not String.IsNullOrEmpty(invoice_city), invoice_city, contact_city)
|
|
Localidad = Ciudad
|
|
Estado = If(Not String.IsNullOrEmpty(invoice_state), invoice_state, contact_state)
|
|
CP = If(Not String.IsNullOrEmpty(contact_zip_code), contact_zip_code, "")
|
|
Correo = If(Not String.IsNullOrEmpty(invoice_email), invoice_email, contact_email)
|
|
Telefono = If(Not String.IsNullOrEmpty(invoice_phone), invoice_phone, contact_phone)
|
|
|
|
Else
|
|
|
|
Nombre = If(Not String.IsNullOrEmpty(contact_name), contact_name, "")
|
|
Direccion = If(Not String.IsNullOrEmpty(contact_address), contact_address, "")
|
|
NumExt = If(Not String.IsNullOrEmpty(contact_ext_number), contact_ext_number, "")
|
|
NumInt = If(Not String.IsNullOrEmpty(contact_int_number), contact_int_number, "")
|
|
Colonia = If(Not String.IsNullOrEmpty(contact_neighborhood), contact_neighborhood, "")
|
|
Ciudad = If(Not String.IsNullOrEmpty(contact_city), contact_city, "")
|
|
Localidad = Ciudad
|
|
Estado = If(Not String.IsNullOrEmpty(contact_state), contact_state, "")
|
|
CP = If(Not String.IsNullOrEmpty(contact_zip_code), contact_zip_code, "")
|
|
Correo = If(Not String.IsNullOrEmpty(contact_email), contact_email, "")
|
|
Telefono = If(Not String.IsNullOrEmpty(contact_phone), contact_phone, "")
|
|
|
|
End If
|
|
|
|
If Not String.IsNullOrEmpty(Estado) Then
|
|
CveEstado = GlobalDTEstado("MEX").FiltroPrimeroValor("CveEstado", $"NombreEstado = '{Estado.Trim}'").ToEntero()
|
|
|
|
'SI NO ENCUENTRA EL ESTADO INGRESA EL DE SONORA
|
|
If CveEstado <= 0 Then
|
|
CveEstado = 26
|
|
End If
|
|
Else
|
|
CveEstado = 26
|
|
End If
|
|
|
|
|
|
'SI NO EXISTE EL RFC UTILIZA EL GENERICO
|
|
If String.IsNullOrEmpty(RFC) Then
|
|
RFC = "XAXX010101000"
|
|
End If
|
|
|
|
If String.IsNullOrEmpty(Nombre) Then
|
|
Resp.TieneError = False
|
|
Resp.Mensajes.Add("El cliente no tiene un nombre")
|
|
Return -1
|
|
End If
|
|
|
|
'VALIDAR QUE NO EXISTA EL RFC
|
|
If RFC <> "XAXX010101000" Then
|
|
If ObjClientes.GetClientes(-1, "-1", "-1", "-1", RFC, "-1", "-1", -1, UsuarioActual.CveEmpresa, 1, TipoCliente:=-1, TopSelect:=1) Then
|
|
If ObjClientes.DtResultados.Rows.Count > 0 Then
|
|
Resp.TieneError = False
|
|
Resp.Mensajes.Add("El RFC ya existe en el sistema")
|
|
Return -1
|
|
End If
|
|
End If
|
|
End If
|
|
|
|
If ObjClientes.AgregarClienteNoFrecuente(Nombre, Direccion, NumExt, NumInt, Colonia, Localidad, Ciudad, CveEstado, RFC, CP, Telefono, Correo, CveSubProyecto, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, "", -1, -1) Then
|
|
If ObjClientes.DtResultados.Rows.Count > 0 Then
|
|
CveCliente = ObjClientes.DtResultados(0)("CveCliente").ToString().ToEntero()
|
|
End If
|
|
End If
|
|
|
|
If CveCliente <= 0 Then
|
|
Resp.TieneError = False
|
|
Resp.Mensajes.Add("Ocurrió un error al crear el cliente")
|
|
Return -1
|
|
End If
|
|
|
|
Return CveCliente
|
|
|
|
End Function
|
|
|
|
Private Function CreaFactura(ObjInventario As ClsInventarios, ObjClientes As ClsClientes, TipoDocto As String, Resp As Modelos.Factura.MMensajeFactura, JsonRequest As JObject, UsuarioActual As Usuario) As Modelos.Factura
|
|
Try
|
|
Resp.TieneError = False
|
|
Dim Serie As String = "-1"
|
|
Dim CveMoneda As Integer = 1
|
|
|
|
Dim CveSubProyecto As Integer = JsonRequest("branch_office_id").ToEntero()
|
|
|
|
If CveSubProyecto <= 0 Then
|
|
Resp.TieneError = False
|
|
Resp.Mensajes.Add("La sucursal es requerida")
|
|
Return Nothing
|
|
End If
|
|
|
|
Dim CveCliente As Integer = If(JsonRequest("user_id") Is Nothing, 0, JsonRequest("user_id").ToEntero())
|
|
|
|
If CveCliente <= 0 Then
|
|
CveCliente = CrearCliente(TipoDocto, ObjClientes, Resp, JsonRequest, UsuarioActual)
|
|
End If
|
|
|
|
If CveCliente <= 0 Then
|
|
Return Nothing
|
|
End If
|
|
|
|
Dim ObjFactura = New Modelos.Factura(UsuarioActual)
|
|
ObjFactura.TipoMensajeRespuesta = Modelos.TipoMensajeRespuesta.TextoLimpio
|
|
ObjFactura.Serie = Serie
|
|
ObjFactura.Folio = -1
|
|
ObjFactura.Version = "3.3"
|
|
ObjFactura.FolioFiscal = ""
|
|
ObjFactura.CveUsuario = UsuarioActual.CveUsuario
|
|
ObjFactura.CveEmpresa = UsuarioActual.CveEmpresa
|
|
ObjFactura.TipoCambio = 1
|
|
ObjFactura.ConvertirPesos = False
|
|
ObjFactura.CveMoneda = CveMoneda
|
|
ObjFactura.Moneda = GlobalDTMonedas.FiltroPrimeroValor("Moneda", String.Format("CveMoneda = {0} ", CveMoneda))
|
|
ObjFactura.MonedaSAT = GlobalDTMonedas.FiltroPrimeroValor("AbreviaturaSAT", String.Format("CveMoneda = {0} ", CveMoneda))
|
|
ObjFactura.TipoDocto = TipoDocto
|
|
ObjFactura.RefDocto = ""
|
|
ObjFactura.CveMesa = -1
|
|
ObjFactura.Fecha = Now
|
|
ObjFactura.CvePrePoliza = -1
|
|
ObjFactura.FechaPago = Now
|
|
ObjFactura.MotivoDescuento = ""
|
|
ObjFactura.FechaEjecucion = Now
|
|
ObjFactura.UsuarioCreo = UsuarioActual.Usuario
|
|
ObjFactura.CveCondicionEntrega = -1
|
|
ObjFactura.CondicionEntrega = ""
|
|
ObjFactura.NumeroCuenta = ""
|
|
ObjFactura.CondicionesPago = 0
|
|
ObjFactura.FormaPago = 0
|
|
ObjFactura.PedidoContrato = ""
|
|
ObjFactura.NumeroContrato = ""
|
|
ObjFactura.DescripcionContrato = ""
|
|
ObjFactura.CveCorte = -1
|
|
ObjFactura.TipoDocumento = ObjFactura.TipodeComprobante
|
|
ObjFactura.Alfa1 = ""
|
|
ObjFactura.Alfa2 = ""
|
|
ObjFactura.Alfa3 = ""
|
|
ObjFactura.CveContrato = -1
|
|
ObjFactura.ConvertirPesos = False
|
|
ObjFactura.CveSubProyecto = CveSubProyecto
|
|
ObjFactura.CveSubProyectoCobranza = CveSubProyecto
|
|
ObjFactura.CveSubProyectoEjecucion = CveSubProyecto
|
|
ObjFactura.SubProyecto = New Modelos.SubProyectoModel(GlobalDTSubProyectos(-1, CveEmpresa:=CveEmpresa).FiltroPrimero(String.Format("CveSubProyecto = {0}", CveSubProyecto)))
|
|
ObjFactura.SubProyectoMatriz = New Modelos.SubProyectoModel(GlobalDTSubProyectos(-1, CveSubProyecto:=-1, CveEmpresa:=UsuarioActual.CveEmpresa).FiltroPrimero("TipoSucursal=1"))
|
|
|
|
'CLIENTE
|
|
ObjFactura.CveCliente = CveCliente
|
|
ObjFactura.CveClienteSucursal = -1
|
|
|
|
ObjFactura.SetCliente()
|
|
|
|
If ObjFactura.TipoDocto = "Cot" Then
|
|
If ObjClientes.GetClientes(CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, UsuarioActual.CveEmpresa, -1, TipoCliente:=-1) Then
|
|
If ObjClientes.DtResultados.Rows.Count > 0 Then
|
|
ObjFactura.CveFormaPago33 = ObjClientes.CveFormaPago33
|
|
ObjFactura.FormaPago33 = GlobalDTVtaFormaPago.FiltroPrimeroValor("FormaPago", String.Format("CveFormaPago = {0}", ObjClientes.CveFormaPago33))
|
|
ObjFactura.FormaPagoSAT33 = GlobalDTVtaFormaPago.FiltroPrimeroValor("ClaveFormaPagoSAT", String.Format("CveFormaPago = {0}", ObjClientes.CveFormaPago33))
|
|
|
|
ObjFactura.CveMetodoPago33 = ObjClientes.CveMetodoPago33
|
|
ObjFactura.MetodoPago33 = GlobalDTVtaMetodoPago.FiltroPrimeroValor("MetodoPago", String.Format("CveMetodoPago = {0}", ObjClientes.CveMetodoPago33))
|
|
ObjFactura.ClaveMetodoPagoSAT = GlobalDTVtaMetodoPago.FiltroPrimeroValor("ClaveMetodoPagoSAT", String.Format("CveMetodoPago = {0}", ObjClientes.CveMetodoPago33))
|
|
|
|
ObjFactura.CveUsoCFDI = ObjClientes.CveUsoCFDI
|
|
ObjFactura.UsoCFDI = GlobalDTSATUsosCFDI.FiltroPrimeroValor("Descripcion", String.Format("CveUsoCFDI = {0}", ObjClientes.CveUsoCFDI))
|
|
ObjFactura.ClaveUsoCFDI = GlobalDTSATUsosCFDI.FiltroPrimeroValor("UsoCFDI", String.Format("CveUsoCFDI = {0}", ObjClientes.CveUsoCFDI))
|
|
|
|
End If
|
|
End If
|
|
|
|
ElseIf ObjFactura.TipoDocto = "Ing" Then
|
|
|
|
'FORMA DE PAGO
|
|
If JsonRequest("invoice_way_to_pay") Is Nothing Then
|
|
Resp.TieneError = False
|
|
Resp.Mensajes.Add("Debe asignar una forma de pago")
|
|
Return Nothing
|
|
End If
|
|
|
|
If Not String.IsNullOrEmpty(JsonRequest("invoice_way_to_pay").ToString()) Then
|
|
Dim RowFormaPago As DataRow = GlobalDTVtaFormaPago.FiltroPrimero(String.Format("ClaveFormaPagoSAT = '{0}'", JsonRequest("invoice_way_to_pay").ToString()))
|
|
If RowFormaPago IsNot Nothing Then
|
|
ObjFactura.CveFormaPago33 = RowFormaPago("CveFormaPago").ToString().ToEntero()
|
|
ObjFactura.FormaPago33 = RowFormaPago("FormaPago").ToString()
|
|
ObjFactura.FormaPagoSAT33 = RowFormaPago("ClaveFormaPagoSAT").ToString()
|
|
Else
|
|
Resp.TieneError = False
|
|
Resp.Mensajes.Add("No se encontro la forma de pago")
|
|
Return Nothing
|
|
End If
|
|
Else
|
|
Resp.TieneError = False
|
|
Resp.Mensajes.Add("Debe asignar una forma de pago")
|
|
Return Nothing
|
|
End If
|
|
|
|
'USO CFDi
|
|
If JsonRequest("invoice_use") Is Nothing Then
|
|
Resp.TieneError = False
|
|
Resp.Mensajes.Add("Debe asignar un uso cfdi")
|
|
Return Nothing
|
|
End If
|
|
|
|
If Not String.IsNullOrEmpty(JsonRequest("invoice_use").ToString()) Then
|
|
Dim RowUsoCFDi As DataRow = GlobalDTSATUsosCFDI.FiltroPrimero(String.Format("UsoCFDI = '{0}'", JsonRequest("invoice_use").ToString()))
|
|
If RowUsoCFDi IsNot Nothing Then
|
|
ObjFactura.CveUsoCFDI = RowUsoCFDi("CveUsoCFDI").ToString().ToEntero()
|
|
ObjFactura.UsoCFDI = RowUsoCFDi("Descripcion").ToString()
|
|
ObjFactura.ClaveUsoCFDI = RowUsoCFDi("UsoCFDI").ToString()
|
|
Else
|
|
Resp.TieneError = False
|
|
Resp.Mensajes.Add("No se encontro el uso cfdi")
|
|
Return Nothing
|
|
End If
|
|
Else
|
|
Resp.TieneError = False
|
|
Resp.Mensajes.Add("Debe asignar un uso cfdi")
|
|
Return Nothing
|
|
End If
|
|
|
|
'METODO DE PAGO
|
|
If JsonRequest("invoice_payment_method") Is Nothing Then
|
|
Resp.TieneError = False
|
|
Resp.Mensajes.Add("Debe asignar un método de pago")
|
|
Return Nothing
|
|
End If
|
|
|
|
If Not String.IsNullOrEmpty(JsonRequest("invoice_payment_method").ToString()) Then
|
|
Dim RowMetodoPago As DataRow = GlobalDTVtaMetodoPago.FiltroPrimero(String.Format("ClaveMetodoPagoSAT = '{0}'", JsonRequest("invoice_payment_method").ToString()))
|
|
If RowMetodoPago IsNot Nothing Then
|
|
ObjFactura.CveMetodoPago33 = RowMetodoPago("CveMetodoPago").ToString().ToEntero()
|
|
ObjFactura.MetodoPago33 = RowMetodoPago("MetodoPago").ToString()
|
|
ObjFactura.ClaveMetodoPagoSAT = RowMetodoPago("ClaveMetodoPagoSAT").ToString()
|
|
Else
|
|
Resp.TieneError = False
|
|
Resp.Mensajes.Add("No se encontro el método de pago")
|
|
Return Nothing
|
|
End If
|
|
Else
|
|
Resp.TieneError = False
|
|
Resp.Mensajes.Add("Debe asignar un método de pago")
|
|
Return Nothing
|
|
End If
|
|
|
|
End If
|
|
|
|
If ObjFactura.Cliente IsNot Nothing AndAlso TipoDocto = "Ing" Then
|
|
|
|
'DATOS DE CONTACTO
|
|
Dim contact_name As String = If(JsonRequest("contact_name") Is Nothing, "", JsonRequest("contact_name").ToString())
|
|
Dim contact_address As String = If(JsonRequest("contact_address") Is Nothing, "", JsonRequest("contact_address").ToString())
|
|
Dim contact_ext_number As String = If(JsonRequest("contact_ext_number") Is Nothing, "", JsonRequest("contact_ext_number").ToString())
|
|
Dim contact_int_number As String = If(JsonRequest("contact_int_number") Is Nothing, "", JsonRequest("contact_int_number").ToString())
|
|
Dim contact_neighborhood As String = If(JsonRequest("contact_neighborhood") Is Nothing, "", JsonRequest("contact_neighborhood").ToString())
|
|
Dim contact_city As String = If(JsonRequest("contact_city") Is Nothing, "", JsonRequest("contact_city").ToString())
|
|
Dim contact_zip_code As String = If(JsonRequest("contact_zip_code") Is Nothing, "", JsonRequest("contact_zip_code").ToString())
|
|
Dim contact_phone As String = If(JsonRequest("contact_phone") Is Nothing, "", JsonRequest("contact_phone").ToString())
|
|
Dim contact_email As String = If(JsonRequest("contact_email") Is Nothing, "", JsonRequest("contact_email").ToString())
|
|
Dim contact_state As String = If(JsonRequest("contact_state") Is Nothing, "", JsonRequest("contact_state").ToString())
|
|
|
|
'DATOS DE FACTURACION
|
|
Dim invoice_rfc As String = If(JsonRequest("invoice_rfc") Is Nothing, "", JsonRequest("invoice_rfc").ToString())
|
|
Dim invoice_name As String = If(JsonRequest("invoice_name") Is Nothing, "", JsonRequest("invoice_name").ToString())
|
|
Dim invoice_address As String = If(JsonRequest("invoice_address") Is Nothing, "", JsonRequest("invoice_address").ToString())
|
|
Dim invoice_city As String = If(JsonRequest("invoice_city") Is Nothing, "", JsonRequest("invoice_city").ToString())
|
|
Dim invoice_state As String = If(JsonRequest("invoice_state") Is Nothing, "", JsonRequest("invoice_state").ToString())
|
|
Dim invoice_email As String = If(JsonRequest("invoice_email") Is Nothing, "", JsonRequest("invoice_email").ToString())
|
|
Dim invoice_phone As String = If(JsonRequest("invoice_phone") Is Nothing, "", JsonRequest("invoice_phone").ToString())
|
|
|
|
Dim CveEstado As Integer = -1
|
|
|
|
ObjFactura.Cliente.RFC = If(Not String.IsNullOrEmpty(invoice_rfc), invoice_rfc, ObjFactura.Cliente.RFC)
|
|
ObjFactura.Cliente.Nombre = If(Not String.IsNullOrEmpty(invoice_name), invoice_name, contact_name)
|
|
ObjFactura.Cliente.NombreComercial = ObjFactura.Cliente.NombreComercial
|
|
ObjFactura.Cliente.Direccion = If(Not String.IsNullOrEmpty(invoice_address), invoice_address, contact_address)
|
|
ObjFactura.Cliente.Mail = If(Not String.IsNullOrEmpty(invoice_email), invoice_email, contact_email)
|
|
ObjFactura.Cliente.Telefono = If(Not String.IsNullOrEmpty(invoice_phone), invoice_phone, contact_phone)
|
|
ObjFactura.Cliente.Localidad = If(Not String.IsNullOrEmpty(invoice_city), invoice_city, contact_city)
|
|
ObjFactura.Cliente.Ciudad = ObjFactura.Cliente.Localidad
|
|
ObjFactura.Cliente.Estado = If(Not String.IsNullOrEmpty(invoice_state), invoice_state, contact_state)
|
|
|
|
If String.IsNullOrEmpty(ObjFactura.Cliente.RFC) Then
|
|
Resp.Mensajes.Add("No se ha ingresado un RFC")
|
|
Return Nothing
|
|
End If
|
|
|
|
If String.IsNullOrEmpty(ObjFactura.Cliente.Nombre) Then
|
|
Resp.Mensajes.Add("No se ha ingresado un nombre para el cliente")
|
|
Return Nothing
|
|
End If
|
|
|
|
If Not String.IsNullOrEmpty(ObjFactura.Cliente.Estado) Then
|
|
CveEstado = GlobalDTEstado("MEX").FiltroPrimeroValor("CveEstado", $"NombreEstado = '{ObjFactura.Cliente.Estado.Trim}'").ToEntero()
|
|
|
|
'SI NO ENCUENTRA EL ESTADO INGRESA EL DE SONORA
|
|
If CveEstado <= 0 Then
|
|
CveEstado = 26
|
|
End If
|
|
Else
|
|
CveEstado = 26
|
|
End If
|
|
|
|
Dim Cliente = ObjFactura.Cliente
|
|
If Not ObjClientes.UpdateClienteNoFrencuente(CveCliente, Cliente.Nombre, Cliente.Direccion, Cliente.NoExt, Cliente.NoInt, Cliente.Colonia, Cliente.Localidad, Cliente.Ciudad, CveEstado, Cliente.RFC, Cliente.CP, Cliente.Telefono, Cliente.Mail, CveSubProyecto, UsuarioActual.CveUsuario, CveEmpresa, "-1", ObjFactura.CveMetodoPago33, ObjFactura.CveFormaPago33) Then
|
|
Resp.TieneError = False
|
|
Resp.Mensajes.Add("No se puedo actualizar un cliente")
|
|
Return Nothing
|
|
End If
|
|
|
|
End If
|
|
|
|
ObjFactura.CveAlmacen = GlobalDTAlmacen(CveEmpresa, CveTipoAlmacen:=1).FiltroPrimeroValor("CveAlmacen", $"CveSubProyecto={CveSubProyecto}").ToEntero()
|
|
|
|
'DETALLES
|
|
ObjFactura.DtDetalle = CreaDTDetalle(ObjInventario, ObjFactura, Resp, UsuarioActual, JsonRequest)
|
|
|
|
If Resp.TieneError Then
|
|
Resp.Mensajes.Add("No se pudieron agregar los productos/servicios")
|
|
Return Nothing
|
|
Else
|
|
If ObjFactura.DtDetalle Is Nothing OrElse ObjFactura.DtDetalle.Rows.Count = 0 Then
|
|
Resp.Mensajes.Add("No se pudieron agregar los productos/servicios")
|
|
Return Nothing
|
|
End If
|
|
End If
|
|
|
|
'INVENTARIO
|
|
If TipoDocto = "Ing" Then
|
|
ObjFactura.DtInventario = ObjFactura.DtDetalle.Copy.FiltraParametros("CveTipoPS = 2")
|
|
ObjFactura.GenerarSalidaAlmacen = True
|
|
ObjFactura.GenerarPDFFactura = False
|
|
End If
|
|
|
|
'IMPORTES
|
|
Dim TotalImporte As Decimal = ObjFactura.DtDetalle.SUMD("TotalImporte")
|
|
Dim ImporteIVA As Decimal = ObjFactura.DtDetalle.SUMD("ImporteIVA")
|
|
Dim ImporteRetIVA As Decimal = ObjFactura.DtDetalle.SUMD("ImporteRetIVA")
|
|
Dim ImporteRetISR As Decimal = ObjFactura.DtDetalle.SUMD("ImporteRetISR")
|
|
Dim ImporteIEPS As Decimal = ObjFactura.DtDetalle.SUMD("ImporteIEPS")
|
|
Dim Descuento As Decimal = ObjFactura.DtDetalle.SUMD("Descuento")
|
|
Dim Amortizacion As Decimal = 0
|
|
|
|
Dim Total As Decimal = (TotalImporte + ImporteIVA + ImporteIEPS) - (ImporteRetIVA + ImporteRetISR + Descuento + Amortizacion)
|
|
|
|
ObjFactura.SubTotal = TotalImporte
|
|
ObjFactura.Descuento = Descuento
|
|
ObjFactura.Amortizacion = Amortizacion
|
|
ObjFactura.IVA = ImporteIVA
|
|
ObjFactura.RetIVA = ImporteRetIVA
|
|
ObjFactura.RetISR = ImporteRetISR
|
|
ObjFactura.IEPS = ImporteIEPS
|
|
ObjFactura.Total = Total
|
|
ObjFactura.TotalOtrosConceptos = 0
|
|
|
|
'SI HAY DIFERENCIA DE UN CENTAVO AJUSTA
|
|
If Math.Abs(JsonRequest("total").ToString().ToDecimal() - ObjFactura.Total) <= 0.01 Then
|
|
Dim diff As Decimal = (JsonRequest("total").ToString().ToDecimal() - ObjFactura.Total)
|
|
If diff <> 0 Then
|
|
'AJUSTA EN EL ULTIMO CONCEPTO
|
|
Dim IVADetalle As Decimal = ObjFactura.DtDetalle.Rows(ObjFactura.DtDetalle.Rows.Count - 1)("ImporteIVA").ToString().ToDecimal()
|
|
|
|
ObjFactura.DtDetalle.Rows(ObjFactura.DtDetalle.Rows.Count - 1)("ImporteIVA") = IVADetalle + diff
|
|
ObjFactura.IVA = ObjFactura.IVA + diff
|
|
ObjFactura.Total = ObjFactura.Total + diff
|
|
End If
|
|
|
|
End If
|
|
|
|
If ObjFactura.Total <> JsonRequest("total").ToString().ToDecimal() Then
|
|
Resp.Mensajes.Add("El total de la factura no coincide con el total enviado")
|
|
Return Nothing
|
|
End If
|
|
|
|
If ObjFactura.Descuento <> JsonRequest("discount").ToString().ToDecimal() Then
|
|
Resp.Mensajes.Add("Los descuentos no coinciden")
|
|
Return Nothing
|
|
End If
|
|
|
|
If (JsonRequest("subtotal").ToString().ToDecimal() - JsonRequest("discount").ToString().ToDecimal()) <> JsonRequest("total").ToString().ToDecimal() Then
|
|
Resp.Mensajes.Add("el subtotal y el descuento no coinciden con el total")
|
|
Return Nothing
|
|
End If
|
|
|
|
If TipoDocto = "Ing" Then
|
|
ObjFactura.Observaciones = "PEDIDO PROVENIENTE DE ECOMMERCE"
|
|
ElseIf TipoDocto = "Cot" Then
|
|
ObjFactura.Observaciones = "COTIZACION PROVENIENTE DE ECOMMERCE"
|
|
End If
|
|
|
|
ObjFactura.OrdenCompra = ""
|
|
ObjFactura.PedidoContrato = ""
|
|
ObjFactura.ObservacionesAlmacen = ""
|
|
ObjFactura.EnviarCorreo = False
|
|
|
|
ObjFactura.Timbre = PreParaTimbre(ObjFactura)
|
|
ObjFactura.FemsaFactura = New Modelos.FemsaFactura() With {
|
|
.AplicaFEMSA = False,
|
|
.FEMSA_Version = 1
|
|
}
|
|
Return ObjFactura
|
|
Catch ex As Exception
|
|
Resp.Mensajes.Add(ex.ToString())
|
|
Return Nothing
|
|
End Try
|
|
|
|
End Function
|
|
|
|
Private Function PreParaTimbre(Obj As Modelos.Factura) As CFDITimbre
|
|
Dim Timbre As New CFDITimbre
|
|
Timbre.Comprobante.TipoComprobante = If(Obj.TipoDocto.Contiene("Ing", "Ant"), "I", If(Obj.TipoDocto.Contiene("Egs", "Dev"), "E", ""))
|
|
Timbre.Comprobante.Folio = Obj.Folio.ToString
|
|
Timbre.Comprobante.Serie = Obj.Serie
|
|
Timbre.Comprobante.Fecha = Obj.FechaCP
|
|
Timbre.Comprobante.FormadePago = Obj.FormaPagoSAT33
|
|
Timbre.Comprobante.CondicionesdePago = Obj.FormaPago33
|
|
Timbre.Comprobante.MetodoPago = Obj.ClaveMetodoPagoSAT
|
|
Timbre.Comprobante.Subtotal = Obj.SubTotal
|
|
Timbre.Comprobante.Descuentos = Obj.Descuento
|
|
Timbre.Comprobante.Moneda = Obj.MonedaSAT
|
|
Timbre.Comprobante.TipoCambio = If(Obj.CveMoneda = 1, "1", Obj.TipoCambio.ToString)
|
|
Timbre.Comprobante.Total = Obj.Total
|
|
|
|
Timbre.Comprobante.LugarExpedicion = Obj.SubProyecto.CP
|
|
Timbre.Comprobante.Confirmacion = ""
|
|
|
|
Timbre.Receptor.RFC = Obj.Cliente.RFC
|
|
Timbre.Receptor.Nombre = Obj.Cliente.Nombre
|
|
Timbre.Receptor.ResidenciaFiscal = ""
|
|
Timbre.Receptor.NumeroRegistroTributario = ""
|
|
Timbre.Receptor.UsoCFDI = Obj.ClaveUsoCFDI
|
|
|
|
|
|
If Obj.CveTipoRelacion > 0 Then
|
|
Select Case Obj.CveTipoRelacion
|
|
Case 1
|
|
Timbre.CFDIRelacionados.TipoRelacion = "01"
|
|
Timbre.CFDIRelacionados.TipoRelacionTexto = "01-Nota de Crédito aplicada a Ingreso"
|
|
Case 2
|
|
Timbre.CFDIRelacionados.TipoRelacion = "02"
|
|
Timbre.CFDIRelacionados.TipoRelacionTexto = "02-Nota de débito de los documentos relacionados"
|
|
Case 3
|
|
Timbre.CFDIRelacionados.TipoRelacion = "03"
|
|
Timbre.CFDIRelacionados.TipoRelacionTexto = "03-Devolución aplicada a Ingreso"
|
|
Case 4
|
|
Timbre.CFDIRelacionados.TipoRelacion = "04"
|
|
Timbre.CFDIRelacionados.TipoRelacionTexto = "04-Refacturación de Ingreso"
|
|
Case 7
|
|
Timbre.CFDIRelacionados.TipoRelacion = "07"
|
|
Timbre.CFDIRelacionados.TipoRelacionTexto = "07-CFDI por aplicación de anticipo"
|
|
Case 8
|
|
Timbre.CFDIRelacionados.TipoRelacion = "08"
|
|
Timbre.CFDIRelacionados.TipoRelacionTexto = "08-Factura generada por pagos en parcialidades "
|
|
Case 9
|
|
Timbre.CFDIRelacionados.TipoRelacion = "09"
|
|
Timbre.CFDIRelacionados.TipoRelacionTexto = "09-Factura generada por pagos diferidos"
|
|
|
|
End Select
|
|
|
|
End If
|
|
|
|
|
|
Dim totSubTotal As Decimal = Obj.SubTotal
|
|
Dim totIVA As Decimal = Obj.IVA
|
|
Dim totRetIVA As Decimal = Obj.RetIVA
|
|
Dim totRetISR As Decimal = Obj.RetISR
|
|
Dim i As Integer = 1
|
|
|
|
'DETALLES
|
|
Dim tPS As String = ""
|
|
|
|
For Each drr As DataRow In Obj.DtDetalle.Rows
|
|
If drr("PS").ToString.Length = 1 Then
|
|
tPS = drr("Obs").ToString
|
|
Else
|
|
If drr("PS").ToString.Length = 0 Then
|
|
tPS = ""
|
|
Else
|
|
tPS = String.Format("{0} {1}", drr("PS"), drr("Obs"))
|
|
End If
|
|
End If
|
|
|
|
'CONDICIONANTE, ESPECIAL
|
|
If Obj.CveEmpresa = 15 Then drr("UM") = "" 'LES COMENTAN QUE NO DEBE IR LA ETIQUETA DE LA UNIDAD EN EL PRODUCTO
|
|
|
|
Dim concepto As New CFDIConceptos With {.Cantidad = drr("Cantidad").ToString.ToDecimal,
|
|
.Descripcion = tPS,
|
|
.ValorUnitario = drr("PU").ToString.ToDecimal,
|
|
.Importe = drr("TotalImporte").ToString.ToDecimal,
|
|
.Descuento = drr("Descuento").ToString.ToDecimal,
|
|
.Unidad = drr("UM").ToString,
|
|
.ClaveUnidad = drr("SATClaveUM").ToString,
|
|
.ClaveProdServ = drr("SATClaveProdServ").ToString,
|
|
.Noidentificacion = drr("Noidentificacion").ToString,
|
|
.CuentaPredial = drr("CuentaPredial").ToString}
|
|
'VERIFICA SUMA SUBTOTALES
|
|
If i = Obj.DtDetalle.Rows.Count AndAlso totSubTotal <> concepto.Importe Then 'PROCESO DE AJUSTA DE DECIMALES
|
|
concepto.Importe = totSubTotal
|
|
End If
|
|
totSubTotal = totSubTotal - concepto.Importe
|
|
|
|
'SIEMPRE ESTAMOS AGREGANDO EL IVA
|
|
concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "T", .Base = concepto.Importe - concepto.Descuento, .TasaOCuota = drr("PorcentajeIVA").ToString.ToDecimal, .Impuesto = "002", .Importe = drr("ImporteIVA").ToString.ToDecimal})
|
|
|
|
If drr("ImporteIEPS").ToString.ToDouble > 0 Then
|
|
concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "T", .Base = concepto.Importe - concepto.Descuento, .TasaOCuota = drr("PorcentajeIEPS").ToString.ToDecimal, .Impuesto = "003", .Importe = drr("ImporteIEPS").ToString.ToDecimal})
|
|
End If
|
|
|
|
If drr("ImporteRetIVA").ToString.ToDouble > 0 Then 'si hay retenciones
|
|
concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "R", .Base = concepto.Importe - concepto.Descuento, .TasaOCuota = drr("PorcentajeRetIVA").ToString.ToDecimal, .Impuesto = "002", .Importe = drr("ImporteRetIVA").ToString.ToDecimal})
|
|
End If
|
|
|
|
If drr("ImporteRetISR").ToString.ToDouble > 0 Then 'retención de ISR
|
|
concepto.Impuestos.Add(New CFDIConceptosImpuestos With {.TrasladooRetencion = "R", .Base = concepto.Importe - concepto.Descuento, .TasaOCuota = drr("PorcentajeRetISR").ToString.ToDecimal, .Impuesto = "001", .Importe = drr("ImporteRetISR").ToString.ToDecimal})
|
|
End If
|
|
|
|
Timbre.Conceptos.Add(concepto)
|
|
i += 1
|
|
Next
|
|
Return Timbre
|
|
End Function
|
|
Private Function CreaDTDetalle(ByRef ObjInventarios As ClsInventarios, ObjFactura As Modelos.Factura, ByRef Retorno As Modelos.Factura.MMensajeFactura, UsuarioActual As Usuario, JsonRequest As JObject) As DataTable
|
|
Dim TmpDT = New DataTable
|
|
TmpDT.Columns.Add("CveVenta", GetType(Integer))
|
|
TmpDT.Columns.Add("Consec", GetType(Integer))
|
|
TmpDT.Columns.Add("Cantidad", GetType(Decimal))
|
|
TmpDT.Columns.Add("Codigo", GetType(String))
|
|
TmpDT.Columns.Add("CveUM", GetType(Integer))
|
|
TmpDT.Columns.Add("UM", GetType(String))
|
|
TmpDT.Columns.Add("SATClaveUM", GetType(String))
|
|
TmpDT.Columns.Add("CveClasificacion", GetType(Integer))
|
|
TmpDT.Columns.Add("Clasificacion", GetType(String))
|
|
TmpDT.Columns.Add("CvePS", GetType(Integer))
|
|
TmpDT.Columns.Add("PS", GetType(String))
|
|
TmpDT.Columns.Add("CodigoPS", GetType(String))
|
|
TmpDT.Columns.Add("SATClaveProdServ", GetType(String))
|
|
TmpDT.Columns.Add("NoIdentificacion", GetType(String))
|
|
TmpDT.Columns.Add("CveTipoPS", GetType(Integer))
|
|
TmpDT.Columns.Add("CveTipoInvPS", GetType(Integer))
|
|
TmpDT.Columns.Add("Serie", GetType(String))
|
|
TmpDT.Columns.Add("CuentaPredial", GetType(String))
|
|
TmpDT.Columns.Add("Obs", GetType(String))
|
|
TmpDT.Columns.Add("TiempoEntrega", GetType(String))
|
|
TmpDT.Columns.Add("PU", GetType(Decimal))
|
|
TmpDT.Columns.Add("IVA", GetType(Decimal))
|
|
TmpDT.Columns.Add("ImporteIVA", GetType(Decimal))
|
|
TmpDT.Columns.Add("PorcentajeIVA", GetType(Decimal))
|
|
TmpDT.Columns.Add("ImporteRetIVA", GetType(Decimal))
|
|
TmpDT.Columns.Add("ImporteRetISR", GetType(Decimal))
|
|
TmpDT.Columns.Add("PorcentajeRetIVA", GetType(Decimal))
|
|
TmpDT.Columns.Add("PorcentajeRetISR", GetType(Decimal))
|
|
TmpDT.Columns.Add("ImporteIEPS", GetType(Decimal))
|
|
TmpDT.Columns.Add("IEPS", GetType(Decimal))
|
|
TmpDT.Columns.Add("PorcentajeIEPS", GetType(Decimal))
|
|
TmpDT.Columns.Add("Descuento", GetType(Decimal))
|
|
TmpDT.Columns.Add("TipoDescuento", GetType(Integer))
|
|
TmpDT.Columns.Add("TotalImporte", GetType(Decimal))
|
|
TmpDT.Columns.Add("Total", GetType(Decimal))
|
|
'Para uso del módulo contable
|
|
TmpDT.Columns.Add("AsientoContableVentas", GetType(Integer))
|
|
TmpDT.Columns.Add("IdCtaContVentas", GetType(Integer))
|
|
TmpDT.Columns.Add("AplicaParaConcepto", GetType(Boolean))
|
|
TmpDT.Columns.Add("CveProyecto", GetType(Integer))
|
|
TmpDT.Columns.Add("Proyecto", GetType(String))
|
|
TmpDT.Columns.Add("CveSubProyecto", GetType(Integer))
|
|
TmpDT.Columns.Add("SubProyecto", GetType(String))
|
|
'TipoDescuento: 1 = Descuento * PU; 2 = Descuento por Total del concepto
|
|
TmpDT.Columns.Add("CvePresupuestoIngreso", GetType(Integer))
|
|
TmpDT.Columns.Add("CveFuenteRecaudacion", GetType(Integer))
|
|
'Contratos
|
|
TmpDT.Columns.Add("CveContratoDetalle", GetType(Integer))
|
|
'Remisiones a Facturas
|
|
TmpDT.Columns.Add("CveVentaDetalle", GetType(Integer))
|
|
TmpDT.Columns.Add("CveVentaDetalleRemision", GetType(Integer))
|
|
TmpDT.Columns.Add("CveVentaDetalleCotizacion", GetType(Integer))
|
|
|
|
'Pedido2 a Facturas
|
|
TmpDT.Columns.Add("CveVentaDetallePedido2", GetType(Integer))
|
|
|
|
TmpDT.Columns.Add("Origen", GetType(Integer))
|
|
'Ordenes Servicio
|
|
TmpDT.Columns.Add("CveOS", GetType(Integer))
|
|
TmpDT.Columns.Add("CveOSDetalle", GetType(Integer))
|
|
TmpDT.Columns.Add("SeFacturara", GetType(Integer))
|
|
TmpDT.Columns.Add("Folio", GetType(Integer))
|
|
TmpDT.Columns.Add("Estatus", GetType(String))
|
|
'Ordenamiento
|
|
TmpDT.Columns.Add("Orden", GetType(Integer))
|
|
TmpDT.Columns.Add("TipoDocto", GetType(String))
|
|
'OC
|
|
TmpDT.Columns.Add("CveOrdenCompraDetalle", GetType(Integer))
|
|
TmpDT.Columns.Add("EntregaDirecta", GetType(Integer))
|
|
|
|
TmpDT.Columns.Add("CveMovimientoDetallePedido", GetType(Integer))
|
|
TmpDT.Columns.Add("CantidadFacturadaRem", GetType(Decimal))
|
|
TmpDT.Columns.Add("CantidadFacturadaCot", GetType(Decimal))
|
|
TmpDT.Columns.Add("CantidadInventario", GetType(Decimal))
|
|
|
|
TmpDT.Columns.Add("ClaveSATFraccionArancelaria", GetType(String))
|
|
TmpDT.Columns.Add("ClaveSATUnidadAduana", GetType(String))
|
|
TmpDT.Columns.Add("ClaveSATFraccionArancelariaDescripcion", GetType(String))
|
|
TmpDT.Columns.Add("ClaveSATUnidadAduanaDescripcion", GetType(String))
|
|
|
|
TmpDT.Columns.Add("CveTamaño", GetType(Integer))
|
|
|
|
|
|
Try
|
|
Dim ListaPS = JArray.Parse(JsonRequest("details").ToString())
|
|
Dim DescuentoTotal As Decimal = JsonRequest("discount").ToString().ToDecimal()
|
|
Dim DescuentoPorPartida As Decimal = (DescuentoTotal / ListaPS.Count)
|
|
|
|
Dim Consec As Integer = 1
|
|
For Each JsonPS As JObject In ListaPS
|
|
Dim Cantidad As Decimal = JsonPS("quantity").ToString.ToDecimal()
|
|
|
|
Dim CvePS As Integer = GlobalDTPSSimplificado(Codigo:=JsonPS("product_sku").ToString()).FiltroPrimeroValor("CvePS").ToEntero()
|
|
|
|
Dim DrPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("")
|
|
|
|
If DrPS Is Nothing Then
|
|
Retorno.TieneError = True
|
|
Retorno.Mensajes.Add(String.Format("No se pudo agregar el producto/servicio: {0}, no se encontró en el sistema", JsonPS("product_sku").ToString()))
|
|
Exit For
|
|
End If
|
|
|
|
'VALIDAR QUE SEA EL MISMO PRODUCTO
|
|
If DrPS("Codigo").ToString() <> JsonPS("product_sku").ToString() Then
|
|
Retorno.TieneError = True
|
|
Retorno.Mensajes.Add(String.Format("No se pudo agregar el producto/servicio: {0}", DrPS("PS").ToString()))
|
|
Exit For
|
|
End If
|
|
|
|
'VALIDA EXISTENCIA ANTES DE GENERAR LA FACTURA
|
|
If ObjFactura.TipoDocto = "Ing" AndAlso DrPS("CveTipoPS").ToString() = "2" Then
|
|
Dim Existencia As Decimal = ObjInventarios.GetExistenciasPS(DrPS("CvePS").ToString.ToEntero, DrPS("CveUnidadMedida").ToString.ToEntero, UsuarioActual.CveEmpresa, ObjFactura.CveAlmacen, CveSubProyecto:=ObjFactura.CveSubProyecto, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm"), ExcluyeAdelantado:=1, PendientePorSurtir:=1, RestringirAlmacenes:=1, ExcluyeApartados:=-1)
|
|
|
|
If Cantidad > Existencia Then
|
|
Retorno.TieneError = True
|
|
Retorno.Mensajes.Add(String.Format("No hay existencia suficiente para este producto: {0}, cuenta con : {1}", DrPS("PSCodigo").ToString(), Existencia))
|
|
Exit For
|
|
End If
|
|
End If
|
|
|
|
|
|
Dim TotalOriginal As Decimal = JsonPS("total_cost").ToString.ToDecimal()
|
|
|
|
Dim PUOrginal As Decimal = JsonPS("cost").ToString.ToDecimal()
|
|
|
|
Dim PorcentajeIVADefault As Decimal = 0.16D
|
|
|
|
Dim DrSubProyecto As DataRow = GlobalDTSubProyectos(-1, JsonRequest("branch_office_id").ToEntero(), CveEmpresa:=CveEmpresa).Rows(0)
|
|
|
|
If DrSubProyecto IsNot Nothing Then
|
|
PorcentajeIVADefault = DrSubProyecto("IVA").ToString().ToDecimal()
|
|
Else
|
|
PorcentajeIVADefault = 0.16D
|
|
End If
|
|
|
|
Dim SubTotal2 As Decimal = (TotalOriginal / (1 + PorcentajeIVADefault))
|
|
|
|
Dim IVA As Decimal = Math.Abs(SubTotal2 - TotalOriginal)
|
|
|
|
Dim SubTotal As Decimal = (SubTotal2 + DescuentoPorPartida)
|
|
|
|
Dim PUCalculado As Decimal = (SubTotal / Cantidad)
|
|
|
|
Dim Row As DataRow = AgregarProductoServicio(Retorno, UsuarioActual, TmpDT, Consec, Cantidad, DrPS("CveUnidadMedida").ToString.ToEntero, DrPS("UnidadMedida").ToString, DrPS("CveClasificacion").ToString.ToEntero, DrPS("Clasificacion").ToString,
|
|
DrPS("CvePS").ToString.ToEntero, DrPS("PS").ToString, "", PUCalculado, DescuentoPorPartida,
|
|
CveSubProyecto:=ObjFactura.CveSubProyecto, CveVentaDetalle:=-1, CveContratoDetalle:=-1, CveVentaDetalleRemision:=-1, RegeneraIEPS:=True)
|
|
If Row IsNot Nothing Then
|
|
TmpDT.Rows.Add(Row)
|
|
Else
|
|
Retorno.TieneError = True
|
|
Retorno.Mensajes.Add(String.Format("No se pudo agregar el producto/servicio: {0}", DrPS("PSCodigo").ToString()))
|
|
Exit For
|
|
End If
|
|
|
|
Consec += 1
|
|
Next
|
|
|
|
Catch ex As Exception
|
|
Retorno.TieneError = True
|
|
Retorno.Mensajes.Add(ex.ToString())
|
|
End Try
|
|
|
|
If Retorno.TieneError = True Then
|
|
TmpDT.Clear()
|
|
TmpDT = Nothing
|
|
End If
|
|
|
|
Return TmpDT
|
|
End Function
|
|
|
|
Private Function AgregarProductoServicio(ByRef Retorno As Modelos.Factura.MMensajeFactura, UsuarioActual As Usuario, TmpDT As DataTable, Consec As Integer, Cantidad As Decimal, CveUM As Integer, UM As String, CveClasificacion As Integer, Clasificacion As String, CvePS As Integer, PS As String, Obs As String,
|
|
PU As Decimal, Descuento As Decimal, CveSubProyecto As Integer,
|
|
Optional Serie As String = "", Optional TiempoEntrega As String = "", Optional EntregaDirecta As Integer = 0,
|
|
Optional CveContratoDetalle As Integer = 0, Optional CveVentaDetalle As Integer = 0, Optional CveMovimientoDetallePedido As Integer = 0,
|
|
Optional CveOrdenCompraDetalle As Integer = 0, Optional CveVentaDetalleRemision As Integer = 0, Optional CveVentaDetalleCotizacion As Integer = 0,
|
|
Optional CuentaPredial As String = "", Optional RegeneraIEPS As Boolean = True, Optional CveVentaDetallePedido2 As Integer = 0,
|
|
Optional ClienteRetIVA As Double = 0, Optional ClienteRetISR As Double = 0, Optional ClienteDesglosaIEPS As Boolean = True) As DataRow
|
|
|
|
|
|
Dim DrPS As DataRow = GlobalDTPS(UsuarioActual.CveEmpresa, CvePS:=CvePS).FiltroPrimero("")
|
|
|
|
If DrPS Is Nothing Then
|
|
Retorno.Mensajes.Add("Ocurrió un error al cargar la información del Producto. Por favor vuelva a intentar.")
|
|
Return Nothing
|
|
End If
|
|
|
|
'verifica si tiene ventaminima
|
|
If Cantidad > 0 AndAlso DrPS("VentaMinima").ToString.ToDouble() > 0 Then
|
|
'verifico que la cantidad sea multiplo de venta minima, es decir ventaminima =5, solo puede vender 5,10,15...
|
|
If Cantidad < DrPS("VentaMinima").ToString.ToDouble() Then
|
|
Retorno.Mensajes.Add("La cantidad es menor que la venta minima")
|
|
Return Nothing
|
|
End If
|
|
End If
|
|
|
|
If (DrPS("SATClaveUnidadMedida").ToString = "" Or DrPS("SATClavePS").ToString = "") Then
|
|
'VALIDA CLAVESAT
|
|
If DrPS("SATClavePS").ToString = "" Then
|
|
Retorno.Mensajes.Add(String.Format("<b>{0}-{1}</b>: Sin producto SAT<br/>", DrPS("Codigo").ToString, DrPS("PS").ToString))
|
|
Return Nothing
|
|
ElseIf DrPS("SATClaveUnidadMedida").ToString = "" Then
|
|
Retorno.Mensajes.Add(String.Format("<b>{0}-{1}</b>: Sin Unidad Medida SAT<br/>", DrPS("Codigo").ToString, DrPS("PS").ToString))
|
|
Return Nothing
|
|
End If
|
|
End If
|
|
|
|
If Not ClienteDesglosaIEPS Then
|
|
If Not RegeneraIEPS Then
|
|
PU = PU * (1 + DrPS("IEPSPorcentaje").ToString.ToDecimal)
|
|
End If
|
|
DrPS("IEPSPorcentaje") = 0
|
|
End If
|
|
|
|
Dim Row As DataRow = Nothing
|
|
Dim TotalCalculableImpuestos As Decimal = 0
|
|
PU = Math.Round(PU, 6) ' el precio unitario puede llevar hasta 6 decimales permitidos
|
|
Dim DrSubProyecto As DataRow = GlobalDTSubProyectos(-1, CveSubProyecto).Rows(0)
|
|
|
|
Row = TmpDT.NewRow()
|
|
Row("CveProyecto") = DrSubProyecto("CveProyecto").ToString().ToEntero()
|
|
Row("Proyecto") = DrSubProyecto("Proyecto").ToString()
|
|
Row("CveSubProyecto") = CveSubProyecto
|
|
Row("SubProyecto") = DrSubProyecto("SubProyecto").ToString()
|
|
Row("Serie") = Serie
|
|
Row("TiempoEntrega") = TiempoEntrega
|
|
Row("Orden") = TmpDT.Rows.Count + 1
|
|
Row("Cantidad") = Cantidad
|
|
Row("CveUM") = CveUM
|
|
Row("UM") = UM
|
|
Row("CveClasificacion") = CveClasificacion
|
|
Row("Clasificacion") = Clasificacion
|
|
Row("CvePS") = CvePS
|
|
Row("Obs") = Obs
|
|
|
|
TotalCalculableImpuestos = (Cantidad * PU) - Descuento
|
|
|
|
Row("PU") = PU
|
|
Row("Codigo") = DrPS("Codigo")
|
|
Row("NoIdentificacion") = DrPS("Codigo")
|
|
Row("ClaveSATFraccionArancelaria") = DrPS("ClaveSATFraccionArancelaria")
|
|
Row("ClaveSATUnidadAduana") = DrPS("ClaveSATUnidadAduana")
|
|
Row("ClaveSATFraccionArancelariaDescripcion") = DrPS("ClaveSATFraccionArancelariaDescripcion")
|
|
Row("ClaveSATUnidadAduanaDescripcion") = DrPS("ClaveSATUnidadAduanaDescripcion")
|
|
Row("Consec") = Consec
|
|
|
|
Row("PS") = DrPS("PS")
|
|
Row("CodigoPS") = DrPS("PSCodigo").ToString
|
|
Row("CveTipoPS") = DrPS("CveTipoPS")
|
|
Row("CveTipoInvPS") = DrPS("Inv_CveMetodoInventario")
|
|
Row("CveTamaño") = DrPS("CveTamaño")
|
|
|
|
If CveClasificacion <= 0 Then Row("CveClasificacion") = DrPS("CveClasificacion")
|
|
If Clasificacion = "" Then Row("Clasificacion") = DrPS("Clasificacion")
|
|
|
|
If DrPS("IVA").ToString.Contiene("-1", "") Then
|
|
Row("PorcentajeIVA") = DrSubProyecto("IVA")
|
|
Else
|
|
Row("PorcentajeIVA") = DrPS("IVA")
|
|
End If
|
|
|
|
Row("IVA") = Row("PorcentajeIVA")
|
|
Row("ImporteIVA") = Math.Round(Row("PorcentajeIVA").ToString.ToDecimal * TotalCalculableImpuestos, 2)
|
|
Row("ImporteRetIVA") = Math.Round(ClienteRetIVA * TotalCalculableImpuestos, 2)
|
|
Row("ImporteRetISR") = Math.Round(ClienteRetISR * TotalCalculableImpuestos, 2)
|
|
Row("PorcentajeRetIVA") = ClienteRetIVA
|
|
Row("PorcentajeRetISR") = ClienteRetISR
|
|
Row("PorcentajeIEPS") = DrPS("IEPSPorcentaje")
|
|
Row("ImporteIEPS") = Math.Round(DrPS("IEPSPorcentaje").ToString.ToDecimal * TotalCalculableImpuestos, 2)
|
|
Row("IEPS") = Row("ImporteIEPS")
|
|
Row("Descuento") = Math.Round(Descuento, 2)
|
|
Row("TipoDescuento") = "2"
|
|
|
|
Row("Total") = Cantidad * PU
|
|
Row("TotalImporte") = Math.Round(Cantidad * PU, 2)
|
|
|
|
Row("SATClaveProdServ") = DrPS("SATClavePS")
|
|
Row("SATClaveUM") = DrPS("SATClaveUnidadMedida")
|
|
|
|
Row("EntregaDirecta") = EntregaDirecta
|
|
'Contratos
|
|
Row("CveContratoDetalle") = CveContratoDetalle
|
|
Row("CveVentaDetalle") = CveVentaDetalle
|
|
Row("CveMovimientoDetallePedido") = CveMovimientoDetallePedido
|
|
Row("CveOrdenCompraDetalle") = CveOrdenCompraDetalle
|
|
Row("CveVentaDetalleRemision") = CveVentaDetalleRemision
|
|
Row("CveVentaDetalleCotizacion") = CveVentaDetalleCotizacion
|
|
Row("CveVentaDetallePedido2") = CveVentaDetallePedido2
|
|
Row("CuentaPredial") = CuentaPredial
|
|
|
|
'RECARGAR GV
|
|
Return Row
|
|
End Function
|
|
#End Region
|
|
|
|
#End Region
|
|
Private Function RegistrarCotizacion(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 TieneError Then
|
|
RespuestaError.message = "Ocurrió un error al obtener el cuerpo de los parametros"
|
|
context.Response.StatusCode = 200
|
|
Return JsonConvert.SerializeObject(RespuestaError)
|
|
End If
|
|
|
|
If Not TieneError Then
|
|
Dim Usuario As Usuario = ValidaUsuarioSistema(100, CveEmpresa)
|
|
If Usuario IsNot Nothing Then
|
|
Dim Resp As New Modelos.Factura.MMensajeFactura
|
|
Dim ObjClientes As New ClsClientes()
|
|
Dim ObjInventario As New ClsInventarios(ObjClientes.IniciaTransacSQL())
|
|
|
|
Try
|
|
Dim ObjFactura = CreaFactura(ObjInventario, ObjClientes, "Cot", Resp, JsonRequest, Usuario)
|
|
|
|
If ObjFactura IsNot Nothing Then
|
|
Resp = ObjFactura.EmitirFactura(False, Transac:=ObjClientes.IniciaTransacSQL())
|
|
|
|
If Resp.CveVenta > 0 Then
|
|
Respuesta.status = "success"
|
|
Respuesta.data = Resp.SerieFolio
|
|
Else
|
|
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
|
|
|
|
ObjFactura.Dispose()
|
|
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
|
|
|
|
Catch ex As Exception
|
|
TieneError = True
|
|
End Try
|
|
|
|
If TieneError Then
|
|
ObjClientes.RollBack()
|
|
Else
|
|
ObjClientes.Commit()
|
|
End If
|
|
|
|
ObjClientes.Dispose()
|
|
ObjInventario.Dispose()
|
|
Else
|
|
TieneError = True
|
|
RespuestaError.message = "no hay un usuario disponible"
|
|
End If
|
|
|
|
End If
|
|
|
|
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 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
|
|
|
|
Respuesta.data = data
|
|
|
|
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 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 = 200
|
|
|
|
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 = 200
|
|
|
|
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)
|
|
request.Headers.Add("X-Authentication", 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 CrearActualizarProductosJson(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
|
|
'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
|
|
payload.Add(New JProperty("products", GenerarPayloadProductos(DtPS)))
|
|
End If
|
|
|
|
Return payload.ToString()
|
|
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 ActualizarPreciosJson(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
|
|
'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
|
|
payload.Add(New JProperty("products", GenerarPayloadPrecios(DtPS)))
|
|
End If
|
|
|
|
Return payload.ToString()
|
|
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 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 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 - V E N D E D O R E 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", RowVendedor("CodigoVendedor")),
|
|
New JProperty("default_branchoffice", RowVendedor("CveSubProyecto"))
|
|
)
|
|
|
|
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
|
|
|
|
If CountPeticionesExitosas > 0 Then
|
|
Retorno = True
|
|
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
|
|
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 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 |