소스 검색

Add ability to add tickets and comments

Alan Lam 4 년 전
부모
커밋
f5d1a354e9

+ 1 - 0
.gitignore

@@ -1,3 +1,4 @@
 /.env
 /.env
 /phinx.php
 /phinx.php
 /vendor/
 /vendor/
+/files/ticket_attachments/*

+ 1 - 0
boot.php

@@ -13,6 +13,7 @@ try {
 	$dotenv->load();
 	$dotenv->load();
 	$dotenv->required(["DB_HOST", "DB_USERNAME", "DB_PASSWORD", "DB_NAME"]);
 	$dotenv->required(["DB_HOST", "DB_USERNAME", "DB_PASSWORD", "DB_NAME"]);
 	$dotenv->required(["DIR_ROOT", "TIMEZONE", "LOCALE", "SESSION_NAME", "ENV"])->notEmpty();
 	$dotenv->required(["DIR_ROOT", "TIMEZONE", "LOCALE", "SESSION_NAME", "ENV"])->notEmpty();
+	$_ENV["ROOT_DIR"] = __DIR__;
 }
 }
 catch(ValidationException $e) {
 catch(ValidationException $e) {
 	echo $e->getMessage();
 	echo $e->getMessage();

+ 2 - 1
composer.json

@@ -27,7 +27,8 @@
         "nesbot/carbon": "^2.58",
         "nesbot/carbon": "^2.58",
         "paragonie/anti-csrf": "^2.3",
         "paragonie/anti-csrf": "^2.3",
         "robmorgan/phinx": "^0.12.10",
         "robmorgan/phinx": "^0.12.10",
-        "vlucas/phpdotenv": "^5.4"
+        "vlucas/phpdotenv": "^5.4",
+		"ext-bcmath": "*"
 	},
 	},
 	"require-dev": {
 	"require-dev": {
 		"roave/security-advisories": "dev-latest"
 		"roave/security-advisories": "dev-latest"

+ 22 - 0
controllers/download_file.php

@@ -0,0 +1,22 @@
+<?php /** @noinspection PhpUnhandledExceptionInspection */
+
+namespace App;
+
+use RuntimeException;
+
+/**
+ * @var string $type
+ * @var string $id
+ */
+
+switch($type) {
+	case "ticket-comment-attachment":
+		$attachment = TicketCommentAttachment::get($id);
+		if(!$attachment) {
+			throw new RuntimeException(__("Attachment not found."));
+		}
+
+		header("Content-Type: $attachment->mime_type");
+		readfile($attachment->getPath());
+		exit(0);
+}

+ 41 - 0
controllers/locations_ajax.php

@@ -0,0 +1,41 @@
+<?php
+
+namespace App;
+
+/**
+ * @var string $action
+ */
+
+$controller = new class($action) {
+	private $action;
+
+	public function __construct(string $action) {
+		$this->action = $action;
+	}
+
+	public function run(): void {
+		switch($this->action) {
+			case "get-options":
+				$this->getOptions();
+				break;
+			default:
+				break;
+		}
+	}
+
+	public function getOptions(): void {
+		$locations = Location::query([], ["sort" => "name"]);
+		$options = [];
+		foreach($locations as $location) {
+			$options[] = [
+				"value" => $location->id,
+				"display" => $location->name
+			];
+		}
+		Json::success([
+			"options" => $options
+		]);
+	}
+};
+
+$controller->run();

+ 54 - 0
controllers/ticket.php

@@ -0,0 +1,54 @@
+<?php /** @noinspection PhpUnhandledExceptionInspection */
+
+namespace App;
+
+use RuntimeException;
+
+/**
+ * @var int $id
+ */
+
+$core = Core::getInstance();
+$core->addBreadcrumb("/tickets", __("Tickets"));
+
+$user = $core->getUser();
+
+$ticket = Ticket::get($id);
+if(!$ticket) {
+	throw new RuntimeException(__("Ticket not found."));
+}
+
+$core->addBreadcrumb("/tickets/$id", $ticket->subject);
+
+$request = Request::fromRequest();
+
+$submit = $request->int("submit");
+if($submit) {
+	$content = $request->string("content");
+	$internal = (int) $request->int("internal");
+	$status = $request->int("status");
+	$attachments = Request::getFileArray("attachments", true);
+
+	$comment = new TicketComment();
+	$comment->ticket_id = $ticket->id;
+	$comment->user_id = $user->id;
+	$comment->content = $content;
+	$comment->internal = $internal;
+	$comment->dts_created = Database::dts();
+	$comment->commit();
+
+	$ticket->status = $status;
+	$ticket->commit();
+
+	foreach($attachments as $attachment) {
+		$comment->addAttachment($attachment);
+	}
+
+	Session::addAlert("success", __("Comment added successfully."));
+
+	Http::redirect($ticket->getUrl());
+}
+
+View::include("header");
+View::include("ticket", compact("ticket"));
+View::include("footer");

+ 14 - 2
controllers/tickets.php

@@ -1,10 +1,22 @@
-<?php
+<?php /** @noinspection PhpUnhandledExceptionInspection */
 
 
 namespace App;
 namespace App;
 
 
 $core = Core::getInstance();
 $core = Core::getInstance();
 $core->addBreadcrumb("/tickets", __("Tickets"));
 $core->addBreadcrumb("/tickets", __("Tickets"));
 
 
+$core = Core::getInstance();
+$core->addScript("/js/ticket-modal.js");
+
+$request = Request::fromRequest();
+
+$nvp = [
+	"dts_deleted" => null
+];
+
+$tickets = Ticket::query($nvp, ["sort" => "dts_updated", "order" => "desc"]);
+
 View::include("header");
 View::include("header");
