File: D:/HostingSpaces/SBogers10/shop.komma.nl/app/Products/Product/ProductModelService.php
<?php declare(strict_types=1);
namespace App\Products\Product;
use App\Catalog\CatalogService;
use App\Finance\RoundingService;
use App\Vat\Models\VatScenario;
use App\Vat\VatScenarioEnum;
use App\Vat\VatService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Komma\KMS\Core\Attributes\Attribute;
use Komma\KMS\Core\ModelService;
use App\Orders\Models\Order;
use App\Orders\Product\OrderedProduct;
use App\Stock\StockService;
class ProductModelService extends ModelService
{
/** @var CatalogService $catalogService */
private $catalogService;
public function __construct()
{
$this->setModelClassName(Product::class);
parent::__construct();
$this->catalogService = app(CatalogService::class);
}
/**
* Makes a single orderedProduct based of a product
*
* @param Product $product
* @param Order $order
* @param int $quantity
* @return OrderedProduct
*/
public static function createOrderedProductFromProduct(Product $product, Order $order, int $quantity)
{
if(!$order->exists) throw new \InvalidArgumentException('The order does not exists. Make sure the order exists first by saving it. Else we cannot save ordered products.');
$vatService = new VatService();
//Fetch all attributes except id, and...
$attributes = $product->getAttributes();
unset($attributes['id']);
//Determine the products name and also add it to the attributes
$attributes['name'] = $product->translation->name ?? null;
$attributes['vat_percentage'] = $vatService->getVatScenarioByEnumValue($product->vat_scenario_enum)->percentage;
//...put those into a new ordered product
$orderedProduct = new OrderedProduct($attributes);
$orderedProduct->quantity = $quantity;
$orderedProduct->product()->associate($product);
//Attach the ordered product to the order.
$order->orderedProducts()->save($orderedProduct);
return $orderedProduct;
}
public function save(Model $model, Collection $attributes = null): Model
{
$model = parent::save($model, $attributes);
$attributes->each(function(Attribute $attribute) use(&$model, &$keys) {
if($attribute->getsValueFromReference() == 'price') {
[$price, $vat_scenario_enum] = explode('|', $attribute->getValue());
$model->price = RoundingService::Round((float) $price); //Rounds fractions of cents. Price already is in cents.
$model->vat_scenario_enum = $vat_scenario_enum;
$model->save();
}
});
return $model;
}
public function load(Model $model, Collection $attributes = null): Collection
{
$attributes = parent::load($model, $attributes);
$attributes->each(function(Attribute $attribute) use(&$model, &$keys) {
if($attribute->getsValueFromReference() == 'price') {
$attribute->setValue($model->price.'|'.$model->vat_scenario_enum);
}
});
return $attributes;
}
public function destroyForModel(Model $model): Model
{
$this->catalogService->destroyForModel($model);
return $model;
}
}