Skip to content

Commit

Permalink
[ADD] Add to Cart.
Browse files Browse the repository at this point in the history
  • Loading branch information
Seiger committed Dec 16, 2024
1 parent f588a79 commit ba8f88a
Show file tree
Hide file tree
Showing 11 changed files with 278 additions and 248 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ of Evolution CMS for seamless and efficient **online commerce**.
- [x] sCommerceAfterProductSave.
- [x] sCommerceAfterProductContentSave.
- [x] sCommerceAfterProductDuplicate.
- [x] Javascript events.
- [x] sCommerceAddedToCart.
- [x] Multi-currency Support (ISO 4217).
- [ ] Integration with Payment Systems.
- [ ] Integration with Warehouses.
Expand Down
2 changes: 2 additions & 0 deletions docs/pages/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ of Evolution CMS for seamless and efficient **online commerce**.
- [x] sCommerceAfterProductSave.
- [x] sCommerceAfterProductContentSave.
- [x] sCommerceAfterProductDuplicate.
- [x] Javascript events.
- [x] sCommerceAddedToCart.
- [x] Multi-currency Support (ISO 4217).
- [ ] Integration with Payment Systems.
- [ ] Integration with Warehouses.
Expand Down
3 changes: 3 additions & 0 deletions lang/en/global.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
"management_base_functionality" => "Management of basic functionality",
"management_product_functionality" => "Product functionality management",
"manager_cannot_change" => "the manager cannot change",
"managing_cart_functionality" => "Managing the cart functionality",
"message" => "Message",
"new_attribute" => "New Attribute",
"new_product" => "New product",
Expand Down Expand Up @@ -123,6 +124,8 @@
"prodattributes_help" => "List of product attributes.",
"prodattributes_icon" => "fa fas fa-paperclip",
"product" => "Product",
"product_attributes_to_display" => "Product attributes to display",
"product_attributes_to_display_help" => "A list of product attributes to display in the cart when returning product details or a product list.",
"product_help" => "The main parameters of the product.",
"product_icon" => "fa fas fa-barcode",
"product_link" => "Link to the product",
Expand Down
3 changes: 3 additions & 0 deletions lang/ru/global.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
"management_base_functionality" => "Управление базовым функционалом",
"management_product_functionality" => "Управление функционалом товара",
"manager_cannot_change" => "менеджер не может изменять",
"managing_cart_functionality" => "Управление функциональностью корзины",
"message" => "Сообщение",
"new_attribute" => "Новый атрибут",
"new_product" => "Новый товар",
Expand Down Expand Up @@ -123,6 +124,8 @@
"prodattributes_help" => "Список атрибутов товара.",
"prodattributes_icon" => "fa fas fa-paperclip",
"product" => "Товар",
"product_attributes_to_display" => "Атрибуты продукта для отображения",
"product_attributes_to_display_help" => "Список атрибутов продукта, которые необходимо выводить в корзине при возврате деталей продукта или списка продуктов.",
"product_help" => "Основные характеристики товара.",
"product_icon" => "fa fas fa-barcode",
"product_link" => "Ссылка на товар",
Expand Down
3 changes: 3 additions & 0 deletions lang/uk/global.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
"management_base_functionality" => "Керування базовим функціоналом",
"management_product_functionality" => "Керування функціоналом товару",
"manager_cannot_change" => "менеджер не може змінювати",
"managing_cart_functionality" => "Керування функціональністю кошика",
"message" => "Повідомлення",
"new_attribute" => "Новий атрибут",
"new_product" => "Новий товар",
Expand Down Expand Up @@ -123,6 +124,8 @@
"prodattributes_help" => "Список атрибутів товара.",
"prodattributes_icon" => "fa fas fa-paperclip",
"product" => "Товар",
"product_attributes_to_display" => "Атрибути продукту для відображення",
"product_attributes_to_display_help" => "Список атрибутів продукта, які потрібно виводити в кошику при поверненні деталей продукта чи списка продуктів.",
"product_help" => "Основні параметри товара.",
"product_icon" => "fa fas fa-barcode",
"product_link" => "Посилання на товар",
Expand Down
2 changes: 1 addition & 1 deletion src/Controllers/sCommerceController.php
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ public function updateCurrenciesConfigs(): bool
*/
public function updateFileConfigs(): bool
{
$filters = ['basic', 'constructor', 'currencies', 'product', 'products'];
$filters = ['basic', 'cart', 'constructor', 'currencies', 'product', 'products'];
$all = request()->all();

if (isset($all['main_product_constructors']) && is_array($all['main_product_constructors']) && count($all['main_product_constructors'])) {
Expand Down
95 changes: 46 additions & 49 deletions src/sCart.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,17 @@
class sCart
{
protected $cartData;
protected $productDetails = [
'id',
'title',
'link',
'coverSrc',
'category',
'sku',
'quantity',
'price',
'specialPrice'
];

public function __construct()
{
Expand All @@ -20,7 +31,7 @@ public function __construct()
*
* @return array An array of items, each with product ID and quantity.
*/
public function getItems(): array
/*public function getItems(): array
{
$items = [];
Expand All @@ -35,7 +46,7 @@ public function getItems(): array
}
return $items;
}
}*/

/**
* Retrieve detailed information about items in the cart.
Expand All @@ -46,7 +57,7 @@ public function getItems(): array
* @return array An array of detailed items, each including the product ID, quantity,
* and additional details such as product attributes and their values.
*/
public function getDetailedItems(): array
/*public function getDetailedItems(): array
{
$items = [];
Expand All @@ -65,7 +76,7 @@ public function getDetailedItems(): array
}
return $items;
}
}*/

/**
* Add a product to the cart.
Expand All @@ -83,9 +94,9 @@ public function addProduct(int $productId = 0, int $optionId = 0, int $quantity
$quantity = max(request()->integer('quantity'), 1);
}

$product = $this->getProductDetails($productId);
$product = sCommerce::getProduct($productId);

if (!$product) {
if (!$product || !$product->id) {
Log::warning('sCart - ' . __('sCommerce::global.product_with_id_not_found', ['id' => $productId]));

return [
Expand Down Expand Up @@ -114,16 +125,12 @@ public function addProduct(int $productId = 0, int $optionId = 0, int $quantity
$this->cartData[$productId][$optionId] = ($quantity == 1 ? 1 : $quantity);
$this->saveCartData();

$totalCartSum = $this->getTotalCartSum();

return [
'success' => true,
'message' => "Product with ID {$productId} added to Cart.",
'productId' => $productId,
'product' => $this->getProductFields($product),
'quantity' => $this->cartData[$productId][$optionId],
'totalCartSum' => $totalCartSum,
'totalCartSumFormatted' => sCommerce::convertPrice($totalCartSum),
'miniCart' => $this->getMiniCart(),
];
}

Expand All @@ -133,11 +140,11 @@ public function addProduct(int $productId = 0, int $optionId = 0, int $quantity
* @param int $productId The ID of the product to remove.
* @return void
*/
public function removeProduct(int $productId): void
/*public function removeProduct(int $productId): void
{
unset($this->cartData[$productId]);
$this->saveCartData();
}
}*/

/**
* Update the quantity of a product in the cart.
Expand All @@ -146,34 +153,40 @@ public function removeProduct(int $productId): void
* @param int $quantity The new quantity of the product.
* @return void
*/
public function updateQuantity(int $productId, int $quantity): void
/*public function updateQuantity(int $productId, int $quantity): void
{
if (isset($this->cartData[$productId])) {
$this->cartData[$productId]['quantity'] = $quantity;
$this->saveCartData();
}
}
}*/

/**
* Get the total sum of items in the cart in current Currency.
*
* @return float The total sum of items in the cart.
* @return array The total sum and items in the cart.
*/
public function getTotalCartSum(): float
public function getMiniCart(): array
{
$total = 0;
$totalSum = 0;
$items = [];
$productIds = array_keys($this->cartData);
$products = sCommerce::getProducts($productIds);

foreach ($products as $product) {
foreach ($this->cartData[$product->id] as $optionId => $quantity) {
$items[] = $this->getProductFields($product);
$price = $product->price_special > 0 ? $product->price_special : $product->price_regular;
$price = sCommerce::convertPriceNumber($price, $product->currency, sCommerce::currentCurrency());
$total += $price * $quantity;
$totalSum += $price * $quantity;
}
}

return $total;
$cart['totalSum'] = $totalSum;
$cart['totalSumFormatted'] = sCommerce::convertPrice($totalSum);
$cart['items'] = $items;

return $cart;
}

/**
Expand All @@ -200,21 +213,6 @@ protected function saveCartData(): void
$_SESSION['sCart'] = $this->cartData;
}

/**
* Get details of a product by its ID.
*
* This method retrieves detailed information about a product from the database.
*
* @param int $productId The ID of the product.
* @throws \UnexpectedValueException If the returned object is not a product.
*/
private function getProductDetails(int $productId): ?sProduct
{
$fields = ['id', 'title', 'link', 'coverSrc', 'category', 'sku', 'quantity', 'price', 'specialPrice'];
$product = sCommerce::getProduct($productId);
return $product && $product->id ? $product : null;
}

/**
* Get details of a product by its ID with selected fields.
*
Expand All @@ -225,18 +223,17 @@ private function getProductDetails(int $productId): ?sProduct
*/
private function getProductFields(object $product): ?array
{
$fields = [
'id',
'title',
'link',
'coverSrc',
'category',
'sku',
'quantity',
'price',
'specialPrice'
];
return $product->only($fields);
$attributes = [];
if (count($attributesDisplay = sCommerce::config('cart.product_attributes_display', []))) {
foreach ($attributesDisplay as $attrDisplay) {
$ad = $product->attribute($attrDisplay);
if ($ad) {
$attributes[$ad['alias']] = array_diff($ad->only(['id', 'position', 'type', 'alias', 'title', 'value', 'code', 'label']), [null]);
}
}
}

return array_merge($product->only($this->productDetails), $attributes);
}

/**
Expand All @@ -246,7 +243,7 @@ private function getProductFields(object $product): ?array
* @param array $attributes The attributes associated with the product in the cart.
* @return array An array of attributes and their values for the product.
*/
private function getProductAttributes(int $productId, array $attributes): array
/*private function getProductAttributes(int $productId, array $attributes): array
{
$productAttributes = [];
Expand All @@ -264,5 +261,5 @@ private function getProductAttributes(int $productId, array $attributes): array
}
return $productAttributes;
}
}*/
}
18 changes: 18 additions & 0 deletions views/partials/settingsCartConfiguration.blade.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
@php use Seiger\sCommerce\Models\sAttribute; @endphp
<h3 class="sectionTrans">
@lang('sCommerce::global.managing_cart_functionality')
</h3>
<div class="row form-row">
<div class="col-auto">
<label for="cart__product_attributes_display">@lang('sCommerce::global.product_attributes_to_display')</label>
<i class="fa fa-question-circle" data-tooltip="@lang('sCommerce::global.product_attributes_to_display_help')"></i>
</div>
<div class="col">
<select id="cart__product_attributes_display" class="form-control select2" name="cart__product_attributes_display[]" multiple onchange="documentDirty=true;">
@foreach(sAttribute::all() as $item)
<option value="{{$item->alias}}" @if(in_array($item->alias, sCommerce::config('cart.product_attributes_display', []))) selected @endif>{{$item->text->pagetitle}}</option>
@endforeach
</select>
</div>
</div>
<div class="split my-3"></div>
Loading

0 comments on commit ba8f88a

Please sign in to comment.