Bladeren bron

Add supplier dropdown to sale item modal

Alan Lam 3 jaren geleden
bovenliggende
commit
668a548c2b

+ 30 - 0
controllers/suppliers_ajax.php

@@ -0,0 +1,30 @@
+<?php
+
+namespace App;
+
+/**
+ * @var string $action
+ * @var string $id
+ */
+
+$controller = new class() {
+	public function __construct() {
+	}
+
+	public function getProducts(int $id) {
+		$supplier = Supplier::require($id);
+		$output = [];
+		foreach($supplier->getProducts() as $product) {
+			$output[] = $product->jsonSerialize();
+		}
+		Json::success([
+			"products" => $output
+		]);
+	}
+};
+
+switch($action) {
+	case "get-products":
+		$controller->getProducts($id);
+		break;
+}

+ 11 - 1
engine/Product.php

@@ -17,7 +17,7 @@ use Exception;
  * @property string $dts_deleted
  */
 
-class Product extends Model {
+class Product extends Model implements \JsonSerializable {
 
 	protected static $table = "product";
 	protected static $idField = "id";
@@ -63,4 +63,14 @@ class Product extends Model {
 		return number_format($this->price, 2);
 	}
 
+	public function jsonSerialize(): array {
+		return [
+			"id" => (int) $this->id,
+			"supplierId" => (int) $this->supplier_id,
+			"name" => $this->name,
+			"sku" => $this->sku,
+			"type" => (int) $this->type,
+			"price" => $this->price,
+		];
+	}
 }

+ 8 - 0
engine/Supplier.php

@@ -30,6 +30,14 @@ class Supplier extends Model {
 		return self::query([], ["sort" => "name"]);
 	}
 
+	public static function getOptions(): array {
+		$options = [];
+		foreach(self::getAll() as $supplier) {
+			$options[$supplier->id] = $supplier->name;
+		}
+		return $options;
+	}
+
 	// Object methods
 
 	/**

+ 52 - 9
public/js/sale-item-modal.js

@@ -13,15 +13,22 @@ class SaleItemModal {
 		this.$form.on("submit", event => this.onSubmit(event));
 		this.form = this.$form.get(0);
 
-		this.$saleItemIdField = this.$form.find("[name=sale_item_id]");
+		this.$saleItemIdField = this.getField("sale_item_id");
 
-		this.$productDropdown = this.$form.find("[name=product_id]");
+		this.$supplierDropdown = this.getField("supplier_id");
+		this.$supplierDropdown.on("change", () => this.onSupplierChange());
+
+		this.$productDropdown = this.getField("product_id");
 		this.$productDropdown.on("change", event => this.onProductChange());
 
-		this.$quantityField = this.$form.find("[name=quantity]");
+		this.$quantityField = this.getField("quantity");
+
+		this.$unitPriceField = this.getField("unit_price");
 
-		this.$unitPriceField = this.$form.find("[name=unit_price]");
+	}
 
+	getField(name) {
+		return this.$form.find(`[name=${name}]`);
 	}
 
 	// Modal lifecycle
@@ -29,7 +36,7 @@ class SaleItemModal {
 	    const $element = $(event.relatedTarget);
 	    const data = $element.data();
 
-		const { saleNumber, item } = data;
+		const { saleNumber, supplierId, item } = data;
 
 		if(!saleNumber) {
 			console.error("saleNumber not provided.");
@@ -38,19 +45,54 @@ class SaleItemModal {
 
 		this.saleNumber = data.saleNumber;
 
-		if(data.item) {
-			const { item } = data;
+		if(item) {
 			this.$title.text("Update Sale Item");
 
 			this.$saleItemIdField.val(item.id);
-			this.$productDropdown.val(item.productId);
+			this.$supplierDropdown.val(supplierId);
+
+			this.onSupplierChange().then(() => {
+				this.$productDropdown.val(item.productId);
+			});
+
 			this.$quantityField.val(item.quantity);
 			this.$unitPriceField.val(item.unitPrice);
 		}
 		else {
 			this.$title.text("Add Sale Item");
 		}
+	}
+
+	onSupplierChange() {
+		const supplierId = this.$supplierDropdown.val();
+
+		this.clearProducts();
+
+		const deferred = $.Deferred();
+
+		if(!supplierId) {
+			deferred.resolve();
+			return deferred;
+		}
+
+		return $.get(`/suppliers/${supplierId}/get-products`).then(response => {
+			const options = [] = response.products.map(product => {
+				const option = document.createElement("option");
+				option.textContent = product.name;
+				option.value = product.id;
+				option.dataset.price = product.price;
+				return option;
+			});
+			this.$productDropdown.append(options);
+		}).catch(error => {
+			if(error.responseJSON && error.responseJSON.message) {
+				toastr.error(error.responseJSON.message);
+			}
+		});
+	}
 
+	clearProducts() {
+		this.$productDropdown.find("option[value!='']").remove();
 	}
 
 	onProductChange() {
@@ -59,12 +101,13 @@ class SaleItemModal {
 	}
 
 	onShown() {
-		this.$productDropdown.trigger("focus");
+		this.$supplierDropdown.trigger("focus");
 	}
 
 	onHidden() {
 		this.$form.get(0).reset();
 		this.$saleItemIdField.val(null);
+		this.clearProducts();
 	}
 
 	onSubmit(event) {

+ 2 - 0
routes/default.php

@@ -34,6 +34,8 @@ $this->addRoute("/^locations\/(get-options)$/", "locations_ajax", ["action"], ["
 $this->addRoute("/^locations\/$slug_pattern\/update$/", "location_form", ["id"], ["requireUser" => true]);
 
 $this->addRoute("/^suppliers$/", "suppliers", [], ["requireUser" => true]);
+$this->addRoute("/^suppliers\/$id_pattern\/(get-products)$/", "suppliers_ajax", ["id", "action"], ["requireUser" => true]);
+
 $this->addRoute("/^suppliers\/add$/", "supplier_form", [], ["requireUser" => true]);
 $this->addRoute("/^suppliers\/$slug_pattern$/", "supplier", ["id"], ["requireUser" => true]);
 $this->addRoute("/^suppliers\/$slug_pattern\/update$/", "supplier_form", ["id"], ["requireUser" => true]);

+ 18 - 13
views/modals/sale_item.php

@@ -1,37 +1,42 @@
-<?php
+<?php /** @noinspection PhpUnhandledExceptionInspection */
 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
+
+			use App\Helpers\HtmlHelper;
+
 			View::include("modals/header", ["title" => __("Sale Item")]);
 			?>
 			<input type="hidden" name="sale_item_id" value="" />
 
 			<div class="modal-body">
-				<div class="mb-2">
+				<div class="mb-3">
+					<label class="form-label" for="sale-item-supplier-id">
+						<?=htmlspecialchars(__("Supplier"))?>
+					</label>
+					<select class="form-control" name="supplier_id" id="sale-item-supplier-id">
+						<option value=""><?=htmlspecialchars(__("Select Supplier"))?></option>
+						<?php
+						HtmlHelper::renderOptions(Supplier::getOptions());
+						?>
+					</select>
+				</div>
+				<div class="mb-3">
 					<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">
+				<div class="mb-3">
 					<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">
+				<div class="mb-3">
 					<label for="sale-item-unit-price" class="form-label">
 						<?=htmlspecialchars(__("Unit Price"))?>
 					</label>

+ 3 - 3
views/sale_items_section.php

@@ -59,7 +59,7 @@ use NumberFormatter;
 				<?php
 				foreach($items as $item) {
 					$product = $item->getProduct();
-					$supplier_name = $product->getSupplier()->name;
+					$supplier = $product->getSupplier();
 					?>
 					<tr>
 						<td>
@@ -67,7 +67,7 @@ use NumberFormatter;
 							<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 />
+							<small class="text-uppercase text-muted"><?=htmlspecialchars($supplier->name)?></small><br />
 							<?=htmlspecialchars($product->name)?>
 						</td>
 						<td class="text-end">
@@ -80,7 +80,7 @@ use NumberFormatter;
 							<?=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))?>">
+							<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-supplier-id="<?=$supplier->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-sale-item" type="button" data-sale-item-id="<?=$item->id?>">