Przeglądaj źródła

Add assigned tests map

Alan Lam 3 lat temu
rodzic
commit
d85970c539
4 zmienionych plików z 295 dodań i 192 usunięć
  1. 192 129
      controllers/user_ajax.php
  2. 98 62
      public/js/app-user.js
  3. 1 1
      routes.php
  4. 4 0
      views/user.php

+ 192 - 129
controllers/user_ajax.php

@@ -1,18 +1,33 @@
 <?php /** @noinspection PhpUnhandledExceptionInspection */
 
+/**
+ * @var int $id
+ * @var string $action
+ */
+
 JSON::header();
 
 $user = User::get($id);
-if(!$user) JSON::fail("User not found.");
+if(!$user) {
+	JSON::fail("User not found.");
+}
 
-switch($action) {
-	case "get-addresses":
+$controller = new class($user) {
+
+	/** @var User */
+	private $user;
+
+	/** @var Test[] */
+	private $locationTests = [];
 
-		$addresses = $user->getAddresses();
+	public function __construct(User $user) {
+		$this->user = $user;
+	}
 
+	public function getAddresses(): void {
 		$output = [];
 
-		foreach($addresses as $address) {
+		foreach($this->user->getAddresses() as $address) {
 			$output[] = [
 				"name" => $address->name,
 				"latitude" => (float) $address->latitude,
@@ -23,16 +38,19 @@ switch($action) {
 		JSON::success([
 			"addresses" => $output
 		]);
+	}
 
-		break;
-
-	case "get-locations":
-
+	/**
+	 * @return void
+	 */
+	public function getLocations(): void {
 		$output = [];
 
 		$address_id = http::value("address_id", "int");
 		$max_distance = http::value("max_distance", "int");
-		if($max_distance <= 0) $max_distance = 50;
+		if($max_distance <= 0) {
+			$max_distance = 50;
+		}
 
 		$date_start = http::value("date_start", "db");
 		$date_end = http::value("date_end", "db");
@@ -41,16 +59,18 @@ switch($action) {
 
 		$address = UserAddress::queryOne([
 			"id" => $address_id,
-			"user_id" => $id,
+			"user_id" => $this->user->id,
 		]);
 
-		if(!$address) throw new Exception("Cannot find address.");
+		if(!$address) {
+			throw new RuntimeException("Cannot find address.");
+		}
 
 		// Get locations according to bounds
 		$bounds = Geolocation::getBounds($address->getGeolocation(), $max_distance);
 
-		list($min_lat, $min_lng) = $bounds->southWest;
-		list($max_lat, $max_lng) = $bounds->northEast;
+		[$min_lat, $min_lng] = $bounds->southWest;
+		[$max_lat, $max_lng] = $bounds->northEast;
 
 		$locations = Location::query([
 			"latitude" => (new Constraint("BETWEEN"))->setValues($min_lat, $max_lat),
@@ -60,20 +80,14 @@ switch($action) {
 		]);
 
 		// Get customers
-		$customers = Customer::load(array_column($locations, "customer_id"));
+		Customer::load(array_column($locations, "customer_id"));
 
 		// Sort locations by distance
-		usort($locations, function($a, $b) use ($address) {
-
-			/**
-			 * @var Location $a
-			 * @var Location $b
-			 */
-
+		usort($locations, static function(Location $a, Location $b) use ($address) {
 			return
-			Geolocation::getDistance($address->getGeolocation(), $a->getGeolocation())
-			<=>
-			Geolocation::getDistance($address->getGeolocation(), $b->getGeolocation());
+				Geolocation::getDistance($address->getGeolocation(), $a->getGeolocation())
+				<=>
+				Geolocation::getDistance($address->getGeolocation(), $b->getGeolocation());
 		});
 
 		// Get tests
@@ -92,147 +106,196 @@ switch($action) {
 		$tests = Test::query($test_nvp);
 
 		// Get projects
-		$projects = Project::load(array_column($tests, "project_id"));
+		Project::load(array_column($tests, "project_id"));
 
-		$location_test_array = [];
 		foreach($tests as $test) {
-			$exists = isset($location_test_array[$test->location_id]);
+			$exists = isset($this->locationTests[$test->location_id]);
 			if(!$exists) {
-				$location_test_array[$test->location_id] = $test;
+				$this->locationTests[$test->location_id] = $test;
 			}
 			else {
-				$existing = $location_test_array[$test->location_id];
+				$existing = $this->locationTests[$test->location_id];
 
 				$unix_start_existing = is_null($existing->dts_start) ? 0 : strtotime($existing->dts_start . " UTC");
 				$unix_start_current = is_null($test->dts_start) ? 0 : strtotime($test->dts_start . " UTC");
 
 				if($unix_start_current > $unix_start_existing) {
-					$location_test_array[$test->location_id] = $test;
+					$this->locationTests[$test->location_id] = $test;
 				}
 			}
 		}
 
-		// Start output
-		foreach($locations as $location) {
-
+		$locations = array_filter($locations, function(Location $location) use ($address, $max_distance, $pending_tests) {
 			// Filter by distance
 			$distance = Geolocation::getDistance($address->getGeolocation(), $location->getGeolocation());
-			if($distance > $max_distance) continue;
-
-			/** @var Test $test */
-			$test = $location_test_array[$location->id] ?? null;
+			if($distance > $max_distance) {
+				return false;
+			}
 
+			// Filter by tests that have not started
 			if($pending_tests) {
-				if(!$test) continue;
-				if($test->dts_start) continue;
-			}
+				$test = $this->locationTests[$location->id] ?? null;
+				if(!$test) {
+					return false;
+				}
 
-			// Get customer
-			$customer = $location->getCustomer();
-			$customer_slug = Util::slug($customer->name, "_");
-
-			// Test
-			/** @var User $tester */
-			$tester = null;
-			$formatted_start_dts = null;
-			$formatted_due_dts = null;
-			$past_due = false;
-
-			// Icon
-			$icon = null;
-			$icon_file = "{$customer_slug}_none.png";
-
-			// Process test
-			if($test) {
-				$tester = $test->getTester();
-				$project = $test->getProject();
-
-				if(!is_null($test->dts_start)) {
-					$unix_start = strtotime($test->dts_start);
-					$formatted_start_dts = date("d/m/Y H:i", $unix_start);
+				if($test->dts_start) {
+					return false;
 				}
+			}
 
-				if(is_null($test->pass)) {
-					$icon_file = "{$customer_slug}_pending.png";
+			return true;
+		});
 
-					// Has due date
-					if(!is_null($test->dts_due)) {
-						$unix_due = strtotime($test->dts_due);
-						$formatted_due_dts = date("d/m/Y H:i", $unix_due);
+		// Start output
+		foreach($locations as $location) {
+			$output[] = $this->getLocationData($location, $address);
+		}
 
-						if($tester && time() > $unix_due) {
-							$icon_file = "{$customer_slug}_past_due.png";
-							$past_due = true;
-						}
-					}
+		JSON::success([
+			"name" => $address->name,
+			"latitude" => (double) $address->latitude,
+			"longitude" => (double) $address->longitude,
+			"locations" => $output
+		]);
 
-				}
-				else if($test->pass) {
-					$icon_file = "{$customer_slug}_pass.png";
-				}
-				else if(!$test->pass) {
-					$icon_file = "{$customer_slug}_fail.png";
-				}
-			}
+	}
 
-			if($icon_file && file_exists("public/img/markers/$icon_file")) {
-				$icon = $icon_file;
-			}
+	public function getAssignedLocations(): void {
+		$pending_tests = $this->user->getPendingTests();
+		$location_ids = array_column($pending_tests, "location_id");
 
-			$data = [
-				"id" => (int) $location->id,
-				"internalId" => (int) $location->internal_id,
-				"name" => $location->name,
-				"address" => $location->getDisplayAddress(),
-				"distance" => $distance,
-				"latitude" => (double) $location->latitude,
-				"longitude" => (double) $location->longitude,
-				"icon" => $icon,
-				"customer" => [
-					"id" => $customer->id,
-					"name" => $customer->name,
-				],
-				"test" => null,
-			];
+		$locations = Location::query(["id" => $location_ids]);
 
-			if($test) {
+		$output = [];
+		foreach($locations as $location) {
+			$output[] = $this->getLocationData($location, null);
+		}
 
-				$pass = is_null($test->pass) ? null : intval($test->pass);
+		JSON::success([
+			"locations" => $output
+		]);
+	}
+
+	private function getLocationData(Location $location, ?UserAddress $address): array {
+		// Get customer
+		$customer = $location->getCustomer();
+		$customer_slug = Util::slug($customer->name, "_");
+
+		// Test
+		/** @var User $tester */
+		$tester = null;
+		$formatted_start_dts = null;
+		$formatted_due_dts = null;
+		$past_due = false;
+
+		// Icon
+		$icon = null;
+		$icon_file = "{$customer_slug}_none.png";
+
+		// Distance
+		$distance = null;
+		if($address) {
+			$distance = Geolocation::getDistance($location->getGeolocation(), $address->getGeolocation());
+		}
 
-				$data["test"] = [
-					"id" => (int) $test->id,
-					"pass" => $pass,
-					"formattedStartDts" => $formatted_start_dts,
-					"formattedDueDts" => $formatted_due_dts,
-					"tester" => null,
-					"pastDue" => $past_due,
-				];
+		// Process test
+		$test = $this->locationTests[$location->id] ?? null;
 
-				if($project) {
-					$data["test"]["project"] = [
-						"id" => (int) $project->id,
-						"name" => $project->name,
-					];
-				}
+		if($test) {
+			$tester = $test->getTester();
+			$project = $test->getProject();
 
-				if($tester) {
-					$data["test"]["tester"] = [
-						"id" => (int) $tester->id,
-						"name" => $tester->getDisplayName(),
-					];
+			if($test->dts_start !== null) {
+				$unix_start = strtotime($test->dts_start);
+				$formatted_start_dts = date("d/m/Y H:i", $unix_start);
+			}
+
+			if($test->pass === null) {
+				$icon_file = "{$customer_slug}_pending.png";
+
+				// Has due date
+				if($test->dts_due !== null) {
+					$unix_due = strtotime($test->dts_due);
+					$formatted_due_dts = date("d/m/Y H:i", $unix_due);
+
+					if($tester && time() > $unix_due) {
+						$icon_file = "{$customer_slug}_past_due.png";
+						$past_due = true;
+					}
 				}
+
+			}
+			else if($test->pass) {
+				$icon_file = "{$customer_slug}_pass.png";
+			}
+			else if(!$test->pass) {
+				$icon_file = "{$customer_slug}_fail.png";
 			}
+		}
 
-			$output[] = $data;
+		if(file_exists("public/img/markers/$icon_file")) {
+			$icon = $icon_file;
 		}
 
-		JSON::success([
-			"name" => $address->name,
-			"latitude" => (double) $address->latitude,
-			"longitude" => (double) $address->longitude,
-			"locations" => $output
-		]);
+		$data = [
+			"id" => (int) $location->id,
+			"internalId" => (int) $location->internal_id,
+			"name" => $location->name,
+			"address" => $location->getDisplayAddress(),
+			"distance" => $distance,
+			"latitude" => (double) $location->latitude,
+			"longitude" => (double) $location->longitude,
+			"icon" => $icon,
+			"customer" => [
+				"id" => $customer->id,
+				"name" => $customer->name,
+			],
+			"test" => null,
+		];
+
+		if($test) {
+			$data["test"] = [
+				"id" => (int) $test->id,
+				"pass" => $test->pass !== null ? (int) $test->pass : null,
+				"formattedStartDts" => $formatted_start_dts,
+				"formattedDueDts" => $formatted_due_dts,
+				"tester" => null,
+				"pastDue" => $past_due,
+			];
+
+			if($project) {
+				$data["test"]["project"] = [
+					"id" => (int) $project->id,
+					"name" => $project->name,
+				];
+			}
+
+			if($tester) {
+				$data["test"]["tester"] = [
+					"id" => (int) $tester->id,
+					"name" => $tester->getDisplayName(),
+				];
+			}
+		}
 
+		return $data;
+	}
+
+
+};
+
+
+switch($action) {
+	case "get-addresses":
+		$controller->getAddresses();
+		break;
+
+	case "get-locations":
+		$controller->getLocations();
+		break;
 
+	case "get-assigned-locations":
+		$controller->getAssignedLocations();
 		break;
 }

+ 98 - 62
public/js/app-user.js

@@ -4,7 +4,7 @@ var locationsInitialised = false;
 var addressMarkers = [];
 var locationMarkers = [];
 
-var infoWindow = false;
+var infoWindow = null;
 
 $(function() {
 	$("[data-toggle=tab]").on("shown.bs.tab", function(event) {
@@ -14,8 +14,12 @@ $(function() {
 			initialiseAddresses();
 		}
 
-		if(event.target.id === "nearby-locations-tab" && locationsInitialised === false) {
-			initialiseLocations();
+		if(event.target.id === "tests-tab") {
+			refreshTestLocations();
+		}
+
+		if(event.target.id === "nearby-locations-tab") {
+			refreshNearbyLocations();
 		}
 
 		const id = $tab.attr("id");
@@ -30,7 +34,7 @@ $(function() {
 	}
 
 	$("#address-id").on("change", function() {
-		initialiseLocations();
+		refreshNearbyLocations();
 	});
 
 	$("#date-range").daterangepicker({
@@ -45,10 +49,10 @@ $(function() {
 		$("#date-start").val(startValue);
 		$("#date-end").val(endValue);
 
-		initialiseLocations();
+		refreshNearbyLocations();
 	});
 
-	$("#pending-tests").on("change", () => initialiseLocations());
+	$("#pending-tests").on("change", () => refreshNearbyLocations());
 
 	$("#delete-address-form button[type=submit]").on("click", event => {
 		const confirmed = confirm("Are you sure you want to delete this address?");
@@ -78,17 +82,14 @@ function initialiseAddresses() {
 				lng: address.longitude
 			};
 
-			let options = {
+			bounds.extend(position);
+
+			let marker = new google.maps.Marker({
 				map: map,
 				position: position,
 				title: address.name,
 				icon: "/img/markers/address.png"
-			};
-
-			bounds.extend(position);
-
-			let marker = new google.maps.Marker(options);
-
+			});
 		}
 
 		map.fitBounds(bounds);
@@ -97,20 +98,50 @@ function initialiseAddresses() {
 
 }
 
-function initialiseLocations() {
-
-	if(infoWindow === false) {
+function clearMaps() {
+	if(infoWindow === null) {
 		infoWindow = new google.maps.InfoWindow();
 	}
 
-	for(var i in locationMarkers) {
-		if(!locationMarkers.hasOwnProperty(i)) continue;
-		let marker = locationMarkers[i];
+	locationMarkers.forEach(marker => {
 		marker.setMap(null);
 		marker = null;
-	}
+	});
 
 	locationMarkers = [];
+}
+
+function refreshTestLocations() {
+	clearMaps();
+
+	let map = maps["assigned-tests-map"];
+	if(!map) {
+		return;
+	}
+
+	$.get("/api/users/" + userId + "/get-assigned-locations", response => {
+		if(!response.success) return false;
+		if(!response.locations) return false;
+
+		let bounds = new google.maps.LatLngBounds();
+
+		// Extend bounds for locations
+		response.locations.forEach(location => {
+			bounds.extend({
+				lat: location.latitude,
+				lng: location.longitude
+			});
+		});
+
+		// Add locations to map
+		addLocationsToMap(response.locations, map);
+
+		map.fitBounds(bounds);
+	});
+}
+
+function refreshNearbyLocations() {
+	clearMaps();
 
 	$("#nearby-locations-list-group").empty();
 
@@ -125,7 +156,7 @@ function initialiseLocations() {
 		if(!response.success) return false;
 		if(!response.locations) return false;
 
-		let bounds = new google.maps.LatLngBounds;
+		let bounds = new google.maps.LatLngBounds();
 
 		// User Address
 		let position = {
@@ -133,48 +164,29 @@ function initialiseLocations() {
 			lng: response.longitude
 		};
 
-		let options = {
+		bounds.extend(position);
+
+		let marker = new google.maps.Marker({
 			map: map,
 			position: position,
 			title: response.name,
 			icon: "/img/markers/address.png"
-		};
-
-		bounds.extend(position);
-
-		let marker = new google.maps.Marker(options);
+		});
 		locationMarkers.push(marker);
 
-		// Locations
-
-		for(let i in response.locations) {
-			if(!response.locations.hasOwnProperty(i)) continue;
-
-			let location = response.locations[i];
-			let position = {
+		// Extend bounds for locations
+		response.locations.forEach(location => {
+			bounds.extend({
 				lat: location.latitude,
 				lng: location.longitude
-			};
-
-			let options = {
-				map: map,
-				position: position,
-				title: location.name
-			};
-
-			if(location.icon) options.icon = "/img/markers/" + location.icon;
-			else options.icon = "/img/markers/building-red.png";
-
-			bounds.extend(position);
+			});
+		});
 
-			let marker = new google.maps.Marker(options);
-
-			locationMarkers.push(marker);
-
-			if(location.internalId == 0) {
-				location.internalId = "N/A";
-			}
+		// Add locations to map
+		addLocationsToMap(response.locations, map);
 
+		// Add locations to nearby locations list group
+		response.locations.forEach(location => {
 
 			// Add to list group
 			let lgi = $("div[data-nearby-location-list-group-item-template]").clone();
@@ -227,15 +239,10 @@ function initialiseLocations() {
 					lgi.find("div[data-test-pass-container] span").addClass("text-" + passClass).text(passText);
 
 				}
-
-
 			}
 
 			lgi.appendTo("#nearby-locations-list-group").show();
-
-			addMarkerClickListenerForLocation(marker, location);
-
-		}
+		});
 
 		map.fitBounds(bounds);
 
@@ -243,10 +250,39 @@ function initialiseLocations() {
 
 }
 
-function addMarkerClickListenerForLocation(marker, location) {
+function addLocationsToMap(locations, map) {
+	locations.forEach(location => {
+		let position = {
+			lat: location.latitude,
+			lng: location.longitude
+		};
 
-	let map = maps["map"];
+		let options = {
+			map: map,
+			position: position,
+			title: location.name
+		};
 
+		if(location.icon) {
+			options.icon = "/img/markers/" + location.icon;
+		}
+		else {
+			options.icon = "/img/markers/building-red.png";
+		}
+
+		let marker = new google.maps.Marker(options);
+
+		locationMarkers.push(marker);
+
+		if(location.internalId == 0) {
+			location.internalId = "N/A";
+		}
+
+		addMarkerClickListenerForLocation(marker, location);
+	});
+}
+
+function addMarkerClickListenerForLocation(marker, location) {
 	marker.addListener("click", function() {
 		let content = "<strong><a href=\"/account/locations/" + location.id + "\" target=\"_blank\">" + location.name + "</a></strong><br />";
 		if(location.internalId) {
@@ -282,7 +318,7 @@ function addMarkerClickListenerForLocation(marker, location) {
 		}
 
 		infoWindow.setContent(content);
-		infoWindow.open(map, marker);
+		infoWindow.open(marker.getMap(), marker);
 	});
 
 }

+ 1 - 1
routes.php

@@ -116,7 +116,7 @@ $routes = [
 	"/^account\/users\/$id_pattern\/(id-document|photo)$/" => ["controller" => "user_verify_image", "params" => ["id", "type"], "require_user_level" => User::LEVEL_TESTER_MANAGER],
 	"/^account\/users\/$id_pattern\/(toggle-archived)$/" => ["controller" => "user_action", "params" => ["id", "action"], "require_user_level" => User::LEVEL_TESTER_MANAGER],
 
-	"/^api\/users\/$id_pattern\/(get-addresses|get-locations)$/" => ["controller" => "user_ajax", "params" => ["id", "action"], "require_user_level" => User::LEVEL_TESTER_MANAGER],
+	"/^api\/users\/$id_pattern\/(get-addresses|get-locations|get-assigned-locations)$/" => ["controller" => "user_ajax", "params" => ["id", "action"], "require_user_level" => User::LEVEL_TESTER_MANAGER],
 
 	// Locations
 	"/^account\/locations$/" => ["controller" => "locations", "require_user_level" => User::LEVEL_CUSTOMER],

+ 4 - 0
views/user.php

@@ -229,7 +229,11 @@ const userId = <?=$user->id?>;
 					<?php
 				}
 				else {
+					$first_location = $pending_tests[0]->getLocation();
 					?>
+					<div class="mb-3" id="assigned-tests-map" style="height: 480px;" data-maps data-lat="<?=$first_location->latitude?>" data-lng="<?=$first_location->longitude?>" data-zoom="10">
+					</div>
+
 					<table class="table table-sm table-hover">
 						<col style="width: 10%;" />
 						<col style="width: 40%;" />