Payments - better recognition of dates
[platal.git] / modules / payment.php
CommitLineData
a2558f2b 1<?php
2/***************************************************************************
5e1513f6 3 * Copyright (C) 2003-2011 Polytechnique.org *
a2558f2b 4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22/* sort en affichant une erreur */
23function cb_erreur($text) {
115c90db 24 global $globals;
9d773172 25 echo "Error.\n";
1e33266a 26 $mymail = new PlMailer();
d7dd70be 27 $mymail->addTo($globals->money->email);
1d55fe45 28 $mymail->setFrom("webmaster@" . $globals->mail->domain);
a7de4ef7 29 $mymail->setSubject("erreur lors d'un télépaiement (CyberPaiement)");
a2558f2b 30 $mymail->setTxtBody("\n\n".var_export($_REQUEST,true));
31 $mymail->send();
9d773172 32 echo "Notification sent.\n";
a2558f2b 33 exit;
34}
35
36/* sort en affichant une erreur */
88e3843c 37function paypal_erreur($text, $send=true)
38{
d7610c35 39 global $erreur, $globals;
a2558f2b 40 if ($erreur) return;
41 $erreur = $text;
42 if (!$send) return;
43
1e33266a 44 $mymail = new PlMailer();
d7dd70be 45 $mymail->addTo($globals->money->email);
1d55fe45 46 $mymail->setFrom("webmaster@" . $globals->mail->domain);
a7de4ef7 47 $mymail->setSubject("erreur lors d'un télépaiement (PayPal)");
a2558f2b 48 $mymail->setTxtBody("\n\n".var_export($_REQUEST,true));
49 $mymail->send();
50
d7610c35 51 Platal::page()->trigError($text);
a2558f2b 52}
53
54/* http://fr.wikipedia.org/wiki/Formule_de_Luhn */
55function luhn($nombre) {
56 $s = strrev($nombre);
57 $sum = 0;
f5e965ca 58 for ($i = 0; $i < strlen($s); ++$i) {
9d773172 59 $dgt = $s{$i};
f5e965ca 60 $sum += ($i % 2) ? (2 * $dgt) % 9 : $dgt;
a2558f2b 61 }
62 return $sum % 10;
63}
64
a7de4ef7 65/* calcule la clé d'acceptation a partir de 5 champs */
f5e965ca 66function cle_accept($d1, $d2, $d3, $d4, $d5)
a2558f2b 67{
f5e965ca
SJ
68 $m1 = luhn($d1 . $d5);
69 $m2 = luhn($d2 . $d5);
70 $m3 = luhn($d3 . $d5);
71 $m4 = luhn($d4 . $d5);
a2558f2b 72 $n = $m1 + $m2 + $m3 + $m4;
f5e965ca
SJ
73 $alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
74 return $alpha{$n-1} . $m1 . $m2 . $m3 . $m4;
a2558f2b 75}
76
17793ccf
FB
77/* decode the comment */
78function comment_decode($comment) {
79 $comment = urldecode($comment);
80 if (is_utf8($comment)) {
81 return $comment;
82 } else {
83 return utf8_encode($comment);
84 }
85}
86
f56ceafe
DB
87/* check if a RIB account number is valid */
88function check_rib($rib)
89{
f3d6e2cc 90 if(strlen($rib) != 23) return false;
f5e965ca 91
f56ceafe
DB
92 // extract fields
93 $rib = strtr(strtoupper($rib),'ABCDEFGHIJKLMNOPQRSTUVWXYZ','12345678912345678923456789');
f3d6e2cc
DB
94 $bank = substr($rib,0,5);
95 $counter = substr($rib,5,5);
96 $account = substr($rib,10,11);
97 $key = substr($rib,21,2);
f5e965ca 98
f56ceafe 99 // check
f5e965ca 100 return (0 == fmod(89 * $bank + 15 * $counter + 3 * $account + $key, 97));
f56ceafe 101}
a2558f2b 102
103class PaymentModule extends PLModule
104{
105 function handlers()
106 {
107 return array(
f5e965ca 108 'payment' => $this->make_hook('payment', AUTH_MDP, 'payment'),
f5e965ca
SJ
109 'payment/cyber2_return' => $this->make_hook('cyber2_return', AUTH_PUBLIC, 'user', NO_HTTPS),
110 'payment/paypal_return' => $this->make_hook('paypal_return', AUTH_PUBLIC, 'user', NO_HTTPS),
111 '%grp/paiement' => $this->make_hook('xnet_payment', AUTH_MDP),
112 '%grp/payment' => $this->make_hook('xnet_payment', AUTH_MDP),
4294dc6c 113 '%grp/payment/csv' => $this->make_hook('payment_csv', AUTH_MDP, 'groupadmin'),
f5e965ca
SJ
114 '%grp/payment/cyber2_return' => $this->make_hook('cyber2_return', AUTH_PUBLIC, 'user', NO_HTTPS),
115 '%grp/payment/paypal_return' => $this->make_hook('paypal_return', AUTH_PUBLIC, 'user', NO_HTTPS),
116 'admin/payments' => $this->make_hook('admin', AUTH_MDP, 'admin'),
117 'admin/payments/methods' => $this->make_hook('adm_methods', AUTH_MDP, 'admin'),
118 'admin/payments/transactions' => $this->make_hook('adm_transactions', AUTH_MDP, 'admin'),
119 'admin/reconcile' => $this->make_hook('adm_reconcile', AUTH_MDP, 'admin'),
120 'admin/reconcile/importlogs' => $this->make_hook('adm_importlogs', AUTH_MDP, 'admin'),
121 'admin/reconcile/transfers' => $this->make_hook('adm_transfers', AUTH_MDP, 'admin'),
122 'admin/reconcile/bankaccounts' => $this->make_hook('adm_bankaccounts', AUTH_MDP, 'admin'),
a2558f2b 123 );
124 }
125
26ba053e 126 function handler_payment($page, $ref = -1)
a2558f2b 127 {
128 global $globals;
129
460d8f55 130 $this->load('money.inc.php');
a2558f2b 131
98a7e9dc 132 if (!empty($GLOBALS['IS_XNET_SITE'])) {
133 if (!$globals->asso('id')) {
134 return PL_NOT_FOUND;
135 }
f5e965ca
SJ
136 $res = XDB::query('SELECT asso_id
137 FROM payments
138 WHERE asso_id = {?} AND id = {?}',
98a7e9dc 139 $globals->asso('id'), $ref);
140 if (!$res->numRows()) {
141 return PL_FORBIDDEN;
142 }
98a7e9dc 143 }
1490093c 144 $page->changeTpl('payment/index.tpl');
46f272fe 145 $page->setTitle('Télépaiements');
a2558f2b 146
147 // initialisation
5e2307dc 148 $op = Env::v('op', 'select');
149 $meth = new PayMethod(Env::i('methode', -1));
a2558f2b 150 $pay = new Payment($ref);
151
152 if($pay->flags->hasflag('old')){
a7d35093 153 $page->trigError("La transaction selectionnée est périmée.");
a2558f2b 154 $pay = new Payment();
155 }
a690a74c 156 $val = Env::v('montant') != 0 ? Env::v('montant') : $pay->amount_def;
a2558f2b 157
158 if (($e = $pay->check($val)) !== true) {
a7d35093 159 $page->trigError($e);
a2558f2b 160 }
161
f5e965ca 162 if ($op == 'submit') {
a2558f2b 163 $pay->init($val, $meth);
164 $pay->prepareform($pay);
165 } else {
f5e965ca 166 $res = XDB::iterator('SELECT timestamp, amount
69fffc4b 167 FROM payment_transactions
8a7fab54 168 WHERE uid = {?} AND ref = {?}
f5e965ca 169 ORDER BY timestamp DESC',
8a7fab54 170 S::v('uid', -1), $ref);
a2558f2b 171
f5e965ca
SJ
172 if ($res->total()) {
173 $page->assign('transactions', $res);
174 }
069dfa8e
SJ
175
176 if ($pay->flags->hasflag('donation')) {
177 $donations = XDB::fetchAllAssoc('SELECT IF(p.display,
178 IF(ap.pid IS NOT NULL, CONCAT(a.full_name, \' (\', pd.promo, \')\'), a.full_name),
179 \'XXXX\') AS name, p.amount
180 FROM payment_transactions AS p
181 INNER JOIN accounts AS a ON (a.uid = p.uid)
182 LEFT JOIN account_profiles AS ap ON (a.uid = ap.uid AND FIND_IN_SET(\'owner\', ap.perms))
183 LEFT JOIN profile_display AS pd ON (ap.pid = pd.pid)
184 WHERE p.ref = {?}
185 ORDER BY LENGTH(p.amount) DESC, p.amount DESC, name',
186 $ref);
187 $sum = 0;
188 foreach ($donations as $d) {
189 $amount = $d['amount'];
190 $sum += trim(strtr(substr($amount, 0, strpos($amount, 'EUR')), ',', '.'));
191 }
192
193 $page->assign('donations', $donations);
194 $page->assign('sum', strtr($sum, '.', ','));
195 }
a2558f2b 196 }
197
f5e965ca
SJ
198 $val = floor($val) . '.' . substr(floor(($val - floor($val)) * 100 + 100), 1);
199 $page->assign('montant', $val);
200 $page->assign('comment', Env::v('comment'));
a2558f2b 201
202 $page->assign('meth', $meth);
f5e965ca 203 $page->assign('pay', $pay);
a2558f2b 204 $page->assign('evtlink', $pay->event());
d6c91d50 205 $page->assign('sex', S::user()->isFemale());
fbb196fa 206 $page->assign('donation', $pay->flags->hasflag('donation'));
a2558f2b 207 }
208
26ba053e 209 function handler_cyber2_return($page, $uid = null)
a690a74c
DB
210 {
211 global $globals, $platal;
aab2ffdd 212
a690a74c
DB
213 /* on vérifie la signature */
214 $vads_params = array();
215 foreach($_REQUEST as $key => $value)
f5e965ca 216 if(substr($key,0,5) == 'vads_') {
9d773172 217 $vads_params[$key] = $value;
f5e965ca 218 }
a690a74c 219 ksort($vads_params);
f5e965ca 220 $signature = sha1(join('+', $vads_params) . '+' . $globals->money->cyperplus_key);
a690a74c
DB
221 //if($signature != Env::v('signature')) {
222 // cb_erreur("signature invalide");
223 //}
aab2ffdd 224
a690a74c 225 /* on extrait les informations sur l'utilisateur */
ba0fd7f8 226 $user = User::get(Env::i('vads_cust_id'));
a690a74c
DB
227 if (!$user) {
228 cb_erreur("uid invalide");
229 }
230
231 /* on extrait la reference de la commande */
232 if (!ereg('-([0-9]+)$', Env::v('vads_order_id'), $matches)) {
233 cb_erreur("référence de commande invalide");
234 }
235
9d773172 236 $ref = $matches[1];
f5e965ca 237 $res = XDB::query('SELECT mail, text, confirmation
a690a74c 238 FROM payments
f336915b 239 WHERE id={?}', $ref);
781c92a2 240 if ($res->numRows() != 1) {
a690a74c
DB
241 cb_erreur("référence de commande inconnue");
242 }
781c92a2 243 list($conf_mail, $conf_title, $conf_text) = $res->fetchOneRow();
aab2ffdd 244
a690a74c 245 /* on extrait le montant */
f5e965ca 246 if (Env::v('vads_currency') != '978') {
a690a74c
DB
247 cb_erreur("monnaie autre que l'euro");
248 }
ba0fd7f8
RB
249 $amount = ((float)Env::i('vads_amount')) / 100;
250 $montant = sprintf("%.02f EUR", $amount);
a690a74c
DB
251
252 /* on extrait le code de retour */
f5e965ca
SJ
253 if (Env::v('vads_result') != '00') {
254 cb_erreur('erreur lors du paiement : ?? (' . Env::v('vads_result') . ')');
a690a74c 255 }
aab2ffdd 256
a690a74c 257 /* on fait l'insertion en base de donnees */
fbb196fa
SJ
258 XDB::execute('INSERT INTO payment_transactions (id, uid, ref, fullref, amount, pkey, comment, display)
259 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
260 Env::v('vads_trans_date'), $user->id(), $ref, Env::v('vads_order_id'), $montant, '', Env::v('vads_order_info'), Env::i('vads_order_info2'));
9d773172 261 echo "Paiement stored.\n";
aab2ffdd 262
a690a74c 263 // We check if it is an Xnet payment and then update the related ML.
6848fb7e 264 $res = XDB::query('SELECT eid, asso_id
a690a74c
DB
265 FROM group_events
266 WHERE paiement_id = {?}', $ref);
781c92a2 267 if ($res->numRows() == 1) {
6848fb7e 268 list($eid, $asso_id) = $res->fetchOneRow();
a690a74c 269 require_once dirname(__FILE__) . '/xnetevents/xnetevents.inc.php';
6848fb7e 270 $evt = get_event_detail($eid, false, $asso_id);
7852229b 271 subscribe_lists_event($user->id(), $evt['short_name'], 1, $amount, true);
a690a74c
DB
272 }
273
274 /* on genere le mail de confirmation */
275 $conf_text = str_replace(
781c92a2 276 array('<prenom>', '<nom>', '<promo>', '<montant>', '<salutation>', '<cher>', '<comment>'),
a690a74c
DB
277 array($user->firstName(), $user->lastName(), $user->promo(), $montant,
278 $user->isFemale() ? 'Chère' : 'Cher', $user->isFemale() ? 'Chère' : 'Cher',
9170f4f9 279 Env::v('vads_order_info')), $conf_text);
a690a74c
DB
280
281 global $globals;
282 $mymail = new PlMailer();
283 $mymail->setFrom($conf_mail);
284 $mymail->addCc($conf_mail);
285 $mymail->setSubject($conf_title);
286 $mymail->setWikiBody($conf_text);
287 $mymail->sendTo($user);
288
289 /* on envoie les details de la transaction à telepaiement@ */
290 $mymail = new PlMailer();
291 $mymail->setFrom("webmaster@" . $globals->mail->domain);
292 $mymail->addTo($globals->money->email);
293 $mymail->setSubject($conf_title);
294 $msg = 'utilisateur : ' . $user->login() . ' (' . $user->id() . ')' . "\n" .
295 'mail : ' . $user->forlifeEmail() . "\n\n" .
296 "paiement : $conf_title ($conf_mail)\n".
9d773172 297 "reference : " . Env::v('vads_order_id') . "\n".
a690a74c
DB
298 "montant : $montant\n\n".
299 "dump de REQUEST:\n".
300 var_export($_REQUEST,true);
301 $mymail->setTxtBody($msg);
302 $mymail->send();
9d773172 303 echo "Notifications sent.\n";
a690a74c
DB
304 exit;
305 }
306
26ba053e 307 function handler_paypal_return($page, $uid = null)
a2558f2b 308 {
da157660 309 $page->changeTpl('payment/retour_paypal.tpl');
a2558f2b 310
311 /* reference banque (numero de transaction) */
7280eb45 312 $no_transaction = Env::s('tx');
a2558f2b 313 /* token a renvoyer pour avoir plus d'information */
7280eb45 314 $clef = Env::s('sig');
a2558f2b 315 /* code retour */
7280eb45 316 $status = Env::s('st');
a2558f2b 317 /* raison */
f5e965ca 318 $reason = ($status == 'Pending') ? Env::s('pending_reason') : Env::s('reason_code');
a2558f2b 319 /* reference complete de la commande */
7280eb45 320 $fullref = Env::s('cm');
a2558f2b 321 /* montant de la transaction */
7280eb45 322 $montant_nb = Env::s('amt');
a2558f2b 323 /* devise */
7280eb45 324 $montant_dev = Env::s('cc');
a2558f2b 325 $montant = "$montant_nb $montant_dev";
326
327 /* on extrait le code de retour */
328 if ($status != "Completed") {
f5e965ca 329 if ($status) {
a2558f2b 330 paypal_erreur("erreur lors du paiement : $status - $reason");
f5e965ca 331 } else {
a7de4ef7 332 paypal_erreur("Paiement annulé", false);
f5e965ca 333 }
a2558f2b 334 }
335
336 /* on extrait les informations sur l'utilisateur */
1eaaa62d
FB
337 $user = User::get($uid);
338 if (!$user) {
a2558f2b 339 paypal_erreur("uid invalide");
340 }
341
342 /* on extrait la reference de la commande */
1eaaa62d 343 if (!ereg('-xorg-([0-9]+)$', $fullref, $matches)) {
a7de4ef7 344 paypal_erreur("référence de commande invalide");
a2558f2b 345 }
346
347 $ref = $matches[1];
f5e965ca 348 $res = XDB::query('SELECT mail, text, confirmation
69fffc4b 349 FROM payments
f5e965ca
SJ
350 WHERE id = {?}', $ref);
351 if (!list($conf_mail, $conf_title, $conf_text) = $res->fetchOneRow()) {
352 paypal_erreur('référence de commande inconnue');
a2558f2b 353 }
354
355 /* on fait l'insertion en base de donnees */
fbb196fa
SJ
356 XDB::execute("INSERT INTO payment_transactions (id, uid, ref, fullref, amount, pkey, comment, display)
357 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, '?})",
358 $no_transaction, $user->id(), $ref, $fullref, $montant, $clef, Env::v('comment'), Get::i('display'));
a2558f2b 359
9ff5b337
SJ
360 // We check if it is an Xnet payment and then update the related ML.
361 $res = XDB::query('SELECT eid
eb41eda9 362 FROM group_events
9ff5b337
SJ
363 WHERE paiement_id = {?}', $ref);
364 if ($eid = $res->fetchOneCell()) {
fd03857b 365 require_once dirname(__FILE__) . '/xnetevents/xnetevents.inc.php';
9ff5b337 366 $evt = get_event_detail($eid);
7852229b 367 subscribe_lists_event($user->id(), $evt['short_name'], 1, $montant, true);
9ff5b337
SJ
368 }
369
a2558f2b 370 /* on genere le mail de confirmation */
fb25f6a6 371 $conf_text = str_replace(array('<prenom>', '<nom>', '<promo>', '<montant>', '<salutation>', '<cher>', '<comment>'),
1eaaa62d 372 array($user->firstName(), $user->lastName(), $user->promo(), $montant,
fb25f6a6
SJ
373 $user->isFemale() ? 'Chère' : 'Cher', $user->isFemale() ? 'Chère' : 'Cher',
374 Env::v('comment')), $conf_text);
a2558f2b 375
7895f3c1 376 global $globals;
1e33266a 377 $mymail = new PlMailer();
a2558f2b 378 $mymail->setFrom($conf_mail);
a2558f2b 379 $mymail->addCc($conf_mail);
380 $mymail->setSubject($conf_title);
88e3843c 381 $mymail->setWikiBody($conf_text);
1eaaa62d 382 $mymail->sendTo($user);
a2558f2b 383
a7de4ef7 384 /* on envoie les details de la transaction à telepaiement@ */
1e33266a 385 $mymail = new PlMailer();
1d55fe45 386 $mymail->setFrom("webmaster@" . $globals->mail->domain);
d7dd70be 387 $mymail->addTo($globals->money->email);
a2558f2b 388 $mymail->setSubject($conf_title);
1eaaa62d
FB
389 $msg = 'utilisateur : ' . $user->login() . ' (' . $user->id() . ')' . "\n" .
390 'mail : ' . $user->forlifeEmail() . "\n\n" .
a2558f2b 391 "paiement : $conf_title ($conf_mail)\n".
1eaaa62d 392 "reference : $champ200\n".
a2558f2b 393 "montant : $montant\n\n".
394 "dump de REQUEST:\n".
395 var_export($_REQUEST,true);
396 $mymail->setTxtBody($msg);
397 $mymail->send();
398
399 $page->assign('texte', $conf_text);
400 $page->assign('erreur', $erreur);
a2558f2b 401 }
98a7e9dc 402
26ba053e 403 function handler_xnet_payment($page, $pid = null)
98a7e9dc 404 {
405 global $globals;
eaf30d86 406
45a5307b
FB
407 $perms = S::v('perms');
408 if (!$perms->hasFlag('groupmember')) {
409 if (is_null($pid)) {
410 return PL_FORBIDDEN;
411 }
412 $res = XDB::query("SELECT 1
eb41eda9 413 FROM group_events AS e
60dd1466 414 INNER JOIN group_event_participants AS ep ON (ep.eid = e.eid AND e.uid = {?})
45a5307b
FB
415 WHERE e.paiement_id = {?} AND e.asso_id = {?}",
416 S::i('uid'), $pid, $globals->asso('id'));
417 if ($res->numRows() == 0) {
418 return PL_FORBIDDEN;
419 }
420 }
421
98a7e9dc 422 if (!is_null($pid)) {
423 return $this->handler_payment($page, $pid);
424 }
1490093c 425 $page->changeTpl('payment/xnet.tpl');
eaf30d86 426
98a7e9dc 427 $res = XDB::query(
428 "SELECT id, text, url
a690a74c 429 FROM payments
010268b2 430 WHERE asso_id = {?} AND NOT FIND_IN_SET('old', flags)
98a7e9dc 431 ORDER BY id DESC", $globals->asso('id'));
432 $tit = $res->fetchAllAssoc();
af387c4b 433 $page->assign('titles', $tit);
98a7e9dc 434
98a7e9dc 435 $trans = array();
436 $event = array();
af387c4b
SJ
437 if (may_update()) {
438 static $orders = array('timestamp' => 'p', 'directory_name' => 'a', 'promo' => 'pd', 'comment' => 'p', 'amount' => 'p');
439
440 if (Get::has('order_id') && Get::has('order') && array_key_exists(Get::v('order'), $orders)) {
441 $order_id = Get::i('order_id');
442 $order = Get::v('order');
443 $ordering = ' ORDER BY ' . $orders[$order] . '.' . $order;
444 if (Get::has('order_inv') && Get::i('order_inv') == 1) {
445 $ordering .= ' DESC';
446 $page->assign('order_inv', 0);
447 } else {
448 $page->assign('order_inv', 1);
449 }
450 $page->assign('order_id', $order_id);
451 $page->assign('order', $order);
741d92e9 452 $page->assign('anchor', 'legend_' . $order_id);
af387c4b
SJ
453 } else {
454 $order_id = false;
455 $ordering = '';
456 $page->assign('order', false);
457 }
458 } else {
459 $ordering = '';
460 $page->assign('order', false);
461 }
98a7e9dc 462 foreach($tit as $foo) {
463 $pid = $foo['id'];
464 if (may_update()) {
af387c4b
SJ
465 $res = XDB::query('SELECT p.uid, IF(p.timestamp = \'0000-00-00\', 0, p.timestamp) AS date, p.comment, p.amount
466 FROM payment_transactions AS p
467 INNER JOIN accounts AS a ON (a.uid = p.uid)
468 LEFT JOIN account_profiles AS ap ON (ap.uid = p.uid AND FIND_IN_SET(\'owner\', ap.perms))
469 LEFT JOIN profile_display AS pd ON (ap.pid = pd.pid)
470 WHERE p.ref = {?}' . (($order_id == $pid) ? $ordering : ''),
471 $pid);
1eaaa62d
FB
472 $trans[$pid] = User::getBulkUsersWithUIDs($res->fetchAllAssoc(), 'uid', 'user');
473 $sum = 0;
474 foreach ($trans[$pid] as $i => $t) {
b3cd1320
DB
475 $sum += strtr(substr($t['amount'], 0, strpos($t['amount'], 'EUR')), ',', '.');
476 $trans[$pid][$i]['amount'] = str_replace('EUR', '€', $t['amount']);
1eaaa62d 477 }
f5e965ca
SJ
478 $trans[$pid][] = array('limit' => true,
479 'amount' => strtr($sum, '.', ',') . ' €');
98a7e9dc 480 }
f5e965ca
SJ
481 $res = XDB::iterRow("SELECT e.eid, e.short_name, e.intitule, ep.nb, ei.montant, ep.paid
482 FROM group_events AS e
483 LEFT JOIN group_event_participants AS ep ON (ep.eid = e.eid AND ep.uid = {?})
484 INNER JOIN group_event_items AS ei ON (ep.eid = ei.eid AND ep.item_id = ei.item_id)
485 WHERE e.paiement_id = {?}",
486 S::v('uid'), $pid);
98a7e9dc 487 $event[$pid] = array();
488 $event[$pid]['paid'] = 0;
489 if ($res->total()) {
490 $event[$pid]['topay'] = 0;
491 while(list($eid, $shortname, $title, $nb, $montant, $paid) = $res->next()) {
492 $event[$pid]['topay'] += ($nb * $montant);
493 $event[$pid]['eid'] = $eid;
494 $event[$pid]['shortname'] = $shortname;
495 $event[$pid]['title'] = $title;
496 $event[$pid]['ins'] = !is_null($nb);
497 $event[$pid]['paid'] = $paid;
498 }
499 }
f5e965ca
SJ
500 $res = XDB::query('SELECT amount
501 FROM payment_transactions
e7d5bad7 502 WHERE ref = {?} AND uid = {?}', $pid, S::v('uid'));
98a7e9dc 503 $montants = $res->fetchColumn();
504
505 foreach ($montants as $m) {
506 $p = strtr(substr($m, 0, strpos($m, 'EUR')), ',', '.');
507 $event[$pid]['paid'] += trim($p);
508 }
509 }
17793ccf 510 $page->register_modifier('decode_comment', 'decode_comment');
98a7e9dc 511 $page->assign('trans', $trans);
512 $page->assign('event', $event);
513 }
eaf30d86 514
4294dc6c
SJ
515 function handler_payment_csv($page, $pid = null)
516 {
517 if (is_null($pid)) {
518 pl_redirect('payment');
519 }
520 if (substr($pid, -4) == '.vcf') {
521 $pid = substr($pid, 0, strlen($pid) - 4);
522 }
523
524 $res = XDB::fetchAllAssoc('SELECT uid, IF(timestamp = \'0000-00-00\', 0, timestamp) AS date, comment, amount
525 FROM payment_transactions
526 WHERE ref = {?}
527 ORDER BY timestamp',
528 $pid);
529 if (is_null($res)) {
530 pl_redirect('payment');
531 }
532
533 $users = User::getBulkUsersWithUIDs($res, 'uid', 'user');
534 $sum = 0;
535
536 pl_cached_content_headers('text/x-csv', 1);
537 $csv = fopen('php://output', 'w');
538 fputcsv($csv, array('Date', 'Nom', 'Prénom', 'Sexe', 'Promotion', 'Email', 'Commentaire', 'Montant'), ';');
539 foreach ($users as $item) {
540 $user = $item['user'];
541 $sum += strtr(substr($item['amount'], 0, strpos($item['amount'], 'EUR')), ',', '.');
542 fputcsv($csv, array(format_datetime($item['date'], '%d/%m/%y'), $user->lastName(), $user->firstName(),
543 ($user->isFemale()) ? 'F' : 'M', $user->promo(), $user->ForlifeEmail(),
544 $item['comment'], str_replace('EUR', '€', $item['amount'])), ';');
545 }
546 fputcsv($csv, array(date('d/m/y'), 'Total', '', '', '' , '', '', strtr($sum, '.', ',') . ' €'), ';');
547
548 fclose($csv);
549 exit;
550 }
551
26ba053e 552 function handler_admin($page, $action = 'list', $id = null) {
46f272fe 553 $page->setTitle('Administration - Paiements');
a7de4ef7 554 $page->assign('title', 'Gestion des télépaiements');
69fffc4b 555 $table_editor = new PLTableEditor('admin/payments','payments','id');
f56ceafe 556 //$table_editor->add_join_table('payment_transactions','ref',true); => on ne supprime jamais une transaction
2e7b5921 557 $table_editor->add_sort_field('flags');
de61dbcf 558 $table_editor->add_sort_field('id', true, true);
69fffc4b 559 $table_editor->on_delete("UPDATE payments SET flags = 'old' WHERE id = {?}", "Le paiement a été archivé");
f5e965ca
SJ
560 $table_editor->describe('text', 'intitulé', true);
561 $table_editor->describe('url', 'site web', false);
562 $table_editor->describe('amount_def', 'montant par défaut', false);
563 $table_editor->describe('amount_min', 'montant minimum', false);
564 $table_editor->describe('amount_max', 'montant maximum', false);
565 $table_editor->describe('mail', 'email contact', true);
566 $table_editor->describe('confirmation', 'message confirmation', false);
9c966750
PC
567
568 // adds a column with the start date of the linked event if there is one
f5e965ca 569 $table_editor->add_option_table('group_events', 'group_events.paiement_id = t.id');
9c966750
PC
570 $table_editor->add_option_field('group_events.debut', 'related_event', 'évènement', 'timestamp');
571
92423144 572 $table_editor->apply($page, $action, $id);
eaf30d86 573 }
f5e965ca 574
26ba053e 575 function handler_adm_transactions($page, $payment_id = null, $action = "list", $id = null) {
f56ceafe
DB
576 // show transactions. FIXME: should not be modifiable
577 $page->setTitle('Administration - Paiements - Transactions');
578 $page->assign('title', "Liste des transactions pour le paiement {$payment_id}");
f5e965ca 579
f56ceafe
DB
580 if ($payment_id == null)
581 $page->trigError("Aucun ID de paiement fourni.");
f5e965ca 582
f56ceafe
DB
583 $table_editor = new PLTableEditor("admin/transactions/{$payment_id}",'payment_transactions','id');
584 $table_editor->set_where_clause(XDB::format('ref = {?}', $payment_id));
585 $table_editor->apply($page, 'list', $id); // only the 'list' action is allowed
f5e965ca 586 $page->assign('readonly', 'readonly'); // don't show modification features
f56ceafe 587 }
f5e965ca 588
26ba053e 589 function handler_adm_bankaccounts($page, $action = "list", $id = null) {
f56ceafe
DB
590 // managment of bank account used for money transfert
591 $page->setTitle('Administration - Paiements - RIBs');
592 $page->assign('title', "Liste des RIBs");
f5e965ca
SJ
593
594 $table_editor = new PLTableEditor('admin/payments/bankaccounts', 'payment_bankaccounts', 'id');
595 $table_editor->describe('asso_id', 'ID du groupe', false);
596 $table_editor->describe('owner', 'titulaire', true);
597 $table_editor->add_option_table('groups', 'groups.id = t.asso_id');
f56ceafe 598 $table_editor->add_option_field('groups.diminutif', 'group_name', 'groupe', 'varchar','account');
f5e965ca 599
f56ceafe 600 // check RIB key
f5e965ca 601 if ($action == 'update' && Post::has('account') && !check_rib(Post::v('account'))) {
f56ceafe 602 $page->trigError("Le RIB n'est pas valide");
f5e965ca 603 $table_editor->apply($page, 'edit', $id);
f56ceafe
DB
604 return;
605 }
f5e965ca 606
f56ceafe
DB
607 $table_editor->apply($page, $action, $id);
608 }
f5e965ca 609
26ba053e 610 function handler_adm_methods($page, $action = "list", $id = null) {
f56ceafe
DB
611 // show and edit payment methods
612 $page->setTitle('Administration - Paiements - Méthodes');
f5e965ca
SJ
613 $page->assign('title', 'Méthodes de paiement');
614 $table_editor = new PLTableEditor('admin/payments/methods', 'payment_methods', 'id');
f56ceafe
DB
615 $table_editor->apply($page, $action, $id);
616 }
617
26ba053e 618 function handler_adm_reconcile($page, $step = 'list', $param = null) {
f56ceafe
DB
619 // reconciles logs with transactions
620 // FIXME: the admin is considered to be fair => he doesn't hack the $step value, nor other params
621 $page->setTitle('Administration - Paiements - Réconciliations');
622 $page->changeTpl('payment/reconcile.tpl');
623 $page->assign('step', $step);
f3d6e2cc 624 $list = true;
f5e965ca 625
f3d6e2cc
DB
626 // actions
627 if ($step == 'delete' && $param != null) {
628 S::assert_xsrf_token();
f5e965ca 629 XDB::execute('DELETE FROM payment_reconcilations WHERE id = {?}', $param);
f3d6e2cc 630 // FIXME: hardcoding !!!
f5e965ca
SJ
631 XDB::execute('UPDATE payment_transactions SET recon_id = NULL,commission = NULL WHERE recon_id = {?} AND method_id = 2', $param);
632 XDB::execute('UPDATE payment_transactions SET recon_id = NULL WHERE recon_id = {?} AND method_id = 1', $param);
633 $page->trigSuccess("L'entrée " . $param . ' a été supprimée.');
634
f3d6e2cc
DB
635 } elseif ($step == 'edit') {
636 $page->trigError("L'édition n'est pas implémentée.");
f5e965ca 637
f3d6e2cc
DB
638 } elseif ($step == 'step5') {
639 $page->trigSuccess("La réconciliation est terminée. Il est maintenant nécessaire de générer les virements.");
f5e965ca 640
f3d6e2cc 641 }
f5e965ca 642
f3d6e2cc
DB
643 if($list) {
644 // show list of reconciliations, with a "add" button
f5e965ca 645 $page->assign('title', 'Réconciliation - Liste');
77b81d91 646 $page->assign('step', 'list');
f5e965ca 647
f3d6e2cc 648 $recongps = array();
f5e965ca 649
f3d6e2cc
DB
650 $res = XDB::query("SELECT r.id, short_name AS method, period_start, period_end, status,
651 payment_count, sum_amounts, sum_commissions
652 FROM payment_reconcilations AS r
f5e965ca 653 LEFT JOIN payment_methods AS m ON (r.method_id = m.id)
f3d6e2cc
DB
654 WHERE recongroup_id IS NULL
655 ORDER BY period_end DESC, period_start DESC");
656 foreach ($res->fetchAllAssoc() as $recon)
657 $recongps[] = array('recons' => array($recon), 'transfers' => array());
f5e965ca 658
f3d6e2cc
DB
659 $res = XDB::query("SELECT recongroup_id AS id
660 FROM payment_reconcilations
661 GROUP BY recongroup_id
662 ORDER BY MAX(period_end) DESC, MIN(period_start) DESC");
663 foreach ($res->fetchAllAssoc() as $recongp) {
664 $res = XDB::query("SELECT r.id, short_name AS method, period_start, period_end, status,
665 payment_count, sum_amounts, sum_commissions
666 FROM payment_reconcilations AS r
f5e965ca
SJ
667 LEFT JOIN payment_methods AS m ON (r.method_id = m.id)
668 WHERE recongroup_id = {?}
f3d6e2cc
DB
669 ORDER BY period_end DESC, period_start DESC",
670 $recongp['id']);
671 $recongp['recons'] = $res->fetchAllAssoc();
672
f5e965ca 673 $res = XDB::query('SELECT id, payment_id, amount, account_id, message, date
f3d6e2cc 674 FROM payment_transfers
f5e965ca 675 WHERE recongroup_id = {?}',
f3d6e2cc
DB
676 $recongp['id']);
677 $recongp['transfers'] = $res->fetchAllAssoc();
f5e965ca 678
f3d6e2cc
DB
679 $recongps[] = $recongp;
680 }
681 $page->assign_by_ref('recongps', $recongps);
682 }
77b81d91 683 }
f5e965ca 684
26ba053e 685 function handler_adm_importlogs($page, $step, $param = null) {
77b81d91
DB
686 $page->setTitle('Administration - Paiements - Réconciliations');
687 $page->changeTpl('payment/reconcile.tpl');
688 $page->assign('step', $step);
f5e965ca 689
77b81d91 690 if (isset($_SESSION['paymentrecon_data'])) {
f56ceafe 691 // create temporary table with imported data
f5e965ca 692 XDB::execute('CREATE TEMPORARY TABLE payment_tmp (
f56ceafe
DB
693 reference VARCHAR(255) PRIMARY KEY,
694 date DATE,
695 amount DECIMAL(9,2),
696 commission DECIMAL(9,2)
f5e965ca 697 )');
f56ceafe 698 foreach ($_SESSION['paymentrecon_data'] as $i)
f5e965ca 699 XDB::execute('INSERT INTO payment_tmp VALUES ({?}, {?}, {?}, {?})',
f56ceafe
DB
700 $i['reference'], $i['date'], $i['amount'], $i['commission']);
701 }
f5e965ca 702
77b81d91 703 if ($step == 'step1') {
f5e965ca 704 $page->assign('title', 'Étape 1');
77b81d91
DB
705 unset($_SESSION['paymentrecon_method']);
706 unset($_SESSION['paymentrecon_data']);
707 unset($_SESSION['paymentrecon_id']);
f5e965ca 708
f56ceafe
DB
709 // was a payment method choosen ?
710 if ($param != null) {
711 $_SESSION['paymentrecon_method'] = (int)$param;
f5e965ca 712 pl_redirect('admin/reconcile/importlogs/step2');
f56ceafe
DB
713
714 } else {
715 // ask to choose a payment method
f5e965ca 716 $res = XDB::query('SELECT id, text FROM payment_methods');
f56ceafe
DB
717 $page->assign('methods', $res->fetchAllAssoc());
718 }
719
720 } elseif ( $step == 'step2' ) {
f5e965ca
SJ
721 $page->assign('title', 'Étape 2');
722
f56ceafe 723 // import logs formated in CVS
f5e965ca 724 $fields = array('date', 'reference', 'amount', 'commission');
f56ceafe 725 $importer = new PaymentLogsImporter();
77b81d91 726 $importer->apply($page, 'admin/reconcile/importlogs/step2', $fields);
f5e965ca 727
f56ceafe
DB
728 // if import is finished
729 $result = $importer->get_result();
730 if($result != null) {
731 $_SESSION['paymentrecon_data'] = $result;
f5e965ca 732 pl_redirect('admin/reconcile/importlogs/step3');
f56ceafe 733 }
f5e965ca 734
f56ceafe 735 } elseif ($step == 'step3' ) {
f5e965ca
SJ
736 $page->assign('title', 'Étape 3');
737
f56ceafe 738 // compute reconcilation summary data
f5e965ca 739 $res = XDB::query('SELECT MIN(date) AS period_start, MAX(date) AS period_end,
f56ceafe
DB
740 count(*) AS payment_count, SUM(amount) AS sum_amounts,
741 SUM(commission) AS sum_commissions
f5e965ca 742 FROM payment_tmp');
f56ceafe
DB
743 $recon = $res->fetchOneAssoc();
744 $recon['method_id'] = $_SESSION['paymentrecon_method'];
f5e965ca 745
f56ceafe
DB
746 // create reconciliation item in database
747 if(Post::has('next')) {
748 S::assert_xsrf_token();
f5e965ca 749
f56ceafe 750 // get parameters
f5e965ca
SJ
751 $recon['period_start'] = preg_replace('/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/', '\3-\2-\1', Post::v('period_start'));
752 $recon['period_end'] = preg_replace('/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/', '\3-\2-\1', Post::v('period_end'));
f56ceafe 753 // FIXME: save checks to be done at next step
f5e965ca 754
f56ceafe
DB
755 // Create reconcilation item in database
756 // FIXME: check if period doesn't overlap with others for the same method_id
f5e965ca 757 XDB::execute('INSERT INTO payment_reconcilations (method_id, period_start, period_end,
f56ceafe 758 payment_count, sum_amounts, sum_commissions)
f5e965ca 759 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
f56ceafe
DB
760 $recon['method_id'], $recon['period_start'], $recon['period_end'],
761 $recon['payment_count'], $recon['sum_amounts'], $recon['sum_commissions']);
762 $_SESSION['paymentrecon_id'] = XDB::insertId();
f5e965ca 763
f56ceafe
DB
764 // reconcile simple cases (trans.commission n'est modifié que s'il vaut NULL)
765 XDB::execute("UPDATE payment_transactions AS trans, payment_tmp AS tmp
f5e965ca
SJ
766 SET trans.recon_id = {?}, trans.commission=tmp.commission
767 WHERE trans.fullref = tmp.reference
768 AND trans.amount = tmp.amount AND DATE(trans.ts_confirmed) = tmp.date
769 AND (trans.commission IS NULL OR trans.commission = tmp.commission)
770 AND method_id = {?} AND recon_id IS NULL AND status = 'confirmed'",
f56ceafe 771 $_SESSION['paymentrecon_id'], $recon['method_id']);
f5e965ca
SJ
772
773 pl_redirect("admin/reconcile/importlogs/step4");
774
f56ceafe
DB
775 // show summary of the imported data + ask form start/end of reconcilation period
776 } else {
777 $recon['period_start'] = preg_replace('/([0-9]{4})-([0-9]{2})-([0-9]{2})/', '\3/\2/\1', $recon['period_start']);
778 $recon['period_end'] = preg_replace('/([0-9]{4})-([0-9]{2})-([0-9]{2})/', '\3/\2/\1', $recon['period_end']);
779 $page->assign('recon', $recon);
780 }
781
782 } elseif ($step == 'step4' ) {
f5e965ca
SJ
783 $page->assign('title', 'Étape 4');
784
f56ceafe 785 // get reconcilation summary informations
f5e965ca 786 $res = XDB::query('SELECT * FROM payment_reconcilations WHERE id = {?}', $_SESSION['paymentrecon_id']);
f56ceafe
DB
787 $recon = $res->fetchOneAssoc();
788 $page->assign('recon', $recon);
789
790 if (Post::has('force')) {
791 S::assert_xsrf_token();
792 foreach (Post::v('force') as $id => $value) {
f5e965ca
SJ
793 XDB::execute('UPDATE payment_transactions AS trans, payment_tmp AS tmp
794 SET trans.recon_id = {?}, trans.commission = tmp.commission
795 WHERE trans.id = {?} AND trans.fullref = tmp.reference',
f56ceafe
DB
796 $_SESSION['paymentrecon_id'], $id);
797 }
f5e965ca
SJ
798 $page->trigSuccess('La réconciliation a été forcée pour ' . count(Post::v('force')) . ' transaction(s).');
799
f56ceafe 800 } elseif (Post::has('next')) {
f5e965ca
SJ
801 if (strlen($recon['comments'])< 3 ) {
802 $page->trigError('Le commentaire doit contenir au moins 3 caractères.');
f56ceafe 803 } else {
f5e965ca 804 XDB::execute("UPDATE payment_reconcilations SET status = 'transfering' WHERE id = {?}", $_SESSION['paymentrecon_id']);
77b81d91 805 pl_redirect('admin/reconcile/step5');
f56ceafe 806 }
f5e965ca 807
f56ceafe
DB
808 } elseif (Post::has('savecomments')) {
809 S::assert_xsrf_token();
810 $recon['comments'] = Post::v('comments');
f3d6e2cc 811 $page->assign('recon', $recon);
f5e965ca 812 XDB::execute('UPDATE payment_reconcilations SET comments = {?} WHERE id = {?}', $recon['comments'], $_SESSION['paymentrecon_id']);
f56ceafe
DB
813 $page->trigSuccess('Les commentaires ont été enregistrés.');
814 }
f5e965ca 815
f56ceafe 816 // reconcilation results - ok
f5e965ca
SJ
817 $res = XDB::query('SELECT count(*), SUM(amount), SUM(commission)
818 FROM payment_transactions
819 WHERE recon_id = {?}',
f56ceafe 820 $recon['id']);
f5e965ca 821 list($ok_count, $ok_sum_amounts, $ok_sum_coms) = $res->fetchOneRow();
f56ceafe 822 $page->assign('ok_count', $ok_count);
f5e965ca 823
f56ceafe 824 // reconcilation results - ref exists, but some data differs
f5e965ca 825 $res = XDB::query('SELECT id, fullref, method_id, ts_confirmed, trans.amount, trans.commission, status, recon_id,
f56ceafe
DB
826 reference, date, tmp.amount as amount2, tmp.commission as commission2
827 FROM payment_transactions AS trans
f5e965ca
SJ
828 INNER JOIN payment_tmp AS tmp ON (trans.fullref = tmp.reference)
829 WHERE trans.recon_id IS NULL OR trans.recon_id != {?}',
f56ceafe
DB
830 $recon['id']);
831 $differs = $res->fetchAllAssoc();
832 $page->assign_by_ref('differs', $differs);
833 $page->assign('differ_count', count($differs));
f5e965ca 834
f56ceafe 835 // reconcilation results - ref doesn't exists in database
f5e965ca
SJ
836 $res = XDB::query('SELECT tmp.*
837 FROM payment_tmp AS tmp
838 LEFT JOIN payment_transactions AS trans ON (trans.fullref = tmp.reference)
839 WHERE trans.fullref IS NULL');
f56ceafe
DB
840 $only_import = $res->fetchAllAssoc();
841 $page->assign_by_ref('only_import', $only_import);
842 $page->assign('onlyim_count', count($only_import));
f5e965ca 843
f56ceafe 844 // reconcilation results - exists in database but not in import
f5e965ca 845 $res = XDB::query('SELECT trans.*
f56ceafe 846 FROM payment_transactions AS trans
f5e965ca
SJ
847 LEFT JOIN payment_tmp AS tmp ON (trans.fullref = tmp.reference)
848 WHERE {?} <= DATE(trans.ts_confirmed) AND DATE(trans.ts_confirmed) <= {?}
849 AND tmp.reference IS NULL AND method_id = {?}',
f56ceafe
DB
850 $recon['period_start'], $recon['period_end'], $recon['method_id']);
851 $only_database = $res->fetchAllAssoc();
852 $page->assign_by_ref('only_database', $only_database);
853 $page->assign('onlydb_count', count($only_database));
f56ceafe 854 }
f3d6e2cc 855 }
f5e965ca 856
26ba053e 857 function handler_adm_transfers($page, $action = null, $id = null) {
77b81d91 858 // list/log all bank transfers and link them to individual transactions
f5e965ca 859
f3d6e2cc
DB
860 if (Post::has('generate')) {
861 $recon_ids = array_keys(Post::v('recon_id'));
f5e965ca 862
f3d6e2cc
DB
863 // generate a new reconcilation group ID
864 $res = XDB::query("SELECT MAX(recongroup_id)+1 FROM payment_reconcilations");
865 $recongp_id = $res->fetchOneCell();
866 if ($recongp_id == null) $recongp_id = 1;
f5e965ca 867
f3d6e2cc
DB
868 // add reconcilations to group
869 // FIXME: should check if reconcilations are in good status
f5e965ca
SJ
870 XDB::execute("UPDATE payment_reconcilations
871 SET recongroup_id = {?}, status = 'closed'
872 WHERE id IN {?}",
873 $recongp_id, $recon_ids);
874
f3d6e2cc 875 // create transfers
f5e965ca 876 XDB::execute('INSERT INTO payment_transfers
f3d6e2cc
DB
877 SELECT NULL, {?}, t.ref, SUM(t.amount+t.commission), NULL, p.text, NULL
878 FROM payment_transactions AS t
f5e965ca
SJ
879 LEFT JOIN payments AS p ON (t.ref = p.id)
880 LEFT JOIN groups AS g ON (p.asso_id = g.id)
f3d6e2cc 881 WHERE t.recon_id IN {?}
f5e965ca
SJ
882 GROUP BY t.ref',
883 $recongp_id, $recon_ids);
884
f3d6e2cc
DB
885 //$res = XDB::query("SELECT * FROM payment_reconcilations WHERE id IN {?}", $recon_ids);
886 //$recons = $res->fetchAllAssoc();
f5e965ca
SJ
887
888 $page->trigSuccess('Les virements ont été générés pour ' . count($recon_ids) . ' réconciliations.');
f3d6e2cc 889 $this->handler_adm_reconcile($page);
f5e965ca
SJ
890
891 } elseif ($action == 'delgroup') {
f3d6e2cc 892 S::assert_xsrf_token();
f5e965ca
SJ
893 XDB::execute("UPDATE payment_reconcilations
894 SET status = 'transfering', recongroup_id = NULL
895 WHERE recongroup_id = {?}", $id);
896 XDB::execute("DELETE FROM payment_transfers
897 WHERE recongroup_id = {?} AND date IS NULL", $id);
898
f3d6e2cc
DB
899 $page->trigSuccess("Les virements non réalisés ont été supprimé du groupe ".$id.".");
900 $this->handler_adm_reconcile($page);
f5e965ca 901
f3d6e2cc
DB
902 } elseif ($action == "confirm") {
903 S::assert_xsrf_token();
f5e965ca
SJ
904 XDB::execute('UPDATE payment_transfers
905 SET date = NOW()
906 WHERE id = {?}', $id);
907
908 $page->trigSuccess('Virement ' . $id . ' confirmé.');
f3d6e2cc 909 $this->handler_adm_reconcile($page);
f5e965ca 910
f3d6e2cc 911 } else {
f5e965ca 912 pl_redirect('admin/reconcile');
f3d6e2cc 913 }
f56ceafe
DB
914 }
915}
916
917class PaymentLogsImporter extends CSVImporter {
f3d6e2cc 918 protected $result;
f5e965ca 919
f3d6e2cc
DB
920 public function __construct() {
921 parent::__construct('');
f5e965ca
SJ
922 $this->registerFunction('systempay_commission', 'Compute BPLC commission', array($this, 'compute_systempay_commission'));
923 $this->registerFunction('payment_id', 'Autocompute payment ID', array($this, 'compute_payment_id'));
f56ceafe 924 //$this->forceValue('payment_id','func_payment_id');
f3d6e2cc 925 }
f5e965ca 926
f3d6e2cc
DB
927 public function run($action = null, $insert_relation = null, $update_relation = null) {
928 $this->result = array();
929 foreach ($this->data as $line) {
f56ceafe 930 $a = $this->makeAssoc($line, $insert_relation);
1fe903b1 931 // convert date
f5e965ca 932 $a['date'] = preg_replace('/([0-9]{2})\/([0-9]{2})\/([0-9]{4}).*/', '\3-\2-\1', $a['date']);
1fe903b1
DB
933 $a['date'] = preg_replace('/T.*/','', $a['date']);
934
935 // convert money
f5e965ca
SJ
936 $a['amount'] = str_replace(',', '.', $a['amount']);
937 $a['commission'] = str_replace(',', '.', $a['commission']);
f3d6e2cc 938 $this->result[] = $a;
f56ceafe 939 }
f3d6e2cc 940 }
f5e965ca 941
f3d6e2cc
DB
942 public function get_result() {
943 return $this->result;
944 }
f5e965ca 945
f3d6e2cc 946 static public function compute_systempay_commission($line, $key, $relation) {
f5e965ca
SJ
947 static $EEE_countries = array(
948 'France', 'Allemagne', 'Autriche', 'Belgique', 'Bulgarie', 'Chypre',
949 'Danemark', 'Espagne', 'Estonie', 'Finlande', 'Grèce', 'Hongrie', 'Irlande', 'Islande', 'Italie',
950 'Lettonie', 'Liechtenstein', 'Lituanie', 'Luxembourg', 'Malte', 'Norvège', 'Pays-Bas', 'Pologne',
951 'Portugal', 'Roumanie', 'Royaume-Uni', 'Slovaquie', 'Slovénie', 'Suède', 'République Tchèque'
952 );
953
954 if($key!='commission' || !array_key_exists('carte', $line)) {
955 return null;
956 }
f3d6e2cc 957 $amount = self::getValue($line, 'amount', $relation['amount']);
f5e965ca
SJ
958 if (in_array($line['pays carte'], $EEE_countries)) {
959 return -0.20 - round($amount * 0.005, 2);
960 } else {
961 return -0.20 - round($amount * 0.005, 2) - 0.76;
962 }
f3d6e2cc
DB
963 }
964
965 static public function compute_payment_id($line, $key, $relation) {
f5e965ca
SJ
966 if ($key != 'payment_id') {
967 return null;
968 }
f3d6e2cc 969 $reference = self::getValue($line, 'reference', $relation['reference']);
f5e965ca 970 if (ereg('-([0-9]+)$', $reference, $matches)) {
f3d6e2cc 971 return $matches[1];
f5e965ca 972 } else {
f56ceafe 973 return null;
f5e965ca 974 }
f3d6e2cc 975 }
a2558f2b 976}
977
a7de4ef7 978// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
a2558f2b 979?>