8 Commits

28 changed files with 1668 additions and 576 deletions

View File

@@ -34,7 +34,7 @@
"response": []
},
{
"name": "Create Tenant (JSON)",
"name": "Create Tenant OnTicket (JSON)",
"request": {
"method": "POST",
"header": [
@@ -51,7 +51,7 @@
],
"body": {
"mode": "raw",
"raw": "{\n \"codigo\": \"acme\",\n \"nombre\": \"Acme\",\n \"dominio\": \"acme.test\",\n \"primary_color\": \"#111111\",\n \"secondary_color\": \"#222222\",\n \"danger_color\": \"#ff0000\",\n \"header_bg_color\": \"#333333\",\n \"footer_bg_color\": \"#333333\",\n \"header_logo\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==\",\n \"footer_logo\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==\"\n}"
"raw": "{\n \"codigo\": \"festival-demo\",\n \"nombre\": \"Festival Demo\",\n \"dominio\": \"festival-demo.test\",\n \"primary_color\": \"#111111\",\n \"secondary_color\": \"#222222\",\n \"danger_color\": \"#ff0000\",\n \"success_color\": \"#00aa55\",\n \"header_bg_color\": \"#333333\",\n \"footer_bg_color\": \"#333333\",\n \"header_logo\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==\",\n \"footer_logo\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==\",\n \"search_product_layout\": \"column_with_image\",\n \"search_group_layout\": \"paginated\",\n \"search_items_per_page\": 12,\n \"website_type_code\": \"onticket\",\n \"extras\": {\n \"heroConfig\": {\n \"title_html\": \"<h1>Festival Demo</h1>\",\n \"description_html\": \"<p>Una experiencia inolvidable</p>\",\n \"button_text\": \"Comprar entradas\",\n \"button_href\": \"/tickets\",\n \"background_image_id\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==\"\n },\n \"eventConfig\": {\n \"title\": \"Festival Demo\",\n \"location\": \"Buenos Aires\",\n \"dates_text\": \"10 y 11 de octubre de 2026\",\n \"dates\": [\n \"2026-10-10\",\n \"2026-10-11\"\n ]\n }\n }\n}"
},
"url": {
"raw": "{{base_url}}/api/tenants",
@@ -67,7 +67,7 @@
"response": []
},
{
"name": "Create Tenant (Form Data)",
"name": "Create Tenant ShopIt (Form Data)",
"request": {
"method": "POST",
"header": [
@@ -110,6 +110,11 @@
"value": "#ff0000",
"type": "text"
},
{
"key": "success_color",
"value": "#00aa55",
"type": "text"
},
{
"key": "header_bg_color",
"value": "#333333",
@@ -129,6 +134,32 @@
"key": "footer_logo",
"type": "file",
"src": []
},
{
"key": "search_product_layout",
"value": "column_with_image",
"type": "text"
},
{
"key": "search_group_layout",
"value": "paginated",
"type": "text"
},
{
"key": "search_items_per_page",
"value": "12",
"type": "text"
},
{
"key": "website_type_code",
"value": "shopit",
"type": "text"
},
{
"key": "extras[carousel][]",
"type": "file",
"src": [],
"description": "Se puede repetir esta key hasta 10 veces. También acepta una imagen base64 o el UUID de un attachment."
}
]
},

View File

@@ -5,27 +5,30 @@ namespace App\Domains\Tenant\Controllers;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Requests\BootstrapTenantRequest;
use App\Domains\Tenant\Resources\TenantResource;
use App\Domains\Tenant\Services\TenantInformationService;
use App\Http\Controllers\Controller;
class BootstrapTenantController extends Controller
{
public function __construct(
protected TenantInformationService $tenantInformationService
) {}
public function __invoke(BootstrapTenantRequest $request): TenantResource
{
/** @var string $dominio */
$dominio = $request->validated('dominio');
return TenantResource::make(
Tenant::query()
->with([
'headerLogo',
'footerLogo',
'mainCarouselImages',
$this->tenantInformationService->load(
Tenant::query()
->where('dominio', $dominio)
->firstOrFail(),
[
'menues',
'socialMedia',
'categories' => fn ($query) => $query->orderBy('nombre'),
])
->where('dominio', $dominio)
->firstOrFail()
]
)
);
}
}

View File

@@ -6,6 +6,7 @@ use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Requests\StoreTenantRequest;
use App\Domains\Tenant\Requests\UpdateTenantRequest;
use App\Domains\Tenant\Resources\TenantResource;
use App\Domains\Tenant\Services\TenantInformationService;
use App\Domains\Tenant\Services\TenantService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
@@ -13,16 +14,20 @@ use Illuminate\Http\Response;
class TenantController extends Controller
{
public function __construct(protected TenantService $tenantService) {}
public function __construct(
protected TenantService $tenantService,
protected TenantInformationService $tenantInformationService,
) {}
public function index(): JsonResponse
{
return TenantResource::collection(
Tenant::query()
->with(['headerLogo', 'footerLogo', 'mainCarouselImages', 'socialMedia'])
->latest()
->paginateFromRequest()
)->response();
$tenants = Tenant::query()
->latest()
->paginateFromRequest();
$this->tenantInformationService->loadMany($tenants->getCollection());
return TenantResource::collection($tenants)->response();
}
public function store(StoreTenantRequest $request): JsonResponse
@@ -30,14 +35,14 @@ class TenantController extends Controller
$tenant = $this->tenantService->create($request->validated());
return TenantResource::make(
$tenant->loadMissing(['headerLogo', 'footerLogo', 'mainCarouselImages', 'socialMedia'])
$this->tenantInformationService->load($tenant)
)->response()->setStatusCode(201);
}
public function show(Tenant $tenant): TenantResource
{
return TenantResource::make(
$tenant->loadMissing(['headerLogo', 'footerLogo', 'mainCarouselImages', 'socialMedia'])
$this->tenantInformationService->load($tenant)
);
}
@@ -46,7 +51,7 @@ class TenantController extends Controller
$tenant = $this->tenantService->update($tenant, $request->validated());
return TenantResource::make(
$tenant->loadMissing(['headerLogo', 'footerLogo', 'mainCarouselImages', 'socialMedia'])
$this->tenantInformationService->load($tenant)
);
}

View File

@@ -28,8 +28,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
'footer_bg_color',
'header_logo_id',
'footer_logo_id',
'hero_config',
'event_config',
'website_type_code',
'search_product_layout',
'search_group_layout',
'search_items_per_page',
@@ -57,8 +56,6 @@ class Tenant extends Model
protected function casts(): array
{
return [
'hero_config' => 'array',
'event_config' => 'array',
'search_product_layout' => ProductLayout::class,
'search_group_layout' => GroupLayout::class,
'search_items_per_page' => 'integer',
@@ -82,27 +79,11 @@ class Tenant extends Model
}
/**
* @return BelongsTo<Attachment, $this>
* @return BelongsTo<WebsiteType, $this>
*/
public function heroBgImage(): BelongsTo
public function websiteType(): BelongsTo
{
return $this->belongsTo(Attachment::class, 'hero_bg_image_id');
}
/**
* @return BelongsToMany<Attachment, $this>
*/
public function mainCarouselImages(): BelongsToMany
{
return $this->belongsToMany(
Attachment::class,
'tenant_main_carousel_images',
'tenant_id',
'attachment_id'
)
->withPivot('orden')
->withTimestamps()
->orderByPivot('orden');
return $this->belongsTo(WebsiteType::class, 'website_type_code', 'codigo');
}
public function catalogItems(): HasMany
@@ -136,6 +117,14 @@ class Tenant extends Model
->orderByPivot('orden');
}
/**
* @return HasMany<WebsiteExtra, $this>
*/
public function websiteExtras(): HasMany
{
return $this->hasMany(WebsiteExtra::class, 'website_code', 'codigo');
}
public function menues(): BelongsToMany
{
return $this->belongsToMany(

View File

@@ -0,0 +1,64 @@
<?php
namespace App\Domains\Tenant\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable([
'website_code',
'website_type_extra_id',
'config',
])]
class WebsiteExtra extends Model
{
use HasFactory;
protected $table = 'websites_extras';
private mixed $resolvedConfig = null;
private bool $hasResolvedConfig = false;
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'website_type_extra_id' => 'integer',
'config' => 'array',
];
}
/**
* @return BelongsTo<Tenant, $this>
*/
public function website(): BelongsTo
{
return $this->belongsTo(Tenant::class, 'website_code', 'codigo');
}
/**
* @return BelongsTo<WebsiteTypeExtra, $this>
*/
public function websiteTypeExtra(): BelongsTo
{
return $this->belongsTo(WebsiteTypeExtra::class, 'website_type_extra_id');
}
public function setResolvedConfig(mixed $config): self
{
$this->resolvedConfig = $config;
$this->hasResolvedConfig = true;
return $this;
}
public function resolvedConfig(): mixed
{
return $this->hasResolvedConfig ? $this->resolvedConfig : $this->config;
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace App\Domains\Tenant\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable([
'codigo',
'nombre',
])]
class WebsiteType extends Model
{
use HasFactory;
protected $table = 'website_type';
/**
* @return HasMany<WebsiteTypeExtra, $this>
*/
public function extras(): HasMany
{
return $this->hasMany(WebsiteTypeExtra::class, 'website_type_code', 'codigo');
}
/**
* @return HasMany<Tenant, $this>
*/
public function tenants(): HasMany
{
return $this->hasMany(Tenant::class, 'website_type_code', 'codigo');
}
}

View File

@@ -0,0 +1,50 @@
<?php
namespace App\Domains\Tenant\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable([
'website_type_code',
'nombre',
'descripcion',
'is_required',
'config_schema',
])]
class WebsiteTypeExtra extends Model
{
use HasFactory;
protected $table = 'website_type_extras';
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'is_required' => 'boolean',
'config_schema' => 'array',
];
}
/**
* @return BelongsTo<WebsiteType, $this>
*/
public function websiteType(): BelongsTo
{
return $this->belongsTo(WebsiteType::class, 'website_type_code', 'codigo');
}
/**
* @return HasMany<WebsiteExtra, $this>
*/
public function websiteExtras(): HasMany
{
return $this->hasMany(WebsiteExtra::class, 'website_type_extra_id');
}
}

