Преглед изворни кода

Add store logos: upload, ready designs or drawn by Claude

- Logo box in the Design tab; the logo belongs to the store and shows on the live store right away
- Upload PNG, JPG or WebP (up to 2 MB), resized and saved as WebP with transparency kept; SVG uploads refused
- 8 ready designs drawn from the store's name, fonts and colours, following the store's look
- Claude draws 3 logos per try, 3 lifetime tries per store (AI_LOGO_LIFETIME_TRIES); failed tries are not counted
- Claude's SVG is rebuilt by LogoSvg: simple shapes and text only, no scripts, links or outside files
- Logo shown in the store header; uploaded logos also top the order emails
- New stores.logo, stores.logo_drafts and stores.ai_logo_tries (run php artisan migrate)
feature/store-logos
fahmisaad пре 21 часа
родитељ
комит
32580f9f81

+ 13
- 2
PROGRESS.md Прегледај датотеку

@@ -4,8 +4,8 @@ This file is the single source of truth for the project plan and status.
4 4
 Update it at the end of every work session.
5 5
 
6 6
 **Last updated:** 2026-11-30
7
-**Current step:** Step 10: Stripe Connect built on branch `feature/stripe-connect` (not committed yet) and tested for real in Stripe test mode: Luna Skin is connected, and a card payment and an FPX payment both landed in its own account. EasyParcel courier booking is done on branch `feature/easyparcel` (not committed yet). Step 9 part 8 on hold
8
-**Next action:** Commit, then merge `feature/easyparcel` and `feature/stripe-connect` into `main` (run `php artisan migrate`). Later: live courier rate at checkout, tracking updates, a lawyer reads the legal pages, backup AI provider, hosting
7
+**Current step:** On branch `feature/stripe-connect` (not committed yet): Stripe Connect (tested with card and FPX), restyled shopper emails, store contact email, and store logos (upload, ready designs, Claude drawings with a lifetime limit). EasyParcel courier booking is done on branch `feature/easyparcel` (not committed yet). Step 9 part 8 on hold
8
+**Next action:** Commit, then merge `feature/stripe-connect` (it includes `feature/easyparcel`) into `main` and run `php artisan migrate`. Later: live courier rate at checkout, tracking updates, a lawyer reads the legal pages, backup AI provider, hosting
9 9
 
10 10
 Status marks: `[ ]` not started · `[~]` in progress · `[x]` done
11 11
 
@@ -163,6 +163,16 @@ Changing from Claude to another AI model (or back) must be a settings change, no
163 163
 - Links are built from `APP_URL`, because the paid email can be sent from the webhook, where there is no shopper visit.
164 164
 - Sender and replies (added 2026-11-30): the emails come from our address (so they are delivered) but under the store's name, such as "Luna Skin <hello@…>". Replies go to the store's "Email for shoppers" (`stores.contact_email`), set in Settings under "How shoppers reach you" next to WhatsApp, with a one-click "Use <account email>". It is also shown at the bottom of the emails. When empty, there is no reply address. The account email is never used unless the merchant saves it.
165 165
 
166
+### Store logos (added 2026-11-30)
167
+
168
+- In the Design tab, a **Logo** box: upload a logo, pick one of 8 ready designs, or "Draw 3 logos" with Claude. The logo belongs to the store (`stores.logo`), not the design, so it shows on the live store right away, without "Publish changes". Without a logo, the header shows the store name as before.
169
+- **Upload:** PNG, JPG or WebP, up to 2 MB, at least 64 pixels. Made smaller to 800 pixels on the longest side and saved as WebP (GD), keeping a see-through background. SVG uploads are not accepted (they can carry code). A new upload deletes the old file.
170
+- **Ready designs** (`wordmark`, `spaced`, `monogram-circle`, `monogram-square`, `two-tone`, `underline`, `badge`, `dot`): drawn by the storefront from the header's words and the store's CSS variables, so they follow the store's fonts and colours when the look changes. Code: `resources/js/storefront/logo.tsx`.
171
+- **Drawn by Claude (decided 2026-11-30):** each try draws 3 SVG logos from the brand name, category, description, colours and heading font (AI task `logo`, Claude Sonnet by default). **Lifetime limit: 3 tries per store** (`AI_LOGO_LIFETIME_TRIES`); a try is taken in one database step so quick double clicks cannot pass the limit, and a try that brings back nothing usable is given back. Every drawing is kept (up to 12) so the merchant can switch later. Real test: Claude drew 3 logos for Luna Skin in about 20 seconds, including a crescent moon for "Luna".
172
+- **Safety:** Claude's SVG is rebuilt by `App\Storefront\Logos\LogoSvg`: only simple shapes, text and gradients, checked attribute values, no scripts, links, pictures, styles, event handlers or outside addresses; ids get a random prefix; text always uses the store's heading font (`var(--sf-font-heading)`).
173
+- **Emails:** an uploaded logo shows at the top of the order emails (at most 48 pixels high). Ready designs and AI drawings are not pictures email apps can show, so those emails keep the store name.
174
+- Not done yet: logo as the browser tab icon; logo in the store footer.
175
+
166 176
 ### How discount codes work (added in Step 8)
167 177
 
168 178
 - Codes live in the `discount_codes` table, per store, saved in capital letters. Shoppers may type them in any case.
@@ -708,3 +718,4 @@ Add one line per work session: date, what was done, what is next.
708 718
 | 2026-11-30 | FPX test passed: order #1009 (RM 47) paid with FPX (Maybank2E test bank) into Luna Skin's own Stripe account.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            | Commit and merge                                                |
709 719
 | 2026-11-30 | Restyled the shopper emails (order paid, order shipped) in each store's own colours, fonts and corners, with View order, WhatsApp and Track parcel buttons and plain-text versions. Checked on desktop and phone width for Luna Skin, Sambal Nenek (Malay, serif) and Crunch & Co. 349 tests pass.                                                                                                                                                                                                                                                                                                                                                                                                                                                       | Commit and merge                                                |
710 720
 | 2026-11-30 | Store contact email: "How shoppers reach you" card in Settings (WhatsApp + email for shoppers); order emails are sent under the store's name with replies to that email, shown in the footer. 352 tests pass; saved and checked for Luna Skin.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           | Commit and merge                                                |
721
+| 2026-11-30 | Store logos: Logo box in the Design tab (upload, 8 ready designs, Claude draws 3 per try with 3 lifetime tries per store), shown in the store header and (uploads) in order emails; Claude's SVG cleaned by LogoSvg. Real Claude test drew a moon logo for Luna Skin. 360 tests pass.                                                                                                                                                                                                                                                                                                                                                                                                                                                                    | Commit and merge                                                |

+ 5
- 0
app/Ai/Drivers/FakeDriver.php Прегледај датотеку

@@ -29,6 +29,11 @@ final class FakeDriver implements AiDriver
29 29
         $answer = match ($request->task) {
30 30
             'edit' => ['reply' => 'Fake AI: I made the main colour darker.', 'theme' => ['colors' => ['primary' => '#3B2A20']]],
31 31
             'pulse' => ['summary' => 'Fake AI: sales are steady this month. Ship your waiting orders first, then check your stock.'],
32
+            'logo' => ['logos' => [
33
+                ['svg' => '<svg viewBox="0 0 400 100"><circle cx="50" cy="50" r="34" fill="#1F3D32"/><text x="100" y="64" font-size="40">Fake Logo</text></svg>'],
34
+                ['svg' => '<svg viewBox="0 0 400 100"><rect x="8" y="16" width="68" height="68" rx="12" fill="#9CC5C0"/><text x="96" y="64" font-size="40">Fake Logo</text></svg>'],
35
+                ['svg' => '<svg viewBox="0 0 400 100"><text x="10" y="64" font-size="44" font-weight="700">Fake Logo</text><rect x="10" y="76" width="120" height="4" fill="#1F3D32"/></svg>'],
36
+            ]],
32 37
             default => SamplePlan::forName($this->storeName($request->prompt)),
33 38
         };
34 39
 

+ 3
- 0
app/Http/Controllers/Concerns/RendersStorefront.php Прегледај датотеку

@@ -8,6 +8,7 @@ use App\Models\Collection;
8 8
 use App\Models\Product;
9 9
 use App\Models\Store;
10 10
 use App\Storefront\Announcements;
11
+use App\Storefront\Logos\StoreLogos;
11 12
 use App\Storefront\Storefront;
12 13
 use App\StorePlan\FeaturedProducts;
13 14
 use App\StorePlan\HeroImages;