-View::include("tickets");
+View::include("tickets", compact("tickets"));
+View::include("modals/ticket");
 View::include("footer");
 View::include("footer");

+ 69 - 0
controllers/tickets_ajax.php

@@ -0,0 +1,69 @@
+<?php
+
+namespace App;
+
+use RuntimeException;
+
+/**
+ * @var string $action
+ */
+
+$controller = new class($action) {
+
+	/** @var string */
+	private $action;
+
+	/** @var User */
+	private $user;
+
+	public function __construct(string $action) {
+		$this->action = $action;
+
+		$core = Core::getInstance();
+		$this->user = $core->getUser();
+	}
+
+	public function run(): void {
+		switch($this->action) {
+			case "create":
+				$this->create();
+				break;
+
+			default:
+				throw new RuntimeException(__("Invalid action."));
+		}
+	}
+
+	private function create(): void {
+		$attachments = Request::getFileArray("attachments", true);
+
+		$request = Request::fromRequest();
+
+		$ticket = new Ticket();
+		$ticket->location_id = $request->int("location_id");
+		$ticket->creator_user_id = $this->user->id;
+		$ticket->subject = $request->string("subject");
+		$ticket->contact_name = $request->string("contact_name");
+		$ticket->dts_created = Database::dts();
+		$ticket->commit();
+
+		$comment = new TicketComment();
+		$comment->ticket_id = $ticket->id;
+		$comment->user_id = $this->user->id;
+		$comment->content = $request->string("content");
+		$comment->dts_created = Database::dts();
+		$comment->commit();
+
+		foreach($attachments as $attachment) {
+			$comment->addAttachment($attachment);
+		}
+
+		Session::addAlert("success", __("Ticket created successfully."));
+
+		Json::success([
+			"id" => $ticket->id
+		]);
+	}
+};
+
+$controller->run();

+ 32 - 0
db/migrations/20221109224205_add_ticket_table.php

@@ -0,0 +1,32 @@
+<?php
+declare(strict_types=1);
+
+use Phinx\Db\Adapter\MysqlAdapter;
+use Phinx\Migration\AbstractMigration;
+
+final class AddTicketTable extends AbstractMigration {
+	public function change(): void {
+		$this->table("ticket", ["signed" => false, "collation" => "utf8mb4_general_ci"])
+			->addColumn("location_id", "integer", ["signed" => false])
+			->addColumn("creator_user_id", "integer", ["signed" => false])
+			->addColumn("assigned_user_id", "integer", ["signed" => false, "null" => true])
+
+			->addColumn("subject", "string")
+			->addColumn("contact_name", "string", ["null" => true])
+			->addColumn("status", "integer", ["signed" => false, "limit" => MysqlAdapter::INT_TINY, "default" => "0"])
+			->addColumn("priority", "integer", ["signed" => false, "limit" => MysqlAdapter::INT_TINY, "default" => "2"])
+			->addColumn("rating", "integer", ["signed" => false, "limit" => MysqlAdapter::INT_TINY, "null" => true])
+
+			->addColumn("dts_due", "datetime", ["null" => true])
+
+			->addColumn("dts_created", "datetime")
+			->addColumn("dts_updated", "datetime", ["null" => true])
+			->addColumn("dts_deleted", "datetime", ["null" => true])
+
+			->addForeignKey("location_id", "location", "id", ["update" => "CASCADE", "delete" => "CASCADE"])
+			->addForeignKey("creator_user_id", "user", "id", ["update" => "CASCADE", "delete" => "CASCADE"])
+			->addForeignKey("assigned_user_id", "user", "id", ["update" => "CASCADE", "delete" => "CASCADE"])
+
+			->create();
+	}
+}

+ 19 - 0
db/migrations/20221109224846_add_ticket_comment_table.php

@@ -0,0 +1,19 @@
+<?php
+declare(strict_types=1);
+
+use Phinx\Migration\AbstractMigration;
+
+final class AddTicketCommentTable extends AbstractMigration {
+	public function change(): void {
+		$this->table("ticket_comment", ["signed" => false, "collation" => "utf8mb4_general_ci"])
+			->addColumn("ticket_id", "integer", ["signed" => false])
+			->addColumn("user_id", "integer", ["signed" => false])
+			->addColumn("content", "text")
+			->addColumn("internal", "boolean", ["signed" => false, "default" => 0])
+			->addColumn("dts_created", "datetime")
+			->addColumn("dts_deleted", "datetime", ["null" => true])
+			->addForeignKey("ticket_id", "ticket", "id", ["update" => "CASCADE", "delete" => "CASCADE"])
+			->addForeignKey("user_id", "user", "id", ["update" => "CASCADE", "delete" => "CASCADE"])
+			->create();
+	}
+}

+ 16 - 0
db/migrations/20221109225114_add_ticket_comment_attachment_table.php

@@ -0,0 +1,16 @@
+<?php
+declare(strict_types=1);
+
+use Phinx\Migration\AbstractMigration;
+
+final class AddTicketCommentAttachmentTable extends AbstractMigration {
+	public function change(): void {
+		$this->table("ticket_comment_attachment", ["signed" => false, "collation" => "utf8mb4_general_ci"])
+			->addColumn("ticket_comment_id", "integer", ["signed" => false])
+			->addColumn("mime_type", "string")
+			->addColumn("file_name", "string")
+			->addColumn("file_size", "integer", ["signed" => false])
+			->addForeignKey("ticket_comment_id", "ticket_comment", "id", ["update" => "CASCADE", "delete" => "RESTRICT"])
+			->create();
+	}
+}

+ 17 - 0
engine/Enums/AbstractEnum.php

