@@ -382,3 +382,38 @@ test('guests cannot consult or submit declarations', function () {
|
||||
$this->get('/conflitos')->assertRedirect('/login');
|
||||
$this->post('/conflitos', personalConflict($this->supplier->id))->assertRedirect('/login');
|
||||
});
|
||||
|
||||
test('composed conflict authority is scoped and never inferred from the environment', function () {
|
||||
require_once dirname(__DIR__, 2).'/packages/purchasing/src/ExecutionContext.php';
|
||||
$execution = new \Tempo\Purchasing\Composition\ExecutionContext;
|
||||
app()->instance(\Tempo\Purchasing\Composition\ExecutionContext::class, $execution);
|
||||
config(['conflict-releases.qa_enabled' => true]);
|
||||
$service = app(\App\Services\ConflictReleases::class);
|
||||
expect($service->ready())->toBeFalse();
|
||||
$this->post('/conflitos', personalConflict($this->supplier->id, $this->r->id))->assertSessionHasNoErrors();
|
||||
$declaration = ConflictDeclaration::query()->firstOrFail();
|
||||
configureConflictDirection($this->admin);
|
||||
$this->actingAs($this->admin);
|
||||
app()->instance('env', 'budget-testing');
|
||||
$metadata = ['contract' => $execution::CONTRACT, 'composition' => 'b4093c6f6707', 'operation' => 'purchasing_conflicts.authorise',
|
||||
'scope' => ['tenant_id' => 1, 'company_id' => 2, 'unit_id' => 2],
|
||||
'actor' => ['host_id' => 15, 'native_id' => $this->admin->id],
|
||||
'generation' => str_repeat('a', 64), 'schema_sha256' => str_repeat('b', 64),
|
||||
'workflow_sha256' => str_repeat('c', 64), 'features' => ['conflict-release' => []]];
|
||||
$input = ['operation_key' => (string) Str::uuid(), 'reason' => 'Autorização sintética de direcção no contexto composto.'];
|
||||
$before = $declaration->getAttributes();
|
||||
try {
|
||||
$execution->within($metadata, DB::connection(), fn () => null, function () use ($service, $input, $declaration) {
|
||||
expect($service->ready())->toBeTrue();
|
||||
$first = $service->authorise($this->admin, $declaration, $input);
|
||||
expect($service->authorise($this->admin, $declaration, $input)->id)->toBe($first->id)
|
||||
->and(ConflictRelease::query()->count())->toBe(1);
|
||||
DB::table('organization_memberships')->where('user_id', $this->admin->id)->delete();
|
||||
expect(fn () => $service->authorise($this->admin, $declaration, $input))->toThrow(\Symfony\Component\HttpKernel\Exception\HttpException::class);
|
||||
});
|
||||
expect($service->ready())->toBeFalse()->and($declaration->fresh()->getAttributes())->toBe($before);
|
||||
} finally {
|
||||
app()->instance('env', 'testing');
|
||||
app()->forgetInstance(\Tempo\Purchasing\Composition\ExecutionContext::class);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
use Tempo\Purchasing\Composition\ExecutionContext;
|
||||
|
||||
require_once dirname(__DIR__, 2).'/packages/purchasing/src/ExecutionContext.php';
|
||||
|
||||
function compositionDeclaration(): array
|
||||
{
|
||||
return ['contract' => ExecutionContext::CONTRACT, 'composition' => 'b4093c6f6707', 'operation' => 'purchasing_conflicts.authorise',
|
||||
'scope' => ['tenant_id' => 1, 'company_id' => 2, 'unit_id' => 2], 'actor' => ['host_id' => 15, 'native_id' => 1],
|
||||
'generation' => str_repeat('a', 64), 'schema_sha256' => str_repeat('b', 64), 'workflow_sha256' => str_repeat('c', 64),
|
||||
'features' => ['conflict-release' => []]];
|
||||
}
|
||||
|
||||
test('capability exists only within the checked connection and execution', function () {
|
||||
$context = new ExecutionContext;
|
||||
$db = new stdClass;
|
||||
$checks = 0;
|
||||
expect($context->allows('conflict-release', $db))->toBeFalse();
|
||||
$result = $context->within(compositionDeclaration(), $db, function () use (&$checks) {
|
||||
$checks++;
|
||||
}, function () use ($context, $db) {
|
||||
expect($context->allows('conflict-release', $db))->toBeTrue()
|
||||
->and($context->allows('conflict-release', new stdClass))->toBeFalse()
|
||||
->and($context->allows('order-cancellation-cycles', $db))->toBeFalse();
|
||||
|
||||
return 'complete';
|
||||
});
|
||||
expect($checks)->toBe(3)->and($result)->toBe('complete')->and($context->allows('conflict-release', $db))->toBeFalse();
|
||||
});
|
||||
|
||||
test('revocation is rechecked and an exception clears the execution', function () {
|
||||
$context = new ExecutionContext;
|
||||
$db = new stdClass;
|
||||
$authorised = true;
|
||||
try {
|
||||
$context->within(compositionDeclaration(), $db, function () use (&$authorised) {
|
||||
if (! $authorised) {
|
||||
throw new RuntimeException('revoked');
|
||||
}
|
||||
}, function () use ($context, $db, &$authorised) {
|
||||
$authorised = false;
|
||||
$context->allows('conflict-release', $db);
|
||||
});
|
||||
} catch (RuntimeException $error) {
|
||||
expect($error->getMessage())->toBe('revoked');
|
||||
}
|
||||
expect($context->allows('conflict-release', $db))->toBeFalse();
|
||||
});
|
||||
|
||||
test('invalid declarations never enter the business closure', function (string $case) {
|
||||
$declaration = compositionDeclaration();
|
||||
match ($case) {
|
||||
'contract' => $declaration['contract'] = 'unknown',
|
||||
'extra' => $declaration['admin'] = true,
|
||||
'hash' => $declaration['workflow_sha256'] = 'unknown',
|
||||
'scope' => $declaration['scope']['unit_id'] = null,
|
||||
'identity' => $declaration['actor']['native_id'] = 0,
|
||||
'feature' => $declaration['features']['all'] = [],
|
||||
'component' => $declaration['features']['order-cancellation-cycles'] = ['root' => '/unknown'],
|
||||
};
|
||||
(new ExecutionContext)->within($declaration, new stdClass, fn () => null, fn () => throw new RuntimeException('business executed'));
|
||||
})->with(['contract', 'extra', 'hash', 'scope', 'identity', 'feature', 'component'])->throws(LogicException::class);
|
||||
|
||||
test('nested execution cannot replace the original authority', function () {
|
||||
$context = new ExecutionContext;
|
||||
$db = new stdClass;
|
||||
$context->within(compositionDeclaration(), $db, fn () => null, function () use ($context, $db) {
|
||||
expect(fn () => $context->within(compositionDeclaration(), $db, fn () => null, fn () => null))->toThrow(LogicException::class);
|
||||
expect($context->allows('conflict-release', $db))->toBeTrue();
|
||||
});
|
||||
expect($context->allows('conflict-release', $db))->toBeFalse();
|
||||
});
|
||||
|
||||
test('read authority cannot execute a write even when the feature is available', function () {
|
||||
$context = new ExecutionContext;
|
||||
$db = new stdClass;
|
||||
$declaration = compositionDeclaration();
|
||||
$declaration['operation'] = 'purchasing_conflicts.view';
|
||||
$context->within($declaration, $db, fn () => null, function () use ($context, $db) {
|
||||
expect($context->allows('conflict-release', $db))->toBeTrue()
|
||||
->and($context->permits('purchasing_conflicts.view', $db))->toBeTrue()
|
||||
->and($context->permits('purchasing_conflicts.authorise', $db))->toBeFalse();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,218 @@
|
||||
<?php
|
||||
|
||||
use Tempo\Purchasing\Delivery\CodeDeployment;
|
||||
|
||||
require_once __DIR__.'/../../integrations/sgf/operational/CodeDeployment.php';
|
||||
|
||||
function deploymentV2Write(string $path, string $body): void
|
||||
{
|
||||
if (! is_dir(dirname($path))) {
|
||||
mkdir(dirname($path), 0700, true);
|
||||
}
|
||||
file_put_contents($path, $body);
|
||||
}
|
||||
|
||||
function deploymentV2Fixture(): array
|
||||
{
|
||||
$root = dirname(__DIR__, 2).'/storage/framework/testing/deployment-v2-'.bin2hex(random_bytes(6));
|
||||
$host = $root.'/host';
|
||||
deploymentV2Write($host.'/app/Existing.php', 'original');
|
||||
deploymentV2Write($host.'/packages/purchasing/current.json', '{"version":"0.1.1"}');
|
||||
deploymentV2Write($host.'/storage/framework/down', '{}');
|
||||
deploymentV2Write($host.'/bootstrap/cache/config.php', '<?php return [];');
|
||||
|
||||
return [$root, $host, new CodeDeployment($host)];
|
||||
}
|
||||
|
||||
function deploymentV2Bundle(string $root, array $bodies, array $before, string $format = 'v2', ?string $from = null, array $added = [], array $schema = []): array
|
||||
{
|
||||
$dir = $root.'/bundle-'.bin2hex(random_bytes(4));
|
||||
$files = [];
|
||||
$overlays = [];
|
||||
foreach ($bodies as $file => $body) {
|
||||
deploymentV2Write($dir.'/'.$file, $body);
|
||||
$files[$file] = hash('sha256', $body);
|
||||
$overlays[$file] = ['before_sha256' => $before[$file], 'after_sha256' => $files[$file]];
|
||||
}
|
||||
$manifest = ['format' => 'tempo.operational-review.'.$format, 'support_files' => $files, 'host_overlays' => $overlays];
|
||||
if ($format === 'v2') {
|
||||
$manifest['composition_transition'] = ['from_manifest_sha256' => $from, 'added_files' => $added, 'schema_files' => $schema];
|
||||
}
|
||||
deploymentV2Write($dir.'/manifest.json', json_encode($manifest, JSON_THROW_ON_ERROR));
|
||||
|
||||
return [$dir, hash_file('sha256', $dir.'/manifest.json')];
|
||||
}
|
||||
|
||||
function deploymentV2Apply(CodeDeployment $deploy, string $dir, string $hash): array
|
||||
{
|
||||
$plan = $deploy->plan($dir, $hash);
|
||||
|
||||
return $deploy->apply($dir, $hash, $plan['target_sha256'], 'Synthetic file-only rehearsal', true);
|
||||
}
|
||||
|
||||
test('v1 still applies replays and restores its exact code cache and module pointer', function () {
|
||||
[$root, $host, $deploy] = deploymentV2Fixture();
|
||||
[$dir, $hash] = deploymentV2Bundle($root, ['app/Existing.php' => 'v1'], ['app/Existing.php' => hash('sha256', 'original')], 'v1');
|
||||
$result = deploymentV2Apply($deploy, $dir, $hash);
|
||||
expect(deploymentV2Apply($deploy, $dir, $hash)['replayed'])->toBeTrue();
|
||||
$deploy->rollback($result['deployment_id'], 'Synthetic recovery', true);
|
||||
expect(file_get_contents($host.'/app/Existing.php'))->toBe('original')
|
||||
->and(file_get_contents($host.'/bootstrap/cache/config.php'))->toBe('<?php return [];')
|
||||
->and(file_get_contents($host.'/packages/purchasing/current.json'))->toBe('{"version":"0.1.1"}');
|
||||
});
|
||||
|
||||
test('v2 expands v1 updates new files and recovers their original absence in order', function () {
|
||||
[$root, $host, $deploy] = deploymentV2Fixture();
|
||||
[$v1, $h1] = deploymentV2Bundle($root, ['app/Existing.php' => 'v1'], ['app/Existing.php' => hash('sha256', 'original')], 'v1');
|
||||
$first = deploymentV2Apply($deploy, $v1, $h1);
|
||||
[$v2, $h2] = deploymentV2Bundle($root, ['app/Existing.php' => 'v2', 'config/merchandise.php' => '<?php return false;'],
|
||||
['app/Existing.php' => hash('sha256', 'v1'), 'config/merchandise.php' => null], 'v2', $h1, ['config/merchandise.php' => null]);
|
||||
$secondPlan = $deploy->plan($v2, $h2);
|
||||
$second = deploymentV2Apply($deploy, $v2, $h2);
|
||||
expect($deploy->apply($v2, $h2, $secondPlan['target_sha256'], 'Replay same operation', true)['replayed'])->toBeTrue()
|
||||
->and(file_get_contents($host.'/config/merchandise.php'))->toBe('<?php return false;');
|
||||
[$v3, $h3] = deploymentV2Bundle($root, ['app/Existing.php' => 'v3', 'config/merchandise.php' => '<?php return null;'],
|
||||
['app/Existing.php' => hash('sha256', 'v2'), 'config/merchandise.php' => hash('sha256', '<?php return false;')], 'v2', $h2);
|
||||
$third = deploymentV2Apply($deploy, $v3, $h3);
|
||||
$deploy->rollback($third['deployment_id'], 'Recover third', true);
|
||||
expect(file_get_contents($host.'/config/merchandise.php'))->toBe('<?php return false;');
|
||||
$deploy->rollback($second['deployment_id'], 'Recover second', true);
|
||||
expect(file_exists($host.'/config/merchandise.php'))->toBeFalse()
|
||||
->and(file_get_contents($host.'/app/Existing.php'))->toBe('v1');
|
||||
$deploy->rollback($first['deployment_id'], 'Recover first', true);
|
||||
expect(file_get_contents($host.'/app/Existing.php'))->toBe('original');
|
||||
});
|
||||
|
||||
test('v2 rejects an undeclared expansion wrong predecessor or existing supposedly new file', function (string $case) {
|
||||
[$root, $host, $deploy] = deploymentV2Fixture();
|
||||
$added = ['config/merchandise.php' => null];
|
||||
if ($case === 'undeclared') {
|
||||
$added = [];
|
||||
}
|
||||
if ($case === 'existing') {
|
||||
deploymentV2Write($host.'/config/merchandise.php', 'preserve');
|
||||
}
|
||||
[$dir, $hash] = deploymentV2Bundle($root, ['config/merchandise.php' => 'new'], ['config/merchandise.php' => null], 'v2', $case === 'predecessor' ? str_repeat('a', 64) : null, $added);
|
||||
expect(fn () => $deploy->plan($dir, $hash))->toThrow(RuntimeException::class);
|
||||
expect(file_get_contents($host.'/app/Existing.php'))->toBe('original');
|
||||
})->with(['undeclared', 'predecessor', 'existing']);
|
||||
|
||||
test('v2 partial failure recovers newly created files without touching unknown edits', function (bool $unknownEdit) {
|
||||
[$root, $host, $deploy] = deploymentV2Fixture();
|
||||
[$dir, $hash] = deploymentV2Bundle($root, ['app/New.php' => 'candidate', 'app/Existing.php' => 'updated'],
|
||||
['app/New.php' => null, 'app/Existing.php' => hash('sha256', 'original')], 'v2', null,
|
||||
['app/New.php' => null, 'app/Existing.php' => hash('sha256', 'original')]);
|
||||
$plan = $deploy->plan($dir, $hash);
|
||||
try {
|
||||
$deploy->apply($dir, $hash, $plan['target_sha256'], 'Synthetic interruption', true, function ($point) {
|
||||
if ($point === 'file:app/New.php') {
|
||||
throw new RuntimeException('Synthetic interruption');
|
||||
}
|
||||
});
|
||||
test()->fail('Expected interruption.');
|
||||
} catch (RuntimeException $error) {
|
||||
expect($error->getMessage())->toBe('Synthetic interruption');
|
||||
}
|
||||
if ($unknownEdit) {
|
||||
deploymentV2Write($host.'/app/New.php', 'user edit');
|
||||
expect(fn () => $deploy->rollback($plan['deployment_id'], 'Recover', true))->toThrow(RuntimeException::class)
|
||||
->and(file_get_contents($host.'/app/New.php'))->toBe('user edit');
|
||||
} else {
|
||||
$deploy->rollback($plan['deployment_id'], 'Recover', true);
|
||||
expect(file_exists($host.'/app/New.php'))->toBeFalse();
|
||||
}
|
||||
expect(file_get_contents($host.'/app/Existing.php'))->toBe('original');
|
||||
})->with([false, true]);
|
||||
|
||||
test('v2 requires an exact schema receipt and pins it to the reviewed target', function () {
|
||||
[$root, $host, $deploy] = deploymentV2Fixture();
|
||||
$file = 'database/sql/synthetic.sql';
|
||||
$body = '-- synthetic, never executed';
|
||||
$schema = [$file => ['before' => null, 'after' => hash('sha256', $body)]];
|
||||
[$dir, $hash] = deploymentV2Bundle($root, [$file => $body], [$file => null], 'v2', null, [$file => null], $schema);
|
||||
expect(fn () => $deploy->plan($dir, $hash))->toThrow(RuntimeException::class);
|
||||
$receiptPath = $host.'/storage/app/private/module-deployments/schema-transition-'.$hash.'.json';
|
||||
$receipt = ['from_manifest_sha256' => null, 'to_manifest_sha256' => $hash, 'host' => str_replace('\\', '/', realpath($host)), 'schema_verified' => true, 'changes' => $schema];
|
||||
deploymentV2Write($receiptPath, json_encode($receipt, JSON_THROW_ON_ERROR));
|
||||
$plan = $deploy->plan($dir, $hash);
|
||||
$receipt['review_reference'] = 'changed after planning';
|
||||
deploymentV2Write($receiptPath, json_encode($receipt, JSON_THROW_ON_ERROR));
|
||||
expect(fn () => $deploy->apply($dir, $hash, $plan['target_sha256'], 'Synthetic', true))->toThrow(RuntimeException::class);
|
||||
expect(file_exists($host.'/'.$file))->toBeFalse();
|
||||
});
|
||||
|
||||
test('v2 rejects forbidden paths extra content and equivalent Windows paths', function (string $case) {
|
||||
[$root, $host, $deploy] = deploymentV2Fixture();
|
||||
[$dir] = deploymentV2Bundle($root, ['app/New.php' => 'candidate'], ['app/New.php' => null], 'v2', null, ['app/New.php' => null]);
|
||||
$manifest = json_decode(file_get_contents($dir.'/manifest.json'), true, 32, JSON_THROW_ON_ERROR);
|
||||
if ($case === 'extra') {
|
||||
deploymentV2Write($dir.'/unexpected.php', 'unlisted');
|
||||
} elseif ($case === 'equivalent') {
|
||||
$manifest['support_files']['app/new.php'] = hash('sha256', 'candidate');
|
||||
} elseif ($case === 'hash') {
|
||||
deploymentV2Write($dir.'/app/New.php', 'tampered');
|
||||
} elseif ($case === 'format') {
|
||||
$manifest['format'] = 'tempo.operational-review.v999';
|
||||
} else {
|
||||
$manifest['host_overlays'] = [$case => $manifest['host_overlays']['app/New.php']];
|
||||
}
|
||||
deploymentV2Write($dir.'/manifest.json', json_encode($manifest, JSON_THROW_ON_ERROR));
|
||||
expect(fn () => $deploy->plan($dir, hash_file('sha256', $dir.'/manifest.json')))->toThrow(RuntimeException::class);
|
||||
expect(file_exists($host.'/app/New.php'))->toBeFalse();
|
||||
})->with(['extra', 'equivalent', 'hash', 'format', '../outside.php', '.env', 'public/vendor/secret.php', 'packages/purchasing/current.json', 'routes/console.php']);
|
||||
|
||||
test('v2 update interruption restores the prior bundle at each durable stage', function (string $point) {
|
||||
[$root, $host, $deploy] = deploymentV2Fixture();
|
||||
[$v1, $h1] = deploymentV2Bundle($root, ['app/Existing.php' => 'v1'], ['app/Existing.php' => hash('sha256', 'original')], 'v1');
|
||||
$first = deploymentV2Apply($deploy, $v1, $h1);
|
||||
[$v2, $h2] = deploymentV2Bundle($root, ['app/Existing.php' => 'v2', 'public/sgf-new.mjs' => 'candidate'],
|
||||
['app/Existing.php' => hash('sha256', 'v1'), 'public/sgf-new.mjs' => null], 'v2', $h1, ['public/sgf-new.mjs' => null]);
|
||||
$plan = $deploy->plan($v2, $h2);
|
||||
try {
|
||||
$deploy->apply($v2, $h2, $plan['target_sha256'], 'Interrupt update', true, function ($at) use ($point) {
|
||||
if ($at === $point) {
|
||||
throw new RuntimeException('Synthetic interruption');
|
||||
}
|
||||
});
|
||||
test()->fail('Expected interruption.');
|
||||
} catch (RuntimeException $error) {
|
||||
expect($error->getMessage())->toBe('Synthetic interruption');
|
||||
}
|
||||
$deploy->rollback($plan['deployment_id'], 'Recover update', true);
|
||||
expect(file_get_contents($host.'/app/Existing.php'))->toBe('v1')
|
||||
->and(file_exists($host.'/public/sgf-new.mjs'))->toBeFalse()
|
||||
->and(hash_file('sha256', $host.'/packages/internal-requisitions/manifest.json'))->toBe($h1)
|
||||
->and(json_decode(file_get_contents($host.'/storage/app/private/module-deployments/current.json'), true)['deployment_id'])->toBe($first['deployment_id']);
|
||||
})->with(['prepared', 'caches-cleared', 'file:app/Existing.php', 'file:public/sgf-new.mjs', 'previous-bundle-preserved', 'bundle-switched']);
|
||||
|
||||
test('deployment uses the verified staged bytes instead of a mutable source directory', function () {
|
||||
[$root, $host, $deploy] = deploymentV2Fixture();
|
||||
[$dir, $hash] = deploymentV2Bundle($root, ['app/New.php' => 'candidate'], ['app/New.php' => null], 'v2', null, ['app/New.php' => null]);
|
||||
$plan = $deploy->plan($dir, $hash);
|
||||
$result = $deploy->apply($dir, $hash, $plan['target_sha256'], 'Stage isolation', true, function ($point) use ($dir) {
|
||||
if ($point === 'prepared') {
|
||||
deploymentV2Write($dir.'/app/New.php', 'source changed after staging');
|
||||
}
|
||||
});
|
||||
expect(file_get_contents($host.'/app/New.php'))->toBe('candidate');
|
||||
$deploy->rollback($result['deployment_id'], 'Recover', true);
|
||||
expect(file_exists($host.'/app/New.php'))->toBeFalse();
|
||||
});
|
||||
|
||||
test('v2 refuses links in either payload or destination', function (string $side) {
|
||||
[$root, $host, $deploy] = deploymentV2Fixture();
|
||||
deploymentV2Write($root.'/outside/New.php', 'preserve outside host');
|
||||
$file = $side === 'host' ? 'app/Linked/New.php' : 'app/New.php';
|
||||
[$dir, $hash] = deploymentV2Bundle($root, [$file => 'candidate'], [$file => null], 'v2', null, [$file => null]);
|
||||
if ($side === 'host') {
|
||||
$linked = @symlink($root.'/outside', $host.'/app/Linked');
|
||||
} else {
|
||||
unlink($dir.'/app/New.php');
|
||||
$linked = @symlink($root.'/outside/New.php', $dir.'/app/New.php');
|
||||
}
|
||||
if (! $linked) {
|
||||
test()->markTestSkipped('Creating symbolic links is unavailable; no privileges were changed.');
|
||||
}
|
||||
expect(fn () => $deploy->plan($dir, $hash))->toThrow(RuntimeException::class);
|
||||
expect(file_get_contents($root.'/outside/New.php'))->toBe('preserve outside host');
|
||||
})->with(['host', 'bundle']);
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
test('composition loads only its verified local calculation when explicitly enabled', function (string $mode) {
|
||||
$root = dirname(__DIR__, 2);
|
||||
$bundle = $root.'/storage/framework/testing/cost-bootstrap-'.bin2hex(random_bytes(6));
|
||||
mkdir($bundle, 0700, true);
|
||||
foreach (['integrations/sgf/operational/bootstrap.php', 'integrations/sgf/operational/RuntimeContext.php', 'integrations/sgf/operational/Composition.php', 'integrations/sgf/sourcing/bootstrap.php'] as $stub) {
|
||||
if (! is_dir(dirname($bundle.'/'.$stub))) {
|
||||
mkdir(dirname($bundle.'/'.$stub), 0700, true);
|
||||
}
|
||||
file_put_contents($bundle.'/'.$stub, '<?php // Test double for unrelated application boot.');
|
||||
}
|
||||
copy($root.'/integrations/sgf/operational/entry.php', $bundle.'/bootstrap.php');
|
||||
$relative = 'packages/purchasing/src/StockCosting.php';
|
||||
mkdir(dirname($bundle.'/'.$relative), 0700, true);
|
||||
copy($root.'/packages/purchasing/src/StockCosting.php', $bundle.'/'.$relative);
|
||||
$pin = hash_file('sha256', $bundle.'/'.$relative);
|
||||
file_put_contents($bundle.'/manifest.json', json_encode(['format' => 'tempo.operational-review.v2', 'support_files' => [$relative => $pin]], JSON_THROW_ON_ERROR));
|
||||
if ($mode === 'tampered') {
|
||||
file_put_contents($bundle.'/'.$relative, '<?php // tampered');
|
||||
}
|
||||
if ($mode === 'disabled') {
|
||||
unlink($bundle.'/'.$relative);
|
||||
}
|
||||
$script = 'require '.var_export($root.'/vendor/autoload.php', true).';'
|
||||
.'Illuminate\\Container\\Container::getInstance()->instance("config", new Illuminate\\Config\\Repository(["merchandise_invoices"=>["costs_enabled"=>'.($mode === 'disabled' ? 'false' : 'true').']]));';
|
||||
if ($mode === 'different_loaded_version') {
|
||||
file_put_contents($bundle.'/different.php', '<?php namespace Tempo\\Purchasing\\Inventory; final class StockCosting {}');
|
||||
$script .= 'require '.var_export($bundle.'/different.php', true).';';
|
||||
}
|
||||
$script .= 'try { require '.var_export($bundle.'/bootstrap.php', true).'; echo "BOOT_OK:".(int)class_exists(Tempo\\Purchasing\\Inventory\\StockCosting::class,false); } catch (RuntimeException $error) { echo "REFUSED:".$error->getMessage(); }';
|
||||
// Subprocess avoids sharing a PHP class definition between composition variants.
|
||||
$process = proc_open([PHP_BINARY, '-r', $script], [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes);
|
||||
expect(is_resource($process))->toBeTrue();
|
||||
fclose($pipes[0]);
|
||||
$out = stream_get_contents($pipes[1]);
|
||||
$error = stream_get_contents($pipes[2]);
|
||||
fclose($pipes[1]);
|
||||
fclose($pipes[2]);
|
||||
expect(proc_close($process))->toBe(0, $error);
|
||||
expect($out)->toStartWith(in_array($mode, ['tampered', 'different_loaded_version'], true) ? 'REFUSED:' : 'BOOT_OK:'.($mode === 'disabled' ? '0' : '1'));
|
||||
})->with(['enabled', 'disabled', 'tampered', 'different_loaded_version']);
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
require_once dirname(__DIR__, 2).'/scripts/lib/SgfWorkflowExtension.php';
|
||||
|
||||
test('workflow namespace transfer preserves rule strings comments and SQL', function () {
|
||||
$source = <<<'PHP'
|
||||
<?php
|
||||
namespace App\Services;
|
||||
use App\Models\User;
|
||||
// App\Models\User is a comment, not a PHP name token.
|
||||
final class Example {
|
||||
public function run(\App\Models\User $user): string {
|
||||
$literal = 'App\Models\User';
|
||||
$sql = "SELECT 'App\\Models\\User'";
|
||||
return $literal;
|
||||
}
|
||||
}
|
||||
PHP;
|
||||
$output = SgfWorkflowExtension::transform($source);
|
||||
expect($output)->toContain('namespace Tempo\Purchasing\Embedded\Services;')
|
||||
->toContain('use Tempo\Purchasing\Embedded\Models\User;')
|
||||
->toContain('run(\Tempo\Purchasing\Embedded\Models\User $user)')
|
||||
->toContain("'App\\Models\\User'")->toContain('// App\Models\User is a comment')
|
||||
->toContain('SELECT \'App\\\\Models\\\\User\'');
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
require_once dirname(__DIR__, 2).'/scripts/lib/SgfWorkflowInventory.php';
|
||||
|
||||
beforeEach(function () {
|
||||
$this->inventoryRoot = sys_get_temp_dir().'/sgf-inventory-'.bin2hex(random_bytes(8));
|
||||
mkdir($this->inventoryRoot.'/source/app', 0700, true);
|
||||
mkdir($this->inventoryRoot.'/bundle/app', 0700, true);
|
||||
file_put_contents($this->inventoryRoot.'/source/app/Workflow.php', '<?php // current');
|
||||
file_put_contents($this->inventoryRoot.'/bundle/app/Workflow.php', '<?php // embedded');
|
||||
$this->manifest = ['files' => ['app/Workflow.php' => hash_file('sha256', $this->inventoryRoot.'/bundle/app/Workflow.php')],
|
||||
'originals' => ['app/Workflow.php' => hash_file('sha256', $this->inventoryRoot.'/source/app/Workflow.php')]];
|
||||
$this->inspect = function (?array $manifest = null, array $paths = ['app/Workflow.php']) {
|
||||
file_put_contents($this->inventoryRoot.'/bundle/manifest.json', json_encode($manifest ?? $this->manifest));
|
||||
|
||||
return SgfWorkflowInventory::inspect($this->inventoryRoot.'/source', $this->inventoryRoot.'/bundle',
|
||||
hash_file('sha256', $this->inventoryRoot.'/bundle/manifest.json'), ['process' => $paths]);
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->inventoryRoot, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST);
|
||||
foreach ($iterator as $file) {
|
||||
$file->isDir() && ! $file->isLink() ? rmdir($file->getPathname()) : unlink($file->getPathname());
|
||||
}
|
||||
rmdir($this->inventoryRoot);
|
||||
});
|
||||
|
||||
test('recognises preserved source without claiming functional acceptance', function () {
|
||||
$result = ($this->inspect)();
|
||||
expect($result['processes']['process']['source_equivalent'])->toBeTrue()
|
||||
->and($result['functional_acceptance'])->toBeFalse()->and($result['read_only'])->toBeTrue();
|
||||
});
|
||||
|
||||
test('reports source drift rather than treating old acceptance as current', function () {
|
||||
file_put_contents($this->inventoryRoot.'/source/app/Workflow.php', '<?php // changed');
|
||||
$result = ($this->inspect)();
|
||||
expect($result['processes']['process']['source_equivalent'])->toBeFalse()
|
||||
->and($result['processes']['process']['components']['app/Workflow.php']['status'])->toBe('source_changed');
|
||||
});
|
||||
|
||||
test('distinguishes missing source from untransferred source', function () {
|
||||
file_put_contents($this->inventoryRoot.'/source/app/New.php', '<?php // new');
|
||||
$result = ($this->inspect)(null, ['app/New.php', 'app/Missing.php']);
|
||||
expect($result['processes']['process']['components']['app/New.php']['status'])->toBe('not_transferred')
|
||||
->and($result['processes']['process']['components']['app/Missing.php']['status'])->toBe('source_missing');
|
||||
});
|
||||
|
||||
test('refuses tampering anywhere in the distributed bundle', function () {
|
||||
file_put_contents($this->inventoryRoot.'/bundle/app/Workflow.php', '<?php // tampered');
|
||||
($this->inspect)();
|
||||
})->throws(RuntimeException::class, 'Workflow bundle integrity failure.');
|
||||
|
||||
test('refuses unsafe manifest paths', function (string $path) {
|
||||
($this->inspect)(['files' => [$path => str_repeat('a', 64)], 'originals' => []]);
|
||||
})->with(['../outside.php', '/absolute.php', 'C:/outside.php', 'app/../outside.php', 'app\\outside.php'])
|
||||
->throws(RuntimeException::class, 'Invalid workflow path.');
|
||||
|
||||
test('refuses an unpinned manifest', function () {
|
||||
file_put_contents($this->inventoryRoot.'/bundle/manifest.json', json_encode($this->manifest));
|
||||
SgfWorkflowInventory::inspect($this->inventoryRoot.'/source', $this->inventoryRoot.'/bundle', str_repeat('0', 64), []);
|
||||
})->throws(RuntimeException::class, 'Unrecognised workflow manifest.');
|
||||
|
||||
test('does not accept an original hash without its distributed file', function () {
|
||||
$manifest = $this->manifest;
|
||||
$manifest['files'] = [];
|
||||
$result = ($this->inspect)($manifest);
|
||||
expect($result['processes']['process']['source_equivalent'])->toBeFalse()
|
||||
->and($result['processes']['process']['components']['app/Workflow.php']['status'])->toBe('not_transferred');
|
||||
});
|
||||
|
||||
test('requires both source and distributed inventories', function () {
|
||||
($this->inspect)(['files' => $this->manifest['files']]);
|
||||
})->throws(RuntimeException::class, 'Original and distributed hashes required.');
|
||||
@@ -76,3 +76,61 @@ test('half cent rounds upwards and the last issue receives the residual', functi
|
||||
test('an unrecognised rounding policy cannot silently change costs', function () {
|
||||
expect(fn () => StockCosting::project('fifo', costingOpening(), [], 'automatic'))->toThrow(InvalidArgumentException::class);
|
||||
});
|
||||
|
||||
test('approved zero issues preserve half up and the exact final balance', function (string $method, array $quantities, array $amounts) {
|
||||
$facts = [costingReceipt(1, 1000, 1)];
|
||||
foreach ($quantities as $index => $quantity) {
|
||||
$facts[] = costingIssue($index + 2, $quantity);
|
||||
}
|
||||
$result = StockCosting::project($method, costingOpening(), $facts, 'half_up_final_balance');
|
||||
expect(array_column(array_column(array_slice($result['movements'], 1), 'value'), 'amount_minor'))->toBe($amounts)
|
||||
->and($result['closing']['quantity_milli'])->toBe(0)
|
||||
->and($result['closing']['value']['amount_minor'])->toBe('0')
|
||||
->and($result['stock_written'])->toBeFalse()->and($result['journals_written'])->toBeFalse();
|
||||
})->with([
|
||||
['fifo', [100, 400, 500], ['0', '0', '1']],
|
||||
['weighted_average', [100, 400, 500], ['0', '0', '1']],
|
||||
['fifo', [500, 100, 400], ['1', '0', '0']],
|
||||
['weighted_average', [500, 100, 400], ['1', '0', '0']],
|
||||
]);
|
||||
|
||||
test('supplier return uses its identified receipt rather than the oldest or average price', function (string $method, string $nextCost) {
|
||||
$facts = [costingReceipt(1, 1000, 100), costingReceipt(2, 1000, 300),
|
||||
['id' => 3, 'reference' => 'synthetic-return-3', 'kind' => 'receipt_return', 'quantity_milli' => 500, 'receipt_reference' => 'synthetic-receipt-2', 'value_minor' => 150], costingIssue(4, 500)];
|
||||
$result = StockCosting::project($method, costingOpening(), $facts, 'half_up_final_balance');
|
||||
expect($result['movements'][2]['value']['amount_minor'])->toBe('150')
|
||||
->and($result['movements'][3]['value']['amount_minor'])->toBe($nextCost)
|
||||
->and($result['movements'][0]['value']['amount_minor'])->toBe('100')
|
||||
->and($result['stock_written'])->toBeFalse()->and($result['journals_written'])->toBeFalse();
|
||||
})->with([['fifo', '50'], ['weighted_average', '83']]);
|
||||
|
||||
test('returning an exhausted original layer requires reconciliation without changing prior costs', function (string $method) {
|
||||
$facts = [costingReceipt(1, 1000, 100), costingIssue(2, 1000), costingReceipt(3, 1000, 300),
|
||||
['id' => 4, 'reference' => 'synthetic-return-4', 'kind' => 'receipt_return', 'quantity_milli' => 500, 'receipt_reference' => 'synthetic-receipt-1']];
|
||||
expect(fn () => StockCosting::project($method, costingOpening(), $facts))->toThrow(DomainException::class);
|
||||
expect(StockCosting::project($method, costingOpening(), array_slice($facts, 0, 3))['movements'][1]['value']['amount_minor'])->toBe('100');
|
||||
})->with(['fifo', 'weighted_average']);
|
||||
|
||||
test('FIFO skips a completely returned layer and never consumes its value again', function () {
|
||||
$facts = [costingReceipt(1, 1000, 100), costingReceipt(2, 1000, 300),
|
||||
['id' => 3, 'reference' => 'synthetic-return-3', 'kind' => 'receipt_return', 'quantity_milli' => 1000, 'receipt_reference' => 'synthetic-receipt-1'], costingIssue(4, 1000)];
|
||||
$result = StockCosting::project('fifo', costingOpening(), $facts);
|
||||
expect($result['movements'][3]['value']['amount_minor'])->toBe('300')->and($result['closing']['value']['amount_minor'])->toBe('0');
|
||||
});
|
||||
|
||||
test('an incompatible posted return is refused instead of rewriting a journal', function () {
|
||||
$facts = [costingReceipt(1, 1000, 100), ['id' => 2, 'reference' => 'synthetic-return-2', 'kind' => 'receipt_return', 'quantity_milli' => 500, 'receipt_reference' => 'synthetic-receipt-1', 'value_minor' => 51]];
|
||||
expect(fn () => StockCosting::project('fifo', costingOpening(), $facts))->toThrow(DomainException::class);
|
||||
});
|
||||
|
||||
test('approved reconstructed layers retain receipt cost for a return and conserve the final balance', function (string $method) {
|
||||
$opening = ['reference' => 'approved-opening-1', 'quantity_milli' => 2000, 'value_minor' => 400,
|
||||
'layers' => [['reference' => 'original-receipt-1', 'quantity_milli' => 1000, 'value_minor' => 100],
|
||||
['reference' => 'reconciled-balance-1', 'quantity_milli' => 1000, 'value_minor' => 300]]];
|
||||
$facts = [['id' => 10, 'reference' => 'return-10', 'kind' => 'receipt_return', 'quantity_milli' => 500, 'receipt_reference' => 'original-receipt-1', 'value_minor' => 50], costingIssue(11, 1500)];
|
||||
$result = StockCosting::project($method, $opening, $facts, 'half_up_final_balance');
|
||||
expect($result['movements'][0]['value']['amount_minor'])->toBe('50')
|
||||
->and($result['movements'][1]['value']['amount_minor'])->toBe('350')
|
||||
->and($result['closing']['value']['amount_minor'])->toBe('0')
|
||||
->and($result['closing']['quantity_milli'])->toBe(0);
|
||||
})->with(['fifo', 'weighted_average']);
|
||||
|
||||
Reference in New Issue
Block a user