91 lines
2.4 KiB
PHP
91 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\Category;
|
|
use App\Models\Product;
|
|
use Illuminate\Support\Collection;
|
|
|
|
class CategoryService
|
|
{
|
|
/** دستههایی که صریحاً غیرفعال شدهاند — بقیه (بدون ردیف) نمایش داده میشوند */
|
|
public function hiddenCategoryNames(): Collection
|
|
{
|
|
return Category::query()
|
|
->where('active', 0)
|
|
->pluck('name');
|
|
}
|
|
|
|
public function filterProductsByVisibleCategories(Collection $products): Collection
|
|
{
|
|
$hidden = $this->hiddenCategoryNames();
|
|
if ($hidden->isEmpty()) {
|
|
return $products;
|
|
}
|
|
|
|
return $products->filter(function ($product) use ($hidden) {
|
|
$group = trim((string) ($product->group_type ?? ''));
|
|
if ($group === '') {
|
|
return true;
|
|
}
|
|
|
|
if (! Category::where('name', $group)->exists()) {
|
|
return true;
|
|
}
|
|
|
|
return ! $hidden->contains($group);
|
|
})->values();
|
|
}
|
|
|
|
public function sortProductsForStore(Collection $products): Collection
|
|
{
|
|
return $products
|
|
->sort(function ($a, $b) {
|
|
$aInStock = (int) ($a->inventory ?? 0) > 0 ? 0 : 1;
|
|
$bInStock = (int) ($b->inventory ?? 0) > 0 ? 0 : 1;
|
|
if ($aInStock !== $bInStock) {
|
|
return $aInStock <=> $bInStock;
|
|
}
|
|
|
|
return ((int) ($b->inventory ?? 0)) <=> ((int) ($a->inventory ?? 0));
|
|
})
|
|
->values();
|
|
}
|
|
|
|
public function syncFromProducts(): int
|
|
{
|
|
$names = Product::query()
|
|
->whereNotNull('group_type')
|
|
->where('group_type', '!=', '')
|
|
->distinct()
|
|
->orderBy('group_type')
|
|
->pluck('group_type');
|
|
|
|
$created = 0;
|
|
$order = (int) Category::max('sort_order');
|
|
|
|
foreach ($names as $name) {
|
|
$name = trim((string) $name);
|
|
if ($name === '') {
|
|
continue;
|
|
}
|
|
|
|
if (Category::where('name', $name)->exists()) {
|
|
continue;
|
|
}
|
|
|
|
$order++;
|
|
Category::create([
|
|
'name' => $name,
|
|
'active' => 1,
|
|
'show_in_filter' => 1,
|
|
'show_in_select' => 1,
|
|
'sort_order' => $order,
|
|
]);
|
|
$created++;
|
|
}
|
|
|
|
return $created;
|
|
}
|
|
}
|