@@ -0,0 +1,17 @@
+<?php
+
+namespace App\Enums;
+
+abstract class AbstractEnum {
+
+	abstract public static function options(): array;
+
+	public static function validate($value): bool {
+		return isset(static::options()[$value]);
+	}
+
+	public static function enumToText($value): string {
+		return static::options()[$value] ?? "";
+	}
+
+}

+ 42 - 0
engine/Enums/TicketPriorities.php

@@ -0,0 +1,42 @@
+<?php
+
+namespace App\Enums;
+
+class TicketPriorities extends AbstractEnum {
+
+	public const LOWEST = 0;
+	public const LOW = 1;
+	public const NORMAL = 2;
+	public const HIGH = 3;
+	public const HIGHEST = 4;
+
+	public static function options(): array {
+		return [
+			self::HIGHEST => __("Highest"),
+			self::HIGH => __("High"),
+			self::NORMAL => __("Normal"),
+			self::LOW => __("Low"),
+			self::LOWEST => __("Lowest"),
+		];
+	}
+
+	public static function getBadgeHtml($value): string {
+		switch($value) {
+			case self::HIGHEST:
+			case self::HIGH:
+				$class = "danger";
+				break;
+			default:
+			case self::NORMAL:
+				$class = "primary";
+				break;
+			case self::LOW:
+			case self::LOWEST:
+				$class = "info";
+				break;
+		}
+
+		return "<span class=\"badge bg-$class\">" . htmlspecialchars(self::enumToText($value)) . "</span>";
+	}
+
+}

+ 24 - 0
engine/Enums/TicketStatuses.php

@@ -0,0 +1,24 @@
+<?php
+
+namespace App\Enums;
+
+class TicketStatuses extends AbstractEnum {
+
+	public const NEW = 0;
+	public const IN_PROGRESS = 1;
+	public const INFORMATION_REQUESTED = 2;
+	public const ON_HOLD = 3;
+	public const SOLVED = 4;
+	public const CLOSED = 5;
+
+	public static function options(): array {
+		return [
+			self::NEW => "New",
+			self::IN_PROGRESS => "In Progress",
+			self::INFORMATION_REQUESTED => "Information Requested",
+			self::ON_HOLD => "On Hold",
+			self::SOLVED => "Solved",
+			self::CLOSED => "Closed",
+		];
+	}
+}

+ 18 - 0
engine/Helpers/HtmlHelper.php

@@ -0,0 +1,18 @@
+<?php
+
+namespace App\Helpers;
+
+class HtmlHelper {
+
+	public static function renderOptions(array $options, $selected_value): void {
+		foreach($options as $value => $display) {
+			$selected = ((string) $value === (string) $selected_value) ? "selected" : "";
+			?>
+			<option value="<?=htmlspecialchars($value)?>" <?=$selected?>>
+				<?=htmlspecialchars($display)?>
+			</option>
+			<?php
+		}
+	}
+
+}

+ 29 - 0
engine/Json.php

@@ -0,0 +1,29 @@
+<?php
+
+namespace App;
+
+class Json {
+
+	public static function header(): void {
+		header("Content-Type: application/json");
+	}
+
+	public static function success(array $data = [], int $response_code = 200): void {
+		self::header();
+		$output = array_merge($data, ["success" => true]);
+		http_response_code($response_code);
+		echo json_encode($output);
+		exit(0);
+	}
+
+	public static function fail(?string $message = null, int $response_code = 400): void {
+		self::header();
+		http_response_code($response_code);
+		echo json_encode([
+			"success" => false,
+			"message" => $message
+		]);
+		exit(0);
+	}
+
+}

+ 45 - 0
engine/Request.php

@@ -2,6 +2,8 @@
 
 
 namespace App;
 namespace App;
 
 
