AmosNotify.php 11.1 KB
Newer Older
Marcello Pivanti's avatar
Marcello Pivanti committed
1
2
3
4
5
6
7
<?php

/**
 * Art-ER Attrattività, ricerca e territorio dell’Emilia-Romagna
 * OPEN 2.0
 *
 *
waltermazza's avatar
waltermazza committed
8
 * @package    arter\amos\notify
Marcello Pivanti's avatar
Marcello Pivanti committed
9
10
11
12
 * @category   CategoryName
 * @author     Elite Division S.r.l.
 */

waltermazza's avatar
waltermazza committed
13
namespace arter\amos\notificationmanager;
Marcello Pivanti's avatar
Marcello Pivanti committed
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

/**
 *
 * Plugin per la gestione delle notifiche.
 *
 * Si basa su una Behavior (NotifyBehavior) che aggiunge funzionalità al modello con gli Events:
 *
 *      ActiveRecord::EVENT_AFTER_INSERT
 *      ActiveRecord::EVENT_AFTER_UPDATE
 *
 * quando un record del modello viene inserito o aggiornato, viene aggiunto un record nella coda delle notifica (Notification)
 * per ogni canale configurato nella Behavior (default CHANNEL_ALL).
 *
 *      ActiveRecord::EVENT_AFTER_FIND
 * ogni volta che viene chiamato questo evento per il modello la Behavior inserisce o aggiorna un record per il canale CHANNEL_READ
 * nella coda dei letti (NotificationsRead)
 *
 *      CrudController::AFTER_FINDMODEL_EVENT (evento scatenato dal metodo findModel del CrudController)
 * ogni volta che viene chiamato questo evento per il modello la Behavior inserisce o aggiorna un record per il canale CHANNEL_READ_DETAIL
 * nella coda dei letti (NotificationsRead)
 *
 * Canali di notifica disponibili, possono essere configurati tramite il parametro 'channels' della NotifyBehavior es:
 *
 *      'channels' => [NotificationChannels::CHANNEL_MAIL,NotificationChannels::CHANNEL_IMMEDIATE_MAIL ,NotificationChannels::CHANNEL_ALL]
 *
 *      se presente il valore NotificationChannels::CHANNEL_ALL ha la precedenza inserendo tutti i canali disponibili.
 *
 * CHANNEL_MAIL             -- Canale per la gestione notifiche per mail (TODO)
 * CHANNEL_IMMEDIATE_MAIL   -- Canale per la gestione notifiche per mail immediata (TODO)
 * CHANNEL_UI               -- Canale per la gestione notifiche da User Interface (TODO)
 * CHANNEL_SMS              -- Canale per la gestione notifiche per SMS (TODO)
 * CHANNEL_READ             -- Canale per la gestione notifiche da ActiveRecord::EVENT_AFTER_FIND
 * CHANNEL_READ_DETAIL      -- Canale per la gestione notifiche da CrudController::AFTER_FINDMODEL_EVENT
 * CHANNEL_FAVOURITES       -- Canale per la gestione dei preferiti
 * CHANNEL_ALL              -- Tutti i Canali
 */

waltermazza's avatar
waltermazza committed
51
52
53
54
55
56
57
58
use arter\amos\core\module\AmosModule;
use arter\amos\core\record\Record;
use arter\amos\notificationmanager\base\NotifierRepository;
use arter\amos\notificationmanager\base\NotifyWidget;
use arter\amos\notificationmanager\listeners\NotifyWorkflowListener;
use arter\amos\notificationmanager\models\NotificationChannels;
use arter\amos\notificationmanager\models\NotificationsConfOpt;
use arter\amos\notificationmanager\utility\NotifyUtility;
Marcello Pivanti's avatar
Marcello Pivanti committed
59
60
61
62
63
64
65
66
use raoul2000\workflow\base\SimpleWorkflowBehavior;
use Yii;
use yii\base\Event;
use yii\db\ActiveQuery;
use yii\log\Logger;

/**
 * Class AmosNotify
waltermazza's avatar
waltermazza committed
67
 * @package arter\amos\notificationmanager
Marcello Pivanti's avatar
Marcello Pivanti committed
68
69
70
71
72
73
74
75
76
77
78
79
80
81
 */
class AmosNotify extends AmosModule implements \yii\base\BootstrapInterface, NotifyWidget
{

