339 lines
11 KiB
PHP
339 lines
11 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Admin;
|
|
|
|
use App\Enums\PriceType;
|
|
use App\Http\Controllers\Concerns\ParsesDataTableQuery;
|
|
use App\Http\Controllers\Controller;
|
|
use App\Http\Requests\Admin\ProductRequest;
|
|
use App\Models\Category;
|
|
use App\Models\Product;
|
|
use App\Models\ProductPrice;
|
|
use App\Models\ProductVariant;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Http\RedirectResponse;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Inertia\Inertia;
|
|
use Inertia\Response;
|
|
|
|
class ProductController extends Controller
|
|
{
|
|
use ParsesDataTableQuery;
|
|
|
|
public function index(Request $request): Response
|
|
{
|
|
$tableQuery = $this->parseDataTableQuery($request);
|
|
$search = $tableQuery['search'];
|
|
$sort = $tableQuery['sort'];
|
|
$direction = $tableQuery['direction'];
|
|
$isActive = $request->string('is_active')->toString();
|
|
|
|
$query = Product::query()
|
|
->with([
|
|
'categories',
|
|
'variants' => fn ($query) => $query
|
|
->with(['prices' => fn ($query) => $query->orderBy('type')])
|
|
->orderBy('created_at'),
|
|
])
|
|
->when($search !== '', function (Builder $query) use ($search): void {
|
|
$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')
|
|
);
|
|
|
|
$this->applySorting($query, $sort, $direction);
|
|
|
|
$products = $query
|
|
->paginate(10)
|
|
->withQueryString();
|
|
|
|
$rows = $products->getCollection()
|
|
->flatMap(fn (Product $product, int $index) => $this->flattenProductForTable($product, $index, $products->firstItem() ?? 1))
|
|
->values()
|
|
->all();
|
|
|
|
return Inertia::render('admin/products/Index', [
|
|
'rows' => $rows,
|
|
'pagination' => [
|
|
'current_page' => $products->currentPage(),
|
|
'last_page' => $products->lastPage(),
|
|
'per_page' => $products->perPage(),
|
|
'total' => $products->total(),
|
|
'links' => $products->linkCollection()->toArray(),
|
|
],
|
|
'filters' => $this->dataTableFilters($tableQuery, [
|
|
'is_active' => $isActive,
|
|
]),
|
|
]);
|
|
}
|
|
|
|
public function create(): Response
|
|
{
|
|
return Inertia::render('admin/products/Create', [
|
|
'categories' => $this->categoryOptions(),
|
|
'priceTypes' => PriceType::selectOptions(),
|
|
]);
|
|
}
|
|
|
|
public function store(ProductRequest $request): RedirectResponse
|
|
{
|
|
$validated = $request->validated();
|
|
|
|
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 $variantData) {
|
|
$this->createVariant($product, $variantData);
|
|
}
|
|
});
|
|
|
|
Inertia::flash('success', 'Produk berhasil ditambahkan.');
|
|
|
|
return redirect()->route('admin.master.products.index');
|
|
}
|
|
|
|
public function edit(Product $product): Response
|
|
{
|
|
$product->load([
|
|
'categories',
|
|
'variants' => fn ($query) => $query
|
|
->with(['prices' => fn ($query) => $query->orderBy('type')])
|
|
->orderBy('created_at'),
|
|
]);
|
|
|
|
return Inertia::render('admin/products/Edit', [
|
|
'categories' => $this->categoryOptions(),
|
|
'priceTypes' => PriceType::selectOptions(),
|
|
'product' => $this->transformProductForForm($product),
|
|
]);
|
|
}
|
|
|
|
public function update(ProductRequest $request, Product $product): RedirectResponse
|
|
{
|
|
$validated = $request->validated();
|
|
|
|
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(fn (ProductVariant $variant) => $variant->delete());
|
|
|
|
foreach ($validated['variants'] as $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']);
|
|
|
|
continue;
|
|
}
|
|
|
|
$this->createVariant($product, $variantData);
|
|
}
|
|
});
|
|
|
|
Inertia::flash('success', 'Produk berhasil diperbarui.');
|
|
|
|
return redirect()->route('admin.master.products.index');
|
|
}
|
|
|
|
public function toggleStatus(Request $request, Product $product): RedirectResponse
|
|
{
|
|
$validated = $request->validate([
|
|
'is_active' => ['required', 'boolean'],
|
|
]);
|
|
|
|
$product->is_active = $validated['is_active'];
|
|
$product->save();
|
|
|
|
Inertia::flash('success', 'Status produk berhasil diperbarui.');
|
|
|
|
return back();
|
|
}
|
|
|
|
public function destroy(Product $product): RedirectResponse
|
|
{
|
|
DB::transaction(function () use ($product): void {
|
|
$product->variants()->delete();
|
|
$product->categories()->detach();
|
|
$product->delete();
|
|
});
|
|
|
|
Inertia::flash('success', 'Produk berhasil dihapus.');
|
|
|
|
return redirect()->route('admin.master.products.index');
|
|
}
|
|
|
|
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();
|
|
}
|
|
|
|
/**
|
|
* @return list<array{value: int, label: string}>
|
|
*/
|
|
private 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> $variantData
|
|
*/
|
|
private function createVariant(Product $product, array $variantData): ProductVariant
|
|
{
|
|
$variant = $product->variants()->create([
|
|
'name' => $variantData['name'],
|
|
'stock' => $variantData['stock'],
|
|
]);
|
|
|
|
$this->syncVariantPrices($variant, $variantData['prices']);
|
|
|
|
return $variant;
|
|
}
|
|
|
|
/**
|
|
* @param list<array{type: string, price: float|int|string}> $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'],
|
|
],
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @return list<array<string, mixed>>
|
|
*/
|
|
private function flattenProductForTable(Product $product, int $productIndex, int $firstItem): array
|
|
{
|
|
$variants = $product->variants->isNotEmpty()
|
|
? $product->variants
|
|
: collect([null]);
|
|
|
|
$variantCount = $variants->count();
|
|
|
|
return $variants
|
|
->values()
|
|
->map(function ($variant, int $variantIndex) use ($product, $productIndex, $firstItem, $variantCount) {
|
|
return [
|
|
'row_id' => $variant
|
|
? "{$product->id}-{$variant->id}"
|
|
: "{$product->id}-empty",
|
|
'product_id' => $product->id,
|
|
'product_name' => $product->name,
|
|
'categories' => $product->categories
|
|
->map(fn (Category $category) => [
|
|
'id' => $category->id,
|
|
'name' => $category->name,
|
|
])
|
|
->values()
|
|
->all(),
|
|
'is_active' => $product->is_active,
|
|
'is_first_variant' => $variantIndex === 0,
|
|
'variant_count' => $variantCount,
|
|
'product_row_number' => $firstItem + $productIndex,
|
|
'variant_id' => $variant?->id,
|
|
'variant_name' => $variant?->name,
|
|
'stock' => $variant?->stock,
|
|
'prices' => $variant
|
|
? $variant->prices
|
|
->map(fn (ProductPrice $price) => [
|
|
'type' => $price->type->value,
|
|
'type_label' => $price->type->label(),
|
|
'price' => $price->price,
|
|
'price_formatted' => $this->formatPrice($price->price),
|
|
])
|
|
->values()
|
|
->all()
|
|
: [],
|
|
];
|
|
})
|
|
->all();
|
|
}
|
|
|
|
/**
|
|
* @return array<string, mixed>
|
|
*/
|
|
private function transformProductForForm(Product $product): array
|
|
{
|
|
return [
|
|
'id' => $product->id,
|
|
'name' => $product->name,
|
|
'description' => $product->description,
|
|
'category_ids' => $product->categories->pluck('id')->all(),
|
|
'variants' => $product->variants
|
|
->map(fn (ProductVariant $variant) => [
|
|
'id' => $variant->id,
|
|
'name' => $variant->name,
|
|
'stock' => $variant->stock,
|
|
'prices' => collect(PriceType::cases())
|
|
->mapWithKeys(function (PriceType $type) use ($variant) {
|
|
$price = $variant->prices->firstWhere('type', $type);
|
|
|
|
return [
|
|
$type->value => $price ? (string) (int) $price->price : '',
|
|
];
|
|
})
|
|
->all(),
|
|
])
|
|
->values()
|
|
->all(),
|
|
];
|
|
}
|
|
|
|
private function formatPrice(float|string $price): string
|
|
{
|
|
return 'Rp '.number_format((float) $price, 0, ',', '.');
|
|
}
|
|
}
|