Compare commits
43 Commits
homo
...
8aa3a26ee7
| Author | SHA1 | Date | |
|---|---|---|---|
| 8aa3a26ee7 | |||
| 1de08c1ca4 | |||
| 3f9bcd84c4 | |||
| 96f26e2e9d | |||
| c4b317d5fc | |||
| 3b2977a330 | |||
| 3b36abd46d | |||
| 12697c2268 | |||
| f4638bc984 | |||
| c3713c62a6 | |||
| 4a51f3afde | |||
| f1df6a5918 | |||
| dbeaf19513 | |||
| dd76d5d951 | |||
| f603a82b5e | |||
| b478c23f3b | |||
| 6858b387c3 | |||
| 893bea1492 | |||
| ec1d80dff2 | |||
| 3968a10f6a | |||
| cf2beb2ff5 | |||
| 484fa204b3 | |||
| 6dd057874a | |||
| 40cbac17c6 | |||
| 45e56c43a6 | |||
| cbb7b1c3a1 | |||
| 6b3a12b624 | |||
| 40a7dece11 | |||
| 5ec65ce3d3 | |||
| b7e1332b8c | |||
| a087a511e0 | |||
| a20b1713d3 | |||
| d56d387933 | |||
| cba32e90e7 | |||
| a674bcfabc | |||
| ace3f136e4 | |||
| 2cc72be850 | |||
| 8e3ee7eff6 | |||
| 27d4f9fac6 | |||
| 9e3163b74f | |||
| b9ad2e589f | |||
| 5416c0fd61 | |||
| 04bf03fc2e |
@@ -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."
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
42
app/Domains/Auth/Controllers/AdminAppLoginController.php
Normal file
42
app/Domains/Auth/Controllers/AdminAppLoginController.php
Normal 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),
|
||||
]);
|
||||
}
|
||||
}
|
||||
26
app/Domains/Auth/Controllers/AdminAppMeController.php
Normal file
26
app/Domains/Auth/Controllers/AdminAppMeController.php
Normal 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)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
*/
|
||||
|
||||
36
app/Domains/Auth/Requests/AdminAppLoginRequest.php
Normal file
36
app/Domains/Auth/Requests/AdminAppLoginRequest.php
Normal 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'],
|
||||
];
|
||||
}
|
||||
}
|
||||
25
app/Domains/Auth/Resources/AdminAppMeResource.php
Normal file
25
app/Domains/Auth/Resources/AdminAppMeResource.php
Normal 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),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
26
app/Domains/Auth/Services/AdminAppContextService.php
Normal file
26
app/Domains/Auth/Services/AdminAppContextService.php
Normal 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;
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ 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;
|
||||
@@ -22,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();
|
||||
@@ -34,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,
|
||||
@@ -76,7 +127,7 @@ class PasswordLoginService
|
||||
$this->recordAttempt(
|
||||
$user,
|
||||
$normalizedEmail,
|
||||
$tenantCode,
|
||||
$attemptTenantCode,
|
||||
$outcome,
|
||||
$ipAddress,
|
||||
$userAgent,
|
||||
@@ -100,7 +151,7 @@ class PasswordLoginService
|
||||
$this->recordAttempt(
|
||||
$user,
|
||||
$normalizedEmail,
|
||||
$tenantCode,
|
||||
$attemptTenantCode,
|
||||
LoginAttempt::OUTCOME_SUCCESS,
|
||||
$ipAddress,
|
||||
$userAgent,
|
||||
@@ -150,7 +201,7 @@ class PasswordLoginService
|
||||
private function recordAttempt(
|
||||
?User $user,
|
||||
string $normalizedEmail,
|
||||
string $tenantCode,
|
||||
?string $tenantCode,
|
||||
string $outcome,
|
||||
?string $ipAddress,
|
||||
?string $userAgent,
|
||||
|
||||
11
app/Domains/Auth/routes/adminapp.php
Normal file
11
app/Domains/Auth/routes/adminapp.php
Normal 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);
|
||||
});
|
||||
@@ -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';
|
||||
|
||||
10
app/Domains/Authorization/Enums/RoleCode.php
Normal file
10
app/Domains/Authorization/Enums/RoleCode.php
Normal file
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Authorization\Enums;
|
||||
|
||||
enum RoleCode: string
|
||||
{
|
||||
case Admin = 'admin';
|
||||
case AdminApp = 'adminapp';
|
||||
case User = 'user';
|
||||
}
|
||||
32
app/Domains/Authorization/Models/Permission.php
Normal file
32
app/Domains/Authorization/Models/Permission.php
Normal 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();
|
||||
}
|
||||
}
|
||||
59
app/Domains/Authorization/Models/Role.php
Normal file
59
app/Domains/Authorization/Models/Role.php
Normal 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);
|
||||
}
|
||||
}
|
||||
32
app/Domains/Authorization/Models/RolePermission.php
Normal file
32
app/Domains/Authorization/Models/RolePermission.php
Normal 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');
|
||||
}
|
||||
}
|
||||
@@ -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'))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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'))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Bootstrap\Requests;
|
||||
|
||||
class AdminAppBootstrapRequest extends TenantBootstrapRequest {}
|
||||
@@ -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 [
|
||||
@@ -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),
|
||||
];
|
||||
}
|
||||
}
|
||||
19
app/Domains/Bootstrap/Services/AdminAppBootstrapService.php
Normal file
19
app/Domains/Bootstrap/Services/AdminAppBootstrapService.php
Normal 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(),
|
||||
];
|
||||
}
|
||||
}
|
||||
26
app/Domains/Bootstrap/Services/TenantBootstrapService.php
Normal file
26
app/Domains/Bootstrap/Services/TenantBootstrapService.php
Normal 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'),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
9
app/Domains/Bootstrap/routes/adminapp.php
Normal file
9
app/Domains/Bootstrap/routes/adminapp.php
Normal 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
|
||||
);
|
||||
9
app/Domains/Bootstrap/routes/api.php
Normal file
9
app/Domains/Bootstrap/routes/api.php
Normal 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';
|
||||
@@ -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',
|
||||
|
||||
15
app/Domains/Catalog/Enums/EventProductType.php
Normal file
15
app/Domains/Catalog/Enums/EventProductType.php
Normal 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');
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
|
||||
@@ -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
|
||||
{
|
||||
@@ -80,7 +96,7 @@ class Variant extends Model
|
||||
public function getName(): string
|
||||
{
|
||||
$name = $this->catalogItem->nombre;
|
||||
$this->loadMissing('definitions.itemAttribute.attribute');
|
||||
$this->loadMissing(['definitions.itemAttribute.attribute', 'eventDate']);
|
||||
$definitions = $this->definitions
|
||||
->map(function (VariantDefinition $definition): ?string {
|
||||
$attributeName = $definition->itemAttribute?->attribute?->nombre;
|
||||
@@ -89,21 +105,28 @@ class Variant extends Model
|
||||
? "{$attributeName}: {$definition->value}"
|
||||
: $definition->value;
|
||||
})
|
||||
->filter()
|
||||
->implode(', ');
|
||||
->filter();
|
||||
|
||||
return $definitions === '' ? $name : "{$name} ({$definitions})";
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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'],
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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) => [
|
||||
|
||||
@@ -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) => [
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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();
|
||||
|
||||
31
app/Domains/Event/Controllers/AdminApp/EventController.php
Normal file
31
app/Domains/Event/Controllers/AdminApp/EventController.php
Normal 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()
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
48
app/Domains/Event/Models/Event.php
Normal file
48
app/Domains/Event/Models/Event.php
Normal file
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Event\Models;
|
||||
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
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);
|
||||
}
|
||||
|
||||
/** @return HasMany<Purchase, $this> */
|
||||
public function purchases(): HasMany
|
||||
{
|
||||
return $this->hasMany(Purchase::class);
|
||||
}
|
||||
}
|
||||
55
app/Domains/Event/Models/EventDate.php
Normal file
55
app/Domains/Event/Models/EventDate.php
Normal 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);
|
||||
}
|
||||
}
|
||||
60
app/Domains/Event/Requests/UpdateEventRequest.php
Normal file
60
app/Domains/Event/Requests/UpdateEventRequest.php
Normal 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.'
|
||||
);
|
||||
}
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
39
app/Domains/Event/Resources/EventResource.php
Normal file
39
app/Domains/Event/Resources/EventResource.php
Normal 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,
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
120
app/Domains/Event/Services/EventService.php
Normal file
120
app/Domains/Event/Services/EventService.php
Normal 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');
|
||||
}
|
||||
}
|
||||
11
app/Domains/Event/routes/adminapp.php
Normal file
11
app/Domains/Event/routes/adminapp.php
Normal 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']);
|
||||
});
|
||||
3
app/Domains/Event/routes/api.php
Normal file
3
app/Domains/Event/routes/api.php
Normal file
@@ -0,0 +1,3 @@
|
||||
<?php
|
||||
|
||||
require __DIR__.'/adminapp.php';
|
||||
@@ -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()
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Forms\Controllers\AdminApp;
|
||||
|
||||
use App\Domains\Forms\Resources\SaleFormResource;
|
||||
use App\Domains\Forms\Services\SaleFormService;
|
||||
use App\Http\Controllers\Controller;
|
||||
|
||||
class SaleFormController extends Controller
|
||||
{
|
||||
public function __construct(protected SaleFormService $saleFormService) {}
|
||||
|
||||
public function __invoke(): SaleFormResource
|
||||
{
|
||||
return SaleFormResource::make($this->saleFormService->get());
|
||||
}
|
||||
}
|
||||
19
app/Domains/Forms/Resources/EventFormResource.php
Normal file
19
app/Domains/Forms/Resources/EventFormResource.php
Normal 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']
|
||||
),
|
||||
];
|
||||
}
|
||||
}
|
||||
17
app/Domains/Forms/Resources/SaleFormResource.php
Normal file
17
app/Domains/Forms/Resources/SaleFormResource.php
Normal file
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Forms\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class SaleFormResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'statuses' => $this->resource['statuses'],
|
||||
];
|
||||
}
|
||||
}
|
||||
22
app/Domains/Forms/Resources/SocialMediaOptionResource.php
Normal file
22
app/Domains/Forms/Resources/SocialMediaOptionResource.php
Normal 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,
|
||||
];
|
||||
}
|
||||
}
|
||||
27
app/Domains/Forms/Services/EventFormService.php
Normal file
27
app/Domains/Forms/Services/EventFormService.php
Normal 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)
|
||||
)),
|
||||
];
|
||||
}
|
||||
}
|
||||
31
app/Domains/Forms/Services/SaleFormService.php
Normal file
31
app/Domains/Forms/Services/SaleFormService.php
Normal file
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Forms\Services;
|
||||
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
|
||||
class SaleFormService
|
||||
{
|
||||
/** @return array{statuses: list<array{code: string, name: string}>} */
|
||||
public function get(): array
|
||||
{
|
||||
$names = [
|
||||
Purchase::STATUS_CREATED => 'Creada',
|
||||
Purchase::STATUS_PENDING_PAYMENT => 'Esperando pago',
|
||||
Purchase::STATUS_PAID => 'Confirmada',
|
||||
Purchase::STATUS_CANCELLED => 'Cancelada',
|
||||
Purchase::STATUS_REJECTED => 'Rechazada',
|
||||
Purchase::STATUS_EXPIRED => 'Vencida',
|
||||
];
|
||||
|
||||
return [
|
||||
'statuses' => array_map(
|
||||
fn (string $status): array => [
|
||||
'code' => $status,
|
||||
'name' => $names[$status],
|
||||
],
|
||||
Purchase::statuses(),
|
||||
),
|
||||
];
|
||||
}
|
||||
}
|
||||
12
app/Domains/Forms/routes/adminapp.php
Normal file
12
app/Domains/Forms/routes/adminapp.php
Normal file
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Forms\Controllers\AdminApp\EventFormController;
|
||||
use App\Domains\Forms\Controllers\AdminApp\SaleFormController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('v1/adminapp/forms')
|
||||
->middleware(['auth:sanctum', 'adminapp.tenant'])
|
||||
->group(function (): void {
|
||||
Route::get('event', EventFormController::class);
|
||||
Route::get('sale', SaleFormController::class);
|
||||
});
|
||||
3
app/Domains/Forms/routes/api.php
Normal file
3
app/Domains/Forms/routes/api.php
Normal file
@@ -0,0 +1,3 @@
|
||||
<?php
|
||||
|
||||
require __DIR__.'/adminapp.php';
|
||||
@@ -57,13 +57,9 @@ class TelepagosWebhookService
|
||||
->whereIn('status', [
|
||||
Purchase::STATUS_CREATED,
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
Purchase::STATUS_IN_REVIEW,
|
||||
])
|
||||
->where('payment_method', 'transfer')
|
||||
->where('total', $amount)
|
||||
->orderByRaw('CASE WHEN status = ? THEN 0 ELSE 1 END', [
|
||||
Purchase::STATUS_IN_REVIEW,
|
||||
])
|
||||
->latest()
|
||||
->first();
|
||||
|
||||
@@ -97,7 +93,6 @@ class TelepagosWebhookService
|
||||
|
||||
if (! in_array($compra->status, [
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
Purchase::STATUS_IN_REVIEW,
|
||||
], true)) {
|
||||
Log::warning("Telepagos webhook: Purchase {$compra->id} is not awaiting payment confirmation");
|
||||
|
||||
|
||||
9
app/Domains/Logging/Enums/ValueChangeActorType.php
Normal file
9
app/Domains/Logging/Enums/ValueChangeActorType.php
Normal file
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Logging\Enums;
|
||||
|
||||
enum ValueChangeActorType: string
|
||||
{
|
||||
case User = 'user';
|
||||
case System = 'system';
|
||||
}
|
||||
65
app/Domains/Logging/Models/Concerns/LogsValueChanges.php
Normal file
65
app/Domains/Logging/Models/Concerns/LogsValueChanges.php
Normal file
@@ -0,0 +1,65 @@
|
||||
<?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
|
||||
{
|
||||
abstract protected function valueChangeTenantCode(): string;
|
||||
|
||||
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([
|
||||
'tenant_code' => $model->valueChangeTenantCode(),
|
||||
'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');
|
||||
}
|
||||
}
|
||||
55
app/Domains/Logging/Models/ValueChange.php
Normal file
55
app/Domains/Logging/Models/ValueChange.php
Normal file
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Logging\Models;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Logging\Enums\ValueChangeActorType;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\MorphTo;
|
||||
|
||||
#[Fillable([
|
||||
'tenant_code',
|
||||
'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);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Tenant, $this> */
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
|
||||
}
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'trackable_id' => 'integer',
|
||||
'changed_at' => 'datetime',
|
||||
'actor_type' => ValueChangeActorType::class,
|
||||
'user_id' => 'integer',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
31
app/Domains/Menu/Models/MenuRole.php
Normal file
31
app/Domains/Menu/Models/MenuRole.php
Normal 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');
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
@@ -124,14 +125,28 @@ class PurchaseController extends Controller
|
||||
$purchaseUpdate['transfer_payer_dni'] = preg_replace('/\D+/', '', (string) $request->validated('transfer_payer_dni'));
|
||||
}
|
||||
|
||||
$updated = Purchase::query()
|
||||
->whereKey($compra->getKey())
|
||||
->whereIn('status', [Purchase::STATUS_CREATED, Purchase::STATUS_PENDING_PAYMENT])
|
||||
->where(function ($query): void {
|
||||
$query->whereNull('expires_at')
|
||||
->orWhere('expires_at', '>', now());
|
||||
})
|
||||
->update($purchaseUpdate);
|
||||
$updated = DB::transaction(function () use ($compra, $purchaseUpdate): bool {
|
||||
/** @var Purchase|null $purchase */
|
||||
$purchase = Purchase::query()
|
||||
->whereKey($compra->getKey())
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if (
|
||||
$purchase === null
|
||||
|| ! in_array($purchase->status, [
|
||||
Purchase::STATUS_CREATED,
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
], true)
|
||||
|| ($purchase->expires_at !== null && $purchase->expires_at->isPast())
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$purchase->update($purchaseUpdate);
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
if ($updated === 0) {
|
||||
throw ValidationException::withMessages([
|
||||
|
||||
@@ -4,6 +4,8 @@ namespace App\Domains\Purchase\Models;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Event\Models\Event;
|
||||
use App\Domains\Logging\Models\Concerns\LogsValueChanges;
|
||||
use App\Domains\Purchase\Events\PurchasePaid;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
@@ -18,6 +20,7 @@ use Illuminate\Support\Facades\DB;
|
||||
#[Fillable([
|
||||
'cart_id',
|
||||
'tenant_codigo',
|
||||
'event_id',
|
||||
'user_id',
|
||||
'status',
|
||||
'payment_method',
|
||||
@@ -31,14 +34,12 @@ use Illuminate\Support\Facades\DB;
|
||||
])]
|
||||
class Purchase extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
use HasFactory, LogsValueChanges;
|
||||
|
||||
public const STATUS_CREATED = 'created';
|
||||
|
||||
public const STATUS_PENDING_PAYMENT = 'pending_payment';
|
||||
|
||||
public const STATUS_IN_REVIEW = 'in_review';
|
||||
|
||||
public const STATUS_PAID = 'paid';
|
||||
|
||||
public const STATUS_CANCELLED = 'cancelled';
|
||||
@@ -47,12 +48,31 @@ class Purchase extends Model
|
||||
|
||||
public const STATUS_EXPIRED = 'expired';
|
||||
|
||||
/** @return list<string> */
|
||||
public static function statuses(): array
|
||||
{
|
||||
return [
|
||||
self::STATUS_CREATED,
|
||||
self::STATUS_PENDING_PAYMENT,
|
||||
self::STATUS_PAID,
|
||||
self::STATUS_CANCELLED,
|
||||
self::STATUS_REJECTED,
|
||||
self::STATUS_EXPIRED,
|
||||
];
|
||||
}
|
||||
|
||||
protected $table = 'compras';
|
||||
|
||||
/** @var array<int, string> */
|
||||
protected array $loggedAttributes = [
|
||||
'status',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'cart_id' => 'integer',
|
||||
'event_id' => 'integer',
|
||||
'user_id' => 'integer',
|
||||
'expires_at' => 'datetime',
|
||||
'total' => 'decimal:2',
|
||||
@@ -67,6 +87,12 @@ class Purchase extends Model
|
||||
return $this->belongsTo(Tenant::class, 'tenant_codigo', 'codigo');
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Event, $this> */
|
||||
public function event(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Event::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<User, $this>
|
||||
*/
|
||||
@@ -133,6 +159,11 @@ class Purchase extends Model
|
||||
return (float) $this->items()->sum('total');
|
||||
}
|
||||
|
||||
protected function valueChangeTenantCode(): string
|
||||
{
|
||||
return $this->tenant_codigo;
|
||||
}
|
||||
|
||||
public function markAsPendingPayment(): void
|
||||
{
|
||||
$this->update([
|
||||
|
||||
@@ -42,6 +42,7 @@ class PurchaseResource extends JsonResource
|
||||
'id' => $this->id,
|
||||
'cart_id' => $this->cart_id,
|
||||
'tenant_codigo' => $this->tenant_codigo,
|
||||
'event_id' => $this->event_id,
|
||||
'user_id' => $this->user_id,
|
||||
'created_at' => $this->created_at,
|
||||
'status' => $this->status,
|
||||
|
||||
@@ -26,6 +26,11 @@ class CheckoutService
|
||||
public function startCheckout(Tenant $tenant, int $userId, array $purchaseData): Purchase
|
||||
{
|
||||
return DB::transaction(function () use ($tenant, $userId, $purchaseData): Purchase {
|
||||
/** @var Tenant $tenant */
|
||||
$tenant = Tenant::query()
|
||||
->lockForUpdate()
|
||||
->findOrFail($tenant->getKey());
|
||||
|
||||
$directItem = $purchaseData['direct_item'] ?? null;
|
||||
$cartId = isset($purchaseData['cart_id']) ? (int) $purchaseData['cart_id'] : null;
|
||||
unset($purchaseData['direct_item'], $purchaseData['cart_id']);
|
||||
@@ -70,7 +75,6 @@ class CheckoutService
|
||||
|
||||
if (in_array($purchase->status, [
|
||||
Purchase::STATUS_PAID,
|
||||
Purchase::STATUS_IN_REVIEW,
|
||||
Purchase::STATUS_CANCELLED,
|
||||
Purchase::STATUS_REJECTED,
|
||||
Purchase::STATUS_EXPIRED,
|
||||
@@ -96,7 +100,6 @@ class CheckoutService
|
||||
->findOrFail($purchase->getKey());
|
||||
|
||||
if (in_array($purchase->status, [
|
||||
Purchase::STATUS_IN_REVIEW,
|
||||
Purchase::STATUS_PAID,
|
||||
], true)) {
|
||||
return $this->loadPurchase($purchase);
|
||||
@@ -112,7 +115,6 @@ class CheckoutService
|
||||
}
|
||||
|
||||
$purchase->update([
|
||||
'status' => Purchase::STATUS_IN_REVIEW,
|
||||
'expires_at' => null,
|
||||
]);
|
||||
|
||||
@@ -618,6 +620,7 @@ class CheckoutService
|
||||
...$purchaseData,
|
||||
'cart_id' => $cartId,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'event_id' => $tenant->active_event_id,
|
||||
'user_id' => $userId,
|
||||
'status' => Purchase::STATUS_CREATED,
|
||||
'payment_method' => null,
|
||||
|
||||
61
app/Domains/Sale/Controllers/AdminApp/SaleController.php
Normal file
61
app/Domains/Sale/Controllers/AdminApp/SaleController.php
Normal file
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Sale\Controllers\AdminApp;
|
||||
|
||||
use App\Domains\Sale\Requests\AdminAppSaleIndexRequest;
|
||||
use App\Domains\Sale\Resources\AdminApp\SaleModificationResource;
|
||||
use App\Domains\Sale\Resources\AdminApp\SaleResource;
|
||||
use App\Domains\Sale\Services\AdminAppSalePdfService;
|
||||
use App\Domains\Sale\Services\AdminAppSaleService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
||||
use Illuminate\Http\Response;
|
||||
|
||||
class SaleController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
protected AdminAppSaleService $saleService,
|
||||
protected AdminAppSalePdfService $salePdfService,
|
||||
) {}
|
||||
|
||||
public function index(AdminAppSaleIndexRequest $request): AnonymousResourceCollection
|
||||
{
|
||||
$tenant = $request->user()->tenant()->firstOrFail();
|
||||
|
||||
return SaleResource::collection(
|
||||
$this->saleService->sales($tenant, $request->validated())
|
||||
)->additional([
|
||||
'confirmed_sales_total' => $this->saleService->confirmedSalesTotal($tenant),
|
||||
]);
|
||||
}
|
||||
|
||||
public function modifications(Request $request): AnonymousResourceCollection
|
||||
{
|
||||
return SaleModificationResource::collection(
|
||||
$this->saleService->modifications(
|
||||
$request->user()->tenant()->firstOrFail()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public function downloadPdf(AdminAppSaleIndexRequest $request): Response
|
||||
{
|
||||
$tenant = $request->user()->tenant()->firstOrFail();
|
||||
|
||||
return $this->salePdfService->downloadSales(
|
||||
$tenant,
|
||||
$this->saleService->salesForExport($tenant, $request->validated()),
|
||||
);
|
||||
}
|
||||
|
||||
public function downloadModificationsPdf(Request $request): Response
|
||||
{
|
||||
$tenant = $request->user()->tenant()->firstOrFail();
|
||||
|
||||
return $this->salePdfService->downloadModifications(
|
||||
$tenant,
|
||||
$this->saleService->modificationsForExport($tenant),
|
||||
);
|
||||
}
|
||||
}
|
||||
30
app/Domains/Sale/Requests/AdminAppSaleIndexRequest.php
Normal file
30
app/Domains/Sale/Requests/AdminAppSaleIndexRequest.php
Normal file
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Sale\Requests;
|
||||
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class AdminAppSaleIndexRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, list<string>> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'q' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'id' => ['sometimes', 'nullable', 'integer', 'min:1'],
|
||||
'sale_date' => ['sometimes', 'nullable', 'date_format:Y-m-d'],
|
||||
'status' => ['sometimes', 'nullable', 'string', Rule::in(Purchase::statuses())],
|
||||
'sort_by' => ['sometimes', 'string', 'in:id,date,customer_name,quantity,status,total'],
|
||||
'sort_direction' => ['sometimes', 'string', 'in:asc,desc'],
|
||||
'page' => ['sometimes', 'integer', 'min:1'],
|
||||
'per_page' => ['sometimes', 'integer', 'min:1', 'max:100'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Sale\Resources\AdminApp;
|
||||
|
||||
use App\Domains\Logging\Models\ValueChange;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin ValueChange */
|
||||
class SaleModificationResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
/** @var Purchase|null $sale */
|
||||
$sale = $this->whenLoaded('trackable');
|
||||
$user = $this->whenLoaded('user');
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'sale_id' => $this->trackable_id,
|
||||
'attribute' => $this->attribute,
|
||||
'old_value' => $this->old_value,
|
||||
'new_value' => $this->new_value,
|
||||
'date' => $this->changed_at->format('Y-m-d'),
|
||||
'time' => $this->changed_at->format('H:i:s'),
|
||||
'actor_type' => $this->actor_type->value,
|
||||
'sale' => $sale instanceof Purchase ? [
|
||||
'id' => $sale->id,
|
||||
'customer_name' => $sale->nombre_apellido,
|
||||
'status' => $sale->status,
|
||||
] : null,
|
||||
'modified_by' => $user ? [
|
||||
'id' => $user->id,
|
||||
'name' => $user->nombre_apellido,
|
||||
'email' => $user->email,
|
||||
] : null,
|
||||
];
|
||||
}
|
||||
}
|
||||
28
app/Domains/Sale/Resources/AdminApp/SaleResource.php
Normal file
28
app/Domains/Sale/Resources/AdminApp/SaleResource.php
Normal file
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Sale\Resources\AdminApp;
|
||||
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin Purchase */
|
||||
class SaleResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$ticketsCount = (int) ($this->tickets_count ?? 0);
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'created_at' => $this->created_at,
|
||||
'customer_name' => $this->nombre_apellido,
|
||||
'quantity' => (int) ($this->quantity ?? 0),
|
||||
'status' => $this->status,
|
||||
'total' => number_format((float) $this->total, 2, '.', ''),
|
||||
'tickets_count' => $ticketsCount,
|
||||
'has_generated_tickets' => $ticketsCount > 0,
|
||||
];
|
||||
}
|
||||
}
|
||||
68
app/Domains/Sale/Services/AdminAppSalePdfService.php
Normal file
68
app/Domains/Sale/Services/AdminAppSalePdfService.php
Normal file
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Sale\Services;
|
||||
|
||||
use App\Domains\Logging\Models\ValueChange;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Barryvdh\DomPDF\Facade\Pdf;
|
||||
use Barryvdh\DomPDF\PDF as DomPdf;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class AdminAppSalePdfService
|
||||
{
|
||||
/** @param Collection<int, Purchase> $sales */
|
||||
public function downloadSales(Tenant $tenant, Collection $sales): Response
|
||||
{
|
||||
$pdf = Pdf::loadView('pdf.adminapp.sales', [
|
||||
'tenant' => $tenant,
|
||||
'sales' => $sales,
|
||||
'generatedAt' => now(),
|
||||
'confirmedSalesTotal' => number_format(
|
||||
(float) $sales->where('status', Purchase::STATUS_PAID)->sum('total'),
|
||||
2,
|
||||
'.',
|
||||
'',
|
||||
),
|
||||
])->setPaper('a4', 'landscape');
|
||||
|
||||
$this->addPageNumbers($pdf);
|
||||
|
||||
return $pdf->download(
|
||||
'ventas_'.$tenant->codigo.'_'.now()->format('Ymd_His').'.pdf'
|
||||
);
|
||||
}
|
||||
|
||||
/** @param Collection<int, ValueChange> $modifications */
|
||||
public function downloadModifications(Tenant $tenant, Collection $modifications): Response
|
||||
{
|
||||
$pdf = Pdf::loadView('pdf.adminapp.sale-modifications', [
|
||||
'tenant' => $tenant,
|
||||
'modifications' => $modifications,
|
||||
'generatedAt' => now(),
|
||||
])->setPaper('a4', 'landscape');
|
||||
|
||||
$this->addPageNumbers($pdf);
|
||||
|
||||
return $pdf->download(
|
||||
'historial_modificaciones_'.$tenant->codigo.'_'.now()->format('Ymd_His').'.pdf'
|
||||
);
|
||||
}
|
||||
|
||||
private function addPageNumbers(DomPdf $pdf): void
|
||||
{
|
||||
$pdf->render();
|
||||
$domPdf = $pdf->getDomPDF();
|
||||
$font = $domPdf->getFontMetrics()->getFont('DejaVu Sans');
|
||||
|
||||
$domPdf->getCanvas()->page_text(
|
||||
385,
|
||||
575,
|
||||
'Página {PAGE_NUM} de {PAGE_COUNT}',
|
||||
$font,
|
||||
7,
|
||||
[0.48, 0.52, 0.49],
|
||||
);
|
||||
}
|
||||
}
|
||||
120
app/Domains/Sale/Services/AdminAppSaleService.php
Normal file
120
app/Domains/Sale/Services/AdminAppSaleService.php
Normal file
@@ -0,0 +1,120 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Sale\Services;
|
||||
|
||||
use App\Domains\Logging\Models\ValueChange;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class AdminAppSaleService
|
||||
{
|
||||
public function confirmedSalesTotal(Tenant $tenant): string
|
||||
{
|
||||
$total = Purchase::query()
|
||||
->where('tenant_codigo', $tenant->codigo)
|
||||
->where('status', Purchase::STATUS_PAID)
|
||||
->sum('total');
|
||||
|
||||
return number_format((float) $total, 2, '.', '');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{
|
||||
* q?: string|null,
|
||||
* id?: int|null,
|
||||
* sale_date?: string|null,
|
||||
* status?: string|null,
|
||||
* sort_by?: string,
|
||||
* sort_direction?: string
|
||||
* } $filters
|
||||
* @return LengthAwarePaginator<Purchase>
|
||||
*/
|
||||
public function sales(Tenant $tenant, array $filters = []): LengthAwarePaginator
|
||||
{
|
||||
return $this->salesQuery($tenant, $filters)
|
||||
->paginateFromRequest()
|
||||
->withQueryString();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $filters
|
||||
* @return Collection<int, Purchase>
|
||||
*/
|
||||
public function salesForExport(Tenant $tenant, array $filters = []): Collection
|
||||
{
|
||||
return $this->salesQuery($tenant, $filters)->get();
|
||||
}
|
||||
|
||||
/** @return LengthAwarePaginator<ValueChange> */
|
||||
public function modifications(Tenant $tenant): LengthAwarePaginator
|
||||
{
|
||||
return $this->modificationsQuery($tenant)
|
||||
->paginateFromRequest()
|
||||
->withQueryString();
|
||||
}
|
||||
|
||||
/** @return Collection<int, ValueChange> */
|
||||
public function modificationsForExport(Tenant $tenant): Collection
|
||||
{
|
||||
return $this->modificationsQuery($tenant)->get();
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $filters */
|
||||
protected function salesQuery(Tenant $tenant, array $filters): Builder
|
||||
{
|
||||
$sortColumns = [
|
||||
'id' => 'id',
|
||||
'date' => 'created_at',
|
||||
'customer_name' => 'nombre_apellido',
|
||||
'quantity' => 'quantity',
|
||||
'status' => 'status',
|
||||
'total' => 'total',
|
||||
];
|
||||
$requestedSort = $filters['sort_by'] ?? 'date';
|
||||
$sortBy = array_key_exists($requestedSort, $sortColumns) ? $requestedSort : 'date';
|
||||
$requestedDirection = $filters['sort_direction'] ?? 'desc';
|
||||
$sortDirection = in_array($requestedDirection, ['asc', 'desc'], true)
|
||||
? $requestedDirection
|
||||
: 'desc';
|
||||
|
||||
return Purchase::query()
|
||||
->where('tenant_codigo', $tenant->codigo)
|
||||
->when($filters['q'] ?? null, function (Builder $query, string $search): void {
|
||||
$term = trim($search);
|
||||
|
||||
$query->where(function (Builder $query) use ($term): void {
|
||||
$query
|
||||
->where('id', 'like', "%{$term}%")
|
||||
->orWhere('nombre_apellido', 'like', "%{$term}%")
|
||||
->orWhere('created_at', 'like', "%{$term}%");
|
||||
});
|
||||
})
|
||||
->when($filters['id'] ?? null, fn (Builder $query, int $id): Builder => $query->whereKey($id))
|
||||
->when(
|
||||
$filters['sale_date'] ?? null,
|
||||
fn (Builder $query, string $date): Builder => $query->whereDate('created_at', $date)
|
||||
)
|
||||
->when(
|
||||
$filters['status'] ?? null,
|
||||
fn (Builder $query, string $status): Builder => $query->where('status', $status)
|
||||
)
|
||||
->withSum('items as quantity', 'cantidad')
|
||||
->withCount('tickets')
|
||||
->orderBy($sortColumns[$sortBy], $sortDirection)
|
||||
->when($sortBy !== 'id', fn (Builder $query): Builder => $query->orderByDesc('id'));
|
||||
}
|
||||
|
||||
/** @return Builder<ValueChange> */
|
||||
protected function modificationsQuery(Tenant $tenant): Builder
|
||||
{
|
||||
return ValueChange::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('trackable_type', (new Purchase)->getMorphClass())
|
||||
->with(['trackable', 'user'])
|
||||
->orderByDesc('changed_at')
|
||||
->orderByDesc('id');
|
||||
}
|
||||
}
|
||||
13
app/Domains/Sale/routes/adminapp.php
Normal file
13
app/Domains/Sale/routes/adminapp.php
Normal file
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Sale\Controllers\AdminApp\SaleController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('v1/adminapp/tenant')
|
||||
->middleware(['auth:sanctum', 'adminapp.tenant'])
|
||||
->group(function (): void {
|
||||
Route::get('sales', [SaleController::class, 'index']);
|
||||
Route::get('sales/pdf', [SaleController::class, 'downloadPdf']);
|
||||
Route::get('sales/modifications', [SaleController::class, 'modifications']);
|
||||
Route::get('sales/modifications/pdf', [SaleController::class, 'downloadModificationsPdf']);
|
||||
});
|
||||
3
app/Domains/Sale/routes/api.php
Normal file
3
app/Domains/Sale/routes/api.php
Normal file
@@ -0,0 +1,3 @@
|
||||
<?php
|
||||
|
||||
require __DIR__.'/adminapp.php';
|
||||
@@ -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',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
66
app/Domains/Tenant/Models/WebsiteExtra.php
Normal file
66
app/Domains/Tenant/Models/WebsiteExtra.php
Normal 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;
|
||||
}
|
||||
}
|
||||
67
app/Domains/Tenant/Models/WebsiteType.php
Normal file
67
app/Domains/Tenant/Models/WebsiteType.php
Normal 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');
|
||||
}
|
||||
}
|
||||
51
app/Domains/Tenant/Models/WebsiteTypeExtra.php
Normal file
51
app/Domains/Tenant/Models/WebsiteTypeExtra.php
Normal 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');
|
||||
}
|
||||
}
|
||||
@@ -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')
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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')));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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'],
|
||||
|
||||
@@ -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
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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>>
|
||||
|
||||
177
app/Domains/Tenant/Services/TenantInformationService.php
Normal file
177
app/Domains/Tenant/Services/TenantInformationService.php
Normal 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;
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
|
||||
367
app/Domains/Tenant/Services/WebsiteExtraService.php
Normal file
367
app/Domains/Tenant/Services/WebsiteExtraService.php
Normal 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;
|
||||
}
|
||||
}
|
||||
87
app/Domains/Tenant/Services/WebsiteTypeService.php
Normal file
87
app/Domains/Tenant/Services/WebsiteTypeService.php
Normal 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;
|
||||
});
|
||||
}
|
||||
}
|
||||
13
app/Domains/Tenant/routes/adminapp.php
Normal file
13
app/Domains/Tenant/routes/adminapp.php
Normal 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']);
|
||||
});
|
||||
@@ -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';
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
30
app/Http/Middleware/EnsureAdminAppTenant.php
Normal file
30
app/Http/Middleware/EnsureAdminAppTenant.php
Normal 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);
|
||||
}
|
||||
}
|
||||
@@ -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',
|
||||
]);
|
||||
|
||||
@@ -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');
|
||||
}
|
||||
};
|
||||
@@ -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']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -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');
|
||||
}
|
||||
};
|
||||
@@ -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']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -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');
|
||||
}
|
||||
};
|
||||
@@ -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(),
|
||||
]);
|
||||
}
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user