1
0

project_ajax.php 11 KB

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