Initial clean version

This commit is contained in:
root
2026-11-11 09:24:28 +01:00
commit ab58b33f9c
156 changed files with 5697 additions and 0 deletions
+36
View File
@@ -0,0 +1,36 @@
<?php
require dirname(__DIR__).'/bootstrap.php';
use App\{Cachets,Regulations};
$n=0;function check($v,$m){global $n;if(!$v)throw new RuntimeException($m);echo 'OK '.(++$n).' '.$m."\n";}
function reject($fn,$label){try{$fn();}catch(RuntimeException $e){check(true,$label);return;}throw new RuntimeException($label);}
$blank=['cachet_code'=>'','cachet_libelle'=>'','cachet_date_de_debut'=>'','cachet_date_de_fin'=>''];
$mn=['cachet_code'=>'MN','cachet_libelle'=>'MUTATION','cachet_date_de_debut'=>'01/07/2026','cachet_date_de_fin'=>'14/10/2026'];
$mh=array_replace($mn,['cachet_code'=>'MH','cachet_libelle'=>'MUTATION HORS PERIODE']);
check(Cachets::parse(['nature_changement_de_club'=>'Mutée'])===null,'Colonne administrative seule ne renseigne rien');
check(Cachets::parse($blank+['nature_changement_de_club'=>'Mutée'])===[],'Mutée sans cachet : aucun muté');
$s=Cachets::parse($mn+['nature_changement_de_club'=>'Non mutée']);
check(Cachets::at($s,'2026-06-30')['mutation']==='none','Avant le début');
check(Cachets::at($s,'2026-07-01')['mutation']==='normal','Début inclus');
check(Cachets::at($s,'2026-10-14')['mutation']==='normal','Fin incluse');
check(Cachets::at($s,'2026-10-15')['mutation']==='none','Fin de cachet sans réimport');
check(Cachets::at(Cachets::parse($mh),'2026-09-26')['mutation']==='outside','MH hors période');
$multi=[];foreach($mn as $k=>$v)$multi[$k.'_1']=$v;foreach($mh as $k=>$v)$multi[$k.'_2']=$v;
check(count(Cachets::parse($multi))===2,'Colonnes de cachets multiples');
check(Cachets::at(Cachets::parse($multi),'2026-09-26')['mutation']==='outside','MN et MH : un seul joueur hors période');
$unknown=array_replace($mn,['cachet_code'=>'XX','cachet_libelle'=>'Autre restriction']);
check(Cachets::at(Cachets::parse($unknown),'2026-09-26')['mutation']==='unknown','Cachet inconnu signalé');
reject(fn()=>Cachets::parse(['cachet_code'=>'']), 'Colonnes partielles refusées');
reject(fn()=>Cachets::parse(array_replace($mn,['cachet_libelle'=>'MUTATION HORS PERIODE'])),'Code et libellé contradictoires refusés');
reject(fn()=>Cachets::parse(array_replace($mn,['cachet_date_de_fin'=>''])),'Fin manquante refusée');
reject(fn()=>Cachets::parse(array_replace($mn,['cachet_date_de_fin'=>'31/02/2026'])),'Date impossible refusée');
reject(fn()=>Cachets::parse(array_replace($mn,['cachet_date_de_fin'=>'01/06/2026'])),'Dates inversées refusées');
$identity=['numero_personne'=>'123','numero_licence'=>'456','nom'=>'TEST','prenom'=>'A','type_licence'=>'Libre'];
$rows=Cachets::groupRows([['line'=>2,'data'=>$identity+$mn],['line'=>3,'data'=>$identity+$mn],['line'=>4,'data'=>$identity+$mh]]);
check(count($rows)===1 && count(Cachets::fromRow($rows[0]))===2,'Lignes multiples regroupées et dédoublonnées');
$bad=Cachets::groupRows([['line'=>2,'data'=>$identity+$mn],['line'=>3,'data'=>array_replace($identity,['numero_personne'=>'999'])+$mh]]);
reject(fn()=>Cachets::fromRow($bad[0]),'Personnes différentes pour la même licence refusées');
$l=['season'=>'2026/2027','licence_type'=>'Libre','licence_status'=>'active','qualified_on'=>'2026-07-01','category_ok'=>'yes','mutation'=>'exempt','imported_cachets'=>$s];
$r=Regulations::individual(['active'=>1],['match_date'=>'2026-09-26'],[$l],['status'=>'available','warnings'=>[]]);
check($r['mutation']==='normal','Cachet importé prioritaire sur exemption manuelle ancienne');
$l['season']='2025/2026';check(Regulations::individual(['active'=>1],['match_date'=>'2026-09-26'],[$l],['status'=>'available','warnings'=>[]])['mutation']==='unknown','Pas de cachet de la saison précédente');
echo "$n tests cachets réussis.\n";
+32
View File
@@ -0,0 +1,32 @@
<?php
require dirname(__DIR__).'/bootstrap.php';
use App\{DB,Csv,Xlsx,Cachets,Regulations};
if(getenv('ESBSC_TEST_DATABASE')!=='1'||empty($argv[1]))exit('Base jetable et export complet requis');
$n=0;function check($v,$m){global $n;if(!$v)throw new RuntimeException($m);echo 'Cachets SQL '.(++$n).' '.$m."\n";}
$actor=(int)DB::value('SELECT id FROM users LIMIT 1');$raw=Xlsx::read($argv[1])['rows'];
$preview=fn($rows,$season='2026/2027')=>Csv::previewRows('players',0,$rows,false,$season);
$apply=function($rows)use($actor){DB::query('INSERT INTO import_batches(actor_id,kind,filename,fingerprint,payload,base_revision) VALUES(?,?,?,?,?,?)',[$actor,'players','44171420d.xlsx',hash('sha256',json_encode($rows)),json_encode($rows),DB::revision()]);return Csv::apply((int)DB::conn()->lastInsertId(),$actor);};
$rows=$preview($raw);foreach($rows as $r)if($r['error'])throw new RuntimeException($r['error']);check(count($rows)===75,'75 licences reconnues');
$before=DB::all('SELECT * FROM sanctions ORDER BY id');$apply($rows);check($before===DB::all('SELECT * FROM sanctions ORDER BY id'),'Sanctions intactes');
$numbers=array_map(fn($r)=>$r['data']['numero_licence'],$raw);$marks=implode(',',array_fill(0,count($numbers),'?'));
$licences=Cachets::decorate(DB::all("SELECT l.* FROM person_licences l JOIN licence_cachets c ON c.licence_id=l.id WHERE l.season='2026/2027' AND l.licence_number IN ($marks)",$numbers));
$counts=['none'=>0,'normal'=>0,'outside'=>0];foreach($licences as $l)$counts[Cachets::at($l['imported_cachets'],'2026-09-26')['mutation']]++;
check($counts===['none'=>65,'normal'=>9,'outside'=>1],'65 sans cachet, 9 MN, 1 MH : '.json_encode($counts));
$counts=['none'=>0,'normal'=>0,'outside'=>0];foreach($licences as $l)$counts[Cachets::at($l['imported_cachets'],'2026-10-15')['mutation']]++;
check($counts===['none'=>66,'normal'=>8,'outside'=>1],'Expiration du 14 octobre respectée');
$again=$preview($raw);check(count(array_filter($again,fn($r)=>$r['action']==='unchanged'))===75,'Réimport identique sans doublon');$rev=DB::revision();$apply($again);check(DB::revision()===$rev,'Réimport identique ne périme pas les contrôles');
$stamped=current(array_filter($raw,fn($r)=>$r['data']['cachet_code']==='MN'));$pn=$stamped['data']['numero_personne'];$ln=$stamped['data']['numero_licence'];
$lid=(int)DB::value('SELECT id FROM person_licences WHERE season=? AND licence_number=?',['2026/2027',$ln]);$saved=DB::one('SELECT * FROM licence_cachets WHERE licence_id=?',[$lid]);
$legacy=$stamped;foreach(array_keys($legacy['data']) as $k)if(str_starts_with($k,'cachet_'))unset($legacy['data'][$k]);$apply($preview([$legacy]));check(DB::one('SELECT * FROM licence_cachets WHERE licence_id=?',[$lid])===$saved,'Ancien export sans colonnes nefface rien');
$without=$stamped;foreach(array_keys($without['data']) as $k)if(str_starts_with($k,'cachet_'))$without['data'][$k]='';$without['data']['nature_changement_de_club']='Mutée';
$apply($preview([$without]));check(DB::value('SELECT payload FROM licence_cachets WHERE licence_id=?',[$lid])==='[]','Export complet sans cachet remplace ancien cachet malgré Mutée');
$apply($preview([$stamped]));
$before=DB::all('SELECT * FROM licence_cachets ORDER BY licence_id');$bad=$stamped;$bad['data']['cachet_date_de_fin']='31/02/2026';$errors=$preview([$without,$bad]);
try{$apply($errors);throw new LogicException('Expected refusal');}catch(RuntimeException $e){check(DB::all('SELECT * FROM licence_cachets ORDER BY licence_id')===$before,'Erreur de date : lot entier refusé');}
$old=$without;$apply($preview([$old],'2025/2026'));check(DB::value('SELECT payload FROM licence_cachets WHERE licence_id=?',[$lid])===$saved['payload'],'Autre saison ne modifie pas le cachet courant');
$a=$stamped;$b=$stamped;$b['data']['cachet_code']='MH';$b['data']['cachet_libelle']='MUTATION HORS PERIODE';$both=$preview([$a,$a,$b]);check(count($both)===1 && count($both[0]['cachets'])===2,'Plusieurs lignes de cachets regroupées');$apply($both);
$one=Cachets::decorate(DB::all('SELECT * FROM person_licences WHERE id=?',[$lid]))[0];check(Cachets::at($one['imported_cachets'],'2026-09-26')['mutation']==='outside','Pas de double comptage MN + MH');
$apply($preview([$stamped]));
$revision=DB::revision();Cachets::migrate();check(DB::revision()===$revision,'Migration cachets relançable');
check((int)DB::value("SELECT COUNT(*) FROM audit_log WHERE action='cachets_import'")>=75,'Historique des modifications conservé');
echo "$n tests SQL cachets réussis.\n";
+21
View File
@@ -0,0 +1,21 @@
<?php
require dirname(__DIR__).'/bootstrap.php';
use App\{DB,Csv,CalendarAlerts,ClubSettings};
if(getenv('ESBSC_TEST_DATABASE')!=='1')exit('Base jetable requise');
function checkVenue(bool $ok,string $message):void{if(!$ok)throw new RuntimeException($message);echo "OK $message\n";}
DB::query("INSERT INTO users(name,email,password_hash,role) VALUES('Test','terrain@example.test','disabled','admin')");$actor=(int)DB::conn()->lastInsertId();
function importVenue(array $r,int $actor):array {
$rows=Csv::previewRows('calendar',1,[['line'=>2,'data'=>$r]]);
if($rows[0]['error'])throw new RuntimeException($rows[0]['error']);
DB::query("INSERT INTO import_batches(actor_id,kind,team_id,filename,fingerprint,payload,base_revision) VALUES(?,'calendar',1,'fixture-terrain.xlsx',?,?,?)",[$actor,hash('sha256',json_encode($r)),json_encode($rows),DB::revision()]);
Csv::apply((int)DB::conn()->lastInsertId(),$actor);
return DB::one('SELECT * FROM matches WHERE fff_match_id=? AND team_id=1',[$r['numero_match']]);
}
$r=['numero_match'=>'TEST-VENUE','equipe_locale_1'=>'BEAUMONT ST CYR ES 1','equipe_adverse_1'=>'ADVERSAIRE 1','recevant_visiteur_1'=>'Recevant','date_du_match_1'=>'2026-10-04','heure_du_match_1'=>'13H00','nom_de_l_installation_1'=>" STADE MICHEL BREMAUD 1\u{00A0}&#x20;"];
$m=importVenue($r,$actor);checkVenue($m['venue']==='STADE MICHEL BREMAUD 1','Nom Footclubs nettoyé et enregistré');
$id=$m['id'];$r['nom_de_l_installation_1']='STADE MICHEL BREMAUD 2';$m=importVenue($r,$actor);checkVenue($m['id']===$id&&$m['venue']==='STADE MICHEL BREMAUD 2','Réimport actualise le terrain sans doublon');
$r['nom_de_l_installation_1']='';$m=importVenue($r,$actor);checkVenue($m['venue']==='STADE MICHEL BREMAUD 2','Export sans terrain conserve l’affectation');
$m['short_name']='E1';$b=array_replace($m,['id'=>999,'short_name'=>'E4','venue'=>'STADE MICHEL BREMAUD 1']);$s=ClubSettings::DEFAULTS;
checkVenue(!CalendarAlerts::compute([$m,$b],$s),'Deux installations distinctes au même horaire acceptées');
$m['venue']='';checkVenue((bool)CalendarAlerts::compute([$m,$b],$s),'Terrain par défaut identique reconnu malgré les espaces');
$b['match_time']='15:00:00';checkVenue(!CalendarAlerts::compute([$m,$b],$s),'13 h et 15 h sur le terrain 1 acceptés');
+20
View File
@@ -0,0 +1,20 @@
// Node is required only for this development test, never on the production server.
const fs=require('node:fs'),vm=require('node:vm'),assert=require('node:assert/strict');
class Element{
constructor(){this.textContent='';this.children=[];this.attributes={};this.dataset={};}
replaceChildren(){this.children=[];}appendChild(e){this.children.push(e);}setAttribute(k,v){this.attributes[k]=v;}
}
const ids=['convocation-data','convocation-form','selection-count','mutation-count','outside-count','ten-count','selected-list','selection-alerts','availability-alerts','group-status','suspension-count','qualification-count'];
const nodes=Object.fromEntries(ids.map(id=>[id,new Element()]));
nodes['convocation-data'].textContent=JSON.stringify({profile:{confirmed:1,mutation_base:4,mutation_bonus:1,outside_limit:2,max_players:14,ten_active:false},players:{1:{name:'Joueur A',mutation:'outside',higher_total:11,status:'available',issues:[],availability:{status:'injured'},badges:[{kind:'mh',label:'MH',detail:'Hors période'}]},2:{name:'Joueur B',mutation:'outside',higher_total:2,status:'available',issues:[]},3:{name:'Joueur C',mutation:'outside',higher_total:0,status:'review',issues:[{message:'Qualification inconnue'}]}}});
let chosen=['1'],onChange;const events={};
nodes['convocation-form'].querySelectorAll=q=>q==='[data-favorite]'?[]:chosen.map(value=>({value}));
nodes['convocation-form'].querySelector=()=>({dispatchEvent(){}});
nodes['convocation-form'].addEventListener=(event,cb)=>{onChange=cb;};
vm.runInNewContext(fs.readFileSync(__dirname+'/../public/assets/convocation.js','utf8'),{Event:class{},document:{getElementById:id=>nodes[id],createElement:()=>new Element(),createTextNode:text=>({textContent:text}),addEventListener:(key,fn)=>{events[key]=fn;}}});
assert.match(nodes['mutation-count'].textContent,/1 \/ 5/);assert.equal(nodes['selected-list'].children.length,1);
assert.match(nodes['group-status'].textContent,/conforme/);assert.match(nodes['availability-alerts'].children[0].textContent,/Blessé/);
assert.equal(nodes['selected-list'].children[0].children[0].textContent,'MH');
events['availability-saved']({detail:{id:1,availability:{status:'available'}}});assert.equal(nodes['availability-alerts'].children.length,0);assert.equal(nodes['selected-list'].children.length,1);
chosen=['1','2','3'];onChange();assert.match(nodes['outside-count'].textContent,/3 \/ 2/);assert.equal(nodes['selected-list'].children.length,3);assert(nodes['selection-alerts'].children.some(n=>n.textContent==='Un quota est dépassé.'));assert(nodes['selection-alerts'].children.some(n=>n.textContent.includes('Qualification inconnue')));assert.match(nodes['group-status'].textContent,/bloqué/);
chosen=[];onChange();assert.equal(nodes['selected-list'].children.length,0);console.log('Compteurs, badges, disponibilités non bloquantes et sélection conservée : OK (DOM simulé).');
+27
View File
@@ -0,0 +1,27 @@
<?php
// Isolated rendering regression: real template and Spond code, database rows supplied by fixture.
namespace App {
final class DB {
public static array $rows=[];
public static function all(string $sql,array $args=[]):array {
if($args!==['2026-09-28'])throw new \RuntimeException('Semaine incorrecte');
return self::$rows;
}
}
}
namespace {
require dirname(__DIR__).'/bootstrap.php';
set_error_handler(function($n,$s,$f,$l){throw new ErrorException($s,0,$n,$f,$l);});
$id=1;$week='2026-09-28';
$summary=['week'=>$week,'end'=>'2026-10-04','groups'=>[],'missing'=>[['id'=>$id,'last_name'=>'TEST','first_name'=>'Spond','discipline'=>[]]],'availability'=>[]];
function renderConvocations(array $summary,?array $provided=null):string{
$_SESSION['csrf']='test-token';$user=['role'=>'viewer'];if($provided!==null)$spond=$provided;
ob_start();try{require dirname(__DIR__).'/templates/convocations.php';return ob_get_contents();}finally{ob_end_clean();}
}
if(!str_contains(renderConvocations($summary),'Spond : Non renseigné'))throw new RuntimeException('Sans import');
\App\DB::$rows=[['player_id'=>1,'match_id'=>null,'status'=>'present','responded_at'=>null,'imported_at'=>'2026-10-02 14:00:00']];
if(!str_contains(renderConvocations($summary),'Spond : Présent'))throw new RuntimeException('Disponibilité non chargée');
$given=[$id=>['status'=>'absent','answers'=>[]]];
if(!str_contains(renderConvocations($summary,$given),'Spond : Absent'))throw new RuntimeException('Contexte fourni non conservé');
echo "OK : variable absente sans import, avec réponse, et contexte fourni. Aucun avertissement PHP.\n";
}
+43
View File
@@ -0,0 +1,43 @@
<?php
require dirname(__DIR__).'/bootstrap.php';
use App\{DB,ParticipationRules as Rules,Regulations,LicenceImport};
if(getenv('ESBSC_TEST_DATABASE')!=='1')exit('Base jetable requise');
$n=0;function checkFinal($v,$m){global $n;if(!$v)throw new RuntimeException($m);echo 'Final '.(++$n).' '.$m."\n";}
DB::conn()->beginTransaction();
try{
DB::query("UPDATE matches SET status='cancelled'");
$p=DB::one("SELECT * FROM players WHERE person_number='V3-TEST'");$pid=$p['id'];$actor=DB::value('SELECT id FROM users LIMIT 1');
$lic=['season'=>'2026/2027','licence_type'=>'Libre','licence_status'=>'active','qualified_on'=>'2026-09-27','category_ok'=>'unknown','mutation'=>'none','imported_facts'=>['birth_date'=>'2004-07-01']];
$disc=['status'=>'available','warnings'=>[]];
checkFinal(Regulations::individual($p,['match_date'=>'2026-09-26'],[$lic],$disc)['status']==='blocked','Samedi avant qualification bloqué');
checkFinal(Regulations::individual($p,['match_date'=>'2026-09-27'],[$lic],$disc)['status']==='available','Dimanche qualifié, pas de contrôle senior répétitif');
$profile=['confirmed'=>1,'championship'=>1,'calendar_complete'=>0,'u23_rule'=>1,'higher_rule'=>1,'ten_rule'=>1,'ten_from'=>'2027-05-01'];
$m=['id'=>999999,'team_id'=>2,'competition'=>'Final D2','match_date'=>'2026-09-27','is_official'=>1];$period=Rules::period($m,$profile);
DB::query("INSERT INTO regulation_profiles(team_id,season,competition,confirmed,championship,reference) VALUES(1,'2026/2027','Final R3',1,1,'Test')");
DB::query("INSERT INTO matches(team_id,competition,match_date,status,is_official) VALUES(1,'Final R3','2026-09-26','played',1)");$source=DB::one('SELECT * FROM matches WHERE id=?',[DB::conn()->lastInsertId()]);
$mp=['starter'=>0,'entry_period'=>'second','goalkeeper'=>0];
checkFinal(Rules::exception($m,$source,$mp,$profile,$lic,$period)[0]===true,'Exception le lendemain');
$m['match_date']='2026-10-04';checkFinal(Rules::exception($m,$source,$mp,$profile,$lic,$period)[0]===true,'Exception conservée une semaine après');
$other=$m;$other['team_id']=3;checkFinal(Rules::exception($other,$source,$mp,$profile,$lic,$period)[0]===false,'Pas exception équipe 3');
$cup=$profile;$cup['championship']=0;checkFinal(Rules::exception($m,$source,$mp,$cup,$lic,$period)[0]===false,'Pas exception coupe réserve');
checkFinal(Rules::exception($m,$source,array_replace($mp,['entry_period'=>'first']),$profile,$lic,$period)[0]===false,'Entrée première période exclue');
checkFinal(Rules::exception($m,$source,array_replace($mp,['entry_period'=>'unknown']),$profile,$lic,$period)[0]===null,'Période manquante : demande ciblée');
$old=$lic;$old['imported_facts']['birth_date']='2003-07-01';checkFinal(Rules::exception($m,$source,$mp,$profile,$old,$period)[0]===false,'Exactement 23 ans au premier juillet exclu');
checkFinal(Rules::exception($m,$source,array_replace($mp,['goalkeeper'=>1]),$profile,$old,$period)[0]===true,'Gardien sans limite âge');
checkFinal(Rules::exception($m,$source,$mp,$profile,$lic,['from'=>'2027-05-01','active'=>true])[0]===false,'Exception arrêtée dans les cinq dernières rencontres');
$upload=DB::value('SELECT id FROM fmi_uploads LIMIT 1');DB::query('INSERT INTO match_participations(match_id,player_id,upload_id,shirt_number,starter,participated,entry_period,goalkeeper) VALUES(?,?,?,12,0,1,?,0)',[$source['id'],$pid,$upload,'second']);
$r=Rules::checks($p,$m,$profile,$lic,$period);checkFinal(!$r['issues']&&count($r['notes'])===1,'Descente autorisée sans alerte générale');
DB::query("INSERT INTO matches(team_id,competition,match_date,status,is_official) VALUES(2,'Final D2','2026-09-27','played',1)");$reserve=DB::conn()->lastInsertId();DB::query('INSERT INTO match_participations(match_id,player_id,upload_id,shirt_number,starter,participated) VALUES(?,?,?,12,1,1)',[$reserve,$pid,$upload]);
checkFinal(!Rules::checks($p,$m,$profile,$lic,$period)['issues'],'A joué en réserve dimanche : exception conservée semaine suivante');
DB::query("INSERT INTO matches(team_id,competition,match_date,status,is_official) VALUES(1,'Final R3','2026-10-01','played',1)");$new=DB::conn()->lastInsertId();DB::query("INSERT INTO match_participations(match_id,player_id,upload_id,shirt_number,starter,participated,entry_period) VALUES(?,?,?,12,0,1,'first')",[$new,$pid,$upload]);
checkFinal(in_array('blocked',array_column(Rules::checks($p,$m,$profile,$lic,$period)['issues'],'level')),'Nouvelle participation E1 première période retire exception');
DB::query('DELETE FROM match_participations WHERE match_id=?',[$new]);
checkFinal(in_array('review',array_column(Rules::checks($p,$m,$profile,$lic,$period)['issues'],'level')),'Dernière FMI absente ne réutilise pas ancienne exception');
$auto=$profile;$auto['calendar_complete']=1;$auto['ten_from']=null;
for($i=1;$i<=6;$i++)DB::query("INSERT INTO matches(team_id,competition,match_date,status,is_official) VALUES(2,'Final D2',?,'scheduled',1)",['2027-05-0'.$i]);
$m['match_date']='2027-05-01';$computed=Rules::period($m,$auto);checkFinal($computed['from']==='2027-05-02'&&!$computed['active'],'Cinq dernières rencontres calculées sur calendrier complet');
$m['match_date']='2027-05-02';checkFinal(Rules::period($m,$auto)['active'],'Début période inclus');
DB::query("UPDATE matches SET match_date='2027-05-10' WHERE team_id=2 AND competition='Final D2' AND match_date='2027-05-01'");checkFinal(Rules::period($m,$auto)['from']==='2027-05-03','Report reprogrammé recalcule période');
DB::query("UPDATE matches SET status='postponed' WHERE team_id=2 AND competition='Final D2' AND match_date='2027-05-10'");checkFinal(Rules::period($m,$auto)['warning']!==null,'Report non daté déclenche alerte ciblée');
}finally{DB::conn()->rollBack();}
echo "$n tests V3 finale réussis.\n";
+10
View File
@@ -0,0 +1,10 @@
<?php
require dirname(__DIR__).'/bootstrap.php';
if(empty($argv[1]))exit("Usage : php tests/fmi.php CHEMIN_FMI_EXEMPLE.pdf\n");
$f=App\Fmi::parse($argv[1]);
if($f['fff_match_id']!=='79131186'||$f['team']!=='E1'||count($f['entries'])!==16)throw new RuntimeException('Composition incorrecte pour la FMI exemple');
if(count(array_filter($f['entries'],fn($r)=>$r['suggested']==='1'))!==15)throw new RuntimeException('Participants incorrects');
if(count(array_filter($f['entries'],fn($r)=>$r['starter']))!==11)throw new RuntimeException('Titulaires incorrects');
$byPerson=array_column($f['entries'],null,'person_number');
if($byPerson['2543123335']['suggested']!=='0')throw new RuntimeException('Remplaçant non entré incorrectement compté');
echo "FMI exemple : 16 inscrits, 11 titulaires, 4 entrées, 1 non-participant.\n";
+41
View File
@@ -0,0 +1,41 @@
<?php
require dirname(__DIR__).'/bootstrap.php';
use App\{Csv,FootclubsDiscipline as F,Xlsx,DB,Sports};
$n=0;function ok($v,$label){global $n;if(!$v)throw new RuntimeException($label);$n++;echo "OK $n $label\n";}
function sample($label){return ['type_dossier'=>'Discipline','sujet_dossier'=>'Licencié','numero_dossier'=>'TEST-DISC','numero_personne'=>'TEST-DISC','libelle_decision'=>$label,'date_d_effet'=>'25/05/2026'];}
foreach(['3 matchs de suspension dont 1 avec sursis'=>2,"3 matchs dont l'automatique + 1 match avec sursis"=>3,'Le match automatique'=>1,'1 Match Ferme par révocation du Sursis'=>1,'2 Matchs Fermes Dont 1 Par Revocation Du Sursis'=>2,'3eme Avertissement - 1 Match Automatique'=>1,'1 match de suspension (3ème avertissement)'=>1] as $label=>$firm)ok((int)F::normalize(sample($label))['nb_matchs']===$firm,$label);
foreach(['2 mois','En instance','Traité le 17/09/2026 avec 2 matchs','3 matchs dont 5 avec sursis'] as $label){try{F::normalize(sample($label));ok(false,'ambiguous rejected');}catch(RuntimeException $e){ok(true,'Refus : '.$label);}}
try{F::flatten(['numero_personne_1'=>'123','numero_personne_2'=>'456']);ok(false,'conflict');}catch(RuntimeException $e){ok(true,'Colonnes contradictoires refusées');}
if(isset($argv[1])){
$counts=[];foreach(Xlsx::read($argv[1])['rows'] as $r){try{$v=F::normalize($r['data']);$k=isset($v['_skip'])?'skipped':($v['status']??'official');}catch(RuntimeException $e){$k='review';}$counts[$k]=($counts[$k]??0)+1;}
ok($counts===['skipped'=>1438,'official'=>255,'review'=>7,'provisional'=>1] || ($counts['skipped']===1438&&$counts['official']===255&&$counts['review']===7&&$counts['provisional']===1),'Historique réel : 1701 lignes classées');
}
if(getenv('ESBSC_TEST_DATABASE')==='1' && isset($argv[2])){
$actor=(int)DB::value('SELECT id FROM users LIMIT 1');
Sports::save('players',Sports::player(['licence_number'=>'2544479543','last_name'=>'LAVERGNE','first_name'=>'Benjamin']),0,$actor);
$raw=Xlsx::read($argv[2])['rows'];
$apply=function($rows)use($actor){DB::query('INSERT INTO import_batches(actor_id,kind,filename,fingerprint,payload,base_revision) VALUES(?,?,?,?,?,?)',[$actor,'discipline','test.xlsx',hash('sha256',json_encode($rows)),json_encode($rows),DB::revision()]);return Csv::apply((int)DB::conn()->lastInsertId(),$actor);};
$rows=Csv::previewRows('discipline',0,$raw);ok(count(array_filter($rows,fn($r)=>$r['error']))===0,'Export actuel reconnu, sans registre staff requis');
$c=$apply($rows);ok($c['create']===1&&$c['skipped']===9,'Un provisoire et neuf lignes explicitement non importées');
$rows=Csv::previewRows('discipline',0,$raw);$c=$apply($rows);ok($c['unchanged']===1,'Réimport idempotent');
$last=$raw[count($raw)-1];$last['data']['libelle_decision']="3 matchs de suspension dont l'automatique";$last['data']['date_d_effet']='13/09/2026';
$rows=Csv::previewRows('discipline',0,[$last]);ok($rows[0]['action']==='update'&&$rows[0]['data']['status']==='official','Décision officielle remplace le même dossier');$apply($rows);
ok((int)DB::value("SELECT COUNT(*) FROM sanctions WHERE external_ref='24022313'")===1,'Pas de cumul provisoire/officiel');
$rows=Csv::previewRows('discipline',0,$raw);ok($rows[count($rows)-1]['action']==='error','Ancien export ne rétablit pas le provisoire');
$unknown=sample('1 Match De Suspension');$rows=Csv::previewRows('discipline',0,[['line'=>2,'data'=>$unknown]]);ok(str_contains($rows[0]['error'],'TEST-DISC'),'Licence absente identifiée dans le message');
}
if(getenv('ESBSC_TEST_DATABASE')==='1'){
$staff=Csv::preview('players',0,"licence;nom;prenom;profil;fonction\n1102438372;MARTINEZ;Antoine;staff;Dirigeant\n");
ok($staff[0]['data']['member_role']==='staff','Import du profil staff');
Sports::save('players',$staff[0]['data'],0,$actor);
$again=Csv::preview('players',0,"licence;nom;prenom\n1102438372;MARTINEZ;Antoine\n");
ok($again[0]['data']['member_role']==='staff'&&$again[0]['data']['staff_function']==='Dirigeant','Ancien export conserve le profil et la fonction');
$both=Csv::preview('players',0,"licence;nom;prenom;profil;fonction\n1102438372;MARTINEZ;Antoine;Joueur et staff;Dirigeant\n");
ok($both[0]['action']==='update'&&$both[0]['data']['member_role']==='player_staff','Double rôle sur la même licence');
$staffRow=null;foreach(Xlsx::read($argv[1])['rows'] as $r){$flat=F::flatten($r['data']);if(($flat['numero_dossier']??'')==='23915538')$staffRow=$r;}
$rows=Csv::previewRows('discipline',0,[$staffRow]);ok($rows[0]['action']==='create'&&$rows[0]['data']['matches_required']===8,'Sanction staff réelle : huit matchs');
$apply($rows);$rows=Csv::previewRows('discipline',0,[$staffRow]);ok($rows[0]['action']==='unchanged','Réimport sanction staff sans doublon');
$p=DB::one("SELECT * FROM players WHERE licence_number='1102438372'");$c=App\Eligibility::check($p,2,'2026-09-20');ok($c['status']==='blocked','Staff suspendu dans le contrôle');
$report=App\Reports::build('2026-05-31','2026-05-31');$ids=array_column(array_column($report['groups'][0]['rows'],'player'),'id');ok(in_array($p['id'],$ids),'Staff présent dans le rapport');
}
echo "$n contrôles réussis\n";
+82
View File
@@ -0,0 +1,82 @@
"""HTTP integration tests. Disposable fixture from tests/integration.php only.
Requirements: requests, beautifulsoup4. Start PHP server with SESSION_SECURE=0.
"""
import os, re
from pathlib import Path
import requests
from bs4 import BeautifulSoup
BASE=os.environ.get('ESBSC_TEST_URL','http://127.0.0.1:8097')
if os.environ.get('ESBSC_TEST_DATABASE')!='1':raise SystemExit('Disposable test database only: ESBSC_TEST_DATABASE=1')
count=0
def check(value,label):
global count
count+=1
assert value,label
print(f'OK HTTP {count} - {label}',flush=True)
def client():
s=requests.Session();s.trust_env=False;return s
def form(s,path,action,extra):
page=s.get(BASE+path); soup=BeautifulSoup(page.text,'html.parser'); f=soup.find('form',action=action)
assert f is not None,(path,action,page.status_code,page.text[:100])
data={i.get('name'):i.get('value','') for i in f.find_all('input',type='hidden')}
data.update(extra);return s.post(BASE+action,data=data)
def login(email,pwd):
s=client();r=form(s,'/login','/login',dict(email=email,password=pwd));return s,r
s=client();r=s.get(BASE+'/players',allow_redirects=False);check(r.status_code==303 and r.headers['Location']=='/login','Accès anonyme redirigé')
s,r=login('admin@example.test','Testing-only-123!');check(r.status_code==200 and 'Disponibilités du club' in r.text,'Connexion administrateur')
for path in ['/','/players','/matches','/sanctions','/events','/imports','/users','/reports','/audit','/check?id=1&team_id=3&date=2026-06-07']:
r=s.get(BASE+path);check(r.status_code==200 and 'Warning:' not in r.text and 'Fatal error' not in r.text,'Page '+path)
r=s.post(BASE+'/players/save',data={'last_name':'Intrus'});check(r.status_code==422 and 'formulaire invalide' in r.text,'Protection CSRF')
r=s.get(BASE+'/check?team_id=3&date=2026-06-07&licences=INCONNUE');check('Licence inconnue' in r.text and 'Contrôle nécessaire' in r.text,'Licence inconnue signalée dans le contrôle')
# Two new accounts; their initial passwords must change.
for email,role in [('coach@example.test','coach'),('viewer@example.test','viewer')]:
r=form(s,'/users','/users/save',dict(email=email,name='Responsable test',role=role,password='Temporary-test-123!',active='1'))
check(r.status_code==200,'Création du compte '+role)
c,r=login(email,'Temporary-test-123!');check('/password' in r.url,'Changement de mot de passe imposé '+role)
r=form(c,'/password','/password',dict(current_password='Temporary-test-123!',new_password='Permanent-test-123!',confirm_password='Permanent-test-123!'))
check('/login' in r.url,'Changement invalide la session '+role)
c,r=login(email,'Permanent-test-123!');check(r.status_code==200 and 'Vue du week-end' in r.text,'Connexion après changement '+role)
token=BeautifulSoup(r.text,'html.parser').find('input',{'name':'csrf'})['value']
r=c.post(BASE+'/players/save',data={'csrf':token,'licence_number':'UNAUTH'});check(r.status_code==422,'Écriture sportive interdite '+role)
r=c.get(BASE+'/users');check(r.status_code==422,'Gestion des comptes interdite '+role)
if role=='coach':coach=c
else:viewer=c
# Existing match #1 created in integration test.
r=form(coach,'/squad?match_id=1','/squad',{'players[]':['1','2']});check(r.status_code==200 and '2 convoqués' in r.text,'Dirigeant enregistre son groupe')
r=form(viewer,'/squad?match_id=1','/squad',{'players[]':['1']});check(r.status_code==422,'Lecture seule ne modifie pas le groupe')
r=form(coach,'/squad?match_id=1','/reports/create',{});check(r.status_code==200 and 'Convocation enregistrée' in r.text,'Rapport basé sur les convoqués')
report_url=r.url;rid=re.search(r'id=(\d+)',report_url).group(1)
r=coach.get(BASE+'/reports/pdf?id='+rid);check(r.status_code==200 and r.content.startswith(b'%PDF-1.4') and r.headers['Content-Type'].startswith('application/pdf'),'Téléchargement PDF authentifié')
r=s.get(BASE+'/reports');check('À refaire' in r.text,'Ancien rapport périmé signalé')
# Create a player containing HTML to verify output escaping.
r=form(s,'/players','/players/save',dict(licence_number='QA-XSS',last_name='<script>alert(1)</script>',first_name='Éric',category='Senior',usual_team_id='1',active='1'))
check(r.status_code==200 and '<script>alert(1)</script>' not in r.text and '&lt;SCRIPT&gt;' in r.text,'Noms échappés contre injection HTML')
r=coach.get(report_url);check('Les données ont changé' in r.text,'Rapport de groupe invalidé après modification')
# Stale edit form cannot overwrite a newer change.
page=s.get(BASE+'/players?id=1');soup=BeautifulSoup(page.text,'html.parser');f=soup.find('form',action='/players/save');data={i['name']:i.get('value','') for i in f.find_all('input',type='hidden')}
r=form(s,'/imports','/freshness',dict(scope='players',note='Contrôle de test'))
data.update(licence_number='00123',last_name='AMIL',first_name='Riyad',active='1',reason='Test ancien formulaire')
r=s.post(BASE+'/players/save',data=data);check(r.status_code==422 and 'Les données ont changé' in r.text,'Édition périmée refusée')
# Real upload flow.
page=s.get(BASE+'/imports');token=BeautifulSoup(page.text,'html.parser').find('input',{'name':'csrf'})['value']
csv='licence;nom;prenom;categorie;equipe;actif\nHTTP-123;ESSAI;Jules;Senior;E1;oui\n'
r=s.post(BASE+'/imports/preview',data=dict(csrf=token,kind='players'),files={'csv':('joueurs.csv',csv.encode(),'text/csv')});check(r.status_code==200 and 'Valider les 1 lignes' in r.text,'Aperçu upload CSV')
url=r.url.replace(BASE,'');r=form(s,url,'/imports/apply',{});check(r.status_code==200 and 'joueurs.csv' in r.text,'Validation upload CSV')
r=s.get(BASE+'/players');check('HTTP-123' in r.text,'Joueur importé présent')
# Account deactivation invalidates the already logged-in coach immediately.
page=s.get(BASE+'/users');soup=BeautifulSoup(page.text,'html.parser');tr=next(tr for tr in soup.select('tbody tr') if 'coach@example.test' in tr.text);editurl=tr.find('a')['href']
r=form(s,editurl,'/users/save',dict(email='coach@example.test',name='Responsable test',role='coach',password=''))
r=coach.get(BASE+'/',allow_redirects=False);check(r.status_code==303 and r.headers['Location']=='/login','Désactivation révoque la session ouverte')
r=s.get(BASE+'/config/database.php');check(r.status_code==404 and 'test-only' not in r.text,'Configuration non exposée')
for path,name in [('/?from=2026-05-31','dashboard'),('/squad?match_id=1','squad'),('/users','users'),('/imports','imports')]:
r=s.get(BASE+path)
out=Path(os.environ.get('ESBSC_QA_DIR','/tmp/esbsc-qa'));out.mkdir(exist_ok=True,parents=True)
# Static render fixture for visual QA; no saved session or credentials.
html=r.text.replace('<link rel="stylesheet" href="/assets/app.css">','<style>'+Path('public/assets/app.css').read_text()+'</style>').replace('<script defer src="/assets/app.js"></script>','')
(out/(name+'.html')).write_text(html)
print(f'{count} tests HTTP réussis.')
+58
View File
@@ -0,0 +1,58 @@
<?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";
+24
View File
@@ -0,0 +1,24 @@
<?php
require dirname(__DIR__).'/bootstrap.php';
use App\{DB,People,PersonMerge,Csv,Sports};
if(getenv('ESBSC_TEST_DATABASE')!=='1')exit('Base de test requise');
function ok($v,$s){if(!$v)throw new RuntimeException($s);echo "OK $s\n";}
$actor=(int)DB::value('SELECT id FROM users LIMIT 1');
DB::query("INSERT INTO players(id,licence_number,last_name,first_name) VALUES(40,'89572837','HEBRAS','Emmanuel'),(107,'89572842','HEBRAS','Emmanuel')");
$r=['line'=>2,'data'=>['numero_personne'=>'1100781229','numero_licence'=>'89572837','nom'=>'HEBRAS','prenom'=>'Emmanuel','type_licence'=>'Libre']];
$s=$r;$s['data']['numero_licence']='89572842';$s['data']['type_licence']='Dirigeant';
$a=People::preview($r,'2026/2027');$b=People::preview($s,'2026/2027');
try{DB::transaction(function()use($a,$b,$actor){People::apply($a,$actor);People::apply($b,$actor);});throw new LogicException('Import should reject');}catch(RuntimeException $e){ok(str_contains($e->getMessage(),'Rapprocher les fiches'),'Conflit intercepté avant erreur SQL');}
ok(DB::value('SELECT person_number FROM players WHERE id=40')===null,'Lot en conflit annulé entièrement');
$san=Sports::save('sanctions',Sports::sanction(['player_id'=>107,'effective_date'=>'2026-09-01','matches_required'=>1,'label'=>'Test fusion']),0,$actor);
DB::query("INSERT INTO disciplinary_events(player_id,event_date,event_type) VALUES(107,'2026-08-31','yellow')");$event=(int)DB::conn()->lastInsertId();
$mid=DB::value('SELECT id FROM matches LIMIT 1');DB::query('INSERT INTO squads(match_id,updated_by) VALUES(?,?)',[$mid,$actor]);$sq=(int)DB::conn()->lastInsertId();DB::query('INSERT INTO squad_players VALUES(?,40),(?,107)',[$sq,$sq]);
PersonMerge::run(40,107,'1100781229','2026/2027');
ok(!DB::one('SELECT * FROM players WHERE id=107'),'Ancienne fiche regroupée');
ok((int)DB::value('SELECT player_id FROM sanctions WHERE id=?',[$san])===40,'Sanction conservée');
ok((int)DB::value('SELECT player_id FROM disciplinary_events WHERE id=?',[$event])===40,'Carton conservé');
ok((int)DB::value('SELECT COUNT(*) FROM squad_players WHERE squad_id=?',[$sq])===1,'Convocation dédoublonnée');
ok((int)DB::value('SELECT COUNT(*) FROM person_licences WHERE player_id=40')===2,'Deux licences conservées');
ok(DB::value('SELECT person_number FROM players WHERE id=40')==='1100781229','Numéro personne affecté');
ok((int)DB::value("SELECT COUNT(*) FROM audit_log WHERE action='merge_person'")===1,'Fusion historisée');
foreach([$r,$s] as $raw){$v=People::preview($raw,'2026/2027');ok($v['id']===40,'Réimport retrouve la fiche commune');}
+22
View File
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
require dirname(__DIR__).'/bootstrap.php';
use App\DB;
if(getenv('ESBSC_TEST_DATABASE')!=='1')exit("Base jetable uniquement.\n");
if((int)DB::value('SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE()')!==0)exit("Base vide requise.\n");
$sql=file_get_contents(dirname(__DIR__).'/database/schema.sql');
$sql=preg_replace('/^CREATE DATABASE.*;\s*USE esbsc_suspensions;\s*/m','',$sql);DB::conn()->exec($sql);
DB::query("INSERT INTO players(id,licence_number,last_name,first_name) VALUES(42,'LEGACY-42','AMIL','Riyad')");
DB::query("INSERT INTO sanctions(player_id,sanction_type,status,effective_date,matches_required) VALUES(42,'commission','served','2026-05-25',1),(42,'red_provisional','provisional','2026-06-10',1)");
DB::query("INSERT INTO matches(fff_match_id,team_id,match_date,opponent,status,counts_for_purge) VALUES('LEGACY-M1',3,'2026-05-31','Ancien match','played',1)");
$cmd=[PHP_BINARY,'-c',php_ini_loaded_file(),dirname(__DIR__).'/bin/console.php','migrate'];
$p=proc_open($cmd,[0=>STDIN,1=>STDOUT,2=>STDERR],$pipes);if(proc_close($p)!==0)throw new RuntimeException('Migration échouée');
$checks=[
'Identifiant et licence conservés'=>DB::value('SELECT licence_number FROM players WHERE id=42')==='LEGACY-42',
'Ancien statut served recalculable'=>DB::value("SELECT status FROM sanctions WHERE sanction_type='commission'")==='official',
'Exclusion provisoire ancienne sécurisée'=>DB::value("SELECT exclusion_date FROM sanctions WHERE sanction_type='red_provisional'")==='2026-06-10',
'Calendrier historique conservé'=>(int)DB::value("SELECT COUNT(*) FROM matches WHERE fff_match_id='LEGACY-M1' AND counts_for_purge=1")===1,
'Fraîcheur non déclarée automatiquement'=>(int)DB::value('SELECT COUNT(*) FROM data_checks')===0,
];
foreach($checks as $label=>$ok){if(!$ok)throw new RuntimeException($label);echo "OK migration - $label\n";}
echo count($checks)." contrôles de migration réussis.\n";
+23
View File
@@ -0,0 +1,23 @@
<?php
require dirname(__DIR__).'/bootstrap.php';
use App\{DB,Csv,People,Sports,Xlsx};
if(getenv('ESBSC_TEST_DATABASE')!=='1')exit('Base de test requise');
$n=0;function ok($v,$m){global $n;if(!$v)throw new RuntimeException($m);echo 'OK '.(++$n).' '.$m."\n";}
$actor=(int)DB::value('SELECT id FROM users LIMIT 1');
$apply=function($rows,$kind='players')use($actor){foreach($rows as $r)if($r['error'])throw new RuntimeException($r['error']);DB::query('INSERT INTO import_batches(actor_id,kind,filename,fingerprint,payload,base_revision) VALUES(?,?,?,?,?,?)',[$actor,$kind,'test.xlsx',hash('sha256',json_encode($rows)),json_encode($rows),DB::revision()]);return Csv::apply((int)DB::conn()->lastInsertId(),$actor);};
// Old fixture linked by the real seasonal licence, preserving the internal id and sanctions.
$id=Sports::save('players',Sports::player(['licence_number'=>'89427490','last_name'=>'AMIL','first_name'=>'Riyad']),0,$actor);
$san=Sports::save('sanctions',Sports::sanction(['player_id'=>$id,'effective_date'=>'2026-05-25','matches_required'=>2,'label'=>'Historique conservé']),0,$actor);
foreach([$argv[1],$argv[2]] as $file){$rows=Csv::previewRows('players',0,Xlsx::read($file)['rows'],false,'2026/2027');$apply($rows);}
ok((int)DB::value('SELECT COUNT(*) FROM players WHERE person_number IS NOT NULL')===100,'100 personnes pour les deux exports');
ok((int)DB::value("SELECT id FROM players WHERE person_number='2547084057'")===$id,'Ancienne fiche rapprochée par identifiant exact');
ok((int)DB::value('SELECT player_id FROM sanctions WHERE id=?',[$san])===$id,'Sanction existante conservée');
ok((int)DB::value("SELECT COUNT(*) FROM person_licences l JOIN players p ON p.id=l.player_id WHERE p.person_number='1152424516'")===2,'Deux licences pour une seule personne');
ok(DB::value("SELECT member_role FROM players WHERE person_number='1152424516'")==='player_staff','Double profil regroupé');
foreach([$argv[1],$argv[2]] as $file){$rows=Csv::previewRows('players',0,Xlsx::read($file)['rows'],false,'2026/2027');$c=$apply($rows);ok($c['create']===0&&$c['update']===0,'Réimport sans modification');}
$row=Xlsx::read($argv[1])['rows'][0];$row['data']['numero_licence']='999999999';$apply(Csv::previewRows('players',0,[$row],false,'2027/2028'));
ok((int)DB::value('SELECT COUNT(*) FROM players WHERE person_number IS NOT NULL')===100,'Nouvelle saison sans nouvelle personne');
$bad=Csv::previewRows('players',0,[$row]);ok($bad[0]['action']==='error','Saison obligatoire');
$disc=Csv::previewRows('discipline',0,Xlsx::read($argv[3])['rows']);ok(count(array_filter($disc,fn($r)=>$r['error']))===0,'Sanctions rapprochées par numéro personne');$apply($disc,'discipline');
People::migrate();ok((int)DB::value('SELECT COUNT(*) FROM players WHERE person_number IS NOT NULL')===100,'Migration relançable');
echo "$n tests personnes réussis\n";
+41
View File
@@ -0,0 +1,41 @@
<?php
require dirname(__DIR__).'/bootstrap.php';
use App\{DB,LicenceImport,Favorites,Regulations,Csv,Xlsx};
if(getenv('ESBSC_TEST_DATABASE')!=='1'||empty($argv[1]))exit('Base jetable et export complet requis');
$n=0;function verify($v,$m){global $n;if(!$v)throw new RuntimeException($m);echo 'RC3 '.(++$n).' '.$m."\n";}
verify(LicenceImport::qualified('2026-09-01')==='2026-09-06','Quatre jours francs : J+5');
verify(LicenceImport::qualified('2026-12-29')==='2027-01-03','Passage année');
verify(LicenceImport::qualified('2028-02-25')==='2028-03-01','Année bissextile');
$raw=Xlsx::read($argv[1])['rows'];$numbers=array_map(fn($r)=>$r['data']['numero_licence'],$raw);$marks=implode(',',array_fill(0,count($numbers),'?'));
$licences=LicenceImport::decorate(DB::all("SELECT * FROM person_licences WHERE season='2026/2027' AND licence_number IN ($marks)",$numbers));
verify(count(array_filter($licences,fn($l)=>$l['licence_status']==='active'))===74,'Export réel : 74 licences actives');
verify(count(array_filter($licences,fn($l)=>$l['licence_status']==='inactive'))===1,'Export réel : une licence inactive');
foreach($licences as $l)verify($l['qualified_on']===LicenceImport::qualified($l['imported_facts']['registered_on']),'Qualification calculée licence #'.$l['id']);
$actor=(int)DB::value('SELECT id FROM users LIMIT 1');$l=$licences[0];$old=$l['imported_facts'];
LicenceImport::save($l['id'],['licence_status'=>'inactive','registered_on'=>'2026-09-01'],$actor,'test.xlsx');
$decorated=LicenceImport::decorate([array_merge($l,['licence_status'=>'active','qualified_on'=>'2000-01-01'])])[0];
$p=DB::one('SELECT * FROM players WHERE id=?',[$l['player_id']]);$disc=['status'=>'available','warnings'=>[]];
$result=Regulations::individual($p,['match_date'=>'2026-09-05'],[$decorated],$disc);
verify(count(array_filter($result['issues'],fn($i)=>$i['level']==='blocked'&&in_array($i['code'],['licence','qualification'])))===2,'Source importée prioritaire : inactif et J+4 bloqués');
LicenceImport::save($l['id'],['licence_status'=>'active'],$actor,'test.xlsx');$decorated=LicenceImport::decorate([$l])[0];
$result=Regulations::individual($p,['match_date'=>'2026-09-06'],[$decorated],$disc);
verify(!array_filter($result['issues'],fn($i)=>in_array($i['code'],['licence','qualification'])),'Qualification atteinte à J+5, statut actif');
$rev=DB::revision();LicenceImport::save($l['id'],[],$actor,'old.xlsx');verify(DB::revision()===$rev,'Colonnes absentes conservées');
LicenceImport::save($l['id'],['registered_on'=>null],$actor,'empty.xlsx');verify(LicenceImport::decorate([$l])[0]['qualified_on']===null,'Date explicitement vide : inconnue, pas ancienne valeur');
LicenceImport::save($l['id'],$old,$actor,'44171420d.xlsx');
$bad=$raw[0];$bad['data']['statut']='Actif peut-être';verify(Csv::previewRows('players',0,[$bad],false,'2026/2027')[0]['action']==='error','Statut inconnu refusé');
$bad=$raw[0];$bad['data']['enregistrement']='31/02/2026';verify(Csv::previewRows('players',0,[$bad],false,'2026/2027')[0]['action']==='error','Date impossible refusée');
$bad=$raw[0];$bad['data']['statut']=$bad['data']['statut']==='Active'?'Non active':'Active';verify(Csv::previewRows('players',0,[$raw[0],$bad],false,'2026/2027')[0]['action']==='error','Lignes cachets : statuts contradictoires refusés');
$m=DB::one("SELECT * FROM matches WHERE fff_match_id='V3-FUTURE'");$players=DB::all("SELECT * FROM players WHERE person_number LIKE 'V3-%' ORDER BY id");$rows=array_map(fn($p)=>['player'=>$p],$players);$pid=(int)$players[0]['id'];$new=(int)$players[1]['id'];
$rank=Favorites::rank($m,$rows);$by=array_column($rank,null,'x');$lookup=fn($r,$id)=>current(array_filter($r,fn($v)=>(int)$v['player']['id']===$id))['favorite'];
verify($lookup($rank,$pid)['on'],'FMI récente suggère le joueur');verify(!$lookup($rank,$new)['on'],'Nouveau joueur accessible parmi les autres');
$squads=DB::all('SELECT * FROM squad_players ORDER BY squad_id,player_id');$rev=DB::revision();Favorites::save($m,$new,'pin',$actor);
verify((int)Favorites::rank($m,$rows)[0]['player']['id']===$new,'Épinglé en tête sans historique');verify(DB::revision()===$rev&&DB::all('SELECT * FROM squad_players ORDER BY squad_id,player_id')===$squads,'Favori ne change ni sélection ni validation');
Favorites::save($m,$pid,'hide',$actor);verify(!$lookup(Favorites::rank($m,$rows),$pid)['on'],'Retrait du favori automatique');
Favorites::save($m,$pid,'auto',$actor);verify($lookup(Favorites::rank($m,$rows),$pid)['on'],'Retour au classement automatique');
$other=$m;$other['team_id']=4;verify(!$lookup(Favorites::rank($other,$rows),$new)['on'],'Favori isolé par équipe');
$other=$m;$other['match_date']='2027-08-01';verify(!$lookup(Favorites::rank($other,$rows),$pid)['on']&&!$lookup(Favorites::rank($other,$rows),$new)['on'],'FMI et favoris isolés par saison');
$other=$m;$other['match_date']=date('Y-m-d',strtotime('-4 days'));verify(!$lookup(Favorites::rank($other,$rows),$pid)['on'],'Aucune FMI postérieure à la rencontre utilisée');
Favorites::save($m,$new,'auto',$actor);
$rev=DB::revision();LicenceImport::migrate();Favorites::migrate();verify(DB::revision()===$rev,'Migrations relançables');
echo "$n vérifications RC3 réussies.\n";
+23
View File
@@ -0,0 +1,23 @@
<?php
require dirname(__DIR__).'/bootstrap.php';
use App\Regulations;
$n=0;function expect($ok,$label){global $n;if(!$ok)throw new RuntimeException($label);echo 'OK '.(++$n).' '.$label."\n";}
$match=['match_date'=>'2026-09-27'];$p=['active'=>1];$disc=['status'=>'available','warnings'=>[]];
$lic=['season'=>'2026/2027','licence_type'=>'Libre','licence_status'=>'active','qualified_on'=>'2026-09-01','category_ok'=>'yes','mutation'=>'normal','mutation_until'=>'2027-06-01'];
expect(Regulations::season('2026-06-30')==='2025/2026','Fin de saison');expect(Regulations::season('2026-07-01')==='2026/2027','Nouvelle saison');
$r=Regulations::individual($p,$match,[$lic],$disc);expect($r['status']==='available'&&$r['mutation']==='normal','Licence joueur contrôlée');
$l=$lic;$l['qualified_on']='2026-09-28';expect(Regulations::individual($p,$match,[$l],$disc)['status']==='blocked','Qualification future bloquée');
$l=$lic;$l['licence_type']='Dirigeant';expect(Regulations::individual($p,$match,[$l],$disc)['status']==='review','Licence dirigeant non assimilée à joueur');
$l=$lic;$l['mutation_until']='2026-09-26';expect(Regulations::individual($p,$match,[$l],$disc)['mutation']==='none','Cachet expiré');
$l=$lic;$l['mutation_until']='2026-09-27';expect(Regulations::individual($p,$match,[$l],$disc)['mutation']==='normal','Dernier jour inclus');
expect(Regulations::individual($p,$match,[], $disc)['status']==='review','Pas de faux vert sans licence');
$profile=['confirmed'=>1,'mutation_base'=>4,'mutation_bonus'=>1,'outside_limit'=>2,'max_players'=>14,'ten_active'=>false,'ten_limit'=>3];
$picked=array_fill(1,5,$r);expect(Regulations::collective($picked,$profile)['status']==='available','E1 cinq mutés autorisés');
$picked[6]=$r;expect(Regulations::collective($picked,$profile)['status']==='blocked','Sixième muté bloqué');
$picked=array_fill(1,3,array_replace($r,['mutation'=>'outside']));expect(Regulations::collective($picked,$profile)['status']==='blocked','Troisième hors période bloqué');
$profile['mutation_bonus']=0;expect(Regulations::collective(array_fill(1,5,$r),$profile)['status']==='blocked','E2 quatre mutés maximum');
$profile['confirmed']=0;expect(Regulations::collective([$r],$profile)['status']==='review','Profil non confirmé');
$profile['confirmed']=1;$profile['ten_active']=true;$high=array_replace($r,['mutation'=>'none','higher_total'=>11]);expect(Regulations::collective(array_fill(1,4,$high),$profile)['status']==='blocked','Quatre joueurs +10 dans période active');
$profile['ten_active']=false;expect(Regulations::collective(array_fill(1,4,$high),$profile)['status']==='available','Pas de blocage +10 hors période');
expect(Regulations::collective([$r],$profile,['Calendrier ancien'])['status']==='review','Fraîcheur explicite');
echo "$n tests V3 réussis.\n";
+41
View File
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
require dirname(__DIR__).'/bootstrap.php';
use App\{Eligibility,Csv,Validation,Pdf};
$n=0;
function expect(bool $v,string $label): void {global $n;$n++;if(!$v)throw new RuntimeException('ECHEC : '.$label);echo "OK $n - $label\n";}
$p=['id'=>1,'active'=>1,'licence_number'=>'DEMO-AMIL'];
$s=['id'=>1,'player_id'=>1,'status'=>'official','effective_date'=>'2026-05-25','matches_required'=>1,'duration_kind'=>'matches','purge_from'=>null,'exclusion_date'=>null];
$m=['id'=>1,'team_id'=>3,'match_date'=>'2026-05-31','counts_for_purge'=>1,'status'=>'played'];
expect(Eligibility::calculate($p,1,'2026-06-07',[$s],[$m])['status']==='blocked','AMIL ne reprend pas en E1 sans match E1 purgé');
expect(Eligibility::calculate($p,3,'2026-06-07',[$s],[$m])['status']==='available','AMIL reprend en E3 après le 31 mai');
expect(Eligibility::calculate($p,3,'2026-05-31',[$s],[$m])['status']==='blocked','Le match cible ne se purge pas lui-même');
expect(Eligibility::calculate($p,3,'2026-06-07',[$s],[array_replace($m,['counts_for_purge'=>0,'status'=>'postponed'])])['status']==='blocked','Un report ne purge pas');
expect(Eligibility::calculate($p,3,'2026-06-07',[array_replace($s,['effective_date'=>'2026-06-01'])],[$m])['status']==='blocked','Pas de purge avant la date d’effet');
expect(Eligibility::calculate($p,3,'2026-06-07',[array_replace($s,['effective_date'=>'2026-06-10'])],[])['status']==='available','Décision future non encore applicable');
expect(Eligibility::calculate($p,3,'2026-06-07',[array_replace($s,['status'=>'revoked'])],[])['status']==='available','Décision révoquée ignorée');
expect(Eligibility::calculate($p,3,'2026-06-07',[array_replace($s,['status'=>'served'])],[])['status']==='blocked','Ancien indicateur served ne libère pas globalement');
expect(Eligibility::calculate(null,3,'2026-06-07',[],[])['status']==='review','Licence inconnue jamais verte');
expect(Eligibility::calculate(array_replace($p,['active'=>0]),3,'2026-06-07',[],[])['status']==='review','Joueur inactif signalé');
$freshness=Eligibility::calculate($p,3,'2026-06-07',[],[],['Import trop ancien']);
expect($freshness['status']==='available' && $freshness['data_warnings']===['Import trop ancien'],'Fraîcheur signalée sans dégrader le statut individuel');
expect(Eligibility::calculate($p,3,'2026-06-07',[array_replace($s,['status'=>'provisional'])],[$m])['status']==='review','Rouge provisoire reste à vérifier après un match');
expect(Eligibility::calculate($p,3,'2026-06-07',[array_replace($s,['exclusion_date'=>'2026-05-30'])],[$m])['status']==='blocked','Lendemain de l’exclusion exclu de la purge');
$period=array_replace($s,['duration_kind'=>'period','end_date'=>'2026-06-07']);
expect(Eligibility::calculate($p,3,'2026-06-07',[$period],[])['status']==='blocked','Fin de période inclusive');
expect(Eligibility::calculate($p,3,'2026-06-08',[$period],[])['status']==='available','Après la fin de période');
expect(Eligibility::calculate($p,3,'2026-06-08',[array_replace($s,['duration_kind'=>'indefinite'])],[])['status']==='blocked','Sans date de fin reste bloquant');
$two=Eligibility::calculate($p,3,'2026-06-07',[$s,array_replace($s,['id'=>2])],[$m]);
expect($two['status']==='blocked' && count($two['details'][1]['matches'])===0,'Deux sanctions ne consomment pas silencieusement le même match');
$future=date('Y-m-d',strtotime('+2 days'));$target=date('Y-m-d',strtotime('+3 days'));
expect(Eligibility::calculate($p,3,$target,[$s],[array_replace($m,['match_date'=>$future])])['status']==='blocked','Un match futur marqué joué par erreur ne compte pas');
expect(Eligibility::calculate($p,3,'2026-06-07',[$s],[array_replace($m,['is_official'=>0])])['status']==='blocked','Un amical ne purge pas même si le drapeau est erroné');
$rows=Csv::read("\xEF\xBB\xBFlicence;nom;prénom\r\n00123;DUPONT;Éric\r\n");
expect($rows[0]['data']['licence']==='00123'&&$rows[0]['data']['prenom']==='Éric','CSV BOM accents et zéro initial');
$rows=Csv::read("licence,nom,prenom\n00123,\"DUPONT, fils\",Eric\n");
expect($rows[0]['data']['nom']==='DUPONT, fils','CSV virgule et guillemets');
try{Validation::date('31/02/2026');expect(false,'Date impossible');}catch(RuntimeException $e){expect(true,'Date impossible rejetée');}
try{Csv::read("nom;nom\na;b\n");expect(false,'Colonnes dupliquées');}catch(RuntimeException $e){expect(true,'Colonnes dupliquées rejetées');}
$pdf=new Pdf();for($i=0;$i<120;$i++)$pdf->line('Joueur Éric - contrôle numéro '.$i);$bytes=$pdf->bytes();
expect(str_starts_with($bytes,'%PDF-1.4')&&str_contains($bytes,'/Count 3'),'PDF paginé');
echo "$n tests réussis.\n";
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App {
final class DB {
public static array $rows=[];
public static array $dates=[2=>'2026-10-03',1=>'2026-10-04',3=>'2026-10-04'];
public static function all(string $sql,array $args=[]):array {if($args!==['2026-09-28'])throw new \RuntimeException('Semaine incorrecte');return self::$rows;}
public static function one(string $sql,array $args=[]):?array{return isset(self::$dates[$args[0]])?['match_date'=>self::$dates[$args[0]]]:null;}
}
}
namespace {
require dirname(__DIR__).'/bootstrap.php';
use App\{DB,Spond,Xlsx};
set_error_handler(function($n,$s,$f,$l){throw new ErrorException($s,0,$n,$f,$l);});
$count=0;
function checkDay(bool $ok,string $label):void {global $count;if(!$ok)throw new RuntimeException($label);echo 'OK '.(++$count).' '.$label."\n";}
function response(string $target,string $status,int $pid=1,?int $mid=null):array{return ['target'=>$target,'status'=>$status,'player_id'=>$pid,'match_id'=>$mid,'event_match_date'=>$mid?(DB::$dates[$mid]??null):null,'responded_at'=>null,'imported_at'=>'2026-10-02 15:00:00'];}
DB::$rows=[response('day:2026-10-03','absent'),response('day:2026-10-04','present'),response('week:2026-09-28','absent',2),response('match:2','present',2,2)];
checkDay(Spond::index('2026-09-28',2)[1]['status']==='absent','E2 utilise la date réelle du samedi');
checkDay(Spond::index('2026-09-28',1)[1]['status']==='present','E1 utilise dimanche sans conflit avec samedi');
checkDay(Spond::index('2026-10-04',3)[1]['status']==='present','Même fichier du dimanche pour plusieurs équipes');
checkDay(Spond::state(Spond::index('2026-10-02'),1)['status']==='unknown','Aucune réponse empruntée à un autre jour');
checkDay(Spond::state(Spond::index('2026-10-03'),2)['status']==='unknown','Anciens imports non datés conservés mais non déduits');
DB::$rows[]=response('match:1:2026-10-04','absent',1,1);
checkDay(Spond::index('2026-10-04',1)[1]['status']==='absent','Réponse match prioritaire sur journée');
checkDay(Spond::index('2026-10-04',3)[1]['status']==='present','Réponse spécifique E1 ne fuit pas vers E3');
checkDay(Spond::index('2026-10-04')[1]['status']==='conflict','Synthèse signale des réponses distinctes pour les événements du même jour');
DB::$dates[1]='2026-10-03';foreach(DB::$rows as &$row)if($row['match_id']===1)$row['event_match_date']='2026-10-03';unset($row);
checkDay(Spond::index('2026-10-04',1)[1]['status']==='absent','Match déplacé : réponse de la nouvelle journée');
checkDay(Spond::index('2026-10-04')[1]['status']==='present','Ancienne réponse spécifique déplacée exclue');
DB::$dates[1]='2026-10-04';DB::$rows=array_slice(DB::$rows,0,4);
$summary=['week'=>'2026-09-28','end'=>'2026-10-04','groups'=>[],'missing'=>[['id'=>1,'last_name'=>'TEST','first_name'=>'Spond','discipline'=>[]]],'availability'=>[]];
$_SESSION['csrf']='test';$user=['role'=>'viewer'];ob_start();require dirname(__DIR__).'/templates/convocations.php';$html=ob_get_clean();
checkDay(str_contains($html,'Samedi 03/10/2026')&&str_contains($html,'Dimanche 04/10/2026'),'Deux dates visibles dans les non-convoqués');
checkDay(str_contains($html,'Spond : Absent')&&str_contains($html,'Spond : Présent')&&!str_contains($html,'Spond : Réponses contradictoires'),'Deux états distincts sans faux conflit');
checkDay(str_contains($html,'data-spond-by-date')&&str_contains($html,'data-spond-date'),'Filtre de présence par journée');
foreach(array_slice($argv,1) as $path){
$source=Xlsx::read($path,'À importer',1,true,['statut','nom']);$rows=Spond::parse($source['rows']);
$date=str_contains(basename($path),'Antran')?'2026-10-03':'2026-10-04';
Spond::assertEventDate($date,$source['preamble']);checkDay(count($rows)>0,'Lecture export '.basename($path).' et date vérifiée');
if(str_contains(basename($path),'Antran')){$rejected=false;try{Spond::assertEventDate('2026-10-04',$source['preamble']);}catch(RuntimeException){$rejected=true;}checkDay($rejected,'Export du samedi refusé si dimanche sélectionné');}
}
}
+14
View File
@@ -0,0 +1,14 @@
const fs=require('node:fs'),vm=require('node:vm'),assert=require('node:assert/strict');
function control(value){return {value,events:{},addEventListener(name,fn){this.events[name]=fn;},dispatchEvent(e){this.events[e.type]?.();}};}
const input=control(''),filter=control('present'),date=control('2026-10-03');input.dataset={filter:'#missing-players'};
let selected=false;
const row={dataset:{spondByDate:JSON.stringify({'2026-10-03':'absent','2026-10-04':'present'})},textContent:'TEST Spond',querySelector(){return selected?{}:null;}};
const document={querySelector(s){return s==='[data-spond-filter]'?filter:s==='[data-spond-date]'?date:null;},querySelectorAll(s){if(s==='[data-filter]')return [input];if(s==='[data-spond-filter], [data-spond-date]')return [filter,date];if(s==='#missing-players tbody tr')return [row];return [];},addEventListener(){}};
vm.runInNewContext(fs.readFileSync(__dirname+'/../public/assets/app.js','utf8'),{document,Event:class{constructor(type){this.type=type;}}});
input.events.input();assert.equal(row.hidden,true);
date.value='2026-10-04';date.events.change();assert.equal(row.hidden,false);
filter.value='absent';filter.events.change();assert.equal(row.hidden,true);
date.value='2026-10-03';date.events.change();assert.equal(row.hidden,false);
filter.value='present';selected=true;filter.events.change();assert.equal(row.hidden,false);
selected=false;delete row.dataset.spondByDate;row.dataset.spondStatus='present';input.events.input();assert.equal(row.hidden,false);
console.log('OK filtres samedi/dimanche, statut par match et sélection conservée');
+53
View File
@@ -0,0 +1,53 @@
<?php
require dirname(__DIR__).'/bootstrap.php';
use App\{DB,ClubRoles,PlayerBadges,Reports,Eligibility,Csv,Xlsx};
if(getenv('ESBSC_TEST_DATABASE')!=='1'||empty($argv[1]))exit('Base jetable et export complet requis');
$n=0;function check31($ok,$label){global $n;if(!$ok)throw new RuntimeException($label);echo 'V31 '.(++$n).' '.$label."\n";}
DB::conn()->beginTransaction();
try{
$actor=(int)DB::value('SELECT id FROM users LIMIT 1');$all=DB::all('SELECT * FROM players');$raw=Xlsx::read($argv[1])['rows'];$p=DB::one('SELECT * FROM players WHERE person_number=?',[$raw[0]['data']['numero_personne']]);$id=(int)$p['id'];
$sport=(int)DB::value("SELECT id FROM club_roles WHERE name='Entraîneur'");$admin=(int)DB::value("SELECT id FROM club_roles WHERE name='Secrétaire'");$player=(int)DB::value("SELECT id FROM club_roles WHERE name='Joueur'");
ClubRoles::assign([$id],$admin,0,'add',$actor);$index=ClubRoles::index();check31(ClubRoles::kinds($p,$index[$id])===['admin'],'Classement manuel prioritaire pour affichage');
check31(count(ClubRoles::filter([$p],$index,'admin',0))===1&&count(ClubRoles::filter([$p],$index,'player',0))===0,'Filtres administratif et joueur');
ClubRoles::assign([$id],$player,4,'add',$actor);ClubRoles::assign([$id],$sport,1,'add',$actor);ClubRoles::assign([$id],$sport,2,'add',$actor);
$index=ClubRoles::index();check31(count($index[$id])===4,'Plusieurs rôles et plusieurs équipes');
check31(count(ClubRoles::staff([$p],$index,1))===1&&count(ClubRoles::staff([$p],$index,2))===1&&count(ClubRoles::staff([$p],$index,3))===0,'Staff strictement affecté à équipe');
check31(count(ClubRoles::filter([$p],$index,'player',4))===1,'Filtre équipe et profil cumulés');
ClubRoles::assign([$id],$sport,2,'add',$actor);check31(count(ClubRoles::index()[$id])===4,'Affectation identique sans doublon');
$snapshot=DB::all('SELECT * FROM person_roles ORDER BY player_id,role_id,team_id');
$row=$raw[0];$row['data']['statut']=$row['data']['statut']==='Active'?'Non active':'Active';$preview=Csv::previewRows('players',0,[$row],false,'2026/2027');check31($preview[0]['action']==='update','Réimport modifie effectivement la licence');
// People::apply is the same per-row path used inside the atomic CSV apply transaction.
App\People::apply($preview[0],$actor,'test-v31.xlsx');check31(DB::all('SELECT * FROM person_roles ORDER BY player_id,role_id,team_id')===$snapshot,'Réimport Footclubs conserve toutes les affectations');
ClubRoles::assign([$id],$sport,2,'remove',$actor);check31(count(ClubRoles::index()[$id])===3&&count(ClubRoles::staff([$p],ClubRoles::index(),1))===1,'Retrait ciblé conserve autres rôles');
$other=(int)DB::value("SELECT id FROM players WHERE person_number='V3-TEST'");ClubRoles::assign([$id,$other],$sport,3,'add',$actor);check31(count(ClubRoles::staff($all,ClubRoles::index(),3))===2,'Affectation groupée');
$before=DB::all('SELECT * FROM person_roles ORDER BY player_id,role_id,team_id');try{ClubRoles::assign([$id,99999999],$admin,2,'add',$actor);throw new LogicException('Expected refusal');}catch(RuntimeException $e){check31(DB::all('SELECT * FROM person_roles ORDER BY player_id,role_id,team_id')===$before,'Personne invalide refusée sans application partielle');}
$available=['status'=>'available','details'=>[]];$blocked=['status'=>'blocked','details'=>[['note'=>'1 / 2 matchs purgés']]];
check31(array_column(PlayerBadges::make(['mutation'=>'normal'],$available,0),'kind')===['mn'],'MN bleu seul');
check31(array_column(PlayerBadges::make(['mutation'=>'outside'],$blocked,2),'kind')===['mh','suspended','yellow'],'Cumul MH suspension et risque');
check31(PlayerBadges::make(['mutation'=>'none'],$available,1)===[],'Pas de badge inutile');
$a=['id'=>$other,'active'=>1,'person_number'=>'V3-TEST'];$sanction=['id'=>99,'player_id'=>$other,'status'=>'confirmed','effective_date'=>'2026-09-01','purge_from'=>'2026-09-01','duration_kind'=>'matches','matches_required'=>1,'exclusion_date'=>null];
$games=[['id'=>1,'team_id'=>1,'match_date'=>'2026-09-10','counts_for_purge'=>1,'is_official'=>1,'status'=>'played']];
$e1=Eligibility::calculate($a,1,'2026-09-20',[$sanction],$games);$e2=Eligibility::calculate($a,2,'2026-09-20',[$sanction],$games);
check31(PlayerBadges::make([],$e1,0)===[]&&array_column(PlayerBadges::make([],$e2,0),'kind')===['suspended'],'Badge suspension dépend de équipe de reprise');
DB::query('DELETE FROM disciplinary_events WHERE player_id=?',[$other]);
foreach([['confirmed','2026-09-27'],['confirmed','2026-09-27'],['confirmed','2026-09-26'],['pending','2026-10-01'],['cancelled','2026-10-01']] as [$status,$end])DB::query("INSERT INTO disciplinary_events(player_id,team_id,event_date,event_type,review_status,warning_effective_date,warning_end_date) VALUES(?,1,'2026-09-01','yellow',?,'2026-09-01',?)",[$other,$status,$end]);
check31(Reports::activeYellows($other,'2026-09-27')===2,'Deux jaunes : seulement confirmés actifs, dernier jour inclus');
check31(Reports::activeYellows($other,'2026-09-28')===0,'Badge risque disparaît à expiration');
$base=['status'=>'available','issues'=>[],'mutation'=>'none','higher_total'=>0];$with=$base;$with['badges']=PlayerBadges::make($base,$available,2);$profile=['confirmed'=>1,'mutation_base'=>4,'mutation_bonus'=>0,'outside_limit'=>2,'max_players'=>14,'ten_active'=>false];
check31(App\Regulations::collective([$with],$profile)['status']==='available','Deux jaunes jamais bloquants');
check31(str_contains(PlayerBadges::html(PlayerBadges::make(['mutation'=>'normal'],$available,0)),'data-badge-detail'),'Détail accessible au clic');
// V3.2.1: registry badges share the match-preparation engine and explicit context.
$rp=DB::one('SELECT * FROM players WHERE id=?',[$other]);$rp['usual_team_id']=1;
$registry=PlayerBadges::registry([$rp],'2026-09-27');
$match=['id'=>0,'team_id'=>1,'match_date'=>'2026-09-27','competition'=>'TEST V321','is_official'=>1,'status'=>'scheduled'];
$prepared=App\Regulations::evaluate($match,[$rp],[$other]);
check31(array_column($registry[$other]['badges'],'kind')===array_column($prepared['checks'][$other]['badges'],'kind'),'Registre et préparation affichent les mêmes badges à date et équipe égales');
check31($registry[$other]['team_id']===1&&PlayerBadges::registry([$rp],'2026-09-27',2)[$other]['team_id']===2,'Équipe habituelle par défaut, équipe de contrôle prioritaire');
check31(in_array('yellow',array_column($registry[$other]['badges'],'kind'),true)&&!in_array('yellow',array_column(PlayerBadges::registry([$rp],'2026-09-28')[$other]['badges'],'kind'),true),'Registre : risque expire au lendemain de la date de fin');
$rp['usual_team_id']=null;$unassigned=PlayerBadges::registry([$rp],'2026-09-27')[$other];
check31($unassigned['team_id']===0&&!in_array('suspended',array_column($unassigned['badges'],'kind'),true)&&in_array('yellow',array_column($unassigned['badges'],'kind'),true),'Sans équipe : suspension non évaluée, jaunes conservés');
check31(str_contains($registry[$other]['badges'][0]['detail'],'27/09/2026'),'Date affichée dans le détail des badges du registre');
check31(PlayerBadges::registry([],'2026-09-27')===[],'Registre filtré vide accepté');
}finally{DB::conn()->rollBack();}
$before=DB::all('SELECT * FROM person_roles');ClubRoles::migrate();check31(DB::all('SELECT * FROM person_roles')===$before,'Migration relançable sans perte');
echo "$n tests V3.1 réussis.\n";
+41
View File
@@ -0,0 +1,41 @@
<?php
require dirname(__DIR__).'/bootstrap.php';
use App\{DB,Convocations,ConvocationExport,ClubRoles,Regulations};
if(getenv('ESBSC_TEST_DATABASE')!=='1')exit('Base jetable requise');
$n=0;function check32($ok,$label){global $n;if(!$ok)throw new RuntimeException($label);echo 'V32 '.(++$n).' '.$label."\n";}
function rejects32($fn,$label){try{$fn();throw new LogicException('Expected refusal: '.$label);}catch(RuntimeException $e){check32(true,$label);}}
Convocations::migrate();Convocations::migrate();
DB::conn()->beginTransaction();
try{
$actor=(int)DB::value('SELECT id FROM users LIMIT 1');$pid=(int)DB::value("SELECT id FROM players WHERE person_number='V3-TEST'");$week=Convocations::week(date('Y-m-d',strtotime('+14 days')));$sat=date('Y-m-d',strtotime($week.' +5 days'));$sun=date('Y-m-d',strtotime($week.' +6 days'));
check32(Convocations::week($sat)===$week&&Convocations::week($sun)===$week,'Samedi et dimanche : même semaine');
check32(Convocations::week('2027-01-03')==='2026-12-28','Semaine à cheval sur deux années');
$r=Convocations::saveAvailability($pid,$sat,'injured','NOTE PRIVÉE TEST',0,$actor);
check32($r['version']==1&&Convocations::state(Convocations::availability($sun),$pid)['status']==='injured','Disponibilité partagée toutes équipes et deux jours');
rejects32(fn()=>Convocations::saveAvailability($pid,$sat,'available','',0,$actor),'Concurrence : ancienne version refusée');
rejects32(fn()=>Convocations::saveAvailability($pid,$sat,'invalid','',1,$actor),'Statut inconnu refusé');
rejects32(fn()=>Convocations::saveAvailability($pid,'2020-01-01','injured','',0,$actor),'Historique non modifiable');
check32(Convocations::state(Convocations::availability(date('Y-m-d',strtotime($week.' +7 days'))),$pid)['status']==='available','Semaine suivante disponible sans effacer précédent historique');
$oldRevision=DB::revision();Convocations::saveAvailability($pid,$sat,'unavailable','NOTE PRIVÉE TEST',1,$actor);check32(DB::revision()===$oldRevision,'Indisponibilité ne périme pas les contrôles');
$mids=[];foreach(DB::all('SELECT * FROM teams ORDER BY sort_order LIMIT 4') as $i=>$t){
DB::query("INSERT INTO matches(fff_match_id,team_id,match_date,match_time,opponent,competition,home_away,status) VALUES(?,?,?,'15:00:00',?,'TEST V32',?,'scheduled')",['V32-'.$i,$t['id'],$i===0?$sat:$sun,$i===0?'Étoile Sportive de Saint-Sauveur et des Communes Réunies':'Club test '.($i+1),$i%2?'away':'home']);$mid=(int)DB::conn()->lastInsertId();$mids[]=$mid;
DB::query('INSERT INTO squads(match_id,updated_by,validated_revision,validated_at) VALUES(?,?,?,NOW())',[$mid,$actor,DB::revision()]);$sid=(int)DB::conn()->lastInsertId();DB::query('INSERT INTO squad_players(squad_id,player_id) VALUES(?,?)',[$sid,$pid]);Convocations::saveStaff($sid,[$pid]);
}
$s=Convocations::build($sat);check32(count($s['groups'])===4,'Quatre groupes alignés dans la synthèse');check32(!in_array($pid,array_column($s['missing'],'id')),'Convoqué absent des non-convoqués');check32(isset($s['duplicates'][$pid]),'Présence dans plusieurs groupes signalée');
$share=Convocations::share($s,$mids,false,false,$s['fingerprint']);$json=json_encode($share);check32(!str_contains($json,'NOTE PRIV')&&!str_contains($json,'person_number')&&!str_contains($json,'availability')&&!str_contains($json,'licence'),'Export public exclut notes, identifiants et données internes');
check32(!$share['include_staff']&&!$share['legend']&&!$share['groups'][0]['staff'],'Staff et légende absents par défaut');
$one=Convocations::share($s,[$mids[1]],true,true,$s['fingerprint']);check32(count($one['groups'])===1&&count($one['groups'][0]['staff'])===1&&$one['legend'],'Export partiel avec options explicites');
rejects32(fn()=>Convocations::share($s,[999999],false,false,$s['fingerprint']),'Match hors semaine refusé');
rejects32(fn()=>Convocations::share($s,[],false,false,$s['fingerprint']),'Export vide refusé');
rejects32(fn()=>Convocations::share($s,$mids,false,false,'old'),'Ancienne synthèse refusée');
DB::query('UPDATE squads SET validated_revision=NULL WHERE match_id=?',[$mids[0]]);$draft=Convocations::build($week);rejects32(fn()=>Convocations::share($draft,$mids,false,false,$draft['fingerprint']),'Brouillon non exportable');
DB::query('UPDATE squads SET validated_revision=? WHERE match_id=?',[DB::revision(),$mids[0]]);DB::touch();$stale=Convocations::build($week);rejects32(fn()=>Convocations::share($stale,$mids,false,false,$stale['fingerprint']),'Données sportives actualisées : revalidation requise');
$staffPerson=DB::one('SELECT * FROM players WHERE id=?',[$pid]);$index=[$pid=>[['kind'=>'admin']]];check32(!ClubRoles::filter([$staffPerson],$index,'staff',0),'Administratifs masqués par défaut dans Staff');$index[$pid]=[['kind'=>'sport'],['kind'=>'player']];check32(count(ClubRoles::filter([$staffPerson],$index,'staff',0))===1&&count(ClubRoles::filter([$staffPerson],$index,'player',0))===1,'Double rôle visible dans les deux pages');
// Real exporter fixtures: long accented names, all four columns, multi-page, Excel literal formulas.
foreach($share['groups'] as $i=>&$g){$g['players']=array_map(fn($j)=>['DUPONT Émilien','MARTIN Jean-Baptiste','DUPUIS-DESCHAMPS Alexandre','LE GALL François'][$j%4].' '.($j+1),range(0,13+$i));$g['staff']=['Éducateur Exemple'];}unset($g);
$share['include_staff']=true;$share['legend']=true;$out=$argv[1]??sys_get_temp_dir();file_put_contents($out.'/v32-convocations.pdf',ConvocationExport::pdf($share));file_put_contents($out.'/v32-convocations.xlsx',ConvocationExport::xlsx($share));file_put_contents($out.'/v32-share.json',json_encode($share));
$large=$share;foreach($large['groups'] as &$g)$g['players']=array_fill(0,30,'DUPUIS-DESCHAMPS Jean-Baptiste Émilien');unset($g);file_put_contents($out.'/v32-long.pdf',ConvocationExport::pdf($large));
$share['groups'][0]['players'][0]='=HYPERLINK("https://example.invalid","test")';$bytes=ConvocationExport::xlsx($share);$tmp=tempnam(sys_get_temp_dir(),'v32-');file_put_contents($tmp,$bytes);$z=new ZipArchive();$z->open($tmp);$xml=$z->getFromName('xl/worksheets/sheet1.xml');check32(!str_contains($xml,'<f>')&&str_contains($xml,'t="inlineStr"'),'Noms Excel stockés en texte, jamais exécutés comme formules');$z->close();unlink($tmp);
check32(str_starts_with(ConvocationExport::pdf($one),'%PDF-1.4'),'PDF produit pour une seule équipe');
}finally{DB::conn()->rollBack();}
echo "V3.2 OK : $n assertions\n";
+37
View File
@@ -0,0 +1,37 @@
<?php
require dirname(__DIR__).'/bootstrap.php';
use App\{DB,Regulations,Reports,Csv,Xlsx};
if(getenv('ESBSC_TEST_DATABASE')!=='1')exit('Base jetable requise');
$n=0;function ok($v,$m){global $n;if(!$v)throw new RuntimeException($m);echo 'V3 SQL '.(++$n).' '.$m."\n";}
$date=date('Y-m-d',strtotime('+7 days'));$season=Regulations::season($date);
$count=DB::value('SELECT COUNT(*) FROM players');Regulations::migrate();ok(DB::value('SELECT COUNT(*) FROM players')===$count,'Migration répétable sans perte');
$actor=(int)DB::value('SELECT id FROM users LIMIT 1');
DB::query("INSERT INTO matches(fff_match_id,team_id,competition,match_date,status,is_official,counts_for_purge) VALUES('V3-FUTURE',1,'V3 championnat',?,'scheduled',1,0)",[$date]);$mid=(int)DB::conn()->lastInsertId();
DB::query("INSERT INTO regulation_profiles(team_id,season,competition,mutation_base,mutation_bonus,outside_limit,max_players,confirmed,reference) VALUES(1,?,'V3 championnat',4,1,2,14,1,'Notification test')",[$season]);
$ids=[];
for($i=0;$i<6;$i++){
DB::query("INSERT INTO players(person_number,last_name,first_name,active) VALUES(?,?,?,1)",[$i?'V3-'.$i:'V3-TEST','TEST V3','Joueur '.$i]);$pid=(int)DB::conn()->lastInsertId();$ids[]=$pid;
DB::query("INSERT INTO person_licences(player_id,season,licence_number,licence_type) VALUES(?,?,?,'Libre')",[$pid,$season,'V3-LIC-'.$i]);$lid=(int)DB::conn()->lastInsertId();
DB::query("INSERT INTO licence_checks(licence_id,licence_status,qualified_on,mutation,mutation_until,category_ok,reference) VALUES(?,'active',?,'normal',?,'yes','Test')",[$lid,date('Y-m-d',strtotime('-10 days')),date('Y-m-d',strtotime('+100 days'))]);
}
foreach(['players','discipline','calendar:1'] as $scope)DB::query("INSERT INTO data_checks(scope,checked_at,note) VALUES(?,NOW(),'Test V3') ON DUPLICATE KEY UPDATE checked_at=NOW()",[$scope]);
$m=DB::one('SELECT * FROM matches WHERE id=?',[$mid]);$players=DB::all("SELECT * FROM players WHERE person_number LIKE 'V3-%'");
$r=Regulations::evaluate($m,$players,$ids);ok($r['summary']['status']==='blocked','Six mutés bloqués côté serveur');
$r=Regulations::evaluate($m,$players,array_slice($ids,0,5));ok($r['summary']['status']==='available','Cinq mutés E1');
$other=$m;$other['competition']='Coupe non configurée';ok(Regulations::evaluate($other,$players,[$ids[0]])['summary']['status']==='review','Pas de profil championnat appliqué à une coupe');
DB::query("INSERT INTO disciplinary_events(player_id,team_id,event_date,event_type,review_status) VALUES(?,1,?,'yellow','cancelled'),(?,1,?,'yellow','pending')",[$ids[0],date('Y-m-d'),$ids[0],date('Y-m-d')]);
$report=Reports::build($date,$date,$mid,true);ok(count(array_filter($report['groups'][0]['rows'],fn($r)=>(int)$r['player']['id']===$ids[0]))===0,'Jaunes annulés et provisoires exclus du risque');
DB::query('INSERT INTO squads(match_id,updated_by) VALUES(?,?)',[$mid,$actor]);$sid=(int)DB::conn()->lastInsertId();foreach($ids as $pid)DB::query('INSERT INTO squad_players(squad_id,player_id) VALUES(?,?)',[$sid,$pid]);
$report=Reports::build($date,$date,$mid,true);ok($report['groups'][0]['regulatory']['status']==='blocked','Rapport intègre les quotas');ok(str_starts_with(Reports::pdf($report),'%PDF'),'PDF V3 généré');
DB::query("INSERT INTO matches(fff_match_id,team_id,competition,match_date,status,is_official,counts_for_purge) VALUES('V3-PLAYED',1,'Coupe V3',?,'scheduled',1,0)",[date('Y-m-d',strtotime('-3 days'))]);$past=(int)DB::conn()->lastInsertId();
$payload=['entries'=>[['person_number'=>'V3-TEST','shirt'=>1,'starter'=>true]]];
DB::query("INSERT INTO fmi_uploads(actor_id,match_id,filename,file_key,file_hash,payload,base_revision) VALUES(?,?,'test.pdf',?,?,?,?)",[$actor,$past,str_repeat('a',32),str_repeat('b',64),json_encode($payload),DB::revision()]);$uid=(int)DB::conn()->lastInsertId();
App\Fmi::apply($uid,$actor,['V3-TEST'=>'1'],true);
ok(DB::value('SELECT status FROM matches WHERE id=?',[$past])==='played','FMI fait passer le calendrier à joué');
ok((int)DB::value('SELECT counts_for_purge FROM matches WHERE id=?',[$past])===1,'FMI actualise le compteur de purge');
ok((int)DB::value('SELECT participated FROM match_participations WHERE match_id=?',[$past])===1,'Participation conservée');
$cal="numero match;date;adversaire;statut\nV3-PLAYED;".date('Y-m-d',strtotime('-3 days')).";Test;prevu\n";
$preview=Csv::preview('calendar',1,$cal);ok($preview[0]['data']['status']==='played','Un export prévu ne dégrade pas une FMI jouée');
$otherDate=Csv::preview('calendar',1,str_replace(date('Y-m-d',strtotime('-3 days')),date('Y-m-d',strtotime('-2 days')),$cal));ok($otherDate[0]['action']==='error','Date contradictoire avec FMI bloquée');
try{App\Fmi::apply($uid,$actor,['V3-TEST'=>'1'],true);ok(false,'Réapplication');}catch(RuntimeException $e){ok(true,'Réapplication FMI refusée');}
echo "$n contrôles SQL V3 réussis\n";
+92
View File
@@ -0,0 +1,92 @@
<?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";
+8
View File
@@ -0,0 +1,8 @@
<?php
require dirname(__DIR__).'/bootstrap.php';
if(getenv('ESBSC_TEST_DATABASE')!=='1')exit('Base jetable requise');
$out=$argv[1]??sys_get_temp_dir();$share=json_decode(file_get_contents(sys_get_temp_dir().'/v4-share.json'),true);$share['branding']=App\ClubSettings::branding();
foreach($share['groups'] as &$g)$g['players']=array_map(fn($i)=>['DUPONT Alex','MARTIN Camille','DUPUIS-DESCHAMPS Jean-Baptiste','LE GALL Émilien'][$i%4],range(0,13));unset($g);
file_put_contents($out.'/v4-share.json',json_encode($share));file_put_contents($out.'/v4-convocations.pdf',App\ConvocationExport::pdf($share));file_put_contents($out.'/v4-convocations.xlsx',App\ConvocationExport::xlsx($share));
$raw=base64_decode($share['branding']['logo_pdf']);if(!str_starts_with($raw,"\xff\xd8"))throw new RuntimeException('Normalisation JPEG invalide');
echo "Exports V4 : PDF, Excel et logo normalisé produits.\n";
+77
View File
@@ -0,0 +1,77 @@
"""HTTP checks for the disposable fixture created by tests/v4.php. Standard library only."""
import os,json,re,urllib.request,urllib.parse,http.cookiejar,zipfile,io
from pathlib import Path
from html.parser import HTMLParser
if os.environ.get('ESBSC_TEST_DATABASE')!='1':raise SystemExit('Disposable database required')
BASE=os.environ.get('ESBSC_TEST_URL','http://127.0.0.1:8124')
fixture=json.loads(Path('/tmp/v4-fixture.json').read_text());count=0
class Fields(HTMLParser):
def __init__(self):super().__init__();self.inputs={};self.selects={};self.current=None;self.options=[]
def handle_starttag(self,tag,attrs):
a=dict(attrs)
if tag=='input' and a.get('name'):self.inputs[a['name']]=a.get('value','')
if tag=='select':self.current=a.get('name');self.options=[]
if tag=='option' and self.current:self.options.append(a)
def handle_endtag(self,tag):
if tag=='select' and self.current:self.selects[self.current]=self.options;self.current=None
def fields(html):p=Fields();p.feed(html);return p
def client():return urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))
def request(c,path,data=None,content_type=None):
if isinstance(data,dict):data=urllib.parse.urlencode(data,doseq=True).encode()
r=urllib.request.Request(BASE+path,data=data)
if content_type:r.add_header('Content-Type',content_type)
try:
with c.open(r) as p:return p.status,p.read().decode(),p.geturl()
except urllib.error.HTTPError as e:return e.code,e.read().decode(),e.geturl()
def check(ok,label):
global count;count+=1;assert ok,label;print('HTTP V4',count,label,flush=True)
def login(email):
c=client();_,html,_=request(c,'/login');s,h,url=request(c,'/login',{'csrf':fields(html).inputs['csrf'],'email':email,'password':'V4-local-test-password'});print('LOGIN FAILURE',s,url,re.sub('<[^>]+>',' ',h)[-1000:]) if not (s==200 and '/login' not in url) else None;check(s==200 and '/login' not in url,'Connexion '+email);return c
admin=login('v4-admin@example.test')
for path in ['/','/players','/staff','/matches','/spond','/settings','/seasons','/regulations','/imports','/users','/convocations?week='+fixture['date'],'/squad?match_id='+str(fixture['mid'][0])]:
code,html,_=request(admin,path);check(code==200 and 'Fatal error' not in html and 'Warning:' not in html,path+' rendu sans erreur')
code,html,_=request(admin,'/squad?match_id='+str(fixture['mid'][0]));check('DUPONT Alex' in html and 'data-profile-player="1"' in html and 'Spond :' in html,'Double profil et disponibilités dans préparation')
csrf=fields(html).inputs['csrf'];code,_,_=request(admin,'/settings/save',{'csrf':'invalide'});check(code==422,'CSRF refusé')
viewer=login('v4-viewer@example.test');_,h,_=request(viewer,'/');viewer_csrf=fields(h).inputs['csrf'];code,_,_=request(viewer,'/spond/apply',{'csrf':viewer_csrf,'batch_id':1});check(code==422,'Lecture seule ne peut importer Spond')
# Synthetic workbook: first sheet deliberately invalid for import, correct second sheet only.
b=io.BytesIO()
with zipfile.ZipFile(b,'w',zipfile.ZIP_DEFLATED) as z:
z.writestr('xl/workbook.xml','<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="À imprimer" sheetId="1" r:id="rId1"/><sheet name="À importer" sheetId="2" r:id="rId2"/></sheets></workbook>')
z.writestr('xl/_rels/workbook.xml.rels','<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Target="worksheets/sheet2.xml"/></Relationships>')
z.writestr('xl/worksheets/sheet1.xml','this sheet must never be parsed')
rows={4:['Statut','Nom','Adresse e-mail','Téléphone','Délai de réponse'],5:['Participe','Alex Dupont','test@example.test','0612345678',fixture['season'][:4]+'-09-26 14:00:00'],6:['Sans réponse','Camille Martin','','',''],7:['Ne peut pas participer','Personne inconnue','','','']}
from xml.sax.saxutils import escape
xml='<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>'
for n,values in rows.items():xml+='<row r="%s">'%n+''.join('<c r="%s%s" t="inlineStr"><is><t>%s</t></is></c>'%(chr(65+i),n,escape(v)) for i,v in enumerate(values))+'</row>'
z.writestr('xl/worksheets/sheet2.xml',xml+'</sheetData></worksheet>')
boundary='esbsc-test-boundary';parts=[]
for k,v in {'csrf':csrf,'week':fixture['date'],'match_id':'0'}.items():parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{k}"\r\n\r\n{v}\r\n'.encode())
parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="xlsx"; filename="spond-test.xlsx"\r\nContent-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\r\n\r\n'.encode()+b.getvalue()+b'\r\n');parts.append(f'--{boundary}--\r\n'.encode())
code,html,url=request(admin,'/spond/preview',b''.join(parts),'multipart/form-data; boundary='+boundary);check(code==200 and 'Aperçu · spond-test.xlsx' in html,'Upload lit exclusivement la deuxième feuille')
f=fields(html);check(f.selects['choices[0]'][int(fixture['ids'][0])+1].get('selected') is not None if False else 'Correspondance mémorisée' in html,'Correspondance précédente proposée')
code,html,_=request(admin,'/spond/apply',{'csrf':csrf,'batch_id':f.inputs['batch_id'],'choices[0]':fixture['ids'][0],'choices[1]':fixture['ids'][1],'choices[2]':'skip'});check(code==200 and 'Enregistrement effectué.' in html,'Import confirmé avec inconnu explicitement ignoré')
code,html,_=request(admin,'/convocations?week='+fixture['date']);check('Spond : Présent' in html and 'Spond : Sans réponse' in html and 'data-spond-filter' in html,'Disponibilités et filtres des non-convoqués')
# Profile settings variant save/read round trip.
code,html,_=request(admin,'/regulations');rev=fields(html).inputs['revision']
form={'csrf':csrf,'revision':rev,'team_id':4,'season':fixture['season'],'competition':'V4 championnat','mutation_base':4,'mutation_bonus':0,'outside_limit':2,'max_players':14,'ten_limit':3,'ten_from':fixture['season'][:4]+'-10-01','ten_rule':'on','championship':'on','special_higher_enabled':'on','confirmed':'on','reference':'Texte de test uniquement : profil confirmé sur base jetable'}
code,html,_=request(admin,'/regulations/save',form);check(code==200 and 'V4 championnat' in html,'Enregistrement profil V4')
# Archive switch is readable but rejects mutation.
next_season=str(int(fixture['season'][:4])+1)+'/'+str(int(fixture['season'][:4])+2)
code,html,_=request(admin,'/seasons/select',{'csrf':csrf,'season':next_season});check(code==200 and 'en consultation' in html,'Sélecteur affiche archive')
code,html,_=request(admin,'/settings/save',{'csrf':csrf});check(code==422 and 'archivée' in html,'Mutation refusée depuis archive')
request(admin,'/seasons/select',{'csrf':csrf,'season':fixture['season']})
code,html,_=request(admin,'/auth/callback?state=bad&code=bad');check(code==422 and 'invalide' in html,'Callback OpenID sans état valide refusé')
# Exercise the actual multipart logo uploader and GD normalization.
import zlib,struct,binascii
w,h=600,300
def chunk(k,data):return struct.pack('>I',len(data))+k+data+struct.pack('>I',binascii.crc32(k+data)&0xffffffff)
raw=b''.join(b'\x00'+(b'\x20\x4b\x38' if y<150 else b'\xee\xee\xee')*w for y in range(h))
png=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',w,h,8,2,0,0,0))+chunk(b'IDAT',zlib.compress(raw))+chunk(b'IEND',b'')
parts=[]
for k,v in {'csrf':csrf,'name':'Club de test V4','short_name':'CLUB TEST','fff_number':'520480','primary':'#204b38','accent':'#296b45','default_venue':'Terrain principal','slot_minutes':'150'}.items():parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{k}"\r\n\r\n{v}\r\n'.encode())
parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="logo"; filename="logo.png"\r\nContent-Type: image/png\r\n\r\n'.encode()+png+b'\r\n');parts.append(f'--{boundary}--\r\n'.encode())
code,html,_=request(admin,'/settings/save',b''.join(parts),'multipart/form-data; boundary='+boundary);check(code==200 and 'Enregistrement effectué.' in html and 'data:image/png;base64,' in html,'Logo PNG uploadé, normalisé et affiché')
code,css,_=request(client(),'/brand.css');check(code==200 and '#204b38' in css,'Palette personnalisée disponible sur connexion')
print('HTTP V4 OK',count)
+26
View File
@@ -0,0 +1,26 @@
<?php
/** Run seed against a migrated V3 database, then migrate V4, then verify. Disposable DB only. */
require dirname(__DIR__).'/bootstrap.php';
use App\{DB,Seasons,ClubRoles};
if(getenv('ESBSC_TEST_DATABASE')!=='1')exit('Base jetable requise');
if(($argv[1]??'')==='seed'){
DB::query("INSERT INTO users(name,email,password_hash,role,must_change_password) VALUES('Admin','upgrade@example.test','inutilisable','admin',0)");$actor=DB::conn()->lastInsertId();
DB::query("INSERT INTO players(person_number,licence_number,last_name,first_name,active,member_role,usual_team_id) VALUES('1100000999','12345678','LEGACY','Alex',1,'player_staff',2)");$p=DB::conn()->lastInsertId();
$season=App\Regulations::season(date('Y-m-d'));DB::query("INSERT INTO person_licences(player_id,season,licence_number,licence_type) VALUES(?,?,?,'Libre')",[$p,$season,'12345678']);DB::query("INSERT INTO person_licences(player_id,season,licence_number,licence_type) VALUES(?,?,?,'Dirigeant')",[$p,$season,'87654321']);
DB::query("INSERT INTO person_roles(player_id,role_id,team_id) VALUES(?,(SELECT id FROM club_roles WHERE kind='sport' LIMIT 1),2)",[$p]);
DB::query("INSERT INTO matches(fff_match_id,team_id,match_date,opponent,competition,home_away,status,counts_for_purge) VALUES('UPGRADE',2,?,'Adversaire','Championnat','home','played',1)",[date('Y-m-d',strtotime('-7 days'))]);$mid=DB::conn()->lastInsertId();
DB::query("INSERT INTO sanctions(player_id,sanction_type,status,effective_date,matches_required,label) VALUES(?,'commission','official',?,4,'Décision à conserver')",[$p,date('Y-m-d',strtotime('-14 days'))]);
DB::query("INSERT INTO fmi_uploads(actor_id,match_id,filename,file_key,file_hash,payload,base_revision,status) VALUES(?,?,'fixture.pdf',?,?,?,1,'applied')",[$actor,$mid,str_repeat('a',32),str_repeat('b',64),'{}']);$fid=DB::conn()->lastInsertId();
DB::query('INSERT INTO match_participations(match_id,player_id,upload_id,shirt_number,starter,participated) VALUES(?,?,?,9,1,1)',[$mid,$p,$fid]);
DB::query('INSERT INTO squads(match_id,updated_by) VALUES(?,?)',[$mid,$actor]);$sid=DB::conn()->lastInsertId();DB::query('INSERT INTO squad_players VALUES(?,?)',[$sid,$p]);DB::query('INSERT INTO squad_staff VALUES(?,?)',[$sid,$p]);
DB::query("INSERT INTO reports(title,match_id,generated_by,revision,snapshot) VALUES('Archive',?,?,1,?)",[$mid,$actor,'{"fixture":"conserver"}']);
echo "Fixture V3 créée : double licence, staff, FMI, sanction, groupe et rapport.\n";
}else{
$p=DB::one("SELECT * FROM players WHERE person_number='1100000999'");
foreach(['person_licences'=>2,'person_roles'=>1,'matches'=>1,'sanctions'=>1,'fmi_uploads'=>1,'match_participations'=>1,'squads'=>1,'squad_players'=>1,'squad_staff'=>1,'reports'=>1] as $table=>$n)if((int)DB::value("SELECT COUNT(*) FROM $table")!==$n)throw new RuntimeException('Perte de données : '.$table);
if(DB::value('SELECT snapshot FROM reports')!=='{"fixture":"conserver"}')throw new RuntimeException('Rapport modifié');
$members=Seasons::decorate([$p]);if(count($members)!==1||$members[0]['usual_team_id']!=2||$members[0]['member_role']!=='player_staff')throw new RuntimeException('Effectif migré incorrectement');
if(count(ClubRoles::index()[$p['id']]??[])!==1)throw new RuntimeException('Staff non migré');
$m=DB::one("SELECT * FROM matches WHERE fff_match_id='UPGRADE'");$check=App\Eligibility::check($p,2,date('Y-m-d'));if($check['details'][0]['remaining']!==3)throw new RuntimeException('Purge modifiée');
echo "Migration réelle V3 → V4 : historiques, double profil et purge 1/4 conservés.\n";
}
+54
View File
@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
require dirname(__DIR__).'/bootstrap.php';
use App\{Xlsx,FootclubsCalendar};
$n=0;
function ok(bool $condition,string $label): void {global $n;$n++;if(!$condition)throw new RuntimeException($label);echo "OK XLSX $n - $label\n";}
function rejects(callable $fn,string $label): void {try{$fn();}catch(RuntimeException $e){ok(true,$label);return;}ok(false,$label);}
/** Minimal wire-format fixtures, including malformed cases; never user deliverables. */
function fixture(string $rows,string $styles='',bool $epoch=false,string $shared=''): string {
$p=tempnam(sys_get_temp_dir(),'esbsc-xlsx-');$z=new ZipArchive();$z->open($p,ZipArchive::OVERWRITE);
$ns='http://schemas.openxmlformats.org/spreadsheetml/2006/main';
$z->addFromString('xl/workbook.xml','<x:workbook xmlns:x="'.$ns.'" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><x:workbookPr date1904="'.($epoch?'1':'0').'"/><x:sheets><x:sheet name="Données" sheetId="1" r:id="r1"/></x:sheets></x:workbook>');
$z->addFromString('xl/_rels/workbook.xml.rels','<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="r1" Target="/xl/worksheets/sheet.xml"/></Relationships>');
$z->addFromString('xl/worksheets/sheet.xml','<x:worksheet xmlns:x="'.$ns.'"><x:sheetData>'.$rows.'</x:sheetData></x:worksheet>');
if($styles!=='')$z->addFromString('xl/styles.xml',$styles);
if($shared!=='')$z->addFromString('xl/sharedStrings.xml',$shared);
$z->close();return $p;
}
function textCell(string $ref,string $v): string {return '<x:c r="'.$ref.'" t="inlineStr"><x:is><x:t>'.htmlspecialchars($v,ENT_XML1,'UTF-8').'</x:t></x:is></x:c>';}
$styles='<x:styleSheet xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><x:numFmts><x:numFmt numFmtId="164" formatCode="000000"/></x:numFmts><x:cellXfs><x:xf numFmtId="0"/><x:xf numFmtId="14"/><x:xf numFmtId="20"/><x:xf numFmtId="164"/></x:cellXfs></x:styleSheet>';
$heads='<x:row r="1">'.textCell('A1','Date').textCell('B1','Heure').textCell('C1','Licence').textCell('D1','Nom').'</x:row>';
$row='<x:row r="2"><x:c r="A2" s="1"><x:v>45292</x:v></x:c><x:c r="B2" s="2"><x:v>0.84375</x:v></x:c><x:c r="C2" s="3"><x:v>123</x:v></x:c>'.textCell('D2','Éric & André').'</x:row>';
$p=fixture($heads.$row,$styles);try{
$r=Xlsx::read($p);$d=$r['rows'][0]['data'];
ok($r['sheet']==='Données','Nom de feuille et XML avec préfixes');
ok($d['date']==='2024-01-01','Date numérique Excel 1900');
ok($d['heure']==='20:15:00','Heure numérique Excel');
ok($d['licence']==='000123','Zéros initiaux selon le format');
ok($d['nom']==='Éric & André','Accents et entités XML');
rejects(fn()=>Xlsx::read($p,'Inconnu'),'Onglet inconnu refusé');
rejects(fn()=>Xlsx::read($p,'',0),'Ligne des titres invalide refusée');
}finally{unlink($p);}
$p=fixture($heads.str_replace('45292','0',$row),$styles,true);try{ok(Xlsx::read($p)['rows'][0]['data']['date']==='1904-01-01','Calendrier Excel 1904');}finally{unlink($p);}
$p=fixture($heads.str_replace('45292','60',$row),$styles);try{rejects(fn()=>Xlsx::read($p),'Date Excel fictive de 1900 rejetée');}finally{unlink($p);}
$p=fixture($heads.str_replace('<x:v>45292</x:v>','<x:f>NOW()</x:f><x:v>45292</x:v>',$row),$styles);try{rejects(fn()=>Xlsx::read($p),'Formule non exécutée et refusée');}finally{unlink($p);}
$p=fixture('<x:row r="1">'.textCell('A1','Titre du rapport').'</x:row>'.str_replace('r="1"','r="3"',str_replace(['A1','B1','C1','D1'],['A3','B3','C3','D3'],$heads)).str_replace(['r="2"','A2','B2','C2','D2'],['r="4"','A4','B4','C4','D4'],$row),$styles);try{ok(Xlsx::read($p,'',3)['rows'][0]['line']===4,'Titres situés après des lignes introductives');}finally{unlink($p);}
$p=fixture('<x:row r="1">'.textCell('A1','Nom').textCell('B1','Nom').'</x:row>');try{rejects(fn()=>Xlsx::read($p),'En-têtes dupliqués rejetés');}finally{unlink($p);}
$p=fixture('<x:row r="1">'.textCell('A1','Nom').'</x:row><x:row r="2"><x:c r="A2" t="s"><x:v>0</x:v></x:c></x:row>','',false, '<x:sst xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><x:si><x:r><x:t>Éric</x:t></x:r><x:r><x:t> Dupont</x:t></x:r></x:si></x:sst>');
try{ok(Xlsx::read($p)['rows'][0]['data']['nom']==='Éric Dupont','Texte partagé avec plusieurs segments');}finally{unlink($p);}
$file=$argv[1]??getenv('FOOTCLUBS_CALENDAR_FILE');
if($file){
$rows=Xlsx::read($file)['rows'];ok(count($rows)===25,'Fichier transmis : 25 rencontres lues');
$normalized=array_map(fn($r)=>FootclubsCalendar::normalize($r['data'],'E1',true),$rows);
ok(count(array_filter($normalized,fn($r)=>$r['statut']==='played'))===3,'Trois résultats après confirmation explicite');
ok(count(array_filter($normalized,fn($r)=>$r['statut']==='scheduled'))===22,'Vingt-deux rencontres sans résultat restent prévues');
$byId=array_column($normalized,null,'numero_match');
ok($byId['56085584']['heure']==='20:15'&&$byId['56085584']['home_away']==='away','Périgny : 20H15 et extérieur');
ok($byId['79131186']['adversaire']==='BRESSUIRE FC 1'&&$byId['79131186']['home_away']==='home','Adversaire et domicile reconnus');
rejects(fn()=>FootclubsCalendar::normalize($rows[0]['data'],'E2',true),'Fichier E1 refusé si E2 sélectionnée');
rejects(fn()=>FootclubsCalendar::normalize($rows[0]['data'],'E1',false),'Un score seul ne prouve pas une purge');
$special=$rows[0]['data'];$special['reporte_rejoue']='Reporté';rejects(fn()=>FootclubsCalendar::normalize($special,'E1',true),'Report ambigu signalé');
$special=$rows[0]['data'];$special['date_du_match_2']='13/09/2026';rejects(fn()=>FootclubsCalendar::normalize($special,'E1',true),'Deux dates contradictoires signalées');
}
echo "$n tests Excel réussis.\n";
+19
View File
@@ -0,0 +1,19 @@
<?php
require dirname(__DIR__).'/bootstrap.php';
use App\{DB,Csv,Xlsx};
if(getenv('ESBSC_TEST_DATABASE')!=='1')exit('Base test requise');
function ok($v,$m){if(!$v)throw new RuntimeException($m);echo "OK $m\n";}
$actor=(int)DB::value('SELECT id FROM users LIMIT 1');
$raw=Xlsx::read($argv[1])['rows'];$rows=Csv::previewRows('discipline',0,$raw);
foreach($rows as $r)if($r['error'])throw new RuntimeException($r['error']);
ok(count(array_filter($rows,fn($r)=>($r['target']??'')==='yellow'))===8,'Huit cartons jaunes reconnus, staff inclus');
$apply=function($rows)use($actor){DB::query('INSERT INTO import_batches(actor_id,kind,filename,fingerprint,payload,base_revision) VALUES(?,?,?,?,?,?)',[$actor,'discipline','yellow.xlsx',hash('sha256',json_encode($rows)),json_encode($rows),DB::revision()]);Csv::apply((int)DB::conn()->lastInsertId(),$actor);};
$apply($rows);$before=DB::value("SELECT COUNT(*) FROM disciplinary_events WHERE source='footclubs_import'");
$again=Csv::previewRows('discipline',0,$raw);ok(count(array_filter($again,fn($r)=>($r['target']??'')==='yellow'&&$r['action']==='unchanged'))===8,'Réimport des huit jaunes identique');$apply($again);
ok(DB::value("SELECT COUNT(*) FROM disciplinary_events WHERE source='footclubs_import'")===$before,'Aucun doublon');
ok((int)DB::value("SELECT COUNT(*) FROM sanctions WHERE external_ref IN ('23990107','24010813','24006253','24010810','24010500','24010811','24022315','24022317')")===0,'Aucun jaune transformé en suspension');
ok(DB::value("SELECT warning_end_date FROM disciplinary_events WHERE source_ref='footclubs:23990107'")==='2026-11-29','Fin officielle du jaune ADAM conservée');
ok(DB::value("SELECT warning_effective_date FROM disciplinary_events WHERE source_ref='footclubs:24010813'")==='2026-09-06','Effet officiel du jaune BARBIER conservé');
DB::query("UPDATE disciplinary_events SET review_status='cancelled',review_reason='Correction justifiée pour test' WHERE source_ref='footclubs:23990107'");
$cancelled=Csv::previewRows('discipline',0,$raw);ok(count(array_filter($cancelled,fn($r)=>str_contains($r['error']??'','annulé manuellement')))===1,'Un réimport ne réactive pas un jaune annulé');