/**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     $newcomers = Newcomer::all();
     foreach ($newcomers as $newcomer) {
         echo 'php app/console  etu:users:create --login "adm' . $newcomer->id . '" --password="******" --firstName "' . addslashes($newcomer->first_name) . '" --lastName "' . addslashes($newcomer->last_name) . '" --email "' . $newcomer->email . '" --branch "' . $newcomer->level . '"' . "\n";
     }
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     $file = $this->argument('file');
     if (!file_exists($file) || !is_file($file)) {
         $this->error('Please provide a valid file.');
     }
     if ($handle = fopen($file, 'r')) {
         while (($data = fgetcsv($handle, 0, ';')) !== false) {
             // If the "level" column is present, use it instead of the
             // "level" option.
             $level = $this->option('level');
             if (count($data) === 7) {
                 $level = $data[6];
             } elseif ($this->option('level') === null) {
                 $this->error('The file does not include the level of the newcomer, please provide it via the "level" flag.');
                 return;
             }
             // See the class description for file format.
             $attributes = ['first_name' => $data[2], 'last_name' => $data[1], 'password' => Str::random(6), 'sex' => strpos($data[0], 'M') !== false ? 'M' : 'F', 'email' => $data[5], 'phone' => $data[4], 'level' => $level, 'birth' => new DateTime($data[3])];
             $newcomer = Newcomer::create($attributes);
             if ($newcomer->save() === false) {
                 $this->error('Error while adding ' . $newcomer->first_name . ' ' . $newcomer->last_name);
             }
         }
     }
 }
 /**
  * Authenticate the newcomer
  *
  * @return Response
  */
 public function loginSubmit()
 {
     $newcomer = Newcomer::where('login', Request::get('login'))->get()->first();
     if ($newcomer) {
         $password = Crypt::decrypt($newcomer->password);
         if ($password == Request::get('password')) {
             Auth::login($newcomer, true);
             return Redirect::route('newcomer.home')->withSuccess('Vous êtes maintenant connecté.');
         }
     }
     return $this->error('Identifiant ou mot de passe incorrect. Contactez integration@utt.fr si vous n\'arrivez pas à vous connecter.');
 }
