Selaa lähdekoodia

Add ability to archive users

Alan Lam 4 vuotta sitten
vanhempi
commit
fdbb29e2f1

+ 34 - 21
controllers/project_ajax.php

@@ -111,14 +111,14 @@ if($submit) {
 				$status_constraint = new Constraint("MORE_THAN_OR_EQUAL");
 				$status_constraint->setValues(Test::STATUS_UNASSIGNED);
 
-				$nvp = [
+				$test = Test::queryOne([
 					"location_id" => $location_id,
 					"project_id" => $project->id,
 					"status" => $status_constraint,
-				];
-
-				$test = Test::queryOne($nvp);
-				if(!$test) throw new Exception("A test does not exist for this project.");
+				]);
+				if(!$test) {
+					throw new RuntimeException("A test does not exist for this project.");
+				}
 
 				/*
 				$max_distance = http::value("max_distance", "int");
@@ -140,12 +140,10 @@ if($submit) {
 				$lng_constraint = new Constraint("BETWEEN");
 				$lng_constraint->setValues($bounds->southWest[1], $bounds->northEast[1]);
 
-				$nvp = [
+				$addresses = UserAddress::query([
 					"latitude" => $lat_constraint,
 					"longitude" => $lng_constraint
-				];
-
-				$addresses = UserAddress::query($nvp);
+				]);
 
 				$users = User::load(array_column($addresses, "user_id"));
 				$user_last_tests = Test::query([
@@ -157,7 +155,9 @@ if($submit) {
 				foreach($user_last_tests as $user_last_test) {
 					$unix_start = strtotime($user_last_test->dts_start . " UTC");
 					$current_start = $user_last_test_times[$user_last_test->tester_id] ?? 0;
-					if($unix_start > $current_start) $user_last_test_times[$user_last_test->tester_id] = $unix_start;
+					if($unix_start > $current_start) {
+						$user_last_test_times[$user_last_test->tester_id] = $unix_start;
+					}
 				}
 
 				$pending_tests = Test::query([
@@ -165,7 +165,8 @@ if($submit) {
 					"status" => Test::STATUS_ASSIGNED,
 				]);
 
-				usort($addresses, function($a, $b) use ($location) {
+				// Sort by distance to location
+				usort($addresses, static function($a, $b) use ($location) {
 					$lat_lng = $location->getGeolocation();
 					return Geolocation::getDistance($lat_lng, $a->getGeolocation()) <=> Geolocation::getDistance($lat_lng, $b->getGeolocation());
 				});
@@ -176,21 +177,33 @@ if($submit) {
 					$user = $address->getUser();
 
 					$is_current_tester = $user->id == $test->tester_id;
-					$is_deactivated = $user->level == User::LEVEL_DEACTIVATED;
-					$is_registered = $user->level == User::LEVEL_REGISTERED;
 					$is_unverified = $user->level <= User::LEVEL_UNVERIFIED;
-					$is_tester = $user->isTester();
 
-					if($is_deactivated) continue;
-					if(!$include_unverified && $is_unverified) continue;
-					if(!$is_tester) continue;
-					if($user->score < $minimum_score) continue;
+					if($user->isArchived()) {
+						continue;
+					}
+
+					if($user->isDeactivated()) {
+						continue;
+					}
+
+					if(!$include_unverified && $user->isUnverified()) {
+						continue;
+					}
+
+					if(!$user->isTester()) {
+						continue;
+					}
+
+					if($user->score < $minimum_score) {
+						continue;
+					}
 
 					$distance_miles = Geolocation::getDistance($location->getGeolocation(), $address->getGeolocation());
 					$distance_kilometers = $distance_miles * Geolocation::KMS_IN_MILE;
 
-					$user_pending_tests = array_filter($pending_tests, function($test) use ($user) {
-						return ($user->id == $test->tester_id);
+					$user_pending_tests = array_filter($pending_tests, static function($test) use ($user) {
+						return ((int) $user->id === (int) $test->tester_id);
 					});
 					$pending_test_count = count($user_pending_tests);
 
@@ -227,7 +240,7 @@ if($submit) {
 						"longitude" => (float) $address->longitude,
 						"pendingTestCount" => $pending_test_count,
 						"isCurrentTester" => $is_current_tester,
-						"isRegistered" => $is_registered,
+						"isRegistered" => $user->isRegistered(),
 						"isUnverified" => $is_unverified,
 						"levelText" => $user->getLevelText(),
 						"levelClass" => $user->getLevelClass(),

+ 41 - 0
controllers/user_action.php

@@ -0,0 +1,41 @@
+<?php
+
+/**
+ * @var int $id
+ * @var string $action
+ */
+
+$controller = new class($id) {
+
+	/** @var User */
+	private $user;
+
+	public function __construct(int $id) {
+		$this->user = User::get($id);
+	}
+
+	public function toggleArchived(): void {
+		if($this->user->archived) {
+			$this->user->archived = 0;
+			Core::addAlert("success", __("User unarchived successfully."));
+		}
+		else {
+			$this->user->archived = 1;
+			Core::addAlert("success", __("User archived successfully."));
+		}
+
+		$this->user->commit();
+
+		Http::redirect($this->user->getURL());
+	}
+};
+
+switch($action) {
+	case "toggle-archived":
+		$controller->toggleArchived();
+		break;
+
+	default:
+		throw new RuntimeException(__("Invalid action."));
+}
+

+ 19 - 6
controllers/users.php

@@ -1,4 +1,4 @@
-<?php
+<?php /** @noinspection PhpUnhandledExceptionInspection */
 
 if(Core::$user->level == User::LEVEL_SUPERADMIN) {
 	$page_title = "Users";
@@ -18,6 +18,8 @@ $sorts = [
 $id = http::value("id", "int");
 $first_name = http::value("first_name", "trim");
 $last_name = http::value("last_name", "trim");
+$archived = Http::value("archived", "int") ?? 0;
+
 $email = http::value("email", "trim");
 $level = http::value("level", "int");
 
@@ -30,9 +32,22 @@ if(strlen($first_name) > 0) $nvp["first_name"] = ((new Constraint("CONTAINS"))->
 if(strlen($last_name) > 0) $nvp["last_name"] = ((new Constraint("CONTAINS"))->setValues($last_name));
 if(strlen($email) > 0) $nvp["email"] = $email;
 if($level !== null) $nvp["level"] = $level;
+if(!$archived) $nvp["archived"] = 0;
+
+$filter_count = null;
+if($nvp) {
+	$filter_count = count(array_keys($nvp));
+}
+if(!$archived) {
+	$filter_count--;
+}
+else {
+	$filter_count++;
+}
 
-$filter_count = "";
-if($nvp) $filter_count = count(array_keys($nvp));
+if($filter_count === 0) {
+	$filter_count = null;
+}
 
 if(empty($nvp)) {
 	$nvp["level"] = (new Constraint("NOT_EQUALS"))->setValues(User::LEVEL_REGISTERED);
@@ -60,8 +75,6 @@ $users = array_slice($users, $pagination_object->offset, $pagination_object->pag
 
 
 View::includeOnce("header", compact("page_title"));
-View::include("users", compact("users", "pagination_object", "filter_count", "id", "first_name", "last_name", "email", "level", "customer_id", "location_id", "sort", "sorts"));
+View::include("users", compact("users", "pagination_object", "filter_count", "id", "first_name", "last_name", "archived", "email", "level", "customer_id", "location_id", "sort", "sorts"));
 View::includeOnce("modal_page_jump");
 View::includeOnce("footer");
-
-?>

+ 11 - 0
db/migrations/20221130204216_add_archived_field_to_user_table.php

@@ -0,0 +1,11 @@
+<?php
+
+use Phinx\Migration\AbstractMigration;
+
+class AddArchivedFieldToUserTable extends AbstractMigration {
+	public function change() {
+		$this->table("user")
+			->addColumn("archived", "boolean", ["signed" => false, "default" => 0, "after" => "activated"])
+			->update();
+	}
+}

+ 26 - 0
engine/html_helper.php

@@ -0,0 +1,26 @@
+<?php
+
+class HtmlHelper {
+
+	public static function selected(?string $value, ?string $selected): string {
+		return ((string) $value === (string) $selected) ? "selected" : "";
+	}
+
+	public static function renderOptions(array $options, ?string $selected): void {
+		foreach($options as $value => $display) {
+			?>
+			<option value="<?=$value?>" <?=self::selected($value, $selected)?>>
+				<?=htmlspecialchars($display)?>
+			</option>
+			<?php
+		}
+	}
+
+	public static function getYesNoOptions(): array {
+		return [
+			1 => __("Yes"),
+			0 => __("No")
+		];
+	}
+
+}

+ 3 - 2
engine/http.php

@@ -91,7 +91,6 @@ class HTTP {
 		$array = [];
 
 		switch($request_type) {
-
 			case "request":
 				$array = $_REQUEST;
 				break;
@@ -105,7 +104,9 @@ class HTTP {
 				trigger_error("http::value called with \"$request_type\" request_type", E_USER_ERROR);
 		}
 
-		if(!isset($array[$key])) return null;
+		if(!isset($array[$key])) {
+			return null;
+		}
 
 		$value = $array[$key];
 

+ 7 - 2
engine/user.php

@@ -11,6 +11,7 @@ use Carbon\CarbonImmutable;
  * @property int $referrer_id
  * @property string $password
  * @property bool $activated
+ * @property bool $archived
  * @property int $level
  * @property int $score
  * @property string $title
@@ -44,7 +45,7 @@ class User extends Model {
 
 	protected static $table = "user";
 	protected static $id_field = "id";
-	protected static $fillable_fields = ["email", "old_id", "referrer_id", "password", "activated", "level", "score", "title", "first_name", "last_name", "gender", "date_of_birth", "locale", "reported", "reported_comment", "can_claim", "phone", "verify_token", "reset_token", "terms_accepted", "newsletter_consent", "preferred_payment_method", "bank_name", "bank_sort_code", "bank_account_number", "paypal_email", "dts_registered", "dts_last_seen", "dts_verified", "dts_deleted", "verifier_id", "verifier_notes"];
+	protected static $fillable_fields = ["email", "old_id", "referrer_id", "password", "activated", "archived", "level", "score", "title", "first_name", "last_name", "gender", "date_of_birth", "locale", "reported", "reported_comment", "can_claim", "phone", "verify_token", "reset_token", "terms_accepted", "newsletter_consent", "preferred_payment_method", "bank_name", "bank_sort_code", "bank_account_number", "paypal_email", "dts_registered", "dts_last_seen", "dts_verified", "dts_deleted", "verifier_id", "verifier_notes"];
 
 	// Constants
 	const LEVEL_BANNED = 0;
@@ -656,7 +657,7 @@ class User extends Model {
 	}
 
 	public function isUnverified() {
-		return $this->level == User::LEVEL_UNVERIFIED;
+		return $this->level <= User::LEVEL_UNVERIFIED;
 	}
 
 	public function isRegistered() {
@@ -768,4 +769,8 @@ class User extends Model {
 		return CarbonImmutable::parse($this->date_of_birth);
 	}
 
+	public function isArchived(): bool {
+		return $this->archived;
+	}
+
 }

+ 9 - 2
engine/user_address.php

@@ -29,9 +29,16 @@ class UserAddress extends Model {
 		"0.25", "0.50", "1.00", "1.50", "2.00", "2.50", "3.00", "4.00", "5.00", "7.50", "10.00", "12.50", "15.00", "20.00", "25.00",
 	];
 
-	// Static method
+	// Static methods
+
+	/**
+	 * @param int $id
+	 * @param User $user
+	 * @return object|UserAddress|null
+	 * @throws Exception
+	 */
 	public static function getByUser(int $id, User $user) {
-		return UserAddress::queryOne([
+		return self::queryOne([
 			"id" => $id,
 			"user_id" => $user->id
 		]);

+ 1 - 0
routes.php

@@ -114,6 +114,7 @@ $routes = [
 	"/^account\/users\/$id_pattern\/verify$/" => ["controller" => "user_verify", "params" => ["id"], "require_user_level" => User::LEVEL_TESTER_MANAGER],
 	"/^account\/users\/$id_pattern\/verify\/(id-document|photo)$/" => ["controller" => "user_verify_image", "params" => ["id", "type"], "require_user_level" => User::LEVEL_TESTER_MANAGER],
 	"/^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],
 

+ 13 - 0
views/user.php

@@ -44,6 +44,8 @@ $min_date_localised = $dt->format("d/m/Y");
 
 $date_range = "{$min_date_localised} - {$max_date_localised}";
 
+$archive_text = $user->isArchived() ? __("Unarchive") : __("Archive");
+
 ?>
 <script>
 const userId = <?=$user->id?>;
@@ -54,6 +56,15 @@ const userId = <?=$user->id?>;
 		<div class="col">
 			<h2>
 				<?=htmlspecialchars($user->getDisplayName())?>
+				<?php
+				if($user->isArchived()) {
+					?>
+					<span class="badge badge-secondary">
+						<?=htmlspecialchars(__("Archived"))?>
+					</span>
+					<?php
+				}
+				?>
 			</h2>
 		</div>
 		<div class="col-auto text-right">
@@ -79,6 +90,8 @@ const userId = <?=$user->id?>;
 							<?php
 						}
 						?>
+						<a href="<?=htmlspecialchars($user->getURL())?>/toggle-archived" class="dropdown-item"><?=htmlspecialchars($archive_text)?></a>
+						<div class="dropdown-divider"></div>
 						<button class="dropdown-item" type="submit" name="action" value="send_documentation_email"><?=htmlspecialchars(__("Send Documentation Email"))?></button>
 					</div>
 

+ 41 - 18
views/users.php

@@ -1,9 +1,24 @@
-<?php
+<?php /** @noinspection PhpUnhandledExceptionInspection */
+
+/**
+ * @var array $sorts
+ * @var int $filter_count
+ * @var string $sort
+ * @var string $first_name
+ * @var string $last_name
+ * @var int $archived
+ * @var int $id
+ * @var int $level
+ * @var string $email
+ * @var object $pagination_object
+ */
 
 $query = $_GET;
 unset($query["path"]);
 $query["sort"] = "SORT";
 
+$filter_show = $filter_count > 0 ? "show" : "";
+
 ?>
 <div class="container mt-3 py-4">
 	<div class="row">
@@ -36,18 +51,13 @@ $query["sort"] = "SORT";
 				<div class="col">
 					<div class="input-group">
 						<div class="input-group-prepend">
-							<span class="input-group-text">
+							<label for="sort-dropdown" class="input-group-text">
 								Sort
-							</span>
+							</label>
 						</div>
 						<select class="form-control" id="sort-dropdown" data-url-template="/account/users?<?=htmlspecialchars(http_build_query($query))?>">
 						<?php
-						foreach($sorts as $value => $display) {
-							$selected = ($value == $sort) ? "selected" : "";
-							?>
-							<option value="<?=$value?>" <?=$selected?>><?=$display?></option>
-							<?php
-						}
+						HtmlHelper::renderOptions($sorts, $sort);
 						?>
 						</select>
 					</div>
@@ -56,7 +66,7 @@ $query["sort"] = "SORT";
 		</div>
 	</div>
 
-	<div class="row mb-3">
+	<div class="form-row mb-3">
 		<div class="col">
 			<a class="btn btn-block btn-primary" href="/account/users">All except Registered</a>
 		</div>
@@ -71,7 +81,7 @@ $query["sort"] = "SORT";
 		</div>
 	</div>
 
-	<div class="collapse" id="filters">
+	<div class="collapse <?=$filter_show?>" id="filters">
 		<div class="card card-body mb-3 bg-light text-dark">
 			<h3>Filters</h3>
 			<form method="get">
@@ -91,6 +101,17 @@ $query["sort"] = "SORT";
 								<input class="form-control" type="text" name="last_name" id="last-name" placeholder="Enter last name" value="<?=htmlspecialchars($last_name)?>" />
 							</div>
 						</div>
+
+						<div class="row mb-1">
+							<label class="col-sm-4 col-form-label" for="archived">Include Archived</label>
+							<div class="col-sm">
+								<select class="form-control" name="archived" id="archived">
+									<?php
+									HtmlHelper::renderOptions(HtmlHelper::getYesNoOptions(), $archived);
+									?>
+								</select>
+							</div>
+						</div>
 					</div>
 					<div class="col-lg">
 
@@ -107,12 +128,7 @@ $query["sort"] = "SORT";
 								<select class="form-control" name="level" id="level">
 									<option value="">Any except Registered</option>
 									<?php
-									foreach(User::LEVELS as $value => $display) {
-										$selected = ($value === $level) ? "selected" : "";
-										?>
-										<option value="<?=$value?>" <?=$selected?>><?=htmlspecialchars($display)?></option>
-										<?php
-									}
+									HtmlHelper::renderOptions(User::LEVELS, $level);
 									?>
 								</select>
 							</div>
@@ -129,6 +145,7 @@ $query["sort"] = "SORT";
 				<div class="row">
 					<div class="col-sm text-center">
 						<button class="btn btn-primary" type="submit">Filter</button>
+						<a class="btn btn-secondary" href="/account/users"><?=htmlspecialchars(__("Reset"))?></a>
 					</div>
 				</div>
 
@@ -136,7 +153,6 @@ $query["sort"] = "SORT";
 		</div>
 	</div>
 
-
 	<?php
 	if(empty($users)) {
 		?>
@@ -177,6 +193,13 @@ $query["sort"] = "SORT";
 					<td class="align-middle">
 						<a href="/account/users/<?=$user->id?>"><?=htmlspecialchars($user->getDisplayName())?></a>
 						<?php
+						if($user->isArchived()) {
+							?>
+							<span class="badge badge-secondary">
+								<?=htmlspecialchars(__("Archived"))?>
+							</span>
+							<?php
+						}
 						if($user->reported) {
 							$comment = $user->reported_comment ?: "Reported";
 							?>