    public $batchFromDate; // format 'yyyy-mm-dd'
    public $defaultSchedule = NotificationsConfOpt::EMAIL_DAY;
    public $confirmEmailNotification = false;
    public $enableNotificationContentLanguage = false;
    
    private static $notifyworkflowlistener;

    /**
     * @var null |string
     * [
waltermazza's avatar
waltermazza committed
82
83
     *      'arter\amos\admin\models\UserProfile' => '@common/mail/notify_validation/validator_user_profile',
     *      'arter\amos\news\models\News' => '@common/mail/notify_validation/validator_news',
Marcello Pivanti's avatar
Marcello Pivanti committed
84
85
86
87
88
89
90
91
     * ]
     *
     */
    public $viewPathEmailNotifyValidator = [];

    /**
     * @var null |string
     * [
waltermazza's avatar
waltermazza committed
92
93
     *      'arter\amos\admin\models\UserProfile' => '@common/mail/notify_validation/validated_user_profile',
     *      'arter\amos\news\models\News' => '@common/mail/notify_validation/validated_news',
Marcello Pivanti's avatar
Marcello Pivanti committed
94
95
96
97
98
99
100
     * ]
     */
    public $viewPathEmailNotifyValidated = [];

    /**
     * @inheritdoc
     */
waltermazza's avatar
waltermazza committed
101
    public $controllerNamespace = 'arter\amos\notificationmanager\controllers';
Marcello Pivanti's avatar
Marcello Pivanti committed
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125

    /**
     * @inheritdoc
     */
    public function __construct($id, $parent = null, array $config = [])
    {
        self::$notifyworkflowlistener = new NotifyWorkflowListener();
        parent::__construct($id, $parent, $config);
    }

