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

Add ability to create sales, invoices and delivery notes

Alan Lam 3 лет назад
Родитель
Сommit
8600772c16
53 измененных файлов с 2881 добавлено и 68 удалено
  1. 274 0
      controllers/document.php
  2. 333 0
      controllers/sale.php
  3. 4 1
      controllers/sales.php
  4. 24 0
      db/migrations/20221219192033_add_sale_table.php
  5. 19 0
      db/migrations/20221219192253_add_sale_note_table.php
  6. 17 0
      db/migrations/20221219201955_add_sale_item_table.php
  7. 41 0
      db/migrations/20221220212227_add_document_table.php
  8. 20 0
      db/migrations/20221220213008_add_document_item_table.php
  9. 31 0
      engine/Address.php
  10. 6 1
      engine/Customer.php
  11. 170 0
      engine/Document.php
  12. 47 0
      engine/DocumentItem.php
  13. 17 0
      engine/Enums/Currencies.php
  14. 21 0
      engine/Enums/DocumentTypes.php
  15. 22 0
      engine/Enums/InvoiceStatuses.php
  16. 23 0
      engine/Enums/SaleStatuses.php
  17. 13 0
      engine/Helpers/HtmlHelper.php
  18. 15 0
      engine/Interfaces/AttachmentInterface.php
  19. 40 0
      engine/Interfaces/CommentInterface.php
  20. 9 0
      engine/Location.php
  21. 16 0
      engine/Request.php
  22. 129 0
      engine/Sale.php
  23. 60 0
      engine/SaleItem.php
  24. 75 0
      engine/SaleNote.php
  25. 19 0
      engine/Setting.php
  26. 5 11
      engine/Ticket.php
  27. 14 1
      engine/TicketComment.php
  28. 33 0
      engine/Traits/DateTimeTrait.php
  29. 23 0
      engine/Traits/SoftDeleteTrait.php
  30. 4 0
      engine/User.php
  31. 6 0
      engine/View.php
  32. 2 0
      public/js/app.js
  33. 70 0
      public/js/document-item-modal.js
  34. 29 0
      public/js/document-page.js
  35. 83 0
      public/js/sale-item-modal.js
  36. 67 0
      public/js/sale-note-modal.js
  37. 29 0
      public/js/sale-page.js
  38. 6 0
      routes/default.php
  39. 68 0
      views/components/comment_card.php
  40. 251 0
      views/document.php
  41. 169 0
      views/document_items_section.php
  42. 47 0
      views/modals/document_item.php
  43. 60 0
      views/modals/new_sale.php
  44. 48 0
      views/modals/sale_item.php
  45. 25 0
      views/modals/sale_note.php
  46. 9 1
      views/product_form.php
  47. 98 0
      views/sale.php
  48. 59 0
      views/sale_invoices_section.php
  49. 145 0
      views/sale_items_section.php
  50. 35 0
      views/sale_notes_section.php
  51. 49 5
      views/sales.php
  52. 1 1
      views/supplier.php
  53. 1 47
      views/ticket.php

+ 274 - 0
controllers/document.php

@@ -0,0 +1,274 @@
+<?php
+
+namespace App;
+
+use App\Enums\DocumentTypes;
+use RuntimeException;
+
+/**
+ * @var string $document_type_string
+ * @var int $document_number
+ * @var string $action
+ */
+
+$action = $action ?? null;
+
+switch($document_type_string) {
+	case "invoices":
+		$document_type = DocumentTypes::INVOICE;
+		break;
+
+	case "delivery-notes":
+		$document_type = DocumentTypes::DELIVERY_NOTE;
+		break;
+
+	default:
+		throw new RuntimeException(__("Invalid document type."));
+}
+
+$request = Request::fromRequest();
+
+$controller = new class($document_type, $document_number) {
+
+	private ?User $user;
+	private int $documentType;
+	private int $documentNumber;
+	private Request $request;
+
+	public function __construct(int $document_type, int $document_number) {
+		$core = Core::getInstance();
+		$this->user = $core->getUser();
+		$this->documentType = $document_type;
+		$this->documentNumber = $document_number;
+		$this->request = Request::fromRequest();
+	}
+
+	private function requireDocument(): Document {
+		$document = Document::queryOne([
+			"type" => $this->documentType,
+			"number" => $this->documentNumber
+		]);
+		if(!$document) {
+			throw new RuntimeException(__("Document not found."));
+		}
+		return $document;
+	}
+
+	private function requireItem(int $item_id): DocumentItem {
+		$document = $this->requireDocument();
+		$items = $document->getItems(["id" => $item_id]);
+		if(!$items) {
+			throw new RuntimeException(__("Item not found."));
+		}
+
+		return $items[0];
+	}
+
+	public function view(): void {
+		$document = $this->requireDocument();
+
+
+		$core = Core::getInstance();
+		$this->user->requireAdmin();
+
+		if($document->isInvoice() || $document->isDeliveryNote()) {
+			/** @var Sale $sale */
+			$sale = $document->getSale();
+			$core->addBreadcrumb("/sales", __("Sales"));
+			$core->addBreadcrumb($sale->getUrl(), __("Sale %d", $sale->getNumber()));
+
+			if($document->isInvoice()) {
+				$core->addBreadcrumb($document->getUrl(), __("Invoice %d", $document->number));
+			}
+			if($document->isDeliveryNote()) {
+				$core->addBreadcrumb($document->getUrl(), __("Delivery Note %d", $document->number));
+			}
+		}
+
+
+		$core->addScript("/js/document-item-modal.js");
+		$core->addScript("/js/document-page.js");
+
+		View::include("header");
+		View::include("document", compact("document"));
+		View::include("modals/document_item");
+		View::include("footer");
+	}
+
+	public function update(): void {
+		$document = $this->requireDocument();
+
+		if($document->isInvoice()) {
+			$document->invoice_status = $this->request->int("invoice_status");
+			$document->terms = $this->request->string("terms");
+			$document->currency = $this->request->string("currency");
+			$document->tax_rate = $this->request->decimal("tax_rate", 2);
+			$document->dts_finalised = $this->request->dateTime("dts_finalised", "Y-m-d\TH:i", $this->user->getTimezone());
+			$document->dts_paid = $this->request->dateTime("dts_paid", "Y-m-d\TH:i", $this->user->getTimezone());
+		}
+
+		$document->date = $this->request->string("date");
+		$document->billing_address = $this->request->string("billing_address");
+		$document->delivery_address = $this->request->string("delivery_address");
+		$document->po_number = $this->request->string("po_number");
+		$document->notes = $this->request->string("notes");
+
+		$document->delivery_company = $this->request->string("delivery_company");
+		$document->tracking_number = $this->request->string("tracking_number");
+
+		$document->commit();
+
+		if($document->isInvoice()) {
+			Session::addAlert("success", __("Invoice updated successfully."));
+		}
+		if($document->isDeliveryNote()) {
+			Session::addAlert("success", __("Delivery note updated successfully."));
+		}
+
+		Http::redirect($document->getUrl());
+
+	}
+
+	public function submitItem(): void {
+		$document = $this->requireDocument();
+
+		$document_item_id = $this->request->int("document_item_id");
+		if($document_item_id) {
+			$item = $this->requireItem($document_item_id);
+			$item->dts_updated = Database::dts();
+		}
+		else {
+			$item = new DocumentItem();
+			$item->document_id = $document->id;
+			$item->dts_created = Database::dts();
+		}
+
+		$item->description = $this->request->string("description");
+		$item->serial_number = $this->request->string("serial_number");
+		$item->quantity = $this->request->int("quantity");
+		$item->unit_price = $this->request->decimal("unit_price", 2);
+		$item->commit();
+
+		JSON::success([
+			"html" => View::getHtml("document_items_section", ["document" => $document])
+		]);
+	}
+
+	public function deleteItem(): void {
+		$document = $this->requireDocument();
+		$document_item_id = $this->request->int("document_item_id");
+		$item = $this->requireItem($document_item_id);
+		$item->softDelete();
+
+		JSON::success([
+			"html" => View::getHtml("document_items_section", ["document" => $document])
+		]);
+	}
+
+	public function deleteItems(): void {
+		$document_item_ids = $this->request->int("document_item_ids");
+		if(!$document_item_ids || !is_array($document_item_ids)) {
+			throw new RuntimeException(__("No items selected."));
+		}
+
+		$items = $this->validateItemIds($document_item_ids);
+		foreach($items as $item) {
+			$item->softDelete();
+		}
+
+		$document = $this->requireDocument();
+
+		Session::addAlert("success", __("Items deleted successfully."));
+		Http::redirect($document->getUrl());
+	}
+
+	public function createDeliveryNote(): void {
+		$document_item_ids = $this->request->int("document_item_ids");
+		if(!$document_item_ids || !is_array($document_item_ids)) {
+			throw new RuntimeException(__("No items selected."));
+		}
+
+		$invoice = $this->requireDocument();
+
+		$items = $this->validateItemIds($document_item_ids);
+
+		$delivery_note = new Document();
+		$delivery_note->user_id = $this->user->id;
+		$delivery_note->sale_id = $invoice->sale_id;
+		$delivery_note->location_id = $invoice->location_id;
+		$delivery_note->related_document_id = $invoice->id;
+		$delivery_note->type = DocumentTypes::DELIVERY_NOTE;
+		$delivery_note->billing_address = $invoice->billing_address;
+		$delivery_note->delivery_address = $invoice->delivery_address;
+		$delivery_note->number = Document::getNextNumber(DocumentTypes::DELIVERY_NOTE);
+		$delivery_note->date = date("Y-m-d");
+		$delivery_note->delivery_company = $invoice->delivery_company;
+		$delivery_note->tracking_number = $invoice->tracking_number;
+		$delivery_note->dts_created = Database::dts();
+		$delivery_note->commit();
+
+		foreach($items as $item) {
+			$delivery_note_item = new DocumentItem();
+			$delivery_note_item->document_id = $delivery_note->id;
+			$delivery_note_item->description = $item->description;
+			$delivery_note_item->serial_number = $item->serial_number;
+			$delivery_note_item->quantity = $item->quantity;
+			$delivery_note_item->unit_price = $item->unit_price;
+			$delivery_note_item->dts_created = Database::dts();
+			$delivery_note_item->commit();
+		}
+
+		Session::addAlert("success", __("Delivery note created successfully."));
+		Http::redirect($delivery_note->getUrl());
+	}
+
+	/**
+	 * @param int[] $document_item_ids
+	 * @return DocumentItem[]
+	 */
+	private function validateItemIds(array $document_item_ids): array {
+		$items = [];
+		foreach($document_item_ids as $document_item_id) {
+			$items[] = $this->requireItem($document_item_id);
+		}
+		return $items;
+	}
+
+};
+
+switch($action) {
+	case "submit":
+		$controller->update();
+		break;
+
+	case "submit-item":
+		$controller->submitItem();
+		break;
+
+	case "delete-item":
+		$controller->deleteItem();
+		break;
+
+	case "items-batch-action":
+
+		$batch_action = $request->string("batch_action");
+		switch($batch_action) {
+
+			case "delete":
+				$controller->deleteItems();
+				break;
+
+			case "create-delivery-note":
+				$controller->createDeliveryNote();
+				break;
+
+			default:
+				throw new RuntimeException(__("Invalid batch action."));
+		}
+
+		break;
+
+	default:
+		$controller->view();
+}
+

+ 333 - 0
controllers/sale.php

@@ -0,0 +1,333 @@
+<?php
+
+namespace App;
+
+use App\Enums\DocumentTypes;
+use App\Enums\InvoiceStatuses;
+use App\Enums\SaleStatuses;
+use RuntimeException;
+
+/**
+ * @var int $number
+ * @var string $action
+ */
+
+$number = $number ?? null;
+$action = $action ?? null;
+
+$request = Request::fromRequest();
+
+$controller = new class($number) {
+
+	private ?int $number;
+
+	private Request $request;
+
+	private User $user;
+
+	public function __construct(?int $number) {
+		$core = Core::getInstance();
+		$this->user = $core->getUser();
+
+		$this->number = $number;
+		$this->request = Request::fromRequest();
+	}
+
+	private function getSale(): ?Sale {
+		if(!$this->number) {
+			return null;
+		}
+
+		return Sale::getByNumber($this->number);
+	}
+
+	private function requireSale(): Sale {
+		$sale = $this->getSale();
+		if(!$sale) {
+			throw new RuntimeException(__("Sale not found."));
+		}
+		return $sale;
+	}
+
+	private function requireNote(?int $note_id): SaleNote {
+		$notes = $this->requireSale()->getNotes(["id" => $note_id]);
+		if(!$notes) {
+			throw new RuntimeException(__("Note not found."));
+		}
+		return $notes[0];
+	}
+
+	private function requireItem(?int $item_id): SaleItem {
+		$items = $this->requireSale()->getItems(["id" => $item_id]);
+		if(!$items) {
+			throw new RuntimeException(__("Item not found."));
+		}
+		return $items[0];
+	}
+
+	public function view(): void {
+		$sale = $this->requireSale();
+
+		$core = Core::getInstance();
+		$this->user->requireAdmin();
+
+		$core->addBreadcrumb("/sales", __("Sales"));
+		$core->addBreadcrumb($sale->getUrl(), __("Sale %d", $sale->getNumber()));
+
+		$core->addScript("/js/sale-item-modal.js");
+		$core->addScript("/js/sale-note-modal.js");
+		$core->addScript("/js/sale-page.js");
+
+		View::include("header");
+		View::include("sale", compact("sale"));
+		View::include("modals/sale_item");
+		View::include("modals/sale_note");
+		View::include("footer");
+	}
+
+	public function createOrUpdate(): void {
+
+		$sale = $this->getSale();
+		if(!$sale) {
+
+			$company_id = $this->request->int("company_id");
+			$company = Company::get($company_id);
+			if(!$company) {
+				throw new RuntimeException(__("Company not found."));
+			}
+
+			$location_id = $this->request->int("location_id");
+			$location = Location::get($location_id);
+			if(!$location) {
+				throw new RuntimeException(__("Location not found."));
+			}
+
+			$sale = new Sale();
+			$sale->company_id = $company->id;
+			$sale->location_id = $location->id;
+			$sale->user_id = $this->user->id;
+			$sale->status = SaleStatuses::NEW;
+			$sale->currency = "GBP";
+			$sale->dts_created = Database::dts();
+
+			$success_message = __("Sale created successfully.");
+		}
+		else {
+			$sale->status = $this->request->int("status");
+			$sale->currency = $this->request->string("currency");
+			$sale->tax_rate = $this->request->decimal("tax_rate", 2);
+
+			if(!SaleStatuses::validate($sale->status)) {
+				throw new RuntimeException(__("Status is invalid."));
+			}
+
+			$sale->dts_updated = Database::dts();
+
+			$success_message = __("Sale updated successfully.");
+		}
+
+		$sale->commit();
+
+		Session::addAlert("success", $success_message);
+
+		Http::redirect($sale->getUrl());
+	}
+
+	public function delete(): void {
+		$sale = $this->requireSale();
+		$sale->softDelete();
+		JSON::success();
+	}
+
+	public function submitNote(): void {
+		$sale = $this->requireSale();
+
+		$note_id = $this->request->int("sale_note_id");
+		if($note_id) {
+			$note = $this->requireNote($note_id);
+		}
+		else {
+			$note = new SaleNote();
+			$note->sale_id = $sale->id;
+			$note->user_id = $this->user->id;
+			$note->dts_created = Database::dts();
+		}
+
+		$note->content = $this->request->string("content");
+		if(empty($note->content)) {
+			throw new RuntimeException(__("Content cannot be empty."));
+		}
+
+		$note->commit();
+
+		JSON::success([
+			"html" => View::getHtml("sale_notes_section", compact("sale"))
+		]);
+	}
+
+	public function deleteNote(): void {
+		$note_id = $this->request->int("note_id");
+		$note = $this->requireNote($note_id);
+		$note->softDelete();
+		JSON::success();
+	}
+
+	public function submitItem(): void {
+		$sale = $this->requireSale();
+
+		$sale_item_id = $this->request->int("sale_item_id");
+		if($sale_item_id) {
+			$item = $this->requireItem($sale_item_id);
+		}
+		else {
+			$item = new SaleItem();
+			$item->sale_id = $sale->id;
+		}
+
+		$product_id = $this->request->int("product_id");
+		$product = Product::get($product_id);
+		if(!$product) {
+			throw new RuntimeException(__("Product not found."));
+		}
+
+		$item->product_id = $product->id;
+		$item->quantity = $this->request->int("quantity");
+		$item->unit_price = $this->request->decimal("unit_price", 2);
+		$item->commit();
+
+		JSON::success([
+			"html" => View::getHtml("sale_items_section", compact("sale"))
+		]);
+	}
+
+	public function deleteItem(): void {
+		$item_id = $this->request->int("sale_item_id");
+		$item = $this->requireItem($item_id);
+		$sale = $item->getSale();
+
+		$item->delete();
+
+		JSON::success([
+			"html" => View::getHtml("sale_items_section", compact("sale"))
+		]);
+	}
+
+	/**
+	 * @param int[] $item_ids
+	 * @return SaleItem[]
+	 */
+	private function validateItemIds(array $item_ids): array {
+		$items = [];
+		foreach($item_ids as $item_id) {
+			$items[] = $this->requireItem($item_id);
+		}
+		return $items;
+	}
+
+	public function deleteItems(): void {
+		$sale = $this->requireSale();
+		$item_ids = $this->request->int("sale_item_ids");
+		if(empty($item_ids) || !is_array($item_ids)) {
+			throw new RuntimeException(__("No items selected."));
+		}
+
+		$items = $this->validateItemIds($item_ids);
+
+		foreach($items as $item) {
+			$item->delete();
+		}
+
+		Session::addAlert("success", __("Items deleted successfully."));
+		Http::redirect($sale->getUrl());
+	}
+
+	public function createInvoiceFromItems(): void {
+		$sale = $this->requireSale();
+		$location = $sale->getLocation();
+		$address = $location->getAddress();
+
+		$item_ids = $this->request->int("sale_item_ids");
+		if(empty($item_ids) || !is_array($item_ids)) {
+			throw new RuntimeException(__("No items selected."));
+		}
+
+		$sale_items = $this->validateItemIds($item_ids);
+
+		$address_string = $location->name . "\n" . $address;
+
+		// OK
+		$invoice = new Document();
+		$invoice->user_id = $this->user->id;
+		$invoice->sale_id = $sale->id;
+		$invoice->location_id = $location->id;
+		$invoice->type = DocumentTypes::INVOICE;
+		$invoice->invoice_status = InvoiceStatuses::DRAFT;
+		$invoice->currency = $sale->currency;
+		$invoice->tax_rate = $sale->tax_rate;
+		$invoice->billing_address = $address_string;
+		$invoice->delivery_address = $address_string;
+		$invoice->number = Document::getNextNumber(DocumentTypes::INVOICE);
+		$invoice->date = date("Y-m-d");
+		$invoice->dts_created = Database::dts();
+		$invoice->commit();
+
+		foreach($sale_items as $sale_item) {
+			$product = $sale_item->getProduct();
+			$supplier = $product->getSupplier();
+
+			$invoice_item = new DocumentItem();
+			$invoice_item->document_id = $invoice->id;
+			$invoice_item->description = $product->name . " ($supplier->name)";
+			$invoice_item->quantity = $sale_item->quantity;
+			$invoice_item->unit_price = $sale_item->unit_price;
+			$invoice_item->dts_created = Database::dts();
+			$invoice_item->commit();
+		}
+
+		Session::addAlert("success", __("Invoice created successfully."));
+		Http::redirect($sale->getUrl() . "/invoices/" . $invoice->number);
+	}
+
+};
+
+switch($action) {
+	case "submit-note":
+		$controller->submitNote();
+		break;
+
+	case "delete-note":
+		$controller->deleteNote();
+		break;
+
+	case "submit-item":
+		$controller->submitItem();
+		break;
+
+	case "delete-item":
+		$controller->deleteItem();
+		break;
+
+	case "submit":
+		$controller->createOrUpdate();
+		break;
+
+	case "items-batch-action":
+		$batch_action = $request->string("batch_action");
+		switch($batch_action) {
+			case "create-invoice":
+				$controller->createInvoiceFromItems();
+				break;
+
+			case "delete":
+				$controller->deleteItems();
+				break;
+
+			default:
+				throw new RuntimeException(__("Invalid batch action."));
+		}
+		break;
+
+	default:
+		$controller->view();
+		break;
+}

+ 4 - 1
controllers/sales.php

@@ -9,8 +9,11 @@ $user->requireAdmin();
 
 $core->addBreadcrumb("/sales", __("Sales"));
 
-$sales = [];
+$nvp = ["dts_deleted" => null];
+
+$sales = Sale::query($nvp, ["sort" => "dts_updated", "order" => "desc"]);
 
 View::include("header");
 View::include("sales", compact("sales"));
+View::include("modals/new_sale");
 View::include("footer");

+ 24 - 0
db/migrations/20221219192033_add_sale_table.php

@@ -0,0 +1,24 @@
+<?php
+declare(strict_types=1);
+
+use Phinx\Db\Adapter\MysqlAdapter;
+use Phinx\Migration\AbstractMigration;
+
+final class AddSaleTable extends AbstractMigration {
+	public function change(): void {
+		$this->table("sale", ["signed" => false])
+			->addColumn("company_id", "integer", ["signed" => false])
+			->addColumn("location_id", "integer", ["signed" => false])
+			->addColumn("user_id", "integer", ["signed" => false])
+			->addColumn("status", "integer", ["signed" => false, "limit" => MysqlAdapter::INT_TINY])
+			->addColumn("currency", "string", ["limit" => 3])
+			->addColumn("tax_rate", "decimal", ["precision" => 5, "scale" => 2, "default" => "20.00"])
+			->addColumn("dts_created", "datetime")
+			->addColumn("dts_updated", "datetime", ["null" => true])
+			->addColumn("dts_deleted", "datetime", ["null" => true])
+			->addForeignKey("company_id", "company", "id", ["update" => "CASCADE", "delete" => "RESTRICT"])
+			->addForeignKey("location_id", "location", "id", ["update" => "CASCADE", "delete" => "RESTRICT"])
+			->addForeignKey("user_id", "user", "id", ["update" => "CASCADE", "delete" => "RESTRICT"])
+			->create();
+	}
+}

+ 19 - 0
db/migrations/20221219192253_add_sale_note_table.php

@@ -0,0 +1,19 @@
+<?php
+declare(strict_types=1);
+
+use Phinx\Migration\AbstractMigration;
+
+final class AddSaleNoteTable extends AbstractMigration {
+	public function change(): void {
+		$this->table("sale_note", ["signed" => false])
+			->addColumn("sale_id", "integer", ["signed" => false])
+			->addColumn("user_id", "integer", ["signed" => false])
+			->addColumn("content", "text")
+			->addColumn("dts_created", "datetime")
+			->addColumn("dts_updated", "datetime", ["null" => true])
+			->addColumn("dts_deleted", "datetime", ["null" => true])
+			->addForeignKey("sale_id", "sale", "id", ["update" => "CASCADE", "delete" => "CASCADE"])
+			->addForeignKey("user_id", "user", "id", ["update" => "CASCADE", "delete" => "RESTRICT"])
+			->create();
+	}
+}

+ 17 - 0
db/migrations/20221219201955_add_sale_item_table.php

@@ -0,0 +1,17 @@
+<?php
+declare(strict_types=1);
+
+use Phinx\Migration\AbstractMigration;
+
+final class AddSaleItemTable extends AbstractMigration {
+	public function change(): void {
+		$this->table("sale_item", ["signed" => false])
+			->addColumn("sale_id", "integer", ["signed" => false])
+			->addColumn("product_id", "integer", ["signed" => false])
+			->addColumn("quantity", "integer", ["signed" => false])
+			->addColumn("unit_price", "decimal", ["precision" => 11, "scale" => 2])
+			->addForeignKey("sale_id", "sale", "id", ["update" => "CASCADE", "delete" => "CASCADE"])
+			->addForeignKey("product_id", "product", "id", ["update" => "CASCADE", "delete" => "RESTRICT"])
+			->create();
+	}
+}

+ 41 - 0
db/migrations/20221220212227_add_document_table.php

@@ -0,0 +1,41 @@
+<?php
+declare(strict_types=1);
+
+use Phinx\Db\Adapter\MysqlAdapter;
+use Phinx\Migration\AbstractMigration;
+
+final class AddDocumentTable extends AbstractMigration {
+	public function change(): void {
+		$this->table("document", ["signed" => false])
+			->addColumn("user_id", "integer", ["signed" => false])
+			->addColumn("sale_id", "integer", ["signed" => false, "null" => true])
+			->addColumn("supplier_id", "integer", ["signed" => false, "null" => true])
+			->addColumn("location_id", "integer", ["signed" => false, "null" => true])
+			->addColumn("related_document_id", "integer", ["signed" => false, "null" => true])
+			->addColumn("type", "integer", ["signed" => false, "limit" => MysqlAdapter::INT_TINY])
+			->addColumn("invoice_status", "integer", ["signed" => false, "limit" => MysqlAdapter::INT_TINY, "null" => true])
+			->addColumn("currency", "string", ["limit" => 3, "null" => true])
+			->addColumn("tax_rate", "decimal", ["precision" => 5, "scale" => 2, "null" => true])
+			->addColumn("billing_address", "string", ["null" => true])
+			->addColumn("delivery_address", "string", ["null" => true])
+			->addColumn("number", "integer", ["signed" => false, "null" => true])
+			->addColumn("date", "date", ["null" => true])
+			->addColumn("po_number", "string", ["null" => true])
+			->addColumn("terms", "string", ["null" => true])
+			->addColumn("delivery_company", "string", ["null" => true])
+			->addColumn("tracking_number", "string", ["null" => true])
+			->addColumn("delivery_cost", "string", ["null" => true])
+			->addColumn("notes", "text", ["null" => true])
+			->addColumn("dts_finalised", "datetime", ["null" => true])
+			->addColumn("dts_paid", "datetime", ["null" => true])
+			->addColumn("dts_created", "datetime")
+			->addColumn("dts_updated", "datetime", ["null" => true])
+			->addColumn("dts_deleted", "datetime", ["null" => true])
+			->addForeignKey("user_id", "user", "id", ["update" => "CASCADE", "delete" => "RESTRICT"])
+			->addForeignKey("sale_id", "sale", "id", ["update" => "CASCADE", "delete" => "CASCADE"])
+			->addForeignKey("supplier_id", "supplier", "id", ["update" => "CASCADE", "delete" => "RESTRICT"])
+			->addForeignKey("location_id", "location", "id", ["update" => "CASCADE", "delete" => "RESTRICT"])
+			->addForeignKey("related_document_id", "document", "id", ["update" => "CASCADE", "delete" => "CASCADE"])
+			->create();
+	}
+}

+ 20 - 0
db/migrations/20221220213008_add_document_item_table.php

@@ -0,0 +1,20 @@
+<?php
+declare(strict_types=1);
+
+use Phinx\Migration\AbstractMigration;
+
+final class AddDocumentItemTable extends AbstractMigration {
+	public function change(): void {
+		$this->table("document_item", ["signed" => false])
+			->addColumn("document_id", "integer", ["signed" => false])
+			->addColumn("description", "string")
+			->addColumn("serial_number", "string", ["null" => true])
+			->addColumn("quantity", "integer", ["signed" => false])
+			->addColumn("unit_price", "decimal", ["precision" => 11, "scale" => 2])
+			->addColumn("dts_created", "datetime")
+			->addColumn("dts_updated", "datetime", ["null" => true])
+			->addColumn("dts_deleted", "datetime", ["null" => true])
+			->addForeignKey("document_id", "document", "id", ["update" => "CASCADE", "delete" => "CASCADE"])
+			->create();
+	}
+}

+ 31 - 0
engine/Address.php

@@ -28,14 +28,38 @@ class Address extends Model {
 
 	public static function getCountryOptions(): array {
 		return [
+			"AU" => __("Australia"),
+			"CA" => __("Canada"),
+			"DK" => __("Denmark"),
 			"FR" => __("France"),
 			"DE" => __("Germany"),
 			"JP" => __("Japan"),
+			"NZ" => __("New Zealand"),
+			"NO" => __("Norway"),
+			"PL" => __("Poland"),
 			"ES" => __("Spain"),
+			"SE" => __("Sweden"),
+			"CH" => __("Switzerland"),
 			"GB" => __("United Kingdom"),
+			"US" => __("United States"),
 		];
 	}
 
+	// Magic methods
+	public function __toString(): string {
+		$county_parts = array_filter([$this->county, $this->state, $this->postal_code]);
+
+		$lines = array_filter([
+			$this->address_1,
+			$this->address_2,
+			$this->city,
+			implode(", ", $county_parts),
+			$this->getDisplayCountry()
+		]);
+
+		return implode("\n", $lines);
+	}
+
 	// Object methods
 
 	public function hasGeolocation(): bool {
@@ -57,4 +81,11 @@ class Address extends Model {
 		}
 	}
 
+	private function getDisplayCountry(): string {
+		if($this->country) {
+			return self::getCountryOptions()[$this->country] ?? "";
+		}
+		return "";
+	}
+
 }

+ 6 - 1
engine/Customer.php

@@ -61,7 +61,12 @@ class Customer extends Model {
 	 * @return Location[]
 	 */
 	public function getLocations(): array {
-		return Location::query(["customer_id" => $this->id, "dts_deleted" => null]);
+		return Location::query([
+			"customer_id" => $this->id,
+			"dts_deleted" => null
+		], [
+			"sort" => "name"
+		]);
 	}
 
 }

+ 170 - 0
engine/Document.php

@@ -0,0 +1,170 @@
+<?php
+
+namespace App;
+
+use App\Enums\DocumentTypes;
+use App\Enums\InvoiceStatuses;
+use App\Traits\DateTimeTrait;
+use App\Traits\SoftDeleteTrait;
+use Exception;
+use NumberFormatter;
+use RuntimeException;
+
+/**
+ * @property int $id
+ * @property int $user_id User who created this document
+ * @property int $sale_id Sale that this document relates to
+ * @property int $supplier_id Used for goods-in documents
+ * @property int $location_id
+ * @property int $related_document_id Used to link a delivery note to an invoice
+ * @property int $type
+ * @property int $invoice_status
+ * @property string $currency
+ * @property string $tax_rate
+ * @property string $billing_address
+ * @property string $delivery_address
+ * @property int $number
+ * @property string $date
+ * @property string $po_number Used for invoices
+ * @property string $terms Used for invoices
+ * @property string $delivery_company
+ * @property string $tracking_number
+ * @property string $delivery_cost
+ * @property string $notes
+ * @property string $dts_finalised
+ * @property string $dts_paid
+ */
+class Document extends Model {
+
+	protected static $table = "document";
+	protected static $idField = "id";
+	protected static $fillableFields = [
+		"user_id", "sale_id", "supplier_id", "location_id", "related_document_id",
+		"type",
+		"invoice_status",
+		"currency", "tax_rate",
+		"billing_address", "delivery_address",
+		"number", "date", "po_number", "terms",
+		"delivery_company", "tracking_number", "delivery_cost",
+		"notes",
+		"dts_finalised", "dts_paid",
+		"dts_created", "dts_updated", "dts_deleted"
+	];
+
+	use DateTimeTrait;
+	use SoftDeleteTrait;
+
+	// Static methods
+
+	/**
+	 * @param int $document_type
+	 * @return int
+	 * @throws Exception
+	 */
+	public static function getNextNumber(int $document_type): int {
+		$document = self::queryOne(["type" => $document_type], ["sort" => "id", "order" => "desc"]);
+		if($document) {
+			return $document->number + 1;
+		}
+
+		return 1000;
+	}
+
+	// Object methods
+
+	/**
+	 * @return Sale|null
+	 * @throws Exception
+	 */
+	public function getSale(): ?Sale {
+		return Sale::get($this->sale_id);
+	}
+
+	/**
+	 * @return string
+	 * @throws Exception
+	 */
+	public function getUrl(): string {
+		if($this->isInvoice()) {
+			/** @var Sale $sale */
+			$sale = $this->getSale();
+			return sprintf("%s/invoices/%s", $sale->getUrl(), $this->number);
+		}
+
+		if($this->isDeliveryNote()) {
+			$sale = $this->getSale();
+			return sprintf("%s/delivery-notes/%s", $sale->getUrl(), $this->number);
+		}
+
+		throw new RuntimeException(__("Unimplemented getUrl for document type: $this->type"));
+	}
+
+	public function isInvoice(): bool {
+		return (int) $this->type === DocumentTypes::INVOICE;
+	}
+
+	public function isDeliveryNote(): bool {
+		return (int) $this->type === DocumentTypes::DELIVERY_NOTE;
+	}
+
+	public function isGoodsIn(): bool {
+		return (int) $this->type === DocumentTypes::GOODS_IN;
+	}
+
+	public function getDisplayInvoiceStatus(): string {
+		return InvoiceStatuses::enumToText($this->invoice_status);
+	}
+
+	public function getDisplayTotal(): string {
+		$formatter = new NumberFormatter("en_GB", NumberFormatter::CURRENCY);
+
+		$subtotal = "0.00";
+
+		foreach($this->getItems() as $item) {
+			$subtotal = bcadd($item->getAmount(), $subtotal, 2);
+		}
+
+		$tax = bcmul($subtotal, $this->tax_rate / 100, 2);
+		$total = bcadd($subtotal, $tax, 2);
+
+		return $formatter->formatCurrency($total, $this->currency);
+	}
+
+	/**
+	 * @return DocumentItem[]
+	 */
+	public function getItems(array $nvp = []): array {
+		$nvp = array_merge($nvp, [
+			"document_id" => $this->id,
+			"dts_deleted" => null
+		]);
+		return DocumentItem::query($nvp);
+	}
+
+	public function getTitle(): string {
+		if($this->isInvoice()) {
+			return __("Invoice %d", $this->number);
+		}
+		if($this->isDeliveryNote()) {
+			return __("Delivery Note %d", $this->number);
+		}
+		return __("Document %d", $this->number);
+	}
+
+	/**
+	 * @return Document|null
+	 * @throws Exception
+	 */
+	public function getRelatedDocument(): ?Document {
+		return self::get($this->related_document_id);
+	}
+
+	/**
+	 * @return User
+	 * @throws Exception
+	 */
+	public function getUser(): User {
+		return User::get($this->user_id);
+	}
+
+}

+ 47 - 0
engine/DocumentItem.php

@@ -0,0 +1,47 @@
+<?php
+
+namespace App;
+
+use App\Traits\DateTimeTrait;
+use App\Traits\SoftDeleteTrait;
+use JsonSerializable;
+
+/**
+ * @property int $id
+ * @property int $document_id
+ * @property string $description
+ * @property string $serial_number
+ * @property int $quantity
+ * @property string $unit_price
+ */
+class DocumentItem extends Model implements JsonSerializable {
+
+	protected static $table = "document_item";
+	protected static $idField = "id";
+	protected static $fillableFields = [
+		"document_id",
+		"description", "serial_number",
+		"quantity", "unit_price",
+		"dts_created", "dts_updated", "dts_deleted"
+	];
+
+	use DateTimeTrait;
+	use SoftDeleteTrait;
+
+	// Object methods
+
+	public function getAmount(): string {
+		return bcmul($this->unit_price, $this->quantity, 2);
+	}
+
+	public function jsonSerialize(): array {
+		return [
+			"id" => (int) $this->id,
+			"documentId" => (int) $this->document_id,
+			"description" => $this->description,
+			"serialNumber" => $this->serial_number,
+			"quantity" => (int) $this->quantity,
+			"unitPrice" => $this->unit_price,
+		];
+	}
+}

+ 17 - 0
engine/Enums/Currencies.php

@@ -0,0 +1,17 @@
+<?php
+
+namespace App\Enums;
+
+class Currencies extends AbstractEnum {
+
+	public const GBP = "GBP";
+	public const EUR = "EUR";
+
+	public static function options(): array {
+		return [
+			self::GBP => __("British Pound (GBP)"),
+			self::EUR => __("Euro (EUR)")
+		];
+	}
+
+}

+ 21 - 0
engine/Enums/DocumentTypes.php

@@ -0,0 +1,21 @@
+<?php
+
+namespace App\Enums;
+
+class DocumentTypes extends AbstractEnum {
+
+	public const INVOICE = 0;
+	public const DELIVERY_NOTE = 1;
+	public const GOODS_IN = 2;
+	public const ADVANCE_REPLACEMENT_UNIT = 3;
+	public const CREDIT_NOTE = 4;
+	public static function options(): array {
+		return [
+			self::INVOICE => __("Invoice"),
+			self::DELIVERY_NOTE => __("Delivery Note"),
+			self::GOODS_IN => __("Goods In"),
+			self::ADVANCE_REPLACEMENT_UNIT => __("Advance Replacement Unit (ARU)"),
+			self::CREDIT_NOTE => __("Credit Note"),
+		];
+	}
+}

+ 22 - 0
engine/Enums/InvoiceStatuses.php

@@ -0,0 +1,22 @@
+<?php
+
+namespace App\Enums;
+
+class InvoiceStatuses extends AbstractEnum {
+
+	public const DRAFT = 0;
+	public const OPEN = 1;
+	public const PAID = 2;
+	public const VOID = 3;
+	public const UNCOLLECTIBLE = 4;
+
+	public static function options(): array {
+		return [
+			self::DRAFT => __("Draft"),
+			self::OPEN => __("Open"),
+			self::PAID => __("Paid"),
+			self::VOID => __("Void"),
+			self::UNCOLLECTIBLE => __("Uncollectible"),
+		];
+	}
+}

+ 23 - 0
engine/Enums/SaleStatuses.php

@@ -0,0 +1,23 @@
+<?php
+
+namespace App\Enums;
+
+class SaleStatuses extends AbstractEnum {
+
+	public const NEW = 0;
+	public const VERIFIED = 1;
+	public const CONFIRMED = 2;
+	public const SHIPPING = 3;
+	public const COMPLETED = 4;
+
+	public static function options(): array {
+		return [
+			self::NEW => __("New"),
+			self::VERIFIED => __("Verified"),
+			self::CONFIRMED => __("Confirmed"),
+			self::SHIPPING => __("Shipping"),
+			self::COMPLETED => __("Completed"),
+		];
+	}
+
+}

+ 13 - 0
engine/Helpers/HtmlHelper.php

@@ -15,4 +15,17 @@ class HtmlHelper {
 		}
 	}
 
+	public static function renderInfoAlert(string $message): void {
+		?>
+		<div class="alert alert-info">
+			<i class="fa fa-fw fa-info-circle"></i>
+			<?=htmlspecialchars($message)?>
+		</div>
+		<?php
+	}
+
+	public static function readonly($value): string {
+		return $value ? "readonly" : "";
+	}
+
 }

+ 15 - 0
engine/Interfaces/AttachmentInterface.php

@@ -0,0 +1,15 @@
+<?php
+
+namespace App\Interfaces;
+
+use Carbon\CarbonImmutable;
+
+interface AttachmentInterface {
+
+	public function getUser(): User;
+	public function isInternal(): bool;
+	public function getDateTimeCreated(): CarbonImmutable;
+	public function getAttachments(): array;
+	public function getHtml(): string;
+
+}

+ 40 - 0
engine/Interfaces/CommentInterface.php

@@ -0,0 +1,40 @@
+<?php
+
+namespace App\Interfaces;
+
+use App\User;
+use Carbon\CarbonImmutable;
+
+interface CommentInterface {
+
+	/**
+	 * @return User
+	 */
+	public function getUser(): User;
+
+	/**
+	 * @return bool
+	 */
+	public function isInternal(): bool;
+
+	/**
+	 * @return CarbonImmutable
+	 */
+	public function getDateTimeCreated(): CarbonImmutable;
+
+	/**
+	 * @return AttachmentInterface[]
+	 */
+	public function getAttachments(): array;
+
+	/**
+	 * @return string
+	 */
+	public function getHtml(): string;
+
+	/**
+	 * @return void
+	 */
+	public function renderEditIcon(): void;
+
+}

+ 9 - 0
engine/Location.php

@@ -53,4 +53,13 @@ class Location extends Model {
 		return sprintf("/locations/%s", $this->getSlug());
 	}
 
+	/**
+	 * @return string
+	 * @throws Exception
+	 */
+	public function getDisplayName(): string {
+		$customer = $this->getCustomer();
+		return sprintf("%s - %s", $customer->name, $this->name);
+	}
+
 }

+ 16 - 0
engine/Request.php

@@ -2,6 +2,7 @@
 
 namespace App;
 
+use Carbon\CarbonImmutable;
 use RuntimeException;
 
 class Request {
@@ -184,5 +185,20 @@ class Request {
 		return ($value !== false) ? $value : null;
 	}
 
+	/**
+	 * @param string $name
+	 * @param string $format
+	 * @param string $timezone
+	 * @return string|null UTC date/time string or null on failure
+	 */
+	public function dateTime(string $name, string $format, string $timezone = "Europe/London"): ?string {
+		$value = $this->data[$name] ?? null;
+		if($value) {
+			$dt = CarbonImmutable::createFromFormat($format, $value, $timezone);
+			return $dt ? (string) $dt->utc() : null;
+		}
+		return null;
+	}
+
 
 }

+ 129 - 0
engine/Sale.php

@@ -0,0 +1,129 @@
+<?php
+
+namespace App;
+
+use App\Enums\DocumentTypes;
+use App\Enums\SaleStatuses;
+use App\Traits\DateTimeTrait;
+use App\Traits\SoftDeleteTrait;
+
+/**
+ * @property int $id
+ * @property int $company_id
+ * @property int $location_id
+ * @property int $user_id
+ * @property int $status
+ * @property string $currency
+ * @property string $tax_rate
+ */
+class Sale extends Model {
+
+	protected static $table = "sale";
+	protected static $idField = "id";
+	protected static $fillableFields = [
+		"company_id", "location_id", "user_id",
+		"status", "currency", "tax_rate",
+		"dts_created", "dts_updated", "dts_deleted"
+	];
+
+	use DateTimeTrait;
+	use SoftDeleteTrait;
+
+	// Static methods
+
+	/**
+	 * @param int $number
+	 * @return Sale|null
+	 * @throws \Exception
+	 */
+	public static function getByNumber(int $number): ?Sale {
+		return self::get($number - 999);
+	}
+
+	// Object methods
+
+	/**
+	 * @return Company
+	 * @throws \Exception
+	 */
+	public function getCompany(): Company {
+		return Company::get($this->company_id);
+	}
+
+	/**
+	 * @return Location
+	 * @throws \Exception
+	 */
+	public function getLocation(): Location {
+		return Location::get($this->location_id);
+	}
+
+	public function getNumber(): int {
+		return $this->id + 999;
+	}
+
+	public function getDisplayStatus(): string {
+		return SaleStatuses::enumToText($this->status);
+	}
+
+	/**
+	 * @param array $nvp
+	 * @return SaleNote[]
+	 */
+	public function getNotes(array $nvp = []): array {
+		$nvp = array_merge($nvp, ["sale_id" => $this->id]);
+		return SaleNote::query($nvp, ["sort" => "id"]);
+	}
+
+	/**
+	 * @param array $nvp
+	 * @return SaleItem[]
+	 */
+	public function getItems(array $nvp = []): array {
+		$nvp = array_merge($nvp, ["sale_id" => $this->id]);
+		return SaleItem::query($nvp, ["sort" => "id"]);
+	}
+
+	public function getUrl(): string {
+		return sprintf("/sales/%d", $this->getNumber());
+	}
+
+	public function getUser(): User {
+		return User::get($this->user_id);
+	}
+
+	public function getDocuments(array $nvp = []): array {
+		$nvp = array_merge($nvp, ["sale_id" => $this->id]);
+
+		return Document::query($nvp, [
+			"sort" => "id",
+			"order" => "desc"
+		]);
+	}
+
+	/**
+	 * @return Document[]
+	 */
+	public function getInvoices(): array {
+		return $this->getDocuments(["type" => DocumentTypes::INVOICE]);
+	}
+
+	public function getTickets(): array {
+		return []; // TODO
+		return Ticket::query([
+			"sale_id" => $this->id
+		], [
+			"sort" => "id",
+			"order" => "desc"
+		]);
+	}
+
+	public function getCurrency(): string {
+		return $this->currency;
+	}
+
+	public function getTitle(): string {
+		return __("Sale %d - %s", $this->getNumber(), $this->getLocation()->getDisplayName());
+	}
+
+}

+ 60 - 0
engine/SaleItem.php

@@ -0,0 +1,60 @@
+<?php
+
+namespace App;
+
+use NumberFormatter;
+
+/**
+ * @property int $id
+ * @property int $sale_id
+ * @property int $product_id
+ * @property int $quantity
+ * @property string $unit_price
+ */
+class SaleItem extends Model implements \JsonSerializable {
+
+	protected static $table = "sale_item";
+	protected static $idField = "id";
+	protected static $fillableFields = [
+		"sale_id", "product_id",
+		"quantity", "unit_price",
+	];
+
+	/**
+	 * @return Sale
+	 * @throws \Exception
+	 */
+	public function getSale(): Sale {
+		return Sale::get($this->sale_id);
+	}
+
+	/**
+	 * @return Product
+	 * @throws \Exception
+	 */
+	public function getProduct(): Product {
+		return Product::get($this->product_id);
+	}
+
+	public function getDisplayPrice(): string {
+		return (new NumberFormatter("en_GB", NumberFormatter::CURRENCY))->formatCurrency($this->unit_price * $this->quantity, $this->getCurrency());
+	}
+
+	private function getCurrency(): string {
+		return $this->getSale()->getCurrency();
+	}
+
+	public function getAmount(): string {
+		return bcmul($this->unit_price, $this->quantity, 2);
+	}
+
+	public function jsonSerialize(): array {
+		return [
+			"id" => (int) $this->id,
+			"saleId" => (int) $this->sale_id,
+			"productId" => (int) $this->product_id,
+			"quantity" => (int) $this->quantity,
+			"unitPrice" => $this->unit_price
+		];
+	}
+}

+ 75 - 0
engine/SaleNote.php

@@ -0,0 +1,75 @@
+<?php
+
+namespace App;
+
+use App\Interfaces\CommentInterface;
+use App\Traits\DateTimeTrait;
+use App\Traits\SoftDeleteTrait;
+use Exception;
+
+/**
+ * @property int $id
+ * @property int $sale_id
+ * @property int $user_id
+ * @property string $content
+ */
+class SaleNote extends Model implements CommentInterface, \JsonSerializable {
+
+	protected static $table = "sale_note";
+	protected static $idField = "id";
+	protected static $fillableFields = [
+		"sale_id", "user_id",
+		"content",
+		"dts_created", "dts_updated", "dts_deleted",
+	];
+
+	use DateTimeTrait;
+	use SoftDeleteTrait;
+
+	/**
+	 * @return User
+	 * @throws Exception
+	 */
+	public function getUser(): User {
+		return User::get($this->user_id);
+	}
+
+	public function isInternal(): bool {
+		return false;
+	}
+
+	public function getAttachments(): array {
+		return [];
+	}
+
+	public function getHtml(): string {
+		return nl2br(htmlspecialchars($this->content));
+	}
+
+	/**
+	 * @return void
+	 * @throws Exception
+	 */
+	public function renderEditIcon(): void {
+		?>
+		<a href="#" data-bs-toggle="modal" data-bs-target="#sale-note-modal" data-sale-number="<?=$this->getSale()->getNumber()?>" data-note="<?=htmlspecialchars(json_encode($this))?>">
+			<i class="fa fa-fw fa-pencil"></i>
+		</a>
+		<?php
+	}
+
+	/**
+	 * @return Sale
+	 * @throws Exception
+	 */
+	private function getSale(): Sale {
+		return Sale::get($this->sale_id);
+	}
+
+	public function jsonSerialize(): array {
+		return [
+			"id" => (int) $this->id,
+			"content" => $this->content
+		];
+	}
+}

+ 19 - 0
engine/Setting.php

@@ -0,0 +1,19 @@
+<?php
+
+namespace App;
+
+/**
+ * @property int $key
+ * @property int $value
+ */
+class Setting extends Model {
+
+	protected static $table = "setting";
+	protected static $idField = "key";
+	protected static $fillableFields = ["key", "value"];
+
+	public function getValue(): ?string {
+		return $this->value;
+	}
+
+}

+ 5 - 11
engine/Ticket.php

@@ -4,6 +4,8 @@ namespace App;
 
 use App\Enums\TicketPriorities;
 use App\Enums\TicketStatuses;
+use App\Traits\DateTimeTrait;
+use App\Traits\SoftDeleteTrait;
 use Carbon\CarbonImmutable;
 
 /**
@@ -18,9 +20,6 @@ use Carbon\CarbonImmutable;
  * @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 {
@@ -34,6 +33,9 @@ class Ticket extends Model {
 		"dts_created", "dts_updated", "dts_deleted",
 	];
 
+	use DateTimeTrait;
+	use SoftDeleteTrait;
+
 	public function getLocation(): Location {
 		return Location::get($this->location_id);
 	}
@@ -46,14 +48,6 @@ class Ticket extends Model {
 		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;
 	}

+ 14 - 1
engine/TicketComment.php

@@ -2,6 +2,7 @@
 
 namespace App;
 
+use App\Interfaces\CommentInterface;
 use Carbon\CarbonImmutable;
 use Exception;
 
@@ -16,7 +17,7 @@ use Exception;
  * @property string $dts_deleted
  */
 
