Merge branch 'develop' into trunk

This commit is contained in:
Vincent BRIDIER 2022-07-11 10:05:22 +02:00
commit c13ef55eee
No known key found for this signature in database
GPG key ID: 8571BFA20420D512
561 changed files with 23683 additions and 20900 deletions

View file

@ -28,4 +28,13 @@ MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=
MAIL_FROM_NAME=
MAIL_HANDLER=
# CAFEL API CREDS
CAFEL_ENDPOINT=
CAFEL_USER=
CAFEL_PASSWORD=
MAIL_INVALID_CAFEL_DATA=equipe.web@ldc.fr
MAIL_INVALID_CAFEL_DATA_IMAGE=equipe.web@ldc.fr
MAIL_INVALID_XML=equipe.web@ldc.fr
MAIL_LIST_SERVICEWEB=equipe.web@ldc.fr

7
.gitignore vendored
View file

@ -2,6 +2,13 @@
/public/hot
/public/storage
/public/images
/public/assets
/public/css
/public/js
/public/mix-manifest.json
/public/loue
/resources/flux_in
storage
/vendor
.idea/
.env

48
.vscode/launch.json vendored Normal file
View file

@ -0,0 +1,48 @@
{
// Utilisez IntelliSense pour en savoir plus sur les attributs possibles.
// Pointez pour afficher la description des attributs existants.
// Pour plus d'informations, visitez : https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Listen for Xdebug",
"type": "php",
"request": "launch",
"port": 9000
},
{
"name": "Launch currently open script",
"type": "php",
"request": "launch",
"program": "${file}",
"cwd": "${fileDirname}",
"port": 0,
"runtimeArgs": [
"-dxdebug.start_with_request=yes"
],
"env": {
"XDEBUG_MODE": "debug,develop",
"XDEBUG_CONFIG": "client_port=${port}"
}
},
{
"name": "Launch Built-in web server",
"type": "php",
"request": "launch",
"runtimeArgs": [
"-dxdebug.mode=debug",
"-dxdebug.start_with_request=yes",
"-S",
"localhost:0"
],
"program": "",
"cwd": "${workspaceRoot}",
"port": 9003,
"serverReadyAction": {
"pattern": "Development Server \\(http://localhost:([0-9]+)\\) started",
"uriFormat": "http://localhost:%s",
"action": "openExternally"
}
}
]
}

22
.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,22 @@
{
"workbench.colorCustomizations": {
"activityBar.activeBackground": "#03837e",
"activityBar.activeBorder": "#f782fc",
"activityBar.background": "#03837e",
"activityBar.foreground": "#e7e7e7",
"activityBar.inactiveForeground": "#e7e7e799",
"activityBarBadge.background": "#f782fc",
"activityBarBadge.foreground": "#15202b",
"sash.hoverBorder": "#03837e",
"statusBar.background": "#02514e",
"statusBar.foreground": "#e7e7e7",
"statusBarItem.hoverBackground": "#03837e",
"statusBarItem.remoteBackground": "#02514e",
"statusBarItem.remoteForeground": "#e7e7e7",
"titleBar.activeBackground": "#02514e",
"titleBar.activeForeground": "#e7e7e7",
"titleBar.inactiveBackground": "#02514e99",
"titleBar.inactiveForeground": "#e7e7e799"
},
"peacock.remoteColor": "#02514e"
}

128
README.md
View file

@ -1,78 +1,62 @@
<p align="center"><img src="https://res.cloudinary.com/dtfbvvkyp/image/upload/v1566331377/laravel-logolockup-cmyk-red.svg" width="400"></p>
# BOGT / Tracabilité Loué
<p align="center">
<a href="https://travis-ci.org/laravel/framework"><img src="https://travis-ci.org/laravel/framework.svg" alt="Build Status"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/d/total.svg" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/v/stable.svg" alt="Latest Stable Version"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/license.svg" alt="License"></a>
</p>
## Installation
```
composer install
cp .env.example .env
php artisan key:generate
php artisan storage:link
```
## About Laravel
Éditez le fichier .env puis :
```
php artisan migrate
```
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
Front :
```
npm install && npm run prod
```
Pour créer un compte admin :
```
php artisan user:create
```
- [Simple, fast routing engine](https://laravel.com/docs/routing).
- [Powerful dependency injection container](https://laravel.com/docs/container).
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
- [Robust background job processing](https://laravel.com/docs/queues).
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
## Commande à mettre dans la crontab toutes les minutes en PROD
```
php artisan schedule:run
```
Laravel is accessible, powerful, and provides tools required for large, robust applications.
## Données
Pour synchroniser les aliments :
```
php artisan cafel:food
```
Pour synchroniser les données BEA (volaille) :
```
php artisan cafel:bea_vol
```
Pour synchroniser les mises en place (oeuf) :
```
php artisan cafel:mep_egg
```
Pour synchroniser les éleveurs (oeuf) :
```
php artisan cafel:breeder_egg
```
Pour synchroniser les éleveurs (volaille) :
```
php artisan cafel:breeder_poultry
```
Pour importer les XML (oeuf) :
```
php artisan xml:egg
```
Pour importer les XML (volaille) :
```
php artisan xml:poultry
```
## Learning Laravel
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework.
If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains over 1500 video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
## Laravel Sponsors
We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the Laravel [Patreon page](https://patreon.com/taylorotwell).
- **[Vehikl](https://vehikl.com/)**
- **[Tighten Co.](https://tighten.co)**
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
- **[64 Robots](https://64robots.com)**
- **[Cubet Techno Labs](https://cubettech.com)**
- **[Cyber-Duck](https://cyber-duck.co.uk)**
- **[British Software Development](https://www.britishsoftware.co)**
- **[Webdock, Fast VPS Hosting](https://www.webdock.io/en)**
- **[DevSquad](https://devsquad.com)**
- [UserInsights](https://userinsights.com)
- [Fragrantica](https://www.fragrantica.com)
- [SOFTonSOFA](https://softonsofa.com/)
- [User10](https://user10.com)
- [Soumettre.fr](https://soumettre.fr/)
- [CodeBrisk](https://codebrisk.com)
- [1Forge](https://1forge.com)
- [TECPRESSO](https://tecpresso.co.jp/)
- [Runtime Converter](http://runtimeconverter.com/)
- [WebL'Agence](https://weblagence.com/)
- [Invoice Ninja](https://www.invoiceninja.com)
- [iMi digital](https://www.imi-digital.de/)
- [Earthlink](https://www.earthlink.ro/)
- [Steadfast Collective](https://steadfastcollective.com/)
- [We Are The Robots Inc.](https://watr.mx/)
- [Understand.io](https://www.understand.io/)
- [Abdel Elrafa](https://abdelelrafa.com)
- [Hyper Host](https://hyper.host)
- [Appoly](https://www.appoly.co.uk)
- [OP.GG](https://op.gg)
## Contributing
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
## Code of Conduct
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
## Security Vulnerabilities
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.
## License
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).
## TODO
- Mettre analytics dans cookie notice
- Cacher la colonne Code EDE dans le cas du filtrage sur volaille (/bo/eleveurs)

View file

@ -1,14 +0,0 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Aliments extends Model
{
public $timestamps = false;
/**
* @var string
*/
protected $table = 'aliments';
}

View file

@ -0,0 +1,38 @@
<?php
namespace App\Console\Commands;
use App\Jobs\CafelBeaVolJob;
use Illuminate\Console\Command;
class CafelBeaVolCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'cafel:bea_vol';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Syncronisation manuelle Cafel (/api/ldc/beavolailles)';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->info('Running the Job, this could take some time.');
$job = new CafelBeaVolJob();
$job->handle();
$this->info('Fin du traitement');
}
}

View file

@ -0,0 +1,38 @@
<?php
namespace App\Console\Commands;
use App\Jobs\CafelEggBreederJob;
use Illuminate\Console\Command;
class CafelEggBreederCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'cafel:breeder_egg';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Syncronisation manuelle Cafel (/api/ldc/eleveursoeufs)';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->info('Running the Job, this could take some time.');
$job = new CafelEggBreederJob();
$job->handle();
$this->info('Fin du traitement');
}
}

View file

@ -0,0 +1,38 @@
<?php
namespace App\Console\Commands;
use App\Jobs\CafelMepEggJob;
use Illuminate\Console\Command;
class CafelEggMepCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'cafel:mep_egg';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Syncronisation manuelle Cafel (/api/ldc/mepoeufs)';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->info('Running the Job, this could take some time.');
$job = new CafelMepEggJob();
$job->handle();
$this->info('Fin du traitement');
}
}

View file

@ -0,0 +1,38 @@
<?php
namespace App\Console\Commands;
use App\Jobs\CafelFoodJob;
use Illuminate\Console\Command;
class CafelFoodCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'cafel:food';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Syncronisation manuelle Cafel (/api/ldc/aliments)';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->info('Running the Job, this could take some time.');
$job = new CafelFoodJob();
$job->handle();
$this->info('Fin du traitement');
}
}

View file

@ -0,0 +1,38 @@
<?php
namespace App\Console\Commands;
use App\Jobs\CafelPoultryBreederJob;
use Illuminate\Console\Command;
class CafelPoultryBreederCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'cafel:breeder_poultry';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Syncronisation manuelle Cafel (/api/ldc/eleveurvolailles)';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->info('Running the Job, this could take some time.');
$job = new CafelPoultryBreederJob();
$job->handle();
$this->info('Fin du traitement');
}
}

View file

@ -0,0 +1,106 @@
<?php
namespace App\Console\Commands;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
/**
* Creates a new user
*/
class CreateUser extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'user:create';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a backend admin user';
/**
* Execute the console command.
*
* @return integer
*/
public function handle()
{
$username = null;
while (is_null($username)) {
try {
$tmp = $this->ask('Type the wanted user username', 'admweb');
$validator = Validator::make(['username' => $tmp], [
'username' => 'required|min:5,max:255|unique:users,username'
]);
$validator->validate();
$username = $tmp;
} catch (ValidationException $e) {
$this->error(sprintf(
'Please provide a valid username %s',
\implode(',', collect($e->errors())->flatten()->all())
));
continue;
}
}
$email = null;
while (is_null($email)) {
try {
$tmp = $this->ask('Type the wanted user email', 'equipe.web@ldc.fr');
$validator = Validator::make(['email' => $tmp], [
'email' => 'required|unique:users,email|email:rfc,dns'
]);
$validator->validate();
$email = $tmp;
} catch (ValidationException $e) {
$this->error(sprintf(
'Please provide a valid email %s',
\implode(',', collect($e->errors())->flatten()->all())
));
continue;
}
}
$name = null;
while (is_null($name)) {
try {
$tmp = $this->ask('Type the wanted user name', 'Saïtama');
$validator = Validator::make(['name' => $tmp], [
'name' => 'required|min:5,max:255'
]);
$validator->validate();
$name = $tmp;
} catch (ValidationException $e) {
$this->error(sprintf(
'Please provide a valid name %s',
\implode(',', collect($e->errors())->flatten()->all())
));
continue;
}
}
$password = $this->secret('Type the wanted user password');
$admin = new User([
'name' => $name,
'email' => $email,
'password' => $password
]);
$admin->username = $username;
$admin->email_verified_at = Carbon::now();
$admin->saveOrFail();
$this->info('User created.');
return 0;
}
}

View file

@ -1,104 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Moba;
use Carbon\Carbon;
class ImportMoba extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'import:moba';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Import des CSV MOBA';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
setlocale(LC_CTYPE, 'en_US.utf8');
$path = base_path("resources/flux_in/*.csv");
$logpath = base_path("resources/flux_in/log/log.txt");
$logs = fopen($logpath, 'a+');
foreach (glob($path) as $file) {
$flag = true;
$lines = 0;
$filename = substr($file, -14);
$year = substr($filename, 0, 4);
$month = substr($filename, 5, 2);
$day = substr($filename, 8, 2);
$date_emballage_array = Carbon::createFromFormat('Y-m-d', $year . '-' . $month . '-' . $day)->subDay()->toArray();
$date_emballage = $date_emballage_array['year'] . '-' . $date_emballage_array['month'] . '-' . $date_emballage_array['day'];
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 50000, ";", '"')) !== FALSE) {
if ($flag) {
$flag = false;
continue;
}
$code_boite = $data[0];
$code_ede = $data[1];
//format dans le fichier Y-m-d
$date_ponte = $data[2];
$code_produit = $data[3];
$libelle_produit = $data[4];
$lot_externe = $data[5];
//format dans le fichier Y-m-d
$dcr = $data[6];
$ean = $data[7];
$moba = new Moba();
$moba->code_boite = $code_boite;
$moba->code_ede = $code_ede;
$moba->date_ponte = $date_ponte;
$moba->code_produit = $code_produit;
$moba->libelle_produit = $libelle_produit;
$moba->lot_externe = $lot_externe;
$moba->dcr = $dcr;
$moba->date_emballage = $date_emballage;
$moba->ean13 = $ean;
$moba->save();
$lines++;
}
}
fclose($handle);
$logtxt = $file . " : " . $lines . " lignes insérées" . PHP_EOL;
fwrite($logs, $logtxt);
//scopy($file, 'archives/'.$file);
unlink($file);
//il n'y a plus de fichier .ok apparement
@unlink($file . '.ok');
}
fclose($logs);
return 0;
}
}

View file

@ -1,15 +1,17 @@
<?php
/*
* Command Name: LDC Web Status Checker
* Description: Envoi des infos Serveur/Laravel vers LDC Web
* Version: 1.0
* Author: Vincent BRIDIER
* Author URI: vincent.bridier@ldc.fr
*/
namespace App\Console\Commands;
/*
* Command Name: LDC Web Status Checker
* Description: Envoi des infos Serveur/Laravel vers LDC Web
* Version: 1.0
* Author: Vincent BRIDIER
* Author URI: vincent.bridier@ldc.fr
*/
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
class LDCWebStatusChecker extends Command
{
@ -27,16 +29,6 @@ class LDCWebStatusChecker extends Command
*/
protected $description = 'Envoi des infos Serveur/Laravel vers LDC Web';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
@ -44,7 +36,7 @@ class LDCWebStatusChecker extends Command
*/
public function handle()
{
$data = [];
$data = [];
$data['uuid'] = config('app.project_uuid');
// Sitemap.xml ?
@ -61,10 +53,10 @@ class LDCWebStatusChecker extends Command
$data['robots'] = 'false';
}
//Check logs
// Check logs .
$data['logs'] = 0;
$patherror = storage_path('/logs');
$files = glob($patherror . '/laravel-*.log');
$patherror = storage_path('/logs');
$files = glob($patherror . '/laravel-*.log');
if (count($files) > 0) {
foreach ($files as $file) {
$data['logs'] = $data['logs'] + filesize($file);
@ -73,14 +65,14 @@ class LDCWebStatusChecker extends Command
$data['code']['version'] = app()->version();
// Send by cURL
$url = 'https://ldc-web.ldc.fr/api/status-checker';
$ch = curl_init($url);
$payload = ['token' => 'CE8S52Qq7stf5k8frF4T', 'datas' => json_encode($data)];
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
try {
Http::post(
'https://ldc-web.s-web.test/api/status-checker',
['token' => 'CE8S52Qq7stf5k8frF4T', 'datas' => json_encode($data)]
);
} catch (\Exception $e) {
report($e);
}
return 0;
}

View file

@ -1,66 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Moba;
class MajEleveurs extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'maj:moba';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
setlocale(LC_CTYPE, 'en_US.utf8');
$path = base_path("resources/flux_in/maj/*.csv");
foreach (glob($path) as $file) {
$flag = true;
$line = 0;
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 50000, ";", '"')) !== FALSE) {
if ($flag) {
$flag = false;
continue;
}
$line++;
$code_boite = $data[0];
$ean13 = $data[7];
$mobas = Moba::where('code_boite', '=', $code_boite)->andWhere('ean13', '=', '')->update(['ean13' => $data[7]]);
echo $line . "\n\r";
}
}
}
return 0;
}
}

View file

@ -0,0 +1,36 @@
<?php
namespace App\Console\Commands;
use App\Jobs\Arcadia\RemoveOldXmlEntries;
use Illuminate\Console\Command;
class RemoveOldXmlEntriesCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'xml:clean_olds';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Run the RemoveOldXmlEntries manually';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->info('Running the Job, this could take some time.');
$job = new RemoveOldXmlEntries();
$job->handle();
$this->info('Job completed');
}
}

View file

@ -0,0 +1,37 @@
<?php
namespace App\Console\Commands;
use App\Jobs\Arcadia\XmlFluxEggJob;
use Illuminate\Console\Command;
class XmlFluxEggCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'xml:egg';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Run the XmlFluxEggJob manually';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->info('Running the Job, this could take some time.');
$job = new XmlFluxEggJob();
$job->console = $this;
$job->handle();
$this->info('Job completed');
}
}

View file

@ -0,0 +1,37 @@
<?php
namespace App\Console\Commands;
use App\Jobs\Arcadia\XmlFluxPoultryJob;
use Illuminate\Console\Command;
class XmlFluxPoultryCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'xml:poultry';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Run the XmlFluxPoultryJob manually';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->info('Running the Job, this could take some time.');
$job = new XmlFluxPoultryJob();
$job->console = $this;
$job->handle();
$this->info('Job completed');
}
}

View file

@ -2,6 +2,13 @@
namespace App\Console;
use App\Jobs\Arcadia\XmlFluxEggJob;
use App\Jobs\Arcadia\XmlFluxPoultryJob;
use App\Jobs\CafelBeaVolJob;
use App\Jobs\CafelEggBreederJob;
use App\Jobs\CafelFoodJob;
use App\Jobs\CafelMepEggJob;
use App\Jobs\CafelPoultryBreederJob;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
@ -12,20 +19,25 @@ class Kernel extends ConsoleKernel
*
* @var array
*/
protected $commands = [
//
];
protected $commands = [];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')
// ->hourly();
// * Jobs cafel sur queue cafel
$schedule->job(CafelFoodJob::class, 'cafel')->onOneServer()->everyThreeHours();
$schedule->job(CafelBeaVolJob::class, 'cafel')->onOneServer()->everyThreeHours();
$schedule->job(CafelMepEggJob::class, 'cafel')->onOneServer()->everyThreeHours();
$schedule->job(CafelEggBreederJob::class, 'cafel')->onOneServer()->everyThreeHours();
$schedule->job(CafelPoultryBreederJob::class, 'cafel')->onOneServer()->everyThreeHours();
$schedule->job(XmlFluxEggJob::class, 'tracea')->onOneServer()->dailyAt('02:00');
$schedule->job(XmlFluxPoultryJob::class, 'tracea')->onOneServer()->dailyAt('22:00');
}
/**
@ -35,7 +47,7 @@ class Kernel extends ConsoleKernel
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
$this->load(__DIR__ . '/Commands');
require base_path('routes/console.php');
}

View file

@ -1,62 +0,0 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Eleveur extends Model
{
use SoftDeletes;
public $timestamps = false;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'code_cafel',
'code_ede',
'civilite',
'nom',
'prenom',
'naissance',
'cp',
'ville',
'elv_date_debut',
'code_inuav',
'exploitation',
'aboutyou',
'vocation',
'likeinjob',
'loue_means',
'path_photo1',
'path_photo2',
'marquage_oeuf',
'marquage_b1',
'marquage_b2'
];
/**
* @var string
*/
protected $table = 'eleveurs';
protected $appends = ['questions'];
public function getQuestionsAttribute(){
if($this->aboutyou != null && $this->aboutyou != ''){
return true;
}
if($this->vocation != null && $this->vocation != ''){
return true;
}
if($this->likeinjob != null && $this->likeinjob != ''){
return true;
}
if($this->loue_means != null && $this->loue_means != ''){
return true;
}
return false;
}
}

13
app/Enums/ApiStatus.php Normal file
View file

@ -0,0 +1,13 @@
<?php
namespace App\Enums;
use Kwaadpepper\Enum\BaseEnumRoutable;
/**
* @method static self OK()
* @method static self KO()
*/
class ApiStatus extends BaseEnumRoutable
{
}

View file

@ -0,0 +1,50 @@
<?php
namespace App\Enums;
use Kwaadpepper\Enum\BaseEnum;
/**
* @method static self il()
* @method static self elle()
* @method static self ils()
* @method static self elles()
*/
final class BreederCivilty extends BaseEnum
{
/**
* Enum values
*
* CAFEL
* 1 il
* 2 elle
* 3 eux (par défaut)
* 4 elles
*
* @return array
*/
protected static function values(): array
{
return [
'il' => 1,
'elle' => 2,
'ils' => 3,
'elles' => 4
];
}
/**
* Enum labels
*
* @return array
*/
protected static function labels(): array
{
return [
'il' => 'Éleveur',
'elle' => 'Éleveuse',
'ils' => 'Éleveurs',
'elles' => 'Éleveuses'
];
}
}

38
app/Enums/BreederType.php Normal file
View file

@ -0,0 +1,38 @@
<?php
namespace App\Enums;
use Kwaadpepper\Enum\BaseEnum;
/**
* @method static self egg()
* @method static self poultry()
*/
final class BreederType extends BaseEnum
{
/**
* Enum values
*
* @return array
*/
protected static function values(): array
{
return [
'egg' => 0,
'poultry' => 1
];
}
/**
* Enum labels
*
* @return array
*/
protected static function labels(): array
{
return [
'egg' => 'Éleveur(se) Oeuf',
'poultry' => 'Éleveur(se) Volaille'
];
}
}

40
app/Enums/FoodType.php Normal file
View file

@ -0,0 +1,40 @@
<?php
namespace App\Enums;
use Kwaadpepper\Enum\BaseEnum;
/**
* 1 Pondeuse ou 2 Poulet
*
* @method static self layers()
* @method static self chicken()
*/
final class FoodType extends BaseEnum
{
/**
* Enum values
*
* @return array
*/
protected static function values(): array
{
return [
'layers' => 1,
'chicken' => 2
];
}
/**
* Enum labels
*
* @return array
*/
protected static function labels(): array
{
return [
'layers' => 'Pondeuses',
'chicken' => 'Poulet'
];
}
}

16
app/Enums/HttpMethods.php Normal file
View file

@ -0,0 +1,16 @@
<?php
namespace App\Enums;
use Kwaadpepper\Enum\BaseEnum;
/**
* @ignore This is used on internal
* @method static self get()
* @method static self post()
* @method static self put()
* @method static self delete()
*/
class HttpMethods extends BaseEnum
{
}

17
app/Enums/LogType.php Normal file
View file

@ -0,0 +1,17 @@
<?php
namespace App\Enums;
use Kwaadpepper\Enum\BaseEnumRoutable;
/**
* @method static self debug()
* @method static self log()
* @method static self warning()
* @method static self info()
* @method static self error()
* @method static self critical()
*/
final class LogType extends BaseEnumRoutable
{
}

View file

@ -0,0 +1,41 @@
<?php
namespace App\Enums;
use Kwaadpepper\Enum\BaseEnum;
/**
* @method static self unkown()
* @method static self labelRouge()
* @method static self bio()
*/
final class PoultryLabelType extends BaseEnum
{
/**
* Enum values
*
* @return array
*/
protected static function values(): array
{
return [
'unkown' => null,
'labelRouge' => 'LABEL',
'bio' => 'BIO'
];
}
/**
* Enum labels
*
* @return array
*/
protected static function labels(): array
{
return [
'unkown' => 'Undefined',
'labelRouge' => 'Label Rouge',
'bio' => 'Bio'
];
}
}

View file

@ -0,0 +1,9 @@
<?php
namespace App\Exceptions;
use ErrorException;
class AbortXmlImportException extends ErrorException
{
}

View file

@ -0,0 +1,9 @@
<?php
namespace App\Exceptions;
use Exception;
class CafelApiException extends Exception
{
}

View file

@ -0,0 +1,9 @@
<?php
namespace App\Exceptions;
use Exception;
class CafelApiImageFetchException extends Exception
{
}

View file

@ -2,6 +2,8 @@
namespace App\Exceptions;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Throwable;
use Kwaadpepper\ExceptionHandler\Exceptions\ExceptionHandler;
@ -12,9 +14,7 @@ class Handler extends ExceptionHandler
*
* @var array
*/
protected $dontReport = [
//
];
protected $dontReport = [];
/**
* A list of the inputs that are never flashed for validation exceptions.
@ -29,23 +29,47 @@ class Handler extends ExceptionHandler
/**
* Report or log an exception.
*
* @param \Throwable $exception
* @param \Throwable $exception
* @return void
*/
public function report(Throwable $exception)
{
if ($exception instanceof CafelApiImageFetchException) {
$this->reportCafelApiImageErrorException($exception);
return;
}
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
* Report Cafel exception image.
*
* @param \Illuminate\Http\Request $request
* @param \Throwable $exception
* @return \Illuminate\Http\Response
* @param CafelApiImageFetchException $exception
* @return void
*/
public function render($request, Throwable $exception)
private function reportCafelApiImageErrorException(CafelApiImageFetchException $exception): void
{
return parent::render($request, $exception);
$dest = config('exception-handler.invalidCafelImage', config('mail.from.address'));
try {
if ($dest and config('exception-handler.enableMaiLog')) {
Mail::send([
'html' => 'mails.invalidCafelImage'
], [
'appName' => config('app.name'),
'emessage' => $exception->getMessage(),
], function ($m) use ($dest) {
/** @var \Illuminate\Mail\Message $m */
$m->to(
$dest,
sprintf('%s Exception Handler', config('app.name'))
)->subject(sprintf(
'%s : Api Cafel, l\'image va être ignoré car elle est invalide.',
config('app.name')
));
});
}
} catch (\Exception $e) {
Log::critical('Handler could not send Exception email', ['exception' => $e]);
} //end try
}
}

View file

@ -0,0 +1,9 @@
<?php
namespace App\Exceptions;
use ErrorException;
class InvalidXmlException extends ErrorException
{
}

View file

@ -1,162 +0,0 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\MiseEnPlace;
use App\Aliments;
use App\Eleveur;
use App\Moba;
use Carbon\Carbon;
class AjaxController extends Controller
{
public function importAliment(Request $request){
$file = $request->file('fileAliment');
$flag = true;
$total = 0;
$imported = 0;
$error = 0;
$errorHtml = "";
if (($handle = fopen($file, "r")) !== FALSE){
while (($data = fgetcsv($handle, 50000, ";", '"')) !== FALSE){
if($flag) { $flag = false; continue; } //skip first row (headers)
if(isset($data[0]) && isset($data[1]) && isset($data[2]) && strpos($data[1], "/") !== false){
$total++;
$codeLot = $data[0];
$dateLivraison = $data[1];
list($d, $m, $y) = explode('/', $dateLivraison);
$date = $y.'-'.$m.'-'.$d;
$aliment = $data[2];
$alim = new Aliments();
$alim->code_lot = $codeLot;
$alim->date_livraison = $date;
$alim->type_aliment = $aliment;
if($alim->save()){
$imported++;
} else {
$error++;
$errorHtml = "<li>Les aliments n'ont pu être importés.</li>";
}
}
}
}
return json_encode(array('errors' => $error, 'errorHtml' => $errorHtml, 'total' => $total, 'imported' => $imported));
}
public function importMep(Request $request){
$file = $request->file('fileMep');
//var_dump($file);
$flag = true;
$total = 0;
$imported = 0;
$error = 0;
$errorHtml = "";
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 50000, ";", '"')) !== FALSE){
if($flag) { $flag = false; continue; } //skip first row (headers)
$total++;
$inuavEleveur = $data[10];
$eleveur = Eleveur::where('code_inuav', 'like', '%' . trim($inuavEleveur) . '%')->first();
if($eleveur === null){
$error++;
$errorHtml .= "<li>Eleveur non trouvé : ".$data[1]." ".$data[2]."</li>";
continue;
} else {
if(strpos($data[7], "/") !== false && strpos($data[8], "/") !== false){
$mep = new MiseEnPlace();
$mep->eleveurId_pondeuse = $eleveur->id;
$mep->code_lot_pondeuse = $data[6];
$mep->hectares_parcours_pondeuse = $data[20];
switch ($data[21]) {
case 'OUI':
$mep->presence_ruche_pondeuse = 1;
break;
default:
$mep->presence_ruche_pondeuse = 0;
break;
}
switch ($data[22]) {
case 'OUI':
$mep->zone_mellifere_pondeuse = 1;
break;
default:
$mep->zone_mellifere_pondeuse = 0;
break;
}
$mep->nom_couvoir = $data[11];
$mep->ville_couvoir = $data[12];
$mep->cp_couvoir = $data[13];
$mep->raison_sociale_eleveur_poulettes = $data[14];
$mep->code_inuav_poulettes = $data[15];
$mep->nom_eleveur_poulettes = $data[16];
$mep->prenom_eleveur_poulettes = $data[17];
$mep->ville_eleveur_poulettes = $data[18];
$mep->cp_eleveur_poulettes = $data[19];
$eleveur->marquage_oeuf = $data[23];
$eleveur->marquage_b1 = $data[24];
$eleveur->marquage_b2 = $data[25];
$eleveur->save();
list($d_naissance, $m_naissance, $y_naissance) = explode('/', $data[7]);
list($d_transfert, $m_transfert, $y_transfert) = explode('/', $data[8]);
$mep->date_naissance_poulettes = $y_naissance.'-'.$m_naissance.'-'.$d_naissance;
$mep->date_transfert_poulettes = $y_transfert.'-'.$m_transfert.'-'.$d_transfert;
$mep->save();
$imported++;
}
}
}
}
return json_encode(array('errors' => $error, 'errorHtml' => $errorHtml, 'total' => $total, 'imported' => $imported));
}
public function rotateToRight(Request $request) {
$home = url('/');
$test = $request->filePath;
// -90deg
$im = imagecreatefromjpeg($request->filePath);
$rotate = imagerotate($im, -90, 0);
imagejpeg($rotate, $test, 100);
return json_encode($home.'/'.$test);
}
public function rotateToLeft(Request $request) {
$home = url('/');
$test = $request->filePath;
// 90deg
$im = imagecreatefromjpeg($request->filePath);
$rotate = imagerotate($im, 90, 0);
imagejpeg($rotate, $test, 100);
return json_encode($home.'/'.$test);
}
public function findMyBox(Request $request) {
$code = $request->code;
$date = explode('/', $request->date);
$day = $date[0];
$month = $date[1];
$dateCarbon = Carbon::createFromDate(null, $month, $day)->toArray();
$year = $dateCarbon['year'];
$dcr = $year.'-'.$month.'-'.$day;
$moba = Moba::where(['code_ede' => $code, 'dcr' => $dcr])->orderBy('id', 'DESC')->first();
if(!$moba){
return redirect()->route('erreur404');
}
return redirect()->route('FrontPage', ['id' => $moba->code_boite]);
}
}

