Skip to content

Commit

Permalink
Update remaining quantity when a sale id done/canceled
Browse files Browse the repository at this point in the history
  • Loading branch information
froozeify committed Jul 21, 2024
1 parent 48b3a92 commit fe79bcc
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/EventSubscriber/Doctrine/SaleSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
use App\Entity\Member;
use App\Entity\Sale;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsEntityListener;
use Doctrine\ORM\Event\PostPersistEventArgs;
use Doctrine\ORM\Event\PostRemoveEventArgs;
use Doctrine\ORM\Event\PrePersistEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\Persistence\Event\LifecycleEventArgs;
Expand All @@ -27,10 +29,46 @@ public function prePersist(Sale $sale, PrePersistEventArgs $args): void {
$this->autoSetFields($sale, $args);
}

public function postPersist(Sale $sale, PostPersistEventArgs $args): void {
$objectManager = $args->getObjectManager();

// We update the inventory item remaining stock
foreach ($sale->getSalePurchasedItems() as $purchasedItem) {
$inventoryItem = $purchasedItem->getItem();
if (!$inventoryItem || is_null($inventoryItem->getQuantity())) {
continue;
}
$inventoryItem->setQuantity($inventoryItem->getQuantity() - ($purchasedItem->getQuantity() * $inventoryItem->getSellingQuantity()));

// No more in stock we don't go negative
if ($inventoryItem->getQuantity() < 0) {
$inventoryItem->setQuantity(0);
}

$objectManager->persist($inventoryItem);
}
$objectManager->flush();
}

public function preUpdate(Sale $sale, PreUpdateEventArgs $args): void {
$this->autoSetFields($sale, $args);
}

public function postRemove(Sale $sale, PostRemoveEventArgs $args): void {
// A sale is canceled, we restock the items
$objectManager = $args->getObjectManager();
foreach ($sale->getSalePurchasedItems() as $purchasedItem) {
$inventoryItem = $purchasedItem->getItem();
if (!$inventoryItem || is_null($inventoryItem->getQuantity())) {
continue;
}

$inventoryItem->setQuantity($inventoryItem->getQuantity() + ($purchasedItem->getQuantity() * $inventoryItem->getSellingQuantity()));
$objectManager->persist($inventoryItem);
}
$objectManager->flush();
}

public function autoSetFields(Sale $sale, LifecycleEventArgs $args): void {
if ($sale->getPrice()) {
return;
Expand Down

0 comments on commit fe79bcc

Please sign in to comment.