project_ajax.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. <?php
  2. /**
  3. * @var int $id
  4. * @var string $action
  5. */
  6. use Carbon\CarbonImmutable;
  7. JSON::header();
  8. $project = Project::get($id);
  9. if(!$project) throw new Exception("Project cannot be found.");
  10. if(!Core::$user->hasPermission($project)) throw new Exception("You do not have permission to access this resource.");
  11. $dt_now = CarbonImmutable::now(TIMEZONE);
  12. $submit = http::value("submit");
  13. if($submit) {
  14. try {
  15. Core::validateCSRFToken($submit);
  16. switch($action) {
  17. // Gets all locations for a project
  18. case "get-locations": {
  19. $customer = $project->getCustomer();
  20. $tests = $project->getTests();
  21. $locations = Location::load(array_column($tests, "location_id"));
  22. $location_tests = [];
  23. foreach($tests as $test) {
  24. if($test->status == Test::STATUS_CANCELLED) continue;
  25. $location_tests[$test->location_id] = $test;
  26. }
  27. $output = [];
  28. foreach($locations as $location) {
  29. $test = $location_tests[$location->id] ?? false;
  30. $test_id = null;
  31. $tester_id = null;
  32. $status = 0;
  33. $status_text = "";
  34. $pass = 0;
  35. $pass_class = "";
  36. $pass_text = "";
  37. $pass_icon = "";
  38. $retest = false;
  39. $class = "secondary";
  40. if($test) {
  41. $test_id = (int) $test->id;
  42. $tester_id = (int) $test->tester_id;
  43. $class = $test->getStatusClass();
  44. $status = $test->status;
  45. $status_text = $test->getStatusText();
  46. $pass = (int) $test->pass;
  47. $pass_class = $test->getPassClass();
  48. $pass_text = $test->getPassText();
  49. $pass_icon = $test->getPassIcon();
  50. $retest = (bool) $test->retest;
  51. }
  52. $output[] = (object) [
  53. "id" => (int) $location->id,
  54. "internalId" => $location->internal_id,
  55. "testId" => $test_id,
  56. "testerId" => $tester_id,
  57. "name" => $location->name,
  58. "address" => $location->getDisplayAddress(["address_1", "address_2", "city", "postal_code"]),
  59. "address1" => $location->address_1,
  60. "status" => $status,
  61. "statusText" => $status_text,
  62. "pass" => $pass,
  63. "passClass" => $pass_class,
  64. "passText" => $pass_text,
  65. "passIcon" => $pass_icon,
  66. "class" => $class,
  67. "latitude" => (float) $location->latitude,
  68. "longitude" => (float) $location->longitude,
  69. "retest" => $retest,
  70. ];
  71. }
  72. usort($output, function($a, $b) {
  73. return $a->status <=> $b->status;
  74. });
  75. JSON::success([
  76. "locations" => $output
  77. ]);
  78. break;
  79. }
  80. // Gets testers near a project
  81. case "get-testers": {
  82. $location_id = http::value("location_id", "int");
  83. $include_unverified = http::value("include_unverified", "int");
  84. $minimum_score = http::value("minimum_score", "int");
  85. $days_since_last_test = http::value("days_since_last_test", "int");
  86. $location = Location::get($location_id);
  87. if(!$location) {
  88. throw new RuntimeException("Location not found.");
  89. }
  90. $test = Test::queryOne([
  91. "location_id" => $location_id,
  92. "project_id" => $project->id,
  93. "status" => Constraint::moreThanOrEquals(Test::STATUS_UNASSIGNED),
  94. ]);
  95. if(!$test) {
  96. throw new RuntimeException("A test does not exist for this project.");
  97. }
  98. /*
  99. $max_distance = http::value("max_distance", "int");
  100. if($max_distance < 2.5) $max_distance = 2.5;
  101. if($max_distance > 25) $max_distance = 25;
  102. */
  103. $max_distance = 25;
  104. if(Core::$user->canAccessProjects()) {
  105. $max_distance = 1000;
  106. }
  107. $bounds = Geolocation::getBounds($location->getGeolocation(), $max_distance);
  108. $addresses = UserAddress::query([
  109. "latitude" => Constraint::between($bounds->southWest[0], $bounds->northEast[0]),
  110. "longitude" => Constraint::between($bounds->southWest[1], $bounds->northEast[1])
  111. ]);
  112. $users = User::load(array_column($addresses, "user_id"));
  113. $user_last_tests = Test::query([
  114. "tester_id" => array_column($users, "id"),
  115. "dts_start" => Constraint::isNotNull(),
  116. ]);
  117. $user_last_test_times = [];
  118. foreach($user_last_tests as $user_last_test) {
  119. $dt_start = $user_last_test->getDateTimeStart();
  120. $unix_start = $dt_start->getTimestamp();
  121. $current_start = $user_last_test_times[$user_last_test->tester_id] ?? 0;
  122. if($unix_start > $current_start) {
  123. $user_last_test_times[$user_last_test->tester_id] = $unix_start;
  124. }
  125. }
  126. $pending_tests = Test::query([
  127. "tester_id" => array_column($users, "id"),
  128. "status" => Test::STATUS_ASSIGNED,
  129. ]);
  130. // Sort by distance to location
  131. usort($addresses, static function($a, $b) use ($location) {
  132. $lat_lng = $location->getGeolocation();
  133. return Geolocation::getDistance($lat_lng, $a->getGeolocation()) <=> Geolocation::getDistance($lat_lng, $b->getGeolocation());
  134. });
  135. $output = [];
  136. foreach($addresses as $address) {
  137. $user = $address->getUser();
  138. $is_current_tester = $user->id == $test->tester_id;
  139. $is_unverified = $user->level <= User::LEVEL_UNVERIFIED;
  140. if($user->isArchived()) {
  141. continue;
  142. }
  143. if($user->isDeactivated()) {
  144. continue;
  145. }
  146. if(!$include_unverified && $user->isUnverified()) {
  147. continue;
  148. }
  149. if(!$user->isTester()) {
  150. continue;
  151. }
  152. if($user->score < $minimum_score) {
  153. continue;
  154. }
  155. $distance_miles = Geolocation::getDistance($location->getGeolocation(), $address->getGeolocation());
  156. $distance_kilometers = $distance_miles * Geolocation::KMS_IN_MILE;
  157. $user_pending_tests = array_filter($pending_tests, static function($test) use ($user) {
  158. return ((int) $user->id === (int) $test->tester_id);
  159. });
  160. $pending_test_count = count($user_pending_tests);
  161. $age = $user->getAge();
  162. // Age check
  163. if(!$project->isAgeValid($age)) {
  164. continue;
  165. }
  166. $max_radius_exceeded = ($distance_miles > $address->max_radius_miles);
  167. $time_last_test = $user_last_test_times[$user->id] ?? false;
  168. if($time_last_test && $days_since_last_test) {
  169. $dt_last_test = CarbonImmutable::createFromTimestamp($time_last_test, TIMEZONE);
  170. $days = $dt_last_test->diffInDays($dt_now);
  171. if($days < $days_since_last_test) {
  172. continue;
  173. }
  174. }
  175. $output[] = [
  176. "id" => (int) $user->id,
  177. "addressId" => (int) $address->id,
  178. "name" => $user->getDisplayName(),
  179. "age" => $age,
  180. "phone" => $user->phone,
  181. "score" => (int) $user->score,
  182. "distanceMiles" => $distance_miles,
  183. "distanceKilometers" => $distance_kilometers,
  184. "maxRadiusMiles" => (float) $address->max_radius_miles,
  185. "maxRadiusKilometers" => $address->max_radius_miles * Geolocation::KMS_IN_MILE,
  186. "maxRadiusExceeded" => $max_radius_exceeded,
  187. "latitude" => (float) $address->latitude,
  188. "longitude" => (float) $address->longitude,
  189. "pendingTestCount" => $pending_test_count,
  190. "isCurrentTester" => $is_current_tester,
  191. "isRegistered" => $user->isRegistered(),
  192. "isUnverified" => $is_unverified,
  193. "levelText" => $user->getLevelText(),
  194. "levelClass" => $user->getLevelClass(),
  195. "termsAccepted" => (bool) $user->terms_accepted,
  196. "reported" => (int) $user->reported,
  197. "reportedComment" => $user->reported_comment,
  198. "timeRegistered" => strtotime($user->dts_registered . " UTC"),
  199. "timeLastTest" => $time_last_test,
  200. ];
  201. }
  202. JSON::success([
  203. "testers" => $output
  204. ]);
  205. }
  206. // Assigns a tester to a test
  207. case "assign-tester": {
  208. $year = http::value("year", "int");
  209. $month = http::value("month", "int");
  210. $day = http::value("day", "int");
  211. $unix_due = 0;
  212. if($year && $month && $day) {
  213. $month = str_pad($month, 2, "0", STR_PAD_LEFT);
  214. $day = str_pad($day, 2, "0", STR_PAD_LEFT);
  215. $unix_due = strtotime("$year-$month-$day");
  216. }
  217. $message = http::value("message");
  218. $location_id = http::value("location_id", "int");
  219. $location = Location::get($location_id);
  220. if(!$location) throw new Exception("Location not found.");
  221. $status_constraint = new Constraint("MORE_THAN_OR_EQUAL");
  222. $status_constraint->setValues(Test::STATUS_UNASSIGNED);
  223. $nvp = [
  224. "location_id" => $location_id,
  225. "project_id" => $project->id,
  226. "status" => $status_constraint,
  227. ];
  228. $test = Test::queryOne($nvp);
  229. if(!$test) throw new Exception("A test does not exist for this location.");
  230. $address_id = http::value("address_id", "int");
  231. $address = UserAddress::get($address_id);
  232. if(!$address) throw new Exception("User address cannot be found.");
  233. $user = $address->getUser();
  234. if($user->level == User::LEVEL_BANNED) throw new Exception("A test cannot be assigned to an banned user.");
  235. if($user->level == User::LEVEL_REGISTERED) throw new Exception("A test cannot be assigned to an unverified user.");
  236. if($user->level == User::LEVEL_UNVERIFIED) throw new Exception("A test cannot be assigned to an unverified user.");
  237. if($user->level == User::LEVEL_DEACTIVATED) throw new Exception("A test cannot be assigned to a deactivated user.");
  238. if($user->level != User::LEVEL_TESTER) throw new Exception("A test cannot be assigned to a user that's not a tester.");
  239. $test->status = Test::STATUS_ASSIGNED;
  240. $test->tester_id = $user->id;
  241. $test->dts_assigned = Util::getDateTime();
  242. $test->dts_updated = Util::getDateTime();
  243. if($unix_due) {
  244. $test->dts_due = "$year-$month-$day 23:59:59";
  245. if(strcmp($test->dts_due, $project->dts_start) < 0) throw new Exception("The date due cannot be before the project start date.");
  246. if(strcmp($test->dts_due, $project->dts_deadline) > 0) throw new Exception("The date due cannot be beyond the project deadline.");
  247. }
  248. $success = $test->commit();
  249. if(!$success) throw new Exception("Test cannot be assigned, please try again later.");
  250. $test->sendAssignEmail($message);
  251. JSON::success();
  252. break;
  253. }
  254. case "add-locations": {
  255. $location_ids = http::value("location_ids", "int");
  256. $customer = $project->getCustomer();
  257. $locations = Location::query([
  258. "customer_id" => $customer->id,
  259. "id" => $location_ids
  260. ]);
  261. $dupe_locations = [];
  262. foreach($locations as $location) {
  263. $test = $project->getActiveTestForLocationId($location->id);
  264. if($test) {
  265. $dupe_locations[] = $location;
  266. }
  267. else {
  268. $project->createTestForLocationId($location->id);
  269. }
  270. }
  271. $dupe_location_objects = [];
  272. foreach($dupe_locations as $location) {
  273. $dupe_location_objects[] = [
  274. "id" => $location->id,
  275. "name" => $location->name
  276. ];
  277. }
  278. JSON::success([
  279. "dupeLocations" => $dupe_location_objects
  280. ]);
  281. break;
  282. }
  283. default:
  284. throw new Exception("Invalid request.");
  285. }
  286. }
  287. catch(Exception $e) {
  288. JSON::fail($e->getMessage());
  289. }
  290. }
  291. JSON::fail("Invalid request.");
  292. ?>