View file

@ -7,17 +7,6 @@ use Illuminate\Foundation\Auth\ConfirmsPasswords;
class ConfirmPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Confirm Password Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password confirmations and
| uses a simple trait to include the behavior. You're free to explore
| this trait and override any functions that require customization.
|
*/
use ConfirmsPasswords;
/**

View file

@ -7,16 +7,5 @@ use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
class ForgotPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset emails and
| includes a trait which assists in sending these notifications from
| your application to your users. Feel free to explore this trait.
|
*/
use SendsPasswordResetEmails;
}

View file

@ -7,17 +7,6 @@ use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
@ -36,9 +25,4 @@ class LoginController extends Controller
{
$this->middleware('guest')->except('logout');
}
public function username()
{
return 'username';
}
}

View file

@ -3,24 +3,13 @@
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\User;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
@ -43,7 +32,7 @@ class RegisterController extends Controller
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
@ -59,7 +48,7 @@ class RegisterController extends Controller
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @param array $data
* @return \App\User
*/
protected function create(array $data)

View file

@ -7,17 +7,6 @@ use Illuminate\Foundation\Auth\ResetsPasswords;
class ResetPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**

View file

@ -7,17 +7,6 @@ use Illuminate\Foundation\Auth\VerifiesEmails;
class VerificationController extends Controller
{
/*
|--------------------------------------------------------------------------
| Email Verification Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling email verification for any
| user that recently registered with the application. Emails may also
| be re-sent if the user didn't receive the original email message.
|
*/
use VerifiesEmails;
/**

View file

@ -0,0 +1,159 @@
<?php
namespace App\Http\Controllers\Bo;
use App\Enums\BreederType;
use App\Http\Controllers\Controller;
use App\Http\Requests\Bo\BreederIndexRequest;
use App\Models\CafelEggBreeder;
use App\Models\CafelPoultryBreeder;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
class BreederController extends Controller
{
/**
* Display a listing of the resource.
*
* @param \App\Http\Requests\Bo\BreederIndexRequest $request
* @return \Illuminate\Http\Response
* @throws \ErrorException If request type is unhandled.
*/
public function index(BreederIndexRequest $request)
{
$showEgg = false;
$showPoultry = false;
$breeders = DB::query();
// * Query Breeders cafel Ids
if ($request->type) {
switch ($request->type) {
case BreederType::egg():
$showEgg = true;
$this->getEggBreeders($request, $breeders);
break;
case BreederType::poultry():
$showPoultry = true;
$this->getPoultryBreeders($request, $breeders);
break;
default:
throw new \ErrorException("Unhandled BreederType type '$request->type'");
}
} else {
$showEgg = true;
$showPoultry = true;
$this->getEggBreeders($request, $breeders);
$breeders = $breeders->union(function ($q) use ($request) {
$this->getPoultryBreeders($request, $q);
});
}//end if
/** @var \Illuminate\Pagination\LengthAwarePaginator */
$breeders = $breeders->orderBy('cafel_code', 'DESC')->paginate();
if ($showEgg) {
/** @var \Illuminate\Database\Eloquent\Builder $eggBreeders */
$eggBreeders = CafelEggBreeder::whereIn(
'cafel_code',
$breeders->getCollection()->pluck('cafel_code')->all()
);
$eggBreeders = $eggBreeders->get();
}
if ($showPoultry) {
/** @var \Illuminate\Database\Eloquent\Builder $poultryBreeders */
$poultryBreeders = CafelPoultryBreeder::whereIn(
'cafel_code',
$breeders->getCollection()->pluck('cafel_code')->all()
);
$poultryBreeders = $poultryBreeders->get();
}
switch (true) {
case $showEgg and $showPoultry:
$breeders->setCollection($eggBreeders->merge($poultryBreeders)->sortBy('cafel_code'));
break;
case $showEgg:
$breeders->setCollection($eggBreeders);
break;
case $showPoultry:
$breeders->setCollection($poultryBreeders);
break;
}
// * Randomize
$breeders->setCollection($breeders->getCollection()->sortBy('cafel_code'));
$searchFields = trans('Code Cafel, EDE, INUAV, Nom, Prénom, Ville, Code postal');
return view('back.breeders.index', [
'breeders' => $breeders,
'searchFields' => $searchFields
]);
}
/**
* View breeder
*
* @param \App\Models\CafelEggBreeder|\App\Models\CafelPoultryBreeder $breeder
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
* @throws \ErrorException If $breeder model is unhandled.
*/
public function show($breeder)
{
if (!($breeder instanceof CafelEggBreeder) and !($breeder instanceof CafelPoultryBreeder)) {
throw new \ErrorException(__METHOD__ . 'Only handles egg and poultry breeder classes');
}
return view('back.breeders.show', compact('breeder'));
}
/**
* Query poultry breeders
*
* @param BreederIndexRequest $request
* @param Builder $breeders
* @return void
*/
private function getPoultryBreeders(BreederIndexRequest $request, Builder &$breeders)
{
$breeders->select('cafel_code')->from('cafel_poultry_breeders');
if ($request->search) {
$this->searchQuery(
$breeders,
'cafel_poultry_breeders',
$request->search,
'cafel_code',
'firstname',
'lastname',
'city',
'postcode',
'inuavs'
);
}
}
/**
* Query Egg breeders
*
* @param BreederIndexRequest $request
* @param Builder $breeders
* @return void
*/
private function getEggBreeders(BreederIndexRequest $request, Builder &$breeders)
{
$breeders = $breeders->select('cafel_code')->from('cafel_egg_breeders');
if ($request->search) {
$this->searchQuery(
$breeders,
'cafel_egg_breeders',
$request->search,
'cafel_code',
'ede_code',
'firstname',
'lastname',
'city',
'postcode',
'inuavs'
);
}
}
}

View file

@ -2,12 +2,76 @@
namespace App\Http\Controllers;
use Illuminate\Database\Query\Builder;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\Session;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
use AuthorizesRequests;
use DispatchesJobs;
use ValidatesRequests;
/**
* Controller
*/
public function __construct()
{
$this->middleware(function ($request, $next) {
// * Flush poultry search if timed out
/** @var \Illuminate\Support\Carbon|null $time */
if ($time = session()->get('poultrySearch.time')) {
if ($time->lessThan(now()->subMinutes(30))) {
session()->forget('poultrySearch');
} else {
// * Refresh search session
Session::put('poultrySearch.time', now());
}
} else {
session()->forget('poultrySearch');
}
return $next($request);
});
}
/**
* Handle search for model.index
*
* @param Builder $query The eloquent query builder.
* @param string $table The query table string.
* @param string $search The query string.
* @phpcs:ignore Squiz.Commenting.FunctionComment.ParamCommentFullStop
* @param string|array ...$field Either a simple array or a string.
* In case of a string the two fields would be concatenate to make the search
* @return Builder
*/
protected function searchQuery(
Builder $query,
string $table,
string $search,
...$field
): Builder {
if (count($field)) {
$query = $query->where(function ($q) use ($field, $search, $table) {
foreach ($field as $f) {
$f = str_replace('?', '\?', $f);
if (is_array($f)) {
$q->orWhereRaw(
sprintf("UPPER(CONCAT(%s)) LIKE UPPER(?)", collect($f)->map(function ($q) use ($table) {
return "`$table`.`$q`";
})->implode(', \' \', ')),
["%$search%"]
);
} else {
$q->orWhereRaw("UPPER(`$table`.`$f`) LIKE UPPER(?)", ["%$search%"]);
}
}
});
}
return $query;
}
}

