Advertisement
Guest User

Untitled

a guest
Sep 20th, 2019
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 18.15 KB | None | 0 0
  1. <?php
  2.  
  3. namespace app\commands;
  4.  
  5. use app\components\notifications\Notification;
  6. use app\components\notifications\NotificationSender;
  7. use app\modules\booking\models\Booking;
  8. use app\modules\booking\models\BookingReview;
  9. use app\modules\booking\models\BookingStatus;
  10. use app\modules\message\models\Dialog;
  11. use app\modules\user\models\User;
  12.  
  13. /**
  14.  * Class BookingNotificationController
  15.  *
  16.  * @author Evgeniy Vologdin <muns@muns.su>
  17.  * @since 2016-01-19
  18.  * @version 0.1
  19.  */
  20. class NotificationMinController extends \yii\console\Controller
  21. {
  22.     // периодичность: 1 раз в минуту
  23.  
  24.     const DAY = 86400;
  25.  
  26.     public function actionIndex()
  27.     {
  28.         $this->cancelNotConfirmed(); // закрытие аренды, если арендодатель не ответил
  29.         $this->cancelNotConfirmedFitting(); // закрытие не подтвержденных примерок и переписок
  30.         $this->cancelOldConfirmedFitting(); // закрытие подтвержденных примерок
  31.         //$this->cancelNotPayment(); // закрытие аренды, если арендатор не внес предоплату
  32.         $this->cancelNotReceived(); // закрытие аренды, если вещь не получена
  33. //      $this->fittingReminder(); //напоминание о том, что скоро примерка (за 5 или 10ч в зависимости от времени)
  34.         $this->fittingStartReminder(); //напоминание о том, что примерка уже началась
  35.         $this->bookingMeetingReminder(); // напоминание о том, что сегодня состоится аренда (за 8 часов до начала аренды)
  36.         $this->bookingFirstPayReminder(); // напоминание о том, что нужно внести предоплату (через 12ч после подтверждения аренды)
  37.         $this->bookingSecondPayReminder(); // напоминание о том, что можно оплатить вторую часть (за 72 часа до начала аренды)
  38.         $this->bookingRequestReminder(); // напоминание о том, что нужно ответить на запрос (через 1ч после запроса)
  39.         $this->bookingReturnReminder(); // напоминание о возврате вещи (за 24 часа до конца аренды)
  40.         $this->bookingMessageReminder(); // напоминание ответить на сообщение (через 1ч после запроса)
  41.         $this->publishReviews(); // публикация отзывов
  42. //        $this->sendReviewNotification(); // напоминание об отзыве
  43.         $this->bookingUpdateReminder(); //оповещение об изменениях в аренде
  44. //        $this->bookingUnreadMessageReminder(); //оповещение о новых сообщениях
  45.     }
  46.  
  47.     /**
  48.      * @deprecated перенесено на rabbitmq
  49.      * @todo удалить после 11.02.2019
  50.      */
  51.     protected function bookingUnreadMessageReminder()
  52.     {
  53.         $bookings = Booking::find()
  54.             ->leftJoin(Dialog::tableName() . ' as d', 'd.book_id = {{%booking}}.id')
  55.             ->where(['d.start_remind_time' => 1])
  56.             ->andWhere('UNIX_TIMESTAMP() - d.last_message_time >= 600')
  57.             ->andWhere('UNIX_TIMESTAMP() - d.last_message_time < 720')
  58.             ->all();
  59.  
  60.         echo "Start chatReminder\n";
  61.  
  62.         foreach ($bookings as $booking) {
  63.             $booking->trigger(Booking::EVENT_CREATE_MESSAGE);
  64.             echo 'remind send for Booking '.$booking->id."\n\r";
  65.         }
  66.  
  67.         echo "Finish chatReminder\n";
  68.     }
  69.  
  70.     protected function bookingUpdateReminder()
  71.     {
  72.         $bookings = Booking::find()
  73.             ->where('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking}}.send_notification_time)) >= 0')
  74.             ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking}}.send_notification_time)) < 120')
  75.             ->all();
  76.  
  77.         echo "Start bookingUpdateReminder\n";
  78.  
  79.         foreach ($bookings as $booking) {
  80.             $booking->trigger(Booking::EVENT_BOOKING_UPDATE_BY_TIMER);
  81.             echo 'remind send for Booking '.$booking->id."\n\r";
  82.             $booking->send_notification_time = null;
  83.             $booking->update(['send_notification_time']);
  84.         }
  85.  
  86.         echo "Finish bookingUpdateReminder\n";
  87.     }
  88.  
  89.     protected function sendNotification($user, $type, Array $params, $sender = null)
  90.     {
  91.         if(isset($sender)){
  92.             $disabled_notifications = isset($sender->disabled_notifications) ? $sender->disabled_notifications : null;
  93.  
  94.             if(empty($disabled_notifications)){
  95.                 $disabled_notifications = isset($sender->booking) ? $sender->booking->disabled_notifications : null;
  96.             }
  97.             if($disabled_notifications != 1){
  98.                 (new NotificationSender($type, $user, $sender, $params))->send();
  99.             }
  100.         } else {
  101.             (new Notification($type, $user, $params))->notificateUser();
  102.         }
  103.     }
  104.  
  105.     protected function cancelNotConfirmed()
  106.     {
  107.         $models = Booking::find()
  108.             ->joinWith(['owner'])
  109.             ->joinWith(['lastStatus'])
  110.             ->where(['{{%booking}}.status' => BookingStatus::STATUS_REQUEST])
  111.             ->andWhere('{{%booking}}.isup_user_id IS NULL')
  112.             ->andWhere(['>=', '{{%booking}}.id', 4430])  //скрипт долгое время не работал из-за ошибки, поэтому отправляем уведомления только самым последним
  113.             ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking_status}}.create_time)) >= 86400')
  114.             ->all();
  115.  
  116.         $this->cancelAutoDenied($models);
  117.     }
  118.  
  119.     protected function cancelNotConfirmedFitting()
  120.     {
  121.         $models = Booking::find()
  122.             ->joinWith(['owner'])
  123.             ->joinWith(['lastStatus'])
  124.             ->where(['{{%booking}}.status' => BookingStatus::STATUS_FITTING_REQUEST])
  125.             ->andWhere(['>=', '{{%booking}}.id', 7389])  // применяется только к арендам от 01.11.2017
  126.             ->andWhere('{{%booking}}.isup_user_id IS NULL')
  127.             ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking_status}}.create_time)) >= 86400')
  128.             ->all();
  129.  
  130.         $this->cancelAutoDenied($models);
  131.     }
  132.  
  133.     protected function cancelOldConfirmedFitting()
  134.     {
  135.         $models = Booking::find()
  136.             ->joinWith(['owner'])
  137.             ->where(['{{%booking}}.status' => BookingStatus::STATUS_FITTING_RESERVED])
  138.             ->andWhere(['>=', '{{%booking}}.id', 7389])  // применяется только к арендам от 01.11.2017
  139.             ->andWhere('{{%booking}}.isup_user_id IS NULL')
  140.             ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking}}.finish_time)) >= ' . self::DAY * 1.5)
  141.             ->all();
  142.  
  143.         $this->cancelAutoDenied($models);
  144.     }
  145.  
  146.     protected function cancelAutoDenied($models)
  147.     {
  148.         $current_date = new \DateTime();
  149.  
  150.         foreach ($models AS $model) {
  151.             /** @var Booking $model */
  152.             if(!$this->isWorkingTime($model->owner, $current_date)){
  153.                 continue;
  154.             }
  155.  
  156.             $status = new BookingStatus();
  157.             $status->status  = BookingStatus::STATUS_AUTO_DENIED;
  158.             $status->user_id = $model->getSellerId();
  159.             $status->booking_id = $model->id;
  160.             $status->booking->scenario = Booking::SCENARIO_CHANGE_STATUS_AUTOMATICALLY;
  161.             if ($status->save()) {
  162.                 echo "booking {$model->UID} denied\n";
  163.             } else {
  164.                 var_dump($status->getErrors());
  165.             }
  166.         }
  167.     }
  168.  
  169.     protected function cancelNotPayment()
  170.     {
  171.         $current_date = new \DateTime();
  172.  
  173.         $models = Booking::find()
  174.             ->joinWith(['lastStatus', 'firstAccount', 'owner'])
  175.             ->where(['{{%booking}}.status' => BookingStatus::STATUS_RESERVED])
  176.             ->andWhere(['>=', '{{%booking}}.id', 4430]) //скрипт долгое время не работал из-за ошибки, поэтому отправляем уведомления только самым последним
  177.             ->andWhere(['{{%booking}}.cash_payment' => '0'])
  178.             ->andWhere('{{%booking}}.isup_user_id IS NULL')
  179.             ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking_status}}.create_time)) >= 86400 OR UNIX_TIMESTAMP({{%booking}}.start_time) <= UNIX_TIMESTAMP()')
  180.             ->andWhere('{{%account}}.id IS NULL')
  181.             ->andWhere('{{%booking}}.full_account_id IS NULL')
  182.             ->all();
  183.  
  184.         foreach ($models AS $model) {
  185.             /** @var Booking $model */
  186.             if(!$this->isWorkingTime($model->owner, $current_date)){
  187.                 continue;
  188.             }
  189.  
  190.             $status = new BookingStatus();
  191.             $status->status  = BookingStatus::STATUS_NOT_PAY_CANCEL;
  192.             $status->user_id = $model->getBuyerId();
  193.             $status->booking_id = $model->id;
  194.             if ($status->save()) {
  195.                 echo "booking {$model->UID} cancel\n";
  196.             } else {
  197.                 var_dump($status->getErrors());
  198.             }
  199.         }
  200.     }
  201.  
  202.     protected function cancelNotReceived()
  203.     {
  204.         $current_date = new \DateTime();
  205.         /** @var Booking[] $models */
  206.         $models = Booking::find()
  207.             //->joinWith(['owner'])
  208.             ->where(['{{%booking}}.status' => BookingStatus::STATUS_RESERVED])
  209.             //->andWhere(['>=', '{{%booking}}.id', 7389])  // применяется только к арендам от 01.11.2017
  210.             ->andWhere('{{%booking}}.isup_user_id IS NULL')
  211.             ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking}}.start_time)) >= 86400')
  212.             ->andWhere('{{%booking}}.first_account_id IS NULL')
  213.             ->andWhere('{{%booking}}.second_account_id IS NULL')
  214.             ->andWhere('{{%booking}}.full_account_id IS NULL')
  215.             ->andWhere('{{%booking}}.deposit_account_id IS NULL')
  216.             ->all();
  217.  
  218.         foreach ($models as $model) {
  219.             if(!$this->isWorkingTime($model->owner, $current_date)){
  220.                 continue;
  221.             }
  222.  
  223.             $status = new BookingStatus();
  224.             $status->status  = BookingStatus::STATUS_NOT_PAY_CANCEL;
  225.             $status->user_id = $model->getBuyerId();
  226.             $status->booking_id = $model->id;
  227.             if ($status->save()) {
  228.                 echo "booking {$model->UID} cancel\n";
  229.             } else {
  230.                 var_dump($status->getErrors());
  231.             }
  232.         }
  233.     }
  234.  
  235.     /**
  236.      * Вроде это дублирует то что внизу
  237.      */
  238.     protected function fittingStartReminder()
  239.     {
  240.         $models = Booking::find()
  241.             ->where(['{{%booking}}.status' => BookingStatus::STATUS_FITTING_RESERVED])
  242.             ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking}}.start_time)) >= 0')
  243.             ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking}}.start_time)) <= 60')
  244.             ->all();
  245.  
  246.         foreach ($models AS $model) {
  247.             $model->trigger(Booking::EVENT_FITTING);
  248.         }
  249.  
  250.         $models = Booking::find()
  251.             ->where(['{{%booking}}.status' => BookingStatus::STATUS_FITTING_RESERVED])
  252.             ->andWhere('(UNIX_TIMESTAMP({{%booking}}.start_time) - UNIX_TIMESTAMP()) >= 36000')
  253.             ->andWhere('(UNIX_TIMESTAMP({{%booking}}.start_time) - UNIX_TIMESTAMP()) <= 36060')
  254.             ->all();
  255.  
  256.         foreach ($models AS $model) {
  257.             $model->trigger(Booking::EVENT_FITTING);
  258.         }
  259.  
  260.         $models = Booking::find()
  261.             ->where(['{{%booking}}.status' => BookingStatus::STATUS_FITTING_RESERVED])
  262.             ->andWhere('(UNIX_TIMESTAMP({{%booking}}.start_time) - UNIX_TIMESTAMP()) >= 18000')
  263.             ->andWhere('(UNIX_TIMESTAMP({{%booking}}.start_time) - UNIX_TIMESTAMP()) <= 18060')
  264.             ->all();
  265.  
  266.         foreach ($models AS $model) {
  267.             $model->trigger(Booking::EVENT_FITTING);
  268.         }
  269.     }
  270.  
  271.     /**
  272.      * А это дублирует то что вверху, оставлю верхний
  273.      */
  274. //  protected function fittingReminder()
  275. //  {
  276. //      $models = Booking::find()
  277. //          ->where(['{{%booking}}.status' => BookingStatus::STATUS_FITTING_RESERVED])
  278. //          ->andWhere('(UNIX_TIMESTAMP({{%booking}}.start_time) - UNIX_TIMESTAMP()) >= 0')
  279. //          ->all();
  280. //
  281. //      echo "Start fittingReminder\n";
  282. //
  283. //      foreach ($models AS $model) {
  284. //          $model->trigger(Booking::EVENT_FITTING);
  285. //      }
  286. //
  287. //      echo "Finish fittingReminder\n";
  288. //  }
  289.  
  290.     protected function bookingFirstPayReminder()
  291.     {
  292.         $models = Booking::find()
  293.             ->joinWith(['firstAccount', 'lastStatus', 'info'])
  294.             ->where(['{{%booking}}.status' => BookingStatus::STATUS_RESERVED])
  295.             ->andWhere(['{{%booking}}.cash_payment' => '0'])
  296.             ->andWhere(['{{%booking_info}}.first_pay_remind' => '0'])
  297.             ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking_status}}.create_time)) >= 43200')
  298.             ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking_status}}.create_time)) < 43320')
  299.             ->andWhere('{{%account}}.id IS NULL')
  300.             ->all();
  301.  
  302.         echo "Start bookingFirstPayReminder\n";
  303.  
  304.         foreach ($models AS $model) {
  305.             $model->info->first_pay_remind = 1;
  306.             $model->info->update(['first_pay_remind']);
  307.         }
  308.  
  309.         echo "Finish bookingFirstPayReminder\n";
  310.     }
  311.  
  312.     protected function bookingSecondPayReminder()
  313.     {
  314.         $models = Booking::find()
  315.             ->joinWith(['info'])
  316.             ->where(['{{%booking}}.status' => BookingStatus::STATUS_RESERVED])
  317.             ->andWhere('{{%booking}}.first_account_id IS NOT NULL')
  318.             ->andWhere('{{%booking}}.second_account_id IS NULL')
  319.             ->andWhere(['{{%booking}}.cash_payment' => '0'])
  320.             ->andWhere(['{{%booking_info}}.second_pay_remind' => '0'])
  321.             ->andWhere('(UNIX_TIMESTAMP({{%booking}}.start_time) - UNIX_TIMESTAMP()) >= 259140')
  322.             ->andWhere('(UNIX_TIMESTAMP({{%booking}}.start_time) - UNIX_TIMESTAMP()) < 259260')
  323.             ->all();
  324.  
  325.         echo "Start bookingSecondPayReminder\n";
  326.  
  327.         foreach ($models AS $model) {
  328.             $model->info->second_pay_remind = 1;
  329.             $model->info->update(['second_pay_remind']);
  330.         }
  331.  
  332.         echo "Finish bookingSecondPayReminder\n";
  333.     }
  334.  
  335.     protected function bookingMeetingReminder()
  336.     {
  337.         $models = Booking::find()
  338.             ->joinWith(['info'])
  339.             ->where(['{{%booking}}.status' => BookingStatus::STATUS_RESERVED])
  340.             ->andWhere(['{{%booking_info}}.meeting_remind' => '0'])
  341.             ->andWhere('(UNIX_TIMESTAMP({{%booking}}.start_time) - UNIX_TIMESTAMP()) >= 28800')
  342.             ->andWhere('(UNIX_TIMESTAMP({{%booking}}.start_time) - UNIX_TIMESTAMP()) < 28920')
  343.             ->all();
  344.  
  345.         echo "Start bookingMeetingReminder\n";
  346.  
  347.         foreach ($models AS $model) {
  348.             $model->info->meeting_remind = 1;
  349.             $model->info->update(['meeting_remind']);
  350.         }
  351.  
  352.         echo "Finish bookingMeetingReminder\n";
  353.     }
  354.  
  355.     protected function bookingRequestReminder()
  356.     {
  357.         $models = Booking::find()
  358.             ->joinWith(['info'])
  359.             ->where(['{{%booking}}.status' => BookingStatus::STATUS_REQUEST])
  360.             ->andWhere(['{{%booking_info}}.request_remind' => '0'])
  361.             ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking}}.create_time)) >= 3600')
  362.             ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking}}.create_time)) < 3720')
  363.             ->all();
  364.  
  365.         echo "Start bookingRequestReminder\n";
  366.  
  367.         foreach ($models AS $model) {
  368.             $model->info->request_remind = 1;
  369.             $model->info->update(['request_remind']);
  370.         }
  371.  
  372.         echo "Finish bookingRequestReminder\n";
  373.     }
  374.  
  375.     protected function bookingReturnReminder()
  376.     {
  377.         $models = Booking::find()
  378.             ->joinWith(['info'])
  379.             ->where(['{{%booking}}.status' => BookingStatus::STATUS_RECEIVED_ACCEPTED])
  380.             ->andWhere(['{{%booking_info}}.return_remind' => '0'])
  381.             ->andWhere('(UNIX_TIMESTAMP({{%booking}}.finish_time) - UNIX_TIMESTAMP()) >= 86400')
  382.             ->andWhere('(UNIX_TIMESTAMP({{%booking}}.finish_time) - UNIX_TIMESTAMP()) < 86520')
  383.             ->all();
  384.  
  385.         echo "Start bookingReturnReminder\n";
  386.  
  387.         foreach ($models AS $model) {
  388.             $model->info->return_remind = 1;
  389.             $model->info->update(['return_remind']);
  390.         }
  391.  
  392.         echo "Finish bookingReturnReminder\n";
  393.     }
  394.  
  395.     protected function bookingMessageReminder()
  396.     {
  397.         $models = Booking::find()
  398.             ->joinWith(['info'])
  399.             ->where(['{{%booking}}.status' => [BookingStatus::STATUS_REQUEST, BookingStatus::STATUS_CREATED]])
  400.             ->andWhere(['{{%booking_info}}.message_remind' => '0'])
  401.             ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking}}.create_time)) >= 3600')
  402.             ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking}}.create_time)) < 3720')
  403.             ->all();
  404.  
  405.         echo "Start bookingMessageReminder\n";
  406.  
  407.         foreach ($models AS $model) {
  408.             $model->info->message_remind = 1;
  409.             $model->info->update(['message_remind']);
  410.         }
  411.  
  412.         echo "Finish bookingMessageReminder\n";
  413.     }
  414.  
  415.     protected function publishReviews()
  416.     {
  417.         $models = BookingReview::find()->leftJoin('{{%booking}}', '{{%booking}}.id = booking_id')->andWhere(['active' => '0'])->andWhere('{{%booking}}.finish_time <= :date' , [
  418.             ':date' => (new \DateTime)->modify('-' . BookingReview::REVIEW_DAYS_TO_PUBLISH . ' day')->format('Y-m-d H:i:s')
  419.         ])->all();
  420.  
  421.         foreach ($models AS $model) {
  422.             echo "Публикация отзыва ID-{$model->id}\n";
  423.             $model->active = 1;
  424.             $model->save(false);
  425.         }
  426.     }
  427.  
  428.     protected function sendReviewNotification()
  429.     {
  430.         $models = Booking::find()->leftJoin("{{%booking_info}} as binfo", "binfo.booking_id = id")->andWhere('binfo.review_notify_count >= 1 AND binfo.review_notify_count < 3')->all();
  431.  
  432.         foreach ($models AS $model) {
  433.             if ((time() - strtotime($model->finish_time)) / 86400 >= 2) {
  434.                 $model->info->review_notify_count = 2;
  435.                 $model->info->save();
  436.             }
  437.  
  438.             if ((time() - strtotime($model->finish_time)) / 86400 >= 6) {
  439.                 $model->info->review_notify_count = 3;
  440.                 $model->info->save();
  441.             }
  442.  
  443.             if ($model->info->isAttributeChanged('review_notify_count') === true) {
  444.                 echo "Отправка {$model->info->review_notify_count} уведомления об отзыве для брони UID-{$model->UID}\n";
  445.                 $model->save(false);
  446.             }
  447.         }
  448.     }
  449.  
  450.     protected function isWorkingTime(User $owner, \DateTime $current_date){
  451.         $working_time = $owner->getDatetimeWorktime($current_date);
  452.  
  453.         if(!is_null($working_time)){
  454.             if(!is_null($working_time->start_time) && $working_time->start_time > $current_date->format('H:i:s')){
  455.                 return false;
  456.             }
  457.  
  458.             if(!is_null($working_time->finish_time) && $working_time->finish_time < $current_date->format('H:i:s')){
  459.                 return false;
  460.             }
  461.         }
  462.  
  463.         return true;
  464.     }
  465. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement