189 lines
11 KiB
PHP
189 lines
11 KiB
PHP
<?php
|
|
|
|
use App\Models\PurchaseOrder;
|
|
use App\Models\User;
|
|
use App\Services\OrderCancellationWorkflow;
|
|
use App\Services\ReceiptWorkflow;
|
|
use App\Services\SupplierPayables;
|
|
use Illuminate\Contracts\Console\Kernel;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Str;
|
|
use Illuminate\Validation\ValidationException;
|
|
use Symfony\Component\Process\Process;
|
|
|
|
require __DIR__.'/../../vendor/autoload.php';
|
|
$database = $argv[1] ?? '';
|
|
$operational = getenv('COMPRAS_STANDALONE_CONVERSION_QA') === '1';
|
|
$app = require __DIR__.'/../../bootstrap/app.php';
|
|
$app->make(Kernel::class)->bootstrap();
|
|
if (! $app->environment($operational ? ['testing', 'standalone-qa'] : ['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.');
|
|
}
|
|
if ($operational && (DB::connection()->getConfig('host') !== '127.0.0.1' || (string) DB::connection()->getConfig('port') !== '55439'
|
|
|| DB::selectOne("select current_setting('cluster_name') as name")->name !== 'sgf_modular_regression_'.substr($database, -12))) {
|
|
throw new LogicException('Owned standalone conversion cluster required.');
|
|
}
|
|
if (($argv[2] ?? '') === 'prepare-runtime' && $operational) {
|
|
require __DIR__.'/../Support/StandaloneCompositionFixture.php';
|
|
prepareSyntheticStandaloneRuntime();
|
|
echo 'synthetic_standalone_inventory_prepared';
|
|
exit;
|
|
}
|
|
config(['inventory_conversion.qa_enabled' => ! $operational, 'inventory_conversion.enabled' => $operational]);
|
|
if (($argv[2] ?? '') === 'prepare-analytics-preview' && $operational) {
|
|
require __DIR__.'/../Support/PaymentFixture.php';
|
|
$f = paymentFixture(['Material', 'Serviços']);
|
|
$payables = app(SupplierPayables::class);
|
|
foreach ([$f['author'], $f['validator']] as $actor) {
|
|
foreach (['view', 'prepare', 'validate', 'payments_view', 'payment_prepare', 'payment_confirm', 'allocation_prepare', 'allocation_confirm'] as $action) {
|
|
DB::table('pa_access')->insert(['tenant_id' => $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0,
|
|
'user_id' => $actor->id, 'person' => 'synthetic-analytics-finance-'.$actor->id, 'action' => $action]);
|
|
}
|
|
}
|
|
auth()->guard()->setUser($f['author']);
|
|
$proposal = $payables->engine($f['author'])->command('prepare', $f['invoice']->id, 'Synthetic analytics invoice', (string) Str::uuid());
|
|
auth()->guard()->setUser($f['validator']);
|
|
$recognised = $payables->engine($f['validator'])->command('validate', $proposal['proposal_id'], 'Independent synthetic invoice recognition', (string) Str::uuid());
|
|
$run = static function (User $actor, string $action, array $data) use ($payables): array {
|
|
auth()->guard()->setUser($actor);
|
|
|
|
return $payables->settlements($actor)->command($action, $data, (string) Str::uuid());
|
|
};
|
|
$payment = $run($f['author'], 'payment-prepare', ['obligation_id' => $recognised['obligation_id'],
|
|
'source_revision' => $recognised['source_revision'], 'amount' => '40.00', 'currency' => 'MZN', 'paid_on' => today()->toDateString(),
|
|
'fact_reference' => 'DOC-ANALYTICS-SYNTHETIC', 'evidence_reference' => 'DOC-ANALYTICS-EVIDENCE', 'reason' => 'Explicit synthetic payment fact for analytical review']);
|
|
$run($f['validator'], 'payment-decide', ['payment_id' => $payment['payment_id'], 'decision' => 'confirmed',
|
|
'evidence_reference' => 'DOC-ANALYTICS-CONFIRMED', 'reason' => 'Independent synthetic payment confirmation']);
|
|
$allocation = $run($f['author'], 'allocation-prepare', ['payment_id' => $payment['payment_id'], 'reference' => 'DOC-ANALYTICS-ALLOCATION',
|
|
'allocations' => [['obligation_id' => $recognised['obligation_id'], 'source_revision' => $recognised['source_revision'], 'amount' => '40.00']],
|
|
'reason' => 'Explicit synthetic invoice allocation']);
|
|
$run($f['validator'], 'allocation-decide', ['proposal_id' => $allocation['proposal_id'], 'decision' => 'confirmed',
|
|
'reason' => 'Independent synthetic allocation confirmation']);
|
|
$allocationId = (int) DB::table('ps_allocations')->where('payment_id', $payment['payment_id'])->value('id');
|
|
$f['validator']->update(['email' => 'analytics-finance@example.test', 'name' => 'Finance synthetic analytics review']);
|
|
echo json_encode(['actor_email' => $f['validator']->email, 'tenant_id' => $f['tenant']->id,
|
|
'order_id' => $f['order']->id, 'allocation_id' => $allocationId, 'payment_amount_minor' => 4000,
|
|
'attribution_route' => '/afectacoes-fornecedores/'.$allocationId.'/imputacao', 'report_route' => '/relatorios'], JSON_THROW_ON_ERROR);
|
|
exit;
|
|
}
|
|
if (($argv[2] ?? '') === 'prepare-cancellation-preview' && $operational) {
|
|
require __DIR__.'/../Support/IssuedOrderCancellationFixture.php';
|
|
config(['order_cancellation.enabled' => true]);
|
|
$fixture = new class extends stdClass
|
|
{
|
|
public function actingAs(User $actor): void
|
|
{
|
|
auth()->guard()->setUser($actor);
|
|
}
|
|
};
|
|
issuedOrderCancellationFixture($fixture, 2);
|
|
$workflow = app(OrderCancellationWorkflow::class);
|
|
$fixture->actingAs($fixture->buyer);
|
|
$record = $workflow->request($fixture->buyer, $fixture->f['order'], $fixture->data);
|
|
$fixture->actingAs($fixture->finance);
|
|
$workflow->decide($fixture->finance, $record, 'approved', 'Independent synthetic cycle-aware cancellation preview');
|
|
$fixture->finance->update(['email' => 'cancellation-finance@example.test', 'name' => 'Finance synthetic cancellation review']);
|
|
echo json_encode(['actor_email' => $fixture->finance->email, 'tenant_id' => $fixture->f['tenant']->id,
|
|
'order_id' => $fixture->f['order']->id, 'cancellation_id' => $record->id, 'source_cycle' => 2, 'state' => 'approved'], JSON_THROW_ON_ERROR);
|
|
exit;
|
|
}
|
|
if (in_array($argv[2] ?? '', ['prepare', 'prepare-preview'], true)) {
|
|
require __DIR__.'/../Support/ReceiptFixture.php';
|
|
$f = receiptFixture();
|
|
$f['stock']->update(['unit' => 'un']);
|
|
if (($argv[2] ?? '') === 'prepare-preview' && $operational) {
|
|
$f['receiver']->update(['email' => 'conversion-warehouse@example.test', 'name' => 'Warehouse synthetic conversion review']);
|
|
echo json_encode(['actor_email' => $f['receiver']->email, 'tenant_id' => $f['tenant']->id, 'order_id' => $f['order']->id], JSON_THROW_ON_ERROR);
|
|
exit;
|
|
}
|
|
$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), $operational ? ['APP_ENV' => 'testing'] : null, 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();
|
|
}
|
|
}
|
|
}
|
|
}
|