View file

@ -1,199 +0,0 @@
<?php
namespace App\Http\Controllers;
use App\Eleveur;
use Illuminate\Http\Request;
use App\Http\Requests\MyRequest;
use Response;
class EleveurController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$eleveurs = Eleveur::all();
return view('eleveurs.index', ['eleveurs' => $eleveurs]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('eleveurs.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(MyRequest $request)
{
$validatedData = $request->validate([
'photo1' => 'mimetypes:image/jpeg|max:1000',
'photo2' => 'mimetypes:image/jpeg|max:1000',
]);
$eleveur = new Eleveur();
$eleveur->code_cafel = $request->code_cafel;
$eleveur->code_ede = $request->code_ede;
$eleveur->civilite = $request->civilite;
$eleveur->nom = $request->nom;
$eleveur->prenom = $request->prenom;
$eleveur->naissance = $request->naissance;
$eleveur->cp = $request->cp;
$eleveur->ville = $request->ville;
$eleveur->elv_date_debut = $request->elv_date_debut;
$eleveur->code_inuav = $request->code_inuav;
$eleveur->marquage_oeuf = $request->marquage_oeuf;
$eleveur->marquage_b1 = $request->marquage_b1;
$eleveur->marquage_b2 = $request->marquage_b2;
if(isset($request->exploitation) && !empty($request->exploitation)){
$eleveur->exploitation = $request->exploitation;
}
if(isset($request->aboutyou) && !empty($request->aboutyou)){
$eleveur->aboutyou = $request->aboutyou;
}
if(isset($request->vocation) && !empty($request->vocation)){
$eleveur->vocation = $request->vocation;
}
if(isset($request->likeinjob) && !empty($request->likeinjob)){
$eleveur->likeinjob = $request->likeinjob;
}
if(isset($request->loue_means) && !empty($request->loue_means)){
$eleveur->loue_means = $request->loue_means;
}
if ($request->photo1){
$path = $request->photo1->store('images/photos');
$path = str_replace('public/', '', $path);
$eleveur->path_photo1 = $path;
}
if ($request->photo2){
$path2 = $request->photo2->store('images/photos');
$path2 = str_replace('public/', '', $path2);
$eleveur->path_photo2 = $path2;
}
$eleveur->save();
return redirect()->route('eleveur.edit', ['eleveur' => $eleveur]);
}
/**
* Display the specified resource.
*
* @param \App\Eleveur $eleveur
* @return \Illuminate\Http\Response
*/
public function show(Eleveur $eleveur)
{
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Eleveur $eleveur
* @return \Illuminate\Http\Response
*/
public function edit(Eleveur $eleveur)
{
return view('eleveurs.edit', ['eleveur' => $eleveur]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Eleveur $eleveur
* @return \Illuminate\Http\Response
*/
public function update(MyRequest $request, Eleveur $eleveur)
{
$validatedData = $request->validate([
'photo1' => 'mimetypes:image/jpeg|max:1000',
'photo2' => 'mimetypes:image/jpeg|max:1000',
]);
$datas = collect($request->all());
if ($request->photo1){
$path = $request->photo1->store('images/photos');
$path = str_replace('public/', '', $path);
$datas->put('path_photo1', $path);
} else {
$datas->put('path_photo1', $request->input('path_photo1_hidden'));
}
if ($request->photo2){
$path2 = $request->photo2->store('images/photos');
$path2 = str_replace('public/', '', $path2);
$datas->put('path_photo2', $path2);
} else {
$datas->put('path_photo2', $request->input('path_photo2_hidden'));
}
$eleveur->update($datas->toArray());
return redirect()->route('eleveur.edit', ['eleveur' => $eleveur]);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Eleveur $eleveur
* @return \Illuminate\Http\Response
*/
public function destroy(Eleveur $eleveur)
{
//
}
public function export(){
$headers = array(
"Content-Encoding" => "UTF-8",
"Content-type" => "Content-type: text/csv; charset=UTF-8",
"Content-Disposition" => "attachment; filename=file.csv",
"Pragma" => "no-cache",
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
"Expires" => "0"
);
$eleveurs = Eleveur::all();
$columns = array('Code Cafel', 'Code EDE', 'Nom', 'Prénom', 'Naissance', 'CP', 'Ville', 'Date Début Elevage', 'Code INUAV', 'Infos Exploitation', 'A propos de l\'éleveur', 'Toujours été éleveur', 'Ce que l\'éleveur aimes', 'Loué ?', 'Photo 1', 'Photo 2' );
$callback = function() use ($eleveurs, $columns)
{
$file = fopen('php://output', 'w');
fputs($file, "\xEF\xBB\xBF"); // use BOM for Office
fputcsv($file, $columns, ";");
foreach($eleveurs as $eleveur) {
if($eleveur->path_photo1 != ""){
$photo1 = "OUI";
}else {
$photo1 = "NON";
}
if($eleveur->path_photo2 != ""){
$photo2 = "OUI";
}else {
$photo2 = "NON";
}
fputcsv($file, array($eleveur->code_cafel, $eleveur->code_ede, $eleveur->nom, $eleveur->prenom, $eleveur->naissance, $eleveur->cp, $eleveur->ville, $eleveur->elv_date_debut, $eleveur->code_inuav, $eleveur->exploitation, $eleveur->aboutyou, $eleveur->vocation, $eleveur->likeinjob, $eleveur->loue_means, $photo1, $photo2), ";");
}
fclose($file);
};
return Response::stream($callback, 200, $headers);
}
}

View file

@ -0,0 +1,25 @@
<?php
namespace App\Http\Controllers\Fo;
use App\Http\Controllers\Controller;
use App\Models\CafelEggBreeder;
use App\Models\CafelPoultryBreeder;
class BreederController extends Controller
{
/**
* Show breeder decription page
*
* @param \App\Models\CafelEggBreeder|\App\Models\CafelPoultryBreeder $breeder
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
* @throws \ErrorException If $breeder model is unhandled.
*/
public function show($breeder)
{
if (!($breeder instanceof CafelEggBreeder) and !($breeder instanceof CafelPoultryBreeder)) {
throw new \ErrorException(__METHOD__ . 'Only handles egg and poultry breeder classes');
}
return \view('front.breeders.show', compact('breeder'));
}
}

View file

@ -1,29 +1,50 @@
<?php
namespace App\Http\Controllers;
namespace App\Http\Controllers\Fo;
use App\Eleveur;
use App\Aliments;
use App\MiseEnPlace;
use App\Moba;
use App\VisuelLibelle;
use App\Http\Controllers\Controller;
use App\Models\CafelEggBreeder;
use App\Models\CafelEggMiseEnPlace;
use App\Models\CafelFood;
use Illuminate\Http\Request;
use App\Models\TraceaEgg;
use App\Models\VisuelLibelle;
use Carbon\Carbon;
class FrontController extends Controller
class EggController extends Controller
{
public function findMyBox(Request $request)
{
$code = $request->code;
$date = explode('/', $request->date);
$day = $date[0];
$month = $date[1];
$moba = TraceaEgg::where('ede_code', '=', $code)
->whereDate('dcr', Carbon::createFromDate(null, $month, $day)->toDate())
->orderBy('box_code', 'DESC')->first();
if (!$moba) {
return view('front.egg.notFound');
}
return redirect()->route('egg.FrontPage', ['id' => $moba->box_code]);
}
public function indexId($id)
{
$multiple = false;
$mobas = Moba::where('code_boite', $id)->orderBy('id', 'DESC')->first();
/** @var \App\Models\TraceaEgg|null */
$mobas = TraceaEgg::where('box_code', $id)->orderBy('box_code', 'DESC')->first();
if (!$mobas)
if (!$mobas) {
return redirect('/search');
}
$edes = $mobas->code_edes;
//check if Bio or not
$code_ede = $mobas->code_ede;
// * check if Bio or not
$code_ede = $mobas->ede_code;
$code_prod = substr($code_ede, 0, 1);
if ($code_prod === 0) {
@ -32,40 +53,43 @@ class FrontController extends Controller
session(['subColor' => 'blue']);
}
$datePonte = $mobas->date_ponte;
$dcr = $mobas->dcr;
$datePonte = $mobas->laying_date;
$date_emballage = $mobas->date_emballage;
//Compare DCR et Today
$date_dcr = Carbon::createFromFormat('Y-m-d', $dcr);
// * Compare DCR et Today
$date_dcr = $mobas->dcr;
$date_today = Carbon::now();
$dcrGood = $date_today < $date_dcr;
$dcrGood = $date_today < $date_dcr;
$eleveurs = Eleveur::whereIn('code_ede', $edes)->get();
if (!$eleveurs) {
return redirect()->route('erreur404');
$eleveurs = CafelEggBreeder::whereIn('ede_code', $edes)->get();
if (!$eleveurs->count()) {
return view('front.egg.notFound');
}
$uniqueEleveurs = $eleveurs->unique('code_ede');
if (count($uniqueEleveurs) > 1) {
$multiple = true;
}
$elevId = $eleveurs->pluck('id');
$inuavs = $eleveurs->pluck('inuavs')->flatten(1);
$mep = CafelEggMiseEnPlace::whereIn('inuav_code', $inuavs)
->where('transfert_date', '<', $datePonte)
->orderBy('transfert_date', 'DESC')->first();
$mep = MiseEnPlace::whereIn('eleveurId_pondeuse', $elevId)->where('date_transfert_poulettes', '<', $datePonte)->orderBy('id', 'DESC')->first();
if ($mep) {
$aliment = Aliments::where('code_lot', $mep->code_lot_pondeuse)->orderBy('id', 'DESC')->first();
$aliment = CafelFood::where('batch_code', $mep->batch_code)->orderBy('delivery_date', 'DESC')->first();
} else {
$mep = '';
$mep = '';
$aliment = "";
}
$dataVisuel = VisuelLibelle::where('ean13', $mobas->ean13)->first();
$dataVisuel = VisuelLibelle::where('ean_13', $mobas->ean_13)->first();
return view('themes.loue.index_id', [
return view('front.egg.index_id', [
'id' => $id,
'multiple' => $multiple,
'datePonte' => $datePonte,
'dcr' => $dcr,
'dcr' => $date_dcr,
'dcrGood' => $dcrGood,
'eleveurs' => $eleveurs,
'mep' => $mep,
@ -77,22 +101,22 @@ class FrontController extends Controller
public function EleveurPortrait($id, $eleveurId)
{
$dateToday = Carbon::now()->toArray();
$dateToday = Carbon::now()->toArray();
$currentYear = $dateToday['year'];
$eleveur = Eleveur::where('id', $eleveurId)->first();
$eleveur = CafelEggBreeder::where('cafel_code', $eleveurId)->first();
if (isset($eleveur->naissance) && !empty($eleveur->naissance)) {
$date_naissance = Carbon::createFromFormat('d/m/Y', $eleveur->naissance)->toArray();
$year = $date_naissance['year'];
$age = $currentYear - $year;
$year = $date_naissance['year'];
$age = $currentYear - $year;
} else {
$age = false;
}
if (isset($eleveur->elv_date_debut) && !empty($eleveur->elv_date_debut)) {
$date_elevage = Carbon::createFromFormat('d/m/Y', $eleveur->elv_date_debut)->toArray();
$year_elevage = $date_elevage['year'];
$age_elevage = $currentYear - $year_elevage;
$age_elevage = $currentYear - $year_elevage;
} else {
$age_elevage = false;
}
@ -127,6 +151,9 @@ class FrontController extends Controller
array_push($questions, array('Si je te dis Loué, ça te fait penser à quoi ?', $eleveur->loue_means));
}
return view('themes.loue.elevages.portrait', ['id' => $id, 'eleveur' => $eleveur, 'age' => $age, 'ageElevage' => $age_elevage, 'questions' => $questions]);
return view('front.egg.elevages.portrait', [
'id' => $id, 'eleveur' => $eleveur, 'age' => $age,
'ageElevage' => $age_elevage, 'questions' => $questions
]);
}
}

View file

@ -0,0 +1,63 @@
<?php
namespace App\Http\Controllers\Fo;
use App\Http\Controllers\Controller;
/**
* This exists because we want these
* to use the Controller middleware
* to apply for poultrySearch and eggSearch session
*/
class InfoController extends Controller
{
/**
* Show poultry infos
*
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
*/
public function poultry()
{
return view('front.poultry.infos.index');
}
/**
* Show poultry free chicken infos
*
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
*/
public function poultryFreeChicken()
{
return view('front.poultry.infos.free-chicken');
}
/**
* Show poultry farm chicken infos
*
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
*/
public function poultryFarmChicken()
{
return view('front.poultry.infos.farm-chicken');
}
/**
* Show poultry food bio infos
*
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
*/
public function poultryBio()
{
return view('front.poultry.food.bio');
}
/**
* Show poultry food label rouge infos
*
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
*/
public function poultryLr()
{
return view('front.poultry.food.lr');
}
}

View file

@ -0,0 +1,96 @@
<?php
namespace App\Http\Controllers\Fo;
use App\Http\Controllers\Controller;
use App\Http\Requests\Fo\SearchPoultryTraceaRequest;
use App\Models\TraceaPoultry;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;
class TraceaPoultryController extends Controller
{
/**
* Show search form
*
* @param SearchPoultryTraceaRequest $request
* @return \Illuminate\Http\RedirectResponse
*/
public function searchSubmit(SearchPoultryTraceaRequest $request)
{
/** @var \App\Models\TraceaPoultry|null */
$traceaPoultry = TraceaPoultry::whereExternalCodeLot($request->codelot)
->where(function ($q) use ($request) {
if ($request->eancode[0] === "0") {
$code = Str::substr($request->eancode, 1);
$q->where('barcode_price', 'LIKE', Str::limit($code, 6, '') . '%')
->orWhere('barcode_weight', 'LIKE', Str::limit($code, 6, '') . '%');
} else {
$q->where('barcode_price', 'LIKE', Str::limit($request->eancode, 7, '') . '%')
->orWhere('barcode_weight', 'LIKE', Str::limit($request->eancode, 7, '') . '%');
}
})->first();
if (!$traceaPoultry) {
return back()->with(
'warning',
// phpcs:ignore Generic.Files.LineLength.TooLong
trans('Aucun produit n\'a pu être trouvé avec ces informations. Vérifiez bien les numéros saisis avec les indication comme sur l\'image ci-dessous.')
);
}
Session::put('poultrySearch', [
'model' => $traceaPoultry,
'time' => now()
]);
// * Flash session with age max show result page to 6
return response()->redirectToRoute('poultry.show');
}
/**
* Show Traceapoultry result
*
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
*/
public function show()
{
// * If result too old or not found
/** @var \App\Models\TraceaPoultry|null */
if (
!($traceaPoultry = Session::get('poultrySearch.model')) or
!\is_object(Session::get('poultrySearch.time')) or
\get_class(Session::get('poultrySearch.time')) !== Carbon::class
) {
Session::forget('poultrySearch');
\redirect()->route('poultry.search')->throwResponse();
}
$distributionPicture = $this->getDistributionPicture($traceaPoultry->sign);
return view('front.poultry.show', compact(
'traceaPoultry',
'distributionPicture'
));
}
/**
* Get distribution sign picture name if exists.
*
* @param string|null $sign
* @return string|null
*/
private function getDistributionPicture(?string $sign): ?string
{
if (\is_null($sign) or empty($sign)) {
return null;
}
if (File::exists(\public_path("assets/images/signs/$sign.png"))) {
return "$sign.png";
}
report(new \RuntimeException("$sign is missing in assets/images/signs"));
return null;
}
}

View file

@ -14,8 +14,9 @@ class Kernel extends HttpKernel
* @var array
*/
protected $middleware = [
\App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
@ -28,6 +29,7 @@ class Kernel extends HttpKernel
*/
protected $middlewareGroups = [
'web' => [
'xss',
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
@ -35,6 +37,7 @@ class Kernel extends HttpKernel
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\SecureHeaders::class
],
'api' => [
@ -61,22 +64,6 @@ class Kernel extends HttpKernel
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
/**
* The priority-sorted list of middleware.
*
* This forces non-global middleware to always be in the given order.
*
* @var array
*/
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\Authenticate::class,
\Illuminate\Routing\Middleware\ThrottleRequests::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
'xss' => \App\Http\Middleware\XssSanitizer::class,
];
}

View file

@ -3,19 +3,36 @@
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Support\Facades\Session;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string
* @param \Illuminate\Http\Request $request
* @return string|null
* @phpcs:disable Squiz.Commenting.FunctionComment.TypeHintMissing
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
$logins = [
'backend' => route('bo.login')
];
if (!$request->expectsJson()) {
// * Notify must login
Session::flash('warning', trans('Veuillez vous connecter pour continuer'));
foreach ($request->route()->gatherMiddleware() as $middleware) {
if (\is_string($middleware) and strpos($middleware, 'auth:') !== false) {
$route = $logins[str_replace('auth:', '', $middleware)] ?? null;
if ($route) {
return $route;
}
}
}
return route('bo.login');
}
abort(401);
}
}

View file

@ -1,17 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode as Middleware;
class CheckForMaintenanceMode extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array
*/
protected $except = [
//
];
}

View file

@ -9,9 +9,7 @@ class EncryptCookies extends Middleware
/**
* The names of the cookies that should not be encrypted.
*
* @var array
* @var array<int, string>
*/
protected $except = [
//
];
protected $except = [];
}

View file

@ -0,0 +1,15 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
class PreventRequestsDuringMaintenance extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array<int, string>
*/
protected $except = [];
}

View file

@ -3,6 +3,7 @@
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
@ -10,15 +11,22 @@ class RedirectIfAuthenticated
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null ...$guards
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle($request, Closure $next, $guard = null)
public function handle(Request $request, Closure $next, ...$guards)
{
if (Auth::guard($guard)->check()) {
return redirect('/home');
$logins = [
'web' => route('bo.eleveurs.index')
];
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return \redirect()->to($logins[$guard]);
}
}
return $next($request);

View file

@ -0,0 +1,69 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
class SecureHeaders
{
/**
* Enumerate headers which you do not want in your application's responses.
* Great starting point would be to go check out @Scott_Helme's:
* https://securityheaders.com/
*
* @var array
*/
private $unwantedHeaderList = [
'X-Powered-By',
'Server',
];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
View::share('nonce', $nonce = \uniqid());
// * For VueJS dev tool to execute
$jsDev = config('app.debug') ? "'unsafe-eval' 'unsafe-inline'" : "'nonce-$nonce'";
$cssDev = config('app.debug') ? "'unsafe-inline'" : "'nonce-$nonce'";
$this->removeUnwantedHeaders($this->unwantedHeaderList);
$response = $next($request);
$response->headers->set('Referrer-Policy', 'no-referrer-when-downgrade');
$response->headers->set('X-Content-Type-Options', 'nosniff');
$response->headers->set('X-XSS-Protection', '1; mode=block');
$response->headers->set('X-Frame-Options', 'SAMEORIGIN');
$response->headers->set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains;');
$cspPolicies = [
// phpcs:ignore Generic.Files.LineLength.TooLong
"style-src 'self' $cssDev https://fonts.googleapis.com;",
// phpcs:ignore Generic.Files.LineLength.TooLong
"script-src 'self' $jsDev https://fonts.googleapis.com;"
];
$response->headers->set(
'Content-Security-Policy',
implode(' ', $cspPolicies)
);
$response->headers->set('Feature-Policy', 'fullscreen picture-in-picture \'self\';');
return $response;
}
/**
* Remove unwanted headers
*
* @param array $headerList
* @return void
*/
private function removeUnwantedHeaders(array $headerList)
{
foreach ($headerList as $header) {
header_remove($header);
}
}
}

View file

@ -9,9 +9,10 @@ class TrimStrings extends Middleware
/**
* The names of the attributes that should not be trimmed.
*
* @var array
* @var array<int, string>
*/
protected $except = [
'current_password',
'password',
'password_confirmation',
];

View file

@ -0,0 +1,20 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustHosts as Middleware;
class TrustHosts extends Middleware
{
/**
* Get the host patterns that should be trusted.
*
* @return array<int, string|null>
*/
public function hosts()
{
return [
$this->allSubdomainsOfApplicationUrl(),
];
}
}

View file

@ -2,7 +2,7 @@
namespace App\Http\Middleware;
use Fideloper\Proxy\TrustProxies as Middleware;
use Illuminate\Http\Middleware\TrustProxies as Middleware;
use Illuminate\Http\Request;
class TrustProxies extends Middleware
@ -10,14 +10,19 @@ class TrustProxies extends Middleware
/**
* The trusted proxies for this application.
*
* @var array|string
* @var array<int, string>|string|null
*/
protected $proxies = "*";
protected $proxies;
/**
* The headers that should be used to detect proxies.
*
* @var int
* @var integer
*/
protected $headers = Request::HEADER_X_FORWARDED_ALL;
protected $headers =
Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_AWS_ELB;
}

View file

@ -6,19 +6,10 @@ use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* Indicates whether the XSRF-TOKEN cookie should be set on the response.
*
* @var bool
*/
protected $addHttpCookie = true;
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
* @var array<int, string>
*/
protected $except = [
//
];
protected $except = [];
}

View file

@ -0,0 +1,47 @@
<?php
namespace App\Http\Middleware;
use App\Lib\ToolboxHelper;
use Illuminate\Http\Request;
class XssSanitizer
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param mixed ...$params
* @return mixed
*/
public function handle(Request $request, \Closure $next, ...$params)
{
$inputs = $request->all();
array_walk_recursive($inputs, function (&$input, $name) use ($params) {
if (!is_string($input)) {
return;
}
if (in_array($name, $params)) {
// ? Is a json input ?
if ($isJson = \json_decode($input, true) and is_array($isJson)) {
// ! Decode each json field recursive.
\array_walk_recursive($isJson, function (&$item) {
if (\is_string($item)) {
$item = clean($item);
$item = ToolboxHelper::stripCkEditorSchemesOnMediaInputs($item);
}
});
} else {
$input = clean($input);
$input = ToolboxHelper::stripCkEditorSchemesOnMediaInputs($input);
}
} else {
$input = strip_tags($input);
$input = \filter_var($input, FILTER_SANITIZE_STRING);
}
});
$request->merge($inputs);
return $next($request);
}
}

View file

@ -0,0 +1,42 @@
<?php
namespace App\Http\Requests\Bo;
use App\Enums\BreederType;
use Illuminate\Foundation\Http\FormRequest;
class BreederIndexRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize()
{
try {
if (!\is_null($this->type)) {
$this->merge([
'type' => BreederType::make(intval($this->type))
]);
}
} catch (\BadMethodCallException $e) {
$this->merge([
'type' => null
]);
}
return auth()->check();
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'type' => 'nullable'
];
}
}

View file

@ -0,0 +1,68 @@
<?php
namespace App\Http\Requests\Fo;
use ArondeParon\RequestSanitizer\Sanitizers\FilterVars;
use ArondeParon\RequestSanitizer\Sanitizers\RemoveNonNumeric;
use ArondeParon\RequestSanitizer\Traits\SanitizesInputs;
use Illuminate\Foundation\Http\FormRequest;
class SearchPoultryTraceaRequest extends FormRequest
{
use SanitizesInputs;
/**
* Sanitize rules
*
* @var array
*/
protected $sanitizers = [
'codelot' => [
RemoveNonNumeric::class,
FilterVars::class => [
'filter' => \FILTER_SANITIZE_NUMBER_INT,
]
],
'eancode' => [
RemoveNonNumeric::class,
FilterVars::class => [
'filter' => \FILTER_SANITIZE_NUMBER_INT,
]
],
];
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'codelot' => 'required|numeric|digits:10',
'eancode' => ['required', 'numeric', 'regex:/^(\d{13})$/']
];
}
/**
* Get custom messages for validator errors.
*
* @return array
*/
public function messages()
{
return [
'eancode.regex' => trans('Doit être un code à 13 chiffres comme par exemple : 0 350217 648298')
];
}
}

View file

@ -1,48 +0,0 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class MyRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'photo1' => 'mimetypes:image/jpeg|max:500000',
'photo2' => 'mimetypes:image/jpeg|max:500000',
];
}
/**
* Get the error messages for the defined validation rules.
*
* @return array
*/
public function messages()
{
return [
'photo1.max' => 'La Photo 1 ne doit pas dépasser 500 Ko',
'photo1.uploaded' => 'La Photo 1 ne doit pas dépasser 500 Ko',
'photo1.mimetypes' => 'La Photo 1 doit être un jpg',
'photo2.max' => 'La Photo 2 ne doit pas dépasser 500 Ko',
'photo2.mimetypes' => 'La Photo 2 doit être un jpg',
'photo2.uploaded' => 'La Photo 2 ne doit pas dépasser 500 Ko',
];
}
}

View file

@ -0,0 +1,103 @@
<?php
namespace App\Http\Requests;
use App\Enums\BreederCivilty;
use App\Models\CafelEggBreeder;
use Illuminate\Foundation\Http\FormRequest;
use Kwaadpepper\Enum\Rules\EnumIsValidRule;
class StoreEleveurRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize()
{
$this->merge([
'code_inuav' => explode(',', $this->code_inuav)
]);
return auth()->check();
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
// TODO: add validation rules using CAFEL API standards.
return [
'code_cafel' => 'nullable|string|min:1|max:100|unique:eleveurs,code_cafel',
'code_ede' => 'required|string|min:1|max:100|unique:eleveurs,code_ede',
'civilite' => ['required', new EnumIsValidRule(BreederCivilty::class)],
'nom' => 'required|string|min:1|max:255',
'prenom' => 'required|string|min:1|max:255',
'naissance' => 'required|date_format:Y-m-d',
'cp' => 'required|numeric|digits:5',
'ville' => 'required|string|min:1|max:255',
'elv_date_debut' => 'nullable|date_format:Y-m-d',
'code_inuav' => [
'array', function ($attribute, $value, $fail) {
if (\strlen(\json_encode($value)) > 255) {
$fail("$attribute : il n'\est pas possible de renseigner autant de code INUAV");
}
}
],
'code_inuav.*' => [
// @phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassBeforeLastUsed
function ($attribute, $value, $fail) {
if (strpos(trim($value), ' ') !== false) {
$fail(trans('Les espaces ne sont pas autorisés dans les codes INUAV'));
}
if (count($this->code_inuav) > count(array_unique($this->code_inuav))) {
$fail(trans('Les codes INUAVS doinvent être uniques'));
}
$q = CafelEggBreeder::query();
$q->where(function ($q) {
foreach ($this->code_inuav as $inuav) {
$q->orWhere('code_inuav', 'LIKE', "%$inuav%");
}
});
// * Update condition
if ($this->eleveur) {
$q->where('id', '!=', $this->eleveur->id);
}
if ($q->count()) {
$fail(trans('Les codes INUAVS doinvent être uniques'));
}
}
],
'exploitation' => 'nullable|string',
'aboutyou' => 'nullable|string',
'vocation' => 'nullable|string',
'likeinjob' => 'nullable|string',
'loue_means' => 'nullable|string',
'photo1' => 'sometimes|mimetypes:image/jpeg|max:1000',
'photo2' => 'sometimes|mimetypes:image/jpeg|max:1000',
'marquage_oeuf' => 'required|string|max:12',
'marquage_b1' => 'required|string|max:14',
'marquage_b2' => 'required|string|max:14',
];
}
/**
* Get the error messages for the defined validation rules.
*
* @return array
*/
public function messages()
{
return [
'photo1.max' => 'La Photo 1 ne doit pas dépasser 500 Ko',
'photo1.uploaded' => 'La Photo 1 ne doit pas dépasser 500 Ko',
'photo1.mimetypes' => 'La Photo 1 doit être un jpg',
'photo2.max' => 'La Photo 2 ne doit pas dépasser 500 Ko',
'photo2.mimetypes' => 'La Photo 2 doit être un jpg',
'photo2.uploaded' => 'La Photo 2 ne doit pas dépasser 500 Ko',
];
}
}

View file

@ -0,0 +1,19 @@
<?php
namespace App\Http\Requests;
class UpdateEleveurRequest extends StoreEleveurRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return \array_merge(parent::rules(), [
'code_cafel' => 'nullable|string|min:1|max:100|unique:eleveurs,code_cafel,' . $this->eleveur->id,
'code_ede' => 'required|string|min:1|max:100|unique:eleveurs,code_ede,' . $this->eleveur->id
]);
}
}

View file

@ -0,0 +1,32 @@
<?php
namespace App\Jobs\Arcadia;
use App\Models\TraceaEgg;
use App\Models\TraceaPoultry;
class RemoveOldXmlEntries
{
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
try {
$q = TraceaPoultry::query();
$q->where('exp_date', '<=', now()->subMonths(config('tracea.keepPoultryMonths', 18)));
$q->delete();
} catch (\Exception $e) {
report($e);
}
try {
$q = TraceaEgg::query();
$q->where('dcr', '<=', now()->subMonths(config('tracea.keepEggMonths', 12)))->destroy();
$q->delete();
} catch (\Exception $e) {
report($e);
}
}
}

View file

@ -0,0 +1,366 @@
<?php
namespace App\Jobs\Arcadia;
use App\Enums\LogType;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
abstract class XArcadiaFlux implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/**
* The Laravel disk name
*
* @var string
*/
protected $disk = null;
/**
* This is for Laravel Console usage
* @var \Illuminate\Console\Command|null
*/
public $console = null;
/**
* This is for Laravel Console usage
* @var \Symfony\Component\Console\Helper\ProgressBar|null
*/
public $progressBar = null;
/**
* invalid xml folder
*
* @var string
*/
protected $invalidFolderName = 'invalid';
/**
* The relative folder where to archive data
*
* @var string
*/
private $archiveFolderName = 'archives';
/**
* The files to ignore
*
* @var array
*/
protected $ignoreFiles = [
'.gitignore', '.gitkeep'
];
/**
* Check if the file extension
*
* @param string $filename
* @param string $extension
* @return boolean
*/
protected function checkExtension(string $filename, string $extension): bool
{
$isExtension = strtolower(pathinfo($filename, \PATHINFO_EXTENSION)) === $extension;
if (!$isExtension) {
Log::warning(sprintf(
'%s : unwanted file type in %s wanted %s',
get_class($this),
$filename,
$extension
));
}
return $isExtension;
}
/**
* Move the file to invalid folder
*
* @param string $filename
* @return void
*/
protected function moveToInvalid(string $filename): void
{
$newFileName = $filename;
if (!$this->getDisk()->exists($filename)) {
$this->log(
sprintf(
'File %s could not be moved to invalid (not found)',
$filename
),
LogType::warning()
);
return;
}
if ($this->getDisk()->exists(sprintf('%s/%s', $this->invalidFolderName, $filename))) {
$ext = \pathinfo($filename, \PATHINFO_EXTENSION);
$newFileName = \sprintf(
'%s_%d.%s',
\substr($filename, 0, 0 - (strlen($ext) + 1)),
\time(),
$ext
);
}
try {
if (!$this->getDisk()->move($filename, sprintf('%s/%s', $this->invalidFolderName, $newFileName))) {
$this->log(
sprintf(
'File %s could not be moved to invalid',
$filename
),
LogType::warning()
);
}
} catch (\Exception $e) {
$this->log(
sprintf(
'File %s could not be moved to invalid',
$filename
),
LogType::warning()
);
}
}
/**
* Suppression des fichiers dans
* invalid qui ont plus de 6 mois
*
* @return void
*/
protected function clearOldInvalids(): void
{
$disk = $this->getDisk();
$invalids = $disk->files($this->invalidFolderName);
// /** @var File */
foreach ($invalids as $invalid) {
$pi = \pathinfo($invalid, \PATHINFO_BASENAME);
if (in_array($pi, $this->ignoreFiles)) {
continue;
}
if ($disk->lastModified($invalid) < strtotime(Carbon::now()->subMonth(6))) {
if (!$disk->delete($invalid)) {
Log::critical(sprintf('%s : Could not delete file %s', get_class($this), $invalid));
};
}
}
}
/**
* Move the file to archives
*
* @param string $filename
* @return void
*/
protected function moveToArchives(string $filename): void
{
$newFileName = $filename;
if (!$this->getDisk()->exists($filename)) {
$this->log(
sprintf(
'File %s could not be moved to archives (not found)',
$filename
),
LogType::warning()
);
return;
}
if ($this->getDisk()->exists(sprintf('%s/%s', $this->archiveFolderName, $filename))) {
$ext = \pathinfo($filename, \PATHINFO_EXTENSION);
$newFileName = \sprintf(
'%s_%d.%s',
\substr($filename, 0, 0 - (strlen($ext) + 1)),
\time(),
$ext
);
}
try {
if (!$this->getDisk()->move($filename, sprintf('%s/%s', $this->archiveFolderName, $newFileName))) {
$this->log(
sprintf(
'File %s could not be moved to archives',
$filename
),
LogType::warning()
);
}
} catch (\Exception $e) {
$this->log(
sprintf(
'File %s could not be moved to archives',
$filename
),
LogType::warning()
);
}
}
/**
* Suppression des fichiers dans
* archives qui ont plus de 2j
*
* @return void
*/
protected function clearOldArchives(): void
{
$disk = $this->getDisk();
$archives = $disk->files($this->archiveFolderName);
// /** @var File */
foreach ($archives as $archive) {
$pi = \pathinfo($archive, \PATHINFO_BASENAME);
if (in_array($pi, $this->ignoreFiles)) {
continue;
}
if ($disk->lastModified($archive) < strtotime(Carbon::now()->subDays(2))) {
if (!$disk->delete($archive)) {
Log::critical(sprintf('%s : Could not delete file %s', get_class($this), $archive));
};
}
}
}
/**
* Get the concerned disk
*
* @return Filesystem
*/
protected function getDisk(): Filesystem
{
return Storage::disk($this->disk);
}
/**
* Logs data
*
* @param string $message
* @param LogType $logtype
* @return void
* @throws \ErrorException If logtype is not handled.
*/
protected function log(string $message, LogType $logtype = null): void
{
if (!$logtype) {
$logtype = LogType::debug();
}
$message = sprintf('%s : %s', get_class($this), $message);
switch ($logtype->value) {
case LogType::debug()->value:
Log::debug($message);
break;
case LogType::info()->value:
Log::info($message);
break;
case LogType::log()->value:
Log::log($message);
break;
case LogType::warning()->value:
Log::warning($message);
break;
case LogType::error()->value:
Log::error($message);
break;
case LogType::critical()->value:
Log::critical($message);
break;
default:
throw new \ErrorException(sprintf('%s : unhandled log type %s', get_class($this), $logtype->label));
} //end switch
$this->consolePrint($message, $logtype);
}
/**
* Prints to the console
*
* @param string $message
* @param LogType $logtype
* @return void
* @throws \ErrorException If logtype is not handled.
*/
protected function consolePrint(string $message, LogType $logtype): void
{
$this->clearProgressBarFromLine();
if ($this->console) {
switch ($logtype->value) {
case LogType::debug()->value:
case LogType::info()->value:
case LogType::log()->value:
$this->console->info($message);
break;
case LogType::warning()->value:
$this->console->comment($message);
break;
case LogType::error()->value:
case LogType::critical()->value:
$this->console->error($message);
break;
default:
throw new \ErrorException(sprintf('%s : unhandled log type %s', get_class($this), $logtype->label));
}
}
}
/**
* Start ProgressBar
*
* @param integer $total
* @return void
*/
protected function startProgressBar(int $total)
{
if ($this->console) {
$this->progressBar = $this->console->getOutput()
->createProgressBar($total - 1);
$this->progressBar->start();
}
}
/**
* Clear the line to write someting
*
* @return void
*/
protected function clearProgressBarFromLine()
{
if ($this->progressBar) {
$this->progressBar->clear();
}
}
/**
* Increment 1 on progress bar
*
* @return void
*/
protected function incrementProgressBar()
{
if ($this->progressBar) {
$this->progressBar->advance();
}
}
/**
* End the progress bar
*
* @return void
*/
protected function endProgressBar()
{
if ($this->progressBar) {
$this->progressBar->finish();
}
}
}

View file

@ -0,0 +1,65 @@
<?php
namespace App\Jobs\Arcadia;
use App\Models\TraceaEgg;
class XmlFluxEggJob extends XmlJobs
{
/**
* The xsd file path used to validate files
*
* @var string|null
*/
protected $xsdSchemaPath = 'resources/documents/traca/oeuf.xsd';
/**
* Disk name from config/filesystems.php
*
* @var string
*/
protected $disk = 'flux_egg';
/**
* The columns to take from the XML subcolumns can be added with a dot
*
* @var array
*/
protected $takeColumns = [
'code_boite' => 'box_code',
'code_ede' => 'ede_code',
'date_de_ponte' => 'laying_date',
'code_produit' => 'product_code',
'lib_produit' => 'product_label',
'lot_externe' => 'external_lot',
'dcr' => 'dcr',
'ean_13' => 'ean_13'
];
/**
* The columns allowed to be null
*
* @var array
*/
protected $nullableFields = [];
/**
* Fields that are unique
*
* @var array
*/
protected $uniqueKeyField = [];
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassBeforeLastUsed
$this->parseData('ML', TraceaEgg::class, null, function ($uniqueColumnsKey, $line) {
TraceaEgg::insert($line);
});
}
}

View file

