Compare commits

...

4 Commits

Author SHA1 Message Date
399e7be3a9 test: refresh visual baselines from CI Ubuntu screenshots
Media now loads on same-origin /storage paths, so baselines must
capture the rendered fixtures. Use full-page snapshots from the CI
runner to keep Pest's exact snapshot match stable across environments.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-29 09:01:56 -03:00
0adaadd9ed fix: serve public media on same-origin storage paths
Pest Browser hosts on 127.0.0.1:port while Storage::url used
http://localhost, so screenshots captured broken images. Use relative
/storage URLs for media and absolutize only OG tags via url().

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-29 08:55:24 -03:00
2405160046 fix: make browser visual CI deterministic for media
Mount host public storage into FrankenPHP so seeded fixtures are served,
and replace PNG-as-JPG fixtures with real JPEGs so Chromium can render them.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-29 08:48:31 -03:00
27f3cee855 feat: ship public site with SEO and visuals
Publish CMS content on public routes with responsive media,
accessibility checks, and deterministic visual baselines.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-29 08:36:59 -03:00
102 changed files with 3992 additions and 61 deletions

View File

@@ -9,6 +9,11 @@ APP_FALLBACK_LOCALE=pt_BR
APP_FAKER_LOCALE=pt_BR APP_FAKER_LOCALE=pt_BR
APP_TIMEZONE=America/Fortaleza APP_TIMEZONE=America/Fortaleza
# Freeze application clock outside production (visual regression / deterministic seeds).
# Example: APP_FROZEN_NOW=2026-03-15T12:00:00-03:00
# Ignored when APP_ENV=production.
# APP_FROZEN_NOW=
APP_MAINTENANCE_DRIVER=file APP_MAINTENANCE_DRIVER=file
# APP_MAINTENANCE_STORE=database # APP_MAINTENANCE_STORE=database

View File

@@ -36,7 +36,7 @@ jobs:
- uses: shivammathur/setup-php@v2 - uses: shivammathur/setup-php@v2
with: with:
php-version: "8.4" php-version: "8.4"
extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, pdo_pgsql, bcmath, intl, sodium extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, pdo_pgsql, bcmath, intl, sodium, gd
coverage: none coverage: none
- uses: actions/cache@v4 - uses: actions/cache@v4
@@ -60,7 +60,7 @@ jobs:
- uses: shivammathur/setup-php@v2 - uses: shivammathur/setup-php@v2
with: with:
php-version: "8.4" php-version: "8.4"
extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, pdo_pgsql, bcmath, intl, sodium extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, pdo_pgsql, bcmath, intl, sodium, gd
coverage: none coverage: none
- uses: actions/cache@v4 - uses: actions/cache@v4
@@ -97,7 +97,7 @@ jobs:
- uses: shivammathur/setup-php@v2 - uses: shivammathur/setup-php@v2
with: with:
php-version: "8.4" php-version: "8.4"
extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, pdo_pgsql, bcmath, intl, sodium extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, pdo_pgsql, bcmath, intl, sodium, gd
coverage: none coverage: none
- uses: actions/cache@v4 - uses: actions/cache@v4
@@ -141,7 +141,7 @@ jobs:
- uses: shivammathur/setup-php@v2 - uses: shivammathur/setup-php@v2
with: with:
php-version: "8.4" php-version: "8.4"
extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, pdo_pgsql, bcmath, intl, sodium extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, pdo_pgsql, bcmath, intl, sodium, gd
coverage: none coverage: none
- uses: actions/cache@v4 - uses: actions/cache@v4
@@ -161,11 +161,15 @@ jobs:
- run: npm run build - run: npm run build
- run: npx playwright install chromium --with-deps - run: npx playwright install chromium --with-deps
- run: php artisan migrate --force - run: php artisan migrate --force
- run: php artisan db:seed --class=VisualContentSeeder --force
- run: php artisan storage:link
- name: Build application image - name: Build application image
run: docker build -t amare-app:ci . run: docker build -t amare-app:ci .
- name: Run browser tests against FrankenPHP container - name: Run browser tests against FrankenPHP container
env:
APP_FROZEN_NOW: "2026-03-15T12:00:00-03:00"
run: | run: |
docker run -d --name amare-web \ docker run -d --name amare-web \
-e APP_ENV=testing \ -e APP_ENV=testing \
@@ -174,6 +178,7 @@ jobs:
-e APP_LOCALE=pt_BR \ -e APP_LOCALE=pt_BR \
-e APP_FALLBACK_LOCALE=pt_BR \ -e APP_FALLBACK_LOCALE=pt_BR \
-e APP_TIMEZONE=America/Fortaleza \ -e APP_TIMEZONE=America/Fortaleza \
-e APP_FROZEN_NOW="${APP_FROZEN_NOW}" \
-e DB_CONNECTION=pgsql \ -e DB_CONNECTION=pgsql \
-e DB_HOST=host.docker.internal \ -e DB_HOST=host.docker.internal \
-e DB_PORT=5432 \ -e DB_PORT=5432 \
@@ -184,6 +189,7 @@ jobs:
-e CACHE_STORE=database \ -e CACHE_STORE=database \
-e QUEUE_CONNECTION=database \ -e QUEUE_CONNECTION=database \
--add-host=host.docker.internal:host-gateway \ --add-host=host.docker.internal:host-gateway \
-v "${GITHUB_WORKSPACE}/storage/app/public:/app/storage/app/public" \
-p 8000:8000 \ -p 8000:8000 \
amare-app:ci amare-app:ci
@@ -197,6 +203,23 @@ jobs:
curl -fsS http://127.0.0.1:8000/up curl -fsS http://127.0.0.1:8000/up
./vendor/bin/pest --testsuite=Browser ./vendor/bin/pest --testsuite=Browser
- name: Collect failure diagnostics
if: failure()
run: |
mkdir -p artifacts/browser
docker logs amare-web > artifacts/browser/container.log 2>&1 || true
cp -R storage/logs artifacts/browser/app-logs 2>/dev/null || true
cp -R tests/Browser/Screenshots artifacts/browser/screenshots 2>/dev/null || true
cp -R tests/.pest artifacts/browser/pest 2>/dev/null || true
- name: Upload browser failure artifacts
if: failure()
uses: actions/upload-artifact@v4
with:
name: browser-failure-artifacts
path: artifacts/browser
if-no-files-found: ignore
container: container:
name: container name: container
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -206,7 +229,7 @@ jobs:
- name: Build production image - name: Build production image
run: docker build -t amare-app:ci . run: docker build -t amare-app:ci .
- name: Verify container healthcheck - name: Verify container healthcheck and storage link
run: | run: |
docker run -d --name amare-health \ docker run -d --name amare-health \
-e APP_ENV=production \ -e APP_ENV=production \
@@ -224,6 +247,7 @@ jobs:
for i in $(seq 1 30); do for i in $(seq 1 30); do
if curl -fsS http://127.0.0.1:8000/up; then if curl -fsS http://127.0.0.1:8000/up; then
docker exec amare-health test -L /app/public/storage
exit 0 exit 0
fi fi
sleep 2 sleep 2

1
.gitignore vendored
View File

@@ -25,3 +25,4 @@ _ide_helper.php
Homestead.json Homestead.json
Homestead.yaml Homestead.yaml
Thumbs.db Thumbs.db
.worktrees/

View File

@@ -35,7 +35,8 @@ RUN install-php-extensions \
opcache \ opcache \
pcntl \ pcntl \
bcmath \ bcmath \
sodium sodium \
gd
RUN useradd --create-home --shell /usr/sbin/nologin --uid 1000 appuser RUN useradd --create-home --shell /usr/sbin/nologin --uid 1000 appuser

28
SPEC.md
View File

@@ -2330,21 +2330,21 @@ O agente deve implementar na sequência, salvo instrução explícita.
### Fase 1 — Site e CMS ### Fase 1 — Site e CMS
- [ ] `site_settings`; - [x] `site_settings`;
- [ ] serviços; - [x] serviços;
- [ ] portfólio e galeria; - [x] portfólio e galeria;
- [ ] depoimentos; - [x] depoimentos;
- [ ] home; - [x] home;
- [ ] listagem e detalhe de serviços; - [x] listagem e detalhe de serviços;
- [ ] listagem e detalhe de portfólio; - [x] listagem e detalhe de portfólio;
- [ ] sobre; - [x] sobre;
- [ ] privacidade; - [x] privacidade;
- [ ] SEO; - [x] SEO;
- [ ] mídia otimizada; - [x] mídia otimizada;
- [ ] snapshots desktop/mobile; - [x] snapshots desktop/mobile;
- [ ] testes de acessibilidade. - [x] testes de acessibilidade.
**Critério de saída:** conteúdo gerenciável no Filament e site público aprovado visualmente. **Critério de saída:** conteúdo gerenciável no Filament e site público aprovado visualmente (baselines em `tests/.pest/snapshots/`; aprovação humana do diff visual no PR).
### Fase 2 — Leads ### Fase 2 — Leads

View File

@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Application\Data;
use App\Models\PortfolioCase;
use App\Models\Service;
use App\Models\SiteSetting;
use App\Models\Testimonial;
use Illuminate\Database\Eloquent\Collection;
final readonly class HomeContent
{
/**
* @param Collection<int, Service> $featuredServices
* @param Collection<int, PortfolioCase> $featuredCases
* @param Collection<int, Testimonial> $testimonials
*/
public function __construct(
public SiteSetting $settings,
public Collection $featuredServices,
public Collection $featuredCases,
public Collection $testimonials,
) {}
}

View File

@@ -0,0 +1,103 @@
<?php
declare(strict_types=1);
namespace App\Application\Data;
use App\Models\PortfolioCase;
use App\Models\SiteSetting;
use Illuminate\Support\Facades\Storage;
final readonly class PageMeta
{
/**
* @param array<string, mixed>|null $jsonLd
*/
public function __construct(
public string $title,
public string $description,
public string $canonical,
public string $ogType = 'website',
public ?string $ogImageUrl = null,
public ?string $ogImageAlt = null,
public ?array $jsonLd = null,
) {}
/**
* @param array<string, mixed>|null $jsonLd
*/
public static function forPage(
string $canonical,
SiteSetting $settings,
?string $title = null,
?string $description = null,
?string $ogImageUrl = null,
?string $ogImageAlt = null,
string $ogType = 'website',
?array $jsonLd = null,
): self {
return new self(
title: filled($title) ? (string) $title : self::defaultTitle($settings),
description: filled($description) ? (string) $description : self::defaultDescription($settings),
canonical: $canonical,
ogType: $ogType,
ogImageUrl: $ogImageUrl ?? self::defaultOgImageUrl($settings),
ogImageAlt: $ogImageAlt ?? $settings->default_og_image_alt,
jsonLd: $jsonLd,
);
}
/**
* @param array<string, mixed>|null $jsonLd
*/
public static function forCase(
PortfolioCase $case,
string $canonical,
SiteSetting $settings,
?array $jsonLd = null,
): self {
$title = filled($case->meta_title) ? (string) $case->meta_title : (string) $case->title;
$description = filled($case->meta_description)
? (string) $case->meta_description
: (filled($case->summary) ? (string) $case->summary : self::defaultDescription($settings));
$ogImageUrl = filled($case->cover_image_path)
? url(Storage::disk('public')->url((string) $case->cover_image_path))
: self::defaultOgImageUrl($settings);
$ogImageAlt = filled($case->cover_image_alt)
? (string) $case->cover_image_alt
: $settings->default_og_image_alt;
return new self(
title: $title,
description: $description,
canonical: $canonical,
ogType: 'article',
ogImageUrl: $ogImageUrl,
ogImageAlt: $ogImageAlt,
jsonLd: $jsonLd,
);
}
private static function defaultTitle(SiteSetting $settings): string
{
return filled($settings->default_meta_title)
? (string) $settings->default_meta_title
: (string) $settings->brand_name;
}
private static function defaultDescription(SiteSetting $settings): string
{
return (string) ($settings->default_meta_description ?? '');
}
private static function defaultOgImageUrl(SiteSetting $settings): ?string
{
if (! filled($settings->default_og_image_path)) {
return null;
}
return url(Storage::disk('public')->url((string) $settings->default_og_image_path));
}
}

View File

@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Application\Queries\Marketing;
use App\Models\PortfolioCase;
final class FindPublishedPortfolioCaseBySlug
{
public function __invoke(string $slug): ?PortfolioCase
{
return PortfolioCase::query()
->published()
->with(['images'])
->where('slug', $slug)
->first();
}
}

View File

@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Application\Queries\Marketing;
use App\Application\Data\HomeContent;
use App\Models\PortfolioCase;
use App\Models\Service;
use App\Models\SiteSetting;
use App\Models\Testimonial;
final class GetHomeContent
{
public function __invoke(): HomeContent
{
return new HomeContent(
settings: SiteSetting::instance(),
featuredServices: Service::query()
->published()
->where('is_featured', true)
->orderBy('sort_order')
->get(),
featuredCases: PortfolioCase::query()
->published()
->where('is_featured', true)
->with(['images'])
->orderBy('sort_order')
->get(),
testimonials: Testimonial::query()
->published()
->orderBy('sort_order')
->get(),
);
}
}

View File

@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Application\Queries\Marketing;
use App\Models\PortfolioCase;
use Illuminate\Database\Eloquent\Collection;
final class GetPublishedPortfolioCases
{
/**
* @return Collection<int, PortfolioCase>
*/
public function __invoke(): Collection
{
return PortfolioCase::query()
->published()
->with(['images'])
->orderBy('sort_order')
->get();
}
}

View File

@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Application\Queries\Marketing;
use App\Models\Service;
use Illuminate\Database\Eloquent\Collection;
final class GetPublishedServices
{
/**
* @return Collection<int, Service>
*/
public function __invoke(): Collection
{
return Service::query()
->published()
->orderBy('sort_order')
->get();
}
}

View File

@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace App\Application\Queries\Marketing;
use App\Models\PortfolioCase;
use Illuminate\Support\Carbon;
final class GetSitemapEntries
{
/**
* @return list<array{loc: string, lastmod: string|null}>
*/
public function __invoke(): array
{
$entries = [
['loc' => route('home'), 'lastmod' => null],
['loc' => route('services.index'), 'lastmod' => null],
['loc' => route('portfolio.index'), 'lastmod' => null],
['loc' => route('about'), 'lastmod' => null],
['loc' => route('privacy'), 'lastmod' => null],
['loc' => route('contact'), 'lastmod' => null],
];
$cases = PortfolioCase::query()
->published()
->orderBy('sort_order')
->get(['slug', 'updated_at']);
foreach ($cases as $case) {
/** @var Carbon|null $updatedAt */
$updatedAt = $case->updated_at;
$entries[] = [
'loc' => route('portfolio.show', $case->slug),
'lastmod' => $updatedAt?->toAtomString(),
];
}
return $entries;
}
}

View File

@@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
namespace App\Console\Commands;
use App\Models\PortfolioCase;
use App\Models\PortfolioImage;
use App\Models\Service;
use App\Models\SiteSetting;
use App\Models\Testimonial;
use App\Support\PublicImageUploadRules;
use App\Support\ResponsiveImage;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
final class MediaGenerateVariantsCommand extends Command
{
protected $signature = 'media:generate-variants';
protected $description = 'Generate responsive image variants for existing public media';
public function handle(): int
{
$disk = PublicImageUploadRules::disk();
$paths = $this->collectPaths();
$generated = 0;
$skipped = 0;
foreach ($paths as $path) {
if (! Storage::disk($disk)->exists($path)) {
$this->warn("Missing file: {$path}");
$skipped++;
continue;
}
ResponsiveImage::generate($path, $disk);
$generated++;
$this->line("Generated variants for {$path}");
}
$this->info("Done. Generated: {$generated}. Skipped: {$skipped}.");
return self::SUCCESS;
}
/**
* @return list<string>
*/
private function collectPaths(): array
{
$paths = [];
$settings = SiteSetting::query()->first();
if ($settings && filled($settings->default_og_image_path)) {
$paths[] = (string) $settings->default_og_image_path;
}
foreach (Service::query()->whereNotNull('cover_image_path')->pluck('cover_image_path') as $path) {
$paths[] = (string) $path;
}
foreach (PortfolioCase::query()->whereNotNull('cover_image_path')->pluck('cover_image_path') as $path) {
$paths[] = (string) $path;
}
foreach (PortfolioImage::query()->whereNotNull('path')->pluck('path') as $path) {
$paths[] = (string) $path;
}
foreach (Testimonial::query()->whereNotNull('photo_path')->pluck('photo_path') as $path) {
$paths[] = (string) $path;
}
return array_values(array_unique($paths));
}
}

View File

@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\PublicSite;
use App\Application\Data\PageMeta;
use App\Application\Queries\Marketing\GetHomeContent;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\View\View;
final class HomeController extends Controller
{
public function __invoke(GetHomeContent $getHomeContent): View
{
$content = $getHomeContent();
return view('pages.home', [
'content' => $content,
'siteSettings' => $content->settings,
'pageMeta' => PageMeta::forPage(
canonical: route('home'),
settings: $content->settings,
jsonLd: [
'@context' => 'https://schema.org',
'@type' => 'Organization',
'name' => $content->settings->brand_name,
'email' => $content->settings->email,
'telephone' => $content->settings->phone,
'address' => [
'@type' => 'PostalAddress',
'addressLocality' => $content->settings->city,
],
],
),
]);
}
}

View File

@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\PublicSite;
use App\Application\Data\PageMeta;
use App\Http\Controllers\Controller;
use App\Models\SiteSetting;
use Illuminate\Contracts\View\View;
final class PageController extends Controller
{
public function about(): View
{
$settings = SiteSetting::instance();
return view('pages.about', [
'siteSettings' => $settings,
'pageMeta' => PageMeta::forPage(
canonical: route('about'),
settings: $settings,
title: 'Sobre',
description: $settings->about_summary ?: ('Conheça a '.$settings->brand_name.'.'),
),
]);
}
public function privacy(): View
{
$settings = SiteSetting::instance();
return view('pages.privacy', [
'siteSettings' => $settings,
'pageMeta' => PageMeta::forPage(
canonical: route('privacy'),
settings: $settings,
title: 'Política de privacidade',
description: 'Política de privacidade da '.$settings->brand_name.'.',
),
]);
}
public function contact(): View
{
$settings = SiteSetting::instance();
return view('pages.contact', [
'siteSettings' => $settings,
'pageMeta' => PageMeta::forPage(
canonical: route('contact'),
settings: $settings,
title: 'Contato',
description: 'Fale com a '.$settings->brand_name.'.',
),
]);
}
}

View File

