Pārlūkot izejas kodu

Avance notificaciones

ElPoteito 2 gadi atpakaļ
vecāks
revīzija
6f985d50b6

+ 137 - 0
commands/EventoController.php

@@ -3,6 +3,9 @@
 namespace app\commands;
 
 use app\components\FirebaseHelper;
+use app\models\Notificacion;
+use app\models\NotificacionUsuario;
+use common\data\Respuesta;
 use v1\models\Dependencia;
 use v1\models\Evento;
 use v1\models\EventoAccion;
@@ -15,6 +18,7 @@ use v1\models\UsuarioDependencia;
 use v1\models\UsuarioGrupo;
 use yii\console\Controller;
 use yii\db\Expression;
+use yii\db\Query;
 use yii\helpers\Json;
 
 class EventoController extends Controller {
@@ -218,6 +222,9 @@ class EventoController extends Controller {
               $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()));
@@ -390,4 +397,134 @@ class EventoController extends Controller {
       }
     } while ($continuar);
   }
+
+  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();
+  }
+
+  public function actionParticipacion() {
+
+    $eventos = (new Query())
+      ->select([
+        "nombre",
+        "tag"
+      ])
+      ->from("Evento")
+      ->andWhere([">=", "fechaFinal", new Expression("now()-interval '7 days'")])
+      ->groupBy(["tag", "nombre"])
+      ->indexBy("tag")
+      ->column();
+    
+      // $sql = $eventos->createCommand()->getRawSql();
+
+      $query2 = (new Query())
+        ->select([
+          "tag",
+          "{{Usuario}}.id",
+          "{{Usuario}}.nombre",
+          "{{Usuario}}.telefono",
+          "case when count({{Resultado}}.accion) > 0 then true else false end as [[Participo]]"
+        ])
+        ->from("Evento")
+        ->innerJoin("EventoGrupo", "{{EventoGrupo}}.[[idEvento]] = {{Evento}}.id")
+        ->innerJoin("Grupo", "{{Grupo}}.id = {{EventoGrupo}}.[[idGrupo]]")
+        ->innerJoin("UsuarioGrupo", "{{UsuarioGrupo}}.[[idGrupo]] = {{Grupo}}.id")
+        ->innerJoin("Usuario", "{{Usuario}}.[[id]] = {{UsuarioGrupo}}.[[idUsuario]]")
+        ->innerJoin("UsuarioDependencia", "{{UsuarioDependencia}}.[[idUsuario]] = {{Usuario}}.id")
+        ->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",
+          "{{Usuario}}.id",
+          "tag"
+        ])
+        ->orderBy([
+          "{{Usuario}}.id" => SORT_ASC,
+          // "tag" => SORT_ASC,
+          "[[Participo]]" => SORT_DESC,
+        ]);
+
+        $aux = [];
+
+        foreach($query2->each() as $consulta) {
+          if (!isset($aux[$consulta['id']])) {
+            $aux[$consulta['id']] = [
+              "nombreUsuario" => $consulta['nombre'],
+              "telefono" => $consulta['telefono'],
+              "id" => $consulta['id'],
+              "eventosFaltantes" => [],
+              "eventosParticipo" => []
+            ];
+          }
+          $nombreEvento = $eventos[$consulta['tag']];
+          if ($consulta['Participo']) {
+            $aux[$consulta['id']]['eventosParticipo'][] = $nombreEvento;
+          } else {
+            $aux[$consulta['id']]['eventosFaltantes'][] = $nombreEvento;
+          }
+        }
+
+        $notificacion = new Notificacion();
+        $notificacion->creado = new Expression("now()");
+
+        if (!$notificacion->save()) {
+          return (new Respuesta($notificacion))
+            ->mensaje("Hubo un problema al generar la notificación");
+        }
+        $notificacion->refresh();
+
+        foreach ($aux as $usuario) {
+          $notificacionUsuario = new NotificacionUsuario();
+          
+          $notificacionUsuario->idNotificacion = $notificacion->id;
+          $notificacionUsuario->idUsuario = $usuario['id'];
+          $notificacionUsuario->nombre = $usuario['nombreUsuario'];
+          $notificacionUsuario->telefono = $usuario['telefono'];
+          $notificacionUsuario->parametros = [
+            [
+              "type" => "text",
+              "text" => count($usuario["eventosParticipo"])."/".count($eventos)
+            ],
+            [
+              "type" => "text",
+              "text" => "gracias por tu"
+            ]
+          ];
+
+          if (!$notificacionUsuario->save()) {
+            return (new Respuesta($notificacionUsuario))
+              ->mensaje("Hubo un problema al generar la notificación");
+          }
+        }
+
+        $notificacion->estatus = Notificacion::ESTATUS_NUEVO;
+
+        $notificacion->save();
+
+        $this->stdout("Terminó");
+    // $this->stdout(json_encode($aux)."\n");
+    // file_put_contents("archivo.json", json_encode($aux));
+  }
 }

