|
|
|
@@ -0,0 +1,229 @@
|
|
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
use App\Models\Requisition;
|
|
|
|
|
use App\Models\User;
|
|
|
|
|
use App\Services\RequisitionAccountAssignments;
|
|
|
|
|
use Carbon\Carbon;
|
|
|
|
|
use Carbon\CarbonImmutable;
|
|
|
|
|
use Illuminate\Contracts\Console\Kernel;
|
|
|
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
|
use Illuminate\Support\Str;
|
|
|
|
|
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
|
|
|
|
use Symfony\Component\Process\Process;
|
|
|
|
|
use Tempo\Finance\GeneralLedger\LedgerSchema;
|
|
|
|
|
|
|
|
|
|
require __DIR__.'/../../vendor/autoload.php';
|
|
|
|
|
$app = require __DIR__.'/../../bootstrap/app.php';
|
|
|
|
|
if (in_array($argv[2] ?? '', ['prepare-native-review', 'read-office-purchase'], true)) {
|
|
|
|
|
$privateRoot = realpath(getenv('SGC_REQUISITION_QA_ROOT') ?: '');
|
|
|
|
|
$boundary = realpath(__DIR__.'/../../storage/framework/testing');
|
|
|
|
|
$databaseName = getenv('DB_DATABASE') ?: '';
|
|
|
|
|
if ($privateRoot === false || $boundary === false || ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $databaseName, $matches)
|
|
|
|
|
|| str_replace('\\', '/', $privateRoot) !== str_replace('\\', '/', $boundary).'/rq01-ledger-qa-'.$matches[1]) {
|
|
|
|
|
throw new LogicException('Private native review root refused.');
|
|
|
|
|
}
|
|
|
|
|
$app->useStoragePath($privateRoot.'/storage');
|
|
|
|
|
}
|
|
|
|
|
$app->make(Kernel::class)->bootstrap();
|
|
|
|
|
$database = $argv[1] ?? '';
|
|
|
|
|
$mode = $argv[2] ?? '';
|
|
|
|
|
require_once __DIR__.'/../Support/RequisitionLedgerQaRuntime.php';
|
|
|
|
|
$source = requisitionLedgerQaSource();
|
|
|
|
|
if (! $app->environment('testing') || DB::connection()->getDatabaseName() !== $database
|
|
|
|
|
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database) || $source === null) {
|
|
|
|
|
throw new LogicException('Owned common-ledger QA composition required.');
|
|
|
|
|
}
|
|
|
|
|
require_once $source.'/bootstrap.php';
|
|
|
|
|
LedgerSchema::assertSynthetic(DB::connection());
|
|
|
|
|
config(['requisition-accounts.qa_enabled' => true]);
|
|
|
|
|
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
|
|
|
|
if ($mode === 'prepare-native-review') {
|
|
|
|
|
require_once __DIR__.'/../Support/RequisitionAccountsNativeReview.php';
|
|
|
|
|
echo json_encode(requisitionAccountsNativeReviewFixture(getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1', getenv('RQ01_NATIVE_OFFICE_JOURNEY') === '1'), JSON_THROW_ON_ERROR);
|
|
|
|
|
exit;
|
|
|
|
|
}
|
|
|
|
|
if ($mode === 'read-office-purchase') {
|
|
|
|
|
if (getenv('RQ01_NATIVE_OFFICE_JOURNEY') !== '1') {
|
|
|
|
|
throw new LogicException('Office HTTP assertions require their explicit synthetic composition.');
|
|
|
|
|
}
|
|
|
|
|
$fixture = json_decode(file_get_contents($privateRoot.'/native-review.json'), true, 64, JSON_THROW_ON_ERROR);
|
|
|
|
|
Carbon::setTestNow($fixture['clock']);
|
|
|
|
|
CarbonImmutable::setTestNow($fixture['clock']);
|
|
|
|
|
require_once __DIR__.'/../Support/NativeOfficePurchaseState.php';
|
|
|
|
|
try {
|
|
|
|
|
$state = DB::transaction(function () use ($fixture) {
|
|
|
|
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
|
|
|
|
|
|
|
|
|
return nativeOfficePurchaseState($fixture);
|
|
|
|
|
});
|
|
|
|
|
echo json_encode($state, JSON_THROW_ON_ERROR);
|
|
|
|
|
} catch (Throwable $error) {
|
|
|
|
|
fwrite(STDERR, get_class($error).': '.$error->getMessage().PHP_EOL);
|
|
|
|
|
exit(1);
|
|
|
|
|
}
|
|
|
|
|
exit;
|
|
|
|
|
}
|
|
|
|
|
$financial = static function (): string {
|
|
|
|
|
$rows = [];
|
|
|
|
|
foreach (['gl_accounts', 'gl_journals', 'gl_lines', 'requisitions', 'requisition_items', 'invoices', 'invoice_items', 'external_payments', 'budget_entries', 'stock_movements'] as $table) {
|
|
|
|
|
$rows[$table] = DB::table($table)->orderBy('id')->get()->toJson();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR));
|
|
|
|
|
};
|
|
|
|
|
$snapshot = static function (): array {
|
|
|
|
|
$frames = [];
|
|
|
|
|
foreach (DB::select("select tablename from pg_tables where schemaname='public' order by tablename") as $table) {
|
|
|
|
|
$name = str_replace('"', '""', $table->tablename);
|
|
|
|
|
$rows = DB::select('select row_to_json(t)::text as row from "'.$name.'" t order by row_to_json(t)::text');
|
|
|
|
|
$frames[$table->tablename] = hash('sha256', json_encode([DB::getSchemaBuilder()->getColumnListing($table->tablename), array_column($rows, 'row')], JSON_THROW_ON_ERROR));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return $frames;
|
|
|
|
|
};
|
|
|
|
|
if ($mode === 'read-native-sources') {
|
|
|
|
|
$frames = DB::transaction(function () use ($snapshot) {
|
|
|
|
|
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
|
|
|
|
|
|
|
|
|
return $snapshot();
|
|
|
|
|
});
|
|
|
|
|
echo json_encode(['snapshot' => $frames], JSON_THROW_ON_ERROR);
|
|
|
|
|
exit;
|
|
|
|
|
}
|
|
|
|
|
if ($mode === 'prepare-recovery') {
|
|
|
|
|
LedgerSchema::install(DB::connection());
|
|
|
|
|
$composition = null;
|
|
|
|
|
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1') {
|
|
|
|
|
require_once __DIR__.'/../Support/IntegratedPurchasingQaSchema.php';
|
|
|
|
|
$composition = integratedPurchasingQaSchema();
|
|
|
|
|
}
|
|
|
|
|
$prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
|
|
|
|
|
$prepare->mustRun();
|
|
|
|
|
$payload = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
|
|
|
|
|
$actor = User::query()->whereKey($payload['actor'])->firstOrFail();
|
|
|
|
|
auth()->guard()->setUser($actor);
|
|
|
|
|
$request = Requisition::query()->whereKey($payload['request'])->firstOrFail();
|
|
|
|
|
$service = app(RequisitionAccountAssignments::class);
|
|
|
|
|
$first = $service->save($actor, $request, $payload['input']);
|
|
|
|
|
$payload['input']['operation_key'] = (string) Str::uuid();
|
|
|
|
|
$payload['input']['version'] = 1;
|
|
|
|
|
$payload['input']['reason'] = 'Segunda versão explícita preservada no restauro';
|
|
|
|
|
$second = $service->save($actor, $request, $payload['input']);
|
|
|
|
|
echo json_encode(['payload' => $payload, 'first' => $first->id, 'second' => $second->id, 'snapshot' => $snapshot(), 'integrated_optional_schema' => $composition], JSON_THROW_ON_ERROR);
|
|
|
|
|
exit;
|
|
|
|
|
}
|
|
|
|
|
if ($mode === 'verify-recovery') {
|
|
|
|
|
$fixture = json_decode($argv[3], true, 64, JSON_THROW_ON_ERROR);
|
|
|
|
|
$composition = $fixture['integrated_optional_schema'] ?? null;
|
|
|
|
|
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1'
|
|
|
|
|
&& (! is_array($composition) || count($composition['migrations'] ?? []) !== 5
|
|
|
|
|
|| count($composition['verified_tables'] ?? []) !== 12)) {
|
|
|
|
|
throw new RuntimeException('Integrated recovery requires the complete optional schema manifest.');
|
|
|
|
|
}
|
|
|
|
|
if ($snapshot() !== $fixture['snapshot']) {
|
|
|
|
|
throw new RuntimeException('Restored account composition differs in tables, columns or rows.');
|
|
|
|
|
}
|
|
|
|
|
$payload = $fixture['payload'];
|
|
|
|
|
$actor = User::query()->whereKey($payload['actor'])->firstOrFail();
|
|
|
|
|
auth()->guard()->setUser($actor);
|
|
|
|
|
$request = Requisition::query()->whereKey($payload['request'])->firstOrFail();
|
|
|
|
|
$service = app(RequisitionAccountAssignments::class);
|
|
|
|
|
$replay = $service->save($actor, $request, $payload['input']);
|
|
|
|
|
$frozen = $service->freezeForItems($actor, [$payload['input']['item_id']]);
|
|
|
|
|
if ($replay->id !== $fixture['second'] || $frozen[$payload['input']['item_id']]['id'] !== $fixture['second']
|
|
|
|
|
|| DB::table('supply_records')->where('kind', 'req_account')->count() !== 2 || $snapshot() !== $fixture['snapshot']) {
|
|
|
|
|
throw new RuntimeException('Restored account versions, audited origin or replay changed.');
|
|
|
|
|
}
|
|
|
|
|
echo json_encode(['tables_equal' => count($fixture['snapshot']), 'versions' => 2, 'audited_account_source_verified' => true,
|
|
|
|
|
'replay_without_effects' => true, 'chart_and_native_financial_sources_preserved' => true,
|
|
|
|
|
'integrated_optional_schema' => $composition], JSON_THROW_ON_ERROR).PHP_EOL;
|
|
|
|
|
exit;
|
|
|
|
|
}
|
|
|
|
|
if ($mode === 'prepare') {
|
|
|
|
|
$f = receiptFixture();
|
|
|
|
|
$f['r']->update(['status' => 'draft']);
|
|
|
|
|
auth()->guard()->setUser($f['issuer']);
|
|
|
|
|
DB::table('gl_accounts')->insert(['tenant_id' => $f['tenant']->id, 'company_id' => 0, 'unit_id' => 0,
|
|
|
|
|
'code' => 'QA-RACE-ACCOUNT', 'label' => 'Conta fictícia de concorrência', 'currency' => 'MZN', 'is_movement' => true]);
|
|
|
|
|
$space = app(RequisitionAccountAssignments::class)->workspace($f['issuer'], $f['r']);
|
|
|
|
|
$line = $space['items'][0];
|
|
|
|
|
$account = $space['accounts']['data'][0];
|
|
|
|
|
echo json_encode(['actor' => $f['issuer']->id, 'tenant' => $f['tenant']->id, 'request' => $f['r']->id, 'fingerprint' => $financial(),
|
|
|
|
|
'input' => ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $line['id'], 'basis_hash' => $line['basis_hash'],
|
|
|
|
|
'reason' => 'Imputação explícita num ensaio de contenção real', 'allocations' => [['account_id' => $account['id'], 'source_hash' => $account['source_hash'],
|
|
|
|
|
'subtotal' => '100.00', 'total' => '100.00']]]], JSON_THROW_ON_ERROR);
|
|
|
|
|
exit;
|
|
|
|
|
}
|
|
|
|
|
if ($mode === 'write') {
|
|
|
|
|
$payload = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR);
|
|
|
|
|
DB::select('select set_config(?, ?, false)', ['application_name', 'sgc_req_account_'.getmypid()]);
|
|
|
|
|
$actor = User::query()->findOrFail($payload['actor']);
|
|
|
|
|
auth()->guard()->setUser($actor);
|
|
|
|
|
try {
|
|
|
|
|
$record = app(RequisitionAccountAssignments::class)->save($actor, Requisition::query()->findOrFail($payload['request']), $payload['input']);
|
|
|
|
|
echo json_encode(['status' => 200, 'id' => $record->id]);
|
|
|
|
|
} catch (HttpExceptionInterface $error) {
|
|
|
|
|
echo json_encode(['status' => $error->getStatusCode()]);
|
|
|
|
|
}
|
|
|
|
|
exit;
|
|
|
|
|
}
|
|
|
|
|
if ($mode !== 'race') {
|
|
|
|
|
throw new InvalidArgumentException('Unknown QA account mode.');
|
|
|
|
|
}
|
|
|
|
|
LedgerSchema::install(DB::connection());
|
|
|
|
|
foreach (['same_operation', 'same_version'] as $scenario) {
|
|
|
|
|
$prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
|
|
|
|
|
$prepare->mustRun();
|
|
|
|
|
$payload = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
|
|
|
|
|
$workers = [];
|
|
|
|
|
DB::beginTransaction();
|
|
|
|
|
try {
|
|
|
|
|
DB::table('tenants')->where('id', $payload['tenant'])->lockForUpdate()->firstOrFail();
|
|
|
|
|
for ($i = 0; $i < 2; $i++) {
|
|
|
|
|
$input = $payload;
|
|
|
|
|
if ($scenario === 'same_version' && $i === 1) {
|
|
|
|
|
$input['input']['operation_key'] = (string) Str::uuid();
|
|
|
|
|
}
|
|
|
|
|
$worker = new Process([PHP_BINARY, __FILE__, $database, 'write', json_encode($input, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30);
|
|
|
|
|
$workers[] = $worker;
|
|
|
|
|
$worker->start();
|
|
|
|
|
}
|
|
|
|
|
$deadline = microtime(true) + 10;
|
|
|
|
|
do {
|
|
|
|
|
DB::select('select pg_stat_clear_snapshot()');
|
|
|
|
|
$blocked = (int) DB::selectOne("select count(*) n from pg_stat_activity where datname=? and application_name like 'sgc_req_account_%' and wait_event_type='Lock'", [$database])->n;
|
|
|
|
|
if ($blocked === 2) {
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
usleep(50000);
|
|
|
|
|
} while (microtime(true) < $deadline);
|
|
|
|
|
if ($blocked !== 2) {
|
|
|
|
|
throw new RuntimeException('Both account writers must demonstrably wait on the company lock.');
|
|
|
|
|
}
|
|
|
|
|
DB::commit();
|
|
|
|
|
$statuses = [];
|
|
|
|
|
foreach ($workers as $worker) {
|
|
|
|
|
$worker->wait();
|
|
|
|
|
if (! $worker->isSuccessful()) {
|
|
|
|
|
throw new RuntimeException('Synthetic account writer failed: '.$worker->getErrorOutput());
|
|
|
|
|
}
|
|
|
|
|
$statuses[] = json_decode($worker->getOutput(), true, 32, JSON_THROW_ON_ERROR)['status'];
|
|
|
|
|
}
|
|
|
|
|
sort($statuses);
|
|
|
|
|
$count = DB::table('supply_records')->where('tenant_id', $payload['tenant'])->where('kind', 'req_account')->count();
|
|
|
|
|
$audits = DB::table('audit_logs')->where('tenant_id', $payload['tenant'])->where('action', 'requisition.accounts_assigned')->count();
|
|
|
|
|
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $count !== 1 || $audits !== 1 || $financial() !== $payload['fingerprint']) {
|
|
|
|
|
throw new RuntimeException('Account contention lost replay/version/source guarantees.');
|
|
|
|
|
}
|
|
|
|
|
echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers' => $blocked, 'versions' => $count, 'audits' => $audits, 'financial_sources_unchanged' => true], JSON_THROW_ON_ERROR).PHP_EOL;
|
|
|
|
|
} finally {
|
|
|
|
|
if (DB::transactionLevel() > 0) {
|
|
|
|
|
DB::rollBack();
|
|
|
|
|
}
|
|
|
|
|
foreach ($workers as $worker) {
|
|
|
|
|
if ($worker->isRunning()) {
|
|
|
|
|
$worker->stop();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|