Files
2026-11-11 09:24:28 +01:00

59 lines
6.8 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
// Run ONLY against a disposable empty migrated database.
declare(strict_types=1);
require dirname(__DIR__).'/bootstrap.php';
use App\{DB,Csv,Sports,Eligibility,Reports};
if(getenv('ESBSC_TEST_DATABASE')!=='1')exit("Set ESBSC_TEST_DATABASE=1 with a disposable database.\n");
if(DB::value('SELECT COUNT(*) FROM players'))exit("Requires an empty player registry.\n");
$n=0;function check(bool $v,string $label): void {global $n;$n++;if(!$v)throw new RuntimeException($label);echo "OK $n - $label\n";}
DB::query("INSERT INTO users(name,email,password_hash,role,must_change_password) VALUES('Test','admin@example.test',?,'admin',0)",[password_hash('Testing-only-123!',PASSWORD_DEFAULT)]);$actor=(int)DB::conn()->lastInsertId();
function batch(string $kind,string $raw,int $team,int $actor): int {
$rows=Csv::preview($kind,$team,$raw);DB::query('INSERT INTO import_batches(actor_id,kind,team_id,filename,fingerprint,payload,base_revision) VALUES(?,?,?,?,?,?,?)',[$actor,$kind,$team?:null,'test.csv',hash('sha256',$kind.$team.$raw),json_encode($rows),DB::revision()]);return (int)DB::conn()->lastInsertId();
}
$raw="licence;nom;prenom;categorie;equipe;actif\n00123;AMIL;Riyad;Senior;E1;oui\n00456;AMIL;Riyad;Senior;E3;oui\n";
$b=batch('players',$raw,0,$actor);Csv::apply($b,$actor);
check((int)DB::value('SELECT COUNT(*) FROM players')===2,'Deux homonymes gardent deux licences distinctes');
Csv::apply(batch('players',$raw,0,$actor),$actor);check((int)DB::value('SELECT COUNT(*) FROM players')===2,'Réimport sans doublon');
$bad=$raw."00789;DUPONT;Éric;Senior;E9;oui\n";$b=batch('players',$bad,0,$actor);
try{Csv::apply($b,$actor);check(false,'Import doit échouer');}catch(RuntimeException $e){check((int)DB::value('SELECT COUNT(*) FROM players')===2,'Import en erreur atomique');}
$cal="numero match;date;adversaire;statut\nMATCH1;31/05/2026;Club test;joue\n";
Csv::apply(batch('calendar',$cal,3,$actor),$actor);Csv::apply(batch('calendar',$cal,1,$actor),$actor);
check((int)DB::value('SELECT COUNT(*) FROM matches')===2,'Même fichier importable pour deux équipes');
$pid=(int)DB::value("SELECT id FROM players WHERE licence_number='00123'");
$disc="licence;reference;date effet;nb matchs;motif\n00123;D1;25/05/2026;1;Sanction test\n";
Csv::apply(batch('discipline',$disc,0,$actor),$actor);Csv::apply(batch('discipline',$disc,0,$actor),$actor);
check((int)DB::value('SELECT COUNT(*) FROM sanctions')===1,'Décisions réimportées sans doublon');
$bad=Csv::preview('discipline',0,str_replace(';1;',';2 mois;',$disc));check($bad[0]['action']==='error','Texte de durée non converti en nombre de matchs');
$bad=Csv::preview('discipline',0,str_replace('00123','99999',$disc));check($bad[0]['action']==='error','Licence inconnue bloquée à l’import disciplinaire');
$b=batch('players',$raw,0,$actor);DB::touch();try{Csv::apply($b,$actor);check(false,'Aperçu périmé');}catch(RuntimeException $e){check(true,'Aperçu périmé refusé');}
$p=DB::one('SELECT * FROM players WHERE id=?',[$pid]);
$unchecked=Eligibility::check($p,3,'2026-06-07');
check($unchecked['status']==='available' && count($unchecked['data_warnings'])===3,'Fraîcheur non attestée signalée séparément');
foreach(['players','discipline','calendar:3'] as $scope)DB::query('INSERT INTO data_checks(scope,checked_at,note) VALUES(?,NOW(),?)',[$scope,'Test']);
check(Eligibility::check($p,3,'2026-06-07')['status']==='available','Disponible quand données vérifiées et purge effectuée');
$prov=DB::transaction(fn()=>Sports::save('sanctions',['player_id'=>$pid,'status'=>'provisional','sanction_type'=>'red_provisional','effective_date'=>'2026-06-10','exclusion_date'=>'2026-06-10','matches_required'=>1,'label'=>'Exclusion'],0,$actor));
$d=Sports::sanction(['player_id'=>$pid,'effective_date'=>'2026-06-15','matches_required'=>2,'purge_from'=>'2026-06-10','label'=>'Décision rouge','external_ref'=>'D2']);
$new=DB::transaction(fn()=>Sports::saveSanction($d,0,$actor,'Commission',$prov));
check(DB::value('SELECT status FROM sanctions WHERE id=?',[$prov])==='revoked','Provisoire remplacée et historisée');
check(DB::value('SELECT exclusion_date FROM sanctions WHERE id=?',[$new])==='2026-06-10','Exclusion conservée au rapprochement');
$report=DB::transaction(fn()=>Reports::build('2026-05-31','2026-05-31'));
check(count($report['groups'])===2,'Rapport multiéquipes');
$target=(int)DB::value("SELECT id FROM matches WHERE fff_match_id='MATCH1' AND team_id=3");
DB::query("INSERT INTO disciplinary_events(player_id,team_id,event_date,event_type,warning_effective_date,warning_end_date) VALUES(?,3,'2026-04-01','yellow','2026-04-01','2026-07-01'),(?,3,'2026-05-01','yellow','2026-05-01','2026-08-01')",[$pid,$pid]);
$risk=Reports::build('2026-05-31','2026-05-31',$target);
check(!in_array('yellow_risk',$risk['groups'][0]['rows'][0]['flags']??[],true),'Jaunes manuels non confirmés exclus du risque officiel');
DB::query("UPDATE disciplinary_events SET review_status='confirmed' WHERE player_id=? AND event_type='yellow'",[$pid]);
$risk=Reports::build('2026-05-31','2026-05-31',$target);
check(in_array('yellow_risk',$risk['groups'][0]['rows'][0]['flags']??[],true),'Deux jaunes actifs signalent le risque au prochain avertissement');
for($i=1;$i<=11;$i++){
$ref='SUPERIEUR-'.$i;$date=sprintf('2026-03-%02d',$i);DB::query("INSERT INTO matches(fff_match_id,team_id,competition,match_date,status,counts_for_purge,is_official) VALUES(?,1,'Championnat R2',?,'played',1,1)",[$ref,$date]);$matchId=(int)DB::conn()->lastInsertId();
DB::query("INSERT INTO fmi_uploads(actor_id,match_id,filename,file_key,file_hash,payload,base_revision,status) VALUES(?,?,'test.pdf',?,?, '{}',0,'applied')",[$actor,$matchId,str_pad((string)$i,32,'0',STR_PAD_LEFT),str_pad((string)$i,64,'0',STR_PAD_LEFT)]);$upload=(int)DB::conn()->lastInsertId();
DB::query('INSERT INTO match_participations(match_id,player_id,upload_id,shirt_number,starter,participated) VALUES(?,?,?,?,1,1)',[$matchId,$pid,$upload,$i]);
}
$ten=Reports::build('2026-05-31','2026-05-31',$target,true);$tenRow=current(array_filter($ten['groups'][0]['rows'],fn($row)=>(int)$row['player']['id']===$pid));
check(($tenRow['higher_team_matches']['total']??0)===11&&in_array('higher_ten',$tenRow['flags']??[],true),'+10 calcule les matchs de championnat en équipes supérieures');
DB::query("DELETE mp FROM match_participations mp JOIN matches m ON m.id=mp.match_id WHERE m.fff_match_id LIKE 'SUPERIEUR-%'");DB::query("DELETE u FROM fmi_uploads u JOIN matches m ON m.id=u.match_id WHERE m.fff_match_id LIKE 'SUPERIEUR-%'");DB::query("DELETE FROM matches WHERE fff_match_id LIKE 'SUPERIEUR-%'");
$id=Reports::save($report,$actor,null);DB::touch();check((int)DB::value('SELECT revision FROM reports WHERE id=?',[$id])!==DB::revision(),'Rapport détectable comme périmé');
file_put_contents(dirname(__DIR__).'/storage/test-report.pdf',Reports::pdf($report));
echo "$n tests d’intégration réussis.\n";