ldc-crm/app/Jobs/SyncEmailOptOuts.php

61 lines
2.2 KiB
PHP

<?php
namespace App\Jobs;
use App\Lib\Helpers\MailjetHelper;
use App\Models\BrandContactList;
use App\Models\CustomerInfo;
use App\Models\SingleOptin;
use Carbon\Carbon;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
class SyncEmailOptOuts implements ShouldQueue
{
use Queueable;
/**
* Execute the job.
*/
public function handle(): void
{
$contacts = MailjetHelper::getContactLists();
foreach ($contacts as $contact) {
$listId = $contact['ID'];
$brandModel = BrandContactList::query()->where('mailjet_list_id', $listId)->with('brand')->first();
if ($brandModel) {
$unsubscribedContacts = MailjetHelper::getUnsubscribedContacts($listId, Carbon::now()->subDay());
if (empty($unsubscribedContacts)) {
continue;
}
foreach ($unsubscribedContacts as $unsubscribedContact) {
$contact = MailjetHelper::getContact($unsubscribedContact['ContactID']);
$crmCustomer = CustomerInfo::getFromEmail($brandModel->brand, $contact[0]["Email"])->first();
if ($crmCustomer) {
$crmCustomer->opt_in = false;
if (!$crmCustomer->saveOrFail()) {
throw new \Exception(sprintf('Optin status not changed for customer (%s) and brand (%d).', $crmCustomer->hashcode, $brandModel->brand->name));
}
} else {
$singleOptin = SingleOptin::query()->where('email', $contact[0]['Email'])
->whereHas('brand', function ($q) use ($brandModel) {
$q->whereId($brandModel->brand->getKey());
})->first();
if ($singleOptin) {
if (!$singleOptin->delete()) {
throw new \Exception(sprintf('SingleOptin (%s) not deleted for brand (%d).', $singleOptin->hashcode, $brandModel->brand->name));
}
}
}
}
}
}
}
}