store 5
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user