AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

StoreLogos.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. <?php
  2. namespace App\Storefront\Logos;
  3. use App\Ai\AiException;
  4. use App\Ai\AiManager;
  5. use App\Mail\StoreBrand;
  6. use App\Models\Store;
  7. use App\StorePlan\Ai\JsonAnswer;
  8. use App\StorePlan\PlanSchema;
  9. use GdImage;
  10. use Illuminate\Http\UploadedFile;
  11. use Illuminate\Support\Facades\DB;
  12. use Illuminate\Support\Facades\Storage;
  13. use Illuminate\Support\Str;
  14. use RuntimeException;
  15. /**
  16. * A store's logo: one the merchant uploads, one of our ready designs, or one Claude draws.
  17. *
  18. * The logo belongs to the store, not to the design, so it shows on the live store right away.
  19. * Ready designs are drawn by the storefront from the store's name, fonts and colours, so they follow
  20. * the store's look when it changes. Claude's drawings are cleaned by LogoSvg before they are kept.
  21. */
  22. class StoreLogos
  23. {
  24. /** Keep in step with LOGO_DESIGNS in resources/js/storefront/logo.tsx. */
  25. public const array DESIGNS = ['wordmark', 'spaced', 'monogram-circle', 'monogram-square', 'two-tone', 'underline', 'badge', 'dot'];
  26. /** Uploaded logos are made smaller than this on their longest side. */
  27. public const int MAX_SIDE = 800;
  28. public const int MIN_SIDE = 64;
  29. /** The square browser tab and home screen icon made from an uploaded logo, in pixels. */
  30. public const int ICON_SIDE = 180;
  31. /** Uploaded logos wider than this (width to height) are too thin to read as a tab icon. */
  32. private const float ICON_MAX_RATIO = 2.0;
  33. /** How many logos one "Draw with AI" try asks for. */
  34. public const int PER_TRY = 3;
  35. /** Claude's drawings kept per store, newest first. */
  36. private const int MAX_DRAFTS = 12;
  37. public function __construct(private readonly AiManager $ai) {}
  38. /**
  39. * Lifetime "Draw with AI" tries per store.
  40. */
  41. public function tryLimit(): int
  42. {
  43. return (int) config('ai.logo.lifetime_tries', 3);
  44. }
  45. public function triesLeft(Store $store): int
  46. {
  47. return max(0, $this->tryLimit() - $store->ai_logo_tries);
  48. }
  49. /**
  50. * The name the logo shows: the store header's words, or the store name.
  51. */
  52. public function name(Store $store): string
  53. {
  54. $plan = $store->published_plan ?? $store->plan ?? [];
  55. $header = $plan['header'] ?? collect($plan['sections'] ?? [])->firstWhere('type', 'header');
  56. $text = trim((string) ($header['content']['logoText'] ?? ''));
  57. return $text !== '' ? $text : $store->name;
  58. }
  59. /**
  60. * What the storefront needs to draw the logo, or null when the store has none.
  61. *
  62. * @return array{type: string, url?: string, width?: int, height?: int, key?: string, svg?: string}|null
  63. */
  64. public function present(Store $store): ?array
  65. {
  66. $logo = $store->logo;
  67. return match ($logo['type'] ?? null) {
  68. 'upload' => ['type' => 'upload', 'url' => Storage::disk('public')->url($logo['path']), 'width' => (int) $logo['width'], 'height' => (int) $logo['height']],
  69. 'design' => in_array($logo['key'] ?? null, self::DESIGNS, true) ? ['type' => 'design', 'key' => $logo['key']] : null,
  70. 'drawn' => is_string($logo['svg'] ?? null) ? ['type' => 'drawn', 'svg' => $logo['svg']] : null,
  71. default => null,
  72. };
  73. }
  74. /**
  75. * Save an uploaded logo, made smaller when large and saved as WebP, keeping a see-through background.
  76. * Saving it again also drops hidden details in the file. Replaces the old logo.
  77. *
  78. * @throws RuntimeException When the picture cannot be read.
  79. */
  80. public function upload(Store $store, UploadedFile $file): void
  81. {
  82. $image = @imagecreatefromstring((string) file_get_contents($file->getRealPath()));
  83. if (! $image instanceof GdImage) {
  84. throw new RuntimeException('The picture could not be read.');
  85. }
  86. $width = imagesx($image);
  87. $height = imagesy($image);
  88. $scale = min(1, self::MAX_SIDE / max($width, $height));
  89. $newWidth = max(1, (int) round($width * $scale));
  90. $newHeight = max(1, (int) round($height * $scale));
  91. $canvas = imagecreatetruecolor($newWidth, $newHeight);
  92. imagealphablending($canvas, false);
  93. imagesavealpha($canvas, true);
  94. imagefill($canvas, 0, 0, imagecolorallocatealpha($canvas, 0, 0, 0, 127));
  95. imagecopyresampled($canvas, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  96. $name = 'logos/'.$store->id.'-'.Str::random(12);
  97. ob_start();
  98. imagewebp($canvas, null, 90);
  99. Storage::disk('public')->put($name.'.webp', (string) ob_get_clean());
  100. $icon = $this->squareIcon($canvas);
  101. if ($icon !== null) {
  102. Storage::disk('public')->put($name.'-icon.png', $icon);
  103. }
  104. $this->replace($store, array_filter([
  105. 'type' => 'upload',
  106. 'path' => $name.'.webp',
  107. 'icon_path' => $icon !== null ? $name.'-icon.png' : null,
  108. 'width' => $newWidth,
  109. 'height' => $newHeight,
  110. ], fn ($value) => $value !== null));
  111. }
  112. /**
  113. * The browser tab icon: the uploaded logo when it is square enough to read at a small size,
  114. * otherwise the store's initials on its main colour. The same icon is used for every logo type,
  115. * and for stores with no logo, so a shop never shows our own icon.
  116. *
  117. * @return array{href: string, type: string, touch: string|null}
  118. */
  119. public function icon(Store $store): array
  120. {
  121. $logo = $store->logo;
  122. if (($logo['type'] ?? null) === 'upload' && is_string($logo['icon_path'] ?? null)) {
  123. $url = Storage::disk('public')->url($logo['icon_path']);
  124. return ['href' => $url, 'type' => 'image/png', 'touch' => $url];
  125. }
  126. $brand = StoreBrand::for($store);
  127. $initials = $this->initials($brand->name);
  128. $letters = htmlspecialchars($initials, ENT_XML1);
  129. $size = mb_strlen($initials) > 1 ? 28 : 36;
  130. $round = ($logo['type'] ?? null) === 'design' && ($logo['key'] ?? null) === 'monogram-circle';
  131. $radius = $round ? 32 : min(32, (int) round($brand->radius * 1.5));
  132. $font = htmlspecialchars($brand->headingFont, ENT_XML1 | ENT_QUOTES);
  133. $svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">'
  134. .'<rect width="64" height="64" rx="'.$radius.'" fill="'.$brand->color('primary').'"/>'
  135. .'<text x="32" y="33" text-anchor="middle" dominant-baseline="central" font-family="'.$font.'"'
  136. .' font-size="'.$size.'" font-weight="700" fill="'.$brand->color('primaryForeground').'">'.$letters.'</text>'
  137. .'</svg>';
  138. return ['href' => 'data:image/svg+xml,'.rawurlencode($svg), 'type' => 'image/svg+xml', 'touch' => null];
  139. }
  140. /**
  141. * Up to two letters: the first letters of the first two words. Keep in step with initials() in logo.tsx.
  142. */
  143. public function initials(string $name): string
  144. {
  145. $words = preg_split('/\s+/u', trim((string) preg_replace('/[^\p{L}\p{N}\s]/u', ' ', $name)), -1, PREG_SPLIT_NO_EMPTY) ?: [];
  146. $letters = count($words) > 1
  147. ? mb_substr($words[0], 0, 1).mb_substr($words[1], 0, 1)
  148. : mb_substr($words[0] ?? '?', 0, 2);
  149. return mb_strtoupper($letters);
  150. }
  151. /**
  152. * 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.
  153. */
  154. private function squareIcon(GdImage $image): ?string
  155. {
  156. $trimmed = @imagecropauto($image, IMG_CROP_SIDES);
  157. $image = $trimmed instanceof GdImage ? $trimmed : $image;
  158. $width = imagesx($image);
  159. $height = imagesy($image);
  160. if ($width / max(1, $height) > self::ICON_MAX_RATIO || $height / max(1, $width) > self::ICON_MAX_RATIO) {
  161. return null;
  162. }
  163. // A little room around the logo, so it does not touch the edges of the tab icon.
  164. $inner = (int) round(self::ICON_SIDE * 0.9);
  165. $scale = min($inner / $width, $inner / $height);
  166. $newWidth = max(1, (int) round($width * $scale));
  167. $newHeight = max(1, (int) round($height * $scale));
  168. $canvas = imagecreatetruecolor(self::ICON_SIDE, self::ICON_SIDE);
  169. imagealphablending($canvas, false);
  170. imagesavealpha($canvas, true);
  171. imagefill($canvas, 0, 0, imagecolorallocatealpha($canvas, 0, 0, 0, 127));
  172. imagecopyresampled($canvas, $image, intdiv(self::ICON_SIDE - $newWidth, 2), intdiv(self::ICON_SIDE - $newHeight, 2), 0, 0, $newWidth, $newHeight, $width, $height);
  173. ob_start();
  174. imagepng($canvas, null, 9);
  175. return (string) ob_get_clean();
  176. }
  177. public function useDesign(Store $store, string $key): void
  178. {
  179. $this->replace($store, ['type' => 'design', 'key' => $key]);
  180. }
  181. /**
  182. * Use one of the drawings Claude made for this store.
  183. */
  184. public function useDrawn(Store $store, int $index): bool
  185. {
  186. $svg = $store->logo_drafts[$index] ?? null;
  187. if (! is_string($svg)) {
  188. return false;
  189. }
  190. $this->replace($store, ['type' => 'drawn', 'svg' => $svg]);
  191. return true;
  192. }
  193. public function remove(Store $store): void
  194. {
  195. $this->replace($store, null);
  196. }
  197. /**
  198. * Ask Claude for new logos. A try counts only when at least one usable logo comes back.
  199. * Returns how many new logos were added, or null when the store has no tries left.
  200. *
  201. * @throws AiException
  202. */
  203. public function draw(Store $store): ?int
  204. {
  205. // Take a try first, in one step, so two quick clicks can never pass the limit.
  206. $taken = DB::table('stores')->where('id', $store->id)->where('ai_logo_tries', '<', $this->tryLimit())->increment('ai_logo_tries');
  207. if ($taken === 0) {
  208. return null;
  209. }
  210. try {
  211. $answer = $this->ai->ask('logo', $this->system(), $this->prompt($store));
  212. $logos = JsonAnswer::decode($answer->text)['logos'] ?? null;
  213. $clean = is_array($logos)
  214. ? array_values(array_filter(array_map(fn ($logo) => is_array($logo) && is_string($logo['svg'] ?? null) ? LogoSvg::clean($logo['svg']) : null, $logos)))
  215. : [];
  216. if ($clean === []) {
  217. throw new AiException('The AI did not draw a usable logo.', AiException::INVALID_RESULT);
  218. }
  219. } catch (AiException $e) {
  220. // Nothing usable: give the try back.
  221. DB::table('stores')->where('id', $store->id)->where('ai_logo_tries', '>', 0)->decrement('ai_logo_tries');
  222. $store->refresh();
  223. throw $e;
  224. }
  225. $store->refresh();
  226. $store->logo_drafts = array_slice([...array_slice($clean, 0, self::PER_TRY), ...($store->logo_drafts ?? [])], 0, self::MAX_DRAFTS);
  227. $store->save();
  228. return min(count($clean), self::PER_TRY);
  229. }
  230. /**
  231. * @param array<string, mixed>|null $logo
  232. */
  233. private function replace(Store $store, ?array $logo): void
  234. {
  235. $old = $store->logo;
  236. $store->logo = $logo;
  237. $store->save();
  238. if (($old['type'] ?? null) === 'upload' && ($old['path'] ?? null) !== ($logo['path'] ?? null)) {
  239. Storage::disk('public')->delete(array_filter([$old['path'], $old['icon_path'] ?? null]));
  240. }
  241. }
  242. private function system(): string
  243. {
  244. return <<<'TEXT'
  245. You design simple, professional logos for small online shops in Malaysia. You draw them as SVG.
  246. Answer with JSON only, in this shape: {"logos": [{"svg": "<svg ...>...</svg>"}, ...]} with exactly 3 logos.
  247. Rules for every logo:
  248. - 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.
  249. - 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.
  250. - 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.
  251. - Use only the store's colours given below (as hex values), plus white or none. A linear or radial gradient between them is allowed.
  252. - 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.
  253. - Make the 3 logos clearly different ideas, for example: an icon beside the name, a monogram badge with the name, and a stylish wordmark.
  254. - Fit the brand: what it sells and its mood. Avoid clichés like a generic shopping cart.
  255. TEXT;
  256. }
  257. private function prompt(Store $store): string
  258. {
  259. $plan = $store->published_plan ?? $store->plan ?? [];
  260. $colors = $plan['theme']['colors'] ?? [];
  261. $font = PlanSchema::FONTS[$plan['theme']['fonts']['heading'] ?? ''] ?? 'a clean sans-serif';
  262. $palette = collect(['primary', 'accent', 'foreground', 'surface', 'background'])
  263. ->filter(fn (string $key) => is_string($colors[$key] ?? null))
  264. ->map(fn (string $key) => "- {$key}: {$colors[$key]}")
  265. ->implode("\n");
  266. return implode("\n", [
  267. 'Store name: '.$this->name($store),
  268. 'What it sells: '.$store->category->value,
  269. 'About the brand: '.Str::limit((string) $store->description, 600),
  270. "The store's heading font (applied for you): ".$font,
  271. "The store's colours:",
  272. $palette !== '' ? $palette : '- primary: #1F1F1F',
  273. ]);
  274. }
  275. }