make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap(); if (! \App\Modules\Identity\Services\LocalDatabaseGuard::allows()) { throw new RuntimeException('Own local development database required.'); } $args = array_values(array_filter(array_slice($argv, 1), fn ($arg) => $arg !== '--apply')); if (count($args) !== 4 || array_filter($args, fn ($id) => ! ctype_digit($id))) { throw new RuntimeException('Usage: document-access.php editor_id reader_id company_id unit_id [--apply]; specific confirmation required.'); } [$editor, $reader, $company, $unit] = array_map('intval', $args); if ($editor === $reader) { throw new RuntimeException('The two specifically confirmed accounts must be distinct.'); } $db = \Illuminate\Support\Facades\DB::class; $scope = $db::table('units as n')->join('companies as c', 'n.company_id', '=', 'c.id')->where('n.id', $unit)->where('c.id', $company)->first(['n.tenant_id','n.company_id','n.id as unit_id','n.name as unit_name','c.name as company_name']); if (! $scope) { throw new RuntimeException('Existing scope not found.'); } $plan = []; foreach ([$editor => ['view','edit'], $reader => ['view']] as $user => $actions) { $account = $db::table('users')->where('id', $user)->first(['id','name','email']); if (! $account) { throw new RuntimeException('Existing account not found; no account created.'); } foreach (['issuer_documents','client_documents','draft_documents'] as $area) { foreach ($actions as $action) { $plan[] = ['user' => $account, 'tenant_id' => $scope->tenant_id, 'company_id' => $company, 'unit_id' => $area === 'draft_documents' ? $unit : null, 'permission' => "$area.$action"]; } } } if (! in_array('--apply', $argv, true)) { echo json_encode(['scope' => $scope, 'grants' => $plan], JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE).PHP_EOL; exit(0); } $db::transaction(function () use ($db, $scope, $plan): void { $db::table('companies')->where('id', $scope->company_id)->lockForUpdate()->firstOrFail(); foreach ($plan as $grant) { $user = $grant['user']->id; foreach (['company.view','unit.view'] as $permission) { app(\App\Modules\Identity\Services\Permissions::class)->require($user, $scope->tenant_id, $scope->company_id, $permission, $permission === 'unit.view' ? $scope->unit_id : null); } $row = array_diff_key($grant, ['user' => true]) + ['user_id' => $user]; if ($db::table('permission_grants')->insertOrIgnore($row + ['created_at' => now(), 'updated_at' => now()])) { \App\Modules\Identity\Services\Audit::record('documents.access.initial_grant', null, $scope->tenant_id, $scope->company_id, $grant['unit_id'], $user, ['permission' => $grant['permission'], 'reason' => 'Preparação documental: concessão especificamente confirmada pelo utilizador.']); } } }); echo "Specifically confirmed document preparation grants applied; no accounts or financial powers created.\n";