Merge branch 'develop' into trunk

This commit is contained in:
Jérémy Munsch 2022-10-27 17:36:55 +02:00
commit e0aefec165
No known key found for this signature in database
GPG key ID: 18361AF3BFEC0FEC
19 changed files with 336 additions and 32 deletions

View file

@ -84,8 +84,11 @@ class EggController extends Controller
$inuavs = $eleveurs->pluck('inuavs')->flatten(1);
$mep = CafelEggMiseEnPlace::whereIn('inuav_code', $inuavs)
->where('transfert_date', '<', $datePonte)
$mep = CafelEggMiseEnPlace::query();
collect($inuavs)->map(function ($inuav) use ($mep) {
$mep->where('inuav_codes', 'LIKE', "%{$inuav}%");
});
$mep->where('transfert_date', '<', $datePonte)
->orderBy('transfert_date', 'DESC')->first();
if ($mep) {

View file

@ -5,7 +5,9 @@ namespace App\Jobs;
use App\Exceptions\CafelApiException;
use App\Exceptions\CafelApiImageFetchException;
use App\Lib\CafelApi\Models\CafelEggBreeder as ApiCafelEggBreeder;
use App\Lib\ToolboxHelper;
use App\Models\CafelEggBreeder;
use Illuminate\Validation\ValidationException;
class CafelEggBreederJob extends CafelJobs
{
@ -16,6 +18,16 @@ class CafelEggBreederJob extends CafelJobs
*/
public function handle()
{
// ! We have to remove all breeders to reimport them all in order to make sure
// ! to delete breeders that dont exists anymore (Api fetch constrain)
// ! vu avec Sylvain 27/10/2022
// * Destroy breeder one by one to trigger destroy event
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\CafelEggBreeder> */
$eggBreeders = CafelEggBreeder::all();
$eggBreeders->each(function (CafelEggBreeder $breeder) {
$breeder->deleteOrFail();
});
$this->syncWithCafelApi(
ApiCafelEggBreeder::class,
'cafel.ldc.eleveursoeufs',
@ -41,8 +53,23 @@ class CafelEggBreederJob extends CafelJobs
) : null;
} catch (CafelApiImageFetchException | CafelApiException $e) {
report($e);
$row['path_picture_1'] = null;
}
$validationException = ValidationException::withMessages([
'path_picture_1' => $e->getMessage()
]);
ToolboxHelper::useReflectionToUpdateProperty(
$validationException->validator,
'data',
['path_picture_1' => $row['path_picture_1']]
);
ToolboxHelper::useReflectionToUpdateProperty(
$validationException->validator,
'failedRules',
['path_picture_1' => $e->getMessage()]
);
throw $validationException;
}//end try
try {
$row['path_picture_2'] = !empty($row['path_picture_2']) ?
ApiCafelEggBreeder::fetchPicture(
@ -51,8 +78,23 @@ class CafelEggBreederJob extends CafelJobs
) : null;
} catch (CafelApiImageFetchException | CafelApiException $e) {
report($e);
$row['path_picture_2'] = null;
}
$validationException = ValidationException::withMessages([
'path_picture_2' => $e->getMessage()
]);
ToolboxHelper::useReflectionToUpdateProperty(
$validationException->validator,
'data',
['path_picture_2' => $row['path_picture_2']]
);
ToolboxHelper::useReflectionToUpdateProperty(
$validationException->validator,
'failedRules',
['path_picture_2' => $e->getMessage()]
);
throw $validationException;
}//end try
foreach (['exploitation', 'aboutyou', 'vocation', 'likeinjob', 'loue_means'] as $fieldName) {
$row[$fieldName] = !empty($row[$fieldName]) ? $row[$fieldName] : null;

View file

@ -70,12 +70,24 @@ abstract class CafelJobs implements ShouldQueue
try {
$saveCallback($row);
} catch (ValidationException $e) {
/** @var \Illuminate\Validation\Validator $validator */
$validator = $e->validator;
/** @var array<string,integer|string> */
$failed = $validator->invalid();
$this->invalidRows[] = collect($row)->put('validation_message', collect($e->errors())
->mapWithKeys(function (array $messages, string $attribute) {
return [$attribute => collect($messages)->implode(', ')];
->mapWithKeys(function (array $messages, string $attribute) use ($failed) {
if (!array_key_exists($attribute, $failed)) {
throw new \RuntimeException(
"ValidationException is missing faling data for '{$attribute}'"
);
}
return [
$attribute => collect($messages)->implode(', ') .
' Valeur vérifiée : ' . \json_encode($failed[$attribute])
];
})->implode(' '))->all();
}
}
}//end foreach
} while (!empty($result));
}