Beispiel #4
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     $newcomers = Newcomer::where('team_id', null)->orderByRaw(' RAND()')->get();
     if ($newcomers->count() == 0) {
         die($this->info('All the newcomers have a team.'));
     }
     $teams = Team::all();
     $count = floor($newcomers->count() / $teams->count());
     foreach ($teams as $team) {
         for ($i = 0; $i < $count; $i++) {
             $newcomer = $newcomers->pop();
             $newcomer->team_id = $team->id;
             if (!$newcomer->save()) {
                 die($this->error('Unable to add #' . $newcomer->id . ' to a team.'));
             }
         }
     }
     $this->info('Newcomers were added to their respective teams!');
 }
 /**
  *
  * @return Response
  */
 public function list()
 {
     // Find students
     $students = Student::select([DB::raw('student_id AS id'), 'first_name', 'last_name', 'phone', DB::raw('1 AS student'), DB::raw('1 AS parent_authorization'), 'wei_payment', 'sandwich_payment', 'guarantee_payment', DB::raw('(ce AND team_accepted) AS ce'), 'volunteer', 'orga', 'wei_validated'])->where('wei', 1)->with('weiPayment')->with('sandwichPayment')->with('guaranteePayment');
     // Find newcomers
     $newcomer = Newcomer::select(['id', 'first_name', 'last_name', 'phone', DB::raw('0 AS student'), 'parent_authorization', 'wei_payment', 'sandwich_payment', 'guarantee_payment', DB::raw('0 AS ce'), DB::raw('0 AS volunteer'), DB::raw('0 AS orga'), DB::raw('1 AS wei_validated')])->where('wei', 1)->with('weiPayment')->with('sandwichPayment')->with('guaranteePayment');
     // Union between newcomers and students
     $users = $students->union($newcomer)->orderBy('last_name')->get();
     return View::make('dashboard.wei.list', ['users' => $users]);
 }
 public function addMember($id)
 {
     $team = Team::find($id);
     if ($team) {
         $newcomer = Newcomer::findOrFail((int) Request::input('newcomer'));
         $newcomer->team_id = $id;
         $newcomer->save();
         return $this->success('Le nouveau a été ajouté à l\'équipe !');
     }
     return $this->error('Équipe inconnue !');
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     // Find email that are ready to be started
     $emails = Email::where('started', 0)->whereNotNull('scheduled_for')->where('scheduled_for', '<=', DB::RAW('NOW()'))->get();
     // set every email as started
     foreach ($emails as $email) {
         $email->started = 1;
         $email->save();
     }
     foreach ($emails as $email) {
         // Generate email list
         // To add more email list edit this file and `App/Models/Email.php
         $list = [];
         $students = [];
         $newcomers = [];
         switch ($email->list) {
             case Email::STUPRELISTE:
                 $list['*****@*****.**'] = ['name' => 'STUPRE-liste', 'user' => null];
                 break;
             case Email::VOLUNTEERS:
                 $students = Student::where('volunteer', 1)->get();
                 break;
             case Email::CE_VALIDATED:
                 $students = Student::where('ce', 1)->whereNotNull('team_id')->where('team_accepted', 1)->get();
                 break;
             case Email::REFERRALS_VALIDATED:
                 $students = Student::where('referral', 1)->where('referral_validated', 1)->get();
                 break;
             case Email::REFERRALS_INCOMPLETE:
                 $students = Student::where('referral', 1)->where('referral_validated', 0)->where(function ($query) {
                     $query->where('phone', '')->orWhereNull('phone')->orWhere('email', '')->orWhereNull('email')->orWhere('referral_text', '')->orWhereNull('referral_text');
                 })->get();
                 break;
             case Email::REFERRALS_VALIDATED_BRANCH:
                 $students = Student::where('referral', 1)->where('referral_validated', 1)->where('branch', '<>', 'tc')->get();
                 break;
             case Email::REFERRALS_VALIDATED_TC:
                 $students = Student::where('referral', 1)->where('referral_validated', 1)->where('branch', '=', 'tc')->get();
                 break;
             case Email::ORGA:
                 $students = Student::where('orga', 1)->get();
                 break;
             case Email::ADMIN:
                 $students = Student::where('admin', 100)->get();
                 break;
             case Email::NEWCOMERS_ALL:
                 $newcomers = Newcomer::all();
                 break;
             case Email::NEWCOMERS_ALL_TC:
                 $newcomers = Newcomer::where('branch', 'TC')->get();
                 break;
             case Email::NEWCOMERS_ALL_BRANCH:
                 $newcomers = Newcomer::where('branch', '<>', 'TC')->where('branch', '<>', 'MP')->get();
                 break;
             case Email::NEWCOMERS_ALL_MASTER:
                 $newcomers = Newcomer::where('branch', 'MP')->get();
                 break;
             case Email::NEWCOMERS_FILLED:
                 $newcomers = Newcomer::where('email', '<>', '')->whereNotNull('email')->get();
                 break;
             case Email::NEWCOMERS_FILLED_TC:
                 $newcomers = Newcomer::where('branch', 'TC')->where('email', '<>', '')->whereNotNull('email')->get();
                 break;
             case Email::NEWCOMERS_FILLED_BRANCH:
                 $newcomers = Newcomer::where('branch', '<>', 'TC')->where('branch', '<>', 'MP')->where('email', '<>', '')->whereNotNull('email')->get();
                 break;
             case Email::NEWCOMERS_FILLED_MASTER:
                 $newcomers = Newcomer::where('branch', 'MP')->where('email', '<>', '')->whereNotNull('email')->get();
                 break;
             default:
                 echo 'Error : Unknown email list id';
                 break;
         }
         // Select email to put in the list
         foreach ($students as $student) {
             $list[$student->email] = ['name' => $student->first_name . ' ' . $student->last_name, 'user' => $student];
         }
         foreach ($newcomers as $newcomer) {
             if (!empty($newcomer->email)) {
                 $list[$newcomer->email] = ['name' => $newcomer->first_name . ' ' . $newcomer->last_name, 'user' => $newcomer];
             } elseif (!empty($newcomer->registration_email)) {
                 $list[$newcomer->registration_email] = ['name' => $newcomer->first_name . ' ' . $newcomer->last_name, 'user' => $newcomer];
             }
         }
         // Set count in db
         $email->done = 0;
         $email->total = count($list);
         $email->save();
         // Send emails
         $delay = 0;
         foreach ($list as $dest => $val) {
             $this->currentUser = $val['user'];
             $view = $email->template;
             if ($email->is_plaintext) {
                 $view = preg_replace_callback('/{{([A-Z0-9_]+)}}/i', array($this, 'replaceCallback'), $view);
                 $view = nl2br(e($view));
             } else {
                 $view = preg_replace_callback('/{{([A-Z0-9_]+)}}/i', array($this, 'replaceCallback'), $view);
             }
             $job = new SendEmail($email, $view, $dest, $val['name']);
             $job->delay($delay);
             $this->dispatch($job);
             $delay += 5;
         }
     }
 }
 /**
  * Check if current user is authorized against a group and a facultative action
  * @param  string  $group  Group of user : admin, ce, orga, referral, student
  * @param  string  $action  Specific action for this group of user
  *
  * @return bool
  */
 public function can($group, $action = '')
 {
     if ($group == 'newcomer') {
         // Check if newcomer is identified
         if (!Auth::check() || !Auth::user() instanceof Newcomer) {
             return false;
         }
         // Action verification
         $count = Newcomer::where('wei', 1)->count();
         switch ($action) {
             case 'wei':
                 if (!Auth::user()->wei && ($this->now() <= new \DateTime(Config::get('services.wei.registrationStart')) || $this->now() >= new \DateTime(Config::get('services.wei.registrationEnd')) || $count >= Config::get('services.wei.newcomerMax'))) {
                     return false;
                 }
                 break;
         }
     } else {
         // Login/student verification
         if (in_array($group, ['student', 'admin', 'orga', 'ce', 'referral', 'volunteer', 'moderator']) && !\EtuUTT::isAuth()) {
             return false;
         }
         $student = \EtuUTT::student();
         // Volunteer verification
         if (in_array($group, ['admin', 'orga', 'ce', 'volunteer', 'moderator']) && !\EtuUTT::student()->volunteer) {
             return false;
         }
         // Group verification
         if ($group == 'admin' && !$student->isAdmin()) {
             return false;
         }
         // Group verification
         if ($group == 'moderator' && !$student->isAdmin() && !$student->isModerator()) {
             return false;
         }
         // Group verification
         if ($group == 'referral' && !$student->referral) {
             return false;
         } elseif ($group == 'orga' && !$student->orga) {
             return false;
         } elseif ($group == 'ce' && !$student->ce) {
             return false;
         }
         $teamCount = Team::count();
         // Action verification
         if ($group == 'ce') {
             switch ($action) {
                 case 'inTeam':
                     if (!$student->team) {
                         return false;
                     }
                     break;
                 case 'respo':
                     if (!$student->team || $student->team->respo_id != $student->student_id) {
                         return false;
                     }
                     break;
                 case 'create':
                     if ($this->now() > new \DateTime(Config::get('services.ce.deadline')) || $teamCount >= Config::get('services.ce.maxteam') || $student->team) {
                         return false;
                     }
                     break;
                 case 'edit':
                     if (!$student->team || $student->team->respo_id != $student->student_id || $this->now() > new \DateTime(Config::get('services.ce.deadline'))) {
                         return false;
                     }
                 case 'join':
                     if (!$student->team || $this->now() > new \DateTime(Config::get('services.ce.deadline'))) {
                         return false;
                     }
                     break;
             }
         } elseif ($group == 'student') {
             switch ($action) {
                 case 'referral':
                     if ($this->now() > new \DateTime(Config::get('services.referral.deadline')) || $student->referral_validated || $student->referral) {
                         return false;
                     }
                     break;
                 case 'ce':
                     if ($this->now() > new \DateTime(Config::get('services.ce.deadline')) || $teamCount >= Config::get('services.ce.maxteam') || $student->ce) {
                         return false;
                     }
                     break;
             }
         } elseif ($group == 'referral') {
             switch ($action) {
                 case 'edit':
                     if ($this->now() > new \DateTime(Config::get('services.referral.deadline')) || $student->referral_validated) {
                         return false;
                     }
                     break;
             }
         }
     }
     return true;
 }
