Sfoglia il codice sorgente

Adds support for practice tests.

Alan Lam 8 anni fa
parent
commit
c27c99b18a

+ 1 - 0
controllers/account.php

@@ -29,6 +29,7 @@ if(Core::$user->level >= User::LEVEL_CUSTOMER) {
 
 if(Core::$user->level >= User::LEVEL_TESTER) {
 	$links["/account/tests"] = "Tests";
+	$links["/account/practice"] = "Practice";
 }
 
 if(Core::$user->level == User::LEVEL_TESTER) {

+ 175 - 0
controllers/practice.php

@@ -0,0 +1,175 @@
+<?php
+
+Core::addScript("public/js/app-test.js");
+
+$template = Template::get($id);
+if(!$template) throw new Exception("Practice form not found.");
+if(!$template->practice) throw new Exception("This practice form is no longer available.");
+
+$page_title = "Practice";
+
+Core::addBreadcrumb("/account/practice", $page_title);
+Core::addBreadcrumb("/account/practice/$id", "Form");
+
+$json = json_decode($template->json);
+
+// Reset
+$reset = http::value("reset");
+
+$tests = $_SESSION["practice_tests"] ?? [];
+$test = $tests[$id] ?? false;
+if(!$test || $reset) {
+	$test = new PracticeTest;
+	$test->tester_id = Core::$user->id;
+	$test->status = Test::STATUS_CONFIRMED;
+	$tests[$id] = $test;
+	$_SESSION["practice_tests"] = $tests;
+
+	if($reset) {
+		// Force redirect if resetting
+		http::redirect("/account/practice/$id");
+	}
+
+}
+
+$is_confirmed = $test->status == Test::STATUS_CONFIRMED;
+$is_started = $test->status == Test::STATUS_STARTED;
+$is_unverified = $test->status == Test::STATUS_PENDING_VERIFICATION;
+
+$submit = http::value("submit");
+if($submit) {
+
+	$previous_timezone = date_default_timezone_get();
+
+	date_default_timezone_set("UTC");
+
+	try {
+		Core::validateCSRFToken($submit);
+
+		$form_exception = new FormException;
+
+		if($is_confirmed) {
+			// Parse before the test form
+			$fields = $json->beforeTest;
+
+		}
+
+		if($is_started || $is_unverified) {
+			// Parse after the test form
+			$fields = $json->duringTest;
+
+			if($is_started) {
+				$duration = http::value("duration", "int");
+				if(!$duration) $form_exception->addError("Duration was not submitted.");
+			}
+		}
+
+		foreach($fields as $field) {
+
+			$name = $field->name ?? false;
+			if(empty($name)) continue; // Not a field
+
+			$label = $field->label ?? "";
+			$type = $field->type;
+			$required = $field->required ?? false;
+			$values = $field->values ?? [];
+
+			if($type == "file") {
+				$file = (object) $_FILES[$name];
+
+				try {
+					if(!$required && $file->error == UPLOAD_ERR_NO_FILE) continue;
+					if($required && $file->error == UPLOAD_ERR_NO_FILE) {
+						throw new Exception("$label is required.");
+					}
+
+					// Detect upload error
+					if($file->error != UPLOAD_ERR_OK) throw new Exception(HTTP::getUploadErrorString($file->error));
+
+					// Get image details
+					$size = @getimagesize($file->tmp_name);
+					if(!$size) throw new Exception("The uploaded file for $label is not an image.");
+					list($width, $height, $type) = $size;
+					if($type != IMAGETYPE_JPEG) throw new Exception("The uploaded file for $label is not a JPEG.");
+
+					// Resize image
+					$output_image = Image::normalise($file->tmp_name);
+
+					// Write image to disk
+					$output_path = $test->getDirectory() . "/" . $name . ".jpg";
+
+					imagejpeg($output_image, $output_path, 60);
+					imagedestroy($output_image);
+				}
+				catch(Exception $e) {
+					$form_exception->addError($e->getMessage());
+				}
+			}
+			else {
+				$value = http::value($name, "trim");
+
+				if($required && empty($value)) $form_exception->addError("$label is required.");
+				if($values && !in_array($value, $values)) $form_exception->addError("Value for $label is invalid.");
+
+				if(in_array($name, Test::TEST_FIELDS)) {
+					$test->$name = $value;
+				}
+				else {
+					$test->setValue($name, $value);
+				}
+			}
+		}
+
+		if($form_exception->hasErrors()) throw $form_exception;
+
+		// Before the Test
+		if($is_confirmed) {
+			$test->status = Test::STATUS_STARTED;
+			$test->dts_start = Util::getDateTime();
+			$test->dts_updated = Util::getDateTime();
+			$tests[$id] = $test;
+			$_SESSION["practice_tests"] = $tests;
+			HTTP::redirect("/account/practice/$id");
+		}
+
+		// During the test
+		if($is_started || $is_unverified) {
+			$test->status = Test::STATUS_PENDING_VERIFICATION;
+
+			if($is_started) {
+				$unix_start = strtotime($test->dts_start);
+				$unix_end = $unix_start + floor($duration / 1000); // $duration is milliseconds
+
+				$test->dts_end = date("Y-m-d H:i:s", $unix_end);
+			}
+
+			$test->pass = ($test->challenge_stage <= 2) ? 1 : 0; // Pass = Challenged during browsing or before
+			$test->dts_updated = Util::getDateTime();
+
+			$tests[$id] = $test;
+			$_SESSION["practice_tests"] = $tests;
+
+			JSON::success();
+		}
+
+	}
+	catch(FormException $e) {
+		$e->generateAlerts();
+	}
+	catch(Exception $e) {
+		Core::addAlert("danger", $e->getMessage());
+	}
+
+	date_default_timezone_set($previous_timezone);
+}
+
+if($is_unverified) {
+	$json = json_decode($template->json);
+	$fields = array_merge($json->beforeTest, $json->duringTest);
+}
+
+View::includeOnce("header", compact("page_title"));
+View::include("practice_form", compact("test", "template", "fields"));
+View::includeOnce("footer");
+
+?>

+ 27 - 0
controllers/practice_file.php

@@ -0,0 +1,27 @@
+<?php
+
+$template = Template::get($id);
+if(!$template) throw new Exception("Practice form not found.");
+
+$tests = $_SESSION["practice_tests"];
+$test = $tests[$id] ?? false;
+if(!$test) throw new Exception("Practice test not found.");
+
+
+if(Core::$user->level < User::LEVEL_ADMIN) {
+	if(Core::$user->id != $test->tester_id) throw new Exception("You do not have permission to access this resource.");
+}
+
+$directory = $test->getDirectory();
+$path = $directory . "/" . $name . ".jpg";
+
+if(file_exists($path)) {
+	header("Content-Type: image/jpeg");
+	readfile($path);
+}
+else {
+	header("Content-Type: image/png");
+	readfile("public/img/blank.png");
+}
+
+?>

+ 16 - 0
controllers/practice_template_select.php

@@ -0,0 +1,16 @@
+<?php
+
+$page_title = "Select Practice Form";
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/practice", $page_title);
+
+$templates = Template::query([
+	"practice" => 1
+]);
+
+View::includeOnce("header", compact("page_title"));
+View::include("practice_template_select", compact("templates"));
+View::includeOnce("footer");
+
+?>

+ 2 - 1
controllers/template_add.php

@@ -25,6 +25,7 @@ if($submit) {
 
 		$template->name = http::value("name", "trim");
 		$template->json = http::value("json", "trim");
+		$template->practice = http::value("practice", "int");
 
 		if(empty($template->name)) $form_exception->addError("Name is required.");
 		if(empty($template->json)) $form_exception->addError("JSON is required.");
@@ -50,7 +51,7 @@ if($submit) {
 }
 
 View::includeOnce("header", compact("page_title"));
-View::include("template_add_form", compact("template"));
+View::include("template_form", compact("page_title", "template"));
 View::includeOnce("footer");
 
 ?>

+ 54 - 0
controllers/template_edit.php

@@ -0,0 +1,54 @@
+<?php
+
+$template = Template::get($id);
+if(!$template) throw new Exception("Template not found.");
+
+$customer = $template->getCustomer();
+
+$page_title = "Edit Template";
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/templates", "Templates");
+Core::addBreadcrumb("/account/templates?customer_id=$customer->id", "$customer->name Templates");
+Core::addBreadcrumb("/account/templates/$id", $template->name);
+Core::addBreadcrumb($_SERVER["REQUEST_URI"], $page_title);
+
+$submit = http::value("submit");
+if($submit) {
+	try {
+		Core::validateCSRFToken($submit);
+
+		$form_exception = new FormException;
+
+		$template->name = http::value("name", "trim");
+		$template->json = http::value("json", "trim");
+		$template->practice = http::value("practice", "int");
+
+		if(empty($template->name)) $form_exception->addError("Name is required.");
+		if(empty($template->json)) $form_exception->addError("JSON is required.");
+
+		$json = json_decode($template->json);
+		if(!$json) {
+			$form_exception->addError("JSON error: " . json_last_error_msg());
+		}
+
+		if($form_exception->hasErrors()) throw $form_exception;
+
+		$success = $template->commit();
+
+		Core::addAlert("success", "Template updated successfully.");
+		HTTP::redirect("/account/templates/$id/edit");
+	}
+	catch(FormException $e) {
+		$e->generateAlerts();
+	}
+	catch(Exception $e) {
+		Core::addAlert("danger", $e->getMessage());
+	}
+}
+
+View::includeOnce("header", compact("page_title"));
+View::include("template_form", compact("page_title", "template"));
+View::includeOnce("footer");
+
+?>

+ 2 - 4
controllers/test.php

@@ -20,8 +20,6 @@ Core::addBreadcrumb("/account", "Account");
 Core::addBreadcrumb("/account/tests", "Tests");
 Core::addBreadcrumb("/account/tests/$id", $page_title);
 
-$fillable_fields = ["shop_left", "shop_right", "attire", "challenge_stage", "challenge_description", "challenger_name", "challenger_description", "challenger_gender", "challenger_eye_contact", "additional_notes"];
-
 // Do test
 if(Core::$user->level == User::LEVEL_TESTER) {
 
@@ -116,7 +114,7 @@ if(Core::$user->level == User::LEVEL_TESTER) {
 					if($required && empty($value)) $form_exception->addError("$label is required.");
 					if($values && !in_array($value, $values)) $form_exception->addError("Value for $label is invalid.");
 
-					if(in_array($name, $fillable_fields)) {
+					if(in_array($name, Test::TEST_FIELDS)) {
 						$test->$name = $value;
 					}
 					else {
@@ -262,7 +260,7 @@ else if(Core::$user->level >= User::LEVEL_ADMIN) {
 
 				$value = http::value($field->name, "trim");
 
-				if(in_array($field->name, $fillable_fields)) $test->{$field->name} = $value;
+				if(in_array($field->name, Test::TEST_FIELDS)) $test->{$field->name} = $value;
 				else {
 					$test_value = TestValue::get($id, $field->name);
 					if(!$test_value) {

+ 4 - 0
controllers/test_invoice.php

@@ -141,6 +141,10 @@ $pdf->Cell(30, 5, utf8_decode("£") . number_format($fee, 2), 0, 0, "R");
 $pdf->Cell(30, 5, utf8_decode("£") . number_format($fee, 2), 0, 0, "R");
 $pdf->SetXY(10, $next_y);
 
+// TODO: Amount Spent field
+
+// TODO: Travel costs
+
 $pdf->MoveY(10);
 
 $pdf->SetTextColor(128);

+ 4 - 0
engine/form.php

@@ -2,6 +2,10 @@
 
 class Form {
 
+	public static function checked($value) {
+		return !empty($value) ? "checked" : "";
+	}
+
 	public static function checkRecaptcha() {
 
 		if(!defined("GOOGLE_RECAPTCHA_SECRET_KEY")) return true;

+ 24 - 0
engine/practice_test.php

@@ -0,0 +1,24 @@
+<?php
+
+class PracticeTest extends Test {
+
+	protected $values = [];
+
+	// Constants
+	public function getValues($as_assoc_array = false) {
+		return $this->values;
+	}
+
+	public function setValue($key, $value) {
+		$this->values[$key] = $value;
+		return true;
+	}
+
+	public function getDirectory() {
+		$directory = ROOT_DIR . "/files/users/$this->tester_id/practice_tests/$this->template_id";
+		if(!file_exists($directory)) mkdir($directory, 0777, true);
+		return $directory;
+	}
+}
+
+?>

+ 1 - 4
engine/template.php

@@ -4,10 +4,7 @@ class Template extends Model {
 
 	protected static $table = "template";
 	protected static $id_field = "id";
-	protected static $fillable_fields = ["customer_id", "name", "json"];
-
-	protected static $field_map = [
-	];
+	protected static $fillable_fields = ["customer_id", "name", "json", "practice"];
 
 	// Object methods
 	public function getCustomer() {

+ 4 - 2
engine/test.php

@@ -6,8 +6,7 @@ class Test extends Model {
 	protected static $id_field = "id";
 	protected static $fillable_fields = ["project_id", "location_id", "tester_id", "status", "test_fee", "test_time", "shop_left", "shop_right", "attire", "challenge_stage", "challenge_description", "challenger_name", "challenger_description", "challenger_gender", "challenger_eye_contact", "additional_notes", "dts_due", "dts_start", "dts_end", "verifier_id", "verifier_notes", "pass", "dts_created", "dts_updated", "dts_assigned", "dts_verified"];
 
-	protected static $field_map = [
-	];
+	public const TEST_FIELDS = ["shop_left", "shop_right", "attire", "challenge_stage", "challenge_description", "challenger_name", "challenger_description", "challenger_gender", "challenger_eye_contact", "additional_notes"];
 
 	// Constants
 
@@ -141,6 +140,9 @@ class Test extends Model {
 
 	public function getDirectory() {
 		$directory = ROOT_DIR . "/files/tests/" . $this->id;
+		if($this->project_id == "PRACTICE") {
+			$directory = ROOT_DIR . "/files/users/$this->tester_id/practice_tests/$this->template_id";
+		}
 		if(!file_exists($directory)) mkdir($directory, 0777, true);
 		return $directory;
 	}

File diff suppressed because it is too large
+ 0 - 0
public/css/bootstrap.min.css


+ 7 - 0
routes.php

@@ -70,6 +70,7 @@ $routes = [
 	// Templates
 	"/^account\/templates$/" => ["controller" => "templates", "require_user_level" => User::LEVEL_CUSTOMER],
 	"/^account\/templates\/add$/" => ["controller" => "template_add", "require_user_level" => User::LEVEL_ADMIN],
+	"/^account\/templates\/$id_pattern\/edit$/" => ["controller" => "template_edit", "params" => ["id"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/templates\/$id_pattern$/" => ["controller" => "template", "params" => ["id"], "require_user_level" => User::LEVEL_CUSTOMER],
 
 	// Users
@@ -96,6 +97,12 @@ $routes = [
 
 	"/^api\/customers\/$id_pattern\/(get-locations)$/" => ["controller" => "customer_ajax", "params" => ["id", "action"], "require_user_level" => User::LEVEL_ADMIN],
 
+	// Practice
+	"/^account\/practice$/" => ["controller" => "practice_template_select", "require_user_level" => User::LEVEL_TESTER],
+	"/^account\/practice\/$id_pattern$/" => ["controller" => "practice", "params" => ["id"],  "require_user_level" => User::LEVEL_TESTER],
+	"/^account\/practice\/$id_pattern\/files\/([a-z_]+)$/" => ["controller" => "practice_file", "params" => ["id", "name"], "require_user_level" => User::LEVEL_TESTER],
+
+	// Submit ID
 	"/^account\/submit-id$/" => ["controller" => "submit_id", "require_user_level" => User::LEVEL_REGISTERED],
 
 

+ 5 - 0
scss/_main.scss

@@ -2,6 +2,11 @@ body {
 	padding-top: 56px;
 }
 
+.text-monospace {
+	font-family: "Courier New", monospace;
+	font-size: 0.8rem;
+}
+
 .card-header {
 	background: #4caf50;
 	border-color: #4caf50;

+ 51 - 0
views/practice_form.php

@@ -0,0 +1,51 @@
+<div class="container mt-3 py-4">
+<?php
+if($test->status == Test::STATUS_CONFIRMED) {
+	$template->renderBeforeTestForm();
+}
+else if($test->status == Test::STATUS_STARTED) {
+	$template->renderDuringTestForm();
+}
+else {
+	?>
+	<h2>Test Completed</h2>
+
+	<p>Thanks for taking a practice test. You can find your submitted results below. If you would like to reset the form and start again, please <a href="/account/practice/<?=$template->id?>?reset=1">click here</a>.</p>
+	<?php
+
+	$values = $test->getValues();
+
+	// View submitted data
+	foreach($fields as $field) {
+
+		$name = $field->name ?? false;
+		if($name) {
+			$field->value = in_array($name, Test::TEST_FIELDS) ? $test->$name : ($values[$name] ?? null);
+		}
+
+		if($field->type == "header") {
+			?>
+			<hr />
+			<?php
+		}
+
+		if($field->type == "file") {
+			?>
+			<div class="row mb-1">
+				<div class="col-sm-4 col-form-label">
+					<?=htmlspecialchars($field->label)?>
+				</div>
+				<div class="col-sm">
+					<a class="btn btn-primary" href="/account/practice/<?=$template->id?>/files/<?=htmlspecialchars($name)?>" target="_blank">View Image</a>
+				</div>
+			</div>
+			<?php
+		}
+		else {
+			Form::renderField($field);
+		}
+
+	}
+}
+?>
+</div>

+ 29 - 0
views/practice_template_select.php

@@ -0,0 +1,29 @@
+<div class="container mt-3 py-4">
+
+	<h2>Select Practice Form</h2>
+
+	<?php
+	if(empty($templates)) {
+		?>
+		<div class="alert alert-info">
+			There are no practice forms available at the moment. Please try again later.
+		</div>
+		<?php
+	}
+	else {
+		?>
+		<div class="list-group">
+		<?php
+		foreach($templates as $template) {
+			?>
+			<a class="list-group-item list-group-item-action" href="/account/practice/<?=$template->id?>">
+				<?=htmlspecialchars($template->name)?>
+			</a>
+			<?php
+		}
+		?>
+		</div>
+		<?php
+	}
+	?>
+</div>

+ 8 - 1
views/template.php

@@ -1,5 +1,12 @@
 <div class="container pt-3 my-4">
-	<h2><?=htmlspecialchars($template->name)?> Template Form Previews</h2>
+	<div class="row">
+		<div class="col align-self-center">
+			<h2><?=htmlspecialchars($template->name)?> Template</h2>
+		</div>
+		<div class="col-auto align-self-center">
+			<a class="btn btn-outline-primary" href="/account/templates/<?=$template->id?>/edit">Edit</a>
+		</div>
+	</div>
 
 	<div class="card mb-3">
 		<div class="card-header">

+ 0 - 16
views/template_add_form.php

@@ -1,16 +0,0 @@
-<div class="container mt-3 py-4">
-
-	<h2>Add Template</h2>
-
-	<form method="post">
-		<div class="form-group">
-			<label for="name">Name</label>
-			<input class="form-control" name="name" id="name" placeholder="Enter name" value="<?=htmlspecialchars($template->name)?>" required />
-		</div>
-		<div class="form-group">
-			<label for="json">JSON</label>
-			<textarea class="form-control" name="json" id="json" placeholder="Enter JSON" rows="16" required><?=htmlspecialchars($template->json)?></textarea>
-		</div>
-		<button class="btn btn-primary" type="submit" name="submit" value="<?=htmlspecialchars($_SESSION["csrf_token"])?>">Add</button>
-	</form>
-</div>

+ 35 - 0
views/template_form.php

@@ -0,0 +1,35 @@
+<div class="container mt-3 py-4">
+
+	<h2><?=htmlspecialchars($page_title)?></h2>
+
+	<form method="post">
+		<div class="row mb-1">
+			<label class="col-sm-4 col-form-label" for="name">Name</label>
+			<div class="col-sm">
+				<input class="form-control" name="name" id="name" placeholder="Enter name" value="<?=htmlspecialchars($template->name)?>" required />
+			</div>
+		</div>
+		<div class="row mb-1">
+			<label class="col-sm-4 col-form-label" for="json">
+				JSON Template Configuration
+				<small class="form-text text-danger">Do not touch this if you don't know what you're doing.</small>
+			</label>
+			<div class="col-sm">
+				<textarea class="form-control text-monospace" name="json" id="json" placeholder="Enter JSON" rows="24" required><?=htmlspecialchars($template->json)?></textarea>
+			</div>
+		</div>
+		<div class="row mt-3 mb-3">
+			<div class="col-sm offset-sm-4">
+				<div class="form-check">
+					<input class="form-check-input" type="checkbox" name="practice" id="practice" value="1" <?=Form::checked($template->practice)?> />
+					<label for="practice" class="form-check-label">Enabled for Practice</label>
+				</div>
+			</div>
+		</div>
+		<div class="row">
+			<div class="col-sm offset-sm-4">
+				<button class="btn btn-primary" type="submit" name="submit" value="<?=htmlspecialchars($_SESSION["csrf_token"])?>">Submit</button>
+			</div>
+		</div>
+	</form>
+</div>

Some files were not shown because too many files changed in this diff