belongsToOrg($user, $organisation); } public function view(User $user, FormTemplate $template): bool { return $this->belongsToOrg($user, $template->organisation); } public function create(User $user, Organisation $organisation): bool { return $this->canManage($user, $organisation); } public function update(User $user, FormTemplate $template): bool { if ($template->is_system && ! $user->hasRole('super_admin')) { return false; } return $this->canManage($user, $template->organisation); } public function deactivate(User $user, FormTemplate $template): bool { return $this->canManage($user, $template->organisation); } public function applyToSchema(User $user, FormTemplate $template, FormSchema $schema): bool { if ($template->organisation_id !== $schema->organisation_id) { return false; } return app(FormSchemaPolicy::class)->update($user, $schema); } private function belongsToOrg(User $user, ?Organisation $organisation): bool { if ($user->hasRole('super_admin')) { return true; } if ($organisation === null) { return false; } return $organisation->users()->where('user_id', $user->id)->exists(); } private function canManage(User $user, ?Organisation $organisation): bool { if ($user->hasRole('super_admin')) { return true; } if ($organisation === null) { return false; } return $organisation->users() ->where('user_id', $user->id) ->wherePivot('role', 'org_admin') ->exists(); } }