293 lines
20 KiB
PHP
293 lines
20 KiB
PHP
<?php
|
|
|
|
use Illuminate\Contracts\Console\Kernel;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Str;
|
|
use Symfony\Component\Process\Process;
|
|
|
|
require dirname(__DIR__).'/vendor/autoload.php';
|
|
require_once __DIR__.'/../tests/Support/LandedQaReceipts.php';
|
|
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
|
$app->make(Kernel::class)->bootstrap();
|
|
$config = DB::connection('pgsql')->getConfig();
|
|
unset($config['name']);
|
|
if ($config['host'] !== '127.0.0.1') {
|
|
throw new LogicException('Ensaio permitido apenas no servidor PostgreSQL local.');
|
|
}
|
|
$database = 'compras_receipts_test_'.bin2hex(random_bytes(6));
|
|
if (! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database) || $database === $config['database']) {
|
|
throw new LogicException('Base descartável inválida.');
|
|
}
|
|
config(['database.connections.quotation_fx_admin' => [...$config, 'database' => 'postgres', 'url' => null]]);
|
|
$admin = DB::connection('quotation_fx_admin');
|
|
$admin->statement('CREATE DATABASE "'.$database.'"');
|
|
$qaVerificationFailed = false;
|
|
try {
|
|
$environment = ['APP_ENV' => 'testing', 'DB_CONNECTION' => 'pgsql', 'DB_URL' => '', 'DB_HOST' => $config['host'],
|
|
'DB_PORT' => (string) $config['port'], 'DB_DATABASE' => $database, 'DB_USERNAME' => $config['username'],
|
|
'DB_PASSWORD' => $config['password'], 'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array',
|
|
'MAIL_MAILER' => 'array', 'QUEUE_CONNECTION' => 'sync', 'BROADCAST_CONNECTION' => 'null'];
|
|
$commands = [
|
|
// One Pest kernel: a second migrate:fresh would retain PostgreSQL functions
|
|
// from existing immutable package schemas while dropping their tables.
|
|
[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/QuotationExchangeTest.php', 'tests/Feature/QuotationExchangeFinanceTest.php', 'tests/Feature/SupplierDocumentIntegrityTest.php', 'tests/Feature/PurchaseAwardOrderTest.php',
|
|
'--filter=foreign|mixed currency|exchange|finance freezes|quotation screen|only current finance|supplier download|supplier upload|supplier document integrity'],
|
|
[PHP_BINARY, 'tests/Concurrency/quotation-exchange-report-worker.php', $database],
|
|
];
|
|
if (in_array('--concurrency-only', $argv, true)) {
|
|
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate']];
|
|
}
|
|
$bankMode = in_array('--bank-accounts-only', $argv, true);
|
|
$conversionMode = in_array('--unit-conversion-only', $argv, true);
|
|
$agreementMode = in_array('--agreement-followup-only', $argv, true);
|
|
$orderLimitMode = in_array('--agreement-order-limits-only', $argv, true);
|
|
$upgradeMode = in_array('--commercial-upgrade-only', $argv, true);
|
|
$benchmarkMode = in_array('--benchmark-read-only', $argv, true);
|
|
$draftMode = in_array('--draft-preparation-only', $argv, true);
|
|
$searchMode = in_array('--procurement-search-only', $argv, true);
|
|
$productionMode = in_array('--warehouse-production-only', $argv, true);
|
|
$configuredLevelsMode = in_array('--configured-approval-levels-only', $argv, true);
|
|
$orderDocumentMode = in_array('--order-document-only', $argv, true);
|
|
$payableInsightsMode = in_array('--payable-insights-only', $argv, true);
|
|
$budgetDistributionMode = in_array('--budget-distribution-only', $argv, true);
|
|
$categoriesMode = in_array('--requisition-categories-only', $argv, true);
|
|
$savedSearchesMode = in_array('--saved-searches-only', $argv, true);
|
|
$categoryApprovalsMode = in_array('--category-approvals-only', $argv, true);
|
|
$orderPartsMode = in_array('--budget-order-parts-only', $argv, true);
|
|
$landedCostsMode = in_array('--import-landed-costs-only', $argv, true);
|
|
if ($landedCostsMode) {
|
|
$environment['COMMON_BUDGET_PATH'] = 'C:/laragon/www/sgf-tempo/packages/budget-control';
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportLandedCostPlanTest.php', 'tests/Feature/ImportLandedCostsTest.php', 'tests/Feature/BudgetLandedCostsContractTest.php',
|
|
'tests/Feature/SupplyPlanningTest.php', 'tests/Feature/BudgetDistributionContractTest.php', 'tests/Feature/BudgetOrderPartsContractTest.php', 'tests/Feature/BudgetTest.php', 'tests/Feature/BudgetReinforcementTest.php', 'tests/Feature/InvoiceTest.php', 'tests/Feature/OperationalHealthTest.php']];
|
|
if (in_array('--native-financial-focused', $argv, true)) {
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportLandedCostsTest.php', '--filter=native independently reviewed cost plan']];
|
|
}
|
|
if (in_array('--tariffs-focused', $argv, true)) {
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportTariffCodesTest.php', 'tests/Feature/RequisitionCatalogueTest.php']];
|
|
}
|
|
if (in_array('--tariff-orders-focused', $argv, true)) {
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php', 'tests/Feature/SupplyPlanningTest.php', 'tests/Feature/ReceiptStockTest.php', '--filter=confirmed import classifications|imported item classification|native partial-order|native consolidated order|import tracking|receipt|stock']];
|
|
if (in_array('--catalogue-receipt-focused', $argv, true)) {
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php', '--filter=catalogue origin survives order issue']];
|
|
}
|
|
}
|
|
if (in_array('--tariff-order-regression', $argv, true)) {
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php', '--filter=foreign|discount evidence|admission basis changes|expired after approval|older synthetic']];
|
|
}
|
|
if (in_array('--landed-concurrency', $argv, true)) {
|
|
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
|
[PHP_BINARY, 'tests/Concurrency/budget-landed-cost-worker.php', $database, 'race']];
|
|
}
|
|
if (in_array('--landed-recovery', $argv, true)) {
|
|
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
|
[PHP_BINARY, 'tests/Concurrency/budget-distribution-recovery-worker.php', $database, 'landed-costs']];
|
|
}
|
|
}
|
|
if ($orderPartsMode) {
|
|
$environment['COMMON_BUDGET_PATH'] = 'C:/laragon/www/sgf-tempo/packages/budget-control';
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/BudgetOrderPartsContractTest.php', 'tests/Feature/BudgetDistributionContractTest.php', 'tests/Feature/BudgetTest.php', 'tests/Feature/BudgetReinforcementTest.php']];
|
|
if (in_array('--order-parts-native', $argv, true)) {
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/BudgetOrderPartsContractTest.php',
|
|
'tests/Feature/InvoiceTest.php', 'tests/Unit/PurchaseLineAmountsTest.php', 'tests/Feature/PurchaseAwardOrderTest.php',
|
|
'--filter=BudgetOrderPartsContractTest|InvoiceTest|PurchaseLineAmountsTest|optional partial-order|native partial-order|native consolidated order|native explicit adoption']];
|
|
}
|
|
if (in_array('--order-parts-recovery', $argv, true)) {
|
|
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
|
[PHP_BINARY, 'tests/Concurrency/budget-distribution-recovery-worker.php', $database, 'order-parts']];
|
|
}
|
|
if (in_array('--order-parts-concurrency', $argv, true)) {
|
|
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
|
[PHP_BINARY, 'tests/Concurrency/budget-order-parts-worker.php', $database, 'race']];
|
|
}
|
|
}
|
|
if ($categoryApprovalsMode) {
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionApprovalLevelsTest.php', 'tests/Feature/RequisitionCategoriesTest.php']];
|
|
}
|
|
if ($savedSearchesMode) {
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/SavedProcurementSearchesTest.php', 'tests/Feature/ProcurementSearchTest.php']];
|
|
}
|
|
if ($categoriesMode) {
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionCategoriesTest.php', 'tests/Feature/RequisitionCatalogueTest.php', 'tests/Feature/IncompleteRequisitionDraftTest.php', 'tests/Feature/EquipmentSparePartsTest.php']];
|
|
}
|
|
if ($budgetDistributionMode) {
|
|
$environment['COMMON_BUDGET_PATH'] = 'C:/laragon/www/sgf-tempo/packages/budget-control';
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/BudgetDistributionContractTest.php', 'tests/Feature/BudgetTest.php', 'tests/Feature/BudgetReinforcementTest.php', 'tests/Feature/InvoiceTest.php']];
|
|
if (in_array('--award-focused', $argv, true)) {
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php', '--filter=distributed approved synthetic|foreign award approves|foreign order cancellation|changed prices or matrix|repeated issuance|fractional quantities and VAT']];
|
|
}
|
|
if (in_array('--distribution-concurrency', $argv, true)) {
|
|
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
|
[PHP_BINARY, 'tests/Concurrency/budget-distribution-worker.php', $database, 'race']];
|
|
}
|
|
if (in_array('--distribution-recovery', $argv, true)) {
|
|
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
|
[PHP_BINARY, 'tests/Concurrency/budget-distribution-recovery-worker.php', $database]];
|
|
}
|
|
if (in_array('--distribution-visual-seed-check', $argv, true)) {
|
|
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
|
[PHP_BINARY, 'tests/Concurrency/budget-distribution-visual-seed.php', $database]];
|
|
}
|
|
if (in_array('--distribution-schema', $argv, true)) {
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/BudgetDistributionSchemaTest.php', 'tests/Feature/BudgetDistributionDeploymentSchemaTest.php', 'tests/Feature/BudgetDistributionContractTest.php']];
|
|
}
|
|
}
|
|
if ($payableInsightsMode) {
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ProcurementPayableInsightsTest.php', ...(in_array('--focused', $argv, true) ? [] : ['tests/Feature/SupplierPayableIntegrationTest.php', 'tests/Feature/ProcurementReportsTest.php'])]];
|
|
}
|
|
if ($orderDocumentMode) {
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseDocumentCompatibilityTest.php', 'tests/Feature/PurchaseAwardOrderTest.php', '--filter=older synthetic|print|issuance|discount evidence']];
|
|
}
|
|
if ($configuredLevelsMode) {
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionApprovalLevelsTest.php', 'tests/Feature/InternalRequisitionCandidateTest.php', 'tests/Feature/OrganizationConfigurationTest.php', 'tests/Feature/WorkflowTaskInboxTest.php', 'tests/Feature/PurchaseProcessTest.php']];
|
|
}
|
|
if ($productionMode) {
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/WarehouseRequestsTest.php', 'tests/Feature/WarehouseFulfilmentTest.php', 'tests/Feature/AutomaticPurchasesTest.php']];
|
|
}
|
|
if ($searchMode) {
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ProcurementSearchTest.php']];
|
|
}
|
|
if ($draftMode) {
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/IncompleteRequisitionDraftTest.php', 'tests/Feature/InternalRequisitionCandidateTest.php', 'tests/Feature/RequisitionCatalogueTest.php', 'tests/Feature/PurchaseProcessTest.php', 'tests/Feature/ProcurementSearchTest.php', 'tests/Feature/ProcurementReportsTest.php']];
|
|
}
|
|
if ($benchmarkMode) {
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ProcurementSearchTest.php', 'tests/Feature/ProcurementReportsTest.php']];
|
|
}
|
|
if ($upgradeMode) {
|
|
$commands = [[PHP_BINARY, 'tests/Concurrency/commercial-upgrade-worker.php', $database]];
|
|
}
|
|
if ($conversionMode) {
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Conversion/ReceiptQuantityConversionTest.php']];
|
|
$commands[] = [PHP_BINARY, 'tests/Concurrency/unit-conversion-worker.php', $database, 'race'];
|
|
}
|
|
if ($agreementMode) {
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/AgreementFollowupTest.php', 'tests/Feature/SupplyPlanningTest.php'],
|
|
[PHP_BINARY, 'tests/Concurrency/agreement-followup-report-worker.php', $database]];
|
|
}
|
|
if ($orderLimitMode) {
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php', '--filter=per order']];
|
|
}
|
|
if ($bankMode && ! in_array('--concurrency-only', $argv, true)) {
|
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/SupplierBankAccountsTest.php', 'tests/Feature/SupplierBankTest.php',
|
|
'tests/Feature/ExternalPaymentTest.php', 'tests/Feature/PaymentIntegrationTest.php', 'tests/Feature/QuotationExchangeFinanceTest.php']];
|
|
}
|
|
if ($landedCostsMode && ! landedQaCommandIsolationVerified($commands)) {
|
|
throw new LogicException('Each Pest kernel must use its own disposable PostgreSQL database.');
|
|
}
|
|
foreach ($commands as $command) {
|
|
$process = new Process($command, dirname(__DIR__), $environment, timeout: 180);
|
|
$process->run();
|
|
echo $process->getOutput();
|
|
if (! $process->isSuccessful()) {
|
|
echo $process->getErrorOutput();
|
|
throw new RuntimeException('Validação PostgreSQL não aprovada.');
|
|
}
|
|
if ($landedCostsMode) {
|
|
$verified = landedQaReceiptsVerified($command, $process->getOutput());
|
|
if (! $verified) {
|
|
echo $process->getErrorOutput();
|
|
throw new RuntimeException('O processo terminou sem os recibos obrigatórios de verificação QA.');
|
|
}
|
|
}
|
|
}
|
|
if ($conversionMode || $agreementMode || $orderLimitMode || $upgradeMode || $benchmarkMode || $draftMode || $searchMode || $productionMode || $configuredLevelsMode || $orderDocumentMode || $payableInsightsMode || $budgetDistributionMode || $categoriesMode || $savedSearchesMode || $categoryApprovalsMode || $orderPartsMode || $landedCostsMode) {
|
|
return;
|
|
}
|
|
config(['database.connections.quotation_fx_proof' => [...$config, 'database' => $database, 'url' => null]]);
|
|
$proof = DB::connection('quotation_fx_proof');
|
|
if ($proof->getDatabaseName() !== $database) {
|
|
throw new LogicException('Ligação de concorrência não isolada.');
|
|
}
|
|
foreach (['same_operation', $bankMode ? 'different_accounts' : 'different_operation_same_currency'] as $scenario) {
|
|
$prepare = new Process([PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, $bankMode ? 'bank_prepare' : 'prepare'], dirname(__DIR__), $environment, timeout: 30);
|
|
$prepare->mustRun();
|
|
$ids = json_decode($prepare->getOutput(), true, 16, JSON_THROW_ON_ERROR);
|
|
$rate = ['operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => '60.1234567890',
|
|
'quoted_on' => date('Y-m-d'), 'source' => 'Fonte exclusivamente sintética de concorrência'];
|
|
if ($bankMode) {
|
|
$rate = [...$ids['bank_data'], 'previous_id' => 0, 'account_key' => (string) Str::uuid(), 'account_identifier' => 'FIRST-SYNTHETIC-ACCOUNT'];
|
|
}
|
|
$beforeAudit = $proof->table('audit_logs')->where('tenant_id', $ids['tenant'])->where('action', $bankMode ? 'supplier.bank_proposed' : 'quotation.exchange_rate_recorded')->count();
|
|
$workers = [];
|
|
$proof->beginTransaction();
|
|
try {
|
|
$proof->table('tenants')->where('id', $ids['tenant'])->lockForUpdate()->firstOrFail();
|
|
for ($i = 0; $i < 2; $i++) {
|
|
if ($i === 1 && $scenario !== 'same_operation') {
|
|
if ($bankMode) {
|
|
$rate['account_key'] = (string) Str::uuid();
|
|
$rate['account_identifier'] = 'OTHER-SYNTHETIC-ACCOUNT';
|
|
} else {
|
|
$rate['operation_id'] = (string) Str::uuid();
|
|
$rate['rate'] = '61';
|
|
}
|
|
}
|
|
$worker = new Process([PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, $bankMode ? 'bank_write' : 'write', json_encode([...$ids, 'rate' => $rate], JSON_THROW_ON_ERROR)], dirname(__DIR__), $environment, timeout: 30);
|
|
$workers[] = $worker;
|
|
$worker->start();
|
|
}
|
|
$deadline = microtime(true) + 10;
|
|
$blocked = 0;
|
|
do {
|
|
$proof->select('select pg_stat_clear_snapshot()');
|
|
$blocked = (int) $proof->selectOne("select count(*) as n from pg_stat_activity where datname = ? and application_name like ? and wait_event_type = 'Lock'", [$database, $bankMode ? 'sgc_bank_write_%' : 'sgc_fx_write_%'])->n;
|
|
if ($blocked >= 2) {
|
|
break;
|
|
}
|
|
usleep(20000);
|
|
} while (microtime(true) < $deadline);
|
|
if ($blocked < 2) {
|
|
throw new RuntimeException('Contenção real de dois escritores não demonstrada.');
|
|
}
|
|
$proof->commit();
|
|
$statuses = [];
|
|
$savedIds = [];
|
|
foreach ($workers as $worker) {
|
|
$worker->wait();
|
|
if (! $worker->isSuccessful()) {
|
|
throw new RuntimeException('Worker de concorrência não concluído.');
|
|
}
|
|
$result = json_decode($worker->getOutput(), true, 16, JSON_THROW_ON_ERROR);
|
|
$statuses[] = $result['status'];
|
|
$savedIds[] = $result['id'];
|
|
}
|
|
sort($statuses);
|
|
if ($bankMode) {
|
|
$expected = $scenario === 'same_operation' ? 1 : 2;
|
|
$versions = $proof->table('supplier_bank_details')->where('supplier_id', $ids['supplier'])->pluck('revision')->all();
|
|
if ($statuses !== [200, 200] || count(array_unique($savedIds)) !== $expected || count($versions) !== 1 + $expected
|
|
|| count(array_unique($versions)) !== count($versions)
|
|
|| $proof->table('audit_logs')->where('tenant_id', $ids['tenant'])->where('action', 'supplier.bank_proposed')->count() !== $beforeAudit + $expected) {
|
|
throw new RuntimeException('Identidades, versões ou auditoria de contas independentes não demonstradas.');
|
|
}
|
|
echo json_encode(['bank_scenario' => $scenario, 'real_lock_contention' => true, 'statuses' => $statuses, 'distinct_new_accounts' => $expected, 'distinct_global_versions' => true], JSON_THROW_ON_ERROR).PHP_EOL;
|
|
|
|
continue;
|
|
}
|
|
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 422])
|
|
|| $proof->table('quotation_exchange_rates')->where('requisition_id', $ids['request'])->count() !== 1
|
|
|| $proof->table('audit_logs')->where('tenant_id', $ids['tenant'])->where('action', 'quotation.exchange_rate_recorded')->count() !== 1) {
|
|
throw new RuntimeException('Unicidade, repetição ou auditoria não demonstradas.');
|
|
}
|
|
echo json_encode(['scenario' => $scenario, 'real_lock_contention' => true, 'statuses' => $statuses, 'one_rate_and_audit' => true], JSON_THROW_ON_ERROR).PHP_EOL;
|
|
} finally {
|
|
if ($proof->transactionLevel() > 0) {
|
|
$proof->rollBack();
|
|
}
|
|
foreach ($workers as $worker) {
|
|
if ($worker->isRunning()) {
|
|
$worker->stop();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} catch (Throwable $error) {
|
|
$qaVerificationFailed = true;
|
|
echo json_encode(['qa_verification_failed' => true, 'message' => $error->getMessage()], JSON_THROW_ON_ERROR).PHP_EOL;
|
|
} finally {
|
|
$admin->statement('DROP DATABASE "'.$database.'" WITH (FORCE)');
|
|
echo json_encode(['database' => $database, 'isolated_database_removed' => true], JSON_THROW_ON_ERROR).PHP_EOL;
|
|
}
|
|
if ($qaVerificationFailed) {
|
|
exit(1);
|
|
}
|