39 Commits

Author SHA1 Message Date
c4b317d5fc feat: Implement value change logging functionality with models, traits, and migration; add tests for logging behavior and value change mapping 2026-08-03 15:43:50 -03:00
3b2977a330 feat: Enhance tenant website extras by adding detailed description HTML for hero and additional info configurations; update related tests for validation 2026-08-03 15:29:14 -03:00
3b36abd46d feat: Refactor event form functionality by removing social media data from AdminAppBootstrapResource and AdminAppBootstrapService; add EventFormController, EventFormResource, and EventFormService; implement routes and tests for event form 2026-08-03 14:02:08 -03:00
12697c2268 feat: Refactor bootstrap functionality by adding AdminApp and Tenant controllers, requests, resources, and services; remove deprecated event form components 2026-08-03 13:37:37 -03:00
f4638bc984 feat: Implement event management functionality with API endpoints and validation 2026-08-03 13:32:31 -03:00
c3713c62a6 feat: Add event management to tenant and catalog
- Introduced Event and EventDate models with relationships to Tenant and CatalogItem.
- Added active_event_id to Tenant model to track the currently active event.
- Updated TenantResource to include active event details in the response.
- Enhanced Ticket model to link to CatalogItem and Variant, allowing for event-specific ticketing.
- Implemented migrations to create events and link them to catalog items and variants.
- Updated seeders to populate events and their associated dates for the Fiesta Futbol Infantil tenant.
- Modified Ticket generation logic to respect event dates over standard ticket dates.
- Added tests for event and ticket functionalities, ensuring proper relationships and date handling.
2026-08-03 12:01:20 -03:00
4a51f3afde feat(website-extras): enhance toggle functionality and update related tests; add additional info configuration to tenant extras 2026-08-03 09:10:50 -03:00
f1df6a5918 feat(seeder): update MenuSeeder and tests to reflect new admin menu structure; change border color in WebsiteTypeSeeder 2026-08-03 09:07:49 -03:00
dbeaf19513 feat(auth): implement AdminAppMeController and AdminAppMeResource; add routes and tests for user context retrieval 2026-07-31 16:11:47 -03:00
dd76d5d951 feat(website-type): add footer logo support in WebsiteType model, controller, and resource; update seeder and tests 2026-07-31 14:16:58 -03:00
f603a82b5e feat(website-type): implement BootstrapWebsiteTypeController and related request/resource for domain-based bootstrapping 2026-07-31 13:39:31 -03:00
b478c23f3b feat(website-type): add new color fields and update related methods in WebsiteType model and service 2026-07-31 12:55:40 -03:00
6858b387c3 feat(website-type): add 'dominio' field to WebsiteType model and update related tests 2026-07-31 12:06:27 -03:00
893bea1492 feat(website-type): add login_header_footer_color field and update related tests 2026-07-31 12:06:13 -03:00
ec1d80dff2 feat(seeder): update image paths in ProductCatalogFromImagesSeeder and TenantSeeder, add new catalog images 2026-07-31 11:45:29 -03:00
3968a10f6a feat(website-type): add presentation fields and site logo relationship to WebsiteType model 2026-07-31 11:39:17 -03:00
cf2beb2ff5 feat(auth): implement AdminApp login functionality with controller, request, routes, and tests 2026-07-31 10:47:55 -03:00
484fa204b3 feat(tenant): add BootstrapTenantController and corresponding tests for tenant bootstrapping functionality 2026-07-31 10:36:46 -03:00
6dd057874a feat(website-extras): add showExtra method and resource for individual website extras, update routes and tests 2026-07-31 09:51:27 -03:00
40cbac17c6 feat(website-extras): implement toggle functionality for website extras and update related tests 2026-07-31 09:47:56 -03:00
45e56c43a6 feat(website-extras): add 'is_enabled' column to websites_extras table and update model and tests 2026-07-31 09:38:30 -03:00
cbb7b1c3a1 feat(database): remove 'database_rules' from WebsiteTypeExtra configurations and related tests 2026-07-31 09:28:12 -03:00
6b3a12b624 feat(website-extras): refactor WebsiteExtra management to use 'codigo' for identification, update routes, requests, and services 2026-07-31 09:27:35 -03:00
40a7dece11 feat(authorization): implement WebsiteExtra management with controller, request, resource, service, routes, middleware, and tests 2026-07-31 09:19:25 -03:00
5ec65ce3d3 fix(authorization): rename pivot table from 'menues_roles' to 'roles_menues' and update related references 2026-07-31 08:35:45 -03:00
b7e1332b8c feat(authorization): refactor role management to use RoleCode enum, update migrations, seeders, and tests 2026-07-31 08:32:00 -03:00
a087a511e0 feat(authorization): filter tenant menus by user roles in bootstrap process 2026-07-31 08:23:18 -03:00
a20b1713d3 feat(authorization): establish many-to-many relationship between roles and menus, add migration and seeder updates 2026-07-30 16:54:25 -03:00
d56d387933 feat(authorization): add role and tenant codes to users, implement validation logic, and create tests 2026-07-30 16:37:37 -03:00
cba32e90e7 feat(authorization): implement AuthorizationSeeder with roles and permissions, add tests 2026-07-30 16:37:37 -03:00
a674bcfabc feat(authorization): add roles and permissions models, migration, and tests 2026-07-30 16:37:20 -03:00
ace3f136e4 refactor(menu): add admin menu items and corresponding test cases 2026-07-30 16:36:43 -03:00
2cc72be850 refactor(website): add 'dates_text' field to event configuration and update related tests 2026-07-29 16:23:24 -03:00
8e3ee7eff6 refactor(tenant): introduce TenantInformationService for loading tenant data and resolving website extras 2026-07-29 15:48:01 -03:00
27d4f9fac6 feat(tenant): implement website extras functionality and validation in tenant creation 2026-07-29 15:16:33 -03:00
9e3163b74f refactor(website): update relationships and migration to use 'website_type_code' instead of 'website_type' 2026-07-29 15:03:31 -03:00
b9ad2e589f refactor(tenant): remove legacy presentation configuration and related carousel images 2026-07-29 14:54:57 -03:00
5416c0fd61 feat(seeder): add WebsiteTypeSeeder and update DatabaseSeeder to include it 2026-07-29 14:42:03 -03:00
04bf03fc2e feat(website): add website type and extras models with migration and tests 2026-07-29 14:09:47 -03:00
173 changed files with 6445 additions and 791 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

