Kaynağa Gözat

Pruebas de mensajea

ElPoteito 2 yıl önce
ebeveyn
işleme
f26f0c7307

+ 399 - 24
commands/EventoController.php

@@ -398,27 +398,377 @@ class EventoController extends Controller {
     } while ($continuar);
   }
 
-  public function consultarNorificacion() {
+  public function actionSincronizarAcumulado() {
+    $firebase = new FirebaseHelper();
+    $firestore = $firebase->firestore();
 
-    $query = Notificacion::find()
-      ->orderBy(["id" => SORT_ASC]);
+    $refGrupos = $firestore->collection("grupos");
+    $refUsuarios = $firestore->collection("usuarios");
+    $refDependencias = $firestore->collection("dependencias");
 
-    $enviando = (clone $query)
-      ->andWhere(["estatus" => Notificacion::ESTATUS_ENVIANDO])
-      ->one();
-    
-    if ($enviando !== null) {
-      $this->stdout("Notificación en poceso: ". $enviando->id ."\n");
-      return null;
+    $grupos = [];
+    $usuarios = [];
+    $dependencias = [];
+
+    foreach ($refGrupos->documents() as $grupo) {
+      $grupos[$grupo->id()] = $grupo->data();
     }
 
-    return (clone $query)
-      ->andWhere(["estatus" => Notificacion::ESTATUS_NUEVO])
-      ->one();
+    foreach ($refUsuarios->documents() as $usuario) {
+      $usuarios[$usuario->id()] = $usuario->data();
+    }
+
+    foreach ($refDependencias->documents() as $dependencia) {
+      $dependencias[$dependencia->id()] = $dependencia->data();
+    }
+
+    $ultimaFecha = null;
+    $limite = 100; // 1000;
+    $continuar = true;
+    do {
+      $this->stdout("Sincronizando ...");
+      $ref = $firestore->collection("eventos")
+        ->where("sincronizado", "==", null)
+        ->orderBy("timestamp", "ASC")
+        ->limit($limite);
+
+      if ($ultimaFecha !== null) {
+        $ref = $ref->startAt([$ultimaFecha]);
+      }
+
+      $c = 0; # Contador de registros procesados
+      foreach ($ref->documents() as $doc) {
+        $this->stdoutln($doc->id());
+        $c++;
+        $data = $doc->data();
+        $ultimaFecha = $data["timestamp"];
+        $modelo = Evento::findOne(["firebaseId" => $doc->id()]);
+        if ($modelo === null) {
+          $modelo = new Evento();
+        }
+        try {
+
+          $modelo->nombre = $data["nombre"];
+          $modelo->descripcion = $data["descripcion"];
+          $modelo->ciudad = $data["ciudad"];
+          $modelo->redSocial = $data["redSocial"];
+          $creado = \DateTime::createFromFormat('Y-m-d\TH:i:s.u\Z', $data["timestamp"]);
+          if ($creado !== false) {
+            $modelo->creado = $creado->format(\DateTime::RFC3339_EXTENDED);
+          }
+          $fechaInicio = $this->cambiarFecha($data["fechaInicio"]);
+          if ($fechaInicio !== false) {
+            $modelo->fechaInicio = $fechaInicio->format(\DateTime::RFC3339_EXTENDED);
+          }
+          $fechaFinal = $this->cambiarFecha($data["fechaFinal"]);
+          if ($fechaFinal !== false) {
+            $modelo->fechaFinal = $fechaFinal->format(\DateTime::RFC3339_EXTENDED);
+          }
+          $modelo->fotoEvento = $data["fotoEvento"];
+          $modelo->url = $data["pathFirebase"];
+          if (isset($data["tag"])) {
+            $modelo->tag = $data["tag"];
+          }
+          $modelo->firebaseId = $doc->id();
+
+          if (!$modelo->save()) {
+            $this->stdoutln('Ocurrió un error al guardar un evento. ' . Json::encode($modelo->getFirstErrors()));
+            continue;
+          }
+
+          if (isset($data["redes"])) {
+            foreach ($data["redes"] as $red) {
+              $eventoRed = Red::find()
+                ->andWhere([
+                  "idEvento" => $modelo->id,
+                  "url" => $red["url"]
+                ])
+                ->one();
+
+              if ($eventoRed === null) {
+                $eventoRed = new Red();
+
+                $eventoRed->idEvento = $modelo->id;
+                $eventoRed->key = $red["key"];
+                $eventoRed->url = $red["url"];
+                $eventoRed->redSocial = $red["redSocial"];
+
+                if (!$eventoRed->save()) {
+                  $this->stdoutln('Ocurrió un error al guardar una red. ' . Json::encode($eventoRed->getFirstErrors()));
+                  continue;
+                }
+              }
+            }
+          }
+
+          foreach ($data["accion"] as $accion) {
+            $eventoAccion = EventoAccion::find()
+              ->andWhere([
+                "idEvento" => $modelo->id,
+                "accion" => $accion
+              ])
+              ->one();
+
+            if ($eventoAccion === null) {
+              $eventoAccion = new EventoAccion();
+
+              $eventoAccion->idEvento = $modelo->id;
+              $eventoAccion->accion = $accion;
+
+              if (!$eventoAccion->save()) {
+                $this->stdoutln('Ocurrió un error al guardar un evento-accion. ' . Json::encode($eventoAccion->getFirstErrors()));
+                continue;
+              }
+            }
+          }
+
+          //Grupos dentro de los eventos
+          foreach ($data["grupos"] as $grupoEvento) {
+            $grupoModelo = Grupo::findOne(["firebaseId" => $grupoEvento]);
+            if ($grupoModelo === null && isset($grupos[$grupoEvento])) {
+              $grupoModelo = new Grupo();
+              $grupoModelo->creado = new Expression('now()');
+              $grupoModelo->nombre = $grupos[$grupoEvento]["nombre"];
+              $grupoModelo->descripcion = $grupos[$grupoEvento]["descripcion"];
+              $grupoModelo->firebaseId = $grupoEvento;
+
+              if (!$grupoModelo->save()) {
+                $this->stdoutln('Ocurrió un error al guardar un grupo. ' . Json::encode($grupoModelo->getFirstErrors()));
+              }
+            }
+            if ($grupoModelo !== null) {
+              $eventoGrupo = EventoGrupo::find()
+                ->andWhere([
+                  "idEvento" => $modelo->id,
+                  "idGrupo" => $grupoModelo->id
+                ])
+                ->one();
+
+              if ($eventoGrupo === null) {
+                $eventoGrupo = new EventoGrupo();
+
+                $eventoGrupo->idEvento = $modelo->id;
+                $eventoGrupo->idGrupo = $grupoModelo->id;
+
+                if (!$eventoGrupo->save()) {
+                  $this->stdoutln('Ocurrió un error al guardar un evento-grupo. ' . Json::encode($eventoGrupo->getFirstErrors()));
+                }
+              }
+            }
+          }
+
+          foreach ($data["usuarios"] as $usuarioEvento) {
+            $usuarioModelo = Usuario::findOne(["uid" => $usuarioEvento["uid"]]);
+            $usuarioRef = isset($usuarios[$usuarioEvento["uid"]])
+              ? $usuarios[$usuarioEvento["uid"]] : null;
+
+            // Usuarios
+            if ($usuarioModelo === null && $usuarioRef !== null) {
+              $usuarioModelo = new Usuario();
+              $usuarioModelo->uid = $usuarioRef["uid"];
+              $usuarioModelo->nombre = $usuarioRef["nombre"];
+              if (isset($usuarioRef["email"])) {
+                $usuarioModelo->email = $usuarioRef["email"];
+              }
+              $usuarioModelo->telefono = $usuarioRef["telefono"];
+              $usuarioModelo->facebook = $usuarioRef["facebook"];
+              if (isset($usuarioRef["facebookVerificado"])) {
+                $usuarioModelo->facebookVerificado = $usuarioRef["facebookVerificado"];
+              }
+              $usuarioModelo->instagram = $usuarioRef["instagram"];
+              if (isset($usuarioRef["instagramVerificado"])) {
+                $usuarioModelo->instagramVerificado = $usuarioRef["instagramVerificado"];
+              }
+              $usuarioModelo->twitter = $usuarioRef["twitter"];
+              if (isset($usuarioRef["twitterVerificado"])) {
+                $usuarioModelo->twitterVerificado = $usuarioRef["twitterVerificado"];
+              }
+              $usuarioModelo->genero = $usuarioRef["genero"];
+              $usuarioModelo->verificado = $usuarioRef["verificado"];
+              $usuarioModelo->creado = new Expression('now()');
+              if ($usuarioRef["estatus"] === false) {
+                $usuarioModelo->eliminado = new Expression('now()');
+              }
+
+              if (!$usuarioModelo->save()) {
+                $this->stdoutln('Ocurrió un error al guardar un usuario. ' . Json::encode($usuarioModelo->getFirstErrors()));
+              }
+            }
+
+            // UsuarioGrupo
+            if ($usuarioModelo !== null && isset($usuarioRef["grupos"]) && isset($usuarioRef["grupos"][0])) {
+              for($i = 0; $i < count($usuarioRef["grupos"]); $i++) {
+                $modelGrupo = Grupo::findOne(['firebaseId' => $usuarioRef["grupos"][$i]]);
+                if (isset($modelGrupo)) {
+                  $usuarioGrupo = UsuarioGrupo::find()
+                    ->andWhere([
+                      "idUsuario" => $usuarioModelo->id,
+                      "idGrupo" => $modelGrupo->id
+                    ])
+                    ->one();
+
+                  if ($usuarioGrupo === null) {
+                    $usuarioGrupo = new UsuarioGrupo();
+
+                    $usuarioGrupo->idUsuario = $usuarioModelo->id;
+                    $usuarioGrupo->idGrupo = $modelGrupo->id;
+
+                    if (!$usuarioGrupo->save()) {
+                      $this->stdoutln('Ocurrió un error al guardar un usuario-grupo. ' . Json::encode($usuarioGrupo->getFirstErrors()));
+                    }
+                  }
+                }
+              }
+            }
+
+            // Resultados
+            if ($usuarioModelo !== null && isset($data["resultado"])) {
+              $resultados = $data["resultado"];
+              if (isset($resultados[$usuarioModelo->uid])) {
+                foreach ($resultados[$usuarioModelo->uid] as $_accion) {
+                  $resultadoModelo = Resultado::find()
+                    ->andWhere([
+                      "idUsuario" => $usuarioModelo->id,
+                      "idEvento" => $modelo->id,
+                      "accion" => $_accion
+                    ])
+                    ->exists();
+
+                  if (!$resultadoModelo) {
+                    $resultadoModelo = new Resultado();
+
+                    $resultadoModelo->idUsuario = $usuarioModelo->id;
+                    $resultadoModelo->idEvento = $modelo->id;
+                    $resultadoModelo->accion = $_accion;
+
+                    if (!$resultadoModelo->save()) {
+                      $this->stdoutln('Ocurrió un error al guardar un resultado. ' . Json::encode($resultadoModelo->getFirstErrors()));
+                    }
+                  }
+                }
+              }
+            }
+
+            // Dependencias
+            if ($usuarioModelo !== null && isset($usuarioRef["dependencias"]) && isset($usuarioRef["dependencias"][0])) {
+              if (!empty($usuarioRef["dependencias"])){
+                if (is_array($usuarioRef["dependencias"])) {
+                  for ($i = 0; $i < count($usuarioRef["dependencias"]); $i++){
+                    $dependenciaModel = Dependencia::findOne(["firebaseId" => $usuarioRef["dependencias"][$i]]);
+                    if ($dependenciaModel === null) {
+                      $dependenciaRef = $dependencias[$usuarioRef["dependencias"][$i]];
+                      $dependenciaModel = new Dependencia();
+    
+                      $dependenciaModel->firebaseId = $usuarioRef["dependencias"][$i];
+                      $dependenciaModel->nombre = $dependenciaRef['nombre'];
+                      $dependenciaModel->descripcion = $dependenciaRef['descripcion'];
+                      $dependenciaModel->estatus = $dependenciaRef['estatus'];
+    
+                      $creado = \DateTime::createFromFormat('Y-m-d\TH:i:s.u\Z', $dependenciaRef["timestamp"]);
+                      if ($creado !== false) {
+                        $dependenciaModel->creado = $creado->format(\DateTime::RFC3339_EXTENDED);
+                      }
+    
+                      if (!$dependenciaModel->save()) {
+                        $this->stdoutln('Ocurrió un error al guardar una dependencia. ' . Json::encode($dependenciaModel->getFirstErrors()));
+                      }
+                    }
+    
+                    //UsuarioDependencia
+                    $usuarioDependencia = UsuarioDependencia::find()
+                      ->andWhere([
+                        "idUsuario" => $usuarioModelo->id,
+                        "idDependencia" => $dependenciaModel->id
+                      ])
+                      ->one();
+    
+                    if ($usuarioDependencia === null) {
+                      $usuarioDependencia = new UsuarioDependencia();
+    
+                      $usuarioDependencia->idUsuario = $usuarioModelo->id;
+                      $usuarioDependencia->idDependencia = $dependenciaModel->id;
+    
+                      if (!$usuarioDependencia->save()) {
+                        $this->stdoutln('Ocurrió un error al guardar un usuario-dependencia. ' . Json::encode($usuarioDependencia->getFirstErrors()));
+                      }
+                    }
+                  }
+                } else {
+                  $dependenciaModel = Dependencia::findOne(["firebaseId" => $usuarioRef["dependencias"]]);
+                    if ($dependenciaModel === null) {
+                      $dependenciaRef = $dependencias[$usuarioRef["dependencias"]];
+                      $dependenciaModel = new Dependencia();
+    
+                      $dependenciaModel->firebaseId = $usuarioRef["dependencias"];
+                      $dependenciaModel->nombre = $dependenciaRef['nombre'];
+                      $dependenciaModel->descripcion = $dependenciaRef['descripcion'];
+                      $dependenciaModel->estatus = $dependenciaRef['estatus'];
+    
+                      $creado = \DateTime::createFromFormat('Y-m-d\TH:i:s.u\Z', $dependenciaRef["timestamp"]);
+                      if ($creado !== false) {
+                        $dependenciaModel->creado = $creado->format(\DateTime::RFC3339_EXTENDED);
+                      }
+    
+                      if (!$dependenciaModel->save()) {
+                        $this->stdoutln('Ocurrió un error al guardar una dependencia. ' . Json::encode($dependenciaModel->getFirstErrors()));
+                      }
+                    }
+    
+                    //UsuarioDependencia
+                    $usuarioDependencia = UsuarioDependencia::find()
+                      ->andWhere([
+                        "idUsuario" => $usuarioModelo->id,
+                        "idDependencia" => $dependenciaModel->id
+                      ])
+                      ->one();
+    
+                    if ($usuarioDependencia === null) {
+                      $usuarioDependencia = new UsuarioDependencia();
+    
+                      $usuarioDependencia->idUsuario = $usuarioModelo->id;
+                      $usuarioDependencia->idDependencia = $dependenciaModel->id;
+    
+                      if (!$usuarioDependencia->save()) {
+                        $this->stdoutln('Ocurrió un error al guardar un usuario-dependencia. ' . Json::encode($usuarioDependencia->getFirstErrors()));
+                      }
+                    }
+                }
+              }
+            }
+          }
+
+          $hoy = new \DateTime();
+          $doc->reference()
+            ->update([
+              ["path" => "sincronizado", "value" => "OK"],
+              ["path" => "sincronizadoFecha", "value" => $hoy->format("Y-m-d H:i:s")],
+            ]);
+          $this->stdoutln("Sincronizado correcto");
+        } catch (\Exception $e) {
+          $this->stdoutln("Exception: {$e->getMessage()}\n");
+          $doc->reference()
+            ->update([
+              ["path" => "sincronizado", "value" => "ERROR"],
+              ["path" => "sincronizadoError", "value" => $e->getMessage()],
+              ["path" => "sincronizadoErrorLine", "value" => $e->getLine()],
+            ]);
+        }
+      }
+
+      # Si los registros procesados son menores al límite, terminar
+      if ($c < $limite) {
+        $continuar = false;
+      }
+    } while ($continuar);
   }
 
   public function actionParticipacion() {
 
+    try {
+      \Yii::$app->db->createCommand("SET TIMEZONE TO 'America/Hermosillo'")
+        ->execute();
+    } catch (\Exception $e) { }
+
     $eventos = (new Query())
       ->select([
         "nombre",
@@ -429,8 +779,6 @@ class EventoController extends Controller {
       ->groupBy(["tag", "nombre"])
       ->indexBy("tag")
       ->column();
-    
-      // $sql = $eventos->createCommand()->getRawSql();
 
       $query2 = (new Query())
         ->select([
@@ -449,11 +797,6 @@ class EventoController extends Controller {
         ->leftJoin("Resultado", "{{Resultado}}.[[idEvento]] = {{Evento}}.id and {{Resultado}}.[[idUsuario]] = {{Usuario}}.id")
         ->andWhere(["{{Usuario}}.eliminado" => null])
         ->andWhere([">=", "fechaFinal", new Expression("now()-interval '7 days'")])
-        /* ->andWhere([
-          "AND",
-          [">=", "fechaFinal", $desde],
-          ["<=", "fechaFinal", $hasta]
-        ]) */
         ->groupBy([
           "{{Usuario}}.nombre",
           "{{Usuario}}.telefono",
@@ -462,7 +805,6 @@ class EventoController extends Controller {
         ])
         ->orderBy([
           "{{Usuario}}.id" => SORT_ASC,
-          // "tag" => SORT_ASC,
           "[[Participo]]" => SORT_DESC,
         ]);
 
@@ -502,7 +844,41 @@ class EventoController extends Controller {
           $notificacionUsuario->idUsuario = $usuario['id'];
           $notificacionUsuario->nombre = $usuario['nombreUsuario'];
           $notificacionUsuario->telefono = $usuario['telefono'];
-          $notificacionUsuario->parametros = [
+          if (count($usuario["eventosParticipo"]) === count($eventos)){
+            $notificacionUsuario->parametros = [
+              [
+                "type" => "text",
+                "text" => count($usuario["eventosParticipo"])."/".count($eventos). "eventos,"
+              ],
+              [
+                "type" => "text",
+                "text" => "gracias por tu"
+              ]
+            ];
+          } else if (count($usuario["eventosParticipo"]) > 0 && count($usuario["eventosParticipo"]) < count($eventos)) {
+            $notificacionUsuario->parametros = [
+              [
+                "type" => "text",
+                "text" => count($usuario["eventosParticipo"])."/".count($eventos). "eventos,"
+              ],
+              [
+                "type" => "text",
+                "text" => "gracias por tu participación. Vamos por el 100% de"
+              ]
+            ];
+          } else if (count($usuario["eventosParticipo"]) === 0) {
+            $notificacionUsuario->parametros = [
+              [
+                "type" => "text",
+                "text" => count($usuario["eventosParticipo"])."/".count($eventos). "eventos."
+              ],
+              [
+                "type" => "text",
+                "text" => "Vamos por el 100% de"
+              ]
+            ];
+          }
+          /* $notificacionUsuario->parametros = [
             [
               "type" => "text",
               "text" => count($usuario["eventosParticipo"])."/".count($eventos)
@@ -511,7 +887,7 @@ class EventoController extends Controller {
               "type" => "text",
               "text" => "gracias por tu"
             ]
-          ];
+          ]; */
 
           if (!$notificacionUsuario->save()) {
             return (new Respuesta($notificacionUsuario))
@@ -524,7 +900,6 @@ class EventoController extends Controller {
         $notificacion->save();
 
         $this->stdout("Terminó");
-    // $this->stdout(json_encode($aux)."\n");
     // file_put_contents("archivo.json", json_encode($aux));
   }
 }

+ 90 - 0
commands/ParticipacionController.php

@@ -0,0 +1,90 @@
+<?php
+
+namespace app\commands;
+
+use app\components\NotificacionController;
+use app\components\Whatsapp;
+use app\models\Notificacion;
+use app\models\NotificacionUsuario;
+use yii\db\Expression;
+use yii\db\Query;
+
+class ParticipacionController extends NotificacionController {
+
+  public function actionParticipacion() {
+
+    $notificacion = $this->consultarNorificacion();
+    if ($notificacion === null) {
+      $this->stdout("No hay notificaciones pendientes\n");
+      return;
+    }
+
+    $params = \Yii::$app->params;
+    $wab = null;
+    if(isset($params["wab"])) {
+      $wab = $params["wab"];
+    }
+
+    if($wab === null) {
+      $this->stdout("No existe la configuración\n");
+    }
+
+    try {
+      /** @var \app\models\Notificacion $notificacion */
+      $notificacion->estatus = Notificacion::ESTATUS_ENVIANDO;
+      $notificacion->save();
+
+      $notificacionUsuario = NotificacionUsuario::find()
+        ->andWhere(["idNotificacion" => $notificacion->id]);
+
+      foreach ($notificacionUsuario->each() as $nu) {
+        $this->stdout("Enviando mensaje a ".$nu->telefono."\n");
+        /** @var \app\models\NotificacionUsuario $nu */
+        // $msgTo = "526624473145";
+        $msgTo = $nu->telefono;
+        if (strlen($nu->telefono) === 10) {
+          $msgTo = "52".$nu->telefono;
+        }
+        $template = "laud_resumen_eventos";
+        // $template = "informe_de_eventos";
+
+        try {
+          $wa = (new Whatsapp())
+            ->set_access_token($wab["access-token"])
+            ->msg_from($wab["phone-id"])
+            ->msg_to($msgTo)
+            ->template($template);
+
+          foreach ($nu['parametros'] as $param) {
+            $wa->add_body_param($param['text'], $param['type']);
+          }
+            $resultado = $wa->send_template_message();
+          
+          if($resultado === null) {
+            $this->stdout("Ocurrió un error al enviar el mensaje\n");
+            return;
+          }
+
+          // $this->stdout("Proceso terminado\n");
+        } catch (\Exception $e) {
+          $this->stdout("Error al enviar el mensaje: {$e->getMessage()}\n");
+        }
+      }
+
+      $notificacion->estatus = Notificacion::ESTATUS_TERMINADO;
+      $notificacion->save();
+    } catch(\Exception $e) {
+      $notificacion->estatus = Notificacion::ESTATUS_ERROR;
+      $notificacion->detalle = "Ocurrió un error en el servidor al generar la notificación {$e->getMessage()} {$e->getCode()}";
+      $notificacion->save();
+      $this->stdout($e->getMessage() . "\n");
+    }
+  }
+
+  public function actionFecha() {
+    $fecha = \Yii::$app->db->createCommand("select now()")
+      ->queryAll();
+
+    var_dump($fecha);
+  }
+}

+ 36 - 0
components/NotificacionController.php

@@ -0,0 +1,36 @@
+<?php
+
+namespace app\components;
+
+use app\models\Notificacion;
+use yii\console\Controller;
+
+class NotificacionController extends Controller {
+
+  public $debug = true;
+
+  public function stdout($texto) {
+    if ($this->debug) {
+      parent::stdout($texto);
+    }
+  }
+
+  public function consultarNorificacion() {
+
+    $query = Notificacion::find()
+      ->orderBy(["id" => SORT_ASC]);
+
+    $enviando = (clone $query)
+      ->andWhere(["estatus" => Notificacion::ESTATUS_ENVIANDO])
+      ->one();
+    
+    if ($enviando !== null) {
+      $this->stdout("Notificación en poceso: ". $enviando->id ."\n");
+      return null;
+    }
+
+    return (clone $query)
+      ->andWhere(["estatus" => Notificacion::ESTATUS_NUEVO])
+      ->one();
+  }
+}