@ -0,0 +1,74 @@
<?php
namespace App\Jobs\Arcadia;
use App\Models\TraceaPoultry;
class XmlFluxPoultryJob extends XmlJobs
{
/**
* The xsd file path used to validate files
*
* @var string|null
*/
protected $xsdSchemaPath = 'resources/documents/traca/cavol.xsd';
/**
* Disk name from config/filesystems.php
*
* @var string
*/
protected $disk = 'flux_poultry';
/**
* The columns to take from the XML subcolumns can be added with a dot
*
* @var array
*/
protected $takeColumns = [
'code_art' => 'item_code',
'article' => 'article',
'lot_code_externe' => 'external_code_lot',
'code_eleveur' => 'breeder_code',
'num_commande' => 'order_num',
'lot_opa' => 'opa_lot',
'gencod_prix' => 'barcode_price',
'gencod_poids' => 'barcode_weight',
'lot_abattoir' => 'abattoir_lot',
'client_commande' => 'customer_order',
'enseigne' => ' sign',
'marque' => 'brand',
'famille' => 'family',
'date_expe' => 'exp_date',
'date_de_prep' => 'prep_date'
];
/**
* The columns allowed to be null
*
* @var array
*/
protected $nullableFields = [
'barcode_price',
'barcode_weight'
];
/**
* Fields that are unique
*
* @var array
*/
protected $uniqueKeyField = [
'item_code', 'order_num', 'external_code_lot'
];
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$this->parseData('HT', TraceaPoultry::class);
}
}

View file

@ -0,0 +1,441 @@
<?php
namespace App\Jobs\Arcadia;
use App\Enums\LogType;
use App\Exceptions\AbortXmlImportException;
use App\Exceptions\InvalidXmlException;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
abstract class XmlJobs extends XArcadiaFlux
{
/**
* The xsd file path used to validate files
*
* @var string|null
*/
protected $xsdSchemaPath = null;
/**
* The xsd file content used to validate files
*
* @var string|null
*/
protected $xsdSchema = null;
/**
* The columns to take from the XML
* subcolumns can be added with a dot
*
* @var array
*/
protected $takeColumns = [];
/**
* The columns allowed to be null
*
* @var array
*/
protected $nullableFields = [];
/**
* Need to encapsulate the freeking XML
* Because provided one is dirty
*
* @var boolean
*/
protected $encapsulate = false;
/**
* Parse Data from the XML and gives it to the callback
*
* @param string $entityName
* @param string $modelClass
* @param callable $afterParseCallback After parse is done.
* @param callable $saveCallback Instead of updateOrCreate, execute $saveCallback.
* @param callable $afterSaveCallback After save is done.
* @return void
* @throws InvalidXmlException If xml file is not valid.
* @throws \ErrorException If no unique columns nor $saveCallback are provided.
* @phpcs:disable Generic.Metrics.CyclomaticComplexity.MaxExceeded
*/
protected function parseData(
string $entityName,
string $modelClass,
callable $afterParseCallback = null,
callable $saveCallback = null,
callable $afterSaveCallback = null
): void {
/** @var Filesystem */
$disk = $this->getDisk();
$this->log('Démarrage du traitement');
$this->assertXsdIsHereIfAny();
$files = $disk->files();
$total = count(array_filter($files, function ($filename) {
if ($this->fileHasToBeIgnored($filename)) {
return false;
}
return true;
}));
$this->startProgressBar($total);
foreach ($files as $filename) {
if ($this->fileHasToBeIgnored($filename)) {
continue;
}
$this->incrementProgressBar();
try {
/** @var string $data */
$data = $disk->get($filename);
$this->validateXmlFile($filename, $data);
try {
if ($this->encapsulate) {
$data = sprintf('<Root>%s</Root>', $data);
/** @var \SimpleXMLElement|false */
$xmlContent = simplexml_load_string($data);
} else {
/** @var \SimpleXMLElement|false */
$xmlContent = simplexml_load_string($data, null, LIBXML_NOCDATA | LIBXML_PARSEHUGE);
}
if ($xmlContent === false) {
throw new InvalidXmlException('XML is Invalid (simplexml_load_string returned false)');
}
} catch (\ErrorException $e) {
throw new InvalidXmlException('XML is Invalid', 0, $e);
}
$data = $this->extract($xmlContent);
$lines = [];
// * Multiple Entities within file
if (isset($data[$entityName])) {
foreach ($data[$entityName] as $traca) {
$line = $this->processFields($traca);
if ($afterParseCallback) {
$afterParseCallback($xmlContent, $line);
}
$lines[] = $line;
}
} else {
// * Only one entity within file
$line = $this->processFields($data);
if ($afterParseCallback) {
$afterParseCallback($xmlContent, $line);
}
$lines[] = $line;
}
// * Mise en base des données
foreach ($lines as $line) {
/** @var array Unique Key columns */
$uniqueColumnsKey = [];
foreach ($this->uniqueKeyField as $uField) {
$uniqueColumnsKey[$uField] = $line[$uField];
}
if ($saveCallback) {
$saveCallback($uniqueColumnsKey, $line);
if ($afterSaveCallback) {
$afterSaveCallback($xmlContent, $line);
}
} elseif (count($uniqueColumnsKey)) {
forward_static_call_array(
[$modelClass, 'updateOrCreate'],
[$uniqueColumnsKey, $line]
);
if ($afterSaveCallback) {
$afterSaveCallback($xmlContent, $line);
}
} else {
throw new \ErrorException('Data not saved');
}
} //end foreach
} catch (InvalidXmlException $e) {
$message = $e->getMessage();
$this->log(
sprintf(
'File %s could not be parsed => %s on line %d',
$filename,
$message,
$e->getLine()
),
LogType::critical()
);
$this->sendInvalidXmlEmail($filename, $e);
$this->moveToInvalid($filename);
continue;
} catch (AbortXmlImportException $e) {
$this->log(
sprintf(
'ERROR: File %s could not be parsed => %s on line %d',
$filename,
$e->getMessage(),
$e->getLine()
),
LogType::error()
);
report($e);
continue;
// * ignore the file
} catch (QueryException $e) {
$this->log(implode(' ', $e->errorInfo), LogType::critical());
report($e);
continue;
} catch (FileNotFoundException $e) {
// This happens because of concurent xml jobs read.
$message = $e->getMessage();
$this->log(
sprintf(
'ERROR: File %s could not be read (not found) => %s on line %d',
$filename,
$message,
$e->getLine()
),
LogType::debug()
);
continue;
// * ignore the file
} catch (\Exception | \ErrorException | \TypeError $e) {
$this->log(
sprintf(
'File %s could not be parsed => %s on line %d',
$filename,
$e->getMessage(),
$e->getLine()
),
LogType::critical()
);
report($e);
continue;
// * ignore the file
} //end try
$this->moveToArchives($filename);
} //end foreach
// Clear old invalids.
$this->clearOldInvalids();
// Clear old archives.
$this->clearOldArchives();
$this->endProgressBar();
}
/**
* Recursive extract to array
*
* @param \SimpleXMLElement|false $sxe
* @return array
*/
protected function extract($sxe = null): array
{
if (!$sxe instanceof \SimpleXMLElement) {
return array();
}
$extract = array();
foreach ($sxe->children() as $key => $value) {
if ($value->count()) {
$extract[$key][] = $this->extract($value);
continue;
}
$value = strval($value);
if (array_key_exists($key, $extract) and is_array($extract[$key])) {
$extract[$key][] = strlen($value) ? $value : null;
} else {
$extract[$key] = strlen($value) ? $value : null;
}
}
return $extract;
}
/**
* Process fields to gather data
*
* @param array $fields
* @return array
* @throws AbortXmlImportException If a field could not be validated.
*/
protected function processFields(array $fields): array
{
$result = [];
foreach ($fields as $key => $field) {
if (!($key = $this->shouldFieldBeConsidered($key))) {
continue;
}
if (!$this->isFieldNullable($key) && is_null($field)) {
throw new AbortXmlImportException(sprintf('The field %s is not allowed to be null', $key));
}
if (is_array($field)) {
// * Flatten data
$it = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($field));
foreach ($it as $k => $f) {
$ko = strtolower(sprintf('%s.%s', $key, $k));
if (!$this->isFieldNullable($ko) && is_null($f)) {
throw new AbortXmlImportException(sprintf(
'%s : The field %s is not allowed to be null',
get_class($this),
$ko
));
}
if (!($k = $this->shouldFieldBeConsidered($ko))) {
continue;
}
$result[$k] = $f;
}
} else {
$result[$key] = $field;
}
} //end foreach
return $result;
}
/**
* Is the filed nullable
*
* @param string $key
* @return boolean
*/
private function isFieldNullable(string $key): bool
{
if (in_array($key, $this->nullableFields)) {
return true;
}
return false;
}
/**
* - replace key name with the corresponding alias
* - strtolower the key
* - snake_case the key
*
* @param string $key
* @return string|false
*/
private function shouldFieldBeConsidered(string $key)
{
$key = strtolower($key);
foreach ($this->takeColumns as $k => $alias) {
if (strtolower($k) === $key) {
return Str::snake(strtolower($alias));
}
}
return false;
}
/**
* Is the file to be ignored
*
* @param string $filename
* @return boolean
*/
protected function fileHasToBeIgnored(string $filename): bool
{
return in_array($filename, $this->ignoreFiles) or !$this->checkExtension($filename, 'xml');
}
/**
* Check if the file is an xml file
*
* @param string $filename
* @return boolean
*/
protected function isFileXml(string $filename): bool
{
$isXml = strtolower(pathinfo($filename, \PATHINFO_EXTENSION)) === 'xml';
if (!$isXml) {
Log::warning(sprintf('%s : unwanted file type in %s', get_class($this), $filename));
}
return $isXml;
}
/**
* Send invalid XML email
*
* @param string $filename
* @param \Throwable $e
* @return void
*/
protected function sendInvalidXmlEmail(string $filename, \Throwable $e)
{
$message = $e->getPrevious()->getMessage();
Mail::send('mails.invalidxml', [
'strError' => sprintf(
'File %s could not be parsed => %s on line %d',
$filename,
$message,
$e->getLine()
),
'filename' => $filename,
'exception' => $e->getPrevious()
], function ($m) {
$m->to(
config('mail.contactsList.invalidXml'),
'XML Exception Handler'
)->subject('You sent me an invalid XML file, please check its validity before resend ASAP.');
});
}
/**
* Assert XSD is readable if configured
*
* @return void
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException If xsd file cant be read.
*/
private function assertXsdIsHereIfAny()
{
if ($this->xsdSchemaPath) {
$this->xsdSchema = File::get($this->xsdSchemaPath);
}
}
/**
* Validate Xml file against XSD if loaded
*
* @param string $fileName
* @param string $fileContent
* @return void
* @throws InvalidXmlException If XML could not be parsed or validated against XSD.
* @phpcs:disable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber
*/
private function validateXmlFile(string $fileName, string $fileContent)
{
if ($this->xsdSchema) {
$domDocument = new \DOMDocument('1.0', 'UTF-8');
try {
if (!$domDocument->loadXML($fileContent)) {
throw new InvalidXmlException("XML Validation $fileName content could not be loaded to validate.");
}
if (!$domDocument->schemaValidateSource($this->xsdSchema, LIBXML_SCHEMA_CREATE)) {
throw new InvalidXmlException(
"XML Validation $fileName content could not be validated against xsd."
);
}
} catch (\Exception $e) {
if (\get_class($e) === InvalidXmlException::class) {
throw $e;
}
throw new InvalidXmlException(
"XML Validation $fileName content could not be validated against xsd.",
0,
1,
__FILE__,
__LINE__,
$e
);
} //end try
} //end if
}
}

View file

@ -0,0 +1,39 @@
<?php
namespace App\Jobs;
use App\Lib\CafelApi\Models\CafelBeaVol;
use App\Models\CafelBeaPoultry;
class CafelBeaVolJob extends CafelJobs
{
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$this->syncWithCafelApi(
CafelBeaVol::class,
'cafel.ldc.beavolailles',
[],
function (array $row) {
// * Validate row data
CafelBeaVol::validateDataRow($row);
/** @var array Unique Key columns */
$uniqueColumnsKey = [];
foreach (CafelBeaVol::UNIQUE_COLUMN_KEYS as $uField) {
$uniqueColumnsKey[$uField] = $row[$uField];
}
forward_static_call_array(
[CafelBeaPoultry::class, 'updateOrCreate'],
[$uniqueColumnsKey, $row]
);
}
);
$this->mailInvalidRows(CafelBeaVol::UNIQUE_COLUMN_KEYS, CafelBeaVol::class);
}
}

View file

@ -0,0 +1,75 @@
<?php
namespace App\Jobs;
use App\Exceptions\CafelApiException;
use App\Exceptions\CafelApiImageFetchException;
use App\Lib\CafelApi\Models\CafelEggBreeder as ApiCafelEggBreeder;
use App\Models\CafelEggBreeder;
class CafelEggBreederJob extends CafelJobs
{
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$this->syncWithCafelApi(
ApiCafelEggBreeder::class,
'cafel.ldc.eleveursoeufs',
[],
function (array $row) {
// * Explode inuav
if (\array_key_exists('inuavs', $row)) {
$row['inuavs'] = explode(',', $row['inuavs']);
}
// * Validate row data
ApiCafelEggBreeder::validateDataRow($row);
// * Cast numeric index
$row['cafel_code'] = intval($row['cafel_code']);
// * Fetch pictures
try {
$row['path_picture_1'] = !empty($row['path_picture_1']) ?
ApiCafelEggBreeder::fetchPicture(
(new CafelEggBreeder())->getTable(),
$row['path_picture_1']
) : null;
} catch (CafelApiImageFetchException | CafelApiException $e) {
report($e);
$row['path_picture_1'] = null;
}
try {
$row['path_picture_2'] = !empty($row['path_picture_2']) ?
ApiCafelEggBreeder::fetchPicture(
(new CafelEggBreeder())->getTable(),
$row['path_picture_2']
) : null;
} catch (CafelApiImageFetchException | CafelApiException $e) {
report($e);
$row['path_picture_2'] = null;
}
foreach (['exploitation', 'aboutyou', 'vocation', 'likeinjob', 'loue_means'] as $fieldName) {
$row[$fieldName] = !empty($row[$fieldName]) ? $row[$fieldName] : null;
}
/** @var array Unique Key columns */
$uniqueColumnsKey = [];
foreach (ApiCafelEggBreeder::UNIQUE_COLUMN_KEYS as $uField) {
$uniqueColumnsKey[$uField] = $row[$uField];
}
forward_static_call_array(
[CafelEggBreeder::class, 'updateOrCreate'],
[$uniqueColumnsKey, $row]
);
}
);
$this->mailInvalidRows(ApiCafelEggBreeder::UNIQUE_COLUMN_KEYS, ApiCafelEggBreeder::class);
}
}

48
app/Jobs/CafelFoodJob.php Normal file
View file

@ -0,0 +1,48 @@
<?php
namespace App\Jobs;
use App\Lib\CafelApi\Models\CafelFood as ApiModelCafelFood;
use App\Models\CafelFood;
class CafelFoodJob extends CafelJobs
{
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$dateDebut = now()->subDays(config('cafel.food_retain', 30));
$this->syncWithCafelApi(
ApiModelCafelFood::class,
'cafel.ldc.aliments',
[
'dateDebut' => $dateDebut->format('Y-m-d'),
'dateFin' => now()->format('Y-m-d')
],
function (array $row) {
// * Validate row data
ApiModelCafelFood::validateDataRow($row);
/** @var array Unique Key columns */
$uniqueColumnsKey = [];
foreach (ApiModelCafelFood::UNIQUE_COLUMN_KEYS as $uField) {
$uniqueColumnsKey[$uField] = $row[$uField];
}
forward_static_call_array(
[CafelFood::class, 'updateOrCreate'],
[$uniqueColumnsKey, $row]
);
}
);
$this->mailInvalidRows(ApiModelCafelFood::UNIQUE_COLUMN_KEYS, ApiModelCafelFood::class);
// * DeleteOld Food
// * Garder une interstice de X jours entre la suppression et ce qu'on récupère de CAFEL
CafelFood::whereDate('delivery_date', '<', $dateDebut->subDays(config('cafel.food_retain', 30)))
->delete();
}
}

117
app/Jobs/CafelJobs.php Normal file
View file

@ -0,0 +1,117 @@
<?php
namespace App\Jobs;
use App\Lib\CafelApi\Models\CafelClientModel;
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\Mail;
use Illuminate\Validation\ValidationException;
abstract class CafelJobs implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/**
* Invalid Rows that should be reported.
*
* @var array
*/
private $invalidRows = [];
/**
* Sync with with cafel api using paginate method.
*
* @param string $apiClassName The CafelClientModel class to use.
* @param string $routeName The route name to use.
* @param array $args Arguments to pass.
* @param callable $saveCallback The save callback to use.
* @return void
* @throws \ErrorException If $apiClassName is not a CafelClientModel class.
*/
protected function syncWithCafelApi(string $apiClassName, string $routeName, array $args, callable $saveCallback)
{
if (!is_subclass_of($apiClassName, CafelClientModel::class)) {
throw new \ErrorException(sprintf(
'%s n\'est pas une class de type %s',
$apiClassName,
CafelClientModel::class
));
}
$pageNumber = 0;
$perPage = 100;
$args = array_merge([
'routeName' => $routeName,
'page' => $pageNumber,
'pageSize' => $perPage
], $args);
do {
/** @var array $result */
$result = \forward_static_call_array([$apiClassName, 'paginate'], $args);
$args['page'] = ++$pageNumber;
foreach ($result as $row) {
if (!is_array($row)) {
throw new \ErrorException(\sprintf(
'Unexpected type for $row got %s',
\gettype($row)
));
}
try {
$saveCallback($row);
} catch (ValidationException $e) {
$this->invalidRows[] = collect($row)->put('validation_message', collect($e->errors())
->mapWithKeys(function (array $messages, string $attribute) {
return [$attribute => collect($messages)->implode(', ')];
})->implode(' '))->all();
}
}
} while (!empty($result));
}
/**
* Send an email with invalid rows
*
* @param array $uniqueKeys
* @param string $jobClass
* @return void
*/
protected function mailInvalidRows(array $uniqueKeys, string $jobClass)
{
/** @var array Unique Key columns */
$invalidRowKeys = [];
$uniqueKeys = \array_merge(['validation_message'], $uniqueKeys);
\collect($this->invalidRows)
->map(function ($invalidRow) use ($uniqueKeys, &$invalidRowKeys) {
$o = [];
foreach ($uniqueKeys as $uField) {
$o[$uField] = $invalidRow[$uField];
}
$invalidRowKeys[] = $o;
});
if (!count($invalidRowKeys)) {
return;
}
Mail::send('mails.invalidApiRows', [
'invalidkeys' => $invalidRowKeys,
'jobClass' => $jobClass
], function ($m) {
$m->to(
config('mail.contactsList.invalidCafel'),
sprintf('%s Exception Handler', config('app.name'))
)->subject('There are invalid data sheets provided by Cafel api.');
});
}
}

View file