@@ -0,0 +1,42 @@
<?php
namespace App\Domains\Auth\Controllers;
use App\Domains\Auth\Requests\AdminAppLoginRequest;
use App\Domains\Auth\Resources\UserResource;
use App\Domains\Auth\Services\PasswordLoginService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
class AdminAppLoginController extends Controller
{
public function __construct(
private readonly PasswordLoginService $passwordLoginService,
) {}
public function __invoke(AdminAppLoginRequest $request): JsonResponse
{
$credentials = $request->validated();
$user = $this->passwordLoginService->authenticateAdminApp(
$credentials['email'],
$credentials['password'],
$request->ip(),
$request->userAgent(),
);
$expirationMinutes = (int) config('sanctum.expiration');
$token = $user->createToken(
'adminapp-token',
['adminapp'],
now()->addMinutes($expirationMinutes),
)->plainTextToken;
return response()->json([
'code' => 'auth.login_success',
'message' => __('api.auth.login_success'),
'token' => $token,
'token_type' => 'Bearer',
'user' => UserResource::make($user),
]);
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace App\Domains\Auth\Controllers;
use App\Domains\Auth\Models\User;
use App\Domains\Auth\Resources\AdminAppMeResource;
use App\Domains\Auth\Services\AdminAppContextService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class AdminAppMeController extends Controller
{
public function __construct(
private readonly AdminAppContextService $adminAppContextService,
) {}
public function __invoke(Request $request): AdminAppMeResource
{
/** @var User $user */
$user = $request->user();
return AdminAppMeResource::make(
$this->adminAppContextService->load($user)
);
}
}

View File

@@ -7,7 +7,7 @@ use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable(['user_id', 'codigo', 'reason', 'status'])]
#[Fillable(['user_id', 'codigo', 'status'])]
#[Hidden(['codigo'])]
class ResetPasswordAttempt extends Model
{

View File

@@ -2,22 +2,30 @@
namespace App\Domains\Auth\Models;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Authorization\Models\Role;
use App\Domains\Tenant\Models\Tenant;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
#[Fillable(['nombre_apellido', 'email', 'password', 'dni', 'telefono', 'google_id'])]
#[Fillable(['nombre_apellido', 'email', 'password', 'dni', 'telefono', 'google_id', 'rol_codigo', 'tenant_codigo'])]
#[Hidden(['password', 'remember_token'])]
class User extends Authenticatable
{
/** @use HasFactory<UserFactory> */
use HasApiTokens, HasFactory, Notifiable;
protected $attributes = [
'rol_codigo' => RoleCode::User->value,
];
protected static function newFactory(): UserFactory
{
return UserFactory::new();
@@ -35,6 +43,22 @@ class User extends Authenticatable
return $this->hasMany(LoginAttempt::class);
}
/**
* @return BelongsTo<Role, $this>
*/
public function role(): BelongsTo
{
return $this->belongsTo(Role::class, 'rol_codigo', 'codigo');
}
/**
* @return BelongsTo<Tenant, $this>
*/
public function tenant(): BelongsTo
{
return $this->belongsTo(Tenant::class, 'tenant_codigo', 'codigo');
}
/**
* @return array<string, string>
*/

View File

@@ -0,0 +1,36 @@
<?php
namespace App\Domains\Auth\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Str;
class AdminAppLoginRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
protected function prepareForValidation(): void
{
$email = $this->input('email');
if (is_string($email)) {
$this->merge([
'email' => Str::lower(trim($email)),
]);
}
}
/**
* @return array<string, mixed>
*/
public function rules(): array
{
return [
'email' => ['required', 'string', 'email', 'max:255'],
'password' => ['required', 'string'],
];
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace App\Domains\Auth\Resources;
use App\Domains\Auth\Models\User;
use App\Domains\Tenant\Resources\TenantResource;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* @mixin User
*/
class AdminAppMeResource extends JsonResource
{
/**
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'user' => UserResource::make($this->resource),
'tenant' => TenantResource::make($this->tenant),
];
}
}

View File

@@ -2,11 +2,12 @@
namespace App\Domains\Auth\Resources;
use App\Domains\Auth\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* @mixin \App\Domains\Auth\Models\User
* @mixin User
*/
class UserResource extends JsonResource
{
@@ -21,6 +22,8 @@ class UserResource extends JsonResource
'email' => $this->email,
'dni' => $this->dni,
'telefono' => $this->telefono,
'rol_codigo' => $this->rol_codigo,
'tenant_codigo' => $this->tenant_codigo,
];
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace App\Domains\Auth\Services;
use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode;
class AdminAppContextService
{
public function load(User $user): User
{
$tenant = $user->tenant()
->with([
'menues' => fn ($query) => $query
->whereHas(
'roles',
fn ($query) => $query->where('codigo', RoleCode::AdminApp->value)
),
])
->firstOrFail();
$user->setRelation('tenant', $tenant);
return $user;
}
}

View File

@@ -5,18 +5,14 @@ namespace App\Domains\Auth\Services;
use App\Domains\Auth\Exceptions\AccountLockedException;
use App\Domains\Auth\Models\LoginAttempt;
use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
class PasswordLoginService
{
public function __construct(
private readonly ResetPasswordAttemptService $resetPasswordAttemptService,
) {}
/**
* @throws AccountLockedException
* @throws ValidationException
@@ -27,6 +23,48 @@ class PasswordLoginService
string $tenantCode,
?string $ipAddress,
?string $userAgent,
): User {
return $this->authenticateUser(
$email,
$password,
$tenantCode,
$ipAddress,
$userAgent,
);
}
/**
* Authenticate a tenant-bound AdminApp user without requiring the caller
* to know their tenant code beforehand.
*
* @throws AccountLockedException
* @throws ValidationException
*/
public function authenticateAdminApp(
string $email,
string $password,
?string $ipAddress,
?string $userAgent,
): User {
return $this->authenticateUser(
$email,
$password,
null,
$ipAddress,
$userAgent,
RoleCode::AdminApp,
true,
);
}
private function authenticateUser(
string $email,
string $password,
?string $tenantCode,
?string $ipAddress,
?string $userAgent,
RoleCode $requiredRole = RoleCode::User,
bool $requiresTenant = false,
): User {
$normalizedEmail = mb_strtolower(trim($email));
$now = CarbonImmutable::now();
@@ -39,17 +77,25 @@ class PasswordLoginService
$ipAddress,
$userAgent,
$now,
$requiredRole,
$requiresTenant,
): array {
$user = User::query()
->where('email', $normalizedEmail)
->where('rol_codigo', $requiredRole->value)
->when(
$requiresTenant,
fn ($query) => $query->whereNotNull('tenant_codigo'),
)
->lockForUpdate()
->first();
$attemptTenantCode = $tenantCode ?? $user?->tenant_codigo;
if ($user?->locked_until?->isFuture()) {
$this->recordAttempt(
$user,
$normalizedEmail,
$tenantCode,
$attemptTenantCode,
LoginAttempt::OUTCOME_ACCOUNT_LOCKED,
$ipAddress,
$userAgent,
@@ -72,7 +118,7 @@ class PasswordLoginService
if ($user === null || ! Hash::check($password, $user->password)) {
if ($user !== null) {
$this->registerFailure($user, $now, $tenantCode);
$this->registerFailure($user, $now);
}
$outcome = $user?->locked_until?->isFuture()
@@ -81,7 +127,7 @@ class PasswordLoginService
$this->recordAttempt(
$user,
$normalizedEmail,
$tenantCode,
$attemptTenantCode,
$outcome,
$ipAddress,
$userAgent,
@@ -105,7 +151,7 @@ class PasswordLoginService
$this->recordAttempt(
$user,
$normalizedEmail,
$tenantCode,
$attemptTenantCode,
LoginAttempt::OUTCOME_SUCCESS,
$ipAddress,
$userAgent,
@@ -131,7 +177,7 @@ class PasswordLoginService
return $result['user'];
}
private function registerFailure(User $user, CarbonImmutable $now, string $tenantCode): void
private function registerFailure(User $user, CarbonImmutable $now): void
{
$windowMinutes = max(1, (int) config('login-security.attempt_window_minutes'));
$maxAttempts = max(1, (int) config('login-security.max_attempts'));
@@ -143,8 +189,6 @@ class PasswordLoginService
? $user->failed_login_attempts + 1
: 1;
$previousAttempts = $user->failed_login_attempts;
$user->forceFill([
'failed_login_attempts' => $attempts,
'last_failed_login_at' => $now,
@@ -152,23 +196,12 @@ class PasswordLoginService
? $now->addMinutes($lockMinutes)
: null,
])->save();
if ($attempts >= $maxAttempts && $previousAttempts < $maxAttempts) {
try {
$this->resetPasswordAttemptService->createForEmail($user->email, $tenantCode, 'account_locked');
} catch (\Throwable $e) {
Log::error('Failed to trigger reset password on account lock', [
'user_id' => $user->id,
'exception' => $e
]);
}
}
}
private function recordAttempt(
?User $user,
string $normalizedEmail,
string $tenantCode,
?string $tenantCode,
string $outcome,
?string $ipAddress,
?string $userAgent,

View File

@@ -11,12 +11,12 @@ use Throwable;
class ResetPasswordAttemptService
{
public function createForEmail(string $email, string $tenantCode, string $reason = 'manual'): void
public function createForEmail(string $email, string $tenantCode): void
{
$emailFingerprint = $this->emailFingerprint($email);
try {
$attemptId = DB::transaction(function () use ($email, $emailFingerprint, $reason): ?int {
$attemptId = DB::transaction(function () use ($email, $emailFingerprint): ?int {
$user = User::query()
->where('email', $email)
->lockForUpdate()
@@ -39,7 +39,6 @@ class ResetPasswordAttemptService
$attempt = $user->resetPasswordAttempts()->create([
'codigo' => $this->generateCode(),
'reason' => $reason,
'status' => ResetPasswordAttempt::STATUS_PENDING,
]);

View File

@@ -0,0 +1,11 @@
<?php
use App\Domains\Auth\Controllers\AdminAppLoginController;
use App\Domains\Auth\Controllers\AdminAppMeController;
use Illuminate\Support\Facades\Route;
Route::prefix('v1/adminapp')->group(function (): void {
Route::post('login', AdminAppLoginController::class)->middleware('throttle:login');
Route::middleware(['auth:sanctum', 'adminapp.tenant'])
->get('me', AdminAppMeController::class);
});

View File

@@ -23,3 +23,5 @@ Route::post('/auth/google/exchange', GoogleTokenExchangeController::class);
Route::middleware('auth:sanctum')->post('/logout', LogoutController::class);
Route::middleware('auth:sanctum')->get('/me', MeController::class);
Route::middleware('auth:sanctum')->put('/me', UpdateProfileController::class);
require __DIR__.'/adminapp.php';

View File

@@ -0,0 +1,10 @@
<?php
namespace App\Domains\Authorization\Enums;
enum RoleCode: string
{
case Admin = 'admin';
case AdminApp = 'adminapp';
case User = 'user';
}

View File

@@ -0,0 +1,32 @@
<?php
namespace App\Domains\Authorization\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Permission extends Model
{
protected $table = 'permisos';
protected $fillable = [
'codigo',
'nombre',
'descripcion',
];
/**
* @return BelongsToMany<Role, $this>
*/
public function roles(): BelongsToMany
{
return $this->belongsToMany(
Role::class,
'roles_permisos',
'codigo_permiso',
'rol_codigo',
'codigo',
'codigo'
)->withTimestamps();
}
}

View File

@@ -0,0 +1,59 @@
<?php
namespace App\Domains\Authorization\Models;
use App\Domains\Auth\Models\User;
use App\Domains\Menu\Models\Menu;
use App\Domains\Menu\Models\MenuRole;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Role extends Model
{
protected $table = 'roles';
protected $fillable = [
'codigo',
'nombre',
'descripcion',
];
/**
* @return BelongsToMany<Permission, $this>
*/
public function permissions(): BelongsToMany
{
return $this->belongsToMany(
Permission::class,
'roles_permisos',
'rol_codigo',
'codigo_permiso',
'codigo',
'codigo'
)->withTimestamps();
}
/**
* @return HasMany<User, $this>
*/
public function users(): HasMany
{
return $this->hasMany(User::class, 'rol_codigo', 'codigo');
}
/**
* @return BelongsToMany<Menu, $this>
*/
public function menus(): BelongsToMany
{
return $this->belongsToMany(
Menu::class,
'roles_menues',
'rol_codigo',
'menu_codigo',
'codigo',
'code'
)->using(MenuRole::class);
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace App\Domains\Authorization\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class RolePermission extends Model
{
protected $table = 'roles_permisos';
protected $fillable = [
'codigo_permiso',
'rol_codigo',
];
/**
* @return BelongsTo<Permission, $this>
*/
public function permission(): BelongsTo
{
return $this->belongsTo(Permission::class, 'codigo_permiso', 'codigo');
}
/**
* @return BelongsTo<Role, $this>
*/
public function role(): BelongsTo
{
return $this->belongsTo(Role::class, 'rol_codigo', 'codigo');
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace App\Domains\Bootstrap\Controllers;
use App\Domains\Bootstrap\Requests\AdminAppBootstrapRequest;
use App\Domains\Bootstrap\Resources\AdminAppBootstrapResource;
use App\Domains\Bootstrap\Services\AdminAppBootstrapService;
use App\Http\Controllers\Controller;
class AdminAppBootstrapController extends Controller
{
public function __construct(protected AdminAppBootstrapService $bootstrapService) {}
public function __invoke(AdminAppBootstrapRequest $request): AdminAppBootstrapResource
{
return AdminAppBootstrapResource::make(
$this->bootstrapService->get((string) $request->validated('dominio'))
);
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace App\Domains\Bootstrap\Controllers;
use App\Domains\Bootstrap\Requests\TenantBootstrapRequest;
use App\Domains\Bootstrap\Services\TenantBootstrapService;
use App\Domains\Tenant\Resources\TenantResource;
use App\Http\Controllers\Controller;
class TenantBootstrapController extends Controller
{
public function __construct(protected TenantBootstrapService $bootstrapService) {}
public function __invoke(TenantBootstrapRequest $request): TenantResource
{
return TenantResource::make(
$this->bootstrapService->get((string) $request->validated('dominio'))
);
}
}

View File

@@ -0,0 +1,5 @@
<?php
namespace App\Domains\Bootstrap\Requests;
class AdminAppBootstrapRequest extends TenantBootstrapRequest {}

View File

@@ -1,12 +1,12 @@
<?php
namespace App\Domains\Tenant\Requests;
namespace App\Domains\Bootstrap\Requests;
use App\Domains\Tenant\Support\TenantDomainNormalizer;
use Closure;
use Illuminate\Foundation\Http\FormRequest;
class BootstrapTenantRequest extends FormRequest
class TenantBootstrapRequest extends FormRequest
{
protected bool $hasInvalidDomain = false;
@@ -23,14 +23,10 @@ class BootstrapTenantRequest extends FormRequest
$this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain)
&& $normalizedDomain === null;
$this->merge([
'dominio' => $normalizedDomain,
]);
$this->merge(['dominio' => $normalizedDomain]);
}
/**
* @return array<string, mixed>
*/
/** @return array<string, mixed> */
public function rules(): array
{
return [

View File

@@ -0,0 +1,35 @@
<?php
namespace App\Domains\Bootstrap\Resources;
use App\Domains\Tenant\Models\WebsiteType;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/** @mixin array{website_type: WebsiteType} */
class AdminAppBootstrapResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
/** @var WebsiteType $websiteType */
$websiteType = $this->resource['website_type'];
return [
'website_type_code' => $websiteType->codigo,
'primary_color' => $websiteType->primary_color,
'secondary_color' => $websiteType->secondary_color,
'danger_color' => $websiteType->danger_color,
'success_color' => $websiteType->success_color,
'warning_color' => $websiteType->warning_color,
'body_color' => $websiteType->body_color,
'darker_body_color' => $websiteType->darker_body_color,
'surface_color' => $websiteType->surface_color,
'background_color' => $websiteType->background_color,
'border_color' => $websiteType->border_color,
'login_header_footer_color' => $websiteType->login_header_footer_color,
'site_logo' => $websiteType->siteLogo?->getTemporaryUrl(1440),
'footer_logo' => $websiteType->footerLogo?->getTemporaryUrl(1440),
];
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace App\Domains\Bootstrap\Services;
use App\Domains\Tenant\Models\WebsiteType;
class AdminAppBootstrapService
{
/** @return array{website_type: WebsiteType} */
public function get(string $domain): array
{
return [
'website_type' => WebsiteType::query()
->with(['siteLogo', 'footerLogo'])
->where('dominio', $domain)
->firstOrFail(),
];
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace App\Domains\Bootstrap\Services;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Services\TenantInformationService;
class TenantBootstrapService
{
public function __construct(protected TenantInformationService $tenantInformationService) {}
public function get(string $domain): Tenant
{
return $this->tenantInformationService->load(
Tenant::query()->where('dominio', $domain)->firstOrFail(),
[
'menues' => fn ($query) => $query->whereHas(
'roles',
fn ($query) => $query->where('codigo', RoleCode::User->value)
),
'categories' => fn ($query) => $query->orderBy('nombre'),
]
);
}
}

View File

@@ -0,0 +1,9 @@
<?php
use App\Domains\Bootstrap\Controllers\AdminAppBootstrapController;
use Illuminate\Support\Facades\Route;
Route::get(
'v1/adminapp/bootstrap/{dominio}',
AdminAppBootstrapController::class
);

View File

@@ -0,0 +1,9 @@
<?php
use App\Domains\Bootstrap\Controllers\TenantBootstrapController;
use Illuminate\Support\Facades\Route;
Route::get('tenants/bootstrap/{dominio}', TenantBootstrapController::class)
->where('dominio', '.*');
require __DIR__.'/adminapp.php';

View File

@@ -178,6 +178,7 @@ class CatalogController extends Controller
'catalogItem.attachments',
'catalogItem.variants.inventory',
'catalogItem.variants.attachments',
'catalogItem.variants.eventDate',
'catalogItem.variants.definitions.itemAttribute.attribute',
'catalogItem.bundleComponents.catalogItem',
'catalogItem.bundleComponents.variant.catalogItem',

View File

@@ -0,0 +1,15 @@
<?php
namespace App\Domains\Catalog\Enums;
enum EventProductType: string
{
case Entry = 'entrada';
case Product = 'producto';
/** @return list<string> */
public static function values(): array
{
return array_column(self::cases(), 'value');
}
}

View File

@@ -4,9 +4,12 @@ namespace App\Domains\Catalog\Models;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Catalog\Enums\CatalogItemType;
use App\Domains\Catalog\Enums\EventProductType;
use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Services\CatalogInventoryService;
use App\Domains\Event\Models\Event;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\Ticket;
use Carbon\CarbonInterface;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -17,6 +20,8 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable([
'tenant_code',
'event_id',
'event_product_type',
'category_id',
'brand_id',
'inventory_id',
@@ -50,6 +55,8 @@ class CatalogItem extends Model
'category_id' => 'integer',
'brand_id' => 'integer',
'inventory_id' => 'integer',
'event_id' => 'integer',
'event_product_type' => EventProductType::class,
'type' => CatalogItemType::class,
'precio' => 'decimal:2',
'inventory_policy' => InventoryPolicy::class,
@@ -65,6 +72,12 @@ class CatalogItem extends Model
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
}
/** @return BelongsTo<Event, $this> */
public function event(): BelongsTo
{
return $this->belongsTo(Event::class);
}
/** @return BelongsTo<Category, $this> */
public function category(): BelongsTo
{
@@ -101,6 +114,12 @@ class CatalogItem extends Model
return $this->hasMany(Variant::class);
}
/** @return HasMany<Ticket, $this> */
public function sourceTickets(): HasMany
{
return $this->hasMany(Ticket::class, 'source_catalog_item_id');
}
/** @return BelongsToMany<Attribute, $this> */
public function attributes(): BelongsToMany
{

View File

@@ -3,6 +3,8 @@
namespace App\Domains\Catalog\Models;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Event\Models\EventDate;
use App\Domains\Ticket\Models\Ticket;
use Carbon\CarbonInterface;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -13,6 +15,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable([
'catalog_item_id',
'event_date_id',
'inventory_id',
'minimum_use_date',
'maximum_use_date',
@@ -29,6 +32,7 @@ class Variant extends Model
{
return [
'catalog_item_id' => 'integer',
'event_date_id' => 'integer',
'inventory_id' => 'integer',
'minimum_use_date' => 'datetime',
'maximum_use_date' => 'datetime',
@@ -41,6 +45,18 @@ class Variant extends Model
return $this->belongsTo(CatalogItem::class);
}
/** @return BelongsTo<EventDate, $this> */
public function eventDate(): BelongsTo
{
return $this->belongsTo(EventDate::class);
}
/** @return HasMany<Ticket, $this> */
public function sourceTickets(): HasMany
{
return $this->hasMany(Ticket::class, 'source_variant_id');
}
/** @return BelongsTo<Inventory, $this> */
public function inventory(): BelongsTo
{
@@ -79,18 +95,38 @@ class Variant extends Model
public function getName(): string
{
return $this->catalogItem->nombre;
$name = $this->catalogItem->nombre;
$this->loadMissing(['definitions.itemAttribute.attribute', 'eventDate']);
$definitions = $this->definitions
->map(function (VariantDefinition $definition): ?string {
$attributeName = $definition->itemAttribute?->attribute?->nombre;
return $attributeName
? "{$attributeName}: {$definition->value}"
: $definition->value;
})
->filter();
if ($this->eventDate !== null) {
$definitions->push('Fecha: '.$this->eventDate->date->format('Y-m-d'));
}
$description = $definitions->implode(', ');
return $description === '' ? $name : "{$name} ({$description})";
}
public function getMinimumUseDate(): ?CarbonInterface
{
return $this->minimum_use_date
return $this->eventDate?->startsAt()
?? $this->minimum_use_date
?? $this->catalogItem->getMinimumUseDate();
}
public function getMaximumUseDate(): ?CarbonInterface
{
return $this->maximum_use_date
return $this->eventDate?->endsAt()
?? $this->maximum_use_date
?? $this->catalogItem->getMaximumUseDate();
}
}

View File

@@ -3,6 +3,7 @@
namespace App\Domains\Catalog\Requests;
use App\Domains\Catalog\Enums\CatalogItemType;
use App\Domains\Catalog\Enums\EventProductType;
use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Shared\Rules\ImageOrBase64Rule;
use Illuminate\Foundation\Http\FormRequest;
@@ -25,6 +26,20 @@ class StoreCatalogItemRequest extends FormRequest
return [
'tenant_code' => ['prohibited'],
'type' => ['sometimes', Rule::enum(CatalogItemType::class)],
'event_id' => [
'sometimes',
'nullable',
'required_with:event_product_type',
Rule::exists('events', 'id')->where(
fn ($query) => $query->where('tenant_code', $tenantCode)
),
],
'event_product_type' => [
'sometimes',
'nullable',
'required_with:event_id',
Rule::enum(EventProductType::class),
],
'category_id' => [
'sometimes',
'nullable',
@@ -73,6 +88,14 @@ class StoreCatalogItemRequest extends FormRequest
'images.*' => ['required', new ImageOrBase64Rule],
'variants' => [Rule::prohibitedIf($isBundle), 'sometimes', 'array'],
'variants.*.real_stock' => ['sometimes', 'integer', 'min:0'],
'variants.*.event_date_id' => [
'sometimes',
'nullable',
'integer',
Rule::exists('event_dates', 'id')->where(
fn ($query) => $query->where('event_id', $this->input('event_id'))
),
],
'variants.*.inventory_id' => ['prohibited'],
'variants.*.reserved_stock' => ['prohibited'],
'variants.*.sold_units' => ['prohibited'],

View File

@@ -32,6 +32,8 @@ class CatalogFeaturedItemResource extends JsonResource
'variants' => $catalogItem->variants
->map(fn (Variant $variant): array => [
'id' => $variant->id,
'event_date_id' => $variant->event_date_id,
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited
? null
: $variant->inventory->availableStock(),

View File

@@ -22,6 +22,8 @@ class CatalogItemDetailResource extends JsonResource
return [
'id' => $this->id,
'type' => $this->type->value,
'event_id' => $this->event_id,
'event_product_type' => $this->event_product_type?->value,
'category_id' => $this->category_id,
'brand_id' => $this->brand_id,
'slug' => $this->slug,
@@ -110,12 +112,16 @@ class CatalogItemDetailResource extends JsonResource
{
return [
'id' => $variant->id,
'event_date_id' => $variant->event_date_id,
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
'stock_tecnico' => $this->variantStock($variant),
'minimum_use_date' => $variant->minimum_use_date,
'maximum_use_date' => $variant->maximum_use_date,
'effective_minimum_use_date' => $variant->minimum_use_date
'effective_minimum_use_date' => $variant->eventDate?->startsAt()
?? $variant->minimum_use_date
?? $this->minimum_use_date,
'effective_maximum_use_date' => $variant->maximum_use_date
'effective_maximum_use_date' => $variant->eventDate?->endsAt()
?? $variant->maximum_use_date
?? $this->maximum_use_date,
'values' => $variant->definitions
->mapWithKeys(fn ($definition) => [

View File

@@ -15,6 +15,8 @@ class CatalogItemResource extends JsonResource
return [
'id' => $this->id,
'type' => $this->type->value,
'event_id' => $this->event_id,
'event_product_type' => $this->event_product_type?->value,
'category_id' => $this->category_id,
'brand_id' => $this->brand_id,
'slug' => $this->slug,
@@ -32,12 +34,16 @@ class CatalogItemResource extends JsonResource
'variants' => $this->whenLoaded('variants', fn () => $this->variants
->map(fn ($variant) => [
'id' => $variant->id,
'event_date_id' => $variant->event_date_id,
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
'real_stock' => $variant->inventory?->real_stock,
'minimum_use_date' => $variant->minimum_use_date,
'maximum_use_date' => $variant->maximum_use_date,
'effective_minimum_use_date' => $variant->minimum_use_date
'effective_minimum_use_date' => $variant->eventDate?->startsAt()
?? $variant->minimum_use_date
?? $this->minimum_use_date,
'effective_maximum_use_date' => $variant->maximum_use_date
'effective_maximum_use_date' => $variant->eventDate?->endsAt()
?? $variant->maximum_use_date
?? $this->maximum_use_date,
'values' => $variant->definitions
->mapWithKeys(fn ($definition) => [

View File

@@ -30,6 +30,8 @@ class CatalogSearchItemResource extends JsonResource
'variants' => $this->variants
->map(fn (Variant $variant): array => [
'id' => $variant->id,
'event_date_id' => $variant->event_date_id,
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
'stock_tecnico' => $this->inventory_policy === InventoryPolicy::Unlimited
? null
: $variant->inventory?->availableStock(),

View File

@@ -5,12 +5,15 @@ namespace App\Domains\Catalog\Services;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Services\AttachmentService;
use App\Domains\Catalog\Enums\CatalogItemType;
use App\Domains\Catalog\Enums\EventProductType;
use App\Domains\Catalog\Models\Attribute;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Category;
use App\Domains\Catalog\Models\Inventory;
use App\Domains\Catalog\Models\ItemAttribute;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Event\Models\Event;
use App\Domains\Event\Models\EventDate;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Pagination\LengthAwarePaginator;
@@ -39,7 +42,12 @@ class CatalogService
$hasDirectStock = array_key_exists('real_stock', $data);
$realStock = (int) ($data['real_stock'] ?? 0);
$hasVariants = $attributeCodes !== [];
$hasEventDateVariants = $variants !== [] && collect($variants)->every(
fn (array $variant): bool => ! empty($variant['event_date_id'])
);
$hasVariants = $attributeCodes !== [] || $hasEventDateVariants;
$this->validateEventData($data);
if ($type === CatalogItemType::Bundle) {
$this->validateBundleData($data, $components);
@@ -121,9 +129,11 @@ class CatalogService
'inventory',
'category',
'brand',
'event',
'itemAttributes.attribute',
'variants.inventory',
'variants.attachments',
'variants.eventDate',
'variants.definitions.itemAttribute.attribute',
'bundleComponents.catalogItem',
'bundleComponents.variant.catalogItem',
@@ -138,10 +148,12 @@ class CatalogService
'inventory',
'category',
'brand',
'event',
'itemAttributes.attribute.options',
'variants' => fn ($query) => $query->orderBy('id'),
'variants.inventory',
'variants.attachments',
'variants.eventDate',
'variants.definitions' => fn ($query) => $query->orderBy('id'),
'variants.definitions.itemAttribute.attribute',
'bundleComponents.catalogItem.inventory',
@@ -195,6 +207,7 @@ class CatalogService
'inventory',
'variants.inventory',
'variants.attachments',
'variants.eventDate',
'variants.definitions.itemAttribute.attribute',
'bundleComponents.catalogItem',
'bundleComponents.variant.catalogItem',
@@ -226,6 +239,7 @@ class CatalogService
'inventory',
'variants.inventory',
'variants.attachments',
'variants.eventDate',
'variants.definitions.itemAttribute.attribute',
'bundleComponents.catalogItem',
'bundleComponents.variant.catalogItem',
@@ -472,8 +486,28 @@ class CatalogService
}
$inventory = $this->createInventory((int) ($data['real_stock'] ?? 0));
$eventDateId = $data['event_date_id'] ?? null;
if (
$eventDateId !== null
&& (
$catalogItem->event_id === null
|| ! EventDate::query()
->whereKey($eventDateId)
->where('event_id', $catalogItem->event_id)
->exists()
)
) {
throw ValidationException::withMessages([
"variants.{$index}.event_date_id" => [
'The event date must belong to the catalog item event.',
],
]);
}
$variant = $catalogItem->variants()->create([
'inventory_id' => $inventory->id,
'event_date_id' => $eventDateId,
'minimum_use_date' => $data['minimum_use_date'] ?? null,
'maximum_use_date' => $data['maximum_use_date'] ?? null,
]);
@@ -501,6 +535,38 @@ class CatalogService
return $variant;
}
/** @param array<string, mixed> $data */
private function validateEventData(array $data): void
{
$eventId = $data['event_id'] ?? null;
$eventProductType = $data['event_product_type'] ?? null;
if (($eventId === null) !== ($eventProductType === null)) {
throw ValidationException::withMessages([
'event_id' => ['Event and event product type must be provided together.'],
]);
}
if ($eventId === null) {
return;
}
if (! Event::query()
->whereKey($eventId)
->where('tenant_code', $data['tenant_code'] ?? null)
->exists()) {
throw ValidationException::withMessages([
'event_id' => ['The event must belong to the catalog item tenant.'],
]);
}
if (! in_array($eventProductType, EventProductType::values(), true)) {
throw ValidationException::withMessages([
'event_product_type' => ['The event product type is invalid.'],
]);
}
}
private function validateVariantUseDates(Variant $variant, int $index): void
{
$minimumUseDate = $variant->getMinimumUseDate();

View File

@@ -0,0 +1,31 @@
<?php
namespace App\Domains\Event\Controllers\AdminApp;
use App\Domains\Event\Requests\UpdateEventRequest;
use App\Domains\Event\Resources\EventResource;
use App\Domains\Event\Services\EventService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class EventController extends Controller
{
public function __construct(protected EventService $eventService) {}
public function show(Request $request): EventResource
{
return EventResource::make(
$this->eventService->activeForTenant($request->user()->tenant()->firstOrFail())
);
}
public function update(UpdateEventRequest $request): EventResource
{
return EventResource::make(
$this->eventService->updateActiveForTenant(
$request->user()->tenant()->firstOrFail(),
$request->validated()
)
);
}
}

View File

@@ -0,0 +1,41 @@
<?php
namespace App\Domains\Event\Models;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Tenant\Models\Tenant;
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([
'tenant_code',
'name',
'address',
])]
class Event extends Model
{
use HasFactory;
public $timestamps = false;
/** @return BelongsTo<Tenant, $this> */
public function tenant(): BelongsTo
{
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
}
/** @return HasMany<EventDate, $this> */
public function dates(): HasMany
{
return $this->hasMany(EventDate::class)->orderBy('date')->orderBy('time_start');
}
/** @return HasMany<CatalogItem, $this> */
public function catalogItems(): HasMany
{
return $this->hasMany(CatalogItem::class);
}
}

View File

@@ -0,0 +1,55 @@
<?php
namespace App\Domains\Event\Models;
use App\Domains\Catalog\Models\Variant;
use Carbon\CarbonInterface;
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;
use Illuminate\Support\Carbon;
#[Fillable([
'event_id',
'date',
'time_start',
'time_end',
])]
class EventDate extends Model
{
use HasFactory;
public $timestamps = false;
protected function casts(): array
{
return [
'event_id' => 'integer',
'date' => 'date:Y-m-d',
];
}
/** @return BelongsTo<Event, $this> */
public function event(): BelongsTo
{
return $this->belongsTo(Event::class);
}
/** @return HasMany<Variant, $this> */
public function variants(): HasMany
{
return $this->hasMany(Variant::class);
}
public function startsAt(): CarbonInterface
{
return Carbon::parse($this->date->format('Y-m-d').' '.$this->time_start);
}
public function endsAt(): CarbonInterface
{
return Carbon::parse($this->date->format('Y-m-d').' '.$this->time_end);
}
}

View File

@@ -0,0 +1,60 @@
<?php
namespace App\Domains\Event\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;
class UpdateEventRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/** @return array<string, mixed> */
public function rules(): array
{
return [
'title' => ['required', 'string', 'max:255'],
'location' => ['required', 'string', 'max:255'],
'dates' => ['required', 'array', 'min:1'],
'dates.*' => ['required', 'array:date,start_time,end_time'],
'dates.*.date' => ['required', 'date_format:Y-m-d', 'distinct'],
'dates.*.start_time' => ['required', 'date_format:H:i'],
'dates.*.end_time' => ['required', 'date_format:H:i'],
'social_media' => ['sometimes', 'array'],
'social_media.*' => ['required', 'array:code,url,orden'],
'social_media.*.code' => [
'required',
'string',
'distinct',
Rule::exists('social_media', 'code'),
],
'social_media.*.url' => ['required', 'url', 'max:2048'],
'social_media.*.orden' => ['sometimes', 'integer', 'min:0', 'distinct'],
'contact' => ['sometimes', 'array:whatsapp_url,instagram_url,facebook_url'],
'contact.whatsapp_url' => ['nullable', 'url', 'max:2048'],
'contact.instagram_url' => ['nullable', 'url', 'max:2048'],
'contact.facebook_url' => ['nullable', 'url', 'max:2048'],
];
}
/** @return array<int, callable> */
public function after(): array
{
return [
function (Validator $validator): void {
$input = $this->all();
if (! array_key_exists('social_media', $input) && ! array_key_exists('contact', $input)) {
$validator->errors()->add(
'social_media',
'The social media field is required.'
);
}
},
];
}
}

View File

@@ -0,0 +1,39 @@
<?php
namespace App\Domains\Event\Resources;
use App\Domains\Event\Models\Event;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/** @mixin Event */
class EventResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
$socialMedia = $this->tenant->socialMedia->keyBy('code');
return [
'id' => $this->id,
'title' => $this->name,
'location' => $this->address,
'dates' => $this->dates->map(fn ($eventDate): array => [
'id' => $eventDate->id,
'date' => $eventDate->date->format('Y-m-d'),
'start_time' => substr($eventDate->time_start, 0, 5),
'end_time' => substr($eventDate->time_end, 0, 5),
])->values(),
'social_media' => $this->tenant->socialMedia->map(fn ($item): array => [
'code' => $item->code,
'url' => $item->pivot->url,
'orden' => $item->pivot->orden,
])->values(),
'contact' => [
'whatsapp_url' => $socialMedia->get('whatsapp')?->pivot->url,
'instagram_url' => $socialMedia->get('instagram')?->pivot->url,
'facebook_url' => $socialMedia->get('facebook')?->pivot->url,
],
];
}
}

View File

@@ -0,0 +1,120 @@
<?php
namespace App\Domains\Event\Services;
use App\Domains\Event\Models\Event;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Support\Facades\DB;
class EventService
{
private const CONTACT_CODES = [
'whatsapp_url' => 'whatsapp',
'instagram_url' => 'instagram',
'facebook_url' => 'facebook',
];
public function activeForTenant(Tenant $tenant): Event
{
return $tenant->events()
->whereKey($tenant->active_event_id)
->with(['dates', 'tenant.socialMedia'])
->firstOrFail();
}
/** @param array<string, mixed> $data */
public function updateActiveForTenant(Tenant $tenant, array $data): Event
{
return DB::transaction(function () use ($tenant, $data): Event {
$tenant = Tenant::query()->whereKey($tenant->getKey())->lockForUpdate()->firstOrFail();
$event = $tenant->active_event_id === null
? $tenant->events()->create([
'name' => $data['title'],
'address' => $data['location'],
])
: $tenant->events()
->whereKey($tenant->active_event_id)
->lockForUpdate()
->firstOrFail();
$event->update([
'name' => $data['title'],
'address' => $data['location'],
]);
if ($tenant->active_event_id === null) {
$tenant->update(['active_event_id' => $event->id]);
}
$this->syncDates($event, $data['dates']);
if (array_key_exists('social_media', $data)) {
$this->syncSocialMedia($tenant, $data['social_media']);
} else {
$this->syncLegacyContact($tenant, $data['contact']);
}
return $event->load(['dates', 'tenant.socialMedia']);
});
}
/** @param array<int, array{date: string, start_time: string, end_time: string}> $dates */
private function syncDates(Event $event, array $dates): void
{
$existingDates = $event->dates()->get()->values();
foreach (array_values($dates) as $index => $date) {
$attributes = [
'date' => $date['date'],
'time_start' => $date['start_time'],
'time_end' => $date['end_time'],
];
$existingDate = $existingDates->get($index);
if ($existingDate) {
$existingDate->update($attributes);
} else {
$event->dates()->create($attributes);
}
}
$existingDates->slice(count($dates))->each->delete();
$event->unsetRelation('dates');
}
/** @param array<string, string|null> $contact */
private function syncLegacyContact(Tenant $tenant, array $contact): void
{
foreach (self::CONTACT_CODES as $field => $code) {
$url = $contact[$field] ?? null;
if ($url === null || $url === '') {
$tenant->socialMedia()->detach($code);
continue;
}
$tenant->socialMedia()->syncWithoutDetaching([
$code => ['url' => $url],
]);
}
$tenant->unsetRelation('socialMedia');
}
/** @param array<int, array{code: string, url: string, orden?: int}> $socialMedia */
private function syncSocialMedia(Tenant $tenant, array $socialMedia): void
{
$associations = [];
foreach (array_values($socialMedia) as $index => $item) {
$associations[$item['code']] = [
'url' => $item['url'],
'orden' => $item['orden'] ?? $index,
];
}
$tenant->socialMedia()->sync($associations);
$tenant->unsetRelation('socialMedia');
}
}

View File

@@ -0,0 +1,11 @@
<?php
use App\Domains\Event\Controllers\AdminApp\EventController;
use Illuminate\Support\Facades\Route;
Route::prefix('v1/adminapp/tenant')
->middleware(['auth:sanctum', 'adminapp.tenant'])
->group(function (): void {
Route::get('event', [EventController::class, 'show']);
Route::put('event', [EventController::class, 'update']);
});

View File

@@ -0,0 +1,3 @@
<?php
require __DIR__.'/adminapp.php';

View File

@@ -0,0 +1,22 @@
<?php
namespace App\Domains\Forms\Controllers\AdminApp;
use App\Domains\Forms\Resources\EventFormResource;
use App\Domains\Forms\Services\EventFormService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class EventFormController extends Controller
{
public function __construct(protected EventFormService $eventFormService) {}
public function __invoke(Request $request): EventFormResource
{
return EventFormResource::make(
$this->eventFormService->get(
$request->user('sanctum')->tenant()->firstOrFail()
)
);
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace App\Domains\Forms\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class EventFormResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
return [
'social_media' => SocialMediaOptionResource::collection(
$this->resource['social_media']
),
];
}
}

View File

@@ -0,0 +1,22 @@
<?php
namespace App\Domains\Forms\Resources;
use App\Domains\Tenant\Models\SocialMedia;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/** @mixin SocialMedia */
class SocialMediaOptionResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
return [
'code' => $this->code,
'name' => $this->name,
'icon' => $this->icon,
'url' => $this->url,
];
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace App\Domains\Forms\Services;
use App\Domains\Tenant\Models\SocialMedia;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Collection;
class EventFormService
{
/** @return array{social_media: Collection<int, SocialMedia>} */
public function get(Tenant $tenant): array
{
$urls = $tenant->socialMedia()
->pluck('tenant_social_media.url', 'social_media.code');
return [
'social_media' => SocialMedia::query()
->orderBy('id')
->get()
->each(fn (SocialMedia $item) => $item->setAttribute(
'url',
$urls->get($item->code)
)),
];
}
}

View File

@@ -0,0 +1,10 @@
<?php
use App\Domains\Forms\Controllers\AdminApp\EventFormController;
use Illuminate\Support\Facades\Route;
Route::prefix('v1/adminapp/forms')
->middleware(['auth:sanctum', 'adminapp.tenant'])
->group(function (): void {
Route::get('event', EventFormController::class);
});

View File

@@ -0,0 +1,3 @@
<?php
require __DIR__.'/adminapp.php';

View File

@@ -0,0 +1,9 @@
<?php
namespace App\Domains\Logging\Enums;
enum ValueChangeActorType: string
{
case User = 'user';
case System = 'system';
}

View File

@@ -0,0 +1,62 @@
<?php
namespace App\Domains\Logging\Models\Concerns;
use App\Domains\Logging\Enums\ValueChangeActorType;
use App\Domains\Logging\Models\ValueChange;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Support\Facades\Auth;
use LogicException;
trait LogsValueChanges
{
public static function bootLogsValueChanges(): void
{
static::updated(function (Model $model): void {
$changedAttributes = array_values(array_intersect(
$model->getLoggedAttributes(),
array_keys($model->getChanges()),
));
if ($changedAttributes === []) {
return;
}
$userId = Auth::id();
$actorType = $userId === null
? ValueChangeActorType::System
: ValueChangeActorType::User;
foreach ($changedAttributes as $attribute) {
$model->valueChanges()->create([
'attribute' => $attribute,
'old_value' => $model->getRawOriginal($attribute),
'new_value' => $model->getAttributes()[$attribute] ?? null,
'changed_at' => now(),
'actor_type' => $actorType,
'user_id' => $userId,
]);
}
});
}
/** @return array<int, string> */
public function getLoggedAttributes(): array
{
if (! property_exists($this, 'loggedAttributes')) {
throw new LogicException(sprintf(
'The [%s] model must define a $loggedAttributes property.',
static::class,
));
}
return array_values(array_unique($this->loggedAttributes));
}
/** @return MorphMany<ValueChange, $this> */
public function valueChanges(): MorphMany
{
return $this->morphMany(ValueChange::class, 'trackable');
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace App\Domains\Logging\Models;
use App\Domains\Auth\Models\User;
use App\Domains\Logging\Enums\ValueChangeActorType;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;
#[Fillable([
'trackable_type',
'trackable_id',
'attribute',
'old_value',
'new_value',
'changed_at',
'actor_type',
'user_id',
])]
class ValueChange extends Model
{
public $timestamps = false;
/** @return MorphTo<Model, $this> */
public function trackable(): MorphTo
{
return $this->morphTo();
}
/** @return BelongsTo<User, $this> */
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
protected function casts(): array
{
return [
'trackable_id' => 'integer',
'changed_at' => 'datetime',
'actor_type' => ValueChangeActorType::class,
'user_id' => 'integer',
];
}
}

View File

@@ -2,6 +2,7 @@
namespace App\Domains\Menu\Models;
use App\Domains\Authorization\Models\Role;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
@@ -78,4 +79,16 @@ class Menu extends Model
->withPivot('static_content')
->withTimestamps();
}
public function roles(): BelongsToMany
{
return $this->belongsToMany(
Role::class,
'roles_menues',
'menu_codigo',
'rol_codigo',
'code',
'codigo'
)->using(MenuRole::class);
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace App\Domains\Menu\Models;
use App\Domains\Authorization\Models\Role;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\Pivot;
class MenuRole extends Pivot
{
protected $table = 'roles_menues';
public $incrementing = true;
public $timestamps = false;
protected $fillable = [
'rol_codigo',
'menu_codigo',
];
public function role(): BelongsTo
{
return $this->belongsTo(Role::class, 'rol_codigo', 'codigo');
}
public function menu(): BelongsTo
{
return $this->belongsTo(Menu::class, 'menu_codigo', 'code');
}
}

View File

@@ -0,0 +1,82 @@
<?php
namespace App\Domains\Tenant\Controllers\AdminApp;
use App\Domains\Auth\Models\User;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Requests\AdminApp\UpdateWebsiteExtraRequest;
use App\Domains\Tenant\Resources\AdminApp\WebsiteExtraResource;
use App\Domains\Tenant\Resources\AdminApp\WebsiteExtrasResource;
use App\Domains\Tenant\Services\TenantInformationService;
use App\Domains\Tenant\Services\WebsiteExtraService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class WebsiteExtraController extends Controller
{
public function __construct(
protected WebsiteExtraService $websiteExtraService,
protected TenantInformationService $tenantInformationService,
) {}
public function show(Request $request): WebsiteExtrasResource
{
return WebsiteExtrasResource::make(
$this->loadTenant($request->user())
);
}
public function showExtra(Request $request, string $websiteExtraCode): WebsiteExtraResource
{
$tenant = $this->loadTenant($request->user());
$definition = $this->websiteExtraService->definitionForTenant($tenant, $websiteExtraCode);
$websiteExtra = $tenant->websiteExtras
->firstWhere('website_type_extra_id', $definition->id);
if (! $websiteExtra) {
abort(404);
}
return WebsiteExtraResource::make($websiteExtra);
}
public function update(
UpdateWebsiteExtraRequest $request,
string $websiteExtraCode
): WebsiteExtrasResource {
$tenant = $request->user()->tenant()->firstOrFail();
$this->websiteExtraService->updateForTenant(
$tenant,
$websiteExtraCode,
$request->validated('config')
);
return WebsiteExtrasResource::make(
$this->loadTenant($request->user())
);
}
public function toggle(Request $request, string $websiteExtraCode): WebsiteExtrasResource
{
$tenant = $request->user()->tenant()->firstOrFail();
$this->websiteExtraService->toggleForTenant($tenant, $websiteExtraCode);
return WebsiteExtrasResource::make(
$this->loadTenant($request->user())
)->additional([
'code' => 'tenant.website_extra_toggled',
'message' => __('api.tenant.website_extra_toggled'),
]);
}
private function loadTenant(User $user): Tenant
{
$tenant = $user->tenant()->firstOrFail();
return $this->tenantInformationService->load($tenant, [
'websiteType.extras',
]);
}
}

View File

@@ -1,31 +0,0 @@
<?php
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\Http\Controllers\Controller;
class BootstrapTenantController extends Controller
{
public function __invoke(BootstrapTenantRequest $request): TenantResource
{
/** @var string $dominio */
$dominio = $request->validated('dominio');
return TenantResource::make(
Tenant::query()
->with([
'headerLogo',
'footerLogo',
'mainCarouselImages',
'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

@@ -7,6 +7,7 @@ use App\Domains\Catalog\Enums\GroupLayout;
use App\Domains\Catalog\Enums\ProductLayout;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Category;
use App\Domains\Event\Models\Event;
use App\Domains\Menu\Models\Menu;
use App\Domains\Menu\Models\TenantMenu;
use Illuminate\Database\Eloquent\Attributes\Fillable;
@@ -28,11 +29,11 @@ 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',
'active_event_id',
])]
class Tenant extends Model
{
@@ -57,11 +58,10 @@ 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',
'active_event_id' => 'integer',
];
}
@@ -82,27 +82,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
@@ -110,6 +94,18 @@ class Tenant extends Model
return $this->hasMany(CatalogItem::class, 'tenant_code', 'codigo');
}
/** @return HasMany<Event, $this> */
public function events(): HasMany
{
return $this->hasMany(Event::class, 'tenant_code', 'codigo');
}
/** @return BelongsTo<Event, $this> */
public function activeEvent(): BelongsTo
{
return $this->belongsTo(Event::class, 'active_event_id');
}
/**
* @return HasMany<Category, $this>
*/
@@ -136,6 +132,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,66 @@
<?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',
'is_enabled',
])]
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',
'is_enabled' => 'boolean',
];
}
/**
* @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,67 @@
<?php
namespace App\Domains\Tenant\Models;
use App\Domains\Attachable\Models\Attachment;
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([
'codigo',
'nombre',
'dominio',
'primary_color',
'secondary_color',
'danger_color',
'success_color',
'warning_color',
'body_color',
'darker_body_color',
'surface_color',
'background_color',
'border_color',
'login_header_footer_color',
'site_logo',
'footer_logo',
])]
class WebsiteType extends Model
{
use HasFactory;
protected $table = 'website_type';
/**
* @return BelongsTo<Attachment, $this>
*/
public function siteLogo(): BelongsTo
{
return $this->belongsTo(Attachment::class, 'site_logo');
}
/**
* @return BelongsTo<Attachment, $this>
*/
public function footerLogo(): BelongsTo
{
return $this->belongsTo(Attachment::class, 'footer_logo');
}
/**
* @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,51 @@
<?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',
'codigo',
'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

@@ -0,0 +1,27 @@
<?php
namespace App\Domains\Tenant\Requests\AdminApp;
use App\Domains\Tenant\Services\WebsiteExtraService;
use Illuminate\Foundation\Http\FormRequest;
class UpdateWebsiteExtraRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/**
* @return array<string, mixed>
*/
public function rules(): array
{
$tenant = $this->user()->tenant()->firstOrFail();
return app(WebsiteExtraService::class)->requestRulesForExtra(
$tenant,
(string) $this->route('websiteExtraCode')
);
}
}

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

@@ -0,0 +1,53 @@
<?php
namespace App\Domains\Tenant\Resources\AdminApp;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Tenant\Models\WebsiteExtra;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* @mixin WebsiteExtra
*/
class WebsiteExtraResource extends JsonResource
{
/**
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'codigo' => $this->websiteTypeExtra->codigo,
'nombre' => $this->websiteTypeExtra->nombre,
'descripcion' => $this->websiteTypeExtra->descripcion,
'is_required' => $this->websiteTypeExtra->is_required,
'is_enabled' => $this->is_enabled,
'request_rules' => $this->websiteTypeExtra->config_schema['request_rules'] ?? [],
'config' => $this->formatConfig(
$this->resolvedConfig(),
fn (Attachment $attachment): string => $attachment->key
),
'resolved_config' => $this->formatConfig(
$this->resolvedConfig(),
fn (Attachment $attachment): string => $attachment->getTemporaryUrl(1440)
),
];
}
private function formatConfig(mixed $value, callable $formatAttachment): mixed
{
if ($value instanceof Attachment) {
return $formatAttachment($value);
}
if (! is_array($value)) {
return $value;
}
return array_map(
fn (mixed $item): mixed => $this->formatConfig($item, $formatAttachment),
$value
);
}
}

View File

@@ -0,0 +1,71 @@
<?php
namespace App\Domains\Tenant\Resources\AdminApp;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* @mixin Tenant
*/
class WebsiteExtrasResource extends JsonResource
{
/**
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
$websiteExtras = $this->websiteExtras->keyBy(
fn ($extra) => $extra->websiteTypeExtra->codigo
);
return [
'website_type' => $this->websiteType ? [
'codigo' => $this->websiteType->codigo,
'nombre' => $this->websiteType->nombre,
] : null,
'definitions' => $this->websiteType?->extras
->mapWithKeys(fn ($definition) => [
$definition->codigo => [
'codigo' => $definition->codigo,
'nombre' => $definition->nombre,
'descripcion' => $definition->descripcion,
'is_required' => $definition->is_required,
'is_enabled' => $websiteExtras
->get($definition->codigo)?->is_enabled,
'request_rules' => $definition->config_schema['request_rules'] ?? [],
],
]) ?? [],
'extras' => $websiteExtras->mapWithKeys(fn ($extra) => [
$extra->websiteTypeExtra->codigo => $this->formatConfig(
$extra->resolvedConfig(),
fn (Attachment $attachment): string => $attachment->key
),
]),
'resolved_extras' => $websiteExtras->mapWithKeys(fn ($extra) => [
$extra->websiteTypeExtra->codigo => $this->formatConfig(
$extra->resolvedConfig(),
fn (Attachment $attachment): string => $attachment->getTemporaryUrl(1440)
),
]),
];
}
private function formatConfig(mixed $value, callable $formatAttachment): mixed
{
if ($value instanceof Attachment) {
return $formatAttachment($value);
}
if (! is_array($value)) {
return $value;
}
return array_map(
fn (mixed $item): mixed => $this->formatConfig($item, $formatAttachment),
$value
);
}
}

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,37 @@ 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,
'active_event_id' => $this->active_event_id,
'active_event' => $this->whenLoaded('activeEvent', fn () => $this->activeEvent === null
? null
: [
'id' => $this->activeEvent->id,
'name' => $this->activeEvent->name,
'address' => $this->activeEvent->address,
'dates' => $this->activeEvent->dates->map(fn ($eventDate): array => [
'id' => $eventDate->id,
'date' => $eventDate->date->format('Y-m-d'),
'time_start' => $eventDate->time_start,
'time_end' => $eventDate->time_end,
])->values(),
]),
'extras' => $this->whenLoaded(
'websiteExtras',
fn () => $this->websiteExtras
->filter(fn ($extra) => $extra->is_enabled)
->mapWithKeys(fn ($extra) => [
$extra->websiteTypeExtra->codigo => $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 +84,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',
'websiteExtras.websiteTypeExtra',
'activeEvent.dates',
];
/**
* @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,367 @@
<?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\WebsiteExtra;
use App\Domains\Tenant\Models\WebsiteType;
use App\Domains\Tenant\Models\WebsiteTypeExtra;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
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);
$allowedCodes = $definitions->pluck('codigo')->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 ($allowedCodes): void {
if (! is_array($value)) {
return;
}
$unknownCodes = array_diff(array_keys($value), $allowedCodes);
if ($unknownCodes !== []) {
$fail(
'The '.$attribute.' field contains extras not supported by the website type: '
.implode(', ', $unknownCodes).'.'
);
}
},
],
];
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->codigo}"] = $rootRules;
foreach ($schemaRules as $path => $pathRules) {
if ($path === '$') {
continue;
}
$rules[$this->requestAttribute($definition->codigo, $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('codigo');
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."],
]);
}
$requestRoot = "extras.{$definition->codigo}";
$transformedConfig = $this->applyTransforms(
$tenant,
$definition,
$config,
$requestRoot
);
$tenant->websiteExtras()->create([
'website_type_extra_id' => $definition->id,
'config' => $transformedConfig,
]);
}
$tenant->unsetRelation('websiteExtras');
}
/**
* Build request rules for one extra addressed by its stable code.
*
* @return array<string, mixed>
*/
public function requestRulesForExtra(Tenant $tenant, string $extraCode): array
{
$definition = $this->definitionForTenant($tenant, $extraCode);
$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, 'required');
$rules = ['config' => $rootRules];
foreach ($schemaRules as $path => $pathRules) {
if ($path === '$') {
continue;
}
$rules[$this->configAttribute('config', $path)] = $this->compileRules($pathRules);
}
return $rules;
}
public function updateForTenant(Tenant $tenant, string $extraCode, mixed $config): WebsiteExtra
{
$definition = $this->definitionForTenant($tenant, $extraCode);
return DB::transaction(function () use ($tenant, $definition, $config): WebsiteExtra {
$transformedConfig = $this->applyTransforms($tenant, $definition, $config, 'config');
return $tenant->websiteExtras()->updateOrCreate(
['website_type_extra_id' => $definition->id],
['config' => $transformedConfig]
);
});
}
public function toggleForTenant(Tenant $tenant, string $extraCode): WebsiteExtra
{
$definition = $this->definitionForTenant($tenant, $extraCode);
return DB::transaction(function () use ($tenant, $definition): WebsiteExtra {
$websiteExtra = $tenant->websiteExtras()
->where('website_type_extra_id', $definition->id)
->lockForUpdate()
->first();
if (! $websiteExtra) {
return $tenant->websiteExtras()->create([
'website_type_extra_id' => $definition->id,
'config' => [],
'is_enabled' => true,
]);
}
$websiteExtra->update([
'is_enabled' => ! $websiteExtra->is_enabled,
]);
return $websiteExtra;
});
}
public function definitionForTenant(Tenant $tenant, string $extraCode): WebsiteTypeExtra
{
return WebsiteTypeExtra::query()
->where('website_type_code', $tenant->website_type_code)
->where('codigo', $extraCode)
->firstOrFail();
}
/**
* @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 $extraCode, string $path): string
{
return $this->configAttribute("extras.{$extraCode}", $path);
}
private function configAttribute(string $root, string $path): string
{
if ($path === '$') {
return $root;
}
if (str_starts_with($path, '$.')) {
$path = substr($path, 2);
}
return "{$root}.{$path}";
}
private function applyTransforms(
Tenant $tenant,
WebsiteTypeExtra $definition,
mixed $config,
string $requestRoot
): 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,
$requestRoot
)
);
}
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,
string $requestRoot
): mixed {
if ($value === null) {
return null;
}
if (($transform['handler'] ?? null) !== 'attachment') {
throw new InvalidArgumentException(
"Unsupported transform handler for {$definition->codigo}: ".($transform['handler'] ?? 'null')
);
}
if (is_string($value) && Str::isUuid($value)) {
$attachment = Attachment::query()->where('key', $value)->first();
if (! $attachment) {
throw ValidationException::withMessages([
$this->configAttribute($requestRoot, $path) => [
'The selected attachment does not exist.',
],
]);
}
} else {
$attachment = $this->attachmentService->store(
$value,
"tenants/{$tenant->codigo}/extras/{$definition->codigo}"
);
}
$expectedType = $transform['attachment_type'] ?? null;
if (
is_string($expectedType)
&& $attachment->type instanceof AttachmentType
&& $attachment->type->value !== $expectedType
) {
throw ValidationException::withMessages([
$this->configAttribute($requestRoot, $path) => [
"The attachment must be of type {$expectedType}.",
],
]);
}
return $attachment->id;
}
}

View File

@@ -0,0 +1,87 @@
<?php
namespace App\Domains\Tenant\Services;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Services\AttachmentService;
use App\Domains\Tenant\Models\WebsiteType;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class WebsiteTypeService
{
public function __construct(
protected AttachmentService $attachmentService,
) {}
/**
* Create a website type and store its logos.
*
* @param array<string, mixed> $data
*/
public function create(array $data): WebsiteType
{
return $this->save(new WebsiteType, $data);
}
/**
* Create or update a website type and replace its logos when provided.
*
* @param array<string, mixed> $attributes
* @param array<string, mixed> $values
*/
public function updateOrCreate(array $attributes, array $values = []): WebsiteType
{
/** @var WebsiteType $websiteType */
$websiteType = WebsiteType::query()->firstOrNew($attributes);
return $this->save($websiteType, [...$attributes, ...$values]);
}
/**
* @param array<string, mixed> $data
*/
private function save(WebsiteType $websiteType, array $data): WebsiteType
{
return DB::transaction(function () use ($websiteType, $data): WebsiteType {
$previousLogos = [];
foreach (['site_logo' => 'siteLogo', 'footer_logo' => 'footerLogo'] as $field => $relation) {
if (! array_key_exists($field, $data)) {
continue;
}
$logo = $data[$field];
$previousLogos[$field] = $websiteType->exists
? $websiteType->{$relation}()->first()
: null;
unset($data[$field]);
$attachment = null;
if ($logo) {
$attachment = is_string($logo) && Str::isUuid($logo)
? Attachment::query()->where('key', $logo)->first()
: $this->attachmentService->store($logo, 'website-types');
}
$data[$field] = $attachment?->id;
}
$websiteType->fill($data)->save();
foreach ($previousLogos as $field => $previousLogo) {
if (
$previousLogo instanceof Attachment
&& $previousLogo->id !== $websiteType->{$field}
&& $previousLogo->id !== $websiteType->site_logo
&& $previousLogo->id !== $websiteType->footer_logo
) {
$this->attachmentService->delete($previousLogo);
}
}
return $websiteType;
});
}
}

View File

@@ -0,0 +1,13 @@
<?php
use App\Domains\Tenant\Controllers\AdminApp\WebsiteExtraController;
use Illuminate\Support\Facades\Route;
Route::prefix('v1/adminapp/tenant')
->middleware(['auth:sanctum', 'adminapp.tenant'])
->group(function (): void {
Route::get('website-extras', [WebsiteExtraController::class, 'show']);
Route::get('website-extras/{websiteExtraCode}', [WebsiteExtraController::class, 'showExtra']);
Route::put('website-extras/{websiteExtraCode}', [WebsiteExtraController::class, 'update']);
Route::patch('website-extras/{websiteExtraCode}/toggle', [WebsiteExtraController::class, 'toggle']);
});

View File

@@ -1,10 +1,8 @@
<?php
use App\Domains\Tenant\Controllers\BootstrapTenantController;
use App\Domains\Tenant\Controllers\TenantController;
use Illuminate\Support\Facades\Route;
Route::get('tenants/bootstrap/{dominio}', BootstrapTenantController::class)
->where('dominio', '.*');
Route::apiResource('tenants', TenantController::class);
require __DIR__.'/adminapp.php';

View File

@@ -22,6 +22,7 @@ class TicketController extends Controller
$tickets = Ticket::query()
->where('tenant_code', $tenant->codigo)
->where('user_id', $request->user()->getKey())
->with('sourceVariant.eventDate', 'sourceVariant.catalogItem')
->orderByDesc('id')
->get();
@@ -35,6 +36,7 @@ class TicketController extends Controller
->where('tenant_code', $tenant->codigo)
->where('user_id', $request->user()->getKey())
->whereIn('id', $ticketIds)
->with('sourceVariant.eventDate', 'sourceVariant.catalogItem')
->orderByDesc('id')
->get();

View File

@@ -3,8 +3,11 @@
namespace App\Domains\Ticket\Models;
use App\Domains\Auth\Models\User;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Tenant\Models\Tenant;
use Carbon\CarbonInterface;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
@@ -66,13 +69,27 @@ class Ticket extends Model
return $this->belongsTo(Purchase::class, 'source_purchase_id');
}
/** @return BelongsTo<CatalogItem, $this> */
public function sourceCatalogItem(): BelongsTo
{
return $this->belongsTo(CatalogItem::class, 'source_catalog_item_id');
}
/** @return BelongsTo<Variant, $this> */
public function sourceVariant(): BelongsTo
{
return $this->belongsTo(Variant::class, 'source_variant_id');
}
public function isValid(): bool
{
$now = now();
$startsAt = $this->getEffectiveStartsAt();
$expiresAt = $this->getEffectiveExpiresAt();
return $this->used_at === null
&& ($this->starts_at === null || $this->starts_at->lessThanOrEqualTo($now))
&& ($this->expires_at === null || $this->expires_at->greaterThan($now));
&& ($startsAt === null || $startsAt->lessThanOrEqualTo($now))
&& ($expiresAt === null || $expiresAt->greaterThan($now));
}
public function getIsValidAttribute(): bool
@@ -82,13 +99,27 @@ class Ticket extends Model
public function getIsExpiredAttribute(): bool
{
$expiresAt = $this->getEffectiveExpiresAt();
return $this->used_at === null
&& $this->expires_at !== null
&& $this->expires_at->lessThanOrEqualTo(now());
&& $expiresAt !== null
&& $expiresAt->lessThanOrEqualTo(now());
}
public function getIsUsedAttribute(): bool
{
return $this->used_at !== null;
}
public function getEffectiveStartsAt(): ?CarbonInterface
{
return $this->sourceVariant?->getMinimumUseDate()
?? $this->starts_at;
}
public function getEffectiveExpiresAt(): ?CarbonInterface
{
return $this->sourceVariant?->getMaximumUseDate()
?? $this->expires_at;
}
}

View File

@@ -20,8 +20,8 @@ class TicketResource extends JsonResource
'description' => $this->description,
'source_catalog_item_id' => $this->source_catalog_item_id,
'source_variant_id' => $this->source_variant_id,
'starts_at' => $this->starts_at,
'expires_at' => $this->expires_at,
'starts_at' => $this->getEffectiveStartsAt(),
'expires_at' => $this->getEffectiveExpiresAt(),
'used_at' => $this->used_at,
'is_valid' => $this->is_valid,
'is_expired' => $this->is_expired,

View File

@@ -35,8 +35,6 @@ class TicketGeneratorService
);
return $targets->map(function (array $target) use (
$catalogItem,
$sourceVariantId,
$sourcePurchaseId,
$user,
): Ticket {
@@ -49,8 +47,8 @@ class TicketGeneratorService
'name' => $item->nombre,
'description' => (string) ($item->descripcion ?? ''),
'source_purchase_id' => $sourcePurchaseId,
'source_catalog_item_id' => $catalogItem->getKey(),
'source_variant_id' => $sourceVariantId,
'source_catalog_item_id' => $item->getKey(),
'source_variant_id' => $target['variant']?->getKey(),
'starts_at' => $selectedItem->getMinimumUseDate(),
'expires_at' => $selectedItem->getMaximumUseDate(),
'used_at' => null,

View File

@@ -0,0 +1,30 @@
<?php
namespace App\Http\Middleware;
use App\Domains\Authorization\Enums\RoleCode;
use Closure;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsureAdminAppTenant
{
/**
* Ensure the authenticated user is an AdminApp user bound to a tenant.
*/
public function handle(Request $request, Closure $next): Response
{
$user = $request->user();
if (
! $user
|| $user->rol_codigo !== RoleCode::AdminApp->value
|| ! $user->tenant_codigo
) {
throw new AuthorizationException;
}
return $next($request);
}
}

View File

@@ -2,6 +2,7 @@
use App\Domains\Auth\Exceptions\AccountLockedException;
use App\Domains\Ticket\Exceptions\TicketNotAvailableException;
use App\Http\Middleware\EnsureAdminAppTenant;
use App\Http\Middleware\SetApiLocale;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\AuthenticationException;
@@ -21,6 +22,9 @@ return Application::configure(basePath: dirname(__DIR__))
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
$middleware->alias([
'adminapp.tenant' => EnsureAdminAppTenant::class,
]);
$middleware->encryptCookies(except: [
'guest_token',
]);

View File

@@ -0,0 +1,53 @@
<?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('permisos', function (Blueprint $table): void {
$table->id();
$table->string('codigo')->unique();
$table->string('nombre');
$table->text('descripcion')->nullable();
$table->timestamps();
});
Schema::create('roles', function (Blueprint $table): void {
$table->id();
$table->string('codigo')->unique();
$table->string('nombre');
$table->text('descripcion')->nullable();
$table->timestamps();
});
Schema::create('roles_permisos', function (Blueprint $table): void {
$table->id();
$table->string('codigo_permiso');
$table->string('rol_codigo');
$table->timestamps();
$table->foreign('codigo_permiso')
->references('codigo')
->on('permisos')
->cascadeOnUpdate()
->cascadeOnDelete();
$table->foreign('rol_codigo')
->references('codigo')
->on('roles')
->cascadeOnUpdate()
->cascadeOnDelete();
$table->unique(['rol_codigo', 'codigo_permiso']);
});
}
public function down(): void
{
Schema::dropIfExists('roles_permisos');
Schema::dropIfExists('roles');
Schema::dropIfExists('permisos');
}
};

View File

@@ -0,0 +1,57 @@
<?php
use App\Domains\Authorization\Enums\RoleCode;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
$now = now();
DB::table('roles')->insertOrIgnore([
[
'codigo' => RoleCode::Admin->value,
'nombre' => 'Administrador general',
'descripcion' => 'Administra la plataforma y todos sus tenants.',
'created_at' => $now,
'updated_at' => $now,
],
[
'codigo' => RoleCode::User->value,
'nombre' => 'Usuario',
'descripcion' => 'Cliente final limitado a sus propios datos y operaciones.',
'created_at' => $now,
'updated_at' => $now,
],
]);
Schema::table('users', function (Blueprint $table): void {
$table->string('rol_codigo')->default(RoleCode::User->value)->after('id');
$table->string('tenant_codigo')->nullable()->after('rol_codigo');
$table->foreign('rol_codigo')
->references('codigo')
->on('roles')
->cascadeOnUpdate()
->restrictOnDelete();
$table->foreign('tenant_codigo')
->references('codigo')
->on('tenants')
->cascadeOnUpdate()
->restrictOnDelete();
});
}
public function down(): void
{
Schema::table('users', function (Blueprint $table): void {
$table->dropForeign(['tenant_codigo']);
$table->dropForeign(['rol_codigo']);
$table->dropColumn(['tenant_codigo', 'rol_codigo']);
});
}
};

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

@@ -0,0 +1,35 @@
<?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('roles_menues', function (Blueprint $table): void {
$table->id();
$table->string('rol_codigo');
$table->string('menu_codigo');
$table->foreign('rol_codigo')
->references('codigo')
->on('roles')
->cascadeOnUpdate()
->cascadeOnDelete();
$table->foreign('menu_codigo')
->references('code')
->on('menues')
->cascadeOnUpdate()
->cascadeOnDelete();
$table->unique(['rol_codigo', 'menu_codigo']);
});
}
public function down(): void
{
Schema::dropIfExists('roles_menues');
}
};

View File

@@ -0,0 +1,35 @@
<?php
use App\Domains\Authorization\Enums\RoleCode;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
private const REMOVED_ROLE_CODE = 'tenant_admin';
public function up(): void
{
DB::table('users')
->where('rol_codigo', self::REMOVED_ROLE_CODE)
->update([
'rol_codigo' => RoleCode::User->value,
'tenant_codigo' => null,
]);
DB::table('roles')
->where('codigo', self::REMOVED_ROLE_CODE)
->delete();
}
public function down(): void
{
DB::table('roles')->insertOrIgnore([
'codigo' => self::REMOVED_ROLE_CODE,
'nombre' => 'Administrador del tenant',
'descripcion' => 'Administra la operación de su propio tenant.',
'created_at' => now(),
'updated_at' => now(),
]);
}
};

View File

@@ -0,0 +1,21 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
if (Schema::hasTable('menues_roles') && ! Schema::hasTable('roles_menues')) {
Schema::rename('menues_roles', 'roles_menues');
}
}
public function down(): void
{
if (Schema::hasTable('roles_menues') && ! Schema::hasTable('menues_roles')) {
Schema::rename('roles_menues', 'menues_roles');
}
}
};

View File

@@ -0,0 +1,52 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('website_type_extras', function (Blueprint $table): void {
$table->string('codigo')->nullable()->after('website_type_code');
});
Schema::table('websites_extras', function (Blueprint $table): void {
$table->unique(
['website_code', 'website_type_extra_id'],
'websites_extras_website_definition_unique'
);
});
DB::table('website_type_extras')
->select(['id', 'nombre'])
->orderBy('id')
->each(function (object $extra): void {
DB::table('website_type_extras')
->where('id', $extra->id)
->update(['codigo' => $extra->nombre]);
});
Schema::table('website_type_extras', function (Blueprint $table): void {
$table->string('codigo')->nullable(false)->change();
$table->unique(
['website_type_code', 'codigo'],
'website_type_extras_type_code_unique'
);
});
}
public function down(): void
{
Schema::table('websites_extras', function (Blueprint $table): void {
$table->dropUnique('websites_extras_website_definition_unique');
});
Schema::table('website_type_extras', function (Blueprint $table): void {
$table->dropUnique('website_type_extras_type_code_unique');
$table->dropColumn('codigo');
});
}
};

View File

@@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
public function up(): void
{
DB::table('website_type_extras')
->select(['id', 'config_schema'])
->orderBy('id')
->each(function (object $definition): void {
$schema = json_decode($definition->config_schema, true);
if (! is_array($schema) || ! array_key_exists('database_rules', $schema)) {
return;
}
unset($schema['database_rules']);
DB::table('website_type_extras')
->where('id', $definition->id)
->update(['config_schema' => json_encode($schema)]);
});
}
public function down(): void
{
// Removed rules cannot be reconstructed generically.
}
};

View File

@@ -0,0 +1,22 @@
<?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::table('websites_extras', function (Blueprint $table): void {
$table->boolean('is_enabled')->nullable()->after('config');
});
}
public function down(): void
{
Schema::table('websites_extras', function (Blueprint $table): void {
$table->dropColumn('is_enabled');
});
}
};

View File

@@ -0,0 +1,57 @@
<?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::table('website_type', function (Blueprint $table): void {
$table->string('dominio')->nullable()->unique()->after('nombre');
$table->string('primary_color')->nullable()->after('dominio');
$table->string('secondary_color')->nullable()->after('primary_color');
$table->string('danger_color')->nullable()->after('secondary_color');
$table->string('success_color')->nullable()->after('danger_color');
$table->string('warning_color')->nullable()->after('success_color');
$table->string('body_color')->nullable()->after('warning_color');
$table->string('darker_body_color')->nullable()->after('body_color');
$table->string('surface_color')->nullable()->after('darker_body_color');
$table->string('background_color')->nullable()->after('surface_color');
$table->string('border_color')->nullable()->after('background_color');
$table->string('login_header_footer_color')->nullable()->after('border_color');
$table->unsignedBigInteger('site_logo')->nullable()->after('login_header_footer_color');
$table->foreign('site_logo')
->references('id')
->on('attachments')
->nullOnDelete();
});
}
public function down(): void
{
Schema::table('website_type', function (Blueprint $table): void {
if (Schema::getConnection()->getDriverName() !== 'sqlite') {
$table->dropForeign(['site_logo']);
}
$table->dropColumn([
'dominio',
'primary_color',
'secondary_color',
'danger_color',
'success_color',
'warning_color',
'body_color',
'darker_body_color',
'surface_color',
'background_color',
'border_color',
'login_header_footer_color',
'site_logo',
]);
});
}
};

View File

@@ -0,0 +1,31 @@
<?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::table('website_type', function (Blueprint $table): void {
$table->unsignedBigInteger('footer_logo')->nullable()->after('site_logo');
$table->foreign('footer_logo')
->references('id')
->on('attachments')
->nullOnDelete();
});
}
public function down(): void
{
Schema::table('website_type', function (Blueprint $table): void {
if (Schema::getConnection()->getDriverName() !== 'sqlite') {
$table->dropForeign(['footer_logo']);
}
$table->dropColumn('footer_logo');
});
}
};

View File

@@ -0,0 +1,80 @@
<?php
use App\Domains\Catalog\Enums\EventProductType;
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('events', function (Blueprint $table): void {
$table->id();
$table->string('tenant_code');
$table->string('name');
$table->string('address');
$table->foreign('tenant_code')
->references('codigo')
->on('tenants')
->cascadeOnUpdate()
->cascadeOnDelete();
});
Schema::create('event_dates', function (Blueprint $table): void {
$table->id();
$table->foreignId('event_id')->constrained('events')->cascadeOnDelete();
$table->date('date');
$table->time('time_start');
$table->time('time_end');
});
Schema::table('tenants', function (Blueprint $table): void {
$table->foreignId('active_event_id')
->nullable()
->constrained('events')
->nullOnDelete();
});
Schema::table('catalog_items', function (Blueprint $table): void {
$table->foreignId('event_id')
->nullable()
->after('tenant_code')
->constrained('events')
->nullOnDelete();
$table->enum('event_product_type', EventProductType::values())
->nullable()
->after('event_id');
});
Schema::table('variantes', function (Blueprint $table): void {
$table->foreignId('event_date_id')
->nullable()
->after('catalog_item_id')
->constrained('event_dates')
->nullOnDelete();
$table->unique(['catalog_item_id', 'event_date_id']);
});
}
public function down(): void
{
Schema::table('tenants', function (Blueprint $table): void {
$table->dropConstrainedForeignId('active_event_id');
});
Schema::table('variantes', function (Blueprint $table): void {
$table->dropUnique(['catalog_item_id', 'event_date_id']);
$table->dropConstrainedForeignId('event_date_id');
});
Schema::table('catalog_items', function (Blueprint $table): void {
$table->dropConstrainedForeignId('event_id');
$table->dropColumn('event_product_type');
});
Schema::dropIfExists('event_dates');
Schema::dropIfExists('events');
}
};

View File

@@ -0,0 +1,43 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
DB::table('tickets')
->whereNotNull('source_variant_id')
->whereNotIn('source_variant_id', DB::table('variantes')->select('id'))
->update(['source_variant_id' => null]);
DB::table('tickets')
->whereNotNull('source_catalog_item_id')
->whereNotIn('source_catalog_item_id', DB::table('catalog_items')->select('id'))
->update(['source_catalog_item_id' => null]);
Schema::table('tickets', function (Blueprint $table): void {
$table->foreign('source_catalog_item_id')
->references('id')
->on('catalog_items')
->cascadeOnUpdate()
->nullOnDelete();
$table->foreign('source_variant_id')
->references('id')
->on('variantes')
->cascadeOnUpdate()
->nullOnDelete();
});
}
public function down(): void
{
Schema::table('tickets', function (Blueprint $table): void {
$table->dropForeign(['source_catalog_item_id']);
$table->dropForeign(['source_variant_id']);
});
}
};

View File

@@ -0,0 +1,31 @@
<?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('value_changes', function (Blueprint $table): void {
$table->id();
$table->morphs('trackable');
$table->string('attribute');
$table->text('old_value')->nullable();
$table->text('new_value')->nullable();
$table->timestamp('changed_at');
$table->string('actor_type');
$table->foreignId('user_id')
->nullable()
->constrained('users')
->cascadeOnUpdate()
->nullOnDelete();
});
}
public function down(): void
{
Schema::dropIfExists('value_changes');
}
};

View File

@@ -1,28 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('reset_password_attempts', function (Blueprint $table): void {
$table->string('reason')->default('manual')->after('codigo');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('reset_password_attempts', function (Blueprint $table): void {
$table->dropColumn('reason');
});
}
};

View File

@@ -17,83 +17,79 @@ class AttributeSeeder extends Seeder
$tenants = Tenant::all();
foreach ($tenants as $tenant) {
// Fiesta Futbol Infantil only uses the Fecha attribute.
// Event dates replace catalog attributes for Fiesta Futbol Infantil.
if ($tenant->codigo === 'fiesta_futbol_infantil') {
Attribute::query()
->where('tenant_codigo', $tenant->codigo)
->whereIn('codigo', ['color', 'talle', 'talle_numerico'])
->whereIn('codigo', ['color', 'talle', 'talle_numerico', 'fecha'])
->delete();
continue;
}
if ($tenant->codigo !== 'fiesta_futbol_infantil') {
$this->seedAttribute($tenant, [
'codigo' => 'color',
'nombre' => 'Color',
'type' => FieldType::Select->value,
'is_required' => true,
'metadata_schema' => [
'hex' => ['type' => 'string'],
$this->seedAttribute($tenant, [
'codigo' => 'color',
'nombre' => 'Color',
'type' => FieldType::Select->value,
'is_required' => true,
'metadata_schema' => [
'hex' => ['type' => 'string'],
],
'options' => [
[
'value' => 'Negro',
'label' => 'Negro',
'sort_order' => 1,
'metadata' => ['hex' => '#000000'],
],
'options' => [
[
'value' => 'Negro',
'label' => 'Negro',
'sort_order' => 1,
'metadata' => ['hex' => '#000000'],
],
[
'value' => 'Gris',
'label' => 'Gris',
'sort_order' => 2,
'metadata' => ['hex' => '#808080'],
],
[
'value' => 'Blanco',
'label' => 'Blanco',
'sort_order' => 3,
'metadata' => ['hex' => '#FFFFFF'],
],
[
'value' => 'Azul',
'label' => 'Azul',
'sort_order' => 4,
'metadata' => ['hex' => '#0000FF'],
],
[
'value' => 'Gris',
'label' => 'Gris',
'sort_order' => 2,
'metadata' => ['hex' => '#808080'],
],
]);
}
[
'value' => 'Blanco',
'label' => 'Blanco',
'sort_order' => 3,
'metadata' => ['hex' => '#FFFFFF'],
],
[
'value' => 'Azul',
'label' => 'Azul',
'sort_order' => 4,
'metadata' => ['hex' => '#0000FF'],
],
],
]);
// Seed Talle (Size - Text options) attribute
if ($tenant->codigo !== 'fiesta_futbol_infantil') {
$this->seedAttribute($tenant, [
'codigo' => 'talle',
'nombre' => 'Talle',
'type' => FieldType::Select->value,
'is_required' => true,
'options' => [
['value' => 'S', 'label' => 'S', 'sort_order' => 1],
['value' => 'M', 'label' => 'M', 'sort_order' => 2],
['value' => 'L', 'label' => 'L', 'sort_order' => 3],
['value' => 'XL', 'label' => 'XL', 'sort_order' => 4],
],
]);
}
$this->seedAttribute($tenant, [
'codigo' => 'talle',
'nombre' => 'Talle',
'type' => FieldType::Select->value,
'is_required' => true,
'options' => [
['value' => 'S', 'label' => 'S', 'sort_order' => 1],
['value' => 'M', 'label' => 'M', 'sort_order' => 2],
['value' => 'L', 'label' => 'L', 'sort_order' => 3],
['value' => 'XL', 'label' => 'XL', 'sort_order' => 4],
],
]);
// Seed Talle Numérico (Numeric Size options) attribute
if ($tenant->codigo !== 'fiesta_futbol_infantil') {
$this->seedAttribute($tenant, [
'codigo' => 'talle_numerico',
'nombre' => 'Talle Numérico',
'type' => FieldType::Select->value,
'is_required' => true,
'options' => [
['value' => '38', 'label' => '38', 'sort_order' => 1],
['value' => '40', 'label' => '40', 'sort_order' => 2],
['value' => '42', 'label' => '42', 'sort_order' => 3],
['value' => '44', 'label' => '44', 'sort_order' => 4],
],
]);
}
$this->seedAttribute($tenant, [
'codigo' => 'talle_numerico',
'nombre' => 'Talle Numérico',
'type' => FieldType::Select->value,
'is_required' => true,
'options' => [
['value' => '38', 'label' => '38', 'sort_order' => 1],
['value' => '40', 'label' => '40', 'sort_order' => 2],
['value' => '42', 'label' => '42', 'sort_order' => 3],
['value' => '44', 'label' => '44', 'sort_order' => 4],
],
]);
// Seed Fecha attribute
$this->seedAttribute($tenant, [

View File

@@ -0,0 +1,152 @@
<?php
namespace Database\Seeders;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Authorization\Models\Permission;
use App\Domains\Authorization\Models\Role;
use Illuminate\Database\Seeder;
class AuthorizationSeeder extends Seeder
{
/**
* @var array<string, array{nombre: string, descripcion: string}>
*/
private const PERMISSIONS = [
'tenant.ver' => [
'nombre' => 'Ver configuración del tenant',
'descripcion' => 'Permite consultar la configuración general de un tenant.',
],
'tenant.editar' => [
'nombre' => 'Editar configuración del tenant',
'descripcion' => 'Permite modificar los datos generales, dominio, colores y recursos visuales del tenant.',
],
'usuarios.ver' => [
'nombre' => 'Ver usuarios',
'descripcion' => 'Permite consultar los usuarios asociados al tenant.',
],
'usuarios.gestionar' => [
'nombre' => 'Gestionar usuarios',
'descripcion' => 'Permite invitar, editar, desactivar y asignar roles permitidos a los usuarios del tenant.',
],
'roles.ver' => [
'nombre' => 'Ver roles',
'descripcion' => 'Permite consultar los roles y sus permisos.',
],
'roles.gestionar' => [
'nombre' => 'Gestionar roles',
'descripcion' => 'Permite crear, modificar y asignar permisos a roles.',
],
'catalogo.ver' => [
'nombre' => 'Ver catálogo',
'descripcion' => 'Permite consultar administrativamente productos, variantes, categorías, marcas y bundles.',
],
'catalogo.gestionar' => [
'nombre' => 'Gestionar catálogo',
'descripcion' => 'Permite crear, modificar, archivar y eliminar productos, variantes, categorías, marcas y bundles.',
],
'inventario.ver' => [
'nombre' => 'Ver inventario',
'descripcion' => 'Permite consultar el stock y la información de inventario.',
],
'inventario.ajustar' => [
'nombre' => 'Ajustar inventario',
'descripcion' => 'Permite modificar el stock disponible.',
],
'pedidos.ver' => [
'nombre' => 'Ver pedidos',
'descripcion' => 'Permite consultar los pedidos del tenant.',
],
'pedidos.gestionar' => [
'nombre' => 'Gestionar pedidos',
'descripcion' => 'Permite modificar estados y datos operativos de los pedidos.',
],
'pedidos.cancelar' => [
'nombre' => 'Cancelar pedidos',
'descripcion' => 'Permite cancelar pedidos y liberar sus reservas de inventario.',
],
'pagos.ver' => [
'nombre' => 'Ver pagos',
'descripcion' => 'Permite consultar el estado y la información de los pagos.',
],
'pagos.gestionar' => [
'nombre' => 'Gestionar pagos',
'descripcion' => 'Permite confirmar, rechazar o devolver pagos.',
],
'tickets.ver' => [
'nombre' => 'Ver tickets',
'descripcion' => 'Permite consultar los tickets emitidos.',
],
'tickets.gestionar' => [
'nombre' => 'Gestionar tickets',
'descripcion' => 'Permite emitir, invalidar o regenerar tickets.',
],
'contenido.gestionar' => [
'nombre' => 'Gestionar contenido',
'descripcion' => 'Permite administrar menús, carruseles, destacados y redes sociales.',
],
'integraciones.ver' => [
'nombre' => 'Ver integraciones',
'descripcion' => 'Permite consultar la configuración y el estado de las integraciones.',
],
'integraciones.gestionar' => [
'nombre' => 'Gestionar integraciones',
'descripcion' => 'Permite configurar credenciales y proveedores de integraciones.',
],
'reportes.ver' => [
'nombre' => 'Ver reportes',
'descripcion' => 'Permite consultar reportes de ventas y métricas.',
],
'reportes.exportar' => [
'nombre' => 'Exportar reportes',
'descripcion' => 'Permite descargar reportes e información comercial.',
],
];
/**
* @var array<string, array{nombre: string, descripcion: string, permisos: list<string>}>
*/
private const ROLES = [
RoleCode::Admin->value => [
'nombre' => 'Administrador general',
'descripcion' => 'Administra la plataforma y todos sus tenants.',
'permisos' => [],
],
RoleCode::AdminApp->value => [
'nombre' => 'Administrador de la aplicación',
'descripcion' => 'Accede a los menús administrativos de la aplicación.',
'permisos' => [],
],
RoleCode::User->value => [
'nombre' => 'Usuario',
'descripcion' => 'Cliente final limitado a sus propios datos y operaciones.',
'permisos' => [],
],
];
public function run(): void
{
foreach (self::PERMISSIONS as $code => $attributes) {
Permission::query()->updateOrCreate(
['codigo' => $code],
$attributes
);
}
foreach (self::ROLES as $code => $attributes) {
$role = Role::query()->updateOrCreate(
['codigo' => $code],
[
'nombre' => $attributes['nombre'],
'descripcion' => $attributes['descripcion'],
]
);
$permissionCodes = $code === RoleCode::Admin->value
? array_keys(self::PERMISSIONS)
: $attributes['permisos'];
$role->permissions()->sync($permissionCodes);
}
}
}

View File

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

View File

@@ -3,6 +3,7 @@
namespace Database\Seeders;
use App\Domains\Catalog\Enums\CatalogItemType;
use App\Domains\Catalog\Enums\EventProductType;
use App\Domains\Catalog\Enums\GroupLayout;
use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Enums\ProductLayout;
@@ -10,6 +11,7 @@ use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Category;
use App\Domains\Catalog\Models\FeaturedGroup;
use App\Domains\Catalog\Services\CatalogService;
use App\Domains\Event\Models\Event;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Seeder;
use RuntimeException;
@@ -28,6 +30,29 @@ class FiestaFutbolInfantilProductSeeder extends Seeder
$this->deleteExistingCatalog($tenant);
$event = Event::query()->updateOrCreate(
[
'tenant_code' => $tenant->codigo,
'name' => 'Fiesta Nacional del Fútbol Infantil',
],
['address' => 'Sunchales, Santa Fe'],
);
$event->dates()->delete();
$eventDates = collect(['2026-10-09', '2026-10-10', '2026-10-11', '2026-10-12'])
->mapWithKeys(function (string $date) use ($event): array {
$eventDate = $event->dates()->create([
'date' => $date,
'time_start' => '00:00:00',
'time_end' => '23:59:59',
]);
return [$date => $eventDate];
});
$tenant->active_event_id = $event->id;
$tenant->save();
$ticketCategory = Category::query()->firstOrCreate([
'nombre' => 'Entradas',
'tenant_code' => $tenant->codigo,
@@ -41,12 +66,14 @@ class FiestaFutbolInfantilProductSeeder extends Seeder
'tenant_code' => $tenant->codigo,
]);
$dates = ['2026-10-09', '2026-10-10', '2026-10-11', '2026-10-12'];
$dates = $eventDates->keys()->all();
$minimumUseDate = $dates[0].' 00:00:00';
$maximumUseDate = $dates[array_key_last($dates)].' 23:59:59';
$generalAdmission = $this->catalogService->create([
'tenant_code' => $tenant->codigo,
'event_id' => $event->id,
'event_product_type' => EventProductType::Entry->value,
'category_id' => $ticketCategory->id,
'slug' => 'entrada-general',
'nombre' => 'Entrada General',
@@ -56,13 +83,10 @@ class FiestaFutbolInfantilProductSeeder extends Seeder
'has_tickets' => true,
'minimum_use_date' => $minimumUseDate,
'maximum_use_date' => $maximumUseDate,
'attribute_codes' => ['fecha'],
'variants' => array_map(
fn (string $date): array => [
'real_stock' => 0,
'minimum_use_date' => $date.' 00:00:00',
'maximum_use_date' => $date.' 23:59:59',
'values' => ['fecha' => $date],
'event_date_id' => $eventDates->get($date)->id,
],
$dates,
),
@@ -81,6 +105,8 @@ class FiestaFutbolInfantilProductSeeder extends Seeder
foreach ($items as $item) {
$createdItems[$item['slug']] = $this->catalogService->create([
'tenant_code' => $tenant->codigo,
'event_id' => $event->id,
'event_product_type' => EventProductType::Product->value,
'descripcion' => $item['descripcion'] ?? $item['nombre'],
'inventory_policy' => InventoryPolicy::Unlimited->value,
'real_stock' => 0,
@@ -92,6 +118,8 @@ class FiestaFutbolInfantilProductSeeder extends Seeder
$this->catalogService->create([
'tenant_code' => $tenant->codigo,
'event_id' => $event->id,
'event_product_type' => EventProductType::Entry->value,
'type' => CatalogItemType::Bundle->value,
'slug' => 'entrada-general-todos-los-dias',
'nombre' => 'Entrada General - Todos los días',
@@ -109,6 +137,8 @@ class FiestaFutbolInfantilProductSeeder extends Seeder
$this->catalogService->create([
'tenant_code' => $tenant->codigo,
'event_id' => $event->id,
'event_product_type' => EventProductType::Product->value,
'type' => CatalogItemType::Bundle->value,
'slug' => 'combo-2-panchos-2-hamburguesas',
'nombre' => 'Combo 2 Panchos + 2 Hamburguesas',

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