@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\SupplierBankDetail;
|
||||
use App\Models\SupplierBankReview;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use App\Services\SupplierBankWorkflow;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Inertia;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class SupplierBankController extends Controller
|
||||
{
|
||||
public function show(Request $request, Supplier $supplier, SupplierBankWorkflow $workflow): Response
|
||||
{
|
||||
abort_unless(in_array($request->user()->purchasing_role, [PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance]), 403);
|
||||
$details = SupplierBankDetail::query()->where('supplier_id', $supplier->id)->latest('revision')->get();
|
||||
$current = $details->first();
|
||||
$canRead = in_array($request->user()->purchasing_role, [PurchasingRole::Procurement, PurchasingRole::Finance]);
|
||||
$data = null;
|
||||
if ($current && $canRead) {
|
||||
app(RequisitionWorkflow::class)->audit($request->user(), 'supplier.bank_viewed', null, null, ['supplier_id' => $supplier->id, 'bank_detail_id' => $current->id]);
|
||||
$data = [...$current->toArray(), ...$current->only(['account_identifier', 'beneficiary', 'evidence_reference', 'reason'])];
|
||||
}
|
||||
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('suppliers/bank', ['supplier' => $supplier->only(['id', 'name']), 'current' => $data, 'currentId' => $current->id ?? 0, 'state' => $workflow->state($supplier), 'history' => $details->map(fn ($detail) => $detail->only(['id', 'revision', 'created_by', 'created_at'])), 'reviews' => SupplierBankReview::query()->whereIn('supplier_bank_detail_id', $details->pluck('id'))->orderBy('id')->get(), 'canPropose' => $request->user()->purchasing_role === PurchasingRole::Procurement, 'canReview' => $current && $request->user()->purchasing_role === PurchasingRole::Finance && $current->created_by !== $request->user()->id && ! SupplierBankReview::query()->where('supplier_bank_detail_id', $current->id)->where('reviewed_by', $request->user()->id)->exists()])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function store(Request $request, Supplier $supplier, SupplierBankWorkflow $workflow): RedirectResponse
|
||||
{
|
||||
$request->merge(['country' => Str::upper(trim($request->string('country')->toString())), 'currency' => Str::upper(trim($request->string('currency')->toString())), 'account_identifier' => Str::upper(preg_replace('/\s+/', '', $request->string('account_identifier')->toString()) ?? '')]);
|
||||
$data = $request->validate(['previous_id' => 'required|integer|min:0', 'bank_name' => 'required|string|max:200', 'country' => ['required', 'regex:/^[A-Z]{2}$/'], 'currency' => ['required', 'regex:/^[A-Z]{3}$/'], 'beneficiary' => 'required|string|max:200', 'account_identifier' => ['required', 'regex:/^[A-Z0-9.\/-]{4,100}$/'], 'evidence_reference' => 'required|string|max:1000', 'reason' => 'required|string|max:2000']);
|
||||
$workflow->propose($request->user(), $supplier, $data);
|
||||
|
||||
return back();
|
||||
}
|
||||
|
||||
public function review(Request $request, Supplier $supplier, SupplierBankDetail $detail, SupplierBankWorkflow $workflow): RedirectResponse
|
||||
{
|
||||
abort_unless($detail->supplier_id === $supplier->id, 404);
|
||||
$data = $request->validate(['decision' => 'required|in:approved,rejected', 'reason' => 'required|string|max:2000', 'independently_verified' => 'accepted']);
|
||||
$workflow->review($request->user(), $detail, $data['decision'], $data['reason']);
|
||||
|
||||
return back();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\AppendOnlyInventoryRecord;
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/** @property int $id
|
||||
* @property int $tenant_id
|
||||
* @property int $supplier_id
|
||||
* @property int $created_by
|
||||
* @property int $revision
|
||||
* @property string $account_identifier
|
||||
* @property string $beneficiary
|
||||
*/
|
||||
class SupplierBankDetail extends Model
|
||||
{
|
||||
use AppendOnlyInventoryRecord, BelongsToTenant;
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
protected $guarded = ['id'];
|
||||
|
||||
protected $hidden = ['account_identifier', 'beneficiary', 'evidence_reference', 'reason'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['account_identifier' => 'encrypted', 'beneficiary' => 'encrypted', 'evidence_reference' => 'encrypted', 'reason' => 'encrypted'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\AppendOnlyInventoryRecord;
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class SupplierBankReview extends Model
|
||||
{
|
||||
use AppendOnlyInventoryRecord, BelongsToTenant;
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
protected $guarded = ['id'];
|
||||
|
||||
protected $hidden = ['reason'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['reason' => 'encrypted'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\SupplierBankDetail;
|
||||
use App\Models\SupplierBankReview;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class SupplierBankWorkflow
|
||||
{
|
||||
private function actor(User $user, Supplier $supplier): void
|
||||
{
|
||||
abort_unless(auth()->id() === $user->id && $user->tenant_id !== null && $supplier->tenant_id === $user->tenant_id, 403);
|
||||
if (app(ConflictGuard::class)->hasConflict($user->id, $supplier->id, null)) {
|
||||
throw ValidationException::withMessages(['bank' => 'Conflito de interesses com este fornecedor.']);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data */
|
||||
public function propose(User $user, Supplier $supplier, array $data): SupplierBankDetail
|
||||
{
|
||||
$this->actor($user, $supplier);
|
||||
abort_unless($user->purchasing_role === PurchasingRole::Procurement, 403);
|
||||
|
||||
return DB::transaction(function () use ($user, $supplier, $data) {
|
||||
app(ConflictGuard::class)->lockCompany($user);
|
||||
$supplier = Supplier::query()->lockForUpdate()->findOrFail($supplier->id);
|
||||
$this->actor($user, $supplier);
|
||||
$latest = SupplierBankDetail::query()->where('supplier_id', $supplier->id)->latest('revision')->first();
|
||||
if ((int) $data['previous_id'] !== ($latest->id ?? 0)) {
|
||||
throw ValidationException::withMessages(['previous_id' => 'Dados bancários alterados. Reabra a ficha antes de propor outra versão.']);
|
||||
}
|
||||
$detail = SupplierBankDetail::query()->create(['tenant_id' => $user->tenant_id, 'supplier_id' => $supplier->id, 'created_by' => $user->id, 'revision' => ($latest->revision ?? 0) + 1, ...array_intersect_key($data, array_flip(['bank_name', 'country', 'currency', 'beneficiary', 'account_identifier', 'evidence_reference', 'reason'])), 'created_at' => now()]);
|
||||
app(RequisitionWorkflow::class)->audit($user, 'supplier.bank_proposed', null, null, ['supplier_id' => $supplier->id, 'bank_detail_id' => $detail->id, 'revision' => $detail->revision]);
|
||||
|
||||
return $detail;
|
||||
});
|
||||
}
|
||||
|
||||
public function review(User $user, SupplierBankDetail $detail, string $decision, string $reason): void
|
||||
{
|
||||
abort_unless($user->purchasing_role === PurchasingRole::Finance && $detail->tenant_id === $user->tenant_id && $detail->created_by !== $user->id, 403);
|
||||
if (! in_array($decision, ['approved', 'rejected']) || trim($reason) === '') {
|
||||
throw ValidationException::withMessages(['bank' => 'Decisão e fundamento obrigatórios.']);
|
||||
}
|
||||
DB::transaction(function () use ($user, $detail, $decision, $reason) {
|
||||
app(ConflictGuard::class)->lockCompany($user);
|
||||
$supplier = Supplier::query()->lockForUpdate()->findOrFail($detail->supplier_id);
|
||||
$this->actor($user, $supplier);
|
||||
$latest = SupplierBankDetail::query()->where('supplier_id', $supplier->id)->latest('revision')->firstOrFail();
|
||||
if ($latest->id !== $detail->id) {
|
||||
throw ValidationException::withMessages(['bank' => 'Versão substituída. Reveja os dados bancários actuais.']);
|
||||
}
|
||||
$existing = SupplierBankReview::query()->where('supplier_bank_detail_id', $detail->id)->where('reviewed_by', $user->id)->first();
|
||||
if ($existing) {
|
||||
if ($existing->decision !== $decision || $existing->reason !== $reason) {
|
||||
throw ValidationException::withMessages(['bank' => 'A decisão anterior é imutável. Proponha nova versão para corrigir dados.']);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
if (! $supplier->eligible() || SupplierBankReview::query()->where('supplier_bank_detail_id', $detail->id)->where('decision', 'rejected')->exists() || SupplierBankReview::query()->where('supplier_bank_detail_id', $detail->id)->count() >= 2) {
|
||||
throw ValidationException::withMessages(['bank' => 'Fornecedor não elegível ou versão já decidida.']);
|
||||
}
|
||||
SupplierBankReview::query()->create(['tenant_id' => $user->tenant_id, 'supplier_bank_detail_id' => $detail->id, 'reviewed_by' => $user->id, 'decision' => $decision, 'reason' => $reason, 'created_at' => now()]);
|
||||
app(RequisitionWorkflow::class)->audit($user, 'supplier.bank_'.$decision, null, null, ['supplier_id' => $supplier->id, 'bank_detail_id' => $detail->id]);
|
||||
});
|
||||
}
|
||||
|
||||
/** Re-evaluate inside the payment transaction in the future; UI readiness is not authorisation. */
|
||||
public function state(Supplier $supplier): string
|
||||
{
|
||||
$detail = SupplierBankDetail::query()->where('supplier_id', $supplier->id)->latest('revision')->first();
|
||||
if (! $detail) {
|
||||
return 'missing';
|
||||
}
|
||||
$reviews = SupplierBankReview::query()->where('supplier_bank_detail_id', $detail->id)->get();
|
||||
if ($reviews->contains('decision', 'rejected')) {
|
||||
return 'rejected';
|
||||
}
|
||||
if ($reviews->count() < 2) {
|
||||
return 'pending';
|
||||
}
|
||||
if (! $supplier->eligible() || app(ConflictGuard::class)->hasConflict($detail->created_by, $supplier->id, null)) {
|
||||
return 'blocked';
|
||||
}
|
||||
foreach ($reviews as $review) {
|
||||
$user = User::query()->where('tenant_id', $supplier->tenant_id)->find($review->reviewed_by);
|
||||
if (! $user || $user->purchasing_role !== PurchasingRole::Finance || $user->id === $detail->created_by || app(ConflictGuard::class)->hasConflict($user->id, $supplier->id, null)) {
|
||||
return 'blocked';
|
||||
}
|
||||
}
|
||||
|
||||
return 'approved';
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@ return Application::configure(basePath: dirname(__DIR__))
|
||||
]);
|
||||
})
|
||||
->withExceptions(function (Exceptions $exceptions): void {
|
||||
$exceptions->dontFlash(['account_identifier', 'beneficiary', 'evidence_reference', 'reason']);
|
||||
$exceptions->shouldRenderJsonWhen(
|
||||
fn (Request $request) => $request->is('api/*') || $request->expectsJson(),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('supplier_bank_details', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
|
||||
$table->foreignId('supplier_id')->constrained()->restrictOnDelete();
|
||||
$table->foreignId('created_by')->constrained('users')->restrictOnDelete();
|
||||
$table->unsignedInteger('revision');
|
||||
$table->string('bank_name', 200);
|
||||
$table->string('country', 2);
|
||||
$table->string('currency', 3);
|
||||
$table->text('beneficiary');
|
||||
$table->text('account_identifier');
|
||||
$table->text('evidence_reference');
|
||||
$table->text('reason');
|
||||
$table->timestamp('created_at');
|
||||
$table->unique(['supplier_id', 'revision']);
|
||||
});
|
||||
Schema::create('supplier_bank_reviews', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
|
||||
$table->foreignId('supplier_bank_detail_id')->constrained()->restrictOnDelete();
|
||||
$table->foreignId('reviewed_by')->constrained('users')->restrictOnDelete();
|
||||
$table->string('decision');
|
||||
$table->text('reason');
|
||||
$table->timestamp('created_at');
|
||||
$table->unique(['supplier_bank_detail_id', 'reviewed_by']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
throw new LogicException('Preservar versões bancárias e validações.');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"tested_at_utc": "2026-10-28T12:32:47+00:00",
|
||||
"separate_database": true,
|
||||
"transport": "Independent PHP service transactions and PostgreSQL connections",
|
||||
"scenarios": [
|
||||
{
|
||||
"name": "distinct_approvals",
|
||||
"passed": true,
|
||||
"overlapping_lock_waits": 2,
|
||||
"state": "approved",
|
||||
"review_count": 2
|
||||
},
|
||||
{
|
||||
"name": "same_approval",
|
||||
"passed": true,
|
||||
"overlapping_lock_waits": 2,
|
||||
"state": "pending",
|
||||
"review_count": 1
|
||||
},
|
||||
{
|
||||
"name": "competing_revisions",
|
||||
"passed": true,
|
||||
"overlapping_lock_waits": 2,
|
||||
"state": "pending",
|
||||
"review_count": 0
|
||||
}
|
||||
],
|
||||
"passed": true,
|
||||
"test_database_dropped": true
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"verified_at_utc": "2026-10-28T12:33:53+00:00",
|
||||
"migration": "2026_10_28_000011_create_supplier_bank_details",
|
||||
"batch": 12,
|
||||
"backup_created": true,
|
||||
"backup_bytes": 230372,
|
||||
"restore_verified": true,
|
||||
"restored_tables": 42,
|
||||
"restore_database_dropped": true,
|
||||
"business_records_unchanged": true,
|
||||
"existing_constraints_preserved": true,
|
||||
"env_unchanged": true,
|
||||
"bank_details_count": 0,
|
||||
"bank_reviews_count": 0,
|
||||
"operational_validation": false
|
||||
}
|
||||
@@ -10,5 +10,6 @@ export const previewPaths: Record<string, string> = {
|
||||
operations: '/consulta/operacoes-stock',
|
||||
equipment: '/consulta/equipamentos',
|
||||
invoices: '/consulta/facturas',
|
||||
bank: '/consulta/dados-bancarios',
|
||||
appearance: '/consulta/aparencia',
|
||||
};
|
||||
|
||||
@@ -119,6 +119,7 @@ const navigation = [
|
||||
{ id: 'operations', title: 'Saídas e inventários', icon: Warehouse },
|
||||
{ id: 'equipment', title: 'Equipamentos e peças', icon: Warehouse },
|
||||
{ id: 'invoices', title: 'Facturas e conferência', icon: FileText },
|
||||
{ id: 'bank', title: 'Dados bancários', icon: ShieldCheck },
|
||||
{ id: 'appearance', title: 'Cores e componentes', icon: Palette },
|
||||
];
|
||||
type Detail = { title: string; subtitle: string; rows: [string, string][] };
|
||||
@@ -127,7 +128,7 @@ const navigationGroups = [
|
||||
{ title: 'Compras', ids: ['requests', 'suppliers', 'quotes', 'orders'] },
|
||||
{ title: 'Armazém', ids: ['receipts', 'stock', 'operations', 'equipment'] },
|
||||
{ title: 'Controlo', ids: ['conflicts'] },
|
||||
{ title: 'Finanças', ids: ['invoices'] },
|
||||
{ title: 'Finanças', ids: ['invoices', 'bank'] },
|
||||
{ title: 'Apresentação', ids: ['appearance'] },
|
||||
];
|
||||
export default function Preview({
|
||||
@@ -663,6 +664,39 @@ export default function Preview({
|
||||
)}
|
||||
{screen === 'operations' && <OperationsDemo />}
|
||||
{screen === 'equipment' && <EquipmentDemo />}
|
||||
{screen === 'bank' && (
|
||||
<Panel
|
||||
title="Dupla validação bancária · exemplo fictício"
|
||||
description="Sem dados de contas, consultas ou gravações de negócio."
|
||||
>
|
||||
<div className="space-y-3 text-sm">
|
||||
<p>
|
||||
Procurement propõe uma versão com
|
||||
evidência. Finanças A confere e aprova;
|
||||
Finanças B confere de forma
|
||||
independente.
|
||||
</p>
|
||||
<p>
|
||||
Uma aprovação: pendente. Duas pessoas
|
||||
distintas: duplamente validado. Repetir
|
||||
a decisão da mesma pessoa não conta duas
|
||||
vezes.
|
||||
</p>
|
||||
<p>
|
||||
Nova versão: disponibilidade anterior
|
||||
substituída e duas novas validações
|
||||
obrigatórias. Rejeição, conflito ou
|
||||
perda de elegibilidade bloqueiam o
|
||||
estado.
|
||||
</p>
|
||||
<p>
|
||||
Cada empresa mantém os seus fornecedores
|
||||
e dados. Não autoriza transferências nem
|
||||
confirma titularidade junto do banco.
|
||||
</p>
|
||||
</div>
|
||||
</Panel>
|
||||
)}
|
||||
{screen === 'invoices' && (
|
||||
<Panel
|
||||
title="Factura parcial · exemplo fictício"
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import {
|
||||
FormErrors,
|
||||
Panel,
|
||||
PageTitle,
|
||||
controlClass,
|
||||
} from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
|
||||
type Detail = {
|
||||
id: number;
|
||||
revision: number;
|
||||
bank_name: string;
|
||||
country: string;
|
||||
currency: string;
|
||||
beneficiary: string;
|
||||
account_identifier: string;
|
||||
evidence_reference: string;
|
||||
reason: string;
|
||||
};
|
||||
type Props = {
|
||||
supplier: { id: number; name: string };
|
||||
current: Detail | null;
|
||||
currentId: number;
|
||||
state: string;
|
||||
history: {
|
||||
id: number;
|
||||
revision: number;
|
||||
created_by: number;
|
||||
created_at: string;
|
||||
}[];
|
||||
reviews: {
|
||||
id: number;
|
||||
supplier_bank_detail_id: number;
|
||||
reviewed_by: number;
|
||||
decision: string;
|
||||
}[];
|
||||
canPropose: boolean;
|
||||
canReview: boolean;
|
||||
};
|
||||
export default function Bank({
|
||||
supplier,
|
||||
current,
|
||||
currentId,
|
||||
state,
|
||||
history,
|
||||
reviews,
|
||||
canPropose,
|
||||
canReview,
|
||||
}: Props) {
|
||||
const form = useForm({
|
||||
previous_id: currentId,
|
||||
bank_name: '',
|
||||
country: '',
|
||||
currency: '',
|
||||
beneficiary: '',
|
||||
account_identifier: '',
|
||||
evidence_reference: '',
|
||||
reason: '',
|
||||
});
|
||||
const review = useForm({
|
||||
decision: 'approved',
|
||||
reason: '',
|
||||
independently_verified: false,
|
||||
});
|
||||
const labels = {
|
||||
bank_name: 'Banco',
|
||||
country: 'Código do país (2 letras)',
|
||||
currency: 'Moeda da conta (3 letras)',
|
||||
beneficiary: 'Titular / beneficiário',
|
||||
account_identifier: 'Identificador da conta fornecido pelo banco',
|
||||
evidence_reference:
|
||||
'Referência da evidência e confirmação independente',
|
||||
reason: 'Fundamento da alteração',
|
||||
};
|
||||
const states: Record<string, string> = {
|
||||
missing: 'Sem dados',
|
||||
pending: 'Pendente de duas validações',
|
||||
approved: 'Duplamente validado',
|
||||
rejected: 'Rejeitado',
|
||||
blocked: 'Bloqueado por elegibilidade ou conflito',
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<Head title="Dados bancários" />
|
||||
<div className="mx-auto grid w-full max-w-5xl gap-6 p-6">
|
||||
<PageTitle
|
||||
eyebrow="SGC · Fornecedores"
|
||||
title={`Dados bancários · ${supplier.name}`}
|
||||
description="Duas pessoas distintas de Finanças validam cada versão. Não autoriza transferências ou pagamentos."
|
||||
/>
|
||||
<Link href={`/fornecedores/${supplier.id}`}>
|
||||
← Ficha do fornecedor
|
||||
</Link>
|
||||
<Panel
|
||||
title={states[state] ?? state}
|
||||
description="A versão mais recente substitui a anterior para efeitos de disponibilidade. A aprovação não confirma a titularidade junto do banco nem valida formatos bancários nacionais."
|
||||
>
|
||||
{current && (
|
||||
<dl className="grid gap-4 text-sm sm:grid-cols-2">
|
||||
{Object.entries(labels).map(([key, label]) => (
|
||||
<div key={key}>
|
||||
<dt className="text-muted-foreground">
|
||||
{label}
|
||||
</dt>
|
||||
<dd className="break-all whitespace-pre-wrap">
|
||||
{current[key as keyof typeof labels]}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
)}
|
||||
{!current && (
|
||||
<p className="text-sm">
|
||||
Os identificadores bancários são apresentados apenas
|
||||
a Procurement e Finanças. Administração consulta o
|
||||
estado e o histórico.
|
||||
</p>
|
||||
)}
|
||||
</Panel>
|
||||
{canReview && current && state === 'pending' && (
|
||||
<Panel title="Conferência independente">
|
||||
<form
|
||||
className="grid gap-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
review.post(
|
||||
`/fornecedores/${supplier.id}/dados-bancarios/${current.id}/validar`,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={review.errors} />
|
||||
<label>
|
||||
Decisão
|
||||
<select
|
||||
className={controlClass}
|
||||
value={review.data.decision}
|
||||
onChange={(e) =>
|
||||
review.setData(
|
||||
'decision',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="approved">Aprovar</option>
|
||||
<option value="rejected">Rejeitar</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Fundamento da conferência
|
||||
<textarea
|
||||
required
|
||||
className="w-full rounded border p-3"
|
||||
value={review.data.reason}
|
||||
onChange={(e) =>
|
||||
review.setData('reason', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="flex gap-3">
|
||||
<input
|
||||
required
|
||||
type="checkbox"
|
||||
checked={review.data.independently_verified}
|
||||
onChange={(e) =>
|
||||
review.setData(
|
||||
'independently_verified',
|
||||
e.target.checked,
|
||||
)
|
||||
}
|
||||
/>
|
||||
Confirmo que conferi os dados e a evidência de
|
||||
forma independente.
|
||||
</label>
|
||||
<Button disabled={review.processing}>
|
||||
Guardar decisão imutável
|
||||
</Button>
|
||||
</form>
|
||||
</Panel>
|
||||
)}
|
||||
{canPropose && (
|
||||
<Panel
|
||||
title="Propor nova versão"
|
||||
description="Preencha integralmente os dados confirmados. A nova versão exige duas validações novas; a versão anterior permanece no histórico."
|
||||
>
|
||||
<form
|
||||
className="grid gap-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post(
|
||||
`/fornecedores/${supplier.id}/dados-bancarios`,
|
||||
{
|
||||
onSuccess: (page) => {
|
||||
form.reset();
|
||||
form.setData(
|
||||
'previous_id',
|
||||
Number(page.props.currentId),
|
||||
);
|
||||
},
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
{Object.entries(labels).map(([key, label]) => (
|
||||
<label key={key}>
|
||||
{label}
|
||||
<Input
|
||||
required
|
||||
autoComplete="off"
|
||||
value={
|
||||
form.data[
|
||||
key as keyof typeof labels
|
||||
]
|
||||
}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
key as keyof typeof labels,
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
<Button disabled={form.processing}>
|
||||
Enviar para dupla validação
|
||||
</Button>
|
||||
</form>
|
||||
</Panel>
|
||||
)}
|
||||
<Panel title="Histórico de versões e decisões">
|
||||
<div className="space-y-4 text-sm">
|
||||
{history.map((h) => (
|
||||
<article key={h.id} className="rounded border p-3">
|
||||
<p>
|
||||
Versão {h.revision} · Autor #{h.created_by}{' '}
|
||||
· {h.created_at}
|
||||
</p>
|
||||
{reviews
|
||||
.filter(
|
||||
(r) =>
|
||||
r.supplier_bank_detail_id === h.id,
|
||||
)
|
||||
.map((r) => (
|
||||
<p key={r.id}>
|
||||
{r.decision === 'approved'
|
||||
? 'Aprovado'
|
||||
: 'Rejeitado'}{' '}
|
||||
· Finanças #{r.reviewed_by}
|
||||
</p>
|
||||
))}
|
||||
</article>
|
||||
))}
|
||||
{history.length === 0 && (
|
||||
<p>Sem versões bancárias registadas.</p>
|
||||
)}
|
||||
</div>
|
||||
</Panel>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -69,6 +69,14 @@ export default function SupplierShow({
|
||||
}
|
||||
/>
|
||||
<Panel title="Dados do fornecedor">
|
||||
{canDocuments && (
|
||||
<Link
|
||||
className="mb-4 inline-block font-semibold text-teal-700"
|
||||
href={`/fornecedores/${supplier.id}/dados-bancarios`}
|
||||
>
|
||||
Dados bancários e dupla validação →
|
||||
</Link>
|
||||
)}
|
||||
<dl className="grid gap-5 text-sm md:grid-cols-2">
|
||||
{Object.entries(supplierFields).map(([key, label]) => (
|
||||
<div key={key}>
|
||||
|
||||
+2
-1
@@ -7,7 +7,7 @@ use Inertia\Inertia;
|
||||
// Public visual consultation. No business records or authenticated identities.
|
||||
Route::get('consulta', function (Request $request) {
|
||||
$screen = $request->query('ecra', 'overview');
|
||||
$allowed = ['overview', 'requests', 'suppliers', 'quotes', 'conflicts', 'orders', 'receipts', 'stock', 'operations', 'equipment', 'invoices', 'appearance'];
|
||||
$allowed = ['overview', 'requests', 'suppliers', 'quotes', 'conflicts', 'orders', 'receipts', 'stock', 'operations', 'equipment', 'invoices', 'bank', 'appearance'];
|
||||
|
||||
return Inertia::render('preview/index', [
|
||||
'auth' => ['user' => null],
|
||||
@@ -20,6 +20,7 @@ Route::get('consulta/{screen}', function (string $screen) {
|
||||
$screens['operacoes-stock'] = 'operations';
|
||||
$screens['equipamentos'] = 'equipment';
|
||||
$screens['facturas'] = 'invoices';
|
||||
$screens['dados-bancarios'] = 'bank';
|
||||
abort_unless(isset($screens[$screen]), 404);
|
||||
|
||||
return Inertia::render('preview/index', ['auth' => ['user' => null], 'initialScreen' => $screens[$screen]]);
|
||||
|
||||
@@ -11,6 +11,7 @@ use App\Http\Controllers\QuotationController;
|
||||
use App\Http\Controllers\RequisitionController;
|
||||
use App\Http\Controllers\StockController;
|
||||
use App\Http\Controllers\StockOperationController;
|
||||
use App\Http\Controllers\SupplierBankController;
|
||||
use App\Http\Controllers\SupplierController;
|
||||
use App\Http\Controllers\SupplierDocumentController;
|
||||
use App\Http\Middleware\EnsureCompanyIsConfigured;
|
||||
@@ -25,6 +26,9 @@ Route::middleware(['auth', 'verified'])->group(function () {
|
||||
Route::post('empresa/iniciar', [CompanyController::class, 'store'])->name('company.store');
|
||||
|
||||
Route::middleware(EnsureCompanyIsConfigured::class)->group(function () {
|
||||
Route::get('fornecedores/{supplier}/dados-bancarios', [SupplierBankController::class, 'show'])->name('suppliers.bank');
|
||||
Route::post('fornecedores/{supplier}/dados-bancarios', [SupplierBankController::class, 'store'])->name('suppliers.bank.store');
|
||||
Route::post('fornecedores/{supplier}/dados-bancarios/{detail}/validar', [SupplierBankController::class, 'review'])->name('suppliers.bank.review');
|
||||
Route::get('facturas', [InvoiceController::class, 'index'])->name('invoices.index');
|
||||
Route::post('ordens/{order}/facturas', [InvoiceController::class, 'store'])->name('invoices.store');
|
||||
Route::post('facturas/{invoice}/validar', [InvoiceController::class, 'validateInvoice'])->name('invoices.validate');
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
use App\Models\Supplier;
|
||||
use App\Models\SupplierBankDetail;
|
||||
use App\Models\User;
|
||||
use App\Services\SupplierBankWorkflow;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
require __DIR__.'/../../vendor/autoload.php';
|
||||
$database = $argv[1] ?? '';
|
||||
if (! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/', $database)) {
|
||||
throw new LogicException('Base de teste inválida.');
|
||||
}
|
||||
$app = require __DIR__.'/../../bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
if (! $app->environment('testing') || DB::connection()->getDatabaseName() !== $database) {
|
||||
throw new LogicException('Worker não isolado.');
|
||||
}
|
||||
DB::select('select set_config(?, ?, false)', ['application_name', 'sgc_bank_'.$argv[4]]);
|
||||
$pid = DB::selectOne('select pg_backend_pid() as pid')->pid;
|
||||
$user = User::query()->findOrFail($argv[2]);
|
||||
auth()->guard()->setUser($user);
|
||||
$payload = json_decode(stream_get_contents(STDIN), true, 512, JSON_THROW_ON_ERROR);
|
||||
try {
|
||||
if ($payload['action'] === 'propose') {
|
||||
app(SupplierBankWorkflow::class)->propose($user, Supplier::query()->findOrFail($argv[3]), $payload['data']);
|
||||
} else {
|
||||
app(SupplierBankWorkflow::class)->review($user, SupplierBankDetail::query()->findOrFail($argv[3]), 'approved', 'Conferência isolada de teste');
|
||||
}
|
||||
$status = 200;
|
||||
} catch (ValidationException) {
|
||||
$status = 422;
|
||||
}
|
||||
echo json_encode(['status' => $status, 'backend_pid' => $pid], JSON_THROW_ON_ERROR);
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\SupplierBankDetail;
|
||||
use App\Models\SupplierBankReview;
|
||||
use App\Models\User;
|
||||
use App\Services\SupplierBankWorkflow;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
require __DIR__.'/../../vendor/autoload.php';
|
||||
foreach (['APP_ENV' => 'testing', 'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array', 'QUEUE_CONNECTION' => 'sync', 'MAIL_MAILER' => 'array'] as $key => $value) {
|
||||
putenv($key.'='.$value);
|
||||
$_ENV[$key] = $_SERVER[$key] = $value;
|
||||
}
|
||||
$app = require __DIR__.'/../../bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
require __DIR__.'/../Support/ReceiptFixture.php';
|
||||
$original = DB::connection();
|
||||
if ($original->getDriverName() !== 'pgsql') {
|
||||
throw new LogicException('Exige PostgreSQL.');
|
||||
}
|
||||
$config = $original->getConfig();
|
||||
$admin = $original->getPdo();
|
||||
$database = 'compras_receipts_test_'.bin2hex(random_bytes(6));
|
||||
$created = false;
|
||||
$processes = [];
|
||||
$report = ['tested_at_utc' => gmdate('c'), 'separate_database' => true, 'transport' => 'Independent PHP service transactions and PostgreSQL connections', 'scenarios' => []];
|
||||
try {
|
||||
$admin->exec('CREATE DATABASE "'.$database.'"');
|
||||
$created = true;
|
||||
config(['database.connections.pgsql' => [...$config, 'database' => $database, 'url' => null]]);
|
||||
DB::purge('pgsql');
|
||||
DB::setDefaultConnection('pgsql');
|
||||
Schema::clearResolvedInstance('db.schema');
|
||||
app()->forgetInstance('db.schema');
|
||||
if (DB::connection()->getDatabaseName() !== $database || Schema::getConnection()->getDatabaseName() !== $database) {
|
||||
throw new LogicException('Migração fora do isolamento recusada.');
|
||||
}
|
||||
Artisan::call('migrate', ['--database' => 'pgsql', '--force' => true]);
|
||||
$workerEnv = ['APP_ENV' => 'testing', 'DB_CONNECTION' => 'pgsql', 'DB_URL' => '', 'DB_DATABASE' => $database, 'DB_HOST' => $config['host'], 'DB_PORT' => (string) $config['port'], 'DB_USERNAME' => $config['username'], 'DB_PASSWORD' => $config['password'], 'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array'];
|
||||
foreach (['distinct_approvals', 'same_approval', 'competing_revisions'] as $scenario) {
|
||||
$f = receiptFixture();
|
||||
$supplier = Supplier::query()->findOrFail($f['order']->supplier_id);
|
||||
$author = $f['issuer'];
|
||||
auth()->guard()->setUser($author);
|
||||
$first = User::factory()->create(['tenant_id' => $author->tenant_id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$second = User::factory()->create(['tenant_id' => $author->tenant_id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$data = ['previous_id' => 0, 'bank_name' => 'Banco fictício', 'country' => 'MZ', 'currency' => 'MZN', 'beneficiary' => 'Titular fictício', 'account_identifier' => 'TEST-PG-0001', 'evidence_reference' => 'Apenas teste', 'reason' => 'Apenas teste'];
|
||||
$detail = app(SupplierBankWorkflow::class)->propose($author, $supplier, $data);
|
||||
$payload = ['action' => 'review'];
|
||||
$target = $detail->id;
|
||||
if ($scenario === 'same_approval') {
|
||||
$second = $first;
|
||||
} elseif ($scenario === 'competing_revisions') {
|
||||
$first = $second = $author;
|
||||
$target = $supplier->id;
|
||||
$payload = ['action' => 'propose', 'data' => [...$data, 'previous_id' => $detail->id]];
|
||||
}
|
||||
$connection = DB::connection();
|
||||
$connection->beginTransaction();
|
||||
$connection->table('tenants')->where('id', $author->tenant_id)->lockForUpdate()->first();
|
||||
$processes = [];
|
||||
foreach ([$first, $second] as $index => $user) {
|
||||
$process = new Process([PHP_BINARY, __DIR__.'/bank-worker.php', $database, (string) $user->id, (string) $target, $index === 0 ? 'A' : 'B'], base_path(), $workerEnv);
|
||||
$process->setInput(json_encode($payload, JSON_THROW_ON_ERROR));
|
||||
$process->setTimeout(40);
|
||||
$process->start();
|
||||
$processes[] = $process;
|
||||
}
|
||||
$statement = $admin->prepare("SELECT count(*) FROM pg_stat_activity WHERE datname = ? AND application_name IN ('sgc_bank_A','sgc_bank_B') AND wait_event_type = 'Lock'");
|
||||
$deadline = microtime(true) + 20;
|
||||
do {
|
||||
$statement->execute([$database]);
|
||||
$waits = (int) $statement->fetchColumn();
|
||||
if ($waits === 2) {
|
||||
break;
|
||||
}
|
||||
foreach ($processes as $process) {
|
||||
if (! $process->isRunning()) {
|
||||
throw new RuntimeException('Worker terminou antes do bloqueio: '.$process->getErrorOutput());
|
||||
}
|
||||
}
|
||||
usleep(20000);
|
||||
} while (microtime(true) < $deadline);
|
||||
$connection->commit();
|
||||
if ($waits !== 2) {
|
||||
throw new RuntimeException('Sem sobreposição de bloqueios.');
|
||||
}
|
||||
$results = [];
|
||||
foreach ($processes as $process) {
|
||||
$process->wait();
|
||||
if (! $process->isSuccessful()) {
|
||||
throw new RuntimeException('Falha do worker: '.$process->getErrorOutput());
|
||||
}
|
||||
$results[] = json_decode($process->getOutput(), true, 512, JSON_THROW_ON_ERROR);
|
||||
}
|
||||
$statuses = array_column($results, 'status');
|
||||
sort($statuses);
|
||||
$state = app(SupplierBankWorkflow::class)->state($supplier);
|
||||
$count = SupplierBankReview::query()->count();
|
||||
if ($statuses !== ($scenario === 'competing_revisions' ? [200, 422] : [200, 200]) || $state !== ($scenario === 'distinct_approvals' ? 'approved' : 'pending') || $count !== match ($scenario) {
|
||||
'distinct_approvals' => 2, 'same_approval' => 1, default => 0
|
||||
} || SupplierBankDetail::query()->count() !== ($scenario === 'competing_revisions' ? 2 : 1) || count(array_unique(array_column($results, 'backend_pid'))) !== 2) {
|
||||
throw new RuntimeException('Resultado concorrente inesperado.');
|
||||
}
|
||||
$report['scenarios'][] = ['name' => $scenario, 'passed' => true, 'overlapping_lock_waits' => $waits, 'state' => $state, 'review_count' => $count];
|
||||
}
|
||||
$report['passed'] = true;
|
||||
} finally {
|
||||
foreach ($processes as $process) {
|
||||
if ($process->isRunning()) {
|
||||
$process->stop();
|
||||
}
|
||||
}
|
||||
if (isset($connection) && $connection->transactionLevel() > 0) {
|
||||
$connection->rollBack();
|
||||
}
|
||||
DB::disconnect('pgsql');
|
||||
if ($created && $database !== $original->getDatabaseName() && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/', $database)) {
|
||||
$admin->exec('DROP DATABASE "'.$database.'"');
|
||||
$report['test_database_dropped'] = true;
|
||||
}
|
||||
}
|
||||
file_put_contents(base_path('docs/bancos-concorrencia-postgresql.json'), json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
|
||||
echo json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -0,0 +1,153 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\SupplierBankDetail;
|
||||
use App\Models\SupplierBankReview;
|
||||
use App\Models\User;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use App\Services\SupplierBankWorkflow;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
|
||||
beforeEach(function () {
|
||||
$this->f = receiptFixture();
|
||||
$this->supplier = Supplier::query()->findOrFail($this->f['order']->supplier_id);
|
||||
$this->buyer = $this->f['issuer'];
|
||||
$this->first = User::factory()->create(['tenant_id' => $this->supplier->tenant_id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$this->second = User::factory()->create(['tenant_id' => $this->supplier->tenant_id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$this->actingAs($this->buyer);
|
||||
$this->data = ['previous_id' => 0, 'bank_name' => 'Banco fictício', 'country' => 'MZ', 'currency' => 'MZN', 'beneficiary' => 'Beneficiário fictício de teste', 'account_identifier' => 'TEST-ACCOUNT-0001', 'evidence_reference' => 'Referência fictícia de conferência', 'reason' => 'Cadastro fictício'];
|
||||
$this->url = '/fornecedores/'.$this->supplier->id.'/dados-bancarios';
|
||||
});
|
||||
|
||||
function bankProposal(object $test): SupplierBankDetail
|
||||
{
|
||||
$test->actingAs($test->buyer);
|
||||
|
||||
return app(SupplierBankWorkflow::class)->propose($test->buyer, $test->supplier, $test->data);
|
||||
}
|
||||
|
||||
function bankApprove(object $test, User $user, SupplierBankDetail $detail, string $decision = 'approved'): void
|
||||
{
|
||||
$test->actingAs($user);
|
||||
app(SupplierBankWorkflow::class)->review($user, $detail, $decision, 'Conferência independente de teste');
|
||||
}
|
||||
|
||||
test('bank data needs two distinct independent finance reviewers', function () {
|
||||
$detail = bankProposal($this);
|
||||
bankApprove($this, $this->first, $detail);
|
||||
expect(app(SupplierBankWorkflow::class)->state($this->supplier))->toBe('pending');
|
||||
bankApprove($this, $this->first, $detail);
|
||||
expect(SupplierBankReview::query()->count())->toBe(1);
|
||||
bankApprove($this, $this->second, $detail);
|
||||
expect(app(SupplierBankWorkflow::class)->state($this->supplier))->toBe('approved');
|
||||
});
|
||||
|
||||
test('bank identifiers are encrypted hidden and absent from audit payloads', function () {
|
||||
$detail = bankProposal($this);
|
||||
expect(DB::table('supplier_bank_details')->where('id', $detail->id)->value('account_identifier'))->not->toBe($this->data['account_identifier']);
|
||||
expect($detail->refresh()->account_identifier)->toBe($this->data['account_identifier']);
|
||||
expect($detail->toArray())->not->toHaveKey('account_identifier')->not->toHaveKey('beneficiary');
|
||||
expect(json_encode(AuditLog::query()->get()->toArray()))->not->toContain($this->data['account_identifier'])->not->toContain($this->data['beneficiary']);
|
||||
});
|
||||
|
||||
test('new bank revision invalidates prior availability and refuses stale proposals and reviews', function () {
|
||||
$old = bankProposal($this);
|
||||
bankApprove($this, $this->first, $old);
|
||||
bankApprove($this, $this->second, $old);
|
||||
$this->data['previous_id'] = $old->id;
|
||||
$this->data['account_identifier'] = 'TEST-ACCOUNT-0002';
|
||||
$new = bankProposal($this);
|
||||
expect($new->revision)->toBe(2)->and(app(SupplierBankWorkflow::class)->state($this->supplier))->toBe('pending');
|
||||
expect(fn () => bankProposal($this))->toThrow(ValidationException::class);
|
||||
expect(fn () => bankApprove($this, $this->first, $old))->toThrow(ValidationException::class);
|
||||
expect(SupplierBankDetail::query()->count())->toBe(2);
|
||||
});
|
||||
|
||||
test('author cannot validate after changing to finance role', function () {
|
||||
$detail = bankProposal($this);
|
||||
$this->buyer->forceFill(['purchasing_role' => PurchasingRole::Finance])->save();
|
||||
$this->post($this->url.'/'.$detail->id.'/validar', ['decision' => 'approved', 'reason' => 'Teste', 'independently_verified' => true])->assertForbidden();
|
||||
});
|
||||
|
||||
test('rejection blocks bank readiness and cannot be erased', function () {
|
||||
$detail = bankProposal($this);
|
||||
bankApprove($this, $this->first, $detail, 'rejected');
|
||||
expect(app(SupplierBankWorkflow::class)->state($this->supplier))->toBe('rejected');
|
||||
expect(fn () => bankApprove($this, $this->second, $detail))->toThrow(ValidationException::class);
|
||||
expect(fn () => $detail->update(['bank_name' => 'Alterado']))->toThrow(LogicException::class);
|
||||
expect(fn () => SupplierBankReview::query()->firstOrFail()->delete())->toThrow(LogicException::class);
|
||||
});
|
||||
|
||||
test('bank eligibility changes with reviewer role or supplier suspension', function () {
|
||||
$detail = bankProposal($this);
|
||||
bankApprove($this, $this->first, $detail);
|
||||
bankApprove($this, $this->second, $detail);
|
||||
$this->first->forceFill(['purchasing_role' => PurchasingRole::Warehouse])->save();
|
||||
expect(app(SupplierBankWorkflow::class)->state($this->supplier))->toBe('blocked');
|
||||
$this->first->forceFill(['purchasing_role' => PurchasingRole::Finance])->save();
|
||||
$this->supplier->update(['status' => 'suspended']);
|
||||
expect(app(SupplierBankWorkflow::class)->state($this->supplier))->toBe('blocked');
|
||||
});
|
||||
|
||||
test('foreign users cannot propose read or validate bank information', function () {
|
||||
$detail = bankProposal($this);
|
||||
$other = receiptFixture();
|
||||
$user = User::factory()->create(['tenant_id' => $other['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$this->actingAs($user)->get($this->url)->assertNotFound();
|
||||
$this->post($this->url.'/'.$detail->id.'/validar', ['decision' => 'approved', 'reason' => 'Teste', 'independently_verified' => true])->assertNotFound();
|
||||
});
|
||||
|
||||
test('warehouse and department heads cannot read bank details', function (PurchasingRole $role) {
|
||||
bankProposal($this);
|
||||
$user = User::factory()->create(['tenant_id' => $this->supplier->tenant_id, 'purchasing_role' => $role]);
|
||||
$this->actingAs($user)->get($this->url)->assertForbidden();
|
||||
})->with([PurchasingRole::Warehouse, PurchasingRole::DepartmentHead, PurchasingRole::Requester]);
|
||||
|
||||
test('administration gets metadata only and finance accesses are audited without account numbers', function () {
|
||||
$detail = bankProposal($this);
|
||||
$admin = User::factory()->create(['tenant_id' => $this->supplier->tenant_id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
$this->actingAs($admin)->get($this->url)->assertOk()->assertInertia(fn ($page) => $page->where('current', null));
|
||||
$this->actingAs($this->first)->get($this->url)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')->assertInertia(fn ($page) => $page->where('current.account_identifier', $this->data['account_identifier']));
|
||||
expect(AuditLog::query()->where('action', 'supplier.bank_viewed')->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('bank audit failure rolls back proposal and review', function () {
|
||||
$detail = bankProposal($this);
|
||||
$this->mock(RequisitionWorkflow::class)->shouldReceive('audit')->andThrow(new RuntimeException('audit failed'));
|
||||
expect(fn () => bankApprove($this, $this->first, $detail))->toThrow(RuntimeException::class);
|
||||
expect(SupplierBankReview::query()->count())->toBe(0);
|
||||
$this->data['previous_id'] = $detail->id;
|
||||
expect(fn () => bankProposal($this))->toThrow(RuntimeException::class);
|
||||
expect(SupplierBankDetail::query()->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('invalid bank submission does not flash sensitive input to the session', function () {
|
||||
$this->post($this->url, [...$this->data, 'country' => 'INVALID'])->assertSessionHasErrors('country');
|
||||
expect(session()->getOldInput('account_identifier'))->toBeNull()
|
||||
->and(session()->getOldInput('beneficiary'))->toBeNull()
|
||||
->and(session()->getOldInput('reason'))->toBeNull();
|
||||
});
|
||||
|
||||
test('bank review requires the independent verification declaration', function () {
|
||||
$detail = bankProposal($this);
|
||||
$this->actingAs($this->first)->post($this->url.'/'.$detail->id.'/validar', ['decision' => 'approved', 'reason' => 'Conferência'])->assertSessionHasErrors('independently_verified');
|
||||
expect(SupplierBankReview::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('supplier conflict blocks a previously approved banking revision', function () {
|
||||
$detail = bankProposal($this);
|
||||
bankApprove($this, $this->first, $detail);
|
||||
bankApprove($this, $this->second, $detail);
|
||||
$this->actingAs($this->first)->post('/conflitos', ['scope' => 'supplier', 'supplier_id' => $this->supplier->id, 'has_conflict' => true, 'known_since' => today()->format('Y-m-d'), 'reason' => 'Conflito fictício declarado depois da conferência.'])->assertSessionHasNoErrors();
|
||||
expect(app(SupplierBankWorkflow::class)->state($this->supplier))->toBe('blocked');
|
||||
});
|
||||
|
||||
test('public bank example exposes no company banking details', function () {
|
||||
auth()->forgetGuards();
|
||||
$this->get('/consulta/dados-bancarios')->assertOk()->assertInertia(fn ($page) => $page->where('initialScreen', 'bank')->where('auth.user', null)->missing('current')->missing('history'));
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
// Explicit operational entry point: backup, restore verification, then only migration 000011.
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
require __DIR__.'/../../vendor/autoload.php';
|
||||
$app = require __DIR__.'/../../bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
$connection = DB::connection();
|
||||
if ($connection->getDriverName() !== 'pgsql' || $connection->getDatabaseName() !== 'compras_dev' || ! $app->environment('local')) {
|
||||
throw new LogicException('Aplicação recusada fora de compras_dev/local.');
|
||||
}
|
||||
$pdo = $connection->getPdo();
|
||||
$migration = '2026_10_28_000011_create_supplier_bank_details';
|
||||
if ($pdo->query("SELECT count(*) FROM migrations WHERE migration = '$migration'")->fetchColumn() > 0) {
|
||||
throw new LogicException('Migração já aplicada; não repetir.');
|
||||
}
|
||||
$config = $connection->getConfig();
|
||||
$bin = 'C:/Program Files/PostgreSQL/17/bin/';
|
||||
foreach (['pg_dump.exe', 'pg_restore.exe'] as $tool) {
|
||||
if (! is_file($bin.$tool)) {
|
||||
throw new LogicException('Ferramentas PostgreSQL 17 ausentes.');
|
||||
}
|
||||
}
|
||||
$envHash = hash_file('sha256', base_path('.env'));
|
||||
$directory = storage_path('app/private/backups/bank-000011-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(3)));
|
||||
if (! mkdir($directory, 0700, true)) {
|
||||
throw new RuntimeException('Não foi possível criar backup privado.');
|
||||
}
|
||||
$env = ['PGHOST' => $config['host'], 'PGPORT' => (string) $config['port'], 'PGUSER' => $config['username'], 'PGPASSWORD' => $config['password'], 'PGSSLMODE' => $config['sslmode'] ?? 'prefer'];
|
||||
$quote = fn (string $name) => '"'.str_replace('"', '""', $name).'"';
|
||||
$fingerprints = function (PDO $db, array $tables) use ($quote): array {
|
||||
$result = [];
|
||||
foreach ($tables as $table) {
|
||||
$rows = $db->query('SELECT md5(row_to_json(t)::text) FROM public.'.$quote($table).' t')->fetchAll(PDO::FETCH_COLUMN);
|
||||
sort($rows, SORT_STRING);
|
||||
$result[$table] = ['count' => count($rows), 'sha256' => hash('sha256', implode('\n', $rows))];
|
||||
}
|
||||
|
||||
return $result;
|
||||
};
|
||||
$tables = $pdo->query("SELECT tablename FROM pg_tables WHERE schemaname = 'public' ORDER BY tablename")->fetchAll(PDO::FETCH_COLUMN);
|
||||
$restoreDatabase = 'compras_restore_check_'.bin2hex(random_bytes(6));
|
||||
$restoreCreated = false;
|
||||
try {
|
||||
// pg_dump and the manifest read exactly the same committed snapshot.
|
||||
$pdo->beginTransaction();
|
||||
$pdo->exec('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY');
|
||||
$snapshot = $pdo->query('SELECT pg_export_snapshot()')->fetchColumn();
|
||||
$backupState = $fingerprints($pdo, $tables);
|
||||
$dump = new Process([$bin.'pg_dump.exe', '--format=custom', '--no-owner', '--no-acl', '--snapshot='.$snapshot, '--file='.$directory.'/database.dump', '--dbname='.$config['database']], base_path(), $env);
|
||||
$dump->setTimeout(120);
|
||||
$dump->run();
|
||||
if (! $dump->isSuccessful()) {
|
||||
throw new RuntimeException('Falha no backup PostgreSQL; migração não executada.');
|
||||
}
|
||||
$pdo->commit();
|
||||
$pdo->exec('CREATE DATABASE '.$quote($restoreDatabase));
|
||||
$restoreCreated = true;
|
||||
$restore = new Process([$bin.'pg_restore.exe', '--exit-on-error', '--no-owner', '--no-acl', '--dbname='.$restoreDatabase, $directory.'/database.dump'], base_path(), $env);
|
||||
$restore->setTimeout(120);
|
||||
$restore->run();
|
||||
if (! $restore->isSuccessful()) {
|
||||
throw new RuntimeException('Restauro de verificação falhou; migração não executada.');
|
||||
}
|
||||
config(['database.connections.budget_restore' => [...$config, 'url' => null, 'database' => $restoreDatabase]]);
|
||||
$restored = DB::connection('budget_restore')->getPdo();
|
||||
if ($fingerprints($restored, $tables) !== $backupState) {
|
||||
throw new RuntimeException('Restauro não corresponde ao backup; migração recusada.');
|
||||
}
|
||||
file_put_contents($directory.'/manifest.json', json_encode(['tables' => $backupState, 'dump_sha256' => hash_file('sha256', $directory.'/database.dump')], JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
file_put_contents($directory.'/RECUPERACAO.txt', "Backup custom PostgreSQL 17 verificado por restauro numa base separada.\nUsar pg_restore --exit-on-error --no-owner --no-acl --dbname=NOVA_BASE database.dump.\nAs credenciais pertencem ao ambiente local e não estão neste manifesto.\nNão restaurar por cima da base existente.\n");
|
||||
DB::disconnect('budget_restore');
|
||||
unset($restored);
|
||||
$pdo->exec('DROP DATABASE '.$quote($restoreDatabase));
|
||||
$restoreCreated = false;
|
||||
$businessTables = array_values(array_diff($tables, ['migrations', 'sessions', 'cache', 'cache_locks', 'jobs', 'failed_jobs', 'job_batches']));
|
||||
$before = $fingerprints($pdo, $businessTables);
|
||||
$oldMigrations = $pdo->query('SELECT id, migration, batch FROM migrations ORDER BY id')->fetchAll(PDO::FETCH_ASSOC);
|
||||
$constraints = $pdo->query("SELECT conname, pg_get_constraintdef(oid) AS definition FROM pg_constraint WHERE connamespace = 'public'::regnamespace ORDER BY conname, definition")->fetchAll(PDO::FETCH_ASSOC);
|
||||
$exit = Artisan::call('migrate', ['--path' => 'database/migrations/'.$migration.'.php', '--force' => true]);
|
||||
if ($exit !== 0) {
|
||||
throw new RuntimeException('Migração falhou; consultar backup privado.');
|
||||
}
|
||||
$after = $fingerprints($pdo, $businessTables);
|
||||
$newMigrations = $pdo->query('SELECT id, migration, batch FROM migrations ORDER BY id')->fetchAll(PDO::FETCH_ASSOC);
|
||||
$newConstraints = $pdo->query("SELECT conname, pg_get_constraintdef(oid) AS definition FROM pg_constraint WHERE connamespace = 'public'::regnamespace ORDER BY conname, definition")->fetchAll(PDO::FETCH_ASSOC);
|
||||
if ($before !== $after || array_slice($newMigrations, 0, count($oldMigrations)) !== $oldMigrations || count($newMigrations) !== count($oldMigrations) + 1 || array_diff(array_map('serialize', $constraints), array_map('serialize', $newConstraints)) !== [] || hash_file('sha256', base_path('.env')) !== $envHash) {
|
||||
throw new RuntimeException('Verificação de preservação falhou; não executar mais escritas.');
|
||||
}
|
||||
$report = ['verified_at_utc' => gmdate('c'), 'migration' => $migration, 'batch' => (int) end($newMigrations)['batch'], 'backup_created' => true, 'backup_bytes' => filesize($directory.'/database.dump'), 'restore_verified' => true, 'restored_tables' => count($tables), 'restore_database_dropped' => true, 'business_records_unchanged' => true, 'existing_constraints_preserved' => true, 'env_unchanged' => true, 'bank_details_count' => (int) $pdo->query('SELECT count(*) FROM supplier_bank_details')->fetchColumn(), 'bank_reviews_count' => (int) $pdo->query('SELECT count(*) FROM supplier_bank_reviews')->fetchColumn(), 'operational_validation' => false];
|
||||
file_put_contents(base_path('docs/bancos-migracao-000011.json'), json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
|
||||
echo json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
} finally {
|
||||
if ($pdo->inTransaction()) {
|
||||
$pdo->rollBack();
|
||||
}
|
||||
DB::disconnect('budget_restore');
|
||||
if ($restoreCreated && preg_match('/^compras_restore_check_[a-f0-9]{12}$/', $restoreDatabase) && $restoreDatabase !== $connection->getDatabaseName()) {
|
||||
$pdo->exec('DROP DATABASE '.$quote($restoreDatabase));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user