<?php
namespace App\Entity;
use App\Service\Helper\DateTimeHelper;
use DateTime;
use Doctrine\ORM\Mapping as ORM;
use Exception;
/**
* @ORM\Table(name="products__items_transactions", uniqueConstraints={
* @ORM\UniqueConstraint(columns={"invoice_product_id", "reason"})
* })
* @ORM\Entity(repositoryClass="App\Repository\ItemTransactionRepository")
*/
class ItemTransaction
{
const REASON_CONFIRM_INVOICE = 'confirm_invoice';
const REASON_REMOVE_INVOICE = 'remove_invoice';
const REASON_CONFIRM_ORDER = 'confirm_order';
const REASON_REFUND_ORDER_ELEMENT = 'refund_order_element';
use IdTrait;
/**
* @ORM\Column(name="created_at", type="datetime", nullable=false)
*/
private DateTime $createdAt;
/**
* @ORM\ManyToOne(targetEntity="Item")
* @ORM\JoinColumn(name="item_id", referencedColumnName="id", nullable=false, onDelete="CASCADE")
*/
private Item $item;
/**
* @ORM\ManyToOne(targetEntity="InvoiceProduct")
* @ORM\JoinColumn(name="invoice_product_id", referencedColumnName="id", nullable=true, onDelete="SET NULL")
*/
private ?InvoiceProduct $invoiceProduct;
/**
* @ORM\ManyToOne(targetEntity="OrderElement")
* @ORM\JoinColumn(name="order_element_id", referencedColumnName="id", nullable=true, onDelete="SET NULL")
*/
private ?OrderElement $orderElement;
/**
* @ORM\Column(name="init_stock", type="integer")
*/
private int $initStock;
/**
* @ORM\Column(name="amount", type="integer")
*/
private int $amount = 0;
/**
* @ORM\Column(name="new_stock", type="integer")
*/
private int $newStock;
/**
* @ORM\Column(name="reason", type="string")
*/
private string $reason;
/**
* @throws Exception
*/
public function __construct(Item $item, string $reason, ?InvoiceProduct $invoiceProduct, ?OrderElement $orderElement)
{
$this->item = $item;
$this->reason = $reason;
$this->initStock = $item->getStock();
$this->newStock = $item->getStock();
if($invoiceProduct) {
if ($reason === self::REASON_CONFIRM_INVOICE) $this->newStock += $invoiceProduct->getQuantity();
elseif ($reason === self::REASON_REMOVE_INVOICE) $this->newStock -= $invoiceProduct->getQuantity();
$this->amount = $invoiceProduct->getQuantity();
}
$this->invoiceProduct = $invoiceProduct;
if($orderElement) {
if ($reason === self::REASON_CONFIRM_ORDER) $this->newStock -= $orderElement->getQuantity();
elseif ($reason === self::REASON_REFUND_ORDER_ELEMENT) $this->newStock += $orderElement->getQuantity();
$this->amount = $orderElement->getQuantity();
}
$this->orderElement = $orderElement;
$this->createdAt = DateTimeHelper::getNowDateTime();
}
public function getItem(): Item
{
return $this->item;
}
public function getNewStock(): int
{
return $this->newStock;
}
public function getReason(): string
{
return $this->reason;
}
public function getOrderElement(): ?OrderElement
{
return $this->orderElement;
}
}