Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace app\commands;
- use app\components\notifications\Notification;
- use app\components\notifications\NotificationSender;
- use app\modules\booking\models\Booking;
- use app\modules\booking\models\BookingReview;
- use app\modules\booking\models\BookingStatus;
- use app\modules\message\models\Dialog;
- use app\modules\user\models\User;
- /**
- * Class BookingNotificationController
- *
- * @author Evgeniy Vologdin <muns@muns.su>
- * @since 2016-01-19
- * @version 0.1
- */
- class NotificationMinController extends \yii\console\Controller
- {
- // периодичность: 1 раз в минуту
- const DAY = 86400;
- public function actionIndex()
- {
- $this->cancelNotConfirmed(); // закрытие аренды, если арендодатель не ответил
- $this->cancelNotConfirmedFitting(); // закрытие не подтвержденных примерок и переписок
- $this->cancelOldConfirmedFitting(); // закрытие подтвержденных примерок
- //$this->cancelNotPayment(); // закрытие аренды, если арендатор не внес предоплату
- $this->cancelNotReceived(); // закрытие аренды, если вещь не получена
- // $this->fittingReminder(); //напоминание о том, что скоро примерка (за 5 или 10ч в зависимости от времени)
- $this->fittingStartReminder(); //напоминание о том, что примерка уже началась
- $this->bookingMeetingReminder(); // напоминание о том, что сегодня состоится аренда (за 8 часов до начала аренды)
- $this->bookingFirstPayReminder(); // напоминание о том, что нужно внести предоплату (через 12ч после подтверждения аренды)
- $this->bookingSecondPayReminder(); // напоминание о том, что можно оплатить вторую часть (за 72 часа до начала аренды)
- $this->bookingRequestReminder(); // напоминание о том, что нужно ответить на запрос (через 1ч после запроса)
- $this->bookingReturnReminder(); // напоминание о возврате вещи (за 24 часа до конца аренды)
- $this->bookingMessageReminder(); // напоминание ответить на сообщение (через 1ч после запроса)
- $this->publishReviews(); // публикация отзывов
- // $this->sendReviewNotification(); // напоминание об отзыве
- $this->bookingUpdateReminder(); //оповещение об изменениях в аренде
- // $this->bookingUnreadMessageReminder(); //оповещение о новых сообщениях
- }
- /**
- * @deprecated перенесено на rabbitmq
- * @todo удалить после 11.02.2019
- */
- protected function bookingUnreadMessageReminder()
- {
- $bookings = Booking::find()
- ->leftJoin(Dialog::tableName() . ' as d', 'd.book_id = {{%booking}}.id')
- ->where(['d.start_remind_time' => 1])
- ->andWhere('UNIX_TIMESTAMP() - d.last_message_time >= 600')
- ->andWhere('UNIX_TIMESTAMP() - d.last_message_time < 720')
- ->all();
- echo "Start chatReminder\n";
- foreach ($bookings as $booking) {
- $booking->trigger(Booking::EVENT_CREATE_MESSAGE);
- echo 'remind send for Booking '.$booking->id."\n\r";
- }
- echo "Finish chatReminder\n";
- }
- protected function bookingUpdateReminder()
- {
- $bookings = Booking::find()
- ->where('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking}}.send_notification_time)) >= 0')
- ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking}}.send_notification_time)) < 120')
- ->all();
- echo "Start bookingUpdateReminder\n";
- foreach ($bookings as $booking) {
- $booking->trigger(Booking::EVENT_BOOKING_UPDATE_BY_TIMER);
- echo 'remind send for Booking '.$booking->id."\n\r";
- $booking->send_notification_time = null;
- $booking->update(['send_notification_time']);
- }
- echo "Finish bookingUpdateReminder\n";
- }
- protected function sendNotification($user, $type, Array $params, $sender = null)
- {
- if(isset($sender)){
- $disabled_notifications = isset($sender->disabled_notifications) ? $sender->disabled_notifications : null;
- if(empty($disabled_notifications)){
- $disabled_notifications = isset($sender->booking) ? $sender->booking->disabled_notifications : null;
- }
- if($disabled_notifications != 1){
- (new NotificationSender($type, $user, $sender, $params))->send();
- }
- } else {
- (new Notification($type, $user, $params))->notificateUser();
- }
- }
- protected function cancelNotConfirmed()
- {
- $models = Booking::find()
- ->joinWith(['owner'])
- ->joinWith(['lastStatus'])
- ->where(['{{%booking}}.status' => BookingStatus::STATUS_REQUEST])
- ->andWhere('{{%booking}}.isup_user_id IS NULL')
- ->andWhere(['>=', '{{%booking}}.id', 4430]) //скрипт долгое время не работал из-за ошибки, поэтому отправляем уведомления только самым последним
- ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking_status}}.create_time)) >= 86400')
- ->all();
- $this->cancelAutoDenied($models);
- }
- protected function cancelNotConfirmedFitting()
- {
- $models = Booking::find()
- ->joinWith(['owner'])
- ->joinWith(['lastStatus'])
- ->where(['{{%booking}}.status' => BookingStatus::STATUS_FITTING_REQUEST])
- ->andWhere(['>=', '{{%booking}}.id', 7389]) // применяется только к арендам от 01.11.2017
- ->andWhere('{{%booking}}.isup_user_id IS NULL')
- ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking_status}}.create_time)) >= 86400')
- ->all();
- $this->cancelAutoDenied($models);
- }
- protected function cancelOldConfirmedFitting()
- {
- $models = Booking::find()
- ->joinWith(['owner'])
- ->where(['{{%booking}}.status' => BookingStatus::STATUS_FITTING_RESERVED])
- ->andWhere(['>=', '{{%booking}}.id', 7389]) // применяется только к арендам от 01.11.2017
- ->andWhere('{{%booking}}.isup_user_id IS NULL')
- ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking}}.finish_time)) >= ' . self::DAY * 1.5)
- ->all();
- $this->cancelAutoDenied($models);
- }
- protected function cancelAutoDenied($models)
- {
- $current_date = new \DateTime();
- foreach ($models AS $model) {
- /** @var Booking $model */
- if(!$this->isWorkingTime($model->owner, $current_date)){
- continue;
- }
- $status = new BookingStatus();
- $status->status = BookingStatus::STATUS_AUTO_DENIED;
- $status->user_id = $model->getSellerId();
- $status->booking_id = $model->id;
- $status->booking->scenario = Booking::SCENARIO_CHANGE_STATUS_AUTOMATICALLY;
- if ($status->save()) {
- echo "booking {$model->UID} denied\n";
- } else {
- var_dump($status->getErrors());
- }
- }
- }
- protected function cancelNotPayment()
- {
- $current_date = new \DateTime();
- $models = Booking::find()
- ->joinWith(['lastStatus', 'firstAccount', 'owner'])
- ->where(['{{%booking}}.status' => BookingStatus::STATUS_RESERVED])
- ->andWhere(['>=', '{{%booking}}.id', 4430]) //скрипт долгое время не работал из-за ошибки, поэтому отправляем уведомления только самым последним
- ->andWhere(['{{%booking}}.cash_payment' => '0'])
- ->andWhere('{{%booking}}.isup_user_id IS NULL')
- ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking_status}}.create_time)) >= 86400 OR UNIX_TIMESTAMP({{%booking}}.start_time) <= UNIX_TIMESTAMP()')
- ->andWhere('{{%account}}.id IS NULL')
- ->andWhere('{{%booking}}.full_account_id IS NULL')
- ->all();
- foreach ($models AS $model) {
- /** @var Booking $model */
- if(!$this->isWorkingTime($model->owner, $current_date)){
- continue;
- }
- $status = new BookingStatus();
- $status->status = BookingStatus::STATUS_NOT_PAY_CANCEL;
- $status->user_id = $model->getBuyerId();
- $status->booking_id = $model->id;
- if ($status->save()) {
- echo "booking {$model->UID} cancel\n";
- } else {
- var_dump($status->getErrors());
- }
- }
- }
- protected function cancelNotReceived()
- {
- $current_date = new \DateTime();
- /** @var Booking[] $models */
- $models = Booking::find()
- //->joinWith(['owner'])
- ->where(['{{%booking}}.status' => BookingStatus::STATUS_RESERVED])
- //->andWhere(['>=', '{{%booking}}.id', 7389]) // применяется только к арендам от 01.11.2017
- ->andWhere('{{%booking}}.isup_user_id IS NULL')
- ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking}}.start_time)) >= 86400')
- ->andWhere('{{%booking}}.first_account_id IS NULL')
- ->andWhere('{{%booking}}.second_account_id IS NULL')
- ->andWhere('{{%booking}}.full_account_id IS NULL')
- ->andWhere('{{%booking}}.deposit_account_id IS NULL')
- ->all();
- foreach ($models as $model) {
- if(!$this->isWorkingTime($model->owner, $current_date)){
- continue;
- }
- $status = new BookingStatus();
- $status->status = BookingStatus::STATUS_NOT_PAY_CANCEL;
- $status->user_id = $model->getBuyerId();
- $status->booking_id = $model->id;
- if ($status->save()) {
- echo "booking {$model->UID} cancel\n";
- } else {
- var_dump($status->getErrors());
- }
- }
- }
- /**
- * Вроде это дублирует то что внизу
- */
- protected function fittingStartReminder()
- {
- $models = Booking::find()
- ->where(['{{%booking}}.status' => BookingStatus::STATUS_FITTING_RESERVED])
- ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking}}.start_time)) >= 0')
- ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking}}.start_time)) <= 60')
- ->all();
- foreach ($models AS $model) {
- $model->trigger(Booking::EVENT_FITTING);
- }
- $models = Booking::find()
- ->where(['{{%booking}}.status' => BookingStatus::STATUS_FITTING_RESERVED])
- ->andWhere('(UNIX_TIMESTAMP({{%booking}}.start_time) - UNIX_TIMESTAMP()) >= 36000')
- ->andWhere('(UNIX_TIMESTAMP({{%booking}}.start_time) - UNIX_TIMESTAMP()) <= 36060')
- ->all();
- foreach ($models AS $model) {
- $model->trigger(Booking::EVENT_FITTING);
- }
- $models = Booking::find()
- ->where(['{{%booking}}.status' => BookingStatus::STATUS_FITTING_RESERVED])
- ->andWhere('(UNIX_TIMESTAMP({{%booking}}.start_time) - UNIX_TIMESTAMP()) >= 18000')
- ->andWhere('(UNIX_TIMESTAMP({{%booking}}.start_time) - UNIX_TIMESTAMP()) <= 18060')
- ->all();
- foreach ($models AS $model) {
- $model->trigger(Booking::EVENT_FITTING);
- }
- }
- /**
- * А это дублирует то что вверху, оставлю верхний
- */
- // protected function fittingReminder()
- // {
- // $models = Booking::find()
- // ->where(['{{%booking}}.status' => BookingStatus::STATUS_FITTING_RESERVED])
- // ->andWhere('(UNIX_TIMESTAMP({{%booking}}.start_time) - UNIX_TIMESTAMP()) >= 0')
- // ->all();
- //
- // echo "Start fittingReminder\n";
- //
- // foreach ($models AS $model) {
- // $model->trigger(Booking::EVENT_FITTING);
- // }
- //
- // echo "Finish fittingReminder\n";
- // }
- protected function bookingFirstPayReminder()
- {
- $models = Booking::find()
- ->joinWith(['firstAccount', 'lastStatus', 'info'])
- ->where(['{{%booking}}.status' => BookingStatus::STATUS_RESERVED])
- ->andWhere(['{{%booking}}.cash_payment' => '0'])
- ->andWhere(['{{%booking_info}}.first_pay_remind' => '0'])
- ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking_status}}.create_time)) >= 43200')
- ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking_status}}.create_time)) < 43320')
- ->andWhere('{{%account}}.id IS NULL')
- ->all();
- echo "Start bookingFirstPayReminder\n";
- foreach ($models AS $model) {
- $model->info->first_pay_remind = 1;
- $model->info->update(['first_pay_remind']);
- }
- echo "Finish bookingFirstPayReminder\n";
- }
- protected function bookingSecondPayReminder()
- {
- $models = Booking::find()
- ->joinWith(['info'])
- ->where(['{{%booking}}.status' => BookingStatus::STATUS_RESERVED])
- ->andWhere('{{%booking}}.first_account_id IS NOT NULL')
- ->andWhere('{{%booking}}.second_account_id IS NULL')
- ->andWhere(['{{%booking}}.cash_payment' => '0'])
- ->andWhere(['{{%booking_info}}.second_pay_remind' => '0'])
- ->andWhere('(UNIX_TIMESTAMP({{%booking}}.start_time) - UNIX_TIMESTAMP()) >= 259140')
- ->andWhere('(UNIX_TIMESTAMP({{%booking}}.start_time) - UNIX_TIMESTAMP()) < 259260')
- ->all();
- echo "Start bookingSecondPayReminder\n";
- foreach ($models AS $model) {
- $model->info->second_pay_remind = 1;
- $model->info->update(['second_pay_remind']);
- }
- echo "Finish bookingSecondPayReminder\n";
- }
- protected function bookingMeetingReminder()
- {
- $models = Booking::find()
- ->joinWith(['info'])
- ->where(['{{%booking}}.status' => BookingStatus::STATUS_RESERVED])
- ->andWhere(['{{%booking_info}}.meeting_remind' => '0'])
- ->andWhere('(UNIX_TIMESTAMP({{%booking}}.start_time) - UNIX_TIMESTAMP()) >= 28800')
- ->andWhere('(UNIX_TIMESTAMP({{%booking}}.start_time) - UNIX_TIMESTAMP()) < 28920')
- ->all();
- echo "Start bookingMeetingReminder\n";
- foreach ($models AS $model) {
- $model->info->meeting_remind = 1;
- $model->info->update(['meeting_remind']);
- }
- echo "Finish bookingMeetingReminder\n";
- }
- protected function bookingRequestReminder()
- {
- $models = Booking::find()
- ->joinWith(['info'])
- ->where(['{{%booking}}.status' => BookingStatus::STATUS_REQUEST])
- ->andWhere(['{{%booking_info}}.request_remind' => '0'])
- ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking}}.create_time)) >= 3600')
- ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking}}.create_time)) < 3720')
- ->all();
- echo "Start bookingRequestReminder\n";
- foreach ($models AS $model) {
- $model->info->request_remind = 1;
- $model->info->update(['request_remind']);
- }
- echo "Finish bookingRequestReminder\n";
- }
- protected function bookingReturnReminder()
- {
- $models = Booking::find()
- ->joinWith(['info'])
- ->where(['{{%booking}}.status' => BookingStatus::STATUS_RECEIVED_ACCEPTED])
- ->andWhere(['{{%booking_info}}.return_remind' => '0'])
- ->andWhere('(UNIX_TIMESTAMP({{%booking}}.finish_time) - UNIX_TIMESTAMP()) >= 86400')
- ->andWhere('(UNIX_TIMESTAMP({{%booking}}.finish_time) - UNIX_TIMESTAMP()) < 86520')
- ->all();
- echo "Start bookingReturnReminder\n";
- foreach ($models AS $model) {
- $model->info->return_remind = 1;
- $model->info->update(['return_remind']);
- }
- echo "Finish bookingReturnReminder\n";
- }
- protected function bookingMessageReminder()
- {
- $models = Booking::find()
- ->joinWith(['info'])
- ->where(['{{%booking}}.status' => [BookingStatus::STATUS_REQUEST, BookingStatus::STATUS_CREATED]])
- ->andWhere(['{{%booking_info}}.message_remind' => '0'])
- ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking}}.create_time)) >= 3600')
- ->andWhere('(UNIX_TIMESTAMP() - UNIX_TIMESTAMP({{%booking}}.create_time)) < 3720')
- ->all();
- echo "Start bookingMessageReminder\n";
- foreach ($models AS $model) {
- $model->info->message_remind = 1;
- $model->info->update(['message_remind']);
- }
- echo "Finish bookingMessageReminder\n";
- }
- protected function publishReviews()
- {
- $models = BookingReview::find()->leftJoin('{{%booking}}', '{{%booking}}.id = booking_id')->andWhere(['active' => '0'])->andWhere('{{%booking}}.finish_time <= :date' , [
- ':date' => (new \DateTime)->modify('-' . BookingReview::REVIEW_DAYS_TO_PUBLISH . ' day')->format('Y-m-d H:i:s')
- ])->all();
- foreach ($models AS $model) {
- echo "Публикация отзыва ID-{$model->id}\n";
- $model->active = 1;
- $model->save(false);
- }
- }
- protected function sendReviewNotification()
- {
- $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();
- foreach ($models AS $model) {
- if ((time() - strtotime($model->finish_time)) / 86400 >= 2) {
- $model->info->review_notify_count = 2;
- $model->info->save();
- }
- if ((time() - strtotime($model->finish_time)) / 86400 >= 6) {
- $model->info->review_notify_count = 3;
- $model->info->save();
- }
- if ($model->info->isAttributeChanged('review_notify_count') === true) {
- echo "Отправка {$model->info->review_notify_count} уведомления об отзыве для брони UID-{$model->UID}\n";
- $model->save(false);
- }
- }
- }
- protected function isWorkingTime(User $owner, \DateTime $current_date){
- $working_time = $owner->getDatetimeWorktime($current_date);
- if(!is_null($working_time)){
- if(!is_null($working_time->start_time) && $working_time->start_time > $current_date->format('H:i:s')){
- return false;
- }
- if(!is_null($working_time->finish_time) && $working_time->finish_time < $current_date->format('H:i:s')){
- return false;
- }
- }
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement