admin.php 62.8 KB
Newer Older
1
<?php
2
namespace Controller;
3 4 5 6

use LQDN\Command\AdminCreateCommand;
use LQDN\Command\AdminDeleteCommand;
use LQDN\Command\AdminChangePasswordCommand;
7
use LQDN\Command\CounterpartCreateCommand;
8 9 10
use LQDN\Command\DonationValidateCommand;
use LQDN\Command\DonationInvalidateCommand;
use LQDN\Command\DonationResetPdfCommand;
okhin's avatar
okhin committed
11
use LQDN\Command\DonationCreateCommand;
12
use LQDN\Command\UserUpdateByAdminCommand;
13
use LQDN\Command\UserCreateCommand;
14
use LQDN\Command\UserUpdateCumulCommand;
15
use LQDN\Command\AdminUpdateTotalUsersCommand;
16 17 18 19 20 21 22

class Admin extends Controller
{
    // Fonction appelée avant routage
    public function beforeRoute($f3, $args)
    {
        parent::beforeRoute($f3, $args);
23 24 25 26

        // Template de base par défaut
        $this->template = "backend/base.html";

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
        // URL de base à utiliser sur le site
        $f3->set('DONS_STATUTS', array(
            0 => "Ponctuel non validé",
            1 => "Ponctuel validé",
            4 => "Récurrent validé",
            42 => "En cours de traitement",
            100 => "Récurrent non validé",
            101 => "Récurrent validé",
            102 => "Récurrent remis",
        ));

        $f3->set('CT_STATUTS', array(
            1 => "Demandé",
            2 => "Envoyé",
            3 => "NPAI",
            99 => "Annulé",
        ));

        $f3->set('CB_STATUTS', array(
            1 => "en cours",
            2 => "à relancer",
            3 => "relancé",
            99 => "résilié",
            100 => "non applicable",
        ));
52
        
53
        $f3->set('TAILLES', array(
54
            0 => _('PlaceHolder -- ne pas utiliser') . ' S',
55 56 57 58 59 60 61 62 63 64 65 66
            1 => _('Coupe Homme, Taille') . ' S',
            2 => _('Coupe Homme, Taille') . ' M',
            3 => _('Coupe Homme, Taille') . ' L',
            4 => _('Coupe Homme, Taille') . ' XL',
            5 => _('Coupe Femme, Taille') . ' S',
            6 => _('Coupe Femme, Taille') . ' M',
            7 => _('Coupe Femme, Taille') . ' L',
            8 => _('Coupe Femme, Taille') . ' XL',
            9 => _('Coupe Homme, Taille') . ' XXL',
            10 => _('Coupe Femme, Taille') . ' XXL',
        ));

67 68 69
        if (!$f3->get('SESSION.admin')) {
            $mapper = new\DB\SQL\Mapper($f3->get('DB'), 'admins');
            $auth = new \Auth($mapper, array('id'=>'user_id', 'pw'=>'password'));
70
            $success = $auth->basic('\Controller\Admin::hash_password');
71
            if (!$success) {
72
                $f3->push('SESSION.error', 'Accès non autorisé');
okhin's avatar
okhin committed
73
                $f3->push('SESSION.message', '');
74 75 76 77 78 79 80 81 82
                $f3->error(401);
            } else {
                $f3->set('SESSION.admin', true);
            }
        };

        $f3->set('PIPLOME_URL', PIPLOME_URL);
    }

83 84
    public function afterRoute($f3, $args)
    {
85 86 87 88 89 90 91 92
        // Test si il y a des messages
        if (!$f3->exists('SESSION.message')) {
            $f3->push('SESSION.message', '');
        }
        if (!$f3->exists('SESSION.error')) {
            $f3->push('SESSION.error', '');
        }

93 94 95 96 97 98 99 100 101
        // Rendu de la page
        if ($this->template!='') {
            echo \Template::instance()->render($this->template);
        }
        // Une fois que tout est affiché, on peut supprimer les notifications
        $f3->clear('SESSION.message');
        $f3->clear('SESSION.error');
    }

102

103 104 105 106 107 108 109 110 111
    public static function hash_password($password)
    {
        return hash('sha256', $password);
    }

    public function show($f3, $args)
    {
        if ($f3->get('VERB')=='POST' && $f3->exists('POST.action')) {
            switch ($f3->get('POST.action')) {
okhin's avatar
okhin committed
112 113 114 115 116 117 118 119 120
            case 'valid':
                $f3->get('container')['command_handler']->handle(new DonationValidateCommand($f3->get('POST.id')));
                break;
            case 'invalid':
                $f3->get('container')['command_handler']->handle(new DonationInvalidateCommand($f3->get('POST.id')));
                break;
            case 'pdf':
                $f3->get('container')['command_handler']->handle(new DonationResetPdfCommand($f3->get('POST.id')));
                break;
121 122 123 124 125 126 127 128
            }
        }

        $text = $f3->exists('POST.texte') ? $f3->get('POST.texte') : '';
        $sum = $f3->exists('POST.somme') ? $f3->get('POST.somme') : '';
        $public = $f3->exists('POST.public') ? $f3->get('POST.public') : '';
        $status = $f3->exists('POST.status') ? $f3->get('POST.status') : '';
        $limit = $f3->exists('POST.limite') ? (int) $f3->get('POST.limite') : 50;
okhin's avatar
okhin committed
129
        $page = $f3->exists('POST.page') ? (int) $f3->get('POST.page') : 1;
130 131
        $date1 = $f3->exists('POST.date1') ? (string) $f3->get('POST.date1') . " 00:00:00" : '';
        $date2 = $f3->exists('POST.date2') ? (string) $f3->get('POST.date2') . " 00:00:00" : date("Y-m-d H:i:s");
132

133
        $results = $f3->get('container')['donation_finder']->adminSearch($text, $sum, $public, $status, $date1, $date2, $limit, $page);
134 135 136 137 138

        $f3->set('row_count', count($results));
        $f3->set('texte', $text);
        $f3->set('somme', $sum);
        $f3->set('limite', $limit);
okhin's avatar
okhin committed
139
        $f3->set('page', $page);
140 141
        $f3->set('public', $public);
        $f3->set('status', $status);
142 143
        $f3->set('date1', substr($date1, 0, 10));
        $f3->set('date2', substr($date2, 0, 10));
144 145 146 147 148 149
        $f3->set('data', $results);
        $f3->set('piplome_url', PIPLOME_URL);

        $f3->set('block_content', 'backend/dons.html');
    }

okhin's avatar
okhin committed
150 151
    public function validate($f3, $args)
    {
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
        $id = '';
        $error = '';
        $db = $f3->get('DB');
        if ($f3->get('VERB')=='GET') {
            if ($f3->exists('PARAMS.id')) {
                $id = $f3->get('PARAMS.id');
            } else {
                $error= 'Pas d\'id associé à ce don';
            }
            if ($id != '') {
                $result = $db->query("SELECT status,
                    somme,
                    adresse_id,
                    user_id
                    FROM dons
                    WHERE id = ".\Utils::asl($id));
                $result = $result->fetch(\PDO::FETCH_ASSOC);
                $user_amount = $db->query("SELECT total, cumul FROM users
                    WHERE id = ".\Utils::asl($result['user_id']));
                $user_amount = $user_amount->fetch(\PDO::FETCH_ASSOC);
            }
            if ($result['status'] >= 100) {
                $status = 101;
            } else {
                $status = 1;
            }
            $total = $user_amount['total'] + $result['somme'];
            $cumul = $user_amount['total'] + $result['somme'];
        }
        if ($error != '') {
182
            $f3->push('SESSION.error', $error);
183
        } else {
okhin's avatar
okhin committed
184 185
            $db->query(
                "UPDATE dons
186 187
                SET status = $status
                WHERE id = ".\Utils::asl($id)
okhin's avatar
okhin committed
188
            );
189 190 191 192 193 194 195 196 197
            $db->query("UPDATE users
                SET total = $total,
                cumul = $cumul
                WHERE id = ".\Utils::asl($result['user_id']));
        }
        $f3->reroute("/admin/users/".$result['user_id']);
    }


okhin's avatar
okhin committed
198 199
    public function invalidate($f3, $args)
    {
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
        $id = '';
        $error = '';
        $db = $f3->get('DB');
        if ($f3->get('VERB')=='GET') {
            if ($f3->exists('PARAMS.id')) {
                $id = $f3->get('PARAMS.id');
            } else {
                $error= 'Pas d\'id associé à ce don';
            }
            if ($id != '') {
                $result = $db->query("SELECT status,
                    somme,
                    adresse_id,
                    user_id
                    FROM dons
                    WHERE id = ".\Utils::asl($id));
                $result = $result->fetch(\PDO::FETCH_ASSOC);
                $user_amount = $db->query("SELECT total, cumul FROM users
                    WHERE id = ".\Utils::asl($result['user_id']));
                $user_amount = $user_amount->fetch(\PDO::FETCH_ASSOC);
            }
            if ($result['status'] >= 100) {
                $status = 100;
            } else {
                $status = 0;
            }
            $total = $user_amount['total'] - $result['somme'];
            $cumul = $user_amount['total'] - $result['somme'];
            if ($cumul < 0) {
                $error = "Impossible d'invalider, une contrepartie a été demandée";
            }
        }
        if ($error != '') {
233
            $f3->push('SESSION.error', $error);
234
        } else {
okhin's avatar
okhin committed
235 236
            $db->query(
                "UPDATE dons
237 238
                SET status = $status
                WHERE id = ".\Utils::asl($id)
okhin's avatar
okhin committed
239
            );
240 241 242 243 244 245 246 247
            $db->query("UPDATE users
                SET total = $total,
                cumul = $cumul
                WHERE id = ".\Utils::asl($result['user_id']));
        }
        $f3->reroute("/admin/users/".$result['user_id']);
    }

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
    public function support($f3, $args)
    {
        $id = '';
        $pseudo = '';
        $email = '';
        $somme = '';
        $lang = '';
        $abo = '0';
        $public = '0';
        $user_id = '';
        $msg = '';
        $adresse_id = '';
        $db = $f3->get('DB');
        if ($f3->get('VERB')=='GET') {
            if ($f3->exists('PARAMS.id')) {
                $id = $f3->get('PARAMS.id');
            }
265
            $f3->set('block_content', 'backend/don.html');
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
        } else {
            $id = $f3->get('POST.id');
            $pseudo = $f3->get('POST.pseudo');
            $email = $f3->get('POST.email');
            $somme = $f3->get('POST.somme');
            $lang = $f3->get('POST.lang');
            if ($f3->exists('POST.abo')) {
                $abo = '1';
            }
            if ($f3->exists('POST.public')) {
                $public = '1';
            }

            // Champs minimaux : pseudo, somme, email
            if ($pseudo=='' or $somme=='' or $email=='') {
                $msg = "Erreur: Les champs 'Pseudo', 'Montant' et 'Email' sont obligatoires";
            } else {
                // Mise à jour ou ajout du don
                if ($id=='') {
                    // We need to check if there's already a user with this email
                    $result = $db->query("SELECT id
okhin's avatar
okhin committed
287 288
                        FROM users
                        WHERE email='".\Utils::asl($email)."'");
289 290
                    if ($result) {
                        // The user already exist, lets get the user_id
291
                        $user_id = $result->fetch(\PDO::FETCH_ASSOC);
292 293 294 295
                        $user_id = $user_id['id'];
                    } else {
                        // Let's create the account first
                        $db->query("INSERT INTO users
okhin's avatar
okhin committed
296 297 298 299 300 301 302 303
                            (email,
                            pseudo,
                            cumul,
                            total)
                            VALUES('".\Utils::asl($email)."',
                                '".\Utils::asl($pseudo)."',
                                '".\Utils::asl($somme)."',
                                '0')");
304 305 306
                        $user_id = $db->lastInsertId();
                    }
                    $db->query("INSERT INTO dons
okhin's avatar
okhin committed
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
                        (datec,
                        user_id,
                        somme,
                        lang,
                        abo,
                        public,
                        status)
                        VALUES
                        (now(),
                            '".\Utils::asl($user_id)."',
                            '".\Utils::asl($somme)."',
                            '".\Utils::asl($lang)."',
                            '".\Utils::asl($abo)."',
                            '".\Utils::asl($public)."',
                            1)");
322 323 324 325 326
                    // Récupération de l'id pour passage en mode édition
                    $id = $db->lastInsertId();
                } else {
                    // We will get the ids associated to the gift first
                    $result = $db->query("SELECT adresse_id,
okhin's avatar
okhin committed
327 328 329
                        user_id
                        FROM dons
                        WHERE id = ".\Utils::asl($f3->get('POST.id')));
330
                    $result = $result->fetch(\PDO::FETCH_ASSOC);
331 332
                    // Let's update the adresse first or create the adress
                    $db->query("UPDATE users
okhin's avatar
okhin committed
333 334 335
                        SET email='".\Utils::asl($email)."',
                        pseudo='".\Utils::asl($pseudo)."'
                        WHERE id={$result['user_id']}");
336
                    $db->query("UPDATE dons
okhin's avatar
okhin committed
337 338 339 340 341 342
                        SET somme='".\Utils::asl($somme)."',
                        lang='".\Utils::asl($lang)."',
                        abo='".\Utils::asl($abo)."',
                        public='".\Utils::asl($public)."', 
                        adresse_id='".$result['adresse_id']."'
                        WHERE id='".\Utils::asl($_POST['id'])."'");
343 344 345 346 347 348 349
                }
            }
        }

        if ($id!='') {
            // Récupération du don, de l'adresse et de l'utilisateur
            $result = $db->query("SELECT d.id AS id,
okhin's avatar
okhin committed
350 351 352 353 354 355 356 357 358 359 360
                u.email AS email,
                u.pseudo AS pseudo,
                d.somme AS somme,
                d.lang AS lang,
                d.abo AS abo,
                d.public AS public,
                d.adresse_id AS adresse_id,
                d.user_id AS user_id
                FROM dons d
                JOIN users u ON u.id = d.user_id
                WHERE d.id=".$id);
361
            $don = $result->fetch(\PDO::FETCH_ASSOC);
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
        } else {
            $don = array(
                'id'=>$id,
                'email'=>$email,
                'pseudo'=>$pseudo,
                'somme'=>$somme,
                'lang'=>$lang,
                'abo'=>$abo,
                'public'=>$public,
                'user_id'=>$user_id,
            );
        }

        $f3->set('id', $id);
        $f3->set('msg', $msg);
        $f3->set('don', $don);

        $f3->set('block_content', 'backend/don.html');
    }

    public function counterparts_dashboard($f3, $args)
    {
        $db = $f3->get('DB');
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
        $f3->set('counterparts_import', '');
        $total = array("hoopie" => 0, "pishirt" => 0, "pibag" => 0, "piplome" => 0);


        if ($f3->get('VERB') == 'POST') {
            $separator = ';';
            // Si on a un POST sur cette page, c'est que l'on a un csv à parser
            if ($_FILES['file']['tmp_name'] == '') {
                $f3->push('SESSION.error', 'Veuillez uploader un fichier au format csv');
            } else {
                // Lecture du fichier
                if (($handle = fopen($_FILES['file']['tmp_name'], "r")) !== false) {
                    // D'abord le header : email / quoi
                    $fields = fgetcsv($handle, 1000, $separator);
                    $mail_idx = -1;
                    $quoi_idx = -1;
                    foreach ($fields as $key => $value) {
                        if ($value == "Quoi") {
                            $quoi_idx = $key;
                        }
                        if ($value == "Mail") {
                            $mail_idx = $key;
                        }
                    }

                    // On tourne sur le fichier maintenant
                    while (($data = fgetcsv($handle, 1000, $separator)) !== false) {
                        // Récupération des données
                        $mail = $data[$mail_idx];
                        $quoi = $data[$quoi_idx];

                        // On cherche l'utilisateur
                        $user = $f3->get('container')['user_finder']->findByEmail($mail);
                        // Et son addresse
                        $adresse = $f3->get('container')['address_finder']->findByUserId($user['id']);

                        if (count($user) >= 1 and is_array($user)) {
                            // On a un utilisateur, cool
                            // On crée une contrepartie, si son cumul est suffisant
                            switch ($quoi) {
                            case 'hoodie':
                                $needed = 250;
                                break;
                            case 'pishirt':
                                $needed = 100;
                                break;
                            case 'pibag':
                                $needed = 50;
                                break;
                            case 'piplome':
                                $needed = 30;
                                break;
                            }
                            if ($user['cumul'] >= $needed) {
                                // Assez de point, on crée
                                $f3->get('container')['command_handler']->handle(new CounterpartCreateCommand($adresse['id'], $user['id'], $quoi, 1, 2, date("Y-m-d H:i:s"), 'Imported from a file'));
                                // On mets à jour le cumul de l'utilisateur
                                $f3->get('container')['command_handler']->handle(new UserUpdateCumulCommand($user['id'], $user['cumul'] - $needed));
                                $total[$quoi] +=1;
                            } else {
                                $f3->push('SESSION.error', 'Pas assez de cumul pour un '.$quoi.' avec l\'email'.$mail);
                            }
                        } else {
                            $f3->push('SESSION.error', 'Pas d\'utilisateur avec l\'adresse '.$mail);
                        }
                    }
                    fclose($handle);
                }
            } // Fin de l'import CSV
            $f3->set('counterparts_import', $total);
        }

457 458 459 460
        // On définit des valeurs par défaut
        $query = "SELECT DISTINCT quoi FROM contreparties;";
        $result = $db->query($query);
        if ($result) {
461
            foreach ($result->fetchAll(\PDO::FETCH_ASSOC) as $row) {
462 463 464 465 466 467
                $f3->set($row['quoi'].'_s1', 0);
                $f3->set($row['quoi'].'_s2', 0);
            }
        }
        // Calcul des quantités
        $query = "SELECT quoi,
okhin's avatar
okhin committed
468 469 470 471
            status,
            COUNT(status) AS qte
            FROM contreparties
            GROUP BY quoi, status;";
472 473
        $result = $db->query($query);
        if ($result) {
474
            foreach ($result->fetchAll(\PDO::FETCH_ASSOC) as $row) {
475 476 477 478 479 480 481 482 483
                $f3->set($row['quoi'].'_s'.$row['status'], $row['qte']);
            }
        }
        // Calcul des pishirts et hoodies par taille
        for ($i=1;$i<9;$i++) {
            $f3->set('pishirt_t'.$i, 0);
            $f3->set('hoodie_t'.$i, 0);
        }
        $query = "SELECT quoi,
okhin's avatar
okhin committed
484 485 486 487
            taille,
            COUNT(taille) AS qte
            FROM contreparties
            GROUP BY quoi, taille;";
488 489
        $result = $db->query($query);
        if ($result) {
490
            foreach ($result->fetchAll(\PDO::FETCH_ASSOC) as $row) {
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
                $f3->set($row['quoi'].'_t'.$row['taille'], $row['qte']);
            }
        }
        $f3->set('block_content', 'backend/contreparties_tableau.html');
    }

    public function counterparts($f3, $args)
    {
        $export = false;
        $texte = '';
        $pibag = '';
        $piplome = '';
        $pishirt = '';
        $hoodie = '';
        $pseudo = '';
        $quoi = 0;
okhin's avatar
okhin committed
507 508
        $limite = 50;
        $page = 1;
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
        $status = '';
        $db = $f3->get('DB');
        if ($f3->get('VERB')=='POST') {
            if ($f3->exists('POST.action')) {
                switch ($f3->get('POST.action')) {
                case 'asked':
                    $db->query("UPDATE contreparties SET status=1 WHERE id=".$f3->get('POST.id')."");
                    break;
                case 'sent':
                    $db->query("UPDATE contreparties SET status=2 WHERE id=".$f3->get('POST.id')."");
                    break;
                case 'npai':
                    $db->query("UPDATE contreparties SET status=3 WHERE id=".$f3->get('POST.id')."");
                    break;
                case 'canceled':
                    $db->query("UPDATE contreparties SET status=99 WHERE id=".$f3->get('POST.id')."");
                    break;
                case 'export':
                    $export = true;
                    break;
                case 'pdf':
                    $db->query("UPDATE dons SET pdf='' WHERE id=".$f3->get('POST.id')."");
                    break;
                }
            }
            $texte = $f3->get('POST.texte');
            $pibag = $f3->get('POST.pibag');
            $piplome = $f3->get('POST.piplome');
            $pishirt = $f3->get('POST.pishirt');
            $hoodie = $f3->get('POST.hoodie');
            $quoi = $quoi + $pibag + $piplome + $pishirt + $hoodie;
okhin's avatar
okhin committed
540 541
            $limite = $f3->exists('POST.limite') ? (int) $f3->get('POST.limite') : 50;
            $page = $f3->exists('POST.page') ? (int) $f3->get('POST.page') : 1;
542 543 544 545
            $status = $f3->get('POST.status');
        }

        $query = "SELECT c.id,
okhin's avatar
okhin committed
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
            c.datec as datec,
            c.quoi as quoi,
            c.taille as taille,
            c.status as status,
            c.user_id as user_id,
            u.email as email,
            u.pseudo as pseudo,
            u.commentaire as commentaire,
            a.nom as nom,
            a.adresse as adresse,
            a.adresse2 as adresse2,
            a.codepostal as codepostal,
            a.ville as ville,
            a.pays as pays
            FROM contreparties c
            INNER JOIN users u ON c.user_id = u.id
            INNER JOIN adresses a ON c.adresse_id = a.id
            WHERE 1=1 ";
564 565
        if ($texte) {
            $query .= " AND (c.id like '%".$texte."%'
okhin's avatar
okhin committed
566 567 568 569 570 571 572 573
                OR u.pseudo like '%".$texte."%'
                OR u.email like '%".$texte."%'
                OR a.nom like '%".$texte."%'
                OR a.ville like '%".$texte."%'
                OR a.pays like '%".$texte."%'
                OR a.codepostal like '%".$texte."%'
                OR a.adresse2 like '%".$texte."%'
                OR a.adresse like '%".$texte."%')";
574 575 576 577 578
        }
        switch ($quoi) {
        case 0:
            break;
        case 1:
579
            $query .= " AND c.quoi='".\Utils::asl('pibag')."' ";
580 581
            break;
        case 2:
582
            $query .= " AND c.quoi='".\Utils::asl('piplome')."' ";
583 584
            break;
        case 4:
585
            $query .= " AND c.quoi='".\Utils::asl('pishirt')."' ";
586 587
            break;
        case 8:
588
            $query .= " AND c.quoi='".\Utils::asl('hoodie')."' ";
589 590 591
            break;
        default:
            $query .= " AND datec IN (
okhin's avatar
okhin committed
592 593 594 595 596 597 598 599 600 601 602 603 604
                SELECT datec
                FROM contreparties
                WHERE status=1
                GROUP BY user_id, datec
                HAVING SUM(
                    CASE quoi
                    WHEN 'pibag' THEN 1
                    WHEN 'piplome' THEN 2
                    WHEN 'pishirt' THEN 4
                    WHEN 'hoodie' THEN 8
                    END
                )=$quoi)
";
605 606
        }
        if ($status) {
607
            $query .= " AND c.status IN (".\Utils::asl($status).") ";
608
        }
okhin's avatar
okhin committed
609 610 611
        $first = ($page - 1) * $limite;
        $last = $page * $limite;
        $query .= " ORDER BY c.datec DESC LIMIT $first, $last;";
612 613 614 615
        $result = $db->query($query);
        $data = array();
        if ($result) {
            $i = 0;
616
            foreach ($result->fetchAll(\PDO::FETCH_ASSOC) as $row) {
617 618
                if ($row['quoi']=='piplome') {
                    $pdf = $db->query("SELECT d.id AS id,
okhin's avatar
okhin committed
619 620 621 622 623
                        a.nom AS pseudo,
                        d.pdf AS pdf
                        FROM dons d
                        JOIN adresses a ON a.id = d.adresse_id
                        WHERE d.id='".$row['taille']."'");
624
                    if ($pdf) {
625
                        $pdf = $pdf->fetch(\PDO::FETCH_ASSOC);
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
                    }
                    $row['pdf_id'] = $pdf['id'];
                    $row['pdf_nom'] = $pdf['pseudo'];
                    $row['pdf_url'] = $pdf['pdf'];
                } else {
                    $row['pdf_id'] = '';
                    $row['pdf_nom'] = '';
                    $row['pdf_url'] = '';
                }
                $data[] = $row;
                $i++;
            }
            $f3->set('row_count', $i);
        } else {
            $f3->set('row_count', 0);
        }

        $f3->set('texte', $texte);
        $f3->set('quoi', $quoi);
        $f3->set('pibag', $pibag);
        $f3->set('piplome', $piplome);
        $f3->set('pishirt', $pishirt);
        $f3->set('hoodie', $hoodie);
        $f3->set('limite', $limite);
okhin's avatar
okhin committed
650
        $f3->set('page', $page);
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
        $f3->set('status', $status);
        $f3->set('query', $query);
        $f3->set('data', $data);
        $f3->set('pseudo', $pseudo);
        $f3->set('PIPLOME_URL', PIPLOME_URL);

        if ($export) {
            $rows = array();
            $count = 1;
            foreach ($data as $row) {
                // Affichage de la taille de manière courte
                $taille = "";
                $atailles = $f3->get('TAILLES');
                if ($row['quoi']!="piplome" and $row['quoi']!="pibag") {
                    $row['taille'] = preg_replace('(Coupe |Taille |omme,|emme,)', '', $atailles[$row['taille']]);
                }
                if ($row['quoi']=="pibag") {
                    $row['taille'] = "N/A";
                }
                $row['count'] = $count++;
671 672 673 674
                $row['email'] = \Utils::clean_encoding($row['email']);
                $row['pseudo'] = \Utils::clean_encoding($row['pseudo']);
                $row['nom'] = \Utils::clean_encoding($row['nom']);
                $adresse = \Utils::clean_encoding($row['adresse']);
675 676 677
                $adresse = preg_replace('/\n|\r/', ' ', $adresse);
                $adresse = preg_replace('/^'.$row['nom'].'/', '', $adresse);
                $row['adresse'] = $adresse;
678
                $adresse2 = \Utils::clean_encoding($row['adresse2']);
679 680 681
                $adresse2 = preg_replace('/\n|\r/', ' ', $adresse2);
                $adresse2 = preg_replace('/^'.$row['nom'].'/', '', $adresse2);
                $row['adresse2'] = $adresse2;
682 683 684 685 686 687 688 689
                $row['codepostal'] = \Utils::clean_encoding($row['codepostal']);
                $row['ville'] = \Utils::clean_encoding($row['ville']);
                $row['pays'] = \Utils::clean_encoding($row['pays']);
                $row['datec'] = \Utils::clean_encoding($row['datec']);
                $row['taille'] = \Utils::clean_encoding($row['taille']);
                $row['pdf_id'] = \Utils::clean_encoding($row['pdf_id']);
                $row['pdf_nom'] = \Utils::clean_encoding($row['pdf_nom']);
                $row['commentaire'] = \Utils::clean_encoding($row['commentaire']);
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
                $rows[] = $row;
            }
            $f3->set('headers', array(
                "email",
                "pseudo",
                "nom",
                "adresse",
                "adresse2",
                "code postal",
                "ville",
                "pays",
                "demande",
                "taille",
                "piplome_id",
                "nom sur le piplome",
                "commentaire",
            ));
            $f3->set('rows', $rows);
            echo Template::instance()->render('export.csv', 'text/csv');
            die();
        } else {
            $f3->set('block_content', 'backend/contreparties.html');
        }
    }

    public function counterpart($f3, $args)
    {
        $id = '';
        $user_id = '';
        $quoi = '';
        $taille = '';
        $nom = '';
        $adresse = '';
        $adresse2 = '';
        $codepostal = '';
        $ville = '';
        $pays = '';
        $msg = '';
        $comment = '';
        $db = $f3->get('DB');
        if ($f3->get('VERB')=='GET') {
            if ($f3->exists('PARAMS.id')) {
                $id = $f3->get('PARAMS.id');
            }
        } else {
            $id = $f3->get('POST.id');
            $user_id = $f3->get('POST.user_id');
            $quoi = $f3->get('POST.quoi');
            $taille = $f3->get('POST.taille');
            $nom = $f3->get('POST.nom');
            $email = $f3->get('POST.email');
            $adresse = $f3->Get('POST.adresse');
            $adresse2 = $f3->Get('POST.adresse2');
            $codepostal = $f3->get('POST.codepostal');
            $ville = $f3->get('POST.ville');
            $pays = $f3->get('POST.pays');
            $status = $f3->get('POST.status');
            $comment = $f3->get('POST.commentaire');

            // Mise à jour de la contrepartie
            if ($id!='') {
                // First, let's retrieve the adresse from the adresse_id if it exists
                $result = $db->query("SELECT adresse_id
okhin's avatar
okhin committed
753 754 755
                    FROM contreparties
                    WHERE id = '".\Utils::asl($f3->get('POST.id'))."'
                    AND adresse_id IS NOT NULL");
756
                $result = $result->fetch(\PDO::FETCH_ASSOC);
757 758 759 760 761
                $adresse_id = $result['adresse_id'];

                if (!$adresse_id or $adresse_id == 0) {
                    // We need to create an adresse_id
                    $db->query("INSERT INTO adresses
okhin's avatar
okhin committed
762 763 764 765 766 767
                        VALUES (nom='".\Utils::asl($nom)."',
                            adresse='".\Utils::asl($adresse)."',
                            adresse2='".\Utils::asl($adresse2)."',
                            codepostal='".\Utils::asl($codepostal)."',
                            ville='".\Utils::asl($ville)."',
                            pays='".\Utils::asl($pays)."')");
768
                    $adresse_id = $db->lastInsertId();
769 770 771 772
                } else {
                    // Updating the adresses first
                    $db->query("UPDATE adresses
                        SET nom='".\Utils::asl($nom)."',
okhin's avatar
okhin committed
773 774 775 776 777
                        adresse='".\Utils::asl($adresse)."',
                        adresse2='".\Utils::asl($adresse2)."',
                        codepostal='".\Utils::asl($codepostal)."',
                        ville='".\Utils::asl($ville)."',
                        pays='".\Utils::asl($pays)."'
778 779
                        WHERE id = $adresse_id");
                };
780
                $db->query("UPDATE contreparties
okhin's avatar
okhin committed
781 782 783 784
                    SET quoi='".\Utils::asl($quoi)."',
                    taille='".\Utils::asl($taille)."',
                    status='".\Utils::asl($status)."'
                    WHERE id='".\Utils::asl($_POST['id'])."'");
785
                // We will update the comment
786
                $db->query("UPDATE users SET commentaire='".\Utils::asl($comment)."' WHERE id='".\Utils::asl($user_id)."'");
787 788 789 790
            }
        }

        if ($id!='') {
791
            $contrepartie = $f3->get('container')['counterpart_finder']->findById((int) $id);
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
        } else {
            $contrepartie = array(
                'id'=>$id,
                'user_id'=>$user_id,
                'quoi'=>$quoi,
                'taille'=>$taille,
                'nom'=>$nom,
                'adresse'=>$adresse,
                'adresse2'=>$adresse2,
                'codepostal'=>$codepostal,
                'ville'=>$ville,
                'pays'=>$pays,
                'status'=>$status,
                'commentaire'=>$comment,
            );
        }
        $pdfs = array();
        if ($contrepartie['quoi']=='piplome') {
            $result = $db->query("SELECT d.id AS id,
okhin's avatar
okhin committed
811 812 813 814 815 816 817
                d.pdf AS pdf,
                a.nom AS nom
                FROM dons d 
                INNER JOIN adresses a ON d.adresse_id = a.id
                WHERE pdf<>'' 
                AND d.status IN (1,4,101)
                AND d.user_id='".$contrepartie['user_id']."'");
818
            if ($result) {
819
                foreach ($result->fetchAll(\PDO::FETCH_ASSOC) as $pdf) {
820 821 822 823 824 825 826 827 828 829 830 831 832
                    $pdfs[] = $pdf;
                }
            }
        }
        $f3->set('pdfs', $pdfs);

        $f3->set('id', $id);
        $f3->set('msg', $msg);
        $f3->set('contrepartie', $contrepartie);

        $f3->set('block_content', 'backend/contrepartie.html');
    }

okhin's avatar
okhin committed
833 834
    public function adresse($f3, $args)
    {
835
        $id = '';
836
        $form_name = '';
837 838 839 840
        $user_id = '';
        $db = $f3->get('DB');
        if ($f3->get('VERB') == 'POST') {
            $id = \Utils::asl($f3->get('POST.id'));
841
            $form_name = $f3->get('POST.action');
842
        }
843 844 845 846 847 848 849 850
        if ($form_name == 'delete') {
            $result = $db->query("SELECT user_id FROM adresses WHERE id = $id");
            $result = $result->fetch(\PDO::FETCH_ASSOC);
            $user_id = \Utils::asl($result["user_id"]);
            $db->query("UPDATE dons SET adresse_id = NULL
                WHERE user_id = $user_id");
            $db->query("UPDATE contreparties SET adresse_id = NULL
                WHERE user_id = $user_id");
okhin's avatar
okhin committed
851 852
            $db->query(
                "DELETE FROM adresses
853
                WHERE id = $id"
854
        );
855 856 857 858 859 860 861 862 863 864
        } else {
            $result = $db->query("SELECT user_id FROM adresses WHERE id = $id");
            $result = $result->fetch(\PDO::FETCH_ASSOC);
            $user_id = \Utils::asl($result["user_id"]);
            $nom = \Utils::asl($f3->get('POST.nom'));
            $adresse = \Utils::asl($f3->get('POST.adresse'));
            $adresse2 = \Utils::asl($f3->get('POST.adresse2'));
            $codepostal = \Utils::asl($f3->get('POST.codepostal'));
            $ville = \Utils::asl($f3->get('POST.ville'));
            $pays = \Utils::asl($f3->get('POST.pays'));
okhin's avatar
okhin committed
865 866
            $db->query(
                "UPDATE adresses SET
867 868 869 870 871 872 873 874 875
                nom = '".$nom."',
                adresse = '".$adresse."',
                adresse2 = '".$adresse2."',
                codepostal = '".$codepostal."',
                ville = '".$ville."',
                pays = '".$pays."'
                WHERE id = $id"
            );
        }
876 877 878
        $f3->reroute("/admin/users/$user_id");
    }

879 880
    public function user($f3, $args)
    {
881
        $id = array_key_exists('id', $args) ? \Utils::asl($args['id']) : '';
882 883 884
        $f3->set('id', $id);

        if ($f3->get('VERB') == 'POST') {
885
            $pseudo = \Utils::asl($f3->get('POST.pseudo'));
886 887 888 889 890 891
            $email = $f3->get('POST.email');
            $commentaire = $f3->get('POST.commentaire');

            if ($id > 0) {
                $f3->get('container')['command_handler']->handle(new UserUpdateByAdminCommand($id, $pseudo, $email, $commentaire));
            } else {
892
                $password = hash('sha256', \Utils::generate_password());
893 894 895 896 897 898 899 900 901 902 903 904
                $db = $f3->get('DB');
                $db->query("INSERT INTO users
                    VALUES pseudo = '".$pseudo."',
                    hash = '".$hash."',
                    commentaire = '".$commentaire."',
                    email = '".$email."'");
                $id = $db->lastInsertId();
            }
        }

        // Let's get everything we have related to our user
        $user = $f3->get('container')['user_finder']->findById($id);
905
        $user['adresse'] = $f3->get('container')['address_finder']->findByUserId($user['id']);
906 907 908 909 910 911 912 913 914 915 916 917
        $user['dons'] = $f3->get('container')['donation_finder']->findByUserId($user['id']);
        $user['contreparties'] = $f3->get('container')['counterpart_finder']->findByUserId($user['id']);

        $f3->set('user', $user);
        $f3->set('block_content', 'backend/user.html');
    }

    public function users($f3, $args)
    {
        $text = $f3->exists('POST.texte') ? $f3->get('POST.texte') : '';
        $status = $f3->exists('POST.status') ? $f3->get('POST.status') : '';
        $limit = $f3->exists('POST.limite') ? (int) $f3->get('POST.limite') : 50;
okhin's avatar
okhin committed
918
        $page = $f3->exists('POST.page') ? (int) $f3->get('POST.page') : 1;
919 920 921 922 923 924

        $results = $f3->get('container')['user_finder']->adminSearch($text, $status, $limit);

        $f3->set('texte', $text);
        $f3->set('status', $status);
        $f3->set('limite', $limit);
okhin's avatar
okhin committed
925
        $f3->set('page', $page);
926 927 928 929 930 931 932 933 934 935 936
        $f3->set('data', $results);
        $f3->set('row_count', count($results));
        $f3->set('block_content', 'backend/users.html');
    }

    public function cbs($f3, $args)
    {
        $export = false;
        $texte = '';
        $status = '';
        $limite = '50';
okhin's avatar
okhin committed
937
        $page = '1';
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
        $db = $f3->get('DB');
        if ($f3->get('VERB')=='POST') {
            if ($f3->exists('POST.action')) {
                switch ($f3->get('POST.action')) {
                case 'current':
                    $db->query("UPDATE users SET status=1 WHERE id=".$f3->get('POST.id')."");
                    break;
                case 'to_relaunch':
                    $db->query("UPDATE users SET status=2 WHERE id=".$f3->get('POST.id')."");
                    break;
                case 'relaunched':
                    $db->query("UPDATE users SET status=3 WHERE id=".$f3->get('POST.id')."");
                    break;
                case 'command':
                    if ($f3->get('POST.command')!='') {
                        $query = "UPDATE users SET status=".$f3->get('POST.command')." where id IN (".$f3->get('POST.checkboxes').")";
                        $db->query($query);
                    }
                    break;
                case 'canceled':
                    $db->query("UPDATE users SET status=99 WHERE id=".$f3->get('POST.id')."");
                    break;
                case 'export':
                    $export = true;
                    break;
                }
            }
okhin's avatar
okhin committed
965 966 967 968 969

            $limit = $f3->exists('POST.limite') ? (int) $f3->get('POST.limite') : 50;
            $page = $f3->exists('POST.page') ? (int) $f3->get('POST.page') : 1;
            $texte = $f3->exists('POST.texte') ? $f3->get('POST.texte') : '';
            $status = $f3->exists('POST.status') ? $f3->get('POST.status') : '';
970 971 972 973 974
        }

        $query = "SELECT id, email, expiration, status FROM users WHERE identifier!='' AND identifier IS NOT NULL AND status != ''";
        if ($texte!='') {
            $query .= " AND (email like '%".$texte."%'
okhin's avatar
okhin committed
975
                OR pseudo like '%".$texte."%')";
976 977 978 979
        }
        if ($status!='') {
            $query .= " AND status='".$status."'";
        }
okhin's avatar
okhin committed
980 981 982
        $first = ($page - 1) * $limit;
        $last = $page * $limit;
        $query .= " ORDER BY expiration ASC LIMIT $first, $last;";
983 984 985 986
        $result = $db->query($query);
        $cbs = array();
        if ($result) {
            $i = 0;
987
            foreach ($result->fetchAll(\PDO::FETCH_ASSOC) as $data) {
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
                $cb['id'] = $data['id'];
                $cb['email'] = $data['email'];
                $time_struct = strptime($data['expiration'], "%Y-%m-%d %H:%M:%S");
                $new_expiration = strftime("%m-%Y", mktime(
                    $time_struct['tm_hour'],
                    $time_struct['tm_min'],
                    $time_struct['tm_sec'],
                    $time_struct['tm_mon']+1,
                    $time_struct['tm_mday'],
                    $time_struct['tm_year']+1900
                ));
                $cb['expiration'] = $new_expiration;
                if ($data['status'] == '') {
                    $cb['status'] = 100;
                } else {
                    $cb['status'] = $data['status'];
                }
                $cbs[] = $cb;
                $i++;
            }
            $f3->set('row_count', $i);
        }

        $f3->set('texte', $texte);
        $f3->set('status', ($status!='') ? $status : 0);
        $f3->set('limite', $limite);
        $f3->set('query', $query);
        $f3->set('data', $cbs);
okhin's avatar
okhin committed
1016
        $f3->set('page', $page);
1017 1018 1019 1020 1021 1022 1023

        if ($export) {
            $statuts = $f3->get('CB_STATUTS');
            $rows = array();
            $count = 1;
            foreach ($cbs as $row) {
                $row['count'] = $count++;
1024 1025 1026
                $row['id'] = \Utils::clean_encoding($row['id']);
                $row['email'] = \Utils::clean_encoding($row['email']);
                $row['expiration'] = \Utils::clean_encoding($row['expiration']);
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
                $row['status'] = $statuts[$row['status']];
                $rows[] = $row;
            }
            $f3->set('headers', array(
                "id",
                "email",
                "expiration",
                "status",
            ));
            $f3->set('rows', $rows);
            echo Template::instance()->render('cbs_export.csv', 'text/csv');
            die();
        } else {
            $f3->set('block_content', 'backend/cbs.html');
        }
    }

    public function banque($f3, $args)
    {
        $message = '';
        $error = '';
        $result = '';
        if ($f3->get('VERB')=='POST') {
            if ($_FILES['file']['tmp_name']=='') {
                $message = "Merci de sélectionner un fichier.";
            } else {
                switch ($f3->get('POST.tab')) {
                case 'verif':
                    $datas = $this->banque_verif($f3, $_FILES['file']['tmp_name']);
                    if ($datas['dons_ok']>0) {
                        $result = $datas['dons_ok'] . " dons ok sur un total de ". $datas['dons_total']." dons.";
                    }
                    if ($datas['recurrents_ok']>0) {
                        $result .= '<br />' . $datas['recurrents_ok'] . " dons récurrents comptabilisés sur un total de ". $datas['recurrents_total']." dons récurrents.";
                    }
                    if ($datas['dons_nok']>0) {
                        $error = $datas['dons_nok'] . " dons avec un souci sur un total de ". $datas['dons_total']." dons.";
                        $message = '';
                        foreach ($datas['dons'] as $key=>$value) {
                            $message .= $value.'<br />';
                        }
                    }
                    if ($datas['recurrents_nok']>0) {
                        $error .= '<br />' . $datas['recurrents_nok'] . " dons récurrents non comptabilisés sur un total de ". $datas['recurrents_total']." dons récurrents.";
                    }
                    break;
                case 'update':
                    if ($f3->get('POST.test')=='1') {
                        $datas = $this->banque_update($f3, $_FILES['file']['tmp_name']);
                        $result = $datas['update'] . " dons récurrents mis à jour sur un total de ". $datas['total']." dons récurrents.";
                        $message = "Il s'agit d'un <b>test</b><br />";
                    } else {
                        $datas = $this->banque_update($f3, $_FILES['file']['tmp_name'], false);
                        $result = $datas['update'] . " dons récurrents mis à jour sur un total de ". $datas['total']." dons récurrents.";
                    }
                    if (count($datas['comptabilise'])>0 or count($datas['sans_cumul'])>0) {
                        $error = count($datas['comptabilise']) . " dons récurrents déjà comptabilisés et ". count($datas['sans_cumul'])." dons récurrents sans cumul.";
                        if (count($datas['comptabilise'])>0) {
                            $message .= 'Dons déjà comptabilisés:<br />';
                            foreach ($datas['comptabilise'] as $key=>$value) {
                                $message .= $value.'<br />';
                            }
                        }
                        if (count($datas['sans_cumul'])>0) {
                            $message .= 'Dons sans cumul:<br />';
                            foreach ($datas['sans_cumul'] as $key=>$value) {
                                $message .= $value.'<br />';
                            }
                        }
                    }
                    break;
                default:
                    $datas = $this->banque_cbs($f3, $_FILES['file']['tmp_name']);
                    $result = $datas['total_cbs'] . " dates d'expiration mises à jour.";
                    break;
                }
            }
        }
        $f3->set('result', $result);
1106 1107
        $f3->push('SESSION.error', $error);
        $f3->push('SESSION.message', $message);
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149

        $f3->set('block_content', 'backend/banque.html');
    }

    public function banque_cbs($f3, $filename)
    {
        $separator = ";";
        $datas = array();
        $db = $f3->get('DB');
        // Lecture du fichier
        if (($handle = fopen($filename, "r")) !== false) {
            // On récupère d'abord les champs du fichier
            $fields = fgetcsv($handle, 1000, $separator);
            $identifier_idx = -1;
            $expire_idx = -1;
            foreach ($fields as $key=>$value) {
                if ($value=="Alias") {
                    $identifier_idx = $key;
                }
                if ($value=="Date expiration") {
                    $expire_idx = $key;
                }
            }

            // On lit maintenant tout, ligne par ligne, afin de stocker les
            // informations bancaires pour chaque don récurrent.
            $total_cbs = 0; // Nombre de CB mises à jour
            while (($data = fgetcsv($handle, 1000, $separator)) !== false) {
                // Récupération de l'identifiant du don
                $identifier = $data[$identifier_idx];

                // Construction de la date d'expiration de la CB
                $expire = $data[$expire_idx];
                $expire = preg_split("#/#", $data[$expire_idx]);
                $expire_date = mktime(0, 0, 0, $expire[0], 1, $expire[1]);
                $expire = strftime("%Y-%m-%d 00:00:00", $expire_date);
                $today_date = time();
                $today = strftime("%Y-%m-%d 00:00:00", $today_date);

                // Mise à jour dans la base de données de la date d'expiration
                $result = $db->query("SELECT user_id FROM identifiers WHERE identifier='".$identifier."'");
                if ($result) {
1150
                    $user_id = $result->fetch(\PDO::FETCH_ASSOC)[0];
1151 1152 1153 1154
                    $total_cbs += 1;
                    $db->query("UPDATE identifiers SET expiration='".$expire. "' WHERE identifier='".$identifier."'");
                    if ($expire_date<$today_date) {
                        $db->query("INSERT INTO dons SET
okhin's avatar
okhin committed
1155 1156 1157 1158 1159 1160
                            status = '103',
                            datec = NOW(),
                            somme = 0,
                            user_id = '" .$user_id ."',
                            identifier = '" . $identifier ."',
                            cumul = 0;");
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
                    }
                }
            }
            fclose($handle);
        }
        $datas['total_cbs'] = $total_cbs;
        return $datas;
    }

    public function banque_verif($f3, $filename)
    {
        $separator = ";";
        $datas = array();
        $db = $f3->get('DB');
        // Lecture du fichier
        if (($handle = fopen($filename, "r")) !== false) {
            // On récupère d'abord les champs du fichier
            $fields = fgetcsv($handle, 1000, $separator);
            $identifier_idx = -1;
            $effect_idx = -1;
            $transaction_idx = -1;
            $amount_idx = -1;
            $statut_idx = -1;
            foreach ($fields as $key=>$value) {
                if ($value=="Identifiant compte client") {
                    $identifier_idx = $key;
                }
                if ($value=="Remis le") {
                    $effect_idx = $key;
                }
                if ($value=="Transaction") {
                    $transaction_idx = $key;
                }
                if ($value=="Montant du paiement") {
                    $amount_idx = $key;
                }
                if ($value=="Statut") {
                    $statut_idx = $key;
                }
            }

            // On lit maintenant tout, ligne par ligne, afin de vérifier les informations bancaires pour chaque don.
            $dons_ok = 0;
            $dons_nok = 0;
            $dons = array();
            $recurrents_ok = 0;
            $recurrents_nok = 0;
            while (($data = fgetcsv($handle, 1000, $separator)) !== false) {
                // Récupération des informations du don
                $identifier = $data[$identifier_idx];
                $effect = $data[$effect_idx];
                $transaction = $data[$transaction_idx];
                $amount = $data[$amount_idx];
                $statut = $data[$statut_idx];
                if ($statut == 'Refusé') {
                    $db->query("UPDATE dons SET status = 103 WHERE id='".$transaction."'");
                    continue;
                }

                if ($identifier=='') {
                    // Pour un don ponctuel, on recherche un équivalent
                    $result = $db->query("SELECT COUNT(*) FROM dons WHERE id='".$transaction. "' AND somme='".$amount."' AND status=1");
                    if ($result) {
1224
                        $combien = $result->fetch(\PDO::FETCH_ASSOC);
1225 1226 1227 1228 1229 1230
                        if ($combien[0]>0) {
                            $dons_ok += 1;
                        } else {
                            $dons_nok += 1;
                            $subresult = $db->query("SELECT id, status, somme FROM dons WHERE id='".$transaction. "'");
                            if ($subresult) {
1231
                                $subresult = $subresult->fetch(\PDO::FETCH_ASSOC);
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
                                if (count($subresult)>0) {
                                    $dons[] = "Transaction " . $transaction . " de " . $subresult[2] . " € avec un statut " . $subresult[1] . ".";
                                } else {
                                    $dons[] = "Transaction " . $transaction . " inconnue.";
                                }
                            } else {
                                $dons[] = "Erreur de requête sur la transaction " . $transaction;
                            }
                        }
                    }
                } else {
                    $time_struct = strptime($effect, "%d/%m/%Y %H:%M:%S");
                    $new_effect = strftime("%Y-%m-%d %H:%M:%S", mktime(
                        $time_struct['tm_hour']+1,
                        $time_struct['tm_min'],
                        $time_struct['tm_sec'],
                        $time_struct['tm_mon']+1,
                        $time_struct['tm_mday'],
                        $time_struct['tm_year']+1900
                    ));
                    // Pour un don récurrent, on recherche son équivalent qui peut ne pas exister
                    $result = $db->query("SELECT email FROM users JOIN identifiers ON identifiers.user_id = users.id  WHERE identifiers.identifier='".$identifier. "'");
                    if ($result) {
1255
                        $email = $result->fetch(\PDO::FETCH_ASSOC);
1256 1257 1258 1259
                        $email = $email[0];

                        $result = $db->query("SELECT COUNT(1) FROM dons d JOIN users u ON u.id = d.user_id WHERE u.email='".$email. "' and d.status=102 and d.datec='".$new_effect."'");
                        if ($result) {
1260
                            $combien = $result->fetch(\PDO::FETCH_ASSOC);
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
                            if ($combien[0]>0) {
                                // Don récurrent comptabilisé
                                $recurrents_ok += 1;
                            } else {
                                // Don récurrent pas encore comptabilisé
                                $recurrents_nok += 1;
                            }
                        }
                    }
                }
            }
            fclose($handle);
            $dons_total = $dons_ok + $dons_nok;
            $recurrents_total = $recurrents_ok + $recurrents_nok;
        }
        $datas['dons_ok'] = $dons_ok;
        $datas['dons_nok'] = $dons_nok;
        $datas['dons_total'] = $dons_total;
        $datas['dons'] = $dons;
        $datas['recurrents_ok'] = $recurrents_ok;
        $datas['recurrents_nok'] = $recurrents_nok;
        $datas['recurrents_total'] = $recurrents_total;
        return $datas;
    }

    public function banque_update($f3, $filename, $testing=true)
    {
        $separator = ";";
        $datas = array();
        $update = 0;
        $total = 0;
        $comptabilise = array();
        $sans_cumul = array();
        $emails = array();
        $db = $f3->get('DB');
        // Lecture du fichier
        if (($handle = fopen($filename, "r")) !== false) {
            // On récupère d'abord les champs du fichier
            $fields = fgetcsv($handle, 1000, $separator);
            $identifier_idx = -1;
            $transaction_idx = -1;
            $effect_idx = -1;
            $amount_idx = -1;
            $statut_idx = -1;
            foreach ($fields as $key=>$value) {
                if ($value=="Alias") {
                    $identifier_idx = $key;
                }
                if ($value=="Commande") {
                    $transaction_idx = $key;
                }
                if ($value=="Date remise") {
                    $effect_idx = $key;
                }
                if ($value=="Montant du paiement") {
                    $amount_idx = $key;
                }
                if ($value=="Statut rapprochement") {
                    $statut_idx = $key;
                }
            }

            // On lit maintenant tout, ligne par ligne, afin de vérifier les informations bancaires pour chaque don.
            while (($data = fgetcsv($handle, 1000, $separator)) !== false) {
                if (count($data) <= 0) {
                    continue;
                }
                // Récupération des informations du don
okhin's avatar
okhin committed
1329 1330 1331 1332 1333 1334
                $identifier = isset($data[$identifier_idx]) ? $data[$identifier_idx] : false;
                $transaction = isset($data[$transaction_idx]) ? $data[$transaction_idx] : false;
                $effect = isset($data[$effect_idx]) ? $data[$effect_idx] : false;
                $amount = isset($data[$amount_idx]) ? $data[$amount_idx] : false;
                $statut = isset($data[$statut_idx]) ? $data[$statut_idx] : false;
                if ($identifier && $transaction && $effect && $amount && $statut == false) {
1335 1336
                    continue;
                }
1337 1338 1339 1340 1341 1342 1343 1344
                if ($statut == 'Refusé') {
                    $db->query("UPDATE dons SET status = 103 WHERE id='".$transaction."'");
                    continue;
                }

                // On ne s'intéresse qu'aux dons récurrents
                if ($identifier!='') {
                    $total ++;
1345
                    $email = '';
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
                    $time_struct = strptime($effect, "%d/%m/%Y %H:%M:%S");
                    $new_effect = strftime("%Y-%m-%d %H:%M:%S", mktime(
                        $time_struct['tm_hour']+1,
                        $time_struct['tm_min'],
                        $time_struct['tm_sec'],
                        $time_struct['tm_mon']+1,
                        $time_struct['tm_mday'],
                        $time_struct['tm_year']+1900
                    ));
                    // Pour un don récurrent, on recherche son équivalent qui peut ne pas exister
                    $result = $db->query("SELECT email
okhin's avatar
okhin committed
1357 1358 1359 1360
                        FROM users
                        JOIN identifiers
                        ON users.id = identifiers.user_id
                        AND identifiers.identifier='".$identifier. "'");
1361 1362 1363
                    if ($result->rowCount() == 0) {
                        // Identifier does not exist, we must create it. We have either a pseudo or an email.
                        $user_field = explode("_", $identifier)[1];
okhin's avatar
okhin committed
1364
                        $user = '';
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377

                        if (strpos($user_field, '@')) {
                            // identifier is an email
                            $user = $f3->get('container')['user_finder']->findByEmail($user_field);
                        } else {
                            // identifier is a pseudo
                            $user = $f3->get('container')['user_finder']->findByPseudo($user_field);
                        }

                        if ($user) {
                            $db->query("INSERT INTO identifiers(user_id, identifier) VALUES ('".$user['id']."', '".$identifier."')");
                            $email = $user['email'];
                        } else {
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
                            // No user, let's try to create the user
                            $email = '';
                            $pseudo = '';
                            if (strpos($user_field, '@')) {
                                $email = $user_field;
                                $pseudo = explode("@", $user_field)[0];
                            } else {
                                $email = $user_field . "@example.org";
                                $pseudo = $user_field;
                            }
                            $hash = hash('sha256', date("%Y-%m-%d %H:%i:%d").$email);
                            $f3->get('container')['command_handler']->handle(new UserCreateCommand($email, $hash, $pseudo, 0, 0));
1390 1391
                        }
                    } else {
1392
                        $email = $result->fetch(\PDO::FETCH_ASSOC);
1393 1394
                        $email = $email['email'];
                        // On stocke l'email pour comptabiliser les dons
1395 1396 1397 1398 1399 1400
                    }
                    if (array_key_exists($email, $emails)) {
                        $emails[$email] ++;
                    } else {
                        $emails[$email] = 1;
                    }
okhin's avatar
okhin committed
1401 1402
                    // On a besoin de l'utilisateur
                    $user = $f3->get('container')['user_finder']->findByEmail($email);
1403
                    // Récupération de l'id du bon abonnement
okhin's avatar
okhin committed
1404
                    $stmt = $db->query("SELECT d.id AS id
1405 1406
                        FROM dons d
                            JOIN users u ON u.id = d.user_id
okhin's avatar
okhin committed
1407
                        WHERE u.email='".$email."'
1408
                            AND d.status=101
1409
                            AND d.id='".$transaction."'");
okhin's avatar
okhin committed
1410 1411
                    $result = $stmt->fetch(\PDO::FETCH_ASSOC);
                    if (!$result) {
okhin's avatar
okhin committed
1412 1413 1414
                        // don non trouvé en statut 101. On le crée (la banque à raison)
                        // statut = cumul
                        $f3->get('container')['command_handler']
okhin's avatar
okhin committed
1415 1416 1417 1418 1419 1420 1421 1422
                            ->handle(new DonationCreateCommand(
                                $user['id'],
                                101,
                                $new_effect,
                                $amount,
                                0,
                                0
                            ));
okhin's avatar
okhin committed
1423 1424 1425 1426 1427 1428 1429 1430
                        // Et on le récupère
                        $cumul = $db->lastInsertId();
                        $don = $f3->get('container')['donation_finder']->findById($cumul);
                    } else {
                        $cumul = $result['id'];
                    }
                    // On regarde si le don n'as pas déjà été ajouté (en vérifiant la datec)
                    $result = $db->query("SELECT COUNT(1)
okhin's avatar
okhin committed
1431 1432 1433 1434 1435 1436 1437
                            FROM dons d
                                JOIN users u ON u.id = d.user_id
                            WHERE u.email='".$email. "'
                                AND d.status=102
                                AND d.datec='".$new_effect."'
                                AND d.cumul=".$cumul."
                            ");
okhin's avatar
okhin committed
1438 1439 1440 1441 1442 1443
                    if ($result) {
                        $combien = $result->fetch();
                        if ($combien[0]==0) {
                            $update ++;
                            // Don récurrent non comptabilisé, on l'ajoute
                            $query = "INSERT INTO dons (status,
1444 1445 1446 1447 1448 1449 1450 1451 1452
                                            datec,
                                            somme,
                                            user_id,
                                            cumul,
                                            identifier)
                                        VALUES (
                                            102,
                                            '".$new_effect."',
                                            ".$amount.",
okhin's avatar
okhin committed
1453
                                            '".$user['id']."',
1454 1455
                                            '".$cumul."',
                                            '".$identifier."')";
okhin's avatar
okhin committed
1456 1457 1458 1459
                            if (!$testing) {
                                $db->query($query);
                                // On met alors à jour le cumul et le total de l'utilisateur concerné
                                $result = $db->query("UPDATE users
1460 1461
                                            SET cumul=cumul+".$amount.",
                                                total=total+".$amount."
okhin's avatar
okhin committed
1462
                                            WHERE id='".$user['id']."'");
1463
                            }
okhin's avatar
okhin committed
1464 1465
                        } else {
                            $comptabilise[] = $identifier;
1466
                        }
okhin's avatar
okhin committed
1467
                    }
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
                }
            }
            fclose($handle);
        }
        $datas['update'] = $update;
        $datas['total'] = $total;
        $datas['comptabilise'] = $comptabilise;
        $datas['sans_cumul'] = $sans_cumul;
        return $datas;
    }

okhin's avatar
okhin committed
1479

1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
    public function stats($f3, $args)
    {
        $startingDay = new \DateTime('2014-11-12');
        $finder = $f3->get('container')['stat_finder'];

        $results = [
            "Dons/heure sur les dernières 24 heures" => $finder->donationsPerHour(),
            "30 derniers dons" => $finder->latestDonations(),
            "Nombre de dons moyen par jour depuis le début de la campagne" => $finder->averageDonationPerDay($startingDay),
            "Montant moyen des dons depuis le début de la campagne" => $finder->averageDonationAmount($startingDay),
            "Nombre de dons par heure depuis le début de la campagne" => $finder->donationsPerHour($startingDay),
            "Répartitions des montants sur les 30 derniers jours" => $finder->donationsRepartitionByDay(),
            "Répartitions des montants depuis le début de la campagne" => $finder->donationsRepartitionByAmount($startingDay),
        ];

        foreach ($results as $title => $result) {
            $columns = [];
            $rows = [];
            foreach ($result as $statline) {
                $columns = array_keys($statline);
                $rows[] = array_values($statline);
            }

            $stats[] = [
                'title' => $title,
                'columns' => $columns,
                'rows' => $rows,
            ];
        }
        $f3->set('stats', $stats);

        $f3->set('block_content', 'backend/stats.html');
    }

1514 1515 1516 1517 1518 1519
    public function recompute($f3, $args)
    {
        $f3->get('container')['command_handler']->handle(new AdminUpdateTotalUsersCommand());
        $this->show($f3, $args);
    }

1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539
    public function accounts($f3, $args)
    {
        if ($f3->get('VERB') == 'POST') {
            $action = $f3->get('POST.action');
            switch ($action) {
                case 'create':
                    $f3->get('container')['command_handler']->handle(new AdminCreateCommand($f3->get('POST.user_id'), $f3->get('POST.password')));
                    break;
                case 'delete':
                    $f3->get('container')['command_handler']->handle(new AdminDeleteCommand($f3->get('POST.id')));
                    break;
                case 'update':
                    $f3->get('container')['command_handler']->handle(new AdminChangePasswordCommand($f3->get('POST.id'), $f3->get('POST.password')));
                    break;
                default:
                    break;
            }
            $f3->reroute('/admin/accounts');
        }

1540
        $admins = $admins->fetchAll(\PDO::FETCH_ASSOC);
1541 1542 1543 1544
        $f3->set('admins', $admins);
        $f3->set('block_content', 'backend/admins.html');
    }
};