View File

@@ -5,6 +5,7 @@ namespace App\Domains\Tenant\Requests;
use App\Domains\Catalog\Enums\GroupLayout;
use App\Domains\Catalog\Enums\ProductLayout;
use App\Domains\Shared\Rules\ImageOrBase64Rule;
use App\Domains\Tenant\Services\WebsiteExtraService;
use App\Domains\Tenant\Support\TenantDomainNormalizer;
use Closure;
use Illuminate\Foundation\Http\FormRequest;
@@ -39,7 +40,7 @@ class StoreTenantRequest extends FormRequest
{
$logoRule = ['required', new ImageOrBase64Rule];
return [
return array_merge([
'codigo' => ['required', 'string', 'max:255', Rule::unique('tenants', 'codigo')],
'nombre' => ['required', 'string', 'max:255'],
'dominio' => [
@@ -62,9 +63,6 @@ class StoreTenantRequest extends FormRequest
'footer_bg_color' => ['required', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
'header_logo' => $logoRule,
'footer_logo' => $logoRule,
'hero_bg_image' => ['nullable', new ImageOrBase64Rule],
'main_carousel_images' => ['sometimes', 'array'],
'main_carousel_images.*' => ['required', 'distinct', new ImageOrBase64Rule],
'social_media' => ['sometimes', 'array'],
'social_media.*.code' => [
'required',
@@ -74,19 +72,15 @@ class StoreTenantRequest extends FormRequest
],
'social_media.*.url' => ['required', 'url', 'max:2048'],
'social_media.*.orden' => ['sometimes', 'integer', 'min:0', 'distinct'],
'hero_config' => ['nullable', 'array'],
'hero_config.title_html' => ['nullable', 'string'],
'hero_config.description_html' => ['nullable', 'string'],
'hero_config.button_text' => ['nullable', 'string'],
'hero_config.button_href' => ['nullable', 'string'],
'event_config' => ['nullable', 'array'],
'event_config.title' => ['nullable', 'string'],
'event_config.location' => ['nullable', 'string'],
'event_config.dates' => ['nullable', 'array'],
'event_config.dates.*' => ['required', 'string'],
'search_product_layout' => ['sometimes', Rule::enum(ProductLayout::class)],
'search_group_layout' => ['sometimes', Rule::enum(GroupLayout::class)],
'search_items_per_page' => ['sometimes', 'integer', 'min:4', 'max:48'],
];
'website_type_code' => [
'required_with:extras',
'sometimes',
'string',
Rule::exists('website_type', 'codigo'),
],
], app(WebsiteExtraService::class)->requestRules($this->input('website_type_code')));
}
}

View File

@@ -73,9 +73,6 @@ class UpdateTenantRequest extends FormRequest
'footer_bg_color' => ['nullable', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
'header_logo' => $logoRule,
'footer_logo' => $logoRule,
'hero_bg_image' => ['nullable', new ImageOrBase64Rule],
'main_carousel_images' => ['sometimes', 'array'],
'main_carousel_images.*' => ['required', 'distinct', new ImageOrBase64Rule],
'social_media' => ['sometimes', 'array'],
'social_media.*.code' => [
'required',
@@ -85,16 +82,6 @@ class UpdateTenantRequest extends FormRequest
],
'social_media.*.url' => ['required', 'url', 'max:2048'],
'social_media.*.orden' => ['sometimes', 'integer', 'min:0', 'distinct'],
'hero_config' => ['nullable', 'array'],
'hero_config.title_html' => ['nullable', 'string'],
'hero_config.description_html' => ['nullable', 'string'],
'hero_config.button_text' => ['nullable', 'string'],
'hero_config.button_href' => ['nullable', 'string'],
'event_config' => ['nullable', 'array'],
'event_config.title' => ['nullable', 'string'],
'event_config.location' => ['nullable', 'string'],
'event_config.dates' => ['nullable', 'array'],
'event_config.dates.*' => ['required', 'string'],
'search_product_layout' => ['sometimes', Rule::enum(ProductLayout::class)],
'search_group_layout' => ['sometimes', Rule::enum(GroupLayout::class)],
'search_items_per_page' => ['sometimes', 'integer', 'min:4', 'max:48'],

View File

@@ -2,6 +2,7 @@
namespace App\Domains\Tenant\Resources;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Catalog\Models\Category;
use App\Domains\Menu\Models\Menu;
use App\Domains\Tenant\Models\Tenant;
@@ -19,12 +20,6 @@ class TenantResource extends JsonResource
*/
public function toArray(Request $request): array
{
$heroConfig = $this->hero_config;
if (is_array($heroConfig)) {
$heroConfig['background_image'] = $this->heroBgImage?->getTemporaryUrl(1440);
unset($heroConfig['background_image_id']);
}
return [
'id' => $this->id,
'codigo' => $this->codigo,
@@ -36,20 +31,28 @@ class TenantResource extends JsonResource
'success_color' => $this->success_color,
'header_bg_color' => $this->header_bg_color,
'footer_bg_color' => $this->footer_bg_color,
'website_type_code' => $this->website_type_code,
'website_type' => $this->whenLoaded(
'websiteType',
fn () => $this->websiteType ? [
'codigo' => $this->websiteType->codigo,
'nombre' => $this->websiteType->nombre,
] : null
),
'extras' => $this->whenLoaded(
'websiteExtras',
fn () => $this->websiteExtras->mapWithKeys(fn ($extra) => [
$extra->websiteTypeExtra->nombre => $this->formatExtraConfig(
$extra->resolvedConfig()
),
])
),
// 1 day
'header_logo' => $this->headerLogo?->getTemporaryUrl(1440),
'footer_logo' => $this->footerLogo?->getTemporaryUrl(1440),
'hero_config' => $heroConfig,
'event_config' => $this->event_config,
'search_product_layout' => $this->search_product_layout->value,
'search_group_layout' => $this->search_group_layout->value,
'search_items_per_page' => $this->search_items_per_page,
'main_carousel_images' => $this->whenLoaded(
'mainCarouselImages',
fn () => $this->mainCarouselImages
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
->values()
),
'social_media' => $this->whenLoaded(
'socialMedia',
fn () => $this->socialMedia
@@ -72,6 +75,23 @@ class TenantResource extends JsonResource
];
}
private function formatExtraConfig(mixed $value): mixed
{
if ($value instanceof Attachment) {
return $value->getTemporaryUrl(1440);
}
if (! is_array($value)) {
return $value;
}
foreach ($value as $key => $item) {
$value[$key] = $this->formatExtraConfig($item);
}
return $value;
}
/**
* @param Collection<int, Category> $categories
* @return Collection<int, array<string, mixed>>

View File

@@ -0,0 +1,177 @@
<?php
namespace App\Domains\Tenant\Services;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Models\WebsiteExtra;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Support\Collection;
class TenantInformationService
{
private const DEFAULT_RELATIONS = [
'headerLogo',
'footerLogo',
'socialMedia',
'websiteType',
'websiteExtras.websiteTypeExtra',
];
/**
* @param array<int|string, mixed> $relations
*/
public function load(Tenant $tenant, array $relations = []): Tenant
{
$this->loadMany(new EloquentCollection([$tenant]), $relations);
return $tenant;
}
/**
* @param EloquentCollection<int, Tenant> $tenants
* @param array<int|string, mixed> $relations
* @return EloquentCollection<int, Tenant>
*/
public function loadMany(
EloquentCollection $tenants,
array $relations = []
): EloquentCollection {
$tenants->loadMissing([
...self::DEFAULT_RELATIONS,
...$relations,
]);
$websiteExtras = $tenants
->flatMap(fn (Tenant $tenant): Collection => $tenant->websiteExtras);
$this->resolveWebsiteExtraAttachments($websiteExtras);
return $tenants;
}
/**
* Replace attachment IDs with their models in each extra's resolved config.
*
* @param Collection<int, WebsiteExtra> $websiteExtras
*/
private function resolveWebsiteExtraAttachments(Collection $websiteExtras): void
{
$attachmentIds = $websiteExtras
->flatMap(function (WebsiteExtra $extra): array {
$ids = [];
foreach ($this->attachmentTransformPaths($extra) as $path) {
$ids = [
...$ids,
...$this->valuesAtPath($extra->config, $this->pathSegments($path)),
];
}
return $ids;
})
->filter(fn (mixed $id): bool => is_int($id) || ctype_digit((string) $id))
->map(fn (mixed $id): int => (int) $id)
->unique()
->values();
$attachments = Attachment::query()
->whereIn('id', $attachmentIds)
->get()
->keyBy('id');
foreach ($websiteExtras as $extra) {
$config = $extra->config;
foreach ($this->attachmentTransformPaths($extra) as $path) {
$config = $this->replaceAtPath(
$config,
$this->pathSegments($path),
fn (mixed $attachmentId): ?Attachment => $attachments->get((int) $attachmentId)
);
}
$extra->setResolvedConfig($config);
}
}
/**
* @return array<int, string>
*/
private function attachmentTransformPaths(WebsiteExtra $extra): array
{
return collect($extra->websiteTypeExtra->config_schema['transforms'] ?? [])
->filter(
fn (mixed $transform): bool => is_array($transform)
&& ($transform['handler'] ?? null) === 'attachment'
)
->keys()
->all();
}
/**
* @return array<int, string>
*/
private function pathSegments(string $path): array
{
$path = ltrim($path, '$');
$path = ltrim($path, '.');
return $path === '' ? [] : explode('.', $path);
}
/**
* @return array<int, mixed>
*/
private function valuesAtPath(mixed $value, array $segments): array
{
if ($segments === []) {
return [$value];
}
if (! is_array($value)) {
return [];
}
$segment = array_shift($segments);
if ($segment === '*') {
return collect($value)
->flatMap(fn (mixed $item): array => $this->valuesAtPath($item, $segments))
->all();
}
if (! array_key_exists($segment, $value)) {
return [];
}
return $this->valuesAtPath($value[$segment], $segments);
}
private function replaceAtPath(mixed $value, array $segments, callable $replace): mixed
{
if ($segments === []) {
return $value === null ? null : $replace($value);
}
if (! is_array($value)) {
return $value;
}
$segment = array_shift($segments);
if ($segment === '*') {
foreach ($value as $key => $item) {
$value[$key] = $this->replaceAtPath($item, $segments, $replace);
}
return $value;
}
if (array_key_exists($segment, $value)) {
$value[$segment] = $this->replaceAtPath($value[$segment], $segments, $replace);
}
return $value;
}
}

View File

@@ -2,17 +2,18 @@
namespace App\Domains\Tenant\Services;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Services\AttachmentService;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class TenantService
{
public function __construct(protected AttachmentService $attachmentService) {}
public function __construct(
protected AttachmentService $attachmentService,
protected WebsiteExtraService $websiteExtraService,
) {}
/**
* Create a new tenant and store its logos.
@@ -24,16 +25,14 @@ class TenantService
return DB::transaction(function () use ($data): Tenant {
$headerLogo = $data['header_logo'] ?? null;
$footerLogo = $data['footer_logo'] ?? null;
$heroBgImage = $data['hero_bg_image'] ?? null;
$mainCarouselImages = $data['main_carousel_images'] ?? [];
$socialMedia = $data['social_media'] ?? [];
$extras = $data['extras'] ?? [];
unset(
$data['header_logo'],
$data['footer_logo'],
$data['hero_bg_image'],
$data['main_carousel_images'],
$data['social_media']
$data['social_media'],
$data['extras'],
);
$headerAttachmentId = null;
@@ -61,22 +60,10 @@ class TenantService
$data['header_logo_id'] = $headerAttachmentId;
$data['footer_logo_id'] = $footerAttachmentId;
if ($heroBgImage) {
$attachment = Str::isUuid($heroBgImage)
? Attachment::query()->where('key', $heroBgImage)->first()
: $this->attachmentService->store($heroBgImage, 'tenants');
if ($attachment) {
$heroConfig = $data['hero_config'] ?? [];
$heroConfig['background_image_id'] = $attachment->id;
$data['hero_config'] = $heroConfig;
}
}
/** @var Tenant $tenant */
$tenant = Tenant::query()->create($data);
$this->syncMainCarouselImages($tenant, $mainCarouselImages);
$this->syncSocialMedia($tenant, $socialMedia);
$this->websiteExtraService->createForTenant($tenant, $extras);
return $tenant;
});
@@ -92,25 +79,17 @@ class TenantService
return DB::transaction(function () use ($tenant, $data): Tenant {
$hasHeaderLogoKey = array_key_exists('header_logo', $data);
$hasFooterLogoKey = array_key_exists('footer_logo', $data);
$hasHeroBgImageKey = array_key_exists('hero_bg_image', $data);
$hasMainCarouselImagesKey = array_key_exists('main_carousel_images', $data);
$hasSocialMediaKey = array_key_exists('social_media', $data);
$headerLogo = $data['header_logo'] ?? null;
$footerLogo = $data['footer_logo'] ?? null;
$heroBgImage = $data['hero_bg_image'] ?? null;
$mainCarouselImages = $data['main_carousel_images'] ?? [];
$socialMedia = $data['social_media'] ?? [];
unset(
$data['header_logo'],
$data['footer_logo'],
$data['hero_bg_image'],
$data['main_carousel_images'],
$data['social_media']
);
$oldHeroBgId = $tenant->hero_bg_image_id;
$tenant->fill($data);
if ($hasHeaderLogoKey) {
@@ -145,34 +124,8 @@ class TenantService
}
}
$currentHeroConfig = $tenant->hero_config ?? [];
if ($hasHeroBgImageKey) {
if ($heroBgImage) {
$attachment = Str::isUuid($heroBgImage)
? Attachment::query()->where('key', $heroBgImage)->first()
: $this->attachmentService->store($heroBgImage, 'tenants');
if ($attachment) {
$currentHeroConfig['background_image_id'] = $attachment->id;
} else {
unset($currentHeroConfig['background_image_id']);
}
} else {
unset($currentHeroConfig['background_image_id']);
}
} else {
if ($oldHeroBgId) {
$currentHeroConfig['background_image_id'] = $oldHeroBgId;
}
}
$tenant->hero_config = empty($currentHeroConfig) ? null : $currentHeroConfig;
$tenant->save();
if ($hasMainCarouselImagesKey) {
$this->syncMainCarouselImages($tenant, $mainCarouselImages);
}
if ($hasSocialMediaKey) {
$this->syncSocialMedia($tenant, $socialMedia);
}
@@ -181,21 +134,6 @@ class TenantService
});
}
/**
* @param array<int, mixed> $images
*/
private function syncMainCarouselImages(Tenant $tenant, array $images): void
{
$attachments = [];
foreach (array_values($images) as $order => $image) {
$attachment = $this->resolveMainCarouselImage($image, $order);
$attachments[$attachment->id] = ['orden' => $order];
}
$tenant->mainCarouselImages()->sync($attachments);
}
/**
* @param array<int, array{code: string, url: string, orden?: int}> $socialMedia
*/
@@ -213,26 +151,4 @@ class TenantService
$tenant->socialMedia()->sync($associations);
$tenant->unsetRelation('socialMedia');
}
private function resolveMainCarouselImage(mixed $image, int $order): Attachment
{
if (is_string($image) && Str::isUuid($image)) {
$attachment = Attachment::query()
->where('key', $image)
->where('type', AttachmentType::Image->value)
->first();
if ($attachment === null) {
throw ValidationException::withMessages([
"main_carousel_images.{$order}" => [
__('api.tenant.invalid_carousel_image'),
],
]);
}
return $attachment;
}
return $this->attachmentService->store($image, 'tenants/main-carousel');
}
}

