project_ajax.php 11 KB

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