-class TicketComment extends Model {
+class TicketComment extends Model implements CommentInterface {
 
 	protected static $table = "ticket_comment";
 	protected static $idField = "id";
@@ -86,4 +87,16 @@ class TicketComment extends Model {
 		return $attachment;
 	}
 
+	public function isInternal(): bool {
+		return (bool) $this->internal;
+	}
+
+	public function getDateTimeCreated(): CarbonImmutable {
+		return $this->getDateTime();
+	}
+
+	public function renderEditIcon(): void {
+		// TODO
+	}
+
 }

+ 33 - 0
engine/Traits/DateTimeTrait.php

@@ -0,0 +1,33 @@
+<?php
+
+namespace App\Traits;
+use Carbon\CarbonImmutable;
+
+/**
+ * @property string $dts_created
+ * @property string $dts_updated
+ * @property string $dts_deleted
+ */
+trait DateTimeTrait {
+
+	public function getDateTimeCreated(): CarbonImmutable {
+		return new CarbonImmutable($this->dts_created, "UTC");
+	}
+
+	public function getDateTimeUpdated(): ?CarbonImmutable {
+		if(!$this->dts_updated) {
+			return null;
+		}
+
+		return new CarbonImmutable($this->dts_updated, "UTC");
+	}
+
+	public function getDateTimeDeleted(): ?CarbonImmutable {
+		if(!$this->dts_deleted) {
+			return null;
+		}
+
+		return new CarbonImmutable($this->dts_deleted, "UTC");
+	}
+
+}

+ 23 - 0
engine/Traits/SoftDeleteTrait.php

@@ -0,0 +1,23 @@
+<?php
+
+namespace App\Traits;
+
+use App\Database;
+
+/**
+ * @property string $dts_deleted
+ * @method bool commit()
+ */
+trait SoftDeleteTrait {
+
+	public function softDelete(): bool {
+		$this->dts_deleted = Database::dts();
+		return $this->commit();
+	}
+
+	public function restore(): bool {
+		$this->dts_deleted = null;
+		return $this->commit();
+	}
+
+}

+ 4 - 0
engine/User.php

@@ -162,4 +162,8 @@ class User extends Model {
 		return $this->formatDateTime($dt, "d/m/Y");
 	}
 
+	public function getTimezone(): string {
+		return "Europe/London";
+	}
+
 }

+ 6 - 0
engine/View.php

@@ -29,4 +29,10 @@ class View {
 
 	}
 
+	public static function getHtml(string $name, array $parameters): string {
+		ob_start();
+		self::include($name, $parameters);
+		return ob_get_clean();
+	}
+
 }

+ 2 - 0
public/js/app.js

@@ -145,4 +145,6 @@ $(() => {
 	if(map) {
 		new GoogleMap(map);
 	}
+
+	toastr.options.positionClass = "toast-bottom-right";
 });

+ 70 - 0
public/js/document-item-modal.js

