Commit 7ed60619 authored by okhin's avatar okhin 🚴
Browse files

Merge branch '50-support-de-batch-pour-les-contreparties' into 'preprod'

Resolve "Support de batch pour les contreparties"

Closes #76, #50, and #71

See merge request lqdn-interne/don!73
parents 2559bc0a 375b289b
...@@ -4,12 +4,15 @@ namespace Controller; ...@@ -4,12 +4,15 @@ namespace Controller;
use LQDN\Command\AdminCreateCommand; use LQDN\Command\AdminCreateCommand;
use LQDN\Command\AdminDeleteCommand; use LQDN\Command\AdminDeleteCommand;
use LQDN\Command\AdminChangePasswordCommand; use LQDN\Command\AdminChangePasswordCommand;
use LQDN\Command\CounterpartCreateCommand;
use LQDN\Command\DonationValidateCommand; use LQDN\Command\DonationValidateCommand;
use LQDN\Command\DonationInvalidateCommand; use LQDN\Command\DonationInvalidateCommand;
use LQDN\Command\DonationResetPdfCommand; use LQDN\Command\DonationResetPdfCommand;
use LQDN\Command\DonationCreateCommand; use LQDN\Command\DonationCreateCommand;
use LQDN\Command\UserUpdateByAdminCommand; use LQDN\Command\UserUpdateByAdminCommand;
use LQDN\Command\UserCreateCommand; use LQDN\Command\UserCreateCommand;
use LQDN\Command\UserUpdateCumulCommand;
use LQDN\Command\AdminUpdateTotalUsersCommand;
class Admin extends Controller class Admin extends Controller
{ {
...@@ -46,12 +49,27 @@ class Admin extends Controller ...@@ -46,12 +49,27 @@ class Admin extends Controller
99 => "résilié", 99 => "résilié",
100 => "non applicable", 100 => "non applicable",
)); ));
$f3->set('TAILLES', array(
0 => _('PlaceHolder -- ne pas utiliser') . ' S',
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',
));
if (!$f3->get('SESSION.admin')) { if (!$f3->get('SESSION.admin')) {
$mapper = new\DB\SQL\Mapper($f3->get('DB'), 'admins'); $mapper = new\DB\SQL\Mapper($f3->get('DB'), 'admins');
$auth = new \Auth($mapper, array('id'=>'user_id', 'pw'=>'password')); $auth = new \Auth($mapper, array('id'=>'user_id', 'pw'=>'password'));
$success = $auth->basic('\Controller\Admin::hash_password'); $success = $auth->basic('\Controller\Admin::hash_password');
if (!$success) { if (!$success) {
$f3->push('SESSION.error', 'Accès non autorisé');
$f3->error(401); $f3->error(401);
} else { } else {
$f3->set('SESSION.admin', true); $f3->set('SESSION.admin', true);
...@@ -61,6 +79,26 @@ class Admin extends Controller ...@@ -61,6 +79,26 @@ class Admin extends Controller
$f3->set('PIPLOME_URL', PIPLOME_URL); $f3->set('PIPLOME_URL', PIPLOME_URL);
} }
public function afterRoute($f3, $args)
{
// 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', '');
}
// 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');
}
public static function hash_password($password) public static function hash_password($password)
{ {
return hash('sha256', $password); return hash('sha256', $password);
...@@ -140,6 +178,7 @@ class Admin extends Controller ...@@ -140,6 +178,7 @@ class Admin extends Controller
$cumul = $user_amount['total'] + $result['somme']; $cumul = $user_amount['total'] + $result['somme'];
} }
if ($error != '') { if ($error != '') {
$f3->push('SESSION.error', $error);
} else { } else {
$db->query( $db->query(
"UPDATE dons "UPDATE dons
...@@ -190,6 +229,7 @@ class Admin extends Controller ...@@ -190,6 +229,7 @@ class Admin extends Controller
} }
} }
if ($error != '') { if ($error != '') {
$f3->push('SESSION.error', $error);
} else { } else {
$db->query( $db->query(
"UPDATE dons "UPDATE dons
...@@ -341,6 +381,78 @@ class Admin extends Controller ...@@ -341,6 +381,78 @@ class Admin extends Controller
public function counterparts_dashboard($f3, $args) public function counterparts_dashboard($f3, $args)
{ {
$db = $f3->get('DB'); $db = $f3->get('DB');
$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);
}
// On définit des valeurs par défaut // On définit des valeurs par défaut
$query = "SELECT DISTINCT quoi FROM contreparties;"; $query = "SELECT DISTINCT quoi FROM contreparties;";
$result = $db->query($query); $result = $db->query($query);
...@@ -990,8 +1102,8 @@ class Admin extends Controller ...@@ -990,8 +1102,8 @@ class Admin extends Controller
} }
} }
$f3->set('result', $result); $f3->set('result', $result);
$f3->set('error', $error); $f3->push('SESSION.error', $error);
$f3->set('message', $message); $f3->push('SESSION.message', $message);
$f3->set('block_content', 'backend/banque.html'); $f3->set('block_content', 'backend/banque.html');
} }
...@@ -1398,6 +1510,12 @@ class Admin extends Controller ...@@ -1398,6 +1510,12 @@ class Admin extends Controller
$f3->set('block_content', 'backend/stats.html'); $f3->set('block_content', 'backend/stats.html');
} }
public function recompute($f3, $args)
{
$f3->get('container')['command_handler']->handle(new AdminUpdateTotalUsersCommand());
$this->show($f3, $args);
}
public function accounts($f3, $args) public function accounts($f3, $args)
{ {
if ($f3->get('VERB') == 'POST') { if ($f3->get('VERB') == 'POST') {
......
...@@ -3,6 +3,7 @@ namespace Controller; ...@@ -3,6 +3,7 @@ namespace Controller;
use LQDN\Command\UserUpdateCumulCommand; use LQDN\Command\UserUpdateCumulCommand;
use LQDN\Command\UserUpdateTotalCommand; use LQDN\Command\UserUpdateTotalCommand;
use LQDN\Command\DonationIncStatusCommand;
class Bank extends Controller class Bank extends Controller
{ {
...@@ -87,7 +88,8 @@ class Bank extends Controller ...@@ -87,7 +88,8 @@ class Bank extends Controller
### Attempt to do it in hmac-sha256 ### Attempt to do it in hmac-sha256
$sig_hash = base64_encode(hash_hmac('sha256', $sig, CERTIFICATE, true)); $sig_hash = base64_encode(hash_hmac('sha256', $sig, CERTIFICATE, true));
$cb_log->write("sig: " . $signature . " == " . $sig_hash); $cb_log->write("sig: " . $signature . " == " . $sig_hash);
if ($sig_hash!=$signature) { $cb_log->write("debug level: ". DEBUG);
if ($sig_hash!=$signature and DEBUG == 0) {
$error = "Error in signature: " . $signature . " != " . $sig_hash; $error = "Error in signature: " . $signature . " != " . $sig_hash;
} }
// Résultats des vérifications globales // Résultats des vérifications globales
...@@ -111,8 +113,7 @@ class Bank extends Controller ...@@ -111,8 +113,7 @@ class Bank extends Controller
$db = $f3->get('DB'); $db = $f3->get('DB');
$id = intval($order_id); $id = intval($order_id);
$cb_log->write("Id: ".$order_id); $cb_log->write("Id: ".$order_id);
$res = $db->query("SELECT * FROM dons WHERE id='".$id."';"); $don = $f3->get('container')['donation_finder']->findById($id);
$don = $res->fetch(\PDO::FETCH_ASSOC);
if (!$don) { if (!$don) {
$cb_log->write("Transaction id not found: ".$order_id); $cb_log->write("Transaction id not found: ".$order_id);
...@@ -148,18 +149,17 @@ class Bank extends Controller ...@@ -148,18 +149,17 @@ class Bank extends Controller
bind_textdomain_codeset("messages", "$charset"); bind_textdomain_codeset("messages", "$charset");
// ok, somme OK, status = completed, transaction found. // ok, somme OK, status = completed, transaction found.
$db->query("UPDATE dons SET status=status+1 WHERE id='".$id."';"); $f3->get('container')['command_handler']->handle(new DonationIncStatusCommand($don['id']));
$res = $db->query("SELECT status FROM dons WHERE id='".$id."';"); $don = $f3->get('container')['donation_finder']->findById($don['id']);
$status = $res->fetch(\PDO::FETCH_ASSOC); $status = $don['status'];
$status = $status['status'];
$user = $f3->get('container')['user_finder']->findById($don['user_id']); $user = $f3->get('container')['user_finder']->findById($don['user_id']);
$cb_log->write("Utilisation d'un utilisateur existant"); $cb_log->write("Utilisation d'un utilisateur existant");
// Ajout du nouveau don au cumul actuel // Ajout du nouveau don au cumul actuel
if ($status!=101) { if ($status!=101) {
$cb_log->write("Ajout de ".$don['somme']); $cb_log->write("Ajout de ".$don['somme']);
$f3->get('container')['command_handler']->handle(new UpdateUserTotalCommand($user['id'], (int) $user['total'] + $don['somme'])); $f3->get('container')['command_handler']->handle(new UserUpdateTotalCommand($user['id'], (int) $user['total'] + $don['somme']));
$f3->get('container')['command_handler']->handle(new UpdateUserCumulCommand($user['id'], (int) $user['cumul'] + $don['cumul'])); $f3->get('container')['command_handler']->handle(new UserUpdateCumulCommand($user['id'], (int) $user['cumul'] + $don['cumul']));
} }
$result = $db->query("SELECT cumul FROM users WHERE id='".$don['user_id']."'"); $result = $db->query("SELECT cumul FROM users WHERE id='".$don['user_id']."'");
$cumul = $result->fetch(\PDO::FETCH_ASSOC); $cumul = $result->fetch(\PDO::FETCH_ASSOC);
......
...@@ -29,6 +29,7 @@ GET @edit_support:/admin/support/edit/@id=Controller\Admin->support ...@@ -29,6 +29,7 @@ GET @edit_support:/admin/support/edit/@id=Controller\Admin->support
POST @modify_support:/admin/support/edit=Controller\Admin->support POST @modify_support:/admin/support/edit=Controller\Admin->support
GET @invalidate_support:/admin/support/invalidate/@id=Controller\Admin->invalidate GET @invalidate_support:/admin/support/invalidate/@id=Controller\Admin->invalidate
GET @validate_support:/admin/support/validate/@id=Controller\Admin->validate GET @validate_support:/admin/support/validate/@id=Controller\Admin->validate
GET @recompute:/admin/recompute=Controller\Admin->recompute
GET|POST @admin_accounts:/admin/accounts=Controller\Admin->accounts GET|POST @admin_accounts:/admin/accounts=Controller\Admin->accounts
...@@ -46,7 +47,7 @@ POST @modify_user:/admin/users/@id=Controller\Admin->user ...@@ -46,7 +47,7 @@ POST @modify_user:/admin/users/@id=Controller\Admin->user
POST @adresse:/admin/adresses=Controller\Admin->adresse POST @adresse:/admin/adresses=Controller\Admin->adresse
GET @counterparts_dashboard:/admin/counterparts_dashboard=Controller\Admin->counterparts_dashboard GET|POST @counterparts_dashboard:/admin/counterparts_dashboard=Controller\Admin->counterparts_dashboard
GET|POST @banque:/admin/banque=Controller\Admin->banque GET|POST @banque:/admin/banque=Controller\Admin->banque
......
...@@ -2,8 +2,8 @@ ...@@ -2,8 +2,8 @@
<h2>Gestion banque</h2> <h2>Gestion banque</h2>
<check if="{{@result}}"><p class="result">{{@result | raw}}</p></check> <check if="{{@result}}"><p class="result">{{@result | raw}}</p></check>
<check if="{{@error}}"><p class="error">{{@error | raw}}</p></check> <check if="{{@SESSION.error}}"><message messages="{{@SESSION.error}}" class="alert alert-danger"/></check>
<check if="{{@message}}"><p class="message">{{@message | raw}}</p></check> <check if="{{@SESSION.message}}"><message messages="{{@SESSION.message}}" class="alert alert-danger" /></p></check>
<section id="cbs"> <section id="cbs">
<h3 >Mise à jour des dates d'expiration des CB</h3> <h3 >Mise à jour des dates d'expiration des CB</h3>
......
<section> <section>
<h2>Import des contreparties depuis un fichier csv</h2>
<p>Veuillez préparer un fichier csv du format : Mail;quoi;</p>
<form enctype="multipart/form-data" method=POST action="{{ 'counterparts_dashboard' | alias}}">
<input type="hidden" id="csrf" name="csrf" value="{{ @CSRF }}" />
<input type="file" id="file" name="file">
<br />
<input type="submit" value="Pousser le fichier">
</form>
{{ var_dump(@counterparts_import) }}
<message messages="{{@SESSION.error}}" class="alert alert-danger" />
</form>
</section>
<h2>Tableau de bord des contreparties</h2> <h2>Tableau de bord des contreparties</h2>
<table cellspacing="0" cellpadding="0"> <table cellspacing="0" cellpadding="0">
<theader> <theader>
...@@ -19,8 +31,8 @@ ...@@ -19,8 +31,8 @@
</tr> </tr>
<tr> <tr>
<td>Hoodies</td> <td>Hoodies</td>
<td style="text-align:right;"><b>{{ @hoodie_s1 }}</b></td> <td style="text-align:right;"><b>{{ @hoopie_s1 }}</b></td>
<td style="text-align:right;">{{ @hoodie_s2 }}</td> <td style="text-align:right;">{{ @hoopie_s2 }}</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
......
...@@ -52,9 +52,8 @@ ...@@ -52,9 +52,8 @@
<input type="submit" value="Voir ce don" /> <input type="submit" value="Voir ce don" />
</form> </form>
<br /> <br />
<check if="{{ @msg }}"> <check if="{{ @SESSION.error }}"> <message messages="{{ @SESSION.error }}" class="alert alert-danger" /> </check>
<span class="error">{{ @msg }}</span> <check if="{{ @SESSION.message }}"> <message messages="{{ @SESSION.message }}" class="alert alert-default" /> </check>
</check>
</section> </section>
<script type="text/javascript"> <script type="text/javascript">
......
...@@ -45,6 +45,8 @@ ...@@ -45,6 +45,8 @@
<input type="submit" value="Filtrer" /> <input type="submit" value="Filtrer" />
</form> </form>
<a href="{{ 'recompute' | alias }}">Recalculer les totaux et cumuls de toute la base de donnée</a>
<br />
<check if="{{ @row_count }}"><b>{{ @row_count }} résultats</b> <check if="{{ @row_count }}"><b>{{ @row_count }} résultats</b>
<br /> <br />
<table cellspacing="0" cellpadding="0"> <table cellspacing="0" cellpadding="0">
......
...@@ -154,7 +154,7 @@ ...@@ -154,7 +154,7 @@
</nav> </nav>
</div> </div>
<section id="messages"> <section id="messages">
<message messages="@SESSION.message" class="alert alert-default"> <message messages="{{ @SESSION.message }}" class="alert alert-default">
<message messages="@SESSION.error" class="alert alert-danger"> <message messages="{{ @SESSION.error }}" class="alert alert-danger">
</section> </section>
...@@ -33,6 +33,24 @@ class CounterpartSeeder extends AbstractSeed ...@@ -33,6 +33,24 @@ class CounterpartSeeder extends AbstractSeed
'status' => 2, 'status' => 2,
'adresse_id' => null, 'adresse_id' => null,
), ),
array(
'id' => 3,
'datec' => '2016-06-22 12:34',
'user_id' => 2,
'quoi' => 'pibag', // [piplome|pibag|pishirt|hoodie]
'taille' => 2,
'status' => 2,
'adresse_id' => null,
),
array(
'id' => 4,
'datec' => '2016-06-22 12:34',
'user_id' => 2,
'quoi' => 'hoopie', // [piplome|pibag|pishirt|hoodie]
'taille' => 2,
'status' => 2,
'adresse_id' => null,
),
); );
$this->table('contreparties')->insert($data)->save(); $this->table('contreparties')->insert($data)->save();
......
<?php
namespace LQDN\Command;
class AdminUpdateTotalUsersCommand
{
// There is no parameters for this command.
}
<?php
namespace LQDN\Command;
class DonationIncStatusCommand
{
private $donId;
public function __construct($donId)
{
$this->donId = $donId;
}
public function getId()
{
return $this->donId;
}
}
...@@ -7,6 +7,8 @@ class UserCreateCommand ...@@ -7,6 +7,8 @@ class UserCreateCommand
private $email; private $email;
private $hash; private $hash;
private $pseudo; private $pseudo;
private $cumul;
private $total;
public function __construct($email, $hash, $pseudo, $cumul, $total) public function __construct($email, $hash, $pseudo, $cumul, $total)
{ {
......
...@@ -23,13 +23,7 @@ class DonationFinder ...@@ -23,13 +23,7 @@ class DonationFinder
public function findByUserId($userId) public function findByUserId($userId)
{ {
$userId = (int) $userId; $userId = (int) $userId;
$donations = []; return $this->connection->executeQuery("SELECT * FROM dons WHERE user_id=:userId", ["userId" => $userId])->fetchAll(\PDO::FETCH_ASSOC);
$stmt = $this->connection->query("SELECT * FROM dons WHERE user_id='$userId'");
while ($donation = $stmt->fetch()) {
$donations[$donation['id']] = $donation;
}
return $donations;
} }
/** /**
...@@ -39,16 +33,9 @@ class DonationFinder ...@@ -39,16 +33,9 @@ class DonationFinder
* *
* @return [] * @return []
*/ */
public function findById($donationId) public function findById($did)
{ {
$donationId = (int) $donationId; return $this->connection->executeQuery("SELECT * FROM dons WHERE id=:did", ["did" => $did])->fetch(\PDO::FETCH_ASSOC);
$donations = [];
$stmt = $this->connection->query("SELECT * FROM dons WHERE id='$donationId'");
while ($donation = $stmt->fetch()) {
$donations[$donationId] = $donation;
}
return $donations;
} }
/** /**
* Return dons for admins. * Return dons for admins.
......
...@@ -7,6 +7,7 @@ use LQDN\Command\DonationCreateCommand; ...@@ -7,6 +7,7 @@ use LQDN\Command\DonationCreateCommand;
use LQDN\Command\DonationInvalidateCommand; use LQDN\Command\DonationInvalidateCommand;
use LQDN\Command\DonationResetPdfCommand; use LQDN\Command\DonationResetPdfCommand;
use LQDN\Command\DonationValidateCommand; use LQDN\Command\DonationValidateCommand;
use LQDN\Command\DonationIncStatusCommand;
class DonationHandler class DonationHandler
{ {
...@@ -67,4 +68,14 @@ EOF; ...@@ -67,4 +68,14 @@ EOF;
{ {
$this->connection->executeUpdate('UPDATE dons SET pdf = "" WHERE id = :id', ['id' => $command->getId()]); $this->connection->executeUpdate('UPDATE dons SET pdf = "" WHERE id = :id', ['id' => $command->getId()]);
} }
/**
* Increase the status of a donation
*
* @param DonationIncStatusCommand $command
*/
public function handleDonationIncStatusCommand(DonationIncStatusCommand $command)
{
$this->connection->executeUpdate('UPDATE dons SET status = status + 1 WHERE id = :id', ['id' => $command->getId()]);
}
} }
...@@ -7,6 +7,7 @@ use LQDN\Command\UserUpdateByAdminCommand; ...@@ -7,6 +7,7 @@ use LQDN\Command\UserUpdateByAdminCommand;
use LQDN\Command\UserUpdateTotalCommand; use LQDN\Command\UserUpdateTotalCommand;
use LQDN\Command\UserUpdateCumulCommand; use LQDN\Command\UserUpdateCumulCommand;
use LQDN\Command\UserCreateCommand; use LQDN\Command\UserCreateCommand;
use LQDN\Command\AdminUpdateTotalUsersCommand;
class UserHandler class UserHandler
{ {
...@@ -39,13 +40,13 @@ class UserHandler ...@@ -39,13 +40,13 @@ class UserHandler
*/ */
public function handleUserCreateCommand(UserCreateCommand $command) public function handleUserCreateCommand(UserCreateCommand $command)
{ {
$stmt = $this->connection->prepare('INSERT INTO users(email, hash, pseudo, total, cumul) VALUES (:email, :hash, :pseudo, :total, :cumul)'); $this->connection->executeUpdate('INSERT INTO users(email, hash, pseudo, total, cumul) VALUES (:email, :hash, :pseudo, :total, :cumul)', [
$stmt->bindValue('email', $command->getEmail()); 'email'=> $command->getEmail(),
$stmt->bindValue('hash', $command->getHash()); 'hash'=> $command->getHash(),
$stmt