View File

@@ -0,0 +1,305 @@
<?php
namespace App\Domains\Tenant\Services;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Services\AttachmentService;
use App\Domains\Shared\Rules\ImageOrBase64Rule;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Models\WebsiteType;
use App\Domains\Tenant\Models\WebsiteTypeExtra;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;
class WebsiteExtraService
{
public function __construct(protected AttachmentService $attachmentService) {}
/**
* Build the request rules declared by the selected website type.
*
* @return array<string, mixed>
*/
public function requestRules(?string $websiteTypeCode): array
{
if (! is_string($websiteTypeCode) || $websiteTypeCode === '') {
return [
'extras' => ['prohibited'],
];
}
$definitions = $this->definitionsFor($websiteTypeCode);
$allowedNames = $definitions->pluck('nombre')->all();
$hasRequiredExtras = $definitions->contains(
fn (WebsiteTypeExtra $definition): bool => $definition->is_required
);
$rules = [
'extras' => [
$hasRequiredExtras ? 'required' : 'sometimes',
'array',
function (string $attribute, mixed $value, \Closure $fail) use ($allowedNames): void {
if (! is_array($value)) {
return;
}
$unknownNames = array_diff(array_keys($value), $allowedNames);
if ($unknownNames !== []) {
$fail(
'The '.$attribute.' field contains extras not supported by the website type: '
.implode(', ', $unknownNames).'.'
);
}
},
],
];
foreach ($definitions as $definition) {
$schemaRules = $definition->config_schema['request_rules'] ?? [];
$rootRules = $this->compileRules($schemaRules['$'] ?? []);
$rootRules = array_values(array_filter(
$rootRules,
fn (mixed $rule): bool => ! in_array($rule, ['required', 'sometimes'], true)
));
array_unshift($rootRules, $definition->is_required ? 'required' : 'sometimes');
$rules["extras.{$definition->nombre}"] = $rootRules;
foreach ($schemaRules as $path => $pathRules) {
if ($path === '$') {
continue;
}
$rules[$this->requestAttribute($definition->nombre, $path)] = $this->compileRules($pathRules);
}
}
return $rules;
}
/**
* Transform and persist each extra selected for a tenant.
*
* @param array<string, mixed> $extras
*/
public function createForTenant(Tenant $tenant, array $extras): void
{
if ($extras === []) {
return;
}
$definitions = $this->definitionsFor((string) $tenant->website_type_code)
->keyBy('nombre');
foreach ($extras as $name => $config) {
/** @var WebsiteTypeExtra|null $definition */
$definition = $definitions->get($name);
if (! $definition) {
throw ValidationException::withMessages([
'extras' => ["The extra {$name} is not supported by the selected website type."],
]);
}
$transformedConfig = $this->applyTransforms($tenant, $definition, $config);
$this->validateDatabaseConfig($definition, $transformedConfig);
$tenant->websiteExtras()->create([
'website_type_extra_id' => $definition->id,
'config' => $transformedConfig,
]);
}
$tenant->unsetRelation('websiteExtras');
}
/**
* @return Collection<int, WebsiteTypeExtra>
*/
private function definitionsFor(string $websiteTypeCode): Collection
{
$websiteType = WebsiteType::query()
->where('codigo', $websiteTypeCode)
->with('extras')
->first();
return $websiteType?->extras ?? collect();
}
/**
* @param string|array<int, mixed> $rules
* @return array<int, mixed>
*/
private function compileRules(string|array $rules): array
{
$compiled = is_string($rules) ? explode('|', $rules) : $rules;
return array_map(
fn (mixed $rule): mixed => $rule === 'image_or_base64'
? new ImageOrBase64Rule
: $rule,
$compiled
);
}
private function requestAttribute(string $extraName, string $path): string
{
if ($path === '$') {
return "extras.{$extraName}";
}
if (str_starts_with($path, '$.')) {
$path = substr($path, 2);
}
return "extras.{$extraName}.{$path}";
}
private function applyTransforms(
Tenant $tenant,
WebsiteTypeExtra $definition,
mixed $config
): mixed {
foreach ($definition->config_schema['transforms'] ?? [] as $path => $transform) {
$segments = $this->pathSegments($path);
$config = $this->transformAtPath(
$config,
$segments,
fn (mixed $value): mixed => $this->transformValue(
$tenant,
$definition,
$path,
$value,
$transform
)
);
}
return $config;
}
/**
* @return array<int, string>
*/
private function pathSegments(string $path): array
{
$path = ltrim($path, '$');
$path = ltrim($path, '.');
return $path === '' ? [] : explode('.', $path);
}
private function transformAtPath(mixed $value, array $segments, callable $transform): mixed
{
if ($segments === []) {
return $transform($value);
}
if (! is_array($value)) {
return $value;
}
$segment = array_shift($segments);
if ($segment === '*') {
foreach ($value as $key => $item) {
$value[$key] = $this->transformAtPath($item, $segments, $transform);
}
return $value;
}
if (array_key_exists($segment, $value)) {
$value[$segment] = $this->transformAtPath($value[$segment], $segments, $transform);
}
return $value;
}
/**
* @param array<string, mixed> $transform
*/
private function transformValue(
Tenant $tenant,
WebsiteTypeExtra $definition,
string $path,
mixed $value,
array $transform
): mixed {
if ($value === null) {
return null;
}
if (($transform['handler'] ?? null) !== 'attachment') {
throw new InvalidArgumentException(
"Unsupported transform handler for {$definition->nombre}: ".($transform['handler'] ?? 'null')
);
}
if (is_string($value) && Str::isUuid($value)) {
$attachment = Attachment::query()->where('key', $value)->first();
if (! $attachment) {
throw ValidationException::withMessages([
$this->requestAttribute($definition->nombre, $path) => [
'The selected attachment does not exist.',
],
]);
}
} else {
$attachment = $this->attachmentService->store(
$value,
"tenants/{$tenant->codigo}/extras/{$definition->nombre}"
);
}
$expectedType = $transform['attachment_type'] ?? null;
if (
is_string($expectedType)
&& $attachment->type instanceof AttachmentType
&& $attachment->type->value !== $expectedType
) {
throw ValidationException::withMessages([
$this->requestAttribute($definition->nombre, $path) => [
"The attachment must be of type {$expectedType}.",
],
]);
}
return $attachment->id;
}
private function validateDatabaseConfig(
WebsiteTypeExtra $definition,
mixed $config
): void {
$schemaRules = $definition->config_schema['database_rules'] ?? [];
$rules = [];
foreach ($schemaRules as $path => $pathRules) {
$attribute = $path === '$'
? 'config'
: 'config.'.ltrim(str_starts_with($path, '$.') ? substr($path, 2) : $path, '.');
$rules[$attribute] = $this->compileRules($pathRules);
}
$validator = Validator::make(['config' => $config], $rules);
if ($validator->fails()) {
$messages = [];
foreach ($validator->errors()->toArray() as $attribute => $errors) {
$suffix = $attribute === 'config' ? '' : substr($attribute, strlen('config'));
$messages["extras.{$definition->nombre}{$suffix}"] = $errors;
}
throw ValidationException::withMessages($messages);
}
}
}

