diff --git a/.env.example b/.env.example index 61908c1..f86eaea 100644 --- a/.env.example +++ b/.env.example @@ -7,7 +7,7 @@ APP_URL=http://localhost LOG_CHANNEL=stack DB_CONNECTION=mysql -DB_HOST=127.0.0.1 +DB_HOST=dev-mysql DB_PORT=3306 DB_DATABASE=homestead DB_USERNAME=homestead @@ -20,8 +20,8 @@ SESSION_DRIVER=file SESSION_LIFETIME=120 MAIL_DRIVER=smtp -MAIL_HOST=smtp.mailtrap.io -MAIL_PORT=2525 +MAIL_HOST=dev-mailpit +MAIL_PORT=1025 MAIL_USERNAME=null MAIL_PASSWORD=null MAIL_ENCRYPTION=null diff --git a/.gitignore b/.gitignore index 179bfe8..d9f19a3 100644 --- a/.gitignore +++ b/.gitignore @@ -27,3 +27,10 @@ npm-debug.log yarn-error.log .npmrc /tests/coverage + + + + +/.npm +.zshrc +/.composer diff --git a/Dockerfile b/Dockerfile index 520028d..b732c9e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM registry.s-web.fr/ldc-web/projets/ldc-web-images-docker/ldcweb-production-7.3:latest +FROM registry.s-web.fr/ldc-web/projets/ldc-web-images-docker/ldcweb-production-7.3:060825-070701 COPY --chown=www-data:www-data . /app/srcs USER root RUN chmod -R 755 /app/srcs/storage diff --git a/README.md b/README.md new file mode 100644 index 0000000..483591a --- /dev/null +++ b/README.md @@ -0,0 +1,14 @@ +# MesBR + +## Tests unitaires + +```bash +cp .env .env.testing + +// Update db vars + +php artisan test +``` + +## Gestion du Legacy +Au moment de la suppression du legacy, ne pas oublier de refaire les factory au propre pour les models \ No newline at end of file diff --git a/app/Console/Commands/ArchiveStatsCommand.php b/app/Console/Commands/ArchiveStatsCommand.php new file mode 100644 index 0000000..a7bd49f --- /dev/null +++ b/app/Console/Commands/ArchiveStatsCommand.php @@ -0,0 +1,49 @@ +handle(); + + $this->info(sprintf( + '%s archive(s) created', + ArchiveStat::count() - $baseArchiveStatCount + )); + $this->info(sprintf( + '%s stat(s) deleted', + $baseStatCount - Statistique::count() + )); + $this->info('Stats archived 👌'); + } +} diff --git a/app/Console/Commands/CustomersClaims.php b/app/Console/Commands/CustomersClaims.php new file mode 100644 index 0000000..a5d1eb0 --- /dev/null +++ b/app/Console/Commands/CustomersClaims.php @@ -0,0 +1,89 @@ + '01/10/2025', + 'delphine.byon@hotmail.fr' => '30/09/2025', + 'aurel_del@hotmail.fr' => '27/09/2025', + 'katy.lancelot@orange.fr' => '26/09/2025' + ]; + + $emails = array_keys($claims); + + // On récupère les contact dont l'identifiant est un ID de CRM + $contacts = Contact::whereIn('contact_email', $emails) + ->where('contact_siteId', '=', $siteId) + ->get(); + + $toAdd = []; + + // Pour chaque contact + foreach ($contacts as $contact) { + + $claimDate = Carbon::createFromFormat('d/m/Y', $claims[$contact->contact_email])->format('Y-m-d'); + + // On vient chercher les paniers dont la date de création est >= à la date de la récla + $paniers = $contact->paniers()->where('panier_createdate', '>=', $claimDate)->get(); + + foreach ($paniers as $panier) { + foreach ($panier->panierContents as $content) { + $contactEmail = $contact->contact_email; + $campId = $panier->panier_campId; + $couponId = $content->panier_content_couponId; + + if (!isset($toAdd[$contactEmail][$campId])) { + $toAdd[$contactEmail][$campId] = []; + } + if (!isset($toAdd[$contactEmail][$campId][$couponId])) { + $toAdd[$contactEmail][$campId][$couponId] = 0; + } + + $toAdd[$contactEmail][$campId][$couponId] += $content->panier_content_printed; + } + } + } + + dd($toAdd); + + return 0; + } +} diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 47a25ff..f3e5531 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -4,10 +4,12 @@ namespace App\Console; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; -use App\Site; -use App\Campagne; -use App\User; -use App\Notification; +use App\Models\Site; +use App\Models\Campagne; +use App\Jobs\ArchiveStatsJob; +use App\Jobs\CleanOldDatasJob; +use App\Models\User; +use App\Models\Notification; use App\Mail\AlertBr; use App\Mail\AlertBrAdmin; use Illuminate\Support\Facades\Mail; @@ -23,7 +25,9 @@ class Kernel extends ConsoleKernel * @var array */ protected $commands = [ - ]; + \App\Console\Commands\CustomersClaims::class, + \App\Console\Commands\ArchiveStatsCommand::class, + ]; /** * Define the application's command schedule. @@ -33,6 +37,12 @@ class Kernel extends ConsoleKernel */ protected function schedule(Schedule $schedule) { + // Archive stats every day at 2:00 AM (to prevent time difference between the server and the reality). + $schedule->job(ArchiveStatsJob::class)->dailyAt('2:00'); + + // Clean datas older than 3 years every day at midnight. + $schedule->job(CleanOldDatasJob::class)->daily(); + // ---- Commande d'alerte appelé tt les jours de la semaine a 7h00 $schedule->call(function () { $sites = Site::all(); @@ -40,7 +50,7 @@ class Kernel extends ConsoleKernel $couponDiffusionGlobal = array(); $sendGlobal = false; foreach ($sites as $site) { -// ---- Pour chaque site + // ---- Pour chaque site $campagnes = Campagne::where(['camp_siteId' => $site->site_id])->get(); foreach ($campagnes as $campagne) { $sendMail = false; @@ -54,16 +64,16 @@ class Kernel extends ConsoleKernel $coupon->coupon_left = $this->getFullQuantity($coupon) - $this->getUsedQuantity($coupon); if ($coupon->coupon_left < $coupon->coupon_seuil_alert) { array_push($couponSeuil, $coupon); - array_push($couponSeuilGlobal, [$site->site_nom , $coupon]); + array_push($couponSeuilGlobal, [$site->site_nom, $coupon]); $sendGlobal = true; $couponAlert = true; } // --- Check MaxDateDiffusion if ($coupon->coupon_maxdatediffusion != null && strtotime($coupon->coupon_maxdatediffusion) < (time() + (30 * 24 * 60 * 60))) { -// Fin de diffusion dans moins de 30jours + // Fin de diffusion dans moins de 30jours array_push($couponDiffusion, $coupon); - array_push($couponDiffusionGlobal, [$site->site_nom , $coupon]); + array_push($couponDiffusionGlobal, [$site->site_nom, $coupon]); $sendGlobal = true; $couponAlert = true; } @@ -80,14 +90,14 @@ class Kernel extends ConsoleKernel } $sendMail = true; } - }//end if - }//end foreach + } //end if + } //end foreach if ($sendMail) { Mail::to($users)->send(new AlertBr($couponSeuil, $couponDiffusion, $site->site_nom)); } - }//end foreach - }//end foreach + } //end foreach + } //end foreach if ($sendGlobal) { $superadmins = array(); $admins = User::where(['roles' => 'superadmin'])->get(); @@ -100,59 +110,5 @@ class Kernel extends ConsoleKernel Mail::to($superadmins)->send(new AlertBrAdmin($couponSeuilGlobal, $couponDiffusionGlobal)); } })->weekdays()->at('7:00'); - - // ---- Sauvegarde des stats tous les jours a 23:45 - // $schedule->call(function () { - // $campagnes = Campagne::all(); - // foreach ($campagnes as $campagne) { - // $last_stat = Statistique::where(['stat_campId' => $campagne->camp_id])->orderBy('created_at', 'DESC')->first(); - // if(isset($last_stat->created_at)){ - // $dateStart = $last_stat->created_at; - // } else { - // $dateStart = Carbon::now()->setTime(0,0,0)->subMonth()->format('Y-m-d H:i:s'); - // } - // $coupons = $campagne->coupons()->get(); - // foreach ($coupons as $coupon) { - // if ($campagne->camp_type == 0 || $campagne->camp_type == 2) { //Calcul des BR consommé pour les murs - // $counts = Mur::selectRaw('count(*) as count, DATE_FORMAT(mur_createdate, "%Y-%m-%d") as date') - // ->where(['mur_couponId' => $coupon->coupon_id, 'mur_campid' => $campagne->camp_id]) - // ->whereBetween('mur_createdate', [$dateStart, Carbon::now()->setTime(23,59,59)->format('Y-m-d H:i:s')]) - // ->groupBy(DB::raw("DATE_FORMAT(mur_createdate, '%Y-%m-%d')")) - // ->pluck('count', 'date'); - // foreach($counts as $date => $count){ - // $stat = new Statistique(); - // $stat->stat_campId = $campagne->camp_id; - // $stat->stat_couponId = $coupon->coupon_id; - // $stat->stat_couponPrinted = $count; - // $stat->created_at = $date; - // $stat->save(); - // } - // } - // else { //Calcul des BR consommé pour les paniers - // $count = 0; - // $paniers = Panier::where('panier_campId', $campagne->camp_id)->where(function($query) use ($dateStart){ - // $query->whereBetween('panier_createdate', [$dateStart, Carbon::now()->setTime(23,59,59)->format('Y-m-d H:i:s')]) - // ->orWhereBetween('panier_updatedate', [$dateStart, Carbon::now()->setTime(23,59,59)->format('Y-m-d H:i:s')]); - // })->get(); - // foreach ($paniers as $panier) { - // $panierContentCount = $panier->panierContents()->where(['panier_content_couponId' => $coupon->coupon_id])->sum('panier_content_printed'); - // $count = $count + $panierContentCount; - // } - // } - // } - // } - // })->everyFifteenMinutes(); - } - - /** - * Register the commands for the application. - * - * @return void - */ - protected function commands() - { - $this->load(__DIR__ . '/Commands'); - - require base_path('routes/console.php'); } } diff --git a/app/Enums/CampaignTypes.php b/app/Enums/CampaignTypes.php new file mode 100644 index 0000000..3c05ef7 --- /dev/null +++ b/app/Enums/CampaignTypes.php @@ -0,0 +1,39 @@ + 0, + 'panier' => 1, + 'murss' => 2, + 'paniers' => 3, + ]; + } + + protected static function labels(): array + { + return [ + 'mur' => trans('Mur'), + 'panier' => trans('Panier'), + 'murss' => trans('Mur sans sélection'), + 'paniers' => trans('Panier Sélectionnable'), + ]; + } +} diff --git a/app/Enums/Countries.php b/app/Enums/Countries.php new file mode 100644 index 0000000..276ea17 --- /dev/null +++ b/app/Enums/Countries.php @@ -0,0 +1,32 @@ + 250, + 'belgique' => 56, + 'luxembourg' => 442, + ]; + } + + protected static function labels(): array + { + return [ + 'france' => 'France', + 'belgique' => 'Belgique', + 'luxembourg' => 'Luxembourg', + ]; + } +} diff --git a/app/Enums/LogActions.php b/app/Enums/LogActions.php new file mode 100644 index 0000000..3b639dd --- /dev/null +++ b/app/Enums/LogActions.php @@ -0,0 +1,32 @@ + 1, + 'impression' => 3, + 'updatecontact' => 4, + ]; + } + + protected static function labels(): array + { + return [ + 'updatebasket' => 'Mise à jour du panier', + 'impression' => 'Impression', + 'updatecontact' => 'Mise à jour du contact', + ]; + } +} diff --git a/app/Enums/UserRoles.php b/app/Enums/UserRoles.php new file mode 100644 index 0000000..7eee8cd --- /dev/null +++ b/app/Enums/UserRoles.php @@ -0,0 +1,32 @@ + 'superadmin', + 'admin' => 'admin', + 'marketing' => 'marketing' + ]; + } + + protected static function labels(): array + { + return [ + 'superadmin' => trans('Super-Admin'), + 'admin' => trans('Admin'), + 'marketing' => trans('Marketing') + ]; + } +} diff --git a/app/Http/Controllers/AjaxController.php b/app/Http/Controllers/AjaxController.php index 5b814ad..a4f1195 100644 --- a/app/Http/Controllers/AjaxController.php +++ b/app/Http/Controllers/AjaxController.php @@ -2,19 +2,16 @@ namespace App\Http\Controllers; -use App\Campagne; -use App\Coupon; -use App\Contact; -use App\Panier; -use App\PanierContent; -use App\Statistique; -use App\Mur; -use App\Log; +use App\Models\Campagne; +use App\Models\Coupon; +use App\Enums\CampaignTypes; +use App\Models\PanierContent; +use App\Models\Statistique; +use App\Models\Mur; +use App\Models\Log; use Illuminate\Http\Request; use App\Traits\GenerateBR; use App\Traits\CouponTrait; -use App\Http\Controllers; -use Carbon\Carbon; class AjaxController extends Controller { @@ -48,7 +45,7 @@ class AjaxController extends Controller } // ---- Dépublie un coupon - public function unpublish_coupons_ajax(Request $request) + public function unpublishCouponsAjax(Request $request) { $coupon_id = $request->input('couponid'); $coupon = Coupon::find($coupon_id); @@ -59,7 +56,7 @@ class AjaxController extends Controller } // ---- Publie un coupon - public function publish_coupons_ajax(Request $request) + public function publishCouponsAjax(Request $request) { $coupon_id = $request->input('couponid'); $coupon = Coupon::find($coupon_id); @@ -69,31 +66,8 @@ class AjaxController extends Controller return json_encode($coupon); } - // ---- Dépublie une campagne - public function unpublish_camp_ajax(Request $request) - { - $campid = $request->input('campid'); - $campagne = Campagne::find($campid); - $campagne->camp_published = 0; - $campagne->save(); - - return json_encode($campagne); - } - - // ---- Publie une campagne - public function publish_camp_ajax(Request $request) - { - $campid = $request->input('campid'); - $campagne = Campagne::find($campid); - $campagne->camp_published = 1; - $campagne->save(); - - return json_encode($campagne); - } - - // ---- Impression des BR - public function impression_ajax(Request $request) + public function impressionAjax(Request $request) { if ($request->session()->has('coupons')) { @@ -132,7 +106,7 @@ class AjaxController extends Controller $coupons = ''; $coupons .= ''; html += ''; @@ -34,7 +33,7 @@ $('#addCoupons').on('click', function(event){ $('#addCoupons').parent().find('.inputGroup input').each(function(event){ if($(this).val() == coupon.coupon_id){ $(this).parent('.inputGroup').remove(); - } + } }) $.fancybox.close(); }); @@ -43,7 +42,7 @@ $('#addCoupons').on('click', function(event){ console.log(e.responseText); } }); -}) +}) @@ -59,21 +58,18 @@ $('body').on('click', '.delete-coupon', function(event){ callback : function (value) { if (value) { event.preventDefault(); - + $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('#csrf').val() } }); $.ajax({ - url: '/remove-coupons-ajax', + url: '/bo/campagne/'+ campid +'/remove-coupon/' + couponid, type: 'POST', - data: { - couponid: couponid, - campid: campid - }, + data: {}, dataType: 'JSON', - success: function (reponse) { + success: function (reponse) { trLinked.remove(); var html = "
"; html += ""; @@ -87,7 +83,7 @@ $('body').on('click', '.delete-coupon', function(event){ }); } } - }); + }); }) @@ -114,14 +110,14 @@ $('body').on('click', '.unpublish', function(event){ couponid: couponid }, dataType: 'JSON', - success: function (reponse) { + success: function (reponse) { element.empty().html('') } }); } } }); - + }) $('body').on('click', '.publish', function(event){ @@ -147,14 +143,14 @@ $('body').on('click', '.publish', function(event){ couponid: couponid }, dataType: 'JSON', - success: function (reponse) { + success: function (reponse) { element.empty().html('') } }); } } }); - + }) @@ -175,20 +171,18 @@ $('body').on('click', '.unpublishcamp', function(event){ } }); $.ajax({ - url: '/unpublish-camp-ajax', + url: '/bo/campagne/'+ campid +'/toggle-publish/0', type: 'POST', - data: { - campid: campid - }, + data: {}, dataType: 'JSON', - success: function (reponse) { + success: function (reponse) { element.empty().html('') } }); } } }); - + }) $('body').on('click', '.publishcamp', function(event){ @@ -208,18 +202,16 @@ $('body').on('click', '.publishcamp', function(event){ } }); $.ajax({ - url: '/publish-camp-ajax', + url: '/bo/campagne/'+ campid +'/toggle-publish/1', type: 'POST', - data: { - campid: campid - }, + data: {}, dataType: 'JSON', - success: function (reponse) { + success: function (reponse) { element.empty().html('') } }); } } }); - -}) \ No newline at end of file + +}) diff --git a/resources/js/app.js b/resources/js/app.js index fa3e437..1549c0b 100644 --- a/resources/js/app.js +++ b/resources/js/app.js @@ -306,17 +306,3 @@ $('body').on('click', '.expand', function(event){ contentDiv.slideUp(); } }) - -$('.open-all-stats').on('click', function(event){ - event.preventDefault(); - $('.couponStats .content').each(function(){ - $(this).slideDown(500); - }) -}) - -$('.close-all-stats').on('click', function(event){ - event.preventDefault(); - $('.couponStats .content').each(function(){ - $(this).slideUp(500); - }) -}) \ No newline at end of file diff --git a/resources/views/bo/maintenance/index.blade.php b/resources/views/bo/maintenance/index.blade.php new file mode 100644 index 0000000..04a859b --- /dev/null +++ b/resources/views/bo/maintenance/index.blade.php @@ -0,0 +1,54 @@ +@extends('layouts.main') + +@section('content') + +

+ + {{ __('Maintenance') }} +

+
+
{{ __("Erreur d'appels") }} :
+ +
+@endsection + +@section('scripts') + + +@endsection diff --git a/resources/views/bo/users/create.blade.php b/resources/views/bo/users/create.blade.php new file mode 100644 index 0000000..3e47586 --- /dev/null +++ b/resources/views/bo/users/create.blade.php @@ -0,0 +1,60 @@ +@extends('layouts.main') + +@section('content') +

+ + {{ __('Nouvel utilisateur') }} +

+@if ($errors->any()) +
+ +
+@endif +
+
+ @csrf +
+
+ + +
+
+ + +
+
+
+
+ + +
+
+ + +
+
+

{{ __('Sites liés') }}

+
+ @foreach($sites as $site) +
+ + + +
+ @endforeach +
+
+ {{ __('Les champs avec un * sont obligatoires') }} + +
+ +
+@endsection diff --git a/resources/views/bo/users/edit.blade.php b/resources/views/bo/users/edit.blade.php new file mode 100644 index 0000000..2646848 --- /dev/null +++ b/resources/views/bo/users/edit.blade.php @@ -0,0 +1,56 @@ +@extends('layouts.main') + +@section('content') +

+ + {{ __("Editer l'utilisateur") }} +

+@if ($errors->any()) +
+ +
+@endif +
+
+ @csrf + @method('PUT') +
+
+ + +
+
+ + +
+
+
+
+ + +
+
+

{{ __('Sites liés') }}

+
+ @foreach($sites as $site) +
+ site_id, $usersites)) checked @endif value="{{$site->site_id}}"/> + + +
+ @endforeach +
+
+ +
+ +
+@endsection diff --git a/resources/views/bo/users/index.blade.php b/resources/views/bo/users/index.blade.php new file mode 100644 index 0000000..013fbdf --- /dev/null +++ b/resources/views/bo/users/index.blade.php @@ -0,0 +1,51 @@ +@extends('layouts.main') + +@section('content') + +

+ + {{ __('Users') }} +

+ +
+
+
{{ __('Gestion des utilisateurs') }}
+ {{ __('Ajouter') }} +
+ + @if (isset($users) && count($users) > 0) +
'; - if ($campagne->camp_type == 0) { + if ($campagne->camp_type->equals(CampaignTypes::mur())) { // ---- POUR LES MURS if (!isset($couponsToPrint)) { die(); @@ -167,7 +141,7 @@ class AjaxController extends Controller $stat->save(); }//end if }//end foreach - } elseif ($campagne->camp_type == 1) { + } elseif ($campagne->camp_type->equals(CampaignTypes::panier())) { // ---- POUR LES PANIERS if (!isset($panier)) { die(); @@ -235,7 +209,7 @@ class AjaxController extends Controller $panier->panier_pending = 1; } $panier->save(); - } elseif ($campagne->camp_type == 2) { + } elseif ($campagne->camp_type->equals(CampaignTypes::murss())) { // ---- POUR LES MURS SANS SELECTION $nbCoupon = 0; $cps = $campagne->coupons()->get(); @@ -266,7 +240,7 @@ class AjaxController extends Controller $stat->save(); }//end if }//end foreach - } elseif ($campagne->camp_type == 3) { + } elseif ($campagne->camp_type->equals(CampaignTypes::paniers())) { // ---- POUR LES PANIERS AVEC SELECTION if (!isset($couponsToPrint)) { die(); @@ -335,16 +309,7 @@ class AjaxController extends Controller die(); } - if ($request->session()->has('contact')) { - $contact = $request->session()->get('contact'); - } - - if ($campagne->camp_type == 0 || $campagne->camp_type == 2) { - if (!isset($contact)) { - die(); - } - return redirect(url('/') . '/?refsite=' . $campagne->camp_siteId . '&refcamp=' . $campagne->camp_id . '&hash=' . $contact->contact_hash); - } elseif ($campagne->camp_type == 1 || $campagne->camp_type == 3) { + if ($campagne->camp_type->equals(CampaignTypes::panier()) || $campagne->camp_type->equals(CampaignTypes::paniers())) { if ($request->session()->has('panier')) { $panier = $request->session()->get('panier'); } else { @@ -353,289 +318,4 @@ class AjaxController extends Controller return redirect(url('/') . '/?basketid=' . $panier->panier_ref); } } - - // ---- Charge les widget d'assistance - public function load_widget(Request $request) - { - if (isset($request->camp_id)) { - $camp_id = $request->camp_id; - } else { - die; - } - - if (isset($request->contact_hash)) { - $contact_hash = $request->contact_hash; - } else { - die; - } - - $campagne = Campagne::where(['camp_id' => $camp_id])->first(); - $contact = Contact::where(['contact_hash' => $contact_hash])->first(); - $coupons = $campagne->coupons; - - foreach ($coupons as $key => $coupon) { - if (!$this->isAvailableToPrint($coupon, $campagne)) { - $coupons->forget($key); - } - } - - $allLogs = Log::where(['log_refsite' => $campagne->camp_siteId, 'log_contactId' => $contact->contact_id, 'log_statut' => 'OK'])->orderBy('created_at', 'DESC')->get(); - $logs = array(); - foreach ($allLogs as &$l) { - $params = json_decode($l->log_params); - if ($l->log_action == 3 || $l->log_action == 1) { - $l->log_message = json_decode($l->log_message, true); - } - if (intval($params->refcamp) == $camp_id) { - array_push($logs, $l); - } - } - - if ($campagne->camp_type == 0 || $campagne->camp_type == 2) { -// ---- Pour les types murs - foreach ($coupons as &$coupon) { - $coupon->isAvailable = $this->isAvailable($coupon, $campagne, $contact); - } - unset($coupon); - - // Montant total et Nombre réductions disponible - $montantDispo = 0; - $montantTotal = 0; - $nbCoupon = 0; - foreach ($coupons as $coupon) { - $montantTotal += $coupon->coupon_value; - if ($coupon->isAvailable == true) { - $montantDispo += $coupon->coupon_value; - $nbCoupon++; - } - } - - if (sizeof($coupons) == $nbCoupon) { - $reset = false; - } else { - $reset = true; - } - - $campagne->url = url('/') . "/?refsite=" . $campagne->camp_siteId . "&refcamp=" . $camp_id . "&hash=" . $contact->contact_hash; - - $returnHTML = view('widgets.mur') - ->with([ - 'campagne' => $campagne, - 'reset' => $reset, - 'montantTotal' => $montantTotal, - 'montantDispo' => $montantDispo, - 'logs' => $logs, - 'contact' => $contact]) - ->renderSections()['widget']; - - return json_encode(array('success' => true, 'html' => $returnHTML)); - } else { -// ---- Pour les types paniers - $panier = Panier::where(['panier_campId' => $campagne->camp_id, 'panier_contactId' => $contact->contact_id, 'panier_pending' => 1])->first(); - if ($panier) { - $panier_ref = $panier->panier_ref; - foreach ($coupons as &$coupon) { - $paniercontent = PanierContent::where(['panier_content_couponId' => $coupon->coupon_id, 'panier_content_panierId' => $panier->panier_id])->first(); - if ($paniercontent) { - $coupon->qty = $paniercontent->panier_content_quantity; - } else { - $coupon->qty = 0; - } - } - $campagne->url = url('/') . "/?basketid=" . $panier_ref; - unset($coupon); - } else { - $panier_ref = ""; - foreach ($coupons as &$coupon) { - $coupon->qty = 0; - } - $campagne->url = "Pas d'url disponible (panier non créé)"; - } - - $returnHTML = view('widgets.panier') - ->with([ - 'campagne' => $campagne, - 'contact' => $contact, - 'panier' => $panier_ref, - 'logs' => $logs, - 'coupons' => $coupons - ]) - ->renderSections()['widget']; - return json_encode(array('success' => true, 'html' => $returnHTML)); - }//end if - } - - // ---- Montre les campagnes avec un compte de démo - public function show_demo(Request $request) - { - if (isset($request->camp_id)) { - $camp_id = $request->camp_id; - } else { - die; - } - - $campagne = Campagne::where(['camp_id' => $camp_id])->first(); - $siteId = $campagne->camp_siteId; - $demoContact = Contact::where(['contact_siteId' => $siteId, 'contact_ref' => 'DEMO'])->first(); - - if (!isset($demoContact)) { - $req = new \Illuminate\Http\Request(); - $req->setMethod('POST'); - $req->request->add([ - 'refsite' => $siteId, - 'refadherent' => 'DEMO', - 'prenom' => 'Compte', - 'nom' => 'Démonstration', - 'email' => 'demo@demo.fr', - 'code_postal' => '72000', - 'commune' => 'Le Mans', - 'pays' => 250 - ]); - - $contact = new Controllers\ContactController(); - $res = $contact->updateContact($req); - $demoContact = Contact::where(['contact_siteId' => $siteId, 'contact_ref' => 'DEMO'])->first(); - } - - if ($campagne->camp_type == 0 || $campagne->camp_type == 2) { - // ---- DEMONSTRATION POUR LES MURS - $myRequest = new \Illuminate\Http\Request(); - $myRequest->setMethod('POST'); - $myRequest->request->add(['refcamp' => $camp_id, 'refadherent' => 'DEMO', 'admin' => 1]); - - // ---- EFFACER LES CONTROLES SI EXISTANT - $mur = new Controllers\MurController(); - $res = $mur->deleteControlContact($myRequest); - - // ---- RETOURNE l'URL - $url = "/?refsite=" . $siteId . "&refcamp=" . $camp_id . "&hash=" . $demoContact->contact_hash; - return json_encode($url); - } else { - // ---- DEMONSTRATION POUR LES PANIERS - $panier = Panier::where(['panier_campId' => $camp_id, 'panier_contactId' => $demoContact->contact_id, 'panier_pending' => 1])->first(); - - if ($panier) { - $url = "/?basketid=" . $panier->panier_ref; - } else { - // --- Pas de panier Création d'un nouveau - // --- Récuperation des coupons de la campagne - $coupons = $campagne->coupons()->get(); - - foreach ($coupons as $key => $coupon) { - if (!$this->isAvailableToPrint($coupon, $campagne)) { - $coupons->forget($key); - } - } - - $couponsTotal = sizeof($coupons); - $couponsAdded = 0; - $basketContent = ""; - - foreach ($coupons as $coupon) { - $basketContent .= "(1)" . $coupon->coupon_code; - $couponsAdded++; - if ($couponsAdded != $couponsTotal) { - $basketContent .= ","; - } - } - // --- création de l'objet request - $req = new \Illuminate\Http\Request(); - $req->setMethod('POST'); - $req->request->add([ - 'refsite' => $siteId, - 'refcamp' => $camp_id, - 'refadherent' => $demoContact->contact_ref, - 'nom' => $demoContact->contact_nom, - 'prenom' => $demoContact->contact_prenom, - 'email' => $demoContact->contact_email, - 'code_postal' => $demoContact->contact_cp, - 'commune' => $demoContact->contact_ville, - 'pays' => $demoContact->contact_country, - 'panier' => $basketContent, - 'admin' => 1 - ]); - $panier = new Controllers\PanierController(); - $res = $panier->updateBasket($req); - $url = "/?basketid=" . $res->original['Panier']->Panier; - }//end if - return json_encode($url); - }//end if - } - - // ---- MAINTENANCE : CLEAN DE LA BDD - // ---- Fonction de récap des contacts que l'on va effacer - public function get_clean_contacts_detail(Request $request) - { - $contacts = Contact::where('contact_updatedate', '<', Carbon::now()->subMonth())->get(); - $date = Carbon::now(); - $contact_count = 0; - foreach ($contacts as $contact) { - $paniers = $contact->paniers()->get(); - $canbeDeleted = true; - foreach ($paniers as $panier) { - if ($panier->panier_pending == 1) { - $canbeDeleted = false; - } - } - if ($canbeDeleted) { - $contact_count++; - // $testcontact .= $contact->contact_id.", "; - } - } - return json_encode(['date' => $date, 'contact_count' => $contact_count]); - } - - // ---- Fonction de nettoyage de la base contact - public function clean_contacts(Request $request) - { - $contacts = Contact::where('contact_updatedate', '<', Carbon::now()->subMonth())->get(); - $testcontact = ""; - foreach ($contacts as $contact) { - $paniers = $contact->paniers()->get(); - $canbeDeleted = true; - foreach ($paniers as $panier) { - if ($panier->panier_pending == 1) { - $canbeDeleted = false; - } - } - $murs = $contact->murs()->get(); - if (isset($murs) && !empty($murs)) { - $canbeDeleted = false; - } - if ($canbeDeleted) { - $contact->delete(); - $testcontact .= $contact->contact_id . ", "; - } - } - return json_encode($testcontact); - } - - // ---- Fonction de nettoyage de la base mur - public function clean_walls(Request $request) - { - $murs = Mur::where('mur_createdate', '<', Carbon::now()->subYear())->where(['mur_deleted' => 1])->get(); - $testmur = ""; - foreach ($murs as $mur) { - $mur->delete(); - $testmur .= $mur->mur_id . ", "; - } - return json_encode($testmur); - } - - // ---- Fonction de nettoyage de la base panier et panierContent - public function clean_baskets(Request $request) - { - $paniers = Panier::where('panier_createdate', '<', Carbon::now()->subMonth(2))->where(['panier_pending' => 0])->get(); - $testpanier = ""; - foreach ($paniers as $panier) { - $testpanier .= $panier->panier_id . ": "; - $panierContents = $panier->panierContents()->get(); - foreach ($panierContents as $panierContent) { - $testpanier .= $panierContent->panier_content_id . ', '; - $panierContent->delete(); - } - $panier->delete(); - } - return json_encode($testpanier); - } } diff --git a/app/Http/Controllers/Api/v0/ContactController.php b/app/Http/Controllers/Api/v0/ContactController.php new file mode 100644 index 0000000..3735ed1 --- /dev/null +++ b/app/Http/Controllers/Api/v0/ContactController.php @@ -0,0 +1,114 @@ + 'string', + 'nom' => 'string', + 'refsite' => 'string', + 'prenom' => 'string', + 'email' => 'email', + 'code_postal' => 'string', + 'commune' => 'string', + ]; + + $validated = []; + foreach ($requiredFields as $field => $type) { + $value = $request->input($field); + if (empty($value)) { + return response()->json([ + 'Statut' => 'KO', + 'Code' => 101, + 'Message' => 'Des paramètres de la requête sont mal renseignés ou non présents' + ]); + } + $validated[$field] = $value; + } + + // Validation spécifique pour l'email + if (!filter_var($validated['email'], FILTER_VALIDATE_EMAIL)) { + return response()->json([ + 'Statut' => 'KO', + 'Code' => 101, + 'Message' => 'L\'email fourni n\'est pas valide' + ]); + } + + // Validation du pays (entier ou par défaut) + $pays = $request->input('pays'); + if ($pays !== null && $pays !== '') { + if (!filter_var($pays, FILTER_VALIDATE_INT)) { + return response()->json([ + 'Statut' => 'KO', + 'Code' => 101, + 'Message' => 'Le pays doit être un entier' + ]); + } + $validated['pays'] = $pays; + } else { + $validated['pays'] = 250; + } + + // Recherche du contact existant + $contact = Contact::where([ + 'contact_siteId' => $validated['refsite'], + 'contact_ref' => $validated['refadherent'] + ])->first(); + + // Si le contact n'existe pas, on vérifie le site + if (!$contact) { + $site = Site::where('site_id', $validated['refsite'])->first(); + if (!$site) { + return response()->json([ + 'Statut' => 'KO', + 'Code' => 102, + 'Message' => 'Le site spécifié n\'existe pas' + ]); + } + $contact = new Contact(); + $contact->contact_ref = $validated['refadherent']; + $contact->contact_siteId = $validated['refsite']; + $contact->contact_hash = $request->input('hashcode') ?: strtoupper(md5(uniqid(time(), true))); + } + + // Mise à jour des champs + $contact->contact_prenom = $validated['prenom']; + $contact->contact_nom = $validated['nom']; + $contact->contact_email = $validated['email']; + $contact->contact_cp = $validated['code_postal']; + $contact->contact_ville = $validated['commune']; + $contact->contact_country = $validated['pays']; + $contact->contact_updatedate = now(); + + if ($request->filled('hashcode')) { + $contact->contact_hash = $request->hashcode; + } + + // Sauvegarde et réponse + if ($contact->save()) { + return response()->json([ + 'Statut' => 'OK', + 'contact' => $contact + ]); + } + + return response()->json([ + 'Statut' => 'KO', + 'Code' => 109, + 'Message' => 'Une erreur est survenue' + ]); + } +} diff --git a/app/Http/Controllers/Api/v0/PanierController.php b/app/Http/Controllers/Api/v0/PanierController.php new file mode 100644 index 0000000..99fd064 --- /dev/null +++ b/app/Http/Controllers/Api/v0/PanierController.php @@ -0,0 +1,509 @@ +admin)) { + $source = 'ADMIN'; + } else { + $source = 'API'; + } + // ---- INIT du log + $log = new Log(); + $log->log_action = config('constants.updatebasket'); + $log->log_source = $source; + + if (isset($request->basketid)) { + $basketid = $request->basketid; + if ($basketid != '') { + $panier = Panier::where('panier_ref', $basketid)->first(); + if (!$panier) { + $log->log_params = json_encode(['basketid' => $basketid]); + $log->log_statut = 'NOK'; + $log->log_message = "Le panier n'existe pas"; + $log->save(); + + return response()->json([ + 'Statut' => 'KO', + 'Code' => 106, + 'Message' => 'Le panier n\'existe pas' + ]); + } + + if (isset($request->panier) && $request->panier != "") { + $panier = $request->panier; + $panierTab = explode(",", $panier); + $coupons = array(); + foreach ($panierTab as $panier) { + $pos = strpos($panier, ")"); + if ($pos === false || substr_count($panier, ")") != 1) { + $log->log_params = json_encode(['basketid' => $basketid, 'panier' => $panier]); + $log->log_statut = 'NOK'; + $log->log_message = "Des paramètres de la requête sont mal renseignés ou non présents"; + $log->save(); + return response()->json([ + 'Statut' => 'KO', + 'Code' => 101, + 'Message' => 'Des paramètres de la requête sont mal renseignés ou non présents' + ]); + } + $quantity = substr($panier, 0, $pos); + $quantity = str_replace("(", "", $quantity); + $couponCode = substr($panier, $pos + 1); + + if (is_numeric($quantity) && is_numeric($couponCode)) { + if (isset($coupons[$couponCode])) { + $coupons[$couponCode] = $coupons[$couponCode] + $quantity; + } else { + $coupons[$couponCode] = $quantity; + } + } else { + $log->log_params = json_encode(['basketid' => $basketid, 'panier' => $panier]); + $log->log_statut = 'NOK'; + $log->log_message = "Des paramètres de la requête sont mal renseignés ou non présents"; + $log->save(); + return response()->json([ + 'Statut' => 'KO', + 'Code' => 101, + 'Message' => 'Des paramètres de la requête sont mal renseignés ou non présents' + ]); + } + }//end foreach + // ---- Préparation message de log avec coupons + $panierCoupons = array(); + foreach ($coupons as $code => $qty) { + array_push($panierCoupons, ['cp_code' => $code, 'qty' => $qty]); + } + if (count($coupons) == 0) { + die(); + } + } else { + $log->log_params = json_encode(['basketid' => $basketid, 'panier' => $panier]); + $log->log_statut = 'NOK'; + $log->log_message = "Des paramètres de la requête sont mal renseignés ou non présents"; + $log->save(); + return response()->json([ + 'Statut' => 'KO', + 'Code' => 101, + 'Message' => 'Des paramètres de la requête sont mal renseignés ou non présents' + ]); + }//end if + + // ---- MAJ du panier + $panier = Panier::where('panier_ref', $basketid)->first(); + if ($panier) { + foreach ($coupons as $couponCode => $quantity) { + $cp = Coupon::where('coupon_code', $couponCode)->first(); + $exists = $cp->campagnes->contains($panier->panier_campId); + if ($cp && $exists) { + $site = $cp->coupon_siteId; + $panierContent = PanierContent::where(['panier_content_panierId' => $panier->panier_id, 'panier_content_couponId' => $cp->coupon_id])->first(); + if ($panierContent) { + $quantity += $panierContent->panier_content_quantity; + if ($quantity <= 0) { + $quantity = 0; + } + // MAJ du contenu + $panierContent->panier_content_quantity = $quantity; + $panierContent->save(); + } else { + // Ajout du contenu + if ($quantity > 0) { + $panierNewContent = new PanierContent(); + $panierNewContent->panier_content_panierId = $panier->panier_id; + $panierNewContent->panier_content_couponId = $cp->coupon_id; + $panierNewContent->panier_content_quantity = $quantity; + $panierNewContent->save(); + } + } + } else { + $log->log_params = json_encode(['refcamp' => $request->refcamp, 'refadherent' => $request->refadherent, 'refsite' => $request->refsite, 'nom' => $request->nom, 'prenom' => $request->prenom, 'email' => $request->email, 'code postal' => $request->code_postal, 'commune' => $request->commune, 'panier' => $request->panier]); + $log->log_statut = 'NOK'; + $log->log_message = "Le coupon ne correspond pas aux coupons liés a la campagne"; + $log->save(); + + return response()->json([ + 'Statut' => 'KO', + 'Code' => 110, + 'Message' => 'Le coupon ne correspond pas aux coupons liés a la campagne' + ]); + }//end if + }//end foreach + // MAJ du status du panier + $qty = $panier->panierContents()->sum('panier_content_quantity'); + if ($qty == 0) { + $panier_pending = 0; + } else { + $panier_pending = 1; + } + $panier->panier_pending = $panier_pending; + $panier->save(); + + $campagne = Campagne::where(['camp_id' => $panier->panier_campId])->first(); + $log->log_refsite = $campagne->camp_siteId; + $log->log_contactId = $panier->panier_contactId; + $log->log_params = json_encode(['refcamp' => $panier->panier_campId, 'basketid' => $basketid, 'panier' => $panier]); + $log->log_statut = 'OK'; + $log->log_message = json_encode(['Message' => 'Le panier a bien été créé/mis à jour', 'Coupons' => $panierCoupons], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + $log->save(); + + $contact = Contact::where(['contact_id' => $panier->panier_contactId])->first(); + $site = Site::where(['site_id' => $campagne->camp_siteId])->first(); + + if (isset($contact->contact_nom) && isset($site->site_nom)) { + if ($panier->panier_pending == 1) { + $encours = "oui"; + } else { + $encours = "non"; + } + $response = new \stdClass(); + $response->Site = $site->site_nom . " (" . $site->site_id . ")"; + $response->Campagne = $campagne->camp_name . " (" . $campagne->camp_id . ")"; + $response->Panier = $panier->panier_ref; + $response->DateCreation = date("d/m/Y", strtotime($panier->panier_createdate)); + $response->EnCours = $encours; + $response->Nom = $contact->contact_nom; + $response->Prenom = $contact->contact_prenom; + $response->Email = $contact->contact_email; + $response->CodePostal = $contact->contact_cp; + $response->Commune = $contact->contact_ville; + + $allPanierContent = $panier->panierContents()->get(); + foreach ($allPanierContent as $panierContent) { + $panCont = []; + $coupon = Coupon::where(['coupon_id' => $panierContent->panier_content_couponId])->first(); + if ($coupon) { + array_push($panCont, $coupon->coupon_code . " - " . $coupon->coupon_name . " (x" . $panierContent->panier_content_quantity . ")"); + } + } + + $response->panierContent = $panCont; + + return response()->json([ + 'Statut' => 'OK', + 'Panier' => $response + ]); + } else { + return response()->json([ + 'Statut' => 'OK', + 'Panier' => $panier + ]); + }//end if + } else { + $log->log_params = json_encode(['basketid' => $basketid, 'panier' => $panier]); + $log->log_statut = 'NOK'; + $log->log_message = "Le panier n'existe pas"; + $log->save(); + return response()->json([ + 'Statut' => 'KO', + 'Code' => 106, + 'Message' => 'Le panier n\'existe pas' + ]); + }//end if + } else { + $log->log_params = json_encode(['basketid' => $basketid, 'panier' => $panier]); + $log->log_statut = 'NOK'; + $log->log_message = "Le panier n'existe pas"; + $log->save(); + return response()->json([ + 'Statut' => 'KO', + 'Code' => 106, + 'Message' => 'Le panier n\'existe pas' + ]); + }//end if + } else { + // ---- Contrôle des paramètres + $error = false; + if (isset($request->refcamp) && $request->refcamp != "") { + $refcamp = $request->refcamp; + $campagne = Campagne::where(['camp_id' => $refcamp])->first(); + if (!$campagne || $campagne->camp_published == 0 || ($campagne->camp_type->value != 1 && $campagne->camp_type->value != 3)) { + $log->log_params = json_encode(['refcamp' => $refcamp]); + $log->log_statut = 'NOK'; + $log->log_message = "La campagne n'existe pas ou n'est pas un panier"; + $log->save(); + + return response()->json([ + 'Statut' => 'KO', + 'Code' => 103, + 'Message' => 'La campagne n\'existe pas ou n\'est pas un panier' + ]); + } + } else { + $error = true; + } + if (isset($request->refadherent) && $request->refadherent != "") { + $refadherent = $request->refadherent; + } else { + $error = true; + } + if (isset($request->nom) && $request->nom != "") { + $nom = $request->nom; + } else { + $error = true; + } + if (isset($request->refsite) && $request->refsite != "") { + $refsite = $request->refsite; + if ($refsite != $campagne->camp_siteId) { + return response()->json([ + 'Statut' => 'KO', + 'Code' => 103, + 'Message' => 'La campagne ne correspond à aucune campagnes du site' + ]); + } + } else { + $error = true; + } + if (isset($request->prenom) && $request->prenom != "") { + $prenom = $request->prenom; + } else { + $error = true; + } + if (isset($request->email) && $request->email != "" && filter_var($request->email, FILTER_VALIDATE_EMAIL)) { + $email = $request->email; + } else { + $error = true; + } + + if (isset($request->code_postal) && $request->code_postal != "") { + $code_postal = $request->code_postal; + } else { + $error = true; + } + if (isset($request->commune) && $request->commune != "") { + $commune = $request->commune; + } else { + $error = true; + } + + if (isset($request->pays) && $request->pays != "") { + if (filter_var($request->pays, FILTER_VALIDATE_INT)) { + $pays = $request->pays; + } else { + $error = true; + } + } else { + $pays = 250; + } + if (isset($request->panier) && $request->panier != "") { + $panier = $request->panier; + $panierTab = explode(",", $panier); + $coupons = array(); + foreach ($panierTab as $panier) { + $pos = strpos($panier, ")"); + if ($pos === false) { + $error = true; + } + $quantity = substr($panier, 0, $pos); + $quantity = str_replace("(", "", $quantity); + $couponCode = substr($panier, $pos + 1); + + if (is_numeric($quantity) && is_numeric($couponCode) && $quantity > 0) { + if (isset($coupons[$couponCode])) { + $coupons[$couponCode] = $coupons[$couponCode] + $quantity; + } else { + $coupons[$couponCode] = $quantity; + } + } + } + if (count($coupons) == 0) { + die(); + } + } else { + $error = true; + }//end if + + // ---- Préparation message de log avec coupons + if (isset($coupons)) { + $panierCoupons = array(); + foreach ($coupons as $code => $qty) { + array_push($panierCoupons, ['cp_code' => $code, 'qty' => $qty]); + } + } + + + if ($error) { + $log->log_params = json_encode(['refcamp' => $request->refcamp, 'refadherent' => $request->refadherent, 'refsite' => $request->refsite, 'nom' => $request->nom, 'prenom' => $request->prenom, 'email' => $request->email, 'code postal' => $request->code_postal, 'commune' => $request->commune, 'panier' => $request->panier]); + $log->log_statut = 'NOK'; + $log->log_message = "Des paramètres de la requête sont mal renseignés ou non présents"; + $log->save(); + + return response()->json([ + 'Statut' => 'KO', + 'Code' => 101, + 'Message' => 'Des paramètres de la requête sont mal renseignés ou non présents' + ]); + } + + // ---- Ajout/MAJ du contact + $contact = Contact::where(['contact_siteId' => $refsite, 'contact_ref' => $refadherent])->first(); + if ($contact) { + // ---- Mise à jour du contact + $contact->contact_prenom = $prenom; + $contact->contact_nom = $nom; + $contact->contact_email = $email; + $contact->contact_cp = $code_postal; + $contact->contact_ville = $commune; + $contact->contact_country = $pays; + $contact->contact_updatedate = date('Y-m-d H:i:s'); + } else { + // ---- Création du contact + $site = Site::where('site_id', $refsite)->first(); + + if ($site) { + $contact = new Contact(); + $contact->contact_nom = $nom; + $contact->contact_prenom = $prenom; + $contact->contact_ref = $refadherent; + $contact->contact_email = $email; + $contact->contact_cp = $code_postal; + $contact->contact_ville = $commune; + $contact->contact_country = $pays; + $contact->contact_siteId = $refsite; + $contact->contact_hash = strtoupper(md5(uniqid(time(), true))); + } else { + $log->log_params = json_encode(['refcamp' => $request->refcamp, 'refadherent' => $request->refadherent, 'refsite' => $request->refsite, 'nom' => $request->nom, 'prenom' => $request->prenom, 'email' => $request->email, 'code postal' => $request->code_postal, 'commune' => $request->commune, 'panier' => $request->panier]); + $log->log_statut = 'NOK'; + $log->log_message = "Le site spécifié n'existe pas"; + $log->save(); + + return response()->json([ + 'Statut' => 'KO', + 'Code' => 102, + 'Message' => 'Le site spécifié n\'existe pas' + ]); + }//end if + }//end if + if (!$contact->save()) { + $log->log_params = json_encode(['refcamp' => $request->refcamp, 'refadherent' => $request->refadherent, 'refsite' => $request->refsite, 'nom' => $request->nom, 'prenom' => $request->prenom, 'email' => $request->email, 'code postal' => $request->code_postal, 'commune' => $request->commune, 'panier' => $request->panier]); + $log->log_statut = 'NOK'; + $log->log_message = "Une erreur est survenue"; + $log->save(); + return response()->json([ + 'Statut' => 'KO', + 'Code' => 109, + 'Message' => 'Une erreur est survenue' + ]); + } + + // ---- Ajout/MAJ du panier + $panier = Panier::where(['panier_campId' => $refcamp, 'panier_contactId' => $contact->contact_id, 'panier_pending' => 1])->first(); + if ($panier) { + foreach ($coupons as $couponCode => $quantity) { + $camp = Campagne::where('camp_id', $panier->panier_campId)->first(); + $cp = $camp->coupons()->where('coupon_code', $couponCode)->first(); + if ($cp) { + $panierContent = PanierContent::where(['panier_content_panierId' => $panier->panier_id, 'panier_content_couponId' => $cp->coupon_id])->first(); + if ($panierContent) { + // $quantity += $panierContent->panier_content_quantity; + $panierContent->panier_content_quantity = $quantity + $panierContent->panier_content_quantity; + // MAJ du contenu + $panierContent->save(); + // $panierContent->update(['panier_content_quantity', $quantity]); + } else { + // Ajout du contenu + if ($quantity > 0) { + $panierNewContent = new PanierContent(); + $panierNewContent->panier_content_panierId = $panier->panier_id; + $panierNewContent->panier_content_couponId = $cp->coupon_id; + $panierNewContent->panier_content_quantity = $quantity; + $panierNewContent->save(); + } + } + } + }//end foreach + } else { + // Ajout du panier et du contenu + $panierRef = strtoupper(md5(uniqid(time(), true))); + $panier = new Panier(); + $panier->panier_ref = $panierRef; + $panier->panier_campId = $refcamp; + $panier->panier_contactId = $contact->contact_id; + $panier->panier_createdate = date('Y-m-d H:i:s'); + $panier->save(); + + foreach ($coupons as $couponCode => $quantity) { + $cp = $campagne->coupons()->where('coupon_code', $couponCode)->first(); + if ($cp) { + // Ajout du contenu + if ($quantity > 0) { + $panierNewContent = new PanierContent(); + $panierNewContent->panier_content_panierId = $panier->panier_id; + $panierNewContent->panier_content_couponId = $cp->coupon_id; + $panierNewContent->panier_content_quantity = $quantity; + $panierNewContent->save(); + } + } + } + }//end if + + $log->log_params = json_encode(['refcamp' => $request->refcamp, 'refadherent' => $request->refadherent, 'refsite' => $request->refsite, 'nom' => $request->nom, 'prenom' => $request->prenom, 'email' => $request->email, 'code postal' => $request->code_postal, 'commune' => $request->commune, 'panier' => $request->panier]); + $log->log_contactId = $panier->panier_contactId; + $log->log_refsite = $request->refsite; + $log->log_statut = 'OK'; + $log->log_message = json_encode(['Message' => 'Le panier a bien été créé/mis à jour', 'Coupons' => $panierCoupons], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + $log->save(); + + $contact = Contact::where(['contact_id' => $panier->panier_contactId])->first(); + $site = Site::where(['site_id' => $campagne->camp_siteId])->first(); + + if (isset($contact->contact_nom) && isset($site->site_nom)) { + if ($panier->panier_pending == 1) { + $encours = "oui"; + } else { + $encours = "non"; + } + $response = new \stdClass(); + $response->Site = $site->site_nom . " (" . $site->site_id . ")"; + $response->Campagne = $campagne->camp_name . " (" . $campagne->camp_id . ")"; + $response->Panier = $panier->panier_ref; + $response->DateCreation = date("d/m/Y", strtotime($panier->panier_createdate)); + $response->EnCours = $encours; + $response->Nom = $contact->contact_nom; + $response->Prenom = $contact->contact_prenom; + $response->Email = $contact->contact_email; + $response->CodePostal = $contact->contact_cp; + $response->Commune = $contact->contact_ville; + + $allPanierContent = $panier->panierContents()->get(); + $panCont = []; + foreach ($allPanierContent as $panierContent) { + $coupon = Coupon::where(['coupon_id' => $panierContent->panier_content_couponId])->first(); + if ($coupon) { + array_push($panCont, $coupon->coupon_code . " - " . $coupon->coupon_name . " (x" . $panierContent->panier_content_quantity . ")"); + } + } + + $response->panierContent = $panCont; + + return response()->json([ + 'Statut' => 'OK', + 'Panier' => $response + ]); + } else { + return response()->json([ + 'Statut' => 'OK', + 'Panier' => $panier + ]); + }//end if + }//end if + } +} diff --git a/app/Http/Controllers/Api/v1/BasketController.php b/app/Http/Controllers/Api/v1/BasketController.php new file mode 100644 index 0000000..61661da --- /dev/null +++ b/app/Http/Controllers/Api/v1/BasketController.php @@ -0,0 +1,187 @@ +logAction = LogActions::updatebasket(); + $this->logSource = 'API'; + } + + public function updateBasket(Request $request) + { + // Validate required parameters + $requiredParams = ['customer_hashcode', 'refcamp', 'refsite', 'panier']; + $error = false; + foreach ($requiredParams as $param) { + if (empty($request->{$param})) { + $error = true; + break; + } + } + + if ($error) { + $this->writeLogErrorWrongRequestParameters( + $request->refcamp ?? null, + $request->customer_hashcode ?? null, + $request->refsite ?? null, + $request->panier ?? null + ); + + return response()->json([ + 'Statut' => 'KO', + 'Code' => 101, + 'Message' => 'Des paramètres de la requête sont mal renseignés ou non présents' + ]); + } + + // Validate campaign + $refcamp = $request->refcamp; + $campagne = Campagne::where('camp_id', $refcamp)->first(); + + if (!$campagne || $campagne->camp_published == 0 || !in_array($campagne->camp_type->value, [1, 3])) { + $this->writeLogErrorIncorrectCampaign($refcamp); + return response()->json([ + 'Statut' => 'KO', + 'Code' => 103, + 'Message' => 'La campagne n\'existe pas ou n\'est pas un panier' + ]); + } + + $refsite = $request->refsite; + if ($refsite != $campagne->camp_siteId) { + return response()->json([ + 'Statut' => 'KO', + 'Code' => 103, + 'Message' => 'La campagne ne correspond à aucune campagnes du site' + ]); + } + + // Parse panier + $panierTab = explode(",", $request->panier); + $coupons = []; + foreach ($panierTab as $item) { + $pos = strpos($item, ")"); + if ($pos === false) { + $error = true; + break; + } + + $quantity = str_replace("(", "", substr($item, 0, $pos)); + $couponCode = substr($item, $pos + 1); + + if (is_numeric($quantity) && is_numeric($couponCode) && $quantity > 0) { + if (isset($coupons[$couponCode])) { + $coupons[$couponCode] += $quantity; + } else { + $coupons[$couponCode] = $quantity; + } + } + } + + if (empty($coupons)) { + die(); + } + + if ($error) { + $this->writeLogErrorWrongRequestParameters( + $refcamp, + $request->customer_hashcode, + $campagne->camp_siteId, + $request->panier + ); + + return response()->json([ + 'Statut' => 'KO', + 'Code' => 101, + 'Message' => 'Des paramètres de la requête sont mal renseignés ou non présents' + ]); + } + + // Prepare panierCoupons for logging + $panierCoupons = []; + foreach ($coupons as $code => $qty) { + $panierCoupons[] = ['cp_code' => $code, 'qty' => $qty]; + } + + // Retrieve customer + $customer = Customers::where('hashcode', $request->customer_hashcode)->first(); + + // Retrieve or create basket + $basket = Basket::where(['campagne_id' => $refcamp, 'customer_id' => $customer->id])->first(); + + if ($basket) { + $camp = Campagne::where('camp_id', $basket->campagne_id)->first(); + foreach ($coupons as $couponCode => $quantity) { + $cp = $camp->coupons()->where('coupon_code', $couponCode)->first(); + if ($cp) { + $basketContent = BasketContent::where(['basket_id' => $basket->id, 'coupon_id' => $cp->coupon_id])->first(); + if ($basketContent) { + $basketContent->quantity += $quantity; + $basketContent->save(); + } else { + $this->addContentToBasket($basket, $cp, $quantity); + } + } + } + } else { + $basket = new Basket(); + $basket->uuid = (string) Str::uuid(); + $basket->campagne()->associate($refcamp); + $basket->customer()->associate($customer); + $basket->save(); + + foreach ($coupons as $couponCode => $quantity) { + $cp = $campagne->coupons()->where('coupon_code', $couponCode)->first(); + if ($cp) { + $this->addContentToBasket($basket, $cp, $quantity); + } + } + } + + // Log success + $this->writeLogSuccessBasketCreated( + $refcamp, + $request->customer_hashcode, + $refsite, + $request->panier, + $panierCoupons + ); + + return response()->json([ + 'Statut' => 'OK', + 'Panier' => $basket + ]); + } + + private function addContentToBasket(Basket $basket, Coupon $coupon, int $quantity): void + { + if ($quantity > 0) { + $newBasketContent = new BasketContent(); + $newBasketContent->basket_id = $basket->id; + $newBasketContent->coupon_id = $coupon->coupon_id; + $newBasketContent->quantity = $quantity; + $newBasketContent->save(); + } + } +} diff --git a/app/Http/Controllers/Api/v1/CouponsController.php b/app/Http/Controllers/Api/v1/CouponsController.php index 01b0dee..74c38f2 100644 --- a/app/Http/Controllers/Api/v1/CouponsController.php +++ b/app/Http/Controllers/Api/v1/CouponsController.php @@ -2,14 +2,15 @@ namespace App\Http\Controllers\Api\v1; -use App\Campagne; -use App\Coupon; +use App\Models\Campagne; +use App\Models\Coupon; +use App\Enums\CampaignTypes; use App\Http\Controllers\Controller; use App\Http\Requests\Coupons\PrintRequest; use App\Http\Resources\StatusResource; use App\Models\Customers; -use App\Models\PrintedWalls; -use App\Statistique; +use App\Models\PrintedCoupons; +use App\Models\Statistique; use App\Traits\CouponTrait; use App\Traits\GenerateBR; use PDF; @@ -39,7 +40,7 @@ class CouponsController extends Controller return new StatusResource(['status' => 'KO', 'code' => 422, 'message' => 'Coupons not found.']); } - $crm = new CrmApiV2(config('crm.CRM_ENDPOINT'), $campagne->site->crm_token, $campagne->site->crm_password); + $crm = new CrmApiV2(config('services.crm.endpoint'), $campagne->site->crm_token, $campagne->site->crm_password); try { /** @@ -58,27 +59,13 @@ class CouponsController extends Controller // TODO : Vérifier si les coupons sont dans la campagne // TODO : Logs $coupons = []; - if ($campagne->camp_type == 0) { + if ($campagne->camp_type->equals(CampaignTypes::mur())) { // ---- POUR LES MURS foreach ($couponsToPrint as $key => $coupon_code) { $cp = Coupon::where(['coupon_code' => $coupon_code])->first(); if (!$this->isUsed($cp, $campagne, $customer)) { - $coupons[] = $this->printCoupon($cp, $customer, $crmInfos); - - // ----- mémorise l'impression - $mur = new PrintedWalls(); - $mur->camp_id = $campagne->camp_id; - $mur->customer_id = $customer->id; - $mur->coupon_id = $cp->coupon_id; - $mur->save(); - - // Sauvegarde de stat - $stat = new Statistique(); - $stat->stat_campId = $campagne->camp_id; - $stat->stat_couponId = $cp->coupon_id; - $stat->stat_couponPrinted = 1; - $stat->save(); + $coupons[] = $this->printCoupon($cp, $customer, $crmInfos, $campagne); } }//end foreach }//end if diff --git a/app/Http/Controllers/Api/v1/CustomerController.php b/app/Http/Controllers/Api/v1/CustomerController.php index d3e29cd..458a417 100644 --- a/app/Http/Controllers/Api/v1/CustomerController.php +++ b/app/Http/Controllers/Api/v1/CustomerController.php @@ -2,22 +2,26 @@ namespace App\Http\Controllers\Api\v1; -use App\Calendrier; -use App\Campagne; +use App\Models\Calendrier; +use App\Models\Campagne; +use App\Enums\CampaignTypes; use App\Http\Requests\Customers\StoreRequest; use App\Http\Resources\CustomersResource; use App\Http\Resources\StatusResource; use App\Models\Customers; use App\Http\Controllers\Controller; +use App\Http\Requests\Customers\BasketRequest; use App\Http\Requests\Customers\MurRequest; use App\Http\Resources\CouponsResource; use App\Traits\CouponTrait; +use App\Traits\GenerateBR; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Request; class CustomerController extends Controller { use CouponTrait; + use GenerateBR; /** * Display a listing of the resource. @@ -107,12 +111,22 @@ class CustomerController extends Controller return new StatusResource(['status' => 'KO', 'code' => '501', 'message' => 'Not Implemented']); } + /** + * Recupere le contenu d'un mur pour une campagne et un user + * @param MurRequest $request + * @return StatusResource + * @throws ValidationException + */ public function mur(MurRequest $request) { $datas = $request->validated(); $customer = Customers::where('hashcode', $datas['hashcode'])->first(); $campagne = Campagne::find($datas['refcamp']); + + if (!$campagne->camp_type->equals(CampaignTypes::mur())) { + return new StatusResource(['status' => 'KO', 'code' => 404, 'message' => 'Campaign is not mur.']); + } if ($campagne->camp_published === 0) { return new StatusResource(['status' => 'KO', 'code' => 404, 'message' => 'Campaign not found.']); } @@ -158,4 +172,79 @@ class CustomerController extends Controller 'coupons' => CouponsResource::collection($coupons) ]); } + + /** + * Recupere le contenu d'un panier pour une campagne et un user + * @param BasketRequest $request + * @return StatusResource + * @throws ValidationException + */ + public function basket(BasketRequest $request) + { + $montantDispo = 0; + $montantTotal = 0; + $nbCoupons = 0; + $couponTotal = 0; + $coupons = []; + + $datas = $request->validated(); + + $customer = Customers::where('hashcode', $datas['hashcode'])->first(); + $campagne = Campagne::find($datas['refcamp']); + + if (!$campagne->camp_type->equals(CampaignTypes::panier())) { + return new StatusResource(['status' => 'KO', 'code' => 404, 'message' => 'Campaign is not basket.']); + } + if ($campagne->camp_published === 0) { + return new StatusResource(['status' => 'KO', 'code' => 404, 'message' => 'Campaign not found.']); + } + $basket = $customer->baskets()->where('campagne_id', $campagne->camp_id)->first(); + if (is_null($basket)) { + return new StatusResource(['status' => 'KO', 'code' => 404, 'message' => 'Basket not found.']); + } + + foreach ($basket->contents as $content) + { + $published = true; + $nbCoupons += $content->quantity; + $couponTotal += $content->printed; + $montantTotal += ($content->coupon->coupon_value * $content->printed); + $coupon = $content->coupon()->whereRaw("coupon_published = 1 AND (coupon_mindatediffusion IS NULL OR coupon_mindatediffusion <= NOW()) AND (coupon_maxdatediffusion IS NULL OR coupon_maxdatediffusion >= NOW()) AND (coupon_maxdatevalidity IS NULL OR coupon_maxdatevalidity >= NOW())")->first(); + if (!is_null($coupon)) + { + // ---- Contrôle des calendriers de diffusion + $calendars = Calendrier::where(['calendrier_couponId' => $coupon->coupon_id])->get(); + if (!$calendars->isEmpty()) { + $published = false; + foreach ($calendars as $calendar) { + if (strtotime(date('Y-m-d H:i:s')) > strtotime($calendar->calendrier_startdate) && strtotime(date('Y-m-d H:i:s')) < strtotime($calendar->calendrier_enddate)) { + $published = true; + } + } + } + if ($published){ + $montantDispo += ($coupon->coupon_value * $content->quantity); + $montantTotal += ($coupon->coupon_value * $content->quantity); + $couponTotal += $content->quantity; + $coupons[] = [ + 'quantity' => $content->quantity, + 'printed' => $content->printed, + 'coupon' => new CouponsResource($coupon) + ]; + } + } + } + + return new StatusResource([ + 'status' => "OK", + 'ref' => $basket->uuid, + 'name' => $campagne->camp_name, + 'limited_printing' => $campagne->camp_limitedPrinting, + 'available_coupon' => $nbCoupons, + 'available_amount' => $montantDispo, + 'total_coupon' => $couponTotal, + 'total_amount' => $montantTotal, + 'coupons' => $coupons + ]); + } } diff --git a/app/Http/Controllers/Api/v1/MurController.php b/app/Http/Controllers/Api/v1/MurController.php index b502130..b8ee182 100644 --- a/app/Http/Controllers/Api/v1/MurController.php +++ b/app/Http/Controllers/Api/v1/MurController.php @@ -2,8 +2,9 @@ namespace App\Http\Controllers\Api\v1; -use App\Calendrier; -use App\Campagne; +use App\Models\Calendrier; +use App\Models\Campagne; +use App\Enums\CampaignTypes; use App\Http\Controllers\Controller; use App\Http\Requests\Murs\MursShowRequest; use App\Http\Resources\CouponsResource; @@ -22,7 +23,7 @@ class MurController extends Controller if ($campagne->camp_published === 0) { return new StatusResource(['status' => 'KO', 'code' => 404, 'message' => 'Campaign not found.']); } - if ($campagne->camp_type !== 0) { + if (!$campagne->camp_type->equals(CampaignTypes::mur())) { return new StatusResource(['status' => 'KO', 'code' => 403, 'message' => 'Campaign type error.']); } diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php index 134286c..1677ff8 100644 --- a/app/Http/Controllers/Auth/LoginController.php +++ b/app/Http/Controllers/Auth/LoginController.php @@ -44,6 +44,6 @@ class LoginController extends Controller */ protected function authenticated() { - return redirect()->route('home'); + return redirect('/'); } } diff --git a/app/Http/Controllers/Bo/MaintenanceController.php b/app/Http/Controllers/Bo/MaintenanceController.php new file mode 100644 index 0000000..14fd91a --- /dev/null +++ b/app/Http/Controllers/Bo/MaintenanceController.php @@ -0,0 +1,29 @@ +where('log_statut', 'NOK') + ->where('created_at', '>=', Carbon::now()->subMonths(5)->startOfMonth()) + ->groupBy('month') + ->orderBy('month', 'asc') + ->get(); + + $logs = $datas->toArray(); + + return view('bo.maintenance.index', compact('logs')); + } +} diff --git a/app/Http/Controllers/Bo/UserController.php b/app/Http/Controllers/Bo/UserController.php new file mode 100644 index 0000000..ae4c798 --- /dev/null +++ b/app/Http/Controllers/Bo/UserController.php @@ -0,0 +1,76 @@ +with(['users' => $users, 'logs' => []]); + } + + public function create(Request $request) + { + $sites = Site::all(); + return view('bo.users.create', compact('sites')); + } + + public function store(StoreUserRequest $request) + { + $user = new User(); + $user->fill($request->validated()); + $user->password = Hash::make($request->password); + $user->save(); + + $sites = Site::whereIn('site_id', $request->site)->get()->pluck('id')->toArray(); + $user->sites()->sync($sites); + + return redirect()->route('bo.users.edit', $user); + } + + public function edit(User $user) + { + $sites = Site::all(); + $usersites = $user->sites()->get()->pluck('site_id')->toArray(); + + return view('bo.users.edit', compact('user', 'sites', 'usersites')); + } + + public function update(UpdateUserRequest $request, User $user) + { + $user->fill($request->validated()); + $user->save(); + + $sites = Site::whereIn('site_id', $request->site)->get()->pluck('id')->toArray(); + $user->sites()->sync($sites); + + $marques = Auth::user()->sites; + $submarques = $marques->map(function ($marque) { + return $marque->only(['id', 'site_nom', 'site_id', 'site_logo']); + }); + session()->put('marques', $submarques); + + return redirect()->route('bo.users.edit', $user); + } + + public function destroy(DestroyUserRequest $request, User $user) + { + if ($user->delete()) { + return redirect()->route('bo.users.index'); + } else { + session()->flash('delete_nok', 'Erreur lors de la suppression'); + return view('bo.user.index'); + } + } +} diff --git a/app/Http/Controllers/BrandChangeController.php b/app/Http/Controllers/BrandChangeController.php new file mode 100644 index 0000000..62e1cbd --- /dev/null +++ b/app/Http/Controllers/BrandChangeController.php @@ -0,0 +1,22 @@ +site_id); + session()->put('site', $site); + return redirect()->back(); + } +} diff --git a/app/Http/Controllers/CampagneController.php b/app/Http/Controllers/CampagneController.php index 9fb08b8..8ae7dce 100644 --- a/app/Http/Controllers/CampagneController.php +++ b/app/Http/Controllers/CampagneController.php @@ -2,21 +2,29 @@ namespace App\Http\Controllers; -use App\Campagne; -use App\Site; -use App\Coupon; -use App\Contact; -use App\Mur; -use App\PanierContent; -use App\Notification; +use App\Models\Campagne; +use App\Models\Site; +use App\Models\Coupon; +use App\Models\Contact; +use App\Enums\CampaignTypes; +use App\Http\Requests\Campaign\AddCouponsCampaign; +use App\Http\Requests\Campaign\DeleteCampaign; +use App\Http\Requests\Campaign\RemoveCouponCampaign; +use App\Http\Requests\Campaign\RemoveNotifCampaign; +use App\Http\Requests\Campaign\ShowDemoCampaign; +use App\Http\Requests\Campaign\StoreCampaign; +use App\Http\Requests\Campaign\StoreNotifCampaign; +use App\Http\Requests\Campaign\UpdateCampaign; +use App\Models\Mur; +use App\Models\PanierContent; +use App\Models\Notification; +use App\Models\Panier; use Illuminate\Http\Request; use Illuminate\Support\Facades\File; use App\Traits\CouponTrait; -use Response; class CampagneController extends Controller { - // use BarcodeGenerator; use CouponTrait; /** @@ -26,8 +34,11 @@ class CampagneController extends Controller */ public function index() { - $campagnes = Campagne::where('camp_siteId', session()->get('site')->site_id)->get(); - return view('campagne.index')->with('campagnes', $campagnes); + // TODO : Revoir le passage du site id ? + $siteId = session()->get('site')->site_id; + + $campagnes = Campagne::where('camp_siteId', $siteId)->get(); + return view('campagnes.index')->with('campagnes', $campagnes); } /** @@ -37,38 +48,32 @@ class CampagneController extends Controller */ public function create() { - return view('campagne.create'); + return view('campagnes.create'); } /** * Store a newly created resource in storage. * - * @param \Illuminate\Http\Request $request + * @param StoreCampaign $request * @return \Illuminate\Http\Response */ - public function store(Request $request) + public function store(StoreCampaign $request) { - - $campagne = new Campagne(); - $campagne->camp_name = $request->input('camp_name'); - $campagne->camp_type = $request->input('camp_type'); - $campagne->camp_published = $request->input('camp_published'); - if (null !== $request->input('camp_limitedPrinting')) { - $campagne->camp_limitedPrinting = $request->input('camp_limitedPrinting'); - } - $campagne->camp_siteId = session()->get('site')->site_id; - + // TODO : Revoir le passage du site $site = session()->get('site'); + $campagne = new Campagne(); + $campagne->fill(array_merge($request->validated(), ['camp_siteId' => $site->site_id])); + $campagne->save(); + if ($site->campagnes()->save($campagne)) { - // File::makeDirectory(public_path('/landings/' . $campagne->camp_id)); - if ($campagne->camp_type == 0) { + if ($campagne->camp_type->equals(CampaignTypes::mur())) { File::copyDirectory(resource_path('/views/template/mur'), public_path('/landings/' . $campagne->camp_id)); - } elseif ($campagne->camp_type == 1) { + } elseif ($campagne->camp_type->equals(CampaignTypes::panier())) { File::copyDirectory(resource_path('/views/template/panier'), public_path('/landings/' . $campagne->camp_id)); - } elseif ($campagne->camp_type == 2) { + } elseif ($campagne->camp_type->equals(CampaignTypes::murss())) { File::copyDirectory(resource_path('/views/template/murnoselection'), public_path('/landings/' . $campagne->camp_id)); - } elseif ($campagne->camp_type == 3) { + } elseif ($campagne->camp_type->equals(CampaignTypes::paniers())) { File::copyDirectory(resource_path('/views/template/panierselection'), public_path('/landings/' . $campagne->camp_id)); } } @@ -79,50 +84,40 @@ class CampagneController extends Controller /** * Show the form for editing the specified resource. * - * @param \App\Campagne $campagne + * @param \App\Models\Campagne $campagne * @return \Illuminate\Http\Response */ public function edit(Campagne $campagne) { - $site = Site::findOrFail(session()->get('site')->id)->first(); + // TODO : Revoir le passage du site id + $siteId = session()->get('site')->id; - $couponsLinked = $campagne->coupons()->get(); - $campid = $campagne->camp_id; + $couponsNotLinked = Coupon::whereDoesntHave('campagnes', function ($q) use ($campagne) { + $q->where('campagne_id', $campagne->camp_id); + })->where('coupon_siteId', $siteId)->where('coupon_published', 1)->get(); - $couponsNotLinked = Coupon::whereDoesntHave('campagnes', function ($q) use ($campid) { - $q->where('campagne_id', $campid); - })->where('coupon_siteId', session()->get('site')->id)->get(); - - return view('campagne.edit', ['campagne' => $campagne, 'coupons' => $couponsNotLinked, 'couponsLinked' => $couponsLinked]); + return view('campagnes.edit', ['campagne' => $campagne, 'coupons' => $couponsNotLinked]); } /** * Update the specified resource in storage. * - * @param \Illuminate\Http\Request $request - * @param \App\Campagne $campagne + * @param UpdateCampaign $request + * @param \App\Models\Campagne $campagne * @return \Illuminate\Http\Response */ - public function update(Request $request, Campagne $campagne) + public function update(UpdateCampaign $request, Campagne $campagne) { - $site = Site::findOrFail(session()->get('site')->id)->first(); - - $couponsLinked = $campagne->coupons()->get(); - $campid = $campagne->camp_id; - - $couponsNotLinked = Coupon::whereDoesntHave('campagnes', function ($q) use ($campid) { - $q->where('campagne_id', $campid); - })->where('coupon_siteId', session()->get('site')->id)->get(); + $campagne->fill($request->validated()); if (!isset($request->camp_limitedPrinting)) { $campagne->camp_limitedPrinting = 0; - $campagne->save(); } - if ($campagne->update($request->all())) { - session()->flash('update_ok', 'La campagne a bien été modifiée'); + if ($campagne->save()) { + session()->flash('update_ok', __('La campagne a bien été modifiée')); } else { - session()->flash('update_nok', 'Erreur lors de l\'enregistrement'); + session()->flash('update_nok', __("Erreur lors de l'enregistrement")); } return redirect()->route('campagne.edit', ['campagne' => $campagne]); @@ -131,45 +126,60 @@ class CampagneController extends Controller /** * Remove the specified resource from storage. * - * @param \App\Campagne $campagne + * @param DeleteCampaign $request + * @param \App\Models\Campagne $campagne * @return \Illuminate\Http\Response */ - public function destroy(Campagne $campagne) + public function destroy(DeleteCampaign $request, Campagne $campagne) { $campagne->camp_published = 0; $campagne->save(); - // File::deleteDirectory(public_path('/landings/' . $campagne->camp_id)); + if ($campagne->delete()) { return redirect(route('campagne.index')); } else { session()->flash('delete_nok', 'Erreur lors de la suppression'); - return view('campagne.edit')->with('campagne', $campagne); + return view('campagnes.edit')->with('campagne', $campagne); } } - /** - * @param \Illuminate\Http\Request $request - * - * @return array - */ - public function saveNotification(Request $request) + // ---- Ajoute des coupons à une campagne + public function addCoupons(AddCouponsCampaign $request, Campagne $campaign) { - $notification = new Notification(); - $notification->notif_name = $request->input('notif_name'); - $notification->notif_email = $request->input('notif_email'); - $notification->notif_campId = $request->input('notif_campId'); + $coupons = Coupon::find($request->ids); + $campaign->coupons()->attach($coupons); + return json_encode($coupons); + } + + // ---- Efface des coupons d'une campagne + public function removeCoupon(RemoveCouponCampaign $request, Campagne $campaign, Coupon $coupon) + { + $campaign->coupons()->detach($coupon); + return json_encode($coupon); + } + + /** + * @param \Illuminate\Http\Request $request + * + * @return array + */ + public function saveNotification(StoreNotifCampaign $request, Campagne $campaign) + { + $notification = new Notification(); + $notification->fill(array_merge($request->validated(), ['notif_campId' => $campaign->camp_id])); $notification->save(); + return redirect()->back(); } /** - * @param \App\Notification $notification + * @param RemoveNotifCampaign $request + * @param \App\Models\Notification $notification * * @return array */ - public function deleteNotification($id) + public function deleteNotification(RemoveNotifCampaign $request, Notification $notification) { - $notification = Notification::find($id); if ($notification->delete()) { return redirect()->back(); } else { @@ -178,21 +188,105 @@ class CampagneController extends Controller } } - /** - * @param \App\Coupon $coupon - * - * @return array - */ - // public function deleteCoupon($id) - // { - // $coupon = Coupon::find($id); - // if ($notification->delete()) { - // return redirect()->back(); - // } else { - // session()->flash('delete_nok', 'Erreur lors de la suppression'); - // return redirect()->back(); - // } - // } + // ---- Montre les campagnes avec un compte de démo + public function showDemo(ShowDemoCampaign $request, Campagne $campaign) + { + $siteId = $campaign->camp_siteId; + $demoContact = Contact::where(['contact_siteId' => $siteId, 'contact_ref' => 'DEMO'])->first(); + + if (!isset($demoContact)) { + $req = new \Illuminate\Http\Request(); + $req->setMethod('POST'); + $req->request->add([ + 'refsite' => $siteId, + 'refadherent' => 'DEMO', + 'prenom' => 'Compte', + 'nom' => 'Démonstration', + 'email' => 'demo@demo.fr', + 'code_postal' => '72000', + 'commune' => 'Le Mans', + 'pays' => 250 + ]); + + $contact = new \App\Http\Controllers\ContactController(); + $res = $contact->updateContact($req); + $demoContact = Contact::where(['contact_siteId' => $siteId, 'contact_ref' => 'DEMO'])->first(); + } + + if ($campaign->camp_type->equals(CampaignTypes::mur()) || $campaign->camp_type->equals(CampaignTypes::murss())) { + // ---- DEMONSTRATION POUR LES MURS + $myRequest = new \Illuminate\Http\Request(); + $myRequest->setMethod('POST'); + $myRequest->request->add(['refcamp' => $campaign->camp_id, 'refadherent' => 'DEMO', 'admin' => 1]); + + // ---- EFFACER LES CONTROLES SI EXISTANT + $mur = new \App\Http\Controllers\MurController(); + $res = $mur->deleteControlContact($myRequest); + + // ---- RETOURNE l'URL + $url = "/?refsite=" . $siteId . "&refcamp=" . $campaign->camp_id . "&hash=" . $demoContact->contact_hash; + return json_encode($url); + } else { + // ---- DEMONSTRATION POUR LES PANIERS + $panier = Panier::where(['panier_campId' => $campaign->camp_id, 'panier_contactId' => $demoContact->contact_id, 'panier_pending' => 1])->first(); + + if ($panier) { + $url = "/?basketid=" . $panier->panier_ref; + } else { + // --- Pas de panier Création d'un nouveau + // --- Récuperation des coupons de la campagne + $coupons = $campaign->coupons()->get(); + + foreach ($coupons as $key => $coupon) { + if (!$this->isAvailableToPrint($coupon, $campaign)) { + $coupons->forget($key); + } + } + + $couponsTotal = count($coupons); + $couponsAdded = 0; + $basketContent = ""; + + foreach ($coupons as $coupon) { + $basketContent .= "(1)" . $coupon->coupon_code; + $couponsAdded++; + if ($couponsAdded != $couponsTotal) { + $basketContent .= ","; + } + } + // --- création de l'objet request + $req = new \Illuminate\Http\Request(); + $req->setMethod('POST'); + $req->request->add([ + 'refsite' => $siteId, + 'refcamp' => $campaign->camp_id, + 'refadherent' => $demoContact->contact_ref, + 'nom' => $demoContact->contact_nom, + 'prenom' => $demoContact->contact_prenom, + 'email' => $demoContact->contact_email, + 'code_postal' => $demoContact->contact_cp, + 'commune' => $demoContact->contact_ville, + 'pays' => $demoContact->contact_country, + 'panier' => $basketContent, + 'admin' => 1 + ]); + $panier = new \App\Http\Controllers\PanierController(); + $res = $panier->updateBasket($req); + $url = "/?basketid=" . $res->original['Panier']->Panier; + } + return json_encode($url); + } + } + + // ---- Dépublie une campagne + public function togglePublish(Request $request, Campagne $campaign, int $state) + { + $campaign->camp_published = $state; + $campaign->save(); + + return json_encode($campaign); + } + public function getDetail(Request $request) { @@ -203,7 +297,7 @@ class CampagneController extends Controller $refcamp = $request->refcamp; $campagne = Campagne::where(['camp_id' => $refcamp])->first(); if (!$campagne) { - return Response::json([ + return response()->json([ 'Statut' => 'KO', 'Code' => 103, 'Message' => 'La campagne n\'existe pas' @@ -216,7 +310,7 @@ class CampagneController extends Controller $refsite = $request->refsite; $site = Site::where(['site_id' => $refsite])->first(); if (!$site) { - return Response::json([ + return response()->json([ 'Statut' => 'KO', 'Code' => 102, 'Message' => 'Le site n\'existe pas' @@ -227,7 +321,7 @@ class CampagneController extends Controller } if ($campagne->camp_siteId != $site->site_id) { - return Response::json([ + return response()->json([ 'Statut' => 'KO', 'Code' => 108, 'Message' => 'Pas de campagne pour ce site' @@ -235,7 +329,7 @@ class CampagneController extends Controller } if ($error) { - return Response::json([ + return response()->json([ 'Statut' => 'KO', 'Code' => 101, 'Message' => 'Des paramètres de la requête sont mal renseignés ou non présents' @@ -244,16 +338,16 @@ class CampagneController extends Controller $enligne = ($campagne->camp_published == 1) ? "oui" : "non"; switch ($campagne->camp_type) { - case 0: + case CampaignTypes::mur(): $type = "mur"; break; - case 1: + case CampaignTypes::panier(): $type = "panier"; break; - case 2: + case CampaignTypes::murss(): $type = "mur sans sélection"; break; - case 3: + case CampaignTypes::paniers(): $type = "panier avec sélection"; break; } @@ -270,7 +364,6 @@ class CampagneController extends Controller if ($coupons->count() > 0) { foreach ($coupons as $coupon) { - // var_dump($coupon->coupon_id); // ---- Calcul du nombre de BR consommé $diffuseMur = Mur::where(['mur_campId' => $campagne->camp_id, 'mur_couponId' => $coupon->coupon_id])->count(); @@ -314,91 +407,9 @@ class CampagneController extends Controller $data['Coupons'][] = $codeTraitement; }//end foreach }//end if - return Response::json([ + return response()->json([ 'Statut' => 'OK', 'Détails Campagne' => $data ]); } - - public function getDiffCamp(Request $request) - { - $error = false; - // ---- Contrôle des paramètres - if (isset($request->refcamp) && $request->refcamp != "") { - $refcamp = $request->refcamp; - $campagne = Campagne::where(['camp_id' => $refcamp])->first(); - if (!$campagne) { - return Response::json([ - 'Statut' => 'KO', - 'Code' => 103, - 'Message' => 'La campagne n\'existe pas' - ]); - } - } else { - $error = true; - } - if (isset($request->refsite) && $request->refsite != "") { - $refsite = $request->refsite; - $site = Site::where(['site_id' => $refsite])->first(); - if (!$site) { - return Response::json([ - 'Statut' => 'KO', - 'Code' => 102, - 'Message' => 'Le site n\'existe pas' - ]); - }; - } else { - $error = true; - } - - if (isset($request->refadherent) && $request->refadherent != "") { - $refadherent = $request->refadherent; - $contact = Contact::where(['contact_siteId' => $refsite, 'contact_ref' => $refadherent])->first(); - if (!$contact) { - return Response::json([ - 'Statut' => 'KO', - 'Code' => 104, - 'Message' => 'Le contact n\'existe pas' - ]); - } - } else { - $error = true; - } - - if ($error) { - return Response::json([ - 'Statut' => 'KO', - 'Code' => 101, - 'Message' => 'Des paramètres de la requête sont mal renseignés ou non présents' - ]); - } - - $data = array ( - 'Statut' => 'OK', - 'Site' => $site->site_nom, - 'Ref campagne' => $campagne->camp_id, - 'Nom campagne' => $campagne->camp_name, - "Ref contact" => $refadherent, - "Email contact" => $contact->contact_email, - ); - - $coupons = $campagne->coupons()->get(); - - if ($coupons->count() > 0) { - foreach ($coupons as &$coupon) { - if ($this->isAvailable($coupon, $campagne, $contact)) { - $dispo = 1; - } else { - $dispo = 0; - } - $codeTraitement = array ( - "Code traitement" => $coupon->coupon_code, - "Nom" => $coupon->coupon_name, - "Nb disponible" => $dispo, - ); - $data['Codes traitement'][] = $codeTraitement; - } - } - return Response::json($data); - } } diff --git a/app/Http/Controllers/ChangeMarqueController.php b/app/Http/Controllers/ChangeMarqueController.php deleted file mode 100644 index d6d54e4..0000000 --- a/app/Http/Controllers/ChangeMarqueController.php +++ /dev/null @@ -1,24 +0,0 @@ -input('site_id'); - $currentRoute = $request->input('current_route'); - $site = \App\Site::findOrFail($siteId); - session()->put('site', $site); - - return redirect('/bo/' . $currentRoute); - } -} diff --git a/app/Http/Controllers/ContactController.php b/app/Http/Controllers/ContactController.php deleted file mode 100644 index f1410ea..0000000 --- a/app/Http/Controllers/ContactController.php +++ /dev/null @@ -1,292 +0,0 @@ -get('site')->site_id)->orderBy('contact_createdate', 'DESC')->take(10)->get(); - - return view('contact.index')->with('contacts', $contacts)->with('search', false); - } - - - public function search_contact(Request $request) - { - session()->put('active_route', 'contact'); - $page = $request->input('page'); - $name = $request->input('searchName'); - $firstname = $request->input('searchFirstname'); - $email = $request->input('searchEmail'); - $cp = $request->input('searchCp'); - $ville = $request->input('searchVille'); - $country = $request->input('searchCountry'); - - if (isset($name) || isset($firstname) || isset($email) || isset($cp) || isset($ville) || isset($country)) { - $contacts = Contact::where('contact_siteId', session()->get('site')->site_id) - ->searchFirstname($firstname) - ->searchName($name) - ->searchEmail($email) - ->searchCp($cp) - ->searchVille($ville) - ->searchCountry($country) - ->paginate(2, ['*'], 'page', $page); - $searchData = array( - 'name' => $name, - 'firstname' => $firstname, - 'email' => $email, - 'cp' => $cp, - 'ville' => $ville, - 'pays' => $country - ); - return view('contact.index')->with('contacts', $contacts)->with('search', true)->with('searchData', $searchData); - } else { - $contacts = Contact::where('contact_siteId', session()->get('site')->site_id)->orderBy('contact_createdate', 'DESC')->take(10)->get(); - - return view('contact.index')->with('contacts', $contacts)->with('search', false); - }//end if - } - - /** - * Show the form for creating a new resource. - * - * @return \Illuminate\Http\Response - */ - public function create() - { - return view('contact.create'); - } - - /** - * Store a newly created resource in storage. - * - * @param \Illuminate\Http\Request $request - * @return \Illuminate\Http\Response - */ - public function store(Request $request) - { - $validatedData = $request->validate([ - 'contact_ref' => 'required|unique:contact', - 'contact_nom' => 'required', - 'contact_prenom' => 'required', - 'contact_email' => 'required', - 'contact_cp' => 'required', - 'contact_ville' => 'required', - 'contact_country' => 'required' - ]); - - $contact = new Contact(); - $contact->contact_nom = $request->input('contact_nom'); - $contact->contact_prenom = $request->input('contact_prenom'); - $contact->contact_ref = $request->input('contact_ref'); - $contact->contact_email = $request->input('contact_email'); - $contact->contact_cp = $request->input('contact_cp'); - $contact->contact_ville = $request->input('contact_ville'); - $contact->contact_country = $request->input('contact_country'); - $contact->contact_hash = strtoupper(md5(uniqid(time(), true))); - - // $site = Site::findOrFail(session()->get('site')->id)->first(); - $site = session()->get('site'); - - $contact->contact_siteId = $site->site_id; - - $contact->save(); - - $contacts = Contact::where('contact_siteId', session()->get('site')->site_id)->orderBy('contact_createdate', 'DESC')->take(10)->get(); - $campagnes = Campagne::where(['camp_siteId' => $contact->contact_siteId, 'camp_published' => 1])->get(); - - return view('contact.edit', ['contact' => $contact, 'created' => true, 'contacts' => $contacts, 'campagnes' => $campagnes]); - } - - - - /** - * Show the form for editing the specified resource. - * - * @param \App\Campagne $campagne - * @return \Illuminate\Http\Response - */ - public function edit(Contact $contact) - { - $campagnes = Campagne::where(['camp_siteId' => $contact->contact_siteId, 'camp_published' => 1])->get(); - - return view('contact.edit', ['contact' => $contact, 'campagnes' => $campagnes]); - } - - - /** - * Update the specified resource in storage. - * - * @param \Illuminate\Http\Request $request - * @param \App\Contact $contact - * @return \Illuminate\Http\Response - */ - public function update(Request $request, Contact $contact) - { - $validatedData = $request->validate([ - 'contact_ref' => 'required', - 'contact_nom' => 'required', - 'contact_prenom' => 'required', - 'contact_email' => 'required', - 'contact_cp' => 'required', - 'contact_ville' => 'required', - 'contact_country' => 'required' - ]); - - $campagnes = Campagne::where(['camp_siteId' => $contact->contact_siteId, 'camp_published' => 1])->get(); - if ($contact->update($request->all())) { - session()->flash('update_ok', 'La campagne a bien été modifiée'); - } else { - session()->flash('update_nok', 'Erreur lors de l\'enregistrement'); - } - - return redirect()->route('contact.edit', ['contact' => $contact]); - } - - public function updateContact(Request $request) - { - if (isset($request->admin)) { - $source = 'ADMIN'; - } else { - $source = 'API'; - } - // ---- INIT du log - // $log = new Log(); - // $log->log_action = config('constants.updatecontact'); - // $log->log_source = $source; - $error = false; - // ---- Contrôle des paramètres - if (isset($request->refadherent) && $request->refadherent != "") { - $refadherent = $request->refadherent; - } else { - $error = true; - } - if (isset($request->nom) && $request->nom != "") { - $nom = $request->nom; - } else { - $error = true; - } - if (isset($request->refsite) && $request->refsite != "") { - $refsite = $request->refsite; - } else { - $error = true; - } - - if (isset($request->prenom) && $request->prenom != "") { - $prenom = $request->prenom; - } else { - $error = true; - } - if (isset($request->email) && $request->email != "" && filter_var($request->email, FILTER_VALIDATE_EMAIL)) { - $email = $request->email; - } else { - $error = true; - } - if (isset($request->code_postal) && $request->code_postal != "") { - $code_postal = $request->code_postal; - } else { - $error = true; - } - if (isset($request->commune) && $request->commune != "") { - $commune = $request->commune; - } else { - $error = true; - } - if (isset($request->pays) && $request->pays != "") { - if (filter_var($request->pays, FILTER_VALIDATE_INT)) { - $pays = $request->pays; - } else { - $error = true; - } - } else { - $pays = 250; - } - - if ($error) { - // $log->log_params = json_encode(['refadherent' => $request->refadherent, 'refsite'=>$request->refsite, 'nom' => $request->nom, 'prenom' => $request->prenom, 'email' => $request->email, 'code postal' => $request->code_postal, 'commune' => $request->commune]); - // $log->log_statut = 'NOK'; - // $log->log_message = "Des paramètres de la requête sont mal renseignés ou non présents"; - // $log->save(); - return Response::json([ - 'Statut' => 'KO', - 'Code' => 101, - 'Message' => 'Des paramètres de la requête sont mal renseignés ou non présents' - ]); - } - - $contact = Contact::where(['contact_siteId' => $refsite, 'contact_ref' => $refadherent])->first(); - - if ($contact) { - $contact->contact_prenom = $prenom; - $contact->contact_nom = $nom; - $contact->contact_email = $email; - $contact->contact_cp = $code_postal; - $contact->contact_ville = $commune; - $contact->contact_country = $pays; - $contact->contact_updatedate = date('Y-m-d H:i:s'); - if (isset($request->hashcode) && $request->hashcode != "") { - $contact->contact_hash = $request->hashcode; - } - } else { - $site = Site::where('site_id', $refsite)->first(); - - if ($site) { - $contact = new Contact(); - $contact->contact_nom = $nom; - $contact->contact_prenom = $prenom; - $contact->contact_ref = $refadherent; - $contact->contact_email = $email; - $contact->contact_cp = $code_postal; - $contact->contact_ville = $commune; - $contact->contact_country = $pays; - $contact->contact_siteId = $refsite; - if (isset($request->hashcode) && $request->hashcode != "") { - $contact->contact_hash = $request->hashcode; - } else { - $contact->contact_hash = strtoupper(md5(uniqid(time(), true))); - } - } else { - // $log->log_params = json_encode(['refadherent' => $request->refadherent, 'refsite'=>$request->refsite, 'nom' => $request->nom, 'prenom' => $request->prenom, 'email' => $request->email, 'code postal' => $request->code_postal, 'commune' => $request->commune]); - // $log->log_refsite = $request->refsite; - // $log->log_statut = 'NOK'; - // $log->log_message = "Le site spécifié n'existe pas"; - // $log->save(); - return Response::json([ - 'Statut' => 'KO', - 'Code' => 102, - 'Message' => 'Le site spécifié n\'existe pas' - ]); - }//end if - }//end if - - if ($contact->save()) { - return Response::json([ - 'Statut' => 'OK', - 'contact' => $contact - ]); - } else { - // $log->log_params = json_encode(['refadherent' => $request->refadherent, 'refsite'=>$request->refsite, 'nom' => $request->nom, 'prenom' => $request->prenom, 'email' => $request->email, 'code postal' => $request->code_postal, 'commune' => $request->commune]); - // $log->log_refsite = $request->refsite; - // $log->log_statut = 'NOK'; - // $log->log_message = "Une erreur est survenue"; - // $log->save(); - return Response::json([ - 'Statut' => 'KO', - 'Code' => 109, - 'Message' => 'Une erreur est survenue' - ]); - } - } -} diff --git a/app/Http/Controllers/CouponController.php b/app/Http/Controllers/CouponController.php index 4e99278..3ee0289 100644 --- a/app/Http/Controllers/CouponController.php +++ b/app/Http/Controllers/CouponController.php @@ -4,14 +4,15 @@ namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Str; -use App\Coupon; -use App\Site; -use App\Campagne; -use App\Mouvement; -use App\Calendrier; +use App\Models\Coupon; +use App\Models\Site; +use App\Models\Campagne; +use App\Models\Mouvement; +use App\Models\Calendrier; +use App\Http\Requests\Coupons\StoreCoupons; +use App\Http\Requests\Coupons\UpdateCoupons; use App\Traits\GenerateBR; use App\Traits\CouponTrait; -use Validator; class CouponController extends Controller { @@ -25,14 +26,9 @@ class CouponController extends Controller */ public function index() { - $campIds = Campagne::where('camp_siteId', session()->get('site')->site_id) - ->get() - ->pluck('camp_id') - ->flatten() - ->toArray(); - - $coupons = Coupon::where('coupon_siteId', session()->get('site')->id)->get(); - + // TODO : Revoir le passage du site + $site = session()->get('site'); + $coupons = Coupon::where('coupon_siteId', $site->id)->get(); foreach ($coupons as $coupon) { // ---- Calcul de la quantité mise à disposition grace aux fonctions dans CouponTrait.php $coupon->coupon_quantity = $this->getFullQuantity($coupon); @@ -40,8 +36,7 @@ class CouponController extends Controller $coupon->coupon_left = 0; // $coupon->coupon_quantity - $this->getUsedQuantity($coupon); } - - return view('coupon.index', ['coupons' => $coupons, 'camps' => $campIds]); + return view('coupon.index', ['coupons' => $coupons]); } /** @@ -51,52 +46,32 @@ class CouponController extends Controller */ public function create() { + // TODO : Revoir le passage du site + $site = session()->get('site'); + $campagnes = Campagne::where('camp_siteId', session()->get('site')->site_id)->get() ->pluck('camp_name', 'camp_id'); - $site = Site::where(['id' => session()->get('site')->id])->first(); + $site = Site::findOrFail($site->id); return view('coupon.create')->with('campagnes', $campagnes)->with('site', $site); } /** * Store a newly created resource in storage. * - * @param \Illuminate\Http\Request $request + * @param StoreCoupons $request * @return \Illuminate\Http\Response */ - public function store(Request $request) + public function store(StoreCoupons $request) { - $data = $request->all(); - - $v = Validator::make($data, [ - 'coupon_code' => 'required|unique:coupon,coupon_code', - 'coupon_validity_text' => 'required', - 'coupon_legal_mentions' => 'required', - 'coupon_decoration_image' => 'required|image|mimes:jpeg,png', - 'coupon_logo_image' => 'required|image|mimes:jpeg,png', - 'coupon_rcs' => 'required', - 'coupon_site_contact' => 'required', - ]); - - $v->sometimes('coupon_gs1code', 'required|image|mimes:jpeg', function ($input) { - return isset($input->coupon_norme); - }); - - if ($v->fails()) { - return redirect()->back() - ->withErrors($v) - ->withInput(); - } - - + $site_id = $request->site_id; $datas = $this->saveImg($request); + $coupon = new Coupon(); + $coupon->fill($datas); - $coupon = new Coupon(); - $coupon->coupon_code = $datas['coupon_code']; - $coupon->coupon_name = $datas['coupon_name']; - $coupon->coupon_value = $datas['coupon_value']; + // TODO : A revoir au moment ou on enlevera les images mobiles if (isset($datas['coupon_thumbnail1'])) { $coupon->coupon_thumbnail1 = $datas['coupon_thumbnail1']; } @@ -112,46 +87,21 @@ class CouponController extends Controller if (isset($datas['coupon_image'])) { $coupon->coupon_image = $datas['coupon_image']; } - if (isset($datas['coupon_norme'])) { - $coupon->coupon_norme = $datas['coupon_norme']; - $coupon->coupon_gs1code = $datas['coupon_gs1code']; - } - if (isset($datas['coupon_enablelimitquantity'])) { - $coupon->coupon_enablelimitquantity = $datas['coupon_enablelimitquantity']; - $coupon->coupon_limitquantity = $datas['coupon_limitquantity']; - } - if (isset($datas['coupon_enablelimitperiod'])) { - $coupon->coupon_enablelimitperiod = $datas['coupon_enablelimitperiod']; - $coupon->coupon_limitperiod = $datas['coupon_limitperiod']; - } - if (isset($datas['coupon_published'])) { - $coupon->coupon_published = $datas['coupon_published']; - } else { + + //TODO : Voir si on peut mettre le set a 0 dans la request + if (!isset($datas['coupon_published'])) { $coupon->coupon_published = 0; } - if (isset($datas['coupon_legal_mentions_splitted'])) { - $coupon->coupon_legal_mentions_splitted = $datas['coupon_legal_mentions_splitted']; - } else { + if (!isset($datas['coupon_legal_mentions_splitted'])) { $coupon->coupon_legal_mentions_splitted = 0; } - $coupon->coupon_validity = $datas['coupon_validity']; - $coupon->coupon_mindatediffusion = $datas['coupon_mindatediffusion']; - $coupon->coupon_maxdatediffusion = $datas['coupon_maxdatediffusion']; - $coupon->coupon_maxdatevalidity = $datas['coupon_maxdatevalidity']; - $coupon->coupon_validity_text = $datas['coupon_validity_text']; - $coupon->coupon_legal_mentions = $datas['coupon_legal_mentions']; - if (isset($datas['coupon_decoration_image'])) { - $coupon->coupon_decoration_image = $datas['coupon_decoration_image']; - } - if (isset($datas['coupon_logo_image'])) { - $coupon->coupon_logo_image = $datas['coupon_logo_image']; - } - $coupon->coupon_rcs = $datas['coupon_rcs']; - $coupon->coupon_site_contact = $datas['coupon_site_contact']; - $coupon->coupon_seuil_alert = $datas['coupon_seuil_alert']; + $br_path = $this->generateBase($request, $coupon); + $coupon->coupon_image = $br_path; + $coupon->coupon_siteId = $site_id; + $coupon->save(); - $site = Site::find($request->input('site_id')); + $site = Site::findOrFail($site_id); $site->coupons()->save($coupon); @@ -161,15 +111,6 @@ class CouponController extends Controller $coupon->mouvements()->save($mouvement); } - if (isset($datas['mouvementNbre'])) { - foreach ($datas['mouvementNbre'] as $key => $value) { - $mouvement = new Mouvement(); - $mouvement->mouvement_nombre = $value; - $mouvement->mouvement_created_at = $datas['mouvementDate'][$key]; - $coupon->mouvements()->save($mouvement); - } - } - if (isset($datas['startdate'])) { foreach ($datas['startdate'] as $key => $value) { $calendar = new Calendrier(); @@ -179,28 +120,13 @@ class CouponController extends Controller } } - $br_path = $this->generateBase($request, $coupon); - $coupon->coupon_image = $br_path; - $coupon->save(); - - return view('coupon.edit', ['coupon' => $coupon]); - } - - /** - * Display the specified resource. - * - * @param \App\Coupon $coupon - * @return \Illuminate\Http\Response - */ - public function show(Coupon $coupon) - { - return view('coupon.show', ['coupon' => $coupon]); + return redirect()->route('coupon.edit', ['coupon' => $coupon]); } /** * Show the form for editing the specified resource. * - * @param \App\Coupon $coupon + * @param \App\Models\Coupon $coupon * @return \Illuminate\Http\Response */ public function edit(Coupon $coupon) @@ -211,33 +137,13 @@ class CouponController extends Controller /** * Update the specified resource in storage. * - * @param \Illuminate\Http\Request $request - * @param \App\Coupon $coupon + * @param UpdateCoupons $request + * @param \App\Models\Coupon $coupon * @return \Illuminate\Http\Response */ - public function update(Request $request, Coupon $coupon) + public function update(UpdateCoupons $request, Coupon $coupon) { - - $data = $request->all(); - - $v = Validator::make($data, [ - 'coupon_decoration_image' => 'image|mimes:jpeg,png', - 'coupon_logo_image' => 'image|mimes:jpeg,png', - ]); - - $v->sometimes('coupon_gs1code', 'required|image|mimes:jpeg', function ($input) { - if (isset($input->coupon_gs1code_image_hidden)) { - return false; - } - return isset($input->coupon_norme); - }); - - if ($v->fails()) { - return redirect('bo/coupon/' . $coupon->coupon_id . '/edit') - ->withErrors($v) - ->withInput(); - } - + //TODO : Voir si on peut mettre le set a 0 dans la request if (!isset($request->coupon_enablelimitquantity)) { $coupon->coupon_enablelimitquantity = 0; } @@ -253,11 +159,17 @@ class CouponController extends Controller if (!isset($request->coupon_legal_mentions_splitted)) { $coupon->coupon_legal_mentions_splitted = 0; } - if ($coupon->update($this->saveImg($request))) { - $datas = $this->saveImg($request); + + $datas = $this->saveImg($request); + // On sauvegarde les informations + if ($coupon->update($datas)) { + // Si l'update est OK on met à jour l'image du BR $br_path = $this->generateBase($request, $coupon); $coupon->coupon_image = $br_path; - $coupon->update($this->saveImg($request)); + $coupon->save(); + + // Si on ajoute des BR + // TODO : Gestion de l'erreur si on ajoute une ligne vide if (isset($datas['mouvementNbre'])) { foreach ($datas['mouvementNbre'] as $key => $value) { $mouvement = new Mouvement(); @@ -266,6 +178,8 @@ class CouponController extends Controller $coupon->mouvements()->save($mouvement); } } + // Si on ajoute une plage de diffusion + // TODO : Gestion de l'erreur si on ajoute une ligne vide if (isset($datas['startdate'])) { $coupon->calendriers()->delete(); foreach ($datas['startdate'] as $key => $value) { @@ -288,7 +202,7 @@ class CouponController extends Controller /** * Remove the specified resource from storage. * - * @param \App\Coupon $coupon + * @param \App\Models\Coupon $coupon * @return \Illuminate\Http\Response */ public function destroy(Coupon $coupon) @@ -296,10 +210,10 @@ class CouponController extends Controller $coupon->coupon_published = 0; $coupon->save(); if ($coupon->delete()) { - return redirect(route('coupon.index')); + return redirect()->route('coupon.index'); } else { session()->flash('delete_nok', 'Erreur lors de la suppression'); - return view('coupon.edit')->with('coupon', $coupon); + return back(); } } @@ -312,8 +226,6 @@ class CouponController extends Controller { $datas = collect($request->all()); - $imgs = collect(array()); - foreach ($datas as $key => $item) { if ($key == 'coupon_image' || $key == 'coupon_gs1code' || $key == 'coupon_decoration_image' || $key == 'coupon_logo_image' || (substr($key, 7, 9) == 'thumbnail' && strlen($key) < 18)) { if (isset($item)) { diff --git a/app/Http/Controllers/ExportController.php b/app/Http/Controllers/ExportController.php deleted file mode 100644 index 9d15242..0000000 --- a/app/Http/Controllers/ExportController.php +++ /dev/null @@ -1,87 +0,0 @@ -format('Y-m-d'); - $enddate = date('Y-m-d'); - - return view('export.index')->with(['sites' => $sites, 'startdate' => $startdate, 'enddate' => $enddate]); - } - - // ------ AJAX Export - public function export_coupons(Request $request) - { - $ids = $request->input('ids'); - $startdate = date('Y-m-d', strtotime($request->input('startdate'))); - $enddate = date('Y-m-d', strtotime($request->input('enddate'))); - $coupons = Coupon::find($ids); - - $labels = $this->getLabelsForStats($startdate, $enddate); - - $paths = array(); - - foreach ($coupons as $coupon) { - $cpName = str_replace(' ', '', $coupon->coupon_name); - $now = strtotime(now()); - $full_path = 'export/' . $cpName . '_' . $now . '.pdf'; - $dataCoupon = $this->getDataForCouponAllCamp($labels, $coupon); - $coupon->couponQuantity = $this->getFullQuantity($coupon); - $coupon->couponFullPrinted = $this->getUsedQuantity($coupon); - $coupon->couponPrinted = $this->getUsedQuantityOnPeriod($coupon, $startdate, $enddate); - - $pdf = App::make('dompdf.wrapper'); - - $myData = new Data(); - - $myData->addPoints($dataCoupon, "My Serie 1"); - $myData->addPoints($labels, "My Serie 2"); - $myData->setAxisName(0, "Coupons Diffusés"); - $myData->setAbscissa("My Serie 2"); - $myData->setSerieTicks("My Serie 2", 2); - $serieSettings = array("R" => 229,"G" => 11,"B" => 11); - $myData->setPalette("My Serie 1", $serieSettings); - $myPicture = new Image(700, 230, $myData); - $myPicture->setGraphArea(60, 40, 670, 190); - $myPicture->setFontProperties(array("FontSize" => 10)); - $myPicture->drawScale(array("DrawSubTicks" => true, 'LabelSkip' => 1, 'LabelRotation' => 25, "Mode" => SCALE_MODE_START0, "CycleBackground" => true,"GridR" => 102,"GridG" => 102,"GridB" => 102)); - $myPicture->setShadow(true, array("X" => 1,"Y" => 1,"R" => 0,"G" => 0,"B" => 0,"Alpha" => 10)); - $myPicture->drawLineChart(array("DisplayColor" => DISPLAY_AUTO)); - $LabelSettings = array("NoTitle" => true); - $myPicture->Render('export/temp.png'); - - $view = view('export.template')->with(['src' => 'export/temp.png', 'coupon' => $coupon, 'startdate' => $startdate, 'enddate' => $enddate])->render(); - - // var_dump($view); - $pdf->loadHTML($view); - $pdf->save($full_path); - array_push($paths, $full_path); - }//end foreach - - return json_encode($paths); - } -} diff --git a/app/Http/Controllers/Fo/BasketController.php b/app/Http/Controllers/Fo/BasketController.php new file mode 100644 index 0000000..d322357 --- /dev/null +++ b/app/Http/Controllers/Fo/BasketController.php @@ -0,0 +1,85 @@ +contents->sum(function ($content) { + return $content->quantity - $content->printed; + }); + + return view('fo.basket.show', compact('basket', 'totalQuantity')); + } + + // FIXME: Docblock + public function print(PrintRequest $request, Basket $basket) + { + $campagne = $basket->campagne; + + // FIXME: Bump to CrmApiV4 + $crm = new CrmApiV2(config('services.crm.endpoint'), $campagne->site->crm_token, $campagne->site->crm_password); + + /** + * @var \LDC\LDCCRM\Models\Customer + */ + $crmInfos = $crm->getCustomer($basket->customer->hashcode); + + if (is_null($crmInfos)) { + throw new \Exception('Customer not found.'); + } + + $coupons = []; + $currentDateTime = date('Y-m-d H:i:s'); + + foreach ($basket->contents as $content) { + $coupon = $content->coupon()->whereRaw( + "coupon_published = 1 AND + (coupon_mindatediffusion IS NULL OR coupon_mindatediffusion <= NOW()) AND + (coupon_maxdatediffusion IS NULL OR coupon_maxdatediffusion >= NOW()) AND + (coupon_maxdatevalidity IS NULL OR coupon_maxdatevalidity >= NOW())" + )->first(); + + if ($coupon !== null) { + $calendars = Calendrier::where('calendrier_couponId', $coupon->coupon_id)->get(); + + $published = true; + if (!$calendars->isEmpty()) { + $published = false; + foreach ($calendars as $calendar) { + if ($currentDateTime > $calendar->calendrier_startdate && $currentDateTime < $calendar->calendrier_enddate) { + $published = true; + break; // Exit loop early as condition is met + } + } + } + + if ($published) { + $qtyToPrint = $content->quantity - $content->printed; + for ($i = 0; $i < $qtyToPrint; $i++) { + $coupons[] = $this->printCoupon($coupon, $basket->customer, $crmInfos, $campagne); + } + $content->printed = $content->quantity; + $content->save(); + } + } + } + + // $coupons contains all printed coupons + $pdf = PDF::loadView('pdf.coupons', ['coupons' => $coupons]); + return $pdf->download(sprintf("coupons_%s_%s_%s.pdf", $crmInfos->firstname, $crmInfos->lastname, date('d-m-Y'))); + } +} diff --git a/app/Http/Controllers/HomeController.php b/app/Http/Controllers/HomeController.php deleted file mode 100644 index c4b2fb8..0000000 --- a/app/Http/Controllers/HomeController.php +++ /dev/null @@ -1,35 +0,0 @@ -middleware('auth'); - } - - /** - * Show the application dashboard. - * - * @return \Illuminate\Http\Response - */ - public function index() - { - $test = Campagne::find(102); - - Debugbar::info($test); - - return view('home')->with([ - 'test' => $test, - ]); - } -} diff --git a/app/Http/Controllers/MaintenanceController.php b/app/Http/Controllers/MaintenanceController.php deleted file mode 100644 index 4b45cfc..0000000 --- a/app/Http/Controllers/MaintenanceController.php +++ /dev/null @@ -1,145 +0,0 @@ -sites()->get(); - $user->linkedSites = ""; - foreach ($sites as $site) { - $user->linkedSites .= '

' . $site->site_nom . '

'; - } - } - $dates = array(date('m/Y')); - for ($i = 1; $i < 12; $i++) { - $datebefore = date("m/Y", strtotime("-" . $i . " months")); - array_push($dates, $datebefore); - } - $count = array(); - foreach ($dates as $month) { - $logs = Log::where(['log_statut' => 'NOK'])->whereMonth('created_at', $month)->count(); - array_push($count, [$month, $logs]); - } - - // $logArray = array(); - // foreach ($logs as $logMonth) { - // $count = count($logMonth); - // foreach ($logMonth as $log) { - // $date = Carbon::parse($log->created_at)->format('m/Y'); - // } - // array_push($logArray, [$date, $count]); - // } - return view('maintenance.index')->with(['users' => $users, 'logs' => $count]); - } - - public function usercreate(Request $request) - { - $sites = Site::all(); - return view('user.create')->with(['sites' => $sites]); - } - - public function userstore(Request $request) - { - - $validatedData = $request->validate([ - 'email' => 'required|unique:users|email', - 'name' => 'required', - 'password' => 'required' - ]); - - $nom = $request->name; - $email = $request->email; - $password = $request->password; - $role = $request->roles; - - $user = new User(); - $user->name = $nom; - $user->email = $email; - $user->password = Hash::make($password); - $user->roles = $role; - $user->save(); - - // MAJ des sites liés - if (isset($request->site)) { - $siteids = $request->site; - $sites = Site::whereIn('site_id', $siteids)->get()->pluck('id')->toArray(); - $user->sites()->sync($sites); - } - - - $sites = Site::all(); - $usersites = $user->sites()->get()->pluck('site_id')->toArray(); - return view('user.edit')->with(['user' => $user, 'sites' => $sites, 'usersites' => $usersites]); - } - - public function useredit(User $user) - { - $sites = Site::all(); - $usersites = $user->sites()->get()->pluck('site_id')->toArray(); - return view('user.edit')->with(['user' => $user, 'sites' => $sites, 'usersites' => $usersites]); - } - - public function userdestroy(User $user) - { - if ($user->delete()) { - return redirect(route('maintenance.show')); - } else { - session()->flash('delete_nok', 'Erreur lors de la suppression'); - return view('maintenance.user.edit')->with('user', $user); - } - } - - public function userupdate(Request $request, User $user) - { - // MAJ du User - $user->name = $request->name; - $user->email = $request->email; - $user->roles = $request->roles; - $user->save(); - - // MAJ des sites liés - $siteids = $request->site; - $sites = Site::whereIn('site_id', $siteids)->get()->pluck('id')->toArray(); - $user->sites()->sync($sites); - - $marques = Auth::user()->sites; - $submarques = $marques->map(function ($marque) { - return $marque->only(['id', 'site_nom', 'site_id', 'site_logo']); - }); - - session()->put('marques', $submarques); - - $users = User::all(); - - foreach ($users as &$user) { - $sites = $user->sites()->get(); - $user->linkedSites = ""; - foreach ($sites as $site) { - $user->linkedSites .= '

' . $site->site_nom . '

'; - } - } - $dates = array('02/2019'); - for ($i = 1; $i < 12; $i++) { - $datebefore = date("m/Y", strtotime("-" . $i . " months")); - array_push($dates, $datebefore); - } - $count = array(); - foreach ($dates as $month) { - $logs = Log::where(['log_statut' => 'NOK'])->whereMonth('created_at', $month)->count(); - array_push($count, [$month, $logs]); - } - return view('maintenance.index')->with(['users' => $users, 'logs' => $count]); - } -} diff --git a/app/Http/Controllers/MouvementController.php b/app/Http/Controllers/MouvementController.php deleted file mode 100644 index 427d5a0..0000000 --- a/app/Http/Controllers/MouvementController.php +++ /dev/null @@ -1,28 +0,0 @@ -mouvement_type = $request->input('mouvement_type'); - $mouvement->mouvement_nombre = $request->input('mouvement_nombre'); - $mouvement->mouvement_commentaire = $request->input('mouvement_commentaire'); - - $coupon = Coupon::find($request->input('coupon_id')); - - $coupon->mouvements()->save($mouvement); - } -} diff --git a/app/Http/Controllers/MurController.php b/app/Http/Controllers/MurController.php deleted file mode 100644 index 94bb192..0000000 --- a/app/Http/Controllers/MurController.php +++ /dev/null @@ -1,316 +0,0 @@ -all(); - if (isset($datas['refcamp'])) { - $ref = intval($datas['refcamp']); - $campagne = Campagne::where(['camp_id' => $ref])->first(); - } else { - abort(404); - } - if (!isset($datas['refsite'])) { - abort(404); - } - if (!isset($campagne) || $campagne->camp_published == 0 || ($campagne->camp_type != 0 && $campagne->camp_type != 2)) { - abort(404); - } - - if (isset($datas['hash'])) { - $contact = Contact::where([ - 'contact_hash' => $datas['hash'], 'contact_siteId' => $campagne->camp_siteId - ])->first(); - } else { - abort(404); - } - - $coupons = $this->getCouponsPublished($campagne); - - foreach ($coupons as $coupon) { - $coupon->isAvailable = $this->isAvailable($coupon, $campagne, $contact); - $coupon->isAvailableToPrint = $this->isAvailableToPrint($coupon, $campagne); - } - unset($coupon); - - // Montant total et Nombre réductions disponible - $montantDispo = 0; - $montantTotal = 0; - $nbCoupon = 0; - $nbCouponToPrint = 0; - foreach ($coupons as $coupon) { - $montantTotal += $coupon->coupon_value; - if ($coupon->isAvailable == true) { - $montantDispo += $coupon->coupon_value; - $nbCoupon++; - } - if ($coupon->isAvailableToPrint == true) { - $nbCouponToPrint++; - } - } - - session()->put('campagne', $campagne); - session()->put('site', $campagne->site); - session()->put('contact', $contact); - - return view('landings::' . $ref . '.index') - ->with(['ref' => $ref, 'coupons' => $coupons, 'contact' => $contact, 'nb' => $nbCoupon, 'nbAvailableToPrint' => $nbCouponToPrint, 'montantDispo' => $montantDispo]); - } - - public function printMur(Request $request) - { - if (isset($request->coupons)) { - session()->put('coupons', $request->coupons); - $coupons = $request->coupons; - } - - if ($request->session()->has('campagne')) { - $campagne = $request->session()->get('campagne'); - } else { - abort(419); - } - - $ref = $campagne->camp_id; - - return view('landings::' . $ref . '.imprimer') - ->with(['ref' => $ref, 'coupons' => $coupons, 'contact' => $request->session()->get('contact')]); - } - - public function deleteControlContact(Request $request) - { - if (isset($request->admin)) { - $source = 'ADMIN'; - } else { - $source = 'API'; - } - - // ---- INIT du log - $log = new Log(); - $log->log_action = config('constants.delctrlcontact'); - $log->log_source = $source; - - $error = false; - // ---- Contrôle des paramètres - if (isset($request->refcamp) && $request->refcamp != "") { - $refcamp = $request->refcamp; - } else { - $error = true; - } - if (isset($request->refadherent) && $request->refadherent != "") { - $refadherent = $request->refadherent; - } else { - $error = true; - } - // Erreur si paramètres mal renseignés - if ($error) { - $log->log_params = json_encode(['refcamp' => $request->refcamp, 'refadherent' => $request->refadherent]); - $log->log_statut = 'NOK'; - $log->log_message = "Des paramètres de la requête sont mal renseignés ou non présents"; - $log->save(); - - return Response::json([ - 'Statut' => 'KO', - 'Code' => 101, - 'Message' => 'Des paramètres de la requête sont mal renseignés ou non présents' - ]); - } - - // Check de la campagne - $campagne = Campagne::where('camp_id', $refcamp)->first(); - - if (!$campagne) { - $log->log_params = json_encode(['refcamp' => $request->refcamp, 'refadherent' => $request->refadherent]); - $log->log_statut = 'NOK'; - $log->log_message = "La campagne n'existe pas"; - $log->save(); - return Response::json([ - 'Statut' => 'KO', - 'Code' => 103, - 'Message' => 'La campagne n\'existe pas' - ]); - } - - - // Check du contact - $contact = Contact::where(['contact_ref' => $refadherent, 'contact_siteId' => $campagne->camp_siteId])->first(); - - if (!$contact) { - $log->log_params = json_encode(['refcamp' => $request->refcamp, 'refadherent' => $request->refadherent]); - $log->log_refsite = $campagne->camp_siteId; - $log->log_statut = 'NOK'; - $log->log_message = "Le contact n'existe pas"; - $log->save(); - - return Response::json([ - 'Statut' => 'KO', - 'Code' => 104, - 'Message' => 'Le contact n\'existe pas' - ]); - } - - if ($campagne) { - // Update - $mur = Mur::where(['mur_campId' => $refcamp, 'mur_contactId' => $contact->contact_id])->update(['mur_deleted' => '1']); - if ($mur != 0) { - $log->log_params = json_encode(['refcamp' => $request->refcamp, 'refadherent' => $request->refadherent]); - $log->log_refsite = $campagne->camp_siteId; - $log->log_contactId = $contact->contact_id; - $log->log_statut = 'OK'; - $log->log_message = $mur . " enregistrements ont été mis à jour."; - $log->save(); - return Response::json([ - 'Statut' => 'OK', - 'Message' => $mur . " enregistrements ont été mis à jour." - ]); - } else { - $log->log_params = json_encode(['refcamp' => $request->refcamp, 'refadherent' => $request->refadherent]); - $log->log_refsite = $campagne->camp_siteId; - $log->log_contactId = $contact->contact_id; - $log->log_statut = 'OK'; - $log->log_message = 'Aucun contrôle à effacer'; - $log->save(); - return Response::json([ - 'Statut' => 'KO', - 'Code' => 110, - 'Message' => 'Aucun contrôle à effacer' - ]); - }//end if - }//end if - return; - } - - public function montantDispoCampagne(Request $request) - { - - // ---- Contrôle des paramètres - if (isset($request->refcamp) && $request->refcamp != "") { - $refcamp = $request->refcamp; - } else { - return Response::json([ - 'Statut' => 'KO', - 'Code' => 101, - 'Message' => 'Des paramètres de la requête sont mal renseignés ou non présents' - ]); - } - - // ------ Recuperation de la campagne - $camp = Campagne::where(['camp_id' => $refcamp])->first(); - if (!$camp) { - return Response::json([ - 'Statut' => 'KO', - 'Code' => 103, - 'Message' => 'La campagne n\'existe pas' - ]); - } - - // ------ Récupération des coupons de la campagne - $coupons = $camp->coupons()->where(['coupon_published' => 1])->get(); - if (count($coupons) == 0) { - return Response::json([ - 'Statut' => 'KO', - 'Code' => 105, - 'Message' => 'La campagne est vide' - ]); - } - - // ---- Montant total et Nombre réductions disponible - $montantTotal = 0; - foreach ($coupons as $coupon) { - $montantTotal += $coupon->coupon_value; - } - - $montantTotal = number_format($montantTotal, 2, ",", " "); - $montantTotal = str_pad($montantTotal, 6, "0", STR_PAD_LEFT); - - return Response::json([ - 'Statut' => 'OK', - 'Message' => $montantTotal - ]); - } - - public function montantDispoContact(Request $request) - { - $error = false; - if (isset($request->refcamp) && $request->refcamp != "") { - $refcamp = $request->refcamp; - } else { - $error = true; - } - - if (isset($request->refsite) && $request->refsite != "") { - $refsite = $request->refsite; - } else { - $error = true; - } - - if (isset($request->refadherent) && $request->refadherent != "") { - $refadherent = $request->refadherent; - } else { - $error = true; - } - - if ($error) { - return Response::json([ - 'Statut' => 'KO', - 'Code' => 101, - 'Message' => 'Des paramètres de la requête sont mal renseignés ou non présents' - ]); - } - - $campagne = Campagne::where(['camp_id' => $refcamp])->where('camp_type', 'IN', array(0,2))->first(); - - if (!$campagne) { - return Response::json([ - 'Statut' => 'KO', - 'Code' => 103, - 'Message' => 'La campagne n\'existe pas' - ]); - } - - $contact = Contact::where(['contact_siteId' => $refsite, 'contact_ref' => $refadherent])->first(); - if (!$contact) { - return Response::json([ - 'Statut' => 'KO', - 'Code' => 104, - 'Message' => 'Le contact n\'existe pas' - ]); - } - - $coupons = $this->getCouponsPublished($campagne); - - foreach ($coupons as &$coupon) { - $coupon->isAvailable = $this->isAvailable($coupon, $campagne, $contact); - } - unset($coupon); - - $montantDispo = 0; - foreach ($coupons as $coupon) { - if ($coupon->isAvailable == true) { - $montantDispo += $coupon->coupon_value; - } - } - - $montantDispo = number_format($montantDispo, 2, ",", " "); - $montantDispo = str_pad($montantDispo, 6, "0", STR_PAD_LEFT); - - return Response::json([ - 'Statut' => 'OK', - 'Message' => $montantDispo - ]); - } -} diff --git a/app/Http/Controllers/PanierController.php b/app/Http/Controllers/PanierController.php index 5bbed0a..7d2252d 100644 --- a/app/Http/Controllers/PanierController.php +++ b/app/Http/Controllers/PanierController.php @@ -3,16 +3,13 @@ namespace App\Http\Controllers; use Illuminate\Http\Request; -use App\Panier; -use App\Campagne; -use App\Coupon; -use App\Contact; -use App\Site; -use App\Log; -use App\PanierContent; +use App\Models\Panier; +use App\Models\Campagne; +use App\Models\Coupon; +use App\Models\Contact; +use App\Enums\CampaignTypes; use App\Traits\CouponTrait; use App\Traits\ThanksTrait; -use Response; class PanierController extends Controller { @@ -40,7 +37,7 @@ class PanierController extends Controller } session()->put('campagne', $campagne); - if ($campagne->camp_type == 1) { + if ($campagne->camp_type->equals(CampaignTypes::panier())) { $coupons = $this->getCouponsPublished($campagne); } else { $panierContents = $this->getPanierContentPublished($panier); @@ -75,502 +72,13 @@ class PanierController extends Controller ->with(['ref' => $ref, 'coupons' => $coupons, 'contact' => $request->session()->get('contact')]); } - public function updateBasket(Request $request) - { - if (isset($request->admin)) { - $source = 'ADMIN'; - } else { - $source = 'API'; - } - // ---- INIT du log - $log = new Log(); - $log->log_action = config('constants.updatebasket'); - $log->log_source = $source; - - if (isset($request->basketid)) { - $basketid = $request->basketid; - if ($basketid != '') { - $panier = Panier::where('panier_ref', $basketid)->first(); - if (!$panier) { - $log->log_params = json_encode(['basketid' => $basketid]); - $log->log_statut = 'NOK'; - $log->log_message = "Le panier n'existe pas"; - $log->save(); - - return Response::json([ - 'Statut' => 'KO', - 'Code' => 106, - 'Message' => 'Le panier n\'existe pas' - ]); - } - - if (isset($request->panier) && $request->panier != "") { - $panier = $request->panier; - $panierTab = explode(",", $panier); - $coupons = array(); - foreach ($panierTab as $panier) { - $pos = strpos($panier, ")"); - if ($pos === false || substr_count($panier, ")") != 1) { - $log->log_params = json_encode(['basketid' => $basketid, 'panier' => $panier]); - $log->log_statut = 'NOK'; - $log->log_message = "Des paramètres de la requête sont mal renseignés ou non présents"; - $log->save(); - return Response::json([ - 'Statut' => 'KO', - 'Code' => 101, - 'Message' => 'Des paramètres de la requête sont mal renseignés ou non présents' - ]); - } - $quantity = substr($panier, 0, $pos); - $quantity = str_replace("(", "", $quantity); - $couponCode = substr($panier, $pos + 1); - - if (is_numeric($quantity) && is_numeric($couponCode)) { - if (isset($coupons[$couponCode])) { - $coupons[$couponCode] = $coupons[$couponCode] + $quantity; - } else { - $coupons[$couponCode] = $quantity; - } - } else { - $log->log_params = json_encode(['basketid' => $basketid, 'panier' => $panier]); - $log->log_statut = 'NOK'; - $log->log_message = "Des paramètres de la requête sont mal renseignés ou non présents"; - $log->save(); - return Response::json([ - 'Statut' => 'KO', - 'Code' => 101, - 'Message' => 'Des paramètres de la requête sont mal renseignés ou non présents' - ]); - } - }//end foreach - // ---- Préparation message de log avec coupons - $panierCoupons = array(); - foreach ($coupons as $code => $qty) { - array_push($panierCoupons, ['cp_code' => $code, 'qty' => $qty]); - } - if (sizeof($coupons) == 0) { - die(); - } - } else { - $log->log_params = json_encode(['basketid' => $basketid, 'panier' => $panier]); - $log->log_statut = 'NOK'; - $log->log_message = "Des paramètres de la requête sont mal renseignés ou non présents"; - $log->save(); - return Response::json([ - 'Statut' => 'KO', - 'Code' => 101, - 'Message' => 'Des paramètres de la requête sont mal renseignés ou non présents' - ]); - }//end if - - // ---- MAJ du panier - $panier = Panier::where('panier_ref', $basketid)->first(); - if ($panier) { - foreach ($coupons as $couponCode => $quantity) { - $cp = Coupon::where('coupon_code', $couponCode)->first(); - $exists = $cp->campagnes->contains($panier->panier_campId); - if ($cp && $exists) { - $site = $cp->coupon_siteId; - $panierContent = PanierContent::where(['panier_content_panierId' => $panier->panier_id, 'panier_content_couponId' => $cp->coupon_id])->first(); - if ($panierContent) { - $quantity += $panierContent->panier_content_quantity; - if ($quantity <= 0) { - $quantity = 0; - } - // MAJ du contenu - $panierContent->panier_content_quantity = $quantity; - $panierContent->save(); - } else { - // Ajout du contenu - if ($quantity > 0) { - $panierNewContent = new PanierContent(); - $panierNewContent->panier_content_panierId = $panier->panier_id; - $panierNewContent->panier_content_couponId = $cp->coupon_id; - $panierNewContent->panier_content_quantity = $quantity; - $panierNewContent->save(); - } - } - } else { - $log->log_params = json_encode(['refcamp' => $request->refcamp, 'refadherent' => $request->refadherent, 'refsite' => $request->refsite, 'nom' => $request->nom, 'prenom' => $request->prenom, 'email' => $request->email, 'code postal' => $request->code_postal, 'commune' => $request->commune, 'panier' => $request->panier]); - $log->log_statut = 'NOK'; - $log->log_message = "Le coupon ne correspond pas aux coupons liés a la campagne"; - $log->save(); - - return Response::json([ - 'Statut' => 'KO', - 'Code' => 110, - 'Message' => 'Le coupon ne correspond pas aux coupons liés a la campagne' - ]); - }//end if - }//end foreach - // MAJ du status du panier - $qty = $panier->panierContents()->sum('panier_content_quantity'); - if ($qty == 0) { - $panier_pending = 0; - } else { - $panier_pending = 1; - } - $panier->panier_pending = $panier_pending; - $panier->save(); - - $campagne = Campagne::where(['camp_id' => $panier->panier_campId])->first(); - // var_dump($panier->panier_campId); - $log->log_refsite = $campagne->camp_siteId; - $log->log_contactId = $panier->panier_contactId; - $log->log_params = json_encode(['refcamp' => $panier->panier_campId, 'basketid' => $basketid, 'panier' => $panier]); - $log->log_statut = 'OK'; - $log->log_message = json_encode(['Message' => 'Le panier a bien été créé/mis à jour', 'Coupons' => $panierCoupons], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); - $log->save(); - - $contact = Contact::where(['contact_id' => $panier->panier_contactId])->first(); - $site = Site::where(['site_id' => $campagne->camp_siteId])->first(); - - if (isset($contact->contact_nom) && isset($site->site_nom)) { - if ($panier->panier_pending == 1) { - $encours = "oui"; - } else { - $encours = "non"; - } - $response = new \stdClass(); - $response->Site = $site->site_nom . " (" . $site->site_id . ")"; - $response->Campagne = $campagne->camp_name . " (" . $campagne->camp_id . ")"; - $response->Panier = $panier->panier_ref; - $response->DateCreation = date("d/m/Y", strtotime($panier->panier_createdate)); - $response->EnCours = $encours; - $response->Nom = $contact->contact_nom; - $response->Prenom = $contact->contact_prenom; - $response->Email = $contact->contact_email; - $response->CodePostal = $contact->contact_cp; - $response->Commune = $contact->contact_ville; - - $allPanierContent = $panier->panierContents()->get(); - foreach ($allPanierContent as $panierContent) { - $panCont = []; - $coupon = Coupon::where(['coupon_id' => $panierContent->panier_content_couponId])->first(); - if ($coupon) { - array_push($panCont, $coupon->coupon_code . " - " . $coupon->coupon_name . " (x" . $panierContent->panier_content_quantity . ")"); - } - } - - $response->panierContent = $panCont; - - return Response::json([ - 'Statut' => 'OK', - 'Panier' => $response - ]); - } else { - return Response::json([ - 'Statut' => 'OK', - 'Panier' => $panier - ]); - }//end if - } else { - $log->log_params = json_encode(['basketid' => $basketid, 'panier' => $panier]); - $log->log_statut = 'NOK'; - $log->log_message = "Le panier n'existe pas"; - $log->save(); - return Response::json([ - 'Statut' => 'KO', - 'Code' => 106, - 'Message' => 'Le panier n\'existe pas' - ]); - }//end if - } else { - $log->log_params = json_encode(['basketid' => $basketid, 'panier' => $panier]); - $log->log_statut = 'NOK'; - $log->log_message = "Le panier n'existe pas"; - $log->save(); - return Response::json([ - 'Statut' => 'KO', - 'Code' => 106, - 'Message' => 'Le panier n\'existe pas' - ]); - }//end if - } else { - // ---- Contrôle des paramètres - $error = false; - if (isset($request->refcamp) && $request->refcamp != "") { - $refcamp = $request->refcamp; - $campagne = Campagne::where(['camp_id' => $refcamp])->first(); - if (!$campagne || $campagne->camp_published == 0 || ($campagne->camp_type != 1 && $campagne->camp_type != 3)) { - $log->log_params = json_encode(['refcamp' => $refcamp]); - $log->log_statut = 'NOK'; - $log->log_message = "La campagne n'existe pas ou n'est pas un panier"; - $log->save(); - - return Response::json([ - 'Statut' => 'KO', - 'Code' => 103, - 'Message' => 'La campagne n\'existe pas ou n\'est pas un panier' - ]); - } - } else { - $error = true; - } - if (isset($request->refadherent) && $request->refadherent != "") { - $refadherent = $request->refadherent; - } else { - $error = true; - } - if (isset($request->nom) && $request->nom != "") { - $nom = $request->nom; - } else { - $error = true; - } - if (isset($request->refsite) && $request->refsite != "") { - $refsite = $request->refsite; - if ($refsite != $campagne->camp_siteId) { - return Response::json([ - 'Statut' => 'KO', - 'Code' => 103, - 'Message' => 'La campagne ne correspond à aucune campagnes du site' - ]); - } - } else { - $error = true; - } - if (isset($request->prenom) && $request->prenom != "") { - $prenom = $request->prenom; - } else { - $error = true; - } - if (isset($request->email) && $request->email != "" && filter_var($request->email, FILTER_VALIDATE_EMAIL)) { - $email = $request->email; - } else { - $error = true; - } - - if (isset($request->code_postal) && $request->code_postal != "") { - $code_postal = $request->code_postal; - } else { - $error = true; - } - if (isset($request->commune) && $request->commune != "") { - $commune = $request->commune; - } else { - $error = true; - } - - if (isset($request->pays) && $request->pays != "") { - if (filter_var($request->pays, FILTER_VALIDATE_INT)) { - $pays = $request->pays; - } else { - $error = true; - } - } else { - $pays = 250; - } - if (isset($request->panier) && $request->panier != "") { - $panier = $request->panier; - $panierTab = explode(",", $panier); - $coupons = array(); - foreach ($panierTab as $panier) { - $pos = strpos($panier, ")"); - if ($pos === false) { - $error = true; - } - $quantity = substr($panier, 0, $pos); - $quantity = str_replace("(", "", $quantity); - $couponCode = substr($panier, $pos + 1); - - if (is_numeric($quantity) && is_numeric($couponCode) && $quantity > 0) { - if (isset($coupons[$couponCode])) { - $coupons[$couponCode] = $coupons[$couponCode] + $quantity; - } else { - $coupons[$couponCode] = $quantity; - } - } - } - if (sizeof($coupons) == 0) { - die(); - } - } else { - $error = true; - }//end if - - // ---- Préparation message de log avec coupons - if (isset($coupons)) { - $panierCoupons = array(); - foreach ($coupons as $code => $qty) { - array_push($panierCoupons, ['cp_code' => $code, 'qty' => $qty]); - } - } - - - if ($error) { - $log->log_params = json_encode(['refcamp' => $request->refcamp, 'refadherent' => $request->refadherent, 'refsite' => $request->refsite, 'nom' => $request->nom, 'prenom' => $request->prenom, 'email' => $request->email, 'code postal' => $request->code_postal, 'commune' => $request->commune, 'panier' => $request->panier]); - $log->log_statut = 'NOK'; - $log->log_message = "Des paramètres de la requête sont mal renseignés ou non présents"; - $log->save(); - - return Response::json([ - 'Statut' => 'KO', - 'Code' => 101, - 'Message' => 'Des paramètres de la requête sont mal renseignés ou non présents' - ]); - } - - // ---- Ajout/MAJ du contact - $contact = Contact::where(['contact_siteId' => $refsite, 'contact_ref' => $refadherent])->first(); - if ($contact) { - // ---- Mise à jour du contact - $contact->contact_prenom = $prenom; - $contact->contact_nom = $nom; - $contact->contact_email = $email; - $contact->contact_cp = $code_postal; - $contact->contact_ville = $commune; - $contact->contact_country = $pays; - $contact->contact_updatedate = date('Y-m-d H:i:s'); - } else { - // ---- Création du contact - $site = Site::where('site_id', $refsite)->first(); - - if ($site) { - $contact = new Contact(); - $contact->contact_nom = $nom; - $contact->contact_prenom = $prenom; - $contact->contact_ref = $refadherent; - $contact->contact_email = $email; - $contact->contact_cp = $code_postal; - $contact->contact_ville = $commune; - $contact->contact_country = $pays; - $contact->contact_siteId = $refsite; - $contact->contact_hash = strtoupper(md5(uniqid(time(), true))); - } else { - $log->log_params = json_encode(['refcamp' => $request->refcamp, 'refadherent' => $request->refadherent, 'refsite' => $request->refsite, 'nom' => $request->nom, 'prenom' => $request->prenom, 'email' => $request->email, 'code postal' => $request->code_postal, 'commune' => $request->commune, 'panier' => $request->panier]); - $log->log_statut = 'NOK'; - $log->log_message = "Le site spécifié n'existe pas"; - $log->save(); - - return Response::json([ - 'Statut' => 'KO', - 'Code' => 102, - 'Message' => 'Le site spécifié n\'existe pas' - ]); - }//end if - }//end if - if (!$contact->save()) { - $log->log_params = json_encode(['refcamp' => $request->refcamp, 'refadherent' => $request->refadherent, 'refsite' => $request->refsite, 'nom' => $request->nom, 'prenom' => $request->prenom, 'email' => $request->email, 'code postal' => $request->code_postal, 'commune' => $request->commune, 'panier' => $request->panier]); - $log->log_statut = 'NOK'; - $log->log_message = "Une erreur est survenue"; - $log->save(); - return Response::json([ - 'Statut' => 'KO', - 'Code' => 109, - 'Message' => 'Une erreur est survenue' - ]); - } - - // ---- Ajout/MAJ du panier - $panier = Panier::where(['panier_campId' => $refcamp, 'panier_contactId' => $contact->contact_id, 'panier_pending' => 1])->first(); - if ($panier) { - foreach ($coupons as $couponCode => $quantity) { - $camp = Campagne::where('camp_id', $panier->panier_campId)->first(); - $cp = $camp->coupons()->where('coupon_code', $couponCode)->first(); - if ($cp) { - $panierContent = PanierContent::where(['panier_content_panierId' => $panier->panier_id, 'panier_content_couponId' => $cp->coupon_id])->first(); - if ($panierContent) { - // $quantity += $panierContent->panier_content_quantity; - $panierContent->panier_content_quantity = $quantity + $panierContent->panier_content_quantity; - // MAJ du contenu - $panierContent->save(); - // $panierContent->update(['panier_content_quantity', $quantity]); - } else { - // Ajout du contenu - if ($quantity > 0) { - $panierNewContent = new PanierContent(); - $panierNewContent->panier_content_panierId = $panier->panier_id; - $panierNewContent->panier_content_couponId = $cp->coupon_id; - $panierNewContent->panier_content_quantity = $quantity; - $panierNewContent->save(); - } - } - } - }//end foreach - } else { - // Ajout du panier et du contenu - $panierRef = strtoupper(md5(uniqid(time(), true))); - $panier = new Panier(); - $panier->panier_ref = $panierRef; - $panier->panier_campId = $refcamp; - $panier->panier_contactId = $contact->contact_id; - $panier->panier_createdate = date('Y-m-d H:i:s'); - $panier->save(); - - foreach ($coupons as $couponCode => $quantity) { - $cp = $campagne->coupons()->where('coupon_code', $couponCode)->first(); - if ($cp) { - // Ajout du contenu - if ($quantity > 0) { - $panierNewContent = new PanierContent(); - $panierNewContent->panier_content_panierId = $panier->panier_id; - $panierNewContent->panier_content_couponId = $cp->coupon_id; - $panierNewContent->panier_content_quantity = $quantity; - $panierNewContent->save(); - } - } - } - }//end if - - $log->log_params = json_encode(['refcamp' => $request->refcamp, 'refadherent' => $request->refadherent, 'refsite' => $request->refsite, 'nom' => $request->nom, 'prenom' => $request->prenom, 'email' => $request->email, 'code postal' => $request->code_postal, 'commune' => $request->commune, 'panier' => $request->panier]); - $log->log_contactId = $panier->panier_contactId; - $log->log_refsite = $request->refsite; - $log->log_statut = 'OK'; - $log->log_message = json_encode(['Message' => 'Le panier a bien été créé/mis à jour', 'Coupons' => $panierCoupons], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); - $log->save(); - - $contact = Contact::where(['contact_id' => $panier->panier_contactId])->first(); - $site = Site::where(['site_id' => $campagne->camp_siteId])->first(); - - if (isset($contact->contact_nom) && isset($site->site_nom)) { - if ($panier->panier_pending == 1) { - $encours = "oui"; - } else { - $encours = "non"; - } - $response = new \stdClass(); - $response->Site = $site->site_nom . " (" . $site->site_id . ")"; - $response->Campagne = $campagne->camp_name . " (" . $campagne->camp_id . ")"; - $response->Panier = $panier->panier_ref; - $response->DateCreation = date("d/m/Y", strtotime($panier->panier_createdate)); - $response->EnCours = $encours; - $response->Nom = $contact->contact_nom; - $response->Prenom = $contact->contact_prenom; - $response->Email = $contact->contact_email; - $response->CodePostal = $contact->contact_cp; - $response->Commune = $contact->contact_ville; - - $allPanierContent = $panier->panierContents()->get(); - $panCont = []; - foreach ($allPanierContent as $panierContent) { - $coupon = Coupon::where(['coupon_id' => $panierContent->panier_content_couponId])->first(); - if ($coupon) { - array_push($panCont, $coupon->coupon_code . " - " . $coupon->coupon_name . " (x" . $panierContent->panier_content_quantity . ")"); - } - } - - $response->panierContent = $panCont; - - return Response::json([ - 'Statut' => 'OK', - 'Panier' => $response - ]); - } else { - return Response::json([ - 'Statut' => 'OK', - 'Panier' => $panier - ]); - }//end if - }//end if - } - public function showBasket(Request $request) { // ---- Contrôle des paramètres if (isset($request->basketid) && $request->basketid != "") { $basketid = $request->basketid; } else { - return Response::json([ + return response()->json([ 'Statut' => 'KO', 'Code' => 106, 'Message' => 'Le panier n\'existe pas' @@ -579,7 +87,7 @@ class PanierController extends Controller $panier = Panier::where('panier_ref', $basketid)->first(); if (!$panier) { - return Response::json([ + return response()->json([ 'Statut' => 'KO', 'Code' => 106, 'Message' => 'Le panier n\'existe pas' @@ -594,7 +102,7 @@ class PanierController extends Controller $contact = $panier->contact()->where(['contact_id' => $panier->panier_contactId])->first(); if (!$contact) { - return Response::json([ + return response()->json([ 'Statut' => 'KO', 'Code' => 104, 'Message' => 'Le contact n\'existe pas' @@ -603,7 +111,7 @@ class PanierController extends Controller $campagne = $panier->campagne()->where(['camp_id' => $panier->panier_campId])->first(); if (!$campagne) { - return Response::json([ + return response()->json([ 'Statut' => 'KO', 'Code' => 103, 'Message' => 'La campagne n\'existe pas' @@ -612,7 +120,7 @@ class PanierController extends Controller $site = $campagne->site()->first(); if ($site === null) { - return Response::json([ + return response()->json([ 'Statut' => 'KO', 'Code' => 102, 'Message' => 'Le site n\'existe pas' @@ -621,7 +129,7 @@ class PanierController extends Controller $allPanierContent = $panier->panierContents()->get(); if ($allPanierContent->count() == 0) { - return Response::json([ + return response()->json([ 'Statut' => 'KO', 'Code' => 108, 'Message' => 'Le panier n\'a pas de coupons liés' @@ -649,7 +157,7 @@ class PanierController extends Controller $response->panierContent = $panCont; - return Response::json([ + return response()->json([ 'Statut' => 'OK', 'Informations Panier' => $response ]); diff --git a/app/Http/Controllers/RedirectController.php b/app/Http/Controllers/RedirectController.php index 8ec9049..289642f 100644 --- a/app/Http/Controllers/RedirectController.php +++ b/app/Http/Controllers/RedirectController.php @@ -15,16 +15,12 @@ class RedirectController extends Controller */ public function __invoke(Request $request) { - $mur = new Controllers\MurController(); $panier = new Controllers\PanierController(); if (isset($request->basketid)) { return $panier->showTemplate($request); -// $this->showTemplate($request); - } elseif (isset($request->hash)) { - return $mur->show($request); } else { - return redirect()->route('home'); + return redirect()->route('login'); } } } diff --git a/app/Http/Controllers/SiteController.php b/app/Http/Controllers/SiteController.php index db2a348..6be1064 100644 --- a/app/Http/Controllers/SiteController.php +++ b/app/Http/Controllers/SiteController.php @@ -2,8 +2,8 @@ namespace App\Http\Controllers; -use App\Site; -use App\User; +use App\Models\Site; +use App\Models\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; @@ -78,7 +78,7 @@ class SiteController extends Controller /** * Show the form for editing the specified resource. * - * @param \App\Site $site + * @param \App\Models\Site $site * @return \Illuminate\Http\Response */ public function edit(Site $site) @@ -90,7 +90,7 @@ class SiteController extends Controller * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request - * @param \App\Site $site + * @param \App\Models\Site $site * @return \Illuminate\Http\Response */ public function update(Request $request, Site $site) diff --git a/app/Http/Controllers/StatistiqueController.php b/app/Http/Controllers/StatistiqueController.php deleted file mode 100644 index 3df7c33..0000000 --- a/app/Http/Controllers/StatistiqueController.php +++ /dev/null @@ -1,120 +0,0 @@ -sites()->get(); - foreach ($sites as $site) { - if (isset($site->campagnes)) { - $campagnes = $site->campagnes; - foreach ($campagnes as $campagne) { - switch ($campagne->camp_type) { - case 0: - $campagne->camp_type = "Mur"; - break; - case 1: - $campagne->camp_type = "Panier"; - break; - case 2: - $campagne->camp_type = "Mur sans sélection"; - break; - case 3: - $campagne->camp_type = "Panier Sélectionnable"; - break; - } - $coupons = $campagne->coupons; - foreach ($coupons as $coupon) { - $coupon->quantity = $this->getFullQuantity($coupon); - $coupon->remain = $this->getFullQuantity($coupon) - $this->getUsedQuantity($coupon); - $coupon->diffused = $this->getDiffusedQuantity($coupon); - $coupon->isPrintable = $this->isAvailableToPrint($coupon, $campagne); - $coupon->isPaused = $this->isPausedToPrint($coupon, $campagne); - } - }//end foreach - }//end if - }//end foreach - return view('stats.index')->with(['sites' => $sites]); - } - - /** - * Show the stat detail of a campaign. - * - * @return \Illuminate\Http\Response - */ - public function statdetail(Campagne $campagne) - { - $count = 0; - $colors = config('constants.colors'); - switch ($campagne->camp_type) { - case 0: - $campagne->camp_type = "Mur"; - break; - case 1: - $campagne->camp_type = "Panier"; - break; - case 2: - $campagne->camp_type = "Mur sans sélection"; - break; - case 3: - $campagne->camp_type = "Panier Sélectionnable"; - break; - } - - $coupons = $campagne->coupons; - foreach ($coupons as $coupon) { - $coupon->quantity = $this->getFullQuantity($coupon); - $coupon->remain = $coupon->quantity - $this->getUsedQuantity($coupon); - $coupon->diffused = $this->getDiffusedQuantity($coupon); - $coupon->isPrintable = $this->isAvailableToPrint($coupon, $campagne); - $coupon->isPaused = $this->isPausedToPrint($coupon, $campagne); - $coupon->color = $coupon->color = "#" . str_pad(dechex(mt_rand(0, 255)), 2, '0', STR_PAD_LEFT) . str_pad(dechex(mt_rand(0, 255)), 2, '0', STR_PAD_LEFT) . str_pad(dechex(mt_rand(0, 255)), 2, '0', STR_PAD_LEFT); - $count++; - } - $enddate = date('Y-m-d'); - $startdate = date('Y-m-d', strtotime("-30 days")); - return view('stats.detail')->with(['campagne' => $campagne, 'startdate' => $startdate, 'enddate' => $enddate]); - } - - public function load_stats(Request $request) - { - $campid = $request->campid; - $startdate = $request->startdate; - $enddate = $request->enddate; - - // ---- Labels pour la période - $labels = $this->getLabelsForStats($startdate, $enddate); - - // ---- Data pour le graphique global - $dataGlobal = $this->getDataForCamp($labels, $campid); - - // ---- Data pour le graphique par coupons - $campagne = Campagne::where(['camp_id' => $campid])->first(); - $coupons = $campagne->coupons; - $dataSpec = []; - foreach ($coupons as $coupon) { - $dataCoupon = $this->getDataForCoupon($labels, $campid, $coupon); - $dataSpec[$coupon->coupon_code] = $dataCoupon; - } - - $data = array('labels' => $labels, 'dataGlobal' => $dataGlobal, 'dataSpec' => $dataSpec); - - return json_encode($data); - } -} diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php index d4b0c2d..9742dae 100644 --- a/app/Http/Kernel.php +++ b/app/Http/Kernel.php @@ -60,11 +60,7 @@ class Kernel extends HttpKernel 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, - 'process.url' => \App\Http\Middleware\ProcessSpecificUrl::class, 'saveroute' => \App\Http\Middleware\SaveCurrentRoute::class, - 'superadmin' => \App\Http\Middleware\SuperAdmin::class, - 'admin' => \App\Http\Middleware\Admin::class, - 'marketing' => \App\Http\Middleware\Marketing::class, ]; /** diff --git a/app/Http/Middleware/Admin.php b/app/Http/Middleware/Admin.php deleted file mode 100644 index 67d123d..0000000 --- a/app/Http/Middleware/Admin.php +++ /dev/null @@ -1,27 +0,0 @@ -roles == 'admin') { - return $next($request); - } elseif (Auth::check() && Auth::user()->roles == 'superadmin') { - return $next($request); - } else { - return redirect('/bo/home'); - } - } -} diff --git a/app/Http/Middleware/Marketing.php b/app/Http/Middleware/Marketing.php deleted file mode 100644 index 90140a1..0000000 --- a/app/Http/Middleware/Marketing.php +++ /dev/null @@ -1,20 +0,0 @@ -path(); - $params = $request->all(); - $paramsCount = count($params); - $contact = new Controllers\ContactController(); - $mur = new Controllers\MurController(); - $panier = new Controllers\PanierController(); - $campagne = new Controllers\CampagneController(); - $ajax = new Controllers\AjaxController(); - switch ($path) { - case 'updatecontact': - $res = $contact->updateContact($request); - break; - case 'delctrlcontact': - $res = $mur->deleteControlContact($request); - break; - case 'mntdispocampagne': - $res = $mur->montantDispoCampagne($request); - break; - case 'mntdispocontact': - $res = $mur->montantDispoContact($request); - break; - case 'updatebasket': - $res = $panier->updateBasket($request); - break; - case 'showbasket': - $res = $panier->showBasket($request); - break; - case 'getdetailcampaign': - $res = $campagne->getDetail($request); - break; - case 'getdiffctccampaign': - $res = $campagne->getDiffCamp($request); - break; - case 'imprime': - $res = $panier->printPanierSelect($request); - return $next($request); - break; - case 'imprimer': - $res = $mur->printMur($request); - return $next($request); - break; - case 'merci': - $res = $mur->getThanks($request); - return $next($request); - break; - case 'merci-panier': - $res = $panier->getThanks($request); - return $next($request); - break; - case 'index': - $res = $ajax->backToIndex($request); - break; - default: - switch ($paramsCount) { - case 0: - return redirect('bo/home'); - break; - case 1: - $res = $panier->showTemplate($request); - return $next($request); - break; - case 3: - $res = $mur->show($request); - return $next($request); - break; - case 4: - $res = $mur->show($request); - return $next($request); - break; - default: - break; - } - break; - }//end switch - - return $res; - } -} diff --git a/app/Http/Middleware/RedirectIfAuthenticated.php b/app/Http/Middleware/RedirectIfAuthenticated.php index 69d750d..bc9bec4 100644 --- a/app/Http/Middleware/RedirectIfAuthenticated.php +++ b/app/Http/Middleware/RedirectIfAuthenticated.php @@ -18,7 +18,7 @@ class RedirectIfAuthenticated public function handle($request, Closure $next, $guard = null) { if (Auth::guard($guard)->check()) { - return redirect()->route('home'); + return redirect()->route('campagne.index'); } return $next($request); diff --git a/app/Http/Middleware/SaveCurrentRoute.php b/app/Http/Middleware/SaveCurrentRoute.php index 45bdab3..f1a64f3 100644 --- a/app/Http/Middleware/SaveCurrentRoute.php +++ b/app/Http/Middleware/SaveCurrentRoute.php @@ -2,8 +2,8 @@ namespace App\Http\Middleware; -use Auth; use Closure; +use Illuminate\Support\Facades\Auth; class SaveCurrentRoute { @@ -16,26 +16,22 @@ class SaveCurrentRoute */ public function handle($request, Closure $next) { - $routeName = explode('.', \Route::currentRouteName()); - - session()->put('active_route', $routeName[0]); - $site = session()->get('site'); - - if (!isset($site)) { - session()->put('site', Auth::user()->sites->first()); - } - - $currentLogo = session()->get('site')->only(['site_logo']); - session()->put('current_logo', $currentLogo); $siteId = session()->get('marques'); - if (!isset($siteId)) { - $marques = Auth::user()->sites; + if (!$site) { + $site = Auth::user()->sites->first(); + session()->put('site', $site); + } + + $currentLogo = $site->only(['site_logo']); + session()->put('current_logo', $currentLogo); + + if (!$siteId) { + $marques = Auth::user()->sites; $submarques = $marques->map(function ($marque) { return $marque->only(['id', 'site_nom', 'site_id', 'site_logo']); }); - session()->put('marques', $submarques); } diff --git a/app/Http/Middleware/SuperAdmin.php b/app/Http/Middleware/SuperAdmin.php deleted file mode 100644 index 2b89f20..0000000 --- a/app/Http/Middleware/SuperAdmin.php +++ /dev/null @@ -1,25 +0,0 @@ -roles == 'superadmin') { - return $next($request); - } else { - return redirect('/bo/home'); - } - } -} diff --git a/app/Http/Middleware/VerifyCsrfToken.php b/app/Http/Middleware/VerifyCsrfToken.php index 44c4e6b..533a515 100644 --- a/app/Http/Middleware/VerifyCsrfToken.php +++ b/app/Http/Middleware/VerifyCsrfToken.php @@ -22,6 +22,5 @@ class VerifyCsrfToken extends Middleware 'updatecontact', 'updatebasket', 'showbasket', - 'delctrlcontact' ]; } diff --git a/app/Http/Requests/Bo/Users/DestroyUserRequest.php b/app/Http/Requests/Bo/Users/DestroyUserRequest.php new file mode 100644 index 0000000..40d6597 --- /dev/null +++ b/app/Http/Requests/Bo/Users/DestroyUserRequest.php @@ -0,0 +1,31 @@ + 'required|unique:users|email', + 'name' => 'required', + 'password' => 'min:8|required', + 'site' => 'required', + 'roles' => 'required' + ]; + } +} diff --git a/app/Http/Requests/Bo/Users/UpdateUserRequest.php b/app/Http/Requests/Bo/Users/UpdateUserRequest.php new file mode 100644 index 0000000..6bc8570 --- /dev/null +++ b/app/Http/Requests/Bo/Users/UpdateUserRequest.php @@ -0,0 +1,38 @@ + [ + 'required', + Rule::unique('users')->ignore($this->user->id) + ], + 'name' => 'required', + 'site' => 'required', + 'roles' => 'required' + ]; + } +} diff --git a/app/Http/Requests/BrandChange/InvokeBrandChange.php b/app/Http/Requests/BrandChange/InvokeBrandChange.php new file mode 100644 index 0000000..29dbc2f --- /dev/null +++ b/app/Http/Requests/BrandChange/InvokeBrandChange.php @@ -0,0 +1,32 @@ +roles === UserRoles::superadmin()->value || Auth::user()->roles === UserRoles::admin()->value); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array + */ + public function rules() + { + return [ + 'site_id' => 'exists:site,id|required' + ]; + } +} diff --git a/app/Http/Requests/Campaign/AddCouponsCampaign.php b/app/Http/Requests/Campaign/AddCouponsCampaign.php new file mode 100644 index 0000000..70cb340 --- /dev/null +++ b/app/Http/Requests/Campaign/AddCouponsCampaign.php @@ -0,0 +1,32 @@ +roles === UserRoles::superadmin()->value || Auth::user()->roles === UserRoles::admin()->value); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array + */ + public function rules() + { + return [ + 'ids' => 'required' + ]; + } +} diff --git a/app/Http/Requests/Campaign/DeleteCampaign.php b/app/Http/Requests/Campaign/DeleteCampaign.php new file mode 100644 index 0000000..ea20b3f --- /dev/null +++ b/app/Http/Requests/Campaign/DeleteCampaign.php @@ -0,0 +1,32 @@ +roles === UserRoles::superadmin()->value || Auth::user()->roles === UserRoles::admin()->value); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array + */ + public function rules() + { + return [ + // + ]; + } +} diff --git a/app/Http/Requests/Campaign/RemoveCouponCampaign.php b/app/Http/Requests/Campaign/RemoveCouponCampaign.php new file mode 100644 index 0000000..03fea9c --- /dev/null +++ b/app/Http/Requests/Campaign/RemoveCouponCampaign.php @@ -0,0 +1,32 @@ +roles === UserRoles::superadmin()->value || Auth::user()->roles === UserRoles::admin()->value); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array + */ + public function rules() + { + return [ + // + ]; + } +} diff --git a/app/Http/Requests/Campaign/RemoveNotifCampaign.php b/app/Http/Requests/Campaign/RemoveNotifCampaign.php new file mode 100644 index 0000000..58940b0 --- /dev/null +++ b/app/Http/Requests/Campaign/RemoveNotifCampaign.php @@ -0,0 +1,32 @@ +roles === UserRoles::superadmin()->value || Auth::user()->roles === UserRoles::admin()->value); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array + */ + public function rules() + { + return [ + // + ]; + } +} diff --git a/app/Http/Requests/Campaign/ShowDemoCampaign.php b/app/Http/Requests/Campaign/ShowDemoCampaign.php new file mode 100644 index 0000000..d937afd --- /dev/null +++ b/app/Http/Requests/Campaign/ShowDemoCampaign.php @@ -0,0 +1,32 @@ +roles === UserRoles::superadmin()->value || Auth::user()->roles === UserRoles::admin()->value); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array + */ + public function rules() + { + return [ + // + ]; + } +} diff --git a/app/Http/Requests/Campaign/StoreCampaign.php b/app/Http/Requests/Campaign/StoreCampaign.php new file mode 100644 index 0000000..6853f6a --- /dev/null +++ b/app/Http/Requests/Campaign/StoreCampaign.php @@ -0,0 +1,35 @@ +roles === UserRoles::superadmin()->value || Auth::user()->roles === UserRoles::admin()->value); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array + */ + public function rules() + { + return [ + 'camp_name' => 'min:5|required', + 'camp_type' => 'integer|required', + 'camp_published' => 'integer|required', + 'camp_limitedPrinting' => 'sometimes|integer|required' + ]; + } +} diff --git a/app/Http/Requests/Campaign/StoreNotifCampaign.php b/app/Http/Requests/Campaign/StoreNotifCampaign.php new file mode 100644 index 0000000..f997d4d --- /dev/null +++ b/app/Http/Requests/Campaign/StoreNotifCampaign.php @@ -0,0 +1,39 @@ +roles === UserRoles::superadmin()->value || Auth::user()->roles === UserRoles::admin()->value); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array + */ + public function rules() + { + return [ + 'notif_name' => 'min:5|required', + 'notif_email' => [ + 'required', + Rule::unique('notification')->where(function ($query) { + return $query->where('notif_campId', $this->campaign->camp_id); + }), + ] + ]; + } +} diff --git a/app/Http/Requests/Campaign/UpdateCampaign.php b/app/Http/Requests/Campaign/UpdateCampaign.php new file mode 100644 index 0000000..0dea541 --- /dev/null +++ b/app/Http/Requests/Campaign/UpdateCampaign.php @@ -0,0 +1,35 @@ +roles === UserRoles::superadmin()->value || Auth::user()->roles === UserRoles::admin()->value); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array + */ + public function rules() + { + return [ + 'camp_name' => 'min:5|required', + 'camp_type' => 'integer|required', + 'camp_published' => 'integer|required', + 'camp_limitedPrinting' => 'sometimes|integer|required' + ]; + } +} diff --git a/app/Http/Requests/Coupons/StoreCoupons.php b/app/Http/Requests/Coupons/StoreCoupons.php new file mode 100644 index 0000000..10ebf7d --- /dev/null +++ b/app/Http/Requests/Coupons/StoreCoupons.php @@ -0,0 +1,75 @@ +roles === UserRoles::superadmin()->value || Auth::user()->roles === UserRoles::admin()->value); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array + */ + public function rules() + { + return [ + 'coupon_code' => [ + 'required', + Rule::unique('coupon', 'coupon_code') + ], + 'coupon_name' => 'string|required', + 'coupon_value' => 'numeric|required', + 'coupon_validity_text' => 'required', + 'coupon_legal_mentions' => 'required', + 'coupon_decoration_image' => 'required|image|mimes:jpeg,png', + 'coupon_logo_image' => 'required|image|mimes:jpeg,png', + 'coupon_rcs' => 'required', + 'coupon_site_contact' => 'required', + 'coupon_seuil_alert' => 'integer|required', + + 'coupon_enablelimitperiod' => 'sometimes|integer|required', + 'coupon_enablelimitquantity' => 'sometimes|integer|required', + 'coupon_mindatediffusion' => 'nullable', + 'coupon_maxdatediffusion' => 'nullable', + 'coupon_validity' => 'integer|required', + 'coupon_maxdatevalidity' => 'nullable', + + 'coupon_legal_mentions_splitted' => 'sometimes|integer|required', + ]; + } + + /** + * Configure the validator instance. + * + * @param \Illuminate\Validation\Validator $validator + * @return void + */ + public function withValidator($validator) + { + $validator->sometimes('coupon_gs1code', 'required|image|mimes:jpeg', function ($input) { + return isset($input->coupon_norme); + }); + + $validator->sometimes('coupon_limitquantity', 'integer|required', function ($input) { + return !is_null($input->coupon_enablelimitquantity); + }); + + $validator->sometimes('coupon_limitperiod', 'integer|required', function ($input) { + return !is_null($input->coupon_enablelimitperiod); + }); + } +} diff --git a/app/Http/Requests/Coupons/UpdateCoupons.php b/app/Http/Requests/Coupons/UpdateCoupons.php new file mode 100644 index 0000000..d0808ee --- /dev/null +++ b/app/Http/Requests/Coupons/UpdateCoupons.php @@ -0,0 +1,82 @@ +roles === UserRoles::superadmin()->value || Auth::user()->roles === UserRoles::admin()->value); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array + */ + public function rules() + { + return [ + 'coupon_code' => [ + 'required', + Rule::unique('coupon', 'coupon_code')->ignore($this->coupon->coupon_id, 'coupon_id') + ], + 'coupon_name' => 'string|required', + 'coupon_value' => 'numeric|required', + 'coupon_seuil_alert' => 'integer|required', + 'coupon_enablelimitperiod' => 'sometimes|integer|required', + 'coupon_enablelimitquantity' => 'sometimes|integer|required', + 'coupon_mindatediffusion' => 'nullable', + 'coupon_maxdatediffusion' => 'nullable', + 'coupon_validity' => 'integer|required', + 'coupon_maxdatevalidity' => 'nullable', + + 'coupon_treatment_center' => 'integer|required', + 'coupon_validity_text' => 'required', + 'coupon_legal_mentions' => 'required', + + 'coupon_rcs' => 'required', + 'coupon_site_contact' => 'email|required', + + 'coupon_norme' => 'sometimes|integer|required', + 'coupon_published' => 'sometimes|integer|required', + 'coupon_legal_mentions_splitted' => 'sometimes|integer|required', + 'coupon_decoration_image' => 'image|mimes:jpeg,png', + 'coupon_logo_image' => 'image|mimes:jpeg,png', + ]; + } + + /** + * Configure the validator instance. + * + * @param \Illuminate\Validation\Validator $validator + * @return void + */ + public function withValidator($validator) + { + $validator->sometimes('coupon_gs1code', 'required|image|mimes:jpeg', function ($input) { + if (isset($input->coupon_gs1code_image_hidden)) { + return false; + } + return isset($input->coupon_norme); + }); + + $validator->sometimes('coupon_limitquantity', 'integer|required', function ($input) { + return !is_null($input->coupon_enablelimitquantity); + }); + + $validator->sometimes('coupon_limitperiod', 'integer|required', function ($input) { + return !is_null($input->coupon_enablelimitperiod); + }); + } +} diff --git a/app/Http/Requests/Customers/BasketRequest.php b/app/Http/Requests/Customers/BasketRequest.php new file mode 100644 index 0000000..706ad6e --- /dev/null +++ b/app/Http/Requests/Customers/BasketRequest.php @@ -0,0 +1,45 @@ + 'string|exists:campagne,camp_id|required', + 'hashcode' => 'string|exists:customers,hashcode|required' + ]; + } + + protected function failedValidation(Validator $validator) + { + if ($this->wantsJson()) { + throw new HttpResponseException(response()->json(new StatusResource([ + 'status' => 'KO', + 'code' => 422, + 'message' => $validator->errors()->messages() + ]), 422)); + } + } +} diff --git a/app/Http/Requests/Customers/SearchCustomers.php b/app/Http/Requests/Customers/SearchCustomers.php new file mode 100644 index 0000000..25357d2 --- /dev/null +++ b/app/Http/Requests/Customers/SearchCustomers.php @@ -0,0 +1,33 @@ +roles, [UserRoles::superadmin()->value, UserRoles::admin()->value]); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array + */ + public function rules() + { + return [ + 'email' => 'sometimes|email|required' + ]; + } +} diff --git a/app/Http/Requests/Export/PDFExport.php b/app/Http/Requests/Export/PDFExport.php new file mode 100644 index 0000000..82f938e --- /dev/null +++ b/app/Http/Requests/Export/PDFExport.php @@ -0,0 +1,34 @@ +roles === UserRoles::superadmin()->value || Auth::user()->roles === UserRoles::admin()->value); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array + */ + public function rules() + { + return [ + 'ids' => 'required', + 'startdate' => 'date|required', + 'enddate' => 'date|required' + ]; + } +} diff --git a/app/Http/Requests/Fo/Basket/PrintRequest.php b/app/Http/Requests/Fo/Basket/PrintRequest.php new file mode 100644 index 0000000..1fb855a --- /dev/null +++ b/app/Http/Requests/Fo/Basket/PrintRequest.php @@ -0,0 +1,49 @@ +basket->campagne; + + if (!$campagne->camp_type->equals(CampaignTypes::panier())) { + throw new \Exception('Campaign is not basket.'); + } + + if ($campagne->camp_published === 0) { + throw new \Exception('Campaign is not published.'); + } + if ($campagne->site->crm_token === null) { + throw new \Exception('CRM Token is missing.'); + } + if ($campagne->site->crm_password === null) { + throw new \Exception('CRM Password is missing.'); + } + } + + /** + * Get the validation rules that apply to the request. + * + * @return array + */ + public function rules() + { + return []; + } +} diff --git a/app/Http/Resources/CouponsResource.php b/app/Http/Resources/CouponsResource.php index ede0c41..2df0b81 100644 --- a/app/Http/Resources/CouponsResource.php +++ b/app/Http/Resources/CouponsResource.php @@ -14,7 +14,7 @@ class CouponsResource extends JsonResource */ public function toArray($request) { - return [ + $coupon = [ 'code' => $this->coupon_code, 'name' => $this->coupon_name, 'value' => $this->coupon_value, @@ -25,6 +25,13 @@ class CouponsResource extends JsonResource 'mobile_image_unavailable' => $this->returnUrl($this->coupon_thumbnail4), 'validity_text' => $this->coupon_validity_text ]; + + if (isset($this->isUsed)){ + return array_merge($coupon, [ + 'used' => $this->isUsed, + ]); + } + return $coupon; } private function returnUrl($assets) diff --git a/app/Jobs/ArchiveStatsJob.php b/app/Jobs/ArchiveStatsJob.php new file mode 100644 index 0000000..da491c2 --- /dev/null +++ b/app/Jobs/ArchiveStatsJob.php @@ -0,0 +1,67 @@ +where('date', '<', now()) + ->each(function ($stat) { + $archiveStat = new ArchiveStat(); + $archiveStat->quantity = $stat->stat_couponPrinted; + $archiveStat->date = $stat->date; + $archiveStat->archive_coupon_id = $stat->stat_couponId; + $archiveStat->archive_campaign_id = $stat->stat_campId; + $archiveStat->saveOrFail(); + }); + + Statistique::query() + ->where('date', '<', now()) + ->delete(); + }); + } catch (\Exception $e) { + Log::error( + sprintf( + "ArchiveStatsJob failed - Code : %s - %s", + $e->getCode(), + $e->getMessage(), + ) + ); + \report($e); + } //end try + } +} diff --git a/app/Jobs/CleanOldDatasJob.php b/app/Jobs/CleanOldDatasJob.php new file mode 100644 index 0000000..af0bde5 --- /dev/null +++ b/app/Jobs/CleanOldDatasJob.php @@ -0,0 +1,81 @@ +where('contact_updatedate', '<', now()->subYears(3)) + ->delete(); + Log::info(\sprintf( + 'CleanOldDatasJob : %s contacts deleted', + $deletedContact + )); + + // Delete old customers. + $deletedCustomers = Customers::query() + ->where('updated_at', '<', now()->subYears(3)) + ->delete(); + Log::info(\sprintf( + 'CleanOldDatasJob : %s customers deleted', + $deletedCustomers + )); + + // Delete old logs. + $deletedLogs = LogModel::query() + ->where('created_at', '<', now()->subYears(3)) + ->delete(); + Log::info(\sprintf( + 'CleanOldDatasJob : %s logs deleted', + $deletedLogs + )); + }); + } catch (\Exception $e) { + Log::error( + sprintf( + "CleanOldDatasJob failed - Code : %s - %s", + $e->getCode(), + $e->getMessage(), + ) + ); + \report($e); + } //end try + } +} diff --git a/app/Jobs/DeleteCrmCustomerJob.php b/app/Jobs/DeleteCrmCustomerJob.php new file mode 100644 index 0000000..74ddf84 --- /dev/null +++ b/app/Jobs/DeleteCrmCustomerJob.php @@ -0,0 +1,108 @@ +onConnection('rabbitmq'); + $this->customer = $customer; + } + + /** + * Execute the job. + * + * @return void + */ + public function handle() + { + $hashchode = $this->customer['hashcode']; + $email = $this->customer['email']; + + try { + DB::transaction(function () use ($hashchode, $email) { + // For baskets and old walls. + $contact = Contact::query()->where('contact_ref', $hashchode)->first(); + if ($contact) { + $contact->deleteOrFail(); + + $this->writeCsvLog('Contact deleted'); + } + + // For walls. + $customer = Customers::query()->where('hashcode', $hashchode)->first(); + if ($customer) { + $customer->deleteOrFail(); + + $this->writeCsvLog('Customer deleted'); + } + }); + } catch (\Exception $e) { + Log::info( + sprintf( + "DeleteCrmCustomerJob failed - Code : %s - %s", + $e->getCode(), + $e->getMessage(), + ) + ); + \report($e); + } //end try + } + + /** + * Write logs in /logs/crm.csv. + * + * @param string $message + * + * @return void + */ + private function writeCsvLog(string $message) + { + + $csvPath = \storage_path('/logs/crm.csv'); + if (!\file_exists($csvPath)) { + $logFile = fopen($csvPath, 'w'); + \fputcsv($logFile, ['date', 'hashcode', 'email', 'action'], ';'); + \fclose($logFile); + } + + $logFile = fopen($csvPath, 'a'); + \fputcsv( + $logFile, + [ + \now()->toAtomString(), + $this->customer['hashcode'], + $this->customer['email'], + $message + ], + ';' + ); + \fclose($logFile); + } +} diff --git a/app/Lib/Helpers/ToolboxHelper.php b/app/Lib/Helpers/ToolboxHelper.php new file mode 100644 index 0000000..6238a46 --- /dev/null +++ b/app/Lib/Helpers/ToolboxHelper.php @@ -0,0 +1,104 @@ + $value], [ + self::mbReplace('.', '\.', $field) => Rule::unique($table, $field)->ignore($id), + ], [ + self::mbReplace('.', '\.', "{$field}.unique") + => trans('crud.libs.toolbox.assertFieldIsUnique', ['attribute' => $field, 'value' => $value]) + ])->validate(); + return; + } + Validator::make([$field => $value], [ + $field => Rule::unique($table)->where($query)->ignore($id), + ], [ + $field . '.unique' => trans( + 'crud.libs.toolbox.assertFieldIsUnique', + ['attribute' => $field, 'value' => $value] + ) + ])->validate(); + } +} diff --git a/app/Models/ArchiveCampaign.php b/app/Models/ArchiveCampaign.php new file mode 100644 index 0000000..ba8073e --- /dev/null +++ b/app/Models/ArchiveCampaign.php @@ -0,0 +1,82 @@ + + */ + protected $fillable = [ + 'name', + 'campaign_id', + 'archive_site_id' + ]; + + /** + * Perform any actions required after the model boots. + * + * @return void + */ + protected static function booted(): void + { + static::creating(function (self $model) { + $model->assertFieldIsUnique('campaign_id', $model->campaign_id); + $site = Site::query()->where('site_id', $model->archive_site_id)->firstOrFail(); + $archiveSite = ArchiveSite::query()->firstOrCreate( + [ + 'site_id' => $model->archive_site_id + ], + [ + 'name' => $site->site_nom + ] + ); + $model->archiveSite()->associate($archiveSite); + }); + static::updating(function () { + throw new \RuntimeException('Updating an archived campaign is not authorized'); + }); + static::deleting(function () { + throw new \RuntimeException('Deleting an archived campaign is not authorized'); + }); + } + + // * RELATIONS + + /** + * ArchiveSite model relation + * @return Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function archiveSite() + { + return $this->belongsTo(ArchiveSite::class); + } + + /** + * ArchiveSite model relation + * @return Illuminate\Database\Eloquent\Relations\HasMany + */ + public function archiveStat() + { + return $this->hasMany(ArchiveStat::class); + } +} diff --git a/app/Models/ArchiveCoupon.php b/app/Models/ArchiveCoupon.php new file mode 100644 index 0000000..e93fd19 --- /dev/null +++ b/app/Models/ArchiveCoupon.php @@ -0,0 +1,60 @@ + + */ + protected $fillable = [ + 'name', + 'coupon_code', + ]; + + /** + * Perform any actions required after the model boots. + * + * @return void + */ + protected static function booted(): void + { + static::creating(function (self $model) { + $model->assertFieldIsUnique('coupon_code', $model->coupon_code); + }); + static::updating(function () { + throw new \RuntimeException('Updating an archived coupon is not authorized'); + }); + static::deleting(function () { + throw new \RuntimeException('Deleting an archived coupon is not authorized'); + }); + } + + // * RELATIONS + + /** + * ArchiveStat model relation + * @return Illuminate\Database\Eloquent\Relations\HasMany + */ + public function archiveStat() + { + return $this->hasMany(ArchiveStat::class); + } +} diff --git a/app/Models/ArchiveSite.php b/app/Models/ArchiveSite.php new file mode 100644 index 0000000..b19b48f --- /dev/null +++ b/app/Models/ArchiveSite.php @@ -0,0 +1,60 @@ + + */ + protected $fillable = [ + 'name', + 'site_id', + ]; + + /** + * Perform any actions required after the model boots. + * + * @return void + */ + protected static function booted(): void + { + static::creating(function (self $model) { + $model->assertFieldIsUnique('site_id', $model->site_id); + }); + static::updating(function (self $model) { + throw new \RuntimeException('Updating an archived site is not authorized'); + }); + static::deleting(function () { + throw new \RuntimeException('Deleting an archived site is not authorized'); + }); + } + + // * RELATIONS + + /** + * ArchiveCampaign model relation + * @return Illuminate\Database\Eloquent\Relations\HasMany + */ + public function archiveCampaign() + { + return $this->hasMany(ArchiveCampaign::class); + } +} diff --git a/app/Models/ArchiveStat.php b/app/Models/ArchiveStat.php new file mode 100644 index 0000000..2f6e0ea --- /dev/null +++ b/app/Models/ArchiveStat.php @@ -0,0 +1,91 @@ + + */ + protected $fillable = [ + 'date', + 'quantity', + ]; + + /** + * Perform any actions required after the model boots. + * + * @return void + */ + protected static function booted(): void + { + static::creating(function (self $model) { + $campaign = Campagne::withTrashed()->where('camp_id', $model->archive_campaign_id)->firstOrFail(); + $archiveCampaign = ArchiveCampaign::query()->firstOrCreate( + [ + 'campaign_id' => $model->archive_campaign_id + ], + [ + 'name' => $campaign->camp_name, + 'archive_site_id' => $campaign->camp_siteId, + ] + ); + $model->archiveCampaign()->associate($archiveCampaign); + + $coupon = Coupon::withTrashed()->where('coupon_id', $model->archive_coupon_id)->firstOrFail(); + $archiveCoupon = ArchiveCoupon::query()->firstOrCreate( + [ + 'coupon_code' => $model->archive_coupon_id + ], + [ + 'name' => $coupon->coupon_code, + ] + ); + $model->archiveCoupon()->associate($archiveCoupon); + }); + static::updating(function () { + throw new \RuntimeException('Upating an archived stat is not authorized'); + }); + static::deleting(function () { + throw new \RuntimeException('Deleting an archived stat is not authorized'); + }); + } + + // * RELATIONS + + /** + * ArchiveCoupon model relation + * @return Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function archiveCoupon() + { + return $this->belongsTo(ArchiveCoupon::class); + } + + /** + * ArchiveCampaign model relation + * @return Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function archiveCampaign() + { + return $this->belongsTo(ArchiveCampaign::class); + } +} diff --git a/app/Models/Basket.php b/app/Models/Basket.php new file mode 100644 index 0000000..283c36b --- /dev/null +++ b/app/Models/Basket.php @@ -0,0 +1,41 @@ +belongsTo(Customers::class, 'customer_id', 'id'); + } + + /** + * Campagne model relation + * @return BelongsTo + */ + public function campagne() + { + return $this->belongsTo(Campagne::class, 'campagne_id', 'camp_id'); + } + + /** + * BasketContent model relation + * @return HasMany + */ + public function contents() + { + return $this->hasMany(BasketContent::class); + } +} diff --git a/app/Models/BasketContent.php b/app/Models/BasketContent.php new file mode 100644 index 0000000..da506fb --- /dev/null +++ b/app/Models/BasketContent.php @@ -0,0 +1,43 @@ +printed = 0; + }); + } + + /** + * Basket model relation + * @return HasOne + */ + public function basket() + { + return $this->hasOne(Basket::class); + } + + /** + * Coupon model relation + * @return HasOne + */ + public function coupon() + { + return $this->hasOne(Coupon::class, 'coupon_id', 'coupon_id'); + } +} diff --git a/app/Calendrier.php b/app/Models/Calendrier.php similarity index 86% rename from app/Calendrier.php rename to app/Models/Calendrier.php index 2d6499a..12da07e 100644 --- a/app/Calendrier.php +++ b/app/Models/Calendrier.php @@ -1,6 +1,6 @@ belongsTo('App\Coupon', 'calendrier_couponId'); + return $this->belongsTo('App\Models\Coupon', 'calendrier_couponId'); } } diff --git a/app/Campagne.php b/app/Models/Campagne.php similarity index 53% rename from app/Campagne.php rename to app/Models/Campagne.php index 8c127f1..d4705fb 100644 --- a/app/Campagne.php +++ b/app/Models/Campagne.php @@ -1,13 +1,36 @@ CampaignTypes::class + ]; + + /** + * @var array + */ + protected $fillable = [ + 'camp_siteId', + 'camp_name', + 'camp_type', + 'camp_limitedPrinting', + 'camp_published' + ]; /** * @var string @@ -47,7 +70,7 @@ class Campagne extends Model */ public function notifications() { - return $this->hasMany('App\Notification', 'notif_campId', 'camp_id'); + return $this->hasMany('App\Models\Notification', 'notif_campId', 'camp_id'); } /** @@ -56,7 +79,7 @@ class Campagne extends Model */ public function murs() { - return $this->hasMany('App\Mur', 'mur_campId', 'camp_id'); + return $this->hasMany('App\Models\Mur', 'mur_campId', 'camp_id'); } /** @@ -65,7 +88,7 @@ class Campagne extends Model */ public function paniers() { - return $this->hasMany('App\Panier', 'panier_campId', 'camp_id'); + return $this->hasMany('App\Models\Panier', 'panier_campId', 'camp_id'); } /** @@ -74,7 +97,7 @@ class Campagne extends Model */ public function site() { - return $this->belongsTo('App\Site', 'camp_siteId', 'site_id'); + return $this->belongsTo('App\Models\Site', 'camp_siteId', 'site_id'); } /** @@ -82,17 +105,24 @@ class Campagne extends Model */ public function coupons() { - return $this->belongsToMany('App\Coupon', 'campagne_coupon', 'campagne_id', 'coup_id'); + return $this->belongsToMany('App\Models\Coupon', 'campagne_coupon', 'campagne_id', 'coup_id'); } /** - * @var array + * printedCoupons relation + * @return HasMany */ - protected $fillable = [ - 'camp_siteId', - 'camp_name', - 'camp_type', - 'camp_limitedPrinting', - 'camp_published' - ]; + public function printedCoupons() + { + return $this->hasMany(PrintedCoupons::class, 'camp_id'); + } + + /** + * Basket model relation + * @return HasMany + */ + public function baskets() + { + return $this->hasMany(Basket::class); + } } diff --git a/app/Contact.php b/app/Models/Contact.php similarity index 76% rename from app/Contact.php rename to app/Models/Contact.php index 28c86bc..c95e56a 100644 --- a/app/Contact.php +++ b/app/Models/Contact.php @@ -1,11 +1,16 @@ hasMany('App\Mur', 'mur_contactId', 'contact_id'); + return $this->hasMany('App\Models\Mur', 'mur_contactId', 'contact_id'); } /** @@ -54,7 +59,7 @@ class Contact extends Model */ public function paniers() { - return $this->hasMany('App\Panier', 'panier_contactId', 'contact_id'); + return $this->hasMany('App\Models\Panier', 'panier_contactId', 'contact_id'); } /** @@ -63,7 +68,7 @@ class Contact extends Model */ public function site() { - return $this->belongsTo('App\Site', 'contact_siteId'); + return $this->belongsTo('App\Models\Site', 'contact_siteId'); } public function scopeSearchName($query, $name) @@ -107,4 +112,14 @@ class Contact extends Model $query->where('contact_country', $country); } } + + /** + * log relation + * + * @return HasMany + */ + public function logs() + { + return $this->hasMany(Log::class, 'log_contactId', 'contact_id'); + } } diff --git a/app/Coupon.php b/app/Models/Coupon.php similarity index 71% rename from app/Coupon.php rename to app/Models/Coupon.php index cab9d0b..d7e2cd5 100644 --- a/app/Coupon.php +++ b/app/Models/Coupon.php @@ -1,13 +1,16 @@ Calendrier - */ - public function calendriers() - { - return $this->hasMany('App\Calendrier', 'calendrier_couponId', 'coupon_id'); - } - - /** - * OneToMany - * Coupon -> PanierContent - */ - public function panierContents() - { - return $this->hasMany('App\PanierContent', 'panier_content_couponId', 'coupon_id'); - } - - /** - * OneToMany - * Coupon -> Mur - */ - public function murs() - { - return $this->hasMany('App\Mur', 'mur_couponId', 'coupon_id'); - } - - /** - * OneToMany - * Coupon -> Mouvement - */ - public function mouvements() - { - return $this->hasMany('App\Mouvement', 'mouvement_couponId', 'coupon_id'); - } - - /** - * ManyToOne - * Coupon -> Site - */ - public function site() - { - return $this->belongsTo('App\Site', 'coupon_siteId'); - } - - /** - * The campagnes that belong to the coupon. - */ - public function campagnes() - { - return $this->belongsToMany('App\Campagne', 'campagne_coupon', 'coup_id', 'campagne_id'); - } - /** * @var array */ @@ -120,4 +70,66 @@ class Coupon extends Model 'coupon_seuil_alert', 'coupon_treatment_center' ]; + + /** + * OneToMany + * Coupon -> Calendrier + */ + public function calendriers() + { + return $this->hasMany('App\Models\Calendrier', 'calendrier_couponId', 'coupon_id'); + } + + /** + * OneToMany + * Coupon -> PanierContent + */ + public function panierContents() + { + return $this->hasMany('App\Models\PanierContent', 'panier_content_couponId', 'coupon_id'); + } + + /** + * OneToMany + * Coupon -> Mur + */ + public function murs() + { + return $this->hasMany('App\Models\Mur', 'mur_couponId', 'coupon_id'); + } + + /** + * OneToMany + * Coupon -> Mouvement + */ + public function mouvements() + { + return $this->hasMany('App\Models\Mouvement', 'mouvement_couponId', 'coupon_id'); + } + + /** + * ManyToOne + * Coupon -> Site + */ + public function site() + { + return $this->belongsTo('App\Models\Site', 'coupon_siteId'); + } + + /** + * The campagnes that belong to the coupon. + */ + public function campagnes() + { + return $this->belongsToMany('App\Models\Campagne', 'campagne_coupon', 'coup_id', 'campagne_id'); + } + + /** + * BasketContent model relation + * @return HasMany + */ + public function basketContents() + { + return $this->hasMany(BasketContent::class); + } } diff --git a/app/Models/Customers.php b/app/Models/Customers.php index 4aae55a..2e93077 100644 --- a/app/Models/Customers.php +++ b/app/Models/Customers.php @@ -2,16 +2,32 @@ namespace App\Models; +use App\Models\Panier; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\HasMany; class Customers extends Model { + /** + * @var string $primaryKey + */ protected $primaryKey = 'hashcode'; + /** + * @var string $keyType + */ protected $keyType = 'string'; + /** + * @var array $fillable + */ protected $fillable = ['hashcode', 'email', 'country']; + /** + * booted method + * + * @return void + */ protected static function booted() { static::creating(function ($customer) { @@ -23,19 +39,54 @@ class Customers extends Model }); } + /** + * getIsoCountry method + * Default is : France + * + * @param string $country + * @return integer + */ private function getIsoCountry($country) { $country = trim(ucfirst(strtolower($country))); switch ($country) { case 'Belgique': - return 56; - break; + $country = 56; + break; case 'Luxembourg': - return 442; - break; + $country = 442; + break; default: - return 250; -// France + $country = 250; } + return $country; + } + + /** + * Printed Coupons Relation + * + * @return HasMany + */ + public function printedCoupons() + { + return $this->hasMany(PrintedCoupons::class, 'customer_id', 'id'); + } + + /** + * Basket model relation + * @return HasMany + */ + public function baskets() + { + return $this->hasMany(Basket::class, 'customer_id', 'id'); + } + + /** + * Panier model relation + * @return HasMany + */ + public function paniers() + { + return $this->hasMany(Panier::class, 'panier_contactId', 'id'); } } diff --git a/app/Log.php b/app/Models/Log.php similarity index 96% rename from app/Log.php rename to app/Models/Log.php index 0ec3a99..5b1b330 100644 --- a/app/Log.php +++ b/app/Models/Log.php @@ -1,6 +1,6 @@ belongsTo('App\Coupon', 'mouvement_couponId'); + return $this->belongsTo('App\Models\Coupon', 'mouvement_couponId'); } } diff --git a/app/Mur.php b/app/Models/Mur.php similarity index 71% rename from app/Mur.php rename to app/Models/Mur.php index 1aa9edd..a811980 100644 --- a/app/Mur.php +++ b/app/Models/Mur.php @@ -1,6 +1,6 @@ belongsTo('App\Campagne', 'mur_campId'); + return $this->belongsTo('App\Models\Campagne', 'mur_campId'); } /** @@ -36,7 +36,7 @@ class Mur extends Model */ public function contact() { - return $this->belongsTo('App\Contact', 'mur_contactId'); + return $this->belongsTo('App\Models\Contact', 'mur_contactId'); } /** @@ -45,6 +45,6 @@ class Mur extends Model */ public function coupon() { - return $this->belongsTo('App\Coupon', 'mur_couponId'); + return $this->belongsTo('App\Models\Coupon', 'mur_couponId'); } } diff --git a/app/Notification.php b/app/Models/Notification.php similarity index 71% rename from app/Notification.php rename to app/Models/Notification.php index 5a9cecf..90203ba 100644 --- a/app/Notification.php +++ b/app/Models/Notification.php @@ -1,6 +1,6 @@ Campagne */ public function campagne() { - return $this->belongsTo('App\Campagne', 'notif_campId'); + return $this->belongsTo('App\Models\Campagne', 'notif_campId'); } } diff --git a/app/Panier.php b/app/Models/Panier.php similarity index 65% rename from app/Panier.php rename to app/Models/Panier.php index e8ec9e9..d1520d9 100644 --- a/app/Panier.php +++ b/app/Models/Panier.php @@ -1,11 +1,14 @@ hasMany('App\PanierContent', 'panier_content_panierId', 'panier_id'); + return $this->hasMany('App\Models\PanierContent', 'panier_content_panierId', 'panier_id'); } /** @@ -37,7 +40,7 @@ class Panier extends Model */ public function campagne() { - return $this->belongsTo('App\Campagne', 'panier_campId'); + return $this->belongsTo('App\Models\Campagne', 'panier_campId'); } /** @@ -46,6 +49,6 @@ class Panier extends Model */ public function contact() { - return $this->belongsTo('App\Contact', 'panier_contactId'); + return $this->belongsTo('App\Models\Contact', 'panier_contactId'); } } diff --git a/app/PanierContent.php b/app/Models/PanierContent.php similarity index 78% rename from app/PanierContent.php rename to app/Models/PanierContent.php index 89e33fe..48c013a 100644 --- a/app/PanierContent.php +++ b/app/Models/PanierContent.php @@ -1,6 +1,6 @@ belongsTo('App\Panier', 'panier_content_panierId', 'panier_id'); + return $this->belongsTo('App\Models\Panier', 'panier_content_panierId', 'panier_id'); } /** @@ -36,7 +36,7 @@ class PanierContent extends Model */ public function coupon() { - return $this->belongsTo('App\Coupon', 'panier_content_couponId'); + return $this->belongsTo('App\Models\Coupon', 'panier_content_couponId'); } /** diff --git a/app/Models/PrintedWalls.php b/app/Models/PrintedCoupons.php similarity index 81% rename from app/Models/PrintedWalls.php rename to app/Models/PrintedCoupons.php index fca2348..1ac08c8 100644 --- a/app/Models/PrintedWalls.php +++ b/app/Models/PrintedCoupons.php @@ -5,7 +5,7 @@ namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; -class PrintedWalls extends Model +class PrintedCoupons extends Model { use HasFactory; } diff --git a/app/Site.php b/app/Models/Site.php similarity index 70% rename from app/Site.php rename to app/Models/Site.php index 0b4614f..0c08ce3 100644 --- a/app/Site.php +++ b/app/Models/Site.php @@ -1,11 +1,14 @@ hasMany('App\Campagne', 'camp_siteId', 'site_id'); + return $this->hasMany('App\Models\Campagne', 'camp_siteId', 'site_id'); } /** @@ -46,7 +49,7 @@ class Site extends Model */ public function contacts() { - return $this->hasMany('App\Contact', 'contact_siteId', 'site_id'); + return $this->hasMany('App\Models\Contact', 'contact_siteId', 'site_id'); } /** @@ -54,7 +57,7 @@ class Site extends Model */ public function users() { - return $this->belongsToMany('App\User', 'site_user', 'site_id', 'user_id'); + return $this->belongsToMany('App\Models\User', 'site_user', 'site_id', 'user_id'); } /** @@ -63,7 +66,7 @@ class Site extends Model */ public function coupons() { - return $this->hasMany('App\Coupon', 'coupon_siteId', 'id'); + return $this->hasMany('App\Models\Coupon', 'coupon_siteId', 'id'); } /** diff --git a/app/Models/Statistique.php b/app/Models/Statistique.php new file mode 100644 index 0000000..db3fb96 --- /dev/null +++ b/app/Models/Statistique.php @@ -0,0 +1,73 @@ + 'date' + ]; + + /** + * Perform any actions required after the model boots. + * + * @return void + */ + protected static function booted(): void + { + static::creating(function (self $model) { + $model->date = now()->toDateString(); + }); + } + + // * RELATIONS + + /** + * ArchiveCoupon model relation + * @return Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function campaign() + { + return $this->belongsTo(Campagne::class, 'stat_campId', 'camp_id'); + } + + /** + * ArchiveCampaign model relation + * @return Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function coupon() + { + return $this->belongsTo(Coupon::class, 'stat_couponId', 'coupon_id'); + } +} diff --git a/app/User.php b/app/Models/User.php similarity index 86% rename from app/User.php rename to app/Models/User.php index bc4472c..e5b3e5e 100644 --- a/app/User.php +++ b/app/Models/User.php @@ -1,10 +1,10 @@ belongsToMany('App\Site', 'site_user', 'user_id', 'site_id'); + return $this->belongsToMany('App\Models\Site', 'site_user', 'user_id', 'site_id'); } diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php index 84c0428..7971bf7 100644 --- a/app/Providers/AuthServiceProvider.php +++ b/app/Providers/AuthServiceProvider.php @@ -12,7 +12,7 @@ class AuthServiceProvider extends ServiceProvider * @var array */ protected $policies = [ - 'App\Model' => 'App\Policies\ModelPolicy', + // 'App\Model' => 'App\Policies\ModelPolicy', ]; /** diff --git a/app/Statistique.php b/app/Statistique.php deleted file mode 100644 index 73de4b0..0000000 --- a/app/Statistique.php +++ /dev/null @@ -1,33 +0,0 @@ -coupon_published == 0) { - $availableToPrint = false; + /** + * Contrôle de la publication de la campagne + */ + if ($campagne->camp_published === 0) { + return false; + } + + // ---- Contrôle de la publication du coupon + if ($coupon->coupon_published === 0) { + return false; } // ---- Contrôle la date de début de diffusion - if ($coupon->coupon_mindatediffusion != null) { + if ($coupon->coupon_mindatediffusion !== null) { if (strtotime(date('Y-m-d')) < strtotime($coupon->coupon_mindatediffusion)) { - $availableToPrint = false; + return false; } } // ---- Contrôle la date de validité - if ($coupon->coupon_maxdatediffusion != null) { + if ($coupon->coupon_maxdatediffusion !== null) { if (strtotime(date('Y-m-d')) > strtotime($coupon->coupon_maxdatediffusion)) { - $availableToPrint = false; + return false; } } @@ -176,31 +184,25 @@ trait CouponTrait } } if (!$pub) { - $availableToPrint = false; + return false; } } - if ($campagne->camp_published == 0) { - $availableToPrint = false; - } - - return $availableToPrint; + return true; } public function isPausedToPrint(Coupon $coupon, Campagne $campagne) { - $availableToPrint = true; - // ---- Contrôle la date de début de diffusion - if ($coupon->coupon_mindatediffusion != null) { + if ($coupon->coupon_mindatediffusion !== null) { if (strtotime(date('Y-m-d')) < strtotime($coupon->coupon_mindatediffusion)) { - $availableToPrint = false; + return false; } } // ---- Contrôle la date de validité - if ($coupon->coupon_maxdatediffusion != null) { + if ($coupon->coupon_maxdatediffusion !== null) { if (strtotime(date('Y-m-d')) > strtotime($coupon->coupon_maxdatediffusion)) { - $availableToPrint = false; + return false; } } @@ -214,11 +216,11 @@ trait CouponTrait } } if (!$pub) { - $availableToPrint = false; + return false; } } - return $availableToPrint; + return true; } @@ -263,28 +265,22 @@ trait CouponTrait public function getFullQuantity(Coupon $coupon) { - $mouvements = $coupon->mouvements()->get(); - $nombre = array(); - foreach ($mouvements as $mouvement) { - array_push($nombre, $mouvement->mouvement_nombre); - } - return array_sum($nombre); + return (int)Mouvement::where('mouvement_couponId', $coupon->coupon_id)->sum('mouvement_nombre'); } public function getUsedQuantity(Coupon $coupon) { $countPrinted = 0; - $couponId = $coupon->coupon_id; - $campagnes = $coupon->campagnes()->get(); - foreach ($campagnes as $campagne) { - if ($campagne->camp_type == 0 || $campagne->camp_type == 2) { -// Murs - $murs = Mur::where(['mur_campid' => $campagne->camp_id, 'mur_couponId' => $coupon->coupon_id])->get(); - $countPrinted = $countPrinted + count($murs); + foreach ($coupon->campagnes as $campagne) { + if ($campagne->camp_type->equals(CampaignTypes::mur()) || $campagne->camp_type->equals(CampaignTypes::murss())) { + // Murs + $murs = Mur::where(['mur_campid' => $campagne->camp_id, 'mur_couponId' => $coupon->coupon_id])->count(); + $countPrinted += $murs; } else { -// Paniers - $campagneId = $campagne->camp_id; - $countPrinted = PanierContent::where('panier_content_couponId', $couponId)->whereHas('panier', function ($query) use ($campagneId) { + // Paniers + // TODO : Revoir la requete + $campagneId = $campagne->camp_id; + $countPrinted = PanierContent::where('panier_content_couponId', $coupon->coupon_id)->whereHas('panier', function ($query) use ($campagneId) { $query->where('panier_campId', $campagneId); })->sum('panier_content_printed'); } @@ -295,17 +291,15 @@ trait CouponTrait public function getDiffusedQuantity(Coupon $coupon) { $countPrinted = 0; - $couponId = $coupon->coupon_id; - $campagnes = $coupon->campagnes()->get(); - foreach ($campagnes as $campagne) { - if ($campagne->camp_type == 0 || $campagne->camp_type == 2) { -// Murs - $murs = Mur::where(['mur_campid' => $campagne->camp_id, 'mur_couponId' => $coupon->coupon_id])->get(); - $countPrinted = $countPrinted + count($murs); + foreach ($coupon->campagnes as $campagne) { + if ($campagne->camp_type->equals(CampaignTypes::mur()) || $campagne->camp_type->equals(CampaignTypes::murss())) { + // Murs + $murs = Mur::where(['mur_campid' => $campagne->camp_id, 'mur_couponId' => $coupon->coupon_id])->count(); + $countPrinted += $murs; } else { -// Paniers + // Paniers $campagneId = $campagne->camp_id; - $panierContents = PanierContent::where('panier_content_couponId', $couponId)->whereHas('panier', function ($query) use ($campagneId) { + $panierContents = PanierContent::where('panier_content_couponId', $coupon->coupon_id)->whereHas('panier', function ($query) use ($campagneId) { $query->where('panier_campId', $campagneId); })->get(); $panierContentCountPrinted = $panierContents->sum('panier_content_printed'); @@ -323,7 +317,7 @@ trait CouponTrait $enddate = date('Y-m-d H:i:s', strtotime($enddate)); $campagnes = $coupon->campagnes()->get(); foreach ($campagnes as $campagne) { - if ($campagne->camp_type == 0 || $campagne->camp_type == 2) { + if ($campagne->camp_type->equals(CampaignTypes::mur()) || $campagne->camp_type->equals(CampaignTypes::murss())) { // Murs $murs = Mur::where(['mur_campid' => $campagne->camp_id, 'mur_couponId' => $coupon->coupon_id])->whereBetween('mur_createdate', [$startdate, $enddate])->get(); $countPrinted = $countPrinted + count($murs); @@ -348,7 +342,7 @@ trait CouponTrait // ---- Contrôle le nombre limite d'impression if ($coupon->coupon_enablelimitquantity === 1) { - $count = PrintedWalls::where( + $count = PrintedCoupons::where( [ ['camp_id', '=', $campagne->camp_id], ['coupon_id', '=', $coupon->coupon_id], @@ -363,7 +357,7 @@ trait CouponTrait // ---- Contrôle la limite de période de diffusion if ($coupon->coupon_enablelimitperiod === 1 && $coupon->coupon_limitperiod > 0) { - $count = PrintedWalls::where( + $count = PrintedCoupons::where( [ ['camp_id', '=', $campagne->camp_id], ['coupon_id', '=', $coupon->coupon_id], diff --git a/app/Traits/GenerateBR.php b/app/Traits/GenerateBR.php index 32d7d93..66c72bf 100644 --- a/app/Traits/GenerateBR.php +++ b/app/Traits/GenerateBR.php @@ -2,10 +2,13 @@ namespace App\Traits; +use App\Models\Campagne; use App\Models\Customers; use Illuminate\Http\Request; -use App\Coupon; -use App\Site; +use App\Models\Coupon; +use App\Models\PrintedCoupons; +use App\Models\Site; +use App\Models\Statistique; trait GenerateBR { @@ -18,8 +21,8 @@ trait GenerateBR $hand_picture = 'build/assets/images/coupons/hand.png'; $mask_img = 'build/assets/images/coupons/mask.png'; - if (null !== $request->input('site_id')) { - $site = Site::where(['id' => $request->input('site_id')])->first(); + if (!is_null($request->site_id)) { + $site = Site::where(['id' => $request->site_id])->first(); } else { $site = $coupon->site()->first(); } @@ -31,43 +34,33 @@ trait GenerateBR $mask = imagecreatefrompng($mask_img); list($maskWidth, $maskHeight) = getimagesize($mask_img); - // ---- Contact distributeur - $text = $coupon->coupon_site_contact; - if (strlen($text) < 30) { - $ImageFond = imagecreate(165, 27); - $box1 = imagettfbbox(8, 0, $arial, $text); - $white = imagecolorallocate($ImageFond, 255, 255, 255); - $black = imagecolorallocate($ImageFond, 0, 0, 0); - $this->imagettftextSp($ImageFond, 8, 0, 5, 23, $black, $arial, $text, 0.01); - imagecolortransparent($ImageFond, $white); - imagecopy($mask, $ImageFond, 743, 365, 0, 0, imagesx($ImageFond), imagesy($ImageFond)); - } else { - $ImageFond = imagecreate(195, 27); - $box1 = imagettfbbox(7, 0, $arial, $text); - $white = imagecolorallocate($ImageFond, 255, 255, 255); - $black = imagecolorallocate($ImageFond, 0, 0, 0); - $this->imagettftextSp($ImageFond, 7, 0, 5, 23, $black, $arial, $text, 0); - imagecolortransparent($ImageFond, $white); - imagecopy($mask, $ImageFond, 713, 365, 0, 0, imagesx($ImageFond), imagesy($ImageFond)); - } - - // ----- Mentions légales + RCS if ($coupon->coupon_legal_mentions_splitted == 0) { $txt_mentions = $coupon->coupon_legal_mentions . " " . $coupon->coupon_rcs; $ImageMentionFond = imagecreate(415, 100); - $boxMentions = imagettfbbox(7, 0, $arial, $txt_mentions); $white = imagecolorallocate($ImageMentionFond, 255, 255, 255); imagefilledrectangle($ImageMentionFond, 0, 0, 414, 99, $white); $black = imagecolorallocate($ImageMentionFond, 0, 0, 0); - $lines_mentions = explode("\r\n", $txt_mentions); + + $cleanedString = str_replace(["\r", "\n"], '', $txt_mentions); + $lines_mentions = str_split($cleanedString, 92); + $y = 19; foreach ($lines_mentions as $line) { $this->imagettftextSp($ImageMentionFond, 7, 0, 15, $y, $black, $arial, $line, 0.01); $y = $y + 9; } - - // imagecolortransparent($ImageMentionFond, $white); + $this->imagettftextSp( + $ImageMentionFond, + 7, + 0, + 15, + $y, + $black, + $arialbd, + sprintf("%s : %s", __('Renseignements'), $coupon->coupon_site_contact), + 0.01 + ); imagecopy($mask, $ImageMentionFond, 335, 235, 0, 0, imagesx($ImageMentionFond), imagesy($ImageMentionFond)); } @@ -86,9 +79,9 @@ trait GenerateBR $black = imagecolorallocate($ImageFond, 0, 0, 0); $blue = imagecolorallocate($ImageFond, 8, 169, 223); $grey = imagecolorallocate($ImageFond, 219, 219, 221); - $this->imagettftext_contour($ImageFond, 95, 0, 5, 110, $grey, $impact, $textMontant, $blue, 3, 3, 3, 3); - $this->imagettftext_contour($ImageFond, 50, 0, 220, 55, $grey, $arial, $textEuro, $blue, 2, 2, 2, 2); - $this->imagettftext_contour($ImageFond, 16, 0, 0, 150, $grey, $impact, $libReduc, $blue, 1, 1, 1, 1); + $this->imagettftextContour($ImageFond, 95, 0, 5, 110, $grey, $impact, $textMontant, $blue, 3, 3, 3, 3); + $this->imagettftextContour($ImageFond, 50, 0, 220, 55, $grey, $arial, $textEuro, $blue, 2, 2, 2, 2); + $this->imagettftextContour($ImageFond, 16, 0, 0, 150, $grey, $impact, $libReduc, $blue, 1, 1, 1, 1); imagecolortransparent($ImageFond, $white); imagecopy($mask, $ImageFond, 360, 10, 0, 0, imagesx($ImageFond), imagesy($ImageFond)); @@ -107,13 +100,11 @@ trait GenerateBR $textFiliLines = explode("\r\n", $textFili); $ImageFond = imagecreate(402, 240); $white = imagecolorallocate($ImageFond, 255, 255, 255); - $blackOpac = imagecolorallocatealpha($ImageFond, 0, 0, 0, 20); $y = 0; foreach ($textFiliLines as $textFiliLine) { $y = $y + 20; $this->imagettftextSp($ImageFond, 11, 25, -100, $y, $black, $arial, $textFiliLine, 0.01); } - // imagettftext($ImageFond , 11 , 25, -100, 11, $blackOpac, $arial, $textReduc); imagecolortransparent($ImageFond, $white); imagecopymerge($mask, $ImageFond, 349, 1, 0, 0, imagesx($ImageFond), imagesy($ImageFond), 30); @@ -158,8 +149,8 @@ trait GenerateBR } imagecolortransparent($ImageFond, $white); imagecopy($mask, $ImageFond, 360, 170, 0, 0, imagesx($ImageFond), imagesy($ImageFond)); - }//end if - // imagettftext($ImageFond , 12 , 0, 0, 14, $black, $arialbd, $textReduc); + } //end if + // ---- Copie le produit dans le mask $size = getimagesize($product_image); switch ($size['mime']) { @@ -221,7 +212,7 @@ trait GenerateBR - function imagettftext_contour($image, $fontsize, $angle, $x, $y, $color, $font, $text, $color_contour, $contour_haut = 1, $contour_bas = 1, $contour_gauche = 1, $contour_droite = 1) + function imagettftextContour($image, $fontsize, $angle, $x, $y, $color, $font, $text, $color_contour, $contour_haut = 1, $contour_bas = 1, $contour_gauche = 1, $contour_droite = 1) { $coords_x = array(); $coords_y = array(); @@ -287,8 +278,8 @@ trait GenerateBR } // imagecolortransparent($ImageMentionFond, $white); imagecopy($mask, $ImageMentionFond, 335, 235, 0, 0, imagesx($ImageMentionFond), imagesy($ImageMentionFond)); - }//end if - }//end if + } //end if + } //end if // ---- Inscription de l'utilisateur et de la ville @@ -311,7 +302,7 @@ trait GenerateBR $dateValidite = date('d/m/Y', strtotime("+" . $coupon->coupon_validity . " day")); } else { $dateValidite = date('d/m/Y', strtotime("+30 day")); -// 30 jours par défaut + // 30 jours par défaut } $ImageFond = imagecreate(120, 40); @@ -372,7 +363,7 @@ trait GenerateBR $black = imagecolorallocate($ImageFond, 0, 0, 0); imagettftext($ImageFond, 11, 0, 0, 14, $black, $arial, $codeBarre); imagecopy($mask, $ImageFond, 52, 390, 0, 0, imagesx($ImageFond), imagesy($ImageFond)); - }//end if + } //end if ob_start(); imagejpeg($mask, null, 100); @@ -387,151 +378,233 @@ trait GenerateBR } // VB 22/04/2021 - public function printCoupon(Coupon $coupon, Customers $customer, $crmInfos) + public function printCoupon(Coupon $coupon, Customers $customer, $crmInfos, Campagne $campagne) { - $arial = public_path() . '/build/assets/fonts/coupons/arial.ttf'; + $arial = public_path() . '/build/assets/fonts/coupons/arial.ttf'; $arialbd = public_path() . '/build/assets/fonts/coupons/arialbd.ttf'; - // ---- Masque dans lequel l'image finale sera placée - $mask = imagecreatefrompng($coupon->coupon_image); + // Load base mask image + $mask = imagecreatefrompng($coupon->coupon_image); list($maskWidth, $maskHeight) = getimagesize($coupon->coupon_image); - - // ----- Mentions légales + RCS dépendant de l'user + // --- Draw Legal Mentions + RCS depending on the user country if ($coupon->coupon_legal_mentions_splitted == 1) { $legalMentions = explode('', $coupon->coupon_legal_mentions); + if ($customer->country !== 250) { // BELGIQUE - Luxembourg - $txt_mentions = $legalMentions[0] . "\n\r" . $legalMentions[1] . " " . $coupon->coupon_rcs; - $ImageMentionFond = imagecreate(420, 145); - $boxMentions = imagettfbbox(7, 0, $arial, $txt_mentions); - $white = imagecolorallocate($ImageMentionFond, 255, 255, 255); - imagefilledrectangle($ImageMentionFond, 0, 0, 414, 99, $white); - $black = imagecolorallocate($ImageMentionFond, 0, 0, 0); - $lines_mentions = explode("\r\n", $txt_mentions); - $y = 19; - foreach ($lines_mentions as $line) { - $this->imagettftextSp($ImageMentionFond, 7, 0, 15, $y, $black, $arial, $line, 0.01); - $y = $y + 9; - } - // imagecolortransparent($ImageMentionFond, $white); - imagecopy($mask, $ImageMentionFond, 335, 235, 0, 0, imagesx($ImageMentionFond), imagesy($ImageMentionFond)); + $txt_mentions = $legalMentions[0] . "\n\r " . $legalMentions[1] . "\n\r " . $coupon->coupon_rcs; + $imageWidth = 420; + $imageHeight = 145; } else { // FR - $txt_mentions = $legalMentions[0] . " " . $coupon->coupon_rcs; - $ImageMentionFond = imagecreate(415, 100); - $boxMentions = imagettfbbox(7, 0, $arial, $txt_mentions); - $white = imagecolorallocate($ImageMentionFond, 255, 255, 255); - imagefilledrectangle($ImageMentionFond, 0, 0, 414, 99, $white); - $black = imagecolorallocate($ImageMentionFond, 0, 0, 0); - $lines_mentions = explode("\r\n", $txt_mentions); - $y = 19; - foreach ($lines_mentions as $line) { - $this->imagettftextSp($ImageMentionFond, 7, 0, 15, $y, $black, $arial, $line, 0.01); - $y = $y + 9; - } - // imagecolortransparent($ImageMentionFond, $white); - imagecopy($mask, $ImageMentionFond, 335, 235, 0, 0, imagesx($ImageMentionFond), imagesy($ImageMentionFond)); - }//end if - }//end if + $txt_mentions = $legalMentions[0] . " " . $coupon->coupon_rcs; + $imageWidth = 415; + $imageHeight = 100; + } + $ImageMentionFond = imagecreate($imageWidth, $imageHeight); + $white = imagecolorallocate($ImageMentionFond, 255, 255, 255); + imagefilledrectangle($ImageMentionFond, 0, 0, $imageWidth - 6, $imageHeight - 46, $white); + $black = imagecolorallocate($ImageMentionFond, 0, 0, 0); - // ---- Inscription de l'utilisateur et de la ville - $libelle = "OFFRE RÉSERVÉE À"; - $user = $crmInfos->firstname . " " . $crmInfos->lastname . "\r\n" . $crmInfos->postcode . " " . $crmInfos->city; - $ImageFond = imagecreate(120, 40); - $white = imagecolorallocate($ImageFond, 255, 255, 255); - $black = imagecolorallocate($ImageFond, 0, 0, 0); - $box1 = imagettfbbox(8, 0, $arial, $user); - $box2 = imagettfbbox(8, 0, $arial, $libelle); - imagettftext($ImageFond, 8, 0, (120 / 2) - (abs($box2[4]) - abs($box2[6])) / 2, 10, $black, $arialbd, $libelle); - imagettftext($ImageFond, 8, 0, (120 / 2) - (abs($box1[4]) - abs($box1[6])) / 2, 25, $black, $arial, $user); - imagecolortransparent($ImageFond, $white); - imagecopy($mask, $ImageFond, 770, 50, 0, 0, imagesx($ImageFond), imagesy($ImageFond)); + $cleanedString = str_replace(["\r", "\n"], '', $txt_mentions); + $lines_mentions = str_split($cleanedString, 92); - // ---- Inscription de la date de validité - $libelle = "Valable jusqu'au :"; + $y = 19; + foreach ($lines_mentions as $line) { + $this->imagettftextSp($ImageMentionFond, 7, 0, 15, $y, $black, $arial, $line, 0.01); + $y += 9; + } - if ($coupon->coupon_validity != 0) { - $dateValidite = date('d/m/Y', strtotime("+" . $coupon->coupon_validity . " day")); - } else { - $dateValidite = date('d/m/Y', strtotime("+30 day")); -// 30 jours par défaut + imagecopy($mask, $ImageMentionFond, 335, 235, 0, 0, imagesx($ImageMentionFond), imagesy($ImageMentionFond)); + + imagedestroy($ImageMentionFond); } + // --- User inscription and city + $libelle = "OFFRE RÉSERVÉE À"; + $user = sprintf( + "%s\r\n%s\r\n%s\r\n%s %s\r\n%s", + $crmInfos->firstname, + $crmInfos->lastname, + $crmInfos->address, + $crmInfos->postcode, + $crmInfos->city, + sprintf('id #%s', str_pad($customer->id, 13, "0", STR_PAD_LEFT)) + ); + + $ImageFond = imagecreate(120, 80); + $white = imagecolorallocate($ImageFond, 255, 255, 255); + $black = imagecolorallocate($ImageFond, 0, 0, 0); + + // Centered libelle text + $boxLibelle = imagettfbbox(8, 0, $arial, $libelle); + $libelleX = (120 / 2) - (abs($boxLibelle[4]) - abs($boxLibelle[6])) / 2; + imagettftext($ImageFond, 8, 0, $libelleX, 10, $black, $arialbd, $libelle); + + // User lines + $userLines = explode("\r\n", $user); + $y = 25; + foreach ($userLines as $line) { + $box = imagettfbbox(8, 0, $arial, $line); + $lineX = (120 / 2) - (abs($box[4]) - abs($box[6])) / 2; + $this->imagettftextSp($ImageFond, 8, 0, $lineX, $y, $black, $arial, $line, 0.01); + $y += 10; + } + + imagecolortransparent($ImageFond, $white); + imagecopy($mask, $ImageFond, 770, 40, 0, 0, imagesx($ImageFond), imagesy($ImageFond)); + imagedestroy($ImageFond); + + // --- Validity date inscription + $libelle = "Valable jusqu'au :"; + $validDays = ($coupon->coupon_validity != 0) ? $coupon->coupon_validity : 30; + $dateValidite = date('d/m/Y', strtotime("+$validDays day")); + $ImageFond = imagecreate(120, 40); - $white = imagecolorallocate($ImageFond, 255, 255, 255); - $black = imagecolorallocate($ImageFond, 0, 0, 0); + $white = imagecolorallocate($ImageFond, 255, 255, 255); + $black = imagecolorallocate($ImageFond, 0, 0, 0); + imagettftext($ImageFond, 8, 0, 1, 8, $black, $arialbd, $libelle); imagettftext($ImageFond, 8, 0, 20, 23, $black, $arial, $dateValidite); + imagecolortransparent($ImageFond, $white); imagecopy($mask, $ImageFond, 780, 142, 0, 0, imagesx($ImageFond), imagesy($ImageFond)); + imagedestroy($ImageFond); - // ---- Création code barre + // Save printed coupon + $printedCoupon = $this->savePrintedCoupon($campagne, $customer, $coupon); + + // --- Right barcode + $codeBarre = str_pad($printedCoupon->id, 13, "0", STR_PAD_LEFT); + $generator = new \Picqer\Barcode\BarcodeGeneratorPNG(); + $base64 = $generator->getBarcode($codeBarre, $generator::TYPE_CODE_128, 2, 30); + $barcodeImage = imagecreatefromstring($base64); + + imagecopy($mask, $barcodeImage, 660, 355, 0, 0, imagesx($barcodeImage), imagesy($barcodeImage)); + imagedestroy($barcodeImage); + + // Text below right barcode + $ImageFond = imagecreate(380, 15); + $white = imagecolorallocate($ImageFond, 255, 255, 255); + $black = imagecolorallocate($ImageFond, 0, 0, 0); + imagettftext($ImageFond, 11, 0, 0, 14, $black, $arial, $codeBarre); + imagecopy($mask, $ImageFond, 800, 385, 0, 0, imagesx($ImageFond), imagesy($ImageFond)); + imagedestroy($ImageFond); + + // --- Barcode treatment text if ($customer->country !== 250) { $textReduc = "Traitement ScanCoupon/HighCo Data Benelux"; + $copyPosition = [70, 230]; } elseif ($coupon->coupon_treatment_center == 0) { $textReduc = "• Traitement ScanCoupon •"; + $copyPosition = [52, 322]; } else { $textReduc = "• Traitement Sogec •"; + $copyPosition = [52, 322]; } $ImageFond = imagecreate(270, 20); - $white = imagecolorallocate($ImageFond, 255, 255, 255); - $black = imagecolorallocate($ImageFond, 0, 0, 0); + $white = imagecolorallocate($ImageFond, 255, 255, 255); + $black = imagecolorallocate($ImageFond, 0, 0, 0); imagettftext($ImageFond, 9, 0, 0, 10, $black, $arialbd, $textReduc); - if ($customer->country !== 250) { - imagecopy($mask, $ImageFond, 70, 230, 0, 0, imagesx($ImageFond), imagesy($ImageFond)); - } else { - imagecopy($mask, $ImageFond, 52, 322, 0, 0, imagesx($ImageFond), imagesy($ImageFond)); - } - + imagecopy($mask, $ImageFond, $copyPosition[0], $copyPosition[1], 0, 0, imagesx($ImageFond), imagesy($ImageFond)); + imagedestroy($ImageFond); + // --- Left barcode if ($customer->country !== 250) { - $codeBarre = imagecreatefromjpeg($coupon->coupon_gs1code); - imageresolution($codeBarre, 72); + $codeBarreImg = imagecreatefromjpeg($coupon->coupon_gs1code); + imageresolution($codeBarreImg, 72); list($width, $height) = getimagesize($coupon->coupon_gs1code); - $r = $width / $height; - $w = 285; - $h = 150; - if ($w / $h > $r) { - $newwidth = $h * $r; - $newheight = $h; - } else { - $newheight = $w / $r; - $newwidth = $w; - } - $test = imagecreatetruecolor($newwidth, $newheight); - imagecopyresampled($test, $codeBarre, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); + $ratio = $width / $height; + $maxWidth = 285; + $maxHeight = 150; - imagecopy($mask, $test, 60, 250, 0, 0, imagesx($test), imagesy($test)); - } else { - $codeBarre = $coupon->coupon_code . strtoupper($customer->crm_id); - $codeBarrePrint = $codeBarre; - if (strpos($customer->crm_id, "@") !== false) { - $codeBarre = $coupon->coupon_code . strtolower($customer->crm_id); - $codeBarrePrint = $coupon->coupon_code . ".@."; + if ($maxWidth / $maxHeight > $ratio) { + $newWidth = $maxHeight * $ratio; + $newHeight = $maxHeight; + } else { + $newHeight = $maxWidth / $ratio; + $newWidth = $maxWidth; } - $generator = new \Picqer\Barcode\BarcodeGeneratorPNG(); - $base64 = $generator->getBarcode($codeBarrePrint, $generator::TYPE_CODE_128_A, 2, 46); + + $resizedImage = imagecreatetruecolor($newWidth, $newHeight); + imagecopyresampled($resizedImage, $codeBarreImg, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); + imagecopy($mask, $resizedImage, 60, 250, 0, 0, $newWidth, $newHeight); + imagedestroy($codeBarreImg); + imagedestroy($resizedImage); + } else { + $codeBarre = $coupon->coupon_code; + $generator = new \Picqer\Barcode\BarcodeGeneratorPNG(); + $base64 = $generator->getBarcode($codeBarre, $generator::TYPE_CODE_128_A, 2, 46); $barcodeImage = imagecreatefromstring($base64); - imagecopy($mask, $barcodeImage, 52, 342, 0, 0, imagesx($barcodeImage), imagesy($barcodeImage)); + imagecopy($mask, $barcodeImage, 10, 342, 0, 0, imagesx($barcodeImage), imagesy($barcodeImage)); + imagedestroy($barcodeImage); + $ImageFond = imagecreate(380, 15); - $white = imagecolorallocate($ImageFond, 255, 255, 255); - $black = imagecolorallocate($ImageFond, 0, 0, 0); + $white = imagecolorallocate($ImageFond, 255, 255, 255); + $black = imagecolorallocate($ImageFond, 0, 0, 0); imagettftext($ImageFond, 11, 0, 0, 14, $black, $arial, $codeBarre); imagecopy($mask, $ImageFond, 52, 390, 0, 0, imagesx($ImageFond), imagesy($ImageFond)); - }//end if + imagedestroy($ImageFond); + } + // Final output as base64 encoded JPEG ob_start(); imagejpeg($mask, null, 100); $contents = ob_get_contents(); ob_end_clean(); - $dataUri = "data:image/jpeg;base64," . base64_encode($contents); - // ---- Libère la mémoire associée aux images manipulées imagedestroy($mask); - imagedestroy($ImageFond); - return $dataUri; + + // Save stat. + $this->saveStat($campagne, $coupon); + + return "data:image/jpeg;base64," . base64_encode($contents); + } + + /** + * Save 'printed_coupons' line. + * + * @param Campagne $campagne + * @param Customers $customer + * @param Coupon $coupon + * @return PrintedCoupons + */ + public function savePrintedCoupon(Campagne $campagne, Customers $customer, Coupon $coupon): PrintedCoupons + { + $mur = new PrintedCoupons(); + $mur->camp_id = $campagne->camp_id; + $mur->customer_id = $customer->id; + $mur->coupon_id = $coupon->coupon_id; + $mur->save(); + + return $mur; + } + + /** + * Save stats in the 'statistiques' table. + * + * @param Campagne $campagne + * @param Coupon $coupon + * @return Statistique + */ + public function saveStat(Campagne $campagne, Coupon $coupon): Statistique + { + $stat = Statistique::query()->firstOrCreate( + [ + 'date' => now()->toDateString(), + 'stat_campId' => $campagne->camp_id, + 'stat_couponId' => $coupon->coupon_id, + ], + [ + 'stat_couponPrinted' => 0, + ] + ); + $stat->stat_couponPrinted += 1; + $stat->save(); + + return $stat; } } diff --git a/app/Traits/GraphTrait.php b/app/Traits/GraphTrait.php deleted file mode 100644 index a10dcd6..0000000 --- a/app/Traits/GraphTrait.php +++ /dev/null @@ -1,76 +0,0 @@ -diff($datetime2); - $days = $interval->format('%a'); - - // ---- Labels des graphiques - $labels = []; - for ($i = 0; $i <= $days; $i++) { - $date = date('d/m/Y', strtotime("+" . $i . " days", strtotime($startdate))); - array_push($labels, $date); - } - - return $labels; - } - - // ---- Data for global graph - public function getDataForCamp($labels, $campid) - { - $dataGlobal = []; - foreach ($labels as $label) { - $date = date('Y-m-d', strtotime(str_replace('/', '-', $label))); - $stat = Statistique::where(['stat_campId' => $campid])->whereDate('created_at', '=', $date)->sum('stat_couponPrinted'); - if (isset($stat)) { - $dataGlobal[] = $stat; - } else { - $dataGlobal[] = 0; - } - } - return $dataGlobal; - } - - // ---- Data for one coupon on one camp - public function getDataForCoupon($labels, $campid, $coupon) - { - $dataCoupon = []; - foreach ($labels as $label) { - $date = date('Y-m-d', strtotime(str_replace('/', '-', $label))); - $stat = Statistique::where(['stat_campId' => $campid, 'stat_couponId' => $coupon->coupon_id])->whereDate('created_at', '=', $date)->sum('stat_couponPrinted'); - if (isset($stat)) { - $dataCoupon[] = $stat; - } else { - $dataCoupon[] = 0; - } - } - return $dataCoupon; - } - - // ---- Data for one coupon all camp - public function getDataForCouponAllCamp($labels, $coupon) - { - $dataCoupon = []; - foreach ($labels as $label) { - $date = date('Y-m-d', strtotime(str_replace('/', '-', $label))); - $stat = Statistique::where(['stat_couponId' => $coupon->coupon_id])->whereDate('created_at', '=', $date)->sum('stat_couponPrinted'); - if (isset($stat)) { - $dataCoupon[] = $stat; - } else { - $dataCoupon[] = 0; - } - } - return $dataCoupon; - } -} diff --git a/app/Traits/HasUniqueField.php b/app/Traits/HasUniqueField.php new file mode 100644 index 0000000..3fee366 --- /dev/null +++ b/app/Traits/HasUniqueField.php @@ -0,0 +1,31 @@ +getTable(); + ToolboxHelper::assertFieldIsUnique($table, $field, $value, $id); + + if (!is_null($slugField)) { + ToolboxHelper::assertFieldIsUnique($table, $slugField, Str::slug($value), $id); + } + } + } +} diff --git a/app/Traits/LogTrait.php b/app/Traits/LogTrait.php new file mode 100644 index 0000000..ac0b659 --- /dev/null +++ b/app/Traits/LogTrait.php @@ -0,0 +1,97 @@ +log_action = $this->logAction->value; + $log->log_source = $this->logSource; + $log->log_params = json_encode(['refcamp' => $refcamp]); + $log->log_statut = 'NOK'; + $log->log_message = "La campagne n'existe pas ou n'est pas un panier"; + $log->save(); + } + + /** + * Write error log when there's a wrong or missing parameter in the request. + * + * @param string $refcamp + * @param string $refadherent + * @param string $refsite + * @param string $panier + * @return void + */ + public function writeLogErrorWrongRequestParameters( + string $refcamp, + string $refadherent, + string $refsite, + string $panier + ) { + $log = new Log(); + $log->log_action = $this->logAction->value; + $log->log_source = $this->logSource; + $log->log_params = json_encode([ + 'refcamp' => $refcamp, + 'refadherent' => $refadherent, + 'refsite' => $refsite, + 'panier' => $panier + ]); + $log->log_statut = 'NOK'; + $log->log_message = "Des paramètres de la requête sont mal renseignés ou non présents"; + $log->save(); + } + + /** + * Write success log when the basket is created or updated. + * + * @param string $refcamp + * @param string $refadherent + * @param string $refsite + * @param string $panier + * @param array $panierCoupons + * @return void + */ + public function writeLogSuccessBasketCreated( + string $refcamp, + string $refadherent, + string $refsite, + string $panier, + array $panierCoupons + ) { + $log = new Log(); + $log->log_action = $this->logAction->value; + $log->log_source = $this->logSource; + $log->log_params = json_encode([ + 'refcamp' => $refcamp, + 'refadherent' => $refadherent, + 'refsite' => $refsite, + 'panier' => $panier + ]); + $log->log_refsite = $refsite; + $log->log_statut = 'OK'; + $log->log_message = json_encode( + ['Message' => 'Le panier a bien été créé/mis à jour', 'Coupons' => $panierCoupons], + JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES + ); + $log->save(); + } + + + + + + + + +} diff --git a/clients/MesBR_V1.php b/clients/MesBR_V1.php index 9ba8119..61cd947 100644 --- a/clients/MesBR_V1.php +++ b/clients/MesBR_V1.php @@ -2,6 +2,8 @@ namespace LDCWEB; +use LDC\LDCCRM\Models\Customer; + class MesBR { @@ -9,10 +11,13 @@ class MesBR private $refCamp; - public function __construct($endpoint, $refCamp) + private $refSite; + + public function __construct($endpoint, $refCamp, $refSite) { $this->endpoint = $endpoint; $this->refCamp = $refCamp; + $this->refSite = $refSite; } public function createCustomer(string $hashcode, string $email, string $country) @@ -81,4 +86,66 @@ class MesBR curl_close($curl); return json_decode($result); } + + // -------- New methods related to baskets (2025/10) + + /** . + * Update basket + * + * @param \LDC\LDCCRM\Models\Customer $crm_customer + * @param string $coupon_id + * @param integer $quantity + * @return array + * 'status' => 'OK', + * 'ref' => Basket REF, + */ + public function updateBasket( + Customer $crm_customer, + string $coupon_id, + int $quantity = 1 + ): array { + $res = $this->callAPI("GET", "/customer/basket/update", [ + 'refsite' => $this->refSite, + 'refcamp' => $this->refCamp, + 'customer_hashcode' => $crm_customer->hashcode, + 'panier' => "({$quantity}){$coupon_id}" + ]); + + if (!$res) { + error_log("MESBR - CODE : 999 - MESSAGE : Cannot read API Response (non json)"); + return ['status' => 'KO', 'code' => 999, 'message' => 'Cannot read API Response (non json)']; + } + if ($res->Statut === 'KO') { + error_log("MESBR - CODE : $res->Code - MESSAGE : $res->Message"); + return ['status' => 'KO', 'code' => $res->Code, 'message' => $res->Message]; + } + return ['status' => 'OK', 'ref' => $res->Panier->ref]; + } + + /** + * Get customer basket + * + * @param \LDC\LDCCRM\Models\Customer $crm_customer + * @return array + */ + public function getBasket( + Customer $crm_customer, + ): array { + $res = $this->callApi("GET", '/customer/basket', [ + 'refcamp' => $this->refCamp, + 'hashcode' => $crm_customer->hashcode + ]); + + if (!$res) { + error_log("MESBR - CODE : 999 - MESSAGE : Cannot read API Response (non json)"); + return ['status' => 'KO', 'code' => 999, 'message' => 'Cannot read API Response (non json)']; + } + + if ($res->status === 'KO') { + error_log("MESBR - CODE : $res->code - MESSAGE : $res->message"); + return ['status' => 'KO', 'code' => $res->code, 'message' => $res->message]; + } + + return ['status' => 'OK', 'coupons' => $res->coupons]; + } } diff --git a/composer.json b/composer.json index 932f5f4..550f552 100644 --- a/composer.json +++ b/composer.json @@ -1,11 +1,6 @@ { - "name": "laravel/laravel", - "description": "The Laravel Framework.", - "keywords": [ - "framework", - "laravel" - ], - "license": "MIT", + "name": "uwil/mesbr", + "description": "Webcoupon management system", "type": "project", "require": { "php": "^7.3", @@ -14,15 +9,16 @@ "barryvdh/laravel-dompdf": "^0.9.0", "doctrine/dbal": "^2.8", "fideloper/proxy": "^4.0", + "kwaadpepper/enum": "^2.0", "laravel/framework": "^8.0", "laravel/tinker": "^2.0", "laravel/ui": "^3.0", "laravelcollective/html": "6.*", - "ldc/ldccrmv2client": "^3.0", + "ldc/ldccrmv2client": "^3.0.5", "picqer/php-barcode-generator": "^0.3.0", "sentry/sentry-laravel": "^4.13", - "szymach/c-pchart": "^3.0", - "uxweb/sweet-alert": "^2.0" + "uxweb/sweet-alert": "^2.0", + "vladimir-yuldashev/laravel-queue-rabbitmq": "^11.3" }, "require-dev": { "beyondcode/laravel-dump-server": "^1.0", diff --git a/composer.lock b/composer.lock index a29125a..c5a61e5 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "30db3ec95147621d8486d7ad5796a124", + "content-hash": "1b3d7e201bf5b5d95441c22f9c4d2265", "packages": [ { "name": "barryvdh/laravel-dompdf", @@ -2615,6 +2615,123 @@ }, "time": "2022-01-27T09:35:39+00:00" }, + { + "name": "paragonie/constant_time_encoding", + "version": "v2.7.0", + "source": { + "type": "git", + "url": "https://github.com/paragonie/constant_time_encoding.git", + "reference": "52a0d99e69f56b9ec27ace92ba56897fe6993105" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/paragonie/constant_time_encoding/zipball/52a0d99e69f56b9ec27ace92ba56897fe6993105", + "reference": "52a0d99e69f56b9ec27ace92ba56897fe6993105", + "shasum": "" + }, + "require": { + "php": "^7|^8" + }, + "require-dev": { + "phpunit/phpunit": "^6|^7|^8|^9", + "vimeo/psalm": "^1|^2|^3|^4" + }, + "type": "library", + "autoload": { + "psr-4": { + "ParagonIE\\ConstantTime\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Paragon Initiative Enterprises", + "email": "security@paragonie.com", + "homepage": "https://paragonie.com", + "role": "Maintainer" + }, + { + "name": "Steve 'Sc00bz' Thomas", + "email": "steve@tobtu.com", + "homepage": "https://www.tobtu.com", + "role": "Original Developer" + } + ], + "description": "Constant-time Implementations of RFC 4648 Encoding (Base-64, Base-32, Base-16)", + "keywords": [ + "base16", + "base32", + "base32_decode", + "base32_encode", + "base64", + "base64_decode", + "base64_encode", + "bin2hex", + "encoding", + "hex", + "hex2bin", + "rfc4648" + ], + "support": { + "email": "info@paragonie.com", + "issues": "https://github.com/paragonie/constant_time_encoding/issues", + "source": "https://github.com/paragonie/constant_time_encoding" + }, + "time": "2024-05-08T12:18:48+00:00" + }, + { + "name": "paragonie/random_compat", + "version": "v9.99.100", + "source": { + "type": "git", + "url": "https://github.com/paragonie/random_compat.git", + "reference": "996434e5492cb4c3edcb9168db6fbb1359ef965a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/paragonie/random_compat/zipball/996434e5492cb4c3edcb9168db6fbb1359ef965a", + "reference": "996434e5492cb4c3edcb9168db6fbb1359ef965a", + "shasum": "" + }, + "require": { + "php": ">= 7" + }, + "require-dev": { + "phpunit/phpunit": "4.*|5.*", + "vimeo/psalm": "^1" + }, + "suggest": { + "ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes." + }, + "type": "library", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Paragon Initiative Enterprises", + "email": "security@paragonie.com", + "homepage": "https://paragonie.com" + } + ], + "description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7", + "keywords": [ + "csprng", + "polyfill", + "pseudorandom", + "random" + ], + "support": { + "email": "info@paragonie.com", + "issues": "https://github.com/paragonie/random_compat/issues", + "source": "https://github.com/paragonie/random_compat" + }, + "time": "2020-10-15T08:29:30+00:00" + }, { "name": "phenx/php-font-lib", "version": "0.5.6", @@ -2705,6 +2822,87 @@ }, "time": "2022-03-07T12:52:04+00:00" }, + { + "name": "php-amqplib/php-amqplib", + "version": "v3.7.3", + "source": { + "type": "git", + "url": "https://github.com/php-amqplib/php-amqplib.git", + "reference": "9f50fe69a9f1a19e2cb25596a354d705de36fe59" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-amqplib/php-amqplib/zipball/9f50fe69a9f1a19e2cb25596a354d705de36fe59", + "reference": "9f50fe69a9f1a19e2cb25596a354d705de36fe59", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "ext-sockets": "*", + "php": "^7.2||^8.0", + "phpseclib/phpseclib": "^2.0|^3.0" + }, + "conflict": { + "php": "7.4.0 - 7.4.1" + }, + "replace": { + "videlalvaro/php-amqplib": "self.version" + }, + "require-dev": { + "ext-curl": "*", + "nategood/httpful": "^0.2.20", + "phpunit/phpunit": "^7.5|^9.5", + "squizlabs/php_codesniffer": "^3.6" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.0-dev" + } + }, + "autoload": { + "psr-4": { + "PhpAmqpLib\\": "PhpAmqpLib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-2.1-or-later" + ], + "authors": [ + { + "name": "Alvaro Videla", + "role": "Original Maintainer" + }, + { + "name": "Raúl Araya", + "email": "nubeiro@gmail.com", + "role": "Maintainer" + }, + { + "name": "Luke Bakken", + "email": "luke@bakken.io", + "role": "Maintainer" + }, + { + "name": "Ramūnas Dronga", + "email": "github@ramuno.lt", + "role": "Maintainer" + } + ], + "description": "Formerly videlalvaro/php-amqplib. This library is a pure PHP implementation of the AMQP protocol. It's been tested against RabbitMQ.", + "homepage": "https://github.com/php-amqplib/php-amqplib/", + "keywords": [ + "message", + "queue", + "rabbitmq" + ], + "support": { + "issues": "https://github.com/php-amqplib/php-amqplib/issues", + "source": "https://github.com/php-amqplib/php-amqplib/tree/v3.7.3" + }, + "time": "2025-02-18T20:11:13+00:00" + }, { "name": "phpoption/phpoption", "version": "1.9.3", @@ -2780,6 +2978,116 @@ ], "time": "2024-07-20T21:41:07+00:00" }, + { + "name": "phpseclib/phpseclib", + "version": "3.0.43", + "source": { + "type": "git", + "url": "https://github.com/phpseclib/phpseclib.git", + "reference": "709ec107af3cb2f385b9617be72af8cf62441d02" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/709ec107af3cb2f385b9617be72af8cf62441d02", + "reference": "709ec107af3cb2f385b9617be72af8cf62441d02", + "shasum": "" + }, + "require": { + "paragonie/constant_time_encoding": "^1|^2|^3", + "paragonie/random_compat": "^1.4|^2.0|^9.99.99", + "php": ">=5.6.1" + }, + "require-dev": { + "phpunit/phpunit": "*" + }, + "suggest": { + "ext-dom": "Install the DOM extension to load XML formatted public keys.", + "ext-gmp": "Install the GMP (GNU Multiple Precision) extension in order to speed up arbitrary precision integer arithmetic operations.", + "ext-libsodium": "SSH2/SFTP can make use of some algorithms provided by the libsodium-php extension.", + "ext-mcrypt": "Install the Mcrypt extension in order to speed up a few other cryptographic operations.", + "ext-openssl": "Install the OpenSSL extension in order to speed up a wide variety of cryptographic operations." + }, + "type": "library", + "autoload": { + "files": [ + "phpseclib/bootstrap.php" + ], + "psr-4": { + "phpseclib3\\": "phpseclib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jim Wigginton", + "email": "terrafrost@php.net", + "role": "Lead Developer" + }, + { + "name": "Patrick Monnerat", + "email": "pm@datasphere.ch", + "role": "Developer" + }, + { + "name": "Andreas Fischer", + "email": "bantu@phpbb.com", + "role": "Developer" + }, + { + "name": "Hans-Jürgen Petrich", + "email": "petrich@tronic-media.com", + "role": "Developer" + }, + { + "name": "Graham Campbell", + "email": "graham@alt-three.com", + "role": "Developer" + } + ], + "description": "PHP Secure Communications Library - Pure-PHP implementations of RSA, AES, SSH2, SFTP, X.509 etc.", + "homepage": "http://phpseclib.sourceforge.net", + "keywords": [ + "BigInteger", + "aes", + "asn.1", + "asn1", + "blowfish", + "crypto", + "cryptography", + "encryption", + "rsa", + "security", + "sftp", + "signature", + "signing", + "ssh", + "twofish", + "x.509", + "x509" + ], + "support": { + "issues": "https://github.com/phpseclib/phpseclib/issues", + "source": "https://github.com/phpseclib/phpseclib/tree/3.0.43" + }, + "funding": [ + { + "url": "https://github.com/terrafrost", + "type": "github" + }, + { + "url": "https://www.patreon.com/phpseclib", + "type": "patreon" + }, + { + "url": "https://tidelift.com/funding/github/packagist/phpseclib/phpseclib", + "type": "tidelift" + } + ], + "time": "2024-12-14T21:12:59+00:00" + }, { "name": "picqer/php-barcode-generator", "version": "v0.3", @@ -6264,77 +6572,6 @@ ], "time": "2024-11-08T15:21:10+00:00" }, - { - "name": "szymach/c-pchart", - "version": "v3.0.17", - "source": { - "type": "git", - "url": "https://github.com/szymach/c-pchart.git", - "reference": "c022568da78f73bb7acf7db7a974934a434d47d7" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/szymach/c-pchart/zipball/c022568da78f73bb7acf7db7a974934a434d47d7", - "reference": "c022568da78f73bb7acf7db7a974934a434d47d7", - "shasum": "" - }, - "require": { - "ext-gd": "*", - "php": "^5.4|^7.0|^8.0" - }, - "require-dev": { - "codeception/codeception": "^4.1.22", - "codeception/module-asserts": "^1.3", - "codeception/module-filesystem": "^1.0", - "phpunit/phpunit": "^5.7|^9.5", - "squizlabs/php_codesniffer": "^3.4" - }, - "type": "library", - "extra": { - "branch-alias": { - "2.0": "2.0.x-dev", - "dev-master": "3.0.x-dev" - } - }, - "autoload": { - "files": [ - "constants.php" - ], - "psr-4": { - "CpChart\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "GPL-3.0-only" - ], - "authors": [ - { - "name": "Jean-Damien Pogolotti", - "homepage": "http://www.pchart.net", - "role": "Creator of the original pChart library" - }, - { - "name": "Piotr Szymaszek", - "homepage": "https://github.com/szymach", - "role": "Developer of the CpChart wrapper package" - } - ], - "description": "Port of \"pChart\" library into PHP 5+", - "homepage": "https://github.com/szymach/c-pchart", - "keywords": [ - "CpChart", - "c-pChart", - "charts", - "pchart", - "statistics" - ], - "support": { - "issues": "https://github.com/szymach/c-pchart/issues", - "source": "https://github.com/szymach/c-pchart/tree/v3.0.17" - }, - "time": "2023-05-27T11:12:02+00:00" - }, { "name": "tijsverkoyen/css-to-inline-styles", "version": "v2.2.7", @@ -6454,6 +6691,69 @@ }, "time": "2020-09-14T23:22:32+00:00" }, + { + "name": "vladimir-yuldashev/laravel-queue-rabbitmq", + "version": "v11.3.0", + "source": { + "type": "git", + "url": "https://github.com/vyuldashev/laravel-queue-rabbitmq.git", + "reference": "a5649faabfd224365b7c363f5e449777316d8627" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/vyuldashev/laravel-queue-rabbitmq/zipball/a5649faabfd224365b7c363f5e449777316d8627", + "reference": "a5649faabfd224365b7c363f5e449777316d8627", + "shasum": "" + }, + "require": { + "ext-json": "*", + "illuminate/queue": "^8.0", + "php": "^7.3|^8.0", + "php-amqplib/php-amqplib": "^2.12|^3.0" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^2.17", + "laravel/horizon": "^5.0", + "mockery/mockery": "^1.0", + "orchestra/testbench": "^6.0", + "phpunit/phpunit": "^9.3" + }, + "suggest": { + "ext-pcntl": "Required to use all features of the queue consumer." + }, + "type": "library", + "extra": { + "laravel": { + "providers": [ + "VladimirYuldashev\\LaravelQueueRabbitMQ\\LaravelQueueRabbitMQServiceProvider" + ] + }, + "branch-alias": { + "dev-master": "11.0-dev" + } + }, + "autoload": { + "psr-4": { + "VladimirYuldashev\\LaravelQueueRabbitMQ\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Vladimir Yuldashev", + "email": "misterio92@gmail.com" + } + ], + "description": "RabbitMQ driver for Laravel Queue. Supports Laravel Horizon.", + "support": { + "issues": "https://github.com/vyuldashev/laravel-queue-rabbitmq/issues", + "source": "https://github.com/vyuldashev/laravel-queue-rabbitmq/tree/v11.3.0" + }, + "time": "2021-07-06T00:05:52+00:00" + }, { "name": "vlucas/phpdotenv", "version": "v5.6.1", diff --git a/config/app.php b/config/app.php index 0195c29..4b01574 100644 --- a/config/app.php +++ b/config/app.php @@ -213,6 +213,9 @@ return [ 'Html' => Collective\Html\HtmlFacade::class, 'Debugbar' => Barryvdh\Debugbar\Facade::class, 'PDF' => Barryvdh\DomPDF\Facade::class, + 'CampaignTypes' => \App\Enums\CampaignTypes::class, + 'Countries' => \App\Enums\Countries::class, + 'UserRoles' => \App\Enums\UserRoles::class, ], ]; diff --git a/config/auth.php b/config/auth.php index 6baa98c..59a56f4 100644 --- a/config/auth.php +++ b/config/auth.php @@ -67,7 +67,7 @@ return [ 'providers' => [ 'users' => [ 'driver' => 'eloquent', - 'model' => App\User::class, + 'model' => App\Models\User::class, ], // 'users' => [ diff --git a/config/constants.php b/config/constants.php index 16a85d2..07e18c0 100644 --- a/config/constants.php +++ b/config/constants.php @@ -2,7 +2,6 @@ return [ 'updatebasket' => 1, -'delctrlcontact' => 2, 'impression' => 3, 'updatecontact' => 4, 'colors' => ['#ffe258', '#8c86ff', '#86ffbc', '#ffc286', '#86caff', '#ff86e7', '#ff869d', '#b9ff86', '#e7ff86', '#b986ff', '#ffae86', '#5c60ff', '#ff5c5c', '#3ba33b', '#8c86ff', '#86ffbc', '#ffc286', '#86caff', '#ff86e7', '#ff869d', '#b9ff86', '#e7ff86', '#b986ff', '#ffae86', '#5c60ff', '#ff5c5c', '#3ba33b'] diff --git a/config/crm.php b/config/crm.php deleted file mode 100644 index 4cc5fa5..0000000 --- a/config/crm.php +++ /dev/null @@ -1,5 +0,0 @@ - env('CRM_ENDPOINT') -]; diff --git a/config/logging.php b/config/logging.php index c385048..169b273 100644 --- a/config/logging.php +++ b/config/logging.php @@ -103,6 +103,11 @@ return [ 'channels' => ['daily', 'stdout'], 'ignore_exceptions' => false, ], - ], + 'crm' => [ + 'driver' => 'single', + 'path' => storage_path('logs/crm.log'), + 'level' => 'debug', + ], + ], ]; diff --git a/config/queue.php b/config/queue.php index 3c48fd8..425f182 100644 --- a/config/queue.php +++ b/config/queue.php @@ -65,6 +65,38 @@ return [ 'block_for' => null, ], + 'rabbitmq' => [ + 'driver' => 'rabbitmq', 'hosts' => [ + [ + 'host' => env('RABBITMQ_HOST', '127.0.0.1'), + 'port' => env('RABBITMQ_PORT', 5672), + 'user' => env('RABBITMQ_USER', 'guest'), + 'password' => env('RABBITMQ_PASSWORD', 'guest'), + 'vhost' => env('RABBITMQ_VHOST', '/'), + ], + ], + 'options' => [ + 'queue' => [ + 'exchange' => 'amq.fanout', + 'exchange_type' => 'fanout', + ], + 'ssl_options' => [ + 'cafile' => env('RABBITMQ_SSL_CAFILE', null), + 'local_cert' => env('RABBITMQ_SSL_LOCALCERT', null), + 'local_key' => env('RABBITMQ_SSL_LOCALKEY', null), + 'verify_peer' => env('RABBITMQ_SSL_VERIFY_PEER', true), + 'passphrase' => env('RABBITMQ_SSL_PASSPHRASE', null), + ], + ], + + /* + * Set to "horizon" if you wish to use Laravel Horizon. + */ + + 'worker' => env('RABBITMQ_WORKER', 'default'), + 'queue' => env('RABBITMQ_QUEUE', 'default'), + ], + ], /* diff --git a/config/services.php b/config/services.php index 0751cb1..572bc76 100644 --- a/config/services.php +++ b/config/services.php @@ -31,9 +31,13 @@ return [ ], 'stripe' => [ - 'model' => App\User::class, + 'model' => App\Models\User::class, 'key' => env('STRIPE_KEY'), 'secret' => env('STRIPE_SECRET'), ], + 'crm' => [ + 'endpoint' => env('CRM_ENDPOINT') + ] + ]; diff --git a/database/factories/CampagneFactory.php b/database/factories/CampagneFactory.php new file mode 100644 index 0000000..c44325a --- /dev/null +++ b/database/factories/CampagneFactory.php @@ -0,0 +1,24 @@ + $this->faker->unique()->bothify('???##'), + 'camp_name' => $this->faker->name(), + 'camp_type' => $this->faker->numberBetween(0, 1), //FIXME: Add Enum after murss and paniers values deletion. + 'camp_limitedPrinting' => $this->faker->numberBetween(0, 1), + 'camp_published' => $this->faker->numberBetween(0, 1), + ]; + } +} diff --git a/database/factories/ContactFactory.php b/database/factories/ContactFactory.php new file mode 100644 index 0000000..b5e874b --- /dev/null +++ b/database/factories/ContactFactory.php @@ -0,0 +1,26 @@ + $this->faker->bothify('??###'), // e.g., LG89 + 'contact_ref' => $this->faker->uuid(), + 'contact_prenom' => $this->faker->firstName(), + 'contact_nom' => $this->faker->lastName(), + 'contact_email' => $this->faker->email(), + 'contact_cp' => $this->faker->numberBetween(7200, 95000), + 'contact_ville' => $this->faker->city(), + ]; + } +} diff --git a/database/factories/CouponFactory.php b/database/factories/CouponFactory.php new file mode 100644 index 0000000..5113973 --- /dev/null +++ b/database/factories/CouponFactory.php @@ -0,0 +1,54 @@ +faker->numberBetween(1000000000000, 9999999999999); + return [ + 'coupon_id' => $this->faker->unique()->randomDigit(), + 'coupon_siteId' => $this->faker->unique()->randomDigit(), + 'coupon_code' => $this->faker->numberBetween(1000000000000, 9999999999999), + 'coupon_gs1code' => 'storage/modelfiles/coupons/' . $couponCode . '.jpg', + 'coupon_name' => $this->faker->name(), + 'coupon_value' => $this->faker->numberBetween(0.5, 3), + 'coupon_thumbnail1' => '', + 'coupon_thumbnail2' => '', + 'coupon_thumbnail3' => '', + 'coupon_thumbnail4' => '', + 'coupon_image' => 'storage/modelfiles/coupons/'. $couponCode .'.png', + 'coupon_enablelimitquantity' => $this->faker->numberBetween(0, 1), + 'coupon_limitquantity' => $this->faker->randomDigit(), + 'coupon_enablelimitperiod' => $this->faker->numberBetween(0, 1), + 'coupon_limitperiod' => $this->faker->numberBetween(0, 30), + 'coupon_validity' => 30, + 'coupon_mindatediffusion' => '2025-10-06', + 'coupon_maxdatediffusion' => '2025-12-07', + 'coupon_maxdatevalidity' => '2026-01-07', + 'coupon_norme' => $this->faker->numberBetween(0, 1), + 'coupon_published' => $this->faker->numberBetween(0, 1), + 'coupon_createdate' => '2025-08-01 13:03:31', + 'coupon_updatedate' => '2025-11-05 20:58:29', + 'coupon_deleted_at' => null, + 'coupon_decoration_image' => 'storage/modelfiles/coupons/'. Str::random(20) .'.png', + 'coupon_logo_image' => 'storage/modelfiles/coupons/'. Str::random(20) .'.jpg', + 'coupon_validity_text' => $this->faker->sentence(), + 'coupon_rcs' => $this->faker->sentence(), + 'coupon_legal_mentions' => $this->faker->sentence(), + 'coupon_legal_mentions_splitted' => $this->faker->numberBetween(0, 1), + 'coupon_site_contact' => $this->faker->email(), + 'coupon_seuil_alert' => 100, + 'coupon_treatment_center' => 0, + ]; + } +} diff --git a/database/factories/PanierFactory.php b/database/factories/PanierFactory.php new file mode 100644 index 0000000..c0e8ec4 --- /dev/null +++ b/database/factories/PanierFactory.php @@ -0,0 +1,22 @@ + strtoupper(md5(uniqid(time(), true))), + 'panier_campId' => $this->faker->randomDigit(), + 'panier_pending' => $this->faker->numberBetween(0, 1) + ]; + } +} diff --git a/database/factories/SiteFactory.php b/database/factories/SiteFactory.php new file mode 100644 index 0000000..e68b87d --- /dev/null +++ b/database/factories/SiteFactory.php @@ -0,0 +1,29 @@ +faker->company; + + return [ + 'site_id' => $this->faker->unique()->bothify('???##'), + 'site_nom' => $company, + 'site_logo' => $this->faker->imageUrl(), + 'site_contact' => $this->faker->email, + 'site_rcs' => $this->faker->sentence, + 'site_libelle' => $company, + 'crm_token' => '', + 'crm_password' => '' + ]; + } +} diff --git a/database/factories/StatistiqueFactory.php b/database/factories/StatistiqueFactory.php index 0ad7a4d..66c0725 100644 --- a/database/factories/StatistiqueFactory.php +++ b/database/factories/StatistiqueFactory.php @@ -2,7 +2,7 @@ use Faker\Generator as Faker; -$factory->define(App\Statistique::class, function (Faker $faker) { +$factory->define(App\Models\Statistique::class, function (Faker $faker) { return [ ]; }); diff --git a/database/factories/UserFactory.php b/database/factories/UserFactory.php index 1665d0b..26f4a90 100644 --- a/database/factories/UserFactory.php +++ b/database/factories/UserFactory.php @@ -13,7 +13,7 @@ use Faker\Generator as Faker; | */ -$factory->define(App\User::class, function (Faker $faker) { +$factory->define(App\Models\User::class, function (Faker $faker) { return [ 'name' => $faker->name, 'email' => $faker->unique()->safeEmail, diff --git a/database/migrations/2019_01_03_154432_create_site_user_pivot_table.php b/database/migrations/2019_01_03_154432_create_site_user_pivot_table.php deleted file mode 100644 index 937f226..0000000 --- a/database/migrations/2019_01_03_154432_create_site_user_pivot_table.php +++ /dev/null @@ -1,41 +0,0 @@ -dropPrimary('site_id'); - // $table->integer('id')->unsigned()->first()->autoIncrement(); - // $table->primary('id'); - // $table->engine = 'InnoDB'; - // }); - - Schema::create('site_user', function (Blueprint $table) { - $table->integer('user_id')->unsigned()->nullable(); - $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); - $table->integer('site_id')->unsigned()->nullable(); - $table->foreign('site_id')->references('id')->on('site')->onDelete('cascade'); - $table->primary(['site_id', 'user_id']); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::drop('site_user'); - } -} diff --git a/database/migrations/2019_01_07_103109_add_fields_to_sites_table.php b/database/migrations/2019_01_07_103109_add_fields_to_sites_table.php deleted file mode 100644 index 6548a2d..0000000 --- a/database/migrations/2019_01_07_103109_add_fields_to_sites_table.php +++ /dev/null @@ -1,34 +0,0 @@ -string('site_rcs', 100)->nullable(); - $table->string('site_libelle', 200)->nullable(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('site', function (Blueprint $table) { - $table->dropColumn('site_rcs'); - $table->dropColumn('site_libelle'); - }); - } -} diff --git a/database/migrations/2019_01_08_094821_add_diffusiondatefield_to_coupons_table.php b/database/migrations/2019_01_08_094821_add_diffusiondatefield_to_coupons_table.php deleted file mode 100644 index bda1e98..0000000 --- a/database/migrations/2019_01_08_094821_add_diffusiondatefield_to_coupons_table.php +++ /dev/null @@ -1,40 +0,0 @@ -date('coupon_maxdatediffusion')->nullable(); - $table->string('coupon_products_image', 500)->nullable(); - $table->string('coupon_validity_text', 500)->nullable(); - $table->string('coupon_legal_mentions', 500)->nullable(); - $table->dropColumn('coupon_quantity'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('coupon', function (Blueprint $table) { - $table->integer('coupon_quantity'); - $table->dropColumn('coupon_maxdatediffusion'); - $table->dropColumn('coupon_products_image'); - $table->dropColumn('coupon_validity_text'); - $table->dropColumn('coupon_legal_mentions'); - }); - } -} diff --git a/database/migrations/2019_01_09_132916_create_campagne_coupon_pivot_table.php b/database/migrations/2019_01_09_132916_create_campagne_coupon_pivot_table.php deleted file mode 100644 index 060aca3..0000000 --- a/database/migrations/2019_01_09_132916_create_campagne_coupon_pivot_table.php +++ /dev/null @@ -1,33 +0,0 @@ -integer('camp_id')->nullable(); - $table->foreign('camp_id')->references('camp_id')->on('campagne')->onDelete('cascade'); - $table->integer('coupon_id')->nullable(); - $table->foreign('coupon_id')->references('coupon_id')->on('coupon')->onDelete('cascade'); - $table->primary(['camp_id', 'coupon_id']); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::drop('campagne_coupon'); - } -} diff --git a/database/migrations/2019_02_27_133440_add_treatmentcenter_to_coupons.php b/database/migrations/2019_02_27_133440_add_treatmentcenter_to_coupons.php deleted file mode 100644 index b14841f..0000000 --- a/database/migrations/2019_02_27_133440_add_treatmentcenter_to_coupons.php +++ /dev/null @@ -1,32 +0,0 @@ -integer('coupon_treatment_center')->default(1); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('coupon', function (Blueprint $table) { - $table->dropColumn('coupon_treatment_center'); - }); - } -} diff --git a/database/migrations/2025_03_26_124019_move_uploaded_files_to_build_folder.php b/database/migrations/2025_03_26_124019_move_uploaded_files_to_build_folder.php deleted file mode 100644 index a149fe4..0000000 --- a/database/migrations/2025_03_26_124019_move_uploaded_files_to_build_folder.php +++ /dev/null @@ -1,85 +0,0 @@ -withTrashed()->get(); - foreach ($couponModels as $couponModel) { - $couponModel->coupon_gs1code = self::getUpdatedFilePath($couponModel->coupon_gs1code ?? ''); - $couponModel->coupon_thumbnail1 = self::getUpdatedFilePath($couponModel->coupon_thumbnail1 ?? ''); - $couponModel->coupon_thumbnail2 = self::getUpdatedFilePath($couponModel->coupon_thumbnail2 ?? ''); - $couponModel->coupon_thumbnail3 = self::getUpdatedFilePath($couponModel->coupon_thumbnail3 ?? ''); - $couponModel->coupon_thumbnail4 = self::getUpdatedFilePath($couponModel->coupon_thumbnail4 ?? ''); - $couponModel->coupon_image = self::getUpdatedFilePath($couponModel->coupon_image ?? ''); - $couponModel->coupon_decoration_image = self::getUpdatedFilePath($couponModel->coupon_decoration_image ?? ''); - $couponModel->coupon_logo_image = self::getUpdatedFilePath($couponModel->coupon_logo_image ?? ''); - $couponModel->save(); - } - - $siteModels = Site::query()->get(); - foreach ($siteModels as $siteModel) { - $siteModel->site_logo = self::getUpdatedFilePath($siteModel->site_logo ?? '',); - $siteModel->save(); - } - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - $couponModels = Coupon::query()->withTrashed()->get(); - foreach ($couponModels as $couponModel) { - $couponModel->coupon_gs1code = self::getOldFilePath($couponModel->coupon_gs1code ?? ''); - $couponModel->coupon_thumbnail1 = self::getOldFilePath($couponModel->coupon_thumbnail1 ?? ''); - $couponModel->coupon_thumbnail2 = self::getOldFilePath($couponModel->coupon_thumbnail2 ?? ''); - $couponModel->coupon_thumbnail3 = self::getOldFilePath($couponModel->coupon_thumbnail3 ?? ''); - $couponModel->coupon_thumbnail4 = self::getOldFilePath($couponModel->coupon_thumbnail4 ?? ''); - $couponModel->coupon_image = self::getOldFilePath($couponModel->coupon_image ?? ''); - $couponModel->coupon_decoration_image = self::getOldFilePath($couponModel->coupon_decoration_image ?? ''); - $couponModel->coupon_logo_image = self::getOldFilePath($couponModel->coupon_logo_image ?? ''); - $couponModel->save(); - } - - $siteModels = Site::query()->get(); - foreach ($siteModels as $siteModel) { - $siteModel->site_logo = self::getOldFilePath($siteModel->site_logo ?? '',); - $siteModel->save(); - } - } - - /** - * Get the updated file path (with 'storage/modelfiles' instead of folder in public) - * @param string $path - * - * @return string - */ - private static function getUpdatedFilePath(string $path): string - { - return !empty($path) ? Str::start($path, 'storage/modelfiles/') : ''; - } - - /** - * Get the old file path (with 'uploads/images' instead of 'storage/modelfiles') - * @param string $path - * - * @return string - */ - private static function getOldFilePath(string $path): string - { - return Str::replaceFirst('storage/modelfiles/', '', $path); - } -} diff --git a/database/migrations/2025_04_11_100847_create_calendrier_table.php b/database/migrations/2025_04_11_100847_create_calendrier_table.php new file mode 100644 index 0000000..1dfb9f5 --- /dev/null +++ b/database/migrations/2025_04_11_100847_create_calendrier_table.php @@ -0,0 +1,34 @@ +integer('calendrier_id', true); + $table->integer('calendrier_couponId')->default(0); + $table->timestamp('calendrier_startdate')->default(DB::raw("'1970-01-01 00:00:01'")); + $table->timestamp('calendrier_enddate')->default(DB::raw("'1970-01-01 00:00:01'")); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('calendrier'); + } +}; diff --git a/database/migrations/2025_04_03_095449_delete_password_resets_table.php b/database/migrations/2025_04_11_100847_create_campagne_coupon_table.php similarity index 52% rename from database/migrations/2025_04_03_095449_delete_password_resets_table.php rename to database/migrations/2025_04_11_100847_create_campagne_coupon_table.php index d4ae8ed..de170b5 100644 --- a/database/migrations/2025_04_03_095449_delete_password_resets_table.php +++ b/database/migrations/2025_04_11_100847_create_campagne_coupon_table.php @@ -4,7 +4,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -class DeletePasswordResetsTable extends Migration +return new class extends Migration { /** * Run the migrations. @@ -13,7 +13,12 @@ class DeletePasswordResetsTable extends Migration */ public function up() { - Schema::dropIfExists('password_resets'); + Schema::create('campagne_coupon', function (Blueprint $table) { + $table->integer('campagne_id'); + $table->integer('coup_id')->index('campagne_coupon_coupon_id_foreign'); + + $table->primary(['campagne_id', 'coup_id']); + }); } /** @@ -23,10 +28,6 @@ class DeletePasswordResetsTable extends Migration */ public function down() { - Schema::create('password_resets', function (Blueprint $table) { - $table->string('email')->index(); - $table->string('token'); - $table->timestamp('created_at')->nullable(); - }); + Schema::dropIfExists('campagne_coupon'); } -} +}; diff --git a/database/migrations/2025_04_11_100847_create_campagne_table.php b/database/migrations/2025_04_11_100847_create_campagne_table.php new file mode 100644 index 0000000..7ddfe52 --- /dev/null +++ b/database/migrations/2025_04_11_100847_create_campagne_table.php @@ -0,0 +1,38 @@ +integer('camp_id', true); + $table->string('camp_siteId', 50); + $table->string('camp_name', 500)->default(''); + $table->integer('camp_type')->default(0)->comment('0 = mur; 1 = panier; 2 = mur sous forme de panier'); + $table->integer('camp_limitedPrinting')->default(0)->comment('Limite l\'impression des paniers à un BR à la fois'); + $table->integer('camp_published')->default(1); + $table->timestamp('camp_createdate')->useCurrent(); + $table->timestamp('camp_updatedate')->useCurrentOnUpdate()->useCurrent(); + $table->timestamp('camp_deleted_at')->nullable(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('campagne'); + } +}; diff --git a/database/migrations/2025_04_11_100847_create_contact_table.php b/database/migrations/2025_04_11_100847_create_contact_table.php new file mode 100644 index 0000000..6cf80c7 --- /dev/null +++ b/database/migrations/2025_04_11_100847_create_contact_table.php @@ -0,0 +1,44 @@ +integer('contact_id', true); + $table->string('contact_siteId', 50); + $table->string('contact_ref', 200)->default(''); + $table->string('contact_prenom', 200)->default(''); + $table->string('contact_nom', 200)->default(''); + $table->string('contact_email', 200)->default(''); + $table->string('contact_cp', 50)->default(''); + $table->string('contact_ville', 200)->default(''); + $table->timestamp('contact_createdate')->useCurrent(); + $table->timestamp('contact_updatedate')->useCurrentOnUpdate()->useCurrent(); + $table->unsignedInteger('contact_country')->default(250); + $table->string('contact_hash', 50)->nullable()->unique('contact_hash'); + + $table->index(['contact_ref', 'contact_email'], 'contact_ref'); + $table->index(['contact_email', 'contact_ref'], 'contact_email'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('contact'); + } +}; diff --git a/database/migrations/2025_04_11_100847_create_coupon_table.php b/database/migrations/2025_04_11_100847_create_coupon_table.php new file mode 100644 index 0000000..0169cd4 --- /dev/null +++ b/database/migrations/2025_04_11_100847_create_coupon_table.php @@ -0,0 +1,62 @@ +integer('coupon_id', true); + $table->integer('coupon_siteId'); + $table->string('coupon_code', 50)->default(''); + $table->string('coupon_gs1code', 500)->default(''); + $table->string('coupon_name', 500)->default(''); + $table->float('coupon_value', 10, 0)->default(0); + $table->string('coupon_thumbnail1', 500)->default(''); + $table->string('coupon_thumbnail2', 500)->default(''); + $table->string('coupon_thumbnail3', 500)->default(''); + $table->string('coupon_thumbnail4', 500)->default(''); + $table->string('coupon_image', 500)->default(''); + $table->integer('coupon_enablelimitquantity')->default(0); + $table->integer('coupon_limitquantity')->default(1); + $table->integer('coupon_enablelimitperiod')->default(0); + $table->integer('coupon_limitperiod')->default(0); + $table->integer('coupon_validity')->default(30); + $table->date('coupon_mindatediffusion')->nullable(); + $table->date('coupon_maxdatediffusion')->nullable(); + $table->date('coupon_maxdatevalidity')->nullable(); + $table->integer('coupon_norme')->default(0)->comment('0 = par défaut; 1 = Benelux'); + $table->integer('coupon_published')->default(1); + $table->timestamp('coupon_createdate')->useCurrent(); + $table->timestamp('coupon_updatedate')->useCurrentOnUpdate()->nullable()->useCurrent(); + $table->timestamp('coupon_deleted_at')->nullable(); + $table->string('coupon_decoration_image', 500)->nullable(); + $table->string('coupon_logo_image', 500)->nullable(); + $table->string('coupon_validity_text', 500)->nullable(); + $table->string('coupon_rcs', 500)->nullable(); + $table->string('coupon_legal_mentions', 1000)->nullable(); + $table->tinyInteger('coupon_legal_mentions_splitted')->default(0); + $table->string('coupon_site_contact', 500)->nullable(); + $table->unsignedInteger('coupon_seuil_alert')->default(100); + $table->integer('coupon_treatment_center')->default(0); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('coupon'); + } +}; diff --git a/database/migrations/2021_04_20_105237_create_customers_table.php b/database/migrations/2025_04_11_100847_create_customers_table.php similarity index 63% rename from database/migrations/2021_04_20_105237_create_customers_table.php rename to database/migrations/2025_04_11_100847_create_customers_table.php index 44b9882..0985d62 100644 --- a/database/migrations/2021_04_20_105237_create_customers_table.php +++ b/database/migrations/2025_04_11_100847_create_customers_table.php @@ -1,10 +1,10 @@ increments('id'); - $table->string('hashcode', 36)->unique(); - $table->string('email')->unique(); - $table->integer('country')->default('250'); + $table->bigInteger('id', true); + $table->string('hashcode', 36)->default(''); + $table->string('email'); + $table->integer('country')->default(250); $table->timestamps(); + + $table->unique(['hashcode', 'email'], 'crm_id'); }); } @@ -31,4 +33,4 @@ class CreateCustomersTable extends Migration { Schema::dropIfExists('customers'); } -} +}; diff --git a/database/migrations/2019_02_19_105641_create_logs_table.php b/database/migrations/2025_04_11_100847_create_logs_table.php similarity index 81% rename from database/migrations/2019_02_19_105641_create_logs_table.php rename to database/migrations/2025_04_11_100847_create_logs_table.php index 31bb828..91dbdb5 100644 --- a/database/migrations/2019_02_19_105641_create_logs_table.php +++ b/database/migrations/2025_04_11_100847_create_logs_table.php @@ -1,10 +1,10 @@ increments('id'); $table->integer('log_action'); $table->string('log_refsite')->nullable(); - $table->integer('log_contactId')->nullable(); + $table->integer('log_contactId')->nullable()->index('FK_log_contact'); $table->string('log_source'); $table->text('log_params')->nullable(); $table->string('log_statut'); $table->text('log_message'); - $table->timestamp('created_at'); + $table->timestamp('created_at')->useCurrent(); }); } + /** * Reverse the migrations. * @@ -34,4 +35,4 @@ class CreateLogsTable extends Migration { Schema::dropIfExists('logs'); } -} +}; diff --git a/database/migrations/2018_09_27_074409_create_mouvements_table.php b/database/migrations/2025_04_11_100847_create_mouvement_table.php similarity index 64% rename from database/migrations/2018_09_27_074409_create_mouvements_table.php rename to database/migrations/2025_04_11_100847_create_mouvement_table.php index 6bb1e5e..1306448 100644 --- a/database/migrations/2018_09_27_074409_create_mouvements_table.php +++ b/database/migrations/2025_04_11_100847_create_mouvement_table.php @@ -1,10 +1,10 @@ engine = 'MyISAM'; $table->increments('mouvement_id'); $table->unsignedInteger('mouvement_couponId'); - $table->string('mouvement_type', 50); - $table->timestamp('mouvement_created_at'); - $table->unsignedInteger('mouvement_nombre'); - $table->string('mouvement_commentaire', 255)->nullable(); + $table->integer('mouvement_nombre'); + $table->string('mouvement_commentaire')->nullable(); + $table->timestamp('mouvement_created_at')->useCurrentOnUpdate()->useCurrent(); }); } @@ -33,4 +31,4 @@ class CreateMouvementsTable extends Migration { Schema::dropIfExists('mouvement'); } -} +}; diff --git a/database/migrations/2025_04_11_100847_create_mur_table.php b/database/migrations/2025_04_11_100847_create_mur_table.php new file mode 100644 index 0000000..df0b772 --- /dev/null +++ b/database/migrations/2025_04_11_100847_create_mur_table.php @@ -0,0 +1,35 @@ +integer('mur_id', true); + $table->integer('mur_campId')->index('FK_mur_campagne'); + $table->integer('mur_contactId')->index('mur_contactId'); + $table->integer('mur_couponId')->index('mur_couponId'); + $table->integer('mur_deleted')->default(0); + $table->timestamp('mur_createdate')->useCurrent(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('mur'); + } +}; diff --git a/database/migrations/2019_02_14_095700_add_name_to_notifications.php b/database/migrations/2025_04_11_100847_create_notification_table.php similarity index 58% rename from database/migrations/2019_02_14_095700_add_name_to_notifications.php rename to database/migrations/2025_04_11_100847_create_notification_table.php index 7e114d9..c588a4a 100644 --- a/database/migrations/2019_02_14_095700_add_name_to_notifications.php +++ b/database/migrations/2025_04_11_100847_create_notification_table.php @@ -1,10 +1,10 @@ integer('notif_id', true); + $table->string('notif_email', 200)->default(''); + $table->integer('notif_campId'); $table->string('notif_name', 100)->nullable(); }); } @@ -25,8 +28,6 @@ class AddNameToNotifications extends Migration */ public function down() { - Schema::table('notification', function (Blueprint $table) { - $table->dropColumn('notif_name'); - }); + Schema::dropIfExists('notification'); } -} +}; diff --git a/database/migrations/2025_04_11_100847_create_panier_content_table.php b/database/migrations/2025_04_11_100847_create_panier_content_table.php new file mode 100644 index 0000000..533a41b --- /dev/null +++ b/database/migrations/2025_04_11_100847_create_panier_content_table.php @@ -0,0 +1,34 @@ +integer('panier_content_id', true); + $table->integer('panier_content_panierId')->default(0)->index('FK_panier_content_panier'); + $table->integer('panier_content_couponId'); + $table->integer('panier_content_quantity')->default(0); + $table->integer('panier_content_printed')->default(0); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('panier_content'); + } +}; diff --git a/database/migrations/2025_04_11_100847_create_panier_table.php b/database/migrations/2025_04_11_100847_create_panier_table.php new file mode 100644 index 0000000..147eaac --- /dev/null +++ b/database/migrations/2025_04_11_100847_create_panier_table.php @@ -0,0 +1,36 @@ +integer('panier_id', true); + $table->string('panier_ref', 100)->default(''); + $table->integer('panier_campId'); + $table->integer('panier_contactId')->index('FK_panier_contact'); + $table->integer('panier_pending')->default(1)->comment('1 = en cours; 0 = terminé'); + $table->timestamp('panier_createdate')->useCurrent(); + $table->timestamp('panier_updatedate')->useCurrentOnUpdate()->useCurrent(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('panier'); + } +}; diff --git a/database/migrations/2014_10_12_100000_create_password_resets_table.php b/database/migrations/2025_04_11_100847_create_password_resets_table.php similarity index 92% rename from database/migrations/2014_10_12_100000_create_password_resets_table.php rename to database/migrations/2025_04_11_100847_create_password_resets_table.php index 0d5cb84..fcacb80 100644 --- a/database/migrations/2014_10_12_100000_create_password_resets_table.php +++ b/database/migrations/2025_04_11_100847_create_password_resets_table.php @@ -1,10 +1,10 @@ integer('camp_id')->index('FK_printed_wall_campagne'); + $table->integer('coupon_id')->index('FK_printed_wall_coupon'); + $table->bigInteger('customer_id')->index('FK_printed_wall_customers'); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('printed_walls'); + } +}; diff --git a/database/migrations/2025_04_11_100847_create_site_table.php b/database/migrations/2025_04_11_100847_create_site_table.php new file mode 100644 index 0000000..aa41a3f --- /dev/null +++ b/database/migrations/2025_04_11_100847_create_site_table.php @@ -0,0 +1,38 @@ +increments('id'); + $table->string('site_id', 50); + $table->string('site_nom', 200)->default(''); + $table->string('site_logo', 500)->default(''); + $table->string('site_contact', 500)->default(''); + $table->string('site_rcs', 100)->nullable(); + $table->string('site_libelle', 200)->nullable(); + $table->string('crm_token')->nullable(); + $table->string('crm_password')->nullable(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('site'); + } +}; diff --git a/database/migrations/2025_04_11_100847_create_site_user_table.php b/database/migrations/2025_04_11_100847_create_site_user_table.php new file mode 100644 index 0000000..9364faf --- /dev/null +++ b/database/migrations/2025_04_11_100847_create_site_user_table.php @@ -0,0 +1,33 @@ +unsignedInteger('user_id')->index('site_user_user_id_foreign'); + $table->unsignedInteger('site_id'); + + $table->primary(['site_id', 'user_id']); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('site_user'); + } +}; diff --git a/database/migrations/2019_02_14_111618_create_statistiques_table.php b/database/migrations/2025_04_11_100847_create_statistiques_table.php similarity index 75% rename from database/migrations/2019_02_14_111618_create_statistiques_table.php rename to database/migrations/2025_04_11_100847_create_statistiques_table.php index a6f48b8..0abeea4 100644 --- a/database/migrations/2019_02_14_111618_create_statistiques_table.php +++ b/database/migrations/2025_04_11_100847_create_statistiques_table.php @@ -1,10 +1,10 @@ increments('id'); - $table->string('stat_campId'); - $table->string('stat_couponId'); + $table->integer('stat_campId'); + $table->integer('stat_couponId'); $table->integer('stat_couponPrinted'); - $table->timestamp('created_at'); + $table->timestamp('created_at')->useCurrent(); }); } @@ -31,4 +31,4 @@ class CreateStatistiquesTable extends Migration { Schema::dropIfExists('statistiques'); } -} +}; diff --git a/database/migrations/2014_10_12_000000_create_users_table.php b/database/migrations/2025_04_11_100847_create_users_table.php similarity index 84% rename from database/migrations/2014_10_12_000000_create_users_table.php rename to database/migrations/2025_04_11_100847_create_users_table.php index 58bebbe..d9bede1 100644 --- a/database/migrations/2014_10_12_000000_create_users_table.php +++ b/database/migrations/2025_04_11_100847_create_users_table.php @@ -1,10 +1,10 @@ increments('id'); $table->string('name'); - $table->string('email'); + $table->string('email', 100)->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); + $table->text('roles')->nullable(); }); } @@ -33,4 +34,4 @@ class CreateUsersTable extends Migration { Schema::dropIfExists('users'); } -} +}; diff --git a/database/migrations/2025_04_11_100850_add_foreign_keys_to_campagne_coupon_table.php b/database/migrations/2025_04_11_100850_add_foreign_keys_to_campagne_coupon_table.php new file mode 100644 index 0000000..c1a783c --- /dev/null +++ b/database/migrations/2025_04_11_100850_add_foreign_keys_to_campagne_coupon_table.php @@ -0,0 +1,34 @@ +foreign(['campagne_id'], 'campagne_coupon_camp_id_foreign')->references(['camp_id'])->on('campagne')->onDelete('CASCADE'); + $table->foreign(['coup_id'], 'campagne_coupon_coupon_id_foreign')->references(['coupon_id'])->on('coupon')->onDelete('CASCADE'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('campagne_coupon', function (Blueprint $table) { + $table->dropForeign('campagne_coupon_camp_id_foreign'); + $table->dropForeign('campagne_coupon_coupon_id_foreign'); + }); + } +}; diff --git a/database/migrations/2019_01_10_083318_add_countryfield_to_contact_table.php b/database/migrations/2025_04_11_100850_add_foreign_keys_to_logs_table.php similarity index 52% rename from database/migrations/2019_01_10_083318_add_countryfield_to_contact_table.php rename to database/migrations/2025_04_11_100850_add_foreign_keys_to_logs_table.php index 8123a69..1862fd1 100644 --- a/database/migrations/2019_01_10_083318_add_countryfield_to_contact_table.php +++ b/database/migrations/2025_04_11_100850_add_foreign_keys_to_logs_table.php @@ -1,10 +1,10 @@ unsignedInteger('contact_country')->default(250); + Schema::table('logs', function (Blueprint $table) { + $table->foreign(['log_contactId'], 'FK_log_contact')->references(['contact_id'])->on('contact')->onDelete('CASCADE'); }); } @@ -25,8 +25,8 @@ class AddCountryfieldToContactTable extends Migration */ public function down() { - Schema::table('contact', function (Blueprint $table) { - $table->dropColumn('contact_country'); + Schema::table('logs', function (Blueprint $table) { + $table->dropForeign('FK_log_contact'); }); } -} +}; diff --git a/database/migrations/2019_01_02_110900_add_roles_to_users_table.php b/database/migrations/2025_04_11_100850_add_foreign_keys_to_mur_table.php similarity index 53% rename from database/migrations/2019_01_02_110900_add_roles_to_users_table.php rename to database/migrations/2025_04_11_100850_add_foreign_keys_to_mur_table.php index 8fb6554..b0d2083 100644 --- a/database/migrations/2019_01_02_110900_add_roles_to_users_table.php +++ b/database/migrations/2025_04_11_100850_add_foreign_keys_to_mur_table.php @@ -1,10 +1,10 @@ text('roles')->nullable(); + Schema::table('mur', function (Blueprint $table) { + $table->foreign(['mur_contactId'], 'FK_mur_contact')->references(['contact_id'])->on('contact')->onDelete('CASCADE'); }); } @@ -25,8 +25,8 @@ class AddRolesToUsersTable extends Migration */ public function down() { - Schema::table('users', function (Blueprint $table) { - $table->dropColumn('roles'); + Schema::table('mur', function (Blueprint $table) { + $table->dropForeign('FK_mur_contact'); }); } -} +}; diff --git a/database/migrations/2025_04_11_100850_add_foreign_keys_to_panier_content_table.php b/database/migrations/2025_04_11_100850_add_foreign_keys_to_panier_content_table.php new file mode 100644 index 0000000..0e7443e --- /dev/null +++ b/database/migrations/2025_04_11_100850_add_foreign_keys_to_panier_content_table.php @@ -0,0 +1,32 @@ +foreign(['panier_content_panierId'], 'FK_panier_content_panier')->references(['panier_id'])->on('panier')->onDelete('CASCADE'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('panier_content', function (Blueprint $table) { + $table->dropForeign('FK_panier_content_panier'); + }); + } +}; diff --git a/database/migrations/2025_04_11_100850_add_foreign_keys_to_panier_table.php b/database/migrations/2025_04_11_100850_add_foreign_keys_to_panier_table.php new file mode 100644 index 0000000..4156734 --- /dev/null +++ b/database/migrations/2025_04_11_100850_add_foreign_keys_to_panier_table.php @@ -0,0 +1,32 @@ +foreign(['panier_contactId'], 'FK_panier_contact')->references(['contact_id'])->on('contact')->onDelete('CASCADE'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('panier', function (Blueprint $table) { + $table->dropForeign('FK_panier_contact'); + }); + } +}; diff --git a/database/migrations/2025_04_11_100850_add_foreign_keys_to_printed_walls_table.php b/database/migrations/2025_04_11_100850_add_foreign_keys_to_printed_walls_table.php new file mode 100644 index 0000000..c4b8624 --- /dev/null +++ b/database/migrations/2025_04_11_100850_add_foreign_keys_to_printed_walls_table.php @@ -0,0 +1,36 @@ +foreign(['camp_id'], 'FK_printed_wall_campagne')->references(['camp_id'])->on('campagne'); + $table->foreign(['coupon_id'], 'FK_printed_wall_coupon')->references(['coupon_id'])->on('coupon'); + $table->foreign(['customer_id'], 'FK_printed_wall_customers')->references(['id'])->on('customers')->onDelete('CASCADE'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('printed_walls', function (Blueprint $table) { + $table->dropForeign('FK_printed_wall_campagne'); + $table->dropForeign('FK_printed_wall_coupon'); + $table->dropForeign('FK_printed_wall_customers'); + }); + } +}; diff --git a/database/migrations/2025_04_11_100850_add_foreign_keys_to_site_user_table.php b/database/migrations/2025_04_11_100850_add_foreign_keys_to_site_user_table.php new file mode 100644 index 0000000..a0282d7 --- /dev/null +++ b/database/migrations/2025_04_11_100850_add_foreign_keys_to_site_user_table.php @@ -0,0 +1,34 @@ +foreign(['site_id'])->references(['id'])->on('site')->onDelete('CASCADE'); + $table->foreign(['user_id'])->references(['id'])->on('users')->onDelete('CASCADE'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('site_user', function (Blueprint $table) { + $table->dropForeign('site_user_site_id_foreign'); + $table->dropForeign('site_user_user_id_foreign'); + }); + } +}; diff --git a/database/migrations/2025_07_29_000000_rename_printed_walls_table.php b/database/migrations/2025_07_29_000000_rename_printed_walls_table.php new file mode 100644 index 0000000..9cafea2 --- /dev/null +++ b/database/migrations/2025_07_29_000000_rename_printed_walls_table.php @@ -0,0 +1,27 @@ +softDeletes('camp_deleted_at'); + Schema::table('printed_coupons', function (Blueprint $table) { + $table->id()->first(); + $table->softDeletes(); }); } @@ -25,8 +26,9 @@ class AddSoftDelete extends Migration */ public function down() { - Schema::table('campagne', function (Blueprint $table) { - // + Schema::table('printed_coupons', function (Blueprint $table) { + $table->dropColumn('id'); + $table->dropSoftDeletes(); }); } -} +}; diff --git a/database/migrations/2025_10_22_094302_create_baskets_table.php b/database/migrations/2025_10_22_094302_create_baskets_table.php new file mode 100644 index 0000000..7e38298 --- /dev/null +++ b/database/migrations/2025_10_22_094302_create_baskets_table.php @@ -0,0 +1,39 @@ +id(); + $table->string('ref', 36)->comment('Hashcode'); + + $table->integer('campagne_id')->comment('Id de la campagne associée'); + $table->foreign('campagne_id')->references('camp_id')->on('campagne'); + + $table->bigInteger('customer_id')->comment('Id du customer associé'); + $table->foreign('customer_id')->references('id')->on('customers'); + + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('baskets'); + } +} diff --git a/database/migrations/2025_10_22_101537_create_basket_contents_table.php b/database/migrations/2025_10_22_101537_create_basket_contents_table.php new file mode 100644 index 0000000..e14b556 --- /dev/null +++ b/database/migrations/2025_10_22_101537_create_basket_contents_table.php @@ -0,0 +1,39 @@ +id(); + $table->integer('quantity')->comment('Quantité de ce coupon dans le panier'); + $table->integer('printed')->comment('Quantité de coupons imprimés dans ce panier'); + + $table->foreignId('basket_id')->constrained('baskets'); + + $table->integer('coupon_id')->comment('Id du coupon associé'); + $table->foreign('coupon_id')->references('coupon_id')->on('coupon'); + + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('basket_contents'); + } +} diff --git a/database/migrations/2019_02_14_083641_add_seuil_to_coupons.php b/database/migrations/2025_10_30_103126_alter_ref_column_on_basket_table.php similarity index 52% rename from database/migrations/2019_02_14_083641_add_seuil_to_coupons.php rename to database/migrations/2025_10_30_103126_alter_ref_column_on_basket_table.php index 3fed9bb..1ac970d 100644 --- a/database/migrations/2019_02_14_083641_add_seuil_to_coupons.php +++ b/database/migrations/2025_10_30_103126_alter_ref_column_on_basket_table.php @@ -1,10 +1,10 @@ unsignedInteger('coupon_seuil_alert')->default(100); + Schema::table('baskets', function (Blueprint $table){ + $table->renameColumn('ref', 'uuid'); + $table->unique('uuid'); }); } @@ -25,8 +26,9 @@ class AddSeuilToCoupons extends Migration */ public function down() { - Schema::table('coupon', function (Blueprint $table) { - $table->dropColumn('coupon_seuil_alert'); + Schema::table('baskets', function (Blueprint $table){ + $table->dropUnique(['uuid']); + $table->renameColumn('uuid', 'ref'); }); } } diff --git a/database/migrations/2025_10_30_160644_alter_statistiques_table.php b/database/migrations/2025_10_30_160644_alter_statistiques_table.php new file mode 100644 index 0000000..5b0344d --- /dev/null +++ b/database/migrations/2025_10_30_160644_alter_statistiques_table.php @@ -0,0 +1,70 @@ +date('date')->nullable()->after('stat_couponPrinted'); + }); + + // Fill the previously created column with created_at date. + DB::table('statistiques')->update([ + 'date' => DB::raw('DATE(created_at)') + ]); + + // Remove nullable option. + Schema::table('statistiques', function (Blueprint $table) { + $table->date('date')->nullable(false)->change(); + }); + + // Create a temp table with only groupped datas. + DB::statement('CREATE TEMPORARY TABLE temp_statistiques AS + SELECT stat_campId, stat_couponId, date, SUM(stat_couponPrinted) AS quantity + FROM statistiques + GROUP BY stat_campId, stat_couponId, date'); + + // Remove all datas from the origin table. + DB::table('statistiques')->truncate(); + + // Insert datas from the temp table to the old one. + DB::statement('INSERT INTO statistiques (stat_campId, stat_couponId, date, stat_couponPrinted) + SELECT stat_campId, stat_couponId, date, quantity FROM temp_statistiques'); + + Schema::table('statistiques', function (Blueprint $table) { + $table->foreign('stat_campId')->references('camp_id')->on('campagne'); + $table->foreign('stat_couponId')->references('coupon_id')->on('coupon'); + $table->unique(['stat_campId', 'stat_couponId', 'date']); + }); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + DB::transaction(function () { + Schema::table('statistiques', function (Blueprint $table) { + $table->dropColumn('date'); + $table->dropForeign('statistiques_stat_campid_foreign'); + $table->dropForeign('statistiques_stat_couponid_foreign'); + $table->dropUnique('statistiques_stat_campid_stat_couponid_date_unique'); + }); + }); + } +} diff --git a/database/migrations/2025_11_03_150025_create_archive_sites_table.php b/database/migrations/2025_11_03_150025_create_archive_sites_table.php new file mode 100644 index 0000000..55939a3 --- /dev/null +++ b/database/migrations/2025_11_03_150025_create_archive_sites_table.php @@ -0,0 +1,33 @@ +id(); + $table->string('name')->comment('Name of the archived site'); + $table->string('site_id', 50)->unique()->comment('Id of the archived site'); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('archive_sites'); + } +} diff --git a/database/migrations/2025_11_03_150033_create_archive_coupons_table.php b/database/migrations/2025_11_03_150033_create_archive_coupons_table.php new file mode 100644 index 0000000..21d2c8d --- /dev/null +++ b/database/migrations/2025_11_03_150033_create_archive_coupons_table.php @@ -0,0 +1,33 @@ +id(); + $table->string('name', 500)->comment('Name of the archived coupon'); + $table->string('coupon_code', 50)->unique()->comment('Treatment code of the archived coupon'); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('archive_coupons'); + } +} diff --git a/database/migrations/2025_11_03_150048_create_archive_campaigns_table.php b/database/migrations/2025_11_03_150048_create_archive_campaigns_table.php new file mode 100644 index 0000000..94ea7a1 --- /dev/null +++ b/database/migrations/2025_11_03_150048_create_archive_campaigns_table.php @@ -0,0 +1,34 @@ +id(); + $table->string('name', 500)->comment('Name of the archived campaign'); + $table->unsignedBigInteger('campaign_id')->unique()->comment('Id of the archived campaign'); + $table->foreignId('archive_site_id')->constrained(); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('archive_campaigns'); + } +} diff --git a/database/migrations/2025_11_03_150056_create_archive_stats_table.php b/database/migrations/2025_11_03_150056_create_archive_stats_table.php new file mode 100644 index 0000000..0a17dc2 --- /dev/null +++ b/database/migrations/2025_11_03_150056_create_archive_stats_table.php @@ -0,0 +1,38 @@ +id(); + $table->unsignedInteger('quantity')->comment('Quantity of distributed coupons this day'); + $table->date('date'); + $table->foreignId('archive_coupon_id')->constrained(); + $table->foreignId('archive_campaign_id')->constrained(); + $table->unique(['date', 'archive_coupon_id', 'archive_campaign_id']); + $table->timestamps(); + }); + + + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('archive_stats'); + } +} diff --git a/resources/assets/images/coupons/mask.png b/resources/assets/images/coupons/mask.png index 34c6d6f..b3d79b6 100755 Binary files a/resources/assets/images/coupons/mask.png and b/resources/assets/images/coupons/mask.png differ diff --git a/resources/js/ajax.js b/resources/js/ajax.js index f9fed68..961ae6a 100644 --- a/resources/js/ajax.js +++ b/resources/js/ajax.js @@ -6,7 +6,7 @@ $('#addCoupons').on('click', function(event){ if($(this).is(':checked')){ ids.push($(this).val()); } - + }) $.ajaxSetup({ headers: { @@ -15,14 +15,13 @@ $('#addCoupons').on('click', function(event){ }); $.ajax({ - url: '/add-coupons-ajax', + url: '/bo/campagne/'+ campid +'/add-coupons', type: 'POST', data: { - ids: ids , - campid: campid + ids: ids }, dataType: 'JSON', - success: function (reponse) { + success: function (reponse) { $.each(reponse, function(index, coupon){ var html = '
'+coupon.coupon_code+'
+ + + + + + + + @foreach ($users as $user) + + + + + + @if (Auth::user()->id === $user->id) + + @else + + @endif + + @endforeach +
{{ __('Nom') }}{{ __('Email') }}{{ __('Rôle') }}{{ __('Site liés') }}
{{ $user->name }}{{ $user->email }}{{ $user->roles }} + @foreach ($user->sites as $site) +

{{ $site->site_nom }}

+ @endforeach +
+
+ @csrf + @method('DELETE') + +
+
+ @endif + +@endsection \ No newline at end of file diff --git a/resources/views/campagne/create.blade.php b/resources/views/campagne/create.blade.php deleted file mode 100644 index b3e8ef3..0000000 --- a/resources/views/campagne/create.blade.php +++ /dev/null @@ -1,33 +0,0 @@ -@extends('layouts.main') - -@section('content') -

Nouvelle campagne

-
- {!! Form::open(['route' => 'campagne.store']) !!} -
-
- {!! Form::label('camp_name', 'Nom') !!} - {!! Form::input('text', 'camp_name', null, ['required']) !!} -
-
- {!! Form::label('camp_type', 'Type') !!} - {!! Form::select('camp_type', ['Mur', 'Panier', 'Mur sans sélection', 'Panier Sélectionnable']) !!} -
-
-
-
- {!! Form::label('camp_published', 'Publier') !!} - {!! Form::select('camp_published', ['Non', 'Oui']) !!} -
-
- {!! Form::label('camp_limitedPrinting', 'Limiter les impressions à 1 BR à la fois') !!} - {!! Form::checkbox('camp_limitedPrinting', 1, false, array('id'=>'camp_limitedPrinting')) !!} - {!! Form::label('camp_limitedPrinting', '') !!} -
-
-
- {!! Form::submit('Enregistrer') !!} -
- {!! Form::close() !!} -
-@endsection diff --git a/resources/views/campagne/edit.blade.php b/resources/views/campagne/edit.blade.php deleted file mode 100644 index 343f568..0000000 --- a/resources/views/campagne/edit.blade.php +++ /dev/null @@ -1,117 +0,0 @@ -@extends('layouts.main') - -@section('content') -

Editer la campagne

-
- {!! Form::model($campagne, ['route' => ['campagne.update', $campagne]]) !!} - @method('PUT') -
-
- {!! Form::label('camp_name', 'Nom') !!} - {!! Form::input('text', 'camp_name', null, ['required']) !!} -
-
- {!! Form::label('camp_type', 'Type') !!} - {!! Form::select('camp_type', ['Mur', 'Panier', 'Mur sans sélection', 'Panier Sélectionnable']) !!} -
-
-
-
- {!! Form::label('camp_published', 'Publier') !!} - {!! Form::select('camp_published', ['Non', 'Oui']) !!} -
-
- {!! Form::label('camp_limitedPrinting', 'Limiter les impressions à 1 BR à la fois') !!} - {!! Form::checkbox('camp_limitedPrinting', 1, ($campagne->camp_limitedPrinting ==1?true:null), array('id'=>'camp_limitedPrinting')) !!} - {!! Form::label('camp_limitedPrinting', '') !!} -
-
-
- {!! Form::submit('Mettre à jour') !!} -
- {!! Form::close() !!} -
-
-

Coupons de la campagne

- - - - - - - - @foreach($couponsLinked as $coupon) - - - - - - @endforeach -
CodeNom
{{ $coupon->coupon_code }}{{ $coupon->coupon_name }}camp_id}} data-couponid={{$coupon->coupon_id}}>
- @if(count($couponsLinked) == 0) -

Pas de coupons liés

- @endif - - -
-
-

Notifications par mail

-
- {!! Form::open(['action' => 'CampagneController@saveNotification']) !!} -
-
- {!! Form::label('notif_name', 'Nom') !!} - {!! Form::input('text', 'notif_name', null, ['required']) !!} - {{ Form::hidden('notif_campId', $campagne->camp_id) }} -
-
-
- {!! Form::label('notif_email', 'Email') !!} - {!! Form::input('text', 'notif_email', null, ['required']) !!} -
-
- - {!! Form::submit('Ajouter') !!} -
-
- {!! Form::close() !!} -
- - - - - - - - - - - @foreach($campagne->notifications as $n) - - - - - - - @endforeach - -
{{__('No') }}{{__('Nom') }}{{__('Email') }}
{{ $n->notif_id }}{{ $n->notif_name }}{{ $n->notif_email }}
-
- -{!! Form::open(['id' => 'delete-hidden']) !!} - @method('DELETE') -{!! Form::close() !!} -@endsection diff --git a/resources/views/campagnes/create.blade.php b/resources/views/campagnes/create.blade.php new file mode 100644 index 0000000..5f6c97c --- /dev/null +++ b/resources/views/campagnes/create.blade.php @@ -0,0 +1,55 @@ +@extends('layouts.main') + +@section('content') +

+ + + + {{ __('Nouvelle campagne') }} +

+
+ @if ($errors->any()) +
+ +
+ @endif +
+ @csrf +
+
+ + +
+
+ + +
+
+
+
+ + +
+
+ + + +
+
+
+ +
+
+
+@endsection diff --git a/resources/views/campagnes/edit.blade.php b/resources/views/campagnes/edit.blade.php new file mode 100644 index 0000000..5da7161 --- /dev/null +++ b/resources/views/campagnes/edit.blade.php @@ -0,0 +1,147 @@ +@extends('layouts.main') + +@section('content') +

+ + + + {{ __('Editer la campagne') }} +

+ +
+ @if ($errors->any()) +
+ +
+ @endif +
+ @csrf + @method('PUT') +
+
+ + +
+
+ + +
+
+
+
+ + +
+
+ + camp_limitedPrinting === 1 ? 'checked="checked"' : '' }} name="camp_limitedPrinting" type="checkbox" value="{{ $campagne->camp_limitedPrinting }}"> + +
+
+
+ +
+
+
+
+

+ + {{ __('Coupons de la campagne') }} +

+ + + + + + + + @foreach($campagne->coupons as $coupon) + + + + + + @endforeach +
{{ __('Code') }}{{ __('Nom') }}
{{ $coupon->coupon_code }}{{ $coupon->coupon_name }}camp_id}} data-couponid={{$coupon->coupon_id}}>
+ @if(count($campagne->coupons) === 0) +

{{ __('Pas de coupons liés') }}

+ @endif + + +
+
+

{{ __('Notifications par mail') }}

+
+
+ @csrf +
+
+ + +
+
+
+ + +
+
+ + +
+
+
+
+ + + + + + + + + + + @foreach($campagne->notifications as $n) + + + + + + + @endforeach + +
{{__('No') }}{{__('Nom') }}{{__('Email') }}
{{ $n->notif_id }}{{ $n->notif_name }}{{ $n->notif_email }}
+
+ +
+ @csrf + @method('DELETE') +
+@endsection diff --git a/resources/views/campagne/index.blade.php b/resources/views/campagnes/index.blade.php similarity index 57% rename from resources/views/campagne/index.blade.php rename to resources/views/campagnes/index.blade.php index 7788bcf..6af8ba4 100644 --- a/resources/views/campagne/index.blade.php +++ b/resources/views/campagnes/index.blade.php @@ -1,7 +1,16 @@ @extends('layouts.main') @section('content') -

Campagnes Ajouter

+

+ + + + {{ __('Campagnes') }} + + + {{ __('Ajouter') }} + +

@@ -19,49 +28,52 @@ - + @if ( $c->camp_published === 1) @else @endif - - + + @endforeach
{{ $c->camp_id }} {{ $c->camp_name }}{{ $c->camp_createdate }}{{ date('d/m/Y H:i', strtotime($c->camp_createdate)) }} + @if ( $c->camp_published === 1) + + @endif + + @if ($c->camp_published === 0) + + @endif +
-
-
- -
-{!! Form::open(['id' => 'delete-hidden']) !!} +
+ @csrf @method('DELETE') -{!! Form::close() !!} +
+ @endsection @section('scripts') -@endsection -@if(isset($created) && $created) - @section('scripts') - - @endsection - @endif diff --git a/resources/views/contact/index.blade.php b/resources/views/contact/index.blade.php deleted file mode 100644 index 404f0eb..0000000 --- a/resources/views/contact/index.blade.php +++ /dev/null @@ -1,99 +0,0 @@ -@extends('layouts.main') - -@section('content') - -

Recherche de contacts Ajouter

-
-
-
-
- - -
-
- - -
-
-
-
- - -
-
- - -
-
-
-
- - -
-
- - -
-
-
- -
-
-
-
-@if(isset($contacts) && count($contacts)>0) -
- - - - - - - - - - @foreach ($contacts as $contact) - @php - switch ($contact->contact_country) { - case 250: - $contact->contact_country = 'France'; - break; - case 56: - $contact->contact_country = 'Belgique'; - break; - case 442: - $contact->contact_country = 'Luxembourg'; - break; - default: - $contact->contact_country = 'France'; - break; - } - @endphp - - - - - - - - - @endforeach - - - - - -
RefNomEmailCode PostalVillePays
{{ $contact->contact_ref }}{{ $contact->contact_prenom }} {{$contact->contact_nom}}{{ $contact->contact_email }}{{ $contact->contact_cp }}{{ $contact->contact_ville }}{{ $contact->contact_country }}
- @if($search) - {{ $contacts->appends(request()->input())->links() }} - @endif -
- -
-@endif -@endsection diff --git a/resources/views/coupon/create.blade.php b/resources/views/coupon/create.blade.php index 5ff0f60..9084c7d 100644 --- a/resources/views/coupon/create.blade.php +++ b/resources/views/coupon/create.blade.php @@ -11,186 +11,192 @@ @endif
-

Nouveau Coupon

- {!! Form::open(['route' => 'coupon.store', 'enctype' => 'multipart/form-data']) !!} +

+ + {{ __('Nouveau Coupon') }} +

+
+ @csrf
- {!! Form::label('coupon_code', 'Code de traitement *') !!} - {!! Form::input('text', 'coupon_code', null, ['required']) !!} + +
- {!! Form::label('coupon_name', 'Nom interne *') !!} - {!! Form::input('text', 'coupon_name', null, ['required']) !!} + +
- {!! Form::label('coupon_value', 'Valeur faciale *') !!} - {!! Form::number('coupon_value', null, ['step' => '0.05', 'required']) !!} + +
- {!! Form::label('initial_quantity', 'Quantité initiale *') !!} - {!! Form::text('initial_quantity', null, ['required']) !!} + +
- {!! Form::label('coupon_norme', 'Activer la Norme GS1') !!} - {!! Form::checkbox('coupon_norme', 1, false, array('id'=>'coupon_norme')) !!} - {!! Form::label('coupon_norme', 'Activer') !!} + + +
- {!! Form::label('coupon_seuil_alert', 'Seuil d\'alerte *') !!} - {!! Form::number('coupon_seuil_alert', 100, ['required']) !!} + +
- {!! Form::label('coupon_enablelimitquantity', 'Activer La limite de quantité') !!} - {!! Form::checkbox('coupon_enablelimitquantity', 1, false, array('id'=>'coupon_enablelimitquantity')) !!} - {!! Form::label('coupon_enablelimitquantity', 'Activer') !!} + + +
- {!! Form::label('coupon_enablelimitperiod', 'Activer la limite sur une période') !!} - {!! Form::checkbox('coupon_enablelimitperiod', 1, false, array('id'=>'coupon_enablelimitperiod')) !!} - {!! Form::label('coupon_enablelimitperiod', 'Activer') !!} + + +
- {!! Form::label('coupon_limitquantity', 'Limiter la diffusion à') !!} + - {!! Form::number('coupon_limitquantity', null, ['class'=>'small']) !!} coupons + {{ __('coupons') }}
- {!! Form::label('coupon_limitperiod', 'Limiter la diffusion à une offre tous les') !!} + - {!! Form::number('coupon_limitperiod', null, ['class'=>'small']) !!} jours + {{ __('jours') }}
-

Validité

+

{{ __('Validité') }}

- {!! Form::label('coupon_mindatediffusion', 'Date de début de diffusion') !!} - {!! Form::date('coupon_mindatediffusion') !!} + +
- {!! Form::label('coupon_maxdatediffusion', 'Date de fin de diffusion') !!} - {!! Form::date('coupon_maxdatediffusion') !!} + +
-
- {!! Form::label('coupon_validity', 'Durée de validité à l\'impression') !!} - - {!! Form::number('coupon_validity', 30, ['class'=>'small', 'required']) !!} jours - -
+ + + {{ __('jours') }} + +
- {!! Form::label('coupon_maxdatevalidity', 'Date de fin de validité') !!} - {!! Form::date('coupon_maxdatevalidity') !!} + +
-

Calendrier de diffusion

+

{{ __('Calendrier de diffusion') }}

-

Vignettes

+

{{ __('Vignettes') }}

- {!! Form::label('coupon_thumbnail1', 'Vignette Desktop active') !!} - {!! Form::file('coupon_thumbnail1', ['class' => 'input-file']) !!} + +
- {!! Form::label('coupon_thumbnail2', 'Vignette Desktop grise') !!} - {!! Form::file('coupon_thumbnail2', ['class' => 'input-file']) !!} + +
- {!! Form::label('coupon_thumbnail3', 'Vignette Mobile active') !!} - {!! Form::file('coupon_thumbnail3', ['class' => 'input-file']) !!} + +
- {!! Form::label('coupon_thumbnail4', 'Vignette Mobile grise') !!} - {!! Form::file('coupon_thumbnail4', ['class' => 'input-file']) !!} + +
-

Informations pour génération

- {{ __('Informations pour génération') }} +
- {!! Form::label('coupon_treatment_center', 'Centre de traitement *') !!} - {!! Form::select('coupon_treatment_center', ['HighCo', 'Sogec']) !!} + +
- {!! Form::label('coupon_legal_mentions_splitted', 'Activer les mentions internationnales') !!} - {!! Form::checkbox('coupon_legal_mentions_splitted', 1, false) !!} - {!! Form::label('coupon_legal_mentions_splitted', 'Activer') !!} + + +
- {!! Form::label('coupon_validity_text', 'Texte de validité *') !!} - {!! Form::textarea('coupon_validity_text', null, ['required']) !!} + +
- {!! Form::label('coupon_legal_mentions', 'Mentions légales *') !!} - {!! Form::textarea('coupon_legal_mentions', $mentions, ['required']) !!} + +
- {!! Form::label('coupon_decoration_image', 'Image de décoration *') !!} - (280x260px ou 280x160px si GS1) - Formats : JPG ou PNG + + {{ __('280x260px ou 280x160px si GS1') }} + {{ __('Formats : JPG ou PNG') }}
- {!! Form::file('coupon_decoration_image', ['class' => 'input-file', 'required', 'accept' => '.jpg,.jpeg,.png']) !!} +
- {!! Form::label('coupon_logo_image', 'Logo à afficher *') !!} - 135x70px - Formats : JPG ou PNG + + {{ __('135x70px') }} + {{ __('Formats : JPG ou PNG') }}
- {!! Form::file('coupon_logo_image', ['class' => 'input-file', 'required']) !!} +
- {!! Form::label('coupon_rcs', 'RCS du site *') !!} - {!! Form::text('coupon_rcs', $site->site_rcs, ['required']) !!} + +
- {!! Form::label('coupon_site_contact', 'Contact mail *') !!} - {!! Form::text('coupon_site_contact', $site->site_contact, ['required']) !!} + +
- {!! Form::label('coupon_gs1code', 'Image du code barre GS1 *') !!} - Formats : JPG + + {{ __('Formats : JPG') }}
- {!! Form::file('coupon_gs1code', ['class' => 'input-file']) !!} +
- {!! Form::label('coupon_published', 'Publié ?') !!} - {!! Form::checkbox('coupon_published', 1, false, array('id'=>'coupon_published')) !!} - {!! Form::label('coupon_published', 'Activer') !!} + + +
- - {!! Form::hidden('site_id', session()->get('site')->id) !!} + +
- Les champs avec un * sont obligatoires - {!! Form::submit('Créer coupon') !!} + {{ __('Les champs avec un * sont obligatoires') }} +
- {!! Form::close() !!} + @endsection diff --git a/resources/views/coupon/edit.blade.php b/resources/views/coupon/edit.blade.php index 4dc75b9..47991dc 100644 --- a/resources/views/coupon/edit.blade.php +++ b/resources/views/coupon/edit.blade.php @@ -11,90 +11,94 @@ @endif
-

Editer le Coupon

- {!! Form::model($coupon, ['route' => ['coupon.update', $coupon], 'enctype' => 'multipart/form-data']) !!} +

+ + {{ __('Editer le Coupon')}} +

+
+ @csrf @method('PUT')
- {!! Form::label('coupon_code', 'Code de traitement *') !!} - {!! Form::input('text', 'coupon_code', $coupon->coupon_code, ['required']) !!} + +
- {!! Form::label('coupon_name', 'Nom interne *') !!} - {!! Form::input('text', 'coupon_name', $coupon->coupon_name, ['required']) !!} + +
- {!! Form::label('coupon_value', 'Valeur faciale *') !!} - {!! Form::number('coupon_value', null, ['step' => '0.05', 'required']) !!} + +
- {!! Form::label('coupon_norme', 'Activer la Norme GS1') !!} - {!! Form::checkbox('coupon_norme', 1, ($coupon->coupon_norme ==1?true:null), array('id'=>'coupon_norme')) !!} - {!! Form::label('coupon_norme', 'Activer') !!} + + coupon_norme === 1 ? 'checked' : null) }}> +
- {!! Form::label('coupon_seuil_alert', 'Seuil d\'alerte *') !!} - {!! Form::number('coupon_seuil_alert', $coupon->coupon_seuil_alert, ['required']) !!} + +
- +
- {!! Form::label('coupon_enablelimitquantity', 'Activer La limite de quantité') !!} - {!! Form::checkbox('coupon_enablelimitquantity', 1, ($coupon->coupon_enablelimitquantity ==1?true:null), array('id'=>'coupon_enablelimitquantity')) !!} - {!! Form::label('coupon_enablelimitquantity', 'Activer') !!} + + coupon_enablelimitquantity === 1 ? 'checked' : null) }}> +
- {!! Form::label('coupon_enablelimitperiod', 'Activer la limite sur une période') !!} - {!! Form::checkbox('coupon_enablelimitperiod', 1, ($coupon->coupon_enablelimitperiod ==1?true:null), array('id'=>'coupon_enablelimitperiod')) !!} - {!! Form::label('coupon_enablelimitperiod', 'Activer') !!} + + coupon_enablelimitperiod === 1 ? 'checked' : null) }}> +
- {!! Form::label('coupon_limitquantity', 'Limiter la diffusion à') !!} + - {!! Form::number('coupon_limitquantity', null, ['class'=>'small']) !!} coupons + {{ __('coupons') }}
- {!! Form::label('coupon_limitperiod', 'Limiter la diffusion à une offre tous les') !!} + - {!! Form::number('coupon_limitperiod', null, ['class'=>'small']) !!} jours + {{ __('jours') }}
-

Validité

+

{{ __('Validité') }}

- {!! Form::label('coupon_mindatediffusion', 'Date de début de diffusion') !!} - {!! Form::date('coupon_mindatediffusion') !!} + +
- {!! Form::label('coupon_maxdatediffusion', 'Date de fin de diffusion') !!} - {!! Form::date('coupon_maxdatediffusion') !!} + +
- {!! Form::label('coupon_validity', 'Durée de validité à l\'impression') !!} + - {!! Form::number('coupon_validity', null, ['class'=>'small', 'required']) !!} jours + {{ __('jours') }}
- {!! Form::label('coupon_maxdatevalidity', 'Date de fin de validité') !!} - {!! Form::date('coupon_maxdatevalidity') !!} + +
-

Calendrier de diffusion

+

{{ __('Calendrier de diffusion') }}

@foreach ($coupon->calendriers()->get() as $calendrier)
@@ -103,12 +107,12 @@
@endforeach
-

Mouvements

+

{{ __('Mouvements') }}

- - + + @foreach ($coupon->mouvements()->get() as $mouvement) @@ -126,136 +130,138 @@
DateQuantité{{ __('Date') }}{{ __('Quantité') }}
-

Vignettes

+

{{ __('Vignettes') }}

- {!! Form::label('coupon_thumbnail1', 'Vignette Desktop active') !!} - {!! Form::file('coupon_thumbnail1', ['class' => 'input-file']) !!} + + @if($coupon->coupon_thumbnail1 != "")
{{ $coupon->coupon_name }}
@endif - {!! Form::input('hidden', 'coupon_thumbnail1_hidden', $coupon->coupon_thumbnail1) !!} +
- {!! Form::label('coupon_thumbnail2', 'Vignette Desktop grise') !!} - {!! Form::file('coupon_thumbnail2', ['class' => 'input-file']) !!} + + @if($coupon->coupon_thumbnail2 != "")
{{ $coupon->coupon_name }}
@endif - {!! Form::input('hidden', 'coupon_thumbnail2_hidden', $coupon->coupon_thumbnail2) !!} +
- {!! Form::label('coupon_thumbnail3', 'Vignette Mobile active') !!} - {!! Form::file('coupon_thumbnail3', ['class' => 'input-file']) !!} + + @if($coupon->coupon_thumbnail3 != "")
{{ $coupon->coupon_name }}
@endif - {!! Form::input('hidden', 'coupon_thumbnail3_hidden', $coupon->coupon_thumbnail3) !!} +
- {!! Form::label('coupon_thumbnail4', 'Vignette Mobile grise') !!} - {!! Form::file('coupon_thumbnail4', ['class' => 'input-file']) !!} + + @if($coupon->coupon_thumbnail4 != "")
{{ $coupon->coupon_name }}
@endif - {!! Form::input('hidden', 'coupon_thumbnail4_hidden', $coupon->coupon_thumbnail4) !!} +
-

Informations pour génération

+

{{ __('Informations pour génération') }}

- {!! Form::label('coupon_treatment_center', 'Centre de traitement *') !!} - {!! Form::select('coupon_treatment_center', ['HighCo', 'Sogec']) !!} + +
- {!! Form::label('coupon_legal_mentions_splitted', 'Activer les mentions internationnales') !!} - {!! Form::checkbox('coupon_legal_mentions_splitted', 1, ($coupon->coupon_legal_mentions_splitted ==1?true:null)) !!} - {!! Form::label('coupon_legal_mentions_splitted', 'Activer') !!} + + coupon_legal_mentions_splitted === 1 ? 'checked' : null) }}> +
- {!! Form::label('coupon_validity_text', 'Texte de validité *') !!} - {!! Form::textarea('coupon_validity_text', null, ['required']) !!} + +
- {!! Form::label('coupon_legal_mentions', 'Mentions légales *') !!} - {!! Form::textarea('coupon_legal_mentions', null, ['required']) !!} + +
- {!! Form::label('coupon_decoration_image', 'Image de décoration *') !!} - 280x260px ou 280x160px si GS1 - Formats : JPG ou PNG + + {{ __('280x260px ou 280x160px si GS1') }} + {{ __('Formats : JPG ou PNG') }}
- - {!! Form::file('coupon_decoration_image', ['class' => 'input-file', 'accept' => '.jpg,.jpeg,.png']) !!} + @if($coupon->coupon_decoration_image != "")
{{ $coupon->coupon_name }}
@endif - {!! Form::input('hidden', 'coupon_decoration_image_hidden', $coupon->coupon_decoration_image) !!} +
- {!! Form::label('coupon_logo_image', 'Logo à afficher *') !!} - 135x70px - Formats : JPG ou PNG + + {{ __('135x70px') }} + {{ __('Formats : JPG ou PNG') }}
- {!! Form::file('coupon_logo_image', ['class' => 'input-file']) !!} + @if($coupon->coupon_logo_image != "")
{{ $coupon->coupon_name }}
@endif - {!! Form::input('hidden', 'coupon_logo_image_hidden', $coupon->coupon_logo_image) !!} +
- {!! Form::label('coupon_rcs', 'RCS du site *') !!} - {!! Form::text('coupon_rcs', null, ['required']) !!} + +
- {!! Form::label('coupon_site_contact', 'Contact mail *') !!} - {!! Form::text('coupon_site_contact', null, ['required']) !!} + +
- {!! Form::label('coupon_gs1code', 'Image du code barre GS1 *') !!} - Formats : JPG + + {{ __('Formats : JPG') }}
- {!! Form::file('coupon_gs1code', ['class' => 'input-file']) !!} + @if($coupon->coupon_gs1code != "")
{{ $coupon->coupon_name }}
- {!! Form::input('hidden', 'coupon_gs1code_image_hidden', $coupon->coupon_gs1code, array('id'=>'coupon_gs1code_image_hidden')) !!} + @endif - +
- {!! Form::label('coupon_published', 'Publié ?') !!} - {!! Form::checkbox('coupon_published', 1, ($coupon->coupon_published ==1?true:null), array('id'=>'coupon_published')) !!} - {!! Form::label('coupon_published', 'Activer') !!} + + coupon_published === 1 ? 'checked' : null) }}> +
-

Bon généré :

+

{{ __('Bon généré') }} :

@if($coupon->coupon_image != "")
@@ -263,12 +269,13 @@
@endif
- {!! Form::hidden('site_id', session()->get('site')->id) !!} + +
- {!! Form::submit('Mettre à jour') !!} +
- - {!! Form::close() !!} + +
@endsection diff --git a/resources/views/coupon/index.blade.php b/resources/views/coupon/index.blade.php index 1f7ea7e..1469dd2 100644 --- a/resources/views/coupon/index.blade.php +++ b/resources/views/coupon/index.blade.php @@ -1,7 +1,14 @@ @extends('layouts.main') @section('content') -

Coupons Ajouter

+

+ + {{ __('Coupons') }} + + + {{ __('Ajouter') }} + +

@@ -38,9 +45,10 @@ @endforeach
- +
-{!! Form::open(['id' => 'delete-hidden']) !!} +
+ @csrf @method('DELETE') -{!! Form::close() !!} +
@endsection diff --git a/resources/views/export/index.blade.php b/resources/views/export/index.blade.php deleted file mode 100644 index 651ea18..0000000 --- a/resources/views/export/index.blade.php +++ /dev/null @@ -1,70 +0,0 @@ -@extends('layouts.main') - -@section('content') -

Export des données coupons

-
-

Période :

- - - - Exporter les données -
-@foreach ($sites as $site) - -

{{ $site->site_nom }} ({{ $site->site_id }})

- @if (isset($site->coupons) && $site->coupons->count()>0) - @foreach ($site->coupons as $coupon) -
- - -
- @endforeach - @endif - -@endforeach -
- Exporter les données - -
- -@endsection - -@section('scripts') - -@endsection \ No newline at end of file diff --git a/resources/views/export/template.blade.php b/resources/views/export/template.blade.php deleted file mode 100644 index bd02a21..0000000 --- a/resources/views/export/template.blade.php +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - - - - -
-

MesBR.eu

-

{{ $coupon->coupon_name }}

-

Diffusions du {{ date('d/m/Y', strtotime($startdate)) }} au {{ date('d/m/Y', strtotime($enddate)) }}

- -

Détail du coupon

- - - - - - - - - - - - - - - @if($coupon->coupon_mindatediffusion != null) - - @else - - @endif - @if($coupon->coupon_maxdatediffusion != null) - - @else - - @endif - -
NomCodeQuantité totaleQté totale diffuséeDate de début de diffusionDate de fin de diffusion
{{ $coupon->coupon_name }}{{ $coupon->coupon_code }}{{ $coupon->couponQuantity }}{{ $coupon->couponFullPrinted }}{{ date('d/m/Y', strtotime($coupon->coupon_mindatediffusion)) }}n/c{{ date('d/m/Y', strtotime($coupon->coupon_maxdatediffusion)) }}n/c
-

Graphique de diffusion sur la période du {{ date('d/m/Y', strtotime($startdate)) }} au {{ date('d/m/Y', strtotime($enddate)) }}

-

Nombre de coupons diffusés : {{ $coupon->couponPrinted }}

- -
- - diff --git a/resources/views/fo/basket/show.blade.php b/resources/views/fo/basket/show.blade.php new file mode 100644 index 0000000..d83cdc0 --- /dev/null +++ b/resources/views/fo/basket/show.blade.php @@ -0,0 +1,49 @@ + + + + + {{ $basket->campagne->site->site_libelle }} - {{ __('Bons de Réduction') }} + + + + + +
+
+ {{ $basket->campagne->site->site_libelle }} +
+ +
+
+
Nombre de coupons :
+

{{ $totalQuantity }}

+
+
+ @if($totalQuantity) +
+

Liste des coupons :

+ +
+ +
+ {{ __('Récupérer') }} +
+ @endif + +
+ + + + diff --git a/resources/views/layouts/header.blade.php b/resources/views/layouts/header.blade.php index 44f9e40..3aa8336 100644 --- a/resources/views/layouts/header.blade.php +++ b/resources/views/layouts/header.blade.php @@ -1,13 +1,13 @@
-

Mes BR

- +
Logo Marque @@ -16,15 +16,15 @@
    @foreach (session()->get('marques') as $marque)
  • - {!! Form::open(['route' => 'change_marque', 'class' => 'marques']) !!} - +
    + @csrf - - {!! Form::close() !!} + +
  • @endforeach
- +
diff --git a/resources/views/layouts/menu.blade.php b/resources/views/layouts/menu.blade.php index ebe0389..5568075 100644 --- a/resources/views/layouts/menu.blade.php +++ b/resources/views/layouts/menu.blade.php @@ -1,16 +1,17 @@ +@php +$authUserRole = Auth::user()->roles; +@endphp