Files
compras/app/Services/BusinessClients.php
T
nala 47649bd46c
tests / ci (push) Canceled after 0s
commit compras1 3011
2026-11-30 09:33:36 +02:00

105 lines
5.2 KiB
PHP

<?php
namespace App\Services;
use App\Models\BusinessClient;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
/** Company-owned client identities; frozen process snapshots never follow later edits. */
final class BusinessClients
{
public function ready(): bool
{
return Schema::hasTable('business_clients');
}
public function canRead(User $actor): bool
{
return $actor->tenant_id !== null && $actor->hasFunctions(['admin', 'procurement', 'finance', ...PeopleHiring::PERMISSIONS]);
}
public function canManage(User $actor): bool
{
return $actor->tenant_id !== null && $actor->hasFunctions(['admin']) && ! app(OrganizationAccess::class)->maintenanceOnly($actor);
}
/** @return list<array<string,mixed>> */
public function choices(User $actor): array
{
if (! $this->ready() || ! $this->canRead($actor)) {
return [];
}
return array_values(BusinessClient::query()->where('tenant_id', $actor->tenant_id)->where('active', true)->orderBy('name')
->get(['id', 'client_key', 'code', 'name', 'tax_number', 'version'])
->map(fn (BusinessClient $client): array => $client->only(['id', 'client_key', 'code', 'name', 'tax_number', 'version']))->all());
}
/** @return array<string,mixed> */
public function snapshot(User $actor, int $id, int $version): array
{
abort_unless($this->ready() && $this->canRead($actor), 403);
$client = BusinessClient::query()->where('tenant_id', $actor->tenant_id)->whereKey($id)->lockForUpdate()->firstOrFail();
abort_unless($client->active && $client->version === $version, 409, 'O cliente mudou ou foi desactivado. Actualize a selecção antes de continuar.');
return $client->only(['id', 'client_key', 'code', 'name', 'tax_number', 'version']);
}
/** @param array<string,mixed> $input */
public function save(User $candidate, ?int $id, array $input): BusinessClient
{
abort_unless($this->ready(), 503);
return DB::transaction(function () use ($candidate, $id, $input): BusinessClient {
app(ConflictGuard::class)->lockCompany($candidate);
$actor = app(CurrentActor::class)->lock($candidate);
abort_unless($this->canManage($actor), 403);
$record = $id === null ? null : BusinessClient::query()->where('tenant_id', $actor->tenant_id)->lockForUpdate()->findOrFail($id);
$existing = $record === null && is_string($input['client_key'] ?? null) && Str::isUuid($input['client_key'])
? BusinessClient::query()->where('tenant_id', $actor->tenant_id)->where('client_key', $input['client_key'])->first() : null;
foreach (['code', 'name', 'tax_number', 'address', 'email', 'reason'] as $field) {
if (is_string($input[$field] ?? null)) {
$input[$field] = trim($input[$field]);
}
}
$data = Validator::make($input, [
'client_key' => $record === null ? 'required|uuid' : 'prohibited',
'version' => $record === null ? 'prohibited' : 'required|integer|min:1',
'code' => ['required', 'string', 'max:40', ...($existing === null ? [Rule::unique('business_clients')->where('tenant_id', $actor->tenant_id)->ignore($record?->id)] : [])],
'name' => 'required|string|min:2|max:180', 'tax_number' => 'nullable|string|max:40',
'address' => 'nullable|string|max:2000', 'email' => 'nullable|email|max:254',
'active' => 'required|boolean', 'reason' => 'required|string|min:10|max:4000',
])->validate();
$fields = array_intersect_key($data, array_flip(['code', 'name', 'tax_number', 'address', 'email', 'active']));
$fields += ['tax_number' => null, 'address' => null, 'email' => null];
$fields['active'] = (bool) $fields['active'];
$hash = hash('sha256', json_encode($fields, JSON_THROW_ON_ERROR));
if ($record === null) {
if ($existing !== null) {
abort_unless($existing->created_by === $actor->id && hash_equals($existing->creation_hash, $hash), 409);
return $existing;
}
} else {
abort_unless($record->version === (int) $data['version'], 409, 'O cliente foi alterado. Actualize antes de guardar.');
}
$before = $record?->attributesToArray();
if ($record === null) {
$record = BusinessClient::query()->create([...$fields, 'tenant_id' => $actor->tenant_id, 'client_key' => $data['client_key'],
'created_by' => $actor->id, 'creation_hash' => $hash, 'version' => 1]);
} else {
$record->fill([...$fields, 'version' => $record->version + 1])->save();
}
app(RequisitionWorkflow::class)->audit($actor, 'business.client_saved', null, $before,
['client' => $record->attributesToArray(), 'reason' => $data['reason']]);
return $record;
});
}
}