public function getPresenterPromoFullStatus()
 {
     if ($this->isUserLoggedIn() && !empty($this->presenterId)) {
         $year_month = date("Y-m");
         $commission_data = CommissionAPI::call("presenter/{$this->presenterId}/{$year_month}/stats");
         $current_month_prs = 0;
         $result = $this->TripSpring2014->getPresenterPromoStatusFull($this->presenterId, $current_month_prs);
         $this->sendSuccess($result);
     } else {
         $this->sendError(404, "User not found");
     }
 }
 public function main()
 {
     $startTime = time();
     $salesPeriods = $this->getSalesPeriods();
     foreach ($salesPeriods as $salesPeriod) {
         $subStart = time();
         $this->out($salesPeriod);
         $statuses = CommissionAPI::call("presenter/{$salesPeriod}/statuses");
         foreach ($statuses as $presenterId => $color) {
             $this->updatePresenterStatus($presenterId, $salesPeriod, strtolower($color));
         }
         $subEnd = time();
         $this->out("{$salesPeriod} Completed in " . ($subEnd - $subStart) . " seconds");
     }
     $endTime = time();
     $this->out("Completed in " . ($endTime - $startTime) . " seconds");
 }
 /**
  * Calculates the final point total for a month for this
  * promotion for all presenters
  *
  * @param string $year_month Must be of format yyyy-mm
  * @return bool
  */
 public function finalize($year_month = NULL)
 {
     ini_set("max_execution_time", 900);
     ini_set("memory_limit", "1024M");
     ini_set("max_input_time", 900);
     $this->RoyaltiesEarned = ClassRegistry::init('RoyaltiesEarned');
     $this->PresenterPoints = ClassRegistry::init('PresenterPoints');
     $this->PresenterType = ClassRegistry::init('PresenterType');
     //gets all presenters
     //$test = file_get_contents('http://www.youniqueproducts.com:8000/presenter/1/2014-01/downline');
     //$commission_data1 = json_decode($test);
     $commission_data = CommissionAPI::call("presenter/1/{$year_month}/downline");
     foreach ($commission_data->children as $value) {
         $this->_calculate($value, $year_month);
     }
     return TRUE;
 }
 public function main()
 {
     $yearmonth = date("Y-m", strtotime("last month"));
     $statuses = CommissionAPI::call("presenter/{$yearmonth}/statuses");
     foreach ($statuses as $presenterId => $color) {
         $this->PresenterType->updateStatus($presenterId, $yearmonth, $color);
         // Let the commission engine know this happened . . .
         // However, since there is not real action to be taken on a white, there is no need to report it.
         if (strtolower($color) != 'white') {
             try {
                 $result = CommissionAPI::write("presenter/" . $presenterId . "/recognizedstatus", array("status" => strtolower($color), "date" => date("c"), "timestamp" => date("c")));
             } catch (Exception $e) {
                 $this->out("Error updating [{$presenterId}] to status [{$color}] based on [{$yearmonth}].");
             }
         }
     }
 }
 public function main()
 {
     $db = ConnectionManager::getDataSource('default');
     $result = $db->query("Select date_sub(now(), interval 2 second) as timestamp");
     $twoSecondsAgo = $result[0][0]["timestamp"];
     $since = $this->SystemSetting->getSystemSetting("commission_load", "0000-00-00");
     $newPresenters = $this->Presenter->findChanges($twoSecondsAgo, $since);
     foreach ($newPresenters as $presenter) {
         $eligibleRaceToStart = $presenter['Presenter']['default_locale'] == 'es_US';
         if ($eligibleRaceToStart) {
             $result = $this->AdminUserAudit->query("Select count(*) as changes\r\n                    from admin_user_audits\r\n                    Where reference_id = " . (int) $presenter['Presenter']['id'] . " and reference_name = 'presenters.default_locale' and notes = 'Admin3 sponsor default locale change' ");
             if ($result[0][0]['changes'] == 0) {
                 $eligibleRaceToStart = true;
             } else {
                 $eligibleRaceToStart = false;
             }
         }
         //getTypeId requires presenter_sequence_id
         $presenterRank = $this->PresenterType->getRecognizedStatus($presenter['Presenter']['id']);
         if ($presenterRank['id'] >= 8) {
             //To get on the Wall of Influence in USD, earn 83333.33 in one month. Alter for other markets
             $goalForWall = $this->Market->getPayPegRate($presenter['Presenter']['market_id']) * 83333.33;
             $wallInfluence = $this->RoyaltiesEarned->isWallInfluence($presenter['Presenter']['id'], $goalForWall);
         } else {
             $wallInfluence = false;
         }
         $result = CommissionAPI::write("presenter/" . $presenter['Presenter']['id'], array("parentId" => $presenter['Presenter']['id'] == 1 ? 0 : $presenter['Presenter']['sponsor_id'], "date" => date("c", strtotime($presenter['Presenter']['consent_to_agreements'])), "name" => $presenter['User']['first_name'] . " " . $presenter['User']['last_name'], "presenter_id" => $presenter['Presenter']['presenter_sequence_id'], "image" => $presenter['User']['largeimage'], "terminated_date" => $presenter['Presenter']['terminated_date'], "timestamp" => date("c", strtotime($presenter['Presenter']['_auditdate'])), "cat1" => $eligibleRaceToStart ? $presenter['Presenter']['default_locale'] : '', "wallInfluence" => $wallInfluence));
     }
     $newOrders = $this->Order->findChanges($twoSecondsAgo, $since);
     foreach ($newOrders as $order) {
         $presenterId = $order['Order']['presenter_id'];
         if ($presenterId == 0) {
             continue;
         }
         $status = "rejected";
         //if(in_array($order['Order']['order_status_id'], array(3,4,5,8))) { MIKEFIX
         if ($this->Order->isCommissionable($order['Order']['order_status_id'])) {
             $status = "accepted";
         }
         $result = CommissionAPI::write("order/" . $order['Order']['id'], array("parentId" => $presenterId, "state" => $status, "date" => date("c", strtotime($order['Order']['date_completed'])), "retail" => Money::fromString($order['Order']['commissionable_total'])->intVal(), "wholesale" => Money::fromString($order['Order']['commissionable_total'])->times(0.75)->intVal(), "timestamp" => date("c", strtotime($order['Order']['_auditdate']))));
     }
     $this->SystemSetting->saveSetting("commission_load", $twoSecondsAgo);
     print "Done";
 }
 public function presenterAdvancements()
 {
     ini_set("memory_limit", '1000M');
     $elite = $this->args[0] ? true : false;
     $this->out('Starting to run presenterAdvancements accomplishment script.');
     if (empty($this->args[1])) {
         $startTime = strtotime(date("Y-m-d 00:00:00", strtotime("Yesterday")));
     } else {
         $startTime = strtotime(date("Y-m-d 00:00:00", strtotime($this->args[1])));
     }
     $this->out($startTime);
     $endTime = strtotime(date("Y-m-d 00:00:00"));
     App::import('model', 'Presenter_type');
     $this->PresenterType = new PresenterType();
     App::import('model', 'Presenter');
     $this->Presenter = new Presenter();
     App::import('model', 'Accomplishment');
     $this->Accomplishment = new Accomplishment();
     $last_yearmonth = date("Ym", strtotime("last month", $startTime));
     $prev_maxes = array();
     $prev_maxes_data = $this->PresenterType->find('all', array('conditions' => array('yearmonth <= ' => $last_yearmonth), 'fields' => array('presenter_id', 'max(presentertypes_id) as max_id'), 'group' => array('presenter_id')));
     foreach ($prev_maxes_data as $value) {
         $prev_maxes[$value['PresenterType']['presenter_id']] = $value[0]['max_id'];
     }
     unset($prev_maxes_data);
     while ($startTime < $endTime) {
         $date = date("Y-m-d", $startTime);
         $this->out($date);
         //CHECK Presenter status advancement
         if ($startTime >= strtotime("2012-11-01")) {
             $yearmonth = date("Y-m", $startTime);
             if (empty($this->proccessedMonths[$yearmonth])) {
                 $this->proccessedMonths[$yearmonth] = 1;
                 $statuses = CommissionAPI::call("presenter/{$yearmonth}/statuses");
                 foreach ($statuses as $presenterId => $color) {
                     if ($color == 'white') {
                         continue;
                     }
                     $prev_max_id = $prev_maxes[$presenterId] ? $prev_maxes[$presenterId] : 0;
                     if ($prev_max_id >= $this->PresenterType->getIdFromType($color)) {
                         continue;
                     }
                     $this->Presenter->id = $presenterId;
                     $small_presenter = $this->Presenter->find('first', array('contain' => array('User'), 'conditions' => array('Presenter.id' => $presenterId), 'fields' => array('User.id')));
                     $user_id = $small_presenter['User']['id'];
                     $newId = $this->PresenterType->getIdFromType($color);
                     while ($prev_max_id < $newId) {
                         $prev_max_id++;
                         if ($prev_max_id == 1 || !$elite && $prev_max_id >= $this->PresenterType->getIdFromType('green')) {
                             continue;
                             //white is not an achievement
                         }
                         //Check to see if we have given them credit for this ID yet
                         $color = $this->PresenterType->getTypeFromId($prev_max_id);
                         if (!$this->Accomplishment->accomplishmentExistsForUser("statusadvancement", $user_id, $color)) {
                             if (empty($this->presenterCache[$presenterId])) {
                                 $this->presenterCache[$presenterId] = $this->Presenter->loadBasicDetails();
                             }
                             $presenter = $this->presenterCache[$presenterId];
                             if (empty($presenter)) {
                                 continue;
                             }
                             $recordDate = strtotime(date("Y-m-t", $startTime));
                             if ($recordDate > time()) {
                                 $recordDate = $startTime;
                             }
                             $this->Accomplishment->presenterStatusAdvancement($presenter, $color, date("Y-m-d 23:59:59", $recordDate));
                             $this->out($presenter['Presenter']['id'] . " - " . $color);
                         }
                     }
                 }
             }
         }
         $startTime = strtotime("tomorrow", $startTime);
     }
     $this->out('Finished running presenterAdvancements accomplishment script.');
 }
 public function getBonusEarnedList()
 {
     $year_month = date("Y-m");
     $presenterId = $this->presenterId;
     //$presenterId = 113;
     $commishlist = CommissionAPI::call("presenter/{$year_month}/export?fields[]=sequence_id&fields[]=id&fields[]=type&fields[]=recognizedStatus&directteam={$presenterId}&filters[]=recognizedStatus%20>=%2040");
     $resultData = new stdClass();
     $ids = array();
     foreach ($commishlist->results as $value) {
         $ids[] = $value->id;
         $identifier = $value->id;
         $resultData->{$identifier} = $value;
     }
     $results = $this->RoyaltiesEarned->getBonusEarnedListResults($ids);
     foreach ($results as $result) {
         $identifier = $result->presenter_id;
         $resultData->{$identifier}->email = $result->email;
         $resultData->{$identifier}->name = $result->name;
         $resultData->{$identifier}->photo = $result->photo;
         $resultData->{$identifier}->sponsor = $result->sponsorName;
         $resultData->{$identifier}->previous_status = $result->previousStatus;
         $resultData->{$identifier}->bonus_earned = $result->bonusEarned;
         $resultData->{$identifier}->presenter_id = $result->presenter_id;
         if ($resultData->{$identifier}->bonus_earned == '') {
             unset($resultData->{$identifier});
         }
         unset($resultData->{$identifier}->recognizedStatus);
         unset($resultData->{$identifier}->type);
         unset($resultData->{$identifier}->id);
     }
     $resultData = (object) array_filter((array) $resultData);
     $this->sendSuccess($resultData);
 }
 private function getCommissionData($yearMonthString)
 {
     $params = "?fields[]=prs";
     $params .= "&fields[]=id";
     $params .= "&fields[]=type";
     $params .= "&fields[]=recognizedStatus";
     //$params .= "&fields[]=signup";
     //$params .= "&fields[]=activeprs";
     //$params .= "&fields[]=companypeople";
     //$params .= "&fields[]=up";
     $commission_data = CommissionAPI::call("presenter/{$yearMonthString}/export/" . $params);
     return $commission_data;
 }
 public function conventionReport()
 {
     $presenterId = $this->presenterId;
     $year_month = date('Y-m');
     $downLine = CommissionAPI::call("presenter/{$year_month}/export?fields[]=sequence_id&fields[]=id&fields[]=type&fields[]=recognizedStatus&fields[]=signup&fields[]=prs&fields[]=lifeprs&fields[]=gen0&fields[]=company&fields[]=firstlevelcount&directteam={$presenterId}");
     $commissionEngineData = [];
     $attendeeList = new stdClass();
     foreach ($downLine->results as $value) {
         $commissionEngineData[$value->id] = $value;
     }
     //get people registered for convention
     $attendees = $this->Presenter->query("\n            select Cvent.*, \n              Presenter.id, Presenter.presenter_sequence_id, Presenter.sponsor_id, \n              User.first_name, User.last_name,\n              Sponsor.first_name, Sponsor.last_name\n            from cvent as Cvent\n            join presenters as Presenter on Cvent.presenter_sequence_id = Presenter.presenter_sequence_id\n            join presenters as ps on Presenter.sponsor_id = ps.id\n            join users as Sponsor on ps.user_id = Sponsor.id\n            join users as User on Presenter.user_id = User.id\n            where Cvent.object = 'Registration'\n            group by Cvent.presenter_sequence_id");
     foreach ($attendees as $attendee) {
         //if presenter_id
         if (array_key_exists($attendee['Presenter']['id'], $commissionEngineData)) {
             $identifier = $attendee['Presenter']['id'];
             $attendeeList->{$identifier} = $commissionEngineData[$identifier];
             $attendeeList->{$identifier}->User = $attendee['User'];
             $attendeeList->{$identifier}->Presenter = $attendee['Presenter'];
             $attendeeList->{$identifier}->Sponsor = $attendee['Sponsor'];
         }
     }
     $this->sendSuccess($attendeeList);
 }
 public function leaderboard($inPresenterId = NULL)
 {
     $result = CommissionAPI::call("presenter/" . date('Y-m') . "/export?" . http_build_query(array("fields" => array("id", "sponsor", "prs30"), "filters" => array("prs30 >= 50000", "cat1 = es_US"))));
     $sponsors = array();
     $total = $this->Presenter->find('count', array('conditions' => array('presenter_status_id' => 3, 'default_locale' => 'es_US')));
     foreach ($result->results as $qualified) {
         if (empty($sponsors[$qualified->sponsor])) {
             $sponsors[$qualified->sponsor] = array();
         }
         $sponsors[$qualified->sponsor][] = $qualified;
     }
     // allow for a secondary sort on the sum of the child prs
     $sponsor_child_prs_totals = [];
     foreach ($sponsors as $key => $value) {
         $total = 0;
         if (count($value) > 1) {
             foreach ($value as $child) {
                 $total += $child->prs30;
             }
         } else {
             $total = $value[0]->prs30;
         }
         $sponsor_child_prs_totals[count($value)][$key] = $total;
     }
     unset($value);
     unset($key);
     // sort $sponsor_child_prs_totals
     foreach ($sponsor_child_prs_totals as $key => $value) {
         uasort($sponsor_child_prs_totals[$key], function ($a, $b) {
             return $b - $a;
         });
     }
     unset($value);
     unset($key);
     // put $sponsor_child_prs_totals back in order of top qty of recruits
     krsort($sponsor_child_prs_totals);
     // rebuild array of qualifiers with the sub sort in place
     $sponsors_sorted = [];
     foreach ($sponsor_child_prs_totals as $value) {
         foreach ($value as $key => $data) {
             $sponsors_sorted[$key] = $sponsors[$key];
         }
     }
     $presenterIds = [];
     //If I am a presenter, then figure out my rank
     if ($this->isPresenterLoggedIn()) {
         $presenterIds[] = $this->presenterId;
         $me = [];
         $rank = 1;
         foreach ($sponsors_sorted as $sponsorId => $children) {
             if ($sponsorId == $this->presenterId) {
                 $me = $sponsors_sorted[$sponsorId];
                 break;
             }
             $rank++;
         }
     } else {
         $rank = count($sponsors_sorted) + 1;
     }
     $leaders = array_slice($sponsors_sorted, 0, 10, true);
     foreach ($leaders as $sponsorId => $children) {
         $presenterIds[] = $sponsorId;
         foreach ($children as $child) {
             $presenterIds[] = $child->id;
         }
     }
     $out = $this->presenterDetailsByIds($presenterIds);
     $sponsors = array();
     $count = 1;
     foreach ($leaders as $sponsorId => $children) {
         $sponsors[] = $this->_createSponsor($out, $sponsorId, $children, $count, $sponsor_child_prs_totals[count($children)][$sponsorId]);
         $count++;
     }
     if ($this->isPresenterLoggedIn()) {
         $me = $this->_createSponsor($out, $this->presenterId, $me, $rank, $sponsor_child_prs_totals[count($children)][$sponsorId]);
     } else {
         $me = array("presenterId" => null, "rank" => "-1", "facebookId" => "2");
     }
     $this->sendSuccess(array("topten" => $sponsors, "me" => $me, "total" => $total));
 }
 public function teamTalkIncentivePoints()
 {
     $result = array();
     $year_month = date("Y-m");
     $presenter = $this->Presenter->presenterFromUserId($this->userId);
     $circles = CommissionAPI::call("presenter/{$presenter['Presenter']['id']}/{$year_month}/circle");
     $count = count($circles);
     if ($circles->notfound == 1) {
         $result = 'false';
     } else {
         for ($i = 0; $i < $count; $i++) {
             $presenter = $this->Presenter->presenterFromPresenterId($circles[$i]->id);
             if ($presenter['Presenter']['presenter_status_id'] != 3) {
                 continue;
             }
             $result[$i]['Presenter']['id'] = $circles[$i]->id;
             $result[$i]['Presenter']['presenter_sequence_id'] = $circles[$i]->sequence_id;
             $result[$i]['Presenter']['recognized_status'] = $circles[$i]->recognizedStatus;
             $trip_points = $this->tripIncentivePoints($circles[$i]->sequence_id);
             $result[$i]['User']['name'] = $presenter['User']['first_name'] . ' ' . $presenter['User']['last_name'];
             $result[$i]['User']['email'] = $presenter['User']['Email']['email'];
             $result[$i]['TripIncentivePoints'] = array('points' => $trip_points);
         }
     }
     $this->sendSuccess($result);
 }
 function reactivationCheck($presenter_id, $commission_total)
 {
     $presenter = $this->Presenter->find('first', array('conditions' => array("Presenter.id" => $presenter_id)));
     $date = new DateTime();
     $current_month = $date->format("Y-m");
     $commission_result = CommissionAPI::call("presenter/{$presenter_id}/{$current_month}/stats");
     $activeprs = $commission_result->activeprs;
     $activeprs = $activeprs == 0 ? 0 : (double) $activeprs / 100;
     $commission_total = (double) $commission_total;
     $updated_prs = $commission_total + $activeprs;
     if ($updated_prs > 125.0) {
         $AdminUser = $this->AdminUser->find('first', array('conditions' => array('AdminUser.id' => 0)));
         $admin_user = new stdClass();
         $admin_user->id = $AdminUser['AdminUser']['id'];
         $this->Presenter->changePresenterStatus($presenter_id, 3, $admin_user);
     }
 }