feat: increase gallery grid from 4 to 5 columns per row on desktopfeat: increase gallery grid from 4 to 5 columns per row on desktop
This commit is contained in:
436
app/Console/Commands/AiTagArtworksCommand.php
Normal file
436
app/Console/Commands/AiTagArtworksCommand.php
Normal file
@@ -0,0 +1,436 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Artwork;
|
||||
use App\Services\TagService;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Generate AI tags for artworks using a local LM Studio vision model.
|
||||
*
|
||||
* Usage:
|
||||
* php artisan artworks:ai-tag
|
||||
* php artisan artworks:ai-tag --after-id=1000 --chunk=20 --dry-run
|
||||
* php artisan artworks:ai-tag --limit=100 --skip-tagged
|
||||
* php artisan artworks:ai-tag --artwork-id=242 # process a single artwork by ID
|
||||
* php artisan artworks:ai-tag --artwork-id=242 --dump-curl # print equivalent curl command (no API call made)
|
||||
* php artisan artworks:ai-tag --artwork-id=242 --debug # print CDN URL, file size, magic bytes and data-URI prefix
|
||||
* php artisan artworks:ai-tag --url=http://192.168.1.5:8200 --model=google/gemma-3-4b
|
||||
*/
|
||||
final class AiTagArtworksCommand extends Command
|
||||
{
|
||||
protected $signature = 'artworks:ai-tag
|
||||
{--artwork-id= : Process only this single artwork ID (bypasses public/approved scope)}
|
||||
{--after-id=0 : Skip artworks with ID ≤ this value (useful for resuming)}
|
||||
{--limit= : Stop after processing this many artworks}
|
||||
{--chunk=50 : DB chunk size}
|
||||
{--dry-run : Print tags but do not persist them}
|
||||
{--skip-tagged : Skip artworks that already have at least one AI tag}
|
||||
{--url-only : Send CDN URL instead of base64 (only works if LM Studio can reach the CDN)}
|
||||
{--dump-curl : Print the equivalent curl command for the API call and skip the actual request}
|
||||
{--debug : Print CDN URL, file size, magic bytes and data-URI prefix for each image}
|
||||
{--url= : LM Studio base URL (overrides config/env)}
|
||||
{--model= : Model identifier (overrides config/env)}
|
||||
{--clear-ai-tags : Delete existing AI tags for each artwork before re-tagging}
|
||||
';
|
||||
|
||||
protected $description = 'Generate tags for artworks via a local LM Studio vision model';
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Prompt
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private const SYSTEM_PROMPT = <<<'PROMPT'
|
||||
You are an expert at analysing visual artwork and generating concise, descriptive tags.
|
||||
PROMPT;
|
||||
|
||||
private const USER_PROMPT = <<<'PROMPT'
|
||||
Analyse the artwork image and return a JSON array of relevant tags.
|
||||
Cover: art style, subject/theme, dominant colours, mood, technique, and medium where visible.
|
||||
|
||||
Rules:
|
||||
- Return ONLY a valid JSON array of lowercase strings — no markdown, no explanation.
|
||||
- Each tag must be 1–4 words, no punctuation except hyphens.
|
||||
- Between 6 and 12 tags total.
|
||||
|
||||
Example output:
|
||||
["digital painting","fantasy","portrait","dark tones","glowing eyes","detailed","dramatic lighting"]
|
||||
PROMPT;
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
public function __construct(private readonly TagService $tagService)
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$artworkId = $this->option('artwork-id') !== null ? (int) $this->option('artwork-id') : null;
|
||||
$afterId = max(0, (int) $this->option('after-id'));
|
||||
$limit = $this->option('limit') !== null ? max(1, (int) $this->option('limit')) : null;
|
||||
$chunk = max(1, min((int) $this->option('chunk'), 200));
|
||||
$dryRun = (bool) $this->option('dry-run');
|
||||
$skipTagged = (bool) $this->option('skip-tagged');
|
||||
$dumpCurl = (bool) $this->option('dump-curl');
|
||||
$verbose = (bool) $this->option('debug');
|
||||
$useBase64 = !(bool) $this->option('url-only');
|
||||
$clearAiTags = (bool) $this->option('clear-ai-tags');
|
||||
|
||||
$baseUrl = rtrim((string) ($this->option('url') ?: config('vision.lm_studio.base_url')), '/');
|
||||
$model = (string) ($this->option('model') ?: config('vision.lm_studio.model'));
|
||||
$maxTags = (int) config('vision.lm_studio.max_tags', 12);
|
||||
|
||||
$this->info("LM Studio : {$baseUrl}");
|
||||
$this->info("Model : {$model}");
|
||||
$this->info("Image mode : " . ($useBase64 ? 'base64 (default)' : 'CDN URL (--url-only)'));
|
||||
$this->info("Dry run : " . ($dryRun ? 'YES' : 'no'));
|
||||
$this->info("Clear AI : " . ($clearAiTags ? 'YES — existing AI tags deleted first' : 'no'));
|
||||
if ($artworkId !== null) {
|
||||
$this->info("Artwork ID : {$artworkId} (single-artwork mode)");
|
||||
}
|
||||
$this->line('');
|
||||
|
||||
// Single-artwork mode: bypass public/approved scope so any artwork can be tested.
|
||||
if ($artworkId !== null) {
|
||||
$artwork = Artwork::withTrashed()->find($artworkId);
|
||||
if ($artwork === null) {
|
||||
$this->error("Artwork #{$artworkId} not found.");
|
||||
return self::FAILURE;
|
||||
}
|
||||
$limit = 1;
|
||||
$query = Artwork::withTrashed()->where('id', $artworkId);
|
||||
} else {
|
||||
$query = Artwork::query()
|
||||
->public()
|
||||
->where('id', '>', $afterId)
|
||||
->whereNotNull('hash')
|
||||
->whereNotNull('thumb_ext')
|
||||
->orderBy('id');
|
||||
|
||||
if ($skipTagged) {
|
||||
// Exclude artworks that already have an AI-sourced tag in the pivot.
|
||||
$query->whereDoesntHave('tags', fn ($q) => $q->where('artwork_tag.source', 'ai'));
|
||||
}
|
||||
}
|
||||
|
||||
$processed = 0;
|
||||
$tagged = 0;
|
||||
$skipped = 0;
|
||||
$errors = 0;
|
||||
|
||||
$query->chunkById($chunk, function ($artworks) use (
|
||||
&$processed, &$tagged, &$skipped, &$errors,
|
||||
$limit, $dryRun, $dumpCurl, $verbose, $useBase64, $baseUrl, $model, $maxTags, $clearAiTags,
|
||||
) {
|
||||
foreach ($artworks as $artwork) {
|
||||
if ($limit !== null && $processed >= $limit) {
|
||||
return false; // stop iteration
|
||||
}
|
||||
|
||||
$processed++;
|
||||
|
||||
$imageUrl = $artwork->thumbUrl('md');
|
||||
if ($imageUrl === null) {
|
||||
$this->warn(" [#{$artwork->id}] No thumb URL — skip");
|
||||
$skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->line(" [#{$artwork->id}] {$artwork->title}");
|
||||
|
||||
// Remove AI tags first if requested.
|
||||
if ($clearAiTags) {
|
||||
$aiTagIds = DB::table('artwork_tag')
|
||||
->where('artwork_id', $artwork->id)
|
||||
->where('source', 'ai')
|
||||
->pluck('tag_id')
|
||||
->all();
|
||||
|
||||
if ($aiTagIds !== []) {
|
||||
if (!$dryRun) {
|
||||
$this->tagService->detachTags($artwork, $aiTagIds);
|
||||
}
|
||||
$this->line(' ✂ Cleared ' . count($aiTagIds) . ' existing AI tag(s)' . ($dryRun ? ' (dry-run)' : ''));
|
||||
}
|
||||
}
|
||||
|
||||
if ($verbose) {
|
||||
$this->line(" CDN URL : {$imageUrl}");
|
||||
}
|
||||
|
||||
try {
|
||||
$tags = $this->fetchTags($baseUrl, $model, $imageUrl, $useBase64, $maxTags, $dumpCurl, $verbose);
|
||||
} catch (Throwable $e) {
|
||||
$this->error(" ✗ API error: " . $e->getMessage());
|
||||
// Show first 120 chars of the response body for easier debugging.
|
||||
if (str_contains($e->getMessage(), 'status code')) {
|
||||
$this->line(" (use --dry-run to test without saving)");
|
||||
}
|
||||
Log::error('artworks:ai-tag API error', [
|
||||
'artwork_id' => $artwork->id,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
$errors++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($tags === []) {
|
||||
$this->warn(" ✗ No tags returned");
|
||||
$skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
$tagList = implode(', ', $tags);
|
||||
$this->line(" → {$tagList}");
|
||||
|
||||
if (!$dryRun) {
|
||||
$aiTagPayload = array_map(fn (string $t) => ['tag' => $t, 'confidence' => null], $tags);
|
||||
|
||||
try {
|
||||
$this->tagService->attachAiTags($artwork, $aiTagPayload);
|
||||
$tagged++;
|
||||
} catch (Throwable $e) {
|
||||
$this->error(" ✗ Save error: " . $e->getMessage());
|
||||
Log::error('artworks:ai-tag save error', [
|
||||
'artwork_id' => $artwork->id,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
$errors++;
|
||||
}
|
||||
} else {
|
||||
$tagged++;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
$this->line('');
|
||||
$this->info("Done. processed={$processed} tagged={$tagged} skipped={$skipped} errors={$errors}");
|
||||
|
||||
return $errors > 0 ? self::FAILURE : self::SUCCESS;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// LM Studio API call
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
private function fetchTags(
|
||||
string $baseUrl,
|
||||
string $model,
|
||||
string $imageUrl,
|
||||
bool $useBase64,
|
||||
int $maxTags,
|
||||
bool $dumpCurl = false,
|
||||
bool $verbose = false,
|
||||
): array {
|
||||
$imageContent = $useBase64
|
||||
? $this->buildBase64ImageContent($imageUrl, $verbose)
|
||||
: ['type' => 'image_url', 'image_url' => ['url' => $imageUrl]];
|
||||
|
||||
$payload = [
|
||||
'model' => $model,
|
||||
'temperature' => (float) config('vision.lm_studio.temperature', 0.3),
|
||||
'max_tokens' => (int) config('vision.lm_studio.max_tokens', 300),
|
||||
'messages' => [
|
||||
[
|
||||
'role' => 'system',
|
||||
'content' => self::SYSTEM_PROMPT,
|
||||
],
|
||||
[
|
||||
'role' => 'user',
|
||||
'content' => [
|
||||
$imageContent,
|
||||
['type' => 'text', 'text' => self::USER_PROMPT],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$timeout = (int) config('vision.lm_studio.timeout', 60);
|
||||
$connectTimeout = (int) config('vision.lm_studio.connect_timeout', 5);
|
||||
$endpoint = "{$baseUrl}/v1/chat/completions";
|
||||
|
||||
// --dump-curl: write payload to a temp file and print the equivalent curl command.
|
||||
if ($dumpCurl) {
|
||||
$jsonPayload = json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
|
||||
// Truncate any base64 data URIs in the printed output so the terminal stays readable.
|
||||
$printable = preg_replace(
|
||||
'/("data:[^;]+;base64,)([A-Za-z0-9+\/=]{60})[A-Za-z0-9+\/=]+(")/',
|
||||
'$1$2...[base64 truncated]$3',
|
||||
$jsonPayload,
|
||||
) ?? $jsonPayload;
|
||||
|
||||
// Write the full (untruncated) payload to a temp file for use with curl --data.
|
||||
$tmpJson = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'sbtag_payload_' . uniqid() . '.json';
|
||||
file_put_contents($tmpJson, $jsonPayload);
|
||||
|
||||
$this->line('');
|
||||
$this->line('<fg=yellow>--- Payload (base64 truncated for display) ---</>');
|
||||
$this->line($printable);
|
||||
$this->line('');
|
||||
$this->line('<fg=yellow>--- curl command (full payload in temp file) ---</>');
|
||||
$this->line(
|
||||
'curl -s -X POST ' . escapeshellarg($endpoint)
|
||||
. ' -H ' . escapeshellarg('Content-Type: application/json')
|
||||
. ' --data @' . escapeshellarg($tmpJson)
|
||||
. ' | python -m json.tool'
|
||||
);
|
||||
$this->line('');
|
||||
$this->info("Full JSON payload written to: {$tmpJson}");
|
||||
|
||||
// Return empty — no real API call is made.
|
||||
return [];
|
||||
}
|
||||
|
||||
$response = Http::timeout($timeout)
|
||||
->connectTimeout($connectTimeout)
|
||||
->post($endpoint, $payload)
|
||||
->throw();
|
||||
|
||||
$body = $response->json();
|
||||
$content = $body['choices'][0]['message']['content'] ?? '';
|
||||
|
||||
return $this->parseTags((string) $content, $maxTags);
|
||||
}
|
||||
|
||||
/**
|
||||
* Download the image using the system curl binary (raw bytes, no encoding surprises),
|
||||
* base64-encode from the local file, then delete it.
|
||||
*
|
||||
* Using curl directly is more reliable than the Laravel Http client here because it
|
||||
* avoids gzip/deflate decoding issues, chunked-transfer quirks, and header parsing
|
||||
* edge cases that could corrupt the image bytes before encoding.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
* @throws \RuntimeException if curl fails or the file is empty
|
||||
*/
|
||||
private function buildBase64ImageContent(string $imageUrl, bool $verbose = false): array
|
||||
{
|
||||
$ext = strtolower(pathinfo(parse_url($imageUrl, PHP_URL_PATH) ?? '', PATHINFO_EXTENSION));
|
||||
$mime = match ($ext) {
|
||||
'png' => 'image/png',
|
||||
'gif' => 'image/gif',
|
||||
'webp' => 'image/webp',
|
||||
default => 'image/jpeg',
|
||||
};
|
||||
|
||||
$tmpPath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'sbtag_' . uniqid() . '.' . ($ext ?: 'jpg');
|
||||
|
||||
try {
|
||||
exec(
|
||||
'curl -s -f -L --max-time 30 -o ' . escapeshellarg($tmpPath) . ' ' . escapeshellarg($imageUrl),
|
||||
$output,
|
||||
$exitCode,
|
||||
);
|
||||
|
||||
if ($exitCode !== 0 || !file_exists($tmpPath) || filesize($tmpPath) === 0) {
|
||||
throw new \RuntimeException("curl failed to download image (exit={$exitCode}, size=" . (file_exists($tmpPath) ? filesize($tmpPath) : 'N/A') . "): {$imageUrl}");
|
||||
}
|
||||
|
||||
$rawBytes = file_get_contents($tmpPath);
|
||||
if ($rawBytes === false || $rawBytes === '') {
|
||||
throw new \RuntimeException("file_get_contents returned empty after curl download: {$tmpPath}");
|
||||
}
|
||||
|
||||
// LM Studio does not support WebP. Convert to JPEG via GD if needed.
|
||||
if ($mime === 'image/webp') {
|
||||
$convertedPath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'sbtag_conv_' . uniqid() . '.jpg';
|
||||
try {
|
||||
if (!function_exists('imagecreatefromwebp')) {
|
||||
throw new \RuntimeException('GD extension with WebP support is required to convert WebP images. Enable ext-gd with WebP support in php.ini.');
|
||||
}
|
||||
$img = imagecreatefromwebp($tmpPath);
|
||||
if ($img === false) {
|
||||
throw new \RuntimeException("GD failed to load WebP: {$tmpPath}");
|
||||
}
|
||||
imagejpeg($img, $convertedPath, 92);
|
||||
imagedestroy($img);
|
||||
$rawBytes = file_get_contents($convertedPath);
|
||||
$mime = 'image/jpeg';
|
||||
if ($verbose) {
|
||||
$this->line(' Convert : WebP → JPEG (LM Studio does not accept WebP)');
|
||||
}
|
||||
} finally {
|
||||
@unlink($convertedPath);
|
||||
}
|
||||
}
|
||||
|
||||
if ($verbose) {
|
||||
$fileSize = filesize($tmpPath);
|
||||
// Show first 8 bytes as hex to confirm it's a real image, not an HTML error page.
|
||||
$magicHex = strtoupper(bin2hex(substr($rawBytes, 0, 8)));
|
||||
$this->line(" File : {$tmpPath}");
|
||||
$this->line(" Size : {$fileSize} bytes");
|
||||
$this->line(" Magic : {$magicHex} (JPEG=FFD8FF, PNG=89504E47, WEBP=52494646)");
|
||||
}
|
||||
|
||||
$base64 = base64_encode($rawBytes);
|
||||
$dataUri = "data:{$mime};base64,{$base64}";
|
||||
|
||||
if ($verbose) {
|
||||
$this->line(" MIME : {$mime}");
|
||||
$this->line(" URI pfx : " . substr($dataUri, 0, 60) . '...');
|
||||
}
|
||||
} finally {
|
||||
@unlink($tmpPath);
|
||||
}
|
||||
|
||||
return ['type' => 'image_url', 'image_url' => ['url' => $dataUri]];
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Response parsing
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Extract a JSON array from the model's response text.
|
||||
*
|
||||
* The model should return just the array, but may include surrounding text
|
||||
* or markdown code fences, so we search for the first `[…]` block.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
private function parseTags(string $content, int $maxTags): array
|
||||
{
|
||||
$content = trim($content);
|
||||
|
||||
// Strip markdown code fences if present (```json … ```)
|
||||
$content = preg_replace('/^```(?:json)?\s*/i', '', $content) ?? $content;
|
||||
$content = preg_replace('/\s*```$/', '', $content) ?? $content;
|
||||
|
||||
// Extract the first JSON array from the text.
|
||||
if (!preg_match('/(\[.*?\])/s', $content, $matches)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$decoded = json_decode($matches[1], true);
|
||||
if (!is_array($decoded)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$tags = [];
|
||||
foreach ($decoded as $item) {
|
||||
if (!is_string($item)) {
|
||||
continue;
|
||||
}
|
||||
$clean = trim(strtolower((string) $item));
|
||||
if ($clean !== '') {
|
||||
$tags[] = $clean;
|
||||
}
|
||||
}
|
||||
|
||||
// Respect the configured max-tags ceiling.
|
||||
return array_slice(array_unique($tags), 0, $maxTags);
|
||||
}
|
||||
}
|
||||
92
app/Console/Commands/FixTagNamesCommand.php
Normal file
92
app/Console/Commands/FixTagNamesCommand.php
Normal file
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\TagNormalizer;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* One-time (and idempotent) command to convert slug-style tag names to
|
||||
* human-readable display names.
|
||||
*
|
||||
* A tag is considered "slug-style" when its name is identical to its slug
|
||||
* (e.g. name="digital-art", slug="digital-art"). Tags that already have a
|
||||
* custom name (user-edited) are left untouched.
|
||||
*
|
||||
* Usage:
|
||||
* php artisan tags:fix-names
|
||||
* php artisan tags:fix-names --dry-run
|
||||
*/
|
||||
final class FixTagNamesCommand extends Command
|
||||
{
|
||||
protected $signature = 'tags:fix-names
|
||||
{--dry-run : Show what would change without writing to the database}
|
||||
';
|
||||
|
||||
protected $description = 'Convert slug-style tag names (e.g. "digital-art") to readable names ("Digital Art")';
|
||||
|
||||
public function __construct(private readonly TagNormalizer $normalizer)
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$dryRun = (bool) $this->option('dry-run');
|
||||
|
||||
if ($dryRun) {
|
||||
$this->warn('DRY-RUN — no changes will be written.');
|
||||
}
|
||||
|
||||
// Only fix rows where name === slug (those were created by the old code).
|
||||
$rows = DB::table('tags')
|
||||
->whereColumn('name', 'slug')
|
||||
->orderBy('id')
|
||||
->get(['id', 'name', 'slug']);
|
||||
|
||||
if ($rows->isEmpty()) {
|
||||
$this->info('Nothing to fix — all tag names are already human-readable.');
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$this->info("Found {$rows->count()} tag(s) with slug-style names.");
|
||||
|
||||
$updated = 0;
|
||||
$bar = $this->output->createProgressBar($rows->count());
|
||||
$bar->start();
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$displayName = $this->normalizer->toDisplayName($row->slug);
|
||||
|
||||
if ($displayName === $row->name) {
|
||||
$bar->advance();
|
||||
continue; // Already correct (e.g. single-word tag "cars" → "Cars" — wait, that would differ)
|
||||
}
|
||||
|
||||
if ($this->output->isVerbose()) {
|
||||
$this->newLine();
|
||||
$this->line(" {$row->slug} → \"{$displayName}\"");
|
||||
}
|
||||
|
||||
if (!$dryRun) {
|
||||
DB::table('tags')
|
||||
->where('id', $row->id)
|
||||
->update(['name' => $displayName]);
|
||||
}
|
||||
|
||||
$updated++;
|
||||
$bar->advance();
|
||||
}
|
||||
|
||||
$bar->finish();
|
||||
$this->newLine(2);
|
||||
|
||||
$suffix = $dryRun ? ' (dry-run, nothing written)' : '';
|
||||
$this->info("Updated {$updated} of {$rows->count()} tag(s){$suffix}.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
288
app/Console/Commands/ImportLegacyAwards.php
Normal file
288
app/Console/Commands/ImportLegacyAwards.php
Normal file
@@ -0,0 +1,288 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\ArtworkAward;
|
||||
use App\Models\ArtworkAwardStat;
|
||||
use App\Services\ArtworkAwardService;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* Migrates legacy `users_opinions` (projekti_old_skinbase) into `artwork_awards`.
|
||||
*
|
||||
* Score mapping (legacy score → new medal):
|
||||
* 4 → gold (weight 3)
|
||||
* 3 → silver (weight 2)
|
||||
* 2 → bronze (weight 1)
|
||||
* 1 → skipped (too low to map meaningfully)
|
||||
*
|
||||
* Usage:
|
||||
* php artisan awards:import-legacy
|
||||
* php artisan awards:import-legacy --dry-run
|
||||
* php artisan awards:import-legacy --chunk=500
|
||||
* php artisan awards:import-legacy --skip-stats (skip final stats recalc)
|
||||
*/
|
||||
class ImportLegacyAwards extends Command
|
||||
{
|
||||
protected $signature = 'awards:import-legacy
|
||||
{--dry-run : Preview only — no writes to DB}
|
||||
{--chunk=250 : Rows to process per batch}
|
||||
{--skip-stats : Skip per-artwork stats recalculation at the end}
|
||||
{--force : Overwrite existing awards instead of skipping duplicates}';
|
||||
|
||||
protected $description = 'Import legacy users_opinions into artwork_awards';
|
||||
|
||||
/** Maps legacy score value → medal string */
|
||||
private const SCORE_MAP = [
|
||||
4 => 'gold',
|
||||
3 => 'silver',
|
||||
2 => 'bronze',
|
||||
];
|
||||
|
||||
public function handle(ArtworkAwardService $service): int
|
||||
{
|
||||
$dryRun = (bool) $this->option('dry-run');
|
||||
$chunk = max(1, (int) $this->option('chunk'));
|
||||
$skipStats = (bool) $this->option('skip-stats');
|
||||
$force = (bool) $this->option('force');
|
||||
|
||||
if ($dryRun) {
|
||||
$this->warn('[DRY-RUN] No data will be written.');
|
||||
}
|
||||
|
||||
// Verify legacy connection is reachable
|
||||
try {
|
||||
DB::connection('legacy')->getPdo();
|
||||
} catch (\Throwable $e) {
|
||||
$this->error('Cannot connect to legacy database: ' . $e->getMessage());
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
if (! DB::connection('legacy')->getSchemaBuilder()->hasTable('users_opinions')) {
|
||||
$this->error('Legacy table `users_opinions` not found.');
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
// Pre-load sets of valid artwork IDs and user IDs from the new DB
|
||||
$this->info('Loading new-DB artwork and user ID sets…');
|
||||
$validArtworkIds = DB::table('artworks')
|
||||
->whereNull('deleted_at')
|
||||
->pluck('id')
|
||||
->flip() // flip so we can use isset() for O(1) lookup
|
||||
->all();
|
||||
|
||||
$validUserIds = DB::table('users')
|
||||
->whereNull('deleted_at')
|
||||
->pluck('id')
|
||||
->flip()
|
||||
->all();
|
||||
|
||||
$this->info(sprintf(
|
||||
'Found %d artworks and %d users in new DB.',
|
||||
count($validArtworkIds),
|
||||
count($validUserIds)
|
||||
));
|
||||
|
||||
// Count legacy rows for progress bar
|
||||
$total = DB::connection('legacy')
|
||||
->table('users_opinions')
|
||||
->count();
|
||||
|
||||
$this->info("Legacy rows to process: {$total}");
|
||||
|
||||
if ($total === 0) {
|
||||
$this->warn('No legacy rows found. Nothing to do.');
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$stats = [
|
||||
'imported' => 0,
|
||||
'skipped_score' => 0,
|
||||
'skipped_artwork' => 0,
|
||||
'skipped_user' => 0,
|
||||
'skipped_duplicate'=> 0,
|
||||
'updated_force' => 0,
|
||||
'errors' => 0,
|
||||
];
|
||||
|
||||
$affectedArtworkIds = [];
|
||||
|
||||
$bar = $this->output->createProgressBar($total);
|
||||
$bar->setFormat(' %current%/%max% [%bar%] %percent:3s%% | imported: %imported% | skipped: %skipped%');
|
||||
$bar->setMessage('0', 'imported');
|
||||
$bar->setMessage('0', 'skipped');
|
||||
$bar->start();
|
||||
|
||||
DB::connection('legacy')
|
||||
->table('users_opinions')
|
||||
->orderBy('opinion_id')
|
||||
->chunk($chunk, function ($rows) use (
|
||||
&$stats,
|
||||
&$affectedArtworkIds,
|
||||
$validArtworkIds,
|
||||
$validUserIds,
|
||||
$dryRun,
|
||||
$force,
|
||||
$bar
|
||||
) {
|
||||
$inserts = [];
|
||||
$now = now();
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$artworkId = (int) $row->artwork_id;
|
||||
$userId = (int) $row->author_id; // author_id = the voter
|
||||
$score = (int) $row->score;
|
||||
$postedAt = $row->post_date ?? $now;
|
||||
|
||||
// --- score → medal ---
|
||||
$medal = self::SCORE_MAP[$score] ?? null;
|
||||
if ($medal === null) {
|
||||
$stats['skipped_score']++;
|
||||
$bar->advance();
|
||||
continue;
|
||||
}
|
||||
|
||||
// --- Artwork must exist in new DB ---
|
||||
if (! isset($validArtworkIds[$artworkId])) {
|
||||
$stats['skipped_artwork']++;
|
||||
$bar->advance();
|
||||
continue;
|
||||
}
|
||||
|
||||
// --- User must exist in new DB ---
|
||||
if (! isset($validUserIds[$userId])) {
|
||||
$stats['skipped_user']++;
|
||||
$bar->advance();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $dryRun) {
|
||||
if ($force) {
|
||||
// Upsert: update medal if row already exists
|
||||
$affected = DB::table('artwork_awards')
|
||||
->where('artwork_id', $artworkId)
|
||||
->where('user_id', $userId)
|
||||
->update([
|
||||
'medal' => $medal,
|
||||
'weight' => ArtworkAward::WEIGHTS[$medal],
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
|
||||
if ($affected > 0) {
|
||||
$stats['updated_force']++;
|
||||
$affectedArtworkIds[$artworkId] = true;
|
||||
$bar->advance();
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
// Skip if already exists
|
||||
if (
|
||||
DB::table('artwork_awards')
|
||||
->where('artwork_id', $artworkId)
|
||||
->where('user_id', $userId)
|
||||
->exists()
|
||||
) {
|
||||
$stats['skipped_duplicate']++;
|
||||
$bar->advance();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
$inserts[] = [
|
||||
'artwork_id' => $artworkId,
|
||||
'user_id' => $userId,
|
||||
'medal' => $medal,
|
||||
'weight' => ArtworkAward::WEIGHTS[$medal],
|
||||
'created_at' => $postedAt,
|
||||
'updated_at' => $postedAt,
|
||||
];
|
||||
|
||||
$affectedArtworkIds[$artworkId] = true;
|
||||
}
|
||||
|
||||
$stats['imported']++;
|
||||
$bar->advance();
|
||||
}
|
||||
|
||||
// Bulk insert the batch (DB::table bypasses the observer intentionally;
|
||||
// stats are recalculated in bulk at the end for performance)
|
||||
if (! $dryRun && ! empty($inserts)) {
|
||||
try {
|
||||
DB::table('artwork_awards')->insert($inserts);
|
||||
} catch (\Throwable $e) {
|
||||
// Fallback: insert one-by-one to isolate constraint violations
|
||||
foreach ($inserts as $row) {
|
||||
try {
|
||||
DB::table('artwork_awards')->insertOrIgnore([$row]);
|
||||
} catch (\Throwable) {
|
||||
$stats['errors']++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$skippedTotal = $stats['skipped_score']
|
||||
+ $stats['skipped_artwork']
|
||||
+ $stats['skipped_user']
|
||||
+ $stats['skipped_duplicate'];
|
||||
|
||||
$bar->setMessage((string) $stats['imported'], 'imported');
|
||||
$bar->setMessage((string) $skippedTotal, 'skipped');
|
||||
});
|
||||
|
||||
$bar->finish();
|
||||
$this->newLine(2);
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Recalculate stats for every affected artwork
|
||||
// -------------------------------------------------------------------------
|
||||
if (! $dryRun && ! $skipStats && ! empty($affectedArtworkIds)) {
|
||||
$artworkCount = count($affectedArtworkIds);
|
||||
$this->info("Recalculating award stats for {$artworkCount} artworks…");
|
||||
|
||||
$statsBar = $this->output->createProgressBar($artworkCount);
|
||||
$statsBar->start();
|
||||
|
||||
foreach (array_keys($affectedArtworkIds) as $artworkId) {
|
||||
try {
|
||||
$service->recalcStats($artworkId);
|
||||
} catch (\Throwable $e) {
|
||||
$this->newLine();
|
||||
$this->warn("Stats recalc failed for artwork #{$artworkId}: {$e->getMessage()}");
|
||||
}
|
||||
$statsBar->advance();
|
||||
}
|
||||
|
||||
$statsBar->finish();
|
||||
$this->newLine(2);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Summary
|
||||
// -------------------------------------------------------------------------
|
||||
$this->table(
|
||||
['Result', 'Count'],
|
||||
[
|
||||
['Imported (new rows)', $stats['imported']],
|
||||
['Forced updates', $stats['updated_force']],
|
||||
['Skipped – bad score', $stats['skipped_score']],
|
||||
['Skipped – artwork gone', $stats['skipped_artwork']],
|
||||
['Skipped – user gone', $stats['skipped_user']],
|
||||
['Skipped – duplicate', $stats['skipped_duplicate']],
|
||||
['Errors', $stats['errors']],
|
||||
]
|
||||
);
|
||||
|
||||
if ($dryRun) {
|
||||
$this->warn('[DRY-RUN] Nothing was written. Re-run without --dry-run to apply.');
|
||||
} else {
|
||||
$this->info('Migration complete.');
|
||||
}
|
||||
|
||||
return $stats['errors'] > 0 ? self::FAILURE : self::SUCCESS;
|
||||
}
|
||||
}
|
||||
266
app/Console/Commands/ImportLegacyComments.php
Normal file
266
app/Console/Commands/ImportLegacyComments.php
Normal file
@@ -0,0 +1,266 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Migrates legacy `artworks_comments` (projekti_old_skinbase) into `artwork_comments`.
|
||||
*
|
||||
* Column mapping:
|
||||
* legacy.comment_id → artwork_comments.legacy_id (idempotency key)
|
||||
* legacy.artwork_id → artwork_comments.artwork_id
|
||||
* legacy.user_id → artwork_comments.user_id
|
||||
* legacy.description → artwork_comments.content
|
||||
* legacy.date + .time → artwork_comments.created_at / updated_at
|
||||
*
|
||||
* Ignored legacy columns: owner, author (username strings), owner_user_id
|
||||
*
|
||||
* Usage:
|
||||
* php artisan comments:import-legacy
|
||||
* php artisan comments:import-legacy --dry-run
|
||||
* php artisan comments:import-legacy --chunk=1000
|
||||
* php artisan comments:import-legacy --allow-guest-user=0 (import rows where user_id maps to 0 / not found, assigning a fallback user_id)
|
||||
*/
|
||||
class ImportLegacyComments extends Command
|
||||
{
|
||||
protected $signature = 'comments:import-legacy
|
||||
{--dry-run : Preview only — no writes to DB}
|
||||
{--chunk=500 : Rows to process per batch}
|
||||
{--skip-empty : Skip comments with empty/whitespace-only content}';
|
||||
|
||||
protected $description = 'Import legacy artworks_comments into artwork_comments';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$dryRun = (bool) $this->option('dry-run');
|
||||
$chunk = max(1, (int) $this->option('chunk'));
|
||||
$skipEmpty = (bool) $this->option('skip-empty');
|
||||
|
||||
if ($dryRun) {
|
||||
$this->warn('[DRY-RUN] No data will be written.');
|
||||
}
|
||||
|
||||
// Verify legacy connection
|
||||
try {
|
||||
DB::connection('legacy')->getPdo();
|
||||
} catch (\Throwable $e) {
|
||||
$this->error('Cannot connect to legacy database: ' . $e->getMessage());
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
if (! DB::connection('legacy')->getSchemaBuilder()->hasTable('artworks_comments')) {
|
||||
$this->error('Legacy table `artworks_comments` not found.');
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
if (! DB::getSchemaBuilder()->hasColumn('artwork_comments', 'legacy_id')) {
|
||||
$this->error('Column `legacy_id` missing from `artwork_comments`. Run: php artisan migrate');
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
// Pre-load valid artwork IDs and user IDs from new DB for O(1) lookup
|
||||
$this->info('Loading new-DB artwork and user ID sets…');
|
||||
|
||||
$validArtworkIds = DB::table('artworks')
|
||||
->whereNull('deleted_at')
|
||||
->pluck('id')
|
||||
->flip()
|
||||
->all();
|
||||
|
||||
$validUserIds = DB::table('users')
|
||||
->whereNull('deleted_at')
|
||||
->pluck('id')
|
||||
->flip()
|
||||
->all();
|
||||
|
||||
$this->info(sprintf(
|
||||
'Found %d artworks and %d users in new DB.',
|
||||
count($validArtworkIds),
|
||||
count($validUserIds)
|
||||
));
|
||||
|
||||
// Already-imported legacy IDs (to resume safely)
|
||||
$this->info('Loading already-imported legacy_ids…');
|
||||
$alreadyImported = DB::table('artwork_comments')
|
||||
->whereNotNull('legacy_id')
|
||||
->pluck('legacy_id')
|
||||
->flip()
|
||||
->all();
|
||||
|
||||
$this->info(sprintf('%d comments already imported (will be skipped).', count($alreadyImported)));
|
||||
|
||||
$total = DB::connection('legacy')->table('artworks_comments')->count();
|
||||
$this->info("Legacy rows to process: {$total}");
|
||||
|
||||
if ($total === 0) {
|
||||
$this->warn('No legacy rows found. Nothing to do.');
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$stats = [
|
||||
'imported' => 0,
|
||||
'skipped_duplicate' => 0,
|
||||
'skipped_artwork' => 0,
|
||||
'skipped_user' => 0,
|
||||
'skipped_empty' => 0,
|
||||
'errors' => 0,
|
||||
];
|
||||
|
||||
$bar = $this->output->createProgressBar($total);
|
||||
$bar->setFormat(' %current%/%max% [%bar%] %percent:3s%% | imported: %imported% | skipped: %skipped%');
|
||||
$bar->setMessage('0', 'imported');
|
||||
$bar->setMessage('0', 'skipped');
|
||||
$bar->start();
|
||||
|
||||
DB::connection('legacy')
|
||||
->table('artworks_comments')
|
||||
->orderBy('comment_id')
|
||||
->chunk($chunk, function ($rows) use (
|
||||
&$stats,
|
||||
&$alreadyImported,
|
||||
$validArtworkIds,
|
||||
$validUserIds,
|
||||
$dryRun,
|
||||
$skipEmpty,
|
||||
$bar
|
||||
) {
|
||||
$inserts = [];
|
||||
$now = now();
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$legacyId = (int) $row->comment_id;
|
||||
$artworkId = (int) $row->artwork_id;
|
||||
$userId = (int) $row->user_id;
|
||||
$content = trim((string) ($row->description ?? ''));
|
||||
|
||||
// --- Already imported ---
|
||||
if (isset($alreadyImported[$legacyId])) {
|
||||
$stats['skipped_duplicate']++;
|
||||
$bar->advance();
|
||||
continue;
|
||||
}
|
||||
|
||||
// --- Content ---
|
||||
if ($skipEmpty && $content === '') {
|
||||
$stats['skipped_empty']++;
|
||||
$bar->advance();
|
||||
continue;
|
||||
}
|
||||
|
||||
// Replace empty content with a placeholder so NOT NULL is satisfied
|
||||
if ($content === '') {
|
||||
$content = '[no content]';
|
||||
}
|
||||
|
||||
// --- Artwork must exist ---
|
||||
if (! isset($validArtworkIds[$artworkId])) {
|
||||
$stats['skipped_artwork']++;
|
||||
$bar->advance();
|
||||
continue;
|
||||
}
|
||||
|
||||
// --- User must exist ---
|
||||
if (! isset($validUserIds[$userId])) {
|
||||
$stats['skipped_user']++;
|
||||
$bar->advance();
|
||||
continue;
|
||||
}
|
||||
|
||||
// --- Build timestamp from separate date + time columns ---
|
||||
$createdAt = $this->buildTimestamp($row->date, $row->time, $now);
|
||||
|
||||
if (! $dryRun) {
|
||||
$inserts[] = [
|
||||
'legacy_id' => $legacyId,
|
||||
'artwork_id' => $artworkId,
|
||||
'user_id' => $userId,
|
||||
'content' => $content,
|
||||
'is_approved' => 1,
|
||||
'created_at' => $createdAt,
|
||||
'updated_at' => $createdAt,
|
||||
'deleted_at' => null,
|
||||
];
|
||||
|
||||
$alreadyImported[$legacyId] = true;
|
||||
}
|
||||
|
||||
$stats['imported']++;
|
||||
$bar->advance();
|
||||
}
|
||||
|
||||
if (! $dryRun && ! empty($inserts)) {
|
||||
try {
|
||||
DB::table('artwork_comments')->insert($inserts);
|
||||
} catch (\Throwable $e) {
|
||||
// Fallback: row-by-row with ignore on unique violations
|
||||
foreach ($inserts as $row) {
|
||||
try {
|
||||
DB::table('artwork_comments')->insertOrIgnore([$row]);
|
||||
} catch (\Throwable) {
|
||||
$stats['errors']++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$skippedTotal = $stats['skipped_duplicate']
|
||||
+ $stats['skipped_artwork']
|
||||
+ $stats['skipped_user']
|
||||
+ $stats['skipped_empty'];
|
||||
|
||||
$bar->setMessage((string) $stats['imported'], 'imported');
|
||||
$bar->setMessage((string) $skippedTotal, 'skipped');
|
||||
});
|
||||
|
||||
$bar->finish();
|
||||
$this->newLine(2);
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Summary
|
||||
// -------------------------------------------------------------------------
|
||||
$this->table(
|
||||
['Result', 'Count'],
|
||||
[
|
||||
['Imported', $stats['imported']],
|
||||
['Skipped – already imported', $stats['skipped_duplicate']],
|
||||
['Skipped – artwork gone', $stats['skipped_artwork']],
|
||||
['Skipped – user gone', $stats['skipped_user']],
|
||||
['Skipped – empty content', $stats['skipped_empty']],
|
||||
['Errors', $stats['errors']],
|
||||
]
|
||||
);
|
||||
|
||||
if ($dryRun) {
|
||||
$this->warn('[DRY-RUN] Nothing was written. Re-run without --dry-run to apply.');
|
||||
} else {
|
||||
$this->info('Migration complete.');
|
||||
}
|
||||
|
||||
return $stats['errors'] > 0 ? self::FAILURE : self::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Combine a legacy `date` (DATE) and `time` (TIME) column into a single datetime string.
|
||||
* Falls back to $fallback when both are null.
|
||||
*/
|
||||
private function buildTimestamp(mixed $date, mixed $time, \Illuminate\Support\Carbon $fallback): string
|
||||
{
|
||||
if (! $date) {
|
||||
return $fallback->toDateTimeString();
|
||||
}
|
||||
|
||||
$datePart = substr((string) $date, 0, 10); // '2000-09-13'
|
||||
$timePart = $time ? substr((string) $time, 0, 8) : '00:00:00'; // '09:34:27'
|
||||
|
||||
// Sanity-check: MySQL TIME can be negative or > 24h for intervals — clamp to midnight
|
||||
if (! preg_match('/^\d{2}:\d{2}:\d{2}$/', $timePart) || $timePart < '00:00:00') {
|
||||
$timePart = '00:00:00';
|
||||
}
|
||||
|
||||
return $datePart . ' ' . $timePart;
|
||||
}
|
||||
}
|
||||
30
app/Console/Commands/RebuildArtworkSearchIndex.php
Normal file
30
app/Console/Commands/RebuildArtworkSearchIndex.php
Normal file
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\ArtworkSearchIndexer;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class RebuildArtworkSearchIndex extends Command
|
||||
{
|
||||
protected $signature = 'artworks:search-rebuild {--chunk=500 : Number of artworks per chunk}';
|
||||
protected $description = 'Re-queue all artworks for Meilisearch indexing (non-blocking, chunk-based).';
|
||||
|
||||
public function __construct(private readonly ArtworkSearchIndexer $indexer)
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$chunk = (int) $this->option('chunk');
|
||||
|
||||
$this->info("Dispatching index jobs in chunks of {$chunk}…");
|
||||
$this->indexer->rebuildAll($chunk);
|
||||
$this->info('All jobs dispatched. Workers will process them asynchronously.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ use App\Console\Commands\BackfillArtworkEmbeddingsCommand;
|
||||
use App\Console\Commands\AggregateSimilarArtworkAnalyticsCommand;
|
||||
use App\Console\Commands\AggregateFeedAnalyticsCommand;
|
||||
use App\Console\Commands\EvaluateFeedWeightsCommand;
|
||||
use App\Console\Commands\AiTagArtworksCommand;
|
||||
use App\Console\Commands\CompareFeedAbCommand;
|
||||
use App\Uploads\Commands\CleanupUploadsCommand;
|
||||
|
||||
@@ -33,6 +34,7 @@ class Kernel extends ConsoleKernel
|
||||
AggregateFeedAnalyticsCommand::class,
|
||||
EvaluateFeedWeightsCommand::class,
|
||||
CompareFeedAbCommand::class,
|
||||
AiTagArtworksCommand::class,
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
121
app/Http/Controllers/Api/ArtworkAwardController.php
Normal file
121
app/Http/Controllers/Api/ArtworkAwardController.php
Normal file
@@ -0,0 +1,121 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Artwork;
|
||||
use App\Models\ArtworkAward;
|
||||
use App\Services\ArtworkAwardService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
final class ArtworkAwardController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ArtworkAwardService $service
|
||||
) {}
|
||||
|
||||
/**
|
||||
* POST /api/artworks/{id}/award
|
||||
* Award the artwork with a medal.
|
||||
*/
|
||||
public function store(Request $request, int $id): JsonResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
$artwork = Artwork::findOrFail($id);
|
||||
|
||||
$this->authorize('award', [ArtworkAward::class, $artwork]);
|
||||
|
||||
$data = $request->validate([
|
||||
'medal' => ['required', 'string', 'in:gold,silver,bronze'],
|
||||
]);
|
||||
|
||||
$award = $this->service->award($artwork, $user, $data['medal']);
|
||||
|
||||
return response()->json(
|
||||
$this->buildPayload($artwork->id, $user->id),
|
||||
201
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* PUT /api/artworks/{id}/award
|
||||
* Change an existing award medal.
|
||||
*/
|
||||
public function update(Request $request, int $id): JsonResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
$artwork = Artwork::findOrFail($id);
|
||||
|
||||
$existingAward = ArtworkAward::where('artwork_id', $artwork->id)
|
||||
->where('user_id', $user->id)
|
||||
->firstOrFail();
|
||||
|
||||
$this->authorize('change', $existingAward);
|
||||
|
||||
$data = $request->validate([
|
||||
'medal' => ['required', 'string', 'in:gold,silver,bronze'],
|
||||
]);
|
||||
|
||||
$award = $this->service->changeAward($artwork, $user, $data['medal']);
|
||||
|
||||
return response()->json($this->buildPayload($artwork->id, $user->id));
|
||||
}
|
||||
|
||||
/**
|
||||
* DELETE /api/artworks/{id}/award
|
||||
* Remove the user's award for this artwork.
|
||||
*/
|
||||
public function destroy(Request $request, int $id): JsonResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
$artwork = Artwork::findOrFail($id);
|
||||
|
||||
$existingAward = ArtworkAward::where('artwork_id', $artwork->id)
|
||||
->where('user_id', $user->id)
|
||||
->firstOrFail();
|
||||
|
||||
$this->authorize('remove', $existingAward);
|
||||
|
||||
$this->service->removeAward($artwork, $user);
|
||||
|
||||
return response()->json($this->buildPayload($artwork->id, $user->id));
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/artworks/{id}/awards
|
||||
* Return award stats + viewer's current award.
|
||||
*/
|
||||
public function show(Request $request, int $id): JsonResponse
|
||||
{
|
||||
$artwork = Artwork::findOrFail($id);
|
||||
|
||||
return response()->json($this->buildPayload($artwork->id, $request->user()?->id));
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// All authorization is delegated to ArtworkAwardPolicy via $this->authorize().
|
||||
|
||||
private function buildPayload(int $artworkId, ?int $userId): array
|
||||
{
|
||||
$stat = \App\Models\ArtworkAwardStat::find($artworkId);
|
||||
|
||||
$userAward = $userId
|
||||
? ArtworkAward::where('artwork_id', $artworkId)
|
||||
->where('user_id', $userId)
|
||||
->value('medal')
|
||||
: null;
|
||||
|
||||
return [
|
||||
'awards' => [
|
||||
'gold' => $stat?->gold_count ?? 0,
|
||||
'silver' => $stat?->silver_count ?? 0,
|
||||
'bronze' => $stat?->bronze_count ?? 0,
|
||||
'score' => $stat?->score_total ?? 0,
|
||||
],
|
||||
'viewer_award' => $userAward,
|
||||
];
|
||||
}
|
||||
}
|
||||
71
app/Http/Controllers/Api/ArtworkNavigationController.php
Normal file
71
app/Http/Controllers/Api/ArtworkNavigationController.php
Normal file
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Resources\ArtworkResource;
|
||||
use App\Models\Artwork;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class ArtworkNavigationController extends Controller
|
||||
{
|
||||
/**
|
||||
* GET /api/artworks/navigation/{id}
|
||||
*
|
||||
* Returns prev/next published artworks by the same author.
|
||||
*/
|
||||
public function neighbors(int $id): JsonResponse
|
||||
{
|
||||
$artwork = Artwork::published()
|
||||
->select(['id', 'user_id', 'title', 'slug'])
|
||||
->find($id);
|
||||
|
||||
if (! $artwork) {
|
||||
return response()->json([
|
||||
'prev_id' => null, 'next_id' => null,
|
||||
'prev_url' => null, 'next_url' => null,
|
||||
'prev_slug' => null, 'next_slug' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
$scope = Artwork::published()
|
||||
->select(['id', 'title', 'slug'])
|
||||
->where('user_id', $artwork->user_id);
|
||||
|
||||
$prev = (clone $scope)->where('id', '<', $id)->orderByDesc('id')->first();
|
||||
$next = (clone $scope)->where('id', '>', $id)->orderBy('id')->first();
|
||||
|
||||
$prevSlug = $prev ? (Str::slug($prev->slug ?: $prev->title) ?: (string) $prev->id) : null;
|
||||
$nextSlug = $next ? (Str::slug($next->slug ?: $next->title) ?: (string) $next->id) : null;
|
||||
|
||||
return response()->json([
|
||||
'prev_id' => $prev?->id,
|
||||
'next_id' => $next?->id,
|
||||
'prev_url' => $prev ? url('/art/' . $prev->id . '/' . $prevSlug) : null,
|
||||
'next_url' => $next ? url('/art/' . $next->id . '/' . $nextSlug) : null,
|
||||
'prev_slug' => $prevSlug,
|
||||
'next_slug' => $nextSlug,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/artworks/{id}/page
|
||||
*
|
||||
* Returns full artwork resource by numeric ID for client-side (no-reload) navigation.
|
||||
*/
|
||||
public function pageData(int $id): JsonResponse
|
||||
{
|
||||
$artwork = Artwork::with(['user.profile', 'categories.contentType', 'tags', 'stats'])
|
||||
->published()
|
||||
->find($id);
|
||||
|
||||
if (! $artwork) {
|
||||
return response()->json(['error' => 'Not found'], 404);
|
||||
}
|
||||
|
||||
$resource = (new ArtworkResource($artwork))->toArray(request());
|
||||
|
||||
return response()->json($resource);
|
||||
}
|
||||
}
|
||||
109
app/Http/Controllers/Api/Search/ArtworkSearchController.php
Normal file
109
app/Http/Controllers/Api/Search/ArtworkSearchController.php
Normal file
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Controllers\Api\Search;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Resources\ArtworkListResource;
|
||||
use App\Models\Artwork;
|
||||
use App\Models\Tag;
|
||||
use App\Services\ArtworkSearchService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* Artwork search endpoints powered by Meilisearch.
|
||||
*
|
||||
* GET /api/search/artworks?q=&tags[]=&category=&orientation=&sort=
|
||||
* GET /api/search/artworks/tag/{slug}
|
||||
* GET /api/search/artworks/category/{cat}
|
||||
* GET /api/search/artworks/related/{id}
|
||||
*/
|
||||
class ArtworkSearchController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ArtworkSearchService $search
|
||||
) {}
|
||||
|
||||
/**
|
||||
* GET /api/search/artworks
|
||||
*/
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'q' => ['nullable', 'string', 'max:200'],
|
||||
'tags' => ['nullable', 'array', 'max:10'],
|
||||
'tags.*' => ['string', 'max:80'],
|
||||
'category' => ['nullable', 'string', 'max:80'],
|
||||
'orientation' => ['nullable', 'in:landscape,portrait,square'],
|
||||
'resolution' => ['nullable', 'string', 'max:20'],
|
||||
'author_id' => ['nullable', 'integer', 'min:1'],
|
||||
'sort' => ['nullable', 'string', 'regex:/^(created_at|downloads|likes|views):(asc|desc)$/'],
|
||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:100'],
|
||||
]);
|
||||
|
||||
$results = $this->search->search(
|
||||
q: (string) ($validated['q'] ?? ''),
|
||||
filters: array_filter([
|
||||
'tags' => $validated['tags'] ?? [],
|
||||
'category' => $validated['category'] ?? null,
|
||||
'orientation' => $validated['orientation'] ?? null,
|
||||
'resolution' => $validated['resolution'] ?? null,
|
||||
'author_id' => $validated['author_id'] ?? null,
|
||||
'sort' => $validated['sort'] ?? null,
|
||||
]),
|
||||
perPage: (int) ($validated['per_page'] ?? 24),
|
||||
);
|
||||
|
||||
// Eager-load relations needed by ArtworkListResource
|
||||
$results->getCollection()->loadMissing(['user', 'categories.contentType']);
|
||||
|
||||
return ArtworkListResource::collection($results)->response();
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/search/artworks/tag/{slug}
|
||||
*/
|
||||
public function byTag(Request $request, string $slug): JsonResponse
|
||||
{
|
||||
$tag = Tag::where('slug', $slug)->first();
|
||||
|
||||
if (! $tag) {
|
||||
return response()->json(['message' => 'Tag not found.'], 404);
|
||||
}
|
||||
|
||||
$results = $this->search->byTag($slug, (int) $request->query('per_page', 24));
|
||||
|
||||
return response()->json([
|
||||
'tag' => ['id' => $tag->id, 'name' => $tag->name, 'slug' => $tag->slug],
|
||||
'results' => $results,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/search/artworks/category/{cat}
|
||||
*/
|
||||
public function byCategory(Request $request, string $cat): JsonResponse
|
||||
{
|
||||
$results = $this->search->byCategory($cat, (int) $request->query('per_page', 24));
|
||||
|
||||
return response()->json($results);
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/search/artworks/related/{id}
|
||||
*/
|
||||
public function related(int $id): JsonResponse
|
||||
{
|
||||
$artwork = Artwork::with(['tags'])->find($id);
|
||||
|
||||
if (! $artwork) {
|
||||
return response()->json(['message' => 'Artwork not found.'], 404);
|
||||
}
|
||||
|
||||
$results = $this->search->related($artwork, 12);
|
||||
|
||||
return response()->json($results);
|
||||
}
|
||||
}
|
||||
@@ -9,44 +9,49 @@ use App\Http\Requests\Tags\PopularTagsRequest;
|
||||
use App\Http\Requests\Tags\TagSearchRequest;
|
||||
use App\Models\Tag;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
|
||||
final class TagController extends Controller
|
||||
{
|
||||
public function search(TagSearchRequest $request): JsonResponse
|
||||
{
|
||||
$q = (string) ($request->validated()['q'] ?? '');
|
||||
$q = trim($q);
|
||||
$q = trim((string) ($request->validated()['q'] ?? ''));
|
||||
|
||||
$query = Tag::query()->where('is_active', true);
|
||||
if ($q !== '') {
|
||||
$query->where(function ($sub) use ($q): void {
|
||||
$sub->where('name', 'like', $q . '%')
|
||||
->orWhere('slug', 'like', $q . '%');
|
||||
});
|
||||
}
|
||||
// Short results cached for 2 min; empty-query (popular suggestions) for 5 min.
|
||||
$ttl = $q === '' ? 300 : 120;
|
||||
$cacheKey = 'tags.search.' . ($q === '' ? '__empty__' : md5($q));
|
||||
|
||||
$tags = $query
|
||||
->orderByDesc('usage_count')
|
||||
->limit(20)
|
||||
->get(['id', 'name', 'slug', 'usage_count']);
|
||||
$data = Cache::remember($cacheKey, $ttl, function () use ($q): mixed {
|
||||
$query = Tag::query()->where('is_active', true);
|
||||
if ($q !== '') {
|
||||
$query->where(function ($sub) use ($q): void {
|
||||
$sub->where('name', 'like', $q . '%')
|
||||
->orWhere('slug', 'like', $q . '%');
|
||||
});
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'data' => $tags,
|
||||
]);
|
||||
return $query
|
||||
->orderByDesc('usage_count')
|
||||
->limit(20)
|
||||
->get(['id', 'name', 'slug', 'usage_count']);
|
||||
});
|
||||
|
||||
return response()->json(['data' => $data]);
|
||||
}
|
||||
|
||||
public function popular(PopularTagsRequest $request): JsonResponse
|
||||
{
|
||||
$limit = (int) ($request->validated()['limit'] ?? 20);
|
||||
$limit = (int) ($request->validated()['limit'] ?? 20);
|
||||
$cacheKey = 'tags.popular.' . $limit;
|
||||
|
||||
$tags = Tag::query()
|
||||
->where('is_active', true)
|
||||
->orderByDesc('usage_count')
|
||||
->limit($limit)
|
||||
->get(['id', 'name', 'slug', 'usage_count']);
|
||||
$data = Cache::remember($cacheKey, 300, function () use ($limit): mixed {
|
||||
return Tag::query()
|
||||
->where('is_active', true)
|
||||
->orderByDesc('usage_count')
|
||||
->limit($limit)
|
||||
->get(['id', 'name', 'slug', 'usage_count']);
|
||||
});
|
||||
|
||||
return response()->json([
|
||||
'data' => $tags,
|
||||
]);
|
||||
return response()->json(['data' => $data]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,24 @@ use Illuminate\Support\Facades\DB;
|
||||
|
||||
class InterviewController extends Controller
|
||||
{
|
||||
public function index(Request $request)
|
||||
{
|
||||
try {
|
||||
$interviews = DB::table('interviews as i')
|
||||
->leftJoin('users as u', 'u.username', '=', 'i.username')
|
||||
->select('i.id', 'i.headline', 'i.username', 'u.id as user_id', 'u.name as uname', 'u.icon')
|
||||
->orderByDesc('i.id')
|
||||
->get();
|
||||
} catch (\Throwable $e) {
|
||||
$interviews = collect();
|
||||
}
|
||||
|
||||
return view('legacy.interviews', [
|
||||
'interviews' => $interviews,
|
||||
'page_title' => 'Interviews',
|
||||
]);
|
||||
}
|
||||
|
||||
public function show(Request $request, $id, $slug = null)
|
||||
{
|
||||
$id = (int) $id;
|
||||
|
||||
@@ -49,6 +49,6 @@ class LatestCommentsController extends Controller
|
||||
|
||||
$page_title = 'Latest Comments';
|
||||
|
||||
return view('community.latest-comments', compact('page_title', 'comments'));
|
||||
return view('web.comments.latest', compact('page_title', 'comments'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,10 +36,11 @@ class LatestController extends Controller
|
||||
'thumb_url' => $present['url'],
|
||||
'thumb_srcset' => $present['srcset'] ?? $present['url'],
|
||||
'uname' => $artwork->user->name ?? 'Skinbase',
|
||||
'published_at' => $artwork->published_at, // required by CursorPaginator
|
||||
];
|
||||
});
|
||||
|
||||
return view('community.latest-artworks', [
|
||||
return view('web.uploads.latest', [
|
||||
'artworks' => $artworks,
|
||||
'page_title' => 'Latest Artworks',
|
||||
]);
|
||||
|
||||
@@ -44,6 +44,6 @@ class MembersController extends Controller
|
||||
});
|
||||
}
|
||||
|
||||
return view('web.browse', compact('page_title', 'artworks'));
|
||||
return view('web.members.photos', compact('page_title', 'artworks'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,26 +14,21 @@ class MonthlyCommentatorsController extends Controller
|
||||
$page = max(1, (int) $request->query('page', 1));
|
||||
|
||||
$query = DB::table('artwork_comments as t1')
|
||||
->leftJoin('users as t2', 't1.user_id', '=', 't2.user_id')
|
||||
->leftJoin('country as c', 't2.country', '=', 'c.id')
|
||||
->leftJoin('users as t2', 't1.user_id', '=', 't2.id')
|
||||
->where('t1.user_id', '>', 0)
|
||||
->whereRaw("DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= t1.date")
|
||||
->whereRaw('t1.created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)')
|
||||
->select(
|
||||
't2.user_id',
|
||||
't2.uname',
|
||||
't2.user_type',
|
||||
't2.country',
|
||||
'c.name as country_name',
|
||||
'c.flag as country_flag',
|
||||
't2.id as user_id',
|
||||
DB::raw('COALESCE(t2.username, t2.name, "User") as uname'),
|
||||
DB::raw('COUNT(*) as num_comments')
|
||||
)
|
||||
->groupBy('t1.user_id')
|
||||
->groupBy('t2.id')
|
||||
->orderByDesc('num_comments');
|
||||
|
||||
$rows = $query->paginate($hits)->withQueryString();
|
||||
|
||||
$page_title = 'Monthly Top Commentators';
|
||||
|
||||
return view('user.monthly-commentators', compact('page_title', 'rows'));
|
||||
return view('web.comments.monthly', compact('page_title', 'rows'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,15 +5,21 @@ namespace App\Http\Controllers\User;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\ProfileUpdateRequest;
|
||||
use App\Models\Artwork;
|
||||
use App\Models\ProfileComment;
|
||||
use App\Models\User;
|
||||
use App\Services\ArtworkService;
|
||||
use App\Services\ThumbnailPresenter;
|
||||
use App\Services\ThumbnailService;
|
||||
use App\Services\UsernameApprovalService;
|
||||
use App\Support\AvatarUrl;
|
||||
use App\Support\UsernamePolicy;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Redirect;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\View\View;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\Rules\Password as PasswordRule;
|
||||
@@ -63,6 +69,66 @@ class ProfileController extends Controller
|
||||
return redirect()->route('profile.show', ['username' => UsernamePolicy::normalize($username)], 301);
|
||||
}
|
||||
|
||||
/** Toggle follow/unfollow for the profile of $username (auth required). */
|
||||
public function toggleFollow(Request $request, string $username): JsonResponse
|
||||
{
|
||||
$normalized = UsernamePolicy::normalize($username);
|
||||
$target = User::query()->whereRaw('LOWER(username) = ?', [$normalized])->firstOrFail();
|
||||
|
||||
$viewerId = Auth::id();
|
||||
|
||||
if ($viewerId === $target->id) {
|
||||
return response()->json(['error' => 'Cannot follow yourself.'], 422);
|
||||
}
|
||||
|
||||
$exists = DB::table('user_followers')
|
||||
->where('user_id', $target->id)
|
||||
->where('follower_id', $viewerId)
|
||||
->exists();
|
||||
|
||||
if ($exists) {
|
||||
DB::table('user_followers')
|
||||
->where('user_id', $target->id)
|
||||
->where('follower_id', $viewerId)
|
||||
->delete();
|
||||
$following = false;
|
||||
} else {
|
||||
DB::table('user_followers')->insertOrIgnore([
|
||||
'user_id' => $target->id,
|
||||
'follower_id'=> $viewerId,
|
||||
'created_at' => now(),
|
||||
]);
|
||||
$following = true;
|
||||
}
|
||||
|
||||
$count = DB::table('user_followers')->where('user_id', $target->id)->count();
|
||||
|
||||
return response()->json([
|
||||
'following' => $following,
|
||||
'follower_count' => $count,
|
||||
]);
|
||||
}
|
||||
|
||||
/** Store a comment on a user profile (auth required). */
|
||||
public function storeComment(Request $request, string $username): RedirectResponse
|
||||
{
|
||||
$normalized = UsernamePolicy::normalize($username);
|
||||
$target = User::query()->whereRaw('LOWER(username) = ?', [$normalized])->firstOrFail();
|
||||
|
||||
$request->validate([
|
||||
'body' => ['required', 'string', 'min:2', 'max:2000'],
|
||||
]);
|
||||
|
||||
ProfileComment::create([
|
||||
'profile_user_id' => $target->id,
|
||||
'author_user_id' => Auth::id(),
|
||||
'body' => $request->input('body'),
|
||||
]);
|
||||
|
||||
return Redirect::route('profile.show', ['username' => strtolower((string) $target->username)])
|
||||
->with('status', 'Comment posted!');
|
||||
}
|
||||
|
||||
public function edit(Request $request): View
|
||||
{
|
||||
return view('profile.edit', [
|
||||
@@ -256,38 +322,211 @@ class ProfileController extends Controller
|
||||
|
||||
private function renderUserProfile(Request $request, User $user)
|
||||
{
|
||||
$isOwner = Auth::check() && Auth::id() === $user->id;
|
||||
$perPage = 24;
|
||||
$isOwner = Auth::check() && Auth::id() === $user->id;
|
||||
$viewer = Auth::user();
|
||||
$perPage = 24;
|
||||
|
||||
// ── Artworks (cursor-paginated) ──────────────────────────────────────
|
||||
$artworks = $this->artworkService->getArtworksByUser($user->id, $isOwner, $perPage)
|
||||
->through(function (Artwork $art) {
|
||||
$present = \App\Services\ThumbnailPresenter::present($art, 'md');
|
||||
$present = ThumbnailPresenter::present($art, 'md');
|
||||
return (object) [
|
||||
'id' => $art->id,
|
||||
'name' => $art->title,
|
||||
'picture' => $art->file_name,
|
||||
'datum' => $art->published_at,
|
||||
'published_at' => $art->published_at, // required by cursor paginator (orders by this column)
|
||||
'thumb' => $present['url'],
|
||||
'thumb_srcset' => $present['srcset'] ?? $present['url'],
|
||||
'uname' => $art->user->name ?? 'Skinbase',
|
||||
'username' => $art->user->username ?? null,
|
||||
'user_id' => $art->user_id,
|
||||
'width' => $art->width,
|
||||
'height' => $art->height,
|
||||
];
|
||||
});
|
||||
|
||||
return (object) [
|
||||
'id' => $art->id,
|
||||
'name' => $art->title,
|
||||
'picture' => $art->file_name,
|
||||
'datum' => $art->published_at,
|
||||
'thumb' => $present['url'],
|
||||
'thumb_srcset' => $present['srcset'] ?? $present['url'],
|
||||
'uname' => $art->user->name ?? 'Skinbase',
|
||||
];
|
||||
});
|
||||
// ── Featured artworks for this user ─────────────────────────────────
|
||||
$featuredArtworks = collect();
|
||||
if (Schema::hasTable('artwork_features')) {
|
||||
$featuredArtworks = DB::table('artwork_features as af')
|
||||
->join('artworks as a', 'a.id', '=', 'af.artwork_id')
|
||||
->where('a.user_id', $user->id)
|
||||
->where('af.is_active', true)
|
||||
->whereNull('af.deleted_at')
|
||||
->whereNull('a.deleted_at')
|
||||
->where('a.is_public', true)
|
||||
->where('a.is_approved', true)
|
||||
->orderByDesc('af.featured_at')
|
||||
->limit(3)
|
||||
->select([
|
||||
'a.id', 'a.title as name', 'a.hash', 'a.thumb_ext',
|
||||
'a.width', 'a.height', 'af.label', 'af.featured_at',
|
||||
])
|
||||
->get()
|
||||
->map(function ($row) {
|
||||
$thumbUrl = ($row->hash && $row->thumb_ext)
|
||||
? ThumbnailService::fromHash($row->hash, $row->thumb_ext, 'md')
|
||||
: '/images/placeholder.jpg';
|
||||
return (object) [
|
||||
'id' => $row->id,
|
||||
'name' => $row->name,
|
||||
'thumb' => $thumbUrl,
|
||||
'label' => $row->label,
|
||||
'featured_at' => $row->featured_at,
|
||||
'width' => $row->width,
|
||||
'height' => $row->height,
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
$legacyUser = (object) [
|
||||
'user_id' => $user->id,
|
||||
'uname' => $user->username ?? $user->name,
|
||||
'name' => $user->name,
|
||||
'real_name' => $user->name,
|
||||
'icon' => DB::table('user_profiles')->where('user_id', $user->id)->value('avatar_hash'),
|
||||
'about_me' => $user->bio ?? null,
|
||||
];
|
||||
// ── Favourites ───────────────────────────────────────────────────────
|
||||
$favourites = collect();
|
||||
if (Schema::hasTable('user_favorites')) {
|
||||
$favourites = DB::table('user_favorites as uf')
|
||||
->join('artworks as a', 'a.id', '=', 'uf.artwork_id')
|
||||
->where('uf.user_id', $user->id)
|
||||
->whereNull('a.deleted_at')
|
||||
->where('a.is_public', true)
|
||||
->where('a.is_approved', true)
|
||||
->orderByDesc('uf.created_at')
|
||||
->limit(12)
|
||||
->select(['a.id', 'a.title as name', 'a.hash', 'a.thumb_ext', 'a.width', 'a.height', 'a.user_id'])
|
||||
->get()
|
||||
->map(function ($row) {
|
||||
$thumbUrl = ($row->hash && $row->thumb_ext)
|
||||
? ThumbnailService::fromHash($row->hash, $row->thumb_ext, 'sm')
|
||||
: '/images/placeholder.jpg';
|
||||
return (object) [
|
||||
'id' => $row->id,
|
||||
'name' => $row->name,
|
||||
'thumb' => $thumbUrl,
|
||||
'width' => $row->width,
|
||||
'height'=> $row->height,
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
// ── Statistics ───────────────────────────────────────────────────────
|
||||
$stats = null;
|
||||
if (Schema::hasTable('user_statistics')) {
|
||||
$stats = DB::table('user_statistics')->where('user_id', $user->id)->first();
|
||||
}
|
||||
|
||||
// ── Social links ─────────────────────────────────────────────────────
|
||||
$socialLinks = collect();
|
||||
if (Schema::hasTable('user_social_links')) {
|
||||
$socialLinks = DB::table('user_social_links')
|
||||
->where('user_id', $user->id)
|
||||
->get()
|
||||
->keyBy('platform');
|
||||
}
|
||||
|
||||
// ── Follower data ────────────────────────────────────────────────────
|
||||
$followerCount = 0;
|
||||
$recentFollowers = collect();
|
||||
$viewerIsFollowing = false;
|
||||
|
||||
if (Schema::hasTable('user_followers')) {
|
||||
$followerCount = DB::table('user_followers')->where('user_id', $user->id)->count();
|
||||
|
||||
$recentFollowers = DB::table('user_followers as uf')
|
||||
->join('users as u', 'u.id', '=', 'uf.follower_id')
|
||||
->leftJoin('user_profiles as up', 'up.user_id', '=', 'u.id')
|
||||
->where('uf.user_id', $user->id)
|
||||
->whereNull('u.deleted_at')
|
||||
->orderByDesc('uf.created_at')
|
||||
->limit(10)
|
||||
->select(['u.id', 'u.username', 'u.name', 'up.avatar_hash', 'uf.created_at as followed_at'])
|
||||
->get()
|
||||
->map(fn ($row) => (object) [
|
||||
'id' => $row->id,
|
||||
'username' => $row->username,
|
||||
'uname' => $row->username ?? $row->name,
|
||||
'avatar_url' => AvatarUrl::forUser((int) $row->id, $row->avatar_hash, 50),
|
||||
'profile_url' => '/@' . strtolower((string) ($row->username ?? $row->id)),
|
||||
'followed_at' => $row->followed_at,
|
||||
]);
|
||||
|
||||
if ($viewer && $viewer->id !== $user->id) {
|
||||
$viewerIsFollowing = DB::table('user_followers')
|
||||
->where('user_id', $user->id)
|
||||
->where('follower_id', $viewer->id)
|
||||
->exists();
|
||||
}
|
||||
}
|
||||
|
||||
// ── Profile comments ─────────────────────────────────────────────────
|
||||
$profileComments = collect();
|
||||
if (Schema::hasTable('profile_comments')) {
|
||||
$profileComments = DB::table('profile_comments as pc')
|
||||
->join('users as u', 'u.id', '=', 'pc.author_user_id')
|
||||
->leftJoin('user_profiles as up', 'up.user_id', '=', 'u.id')
|
||||
->where('pc.profile_user_id', $user->id)
|
||||
->where('pc.is_active', true)
|
||||
->whereNull('u.deleted_at')
|
||||
->orderByDesc('pc.created_at')
|
||||
->limit(10)
|
||||
->select([
|
||||
'pc.id', 'pc.body', 'pc.created_at',
|
||||
'u.id as author_id', 'u.username as author_username', 'u.name as author_name',
|
||||
'up.avatar_hash as author_avatar_hash', 'up.signature as author_signature',
|
||||
])
|
||||
->get()
|
||||
->map(fn ($row) => (object) [
|
||||
'id' => $row->id,
|
||||
'body' => $row->body,
|
||||
'created_at' => $row->created_at,
|
||||
'author_id' => $row->author_id,
|
||||
'author_name' => $row->author_username ?? $row->author_name ?? 'Unknown',
|
||||
'author_profile_url' => '/@' . strtolower((string) ($row->author_username ?? $row->author_id)),
|
||||
'author_avatar' => AvatarUrl::forUser((int) $row->author_id, $row->author_avatar_hash, 50),
|
||||
'author_signature' => $row->author_signature,
|
||||
]);
|
||||
}
|
||||
|
||||
// ── Profile data ─────────────────────────────────────────────────────
|
||||
$profile = $user->profile;
|
||||
|
||||
// ── Country name (from old country_list table if available) ──────────
|
||||
$countryName = null;
|
||||
if ($profile?->country_code) {
|
||||
if (Schema::hasTable('country_list')) {
|
||||
$countryName = DB::table('country_list')
|
||||
->where('country_code', $profile->country_code)
|
||||
->value('country_name');
|
||||
}
|
||||
$countryName = $countryName ?? strtoupper((string) $profile->country_code);
|
||||
}
|
||||
|
||||
// ── Increment profile views (async-safe, ignore errors) ──────────────
|
||||
if (! $isOwner) {
|
||||
try {
|
||||
DB::table('user_statistics')
|
||||
->updateOrInsert(
|
||||
['user_id' => $user->id],
|
||||
['profile_views' => DB::raw('COALESCE(profile_views, 0) + 1'), 'updated_at' => now()]
|
||||
);
|
||||
} catch (\Throwable) {}
|
||||
}
|
||||
|
||||
return response()->view('legacy.profile', [
|
||||
'user' => $legacyUser,
|
||||
'artworks' => $artworks,
|
||||
'page_title' => 'Profile: ' . ($legacyUser->uname ?? ''),
|
||||
'page_canonical' => url('/@' . strtolower((string) ($user->username ?? ''))),
|
||||
'user' => $user,
|
||||
'profile' => $profile,
|
||||
'artworks' => $artworks,
|
||||
'featuredArtworks' => $featuredArtworks,
|
||||
'favourites' => $favourites,
|
||||
'stats' => $stats,
|
||||
'socialLinks' => $socialLinks,
|
||||
'followerCount' => $followerCount,
|
||||
'recentFollowers' => $recentFollowers,
|
||||
'viewerIsFollowing' => $viewerIsFollowing,
|
||||
'profileComments' => $profileComments,
|
||||
'countryName' => $countryName,
|
||||
'isOwner' => $isOwner,
|
||||
'page_title' => 'Profile: ' . ($user->username ?? $user->name ?? ''),
|
||||
'page_canonical' => url('/@' . strtolower((string) ($user->username ?? ''))),
|
||||
'page_meta_description' => 'View the profile of ' . ($user->username ?? $user->name) . ' on Skinbase.org — artworks, favourites and more.',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,6 +59,6 @@ class TodayDownloadsController extends Controller
|
||||
|
||||
$page_title = 'Today Downloaded Artworks';
|
||||
|
||||
return view('web.browse', ['page_title' => $page_title, 'artworks' => $paginator]);
|
||||
return view('web.downloads.today', ['page_title' => $page_title, 'artworks' => $paginator]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ class TodayInHistoryController extends Controller
|
||||
});
|
||||
}
|
||||
|
||||
return view('user.today-in-history', [
|
||||
return view('legacy.today-in-history', [
|
||||
'artworks' => $artworks,
|
||||
'page_title' => 'Popular on this day in history',
|
||||
]);
|
||||
|
||||
@@ -21,7 +21,6 @@ class TopAuthorsController extends Controller
|
||||
}
|
||||
|
||||
$sub = Artwork::query()
|
||||
->select('artworks.user_id')
|
||||
->join('artwork_stats', 'artwork_stats.artwork_id', '=', 'artworks.id')
|
||||
->where('artworks.is_public', true)
|
||||
->where('artworks.is_approved', true)
|
||||
@@ -52,6 +51,6 @@ class TopAuthorsController extends Controller
|
||||
|
||||
$page_title = 'Top Authors';
|
||||
|
||||
return view('user.top-authors', compact('page_title', 'authors', 'metric'));
|
||||
return view('web.authors.top', compact('page_title', 'authors', 'metric'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,6 +51,6 @@ class TopFavouritesController extends Controller
|
||||
|
||||
$page_title = 'Top Favourites';
|
||||
|
||||
return view('user.top-favourites', ['page_title' => $page_title, 'artworks' => $paginator]);
|
||||
return view('legacy.top-favourites', ['page_title' => $page_title, 'artworks' => $paginator]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ namespace App\Http\Controllers\Web;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Resources\ArtworkResource;
|
||||
use App\Models\Artwork;
|
||||
use App\Models\ArtworkComment;
|
||||
use App\Services\ThumbnailPresenter;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -102,6 +103,27 @@ final class ArtworkPageController extends Controller
|
||||
->values()
|
||||
->all();
|
||||
|
||||
$comments = ArtworkComment::with(['user.profile'])
|
||||
->where('artwork_id', $artwork->id)
|
||||
->where('is_approved', true)
|
||||
->orderBy('created_at')
|
||||
->limit(500)
|
||||
->get()
|
||||
->map(fn(ArtworkComment $c) => [
|
||||
'id' => $c->id,
|
||||
'content' => (string) $c->content,
|
||||
'created_at' => $c->created_at?->toIsoString(),
|
||||
'user' => [
|
||||
'id' => $c->user?->id,
|
||||
'name' => $c->user?->name,
|
||||
'username' => $c->user?->username,
|
||||
'profile_url' => $c->user?->username ? '/@' . $c->user->username : null,
|
||||
'avatar_url' => $c->user?->profile?->avatar_url,
|
||||
],
|
||||
])
|
||||
->values()
|
||||
->all();
|
||||
|
||||
return view('artworks.show', [
|
||||
'artwork' => $artwork,
|
||||
'artworkData' => $artworkData,
|
||||
@@ -111,6 +133,7 @@ final class ArtworkPageController extends Controller
|
||||
'presentSq' => $thumbSq,
|
||||
'meta' => $meta,
|
||||
'relatedItems' => $related,
|
||||
'comments' => $comments,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ use App\Models\Category;
|
||||
use App\Models\ContentType;
|
||||
use App\Models\Artwork;
|
||||
use App\Services\ArtworkService;
|
||||
use App\Services\ArtworkSearchService;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Pagination\AbstractPaginator;
|
||||
@@ -15,8 +16,17 @@ class BrowseGalleryController extends \App\Http\Controllers\Controller
|
||||
{
|
||||
private const CONTENT_TYPE_SLUGS = ['photography', 'wallpapers', 'skins', 'other'];
|
||||
|
||||
public function __construct(private ArtworkService $artworks)
|
||||
{
|
||||
private const SORT_MAP = [
|
||||
'latest' => 'created_at:desc',
|
||||
'popular' => 'views:desc',
|
||||
'liked' => 'likes:desc',
|
||||
'downloads' => 'downloads:desc',
|
||||
];
|
||||
|
||||
public function __construct(
|
||||
private ArtworkService $artworks,
|
||||
private ArtworkSearchService $search,
|
||||
) {
|
||||
}
|
||||
|
||||
public function browse(Request $request)
|
||||
@@ -24,7 +34,10 @@ class BrowseGalleryController extends \App\Http\Controllers\Controller
|
||||
$sort = (string) $request->query('sort', 'latest');
|
||||
$perPage = $this->resolvePerPage($request);
|
||||
|
||||
$artworks = $this->artworks->browsePublicArtworks($perPage, $sort);
|
||||
$artworks = Artwork::search('')->options([
|
||||
'filter' => 'is_public = true AND is_approved = true',
|
||||
'sort' => [self::SORT_MAP[$sort] ?? 'created_at:desc'],
|
||||
])->paginate($perPage);
|
||||
$seo = $this->buildPaginationSeo($request, url('/browse'), $artworks);
|
||||
|
||||
$mainCategories = $this->mainCategories();
|
||||
@@ -69,7 +82,10 @@ class BrowseGalleryController extends \App\Http\Controllers\Controller
|
||||
|
||||
$normalizedPath = trim((string) $path, '/');
|
||||
if ($normalizedPath === '') {
|
||||
$artworks = $this->artworks->getArtworksByContentType($contentSlug, $perPage, $sort);
|
||||
$artworks = Artwork::search('')->options([
|
||||
'filter' => 'is_public = true AND is_approved = true AND content_type = "' . $contentSlug . '"',
|
||||
'sort' => [self::SORT_MAP[$sort] ?? 'created_at:desc'],
|
||||
])->paginate($perPage);
|
||||
$seo = $this->buildPaginationSeo($request, url('/' . $contentSlug), $artworks);
|
||||
|
||||
return view('gallery.index', [
|
||||
@@ -98,7 +114,10 @@ class BrowseGalleryController extends \App\Http\Controllers\Controller
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$artworks = $this->artworks->getArtworksByCategoryPath(array_merge([$contentSlug], $segments), $perPage, $sort);
|
||||
$artworks = Artwork::search('')->options([
|
||||
'filter' => 'is_public = true AND is_approved = true AND category = "' . $category->slug . '"',
|
||||
'sort' => [self::SORT_MAP[$sort] ?? 'created_at:desc'],
|
||||
])->paginate($perPage);
|
||||
$seo = $this->buildPaginationSeo($request, url('/' . $contentSlug . '/' . strtolower($category->full_slug_path)), $artworks);
|
||||
|
||||
$subcategories = $category->children()->orderBy('sort_order')->orderBy('name')->get();
|
||||
|
||||
@@ -17,6 +17,11 @@ class CategoryController extends Controller
|
||||
$this->artworkService = $artworkService;
|
||||
}
|
||||
|
||||
public function index(Request $request)
|
||||
{
|
||||
return $this->browseCategories();
|
||||
}
|
||||
|
||||
public function show(Request $request, $id, $slug = null, $group = null)
|
||||
{
|
||||
$path = trim($request->path(), '/');
|
||||
|
||||
@@ -27,17 +27,20 @@ class HomeController extends Controller
|
||||
|
||||
$featuredResult = $this->artworks->getFeaturedArtworks(null, 39);
|
||||
if ($featuredResult instanceof \Illuminate\Pagination\LengthAwarePaginator) {
|
||||
$featured = $featuredResult->getCollection()->first();
|
||||
$featuredCollection = $featuredResult->getCollection();
|
||||
$featured = $featuredCollection->get(0);
|
||||
$memberFeatured = $featuredCollection->get(1);
|
||||
} elseif (is_array($featuredResult)) {
|
||||
$featured = $featuredResult[0] ?? null;
|
||||
$memberFeatured = $featuredResult[1] ?? null;
|
||||
} elseif ($featuredResult instanceof Collection) {
|
||||
$featured = $featuredResult->first();
|
||||
$featured = $featuredResult->get(0);
|
||||
$memberFeatured = $featuredResult->get(1);
|
||||
} else {
|
||||
$featured = $featuredResult;
|
||||
$memberFeatured = null;
|
||||
}
|
||||
|
||||
$memberFeatured = $featured;
|
||||
|
||||
$latestUploads = $this->artworks->getLatestArtworks(20);
|
||||
|
||||
// Forum news (prefer migrated legacy news category id 2876, fallback to slug)
|
||||
|
||||
49
app/Http/Controllers/Web/SearchController.php
Normal file
49
app/Http/Controllers/Web/SearchController.php
Normal file
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Controllers\Web;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Services\ArtworkSearchService;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
|
||||
final class SearchController extends Controller
|
||||
{
|
||||
public function __construct(private readonly ArtworkSearchService $search) {}
|
||||
|
||||
public function index(Request $request): View
|
||||
{
|
||||
$q = trim((string) $request->query('q', ''));
|
||||
$sort = $request->query('sort', 'latest');
|
||||
|
||||
$sortMap = [
|
||||
'popular' => 'views:desc',
|
||||
'likes' => 'likes:desc',
|
||||
'latest' => 'created_at:desc',
|
||||
'downloads' => 'downloads:desc',
|
||||
];
|
||||
|
||||
$artworks = null;
|
||||
$popular = collect();
|
||||
|
||||
if ($q !== '') {
|
||||
$artworks = $this->search->search($q, [
|
||||
'sort' => ($sortMap[$sort] ?? 'created_at:desc'),
|
||||
]);
|
||||
} else {
|
||||
$popular = $this->search->popular(16)->getCollection();
|
||||
}
|
||||
|
||||
return view('search.index', [
|
||||
'q' => $q,
|
||||
'sort' => $sort,
|
||||
'artworks' => $artworks ?? collect()->paginate(0),
|
||||
'popular' => $popular,
|
||||
'page_title' => $q !== '' ? 'Search: ' . $q . ' — Skinbase' : 'Search — Skinbase',
|
||||
'page_meta_description' => 'Search Skinbase for artworks, photography, wallpapers and skins.',
|
||||
'page_robots' => 'noindex,follow',
|
||||
]);
|
||||
}
|
||||
}
|
||||
47
app/Http/Controllers/Web/SectionsController.php
Normal file
47
app/Http/Controllers/Web/SectionsController.php
Normal file
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Web;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\ContentType;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class SectionsController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
// Load all content types with full category tree (roots + children)
|
||||
$contentTypes = ContentType::with([
|
||||
'rootCategories' => function ($q) {
|
||||
$q->active()
|
||||
->withCount(['artworks as artwork_count'])
|
||||
->orderBy('sort_order')
|
||||
->orderBy('name');
|
||||
},
|
||||
'rootCategories.children' => function ($q) {
|
||||
$q->active()
|
||||
->withCount(['artworks as artwork_count'])
|
||||
->orderBy('sort_order')
|
||||
->orderBy('name');
|
||||
},
|
||||
])->orderBy('id')->get();
|
||||
|
||||
// Total artwork counts per content type via a single aggregation query
|
||||
$artworkCountsByType = DB::table('artworks')
|
||||
->join('artwork_category', 'artworks.id', '=', 'artwork_category.artwork_id')
|
||||
->join('categories', 'artwork_category.category_id', '=', 'categories.id')
|
||||
->where('artworks.is_approved', true)
|
||||
->where('artworks.is_public', true)
|
||||
->whereNull('artworks.deleted_at')
|
||||
->select('categories.content_type_id', DB::raw('COUNT(DISTINCT artworks.id) as total'))
|
||||
->groupBy('categories.content_type_id')
|
||||
->pluck('total', 'content_type_id');
|
||||
|
||||
return view('web.sections', [
|
||||
'contentTypes' => $contentTypes,
|
||||
'artworkCountsByType' => $artworkCountsByType,
|
||||
'page_title' => 'Browse Sections',
|
||||
'page_meta_description' => 'Browse all artwork sections on Skinbase — Photography, Wallpapers, Skins and more.',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -6,24 +6,57 @@ namespace App\Http\Controllers\Web;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Tag;
|
||||
use App\Services\ArtworkSearchService;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
|
||||
final class TagController extends Controller
|
||||
{
|
||||
public function show(Tag $tag): View
|
||||
public function __construct(private readonly ArtworkSearchService $search) {}
|
||||
|
||||
public function show(Tag $tag, Request $request): View
|
||||
{
|
||||
$artworks = $tag->artworks()
|
||||
->public()
|
||||
->published()
|
||||
->leftJoin('artwork_stats', 'artwork_stats.artwork_id', '=', 'artworks.id')
|
||||
->orderByDesc('artwork_stats.views')
|
||||
->orderByDesc('artworks.published_at')
|
||||
->select('artworks.*')
|
||||
->paginate(24);
|
||||
$sort = $request->query('sort', 'popular'); // popular | latest | downloads
|
||||
$perPage = min((int) $request->query('per_page', 24), 100);
|
||||
|
||||
// Convert sort param to Meili sort expression
|
||||
$sortMap = [
|
||||
'popular' => 'views:desc',
|
||||
'likes' => 'likes:desc',
|
||||
'latest' => 'created_at:desc',
|
||||
'downloads' => 'downloads:desc',
|
||||
];
|
||||
$meiliSort = $sortMap[$sort] ?? 'views:desc';
|
||||
|
||||
$artworks = \App\Models\Artwork::search('')
|
||||
->options([
|
||||
'filter' => 'is_public = true AND is_approved = true AND tags = "' . addslashes($tag->slug) . '"',
|
||||
'sort' => [$meiliSort],
|
||||
])
|
||||
->paginate($perPage)
|
||||
->appends(['sort' => $sort]);
|
||||
|
||||
// Eager-load relations needed by the artwork-card component.
|
||||
// Scout returns bare Eloquent models; without this, each card triggers N+1 queries.
|
||||
$artworks->getCollection()->loadMissing(['user.profile']);
|
||||
|
||||
// OG image: first result's thumbnail
|
||||
$ogImage = null;
|
||||
if ($artworks->count() > 0) {
|
||||
$first = $artworks->getCollection()->first();
|
||||
$ogImage = $first?->thumbUrl('md');
|
||||
}
|
||||
|
||||
return view('tags.show', [
|
||||
'tag' => $tag,
|
||||
'tag' => $tag,
|
||||
'artworks' => $artworks,
|
||||
'sort' => $sort,
|
||||
'ogImage' => $ogImage,
|
||||
'page_title' => 'Artworks tagged "' . $tag->name . '" — Skinbase',
|
||||
'page_meta_description' => 'Browse all Skinbase artworks tagged "' . $tag->name . '". Discover photography, wallpapers and skins.',
|
||||
'page_canonical' => route('tags.show', $tag->slug),
|
||||
'page_robots' => 'index,follow',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,17 +5,12 @@ declare(strict_types=1);
|
||||
namespace App\Http\Requests\Tags;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
final class PopularTagsRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
if (! $this->user()) {
|
||||
throw new NotFoundHttpException();
|
||||
}
|
||||
|
||||
return true;
|
||||
return true; // public endpoint
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
|
||||
@@ -5,17 +5,12 @@ declare(strict_types=1);
|
||||
namespace App\Http\Requests\Tags;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
final class TagSearchRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
if (! $this->user()) {
|
||||
throw new NotFoundHttpException();
|
||||
}
|
||||
|
||||
return true;
|
||||
return true; // public endpoint
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
|
||||
42
app/Jobs/DeleteArtworkFromIndexJob.php
Normal file
42
app/Jobs/DeleteArtworkFromIndexJob.php
Normal file
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Models\Artwork;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* Queued job: remove a single artwork document from Meilisearch.
|
||||
*/
|
||||
class DeleteArtworkFromIndexJob implements ShouldQueue
|
||||
{
|
||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||
|
||||
public int $tries = 3;
|
||||
public int $timeout = 30;
|
||||
|
||||
public function __construct(public readonly int $artworkId) {}
|
||||
|
||||
public function handle(): void
|
||||
{
|
||||
// Create a bare model instance just to call unsearchable() with the right ID.
|
||||
$artwork = new Artwork();
|
||||
$artwork->id = $this->artworkId;
|
||||
$artwork->unsearchable();
|
||||
}
|
||||
|
||||
public function failed(\Throwable $e): void
|
||||
{
|
||||
Log::error('DeleteArtworkFromIndexJob failed', [
|
||||
'artwork_id' => $this->artworkId,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
52
app/Jobs/IndexArtworkJob.php
Normal file
52
app/Jobs/IndexArtworkJob.php
Normal file
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Models\Artwork;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* Queued job: index (or re-index) a single Artwork in Meilisearch.
|
||||
*/
|
||||
class IndexArtworkJob implements ShouldQueue
|
||||
{
|
||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||
|
||||
public int $tries = 3;
|
||||
public int $timeout = 30;
|
||||
|
||||
public function __construct(public readonly int $artworkId) {}
|
||||
|
||||
public function handle(): void
|
||||
{
|
||||
$artwork = Artwork::with(['user', 'tags', 'categories', 'stats', 'awardStat'])
|
||||
->find($this->artworkId);
|
||||
|
||||
if (! $artwork) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (! $artwork->is_public || ! $artwork->is_approved || ! $artwork->published_at) {
|
||||
// Not public/approved — ensure it is removed from the index.
|
||||
$artwork->unsearchable();
|
||||
return;
|
||||
}
|
||||
|
||||
$artwork->searchable();
|
||||
}
|
||||
|
||||
public function failed(\Throwable $e): void
|
||||
{
|
||||
Log::error('IndexArtworkJob failed', [
|
||||
'artwork_id' => $this->artworkId,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
use App\Services\ThumbnailService;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Laravel\Scout\Searchable;
|
||||
|
||||
/**
|
||||
* App\Models\Artwork
|
||||
@@ -23,7 +24,7 @@ use Illuminate\Support\Facades\DB;
|
||||
*/
|
||||
class Artwork extends Model
|
||||
{
|
||||
use HasFactory, SoftDeletes;
|
||||
use HasFactory, SoftDeletes, Searchable;
|
||||
|
||||
protected $table = 'artworks';
|
||||
|
||||
@@ -173,6 +174,77 @@ class Artwork extends Model
|
||||
return $this->hasMany(ArtworkFeature::class, 'artwork_id');
|
||||
}
|
||||
|
||||
public function awards(): HasMany
|
||||
{
|
||||
return $this->hasMany(ArtworkAward::class);
|
||||
}
|
||||
|
||||
public function awardStat(): HasOne
|
||||
{
|
||||
return $this->hasOne(ArtworkAwardStat::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the Meilisearch document for this artwork.
|
||||
* Includes all fields required for search, filtering, sorting, and display.
|
||||
*/
|
||||
public function toSearchableArray(): array
|
||||
{
|
||||
$this->loadMissing(['user', 'tags', 'categories.contentType', 'stats', 'awardStat']);
|
||||
|
||||
$stat = $this->stats;
|
||||
$awardStat = $this->awardStat;
|
||||
|
||||
// Orientation derived from pixel dimensions
|
||||
$orientation = 'square';
|
||||
if ($this->width && $this->height) {
|
||||
if ($this->width > $this->height) {
|
||||
$orientation = 'landscape';
|
||||
} elseif ($this->height > $this->width) {
|
||||
$orientation = 'portrait';
|
||||
}
|
||||
}
|
||||
|
||||
// Resolution string e.g. "1920x1080"
|
||||
$resolution = ($this->width && $this->height)
|
||||
? $this->width . 'x' . $this->height
|
||||
: '';
|
||||
|
||||
// Primary category slug (first attached category)
|
||||
$primaryCategory = $this->categories->first();
|
||||
$category = $primaryCategory?->slug ?? '';
|
||||
$content_type = $primaryCategory?->contentType?->slug ?? '';
|
||||
|
||||
// Tag slugs array
|
||||
$tags = $this->tags->pluck('slug')->values()->all();
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'slug' => $this->slug,
|
||||
'title' => $this->title,
|
||||
'description' => (string) ($this->description ?? ''),
|
||||
'author_id' => $this->user_id,
|
||||
'author_name' => $this->user?->name ?? 'Skinbase',
|
||||
'category' => $category,
|
||||
'content_type' => $content_type,
|
||||
'tags' => $tags,
|
||||
'resolution' => $resolution,
|
||||
'orientation' => $orientation,
|
||||
'downloads' => (int) ($stat?->downloads ?? 0),
|
||||
'likes' => (int) ($stat?->favorites ?? 0),
|
||||
'views' => (int) ($stat?->views ?? 0),
|
||||
'created_at' => $this->published_at?->toDateString() ?? $this->created_at?->toDateString() ?? '',
|
||||
'is_public' => (bool) $this->is_public,
|
||||
'is_approved' => (bool) $this->is_approved,
|
||||
'awards' => [
|
||||
'gold' => $awardStat?->gold_count ?? 0,
|
||||
'silver' => $awardStat?->silver_count ?? 0,
|
||||
'bronze' => $awardStat?->bronze_count ?? 0,
|
||||
'score' => $awardStat?->score_total ?? 0,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
// Scopes
|
||||
public function scopePublic(Builder $query): Builder
|
||||
{
|
||||
|
||||
44
app/Models/ArtworkAward.php
Normal file
44
app/Models/ArtworkAward.php
Normal file
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class ArtworkAward extends Model
|
||||
{
|
||||
protected $table = 'artwork_awards';
|
||||
|
||||
protected $fillable = [
|
||||
'artwork_id',
|
||||
'user_id',
|
||||
'medal',
|
||||
'weight',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'artwork_id' => 'integer',
|
||||
'user_id' => 'integer',
|
||||
'weight' => 'integer',
|
||||
];
|
||||
|
||||
public const MEDALS = ['gold', 'silver', 'bronze'];
|
||||
|
||||
public const WEIGHTS = [
|
||||
'gold' => 3,
|
||||
'silver' => 2,
|
||||
'bronze' => 1,
|
||||
];
|
||||
|
||||
public function artwork(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Artwork::class);
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
}
|
||||
40
app/Models/ArtworkAwardStat.php
Normal file
40
app/Models/ArtworkAwardStat.php
Normal file
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class ArtworkAwardStat extends Model
|
||||
{
|
||||
protected $table = 'artwork_award_stats';
|
||||
|
||||
public $primaryKey = 'artwork_id';
|
||||
public $incrementing = false;
|
||||
public $timestamps = false;
|
||||
|
||||
protected $fillable = [
|
||||
'artwork_id',
|
||||
'gold_count',
|
||||
'silver_count',
|
||||
'bronze_count',
|
||||
'score_total',
|
||||
'updated_at',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'artwork_id' => 'integer',
|
||||
'gold_count' => 'integer',
|
||||
'silver_count' => 'integer',
|
||||
'bronze_count' => 'integer',
|
||||
'score_total' => 'integer',
|
||||
'updated_at' => 'datetime',
|
||||
];
|
||||
|
||||
public function artwork(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Artwork::class);
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ class ArtworkComment extends Model
|
||||
protected $table = 'artwork_comments';
|
||||
|
||||
protected $fillable = [
|
||||
'legacy_id',
|
||||
'artwork_id',
|
||||
'user_id',
|
||||
'content',
|
||||
|
||||
47
app/Models/ProfileComment.php
Normal file
47
app/Models/ProfileComment.php
Normal file
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class ProfileComment extends Model
|
||||
{
|
||||
protected $table = 'profile_comments';
|
||||
|
||||
protected $fillable = [
|
||||
'profile_user_id',
|
||||
'author_user_id',
|
||||
'body',
|
||||
'is_active',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'is_active' => 'boolean',
|
||||
'created_at' => 'datetime',
|
||||
'updated_at' => 'datetime',
|
||||
];
|
||||
|
||||
/** Profile owner */
|
||||
public function profileUser(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'profile_user_id');
|
||||
}
|
||||
|
||||
/** Comment author */
|
||||
public function author(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'author_user_id');
|
||||
}
|
||||
|
||||
public function authorProfile(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(UserProfile::class, 'author_user_id', 'user_id');
|
||||
}
|
||||
|
||||
/** Scope: only active (not removed) comments */
|
||||
public function scopeActive($query)
|
||||
{
|
||||
return $query->where('is_active', true);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ namespace App\Models;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
final class Tag extends Model
|
||||
{
|
||||
@@ -32,6 +33,11 @@ final class Tag extends Model
|
||||
->withPivot(['source', 'confidence']);
|
||||
}
|
||||
|
||||
public function synonyms(): HasMany
|
||||
{
|
||||
return $this->hasMany(TagSynonym::class);
|
||||
}
|
||||
|
||||
public function getRouteKeyName(): string
|
||||
{
|
||||
return 'slug';
|
||||
|
||||
25
app/Models/TagSynonym.php
Normal file
25
app/Models/TagSynonym.php
Normal file
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
final class TagSynonym extends Model
|
||||
{
|
||||
public $timestamps = false;
|
||||
|
||||
protected $table = 'tag_synonyms';
|
||||
|
||||
protected $fillable = [
|
||||
'tag_id',
|
||||
'synonym',
|
||||
];
|
||||
|
||||
public function tag(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tag::class);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ namespace App\Models;
|
||||
|
||||
// use Illuminate\Contracts\Auth\MustVerifyEmail;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
@@ -73,6 +74,38 @@ class User extends Authenticatable
|
||||
return $this->hasOne(UserProfile::class, 'user_id');
|
||||
}
|
||||
|
||||
public function statistics(): HasOne
|
||||
{
|
||||
return $this->hasOne(UserStatistic::class, 'user_id');
|
||||
}
|
||||
|
||||
/** Users that follow this user */
|
||||
public function followers(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(
|
||||
User::class,
|
||||
'user_followers',
|
||||
'user_id',
|
||||
'follower_id'
|
||||
)->withPivot('created_at');
|
||||
}
|
||||
|
||||
/** Users that this user follows */
|
||||
public function following(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(
|
||||
User::class,
|
||||
'user_followers',
|
||||
'follower_id',
|
||||
'user_id'
|
||||
)->withPivot('created_at');
|
||||
}
|
||||
|
||||
public function profileComments(): HasMany
|
||||
{
|
||||
return $this->hasMany(ProfileComment::class, 'profile_user_id');
|
||||
}
|
||||
|
||||
public function hasRole(string $role): bool
|
||||
{
|
||||
return strtolower((string) ($this->role ?? '')) === strtolower($role);
|
||||
|
||||
37
app/Models/UserFollower.php
Normal file
37
app/Models/UserFollower.php
Normal file
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class UserFollower extends Model
|
||||
{
|
||||
protected $table = 'user_followers';
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
protected $fillable = [
|
||||
'user_id',
|
||||
'follower_id',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'created_at' => 'datetime',
|
||||
];
|
||||
|
||||
const CREATED_AT = 'created_at';
|
||||
const UPDATED_AT = null;
|
||||
|
||||
/** The user being followed */
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'user_id');
|
||||
}
|
||||
|
||||
/** The user who is following */
|
||||
public function follower(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'follower_id');
|
||||
}
|
||||
}
|
||||
30
app/Models/UserStatistic.php
Normal file
30
app/Models/UserStatistic.php
Normal file
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class UserStatistic extends Model
|
||||
{
|
||||
protected $table = 'user_statistics';
|
||||
protected $primaryKey = 'user_id';
|
||||
public $incrementing = false;
|
||||
protected $keyType = 'int';
|
||||
|
||||
protected $fillable = [
|
||||
'user_id',
|
||||
'uploads',
|
||||
'downloads',
|
||||
'pageviews',
|
||||
'awards',
|
||||
'profile_views',
|
||||
];
|
||||
|
||||
public $timestamps = true;
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'user_id');
|
||||
}
|
||||
}
|
||||
40
app/Observers/ArtworkAwardObserver.php
Normal file
40
app/Observers/ArtworkAwardObserver.php
Normal file
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Observers;
|
||||
|
||||
use App\Models\ArtworkAward;
|
||||
use App\Services\ArtworkAwardService;
|
||||
|
||||
class ArtworkAwardObserver
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ArtworkAwardService $service
|
||||
) {}
|
||||
|
||||
public function created(ArtworkAward $award): void
|
||||
{
|
||||
$this->refresh($award);
|
||||
}
|
||||
|
||||
public function updated(ArtworkAward $award): void
|
||||
{
|
||||
$this->refresh($award);
|
||||
}
|
||||
|
||||
public function deleted(ArtworkAward $award): void
|
||||
{
|
||||
$this->refresh($award);
|
||||
}
|
||||
|
||||
private function refresh(ArtworkAward $award): void
|
||||
{
|
||||
$this->service->recalcStats($award->artwork_id);
|
||||
|
||||
$artwork = $award->artwork;
|
||||
if ($artwork) {
|
||||
$this->service->syncToSearch($artwork);
|
||||
}
|
||||
}
|
||||
}
|
||||
56
app/Observers/ArtworkObserver.php
Normal file
56
app/Observers/ArtworkObserver.php
Normal file
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Observers;
|
||||
|
||||
use App\Models\Artwork;
|
||||
use App\Services\ArtworkSearchIndexer;
|
||||
|
||||
/**
|
||||
* Syncs artwork documents to Meilisearch on every relevant model event.
|
||||
*
|
||||
* All operations are dispatched to the queue — no blocking calls.
|
||||
*/
|
||||
class ArtworkObserver
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ArtworkSearchIndexer $indexer
|
||||
) {}
|
||||
|
||||
/** New artwork created — index once published and approved. */
|
||||
public function created(Artwork $artwork): void
|
||||
{
|
||||
$this->indexer->index($artwork);
|
||||
}
|
||||
|
||||
/** Artwork updated — covers publish, approval, metadata changes. */
|
||||
public function updated(Artwork $artwork): void
|
||||
{
|
||||
// When soft-deleted, remove from index immediately.
|
||||
if ($artwork->isDirty('deleted_at') && $artwork->deleted_at !== null) {
|
||||
$this->indexer->delete($artwork->id);
|
||||
return;
|
||||
}
|
||||
|
||||
$this->indexer->update($artwork);
|
||||
}
|
||||
|
||||
/** Soft delete — remove from search. */
|
||||
public function deleted(Artwork $artwork): void
|
||||
{
|
||||
$this->indexer->delete($artwork->id);
|
||||
}
|
||||
|
||||
/** Force delete — ensure removal from index. */
|
||||
public function forceDeleted(Artwork $artwork): void
|
||||
{
|
||||
$this->indexer->delete($artwork->id);
|
||||
}
|
||||
|
||||
/** Restored from soft-delete — re-index. */
|
||||
public function restored(Artwork $artwork): void
|
||||
{
|
||||
$this->indexer->index($artwork);
|
||||
}
|
||||
}
|
||||
69
app/Policies/ArtworkAwardPolicy.php
Normal file
69
app/Policies/ArtworkAwardPolicy.php
Normal file
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Models\ArtworkAward;
|
||||
use App\Models\Artwork;
|
||||
use App\Models\User;
|
||||
|
||||
class ArtworkAwardPolicy
|
||||
{
|
||||
/**
|
||||
* Admins bypass all checks.
|
||||
*/
|
||||
public function before(User $user, string $ability): ?bool
|
||||
{
|
||||
if (method_exists($user, 'isAdmin') && $user->isAdmin()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Any authenticated user with a mature account may award any artwork
|
||||
* that isn't their own.
|
||||
* Returns false (→ 403 or 404 based on caller) when the check fails.
|
||||
*/
|
||||
public function award(User $user, Artwork $artwork): bool
|
||||
{
|
||||
if (! $artwork->is_public || ! $artwork->is_approved) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($artwork->user_id === $user->id) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->accountIsMature($user);
|
||||
}
|
||||
|
||||
/**
|
||||
* The user may change a medal they already placed.
|
||||
*/
|
||||
public function change(User $user, ArtworkAward $award): bool
|
||||
{
|
||||
return $user->id === $award->user_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* The user may remove a medal they already placed.
|
||||
*/
|
||||
public function remove(User $user, ArtworkAward $award): bool
|
||||
{
|
||||
return $user->id === $award->user_id;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private function accountIsMature(User $user): bool
|
||||
{
|
||||
if (! $user->created_at) {
|
||||
return true; // cannot verify — allow
|
||||
}
|
||||
|
||||
return $user->created_at->diffInDays(now()) >= 7;
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,10 @@ use Illuminate\Cache\RateLimiting\Limit;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use App\Models\ArtworkAward;
|
||||
use App\Observers\ArtworkAwardObserver;
|
||||
use App\Models\Artwork;
|
||||
use App\Observers\ArtworkObserver;
|
||||
use App\Services\Upload\Contracts\UploadDraftServiceInterface;
|
||||
use App\Services\Upload\UploadDraftService;
|
||||
use Illuminate\Support\Facades\View;
|
||||
@@ -37,6 +41,9 @@ class AppServiceProvider extends ServiceProvider
|
||||
$this->configureUploadRateLimiters();
|
||||
$this->configureMailFailureLogging();
|
||||
|
||||
ArtworkAward::observe(ArtworkAwardObserver::class);
|
||||
Artwork::observe(ArtworkObserver::class);
|
||||
|
||||
// Provide toolbar counts and user info to layout views (port of legacy toolbar logic)
|
||||
View::composer(['layouts.nova', 'layouts.nova.*'], function ($view) {
|
||||
$uploadCount = $favCount = $msgCount = $noticeCount = 0;
|
||||
|
||||
@@ -4,7 +4,9 @@ namespace App\Providers;
|
||||
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use App\Models\Artwork;
|
||||
use App\Models\ArtworkAward;
|
||||
use App\Policies\ArtworkPolicy;
|
||||
use App\Policies\ArtworkAwardPolicy;
|
||||
|
||||
class AuthServiceProvider extends ServiceProvider
|
||||
{
|
||||
@@ -14,7 +16,8 @@ class AuthServiceProvider extends ServiceProvider
|
||||
* @var array<class-string, class-string>
|
||||
*/
|
||||
protected $policies = [
|
||||
Artwork::class => ArtworkPolicy::class,
|
||||
Artwork::class => ArtworkPolicy::class,
|
||||
ArtworkAward::class => ArtworkAwardPolicy::class,
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
132
app/Services/ArtworkAwardService.php
Normal file
132
app/Services/ArtworkAwardService.php
Normal file
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Jobs\IndexArtworkJob;
|
||||
use App\Models\Artwork;
|
||||
use App\Models\ArtworkAward;
|
||||
use App\Models\ArtworkAwardStat;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class ArtworkAwardService
|
||||
{
|
||||
/**
|
||||
* Award an artwork with the given medal.
|
||||
* Throws ValidationException if the user already awarded this artwork.
|
||||
*/
|
||||
public function award(Artwork $artwork, User $user, string $medal): ArtworkAward
|
||||
{
|
||||
$this->validateMedal($medal);
|
||||
|
||||
$existing = ArtworkAward::where('artwork_id', $artwork->id)
|
||||
->where('user_id', $user->id)
|
||||
->first();
|
||||
|
||||
if ($existing) {
|
||||
throw ValidationException::withMessages([
|
||||
'medal' => 'You have already awarded this artwork. Use change to update.',
|
||||
]);
|
||||
}
|
||||
|
||||
$award = ArtworkAward::create([
|
||||
'artwork_id' => $artwork->id,
|
||||
'user_id' => $user->id,
|
||||
'medal' => $medal,
|
||||
'weight' => ArtworkAward::WEIGHTS[$medal],
|
||||
]);
|
||||
|
||||
$this->recalcStats($artwork->id);
|
||||
$this->syncToSearch($artwork);
|
||||
|
||||
return $award;
|
||||
}
|
||||
|
||||
/**
|
||||
* Change an existing award medal for a user/artwork pair.
|
||||
*/
|
||||
public function changeAward(Artwork $artwork, User $user, string $medal): ArtworkAward
|
||||
{
|
||||
$this->validateMedal($medal);
|
||||
|
||||
$award = ArtworkAward::where('artwork_id', $artwork->id)
|
||||
->where('user_id', $user->id)
|
||||
->firstOrFail();
|
||||
|
||||
$award->update([
|
||||
'medal' => $medal,
|
||||
'weight' => ArtworkAward::WEIGHTS[$medal],
|
||||
]);
|
||||
|
||||
$this->recalcStats($artwork->id);
|
||||
$this->syncToSearch($artwork);
|
||||
|
||||
return $award->fresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove an award for a user/artwork pair.
|
||||
*/
|
||||
public function removeAward(Artwork $artwork, User $user): void
|
||||
{
|
||||
ArtworkAward::where('artwork_id', $artwork->id)
|
||||
->where('user_id', $user->id)
|
||||
->delete();
|
||||
|
||||
$this->recalcStats($artwork->id);
|
||||
$this->syncToSearch($artwork);
|
||||
}
|
||||
|
||||
/**
|
||||
* Recalculate and persist stats for the given artwork.
|
||||
*/
|
||||
public function recalcStats(int $artworkId): ArtworkAwardStat
|
||||
{
|
||||
$counts = DB::table('artwork_awards')
|
||||
->where('artwork_id', $artworkId)
|
||||
->selectRaw('
|
||||
SUM(medal = \'gold\') AS gold_count,
|
||||
SUM(medal = \'silver\') AS silver_count,
|
||||
SUM(medal = \'bronze\') AS bronze_count
|
||||
')
|
||||
->first();
|
||||
|
||||
$gold = (int) ($counts->gold_count ?? 0);
|
||||
$silver = (int) ($counts->silver_count ?? 0);
|
||||
$bronze = (int) ($counts->bronze_count ?? 0);
|
||||
$score = ($gold * 3) + ($silver * 2) + ($bronze * 1);
|
||||
|
||||
$stat = ArtworkAwardStat::updateOrCreate(
|
||||
['artwork_id' => $artworkId],
|
||||
[
|
||||
'gold_count' => $gold,
|
||||
'silver_count' => $silver,
|
||||
'bronze_count' => $bronze,
|
||||
'score_total' => $score,
|
||||
'updated_at' => now(),
|
||||
]
|
||||
);
|
||||
|
||||
return $stat;
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue a non-blocking reindex for the artwork after award stats change.
|
||||
*/
|
||||
public function syncToSearch(Artwork $artwork): void
|
||||
{
|
||||
IndexArtworkJob::dispatch($artwork->id);
|
||||
}
|
||||
|
||||
private function validateMedal(string $medal): void
|
||||
{
|
||||
if (! in_array($medal, ArtworkAward::MEDALS, true)) {
|
||||
throw ValidationException::withMessages([
|
||||
'medal' => 'Invalid medal. Must be gold, silver, or bronze.',
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
61
app/Services/ArtworkSearchIndexer.php
Normal file
61
app/Services/ArtworkSearchIndexer.php
Normal file
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Jobs\DeleteArtworkFromIndexJob;
|
||||
use App\Jobs\IndexArtworkJob;
|
||||
use App\Models\Artwork;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* Manages Meilisearch index operations for artworks.
|
||||
*
|
||||
* All write operations are dispatched to queues — never block requests.
|
||||
*/
|
||||
final class ArtworkSearchIndexer
|
||||
{
|
||||
/**
|
||||
* Queue an artwork for indexing (insert or update).
|
||||
*/
|
||||
public function index(Artwork $artwork): void
|
||||
{
|
||||
IndexArtworkJob::dispatch($artwork->id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue an artwork for re-indexing after an update.
|
||||
*/
|
||||
public function update(Artwork $artwork): void
|
||||
{
|
||||
IndexArtworkJob::dispatch($artwork->id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue removal of an artwork from the index.
|
||||
*/
|
||||
public function delete(int $id): void
|
||||
{
|
||||
DeleteArtworkFromIndexJob::dispatch($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebuild the entire artworks index in background chunks.
|
||||
* Run via: php artisan artworks:search-rebuild
|
||||
*/
|
||||
public function rebuildAll(int $chunkSize = 500): void
|
||||
{
|
||||
Artwork::with(['user', 'tags', 'categories', 'stats', 'awardStat'])
|
||||
->public()
|
||||
->published()
|
||||
->orderBy('id')
|
||||
->chunk($chunkSize, function ($artworks): void {
|
||||
foreach ($artworks as $artwork) {
|
||||
IndexArtworkJob::dispatch($artwork->id);
|
||||
}
|
||||
});
|
||||
|
||||
Log::info('ArtworkSearchIndexer::rebuildAll — jobs dispatched');
|
||||
}
|
||||
}
|
||||
191
app/Services/ArtworkSearchService.php
Normal file
191
app/Services/ArtworkSearchService.php
Normal file
@@ -0,0 +1,191 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Artwork;
|
||||
use App\Models\Tag;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
|
||||
/**
|
||||
* High-level search API powered by Meilisearch via Laravel Scout.
|
||||
*
|
||||
* No Meili calls in controllers — always go through this service.
|
||||
*/
|
||||
final class ArtworkSearchService
|
||||
{
|
||||
private const BASE_FILTER = 'is_public = true AND is_approved = true';
|
||||
private const CACHE_TTL = 300; // 5 minutes
|
||||
|
||||
/**
|
||||
* Full-text search with optional filters.
|
||||
*
|
||||
* Supported $filters keys:
|
||||
* tags array<string> — tag slugs (AND match)
|
||||
* category string
|
||||
* orientation string — landscape | portrait | square
|
||||
* resolution string — e.g. "1920x1080"
|
||||
* author_id int
|
||||
* sort string — created_at|downloads|likes|views (suffix :asc or :desc)
|
||||
*/
|
||||
public function search(string $q, array $filters = [], int $perPage = 24): LengthAwarePaginator
|
||||
{
|
||||
$filterParts = [self::BASE_FILTER];
|
||||
$sort = [];
|
||||
|
||||
if (! empty($filters['tags'])) {
|
||||
foreach ((array) $filters['tags'] as $tag) {
|
||||
$filterParts[] = 'tags = "' . addslashes((string) $tag) . '"';
|
||||
}
|
||||
}
|
||||
|
||||
if (! empty($filters['category'])) {
|
||||
$filterParts[] = 'category = "' . addslashes((string) $filters['category']) . '"';
|
||||
}
|
||||
|
||||
if (! empty($filters['orientation'])) {
|
||||
$filterParts[] = 'orientation = "' . addslashes((string) $filters['orientation']) . '"';
|
||||
}
|
||||
|
||||
if (! empty($filters['resolution'])) {
|
||||
$filterParts[] = 'resolution = "' . addslashes((string) $filters['resolution']) . '"';
|
||||
}
|
||||
|
||||
if (! empty($filters['author_id'])) {
|
||||
$filterParts[] = 'author_id = ' . (int) $filters['author_id'];
|
||||
}
|
||||
|
||||
if (! empty($filters['sort'])) {
|
||||
[$field, $dir] = $this->parseSort((string) $filters['sort']);
|
||||
if ($field) {
|
||||
$sort[] = $field . ':' . $dir;
|
||||
}
|
||||
}
|
||||
|
||||
$options = ['filter' => implode(' AND ', $filterParts)];
|
||||
if ($sort !== []) {
|
||||
$options['sort'] = $sort;
|
||||
}
|
||||
|
||||
return Artwork::search($q ?: '')
|
||||
->options($options)
|
||||
->paginate($perPage);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load artworks for a tag page, sorted by views + likes descending.
|
||||
*/
|
||||
public function byTag(string $slug, int $perPage = 24): LengthAwarePaginator
|
||||
{
|
||||
$tag = Tag::where('slug', $slug)->first();
|
||||
if (! $tag) {
|
||||
return $this->emptyPaginator($perPage);
|
||||
}
|
||||
|
||||
$cacheKey = "search.tag.{$slug}.page." . request()->get('page', 1);
|
||||
|
||||
return Cache::remember($cacheKey, self::CACHE_TTL, function () use ($slug, $perPage) {
|
||||
return Artwork::search('')
|
||||
->options([
|
||||
'filter' => self::BASE_FILTER . ' AND tags = "' . addslashes($slug) . '"',
|
||||
'sort' => ['views:desc', 'likes:desc'],
|
||||
])
|
||||
->paginate($perPage);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Load artworks for a category, sorted by created_at desc.
|
||||
*/
|
||||
public function byCategory(string $cat, int $perPage = 24, array $filters = []): LengthAwarePaginator
|
||||
{
|
||||
$cacheKey = "search.cat.{$cat}.page." . request()->get('page', 1);
|
||||
|
||||
return Cache::remember($cacheKey, self::CACHE_TTL, function () use ($cat, $perPage) {
|
||||
return Artwork::search('')
|
||||
->options([
|
||||
'filter' => self::BASE_FILTER . ' AND category = "' . addslashes($cat) . '"',
|
||||
'sort' => ['created_at:desc'],
|
||||
])
|
||||
->paginate($perPage);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Related artworks: same tags, different artwork, ranked by views + likes.
|
||||
* Limit 12.
|
||||
*/
|
||||
public function related(Artwork $artwork, int $limit = 12): LengthAwarePaginator
|
||||
{
|
||||
$tags = $artwork->tags()->pluck('tags.slug')->values()->all();
|
||||
|
||||
if ($tags === []) {
|
||||
return $this->popular($limit);
|
||||
}
|
||||
|
||||
$cacheKey = "search.related.{$artwork->id}";
|
||||
|
||||
return Cache::remember($cacheKey, self::CACHE_TTL, function () use ($artwork, $tags, $limit) {
|
||||
$tagFilters = implode(' OR ', array_map(
|
||||
fn ($t) => 'tags = "' . addslashes($t) . '"',
|
||||
$tags
|
||||
));
|
||||
|
||||
return Artwork::search('')
|
||||
->options([
|
||||
'filter' => self::BASE_FILTER . ' AND id != ' . $artwork->id . ' AND (' . $tagFilters . ')',
|
||||
'sort' => ['views:desc', 'likes:desc'],
|
||||
])
|
||||
->paginate($limit);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Most popular artworks by views.
|
||||
*/
|
||||
public function popular(int $perPage = 24): LengthAwarePaginator
|
||||
{
|
||||
return Cache::remember('search.popular.page.' . request()->get('page', 1), self::CACHE_TTL, function () use ($perPage) {
|
||||
return Artwork::search('')
|
||||
->options([
|
||||
'filter' => self::BASE_FILTER,
|
||||
'sort' => ['views:desc', 'likes:desc'],
|
||||
])
|
||||
->paginate($perPage);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Most recent artworks by created_at.
|
||||
*/
|
||||
public function recent(int $perPage = 24): LengthAwarePaginator
|
||||
{
|
||||
return Cache::remember('search.recent.page.' . request()->get('page', 1), self::CACHE_TTL, function () use ($perPage) {
|
||||
return Artwork::search('')
|
||||
->options([
|
||||
'filter' => self::BASE_FILTER,
|
||||
'sort' => ['created_at:desc'],
|
||||
])
|
||||
->paginate($perPage);
|
||||
});
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private function parseSort(string $sort): array
|
||||
{
|
||||
$allowed = ['created_at', 'downloads', 'likes', 'views'];
|
||||
$parts = explode(':', $sort, 2);
|
||||
$field = $parts[0] ?? '';
|
||||
$dir = strtolower($parts[1] ?? 'desc') === 'asc' ? 'asc' : 'desc';
|
||||
|
||||
return in_array($field, $allowed, true) ? [$field, $dir] : [null, 'desc'];
|
||||
}
|
||||
|
||||
private function emptyPaginator(int $perPage): LengthAwarePaginator
|
||||
{
|
||||
return new \Illuminate\Pagination\LengthAwarePaginator([], 0, $perPage);
|
||||
}
|
||||
}
|
||||
@@ -301,7 +301,7 @@ class ArtworkService
|
||||
{
|
||||
$query = Artwork::where('user_id', $userId)
|
||||
->with([
|
||||
'user:id,name',
|
||||
'user:id,name,username',
|
||||
'categories' => function ($q) {
|
||||
$q->select('categories.id', 'categories.content_type_id', 'categories.parent_id', 'categories.name', 'categories.slug', 'categories.sort_order')
|
||||
->with(['parent:id,parent_id,content_type_id,name,slug', 'contentType:id,slug,name']);
|
||||
|
||||
@@ -6,6 +6,17 @@ namespace App\Services;
|
||||
|
||||
final class TagNormalizer
|
||||
{
|
||||
/**
|
||||
* Normalize a raw tag string to a clean, ASCII-only slug.
|
||||
*
|
||||
* Steps:
|
||||
* 1. Trim + lowercase
|
||||
* 2. Transliterate Unicode → ASCII (iconv or Transliterator)
|
||||
* 3. Strip everything except [a-z0-9 -]
|
||||
* 4. Collapse whitespace, replace spaces with hyphens
|
||||
* 5. Strip leading/trailing hyphens
|
||||
* 6. Enforce max length
|
||||
*/
|
||||
public function normalize(string $tag): string
|
||||
{
|
||||
$value = trim($tag);
|
||||
@@ -15,25 +26,63 @@ final class TagNormalizer
|
||||
|
||||
$value = mb_strtolower($value, 'UTF-8');
|
||||
|
||||
// Remove emoji / symbols and keep only letters, numbers, whitespace and hyphens.
|
||||
// (Unicode safe: \p{L} letters, \p{N} numbers)
|
||||
$value = (string) preg_replace('/[^\p{L}\p{N}\s\-]+/u', '', $value);
|
||||
// Transliterate to ASCII (e.g. é→e, ü→u, 日→nihon).
|
||||
// Try Transliterator first (intl extension), fall back to iconv.
|
||||
if (class_exists('\Transliterator')) {
|
||||
$trans = \Transliterator::create('Any-Latin; Latin-ASCII; Lower()');
|
||||
if ($trans !== null) {
|
||||
$value = (string) ($trans->transliterate($value) ?: $value);
|
||||
}
|
||||
} elseif (function_exists('iconv')) {
|
||||
$ascii = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $value);
|
||||
if ($ascii !== false && $ascii !== '') {
|
||||
$value = $ascii;
|
||||
}
|
||||
}
|
||||
|
||||
// Keep only ASCII letters, digits, spaces and hyphens.
|
||||
$value = (string) preg_replace('/[^a-z0-9\s\-]+/', '', $value);
|
||||
|
||||
// Normalize whitespace.
|
||||
$value = (string) preg_replace('/\s+/u', ' ', $value);
|
||||
$value = (string) preg_replace('/\s+/', ' ', $value);
|
||||
$value = trim($value);
|
||||
|
||||
// Spaces -> hyphens and collapse repeats.
|
||||
// Spaces → hyphens, collapse repeats, strip edge hyphens.
|
||||
$value = str_replace(' ', '-', $value);
|
||||
$value = (string) preg_replace('/\-+/u', '-', $value);
|
||||
$value = trim($value, "-\t\n\r\0\x0B");
|
||||
$value = (string) preg_replace('/-+/', '-', $value);
|
||||
$value = trim($value, '-');
|
||||
|
||||
$maxLength = (int) config('tags.max_length', 32);
|
||||
if ($maxLength > 0 && mb_strlen($value, 'UTF-8') > $maxLength) {
|
||||
$value = mb_substr($value, 0, $maxLength, 'UTF-8');
|
||||
if ($maxLength > 0 && strlen($value) > $maxLength) {
|
||||
$value = substr($value, 0, $maxLength);
|
||||
$value = rtrim($value, '-');
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a normalized slug back to a human-readable display name.
|
||||
*
|
||||
* "blue-sky" → "Blue Sky"
|
||||
* "sci-fi-landscape" → "Sci Fi Landscape"
|
||||
* "3d" → "3D"
|
||||
*
|
||||
* If the raw input is available, pass it instead of the slug — it gives
|
||||
* better casing (e.g. the AI sends "digital painting", no hyphens yet).
|
||||
*/
|
||||
public function toDisplayName(string $slugOrRaw): string
|
||||
{
|
||||
// If raw input still has mixed case or spaces, title-case it directly.
|
||||
$clean = trim($slugOrRaw);
|
||||
if ($clean === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
// Replace hyphens and underscores with spaces for word splitting.
|
||||
$spaced = str_replace(['-', '_'], ' ', $clean);
|
||||
|
||||
// Title-case each word (mb_convert_case handles UTF-8 safely).
|
||||
return mb_convert_case($spaced, MB_CASE_TITLE, 'UTF-8');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Jobs\IndexArtworkJob;
|
||||
use App\Models\Artwork;
|
||||
use App\Models\Tag;
|
||||
use App\Services\TagNormalizer;
|
||||
@@ -19,14 +20,17 @@ final class TagService
|
||||
|
||||
public function createOrFindTag(string $rawTag): Tag
|
||||
{
|
||||
$normalized = $this->normalizer->normalize($rawTag);
|
||||
$normalized = $this->normalizer->normalize($rawTag);
|
||||
$this->validateNormalizedTag($normalized);
|
||||
|
||||
// Keep tags normalized in both name and slug (spec: normalize all tags).
|
||||
// Unique(slug) + Unique(name) prevents duplicates.
|
||||
// Derive display name from the clean slug, not the raw input.
|
||||
// This ensures consistent casing regardless of how the tag was submitted.
|
||||
// "digital-art" → "Digital Art", "sci-fi-landscape" → "Sci Fi Landscape"
|
||||
$displayName = $this->normalizer->toDisplayName($normalized);
|
||||
|
||||
return Tag::query()->firstOrCreate(
|
||||
['slug' => $normalized],
|
||||
['name' => $normalized, 'usage_count' => 0, 'is_active' => true]
|
||||
['name' => $displayName, 'usage_count' => 0, 'is_active' => true]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -83,6 +87,8 @@ final class TagService
|
||||
$artwork->tags()->updateExistingPivot($tagId, $payload);
|
||||
}
|
||||
});
|
||||
|
||||
$this->queueReindex($artwork);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -147,6 +153,8 @@ final class TagService
|
||||
$this->incrementUsageCounts($newlyAttachedTagIds);
|
||||
}
|
||||
});
|
||||
|
||||
$this->queueReindex($artwork);
|
||||
}
|
||||
|
||||
public function detachTags(Artwork $artwork, array $tagSlugsOrIds): void
|
||||
@@ -179,6 +187,8 @@ final class TagService
|
||||
$artwork->tags()->detach($existing);
|
||||
$this->decrementUsageCounts($existing);
|
||||
});
|
||||
|
||||
$this->queueReindex($artwork);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -236,6 +246,8 @@ final class TagService
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
$this->queueReindex($artwork);
|
||||
}
|
||||
|
||||
public function updateUsageCount(Tag $tag): void
|
||||
@@ -326,4 +338,13 @@ final class TagService
|
||||
->whereIn('id', $tagIds)
|
||||
->update(['usage_count' => DB::raw('CASE WHEN usage_count > 0 THEN usage_count - 1 ELSE 0 END')]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch a non-blocking reindex job for the given artwork.
|
||||
* Called after every tag mutation so the search index stays consistent.
|
||||
*/
|
||||
private function queueReindex(Artwork $artwork): void
|
||||
{
|
||||
IndexArtworkJob::dispatch($artwork->id);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user