@ -0,0 +1,49 @@
<?php
namespace App\Jobs;
use App\Lib\CafelApi\Models\CafelMepEgg;
use App\Models\CafelEggMiseEnPlace;
class CafelMepEggJob extends CafelJobs
{
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$dateDebut = now()->subDays(config('cafel.mises_en_places_retain', 370));
$this->syncWithCafelApi(
CafelMepEgg::class,
'cafel.ldc.mepoeufs',
[
'dateDebut' => $dateDebut->format('Y-m-d'),
'dateFin' => now()->format('Y-m-d')
],
function (array $row) {
// * Validate row data
CafelMepEgg::validateDataRow($row);
/** @var array Unique Key columns */
$uniqueColumnsKey = [];
foreach (CafelMepEgg::UNIQUE_COLUMN_KEYS as $uField) {
$uniqueColumnsKey[$uField] = $row[$uField];
}
forward_static_call_array(
[CafelEggMiseEnPlace::class, 'updateOrCreate'],
[$uniqueColumnsKey, $row]
);
}
);
$this->mailInvalidRows(CafelMepEgg::UNIQUE_COLUMN_KEYS, CafelMepEgg::class);
// * DeleteOld MEPs
// * Garder une interstice de X jours entre la suppression et ce qu'on récupère de CAFEL
CafelEggMiseEnPlace::whereDate('transfert_date', '<', $dateDebut->subDays(
config('cafel.mises_en_places_retain', 370)
))->delete();
}
}

View file

@ -0,0 +1,75 @@
<?php
namespace App\Jobs;
use App\Exceptions\CafelApiException;
use App\Exceptions\CafelApiImageFetchException;
use App\Lib\CafelApi\Models\CafelPoultryBreeder as ApiCafelPoultryBreeder;
use App\Models\CafelPoultryBreeder;
class CafelPoultryBreederJob extends CafelJobs
{
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$this->syncWithCafelApi(
ApiCafelPoultryBreeder::class,
'cafel.ldc.eleveursvolailles',
[],
function (array $row) {
// * Explode inuav
if (\array_key_exists('inuavs', $row)) {
$row['inuavs'] = explode(',', $row['inuavs']);
}
// * Validate row data
ApiCafelPoultryBreeder::validateDataRow($row);
// * Cast numeric index
$row['cafel_code'] = intval($row['cafel_code']);
// * Fetch pictures
try {
$row['path_picture_1'] = !empty($row['path_picture_1']) ?
ApiCafelPoultryBreeder::fetchPicture(
(new CafelPoultryBreeder())->getTable(),
$row['path_picture_1']
) : null;
} catch (CafelApiImageFetchException | CafelApiException $e) {
report($e);
$row['path_picture_1'] = null;
}
try {
$row['path_picture_2'] = !empty($row['path_picture_2']) ?
ApiCafelPoultryBreeder::fetchPicture(
(new CafelPoultryBreeder())->getTable(),
$row['path_picture_2']
) : null;
} catch (CafelApiImageFetchException | CafelApiException $e) {
report($e);
$row['path_picture_2'] = null;
}
foreach (['issue_1', 'issue_2'] as $fieldName) {
$row[$fieldName] = !empty($row[$fieldName]) ? $row[$fieldName] : null;
}
/** @var array Unique Key columns */
$uniqueColumnsKey = [];
foreach (ApiCafelPoultryBreeder::UNIQUE_COLUMN_KEYS as $uField) {
$uniqueColumnsKey[$uField] = $row[$uField];
}
forward_static_call_array(
[CafelPoultryBreeder::class, 'updateOrCreate'],
[$uniqueColumnsKey, $row]
);
}
);
$this->mailInvalidRows(ApiCafelPoultryBreeder::UNIQUE_COLUMN_KEYS, ApiCafelPoultryBreeder::class);
}
}

55
app/Lib/CafelApi.php Normal file
View file

@ -0,0 +1,55 @@
<?php
namespace App\Lib;
use App\Exceptions\CafelApiException;
class CafelApi
{
/**
* The api endpoint url
*
* @var string
*/
protected static $endpoint;
/**
* The api user
*
* @var string
*/
protected static $user;
/**
* The api user password
*
* @var string
*/
protected static $password;
/**
* CafelApi
*
* @param string|null $endpoint The api endpoint url.
* @param string|null $user The api user.
* @param string|null $password The api password.
* @throws CafelApiException If cafel.user, cafel.password or
* cafel.endpoint is missing on .env file or in laravel config.
*/
public function __construct(string $endpoint = null, string $user = null, string $password = null)
{
self::$endpoint = self::$endpoint ?: $endpoint;
self::$user = self::$user ?: $user;
self::$password = self::$password ?: $password;
static::$user = static::$user ?: config('cafel.user');
static::$password = static::$password ?: config('cafel.password');
static::$endpoint = static::$endpoint ?: config('cafel.endpoint');
if (!self::$user or !self::$password or !self::$endpoint) {
throw new CafelApiException(
'Either config or .env file need to have the token var set (cafel.user, cafel.password, cafel.endpoint)'
);
}
}
}

View file

@ -0,0 +1,42 @@
<?php
namespace App\Lib\CafelApi\Models;
/**
* @author Jérémy Munsch <jeremy.munsch@ldc.fr>
*/
abstract class CafelBeaVol extends CafelClientModel
{
/**
* Unique columns key
*
* @var array
*/
public const UNIQUE_COLUMN_KEYS = [
'batch_code', 'last_audit_date'
];
/**
* Validation rules from cafel Api
*
* @var array
*/
protected static $validationRules = [
// Eg Score A .
'bea_code' => 'required|string|min:2|max:10',
// Eg 19377/0 .
'batch_code' => 'required|max:10|regex:/^[0-9A-Z]*\/\d$/',
'last_audit_date' => 'required|date_format:Y-m-d'
];
/**
* Column translations
*
* @var array
*/
protected static $columnsTranslations = [
'Bea_score' => 'bea_code',
'Batch_code' => 'batch_code',
'Last_audit_date' => 'last_audit_date'
];
}

View file

@ -0,0 +1,242 @@
<?php
namespace App\Lib\CafelApi\Models;
use App\Enums\HttpMethods;
use App\Exceptions\CafelApiException;
use App\Lib\CafelApi\Transport\ApiInterface;
use App\Lib\CafelApi\Transport\Request;
use App\Lib\FileHelper;
use App\Lib\ToolboxHelper;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
/**
*
* @author Jérémy Munsch <jeremy.munsch@ldc.fr>
*/
abstract class CafelClientModel implements \JsonSerializable
{
/**
* The Api object that will handle requests and responses
*
* @var \App\Lib\CafelApi\Transport\ApiInterface
*/
protected static $apiInterface;
/**
* Validation rules from cafel Api
*
* @var array
*/
protected static $validationRules = [];
/**
* Column translations
*
* @var array
*/
protected static $columnsTranslations = [];
/**
* Create the Api interface
*
* @return void
*/
protected static function setUpApiInterface()
{
self::$apiInterface = self::$apiInterface ?: new ApiInterface();
}
/**
* Generate a Request from the route name
*
* @param string $routeName
* @param array $query Params to pass on to the route.
* @param array $data Http body params.
* @return \App\Lib\CafelApi\Transport\Request
* @throws \ErrorException If the requested route is unknown.
* @throws \ErrorException If a required parameter is missing.
*/
public static function getResquest(string $routeName, array $query = [], array $data = []): Request
{
// Convert bool to integer.
$query = \array_map(function ($v) {
return is_bool($v) ? (int)$v : $v;
}, $query);
$data = \array_map(function ($v) {
return is_bool($v) ? (int)$v : $v;
}, $data);
$routes = config('cafel.routes');
if (!isset($routes[$routeName])) {
throw new \ErrorException("Unknown route $routeName from the crm");
}
$route = $routes[$routeName];
$matches = [];
$matchedIndex = [];
\preg_match_all('/{([\w-]*)}/', $route['uri'], $matches);
if (\count($matches[0])) {
foreach ($matches[0] as $k => $match) {
if (!isset($query[$matches[1][$k]])) {
throw new \ErrorException(sprintf('Missing required parameter %s', $matches[1][$k]));
}
$route['uri'] = str_replace($match, $query[$matches[1][$k]], $route['uri']);
$matchedIndex[$matches[1][$k]] = $query[$matches[1][$k]];
}
}
foreach ($matchedIndex as $key => $value) {
unset($query[$key]);
}
if (count($query)) {
$route['uri'] = sprintf('%s?%s', $route['uri'], \http_build_query($query));
}
return new Request(HttpMethods::make($route['methods'][0]), $route['uri'], [], $data);
}
/**
* Validate data row from api.
*
* @param array $data
* @return void
* @throws \Illuminate\Validation\ValidationException If data does not validate.
*/
public static function validateDataRow(array $data)
{
$validationRules = collect(static::$validationRules)
/** @var string|array $rule */
->mapWithKeys(function ($rules, string $attribute) {
return [
$attribute => is_array($rules) ? collect($rules)
->map(function ($rule) {
// * Handle new rule instance
return \is_array($rule) ? new $rule[0]($rule[1]) : $rule;
})->all() : $rules
];
})->all();
static::validateData($data, $validationRules);
}
/**
* Validate data from api
*
* @param array $data
* @param array $rules
* @return array
* @throws \Illuminate\Validation\ValidationException If data does not validate.
*/
protected function validateData(array $data, array $rules): array
{
return Validator::validate($data, $rules);
}
/**
* Get paginated mises en places
*
* @param string $routeName
* @param integer $page
* @param integer $pageSize
* @param mixed ...$args
* @return array
* @throws \App\Exceptions\CafelApiException If reponse status is KO, or body is not an array.
*/
public static function paginate(string $routeName, int $page, int $pageSize = 100, ...$args): array
{
self::setUpApiInterface();
$request = CafelClientModel::getResquest(
$routeName,
array_merge($args, ['page' => $page, 'pageSize' => $pageSize])
);
$response = self::$apiInterface->call($request);
if (!\is_array($response->body)) {
throw new CafelApiException('Response should have been an array');
}
$out = [];
foreach ($response->body as $row) {
$out[] = static::translateColumns($row);
}
return $out;
}
/**
* Translate row keys
*
* @param array $row
* @return array
*/
protected static function translateColumns(array $row): array
{
foreach (static::$columnsTranslations as $cafelName => $newName) {
$row = static::renameArrKey($row, $cafelName, $newName);
}
return $row;
}
/**
* Rename array key
*
* @param array $arr
* @param string $oldKey
* @param string $newKey
* @return array
*/
protected static function renameArrKey(array $arr, string $oldKey, string $newKey): array
{
// * Failsafe
if (!isset($arr[$oldKey])) {
return $arr;
}
$keys = array_keys($arr);
$keys[array_search($oldKey, $keys)] = $newKey;
$newArr = array_combine($keys, $arr);
return $newArr;
}
/**
* Fetch and store picture to a path
*
* @param string $folder The folder where to put the picture.
* @param string $url The cafel image url.
* @return string The picture path
* @throws \App\Exceptions\CafelApiException If Response is not a valid array.
* @throws \ErrorException If writing to temp file failed.
* @throws \App\Exceptions\CafelApiImageFetchException If invalid image was given or ext could not be confirmed.
* @phpcs:ignore Squiz.Commenting.FunctionCommentThrowTag.WrongNumber
*/
public static function fetchPicture(string $folder, string $url): string
{
/** @var array $query */
parse_str(\parse_url($url, \PHP_URL_QUERY), $query);
$idPhoto = intval($query['idPhoto']);
self::setUpApiInterface();
$request = CafelClientModel::getResquest(
'cafel.ldc.photoeleveur',
['idPhoto' => $idPhoto]
);
$response = self::$apiInterface->call($request);
if (!\is_array($response->body)) {
throw new CafelApiException('Response should have been an array');
}
// * Filter Keys using intersection
\extract(\array_intersect_key($response->body, ['Ext' => '', 'Name' => '', 'Data' => '']));
return ToolboxHelper::storeImage(
$folder,
FileHelper::fromBase64(
Str::lower($Name),
Str::lower($Ext),
$Data
),
false
);
}
}

View file

