Skip to content

Commit

Permalink
change order of steps when saving order
Browse files Browse the repository at this point in the history
set order id and unit price of each line item before validating line item
  • Loading branch information
creme332 committed May 22, 2024
1 parent 69239d8 commit 48b2d7c
Showing 1 changed file with 34 additions and 19 deletions.
53 changes: 34 additions & 19 deletions src/models/Order.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,20 +122,8 @@ public function save(): bool
$update_stock_stm = $conn->prepare($query);

foreach ($this->line_items as $line_item) {
$line_item_errors = $line_item->validate();

if (!empty($line_item_errors)) {
// line item contains invalid attributes
$conn->rollBack();
$conn = null;

$error_message = "Invalid line item:" . json_encode($line_item->toArray());
$error_message .= " Errors: " . json_encode($line_item_errors);

throw new Exception(
$error_message
);
}
// set order ID of line item
$line_item->setOrderID($new_order_id);

// fetch product corresponding to line item
$product = Product::getByID($line_item->getProductID());
Expand All @@ -147,22 +135,49 @@ public function save(): bool
throw new Exception("Product with ID " . $line_item->getProductID() . " does not exist");
}

// set true unit price of line item
$line_item->setUnitPrice($product->getPrice());

// get stock level for current product
$stock_level = $store->getProductStock($product->getProductID());

if ($line_item->getQuantity() > $stock_level) {
// store does not have enough stock
$conn->rollBack();
$conn = null;

$error_message = <<< EOL
Store with ID $this->store_id has insufficient stock ($stock_level) for the following line item:
Product ID = {$line_item->getProductID()} and quantity = {$line_item->getQuantity()}.
EOL;

throw new Exception($error_message);
}

// validate line item
$line_item_errors = $line_item->validate();
if (!empty($line_item_errors)) {
// line item contains invalid attributes
$conn->rollBack();
$conn = null;

$line_item_info = json_encode($line_item->toArray());
$line_item_errors = json_encode($line_item_errors);

$error_message = <<< EOL
Invalid line item:
$line_item_info
Errors:
$line_item_errors
EOL;

throw new Exception(
"Store with ID " . $this->store_id
. " has insufficient stock for product " . $line_item->getProductID()
$error_message
);
}

// insert into order_product table
$line_item->setOrderID($new_order_id);
$line_item->setUnitPrice($product->getPrice());
// insert line item into order_product table

$success = $insert_line_item_stm->execute($line_item->toArray());
if (!$success) {
Expand Down

0 comments on commit 48b2d7c

Please sign in to comment.