ldc-mesbr-app/app/Jobs/DeleteCrmCustomerJob.php

108 lines
2.6 KiB
PHP

<?php
namespace App\Jobs;
use App\Models\Contact;
use App\Models\Customers;
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\DB;
use Illuminate\Support\Facades\Log;
class DeleteCrmCustomerJob implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/**
* @var array $customer
*/
private $customer;
/**
* Create a new job instance.
*
* @param array $customer
*/
public function __construct($customer)
{
$this->onConnection('rabbitmq');
$this->customer = $customer;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$hashchode = $this->customer['hashcode'];
$email = $this->customer['email'];
try {
DB::transaction(function () use ($hashchode, $email) {
// For baskets and old walls.
$contact = Contact::query()->where('contact_ref', $hashchode)->first();
if ($contact) {
$contact->deleteOrFail();
$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(
"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);
}
$logFile = fopen($csvPath, 'a');
\fputcsv(
$logFile,
[
\now()->toAtomString(),
$this->customer['hashcode'],
$this->customer['email'],
$message
],
';'
);
\fclose($logFile);
}
}