+use RuntimeException;
+
 class Request {
 class Request {
 
 
 	private $data;
 	private $data;
@@ -26,6 +28,49 @@ class Request {
 		return $request;
 		return $request;
 	}
 	}
 
 
+	/**
+	 * @param string $name
+	 * @param bool $validate Performs validation and returns only files that have been uploaded
+	 * @return array|array[]
+	 */
+	public static function getFileArray(string $name, bool $validate = false): array {
+		$form_files = $_FILES[$name] ?? [];
+		$files = [];
+		if($form_files) {
+			// Single file field
+			$names = $form_files["name"];
+			if(!is_array($names)) {
+				return [$form_files];
+			}
+
+			// Multiple file field
+			$file_count = count($form_files["name"]);
+			for($i = 0; $i < $file_count; $i++) {
+				$files[] = [
+					"name" => $form_files["name"][$i],
+					"type" => $form_files["type"][$i],
+					"size" => $form_files["size"][$i],
+					"tmp_name" => $form_files["tmp_name"][$i],
+					"error" => $form_files["error"][$i],
+				];
+			}
+		}
+
+		if($validate) {
+			foreach($files as $index => $file) {
+				if(!in_array($file["error"], [UPLOAD_ERR_OK, UPLOAD_ERR_NO_FILE])) {
+					throw new RuntimeException(__("File upload error."));
+				}
+
+				if($file["error"] === UPLOAD_ERR_NO_FILE) {
+					unset($files[$index]);
+				}
+			}
+		}
+
+		return array_values($files);
+	}
+
 	// Object methods
 	// Object methods
 
 
 	public function hasData(): bool {
 	public function hasData(): bool {

+ 99 - 0
engine/Ticket.php

@@ -0,0 +1,99 @@
+<?php
+
+namespace App;
+
+use App\Enums\TicketPriorities;
+use App\Enums\TicketStatuses;
+use Carbon\CarbonImmutable;
+
+/**
+ * Class Ticket
+ * @property int $id
+ * @property int $location_id
+ * @property int $creator_user_id
+ * @property int $assigned_user_id
+ * @property string $subject
+ * @property string $contact_name
+ * @property int $status
+ * @property int $priority
+ * @property int $rating
+ * @property string $dts_due
+ * @property string $dts_created
+ * @property string $dts_updated
+ * @property string $dts_deleted
+ */
+
+class Ticket extends Model {
+
+	protected static $table = "ticket";
+	protected static $idField = "id";
+	protected static $fillableFields = [
+		"location_id", "creator_user_id", "assigned_user_id",
+		"subject", "contact_name", "status", "priority", "rating",
+		"dts_due",
+		"dts_created", "dts_updated", "dts_deleted",
+	];
+
+	public function getLocation(): Location {
+		return Location::get($this->location_id);
+	}
+
+	public function getCreator(): User {
+		return User::get($this->creator_user_id);
+	}
+
+	public function getAssignedTo(): ?User {
+		return User::get($this->assigned_user_id);
+	}
+
+	public function getDateTimeCreated(): CarbonImmutable {
+		return new CarbonImmutable($this->dts_created, "UTC");
+	}
+
+	public function getDateTimeUpdated(): ?CarbonImmutable {
+		return $this->dts_updated ? new CarbonImmutable($this->dts_updated, "UTC") : null;
+	}
+
+	public function getDateTimeDue(): ?CarbonImmutable {
+		return $this->dts_due ? new CarbonImmutable($this->dts_due, "UTC") : null;
+	}
+
+	/**
+	 * @return TicketComment[]
+	 */
+	public function getComments(): array {
+		return TicketComment::query(["ticket_id" => $this->id], ["sort" => "id"]);
+	}
+
+	public function getDisplayCreator(): string {
+		$creator = $this->getCreator();
+		return $creator->getDisplayName() . " ($creator->email)";
+	}
+
+	public function getDisplayAssignedTo(): string {
+		$assigned_to = $this->getAssignedTo();
+		return $assigned_to ? $assigned_to->getDisplayName() . " ($assigned_to->email)" : __("Unassigned");
+	}
+
+	public function getDisplayStatus(): string {
+		return TicketStatuses::enumToText($this->status);
+	}
+
+	public function getPriorityBadgeHtml(): string {
+		return TicketPriorities::getBadgeHtml($this->priority);
+	}
+
+	public function getDisplayCreatedDateTime(): string {
+		return $this->getDateTimeCreated()->format("d/m/Y H:i");
+	}
+
+	public function getDisplayUpdatedDateTime(): string {
+		$dt_updated = $this->getDateTimeUpdated();
+		return $dt_updated ? $dt_updated->format("d/m/Y H:i") : __("Never");
+	}
+
+	public function getUrl(): string {
+		return sprintf("/tickets/%d", $this->id);
+	}
+
+}

+ 89 - 0
engine/TicketComment.php

@@ -0,0 +1,89 @@
+<?php
+
+namespace App;
+
+use Carbon\CarbonImmutable;
+use Exception;
+
+/**
+ * Class TicketComment
+ * @property int $id
+ * @property int $ticket_id
+ * @property int $user_id
+ * @property string $content
+ * @property int $internal
+ * @property string $dts_created
+ * @property string $dts_deleted
+ */
+
+class TicketComment extends Model {
+
+	protected static $table = "ticket_comment";
+	protected static $idField = "id";
+	protected static $fillableFields = [
+		"ticket_id", "user_id",
+		"content",
+		"internal",
+		"dts_created", "dts_deleted",
+	];
+
+	/**
+	 * @return Ticket
+	 * @throws Exception
+	 */
+	public function getTicket(): Ticket {
+		return Ticket::get($this->ticket_id);
+	}
+
+	/**
+	 * @return User
+	 * @throws Exception
+	 */
+	public function getUser(): User {
+		return User::get($this->user_id);
+	}
+
+	public function getDateTime(): CarbonImmutable {
+		return new CarbonImmutable($this->dts_created, "UTC");
+	}
+
+	/**
+	 * @return TicketCommentAttachment[]
+	 */
+	public function getAttachments(): array {
+		return TicketCommentAttachment::query([
+			"ticket_comment_id" => $this->id,
+		], [
+			"sort" => "id",
+			"order" => "desc"
+		]);
+	}
+
+	public function getHtml(): string {
+		return nl2br(htmlspecialchars($this->content));
+	}
+
+	public function getDisplayDateTimeCreated(): string {
+		return $this->getDateTime()->format("d/m/Y H:i");
+	}
+
+	/**
+	 * @param array $form_file
+	 * @return TicketCommentAttachment
+	 * @throws Exception
+	 */
+	public function addAttachment(array $form_file): TicketCommentAttachment {
+		$attachment = new TicketCommentAttachment();
+		$attachment->ticket_comment_id = $this->id;
+		$attachment->mime_type = $form_file["type"];
+		$attachment->file_name = $form_file["name"];
+		$attachment->file_size = $form_file["size"];
+		$attachment->commit();
+
+		$path = $attachment->getPath();
+		move_uploaded_file($form_file["tmp_name"], $path);
+
+		return $attachment;
+	}
+
+}

+ 52 - 0
engine/TicketCommentAttachment.php

@@ -0,0 +1,52 @@
+<?php
+
+namespace App;
+
+use RuntimeException;
+
+/**
+ * Class TicketCommentAttachment
+ * @property int $id
+ * @property int $ticket_comment_id
+ * @property string $mime_type
+ * @property string $file_name
+ * @property int $file_size
+ */
+
+class TicketCommentAttachment extends Model {
+	protected static $table = "ticket_comment_attachment";
+	protected static $idField = "id";
+	protected static $fillableFields = [
+		"ticket_comment_id",
+		"mime_type", "file_name", "file_size"
+	];
+
+	public function getTicketComment(): TicketComment {
+		return TicketComment::get($this->ticket_comment_id);
+	}
+
+	private function getDirectory(): string {
+		$subfolder = bcdiv($this->id, 1000);
+		$folder = $_ENV["ROOT_DIR"] . "/files/ticket_attachments/$subfolder";
+
+		if(!file_exists($folder) && !mkdir($folder, 0777, true) && !is_dir($folder)) {
+			throw new RuntimeException(sprintf('Directory "%s" was not created', $folder));
+		}
+
+		return $folder;
+	}
+
+	public function getPath(): string {
+		return $this->getDirectory() . "/" . $this->id;
+	}
+
+	public function renderButton(): void {
+		?>
+		<a class="btn btn-sm btn-outline-primary" href="/download-file/ticket-comment-attachment/<?=$this->id?>" target="_blank">
+			<i class="fa fa-fw fa-paperclip"></i>
+			<?=htmlspecialchars($this->file_name)?>
+		</a>
+		<?php
+	}
+
+}

+ 22 - 0
engine/User.php

@@ -3,6 +3,7 @@
 namespace App;
 namespace App;
 
 
 use Carbon\CarbonImmutable;
 use Carbon\CarbonImmutable;
+use DateTimeInterface;
 use Exception;
 use Exception;
 use RuntimeException;
 use RuntimeException;
 
 
@@ -123,4 +124,25 @@ class User extends Model {
 			throw new RuntimeException(__("You do not have permission to access this page."));
 			throw new RuntimeException(__("You do not have permission to access this page."));
 		}
 		}
 	}
 	}