@ -0,0 +1,97 @@
<?php
namespace App\Lib\CafelApi\Models;
use App\Enums\BreederCivilty;
use Kwaadpepper\Enum\Rules\EnumIsValidRule;
/**
*
* @author Jérémy Munsch <jeremy.munsch@ldc.fr>
*/
abstract class CafelEggBreeder extends CafelClientModel
{
/**
* Unique columns key
*
* @var array
*/
public const UNIQUE_COLUMN_KEYS = [
'cafel_code'
];
/**
* Validation rules from cafel Api
*
* @var array
*/
protected static $validationRules = [
'cafel_code' => 'required|numeric|min:0',
/**
* Un numéro d’identification attribué à l’exploitation
* Un ou des codes œuf qui sont composés de la façon suivante :
* Un chiffre compris entre 0 et 3 qui désigne le mode d’élevage
* (
* 0 pour la production biologique,
* 1 pour la production en plein air,
* 2 pour la production au sol,
* 3 pour la production en cages
* )
* 2 lettres qui représentent le code iso du pays de production (FR pour la France)
* 3 lettres qui désignent le site d’élevage.
* Tous les ateliers d’une même exploitation possèdent la même combinaison de lettres
* 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/',
// 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',
'firstname' => 'required|string|min:1|max:255',
'birth_date' => 'required|date_format:Y-m-d',
'postcode' => 'required|numeric',
'city' => 'required|string|min:1|max:255',
'date_start_operation' => 'required|date_format:Y-m-d',
'inuavs' => 'required|array',
// Eg V072FXT (un seul par ligne).
'inuavs.*' => 'required|string|regex:/^[A-Z]\d{3}[A-Z]{3}$/',
'exploitation' => 'nullable|string',
'aboutyou' => 'nullable|string',
'vocation' => 'nullable|string',
'likeinjob' => 'nullable|string',
'loue_means' => 'nullable|string',
'path_picture_1' => 'nullable|string|regex:/^https:\/\/base\.loue\.fr\/api\/ldc\/photoEleveur\?idPhoto=\d+$/',
'path_picture_2' => 'nullable|string|regex:/^https:\/\/base\.loue\.fr\/api\/ldc\/photoEleveur\?idPhoto=\d+$/',
'marking_egg' => 'required|string|min:1|max:12',
'marking_b1' => 'required|string|min:1|max:14',
'marking_b2' => 'required|string|min:1|max:14'
];
/**
* Column translations
*
* @var array
*/
protected static $columnsTranslations = [
'Cafel_code' => 'cafel_code',
'Ede_code' => 'ede_code',
'Civility' => 'civility',
'Lastname' => 'lastname',
'Firstname' => 'firstname',
'Birthday' => 'birth_date',
'Postcode' => 'postcode',
'City' => 'city',
'Date_start_operation' => 'date_start_operation',
'Inuav_code' => 'inuavs',
'Issue_1' => 'exploitation',
'Issue_2' => 'aboutyou',
'Issue_3' => 'vocation',
'Issue_4' => 'likeinjob',
'Issue_5' => 'loue_means',
'Picture_1_url' => 'path_picture_1',
'Picture_2_url' => 'path_picture_2',
'Egg_marking' => 'marking_egg',
'Box_marking_1' => 'marking_b1',
'Box_marking_2' => 'marking_b2'
];
}

View file

@ -0,0 +1,45 @@
<?php
namespace App\Lib\CafelApi\Models;
use App\Enums\FoodType;
use Kwaadpepper\Enum\Rules\EnumIsValidRule;
/**
* @author Jérémy Munsch <jeremy.munsch@ldc.fr>
*/
abstract class CafelFood extends CafelClientModel
{
/**
* Unique columns key
*
* @var array
*/
public const UNIQUE_COLUMN_KEYS = [
'batch_code', 'delivery_date'
];
/**
* Validation rules from cafel Api
*
* @var array
*/
protected static $validationRules = [
// 1 Pondeuse ou 2 Poulet .
'food_type' => ['required', [EnumIsValidRule::class, FoodType::class]],
// Eg 19377/0 .
'batch_code' => 'required|max:10|regex:/^[0-9A-Z]*\/\d$/',
'delivery_date' => 'required|date_format:Y-m-d'
];
/**
* Column translations
*
* @var array
*/
protected static $columnsTranslations = [
'Food_type' => 'food_type',
'Batch_code' => 'batch_code',
'Delivery_date' => 'delivery_date'
];
}

View file

@ -0,0 +1,42 @@
<?php
namespace App\Lib\CafelApi\Models;
/**
* @author Jérémy Munsch <jeremy.munsch@ldc.fr>
*/
abstract class CafelMepEgg extends CafelClientModel
{
/**
* Unique columns key
*
* @var array
*/
public const UNIQUE_COLUMN_KEYS = [
'batch_code'
];
/**
* Validation rules from cafel Api
*
* @var array
*/
protected static $validationRules = [
// Eg V072FXT (un seul par ligne).
'inuav_code' => 'required|string|regex:/^[A-Z]\d{3}[A-Z]{3}$/',
// Eg 19377/0 .
'batch_code' => 'required|max:10|regex:/^[0-9A-Z]*\/\d$/',
'transfert_date' => 'required|date_format:Y-m-d'
];
/**
* Column translations
*
* @var array
*/
protected static $columnsTranslations = [
'Inuav_code' => 'inuav_code',
'Batch_code' => 'batch_code',
'Transfert_date' => 'transfert_date'
];
}

View file

@ -0,0 +1,67 @@
<?php
namespace App\Lib\CafelApi\Models;
use App\Enums\BreederCivilty;
use Kwaadpepper\Enum\Rules\EnumIsValidRule;
/**
*
* @author Jérémy Munsch <jeremy.munsch@ldc.fr>
*/
abstract class CafelPoultryBreeder extends CafelClientModel
{
/**
* Unique columns key
*
* @var array
*/
public const UNIQUE_COLUMN_KEYS = [
'cafel_code'
];
/**
* Validation rules from cafel Api
*
* @var array
*/
protected static $validationRules = [
'cafel_code' => 'required|numeric|min:0',
// 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',
'firstname' => 'required|string|min:1|max:255',
'birth_date' => 'required|date_format:Y-m-d',
'postcode' => 'required|numeric',
'city' => 'required|string|min:1|max:255',
'date_start_operation' => 'required|date_format:Y-m-d',
'inuavs' => 'required|array',
// Eg V072FXT (un seul par ligne).
'inuavs.*' => 'required|string|regex:/^[A-Z]\d{3}[A-Z]{3}$/',
'issue_1' => 'nullable|string',
'issue_2' => 'nullable|string',
'path_picture_1' => 'nullable|string|regex:/^https:\/\/base\.loue\.fr\/api\/ldc\/photoEleveur\?idPhoto=\d+$/',
'path_picture_2' => 'nullable|string|regex:/^https:\/\/base\.loue\.fr\/api\/ldc\/photoEleveur\?idPhoto=\d+$/',
];
/**
* Column translations
*
* @var array
*/
protected static $columnsTranslations = [
'Cafel_code' => 'cafel_code',
'Civility' => 'civility',
'Lastname' => 'lastname',
'Firstname' => 'firstname',
'Birthday' => 'birth_date',
'Postcode' => 'postcode',
'City' => 'city',
'Date_start_operation' => 'date_start_operation',
'Inuav_code' => 'inuavs',
'Issue_1' => 'issue_1',
'Issue_2' => 'issue_2',
'Picture_1_url' => 'path_picture_1',
'Picture_2_url' => 'path_picture_2',
];
}

View file

@ -0,0 +1,174 @@
<?php
namespace App\Lib\CafelApi\Transport;
use App\Enums\ApiStatus;
use App\Exceptions\CafelApiException;
use App\Lib\CafelApi\Models\CafelClientModel;
/**
* @ignore
*
* This class contains static api credentials
* It handles a request to get a response
*
* @package LDCCrmClient
* @subpackage transport
*/
class ApiInterface
{
/**
* The api endpoint url
*
* @var string
*/
protected static $endpoint;
/**
* The api user
*
* @var string
*/
protected static $user;
/**
* The api user password
*
* @var string
*/
protected static $password;
/**
* The api token
* ! For the service that should be stateless
*
* @var string
*/
protected static $token;
/**
* CafelApi
*
* @param string|null $endpoint The api endpoint url.
* @param string|null $user The api user.
* @param string|null $password The api password.
* @throws \App\Exceptions\CafelApiException If cafel.user, cafel.password or
* cafel.endpoint is missing on .env file or in laravel config. Or
* if authentification to the service failed.
*/
public function __construct(string $endpoint = null, string $user = null, string $password = null)
{
self::$endpoint = self::$endpoint ?: $endpoint;
self::$user = self::$user ?: $user;
self::$password = self::$password ?: $password;
static::$user = static::$user ?: config('cafel.user');
static::$password = static::$password ?: config('cafel.password');
static::$endpoint = static::$endpoint ?: config('cafel.endpoint');
if (!self::$user or !self::$password or !self::$endpoint) {
throw new CafelApiException(
'Either config or .env file need to have the token var set (cafel.user, cafel.password, cafel.endpoint)'
);
}
$this->authenticate();
}
/**
* Login to the api
* !That should be stateless !!!!!
*
* @return void
* @throws CafelApiException If Authentification failed.
*/
private function authenticate()
{
$request = CafelClientModel::getResquest(
'cafel.users.connect',
[],
[
'Login' => static::$user,
'Password' => static::$password
]
);
$response = $this->call($request);
if (!isset($response->body['token'])) {
throw new CafelApiException('Missing api token after authentification');
}
self::$token = $response->body['token'];
}
/**
* Make a crm http call to get a reponse
*
* @param \App\Lib\CafelApi\Transport\Request $request
* @return \App\Lib\CafelApi\Transport\Response
* @throws \App\Exceptions\CafelApiException If reponse status is KO.
*/
public function call(Request $request): Response
{
$response = $this->processRequest($request);
// * Handle response Status.
if ($response->status->equals(ApiStatus::KO())) {
throw new CafelApiException($response->message, $response->httpCode);
}
return $response;
}
/**
* Process request
*
* @param Request $request
* @return Response
*/
private function processRequest(Request $request): Response
{
$this->setCredentials($request);
$this->setHeaders($request);
$request->setEndpoint(self::$endpoint);
/** @var \Psr\Http\Message\ResponseInterface $response */
$response = $request->call();
$status = in_array($response->getStatusCode(), [200, 201]) ?
ApiStatus::OK() : ApiStatus::KO();
return new Response($status, $response);
}
/**
* Add spécific headers to the request
*
* @param Request $request
* @return void
*/
private function setHeaders(Request &$request): void
{
$headers = [
'User-Agent' => sprintf('BOGT CAFEL API client version %s', config('cafel.client_version')),
'Accept' => 'application/json',
'Content-Type' => 'application/json'
];
$request->addHeaders($headers);
}
/**
* Inject bearer credentials into the request
*
* @param \LDC\LDCCRM\Transport\Request $request
* @return void
*/
protected function setCredentials(Request $request)
{
if (self::$token) {
$request->addHeaders([
'Authorization' => implode(',', [
sprintf('Bearer %s', self::$token)
])
]);
}
}
}

View file

@ -0,0 +1,202 @@
<?php
namespace App\Lib\CafelApi\Transport;
use App\Enums\HttpMethods;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request as Psr7Request;
use GuzzleHttp\Psr7\Utils as Psr7Utils;
use GuzzleHttp\RequestOptions;
use GuzzleHttp\Utils as GuzzleHttpUtils;
use Psr\Http\Message\ResponseInterface;
/**
* The LDC CRM request
* Contains the http method, the requested url and data to pass
*
* @property \App\Enums\HttpMethods $method readonly method
* @property string $uri readonly uri
* @property array $headers headers
* @property array $data readonly data
*
* @package LDCCrmClient
* @subpackage transport
*/
class Request
{
/**
* GuzzleHttp client
*
* @var \GuzzleHttp\Client
*/
private $client;
/**
* The http method
*
* @var \App\Enums\HttpMethods
*/
protected $method;
/**
* The http url
*
* @var string
*/
protected $uri;
/**
* Data to pass to the http headers
*
* @var array
*/
protected $headers = [];
/**
* Data to pass to the http body
*
* @var array
*/
protected $data = [];
/**
* Guzzle request
*
* @var callable the returns \GuzzleHttp\Psr7\Request
*/
private $request;
/**
* The Api endpoint
*
* @var string
*/
private $endpoint;
/**
* Request
*
* @param \App\Enums\HttpMethods $method
* @param string $uri
* @param array $headers
* @param array $data
*/
public function __construct(
HttpMethods $method,
string $uri,
array $headers = [],
array $data = []
) {
$this->hidden = function () {
return [];
};
$this->method = $method;
$this->uri = $uri;
$this->data = $data;
$this->headers = $headers;
$this->client = new Client([
RequestOptions::HEADERS => [
'User-Agent' => sprintf(
'BOGT CAFEL API client version %s',
config('cafel.client_version')
)
]
]);
}
/**
* Generic accessor
*
* @param string $field
* @return mixed|null
*/
public function __get(string $field)
{
if (\in_array($field, ['method', 'uri', 'data'])) {
return $this->{$field};
}
return null;
}
/**
* make the guzzle request
*
* @return void
*/
private function makeRequest(): void
{
$this->request = function () {
$uri = $this->uri;
// * If query merge query and data, set data to empty.
if ($this->method->equals(HttpMethods::get())) {
// * Merge query in url with Data
parse_str(\parse_url($uri, \PHP_URL_QUERY) ?? '', $query);
// * Remove query part.
$uri = strtok($uri, '?');
// * Append build query
$uri = sprintf("%s?%s", $uri, http_build_query(array_merge($query, $this->data)));
$this->data = [];
}
$request = new Psr7Request(
\strtoupper($this->method),
sprintf('%s/%s', $this->endpoint, $uri),
$this->headers
);
$request = Psr7Utils::modifyRequest($request, [
'body' => GuzzleHttpUtils::jsonEncode($this->data)
]);
return $request;
};
}
/**
* Set the api endpoint to the request
*
* @param string $endpoint
* @return void
*/
public function setEndpoint(string $endpoint): void
{
$this->endpoint = $endpoint;
}
/**
* Make the Http request
*
* @return ResponseInterface
*/
public function call(): ResponseInterface
{
$this->makeRequest();
/** @var \GuzzleHttp\Psr7\Request */
$request = ($this->request)();
return $this->client->send($request, [
// ! Do not throw HTTP Exceptions.
'http_errors' => false,
'allow_redirects' => false
]);
}
/**
* Add headers to the request
*
* @param array $headers
* @return void
*/
public function addHeaders(array $headers)
{
$this->headers = \array_merge($this->headers, $headers);
}
/**
* Add data to the request
*
* @param array $data
* @return void
*/
public function addData(array $data)
{
$this->data = \array_merge($this->data, $data);
}
}

View file

@ -0,0 +1,126 @@
<?php
namespace App\Lib\CafelApi\Transport;
use App\Enums\ApiStatus;
use App\Exceptions\CafelApiException;
use Psr\Http\Message\ResponseInterface;
/**
* @property int $httpCode The http response code
* @property string $message The api message
* @property array $headers The http reponse headers
* @property array $body The http response body, this is parsed json
* @property ?array $data The reponse data
*
*/
class Response
{
/**
* The response http code
*
* @var integer
*/
private $httpCode = 0;
/**
* The response headers
*
* @var string
*/
private $headers;
/**
* The response body
*
* @var string
*/
private $body;
/**
* The interface message
*
* @var string
*/
private $message;
/**
* PSR response
*
* @var \Psr\Http\Message\ResponseInterface
*/
private $response;
/**
* Response
*
* @param \App\Enums\ApiStatus $status
* @param \Psr\Http\Message\ResponseInterface $response
* @throws \App\Exceptions\CafelApiException If HTTP response body in not JSON.
*/
public function __construct(ApiStatus $status, ResponseInterface $response)
{
$this->response = $response;
$this->status = $status;
$this->httpCode = $response->getStatusCode();
$this->headers = $response->getHeaders();
/** @var \GuzzleHttp\Psr7\Stream */
$this->body = $response->getBody();
if (!in_array($response->getStatusCode(), [200, 201])) {
$this->message = $response->getReasonPhrase();
}
// * 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);
}
throw new CafelApiException('The Api should have returned JSON data');
}
$this->body = $decodedJson;
// * If Api Error.
if ($this->status->equals(ApiStatus::KO())) {
new CafelApiException("CAfel Api responded http code $this->httpCode");
}
return $this;
}
/**
* Generic accessor
*
* @param string $field
* @return mixed|null
*/
public function __get(string $field)
{
if (
\in_array($field, [
'status', 'httpCode', 'headers',
'body', 'message', 'response'
])
) {
return $this->{$field};
}
if ($field === 'data' and isset($this->body[$field])) {
return $this->body[$field];
}
return null;
}
/**
* Try to decode json and return false if it is
* not a valid json
*
* @param string $string
* @return array|false Returns an associative data array or false if failed to parse.
*/
private function tryDecodeJson(string $string)
{
/** @var array|null */
$data = json_decode($string, true);
return (json_last_error() == JSON_ERROR_NONE) ? $data : false;
}
}

104
app/Lib/FileHelper.php Normal file
View file

@ -0,0 +1,104 @@
<?php
namespace App\Lib;
use App\Exceptions\CafelApiImageFetchException;
use Illuminate\Http\File;
use Illuminate\Support\Facades\File as FacadesFile;
use SplFileInfo;
use Symfony\Component\Mime\MimeTypes;
class FileHelper
{
/**
* Generate from blob
*
* @param string $mimeType
* @param string $blob
* @param string|null $fileName
* @return SplFileInfo
* @throws \ErrorException If writing to temp file failed.
*/
public static function fromBlob(string $mimeType, string $blob, string $fileName = null): SplFileInfo
{
// * Create temp file and get its absolute path
if (!($tempFile = tmpfile())) {
new \ErrorException('Could not create temp file');
}
$tempFilePath = stream_get_meta_data($tempFile)['uri'];
// * Save file data in file
if (!(file_put_contents($tempFilePath, $blob))) {
new \ErrorException('Could not write on temp file');
}
$tempFileObject = new File($tempFilePath);
$filePath = $fileName ?? $tempFileObject->getFilename();
$mimeType = $tempFileObject->getMimeType() ?? $mimeType;
$extension = collect((new MimeTypes())->getExtensions($mimeType))->first();
if (!FacadesFile::put(\storage_path("tmp/$filePath.$extension"), $blob)) {
new \ErrorException('Could not write on temp file');
}
// Close this file after response is sent.
// Closing the file will cause to remove it from temp director!
app()->terminating(function () use ($tempFile) {
fclose($tempFile);
});
return new SplFileInfo(\storage_path("tmp/$filePath.$extension"));
}
/**
* Generate from blob
*
* @param string $fileName
* @param string $extension
* @param string $base64String
* @return SplFileInfo
* @throws \ErrorException If writing to temp file failed.
* @throws \App\Exceptions\CafelApiImageFetchException If invalid image was given or ext could not be confirmed.
*/
public static function fromBase64(string $fileName, string $extension, string $base64String): SplFileInfo
{
// * Create temp file and get its absolute path
if (!($tempFile = tmpfile())) {
new \ErrorException('Could not create temp file');
}
$tempFilePath = stream_get_meta_data($tempFile)['uri'];
if (!($blob = \base64_decode($base64String, true))) {
throw new CafelApiImageFetchException("Invalid base64 string given for image '$fileName'");
}
// * Save file data in file
if (!(file_put_contents($tempFilePath, $blob))) {
throw new \ErrorException('Could not write on temp file');
}
$tempFileObject = new File($tempFilePath);
$filePath = $fileName ?? $tempFileObject->getFilename();
$mimeType = $tempFileObject->getMimeType();
$guessedExt = $mimeType ? collect((new MimeTypes())->getExtensions($mimeType))->first() : $extension;
// * Ignore jpeg that is guessed as jpg
if ($guessedExt !== $extension and !($extension === 'jpeg' && $guessedExt === 'jpg')) {
throw new CafelApiImageFetchException(
"Given extension '$extension' could not be confirmed, found '$guessedExt' for image '$fileName'"
);
}
if (!FacadesFile::put(\storage_path("tmp/$filePath.$extension"), $blob)) {
throw new \ErrorException('Could not write on temp file');
}
// Close this file after response is sent.
// Closing the file will cause to remove it from temp director!
app()->terminating(function () use ($tempFile) {
fclose($tempFile);
});
return new SplFileInfo(\storage_path("tmp/$filePath.$extension"));
}
}

217
app/Lib/ToolboxHelper.php Normal file
View file

@ -0,0 +1,217 @@
<?php
namespace App\Lib;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
abstract class ToolboxHelper
{
/**
* Store an image of different types
*
* @param string $table
* @param \Illuminate\Http\UploadedFile|\SplFileInfo|string $image
* @param boolean $randomizePath
* @return string
* @throws \ErrorException If file copy fails.
*/
public static function storeImage(string $table, $image, bool $randomizePath = true): string
{
/** @var \Illuminate\Http\UploadedFile $image */
if (\is_object($image) and get_class($image) === UploadedFile::class) {
$newPath = self::prepareMoveFile($table, $image->getClientOriginalName(), $randomizePath);
$newPath = str_replace(storage_path('app'), '', $newPath);
$image->storePubliclyAs(
pathinfo($newPath, \PATHINFO_DIRNAME),
pathinfo($newPath, \PATHINFO_BASENAME)
);
return 'storage' . str_replace('/public', '', $newPath);
}
/** @var \SplFileInfo $image */
if (\is_object($image) and get_class($image) === \SplFileInfo::class) {
$newPath = self::prepareMoveFile($table, $image->getBaseName(), $randomizePath);
if (!File::copy($image->getRealPath(), $newPath)) {
throw new \ErrorException(sprintf(
'Failed to copy file %s to %s',
$image->getRealPath(),
$newPath
));
}
return \ltrim(str_replace(\storage_path('app/public'), '/storage', $newPath), '/');
}
if (\is_string($image)) {
return $image;
}
}
/**
* Prepare storage path and return
* the image full path
*
* @param string $table Model table name.
* @param string $filename The basename for the file.
* @param boolean $randomizeName Use uuid in name path.
* @return string
*/
private static function prepareMoveFile(string $table, string $filename, bool $randomizeName = true): string
{
$pathFolder = \storage_path(sprintf('app/public/images/%s', $table));
if (!File::exists($pathFolder)) {
File::makeDirectory($pathFolder, 0755, true);
}
$filename = sprintf('%s-%s', $randomizeName ? Str::uuid() : 'R', $filename);
$fullPath = sprintf('%s/%s', $pathFolder, $filename);
if (File::exists($fullPath)) {
File::delete($fullPath);
}
return $fullPath;
}
/**
* Strip scheme (https) on oembed urls
* Only embed allowed are for MP4 self hosted videos right now
*
* https is force by ckeditor MediaElements which natively supports
* only cloud hosted medias (youtube, spotify etc..)
*
* @param string $input
* @return string
*/
public static function stripCkEditorSchemesOnMediaInputs(string $input): string
{
$input = \preg_replace('/(?<=<oembed url=")(https:\/\/)(?=.*?">)/m', '', $input);
return $input;
}
/**
* Assert That no Back Office url is present on txt
*
* @param string $field
* @param string $text
* @return string
* @throws \Illuminate\Validation\ValidationException If url is a bo url.
*/
public static function assertNoInternalBoUrls(string $field, string $text): string
{
$routes = Route::getRoutes();
// * Url replace and email replace.
$text = preg_replace_callback(
// phpcs:ignore Generic.Files.LineLength.TooLong
'/(?P<url>(?:http[s]?:\/\/.)?(?:www\.)?[-a-zA-Z0-9@%._\+~#=]{2,256}\.[a-z]{2,6}\b(?:[-a-zA-Z0-9@:%_\+.~#?&\/\/=]*))/',
function ($matches) use ($routes, $field) {
$match = collect($matches)->first() ?? '';
$url = $match;
try {
$request = Request::create($url);
// If a route is match then it do not throws exception.
if (
\parse_url(config('app.url'), \PHP_URL_HOST) === \parse_url($url, \PHP_URL_HOST) &&
trim($routes->match($request)->getPrefix() ?? '', '/') === 'bo'
) {
// Removes the matched url.
throw ValidationException::withMessages([
$field => sprintf(
'%s : Il est interdit de coller une url du back office dans ce champ',
trans($field)
)
]);
}
return $match;
} catch (NotFoundHttpException $e) {
return $match;
}
},
$text
);
return $text;
}
/**
* Assert That only external url is present on txt
*
* @param string $field
* @param string $text
* @return string
* @throws \Illuminate\Validation\ValidationException If url is a bo url.
*/
public static function assertNoInternalUrls(string $field, string $text): string
{
self::assertNoInternalBoUrls($field, $text);
$routes = Route::getRoutes();
// * Url replace and email replace.
$text = preg_replace_callback(
// phpcs:ignore Generic.Files.LineLength.TooLong
'/(?P<url>(?:http[s]?:\/\/.)?(?:www\.)?[-a-zA-Z0-9@%._\+~#=]{2,256}\.[a-z]{2,6}\b(?:[-a-zA-Z0-9@:%_\+.~#?&\/\/=]*))/',
function ($matches) use ($routes, $field) {
$match = collect($matches)->first() ?? '';
$url = $match;
try {
$request = Request::create($url);
// If a route is match then it do not throws exception.
if (
\parse_url(config('app.url'), \PHP_URL_HOST) === \parse_url($url, \PHP_URL_HOST) &&
$routes->match($request)
) {
// Removes the matched url.
throw ValidationException::withMessages([
$field => sprintf(
'%s : Il est interdit de coller une url de %s dans ce champ',
trans($field),
config('app.name')
)
]);
}
return $match;
} catch (NotFoundHttpException $e) {
return $match;
}
},
$text
);
return $text;
}
/**
* * Register CSP report URI
*
* Put this function inside RouteServiceProvider,
* and call it in RouteServiceProvider::boot
*
* ! Use this in conjonction with kwaadpepper/exception-handler
*
* @return void
*/
public static function cspReportRoute()
{
// * CSP REPORT URI, Please add /csp-report to VerifyCsrfToken $except middleware
\Illuminate\Support\Facades\Route::post('/csp-report', function () {
$isCspRequest = request()->header('Content-Type') === 'application/csp-report';
if (!$isCspRequest or !request()->json('csp-report') or !is_array(request()->json('csp-report'))) {
abort(401);
}
// * Flatten if needed
$cspReport = collect(request()->json('csp-report'))
->flatMap(function ($v, $k) {
return [$k => is_array($v) ? collect($v)->flatten()->implode(', ') : $v];
})->all();
// * Filter array keys
$cspReport = collect(array_intersect_key($cspReport, [
'blocked-uri' => '', 'document-uri' => '', 'original-policy' => '',
'referrer' => '', 'violated-directive' => ''
]));
report(new \Illuminate\Http\Client\HttpClientException(sprintf(
"CSP REPORT for %s : \n %s",
$cspReport->get('document-uri'),
$cspReport->implode("\n")
)));
})->middleware('throttle:5,2')
->withoutMiddleware(\App\Http\Middleware\VerifyCsrfToken::class)
->name('cspReportUri');
}
}