@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\PublicSite;
use App\Application\Data\PageMeta;
use App\Application\Queries\Marketing\FindPublishedPortfolioCaseBySlug;
use App\Http\Controllers\Controller;
use App\Models\PortfolioCase;
use App\Models\SiteSetting;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Response;
use Illuminate\Pagination\LengthAwarePaginator;
final class PortfolioController extends Controller
{
public function index(): View
{
$settings = SiteSetting::instance();
/** @var LengthAwarePaginator<int, PortfolioCase> $cases */
$cases = PortfolioCase::query()
->published()
->with(['images'])
->orderBy('sort_order')
->paginate(9);
return view('pages.portfolio.index', [
'cases' => $cases,
'siteSettings' => $settings,
'pageMeta' => PageMeta::forPage(
canonical: route('portfolio.index'),
settings: $settings,
title: 'Portfólio',
description: 'Casos reais de eventos conduzidos pela '.$settings->brand_name.'.',
),
]);
}
public function show(string $slug, FindPublishedPortfolioCaseBySlug $findPublishedPortfolioCaseBySlug): View|Response
{
$case = $findPublishedPortfolioCaseBySlug($slug);
if ($case === null) {
abort(404);
}
$settings = SiteSetting::instance();
$canonical = route('portfolio.show', $case->slug);
return view('pages.portfolio.show', [
'case' => $case,
'siteSettings' => $settings,
'pageMeta' => PageMeta::forCase(
case: $case,
canonical: $canonical,
settings: $settings,
jsonLd: [
'@context' => 'https://schema.org',
'@type' => 'Article',
'headline' => $case->title,
'description' => $case->summary,
'url' => $canonical,
'datePublished' => $case->published_at?->toAtomString(),
'dateModified' => $case->updated_at?->toAtomString(),
],
),
]);
}
}

View File

@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\PublicSite;
use App\Http\Controllers\Controller;
use Illuminate\Http\Response;
final class RobotsController extends Controller
{
public function __invoke(): Response
{
$body = implode("\n", [
'User-agent: *',
'Allow: /',
'Sitemap: '.url('/sitemap.xml'),
'',
]);
return response($body, 200, [
'Content-Type' => 'text/plain; charset=UTF-8',
]);
}
}

View File

@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\PublicSite;
use App\Application\Data\PageMeta;
use App\Application\Queries\Marketing\GetPublishedServices;
use App\Http\Controllers\Controller;
use App\Models\SiteSetting;
use Illuminate\Contracts\View\View;
final class ServiceController extends Controller
{
public function index(GetPublishedServices $getPublishedServices): View
{
$settings = SiteSetting::instance();
$services = $getPublishedServices();
return view('pages.services.index', [
'services' => $services,
'siteSettings' => $settings,
'pageMeta' => PageMeta::forPage(
canonical: route('services.index'),
settings: $settings,
title: 'Serviços',
description: 'Conheça os serviços de assessoria de eventos da '.$settings->brand_name.'.',
),
]);
}
}

View File

@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\PublicSite;
use App\Application\Queries\Marketing\GetSitemapEntries;
use App\Http\Controllers\Controller;
use Illuminate\Http\Response;
final class SitemapController extends Controller
{
public function __invoke(GetSitemapEntries $getSitemapEntries): Response
{
return response()
->view('pages.sitemap', [
'entries' => $getSitemapEntries(),
], 200, [
'Content-Type' => 'application/xml',
]);
}
}

View File

@@ -1,8 +1,15 @@
<?php <?php
declare(strict_types=1);
namespace App\Providers; namespace App\Providers;
use App\Application\Data\PageMeta;
use App\Models\SiteSetting;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
use Illuminate\View\View as ViewInstance;
class AppServiceProvider extends ServiceProvider class AppServiceProvider extends ServiceProvider
{ {
@@ -19,6 +26,38 @@ class AppServiceProvider extends ServiceProvider
*/ */
public function boot(): void public function boot(): void
{ {
// $this->freezeClockWhenConfigured();
View::composer('layouts.public', function (ViewInstance $view): void {
$settings = $view->offsetExists('siteSettings')
? $view->offsetGet('siteSettings')
: SiteSetting::instance();
if (! $view->offsetExists('siteSettings')) {
$view->with('siteSettings', $settings);
}
if (! $view->offsetExists('pageMeta')) {
$view->with('pageMeta', PageMeta::forPage(
canonical: url()->current(),
settings: $settings,
));
}
});
}
private function freezeClockWhenConfigured(): void
{
if ($this->app->environment('production')) {
return;
}
$frozenNow = config('app.frozen_now');
if (! filled($frozenNow)) {
return;
}
CarbonImmutable::setTestNow(CarbonImmutable::parse((string) $frozenNow));
} }
} }

View File

@@ -4,10 +4,12 @@ declare(strict_types=1);
namespace App\Support; namespace App\Support;
use Filament\Forms\Components\BaseFileUpload;
use Filament\Forms\Components\FileUpload; use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\TextInput; use Filament\Forms\Components\TextInput;
use Filament\Schemas\Components\Utilities\Get; use Filament\Schemas\Components\Utilities\Get;
use Illuminate\Validation\Rules\File; use Illuminate\Validation\Rules\File;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
final class PublicImageUploadRules final class PublicImageUploadRules
{ {
@@ -31,7 +33,19 @@ final class PublicImageUploadRules
->validationMessages(self::validationMessages()) ->validationMessages(self::validationMessages())
->getUploadedFileNameForStorageUsing( ->getUploadedFileNameForStorageUsing(
fn ($file): string => (string) str()->uuid().'.'.$file->getClientOriginalExtension(), fn ($file): string => (string) str()->uuid().'.'.$file->getClientOriginalExtension(),
); )
->saveUploadedFileUsing(function (BaseFileUpload $component, TemporaryUploadedFile $file): ?string {
$path = $component->saveUploadedFile($file);
if (filled($path)) {
ResponsiveImage::generate((string) $path, $component->getDiskName());
}
return $path;
})
->deleteUploadedFileUsing(function (BaseFileUpload $component, string $file): void {
ResponsiveImage::delete($file, $component->getDiskName());
});
} }
public static function altTextField(string $name, string $imageField, string $label = 'Texto alternativo'): TextInput public static function altTextField(string $name, string $imageField, string $label = 'Texto alternativo'): TextInput

View File

@@ -0,0 +1,151 @@
<?php
declare(strict_types=1);
namespace App\Support;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\ImageManager;
use Throwable;
final class ResponsiveImage
{
/** @var list<int> */
public const WIDTHS = [480, 960, 1440];
public static function generate(string $path, ?string $disk = null): void
{
$filesystem = self::filesystem($disk);
if (! $filesystem->exists($path)) {
return;
}
$manager = new ImageManager(new Driver);
$contents = $filesystem->get($path);
if ($contents === null) {
return;
}
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
foreach (self::WIDTHS as $width) {
$variantPath = self::variantPath($path, $width);
$variant = $manager->read($contents);
if ($variant->width() > $width) {
$variant->scale(width: $width);
}
$encoded = match ($extension) {
'png' => $variant->toPng(),
'webp' => $variant->toWebp(quality: 82),
default => $variant->toJpeg(quality: 82),
};
$filesystem->put($variantPath, (string) $encoded);
}
}
public static function deleteVariants(string $path, ?string $disk = null): void
{
$filesystem = self::filesystem($disk);
foreach (self::WIDTHS as $width) {
$variantPath = self::variantPath($path, $width);
if ($filesystem->exists($variantPath)) {
$filesystem->delete($variantPath);
}
}
}
public static function delete(string $path, ?string $disk = null): void
{
$filesystem = self::filesystem($disk);
self::deleteVariants($path, $disk);
if ($filesystem->exists($path)) {
$filesystem->delete($path);
}
}
public static function replace(string $previousPath, string $newPath, ?string $disk = null): void
{
if ($previousPath !== '' && $previousPath !== $newPath) {
self::delete($previousPath, $disk);
}
self::generate($newPath, $disk);
}
public static function variantPath(string $path, int $width): string
{
$directory = trim(dirname($path), '.');
$filename = pathinfo($path, PATHINFO_FILENAME);
$extension = pathinfo($path, PATHINFO_EXTENSION);
$variantName = $filename.'-'.$width.($extension !== '' ? '.'.$extension : '');
return $directory === '' ? $variantName : $directory.'/'.$variantName;
}
/**
* @return list<array{path: string, width: int}>
*/
public static function availableVariants(string $path, ?string $disk = null): array
{
$filesystem = self::filesystem($disk);
$variants = [];
foreach (self::WIDTHS as $width) {
$variantPath = self::variantPath($path, $width);
if ($filesystem->exists($variantPath)) {
$variants[] = [
'path' => $variantPath,
'width' => $width,
];
}
}
return $variants;
}
/**
* @return array{width: int, height: int}|null
*/
public static function dimensions(string $path, ?string $disk = null): ?array
{
$filesystem = self::filesystem($disk);
if (! $filesystem->exists($path)) {
return null;
}
try {
$contents = $filesystem->get($path);
if ($contents === null) {
return null;
}
$image = (new ImageManager(new Driver))->read($contents);
return [
'width' => $image->width(),
'height' => $image->height(),
];
} catch (Throwable) {
return null;
}
}
private static function filesystem(?string $disk): Filesystem
{
return Storage::disk($disk ?? PublicImageUploadRules::disk());
}
}

View File

