فهرست منبع

Base sincronización

Hugo Quijada 3 سال پیش
والد
کامیت
2a1612715f
2فایلهای تغییر یافته به همراه146 افزوده شده و 0 حذف شده
  1. 71 0
      commands/EventoController.php
  2. 75 0
      components/FirebaseHelper.php

+ 71 - 0
commands/EventoController.php

@@ -0,0 +1,71 @@
+<?php
+
+namespace app\commands;
+
+use app\components\FirebaseHelper;
+use v1\models\Evento;
+use v1\models\Grupo;
+use yii\console\Controller;
+
+class EventoController extends Controller {
+
+  public function actionSincronizar() {
+    $firebase = new FirebaseHelper();
+    $firestore = $firebase->firestore();
+
+    $ultimaFecha = null;
+    $limite = 1; // 1000;
+    $continuar = true;
+    do {
+      $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) {
+        $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"];
+
+          // Mapear información de los modelos
+
+          $hoy = new \DateTime();
+          $doc->reference()
+            ->update([
+              ["path" => "sincronizado", "value" => "OK"],
+              ["path" => "sincronizadoFecha", "value" => $hoy->format("Y-m-d H:i:s")],
+              ["path" => "evidencias", "value" => $data["evidencias"]],
+            ]);
+        } catch(\Exception $e) {
+          $this->stdout("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);
+  }
+
+}

+ 75 - 0
components/FirebaseHelper.php

@@ -0,0 +1,75 @@
+<?php
+
+namespace app\components;
+
+use Kreait\Firebase\Factory;
+use Kreait\Firebase\Messaging\CloudMessage;
+
+class FirebaseHelper {
+
+  const TIPO_PAGO = "pago";
+  const TIPO_PEDIDO = "pedido";
+  const TIPO_PROMOCION = "promocion";
+
+  private $_firebase = null;
+  private $_firestore = null;
+  private $_messaging = null;
+
+  function firebase() {
+    $params = \Yii::$app->params;
+    if($this->_firebase === null) {
+      $this->_firebase = (new Factory)
+        ->withServiceAccount($params['firebaseKey']);
+    }
+
+    return $this->_firebase;
+  }
+
+  function firestore() {
+    if($this->_firestore === null) {
+      $this->_firestore = self::firebase()
+        ->createFirestore()
+        ->database();
+    }
+
+    return $this->_firestore;
+  }
+
+  function messaging() {
+    if($this->_messaging === null) {
+      $this->_messaging = $this->firebase()
+        ->createMessaging();
+    }
+    return $this->_messaging;
+  }
+
+  public static function enviarNotificacion($idCliente, CloudMessage $notificacion) {
+    $model = new self();
+    return $model->enviar($idCliente, $notificacion);
+  }
+
+  public function enviar($idCliente, CloudMessage $notificacion) {
+    if(!$idCliente)
+      return null;
+
+    $firestore = $this->firestore();
+    $doc = $firestore->collection("clientes")
+      ->document($idCliente);
+
+    $data = $doc->snapshot()->data();
+    $tokens = $data["tokens"];
+
+    if(empty($tokens))
+      return null;
+    
+    $resultado = $this->messaging()->sendMulticast($notificacion, $tokens);
+    # Actualizar los tokens en firestore con los que si funcionaron
+    $tokenValidos = $resultado->validTokens();
+
+    $doc->update([
+      ["path" => "tokens", "value" => $tokenValidos],
+    ]);
+
+  }
+
+}