View file

@ -1,38 +0,0 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class MiseEnPlace extends Model
{
public $timestamps = false;
/**
* @var string
*/
protected $table = 'mise_en_place';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'eleveurId_pondeuse',
'code_lot_pondeuse',
'hectares_parcours_pondeuse',
'presence_ruche_pondeuse',
'zone_mellifere_pondeuse',
'nom_couvoir',
'ville_couvoir',
'cp_couvoir',
'raison_sociale_eleveur_poulettes',
'code_inuav_poulettes',
'nom_eleveur_poulettes',
'prenom_eleveur_poulettes',
'ville_eleveur_poulettes',
'cp_eleveur_poulettes',
'date_naissance_poulettes',
'date_transfert_poulettes'
];
}

View file

@ -1,18 +0,0 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Moba extends Model
{
public $timestamps = false;
protected $table = 'moba';
public function getCodeEdesAttribute()
{
return Moba::select('code_ede')->where('code_boite', $this->code_boite)->distinct()->get()->pluck('code_ede');
}
}

15
app/Models/Aliment.php Normal file
View file

@ -0,0 +1,15 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Aliment extends Model
{
/**
* Indicates if the model should be timestamped.
*
* @var boolean
*/
public $timestamps = false;
}

View file

@ -0,0 +1,69 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
class CafelBeaPoultry extends Model
{
/**
* The primary key for the model.
*
* @var string
*/
protected $primaryKey = null;
/**
* Indicates if the IDs are auto-incrementing.
*
* @var boolean
*/
public $incrementing = false;
/**
* Indicates if the model should be timestamped.
*
* @var boolean
*/
public $timestamps = false;
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'last_audit_date' => 'date'
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'bea_code',
'batch_code',
'last_audit_date'
];
// * METHODS
/**
* Get Bea using cafel lot code
*
* @param integer $codeLotCafel
* @return self|null
*/
public static function whereCodeLotCafel(int $codeLotCafel): ?self
{
return Cache::remember("beaCafel$codeLotCafel", 5, function () use ($codeLotCafel) {
return self::where(
'batch_code',
'LIKE',
'%' . \filter_var($codeLotCafel, \FILTER_SANITIZE_STRING) . '/%'
)->first();
});
}
}

View file

@ -0,0 +1,162 @@
<?php
namespace App\Models;
use App\Enums\BreederCivilty;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;
use Kwaadpepper\Enum\Traits\CastsEnums;
class CafelEggBreeder extends Model
{
use CastsEnums;
/**
* The primary key for the model.
*
* @var string
*/
protected $primaryKey = 'cafel_code';
/**
* Indicates if the IDs are auto-incrementing.
*
* @var boolean
*/
public $incrementing = false;
/**
* Indicates if the model should be timestamped.
*
* @var boolean
*/
public $timestamps = false;
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'birth_date' => 'date',
'date_start_operation' => 'date',
'inuavs' => 'array'
];
/**
* Map attribute names to enum classes.
*
* @var array
*/
protected $enumCasts = [
'civility' => BreederCivilty::class
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'cafel_code',
'ede_code',
'civility',
'lastname',
'firstname',
'birth_date',
'postcode',
'city',
'date_start_operation',
'inuavs',
'exploitation',
'aboutyou',
'vocation',
'likeinjob',
'loue_means',
'path_picture_1',
'path_picture_2',
'marking_egg',
'marking_b1',
'marking_b2'
];
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = ['questions'];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted()
{
// * EVENT CLOSURES.
static::creating(function (self $model) {
return self::areInuavCodesUniques($model);
});
static::updating(function (self $model) {
if ($model->getRawOriginal('path_picture_1') !== $model->path_picture_1) {
Storage::delete(\public_path($model->getRawOriginal('path_picture_1')));
}
if ($model->getRawOriginal('path_picture_2') !== $model->path_picture_2) {
Storage::delete(\public_path($model->getRawOriginal('path_picture_2')));
}
return self::areInuavCodesUniques($model);
});
}
// * METHODS
/**
* Questions attribute accessor
*
* @return boolean
*/
public function getQuestionsAttribute(): bool
{
if ($this->aboutyou != null && $this->aboutyou != '') {
return true;
}
if ($this->vocation != null && $this->vocation != '') {
return true;
}
if ($this->likeinjob != null && $this->likeinjob != '') {
return true;
}
if ($this->loue_means != null && $this->loue_means != '') {
return true;
}
return false;
}
/**
* Check if inuav codes are unique
*
* @param self $eleveur
* @return boolean
* @throws \Illuminate\Validation\ValidationException If inuav code is already used.
*/
protected static function areInuavCodesUniques(self $eleveur): bool
{
$q = self::query();
// * Update condition
$q->where(function ($q) use ($eleveur) {
foreach ($eleveur->inuavs as $inuav) {
$q->orWhere('inuavs', 'LIKE', "%$inuav%");
}
});
if ($eleveur->cafel_code) {
$q->where('cafel_code', '!=', $eleveur->cafel_code);
}
if ($q->count()) {
throw ValidationException::withMessages(['inuavs' => 'Les codes INUAVS doinvent être uniques'
]);
}
return true;
}
}

View file

@ -0,0 +1,49 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class CafelEggMiseEnPlace extends Model
{
/**
* The primary key for the model.
*
* @var string
*/
protected $primaryKey = 'batch_code';
/**
* Indicates if the IDs are auto-incrementing.
*
* @var boolean
*/
public $incrementing = false;
/**
* Indicates if the model should be timestamped.
*
* @var boolean
*/
public $timestamps = false;
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'transfert_date' => 'date'
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'batch_code',
'inuav_code',
'transfert_date'
];
}

83
app/Models/CafelFood.php Normal file
View file

@ -0,0 +1,83 @@
<?php
namespace App\Models;
use App\Enums\FoodType;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Kwaadpepper\Enum\Traits\CastsEnums;
class CafelFood extends Model
{
use CastsEnums;
/**
* The primary key for the model.
*
* @var string
*/
protected $primaryKey = 'batch_code';
/**
* Indicates if the IDs are auto-incrementing.
*
* @var boolean
*/
public $incrementing = false;
/**
* Indicates if the model should be timestamped.
*
* @var boolean
*/
public $timestamps = false;
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'delivery_date' => 'date'
];
/**
* Map attribute names to enum classes.
*
* @var array
*/
protected $enumCasts = [
'food_type' => FoodType::class
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'batch_code',
'food_type',
'delivery_date'
];
// * METHODS
/**
* Get Food using cafel lot code
*
* @param \App\Enums\FoodType $food_type
* @param integer $codeLotCafel
* @return self|null
*/
public static function whereCodeLotCafel(FoodType $food_type, int $codeLotCafel): ?self
{
return Cache::remember("foodCafel$codeLotCafel", 5, function () use ($food_type, $codeLotCafel) {
return self::where(
'batch_code',
'LIKE',
'%' . \filter_var($codeLotCafel, \FILTER_SANITIZE_STRING) . '/%'
)->whereFoodType($food_type)->first();
});
}
}

View file

@ -0,0 +1,127 @@
<?php
namespace App\Models;
use App\Enums\BreederCivilty;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;
use Kwaadpepper\Enum\Traits\CastsEnums;
class CafelPoultryBreeder extends Model
{
use CastsEnums;
/**
* The primary key for the model.
*
* @var string
*/
protected $primaryKey = 'cafel_code';
/**
* Indicates if the IDs are auto-incrementing.
*
* @var boolean
*/
public $incrementing = false;
/**
* Indicates if the model should be timestamped.
*
* @var boolean
*/
public $timestamps = false;
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'birth_date' => 'date',
'date_start_operation' => 'date',
'inuavs' => 'array'
];
/**
* Map attribute names to enum classes.
*
* @var array
*/
protected $enumCasts = [
'civility' => BreederCivilty::class
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'cafel_code',
'civility',
'lastname',
'firstname',
'birth_date',
'postcode',
'city',
'date_start_operation',
'inuavs',
'issue_1',
'issue_2',
'path_picture_1',
'path_picture_2',
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted()
{
// * EVENT CLOSURES.
static::creating(function (self $model) {
return self::areInuavCodesUniques($model);
});
static::updating(function (self $model) {
if ($model->getRawOriginal('path_picture_1') !== $model->path_picture_1) {
Storage::delete(\public_path($model->getRawOriginal('path_picture_1')));
}
if ($model->getRawOriginal('path_picture_2') !== $model->path_picture_2) {
Storage::delete(\public_path($model->getRawOriginal('path_picture_2')));
}
return self::areInuavCodesUniques($model);
});
}
// * METHODS
/**
* Check if inuav codes are unique
*
* @param self $breeder
* @return boolean
* @throws \Illuminate\Validation\ValidationException If inuav code is already used.
*/
protected static function areInuavCodesUniques(self $breeder): bool
{
$q = self::query();
// * Update condition
$q->where(function ($q) use ($breeder) {
foreach ($breeder->inuavs as $inuav) {
$q->orWhere('inuavs', 'LIKE', "%$inuav%");
}
});
if ($breeder->cafel_code) {
$q->where('cafel_code', '!=', $breeder->cafel_code);
}
if ($q->count()) {
throw ValidationException::withMessages([
'inuavs' => 'Les codes INUAVS doinvent être uniques'
]);
}
return true;
}
}

68
app/Models/TraceaEgg.php Normal file
View file

@ -0,0 +1,68 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
class TraceaEgg extends Model
{
/**
* The primary key for the model.
*
* @var string
*/
protected $primaryKey = null;
/**
* Indicates if the IDs are auto-incrementing.
*
* @var boolean
*/
public $incrementing = false;
/**
* Indicates if the model should be timestamped.
*
* @var boolean
*/
public $timestamps = false;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'box_code',
'ede_code',
'laying_date',
'product_code',
'product_label',
'external_lot',
'dcr',
'ean_13'
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'laying_date' => 'date',
'dcr' => 'date'
];
/**
* Accessor codes EDE attribute
*
* @return \Illuminate\Database\Eloquent\Collection
*/
public function getCodeEdesAttribute(): Collection
{
return self::select('ede_code')
->where('box_code', $this->box_code)
->distinct()->get()->pluck('ede_code');
}
}

View file

@ -0,0 +1,156 @@
<?php
namespace App\Models;
use App\Enums\FoodType;
use App\Enums\PoultryLabelType;
use App\Traits\HasCompositePrimaryKey;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
class TraceaPoultry extends Model
{
use HasCompositePrimaryKey;
/**
* The primary key for the model.
*
* @var string
*/
protected $primaryKey = [
'item_code', 'order_num',
'external_code_lot'
];
/**
* Indicates if the IDs are auto-incrementing.
*
* @var boolean
*/
public $incrementing = false;
/**
* Indicates if the model should be timestamped.
*
* @var boolean
*/
public $timestamps = false;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'item_code',
'article',
'external_code_lot',
'breeder_code',
'order_num',
'opa_lot',
'barcode_price',
'barcode_weight',
'abattoir_lot',
'customer_order',
'sign',
'brand',
'family',
'exp_date',
'prep_date'
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'exp_date' => 'date',
'prep_date' => 'date'
];
// * METHODS
/**
* Getter Label
*
* @return \App\Enums\PoultryLabelType
*/
public function getLabelAttribute(): PoultryLabelType
{
$family = Str::upper($this->getAttributeFromArray('family'));
switch (true) {
case \strpos($family, 'LABEL') !== false:
return PoultryLabelType::labelRouge();
case \strpos($family, 'BIO') !== false:
return PoultryLabelType::labelRouge();
default:
return PoultryLabelType::unkown();
}
}
/**
* Get associatedBreeder
*
* @return \App\Models\CafelPoultryBreeder|null
*/
public function getBreederAttribute(): ?CafelPoultryBreeder
{
$matches = [];
preg_match('/(?P<inuav>V\d{3}[A-Z]{3})/', \strval($this->breeder_code), $matches);
if (!\array_key_exists('inuav', $matches)) {
return collect();
}
return Cache::remember("traceaPoultryBreeder$this->id", 5, function () use ($matches) {
return CafelPoultryBreeder::where(
'inuavs',
'LIKE',
'%' . \filter_var($matches['inuav'], \FILTER_SANITIZE_STRING) . '%'
)->first();
});
}
/**
* * Get Bea
*
* L'explication du batch code est un non sens.... putin de merde
*
* Comment faisons-nous pour lier notre lot à une note BEA ?
* (code lot sous ce format : XXXXX/0 pour les données BEA) -> Code lot CAFEL / Code OPA
* Comment faisons-nous pour lier notre lot à son alimentation ?
* (code lot sous ce format : XXXXX/0 pour les données alimentation) -> Code lot CAFEL / Code OPA
* Pour ces questions, peux-tu nous dire avec les informations que nous recevons du flux Sablé
* les règles que nous devons utiliser stp ? * -> @Mathilde Hervier peux-tu répondre à cette question ?
* Le 6e champ reçu dans le fichier xml est le code lot OPA qui sert donc à faire le lien avec la CAFEL
*
* @return \App\Models\CafelBeaPoultry|null
*/
public function getBeaAttribute(): ?CafelBeaPoultry
{
// * On utilise code lot_opa vue que son explication de merde est inversée ... Uu
return CafelBeaPoultry::whereCodeLotCafel(\intval($this->opa_lot));
}
/**
* * Get Food
*
*
* L'explication du batch code est un non sens.... putin de merde
*
* Comment faisons-nous pour lier notre lot à une note BEA ?
* (code lot sous ce format : XXXXX/0 pour les données BEA) -> Code lot CAFEL / Code OPA
* Comment faisons-nous pour lier notre lot à son alimentation ?
* (code lot sous ce format : XXXXX/0 pour les données alimentation) -> Code lot CAFEL / Code OPA
* Pour ces questions, peux-tu nous dire avec les informations que nous recevons du flux Sablé
* les règles que nous devons utiliser stp ? * -> @Mathilde Hervier peux-tu répondre à cette question ?
* Le 6e champ reçu dans le fichier xml est le code lot OPA qui sert donc à faire le lien avec la CAFEL
*
* @return \App\Models\CafelFood|null
*/
public function getFoodAttribute(): ?CafelFood
{
// * On utilise code lot_opa vue que son explication de merde est inversée ... Uu
return CafelFood::whereCodeLotCafel(FoodType::chicken(), \intval($this->opa_lot));
}
}

115
app/Models/User.php Normal file
View file

@ -0,0 +1,115 @@
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'username'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted()
{
// * EVENT CLOSURES.
static::creating(function (User $user) {
static::assertUsernameIsUnique($user->id, $user->username);
static::assertEmailIsUnique($user->id, $user->email);
if (Hash::needsRehash($user->password)) {
$user->password = Hash::make($user->password);
}
$user->remember_token = Str::random(10);
});
static::updating(function (User $user) {
static::assertUsernameIsUnique($user->id, $user->username);
static::assertEmailIsUnique($user->id, $user->email);
if (Hash::needsRehash($user->password)) {
$user->password = Hash::make($user->password);
}
$user->remember_token = Str::random(10);
});
}
/**
* Asserts using validation that the email is unique
*
* @param mixed $id
* @param mixed $email
* @return void
* @throws \Illuminate\Validation\ValidationException If user email as already used.
*/
private static function assertEmailIsUnique($id, $email)
{
self::assertFieldIsUnique($id, 'email', $email);
}
/**
* Asserts using validation that the login is unique
*
* @param mixed $id
* @param mixed $login
* @return void
* @throws \Illuminate\Validation\ValidationException If user login as already used.
*/
private static function assertUsernameIsUnique($id, $login)
{
self::assertFieldIsUnique($id, 'username', $login);
}
/**
* Asserts that the field is unique
*
* @param mixed $id
* @param string $field
* @param mixed $value
* @return void
* @throws \Illuminate\Validation\ValidationException If the field is not unique.
*/
private static function assertFieldIsUnique($id, string $field, $value)
{
Validator::make([$field => $value], [
$field => Rule::unique('users', $field)->ignore($id),
], [
$field . '.unique' => trans('La valeur :value pour le champ :attribute est déjà utilisé', [
'attribute' => $field,
'value' => $value
])
])->validate();
}
}

View file

@ -1,10 +1,9 @@
<?php
namespace App;
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class VisuelLibelle extends Model
{
protected $table = 'visuels_libelles';
}

View file

@ -2,8 +2,11 @@
namespace App\Providers;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\URL;
class AppServiceProvider extends ServiceProvider
{
@ -14,7 +17,6 @@ class AppServiceProvider extends ServiceProvider
*/
public function register()
{
//
}
/**
@ -22,15 +24,26 @@ class AppServiceProvider extends ServiceProvider
*
* @return void
*/
public function boot(Request $request)
public function boot()
{
$proxy_url = env('PROXY_URL');
$host = $request->getHost();
if($this->app->environment('dev')) {
\URL::forceScheme('https');
} elseif($this->app->environment('production')) {
\URL::forceRootUrl($proxy_url);
\URL::forceScheme('https');
}
URL::forceScheme('https');
// * HA PROXY FIX
App::singleton('clientIp', function () {
if (config('app.env') === 'local') {
return request()->getClientIp();
} else {
return request()->server('HTTP_X_FORWARDED_FOR') ??
request()->getClientIp();
}
});
// * LOCAL FORCE eg: for Carbon
setlocale(LC_ALL, \sprintf(
'%s_%s.UTF-8',
config('app.locale'),
\strtoupper(config('app.locale'))
));
Carbon::setLocale(config('app.locale'));
Paginator::useBootstrap();
}
}

View file

@ -3,7 +3,6 @@
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
class AuthServiceProvider extends ServiceProvider
{
@ -24,7 +23,5 @@ class AuthServiceProvider extends ServiceProvider
public function boot()
{
$this->registerPolicies();
//
}
}

Some files were not shown because too many files have changed in this diff Show more