Просмотр исходного кода

Add support for invoicing locations for new tests on verification

Alan Lam 2 лет назад
Родитель
Сommit
f374c659f2

+ 2 - 1
composer.json

@@ -15,7 +15,8 @@
 	"ext-simplexml": "*",
     "nesbot/carbon": "^2.50",
 	"ext-bcmath": "*",
-	"ext-intl": "*"
+	"ext-intl": "*",
+    "stripe/stripe-php": "^15.10"
   },
   "config": {
     "platform": {

+ 62 - 2
composer.lock

@@ -4,7 +4,7 @@
         "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
         "This file is @generated automatically"
     ],
-    "content-hash": "ee645aa79addf8dc309d97dd17e322af",
+    "content-hash": "12e408f70976f2938541fa21484363ab",
     "packages": [
         {
             "name": "cakephp/cache",
@@ -1289,6 +1289,65 @@
             ],
             "time": "2020-04-28T12:40:35+00:00"
         },
+        {
+            "name": "stripe/stripe-php",
+            "version": "v15.10.0",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/stripe/stripe-php.git",
+                "reference": "3df1a19a33477af9ead8984dbd84e8f637c36199"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/stripe/stripe-php/zipball/3df1a19a33477af9ead8984dbd84e8f637c36199",
+                "reference": "3df1a19a33477af9ead8984dbd84e8f637c36199",
+                "shasum": ""
+            },
+            "require": {
+                "ext-curl": "*",
+                "ext-json": "*",
+                "ext-mbstring": "*",
+                "php": ">=5.6.0"
+            },
+            "require-dev": {
+                "friendsofphp/php-cs-fixer": "3.5.0",
+                "phpstan/phpstan": "^1.2",
+                "phpunit/phpunit": "^5.7 || ^9.0"
+            },
+            "type": "library",
+            "extra": {
+                "branch-alias": {
+                    "dev-master": "2.0-dev"
+                }
+            },
+            "autoload": {
+                "psr-4": {
+                    "Stripe\\": "lib/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "Stripe and contributors",
+                    "homepage": "https://github.com/stripe/stripe-php/contributors"
+                }
+            ],
+            "description": "Stripe PHP Library",
+            "homepage": "https://stripe.com/",
+            "keywords": [
+                "api",
+                "payment processing",
+                "stripe"
+            ],
+            "support": {
+                "issues": "https://github.com/stripe/stripe-php/issues",
+                "source": "https://github.com/stripe/stripe-php/tree/v15.10.0"
+            },
+            "time": "2024-09-18T18:38:30+00:00"
+        },
         {
             "name": "symfony/config",
             "version": "v5.1.3",
@@ -2305,7 +2364,8 @@
         "ext-mbstring": "*",
         "ext-readline": "*",
         "ext-simplexml": "*",
-        "ext-bcmath": "*"
+        "ext-bcmath": "*",
+        "ext-intl": "*"
     },
     "platform-dev": [],
     "platform-overrides": {

+ 5 - 1
controllers/project_ajax.php

@@ -69,6 +69,8 @@ if($submit) {
 						$pass_text = $test->getPassText();
 						$pass_icon = $test->getPassIcon();
 						$retest = (bool) $test->retest;
+						$payment_required = (bool) $test->payment_required;
+						$paid = (bool) $test->dts_paid;
 					}
 
 					$output[] = (object) [
@@ -89,10 +91,12 @@ if($submit) {
 						"latitude" => (float) $location->latitude,
 						"longitude" => (float) $location->longitude,
 						"retest" => $retest,
+						"paymentRequired" => !empty($payment_required),
+						"paid" => !empty($paid)
 					];
 				}
 
-				usort($output, function($a, $b) {
+				usort($output, static function(object $a, object $b) {
 					return $a->status <=> $b->status;
 				});
 

+ 76 - 0
controllers/stripe_webhook.php

@@ -0,0 +1,76 @@
+<?php /** @noinspection PhpPossiblePolymorphicInvocationInspection */
+
+use Stripe\Exception\SignatureVerificationException;
+use Stripe\StripeClient;
+use Stripe\Webhook;
+
+$payload = @file_get_contents('php://input');
+if(!$payload) {
+	exit();
+}
+
+$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? "";
+
+$event = null;
+
+try {
+	$stripe = new StripeClient(STRIPE_SECRET_KEY);
+
+	$event = Webhook::constructEvent($payload, $sig_header, STRIPE_WEBHOOK_SECRET);
+
+	$event_type_parts = explode(".", $event->type);
+	$event_action = array_pop($event_type_parts);
+	$event_entity = implode(".", $event_type_parts);
+
+	// Handle the event
+	switch($event_entity) {
+
+		case "invoice": {
+			/** @var \Stripe\Invoice $invoice */
+			$invoice = $event->data->object;
+
+			$stripe_customer = $stripe->customers->retrieve($invoice->customer);
+
+			$location = Location::queryOne(["stripe_customer_id" => $stripe_customer->id]);
+			if(!$location) {
+				goto HTTP_OK;
+			}
+
+			switch($event_action) {
+				case "payment_succeeded": {
+					$test_id = $invoice->metadata->test_id ?? null;
+					if($test_id) {
+						$test = Test::get($test_id);
+						$test->dts_paid = DB::dts();
+						$test->commit();
+					}
+
+					break;
+				}
+			}
+
+			break;
+		}
+
+		default:
+			http_response_code(400);
+			exit();
+	}
+}
+catch(UnexpectedValueException $e) {
+	// Invalid payload
+	http_response_code(400);
+	exit();
+}
+catch(SignatureVerificationException $e) {
+	http_response_code(400);
+	exit();
+}
+catch(Exception $e) {
+	http_response_code(400);
+	die($e->getMessage());
+}
+
+HTTP_OK:
+http_response_code(200);
+exit;

+ 51 - 11
controllers/test_verify_form.php

@@ -10,6 +10,8 @@
  * @var string[] $template_keys
  */
 
+use Helpers\StripeHelper;
+
 $customer = $project->getCustomer();
 $tester = $test->getTester();
 
@@ -31,8 +33,11 @@ if($submit) {
 		$accept_tester_invoice = http::value("accept_tester_invoice");
 		$reject_tester_invoice = http::value("reject_tester_invoice");
 
+		$payment_required = (bool) http::value("payment_required", "int");
+		$invoice_amount = http::value("invoice_amount", "decimal-2");
+
 		if(($accept || $reject) && $test->getStatus() !== Test::STATUS_PENDING_VERIFICATION) {
-			throw new Exception("This test is no longer pending verification.");
+			throw new RuntimeException("This test is no longer pending verification.");
 		}
 
 		if(empty($test->verifier_id)) {
@@ -42,13 +47,26 @@ if($submit) {
 
 		$test->verifier_notes = http::value("verifier_notes", "trim");
 
+		// Validation
+
 		// Check selected retest project
 		$new_test_project = false;
 		$new_test_project_id = http::value("new_test_project_id", "int");
 		$new_test_is_retest = http::value("new_test_is_retest", "int");
 		if($new_test_project_id) {
 			$new_test_project = Project::get($new_test_project_id);
-			if(!$new_test_project || $new_test_project->customer_id != $customer->id) throw new Exception("The new test project selected is invalid.");
+			if(!$new_test_project || $new_test_project->customer_id != $customer->id) {
+				throw new RuntimeException("The new test project selected is invalid.");
+			}
+
+			if($payment_required) {
+				if($invoice_amount < 0) {
+					throw new RuntimeException(__("Invoice amount cannot be less than 0.00."));
+				}
+				if(!$location->email) {
+					throw new RuntimeException(__("Location does not have an email address set."));
+				}
+			}
 		}
 
 		// Modify test values
@@ -95,7 +113,9 @@ if($submit) {
 		}
 
 		$test->test_travel_cost = HTTP::value("travel_cost", "float") ?? 0;
-		if($test->test_travel_cost < 0 || $test->test_travel_cost > 999.99) $form_exception->addError("Travel costs must be between 0 and 999.99.");
+		if($test->test_travel_cost < 0 || $test->test_travel_cost > 999.99) {
+			$form_exception->addError("Travel costs must be between 0 and 999.99.");
+		}
 
 		// Test forms
 		foreach($fields as $field) {
@@ -154,10 +174,12 @@ if($submit) {
 
 		$test->dts_updated = Util::getDateTime();
 		$success = $test->commit();
-		if(!$success) throw new Exception("Failed to update the test. Please try again later.");
+		if(!$success) {
+			throw new RuntimeException("Failed to update the test. Please try again later.");
+		}
 
 		if($new_test_project) {
-			$new_test = new Test;
+			$new_test = new Test();
 			$new_test->project_id = $new_test_project->id;
 			$new_test->location_id = $location->id;
 			$new_test->status = Test::STATUS_UNASSIGNED;
@@ -166,17 +188,24 @@ if($submit) {
 				$new_test->retest = 1;
 			}
 			$success = $new_test->commit();
+
+			if($payment_required) {
+				$helper = StripeHelper::getInstance();
+				$helper->createInvoice($new_test, $invoice_amount);
+			}
 		}
 
 		// If rejected, recreate empty test for the location
 		if($reject) {
-			$new_test = new Test;
+			$new_test = new Test();
 			$new_test->project_id = $test->project_id;
 			$new_test->location_id = $test->location_id;
 			$new_test->status = Test::STATUS_UNASSIGNED;
 			$new_test->dts_created = Util::getDateTime();
 			$success = $new_test->commit();
-			if(!$success) throw new Exception("Failed to create a new test. Please try again later.");
+			if(!$success) {
+				throw new RuntimeException("Failed to create a new test. Please try again later.");
+			}
 		}
 
 		if($accept) {
@@ -248,12 +277,16 @@ if($submit) {
 
 			if($accept_tester_invoice) {
 				$success = $test->markTesterInvoicePaid();
-				if(!$success) throw new Exception("Failed to mark tester invoice as paid.");
+				if(!$success) {
+					throw new RuntimeException("Failed to mark tester invoice as paid.");
+				}
 			}
 
 			if($reject_tester_invoice) {
 				$success = $test->rejectTesterInvoice();
-				if(!$success) throw new Exception("Failed to reject tester invoice.");
+				if(!$success) {
+					throw new RuntimeException("Failed to reject tester invoice.");
+				}
 			}
 
 		}
@@ -272,12 +305,19 @@ if($submit) {
 $projects = $customer->getProjects();
 
 $future_projects = array_filter($projects, static function(Project $p) use ($project) {
-	if($p->id == $project->id) return false;
-	if($p->template_id != $project->template_id) return false;
+	if($p->id == $project->id) {
+		return false;
+	}
+	if($p->template_id != $project->template_id) {
+		return false;
+	}
 	$unix_deadline = Util::getUnixTimeFromUTC($p->dts_deadline);
 	return ($unix_deadline > time());
 });
 
+
+Core::addScript("public/js/app-test-verify-form.js");
+
 View::includeOnce("header", compact("page_title"));
 View::include("test_verify_form", compact("test", "tester", "location", "project", "future_projects", "customer", "template", "fields", "tester_message"));
 View::includeOnce("footer");

+ 13 - 0
db/migrations/20240930103716_add_payment_fields_to_test_table.php

@@ -0,0 +1,13 @@
+<?php
+
+use Phinx\Migration\AbstractMigration;
+
+class AddPaymentFieldsToTestTable extends AbstractMigration {
+	public function change() {
+		$this->table("test")
+			->addColumn("stripe_invoice_id", "string", ["null" => true, "after" => "tester_id"])
+			->addColumn("payment_required", "boolean", ["signed" => false, "default" => 0, "after" => "status_tester_invoice"])
+			->addColumn("dts_paid", "datetime", ["null" => true, "after" => "dts_verified"])
+			->update();
+	}
+}

+ 11 - 0
db/migrations/20240930104028_add_payment_fields_to_location_table.php

@@ -0,0 +1,11 @@
+<?php
+
+use Phinx\Migration\AbstractMigration;
+
+class AddPaymentFieldsToLocationTable extends AbstractMigration {
+	public function change() {
+		$this->table("location")
+			->addColumn("stripe_customer_id", "string", ["null" => true, "after" => "customer_id"])
+			->update();
+	}
+}

+ 110 - 0
engine/helpers/stripe_helper.php

@@ -0,0 +1,110 @@
+<?php
+
+namespace Helpers;
+
+use Exception;
+use Location;
+use Stripe\Customer;
+use Stripe\Invoice;
+use Stripe\StripeClient;
+use Test;
+
+class StripeHelper {
+
+	private StripeClient $client;
+
+	public static function getInstance(): self {
+		return new self(STRIPE_SECRET_KEY);
+	}
+
+	public function __construct(string $private_key) {
+		$this->client = new StripeClient($private_key);
+	}
+
+	/**
+	 * @param Location $location
+	 * @return Customer
+	 * @throws Exception
+	 */
+	public function createOrUpdateCustomer(Location $location): Customer {
+		$customer = $location->getCustomer();
+
+		$data = [
+			"name" => $customer->name . " - " . $location->name,
+			"email" => $location->email,
+			"phone" => $location->phone,
+			"metadata" => [
+				"location_id" => $location->id,
+			]
+		];
+
+		if($location->stripe_customer_id) {
+			$stripe_customer = $this->client->customers->update($location->stripe_customer_id, $data);
+		}
+		else {
+			$stripe_customer = $this->client->customers->create($data);
+		}
+
+		$location->stripe_customer_id = $stripe_customer->id;
+		$location->commit();
+
+		return $stripe_customer;
+	}
+
+	/**
+	 * @param Test $test
+	 * @param string $price
+	 * @return Invoice
+	 * @throws Exception
+	 */
+	public function createInvoice(Test $test, string $price): Invoice {
+		$location = $test->getLocation();
+		if($location->stripe_customer_id) {
+			$customer = $this->client->customers->retrieve($location->stripe_customer_id);
+		}
+		else {
+			$customer = $this->createOrUpdateCustomer($location);
+		}
+
+		if($test->stripe_invoice_id) {
+			return $this->client->invoices->retrieve($test->stripe_invoice_id);
+
+		}
+
+		$invoice = $this->client->invoices->create([
+			"collection_method" => "send_invoice",
+			"customer" => $customer->id,
+			"metadata" => [
+				"test_id" => $test->id,
+			],
+			"days_until_due" => 0,
+			"payment_settings" => [
+				"payment_method_types" => [
+					"card",
+				]
+			]
+		]);
+
+		$this->client->invoiceItems->create([
+			"customer" => $customer->id,
+			"amount" => bcmul($price, 100),
+			"currency" => "gbp",
+			"description" => "Check Policy test fee",
+			"metadata" => [
+				"test_id" => $test->id,
+			],
+			"invoice" => $invoice->id,
+		]);
+
+		$this->client->invoices->finalizeInvoice($invoice->id);
+
+		$test->stripe_invoice_id = $invoice->id;
+		$test->commit();
+
+		$this->client->invoices->sendInvoice($invoice->id);
+
+		return $invoice;
+	}
+
+
+}

+ 6 - 0
engine/http.php

@@ -147,6 +147,12 @@ class HTTP {
 				return is_array($value) ? filter_var_array($value, FILTER_VALIDATE_EMAIL) : filter_var($value, FILTER_VALIDATE_EMAIL);
 			}
 
+			case "decimal-2": {
+				return is_array($value) ? array_map(static function($value) {
+					return number_format($value, 2, ".", "");
+				}, $value) : number_format($value, 2, ".", "");
+			}
+
 			default: {
 				throw new RuntimeException("Unknown validation type: $validation");
 			}

+ 3 - 1
engine/location.php

@@ -3,6 +3,7 @@
 /**
  * @property int $id
  * @property int $customer_id
+ * @property string $stripe_customer_id
  * @property string $name
  * @property string $legal_entity_name
  * @property string $address_1
@@ -46,7 +47,8 @@ class Location extends Model {
 	protected static $table = "location";
 	protected static $id_field = "id";
 	protected static $fillable_fields = [
-		"customer_id", "name", "legal_entity_name",
+		"customer_id", "stripe_customer_id",
+		"name", "legal_entity_name",
 		"address_1", "address_2", "city", "county", "postal_code", "state", "country", "email", "phone",
 		"opening_hours", "notes",
 		"shop_left", "shop_right",

+ 6 - 2
engine/test.php

@@ -9,8 +9,10 @@ use Mpdf\Mpdf;
  * @property int $project_id
  * @property int $location_id
  * @property int $tester_id
+ * @property int $stripe_invoice_id
  * @property int $status
  * @property int $status_tester_invoice
+ * @property int $payment_required
  * @property float $customer_fee
  * @property float $test_fee
  * @property string $test_time
@@ -44,6 +46,7 @@ use Mpdf\Mpdf;
  * @property string $dts_assigned
  * @property string $dts_rejected
  * @property string $dts_verified
+ * @property string $dts_paid
  */
 
 class Test extends Model {
@@ -51,8 +54,9 @@ class Test extends Model {
 	protected static $table = "test";
 	protected static $id_field = "id";
 	protected static $fillable_fields = [
-		"project_id", "location_id", "tester_id",
+		"project_id", "location_id", "tester_id", "stripe_invoice_id",
 		"status", "status_tester_invoice",
+		"payment_required",
 		"customer_fee", "test_fee", "test_time", "test_travel_cost", "test_travel_cost_description",
 		"shop_left", "shop_right", "attire",
 		"challenge_stage",
@@ -65,7 +69,7 @@ class Test extends Model {
 		"void_primary",
 		"void_secondary",
 		"dts_created", "dts_updated",
-		"dts_assigned", "dts_rejected", "dts_verified"
+		"dts_assigned", "dts_rejected", "dts_verified", "dts_paid",
 	];
 
 	public const TEST_FIELDS = ["shop_left", "shop_right", "attire", "challenge_stage", "challenge_description", "challenger_name", "challenger_description", "challenger_gender", "challenger_eye_contact", "additional_notes"];

+ 4 - 1
public/js/app-project.js

@@ -203,11 +203,14 @@ function initialiseLocations() {
 
 			var statusTd = $("<td>").addClass("align-middle").addClass("text-center");
 			statusTd.append($("<span>").addClass("badge").addClass("badge-" + cssClass).text(location.statusText));
+			if(location.paymentRequired) {
+				statusTd.append(`<br /><span class="badge badge-danger">Unpaid</span>`);
+			}
 			tr.append(statusTd);
 
 			var passTd = $("<td>").addClass("align-middle").addClass("text-center").addClass("text-" + location.passClass);
 			var div = $("<div>").attr("title", location.passText).attr("data-toggle", "tooltip");
-			div.append($("<i>").addClass().addClass("fas").addClass("fa-fw").addClass("fa-" + location.passIcon));
+			div.append($("<i>").addClass("fas").addClass("fa-fw").addClass("fa-" + location.passIcon));
 			passTd.append(div);
 			tr.append(passTd);
 			div.tooltip();

+ 18 - 0
public/js/app-test-verify-form.js

@@ -0,0 +1,18 @@
+class TestVerifyForm {
+
+	constructor() {
+
+		this.$invoiceAmountField = $("#invoice-amount");
+
+		this.$newTestProjectField = $("#new-test-project-id");
+		this.$newTestProjectField.on("change", event => {
+			const $option = this.$newTestProjectField.find("option:selected");
+			const customerFee = $option.attr("data-customer-fee");
+			this.$invoiceAmountField.val(customerFee);
+		});
+
+	}
+
+}
+
+$(() => new TestVerifyForm());

+ 1 - 0
public/serve.bat

@@ -0,0 +1 @@
+php -c C:\Windows\php-cli.ini -S localhost:8080 server.php

+ 67 - 0
public/server.php

@@ -0,0 +1,67 @@
+<?php
+
+if(PHP_SAPI !== "cli-server") {
+	header("Location: /");
+	exit();
+}
+
+error_reporting(E_ALL & ~E_DEPRECATED);
+
+$name = basename(__FILE__);
+$uri = $_SERVER["REQUEST_URI"];
+$uri_parts = explode("?", $uri);
+
+$_REQUEST["path"] = $uri_parts[0];
+
+chdir(__DIR__);
+
+$file_path = realpath(ltrim($uri_parts[0], '/'));
+
+error_log($file_path);
+
+if($file_path && is_dir($file_path)) {
+	// attempt to find an index file
+	foreach(['index.php', 'index.html'] as $index_file) {
+		if($file_path = realpath($file_path . DIRECTORY_SEPARATOR . $index_file)) {
+			break;
+		}
+	}
+}
+if($file_path && is_file($file_path)) {
+	// 1. check that file is not outside of this directory for security
+	// 2. check for circular reference to self
+	// 3. don't serve dotfiles
+
+	$is_current_directory = strpos($file_path, __DIR__ . DIRECTORY_SEPARATOR) === 0;
+	$is_this_file = $file_path == __FILE__;
+	$is_dot_file = substr($name, 0, 1) == '.';
+
+	if($is_current_directory && !$is_this_file && !$is_dot_file) {
+		$extension = strtolower(substr($file_path, -4));
+
+		if($extension === '.php') {
+			// php file; serve through interpreter
+			include $file_path;
+		}
+		else {
+			if($extension === ".css") {
+				header("Content-Type: text/css");
+			}
+			if($extension === ".js") {
+				header("Content-Type: text/javascript");
+			}
+
+			// asset file; serve from filesystem
+			readfile($file_path);
+		}
+	}
+	else {
+		// disallowed file
+		header("HTTP/1.1 404 Not Found");
+		echo "404 Not Found";
+	}
+}
+else {
+	// rewrite to our index file
+	include __DIR__ . DIRECTORY_SEPARATOR . 'index.php';
+}

+ 5 - 1
router.php

@@ -14,7 +14,11 @@ try {
 	require "routes.php";
 
 	$path = http::value("path");
-	if(empty($path)) $path = "home";
+	if(empty($path)) {
+		$path = "home";
+	}
+
+	$path = ltrim($path, "/");
 
 	// Loop through routes
 	foreach($routes as $regex => $options) {

+ 3 - 0
routes.php

@@ -151,4 +151,7 @@ $routes = [
 	// Overview
 	"/^account\/overview$/" => ["controller" => "overview", "require_user_level" => User::LEVEL_TESTER_MANAGER],
 
+	// Webhooks
+	"/^webhooks\/stripe$/" => ["controller" => "stripe_webhook"],
+
 ];

+ 198 - 126
views/test_verify_form.php

@@ -360,176 +360,247 @@ function render_card_list_group($details) {
 							</div>
 						</div>
 						<hr />
-						<?php
-						if($template->hasPassFail()) {
+
+						<section class="mb-4">
+							<h5><?=htmlspecialchars(__("Overrides"))?></h5>
+
+							<?php
+							if($template->hasPassFail()) {
+								?>
+								<div class="row mb-1">
+									<label class="col-sm-4 col-form-label col-form-label-sm" for="pass-override">Pass Override</label>
+									<div class="col-sm">
+										<select class="form-control form-control-sm" name="pass_override" id="pass-override">
+											<option value="">None</option>
+											<option value="1">Pass</option>
+											<option value="0">Fail</option>
+										</select>
+									</div>
+								</div>
+								<?php
+							}
 							?>
 							<div class="row mb-1">
-								<label class="col-sm-4 col-form-label col-form-label-sm" for="pass-override">Pass Override</label>
+								<label class="col-sm-4 col-form-label col-form-label-sm" for="start-override">Start Override</label>
+
 								<div class="col-sm">
-									<select class="form-control form-control-sm" name="pass_override" id="pass-override">
-										<option value="">None</option>
-										<option value="1">Pass</option>
-										<option value="0">Fail</option>
-									</select>
+									<input class="form-control form-control-sm" type="datetime-local" name="start_override" id="start-override" />
 								</div>
 							</div>
-							<?php
-						}
-						?>
-						<div class="row mb-1">
-							<label class="col-sm-4 col-form-label col-form-label-sm" for="start-override">Start Override</label>
-
-							<div class="col-sm">
-								<input class="form-control form-control-sm" type="datetime-local" name="start_override" id="start-override" />
-							</div>
-
-						</div>
-						<div class="row mb-1">
-							<label class="col-sm-4 col-form-label col-form-label-sm" for="end-override">End Override</label>
-							<div class="col-sm">
-								<input class="form-control form-control-sm" type="datetime-local" name="end_override" id="end-override" />
+							<div class="row mb-1">
+								<label class="col-sm-4 col-form-label col-form-label-sm" for="end-override">End Override</label>
+								<div class="col-sm">
+									<input class="form-control form-control-sm" type="datetime-local" name="end_override" id="end-override" />
+								</div>
 							</div>
-						</div>
-						<div class="row mb-1">
-							<label class="col-sm-4 col-form-label col-form-label-sm" for="customer-fee">Customer Fee Override</label>
-							<div class="col-sm">
-								<div class="input-group input-group-sm">
-									<div class="input-group-prepend">
-										<span class="input-group-text">£</span>
+							<div class="row mb-1">
+								<label class="col-sm-4 col-form-label col-form-label-sm" for="customer-fee">Customer Fee Override</label>
+								<div class="col-sm">
+									<div class="input-group input-group-sm">
+										<div class="input-group-prepend">
+											<span class="input-group-text">£</span>
+										</div>
+										<input class="form-control" type="number" step="0.01" min="0" name="customer_fee" id="customer-fee" placeholder="Enter customer fee override" value="<?=htmlspecialchars($test->customer_fee)?>" />
 									</div>
-									<input class="form-control" type="number" step="0.01" min="0" name="customer_fee" id="customer-fee" placeholder="Enter customer fee override" value="<?=htmlspecialchars($test->customer_fee)?>" />
 								</div>
 							</div>
-						</div>
-						<div class="row mb-1">
-							<label class="col-sm-4 col-form-label col-form-label-sm" for="tester-fee">Tester Fee Override</label>
-							<div class="col-sm">
-								<div class="input-group input-group-sm">
-									<div class="input-group-prepend">
-										<span class="input-group-text">£</span>
+							<div class="row mb-1">
+								<label class="col-sm-4 col-form-label col-form-label-sm" for="tester-fee">Tester Fee Override</label>
+								<div class="col-sm">
+									<div class="input-group input-group-sm">
+										<div class="input-group-prepend">
+											<span class="input-group-text">£</span>
+										</div>
+										<input class="form-control" type="number" step="0.01" min="0" name="tester_fee" id="tester-fee" placeholder="Enter tester fee override" value="<?=htmlspecialchars($test->test_fee)?>" />
 									</div>
-									<input class="form-control" type="number" step="0.01" min="0" name="tester_fee" id="tester-fee" placeholder="Enter tester fee override" value="<?=htmlspecialchars($test->test_fee)?>" />
 								</div>
 							</div>
-						</div>
-						<row class="row mb-1">
-							<label class="col-sm-4 col-form-label col-form-label-sm" for="travel-cost">Travel Costs</label>
-							<div class="col-sm">
-								<div class="input-group input-group-sm">
-									<div class="input-group-prepend">
-										<span class="input-group-text">£</span>
+						</section>
+
+						<section class="mb-4">
+							<h5><?=htmlspecialchars(__("Costs & Notes"))?></h5>
+
+							<div class="row mb-1">
+								<label class="col-sm-4 col-form-label col-form-label-sm" for="travel-cost">Travel Costs</label>
+								<div class="col-sm">
+									<div class="input-group input-group-sm">
+										<div class="input-group-prepend">
+											<span class="input-group-text">£</span>
+										</div>
+										<input class="form-control" type="number" step="0.01" min="0" max="999.99" name="travel_cost" id="travel-cost" placeholder="Enter travel costs" value="<?=htmlspecialchars($test->test_travel_cost)?>" />
 									</div>
-									<input class="form-control" type="number" step="0.01" min="0" max="999.99" name="travel_cost" id="travel-cost" placeholder="Enter travel costs" value="<?=htmlspecialchars($test->test_travel_cost)?>" />
 								</div>
 							</div>
-						</row>
-						
-						<div class="row mb-1">
-							<label class="col-sm-4 col-form-label col-form-label-sm" for="verifier-notes">Verifier Notes</label>
-							<div class="col-sm">
-								<textarea class="form-control form-control-sm" name="verifier_notes" id="verifier-notes" placeholder="Enter verifier notes" rows="4"><?=htmlspecialchars($test->verifier_notes)?></textarea>
+
+							<div class="row mb-1">
+								<label class="col-sm-4 col-form-label col-form-label-sm" for="verifier-notes">Verifier Notes</label>
+								<div class="col-sm">
+									<textarea class="form-control form-control-sm" name="verifier_notes" id="verifier-notes" placeholder="Enter verifier notes" rows="4"><?=htmlspecialchars($test->verifier_notes)?></textarea>
+								</div>
 							</div>
-						</div>
 
-						<div class="row mb-1 align-items-center">
-							<label class="col-sm-4 col-form-label col-form-label-sm" for="retest">Set As Retest</label>
-							<div class="col-sm">
-								<div class="custom-control custom-checkbox">
-									<input class="custom-control-input" type="checkbox" name="retest" id="retest" value="1" <?=Form::checked($test->retest)?> />
-									<label class="custom-control-label" for="retest">This test was a retest</label>
+							<div class="row mb-1 align-items-center">
+								<label class="col-sm-4 col-form-label col-form-label-sm" for="retest">Set As Retest</label>
+								<div class="col-sm">
+									<div class="custom-control custom-checkbox">
+										<input class="custom-control-input" type="checkbox" name="retest" id="retest" value="1" <?=Form::checked($test->retest)?> />
+										<label class="custom-control-label" for="retest">This test was a retest</label>
+									</div>
 								</div>
 							</div>
-						</div>
+						</section>
 
-                        <div class="row mb-1">
-                            <label class="col-sm-4 col-form-label col-form-label-sm" for="new-test-project-id">Create New Test</label>
-                            <div class="col-sm">
-								<div class="input-group">
-									<select class="form-control" name="new_test_project_id" id="new-test-project-id">
-										<option value="0">Do not create</option>
-										<?php
-										foreach($future_projects as $future_project) {
-											?>
-											<option value="<?=$future_project->id?>"><?=htmlspecialchars($future_project->name)?></option>
+						<section class="mb-4">
+							<h5><?=htmlspecialchars(__("New Test"))?></h5>
+
+							<div class="row mb-1">
+								<label class="col-sm-4 col-form-label col-form-label-sm" for="new-test-project-id">
+									Create New Test
+								</label>
+								<div class="col-sm">
+									<div class="input-group">
+										<select class="form-control" name="new_test_project_id" id="new-test-project-id">
+											<option value="0">Do not create</option>
 											<?php
-										}
-										?>
-									</select>
-									<div class="input-group-append">
-										<div class="input-group-text">
-											<div class="custom-control custom-checkbox">
-												<input class="custom-control-input" type="checkbox" name="new_test_is_retest" id="new-test-is-retest" value="1" />
-												<label class="custom-control-label" for="new-test-is-retest"><?=htmlspecialchars(__("Retest"))?></label>
+											foreach($future_projects as $future_project) {
+												?>
+												<option value="<?=$future_project->id?>" data-customer-fee="<?=$future_project->default_customer_fee?>">
+													<?=htmlspecialchars($future_project->name)?>
+												</option>
+												<?php
+											}
+											?>
+										</select>
+										<div class="input-group-append">
+											<div class="input-group-text">
+												<div class="custom-control custom-checkbox">
+													<input class="custom-control-input" type="checkbox" name="new_test_is_retest" id="new-test-is-retest" value="1" />
+													<label class="custom-control-label" for="new-test-is-retest"><?=htmlspecialchars(__("Retest"))?></label>
+												</div>
 											</div>
 										</div>
 									</div>
 								</div>
-                            </div>
-                        </div>
+							</div>
 
-						<?php
-						if($test->getStatus() === Test::STATUS_PENDING_VERIFICATION) {
-							?>
 							<?php
-							$customer_checked = $customer->email_after_test;
-							$location_checked = $customer->email_locations_after_test;
-
-							$email_address_configs = [
-								["email" => $customer->email, "label" => "Email Headquarters", "name" => "email_customer", "checked" => $customer_checked],
-								["email" => $location->email, "label" => "Email Venue", "name" => "email_location", "checked" => $location_checked],
-								["email" => $location->area_manager_email, "label" => "Email AM", "name" => "email_location_area_manager", "checked" => $location_checked],
-								["email" => $location->operations_manager_email, "label" => "Email OM", "name" => "email_location_operations_manager", "checked" => $location_checked],
-								["email" => $location->gaming_manager_email, "label" => "Email GM", "name" => "email_location_gaming_manager", "checked" => $location_checked],
-								["email" => $location->senior_gaming_manager_email, "label" => "Email SGM", "name" => "email_location_senior_gaming_manager", "checked" => $location_checked],
-							];
-
-							foreach($email_address_configs as $email_address_config) {
-								$email_address = $email_address_config["email"];
-								if(!$email_address) {
-									continue;
-								}
-
-								$label = $email_address_config["label"];
-								$name = $email_address_config["name"];
-								$checked = $email_address_config["checked"];
-								$id = str_replace("_", "-", $name);
+							if($location->email) {
 								?>
-								<div class="row mb-1">
-									<label class="col-sm-4 col-form-label col-form-label-sm" for="<?=$id?>">
-										<?=htmlspecialchars($label)?>
+								<div class="row mb-1 align-items-center">
+									<label class="col-sm-4 col-form-label col-form-label-sm" for="payment-required">
+										Invoice Location
 									</label>
 									<div class="col-sm">
-										<div class="custom-control custom-checkbox">
-											<input class="custom-control-input" type="checkbox" name="<?=$name?>" id="<?=$id?>" value="1" <?=Form::checked($checked)?> />
-											<label class="custom-control-label" for="<?=$id?>"><?=htmlspecialchars($email_address)?></label>
+										<div class="custom-control custom-switch">
+											<input class="custom-control-input" id="payment-required" name="payment_required" type="checkbox" value="1" />
+											<label class="custom-control-label" for="payment-required"><?=htmlspecialchars(__("Send Invoice"))?></label>
+										</div>
+									</div>
+								</div>
+
+								<div class="row mb-1 align-items-center">
+									<label class="col-sm-4 col-form-label col-form-label-sm" for="invoice-amount">
+										Invoice Amount
+									</label>
+									<div class="col-sm">
+										<div class="input-group input-group-sm">
+											<div class="input-group-prepend">
+												<span class="input-group-text">£</span>
+											</div>
+											<input class="form-control" type="number" step="0.01" min="0" max="999.99" name="invoice_amount" id="invoice-amount" placeholder="Enter invoice amount" value="0.00" />
 										</div>
 									</div>
 								</div>
+
 								<?php
 							}
 							?>
-							<div class="row mb-1">
-								<label class="col-sm-4 col-form-label col-form-label-sm" for="include-previous-test"><?=htmlspecialchars(__("Previous Test"))?></label>
-								<div class="col-sm">
-									<div class="custom-control custom-checkbox">
-										<input class="custom-control-input" type="checkbox" name="include_previous_test" id="include-previous-test" value="1" checked />
-										<label class="custom-control-label" for="include-previous-test">
-											<?=htmlspecialchars(__("Attach PDF"))?>
+
+						</section>
+
+						<?php
+						if($test->getStatus() === Test::STATUS_PENDING_VERIFICATION) {
+							?>
+							<section class="mb-4">
+								<h5><?=htmlspecialchars(__("Notifications"))?></h5>
+
+								<?php
+								$customer_checked = $customer->email_after_test;
+								$location_checked = $customer->email_locations_after_test;
+
+								$email_address_configs = [
+									["email" => $customer->email, "label" => "Email Headquarters", "name" => "email_customer", "checked" => $customer_checked],
+									["email" => $location->email, "label" => "Email Venue", "name" => "email_location", "checked" => $location_checked],
+									["email" => $location->area_manager_email, "label" => "Email AM", "name" => "email_location_area_manager", "checked" => $location_checked],
+									["email" => $location->operations_manager_email, "label" => "Email OM", "name" => "email_location_operations_manager", "checked" => $location_checked],
+									["email" => $location->gaming_manager_email, "label" => "Email GM", "name" => "email_location_gaming_manager", "checked" => $location_checked],
+									["email" => $location->senior_gaming_manager_email, "label" => "Email SGM", "name" => "email_location_senior_gaming_manager", "checked" => $location_checked],
+								];
+
+								foreach($email_address_configs as $email_address_config) {
+									$email_address = $email_address_config["email"];
+									if(!$email_address) {
+										continue;
+									}
+
+									$label = $email_address_config["label"];
+									$name = $email_address_config["name"];
+									$checked = $email_address_config["checked"];
+									$id = str_replace("_", "-", $name);
+									?>
+									<div class="row mb-1">
+										<label class="col-sm-4 col-form-label col-form-label-sm" for="<?= $id ?>">
+											<?= htmlspecialchars($label) ?>
 										</label>
+										<div class="col-sm">
+											<div class="custom-control custom-checkbox">
+												<input class="custom-control-input" type="checkbox" name="<?= $name ?>"
+													   id="<?= $id ?>" value="1" <?= Form::checked($checked) ?> />
+												<label class="custom-control-label"
+													   for="<?= $id ?>"><?= htmlspecialchars($email_address) ?></label>
+											</div>
+										</div>
+									</div>
+									<?php
+								}
+								?>
+								<div class="row mb-1">
+									<label class="col-sm-4 col-form-label col-form-label-sm"
+										   for="include-previous-test"><?= htmlspecialchars(__("Previous Test")) ?></label>
+									<div class="col-sm">
+										<div class="custom-control custom-checkbox">
+											<input class="custom-control-input" type="checkbox" name="include_previous_test"
+												   id="include-previous-test" value="1" checked/>
+											<label class="custom-control-label" for="include-previous-test">
+												<?= htmlspecialchars(__("Attach PDF")) ?>
+											</label>
+										</div>
 									</div>
 								</div>
-							</div>
 
-							<div class="row mb-1">
-								<label class="col-sm-4 col-form-label" for="tester-message">Message to Tester (if rejecting)</label>
-								<div class="col-sm">
-									<textarea class="form-control form-control-sm" name="tester_message" id="tester-message" placeholder="Enter message to tester" rows="4"><?=htmlspecialchars($tester_message)?></textarea>
+								<div class="row mb-1">
+									<label class="col-sm-4 col-form-label col-form-label-sm" for="tester-message">Message to Tester (if
+										rejecting)</label>
+									<div class="col-sm">
+								<textarea class="form-control form-control-sm" name="tester_message"
+										  id="tester-message" placeholder="Enter message to tester"
+										  rows="4"><?= htmlspecialchars($tester_message) ?></textarea>
+									</div>
 								</div>
-							</div>
+							</section>
+							<?php
+						}
+						?>
+
+						<?php
+						// Submit buttons
 
+						if($test->getStatus() === Test::STATUS_PENDING_VERIFICATION) {
+							?>
 							<div class="row mb-1">
 								<div class="col-sm offset-sm-4">
-									<button class="btn btn-success" type="submit" name="accept" value="1">Accept</button>
+									<button class="btn btn-success" type="submit" name="accept" value="1">Accept
+									</button>
 									<button class="btn btn-danger" type="submit" name="reject" value="1">Reject</button>
 								</div>
 							</div>
@@ -545,6 +616,7 @@ function render_card_list_group($details) {
 							<?php
 						}
 						?>
+
 					</div>
 				</div>