    /**
     * @inheritdoc
     */
    public static function getModuleName()
    {
        return "notify";
    }

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
waltermazza's avatar
waltermazza committed
126
        \Yii::setAlias('@arter/amos/notificationmanager/commands', __DIR__ . '/commands/');
Marcello Pivanti's avatar
Marcello Pivanti committed
127
128
129
130
131
132
133
134
135
136
        // initialize the module with the configuration loaded from config.php
        \Yii::configure($this, require(__DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php'));
    }

    /**
     * @param \yii\console\Application $app
     */
    public function bootstrap($app)
    {
        if ($app instanceof \yii\console\Application) {
waltermazza's avatar
waltermazza committed
137
            $this->controllerNamespace = 'arter\amos\notificationmanager\commands';
Marcello Pivanti's avatar
Marcello Pivanti committed
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
        } else {
            Event::on(
                Record::className(),
                SimpleWorkflowBehavior::EVENT_AFTER_CHANGE_STATUS,
                [self::$notifyworkflowlistener, 'afterChangeStatus']
            );
        }
    }

    /**
     * @inheritdoc
     */
    protected function getDefaultModels()
    {
        return [
            'ChangeStatusEmail' => __NAMESPACE__ . '\\' . 'models\ChangeStatusEmail',
            'Notification' => __NAMESPACE__ . '\\' . 'models\Notification',
            'NotificationChannels' => __NAMESPACE__ . '\\' . 'models\NotificationChannels',
            'NotificationConf' => __NAMESPACE__ . '\\' . 'models\NotificationConf',
            'NotificationsConfOpt' => __NAMESPACE__ . '\\' . 'models\NotificationsConfOpt',
            'NotificationconfNetwork' => __NAMESPACE__ . '\\' . 'models\NotificationconfNetwork',
            'NotificationsRead' => __NAMESPACE__ . '\\' . 'models\NotificationsRead',
            'NotificationSendEmail' => __NAMESPACE__ . '\\' . 'models\NotificationSendEmail',
        ];
    }

    /**
     * @inheritdoc
     */
    public function getWidgetGraphics()
    {
        return [];
    }

    /**
     * @inheritdoc
     */
    public function getWidgetIcons()
    {
        return [];
    }

    /**
     * @param int $uid
     * @param string $class_name
     * @param ActiveQuery|null $externalquery
     * @param NotificationChannels $channel
     */
    public function notificationOff($uid, $class_name, $externalquery = null, $channel)
    {
        try {
            $repository = new NotifierRepository();
            $repository->notificationOff($uid, $class_name, $externalquery, $channel);
        } catch (\Exception $ex) {
            Yii::getLogger()->log($ex->getTraceAsString(), Logger::LEVEL_ERROR);
        }
    }

    /**
     * @param int $uid
     * @param string $class_name
     * @param ActiveQuery|null $externalquery
     * @param NotificationChannels $channel
     */
    public function notificationOn($uid, $class_name, $externalquery = null, $channel)
    {
        try {
            $repository = new NotifierRepository();
            $repository->notificationOn($uid, $class_name, $externalquery, $channel);
        } catch (\Exception $ex) {
            Yii::getLogger()->log($ex->getTraceAsString(), Logger::LEVEL_ERROR);
        }
    }

    /**
     * @param int $uid
     * @param string $class_name
     * @param ActiveQuery|null $externalquery
     * @return false|int|null|string
     */
    public function countNotRead($uid, $class_name, $externalquery = null)
    {
        $result = 0;
        try {
            $repository = new NotifierRepository();
            $result = $repository->countNotRead($uid, $class_name, $externalquery);
        } catch (\Exception $ex) {
            Yii::getLogger()->log($ex->getTraceAsString(), Logger::LEVEL_ERROR);
        }
        
        return $result;
    }

    /**
     * @param $model
     * @param int|null $uid
     * @return bool
     */
    public function modelIsRead($model, $uid = null)
    {
        $result = false;
        try {
            $repository = new NotifierRepository();
            $result = $repository->modelIsRead($model, $uid);
        } catch (\Exception $ex) {
            Yii::getLogger()->log($ex->getTraceAsString(), Logger::LEVEL_ERROR);
        }
        
        return $result;
    }

    /**
     * @param string $modelClassName
     * @param int $channel
     * @param string $type
     * @return array|bool
     */
    public static function manageNewChannelNotifications($modelClassName, $channel, $type)
    {
        $retval = false;
        try {
            /** @var NotificationChannels $notificationChannel */
            $notificationChannel = AmosNotify::instance()->createModel('NotificationChannels');
            $retval = $notificationChannel->manageNewChannelNotifications($modelClassName, $channel, $type);
        } catch (\Exception $ex) {
            Yii::getLogger()->log($ex->getTraceAsString(), Logger::LEVEL_ERROR);
        }
        
        return $retval;
    }

    /**
     * @param int $uid
     * @param string $class_name
     * @param int $contentId
     * @return bool
     */
    public function favouriteOn($uid, $class_name, $contentId)
    {
        $ok = true;
        try {
            $repository = new NotifierRepository();
            $ok = $repository->favouriteOn($uid, $class_name, $contentId);
        } catch (\Exception $ex) {
            Yii::getLogger()->log($ex->getTraceAsString(), Logger::LEVEL_ERROR);
        }
        
        return $ok;
    }

    /**
     * @param int $uid
     * @param string $class_name
     * @param int $contentId
     * @return bool
     */
    public function favouriteOff($uid, $class_name, $contentId)
    {
        $ok = true;
        try {
            $repository = new NotifierRepository();
            $ok = $repository->favouriteOff($uid, $class_name, $contentId);
        } catch (\Exception $ex) {
            Yii::getLogger()->log($ex->getTraceAsString(), Logger::LEVEL_ERROR);
        }
        
        return $ok;
    }

    /**
     * @param $model
     * @param int|null $uid
     * @return bool
     */
    public function isFavorite($model, $uid = null)
    {
        $result = false;
        try {
            //$repository = new NotifierRepository();
            //$result = $repository->isFavorite($model, $uid);
        } catch (\Exception $ex) {
            Yii::getLogger()->log($ex->getTraceAsString(), Logger::LEVEL_ERROR);
        }

        return $result;
    }

    /**
     * The method save the notification configuration.
     * @param int $userId
     * @param int $emailFrequency
     * @param int $smsFrequency
     * @return bool
     */
    public function saveNotificationConf($userId, $emailFrequency = 0, $smsFrequency = 0, $params = [])
    {	
        $notifyUtility = new NotifyUtility();
        return $notifyUtility->saveNotificationConf($userId, $emailFrequency, $smsFrequency, $params);
    }

    /**
     * This method set the user default notifications configurations.
     * @param int $userId
     * @return bool
     */
    public function setDefaultNotificationsConfs($userId)
    {
        $notifyUtility = new NotifyUtility();
        return $notifyUtility->setDefaultNotificationsConfs($userId);
    }
}