View File

@@ -0,0 +1,73 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('website_type', function (Blueprint $table): void {
$table->id();
$table->string('codigo')->unique();
$table->string('nombre');
$table->timestamps();
});
Schema::table('tenants', function (Blueprint $table): void {
$table->string('website_type_code')->nullable();
$table->foreign('website_type_code')
->references('codigo')
->on('website_type')
->cascadeOnUpdate()
->nullOnDelete();
});
Schema::create('website_type_extras', function (Blueprint $table): void {
$table->id();
$table->string('website_type_code');
$table->foreign('website_type_code')
->references('codigo')
->on('website_type')
->cascadeOnUpdate()
->cascadeOnDelete();
$table->string('nombre');
$table->text('descripcion');
$table->boolean('is_required')->default(false);
$table->json('config_schema');
$table->timestamps();
});
Schema::create('websites_extras', function (Blueprint $table): void {
$table->id();
$table->string('website_code');
$table->foreignId('website_type_extra_id')
->constrained('website_type_extras')
->cascadeOnUpdate()
->cascadeOnDelete();
$table->json('config');
$table->timestamps();
$table->foreign('website_code')
->references('codigo')
->on('tenants')
->cascadeOnUpdate()
->cascadeOnDelete();
});
}
public function down(): void
{
Schema::dropIfExists('websites_extras');
Schema::dropIfExists('website_type_extras');
Schema::table('tenants', function (Blueprint $table): void {
$table->dropForeign(['website_type_code']);
$table->dropColumn('website_type_code');
});
Schema::dropIfExists('website_type');
}
};

View File

@@ -0,0 +1,44 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::dropIfExists('tenant_main_carousel_images');
Schema::table('tenants', function (Blueprint $table): void {
$table->dropColumn('hero_bg_image_id');
$table->dropColumn(['hero_config', 'event_config']);
});
}
public function down(): void
{
Schema::table('tenants', function (Blueprint $table): void {
$table->json('hero_config')->nullable();
$table->json('event_config')->nullable();
$table->unsignedBigInteger('hero_bg_image_id')
->virtualAs('hero_config->>"$.background_image_id"')
->nullable();
});
Schema::create('tenant_main_carousel_images', function (Blueprint $table): void {
$table->id();
$table->foreignId('tenant_id')
->constrained('tenants')
->cascadeOnDelete();
$table->foreignId('attachment_id')
->constrained('attachments')
->cascadeOnDelete();
$table->unsignedInteger('orden')->default(0);
$table->timestamps();
$table->unique(['tenant_id', 'attachment_id']);
$table->index(['tenant_id', 'orden']);
});
}
};

View File

