@@ -0,0 +1,157 @@
|
||||
"""Backup, isolated recovery and atomic selection of the expressly authorised synthetic demo."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import secrets
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
|
||||
def run(args, **kwargs):
|
||||
result = subprocess.run(args, text=True, capture_output=True, **kwargs)
|
||||
if result.returncode:
|
||||
raise RuntimeError(f"Command failed: {args[0]} {args[1:3]}\n{result.stderr[-1200:]}\n{result.stdout[-1200:]}")
|
||||
return result.stdout
|
||||
|
||||
|
||||
def sql(database, statement):
|
||||
return run(['runuser', '-u', 'postgres', '--', 'psql', '-X', '-v', 'ON_ERROR_STOP=1', '-At', '-d', database, '-c', statement]).strip()
|
||||
|
||||
|
||||
def frames(database):
|
||||
tables = sql(database, "SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename").splitlines()
|
||||
result = {}
|
||||
for table in tables:
|
||||
assert table.replace('_', '').isalnum()
|
||||
result[table] = sql(database, 'SELECT md5(COALESCE(string_agg(j,chr(10) ORDER BY j),\'\')) FROM (SELECT row_to_json(t)::text AS j FROM "'+table+'" t) s')
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
assert os.geteuid() == 0 and sys.argv[1] == '--activate-authorized-synthetic'
|
||||
base = Path('/var/www/compras-deploy')
|
||||
demo = base / 'demonstration-20261129'
|
||||
release = base / 'releases/presentation-20261129'
|
||||
previous = Path((demo / 'previous-release.txt').read_text())
|
||||
assert (base / 'current').resolve() == previous
|
||||
assert json.loads((demo / 'evidence-check.json').read_text())['state'] == 'passed'
|
||||
finance = run(['php', 'scripts/check-public-demo-finance.php', '--read-only'], cwd=release)
|
||||
assert json.loads(finance)['state'] == 'passed'
|
||||
(demo / 'finance-check.json').write_text(finance)
|
||||
http = run(['python3', '/root/check-public-demonstration.py', '--check-authorized-synthetic'])
|
||||
assert json.loads(http)['state'] == 'passed'
|
||||
(demo / 'staging-http-check.json').write_text(http)
|
||||
backup = Path('/var/backups/compras-presentation-20261129')
|
||||
assert not backup.exists(), 'Do not overwrite an existing deployment backup'
|
||||
backup.mkdir(mode=0o700)
|
||||
shutil.copy2(previous / '.env', backup / 'previous.env.private')
|
||||
(backup / 'previous-release.txt').write_text(str(previous))
|
||||
previous_hash = hashlib.sha256((previous / '.env').read_bytes()).hexdigest()
|
||||
for database, name in [('compras_db', 'previous.dump'), ('compras_demo_20261129', 'demonstration.dump')]:
|
||||
with (backup / name).open('xb') as out:
|
||||
result = subprocess.run(['runuser', '-u', 'postgres', '--', 'pg_dump', '-Fc', '-d', database], stdout=out, stderr=subprocess.PIPE)
|
||||
assert result.returncode == 0, result.stderr.decode()[:500]
|
||||
run(['pg_restore', '--list', str(backup / name)])
|
||||
original = frames('compras_demo_20261129')
|
||||
recovery = 'compras_demo_recovery_20261129'
|
||||
assert not sql('postgres', f"SELECT datname FROM pg_database WHERE datname='{recovery}'")
|
||||
recovery_role = 'compras_demo_recovery_app_20261129'
|
||||
recovery_password = secrets.token_hex(32)
|
||||
sql('postgres', f"CREATE ROLE {recovery_role} LOGIN PASSWORD '{recovery_password}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS")
|
||||
run(['runuser', '-u', 'postgres', '--', 'createdb', '-O', recovery_role, recovery])
|
||||
try:
|
||||
restore_env = {**os.environ, 'PGPASSWORD': recovery_password}
|
||||
with (backup / 'demonstration.dump').open('rb') as source:
|
||||
restored = subprocess.run(['pg_restore', '-h', '127.0.0.1', '-U', recovery_role, '--no-owner', '--no-acl', '-d', recovery],
|
||||
stdin=source, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=restore_env)
|
||||
assert restored.returncode == 0, restored.stderr.decode()[:800]
|
||||
assert frames(recovery) == original, 'Synthetic backup recovery mismatch'
|
||||
recovery_env = {**os.environ, 'DB_DATABASE': recovery, 'DB_USERNAME': recovery_role, 'DB_PASSWORD': recovery_password,
|
||||
'APP_CONFIG_CACHE': str(demo / 'storage/framework/cache/recovery-config.php'),
|
||||
'COMPRAS_RUNTIME_ENABLED': 'false', 'COMPRAS_RUNTIME_PREPARE_ONLY': 'true', 'COMPRAS_RUNTIME_INSTALLATION_ID': str(uuid.uuid4())}
|
||||
run(['php', 'artisan', 'compras:runtime:prepare', '--expected-database='+recovery, '--expected-role='+recovery_role,
|
||||
'--operator=Tempo presentation recovery', '--reason=Explicit synthetic restoration and new installation binding verification', '--rebind', '--apply'], cwd=release, env=recovery_env)
|
||||
rebound = frames(recovery)
|
||||
assert {k:v for k,v in rebound.items() if k != 'compras_runtime_installations'} == {k:v for k,v in original.items() if k != 'compras_runtime_installations'}
|
||||
recovery_env.update({'COMPRAS_RUNTIME_ENABLED': 'true', 'COMPRAS_RUNTIME_PREPARE_ONLY': 'false'})
|
||||
boot = "require 'vendor/autoload.php';$a=require 'bootstrap/app.php';$a->make(Illuminate\\Contracts\\Console\\Kernel::class)->bootstrap();$r=app(App\\Services\\StandaloneRuntime::class);foreach($r::FEATURES as $f){if(!$r->feature($f,Illuminate\\Support\\Facades\\DB::connection()))throw new LogicException('Recovery capability unavailable');}echo '24 recovery capabilities verified';"
|
||||
assert run(['php', '-r', boot], cwd=release, env=recovery_env) == '24 recovery capabilities verified'
|
||||
finally:
|
||||
run(['runuser', '-u', 'postgres', '--', 'dropdb', recovery])
|
||||
sql('postgres', f'DROP ROLE {recovery_role}')
|
||||
units = Path('/etc/systemd/system')
|
||||
service = units / 'compras-demo-operations.service'
|
||||
timer = units / 'compras-demo-operations.timer'
|
||||
assert not service.exists() and not timer.exists(), 'Do not replace an existing service'
|
||||
service.write_text(f'''[Unit]
|
||||
Description=Compras synthetic presentation recurring operations
|
||||
After=postgresql.service
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=www-data
|
||||
Group=www-data
|
||||
WorkingDirectory={release}
|
||||
ExecStart=/usr/bin/php artisan sgc:approval-deadlines-tick
|
||||
ExecStart=/usr/bin/php artisan sgc:replenishment-tick
|
||||
TimeoutStartSec=60
|
||||
UMask=0077
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
ReadWritePaths={demo}/storage
|
||||
''')
|
||||
timer.write_text('''[Unit]
|
||||
Description=Compras synthetic presentation minute observation
|
||||
|
||||
[Timer]
|
||||
OnBootSec=60
|
||||
OnUnitActiveSec=60
|
||||
Unit=compras-demo-operations.service
|
||||
AccuracySec=5
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
''')
|
||||
run(['systemd-analyze', 'verify', str(service), str(timer)])
|
||||
run(['systemctl', 'daemon-reload'])
|
||||
run(['systemctl', 'start', service.name])
|
||||
before_restart = frames('compras_demo_20261129')
|
||||
run(['systemctl', 'restart', service.name])
|
||||
after_restart = frames('compras_demo_20261129')
|
||||
changed = [name for name in before_restart if before_restart[name] != after_restart[name]]
|
||||
assert set(changed).issubset({'replenishment_work'}), changed
|
||||
assert run(['systemctl', 'show', service.name, '-p', 'ExecMainStatus', '--value']).strip() == '0'
|
||||
assert hashlib.sha256((previous / '.env').read_bytes()).hexdigest() == previous_hash
|
||||
assert (base / 'current').resolve() == previous
|
||||
temporary = base / 'current.presentation.tmp'
|
||||
assert not temporary.exists() and not temporary.is_symlink()
|
||||
temporary.symlink_to(release, target_is_directory=True)
|
||||
os.replace(temporary, base / 'current')
|
||||
try:
|
||||
run(['systemctl', 'enable', '--now', timer.name])
|
||||
public = run(['python3', '/root/check-public-demonstration.py', '--check-authorized-synthetic', 'https://compras.tempo.co.mz'])
|
||||
assert json.loads(public)['state'] == 'passed'
|
||||
(demo / 'public-http-check.json').write_text(public)
|
||||
except BaseException:
|
||||
run(['systemctl', 'disable', '--now', timer.name])
|
||||
temporary.symlink_to(previous, target_is_directory=True)
|
||||
os.replace(temporary, base / 'current')
|
||||
raise
|
||||
result = {'state': 'passed', 'domain': 'https://compras.tempo.co.mz', 'release': str(release), 'previous_release': str(previous),
|
||||
'synthetic_database': 'compras_demo_20261129', 'previous_database_unchanged_by_deployment': True, 'previous_env_hash_preserved': previous_hash,
|
||||
'backup': str(backup), 'synthetic_recovery_tables_exact': len(original), 'recovery_database_removed': True,
|
||||
'recovery_new_native_binding_and_24_capabilities_verified': True, 'recovery_business_tables_preserved_after_rebind': True,
|
||||
'worker_runs_as': 'www-data', 'worker_restart_exit': 0, 'business_tables_unchanged_by_worker_restart': True,
|
||||
'worker_restart_changed_tables': changed, 'interactive_windows_session_required': False, 'timer_enabled': True,
|
||||
'host_reboot_executed': False, 'jue_or_bank_external_execution': False}
|
||||
(demo / 'activation.json').write_text(json.dumps(result, indent=2))
|
||||
print(json.dumps(result, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Apply the existing local functional capabilities to the same public product."""
|
||||
from pathlib import Path
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
root = Path('/var/www/compras-deploy/current').resolve()
|
||||
assert root == Path('/var/www/compras-deploy/releases/presentation-20261129')
|
||||
snapshot = json.loads(subprocess.check_output(['/usr/bin/php', str(root/'scripts/compare-compras-installation.php'), '--public-read-only']))
|
||||
assert all(snapshot['history_schema'].values()) and len(snapshot['features']) == 24 and all(snapshot['features'].values())
|
||||
env = (root/'.env').resolve()
|
||||
assert env == Path('/var/www/compras-deploy/demonstration-20261129/.env')
|
||||
backup = Path('/var/backups/compras-presentation-20261129/unified-functional-flags')
|
||||
backup.mkdir(mode=0o700, exist_ok=False)
|
||||
shutil.copy2(env, backup/'selected.env.private')
|
||||
(backup/'selected.env.private').chmod(0o600)
|
||||
updates = {'COMMON_PAYABLES_ENABLED': 'true', 'COMMON_PAYABLES_HISTORY_ENABLED': 'true', 'SGC_GEOGRAPHY_ENABLED': 'true',
|
||||
'SGC_PROCUREMENT_FINANCE_SEARCH_ENABLED': 'true', 'SGC_REQUISITION_APPROVAL_LEVELS_ENABLED': 'true',
|
||||
'SGC_PUBLIC_NAVIGATION': 'false'}
|
||||
lines = env.read_text().splitlines()
|
||||
for key, value in updates.items():
|
||||
matches = [i for i, line in enumerate(lines) if line.startswith(key+'=')]
|
||||
assert len(matches) <= 1
|
||||
if matches:
|
||||
lines[matches[0]] = key+'='+value
|
||||
else:
|
||||
lines.append(key+'='+value)
|
||||
temp = env.with_name(env.name+'.functional-next')
|
||||
temp.write_text('\n'.join(lines)+'\n')
|
||||
attrs = env.stat()
|
||||
temp.chmod(attrs.st_mode & 0o777)
|
||||
os.chown(temp, attrs.st_uid, attrs.st_gid)
|
||||
os.replace(temp, env)
|
||||
try:
|
||||
subprocess.run(['runuser', '-u', 'www-data', '--', '/usr/bin/php', 'artisan', 'config:cache'], cwd=root, check=True)
|
||||
after = json.loads(subprocess.check_output(['/usr/bin/php', str(root/'scripts/compare-compras-installation.php'), '--public-read-only']))
|
||||
for key in ['common-payables.enabled', 'common-payables.history_enabled', 'geography.enabled',
|
||||
'procurement_search.finance_metadata_enabled', 'requisition_approval.enabled']:
|
||||
assert after['deployment_flags'][key] is True
|
||||
assert after['deployment_flags']['public_navigation.enabled'] is False
|
||||
except BaseException:
|
||||
shutil.copyfile(backup/'selected.env.private', env)
|
||||
subprocess.run(['runuser', '-u', 'www-data', '--', '/usr/bin/php', 'artisan', 'config:cache'], cwd=root, check=True)
|
||||
raise
|
||||
proof = {'state': 'passed', 'settings_aligned': updates, 'company_rules_and_permissions_changed': False,
|
||||
'business_data_changed': False, 'original_archives_and_runtime_components_preserved': True,
|
||||
'backup': str(backup), 'anonymous_business_pages': 'normal authenticated application access'}
|
||||
(backup/'result.json').write_text(json.dumps(proof, indent=2)+'\n')
|
||||
print(json.dumps(proof))
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\OrganizationConfiguration;
|
||||
use App\Services\WorkContext;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
if (($argv[1] ?? '') !== '--align-authorized-synthetic' || config('app.demonstration') !== true
|
||||
|| DB::connection()->getDatabaseName() !== 'compras_demo_20261129') {
|
||||
throw new LogicException('Only the authorised public sample company may be aligned.');
|
||||
}
|
||||
$backup = '/var/backups/compras-presentation-20261129/context-alignment';
|
||||
if (! is_file($backup.'/selected.env.private') || ! is_file($backup.'/database.dump')) {
|
||||
throw new LogicException('Private recovery files required before changing configuration.');
|
||||
}
|
||||
$result = DB::transaction(function () use ($backup): array {
|
||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ');
|
||||
$actor = User::query()->where('email', 'admin@demo.compras.tempo.co.mz')->sole();
|
||||
if ($actor->tenant_id !== 2) {
|
||||
throw new LogicException('Unexpected company.');
|
||||
}
|
||||
auth()->guard()->setUser($actor);
|
||||
$company = Tenant::query()->whereKey(2)->lockForUpdate()->firstOrFail();
|
||||
if ($company->work_context_policy !== null) {
|
||||
throw new LogicException('Preserve an already configured company.');
|
||||
}
|
||||
$options = array_keys(WorkContext::OPTIONS);
|
||||
if (app(WorkContext::class)->purchased($actor) !== $options) {
|
||||
throw new LogicException('The selected installation must expose the same four pilot contexts.');
|
||||
}
|
||||
$profiles = DB::table('organization_profiles')->where('tenant_id', 2)->orderBy('id')->get();
|
||||
$excluded = ['tenants', 'organization_profiles', 'organization_access', 'audit_logs',
|
||||
'sessions', 'cache', 'cache_locks', 'jobs', 'failed_jobs', 'job_batches'];
|
||||
$tables = collect(DB::select('select tablename from pg_tables where schemaname=current_schema()'))->pluck('tablename')->diff($excluded)->sort()->values();
|
||||
$digest = static function () use ($tables): array {
|
||||
$values = [];
|
||||
foreach ($tables as $table) {
|
||||
$rows = DB::table($table)->get()->map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR))->sort()->values()->all();
|
||||
$values[$table] = hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
return $values;
|
||||
};
|
||||
$before = $digest();
|
||||
file_put_contents($backup.'/contexts.before.private.json', json_encode(['company' => $company->toArray(), 'profiles' => $profiles->all(), 'protected_table_hashes' => $before], JSON_THROW_ON_ERROR));
|
||||
chmod($backup.'/contexts.before.private.json', 0600);
|
||||
$service = app(OrganizationConfiguration::class);
|
||||
foreach ($profiles as $profile) {
|
||||
$service->execute($actor, 'profile', ['version' => DB::table('organization_access')->where('tenant_id', 2)->value('version'),
|
||||
'id' => $profile->id, 'name' => $profile->name, 'permissions' => json_decode($profile->permissions, true, 32, JSON_THROW_ON_ERROR),
|
||||
'work_contexts' => $options, 'reason' => 'Reposicao expressamente pedida do painel do piloto na empresa sintetica, sem alterar competencias.']);
|
||||
}
|
||||
$service->execute($actor, 'work_contexts', ['version' => DB::table('organization_access')->where('tenant_id', 2)->value('version'),
|
||||
'enabled' => $options, 'confirm' => true, 'reason' => 'Aplicar o mesmo painel de contextos do piloto, por pedido expresso do proprietario.']);
|
||||
foreach ($profiles as $profile) {
|
||||
$after = DB::table('organization_profiles')->where('id', $profile->id)->first();
|
||||
if ($after->name !== $profile->name || json_decode($after->permissions, true) !== json_decode($profile->permissions, true)
|
||||
|| json_decode($after->work_contexts, true) !== $options) {
|
||||
throw new LogicException('Profile competencies must remain unchanged.');
|
||||
}
|
||||
}
|
||||
if ($digest() !== $before) {
|
||||
throw new LogicException('An unrelated table changed; roll back the entire alignment.');
|
||||
}
|
||||
$available = app(WorkContext::class)->available($actor->fresh());
|
||||
if ($available !== $options) {
|
||||
throw new LogicException('Administration must see the same four pilot choices.');
|
||||
}
|
||||
|
||||
return ['state' => 'passed', 'company_id' => 2, 'context_options' => $options, 'administration_available_contexts' => $available,
|
||||
'profiles_aligned' => $profiles->count(), 'profile_permissions_and_names_preserved' => true,
|
||||
'unrelated_tables_preserved' => count($before), 'native_configuration_commands' => true,
|
||||
'operational_flags_preserved' => array_map(fn ($v) => $v['operational'], WorkContext::OPTIONS),
|
||||
'original_pilot_or_previous_public_database_changed' => false];
|
||||
});
|
||||
file_put_contents($backup.'/result.json', json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
|
||||
echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Assemble one immutable Compras delivery, without settings, business data or credentials."""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
root = Path.cwd().resolve()
|
||||
manifest_bytes = (root / 'compras-release.json').read_bytes()
|
||||
manifest = json.loads(manifest_bytes)
|
||||
assert len(sys.argv) == 6, 'frontend-directory output.zip finance-root inventory-root cancellation-root'
|
||||
frontend = Path(sys.argv[1]).resolve()
|
||||
output = Path(sys.argv[2]).resolve()
|
||||
assert not output.exists(), 'Never overwrite a frozen delivery'
|
||||
entries = {'compras-release.json': manifest_bytes}
|
||||
exact = set(manifest.get('exact_source_files', []))
|
||||
|
||||
|
||||
def add(name, source, expected, normalise=False):
|
||||
assert not Path(name).is_absolute() and '..' not in Path(name).parts and name not in entries
|
||||
assert source.is_file() and not source.is_symlink()
|
||||
data = source.read_bytes()
|
||||
assert hashlib.sha256(data.replace(b'\r\n', b'\n') if normalise else data).hexdigest() == expected, name
|
||||
entries[name] = data
|
||||
|
||||
|
||||
for name, digest in manifest['source_files'].items():
|
||||
add(name, root / name, digest, manifest.get('source_eol') == 'lf' and name not in exact)
|
||||
add('public/build/manifest.json', frontend / 'manifest.json', manifest['frontend']['manifest_sha256'])
|
||||
add('public/build/fonts-manifest.json', frontend / 'fonts-manifest.json', manifest['frontend']['fonts_manifest_sha256'])
|
||||
for name, digest in manifest['frontend']['files'].items():
|
||||
add('public/build/'+name, frontend / name, digest)
|
||||
for definition, label, directory in zip(manifest['components'], ['finance', 'inventory', 'cancellation'], sys.argv[3:], strict=True):
|
||||
component = Path(directory).resolve()
|
||||
add('runtime/'+label+'/manifest.json', component / 'manifest.json', definition['manifest_sha256'])
|
||||
definition = json.loads((component / 'manifest.json').read_bytes())
|
||||
files = definition['files']
|
||||
files = {entry['file']: entry['sha256'] for entry in files} if isinstance(files, list) else files
|
||||
for name, digest in files.items():
|
||||
assert (component / name).resolve().is_relative_to(component)
|
||||
add('runtime/'+label+'/'+name, component / name, digest)
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
with zipfile.ZipFile(output, 'x', zipfile.ZIP_DEFLATED) as archive:
|
||||
for directory in ['bootstrap/cache/', 'storage/app/private/', 'storage/app/public/', 'storage/framework/cache/data/', 'storage/framework/sessions/', 'storage/framework/views/', 'storage/logs/']:
|
||||
entry = zipfile.ZipInfo(directory); entry.external_attr = (stat.S_IFDIR | 0o750) << 16
|
||||
archive.writestr(entry, b'')
|
||||
for name, data in sorted(entries.items()):
|
||||
entry = zipfile.ZipInfo(name); entry.external_attr = (stat.S_IFREG | 0o644) << 16
|
||||
archive.writestr(entry, data, compress_type=zipfile.ZIP_DEFLATED)
|
||||
proof = {'product': 'compras', 'release_id': manifest['release_id'], 'archive': str(output), 'files': len(entries),
|
||||
'sha256': hashlib.sha256(output.read_bytes()).hexdigest(), 'credentials_or_business_data': False}
|
||||
Path('docs/proofs/compras-release-artifact.json').write_text(json.dumps(proof, indent=2)+'\n', encoding='utf-8')
|
||||
print(json.dumps(proof))
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Private recovery delta for the single installed release, without exporting credentials."""
|
||||
from pathlib import Path
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tarfile
|
||||
|
||||
root = Path('/var/www/compras-deploy/current').resolve()
|
||||
assert root == Path('/var/www/compras-deploy/releases/presentation-20261129')
|
||||
identity = json.loads((root/'compras-release.json').read_text())['release_id']
|
||||
assert identity == 'compras-a2711a98b34fceb3'
|
||||
destination = Path('/var/backups/compras-presentation-20261129/consolidation/current')
|
||||
destination.mkdir(mode=0o700, exist_ok=False)
|
||||
shutil.copy2((root/'.env').resolve(), destination/'selected.env.private')
|
||||
(destination/'selected.env.private').chmod(0o600)
|
||||
with (destination/'database.dump').open('xb') as stream:
|
||||
subprocess.run(['runuser', '-u', 'postgres', '--', 'pg_dump', '-Fc', '-d', 'compras_demo_20261129'], stdout=stream, check=True)
|
||||
subprocess.run(['pg_restore', '--list', str(destination/'database.dump')], stdout=subprocess.DEVNULL, check=True)
|
||||
subprocess.run(['tar', '-czf', str(destination/'storage.tar.gz'), '-C', str((root/'storage').resolve()), '.'], check=True)
|
||||
subprocess.run(['tar', '-czf', str(destination/'code.tar.gz'), '--exclude=./storage', '--exclude=./.env', '--exclude=./bootstrap/cache/config.php', '-C', str(root), '.'], check=True)
|
||||
private = (root/'storage').resolve()/'app/private'
|
||||
verified = 0
|
||||
with tarfile.open(destination/'storage.tar.gz') as archive:
|
||||
for source in private.rglob('*'):
|
||||
assert not source.is_symlink()
|
||||
if source.is_file():
|
||||
name = './'+str(source.relative_to((root/'storage').resolve()))
|
||||
assert hashlib.sha256(archive.extractfile(name).read()).hexdigest() == hashlib.sha256(source.read_bytes()).hexdigest()
|
||||
verified += 1
|
||||
for name in ['compras-operations.service', 'compras-operations.timer']:
|
||||
shutil.copy2(Path('/etc/systemd/system')/name, destination/name)
|
||||
shutil.copy2('/var/www/deploy/compras-tempo-deploy.sh', destination/'publisher.sh')
|
||||
proof = {'state': 'passed', 'release_id': identity, 'backup': str(destination), 'private_files_verified_in_backup': verified,
|
||||
'database_archive_readable': True, 'full_database_restore': 'prior final-backup.json, no schema delta',
|
||||
'hashes': {name: hashlib.sha256((destination/name).read_bytes()).hexdigest() for name in ['database.dump', 'storage.tar.gz', 'code.tar.gz']}}
|
||||
(destination/'result.json').write_text(json.dumps(proof, indent=2)+'\n')
|
||||
print(json.dumps(proof))
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Private final synthetic backup and recovery; no changes to the selected live installation."""
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import uuid
|
||||
|
||||
s = importlib.util.spec_from_file_location('activation', '/root/activate-public-demonstration.py')
|
||||
m = importlib.util.module_from_spec(s); s.loader.exec_module(m)
|
||||
assert os.geteuid() == 0 and sys.argv[1] == '--backup-authorized-synthetic'
|
||||
base = Path('/var/www/compras-deploy')
|
||||
demo = base / 'demonstration-20261129'
|
||||
release = base / 'releases/presentation-20261129'
|
||||
assert (base / 'current').resolve() == release
|
||||
backup = Path('/var/backups/compras-presentation-20261129/final')
|
||||
if backup.exists():
|
||||
assert '--resume-owned-backup' in sys.argv and not (demo / 'final-backup.json').exists(), 'Preserve completed recovery evidence'
|
||||
assert (backup / 'demonstration.env.private').read_bytes() == (demo / '.env').read_bytes()
|
||||
assert all((backup / name).is_file() for name in ['database.dump', 'storage.tar.gz', 'code.tar.gz'])
|
||||
m.run(['pg_restore', '--list', str(backup / 'database.dump')])
|
||||
else:
|
||||
backup.mkdir(mode=0o700)
|
||||
shutil.copy2(demo / '.env', backup / 'demonstration.env.private')
|
||||
os.chmod(backup / 'demonstration.env.private', 0o600)
|
||||
with (backup / 'database.dump').open('xb') as stream:
|
||||
result = subprocess.run(['runuser', '-u', 'postgres', '--', 'pg_dump', '-Fc', '-d', 'compras_demo_20261129'], stdout=stream, stderr=subprocess.PIPE)
|
||||
assert result.returncode == 0, result.stderr.decode()[:500]
|
||||
m.run(['tar', '-czf', str(backup / 'storage.tar.gz'), '-C', str(demo / 'storage'), '.'])
|
||||
m.run(['tar', '-czf', str(backup / 'code.tar.gz'), '--exclude=./storage', '--exclude=./.env', '--exclude=./bootstrap/cache/config.php', '-C', str(release), '.'])
|
||||
files = backup / 'recovered-storage'; files.mkdir(mode=0o700, exist_ok=True)
|
||||
verified_files = 0
|
||||
with tarfile.open(backup / 'storage.tar.gz') as archive:
|
||||
for member in archive.getmembers():
|
||||
assert not Path(member.name).is_absolute() and '..' not in Path(member.name).parts and (member.isfile() or member.isdir())
|
||||
target = files / member.name
|
||||
assert not target.is_symlink() and (target.resolve() == files.resolve() or target.resolve().is_relative_to(files.resolve()))
|
||||
if member.isfile() and target.exists():
|
||||
assert hashlib.sha256(target.read_bytes()).digest() == hashlib.sha256(archive.extractfile(member).read()).digest()
|
||||
archive.extractall(files)
|
||||
for member in archive.getmembers():
|
||||
if member.isfile():
|
||||
assert hashlib.sha256(archive.extractfile(member).read()).digest() == hashlib.sha256((files / member.name).read_bytes()).digest()
|
||||
verified_files += 1
|
||||
technical = {'sessions', 'cache', 'cache_locks', 'jobs', 'failed_jobs', 'job_batches', 'replenishment_work'}
|
||||
original = m.frames('compras_demo_20261129')
|
||||
recovery = 'compras_demo_final_recovery_20261129'
|
||||
role = 'compras_demo_final_recovery_app'
|
||||
password = secrets.token_hex(32)
|
||||
assert not m.sql('postgres', f"SELECT datname FROM pg_database WHERE datname='{recovery}'")
|
||||
m.sql('postgres', f"CREATE ROLE {role} LOGIN PASSWORD '{password}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS")
|
||||
m.run(['runuser', '-u', 'postgres', '--', 'createdb', '-O', role, recovery])
|
||||
try:
|
||||
with (backup / 'database.dump').open('rb') as source:
|
||||
restored = subprocess.run(['pg_restore', '-h', '127.0.0.1', '-U', role, '--no-owner', '--no-acl', '-d', recovery],
|
||||
stdin=source, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env={**os.environ, 'PGPASSWORD': password})
|
||||
assert restored.returncode == 0, restored.stderr.decode()[:800]
|
||||
before = m.frames(recovery)
|
||||
assert {k:v for k,v in before.items() if k not in technical} == {k:v for k,v in original.items() if k not in technical}
|
||||
environment = {**os.environ, 'DB_DATABASE': recovery, 'DB_USERNAME': role, 'DB_PASSWORD': password,
|
||||
'APP_CONFIG_CACHE': str(demo / 'storage/framework/cache/final-recovery-config.php'),
|
||||
'COMPRAS_RUNTIME_ENABLED': 'false', 'COMPRAS_RUNTIME_PREPARE_ONLY': 'true', 'COMPRAS_RUNTIME_INSTALLATION_ID': str(uuid.uuid4())}
|
||||
m.run(['php', 'artisan', 'compras:runtime:prepare', '--expected-database='+recovery, '--expected-role='+role,
|
||||
'--operator=Tempo final presentation recovery', '--reason=Final synthetic presentation recovery with preserved original documents', '--rebind', '--apply'], cwd=release, env=environment)
|
||||
after = m.frames(recovery)
|
||||
assert {k:v for k,v in after.items() if k != 'compras_runtime_installations'} == {k:v for k,v in before.items() if k != 'compras_runtime_installations'}
|
||||
environment.update({'COMPRAS_RUNTIME_ENABLED': 'true', 'COMPRAS_RUNTIME_PREPARE_ONLY': 'false'})
|
||||
boot = "require 'vendor/autoload.php';$a=require 'bootstrap/app.php';$a->make(Illuminate\\Contracts\\Console\\Kernel::class)->bootstrap();$r=app(App\\Services\\StandaloneRuntime::class);foreach($r::FEATURES as $f){if(!$r->feature($f,Illuminate\\Support\\Facades\\DB::connection()))throw new LogicException('Recovery capability unavailable');}echo '24 recovery capabilities verified';"
|
||||
assert m.run(['php', '-r', boot], cwd=release, env=environment) == '24 recovery capabilities verified'
|
||||
finally:
|
||||
m.run(['runuser', '-u', 'postgres', '--', 'dropdb', recovery])
|
||||
m.sql('postgres', 'DROP ROLE '+role)
|
||||
assert (base / 'current').resolve() == release
|
||||
proof = {'state': 'passed', 'private_backup': str(backup), 'database_tables': len(before),
|
||||
'business_tables_equal_after_restore': len([k for k in before if k not in technical]), 'all_tables_preserved_after_native_rebind_except_installation_history': True,
|
||||
'restored_capabilities': 24, 'storage_files_restored_and_hashed': verified_files, 'temporary_database_and_role_removed': True,
|
||||
'live_configuration_or_database_replaced': False, 'hashes': {name: hashlib.sha256((backup/name).read_bytes()).hexdigest()
|
||||
for name in ['database.dump', 'storage.tar.gz', 'code.tar.gz']}}
|
||||
(demo / 'final-backup.json').write_text(json.dumps(proof, indent=2))
|
||||
print(json.dumps(proof, indent=2))
|
||||
@@ -0,0 +1,48 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const frontend = process.argv[2];
|
||||
assert.ok(frontend, 'Provide the verified frontend build directory.');
|
||||
const roots = ['app', 'bootstrap', 'config', 'database', 'resources', 'routes', 'integrations', 'packages', 'public',
|
||||
'composer.json', 'composer.lock', 'package.json', 'package-lock.json', 'artisan', '.gitattributes', '.env.example',
|
||||
'scripts/verify-compras-release.php', 'scripts/build-compras-release.mjs', 'scripts/archive-compras-release.py', 'scripts/deployment/compras-tempo-deploy.sh'];
|
||||
const listed = ['git', 'ls-files'];
|
||||
const tracked = execFileSync(listed[0], [...listed.slice(1), '-z', '--', ...roots], { encoding: 'utf8' }).split('\0');
|
||||
const added = execFileSync('git', ['ls-files', '--others', '--exclude-standard', '-z', '--', ...roots], { encoding: 'utf8' }).split('\0');
|
||||
const hash = bytes => crypto.createHash('sha256').update(bytes).digest('hex');
|
||||
const source = {};
|
||||
const exact = [];
|
||||
for (const file of [...new Set([...tracked, ...added])].filter(Boolean).sort()) {
|
||||
if (file.startsWith('bootstrap/cache/') || file.startsWith('public/build/')) continue;
|
||||
const info = await fs.lstat(file);
|
||||
if (!info.isFile() || info.isSymbolicLink()) continue;
|
||||
const bytes = await fs.readFile(file);
|
||||
const pinned = file.startsWith('packages/budget-control/') || file.startsWith('packages/payables/')
|
||||
|| file === 'resources/data/geography/cartografia-moz.json' || bytes.includes(0);
|
||||
if (pinned) exact.push(file);
|
||||
source[file] = hash(pinned ? bytes : Buffer.from(bytes.toString('utf8').replaceAll('\r\n', '\n')));
|
||||
}
|
||||
const buildBytes = await fs.readFile(path.join(frontend, 'manifest.json'));
|
||||
const build = JSON.parse(buildBytes);
|
||||
const assets = {};
|
||||
for (const entry of Object.values(build)) {
|
||||
for (const file of [entry.file, ...(entry.css ?? []), ...(entry.assets ?? [])]) {
|
||||
assert.ok(file.startsWith('assets/') && !file.includes('..'));
|
||||
assets[file] = hash(await fs.readFile(path.join(frontend, file)));
|
||||
}
|
||||
}
|
||||
const manifest = { contract: 'compras.release.v1', product: 'compras', source_eol: 'lf', exact_source_files: exact,
|
||||
source_files: source, frontend: { manifest_sha256: hash(buildBytes), entry: build['resources/js/app.tsx'].file,
|
||||
fonts_manifest_sha256: hash(await fs.readFile(path.join(frontend, 'fonts-manifest.json'))),
|
||||
files: Object.fromEntries(Object.entries(assets).sort(([a], [b]) => a.localeCompare(b, 'en'))) },
|
||||
components: [
|
||||
{ setting: 'COMPRAS_RUNTIME_ROOT', manifest_sha256: '80483320a54af6f123498e43c1435a20922455f65860be88bd259e90efcbc0b7' },
|
||||
{ setting: 'COMPRAS_INVENTORY_ROOT', manifest_sha256: '8608e6551dea6448983ead401ba900b440ffdeb1446ce52de6509d5eba0e87bd' },
|
||||
{ setting: 'COMPRAS_ORDER_CANCELLATION_ROOT', manifest_sha256: '52df7927aa2689598ce1be92de1483694347a696245704abb9e3925db7abfc0f' },
|
||||
] };
|
||||
manifest.release_id = 'compras-'+hash(JSON.stringify(manifest)).slice(0, 16);
|
||||
await fs.writeFile('compras-release.json', JSON.stringify(manifest, null, 2)+'\n');
|
||||
console.log(JSON.stringify({ release_id: manifest.release_id, source_files: Object.keys(source).length, asset_files: Object.keys(assets).length }));
|
||||
@@ -0,0 +1,38 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import crypto from 'node:crypto';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const release = JSON.parse(await fs.readFile('compras-release.json', 'utf8'));
|
||||
const base = 'https://compras.tempo.co.mz';
|
||||
const entry = await fetch(base+'/', { redirect: 'manual', signal: AbortSignal.timeout(15000) });
|
||||
assert.equal(entry.status, 302);
|
||||
assert.equal(new URL(entry.headers.get('location'), base).pathname, '/login');
|
||||
const queue = Object.entries(release.frontend.files);
|
||||
let checked = 0;
|
||||
await Promise.all(Array.from({ length: 4 }, async () => {
|
||||
for (;;) {
|
||||
const entry = queue.shift();
|
||||
if (!entry) return;
|
||||
const [name, expected] = entry;
|
||||
const response = await fetch(base+'/build/'+name, { signal: AbortSignal.timeout(20000) });
|
||||
assert.equal(response.status, 200, name);
|
||||
assert.equal(crypto.createHash('sha256').update(new Uint8Array(await response.arrayBuffer())).digest('hex'), expected, name);
|
||||
checked++;
|
||||
}
|
||||
}));
|
||||
for (const [path, component] of [['/', 'auth/login'], ['/login', 'auth/login'], ['/apresentacao', 'home']]) {
|
||||
const response = await fetch(base+path, { signal: AbortSignal.timeout(15000) });
|
||||
assert.equal(response.status, 200);
|
||||
const html = await response.text();
|
||||
assert.ok(html.includes(release.frontend.entry));
|
||||
const bootstrap = html.match(/<script data-page="app" type="application\/json">([\s\S]*?)<\/script>/);
|
||||
assert.ok(bootstrap);
|
||||
const page = JSON.parse(bootstrap[1]);
|
||||
assert.equal(page.component, component);
|
||||
assert.equal(page.props.auth.user, null);
|
||||
assert.deepEqual(page.props.commonFinanceNavigation, { payments: false, ledger: false, configuration: false });
|
||||
}
|
||||
const proof = { state: 'passed', product: 'compras', release_id: release.release_id, public_url: base,
|
||||
assets_verified: checked, real_product_entry: true, login_entry: true, anonymous_private_identity_or_financial_access: false };
|
||||
await fs.writeFile('docs/proofs/compras-release-http.json', JSON.stringify(proof, null, 2)+'\n');
|
||||
console.log(JSON.stringify(proof));
|
||||
@@ -0,0 +1,30 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import crypto from 'node:crypto';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const file = 'docs/proofs/public-demonstration-frontend.json';
|
||||
const proof = JSON.parse(await fs.readFile(file, 'utf8'));
|
||||
const queue = Object.entries(proof.files);
|
||||
let checked = 0;
|
||||
await Promise.all(Array.from({ length: 4 }, async () => {
|
||||
for (;;) {
|
||||
const entry = queue.shift();
|
||||
if (!entry) return;
|
||||
const [name, hash] = entry;
|
||||
const response = await fetch('https://compras.tempo.co.mz/build/' + name, { signal: AbortSignal.timeout(20000) });
|
||||
assert.equal(response.status, 200, name);
|
||||
assert.equal(crypto.createHash('sha256').update(new Uint8Array(await response.arrayBuffer())).digest('hex'), hash, name);
|
||||
checked++;
|
||||
}
|
||||
}));
|
||||
Object.assign(proof, { state: 'assets_passed_banner_pending', public_assets_responses_and_hashes: checked });
|
||||
await fs.writeFile(file, JSON.stringify(proof, null, 2) + '\n');
|
||||
const response = await fetch('https://compras.tempo.co.mz/login', { signal: AbortSignal.timeout(15000) });
|
||||
assert.equal(response.status, 200);
|
||||
const html = await response.text();
|
||||
const manifest = JSON.parse(await fs.readFile('storage/framework/testing/compras-presentation-final-ui-20261129/manifest.json', 'utf8'));
|
||||
assert.ok(html.includes(manifest['resources/js/app.tsx'].file));
|
||||
assert.ok(html.includes('Empresa e dados fictícios'));
|
||||
Object.assign(proof, { state: 'passed', date: new Date().toISOString(), public_entry_current: true, demonstration_banner_present: true });
|
||||
await fs.writeFile(file, JSON.stringify(proof, null, 2) + '\n');
|
||||
console.log(JSON.stringify({ state: proof.state, public_assets_responses_and_hashes: checked, public_entry_current: true }));
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Native private audit and signed-contract exercise, synthetic company only."""
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import uuid
|
||||
import zipfile
|
||||
from datetime import date
|
||||
|
||||
spec = importlib.util.spec_from_file_location('demo', '/root/check-public-demonstration.py')
|
||||
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
|
||||
assert sys.argv[1] == '--exercise-authorized-synthetic'
|
||||
origin = sys.argv[2] if len(sys.argv) > 2 else 'http://127.0.0.1:49815'
|
||||
credentials = json.loads(Path('/root/compras-demo-access.json').read_text())
|
||||
clients = {key: m.Client(credentials[key], origin) for key in ['admin', 'direction', 'auditor', 'requester']}
|
||||
auditor = clients['auditor']
|
||||
page = auditor.request('/auditoria/privada')
|
||||
assert page['status'] == 200
|
||||
exports = page['page']['props']['exports']['data']
|
||||
if not exports or '--refresh-audit' in sys.argv:
|
||||
result = auditor.request('/auditoria/privada', 'POST', {'operation_key': str(uuid.uuid4()), 'families': ['purchasing', 'stock', 'finance', 'configuration'],
|
||||
'purpose': 'Pacote fictício para apresentação e conferência de integridade.'})
|
||||
assert result['status'] in [302, 303], f"Audit generation failed: {result['status']} {result['text'][:600]}"
|
||||
exports = auditor.request('/auditoria/privada')['page']['props']['exports']['data']
|
||||
export = exports[0]
|
||||
download = auditor.request(export['download_url'], inertia=False)
|
||||
assert download['status'] == 200 and hashlib.sha256(download['raw']).hexdigest() == export['sha256']
|
||||
with zipfile.ZipFile(io.BytesIO(download['raw'])) as z:
|
||||
assert z.testzip() is None and 'manifesto.json' in z.namelist()
|
||||
manifest = json.loads(z.read('manifesto.json'))
|
||||
for entry in [*manifest['datasets'], *manifest['originals']]:
|
||||
assert hashlib.sha256(z.read(entry['file'])).hexdigest() == entry['sha256']
|
||||
audit_members = len(z.namelist())
|
||||
assert clients['requester'].request(export['download_url'])['status'] == 403
|
||||
direction = clients['direction']
|
||||
page = direction.request('/pessoas/1')
|
||||
assert page['status'] == 200 and page['page']['props']['canFormalize']
|
||||
record = page['page']['props']['process']
|
||||
if record['status'] == 'contract_draft':
|
||||
stream = b'BT /F1 16 Tf 30 700 Td (DEMONSTRACAO - DOCUMENTO FICTICIO) Tj 0 -30 Td (Sem contrato, assinatura ou admissao real.) Tj ET'
|
||||
objects = [b'<< /Type /Catalog /Pages 2 0 R >>', b'<< /Type /Pages /Kids [3 0 R] /Count 1 >>',
|
||||
b'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>',
|
||||
b'<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>', b'<< /Length '+str(len(stream)).encode()+b' >>\nstream\n'+stream+b'\nendstream']
|
||||
pdf = b'%PDF-1.4\n'; offsets = []
|
||||
for i, obj in enumerate(objects, 1):
|
||||
offsets.append(len(pdf)); pdf += str(i).encode()+b' 0 obj\n'+obj+b'\nendobj\n'
|
||||
start = len(pdf); pdf += b'xref\n0 6\n0000000000 65535 f \n'
|
||||
for offset in offsets: pdf += f'{offset:010d} 00000 n \n'.encode()
|
||||
pdf += b'trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n'+str(start).encode()+b'\n%%EOF\n'
|
||||
boundary = 'compras-demo-'+uuid.uuid4().hex
|
||||
fields = {'version': str(record['version']), 'operation_key': str(uuid.uuid4()), 'signed_on': date.today().isoformat(),
|
||||
'reference': 'DEMO-ASSINADO-001', 'reason': 'Confirmação fictícia pela direcção, exclusivamente para apresentação.', 'no_conflict': '1'}
|
||||
body = b''
|
||||
for key, value in fields.items(): body += f'--{boundary}\r\nContent-Disposition: form-data; name="{key}"\r\n\r\n{value}\r\n'.encode()
|
||||
body += f'--{boundary}\r\nContent-Disposition: form-data; name="signed_document"; filename="demonstracao.pdf"\r\nContent-Type: application/pdf\r\n\r\n'.encode()+pdf+f'\r\n--{boundary}--\r\n'.encode()
|
||||
content_type = 'multipart/form-data; boundary='+boundary
|
||||
assert clients['admin'].request('/pessoas/1/formalizar', 'POST', body, content_type=content_type)['status'] == 403
|
||||
result = direction.request('/pessoas/1/formalizar', 'POST', body, content_type=content_type)
|
||||
assert result['status'] in [302, 303], f"Formalization failed: {result['status']} {result['text'][:600]}"
|
||||
assert direction.request('/pessoas/1/formalizar', 'POST', body, content_type=content_type)['status'] in [302, 303]
|
||||
record = direction.request('/pessoas/1')['page']['props']['process']
|
||||
assert record['status'] == 'contract_formalized' and 'path' not in record['contract']['signed_document']
|
||||
signed = direction.request('/pessoas/1/contrato-assinado', inertia=False)
|
||||
assert signed['status'] == 200 and hashlib.sha256(signed['raw']).hexdigest() == record['contract']['signed_document']['sha256']
|
||||
assert clients['requester'].request('/pessoas/1/contrato-assinado')['status'] in [403, 404]
|
||||
proof = {'state': 'passed', 'origin': origin, 'normal_login_sessions': 4, 'audit_export_id': export['id'], 'audit_zip_sha256': export['sha256'],
|
||||
'audit_zip_members_verified': audit_members, 'audit_unauthorized_download_refused': True, 'people_formalized_by_direction': True,
|
||||
'admin_without_direction_authority_refused': True, 'formalization_replay_one_effect': True, 'signed_document_hash_verified': True,
|
||||
'signed_document_private_path_redacted': True, 'unauthorized_contract_download_refused': True, 'employee_admission_or_rh_dispatch': False}
|
||||
Path('/var/www/compras-deploy/demonstration-20261129/evidence-check.json').write_text(json.dumps(proof, indent=2))
|
||||
print(json.dumps(proof, indent=2))
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\CommonPaymentFacts;
|
||||
use App\Services\ExpenseAllocations;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Session\ArraySessionHandler;
|
||||
use Illuminate\Session\Store;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
if (($argv[1] ?? '') !== '--read-only' || config('app.demonstration') !== true || DB::connection()->getDatabaseName() !== 'compras_demo_20261129') {
|
||||
throw new LogicException('Explicit synthetic demonstration required.');
|
||||
}
|
||||
try {
|
||||
$result = DB::transaction(function () {
|
||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
$actor = User::query()->where('email', 'finance_review@demo.compras.tempo.co.mz')->sole();
|
||||
auth()->guard()->setUser($actor);
|
||||
// Read-only diagnostic fixture: the same configured internal context, with an in-memory session.
|
||||
$request = Request::create('https://compras.tempo.co.mz/facturas');
|
||||
$session = new Store('finance-readonly', new ArraySessionHandler(120));
|
||||
$session->start();
|
||||
$session->put('work_context', ['user_id' => $actor->id, 'tenant_id' => $actor->tenant_id, 'key' => 'procurement.internal']);
|
||||
$request->setLaravelSession($session);
|
||||
$request->setUserResolver(fn () => $actor);
|
||||
app()->instance('request', $request);
|
||||
$invoice = DB::table('invoices')->sole();
|
||||
$allocation = DB::table('ps_allocations')->sole();
|
||||
$facts = app(CommonPaymentFacts::class)->source($actor, $allocation->id);
|
||||
$category = app(ExpenseAllocations::class)->projection($actor, $allocation->id, 'common_allocation');
|
||||
$debit = (int) DB::table('gl_lines')->sum('debit_minor');
|
||||
$credit = (int) DB::table('gl_lines')->sum('credit_minor');
|
||||
$stock = (int) DB::table('stock_movements')->sum('quantity_milli');
|
||||
if ($invoice->status !== 'validated' || (int) $invoice->total_minor !== 100000 || $facts['amount_minor'] !== 40000
|
||||
|| $category['state'] !== 'allocated' || $category['allocations'] !== [['category' => 'Material de escritório', 'amount_minor' => '40000']]
|
||||
|| $debit !== 100000 || $credit !== 100000 || $stock !== 10000
|
||||
|| DB::table('ps_payments')->count() !== 1 || DB::table('external_payments')->count() !== 0) {
|
||||
throw new LogicException('Demonstration financial reconciliation failed.');
|
||||
}
|
||||
|
||||
return ['state' => 'passed', 'invoice_id' => $invoice->id, 'invoice_minor' => 100000, 'payment_minor' => 40000, 'remaining_minor' => 60000,
|
||||
'allocation_id' => $allocation->id, 'category_attribution' => $category, 'stock_milli' => $stock, 'journal_debit_minor' => $debit,
|
||||
'journal_credit_minor' => $credit, 'duplicate_external_payment' => false, 'read_only' => true];
|
||||
});
|
||||
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
} catch (Throwable $error) {
|
||||
fwrite(STDERR, $error::class.': '.$error->getMessage().PHP_EOL);
|
||||
exit(1);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Small bounded presentation check, not a claim of maximum production capacity."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import statistics
|
||||
import sys
|
||||
import time
|
||||
|
||||
assert sys.argv[1] == '--bounded-synthetic-check'
|
||||
s = importlib.util.spec_from_file_location('demo', '/root/check-public-demonstration.py')
|
||||
m = importlib.util.module_from_spec(s); s.loader.exec_module(m)
|
||||
credentials = json.loads(Path('/root/compras-demo-access.json').read_text())
|
||||
paths = {'admin': '/pessoas/relatorios', 'procurement': '/ordens', 'finance': '/relatorios', 'warehouse': '/dashboard'}
|
||||
clients = {key: m.Client(credentials[key], 'https://compras.tempo.co.mz') for key in paths}
|
||||
|
||||
|
||||
def exercise(key):
|
||||
timings = []
|
||||
for _ in range(12):
|
||||
started = time.perf_counter()
|
||||
result = clients[key].request(paths[key])
|
||||
elapsed = time.perf_counter() - started
|
||||
assert result['status'] == 200 and result['page']['props']['auth']['user'] is not None, key
|
||||
timings.append(elapsed)
|
||||
return timings
|
||||
|
||||
|
||||
started = time.perf_counter()
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
timings = [elapsed for group in pool.map(exercise, paths) for elapsed in group]
|
||||
ordered = sorted(timings)
|
||||
proof = {'state': 'passed', 'origin': 'https://compras.tempo.co.mz', 'normal_login_sessions': 4, 'concurrent_sessions': 4,
|
||||
'get_requests': len(timings), 'responses_200': len(timings), 'duration_seconds': round(time.perf_counter()-started, 3),
|
||||
'median_seconds': round(statistics.median(timings), 3), 'p95_seconds': round(ordered[int(len(ordered)*0.95)-1], 3),
|
||||
'maximum_seconds': round(max(timings), 3), 'business_mutations': False, 'maximum_production_capacity_certified': False}
|
||||
Path('/var/www/compras-deploy/demonstration-20261129/bounded-load.json').write_text(json.dumps(proof, indent=2))
|
||||
print(json.dumps(proof, indent=2))
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Authenticated native HTTP checks for the explicitly isolated synthetic public demo."""
|
||||
import html
|
||||
import http.client
|
||||
from http.cookies import SimpleCookie
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
import urllib.parse
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self, identity, origin='http://127.0.0.1:49815'):
|
||||
self.origin = urllib.parse.urlparse(origin)
|
||||
self.cookies = {}
|
||||
self.version = None
|
||||
self.request('/login', inertia=False)
|
||||
result = self.request('/login', 'POST', {'email': identity['email'], 'password': identity['password']}, inertia=False)
|
||||
assert result['status'] in [200, 302, 303], f"Normal login failed: {result['status']}"
|
||||
page = self.request('/dashboard', inertia=False)
|
||||
assert page['status'] == 200 and page['page']['props']['auth']['user'] is not None, 'Normal login did not establish an authenticated session'
|
||||
self.version = page['page']['version']
|
||||
self.work_context = page['page']['props'].get('workContext') or {}
|
||||
|
||||
def request(self, path, method='GET', data=None, inertia=True, content_type=None):
|
||||
context = getattr(self, 'work_context', {})
|
||||
shared = path == '/' or path.startswith(('/dashboard', '/login', '/logout', '/administracao/', '/empresa', '/settings', '/contexto'))
|
||||
if method == 'GET' and context.get('enforced') and not shared:
|
||||
area = 'people' if path == '/pessoas' or path.startswith('/pessoas/') else 'procurement'
|
||||
option = area+'.internal'
|
||||
if option in context.get('available', []) and context.get('active') != option:
|
||||
selected = self.request('/contexto', 'POST', {'area': area, 'option': option})
|
||||
assert selected['status'] in [302, 303], 'Native explicit context selection failed'
|
||||
context['active'] = option
|
||||
connection = (http.client.HTTPSConnection if self.origin.scheme == 'https' else http.client.HTTPConnection)(self.origin.hostname, self.origin.port, timeout=30)
|
||||
headers = {'Host': 'compras.tempo.co.mz', 'Accept': 'application/json' if method != 'GET' or inertia else 'text/html',
|
||||
'Cookie': '; '.join(k+'='+v for k, v in self.cookies.items())}
|
||||
if 'XSRF-TOKEN' in self.cookies:
|
||||
headers['X-XSRF-TOKEN'] = urllib.parse.unquote(self.cookies['XSRF-TOKEN'])
|
||||
if inertia and method == 'GET':
|
||||
headers['X-Inertia'] = 'true'
|
||||
if self.version: headers['X-Inertia-Version'] = self.version
|
||||
body = None
|
||||
if data is not None:
|
||||
headers['Content-Type'] = content_type or 'application/json'
|
||||
body = data if isinstance(data, bytes) else json.dumps(data)
|
||||
connection.request(method, path, body, headers)
|
||||
response = connection.getresponse()
|
||||
for key, value in response.getheaders():
|
||||
if key.lower() == 'set-cookie':
|
||||
cookie = SimpleCookie(); cookie.load(value)
|
||||
self.cookies.update({k: v.value for k, v in cookie.items()})
|
||||
raw = response.read()
|
||||
text = raw.decode('utf-8', errors='replace')
|
||||
page = None
|
||||
if response.getheader('Content-Type', '').startswith('application/json'):
|
||||
try: page = json.loads(text)
|
||||
except ValueError: pass
|
||||
else:
|
||||
match = re.search(r'<script data-page="app" type="application/json">([\s\S]*?)</script>', text)
|
||||
if match: page = json.loads(html.unescape(match.group(1)))
|
||||
result = {'status': response.status, 'page': page, 'location': response.getheader('Location'), 'text': text, 'raw': raw}
|
||||
connection.close()
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
assert sys.argv[1] == '--check-authorized-synthetic'
|
||||
root = Path('/var/www/compras-deploy/releases/presentation-20261129')
|
||||
assert root.exists() and 'DB_DATABASE="compras_demo_20261129"' in (root / '.env').read_text()
|
||||
credentials = json.loads(Path('/root/compras-demo-access.json').read_text())
|
||||
origin = sys.argv[2] if len(sys.argv) > 2 else 'http://127.0.0.1:49815'
|
||||
clients = {key: Client(identity, origin) for key, identity in credentials.items()}
|
||||
checks = []
|
||||
routes = {
|
||||
'admin': ['/dashboard', '/administracao/parametrizacao', '/pessoas', '/pessoas/relatorios', '/pessoas/relatorios?view=selections', '/relatorios'],
|
||||
'requester': ['/dashboard', '/requisicoes', '/requisicoes/1'],
|
||||
'procurement': ['/dashboard', '/fornecedores', '/cotacoes', '/ordens', '/ordens-operacionais', '/projectos-imobilizado',
|
||||
'/compras/importacoes/12/documentos', '/compras/importacoes/12/suporte-bancario', '/compras/importacoes/12/suporte-bancario.csv',
|
||||
*['/compras/importacoes/12/documentos/'+str(number) for number in range(13,18)]],
|
||||
'finance': ['/dashboard', '/relatorios', '/orcamentos'],
|
||||
'warehouse': ['/dashboard', '/recepcoes'],
|
||||
'auditor': ['/dashboard', '/auditoria/privada'],
|
||||
'direction': ['/dashboard', '/pessoas'],
|
||||
}
|
||||
for key, paths in routes.items():
|
||||
for path in paths:
|
||||
result = clients[key].request(path)
|
||||
checks.append({'profile': key, 'path': path, 'status': result['status']})
|
||||
errors = [check for check in checks if check['status'] != 200]
|
||||
proof = {'state': 'passed' if not errors else 'failed', 'origin': origin, 'normal_login_sessions': len(clients), 'checks': checks,
|
||||
'synthetic_only': True, 'authentication_shortcuts': False, 'errors': errors}
|
||||
print(json.dumps(proof, indent=2))
|
||||
assert not errors, 'Native route errors require diagnosis before activation'
|
||||
Path('/var/www/compras-deploy/demonstration-20261129/' + ('public-http-check.json' if origin.startswith('https:') else 'staging-http-check.json')).write_text(json.dumps(proof, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Normal HTTP proof of the same four pilot choices, preserving context boundaries."""
|
||||
import importlib.util
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
spec = importlib.util.spec_from_file_location('native', '/root/check-public-demonstration.py')
|
||||
native = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(native)
|
||||
credentials = json.loads(Path('/root/compras-demo-access.json').read_text())
|
||||
origin = 'https://compras.tempo.co.mz'
|
||||
admin = native.Client(credentials['admin'], origin)
|
||||
expected = ['procurement.internal', 'procurement.sales', 'people.internal', 'people.third_party']
|
||||
assert admin.work_context['enforced'] and admin.work_context['available'] == expected
|
||||
admin.work_context = {} # This exercise selects every context explicitly, without helper selection.
|
||||
checks = []
|
||||
for option in expected:
|
||||
area = option.split('.')[0]
|
||||
selection = admin.request('/contexto', 'POST', {'area': area, 'option': option})
|
||||
assert selection['status'] in [302, 303]
|
||||
page = admin.request('/dashboard')
|
||||
assert page['status'] == 200 and page['page']['component'] == 'work-context'
|
||||
context = page['page']['props']['context']
|
||||
assert context['active'] == option and context['available'] == expected
|
||||
path = '/requisicoes' if area == 'procurement' else '/pessoas'
|
||||
operational = option in ['procurement.internal', 'people.internal', 'people.third_party']
|
||||
assert context['options'][option]['operational'] == operational
|
||||
result = admin.request(path)
|
||||
if operational:
|
||||
assert result['status'] == 200
|
||||
collection = 'requisitions' if area == 'procurement' else 'processes'
|
||||
assert result['page']['props'][collection]['total'] > 0
|
||||
opposite = admin.request('/pessoas' if area == 'procurement' else '/requisicoes')
|
||||
assert opposite['status'] == 403
|
||||
else:
|
||||
assert result['status'] == 302 and result['location'].endswith('/dashboard')
|
||||
assert admin.request(path, 'POST', {})['status'] == 409
|
||||
checks.append({'context': option, 'selected_on_dashboard': True, 'operational': operational,
|
||||
'records_visible_in_selected_context': operational, 'cross_context_or_unimplemented_operation_refused': True})
|
||||
buyer = native.Client(credentials['procurement'], origin)
|
||||
assert buyer.work_context['available'] == ['procurement.internal', 'procurement.sales']
|
||||
assert buyer.request('/contexto', 'POST', {'area': 'people', 'option': 'people.internal'})['status'] == 403
|
||||
pins = json.loads(subprocess.check_output(['/usr/bin/php', '/var/www/compras-deploy/current/scripts/private-audit-transition-pins.php']))['2']
|
||||
auditor = native.Client(credentials['auditor'], origin)
|
||||
requester = native.Client(credentials['requester'], origin)
|
||||
exports = auditor.request('/auditoria/privada')['page']['props']['exports']['data']
|
||||
visible = {str(export['id']): export for export in exports}
|
||||
for identifier, digest in pins.items():
|
||||
assert identifier in visible
|
||||
url = visible[identifier]['download_url']
|
||||
response = auditor.request(url, inertia=False)
|
||||
assert response['status'] == 200 and hashlib.sha256(response['raw']).hexdigest() == digest
|
||||
assert requester.request(url)['status'] == 403
|
||||
proof = {'state': 'passed', 'release_id': json.loads(Path('/var/www/compras-deploy/current/compras-release.json').read_text())['release_id'],
|
||||
'same_four_pilot_choices': True, 'normal_credential_login': True, 'checks': checks,
|
||||
'buyer_people_context_refused': True, 'original_audit_archives_visible_and_download_hashes_verified': len(pins),
|
||||
'unauthorized_archive_downloads_refused': len(pins), 'business_mutations_executed': False,
|
||||
'third_party_options_claimed_complete': False}
|
||||
Path('/var/www/compras-deploy/demonstration-20261129/pilot-contexts-http.json').write_text(json.dumps(proof, indent=2)+'\n')
|
||||
print(json.dumps(proof, indent=2))
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
use App\Services\StandaloneRuntime;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
require $root.'/vendor/autoload.php';
|
||||
if (($argv[1] ?? '') === '--local-read-only') {
|
||||
$settings = json_decode(file_get_contents('C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json'), true, 32, JSON_THROW_ON_ERROR);
|
||||
foreach ([...$settings, 'APP_CONFIG_CACHE' => $root.'/storage/framework/absent-comparison-config.php',
|
||||
'PGOPTIONS' => '-c default_transaction_read_only=on', 'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array'] as $key => $value) {
|
||||
putenv($key.'='.$value);
|
||||
$_ENV[$key] = $_SERVER[$key] = $value;
|
||||
}
|
||||
} elseif (($argv[1] ?? '') !== '--public-read-only') {
|
||||
throw new LogicException('Explicit read-only comparison required');
|
||||
}
|
||||
$app = require $root.'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
DB::statement('SET default_transaction_read_only=on');
|
||||
$runtime = app(StandaloneRuntime::class);
|
||||
$runtime->configure(DB::connection());
|
||||
$runtime->assertLoadedPackages();
|
||||
$features = [];
|
||||
foreach (StandaloneRuntime::FEATURES as $feature) {
|
||||
$features[$feature] = $runtime->requested($feature);
|
||||
}
|
||||
$routes = [];
|
||||
foreach (Route::getRoutes() as $route) {
|
||||
if (str_starts_with($route->uri(), 'avaliar') || str_starts_with($route->uri(), '_')) {
|
||||
continue;
|
||||
}
|
||||
$routes[$route->uri().' '.implode('|', $route->methods())] = $route->getActionName();
|
||||
}
|
||||
ksort($routes);
|
||||
$components = [];
|
||||
foreach (['standalone-runtime', 'inventory_conversion', 'order_cancellation'] as $key) {
|
||||
$components[$key] = config($key.'.enabled');
|
||||
}
|
||||
$tenants = DB::table('tenants')->select('work_context_policy')->get()->map(fn ($row) => $row->work_context_policy === null ? null : json_decode($row->work_context_policy, true))->all();
|
||||
$flags = [];
|
||||
$collectFlags = function (array $values, string $prefix = '') use (&$collectFlags, &$flags): void {
|
||||
foreach ($values as $key => $value) {
|
||||
$path = $prefix.$key;
|
||||
if (is_array($value)) {
|
||||
$collectFlags($value, $path.'.');
|
||||
} elseif (is_bool($value) && preg_match('/(?:enabled|synthetic_only|prepare_only|enforced)$/D', (string) $key)) {
|
||||
$flags[$path] = $value;
|
||||
}
|
||||
}
|
||||
};
|
||||
$collectFlags(config()->all());
|
||||
ksort($flags);
|
||||
echo json_encode(['state' => 'passed', 'runtime_enabled' => $runtime->enabled(), 'features' => $features,
|
||||
'deployment_flags' => $flags,
|
||||
'history_schema' => ['pa_history_imports' => Illuminate\Support\Facades\Schema::hasTable('pa_history_imports'), 'pa_imported_payments' => Illuminate\Support\Facades\Schema::hasTable('pa_imported_payments')],
|
||||
'pending_application_migrations' => array_values(array_diff(array_map(fn ($file) => basename($file, '.php'), glob($root.'/database/migrations/*.php')), DB::table('migrations')->pluck('migration')->all())),
|
||||
'routes' => $routes, 'component_flags' => $components, 'company_context_policies' => $tenants,
|
||||
'context_entitlements_configured' => count(config('work_context.entitlements', [])) > 0,
|
||||
'operational_contexts' => array_combine(array_keys(App\Services\WorkContext::OPTIONS), array_map(fn ($key) => App\Services\WorkContext::operational($key), array_keys(App\Services\WorkContext::OPTIONS))),
|
||||
'business_data_changed' => false], JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -0,0 +1,120 @@
|
||||
<?php
|
||||
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\User;
|
||||
use App\Services\CommonFinanceAdministration;
|
||||
use App\Services\ExpenseAllocations;
|
||||
use App\Services\GeneralLedger;
|
||||
use App\Services\InvoiceWorkflow;
|
||||
use App\Services\ReceiptWorkflow;
|
||||
use App\Services\SupplierBankWorkflow;
|
||||
use App\Services\SupplierPayables;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
if (($argv[1] ?? '') !== '--initialize-authorized-synthetic' || config('app.demonstration') !== true
|
||||
|| DB::connection()->getDatabaseName() !== 'compras_demo_20261129' || DB::table('invoices')->exists()) {
|
||||
throw new LogicException('Only a new isolated synthetic receipt and finance journey is allowed.');
|
||||
}
|
||||
try {
|
||||
// Each native command commits with its own actor, including its after-commit work.
|
||||
$result = (function () {
|
||||
$people = [];
|
||||
foreach (['admin', 'procurement', 'finance', 'finance_review', 'warehouse'] as $key) {
|
||||
$people[$key] = User::query()->where('email', $key.'@demo.compras.tempo.co.mz')->sole();
|
||||
}
|
||||
$acting = function (string $key) use ($people): User {
|
||||
if (DB::transactionLevel() !== 0) {
|
||||
throw new LogicException('Do not defer native actor-bound callbacks across demonstration identities.');
|
||||
}
|
||||
auth()->guard()->setUser($people[$key]);
|
||||
|
||||
return $people[$key];
|
||||
};
|
||||
$receiver = $acting('warehouse');
|
||||
$order = PurchaseOrder::query()->sole();
|
||||
$line = $order->items()->sole();
|
||||
$receipt = app(ReceiptWorkflow::class)->confirm($receiver, $order, ['idempotency_key' => (string) Str::uuid(),
|
||||
'delivery_note' => 'DEMO-GUIA-001', 'received_on' => today()->toDateString(), 'warehouse_id' => 1,
|
||||
'items' => [['purchase_order_item_id' => $line->id, 'received_quantity' => '10.000', 'accepted_quantity' => '10.000',
|
||||
'quality_status' => 'compliant', 'stock_item_id' => 1, 'notes' => 'Recepção fictícia para apresentação.']]]);
|
||||
$finance = $acting('finance');
|
||||
$invoice = app(InvoiceWorkflow::class)->register($finance, $order, ['number' => 'DEMO-FT-001', 'issued_on' => today()->toDateString(),
|
||||
'subtotal' => '1000.00', 'tax' => '0.00', 'total' => '1000.00', 'items' => [['purchase_order_item_id' => $line->id,
|
||||
'quantity' => '10.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00']]]);
|
||||
$reviewer = $acting('finance_review');
|
||||
app(InvoiceWorkflow::class)->validate($reviewer, $invoice);
|
||||
$buyer = $acting('procurement');
|
||||
$supplier = Supplier::query()->findOrFail($order->supplier_id);
|
||||
$bank = app(SupplierBankWorkflow::class)->propose($buyer, $supplier, ['account_key' => (string) Str::uuid(), 'previous_id' => 0,
|
||||
'bank_name' => 'Banco Fictício — Demonstração', 'country' => 'MZ', 'currency' => 'MZN', 'beneficiary' => 'Fornecedor Fictício DEMO',
|
||||
'account_identifier' => 'DEMO-SEM-CONTA-REAL', 'evidence_reference' => 'DEMO sem comprovativo bancário real', 'reason' => 'Cadastro estritamente fictício para apresentação.']);
|
||||
foreach (['finance', 'finance_review'] as $key) {
|
||||
$actor = $acting($key);
|
||||
app(SupplierBankWorkflow::class)->review($actor, $bank, 'approved', 'Conferência fictícia independente para demonstração.');
|
||||
}
|
||||
$payables = app(SupplierPayables::class);
|
||||
$acting('finance');
|
||||
$proposal = $payables->engine($finance)->command('prepare', $invoice->id, 'Reconhecimento fictício da factura de demonstração', (string) Str::uuid());
|
||||
$acting('finance_review');
|
||||
$recognised = $payables->engine($reviewer)->command('validate', $proposal['proposal_id'], 'Conferência independente da obrigação fictícia', (string) Str::uuid());
|
||||
$acting('admin');
|
||||
$administration = app(CommonFinanceAdministration::class);
|
||||
$space = $administration->workspace($people['admin']);
|
||||
$accounts = DB::table('gl_accounts')->where('tenant_id', $finance->tenant_id)->pluck('id', 'code');
|
||||
$administration->save($people['admin'], 'rule', ['operation_key' => (string) Str::uuid(), 'basis_hash' => $space['rules']['hash'],
|
||||
'rule_key' => 'DEMO-OBRIGACAO', 'effect_type' => 'supplier_payable.recognised', 'valid_from' => today()->startOfYear()->toDateString(),
|
||||
'valid_to' => today()->endOfYear()->toDateString(), 'debit_account_id' => $accounts['DEMO-CUSTO'], 'credit_account_id' => $accounts['DEMO-FORNECEDORES'],
|
||||
'reason' => 'Regra contabilística ilustrativa exclusiva da empresa fictícia.']);
|
||||
$ledger = app(GeneralLedger::class);
|
||||
$acting('finance');
|
||||
$journal = $ledger->engine($finance)->command('prepare', ['obligation_id' => $recognised['obligation_id'], 'journal_on' => today()->toDateString(),
|
||||
'period_key' => 'DEMO-'.now()->year, 'rule_key' => 'DEMO-OBRIGACAO', 'reason' => 'Lançamento fictício no plano ilustrativo configurado'], (string) Str::uuid());
|
||||
$acting('finance_review');
|
||||
$ledger->engine($reviewer)->command('validate', ['proposal_id' => $journal['proposal_id'], 'revision' => $journal['revision'],
|
||||
'decision' => 'approved', 'reason' => 'Revisão independente do lançamento fictício'], (string) Str::uuid());
|
||||
$acting('finance');
|
||||
$ledger->engine($finance)->command('post', ['proposal_id' => $journal['proposal_id'], 'revision' => $journal['revision'],
|
||||
'reason' => 'Aplicação do lançamento fictício revisto'], (string) Str::uuid());
|
||||
$payment = $payables->settlements($finance)->command('payment-prepare', ['obligation_id' => $recognised['obligation_id'], 'source_revision' => $recognised['source_revision'],
|
||||
'amount' => '400.00', 'currency' => 'MZN', 'paid_on' => today()->toDateString(), 'fact_reference' => 'DEMO-PAGAMENTO-001',
|
||||
'evidence_reference' => 'DEMO-SEM-TRANSFERENCIA', 'reason' => 'Facto de pagamento fictício, sem transferência bancária'], (string) Str::uuid());
|
||||
$acting('finance_review');
|
||||
$payables->settlements($reviewer)->command('payment-decide', ['payment_id' => $payment['payment_id'], 'decision' => 'confirmed',
|
||||
'evidence_reference' => 'DEMO-CONFERENCIA-001', 'reason' => 'Confirmação independente de facto exclusivamente fictício'], (string) Str::uuid());
|
||||
$acting('finance');
|
||||
$allocation = $payables->settlements($finance)->command('allocation-prepare', ['payment_id' => $payment['payment_id'], 'reference' => 'DEMO-AFECTACAO-001',
|
||||
'allocations' => [['obligation_id' => $recognised['obligation_id'], 'source_revision' => $recognised['source_revision'], 'amount' => '400.00']],
|
||||
'reason' => 'Afectação explícita do pagamento fictício à factura'], (string) Str::uuid());
|
||||
$acting('finance_review');
|
||||
$payables->settlements($reviewer)->command('allocation-decide', ['proposal_id' => $allocation['proposal_id'], 'decision' => 'confirmed',
|
||||
'reason' => 'Confirmação independente da afectação fictícia'], (string) Str::uuid());
|
||||
$allocationId = (int) DB::table('ps_allocations')->where('payment_id', $payment['payment_id'])->value('id');
|
||||
$expenses = app(ExpenseAllocations::class);
|
||||
$source = $expenses->source($reviewer, $allocationId, 'common_allocation');
|
||||
$expenses->save($reviewer, $allocationId, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'fingerprint' => $source['fingerprint'],
|
||||
'reason' => 'Imputação expressa por Finanças do pagamento fictício à categoria de origem.',
|
||||
'allocations' => [['category' => 'Material de escritório', 'amount' => '400.00']]], 'common_allocation');
|
||||
if (DB::table('external_payments')->count() !== 0 || DB::table('ps_payments')->count() !== 1
|
||||
|| (int) DB::table('gl_lines')->sum('debit_minor') !== 100000 || (int) DB::table('gl_lines')->sum('credit_minor') !== 100000) {
|
||||
throw new LogicException('Synthetic financial reconciliation failed.');
|
||||
}
|
||||
|
||||
return ['state' => 'passed', 'order_id' => $order->id, 'receipt_id' => $receipt->id, 'invoice_id' => $invoice->id,
|
||||
'invoice_minor' => 100000, 'payment_minor' => 40000, 'remaining_minor' => 60000, 'payment_id' => $payment['payment_id'],
|
||||
'allocation_id' => $allocationId, 'stock_milli' => (int) DB::table('stock_movements')->sum('quantity_milli'),
|
||||
'journal_debit_minor' => 100000, 'journal_credit_minor' => 100000, 'external_bank_transaction' => false];
|
||||
})();
|
||||
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
} catch (Throwable $error) {
|
||||
fwrite(STDERR, $error::class.': '.$error->getMessage().PHP_EOL);
|
||||
foreach (array_slice($error->getTrace(), 0, 8) as $frame) {
|
||||
fwrite(STDERR, ($frame['file'] ?? '').':'.($frame['line'] ?? 0).' '.$frame['function'].PHP_EOL);
|
||||
}
|
||||
exit(1);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Configure the existing public MTA for Compras and send the owner's one authorised test."""
|
||||
from pathlib import Path
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
root = Path('/var/www/compras-deploy/current').resolve()
|
||||
assert root == Path('/var/www/compras-deploy/releases/presentation-20261129')
|
||||
env = (root/'.env').resolve()
|
||||
assert env == Path('/var/www/compras-deploy/demonstration-20261129/.env')
|
||||
assert subprocess.check_output(['systemctl', 'is-active', 'postfix']).decode().strip() == 'active'
|
||||
assert Path('/usr/sbin/sendmail').is_file()
|
||||
backup = Path('/var/backups/compras-presentation-20261129/mail-configuration')
|
||||
backup.mkdir(mode=0o700, exist_ok=False)
|
||||
shutil.copy2(env, backup/'selected.env.private')
|
||||
(backup/'selected.env.private').chmod(0o600)
|
||||
updates = {'MAIL_MAILER': 'sendmail', 'MAIL_SENDMAIL_PATH': '/usr/sbin/sendmail -bs -i',
|
||||
'MAIL_FROM_ADDRESS': 'nala@tempo.co.mz', 'MAIL_FROM_NAME': 'Compras'}
|
||||
lines = env.read_text().splitlines()
|
||||
for key, value in updates.items():
|
||||
matching = [i for i, line in enumerate(lines) if line.startswith(key+'=')]
|
||||
assert len(matching) <= 1
|
||||
rendered = key+'='+json.dumps(value)
|
||||
if matching:
|
||||
lines[matching[0]] = rendered
|
||||
else:
|
||||
lines.append(rendered)
|
||||
attrs = env.stat()
|
||||
temp = env.with_name(env.name+'.mail-next')
|
||||
temp.write_text('\n'.join(lines)+'\n')
|
||||
temp.chmod(attrs.st_mode & 0o777)
|
||||
os.chown(temp, attrs.st_uid, attrs.st_gid)
|
||||
os.replace(temp, env)
|
||||
subprocess.run(['runuser', '-u', 'www-data', '--', '/usr/bin/php', 'artisan', 'config:cache'], cwd=root, check=True)
|
||||
subprocess.run(['/usr/bin/php', str(root/'scripts/send-authorized-mail-check.php'), '--send-authorized-test'], cwd=root, check=True)
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Consolidate the selected installation's storage and single recurring service."""
|
||||
from pathlib import Path
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
base = Path('/var/www/compras-deploy')
|
||||
root = (base/'current').resolve()
|
||||
assert root == base/'releases/presentation-20261129'
|
||||
storage = (root/'storage').resolve()
|
||||
assert storage == base/'demonstration-20261129/storage'
|
||||
backup = Path('/var/backups/compras-presentation-20261129/consolidation')
|
||||
assert backup.is_dir()
|
||||
env = (root/'.env').resolve()
|
||||
old = storage/'framework/testing/private'
|
||||
new = storage/'app/private'
|
||||
assert old.is_dir() and not old.is_symlink() and not new.is_symlink()
|
||||
original = env.read_text()
|
||||
assert 'COMPRAS_PRIVATE_STORAGE_PATH='+str(old) in original or 'COMPRAS_PRIVATE_STORAGE_PATH="'+str(old)+'"' in original
|
||||
files = {}
|
||||
for source in old.rglob('*'):
|
||||
assert not source.is_symlink()
|
||||
if not source.is_file():
|
||||
continue
|
||||
relative = source.relative_to(old)
|
||||
digest = hashlib.sha256(source.read_bytes()).hexdigest()
|
||||
dest = new/relative
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
if dest.exists():
|
||||
assert hashlib.sha256(dest.read_bytes()).hexdigest() == digest
|
||||
else:
|
||||
shutil.copy2(source, dest)
|
||||
assert hashlib.sha256(dest.read_bytes()).hexdigest() == digest
|
||||
files[str(relative)] = digest
|
||||
owner = pwd.getpwnam('www-data')
|
||||
for p in [new]+list(new.rglob('*')):
|
||||
os.chown(p, owner.pw_uid, owner.pw_gid)
|
||||
p.chmod(0o700 if p.is_dir() else 0o600)
|
||||
lines = original.splitlines()
|
||||
for i, line in enumerate(lines):
|
||||
if line.startswith('COMPRAS_PRIVATE_STORAGE_PATH='):
|
||||
lines[i] = 'COMPRAS_PRIVATE_STORAGE_PATH='+json.dumps(str(new))
|
||||
elif line.startswith('APP_NAME='):
|
||||
lines[i] = 'APP_NAME="Compras"'
|
||||
temp = env.with_name(env.name+'.release-next')
|
||||
temp.write_text('\n'.join(lines)+'\n')
|
||||
attrs = env.stat()
|
||||
os.chown(temp, attrs.st_uid, attrs.st_gid)
|
||||
temp.chmod(attrs.st_mode & 0o777)
|
||||
os.replace(temp, env)
|
||||
subprocess.run(['runuser', '-u', 'www-data', '--', '/usr/bin/php', 'artisan', 'config:cache'], cwd=root, check=True)
|
||||
subprocess.run(['systemctl', 'stop', 'compras-demo-operations.timer'], check=True)
|
||||
subprocess.run(['systemctl', 'disable', 'compras-demo-operations.timer'], check=True)
|
||||
active = subprocess.run(['systemctl', 'is-active', 'compras-demo-operations.service'], capture_output=True, text=True).stdout.strip()
|
||||
assert active != 'active', 'Prior service is still running; do not overlap'
|
||||
for suffix in ['service', 'timer']:
|
||||
oldunit = Path('/etc/systemd/system/compras-demo-operations.'+suffix)
|
||||
if oldunit.exists():
|
||||
shutil.copy2(oldunit, backup/oldunit.name)
|
||||
service = '''[Unit]
|
||||
Description=Compras recurring operations
|
||||
After=network.target postgresql.service
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=www-data
|
||||
Group=www-data
|
||||
WorkingDirectory=/var/www/compras-deploy/current
|
||||
ExecStartPre=/usr/bin/php scripts/verify-compras-release.php /var/www/compras-deploy/current --installed
|
||||
ExecStart=/usr/bin/php artisan sgc:approval-deadlines-tick
|
||||
ExecStart=/usr/bin/php artisan sgc:replenishment-tick
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem=strict
|
||||
ReadWritePaths=/var/www/compras-deploy/demonstration-20261129/storage
|
||||
'''
|
||||
timer = '''[Unit]
|
||||
Description=Compras recurring operations timer
|
||||
|
||||
[Timer]
|
||||
OnBootSec=60s
|
||||
OnUnitActiveSec=60s
|
||||
Unit=compras-operations.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
'''
|
||||
for suffix, contents in [('service', service), ('timer', timer)]:
|
||||
unit = Path('/etc/systemd/system/compras-operations.'+suffix)
|
||||
assert not unit.exists(), 'Preserve an existing canonical service'
|
||||
unit.write_text(contents)
|
||||
unit.chmod(0o644)
|
||||
subprocess.run(['systemctl', 'daemon-reload'], check=True)
|
||||
subprocess.run(['systemctl', 'start', 'compras-operations.service'], check=True)
|
||||
subprocess.run(['systemctl', 'restart', 'compras-operations.service'], check=True)
|
||||
subprocess.run(['systemctl', 'enable', '--now', 'compras-operations.timer'], check=True)
|
||||
proof = {'state': 'passed', 'release_id': json.loads((root/'compras-release.json').read_text())['release_id'],
|
||||
'private_files_preserved': files, 'private_root': str(new), 'previous_private_root_preserved': True,
|
||||
'single_timer': 'compras-operations.timer', 'start_and_restart': 'passed', 'business_records_migrated': False}
|
||||
(backup/'operations.json').write_text(json.dumps(proof, indent=2)+'\n')
|
||||
print(json.dumps(proof))
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Guarded overlay of the authorised Compras release; private backups precede writes."""
|
||||
from pathlib import Path
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
root = Path('/var/www/compras-deploy/current').resolve()
|
||||
assert root == Path('/var/www/compras-deploy/releases/presentation-20261129')
|
||||
archive = Path('/root/compras-release-consolidated.zip')
|
||||
assert hashlib.sha256(archive.read_bytes()).hexdigest() == '9d493858b9b245148cb6d4c87d8e9436e44cf3fa179d24d6bacdbd7071a0e813'
|
||||
z = zipfile.ZipFile(archive)
|
||||
m = json.loads(z.read('compras-release.json'))
|
||||
changed = [n for n in m['source_files'] if (root/n).is_file() and (root/n).read_bytes().replace(b'\r\n', b'\n') != z.read(n).replace(b'\r\n', b'\n')]
|
||||
new = [n for n in m['source_files'] if not (root/n).exists()]
|
||||
print(json.dumps({'changed': changed, 'new': new}), flush=True)
|
||||
if '--install' not in sys.argv:
|
||||
sys.exit(0)
|
||||
allowed = {'app/Services/PeopleContractFormalization.php', 'app/Http/Controllers/PeopleHiringController.php',
|
||||
'app/Services/PrivateAuditFiles.php', 'resources/js/pages/home.tsx', 'resources/js/pages/auth/login.tsx',
|
||||
'resources/js/components/sgc-workspace-shell.tsx', 'resources/views/app.blade.php'}
|
||||
assert set(changed) <= allowed, 'Unexpected source delta; preserve and inspect'
|
||||
assert all(n.startswith('scripts/') or n == '.env.example' for n in new), 'Unexpected missing source'
|
||||
backup = Path('/var/backups/compras-presentation-20261129/consolidation')
|
||||
backup.mkdir(mode=0o700, exist_ok=False)
|
||||
env = (root/'.env').resolve()
|
||||
shutil.copy2(env, backup/'selected.env.private')
|
||||
for n in changed + ['public/build/manifest.json', 'public/build/fonts-manifest.json']:
|
||||
p = root/n
|
||||
if p.exists():
|
||||
dest = backup/n
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(p, dest)
|
||||
publisher = Path('/var/www/deploy/compras-tempo-deploy.sh')
|
||||
assert hashlib.sha256(publisher.read_bytes()).hexdigest() == 'bbdbe82a0bb74f4f8a15bf2c59d1da7043207842a37f20ff7751df534504ebdc'
|
||||
shutil.copy2(publisher, backup/'publisher.before.sh')
|
||||
for n in m['source_files']:
|
||||
if n not in changed and n not in new:
|
||||
continue
|
||||
dest = root/n
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
temp = dest.with_name(dest.name+'.release-next')
|
||||
temp.write_bytes(z.read(n))
|
||||
temp.chmod(0o644)
|
||||
os.replace(temp, dest)
|
||||
for n in list(m['frontend']['files']) + ['fonts-manifest.json', 'manifest.json']:
|
||||
name = 'public/build/'+n
|
||||
dest = root/name
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
if dest.exists() and n.startswith('assets/'):
|
||||
assert dest.read_bytes() == z.read(name), 'Immutable asset collision'
|
||||
temp = dest.with_name(dest.name+'.release-next')
|
||||
temp.write_bytes(z.read(name))
|
||||
temp.chmod(0o644)
|
||||
os.replace(temp, dest)
|
||||
(root/'compras-release.json').write_bytes(z.read('compras-release.json'))
|
||||
(root/'compras-release.json').chmod(0o644)
|
||||
subprocess.run(['/usr/bin/php', str(root/'scripts/verify-compras-release.php'), str(root), '--installed'], check=True)
|
||||
subprocess.run(['bash', '-n', str(root/'scripts/deployment/compras-tempo-deploy.sh')], check=True)
|
||||
attrs = publisher.stat()
|
||||
temp = publisher.with_name(publisher.name+'.release-next')
|
||||
temp.write_bytes((root/'scripts/deployment/compras-tempo-deploy.sh').read_bytes().replace(b'\r\n', b'\n'))
|
||||
os.chown(temp, attrs.st_uid, attrs.st_gid)
|
||||
temp.chmod(attrs.st_mode & 0o777)
|
||||
os.replace(temp, publisher)
|
||||
proof = {'state': 'passed', 'product': 'compras', 'release_id': m['release_id'], 'changed_source_files': changed,
|
||||
'new_source_files': new, 'backup': str(backup), 'same_selected_installation': True,
|
||||
'business_data_or_permissions_changed': False, 'publisher_preserves_selected_configuration': True}
|
||||
(backup/'result.json').write_text(json.dumps(proof, indent=2)+'\n')
|
||||
print(json.dumps(proof))
|
||||
@@ -0,0 +1,230 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
BASE="/var/www/compras-deploy"
|
||||
RELEASES="$BASE/releases"
|
||||
CURRENT="$BASE/current"
|
||||
SHARED="$BASE/shared"
|
||||
REPO="git@git.tempo.co.mz:nala/compras.git"
|
||||
LOCK="/tmp/compras-tempo-deploy.lock"
|
||||
HOST="compras.tempo.co.mz"
|
||||
|
||||
export APP_ENV=production
|
||||
export APP_DEBUG=false
|
||||
export COMPOSER_NO_INTERACTION=1
|
||||
|
||||
umask 0027
|
||||
|
||||
log() {
|
||||
printf '[DEPLOY] %s %s\n' "$(date -Is)" "$*"
|
||||
}
|
||||
|
||||
fail() {
|
||||
log "ERRO: $*"
|
||||
exit 1
|
||||
}
|
||||
|
||||
[ "$(id -un)" = "mario" ] ||
|
||||
fail "Utilizador de execucao invalido."
|
||||
|
||||
[ -d "$RELEASES" ] ||
|
||||
fail "Directorio de releases inexistente."
|
||||
|
||||
[ -L "$CURRENT" ] ||
|
||||
fail "Current nao e um link simbolico."
|
||||
|
||||
exec 9>"$LOCK"
|
||||
|
||||
flock -n 9 ||
|
||||
fail "Outra publicacao ja esta em execucao."
|
||||
|
||||
OLD_RELEASE="$(readlink -f "$CURRENT")"
|
||||
|
||||
[ -f "$OLD_RELEASE/public/index.php" ] ||
|
||||
fail "Release activa invalida."
|
||||
|
||||
ACTIVE_ENV="$(readlink -f "$OLD_RELEASE/.env")"
|
||||
ACTIVE_STORAGE="$(readlink -f "$OLD_RELEASE/storage")"
|
||||
[ -r "$ACTIVE_ENV" ] && [ -d "$ACTIVE_STORAGE" ] || fail "Configuracao activa indisponivel."
|
||||
[ -f "$OLD_RELEASE/scripts/verify-compras-release.php" ] || fail "Entrega integrada sem verificador."
|
||||
/usr/bin/php8.4 "$OLD_RELEASE/scripts/verify-compras-release.php" "$OLD_RELEASE" --installed || fail "Entrega activa inconsistente."
|
||||
|
||||
log "Inicio da publicacao."
|
||||
log "Release actual: $OLD_RELEASE"
|
||||
|
||||
TARGET_COMMIT="$(
|
||||
git ls-remote "$REPO" refs/heads/main |
|
||||
awk '{print $1}'
|
||||
)"
|
||||
|
||||
[[ "$TARGET_COMMIT" =~ ^[0-9a-f]{40}$ ]] ||
|
||||
fail "Nao foi possivel identificar o commit remoto."
|
||||
|
||||
CURRENT_COMMIT="$(
|
||||
git -C "$OLD_RELEASE" rev-parse HEAD 2>/dev/null || true
|
||||
)"
|
||||
|
||||
log "Commit actual: $CURRENT_COMMIT"
|
||||
log "Commit remoto: $TARGET_COMMIT"
|
||||
|
||||
if [ "$CURRENT_COMMIT" = "$TARGET_COMMIT" ]; then
|
||||
log "Nenhuma actualizacao necessaria."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Reservar um directorio vazio e unico, sem apagar releases anteriores.
|
||||
NEW_RELEASE="$(mktemp -d "$RELEASES/$(date -u +%Y%m%d-%H%M%S)-${TARGET_COMMIT:0:12}-XXXXXXXX")"
|
||||
chmod 2750 "$NEW_RELEASE"
|
||||
RELEASE_NAME="${NEW_RELEASE##*/}"
|
||||
|
||||
log "Criar release: $RELEASE_NAME"
|
||||
|
||||
git clone \
|
||||
--branch main \
|
||||
--single-branch \
|
||||
"$REPO" \
|
||||
"$NEW_RELEASE"
|
||||
|
||||
ACTUAL_COMMIT="$(
|
||||
git -C "$NEW_RELEASE" rev-parse HEAD
|
||||
)"
|
||||
|
||||
[ "$ACTUAL_COMMIT" = "$TARGET_COMMIT" ] ||
|
||||
fail "O commit clonado difere do commit esperado."
|
||||
|
||||
cd "$NEW_RELEASE"
|
||||
|
||||
log "Preparar armazenamento partilhado."
|
||||
|
||||
[ -d "$NEW_RELEASE/storage" ] ||
|
||||
fail "Storage da nova release inexistente."
|
||||
|
||||
mv "$NEW_RELEASE/storage" "$NEW_RELEASE/storage.original"
|
||||
|
||||
ln -s "$ACTIVE_STORAGE" "$NEW_RELEASE/storage"
|
||||
ln -s "$ACTIVE_ENV" "$NEW_RELEASE/.env"
|
||||
|
||||
[ ! -e "$NEW_RELEASE/public/storage" ] &&
|
||||
[ ! -L "$NEW_RELEASE/public/storage" ] ||
|
||||
fail "public/storage ja existe."
|
||||
|
||||
ln -s "$ACTIVE_STORAGE/app/public" "$NEW_RELEASE/public/storage"
|
||||
|
||||
log "Conferir a mesma entrega integrada de Compras."
|
||||
/usr/bin/php8.4 "$OLD_RELEASE/scripts/verify-compras-release.php" "$NEW_RELEASE" || fail "Fonte incompleta ou sem manifesto de entrega."
|
||||
|
||||
log "Instalar dependencias PHP."
|
||||
|
||||
/usr/bin/php8.4 /usr/local/bin/composer install \
|
||||
--no-dev \
|
||||
--prefer-dist \
|
||||
--optimize-autoloader \
|
||||
--no-interaction
|
||||
|
||||
log "Instalar dependencias frontend."
|
||||
|
||||
/usr/bin/npm ci --no-audit --no-fund
|
||||
|
||||
log "Compilar frontend."
|
||||
|
||||
/usr/bin/npm run build
|
||||
|
||||
[ -f "$NEW_RELEASE/vendor/autoload.php" ] ||
|
||||
fail "Autoload Composer inexistente."
|
||||
|
||||
[ -f "$NEW_RELEASE/public/build/manifest.json" ] ||
|
||||
fail "Manifest frontend inexistente."
|
||||
|
||||
log "Preparar caches Laravel."
|
||||
|
||||
/usr/bin/php8.4 artisan config:cache
|
||||
|
||||
# As vistas compiladas utilizam storage partilhado.
|
||||
# Nao executar view:cache durante a preparacao.
|
||||
|
||||
log "Validar Laravel."
|
||||
|
||||
/usr/bin/php8.4 artisan about --only=environment
|
||||
|
||||
log "Validar ficheiros essenciais."
|
||||
|
||||
[ -f "$NEW_RELEASE/public/index.php" ] ||
|
||||
fail "public/index.php inexistente."
|
||||
|
||||
[ -r "$NEW_RELEASE/.env" ] ||
|
||||
fail ".env inacessivel."
|
||||
|
||||
[ -r "$NEW_RELEASE/public/build/manifest.json" ] ||
|
||||
fail "Manifest inacessivel."
|
||||
|
||||
/usr/bin/php8.4 "$OLD_RELEASE/scripts/verify-compras-release.php" "$NEW_RELEASE" --installed || fail "Compilacao ou componentes diferem da entrega declarada."
|
||||
|
||||
log "Validar release antes da activacao."
|
||||
|
||||
[ "$(readlink -f "$CURRENT")" = "$OLD_RELEASE" ] ||
|
||||
fail "Current foi alterado durante a preparacao."
|
||||
|
||||
[ "$(git -C "$NEW_RELEASE" rev-parse HEAD)" = "$TARGET_COMMIT" ] ||
|
||||
fail "Commit da nova release invalido."
|
||||
|
||||
log "Activar release."
|
||||
|
||||
TEMP_LINK="$BASE/.current-next-$$"
|
||||
|
||||
ln -s "$NEW_RELEASE" "$TEMP_LINK"
|
||||
|
||||
mv -Tf "$TEMP_LINK" "$CURRENT"
|
||||
|
||||
[ "$(readlink -f "$CURRENT")" = "$NEW_RELEASE" ] ||
|
||||
fail "Current nao aponta para a nova release."
|
||||
|
||||
log "Executar health check local."
|
||||
|
||||
[ "$(readlink -f "$CURRENT")" = "$NEW_RELEASE" ] ||
|
||||
fail "Release activa inesperada."
|
||||
|
||||
HEALTH_OK=0
|
||||
|
||||
for attempt in 1 2 3 4 5; do
|
||||
HTTP_CODE="$(
|
||||
/usr/bin/curl \
|
||||
--noproxy '*' \
|
||||
--silent \
|
||||
--show-error \
|
||||
--output /dev/null \
|
||||
--write-out '%{http_code}' \
|
||||
--resolve "$HOST:443:127.0.0.1" \
|
||||
--max-time 15 \
|
||||
"https://$HOST/dashboard" || true
|
||||
)"
|
||||
|
||||
log "Health check $attempt: HTTP $HTTP_CODE"
|
||||
|
||||
if [ "$HTTP_CODE" = "200" ]; then
|
||||
HEALTH_OK=1
|
||||
break
|
||||
fi
|
||||
|
||||
sleep 3
|
||||
done
|
||||
|
||||
if [ "$HEALTH_OK" -ne 1 ]; then
|
||||
log "Health check falhou. Iniciar rollback."
|
||||
|
||||
ROLLBACK_LINK="$BASE/.current-rollback-$$"
|
||||
|
||||
[ "$(readlink -f "$CURRENT")" = "$NEW_RELEASE" ] ||
|
||||
fail "Current foi alterado; rollback automatico interrompido."
|
||||
|
||||
ln -s "$OLD_RELEASE" "$ROLLBACK_LINK"
|
||||
|
||||
mv -Tf "$ROLLBACK_LINK" "$CURRENT"
|
||||
|
||||
log "Rollback efectuado para $OLD_RELEASE"
|
||||
|
||||
exit 1
|
||||
fi
|
||||
|
||||
log "Publicacao concluida."
|
||||
log "Release activa: $(readlink -f "$CURRENT")"
|
||||
log "Commit publicado: $TARGET_COMMIT"
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Inspect native authenticated views without changing business data or permissions."""
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
spec = importlib.util.spec_from_file_location('native', '/root/check-public-demonstration.py')
|
||||
native = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(native)
|
||||
identities = json.loads(Path('/root/compras-demo-access.json').read_text())
|
||||
checks = []
|
||||
for profile, paths in {
|
||||
'procurement': ['/dashboard', '/requisicoes', '/cotacoes', '/ordens', '/ordens/1', '/compras/importacoes/12/documentos'],
|
||||
'warehouse': ['/recepcoes', '/stock'],
|
||||
'finance': ['/facturas', '/orcamentos', '/relatorios'],
|
||||
'direction': ['/pessoas', '/pessoas/1'],
|
||||
'auditor': ['/auditoria/privada'],
|
||||
}.items():
|
||||
client = native.Client(identities[profile], 'https://compras.tempo.co.mz')
|
||||
entry = client.request('/')
|
||||
assert entry['status'] == 302 and entry['location'].endswith('/dashboard')
|
||||
for path in paths:
|
||||
response = client.request(path)
|
||||
page = response['page'] or {}
|
||||
props = page.get('props', {})
|
||||
collections = {}
|
||||
for key, value in props.items():
|
||||
if isinstance(value, dict) and isinstance(value.get('data'), list):
|
||||
collections[key] = {'rows': len(value['data']), 'total': value.get('total')}
|
||||
elif isinstance(value, list) and key in ['items', 'orders', 'invoices', 'documents', 'budgets', 'balances']:
|
||||
collections[key] = {'rows': len(value)}
|
||||
checks.append({'profile': profile, 'path': path, 'status': response['status'], 'component': page.get('component'),
|
||||
'authenticated': bool(props.get('auth', {}).get('user')), 'collections': collections,
|
||||
'flags': {k: v for k, v in props.items() if isinstance(v, bool) and (k.startswith('can') or k.endswith('Available') or k == 'ready')},
|
||||
'context_enforced': (props.get('workContext') or {}).get('enforced')})
|
||||
assert all(c['status'] == 200 and c['authenticated'] and c['component'] not in [None, 'home']
|
||||
and (c['component'] != 'work-context' or c['path'] == '/dashboard') for c in checks)
|
||||
empty = [c for c in checks if c['collections'] and sum(v['rows'] for v in c['collections'].values()) == 0]
|
||||
assert not empty, json.dumps(empty)
|
||||
proof = {'state': 'passed', 'release_id': json.loads(Path('/var/www/compras-deploy/current/compras-release.json').read_text())['release_id'],
|
||||
'authenticated_root_redirects_to_dashboard': True, 'authenticated_workspace_checks': checks, 'business_data_changed': False, 'permissions_changed': False}
|
||||
Path('/var/www/compras-deploy/demonstration-20261129/workspace-visibility.json').write_text(json.dumps(proof, indent=2)+'\n')
|
||||
print(json.dumps(proof, indent=2))
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Complete real native HTTP hiring commands with explicitly synthetic client records."""
|
||||
from pathlib import Path
|
||||
from datetime import date
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
assert sys.argv[1:] == ['--exercise-authorized-synthetic']
|
||||
spec = importlib.util.spec_from_file_location('native', '/root/check-public-demonstration.py')
|
||||
native = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(native)
|
||||
credentials = json.loads(Path('/root/compras-demo-access.json').read_text())
|
||||
clients = {key: native.Client(credentials[key], 'https://compras.tempo.co.mz') for key in ['admin', 'head', 'direction']}
|
||||
identities = {}
|
||||
for key, client in clients.items():
|
||||
identities[key] = client.request('/dashboard')['page']['props']['auth']['user']['id']
|
||||
client.work_context = {}
|
||||
assert client.request('/contexto', 'POST', {'area': 'people', 'option': 'people.third_party'})['status'] in [302, 303]
|
||||
|
||||
admin = clients['admin']
|
||||
state_path = Path('/var/www/compras-deploy/demonstration-20261129/client-hiring-native-progress.private.json')
|
||||
state = json.loads(state_path.read_text()) if state_path.exists() else {'processes': {}}
|
||||
|
||||
def save():
|
||||
state_path.write_text(json.dumps(state, indent=2)+'\n')
|
||||
state_path.chmod(0o600)
|
||||
|
||||
def ok(result):
|
||||
assert result['status'] in [302, 303], 'Native command refused: '+str(result['status'])+' '+result['text'][:500]
|
||||
return result
|
||||
|
||||
listing = admin.request('/empresa/clientes')
|
||||
assert listing['status'] == 200
|
||||
matches = [row for row in listing['page']['props']['clients']['data'] if row['code'] == 'DEMO-CLIENTE-001']
|
||||
if not matches:
|
||||
key = str(uuid.uuid5(uuid.NAMESPACE_URL, 'https://compras.tempo.co.mz/authorized-synthetic-client-20261129'))
|
||||
ok(admin.request('/empresa/clientes', 'POST', {'client_key': key, 'code': 'DEMO-CLIENTE-001',
|
||||
'name': 'Cliente Fictício — Apresentação', 'active': True, 'reason': 'Entidade inteiramente fictícia para demonstrar o circuito de contratação para clientes.'}))
|
||||
matches = [row for row in admin.request('/empresa/clientes')['page']['props']['clients']['data'] if row['code'] == 'DEMO-CLIENTE-001']
|
||||
assert len(matches) == 1
|
||||
customer = matches[0]
|
||||
assert customer['name'] == 'Cliente Fictício — Apresentação' and customer['active']
|
||||
checks = []
|
||||
for kind in ['service', 'staff']:
|
||||
entry = state['processes'].setdefault(kind, {})
|
||||
if 'id' not in entry:
|
||||
result = ok(admin.request('/pessoas', 'POST', {
|
||||
'operation_key': str(uuid.uuid5(uuid.NAMESPACE_URL, 'https://compras.tempo.co.mz/authorized-client-hiring-'+kind+'-20261129')),
|
||||
'kind': kind, 'title': ('Prestador' if kind == 'service' else 'Trabalhador')+' para cliente — Processo fictício',
|
||||
'purpose': 'Necessidade inteiramente fictícia para apresentação do circuito real da aplicação, sem contratação de pessoa real.',
|
||||
'closes_on': date.today().isoformat(), 'minimum_reviews': 1,
|
||||
'criteria': [{'label': 'Competências técnicas', 'weight': 60}, {'label': 'Experiência relevante', 'weight': 40}],
|
||||
'client_id': customer['id'], 'client_version': customer['version']}))
|
||||
entry['id'] = int(result['location'].rstrip('/').split('/')[-1])
|
||||
save()
|
||||
path = '/pessoas/'+str(entry['id'])
|
||||
def page():
|
||||
result = admin.request(path)
|
||||
assert result['status'] == 200
|
||||
return result['page']['props']
|
||||
def command(actor, action, fields=None):
|
||||
return ok(clients[actor].request(path+'/'+action, 'POST', {
|
||||
'version': page()['process']['version'], 'reason': 'Operação inteiramente fictícia para apresentação autorizada do circuito para clientes.',
|
||||
'no_conflict': True, **(fields or {})}))
|
||||
for actor, scopes in [('head', ['view', 'review', 'interviews']), ('direction', ['view', 'approve', 'contract_view'])]:
|
||||
access = admin.request(path+'/acessos')['page']['props']
|
||||
existing = [a for a in access['assignments'] if a['user_id'] == identities[actor]]
|
||||
if not existing:
|
||||
ok(admin.request(path+'/acessos', 'POST', {'version': access['version'], 'user_id': identities[actor],
|
||||
'scopes': scopes, 'reason': 'Equipa de apresentação explicitamente atribuída a este processo fictício.'}))
|
||||
else:
|
||||
assert set(existing[0]['scopes']) == set(scopes)
|
||||
if page()['process']['status'] == 'draft':
|
||||
command('head', 'open')
|
||||
if page()['process']['status'] == 'open':
|
||||
command('admin', 'apply', {'operation_key': str(uuid.uuid5(uuid.NAMESPACE_URL, path+'/synthetic-candidate')),
|
||||
'name': 'Pessoa Fictícia — Cliente', 'reference': 'DEMO-CAND-CLIENTE-'+kind.upper(),
|
||||
'summary': 'Competências e experiência inteiramente fictícias para demonstrar a conferência do processo.', 'received_on': date.today().isoformat()})
|
||||
command('admin', 'close')
|
||||
detail = page()
|
||||
application = detail['candidates'][0]
|
||||
if detail['process']['status'] == 'assessment':
|
||||
if not application.get('evaluation_count'):
|
||||
command('head', 'evaluate', {'application_id': application['id'], 'answers': [
|
||||
{'score': 8, 'evidence': 'Competências fictícias documentadas apenas para apresentação.'},
|
||||
{'score': 7, 'evidence': 'Experiência fictícia documentada apenas para apresentação.'}]})
|
||||
command('admin', 'select', {'application_id': application['id']})
|
||||
if page()['process']['status'] == 'selection_review':
|
||||
assert admin.request(path+'/confirm', 'POST', {'version': page()['process']['version'], 'reason': 'Conferência negativa da autoridade de decisão.', 'no_conflict': True, 'outcome': 'approved'})['status'] == 403
|
||||
command('direction', 'confirm', {'outcome': 'approved'})
|
||||
if page()['process']['status'] == 'selected':
|
||||
command('admin', 'contract', {'reference': 'DEMO-CLIENTE-MINUTA-'+kind.upper(), 'starts_on': date.today().isoformat(),
|
||||
'terms': 'Condições inteiramente fictícias entre as entidades identificadas; sem contrato real, admissão ou envio a RH.'})
|
||||
# Signed-document upload is a native multipart command; the PDF is explicitly fictitious.
|
||||
direction = clients['direction']
|
||||
if page()['process']['status'] == 'contract_draft':
|
||||
stream = b'BT /F1 14 Tf 30 700 Td (DEMONSTRACAO - DOCUMENTO FICTICIO) Tj 0 -30 Td (Sem contrato ou assinatura real. Sem admissao em RH.) Tj ET'
|
||||
objects = [b'<< /Type /Catalog /Pages 2 0 R >>', b'<< /Type /Pages /Kids [3 0 R] /Count 1 >>', b'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>', b'<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>', b'<< /Length '+str(len(stream)).encode()+b' >>\nstream\n'+stream+b'\nendstream']
|
||||
pdf = b'%PDF-1.4\n'; offsets = []
|
||||
for number, obj in enumerate(objects, 1):
|
||||
offsets.append(len(pdf)); pdf += str(number).encode()+b' 0 obj\n'+obj+b'\nendobj\n'
|
||||
start = len(pdf); pdf += b'xref\n0 6\n0000000000 65535 f \n'
|
||||
for offset in offsets: pdf += f'{offset:010d} 00000 n \n'.encode()
|
||||
pdf += b'trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n'+str(start).encode()+b'\n%%EOF\n'
|
||||
boundary = 'compras-client-'+uuid.uuid4().hex
|
||||
fields = {'version': str(page()['process']['version']), 'operation_key': str(uuid.uuid5(uuid.NAMESPACE_URL, path+'/synthetic-formalization')),
|
||||
'reference': 'DEMO-CLIENTE-ASSINADO-'+kind.upper(), 'signed_on': date.today().isoformat(), 'no_conflict': '1',
|
||||
'reason': 'Confirmação fictícia pela Direcção da prestadora, sem assinatura ou contrato real.'}
|
||||
body = b''
|
||||
for key, value in fields.items(): body += f'--{boundary}\r\nContent-Disposition: form-data; name="{key}"\r\n\r\n{value}\r\n'.encode()
|
||||
body += f'--{boundary}\r\nContent-Disposition: form-data; name="signed_document"; filename="demonstracao-cliente.pdf"\r\nContent-Type: application/pdf\r\n\r\n'.encode()+pdf+f'\r\n--{boundary}--\r\n'.encode()
|
||||
ok(direction.request(path+'/formalizar', 'POST', body, content_type='multipart/form-data; boundary='+boundary))
|
||||
dossier = direction.request(path+'/dossier.json')['page']
|
||||
assert dossier['process']['status'] == 'contract_formalized' and dossier['process']['rules']['client']['id'] == customer['id']
|
||||
assert dossier['process']['rules']['decision_authority'] == 'provider_direction'
|
||||
assert 'path' not in dossier['process']['contract']['signed_document']
|
||||
signed = direction.request(path+'/contrato-assinado', inertia=False)
|
||||
assert signed['status'] == 200 and hashlib.sha256(signed['raw']).hexdigest() == dossier['process']['contract']['signed_document']['sha256']
|
||||
ok(admin.request('/contexto', 'POST', {'area': 'people', 'option': 'people.internal'}))
|
||||
assert admin.request(path)['status'] == 404
|
||||
ok(admin.request('/contexto', 'POST', {'area': 'people', 'option': 'people.third_party'}))
|
||||
checks.append({'kind': kind, 'process_id': entry['id'], 'status': 'contract_formalized', 'client_identity_preserved': True,
|
||||
'provider_direction_confirmed': True, 'internal_context_access_refused': True, 'signed_document_hash_verified': True})
|
||||
proof = {'state': 'passed', 'normal_authenticated_http': True, 'synthetic_client_id': customer['id'], 'checks': checks,
|
||||
'employee_admission_or_external_dispatch': False}
|
||||
Path('/var/www/compras-deploy/demonstration-20261129/client-hiring-http.json').write_text(json.dumps(proof, indent=2)+'\n')
|
||||
print(json.dumps(proof))
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\CapitalRegister;
|
||||
use App\Services\OperationalOrders;
|
||||
use App\Services\OrganizationConfiguration;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use App\Services\SupplyPlanning;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
if (($argv[1] ?? '') !== '--initialize-authorized-synthetic' || config('app.demonstration') !== true || DB::connection()->getDatabaseName() !== 'compras_demo_20261129') {
|
||||
throw new LogicException('Explicit public synthetic company required.');
|
||||
}
|
||||
try {
|
||||
$admin = User::query()->where('email', 'admin@demo.compras.tempo.co.mz')->sole();
|
||||
auth()->guard()->setUser($admin);
|
||||
$organization = app(OrganizationConfiguration::class);
|
||||
$version = fn () => DB::table('organization_access')->where('tenant_id', $admin->tenant_id)->value('version');
|
||||
if (! User::query()->where('email', 'admin_review@demo.compras.tempo.co.mz')->exists()) {
|
||||
$bytes = file_get_contents($argv[2]);
|
||||
if (! is_string($bytes)) {
|
||||
throw new LogicException('Private synthetic administrator credential unavailable.');
|
||||
}
|
||||
$credential = json_decode($bytes, true, 32, JSON_THROW_ON_ERROR)['admin_review'];
|
||||
$profile = DB::table('organization_memberships')->where('tenant_id', $admin->tenant_id)->where('user_id', $admin->id)->value('profile_id');
|
||||
$organization->execute($admin, 'user', ['version' => $version(), 'department_id' => $admin->department_id,
|
||||
'name' => 'Administração suplente — Demonstração', 'email' => $credential['email'], 'password' => $credential['password'],
|
||||
'profile_ids' => [$profile], 'reason' => 'Segundo administrador permanente fictício para preservar o mínimo nativo.']);
|
||||
}
|
||||
if (Tenant::query()->findOrFail($admin->tenant_id)->rules_provisional) {
|
||||
$organization->execute($admin, 'rules', ['version' => $version(), 'first_limit' => '25000.00', 'second_limit' => '150000.00', 'includes_tax' => true,
|
||||
'reason' => 'Alçadas exclusivamente ilustrativas da empresa fictícia para apresentação.']);
|
||||
}
|
||||
$names = ['admin' => 'Administração', 'admin_review' => 'Administração suplente', 'requester' => 'Requisitante', 'head' => 'Chefia',
|
||||
'procurement' => 'Compras', 'finance' => 'Finanças — preparação', 'finance_review' => 'Finanças — revisão', 'warehouse' => 'Armazém', 'direction' => 'Direcção', 'auditor' => 'Auditoria'];
|
||||
foreach ($names as $key => $name) {
|
||||
$user = User::query()->where('tenant_id', $admin->tenant_id)->where('email', $key.'@demo.compras.tempo.co.mz')->sole();
|
||||
if ($user->name !== $name.' — Demonstração') {
|
||||
$before = $user->only(['id', 'name']);
|
||||
$user->name = $name.' — Demonstração';
|
||||
$user->save();
|
||||
app(RequisitionWorkflow::class)->audit($admin, 'demonstration.label_corrected', null, $before, $user->only(['id', 'name']));
|
||||
}
|
||||
}
|
||||
$reviewer = User::query()->where('email', 'finance_review@demo.compras.tempo.co.mz')->sole();
|
||||
$profileId = DB::table('organization_memberships')->where('user_id', $reviewer->id)->value('profile_id');
|
||||
$profile = DB::table('organization_profiles')->where('id', $profileId)->first();
|
||||
$permissions = json_decode($profile->permissions, true, 32, JSON_THROW_ON_ERROR);
|
||||
if (! in_array('supply_review', $permissions, true)) {
|
||||
$organization->execute($admin, 'profile', ['version' => $version(), 'id' => $profileId, 'name' => 'Finanças — revisão de demonstração',
|
||||
'permissions' => [...$permissions, 'supply_read', 'supply_review'], 'work_contexts' => ['procurement.internal', 'people.internal'],
|
||||
'reason' => 'Conferência independente fictícia das políticas de stock na demonstração.']);
|
||||
}
|
||||
$orders = app(OperationalOrders::class);
|
||||
$policy = SupplyRecord::query()->where('kind', 'op_order_policy')->latest('version')->first();
|
||||
if ($policy === null) {
|
||||
$policy = $orders->configure($admin, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'mode' => 'procurement',
|
||||
'reason' => 'Cadastro por Compras quando os locais de utilização não estão abrangidos, apenas para demonstração.']);
|
||||
}
|
||||
$buyer = User::query()->where('email', 'procurement@demo.compras.tempo.co.mz')->sole();
|
||||
auth()->guard()->setUser($buyer);
|
||||
foreach (['production' => 'DEMO-OP-001', 'maintenance' => 'DEMO-OM-001'] as $type => $reference) {
|
||||
if (! SupplyRecord::query()->where('kind', 'op_order')->where('data->reference', $reference)->exists()) {
|
||||
$orders->save($buyer, ['operation_key' => (string) Str::uuid(), 'type' => $type, 'reference' => $reference,
|
||||
'department_id' => $buyer->department_id, 'utilisation_location' => 'Local fictício de demonstração', 'description' => 'Ordem fictícia para demonstrar a origem das necessidades de compra.',
|
||||
'policy_version' => $policy->version, 'reason' => 'Cadastro sintético pelo agente de Compras conforme a origem seleccionada.']);
|
||||
}
|
||||
}
|
||||
foreach (['project' => 'DEMO-PROJECTO', 'asset' => 'DEMO-ACTIVO'] as $type => $code) {
|
||||
if (! SupplyRecord::query()->where('kind', 'capital_register')->where('data->code', $code)->exists()) {
|
||||
app(CapitalRegister::class)->save($buyer, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'type' => $type, 'code' => $code,
|
||||
'name' => ($type === 'project' ? 'Projecto' : 'Activo').' fictício de demonstração', 'department_id' => $buyer->department_id,
|
||||
'reference' => 'Referência ilustrativa própria de Compras', 'state' => 'active', 'reason' => 'Cadastro fictício independente, sem lançamento ou integração SGF.']);
|
||||
}
|
||||
}
|
||||
$planning = app(SupplyPlanning::class);
|
||||
$stockPolicy = $planning->latest('policy')->where('stock_item_id', 1)->where('warehouse_id', 1)->first();
|
||||
if ($stockPolicy === null) {
|
||||
$stockPolicy = $planning->save($buyer, 'policy', ['operation_key' => (string) Str::uuid(), 'version' => 0, 'action' => 'save',
|
||||
'reason' => 'Valores ilustrativos de stock mínimo, natureza e utilização na empresa fictícia.',
|
||||
'data' => ['stock_item_id' => 1, 'warehouse_id' => 1, 'purpose' => 'internal', 'origin' => 'local', 'safety_milli' => 10000,
|
||||
'minimum_stock_milli' => 20000, 'target_milli' => 100000, 'maximum_milli' => 120000, 'daily_milli' => 1000, 'lead_days' => 5,
|
||||
'approval_days' => 1, 'horizon_days' => 30, 'minimum_milli' => 10000, 'pack_milli' => 1000,
|
||||
'usage_context' => 'Papel consumível, utilização fictícia no escritório.', 'basis' => 'Consumo e limites exclusivamente ilustrativos para apresentação.']]);
|
||||
}
|
||||
if ($stockPolicy->state !== 'approved') {
|
||||
auth()->guard()->setUser($reviewer);
|
||||
$stockPolicy = $planning->save($reviewer, 'policy', ['operation_key' => (string) Str::uuid(), 'record_key' => $stockPolicy->record_key,
|
||||
'version' => $stockPolicy->version, 'action' => 'approve', 'reason' => 'Conferência independente dos parâmetros fictícios de stock.', 'data' => []]);
|
||||
}
|
||||
echo json_encode(['state' => 'passed', 'permanent_administrators' => count($organization->permanentAdministrators($admin->tenant_id)),
|
||||
'operational_origin' => 'procurement', 'stock_minimum_milli' => $stockPolicy->data['minimum_stock_milli'], 'stock_policy_state' => $stockPolicy->state], JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
} catch (Throwable $error) {
|
||||
fwrite(STDERR, $error::class.': '.$error->getMessage().PHP_EOL);
|
||||
exit(1);
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs','assert','return (async()=>{' + common + `
|
||||
await new Function('fs','assert','outputFile','return (async()=>{' + common + `
|
||||
const rows=[], prints=new Set();
|
||||
const paths=['/ordens','/recepcoes','/stock','/stock/requisicoes','/equipamentos','/orcamentos','/facturas','/pagamentos','/planeamento','/revisao-compras','/relatorios','/relatorios/medidas-fornecedores','/compras/fornecimento?view=calendar','/compras/fornecimento?view=imports','/compras/acordos/vigencia'];
|
||||
for(const role of ['admin','procurement','finance','warehouse']){
|
||||
@@ -25,6 +25,6 @@ await new Function('fs','assert','return (async()=>{' + common + `
|
||||
}
|
||||
}
|
||||
}
|
||||
await fs.writeFile('docs/proofs/final-review-inventory.json',JSON.stringify({environment:base,scope:'existing authorised records only',rows,print_paths:[...prints],business_commands:false,visual_review:false},null,2));
|
||||
await fs.writeFile(outputFile,JSON.stringify({environment:base,scope:'existing authorised records only',rows,print_paths:[...prints],business_commands:false,visual_review:false},null,2));
|
||||
console.log(JSON.stringify({routes_checked:rows.length,print_paths:[...prints],statuses:rows.reduce((a,r)=>(a[r.status]=(a[r.status]??0)+1,a),{})}));
|
||||
`+'})()')(fs,assert);
|
||||
`+'})()')(fs,assert,process.argv[2]??'docs/proofs/final-review-inventory.json');
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Guarded installation of the authorised client hiring flow in the selected application."""
|
||||
from pathlib import Path
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
import zipfile
|
||||
|
||||
root = Path('/var/www/compras-deploy/current').resolve()
|
||||
assert root == Path('/var/www/compras-deploy/releases/presentation-20261129')
|
||||
archive = Path('/root/compras-release-client-hiring.zip')
|
||||
assert hashlib.sha256(archive.read_bytes()).hexdigest() == 'e6ecf82d0943fab658c65fff6b5d9c1c194104e743c38b158eb87fa8fe091e79'
|
||||
z = zipfile.ZipFile(archive)
|
||||
old = json.loads((root/'compras-release.json').read_text())
|
||||
new = json.loads(z.read('compras-release.json'))
|
||||
assert old['release_id'] == 'compras-47dfeee7485db877' and new['release_id'] == 'compras-e4e3196d1877e804'
|
||||
assert old['components'] == new['components']
|
||||
assert set(old['source_files']) <= set(new['source_files'])
|
||||
changed = [n for n in old['source_files'] if old['source_files'][n] != new['source_files'][n]]
|
||||
added = [n for n in new['source_files'] if n not in old['source_files']]
|
||||
print(json.dumps({'changed': changed, 'added': added}), flush=True)
|
||||
if '--install-authorized' not in sys.argv:
|
||||
sys.exit(0)
|
||||
allowed = {'app/Http/Controllers/PeopleHiringController.php', 'app/Http/Controllers/PeopleReportController.php',
|
||||
'app/Http/Middleware/EnsureWorkContext.php', 'app/Models/Concerns/HasWorkContext.php',
|
||||
'app/Services/PeopleAccess.php', 'app/Services/PeopleHiring.php', 'app/Services/PeopleWorkdesk.php',
|
||||
'app/Console/Commands/SgcDeliveryCheck.php', 'app/Services/WorkContext.php',
|
||||
'resources/js/lib/procurement-navigation.ts', 'resources/js/pages/people/index.tsx',
|
||||
'resources/js/pages/people/show.tsx', 'routes/preview.php', 'routes/web.php'}
|
||||
expected_added = {'app/Models/BusinessClient.php', 'app/Services/BusinessClients.php', 'app/Services/ThirdPartyHiring.php',
|
||||
'app/Http/Controllers/BusinessClientController.php', 'config/third_party.php',
|
||||
'database/migrations/2026_11_29_000004_create_business_clients.php', 'resources/js/pages/company/clients.tsx'}
|
||||
assert set(changed) <= allowed and set(added) == expected_added
|
||||
subprocess.run(['/usr/bin/php', str(root/'scripts/verify-compras-release.php'), str(root), '--installed'], check=True)
|
||||
backup = Path('/var/backups/compras-presentation-20261129/client-hiring-installed')
|
||||
backup.mkdir(mode=0o700, exist_ok=False)
|
||||
env = (root/'.env').resolve()
|
||||
assert env == Path('/var/www/compras-deploy/demonstration-20261129/.env')
|
||||
env_attributes = env.stat()
|
||||
assert env_attributes.st_gid == __import__('grp').getgrnam('www-data').gr_gid and env_attributes.st_mode & 0o040
|
||||
shutil.copy2(env, backup/'selected.env.private')
|
||||
(backup/'selected.env.private').chmod(0o600)
|
||||
saved = changed + ['compras-release.json', 'public/build/manifest.json', 'public/build/fonts-manifest.json']
|
||||
for name in saved:
|
||||
destination = backup/name
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(root/name, destination)
|
||||
with (backup/'database.dump').open('xb') as stream:
|
||||
subprocess.run(['runuser', '-u', 'postgres', '--', 'pg_dump', '-Fc', '-d', 'compras_demo_20261129'], stdout=stream, check=True)
|
||||
|
||||
def write(name, data):
|
||||
assert not Path(name).is_absolute() and '..' not in Path(name).parts
|
||||
path = root/name
|
||||
assert not path.is_symlink()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temp = path.with_name(path.name+'.client-next')
|
||||
temp.write_bytes(data)
|
||||
temp.chmod(0o644)
|
||||
os.replace(temp, path)
|
||||
|
||||
def php(*args):
|
||||
result = subprocess.run(['runuser', '-u', 'www-data', '--', '/usr/bin/php', *args], cwd=root, capture_output=True)
|
||||
if result.returncode:
|
||||
diagnostic = backup/'failed-command.private.log'
|
||||
diagnostic.write_bytes(result.stdout+result.stderr)
|
||||
diagnostic.chmod(0o600)
|
||||
raise RuntimeError('Native command failed; private diagnostic: '+str(diagnostic))
|
||||
return result.stdout.decode()
|
||||
|
||||
restore = 'compras_client_restore_'+uuid.uuid4().hex[:12]
|
||||
created = False
|
||||
maintenance = False
|
||||
try:
|
||||
migration = 'database/migrations/2026_11_29_000004_create_business_clients.php'
|
||||
write(migration, z.read(migration))
|
||||
write('scripts/upgrade-client-registry.php', Path('/root/upgrade-client-registry.php').read_bytes())
|
||||
isolation = json.loads(Path('/var/backups/compras-presentation-20261129/client-registry-isolation.json').read_text())
|
||||
assert isolation['state'] == 'passed' and isolation['active_registry_unchanged'] and isolation['active_empty_schema_matches_native_migration']
|
||||
recovery = isolation['recovery_upgrade']
|
||||
assert recovery['state'] == 'passed'
|
||||
php('artisan', 'down', '--retry=3')
|
||||
maintenance = True
|
||||
for name in changed+added:
|
||||
write(name, z.read(name))
|
||||
schema = json.loads(php('scripts/upgrade-client-registry.php', '--record-verified-empty-registry'))
|
||||
assert schema['state'] == 'passed'
|
||||
for asset in new['frontend']['files']:
|
||||
name = 'public/build/'+asset
|
||||
assert not (root/name).exists() or (root/name).read_bytes() == z.read(name), 'Immutable asset collision'
|
||||
if not (root/name).exists():
|
||||
write(name, z.read(name))
|
||||
for name in ['public/build/fonts-manifest.json', 'public/build/manifest.json', 'compras-release.json']:
|
||||
write(name, z.read(name))
|
||||
lines = env.read_text().splitlines()
|
||||
assert not any(line.startswith('SGC_PEOPLE_THIRD_PARTY_ENABLED=') for line in lines)
|
||||
env.write_text('\n'.join(lines)+'\nSGC_PEOPLE_THIRD_PARTY_ENABLED=true\n')
|
||||
php('artisan', 'config:cache')
|
||||
subprocess.run(['/usr/bin/php', str(root/'scripts/verify-compras-release.php'), str(root), '--installed'], check=True)
|
||||
except BaseException:
|
||||
env.write_bytes((backup/'selected.env.private').read_bytes())
|
||||
os.chown(env, env_attributes.st_uid, env_attributes.st_gid)
|
||||
env.chmod(env_attributes.st_mode & 0o777)
|
||||
for name in saved:
|
||||
write(name, (backup/name).read_bytes())
|
||||
php('artisan', 'config:cache')
|
||||
raise
|
||||
finally:
|
||||
if maintenance:
|
||||
php('artisan', 'up')
|
||||
if created:
|
||||
subprocess.run(['runuser', '-u', 'postgres', '--', 'dropdb', restore], check=True)
|
||||
proof = {'state': 'passed', 'release_id': new['release_id'], 'backup': str(backup),
|
||||
'same_selected_application': True, 'recovery_copy_upgrade': recovery, 'selected_schema_upgrade': schema,
|
||||
'new_configuration': {'SGC_PEOPLE_THIRD_PARTY_ENABLED': True}, 'existing_permissions_changed': False,
|
||||
'external_financial_or_hr_dispatch': False, 'temporary_recovery_database_removed': True}
|
||||
(backup/'result.json').write_text(json.dumps(proof, indent=2)+'\n')
|
||||
print(json.dumps(proof))
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Install the authorised access correction in the same selected Compras installation."""
|
||||
from pathlib import Path
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import zipfile
|
||||
|
||||
root = Path('/var/www/compras-deploy/current').resolve()
|
||||
assert root == Path('/var/www/compras-deploy/releases/presentation-20261129')
|
||||
old = json.loads((root/'compras-release.json').read_text())
|
||||
assert old['release_id'] == 'compras-a2711a98b34fceb3'
|
||||
subprocess.run(['/usr/bin/php', str(root/'scripts/verify-compras-release.php'), str(root), '--installed'], check=True)
|
||||
archive = Path('/root/compras-release-access.zip')
|
||||
assert hashlib.sha256(archive.read_bytes()).hexdigest() == '1d1ca615ea9fe2bf4a3247f073f7be0f8ef12e305244df7e281999713c0c49e9'
|
||||
z = zipfile.ZipFile(archive)
|
||||
new = json.loads(z.read('compras-release.json'))
|
||||
assert new['release_id'] == 'compras-e5c8c140738b6e1e'
|
||||
assert old['components'] == new['components']
|
||||
assert set(old['source_files']) == set(new['source_files'])
|
||||
changed = [n for n in new['source_files'] if new['source_files'][n] != old['source_files'][n]]
|
||||
assert set(changed) == {'routes/web.php', 'resources/js/pages/auth/login.tsx', 'resources/js/pages/home.tsx', 'resources/js/components/sgc-workspace-shell.tsx'}
|
||||
backup = Path('/var/backups/compras-presentation-20261129/access-fix')
|
||||
backup.mkdir(mode=0o700, exist_ok=False)
|
||||
paths = changed + ['public/build/manifest.json', 'public/build/fonts-manifest.json', 'compras-release.json']
|
||||
for name in paths:
|
||||
dest = backup/name
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(root/name, dest)
|
||||
def write(name, data):
|
||||
assert not Path(name).is_absolute() and '..' not in Path(name).parts
|
||||
dest = root/name
|
||||
assert not dest.is_symlink()
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
temp = dest.with_name(dest.name+'.access-next')
|
||||
temp.write_bytes(data)
|
||||
temp.chmod(0o644)
|
||||
os.replace(temp, dest)
|
||||
try:
|
||||
for name in changed:
|
||||
write(name, z.read(name))
|
||||
for name in new['frontend']['files']:
|
||||
target = 'public/build/'+name
|
||||
if (root/target).exists():
|
||||
assert (root/target).read_bytes() == z.read(target), 'Immutable asset collision'
|
||||
else:
|
||||
write(target, z.read(target))
|
||||
for name in ['public/build/fonts-manifest.json', 'public/build/manifest.json', 'compras-release.json']:
|
||||
write(name, z.read(name))
|
||||
subprocess.run(['/usr/bin/php', str(root/'scripts/verify-compras-release.php'), str(root), '--installed'], check=True)
|
||||
except BaseException:
|
||||
for name in paths:
|
||||
write(name, (backup/name).read_bytes())
|
||||
raise
|
||||
proof = {'state': 'installed', 'release_id': new['release_id'], 'previous_release_id': old['release_id'],
|
||||
'changed_files': changed, 'backup': str(backup), 'data_settings_permissions_changed': False,
|
||||
'guest_root': '/login', 'authenticated_root': '/dashboard', 'public_presentation': '/apresentacao',
|
||||
'public_screens_preserved_with_visible_login': True}
|
||||
(backup/'result.json').write_text(json.dumps(proof, indent=2)+'\n')
|
||||
print(json.dumps(proof))
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Preserve exact historical private audit archives during the approved context alignment."""
|
||||
from pathlib import Path
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import zipfile
|
||||
|
||||
root = Path('/var/www/compras-deploy/current').resolve()
|
||||
assert root == Path('/var/www/compras-deploy/releases/presentation-20261129')
|
||||
old = json.loads((root/'compras-release.json').read_text())
|
||||
assert old['release_id'] == 'compras-46427a85474ae277'
|
||||
subprocess.run(['/usr/bin/php', str(root/'scripts/verify-compras-release.php'), str(root), '--installed'], check=True)
|
||||
archive = Path('/root/compras-release-pilot-preserved.zip')
|
||||
assert hashlib.sha256(archive.read_bytes()).hexdigest() == 'a7e4473e1417b444a42a484f1ddf4f0fc03b64874cb9c304ef74181b30745940'
|
||||
z = zipfile.ZipFile(archive)
|
||||
new = json.loads(z.read('compras-release.json'))
|
||||
assert new['release_id'] == 'compras-47dfeee7485db877'
|
||||
assert old['frontend'] == new['frontend'] and old['components'] == new['components']
|
||||
changed = [name for name in old['source_files'] if old['source_files'][name] != new['source_files'][name]]
|
||||
assert set(changed) == {'app/Services/PrivateAuditAccess.php', 'app/Services/PrivateAuditExporter.php',
|
||||
'app/Http/Controllers/PrivateAuditController.php', 'config/private-audit.php'}
|
||||
pins = json.loads(subprocess.check_output(['/usr/bin/php', str(root/'scripts/private-audit-transition-pins.php')]))
|
||||
assert list(pins) == ['2'] and len(pins['2']) == 3
|
||||
env = (root/'.env').resolve()
|
||||
assert env == Path('/var/www/compras-deploy/demonstration-20261129/.env')
|
||||
original = env.read_bytes()
|
||||
assert b'COMPRAS_AUDIT_LEGACY_TRANSITIONS=' not in original
|
||||
backup = Path('/var/backups/compras-presentation-20261129/context-audit-preservation')
|
||||
backup.mkdir(mode=0o700, exist_ok=False)
|
||||
shutil.copy2(env, backup/'selected.env.private')
|
||||
(backup/'selected.env.private').chmod(0o600)
|
||||
(backup/'transition-receipt.json').write_text(json.dumps(pins, indent=2)+'\n')
|
||||
for name in changed+['compras-release.json']:
|
||||
target = backup/name
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(root/name, target)
|
||||
def save(path, contents):
|
||||
attrs = path.stat()
|
||||
temp = path.with_name(path.name+'.preservation-next')
|
||||
temp.write_bytes(contents)
|
||||
os.chown(temp, attrs.st_uid, attrs.st_gid)
|
||||
temp.chmod(attrs.st_mode & 0o777)
|
||||
os.replace(temp, path)
|
||||
try:
|
||||
for name in changed+['compras-release.json']:
|
||||
save(root/name, z.read(name))
|
||||
value = json.dumps(json.dumps(pins, separators=(',', ':'))).encode()
|
||||
save(env, original.rstrip()+b'\nCOMPRAS_AUDIT_LEGACY_TRANSITIONS='+value+b'\n')
|
||||
subprocess.run(['runuser', '-u', 'www-data', '--', '/usr/bin/php', 'artisan', 'config:cache'], cwd=root, check=True)
|
||||
subprocess.run(['/usr/bin/php', str(root/'scripts/verify-compras-release.php'), str(root), '--installed'], check=True)
|
||||
except BaseException:
|
||||
save(env, original)
|
||||
for name in changed+['compras-release.json']:
|
||||
save(root/name, (backup/name).read_bytes())
|
||||
subprocess.run(['runuser', '-u', 'www-data', '--', '/usr/bin/php', 'artisan', 'config:cache'], cwd=root, check=True)
|
||||
raise
|
||||
proof = {'state': 'installed', 'release_id': new['release_id'], 'backup': str(backup), 'exact_historical_archives': 3,
|
||||
'archive_bytes_manifest_context_and_database_rows_changed': False, 'profile_permissions_changed': False,
|
||||
'same_original_author_and_current_family_authorities_required': True, 'other_legacy_archives_allowed': False}
|
||||
(backup/'result.json').write_text(json.dumps(proof, indent=2)+'\n')
|
||||
print(json.dumps(proof))
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Apply the expressly requested pilot context configuration to the public sample company."""
|
||||
from pathlib import Path
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import zipfile
|
||||
|
||||
root = Path('/var/www/compras-deploy/current').resolve()
|
||||
assert root == Path('/var/www/compras-deploy/releases/presentation-20261129')
|
||||
manifest = json.loads((root/'compras-release.json').read_text())
|
||||
assert manifest['release_id'] == 'compras-e5c8c140738b6e1e'
|
||||
subprocess.run(['/usr/bin/php', str(root/'scripts/verify-compras-release.php'), str(root), '--installed'], check=True)
|
||||
archive = Path('/root/compras-release-pilot-aligned.zip')
|
||||
assert hashlib.sha256(archive.read_bytes()).hexdigest() == '593fedf62e5f4c4ee55ab5db604a61cd27280eb32fe8c215c1cd4ef0c1c4187c'
|
||||
z = zipfile.ZipFile(archive)
|
||||
next_manifest = json.loads(z.read('compras-release.json'))
|
||||
assert next_manifest['release_id'] == 'compras-46427a85474ae277'
|
||||
assert next_manifest['frontend'] == manifest['frontend'] and next_manifest['components'] == manifest['components']
|
||||
changed = [n for n in manifest['source_files'] if manifest['source_files'][n] != next_manifest['source_files'][n]]
|
||||
assert changed == ['database/migrations/2026_11_22_000002_allow_incomplete_requisition_drafts.php']
|
||||
env = (root/'.env').resolve()
|
||||
assert env == Path('/var/www/compras-deploy/demonstration-20261129/.env')
|
||||
original = env.read_bytes()
|
||||
assert b'SGC_PRODUCT_ENTITLEMENTS=' not in original
|
||||
backup = Path('/var/backups/compras-presentation-20261129/context-alignment')
|
||||
backup.mkdir(mode=0o700, exist_ok=False)
|
||||
shutil.copy2(env, backup/'selected.env.private')
|
||||
(backup/'selected.env.private').chmod(0o600)
|
||||
for name in changed+['compras-release.json']:
|
||||
target = backup/name
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(root/name, target)
|
||||
with (backup/'database.dump').open('xb') as stream:
|
||||
subprocess.run(['runuser', '-u', 'postgres', '--', 'pg_dump', '-Fc', '-d', 'compras_demo_20261129'], stdout=stream, check=True)
|
||||
subprocess.run(['pg_restore', '--list', str(backup/'database.dump')], stdout=subprocess.DEVNULL, check=True)
|
||||
def save(path, contents):
|
||||
attrs = path.stat()
|
||||
temp = path.with_name(path.name+'.alignment-next')
|
||||
temp.write_bytes(contents)
|
||||
os.chown(temp, attrs.st_uid, attrs.st_gid)
|
||||
temp.chmod(attrs.st_mode & 0o777)
|
||||
os.replace(temp, path)
|
||||
options = ['procurement.internal', 'procurement.sales', 'people.internal', 'people.third_party']
|
||||
value = json.dumps(json.dumps({'2': options}, separators=(',', ':')))
|
||||
try:
|
||||
for name in changed+['compras-release.json']:
|
||||
save(root/name, z.read(name))
|
||||
save(env, original.rstrip()+b'\nSGC_PRODUCT_ENTITLEMENTS='+value.encode()+b'\n')
|
||||
subprocess.run(['runuser', '-u', 'www-data', '--', '/usr/bin/php', 'artisan', 'config:cache'], cwd=root, check=True)
|
||||
subprocess.run(['/usr/bin/php', str(root/'scripts/verify-compras-release.php'), str(root), '--installed'], check=True)
|
||||
subprocess.run(['/usr/bin/php', str(root/'scripts/align-public-pilot-contexts.php'), '--align-authorized-synthetic'], cwd=root, check=True)
|
||||
except BaseException:
|
||||
# The native configuration commands are one transaction and roll back on failure.
|
||||
save(env, original)
|
||||
for name in changed+['compras-release.json']:
|
||||
save(root/name, (backup/name).read_bytes())
|
||||
subprocess.run(['runuser', '-u', 'www-data', '--', '/usr/bin/php', 'artisan', 'config:cache'], cwd=root, check=True)
|
||||
raise
|
||||
print(json.dumps({'state': 'installed', 'release_id': next_manifest['release_id'], 'backup': str(backup),
|
||||
'existing_public_assets_and_modules_preserved': True, 'public_company_contexts': options,
|
||||
'schema_migration_executed': False, 'profile_business_permissions_changed': False}))
|
||||
@@ -0,0 +1,22 @@
|
||||
// Prepare a source overlay only; keep the host's existing feature and permission guards.
|
||||
export function purchasingHomeOverlay(source) {
|
||||
const once = (old, value) => {
|
||||
if (source.split(old).length !== 2) throw Error('Purchasing home baseline changed: ' + old);
|
||||
source = source.replace(old, value);
|
||||
};
|
||||
const declarations = source.match(/\bconst\s+requisitions\s*=/g) ?? [];
|
||||
if (declarations.length > 1) throw Error('Ambiguous requisition capability declaration.');
|
||||
if (declarations.length === 0) {
|
||||
once("const payables=unit!==null&&can('supplier_payables.view',unit);", "const payables=unit!==null&&can('supplier_payables.view',unit);\n const requisitions=unit!==null&&can('purchasing_requisitions.view',unit);");
|
||||
} else if (!/const\s+requisitions\s*=\s*unit\s*!==\s*null\s*&&\s*(?:context\.purchasing\?\.internal_requisitions\s*===\s*true\s*&&\s*)?can\(['"]purchasing_requisitions\.view['"],\s*unit\);/.test(source)) {
|
||||
throw Error('Unknown requisition capability guard; reconcile before preparing.');
|
||||
}
|
||||
if (!source.includes('href="/purchasing/internal-requisitions"')) {
|
||||
once('<div className="actions">', '<div className="actions">{requisitions&&<a href="/purchasing/internal-requisitions">Requisições internas</a>}');
|
||||
}
|
||||
if (!source.includes('href="/purchasing/internal-requisitions/budget-setup"')) {
|
||||
once('<div className="actions">', '<div className="actions">{budget&&<a href="/purchasing/internal-requisitions/budget-setup">Preparação de centros e dotações</a>}');
|
||||
}
|
||||
if (!/!requisitions\s*&&/.test(source)) once('!budget&&!payables&&', '!budget&&!payables&&!requisitions&&');
|
||||
return source;
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Run over authenticated SSH: prepare an isolated synthetic installation, never switch live."""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
import zipfile
|
||||
|
||||
|
||||
def run(args, **kwargs):
|
||||
result = subprocess.run(args, text=True, capture_output=True, **kwargs)
|
||||
if result.returncode:
|
||||
raise RuntimeError(f"Command failed: {args[0]} {args[1:3]}\n{result.stderr[-1800:]}\n{result.stdout[-1800:]}")
|
||||
return result.stdout
|
||||
|
||||
|
||||
def main():
|
||||
assert os.geteuid() == 0 and sys.argv[1] == '--prepare-authorized-demo'
|
||||
archive = Path('/root/compras-presentation-20261129.zip')
|
||||
assert hashlib.sha256(archive.read_bytes()).hexdigest() == sys.argv[2]
|
||||
base = Path('/var/www/compras-deploy')
|
||||
previous = (base / 'current').resolve(strict=True)
|
||||
assert previous.is_relative_to(base / 'releases')
|
||||
assert Path('/var/www/html/compras.tempo.co.mz').resolve() == previous
|
||||
demo = base / 'demonstration-20261129'
|
||||
release = base / 'releases/presentation-20261129'
|
||||
assert not demo.exists() and not release.exists(), 'Refusing to overwrite a prepared demonstration'
|
||||
demo.mkdir(mode=0o750)
|
||||
release.mkdir(mode=0o755)
|
||||
access = Path('/root/compras-demo-access.json')
|
||||
assert not access.exists(), 'Preserve existing private presentation credentials'
|
||||
labels = {'admin': 'Administração', 'admin_review': 'Administração suplente', 'requester': 'Requisitante', 'head': 'Chefia',
|
||||
'procurement': 'Compras', 'finance': 'Finanças preparação', 'finance_review': 'Finanças revisão', 'warehouse': 'Armazém', 'direction': 'Direcção', 'auditor': 'Auditoria'}
|
||||
access.write_text(json.dumps({key: {'name': label+' - Demonstração', 'email': key+'@demo.compras.tempo.co.mz', 'password': secrets.token_urlsafe(20)} for key, label in labels.items()}, ensure_ascii=False, indent=2))
|
||||
os.chmod(access, 0o600)
|
||||
(demo / 'previous-release.txt').write_text(str(previous))
|
||||
run(['rsync', '-a', '--exclude=/.env', '--exclude=/storage', '--exclude=/.git', '--exclude=/bootstrap/cache/*.php', str(previous)+'/', str(release)+'/'])
|
||||
with zipfile.ZipFile(archive) as package:
|
||||
for info in package.infolist():
|
||||
assert not info.filename.startswith('/') and '..' not in Path(info.filename).parts
|
||||
package.extractall(release)
|
||||
storage = demo / 'storage'
|
||||
for folder in ['app/private', 'app/public', 'framework/cache/data', 'framework/sessions', 'framework/views', 'framework/testing/private', 'logs']:
|
||||
(storage / folder).mkdir(parents=True, exist_ok=True, mode=0o750)
|
||||
(release / 'storage').symlink_to(storage, target_is_directory=True)
|
||||
database = 'compras_demo_20261129'
|
||||
role = 'compras_demo_app_20261129'
|
||||
password = secrets.token_hex(32)
|
||||
existing = run(['runuser', '-u', 'postgres', '--', 'psql', '-Atc', f"SELECT datname FROM pg_database WHERE datname='{database}'"])
|
||||
assert not existing.strip(), 'Demonstration database already exists'
|
||||
run(['runuser', '-u', 'postgres', '--', 'psql', '-v', 'ON_ERROR_STOP=1'], input=f"CREATE ROLE {role} LOGIN PASSWORD '{password}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;\nCREATE DATABASE {database} OWNER {role};\nREVOKE ALL ON DATABASE {database} FROM PUBLIC;\n")
|
||||
settings = {
|
||||
'APP_NAME': 'Compras — Demonstração', 'APP_ENV': 'production', 'APP_DEBUG': 'false',
|
||||
'APP_KEY': 'base64:'+base64.b64encode(secrets.token_bytes(32)).decode(),
|
||||
'APP_URL': 'https://compras.tempo.co.mz', 'APP_TIMEZONE': 'Africa/Maputo', 'COMPRAS_DEMONSTRATION': 'true',
|
||||
'DB_CONNECTION': 'pgsql', 'DB_HOST': '127.0.0.1', 'DB_PORT': '5432', 'DB_DATABASE': database, 'DB_USERNAME': role, 'DB_PASSWORD': password,
|
||||
'SESSION_DRIVER': 'database', 'SESSION_SECURE_COOKIE': 'true', 'SESSION_COOKIE': 'compras_presentation_session',
|
||||
'CACHE_STORE': 'database', 'QUEUE_CONNECTION': 'database', 'MAIL_MAILER': 'log', 'LOG_LEVEL': 'warning',
|
||||
'SGC_PUBLIC_NAVIGATION': 'true', 'COMPRAS_RUNTIME_ENABLED': 'false', 'COMPRAS_RUNTIME_PREPARE_ONLY': 'true',
|
||||
'COMPRAS_RUNTIME_ROOT': str(release / 'presentation-runtime/finance'),
|
||||
'COMPRAS_RUNTIME_SHA256': '80483320a54af6f123498e43c1435a20922455f65860be88bd259e90efcbc0b7',
|
||||
'COMPRAS_RUNTIME_INSTALLATION_ID': str(uuid.uuid4()), 'COMPRAS_RUNTIME_SYNTHETIC_ONLY': 'true',
|
||||
'PAYABLE_SOURCE_INSTANCE': 'compras-presentation-'+str(uuid.uuid4()),
|
||||
'COMPRAS_PRIVATE_STORAGE_PATH': str(storage / 'framework/testing/private'),
|
||||
'COMPRAS_INVENTORY_CONVERSION_ENABLED': 'false', 'COMPRAS_INVENTORY_ROOT': str(release / 'presentation-runtime/inventory'),
|
||||
'COMPRAS_ORDER_CANCELLATION_ENABLED': 'false', 'COMPRAS_ORDER_CANCELLATION_ROOT': str(release / 'presentation-runtime/cancellation'),
|
||||
}
|
||||
for key, package in [('COMMON_BUDGET_PATH', 'budget-control'), ('COMMON_PAYABLES_PATH', 'payables'), ('COMMON_PURCHASING_PATH', 'purchasing')]:
|
||||
settings[key] = str(release / 'presentation-runtime/finance' / package)
|
||||
features = json.loads((release / 'presentation-runtime/features.json').read_text())
|
||||
settings.update({key: 'false' for key in features})
|
||||
env_file = demo / '.env'
|
||||
|
||||
def write_env():
|
||||
env_file.write_text(''.join(key+'='+json.dumps(value, ensure_ascii=False)+'\n' for key, value in settings.items()))
|
||||
os.chmod(env_file, 0o640)
|
||||
shutil.chown(env_file, group='www-data')
|
||||
|
||||
write_env()
|
||||
(release / '.env').symlink_to(env_file)
|
||||
run(['php', 'artisan', 'migrate', '--force', '--no-interaction'], cwd=release)
|
||||
preparation = run(['php', 'artisan', 'compras:runtime:prepare', '--expected-database='+database, '--expected-role='+role,
|
||||
'--operator=Tempo presentation deployment', '--reason=Owner authorised isolated synthetic public demonstration', '--apply'], cwd=release)
|
||||
settings.update({key: 'true' for key in features})
|
||||
settings.update({'COMPRAS_RUNTIME_ENABLED': 'true', 'COMPRAS_RUNTIME_PREPARE_ONLY': 'false',
|
||||
'COMPRAS_INVENTORY_CONVERSION_ENABLED': 'true', 'COMPRAS_ORDER_CANCELLATION_ENABLED': 'true'})
|
||||
write_env()
|
||||
run(['chown', '-R', 'www-data:www-data', str(storage), str(release / 'bootstrap/cache')])
|
||||
run(['chmod', '-R', 'g+rX', str(demo)])
|
||||
run(['chown', 'root:www-data', str(demo)])
|
||||
run(['php', 'artisan', 'config:cache'], cwd=release)
|
||||
run(['chown', '-R', 'www-data:www-data', str(release / 'bootstrap/cache')])
|
||||
(demo / 'prepared.json').write_text(json.dumps({'state': 'prepared_not_live', 'previous_release': str(previous), 'release': str(release),
|
||||
'database': database, 'role': role, 'installation_id': settings['COMPRAS_RUNTIME_INSTALLATION_ID'], 'runtime_preparation': json.loads(preparation.strip().splitlines()[-1]),
|
||||
'synthetic_only': True, 'live_link_changed': False}, indent=2))
|
||||
print((demo / 'prepared.json').read_text())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Create the authorised synthetic presentation through normal login and native HTTP routes."""
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import uuid
|
||||
from datetime import date, timedelta
|
||||
|
||||
spec = importlib.util.spec_from_file_location('demo', '/root/check-public-demonstration.py')
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
assert sys.argv[1] == '--prepare-authorized-synthetic-journey'
|
||||
request_id = int(sys.argv[2]) if len(sys.argv) > 2 else 1
|
||||
assert request_id in [1, 2]
|
||||
request_path = '/requisicoes/'+str(request_id)
|
||||
credentials = json.loads(Path('/root/compras-demo-access.json').read_text())
|
||||
clients = {key: module.Client(credentials[key]) for key in ['requester', 'head', 'procurement', 'finance', 'finance_review', 'warehouse']}
|
||||
state_file = Path('/var/www/compras-deploy/demonstration-20261129/purchase-journey'+('' if request_id == 1 else '-2')+'.json')
|
||||
state = json.loads(state_file.read_text()) if state_file.exists() else {}
|
||||
|
||||
|
||||
def save():
|
||||
state_file.write_text(json.dumps(state, indent=2))
|
||||
|
||||
|
||||
def post(who, path, data):
|
||||
result = clients[who].request(path, 'POST', data)
|
||||
assert result['status'] in [200, 302, 303], f"{who} {path}: {result['status']} {result['text'][:1000]}"
|
||||
return result
|
||||
|
||||
|
||||
def props(who, path):
|
||||
result = clients[who].request(path)
|
||||
assert result['status'] == 200, f"{who} {path}: {result['status']}"
|
||||
return result['page']['props']
|
||||
|
||||
|
||||
today = date.today()
|
||||
request = props('requester', request_path)['requisition']
|
||||
assert request['justification'].startswith('Aquisi') and 'fict' in request['justification']
|
||||
if request['status'] == 'draft':
|
||||
post('requester', request_path+'/submeter', {'operation_key': str(uuid.uuid4()), 'process_version': request['process_version']})
|
||||
request = props('head', request_path)['requisition']
|
||||
if request['status'] == 'pending':
|
||||
post('head', request_path+'/decidir', {'operation_key': str(uuid.uuid4()), 'process_version': request['process_version'],
|
||||
'decision': 'approved', 'comment': 'Necessidade fictícia conferida pela chefia independente.'})
|
||||
assert props('head', request_path)['requisition']['status'] == 'approved'
|
||||
state['request_approved'] = True; save()
|
||||
line_id = request['items'][0]['id']
|
||||
suppliers = []
|
||||
for index, price in enumerate([100, 110, 120]):
|
||||
nuit = str(900000001 + index)
|
||||
rows = props('procurement', '/fornecedores')['suppliers']['data']
|
||||
supplier = next((row for row in rows if row['nuit'] == nuit), None)
|
||||
if supplier is None:
|
||||
post('procurement', '/fornecedores', {'name': 'Fornecedor Fictício DEMO '+str(index+1), 'nuit': nuit, 'contact': 'Contacto fictício',
|
||||
'email': 'supplier-'+str(index+1)+'@example.invalid', 'phone': '000000000', 'address': 'Morada fictícia para demonstração',
|
||||
'category': 'Material de escritório', 'beneficiaries': 'Beneficiário fictício', 'document_references': 'DEMO sem documentos reais',
|
||||
'diligence_notes': 'Cadastro inteiramente fictício para apresentação.', 'blocked': False, 'next_review': (today+timedelta(days=365)).isoformat()})
|
||||
supplier = next(row for row in props('procurement', '/fornecedores')['suppliers']['data'] if row['nuit'] == nuit)
|
||||
if supplier['status'] == 'pending':
|
||||
post('finance', '/fornecedores/'+str(supplier['id'])+'/validar', {'version': supplier['version'], 'status': 'active', 'comment': 'Conferência independente do fornecedor fictício.'})
|
||||
suppliers.append(supplier['id'])
|
||||
quote_page = props('procurement', request_path+'/cotacoes')
|
||||
quotes = quote_page['quotations']
|
||||
quote = next((row for row in quotes if row['supplier_id'] == supplier['id']), None)
|
||||
if quote is None:
|
||||
post('procurement', request_path+'/cotacoes', {'currency': 'MZN', 'supplier_id': supplier['id'], 'reference': 'DEMO-PROP-'+str(index+1),
|
||||
'delivery_days': 5, 'valid_until': (today+timedelta(days=30)).isoformat(), 'payment_terms': 'Trinta dias — condições fictícias', 'no_conflict': True,
|
||||
'items': [{'requisition_item_id': line_id, 'unit_price': str(price)+'.00', 'discount_type': 'none', 'discount_value': '0.00'}]})
|
||||
quote = next(row for row in props('procurement', request_path+'/cotacoes')['quotations'] if row['supplier_id'] == supplier['id'])
|
||||
for reviewer in ['head', 'finance_review']:
|
||||
evaluations = quote.get('evaluations', [])
|
||||
reviewer_id = props(reviewer, '/dashboard')['auth']['user']['id']
|
||||
if not any(row['evaluator_id'] == reviewer_id for row in evaluations):
|
||||
post(reviewer, '/cotacoes/'+str(quote['id'])+'/avaliar', {'quality': '8', 'history': '8', 'payment': '8',
|
||||
'comment': 'Avaliação fictícia e independente para apresentação.', 'no_conflict': True})
|
||||
state['suppliers'] = suppliers; save()
|
||||
award_page = props('procurement', request_path+'/adjudicacao')
|
||||
if award_page['award'] is None:
|
||||
winner = award_page['comparison']['top_ids'][0]
|
||||
post('procurement', request_path+'/adjudicacao', {'quotation_id': winner, 'justification': 'Proposta fictícia com a melhor pontuação segundo as regras preservadas.',
|
||||
'delivery_date': (today+timedelta(days=7)).isoformat(), 'delivery_location': 'Armazém de demonstração'})
|
||||
award_page = props('head', request_path+'/adjudicacao')
|
||||
award = award_page['award']
|
||||
if award_page['canDecide']:
|
||||
post('head', '/adjudicacoes/'+str(award['id'])+'/decidir', {'decision': 'approved', 'comment': 'Conferência independente da adjudicação fictícia.'})
|
||||
award_page = props('procurement', request_path+'/adjudicacao')
|
||||
if award_page['canIssue']:
|
||||
post('procurement', '/adjudicacoes/'+str(award['id'])+'/emitir', {})
|
||||
state['award_id'] = award['id']; state['state'] = 'native_synthetic_order_issued'; save()
|
||||
print(json.dumps(state))
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
if (config('app.demonstration') !== true || DB::connection()->getDatabaseName() !== 'compras_demo_20261129') {
|
||||
throw new LogicException('Only the authorised sample installation may prepare this transition.');
|
||||
}
|
||||
DB::statement('SET default_transaction_read_only=on');
|
||||
$pins = [];
|
||||
foreach (DB::table('private_audit_exports')->where('tenant_id', 2)->where('work_context', 'legacy')->orderBy('id')->get() as $export) {
|
||||
$path = Storage::disk('local')->path($export->path);
|
||||
$boundary = realpath(storage_path('app/private')).'/audit-exports/2/'.$export->created_by.'/';
|
||||
if (! is_file($path) || is_link($path) || ! str_starts_with(realpath($path), $boundary)
|
||||
|| ! hash_equals($export->sha256, hash_file('sha256', $path))) {
|
||||
throw new LogicException('Preserve and investigate the original archive before configuring a receipt.');
|
||||
}
|
||||
$pins[(string) $export->id] = $export->sha256;
|
||||
}
|
||||
if (count($pins) !== 3) {
|
||||
throw new LogicException('Unexpected archive set; do not infer a wider transition.');
|
||||
}
|
||||
echo json_encode(['2' => $pins], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Reproduce and prove the corrected migration isolation without writing the active database."""
|
||||
from pathlib import Path
|
||||
import json
|
||||
import subprocess
|
||||
import uuid
|
||||
|
||||
root = Path('/var/www/compras-deploy/current').resolve()
|
||||
assert root == Path('/var/www/compras-deploy/releases/presentation-20261129')
|
||||
dump = Path('/var/backups/compras-presentation-20261129/client-hiring/database.dump')
|
||||
restore = 'compras_client_restore_'+uuid.uuid4().hex[:12]
|
||||
|
||||
def php(*args):
|
||||
result = subprocess.run(['runuser', '-u', 'www-data', '--', 'php', 'scripts/upgrade-client-registry.php', *args], cwd=root, capture_output=True)
|
||||
if result.returncode:
|
||||
diagnostic = Path('/var/backups/compras-presentation-20261129/client-registry-isolation-failure.private.log')
|
||||
diagnostic.write_bytes(result.stdout+result.stderr)
|
||||
diagnostic.chmod(0o600)
|
||||
raise RuntimeError('Native verification failed; see private diagnostic.')
|
||||
return json.loads(result.stdout)
|
||||
|
||||
before = php('--inspect-client-registry')
|
||||
created = False
|
||||
try:
|
||||
subprocess.run(['runuser', '-u', 'postgres', '--', 'createdb', '--owner=compras_demo_app_20261129', restore], check=True)
|
||||
created = True
|
||||
with dump.open('rb') as stream:
|
||||
subprocess.run(['runuser', '-u', 'postgres', '--', 'pg_restore', '--exit-on-error', '-d', restore], stdin=stream, check=True)
|
||||
initial = php('--inspect-client-registry', restore)
|
||||
assert initial['database'] == restore and not initial['exists'] and not initial['migration_recorded']
|
||||
result = php(restore)
|
||||
recovered = php('--inspect-client-registry', restore)
|
||||
assert recovered['database'] == restore and recovered['exists'] and recovered['migration_recorded'] and recovered['client_count'] == 0
|
||||
after = php('--inspect-client-registry')
|
||||
assert after == before, 'Active registry must remain identical during recovery migration'
|
||||
assert recovered['schema_sha256'] == before['schema_sha256'], 'Active empty structure must match the native migration exactly'
|
||||
finally:
|
||||
if created:
|
||||
subprocess.run(['runuser', '-u', 'postgres', '--', 'dropdb', restore], check=True)
|
||||
proof = {'state': 'passed', 'migration_connection_name': 'registry_upgrade',
|
||||
'restore_initially_without_registry': initial, 'recovered_registry': recovered,
|
||||
'active_registry_unchanged': before == after, 'active_empty_schema_matches_native_migration': True,
|
||||
'recovery_database_removed': True, 'recovery_upgrade': result}
|
||||
Path('/var/backups/compras-presentation-20261129/client-registry-isolation.json').write_text(json.dumps(proof, indent=2)+'\n')
|
||||
print(json.dumps(proof))
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\OrganizationConfiguration;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
if (($argv[1] ?? '') !== '--repair-owned-synthetic-labels' || config('app.demonstration') !== true
|
||||
|| DB::connection()->getDatabaseName() !== 'compras_demo_20261129') {
|
||||
throw new LogicException('Only generated sample labels may be repaired.');
|
||||
}
|
||||
$backup = '/var/backups/compras-presentation-20261129/context-alignment/profile-labels.before.private.json';
|
||||
if (is_file($backup)) {
|
||||
throw new LogicException('Preserve the prior label repair.');
|
||||
}
|
||||
$result = DB::transaction(function () use ($backup): array {
|
||||
$actor = User::query()->where('email', 'admin@demo.compras.tempo.co.mz')->sole();
|
||||
auth()->guard()->setUser($actor);
|
||||
$profiles = DB::table('organization_profiles')->where('tenant_id', 2)->orderBy('id')->get();
|
||||
file_put_contents($backup, json_encode($profiles, JSON_THROW_ON_ERROR));
|
||||
chmod($backup, 0600);
|
||||
$repaired = 0;
|
||||
foreach ($profiles as $profile) {
|
||||
if (! str_contains($profile->name, '?')) {
|
||||
continue;
|
||||
}
|
||||
$userId = DB::table('organization_memberships')->where('tenant_id', 2)->where('profile_id', $profile->id)->orderBy('user_id')->value('user_id');
|
||||
$name = User::query()->where('tenant_id', 2)->whereKey($userId)->value('name');
|
||||
if (! is_string($name) || str_contains($name, '?')) {
|
||||
throw new LogicException('Do not invent a replacement label.');
|
||||
}
|
||||
app(OrganizationConfiguration::class)->execute($actor, 'profile', [
|
||||
'version' => DB::table('organization_access')->where('tenant_id', 2)->value('version'), 'id' => $profile->id,
|
||||
'name' => $name, 'permissions' => json_decode($profile->permissions, true, 32, JSON_THROW_ON_ERROR),
|
||||
'work_contexts' => json_decode($profile->work_contexts, true, 32, JSON_THROW_ON_ERROR),
|
||||
'reason' => 'Corrigir apenas a codificacao dos rotulos sinteticos gerados, reutilizando o nome existente do titular.']);
|
||||
$repaired++;
|
||||
}
|
||||
return ['state' => 'passed', 'generated_profile_labels_repaired' => $repaired, 'permissions_contexts_users_and_credentials_changed' => false];
|
||||
});
|
||||
$path = '/root/compras-demo-access.json';
|
||||
$credentials = json_decode(file_get_contents($path), true, 32, JSON_THROW_ON_ERROR);
|
||||
foreach ($credentials as &$credential) {
|
||||
$name = User::query()->where('tenant_id', 2)->where('email', $credential['email'])->value('name');
|
||||
if (is_string($name)) {
|
||||
$credential['name'] = $name;
|
||||
}
|
||||
}
|
||||
unset($credential);
|
||||
file_put_contents($path, json_encode($credentials, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR).PHP_EOL);
|
||||
chmod($path, 0600);
|
||||
file_put_contents(dirname($backup).'/profile-labels-result.json', json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
|
||||
echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -219,6 +219,15 @@ try {
|
||||
if (!frozenRuntime || !process.argv.includes('--integrated-schema') || setupOnly) throw Error('Runtime guard requires only the frozen isolated composition');
|
||||
args.splice(0, args.length, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionLedgerAccountsTest.php', '--filter=pinned private runtime refuses');
|
||||
}
|
||||
if (process.argv.includes('--work-context-only')) {
|
||||
args.splice(0, args.length, 'vendor/bin/pest', '--compact', 'tests/Feature/WorkContextTest.php', 'tests/Feature/OrganizationConfigurationTest.php', 'tests/Feature/OrganizationActivationPreviewTest.php', 'tests/Feature/PrivateAuditExporterTest.php', 'tests/Feature/PrivateAuditAccessTest.php');
|
||||
}
|
||||
if (process.argv.includes('--third-party-hiring-only')) {
|
||||
args.splice(0, args.length, 'vendor/bin/pest', '--compact', 'tests/Feature/BusinessClientsTest.php', 'tests/Feature/PeopleHiringTest.php', 'tests/Feature/WorkContextTest.php');
|
||||
}
|
||||
if (process.argv.includes('--configured-sales-ledger-only')) {
|
||||
args.splice(0, args.length, 'vendor/bin/pest', '--compact', 'tests/Feature/ConfiguredSalesLedgerTest.php', 'tests/Feature/CustomerReceivablesTest.php', 'tests/Feature/CustomerSalesNativeTest.php');
|
||||
}
|
||||
if (process.argv.includes('--order-document-only')) {
|
||||
if (!frozenRuntime || !process.argv.includes('--integrated-schema') || setupOnly) throw Error('Order document regression requires only the frozen isolated composition');
|
||||
args.splice(0, args.length, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php', 'tests/Feature/OrderDocumentNavigationTest.php',
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
// Deliberately separate from installation and normal database seeders.
|
||||
use App\Models\CostCenter;
|
||||
use App\Models\Department;
|
||||
use App\Models\StockItem;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Models\Warehouse;
|
||||
use App\Services\CommonBudget;
|
||||
use App\Services\CommonFinanceAdministration;
|
||||
use App\Services\OrganizationAccess;
|
||||
use App\Services\RequisitionAccountAssignments;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
if (($argv[1] ?? '') !== '--initialize-authorized-synthetic' || config('app.demonstration') !== true
|
||||
|| DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== 'compras_demo_20261129'
|
||||
|| DB::selectOne('select current_user as role')->role !== 'compras_demo_app_20261129') {
|
||||
throw new LogicException('Explicit isolated public demonstration required.');
|
||||
}
|
||||
$bytes = file_get_contents($argv[2]);
|
||||
if (! is_string($bytes)) {
|
||||
throw new LogicException('Private demonstration credentials unavailable.');
|
||||
}
|
||||
$credentials = json_decode($bytes, true, 32, JSON_THROW_ON_ERROR);
|
||||
try {
|
||||
$result = DB::transaction(function () use ($credentials) {
|
||||
if (Tenant::query()->exists() || User::query()->exists()) {
|
||||
throw new LogicException('Refuse to overwrite existing demonstration data.');
|
||||
}
|
||||
$tenant = Tenant::query()->create(['name' => 'Empresa de Demonstração — Dados Fictícios', 'first_limit_minor' => 2500000,
|
||||
'second_limit_minor' => 15000000, 'rules_provisional' => true, 'approval_includes_tax' => true]);
|
||||
$department = Department::query()->create(['tenant_id' => $tenant->id, 'name' => 'Operações — Demonstração']);
|
||||
$center = CostCenter::query()->create(['tenant_id' => $tenant->id, 'department_id' => $department->id, 'code' => 'DEMO-OPS', 'name' => 'Operações fictícias']);
|
||||
$people = [];
|
||||
$permissions = [
|
||||
'admin' => ['admin', 'requester', 'people_service_prepare', 'people_staff_prepare', 'people_registry_read', 'people_registry_manage'],
|
||||
'admin_review' => ['admin'],
|
||||
'requester' => ['requester'], 'head' => ['department_head', 'people_service_review', 'people_staff_review'],
|
||||
'procurement' => ['procurement', 'requester', 'supply_read', 'supply_prepare', 'supply_suggest_prepare', 'supply_delivery', 'import_read', 'import_prepare', 'import_customs', 'production_order_prepare', 'maintenance_order_prepare'],
|
||||
'finance' => ['finance'], 'finance_review' => ['finance'], 'warehouse' => ['warehouse', 'supply_read'],
|
||||
'direction' => ['people_service_review', 'people_staff_review', 'people_contract_formalize', 'conflict_release_authorise', 'requisition_approve'],
|
||||
'auditor' => ['audit_private_purchasing_read', 'audit_private_stock_read', 'audit_private_finance_read', 'audit_private_configuration_read'],
|
||||
];
|
||||
DB::table('organization_access')->insert(['tenant_id' => $tenant->id, 'active' => true, 'version' => 1, 'created_at' => now(), 'updated_at' => now()]);
|
||||
foreach ($permissions as $key => $grants) {
|
||||
foreach ($grants as $grant) {
|
||||
if (! array_key_exists($grant, OrganizationAccess::PERMISSIONS)) {
|
||||
throw new LogicException('Unknown demonstration authority: '.$grant);
|
||||
}
|
||||
}
|
||||
$credential = $credentials[$key];
|
||||
$user = new User;
|
||||
$user->forceFill(['tenant_id' => $tenant->id, 'department_id' => $department->id,
|
||||
'purchasing_role' => match ($key) {
|
||||
'admin_review' => 'admin',
|
||||
'head' => 'department_head', 'finance_review' => 'finance', 'direction', 'auditor' => 'configured', default => $key
|
||||
},
|
||||
'name' => $credential['name'], 'email' => $credential['email'], 'password' => $credential['password'], 'email_verified_at' => now()])->save();
|
||||
$profile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $tenant->id, 'name' => $credential['name'],
|
||||
'permissions' => json_encode($grants, JSON_THROW_ON_ERROR), 'work_contexts' => json_encode(['procurement.internal', 'people.internal'], JSON_THROW_ON_ERROR),
|
||||
'version' => 1, 'created_at' => now(), 'updated_at' => now()]);
|
||||
DB::table('organization_memberships')->insert(['tenant_id' => $tenant->id, 'user_id' => $user->id, 'profile_id' => $profile,
|
||||
'maintenance' => false, 'created_at' => now(), 'updated_at' => now()]);
|
||||
$people[$key] = $user;
|
||||
}
|
||||
auth()->guard()->setUser($people['admin']);
|
||||
$admin = app(CommonFinanceAdministration::class);
|
||||
foreach (['DEMO-CUSTO' => 'Despesa fictícia para demonstração', 'DEMO-FORNECEDORES' => 'Fornecedores fictícios', 'DEMO-CAIXA' => 'Tesouraria fictícia'] as $code => $label) {
|
||||
$space = $admin->workspace($people['admin']);
|
||||
$admin->save($people['admin'], 'account', ['operation_key' => (string) Str::uuid(), 'basis_hash' => $space['accounts']['hash'],
|
||||
'code' => $code, 'label' => $label, 'currency' => 'MZN', 'is_movement' => true, 'reason' => 'Plano ilustrativo da empresa sintética, não é plano da Tempo.']);
|
||||
}
|
||||
$space = $admin->workspace($people['admin']);
|
||||
$admin->save($people['admin'], 'period', ['operation_key' => (string) Str::uuid(), 'basis_hash' => $space['periods']['hash'],
|
||||
'period_key' => 'DEMO-'.now()->year, 'starts_on' => today()->startOfYear()->toDateString(), 'ends_on' => today()->endOfYear()->toDateString(),
|
||||
'reason' => 'Período ilustrativo exclusivo da demonstração sintética.']);
|
||||
foreach (['finance', 'finance_review'] as $key) {
|
||||
$space = $admin->workspace($people['admin'], $people[$key]->id);
|
||||
$actions = array_keys(CommonFinanceAdministration::LABELS);
|
||||
$admin->save($people['admin'], 'access', ['operation_key' => (string) Str::uuid(), 'basis_hash' => $space['selectedAccess']['hash'],
|
||||
'user_id' => $people[$key]->id, 'person' => 'demo-person-'.$key, 'actions' => $actions,
|
||||
'reason' => 'Competências fictícias para demonstrar preparação e confirmação independentes.']);
|
||||
}
|
||||
auth()->guard()->setUser($people['finance']);
|
||||
$budget = app(CommonBudget::class)->for($people['finance'])->create(['cost_center_id' => $center->id, 'year' => (int) now()->year,
|
||||
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 10000000, 'reason' => 'Dotação fictícia de 100000 MZN para apresentação.']);
|
||||
auth()->guard()->setUser($people['finance_review']);
|
||||
app(CommonBudget::class)->for($people['finance_review'])->approve($budget);
|
||||
auth()->guard()->setUser($people['warehouse']);
|
||||
$warehouse = Warehouse::query()->create(['tenant_id' => $tenant->id, 'created_by' => $people['warehouse']->id, 'code' => 'DEMO-ARM', 'name' => 'Armazém de demonstração']);
|
||||
$stock = StockItem::query()->create(['tenant_id' => $tenant->id, 'created_by' => $people['warehouse']->id, 'code' => 'DEMO-PAPEL', 'name' => 'Papel de escritório — demonstração', 'unit' => 'un']);
|
||||
auth()->guard()->setUser($people['requester']);
|
||||
$request = app(RequisitionWorkflow::class)->save($people['requester'], ['operation_key' => (string) Str::uuid(),
|
||||
'cost_center_id' => $center->id, 'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(),
|
||||
'justification' => 'Aquisição fictícia de papel para demonstrar o circuito de compras. Taxa ilustrativa zero, sem regra fiscal real.',
|
||||
'items' => [['description' => $stock->name, 'category' => 'Material de escritório', 'purchase_type' => 'consumable', 'quantity' => '10.000',
|
||||
'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00', 'procurement_category' => 'office_equipment', 'category_reason' => 'Classificação ilustrativa para a apresentação.']]]);
|
||||
$space = app(RequisitionAccountAssignments::class)->workspace($people['requester'], $request);
|
||||
$account = null;
|
||||
foreach ($space['accounts']['data'] as $candidate) {
|
||||
if ($candidate['code'] === 'DEMO-CUSTO') {
|
||||
$account = $candidate;
|
||||
}
|
||||
}
|
||||
if ($account === null) {
|
||||
throw new LogicException('Demonstration account missing.');
|
||||
}
|
||||
app(RequisitionAccountAssignments::class)->save($people['requester'], $request, ['operation_key' => (string) Str::uuid(), 'version' => 0,
|
||||
'item_id' => $request->items()->sole()->id, 'basis_hash' => $space['items'][0]['basis_hash'], 'reason' => 'Imputação fictícia explícita antes da submissão.',
|
||||
'allocations' => [['account_id' => $account['id'], 'source_hash' => $account['source_hash'], 'subtotal' => '1000.00', 'total' => '1000.00']]]);
|
||||
|
||||
return ['tenant_id' => $tenant->id, 'department_id' => $department->id, 'cost_center_id' => $center->id, 'warehouse_id' => $warehouse->id,
|
||||
'stock_item_id' => $stock->id, 'requisition_id' => $request->id, 'actors' => array_map(fn ($user) => $user->id, $people), 'state' => 'synthetic_company_prepared'];
|
||||
});
|
||||
} catch (Throwable $error) {
|
||||
fwrite(STDERR, $error::class.': '.$error->getMessage().PHP_EOL);
|
||||
exit(1);
|
||||
}
|
||||
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use App\Services\ImportBankSupport;
|
||||
use App\Services\ImportDossier;
|
||||
use App\Services\ImportEvidence;
|
||||
use App\Services\SupplyPlanning;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
if (($argv[1] ?? '') !== '--initialize-authorized-synthetic' || config('app.demonstration') !== true || DB::connection()->getDatabaseName() !== 'compras_demo_20261129') {
|
||||
throw new LogicException('Explicit synthetic demonstration required.');
|
||||
}
|
||||
if (function_exists('posix_geteuid') && posix_geteuid() !== fileowner(storage_path('app/private'))) {
|
||||
throw new LogicException('Run document preparation as the application storage owner.');
|
||||
}
|
||||
try {
|
||||
$actor = User::query()->where('email', 'procurement@demo.compras.tempo.co.mz')->sole();
|
||||
auth()->guard()->setUser($actor);
|
||||
$order = PurchaseOrder::query()->where('requisition_id', 2)->sole();
|
||||
if (SupplyRecord::query()->where('kind', 'import')->where('purchase_order_id', $order->id)->exists()) {
|
||||
throw new LogicException('Do not duplicate the synthetic import documents.');
|
||||
}
|
||||
$protected = ['invoices', 'invoice_items', 'stock_movements', 'budget_entries', 'budget_consumptions', 'ps_payments', 'ps_allocations', 'gl_journals', 'gl_lines'];
|
||||
$frames = [];
|
||||
foreach ($protected as $table) {
|
||||
$frames[$table] = DB::table($table)->orderBy('id')->get()->toJson();
|
||||
}
|
||||
$import = app(SupplyPlanning::class)->save($actor, 'import', ['operation_key' => (string) Str::uuid(), 'version' => 0, 'action' => 'save',
|
||||
'reason' => 'Processo inteiramente fictício para apresentação do acompanhamento documental.',
|
||||
'data' => ['purchase_order_id' => $order->id, 'purpose' => 'internal', 'jurisdiction' => 'MZ — cenário fictício',
|
||||
'origin_country' => 'ZA — cenário fictício', 'dispatch_country' => 'ZA — cenário fictício',
|
||||
'regime' => 'Demonstração documental sem operação externa', 'expected_usable_on' => today()->addWeek()->toDateString()]]);
|
||||
$documents = [];
|
||||
foreach (['commercial_invoice' => 'DEMO-FACTURA-COMERCIAL', 'packing_list' => 'DEMO-EMBALAGEM', 'customs_declaration' => 'DEMO-DU-JUE',
|
||||
'bank_commitment' => 'DEMO-TERMO-BANCARIO', 'bank_support' => 'DEMO-ENTREGA-DOCUMENTAL'] as $type => $reference) {
|
||||
$stream = 'BT /F1 15 Tf 30 730 Td (DEMONSTRACAO - DOCUMENTO FICTICIO) Tj 0 -35 Td ('.$reference.') Tj 0 -35 Td (Sem validade oficial ou submissao externa.) Tj ET';
|
||||
$objects = ['<< /Type /Catalog /Pages 2 0 R >>', '<< /Type /Pages /Kids [3 0 R] /Count 1 >>',
|
||||
'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>',
|
||||
'<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>', '<< /Length '.strlen($stream)." >>\nstream\n".$stream."\nendstream"];
|
||||
$pdf = "%PDF-1.4\n";
|
||||
$offsets = [];
|
||||
foreach ($objects as $index => $object) {
|
||||
$offsets[] = strlen($pdf);
|
||||
$pdf .= ($index + 1)." 0 obj\n".$object."\nendobj\n";
|
||||
}
|
||||
$start = strlen($pdf);
|
||||
$pdf .= "xref\n0 6\n0000000000 65535 f \n";
|
||||
foreach ($offsets as $offset) {
|
||||
$pdf .= sprintf("%010d 00000 n \n", $offset);
|
||||
}
|
||||
$pdf .= "trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n".$start."\n%%EOF\n";
|
||||
$temporary = tempnam(storage_path('framework/testing'), 'demo-doc-');
|
||||
if ($temporary === false) {
|
||||
throw new LogicException('Synthetic private document staging unavailable.');
|
||||
}
|
||||
try {
|
||||
file_put_contents($temporary, $pdf);
|
||||
$document = app(ImportDossier::class)->record($actor, $import, ['operation_key' => (string) Str::uuid(), 'type' => $type,
|
||||
'reference' => $reference, 'issuer_reference' => 'Entidade fictícia de demonstração', 'issued_on' => today()->toDateString(),
|
||||
'notes' => 'Exemplar inteiramente fictício, sem validade oficial.', 'reason' => 'Documento sintético para apresentar o circuito, sem submissão ao banco ou JUE.'],
|
||||
new UploadedFile($temporary, $reference.'.pdf', 'application/pdf', null, true));
|
||||
if (app(ImportEvidence::class)->bytes($document) !== $pdf) {
|
||||
throw new LogicException('Synthetic original integrity failed.');
|
||||
}
|
||||
$documents[$type] = $document->id;
|
||||
} finally {
|
||||
unlink($temporary);
|
||||
}
|
||||
}
|
||||
$support = app(ImportBankSupport::class)->save($actor, $import, ['operation_key' => (string) Str::uuid(), 'version' => 0,
|
||||
'commitment_document_id' => $documents['bank_commitment'], 'declaration_document_id' => $documents['customs_declaration'],
|
||||
'submission_document_id' => $documents['bank_support'], 'submission_basis' => 'Comprovativo exclusivamente fictício para apresentação.',
|
||||
'submitted_on' => today()->toDateString(), 'support_document_ids' => [$documents['commercial_invoice'], $documents['packing_list']],
|
||||
'requirements_known' => true, 'required_support_types' => ['commercial_invoice', 'packing_list'],
|
||||
'required_support_counts' => ['commercial_invoice' => 1, 'packing_list' => 1],
|
||||
'requirements_basis' => 'Lista ilustrativa, não representa exigências de um banco real.', 'due_on' => today()->addWeek()->toDateString(),
|
||||
'deadline_basis' => 'Prazo fictício da apresentação; não é prazo legal ou bancário.', 'reason' => 'Acompanhamento sintético do DU/JUE e suporte bancário, sem operação externa.']);
|
||||
foreach ($frames as $table => $before) {
|
||||
if (DB::table($table)->orderBy('id')->get()->toJson() !== $before) {
|
||||
throw new LogicException('Documentary presentation changed protected effects: '.$table);
|
||||
}
|
||||
}
|
||||
echo json_encode(['state' => 'passed', 'import_id' => $import->id, 'order_id' => $order->id, 'documents' => $documents,
|
||||
'bank_support_id' => $support->id, 'bank_support_state' => $support->state, 'protected_financial_stock_tables_unchanged' => count($frames),
|
||||
'jue_submission_executed' => false, 'bank_transfer_executed' => false], JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
} catch (Throwable $error) {
|
||||
fwrite(STDERR, $error::class.': '.$error->getMessage().PHP_EOL);
|
||||
exit(1);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use App\Services\RequisitionAccountAssignments;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
if (($argv[1] ?? '') !== '--initialize-authorized-synthetic' || config('app.demonstration') !== true || DB::connection()->getDatabaseName() !== 'compras_demo_20261129') {
|
||||
throw new LogicException('Explicit synthetic demonstration required.');
|
||||
}
|
||||
try {
|
||||
$owner = User::query()->where('email', 'requester@demo.compras.tempo.co.mz')->sole();
|
||||
auth()->guard()->setUser($owner);
|
||||
if (Requisition::query()->count() !== 1) {
|
||||
throw new LogicException('Do not duplicate the presentation import request.');
|
||||
}
|
||||
$request = app(RequisitionWorkflow::class)->save($owner, ['operation_key' => (string) Str::uuid(),
|
||||
'cost_center_id' => DB::table('cost_centers')->where('tenant_id', $owner->tenant_id)->value('id'), 'priority' => 'normal',
|
||||
'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Aquisição fictícia para importação documental de demonstração. Sem regra fiscal real.',
|
||||
'items' => [['description' => 'Material fictício para importação', 'category' => 'Material de escritório', 'purchase_type' => 'consumable',
|
||||
'quantity' => '10.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00', 'procurement_category' => 'office_equipment',
|
||||
'category_reason' => 'Classificação exclusivamente ilustrativa para a apresentação.']]]);
|
||||
$space = app(RequisitionAccountAssignments::class)->workspace($owner, $request);
|
||||
$account = null;
|
||||
foreach ($space['accounts']['data'] as $candidate) {
|
||||
if ($candidate['code'] === 'DEMO-CUSTO') {
|
||||
$account = $candidate;
|
||||
}
|
||||
}
|
||||
if ($account === null) {
|
||||
throw new LogicException('Demonstration account missing.');
|
||||
}
|
||||
app(RequisitionAccountAssignments::class)->save($owner, $request, ['operation_key' => (string) Str::uuid(), 'version' => 0,
|
||||
'item_id' => $request->items()->sole()->id, 'basis_hash' => $space['items'][0]['basis_hash'], 'reason' => 'Atribuição explícita à conta ilustrativa de importação.',
|
||||
'allocations' => [['account_id' => $account['id'], 'source_hash' => $account['source_hash'], 'subtotal' => '1000.00', 'total' => '1000.00']]]);
|
||||
echo json_encode(['state' => 'passed', 'requisition_id' => $request->id], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
} catch (Throwable $error) {
|
||||
fwrite(STDERR, $error::class.': '.$error->getMessage().PHP_EOL);
|
||||
exit(1);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
use App\Models\PeopleProcess;
|
||||
use App\Models\User;
|
||||
use App\Services\PeopleAccess;
|
||||
use App\Services\PeopleHiring;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
if (($argv[1] ?? '') !== '--initialize-authorized-synthetic' || config('app.demonstration') !== true
|
||||
|| DB::connection()->getDatabaseName() !== 'compras_demo_20261129' || PeopleProcess::query()->exists()) {
|
||||
throw new LogicException('Only a new isolated synthetic People journey is allowed.');
|
||||
}
|
||||
try {
|
||||
$result = DB::transaction(function () {
|
||||
$people = [];
|
||||
foreach (['admin', 'head', 'direction'] as $key) {
|
||||
$people[$key] = User::query()->where('email', $key.'@demo.compras.tempo.co.mz')->sole();
|
||||
}
|
||||
$workflow = app(PeopleHiring::class);
|
||||
$command = function (string $actor, ?PeopleProcess $record, string $action, array $data) use ($people, $workflow): PeopleProcess {
|
||||
auth()->guard()->setUser($people[$actor]);
|
||||
|
||||
return $workflow->execute($people[$actor], $record?->id, $action, [
|
||||
'version' => $record?->fresh()->version, 'reason' => 'Percurso fictício para apresentação, sem contratação ou admissão real.', 'no_conflict' => true, ...$data]);
|
||||
};
|
||||
$record = $command('admin', null, 'create', ['operation_key' => (string) Str::uuid(), 'kind' => 'staff',
|
||||
'title' => 'Técnico de manutenção — Demonstração', 'purpose' => 'Processo inteiramente fictício para demonstrar recrutamento e registo documental.',
|
||||
'closes_on' => today()->toDateString(), 'minimum_reviews' => 1,
|
||||
'criteria' => [['label' => 'Competências técnicas', 'weight' => 60], ['label' => 'Experiência relevante', 'weight' => 40]]]);
|
||||
foreach (['head' => ['view', 'review', 'interviews'], 'direction' => ['view', 'approve', 'contract_view']] as $key => $scopes) {
|
||||
auth()->guard()->setUser($people['admin']);
|
||||
app(PeopleAccess::class)->assign($people['admin'], $record->id, ['version' => DB::table('people_access_states')->where('people_process_id', $record->id)->value('version'),
|
||||
'user_id' => $people[$key]->id, 'scopes' => $scopes, 'reason' => 'Equipa fictícia explicitamente designada para a apresentação.']);
|
||||
}
|
||||
$command('head', $record, 'open', []);
|
||||
$command('admin', $record, 'apply', ['operation_key' => (string) Str::uuid(), 'name' => 'Pessoa Fictícia de Demonstração',
|
||||
'reference' => 'DEMO-CAND-001', 'summary' => 'Perfil e experiência exclusivamente fictícios para a demonstração do circuito.', 'received_on' => today()->toDateString()]);
|
||||
$command('admin', $record, 'close', []);
|
||||
$application = DB::table('people_applications')->where('people_process_id', $record->id)->sole();
|
||||
$command('head', $record, 'evaluate', ['application_id' => $application->id, 'answers' => [
|
||||
['score' => 8, 'evidence' => 'Competências fictícias, sem avaliação de pessoa real.'],
|
||||
['score' => 7, 'evidence' => 'Experiência fictícia, exclusivamente ilustrativa.']]]);
|
||||
$command('admin', $record, 'select', ['application_id' => $application->id]);
|
||||
$command('direction', $record, 'confirm', ['outcome' => 'approved']);
|
||||
$command('admin', $record, 'contract', ['reference' => 'DEMO-MINUTA-001', 'starts_on' => today()->addWeek()->toDateString(),
|
||||
'terms' => 'Termos exclusivamente fictícios. Este documento serve a apresentação e não constitui um contrato de trabalho real.']);
|
||||
|
||||
return ['process_id' => $record->id, 'state' => $record->fresh()->status, 'candidate_id' => $application->id,
|
||||
'formalization_authority' => $people['direction']->id, 'signed_contract_confirmation_available' => true, 'employee_admission' => false];
|
||||
});
|
||||
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
} catch (Throwable $error) {
|
||||
fwrite(STDERR, $error::class.': '.$error->getMessage().PHP_EOL);
|
||||
exit(1);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Mail\Message;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
$resultPath = '/var/backups/compras-presentation-20261129/mail-configuration/submission.json';
|
||||
if (($argv[1] ?? '') !== '--send-authorized-test' || config('app.demonstration') !== true
|
||||
|| DB::connection()->getDatabaseName() !== 'compras_demo_20261129' || config('mail.default') !== 'sendmail'
|
||||
|| config('mail.from.address') !== 'nala@tempo.co.mz' || is_file($resultPath)) {
|
||||
throw new LogicException('Only one explicitly authorised mail test may be sent.');
|
||||
}
|
||||
$messageId = Str::uuid()->toString().'@compras.tempo.co.mz';
|
||||
file_put_contents($resultPath, json_encode(['state' => 'submission_started', 'message_id' => $messageId], JSON_THROW_ON_ERROR));
|
||||
$sent = Mail::raw("Mensagem de verificacao do envio real de email da aplicacao Compras, autorizada pelo responsavel.\nSem dados de processos, anexos ou credenciais.\nReferencia: ".$messageId,
|
||||
function (Message $message) use ($messageId): void {
|
||||
$message->to('nala@tempo.co.mz')->subject('Compras - verificacao do envio de email');
|
||||
$message->getSymfonyMessage()->getHeaders()->addIdHeader('Message-ID', $messageId);
|
||||
});
|
||||
if ($sent === null) {
|
||||
throw new LogicException('No mail submission receipt returned.');
|
||||
}
|
||||
$result = ['state' => 'submitted', 'message_id' => $sent->getMessageId(), 'recipient' => 'nala@tempo.co.mz',
|
||||
'sender' => config('mail.from.address'), 'transport' => config('mail.default'), 'business_or_credential_data_sent' => false];
|
||||
file_put_contents($resultPath, json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
|
||||
echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -3,6 +3,7 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import {spawnSync} from 'node:child_process';
|
||||
import { purchasingHomeOverlay } from './lib/sgf-purchasing-home-overlay.mjs';
|
||||
|
||||
const host=fs.realpathSync(process.argv[2]||'');
|
||||
if(fs.existsSync(path.join(host,'public/hot')))throw Error('Stop the source frontend watcher before freezing a candidate.');
|
||||
@@ -19,9 +20,7 @@ app=replace(app,'{labels[p]}','{list?.catalogue_labels?.[p] ?? labels[p] ?? p}')
|
||||
app=replace(app,'{labels[g.permission]}','{list?.catalogue_labels?.[g.permission] ?? labels[g.permission] ?? g.permission}');
|
||||
fs.writeFileSync(path.join(work,'resources/js/app.jsx'),app);
|
||||
let home=fs.readFileSync(path.join(work,'resources/js/PurchasingHome.jsx'),'utf8');
|
||||
home=replace(home,"const payables=unit!==null&&can('supplier_payables.view',unit);", "const payables=unit!==null&&can('supplier_payables.view',unit);\n const requisitions=unit!==null&&can('purchasing_requisitions.view',unit);");
|
||||
home=replace(home,'<div className="actions">','<div className="actions">{requisitions&&<a href="/purchasing/internal-requisitions">Requisições internas</a>}{budget&&<a href="/purchasing/internal-requisitions/budget-setup">Preparação de centros e dotações</a>}');
|
||||
home=replace(home,'!budget&&!payables&&','!budget&&!payables&&!requisitions&&');
|
||||
home=purchasingHomeOverlay(home);
|
||||
fs.writeFileSync(path.join(work,'resources/js/PurchasingHome.jsx'),home);
|
||||
let config=fs.readFileSync(path.join(work,'vite.config.js'),'utf8');
|
||||
config=replace(config,'defineConfig({',`defineConfig({\n cacheDir: ${JSON.stringify(path.join(work,'vite-cache'))},`);
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
require dirname(__DIR__).'/integrations/sgf/operational/CodeDeployment.php';
|
||||
|
||||
use Tempo\Purchasing\Delivery\CodeDeployment;
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
$host = realpath($root.'/../sgf-tempo');
|
||||
$bundle = realpath($argv[1] ?? '');
|
||||
if (! $host || ! $bundle || ! str_starts_with($bundle, realpath($root.'/storage/app/private/candidates').DIRECTORY_SEPARATOR)) {
|
||||
throw new RuntimeException('Only an existing private candidate can be rehearsed.');
|
||||
}
|
||||
$manifest = json_decode(file_get_contents($bundle.'/manifest.json'), true, 64, JSON_THROW_ON_ERROR);
|
||||
$pin = hash_file('sha256', $bundle.'/manifest.json');
|
||||
$pointer = file_get_contents($host.'/packages/purchasing/current.json');
|
||||
$checks = [];
|
||||
$check = function (bool $condition, string $label) use (&$checks): void {
|
||||
if (! $condition) {
|
||||
throw new RuntimeException($label);
|
||||
}
|
||||
$checks[] = $label;
|
||||
};
|
||||
$destination = $root.'/storage/framework/testing/sgf-integration-recovery-'.bin2hex(random_bytes(6));
|
||||
mkdir($destination, 0700, true);
|
||||
foreach ($manifest['host_overlays'] as $path => $entry) {
|
||||
if (str_contains($path, '..') || str_starts_with($path, '/') || str_contains($path, ':')) {
|
||||
throw new RuntimeException('Unsafe candidate path.');
|
||||
}
|
||||
if (! is_dir(dirname($destination.'/'.$path))) {
|
||||
mkdir(dirname($destination.'/'.$path), 0700, true);
|
||||
}
|
||||
$check(hash_file('sha256', $host.'/'.$path) === $entry['before_sha256'], 'source unchanged '.$path);
|
||||
copy($host.'/'.$path, $destination.'/'.$path);
|
||||
}
|
||||
foreach (['packages/purchasing', 'bootstrap/cache', 'storage/framework'] as $dir) {
|
||||
if (! is_dir($destination.'/'.$dir)) {
|
||||
mkdir($destination.'/'.$dir, 0700, true);
|
||||
}
|
||||
}
|
||||
file_put_contents($destination.'/packages/purchasing/current.json', $pointer);
|
||||
file_put_contents($destination.'/storage/framework/down', '{}');
|
||||
$deploy = new CodeDeployment($destination);
|
||||
$plan = $deploy->plan($bundle, $pin);
|
||||
$check($plan['writes'] === false, 'plan read only');
|
||||
$applied = $deploy->apply($bundle, $pin, $plan['target_sha256'], 'Synthetic integration recovery', true);
|
||||
foreach ($manifest['host_overlays'] as $path => $entry) {
|
||||
$check(hash_file('sha256', $destination.'/'.$path) === $entry['after_sha256'], 'candidate applied '.$path);
|
||||
}
|
||||
$check($deploy->apply($bundle, $pin, $plan['target_sha256'], 'Synthetic integration recovery', true)['replayed'] === true, 'retry idempotent');
|
||||
$rolled = $deploy->rollback($applied['deployment_id'], 'Synthetic integration recovery', true);
|
||||
$check($rolled['state'] === 'rolled-back', 'rollback completed');
|
||||
foreach ($manifest['host_overlays'] as $path => $entry) {
|
||||
$check(hash_file('sha256', $destination.'/'.$path) === $entry['before_sha256'], 'previous code restored '.$path);
|
||||
$check(hash_file('sha256', $host.'/'.$path) === $entry['before_sha256'], 'actual host preserved '.$path);
|
||||
}
|
||||
$check(file_get_contents($host.'/packages/purchasing/current.json') === $pointer, 'actual host pointer preserved');
|
||||
$proof = ['date' => gmdate('c'), 'candidate' => basename($bundle), 'manifest_sha256' => $pin,
|
||||
'passed' => true, 'checks' => $checks, 'file_copy' => $destination,
|
||||
'database_connected' => false, 'schema_changed' => false, 'destination_installed' => false,
|
||||
'new_demo' => false, 'services_restarted' => false, 'business_flow_acceptance' => false];
|
||||
file_put_contents($root.'/docs/proofs/sgf-total-integration-recovery-20261130.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR)."\n");
|
||||
echo json_encode(['passed' => true, 'checks' => count($checks), 'installed' => false, 'database_connected' => false]);
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Private recovery snapshot of the selected, verified pilot-aligned sample installation."""
|
||||
from pathlib import Path
|
||||
import hashlib
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
root = Path('/var/www/compras-deploy/current').resolve()
|
||||
assert root == Path('/var/www/compras-deploy/releases/presentation-20261129')
|
||||
manifest = json.loads((root/'compras-release.json').read_text())
|
||||
assert manifest['release_id'] == 'compras-47dfeee7485db877'
|
||||
subprocess.run(['/usr/bin/php', str(root/'scripts/verify-compras-release.php'), str(root), '--installed'], check=True)
|
||||
backup = Path('/var/backups/compras-presentation-20261129/pilot-aligned-current')
|
||||
backup.mkdir(mode=0o700, exist_ok=False)
|
||||
shutil.copy2((root/'.env').resolve(), backup/'selected.env.private')
|
||||
(backup/'selected.env.private').chmod(0o600)
|
||||
with (backup/'database.dump').open('xb') as stream:
|
||||
subprocess.run(['runuser', '-u', 'postgres', '--', 'pg_dump', '-Fc', '-d', 'compras_demo_20261129'], stdout=stream, check=True)
|
||||
subprocess.run(['pg_restore', '--list', str(backup/'database.dump')], stdout=subprocess.DEVNULL, check=True)
|
||||
source = Path('/root/compras-release-pilot-preserved.zip')
|
||||
assert hashlib.sha256(source.read_bytes()).hexdigest() == 'a7e4473e1417b444a42a484f1ddf4f0fc03b64874cb9c304ef74181b30745940'
|
||||
shutil.copy2(source, backup/'product.zip')
|
||||
subprocess.run(['systemctl', 'start', 'compras-operations.service'], check=True)
|
||||
status = subprocess.check_output(['systemctl', 'show', 'compras-operations.service', '-p', 'Result', '-p', 'ExecMainStatus']).decode()
|
||||
assert 'Result=success' in status and 'ExecMainStatus=0' in status
|
||||
assert subprocess.check_output(['systemctl', 'is-active', 'compras-operations.timer']).decode().strip() == 'active'
|
||||
proof = {'state': 'passed', 'release_id': manifest['release_id'], 'backup': str(backup), 'current_dump_readable': True,
|
||||
'prior_full_schema_restore_preserved': True, 'new_schema_migrations': False,
|
||||
'storage_bytes_preserved_and_download_verified': True, 'recurring_service_after_context_alignment': 'passed',
|
||||
'hashes': {name: hashlib.sha256((backup/name).read_bytes()).hexdigest() for name in ['database.dump', 'product.zip']}}
|
||||
(backup/'result.json').write_text(json.dumps(proof, indent=2)+'\n')
|
||||
print(json.dumps(proof))
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Stop only this delivery's no-longer-needed loopback rehearsal process group."""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import signal
|
||||
|
||||
pidfile = Path('/var/www/compras-deploy/demonstration-20261129/staging-pid')
|
||||
pid = int(pidfile.read_text())
|
||||
assert pid == 1173215 and os.getpgid(pid) == pid
|
||||
assert Path('/proc/1173216/cwd').resolve() == Path('/var/www/compras-deploy/releases/presentation-20261129')
|
||||
assert Path('/proc/1173216/cmdline').read_bytes().split(b'\0')[:5] == [b'php', b'-S', b'127.0.0.1:49815', b'-t', b'public']
|
||||
assert Path('/proc/'+str(pid)+'/cmdline').read_bytes().split(b'\0')[:7] == [b'runuser', b'-u', b'www-data', b'--', b'php', b'-S', b'127.0.0.1:49815']
|
||||
os.killpg(pid, signal.SIGTERM)
|
||||
print('Owned loopback staging stopped; selected public application preserved.')
|
||||
@@ -0,0 +1,173 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$root = dirname(__DIR__);
|
||||
$clientRelease = ($argv[1] ?? '') === '--apply-authorized-client-hiring-release';
|
||||
if (! $clientRelease && ($argv[1] ?? '') !== '--apply-authorized-local-unification') {
|
||||
throw new LogicException('Explicit local/public unification required.');
|
||||
}
|
||||
$settingsPath = 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json';
|
||||
$settings = json_decode(file_get_contents($settingsPath), true, 32, JSON_THROW_ON_ERROR);
|
||||
if (($settings['APP_ENV'] ?? '') !== 'payable-testing' || ($settings['DB_HOST'] ?? '') !== '127.0.0.1'
|
||||
|| realpath($settings['HOST_ROOT'] ?? '') !== realpath($root)
|
||||
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $settings['DB_DATABASE'] ?? '', $match)
|
||||
|| $settings['DB_USERNAME'] !== 'payable_qa_'.$match[1]) {
|
||||
throw new LogicException('Refuse any other local installation.');
|
||||
}
|
||||
$archive = $root.'/storage/app/private/'.($clientRelease ? 'compras-release-client-hiring.zip' : 'compras-release-pilot-preserved.zip');
|
||||
$expectedArchiveHash = $clientRelease ? ($argv[2] ?? '') : 'a7e4473e1417b444a42a484f1ddf4f0fc03b64874cb9c304ef74181b30745940';
|
||||
if (! preg_match('/^[a-f0-9]{64}$/D', $expectedArchiveHash) || hash_file('sha256', $archive) !== $expectedArchiveHash) {
|
||||
throw new LogicException('Use the same frozen public release.');
|
||||
}
|
||||
$zip = new ZipArchive;
|
||||
if ($zip->open($archive, ZipArchive::RDONLY) !== true || $zip->getFromName('compras-release.json') !== file_get_contents($root.'/compras-release.json')) {
|
||||
throw new LogicException('Source release differs from the public delivery.');
|
||||
}
|
||||
$manifest = json_decode($zip->getFromName('compras-release.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
$migrations = $clientRelease ? ['database/migrations/2026_11_29_000004_create_business_clients.php']
|
||||
: ['database/migrations/2026_11_03_000005_add_operational_geography_references.php',
|
||||
'database/migrations/2026_11_29_000003_allow_signed_people_contract.php'];
|
||||
$app = require $root.'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
$owner = DB::connection('pgsql')->getConfig();
|
||||
unset($owner['name']);
|
||||
if ($owner['host'] !== '127.0.0.1') {
|
||||
throw new LogicException('A local recovery authority is required.');
|
||||
}
|
||||
$liveConfig = [...$owner, 'url' => null, 'database' => $settings['DB_DATABASE'], 'username' => $settings['DB_USERNAME'], 'password' => $settings['DB_PASSWORD']];
|
||||
config(['database.connections.unify_live' => $liveConfig, 'database.connections.unify_admin' => [...$owner, 'url' => null, 'database' => 'postgres']]);
|
||||
$live = DB::connection('unify_live');
|
||||
$admin = DB::connection('unify_admin');
|
||||
$identity = $live->selectOne('select current_database() as db, current_user as role');
|
||||
if ($identity->db !== $settings['DB_DATABASE'] || $identity->role !== $settings['DB_USERNAME']) {
|
||||
throw new LogicException('Live identity mismatch.');
|
||||
}
|
||||
foreach ($migrations as $migration) {
|
||||
if ($live->table('migrations')->where('migration', basename($migration, '.php'))->exists()) {
|
||||
throw new LogicException('Inspect an already applied unification instead of repeating it.');
|
||||
}
|
||||
}
|
||||
$directory = 'C:/laragon/data/compras/backups/local-public-unification-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(3));
|
||||
if (! mkdir($directory, 0700, true)) {
|
||||
throw new LogicException('Private recovery directory unavailable.');
|
||||
}
|
||||
copy($settingsPath, $directory.'/settings.before.private.json');
|
||||
copy($root.'/public/build/manifest.json', $directory.'/manifest.before.json');
|
||||
$tables = array_column($live->select("select tablename from pg_tables where schemaname='public' order by tablename"), 'tablename');
|
||||
$columns = [];
|
||||
foreach ($tables as $table) {
|
||||
$columns[$table] = Schema::connection('unify_live')->getColumnListing($table);
|
||||
}
|
||||
$fingerprint = static function ($connection, array $selection): array {
|
||||
$out = [];
|
||||
foreach ($selection as $table => $fields) {
|
||||
$quoted = implode(',', array_map(fn ($field) => '"'.str_replace('"', '""', $field).'"', $fields));
|
||||
$rows = $connection->select('select row_to_json(t)::text as row from (select '.$quoted.' from "'.str_replace('"', '""', $table).'") t order by row_to_json(t)::text');
|
||||
$out[$table] = hash('sha256', json_encode(array_column($rows, 'row'), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
return $out;
|
||||
};
|
||||
$pg = static function (string $binary, array $arguments, array $connection): void {
|
||||
$process = new Process(['C:/Program Files/PostgreSQL/17/bin/'.$binary.'.exe', ...$arguments], null,
|
||||
['PGHOST' => $connection['host'], 'PGPORT' => (string) $connection['port'], 'PGUSER' => $connection['username'], 'PGPASSWORD' => $connection['password']], timeout: 120);
|
||||
$process->run();
|
||||
if (! $process->isSuccessful()) {
|
||||
throw new RuntimeException('Private '.$binary.' failed; no credentials are printed.');
|
||||
}
|
||||
};
|
||||
$restoreName = 'compras_unify_restore_'.bin2hex(random_bytes(6));
|
||||
$created = false;
|
||||
try {
|
||||
$live->beginTransaction();
|
||||
$live->statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
$before = $fingerprint($live, $columns);
|
||||
$snapshot = $live->selectOne('select pg_export_snapshot() as snapshot')->snapshot;
|
||||
$pg('pg_dump', ['--format=custom', '--snapshot='.$snapshot, '--file='.$directory.'/before.dump', '--dbname='.$liveConfig['database']], $liveConfig);
|
||||
$live->commit();
|
||||
$admin->statement('CREATE DATABASE "'.$restoreName.'"');
|
||||
$created = true;
|
||||
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restoreName, $directory.'/before.dump'], $owner);
|
||||
config(['database.connections.unify_restore' => [...$owner, 'url' => null, 'database' => $restoreName]]);
|
||||
$restore = DB::connection('unify_restore');
|
||||
if ($fingerprint($restore, $columns) !== $before) {
|
||||
throw new LogicException('Recovered rows differ from the private snapshot.');
|
||||
}
|
||||
if (Artisan::call('migrate', ['--database' => 'unify_restore', '--path' => $migrations, '--force' => true]) !== 0) {
|
||||
throw new LogicException('Recovery-copy upgrade failed.');
|
||||
}
|
||||
$protected = array_diff_key($columns, array_flip(['migrations']));
|
||||
if ($fingerprint($restore, $protected) !== array_intersect_key($before, $protected)) {
|
||||
throw new LogicException('Recovery-copy original data changed.');
|
||||
}
|
||||
$activeProtected = array_diff_key($protected, array_flip(['sessions', 'cache', 'cache_locks', 'jobs', 'failed_jobs', 'job_batches']));
|
||||
$live->beginTransaction();
|
||||
foreach (array_keys($activeProtected) as $table) {
|
||||
$live->statement('LOCK TABLE "'.str_replace('"', '""', $table).'" IN SHARE ROW EXCLUSIVE MODE');
|
||||
}
|
||||
if ($fingerprint($live, $activeProtected) !== array_intersect_key($before, $activeProtected)) {
|
||||
throw new LogicException('Business state changed since backup; preserve it and prepare a fresh snapshot.');
|
||||
}
|
||||
if (Artisan::call('migrate', ['--database' => 'unify_live', '--path' => $migrations, '--force' => true]) !== 0
|
||||
|| $fingerprint($live, $activeProtected) !== array_intersect_key($before, $activeProtected)) {
|
||||
throw new LogicException('Atomic local upgrade failed preservation checks.');
|
||||
}
|
||||
$live->commit();
|
||||
foreach (array_keys($manifest['frontend']['files']) as $file) {
|
||||
$name = 'public/build/'.$file;
|
||||
$bytes = $zip->getFromName($name);
|
||||
if (! is_string($bytes) || hash('sha256', $bytes) !== $manifest['frontend']['files'][$file]) {
|
||||
throw new LogicException('Frozen frontend content mismatch.');
|
||||
}
|
||||
$target = $root.'/'.$name;
|
||||
if (is_file($target) && file_get_contents($target) !== $bytes) {
|
||||
throw new LogicException('Preserve an immutable asset collision.');
|
||||
}
|
||||
if (! is_file($target)) {
|
||||
file_put_contents($target, $bytes);
|
||||
}
|
||||
}
|
||||
foreach (['fonts-manifest.json', 'manifest.json'] as $file) {
|
||||
$target = $root.'/public/build/'.$file;
|
||||
file_put_contents($target.'.unify-next', $zip->getFromName('public/build/'.$file));
|
||||
if (! rename($target.'.unify-next', $target)) {
|
||||
throw new LogicException('Frontend pointer switch failed; original manifest is backed up.');
|
||||
}
|
||||
}
|
||||
$report = ['state' => 'passed', 'release_id' => $manifest['release_id'], 'backup' => $directory,
|
||||
'restored_tables_verified' => count($tables), 'protected_business_tables_preserved' => count($activeProtected),
|
||||
'selected_migrations_applied' => $migrations, 'frontend_assets' => count($manifest['frontend']['files']),
|
||||
'settings_users_permissions_and_original_columns_preserved' => true, 'public_or_sgf_database_changed' => false];
|
||||
if ($clientRelease) {
|
||||
$nextSettings = [...$settings, 'SGC_PEOPLE_THIRD_PARTY_ENABLED' => 'true'];
|
||||
$temporarySettings = $settingsPath.'.client-next';
|
||||
file_put_contents($temporarySettings, json_encode($nextSettings, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
|
||||
if (! rename($temporarySettings, $settingsPath)) {
|
||||
throw new LogicException('Client hiring configuration switch failed; original settings are backed up.');
|
||||
}
|
||||
$report['settings_users_permissions_and_original_columns_preserved'] = false;
|
||||
$report['original_settings_users_permissions_and_original_columns_preserved'] = true;
|
||||
$report['added_configuration'] = ['SGC_PEOPLE_THIRD_PARTY_ENABLED' => true];
|
||||
}
|
||||
} finally {
|
||||
if ($live->transactionLevel() > 0) {
|
||||
$live->rollBack();
|
||||
}
|
||||
DB::purge('unify_restore');
|
||||
if ($created) {
|
||||
if (! preg_match('/^compras_unify_restore_[a-f0-9]{12}$/D', $restoreName) || $restoreName === $settings['DB_DATABASE']) {
|
||||
throw new LogicException('Recovery cleanup identity mismatch.');
|
||||
}
|
||||
$admin->statement('DROP DATABASE "'.$restoreName.'"');
|
||||
}
|
||||
$zip->close();
|
||||
}
|
||||
$report['temporary_restore_database_removed'] = true;
|
||||
file_put_contents($root.'/docs/proofs/'.($clientRelease ? 'compras-local-client-hiring.json' : 'compras-local-unification.json'), json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
|
||||
echo json_encode($report, JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
$inspect = ($argv[1] ?? '') === '--inspect-client-registry';
|
||||
$reconcile = ($argv[1] ?? '') === '--record-verified-empty-registry';
|
||||
$target = $reconcile ? '--apply-authorized-client-registry' : ($inspect ? ($argv[2] ?? '--apply-authorized-client-registry') : ($argv[1] ?? ''));
|
||||
$restore = preg_match('/^compras_client_restore_[a-f0-9]{12}$/D', $target) === 1;
|
||||
if (! $restore && $target !== '--apply-authorized-client-registry') {
|
||||
throw new LogicException('An explicit recovery copy or authorised installation is required.');
|
||||
}
|
||||
$base = DB::connection()->getConfig();
|
||||
unset($base['name']);
|
||||
if ($base['driver'] !== 'pgsql' || ! in_array($base['host'], ['127.0.0.1', 'localhost'], true)
|
||||
|| ($base['database'] !== 'compras_demo_20261129' && ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $base['database']))) {
|
||||
throw new LogicException('Refuse any other installation.');
|
||||
}
|
||||
config(['database.connections.registry_upgrade' => [...$base, 'url' => null, 'database' => $restore ? $target : $base['database']]]);
|
||||
$db = DB::connection('registry_upgrade');
|
||||
$identity = $db->selectOne('select current_database() as database_name');
|
||||
if ($db->getName() !== 'registry_upgrade' || $identity->database_name !== ($restore ? $target : $base['database'])) {
|
||||
throw new LogicException('Migration connection identity mismatch; refuse all writes.');
|
||||
}
|
||||
$exists = $db->getSchemaBuilder()->hasTable('business_clients');
|
||||
if ($inspect || $reconcile) {
|
||||
$schema = [];
|
||||
if ($exists) {
|
||||
$schema['columns'] = $db->select("select a.attname,format_type(a.atttypid,a.atttypmod) as type,a.attnotnull,pg_get_expr(d.adbin,d.adrelid) as default_value from pg_attribute a left join pg_attrdef d on d.adrelid=a.attrelid and d.adnum=a.attnum where a.attrelid='business_clients'::regclass and a.attnum>0 and not a.attisdropped order by a.attnum");
|
||||
$schema['constraints'] = $db->select("select conname,pg_get_constraintdef(oid) as definition from pg_constraint where conrelid='business_clients'::regclass order by conname");
|
||||
$schema['indexes'] = $db->select("select indexname,indexdef from pg_indexes where schemaname='public' and tablename='business_clients' order by indexname");
|
||||
$schema['triggers'] = $db->select("select tgname,pg_get_triggerdef(oid) as definition from pg_trigger where tgrelid='business_clients'::regclass and not tgisinternal order by tgname");
|
||||
$schema['function'] = $db->select("select pg_get_functiondef('sgc_preserve_business_client()'::regprocedure) as definition");
|
||||
}
|
||||
$schemaHash = $exists ? hash('sha256', json_encode($schema, JSON_THROW_ON_ERROR)) : null;
|
||||
if ($reconcile) {
|
||||
if (! $exists || ! hash_equals('4187827c43b41406db7b959f093cc8b2761b04406b268690718e025d3f2e1474', $schemaHash)
|
||||
|| $identity->database_name !== 'compras_demo_20261129') {
|
||||
throw new LogicException('Only the exact privately recovered native schema may be reconciled.');
|
||||
}
|
||||
$db->transaction(function () use ($db): void {
|
||||
$db->statement('LOCK TABLE business_clients,migrations IN SHARE ROW EXCLUSIVE MODE');
|
||||
if ($db->table('business_clients')->exists() || $db->table('migrations')->where('migration', '2026_11_29_000004_create_business_clients')->exists()) {
|
||||
throw new LogicException('Preserve existing registry data or migration decisions.');
|
||||
}
|
||||
$repository = new Illuminate\Database\Migrations\DatabaseMigrationRepository(app('db'), 'migrations');
|
||||
$repository->setSource('registry_upgrade');
|
||||
$repository->log('2026_11_29_000004_create_business_clients', $repository->getNextBatchNumber());
|
||||
});
|
||||
echo json_encode(['state' => 'passed', 'mode' => 'exact_empty_schema_reconciled', 'schema_sha256' => $schemaHash,
|
||||
'existing_business_data_changed' => false, 'permissions_changed' => false], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
exit(0);
|
||||
}
|
||||
echo json_encode(['database' => $identity->database_name, 'connection_name' => $db->getName(), 'exists' => $exists,
|
||||
'schema_sha256' => $schemaHash,
|
||||
'migration_recorded' => $db->table('migrations')->where('migration', '2026_11_29_000004_create_business_clients')->exists(),
|
||||
'client_count' => $exists ? $db->table('business_clients')->count() : null], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
exit(0);
|
||||
}
|
||||
if ($exists) {
|
||||
throw new LogicException('Registry already installed; inspect instead of repeating this upgrade.');
|
||||
}
|
||||
$migration = 'database/migrations/2026_11_29_000004_create_business_clients.php';
|
||||
$tables = array_column($db->select("select tablename from pg_tables where schemaname='public' order by tablename"), 'tablename');
|
||||
$protected = array_values(array_diff($tables, ['migrations', 'sessions', 'cache', 'cache_locks', 'jobs', 'failed_jobs', 'job_batches']));
|
||||
$fingerprint = static function () use ($db, $protected): array {
|
||||
$hashes = [];
|
||||
foreach ($protected as $table) {
|
||||
$quoted = '"'.str_replace('"', '""', $table).'"';
|
||||
$rows = $db->select('select row_to_json(t)::text as row from '.$quoted.' t order by row_to_json(t)::text');
|
||||
$hashes[$table] = hash('sha256', json_encode(array_column($rows, 'row'), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
return $hashes;
|
||||
};
|
||||
$db->transaction(function () use ($db, $protected, $fingerprint, $migration): void {
|
||||
foreach ($protected as $table) {
|
||||
$db->statement('LOCK TABLE "'.str_replace('"', '""', $table).'" IN SHARE ROW EXCLUSIVE MODE');
|
||||
}
|
||||
$before = $fingerprint();
|
||||
if (Artisan::call('migrate', ['--database' => 'registry_upgrade', '--path' => [$migration], '--force' => true]) !== 0
|
||||
|| $fingerprint() !== $before || $db->table('business_clients')->count() !== 0) {
|
||||
throw new LogicException('Registry upgrade failed preservation checks.');
|
||||
}
|
||||
});
|
||||
echo json_encode(['state' => 'passed', 'mode' => $restore ? 'recovery_copy' : 'selected_installation',
|
||||
'existing_business_tables_preserved' => count($protected), 'client_records_created' => 0,
|
||||
'permissions_changed' => false, 'migration' => $migration], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Read only log records belonging to the owner's authorised Compras test."""
|
||||
from pathlib import Path
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
directory = Path('/var/backups/compras-presentation-20261129/mail-configuration')
|
||||
receipt = json.loads((directory/'submission.json').read_text())
|
||||
assert receipt['state'] == 'submitted' and receipt['recipient'] == 'nala@tempo.co.mz'
|
||||
log = Path('/var/log/mail.log')
|
||||
if log.exists():
|
||||
with log.open('rb') as stream:
|
||||
stream.seek(max(0, log.stat().st_size-4*1024*1024))
|
||||
lines = stream.read().decode('utf-8', errors='replace').splitlines()
|
||||
else:
|
||||
lines = subprocess.check_output(['journalctl', '--since', '-15 minutes', '--no-pager', '-o', 'cat', 'SYSLOG_FACILITY=2']).decode('utf-8', errors='replace').splitlines()
|
||||
identifiers = {receipt['message_id']}
|
||||
matching = []
|
||||
for _ in range(5):
|
||||
for line in lines:
|
||||
if any(identifier+':' in line or 'message-id=<'+identifier+'>' in line for identifier in identifiers):
|
||||
if line not in matching:
|
||||
matching.append(line)
|
||||
identifiers.update(re.findall(r'queued as ([A-Za-z0-9]+)', line))
|
||||
delivered = [line for line in matching if 'to=<nala@tempo.co.mz>' in line and 'status=sent' in line and re.search(r'relay=(?:dovecot|virtual|local|[^,]*lmtp)', line)]
|
||||
mailbox = subprocess.run(['doveadm', 'search', '-u', 'nala@tempo.co.mz', 'HEADER', 'Subject',
|
||||
'Compras - verificacao do envio de email', 'SINCE', '29-Nov-2026'], capture_output=True, text=True)
|
||||
mailbox_matches = [line for line in mailbox.stdout.splitlines() if re.fullmatch(r'[a-f0-9]{32} [0-9]+', line)] if mailbox.returncode == 0 else []
|
||||
proof = {'state': 'delivered_to_mailbox' if delivered or len(mailbox_matches) == 1 else 'submission_accepted_delivery_not_yet_verified',
|
||||
'sender': receipt['sender'], 'recipient': receipt['recipient'], 'transport': receipt['transport'],
|
||||
'queue_identifiers': sorted(identifiers), 'matching_mail_log_records': len(matching),
|
||||
'mailbox_delivery_records': len(delivered), 'targeted_test_message_found_in_authorized_mailbox': len(mailbox_matches) == 1,
|
||||
'mailbox_other_messages_or_message_bodies_read': False, 'test_messages_sent': 1, 'business_or_credential_data_sent': False}
|
||||
(directory/'delivery.json').write_text(json.dumps(proof, indent=2)+'\n')
|
||||
print(json.dumps(proof))
|
||||
if '--diagnose' in sys.argv:
|
||||
print('\n'.join(matching))
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
// Read-only release verification. No Laravel bootstrap, database or business commands.
|
||||
$arguments = $argv ?? [];
|
||||
$root = realpath($arguments[1] ?? '');
|
||||
try {
|
||||
if ($root === false || ! is_dir($root)) {
|
||||
throw new LogicException('Compras release directory required.');
|
||||
}
|
||||
$bytes = file_get_contents($root.'/compras-release.json');
|
||||
if (! is_string($bytes)) {
|
||||
throw new LogicException('Compras release manifest missing.');
|
||||
}
|
||||
$manifest = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
|
||||
if (($manifest['product'] ?? null) !== 'compras' || ($manifest['contract'] ?? null) !== 'compras.release.v1') {
|
||||
throw new LogicException('Unexpected product or release contract.');
|
||||
}
|
||||
$identity = $manifest;
|
||||
unset($identity['release_id']);
|
||||
if (! hash_equals($manifest['release_id'], 'compras-'.substr(hash('sha256', json_encode($identity, JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)), 0, 16))) {
|
||||
throw new LogicException('Release identity mismatch.');
|
||||
}
|
||||
$verify = static function (string $base, string $file, string $digest, bool $normalise = false): void {
|
||||
$contents = is_file($base.'/'.$file) ? file_get_contents($base.'/'.$file) : false;
|
||||
$actual = is_string($contents) ? hash('sha256', $normalise ? str_replace("\r\n", "\n", $contents) : $contents) : false;
|
||||
if ($file === '' || str_starts_with($file, '/') || str_contains($file, '..') || str_contains($file, '\\')
|
||||
|| is_link($base.'/'.$file) || ! is_string($actual) || ! hash_equals($digest, $actual)) {
|
||||
throw new LogicException('Release file mismatch: '.$file);
|
||||
}
|
||||
};
|
||||
foreach ($manifest['source_files'] as $file => $digest) {
|
||||
$verify($root, $file, $digest, ($manifest['source_eol'] ?? 'exact') === 'lf' && ! in_array($file, $manifest['exact_source_files'] ?? [], true));
|
||||
}
|
||||
$compiled = in_array('--compiled', $arguments, true) || in_array('--installed', $arguments, true);
|
||||
if ($compiled) {
|
||||
$verify($root, 'public/build/manifest.json', $manifest['frontend']['manifest_sha256']);
|
||||
if (isset($manifest['frontend']['fonts_manifest_sha256'])) {
|
||||
$verify($root, 'public/build/fonts-manifest.json', $manifest['frontend']['fonts_manifest_sha256']);
|
||||
}
|
||||
foreach ($manifest['frontend']['files'] as $file => $digest) {
|
||||
$verify($root.'/public/build', $file, $digest);
|
||||
}
|
||||
}
|
||||
if (in_array('--installed', $arguments, true)) {
|
||||
$settings = parse_ini_file($root.'/.env', false, INI_SCANNER_RAW);
|
||||
if (! is_array($settings) || ($settings['COMPRAS_RUNTIME_ENABLED'] ?? null) !== 'true') {
|
||||
throw new LogicException('Integrated Compras runtime is not selected.');
|
||||
}
|
||||
foreach ($manifest['components'] as $component) {
|
||||
$componentRoot = realpath($settings[$component['setting']] ?? '');
|
||||
if ($componentRoot === false) {
|
||||
throw new LogicException('Selected component unavailable.');
|
||||
}
|
||||
$verify($componentRoot, 'manifest.json', $component['manifest_sha256']);
|
||||
$componentBytes = file_get_contents($componentRoot.'/manifest.json');
|
||||
if (! is_string($componentBytes)) {
|
||||
throw new LogicException('Component manifest unreadable.');
|
||||
}
|
||||
$componentManifest = json_decode($componentBytes, true, 512, JSON_THROW_ON_ERROR);
|
||||
foreach ($componentManifest['files'] as $key => $entry) {
|
||||
if (is_array($entry)) {
|
||||
$verify($componentRoot, $entry['file'], $entry['sha256']);
|
||||
} else {
|
||||
$verify($componentRoot, $key, $entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
echo json_encode(['state' => 'passed', 'product' => 'compras', 'release_id' => $manifest['release_id'],
|
||||
'source_files' => count($manifest['source_files']), 'asset_files' => $compiled ? count($manifest['frontend']['files']) : 0,
|
||||
'installed_components' => in_array('--installed', $arguments, true) ? count($manifest['components']) : 0], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
} catch (Throwable $error) {
|
||||
fwrite(STDERR, $error->getMessage().PHP_EOL);
|
||||
exit(1);
|
||||
}
|
||||
Reference in New Issue
Block a user