Club Delphi  
    FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Principal > Varios
Registrarse FAQ Miembros Calendario Guía de estilo Temas de Hoy

Grupo de Teaming del ClubDelphi

Respuesta
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 07-02-2017
Avatar de noshy
noshy noshy is offline
Miembro
 
Registrado: jul 2003
Posts: 139
Poder: 21
noshy Va por buen camino
Código Delphi [-]
procedure TFDespachoAutomatico.server2Execute(AContext: TIdContext);
var
  vDespDatoRec       : string;  //Guarda la Cadena Recibida
  vDespRespLogin     : Integer; //Resuesta del Login
  vDespJSONDato      : TlkJSONobject;
  vDespJSONRespuestaFinal : TlkJSONobject;
  vDespJSONRespuestaLogin : TlkJSONobject;
  vDespUsuario       : string;  //Usuario logueado
  vDespLoginVersion  : string;
  vDespAuxS          : string;  //Variable Auxiliar String
  vDespTipoDato      : Integer; //Tipo de dato solicitado
  vDespMovil         : Integer; //Movil que envia la posicion
  vDespIdViaje       : Integer;   //Id Viaje Datos
  vDespIdViajeEnUso  : Integer; //Id Viaje En Uso
  vDespDomicilio     : string;
  vDespObservaciones : string;
  vDespViajeLat      : string;
  vDespViajeLng      : string;
  vDespRespS         : string;
  vDespMsgError      : string;



        //Funcion IdViajeEnusoInt ----------------------------------------------
        function IdViajeEnusoInt(vIdViaje: Integer):Integer;
        var
          vQryVEU : TADOQuery;
        begin
          Result := 0;
          vQryVEU            := TADOQuery.Create(nil);
          vQryVEU.Connection := conDB1;
          try
            with vQryVEU do
            begin
              Close;
              SQL.Clear;
              SQL.Add('Select idViajeEnUso from AppViajes_DatoViajes with (NOLOCK) where ');
              SQL.Add('id = :vIdViaje ');
              Parameters.ParamByName('vIdViaje').Value := vIdViaje;
              Open;
            end;
            if vQryVEU.RecordCount > 0 then
              Result := vQryVEU['idViajeEnUso']
            else
              Result := 0;
          finally
            FreeAndNil(vQryVEU);
          end;
        end;
        //Fin Funcion IdViajeEnusoInt ------------------------------------------

        //Funcion GrabarLogint -------------------------------------------------
        procedure GrabarlogInt(vDato, vCarpeta : string);
        var
         F: TextFile;
         Nombre :string;
        begin
          try
            if not DirectoryExists(GetCurrentDir + '\Log') then
              CreateDir(GetCurrentDir + '\Log');

            if not DirectoryExists(GetCurrentDir + '\Log\' + vCarpeta) then
              CreateDir(GetCurrentDir + '\Log\' + vCarpeta);

            nombre:=GetCurrentDir + '\Log\' + vCarpeta + '\' + FormatDateTime('YYYYMMDD',Now) + '.log';

            AssignFile(F, nombre);

            if (FileExists(nombre)) then
              Append(F)
            else
              ReWrite(F);

            if vCarpeta = 'Despacho' then
              Writeln(F, vDato )
            else
              Writeln(F, '['+DateTimeToStr(Now)+'] '+ vDato );
          finally
            CloseFile(F);
          end;
        end;
        //Fin Funcion GrabarLogint ---------------------------------------------

        //Funcion LogInt -------------------------------------------------------
        procedure LogInt(vDespLog: string; vDespTipo: Integer);
        begin
          case vDespTipo of
           0: begin //Log Errores
                GrabarlogInt(vDespLog,'Errores');  //Log Errores
                //Mostramos el log
                mmoErrores.Lines.Add(DateTimeToStr(Now)+' - '+vDespLog);
                //Booramos el excedente de 100 lineas
                if mmoErrores.Lines.Count > 20 then
                begin
                   mmoErrores.Lines.Delete(0);
                   mmoErrores.Lines.Delete(0);
                end;
                SendMessage(mmoErrores.Handle, EM_SCROLL, SB_BOTTOM, 0);
              end;
           1: begin //Log Crudo
                GrabarlogInt(vDespLog,'Crudo');  //Log Crudo
                if chkLogCrudo.Checked then
                begin
                  //Mostramos el log
                  mmoLog.Lines.Add(DateTimeToStr(Now)+' - '+vDespLog);
                  //Booramos el excedente de 100 lineas
                  if mmoLog.Lines.Count > 20 then
                  begin
                     mmoLog.Lines.Delete(0);
                     mmoLog.Lines.Delete(0);
                  end;
                  SendMessage(mmoLog.Handle, EM_SCROLL, SB_BOTTOM, 0);
                end;
              end;
           2: begin //Log Viajes
                GrabarlogInt(vDespLog,'Viajes');  //Log Viajes
                if chkLogViaje.Checked then
                begin
                  //Mostramos el log
                  mmoLog.Lines.Add(DateTimeToStr(Now)+' - '+vDespLog);
                  //Booramos el excedente de 100 lineas
                  if mmoLog.Lines.Count > 20 then
                  begin
                     mmoLog.Lines.Delete(0);
                     mmoLog.Lines.Delete(0);
                  end;
                  SendMessage(mmoLog.Handle, EM_SCROLL, SB_BOTTOM, 0);
                end;
              end;
          end;
        end;
        //Fin Funcion LogInt ---------------------------------------------------

        //Funcion DatoViajesInt ------------------------------------------------
        function DatoViajesInt(vDespLeido : Boolean; vDespRespuesta, vDespId: Integer):Boolean;
        var
          vQryDato : TADOQuery;
        begin
          Result := True;
          vQryDato            := TADOQuery.Create(nil);
          vQryDato.Connection := conDB;
          try
            with vQryDato do
            begin
              Close;
              SQL.Clear;
              SQL.Add('update AppViajes_DatoViajes set leido = :vleido, respuesta = :vrespuesta ');
              if vDespRespuesta = 1 then
              begin
                SQL.Add(',TipoDato = 2 ');
              end;
              SQL.Add('where id = :vid ');
              Parameters.ParamByName('vleido').Value     := vDespLeido;
              Parameters.ParamByName('vrespuesta').Value := vDespRespuesta;
              Parameters.ParamByName('vid').Value        := vDespId;
              ExecSQL;
            end;
          finally
            FreeAndNil(vQryDato);
          end;
        end;
        //Fin Funcion DatoViajesInt ----------------------------------

        //Procedimiento GuardarPosicionInt -------------------------------
        procedure GuardarPosicionInt(vDespMovil, vDespEstado, vDespConConsulta: Integer; vDespLat, vDespLng: string; vDespFecha: TDateTime );
        var
          vCant : Integer;
          vQryGP  : TADOQuery;
        begin
          vQryGP := TADOQuery.Create(nil);
          vQryGP.Connection := conDB;
          try
            with vQryGP do
            begin
              Close;
              SQL.Clear;
              SQL.Add('Select count(*) as total from AppViajes_UltimaPosicion with (NOLOCK) where movil = :movil');
              Parameters.ParamByName('movil').Value := vDespMovil;
              Open;
            end;
            vCant := vQryGP['total'];
            if vCant > 0 then
            begin
              with vQryGP do
              begin
                Close;
                SQL.Clear;
                SQL.Add('update AppViajes_UltimaPosicion set lat = :lat, lng = :lng, fecha = :fecha, estado = :estado, conConsulta = :conConsulta');
                SQL.Add('where movil = :movil');
                Parameters.ParamByName('lat').Value         := vDespLat;
                Parameters.ParamByName('lng').Value         := vDespLng;
                Parameters.ParamByName('fecha').Value       := vDespFecha;
                Parameters.ParamByName('estado').Value      := vDespEstado;
                Parameters.ParamByName('conConsulta').Value := vDespConConsulta;
                Parameters.ParamByName('movil').Value       := vDespMovil;
                ExecSQL;
              end;
            end
            else
            begin
              with vQryGP do
              begin
                Close;
                SQL.Clear;
                SQL.Add('Insert into AppViajes_UltimaPosicion(movil, lat, lng, fecha, estado, conConsulta)');
                SQL.Add('Values(:movil, :lat, :lng, :fecha, :estado, :conConsulta)');
                Parameters.ParamByName('movil').Value       := vDespMovil;
                Parameters.ParamByName('lat').Value         := vDespLat;
                Parameters.ParamByName('lng').Value         := vDespLng;
                Parameters.ParamByName('fecha').Value       := vDespFecha;
                Parameters.ParamByName('estado').Value      := vDespEstado;
                Parameters.ParamByName('conConsulta').Value := vDespConConsulta;
                ExecSQL;
              end;
            end;
          finally
            FreeAndNil(vQryGP);
          end;
        end;
        //FIN Procedimiento GuardarPosicion --------------------------------------

        //Funcion PosicionInt --------------------------------------------------
        function PosicionInt(vDespCadena: string):Boolean;
        var
          vJSONPosicion : TlkJSONobject;
          vMovil : Integer;
          vLat, vLng : string;
          vEstado : Integer;
        begin
          vJSONPosicion := TlkJSON.ParseText(vDespCadena) as TlkJSONobject;
          Result := False;
          try
            vMovil  := StrToInt(vartostr(vJSONPosicion.Field['posicion'].Field['movil'].Value));
            vLat    := vartostr(vJSONPosicion.Field['posicion'].Field['lat'].Value);
            vLat := ReplaceStr(Trim(vLat), '.', ',');
            vLng    := vartostr(vJSONPosicion.Field['posicion'].Field['lng'].Value);
            vLng := ReplaceStr(Trim(vLng), '.', ',');
            vEstado := StrToInt(vartostr(vJSONPosicion.Field['posicion'].Field['estado'].Value));

            if vEstado = 0 then
              vEstado := 3;

            if vEstado = 1 then
              vEstado := 2;

            GuardarPosicionInt(vMovil, vEstado, 0, vLat, vLng, now );
            Result := True;
          finally
            FreeAndnil(vJSONPosicion);
          end;
        end;
        //Fin Funcion PosicionInt ----------------------------------------------

        //Funcion PendienteLatInt ----------------------------------------------
        function PendienteLatInt(vDespIdViajeEnuso: Integer):string;
        var
          vQryLat : TADOQuery;
        begin
          Result := '';
          vQryLat            := TADOQuery.Create(nil);
          vQryLat.Connection := conDB;
          try
            with vQryLat do
            begin
              Close;
              SQL.Clear;
              SQL.Add('Select p.Lat from sat_viajespendientes p, AppViajes_ViajesEnUso u with (NOLOCK) where ');
              SQL.Add('p.id = u.idViajePendiente ');
              SQL.Add('and u.id = :vidviajeenuso ');
              Parameters.ParamByName('vidviajeenuso').Value := vDespIdViajeEnuso;
              Open;
            end;
            if vQryLat.RecordCount > 0 then
              Result := vQryLat['Lat']
            else
              Result := '';
          finally
            FreeAndNil(vQryLat);
          end;
        end;
        //Fin Funcion PendienteLatInt ------------------------------------------

        //funcion PendienteLngInt ----------------------------------------------
        function PendienteLngInt(vIdViajeEnuso: Integer):string;
        var
          vQryLng : TADOQuery;
        begin
          Result := '';
          vQryLng            := TADOQuery.Create(nil);
          vQryLng.Connection := conDB;
          try
            with vQryLng do
            begin
              Close;
              SQL.Clear;
              SQL.Add('Select p.Lng from sat_viajespendientes p, AppViajes_ViajesEnUso u with (NOLOCK) where ');
              SQL.Add('p.id = u.idViajePendiente ');
              SQL.Add('and u.id = :vidviajeenuso ');
              Parameters.ParamByName('vidviajeenuso').Value := vIdViajeEnuso;
              Open;
            end;
            if vQryLng.RecordCount > 0 then
              Result := vQryLng['Lng']
            else
              Result := '';
          finally
            FreeAndNil(vQryLng);
          end;
        end;
        //Fin funcion PendienteLngInt ------------------------------------------

        //Funcion ArmarDomicilioInt --------------------------------------------
        function ArmarDomicilioInt(vDomIdViajeEnuso: Integer):string;
        var
          vQryCalle : TADOQuery;
          vDomicilioArmado : string;
          vPiso, vDpto : string;
        begin
          vDomicilioArmado := '';
          Result := '';
          try
            vQryCalle            := TADOQuery.Create(nil);
            vQryCalle.Connection := conDB;
            with vQryCalle do
            begin
              Close;
              SQL.Clear;
              SQL.Add('Select p.calle, p.altura, p.piso, p.dpto from sat_viajespendientes p, AppViajes_ViajesEnUso u with (NOLOCK) where ');
              SQL.Add('p.id = u.idViajePendiente ');
              SQL.Add('and u.id = :vidviajeenuso ');
              Parameters.ParamByName('vidviajeenuso').Value := vDomIdViajeEnuso;
              Open;
            end;
            vDomicilioArmado := Trim(vQryCalle['calle']);
            vDomicilioArmado := vDomicilioArmado + ' ' + IntToStr(vQryCalle['altura']);

            try
              vPiso := Trim(vQryCalle['piso']);
              vDpto := Trim(vQryCalle['dpto']);
            except
              vPiso := '';
              vDpto := '';
            end;

            if vPiso.Length > 0 then
              vDomicilioArmado := vDomicilioArmado + ' Piso '+Trim(vQryCalle['piso']);

            if vDpto.Length > 0 then
              vDomicilioArmado := vDomicilioArmado + ' Dpto '+Trim(vQryCalle['dpto']);

            Result := vDomicilioArmado;

          finally
            FreeAndNil(vQryCalle);
          end;

        end;
        //Fin Funcion ArmarDomicilioInt ----------------------------------------

        //Funcion PendienteObservacionesInt ------------------------------------
        function PendienteObservacionesInt(vObsIdViajeEnuso: Integer):string;
        var
          vQryObservaciones : TADOQuery;
        begin
          Result := '';
          vQryObservaciones            := TADOQuery.Create(nil);
          vQryObservaciones.Connection := conDB;
          try
            with vQryObservaciones do
            begin
              Close;
              SQL.Clear;
              SQL.Add('Select p.observaciones from sat_viajespendientes p, AppViajes_ViajesEnUso u with (NOLOCK) where ');
              SQL.Add('p.id = u.idViajePendiente ');
              SQL.Add('and u.id = :vidviajeenuso ');
              Parameters.ParamByName('vidviajeenuso').Value := vObsIdViajeEnuso;
              Open;
            end;
            if vQryObservaciones.RecordCount > 0 then
              Result := vQryObservaciones['observaciones']
            else
              Result := '';
          finally
            FreeAndNil(vQryObservaciones);
          end;
        end;


        //Funcion PendienteBarrioInt -------------------------------------------
        function PendienteBarrioInt(vBarrioIdViajeEnuso: Integer):string;
        var
          vQryBarrio : TADOQuery;
        begin
          Result := '';
          vQryBarrio            := TADOQuery.Create(nil);
          vQryBarrio.Connection := conDB;
          try
            with vQryBarrio do
            begin
              Close;
              SQL.Clear;
              SQL.Add('Select p.barrio from sat_viajespendientes p, AppViajes_ViajesEnUso u with (NOLOCK) where ');
              SQL.Add('p.id = u.idViajePendiente ');
              SQL.Add('and u.id = :vidviajeenuso ');
              Parameters.ParamByName('vidviajeenuso').Value := vBarrioIdViajeEnuso;
              Open;
            end;
            while not vQryBarrio.Eof do
            begin
              Result := Trim(vQryBarrio['barrio']);
              vQryBarrio.Next;
            end;

          finally
            FreeAndNil(vQryBarrio);
          end;
        end;
        //Fin Funcion PendienteBarrioInt ---------------------------------------

        //Funcion PendienteInfoTmpInt ------------------------------------------
        function PendienteInfoTmpInt(vInfoIdViajeEnuso: Integer):string;
        var
          vQryInfoTmp : TADOQuery;
        begin
          Result := '-';
          vQryInfoTmp            := TADOQuery.Create(nil);
          vQryInfoTmp.Connection := conDB;
          try
            with vQryInfoTmp do
            begin
              Close;
              SQL.Clear;
              SQL.Add('Select p.infotmp from sat_viajespendientes p, AppViajes_ViajesEnUso u with (NOLOCK) where ');
              SQL.Add('p.id = u.idViajePendiente ');
              SQL.Add('and u.id = :vidviajeenuso ');
              Parameters.ParamByName('vidviajeenuso').Value := vInfoIdViajeEnuso;
              Open;
            end;
            try
              Result := Trim(vQryInfoTmp['infotmp'])
            except
              Result := '-';
            end;
          finally
            FreeAndNil(vQryInfoTmp);
          end;
        end;
        //Fin Funcion PendienteInfoTmpInt --------------------------------------

        //Funcion ControlInt ---------------------------------------------------
        function ControlInt(vDespControlMovil: Integer):string;
        var
          vDespQryControl  : TADOQuery;
          //vDespCadenaCtr   : string;
          vDespJSONControl : TlkJSONobject;
          vDespText, vObs  : string;
          vDespIdViaje     : Integer;
          vDespBarrio      : string;
        begin
          Result := '';
          vDespQryControl := TADOQuery.Create(nil);
          vDespQryControl.Connection := conDB1;
          vDespJSONControl  := TlkJSONobject.Create;
          try
            with vDespQryControl do
            begin
              Close;
              SQL.Clear;
              SQL.Add('Select id, movil, texto, idViajeEnUso ');
              SQL.Add('from AppViajes_DatoViajes with (NOLOCK) where ');
              SQL.Add('movil = :vctrmovil and ');
              SQL.Add('tipodato = 1 and leido = 0 ');  //que tipodato = 1 (proposicion) y no este leido
              Parameters.ParamByName('vctrmovil').Value := vDespControlMovil;
              Open;
            end;

            //SI tiene viaje asignado
            while not vDespQryControl.Eof do
            begin
              //vText    := LimpiarTexto(vQryViajes['texto']);
              vDespText    := vDespQryControl['texto'];
              vDespIdViaje := vDespQryControl['id'];

              vDespBarrio  := PendienteBarrioInt(vDespQryControl['idViajeEnUso']);
              if vDespBarrio.Length > 0 then
                vObs := 'Barrio: '+vDespBarrio
              else
                vObs := '';

              //vObs     :=  vObs +' '+  LimpiarTexto(PendienteInfoTmp(vQryViajes['idViajeEnUso']));
              vObs     :=  vObs +' '+  PendienteInfoTmpInt(vDespQryControl['idViajeEnUso']);

              vDespJSONControl.Add('domicilio', vDespText);  //Domicilio
              vDespJSONControl.Add('obs', vObs);             //Observaqciones
              vDespJSONControl.Add('idviaje', vDespIdViaje); //Id VIaje

              //Se marca el viaje como leido y se devuelve la cadena co el viaje
              if DatoViajesInt(True, 0,vDespQryControl['Id']) then //cambiamos el viaje a leido
              begin
                Result := TlkJSON.GenerateText(vDespJSONControl);
              end;

              vDespQryControl.Next;
            end;
          finally
            FreeAndNil(vDespQryControl);
            FreeAndnil(vDespJSONControl);
          end;
        end;
        //Fin Funcion ControlInt -----------------------------------------------

        //Funcion ControlQTAInt ------------------------------------------------
        function ControlQTAInt(vDespQTAMovil: Integer):string;
        var
          vDespQryViajesQTA    : TADOQuery;
          vDespJSONControlQTA : TlkJSONobject;
          //vDespCadena: string;
          vDespIdViaje: Integer;
        begin
          vDespQryViajesQTA := TADOQuery.Create(nil);
          vDespQryViajesQTA.Connection := conDB2;
          vDespJSONControlQTA  := TlkJSONobject.Create;
          try
            //CONTROL DE VIAJES QTA ------------------------------------------------------
            with vDespQryViajesQTA do
            begin
              Close;
              SQL.Clear;
              SQL.Add('Select id, movil, idViajeEnUso ');
              SQL.Add('from AppViajes_DatoViajes with (NOLOCK) where ');
              SQL.Add('tipodato = 3 and leido = 0 and ');  //que tipodato = 3 (CANCELADO) y no este leido
              SQL.Add('movil = :vvqtamovil ');
              Parameters.ParamByName('vvqtamovil').Value := vDespQTAMovil;
              Open;
            end;
            //SI tiene viaje asignado
            while not vDespQryViajesQTA.Eof do
            begin
              vDespIdViaje := vDespQryViajesQTA['id'];

              vDespJSONControlQTA.Add('estado', 'qta');  //estado
              vDespJSONControlQTA.Add('movil', IntToStr(vDespQTAMovil));  //movil
              vDespJSONControlQTA.Add('idviajeqta', vDespIdViaje); //Id VIaje

              if DatoViajesInt(True, 0,vDespQryViajesQTA['Id']) then //cambiamos el viaje a leido
              begin
                Result := TlkJSON.GenerateText(vDespJSONControlQTA);
              end;

              vDespQryViajesQTA.Next
            end;
          finally
            FreeAndNil(vDespQryViajesQTA);
            FreeAndnil(vDespJSONControlQTA);
          end;
        end;
        //Fin Funcion ControlQTAInt --------------------------------------------

        //Funcion LoginInt -----------------------------------------------------
        function LoginInt(vDespCadena: string):Integer;
        var
          vDespJSONLogin : TlkJSONobject;
          vDespUser, vDespPass: string;
          vDespQryLogin : TADOQuery;
        begin
          Result := 3; //Por defecto lo ponemos como error interno al resultado
          vDespQryLogin := TADOQuery.Create(nil);
          vDespQryLogin.Connection := conDB;

          vDespUser := '-';
          vDespPass := '-';
          //Creamos el objeto con el json enviado
          vDespJSONLogin := TlkJSON.ParseText(vDespCadena) as TlkJSONobject;
          try
            try
              vDespUser := vartostr(vDespJSONLogin.Field['login'].Field['user'].Value);
              vDespPass := vartostr(vDespJSONLogin.Field['login'].Field['pass'].Value);
            except
              Result := 3; //Error interno
              //Exit;
            end;

            //Validacion del usuario
            with vDespQryLogin do
            begin
              Close;
              SQL.Clear;
              SQL.Add('Select count(*) as total from AppViajes_Choferes with (NOLOCK) where usuario = :vusu and password = :vpass ');
              Parameters.ParamByName('vusu').Value  := vDespUser;
              Parameters.ParamByName('vpass').Value := vDespPass;
              Open;
            end;
            if vDespQryLogin['total'] > 0 then
            begin
              Result := 0; //Ingreso permitido
            end
            else
            begin
              Result := 1; //Ingreso denegado
            end;
          finally
            FreeAndNil(vDespQryLogin);
            FreeAndnil(vDespJSONLogin);
          end;
        end;
        //Fin Funcion LoginInt -------------------------------------------------

        //Funcion ValidarMovilQRXInt -------------------------------------------
        function ValidarMovilQRXInt(vMovilQRX: Integer):string;
        var
          vFecha     : TDateTime;
          //vOrigenQRX : string;
          qryQRX     : TADOQuery;
          vJSONQRX   : TlkJSONobject;
          s          : string;
          vResultado :  Boolean;
        begin
          qryQRX            := TADOQuery.Create(nil);
          qryQRX.Connection := conDB;
          vJSONQRX := TlkJSONobject.Create;
          try
            Result := '{}';
            vResultado := False; //QAP

            //Validamos si el movil se encuentra QRX
            with qryQRX do
            begin
              Close;
              SQL.Clear;
              SQL.Add('Select GETDATE() as fecha ');
              Open;
            end;
            vFecha := qryQRX['fecha']; //Obtenermos la fecha del server
            with qryQRX do
            begin
              Close;
              SQL.Clear;
              SQL.Add('Select nromovil,indefinido,fechafin from sat_movilesqrx with (NOLOCK) where nromovil = :vmov ');
              SQL.Add('and fechainicio <= GETDATE()  ');
              Parameters.ParamByName('vmov').Value := vMovilQRX;
              Open;
            end;
            while not qryQRX.Eof do
            begin
              if qryQRX['nromovil'] = vMovilQRX then
              begin
                if qryQRX['indefinido']= 's' then
                begin
                  vResultado := True; //QRX sin fecha de fin
                end
                else
                begin
                  if vFecha < qryQRX['fechafin'] then
                  begin
                    vResultado := True; //QRX dentro de la fecha de fin
                  end;
                end;
              end;
              qryQRX.Next;
            end;

            if vResultado then
              vJSONQRX.Add('estado', 'QRX')
            else
              vJSONQRX.Add('estado', 'QAP');
            //------------------------------------------------------
            s := TlkJSON.GenerateText(vJSONQRX);

            Result := s;
          finally
            FreeAndNil(qryQRX);
            FreeAndnil(vJSONQRX);
          end;
        end;
        //Fin Funcion ValidarMovilQRXInt ---------------------------------------

        //Funcion UsuarioMovilInt ----------------------------------------------
        function UsuarioMovilInt(vUsuario: string): Integer;
        var
          vQryMovil : TADOQuery;
        begin
          vQryMovil := TADOQuery.Create(nil);
          vQryMovil.Connection := conDB;
          try
            //Validacion del usuario
            with vQryMovil do
            begin
              Close;
              SQL.Clear;
              SQL.Add('Select movil from AppViajes_Choferes with (NOLOCK) where usuario = :vusu');
              Parameters.ParamByName('vusu').Value  := Trim(vUsuario);
              Open;
            end;
            try
              Result := vQryMovil['movil'];
            except
              Result := 0;
            end;
          finally
            FreeAndNil(vQryMovil);
          end;
        end;
        //Fin Funcion UsuarioMovilInt ------------------------------------------

        //Funcion ViajesInt ----------------------------------------------------
        function ViajesInt(vViajeMovil: Integer):String;
        var
          vJSONViajes : TlkJSONobject;
          vQryViajes  : TADOQuery;
          vCount      : integer;
          s : string;
          vTotal : integer;
          vTexto : string;
        begin
          Result := '';
          vQryViajes := TADOQuery.Create(nil);
          vQryViajes.Connection := conDB;
          vJSONViajes := TlkJSONobject.Create;
          try
            with vQryViajes do
            begin
              Close;
              SQL.Clear;
              SQL.Add('Select top 5 calle, altura, fechaenviado, estado from sat_viajesenviadostmp with (NOLOCK) where movil = :vmovil ');
              SQL.Add('order by fechaenviado desc ');
              Parameters.ParamByName('vmovil').Value := vViajeMovil;
              Open;
            end;

            try
              vTotal := vQryViajes.RecordCount;
            except
              vTotal := 0;
            end;
            //Log(IntToStr(vTotal)+' Viajes');

            vCount := 1;

            //Log('Reg: '+IntToStr(vQry.RecordCount));

            while not vQryViajes.Eof do
            begin
              //vJSONRes.Add('dv'+IntToStr(vCount), '['+DateToStr(vQry['fecha'])+'] $'+FloatToStrF(vQry['deuda'],ffFixed,14,2)+'-'+trim(vQry['detalle']) );
              vTexto := '['+DateTimeToStr(vQryViajes['fechaenviado'])+'] '+Trim(vQryViajes['calle'])+' '+IntToStr(vQryViajes['altura']);
              if vQryViajes['estado'] = 'QTA' then
                 vTexto := vTexto +' ['+vQryViajes['estado']+']';
              vJSONViajes.Add('viaje'+IntToStr(vCount), vTexto);
              /////
              vCount := vCount + 1;
              vQryViajes.Next;
            end;
            //El en ultimo registro colocamos el total de viajes----
            vJSONViajes.Add('total', IntToStr(vTotal));
            //------------------------------------------------------

            s := TlkJSON.GenerateText(vJSONViajes);

            Result := s;

          finally
            FreeAndNil(vQryViajes);
            FreeAndnil(vJSONViajes);
          end;
        end;
        //Fin Funcion ViajesInt ------------------------------------------------
__________________
\_--> NoShY <--_/
Responder Con Cita
  #2  
Antiguo 07-02-2017
Avatar de noshy
noshy noshy is offline
Miembro
 
Registrado: jul 2003
Posts: 139
Poder: 21
noshy Va por buen camino
Código Delphi [-]
begin
  //Recibimos la cadena
  try
    vDespDatoRec := AContext.Connection.IOHandler.ReadLn();
  except
    Exit;
  end;

  if vDespDatoRec.Length < 5 then
  begin
    Exit;
  end;

  //Mostramos la cadena en el log
  logInt(vDespDatoRec,1);


  //Verificamos el tipo de campo que manda el JSON
  vDespTipoDato := 0; //Por defecto tipo de dato 0 (nada)

  //Mensaje de error por defecto en blanco
  vDespMsgError := '';


  vDespJSONDato := TlkJSON.ParseText(vDespDatoRec) as TlkJSONobject;
  try
    try
      vDespUsuario  := vartostr(vDespJSONDato.Field['login'].Field['user'].Value);
      vDespTipoDato := 1; //login
    except

    end;

    try
      vDespLoginVersion := vartostr(vDespJSONDato.Field['login'].Field['version'].Value);
    except
      vDespLoginVersion := '1';
    end;

    try
      vDespMovil := StrToInt(vartostr(vDespJSONDato.Field['posicion'].Field['movil'].Value));
      vDespTipoDato := 2; //Posicion
    except

    end;

    try
      vDespMovil   := StrToInt(vartostr(vDespJSONDato.Field['viajeaceptado'].Field['movil'].Value));
      vDespIdViaje := StrToInt(vartostr(vDespJSONDato.Field['viajeaceptado'].Field['idviaje'].Value));
      vDespTipoDato := 3; //Viaje Aceptado
    except

    end;

    try
      vDespMovil   := StrToInt(vartostr(vDespJSONDato.Field['viajerechazado'].Field['movil'].Value));
      vDespIdViaje := StrToInt(vartostr(vDespJSONDato.Field['viajerechazado'].Field['idviaje'].Value));
      vDespTipoDato := 4; //Viaje Rechazado
    except

    end;

    try
      vDespMovil   := StrToInt(vartostr(vDespJSONDato.Field['viajetimeout'].Field['movil'].Value));
      vDespIdViaje := StrToInt(vartostr(vDespJSONDato.Field['viajetimeout'].Field['idviaje'].Value));
      vDespTipoDato := 5; //Viaje time out
    except

    end;

    try
      vDespMovil := StrToInt(vartostr(vDespJSONDato.Field['historialviajes'].Field['movil'].Value));
      vDespTipoDato := 6; //Historial de Viajes
    except

    end;

    try
      vDespMovil := StrToInt(vartostr(vDespJSONDato.Field['estadoqapqrx'].Field['movil'].Value));
      vDespTipoDato := 7; //Estado del Móvil
    except

    end;

  finally
    vDespJSONDato.Free;
  end;


  //Si no trae algun dato salimos de la funcion
  if vDespTipoDato = 0  then
  begin
    Exit;
  end;


  //Procesamos los datos
  case vDespTipoDato of
  1: begin  //LOGIN
        //Armamos el JSON para enviar como respuesta
        vDespJSONRespuestaLogin  := TlkJSONobject.Create;
        try
          //Chequeamos el login y guardamos el resultado
          vDespRespLogin := LoginInt(vDespDatoRec);

          //Control de Version segun Config
          if vDespConfig_ControlVersion then
          begin
            try
              if StrToFloat(vDespLoginVersion) < vDespConfig_VersionActual then
              begin
                vDespRespLogin := 9;
                vDespMsgError := 'Esta utilizando una version obsoleta. Debe Actualizar la App...';
              end;
            except
              vDespRespLogin := 0;
            end;
          end;

          //Controlamos si hay otro usuario logueado
          {if LoginOtroUsuario(UsuarioMovil(vUsuario)) then
          begin
            vRespLogin := 9;
            vMsgError := 'Existe otro Usuario Logueado en el mismo Movil...';
          end;   }

          //permiso a la aplicacion
          vDespJSONRespuestaLogin.Add('permiso'          , IntToStr(vDespRespLogin) );
          //Config (segundos para el time out)
          vDespJSONRespuestaLogin.Add('segTimeOut'       , IntToStr(vDespConfig_AutoTimeOut) );       //armar la funcion con el setup
          vDespJSONRespuestaLogin.Add('movil'            , IntToStr(UsuarioMovilInt(vDespUsuario)) ); //enviamos el movil del usuario logueado
          vDespJSONRespuestaLogin.Add('intervaloreporte' , IntToStr(vDespConfig_IntervaloReporte) );  //Intervalo en seg para el reporte
          vDespJSONRespuestaLogin.Add('segfinalizarviaje', IntToStr(vDespConfig_FinalizarViaje) );    //Intervalo en seg para el reporte
          vDespJSONRespuestaLogin.Add('msgerror'         , vDespMsgError);                            //Intervalo en seg para el reporte
          //Enviamos el JSOn con la respuesta
          AContext.Connection.IOHandler.WriteLn(TlkJSON.GenerateText(vDespJSONRespuestaLogin));
          Log('->'+vDespUsuario+' '+TlkJSON.GenerateText(vDespJSONRespuestaLogin),1);
        finally
          FreeAndNil(vDespJSONRespuestaLogin);
        end;
     end;
  2: begin //POSICION
        //Guardamos posicion segun Config
        if vDespConfig_GuardarPosicion then
        begin
          if not PosicionInt(vDespDatoRec) then
          begin
            logInt('Error en Guardar Posicion ',0);
          end;
        end;

        vDespAuxS := '';

        //Enviamos Viajes segun Config
        if vDespConfig_EnviarViajes then
        begin
          vDespAuxS := ControlInt(vDespMovil); //VERIFICA SI TIENE VIAJE ASIGNADO
          if Length(vDespAuxS) = 0 then
          begin
            vDespAuxS := ControlQTAInt(vDespMovil); //VERIFICA SI TIENE VIAJE QTA
          end;
        end;

        if Length(vDespAuxS) = 0 then
        begin
          vDespAuxS := '{}';
        end;

        //Enviamos el JSOn con la respuesta
        AContext.Connection.IOHandler.WriteLn(vDespAuxS);

        if vDespAuxS.Length > 2 then
          Log('Viaje -> '+IntToStr(vDespMovil)+' -> '+vDespAuxS,2);
     end;
  3: begin //VIAJE ACEPTADO - QTH FINAL
       //Armamos el JSON para enviar EL QTH FINAL como respuesta
       vDespJSONRespuestaFinal  := TlkJSONobject.Create;
       try
         //vDespIdViaje := StrToInt(vartostr(vDespJSONDato.Field['viajeaceptado'].Field['idviaje'].Value));
         vDespIdViajeEnUso := idviajeenusoInt(vDespIdViaje);
         if vDespIdViajeEnUso > 0 then
         begin
           //vDomicilio := Trim(PendienteCalle(vIdViajeEnUso))+' '+IntToStr(PendienteAltura(vIdViajeEnUso))+' '+PendientePisoDpto(vIdViajeEnUso);
           vDespDomicilio := ArmarDomicilioInt(vDespIdViajeEnUso);
           vDespObservaciones := Trim(PendienteInfoTmpInt(vDespIdViajeEnUso))+' '+trim(PendienteObservacionesInt(vDespIdViajeEnUso));
           vDespViajeLat := Trim(PendienteLatInt(vDespIdViajeEnUso));
           vDespViajeLng := Trim(PendienteLngInt(vDespIdViajeEnUso));
         end
         else
         begin
           vDespDomicilio := 'VIAJE CANCELADO';
           vDespObservaciones := '';
           vDespViajeLat := '';
           vDespViajeLng := '';
         end;

         //DATOS DEL VIAJE
         vDespJSONRespuestaFinal.Add('domicilio'    , vDespDomicilio);
         vDespJSONRespuestaFinal.Add('observaciones', vDespObservaciones);
         vDespJSONRespuestaFinal.Add('lat', vDespViajeLat);
         vDespJSONRespuestaFinal.Add('lng', vDespViajeLng);
         vDespJSONRespuestaFinal.Add('idviaje', IntToStr(vDespIdViaje));

         //Enviamos el JSOn con la respuesta
         AContext.Connection.IOHandler.WriteLn(TlkJSON.GenerateText(vDespJSONRespuestaFinal));
         logInt('Viaje Aceptado -> '+IntToStr(vDespMovil)+' -> '+TlkJSON.GenerateText(vDespJSONRespuestaFinal),2);

         //Marcamos el viaje como aceptado
         DatoViajesInt(True,1, vDespIdViaje);   //MARCAMOS EL VIAJE COMO ACEPTADO
       finally
         FreeAndnil(vDespJSONRespuestaFinal);
       end;
     end;
  4: begin //VIAJE RECHAZADO
       //vDespIdViaje := StrToInt(vartostr(vDespJSONDato.Field['viajerechazado'].Field['idviaje'].Value));
       vDespIdViajeEnUso := idviajeenusoInt(vDespIdViaje);

       //Marcamos el viaje como rechazado
       DatoViajesInt(True,2, vDespIdViaje);   //MARCAMOS EL VIAJE COMO RECHAZADO

       logInt('Viaje Rechazado -> '+IntToStr(vDespMovil) ,2);
     end;
  5: begin //VIAJE TIME OUT
       //vDespIdViaje := StrToInt(vartostr(vDespJSONDato.Field['viajetimeout'].Field['idviaje'].Value));
       vDespIdViajeEnUso := idviajeenusoInt(vDespIdViaje);

       //Marcamos el viaje como timeout
       DatoViajesInt(True,3, vDespIdViaje);   //MARCAMOS EL VIAJE COMO TIME OUT

       logInt('Viaje TimeOut -> '+IntToStr(vDespMovil) ,2);
     end;
  6: begin //HISTORIAL DE VIAJES
       vDespRespS := ViajesInt(vDespMovil);
       //Log('--> '+vRespS);
       AContext.Connection.IOHandler.WriteLn(vDespRespS);
     end;
  7: begin //ESTADO QAP / QRX DELMOVIL
       vDespRespS := ValidarMovilQRXInt(vDespMovil);
       AContext.Connection.IOHandler.WriteLn(vDespRespS)
     end;
  else
    begin
      LogInt('No trajo dato alguno... ',0)
    end;
  end;


  //---------------------------------------------------------------------------

end;
__________________
\_--> NoShY <--_/
Responder Con Cita
  #3  
Antiguo 07-02-2017
Avatar de noshy
noshy noshy is offline
Miembro
 
Registrado: jul 2003
Posts: 139
Poder: 21
noshy Va por buen camino
El codigo de arriba es el codigo ya limpio de todas las pruebas con try / except, por si alguien lo quiere revisar.
__________________
\_--> NoShY <--_/
Responder Con Cita
  #4  
Antiguo 07-02-2017
Reasen Reasen is offline
Miembro
NULL
 
Registrado: dic 2015
Ubicación: Barcelona
Posts: 140
Poder: 9
Reasen Va por buen camino
Prueba con MadExcept lo puedes usar gratis mientras no sea para fines comerciales.
Responder Con Cita
  #5  
Antiguo 08-02-2017
Avatar de noshy
noshy noshy is offline
Miembro
 
Registrado: jul 2003
Posts: 139
Poder: 21
noshy Va por buen camino
Cita:
Empezado por Reasen Ver Mensaje
Prueba con MadExcept lo puedes usar gratis mientras no sea para fines comerciales.

gracias, lo probare!!!
__________________
\_--> NoShY <--_/
Responder Con Cita
Respuesta



Normas de Publicación
no Puedes crear nuevos temas
no Puedes responder a temas
no Puedes adjuntar archivos
no Puedes editar tus mensajes

El código vB está habilitado
Las caritas están habilitado
Código [IMG] está habilitado
Código HTML está deshabilitado
Saltar a Foro

Temas Similares
Tema Autor Foro Respuestas Último mensaje
no me detecta teclado numero Rofocale Varios 4 20-06-2011 23:00:14
BDS 2006 no detecta el IIS 7 en Win Vista ozrics Windows 0 17-06-2007 04:19:45
Software k detecta hardware Mrcl Debates 2 03-01-2007 22:07:58
la función SetSchemaInfo no detecta los índices amezeta32 Conexión con bases de datos 1 29-08-2006 22:51:53
¿Cua es el error que me detecta???? gandalf_27 C++ Builder 1 27-04-2006 19:57:44


La franja horaria es GMT +2. Ahora son las 21:06:30.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi
Copyright 1996-2007 Club Delphi