@@ -8,6 +8,7 @@
"require": { "require": {
"php": "^8.3", "php": "^8.3",
"filament/filament": "^5.0", "filament/filament": "^5.0",
"intervention/image": "^3.0",
"laravel/framework": "^13.8", "laravel/framework": "^13.8",
"laravel/tinker": "^3.0" "laravel/tinker": "^3.0"
}, },
@@ -69,7 +70,7 @@
"vendor/bin/pint --test" "vendor/bin/pint --test"
], ],
"phpstan": [ "phpstan": [
"vendor/bin/phpstan analyse --memory-limit=1G" "vendor/bin/phpstan analyse --memory-limit=1G --debug"
], ],
"security-audit": [ "security-audit": [
"composer audit --no-interaction" "composer audit --no-interaction"
@@ -81,7 +82,7 @@
"@test" "@test"
], ],
"visual:update": [ "visual:update": [
"@php artisan test --testsuite=Browser -- --update-snapshots" "@php artisan test --testsuite=Browser --update-snapshots"
], ],
"post-autoload-dump": [ "post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump", "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",

146
composer.lock generated
View File

@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "f86a5740384eb06ae059db6a1d6b3d7f", "content-hash": "b7cd97df13085158d9ecb6ad877a600f",
"packages": [ "packages": [
{ {
"name": "anourvalar/eloquent-serialize", "name": "anourvalar/eloquent-serialize",
@@ -2026,6 +2026,150 @@
], ],
"time": "2026-07-17T13:53:03+00:00" "time": "2026-07-17T13:53:03+00:00"
}, },
{
"name": "intervention/gif",
"version": "4.2.4",
"source": {
"type": "git",
"url": "https://github.com/Intervention/gif.git",
"reference": "c3598a16ebe7690cd55640c44144a9df383ea73c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/Intervention/gif/zipball/c3598a16ebe7690cd55640c44144a9df383ea73c",
"reference": "c3598a16ebe7690cd55640c44144a9df383ea73c",
"shasum": ""
},
"require": {
"php": "^8.1"
},
"require-dev": {
"phpstan/phpstan": "^2.1",
"phpunit/phpunit": "^10.0 || ^11.0 || ^12.0",
"slevomat/coding-standard": "~8.0",
"squizlabs/php_codesniffer": "^3.8"
},
"type": "library",
"autoload": {
"psr-4": {
"Intervention\\Gif\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Oliver Vogel",
"email": "oliver@intervention.io",
"homepage": "https://intervention.io/"
}
],
"description": "Native PHP GIF Encoder/Decoder",
"homepage": "https://github.com/intervention/gif",
"keywords": [
"animation",
"gd",
"gif",
"image"
],
"support": {
"issues": "https://github.com/Intervention/gif/issues",
"source": "https://github.com/Intervention/gif/tree/4.2.4"
},
"funding": [
{
"url": "https://paypal.me/interventionio",
"type": "custom"
},
{
"url": "https://github.com/Intervention",
"type": "github"
},
{
"url": "https://ko-fi.com/interventionphp",
"type": "ko_fi"
}
],
"time": "2026-01-04T09:27:23+00:00"
},
{
"name": "intervention/image",
"version": "3.11.8",
"source": {
"type": "git",
"url": "https://github.com/Intervention/image.git",
"reference": "cf04c8dd245697f701057c13d4bfe140d584e738"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/Intervention/image/zipball/cf04c8dd245697f701057c13d4bfe140d584e738",
"reference": "cf04c8dd245697f701057c13d4bfe140d584e738",
"shasum": ""
},
"require": {
"ext-mbstring": "*",
"intervention/gif": "^4.2",
"php": "^8.1"
},
"require-dev": {
"mockery/mockery": "^1.6",
"phpstan/phpstan": "^2.1",
"phpunit/phpunit": "^10.0 || ^11.0 || ^12.0",
"slevomat/coding-standard": "~8.0",
"squizlabs/php_codesniffer": "^4"
},
"suggest": {
"ext-exif": "Recommended to be able to read EXIF data properly."
},
"type": "library",
"autoload": {
"psr-4": {
"Intervention\\Image\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Oliver Vogel",
"email": "oliver@intervention.io",
"homepage": "https://intervention.io"
}
],
"description": "PHP Image Processing",
"homepage": "https://image.intervention.io",
"keywords": [
"gd",
"image",
"imagick",
"resize",
"thumbnail",
"watermark"
],
"support": {
"issues": "https://github.com/Intervention/image/issues",
"source": "https://github.com/Intervention/image/tree/3.11.8"
},
"funding": [
{
"url": "https://paypal.me/interventionio",
"type": "custom"
},
{
"url": "https://github.com/Intervention",
"type": "github"
},
{
"url": "https://ko-fi.com/interventionphp",
"type": "ko_fi"
}
],
"time": "2026-05-01T08:20:10+00:00"
},
{ {
"name": "kirschbaum-development/eloquent-power-joins", "name": "kirschbaum-development/eloquent-power-joins",
"version": "4.3.3", "version": "4.3.3",

View File

@@ -67,6 +67,18 @@ return [
'timezone' => env('APP_TIMEZONE', 'America/Fortaleza'), 'timezone' => env('APP_TIMEZONE', 'America/Fortaleza'),
/*
|--------------------------------------------------------------------------
| Frozen Clock (non-production)
|--------------------------------------------------------------------------
|
| When set outside production, the application clock is frozen for
| deterministic rendering (visual regression / seeded content).
|
*/
'frozen_now' => env('APP_FROZEN_NOW'),
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Application Locale Configuration | Application Locale Configuration

View File

@@ -41,7 +41,9 @@ return [
'public' => [ 'public' => [
'driver' => 'local', 'driver' => 'local',
'root' => storage_path('app/public'), 'root' => storage_path('app/public'),
'url' => rtrim(env('APP_URL', 'http://localhost'), '/').'/storage', // Same-origin path so Pest Browser / any host:port can load media.
// Absolute URLs for OG tags should be built with url(...).
'url' => '/storage',
'visibility' => 'public', 'visibility' => 'public',
'throw' => false, 'throw' => false,
'report' => false, 'report' => false,

View File

@@ -0,0 +1,172 @@
<?php
declare(strict_types=1);
namespace Database\Seeders;
use App\Models\PortfolioCase;
use App\Models\PortfolioImage;
use App\Models\Service;
use App\Models\SiteSetting;
use App\Models\Testimonial;
use Illuminate\Database\Seeder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
/**
* Deterministic content for visual regression. Keep separate from ContentSeeder demo data.
*/
class VisualContentSeeder extends Seeder
{
public const FROZEN_NOW = '2026-03-15T12:00:00-03:00';
private const SEED_TIMESTAMP = '2026-03-15 12:00:00';
public function run(): void
{
Carbon::setTestNow(Carbon::parse(self::FROZEN_NOW));
$this->seedSiteSettings();
$this->seedServices();
$this->seedPortfolioCases();
$this->seedTestimonials();
}
private function seedSiteSettings(): void
{
SiteSetting::query()->updateOrCreate([], [
'brand_name' => 'Amare Assessoria',
'hero_eyebrow' => 'Assessoria de eventos',
'hero_title' => 'Celebrações com propósito',
'hero_subtitle' => 'Planejamento completo para casamentos e eventos corporativos em Fortaleza.',
'hero_cta_label' => 'Solicitar orçamento',
'about_summary' => 'Assessoria boutique especializada em experiências memoráveis.',
'email' => 'contato@amare.local',
'phone' => '(85) 99999-9999',
'city' => 'Fortaleza, CE',
'social_links' => [
'instagram' => 'https://instagram.com/amare',
],
'default_meta_title' => 'Amare Assessoria de Eventos',
'default_meta_description' => 'Assessoria premium para casamentos e eventos corporativos.',
'default_og_image_path' => $this->copyFixture('og-default.jpg', 'visual/og/og-default.jpg'),
'default_og_image_alt' => 'Identidade visual da Amare Assessoria de Eventos',
'analytics_enabled' => false,
'analytics_script' => null,
]);
}
private function seedServices(): void
{
foreach ([
[
'title' => 'Casamentos',
'slug' => 'casamentos',
'summary' => 'Planejamento completo do grande dia.',
'description' => 'Do briefing ao último brinde, cuidamos de cada detalhe do casamento.',
'sort_order' => 1,
'is_featured' => true,
],
[
'title' => 'Eventos corporativos',
'slug' => 'eventos-corporativos',
'summary' => 'Experiências alinhadas à marca.',
'description' => 'Lançamentos, convenções e encontros corporativos com operação impecável.',
'sort_order' => 2,
'is_featured' => true,
],
] as $service) {
Service::query()->updateOrCreate(
['slug' => $service['slug']],
[
...$service,
'cover_image_path' => $this->copyFixture('service-cover.jpg', 'visual/services/'.$service['slug'].'.jpg'),
'cover_image_alt' => 'Capa do serviço '.$service['title'],
'published_at' => Carbon::parse(self::SEED_TIMESTAMP),
],
);
}
}
private function seedPortfolioCases(): void
{
$cases = [
[
'title' => 'Casamento Ana e Lucas',
'slug' => 'casamento-ana-lucas',
'summary' => 'Cerimônia ao ar livre em Fortaleza.',
'event_type' => 'Casamento',
'city' => 'Fortaleza',
'venue' => 'Espaço Jardim Atlântico',
'event_date' => '2025-11-20',
'challenge' => 'Integrar cerimônia e recepção em áreas distintas.',
'solution' => 'Operação sincronizada com sinalização e timing detalhado.',
'result' => 'Experiência fluida para 180 convidados.',
'sort_order' => 1,
],
[
'title' => 'Lançamento Verano',
'slug' => 'lancamento-verano',
'summary' => 'Evento corporativo de lançamento de coleção.',
'event_type' => 'Corporativo',
'city' => 'Fortaleza',
'venue' => 'Centro de Convenções',
'event_date' => '2025-09-10',
'challenge' => 'Ativar marca em ambiente multiestação.',
'solution' => 'Fluxo de convidados e fornecedores com cronograma minuto a minuto.',
'result' => 'Alta percepção de marca e cobertura de imprensa.',
'sort_order' => 2,
],
];
foreach ($cases as $caseData) {
$case = PortfolioCase::query()->updateOrCreate(
['slug' => $caseData['slug']],
[
...$caseData,
'cover_image_path' => $this->copyFixture('portfolio-cover.jpg', 'visual/portfolio/'.$caseData['slug'].'-cover.jpg'),
'cover_image_alt' => 'Capa do caso '.$caseData['title'],
'is_featured' => true,
'published_at' => Carbon::parse(self::SEED_TIMESTAMP),
],
);
PortfolioImage::query()->where('portfolio_case_id', $case->id)->delete();
PortfolioImage::query()->create([
'portfolio_case_id' => $case->id,
'path' => $this->copyFixture('gallery.jpg', 'visual/portfolio/'.$caseData['slug'].'-gallery-1.jpg'),
'alt_text' => 'Galeria '.$caseData['title'].' 1',
'caption' => 'Detalhe da decoração',
'sort_order' => 1,
]);
}
}
private function seedTestimonials(): void
{
Testimonial::query()->updateOrCreate(
[
'author_name' => 'Ana Souza',
'quote' => 'A Amare transformou nosso casamento em uma experiência inesquecível.',
],
[
'context' => 'Noiva',
'sort_order' => 1,
'is_featured' => true,
'photo_path' => $this->copyFixture('testimonial.jpg', 'visual/testimonials/ana-souza.jpg'),
'photo_alt' => 'Foto de Ana Souza',
'published_at' => Carbon::parse(self::SEED_TIMESTAMP),
],
);
}
private function copyFixture(string $fixtureName, string $destination): string
{
$source = base_path('tests/fixtures/images/'.$fixtureName);
Storage::disk('public')->put($destination, File::get($source));
return $destination;
}
}

3
docker/entrypoint.sh Normal file → Executable file
View File

@@ -8,6 +8,9 @@ fi
mkdir -p storage/framework/cache storage/framework/sessions storage/framework/views storage/logs bootstrap/cache mkdir -p storage/framework/cache storage/framework/sessions storage/framework/views storage/logs bootstrap/cache
# Idempotent public disk symlink for serving uploaded media from the container.
php artisan storage:link --force --no-interaction
php artisan package:discover --ansi php artisan package:discover --ansi
php artisan config:cache php artisan config:cache
php artisan route:cache php artisan route:cache

View File

@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-07-29

View File

@@ -0,0 +1,108 @@
## Context
O repositório está no fim da Fase 1: CMS completo no Filament (`site_settings`, `services`, `portfolio_cases`, `portfolio_images`, `testimonials`), Policies admin-only, factories, `ContentSeeder` e testes feature. O site público, porém, ainda é o placeholder da Fase 0: `routes/web.php` tem apenas `Route::view('/', 'pages.home')`, o layout `resources/views/layouts/public.blade.php` só emite `@yield('title')`, não existe `app/Application/`, não existem componentes Blade de conteúdo, nem snapshots visuais, nem testes de acessibilidade.
Restrições relevantes já materializadas no repositório e que condicionam o desenho:
- Runtime é `dunglas/frankenphp:1-php8.4-bookworm` **sem extensão `gd`/`imagick`** e **sem fontes instaladas**.
- `docker/entrypoint.sh` faz apenas `config:cache`, `route:cache`, `view:cache`; **não executa `storage:link`**, então o disco `public` não é servido pelo contêiner.
- O job `browser` do CI sobe o contêiner apontando para o mesmo PostgreSQL do runner, roda `php artisan migrate --force` no host e **não executa seed** — hoje as páginas testadas não dependem de conteúdo.
- `PublicImageUploadRules` grava um único arquivo por upload, com nome UUID, no disco `public` (ou `s3` quando padrão).
- Tailwind 4 sem `tailwind.config.js`; tokens em `resources/css/tokens.css` mapeados por `@theme` em `app.css`, com bloco `prefers-reduced-motion` já presente.
## Goals / Non-Goals
**Goals:**
- Entregar as rotas públicas do SPEC §5.1 que faltam, renderizando somente conteúdo publicado.
- Home editorial dirigida por `site_settings` e conteúdo publicado, na ordem do SPEC §6.2.
- SEO renderizado por página (title, description, canonical, Open Graph, JSON-LD), `sitemap.xml` e `robots.txt` por rota.
- Mídia responsiva com variantes, `srcset`, lazy loading e dimensões reservadas.
- Regressão visual determinística e verificação automatizada de acessibilidade nas rotas públicas, plugadas no gate `browser`.
**Non-Goals:**
- Briefing/lead (WEB-05, Fase 2), page builder, busca no site, i18n, PWA.
- CDN, cache HTTP/edge, otimização além do necessário para as metas do SPEC §6.6.
- Refatorar o CMS existente além do hook de variantes de imagem.
## Decisions
### D1 — Páginas públicas em Blade + controllers finos, sem Livewire
Rotas apontam para controllers em `app/Http/Controllers/PublicSite/` (`HomeController`, `ServiceController`, `PortfolioController`, `PageController`, `SitemapController`, `RobotsController`). Nenhuma seção pública tem estado ou interação, e o SPEC §11.1 é explícito em não transformar seção estática em componente Livewire.
*Alternativas:* componentes Livewire full-page (rejeitado: overhead sem estado, prejudica cache de view e snapshots); rotas `Route::view` (rejeitado: precisam de dados e de metadados de SEO).
### D2 — Leitura via Queries finas na camada Application
`app/Application/Queries/Marketing/`: `GetHomeContent`, `GetPublishedServices`, `GetPublishedPortfolioCases`, `FindPublishedPortfolioCaseBySlug`, `GetSitemapEntries`. Usam Eloquent direto com `published()` + eager loading explícito, conforme SPEC §9.3 e §9.6. Sem repositórios genéricos, sem Actions (não há escrita nesta change).
`GetHomeContent` retorna um DTO readonly (`app/Application/Data/HomeContent.php`) para o controller não montar array solto.
*Alternativa:* consultar Models direto na view (rejeitado: N+1 e regra de publicação espalhada).
### D3 — SEO por DTO + partial único no layout
Cada controller monta `App\Application\Data\PageMeta` (title, description, canonical, ogType, ogImageUrl, ogImageAlt, jsonLd) com fallback para `site_settings`. O layout renderiza um partial `components/seo/meta.blade.php`. A escolha de fallback fica em um único lugar (`PageMeta::forPage()` / `::forCase()`), testável em unit test sem banco.
*Alternativa:* pacote de SEO (rejeitado: dependência desnecessária para 7 rotas); `@section('meta')` por página (rejeitado: duplicação e fallback inconsistente).
### D4 — Sitemap e robots por rota, sem pacote
`/sitemap.xml` retorna uma view Blade XML com `Content-Type: application/xml`, alimentada por `GetSitemapEntries` (rotas estáticas + slugs publicados com `updated_at`). `/robots.txt` vira rota `text/plain` referenciando o sitemap absoluto; o arquivo estático `public/robots.txt` é removido para não sombrear a rota no Caddy.
### D5 — Variantes responsivas geradas no upload, nomeadas por convenção
Novo `App\Support\ResponsiveImage`:
- Larguras fixas: 480, 960, 1440. Formato mantido (jpeg/png/webp), qualidade fixa.
- Nome derivado do original: `<uuid>.jpg``<uuid>-480.jpg`, `<uuid>-960.jpg`, `<uuid>-1440.jpg`, sem coluna nova no banco.
- Geração síncrona no hook `saveUploadedFileUsing` das FileUploads de `PublicImageUploadRules`, portanto vale para todos os Resources do CMS sem duplicação.
- Componente Blade `<x-media.image>` monta `srcset`/`sizes`, `width`/`height`, `alt` e `loading` (eager só no hero).
- Comando `php artisan media:generate-variants` para backfill de imagens já existentes e para o seed.
Requer extensão **`gd`** no `Dockerfile`, no CI e no ambiente local, e a dependência `intervention/image` (v3, driver GD).
*Alternativas:* coluna `jsonb` com variantes (rejeitado: migração e sincronização de estado por um dado derivável do nome); resize on-the-fly por rota (rejeitado: CPU por request, cache e risco de path traversal); `spatie/laravel-medialibrary` (rejeitado: peso e reescrita do CMS já entregue); checar existência de variante em cada render (rejeitado: `stat`/HEAD por imagem, caro no S3 — por isso a geração é garantida no upload e no backfill).
### D6 — Determinismo visual: relógio congelado por env, seed dedicado e fontes self-hosted
- `APP_FROZEN_NOW`: quando definido e `APP_ENV !== 'production'`, um provider chama `CarbonImmutable::setTestNow()`. Isso congela o relógio **do servidor**, que é o processo que renderiza — `travelTo()` no processo de teste não afeta o contêiner FrankenPHP.
- `VisualContentSeeder`: conteúdo fixo (textos, datas, ordem, imagens fixture versionadas em `tests/fixtures/images/`), executado no job `browser` antes da suíte.
- Fontes **self-hosted** via Vite, sem CDN, e `font-family` sem depender de fonte do sistema — o Chromium do Playwright roda no runner, não na imagem da aplicação, então fonte do sistema seria não determinística.
- Animações desabilitadas reutilizando o bloco `prefers-reduced-motion` já existente em `tokens.css`, com o Playwright emulando `reduce`. Sem código condicional de teste na aplicação.
### D7 — Acessibilidade via axe-core na suíte browser
Verificação automatizada nas rotas cobertas usando a assertion de acessibilidade do Pest Browser quando disponível; caso contrário, injetar `axe-core` (devDependency npm) na página e falhar em issues `critical`/`serious`. Regras estruturais baratas (um `h1`, landmarks, `alt` presente) ficam também em feature tests de HTML, que rodam sem browser e falham mais cedo.
### D8 — Infra de suporte: `storage:link` e seed no CI
- `docker/entrypoint.sh` passa a executar `php artisan storage:link` de forma idempotente, senão as imagens do disco `public` não são servidas pelo contêiner e todo snapshot com imagem falha.
- Job `browser` do CI passa a rodar `php artisan db:seed --class=VisualContentSeeder --force` antes dos testes e a publicar screenshots, diffs, logs da aplicação e logs do browser em falha (`if: failure()`).
### D9 — Páginas de erro
`resources/views/errors/404.blade.php` e `500.blade.php` usando o layout público. A 500 não recebe dados da exceção; em produção `APP_DEBUG=false` garante o handler genérico. Um feature test força uma exceção em rota de teste para verificar ausência de stack trace.
## Risks / Trade-offs
- **Snapshot instável por ambiente de renderização** → fontes self-hosted, viewport fixo, relógio congelado, seed determinístico, `reduce` motion, mesma imagem de aplicação do deploy; baseline só muda por `composer visual:update` com revisão humana.
- **`gd` + `intervention/image` aumentam a imagem e o tempo de upload** → três larguras fixas, sem editor de imagem, sem fila; se o upload ficar lento na prática, mover para job em fila é mudança local no hook.
- **Variantes órfãs ao trocar/excluir imagem** → remoção das variantes junto do original no mesmo hook; backfill pelo comando artisan quando houver divergência.
- **`route:cache` no entrypoint com nova rota `/robots.txt`** → remover o arquivo estático evita que o Caddy sirva o arquivo antes da aplicação; teste feature garante que a rota responde.
- **Seed no CI acopla o job `browser` a dados fixos** → seeder dedicado e versionado, separado do `ContentSeeder` de demonstração, para que mudança de demo não quebre snapshot.
- **Metas de LCP/CLS não são medidas automaticamente nesta change** → mitigado parcialmente por dimensões reservadas, lazy loading e hero eager; medição formal fica na Fase 5 (performance).
## Migration Plan
1. Sem migração de banco: nenhuma coluna nova.
2. Deploy exige `gd` na imagem e `storage:link` no entrypoint — ambos entram no mesmo build, validados pelo job `container`.
3. Após o deploy, rodar `php artisan media:generate-variants` uma vez para as imagens já enviadas; a renderização usa o original enquanto o backfill não roda.
4. Rollback: promover a imagem anterior. Variantes extras no storage ficam inertes e não quebram a versão antiga.
## Open Questions
- A API de acessibilidade do Pest Browser 4 cobre axe (`critical`/`serious`) ou será necessário injetar `axe-core` manualmente? Resolver na primeira fatia da suíte browser.
- Fonte tipográfica definitiva da marca (arquivo self-hosted) ainda não foi escolhida; até lá, usar a stack de tokens atual e ajustar antes de gravar as baselines.

View File

@@ -0,0 +1,45 @@
## Why
O CMS da Fase 1 está concluído (`site-settings`, `service-catalog`, `portfolio-cases`, `testimonials`, `content-media`), mas nenhum conteúdo publicado chega ao visitante: a única rota pública é `/` com um placeholder estático "Em breve". Sem o site público, o critério de saída da Fase 1 ("site público aprovado visualmente") não é atendido, a hipótese de aquisição do SPEC §2.2 não pode ser testada e a Fase 2 (briefing/leads) não tem onde ancorar o CTA.
## What Changes
- Implementar as rotas públicas do SPEC §5.1 ainda ausentes: `/servicos`, `/portfolio`, `/portfolio/{slug}`, `/sobre`, `/privacidade`, `/contato` (shell) e `/sitemap.xml`.
- Substituir a home placeholder por home editorial dirigida por conteúdo publicado, na ordem do SPEC §6.2 (WEB-01).
- Renderizar SEO por página: title, meta description, canonical, Open Graph, dados estruturados básicos, `robots.txt` servido por rota e sitemap com slugs publicados (SPEC §6.6).
- Injetar script de analytics apenas quando `analytics_enabled` estiver ativo em `site_settings` (WEB-06).
- Entregar mídia responsiva: variantes geradas no upload, `srcset`/`sizes`, `loading="lazy"` fora da primeira dobra e dimensões reservadas contra CLS (SPEC §6.4).
- Páginas de erro 404 com identidade visual e 500 sem stack trace em produção (WEB-07).
- Adicionar regressão visual determinística desktop/mobile para as telas do SPEC §13.5 já existentes nesta fase e testes automatizados de acessibilidade nas rotas públicas (SPEC §6.5, §13.8).
- Elevar o gate `browser` do CI para incluir snapshots visuais e acessibilidade, publicando artefatos diagnósticos em falha.
## Non-Goals
Conforme [SPEC.md §4.2](../../SPEC.md) e a divisão de fases:
- Formulário de briefing (WEB-05) e captura de lead — Fase 2. Esta change entrega apenas a página `/contato` com dados de contato do `site_settings`; o componente Livewire do briefing e as jornadas E2E-01/E2E-02 ficam para `build-lead-capture`.
- Snapshots de Briefing, Login, Dashboard e Detalhe do evento (SPEC §13.5) — dependem de telas de fases posteriores.
- Page builder, editor visual de páginas, busca no site, i18n, PWA.
- Password reset do painel interno (lacuna conhecida de `internal-authentication`, sem relação com o site público).
- Auditoria de publicação/despublicação (ADM-02) — Fase 5.
## Capabilities
### New Capabilities
- `public-site-pages`: rotas, layout e páginas públicas que exibem somente conteúdo publicado (WEB-01, WEB-02, WEB-03, WEB-04, WEB-07, SPEC §19).
- `public-seo`: metadados por página, canonical, Open Graph, dados estruturados, sitemap, robots e analytics condicional (SPEC §6.6, WEB-06).
- `visual-regression`: snapshots determinísticos desktop/mobile das telas públicas (SPEC §13.5).
- `web-accessibility`: verificação automatizada de acessibilidade das rotas públicas (SPEC §6.5, §13.8).
### Modified Capabilities
- `content-media`: além de validar upload, o sistema MUST gerar/servir variantes responsivas, aplicar lazy loading fora da primeira dobra e reservar dimensões (SPEC §6.4).
- `quality-gates`: o gate `browser` MUST executar snapshots visuais e acessibilidade e publicar artefatos diagnósticos em falha (SPEC §13.4, §14.1).
## Impact
- **Cria**: `routes/web.php` (rotas públicas), controllers em `app/Http/Controllers/PublicSite/`, Queries em `app/Application/Queries/Marketing/`, componentes Blade em `resources/views/components/` e páginas em `resources/views/pages/`, testes em `tests/Feature/PublicSite/` e `tests/Browser/`, baselines de snapshot versionadas.
- **Altera**: `resources/views/layouts/public.blade.php` (head SEO, landmarks, skip link), `app/Support/PublicImageUploadRules.php` e Filament Resources (geração de variantes), `ContentSeeder` (dados determinísticos para snapshots), `.github/workflows/ci.yml`, `public/robots.txt` (substituído por rota), `composer.json` se novo script for necessário.
- **Depende de**: specs `site-settings`, `service-catalog`, `portfolio-cases`, `testimonials`, `content-media`, `design-tokens`.
- **Risco**: instabilidade de snapshot (mitigada por relógio congelado, seed determinístico, fontes na imagem e animações desabilitadas — SPEC §13.5, §20).

View File

@@ -0,0 +1,52 @@
## ADDED Requirements
### Requirement: Public images are served in responsive variants
The system SHALL generate or serve responsive variants for public content images (service covers, portfolio covers and gallery, testimonial photos) and reference them with `srcset` and `sizes` so browsers download an appropriately sized file (SPEC §6.4). Variant generation MUST happen on upload, not on each request.
#### Scenario: Variants are produced on upload
- **WHEN** an admin uploads a public content image
- **THEN** responsive variants MUST be generated and stored alongside the original
- **AND** the database MUST keep only paths, never binary data
#### Scenario: Public markup offers multiple sources
- **WHEN** a public page renders a content image
- **THEN** the `img` element MUST expose `srcset` with the available variants
- **AND** MUST expose a `sizes` attribute matching the layout
#### Scenario: Missing variant falls back to the original
- **GIVEN** an image stored before variant generation existed
- **WHEN** it is rendered on a public page
- **THEN** the original file MUST be used without breaking the page
### Requirement: Public images avoid layout shift and defer offscreen loading
Public content images SHALL reserve their space through explicit `width` and `height` (or equivalent aspect-ratio styling) and MUST use `loading="lazy"` when rendered below the fold. Above-the-fold hero imagery MUST NOT be lazy loaded (SPEC §6.4, §6.6).
#### Scenario: Offscreen image is lazy loaded
- **WHEN** a page renders an image below the first viewport
- **THEN** the `img` element MUST carry `loading="lazy"`
#### Scenario: Hero image loads eagerly
- **WHEN** the home hero image is rendered
- **THEN** it MUST NOT carry `loading="lazy"`
#### Scenario: Dimensions are reserved
- **WHEN** any public content image is rendered
- **THEN** width and height (or aspect ratio) MUST be declared so layout does not shift after load
### Requirement: Production images are not served from ephemeral container disk
Public image variants SHALL be stored on the configured filesystem disk (S3-compatible in production) and referenced by URL, so a container restart or redeploy does not lose media (SPEC §6.4).
#### Scenario: Media survives container replacement
- **GIVEN** production uses the S3-compatible disk
- **WHEN** the application container is replaced
- **THEN** previously uploaded images and variants MUST remain reachable

View File

@@ -0,0 +1,90 @@
## ADDED Requirements
### Requirement: Every public page emits title, description and canonical
The system SHALL render a unique `<title>`, a `<meta name="description">` and a `<link rel="canonical">` on every public route (SPEC §6.6, §19). Portfolio cases MUST use `meta_title`/`meta_description` when filled and fall back to title/summary otherwise. Pages without page-level metadata MUST fall back to `default_meta_title` and `default_meta_description` from `site_settings`.
#### Scenario: Page-level metadata overrides defaults
- **GIVEN** a published case with `meta_title` and `meta_description` filled
- **WHEN** a visitor loads the case detail
- **THEN** the rendered title and description MUST use the case values
#### Scenario: Missing metadata falls back to site defaults
- **GIVEN** a published case without `meta_title`
- **WHEN** a visitor loads the case detail
- **THEN** the rendered title MUST be derived from the case title
- **AND** the description MUST fall back to the case summary or the site default
#### Scenario: Canonical points to the absolute route URL
- **WHEN** any public page is rendered
- **THEN** the canonical URL MUST be the absolute URL of that route without query parameters
### Requirement: Open Graph metadata is emitted for sharing
The system SHALL emit Open Graph tags (`og:title`, `og:description`, `og:type`, `og:url`, `og:image`) on public pages. The image MUST use the page cover image when available and `default_og_image_path` from `site_settings` otherwise.
#### Scenario: Case detail uses its cover as OG image
- **GIVEN** a published case with a cover image
- **WHEN** the case detail is rendered
- **THEN** `og:image` MUST reference the case cover image URL
#### Scenario: Pages without cover use the default OG image
- **WHEN** a page without its own image is rendered
- **THEN** `og:image` MUST reference `default_og_image_path`
### Requirement: Sitemap and robots are served by the application
The system SHALL serve `/sitemap.xml` listing the home, institutional routes, the services listing, the portfolio listing and every published case slug with its last modification date. `/robots.txt` MUST be served by an application route referencing the sitemap URL.
#### Scenario: Sitemap contains only published slugs
- **GIVEN** one published case and one draft case
- **WHEN** `/sitemap.xml` is requested
- **THEN** the response MUST include the published slug
- **AND** MUST NOT include the draft slug
#### Scenario: Newly published case enters the sitemap
- **WHEN** an admin publishes a case
- **THEN** the case slug MUST appear in `/sitemap.xml` on the next request
#### Scenario: Robots references the sitemap
- **WHEN** `/robots.txt` is requested
- **THEN** the response MUST be `text/plain`
- **AND** MUST contain the absolute `/sitemap.xml` URL
### Requirement: Basic structured data is emitted where applicable
The system SHALL emit JSON-LD structured data: `Organization` on the home using `site_settings`, and `Article` or equivalent creative work on the case detail.
#### Scenario: Home exposes organization data
- **WHEN** the home is rendered
- **THEN** a JSON-LD block of type `Organization` MUST be present with brand name and contact data
#### Scenario: Structured data is valid JSON
- **WHEN** any public page emits JSON-LD
- **THEN** the script content MUST parse as valid JSON
### Requirement: Analytics script is injected only when explicitly enabled
The system SHALL render the analytics snippet from `site_settings` only when `analytics_enabled` is true and the script field is non-empty (WEB-06). Analytics MUST be disabled by default.
#### Scenario: Analytics disabled emits nothing
- **GIVEN** `analytics_enabled` is false
- **WHEN** any public page is rendered
- **THEN** the analytics snippet MUST NOT appear in the HTML
#### Scenario: Analytics enabled injects the configured snippet
- **GIVEN** `analytics_enabled` is true and a snippet is configured
- **WHEN** a public page is rendered
- **THEN** the snippet MUST be present exactly once

View File

@@ -0,0 +1,115 @@
## ADDED Requirements
### Requirement: Public routes serve published content without authentication
The system SHALL expose the public routes of SPEC §5.1: `home` (`/`), `services.index` (`/servicos`), `portfolio.index` (`/portfolio`), `portfolio.show` (`/portfolio/{slug}`), `about` (`/sobre`), `contact` (`/contato`) and `privacy` (`/privacidade`). Every public route MUST respond without authentication and MUST NOT expose unpublished content, internal fields, or internal notes (SPEC §19).
#### Scenario: Guest reaches every public route
- **WHEN** an unauthenticated visitor requests any public route
- **THEN** the response status MUST be 200
- **AND** no redirect to `/admin/login` MUST occur
#### Scenario: Unpublished content is invisible
- **GIVEN** a service, portfolio case, or testimonial with `published_at` null
- **WHEN** a visitor loads the corresponding public page
- **THEN** the record MUST NOT appear in the rendered output
#### Scenario: Unpublished case detail returns 404
- **GIVEN** a portfolio case saved as draft
- **WHEN** a visitor requests `/portfolio/{slug}` for that case
- **THEN** the response status MUST be 404
#### Scenario: Published case detail becomes reachable
- **GIVEN** a portfolio case saved as draft
- **WHEN** an admin fills the required fields and publishes the case
- **THEN** `/portfolio/{slug}` MUST respond 200
- **AND** the case MUST appear in the `/portfolio` listing
### Requirement: Home renders the editorial structure from CMS content
The home page SHALL render, in the order defined by SPEC §6.2, header/navigation, hero, featured visual proof, services summary, working method, selected cases, testimonials, final briefing CTA, and footer with contact, social links and legal links (WEB-01). Hero copy, brand name and contact data MUST come from `site_settings`; services, cases and testimonials MUST come from published records.
#### Scenario: Published content is displayed in configured order
- **GIVEN** published services, cases and testimonials exist
- **WHEN** a visitor loads the home
- **THEN** the published content MUST be displayed following the `sort_order` and featured flags
- **AND** the hero MUST show the values stored in `site_settings`
#### Scenario: CTA leads to the briefing page
- **WHEN** a visitor activates the primary or final CTA on the home
- **THEN** the visitor MUST be taken to the `contact` route
#### Scenario: Empty content does not break the home
- **GIVEN** no published services, cases or testimonials
- **WHEN** a visitor loads the home
- **THEN** the response MUST be 200
- **AND** the affected sections MUST be omitted instead of rendering empty containers
#### Scenario: Home has no console errors
- **WHEN** the home is loaded in a real browser at desktop and mobile viewports
- **THEN** the browser console MUST contain no JavaScript errors
### Requirement: Listing and detail pages exist for catalog content
The system SHALL render a services listing (WEB-02) and a portfolio listing plus case detail (WEB-03). The case detail MUST present summary, event type, optional city/venue/date, challenge, solution, optional result, cover image and the ordered gallery.
#### Scenario: Services listing shows published services
- **WHEN** a visitor loads `/servicos`
- **THEN** every published service MUST be listed with title and summary in `sort_order`
#### Scenario: Gallery respects stored order
- **GIVEN** a published case with multiple gallery images
- **WHEN** a visitor loads the case detail
- **THEN** the images MUST be rendered ordered by `sort_order`
#### Scenario: Listings paginate open-ended growth
- **WHEN** the number of published cases exceeds the page size
- **THEN** `/portfolio` MUST paginate instead of rendering all records
### Requirement: Institutional and error pages have brand identity
The system SHALL provide the Sobre and Política de privacidade pages and branded error pages (WEB-07). The 404 page MUST use the public layout, and the 500 page MUST NOT expose stack traces or internal details when `APP_DEBUG` is false.
#### Scenario: Unknown URL renders branded 404
- **WHEN** a visitor requests a non-existent public URL
- **THEN** the response status MUST be 404
- **AND** the page MUST use the public layout and offer navigation back to the home
#### Scenario: Server error hides internals in production
- **GIVEN** `APP_DEBUG` is false
- **WHEN** an unhandled exception occurs on a public route
- **THEN** the response MUST be a generic branded error page
- **AND** MUST NOT contain a stack trace, file path, or environment variable
### Requirement: Contact page presents contact data as briefing placeholder
The `contact` route SHALL render the contact page using `site_settings` (e-mail, phone, city, social links) so the home CTA has a valid destination before the briefing form exists. The page MUST NOT create leads in this change.
#### Scenario: Contact page shows configured contact data
- **WHEN** a visitor loads `/contato`
- **THEN** the e-mail and phone stored in `site_settings` MUST be displayed
- **AND** no lead record MUST be created
### Requirement: Public pages avoid N+1 queries
Public pages SHALL load related content with explicit eager loading through dedicated read Queries in the Application layer. Rendering a page MUST NOT issue one query per related record (SPEC §19).
#### Scenario: Case detail loads gallery in bounded queries
- **WHEN** a case detail page with many gallery images is rendered
- **THEN** the gallery MUST be loaded with eager loading
- **AND** the query count MUST NOT grow with the number of images

View File

@@ -0,0 +1,21 @@
## MODIFIED Requirements
### Requirement: Browser tests run against FrankenPHP-served application
The system SHALL execute browser tests using Pest Browser/Playwright against an application served by FrankenPHP in CI. The `browser` job MUST cover the E2E journeys available in the current phase, the visual regression assertions and the automated accessibility checks for public routes, and MUST run in assertion mode without regenerating baselines (SPEC §13.4, §13.5, §13.8, §14.1).
#### Scenario: Browser job validates served application
- **WHEN** the `browser` CI job runs
- **THEN** tests execute against the built application artifact or equivalent production-like image
#### Scenario: Browser job covers visual and accessibility assertions
- **WHEN** the `browser` CI job runs
- **THEN** it MUST execute the visual regression suite and the accessibility suite
- **AND** a failing snapshot or a critical/serious accessibility issue MUST block merge
#### Scenario: Browser failures publish diagnostics
- **WHEN** a browser test fails in CI
- **THEN** the job MUST publish screenshots, snapshot diffs, application logs and browser logs as artifacts

View File

@@ -0,0 +1,51 @@
## ADDED Requirements
### Requirement: Public screens have desktop and mobile visual baselines
The system SHALL keep versioned screenshot baselines for the public screens available in this phase (SPEC §13.5): Home, Serviços, Portfólio and Detalhe do portfólio, at 1440×1000 desktop and 390×844 mobile. A rendering change that alters those screens MUST fail the browser suite until the diff is reviewed.
#### Scenario: Unintended visual change fails the suite
- **GIVEN** approved baselines exist
- **WHEN** a code change alters the rendering of a covered screen
- **THEN** the visual assertion MUST fail and report the diff
#### Scenario: Both viewports are covered
- **WHEN** the visual suite runs
- **THEN** each covered screen MUST be asserted at 1440×1000 and 390×844
### Requirement: Visual runs are deterministic
Visual runs SHALL be deterministic per SPEC §13.5: fixed Chromium and Linux image, fixed viewport, timezone `America/Fortaleza`, locale `pt-BR`, fonts installed in the image, frozen clock, deterministic seed, animations and transitions disabled, and no dependency on external network.
#### Scenario: Repeated run without code change produces no diff
- **WHEN** the visual suite runs twice against the same commit and seed
- **THEN** both runs MUST pass with no pixel diff
#### Scenario: Time-dependent content does not cause drift
- **GIVEN** the clock is frozen and the seed is deterministic
- **WHEN** the suite runs on a different calendar day
- **THEN** rendered dates MUST remain identical to the baseline
#### Scenario: Motion is disabled during capture
- **WHEN** a screenshot is captured
- **THEN** CSS animations and transitions MUST be disabled
### Requirement: Baseline updates are explicit and reviewed
Baselines SHALL only be updated through the explicit `composer visual:update` command, and the resulting diff MUST be reviewed by a human before merge. Baselines MUST NOT be regenerated automatically to make CI pass.
#### Scenario: CI does not regenerate baselines
- **WHEN** the `browser` CI job runs
- **THEN** it MUST run in assertion mode
- **AND** MUST NOT write new baselines
#### Scenario: Developer updates baselines intentionally
- **WHEN** a developer runs `composer visual:update`
- **THEN** the updated baseline files MUST be written to the versioned baseline directory for review

View File

@@ -0,0 +1,68 @@
## ADDED Requirements
### Requirement: Public routes have no critical or serious accessibility issues
The system SHALL run automated accessibility checks on the public routes covered by the browser suite (SPEC §6.5, §13.8). A critical or serious issue MUST fail the suite.
#### Scenario: Critical issue blocks the suite
- **WHEN** the automated accessibility check reports a critical or serious issue on a covered route
- **THEN** the browser suite MUST fail and report the offending rule and selector
#### Scenario: Covered routes are checked
- **WHEN** the accessibility suite runs
- **THEN** the home, services listing, portfolio listing and case detail MUST each be checked
### Requirement: Public pages use accessible semantic structure
Public pages SHALL provide semantic landmarks, exactly one `h1` per page, a coherent heading order, alt text on every content image, and visible focus on interactive elements (SPEC §6.5).
#### Scenario: Single h1 per page
- **WHEN** any public page is rendered
- **THEN** exactly one `h1` element MUST be present
#### Scenario: Landmarks are present
- **WHEN** any public page is rendered
- **THEN** `header`, `main`, `nav` and `footer` landmarks MUST be present
#### Scenario: Content images expose alt text
- **WHEN** a page renders a cover or gallery image
- **THEN** the `alt` attribute MUST contain the stored alt text
### Requirement: Public pages are fully keyboard operable
Visitors SHALL be able to reach and activate every interactive element with the keyboard, with a visible focus indicator and a skip link to the main content.
#### Scenario: Keyboard reaches the primary CTA
- **WHEN** a visitor navigates the home with the Tab key
- **THEN** the primary CTA MUST receive focus with a visible indicator
- **AND** activating it with the keyboard MUST navigate to the contact route
#### Scenario: Skip link bypasses navigation
- **WHEN** a visitor focuses the first element of a public page
- **THEN** a skip link to the main content MUST be available
### Requirement: Reduced motion preference is honored
The system SHALL suppress non-essential animation and transition when the user agent reports `prefers-reduced-motion: reduce`.
#### Scenario: Reduced motion disables transitions
- **GIVEN** the browser reports `prefers-reduced-motion: reduce`
- **WHEN** a public page is loaded
- **THEN** decorative transitions and animations MUST NOT run
### Requirement: Public pages emit no console errors
Covered public routes SHALL load without JavaScript console errors in a real browser (SPEC §13.8, §19).
#### Scenario: Console stays clean on covered routes
- **WHEN** a covered public route is loaded in the browser suite
- **THEN** the console MUST contain no error-level messages

View File

@@ -0,0 +1,72 @@
## 1. Fundação de leitura e layout público
- [x] 1.1 Criar `app/Application/Queries/Marketing/GetPublishedServices` e `GetPublishedPortfolioCases` (scope `published()`, ordenação por `sort_order`, eager loading explícito) com feature tests cobrindo exclusão de rascunho e ordem
- [x] 1.2 Criar `FindPublishedPortfolioCaseBySlug` retornando `null` para rascunho, com teste
- [x] 1.3 Criar `app/Application/Data/PageMeta` com fallback para `site_settings` e unit test sem banco (title/description/canonical/OG)
- [x] 1.4 Estender `layouts/public.blade.php` com head de SEO (`components/seo/meta.blade.php`), landmarks completos, navegação e footer alimentados por `site_settings`; feature test do head
- [x] 1.5 Rodar `composer pint`, `composer phpstan` e `composer test:feature`
## 2. Mídia responsiva
- [x] 2.1 Adicionar extensão `gd` ao `Dockerfile` e às matrizes de PHP do CI; adicionar `intervention/image` ao `composer.json`
- [x] 2.2 Criar `app/Support/ResponsiveImage` gerando variantes 480/960/1440 com nome derivado do original, e removendo variantes quando o original é substituído/excluído; unit test com `Storage::fake`
- [x] 2.3 Plugar a geração no `saveUploadedFileUsing` de `PublicImageUploadRules` e cobrir com feature test em um Resource do CMS
- [x] 2.4 Criar componente `<x-media.image>` com `srcset`, `sizes`, `width`/`height`, `alt` e `loading` configurável; feature test verificando lazy fora da dobra e eager no hero
- [x] 2.5 Criar comando `php artisan media:generate-variants` para backfill, com teste
- [x] 2.6 Adicionar `php artisan storage:link` idempotente ao `docker/entrypoint.sh` e validar no job `container`
- [x] 2.7 Rodar `composer quality`
## 3. Home editorial (WEB-01)
- [x] 3.1 Criar `GetHomeContent` + DTO `HomeContent` (hero de `site_settings`, serviços/casos em destaque, depoimentos publicados) com feature test
- [x] 3.2 Criar `HomeController` e substituir `Route::view('/')` pela rota nomeada `home`
- [x] 3.3 Implementar as seções do SPEC §6.2 como componentes Blade reutilizáveis (hero, prova visual, serviços, método, casos, depoimentos, CTA final)
- [x] 3.4 Feature tests: conteúdo publicado exibido em ordem, rascunho ausente, seções omitidas quando não há conteúdo, CTA aponta para a rota `contact`
- [x] 3.5 Rodar `composer quality`
## 4. Serviços, portfólio e páginas institucionais (WEB-02, WEB-03, WEB-07)
- [x] 4.1 Rota + controller + view de `/servicos` listando serviços publicados; feature test
- [x] 4.2 Rota + controller + view de `/portfolio` com paginação; feature test incluindo paginação e exclusão de rascunho
- [x] 4.3 Rota + view de `/portfolio/{slug}` com desafio, solução, resultado e galeria ordenada; feature tests de 200 publicado, 404 rascunho e ordem da galeria
- [x] 4.4 Rotas + views de `/sobre` e `/privacidade` usando `site_settings`; feature tests
- [x] 4.5 Rota + view de `/contato` exibindo e-mail, telefone e redes de `site_settings`, sem criação de lead; feature test
- [x] 4.6 Views `errors/404.blade.php` e `errors/500.blade.php` com layout público; feature tests de 404 branded e de 500 sem stack trace com `APP_DEBUG=false`
- [x] 4.7 Teste de contagem de queries no detalhe do caso para garantir ausência de N+1
- [x] 4.8 Rodar `composer quality`
## 5. SEO, sitemap e analytics
- [x] 5.1 Aplicar `PageMeta` em todos os controllers públicos (title, description, canonical, OG) com feature tests de override por caso e de fallback para os padrões do site
- [x] 5.2 Emitir JSON-LD `Organization` na home e `Article`/creative work no detalhe do caso; feature test validando JSON parseável
- [x] 5.3 Criar `GetSitemapEntries`, rota `/sitemap.xml` e view XML; feature tests de inclusão de publicado, exclusão de rascunho e entrada após publicação
- [x] 5.4 Substituir `public/robots.txt` por rota `text/plain` referenciando o sitemap absoluto; feature test
- [x] 5.5 Injetar o snippet de analytics apenas com `analytics_enabled` verdadeiro; feature tests dos dois estados
- [x] 5.6 Rodar `composer quality`
## 6. Acessibilidade
- [x] 6.1 Feature tests estruturais de HTML: um único `h1`, landmarks `header/nav/main/footer`, `alt` presente nas imagens de conteúdo
- [x] 6.2 Garantir skip link funcional e foco visível em todos os elementos interativos das páginas novas
- [x] 6.3 Adicionar verificação axe na suíte browser para home, serviços, portfólio e detalhe do caso, falhando em issues `critical`/`serious`
- [x] 6.4 Teste browser de navegação por teclado até o CTA principal e ativação por teclado
- [x] 6.5 Teste browser garantindo ausência de erros no console nas rotas cobertas
- [x] 6.6 Verificar `prefers-reduced-motion: reduce` desabilitando transições; teste browser com emulação
- [x] 6.7 Rodar `composer test:browser`
## 7. Regressão visual
- [x] 7.1 Adicionar fontes self-hosted via Vite e remover qualquer dependência de fonte de sistema ou CDN
- [x] 7.2 Implementar `APP_FROZEN_NOW` (provider que chama `CarbonImmutable::setTestNow()` fora de produção) e documentar em `.env.example`; unit test do provider
- [x] 7.3 Criar `VisualContentSeeder` determinístico (textos, datas e imagens fixture fixas), separado do `ContentSeeder`
- [x] 7.4 Criar testes de snapshot para Home, Serviços, Portfólio e Detalhe do portfólio em 1440×1000 e 390×844; gravar baselines versionadas
- [x] 7.5 Confirmar que duas execuções consecutivas no mesmo commit não produzem diff
- [x] 7.6 Verificar que `composer visual:update` grava baselines e que a suíte padrão roda em modo assertivo
## 8. Gate de CI e fechamento da fase
- [x] 8.1 Job `browser` do CI: executar `php artisan db:seed --class=VisualContentSeeder --force` antes da suíte
- [x] 8.2 Job `browser` do CI: publicar screenshots, diffs de snapshot, logs da aplicação e logs do browser com `if: failure()`
- [ ] 8.3 Confirmar os cinco jobs verdes (`static`, `unit`, `feature`, `browser`, `container`) em pull request
- [x] 8.4 Rodar `composer quality` completo e registrar o resultado no PR
- [x] 8.5 Revisar o critério de saída da Fase 1 (conteúdo gerenciável no Filament e site público aprovado visualmente) e atualizar `SPEC.md` §18 marcando apenas itens comprovados

View File

@@ -1,2 +0,0 @@
User-agent: *
Disallow:

View File

@@ -59,6 +59,17 @@
color: var(--amare-color-text); color: var(--amare-color-text);
font-family: var(--amare-font-sans); font-family: var(--amare-font-sans);
} }
a:focus-visible,
button:focus-visible,
summary:focus-visible,
input:focus-visible,
textarea:focus-visible,
select:focus-visible,
[tabindex]:focus-visible {
outline: 2px solid var(--amare-color-accent);
outline-offset: 3px;
}
} }
@utility container-amare { @utility container-amare {

View File

@@ -1,7 +1,7 @@
:root { :root {
/* Typography */ /* Typography */
--amare-font-sans: 'Instrument Sans', ui-sans-serif, system-ui, sans-serif; --amare-font-sans: var(--font-instrument-sans, 'Instrument Sans'), sans-serif;
--amare-font-serif: 'Georgia', 'Times New Roman', serif; --amare-font-serif: var(--font-instrument-sans, 'Instrument Sans'), sans-serif;
/* Font scale */ /* Font scale */
--amare-text-xs: 0.75rem; --amare-text-xs: 0.75rem;
@@ -40,9 +40,9 @@
--amare-color-text: #1a1410; --amare-color-text: #1a1410;
--amare-color-text-muted: #4a4038; --amare-color-text-muted: #4a4038;
--amare-color-border: #d9cfc0; --amare-color-border: #d9cfc0;
--amare-color-accent: #b8860b; --amare-color-accent: #8a6500;
--amare-color-accent-hover: #996f00; --amare-color-accent-hover: #6f5200;
--amare-color-accent-text: #1a1410; --amare-color-accent-text: #fffdf8;
--amare-color-success: #166534; --amare-color-success: #166534;
--amare-color-warning: #92400e; --amare-color-warning: #92400e;
--amare-color-error: #991b1b; --amare-color-error: #991b1b;

View File

@@ -0,0 +1,37 @@
@php
$manifestPath = public_path('build/fonts-manifest.json');
$hotManifestPath = public_path('hot') !== '' && is_file(public_path('build/fonts-manifest.dev.json'))
? public_path('build/fonts-manifest.dev.json')
: null;
$manifestFile = is_file($manifestPath) ? $manifestPath : $hotManifestPath;
$manifest = is_string($manifestFile) && is_file($manifestFile)
? json_decode((string) file_get_contents($manifestFile), true)
: null;
$cssFile = is_array($manifest) ? ($manifest['style']['file'] ?? null) : null;
$preloads = is_array($manifest) ? ($manifest['preloads'] ?? []) : [];
$familyStyles = is_array($manifest) ? ($manifest['style']['familyStyles'] ?? []) : [];
$variables = is_array($manifest) ? ($manifest['style']['variables'] ?? []) : [];
@endphp
@if (is_array($manifest))
@foreach ($preloads as $preload)
<link
rel="preload"
as="{{ $preload['as'] ?? 'font' }}"
href="{{ asset('build/'.$preload['file']) }}"
type="{{ $preload['type'] ?? 'font/woff2' }}"
crossorigin="{{ $preload['crossorigin'] ?? 'anonymous' }}"
>
@endforeach
@if (filled($cssFile))
<link rel="stylesheet" href="{{ asset('build/'.$cssFile) }}">
@elseif ($familyStyles !== [])
<style>
{!! implode("\n", array_values($variables)) !!}
{!! implode("\n", array_values($familyStyles)) !!}
</style>
@endif
@endif

View File

@@ -0,0 +1,37 @@
@props([
'cases',
])
@if ($cases->isNotEmpty())
<section aria-labelledby="cases-heading" class="border-b border-amare-border py-16">
<div class="container-amare space-y-8">
<div class="max-w-2xl space-y-3">
<h2 id="cases-heading" class="text-3xl font-semibold text-amare-text">Casos selecionados</h2>
<p class="text-amare-text-muted">Histórias recentes de celebrações conduzidas pela Amare.</p>
</div>
<div class="grid gap-8">
@foreach ($cases as $case)
<article class="grid gap-4 border-t border-amare-border pt-6 md:grid-cols-[200px_minmax(0,1fr)]">
@if (filled($case->cover_image_path))
<x-media.image
:path="$case->cover_image_path"
:alt="$case->cover_image_alt ?: $case->title"
sizes="200px"
class="aspect-square w-full object-cover"
/>
@endif
<div class="space-y-2">
<h3 class="text-2xl font-semibold text-amare-text">{{ $case->title }}</h3>
<p class="text-sm text-amare-text-muted">{{ $case->event_type }}@if($case->city) · {{ $case->city }}@endif</p>
<p class="text-amare-text-muted">{{ $case->summary }}</p>
<a href="{{ url('/portfolio/'.$case->slug) }}" class="inline-flex text-sm font-semibold text-amare-accent hover:text-amare-accent-hover">
Ver caso
</a>
</div>
</article>
@endforeach
</div>
</div>
</section>
@endif

View File

@@ -0,0 +1,20 @@
@props([
'settings',
])
<section aria-labelledby="final-cta-heading" class="py-16">
<div class="container-amare rounded-xl border border-amare-border bg-amare-bg-muted px-8 py-12 text-center">
<h2 id="final-cta-heading" class="text-3xl font-semibold text-amare-text">Vamos planejar o seu evento?</h2>
<p class="mx-auto mt-3 max-w-2xl text-amare-text-muted">
Conte um pouco do que você imagina. A próxima conversa começa no briefing.
</p>
<div class="mt-8">
<a
href="{{ route('contact') }}"
class="inline-flex items-center rounded-md bg-amare-accent px-5 py-3 text-sm font-semibold text-amare-accent-text transition-colors duration-(--amare-duration-normal) ease-(--amare-ease-standard) hover:bg-amare-accent-hover"
>
{{ $settings->hero_cta_label }}
</a>
</div>
</div>
</section>

View File

@@ -0,0 +1,43 @@
@props([
'settings',
])
<section aria-labelledby="hero-heading" class="relative overflow-hidden border-b border-amare-border bg-amare-bg">
<div class="container-amare grid gap-10 py-16 md:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)] md:items-center md:py-24">
<div class="space-y-6">
@if (filled($settings->hero_eyebrow))
<p class="text-sm font-medium uppercase tracking-[0.18em] text-amare-accent">{{ $settings->hero_eyebrow }}</p>
@endif
<h1 id="hero-heading" class="max-w-3xl text-4xl font-semibold tracking-tight text-amare-text md:text-5xl">
{{ $settings->hero_title }}
</h1>
@if (filled($settings->hero_subtitle))
<p class="max-w-2xl text-lg text-amare-text-muted">{{ $settings->hero_subtitle }}</p>
@endif
<div>
<a
href="{{ route('contact') }}"
data-testid="home-primary-cta"
class="inline-flex items-center rounded-md bg-amare-accent px-5 py-3 text-sm font-semibold text-amare-accent-text transition-colors duration-(--amare-duration-normal) ease-(--amare-ease-standard) hover:bg-amare-accent-hover focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-3 focus-visible:outline-amare-accent"
>
{{ $settings->hero_cta_label }}
</a>
</div>
</div>
@if (filled($settings->default_og_image_path))
<div class="min-h-72 overflow-hidden rounded-xl bg-amare-bg-muted">
<x-media.image
:path="$settings->default_og_image_path"
:alt="$settings->default_og_image_alt ?: $settings->brand_name"
loading="eager"
sizes="(max-width: 768px) 100vw, 40vw"
class="h-full w-full object-cover"
/>
</div>
@endif
</div>
</section>

View File

@@ -0,0 +1,21 @@
@props([
'settings',
])
<section aria-labelledby="method-heading" class="border-b border-amare-border bg-amare-bg-muted py-16">
<div class="container-amare grid gap-8 md:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)] md:items-start">
<div class="space-y-3">
<h2 id="method-heading" class="text-3xl font-semibold text-amare-text">Método de trabalho</h2>
<p class="text-amare-text-muted">Do briefing ao dia do evento, com clareza e acompanhamento próximo.</p>
</div>
<div class="space-y-4 text-amare-text-muted">
<p>{{ $settings->about_summary }}</p>
<ol class="grid gap-3">
<li>1. Escuta e briefing inicial</li>
<li>2. Planejamento e curadoria</li>
<li>3. Coordenação no dia do evento</li>
</ol>
</div>
</div>
</section>

View File

@@ -0,0 +1,31 @@
@props([
'cases',
])
@if ($cases->isNotEmpty())
<section aria-labelledby="proof-heading" class="border-b border-amare-border bg-amare-bg-muted py-16">
<div class="container-amare space-y-8">
<div class="max-w-2xl space-y-3">
<h2 id="proof-heading" class="text-3xl font-semibold text-amare-text">Prova visual</h2>
<p class="text-amare-text-muted">Eventos em destaque que mostram o cuidado com cada celebração.</p>
</div>
<div class="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
@foreach ($cases as $case)
<article class="space-y-3">
@if (filled($case->cover_image_path))
<x-media.image
:path="$case->cover_image_path"
:alt="$case->cover_image_alt ?: $case->title"
sizes="(max-width: 768px) 100vw, 33vw"
class="aspect-[4/3] w-full object-cover"
/>
@endif
<h3 class="text-xl font-semibold text-amare-text">{{ $case->title }}</h3>
<p class="text-sm text-amare-text-muted">{{ $case->summary }}</p>
</article>
@endforeach
</div>
</div>
</section>
@endif

View File

@@ -0,0 +1,29 @@
@props([
'services',
])
@if ($services->isNotEmpty())
<section aria-labelledby="services-heading" class="border-b border-amare-border py-16">
<div class="container-amare space-y-8">
<div class="max-w-2xl space-y-3">
<h2 id="services-heading" class="text-3xl font-semibold text-amare-text">Serviços</h2>
<p class="text-amare-text-muted">Um resumo do que a assessoria pode conduzir com você.</p>
</div>
<div class="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
@foreach ($services as $service)
<article class="space-y-3 border-t border-amare-border pt-4">
<h3 class="text-xl font-semibold text-amare-text">{{ $service->title }}</h3>
<p class="text-amare-text-muted">{{ $service->summary }}</p>
</article>
@endforeach
</div>
<p>
<a href="{{ url('/servicos') }}" class="text-sm font-semibold text-amare-accent transition-colors hover:text-amare-accent-hover">
Ver todos os serviços
</a>
</p>
</div>
</section>
@endif

View File

@@ -0,0 +1,28 @@
@props([
'testimonials',
])
@if ($testimonials->isNotEmpty())
<section aria-labelledby="testimonials-heading" class="border-b border-amare-border bg-amare-bg-muted py-16">
<div class="container-amare space-y-8">
<div class="max-w-2xl space-y-3">
<h2 id="testimonials-heading" class="text-3xl font-semibold text-amare-text">Depoimentos</h2>
<p class="text-amare-text-muted">Quem celebrou com a Amare conta como foi a experiência.</p>
</div>
<div class="grid gap-6 md:grid-cols-2">
@foreach ($testimonials as $testimonial)
<blockquote class="space-y-4 border-t border-amare-border pt-4">
<p class="text-lg text-amare-text">{{ $testimonial->quote }}</p>
<footer class="text-sm text-amare-text-muted">
<cite class="not-italic font-semibold text-amare-text">{{ $testimonial->author_name }}</cite>
@if (filled($testimonial->context))
<span> {{ $testimonial->context }}</span>
@endif
</footer>
</blockquote>
@endforeach
</div>
</div>
</section>
@endif

View File

@@ -0,0 +1,47 @@
@props([
'path',
'alt',
'sizes' => '(max-width: 768px) 100vw, 960px',
'loading' => 'lazy',
'width' => null,
'height' => null,
'disk' => null,
'class' => null,
])
@php
use App\Support\PublicImageUploadRules;
use App\Support\ResponsiveImage;
use Illuminate\Support\Facades\Storage;
$diskName = $disk ?? PublicImageUploadRules::disk();
$filesystem = Storage::disk($diskName);
$src = $filesystem->url($path);
$variants = ResponsiveImage::availableVariants($path, $diskName);
$srcset = collect($variants)
->map(fn (array $variant): string => $filesystem->url($variant['path']).' '.$variant['width'].'w')
->implode(', ');
if ($srcset === '' && $filesystem->exists($path)) {
$srcset = null;
}
$dimensions = ($width === null || $height === null)
? ResponsiveImage::dimensions($path, $diskName)
: null;
$resolvedWidth = $width ?? $dimensions['width'] ?? null;
$resolvedHeight = $height ?? $dimensions['height'] ?? null;
$loadingValue = $loading === 'eager' ? 'eager' : 'lazy';
@endphp
<img
src="{{ $src }}"
@if ($srcset) srcset="{{ $srcset }}" sizes="{{ $sizes }}" @endif
alt="{{ $alt }}"
@if ($resolvedWidth) width="{{ $resolvedWidth }}" @endif
@if ($resolvedHeight) height="{{ $resolvedHeight }}" @endif
loading="{{ $loadingValue }}"
@if ($class) class="{{ $class }}" @endif
{{ $attributes->except(['path', 'alt', 'sizes', 'loading', 'width', 'height', 'disk', 'class']) }}
>

View File

@@ -0,0 +1,21 @@
@props([
'pageMeta',
])
<meta name="description" content="{{ $pageMeta->description }}">
<link rel="canonical" href="{{ $pageMeta->canonical }}">
<meta property="og:title" content="{{ $pageMeta->title }}">
<meta property="og:description" content="{{ $pageMeta->description }}">
<meta property="og:type" content="{{ $pageMeta->ogType }}">
<meta property="og:url" content="{{ $pageMeta->canonical }}">
@if ($pageMeta->ogImageUrl)
<meta property="og:image" content="{{ $pageMeta->ogImageUrl }}">
@if ($pageMeta->ogImageAlt)
<meta property="og:image:alt" content="{{ $pageMeta->ogImageAlt }}">
@endif
@endif
@if ($pageMeta->jsonLd)
<script type="application/ld+json">{!! json_encode($pageMeta->jsonLd, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) !!}</script>
@endif

View File

@@ -0,0 +1,14 @@
@extends('layouts.public')
@section('content')
<div class="container-amare max-w-2xl space-y-6 py-8 text-center">
<p class="text-sm uppercase tracking-[0.18em] text-amare-accent">Erro 404</p>
<h1 class="text-4xl font-semibold text-amare-text">Página não encontrada</h1>
<p class="text-amare-text-muted">O endereço que você tentou abrir não existe ou foi movido.</p>
<p>
<a href="{{ route('home') }}" class="inline-flex rounded-md bg-amare-accent px-5 py-3 text-sm font-semibold text-amare-accent-text hover:bg-amare-accent-hover">
Voltar para a home
</a>
</p>
</div>
@endsection

View File

@@ -0,0 +1,14 @@
@extends('layouts.public')
@section('content')
<div class="container-amare max-w-2xl space-y-6 py-8 text-center">
<p class="text-sm uppercase tracking-[0.18em] text-amare-accent">Erro 500</p>
<h1 class="text-4xl font-semibold text-amare-text">Algo deu errado</h1>
<p class="text-amare-text-muted">Não foi possível concluir o pedido agora. Tente novamente em instantes.</p>
<p>
<a href="{{ route('home') }}" class="inline-flex rounded-md bg-amare-accent px-5 py-3 text-sm font-semibold text-amare-accent-text hover:bg-amare-accent-hover">
Voltar para a home
</a>
</p>
</div>
@endsection

View File

@@ -5,8 +5,10 @@
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light"> <meta name="color-scheme" content="light">
<title>@yield('title', config('app.name'))</title> <title>{{ $pageMeta->title }}</title>
<x-seo.meta :page-meta="$pageMeta" />
<x-fonts />
@vite(['resources/css/app.css', 'resources/js/app.js']) @vite(['resources/css/app.css', 'resources/js/app.js'])
</head> </head>
<body class="min-h-screen antialiased"> <body class="min-h-screen antialiased">
@@ -15,10 +17,18 @@
</a> </a>
<header class="border-b border-amare-border bg-amare-bg"> <header class="border-b border-amare-border bg-amare-bg">
<div class="container-amare flex items-center justify-between py-4"> <div class="container-amare flex items-center justify-between gap-6 py-4">
<a href="{{ url('/') }}" class="text-lg font-semibold text-amare-text transition-colors duration-(--amare-duration-normal) ease-(--amare-ease-standard) hover:text-amare-accent"> <a href="{{ url('/') }}" class="text-lg font-semibold text-amare-text transition-colors duration-(--amare-duration-normal) ease-(--amare-ease-standard) hover:text-amare-accent">
{{ config('app.name') }} {{ $siteSettings->brand_name }}
</a> </a>
<nav aria-label="Principal" class="flex flex-wrap items-center gap-4 text-sm text-amare-text-muted">
<a href="{{ route('home') }}" class="transition-colors hover:text-amare-accent">Início</a>
<a href="{{ route('services.index') }}" class="transition-colors hover:text-amare-accent">Serviços</a>
<a href="{{ route('portfolio.index') }}" class="transition-colors hover:text-amare-accent">Portfólio</a>
<a href="{{ route('about') }}" class="transition-colors hover:text-amare-accent">Sobre</a>
<a href="{{ route('contact') }}" class="transition-colors hover:text-amare-accent">Contato</a>
</nav>
</div> </div>
</header> </header>
@@ -27,9 +37,40 @@
</main> </main>
<footer class="border-t border-amare-border bg-amare-bg-muted"> <footer class="border-t border-amare-border bg-amare-bg-muted">
<div class="container-amare py-8 text-sm text-amare-text-muted"> <div class="container-amare flex flex-col gap-4 py-8 text-sm text-amare-text-muted md:flex-row md:items-start md:justify-between">
<p>&copy; {{ now()->year }} {{ config('app.name') }}. Todos os direitos reservados.</p> <div class="space-y-2">
<p class="font-medium text-amare-text">{{ $siteSettings->brand_name }}</p>
@if ($siteSettings->email)
<p>
<a href="mailto:{{ $siteSettings->email }}" class="transition-colors hover:text-amare-accent">{{ $siteSettings->email }}</a>
</p>
@endif
@if ($siteSettings->phone)
<p>{{ $siteSettings->phone }}</p>
@endif
@if ($siteSettings->city)
<p>{{ $siteSettings->city }}</p>
@endif
</div>
<div class="space-y-2">
<p class="font-medium text-amare-text">Links</p>
<p><a href="{{ route('privacy') }}" class="transition-colors hover:text-amare-accent">Política de privacidade</a></p>
@foreach ($siteSettings->social_links ?? [] as $network => $url)
@if (filled($url))
<p>
<a href="{{ $url }}" class="transition-colors hover:text-amare-accent" rel="noopener noreferrer" target="_blank">{{ ucfirst((string) $network) }}</a>
</p>
@endif
@endforeach
</div>
<p>&copy; {{ now()->year }} {{ $siteSettings->brand_name }}. Todos os direitos reservados.</p>
</div> </div>
</footer> </footer>
@if ($siteSettings->analytics_enabled && filled($siteSettings->analytics_script))
{!! $siteSettings->analytics_script !!}
@endif
</body> </body>
</html> </html>

View File

@@ -0,0 +1,12 @@
@extends('layouts.public')
@section('content')
<div class="container-amare max-w-3xl space-y-6">
<h1 class="text-4xl font-semibold text-amare-text">Sobre</h1>
<p class="text-lg text-amare-text-muted">{{ $siteSettings->about_summary }}</p>
<p class="text-amare-text-muted">
A {{ $siteSettings->brand_name }} atua em {{ $siteSettings->city }} com foco em planejamento completo,
presença no dia do evento e uma condução serena do início ao fim.
</p>
</div>
@endsection

View File

@@ -0,0 +1,28 @@
@extends('layouts.public')
@section('content')
<div class="container-amare space-y-6">
<h1 class="text-4xl font-semibold text-amare-text">Contato</h1>
<p class="max-w-2xl text-amare-text-muted">
Em breve você poderá enviar um briefing por aqui. Enquanto isso, fale conosco pelos canais abaixo.
</p>
<div class="space-y-2 text-amare-text-muted">
@if ($siteSettings->email)
<p><a href="mailto:{{ $siteSettings->email }}" class="text-amare-accent hover:text-amare-accent-hover">{{ $siteSettings->email }}</a></p>
@endif
@if ($siteSettings->phone)
<p>{{ $siteSettings->phone }}</p>
@endif
@if ($siteSettings->city)
<p>{{ $siteSettings->city }}</p>
@endif
@foreach ($siteSettings->social_links ?? [] as $network => $url)
@if (filled($url))
<p>
<a href="{{ $url }}" class="text-amare-accent hover:text-amare-accent-hover" rel="noopener noreferrer" target="_blank">{{ ucfirst((string) $network) }}</a>
</p>
@endif
@endforeach
</div>
</div>
@endsection

View File

@@ -1,20 +1,11 @@
@extends('layouts.public') @extends('layouts.public')
@section('title', config('app.name'))
@section('content') @section('content')
<div class="container-amare"> <x-home.hero :settings="$content->settings" />
<section class="rounded-xl border border-amare-border bg-amare-bg-muted p-8 shadow-amare-md"> <x-home.proof :cases="$content->featuredCases" />
<p class="mb-3 text-sm font-medium uppercase tracking-wide text-amare-accent">Assessoria de eventos</p> <x-home.services :services="$content->featuredServices" />
<h1 class="mb-4 text-4xl font-semibold text-amare-text">Em breve</h1> <x-home.method :settings="$content->settings" />
<p class="max-w-2xl text-lg text-amare-text-muted"> <x-home.cases :cases="$content->featuredCases" />
Estamos preparando a nova presença digital da assessoria. Em breve você poderá conhecer nossos serviços e solicitar um briefing. <x-home.testimonials :testimonials="$content->testimonials" />
</p> <x-home.final-cta :settings="$content->settings" />
<div class="mt-8">
<span class="inline-flex items-center rounded-full border border-amare-border bg-amare-bg px-4 py-2 text-sm text-amare-text">
Fase 0 Fundação concluída
</span>
</div>
</section>
</div>
@endsection @endsection

View File

@@ -0,0 +1,39 @@
@extends('layouts.public')
@section('content')
<div class="container-amare space-y-10">
<div class="max-w-2xl space-y-3">
<h1 class="text-4xl font-semibold text-amare-text">Portfólio</h1>
<p class="text-lg text-amare-text-muted">Casos reais de celebrações conduzidas com atenção a cada detalhe.</p>
</div>
@if ($cases->isEmpty())
<p class="text-amare-text-muted">Em breve publicaremos novos casos.</p>
@else
<div class="grid gap-8 md:grid-cols-2 lg:grid-cols-3">
@foreach ($cases as $case)
<article class="space-y-3">
@if (filled($case->cover_image_path))
<a href="{{ route('portfolio.show', $case->slug) }}">
<x-media.image
:path="$case->cover_image_path"
:alt="$case->cover_image_alt ?: $case->title"
sizes="(max-width: 768px) 100vw, 33vw"
class="aspect-[4/3] w-full object-cover"
/>
</a>
@endif
<h2 class="text-xl font-semibold text-amare-text">
<a href="{{ route('portfolio.show', $case->slug) }}" class="hover:text-amare-accent">{{ $case->title }}</a>
</h2>
<p class="text-sm text-amare-text-muted">{{ $case->summary }}</p>
</article>
@endforeach
</div>
<div>
{{ $cases->links() }}
</div>
@endif
</div>
@endsection

View File

@@ -0,0 +1,64 @@
@extends('layouts.public')
@section('content')
<article class="container-amare space-y-10">
<header class="max-w-3xl space-y-4">
<p class="text-sm uppercase tracking-[0.18em] text-amare-accent">{{ $case->event_type }}</p>
<h1 class="text-4xl font-semibold text-amare-text">{{ $case->title }}</h1>
<p class="text-lg text-amare-text-muted">{{ $case->summary }}</p>
<p class="text-sm text-amare-text-muted">
@if ($case->city){{ $case->city }}@endif
@if ($case->venue) · {{ $case->venue }}@endif
@if ($case->event_date) · {{ $case->event_date->format('d/m/Y') }}@endif
</p>
</header>
@if (filled($case->cover_image_path))
<x-media.image
:path="$case->cover_image_path"
:alt="$case->cover_image_alt ?: $case->title"
loading="eager"
sizes="(max-width: 1024px) 100vw, 72rem"
class="aspect-[16/9] w-full object-cover"
/>
@endif
<div class="grid gap-8 md:grid-cols-3">
<section class="space-y-2">
<h2 class="text-xl font-semibold text-amare-text">Desafio</h2>
<p class="text-amare-text-muted">{!! nl2br(e($case->challenge)) !!}</p>
</section>
<section class="space-y-2">
<h2 class="text-xl font-semibold text-amare-text">Solução</h2>
<p class="text-amare-text-muted">{!! nl2br(e($case->solution)) !!}</p>
</section>
@if (filled($case->result))
<section class="space-y-2">
<h2 class="text-xl font-semibold text-amare-text">Resultado</h2>
<p class="text-amare-text-muted">{!! nl2br(e($case->result)) !!}</p>
</section>
@endif
</div>
@if ($case->images->isNotEmpty())
<section aria-labelledby="gallery-heading" class="space-y-6">
<h2 id="gallery-heading" class="text-2xl font-semibold text-amare-text">Galeria</h2>
<div class="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
@foreach ($case->images as $image)
<figure class="space-y-2">
<x-media.image
:path="$image->path"
:alt="$image->alt_text"
sizes="(max-width: 768px) 100vw, 33vw"
class="aspect-square w-full object-cover"
/>
@if (filled($image->caption))
<figcaption class="text-sm text-amare-text-muted">{{ $image->caption }}</figcaption>
@endif
</figure>
@endforeach
</div>
</section>
@endif
</article>
@endsection

View File

@@ -0,0 +1,15 @@
@extends('layouts.public')
@section('content')
<div class="container-amare max-w-3xl space-y-6">
<h1 class="text-4xl font-semibold text-amare-text">Política de privacidade</h1>
<p class="text-amare-text-muted">
A {{ $siteSettings->brand_name }} trata dados pessoais com responsabilidade e somente para finalidades
relacionadas ao atendimento de interessados e à operação do site.
</p>
<p class="text-amare-text-muted">
Para dúvidas sobre privacidade, escreva para
<a href="mailto:{{ $siteSettings->email }}" class="text-amare-accent hover:text-amare-accent-hover">{{ $siteSettings->email }}</a>.
</p>
</div>
@endsection

View File

@@ -0,0 +1,36 @@
@extends('layouts.public')
@section('content')
<div class="container-amare space-y-10">
<div class="max-w-2xl space-y-3">
<h1 class="text-4xl font-semibold text-amare-text">Serviços</h1>
<p class="text-lg text-amare-text-muted">Assessoria completa para casamentos e eventos corporativos.</p>
</div>
@if ($services->isEmpty())
<p class="text-amare-text-muted">Em breve publicaremos o catálogo de serviços.</p>
@else
<div class="grid gap-8 md:grid-cols-2">
@foreach ($services as $service)
<article class="space-y-3 border-t border-amare-border pt-6">
@if (filled($service->cover_image_path))
<x-media.image
:path="$service->cover_image_path"
:alt="$service->cover_image_alt ?: $service->title"
sizes="(max-width: 768px) 100vw, 50vw"
class="aspect-[16/10] w-full object-cover"
/>
@endif
<h2 class="text-2xl font-semibold text-amare-text">{{ $service->title }}</h2>
<p class="text-amare-text-muted">{{ $service->summary }}</p>
@if (filled($service->description))
<div class="prose prose-amare max-w-none text-amare-text-muted">
{!! nl2br(e($service->description)) !!}
</div>
@endif
</article>
@endforeach
</div>
@endif
</div>
@endsection

View File

@@ -0,0 +1,11 @@
{!! '<'.'?xml version="1.0" encoding="UTF-8"?>' !!}
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
@foreach ($entries as $entry)
<url>
<loc>{{ $entry['loc'] }}</loc>
@if (! empty($entry['lastmod']))
<lastmod>{{ $entry['lastmod'] }}</lastmod>
@endif
</url>
@endforeach
</urlset>

View File

@@ -2,6 +2,21 @@
declare(strict_types=1); declare(strict_types=1);
use App\Http\Controllers\PublicSite\HomeController;
use App\Http\Controllers\PublicSite\PageController;
use App\Http\Controllers\PublicSite\PortfolioController;
use App\Http\Controllers\PublicSite\RobotsController;
use App\Http\Controllers\PublicSite\ServiceController;
use App\Http\Controllers\PublicSite\SitemapController;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
Route::view('/', 'pages.home')->name('home'); Route::get('/', HomeController::class)->name('home');
Route::get('/servicos', [ServiceController::class, 'index'])->name('services.index');
Route::get('/portfolio', [PortfolioController::class, 'index'])->name('portfolio.index');
Route::get('/portfolio/{slug}', [PortfolioController::class, 'show'])->name('portfolio.show');
Route::get('/sobre', [PageController::class, 'about'])->name('about');
Route::get('/privacidade', [PageController::class, 'privacy'])->name('privacy');
Route::get('/contato', [PageController::class, 'contact'])->name('contact');
Route::get('/sitemap.xml', SitemapController::class)->name('sitemap');
Route::get('/robots.txt', RobotsController::class)->name('robots');

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
use App\Models\PortfolioCase;
use App\Models\SiteSetting;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function (): void {
SiteSetting::instance();
});
it('has no critical or serious accessibility issues on covered public routes', function (): void {
$case = PortfolioCase::factory()->published()->create([
'slug' => 'casamento-jardim',
'title' => 'Casamento Jardim',
]);
$routes = [
'/',
'/servicos',
'/portfolio',
'/portfolio/'.$case->slug,
];
foreach ($routes as $route) {
$this->visit($route)
->assertNoAccessibilityIssues(1);
}
});
it('reaches the primary CTA by keyboard and activates it', function (): void {
$page = $this->visit('/');
$page->script('() => document.querySelector(\'a[href="#conteudo"]\')?.focus()');
$reachedCta = false;
for ($i = 0; $i < 30; $i++) {
$testId = $page->script('() => document.activeElement?.getAttribute("data-testid")');
if ($testId === 'home-primary-cta') {
$reachedCta = true;
break;
}
$page->keys(':focus', 'Tab');
}
expect($reachedCta)->toBeTrue();
$outlineStyle = $page->script('() => getComputedStyle(document.activeElement).outlineStyle');
expect($outlineStyle)->not->toBe('none');
$page->keys('[data-testid="home-primary-cta"]', 'Enter')
->assertPathIs('/contato');
});
it('loads covered public routes without console errors', function (): void {
$case = PortfolioCase::factory()->published()->create([
'slug' => 'casamento-jardim',
]);
foreach (['/', '/servicos', '/portfolio', '/portfolio/'.$case->slug] as $route) {
$this->visit($route)
->assertNoJavaScriptErrors();
}
});
it('disables transitions when prefers-reduced-motion is reduce', function (): void {
$page = $this->visit('/', [
'reducedMotion' => 'reduce',
]);
$duration = $page->script(<<<'JS'
() => {
const probe = document.createElement('div');
probe.style.transition = 'opacity var(--amare-duration-normal) ease';
document.body.appendChild(probe);
const value = getComputedStyle(probe).transitionDuration;
probe.remove();
return value;
}
JS);
expect((float) $duration)->toBeLessThan(0.02);
});

View File

@@ -2,10 +2,14 @@
declare(strict_types=1); declare(strict_types=1);
use App\Models\SiteSetting;
it('renders the public home page', function (): void { it('renders the public home page', function (): void {
$settings = SiteSetting::instance();
$this->visit('/') $this->visit('/')
->assertSee('Em breve') ->assertSee($settings->hero_title)
->assertSee(config('app.name')); ->assertSee($settings->brand_name);
}); });
it('renders the admin login page', function (): void { it('renders the admin login page', function (): void {

View File

@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
use App\Models\SiteSetting;
use Database\Seeders\VisualContentSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Artisan;
uses(RefreshDatabase::class);
beforeEach(function (): void {
putenv('APP_FROZEN_NOW='.VisualContentSeeder::FROZEN_NOW);
$_ENV['APP_FROZEN_NOW'] = VisualContentSeeder::FROZEN_NOW;
$_SERVER['APP_FROZEN_NOW'] = VisualContentSeeder::FROZEN_NOW;
$this->refreshApplication();
Artisan::call('db:seed', ['--class' => VisualContentSeeder::class, '--force' => true]);
SiteSetting::instance();
});
afterEach(function (): void {
putenv('APP_FROZEN_NOW');
unset($_ENV['APP_FROZEN_NOW'], $_SERVER['APP_FROZEN_NOW']);
});
$screens = [
'home' => '/',
'services' => '/servicos',
'portfolio' => '/portfolio',
'portfolio-detail' => '/portfolio/casamento-ana-lucas',
];
$viewports = [
'desktop' => [1440, 1000],
'mobile' => [390, 844],
];
foreach ($screens as $screen => $path) {
foreach ($viewports as $viewport => [$width, $height]) {
it("matches {$screen} {$viewport} visual baseline", function () use ($path, $width, $height): void {
$this->visit($path, [
'reducedMotion' => 'reduce',
])
->withLocale('pt-BR')
->withTimezone('America/Fortaleza')
->resize($width, $height)
->assertScreenshotMatches();
});
}
}

View File

@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Application\Queries\Marketing;
use App\Application\Queries\Marketing\FindPublishedPortfolioCaseBySlug;
use App\Models\PortfolioCase;
use App\Models\PortfolioImage;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class FindPublishedPortfolioCaseBySlugTest extends TestCase
{
use RefreshDatabase;
public function test_returns_published_case_with_images_and_null_for_draft(): void
{
$published = PortfolioCase::factory()->published()->create([
'slug' => 'casamento-jardim',
]);
PortfolioImage::query()->create([
'portfolio_case_id' => $published->id,
'path' => 'content/gallery.jpg',
'alt_text' => 'Galeria',
'caption' => null,
'sort_order' => 1,
]);
PortfolioCase::factory()->create([
'slug' => 'rascunho-interno',
'published_at' => null,
]);
$found = (new FindPublishedPortfolioCaseBySlug)('casamento-jardim');
$draft = (new FindPublishedPortfolioCaseBySlug)('rascunho-interno');
$missing = (new FindPublishedPortfolioCaseBySlug)('inexistente');
$this->assertNotNull($found);
$this->assertTrue($found->is($published));
$this->assertTrue($found->relationLoaded('images'));
$this->assertCount(1, $found->images);
$this->assertNull($draft);
$this->assertNull($missing);
}
}

View File

@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Application\Queries\Marketing;
use App\Application\Queries\Marketing\GetHomeContent;
use App\Models\PortfolioCase;
use App\Models\Service;
use App\Models\SiteSetting;
use App\Models\Testimonial;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class GetHomeContentTest extends TestCase
{
use RefreshDatabase;
public function test_returns_settings_featured_published_content_in_sort_order(): void
{
$settings = SiteSetting::instance();
Service::factory()->create(['title' => 'Draft Service', 'is_featured' => true, 'published_at' => null]);
Service::factory()->published()->create(['title' => 'Published Not Featured', 'is_featured' => false, 'sort_order' => 1]);
$serviceB = Service::factory()->published()->featured()->create(['title' => 'Featured B', 'sort_order' => 20]);
$serviceA = Service::factory()->published()->featured()->create(['title' => 'Featured A', 'sort_order' => 10]);
PortfolioCase::factory()->create(['title' => 'Draft Case', 'is_featured' => true, 'published_at' => null]);
$caseB = PortfolioCase::factory()->published()->create(['title' => 'Case B', 'is_featured' => true, 'sort_order' => 20]);
$caseA = PortfolioCase::factory()->published()->create(['title' => 'Case A', 'is_featured' => true, 'sort_order' => 10]);
Testimonial::factory()->create(['author_name' => 'Draft Author', 'published_at' => null]);
$testimonialB = Testimonial::factory()->published()->create(['author_name' => 'Author B', 'sort_order' => 20]);
$testimonialA = Testimonial::factory()->published()->create(['author_name' => 'Author A', 'sort_order' => 10]);
$content = (new GetHomeContent)();
$this->assertTrue($content->settings->is($settings));
$this->assertCount(2, $content->featuredServices);
$this->assertTrue($content->featuredServices->get(0)?->is($serviceA));
$this->assertTrue($content->featuredServices->get(1)?->is($serviceB));
$this->assertCount(2, $content->featuredCases);
$this->assertTrue($content->featuredCases->get(0)?->is($caseA));
$this->assertTrue($content->featuredCases->get(1)?->is($caseB));
$this->assertTrue($content->featuredCases->get(0)?->relationLoaded('images'));
$this->assertCount(2, $content->testimonials);
$this->assertTrue($content->testimonials->get(0)?->is($testimonialA));
$this->assertTrue($content->testimonials->get(1)?->is($testimonialB));
}
}

View File

@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Application\Queries\Marketing;
use App\Application\Queries\Marketing\GetPublishedPortfolioCases;
use App\Models\PortfolioCase;
use App\Models\PortfolioImage;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class GetPublishedPortfolioCasesTest extends TestCase
{
use RefreshDatabase;
public function test_excludes_drafts_orders_by_sort_order_and_eager_loads_images(): void
{
PortfolioCase::factory()->create([
'title' => 'Draft Case',
'sort_order' => 1,
'published_at' => null,
]);
$second = PortfolioCase::factory()->published()->create([
'title' => 'Second Case',
'sort_order' => 20,
]);
$first = PortfolioCase::factory()->published()->create([
'title' => 'First Case',
'sort_order' => 10,
]);
PortfolioImage::query()->create([
'portfolio_case_id' => $first->id,
'path' => 'content/first-a.jpg',
'alt_text' => 'First A',
'caption' => null,
'sort_order' => 1,
]);
PortfolioImage::query()->create([
'portfolio_case_id' => $first->id,
'path' => 'content/first-b.jpg',
'alt_text' => 'First B',
'caption' => null,
'sort_order' => 2,
]);
$cases = (new GetPublishedPortfolioCases)();
$this->assertCount(2, $cases);
$this->assertTrue($cases->get(0)?->is($first));
$this->assertTrue($cases->get(1)?->is($second));
$this->assertFalse($cases->contains(fn (PortfolioCase $case): bool => $case->title === 'Draft Case'));
$this->assertTrue($cases->get(0)?->relationLoaded('images'));
$this->assertCount(2, $cases->get(0)?->images ?? []);
}
}

View File

@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Application\Queries\Marketing;
use App\Application\Queries\Marketing\GetPublishedServices;
use App\Models\Service;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class GetPublishedServicesTest extends TestCase
{
use RefreshDatabase;
public function test_excludes_draft_services_and_orders_by_sort_order(): void
{
Service::factory()->create([
'title' => 'Draft Service',
'sort_order' => 1,
'published_at' => null,
]);
$second = Service::factory()->published()->create([
'title' => 'Second Published',
'sort_order' => 20,
]);
$first = Service::factory()->published()->create([
'title' => 'First Published',
'sort_order' => 10,
]);
$services = (new GetPublishedServices)();
$this->assertCount(2, $services);
$this->assertTrue($services->get(0)?->is($first));
$this->assertTrue($services->get(1)?->is($second));
$this->assertFalse($services->contains(fn (Service $service): bool => $service->title === 'Draft Service'));
}
}

View File

@@ -4,17 +4,23 @@ declare(strict_types=1);
namespace Tests\Feature; namespace Tests\Feature;
use App\Models\SiteSetting;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase; use Tests\TestCase;
class HomePageTest extends TestCase class HomePageTest extends TestCase
{ {
use RefreshDatabase;
public function test_home_page_renders_successfully(): void public function test_home_page_renders_successfully(): void
{ {
$settings = SiteSetting::instance();
$response = $this->get('/'); $response = $this->get('/');
$response $response
->assertOk() ->assertOk()
->assertSee('Em breve') ->assertSee($settings->hero_title)
->assertSee(config('app.name')); ->assertSee($settings->brand_name);
} }
} }

View File

@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Marketing;
use App\Filament\Pages\ManageSiteSettings;
use App\Models\SiteSetting;
use App\Models\User;
use App\Support\ResponsiveImage;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Livewire\Livewire;
use Tests\TestCase;
class ResponsiveImageUploadTest extends TestCase
{
use RefreshDatabase;
public function test_cms_upload_generates_responsive_variants(): void
{
Storage::fake('public');
$admin = User::factory()->admin()->create();
SiteSetting::instance();
$this->actingAs($admin);
Livewire::test(ManageSiteSettings::class)
->set('data.default_og_image_path', [
UploadedFile::fake()->image('og-image.jpg', 1600, 900),
])
->set('data.default_og_image_alt', 'Casal celebrando com a equipe Amare')
->call('save')
->assertHasNoFormErrors();
$path = SiteSetting::instance()->refresh()->default_og_image_path;
$this->assertNotNull($path);
Storage::disk('public')->assertExists($path);
foreach (ResponsiveImage::WIDTHS as $width) {
Storage::disk('public')->assertExists(ResponsiveImage::variantPath($path, $width));
}
}
}

View File

@@ -66,7 +66,7 @@ class SiteSettingsTest extends TestCase
Livewire::test(ManageSiteSettings::class) Livewire::test(ManageSiteSettings::class)
->set('data.default_og_image_path', [ ->set('data.default_og_image_path', [
UploadedFile::fake()->create('og-image.jpg', 512, 'image/jpeg'), UploadedFile::fake()->image('og-image.jpg', 1200, 800),
]) ])
->set('data.default_og_image_alt', 'Casal celebrando com a equipe Amare') ->set('data.default_og_image_alt', 'Casal celebrando com a equipe Amare')
->call('save') ->call('save')
@@ -90,7 +90,7 @@ class SiteSettingsTest extends TestCase
Livewire::test(ManageSiteSettings::class) Livewire::test(ManageSiteSettings::class)
->set('data.default_og_image_path', [ ->set('data.default_og_image_path', [
UploadedFile::fake()->create('og-image.jpg', 512, 'image/jpeg'), UploadedFile::fake()->image('og-image.jpg', 800, 600),
]) ])
->set('data.default_og_image_alt', null) ->set('data.default_og_image_alt', null)
->call('save') ->call('save')

View File

@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace Tests\Feature;
use App\Models\Service;
use App\Support\ResponsiveImage;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\ImageManager;
use Tests\TestCase;
class MediaGenerateVariantsCommandTest extends TestCase
{
use RefreshDatabase;
public function test_command_backfills_variants_for_existing_images(): void
{
Storage::fake('public');
$manager = new ImageManager(new Driver);
$path = 'content/services/backfill.jpg';
Storage::disk('public')->put($path, (string) $manager->create(1400, 900)->toJpeg());
Service::factory()->published()->create([
'cover_image_path' => $path,
]);
$exitCode = Artisan::call('media:generate-variants');
$this->assertSame(0, $exitCode);
foreach (ResponsiveImage::WIDTHS as $width) {
Storage::disk('public')->assertExists(ResponsiveImage::variantPath($path, $width));
}
}
}

View File

@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\PublicSite;
use App\Models\PortfolioCase;
use App\Models\PortfolioImage;
use App\Models\SiteSetting;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
class AccessibilityStructureTest extends TestCase
{
use RefreshDatabase;
public function test_public_pages_have_single_h1_and_landmarks(): void
{
Storage::fake('public');
SiteSetting::instance();
$case = PortfolioCase::factory()->published()->create([
'slug' => 'casamento-jardim',
'title' => 'Casamento Jardim',
'cover_image_path' => 'cases/cover.jpg',
'cover_image_alt' => 'Capa do casamento',
]);
$routes = [
route('home'),
route('services.index'),
route('portfolio.index'),
route('portfolio.show', $case->slug),
route('about'),
route('privacy'),
route('contact'),
];
foreach ($routes as $url) {
$html = $this->get($url)->assertOk()->getContent();
$this->assertSame(1, preg_match_all('/<h1\b/i', $html), "Expected one h1 on {$url}");
$this->assertMatchesRegularExpression('/<header\b/i', $html);
$this->assertMatchesRegularExpression('/<nav\b/i', $html);
$this->assertMatchesRegularExpression('/<main\b/i', $html);
$this->assertMatchesRegularExpression('/<footer\b/i', $html);
$this->assertStringContainsString('href="#conteudo"', $html);
}
}
public function test_content_images_expose_alt_text(): void
{
Storage::fake('public');
SiteSetting::instance();
$case = PortfolioCase::factory()->published()->create([
'slug' => 'casamento-jardim',
'title' => 'Casamento Jardim',
'cover_image_path' => 'cases/cover.jpg',
'cover_image_alt' => 'Capa do casamento',
]);
PortfolioImage::query()->create([
'portfolio_case_id' => $case->id,
'path' => 'content/gallery-a.jpg',
'alt_text' => 'Galeria A',
'caption' => null,
'sort_order' => 1,
]);
$this->get(route('portfolio.show', $case->slug))
->assertOk()
->assertSee('alt="Capa do casamento"', false)
->assertSee('alt="Galeria A"', false);
}
public function test_interactive_elements_have_visible_focus_styles(): void
{
$css = file_get_contents(resource_path('css/app.css'));
$this->assertIsString($css);
$this->assertStringContainsString(':focus-visible', $css);
$this->assertStringContainsString('outline', $css);
}
}

View File

@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\PublicSite;
use App\Models\SiteSetting;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class AnalyticsSnippetTest extends TestCase
{
use RefreshDatabase;
public function test_analytics_snippet_is_absent_when_disabled(): void
{
SiteSetting::instance()->update([
'analytics_enabled' => false,
'analytics_script' => '<script data-analytics="amare">console.log("track")</script>',
]);
$this->get(route('home'))
->assertOk()
->assertDontSee('data-analytics="amare"', false)
->assertDontSee('console.log("track")', false);
}
public function test_analytics_snippet_is_injected_once_when_enabled(): void
{
SiteSetting::instance()->update([
'analytics_enabled' => true,
'analytics_script' => '<script data-analytics="amare">console.log("track")</script>',
]);
$html = $this->get(route('home'))->assertOk()->getContent();
$this->assertSame(1, substr_count($html, 'data-analytics="amare"'));
$this->assertSame(1, substr_count($html, 'console.log("track")'));
}
}

View File

@@ -0,0 +1,100 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\PublicSite;
use App\Models\PortfolioCase;
use App\Models\Service;
use App\Models\SiteSetting;
use App\Models\Testimonial;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class HomePageContentTest extends TestCase
{
use RefreshDatabase;
public function test_published_featured_content_appears_in_order_and_drafts_are_hidden(): void
{
$settings = SiteSetting::instance();
$settings->update([
'hero_title' => 'Celebrações com propósito',
'hero_cta_label' => 'Solicitar orçamento',
]);
Service::factory()->create([
'title' => 'Serviço Rascunho',
'is_featured' => true,
'published_at' => null,
]);
Service::factory()->published()->featured()->create([
'title' => 'Serviço B',
'sort_order' => 20,
]);
Service::factory()->published()->featured()->create([
'title' => 'Serviço A',
'sort_order' => 10,
]);
PortfolioCase::factory()->create([
'title' => 'Caso Rascunho',
'is_featured' => true,
'published_at' => null,
]);
PortfolioCase::factory()->published()->create([
'title' => 'Caso B',
'is_featured' => true,
'sort_order' => 20,
]);
PortfolioCase::factory()->published()->create([
'title' => 'Caso A',
'is_featured' => true,
'sort_order' => 10,
]);
Testimonial::factory()->create([
'author_name' => 'Autor Rascunho',
'published_at' => null,
]);
Testimonial::factory()->published()->create([
'author_name' => 'Autor B',
'quote' => 'Depoimento B',
'sort_order' => 20,
]);
Testimonial::factory()->published()->create([
'author_name' => 'Autor A',
'quote' => 'Depoimento A',
'sort_order' => 10,
]);
$response = $this->get(route('home'));
$response
->assertOk()
->assertSee('Celebrações com propósito')
->assertSeeInOrder(['Serviço A', 'Serviço B'])
->assertSeeInOrder(['Caso A', 'Caso B'])
->assertSeeInOrder(['Autor A', 'Autor B'])
->assertDontSee('Serviço Rascunho')
->assertDontSee('Caso Rascunho')
->assertDontSee('Autor Rascunho')
->assertSee('href="'.route('contact').'"', false);
}
public function test_empty_sections_are_omitted_when_no_published_content(): void
{
SiteSetting::instance();
$response = $this->get(route('home'));
$response
->assertOk()
->assertDontSee('id="services-heading"', false)
->assertDontSee('id="proof-heading"', false)
->assertDontSee('id="cases-heading"', false)
->assertDontSee('id="testimonials-heading"', false)
->assertSee('id="method-heading"', false)
->assertSee('id="final-cta-heading"', false);
}
}

View File

@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\PublicSite;
use App\Support\ResponsiveImage;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\ImageManager;
use Tests\TestCase;
class MediaImageComponentTest extends TestCase
{
public function test_hero_image_is_eager_and_below_fold_is_lazy_with_srcset(): void
{
Storage::fake('public');
$manager = new ImageManager(new Driver);
Storage::disk('public')->put('content/hero.jpg', (string) $manager->create(1600, 900)->toJpeg());
ResponsiveImage::generate('content/hero.jpg', 'public');
Storage::disk('public')->put('content/below.jpg', (string) $manager->create(1200, 800)->toJpeg());
ResponsiveImage::generate('content/below.jpg', 'public');
$hero = Blade::render(
'<x-media.image path="content/hero.jpg" alt="Hero Amare" loading="eager" sizes="100vw" />'
);
$below = Blade::render(
'<x-media.image path="content/below.jpg" alt="Galeria" loading="lazy" />'
);
$this->assertStringContainsString('loading="eager"', $hero);
$this->assertStringNotContainsString('loading="lazy"', $hero);
$this->assertStringContainsString('alt="Hero Amare"', $hero);
$this->assertStringContainsString('srcset=', $hero);
$this->assertStringContainsString('sizes="100vw"', $hero);
$this->assertStringContainsString('width="', $hero);
$this->assertStringContainsString('height="', $hero);
$this->assertStringContainsString('loading="lazy"', $below);
$this->assertStringContainsString('alt="Galeria"', $below);
$this->assertStringContainsString('srcset=', $below);
$this->assertStringContainsString('sizes="', $below);
}
public function test_missing_variants_fall_back_to_original_without_srcset(): void
{
Storage::fake('public');
$manager = new ImageManager(new Driver);
Storage::disk('public')->put('content/legacy.jpg', (string) $manager->create(800, 600)->toJpeg());
$html = Blade::render(
'<x-media.image path="content/legacy.jpg" alt="Legado" />'
);
$this->assertStringContainsString('alt="Legado"', $html);
$this->assertStringContainsString('loading="lazy"', $html);
$this->assertStringNotContainsString('srcset=', $html);
}
}

View File

@@ -0,0 +1,101 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\PublicSite;
use App\Models\PortfolioCase;
use App\Models\SiteSetting;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
class PageMetaRenderingTest extends TestCase
{
use RefreshDatabase;
public function test_case_meta_overrides_appear_in_rendered_head(): void
{
Storage::fake('public');
SiteSetting::instance()->update([
'default_meta_title' => 'Default Title',
'default_meta_description' => 'Default Description',
'default_og_image_path' => 'og/default.jpg',
'default_og_image_alt' => 'Default alt',
]);
$case = PortfolioCase::factory()->published()->create([
'slug' => 'casamento-jardim',
'title' => 'Casamento Jardim',
'summary' => 'Resumo do caso',
'meta_title' => 'Meta do Casamento',
'meta_description' => 'Descrição SEO do casamento',
'cover_image_path' => 'cases/cover.jpg',
'cover_image_alt' => 'Capa do casamento',
]);
$canonical = route('portfolio.show', $case->slug);
$this->get($canonical)
->assertOk()
->assertSee('<title>Meta do Casamento</title>', false)
->assertSee('content="Descrição SEO do casamento"', false)
->assertSee('href="'.$canonical.'"', false)
->assertSee('content="article"', false)
->assertSee(Storage::disk('public')->url('cases/cover.jpg'), false)
->assertSee('content="Capa do casamento"', false);
}
public function test_case_without_meta_falls_back_to_title_summary_and_site_og(): void
{
Storage::fake('public');
SiteSetting::instance()->update([
'default_meta_title' => 'Default Title',
'default_meta_description' => 'Default Description',
'default_og_image_path' => 'og/default.jpg',
'default_og_image_alt' => 'Default alt',
]);
$case = PortfolioCase::factory()->published()->create([
'slug' => 'casamento-praia',
'title' => 'Casamento Praia',
'summary' => 'Resumo praia',
'meta_title' => null,
'meta_description' => null,
'cover_image_path' => '',
'cover_image_alt' => '',
]);
$canonical = route('portfolio.show', $case->slug);
$this->get($canonical)
->assertOk()
->assertSee('<title>Casamento Praia</title>', false)
->assertSee('content="Resumo praia"', false)
->assertSee('href="'.$canonical.'"', false)
->assertSee(Storage::disk('public')->url('og/default.jpg'), false)
->assertSee('content="Default alt"', false);
}
public function test_institutional_page_falls_back_to_site_defaults_when_no_page_title_override_needed(): void
{
Storage::fake('public');
SiteSetting::instance()->update([
'default_meta_title' => 'Amare Assessoria de Eventos',
'default_meta_description' => 'Assessoria premium.',
'default_og_image_path' => 'og/default.jpg',
]);
$canonical = route('home');
$this->get($canonical)
->assertOk()
->assertSee('<title>Amare Assessoria de Eventos</title>', false)
->assertSee('content="Assessoria premium."', false)
->assertSee('href="'.$canonical.'"', false)
->assertSee(Storage::disk('public')->url('og/default.jpg'), false);
}
}

View File

@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\PublicSite;
use App\Models\SiteSetting;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
class PublicLayoutSeoTest extends TestCase
{
use RefreshDatabase;
public function test_public_layout_emits_seo_head_landmarks_and_site_settings_chrome(): void
{
Storage::fake('public');
$settings = SiteSetting::instance();
$settings->update([
'brand_name' => 'Amare Brand',
'email' => 'hello@amare.test',
'phone' => '(85) 91111-1111',
'city' => 'Fortaleza, CE',
'default_meta_title' => 'Titulo SEO Amare',
'default_meta_description' => 'Descricao SEO Amare',
'default_og_image_path' => 'og/default.jpg',
'default_og_image_alt' => 'Imagem OG Amare',
'social_links' => [
'instagram' => 'https://instagram.com/amare',
],
]);
$response = $this->get('/');
$response
->assertOk()
->assertSee('<title>Titulo SEO Amare</title>', false)
->assertSee('name="description"', false)
->assertSee('Descricao SEO Amare', false)
->assertSee('rel="canonical"', false)
->assertSee('property="og:title"', false)
->assertSee('property="og:description"', false)
->assertSee('property="og:type"', false)
->assertSee('property="og:url"', false)
->assertSee('property="og:image"', false)
->assertSee('property="og:image:alt"', false)
->assertSee('Imagem OG Amare', false)
->assertSee('<header', false)
->assertSee('<nav', false)
->assertSee('<main', false)
->assertSee('<footer', false)
->assertSee('Amare Brand')
->assertSee('hello@amare.test')
->assertSee('(85) 91111-1111')
->assertSee('Política de privacidade')
->assertSee('https://instagram.com/amare', false);
}
}

View File

@@ -0,0 +1,179 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\PublicSite;
use App\Models\PortfolioCase;
use App\Models\PortfolioImage;
use App\Models\Service;
use App\Models\SiteSetting;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use Tests\TestCase;
class PublicPagesTest extends TestCase
{
use RefreshDatabase;
public function test_services_index_lists_published_services_in_sort_order(): void
{
SiteSetting::instance();
Service::factory()->create(['title' => 'Rascunho', 'published_at' => null]);
Service::factory()->published()->create(['title' => 'Serviço B', 'sort_order' => 20]);
Service::factory()->published()->create(['title' => 'Serviço A', 'sort_order' => 10]);
$this->get(route('services.index'))
->assertOk()
->assertSeeInOrder(['Serviço A', 'Serviço B'])
->assertDontSee('Rascunho');
}
public function test_portfolio_index_paginates_and_excludes_drafts(): void
{
SiteSetting::instance();
PortfolioCase::factory()->create(['title' => 'Rascunho', 'published_at' => null]);
foreach (range(1, 10) as $index) {
PortfolioCase::factory()->published()->create([
'title' => 'Caso '.$index,
'slug' => 'caso-pagina-'.$index,
'sort_order' => $index,
]);
}
$this->assertSame(10, PortfolioCase::query()->published()->count());
$this->get(route('portfolio.index'))
->assertOk()
->assertSee('>Caso 1</', false)
->assertSee('>Caso 9</', false)
->assertDontSee('>Caso 10</', false)
->assertDontSee('Rascunho');
$this->get(route('portfolio.index', ['page' => 2]))
->assertOk()
->assertSee('>Caso 10</', false)
->assertDontSee('>Caso 9</', false);
}
public function test_portfolio_show_renders_published_case_gallery_order_and_404_for_draft(): void
{
SiteSetting::instance();
$published = PortfolioCase::factory()->published()->create([
'slug' => 'casamento-jardim',
'title' => 'Casamento Jardim',
'challenge' => 'Desafio do caso',
'solution' => 'Solução do caso',
'result' => 'Resultado do caso',
]);
PortfolioImage::query()->create([
'portfolio_case_id' => $published->id,
'path' => 'content/gallery-b.jpg',
'alt_text' => 'Imagem B',
'caption' => null,
'sort_order' => 2,
]);
PortfolioImage::query()->create([
'portfolio_case_id' => $published->id,
'path' => 'content/gallery-a.jpg',
'alt_text' => 'Imagem A',
'caption' => null,
'sort_order' => 1,
]);
PortfolioCase::factory()->create([
'slug' => 'rascunho',
'published_at' => null,
]);
$this->get(route('portfolio.show', 'casamento-jardim'))
->assertOk()
->assertSee('Casamento Jardim')
->assertSee('Desafio do caso')
->assertSee('Solução do caso')
->assertSee('Resultado do caso')
->assertSeeInOrder(['Imagem A', 'Imagem B']);
$this->get(route('portfolio.show', 'rascunho'))->assertNotFound();
}
public function test_about_privacy_and_contact_use_site_settings_without_creating_leads(): void
{
$settings = SiteSetting::instance();
$settings->update([
'about_summary' => 'Sobre a Amare boutique',
'email' => 'contato@amare.test',
'phone' => '(85) 90000-0000',
'social_links' => ['instagram' => 'https://instagram.com/amare'],
]);
$this->get(route('about'))
->assertOk()
->assertSee('Sobre a Amare boutique');
$this->get(route('privacy'))
->assertOk()
->assertSee('Política de privacidade')
->assertSee('contato@amare.test');
$this->get(route('contact'))
->assertOk()
->assertSee('contato@amare.test')
->assertSee('(85) 90000-0000')
->assertSee('https://instagram.com/amare', false);
}
public function test_branded_404_and_500_without_stack_trace_when_debug_disabled(): void
{
SiteSetting::instance();
$this->get('/rota-inexistente-amare')
->assertNotFound()
->assertSee('Página não encontrada')
->assertSee('Voltar para a home');
Route::get('/__test-server-error', function (): never {
throw new \RuntimeException('segredo-interno-amare');
});
config(['app.debug' => false]);
$response = $this->get('/__test-server-error');
$response
->assertStatus(500)
->assertSee('Algo deu errado')
->assertDontSee('segredo-interno-amare')
->assertDontSee('RuntimeException');
}
public function test_portfolio_show_avoids_n_plus_one_on_gallery(): void
{
SiteSetting::instance();
$case = PortfolioCase::factory()->published()->create(['slug' => 'caso-n1']);
foreach (range(1, 8) as $order) {
PortfolioImage::query()->create([
'portfolio_case_id' => $case->id,
'path' => "content/gallery-{$order}.jpg",
'alt_text' => "Imagem {$order}",
'caption' => null,
'sort_order' => $order,
]);
}
DB::enableQueryLog();
$this->get(route('portfolio.show', 'caso-n1'))->assertOk();
$queryCount = count(DB::getQueryLog());
DB::disableQueryLog();
$this->assertLessThan(15, $queryCount);
}
}

View File

@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
use App\Models\SiteSetting;
use Database\Seeders\VisualContentSeeder;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Storage;
it('exposes public disk urls as same-origin storage paths', function (): void {
expect(Storage::disk('public')->url('visual/og/og-default.jpg'))
->toStartWith('/storage/')
->not->toContain('http://localhost');
});
it('links seeded visual fixtures into public storage', function (): void {
Artisan::call('storage:link', ['--force' => true]);
Artisan::call('db:seed', ['--class' => VisualContentSeeder::class, '--force' => true]);
$settings = SiteSetting::instance();
$path = (string) $settings->default_og_image_path;
expect($path)->not->toBeEmpty()
->and(is_file(public_path('storage/'.$path)))->toBeTrue()
->and(mime_content_type(public_path('storage/'.$path)))->toBe('image/jpeg');
});
it('renders home media with same-origin storage urls', function (): void {
Artisan::call('db:seed', ['--class' => VisualContentSeeder::class, '--force' => true]);
$html = $this->get('/')->assertOk()->getContent();
expect($html)
->toContain('src="/storage/visual/')
->not->toContain('src="http://localhost/storage/');
});

View File

@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\PublicSite;
use App\Models\SiteSetting;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class RobotsTxtTest extends TestCase
{
use RefreshDatabase;
public function test_robots_txt_is_plain_text_and_references_absolute_sitemap(): void
{
SiteSetting::instance();
$response = $this->get('/robots.txt');
$response
->assertOk()
->assertHeader('Content-Type', 'text/plain; charset=UTF-8')
->assertSee('User-agent: *', false)
->assertSee('Sitemap: '.url('/sitemap.xml'), false);
}
}

View File

@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\PublicSite;
use App\Models\PortfolioCase;
use App\Models\SiteSetting;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class SitemapTest extends TestCase
{
use RefreshDatabase;
public function test_sitemap_includes_static_routes_and_only_published_cases(): void
{
SiteSetting::instance();
$published = PortfolioCase::factory()->published()->create([
'slug' => 'casamento-jardim',
'updated_at' => now()->subDay(),
]);
PortfolioCase::factory()->create([
'slug' => 'rascunho-secreto',
'published_at' => null,
]);
$response = $this->get('/sitemap.xml');
$response
->assertOk()
->assertHeader('Content-Type', 'application/xml')
->assertSee(route('home'), false)
->assertSee(route('services.index'), false)
->assertSee(route('portfolio.index'), false)
->assertSee(route('about'), false)
->assertSee(route('privacy'), false)
->assertSee(route('contact'), false)
->assertSee(route('portfolio.show', $published->slug), false)
->assertDontSee('rascunho-secreto', false);
}
public function test_newly_published_case_appears_in_sitemap(): void
{
SiteSetting::instance();
$case = PortfolioCase::factory()->create([
'slug' => 'novo-caso',
'published_at' => null,
]);
$this->get('/sitemap.xml')
->assertOk()
->assertDontSee(route('portfolio.show', $case->slug), false);
$case->update(['published_at' => now()]);
$this->get('/sitemap.xml')
->assertOk()
->assertSee(route('portfolio.show', $case->slug), false);
}
}

View File

@@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\PublicSite;
use App\Models\PortfolioCase;
use App\Models\SiteSetting;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class StructuredDataTest extends TestCase
{
use RefreshDatabase;
public function test_home_emits_parseable_organization_json_ld(): void
{
SiteSetting::instance()->update([
'brand_name' => 'Amare Brand',
'email' => 'hello@amare.test',
'phone' => '(85) 91111-1111',
'city' => 'Fortaleza, CE',
]);
$html = $this->get(route('home'))->assertOk()->getContent();
$jsonLd = $this->extractJsonLd($html);
$this->assertSame('Organization', $jsonLd['@type']);
$this->assertSame('Amare Brand', $jsonLd['name']);
$this->assertSame('hello@amare.test', $jsonLd['email']);
$this->assertSame('(85) 91111-1111', $jsonLd['telephone']);
$this->assertSame('Fortaleza, CE', $jsonLd['address']['addressLocality']);
}
public function test_portfolio_show_emits_parseable_article_json_ld(): void
{
SiteSetting::instance();
$case = PortfolioCase::factory()->published()->create([
'slug' => 'casamento-jardim',
'title' => 'Casamento Jardim',
'summary' => 'Resumo do caso',
'cover_image_path' => 'cases/cover.jpg',
]);
$html = $this->get(route('portfolio.show', $case->slug))->assertOk()->getContent();
$jsonLd = $this->extractJsonLd($html);
$this->assertContains($jsonLd['@type'], ['Article', 'CreativeWork']);
$this->assertSame('Casamento Jardim', $jsonLd['headline'] ?? $jsonLd['name']);
$this->assertSame('Resumo do caso', $jsonLd['description']);
$this->assertSame(route('portfolio.show', $case->slug), $jsonLd['url'] ?? $jsonLd['mainEntityOfPage']);
}
/**
* @return array<string, mixed>
*/
private function extractJsonLd(string $html): array
{
$this->assertMatchesRegularExpression(
'/<script type="application\/ld\+json">(.*?)<\/script>/s',
$html,
);
preg_match('/<script type="application\/ld\+json">(.*?)<\/script>/s', $html, $matches);
/** @var array<string, mixed> $decoded */
$decoded = json_decode($matches[1], true, flags: JSON_THROW_ON_ERROR);
return $decoded;
}
}

View File

@@ -0,0 +1,131 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Application\Data;
use App\Application\Data\PageMeta;
use App\Models\PortfolioCase;
use App\Models\SiteSetting;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
class PageMetaTest extends TestCase
{
public function test_for_page_falls_back_to_site_settings_defaults(): void
{
Storage::fake('public');
$settings = new SiteSetting([
'brand_name' => 'Amare Assessoria',
'default_meta_title' => 'Amare Assessoria de Eventos',
'default_meta_description' => 'Assessoria premium.',
'default_og_image_path' => 'og/default.jpg',
'default_og_image_alt' => 'Marca Amare',
]);
$meta = PageMeta::forPage(
canonical: 'https://amare.test/sobre',
settings: $settings,
);
$this->assertSame('Amare Assessoria de Eventos', $meta->title);
$this->assertSame('Assessoria premium.', $meta->description);
$this->assertSame('https://amare.test/sobre', $meta->canonical);
$this->assertSame('website', $meta->ogType);
$this->assertSame(url(Storage::disk('public')->url('og/default.jpg')), $meta->ogImageUrl);
$this->assertSame('Marca Amare', $meta->ogImageAlt);
}
public function test_for_page_uses_explicit_overrides_when_provided(): void
{
Storage::fake('public');
$settings = new SiteSetting([
'default_meta_title' => 'Default Title',
'default_meta_description' => 'Default Description',
'default_og_image_path' => 'og/default.jpg',
'default_og_image_alt' => 'Default alt',
]);
$meta = PageMeta::forPage(
canonical: 'https://amare.test/servicos',
settings: $settings,
title: 'Serviços',
description: 'Catálogo de serviços',
ogImageUrl: 'https://amare.test/storage/services/cover.jpg',
ogImageAlt: 'Capa serviços',
);
$this->assertSame('Serviços', $meta->title);
$this->assertSame('Catálogo de serviços', $meta->description);
$this->assertSame('https://amare.test/storage/services/cover.jpg', $meta->ogImageUrl);
$this->assertSame('Capa serviços', $meta->ogImageAlt);
}
public function test_for_case_prefers_case_meta_and_cover_over_defaults(): void
{
Storage::fake('public');
$settings = new SiteSetting([
'default_meta_title' => 'Default Title',
'default_meta_description' => 'Default Description',
'default_og_image_path' => 'og/default.jpg',
'default_og_image_alt' => 'Default alt',
]);
$case = new PortfolioCase([
'title' => 'Casamento Jardim',
'summary' => 'Resumo do caso',
'meta_title' => 'Meta do Casamento',
'meta_description' => 'Descrição SEO do casamento',
'cover_image_path' => 'cases/cover.jpg',
'cover_image_alt' => 'Capa do casamento',
]);
$meta = PageMeta::forCase(
case: $case,
canonical: 'https://amare.test/portfolio/casamento-jardim',
settings: $settings,
);
$this->assertSame('Meta do Casamento', $meta->title);
$this->assertSame('Descrição SEO do casamento', $meta->description);
$this->assertSame('https://amare.test/portfolio/casamento-jardim', $meta->canonical);
$this->assertSame('article', $meta->ogType);
$this->assertSame(url(Storage::disk('public')->url('cases/cover.jpg')), $meta->ogImageUrl);
$this->assertSame('Capa do casamento', $meta->ogImageAlt);
}
public function test_for_case_falls_back_to_title_summary_and_site_defaults(): void
{
Storage::fake('public');
$settings = new SiteSetting([
'default_meta_title' => 'Default Title',
'default_meta_description' => 'Default Description',
'default_og_image_path' => 'og/default.jpg',
'default_og_image_alt' => 'Default alt',
]);
$case = new PortfolioCase([
'title' => 'Casamento Praia',
'summary' => 'Resumo praia',
'meta_title' => null,
'meta_description' => null,
'cover_image_path' => null,
'cover_image_alt' => null,
]);
$meta = PageMeta::forCase(
case: $case,
canonical: 'https://amare.test/portfolio/casamento-praia',
settings: $settings,
);
$this->assertSame('Casamento Praia', $meta->title);
$this->assertSame('Resumo praia', $meta->description);
$this->assertSame(url(Storage::disk('public')->url('og/default.jpg')), $meta->ogImageUrl);
$this->assertSame('Default alt', $meta->ogImageAlt);
}
}

View File

@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace Tests\Unit;
use Carbon\CarbonImmutable;
use Tests\TestCase;
class FrozenNowProviderTest extends TestCase
{
protected function tearDown(): void
{
putenv('APP_FROZEN_NOW');
unset($_ENV['APP_FROZEN_NOW'], $_SERVER['APP_FROZEN_NOW']);
CarbonImmutable::setTestNow();
parent::tearDown();
}
public function test_app_frozen_now_freezes_clock_outside_production(): void
{
putenv('APP_FROZEN_NOW=2026-03-15T12:00:00-03:00');
$_ENV['APP_FROZEN_NOW'] = '2026-03-15T12:00:00-03:00';
$_SERVER['APP_FROZEN_NOW'] = '2026-03-15T12:00:00-03:00';
$this->refreshApplication();
$this->assertTrue(CarbonImmutable::hasTestNow());
$this->assertSame(
'2026-03-15T12:00:00-03:00',
CarbonImmutable::now()->toIso8601String(),
);
}
public function test_missing_app_frozen_now_does_not_freeze_clock(): void
{
putenv('APP_FROZEN_NOW');
unset($_ENV['APP_FROZEN_NOW'], $_SERVER['APP_FROZEN_NOW']);
$this->refreshApplication();
$this->assertFalse(CarbonImmutable::hasTestNow());
}
}

View File

@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace Tests\Unit;
use App\Support\ResponsiveImage;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\ImageManager;
use Tests\TestCase;
class ResponsiveImageTest extends TestCase
{
public function test_generates_named_variants_and_removes_them_with_original(): void
{
Storage::fake('public');
$manager = new ImageManager(new Driver);
$original = $manager->create(2000, 1200)->toJpeg(quality: 90);
$path = 'content/abc123.jpg';
Storage::disk('public')->put($path, (string) $original);
ResponsiveImage::generate($path, 'public');
Storage::disk('public')->assertExists('content/abc123-480.jpg');
Storage::disk('public')->assertExists('content/abc123-960.jpg');
Storage::disk('public')->assertExists('content/abc123-1440.jpg');
$variant480 = (new ImageManager(new Driver))->read(Storage::disk('public')->path('content/abc123-480.jpg'));
$this->assertSame(480, $variant480->width());
ResponsiveImage::delete($path, 'public');
Storage::disk('public')->assertMissing($path);
Storage::disk('public')->assertMissing('content/abc123-480.jpg');
Storage::disk('public')->assertMissing('content/abc123-960.jpg');
Storage::disk('public')->assertMissing('content/abc123-1440.jpg');
}
public function test_replace_deletes_previous_variants_and_generates_for_new_original(): void
{
Storage::fake('public');
$manager = new ImageManager(new Driver);
Storage::disk('public')->put('content/old.jpg', (string) $manager->create(1600, 900)->toJpeg());
ResponsiveImage::generate('content/old.jpg', 'public');
Storage::disk('public')->put('content/new.jpg', (string) $manager->create(1800, 1000)->toJpeg());
ResponsiveImage::replace('content/old.jpg', 'content/new.jpg', 'public');
Storage::disk('public')->assertMissing('content/old.jpg');
Storage::disk('public')->assertMissing('content/old-480.jpg');
Storage::disk('public')->assertExists('content/new.jpg');
Storage::disk('public')->assertExists('content/new-480.jpg');
Storage::disk('public')->assertExists('content/new-960.jpg');
Storage::disk('public')->assertExists('content/new-1440.jpg');
}
}

View File

@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
it('ships visual content fixtures as valid jpeg images', function (): void {
$fixtures = [
'og-default.jpg',
'portfolio-cover.jpg',
'service-cover.jpg',
'gallery.jpg',
'testimonial.jpg',
];
foreach ($fixtures as $fixture) {
$path = dirname(__DIR__).'/fixtures/images/'.$fixture;
expect(is_file($path))->toBeTrue("Missing fixture: {$fixture}");
$info = getimagesize($path);
expect($info)->not->toBeFalse("Unreadable fixture: {$fixture}")
->and($info[0] ?? null)->toBeGreaterThan(0)
->and($info[1] ?? null)->toBeGreaterThan(0)
->and($info[2] ?? null)->toBe(IMAGETYPE_JPEG)
->and($info['mime'] ?? null)->toBe('image/jpeg');
}
});

Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 B

After

Width:  |  Height:  |  Size: 310 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 B

After

Width:  |  Height:  |  Size: 310 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 B

After

Width:  |  Height:  |  Size: 310 B

Some files were not shown because too many files have changed in this diff Show More