| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236 |
- <?php
-
- namespace App\Storefront\Logos;
-
- use App\Ai\AiException;
- use App\Ai\AiManager;
- use App\Models\Store;
- use App\StorePlan\Ai\JsonAnswer;
- use App\StorePlan\PlanSchema;
- use GdImage;
- use Illuminate\Http\UploadedFile;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Storage;
- use Illuminate\Support\Str;
- use RuntimeException;
-
- /**
- * A store's logo: one the merchant uploads, one of our ready designs, or one Claude draws.
- *
- * The logo belongs to the store, not to the design, so it shows on the live store right away.
- * Ready designs are drawn by the storefront from the store's name, fonts and colours, so they follow
- * the store's look when it changes. Claude's drawings are cleaned by LogoSvg before they are kept.
- */
- class StoreLogos
- {
- /** Keep in step with LOGO_DESIGNS in resources/js/storefront/logo.tsx. */
- public const array DESIGNS = ['wordmark', 'spaced', 'monogram-circle', 'monogram-square', 'two-tone', 'underline', 'badge', 'dot'];
-
- /** Uploaded logos are made smaller than this on their longest side. */
- public const int MAX_SIDE = 800;
-
- public const int MIN_SIDE = 64;
-
- /** How many logos one "Draw with AI" try asks for. */
- public const int PER_TRY = 3;
-
- /** Claude's drawings kept per store, newest first. */
- private const int MAX_DRAFTS = 12;
-
- public function __construct(private readonly AiManager $ai) {}
-
- /**
- * Lifetime "Draw with AI" tries per store.
- */
- public function tryLimit(): int
- {
- return (int) config('ai.logo.lifetime_tries', 3);
- }
-
- public function triesLeft(Store $store): int
- {
- return max(0, $this->tryLimit() - $store->ai_logo_tries);
- }
-
- /**
- * The name the logo shows: the store header's words, or the store name.
- */
- public function name(Store $store): string
- {
- $plan = $store->published_plan ?? $store->plan ?? [];
- $header = $plan['header'] ?? collect($plan['sections'] ?? [])->firstWhere('type', 'header');
- $text = trim((string) ($header['content']['logoText'] ?? ''));
-
- return $text !== '' ? $text : $store->name;
- }
-
- /**
- * What the storefront needs to draw the logo, or null when the store has none.
- *
- * @return array{type: string, url?: string, width?: int, height?: int, key?: string, svg?: string}|null
- */
- public function present(Store $store): ?array
- {
- $logo = $store->logo;
-
- return match ($logo['type'] ?? null) {
- 'upload' => ['type' => 'upload', 'url' => Storage::disk('public')->url($logo['path']), 'width' => (int) $logo['width'], 'height' => (int) $logo['height']],
- 'design' => in_array($logo['key'] ?? null, self::DESIGNS, true) ? ['type' => 'design', 'key' => $logo['key']] : null,
- 'drawn' => is_string($logo['svg'] ?? null) ? ['type' => 'drawn', 'svg' => $logo['svg']] : null,
- default => null,
- };
- }
-
- /**
- * Save an uploaded logo, made smaller when large and saved as WebP, keeping a see-through background.
- * Saving it again also drops hidden details in the file. Replaces the old logo.
- *
- * @throws RuntimeException When the picture cannot be read.
- */
- public function upload(Store $store, UploadedFile $file): void
- {
- $image = @imagecreatefromstring((string) file_get_contents($file->getRealPath()));
-
- if (! $image instanceof GdImage) {
- throw new RuntimeException('The picture could not be read.');
- }
-
- $width = imagesx($image);
- $height = imagesy($image);
- $scale = min(1, self::MAX_SIDE / max($width, $height));
- $newWidth = max(1, (int) round($width * $scale));
- $newHeight = max(1, (int) round($height * $scale));
-
- $canvas = imagecreatetruecolor($newWidth, $newHeight);
- imagealphablending($canvas, false);
- imagesavealpha($canvas, true);
- imagefill($canvas, 0, 0, imagecolorallocatealpha($canvas, 0, 0, 0, 127));
- imagecopyresampled($canvas, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
-
- $path = 'logos/'.$store->id.'-'.Str::random(12).'.webp';
- ob_start();
- imagewebp($canvas, null, 90);
- Storage::disk('public')->put($path, (string) ob_get_clean());
-
- $this->replace($store, ['type' => 'upload', 'path' => $path, 'width' => $newWidth, 'height' => $newHeight]);
- }
-
- public function useDesign(Store $store, string $key): void
- {
- $this->replace($store, ['type' => 'design', 'key' => $key]);
- }
-
- /**
- * Use one of the drawings Claude made for this store.
- */
- public function useDrawn(Store $store, int $index): bool
- {
- $svg = $store->logo_drafts[$index] ?? null;
-
- if (! is_string($svg)) {
- return false;
- }
-
- $this->replace($store, ['type' => 'drawn', 'svg' => $svg]);
-
- return true;
- }
-
- public function remove(Store $store): void
- {
- $this->replace($store, null);
- }
-
- /**
- * Ask Claude for new logos. A try counts only when at least one usable logo comes back.
- * Returns how many new logos were added, or null when the store has no tries left.
- *
- * @throws AiException
- */
- public function draw(Store $store): ?int
- {
- // Take a try first, in one step, so two quick clicks can never pass the limit.
- $taken = DB::table('stores')->where('id', $store->id)->where('ai_logo_tries', '<', $this->tryLimit())->increment('ai_logo_tries');
-
- if ($taken === 0) {
- return null;
- }
-
- try {
- $answer = $this->ai->ask('logo', $this->system(), $this->prompt($store));
- $logos = JsonAnswer::decode($answer->text)['logos'] ?? null;
- $clean = is_array($logos)
- ? array_values(array_filter(array_map(fn ($logo) => is_array($logo) && is_string($logo['svg'] ?? null) ? LogoSvg::clean($logo['svg']) : null, $logos)))
- : [];
-
- if ($clean === []) {
- throw new AiException('The AI did not draw a usable logo.', AiException::INVALID_RESULT);
- }
- } catch (AiException $e) {
- // Nothing usable: give the try back.
- DB::table('stores')->where('id', $store->id)->where('ai_logo_tries', '>', 0)->decrement('ai_logo_tries');
- $store->refresh();
-
- throw $e;
- }
-
- $store->refresh();
- $store->logo_drafts = array_slice([...array_slice($clean, 0, self::PER_TRY), ...($store->logo_drafts ?? [])], 0, self::MAX_DRAFTS);
- $store->save();
-
- return min(count($clean), self::PER_TRY);
- }
-
- /**
- * @param array<string, mixed>|null $logo
- */
- private function replace(Store $store, ?array $logo): void
- {
- $old = $store->logo;
-
- $store->logo = $logo;
- $store->save();
-
- if (($old['type'] ?? null) === 'upload' && ($old['path'] ?? null) !== ($logo['path'] ?? null)) {
- Storage::disk('public')->delete($old['path']);
- }
- }
-
- private function system(): string
- {
- return <<<'TEXT'
- You design simple, professional logos for small online shops in Malaysia. You draw them as SVG.
-
- Answer with JSON only, in this shape: {"logos": [{"svg": "<svg ...>...</svg>"}, ...]} with exactly 3 logos.
-
- Rules for every logo:
- - A wide logo for a website header: viewBox about "0 0 400 100" (width 240 to 600, height 80 to 140). No width or height on the svg element.
- - Show the store name exactly as given, spelled exactly, as a <text> element. Do not set font-family: the store's own font is applied. Pick a font-size and positions so the whole name fits inside the viewBox: each letter is about 0.6 times the font-size wide.
- - You may add a simple mark or icon on the left made from basic shapes (circle, rect, path, polygon). Keep it simple and clear at small sizes.
- - Use only the store's colours given below (as hex values), plus white or none. A linear or radial gradient between them is allowed.
- - Allowed elements only: svg, g, path, circle, ellipse, rect, line, polyline, polygon, text, tspan, defs, linearGradient, radialGradient, stop. No images, links, scripts, styles, filters, masks, clip paths, animation or embedded fonts.
- - Make the 3 logos clearly different ideas, for example: an icon beside the name, a monogram badge with the name, and a stylish wordmark.
- - Fit the brand: what it sells and its mood. Avoid clichés like a generic shopping cart.
- TEXT;
- }
-
- private function prompt(Store $store): string
- {
- $plan = $store->published_plan ?? $store->plan ?? [];
- $colors = $plan['theme']['colors'] ?? [];
- $font = PlanSchema::FONTS[$plan['theme']['fonts']['heading'] ?? ''] ?? 'a clean sans-serif';
- $palette = collect(['primary', 'accent', 'foreground', 'surface', 'background'])
- ->filter(fn (string $key) => is_string($colors[$key] ?? null))
- ->map(fn (string $key) => "- {$key}: {$colors[$key]}")
- ->implode("\n");
-
- return implode("\n", [
- 'Store name: '.$this->name($store),
- 'What it sells: '.$store->category->value,
- 'About the brand: '.Str::limit((string) $store->description, 600),
- "The store's heading font (applied for you): ".$font,
- "The store's colours:",
- $palette !== '' ? $palette : '- primary: #1F1F1F',
- ]);
- }
- }
|