@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
use App\Http\Controllers\ProcurementReviewReportController;
|
||||
use App\Services\ProcurementReviewCsv;
|
||||
use App\Services\ProcurementReviewReport;
|
||||
use App\Services\QuotationExchange;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Database\Events\QueryExecuted;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
require __DIR__.'/../../vendor/autoload.php';
|
||||
$database = $argv[1] ?? '';
|
||||
if (! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $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::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database) {
|
||||
throw new LogicException('Worker não isolado.');
|
||||
}
|
||||
require __DIR__.'/../Support/QualificationFixture.php';
|
||||
$f = qualificationFixture();
|
||||
auth()->guard()->setUser($f['analyst']);
|
||||
$exchange = app(QuotationExchange::class);
|
||||
$exchange->record($f['analyst'], $f['r'], ['operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => '60.1234567890',
|
||||
'quoted_on' => today()->toDateString(), 'source' => '=FONTE-SINTETICA;sem execução']);
|
||||
$quote = $f['quote'];
|
||||
$quote->update(['currency' => 'USD', 'exchange_basis' => $exchange->basis($f['r'], 'USD')]);
|
||||
$line = $f['r']->items()->sole();
|
||||
$quote->items()->create(['tenant_id' => $quote->tenant_id, 'requisition_item_id' => $line->id, 'description' => $line->description,
|
||||
'quantity' => $line->quantity, 'unit_price_minor' => 10000, 'tax_rate' => 0, 'subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000]);
|
||||
auth()->guard()->setUser($f['issuer']);
|
||||
$before = DB::table('audit_logs')->count();
|
||||
$proof = null;
|
||||
$inspected = false;
|
||||
DB::listen(function (QueryExecuted $query) use (&$proof, &$inspected): void {
|
||||
if (! $inspected && str_contains($query->sql, 'from "quotations"')) {
|
||||
$inspected = true;
|
||||
$proof = DB::selectOne("select current_setting('transaction_isolation') as isolation, current_setting('transaction_read_only') as read_only");
|
||||
}
|
||||
});
|
||||
$request = Request::create('/requisicoes/'.$f['r']->id.'/relatorio.csv');
|
||||
$request->setUserResolver(fn () => $f['issuer']);
|
||||
$response = app(ProcurementReviewReportController::class)->csv($request, $f['r'], app(ProcurementReviewReport::class), app(ProcurementReviewCsv::class));
|
||||
$content = $response->getContent();
|
||||
if ($response->getStatusCode() !== 200 || ! str_contains($content, '601235') || ! str_contains($content, "'=FONTE-SINTETICA")
|
||||
|| $proof?->isolation !== 'repeatable read' || $proof?->read_only !== 'on' || DB::table('audit_logs')->count() !== $before) {
|
||||
throw new RuntimeException('Exportação, exactidão, protecção de células ou leitura consistente não demonstradas.');
|
||||
}
|
||||
DB::table('users')->where('id', $f['issuer']->id)->update(['purchasing_role' => 'requester']);
|
||||
$revoked = false;
|
||||
try {
|
||||
app(ProcurementReviewReportController::class)->csv($request, $f['r'], app(ProcurementReviewReport::class), app(ProcurementReviewCsv::class));
|
||||
} catch (HttpExceptionInterface $error) {
|
||||
$revoked = $error->getStatusCode() === 403;
|
||||
}
|
||||
if (! $revoked) {
|
||||
throw new RuntimeException('Revogação de acesso não reaplicada.');
|
||||
}
|
||||
echo json_encode(['result' => 'passed', 'checks' => ['controller_csv', 'exact_mzn_reference', 'formula_cell_protection', 'repeatable_read_read_only', 'no_audit_write', 'revoked_cached_actor']], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
use App\Models\Requisition;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\User;
|
||||
use App\Services\QuotationExchange;
|
||||
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 Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
require __DIR__.'/../../vendor/autoload.php';
|
||||
$database = $argv[1] ?? '';
|
||||
if (! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $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::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database) {
|
||||
throw new LogicException('Worker não isolado.');
|
||||
}
|
||||
if (($argv[2] ?? '') === 'migrate') {
|
||||
if (Schema::getConnection()->getDatabaseName() !== $database || DB::connection('pgsql')->getDatabaseName() !== $database) {
|
||||
throw new LogicException('Esquema fora da base isolada.');
|
||||
}
|
||||
Artisan::call('migrate', ['--database' => 'pgsql', '--force' => true]);
|
||||
echo json_encode(['isolated_schema_prepared' => true], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
exit(0);
|
||||
}
|
||||
if (($argv[2] ?? '') === 'bank_prepare') {
|
||||
require __DIR__.'/../Support/PaymentFixture.php';
|
||||
$f = paymentFixture();
|
||||
echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $f['issuer']->id, 'supplier' => $f['supplier']->id, 'bank_data' => $f['bank_data']], JSON_THROW_ON_ERROR);
|
||||
exit(0);
|
||||
}
|
||||
if (($argv[2] ?? '') === 'prepare') {
|
||||
require __DIR__.'/../Support/QualificationFixture.php';
|
||||
$f = qualificationFixture();
|
||||
echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $f['analyst']->id, 'request' => $f['r']->id], JSON_THROW_ON_ERROR);
|
||||
exit(0);
|
||||
}
|
||||
$input = json_decode($argv[3] ?? '', true, 16, JSON_THROW_ON_ERROR);
|
||||
DB::select('select set_config(?, ?, false)', ['application_name', (($argv[2] ?? '') === 'bank_write' ? 'sgc_bank_write_' : 'sgc_fx_write_').getmypid()]);
|
||||
$actor = User::query()->findOrFail($input['actor']);
|
||||
auth()->guard()->setUser($actor);
|
||||
try {
|
||||
if (($argv[2] ?? '') === 'bank_write') {
|
||||
$detail = app(SupplierBankWorkflow::class)->propose($actor, Supplier::query()->findOrFail($input['supplier']), $input['rate']);
|
||||
} else {
|
||||
app(QuotationExchange::class)->record($actor, Requisition::query()->findOrFail($input['request']), $input['rate']);
|
||||
}
|
||||
$status = 200;
|
||||
} catch (ValidationException) {
|
||||
$status = 422;
|
||||
} catch (HttpExceptionInterface $error) {
|
||||
$status = $error->getStatusCode();
|
||||
}
|
||||
echo json_encode(['status' => $status, 'id' => isset($detail) ? $detail->id : null], JSON_THROW_ON_ERROR);
|
||||
@@ -0,0 +1,112 @@
|
||||
<?php
|
||||
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\User;
|
||||
use App\Services\ReceiptWorkflow;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
require __DIR__.'/../../vendor/autoload.php';
|
||||
$database = $argv[1] ?? '';
|
||||
$app = require __DIR__.'/../../bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database
|
||||
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)) {
|
||||
throw new LogicException('Worker de conversão fora de QA.');
|
||||
}
|
||||
config(['inventory_conversion.qa_enabled' => true]);
|
||||
if (($argv[2] ?? '') === 'prepare') {
|
||||
require __DIR__.'/../Support/ReceiptFixture.php';
|
||||
$f = receiptFixture();
|
||||
$f['stock']->update(['unit' => 'un']);
|
||||
$body = receiptPayload($f, '1.000');
|
||||
$body['items'][0]['conversion'] = ['numerator' => '12', 'denominator' => '1', 'source' => 'Embalagem sintética de corrida', 'version' => 'QA-RACE-1'];
|
||||
echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $f['receiver']->id, 'order' => $f['order']->id, 'body' => $body], JSON_THROW_ON_ERROR);
|
||||
exit;
|
||||
}
|
||||
if (($argv[2] ?? '') === 'write') {
|
||||
$input = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR);
|
||||
DB::select('select set_config(?, ?, false)', ['application_name', 'sgc_conversion_write_'.getmypid()]);
|
||||
$actor = User::query()->findOrFail($input['actor']);
|
||||
auth()->guard()->setUser($actor);
|
||||
try {
|
||||
$receipt = app(ReceiptWorkflow::class)->confirm($actor, PurchaseOrder::query()->findOrFail($input['order']), $input['body']);
|
||||
echo json_encode(['status' => 200, 'id' => $receipt->id], JSON_THROW_ON_ERROR);
|
||||
} catch (ValidationException) {
|
||||
echo json_encode(['status' => 422, 'id' => null], JSON_THROW_ON_ERROR);
|
||||
}
|
||||
exit;
|
||||
}
|
||||
if (($argv[2] ?? '') !== 'race') {
|
||||
throw new InvalidArgumentException('Modo de worker inválido.');
|
||||
}
|
||||
foreach (['same_body', 'conflicting_body'] as $scenario) {
|
||||
$prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
|
||||
$prepare->mustRun();
|
||||
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
|
||||
$workers = [];
|
||||
$db = DB::connection();
|
||||
$db->beginTransaction();
|
||||
try {
|
||||
$db->table('tenants')->where('id', $input['tenant'])->lockForUpdate()->firstOrFail();
|
||||
for ($i = 0; $i < 2; $i++) {
|
||||
if ($i === 1 && $scenario === 'conflicting_body') {
|
||||
$input['body']['items'][0]['conversion']['numerator'] = '24';
|
||||
}
|
||||
$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;
|
||||
$blocked = 0;
|
||||
do {
|
||||
$db->select('select pg_stat_clear_snapshot()');
|
||||
$blocked = (int) $db->selectOne("select count(*) as n from pg_stat_activity where datname=? and application_name like 'sgc_conversion_write_%' and wait_event_type='Lock'", [$database])->n;
|
||||
if ($blocked >= 2) {
|
||||
break;
|
||||
}
|
||||
usleep(50000);
|
||||
} while (microtime(true) < $deadline);
|
||||
if ($blocked < 2) {
|
||||
throw new RuntimeException('Contenção real não demonstrada.');
|
||||
}
|
||||
$db->commit();
|
||||
$statuses = [];
|
||||
$ids = [];
|
||||
foreach ($workers as $worker) {
|
||||
$worker->wait();
|
||||
if (! $worker->isSuccessful()) {
|
||||
throw new RuntimeException($worker->getErrorOutput());
|
||||
}
|
||||
$result = json_decode($worker->getOutput(), true, 32, JSON_THROW_ON_ERROR);
|
||||
$statuses[] = $result['status'];
|
||||
if ($result['id'] !== null) {
|
||||
$ids[] = $result['id'];
|
||||
}
|
||||
}
|
||||
sort($statuses);
|
||||
$movements = $db->table('stock_movements')->where('tenant_id', $input['tenant'])->get();
|
||||
if ($statuses !== ($scenario === 'same_body' ? [200, 200] : [200, 422]) || count(array_unique($ids)) !== 1 || $movements->count() !== 1
|
||||
|| $db->table('goods_receipts')->where('purchase_order_id', $input['order'])->count() !== 1
|
||||
|| $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', 'receipt.confirmed')->count() !== 1) {
|
||||
throw new RuntimeException('Unicidade da recepção/movimento/auditoria não demonstrada.');
|
||||
}
|
||||
$movement = $movements->sole();
|
||||
$basis = json_decode($movement->snapshot, true, 32, JSON_THROW_ON_ERROR)['quantity_conversion'];
|
||||
if ((string) $movement->quantity_milli !== $basis['accepted_stock_milli'] || $basis['accepted_document_milli'] !== '1000') {
|
||||
throw new RuntimeException('Quantidades física/documental divergentes.');
|
||||
}
|
||||
echo json_encode(['conversion_scenario' => $scenario, 'real_lock_contention' => true, 'statuses' => $statuses, 'one_receipt_movement_audit' => true], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
} finally {
|
||||
if ($db->transactionLevel() > 0) {
|
||||
$db->rollBack();
|
||||
}
|
||||
foreach ($workers as $worker) {
|
||||
if ($worker->isRunning()) {
|
||||
$worker->stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user