project_ajax.php 12 KB

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