diff --git a/app/Jobs/DeleteCrmCustomerJob.php b/app/Jobs/DeleteCrmCustomerJob.php index b342131..0729dec 100644 --- a/app/Jobs/DeleteCrmCustomerJob.php +++ b/app/Jobs/DeleteCrmCustomerJob.php @@ -9,6 +9,7 @@ use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; class DeleteCrmCustomerJob implements ShouldQueue @@ -44,36 +45,64 @@ class DeleteCrmCustomerJob implements ShouldQueue $hashchode = $this->customer['hashcode']; $email = $this->customer['email']; - // For baskets and old walls. - $contact = Contact::where('contact_ref', $hashchode)->first(); - if ($contact) { - $contact->murs()->delete(); - $contact->paniers()->delete(); - $contact->logs()->delete(); - $contact->delete(); + try { + DB::transaction(function () use ($hashchode, $email) { + // For baskets and old walls. + $contact = Contact::query()->where('contact_ref', $hashchode)->first(); + if ($contact) { + $contact->deleteOrFail(); - Log::channel('crm')->info( + $this->writeCsvLog('Contact deleted'); + } + + // For walls. + $customer = Customers::query()->where('hashcode', $hashchode)->first(); + if ($customer) { + $customer->deleteOrFail(); + + $this->writeCsvLog('Customer deleted'); + } + }); + } catch (\Exception $e) { + Log::info( sprintf( - "Hashcode : %s - Email : %s - Contact deleted.", - $hashchode, - $email + "DeleteCrmCustomerJob failed - Code : %s - %s", + $e->getCode(), + $e->getMessage(), ) ); + \report($e); + } //end try + } + + /** + * Write logs in /logs/crm.csv. + * + * @param string $message + * + * @return void + */ + private function writeCsvLog(string $message) + { + + $csvPath = \storage_path('/logs/crm.csv'); + if (!\file_exists($csvPath)) { + $logFile = fopen($csvPath, 'w'); + \fputcsv($logFile, ['date', 'hashcode', 'email', 'action'], ';'); + \fclose($logFile); } - // For walls. - $customer = Customers::where('hashcode', $hashchode)->first(); - if ($customer) { - $customer->printedWalls()->delete(); - $customer->delete(); - - Log::channel('crm')->info( - sprintf( - "Hashcode : %s - Email : %s - Customer deleted.", - $hashchode, - $email - ) - ); - } + $logFile = fopen($csvPath, 'a'); + \fputcsv( + $logFile, + [ + \now()->toAtomString(), + $this->customer['hashcode'], + $this->customer['email'], + $message + ], + ';' + ); + \fclose($logFile); } }