| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- <?php
- namespace App\Http\Controllers;
- use App\Http\Controllers\Concerns\ResolvesActiveUnit;
- use App\Services\KanbanService;
- use App\Http\Requests\KanbanRequest;
- use App\Http\Resources\KanbanResource;
- use App\Models\Unit;
- use Illuminate\Http\JsonResponse;
- class KanbanController extends Controller
- {
- use ResolvesActiveUnit;
- public function __construct(
- protected KanbanService $service,
- ) {}
- public function index(): JsonResponse
- {
- $user = auth()->user();
- if ($this->isMatriz($user)) {
- $items = $this->service->getAll();
- } else {
- $items = $this->service->getAllForUnit($this->activeUnitId($user));
- }
- return $this->successResponse(payload: KanbanResource::collection($items));
- }
- public function store(KanbanRequest $request): JsonResponse
- {
- $data = $request->validated();
- $user = auth()->user();
- $isMatriz = $this->isMatriz($user);
- $data['origin'] = $isMatriz ? 'matriz' : 'unit';
- $data['created_by_user_id'] = $user->id;
- $data['unit_id'] = $isMatriz ? null : $this->activeUnitId($user);
- // Broadcast to all units
- if ($isMatriz && ($data['scope'] ?? null) === 'all') {
- $unitIds = Unit::query()->pluck('id');
- $created = [];
- foreach ($unitIds as $unitId) {
- $created[] = $this->service->create(array_merge($data, [
- 'target_unit_id' => $unitId,
- ]));
- }
- return $this->successResponse(
- payload: KanbanResource::collection($created),
- message: __('messages.created'),
- code: 201
- );
- }
- if ($isMatriz) {
- if (($data['scope'] ?? null) === 'internal') {
- $data['target_unit_id'] = null;
- }
- // scope='specific' → target_unit_id already set from request
- } else {
- // Franchisee: internal = own unit, specific = Matriz (null target)
- $data['target_unit_id'] = (($data['scope'] ?? null) === 'internal')
- ? $this->activeUnitId($user)
- : null;
- }
- $item = $this->service->create($data);
- return $this->successResponse(
- payload: new KanbanResource($item),
- message: __('messages.created'),
- code: 201
- );
- }
- public function show(int $id): JsonResponse
- {
- $item = $this->service->findById($id);
- return $this->successResponse(payload: new KanbanResource($item));
- }
- public function update(KanbanRequest $request, int $id): JsonResponse
- {
- $item = $this->service->update($id, $request->validated());
- return $this->successResponse(payload: new KanbanResource($item), message: __('messages.updated'));
- }
- public function destroy(int $id): JsonResponse
- {
- $this->service->delete($id);
- return $this->successResponse(message: __('messages.deleted'), code: 204);
- }
- private function isMatriz(\App\Models\User $user): bool
- {
- return $user->user_type === 'ADMIN';
- }
- }
|