| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335 |
- <?php
-
- namespace App\Storefront\Logos;
-
- use App\Ai\AiException;
- use App\Ai\AiManager;
- use App\Mail\StoreBrand;
- 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;
-
- /** The square browser tab and home screen icon made from an uploaded logo, in pixels. */
- public const int ICON_SIDE = 180;
-
- /** Uploaded logos wider than this (width to height) are too thin to read as a tab icon. */
- private const float ICON_MAX_RATIO = 2.0;
-
- /** 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);
-
- $name = 'logos/'.$store->id.'-'.Str::random(12);
- ob_start();
- imagewebp($canvas, null, 90);
- Storage::disk('public')->put($name.'.webp', (string) ob_get_clean());
-
- $icon = $this->squareIcon($canvas);
-
- if ($icon !== null) {
- Storage::disk('public')->put($name.'-icon.png', $icon);
- }
-
- $this->replace($store, array_filter([
- 'type' => 'upload',
- 'path' => $name.'.webp',
- 'icon_path' => $icon !== null ? $name.'-icon.png' : null,
- 'width' => $newWidth,
- 'height' => $newHeight,
- ], fn ($value) => $value !== null));
- }
-
- /**
- * The browser tab icon: the uploaded logo when it is square enough to read at a small size,
- * otherwise the store's initials on its main colour. The same icon is used for every logo type,
- * and for stores with no logo, so a shop never shows our own icon.
- *
- * @return array{href: string, type: string, touch: string|null}
- */
- public function icon(Store $store): array
- {
- $logo = $store->logo;
-
- if (($logo['type'] ?? null) === 'upload' && is_string($logo['icon_path'] ?? null)) {
- $url = Storage::disk('public')->url($logo['icon_path']);
-
- return ['href' => $url, 'type' => 'image/png', 'touch' => $url];
- }
-
- $brand = StoreBrand::for($store);
- $initials = $this->initials($brand->name);
- $letters = htmlspecialchars($initials, ENT_XML1);
- $size = mb_strlen($initials) > 1 ? 28 : 36;
- $round = ($logo['type'] ?? null) === 'design' && ($logo['key'] ?? null) === 'monogram-circle';
- $radius = $round ? 32 : min(32, (int) round($brand->radius * 1.5));
- $font = htmlspecialchars($brand->headingFont, ENT_XML1 | ENT_QUOTES);
-
- $svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">'
- .'<rect width="64" height="64" rx="'.$radius.'" fill="'.$brand->color('primary').'"/>'
- .'<text x="32" y="33" text-anchor="middle" dominant-baseline="central" font-family="'.$font.'"'
- .' font-size="'.$size.'" font-weight="700" fill="'.$brand->color('primaryForeground').'">'.$letters.'</text>'
- .'</svg>';
-
- return ['href' => 'data:image/svg+xml,'.rawurlencode($svg), 'type' => 'image/svg+xml', 'touch' => null];
- }
-
- /**
- * Up to two letters: the first letters of the first two words. Keep in step with initials() in logo.tsx.
- */
- public function initials(string $name): string
- {
- $words = preg_split('/\s+/u', trim((string) preg_replace('/[^\p{L}\p{N}\s]/u', ' ', $name)), -1, PREG_SPLIT_NO_EMPTY) ?: [];
-
- $letters = count($words) > 1
- ? mb_substr($words[0], 0, 1).mb_substr($words[1], 0, 1)
- : mb_substr($words[0] ?? '?', 0, 2);
-
- return mb_strtoupper($letters);
- }
-
- /**
- * The logo on a square see-through canvas, with plain edges (see-through or one solid colour) cut off first. Null when the logo is too wide to read.
- */
- private function squareIcon(GdImage $image): ?string
- {
- $trimmed = @imagecropauto($image, IMG_CROP_SIDES);
- $image = $trimmed instanceof GdImage ? $trimmed : $image;
- $width = imagesx($image);
- $height = imagesy($image);
-
- if ($width / max(1, $height) > self::ICON_MAX_RATIO || $height / max(1, $width) > self::ICON_MAX_RATIO) {
- return null;
- }
-
- // A little room around the logo, so it does not touch the edges of the tab icon.
- $inner = (int) round(self::ICON_SIDE * 0.9);
- $scale = min($inner / $width, $inner / $height);
- $newWidth = max(1, (int) round($width * $scale));
- $newHeight = max(1, (int) round($height * $scale));
-
- $canvas = imagecreatetruecolor(self::ICON_SIDE, self::ICON_SIDE);
- imagealphablending($canvas, false);
- imagesavealpha($canvas, true);
- imagefill($canvas, 0, 0, imagecolorallocatealpha($canvas, 0, 0, 0, 127));
- imagecopyresampled($canvas, $image, intdiv(self::ICON_SIDE - $newWidth, 2), intdiv(self::ICON_SIDE - $newHeight, 2), 0, 0, $newWidth, $newHeight, $width, $height);
-
- ob_start();
- imagepng($canvas, null, 9);
-
- return (string) ob_get_clean();
- }
-
- 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(array_filter([$old['path'], $old['icon_path'] ?? null]));
- }
- }
-
- 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',
- ]);
- }
- }
|