+
+	public function getDisplayName(): string {
+		return $this->first_name . " " . $this->last_name;
+	}
+
+	public function getAvatarUrl(): string {
+		return "https://www.gravatar.com/avatar/" . md5($this->email) . "?d=mp";
+	}
+
+	public function formatDateTime(?DateTimeInterface $dt, string $format = "d/m/Y H:i"): string {
+		if(!$dt) {
+			return __("Never");
+		}
+
+		return CarbonImmutable::instance($dt)->setTimezone("Europe/London")->format("d/m/Y H:i");
+	}
+
+	public function formatDate(?DateTimeInterface $dt): string {
+		return $this->formatDateTime($dt, "d/m/Y");
+	}
+
 }
 }

+ 3 - 2
public/js/app.js

@@ -71,7 +71,8 @@ class AddressMap {
 }
 }
 
 
 /* Map Overview */
 /* Map Overview */
-class Map {
+
+class GoogleMap {
 	constructor(element) {
 	constructor(element) {
 		this.element = element;
 		this.element = element;
 		this.markers = [];
 		this.markers = [];
@@ -142,6 +143,6 @@ $(() => {
 
 
 	const map = document.getElementById("map");
 	const map = document.getElementById("map");
 	if(map) {
 	if(map) {
-		new Map(map);
+		new GoogleMap(map);
 	}
 	}
 });
 });

+ 62 - 0
public/js/ticket-modal.js

@@ -0,0 +1,62 @@
+class TicketModal {
+	constructor() {
+		this.$modal = $("#ticket-modal");
+		this.modal = bootstrap.Modal.getInstance(this.$modal.get(0));
+
+		this.$modal.on("show.bs.modal", event => this.onShow(event));
+		this.$modal.on("shown.bs.modal", () => this.onShown());
+		this.$modal.on("hidden.bs.modal", () => this.onHidden());
+
+		this.$title = this.$modal.find(".modal-title");
+
+		this.$form = this.$modal.find("form");
+		this.$form.on("submit", event => this.onSubmit(event));
+
+		this.$subjectField = this.$form.find("[name=subject]");
+		this.$locationDropdown = this.$form.find("[name=location_id]");
+	}
+
+	// Modal lifecycle
+	onShow(event) {
+	    const $element = $(event.relatedTarget);
+	    const data = $element.data();
+	}
+
+	onShown() {
+	    this.$subjectField.trigger("focus");
+		fetch("/locations/get-options").then(body => {
+			return body.json()
+		}).then(response => {
+			const $options = response.options.map(option => {
+				const $option = $(`<option value="${option.value}">`);
+				$option.text(option.display);
+				return $option;
+			});
+			this.$locationDropdown.append($options);
+		});
+	}
+
+	onHidden() {
+		this.$form.get(0).reset();
+		this.$locationDropdown.find("option[value!='']").remove();
+	}
+
+	onSubmit(event) {
+		event.preventDefault();
+
+		$.ajax({
+			url: "/tickets/create",
+			type: "POST",
+			data: new FormData(this.$form.get(0)),
+			processData: false,
+			contentType: false,
+			success: response => {
+				this.$modal.modal("hide");
+				window.location = `/tickets/${response.id}`;
+			}
+		})
+	}
+
+}
+
+$(() => new TicketModal());

+ 6 - 0
routes/default.php

@@ -28,6 +28,7 @@ $this->addRoute("/^companies\/$slug_pattern\/update$/", "company_form", ["id"],
 
 
 $this->addRoute("/^locations$/", "locations", [], ["requireUser" => true]);
 $this->addRoute("/^locations$/", "locations", [], ["requireUser" => true]);
 $this->addRoute("/^locations\/add$/", "location_form", [], ["requireUser" => true]);
 $this->addRoute("/^locations\/add$/", "location_form", [], ["requireUser" => true]);
+$this->addRoute("/^locations\/(get-options)$/", "locations_ajax", ["action"], ["requireUser" => true]);
 $this->addRoute("/^locations\/$slug_pattern\/update$/", "location_form", ["id"], ["requireUser" => true]);
 $this->addRoute("/^locations\/$slug_pattern\/update$/", "location_form", ["id"], ["requireUser" => true]);
 
 
 $this->addRoute("/^suppliers$/", "suppliers", [], ["requireUser" => true]);
 $this->addRoute("/^suppliers$/", "suppliers", [], ["requireUser" => true]);
@@ -45,7 +46,12 @@ $this->addRoute("/^users\/add$/", "user_form", [], ["requireUser" => true]);
 $this->addRoute("/^users\/$id_pattern\/update$/", "user_form", ["id"], ["requireUser" => true]);
 $this->addRoute("/^users\/$id_pattern\/update$/", "user_form", ["id"], ["requireUser" => true]);
 
 
 $this->addRoute("/^sales$/", "sales", [], ["requireUser" => true]);
 $this->addRoute("/^sales$/", "sales", [], ["requireUser" => true]);
+
 $this->addRoute("/^tickets$/", "tickets", [], ["requireUser" => true]);
 $this->addRoute("/^tickets$/", "tickets", [], ["requireUser" => true]);
+$this->addRoute("/^tickets\/(create)$/", "tickets_ajax", ["action"], ["requireUser" => true]);
+$this->addRoute("/^tickets\/(\d+)$/", "ticket", ["id"], ["requireUser" => true]);
+
+$this->addRoute("/^download-file\/(ticket-comment-attachment)\/(\d+)$/", "download_file", ["type", "id"], ["requireUser" => true]);
 
 
 $this->addRoute("/^reset-password$/", "reset_password");
 $this->addRoute("/^reset-password$/", "reset_password");
 $this->addRoute("/^settings$/", "settings", [], ["requireUser" => true]);
 $this->addRoute("/^settings$/", "settings", [], ["requireUser" => true]);

+ 1 - 0
views/footer.php

@@ -1,3 +1,4 @@
+				</div>
 			</div>
 			</div>
 		</div>
 		</div>
 		<footer>
 		<footer>

+ 20 - 4
views/header.php

@@ -16,10 +16,16 @@ $google_api_key = $_ENV["GOOGLE_API_KEY"] ?? null;
 	<meta http-equiv="X-UA-Compatible" content="ie=edge">
 	<meta http-equiv="X-UA-Compatible" content="ie=edge">
 	<title><?=htmlspecialchars($core->getSiteName())?></title>
 	<title><?=htmlspecialchars($core->getSiteName())?></title>
 
 
-	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
-	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
-	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
-	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" />
+	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.1/dist/jquery.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
+
+	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" integrity="sha256-IUOUHAPazai08QFs7W4MbzTlwEWFo7z/4zw8YmxEiko=" crossorigin="anonymous">
+	<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha256-xLI5SjD6DkojxrMIVBNT4ghypv12Xtj7cOa0AgKd6wA=" crossorigin="anonymous"></script>
+
+	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/toastr@2.1.4/build/toastr.min.css" integrity="sha256-R91pD48xW+oHbpJYGn5xR0Q7tMhH4xOrWn1QqMRINtA=" crossorigin="anonymous">
+	<script src="https://cdn.jsdelivr.net/npm/toastr@2.1.4/build/toastr.min.js" integrity="sha256-Hgwq1OBpJ276HUP9H3VJkSv9ZCGRGQN+JldPJ8pNcUM=" crossorigin="anonymous"></script>
+
+	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
+
 	<?php
 	<?php
 	if($google_api_key) {
 	if($google_api_key) {
 		?>
 		?>
@@ -30,6 +36,14 @@ $google_api_key = $_ENV["GOOGLE_API_KEY"] ?? null;
 
 
 	<script src="/js/app.js"></script>
 	<script src="/js/app.js"></script>
 
 
+	<?php
+	foreach($core->getGlobalScripts() as $script) {
+		?>
+		<script src="<?=htmlspecialchars($script)?>"></script>
+		<?php
+	}
+	?>
+
 	<style>
 	<style>
 		input:invalid, select:invalid {
 		input:invalid, select:invalid {
 			border: 1px solid red;
 			border: 1px solid red;
@@ -108,3 +122,5 @@ $google_api_key = $_ENV["GOOGLE_API_KEY"] ?? null;
 			<?php
 			<?php
 			View::include("components/breadcrumbs");
 			View::include("components/breadcrumbs");
 			View::include("components/alerts");
 			View::include("components/alerts");
+			?>
+			<div class="mb-3">

+ 10 - 0
views/modals/header.php

@@ -0,0 +1,10 @@
+<?php
+/**
+ * @var string $title
+ */
+?>
+<div class="modal-header">
+	<h5 class="modal-title"><?=htmlspecialchars($title)?></h5>
+	<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
+</div>
+

+ 47 - 0
views/modals/ticket.php

@@ -0,0 +1,47 @@
+<?php
+namespace App;
+?>
+<div class="modal fade" role="dialog" tabindex="-1" data-bs-backdrop="static" id="ticket-modal">
+	<div class="modal-dialog modal-lg">
+		<form class="modal-content" method="post">
+			<?php
+			View::include("modals/header", ["title" => __("New Ticket")]);
+			?>
+			<div class="modal-body">
+				<div class="mb-2">
+					<label class="form-label" for="ticket-subject"><?=htmlspecialchars(__("Subject"))?></label>
+					<input class="form-control" type="text" name="subject" id="ticket-subject" maxlength="255" placeholder="<?=htmlspecialchars(__("Type subject"))?>" required />
+				</div>
+				<div class="mb-2">
+					<label class="form-label" for="ticket-content"><?=htmlspecialchars(__("Content"))?></label>
+					<textarea class="form-control" name="content" id="ticket-content" rows="8" placeholder="<?=htmlspecialchars(__("Type content"))?>" required></textarea>
+				</div>
+				<div class="row">
+					<div class="col-lg">
+						<div class="mb-2">
+							<label class="form-label" for="ticket-location"><?=htmlspecialchars(__("Location"))?></label>
+							<select class="form-control" name="location_id" id="ticket-location" required>
+								<option value=""><?=htmlspecialchars(__("Select Location"))?></option>
+							</select>
+						</div>
+					</div>
+					<div class="col-lg">
+						<div class="mb-2">
+							<label class="form-label" for="ticket-contact-name"><?=htmlspecialchars(__("Contact Name"))?></label>
+							<input class="form-control" name="contact_name" id="ticket-contact-name" type="text" maxlength="255" placeholder="<?=htmlspecialchars(__("Type contact name"))?>" />
+						</div>
+					</div>
+				</div>
+				<div class="mb-2">
+					<label class="form-label" for="ticket-attachments"><?=htmlspecialchars(__("Attachments"))?></label>
+					<input class="form-control" type="file" name="attachments[]" multiple />
+				</div>
+			</div>
+			<div class="modal-footer">
+				<button type="submit" class="btn btn-success">
+					<?= htmlspecialchars(__("Save")) ?>
+				</button>
+			</div>
+		</form>
+	</div>
+</div>

+ 203 - 0
views/ticket.php

@@ -0,0 +1,203 @@
+<?php
+
+namespace App;
+
+use App\Enums\TicketStatuses;
+use App\Helpers\HtmlHelper;
+
+/**
+ * @var Ticket $ticket
+ */
+
+$core = Core::getInstance();
+$user = $core->getUser();
+
+$comments = $ticket->getComments();
+$ticket_details = array_shift($comments);
+$attachments = $ticket_details->getAttachments();
+$creator = $ticket->getCreator();
+
+$render_data_row = static function(string $title, string $html): void {
+	?>
+	<div class="row">
+		<div class="col-6">
+			<strong><?=htmlspecialchars($title)?></strong>
+		</div>
+		<div class="col-6">
+			<?=$html?>
+		</div>
+	</div>
+	<?php
+};
+
+?>
+<div class="card mb-3">
+	<div class="card-header">
+		<?=htmlspecialchars(__("Ticket #%d", $ticket->id))?>
+		<span class="float-end badge bg-primary">
+			<?=htmlspecialchars($ticket->getDisplayStatus())?>
+		</span>
+	</div>
+	<div class="card-body">
+		<h5>
+			<?=htmlspecialchars($ticket->subject)?>
+		</h5>
+		<div>
+			<i class="fa fa-fw fa-user-circle"></i>
+			<?=htmlspecialchars($creator->getDisplayName())?> (<?=htmlspecialchars($creator->email)?>)
+		</div>
+		<div>
+			<i class="fa fa-fw fa-map-marker"></i>
+			<?=htmlspecialchars($ticket->getLocation()->name)?>
+		</div>
+	</div>
+	<div class="card-body border-top">
+		<h5><?=htmlspecialchars(__("Details"))?></h5>
+		<?=$ticket_details->getHtml()?>
+	</div>
+	<?php
+	if($attachments) {
+		?>
+		<div class="card-body border-top">
+			<h5><?=htmlspecialchars(__("Attachments"))?></h5>
+			<?php
+			foreach($attachments as $attachment) {
+				$attachment->renderButton();
+			}
+			?>
+		</div>
+		<?php
+	}
+	?>
+	<div class="card-body border-top">
+		<h5><?=htmlspecialchars(__("Other Details"))?></h5>
+		<div class="row">
+			<div class="col-xl">
+				<?php
+				$render_data_row(__("Assigned:"), htmlspecialchars($ticket->getDisplayAssignedTo()));
+				$render_data_row(__("Priority:"), $ticket->getPriorityBadgeHtml());
+				$render_data_row(__("Contact Name:"), htmlspecialchars($ticket->contact_name));
+				?>
+			</div>
+			<div class="col-xl">
+				<?php
+				$render_data_row(__("Updated:"), $user->formatDateTime($ticket->getDateTimeUpdated()));
+				$render_data_row(__("Created:"), $user->formatDateTime($ticket->getDateTimeCreated()));
+				?>
+			</div>
+		</div>
+	</div>
+</div>
+
+<div class="card mb-3">
+	<div class="card-header">
+		<?=htmlspecialchars(__("Add Comment"))?>
+	</div>
+	<div class="card-body">
+		<form method="post" enctype="multipart/form-data">
+			<div class="row">
+				<div class="col-lg">
+					<div class="mb-2">
+						<label class="form-label" for="content"><?=htmlspecialchars(__("Comment"))?></label>
+						<textarea class="form-control" name="content" id="content" rows="4" placeholder="<?=htmlspecialchars(__("Type comment"))?>" required></textarea>
+					</div>
+
+					<div class="mb-2">
+						<div class="form-check form-switch">
+							<input class="form-check-input" name="internal" id="internal" type="checkbox" value="1" />
+							<label class="form-check-label" for="internal">
+								<?=htmlspecialchars(__("Internal Comment"))?>
+							</label>
+						</div>
+					</div>
+				</div>
+				<div class="col-lg">
+					<div class="mb-2">
+						<label class="form-label" for="status"><?=htmlspecialchars(__("Status"))?></label>
+						<select name="status" id="status" class="form-control">
+							<?php
+							HtmlHelper::renderOptions(TicketStatuses::options(), $ticket->status);
+							?>
+						</select>
+					</div>
+
+					<div class="mb-2">
+						<label class="form-label" for="attachments"><?=htmlspecialchars(__("Attachments"))?></label>
+						<input class="form-control" type="file" id="attachments" name="attachments[]" multiple />
+					</div>
+				</div>
+			</div>
+
+			<button type="submit" class="btn btn-primary" name="submit" value="1">
+				<?=htmlspecialchars(__("Update Ticket"))?>
+			</button>
+
+		</form>
+	</div>
+</div>
+
+
+<h3>
+	<?=htmlspecialchars(__("All Comments"))?>
+</h3>
+
+<?php
+if(empty($comments)) {
+	?>
+	<div class="alert alert-info">
+		<i class="fa fa-fw fa-info-circle"></i>
+		<?=htmlspecialchars(__("No comments have been added to this ticket."))?>
+	</div>
+	<?php
+}
+else {
+	foreach(array_reverse($comments) as $comment) {
+		$comment_user = $comment->getUser();
+		$attachments = $comment->getAttachments();
+		?>
+		<div class="card card-body mb-3">
+			<div class="d-flex">
+				<div class="flex-shrink-0">
+					<img src="<?=htmlspecialchars($comment_user->getAvatarUrl())?>" alt="<?=htmlspecialchars($comment_user->getDisplayName())?>" />
+				</div>
+				<div class="flex-grow-1 ms-3">
+					<div class="float-end">
+						<?php
+						if($comment->internal) {
+							?>
+							<span class="badge bg-primary">
+								<?=htmlspecialchars(__("Internal Comment"))?>
+							</span>
+							<?php
+						}
+						?>
+					</div>
+					<div>
+						<i class="fa fa-fw fa-user-circle"></i>
+						<?=htmlspecialchars($comment_user->getDisplayName())?> (<?=htmlspecialchars($comment_user->email)?>)
+					</div>
+					<div>
+						<i class="fa fa-fw fa-clock"></i>
+						<?=htmlspecialchars($comment->getDisplayDateTimeCreated())?>
+					</div>
+					<hr />
+					<?=$comment->getHtml()?>
+
+					<?php
+					if($attachments) {
+						?>
+						<hr />
+						<h5><?=htmlspecialchars(__("Attachments"))?></h5>
+						<?php
+						foreach($attachments as $attachment) {
+							$attachment->renderButton();
+						}
+					}
+					?>
+
+				</div>
+			</div>
+		</div>
+		<?php
+	}
+}

+ 70 - 5
views/tickets.php

@@ -2,6 +2,13 @@
 
 
 namespace App;
 namespace App;
 
 
+/**
+ * @var Ticket[] $tickets
+ */
+
+$core = Core::getInstance();
+$user = $core->getUser();
+
 ?>
 ?>
 
 
 <div class="row mb-3">
 <div class="row mb-3">
@@ -9,14 +16,72 @@ namespace App;
 		<h3><?=htmlspecialchars(__("Tickets"))?></h3>
 		<h3><?=htmlspecialchars(__("Tickets"))?></h3>
 	</div>
 	</div>
 	<div class="col-auto">
 	<div class="col-auto">
-		<a class="btn btn-success" href="/tickets/add">
+		<a class="btn btn-success" href="/tickets/add" data-bs-toggle="modal" data-bs-target="#ticket-modal">
 			<i class="fa fa-fw fa-plus"></i>
 			<i class="fa fa-fw fa-plus"></i>
 			<?=htmlspecialchars(__("Add"))?>
 			<?=htmlspecialchars(__("Add"))?>
 		</a>
 		</a>
 	</div>
 	</div>
 </div>
 </div>
 
 
-<div class="alert alert-warning">
-	<i class="fa fa-fw fa-info-circle"></i>
-	<?=htmlspecialchars(__("Coming soon..."))?>
-</div>
+<?php
+if(!$tickets) {
+	?>
+	<div class="alert alert-info">
+		<i class="fa fa-fw fa-info-circle"></i>
+		<?=htmlspecialchars(__("No tickets to display."))?>
+	</div>
+	<?php
+}
+else {
+	?>
+	<table class="table table-bordered table-hover">
+		<colgroup>
+			<col style="width: 1%;" />
+			<col style="width: 1%;" />
+			<col style="width: 30%;" />
+			<col style="width: 15%;" />
+			<col style="width: 15%;" />
+			<col style="width: 15%;" />
+			<col style="width: 15%;" />
+		</colgroup>
+		<thead>
+		<tr>
+			<th></th>
+			<th><?=htmlspecialchars("#")?></th>
+			<th><?=htmlspecialchars(__("Subject / Location"))?></th>
+			<th><?=htmlspecialchars(__("Status"))?></th>
+			<th><?=htmlspecialchars(__("Assigned To"))?></th>
+			<th><?=htmlspecialchars(__("Created"))?></th>
+			<th><?=htmlspecialchars(__("Updated"))?></th>
+		</tr>
+		</thead>
+		<tbody>
+		<?php
+		foreach($tickets as $ticket) {
+			$location = $ticket->getLocation();
+			?>
+			<tr>
+				<td>
+					<label for="ticket-checkbox-<?=$ticket->id?>" class="sr-only"></label>
+					<input type="checkbox" id="ticket-checkbox-<?=$ticket->id?>" name="ticket_ids[]" value="<?=$ticket->id?>" />
+				</td>
+				<td class="text-end"><?=$ticket->id?></td>
+				<td>
+					<strong>
+						<a href="/tickets/<?=$ticket->id?>"><?=htmlspecialchars($ticket->subject)?></a>
+					</strong><br />
+					<?=htmlspecialchars($location->name)?>
+				</td>
+				<td><?=htmlspecialchars($ticket->getDisplayStatus())?></td>
+				<td><?=htmlspecialchars($ticket->getDisplayAssignedTo())?></td>
+				<td><?=htmlspecialchars($user->formatDateTime($ticket->getDateTimeCreated()))?></td>
+				<td><?=htmlspecialchars($user->formatDateTime($ticket->getDateTimeUpdated()))?></td>
+			</tr>
+			<?php
+		}
+		?>
+		</tbody>
+	</table>
+	<?php
+}
+