Advertisement
Guest User

refactor.php

a guest
Apr 7th, 2016
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 7.29 KB | None | 0 0
  1. <?php
  2.  
  3. public function findAvailablePlan($user, $planId, $bypassRestrictions=false)
  4. {
  5.     if ($bypassRestrictions) {
  6.         return $plan = Plan::with('groups')->find(planId);
  7.     }
  8.  
  9.     return Plan::with(array('groups' => function($query) use($user) {
  10.         $today = Carbon::now();
  11.         $age = (int)$user->birthday->diffInYears($today) * 12;
  12.         $birthday = $user->birthday;
  13.         # On s'assure que le cours n'est pas fini et qu'il reste de la place
  14.        $query->where('end_date', '>', $today);
  15.         $query->where('nbr_places_remaining', '>', 0)
  16.             ->orWhereNull('nbr_places_remaining');
  17.         # On vérifie le sexe
  18.        $query->where(function($query) use ($user) {
  19.             $query->where('restriction_sex', '=', 'A')
  20.                 ->orWhere('restriction_sex', '=', $user->sex);
  21.         });
  22.         # On vérifie l'age.
  23.        $query->where(function($query) use ($age, $birthday) {
  24.             $query->where(function($query) use ($age) {
  25.                 $query->whereNull('validate_age_on');
  26.                 $query->where(function($query) use ($age) {
  27.                     $query->where('restriction_age_min', '<=', $age)
  28.                         ->orWhereNull('restriction_age_min');
  29.                 });
  30.                 $query->where(function($query) use ($age) {
  31.                     $query->where('restriction_age_max', '>=', $age)
  32.                         ->orWhereNull('restriction_age_max');
  33.                 });
  34.             });
  35.             $query->orWhere(function($query) use ($birthday) {
  36.                 $query->whereNotNull('validate_age_on');
  37.                 $query->where(function($query) use ($birthday) {
  38.                     $query->where("restriction_age_min",  "<=",  DB::raw("EXTRACT(YEAR FROM AGE(validate_age_on, '{$birthday->format('Y-m-d')}')) * 12"))
  39.                         ->orWhereNull('restriction_age_min');
  40.                 });
  41.                 $query->where(function($query) use ($birthday) {
  42.                     $query->where("restriction_age_max",  ">=", DB::raw("EXTRACT(YEAR FROM AGE(validate_age_on, '{$birthday->format('Y-m-d')}')) * 12"))
  43.                         ->orWhereNull('restriction_age_max');
  44.                 });
  45.             });
  46.         });
  47.     }))->find($planId);
  48. }
  49.  
  50. public static function registerUser($userId, $planId, $quantity = 1,$billingItemId = NULL, $cartId = NULL, $byPassRestrictions = FALSE, $createdBy = NULL) {
  51.     try {
  52.  
  53.         $user = User::find($userId); /** @var \App\Models\User $user */
  54.  
  55.         if (!user) {
  56.             throw new UserNotFoundException();
  57.         }
  58.  
  59.         $plan = $findAvailablePlan($user, $planId, $byPassRestrictions);
  60.  
  61.         if (!$plan) {
  62.             throw new PlanNotFoundException();
  63.         }
  64.  
  65.         if (count($plan->groups) < 1) {
  66.             throw new NoGroupsFoundException();
  67.         }
  68.  
  69.         if($plan->type_plan == "PASS") { # On crée une entrée dans la table Pass en fct de la quantité
  70.            $pass = new Pass;
  71.             $pass->user()->associate($user);
  72.             $pass->plan()->associate($plan);
  73.             $pass->initial_quantity     = $plan->quantity * $quantity;
  74.             $pass->remaining_quantity   = $plan->quantity * $quantity;
  75.             $pass->expiration_date      = $plan->pass_exp_date;
  76.             $pass->billing_item_id      = $billingItemId;
  77.             $pass->save();
  78.         }elseif($plan->type_plan == "INTERVAL" || $plan->type_plan == "SESSION") { # Enregistrement standard
  79.            foreach($plan->groups as $group) {
  80.  
  81.  
  82.                 if($plan->type_plan == "SESSION") {
  83.                     $sessions = $group->sessions()->get();
  84.                 }else {
  85.                     # Plan par interval, on va chercher les plages où l'utilisateur a le droit de s'inscrire
  86.                    $sessions = $group->sessions()->whereBetween('start_date', [$plan->restriction_start_date, $plan->restriction_end_date])->get();
  87.                 }
  88.                 if(count($sessions) > 0) {
  89.                     $registrations = [];
  90.  
  91.                     foreach($sessions as $session) {
  92.                         array_push($registrations, array(
  93.                             'user_id'           => $userId,
  94.                             'created_by_user_id'=> $createdBy != NULL ? $createdBy: $user->id,
  95.                             'session_id'        => $session->id,
  96.                             'type_status_id'    => 'OK',
  97.                             'created_at'        => Carbon::now(),
  98.                             'updated_at'        => Carbon::now(),
  99.                             'billing_item_id'   => $billingItemId,
  100.                             'cart_id'           => $cartId,
  101.                         ));
  102.  
  103.                     }
  104.  
  105.                     # On fait de l'insertion de masse pour pas faire 58 INSERT de suite
  106.                    Registration::insert($registrations);
  107.                 }else {
  108.                     $errorCode  = "NO_SESSION";
  109.                     $errorDescription = "Aucune session ne peut être inscrite";
  110.                 }
  111.  
  112.                 if(isset($group->nbr_places))
  113.                 {
  114.                     $group->nbr_places_remaining--;
  115.                     $group->save();
  116.  
  117.                     # On met à jour les places dans les sessions que l'utilisateur a été inscrit
  118.                    if($plan->type_plan == "SESSION") {
  119.                         DB::update('UPDATE "session" SET nbr_places_remaining = nbr_places_remaining -1
  120.                            WHERE group_id = :groupId AND start_date >= now()' , ['groupId' => $group->id]) ;
  121.                     }else {
  122.                         DB::update('UPDATE "session" SET nbr_places_remaining = nbr_places_remaining -1
  123.                            WHERE group_id = :groupId AND start_date >= now() AND start_date BETWEEN CAST(COALESCE(:startDate, \'1901-01-01\') AS TIMESTAMP) AND CAST(COALESCE(:endDate, \'2099-12-12\') AS TIMESTAMP)'
  124.                             , ['groupId' => $group->id, 'startDate' => $plan->restriction_start_date, 'endDate' => $plan->restriction_end_date ]) ;
  125.                     }
  126.                 }
  127.  
  128.                 # On crée le group_registration, que l'utilisateur ce soit inscrit à une session ou pas. C'est important dans le cas où les horaires ne sont pas décidés
  129.                $groupRegistration = new GroupRegistration;
  130.                 $groupRegistration->group_id = $group->id;
  131.                 $groupRegistration->user_id = $userId;
  132.                 $groupRegistration->billing_item_id = $billingItemId;
  133.                 if($plan->type_plan == "SESSION") {
  134.                     $groupRegistration->start_date  = $group->start_date;
  135.                     $groupRegistration->end_date    = $group->end_date;
  136.                 }else {
  137.                     $groupRegistration->start_date  = $plan->restriction_start_date;
  138.                     $groupRegistration->end_date    = $plan->restriction_end_date;
  139.                 }
  140.                 $groupRegistration->save();
  141.             }
  142.         }
  143.         return TRUE;
  144.     } catch (UserNotFoundException $noUserException) {
  145.         //TODO PaymentLog ...
  146.         return false;
  147.     } catch (PlanNotFoundException $noPlanException) {
  148.         //TODO PaymentLog ...
  149.         return false;
  150.     } catch (NoGroupsFoundException $noGroupsException) {
  151.         //TODO PaymentLog ...
  152.         return false;
  153.     }
  154. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement