Compare commits

...
4 Commits
8 changed files with 130 additions and 25 deletions
@@ -5,15 +5,24 @@ namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Sleep;
use Throwable;
class CheckDevelopmentEnvironment extends Command
{
protected $signature = 'portal:dev-check';
protected $signature = 'portal:dev-check {--wait=0 : Segundos para aguardar uma falha transitória do PostgreSQL}';
protected $description = 'Verifica o arranque local sem alterar dados ou mostrar credenciais';
public function handle(): int
{
$wait = filter_var($this->option('wait'), FILTER_VALIDATE_INT, ['options' => ['min_range' => 0, 'max_range' => 3600]]);
if ($wait === false) {
$this->error('--wait deve ser um inteiro entre 0 e 3600 segundos.');
return self::INVALID;
}
$checks = [
'PHP >= 8.4.1' => version_compare(PHP_VERSION, '8.4.1', '>='),
'Driver PostgreSQL activo' => extension_loaded('pdo_pgsql'),
@@ -25,14 +34,17 @@ class CheckDevelopmentEnvironment extends Command
];
if ($checks['Driver PostgreSQL activo'] && $checks['Base PostgreSQL configurada']) {
$checks['Ligação à base de dados'] = $this->checkConnection($wait);
}
if ($checks['Ligação à base de dados'] ?? false) {
try {
DB::selectOne('SELECT 1');
$checks['Ligação à base de dados'] = true;
$checks['Extensão PostGIS instalada'] = (bool) DB::selectOne("SELECT EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'postgis') AS installed")->installed;
$checks['Tabelas principais instaladas'] = collect(['migrations', 'users', 'sectors', 'opportunities', 'sessions', 'cache', 'jobs'])
->every(fn (string $table): bool => Schema::hasTable($table));
} catch (\Throwable) {
$checks['Ligação à base de dados'] = false;
} catch (Throwable) {
$checks['Esquema da base de dados verificável'] = false;
$this->warn('A ligação foi estabelecida, mas a verificação do esquema falhou. Verifique as permissões e a preparação QA.');
}
}
@@ -48,4 +60,61 @@ class CheckDevelopmentEnvironment extends Command
return self::SUCCESS;
}
private function checkConnection(int $wait): bool
{
$deadline = microtime(true) + $wait;
while (true) {
try {
DB::selectOne('SELECT 1');
return true;
} catch (Throwable $error) {
[$reason, $retryable] = $this->connectionFailure($error);
$remaining = $deadline - microtime(true);
if (! $retryable || $remaining <= 0) {
$this->warn($reason);
if ($retryable) {
$this->warn('Inicie Docker Desktop e execute ./deploy/local/start.ps1. Consulte os registos com docker compose --env-file .env -f deploy/local/compose.yaml logs --tail 40 postgres.');
}
return false;
}
$this->line('[AGUARDA] '.$reason.' Nova tentativa; prazo restante: '.(int) ceil($remaining).' s.');
DB::purge();
Sleep::for(min(5, $remaining))->seconds();
}
}
}
/** @return array{string, bool} */
private function connectionFailure(Throwable $error): array
{
// Inspect the chain internally; never print exception messages, DSNs or credentials.
$messages = '';
do {
$messages .= ' '.strtolower($error->getMessage()).' '.strtolower((string) $error->getCode());
$error = $error->getPrevious();
} while ($error !== null);
if (str_contains($messages, '28p01') || str_contains($messages, '28000')
|| str_contains($messages, 'password authentication failed') || str_contains($messages, 'no pg_hba.conf entry')) {
return ['Autenticação PostgreSQL recusada. Verifique as credenciais e as regras de acesso; aguardar não corrige este erro.', false];
}
if (str_contains($messages, '3d000') || preg_match('/database .* does not exist/', $messages)) {
return ['A base PostgreSQL configurada não existe. Verifique a configuração e a preparação QA.', false];
}
if (str_contains($messages, '57p03') || str_contains($messages, 'recovery mode')
|| str_contains($messages, 'not yet accepting connections') || str_contains($messages, 'database system is starting up')) {
return ['PostgreSQL em arranque ou recuperação; aguarde a conclusão sem remover o volume.', true];
}
if (preg_match('/\b08[0-9a-z]{3}\b/', $messages) || str_contains($messages, 'connection refused')
|| str_contains($messages, '57p01') || str_contains($messages, '57p02')) {
return ['PostgreSQL indisponível. Verifique se Docker Desktop e o contentor local estão iniciados.', true];
}
return ['Falha PostgreSQL não transitória. Verifique a configuração e os registos do servidor.', false];
}
}
+13 -4
View File
@@ -202,7 +202,10 @@ class Delivery:
self.run(['npm','run','build'],cwd=release,env=env)
self.run(['npm','run','types:check'],cwd=release,env=env)
self.run([self.c['php'],'tools/portal-diagnostics-deployment-guard.php'],cwd=release,env=env)
self.run([self.c['php'],'vendor/bin/phpunit','--configuration=phpunit.xml','--testsuite','Unit','--do-not-cache-result'],cwd=release,env=env)
# Unit fixtures mock DB/mail and select their own feature settings.
# Do not inject the destination's enabled-module flags into those mocks.
unit_env={k:v for k,v in env.items() if not k.startswith(('PORTAL_','INVESTMOZ_'))}
self.run([self.c['php'],'vendor/bin/phpunit','--configuration=phpunit.xml','--testsuite','Unit','--do-not-cache-result'],cwd=release,env=unit_env)
tests=sorted((release/'tests/frontend').glob('*.test.mjs'))
self.run(['node','--test',*tests],cwd=release,env=env)
# Final production vendor from the same lock, before linking any real configuration.
@@ -259,6 +262,9 @@ class Delivery:
latest=self.git('rev-parse','refs/heads/delivery-target')
write_json(self.state/'requests'/(latest+'.json'),{'commit':latest,'reason':'newer integration during build'})
return {'status':'superseded','commit':target,'newer_commit':latest}
# A programmer may have edited the served release while CI was running.
# Recheck immediately before the atomic switch, preserving that work.
refuse_drift(self.current.resolve(),installed['hashes'])
previous=promote(self.current,release,lambda:self.health(target))
try:
self.run([self.c['php'],str(release/'artisan'),'queue:restart'],cwd=release)
@@ -271,15 +277,16 @@ class Delivery:
raise
return {key:value for key,value in info.items() if key!='hashes'}
def process(self) -> None:
def process(self) -> bool:
import fcntl
self.state.mkdir(parents=True,exist_ok=True)
for directory in ['reports','logs','processed','qa-runtime']: (self.state/directory).mkdir(exist_ok=True)
with (self.state/'delivery.lock').open('a') as lock:
fcntl.flock(lock,fcntl.LOCK_EX)
succeeded=True
for _ in range(3):
requests=sorted((self.state/'requests').glob('*.json'))
if not requests:return
if not requests:return succeeded
for path in requests:
if not SHA.fullmatch(path.stem):raise RuntimeError('Unexpected queue entry')
path.rename(self.state/'processed'/(path.stem+'-'+uuid.uuid4().hex[:8]+'.json'))
@@ -288,11 +295,13 @@ class Delivery:
try:
target=self.latest();report=self.deliver(target)
except Exception as error:
succeeded=False
report={'status':'failed','commit':target,'error':str(error),'active_release_preserved':True}
finally:self.log=None
report.update(requested_commits=[p.stem for p in requests],finished_at=datetime.datetime.now(datetime.timezone.utc).isoformat())
write_json(self.state/'reports'/((target or 'fetch-failed')+'-'+str(time.time_ns())+'.json'),report)
print(json.dumps(report),flush=True)
return succeeded
def rollback(self) -> dict:
import fcntl
@@ -326,6 +335,6 @@ def main():
if Path(config['legacy_root']).resolve()!=Path('/var/www/html/teste-investidor.tempo.co.mz'):raise SystemExit('Unexpected persistent application target')
runner=Delivery(config)
if args.rollback:print(json.dumps(runner.rollback()),flush=True)
else:runner.process()
else:raise SystemExit(0 if runner.process() else 1)
if __name__=='__main__':main()
+1 -1
View File
@@ -114,7 +114,7 @@ export async function portalRequest<T>(
const headers = new Headers(options.headers);
headers.set('Accept', 'application/json');
if (options.method && !['GET', 'HEAD'].includes(options.method.toUpperCase())) {
const token = document.cookie.split('; ').find(value => value.startsWith('XSRF-TOKEN='))?.slice(11);
const token = typeof document === 'undefined' ? undefined : document.cookie.split('; ').find(value => value.startsWith('XSRF-TOKEN='))?.slice(11);
if (token) headers.set('X-XSRF-TOKEN', decodeURIComponent(token));
}
const response = await fetch(url, {
+1 -4
View File
@@ -2,13 +2,10 @@
namespace Tests\Unit;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
use PHPUnit\Framework\TestCase;
class ExampleTest extends TestCase
{
use RefreshDatabase;
public function test_that_true_is_true()
{
$this->assertTrue(true);
+15
View File
@@ -144,6 +144,21 @@ await test('fetch accepts a real server confirmation', async (t) => {
assert.equal(response.data.reference, 'IR-SERVER-001');
});
await test('browser writes preserve the CSRF cookie header', async (t) => {
const previous = Object.getOwnPropertyDescriptor(globalThis, 'document');
Object.defineProperty(globalThis, 'document', { configurable: true, value: { cookie: 'other=x; XSRF-TOKEN=qa%2Ftoken' } });
try {
t.mock.method(globalThis, 'fetch', async (_url, options) => {
assert.equal(options.headers.get('X-XSRF-TOKEN'), 'qa/token');
return new Response('{"success":true}', { status: 201 });
});
await portalRequest('/api/v1/interest-requests', { method: 'POST' });
} finally {
if (previous) Object.defineProperty(globalThis, 'document', previous);
else delete globalThis.document;
}
});
for (const status of [422, 429, 500]) {
await test(`HTTP ${status} never becomes a successful confirmation`, async (t) => {
t.mock.method(
+14 -3
View File
@@ -2,6 +2,7 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import {
portalNavigation,
legacyPortalNavigation,
currentNavigationGroup,
currentNavigationItem,
} from '../../resources/js/lib/portal-navigation.ts';
@@ -15,7 +16,7 @@ void test('public and authenticated navigation share groups without revealing ma
assert.deepEqual(publicGroups.slice(0, 3), investor.slice(0, 3));
assert.deepEqual(
publicGroups.map((g) => g.id),
['explore', 'prepare', 'support', 'partnerships', 'account'],
['discovery', 'realization', 'support', 'account'],
);
const hrefs = JSON.stringify(investor);
assert.equal(hrefs.includes('/management/'), false);
@@ -32,7 +33,7 @@ void test('management and optional modules follow permissions and feature flags'
education: true,
ai: true,
});
assert.equal(groups.at(-1).id, 'management');
assert.ok(groups.some((group) => group.id === 'management'));
assert.equal(JSON.stringify(groups).includes('/investidor/negocios'), true);
assert.equal(JSON.stringify(groups).includes('/management/ai'), true);
assert.equal(
@@ -48,7 +49,9 @@ void test('management and optional modules follow permissions and feature flags'
});
void test('detail URLs and filtered catalogue pages retain the current group', () => {
const groups = portalNavigation({ authenticated: true, manager: true });
// Preserve the retained catalogue's detail/filter matching independently
// of the reconciled shell's new grouping names.
const groups = legacyPortalNavigation({ authenticated: true, manager: true });
for (const url of [
'/carteira/project/fixture',
'/zonas?category=zee',
@@ -81,3 +84,11 @@ void test('detail URLs and filtered catalogue pages retain the current group', (
'zee',
);
});
void test('reconciled navigation selects discovery, realization and private support correctly', () => {
const groups = portalNavigation({ authenticated: false, manager: false });
assert.equal(currentNavigationGroup(groups, '/oportunidades/fixture'), 'discovery');
assert.equal(currentNavigationGroup(groups, '/simulador-fiscal'), 'realization');
assert.equal(currentNavigationGroup(groups, '/balcao-virtual/dossiers/fixture'), 'support');
assert.equal(currentNavigationGroup(groups, '/management/crm/leads'), null);
});
@@ -114,15 +114,19 @@ void test('business plan values in the dossier equal the existing simulator fore
const finance = report.sections.find((section) => section.id === 'finance');
const row = (field) =>
finance.rows.find((item) => item.field === field).value;
const numeric = (value) => {
assert.match(value, /MZN$/);
return value.replace(/\s|MZN/g, '').replace(',', '.');
};
assert.equal(
row('Facturação no horizonte'),
`${expected.totalRevenue} MZN`,
numeric(row('Facturação no horizonte')),
expected.totalRevenue,
);
assert.equal(
row('Resultado antes de impostos'),
`${expected.totalProfitBeforeTax} MZN`,
numeric(row('Resultado antes de impostos')),
expected.totalProfitBeforeTax,
);
assert.equal(row('Caixa final projectada'), `${expected.endingCash} MZN`);
assert.equal(numeric(row('Caixa final projectada')), expected.endingCash);
assert.equal(row('Reconciliação do financiamento'), expected.fundingStatus);
});
+3 -3
View File
@@ -26,8 +26,8 @@ void test('portal home hero exposes a direct public simulator link', () => {
void test('completed simulator result keeps public interest submission independent', () => {
assert.match(simulator, /href="\/manifestar-interesse"/);
assert.match(
simulator,
/Manifestar interesse sem partilhar\s+esta simulação/,
simulator.replace(/\s+/g, ' '),
/Manifestar interesse sem partilhar esta simulação/,
);
assert.match(simulator, /sem\s+partilhar os dados desta simulação/);
assert.match(simulator.replace(/\s+/g, ' '), /sem partilhar os dados desta simulação/);
});