217 lines
15 KiB
PHP
217 lines
15 KiB
PHP
<?php
|
|
|
|
use App\Enums\PurchasingRole;
|
|
use App\Models\SupplyRecord;
|
|
use App\Models\User;
|
|
use App\Services\CommonBudget;
|
|
use App\Services\ImportBankSupport;
|
|
use App\Services\ImportEstimates;
|
|
use App\Services\ImportLegalEstimates;
|
|
use App\Services\ImportLegalRules;
|
|
use App\Services\SupplyPlanning;
|
|
use GuzzleHttp\Client;
|
|
use GuzzleHttp\Cookie\CookieJar;
|
|
use GuzzleHttp\Exception\ConnectException;
|
|
use Illuminate\Contracts\Console\Kernel;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\File;
|
|
use Illuminate\Support\Facades\Hash;
|
|
use Illuminate\Support\Facades\Storage;
|
|
use Illuminate\Support\Str;
|
|
use Symfony\Component\Process\Process;
|
|
use Tempo\Finance\Budget\BudgetImportEstimate;
|
|
|
|
require __DIR__.'/../../vendor/autoload.php';
|
|
$app = require __DIR__.'/../../bootstrap/app.php';
|
|
$app->make(Kernel::class)->bootstrap();
|
|
$database = $argv[1] ?? '';
|
|
$corpus = realpath($argv[3] ?? '');
|
|
$candidateRelative = $argv[4] ?? '';
|
|
$candidateHash = $argv[5] ?? '';
|
|
$reviewMode = ($argv[2] ?? '') === 'legal-review';
|
|
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database
|
|
|| DB::connection()->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)
|
|
|| $corpus === false || ! preg_match('~^storage/framework/testing/[A-Za-z0-9_-]+$~D', $candidateRelative)
|
|
|| ! preg_match('/^[a-f0-9]{64}$/D', $candidateHash) || hash_file('sha256', base_path($candidateRelative.'/manifest.json')) !== $candidateHash) {
|
|
throw new LogicException('HTTP source review requires a supplied corpus, validated private candidate and disposable PostgreSQL.');
|
|
}
|
|
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
|
require_once __DIR__.'/../Support/SupplyFixture.php';
|
|
require_once __DIR__.'/../Support/ImportLegalQaFixture.php';
|
|
require_once __DIR__.'/../Support/ImportBankQaFixture.php';
|
|
$files = glob(str_replace('\\', '/', $corpus).'/Legislacao/2022/12 Dezembro/series-i/br-series-i-29-12-2022-*.pdf');
|
|
if ($files === false || count($files) !== 1 || filesize($files[0]) <= 2097152) {
|
|
throw new LogicException('Select the complete shared official journal, not a small extracted example.');
|
|
}
|
|
$path = $files[0];
|
|
$originalHash = hash_file('sha256', $path);
|
|
$f = receiptFixture();
|
|
supplyGrant($f['issuer'], ['procurement', 'import_customs']);
|
|
auth()->guard()->setUser($f['issuer']);
|
|
$password = Str::random(48);
|
|
$f['issuer']->forceFill(['password' => Hash::make($password)])->save();
|
|
$fingerprint = fn () => [DB::table('budget_entries')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('stock_movements')->get()->toJson()];
|
|
$before = $fingerprint();
|
|
$directory = storage_path('framework/testing/legal-http-'.$database);
|
|
foreach (['public', 'storage/framework/sessions', 'storage/framework/views', 'storage/framework/cache/data', 'storage/logs', 'storage/app/private'] as $relative) {
|
|
File::ensureDirectoryExists($directory.'/'.$relative);
|
|
}
|
|
File::copyDirectory(base_path($candidateRelative), $directory.'/public/build');
|
|
$socket = stream_socket_server('tcp://127.0.0.1:0', $errorCode, $error);
|
|
if ($socket === false) {
|
|
throw new RuntimeException('Unable to reserve a loopback QA port.');
|
|
}
|
|
$address = stream_socket_get_name($socket, false);
|
|
fclose($socket);
|
|
$port = substr($address, strrpos($address, ':') + 1);
|
|
$url = 'http://'.($reviewMode ? 'localhost' : '127.0.0.1').':'.$port;
|
|
$server = new Process([PHP_BINARY, '-d', 'upload_max_filesize=64M', '-d', 'post_max_size=70M', '-S', '127.0.0.1:'.$port,
|
|
'tests/Support/import-legal-http-router.php'], base_path(), ['APP_ENV' => 'testing', 'APP_DEBUG' => 'false',
|
|
'APP_URL' => $url, 'ASSET_URL' => $url, 'SGC_LEGAL_HTTP_QA_ROOT' => $directory, 'SGC_LEGAL_HTTP_QA_PORT' => $port,
|
|
'SESSION_COOKIE' => 'sgc_legal_http_'.substr($database, -12), 'SESSION_DRIVER' => 'file'], timeout: null);
|
|
$client = new Client(['base_uri' => $url, 'cookies' => $cookies = new CookieJar, 'http_errors' => false, 'allow_redirects' => false,
|
|
'timeout' => 20, 'expect' => false]);
|
|
$result = null;
|
|
try {
|
|
$server->start();
|
|
$ready = false;
|
|
$deadline = microtime(true) + 10;
|
|
do {
|
|
try {
|
|
$ready = $client->get('/up')->getStatusCode() === 200;
|
|
} catch (ConnectException) {
|
|
usleep(50000);
|
|
}
|
|
} while (! $ready && $server->isRunning() && microtime(true) < $deadline);
|
|
if (! $ready || $client->get('/login')->getStatusCode() !== 200) {
|
|
throw new RuntimeException('Private native HTTP login page unavailable.');
|
|
}
|
|
$token = fn () => rawurldecode($cookies->getCookieByName('XSRF-TOKEN')?->getValue() ?? '');
|
|
if ($token() === '') {
|
|
throw new RuntimeException('Native session did not issue a CSRF cookie.');
|
|
}
|
|
$login = $client->post('/login', ['headers' => ['Accept' => 'application/json', 'X-XSRF-TOKEN' => $token()],
|
|
'form_params' => ['email' => $f['issuer']->email, 'password' => $password]]);
|
|
if (! in_array($login->getStatusCode(), [200, 302, 303], true)) {
|
|
throw new RuntimeException('Native synthetic Fortify login failed: '.$login->getStatusCode());
|
|
}
|
|
$route = '/requisicoes/'.$f['r']->id.'/base-legal';
|
|
$headers = ['Accept' => 'application/json', 'X-XSRF-TOKEN' => $token(), 'Referer' => $url.$route];
|
|
$negative = $client->post($route, ['headers' => ['Accept' => 'application/json'], 'json' => ['action' => 'source']]);
|
|
if ($negative->getStatusCode() !== 419) {
|
|
throw new RuntimeException('Native HTTP source requests must require CSRF: '.$negative->getStatusCode());
|
|
}
|
|
$input = ['operation_key' => (string) Str::uuid(), 'action' => 'source', 'version' => '0',
|
|
'official_reference' => 'BR I Série 251 de 29/12/2022 — exemplar integral real partilhado',
|
|
'reason' => 'Ensaio HTTP estritamente QA com exemplar oficial real, empresa e conta sintéticas; sem publicar regras'];
|
|
foreach ([1, 2] as $attempt) {
|
|
$multipart = array_map(fn ($name) => ['name' => $name, 'contents' => $input[$name]], array_keys($input));
|
|
$multipart[] = ['name' => 'file', 'contents' => fopen($path, 'rb'), 'filename' => basename($path), 'headers' => ['Content-Type' => 'application/pdf']];
|
|
$response = $client->post($route, ['headers' => $headers, 'multipart' => $multipart]);
|
|
if (! in_array($response->getStatusCode(), [302, 303], true)) {
|
|
throw new RuntimeException('Native large-source multipart upload failed: '.$response->getStatusCode());
|
|
}
|
|
}
|
|
$initial = $client->get($route);
|
|
if ($initial->getStatusCode() !== 200 || ! preg_match('~<script[^>]*data-page="[^"]+"[^>]*>(.*?)</script>~s', (string) $initial->getBody(), $initialData)) {
|
|
throw new RuntimeException('Native source page bootstrap unavailable: '.$initial->getStatusCode());
|
|
}
|
|
$initialPage = json_decode($initialData[1], true, 64, JSON_THROW_ON_ERROR);
|
|
$page = $client->get($route, ['headers' => ['X-Inertia' => 'true', 'X-Inertia-Version' => $initialPage['version'], 'Accept' => 'text/html, application/xhtml+xml']]);
|
|
if ($page->getStatusCode() !== 200 || ! str_contains($page->getHeaderLine('Content-Type'), 'application/json')) {
|
|
throw new RuntimeException('Native Inertia page did not accept its bootstrap version: '.$page->getStatusCode());
|
|
}
|
|
$props = json_decode((string) $page->getBody(), true, 64, JSON_THROW_ON_ERROR)['props'] ?? [];
|
|
$source = SupplyRecord::query()->where('kind', 'import_legal_source')->sole();
|
|
$download = $client->get($route.'/fontes/'.$source->id);
|
|
$guest = new Client(['base_uri' => $url, 'http_errors' => false, 'allow_redirects' => false, 'timeout' => 10]);
|
|
$anonymous = $guest->get($route.'/fontes/'.$source->id, ['headers' => ['Accept' => 'application/json']]);
|
|
if ($page->getStatusCode() !== 200 || ($props['sources']['total'] ?? null) !== 1 || ($props['rules']['total'] ?? null) !== 0
|
|
|| $download->getStatusCode() !== 200 || hash('sha256', (string) $download->getBody()) !== $originalHash
|
|
|| hash_file('sha256', $path) !== $originalHash || $anonymous->getStatusCode() !== 401
|
|
|| DB::table('audit_logs')->where('tenant_id', $f['tenant']->id)->where('action', 'import.legal_source_recorded')->count() !== 1
|
|
|| $fingerprint() !== $before) {
|
|
throw new RuntimeException('Native source scope, large bytes, idempotence, authentication or financial preservation not demonstrated.');
|
|
}
|
|
DB::table('organization_memberships')->where('user_id', $f['issuer']->id)->delete();
|
|
$revoked = $client->get($route.'/fontes/'.$source->id, ['headers' => ['Accept' => 'application/json']]);
|
|
if ($revoked->getStatusCode() !== 403) {
|
|
throw new RuntimeException('Native download did not revalidate revoked QA authority.');
|
|
}
|
|
$result = ['native_legal_http_login' => true, 'csrf_required' => true, 'large_multipart_upload_bytes' => filesize($path),
|
|
'original_sha256' => $originalHash, 'original_unchanged' => true, 'exact_native_download' => true, 'one_source_one_audit_after_replay' => true,
|
|
'guest_status' => 401, 'revoked_status' => 403, 'rules_published' => 0, 'financial_stock_unchanged' => true,
|
|
'private_upload_limit' => '64M', 'private_post_limit' => '70M', 'global_php_config_unchanged' => true];
|
|
if ($reviewMode) {
|
|
// Existing factory password is confined to guarded, disposable synthetic QA identities.
|
|
$reviewer = $f['otherReceiver'];
|
|
supplyGrant($reviewer, ['procurement', 'requester', 'import_read', 'import_prepare', 'import_customs']);
|
|
config(['import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true, 'import-estimates.qa_enabled' => true,
|
|
'import-dossier.qa_enabled' => true, 'import-bank-support.qa_enabled' => true, 'import-readiness.qa_enabled' => true]);
|
|
Storage::set('local', Storage::build(['driver' => 'local', 'root' => $directory.'/storage/app/private', 'throw' => true]));
|
|
$author = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
|
$approver = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
|
supplyGrant($author, ['finance']);
|
|
supplyGrant($approver, ['finance']);
|
|
auth()->guard()->setUser($author);
|
|
$budget = app(CommonBudget::class)->for($author)->create(['cost_center_id' => $f['r']->cost_center_id, 'year' => (int) now()->year,
|
|
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 1000000, 'reason' => 'Dotação estritamente sintética da revisão nativa']);
|
|
auth()->guard()->setUser($approver);
|
|
app(CommonBudget::class)->for($approver)->approve($budget);
|
|
auth()->guard()->setUser($reviewer);
|
|
$draftRequest = $f['r']->replicate();
|
|
$draftRequest->fill(['number' => 'VISUAL-LEGAL-'.Str::random(8), 'requester_id' => $reviewer->id, 'status' => 'draft']);
|
|
$draftRequest->save();
|
|
$draftItem = $f['r']->items()->sole()->replicate();
|
|
$draftItem->requisition_id = $draftRequest->id;
|
|
$draftItem->save();
|
|
$legalDraft = app(ImportLegalRules::class)->save($reviewer, importLegalQaInput(['title' => 'Regra de ensaio — dados fictícios', 'charges' => [importLegalQaCharge()]]), importLegalQaFile());
|
|
$legalRule = app(ImportLegalRules::class)->save($reviewer, ['operation_key' => (string) Str::uuid(), 'record_key' => $legalDraft->record_key,
|
|
'version' => 1, 'action' => 'publish', 'reason' => 'Publicação de dados estritamente fictícios para revisão nativa isolada']);
|
|
$amountInput = importLegalQaAmountInput($draftItem->id, $legalRule->id);
|
|
$amountInput['bases']['synthetic-duty']['value_minor'] = 10000;
|
|
$amount = app(ImportLegalEstimates::class)->save($reviewer, $draftRequest, $amountInput);
|
|
app(ImportEstimates::class)->save($reviewer, $draftRequest, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'budget_id' => $budget,
|
|
'reason' => 'Plano fictício apenas com direitos neste cenário; sem reserva ou submissão', 'legal_sources' => ['duty' => ['estimate_id' => $amount->id, 'charge_key' => 'synthetic-duty']],
|
|
'components' => array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => $kind === 'duty' ? 'known' : 'not_applicable',
|
|
'basis' => 'Pressuposto estritamente sintético desta revisão, não isenção real', 'subtotal_minor' => $kind === 'duty' ? 750 : null,
|
|
'tax_minor' => $kind === 'duty' ? 0 : null, 'total_minor' => $kind === 'duty' ? 750 : null], BudgetImportEstimate::KINDS)]);
|
|
$import = app(SupplyPlanning::class)->save($reviewer, 'import', supplyInput(['purchase_order_id' => $f['order']->id, 'purpose' => 'internal',
|
|
'jurisdiction' => 'Âmbito fictício QA', 'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Regime fictício QA']));
|
|
$bank = importBankQaFixture($reviewer, $import);
|
|
app(ImportBankSupport::class)->save($reviewer, $import, $bank['input']);
|
|
$stopFile = $directory.'/stop';
|
|
echo json_encode(['private_review_running' => true, 'url' => $url, 'stop_file' => $stopFile,
|
|
'synthetic_user' => $reviewer->email, 'draft_request' => $draftRequest->id, 'import' => $import->id,
|
|
'legal_url' => $url.'/requisicoes/'.$draftRequest->id.'/base-legal?'.http_build_query(['code' => '1234', 'origin' => 'Synthetic A', 'sector' => 'Synthetic sector', 'date' => '2026-11-27']),
|
|
'private_candidate_manifest' => $candidateHash, 'pilot_assets_changed' => false], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR).PHP_EOL;
|
|
$deadline = microtime(true) + 3600;
|
|
while (! is_file($stopFile) && microtime(true) < $deadline) {
|
|
if (! $server->isRunning()) {
|
|
throw new RuntimeException('Private native review server stopped unexpectedly.');
|
|
}
|
|
$server->getIncrementalOutput();
|
|
$server->getIncrementalErrorOutput();
|
|
usleep(100000);
|
|
}
|
|
$result['private_native_review_stopped'] = true;
|
|
}
|
|
} catch (Throwable $error) {
|
|
$summary = 'No native exception log.';
|
|
$log = $directory.'/storage/logs/laravel.log';
|
|
if (is_file($log) && preg_match_all('/testing\.ERROR: ([^\r\n]+)/', file_get_contents($log), $matches) && $matches[1] !== []) {
|
|
$summary = substr(str_replace($password, '[synthetic credential redacted]', end($matches[1])), 0, 300);
|
|
}
|
|
throw new RuntimeException($error->getMessage().' Native diagnostic: '.$summary);
|
|
} finally {
|
|
$server->stop();
|
|
$resolved = realpath($directory);
|
|
$boundary = realpath(storage_path('framework/testing'));
|
|
if ($resolved !== false && $boundary !== false && str_replace('\\', '/', $resolved) === str_replace('\\', '/', $boundary).'/legal-http-'.$database) {
|
|
File::deleteDirectory($resolved);
|
|
}
|
|
if ($result !== null) {
|
|
echo json_encode([...$result, 'private_http_server_stopped' => true, 'private_http_root_removed' => ! is_dir($directory)], JSON_THROW_ON_ERROR).PHP_EOL;
|
|
}
|
|
}
|