Beispiel #9
0
 public static function boot()
 {
     parent::boot();
     Newcomer::creating(function ($newcomer) {
         if (empty($newcomer->password)) {
             $newcomer->password = Crypt::encrypt(self::generatePassword());
         }
         if (empty($newcomer->login)) {
             $login = strtolower(mb_substr(mb_substr(preg_replace("/[^A-Za-z0-9]/", '', $newcomer->first_name), 0, 1) . preg_replace("/[^A-Za-z0-9]/", '', $newcomer->last_name), 0, 8));
             $i = '';
             while (Newcomer::where(['login' => $login . $i])->count()) {
                 if (empty($i)) {
                     $i = 1;
                 }
                 $i++;
             }
             $newcomer->login = $login . $i;
         }
     });
 }
 /**
  * Match all newcomer without a referral to a referral
  *
  * In this algorithme, we first try to match godsons to referral of the same branch
  * Then we try to match them we other branch if there is no space left.
  *
  * Current algorithme as 7 big steps :
  *
  * * STEP 1 : Creation of $counts and $counts2 arrays.
  * $counts is used in steps 2 and 3 to lower the number of queries to DB.
  * And $counts2 is used in steps X, X and X to lower the number of queries to DB.
  * The only difference between theses two arrays is that user are grouped by branch in the first one.
  *
  * * STEP 2 : Calculate the future number of godson for each referrals.
  * We get the number of newcomers and we add one to each referral until reaching their wanted maximum.
  * If there is still newcomers when all maximums are reached, we increment the maximum
  * (with $counts[branch]['+1']) for everyone except thoses with a maximum at 5 (6 godsons is really too much)
  * and we do it again until reaching the $MAXIMUM_OVERFLOW.
  *
  * * STEP 3 : Give godsons to referrals according to the calculated value in
  * precedent step and according to referral and godsons location.
  * For every newcomers, we take all referrals of his branch that have place left
  * and we try to match them by full postal_code and country. If there is a match
  * We associate them, if there is a multiple match, we take a random referral in the list
  * If there is no match we pass this newcomer and try with another one. At the
  * end of the newcomer list, we try agains with the newcomer that we have passed
  * with another matching solution. We do this again with all theses matching solution :
  *   * Full postal code
  *   * French departement code
  *   * French region
  *   * Country
  * If there is still no match, we try to match newcomers with everyone of his branch
  *
  * * STEP 4 : Remove PMOM and Master from left newcomers
  * We will now try to match newcomers with referral from other branches.
  * So we remove PMOM and masters because we don't want to associate them
  * with other branch referrals.
  *
  * * STEP 5 : Calculate the future number of godson for each referrals.
  * It's like the step 2 but we match newcomers with all branches
  * * STEP 6 : Give godsons to referrals according to the calculated value in
  * It's like the step 3 but we match newcomers with all branches
  *
  * * STEP 7 : If everyone has now a referral we save everything to DB
  *
  * Good luck if you want to edit this algo :)
  *
  */
 public static function matchReferrals()
 {
     // Settings you can tweak
     $MAXIMUM_OVERFLOW = 2;
     // Maximum of godson that can be added to a referral original max
     /***********************************************************************
      * STEP 1 : Creation of $counts and $counts2 arrays.
      **********************************************************************/
     // This array is created to minimize the number of query to db
     /*$counts = [
           'TC' => [
               42 => [ // 42 is a referral id
                   'current' => XX, // Current number of godson
                   'future' => XX, // Number of godson that will be associated at the end of the next step
                   'max' => XX, // Maximum number of godson asked by referral
                   '+1' => X, // Number of godson that can be added to `max` because there is not enough referrals. Used in step 2
                   '+1r2' => X, // Number of godson that can be added to `max` because there is not enough referrals. Used in step X
                   'student' => X, // Instance of the referral
               ]
               // referrals are deleted from the array once they reach the maximum
           ]
       ];
       $counts2 = [
           42 => [ // 42 is a referral id
               'current' => XX, // Current number of godson
               'future' => XX, // Number of godson that will be associated at the end of the next step
               'max' => XX, // Maximum number of godson asked by referral
               '+1' => X, // Number of godson that can be added to `max` because there is not enough referrals. Used in step 2
               '+1r2' => X, // Number of godson that can be added to `max` because there is not enough referrals. Used in step X
               'student' => X, // Instance of the referral
           ]
           // referrals are deleted from the array once they reach the maximum
       ];*/
     $counts = [];
     $counts2 = [];
     $referrals = Student::where(['referral' => 1, 'referral_validated' => 1])->get();
     foreach ($referrals as $referral) {
         if (!isset($counts[$referral->branch])) {
             $counts[$referral->branch] = [];
         }
         if ($referral->branch != 'MP') {
             // Remove masters
             $counts[$referral->branch][$referral->student_id] = ['current' => $referral->newcomers->count(), 'future' => $referral->newcomers->count(), 'max' => $referral->referral_max, '+1' => 0, '+1r2' => 0, 'student' => $referral];
         }
         // This array is used when there is no place left in some branches and we put godson from a branch to a referral from another
         if ($referral->branch != 'TC' && $referral->branch != 'MM' && $referral->branch != 'MP') {
             // Remove masters because they cannot have an engineer godson
             $counts2[$referral->student_id] =& $counts[$referral->branch][$referral->student_id];
         }
     }
     /***********************************************************************
      * STEP 2 : Calculate the future number of godson for each referrals
      **********************************************************************/
     foreach ($counts as $branch => $data) {
         // Get number of newcomers for this branch
         $newcomers = Newcomer::where(['branch' => $branch, 'referral_id' => null])->count();
         $currentGoal = 1;
         $overflow = 0;
         // Is true when we decide to add one to each maximum (but still < 5)
         while ($newcomers > 0 && $currentGoal <= 5) {
             // Randomize the foreach
             $student_ids = array_keys($data);
             shuffle($student_ids);
             foreach ($student_ids as $student_id) {
                 $referral_array =& $counts[$branch][$student_id];
                 if ($referral_array['future'] < $currentGoal && $currentGoal <= $referral_array['max'] + $referral_array['+1'] && $newcomers > 0) {
                     $transfer = $currentGoal - $referral_array['future'];
                     $referral_array['future'] += $transfer;
                     $newcomers -= $transfer;
                 }
             }
             $currentGoal++;
             // Check if need to go over maximums and add +1
             if ($currentGoal > 5 && $overflow < $MAXIMUM_OVERFLOW && $newcomers > 0) {
                 foreach ($data as $student_id => $tmp) {
                     if ($counts[$branch][$student_id]['max'] < 5) {
                         $counts[$branch][$student_id]['+1']++;
                     }
                 }
                 $overflow++;
                 $currentGoal = 1;
             }
         }
         // Debugging snippet to see repartition and set the $MAXIMUM_OVERFLOW var
         /*
         $future = 0;
         foreach ($data as $student_id => $tmp) {
             $future += $counts[$branch][$student_id]['future'];
         }
         echo '-----'.$branch.'-----'."\n";
         echo 'Nombre de nouveaux : '.(Newcomer::where(['branch' => $branch])->count())."\n";
         echo 'Nombre de nouveaux qui ont trouvé un parrain : '.$future . " (peut être superieur au nombre de nouveaux si des parrains de cette branche ont parrainé des nouveaux d'autres branches)\n";
         print_r($counts[$branch]);
         */
     }
     /***********************************************************************
      * STEP 3 : Give godsons to referrals according to the calculated value
      * in precedent step and according to referral and godsons location
      **********************************************************************/
     $round = 0;
     $allNewcomers = Newcomer::whereNull('referral_id')->get();
     $newcomers = [];
     foreach ($allNewcomers as $value) {
         $newcomers[] = $value;
     }
     $branchNotFound = [];
     // Newcomers in this array will have referral from other branches
     while (count($newcomers) > 0) {
         foreach ($newcomers as $key => $newcomer) {
             // Create array of users that are matching with the newcomer
             $matchingArray = [];
             if (isset($counts[$newcomer->branch])) {
                 foreach ($counts[$newcomer->branch] as $student_id => $array) {
                     if ($array['current'] >= $array['future']) {
                         unset($counts[$newcomer->branch][$student_id]);
                     } else {
                         switch ($round) {
                             case 0:
                                 // Match if newcomer and referral have same postal_code and country
                                 if ($newcomer->postal_code == $array['student']->postal_code && strtolower($newcomer->country) == strtolower($array['student']->country)) {
                                     $matchingArray[] = $student_id;
                                 }
                                 break;
                             case 1:
                                 // Match if newcomer and referral have same french departement (postal_code/1000) and country
                                 if (floor($newcomer->postal_code / 1000) == floor($array['student']->postal_code / 1000) && strtolower($newcomer->country) == strtolower($array['student']->country)) {
                                     $matchingArray[] = $student_id;
                                 }
                                 break;
                             case 2:
                                 // Match if newcomer and referral have same french region (region[postal_code/1000]) and country
                                 if (isset(self::REGION[floor($newcomer->postal_code / 1000)]) && isset(self::REGION[floor($array['student']->postal_code / 1000)]) && self::REGION[floor($newcomer->postal_code / 1000)] == self::REGION[floor($array['student']->postal_code / 1000)] && strtolower($newcomer->country) == strtolower($array['student']->country)) {
                                     $matchingArray[] = $student_id;
                                 }
                                 break;
                             case 3:
                                 // Match if newcomer and referral have same country
                                 if (trim(strtolower($newcomer->country)) == trim(strtolower($array['student']->country))) {
                                     $matchingArray[] = $student_id;
                                 }
                                 break;
                             default:
                                 // Match if newcomer and referral have nothing in common
                                 $matchingArray[] = $student_id;
                         }
                     }
                 }
                 // Take a random student in the matched referral list
                 if (count($matchingArray)) {
                     $student_id = $matchingArray[array_rand($matchingArray)];
                     $newcomer->referral_id = $student_id;
                     $counts[$newcomer->branch][$student_id]['current']++;
                     // Debugging snippet
                     /*
                     $student = $counts[$newcomer->branch][$student_id]['student'];
                     echo $round.' '. $newcomer->first_name . ' '.$newcomer->last_name.' ('.$newcomer->branch.'|'.$newcomer->postal_code.','.$newcomer->country.') => ' .$student->first_name . ' '.$student->last_name.' ('.$student->branch.'|'.$student->postal_code.','.$student->country.')'
                         .' '.$counts[$newcomer->branch][$student_id]['current'].'/'.$counts[$newcomer->branch][$student_id]['future']."\n";
                     */
                     unset($newcomers[$key]);
                 } elseif ($round >= 4) {
                     $branchNotFound[] = $newcomers[$key];
                     unset($newcomers[$key]);
                 }
             } else {
                 $branchNotFound[] = $newcomers[$key];
                 unset($newcomers[$key]);
             }
         }
         $round++;
     }
     /***********************************************************************
      * STEP 4 : Remove PMOM and Master from left newcomers
      **********************************************************************/
     foreach ($branchNotFound as $key => $value) {
         if ($value->branch == 'MM' || $value->branch == 'MP') {
             unset($branchNotFound[$key]);
         }
     }
     /***********************************************************************
      * STEP 5 : Calculate the future number of godson for each referrals
      **********************************************************************/
     $newcomers = count($branchNotFound);
     $currentGoal = 1;
     $overflow = 0;
     // Is true when we decide to add one to each maximum (but still <= 5)
     while ($newcomers > 0 && $currentGoal <= 5) {
         // Randomize
         $student_ids = array_keys($counts2);
         shuffle($student_ids);
         foreach ($student_ids as $student_id) {
             // unset($counts2[$student_id]['student']); // Uncomment this to debug
             $referral_array =& $counts2[$student_id];
             if ($referral_array['future'] < $currentGoal && $currentGoal <= $referral_array['max'] + $referral_array['+1r2'] && $newcomers > 0) {
                 $transfer = $currentGoal - $referral_array['future'];
                 $referral_array['future'] += $transfer;
                 $newcomers -= $transfer;
             }
         }
         $currentGoal++;
         // Check if need to go over maximums and add +1
         if ($currentGoal > 5 && $overflow < $MAXIMUM_OVERFLOW && $newcomers > 0) {
             foreach ($counts2 as $student_id => $tmp) {
                 if ($counts2[$student_id]['max'] < 5) {
                     $counts2[$student_id]['+1r2']++;
                 }
             }
             $overflow++;
             $currentGoal = 1;
         }
     }
     /***********************************************************************
      * STEP 6 : Give godsons to referrals according to the calculated value
      * in precedent step and according to referral and godsons location
      **********************************************************************/
     $round = 0;
     $newcomers = $branchNotFound;
     while (count($newcomers) > 0) {
         foreach ($newcomers as $key => $newcomer) {
             // Create array of users that are matching with the newcomer
             $matchingArray = [];
             if (isset($counts2)) {
                 foreach ($counts2 as $student_id => $array) {
                     if ($array['current'] >= $array['future']) {
                         unset($counts2[$student_id]);
                     } else {
                         switch ($round) {
                             case 0:
                                 // Match if newcomer and referral have same postal_code and country
                                 if ($newcomer->postal_code == $array['student']->postal_code && strtolower($newcomer->country) == strtolower($array['student']->country)) {
                                     $matchingArray[] = $student_id;
                                 }
                                 break;
                             case 1:
                                 // Match if newcomer and referral have same french departement (postal_code/1000) and country
                                 if (floor($newcomer->postal_code / 1000) == floor($array['student']->postal_code / 1000) && strtolower($newcomer->country) == strtolower($array['student']->country)) {
                                     $matchingArray[] = $student_id;
                                 }
                                 break;
                             case 2:
                                 // Match if newcomer and referral have same french region (region[postal_code/1000]) and country
                                 if (isset(self::REGION[floor($newcomer->postal_code / 1000)]) && isset(self::REGION[floor($array['student']->postal_code / 1000)]) && self::REGION[floor($newcomer->postal_code / 1000)] == self::REGION[floor($array['student']->postal_code / 1000)] && strtolower($newcomer->country) == strtolower($array['student']->country)) {
                                     $matchingArray[] = $student_id;
                                 }
                                 break;
                             case 3:
                                 // Match if newcomer and referral have same country
                                 if (trim(strtolower($newcomer->country)) == trim(strtolower($array['student']->country))) {
                                     $matchingArray[] = $student_id;
                                 }
                                 break;
                             default:
                                 // Match if newcomer and referral have nothing in common
                                 $matchingArray[] = $student_id;
                         }
                     }
                 }
                 // Take a random student in the matched referral list
                 if (count($matchingArray)) {
                     $student_id = $matchingArray[array_rand($matchingArray)];
                     $newcomer->referral_id = $student_id;
                     $counts2[$student_id]['current']++;
                     // Debugging code
                     /*
                     $student = $counts2[$student_id]['student'];
                     echo $round.' '. $newcomer->first_name . ' '.$newcomer->last_name.' ('.$newcomer->branch.'|'.$newcomer->postal_code.','.$newcomer->country.') => ' .$student->first_name . ' '.$student->last_name.' ('.$student->branch.'|'.$student->postal_code.','.$student->country.')'
                         .' '.$counts2[$student_id]['current'].'/'.$counts2[$student_id]['future']."\n";
                     */
                     unset($newcomers[$key]);
                 } elseif ($round >= 4) {
                     // Warning not all student have referral !!
                     $branchNotFound[] = $newcomers[$key];
                     unset($newcomers[$key]);
                 }
             } else {
                 // Warning not all student have referral !!
                 $branchNotFound[] = $newcomers[$key];
                 unset($newcomers[$key]);
             }
         }
         $round++;
     }
     /***********************************************************************
      * Debugging snippet that synthetise referral matching
      **********************************************************************/
     /*
     $referralList = [];
     foreach ($allNewcomers as $newcomer) {
         $referralList[$newcomer->referral_id][] = $newcomer;
     }
     foreach ($referralList as $referral_id => $array) {
         if (isset($array[0]->referral)) {
             echo '<h3>'.$array[0]->referral->first_name.' '.$array[0]->referral->last_name.'</h3>';
     
             echo '<p>max: '.$array[0]->referral->referral_max.', '.$array[0]->referral->branch.$array[0]->referral->level.', '.$array[0]->referral->postal_code.', '.$array[0]->referral->country.'</p><ul>';
         } else {
             echo '<h3>Aucun</h3><ul>';
         }
         foreach ($array as $godson) {
             echo '<li>'.$godson->first_name.' '.$godson->last_name.' : '.$godson->branch.', '.$godson->postal_code.', '.$godson->country.', ';
             if (isset($godson->referral)) {
                 if ($godson->postal_code == $godson->referral->postal_code
                             && strtolower($godson->country) == strtolower($godson->referral->country)) {
                     echo 'CP';
                 } elseif (floor($godson->postal_code/1000) == floor($godson->referral->postal_code/1000)
                             && strtolower($godson->country) == strtolower($godson->referral->country)) {
                     echo 'departement';
                 } elseif (isset(self::REGION[floor($godson->postal_code/1000)]) && isset(self::REGION[floor($godson->referral->postal_code/1000)])
                             && self::REGION[floor($godson->postal_code/1000)] == self::REGION[floor($godson->referral->postal_code/1000)]
                             && strtolower($godson->country) == strtolower($godson->referral->country)) {
                     echo 'region';
                 } elseif (trim(strtolower($godson->country)) == trim(strtolower($godson->referral->country))) {
                     echo 'pays';
                 }
             }
             echo '</li>';
         }
         echo '</ul>';
     }
     */
     /***********************************************************************
      * STEP 7 : If everyone has now a referral we save everything to DB
      **********************************************************************/
     // If we cannot match everyone, we cancel everything
     if (count($newcomers) > 0) {
         return false;
     }
     // Save it to DB
     foreach ($allNewcomers as $newcomer) {
         $newcomer->save();
     }
     return true;
 }
 /**
  * Display one or multiple newcomer's letter
  *
  * @param  int $id
  * @param  int $limit
  * @param  string $category
  * @return Response
  */
 public function letter($id, $limit = null, $category = null)
 {
     if ($limit === null) {
         $newcomers = [Newcomer::findOrFail($id)];
     } elseif ($category != null) {
         $newcomers = Newcomer::where('branch', '=', strtoupper($category))->offset($id)->limit($limit)->get();
     } else {
         $newcomers = Newcomer::offset($id)->limit($limit)->get();
     }
     // Parse phone number and save it to db
     foreach ($newcomers as $newcomer) {
         if (isset($newcomer->referral->phone)) {
             if (preg_match('/^(?:0([0-9])|(?:00|\\+)33[\\. -]?([0-9]))[\\. -]?([0-9]{2})[\\. -]?([0-9]{2})[\\. -]?([0-9]{2})[\\. -]?([0-9]{2})[\\. -]?$/', $newcomer->referral->phone, $m) && $newcomer->referral->phone != '0' . $m[1] . $m[2] . '.' . $m[3] . '.' . $m[4] . '.' . $m[5] . '.' . $m[6]) {
                 $referral = $newcomer->referral;
                 $referral->phone = '0' . $m[1] . $m[2] . '.' . $m[3] . '.' . $m[4] . '.' . $m[5] . '.' . $m[6];
                 $referral->save();
             }
         }
     }
     return View::make('dashboard.newcomers.letter', ['newcomers' => $newcomers, 'i' => $id, 'count' => Newcomer::count()]);
 }
 /**
  * Export the newcomers.
  *
  * @return string
  */
 public function getExportNewcomers()
 {
     $newcomers = Newcomer::select([\DB::raw('newcomers.first_name'), \DB::raw('newcomers.last_name'), \DB::raw('newcomers.branch')])->orderBy('last_name')->leftjoin('students as s', 's.student_id', '=', 'newcomers.referral_id')->addSelect([\DB::raw('s.first_name as referral_first_name'), \DB::raw('s.last_name as referral_last_name'), \DB::raw('s.email as referral_email'), \DB::raw('s.phone as referral_phone')])->get();
     return Excel::create('Newcomers', function ($file) use($newcomers) {
         $file->sheet('', function ($sheet) use($newcomers) {
             $sheet->fromArray($newcomers);
         });
     })->export('csv');
 }
 public function prematchSubmit()
 {
     $input = Request::only('referralCountries', 'newcomerCountries', 'referralBranches', 'newcomerBranches');
     // Referral Countries
     foreach ($input['referralCountries'] as $key => $value) {
         if ($key === 0) {
             $key = '';
         }
         Student::where('country', $key)->update(['country' => $value]);
     }
     // UpdateNewcomersTable Countries
     foreach ($input['newcomerCountries'] as $key => $value) {
         if ($key === 0) {
             $key = '';
         }
         Newcomer::where('country', $key)->update(['country' => $value]);
     }
     // Referral branches
     foreach ($input['referralBranches'] as $key => $value) {
         if ($key === 0) {
             $key = '';
         }
         Student::where('branch', $key)->update(['branch' => $value]);
     }
     // UpdateNewcomersTable branches
     foreach ($input['newcomerBranches'] as $key => $value) {
         if ($key === 0) {
             $key = '';
         }
         Newcomer::where('branch', $key)->update(['branch' => $value]);
     }
     // Redirect to referral assignation
     return redirect(route('dashboard.referrals.match'));
 }