Files
ESBSC-CONVOC/tests/v4.php
2026-11-11 09:24:28 +01:00

93 lines
12 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
require dirname(__DIR__).'/bootstrap.php';
use App\{DB,Sports,Seasons,ClubSettings,ClubRoles,CalendarAlerts,Spond,Regulations,Convocations,ConvocationExport,Oidc,Xlsx,V4Migration};
use Firebase\JWT\JWT;
if(getenv('ESBSC_TEST_DATABASE')!=='1')exit('Base jetable requise');
$count=0;
function verify4(bool $ok,string $label): void {global $count;if(!$ok)throw new RuntimeException($label);echo 'V4 '.(++$count).' '.$label."\n";}
function reject4(callable $f,string $label): void {try{$f();}catch(RuntimeException $e){verify4(true,$label);return;}throw new LogicException('Refus attendu : '.$label);}
$season=Seasons::active();$year=(int)substr($season,0,4);$date=$year.'-10-18';$week=Convocations::week($date);
$settings=ClubSettings::get();$settings['fff_number']='520480';ClubSettings::put($settings);
DB::query("INSERT INTO users(name,email,password_hash,role,must_change_password) VALUES('Admin test','v4-admin@example.test',?,'admin',0)",[password_hash('V4-local-test-password',PASSWORD_DEFAULT)]);$actor=(int)DB::conn()->lastInsertId();
DB::query("INSERT INTO users(name,email,password_hash,role,must_change_password) VALUES('Lecture test','v4-viewer@example.test',?,'viewer',0)",[password_hash('V4-local-test-password',PASSWORD_DEFAULT)]);
$ids=[];foreach([['DUPONT','Alex','player_staff'],['MARTIN','Camille','player'],['DURAND','Morgan','staff']] as [$last,$first,$role])$ids[]=DB::transaction(fn()=>Sports::save('players',Sports::player(['person_number'=>(string)(1100000000+count($ids)),'last_name'=>$last,'first_name'=>$first,'member_role'=>$role]),0,$actor));
[$p1,$p2,$staff]=$ids;
verify4(count(Seasons::decorate(DB::all('SELECT * FROM players')))===3,'Effectif lié à la saison');
$role=(int)DB::value("SELECT id FROM club_roles WHERE kind='sport' LIMIT 1");ClubRoles::assign([$p1],$role,1,'add',$actor);
verify4(in_array('player',ClubRoles::kinds(DB::one('SELECT * FROM players WHERE id=?',[$p1]),ClubRoles::index()[$p1]),true),'Double licence toujours sélectionnable avec staff');
$mid=[];foreach([1,2,3,4] as $i){DB::query("INSERT INTO matches(fff_match_id,team_id,match_date,match_time,opponent,competition,home_away,status,venue) VALUES(?,?,?,'15:00:00',?,'V4 championnat','home','scheduled','')",['V4-'.$i,$i,$date,'Adversaire '.$i]);$mid[]=(int)DB::conn()->lastInsertId();}
$games=DB::all("SELECT m.*,t.short_name FROM matches m JOIN teams t ON t.id=m.team_id WHERE competition='V4 championnat'");$alerts=CalendarAlerts::all($games);
verify4(count($alerts)===1&&count($alerts[$date]['messages'])===7,'Quatre réceptions et six chevauchements détectés');
CalendarAlerts::resolve($date,$alerts[$date]['fingerprint'],'E3 sur le terrain annexe, horaires validés',true,$actor);
verify4(CalendarAlerts::all($games)[$date]['resolved'],'Alerte marquée traitée avec justification');
DB::query("UPDATE matches SET match_time='18:00:00' WHERE id=?",[$mid[0]]);$newGames=DB::all("SELECT m.*,t.short_name FROM matches m JOIN teams t ON t.id=m.team_id WHERE competition='V4 championnat'");
verify4(!CalendarAlerts::all($newGames)[$date]['resolved'],'Changement horaire réactive l’alerte');
$two=array_slice($games,0,2);$two[1]['venue']='Terrain entraînement';verify4(!CalendarAlerts::compute($two,ClubSettings::get()),'Deux terrains distincts sans chevauchement');$two[1]['venue']='';$two[1]['match_time']=null;verify4(count(CalendarAlerts::compute($two,ClubSettings::get())[$date]['messages'])===1,'Heure manquante signalée');
$rows=Spond::parse([['line'=>5,'data'=>['statut'=>'Participe','nom'=>'Alex Dupont','adresse_e_mail'=>'test@example.test','telephone'=>'0612345678','delai_de_reponse'=>$year.'-09-24 13:12:10']],['line'=>6,'data'=>['statut'=>'Sans réponse','nom'=>'Camille Martin']]]);
verify4($rows[0]['status']==='present'&&$rows[1]['status']==='unanswered','Trois états Spond distincts et horodatage conservé');
verify4(Spond::normalizeName('DUPONT Alex')===Spond::normalizeName('Alex Dupont'),'Nom/prénom inversés reconnus');
reject4(fn()=>Spond::parse([['line'=>5,'data'=>['statut'=>'Peut-être','nom'=>'Alex']]]),'État inconnu refusé');
function spondBatch4(array $rows,string $week,int $actor,?int $match=null): int {DB::query('INSERT INTO spond_batches(actor_id,target,week_start,match_id,filename,payload,base_revision) VALUES(?,?,?,?,?,?,?)',[$actor,$match?'match:'.$match:'week:'.$week,$week,$match,'fixture.xlsx',json_encode($rows),DB::revision()]);return (int)DB::conn()->lastInsertId();}
$bid=spondBatch4($rows,$week,$actor);reject4(fn()=>Spond::apply($bid,[$p1,$p1],$actor),'Deux lignes vers la même personne refusées');
Spond::apply($bid,[$p1,$p2],$actor);verify4(Spond::index($week)[$p2]['status']==='unanswered','Sans réponse n’est pas absent');
reject4(fn()=>Spond::apply($bid,[$p1,$p2],$actor),'Aperçu déjà appliqué refusé');
verify4(!str_contains(DB::value('SELECT payload FROM spond_batches WHERE id=?',[$bid]),'test@example.test'),'Coordonnées retirées après import');
$rows[0]['status']='absent';$rows[0]['responded_at']=$year.'-09-25 10:00:00';$bid=spondBatch4($rows,$week,$actor);Spond::apply($bid,[$p1,$p2],$actor);
verify4((int)DB::value('SELECT COUNT(*) FROM spond_responses')===2&&Spond::index($week)[$p1]['status']==='absent','Réimport actualise sans doublonner');
$older=$rows;$older[0]['responded_at']=$year.'-09-23 10:00:00';$bid=spondBatch4($older,$week,$actor);reject4(fn()=>Spond::apply($bid,[$p1,$p2],$actor),'Export avec réponse plus ancienne refusé');
$rows[0]['status']='present';$bid=spondBatch4([$rows[0]],$week,$actor,$mid[0]);Spond::apply($bid,[$p1],$actor);
verify4(Spond::index($week,$mid[0])[$p1]['status']==='conflict','Réponses semaine et match contradictoires visibles');
verify4(Spond::index($week,$mid[1])[$p1]['status']==='absent','Réponse d’un autre match ne fuit pas');
$profile=['confirmed'=>1,'mutation_base'=>4,'mutation_bonus'=>1,'outside_limit'=>2,'max_players'=>14,'ten_active'=>true,'ten_limit'=>2,'higher_threshold'=>7];$r=['mutation'=>'none','higher_total'=>8,'issues'=>[]];
verify4(Regulations::collective([$r,$r],$profile)['status']==='available','Variante +7 : deux joueurs permis');
verify4(Regulations::collective([$r,$r,$r],$profile)['status']==='blocked','Variante +7 : troisième joueur bloqué');
$r['higher_total']=7;verify4(Regulations::collective([$r,$r,$r],$profile)['higher_ten']===0,'Seuil strict : sept ne compte pas comme plus de sept');
$profile['higher_threshold']=10;$r['higher_total']=10;verify4(Regulations::collective([$r],$profile)['higher_ten']===0,'Seuil strict plus de dix');
$r['mutation']='outside';verify4(Regulations::collective([$r,$r,$r],$profile)['status']==='blocked','Quota hors période appliqué à tout le groupe');
// The +7 variant requires both the competition profile and the match justification.
DB::conn()->beginTransaction();
try{
DB::query("INSERT INTO regulation_profiles(team_id,season,competition,confirmed,championship,ten_rule,ten_from,special_higher_enabled,reference) VALUES(4,?,'V4 championnat',1,1,1,?,1,'Fixture réglementaire')",[$season,$year.'-10-01']);
$match=DB::one('SELECT * FROM matches WHERE id=?',[$mid[3]]);
verify4(Regulations::effectiveProfile($match)[0]['higher_threshold']==10,'Profil standard reste à +10');
$match['special_higher_rule']=1;$match['special_higher_reference']='Adversaire et texte vérifiés';
verify4(Regulations::effectiveProfile($match)[0]['higher_threshold']==7,'Variante confirmée active le seuil +7');
$match['special_higher_reference']='';verify4(Regulations::effectiveProfile($match)[0]['higher_threshold']==10,'Sans justificatif : variante non activée');
$match['special_higher_reference']='Vérifié';$match['match_date']=$year.'-09-01';verify4(Regulations::effectiveProfile($match)[0]['higher_threshold']==10,'Variante hors période non activée');
}finally{DB::conn()->rollBack();}
// Known RSA key signed tokens exercise the actual vendored signature validator.
$key=openssl_pkey_new(['private_key_bits'=>2048,'private_key_type'=>OPENSSL_KEYTYPE_RSA]);$pub=openssl_pkey_get_details($key);$b64=fn($s)=>rtrim(strtr(base64_encode($s),'+/','-_'),'=');
$jwks=['keys'=>[['kty'=>'RSA','kid'=>'test-key','alg'=>'RS256','n'=>$b64($pub['rsa']['n']),'e'=>$b64($pub['rsa']['e'])]]];$cfg=['issuer'=>'https://issuer.example.test','client_id'=>'club'];$claims=['iss'=>$cfg['issuer'],'sub'=>'responsable-1','aud'=>'club','iat'=>time(),'exp'=>time()+300,'nonce'=>'test-nonce'];
$jwt=JWT::encode($claims,$key,'RS256','test-key');verify4(Oidc::validateToken($jwt,$jwks,$cfg,'test-nonce')['sub']==='responsable-1','OpenID : signature et claims validés');
foreach(['iss'=>'https://wrong.example.test','aud'=>'autre-client','nonce'=>'autre','exp'=>time()-300,'iat'=>time()+600,'azp'=>'autre'] as $claim=>$value){$bad=JWT::encode(array_replace($claims,[$claim=>$value]),$key,'RS256','test-key');reject4(fn()=>Oidc::validateToken($bad,$jwks,$cfg,'test-nonce'),'OpenID refuse '.$claim);}
$parts=explode('.',$jwt);$parts[2][0]=$parts[2][0]==='A'?'B':'A';reject4(fn()=>Oidc::validateToken(implode('.',$parts),$jwks,$cfg,'test-nonce'),'Signature altérée refusée');
$none=$b64('{"alg":"none"}').'.'.$b64(json_encode($claims)).'.';reject4(fn()=>Oidc::validateToken($none,$jwks,$cfg,'test-nonce'),'Jeton non signé refusé');
$multi=JWT::encode(array_replace($claims,['aud'=>['club','another']]),$key,'RS256','test-key');reject4(fn()=>Oidc::validateToken($multi,$jwks,$cfg,'test-nonce'),'Audience multiple sans azp refusée');
$share=['branding'=>ClubSettings::branding(),'week'=>$week,'groups'=>array_map(fn($i)=>['team'=>'Équipe '.$i,'opponent'=>'Club adverse '.$i,'when'=>'18/10/'.$year.' · 15:00','side'=>$i%2?'home':'away','players'=>['DUPONT Alex','MARTIN Camille'],'staff'=>[]],[1,2,3,4]),'include_staff'=>false,'legend'=>false];
$share['branding']['short_name']='CLUB TEST';$share['branding']['primary']='#244e35';
file_put_contents(sys_get_temp_dir().'/v4-share.json',json_encode($share));file_put_contents(sys_get_temp_dir().'/v4-convocations.pdf',ConvocationExport::pdf($share));file_put_contents(sys_get_temp_dir().'/v4-convocations.xlsx',ConvocationExport::xlsx($share));
verify4(str_starts_with(ConvocationExport::pdf($share),'%PDF'),'PDF personnalisé produit');
verify4(ClubSettings::contrast('#ffffff')==='#111111'&&ClubSettings::contrast('#000000')==='#ffffff','Contraste des couleurs personnalisé');
$before=DB::value('SELECT COUNT(*) FROM players');V4Migration::migrate();verify4(DB::value('SELECT COUNT(*) FROM players')===$before,'Migration V4 répétée sans perte');
// Opening a season preserves discipline, calendars, roles and past membership.
DB::query("INSERT INTO sanctions(player_id,sanction_type,status,effective_date,matches_required,label) VALUES(?,'commission','official',?,4,'Test report intersaison')",[$p1,$year.'-06-20']);
DB::query("INSERT INTO data_checks(scope,checked_at,note) VALUES('players',NOW(),'Test saison') ON DUPLICATE KEY UPDATE note=VALUES(note)");
$next=($year+1).'/'.($year+2);Seasons::create($next,false,$actor);
verify4(count(Seasons::decorate(DB::all('SELECT * FROM players')))===0,'Nouvelle saison vide sans supprimer les personnes');
verify4((int)DB::value('SELECT COUNT(*) FROM matches')===4&&(int)DB::value('SELECT COUNT(*) FROM sanctions')===1,'Calendriers et sanctions conservés');
verify4(count(Seasons::decorate(DB::all('SELECT * FROM players'),$season))===3,'Effectif précédent conservé');
verify4((int)DB::value('SELECT COUNT(*) FROM season_data_checks WHERE season=?',[$season])===1,'Anciennes validations conservées');
Seasons::select($season);reject4(fn()=>Seasons::assertWritable(),'Archive en lecture seule');
verify4(count(ClubRoles::index())===1,'Staff archivé consultable');
Seasons::select($next);
DB::query('UPDATE players SET active=0,usual_team_id=2 WHERE id=?',[$p1]);
$import=App\People::preview(['line'=>1,'data'=>['numero_personne'=>'1100000000','numero_licence'=>'999000123','type_licence'=>'Libre','nom'=>'DUPONT','prenom'=>'Alex']],$next);
verify4($import['data']['active']===1&&$import['data']['usual_team_id']===null,'Réimport nouvelle saison : actif, sans ancienne affectation');
DB::transaction(fn()=>App\People::apply($import,$actor));
verify4(count(Seasons::decorate(DB::all('SELECT * FROM players')))===1,'Réimport retrouve la même personne et crée sa présence saisonnière');
verify4(count(Seasons::decorate(DB::all('SELECT * FROM players'),$season))===3,'Réimport laisse l’ancien effectif intact');
// Return to initial active season only in this disposable fixture, for the HTTP checks.
$s=ClubSettings::get();$s['active_season']=$season;ClubSettings::put($s);Seasons::select($season);
file_put_contents(sys_get_temp_dir().'/v4-fixture.json',json_encode(compact('ids','mid','season','date','week','actor')));
echo "V4 OK : $count assertions\n";