project_ajax.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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 = 4000;
  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. $user_ids = array_column($addresses, "user_id");
  136. $reject_data = [];
  137. $reject_rows = UserLocationReject::query(["user_id" => $user_ids, "location_id" => $location_id]);
  138. foreach($reject_rows as $reject_row) {
  139. $reject_data[$reject_row->user_id] = $reject_row;
  140. }
  141. $output = [];
  142. foreach($addresses as $address) {
  143. $user = $address->getUser();
  144. if(!$user) {
  145. continue;
  146. }
  147. $is_current_tester = $user->id == $test->tester_id;
  148. $is_unverified = $user->level <= User::LEVEL_UNVERIFIED;
  149. if($user->isArchived()) {
  150. continue;
  151. }
  152. if($user->isDeactivated()) {
  153. continue;
  154. }
  155. if(!$include_unverified && $user->isUnverified()) {
  156. continue;
  157. }
  158. if(!$user->isTester()) {
  159. continue;
  160. }
  161. if($user->score < $minimum_score) {
  162. continue;
  163. }
  164. $rejected = $reject_data[$user->id] ?? null;
  165. $last_rejected = null;
  166. $reject_count = 0;
  167. if($rejected) {
  168. $last_rejected = $rejected->getDateTimeLastRejected()->format("d/m/Y");
  169. $reject_count = $rejected->reject_count;
  170. }
  171. $distance_miles = Geolocation::getDistance($location->getGeolocation(), $address->getGeolocation());
  172. $distance_kilometers = $distance_miles * Geolocation::KMS_IN_MILE;
  173. $user_pending_tests = array_filter($pending_tests, static function($test) use ($user) {
  174. return ((int) $user->id === (int) $test->tester_id);
  175. });
  176. $pending_test_count = count($user_pending_tests);
  177. $age = $user->getAge();
  178. // Age check
  179. if(!$project->isAgeValid($age)) {
  180. continue;
  181. }
  182. $max_radius_exceeded = ($distance_miles > $address->max_radius_miles);
  183. $time_last_test = $user_last_test_times[$user->id] ?? false;
  184. if($time_last_test && $days_since_last_test) {
  185. $dt_last_test = CarbonImmutable::createFromTimestamp($time_last_test, TIMEZONE);
  186. $days = $dt_last_test->diffInDays($dt_now);
  187. if($days < $days_since_last_test) {
  188. continue;
  189. }
  190. }
  191. $output[] = [
  192. "id" => (int) $user->id,
  193. "addressId" => (int) $address->id,
  194. "name" => $user->getDisplayName(),
  195. "age" => $age,
  196. "phone" => $user->phone,
  197. "score" => (int) $user->score,
  198. "distanceMiles" => $distance_miles,
  199. "distanceKilometers" => $distance_kilometers,
  200. "maxRadiusMiles" => (float) $address->max_radius_miles,
  201. "maxRadiusKilometers" => $address->max_radius_miles * Geolocation::KMS_IN_MILE,
  202. "maxRadiusExceeded" => $max_radius_exceeded,
  203. "latitude" => (float) $address->latitude,
  204. "longitude" => (float) $address->longitude,
  205. "pendingTestCount" => $pending_test_count,
  206. "isCurrentTester" => $is_current_tester,
  207. "isRegistered" => $user->isRegistered(),
  208. "isUnverified" => $is_unverified,
  209. "levelText" => $user->getLevelText(),
  210. "levelClass" => $user->getLevelClass(),
  211. "termsAccepted" => (bool) $user->terms_accepted,
  212. "reported" => (int) $user->reported,
  213. "reportedComment" => $user->reported_comment,
  214. "timeRegistered" => strtotime($user->dts_registered . " UTC"),
  215. "timeLastTest" => $time_last_test,
  216. "rejected" => (bool) $rejected,
  217. "rejectCount" => (int) $reject_count,
  218. "dateLastRejected" => $last_rejected
  219. ];
  220. }
  221. JSON::success([
  222. "testers" => $output
  223. ]);
  224. }
  225. // Assigns a tester to a test
  226. case "assign-tester": {
  227. $year = http::value("year", "int");
  228. $month = http::value("month", "int");
  229. $day = http::value("day", "int");
  230. $unix_due = 0;
  231. if($year && $month && $day) {
  232. $month = str_pad($month, 2, "0", STR_PAD_LEFT);
  233. $day = str_pad($day, 2, "0", STR_PAD_LEFT);
  234. $unix_due = strtotime("$year-$month-$day");
  235. }
  236. $message = http::value("message");
  237. $location_id = http::value("location_id", "int");
  238. $location = Location::get($location_id);
  239. if(!$location) throw new Exception("Location not found.");
  240. $status_constraint = new Constraint("MORE_THAN_OR_EQUAL");
  241. $status_constraint->setValues(Test::STATUS_UNASSIGNED);
  242. $nvp = [
  243. "location_id" => $location_id,
  244. "project_id" => $project->id,
  245. "status" => $status_constraint,
  246. ];
  247. $test = Test::queryOne($nvp);
  248. if(!$test) throw new Exception("A test does not exist for this location.");
  249. $address_id = http::value("address_id", "int");
  250. $address = UserAddress::get($address_id);
  251. if(!$address) throw new Exception("User address cannot be found.");
  252. $user = $address->getUser();
  253. if($user->level == User::LEVEL_BANNED) throw new Exception("A test cannot be assigned to an banned user.");
  254. if($user->level == User::LEVEL_REGISTERED) throw new Exception("A test cannot be assigned to an unverified user.");
  255. if($user->level == User::LEVEL_UNVERIFIED) throw new Exception("A test cannot be assigned to an unverified user.");
  256. if($user->level == User::LEVEL_DEACTIVATED) throw new Exception("A test cannot be assigned to a deactivated user.");
  257. if($user->level != User::LEVEL_TESTER) throw new Exception("A test cannot be assigned to a user that's not a tester.");
  258. $test->status = Test::STATUS_ASSIGNED;
  259. $test->tester_id = $user->id;
  260. $test->dts_assigned = Util::getDateTime();
  261. $test->dts_rejected = null;
  262. $test->dts_updated = Util::getDateTime();
  263. if($unix_due) {
  264. $test->dts_due = "$year-$month-$day 23:59:59";
  265. if(strcmp($test->dts_due, $project->dts_start) < 0) throw new Exception("The date due cannot be before the project start date.");
  266. if(strcmp($test->dts_due, $project->dts_deadline) > 0) throw new Exception("The date due cannot be beyond the project deadline.");
  267. }
  268. $success = $test->commit();
  269. if(!$success) throw new Exception("Test cannot be assigned, please try again later.");
  270. $test->sendAssignEmail($message);
  271. JSON::success();
  272. break;
  273. }
  274. case "add-locations": {
  275. $location_ids = http::value("location_ids", "int");
  276. $customer = $project->getCustomer();
  277. $locations = Location::query([
  278. "customer_id" => $customer->id,
  279. "id" => $location_ids
  280. ]);
  281. $dupe_locations = [];
  282. foreach($locations as $location) {
  283. $test = $project->getActiveTestForLocationId($location->id);
  284. if($test) {
  285. $dupe_locations[] = $location;
  286. }
  287. else {
  288. $project->createTestForLocationId($location->id);
  289. }
  290. }
  291. $dupe_location_objects = [];
  292. foreach($dupe_locations as $location) {
  293. $dupe_location_objects[] = [
  294. "id" => $location->id,
  295. "name" => $location->name
  296. ];
  297. }
  298. JSON::success([
  299. "dupeLocations" => $dupe_location_objects
  300. ]);
  301. break;
  302. }
  303. default:
  304. throw new Exception("Invalid request.");
  305. }
  306. }
  307. catch(Exception $e) {
  308. JSON::fail($e->getMessage());
  309. }
  310. }
  311. JSON::fail("Invalid request.");
  312. ?>