diff --git a/app/Exceptions/MailjetException.php b/app/Exceptions/MailjetException.php new file mode 100644 index 0000000..a86b7c4 --- /dev/null +++ b/app/Exceptions/MailjetException.php @@ -0,0 +1,32 @@ +returnedMessage = $response->getBody()['ErrorMessage'] ?? $response->getReasonPhrase(); + + parent::__construct( + $message, + $response->getStatus() + ); + } +} diff --git a/app/Http/Controllers/Api/WebhookController.php b/app/Http/Controllers/Api/WebhookController.php index c3e9a06..92c68b2 100644 --- a/app/Http/Controllers/Api/WebhookController.php +++ b/app/Http/Controllers/Api/WebhookController.php @@ -6,31 +6,41 @@ use App\Http\Controllers\Controller; use App\Lib\Helpers\MailjetHelper; use App\Models\Brand; use Illuminate\Http\Request; +use App\Exceptions\MailjetException; class WebhookController extends Controller { /** - * Undocumented function + * Handles incoming Mailjet webhook events * * @param Request $request - * @return void + * @return \Illuminate\Http\JsonResponse */ - public function handleMailjetWebhook(Request $request): void + public function handleMailjetWebhook(Request $request): \Illuminate\Http\JsonResponse { $data = $request->all(); if ($data["event"] === "spam") { - $campaign = MailjetHelper::getCampaign($data["mj_campaign_id"]); - if (!$campaign) { - return; - } + try { + $campaign = MailjetHelper::getCampaign($data['mj_campaign_id']); - $brand = Brand::query()->where('newsletter_email', $campaign['FromEmail'])->first(); - if (!$brand) { - return; - } + if (!$campaign) { + return response()->json(['status' => 'error', 'message' => 'Campaign not found']); + } - MailjetHelper::unsubscribeContact($brand, $data["email"]); - } + $brand = Brand::getBrandByNewsletterEmail($campaign[0]['FromEmail']); + if (!$brand) { + return response()->json(['status' => 'error', 'message' => 'Brand not found']); + } + + MailjetHelper::unsubscribeContact($brand, $data['email']); + + return response()->json(['status' => 'ok']); + } catch (MailjetException $e) { + report($e); + + return response()->json(['status' => 'error', 'message' => $e->returnedMessage]); + } + }//end if } } diff --git a/app/Http/Controllers/Bo/CustomerController.php b/app/Http/Controllers/Bo/CustomerController.php index 72539ee..d5547b2 100644 --- a/app/Http/Controllers/Bo/CustomerController.php +++ b/app/Http/Controllers/Bo/CustomerController.php @@ -25,6 +25,7 @@ use Illuminate\Support\Str; use League\Csv\Writer; use Symfony\Component\HttpFoundation\StreamedResponse; use App\Lib\Helpers\MailjetHelper; +use App\Exceptions\MailjetException; class CustomerController extends Controller { @@ -238,7 +239,7 @@ class CustomerController extends Controller return $this->buildCsvDownloadResponse($response, $w); } - return $this->importToMailjet($request, $w) + return $this->importToMailjet($request, $w); } /** @@ -377,26 +378,31 @@ class CustomerController extends Controller */ private function importToMailjet(CustomerExport $request, Writer $writer): \Illuminate\Http\RedirectResponse { - $brandModel = Brand::find($request->brand); - $contactList = MailjetHelper::createContactList( - sprintf("%s - %s", now()->format('d/m/Y'), $brandModel->name) - ); + $brandModel = Brand::find($request->brand); - if (empty($contactList)) { - return back()->withErrors('Impossible de créer la liste de contacts Mailjet.'); - } + try { + $contactList = MailjetHelper::createContactList( + sprintf("%s - %s", now()->format('d/m/Y'), $brandModel->name) + ); - $mailjetListId = $contactList[0]['ID']; + $mailjetListId = $contactList[0]['ID']; - BrandContactList::create([ - 'brand_id' => $brandModel->getKey(), - 'mailjet_list_id' => $mailjetListId, - ]); + $csvData = MailjetHelper::uploadCsvFile($mailjetListId, $writer->toString()); + MailjetHelper::importContacts($mailjetListId, $csvData['ID']); - $csvData = MailjetHelper::uploadCsvFile($mailjetListId, $writer->toString()); - $importJob = MailjetHelper::importContacts($mailjetListId, $csvData['ID']); + BrandContactList::createBrandContactList( + $brandModel, + $mailjetListId, + ); - return back()->with('success', 'Liste créée et contacts importés avec succès.'); + return back()->with('success', 'Liste créée et contacts importés avec succès.'); + } catch (MailjetException $e) { + report($e); + return back()->withErrors(sprintf( + 'Impossible de créer la liste de contacts Mailjet : %s.', + $e->returnedMessage + )); + }//end try } /** diff --git a/app/Jobs/SyncEmailOptOuts.php b/app/Jobs/SyncEmailOptOuts.php index 2435371..86064e3 100644 --- a/app/Jobs/SyncEmailOptOuts.php +++ b/app/Jobs/SyncEmailOptOuts.php @@ -7,6 +7,7 @@ use App\Models\BrandContactList; use Carbon\Carbon; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; +use App\Exceptions\MailjetException; class SyncEmailOptOuts implements ShouldQueue { @@ -19,25 +20,34 @@ class SyncEmailOptOuts implements ShouldQueue */ public function handle(): void { - $contacts = MailjetHelper::getContactLists(); + try { + $contactLists = MailjetHelper::getContactLists(); - foreach ($contacts as $contact) { - $listId = $contact['ID']; - $brandModel = BrandContactList::query()->where('mailjet_list_id', $listId)->with('brand')->first(); + if (empty($contactLists)) { + return; + } - if ($brandModel) { - $unsubscribedContacts = MailjetHelper::getUnsubscribedContacts($listId, Carbon::now()->subDay()); + foreach ($contactLists as $contactList) { + $listId = $contactList['ID']; + $brandModel = BrandContactList::getBrandContactListByMailjetListId($listId); - if (empty($unsubscribedContacts)) { - continue; - } + if ($brandModel) { + $unsubscribedContacts = MailjetHelper::getUnsubscribedContacts($listId, Carbon::now()->subDay()); - foreach ($unsubscribedContacts as $unsubscribedContact) { - $contact = MailjetHelper::getContact($unsubscribedContact['ContactID']); + if (empty($unsubscribedContacts)) { + continue; + } - MailjetHelper::unsubscribeContact($brandModel->brand, $contact[0]["Email"]); + foreach ($unsubscribedContacts as $unsubscribedContact) { + $contact = MailjetHelper::getContact($unsubscribedContact['ContactID']); + + MailjetHelper::unsubscribeContact($brandModel->brand, $contact[0]["Email"]); + } } } - } + } catch (MailjetException $e) { + report($e); + return; + }//end try } } diff --git a/app/Lib/Helpers/MailjetHelper.php b/app/Lib/Helpers/MailjetHelper.php index e2b4660..2504bd8 100644 --- a/app/Lib/Helpers/MailjetHelper.php +++ b/app/Lib/Helpers/MailjetHelper.php @@ -5,6 +5,8 @@ namespace App\Lib\Helpers; use App\Models\Brand; use App\Models\CustomerInfo; use App\Models\SingleOptin; +use App\Exceptions\MailjetException; +use Illuminate\Support\Facades\Cache; use Mailjet\Resources; class MailjetHelper @@ -14,24 +16,37 @@ class MailjetHelper * * @param integer $campaignId * @return array + * @throws \App\Exceptions\MailjetException If the Mailjet API call fails. */ public static function getCampaign(int $campaignId): array { - $response = app('mailjetClient')->get(Resources::$Campaign, [ - 'id' => $campaignId - ]); + return Cache::remember("mailjet_campaign_{$campaignId}", 86400, function () use ($campaignId) { + $response = app('mailjetClient')->get(Resources::$Campaign, [ + 'id' => $campaignId + ]); - if ($response->success()) { - return $response->getData(); - } else { - return []; - } + if ($response->success()) { + return $response->getData(); + } else { + throw new MailjetException( + $response, + sprintf( + 'Mailjet API Error: Unable to retrieve campaign + (Campaign ID: %d | Error Code: %d | Message: %s)', + $campaignId, + $response->getStatus(), + $response->getBody()['ErrorMessage'] ?? $response->getReasonPhrase() + ), + ); + } + }); } /** * Retrieves contact lists * * @return array + * @throws \App\Exceptions\MailjetException If the Mailjet API call fails. */ public static function getContactLists(): array { @@ -47,7 +62,14 @@ class MailjetHelper if ($response->success()) { return $response->getData(); } else { - return []; + throw new MailjetException( + $response, + sprintf( + 'Mailjet API Error: Unable to retrieve contact lists (Code: %d | Message: %s)', + $response->getStatus(), + $response->getBody()['ErrorMessage'] ?? $response->getReasonPhrase() + ), + ); } } @@ -57,6 +79,7 @@ class MailjetHelper * @param integer $contactListId * @param \Carbon\Carbon|null $lastActivity * @return array + * @throws \App\Exceptions\MailjetException If the Mailjet API call fails. */ public static function getUnsubscribedContacts(int $contactListId, \Carbon\Carbon|null $lastActivity = null): array { @@ -82,7 +105,15 @@ class MailjetHelper if ($response->success()) { return $response->getData(); } else { - return []; + throw new MailjetException( + $response, + sprintf( + 'Mailjet API Error: Unable to retrieve unsubscribed contacts for list %d (Code: %d | Message: %s)', + $contactListId, + $response->getStatus(), + $response->getBody()['ErrorMessage'] ?? $response->getReasonPhrase() + ), + ); } } @@ -91,6 +122,7 @@ class MailjetHelper * * @param integer $contactId * @return array + * @throws \App\Exceptions\MailjetException If the Mailjet API call fails. */ public static function getContact(int $contactId): array { @@ -101,7 +133,15 @@ class MailjetHelper if ($response->success()) { return $response->getData(); } else { - return []; + throw new MailjetException( + $response, + sprintf( + 'Mailjet API Error: Unable to retrieve contact (Contact ID: %d | Error Code: %d | Message: %s)', + $contactId, + $response->getStatus(), + $response->getBody()['ErrorMessage'] ?? $response->getReasonPhrase() + ), + ); } } @@ -110,6 +150,7 @@ class MailjetHelper * * @param string $listName * @return array + * @throws \App\Exceptions\MailjetException If the Mailjet API call fails. */ public static function createContactList(string $listName): array { @@ -122,7 +163,15 @@ class MailjetHelper if ($response->success()) { return $response->getData(); } else { - return []; + throw new MailjetException( + $response, + sprintf( + 'Mailjet API Error: Unable to create contact list (List Name: %s | Error Code: %d | Message: %s)', + $listName, + $response->getStatus(), + $response->getBody()['ErrorMessage'] ?? $response->getReasonPhrase() + ) + ); } } @@ -132,6 +181,7 @@ class MailjetHelper * @param integer $mailjetListId * @param string $csvFile * @return array + * @throws \App\Exceptions\MailjetException If the Mailjet API call fails. */ public static function uploadCsvFile(int $mailjetListId, string $csvFile): array { @@ -143,7 +193,15 @@ class MailjetHelper if ($response->success()) { return $response->getData(); } else { - return []; + throw new MailjetException( + $response, + sprintf( + 'Mailjet API Error: Unable to upload csv file (List ID: %d | Error Code: %d | Message: %s)', + $mailjetListId, + $response->getStatus(), + $response->getBody()['ErrorMessage'] ?? $response->getReasonPhrase() + ) + ); } } @@ -153,6 +211,7 @@ class MailjetHelper * @param integer $listId * @param integer $dataId * @return array + * @throws \App\Exceptions\MailjetException If the Mailjet API call fails. */ public static function importContacts(int $listId, int $dataId): array { @@ -167,7 +226,17 @@ class MailjetHelper if ($response->success()) { return $response->getData(); } else { - return []; + throw new MailjetException( + $response, + sprintf( + 'Mailjet API Error: Unable to import contacts + (List ID: %d | Data ID: %d | Error Code: %d | Message: %s)', + $listId, + $dataId, + $response->getStatus(), + $response->getBody()['ErrorMessage'] ?? $response->getReasonPhrase() + ), + ); } } diff --git a/app/Models/Brand.php b/app/Models/Brand.php index a9e65f9..2d3f89b 100644 --- a/app/Models/Brand.php +++ b/app/Models/Brand.php @@ -144,6 +144,19 @@ class Brand extends Model }); } + /** + * Get brand by newsletter_email. + * + * @param string $newsletter_email + * @return Brand|null + */ + public static function getBrandByNewsletterEmail(string $newsletter_email): ?Brand + { + return Cache::remember("brand_{$newsletter_email}", 86400, function () use ($newsletter_email) { + return self::query()->where('newsletter_email', $newsletter_email)->first(); + }); + } + // * RELATIONS /** diff --git a/app/Models/BrandContactList.php b/app/Models/BrandContactList.php index 8fb7594..e63b610 100644 --- a/app/Models/BrandContactList.php +++ b/app/Models/BrandContactList.php @@ -3,6 +3,7 @@ namespace App\Models; use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Facades\Cache; class BrandContactList extends Model { @@ -16,6 +17,40 @@ class BrandContactList extends Model 'mailjet_list_id', ]; + // * METHODS + + /** + * Create a brand contact list. + * + * @param Brand $brand + * @param integer $mailjetListId + * @return BrandContactList + */ + public static function createBrandContactList(Brand $brand, int $mailjetListId): BrandContactList + { + $brandContactList = self::create([ + 'brand_id' => $brand->getKey(), + 'mailjet_list_id' => $mailjetListId, + ]); + + Cache::put("brand_contact_list_{$mailjetListId}", $brandContactList, 86400); + + return $brandContactList; + } + + /** + * Get brand contact list by mailjet_list_id. + * + * @param integer $mailjetListId + * @return BrandContactList|null + */ + public static function getBrandContactListByMailjetListId(int $mailjetListId): ?BrandContactList + { + return Cache::remember("brand_contact_list_{$mailjetListId}", 86400, function () use ($mailjetListId) { + return self::query()->where('mailjet_list_id', $mailjetListId)->with('brand')->first(); + }); + } + // * RELATIONS /** diff --git a/app/Providers/MailjetServiceProvider.php b/app/Providers/MailjetServiceProvider.php index 681d38f..9e71e17 100644 --- a/app/Providers/MailjetServiceProvider.php +++ b/app/Providers/MailjetServiceProvider.php @@ -17,8 +17,8 @@ class MailjetServiceProvider extends ServiceProvider // Mailjet client to call the API. App::singleton('mailjetClient', function () { $mailjetClient = new \Mailjet\Client( - config('mailjet.public'), - config('mailjet.secret'), + config('services.mailjet.public'), + config('services.mailjet.secret'), true, [ 'version' => 'v3', diff --git a/config/mailjet.php b/config/mailjet.php deleted file mode 100644 index a39ca6d..0000000 --- a/config/mailjet.php +++ /dev/null @@ -1,6 +0,0 @@ - env('MJ_APIKEY_PUBLIC'), - 'secret' => env('MJ_APIKEY_PRIVATE'), -]; diff --git a/config/services.php b/config/services.php index 88b9614..0f3701d 100644 --- a/config/services.php +++ b/config/services.php @@ -31,4 +31,8 @@ return [ 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), ], + 'mailjet' => [ + 'public' => env('MJ_APIKEY_PUBLIC'), + 'secret' => env('MJ_APIKEY_PRIVATE'), + ], ];