View file

@ -23,6 +23,11 @@ class CafelMepEggJob extends CafelJobs
'dateFin' => now()->format('Y-m-d')
],
function (array $row) {
// * Explode inuav
if (\array_key_exists('inuav_codes', $row)) {
$row['inuav_codes'] = explode(',', $row['inuav_codes']);
}
// * Validate row data
CafelMepEgg::validateDataRow($row);

View file

@ -23,6 +23,11 @@ class CafelMepPoultryJob extends CafelJobs
'dateFin' => now()->format('Y-m-d')
],
function (array $row) {
// * Explode inuav
if (\array_key_exists('inuav_codes', $row)) {
$row['inuav_codes'] = explode(',', $row['inuav_codes']);
}
// * Validate row data
CafelMepPoultry::validateDataRow($row);

View file

@ -5,7 +5,9 @@ namespace App\Jobs;
use App\Exceptions\CafelApiException;
use App\Exceptions\CafelApiImageFetchException;
use App\Lib\CafelApi\Models\CafelPoultryBreeder as ApiCafelPoultryBreeder;
use App\Lib\ToolboxHelper;
use App\Models\CafelPoultryBreeder;
use Illuminate\Validation\ValidationException;
class CafelPoultryBreederJob extends CafelJobs
{
@ -16,6 +18,16 @@ class CafelPoultryBreederJob extends CafelJobs
*/
public function handle()
{
// ! We have to remove all breeders to reimport them all in order to make sure
// ! to delete breeders that dont exists anymore (Api fetch constrain)
// ! vu avec Sylvain 27/10/2022
// * Destroy breeder one by one to trigger destroy event
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\CafelEggBreeder> */
$poultryBreeders = CafelPoultryBreeder::all();
$poultryBreeders->each(function (CafelPoultryBreeder $breeder) {
$breeder->deleteOrFail();
});
$this->syncWithCafelApi(
ApiCafelPoultryBreeder::class,
'cafel.ldc.eleveursvolailles',
@ -41,8 +53,23 @@ class CafelPoultryBreederJob extends CafelJobs
) : null;
} catch (CafelApiImageFetchException | CafelApiException $e) {
report($e);
$row['path_picture_1'] = null;
}
$validationException = ValidationException::withMessages([
'path_picture_1' => $e->getMessage()
]);
ToolboxHelper::useReflectionToUpdateProperty(
$validationException->validator,
'data',
['path_picture_1' => $row['path_picture_1']]
);
ToolboxHelper::useReflectionToUpdateProperty(
$validationException->validator,
'failedRules',
['path_picture_1' => $e->getMessage()]
);
throw $validationException;
}//end try
try {
$row['path_picture_2'] = !empty($row['path_picture_2']) ?
ApiCafelPoultryBreeder::fetchPicture(
@ -51,8 +78,23 @@ class CafelPoultryBreederJob extends CafelJobs
) : null;
} catch (CafelApiImageFetchException | CafelApiException $e) {
report($e);
$row['path_picture_2'] = null;
}
$validationException = ValidationException::withMessages([
'path_picture_2' => $e->getMessage()
]);
ToolboxHelper::useReflectionToUpdateProperty(
$validationException->validator,
'data',
['path_picture_2' => $row['path_picture_2']]
);
ToolboxHelper::useReflectionToUpdateProperty(
$validationException->validator,
'failedRules',
['path_picture_2' => $e->getMessage()]
);
throw $validationException;
}//end try
foreach (['issue_1', 'issue_2'] as $fieldName) {
$row[$fieldName] = !empty($row[$fieldName]) ? $row[$fieldName] : null;

View file

@ -17,7 +17,7 @@ abstract class CafelEggBreeder extends CafelClientModel
* @var array
*/
public const UNIQUE_COLUMN_KEYS = [
'cafel_code'
'cafel_code', 'ede_code'
];
/**
@ -43,7 +43,7 @@ abstract class CafelEggBreeder extends CafelClientModel
* 2 chiffres qui représentent le numéro d’ordre de chaque atelier dans une même exploitation
* eg : 1FRZFC01
*/
'ede_code' => 'required|regex:/[0-3][A-Z]{5}\d\d/',
'ede_code' => 'required|regex:/^[0-3][A-Z]{5}\d\d$/',
// Valeurs possibles pour civility : 1 M, 2 MME, 3 EUX, 4 ELLES .
'civility' => ['required', [EnumIsValidRule::class, BreederCivilty::class]],
'lastname' => 'required|string|min:1|max:255',

View file

@ -22,8 +22,10 @@ abstract class CafelMepEgg extends CafelClientModel
* @var array
*/
protected static $validationRules = [
// Eg V072FXT (un seul ou plusieurs separe par une virgule).
'inuav_codes' => 'required|array',
// Eg V072FXT (un seul par ligne).
'inuav_code' => 'required|string|regex:/^[A-Z]\d{3}[A-Z]{3}$/',
'inuav_codes.*' => 'required|string|regex:/^[A-Z]\d{3}[A-Z]{3}$/',
// Eg 19377/0 .
'batch_code' => [
'required',
@ -39,7 +41,7 @@ abstract class CafelMepEgg extends CafelClientModel
* @var array
*/
protected static $columnsTranslations = [
'Inuav_code' => 'inuav_code',
'Inuav_code' => 'inuav_codes',
'Batch_code' => 'batch_code',
'Transfert_date' => 'transfert_date'
];

View file

@ -22,8 +22,10 @@ abstract class CafelMepPoultry extends CafelClientModel
* @var array
*/
protected static $validationRules = [
// Eg V072FXT (un seul ou plusieurs separe par une virgule).
'inuav_codes' => 'required|array',
// Eg V072FXT (un seul par ligne).
'inuav_code' => 'required|string|regex:/^[A-Z]\d{3}[A-Z]{3}$/',
'inuav_codes.*' => 'required|string|regex:/^[A-Z]\d{3}[A-Z]{3}$/',
// Eg 19377/0 .
'batch_code' => [
'required',
@ -39,7 +41,7 @@ abstract class CafelMepPoultry extends CafelClientModel
* @var array
*/
protected static $columnsTranslations = [
'Inuav_code' => 'inuav_code',
'Inuav_code' => 'inuav_codes',
'Batch_code' => 'batch_code',
'Transfert_date' => 'transfert_date'
];

View file

@ -105,7 +105,7 @@ class ApiInterface
*
* @param \App\Lib\CafelApi\Transport\Request $request
* @return \App\Lib\CafelApi\Transport\Response
* @throws \App\Exceptions\CafelApiException If reponse status is KO.
* @throws \App\Exceptions\CafelApiException If reponse status is KO or not Json.
*/
public function call(Request $request): Response
{
@ -122,8 +122,9 @@ class ApiInterface
/**
* Process request
*
* @param Request $request
* @return Response
* @param \App\Lib\CafelApi\Transport\Request $request
* @return \App\Lib\CafelApi\Transport\Response
* @throws \App\Exceptions\CafelApiException If HTTP response body in not JSON.
*/
private function processRequest(Request $request): Response
{
@ -136,13 +137,13 @@ class ApiInterface
$status = in_array($response->getStatusCode(), [200, 201]) ?
ApiStatus::OK() : ApiStatus::KO();
return new Response($status, $response);
return new Response($status, $response, $request);
}
/**
* Add spécific headers to the request
*
* @param Request $request
* @param \App\Lib\CafelApi\Transport\Request $request
* @return void
*/
private function setHeaders(Request &$request): void

View file

@ -56,9 +56,10 @@ class Response
*
* @param \App\Enums\ApiStatus $status
* @param \Psr\Http\Message\ResponseInterface $response
* @param \App\Lib\CafelApi\Transport\Request $request
* @throws \App\Exceptions\CafelApiException If HTTP response body in not JSON.
*/
public function __construct(ApiStatus $status, ResponseInterface $response)
public function __construct(ApiStatus $status, ResponseInterface $response, Request $request)
{
$this->response = $response;
$this->status = $status;
@ -74,9 +75,18 @@ class Response
// * Body should be json data.
if (($decodedJson = $this->tryDecodeJson($this->body->getContents())) === false) {
if (in_array(config('app.env'), ['testing', 'local'])) {
dump((string)$this->body);
dump(
'should have been json',
$this->httpCode,
$this->status,
$this->headers,
$request->uri,
(string)$this->body
);
}
throw new CafelApiException('The Api should have returned JSON data');
throw new CafelApiException(
"The Api should have returned JSON data '{$request->uri}'"
);
}
$this->body = $decodedJson;

View file

@ -12,6 +12,23 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
abstract class ToolboxHelper
{
/**
* Update any prop using reflexion
*
* @param object $object
* @param string $property
* @param mixed $value
* @return void
* @throws \ReflectionException If the class or property does not exist.
*/
public static function useReflectionToUpdateProperty(object &$object, string $property, $value)
{
$refProperty = new \ReflectionProperty(\get_class($object), $property);
$refProperty->setAccessible(true);
$refProperty->setValue($object, $value);
$refProperty->setAccessible(false);
}
/**
* Store an image of different types
*

View file

@ -5,6 +5,8 @@ namespace App\Models;
use App\Enums\BreederCivilty;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Kwaadpepper\Enum\Traits\CastsEnums;
@ -98,6 +100,7 @@ class CafelEggBreeder extends Model
// * EVENT CLOSURES.
static::creating(function (self $model) {
return self::areInuavCodesUniques($model);
return self::isEdeCodeUnique($model);
});
static::updating(function (self $model) {
if ($model->getRawOriginal('path_picture_1') !== $model->path_picture_1) {
@ -107,6 +110,15 @@ class CafelEggBreeder extends Model
Storage::delete(\public_path($model->getRawOriginal('path_picture_2')));
}
return self::areInuavCodesUniques($model);
return self::isEdeCodeUnique($model);
});
static::deleting(function (self $model) {
if ($model->getRawOriginal('path_picture_1')) {
Storage::delete(\public_path($model->getRawOriginal('path_picture_1')));
}
if ($model->getRawOriginal('path_picture_2')) {
Storage::delete(\public_path($model->getRawOriginal('path_picture_2')));
}
});
}
@ -160,4 +172,21 @@ class CafelEggBreeder extends Model
}
return true;
}
/**
* Check if ede code is unique
*
* @param self $breeder
* @return boolean
* @throws \Illuminate\Validation\ValidationException If ede code is already used.
*/
protected static function isEdeCodeUnique(self $breeder): bool
{
Validator::make([
'ede_code' => $breeder->ede_code
], ['ede_code' => [
Rule::unique($breeder->getTable(), 'ede_code')->ignore($breeder->id)
]])->validate();
return true;
}
}

View file

@ -33,7 +33,8 @@ class CafelEggMiseEnPlace extends Model
* @var array
*/
protected $casts = [
'transfert_date' => 'date'
'transfert_date' => 'date',
'inuav_codes' => 'array'
];
/**
@ -43,7 +44,7 @@ class CafelEggMiseEnPlace extends Model
*/
protected $fillable = [
'batch_code',
'inuav_code',
'inuav_codes',
'transfert_date'
];
}

View file

@ -94,6 +94,14 @@ class CafelPoultryBreeder extends Model
}
return self::areInuavCodesUniques($model);
});
static::deleting(function (self $model) {
if ($model->getRawOriginal('path_picture_1')) {
Storage::delete(\public_path($model->getRawOriginal('path_picture_1')));
}
if ($model->getRawOriginal('path_picture_2')) {
Storage::delete(\public_path($model->getRawOriginal('path_picture_2')));
}
});
}
// * METHODS

View file

@ -34,7 +34,8 @@ class CafelPoultryMiseEnPlace extends Model
* @var array
*/
protected $casts = [
'transfert_date' => 'date'
'transfert_date' => 'date',
'inuav_codes' => 'array'
];
/**
@ -44,7 +45,7 @@ class CafelPoultryMiseEnPlace extends Model
*/
protected $fillable = [
'batch_code',
'inuav_code',
'inuav_codes',
'transfert_date'
];

View file

@ -1,8 +1,9 @@
<?php
return [
// ! Food et MEp sont requis pour afficher un resultat traca volaille
// * How many days should we retain Aliment
'food_retain' => 30,
'food_retain' => 370,
// * How many days should we retain MEP (egg)
'mises_en_places_retain' => 370,
'client_version' => '1.0',

View file

@ -0,0 +1,42 @@
<?php
use App\Models\CafelEggBreeder;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
class AddUniqueOnEdeEggBreeders extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// * Destroy breeder one by one to trigger destroy event
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\CafelEggBreeder> */
$eggBreeders = CafelEggBreeder::all();
$eggBreeders->each(function (CafelEggBreeder $breeder) {
$breeder->deleteOrFail();
});
Schema::table('cafel_egg_breeders', function (Blueprint $table) {
$table->unique(['ede_code']);
});
Log::alert('Please reimport all egg breeders');
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('cafel_egg_breeders', function (Blueprint $table) {
$table->dropUnique(['ede_code']);
});
}
}

View file

@ -0,0 +1,81 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class MakeMisesEnPlaceHandleMultipleInuav extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('cafel_egg_mise_en_places', function (Blueprint $table) {
$table->renameColumn('inuav_code', 'inuav_codes');
});
Schema::table('cafel_poultry_mise_en_places', function (Blueprint $table) {
$table->renameColumn('inuav_code', 'inuav_codes');
});
Schema::table('cafel_egg_mise_en_places', function (Blueprint $table) {
$table->string('inuav_codes', 400)->change();
});
Schema::table('cafel_poultry_mise_en_places', function (Blueprint $table) {
$table->string('inuav_codes', 400)->change();
});
DB::table('cafel_egg_mise_en_places')->get()
->each(function (object $eggMep) {
DB::table('cafel_egg_mise_en_places')
->where('batch_code', $eggMep->batch_code)
->update(['inuav_codes' => collect(
explode(',', $eggMep->inuav_codes)
)->filter()->jsonSerialize()]);
});
DB::table('cafel_poultry_mise_en_places')->get()
->each(function (object $poultryMep) {
DB::table('cafel_poultry_mise_en_places')
->where('batch_code', $poultryMep->batch_code)
->update(['inuav_codes' => collect(
explode(',', $poultryMep->inuav_codes)
)->filter()->jsonSerialize()]);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::table('cafel_egg_mise_en_places')->get()
->each(function (object $eggMep) {
DB::table('cafel_egg_mise_en_places')
->where('batch_code', $eggMep->batch_code)
->update(['inuav_codes' => collect(json_decode($eggMep->inuav_codes))->filter()
->first()]);
});
DB::table('cafel_poultry_mise_en_places')->get()
->each(function (object $poultryMep) {
DB::table('cafel_poultry_mise_en_places')
->where('batch_code', $poultryMep->batch_code)
->update(['inuav_codes' => collect(json_decode($poultryMep->inuav_codes))->filter()
->first()]);
});
Schema::table('cafel_egg_mise_en_places', function (Blueprint $table) {
$table->string('inuav_codes', 100)->change();
});
Schema::table('cafel_poultry_mise_en_places', function (Blueprint $table) {
$table->string('inuav_codes', 100)->change();
});
Schema::table('cafel_egg_mise_en_places', function (Blueprint $table) {
$table->renameColumn('inuav_codes', 'inuav_code');
});
Schema::table('cafel_poultry_mise_en_places', function (Blueprint $table) {
$table->renameColumn('inuav_codes', 'inuav_code');
});
}
}