318 lines
10 KiB
PHP
318 lines
10 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Master;
|
|
|
|
use App\Models\Category;
|
|
use App\Models\Product;
|
|
use App\Models\ProductPrice;
|
|
use App\Models\ProductVariant;
|
|
use App\Services\Media\MediaService;
|
|
use App\Support\Media\MediaPresenter;
|
|
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class ProductService
|
|
{
|
|
private const MAX_VARIANT_IMAGES = 5;
|
|
|
|
public function __construct(
|
|
private readonly MediaService $mediaService,
|
|
) {}
|
|
|
|
/**
|
|
* @return list<array{
|
|
* id: int,
|
|
* name: string,
|
|
* edit_url: string,
|
|
* variants: list<array{
|
|
* id: int,
|
|
* name: string,
|
|
* stock_formatted: string,
|
|
* images: list<array<string, mixed>>,
|
|
* }>,
|
|
* }>
|
|
*/
|
|
public function outOfStockGroups(): array
|
|
{
|
|
return $this->inventoryAlertGroups(
|
|
fn (ProductVariant $variant): bool => $variant->stock <= 0,
|
|
);
|
|
}
|
|
|
|
/**
|
|
* @return list<array{
|
|
* id: int,
|
|
* name: string,
|
|
* edit_url: string,
|
|
* variants: list<array{
|
|
* id: int,
|
|
* name: string,
|
|
* stock_formatted: string,
|
|
* images: list<array<string, mixed>>,
|
|
* }>,
|
|
* }>
|
|
*/
|
|
public function stockWarningGroups(): array
|
|
{
|
|
return $this->inventoryAlertGroups(function (ProductVariant $variant): bool {
|
|
if ($variant->stock <= 0) {
|
|
return false;
|
|
}
|
|
|
|
return $variant->stock < ProductVariant::minStock();
|
|
});
|
|
}
|
|
|
|
/**
|
|
* @return list<array{
|
|
* id: int,
|
|
* name: string,
|
|
* edit_url: string,
|
|
* variants: list<array{
|
|
* id: int,
|
|
* name: string,
|
|
* stock_formatted: string,
|
|
* images: list<array<string, mixed>>,
|
|
* }>,
|
|
* }>
|
|
*/
|
|
private function inventoryAlertGroups(callable $filter): array
|
|
{
|
|
return ProductVariant::query()
|
|
->with(['product', 'media'])
|
|
->whereHas('product', fn (Builder $query) => $query->where('is_active', true))
|
|
->get()
|
|
->filter($filter)
|
|
->sortBy([
|
|
fn (ProductVariant $variant) => $variant->product->name,
|
|
fn (ProductVariant $variant) => $variant->name,
|
|
])
|
|
->groupBy('product_id')
|
|
->map(function ($variants, $productId) {
|
|
$product = $variants->first()->product;
|
|
|
|
return [
|
|
'id' => (int) $productId,
|
|
'name' => $product->name,
|
|
'edit_url' => route('admin.master.products.edit', $productId),
|
|
'variants' => $variants->map(function (ProductVariant $variant): array {
|
|
return [
|
|
'id' => $variant->id,
|
|
'name' => $variant->name,
|
|
'stock_formatted' => number_format($variant->stock, 0, ',', '.').' pcs',
|
|
'images' => MediaPresenter::collection($variant, 'images'),
|
|
];
|
|
})->values()->all(),
|
|
];
|
|
})
|
|
->values()
|
|
->all();
|
|
}
|
|
|
|
/**
|
|
* @param array{search: string, sort: string, direction: 'asc'|'desc'} $tableQuery
|
|
*/
|
|
public function paginateForIndex(array $tableQuery, string $isActive, string $categoryId = ''): LengthAwarePaginator
|
|
{
|
|
$query = Product::query()
|
|
->with([
|
|
'categories',
|
|
'variants' => fn ($query) => $query
|
|
->with(['prices' => fn ($query) => $query->orderBy('type'), 'media'])
|
|
->orderBy('created_at'),
|
|
])
|
|
->when($tableQuery['search'] !== '', function (Builder $query) use ($tableQuery): void {
|
|
$search = $tableQuery['search'];
|
|
$query->where(function (Builder $query) use ($search): void {
|
|
$query->where('name', 'like', "%{$search}%")
|
|
->orWhere('slug', 'like', "%{$search}%")
|
|
->orWhere('description', 'like', "%{$search}%")
|
|
->orWhereHas('categories', fn (Builder $query) => $query->where('name', 'like', "%{$search}%"))
|
|
->orWhereHas('variants', fn (Builder $query) => $query->where('name', 'like', "%{$search}%"));
|
|
});
|
|
})
|
|
->when(
|
|
$isActive !== '',
|
|
fn (Builder $query) => $query->where('is_active', $isActive === '1')
|
|
)
|
|
->when(
|
|
$categoryId !== '',
|
|
fn (Builder $query) => $query->whereHas('categories', fn (Builder $query) => $query->where('categories.id', $categoryId))
|
|
);
|
|
|
|
$this->applySorting($query, $tableQuery['sort'], $tableQuery['direction']);
|
|
|
|
return $query
|
|
->paginate(10)
|
|
->withQueryString()
|
|
->through(function (Product $product) {
|
|
$product->variants->each(function (ProductVariant $variant): void {
|
|
$variant->setAttribute(
|
|
'images',
|
|
MediaPresenter::collection($variant, 'images'),
|
|
);
|
|
});
|
|
|
|
return $product;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* @return list<array{value: int, label: string}>
|
|
*/
|
|
public function categoryOptions(): array
|
|
{
|
|
return Category::query()
|
|
->orderBy('name')
|
|
->get(['id', 'name'])
|
|
->map(fn (Category $category) => [
|
|
'value' => $category->id,
|
|
'label' => $category->name,
|
|
])
|
|
->all();
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $validated
|
|
*/
|
|
public function create(array $validated): void
|
|
{
|
|
DB::transaction(function () use ($validated): void {
|
|
$product = Product::create([
|
|
'name' => $validated['name'],
|
|
'description' => $validated['description'] ?? null,
|
|
'is_active' => true,
|
|
]);
|
|
|
|
$product->categories()->sync($validated['category_ids']);
|
|
|
|
foreach ($validated['variants'] as $index => $variantData) {
|
|
$this->createVariant($product, $variantData, $index);
|
|
}
|
|
});
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $validated
|
|
*/
|
|
public function update(Product $product, array $validated): void
|
|
{
|
|
DB::transaction(function () use ($validated, $product): void {
|
|
$product->name = $validated['name'];
|
|
$product->description = $validated['description'] ?? null;
|
|
$product->save();
|
|
|
|
$product->categories()->sync($validated['category_ids']);
|
|
|
|
$submittedVariantIds = collect($validated['variants'])
|
|
->pluck('id')
|
|
->filter()
|
|
->map(fn ($id) => (int) $id)
|
|
->all();
|
|
|
|
$product->variants()
|
|
->whereNotIn('id', $submittedVariantIds)
|
|
->get()
|
|
->each(function (ProductVariant $variant): void {
|
|
$variant->clearMediaCollection('images');
|
|
$variant->delete();
|
|
});
|
|
|
|
foreach ($validated['variants'] as $index => $variantData) {
|
|
if (! empty($variantData['id'])) {
|
|
$variant = $product->variants()->findOrFail($variantData['id']);
|
|
$variant->name = $variantData['name'];
|
|
$variant->stock = $variantData['stock'];
|
|
$variant->save();
|
|
$this->syncVariantPrices($variant, $variantData['prices']);
|
|
$this->syncVariantImages($variant, $variantData, $index);
|
|
|
|
continue;
|
|
}
|
|
|
|
$this->createVariant($product, $variantData, $index);
|
|
}
|
|
});
|
|
}
|
|
|
|
public function toggleStatus(Product $product, bool $isActive): void
|
|
{
|
|
$product->is_active = $isActive;
|
|
$product->save();
|
|
}
|
|
|
|
public function delete(Product $product): void
|
|
{
|
|
DB::transaction(function () use ($product): void {
|
|
$product->variants()->each(function (ProductVariant $variant): void {
|
|
$variant->clearMediaCollection('images');
|
|
});
|
|
$product->variants()->delete();
|
|
$product->categories()->detach();
|
|
$product->delete();
|
|
});
|
|
}
|
|
|
|
private function applySorting(Builder $query, string $sort, string $direction): void
|
|
{
|
|
if (in_array($sort, ['name', 'slug', 'is_active'], true)) {
|
|
$query->orderBy($sort, $direction);
|
|
|
|
return;
|
|
}
|
|
|
|
$query->latest();
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $variantData
|
|
*/
|
|
private function createVariant(Product $product, array $variantData, int $index): ProductVariant
|
|
{
|
|
$variant = $product->variants()->create([
|
|
'name' => $variantData['name'],
|
|
'stock' => $variantData['stock'],
|
|
]);
|
|
|
|
$this->syncVariantPrices($variant, $variantData['prices']);
|
|
$this->syncVariantImages($variant, $variantData, $index);
|
|
|
|
return $variant;
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $variantData
|
|
*/
|
|
private function syncVariantImages(ProductVariant $variant, array $variantData, int $index): void
|
|
{
|
|
$this->mediaService->syncCollection(
|
|
$variant,
|
|
'images',
|
|
$variantData['images'] ?? null,
|
|
$variantData['remove_media_ids'] ?? null,
|
|
self::MAX_VARIANT_IMAGES,
|
|
required: true,
|
|
errorKey: "variants.{$index}.images",
|
|
);
|
|
}
|
|
|
|
/**
|
|
* @param list<array{type: string, price: int}> $prices
|
|
*/
|
|
private function syncVariantPrices(ProductVariant $variant, array $prices): void
|
|
{
|
|
foreach ($prices as $priceData) {
|
|
ProductPrice::updateOrCreate(
|
|
[
|
|
'variant_id' => $variant->id,
|
|
'type' => $priceData['type'],
|
|
],
|
|
[
|
|
'price' => $priceData['price'],
|
|
],
|
|
);
|
|
}
|
|
}
|
|
}
|