@@ -72,6 +73,8 @@ trait RendersStorefront
72 73
             'shop' => [
73 74
                 // Digits only, such as 60123456789, or null when the merchant has not set one.
74 75
                 'whatsapp' => $store->whatsapp_number,
76
+                // The store's logo (uploaded, a ready design, or drawn by AI), or null to show the name.
77
+                'logo' => app(StoreLogos::class)->present($store),
75 78
                 // In ringgit, or null when shipping is never free.
76 79
                 'free_shipping_over' => $store->free_shipping_over !== null ? $store->free_shipping_over / 100 : null,
77 80
                 // Lines for the slim bar above the header. Empty when the merchant switched it off.

+ 15
- 1
app/Http/Controllers/StoreController.php Прегледај датотеку

@@ -10,6 +10,7 @@ use App\Http\Requests\Stores\CreateStoreRequest;
10 10
 use App\Models\Product;
11 11
 use App\Models\Store;
12 12
 use App\Models\StoreGeneration;
13
+use App\Storefront\Logos\StoreLogos;
13 14
 use App\Storefront\Storefront;
14 15
 use App\StorePlan\FeaturedProducts;
15 16
 use App\StorePlan\HeroImages;
@@ -57,7 +58,7 @@ class StoreController extends Controller
57 58
     /**
58 59
      * Show one store. Looking it up through the user means other people's stores give a 404.
59 60
      */
60
-    public function show(Request $request, UsageLimits $usage, string $slug): Response
61
+    public function show(Request $request, UsageLimits $usage, StoreLogos $logos, string $slug): Response
61 62
     {
62 63
         $store = $request->user()->stores()->where('slug', $slug)->firstOrFail();
63 64
 
@@ -75,6 +76,19 @@ class StoreController extends Controller
75 76
                 ->get()
76 77
                 ->map(fn (StoreGeneration $edit) => $this->presentGeneration($edit)),
77 78
             'usage' => $usage->for($request->user()),
79
+            // The Logo box: the current logo, ready designs, Claude's drawings and the tries left.
80
+            'logo' => [
81
+                'current' => $logos->present($store),
82
+                'name' => $logos->name($store),
83
+                'designs' => StoreLogos::DESIGNS,
84
+                'drafts' => $store->logo_drafts ?? [],
85
+                'tries_left' => $logos->triesLeft($store),
86
+                'tries_total' => $logos->tryLimit(),
87
+                'per_try' => StoreLogos::PER_TRY,
88
+                // So the box can draw the designs in the store's own colours and fonts.
89
+                'theme' => ($store->plan ?? [])['theme'] ?? null,
90
+                'fonts' => PlanSchema::FONTS,
91
+            ],
78 92
             // Featured product sections of the working design, and the products they can show.
79 93
             'featuredSections' => $store->plan !== null ? FeaturedProducts::sections($store->plan) : [],
80 94
             // Hero sections of the working design, and the photos they can use.

+ 106
- 0
app/Http/Controllers/StoreLogoController.php Прегледај датотеку

@@ -0,0 +1,106 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers;
4
+
5
+use App\Ai\AiException;
6
+use App\Models\Store;
7
+use App\Storefront\Logos\StoreLogos;
8
+use Illuminate\Http\RedirectResponse;
9
+use Illuminate\Http\Request;
10
+use Illuminate\Validation\Rule;
11
+use Inertia\Inertia;
12
+use RuntimeException;
13
+
14
+/**
15
+ * The Logo box in the Design tab: upload a logo, pick a ready design, or have Claude draw some.
16
+ * The logo belongs to the store, so a live store shows it right away (no "Publish changes" needed).
17
+ */
18
+class StoreLogoController extends Controller
19
+{
20
+    public function upload(Request $request, string $slug, StoreLogos $logos): RedirectResponse
21
+    {
22
+        $store = $this->ownedStore($request, $slug);
23
+
24
+        $request->validate([
25
+            'logo' => [
26
+                'required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048',
27
+                'dimensions:min_width='.StoreLogos::MIN_SIDE.',min_height='.StoreLogos::MIN_SIDE.',max_width=6000,max_height=6000',
28
+            ],
29
+        ], [
30
+            'logo.max' => __('The logo must be 2 MB or smaller.'),
31
+            'logo.mimes' => __('Use a PNG, JPG or WebP picture. PNG keeps a see-through background.'),
32
+            'logo.dimensions' => __('Use a picture at least :size pixels on each side.', ['size' => StoreLogos::MIN_SIDE]),
33
+        ]);
34
+
35
+        try {
36
+            $logos->upload($store, $request->file('logo'));
37
+        } catch (RuntimeException) {
38
+            return back()->withErrors(['logo' => __('That picture could not be read. Try saving it as PNG.')]);
39
+        }
40
+
41
+        Inertia::flash('toast', ['type' => 'success', 'message' => __('Logo uploaded. It shows on your store now.')]);
42
+
43
+        return back();
44
+    }
45
+
46
+    /**
47
+     * Use a ready design, or one of the logos Claude drew.
48
+     */
49
+    public function choose(Request $request, string $slug, StoreLogos $logos): RedirectResponse
50
+    {
51
+        $store = $this->ownedStore($request, $slug);
52
+
53
+        $validated = $request->validate([
54
+            'design' => ['required_without:drawn', 'nullable', Rule::in(StoreLogos::DESIGNS)],
55
+            'drawn' => ['required_without:design', 'nullable', 'integer', 'min:0'],
56
+        ]);
57
+
58
+        if (filled($validated['design'] ?? null)) {
59
+            $logos->useDesign($store, $validated['design']);
60
+        } elseif (! $logos->useDrawn($store, (int) $validated['drawn'])) {
61
+            return back()->withErrors(['logo' => __('That logo is no longer available.')]);
62
+        }
63
+
64
+        Inertia::flash('toast', ['type' => 'success', 'message' => __('Logo saved. It shows on your store now.')]);
65
+
66
+        return back();
67
+    }
68
+
69
+    /**
70
+     * Ask Claude for new logos. Each store has a lifetime number of tries.
71
+     */
72
+    public function draw(Request $request, string $slug, StoreLogos $logos): RedirectResponse
73
+    {
74
+        $store = $this->ownedStore($request, $slug);
75
+
76
+        try {
77
+            $made = $logos->draw($store);
78
+        } catch (AiException $e) {
79
+            report($e);
80
+
81
+            return back()->withErrors(['logo' => __('The AI could not draw logos just now. This try was not counted. Please try again.')]);
82
+        }
83
+
84
+        if ($made === null) {
85
+            return back()->withErrors(['logo' => __('You have used all :count AI logo tries for this store. You can still pick any logo drawn before, a ready design, or upload your own.', ['count' => $logos->tryLimit()])]);
86
+        }
87
+
88
+        Inertia::flash('toast', ['type' => 'success', 'message' => __('The AI drew :count new logos. Pick one below.', ['count' => $made])]);
89
+
90
+        return back();
91
+    }
92
+
93
+    public function destroy(Request $request, string $slug, StoreLogos $logos): RedirectResponse
94
+    {
95
+        $logos->remove($this->ownedStore($request, $slug));
96
+
97
+        Inertia::flash('toast', ['type' => 'success', 'message' => __('Logo removed. Your store shows its name instead.')]);
98
+
99
+        return back();
100
+    }
101
+
102
+    private function ownedStore(Request $request, string $slug): Store
103
+    {
104
+        return $request->user()->stores()->where('slug', $slug)->firstOrFail();
105
+    }
106
+}

+ 27
- 0
app/Mail/StoreBrand.php Прегледај датотеку

@@ -6,6 +6,7 @@ use App\Models\Order;
6 6
 use App\Models\Store;
7 7
 use App\StorePlan\PlanSchema;
8 8
 use App\Support\MalaysianPhone;
9
+use Illuminate\Support\Facades\Storage;
9 10
 
10 11
 /**
11 12
  * How a store looks in the emails its shoppers get: its name, colours, fonts and corners,
@@ -82,6 +83,32 @@ final readonly class StoreBrand
82 83
         );
83 84
     }
84 85
 
86
+    /**
87
+     * The uploaded logo's full web address, for the top of the email. Designed and AI-drawn logos are not
88
+     * pictures that email apps can show, so those emails show the store's name instead.
89
+     *
90
+     * @return array{url: string, width: int, height: int}|null
91
+     */
92
+    public function logo(): ?array
93
+    {
94
+        $logo = $this->store->logo;
95
+
96
+        if (($logo['type'] ?? null) !== 'upload') {
97
+            return null;
98
+        }
99
+
100
+        $url = Storage::disk('public')->url($logo['path']);
101
+
102
+        // Shown at most 48 pixels high and 220 wide, keeping its shape.
103
+        $scale = min(48 / max(1, $logo['height']), 220 / max(1, $logo['width']), 1);
104
+
105
+        return [
106
+            'url' => str_starts_with($url, 'http') ? $url : url($url),
107
+            'width' => (int) round($logo['width'] * $scale),
108
+            'height' => (int) round($logo['height'] * $scale),
109
+        ];
110
+    }
111
+
85 112
     /**
86 113
      * The email address shoppers can write to, when the merchant set one.
87 114
      */

+ 6
- 0
app/Models/Store.php Прегледај датотеку

@@ -31,6 +31,9 @@ use Illuminate\Support\Str;
31 31
  * @property array<string, mixed>|null $plan
32 32
  * @property string|null $whatsapp_number
33 33
  * @property string|null $contact_email Where shoppers' replies to the store's emails go
34
+ * @property array{type: 'upload', path: string, width: int, height: int}|array{type: 'design', key: string}|array{type: 'drawn', svg: string}|null $logo
35
+ * @property list<string>|null $logo_drafts Logos Claude drew for this store (cleaned SVG)
36
+ * @property int $ai_logo_tries Successful "Draw with AI" tries, for the lifetime limit
34 37
  * @property int $shipping_west
35 38
  * @property int $shipping_east
36 39
  * @property int|null $free_shipping_over
@@ -236,6 +239,9 @@ class Store extends Model
236 239
             'announcement_enabled' => 'boolean',
237 240
             'announcement_messages' => 'array',
238 241
             'pickup_address' => 'array',
242
+            'logo' => 'array',
243
+            'logo_drafts' => 'array',
244
+            'ai_logo_tries' => 'integer',
239 245
             'parcel_weight' => 'integer',
240 246
             'parcel_size' => 'array',
241 247
         ];

+ 216
- 0
app/Storefront/Logos/LogoSvg.php Прегледај датотеку

@@ -0,0 +1,216 @@
1
+<?php
2
+
3
+namespace App\Storefront\Logos;
4
+
5
+use DOMDocument;
6
+use DOMElement;
7
+use DOMNode;
8
+
9
+/**
10
+ * Makes a logo drawing from the AI safe to put inside a store page.
11
+ *
12
+ * The drawing is rebuilt from scratch, keeping only simple shapes, text and colour gradients, with a short
13
+ * list of attributes whose values are checked. Anything that could run code or load something from outside
14
+ * (scripts, links, pictures, styles, event handlers, foreign content) is dropped. Text always uses the
15
+ * store's heading font, through a CSS variable the storefront sets.
16
+ */
17
+final class LogoSvg
18
+{
19
+    /** Bigger drawings are refused: a logo is a few shapes. */
20
+    public const int MAX_BYTES = 20000;
21
+
22
+    private const int MAX_ELEMENTS = 300;
23
+
24
+    private const array ELEMENTS = [
25
+        'svg', 'g', 'path', 'circle', 'ellipse', 'rect', 'line', 'polyline', 'polygon',
26
+        'text', 'tspan', 'defs', 'lineargradient', 'radialgradient', 'stop',
27
+    ];
28
+
29
+    private const array NUMBERS = [
30
+        'x', 'y', 'x1', 'y1', 'x2', 'y2', 'cx', 'cy', 'r', 'rx', 'ry', 'fx', 'fy', 'width', 'height',
31
+        'stroke-width', 'opacity', 'fill-opacity', 'stroke-opacity', 'stop-opacity', 'font-size', 'letter-spacing', 'offset', 'dx', 'dy',
32
+    ];
33
+
34
+    private const array COLORS = ['fill', 'stroke', 'stop-color'];
35
+
36
+    private const array KEYWORDS = [
37
+        'stroke-linecap' => ['butt', 'round', 'square'],
38
+        'stroke-linejoin' => ['miter', 'round', 'bevel'],
39
+        'fill-rule' => ['nonzero', 'evenodd'],
40
+        'clip-rule' => ['nonzero', 'evenodd'],
41
+        'text-anchor' => ['start', 'middle', 'end'],
42
+        'dominant-baseline' => ['auto', 'middle', 'central', 'hanging', 'alphabetic'],
43
+        'font-weight' => ['normal', 'bold', '300', '400', '500', '600', '700', '800', '900'],
44
+        'font-style' => ['normal', 'italic'],
45
+        'gradientunits' => ['userSpaceOnUse', 'objectBoundingBox'],
46
+    ];
47
+
48
+    /**
49
+     * The cleaned drawing, or null when it is not a usable logo.
50
+     */
51
+    public static function clean(string $svg): ?string
52
+    {
53
+        $svg = trim($svg);
54
+
55
+        if ($svg === '' || strlen($svg) > self::MAX_BYTES || stripos($svg, '<!DOCTYPE') !== false || stripos($svg, '<!ENTITY') !== false) {
56
+            return null;
57
+        }
58
+
59
+        $source = new DOMDocument;
60
+        $previous = libxml_use_internal_errors(true);
61
+        // No network, no entities: the text is only read, never trusted.
62
+        $loaded = $source->loadXML($svg, LIBXML_NONET);
63
+        libxml_clear_errors();
64
+        libxml_use_internal_errors($previous);
65
+
66
+        $root = $source->documentElement;
67
+
68
+        if (! $loaded || ! $root instanceof DOMElement || strtolower($root->localName) !== 'svg') {
69
+            return null;
70
+        }
71
+
72
+        $viewBox = self::viewBox($root->getAttribute('viewBox'));
73
+
74
+        if ($viewBox === null) {
75
+            return null;
76
+        }
77
+
78
+        $target = new DOMDocument;
79
+        $out = $target->createElementNS('http://www.w3.org/2000/svg', 'svg');
80
+        $out->setAttribute('viewBox', $viewBox);
81
+        $target->appendChild($out);
82
+
83
+        // Ids get a random prefix, so two logos on one page never share a gradient by accident.
84
+        $prefix = 'l'.bin2hex(random_bytes(3)).'-';
85
+        $count = 0;
86
+
87
+        foreach (iterator_to_array($root->childNodes) as $child) {
88
+            self::copy($child, $out, $target, $prefix, $count);
89
+        }
90
+
91
+        if ($count === 0 || $count > self::MAX_ELEMENTS) {
92
+            return null;
93
+        }
94
+
95
+        $result = $target->saveXML($out);
96
+
97
+        return is_string($result) && strlen($result) <= self::MAX_BYTES ? $result : null;
98
+    }
99
+
100
+    private static function copy(DOMNode $node, DOMElement $parent, DOMDocument $target, string $prefix, int &$count): void
101
+    {
102
+        if ($node->nodeType === XML_TEXT_NODE) {
103
+            // Only text inside text elements matters; whitespace elsewhere is dropped.
104
+            if (in_array(strtolower($parent->localName), ['text', 'tspan'], true) && trim((string) $node->nodeValue) !== '') {
105
+                $parent->appendChild($target->createTextNode((string) $node->nodeValue));
106
+            }
107
+
108
+            return;
109
+        }
110
+
111
+        if (! $node instanceof DOMElement) {
112
+            return;
113
+        }
114
+
115
+        $name = strtolower($node->localName);
116
+
117
+        if (! in_array($name, self::ELEMENTS, true) || $name === 'svg') {
118
+            return;
119
+        }
120
+
121
+        $count++;
122
+
123
+        if ($count > self::MAX_ELEMENTS) {
124
+            return;
125
+        }
126
+
127
+        $element = $target->createElementNS('http://www.w3.org/2000/svg', $node->localName);
128
+
129
+        foreach (iterator_to_array($node->attributes ?? []) as $attribute) {
130
+            $key = strtolower($attribute->localName);
131
+            $value = self::value($key, trim($attribute->value), $prefix);
132
+
133
+            if ($value !== null) {
134
+                $element->setAttribute($attribute->localName, $value);
135
+            }
136
+        }
137
+
138
+        if (in_array($name, ['text', 'tspan'], true)) {
139
+            $element->setAttribute('style', 'font-family: var(--sf-font-heading, sans-serif)');
140
+        }
141
+
142
+        $parent->appendChild($element);
143
+
144
+        foreach (iterator_to_array($node->childNodes) as $child) {
145
+            self::copy($child, $element, $target, $prefix, $count);
146
+        }
147
+    }
148
+
149
+    /**
150
+     * The checked value of an attribute, or null to drop it.
151
+     */
152
+    private static function value(string $key, string $value, string $prefix): ?string
153
+    {
154
+        if ($value === '' || strlen($value) > 4000) {
155
+            return null;
156
+        }
157
+
158
+        if ($key === 'id') {
159
+            return preg_match('/^[A-Za-z][A-Za-z0-9_-]{0,40}$/', $value) === 1 ? $prefix.$value : null;
160
+        }
161
+
162
+        if (in_array($key, self::NUMBERS, true)) {
163
+            return preg_match('/^-?\d*\.?\d+(%|px|em)?$/', $value) === 1 ? $value : null;
164
+        }
165
+
166
+        if (in_array($key, self::COLORS, true)) {
167
+            return self::color($value, $prefix);
168
+        }
169
+
170
+        if (isset(self::KEYWORDS[$key])) {
171
+            return in_array($value, self::KEYWORDS[$key], true) ? $value : null;
172
+        }
173
+
174
+        return match ($key) {
175
+            // Path data and point lists: numbers, letters for commands, commas and spaces only.
176
+            'd' => preg_match('/^[MmLlHhVvCcSsQqTtAaZz0-9eE.,\s+-]+$/', $value) === 1 ? $value : null,
177
+            'points' => preg_match('/^[0-9eE.,\s+-]+$/', $value) === 1 ? $value : null,
178
+            'transform', 'gradienttransform' => preg_match('/^((translate|scale|rotate|matrix|skewX|skewY)\(\s*[-0-9eE.,\s]+\)\s*)+$/', $value) === 1 ? $value : null,
179
+            default => null,
180
+        };
181
+    }
182
+
183
+    private static function color(string $value, string $prefix): ?string
184
+    {
185
+        if (preg_match('/^#[0-9A-Fa-f]{3}([0-9A-Fa-f]{3})?$/', $value) === 1 || in_array(strtolower($value), ['none', 'currentcolor', 'white', 'black', 'transparent'], true)) {
186
+            return $value;
187
+        }
188
+
189
+        // A gradient defined in the same drawing.
190
+        if (preg_match('/^url\(#([A-Za-z][A-Za-z0-9_-]{0,40})\)$/', $value, $match) === 1) {
191
+            return 'url(#'.$prefix.$match[1].')';
192
+        }
193
+
194
+        return null;
195
+    }
196
+
197
+    /**
198
+     * Four numbers, with a sensible logo shape: not tiny, not huge, not taller than wide by much.
199
+     */
200
+    private static function viewBox(string $value): ?string
201
+    {
202
+        $parts = preg_split('/[\s,]+/', trim($value)) ?: [];
203
+
204
+        if (count($parts) !== 4 || array_filter($parts, fn (string $part) => ! is_numeric($part)) !== []) {
205
+            return null;
206
+        }
207
+
208
+        [$x, $y, $width, $height] = array_map('floatval', $parts);
209
+
210
+        if ($width < 20 || $height < 20 || $width > 2000 || $height > 2000 || $width / $height > 8 || $height / $width > 2) {
211
+            return null;
212
+        }
213
+
214
+        return implode(' ', array_map(fn (float $number) => rtrim(rtrim(number_format($number, 2, '.', ''), '0'), '.'), [$x, $y, $width, $height]));
215
+    }
216
+}

+ 236
- 0
app/Storefront/Logos/StoreLogos.php Прегледај датотеку

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

+ 15
- 0
config/ai.php Прегледај датотеку

@@ -37,6 +37,13 @@ return [
37 37
             'max_tokens' => 6000,
38 38
         ],
39 39
 
40
+        // "Draw with AI" in the Logo box: three simple SVG logos from the brand. Claude draws well.
41
+        'logo' => [
42
+            'provider' => env('AI_LOGO_PROVIDER') ?: 'claude',
43
+            'model' => env('AI_LOGO_MODEL') ?: 'claude-sonnet-5-5',
44
+            'max_tokens' => 12000,
45
+        ],
46
+
40 47
         // The short daily note at the top of the dashboard ("Store pulse"). A cheap model is enough.
41 48
         'pulse' => [
42 49
             'provider' => env('AI_PULSE_PROVIDER') ?: 'deepseek',
@@ -54,6 +61,14 @@ return [
54 61
         'daily_rewrites' => (int) env('AI_PULSE_DAILY_REWRITES', 3),
55 62
     ],
56 63
 
64
+    /*
65
+     * "Draw with AI" logos: how many tries each store gets, ever (each try draws 3 logos).
66
+     * A try that brings back nothing usable is not counted.
67
+     */
68
+    'logo' => [
69
+        'lifetime_tries' => (int) env('AI_LOGO_LIFETIME_TRIES', 3),
70
+    ],
71
+
57 72
     'providers' => [
58 73
         'claude' => [
59 74
             'driver' => ClaudeDriver::class,

+ 27
- 0
database/migrations/2026_11_30_000003_add_logo_to_stores.php Прегледај датотеку

@@ -0,0 +1,27 @@
1
+<?php
2
+
3
+use Illuminate\Database\Migrations\Migration;
4
+use Illuminate\Database\Schema\Blueprint;
5
+use Illuminate\Support\Facades\Schema;
6
+
7
+return new class extends Migration
8
+{
9
+    public function up(): void
10
+    {
11
+        Schema::table('stores', function (Blueprint $table) {
12
+            // The store's logo: an uploaded picture, one of our ready designs, or one Claude drew.
13
+            $table->json('logo')->nullable()->after('contact_email');
14
+            // Every logo Claude drew for this store (cleaned SVG), so the merchant can pick one later.
15
+            $table->json('logo_drafts')->nullable()->after('logo');
16
+            // Successful "Draw with AI" tries. There is a lifetime limit per store.
17
+            $table->unsignedSmallInteger('ai_logo_tries')->default(0)->after('logo_drafts');
18
+        });
19
+    }
20
+
21
+    public function down(): void
22
+    {
23
+        Schema::table('stores', function (Blueprint $table) {
24
+            $table->dropColumn(['logo', 'logo_drafts', 'ai_logo_tries']);
25
+        });
26
+    }
27
+};

+ 324
- 0
resources/js/components/stores/logo-box.tsx Прегледај датотеку

@@ -0,0 +1,324 @@
1
+import { router, useForm, usePage } from '@inertiajs/react';
2
+import {
3
+    Check,
4
+    ChevronDown,
5
+    Sparkles,
6
+    Stamp,
7
+    Trash2,
8
+    Upload,
9
+} from 'lucide-react';
10
+import type { FormEvent } from 'react';
11
+import { useState } from 'react';
12
+import StoreLogoController from '@/actions/App/Http/Controllers/StoreLogoController';
13
+import InputError from '@/components/input-error';
14
+import { Button } from '@/components/ui/button';
15
+import { Spinner } from '@/components/ui/spinner';
16
+import { cn } from '@/lib/utils';
17
+import { LogoDesign, StoreLogo } from '@/storefront/logo';
18
+import { fontStylesheetUrl, themeStyle } from '@/storefront/theme';
19
+import type {
20
+    FontMap,
21
+    LogoDesignKey,
22
+    StoreLogoData,
23
+    Theme,
24
+} from '@/storefront/types';
25
+import type { Store } from '@/types';
26
+
27
+export type LogoSettings = {
28
+    current: StoreLogoData | null;
29
+    /** The words the logo shows: the store header's words. */
30
+    name: string;
31
+    designs: LogoDesignKey[];
32
+    /** Logos the AI drew for this store, cleaned on the server. */
33
+    drafts: string[];
34
+    tries_left: number;
35
+    tries_total: number;
36
+    per_try: number;
37
+    theme: Theme | null;
38
+    fonts: FontMap;
39
+};
40
+
41
+/**
42
+ * The Logo box in the Design tab: upload a logo, pick a ready design, or have the AI draw some.
43
+ * The logo belongs to the store, so it shows on the live store right away.
44
+ */
45
+export function LogoBox({
46
+    store,
47
+    logo,
48
+    busy,
49
+}: {
50
+    store: Store;
51
+    logo: LogoSettings;
52
+    busy: boolean;
53
+}) {
54
+    const [saving, setSaving] = useState(false);
55
+    const [drawing, setDrawing] = useState(false);
56
+    const upload = useForm<{ logo: File | null }>({ logo: null });
57
+    const errors = usePage().props.errors as Record<string, string | undefined>;
58
+    const disabled = busy || saving || drawing || upload.processing;
59
+
60
+    // The store's colours and fonts, so every design looks as it will in the store.
61
+    const look = logo.theme ? themeStyle(logo.theme, logo.fonts) : undefined;
62
+    const fontUrl = logo.theme
63
+        ? fontStylesheetUrl(logo.theme, logo.fonts)
64
+        : null;
65
+
66
+    const choose = (data: { design: LogoDesignKey } | { drawn: number }) => {
67
+        setSaving(true);
68
+        router.put(StoreLogoController.choose.url(store.slug), data, {
69
+            preserveScroll: true,
70
+            onFinish: () => setSaving(false),
71
+        });
72
+    };
73
+
74
+    const remove = () => {
75
+        if (
76
+            !window.confirm(
77
+                'Remove the logo? Your store will show its name instead.',
78
+            )
79
+        ) {
80
+            return;
81
+        }
82
+
83
+        setSaving(true);
84
+        router.delete(StoreLogoController.destroy.url(store.slug), {
85
+            preserveScroll: true,
86
+            onFinish: () => setSaving(false),
87
+        });
88
+    };
89
+
90
+    const send = (event: FormEvent) => {
91
+        event.preventDefault();
92
+        upload.post(StoreLogoController.upload.url(store.slug), {
93
+            preserveScroll: true,
94
+            forceFormData: true,
95
+            onSuccess: () => upload.reset(),
96
+        });
97
+    };
98
+
99
+    const draw = () => {
100
+        setDrawing(true);
101
+        router.post(
102
+            StoreLogoController.draw.url(store.slug),
103
+            {},
104
+            { preserveScroll: true, onFinish: () => setDrawing(false) },
105
+        );
106
+    };
107
+
108
+    const isCurrent = (data: { design: LogoDesignKey } | { drawn: string }) =>
109
+        'design' in data
110
+            ? logo.current?.type === 'design' &&
111
+              logo.current.key === data.design
112
+            : logo.current?.type === 'drawn' && logo.current.svg === data.drawn;
113
+
114
+    return (
115
+        <details className="group rounded-xl border p-4" data-test="logo-box">
116
+            {fontUrl && <link rel="stylesheet" href={fontUrl} />}
117
+            <summary className="flex cursor-pointer list-none items-start gap-3 [&::-webkit-details-marker]:hidden">
118
+                <Stamp className="mt-0.5 size-5 shrink-0 text-muted-foreground" />
119
+                <div>
120
+                    <h3 className="font-medium">Logo</h3>
121
+                    <p className="mt-0.5 text-sm text-muted-foreground">
122
+                        Upload your logo, pick a ready design, or let the AI
123
+                        draw some. It shows on your store right away.
124
+                    </p>
125
+                </div>
126
+                <ChevronDown
127
+                    className="mt-1 ml-auto size-4 shrink-0 text-muted-foreground transition-transform group-open:rotate-180"
128
+                    aria-hidden="true"
129
+                />
130
+            </summary>
131
+
132
+            <div className="mt-5 space-y-6">
133
+                {/* What the store shows now */}
134
+                <div className="space-y-2">
135
+                    <p className="text-sm font-medium">Your logo now</p>
136
+                    <div className="flex flex-wrap items-center gap-3">
137
+                        <div
138
+                            style={look}
139
+                            className="flex min-h-20 min-w-56 items-center rounded-lg border bg-(--sf-bg,white) px-5 py-4"
140
+                            data-test="current-logo"
141
+                        >
142
+                            {logo.current ? (
143
+                                <StoreLogo
144
+                                    logo={logo.current}
145
+                                    name={logo.name}
146
+                                />
147
+                            ) : (
148
+                                <span className="text-sm text-muted-foreground">
149
+                                    No logo yet. Your store shows its name.
150
+                                </span>
151
+                            )}
152
+                        </div>
153
+                        {logo.current && (
154
+                            <Button
155
+                                type="button"
156
+                                variant="ghost"
157
+                                size="sm"
158
+                                onClick={remove}
159
+                                disabled={disabled}
160
+                            >
161
+                                <Trash2 />
162
+                                Remove
163
+                            </Button>
164
+                        )}
165
+                    </div>
166
+                    <InputError message={errors.logo} />
167
+                </div>
168
+
169
+                {/* Upload */}
170
+                <form onSubmit={send} className="space-y-2" noValidate>
171
+                    <p className="text-sm font-medium">Upload your own</p>
172
+                    <div className="flex flex-wrap items-center gap-2">
173
+                        <label htmlFor="logo-file" className="sr-only">
174
+                            Choose a logo picture
175
+                        </label>
176
+                        <input
177
+                            id="logo-file"
178
+                            type="file"
179
+                            accept="image/png,image/jpeg,image/webp"
180
+                            onChange={(event) =>
181
+                                upload.setData(
182
+                                    'logo',
183
+                                    event.target.files?.[0] ?? null,
184
+                                )
185
+                            }
186
+                            className="max-w-full text-sm file:mr-3 file:rounded-md file:border file:bg-transparent file:px-3 file:py-1.5 file:text-sm file:font-medium"
187
+                        />
188
+                        <Button
189
+                            size="sm"
190
+                            variant="outline"
191
+                            disabled={disabled || upload.data.logo === null}
192
+                        >
193
+                            {upload.processing ? <Spinner /> : <Upload />}
194
+                            Upload logo
195
+                        </Button>
196
+                    </div>
197
+                    <p className="text-xs text-muted-foreground">
198
+                        PNG, JPG or WebP, up to 2 MB. A PNG with a see-through
199
+                        background looks best. A wide logo suits the top of your
200
+                        store.
201
+                    </p>
202
+                    <InputError message={upload.errors.logo} />
203
+                </form>
204
+
205
+                {/* Ready designs */}
206
+                {logo.theme && (
207
+                    <div className="space-y-2">
208
+                        <p className="text-sm font-medium">Ready designs</p>
209
+                        <p className="text-xs text-muted-foreground">
210
+                            Made from your store name, fonts and colours. They
211
+                            change with your store&apos;s look.
212
+                        </p>
213
+                        <div
214
+                            style={look}
215
+                            className="grid gap-2 sm:grid-cols-2"
216
+                            data-test="logo-designs"
217
+                        >
218
+                            {logo.designs.map((design) => (
219
+                                <LogoChoice
220
+                                    key={design}
221
+                                    current={isCurrent({ design })}
222
+                                    disabled={disabled}
223
+                                    onChoose={() => choose({ design })}
224
+                                >
225
+                                    <LogoDesign
226
+                                        design={design}
227
+                                        name={logo.name}
228
+                                    />
229
+                                </LogoChoice>
230
+                            ))}
231
+                        </div>
232
+                    </div>
233
+                )}
234
+
235
+                {/* Drawn by AI */}
236
+                <div className="space-y-2">
237
+                    <p className="text-sm font-medium">Draw with AI</p>
238
+                    <p className="text-xs text-muted-foreground">
239
+                        The AI draws {logo.per_try} new logos for your brand
240
+                        each time, in your colours. You have{' '}
241
+                        <span
242
+                            className="font-medium text-foreground"
243
+                            data-test="logo-tries-left"
244
+                        >
245
+                            {logo.tries_left} of {logo.tries_total}
246
+                        </span>{' '}
247
+                        tries left for this store. A try that fails is not
248
+                        counted.
249
+                    </p>
250
+                    <Button
251
+                        type="button"
252
+                        size="sm"
253
+                        onClick={draw}
254
+                        disabled={disabled || logo.tries_left === 0}
255
+                        data-test="logo-draw"
256
+                    >
257
+                        {drawing ? <Spinner /> : <Sparkles />}
258
+                        {drawing
259
+                            ? 'Drawing… about 30 seconds'
260
+                            : logo.tries_left === 0
261
+                              ? 'No tries left'
262
+                              : `Draw ${logo.per_try} logos`}
263
+                    </Button>
264
+
265
+                    {logo.drafts.length > 0 && (
266
+                        <div
267
+                            style={look}
268
+                            className="grid gap-2 pt-2 sm:grid-cols-2"
269
+                            data-test="logo-drafts"
270
+                        >
271
+                            {logo.drafts.map((svg, index) => (
272
+                                <LogoChoice
273
+                                    key={svg}
274
+                                    current={isCurrent({ drawn: svg })}
275
+                                    disabled={disabled}
276
+                                    onChoose={() => choose({ drawn: index })}
277
+                                >
278
+                                    <StoreLogo
279
+                                        logo={{ type: 'drawn', svg }}
280
+                                        name={logo.name}
281
+                                    />
282
+                                </LogoChoice>
283
+                            ))}
284
+                        </div>
285
+                    )}
286
+                </div>
287
+            </div>
288
+        </details>
289
+    );
290
+}
291
+
292
+/** One logo to pick, on the store's background colour. */
293
+function LogoChoice({
294
+    current,
295
+    disabled,
296
+    onChoose,
297
+    children,
298
+}: {
299
+    current: boolean;
300
+    disabled: boolean;
301
+    onChoose: () => void;
302
+    children: React.ReactNode;
303
+}) {
304
+    return (
305
+        <button
306
+            type="button"
307
+            onClick={onChoose}
308
+            disabled={disabled || current}
309
+            aria-pressed={current}
310
+            className={cn(
311
+                'relative flex min-h-20 items-center justify-center overflow-hidden rounded-lg border bg-(--sf-bg) px-4 py-4 transition hover:border-foreground/40 disabled:cursor-default',
312
+                current && 'border-emerald-600 ring-2 ring-emerald-600/30',
313
+            )}
314
+        >
315
+            {children}
316
+            {current && (
317
+                <span className="absolute top-1.5 right-1.5 flex items-center gap-1 rounded-full bg-emerald-600 px-1.5 py-0.5 text-[10px] font-medium text-white">
318
+                    <Check className="size-3" />
319
+                    In use
320
+                </span>
321
+            )}
322
+        </button>
323
+    );
324
+}

+ 6
- 0
resources/js/pages/stores/show.tsx Прегледај датотеку

@@ -15,6 +15,8 @@ import DesignChat from '@/components/stores/design-chat';
15 15
 import FeaturedPicker from '@/components/stores/featured-picker';
16 16
 import HeroPicker from '@/components/stores/hero-picker';
17 17
 import BentoBox from '@/components/stores/bento-box';
18
+import type { LogoSettings } from '@/components/stores/logo-box';
19
+import { LogoBox } from '@/components/stores/logo-box';
18 20
 import LayoutPicker from '@/components/stores/layout-picker';
19 21
 import VideoBox from '@/components/stores/video-box';
20 22
 import StylePicker from '@/components/stores/style-picker';
@@ -86,6 +88,7 @@ type Props = {
86 88
     bentoSections: BentoSectionInfo[];
87 89
     homeSections: HomeSectionInfo[];
88 90
     linkSuggestions: LinkSuggestion[];
91
+    logo: LogoSettings;
89 92
 };
90 93
 
91 94
 export default function ShowStore({
@@ -105,6 +108,7 @@ export default function ShowStore({
105 108
     bentoSections,
106 109
     homeSections,
107 110
     linkSuggestions,
111
+    logo,
108 112
 }: Props) {
109 113
     const [device, setDevice] = useState<Device>('desktop');
110 114
     const [confirmOpen, setConfirmOpen] = useState(false);
@@ -417,6 +421,8 @@ export default function ShowStore({
417 421
                                 />
418 422
                             </div>
419 423
 
424
+                            <LogoBox store={store} logo={logo} busy={busy} />
425
+
420 426
                             <StylePicker
421 427
                                 store={store}
422 428
                                 current={style}

+ 203
- 0
resources/js/storefront/logo.tsx Прегледај датотеку

@@ -0,0 +1,203 @@
1
+import { cn } from '@/lib/utils';
2
+import type { LogoDesignKey, StoreLogoData } from './types';
3
+
4
+/** Keep in step with StoreLogos::DESIGNS. */
5
+export const LOGO_DESIGNS: LogoDesignKey[] = [
6
+    'wordmark',
7
+    'spaced',
8
+    'monogram-circle',
9
+    'monogram-square',
10
+    'two-tone',
11
+    'underline',
12
+    'badge',
13
+    'dot',
14
+];
15
+
16
+/** Up to two letters for a badge: the first letters of the first two words. */
17
+export function initials(name: string): string {
18
+    const words = name
19
+        .replace(/[^\p{L}\p{N}\s]/gu, ' ')
20
+        .split(/\s+/)
21
+        .filter(Boolean);
22
+
23
+    return (
24
+        words.length > 1
25
+            ? words[0][0] + words[1][0]
26
+            : (words[0] ?? '?').slice(0, 2)
27
+    ).toUpperCase();
28
+}
29
+
30
+/**
31
+ * A store's logo. Reads the store's colours and fonts from the storefront's CSS variables,
32
+ * so ready designs follow the store's look when it changes.
33
+ */
34
+export function StoreLogo({
35
+    logo,
36
+    name,
37
+    className,
38
+}: {
39
+    logo: StoreLogoData;
40
+    name: string;
41
+    className?: string;
42
+}) {
43
+    if (logo.type === 'upload') {
44
+        return (
45
+            <img
46
+                src={logo.url}
47
+                width={logo.width}
48
+                height={logo.height}
49
+                alt={name}
50
+                className={cn(
51
+                    'h-10 w-auto max-w-[200px] object-contain md:h-12',
52
+                    className,
53
+                )}
54
+                data-test="store-logo"
55
+            />
56
+        );
57
+    }
58
+
59
+    if (logo.type === 'drawn') {
60
+        return (
61
+            <span
62
+                role="img"
63
+                aria-label={name}
64
+                className={cn(
65
+                    'block h-10 md:h-12 [&>svg]:h-full [&>svg]:w-auto [&>svg]:max-w-[260px]',
66
+                    className,
67
+                )}
68
+                // Cleaned on the server by LogoSvg: simple shapes and text only.
69
+                dangerouslySetInnerHTML={{ __html: logo.svg }}
70
+                data-test="store-logo"
71
+            />
72
+        );
73
+    }
74
+
75
+    return <LogoDesign design={logo.key} name={name} className={className} />;
76
+}
77
+
78
+/** One of the ready designs, drawn from the store's name, fonts and colours. */
79
+export function LogoDesign({
80
+    design,
81
+    name,
82
+    className,
83
+}: {
84
+    design: LogoDesignKey;
85
+    name: string;
86
+    className?: string;
87
+}) {
88
+    const heading = 'font-(family-name:--sf-font-heading) text-(--sf-fg)';
89
+    const mark = (shape: 'circle' | 'square') => (
90
+        <span
91
+            aria-hidden="true"
92
+            className={cn(
93
+                'flex size-9 shrink-0 items-center justify-center bg-(--sf-primary) text-sm font-bold tracking-wide text-(--sf-primary-fg)',
94
+                shape === 'circle' ? 'rounded-full' : 'rounded-(--sf-radius)',
95
+            )}
96
+        >
97
+            {initials(name)}
98
+        </span>
99
+    );
100
+    const [first, ...rest] = name.split(' ');
101
+
102
+    const body = (() => {
103
+        switch (design) {
104
+            case 'spaced':
105
+                return (
106
+                    <span
107
+                        className={cn(
108
+                            heading,
109
+                            'text-lg font-semibold tracking-[0.22em] uppercase',
110
+                        )}
111
+                    >
112
+                        {name}
113
+                    </span>
114
+                );
115
+            case 'monogram-circle':
116
+            case 'monogram-square':
117
+                return (
118
+                    <span className="inline-flex items-center gap-2.5">
119
+                        {mark(
120
+                            design === 'monogram-circle' ? 'circle' : 'square',
121
+                        )}
122
+                        <span className={cn(heading, 'text-xl font-semibold')}>
123
+                            {name}
124
+                        </span>
125
+                    </span>
126
+                );
127
+            case 'two-tone':
128
+                return (
129
+                    <span
130
+                        className={cn(
131
+                            heading,
132
+                            'text-xl font-bold tracking-tight',
133
+                        )}
134
+                    >
135
+                        <span className="text-(--sf-primary)">{first}</span>
136
+                        {rest.length > 0 && ` ${rest.join(' ')}`}
137
+                    </span>
138
+                );
139
+            case 'underline':
140
+                return (
141
+                    <span className="inline-flex flex-col items-start gap-1">
142
+                        <span
143
+                            className={cn(
144
+                                heading,
145
+                                'text-xl leading-none font-bold',
146
+                            )}
147
+                        >
148
+                            {name}
149
+                        </span>
150
+                        <span
151
+                            aria-hidden="true"
152
+                            className="h-[3px] w-2/5 rounded-full bg-(--sf-accent)"
153
+                        />
154
+                    </span>
155
+                );
156
+            case 'badge':
157
+                return (
158
+                    <span
159
+                        className={cn(
160
+                            heading,
161
+                            'rounded-(--sf-radius) border-2 border-(--sf-fg) px-3 py-1 text-sm font-bold tracking-[0.16em] uppercase',
162
+                        )}
163
+                    >
164
+                        {name}
165
+                    </span>
166
+                );
167
+            case 'dot':
168
+                return (
169
+                    <span
170
+                        className={cn(
171
+                            heading,
172
+                            'text-xl font-bold tracking-tight',
173
+                        )}
174
+                    >
175
+                        {name}
176
+                        <span aria-hidden="true" className="text-(--sf-accent)">
177
+                            .
178
+                        </span>
179
+                    </span>
180
+                );
181
+            default:
182
+                return (
183
+                    <span className={cn(heading, 'text-xl font-semibold')}>
184
+                        {name}
185
+                    </span>
186
+                );
187
+        }
188
+    })();
189
+
190
+    return (
191
+        <span
192
+            className={cn(
193
+                'inline-flex items-center whitespace-nowrap',
194
+                className,
195
+            )}
196
+            aria-label={name}
197
+            role="img"
198
+            data-test="store-logo"
199
+        >
200
+            {body}
201
+        </span>
202
+    );
203
+}

+ 14
- 3
resources/js/storefront/sections/header.tsx Прегледај датотеку

@@ -2,6 +2,7 @@ import { Menu, ShoppingBag, X } from 'lucide-react';
2 2
 import { useEffect, useState } from 'react';
3 3
 import { cn } from '@/lib/utils';
4 4
 import { useStorefront } from '../context';
5
+import { StoreLogo } from '../logo';
5 6
 import { storefrontText } from '../text';
6 7
 import type { HeaderSection } from '../types';
7 8
 import { Container, SfButton, SfLink } from '../ui';
@@ -13,7 +14,7 @@ export function Header({
13 14
 }) {
14 15
     const { logoText, links, cta } = section.content;
15 16
     const centered = section.variant === 'centered';
16
-    const { cart, language } = useStorefront();
17
+    const { cart, language, shop } = useStorefront();
17 18
     const t = storefrontText(language);
18 19
     const [open, setOpen] = useState(false);
19 20
 
@@ -86,8 +87,18 @@ export function Header({
86 87
             >
87 88
                 {centered && <div className="md:hidden">{menuButton}</div>}
88 89
 
89
-                <SfLink href="#" className="sf-heading text-xl font-semibold">
90
-                    {logoText}
90
+                <SfLink
91
+                    href="#"
92
+                    className={cn(
93
+                        'shrink-0',
94
+                        !shop.logo && 'sf-heading text-xl font-semibold',
95
+                    )}
96
+                >
97
+                    {shop.logo ? (
98
+                        <StoreLogo logo={shop.logo} name={logoText} />
99
+                    ) : (
100
+                        logoText
101
+                    )}
91 102
                 </SfLink>
92 103
 
93 104
                 <nav

+ 19
- 0
resources/js/storefront/types.ts Прегледај датотеку

@@ -364,6 +364,8 @@ export type StoreOrder = {
364 364
 export type ShopInfo = {
365 365
     /** Digits only with country code, such as 60123456789. */
366 366
     whatsapp: string | null;
367
+    /** The store's logo, or null to show its name. */
368
+    logo?: StoreLogoData | null;
367 369
     /** In ringgit. Orders at or above this ship free. */
368 370
     free_shipping_over: number | null;
369 371
     /** Collections with at least one product shoppers can see. */
@@ -408,3 +410,20 @@ export type StoreCollection = {
408 410
     image: string | null;
409 411
     count: number;
410 412
 };
413
+
414
+/** A store's logo: an uploaded picture, one of the ready designs, or a cleaned drawing by the AI. */
415
+export type StoreLogoData =
416
+    | { type: 'upload'; url: string; width: number; height: number }
417
+    | { type: 'design'; key: LogoDesignKey }
418
+    | { type: 'drawn'; svg: string };
419
+
420
+/** Keep in step with StoreLogos::DESIGNS. */
421
+export type LogoDesignKey =
422
+    | 'wordmark'
423
+    | 'spaced'
424
+    | 'monogram-circle'
425
+    | 'monogram-square'
426
+    | 'two-tone'
427
+    | 'underline'
428
+    | 'badge'
429
+    | 'dot';

+ 5
- 1
resources/views/components/mail/store.blade.php Прегледај датотеку

@@ -31,7 +31,11 @@
31 31
                 {{-- Store name --}}
32 32
                 <tr>
33 33
                     <td align="center" style="padding: 0 0 24px;">
34
-                        <a href="{{ $brand->storeUrl() }}" style="font-family: {{ $brand->headingFont }}; font-size: 24px; font-weight: 700; letter-spacing: -0.01em; color: {{ $brand->color('foreground') }}; text-decoration: none;">{{ $brand->name }}</a>
34
+                        @if ($logo = $brand->logo())
35
+                            <a href="{{ $brand->storeUrl() }}" style="text-decoration: none;"><img src="{{ $logo['url'] }}" width="{{ $logo['width'] }}" height="{{ $logo['height'] }}" alt="{{ $brand->name }}" style="display: block; border: 0; width: {{ $logo['width'] }}px; height: {{ $logo['height'] }}px;"></a>
36
+                        @else
37
+                            <a href="{{ $brand->storeUrl() }}" style="font-family: {{ $brand->headingFont }}; font-size: 24px; font-weight: 700; letter-spacing: -0.01em; color: {{ $brand->color('foreground') }}; text-decoration: none;">{{ $brand->name }}</a>
38
+                        @endif
35 39
                     </td>
36 40
                 </tr>
37 41
 

+ 6
- 0
routes/web.php Прегледај датотеку

@@ -19,6 +19,7 @@ use App\Http\Controllers\SectionLayoutController;
19 19
 use App\Http\Controllers\StoreController;
20 20
 use App\Http\Controllers\StoreDesignController;
21 21
 use App\Http\Controllers\StoreGenerationController;
22
+use App\Http\Controllers\StoreLogoController;
22 23
 use App\Http\Controllers\StorePublishController;
23 24
 use App\Http\Controllers\StoreSettingsController;
24 25
 use App\Http\Controllers\StoreStyleController;
@@ -156,6 +157,11 @@ Route::middleware(['auth', 'verified'])->group(function () {
156 157
     Route::put('stores/{slug}/bento/{sectionId}', [BentoSectionController::class, 'update'])->name('stores.bento.update');
157 158
     Route::delete('stores/{slug}/bento/{sectionId}', [BentoSectionController::class, 'destroy'])->name('stores.bento.destroy');
158 159
     Route::post('stores/{slug}/hero/{sectionId}/photo', [HeroImageController::class, 'upload'])->name('stores.hero.upload');
160
+    // The store's logo (Design tab). Belongs to the store, so it shows on the live store right away.
161
+    Route::post('stores/{slug}/logo/upload', [StoreLogoController::class, 'upload'])->middleware('throttle:20,1')->name('stores.logo.upload');
162
+    Route::put('stores/{slug}/logo', [StoreLogoController::class, 'choose'])->name('stores.logo.choose');
163
+    Route::post('stores/{slug}/logo/draw', [StoreLogoController::class, 'draw'])->middleware('throttle:5,1')->name('stores.logo.draw');
164
+    Route::delete('stores/{slug}/logo', [StoreLogoController::class, 'destroy'])->name('stores.logo.destroy');
159 165
     Route::get('stores/{slug}/settings', [StoreSettingsController::class, 'edit'])->name('stores.settings');
160 166
     Route::put('stores/{slug}/settings', [StoreSettingsController::class, 'update'])->name('stores.settings.update');
161 167
     Route::post('stores/{slug}/publish', [StorePublishController::class, 'publish'])->name('stores.publish');

+ 193
- 0
tests/Feature/Stores/StoreLogoTest.php Прегледај датотеку

@@ -0,0 +1,193 @@
1
+<?php
2
+
3
+namespace Tests\Feature\Stores;
4
+
5
+use App\Ai\AiManager;
6
+use App\Ai\AiResponse;
7
+use App\Mail\OrderConfirmation;
8
+use App\Models\Order;
9
+use App\Models\Store;
10
+use App\Models\User;
11
+use App\Storefront\Logos\LogoSvg;
12
+use App\StorePlan\SamplePlan;
13
+use Illuminate\Foundation\Testing\RefreshDatabase;
14
+use Illuminate\Http\UploadedFile;
15
+use Illuminate\Support\Facades\Storage;
16
+use Inertia\Testing\AssertableInertia as Assert;
17
+use Tests\TestCase;
18
+
19
+/**
20
+ * The store logo: uploaded, a ready design, or drawn by the AI (with a lifetime limit).
21
+ */
22
+class StoreLogoTest extends TestCase
23
+{
24
+    use RefreshDatabase;
25
+
26
+    private User $user;
27
+
28
+    private Store $store;
29
+
30
+    protected function setUp(): void
31
+    {
32
+        parent::setUp();
33
+
34
+        Storage::fake('public');
35
+        config(['ai.tasks.logo.provider' => 'fake', 'ai.logo.lifetime_tries' => 3]);
36
+
37
+        $this->user = User::factory()->create();
38
+        $this->store = Store::factory()->for($this->user)->create(['name' => 'Kedai Ali']);
39
+        $this->store->plan = SamplePlan::for($this->store);
40
+        $this->store->save();
41
+        $this->actingAs($this->user);
42
+    }
43
+
44
+    private function png(int $width = 600, int $height = 200): UploadedFile
45
+    {
46
+        $image = imagecreatetruecolor($width, $height);
47
+        imagesavealpha($image, true);
48
+        imagefill($image, 0, 0, imagecolorallocatealpha($image, 0, 0, 0, 127));
49
+        imagefilledrectangle($image, 10, 10, 60, 60, imagecolorallocate($image, 200, 30, 30));
50
+        $path = tempnam(sys_get_temp_dir(), 'logo').'.png';
51
+        imagepng($image, $path);
52
+
53
+        return new UploadedFile($path, 'logo.png', 'image/png', null, true);
54
+    }
55
+
56
+    public function test_an_uploaded_logo_is_made_smaller_saved_as_webp_and_shown_in_the_store()
57
+    {
58
+        $this->post(route('stores.logo.upload', $this->store->slug), ['logo' => $this->png(1600, 400)])
59
+            ->assertSessionHasNoErrors();
60
+
61
+        $logo = $this->store->fresh()->logo;
62
+        $this->assertSame('upload', $logo['type']);
63
+        $this->assertStringEndsWith('.webp', $logo['path']);
64
+        $this->assertSame([800, 200], [$logo['width'], $logo['height']]);
65
+        Storage::disk('public')->assertExists($logo['path']);
66
+
67
+        $this->get(route('stores.preview', $this->store->slug))
68
+            ->assertInertia(fn (Assert $page) => $page
69
+                ->where('shop.logo.type', 'upload')
70
+                ->where('shop.logo.width', 800));
71
+
72
+        // A new logo replaces the old file.
73
+        $this->post(route('stores.logo.upload', $this->store->slug), ['logo' => $this->png()]);
74
+        Storage::disk('public')->assertMissing($logo['path']);
75
+    }
76
+
77
+    public function test_uploads_are_checked()
78
+    {
79
+        $this->post(route('stores.logo.upload', $this->store->slug), ['logo' => $this->png(40, 40)])
80
+            ->assertSessionHasErrors('logo');
81
+        $this->post(route('stores.logo.upload', $this->store->slug), ['logo' => UploadedFile::fake()->create('logo.svg', 4, 'image/svg+xml')])
82
+            ->assertSessionHasErrors('logo');
83
+
84
+        $this->assertNull($this->store->fresh()->logo);
85
+    }
86
+
87
+    public function test_a_ready_design_can_be_picked_and_removed()
88
+    {
89
+        $this->put(route('stores.logo.choose', $this->store->slug), ['design' => 'monogram-circle'])->assertSessionHasNoErrors();
90
+        $this->assertSame(['type' => 'design', 'key' => 'monogram-circle'], $this->store->fresh()->logo);
91
+
92
+        $this->put(route('stores.logo.choose', $this->store->slug), ['design' => 'made-up'])->assertSessionHasErrors('design');
93
+
94
+        $this->delete(route('stores.logo.destroy', $this->store->slug));
95
+        $this->assertNull($this->store->fresh()->logo);
96
+    }
97
+
98
+    public function test_the_ai_draws_logos_that_can_be_picked_and_each_store_has_a_lifetime_limit()
99
+    {
100
+        $this->post(route('stores.logo.draw', $this->store->slug))->assertSessionHasNoErrors();
101
+
102
+        $store = $this->store->fresh();
103
+        $this->assertSame(1, $store->ai_logo_tries);
104
+        $this->assertCount(3, $store->logo_drafts);
105
+        $this->assertStringContainsString('var(--sf-font-heading', $store->logo_drafts[0]);
106
+
107
+        $this->put(route('stores.logo.choose', $this->store->slug), ['drawn' => 1])->assertSessionHasNoErrors();
108
+        $this->assertSame('drawn', $this->store->fresh()->logo['type']);
109
+        $this->put(route('stores.logo.choose', $this->store->slug), ['drawn' => 99])->assertSessionHasErrors('logo');
110
+
111
+        $this->post(route('stores.logo.draw', $this->store->slug));
112
+        $this->post(route('stores.logo.draw', $this->store->slug));
113
+        $this->post(route('stores.logo.draw', $this->store->slug))->assertSessionHasErrors('logo');
114
+
115
+        $store = $this->store->fresh();
116
+        $this->assertSame(3, $store->ai_logo_tries);
117
+        $this->assertCount(9, $store->logo_drafts);
118
+
119
+        $this->get(route('stores.show', $this->store->slug))
120
+            ->assertInertia(fn (Assert $page) => $page
121
+                ->where('logo.tries_left', 0)
122
+                ->where('logo.tries_total', 3)
123
+                ->has('logo.drafts', 9)
124
+                ->has('logo.designs', 8));
125
+    }
126
+
127
+    public function test_a_failed_drawing_does_not_use_a_try()
128
+    {
129
+        $this->mock(AiManager::class)->shouldReceive('ask')->andReturn(new AiResponse('{"logos": [{"svg": "<script>alert(1)</script>"}]}', 'fake', 'fake'));
130
+
131
+        $this->post(route('stores.logo.draw', $this->store->slug))->assertSessionHasErrors('logo');
132
+
133
+        $this->assertSame(0, $this->store->fresh()->ai_logo_tries);
134
+        $this->assertNull($this->store->fresh()->logo_drafts);
135
+    }
136
+
137
+    public function test_drawings_are_cleaned_of_anything_that_could_run_code_or_load_from_outside()
138
+    {
139
+        $clean = LogoSvg::clean(<<<'SVG'
140
+            <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 400 100" width="999" onload="alert(1)">
141
+                <script>alert(1)</script>
142
+                <style>text { fill: red }</style>
143
+                <defs><linearGradient id="g"><stop offset="0" stop-color="#112233"/><stop offset="1" stop-color="javascript:x"/></linearGradient></defs>
144
+                <circle cx="50" cy="50" r="30" fill="url(#g)" onclick="alert(1)" style="fill: url(https://evil.test/x)"/>
145
+                <image href="https://evil.test/x.png" width="10" height="10"/>
146
+                <a href="javascript:alert(1)"><rect width="10" height="10"/></a>
147
+                <foreignObject><div>hi</div></foreignObject>
148
+                <path d="M0 0 L10 10 Z" fill="https://evil.test"/>
149
+                <text x="100" y="60" font-size="40" font-family="Comic Sans">Kedai Ali</text>
150
+            </svg>
151
+            SVG);
152
+
153
+        $this->assertNotNull($clean);
154
+        $this->assertStringNotContainsString('script', $clean);
155
+        $this->assertStringNotContainsString('onload', $clean);
156
+        $this->assertStringNotContainsString('onclick', $clean);
157
+        $this->assertStringNotContainsString('evil.test', $clean);
158
+        $this->assertStringNotContainsString('javascript', $clean);
159
+        $this->assertStringNotContainsString('<image', $clean);
160
+        $this->assertStringNotContainsString('<a', $clean);
161
+        $this->assertStringNotContainsString('foreignObject', $clean);
162
+        $this->assertStringNotContainsString('Comic Sans', $clean);
163
+        $this->assertStringNotContainsString('width="999"', $clean);
164
+        $this->assertStringContainsString('Kedai Ali', $clean);
165
+        $this->assertStringContainsString('<path d="M0 0 L10 10 Z"/>', $clean);
166
+        // The gradient keeps working under its new, unique id.
167
+        $this->assertMatchesRegularExpression('/id="(l[0-9a-f]{6}-g)".*fill="url\(#\1\)"/s', $clean);
168
+
169
+        $this->assertNull(LogoSvg::clean('<div>not a drawing</div>'));
170
+        $this->assertNull(LogoSvg::clean('<svg viewBox="0 0 5000 10"><rect width="1" height="1"/></svg>'));
171
+        $this->assertNull(LogoSvg::clean('<!DOCTYPE svg [<!ENTITY x SYSTEM "file:///etc/passwd">]><svg viewBox="0 0 400 100"><text>&x;</text></svg>'));
172
+    }
173
+
174
+    public function test_an_uploaded_logo_tops_the_order_emails()
175
+    {
176
+        $this->post(route('stores.logo.upload', $this->store->slug), ['logo' => $this->png(1600, 400)]);
177
+        $order = Order::factory()->for($this->store)->paid()->create();
178
+
179
+        (new OrderConfirmation($order->fresh()))
180
+            ->assertSeeInHtml('alt="Kedai Ali"', false)
181
+            ->assertSeeInHtml('width="192" height="48"', false);
182
+    }
183
+
184
+    public function test_another_merchants_store_logo_cannot_be_changed()
185
+    {
186
+        $other = Store::factory()->create();
187
+
188
+        $this->post(route('stores.logo.upload', $other->slug), ['logo' => $this->png()])->assertNotFound();
189
+        $this->put(route('stores.logo.choose', $other->slug), ['design' => 'wordmark'])->assertNotFound();
190
+        $this->post(route('stores.logo.draw', $other->slug))->assertNotFound();
191
+        $this->delete(route('stores.logo.destroy', $other->slug))->assertNotFound();
192
+    }
193
+}

Loading…
Откажи
Сачувај