project_ajax.php 12 KB

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