store/app/Services/System/HomepageService.php

83 lines
3.0 KiB
PHP

<?php
namespace App\Services\System;
use App\Models\Category;
use App\Models\Product;
use App\Models\SystemConfiguration;
use App\Services\Concerns\CachesQuery;
use App\Services\Manage\CuttingResultPriceResolver;
use App\Services\System\Setting\HomepageSettingService;
use App\Settings\SocialMediaSettings;
use App\Settings\SystemSettings;
use App\Support\Media\MediaPresenter;
class HomepageService
{
use CachesQuery;
public function __construct(
private readonly CuttingResultPriceResolver $cuttingResultPriceResolver,
private readonly HomepageSettingService $homepageSettingService,
) {}
public function pageData(): array
{
return $this->cacheRemember('homepage:page_data', 900, function () {
$categories = Category::getActiveWithProducts();
$products = $this->getProducts();
$configuration = SystemConfiguration::instance();
$logo = MediaPresenter::first($configuration, 'logo');
$logoUrl = $logo['url'] ?? null;
$settings = app(SystemSettings::class);
$socialSettings = app(SocialMediaSettings::class);
return [
'categories' => $categories,
'products' => $products,
'appName' => $settings->app_name ?? 'DST Collection',
'aboutApp' => $settings->about_app ?? '',
'contactEmail' => $settings->email ?? '',
'contactPhone' => $settings->phone ?? '',
'contactAddress' => $settings->address ?? '',
'logoUrl' => $logoUrl,
'instagramUrl' => $socialSettings->instagram_url ?? null,
'facebookUrl' => $socialSettings->facebook_url ?? null,
'tiktokUrl' => $socialSettings->tiktok_url ?? null,
'homepage' => $this->homepageSettingService->homepageData(),
];
});
}
private function getProducts()
{
$products = Product::getActiveWithVariantsAndCategories();
$allVariantIds = $products
->flatMap(fn ($product) => $product->variants->pluck('id'))
->all();
$allPricesByVariant = $this->cuttingResultPriceResolver->latestPricesForVariants($allVariantIds);
return $products->map(function ($product) use ($allPricesByVariant) {
$product->variants->each(function ($variant) use ($allPricesByVariant) {
$variant->setAttribute('images', MediaPresenter::collection($variant, 'images'));
$variantPrices = $allPricesByVariant->get($variant->id, collect());
$variant->setAttribute(
'prices',
$variantPrices->map(fn ($price) => [
'type' => $price->price_type->value,
'type_label' => $price->price_type->label(),
'price' => (int) $price->price,
'price_formatted' => $price->price_formatted,
])->values()->all(),
);
});
return $product;
});
}
}