Files
2026-04-04 13:44:52 +11:00

335 lines
9.6 KiB
PHP

<?php
namespace App\Models;
use App\Dto\Scraping\ScrapeSchemaDto;
use App\Enums\ScraperService;
use App\Services\Helpers\CurrencyHelper;
use App\Services\Helpers\ScrapeStrategyHelper;
use Database\Factories\StoreFactory;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\HtmlString;
use Illuminate\Support\Str;
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
/**
* @property string $name
* @property string $initials
* @property array $domains
* @property HtmlString $domains_html
* @property array $scrape_strategy
* @property ScrapeSchemaDto $scrape_schema
* @property ?array $availability_match_config
* @property array $settings
* @property string $scraper_service
* @property array $scraper_options
* @property string $locale
* @property string $currency
* @property Collection $urls
* @property Collection $products
* @property ?User $user
* @property ?string $cookies
*/
class Store extends Model
{
/** @use HasFactory<StoreFactory> */
use HasFactory;
use HasSlug;
protected $fillable = [
'name',
'initials',
'domains',
'scrape_strategy',
'settings',
'notes',
'user_id',
'cookies',
];
protected function casts(): array
{
return [
'domains' => 'array',
'scrape_strategy' => 'array',
'settings' => 'array',
];
}
protected function scrapeSchema(): Attribute
{
return Attribute::make(
get: fn () => ScrapeStrategyHelper::toSchema($this->scrape_strategy ?? []),
);
}
protected function availabilityMatchConfig(): Attribute
{
return Attribute::make(
get: fn () => ScrapeStrategyHelper::getAvailabilityMatch($this->scrape_strategy ?? []),
);
}
public static function booted()
{
static::deleted(function (Store $store) {
// Get all products before deleting URLs (since products() relationship uses URLs).
$products = Product::whereIn('id', function ($query) use ($store) {
$query->select('product_id')
->from('urls')
->where('store_id', $store->id);
})->get();
// Delete URLs individually to trigger model events (which cascade delete prices).
$store->urls->each->delete();
// Update price cache for all affected products.
$products->each(fn (Product $product) => $product->updatePriceCache());
});
}
public function getSlugOptions(): SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug');
}
/***************************************************
* Relationships.
**************************************************/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function urls(): HasMany
{
return $this->hasMany(Url::class);
}
public function products(): HasManyThrough
{
return $this->hasManyThrough(
Product::class,
Url::class,
'store_id',
'id',
'id',
'product_id'
);
}
/***************************************************
* Scopes.
**************************************************/
public function scopeDomainFilter(Builder $query, string|array $domains): Builder
{
$domains = collect(Arr::wrap($domains))
->filter()
->flatMap(fn (string $domain) => static::domainCandidates($domain))
->unique()
->values();
$first = $domains->shift();
if ($first === null) {
return $query->whereRaw('0 = 1');
}
$driver = $query->getConnection()->getDriverName(); // @phpstan-ignore-line
if ($driver === 'sqlite') {
return $query->where(function (Builder $subQuery) use ($first, $domains) {
$candidates = collect([$first])
->merge($domains)
->filter()
->unique()
->values();
foreach ($candidates as $candidate) {
$needle = static::domainLikePattern($candidate);
$subQuery->orWhere('domains', 'like', $needle);
}
});
}
return $query->where(function (Builder $subQuery) use ($first, $domains) {
$subQuery->whereJsonContains('domains', ['domain' => $first]);
foreach ($domains as $domain) {
$subQuery->orWhereJsonContains('domains', ['domain' => $domain]);
}
});
}
public static function findByDomain(string|array $domains): ?self
{
$domains = collect(Arr::wrap($domains))
->filter()
->map(fn (string $domain) => static::normalizeDomain($domain))
->unique()
->values();
if ($domains->isEmpty()) {
return null;
}
$store = static::query()->domainFilter($domains->all())->oldest()->first();
if ($store) {
return $store;
}
$domainPatterns = $domains
->flatMap(fn (string $domain) => static::domainCandidates($domain))
->map(fn (string $domain) => static::domainLikePattern($domain))
->unique()
->values();
if ($domainPatterns->isEmpty()) {
return null;
}
return static::query()
->where(function (Builder $query) use ($domainPatterns) {
foreach ($domainPatterns as $pattern) {
$query->orWhereRaw('LOWER(domains) LIKE ?', [$pattern]);
}
})
->oldest()
->first();
}
/***************************************************
* Attributes.
**************************************************/
public function initials(): Attribute
{
return Attribute::make(
get: function ($value) {
if (! empty($value)) {
return strtoupper($value);
}
$parts = explode(' ', Str::slug($this->name, ' '));
$initials = count($parts) > 1
? collect(explode(' ', Str::slug($this->name, ' ')))
->map(fn ($part) => Str::substr($part, 0, 1))
->take(2)->join('')
: Str::substr($this->name, 0, 2);
return strtoupper($initials);
}
);
}
public function domainsHtml(): Attribute
{
return Attribute::make(
get: fn () => new HtmlString(Str::limit(collect($this->domains)
->pluck('domain')
->join(', ')))
);
}
public function scraperService(): Attribute
{
return Attribute::make(
get: function () {
return data_get($this->settings, 'scraper_service', ScraperService::Http->value);
}
);
}
public function scraperOptions(): Attribute
{
return Attribute::make(
get: function () {
return collect(explode(PHP_EOL, data_get($this->settings, 'scraper_service_settings', '')))
->filter(fn ($option) => ! empty($option) && Str::contains($option, '='))
->mapWithKeys(function ($option) {
$parts = explode('=', $option);
return [data_get($parts, 0) => data_get($parts, 1)];
})
->toArray();
}
);
}
public function testUrl(): Attribute
{
return Attribute::make(
get: fn () => data_get($this->settings, 'test_url', ''),
);
}
public function locale(): Attribute
{
return Attribute::make(
get: fn () => data_get($this->settings, 'locale_settings.locale', CurrencyHelper::getLocale()),
);
}
public function currency(): Attribute
{
return Attribute::make(
get: fn () => data_get($this->settings, 'locale_settings.currency', CurrencyHelper::getCurrency()),
);
}
/***************************************************
* Helpers.
**************************************************/
public function hasDomain($domain): bool
{
return collect($this->domains)
->pluck('domain')
->map(fn ($value) => static::normalizeDomain((string) $value))
->contains(static::normalizeDomain((string) $domain));
}
protected static function normalizeDomain(string $domain): string
{
$domain = strtolower(trim($domain));
return str_starts_with($domain, 'www.')
? substr($domain, 4)
: $domain;
}
/**
* @return array<int, string>
*/
protected static function domainCandidates(string $domain): array
{
$normalized = static::normalizeDomain($domain);
return array_values(array_unique([
strtolower(trim($domain)),
$normalized,
'www.'.$normalized,
]));
}
protected static function domainLikePattern(string $domain): string
{
return '%"domain":%'.strtolower($domain).'%';
}
}