| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410 |
- <?php
- /**
- * @var int $id
- * @var string $action
- */
- use Carbon\CarbonImmutable;
- JSON::header();
- $project = Project::get($id);
- if(!$project) throw new Exception("Project cannot be found.");
- if(!Core::$user->hasPermission($project)) throw new Exception("You do not have permission to access this resource.");
- $dt_now = CarbonImmutable::now(TIMEZONE);
- $submit = http::value("submit");
- if($submit) {
- try {
- Core::validateCSRFToken($submit);
- switch($action) {
- // Gets all locations for a project
- case "get-locations": {
- $customer = $project->getCustomer();
- $tests = $project->getTests();
- $locations = Location::load(array_column($tests, "location_id"));
- $location_tests = [];
- foreach($tests as $test) {
- if($test->status == Test::STATUS_CANCELLED) continue;
- $location_tests[$test->location_id] = $test;
- }
- $output = [];
- foreach($locations as $location) {
- $test = $location_tests[$location->id] ?? false;
- $test_id = null;
- $tester_id = null;
- $status = 0;
- $status_text = "";
- $pass = 0;
- $pass_class = "";
- $pass_text = "";
- $pass_icon = "";
- $retest = false;
- $paid = true;
- $class = "secondary";
- if($test) {
- $test_id = (int) $test->id;
- $tester_id = (int) $test->tester_id;
- $class = $test->getStatusClass();
- $status = $test->status;
- $status_text = $test->getStatusText();
- $pass = (int) $test->pass;
- $pass_class = $test->getPassClass();
- $pass_text = $test->getPassText();
- $pass_icon = $test->getPassIcon();
- $retest = (bool) $test->retest;
- $payment_required = (bool) $test->payment_required;
- $paid = (bool) $test->dts_paid;
- }
- $output[] = (object) [
- "id" => (int) $location->id,
- "internalId" => $location->internal_id,
- "testId" => $test_id,
- "testerId" => $tester_id,
- "name" => $location->name,
- "address" => $location->getDisplayAddress(["address_1", "address_2", "city", "postal_code"]),
- "address1" => $location->address_1,
- "status" => $status,
- "statusText" => $status_text,
- "pass" => $pass,
- "passClass" => $pass_class,
- "passText" => $pass_text,
- "passIcon" => $pass_icon,
- "class" => $class,
- "latitude" => (float) $location->latitude,
- "longitude" => (float) $location->longitude,
- "retest" => $retest,
- "paymentRequired" => !empty($payment_required),
- "paid" => !empty($paid)
- ];
- }
- usort($output, static function(object $a, object $b) {
- return $a->status <=> $b->status;
- });
- JSON::success([
- "locations" => $output
- ]);
- break;
- }
- // Gets testers near a project
- case "get-testers": {
- $location_id = http::value("location_id", "int");
- $include_unverified = http::value("include_unverified", "int");
- $minimum_score = http::value("minimum_score", "int");
- $days_since_last_test = http::value("days_since_last_test", "int");
- $location = Location::get($location_id);
- if(!$location) {
- throw new RuntimeException("Location not found.");
- }
- $test = Test::queryOne([
- "location_id" => $location_id,
- "project_id" => $project->id,
- "status" => Constraint::moreThanOrEquals(Test::STATUS_UNASSIGNED),
- ]);
- if(!$test) {
- throw new RuntimeException("A test does not exist for this project.");
- }
- /*
- $max_distance = http::value("max_distance", "int");
- if($max_distance < 2.5) $max_distance = 2.5;
- if($max_distance > 25) $max_distance = 25;
- */
- $max_distance = 25;
- if(Core::$user->canAccessProjects()) {
- $max_distance = 4000;
- }
- $bounds = Geolocation::getBounds($location->getGeolocation(), $max_distance);
- $addresses = UserAddress::query([
- "latitude" => Constraint::between($bounds->southWest[0], $bounds->northEast[0]),
- "longitude" => Constraint::between($bounds->southWest[1], $bounds->northEast[1])
- ]);
- $users = User::load(array_column($addresses, "user_id"));
- $user_last_tests = Test::query([
- "tester_id" => array_column($users, "id"),
- "dts_start" => Constraint::isNotNull(),
- ]);
- $user_last_test_times = [];
- foreach($user_last_tests as $user_last_test) {
- $dt_start = $user_last_test->getDateTimeStart();
- $unix_start = $dt_start->getTimestamp();
- $current_start = $user_last_test_times[$user_last_test->tester_id] ?? 0;
- if($unix_start > $current_start) {
- $user_last_test_times[$user_last_test->tester_id] = $unix_start;
- }
- }
- $pending_tests = Test::query([
- "tester_id" => array_column($users, "id"),
- "status" => Test::STATUS_ASSIGNED,
- ]);
- // Sort by distance to location
- usort($addresses, static function($a, $b) use ($location) {
- $lat_lng = $location->getGeolocation();
- return Geolocation::getDistance($lat_lng, $a->getGeolocation()) <=> Geolocation::getDistance($lat_lng, $b->getGeolocation());
- });
- $user_ids = array_column($addresses, "user_id");
- $reject_data = [];
- $reject_rows = UserLocationReject::query(["user_id" => $user_ids, "location_id" => $location_id]);
- foreach($reject_rows as $reject_row) {
- $reject_data[$reject_row->user_id] = $reject_row;
- }
- $output = [];
- foreach($addresses as $address) {
- $user = $address->getUser();
- if(!$user) {
- continue;
- }
- $is_current_tester = $user->id == $test->tester_id;
- $is_unverified = $user->level <= User::LEVEL_UNVERIFIED;
- if($user->isArchived()) {
- continue;
- }
- if($user->isDeactivated()) {
- continue;
- }
- if(!$include_unverified && $user->isUnverified()) {
- continue;
- }
- if(!$user->isTester()) {
- continue;
- }
- if($user->score < $minimum_score) {
- continue;
- }
- $rejected = $reject_data[$user->id] ?? null;
- $last_rejected = null;
- $reject_count = 0;
- if($rejected) {
- $last_rejected = $rejected->getDateTimeLastRejected()->format("d/m/Y");
- $reject_count = $rejected->reject_count;
- }
- $distance_miles = Geolocation::getDistance($location->getGeolocation(), $address->getGeolocation());
- $distance_kilometers = $distance_miles * Geolocation::KMS_IN_MILE;
- $user_pending_tests = array_filter($pending_tests, static function($test) use ($user) {
- return ((int) $user->id === (int) $test->tester_id);
- });
- $pending_test_count = count($user_pending_tests);
- $age = $user->getAge();
- // Age check
- if(!$project->isAgeValid($age)) {
- continue;
- }
- $max_radius_exceeded = ($distance_miles > $address->max_radius_miles);
- $time_last_test = $user_last_test_times[$user->id] ?? false;
- if($time_last_test && $days_since_last_test) {
- $dt_last_test = CarbonImmutable::createFromTimestamp($time_last_test, TIMEZONE);
- $days = $dt_last_test->diffInDays($dt_now);
- if($days < $days_since_last_test) {
- continue;
- }
- }
- $output[] = [
- "id" => (int) $user->id,
- "addressId" => (int) $address->id,
- "name" => $user->getDisplayName(),
- "age" => $age,
- "phone" => $user->phone,
- "score" => (int) $user->score,
- "distanceMiles" => $distance_miles,
- "distanceKilometers" => $distance_kilometers,
- "maxRadiusMiles" => (float) $address->max_radius_miles,
- "maxRadiusKilometers" => $address->max_radius_miles * Geolocation::KMS_IN_MILE,
- "maxRadiusExceeded" => $max_radius_exceeded,
- "latitude" => (float) $address->latitude,
- "longitude" => (float) $address->longitude,
- "pendingTestCount" => $pending_test_count,
- "isCurrentTester" => $is_current_tester,
- "isRegistered" => $user->isRegistered(),
- "isUnverified" => $is_unverified,
- "levelText" => $user->getLevelText(),
- "levelClass" => $user->getLevelClass(),
- "termsAccepted" => (bool) $user->terms_accepted,
- "reported" => (int) $user->reported,
- "reportedComment" => $user->reported_comment,
- "timeRegistered" => strtotime($user->dts_registered . " UTC"),
- "timeLastTest" => $time_last_test,
- "rejected" => (bool) $rejected,
- "rejectCount" => (int) $reject_count,
- "dateLastRejected" => $last_rejected
- ];
- }
- JSON::success([
- "testers" => $output
- ]);
- }
- // Assigns a tester to a test
- case "assign-tester": {
- $year = http::value("year", "int");
- $month = http::value("month", "int");
- $day = http::value("day", "int");
- $unix_due = 0;
- if($year && $month && $day) {
- $month = str_pad($month, 2, "0", STR_PAD_LEFT);
- $day = str_pad($day, 2, "0", STR_PAD_LEFT);
- $unix_due = strtotime("$year-$month-$day");
- }
- $message = http::value("message");
- $location_id = http::value("location_id", "int");
- $location = Location::get($location_id);
- if(!$location) throw new Exception("Location not found.");
- $status_constraint = new Constraint("MORE_THAN_OR_EQUAL");
- $status_constraint->setValues(Test::STATUS_UNASSIGNED);
- $nvp = [
- "location_id" => $location_id,
- "project_id" => $project->id,
- "status" => $status_constraint,
- ];
- $test = Test::queryOne($nvp);
- if(!$test) throw new Exception("A test does not exist for this location.");
- $address_id = http::value("address_id", "int");
- $address = UserAddress::get($address_id);
- if(!$address) throw new Exception("User address cannot be found.");
- $user = $address->getUser();
- if($user->level == User::LEVEL_BANNED) throw new Exception("A test cannot be assigned to an banned user.");
- if($user->level == User::LEVEL_REGISTERED) throw new Exception("A test cannot be assigned to an unverified user.");
- if($user->level == User::LEVEL_UNVERIFIED) throw new Exception("A test cannot be assigned to an unverified user.");
- if($user->level == User::LEVEL_DEACTIVATED) throw new Exception("A test cannot be assigned to a deactivated user.");
- if($user->level != User::LEVEL_TESTER) throw new Exception("A test cannot be assigned to a user that's not a tester.");
- $test->status = Test::STATUS_ASSIGNED;
- $test->tester_id = $user->id;
- $test->dts_assigned = Util::getDateTime();
- $test->dts_rejected = null;
- $test->dts_updated = Util::getDateTime();
- if($unix_due) {
- $test->dts_due = "$year-$month-$day 23:59:59";
- if(strcmp($test->dts_due, $project->dts_start) < 0) throw new Exception("The date due cannot be before the project start date.");
- if(strcmp($test->dts_due, $project->dts_deadline) > 0) throw new Exception("The date due cannot be beyond the project deadline.");
- }
- $success = $test->commit();
- if(!$success) throw new Exception("Test cannot be assigned, please try again later.");
- $test->sendAssignEmail($message);
- JSON::success();
- break;
- }
- case "add-locations": {
- $location_ids = http::value("location_ids", "int");
- $customer = $project->getCustomer();
- $locations = Location::query([
- "customer_id" => $customer->id,
- "id" => $location_ids
- ]);
- $dupe_locations = [];
- foreach($locations as $location) {
- $test = $project->getActiveTestForLocationId($location->id);
- if($test) {
- $dupe_locations[] = $location;
- }
- else {
- $project->createTestForLocationId($location->id);
- }
- }
- $dupe_location_objects = [];
- foreach($dupe_locations as $location) {
- $dupe_location_objects[] = [
- "id" => $location->id,
- "name" => $location->name
- ];
- }
- JSON::success([
- "dupeLocations" => $dupe_location_objects
- ]);
- break;
- }
- default:
- throw new Exception("Invalid request.");
- }
- }
- catch(Exception $e) {
- JSON::fail($e->getMessage());
- }
- }
- JSON::fail("Invalid request.");
- ?>
|