commit compras1 3011
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-30 09:33:36 +02:00
parent 96b30368bc
commit 47649bd46c
163 changed files with 9419 additions and 145 deletions
+1 -1
View File
@@ -57,7 +57,7 @@ class SgcDeliveryCheck extends Command
$clean = false;
}
foreach ($enabled as $key) {
if (! (WorkContext::OPTIONS[$key]['operational'] ?? false)) {
if (! WorkContext::operational($key)) {
$this->error('Percurso operacional ainda pendente: '.$key);
$clean = false;
}
@@ -0,0 +1,45 @@
<?php
namespace App\Http\Controllers;
use App\Models\BusinessClient;
use App\Services\BusinessClients;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Symfony\Component\HttpFoundation\Response;
final class BusinessClientController extends Controller
{
public function index(Request $request, BusinessClients $clients): Response
{
$actor = $this->staffIdentity($request);
abort_unless($clients->ready(), 503);
abort_unless($clients->canRead($actor), 403);
$filters = $request->validate(['search' => 'nullable|string|max:180', 'page' => 'nullable|integer|min:1']);
$query = BusinessClient::query()->where('tenant_id', $actor->tenant_id)
->select(['id', 'client_key', 'code', 'name', 'tax_number', 'address', 'email', 'active', 'version']);
if (trim($filters['search'] ?? '') !== '') {
$query->where(fn ($q) => $q->where('name', 'like', '%'.$filters['search'].'%')->orWhere('code', 'like', '%'.$filters['search'].'%'));
}
Inertia::encryptHistory();
$response = Inertia::render('company/clients', ['clients' => $query->orderBy('name')->paginate(20)->withQueryString(),
'filters' => $filters, 'canManage' => $clients->canManage($actor)])->toResponse($request);
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
return $response;
}
public function store(Request $request, BusinessClients $clients): Response
{
$clients->save($this->staffIdentity($request), null, $request->all());
return redirect('/empresa/clientes')->with('success', 'Cliente registado.');
}
public function update(Request $request, int $client, BusinessClients $clients): Response
{
$clients->save($this->staffIdentity($request), $client, $request->all());
return redirect('/empresa/clientes')->with('success', 'Cliente actualizado; os processos anteriores conservam a sua identificação original.');
}
}
@@ -7,10 +7,12 @@ use App\Models\PeopleProcess;
use App\Models\Tenant;
use App\Models\User;
use App\Services\AiPreparationPlan;
use App\Services\BusinessClients;
use App\Services\CandidateTriage;
use App\Services\IntelligencePolicy;
use App\Services\PeopleAccess;
use App\Services\PeopleClarifications;
use App\Services\PeopleContractFormalization;
use App\Services\PeopleEvidenceBrief;
use App\Services\PeopleForms;
use App\Services\PeopleHiring;
@@ -18,10 +20,12 @@ use App\Services\PeopleOperationalInsights;
use App\Services\PeopleProcessProjection;
use App\Services\PeopleRegistry;
use App\Services\PeopleWorkdesk;
use App\Services\WorkContext;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;
use Inertia\Inertia;
use Symfony\Component\HttpFoundation\Response;
@@ -37,6 +41,7 @@ class PeopleHiringController extends Controller
$kinds = $workflow->kinds($this->actor($request));
abort_unless($kinds !== [], 403);
$availableKinds = $kinds;
$clientMode = app(WorkContext::class)->active($request) === 'people.third_party';
$filter = $request->validate(['kind' => 'nullable|in:service,staff', 'search' => 'nullable|string|max:100', 'status' => ['nullable', Rule::in(PeopleWorkdesk::STATES)],
'from' => 'nullable|date_format:Y-m-d', 'to' => ['nullable', 'date_format:Y-m-d', Rule::when($request->filled('from'), 'after_or_equal:from')]]);
if (isset($filter['kind'])) {
@@ -47,8 +52,11 @@ class PeopleHiringController extends Controller
$query = app(PeopleAccess::class)->visible(PeopleProcess::query()->whereIn('kind', $kinds), $this->actor($request));
if (($filter['search'] ?? '') !== '') {
$search = $filter['search'];
$query->where(function ($q) use ($search) {
$query->where(function ($q) use ($search, $clientMode) {
$q->whereLike('title', '%'.$search.'%');
if ($clientMode) {
$q->orWhere('rules->client->name', 'like', '%'.$search.'%')->orWhere('rules->client->code', 'like', '%'.$search.'%');
}
if (preg_match('/^(?:PES-)?([1-9][0-9]*)$/D', $search, $matches)) {
$reference = filter_var($matches[1], FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
if ($reference !== false) {
@@ -67,14 +75,18 @@ class PeopleHiringController extends Controller
$query->whereDate('created_at', '<=', $filter['to']);
}
$workdesk = $ready ? app(PeopleWorkdesk::class)->build(clone $query, $this->actor($request)) : null;
$processes = $ready ? (clone $query)->select(['id', 'title', 'kind', 'status', 'closes_on', 'created_at', 'rules'])->latest('id')->paginate(15)->withQueryString()
->through(fn (PeopleProcess $process) => [...$process->only(['id', 'title', 'kind', 'status', 'closes_on', 'created_at']),
...($clientMode ? ['client' => array_intersect_key($process->rules['client'] ?? [], array_flip(['id', 'code', 'name', 'version']))] : [])]) : null;
Inertia::encryptHistory();
$response = Inertia::render('people/index', ['ready' => $ready, 'kinds' => $kinds, 'availableKinds' => $availableKinds,
'filters' => $filter, 'workdesk' => $workdesk, 'insights' => $workdesk === null ? null : app(PeopleOperationalInsights::class)->build($workdesk),
'clientMode' => $clientMode, 'clients' => $clientMode ? app(BusinessClients::class)->choices($this->actor($request)) : [],
'company' => Tenant::query()->findOrFail($this->actor($request)->tenant_id)->only(['name']),
'canPrepare' => array_values(array_filter($availableKinds, fn ($kind) => $workflow->allowed($this->actor($request), $kind, 'prepare'))),
'formFields' => ['staff' => PeopleForms::STAFF, 'service' => PeopleForms::SERVICE],
'administration' => $ready && $this->actor($request)->hasFunctions(['admin']) ? PeopleProcess::query()->whereIn('kind', $kinds)->orderByDesc('id')->get(['id', 'kind', 'status']) : [],
'processes' => $ready ? (clone $query)->select(['id', 'title', 'kind', 'status', 'closes_on', 'created_at'])->latest('id')->paginate(15)->withQueryString() : null])->toResponse($request);
'processes' => $processes])->toResponse($request);
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
return $response;
@@ -107,8 +119,9 @@ class PeopleHiringController extends Controller
'canPrepare' => $workflow->allowed($this->actor($request), $record->kind, 'prepare') && $access->can($this->actor($request), $record, 'prepare'),
'canViewElectronicSources' => app(CandidateTriage::class)->canRead($this->actor($request), $record),
'canReview' => $workflow->allowed($this->actor($request), $record->kind, 'review') && $access->can($this->actor($request), $record, 'review') && $this->actor($request)->id !== $record->created_by,
'canApprove' => $workflow->allowed($this->actor($request), $record->kind, 'review') && $access->can($this->actor($request), $record, 'approve') && ! in_array($this->actor($request)->id, $workflow->decisionContributors($record), true),
'canApprove' => $workflow->canConfirm($this->actor($request), $record) && ! in_array($this->actor($request)->id, $workflow->decisionContributors($record), true),
'canContract' => $workflow->allowed($this->actor($request), $record->kind, 'prepare') && $access->can($this->actor($request), $record, 'contract'),
'canFormalize' => app(PeopleContractFormalization::class)->can($this->actor($request), $record),
'canManage' => $access->manages($this->actor($request), $record),
'history' => AuditLog::query()->where('action', 'like', 'people.%')->where('after->id', $record->id)->orderBy('id')->get(['id', 'action', 'user_id', 'created_at'])])->toResponse($request);
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
@@ -126,8 +139,8 @@ class PeopleHiringController extends Controller
$record = PeopleProcess::query()->findOrFail($process);
$data = $projection->read($this->actor($request), $record);
return response()->json(['schema' => 'sgc.people.process-dossier.v1', 'exported_at' => now()->toIso8601String(),
'effect' => 'preparation_only',
return response()->json(['schema' => $record->status === 'contract_formalized' ? 'sgc.people.process-dossier.v2' : 'sgc.people.process-dossier.v1', 'exported_at' => now()->toIso8601String(),
'effect' => $record->status === 'contract_formalized' ? 'signed_contract_record_only' : 'preparation_only',
'process' => Arr::only($data['process'], ['id', 'kind', 'title', 'purpose', 'closes_on', 'status', 'version', 'selected_application_id', 'rules', 'selection', 'contract']),
'candidates' => $data['candidates']])
->header('Content-Disposition', 'attachment; filename="PES-'.$record->id.'-dossier-v'.$record->version.'.json"')
@@ -167,6 +180,26 @@ class PeopleHiringController extends Controller
return redirect('/pessoas/'.$record->id);
}
public function formalize(Request $request, int $process, PeopleContractFormalization $service): Response
{
$record = $service->confirm($this->actor($request), $process, $request->all());
return redirect('/pessoas/'.$record->id);
}
public function signedContract(Request $request, int $process): Response
{
$record = PeopleProcess::query()->findOrFail($process);
$data = app(PeopleProcessProjection::class)->read($this->actor($request), $record);
abort_unless(isset($data['process']['contract']['signed_document']) && $record->status === 'contract_formalized', 404);
$document = $record->contract['signed_document'];
$disk = Storage::disk('people_contracts');
abort_unless($disk->exists($document['path']) && hash_equals($document['sha256'], hash('sha256', $disk->get($document['path']))), 409);
return $disk->download($document['path'], 'contrato-assinado-'.$record->id.'.pdf', [
'Cache-Control' => 'private, no-store', 'X-Content-Type-Options' => 'nosniff']);
}
public function store(Request $request, PeopleHiring $workflow): Response
{
abort_unless(Schema::hasTable('people_processes'), 503);
@@ -10,6 +10,7 @@ use App\Services\PeopleDeadlineReport;
use App\Services\PeopleHiring;
use App\Services\PeopleSelectionReport;
use App\Services\PeopleWorkdesk;
use App\Services\WorkContext;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
@@ -38,6 +39,7 @@ class PeopleReportController extends Controller
'to' => ['nullable', 'date_format:Y-m-d', Rule::when($request->filled('from'), 'after_or_equal:from')],
]);
$query = app(PeopleAccess::class)->visible(PeopleProcess::query()->whereIn('kind', $kinds), $actor);
$clientMode = app(WorkContext::class)->active($request) === 'people.third_party';
foreach (['kind', 'status'] as $field) {
if (! empty($filters[$field])) {
$query->where($field, $filters[$field]);
@@ -45,8 +47,11 @@ class PeopleReportController extends Controller
}
if (! empty($filters['search'])) {
$search = $filters['search'];
$query->where(function ($q) use ($search) {
$query->where(function ($q) use ($search, $clientMode) {
$q->whereLike('title', '%'.$search.'%');
if ($clientMode) {
$q->orWhere('rules->client->name', 'like', '%'.$search.'%')->orWhere('rules->client->code', 'like', '%'.$search.'%');
}
if (preg_match('/^(?:PES-)?([1-9][0-9]*)$/D', $search, $matches)) {
$id = filter_var($matches[1], FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
if ($id !== false) {
@@ -61,7 +66,9 @@ class PeopleReportController extends Controller
if (! empty($filters['to'])) {
$query->whereDate('created_at', '<=', $filters['to']);
}
$columns = ['id', 'title', 'kind', 'status', 'closes_on', 'created_at'];
$baseColumns = ['id', 'title', 'kind', 'status', 'closes_on', 'created_at'];
$columns = [...$baseColumns, ...($clientMode ? ['rules'] : [])];
$displayTitle = static fn (PeopleProcess $process): string => $process->title.($clientMode && isset($process->rules['client']['name']) ? ' · Cliente: '.$process->rules['client']['name'] : '');
$page = $request->routeIs('people.reports.csv') ? null : (clone $query)->latest('id')->paginate(25, $columns)->withQueryString();
$applications = ($filters['view'] ?? 'processes') === 'applications';
$selections = ($filters['view'] ?? 'processes') === 'selections';
@@ -89,7 +96,7 @@ class PeopleReportController extends Controller
} elseif ($request->routeIs('people.reports.csv')) {
// Materialise within the read-only snapshot; streaming runs after the transaction.
$rows = (clone $query)->orderBy('id')->get($columns);
$response = response()->streamDownload(function () use ($rows, $applications, $selections, $metrics) {
$response = response()->streamDownload(function () use ($rows, $applications, $selections, $metrics, $displayTitle) {
$file = fopen('php://output', 'w');
if ($file === false) {
throw new \RuntimeException('Não foi possível abrir a exportação.');
@@ -99,7 +106,8 @@ class PeopleReportController extends Controller
$selectionColumns = ['Situação da selecção', 'Proposta em', 'Decisão em', 'Pendência', 'Acesso à minuta', 'Referência da minuta', 'Minuta preparada em', 'Início previsto na minuta'];
fputcsv($file, ['Referência', 'Título', 'Percurso', 'Estado', 'Fecho de candidaturas', 'Criado em', ...($applications ? $extra : ($selections ? $selectionColumns : []))], ';', '"', '');
foreach ($rows as $row) {
$title = preg_match('/^[\s]*[=+@-]/u', $row->title) ? "'".$row->title : $row->title;
$title = $displayTitle($row);
$title = preg_match('/^[\s]*[=+@-]/u', $title) ? "'".$title : $title;
$counts = $metrics[$row->id] ?? [];
$values = $applications ? array_values(array_map(fn ($value) => $value === null ? 'Sem acesso' : ($value === 'selection_snapshot' ? 'Selecção preservada' : ($value === 'current_eligibility' ? 'Elegibilidade actual' : $value)), $counts)) : [];
if ($selections) {
@@ -111,6 +119,7 @@ class PeopleReportController extends Controller
}, 'relatorio-pessoas.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
} else {
$summary = (clone $query)->selectRaw('kind, status, count(*) as total')->groupBy('kind', 'status')->get();
$page?->through(fn (PeopleProcess $process) => [...$process->only($baseColumns), 'title' => $displayTitle($process)]);
Inertia::encryptHistory();
$response = Inertia::render('people/reports', [
'filters' => $filters, 'kinds' => $kinds, 'summary' => $summary,
@@ -151,6 +160,6 @@ class PeopleReportController extends Controller
private static function states(): array
{
return ['draft' => 'Abertura por conferir', 'open' => 'Recepção de candidaturas', 'assessment' => 'Avaliação',
'selection_review' => 'Selecção por conferir', 'selected' => 'Selecção aprovada', 'contract_draft' => 'Minuta contratual preparada'];
'selection_review' => 'Selecção por conferir', 'selected' => 'Selecção aprovada', 'contract_draft' => 'Minuta contratual preparada', 'contract_formalized' => 'Contrato formalizado'];
}
}
@@ -16,7 +16,9 @@ final class PrivateAuditController extends Controller
{
$scope = $access->current($this->staffIdentity($request));
$request->validate(['page' => 'nullable|integer|min:1|max:1000000']);
$exports = PrivateAuditExport::query()->where('created_by', $scope['actor']->id)->where('work_context', $scope['context'])->latest('id')->paginate(20)
$legacyIds = $access->legacyExportIds($scope['actor'], $scope['context']);
$exports = PrivateAuditExport::query()->where('created_by', $scope['actor']->id)
->where(fn ($query) => $query->where('work_context', $scope['context'])->orWhereIn('id', $legacyIds))->latest('id')->paginate(20)
->through(fn (PrivateAuditExport $export) => ['id' => $export->id, 'families' => $export->families,
'created_at' => $export->created_at, 'size' => $export->size, 'sha256' => $export->sha256,
'download_url' => '/auditoria/privada/'.$export->id.'/download']);
+3 -2
View File
@@ -17,10 +17,11 @@ class EnsureWorkContext
if ($user instanceof User && $contexts->enforced($user) && ($area = WorkContext::area($request->path())) !== null) {
$key = $contexts->active($request);
abort_unless($key !== null && WorkContext::OPTIONS[$key]['area'] === $area, 403, 'Seleccione uma área e opção autorizadas no Painel Inicial.');
if (! WorkContext::OPTIONS[$key]['operational'] && $request->isMethod('GET')) {
if (! WorkContext::operational($key) && $request->isMethod('GET')) {
return redirect('/dashboard');
}
abort_unless(WorkContext::OPTIONS[$key]['operational'], 409, 'O percurso operacional desta opção ainda está em implementação.');
abort_unless(WorkContext::operational($key), 409, 'O percurso operacional desta opção ainda está em implementação.');
abort_unless(WorkContext::allowsPath($key, $request->path()), 403, 'Seleccione o contexto de origem desta operação.');
}
return $next($request);
@@ -19,7 +19,7 @@ class PublicDevelopmentNavigation
}
$path = '/'.$request->path();
if ($request->path() === '/') {
return redirect('/dashboard');
return $next($request);
}
if (! isset(PublicNavigation::PAGES[$path])) {
return $next($request);
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
/** @property int $id
* @property int $tenant_id
* @property int $version
* @property bool $active
* @property string $client_key
* @property string $code
* @property string $name
* @property string|null $tax_number
* @property string $creation_hash
* @property int $created_by
*/
class BusinessClient extends Model
{
use BelongsToTenant;
protected $guarded = ['id'];
protected function casts(): array
{
return ['active' => 'boolean', 'version' => 'integer'];
}
}
+1 -1
View File
@@ -30,7 +30,7 @@ trait HasWorkContext
if ($actor instanceof User && app(WorkContext::class)->enforced($actor)) {
$key = app(WorkContext::class)->active(request());
$area = $model->getTable() === 'people_processes' ? 'people' : 'procurement';
abort_unless($key !== null && WorkContext::OPTIONS[$key]['operational'] && WorkContext::OPTIONS[$key]['area'] === $area, 403);
abort_unless($key !== null && WorkContext::operational($key) && WorkContext::OPTIONS[$key]['area'] === $area, 403);
$model->setAttribute('work_context_key', $key);
}
});
+104
View File
@@ -0,0 +1,104 @@
<?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;
});
}
}
+93
View File
@@ -0,0 +1,93 @@
<?php
namespace App\Services;
use App\Enums\PurchasingRole;
use App\Models\StockOperation;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
/** Invoice-linked evidence around the existing lot/reservation/physical issue workflow. */
final class CustomerDeliveries
{
/** @param array<string,mixed> $input
* @return array<string,mixed> */
public function record(User $actor, array $input): array
{
abort_unless(app(CustomerSales::class)->ready() && Schema::hasTable('customer_deliveries'), 503);
app(CustomerSales::class)->assertCan($actor, 'delivery');
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'invoice_id' => 'required|integer|min:1',
'line_no' => 'required|integer|between:1,50', 'warehouse_id' => 'required|integer|min:1',
'quantity' => 'required|string|regex:/^[0-9]{1,6}(\.[0-9]{1,3})?$/D', 'reference' => 'required|string|max:120',
'reason' => 'required|string|min:10|max:2000'])->validate();
foreach (['invoice_id', 'line_no', 'warehouse_id'] as $field) {
$data[$field] = (int) $data[$field];
}
$quantity = ReceiptWorkflow::milli($data['quantity']);
return DB::transaction(function () use ($actor, $data, $quantity): array {
app(ConflictGuard::class)->lockCompany($actor);
$current = app(CurrentActor::class)->lock($actor, [PurchasingRole::Warehouse]);
abort_unless(app(CustomerSales::class)->can($current, 'delivery'), 403);
$source = SalesStockSource::for($current, $data['invoice_id'], $data['line_no'], $quantity);
$hash = hash('sha256', json_encode([$data, $source->snapshot], JSON_THROW_ON_ERROR));
$old = DB::table('customer_deliveries')->where('tenant_id', $current->tenant_id)->where('operation_key', $data['operation_key'])->lockForUpdate()->first();
if ($old !== null) {
abort_unless((int) $old->created_by === $current->id, 403);
abort_unless(hash_equals($old->payload_hash, $hash), 409, 'A chave de entrega já foi utilizada com outro conteúdo.');
return ['id' => (int) $old->id, 'stock_operation_id' => (int) $old->stock_operation_id, 'replayed' => true];
}
$delivered = DB::table('customer_deliveries')->where('tenant_id', $current->tenant_id)->where('invoice_id', $data['invoice_id'])
->where('invoice_line_no', $data['line_no'])->sum('quantity_milli');
abort_unless($quantity <= $source->snapshot['invoice_quantity_milli'] - (int) $delivered, 409,
'A quantidade excede o saldo da linha facturada ainda por entregar.');
$operation = app(StockWorkflow::class)->record($current, ['kind' => 'issue', 'reference' => $data['reference'],
'idempotency_key' => $data['operation_key'], 'responsible_id' => $current->id, 'warehouse_id' => $data['warehouse_id'],
'stock_item_id' => $source->snapshot['stock_item_id'], 'quantity' => $data['quantity'], 'reason' => $data['reason'],
'destination' => $source->snapshot['client']['name'].' · '.$source->snapshot['invoice_reference']], $source);
$id = DB::table('customer_deliveries')->insertGetId(['tenant_id' => $current->tenant_id, 'company_id' => 0, 'unit_id' => 0,
'invoice_id' => $data['invoice_id'], 'invoice_line_no' => $data['line_no'], 'stock_operation_id' => $operation->id,
'quantity_milli' => $quantity, 'operation_key' => $data['operation_key'], 'payload_hash' => $hash,
'created_by' => $current->id, 'reason' => $data['reason'], 'created_at' => now()]);
app(RequisitionWorkflow::class)->audit($current, 'sales.delivered', null, null,
['delivery_id' => $id, 'invoice_id' => $data['invoice_id'], 'line_no' => $data['line_no'], 'stock_operation_id' => $operation->id, 'quantity_milli' => $quantity]);
return ['id' => $id, 'stock_operation_id' => $operation->id, 'replayed' => false];
});
}
/** @return array<string,mixed> */
public function workspace(User $actor, ?int $invoiceId = null): array
{
$actor = app(CustomerSales::class)->assertCan($actor, 'delivery_view');
$engine = app(CustomerSales::class)->engine($actor);
abort_unless(app(CustomerSales::class)->can($actor, 'delivery_view') && Schema::hasTable('customer_deliveries'), 403);
$query = DB::table('cr_invoices')->where(['tenant_id' => $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0]);
if ($invoiceId !== null) {
$query->where('id', $invoiceId);
}
$invoices = [];
foreach ($query->orderByDesc('id')->limit(20)->pluck('id') as $id) {
$invoice = $engine->deliveryInvoice((int) $id);
foreach ($invoice['lines'] as &$line) {
$line['delivered_milli'] = (int) DB::table('customer_deliveries')->where('tenant_id', $actor->tenant_id)->where('invoice_id', $id)
->where('invoice_line_no', $line['line_no'])->sum('quantity_milli');
$line['remaining_milli'] = $line['quantity_milli'] - $line['delivered_milli'];
}
unset($line);
$invoices[] = $invoice;
}
$deliveries = DB::table('customer_deliveries')->where('tenant_id', $actor->tenant_id)
->when($invoiceId !== null, fn ($query) => $query->where('invoice_id', $invoiceId))->orderByDesc('id')->limit(20)->get();
$operations = StockOperation::query()->where('tenant_id', $actor->tenant_id)->whereIn('id', $deliveries->pluck('stock_operation_id'))
->get(['id', 'reference', 'warehouse_id'])->keyBy('id');
return ['invoices' => $invoices, 'deliveries' => $deliveries->map(fn ($delivery) => ['id' => (int) $delivery->id,
'invoice_id' => (int) $delivery->invoice_id, 'line_no' => (int) $delivery->invoice_line_no,
'quantity_milli' => (int) $delivery->quantity_milli, 'created_at' => $delivery->created_at,
'stock_operation_id' => (int) $delivery->stock_operation_id, 'reference' => $operations->get($delivery->stock_operation_id)?->reference])->all()];
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace App\Services;
use Illuminate\Database\Connection;
/** Explicit host evidence only; stock remains owned by the existing common movement writer. */
final class CustomerDeliverySchema
{
public static function install(Connection $db, \Closure $verifyInstallation): void
{
$verifyInstallation($db);
if ($db->getDriverName() !== 'pgsql' || $db->getSchemaBuilder()->hasTable('customer_deliveries')
|| ! $db->getSchemaBuilder()->hasTable('cr_invoices') || ! $db->getSchemaBuilder()->hasTable('stock_operations')) {
throw new \LogicException('CUSTOMER_DELIVERY_SCHEMA_CONTEXT');
}
$db->transaction(function () use ($db): void {
$db->unprepared(<<<'SQL'
CREATE TABLE customer_deliveries(
id bigserial PRIMARY KEY,tenant_id bigint NOT NULL REFERENCES tenants(id),company_id bigint NOT NULL DEFAULT 0 CHECK(company_id=0),unit_id bigint NOT NULL DEFAULT 0 CHECK(unit_id=0),
invoice_id bigint NOT NULL,invoice_line_no integer NOT NULL CHECK(invoice_line_no BETWEEN 1 AND 50),stock_operation_id bigint NOT NULL REFERENCES stock_operations(id),
quantity_milli bigint NOT NULL CHECK(quantity_milli>0),operation_key uuid NOT NULL,payload_hash char(64) NOT NULL,created_by bigint NOT NULL REFERENCES users(id),reason text NOT NULL,created_at timestamp NOT NULL,
UNIQUE(tenant_id,operation_key),UNIQUE(stock_operation_id),FOREIGN KEY(invoice_id,tenant_id,company_id,unit_id) REFERENCES cr_invoices(id,tenant_id,company_id,unit_id)
);
CREATE FUNCTION customer_delivery_guard() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE i cr_invoices%ROWTYPE; o stock_operations%ROWTYPE; line jsonb; delivered bigint; movements bigint; physical bigint;
BEGIN
SELECT * INTO STRICT i FROM cr_invoices WHERE id=NEW.invoice_id AND tenant_id=NEW.tenant_id AND company_id=NEW.company_id AND unit_id=NEW.unit_id FOR UPDATE;
SELECT * INTO STRICT o FROM stock_operations WHERE id=NEW.stock_operation_id AND tenant_id=NEW.tenant_id;
line := i.snapshot->'amounts'->'lines'->(NEW.invoice_line_no-1);
SELECT coalesce(sum(quantity_milli),0) INTO delivered FROM customer_deliveries WHERE tenant_id=NEW.tenant_id AND company_id=NEW.company_id AND unit_id=NEW.unit_id AND invoice_id=NEW.invoice_id AND invoice_line_no=NEW.invoice_line_no;
SELECT count(*),coalesce(sum(quantity_milli),0) INTO movements,physical FROM stock_movements WHERE tenant_id=NEW.tenant_id AND stock_operation_id=o.id AND warehouse_id=o.warehouse_id AND stock_item_id=o.stock_item_id AND movement_type='issue';
IF line IS NULL OR (line->>'line_no')::integer IS DISTINCT FROM NEW.invoice_line_no
OR (line->>'stock_item_id')::bigint IS DISTINCT FROM o.stock_item_id
OR delivered>(line->>'quantity_milli')::bigint-NEW.quantity_milli
OR o.kind<>'issue' OR o.quantity_milli<>NEW.quantity_milli OR o.created_by<>NEW.created_by
OR (o.snapshot->'sales_invoice'->>'invoice_id')::bigint IS DISTINCT FROM i.id
OR (o.snapshot->'sales_invoice'->>'line_no')::integer IS DISTINCT FROM NEW.invoice_line_no
OR o.snapshot->'sales_invoice'->>'invoice_revision' IS DISTINCT FROM i.revision
OR movements<>1 OR physical<>-NEW.quantity_milli
THEN RAISE EXCEPTION 'CUSTOMER_DELIVERY_SOURCE_OR_QUANTITY_MISMATCH' USING ERRCODE='23514'; END IF;
RETURN NEW;
END $$;
CREATE TRIGGER customer_delivery_guard BEFORE INSERT ON customer_deliveries FOR EACH ROW EXECUTE FUNCTION customer_delivery_guard();
CREATE FUNCTION customer_delivery_preserve() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'CUSTOMER_DELIVERY_APPEND_ONLY'; END $$;
CREATE TRIGGER customer_delivery_preserve BEFORE UPDATE OR DELETE ON customer_deliveries FOR EACH ROW EXECUTE FUNCTION customer_delivery_preserve();
SQL);
});
}
}
+194
View File
@@ -0,0 +1,194 @@
<?php
namespace App\Services;
use App\Enums\PurchasingRole;
use App\Models\BusinessClient;
use App\Models\StockItem;
use App\Models\Tenant;
use App\Models\User;
use Brick\Math\BigDecimal;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Tempo\Finance\GeneralLedger\LedgerSchema;
use Tempo\Finance\GeneralLedger\Receivables;
use Tempo\Finance\GeneralLedger\ReceivablesSchema;
/** Native actor/catalogue adapter. All customer financial writes belong to the common core. */
final class CustomerSales
{
public function ready(): bool
{
if (config('third_party.sales_enabled') !== true || ! class_exists(Receivables::class, false)
|| ! Schema::hasTable('business_clients') || ! Schema::hasTable('cr_invoices')) {
return false;
}
$runtime = app(StandaloneRuntime::class);
if ($runtime->enabled()) {
return $runtime->feature('standalone-sales', DB::connection());
}
if (app()->environment('testing') && config('customer_sales.qa_enabled') === true && DB::getDriverName() === 'pgsql') {
LedgerSchema::assertSynthetic(DB::connection());
return true;
}
return false;
}
private function actor(User $actor, bool $lock = false): User
{
abort_unless($this->ready() && auth()->id() === $actor->id && $actor->tenant_id !== null, 403);
$fresh = $lock ? app(CurrentActor::class)->lock($actor) : User::query()->where('tenant_id', $actor->tenant_id)->findOrFail($actor->id);
abort_if(app(OrganizationAccess::class)->maintenanceOnly($fresh), 403);
$contexts = app(WorkContext::class);
if ($contexts->enforced($fresh)) {
abort_unless(app()->bound('request') && request()->hasSession() && $contexts->active(request()) === 'procurement.sales', 403,
'Seleccione Venda para terceiros no Painel Inicial.');
}
return $fresh;
}
private function person(User $actor): string
{
if (Schema::hasTable('pa_access')) {
$people = DB::table('pa_access')->where(['tenant_id' => $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0, 'user_id' => $actor->id])
->distinct()->pluck('person')->all();
abort_if(count($people) > 1, 409, 'A identidade financeira do operador tem correspondências divergentes.');
if ($people !== []) {
abort_unless(is_string($people[0]) && trim($people[0]) !== '', 409);
return $people[0];
}
}
return 'compras-user:'.$actor->tenant_id.':'.$actor->id;
}
public function can(User $actor, string $action): bool
{
$roles = match ($action) {
'series' => [PurchasingRole::Admin],
'invoice_prepare', 'invoice_issue' => [PurchasingRole::Procurement],
'invoice_review', 'receipts_view', 'receipt_prepare', 'receipt_decide', 'allocation_prepare', 'allocation_decide', 'reversal_prepare', 'reversal_decide' => [PurchasingRole::Finance],
'delivery_view', 'delivery' => [PurchasingRole::Warehouse],
'view' => [PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::Admin],
default => [],
};
return $roles !== [] && $actor->hasFunctions($roles) && ! app(OrganizationAccess::class)->maintenanceOnly($actor);
}
public function assertCan(User $actor, string $action): User
{
$current = $this->actor($actor);
abort_unless($this->can($current, $action), 403);
return $current;
}
public function engine(User $actor): Receivables
{
$fresh = $this->actor($actor);
$person = $this->person($fresh);
$scope = ['tenant_id' => (int) $fresh->tenant_id, 'company_id' => 0, 'unit_id' => 0];
return new Receivables(DB::connection(), $scope, $fresh->id, $person,
function (string $action) use ($fresh, $person): void {
$current = $this->actor($fresh, ! in_array($action, ['view', 'receipts_view', 'delivery_view'], true));
abort_unless($this->person($current) === $person, 409, 'A identidade do operador mudou; reabra o documento.');
abort_unless($this->can($current, $action), 403);
}, fn () => app(ConflictGuard::class)->lockCompany($fresh),
fn (string $kind, array $input) => $this->source($fresh, $kind, $input));
}
/** @return array{actor:User,scope:array<string,int>,person:string} */
public function financialContext(User $actor): array
{
$fresh = $this->actor($actor);
abort_unless($fresh->hasFunctions([PurchasingRole::Finance, PurchasingRole::Admin]), 403);
$scope = ['tenant_id' => (int) $fresh->tenant_id, 'company_id' => 0, 'unit_id' => 0];
$person = $this->person($fresh);
abort_unless(DB::table('pa_access')->where($scope)->where(['user_id' => $fresh->id, 'action' => 'view', 'person' => $person])->exists(), 403);
return ['actor' => $fresh, 'scope' => $scope, 'person' => $person];
}
/** @param array<string,mixed> $input
* @return array<string,mixed> */
private function source(User $actor, string $kind, array $input): array
{
abort_unless(in_array($kind, ['invoice', 'receipt'], true), 403);
$client = BusinessClient::query()->where('tenant_id', $actor->tenant_id)->whereKey($input['client_id'])->lockForUpdate()->firstOrFail();
abort_unless($client->version === $input['client_version'] && ($kind !== 'invoice' || $client->active), 409,
'O cliente mudou ou deixou de aceitar novas operações; actualize a selecção.');
$snapshot = $client->only(['id', 'code', 'name', 'tax_number', 'address', 'version']);
if ($kind === 'receipt') {
return ['client' => $snapshot];
}
$lines = [];
foreach ($input['lines'] as $line) {
$item = StockItem::query()->where('tenant_id', $actor->tenant_id)->whereKey($line['stock_item_id'])->lockForUpdate()->firstOrFail();
$lines[] = [...$line, ...$item->only(['id', 'code', 'name', 'unit']), 'stock_item_id' => $item->getKey()];
}
$company = Tenant::query()->findOrFail($actor->tenant_id);
return ['client' => $snapshot, 'lines' => $lines, 'issuer' => ['id' => $company->id, 'name' => $company->name,
...array_intersect_key($company->company_details ?? [], array_flip(['legal_name', 'nuit', 'address', 'phone', 'email']))]];
}
/** @param array<string,mixed> $input
* @return array<string,mixed> */
public function command(User $actor, string $action, array $input): array
{
$this->assertCan($actor, $action);
$rules = match ($action) {
'series' => ['series_key' => 'required|string|max:80', 'prefix' => 'required|string|max:80', 'starts_on' => 'required|date_format:Y-m-d',
'ends_on' => 'required|date_format:Y-m-d|after_or_equal:starts_on', 'first_number' => 'required|integer|min:1'],
'invoice_prepare' => ['client_id' => 'required|integer|min:1', 'client_version' => 'required|integer|min:1',
'series_key' => 'required|string|max:80', 'issued_on' => 'required|date_format:Y-m-d', 'due_on' => 'required|date_format:Y-m-d|after_or_equal:issued_on',
'lines' => 'required|array|min:1|max:50', 'lines.*.stock_item_id' => 'required|integer|min:1',
'lines.*.quantity' => 'required|string|regex:/^[0-9]{1,6}(\.[0-9]{1,3})?$/D',
'lines.*.unit_price' => 'required|string|regex:/^[0-9]{1,9}(\.[0-9]{1,2})?$/D',
'lines.*.tax_rate' => 'required|string|regex:/^[0-9]{1,3}(\.[0-9]{1,4})?$/D', 'lines.*.tax_basis' => 'required|string|max:1000'],
'invoice_review' => ['proposal_id' => 'required|integer|min:1', 'revision' => 'required|string|size:64', 'decision' => 'required|in:approved,rejected'],
'invoice_issue' => ['proposal_id' => 'required|integer|min:1', 'revision' => 'required|string|size:64'],
'receipt_prepare' => ['client_id' => 'required|integer|min:1', 'client_version' => 'required|integer|min:1',
'amount' => 'required|string|regex:/^[0-9]{1,12}(\.[0-9]{1,2})?$/D', 'received_on' => 'required|date_format:Y-m-d', 'reference' => 'required|string|max:180'],
'allocation_prepare' => ['invoice_id' => 'required|integer|min:1', 'receipt_id' => 'required|integer|min:1',
'amount' => 'required|string|regex:/^[0-9]{1,12}(\.[0-9]{1,2})?$/D'],
'reversal_prepare' => ['allocation_id' => 'required|integer|min:1'],
'receipt_decide', 'allocation_decide', 'reversal_decide' => ['proposal_id' => 'required|integer|min:1', 'revision' => 'required|string|size:64', 'decision' => 'required|in:confirmed,rejected'],
default => throw new \InvalidArgumentException('Comando de venda desconhecido.'),
};
$data = Validator::make($input, $rules + ['operation_key' => 'required|uuid', 'reason' => 'required|string|min:10|max:2000'])->validate();
$key = $data['operation_key'];
unset($data['operation_key']);
foreach (['client_id', 'client_version', 'first_number', 'proposal_id', 'invoice_id', 'receipt_id', 'allocation_id'] as $field) {
if (isset($data[$field])) {
$data[$field] = (int) $data[$field];
}
}
if (isset($data['amount'])) {
$data['amount_minor'] = BigDecimal::of($data['amount'])->multipliedBy(100)->toInt();
unset($data['amount']);
}
if (isset($data['lines'])) {
$data['lines'] = array_map(fn ($line) => ['stock_item_id' => (int) $line['stock_item_id'],
'quantity_milli' => ReceiptWorkflow::milli($line['quantity']),
'unit_price_minor' => BigDecimal::of($line['unit_price'])->multipliedBy(100)->toInt(),
'tax_rate' => $line['tax_rate'], 'tax_basis' => trim($line['tax_basis'])], $data['lines']);
}
return DB::transaction(function () use ($actor, $action, $data, $key): array {
$result = $this->engine($actor)->command($action, $data, $key);
if (! $result['replayed']) {
app(RequisitionWorkflow::class)->audit($actor, 'sales.'.$action, null, null, ['result' => $result, 'reason' => $data['reason']]);
}
return $result;
});
}
}
+1
View File
@@ -60,6 +60,7 @@ class OrganizationAccess
'finance' => 'Conferência e operações financeiras',
'warehouse' => 'Recepção e operações de armazém',
'admin' => 'Administrar a empresa, utilizadores e parametrização',
'people_contract_formalize' => 'Direcção: confirmar contrato assinado de Pessoas',
'people_service_prepare' => 'Preparar contratação de prestadores individuais',
'people_service_review' => 'Avaliar e conferir contratação de prestadores individuais',
'people_staff_prepare' => 'Preparar recrutamento de trabalhadores',
+3
View File
@@ -76,6 +76,9 @@ class PeopleAccess
$target = User::query()->where('tenant_id', $actor->tenant_id)->where('id', $data['user_id'])->firstOrFail();
abort_unless($data['scopes'] === [] || app(PeopleHiring::class)->allowed($target, $record->kind), 422, 'Atribua primeiro um perfil compatível com este percurso na parametrização da empresa.');
foreach ($data['scopes'] as $scope) {
if ($scope === 'approve' && app(ThirdPartyHiring::class)->isClientProcess($record) && ! app(ThirdPartyHiring::class)->direction($target)) {
throw ValidationException::withMessages(['scopes' => 'A decisão final para o cliente exige a autoridade de Direcção da prestadora.']);
}
$function = match ($scope) {
'review', 'approve' => 'review', 'prepare', 'contract' => 'prepare', default => null
};
+1 -1
View File
@@ -12,7 +12,7 @@ class PeopleApplicationReport
/** @return array<string,int|string|null> */
public function counts(PeopleProcess $process, User $actor): array
{
$frozen = in_array($process->status, ['selected', 'contract_draft'], true);
$frozen = in_array($process->status, ['selected', 'contract_draft', 'contract_formalized'], true);
$rows = $frozen ? ($process->selection['rows'] ?? []) : app(PeopleHiring::class)->matrix($process);
$complete = count(array_filter($rows, fn ($row) => $row['score_minor'] !== null));
$started = count(array_filter($rows, fn ($row) => $row['evaluation_count'] > 0));
+3 -3
View File
@@ -93,13 +93,13 @@ class PeopleClarifications
$users = User::query()->where('tenant_id', $process->tenant_id)->orderBy('name')->get()->filter(fn ($user) => $this->eligibleResponsible($user, $process))->map(fn ($user) => $user->only(['id', 'name']))->values()->all();
}
return ['ready' => true, 'items' => $items, 'sources' => $sources, 'users' => $users, 'preservedDecision' => in_array($process->status, ['selected', 'contract_draft'], true)];
return ['ready' => true, 'items' => $items, 'sources' => $sources, 'users' => $users, 'preservedDecision' => in_array($process->status, ['selected', 'contract_draft', 'contract_formalized'], true)];
}
/** @return list<array<string,mixed>> */
public function sources(User $actor, PeopleProcess $process): array
{
if (! Schema::hasTable('people_clarifications') || ! in_array($process->status, ['assessment', 'selection_review', 'selected', 'contract_draft'], true) || ! $this->canRaise($actor, $process)) {
if (! Schema::hasTable('people_clarifications') || ! in_array($process->status, ['assessment', 'selection_review', 'selected', 'contract_draft', 'contract_formalized'], true) || ! $this->canRaise($actor, $process)) {
return [];
}
$existing = DB::table('people_clarifications')->where('tenant_id', $process->tenant_id)->where('people_process_id', $process->id)->get(['people_review_id', 'criterion_index']);
@@ -139,7 +139,7 @@ class PeopleClarifications
$data['responsible_id'] = $responsible->id;
}
if ($command === 'create') {
abort_unless(in_array($process->status, ['assessment', 'selection_review', 'selected', 'contract_draft'], true), 409);
abort_unless(in_array($process->status, ['assessment', 'selection_review', 'selected', 'contract_draft', 'contract_formalized'], true), 409);
$data += Validator::make($input, ['operation_key' => 'required|uuid', 'review_id' => 'required|integer|min:1', 'criterion_index' => 'required|integer|between:0,19'])->validate();
$review = DB::table('people_reviews as r')->join('people_applications as a', 'a.id', '=', 'r.people_application_id')->where('r.tenant_id', $process->tenant_id)->where('a.people_process_id', $process->id)->where('r.id', $data['review_id'])->first(['r.id', 'r.answers', 'a.id as application_id']);
abort_unless($review !== null, 404);
@@ -0,0 +1,86 @@
<?php
namespace App\Services;
use App\Models\PeopleProcess;
use App\Models\User;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
/** Direction records signed evidence; no employee admission or external dispatch. */
final class PeopleContractFormalization
{
public function ready(): bool
{
return Schema::hasTable('migrations') && DB::table('migrations')->where('migration', '2026_11_29_000003_allow_signed_people_contract')->exists();
}
public function can(User $actor, PeopleProcess $record): bool
{
$access = app(PeopleAccess::class);
return $this->ready() && $actor->tenant_id === $record->tenant_id
&& ! app(OrganizationAccess::class)->maintenanceOnly($actor)
&& in_array('people_contract_formalize', app(OrganizationAccess::class)->permissions($actor), true)
&& $access->can($actor, $record, 'view')
&& ($access->can($actor, $record, 'contract') || $access->can($actor, $record, 'contract_view'));
}
/** @param array<string,mixed> $input */
public function confirm(User $actor, int $id, array $input): PeopleProcess
{
abort_unless($this->ready(), 503, 'A instalação da formalização contratual está pendente.');
$created = null;
try {
return DB::transaction(function () use ($actor, $id, $input, &$created) {
app(ConflictGuard::class)->lockCompany($actor);
$fresh = app(CurrentActor::class)->lock($actor);
$record = PeopleProcess::query()->where('tenant_id', $fresh->tenant_id)->lockForUpdate()->findOrFail($id);
abort_unless($this->can($fresh, $record), 403);
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'operation_key' => 'required|uuid',
'signed_on' => 'required|date_format:Y-m-d|before_or_equal:today', 'reference' => 'required|string|max:200',
'reason' => 'required|string|min:10|max:4000', 'no_conflict' => 'accepted',
'signed_document' => 'required|file|mimes:pdf|max:10240'])->validate();
/** @var UploadedFile $file */
$file = $data['signed_document'];
$digest = hash_file('sha256', $file->getRealPath());
abort_unless(is_string($digest), 503, 'Não foi possível conferir o documento assinado.');
$hash = hash('sha256', json_encode([$data['signed_on'], $data['reference'], $data['reason'], $digest], JSON_THROW_ON_ERROR));
if (($record->contract['formalization_operation_key'] ?? null) === $data['operation_key']) {
abort_unless(hash_equals($record->contract['formalization_hash'], $hash), 409);
return $record;
}
abort_unless($record->version === (int) $data['version'], 409, 'O processo mudou. Actualize antes de confirmar.');
abort_unless($record->status === 'contract_draft' && ($record->contract['status'] ?? null) === 'draft'
&& $record->selected_application_id !== null, 409, 'Prepare a minuta após a selecção aprovada.');
$disk = Storage::disk('people_contracts');
$path = $file->storeAs($record->tenant_id.'/'.$record->id, Str::uuid().'.pdf', 'people_contracts');
$created = $path;
abort_unless(is_string($path) && hash_equals($digest, hash('sha256', $disk->get($path))), 503);
$before = app(PeopleHiring::class)->snapshot($record);
$record->contract = [...$record->contract, 'status' => 'formalized', 'signed_on' => $data['signed_on'],
'signed_reference' => $data['reference'], 'formalized_at' => now()->toIso8601String(), 'formalized_by' => $fresh->id,
'formalization_reason' => $data['reason'], 'formalization_operation_key' => $data['operation_key'], 'formalization_hash' => $hash,
'signed_document' => ['path' => $path, 'sha256' => $digest, 'bytes' => $file->getSize()]];
$record->status = 'contract_formalized';
$record->version++;
$record->save();
$after = app(PeopleHiring::class)->snapshot($record);
unset($after['contract']['signed_document']['path']);
app(RequisitionWorkflow::class)->audit($fresh, 'people.contract_formalized', null, $before, $after);
return $record;
});
} catch (\Throwable $error) {
if (is_string($created)) {
Storage::disk('people_contracts')->delete($created);
}
throw $error;
}
}
}
+4 -1
View File
@@ -19,11 +19,14 @@ class PeopleContractHandoff
&& ! empty($process->contract['reference'])
&& $process->selected_application_id !== null, 409, 'A ligação a RH exige contrato interno formalizado.');
$contract = $process->contract;
unset($contract['signed_document']['path'], $contract['formalization_operation_key'], $contract['formalization_hash']);
return ['schema' => 'sgc.people.contract_formalized.v1',
'idempotency_key' => 'sgc:'.$process->tenant_id.':people:'.$process->id.':contract:'.$process->version,
'tenant_id' => $process->tenant_id, 'process_id' => $process->id, 'process_version' => $process->version,
'application_id' => $process->selected_application_id, 'kind' => $process->kind,
'work_context_key' => $process->getAttribute('work_context_key'),
'contract' => $process->contract];
'contract' => $contract];
}
}
+5 -4
View File
@@ -22,20 +22,21 @@ class PeopleEvidenceBrief
$rules = $process['rules'];
$add('rules', count($rules['criteria']).' critérios preservados; mínimo de '.$rules['minimum_reviews'].' avaliações independentes por candidatura. Estes requisitos não comprovam que todas as avaliações já foram feitas.',
'#people-report-scope', 'Âmbito e critérios preservados', 'process.rules', $rules);
$frozen = $process['selection'] !== null && in_array($process['status'], ['selection_review', 'selected', 'contract_draft'], true);
$frozen = $process['selection'] !== null && in_array($process['status'], ['selection_review', 'selected', 'contract_draft', 'contract_formalized'], true);
$rows = $frozen ? $process['selection']['rows'] : $candidates;
$add('candidates', count($rows).' candidaturas constam da '.($frozen ? 'base de selecção preservada apresentada no relatório.' : 'matriz actual apresentada no relatório.').' A pontuação não constitui selecção automática.',
'#people-report-candidates', 'Candidaturas e avaliação', $frozen ? 'process.selection.rows' : 'candidates', $rows);
if ($process['selection'] !== null) {
$approved = in_array($process['status'], ['selected', 'contract_draft'], true);
$approved = in_array($process['status'], ['selected', 'contract_draft', 'contract_formalized'], true);
$text = $approved ? 'Existe uma selecção aprovada e preservada; não equivale a contrato assinado ou admissão efectiva.' :
($process['status'] === 'selection_review' ? 'Existe uma proposta de selecção pendente de conferência independente.' : 'A proposta de selecção foi devolvida para nova análise; não está aprovada.');
$add('selection', $text,
'#people-report-selection', 'Fundamento da selecção', 'process.selection', [$process['status'], $process['selection']]);
}
if ($contractVisible && $process['contract'] !== null) {
$add('contract', 'Consta uma minuta contratual de preparação interna, sem confirmação de assinatura ou admissão efectiva.',
'#people-report-contract', 'Minuta contratual', 'process.contract', $process['contract']);
$formalized = $process['status'] === 'contract_formalized' && ($process['contract']['status'] ?? null) === 'formalized';
$add('contract', $formalized ? 'Consta contrato assinado, com comprovativo e confirmação registada pela direcção. A admissão efectiva mantém registo separado.' : 'Consta uma minuta contratual de preparação interna, sem confirmação de assinatura ou admissão efectiva.',
'#people-report-contract', $formalized ? 'Contrato formalizado' : 'Minuta contratual', 'process.contract', $process['contract']);
}
if ($clarifications['ready']) {
$pending = count(array_filter($clarifications['items'], fn ($item) => $item['status'] !== 'resolved'));
+18 -4
View File
@@ -30,6 +30,12 @@ class PeopleHiring
return array_values(array_filter(['service', 'staff'], fn ($kind) => $this->allowed($actor, $kind)));
}
public function canConfirm(User $actor, PeopleProcess $record): bool
{
return $this->allowed($actor, $record->kind, 'review') && app(PeopleAccess::class)->can($actor, $record, 'approve')
&& (! app(ThirdPartyHiring::class)->isClientProcess($record) || app(ThirdPartyHiring::class)->direction($actor));
}
/** @return array<string,mixed> */
public function snapshot(PeopleProcess $record): array
{
@@ -88,9 +94,13 @@ class PeopleHiring
$actor = app(CurrentActor::class)->lock($actor);
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
if ($command === 'create') {
$context = app(ThirdPartyHiring::class)->creationContext($actor);
$clientRules = $context === 'people.third_party'
? ['client_id' => 'required|integer|min:1', 'client_version' => 'required|integer|min:1']
: ['client_id' => 'prohibited', 'client_version' => 'prohibited'];
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'kind' => 'required|in:service,staff', 'title' => 'required|string|min:3|max:200',
'purpose' => 'required|string|min:10|max:5000', 'closes_on' => 'required|date_format:Y-m-d|after_or_equal:today', 'minimum_reviews' => 'required|integer|between:1,20',
'criteria' => 'required|array|min:1|max:20', 'criteria.*.label' => 'required|string|max:150|distinct', 'criteria.*.weight' => 'required|integer|between:1,100'])->validate();
'criteria' => 'required|array|min:1|max:20', 'criteria.*.label' => 'required|string|max:150|distinct', 'criteria.*.weight' => 'required|integer|between:1,100', ...$clientRules])->validate();
abort_unless($this->allowed($actor, $data['kind'], 'prepare'), 403);
if (array_sum(array_column($data['criteria'], 'weight')) !== 100) {
throw ValidationException::withMessages(['criteria' => 'As ponderações dos critérios devem somar 100%.']);
@@ -100,18 +110,19 @@ class PeopleHiring
$data['annex'] = $annex;
}
$hash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR));
$existing = PeopleProcess::query()->where('operation_key', $data['operation_key'])->first();
$existing = PeopleProcess::query()->withoutGlobalScope('work_context')->where('tenant_id', $actor->tenant_id)->where('operation_key', $data['operation_key'])->first();
if ($existing) {
abort_unless($existing->created_by === $actor->id && $existing->creation_hash === $hash, 409);
abort_unless($existing->created_by === $actor->id && $existing->creation_hash === $hash && $existing->getAttribute('work_context_key') === $context, 409);
return $existing;
}
$submissionForm = app(SubmissionForms::class)->opportunity($actor->tenant_id, $data['kind']);
$client = $context === 'people.third_party' ? app(ThirdPartyHiring::class)->clientRules($actor, (int) $data['client_id'], (int) $data['client_version']) : [];
$record = PeopleProcess::query()->create(['tenant_id' => $actor->tenant_id, 'created_by' => $actor->id,
'operation_key' => $data['operation_key'], 'creation_hash' => $hash, 'kind' => $data['kind'], 'title' => $data['title'],
'purpose' => $data['purpose'], 'closes_on' => $data['closes_on'], 'rules' => ['minimum_reviews' => (int) $data['minimum_reviews'],
'criteria' => array_map(fn ($criterion) => ['label' => trim($criterion['label']), 'weight' => (int) $criterion['weight']], $data['criteria']),
...($annex === null ? [] : ['annex' => $annex]), ...($submissionForm === null ? [] : ['submission_form' => $submissionForm])]]);
...$client, ...($annex === null ? [] : ['annex' => $annex]), ...($submissionForm === null ? [] : ['submission_form' => $submissionForm])]]);
DB::table('people_access_states')->insert(['tenant_id' => $record->tenant_id, 'people_process_id' => $record->id, 'version' => 1]);
app(PeopleAccess::class)->insert($record, $actor->id, ['view', 'prepare', 'contract', 'manage', ...(! empty($annex['fields']['financial']) ? ['financial'] : [])], 'Preparação assumida ao criar o processo.');
$before = null;
@@ -129,6 +140,9 @@ class PeopleHiring
'open', 'evaluate' => 'review', 'confirm' => 'approve', 'contract' => 'contract', default => 'prepare'
};
abort_unless(app(PeopleAccess::class)->can($actor, $record, $scope), 403);
if ($command === 'confirm') {
abort_unless($this->canConfirm($actor, $record), 403, 'A decisão final para o cliente compete à Direcção da prestadora.');
}
if ($command === 'open') {
Validator::make($input, ['no_conflict' => 'accepted'])->validate();
abort_unless($record->status === 'draft' && $record->created_by !== $actor->id, 403, 'A abertura exige conferente distinto do preparador.');
+1
View File
@@ -15,6 +15,7 @@ class PeopleProcessProjection
abort_unless($access->can($actor, $record, 'view'), 403);
$workflow = app(PeopleHiring::class);
$snapshot = $workflow->snapshot($record);
unset($snapshot['contract']['signed_document']['path'], $snapshot['contract']['formalization_operation_key'], $snapshot['contract']['formalization_hash']);
$rows = $workflow->matrix($record);
if (! $access->can($actor, $record, 'financial')) {
unset($snapshot['rules']['annex']['fields']['financial']);
+2 -1
View File
@@ -15,7 +15,7 @@ class PeopleSelectionReport
$selection = $process->selection ?? [];
$state = match ($process->status) {
'selection_review' => 'Proposta por conferir',
'selected', 'contract_draft' => 'Selecção aprovada',
'selected', 'contract_draft', 'contract_formalized' => 'Selecção aprovada',
default => ($selection['outcome'] ?? null) === 'returned' ? 'Proposta devolvida' : 'Sem proposta de selecção',
};
$pending = match ($process->status) {
@@ -24,6 +24,7 @@ class PeopleSelectionReport
'selection_review' => 'Conferir proposta por pessoa independente',
'selected' => 'Preparar minuta contratual',
'contract_draft' => 'Minuta preparada; formalização não registada neste percurso',
'contract_formalized' => 'Contrato assinado confirmado pela direcção',
default => 'Consultar processo',
};
+8 -4
View File
@@ -10,7 +10,7 @@ use Illuminate\Support\Facades\Schema;
class PeopleWorkdesk
{
public const STATES = ['draft', 'open', 'assessment', 'selection_review', 'selected', 'contract_draft'];
public const STATES = ['draft', 'open', 'assessment', 'selection_review', 'selected', 'contract_draft', 'contract_formalized'];
/** @param Builder<PeopleProcess> $query
* @return array<string,mixed>
@@ -29,14 +29,18 @@ class PeopleWorkdesk
foreach ((clone $query)->orderBy('id')->lazyById(100) as $record) {
$total++;
// Preparing a draft does not close a hiring process or prove a signed contract.
$active++;
$active += $record->status === 'contract_formalized' ? 0 : 1;
$contractDrafts += $record->status === 'contract_draft' ? 1 : 0;
$scopes = $access->scopes($actor, $record);
$prepare = ! $maintenance && in_array('prepare', $scopes, true) && $workflow->allowed($actor, $record->kind, 'prepare');
$review = ! $maintenance && in_array('review', $scopes, true) && $workflow->allowed($actor, $record->kind, 'review');
$approve = ! $maintenance && in_array('approve', $scopes, true) && $workflow->allowed($actor, $record->kind, 'review');
$approve = ! $maintenance && $workflow->canConfirm($actor, $record);
$contract = ! $maintenance && in_array('contract', $scopes, true) && $workflow->allowed($actor, $record->kind, 'prepare');
$base = ['process_id' => $record->id, 'reference' => 'PES-'.$record->id, 'title' => $record->title, 'kind' => $record->kind, 'status' => $record->status];
$title = $record->title;
if (app(ThirdPartyHiring::class)->isClientProcess($record) && isset($record->rules['client']['name'])) {
$title .= ' · Cliente: '.$record->rules['client']['name'];
}
$base = ['process_id' => $record->id, 'reference' => 'PES-'.$record->id, 'title' => $title, 'kind' => $record->kind, 'status' => $record->status];
$pendingTriage = in_array($record->status, ['open', 'assessment'], true) ? app(CandidateTriage::class)->pending($record) : 0;
$item = fn (string $action, string $label, ?string $due = null, ?int $application = null) => [...$base,
'id' => $record->id.':'.$action.($application === null ? '' : ':'.$application), 'action' => $action, 'label' => $label, 'due_on' => $due,
+21
View File
@@ -2,6 +2,7 @@
namespace App\Services;
use App\Models\PrivateAuditExport;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
@@ -31,6 +32,26 @@ final class PrivateAuditAccess
&& Schema::hasTable('private_audit_exports');
}
/** Exact historical archives approved for the installation's context transition.
* @return list<int>
*/
public function legacyExportIds(User $actor, string $context): array
{
if ($context !== 'procurement.internal' || auth()->id() !== $actor->id || $actor->tenant_id === null) {
return [];
}
$pins = config('private-audit.legacy_export_transitions.'.$actor->tenant_id, []);
if (! is_array($pins) || $pins === []) {
return [];
}
return array_values(PrivateAuditExport::query()->where('tenant_id', $actor->tenant_id)->where('created_by', $actor->id)->where('work_context', 'legacy')
->whereIn('id', array_keys($pins))->get(['id', 'sha256'])
->filter(fn (PrivateAuditExport $export) => is_string($pins[$export->id] ?? null)
&& preg_match('/^[a-f0-9]{64}$/D', $pins[$export->id]) === 1 && hash_equals($pins[$export->id], $export->sha256))
->map(fn (PrivateAuditExport $export) => (int) $export->id)->all());
}
/** @return array{actor:User,context:string,granted:list<string>} */
public function current(User $candidate): array
{
+3 -1
View File
@@ -139,7 +139,9 @@ final class PrivateAuditExporter
$scope = app(PrivateAuditAccess::class)->authorise($candidate, $export->families);
$actor = $scope['actor'];
abort_unless($export->tenant_id === $actor->tenant_id && $export->created_by === $actor->id, 404);
abort_unless($scope['context'] === $export->work_context, 409, 'Seleccione o contexto original da exportação.');
abort_unless($scope['context'] === $export->work_context
|| in_array($export->id, app(PrivateAuditAccess::class)->legacyExportIds($actor, $scope['context']), true),
409, 'Seleccione o contexto original da exportação.');
$prefix = 'audit-exports/'.$actor->tenant_id.'/'.$actor->id.'/';
abort_unless(preg_match('/^'.preg_quote($prefix, '/').'[a-f0-9-]{36}\/auditoria\.zip$/D', $export->path) === 1, 409);
$disk = Storage::disk('local');
+8 -5
View File
@@ -8,7 +8,7 @@ use Illuminate\Support\Str;
use LogicException;
use RuntimeException;
/** Only new, individually tracked files in an owned QA workspace; never recursive deletion. */
/** Only new, individually tracked files in private application storage. */
final class PrivateAuditFiles
{
public readonly string $relative;
@@ -24,12 +24,15 @@ final class PrivateAuditFiles
public function __construct(User $actor)
{
$disk = Storage::disk('local');
$boundary = realpath(base_path('storage/framework/testing'));
$operational = app(StandaloneRuntime::class)->enabled();
abort_if($operational && ! app(PrivateAuditAccess::class)->ready(), 503);
$boundary = realpath($operational ? storage_path() : base_path('storage/framework/testing'));
$storageRoot = realpath($disk->path(''));
abort_unless($actor->id === auth()->id() && $actor->tenant_id !== null && $boundary !== false && $storageRoot !== false
&& $this->within($storageRoot, $boundary), 503, 'A exportação requer armazenamento QA isolado.');
$public = realpath(public_path());
abort_if($public !== false && $this->within($storageRoot, $public), 503, 'O pacote de auditoria não pode usar armazenamento público.');
&& $this->within($storageRoot, $boundary), 503, 'A exportação requer armazenamento privado da aplicação.');
foreach ([realpath(public_path()), realpath(storage_path('app/public'))] as $public) {
abort_if($public !== false && ($storageRoot === $public || $this->within($storageRoot, $public)), 503, 'O pacote de auditoria não pode usar armazenamento público.');
}
$this->relative = 'audit-exports/'.$actor->tenant_id.'/'.$actor->id.'/'.Str::uuid();
$this->root = $disk->path($this->relative);
$parent = $storageRoot;
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace App\Services;
use App\Models\User;
/** Only a current authorised read of an issued invoice can construct this source. */
final readonly class SalesStockSource
{
/** @param array<string,mixed> $snapshot */
private function __construct(public array $snapshot) {}
public static function for(User $actor, int $invoiceId, int $lineNumber, int $quantity): self
{
abort_unless($invoiceId > 0 && $lineNumber > 0 && $quantity > 0, 422);
$invoice = app(CustomerSales::class)->engine($actor)->deliveryInvoice($invoiceId);
$selected = null;
foreach ($invoice['lines'] as $line) {
if ($line['line_no'] === $lineNumber) {
$selected = $line;
break;
}
}
abort_unless(is_array($selected) && is_int($selected['stock_item_id'] ?? null)
&& $quantity <= $selected['quantity_milli'], 409, 'Seleccione uma linha de stock da factura emitida e a quantidade ainda por entregar.');
return new self(['invoice_id' => $invoiceId, 'invoice_reference' => $invoice['reference'], 'invoice_revision' => $invoice['revision'],
'client' => $invoice['client'], 'line_no' => $lineNumber, 'stock_item_id' => $selected['stock_item_id'],
'invoice_quantity_milli' => $selected['quantity_milli'], 'quantity_milli' => $quantity]);
}
public function verify(User $actor): void
{
$current = self::for($actor, $this->snapshot['invoice_id'], $this->snapshot['line_no'], $this->snapshot['quantity_milli']);
abort_unless($current->snapshot === $this->snapshot, 409, 'A origem da entrega mudou; reabra a factura.');
}
}
+2 -1
View File
@@ -27,7 +27,8 @@ final class StandaloneInstallation
}
$settings = config('standalone-runtime');
$settings['enabled'] = true;
$settings['features'] = array_fill_keys(StandaloneRuntime::FEATURES, true);
$selected = (new StandaloneArtifact)->verify($settings['root'], $settings['manifest_sha256']);
$settings['features'] = array_fill_keys(array_values(array_intersect(StandaloneRuntime::FEATURES, $selected['manifest']['capabilities'])), true);
$runtime = new StandaloneRuntime($settings, new StandaloneArtifact);
$artifact = $runtime->artifact();
$runtime->assertLoadedPackages(allowMissing: true);
+11 -1
View File
@@ -12,7 +12,7 @@ final class StandaloneRuntime
'urgent-reviews', 'urgent-quotations', 'conflict-releases', 'private-audit', 'expense-allocations',
'agreement-order-limits', 'order-parts', 'import-tariffs', 'import-legal', 'import-dossier',
'import-bank-support', 'import-readiness', 'import-estimates', 'import-landed-costs', 'budget-distributions',
'supplier-payables', 'general-ledger', 'supplier-settlements', 'general-ledger-cycle', 'finance-configuration'];
'supplier-payables', 'general-ledger', 'supplier-settlements', 'general-ledger-cycle', 'finance-configuration', 'standalone-sales'];
/** @var array{root:string,manifest:array<string,mixed>,paths:array<string,string>}|null */
private ?array $artifact = null;
@@ -85,6 +85,16 @@ final class StandaloneRuntime
}
}
if (! $allowMissing) {
if ($this->requested('standalone-sales')) {
foreach (['ReceivablesSchema' => ['CONTRACT', 'COMMON-RECEIVABLES-v1'],
'ConfiguredSales' => ['CONTRACT', 'COMMON-LEDGER-CONFIGURED-SALES-v1'],
'CustomerInvoiceMath' => ['POLICY', 'COMMON-CUSTOMER-LINE-AMOUNTS-v1']] as $type => [$constant, $value]) {
$class = 'Tempo\\Finance\\GeneralLedger\\'.$type;
if (! class_exists($class, false) || (new \ReflectionClass($class))->getConstant($constant) !== $value) {
throw new LogicException('COMPRAS_RUNTIME_CUSTOMER_CONTRACT');
}
}
}
if ($this->requested('finance-configuration')) {
$configuration = 'Tempo\\Finance\\GeneralLedger\\LedgerConfiguration';
if (! class_exists($configuration, false) || (new \ReflectionClass($configuration))->getConstant('VERSION') !== 'COMMON-FINANCE-CONFIGURATION-v1') {
+12 -1
View File
@@ -14,7 +14,8 @@ final class StandaloneSchema
foreach (['import-legal' => ['import-tariffs'], 'import-bank-support' => ['import-dossier'],
'import-readiness' => ['import-dossier'], 'general-ledger' => ['supplier-payables'],
'supplier-settlements' => ['supplier-payables'], 'general-ledger-cycle' => ['general-ledger', 'supplier-settlements'],
'finance-configuration' => ['supplier-payables', 'general-ledger']] as $feature => $dependencies) {
'finance-configuration' => ['supplier-payables', 'general-ledger'],
'standalone-sales' => ['general-ledger-cycle', 'finance-configuration']] as $feature => $dependencies) {
foreach ($dependencies as $dependency) {
if (($features[$feature] ?? false) === true && ($features[$dependency] ?? false) !== true) {
throw new LogicException('COMPRAS_RUNTIME_FEATURE_DEPENDENCY:'.$feature.':'.$dependency);
@@ -28,6 +29,16 @@ final class StandaloneSchema
continue;
}
$required = match ($feature) {
'standalone-sales' => ['business_clients' => ['id', 'tenant_id', 'version'],
'cr_series' => ['id', 'tenant_id', 'company_id', 'unit_id', 'series_key'],
'cr_invoice_proposals' => ['id', 'revision', 'snapshot'], 'cr_invoice_reviews' => ['id', 'proposal_id', 'decision'],
'cr_invoices' => ['id', 'client_id', 'reference', 'total_minor', 'snapshot'],
'cr_receipt_proposals' => ['id', 'client_id', 'amount_minor'], 'cr_receipt_decisions' => ['id', 'proposal_id', 'decision'],
'cr_allocation_proposals' => ['id', 'invoice_id', 'receipt_id', 'amount_minor'], 'cr_allocation_decisions' => ['id', 'proposal_id', 'decision'],
'cr_reversal_proposals' => ['id', 'allocation_id'], 'cr_reversal_decisions' => ['id', 'proposal_id', 'decision'],
'cr_commands' => ['id', 'operation_key', 'request_hash'], 'cr_events' => ['id', 'kind', 'entity_id'],
'gl_configured_sales' => ['contract', 'original_validator_sha256'], 'gl_rules' => ['tax_account_id'],
'customer_deliveries' => ['id', 'tenant_id', 'invoice_id', 'invoice_line_no', 'stock_operation_id', 'quantity_milli']],
'capital-register' => ['equipment' => ['id', 'tenant_id', 'department_id']],
'private-audit' => ['private_audit_exports' => ['id', 'tenant_id']],
'conflict-releases' => ['conflict_releases' => ['id', 'tenant_id']],
+10 -4
View File
@@ -27,7 +27,7 @@ class StockWorkflow
}
/** @param array{kind: string, reference: string, idempotency_key: string, responsible_id: int, warehouse_id: int, stock_item_id: int, destination_warehouse_id?: int, quantity: string, reason: string, destination?: string, count_id?: int, ledger_version?: int, equipment_id?: int,lot_counts?:list<array<string,mixed>>,lot_version?:string} $data */
public function record(User $actor, array $data): StockOperation
public function record(User $actor, array $data, ?SalesStockSource $sale = null): StockOperation
{
if (! in_array($data['kind'], ['issue', 'transfer', 'count', 'adjustment'], true)) {
throw ValidationException::withMessages(['kind' => 'Esta operação exige o seu próprio percurso de preparação e aprovação.']);
@@ -35,11 +35,17 @@ class StockWorkflow
$roles = $data['kind'] === 'adjustment' ? [PurchasingRole::Warehouse, 'inventory_adjust_review'] : [PurchasingRole::Warehouse];
abort_unless($actor->tenant_id !== null && $actor->hasFunctions($roles) && auth()->id() === $actor->id, 403);
return DB::transaction(function () use ($actor, $data) {
return DB::transaction(function () use ($actor, $data, $sale) {
// Same first lock as receipts: includes empty balances and concurrent receipts.
app(ConflictGuard::class)->lockCompany($actor);
$actor = app(CurrentActor::class)->lock($actor);
abort_unless($actor->hasFunctions($data['kind'] === 'adjustment' ? [PurchasingRole::Warehouse, 'inventory_adjust_review'] : [PurchasingRole::Warehouse]), 403);
if ($sale !== null) {
$sale->verify($actor);
abort_unless($data['kind'] === 'issue' && $data['stock_item_id'] === $sale->snapshot['stock_item_id']
&& ReceiptWorkflow::milli($data['quantity']) === $sale->snapshot['quantity_milli'], 409);
$data['sales_invoice'] = $sale->snapshot;
}
$hash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR));
$existing = StockOperation::query()->where('idempotency_key', $data['idempotency_key'])->first();
if ($existing) {
@@ -57,7 +63,7 @@ class StockWorkflow
$item = StockItem::query()->findOrFail($data['stock_item_id']);
$equipment = $data['kind'] === 'issue' && isset($data['equipment_id']) ? Equipment::query()->findOrFail($data['equipment_id']) : null;
$part = $data['kind'] === 'issue' ? SparePart::query()->where('stock_item_id', $item->id)->first() : null;
if ($part) {
if ($part && $sale === null) {
if (! $equipment) {
throw ValidationException::withMessages(['equipment_id' => 'Seleccione o equipamento de destino associado à peça.']);
}
@@ -125,7 +131,7 @@ class StockWorkflow
'equipment_id' => $equipment?->id, 'spare_part_id' => $part?->id,
'payload_hash' => $hash, 'destination' => $data['destination'] ?? null, 'reason' => $data['reason'],
'quantity_milli' => $quantity, 'theoretical_milli' => $balance['quantity'], 'ledger_version' => $balance['version'], 'recorded_at' => now(),
'snapshot' => [...$lotSnapshot, 'actor' => $actor->only(['id', 'name']), 'responsible' => $responsible->only(['id', 'name']), 'stock_item' => $item->only(['id', 'code', 'name', 'unit']), 'warehouse' => $warehouse->only(['id', 'code', 'name']), 'destination_warehouse' => $destination?->only(['id', 'code', 'name']), 'equipment' => $equipment?->toArray(), 'spare_part' => $part?->toArray(), 'difference_milli' => $quantity - $balance['quantity'], 'budget_checked' => false, 'development_only' => app(StandaloneRuntime::class)->syntheticOnly()],
'snapshot' => [...$lotSnapshot, ...($sale === null ? [] : ['sales_invoice' => $sale->snapshot]), 'actor' => $actor->only(['id', 'name']), 'responsible' => $responsible->only(['id', 'name']), 'stock_item' => $item->only(['id', 'code', 'name', 'unit']), 'warehouse' => $warehouse->only(['id', 'code', 'name']), 'destination_warehouse' => $destination?->only(['id', 'code', 'name']), 'equipment' => $equipment?->toArray(), 'spare_part' => $part?->toArray(), 'difference_milli' => $quantity - $balance['quantity'], 'budget_checked' => false, 'development_only' => app(StandaloneRuntime::class)->syntheticOnly()],
]);
if ($adjustment !== null) {
foreach ([['decrease_milli', -1, 'adjustment_out'], ['increase_milli', 1, 'adjustment_in']] as [$key, $sign, $type]) {
+43
View File
@@ -0,0 +1,43 @@
<?php
namespace App\Services;
use App\Models\PeopleProcess;
use App\Models\Tenant;
use App\Models\User;
/** Client identity and the provider's Direction authority in the existing hiring lifecycle. */
final class ThirdPartyHiring
{
public function creationContext(User $actor): string
{
$contexts = app(WorkContext::class);
$key = $contexts->enforced($actor) && app()->bound('request') && request()->hasSession()
? $contexts->active(request()) : 'people.internal';
abort_unless(in_array($key, ['people.internal', 'people.third_party'], true) && WorkContext::operational($key), 403);
return $key;
}
public function isClientProcess(PeopleProcess $record): bool
{
return $record->getAttribute('work_context_key') === 'people.third_party';
}
public function direction(User $actor): bool
{
// The existing separately assigned Direction authority never follows from Admin.
return in_array('people_contract_formalize', app(OrganizationAccess::class)->permissions($actor), true)
&& ! app(OrganizationAccess::class)->maintenanceOnly($actor);
}
/** @return array<string,mixed> */
public function clientRules(User $actor, int $client, int $version): array
{
$snapshot = app(BusinessClients::class)->snapshot($actor, $client, $version);
$provider = Tenant::query()->findOrFail($actor->tenant_id);
return ['client' => $snapshot, 'provider' => ['tenant_id' => $actor->tenant_id, 'name' => $provider->name],
'decision_authority' => 'provider_direction'];
}
}
+34 -2
View File
@@ -17,6 +17,18 @@ class WorkContext
'people.third_party' => ['area' => 'people', 'areaLabel' => 'Pessoas e contratações', 'label' => 'Contratações para terceiros', 'operational' => false],
];
public static function operational(string $key): bool
{
if ($key === 'procurement.sales') {
return app(CustomerSales::class)->ready();
}
if ($key === 'people.third_party') {
return config('third_party.people_enabled') === true && Schema::hasTable('business_clients');
}
return self::OPTIONS[$key]['operational'] ?? false;
}
/** @return list<string> */
public function purchased(User $user): array
{
@@ -147,14 +159,20 @@ class WorkContext
if ($area === null) {
$sharedPaths[] = $path;
}
if ($area === null || ($active !== null && self::OPTIONS[$active]['operational'] && self::OPTIONS[$active]['area'] === $area)) {
if ($area === null || ($active !== null && self::operational($active) && self::OPTIONS[$active]['area'] === $area && self::allowsPath($active, $path))) {
$paths[] = $path;
}
}
}
$options = self::OPTIONS;
foreach ($options as $key => &$option) {
$option['operational'] = self::operational($key);
}
unset($option);
return ['enforced' => $enabled, 'active' => $active, 'paths' => $paths, 'sharedPaths' => $sharedPaths, 'permissions' => $permissions,
'options' => self::OPTIONS, 'available' => $enabled ? $this->available($user) : [],
'options' => $options, 'available' => $enabled ? $this->available($user) : [],
'purchased' => $user instanceof User ? $this->purchased($user) : []];
}
@@ -167,4 +185,18 @@ class WorkContext
return $path === '/pessoas' || str_starts_with($path, '/pessoas/') ? 'people' : 'procurement';
}
public static function allowsPath(string $key, string $path): bool
{
$path = '/'.ltrim(explode('?', $path)[0], '/');
if (self::area($path) === null) {
return true;
}
$salesPath = $path === '/vendas' || str_starts_with($path, '/vendas/');
if ($key === 'procurement.sales') {
return $salesPath || $path === '/general-ledger' || str_starts_with($path, '/general-ledger/');
}
return ! $salesPath;
}
}