@@ -23,6 +23,7 @@ class DatabaseSeeder extends Seeder
]);
$this->call([
WebsiteTypeSeeder::class,
SocialMediaSeeder::class,
TenantSeeder::class,
AttributeSeeder::class,

View File

@@ -21,6 +21,16 @@ class MenuSeeder extends Seeder
'route' => '/product/:id',
],
['code' => 'checkout', 'label' => 'Finalizar compra', 'route' => '/checkout'],
['code' => 'admin.event', 'label' => 'Eventos', 'route' => '/admin/event'],
['code' => 'admin.catalog', 'label' => 'Catálogo', 'route' => '/admin/catalog'],
['code' => 'admin.combos', 'label' => 'Combos', 'route' => '/admin/combos'],
[
'code' => 'admin.categories',
'label' => 'Categorías',
'route' => '/admin/categories',
],
['code' => 'admin.ventas', 'label' => 'Ventas', 'route' => '/admin/ventas'],
['code' => 'admin.staff', 'label' => 'Staff', 'route' => '/admin/staff'],
[
'code' => 'account',
'label' => 'Mi cuenta',

View File

@@ -2,23 +2,17 @@
namespace Database\Seeders;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Services\AttachmentService;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Services\TenantService;
use Illuminate\Database\Seeder;
use Illuminate\Http\UploadedFile;
use RuntimeException;
use Throwable;
class TenantSeeder extends Seeder
{
private const SONDER_MAIN_CAROUSEL_IMAGES = [
'01-urban-team.png',
'02-running-shoes.png',
'03-streetwear.png',
'04-football-training.png',
'05-activewear-essentials.png',
'06-city-runners.png',
];
private const SOCIAL_MEDIA = [
[
'code' => 'instagram',
@@ -44,88 +38,13 @@ class TenantSeeder extends Seeder
public function __construct(protected TenantService $tenantService) {}
/**
* Run the database seeds.
*/
public function run(): void
{
// Check if tenant 'sonder' already exists and delete it to prevent duplicates
$existing = Tenant::query()->where('codigo', 'sonder')->first();
if ($existing) {
$attachmentService = app(AttachmentService::class);
if ($existing->headerLogo) {
try {
$attachmentService->delete($existing->headerLogo);
} catch (\Throwable $e) {
// Ignore exception on cleanup
}
}
if ($existing->footerLogo && $existing->footer_logo_id !== $existing->header_logo_id) {
try {
$attachmentService->delete($existing->footerLogo);
} catch (\Throwable $e) {
// Ignore exception on cleanup
}
}
foreach ($existing->mainCarouselImages as $mainCarouselImage) {
try {
$attachmentService->delete($mainCarouselImage);
} catch (\Throwable $e) {
// Ignore exception on cleanup
}
}
$existing->delete();
}
$this->deleteTenant('sonder');
// Check if domain 'localhost' is already in use by another tenant and delete it
$existingDomain = Tenant::query()->where('dominio', 'localhost')->first();
if ($existingDomain) {
$existingDomain->delete();
}
$headerImagePath = public_path('images/sonder_header.png');
$footerImagePath = public_path('images/sonder_footer.png');
if (! file_exists($headerImagePath)) {
throw new \RuntimeException("Image not found at path: {$headerImagePath}");
}
if (! file_exists($footerImagePath)) {
throw new \RuntimeException("Image not found at path: {$footerImagePath}");
}
$headerLogo = new UploadedFile(
$headerImagePath,
'sonder_header.png',
'image/png',
null,
true
);
$footerLogo = new UploadedFile(
$footerImagePath,
'sonder_footer.png',
'image/png',
null,
true
);
$mainCarouselImages = [];
foreach (self::SONDER_MAIN_CAROUSEL_IMAGES as $filename) {
$imagePath = public_path("images/sonder-main-carousel/{$filename}");
if (! file_exists($imagePath)) {
throw new \RuntimeException("Image not found at path: {$imagePath}");
}
$mainCarouselImages[] = new UploadedFile(
$imagePath,
$filename,
'image/png',
null,
true
);
}
Tenant::query()
->where('dominio', 'localhost')
->delete();
$this->tenantService->create([
'codigo' => 'sonder',
@@ -137,82 +56,46 @@ class TenantSeeder extends Seeder
'success_color' => '#198754',
'header_bg_color' => '#ffffff',
'footer_bg_color' => '#313131',
'header_logo' => $headerLogo,
'footer_logo' => $footerLogo,
'main_carousel_images' => $mainCarouselImages,
'header_logo' => $this->uploadedImage('images/sonder_header.png', 'sonder_header.png'),
'footer_logo' => $this->uploadedImage('images/sonder_footer.png', 'sonder_footer.png'),
'social_media' => self::SOCIAL_MEDIA,
'website_type_code' => 'shopit',
'extras' => [
'carousel' => [
$this->uploadedImage(
'images/sonder-main-carousel/01-urban-team.png',
'01-urban-team.png',
),
$this->uploadedImage(
'images/sonder-main-carousel/02-running-shoes.png',
'02-running-shoes.png',
),
$this->uploadedImage(
'images/sonder-main-carousel/03-streetwear.png',
'03-streetwear.png',
),
$this->uploadedImage(
'images/sonder-main-carousel/04-football-training.png',
'04-football-training.png',
),
$this->uploadedImage(
'images/sonder-main-carousel/05-activewear-essentials.png',
'05-activewear-essentials.png',
),
$this->uploadedImage(
'images/sonder-main-carousel/06-city-runners.png',
'06-city-runners.png',
),
],
],
]);
// Check if tenant 'fiesta_futbol_infantil' already exists
$existingFiesta = Tenant::query()->where('codigo', 'fiesta_futbol_infantil')->first();
if ($existingFiesta) {
$attachmentService = app(AttachmentService::class);
if ($existingFiesta->headerLogo) {
try {
$attachmentService->delete($existingFiesta->headerLogo);
} catch (\Throwable $e) {
}
}
if ($existingFiesta->footerLogo && $existingFiesta->footer_logo_id !== $existingFiesta->header_logo_id) {
try {
$attachmentService->delete($existingFiesta->footerLogo);
} catch (\Throwable $e) {
}
}
if ($existingFiesta->heroBgImage) {
try {
$attachmentService->delete($existingFiesta->heroBgImage);
} catch (\Throwable $e) {
}
}
$existingFiesta->delete();
}
$this->deleteTenant('fiesta_futbol_infantil');
$fiestaDomain = 'fiesta-futbol-infantil.localhost';
$existingFiestaDomain = Tenant::query()->where('dominio', $fiestaDomain)->first();
if ($existingFiestaDomain) {
$existingFiestaDomain->delete();
}
$fiestaHeaderImagePath = public_path('images/futbol_infantil_header.png');
$fiestaFooterImagePath = public_path('images/futbol_infantil_footer.png');
$fiestaHeroBgImagePath = public_path('images/futbol_infantil_hero.jpg');
if (! file_exists($fiestaHeaderImagePath)) {
throw new \RuntimeException("Image not found at path: {$fiestaHeaderImagePath}");
}
if (! file_exists($fiestaFooterImagePath)) {
throw new \RuntimeException("Image not found at path: {$fiestaFooterImagePath}");
}
if (! file_exists($fiestaHeroBgImagePath)) {
throw new \RuntimeException("Image not found at path: {$fiestaHeroBgImagePath}");
}
$fiestaHeaderLogo = new UploadedFile(
$fiestaHeaderImagePath,
'futbol_infantil_header.png',
'image/png',
null,
true
);
$fiestaFooterLogo = new UploadedFile(
$fiestaFooterImagePath,
'futbol_infantil_footer.png',
'image/png',
null,
true
);
$fiestaHeroBgImage = new UploadedFile(
$fiestaHeroBgImagePath,
'futbol_infantil_hero.jpg',
'image/jpeg',
null,
true
);
Tenant::query()
->where('dominio', $fiestaDomain)
->delete();
$this->tenantService->create([
'codigo' => 'fiesta_futbol_infantil',
@@ -224,21 +107,110 @@ class TenantSeeder extends Seeder
'success_color' => '#198754',
'header_bg_color' => '#ffffff',
'footer_bg_color' => '#015327',
'header_logo' => $fiestaHeaderLogo,
'footer_logo' => $fiestaFooterLogo,
'hero_bg_image' => $fiestaHeroBgImage,
'hero_config' => [
'title_html' => '<strong>ASEGURÁ TU LUGAR</strong>',
'description_html' => '<strong>Comprá tu entrada oficial en segundos</strong> de forma 100% segura. Preparate para vivir la experiencia completa.',
'button_text' => 'Quiero mi entrada',
'button_href' => null,
],
'event_config' => [
'title' => 'FIESTA NACIONAL DEL FÚTBOL INFANTIL',
'location' => 'Sunchales, Santa Fe',
'dates' => ['2026-10-09', '2026-10-10', '2026-10-11', '2026-10-12'],
],
'header_logo' => $this->uploadedImage(
'images/futbol_infantil_header.png',
'futbol_infantil_header.png',
),
'footer_logo' => $this->uploadedImage(
'images/futbol_infantil_footer.png',
'futbol_infantil_footer.png',
),
'social_media' => self::SOCIAL_MEDIA,
'website_type_code' => 'onticket',
'extras' => [
'heroConfig' => [
'title_html' => '<h1>Fiesta Fútbol Infantil</h1>',
'description_html' => '<p>Viví una jornada inolvidable de fútbol infantil.</p>',
'button_text' => 'Comprar entradas',
'button_href' => '/tickets',
'background_image_id' => $this->uploadedImage(
'images/futbol_infantil_hero.jpg',
'futbol_infantil_hero.jpg',
),
],
'eventConfig' => [
'title' => 'Fiesta Fútbol Infantil',
'location' => 'Rosario, Santa Fe',
'dates_text' => '9, 10, 11 y 12 de Octubre 2026',
'dates' => [
'2026-12-05',
'2026-12-06',
],
],
],
]);
}
private function deleteTenant(string $codigo): void
{
$tenant = Tenant::query()
->where('codigo', $codigo)
->first();
if ($tenant === null) {
return;
}
$attachmentService = app(AttachmentService::class);
$extraAttachments = Attachment::query()
->where('path', 'like', 'tenants/%/extras/%')
->get()
->filter(
fn (Attachment $attachment): bool => str_starts_with(
$attachment->path,
"tenants/{$codigo}/extras/"
)
);
foreach ($extraAttachments as $attachment) {
try {
$attachmentService->delete($attachment);
} catch (Throwable) {
// Ignore cleanup errors while recreating demo data.
}
}
if ($tenant->headerLogo) {
try {
$attachmentService->delete($tenant->headerLogo);
} catch (Throwable) {
// Ignore cleanup errors while recreating demo data.
}
}
if ($tenant->footerLogo && $tenant->footer_logo_id !== $tenant->header_logo_id) {
try {
$attachmentService->delete($tenant->footerLogo);
} catch (Throwable) {
// Ignore cleanup errors while recreating demo data.
}
}
$tenant->delete();
}
private function uploadedImage(string $relativePath, string $filename): UploadedFile
{
$path = public_path($relativePath);
if (! file_exists($path)) {
throw new RuntimeException("Image not found at path: {$path}");
}
$mimeType = match (strtolower(pathinfo($filename, PATHINFO_EXTENSION))) {
'jpg', 'jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'webp' => 'image/webp',
default => 'image/png',
};
return new UploadedFile(
$path,
$filename,
$mimeType,
null,
true,
);
}
}

View File

@@ -0,0 +1,105 @@
<?php
namespace Database\Seeders;
use App\Domains\Tenant\Models\WebsiteType;
use Illuminate\Database\Seeder;
class WebsiteTypeSeeder extends Seeder
{
public function run(): void
{
$shopIt = WebsiteType::query()->updateOrCreate(
['codigo' => 'shopit'],
['nombre' => 'ShopIt'],
);
$shopIt->extras()->updateOrCreate(
['nombre' => 'carousel'],
[
'descripcion' => 'Listado de attachments que se muestran en el carousel principal.',
'is_required' => false,
'config_schema' => [
'request_rules' => [
'$' => 'required|array|max:10',
'$.*' => 'required|image_or_base64|distinct',
],
'transforms' => [
'$.*' => [
'handler' => 'attachment',
'attachment_type' => 'image',
],
],
'database_rules' => [
'$' => 'required|array',
'$.*' => 'required|integer|distinct|exists:attachments,id',
],
],
],
);
$onTicket = WebsiteType::query()->updateOrCreate(
['codigo' => 'onticket'],
['nombre' => 'OnTicket'],
);
$onTicket->extras()->updateOrCreate(
['nombre' => 'heroConfig'],
[
'descripcion' => 'Configuracion del hero principal del evento.',
'is_required' => false,
'config_schema' => [
'request_rules' => [
'$' => 'required|array',
'title_html' => 'nullable|string',
'description_html' => 'nullable|string',
'button_text' => 'nullable|string',
'button_href' => 'nullable|string',
'background_image_id' => 'nullable|image_or_base64',
],
'transforms' => [
'background_image_id' => [
'handler' => 'attachment',
'attachment_type' => 'image',
],
],
'database_rules' => [
'$' => 'required|array',
'title_html' => 'nullable|string',
'description_html' => 'nullable|string',
'button_text' => 'nullable|string',
'button_href' => 'nullable|string',
'background_image_id' => 'nullable|integer|exists:attachments,id',
],
],
],
);
$onTicket->extras()->updateOrCreate(
['nombre' => 'eventConfig'],
[
'descripcion' => 'Informacion principal del evento.',
'is_required' => false,
'config_schema' => [
'request_rules' => [
'$' => 'required|array',
'title' => 'nullable|string',
'location' => 'nullable|string',
'dates_text' => 'nullable|string|max:255',
'dates' => 'nullable|array',
'dates.*' => 'required|date_format:Y-m-d|distinct',
],
'transforms' => [],
'database_rules' => [
'$' => 'required|array',
'title' => 'nullable|string',
'location' => 'nullable|string',
'dates_text' => 'nullable|string|max:255',
'dates' => 'nullable|array',
'dates.*' => 'required|date_format:Y-m-d|distinct',
],
],
],
);
}
}

View File

@@ -94,9 +94,6 @@ return [
'schema_required' => 'The schema is required for static menus.',
'not_found' => 'The specified menu does not exist.',
],
'tenant' => [
'invalid_carousel_image' => 'The specified image does not exist or is not an image attachment.',
],
'errors' => [
'forbidden' => 'You do not have permission to perform this action.',
'not_found' => 'The requested resource was not found.',

View File

@@ -94,9 +94,6 @@ return [
'schema_required' => 'El schema es obligatorio para los menús estáticos.',
'not_found' => 'El menú indicado no existe.',
],
'tenant' => [
'invalid_carousel_image' => 'La imagen indicada no existe o no es un attachment de tipo imagen.',
],
'errors' => [
'forbidden' => 'No tienes permiso para realizar esta acción.',
'not_found' => 'El recurso solicitado no fue encontrado.',

View File

@@ -14,6 +14,37 @@ class MenuSeederTest extends TestCase
{
use RefreshDatabase;
public function test_it_seeds_the_admin_menus(): void
{
$tenant = $this->createTenant('admin_tenant');
$this->seed(MenuSeeder::class);
$expectedMenus = [
'admin.catalog' => ['Catálogo', '/admin/catalog'],
'admin.categories' => ['Categorías', '/admin/categories'],
'admin.combos' => ['Combos', '/admin/combos'],
'admin.event' => ['Eventos', '/admin/event'],
'admin.staff' => ['Staff', '/admin/staff'],
'admin.ventas' => ['Ventas', '/admin/ventas'],
];
$adminMenus = Menu::query()
->whereIn('code', array_keys($expectedMenus))
->get()
->keyBy('code');
$this->assertCount(count($expectedMenus), $adminMenus);
foreach ($expectedMenus as $code => [$label, $route]) {
$this->assertSame($label, $adminMenus->get($code)?->label);
$this->assertSame($route, $adminMenus->get($code)?->route);
$this->assertTrue(
$tenant->menues()->where('menues.code', $code)->exists()
);
}
}
public function test_it_seeds_the_account_menu_hierarchy(): void
{
$tenant = $this->createTenant('account_tenant');

View File

@@ -5,6 +5,7 @@ namespace Tests\Feature\Seeders;
use App\Domains\Tenant\Models\Tenant;
use Database\Seeders\SocialMediaSeeder;
use Database\Seeders\TenantSeeder;
use Database\Seeders\WebsiteTypeSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
@@ -13,38 +14,12 @@ class TenantSeederTest extends TestCase
{
use RefreshDatabase;
public function test_it_loads_the_sonder_main_carousel_images_in_order(): void
{
Storage::fake('s3');
$this->seed([
SocialMediaSeeder::class,
TenantSeeder::class,
]);
$tenant = Tenant::query()->where('codigo', 'sonder')->firstOrFail();
$images = $tenant->mainCarouselImages()->get();
$this->assertSame([
'01-urban-team.png',
'02-running-shoes.png',
'03-streetwear.png',
'04-football-training.png',
'05-activewear-essentials.png',
'06-city-runners.png',
], $images->pluck('filename')->all());
$this->assertSame([0, 1, 2, 3, 4, 5], $images->pluck('pivot.orden')->all());
foreach ($images as $image) {
Storage::disk('s3')->assertExists($image->path);
}
}
public function test_it_assigns_social_media_to_both_tenants_in_order(): void
{
Storage::fake('s3');
$this->seed([
WebsiteTypeSeeder::class,
SocialMediaSeeder::class,
TenantSeeder::class,
]);
@@ -69,4 +44,66 @@ class TenantSeederTest extends TestCase
$this->assertSame([0, 1, 2, 3], $socialMedia->pluck('pivot.orden')->all());
}
}
public function test_it_assigns_each_tenant_its_website_type_and_extras(): void
{
Storage::fake('s3');
$this->seed([
WebsiteTypeSeeder::class,
SocialMediaSeeder::class,
TenantSeeder::class,
]);
$sonder = Tenant::query()
->where('codigo', 'sonder')
->with('websiteExtras.websiteTypeExtra')
->sole();
$this->assertSame('shopit', $sonder->website_type_code);
$carousel = $sonder->websiteExtras
->firstWhere('websiteTypeExtra.nombre', 'carousel');
$this->assertNotNull($carousel);
$this->assertCount(6, $carousel->config);
foreach ($carousel->config as $attachmentId) {
$this->assertDatabaseHas('attachments', [
'id' => $attachmentId,
'type' => 'image',
]);
}
$fiesta = Tenant::query()
->where('codigo', 'fiesta_futbol_infantil')
->with('websiteExtras.websiteTypeExtra')
->sole();
$this->assertSame('onticket', $fiesta->website_type_code);
$extras = $fiesta->websiteExtras->keyBy('websiteTypeExtra.nombre');
$this->assertEqualsCanonicalizing(
['heroConfig', 'eventConfig'],
$extras->keys()->all(),
);
$heroConfig = $extras->get('heroConfig')->config;
$this->assertSame('<h1>Fiesta Fútbol Infantil</h1>', $heroConfig['title_html']);
$this->assertIsInt($heroConfig['background_image_id']);
$this->assertDatabaseHas('attachments', [
'id' => $heroConfig['background_image_id'],
'type' => 'image',
]);
$this->assertSame([
'title' => 'Fiesta Fútbol Infantil',
'location' => 'Rosario, Santa Fe',
'dates_text' => '9, 10, 11 y 12 de Octubre 2026',
'dates' => [
'2026-12-05',
'2026-12-06',
],
], $extras->get('eventConfig')->config);
}
}

View File

@@ -0,0 +1,103 @@
<?php
namespace Tests\Feature\Seeders;
use App\Domains\Tenant\Models\WebsiteType;
use Database\Seeders\WebsiteTypeSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class WebsiteTypeSeederTest extends TestCase
{
use RefreshDatabase;
public function test_it_seeds_website_types_and_their_config_schemas_idempotently(): void
{
$this->seed(WebsiteTypeSeeder::class);
$this->seed(WebsiteTypeSeeder::class);
$this->assertSame(2, WebsiteType::query()->count());
$shopIt = WebsiteType::query()
->where('codigo', 'shopit')
->with('extras')
->sole();
$this->assertSame('ShopIt', $shopIt->nombre);
$this->assertSame(['carousel'], $shopIt->extras->pluck('nombre')->all());
$this->assertSame([
'request_rules' => [
'$' => 'required|array|max:10',
'$.*' => 'required|image_or_base64|distinct',
],
'transforms' => [
'$.*' => [
'handler' => 'attachment',
'attachment_type' => 'image',
],
],
'database_rules' => [
'$' => 'required|array',
'$.*' => 'required|integer|distinct|exists:attachments,id',
],
], $shopIt->extras->sole()->config_schema);
$onTicket = WebsiteType::query()
->where('codigo', 'onticket')
->with('extras')
->sole();
$this->assertSame('OnTicket', $onTicket->nombre);
$this->assertEqualsCanonicalizing(
['heroConfig', 'eventConfig'],
$onTicket->extras->pluck('nombre')->all(),
);
$heroSchema = $onTicket->extras->firstWhere('nombre', 'heroConfig')->config_schema;
$this->assertSame([
'request_rules' => [
'$' => 'required|array',
'title_html' => 'nullable|string',
'description_html' => 'nullable|string',
'button_text' => 'nullable|string',
'button_href' => 'nullable|string',
'background_image_id' => 'nullable|image_or_base64',
],
'transforms' => [
'background_image_id' => [
'handler' => 'attachment',
'attachment_type' => 'image',
],
],
'database_rules' => [
'$' => 'required|array',
'title_html' => 'nullable|string',
'description_html' => 'nullable|string',
'button_text' => 'nullable|string',
'button_href' => 'nullable|string',
'background_image_id' => 'nullable|integer|exists:attachments,id',
],
], $heroSchema);
$eventSchema = $onTicket->extras->firstWhere('nombre', 'eventConfig')->config_schema;
$this->assertSame([
'request_rules' => [
'$' => 'required|array',
'title' => 'nullable|string',
'location' => 'nullable|string',
'dates_text' => 'nullable|string|max:255',
'dates' => 'nullable|array',
'dates.*' => 'required|date_format:Y-m-d|distinct',
],
'transforms' => [],
'database_rules' => [
'$' => 'required|array',
'title' => 'nullable|string',
'location' => 'nullable|string',
'dates_text' => 'nullable|string|max:255',
'dates' => 'nullable|array',
'dates.*' => 'required|date_format:Y-m-d|distinct',
],
], $eventSchema);
}
}

View File

@@ -0,0 +1,192 @@
<?php
namespace Tests\Feature\Tenant;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Services\TenantInformationService;
use Database\Seeders\WebsiteTypeSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
class StoreTenantWithExtrasTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
Storage::fake('s3');
$this->seed(WebsiteTypeSeeder::class);
}
public function test_it_creates_a_tenant_and_validates_and_stores_its_website_extras(): void
{
$response = $this->postJson('/api/tenants', array_merge($this->tenantData(), [
'website_type_code' => 'onticket',
'extras' => [
'eventConfig' => [
'title' => 'Festival',
'location' => 'Buenos Aires',
'dates_text' => '10 y 11 de octubre de 2026',
'dates' => ['2026-10-10', '2026-10-11'],
],
],
]));
$response
->assertCreated()
->assertJsonPath('data.website_type_code', 'onticket')
->assertJsonPath('data.website_type.codigo', 'onticket')
->assertJsonPath('data.extras.eventConfig.title', 'Festival');
$tenant = Tenant::query()->where('codigo', 'festival')->sole();
$this->assertDatabaseHas('websites_extras', [
'website_code' => $tenant->codigo,
]);
$this->assertSame(
[
'title' => 'Festival',
'location' => 'Buenos Aires',
'dates_text' => '10 y 11 de octubre de 2026',
'dates' => ['2026-10-10', '2026-10-11'],
],
$tenant->websiteExtras()->sole()->config
);
}
public function test_it_rejects_an_extra_not_supported_by_the_selected_website_type(): void
{
$this->postJson('/api/tenants', array_merge($this->tenantData(), [
'website_type_code' => 'shopit',
'extras' => [
'eventConfig' => [
'title' => 'Not supported',
],
],
]))
->assertUnprocessable()
->assertJsonValidationErrors(['extras']);
$this->assertDatabaseMissing('tenants', ['codigo' => 'festival']);
}
public function test_it_applies_the_extra_schema_rules(): void
{
$this->postJson('/api/tenants', array_merge($this->tenantData(), [
'website_type_code' => 'onticket',
'extras' => [
'eventConfig' => [
'dates' => ['not-a-date'],
],
],
]))
->assertUnprocessable()
->assertJsonValidationErrors(['extras.eventConfig.dates.0']);
$this->assertDatabaseMissing('tenants', ['codigo' => 'festival']);
}
public function test_it_transforms_extra_images_to_attachment_ids(): void
{
$image = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';
$response = $this->postJson('/api/tenants', array_merge($this->tenantData(), [
'website_type_code' => 'shopit',
'extras' => [
'carousel' => [$image],
],
]));
$response->assertCreated();
$tenant = Tenant::query()
->where('codigo', 'festival')
->sole();
$config = $tenant->websiteExtras()
->sole()
->config;
$this->assertCount(1, $config);
$this->assertIsInt($config[0]);
$this->assertDatabaseHas('attachments', [
'id' => $config[0],
'type' => 'image',
]);
$attachment = Attachment::query()->findOrFail($config[0]);
$carouselUrl = $response->json('data.extras.carousel.0');
$this->assertIsString($carouselUrl);
$this->assertStringContainsString($attachment->key, $carouselUrl);
app(TenantInformationService::class)->load($tenant);
$this->assertInstanceOf(
Attachment::class,
$tenant->websiteExtras->sole()->resolvedConfig()[0]
);
}
public function test_it_returns_scalar_attachment_fields_as_temporary_urls(): void
{
$image = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';
$response = $this->postJson('/api/tenants', array_merge($this->tenantData(), [
'website_type_code' => 'onticket',
'extras' => [
'heroConfig' => [
'title_html' => '<h1>Festival</h1>',
'background_image_id' => $image,
],
],
]));
$response->assertCreated();
$heroConfig = Tenant::query()
->where('codigo', 'festival')
->sole()
->websiteExtras()
->whereHas(
'websiteTypeExtra',
fn ($query) => $query->where('nombre', 'heroConfig')
)
->sole()
->config;
$attachment = Attachment::query()->findOrFail($heroConfig['background_image_id']);
$backgroundUrl = $response->json('data.extras.heroConfig.background_image_id');
$this->assertIsString($backgroundUrl);
$this->assertStringContainsString($attachment->key, $backgroundUrl);
}
/**
* @return array<string, mixed>
*/
private function tenantData(): array
{
$image = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';
return [
'codigo' => 'festival',
'nombre' => 'Festival',
'dominio' => 'festival.test',
'primary_color' => '#111111',
'secondary_color' => '#222222',
'danger_color' => '#333333',
'success_color' => '#444444',
'header_bg_color' => '#ffffff',
'footer_bg_color' => '#ffffff',
'header_logo' => $image,
'footer_logo' => $image,
'search_product_layout' => 'column_with_image',
'search_group_layout' => 'paginated',
'search_items_per_page' => 12,
];
}
}

View File

@@ -1,191 +0,0 @@
<?php
namespace Tests\Feature\Tenant;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Tests\TestCase;
class TenantMainCarouselImagesTest extends TestCase
{
use RefreshDatabase;
public function test_a_tenant_has_ordered_main_carousel_images(): void
{
$tenant = $this->createTenant();
$firstAttachment = $this->createAttachment('first.png');
$secondAttachment = $this->createAttachment('second.png');
$tenant->mainCarouselImages()->attach([
$secondAttachment->id => ['orden' => 2],
$firstAttachment->id => ['orden' => 1],
]);
$attachments = $tenant->mainCarouselImages()->get();
$this->assertCount(2, $attachments);
$this->assertTrue($attachments[0]->is($firstAttachment));
$this->assertTrue($attachments[1]->is($secondAttachment));
$this->assertSame([1, 2], $attachments->pluck('pivot.orden')->all());
}
public function test_bootstrap_returns_all_main_carousel_image_urls_in_order(): void
{
$tenant = $this->createTenant();
$firstAttachment = $this->createAttachment('first.png');
$secondAttachment = $this->createAttachment('second.png');
$tenant->mainCarouselImages()->attach([
$secondAttachment->id => ['orden' => 20],
$firstAttachment->id => ['orden' => 10],
]);
$response = $this->getJson('/api/tenants/bootstrap/acme.com');
$response
->assertOk()
->assertJsonCount(2, 'data.main_carousel_images');
$urls = $response->json('data.main_carousel_images');
$this->assertStringContainsString($firstAttachment->key, $urls[0]);
$this->assertStringContainsString($secondAttachment->key, $urls[1]);
}
public function test_show_returns_an_empty_main_carousel_images_array_when_the_tenant_has_no_images(): void
{
$tenant = $this->createTenant();
$this->getJson("/api/tenants/{$tenant->codigo}")
->assertOk()
->assertJsonPath('data.main_carousel_images', []);
}
public function test_store_uploads_and_attaches_main_carousel_images_in_request_order(): void
{
Storage::fake('s3');
$headerLogo = $this->createAttachment('header.png');
$footerLogo = $this->createAttachment('footer.png');
$response = $this
->withHeader('Accept', 'application/json')
->post('/api/tenants', [
...$this->tenantPayload(),
'header_logo' => $headerLogo->key,
'footer_logo' => $footerLogo->key,
'main_carousel_images' => [
UploadedFile::fake()->image('first-carousel.png', 1200, 300),
UploadedFile::fake()->image('second-carousel.png', 1200, 300),
],
]);
$response
->assertCreated()
->assertJsonCount(2, 'data.main_carousel_images');
$tenant = Tenant::query()->where('codigo', 'new-acme')->firstOrFail();
$images = $tenant->mainCarouselImages()->get();
$this->assertSame(
['first-carousel.png', 'second-carousel.png'],
$images->pluck('filename')->all()
);
$this->assertSame([0, 1], $images->pluck('pivot.orden')->all());
Storage::disk('s3')->assertExists($images[0]->path);
Storage::disk('s3')->assertExists($images[1]->path);
}
public function test_update_replaces_and_can_clear_main_carousel_images(): void
{
$tenant = $this->createTenant();
$oldImage = $this->createAttachment('old.png');
$firstImage = $this->createAttachment('first.png');
$secondImage = $this->createAttachment('second.png');
$tenant->mainCarouselImages()->attach($oldImage->id, ['orden' => 0]);
$this->putJson("/api/tenants/{$tenant->codigo}", [
'main_carousel_images' => [$secondImage->key, $firstImage->key],
])
->assertOk()
->assertJsonCount(2, 'data.main_carousel_images');
$this->assertSame(
[$secondImage->id, $firstImage->id],
$tenant->mainCarouselImages()->pluck('attachments.id')->all()
);
$this->assertDatabaseMissing('tenant_main_carousel_images', [
'tenant_id' => $tenant->id,
'attachment_id' => $oldImage->id,
]);
$this->putJson("/api/tenants/{$tenant->codigo}", [
'main_carousel_images' => [],
])
->assertOk()
->assertJsonPath('data.main_carousel_images', []);
$this->assertDatabaseMissing('tenant_main_carousel_images', [
'tenant_id' => $tenant->id,
]);
}
/**
* @return array<string, string>
*/
private function tenantPayload(): array
{
return [
'codigo' => 'new-acme',
'nombre' => 'New Acme',
'dominio' => 'new-acme.com',
'primary_color' => '#111111',
'secondary_color' => '#222222',
'danger_color' => '#333333',
'success_color' => '#444444',
'header_bg_color' => '#ffffff',
'footer_bg_color' => '#ffffff',
];
}
private function createTenant(): Tenant
{
$headerLogo = $this->createAttachment('header.png');
$footerLogo = $this->createAttachment('footer.png');
return Tenant::query()->create([
'codigo' => 'acme',
'nombre' => 'Acme',
'dominio' => 'acme.com',
'primary_color' => '#111111',
'secondary_color' => '#222222',
'danger_color' => '#333333',
'success_color' => '#444444',
'header_bg_color' => '#ffffff',
'footer_bg_color' => '#ffffff',
'header_logo_id' => $headerLogo->id,
'footer_logo_id' => $footerLogo->id,
]);
}
private function createAttachment(string $filename): Attachment
{
$key = (string) Str::uuid();
return Attachment::query()->create([
'key' => $key,
'path' => "tenants/main-carousel/{$key}.png",
'filename' => $filename,
'type' => AttachmentType::Image,
'mime_type' => 'image/png',
'extension' => 'png',
'size' => 100,
]);
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace Tests\Feature\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Schema;
use Tests\TestCase;
class TenantPresentationConfigRemovalTest extends TestCase
{
use RefreshDatabase;
public function test_legacy_presentation_config_is_not_part_of_tenants(): void
{
$this->assertFalse(Schema::hasTable('tenant_main_carousel_images'));
$this->assertFalse(Schema::hasColumn('tenants', 'hero_bg_image_id'));
$this->assertFalse(Schema::hasColumn('tenants', 'hero_config'));
$this->assertFalse(Schema::hasColumn('tenants', 'event_config'));
}
}

View File

@@ -0,0 +1,125 @@
<?php
namespace Tests\Feature\Tenant;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Models\WebsiteType;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Schema;
use Tests\TestCase;
class WebsiteExtrasTest extends TestCase
{
use RefreshDatabase;
public function test_website_extra_tables_have_the_expected_columns(): void
{
$this->assertTrue(Schema::hasColumn('tenants', 'website_type_code'));
$this->assertEqualsCanonicalizing([
'id',
'codigo',
'nombre',
'created_at',
'updated_at',
], Schema::getColumnListing('website_type'));
$this->assertEqualsCanonicalizing([
'id',
'website_type_code',
'nombre',
'descripcion',
'is_required',
'config_schema',
'created_at',
'updated_at',
], Schema::getColumnListing('website_type_extras'));
$this->assertEqualsCanonicalizing([
'id',
'website_code',
'website_type_extra_id',
'config',
'created_at',
'updated_at',
], Schema::getColumnListing('websites_extras'));
}
public function test_models_map_the_diagram_relations_and_casts(): void
{
$type = WebsiteType::query()->create([
'codigo' => 'store',
'nombre' => 'Tienda',
]);
$typeExtra = $type->extras()->create([
'nombre' => 'WhatsApp',
'descripcion' => 'Configuracion del canal de WhatsApp',
'is_required' => true,
'config_schema' => [
'type' => 'object',
'required' => ['phone'],
],
]);
$tenant = $this->createTenant();
$tenant->websiteType()->associate($type)->save();
$websiteExtra = $tenant->websiteExtras()->create([
'website_type_extra_id' => $typeExtra->id,
'config' => ['phone' => '+5491112345678'],
]);
$this->assertTrue($type->extras()->firstOrFail()->is($typeExtra));
$this->assertSame($type->codigo, $typeExtra->website_type_code);
$this->assertTrue($type->tenants()->firstOrFail()->is($tenant));
$this->assertTrue($tenant->websiteType()->firstOrFail()->is($type));
$this->assertSame($type->codigo, $tenant->website_type_code);
$this->assertTrue($typeExtra->websiteType()->firstOrFail()->is($type));
$this->assertTrue($typeExtra->websiteExtras()->firstOrFail()->is($websiteExtra));
$this->assertTrue($websiteExtra->website()->firstOrFail()->is($tenant));
$this->assertTrue($websiteExtra->websiteTypeExtra()->firstOrFail()->is($typeExtra));
$this->assertTrue($typeExtra->is_required);
$this->assertSame([
'type' => 'object',
'required' => ['phone'],
], $typeExtra->config_schema);
$this->assertSame(['phone' => '+5491112345678'], $websiteExtra->config);
}
public function test_deleting_a_type_cascades_its_definitions_and_website_values(): void
{
$type = WebsiteType::query()->create([
'codigo' => 'store',
'nombre' => 'Tienda',
]);
$typeExtra = $type->extras()->create([
'nombre' => 'WhatsApp',
'descripcion' => 'Configuracion del canal de WhatsApp',
'config_schema' => ['type' => 'object'],
]);
$websiteExtra = $this->createTenant()->websiteExtras()->create([
'website_type_extra_id' => $typeExtra->id,
'config' => ['phone' => '+5491112345678'],
]);
$type->delete();
$this->assertDatabaseMissing('website_type_extras', ['id' => $typeExtra->id]);
$this->assertDatabaseMissing('websites_extras', ['id' => $websiteExtra->id]);
}
private function createTenant(): Tenant
{
return Tenant::query()->create([
'codigo' => 'acme',
'nombre' => 'Acme',
'dominio' => 'acme.com',
'primary_color' => '#111111',
'secondary_color' => '#222222',
'danger_color' => '#333333',
'success_color' => '#444444',
'header_bg_color' => '#ffffff',
'footer_bg_color' => '#ffffff',
'header_logo_id' => 1,
'footer_logo_id' => 2,
]);
}
}