SystemNotificationRollBackItemJob.php 1.8 KB
<?php

namespace App\Jobs;

use App\Enums\NotificationStatusEnum;
use App\Helpers\IMHelper;
use App\Models\NotificationUser;
use Illuminate\Bus\Batchable;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Redis;
use Throwable;

class SystemNotificationRollBackItemJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, Batchable;

    public NotificationUser $notificationUser;

    public function __construct(NotificationUser $notificationUser)
    {
        $this->notificationUser = $notificationUser;
        $this->queue            = 'im_rollback';
    }

    /**
     * @throws \Illuminate\Contracts\Redis\LimiterTimeoutException
     */
    public function handle(): void
    {
        if ($this->batch()?->cancelled()) {
            return;
        }


        if (!empty($this->notificationUser->getAttribute('msg_key'))) {
            Redis::throttle('im-rollback')->allow(200)->every(1)->then(function () {
                $this->notificationUser->update(['status' => NotificationStatusEnum::PROCESSING]);
                $result = IMHelper::rollbackChatMessage(IMHelper::SYSTEM_USER, $this->notificationUser->getAttribute('user_id'), $this->notificationUser->getAttribute('msg_key'))->json('ActionStatus');
                $this->notificationUser->update(['status' => $result === 'OK' ? NotificationStatusEnum::ROLLBACK : NotificationStatusEnum::SUCCESS]);
            }, function () {
                $this->release(1);
            });
        }
    }

    public function failed(Throwable $exception): void
    {
        $this->notificationUser->update(['status' => NotificationStatusEnum::SUCCESS]);
    }
}