+ 5 - 1
commands/UsuarioController.php

@@ -83,7 +83,11 @@ class UsuarioController extends Controller {
 
           $creado = \DateTime::createFromFormat('Y-m-d\TH:i:s.u\Z', $data["timestamp"]);
           if ($creado !== false) {
-            $modelo->creado = $creado->format(\DateTime::RFC3339_EXTENDED);
+            $modelo->creado = new Expression("now()");
+          }
+
+          if ($data["estatus"] === false) {
+            $modelo->eliminado = $creado->format(\DateTime::RFC3339_EXTENDED);
           }
 
           if (!$modelo->save()) {

+ 2 - 1
config/web.php

@@ -59,7 +59,8 @@ $config = [
             'v1/resultado',
             'v1/usuario',
             'v1/reporte-individual',
-            'v1/reporte-global'
+            'v1/reporte-global',
+            'v1/evento-notificacion'
           ],
         ]
       ],

+ 47 - 0
migrations/m230420_191735_notificaciones.php

@@ -0,0 +1,47 @@
+<?php
+
+use yii\db\Migration;
+
+/**
+ * Class m230420_191735_notificaciones
+ */
+class m230420_191735_notificaciones extends Migration {
+  /**
+   * {@inheritdoc}
+   */
+  public function safeUp() {
+    $this->createTable('Notificacion', [
+      'id' => $this->primaryKey(),
+      'envio' => $this->timestamp().' with time zone',
+      'estatus' => $this->string(10),
+      'creado' => $this->timestamp().' with time zone',
+      'modificado' => $this->timestamp().' with time zone',
+      'detalle' => $this->json()
+    ]);
+
+    $this->createTable('NotificacionUsuario', [
+      'id' => $this->primaryKey(),
+      'idNotificacion' => $this->integer(),
+      'idUsuario' => $this->integer(),
+      'nombre' => $this->string(100),
+      'telefono' => $this->string(10),
+      'parametros' => $this->json(),
+      'detalle' => $this->json()
+    ]);
+
+    $this->addForeignKey('NotificacionUsuario_idNotificacion_FK', 'NotificacionUsuario', 'idNotificacion', 'Notificacion', 'id');
+    $this->addForeignKey('NotificacionUsuario_idUsuario_FK', 'NotificacionUsuario', 'idUsuario', 'Usuario', 'id');
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function safeDown() {
+    $this->dropForeignKey('NotificacionUsuario_idUsuario_FK', 'NotificacionUsuario');
+    $this->dropForeignKey('NotificacionUsuario_idNotificacion_FK', 'NotificacionUsuario');
+
+    $this->dropTable('NotificacionUsuario');
+
+    $this->dropTable('Notificacion');
+  }
+}

+ 65 - 0
models/Notificacion.php

@@ -0,0 +1,65 @@
+<?php
+
+namespace app\models;
+
+use Yii;
+
+/**
+ * This is the model class for table "Notificacion".
+ *
+ * @property int $id
+ * @property string|null $envio
+ * @property string|null $estatus
+ * @property string|null $creado
+ * @property string|null $modificado
+ * @property string|null $detalle
+ *
+ * @property NotificacionUsuario[] $notificacionUsuarios
+ */
+class Notificacion extends \yii\db\ActiveRecord {
+
+  public const ESTATUS_NUEVO = "Nuevo";
+  public const ESTATUS_ENVIANDO = "Enviando";
+  public const ESTATUS_TERMINADO = "Terminado";
+  public const ESTATUS_ERROR = "Error";
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function tableName() {
+    return 'Notificacion';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function rules() {
+    return [
+      [['envio', 'creado', 'modificado', 'detalle'], 'safe'],
+      [['estatus'], 'string', 'max' => 10],
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function attributeLabels() {
+    return [
+      'id' => 'ID',
+      'envio' => 'Envio',
+      'estatus' => 'Estatus',
+      'creado' => 'Creado',
+      'modificado' => 'Modificado',
+      'detalle' => 'Detalle',
+    ];
+  }
+
+  /**
+   * Gets query for [[NotificacionUsuarios]].
+   *
+   * @return \yii\db\ActiveQuery
+   */
+  public function getNotificacionUsuarios() {
+    return $this->hasMany(NotificacionUsuario::class, ['idNotificacion' => 'id']);
+  }
+}

+ 76 - 0
models/NotificacionUsuario.php

@@ -0,0 +1,76 @@
+<?php
+
+namespace app\models;
+
+use Yii;
+
+/**
+ * This is the model class for table "NotificacionUsuario".
+ *
+ * @property int $id
+ * @property int|null $idNotificacion
+ * @property int|null $idUsuario
+ * @property string|null $nombre
+ * @property string|null $telefono
+ * @property string|null $parametros
+ * @property string|null $detalle
+ *
+ * @property Notificacion $notificacion
+ * @property Usuario $usuario
+ */
+class NotificacionUsuario extends \yii\db\ActiveRecord {
+  /**
+   * {@inheritdoc}
+   */
+  public static function tableName() {
+    return 'NotificacionUsuario';
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function rules() {
+    return [
+      [['idNotificacion', 'idUsuario'], 'default', 'value' => null],
+      [['idNotificacion', 'idUsuario'], 'integer'],
+      [['parametros', 'detalle'], 'safe'],
+      [['nombre'], 'string', 'max' => 100],
+      [['telefono'], 'string', 'max' => 10],
+      [['idNotificacion'], 'exist', 'skipOnError' => true, 'targetClass' => Notificacion::class, 'targetAttribute' => ['idNotificacion' => 'id']],
+      [['idUsuario'], 'exist', 'skipOnError' => true, 'targetClass' => Usuario::class, 'targetAttribute' => ['idUsuario' => 'id']],
+    ];
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function attributeLabels() {
+    return [
+      'id' => 'ID',
+      'idNotificacion' => 'Id Notificacion',
+      'idUsuario' => 'Id Usuario',
+      'nombre' => 'Nombre',
+      'telefono' => 'Telefono',
+      'parametros' => 'Parametros',
+      'detalle' => 'Detalle',
+    ];
+  }
+
+  /**
+   * Gets query for [[notificacion]].
+   *
+   * @return \yii\db\ActiveQuery
+   */
+  public function getNotificacion() {
+    return $this->hasOne(Notificacion::class, ['id' => 'idNotificacion']);
+  }
+
+  /**
+   * Gets query for [[usuario]].
+   *
+   * @return \yii\db\ActiveQuery
+   */
+  public function getUsuario() {
+    return $this->hasOne(Usuario::class, ['id' => 'idUsuario']);
+  }
+}

+ 90 - 0
modules/v1/controllers/EventoNotificacionController.php

@@ -0,0 +1,90 @@
+<?php
+
+namespace v1\controllers;
+
+use common\data\Respuesta;
+use common\rest\JsonController;
+use yii\db\Expression;
+use yii\db\Query;
+
+class EventoNotificacionController extends JsonController {
+
+  public function actionIndex() {
+    /* $desde = trim($this->req->get("desde", ""));
+    $hasta = trim($this->req->get("hasta", "")); */
+
+    $eventos = (new Query())
+      ->select([
+        "nombre",
+        "tag"
+      ])
+      ->from("Evento")
+      ->andWhere([">=", "fechaFinal", new Expression("now()-interval '7 days'")])
+      // ->andWhere([
+      //   "AND",
+      //   [">=", "fechaFinal", $desde],
+      //   ["<=", "fechaFinal", $hasta]
+      // ])
+      ->groupBy(["tag", "nombre"])
+      ->indexBy("tag")
+      ->column();
+
+    // $sql = $eventos->createCommand()->getRawSql();
+
+    $query2 = (new Query())
+      ->select([
+        "tag",
+        "{{Usuario}}.id",
+        "{{Usuario}}.nombre",
+        "{{Usuario}}.telefono",
+        "case when count({{Resultado}}.accion) > 0 then true else false end as [[Participo]]"
+      ])
+      ->from("Evento")
+      ->innerJoin("EventoGrupo", "{{EventoGrupo}}.[[idEvento]] = {{Evento}}.id")
+      ->innerJoin("Grupo", "{{Grupo}}.id = {{EventoGrupo}}.[[idGrupo]]")
+      ->innerJoin("UsuarioGrupo", "{{UsuarioGrupo}}.[[idGrupo]] = {{Grupo}}.id")
+      ->innerJoin("Usuario", "{{Usuario}}.[[id]] = {{UsuarioGrupo}}.[[idUsuario]]")
+      ->innerJoin("UsuarioDependencia", "{{UsuarioDependencia}}.[[idUsuario]] = {{Usuario}}.id")
+      ->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",
+        "{{Usuario}}.id",
+        "tag"
+      ])
+      ->orderBy([
+        "{{Usuario}}.id" => SORT_ASC,
+        // "tag" => SORT_ASC,
+        "[[Participo]]" => SORT_DESC,
+      ]);
+
+    $aux = [];
+    foreach ($query2->each() as $consulta) {
+      if (!isset($aux[$consulta['id']])) {
+        $aux[$consulta['id']] = [
+          "nombreUsuario" => $consulta['nombre'],
+          "telefono" => $consulta['telefono'],
+          "id" => $consulta['id'],
+          "eventosFaltantes" => [],
+          "eventosParticipo" => []
+        ];
+      }
+      $nombreEvento = $eventos[$consulta['tag']];
+      if ($consulta['Participo']) {
+        $aux[$consulta['id']]['eventosParticipo'][] = $nombreEvento;
+      } else {
+        $aux[$consulta['id']]['eventosFaltantes'][] = $nombreEvento;
+      }
+    }
+
+    return (new Respuesta())
+      ->detalle($aux);
+  }
+}

+ 1 - 1
modules/v1/controllers/ReporteIndividualController.php

@@ -96,7 +96,7 @@ class ReporteIndividualController extends AuthController {
       $query->andWhere([
         "AND",
         [">=", "{{Evento}}.[[fechaInicio]]", $fechaInicio],
-        ["<=", "{{Evento}}.[[fechaFinal]]", $fechaFinal],
+        ["<=", "{{Evento}}.[[fechaInicio]]", $fechaFinal],
       ]);
     }
 

+ 35 - 0
modules/v1/models/NotificacionUsuario.php

@@ -0,0 +1,35 @@
+<?php
+
+namespace v1\models;
+
+use app\models\NotificacionUsuario as ModelsNotificacionUsuario;
+
+class NotificacionUsuario extends ModelsNotificacionUsuario {
+
+  public function fields () {
+    return [
+      'id',
+      'idNotificacion',
+      'idUsuario',
+      'nombre',
+      'telefono',
+      'parametros',
+      'detalle',
+    ];
+  }
+
+  public function extraFields () {
+    return [
+      'notificacion',
+      'usuario'
+    ];
+  }
+
+  public function getNotificacion() {
+    return $this->hasOne(Notificacion::class, ['id' => 'idNotificacion']);
+  }
+
+  public function getUsuario() {
+    return $this->hasOne(Usuario::class, ['id' => 'idUsuario']);
+  }
+}

+ 29 - 0
modules/v1/models/Notificacon.php

@@ -0,0 +1,29 @@
+<?php
+
+namespace v1\models;
+
+use app\models\Notificacion as ModelsNotificacion;
+
+class Notificacion extends ModelsNotificacion {
+
+  public function fields () {
+    return [
+      'id',
+      'envio',
+      'estatus',
+      'creado',
+      'modificado',
+      'detalle',
+    ];
+  }
+
+  public function extraFields () {
+    return [
+      'notificacionUsuarios'
+    ];
+  }
+
+  public function getNotificacionUsuarios() {
+    return $this->hasMany(NotificacionUsuario::class, ['idNotificacion' => 'id']);
+  }
+}