@@ -0,0 +1,70 @@
+class DocumentItemModal {
+	constructor() {
+		this.$modal = $("#document-item-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.form = this.$form.get(0);
+
+		this.$documentItemIdField = this.$form.find("[name=document_item_id]");
+
+		this.$descriptionField = this.$form.find("[name=description]");
+		this.$serialNumberField = this.$form.find("[name=serial_number]");
+
+		this.$quantityField = this.$form.find("[name=quantity]");
+
+		this.$unitPriceField = this.$form.find("[name=unit_price]");
+	}
+
+	// Modal lifecycle
+	onShow(event) {
+	    const $element = $(event.relatedTarget);
+	    const data = $element.data();
+
+		const { item } = data;
+
+		if(item) {
+			this.$title.text("Update Invoice Item");
+
+			this.$documentItemIdField.val(item.id);
+			this.$descriptionField.val(item.description);
+			this.$serialNumberField.val(item.serialNumber);
+			this.$quantityField.val(item.quantity);
+			this.$unitPriceField.val(item.unitPrice);
+		}
+		else {
+			this.$title.text("Add Invoice Item");
+		}
+
+	}
+
+	onShown() {
+		this.$descriptionField.trigger("focus");
+	}
+
+	onHidden() {
+		this.$form.get(0).reset();
+		this.$documentItemIdField.val(null);
+	}
+
+	onSubmit(event) {
+		event.preventDefault();
+
+		$.post(window.location + `/submit-item`, this.$form.serialize()).then(response => {
+			this.$modal.modal("hide");
+			$("#document-items-section").html(response.html);
+			toastr.success("Item saved successfully.");
+			DocumentPage.InitItemsSection();
+		});
+	}
+
+}
+
+$(() => new DocumentItemModal());

+ 29 - 0
public/js/document-page.js

@@ -0,0 +1,29 @@
+class DocumentPage {
+	static InitItemsSection() {
+		const $table = $("#document-items-section table");
+		const $checkboxes = $table.find("input[type=checkbox]");
+		const $allCheckbox = $("#all-items-checkbox");
+		$allCheckbox.on("change", () => {
+			const checked = $allCheckbox.prop("checked");
+			$checkboxes.prop("checked", checked);
+		});
+
+		$table.find(".btn-delete-document-item").on("click", event => {
+			const documentItemId = $(event.currentTarget).data("document-item-id");
+			const confirmed = confirm("Are you sure you want to delete this item?");
+			if(confirmed) {
+				$.post(window.location + "/delete-item", {
+					document_item_id: documentItemId
+				}).then(response => {
+					toastr.success("Item deleted successfully.");
+					$("#document-items-section").html(response.html);
+					DocumentPage.InitItemsSection();
+				});
+			}
+		});
+	}
+}
+
+$(() => {
+	DocumentPage.InitItemsSection();
+});

+ 83 - 0
public/js/sale-item-modal.js

@@ -0,0 +1,83 @@
+class SaleItemModal {
+	constructor() {
+		this.$modal = $("#sale-item-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.form = this.$form.get(0);
+
+		this.$saleItemIdField = this.$form.find("[name=sale_item_id]");
+
+		this.$productDropdown = this.$form.find("[name=product_id]");
+		this.$productDropdown.on("change", event => this.onProductChange());
+
+		this.$quantityField = this.$form.find("[name=quantity]");
+
+		this.$unitPriceField = this.$form.find("[name=unit_price]");
+
+	}
+
+	// Modal lifecycle
+	onShow(event) {
+	    const $element = $(event.relatedTarget);
+	    const data = $element.data();
+
+		const { saleNumber, item } = data;
+
+		if(!saleNumber) {
+			console.error("saleNumber not provided.");
+			return false;
+		}
+
+		this.saleNumber = data.saleNumber;
+
+		if(data.item) {
+			const { item } = data;
+			this.$title.text("Update Sale Item");
+
+			this.$saleItemIdField.val(item.id);
+			this.$productDropdown.val(item.productId);
+			this.$quantityField.val(item.quantity);
+			this.$unitPriceField.val(item.unitPrice);
+		}
+		else {
+			this.$title.text("Add Sale Item");
+		}
+
+	}
+
+	onProductChange() {
+		const $option = this.$productDropdown.find("option:selected");
+		this.$unitPriceField.val($option.data("price"));
+	}
+
+	onShown() {
+		this.$productDropdown.trigger("focus");
+	}
+
+	onHidden() {
+		this.$form.get(0).reset();
+		this.$saleItemIdField.val(null);
+	}
+
+	onSubmit(event) {
+		event.preventDefault();
+
+		$.post(`/sales/${this.saleNumber}/submit-item`, this.$form.serialize()).then(response => {
+			this.$modal.modal("hide");
+			$("#sale-items-section").html(response.html);
+			toastr.success("Item saved successfully.");
+			SalePage.InitSaleItemSection();
+		});
+	}
+
+}
+
+$(() => new SaleItemModal());

+ 67 - 0
public/js/sale-note-modal.js

@@ -0,0 +1,67 @@
+class SaleNoteModal {
+	constructor() {
+		this.$modal = $("#sale-note-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.form = this.$form.get(0);
+
+		this.$saleNoteIdField = this.$form.find("[name=sale_note_id]");
+
+		this.$contentField = this.$form.find("[name=content]");
+	}
+
+	// Modal lifecycle
+	onShow(event) {
+	    const $element = $(event.relatedTarget);
+	    const data = $element.data();
+
+		const { saleNumber, note } = data;
+
+		if(!saleNumber) {
+			console.error("saleNumber not provided.");
+			return false;
+		}
+
+		this.saleNumber = data.saleNumber;
+
+		if(note) {
+			this.$title.text("Update Sale Note");
+
+			this.$saleNoteIdField.val(note.id);
+			this.$contentField.val(note.content);
+		}
+		else {
+			this.$title.text("Add Sale Note");
+		}
+	}
+
+	onShown() {
+		this.$contentField.trigger("focus");
+	}
+
+	onHidden() {
+		this.$form.get(0).reset();
+		this.$saleNoteIdField.val(null);
+	}
+
+	onSubmit(event) {
+		event.preventDefault();
+
+		$.post(`/sales/${this.saleNumber}/submit-note`, this.$form.serialize()).then(response => {
+			this.$modal.modal("hide");
+			$("#sale-notes-section").html(response.html);
+			toastr.success("Note saved successfully.");
+		});
+	}
+
+}
+
+$(() => new SaleNoteModal());

+ 29 - 0
public/js/sale-page.js

@@ -0,0 +1,29 @@
+class SalePage {
+	static InitSaleItemSection() {
+		const $table = $("#sale-items-section table");
+		const $checkboxes = $table.find("input[type=checkbox]");
+		const $allCheckbox = $("#sale-items-all-checkbox");
+		$allCheckbox.on("change", () => {
+			const checked = $allCheckbox.prop("checked");
+			$checkboxes.prop("checked", checked);
+		});
+
+		$table.find(".btn-delete-sale-item").on("click", event => {
+			const saleItemId = $(event.currentTarget).data("sale-item-id");
+			const confirmed = confirm("Are you sure you want to delete this sale item?");
+			if(confirmed) {
+				$.post(window.location + "/delete-item", {
+					sale_item_id: saleItemId
+				}).then(response => {
+					toastr.success("Sale item deleted successfully.");
+					$("#sale-items-section").html(response.html);
+					SalePage.InitSaleItemSection();
+				});
+			}
+		});
+	}
+}
+
+$(() => {
+	SalePage.InitSaleItemSection();
+});

+ 6 - 0
routes/default.php

@@ -46,6 +46,12 @@ $this->addRoute("/^users\/add$/", "user_form", [], ["requireUser" => true]);
 $this->addRoute("/^users\/$id_pattern\/update$/", "user_form", ["id"], ["requireUser" => true]);
 
 $this->addRoute("/^sales$/", "sales", [], ["requireUser" => true]);
+$this->addRoute("/^sales\/(submit)$/", "sale", ["action"], ["requireUser" => true]);
+$this->addRoute("/^sales\/(\d+)$/", "sale", ["number"], ["requireUser" => true]);
+$this->addRoute("/^sales\/(\d+)\/(submit|submit-note|delete-note|submit-item|delete-item|items-batch-action)$/", "sale", ["number", "action"], ["requireUser" => true]);
+
+$this->addRoute("/^sales\/\d+\/(invoices|delivery-notes)\/(\d+)$/", "document", ["document_type_string", "document_number"], ["requireUser" => true]);
+$this->addRoute("/^sales\/\d+\/(invoices|delivery-notes)\/(\d+)\/(submit|submit-item|delete-item|items-batch-action)$/", "document", ["document_type_string", "document_number", "action"], ["requireUser" => true]);
 
 $this->addRoute("/^tickets$/", "tickets", [], ["requireUser" => true]);
 $this->addRoute("/^tickets\/(create)$/", "tickets_ajax", ["action"], ["requireUser" => true]);

+ 68 - 0
views/components/comment_card.php

@@ -0,0 +1,68 @@
+<?php
+
+namespace App;
+
+use App\Interfaces\CommentInterface;
+
+/**
+ * @var CommentInterface $comment
+ */
+
+$core = Core::getInstance();
+$user = $core->getUser();
+
+$comment_user = $comment->getUser();
+$is_internal = $comment->isInternal();
+$dt_created = $comment->getDateTimeCreated();
+$attachments = $comment->getAttachments();
+$html = $comment->getHtml();
+
+?>
+
+<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($is_internal) {
+					?>
+					<span class="badge bg-primary">
+						<?=htmlspecialchars(__("Internal Comment"))?>
+					</span>
+					<?php
+				}
+
+				if($comment_user->is($user)) {
+					$comment->renderEditIcon();
+				}
+				?>
+			</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($user->formatDateTime($dt_created))?>
+			</div>
+			<hr />
+			<?=$html?>
+
+			<?php
+			if($attachments) {
+				?>
+				<hr />
+				<h5><?=htmlspecialchars(__("Attachments"))?></h5>
+				<?php
+				foreach($attachments as $attachment) {
+					$attachment->renderButton();
+				}
+			}
+			?>
+
+		</div>
+	</div>
+</div>

+ 251 - 0
views/document.php

@@ -0,0 +1,251 @@
+<?php /** @noinspection PhpUnhandledExceptionInspection */
+
+namespace App;
+
+use App\Enums\Currencies;
+use App\Enums\InvoiceStatuses;
+use App\Helpers\HtmlHelper;
+use NumberFormatter;
+
+/**
+ * @var Sale $sale
+ * @var Document $document
+ */
+
+$core = Core::getInstance();
+$user = $core->getUser();
+
+$sale = $document->getSale();
+$related_document = $document->getRelatedDocument();
+
+?>
+<section class="mb-4">
+	<h3><?=htmlspecialchars($document->getTitle())?></h3>
+	<form action="<?=htmlspecialchars($document->getUrl())?>/submit" method="post">
+
+		<div class="row">
+			<div class="col-xl-8">
+
+				<h4><?=htmlspecialchars(__("Main Details"))?></h4>
+
+				<?php
+				$user->insertCsrfToken();
+				?>
+
+				<div class="row">
+					<?php
+					if($document->isInvoice()) {
+						?>
+						<div class="col-sm-6">
+							<div class="mb-3">
+								<label for="invoice-status" class="form-label">
+									<?=htmlspecialchars(__("Status"))?>
+								</label>
+								<select class="form-control" name="invoice_status" id="invoice-status">
+									<?php
+									HtmlHelper::renderOptions(InvoiceStatuses::options(), $document->invoice_status);
+									?>
+								</select>
+							</div>
+						</div>
+						<?php
+					}
+					?>
+					<div class="col-sm-6">
+						<div class="mb-3">
+							<label for="date" class="form-label">
+								<?=htmlspecialchars(__("Date"))?>
+							</label>
+							<input class="form-control" type="date" name="date" id="date" value="<?=$document->date?>" required />
+						</div>
+					</div>
+				</div>
+
+				<?php
+				if($document->isInvoice()) {
+					?>
+					<div class="row">
+						<div class="col">
+							<div class="mb-3">
+								<label for="currency" class="form-label">
+									<?=htmlspecialchars(__("Currency"))?>
+								</label>
+								<select class="form-control" name="currency" id="currency">
+									<?php
+									HtmlHelper::renderOptions(Currencies::options(), $document->currency);
+									?>
+								</select>
+							</div>
+						</div>
+						<div class="col">
+							<div class="mb-3">
+								<label for="tax-rate" class="form-label">
+									<?=htmlspecialchars(__("Tax Rate (%)"))?>
+								</label>
+								<input type="number" class="form-control" name="tax_rate" id="tax-rate" min="0" step="0.01" value="<?=htmlspecialchars($document->tax_rate)?>" placeholder="<?=htmlspecialchars(__("Type tax rate"))?>" required />
+							</div>
+						</div>
+					</div>
+					<?php
+				}
+				?>
+
+				<div class="row">
+					<div class="col-sm-6">
+						<div class="mb-3">
+							<label for="billing-address" class="form-label">
+								<?=htmlspecialchars(__("Billing Address"))?>
+							</label>
+							<textarea class="form-control" name="billing_address" id="billing-address" rows="6" placeholder="<?=htmlspecialchars(__("Type billing address"))?>" required><?=htmlspecialchars($document->billing_address)?></textarea>
+						</div>
+					</div>
+					<div class="col-sm-6">
+						<div class="mb-3">
+							<label for="delivery-address" class="form-label">
+								<?=htmlspecialchars(__("Delivery Address"))?>
+							</label>
+							<textarea class="form-control" name="delivery_address" id="delivery-address" rows="6" placeholder="<?=htmlspecialchars(__("Type delivery address"))?>"><?=htmlspecialchars($document->delivery_address)?></textarea>
+						</div>
+					</div>
+				</div>
+
+				<div class="row">
+					<div class="col-sm-6">
+						<div class="mb-3">
+							<label for="po-number" class="form-label">
+								<?=htmlspecialchars(__("PO Number"))?>
+							</label>
+							<input type="text" class="form-control" name="po_number" id="po-number" placeholder="<?=htmlspecialchars(__("Type PO number"))?>" value="<?=htmlspecialchars($document->po_number)?>" />
+						</div>
+					</div>
+					<?php
+					if($document->isInvoice()) {
+						?>
+						<div class="col-sm-6">
+							<div class="mb-3">
+								<label for="terms" class="form-label">
+									<?=htmlspecialchars(__("Terms"))?>
+								</label>
+								<input type="text" class="form-control" name="terms" id="terms" placeholder="<?=htmlspecialchars(__("Type terms"))?>" value="<?=htmlspecialchars($document->terms)?>" />
+							</div>
+						</div>
+						<?php
+					}
+					?>
+				</div>
+
+				<div class="mb-3">
+					<label for="notes" class="form-label">
+						<?=htmlspecialchars(__("Notes"))?>
+					</label>
+					<textarea class="form-control" name="notes" id="notes" rows="6" placeholder="<?=htmlspecialchars(__("Type notes"))?>"><?=htmlspecialchars($document->notes)?></textarea>
+				</div>
+
+			</div>
+			<div class="col-xl-4">
+				<h4><?=htmlspecialchars(__("Additional Details"))?></h4>
+
+				<?php
+				if($document->isInvoice()) {
+					?>
+					<div class="mb-3">
+						<label for="dts-finalised" class="form-label">
+							<?=htmlspecialchars(__("Date/Time Finalised"))?>
+						</label>
+						<input class="form-control" type="datetime-local" name="dts_finalised" id="dts-finalised" value="<?=$document->dts_finalised?>" />
+					</div>
+					<div class="mb-3">
+						<label for="dts-paid" class="form-label">
+							<?=htmlspecialchars(__("Date/Time Paid"))?>
+						</label>
+						<input class="form-control" type="datetime-local" name="dts_paid" id="dts-paid" value="<?=$document->dts_paid?>" />
+					</div>
+					<?php
+				}
+				?>
+
+				<div class="mb-3">
+					<label for="delivery-company" class="form-label">
+						<?=htmlspecialchars(__("Delivery Company"))?>
+					</label>
+					<input type="text" class="form-control" name="delivery_company" id="delivery-company" placeholder="<?=htmlspecialchars(__("Type delivery company"))?>" value="<?=htmlspecialchars($document->delivery_company)?>" />
+				</div>
+				<div class="mb-3">
+					<label for="tracking-number" class="form-label">
+						<?=htmlspecialchars(__("Tracking Number"))?>
+					</label>
+					<input type="text" class="form-control" name="tracking_number" id="tracking-number" placeholder="<?=htmlspecialchars(__("Type tracking number"))?>" value="<?=htmlspecialchars($document->tracking_number)?>" />
+				</div>
+
+				<dl>
+					<dt><?=htmlspecialchars(__("Created By"))?></dt>
+					<dd><?=htmlspecialchars($document->getUser()->getDisplayName())?></dd>
+
+					<dt><?=htmlspecialchars(__("Date/Time Created"))?></dt>
+					<dd><?=htmlspecialchars($user->formatDateTime($document->getDateTimeCreated()))?></dd>
+
+					<?php
+					if($sale) {
+						?>
+						<dt><?=htmlspecialchars(__("Related Sale"))?></dt>
+						<dd>
+							<a href="<?=htmlspecialchars($sale->getUrl())?>">
+								<?=htmlspecialchars($sale->getTitle())?>
+							</a>
+						</dd>
+						<?php
+					}
+
+					if($related_document) {
+						?>
+						<dt><?=htmlspecialchars(__("Related Document"))?></dt>
+						<dd>
+							<a href="<?=htmlspecialchars($related_document->getUrl())?>">
+								<?=htmlspecialchars($related_document->getTitle())?>
+							</a>
+						</dd>
+						<?php
+					}
+					?>
+				</dl>
+
+
+			</div>
+		</div>
+
+		<button type="submit" class="btn btn-primary">
+			<i class="fa fa-fw fa-save"></i>
+			<?=htmlspecialchars(__("Save"))?>
+		</button>
+
+		<?php
+		if($document->isInvoice()) {
+			?>
+			<div class="dropdown d-inline-block">
+				<button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
+					<i class="fa fa-fw fa-file-invoice"></i>
+					<?=htmlspecialchars(__("Generate PDF"))?>
+				</button>
+				<div class="dropdown-menu">
+					<a href="#" class="dropdown-item"><?=htmlspecialchars(__("Proforma Invoice"))?></a>
+					<a href="#" class="dropdown-item"><?=htmlspecialchars(__("Commercial Invoice"))?></a>
+				</div>
+			</div>
+			<?php
+		}
+		else {
+			?>
+			<button type="button" class="btn btn-primary">
+				<i class="fa fa-fw fa-file-invoice"></i>
+				<?=htmlspecialchars(__("Generate PDF"))?>
+			</button>
+			<?php
+		}
+		?>
+
+
+	</form>
+</section>
+
+<?php
+View::include("document_items_section", ["document" => $document]);

+ 169 - 0
views/document_items_section.php

@@ -0,0 +1,169 @@
+<?php
+namespace App;
+
+use NumberFormatter;
+
+/**
+ * @var Document $document
+ */
+
+?>
+<section class="mb-4" id="document-items-section">
+
+	<div class="row mb-3">
+		<div class="col">
+			<h3><?=htmlspecialchars(__("Items"))?></h3>
+		</div>
+		<div class="col-auto">
+			<button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#document-item-modal">
+				<i class="fa fa-fw fa-plus"></i>
+				<?=htmlspecialchars(__("Add Item"))?>
+			</button>
+		</div>
+	</div>
+
+	<form action="<?=htmlspecialchars($document->getUrl())?>/items-batch-action" method="post">
+
+		<table class="table table-bordered table-hover mb-2">
+			<colgroup>
+				<col style="width: 1%"/>
+				<col style="width: 35%"/>
+				<col style="width: 20%"/>
+				<col style="width: 15%"/>
+				<?php
+				if($document->isInvoice()) {
+					?>
+					<col style="width: 15%"/>
+					<col style="width: 15%"/>
+					<?php
+				}
+				?>
+				<col style="width: 1%"/>
+			</colgroup>
+			<thead>
+			<tr>
+				<th>
+					<!--suppress HtmlFormInputWithoutLabel -->
+					<input class="form-check-input" id="all-items-checkbox" type="checkbox" />
+				</th>
+				<th><?=htmlspecialchars(__("Description"))?></th>
+				<th><?=htmlspecialchars(__("Serial Number"))?></th>
+				<th><?=htmlspecialchars(__("Quantity"))?></th>
+				<?php
+				if($document->isInvoice()) {
+					?>
+					<th><?=htmlspecialchars(__("Unit Price"))?></th>
+					<th><?=htmlspecialchars(__("Amount"))?></th>
+					<?php
+				}
+				?>
+				<th><?=htmlspecialchars(__("Actions"))?></th>
+			</tr>
+			</thead>
+			<tbody>
+			<?php
+			$formatter = new NumberFormatter("en_GB", NumberFormatter::CURRENCY);
+			$currency = $document->currency;
+			$subtotal = "0.00";
+
+			foreach($document->getItems() as $item) {
+				?>
+				<tr>
+					<td>
+						<!--suppress HtmlFormInputWithoutLabel -->
+						<input class="form-check-input" type="checkbox" name="document_item_ids[]" value="<?=$item->id?>" />
+					</td>
+					<td>
+						<?=htmlspecialchars($item->description)?>
+					</td>
+					<td>
+						<?=htmlspecialchars($item->serial_number)?>
+					</td>
+					<td class="text-end">
+						<?=$item->quantity?>
+					</td>
+					<?php
+					if($document->isInvoice()) {
+						?>
+						<td class="text-end">
+							<?=htmlspecialchars($formatter->formatCurrency($item->unit_price, $currency))?>
+						</td>
+						<td class="text-end">
+							<?=htmlspecialchars($formatter->formatCurrency($item->getAmount(), $currency))?>
+						</td>
+						<?php
+						$subtotal = bcadd($subtotal, $item->getAmount());
+					}
+					?>
+					<td class="p-1 text-nowrap">
+						<button class="btn btn-sm btn-primary" type="button" data-bs-toggle="modal" data-bs-target="#document-item-modal" data-document-id="<?=$document->id?>" data-item="<?=htmlspecialchars(json_encode($item))?>">
+							<i class="fa fa-fw fa-pencil"></i>
+						</button>
+						<button class="btn btn-sm btn-danger btn-delete-document-item" type="button" data-document-item-id="<?=$item->id?>">
+							<i class="fa fa-fw fa-trash"></i>
+						</button>
+					</td>
+				</tr>
+				<?php
+			}
+			?>
+			</tbody>
+			<?php
+			if($document->isInvoice()) {
+				$tax = bcmul($subtotal, $document->tax_rate / 100, 2);
+				$total = bcadd($subtotal, $tax, 2);
+				?>
+				<tfoot>
+				<tr>
+					<th colspan="5" class="text-end"><?=htmlspecialchars(__("Subtotal"))?></th>
+					<td class="text-end"><?=htmlspecialchars($formatter->formatCurrency($subtotal, $currency))?></td>
+					<td></td>
+				</tr>
+				<tr>
+					<th colspan="5" class="text-end"><?=htmlspecialchars(__("Tax Rate"))?></th>
+					<td class="text-end">
+						<?=$document->tax_rate?>%
+					</td>
+					<td></td>
+				</tr>
+				<tr>
+					<th colspan="5" class="text-end"><?=htmlspecialchars(__("Tax"))?></th>
+					<td class="text-end">
+						<?=htmlspecialchars($formatter->formatCurrency($tax, $currency))?>
+					</td>
+					<td></td>
+				</tr>
+				<tr>
+					<th colspan="5" class="text-end"><?=htmlspecialchars(__("Total"))?></th>
+					<td class="text-end">
+						<?=htmlspecialchars($formatter->formatCurrency($total, $currency))?>
+					</td>
+					<td></td>
+				</tr>
+				</tfoot>
+				<?php
+			}
+			?>
+		</table>
+
+		<div class="mb-1">
+			<?=htmlspecialchars(__("With selected items:"))?>
+		</div>
+
+		<?php
+		if($document->isInvoice()) {
+			?>
+			<button type="submit" class="btn btn-primary" name="batch_action" value="create-delivery-note">
+				<i class="fa fa-fw fa-file-invoice"></i>
+				<?=htmlspecialchars(__("Create Delivery Note"))?>
+			</button>
+			<?php
+		}
+		?>
+
+		<button type="submit" class="btn btn-danger" name="batch_action" value="delete">
+			<i class="fa fa-fw fa-trash"></i>
+			<?=htmlspecialchars(__("Delete"))?>
+		</button>
+	</form>
+</section>

+ 47 - 0
views/modals/document_item.php

@@ -0,0 +1,47 @@
+<?php
+namespace App;
+?>
+<div class="modal fade" role="dialog" tabindex="-1" data-backdrop="static" id="document-item-modal">
+	<div class="modal-dialog modal-lg">
+		<form class="modal-content" method="post">
+			<?php
+			View::include("modals/header", ["title" => __("Document Item")]);
+			?>
+			<input type="hidden" name="document_item_id" value="" />
+
+			<div class="modal-body">
+				<div class="mb-2">
+					<label for="document-item-description" class="form-label">
+						<?=htmlspecialchars(__("Description"))?>
+					</label>
+
+					<input class="form-control" type="text" name="description" id="document-item-description" placeholder="<?=htmlspecialchars(__("Type description"))?>" maxlength="255" required />
+				</div>
+				<div class="mb-2">
+					<label for="document-item-serial-number" class="form-label">
+						<?=htmlspecialchars(__("Description"))?>
+					</label>
+
+					<input class="form-control" type="text" name="serial_number" id="document-item-serial-number" placeholder="<?=htmlspecialchars(__("Type serial number"))?>" maxlength="255" />
+				</div>
+				<div class="mb-2">
+					<label for="sale-item-quantity" class="form-label">
+						<?=htmlspecialchars(__("Quantity"))?>
+					</label>
+					<input class="form-control" type="number" name="quantity" id="sale-item-quantity" min="0" value="1" placeholder="<?=htmlspecialchars(__("Type quantity"))?>" required />
+				</div>
+				<div class="mb-2">
+					<label for="sale-item-unit-price" class="form-label">
+						<?=htmlspecialchars(__("Unit Price"))?>
+					</label>
+					<input class="form-control" type="number" name="unit_price" id="sale-item-unit-price" min="0.00" step="0.01" value="0.00" placeholder="<?=htmlspecialchars(__("Type unit price"))?>" required />
+				</div>
+			</div>
+			<div class="modal-footer">
+				<button type="submit" class="btn btn-success">
+					<?= htmlspecialchars(__("Save")) ?>
+				</button>
+			</div>
+		</form>
+	</div>
+</div>

+ 60 - 0
views/modals/new_sale.php

@@ -0,0 +1,60 @@
+<?php
+namespace App;
+
+?>
+<div class="modal fade" role="dialog" tabindex="-1" data-backdrop="static" id="new-sale-modal">
+	<div class="modal-dialog modal-lg">
+		<form class="modal-content" method="post" action="/sales/submit">
+			<?php
+			View::include("modals/header", ["title" => __("New Sale")]);
+			?>
+			<div class="modal-body">
+				<div class="mb-3">
+					<label for="new-sale-company-id" class="form-label">
+						<?=htmlspecialchars(__("Company"))?>
+					</label>
+					<select class="form-control" name="company_id" id="new-sale-company-id">
+						<?php
+						foreach(Company::getAll() as $company) {
+							?>
+							<option value="<?=$company->id?>">
+								<?=htmlspecialchars($company->name)?>
+							</option>
+							<?php
+						}
+						?>
+					</select>
+				</div>
+
+				<div class="mb-3">
+					<label class="form-label" for="location-id"><?= htmlspecialchars(__("Location")) ?></label>
+					<select class="form-control" name="location_id" id="location-id">
+						<?php
+						foreach(Customer::getAll() as $customer) {
+							?>
+							<optgroup label="<?=htmlspecialchars($customer->name)?>">
+								<?php
+								foreach($customer->getLocations() as $location) {
+									?>
+									<option value="<?=$location->id?>">
+										<?=htmlspecialchars($location->name)?>
+									</option>
+									<?php
+								}
+								?>
+							</optgroup>
+							<?php
+						}
+						?>
+					</select>
+				</div>
+
+			</div>
+			<div class="modal-footer">
+				<button type="submit" class="btn btn-success">
+					<?= htmlspecialchars(__("Submit")) ?>
+				</button>
+			</div>
+		</form>
+	</div>
+</div>

+ 48 - 0
views/modals/sale_item.php

@@ -0,0 +1,48 @@
+<?php
+namespace App;
+?>
+<div class="modal fade" role="dialog" tabindex="-1" data-backdrop="static" id="sale-item-modal">
+	<div class="modal-dialog modal-lg">
+		<form class="modal-content" method="post">
+			<?php
+			View::include("modals/header", ["title" => __("Sale Item")]);
+			?>
+			<input type="hidden" name="sale_item_id" value="" />
+
+			<div class="modal-body">
+				<div class="mb-2">
+					<label for="sale-item-product-id" class="form-label"><?=htmlspecialchars(__("Product"))?></label>
+					<select class="form-control" name="product_id" id="sale-item-product-id">
+						<option value=""><?=htmlspecialchars(__("Select Product"))?></option>
+						<?php
+						foreach(Product::getAll() as $product) {
+							?>
+							<option value="<?=$product->id?>" data-price="<?=$product->price?>" data-price-eur="">
+								<?=htmlspecialchars($product->name)?>
+							</option>
+							<?php
+						}
+						?>
+					</select>
+				</div>
+				<div class="mb-2">
+					<label for="sale-item-quantity" class="form-label">
+						<?=htmlspecialchars(__("Quantity"))?>
+					</label>
+					<input class="form-control" type="number" name="quantity" id="sale-item-quantity" min="0" value="1" placeholder="<?=htmlspecialchars(__("Type quantity"))?>" required />
+				</div>
+				<div class="mb-2">
+					<label for="sale-item-unit-price" class="form-label">
+						<?=htmlspecialchars(__("Unit Price"))?>
+					</label>
+					<input class="form-control" type="number" name="unit_price" id="sale-item-unit-price" min="0.00" step="0.01" value="0.00" placeholder="<?=htmlspecialchars(__("Type unit price"))?>" required />
+				</div>
+			</div>
+			<div class="modal-footer">
+				<button type="submit" class="btn btn-success">
+					<?= htmlspecialchars(__("Save")) ?>
+				</button>
+			</div>
+		</form>
+	</div>
+</div>

+ 25 - 0
views/modals/sale_note.php

@@ -0,0 +1,25 @@
+<?php
+namespace App;
+?>
+<div class="modal fade" role="dialog" tabindex="-1" data-backdrop="static" id="sale-note-modal">
+	<div class="modal-dialog modal-lg">
+		<form class="modal-content" method="post">
+			<?php
+			View::include("modals/header", ["title" => __("Sale Note")]);
+			?>
+			<input type="hidden" name="sale_note_id" value="" />
+
+			<div class="modal-body">
+				<div class="mb-2">
+					<label for="sale-note-content" class="form-label"><?=htmlspecialchars(__("Content"))?></label>
+					<textarea class="form-control" name="content" id="sale-note-content" rows="4" placeholder="<?=htmlspecialchars(__("Type content"))?>" required></textarea>
+				</div>
+			</div>
+			<div class="modal-footer">
+				<button type="submit" class="btn btn-success">
+					<?= htmlspecialchars(__("Save")) ?>
+				</button>
+			</div>
+		</form>
+	</div>
+</div>

+ 9 - 1
views/product_form.php

@@ -11,6 +11,14 @@ $core = Core::getInstance();
 $user = $core->getUser();
 
 $suppliers = Supplier::getAll();
+$request = Request::fromRequest();
+
+if($product->isNew()) {
+	$supplier_id = $request->int("supplier_id");
+}
+else {
+	$supplier_id = $product->supplier_id;
+}
 
 ?>
 <h3><?=htmlspecialchars($title)?></h3>
@@ -27,7 +35,7 @@ $suppliers = Supplier::getAll();
 			<?php
 			foreach($suppliers as $supplier) {
 				?>
-				<option value="<?=$supplier->id?>" <?=Html::selected($supplier->id, $product->supplier_id)?>>
+				<option value="<?=$supplier->id?>" <?=Html::selected($supplier->id, $supplier_id)?>>
 					<?=htmlspecialchars($supplier->name)?>
 				</option>
 				<?php

+ 98 - 0
views/sale.php

@@ -0,0 +1,98 @@
+<?php /** @noinspection PhpUnhandledExceptionInspection */
+
+namespace App;
+
+use App\Enums\Currencies;
+use App\Enums\SaleStatuses;
+use App\Helpers\HtmlHelper;
+
+/**
+ * @var Sale $sale
+ */
+
+?>
+
+<section class="mb-4">
+	<h3><?=htmlspecialchars($sale->getTitle())?></h3>
+
+	<form class="mb-4" action="<?=htmlspecialchars($sale->getUrl())?>/submit" method="post">
+
+		<div class="row">
+
+			<div class="col-xl-6">
+
+				<h4><?=htmlspecialchars(__("Main Details"))?></h4>
+
+				<div class="mb-3">
+					<label class="form-label" for="currency"><?=htmlspecialchars(__("Currency"))?></label>
+					<select class="form-control" name="currency" id="currency">
+						<?php
+						HtmlHelper::renderOptions(Currencies::options(), $sale->currency);
+						?>
+					</select>
+				</div>
+
+				<div class="mb-3">
+					<label class="form-label" for="status">
+						<?=htmlspecialchars(__("Status"))?>
+					</label>
+					<select class="form-control" name="status" id="status">
+						<?php
+						HtmlHelper::renderOptions(SaleStatuses::options(), $sale->status);
+						?>
+					</select>
+				</div>
+
+				<div class="mb-3">
+					<label for="tax-rate" class="form-label">
+						<?=htmlspecialchars(__("Tax Rate (%)"))?>
+					</label>
+					<input class="form-control" type="number" name="tax_rate" id="tax-rate" value="<?=$sale->tax_rate?>" min="0" max="100.00" step="0.01" placeholder="Type tax rate" required />
+				</div>
+
+			</div>
+			<div class="col-xl-6">
+
+				<h4><?=htmlspecialchars(__("Additional Details"))?></h4>
+				<dl>
+					<dt><?=htmlspecialchars(__("Company"))?></dt>
+					<dd><?=htmlspecialchars($sale->getCompany()->name)?></dd>
+
+					<dt><?=htmlspecialchars(__("Location"))?></dt>
+					<dd><?=htmlspecialchars($sale->getLocation()->getDisplayName())?></dd>
+
+					<dt><?=htmlspecialchars(__("Created By"))?></dt>
+					<dd><?=htmlspecialchars($sale->getUser()->getDisplayName())?></dd>
+
+					<dt><?=htmlspecialchars(__("Created Date/Time"))?></dt>
+					<dd><?=htmlspecialchars($sale->getDateTimeCreated()->format("d/m/Y H:i"))?></dd>
+
+				</dl>
+			</div>
+		</div>
+
+		<button type="submit" class="btn btn-primary">
+			<i class="fa fa-fw fa-save"></i>
+			<?=htmlspecialchars(__("Save Sale"))?>
+		</button>
+	</form>
+</section>
+
+<?php
+View::include("sale_items_section", compact("sale"));
+View::include("sale_invoices_section", compact("sale"));
+View::include("sale_notes_section", compact("sale"));
+?>
+
+<section class="mb-4">
+	<h3><?=htmlspecialchars(__("Tickets"))?></h3>
+	<?php
+	$tickets = $sale->getTickets();
+	if(empty($tickets)) {
+		HtmlHelper::renderInfoAlert(__("No tickets to display."));
+	}
+	else {
+
+	}
+	?>
+</section>

+ 59 - 0
views/sale_invoices_section.php

@@ -0,0 +1,59 @@
+<?php
+
+namespace App;
+
+/**
+ * @var Sale $sale
+ */
+
+use App\Helpers\HtmlHelper;
+
+?>
+
+<section class="mb-4">
+	<h3><?=htmlspecialchars(__("Invoices"))?></h3>
+	<?php
+	$invoices = $sale->getInvoices();
+	if(empty($invoices)) {
+		HtmlHelper::renderInfoAlert(__("No invoices to display."));
+	}
+	else {
+		?>
+		<table class="table table-bordered table-hover">
+			<thead>
+			<tr>
+				<th><?=htmlspecialchars(__("Number"))?></th>
+				<th><?=htmlspecialchars(__("Status"))?></th>
+				<th><?=htmlspecialchars(__("Total"))?></th>
+				<th><?=htmlspecialchars(__("Actions"))?></th>
+			</tr>
+			</thead>
+			<tbody>
+			<?php
+			foreach($invoices as $invoice) {
+				?>
+				<tr>
+					<td class="text-end">
+						<?=$invoice->number?>
+					</td>
+					<td>
+						<?=htmlspecialchars($invoice->getDisplayInvoiceStatus())?>
+					</td>
+					<td class="text-end">
+						<?=htmlspecialchars($invoice->getDisplayTotal())?>
+					</td>
+					<td class="p-1">
+						<a href="<?=htmlspecialchars($invoice->getUrl())?>" class="btn btn-sm btn-primary">
+							<?=htmlspecialchars(__("View"))?>
+						</a>
+					</td>
+				</tr>
+				<?php
+			}
+			?>
+			</tbody>
+		</table>
+		<?php
+	}
+	?>
+</section>

+ 145 - 0
views/sale_items_section.php

@@ -0,0 +1,145 @@
+<?php
+
+namespace App;
+
+use App\Helpers\HtmlHelper;
+use NumberFormatter;
+
+/**
+ * @var Sale $sale
+ */
+
+?>
+<section id="sale-items-section" class="mb-4">
+	<div class="row mb-3">
+		<div class="col">
+			<h3><?=htmlspecialchars("Sale Items")?></h3>
+		</div>
+		<div class="col-auto">
+			<button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#sale-item-modal" data-sale-number="<?=$sale->getNumber()?>">
+				<i class="fa fa-fw fa-plus"></i>
+				<?=htmlspecialchars(__("Add Item"))?>
+			</button>
+		</div>
+	</div>
+	<?php
+	$items = $sale->getItems();
+	if(empty($items)) {
+		HtmlHelper::renderInfoAlert(__("No items to display."));
+	}
+	else {
+		$subtotal = "0.00";
+		$formatter = new NumberFormatter("en_GB", NumberFormatter::CURRENCY);
+		$currency = $sale->getCurrency();
+		?>
+		<form action="<?=$sale->getUrl()?>/items-batch-action" method="post">
+			<table id="sale-items-table" class="table table-bordered table-hover mb-2">
+				<colgroup>
+					<col style="width: 1%"/>
+					<col style="width: 40%"/>
+					<col style="width: 20%"/>
+					<col style="width: 20%"/>
+					<col style="width: 20%"/>
+					<col style="width: 1%"/>
+				</colgroup>
+				<thead>
+				<tr>
+					<th>
+						<!--suppress HtmlFormInputWithoutLabel -->
+						<input class="form-check-input" id="sale-items-all-checkbox" type="checkbox" />
+					</th>
+					<th><?=htmlspecialchars(__("Product"))?></th>
+					<th><?=htmlspecialchars(__("Quantity"))?></th>
+					<th><?=htmlspecialchars(__("Unit Price"))?></th>
+					<th><?=htmlspecialchars(__("Amount"))?></th>
+					<th><?=htmlspecialchars(__("Actions"))?></th>
+				</tr>
+				</thead>
+				<tbody>
+				<?php
+				foreach($items as $item) {
+					$product = $item->getProduct();
+					$supplier_name = $product->getSupplier()->name;
+					?>
+					<tr>
+						<td>
+							<!--suppress HtmlFormInputWithoutLabel -->
+							<input class="form-check-input" type="checkbox" value="<?=$item->id?>" name="sale_item_ids[]" />
+						</td>
+						<td>
+							<small class="text-uppercase text-muted"><?=htmlspecialchars($supplier_name)?></small><br />
+							<?=htmlspecialchars($product->name)?>
+						</td>
+						<td class="text-end">
+							<?=$item->quantity?>
+						</td>
+						<td class="text-end">
+							<?=htmlspecialchars($formatter->formatCurrency($item->unit_price, $currency))?>
+						</td>
+						<td class="text-end">
+							<?=htmlspecialchars($formatter->formatCurrency($item->getAmount(), $currency))?>
+						</td>
+						<td class="p-1 text-nowrap">
+							<button class="btn btn-sm btn-primary" type="button" data-bs-toggle="modal" data-bs-target="#sale-item-modal" data-sale-number="<?=$sale->getNumber()?>" data-item="<?=htmlspecialchars(json_encode($item))?>">
+								<i class="fa fa-fw fa-pencil"></i>
+							</button>
+							<button class="btn btn-sm btn-danger btn-delete-sale-item" type="button" data-sale-item-id="<?=$item->id?>">
+								<i class="fa fa-fw fa-trash"></i>
+							</button>
+						</td>
+					</tr>
+					<?php
+					$subtotal = bcadd($subtotal, $item->getAmount());
+				}
+				$tax = bcmul($subtotal, $sale->tax_rate / 100, 2);
+				$total = bcadd($subtotal, $tax, 2);
+				?>
+				</tbody>
+				<tfoot>
+				<tr>
+					<th colspan="4" class="text-end"><?=htmlspecialchars(__("Subtotal"))?></th>
+					<td class="text-end"><?=htmlspecialchars($formatter->formatCurrency($subtotal, $currency))?></td>
+					<td></td>
+				</tr>
+				<tr>
+					<th colspan="4" class="text-end"><?=htmlspecialchars(__("Tax Rate"))?></th>
+					<td class="text-end">
+						<?=$sale->tax_rate?>%
+					</td>
+					<td></td>
+				</tr>
+				<tr>
+					<th colspan="4" class="text-end"><?=htmlspecialchars(__("Tax"))?></th>
+					<td class="text-end">
+						<?=htmlspecialchars($formatter->formatCurrency($tax, $currency))?>
+					</td>
+					<td></td>
+				</tr>
+				<tr>
+					<th colspan="4" class="text-end"><?=htmlspecialchars(__("Total"))?></th>
+					<td class="text-end">
+						<?=htmlspecialchars($formatter->formatCurrency($total, $currency))?>
+					</td>
+					<td></td>
+				</tr>
+				</tfoot>
+			</table>
+
+			<div class="mb-1">
+				<?=htmlspecialchars(__("With selected items:"))?>
+			</div>
+
+			<button type="submit" class="btn btn-primary" name="batch_action" value="create-invoice">
+				<i class="fa fa-fw fa-file-invoice"></i>
+				<?=htmlspecialchars(__("Create Invoice"))?>
+			</button>
+			<button type="submit" class="btn btn-danger" name="batch_action" value="delete">
+				<i class="fa fa-fw fa-trash"></i>
+				<?=htmlspecialchars(__("Delete"))?>
+			</button>
+
+		</form>
+		<?php
+	}
+	?>
+</section>

+ 35 - 0
views/sale_notes_section.php

@@ -0,0 +1,35 @@
+<?php
+
+namespace App;
+
+use App\Helpers\HtmlHelper;
+
+/**
+ * @var Sale $sale
+ */
+
+?>
+<section class="mb-4" id="sale-notes-section">
+	<div class="row mb-3">
+		<div class="col">
+			<h3><?=htmlspecialchars(__("Notes"))?></h3>
+		</div>
+		<div class="col-auto">
+			<button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#sale-note-modal" data-sale-number="<?=$sale->getNumber()?>">
+				<i class="fa fa-fw fa-plus"></i>
+				<?=htmlspecialchars(__("Add Note"))?>
+			</button>
+		</div>
+	</div>
+	<?php
+	$notes = $sale->getNotes();
+	if(empty($notes)) {
+		HtmlHelper::renderInfoAlert(__("No notes to display."));
+	}
+	else {
+		foreach($notes as $note) {
+			View::include("components/comment_card", ["comment" => $note]);
+		}
+	}
+	?>
+</section>

+ 49 - 5
views/sales.php

@@ -2,20 +2,64 @@
 
 namespace App;
 
+/**
+ * @var Sale[] $sales
+ */
+
 ?>
 <div class="row mb-3">
 	<div class="col">
 		<h3><?=htmlspecialchars(__("Sales"))?></h3>
 	</div>
 	<div class="col-auto">
-		<a class="btn btn-success" href="/sales/add">
+		<a class="btn btn-success" data-bs-toggle="modal" data-bs-target="#new-sale-modal">
 			<i class="fa fa-fw fa-plus"></i>
 			<?=htmlspecialchars(__("Add"))?>
 		</a>
 	</div>
 </div>
 
-<div class="alert alert-warning">
-	<i class="fa fa-fw fa-info-circle"></i>
-	<?=htmlspecialchars(__("Coming soon..."))?>
-</div>
+<?php
+
+if(empty($sales)) {
+	?>
+	<div class="alert alert-info">
+		<i class="fa fa-fw fa-info-circle"></i>
+		<?=htmlspecialchars(__("No sales to display."))?>
+	</div>
+	<?php
+}
+else {
+	?>
+	<table class="table table-bordered table-hover">
+		<thead>
+		<tr>
+			<th><?=htmlspecialchars(__("Number"))?></th>
+			<th><?=htmlspecialchars(__("Status"))?></th>
+			<th><?=htmlspecialchars(__("Actions"))?></th>
+		</tr>
+		</thead>
+		<tbody>
+		<?php
+		foreach($sales as $sale) {
+			?>
+			<tr>
+				<td class="text-right">
+					<?=number_format($sale->getNumber())?>
+				</td>
+				<td>
+					<?=htmlspecialchars($sale->getDisplayStatus())?>
+				</td>
+				<td class="p-1">
+					<a class="btn btn-sm btn-primary" href="<?=htmlspecialchars($sale->getUrl())?>">
+						<?=htmlspecialchars(__("View"))?>
+					</a>
+				</td>
+			</tr>
+			<?php
+		}
+		?>
+		</tbody>
+	</table>
+	<?php
+}

+ 1 - 1
views/supplier.php

@@ -17,7 +17,7 @@ $products = $supplier->getProducts();
 		<h4><?=htmlspecialchars(__("Products"))?></h4>
 	</div>
 	<div class="col-auto">
-		<a class="btn btn-primary" href="<?=htmlspecialchars($supplier->getUrl())?>/products/add">
+		<a class="btn btn-primary" href="/products/add?supplier_id=<?=$supplier->id?>">
 			<i class="fa fa-fw fa-plus"></i>
 			<?=htmlspecialchars(__("Add"))?>
 		</a>

+ 1 - 47
views/ticket.php

@@ -188,52 +188,6 @@ if(empty($comments)) {
 }
 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
+		View::include("components/comment_card", ["comment" => $comment]);
 	}
 }