refactor(backend): reorganize domains into Core, Commerce, Ticketing and Shared
This commit is contained in:
@@ -1,69 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Staff\Controllers;
|
||||
|
||||
use App\Domains\Staff\Requests\StoreStaffRequest;
|
||||
use App\Domains\Staff\Requests\UpdateStaffRequest;
|
||||
use App\Domains\Staff\Resources\StaffResource;
|
||||
use App\Domains\Staff\Services\StaffService;
|
||||
use App\Domains\Ticket\Requests\ScanAttemptIndexRequest;
|
||||
use App\Domains\Ticket\Resources\Scanner\ScanAttemptResource;
|
||||
use App\Domains\Ticket\Services\ScannerTicketService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class AdminAppStaffController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly StaffService $staffService,
|
||||
private readonly ScannerTicketService $scannerTicketService,
|
||||
) {}
|
||||
|
||||
public function index(Request $request): AnonymousResourceCollection
|
||||
{
|
||||
return StaffResource::collection($this->staffService->list(
|
||||
$request->user()->tenant()->firstOrFail(),
|
||||
$request->string('search')->trim()->toString() ?: null,
|
||||
));
|
||||
}
|
||||
|
||||
public function store(StoreStaffRequest $request): StaffResource
|
||||
{
|
||||
return StaffResource::make($this->staffService->create(
|
||||
$request->user()->tenant()->firstOrFail(),
|
||||
$request->validated(),
|
||||
));
|
||||
}
|
||||
|
||||
public function update(UpdateStaffRequest $request, int $staff): StaffResource
|
||||
{
|
||||
return StaffResource::make($this->staffService->update(
|
||||
$request->user()->tenant()->firstOrFail(),
|
||||
$staff,
|
||||
$request->validated(),
|
||||
));
|
||||
}
|
||||
|
||||
public function destroy(Request $request, int $staff): Response
|
||||
{
|
||||
$this->staffService->delete($request->user()->tenant()->firstOrFail(), $staff);
|
||||
|
||||
return response()->noContent();
|
||||
}
|
||||
|
||||
public function scanAttempts(
|
||||
ScanAttemptIndexRequest $request,
|
||||
int $staff,
|
||||
): AnonymousResourceCollection {
|
||||
$scanner = $this->staffService->find(
|
||||
$request->user()->tenant()->firstOrFail(),
|
||||
$staff,
|
||||
);
|
||||
|
||||
return ScanAttemptResource::collection(
|
||||
$this->scannerTicketService->attemptsByStaff($scanner, $request->validated())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Staff\Requests;
|
||||
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class StoreStaffRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
if (is_string($this->input('email'))) {
|
||||
$this->merge(['email' => mb_strtolower(trim($this->input('email')))]);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
$categoryRules = $this->user()->tenant()->firstOrFail()
|
||||
->requiresScannerCategoryValidation()
|
||||
? ['required', 'array', 'min:1']
|
||||
: ['sometimes', 'array'];
|
||||
|
||||
return [
|
||||
'nombre_apellido' => ['required', 'string', 'max:255'],
|
||||
'dni' => ['required', 'string', 'max:50'],
|
||||
'email' => [
|
||||
'required',
|
||||
'email',
|
||||
'max:255',
|
||||
Rule::unique('users', 'active_email')->where('rol_codigo', RoleCode::Scanner->value)->whereNull('deleted_at'),
|
||||
],
|
||||
'category_ids' => $categoryRules,
|
||||
'category_ids.*' => ['integer', 'distinct', Rule::exists('categorias', 'id')],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Staff\Requests;
|
||||
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class UpdateStaffRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
if (is_string($this->input('email'))) {
|
||||
$this->merge(['email' => mb_strtolower(trim($this->input('email')))]);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
$staffId = (int) $this->route('staff');
|
||||
$categoryRules = $this->user()->tenant()->firstOrFail()
|
||||
->requiresScannerCategoryValidation()
|
||||
? ['required', 'array', 'min:1']
|
||||
: ['sometimes', 'array'];
|
||||
|
||||
return [
|
||||
'nombre_apellido' => ['required', 'string', 'max:255'],
|
||||
'dni' => ['required', 'string', 'max:50'],
|
||||
'email' => [
|
||||
'required',
|
||||
'email',
|
||||
'max:255',
|
||||
Rule::unique('users', 'active_email')->where('rol_codigo', RoleCode::Scanner->value)
|
||||
->whereNull('deleted_at')
|
||||
->ignore($staffId),
|
||||
],
|
||||
'category_ids' => $categoryRules,
|
||||
'category_ids.*' => ['integer', 'distinct', Rule::exists('categorias', 'id')],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Staff\Resources;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin User */
|
||||
class StaffResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'nombre_apellido' => $this->nombre_apellido,
|
||||
'dni' => $this->dni,
|
||||
'email' => $this->email,
|
||||
'rol_codigo' => $this->rol_codigo,
|
||||
'role' => $this->whenLoaded('role', fn () => [
|
||||
'codigo' => $this->role?->codigo,
|
||||
'nombre' => $this->role?->nombre,
|
||||
]),
|
||||
'categories' => $this->whenLoaded('scanCategories', fn () => $this->scanCategories
|
||||
->map(fn ($category) => [
|
||||
'id' => $category->id,
|
||||
'nombre' => $category->nombre,
|
||||
])->values()),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Staff\Services;
|
||||
|
||||
use App\Domains\Auth\Models\ResetPasswordAttempt;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Auth\Services\ResetPasswordAttemptService;
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class StaffService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ResetPasswordAttemptService $resetPasswordAttemptService,
|
||||
) {}
|
||||
|
||||
/** @return Collection<int, User> */
|
||||
public function list(Tenant $tenant, ?string $search = null): Collection
|
||||
{
|
||||
return $this->staffQuery($tenant)
|
||||
->with(['role', 'scanCategories' => fn ($query) => $query->orderBy('nombre')])
|
||||
->when($search, function (Builder $query, string $search): void {
|
||||
$query->where(function (Builder $query) use ($search): void {
|
||||
$query->where('nombre_apellido', 'like', "%{$search}%")
|
||||
->orWhere('dni', 'like', "%{$search}%")
|
||||
->orWhere('email', 'like', "%{$search}%");
|
||||
});
|
||||
})
|
||||
->orderBy('nombre_apellido')
|
||||
->get();
|
||||
}
|
||||
|
||||
/** @return Collection<int, Category> */
|
||||
private function assignableCategories(Tenant $tenant): Collection
|
||||
{
|
||||
return Category::query()
|
||||
->whereNull('categoria_id')
|
||||
->where(function (Builder $query) use ($tenant): void {
|
||||
$query->where('tenant_code', $tenant->codigo)
|
||||
->orWhereHas('catalogItems', fn (Builder $items) => $items
|
||||
->where('tenant_code', $tenant->codigo));
|
||||
})
|
||||
->orderBy('nombre')
|
||||
->get();
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $data */
|
||||
public function create(Tenant $tenant, array $data): User
|
||||
{
|
||||
$categoryIds = $this->categoryIdsFor($tenant, $data);
|
||||
$this->assertCategoriesBelongToTenant($tenant, $categoryIds);
|
||||
|
||||
return DB::transaction(function () use ($tenant, $data, $categoryIds): User {
|
||||
$staff = User::query()->create([
|
||||
...Arr::only($data, ['nombre_apellido', 'dni', 'email']),
|
||||
'email' => mb_strtolower(trim((string) $data['email'])),
|
||||
'password' => Str::random(64),
|
||||
'rol_codigo' => RoleCode::Scanner->value,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
]);
|
||||
$staff->scanCategories()->sync($categoryIds);
|
||||
$this->resetPasswordAttemptService->createForScannerEmail(
|
||||
$staff->email,
|
||||
ResetPasswordAttempt::REASON_STAFF_CREATED,
|
||||
);
|
||||
|
||||
return $staff->load('role', 'scanCategories');
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $data */
|
||||
public function update(Tenant $tenant, int $staffId, array $data): User
|
||||
{
|
||||
$staff = $this->find($tenant, $staffId);
|
||||
$categoryIds = $this->categoryIdsFor($tenant, $data);
|
||||
$this->assertCategoriesBelongToTenant($tenant, $categoryIds);
|
||||
|
||||
return DB::transaction(function () use ($staff, $data, $categoryIds): User {
|
||||
$attributes = Arr::only($data, ['nombre_apellido', 'dni', 'email']);
|
||||
$attributes['email'] = mb_strtolower(trim((string) $data['email']));
|
||||
$staff->update($attributes);
|
||||
$staff->scanCategories()->sync($categoryIds);
|
||||
|
||||
return $staff->load('role', 'scanCategories');
|
||||
});
|
||||
}
|
||||
|
||||
public function delete(Tenant $tenant, int $staffId): void
|
||||
{
|
||||
$staff = $this->find($tenant, $staffId);
|
||||
|
||||
DB::transaction(function () use ($staff): void {
|
||||
$staff->tokens()->delete();
|
||||
$staff->delete();
|
||||
});
|
||||
}
|
||||
|
||||
public function find(Tenant $tenant, int $staffId): User
|
||||
{
|
||||
return $this->staffQuery($tenant)->findOrFail($staffId);
|
||||
}
|
||||
|
||||
private function staffQuery(Tenant $tenant): Builder
|
||||
{
|
||||
return User::query()
|
||||
->where('tenant_codigo', $tenant->codigo)
|
||||
->where('rol_codigo', RoleCode::Scanner->value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<int, int>
|
||||
*/
|
||||
private function categoryIdsFor(Tenant $tenant, array $data): array
|
||||
{
|
||||
if (! $tenant->requiresScannerCategoryValidation()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $data['category_ids'];
|
||||
}
|
||||
|
||||
/** @param array<int, int> $categoryIds */
|
||||
private function assertCategoriesBelongToTenant(Tenant $tenant, array $categoryIds): void
|
||||
{
|
||||
$validIds = $this->assignableCategories($tenant)
|
||||
->whereIn('id', $categoryIds)
|
||||
->pluck('id');
|
||||
|
||||
if ($validIds->count() !== count($categoryIds)) {
|
||||
throw ValidationException::withMessages([
|
||||
'category_ids' => 'Una o más categorías no pertenecen al tenant.',
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
# Dominio Staff
|
||||
|
||||
## Propósito
|
||||
|
||||
Administra usuarios de personal de un tenant y las categorías que tienen habilitadas para operar o escanear.
|
||||
|
||||
## Componentes
|
||||
|
||||
- `AdminAppStaffController`: listado, alta, modificación y baja.
|
||||
- `StaffService`: aplica el alcance por tenant, busca personal y sincroniza sus datos/asignaciones.
|
||||
- `StoreStaffRequest` y `UpdateStaffRequest`: validan cada operación.
|
||||
- `StaffResource`: representación de salida para AdminApp.
|
||||
|
||||
## Endpoints
|
||||
|
||||
Recurso REST `/v1/adminapp/tenant/staff`, excepto detalle individual, protegido por `auth:sanctum` y `adminapp.tenant`.
|
||||
|
||||
## Dependencias y reglas
|
||||
|
||||
Usa `Auth/User` como entidad de personal, `Authorization` para su rol, `Catalog/Category` para asignaciones y `Tenant` para aislamiento. Toda búsqueda, edición o borrado debe comprobar que el usuario pertenece al tenant autenticado.
|
||||
@@ -1,11 +0,0 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Staff\Controllers\AdminAppStaffController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('v1/adminapp/tenant')
|
||||
->middleware(['auth:sanctum', 'adminapp.tenant'])
|
||||
->group(function (): void {
|
||||
Route::get('staff/{staff}/scan-attempts', [AdminAppStaffController::class, 'scanAttempts']);
|
||||
Route::apiResource('staff', AdminAppStaffController::class)->except('show');
|
||||
});
|
||||
Reference in New Issue
Block a user