2 /***************************************************************************
3 * Copyright (C) 2003-2011 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
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. *
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. *
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 *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
22 /* sort en affichant une erreur */
23 function cb_erreur($text) {
26 $mymail = new PlMailer();
27 $mymail->addTo($globals->money
->email
);
28 $mymail->setFrom("webmaster@" . $globals->mail
->domain
);
29 $mymail->setSubject("erreur lors d'un télépaiement (CyberPaiement)");
30 $mymail->setTxtBody("\n\n".var_export($_REQUEST,true
));
32 echo "Notification sent.\n";
36 /* sort en affichant une erreur */
37 function paypal_erreur($text, $send=true
)
39 global $erreur, $globals;
44 $mymail = new PlMailer();
45 $mymail->addTo($globals->money
->email
);
46 $mymail->setFrom("webmaster@" . $globals->mail
->domain
);
47 $mymail->setSubject("erreur lors d'un télépaiement (PayPal)");
48 $mymail->setTxtBody("\n\n".var_export($_REQUEST,true
));
51 Platal
::page()->trigError($text);
54 /* http://fr.wikipedia.org/wiki/Formule_de_Luhn */
55 function luhn($nombre) {
58 for ($i = 0; $i < strlen($s); ++
$i) {
60 $sum +
= ($i %
2) ?
(2 * $dgt) %
9 : $dgt;
65 /* calcule la clé d'acceptation a partir de 5 champs */
66 function cle_accept($d1, $d2, $d3, $d4, $d5)
68 $m1 = luhn($d1 . $d5);
69 $m2 = luhn($d2 . $d5);
70 $m3 = luhn($d3 . $d5);
71 $m4 = luhn($d4 . $d5);
72 $n = $m1 +
$m2 +
$m3 +
$m4;
73 $alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
74 return $alpha{$n-1} . $m1 . $m2 . $m3 . $m4;
77 /* decode the comment */
78 function comment_decode($comment) {
79 $comment = urldecode($comment);
80 if (is_utf8($comment)) {
83 return utf8_encode($comment);
87 /* check if a RIB account number is valid */
88 function check_rib($rib)
90 if(strlen($rib) != 23) return false
;
93 $rib = strtr(strtoupper($rib),'ABCDEFGHIJKLMNOPQRSTUVWXYZ','12345678912345678923456789');
94 $bank = substr($rib,0,5);
95 $counter = substr($rib,5,5);
96 $account = substr($rib,10,11);
97 $key = substr($rib,21,2);
100 return (0 == fmod(89 * $bank +
15 * $counter +
3 * $account +
$key, 97));
103 class PaymentModule
extends PLModule
108 'payment' => $this->make_hook('payment', AUTH_MDP
, 'payment'),
109 'payment/cyber_return' => $this->make_hook('cyber_return', AUTH_PUBLIC
, 'user', NO_HTTPS
),
110 'payment/cyber2_return' => $this->make_hook('cyber2_return', AUTH_PUBLIC
, 'user', NO_HTTPS
),
111 'payment/paypal_return' => $this->make_hook('paypal_return', AUTH_PUBLIC
, 'user', NO_HTTPS
),
112 '%grp/paiement' => $this->make_hook('xnet_payment', AUTH_MDP
),
113 '%grp/payment' => $this->make_hook('xnet_payment', AUTH_MDP
),
114 '%grp/payment/cyber_return' => $this->make_hook('cyber_return', AUTH_PUBLIC
, 'user', NO_HTTPS
),
115 '%grp/payment/cyber2_return' => $this->make_hook('cyber2_return', AUTH_PUBLIC
, 'user', NO_HTTPS
),
116 '%grp/payment/paypal_return' => $this->make_hook('paypal_return', AUTH_PUBLIC
, 'user', NO_HTTPS
),
117 'admin/payments' => $this->make_hook('admin', AUTH_MDP
, 'admin'),
118 'admin/payments/methods' => $this->make_hook('adm_methods', AUTH_MDP
, 'admin'),
119 'admin/payments/transactions' => $this->make_hook('adm_transactions', AUTH_MDP
, 'admin'),
120 'admin/reconcile' => $this->make_hook('adm_reconcile', AUTH_MDP
, 'admin'),
121 'admin/reconcile/importlogs' => $this->make_hook('adm_importlogs', AUTH_MDP
, 'admin'),
122 'admin/reconcile/transfers' => $this->make_hook('adm_transfers', AUTH_MDP
, 'admin'),
123 'admin/reconcile/bankaccounts' => $this->make_hook('adm_bankaccounts', AUTH_MDP
, 'admin'),
127 function handler_payment($page, $ref = -1)
131 $this->load('money.inc.php');
133 if (!empty($GLOBALS['IS_XNET_SITE'])) {
134 if (!$globals->asso('id')) {
137 $res = XDB
::query('SELECT asso_id
139 WHERE asso_id = {?} AND id = {?}',
140 $globals->asso('id'), $ref);
141 if (!$res->numRows()) {
145 $page->changeTpl('payment/index.tpl');
146 $page->setTitle('Télépaiements');
149 $op = Env
::v('op', 'select');
150 $meth = new PayMethod(Env
::i('methode', -1));
151 $pay = new Payment($ref);
153 if($pay->flags
->hasflag('old')){
154 $page->trigError("La transaction selectionnée est périmée.");
155 $pay = new Payment();
157 $val = Env
::v('montant') != 0 ? Env
::v('montant') : $pay->amount_def
;
159 if (($e = $pay->check($val)) !== true
) {
160 $page->trigError($e);
163 if ($op == 'submit') {
164 $pay->init($val, $meth);
165 $pay->prepareform($pay);
167 $res = XDB
::iterator('SELECT timestamp, amount
168 FROM payment_transactions
169 WHERE uid = {?} AND ref = {?}
170 ORDER BY timestamp DESC',
171 S
::v('uid', -1), $ref);
174 $page->assign('transactions', $res);
178 $val = floor($val) . '.' . substr(floor(($val - floor($val)) * 100 +
100), 1);
179 $page->assign('montant', $val);
180 $page->assign('comment', Env
::v('comment'));
182 $page->assign('meth', $meth);
183 $page->assign('pay', $pay);
184 $page->assign('evtlink', $pay->event());
185 $page->assign('sex', S
::user()->isFemale());
188 function handler_cyber_return($page, $uid = null
)
190 /* reference banque (numero de transaction) */
191 $champ901 = Env
::s('CHAMP901');
192 /* cle d'acceptation */
193 $champ905 = Env
::s('CHAMP905');
195 $champ906 = Env
::s('CHAMP906');
196 /* email renvoye par la banque */
197 $champ104 = Env
::s('CHAMP104');
198 /* reference complete de la commande */
199 $champ200 = Env
::s('CHAMP200');
200 /* montant de la transaction */
201 $champ201 = Env
::s('CHAMP201');
203 $champ202 = Env
::s('CHAMP202');
204 $montant = "$champ201 $champ202";
206 /* on extrait les informations sur l'utilisateur */
207 $user = User
::get($uid);
209 cb_erreur("uid invalide");
213 /* on extrait la reference de la commande */
214 if (!ereg('-xorg-([0-9]+)$', $champ200, $matches)) {
215 cb_erreur("référence de commande invalide");
218 echo ($ref = $matches[1]);
219 $res = XDB
::query('SELECT mail, text, confirmation
221 WHERE id = {?}', $ref);
222 if (!list($conf_mail, $conf_title, $conf_text) = $res->fetchOneRow()) {
223 cb_erreur("référence de commande inconnue");
226 /* on extrait le code de retour */
227 if ($champ906 != "0000") {
228 $res = XDB
::query('SELECT rcb.text, c.id, c.text
229 FROM payment_codeRCB AS rcb
230 LEFT JOIN payment_codeC AS c ON (rcb.codeC = c.id)
231 WHERE rcb.id = {?}', $champ906);
232 if (list($rcb_text, $c_id, $c_text) = $res->fetchOneRow()) {
233 cb_erreur("erreur lors du paiement : $c_text ($c_id)");
235 cb_erreur("erreur inconnue lors du paiement");
239 /* on fait l'insertion en base de donnees */
240 XDB
::execute('INSERT INTO payment_transactions (id, uid, ref, fullref, amount, pkey, comment)
241 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})',
242 $champ901, $user->id(), $ref, $champ200, $montant, $champ905, Env
::v('comment'));
244 // We check if it is an Xnet payment and then update the related ML.
245 $res = XDB
::query('SELECT eid
247 WHERE paiement_id = {?}', $ref);
248 if ($eid = $res->fetchOneCell()) {
249 require_once dirname(__FILE__
) . '/xnetevents/xnetevents.inc.php';
250 $evt = get_event_detail($eid);
251 subscribe_lists_event($uid, $evt, 1, $montant, true
);
254 /* on genere le mail de confirmation */
255 $conf_text = str_replace(
256 array('<prenom>', '<nom>', '<promo>', '<montant>', '<salutation>', '<cher>', '<comment>'),
257 array($user->firstName(), $user->lastName(), $user->promo(), $montant,
258 $user->isFemale() ?
'Chère' : 'Cher', $user->isFemale() ?
'Chère' : 'Cher',
259 Env
::v('comment')), $conf_text);
262 $mymail = new PlMailer();
263 $mymail->setFrom($conf_mail);
264 $mymail->addCc($conf_mail);
265 $mymail->setSubject($conf_title);
266 $mymail->setWikiBody($conf_text);
267 $mymail->sendTo($user);
269 /* on envoie les details de la transaction à telepaiement@ */
270 $mymail = new PlMailer();
271 $mymail->setFrom("webmaster@" . $globals->mail
->domain
);
272 $mymail->addTo($globals->money
->email
);
273 $mymail->setSubject($conf_title);
274 $msg = 'utilisateur : ' . $user->login() . ' (' . $user->id() . ')' . "\n" .
275 'mail : ' . $user->forlifeEmail() . "\n\n" .
276 "paiement : $conf_title ($conf_mail)\n".
277 "reference : $champ200\n".
278 "montant : $montant\n\n".
279 "dump de REQUEST:\n".
280 var_export($_REQUEST,true
);
281 $mymail->setTxtBody($msg);
286 function handler_cyber2_return($page, $uid = null
)
288 global $globals, $platal;
290 /* on vérifie la signature */
291 $vads_params = array();
292 foreach($_REQUEST as $key => $value)
293 if(substr($key,0,5) == 'vads_') {
294 $vads_params[$key] = $value;
297 $signature = sha1(join('+', $vads_params) . '+' . $globals->money
->cyperplus_key
);
298 //if($signature != Env::v('signature')) {
299 // cb_erreur("signature invalide");
302 /* on extrait les informations sur l'utilisateur */
303 $user = User
::get(Env
::i('vads_cust_id'));
305 cb_erreur("uid invalide");
308 /* on extrait la reference de la commande */
309 if (!ereg('-([0-9]+)$', Env
::v('vads_order_id'), $matches)) {
310 cb_erreur("référence de commande invalide");
314 $res = XDB
::query('SELECT mail, text, confirmation
316 WHERE id={?}', $ref);
317 if ($res->numRows() != 1) {
318 cb_erreur("référence de commande inconnue");
320 list($conf_mail, $conf_title, $conf_text) = $res->fetchOneRow();
322 /* on extrait le montant */
323 if (Env
::v('vads_currency') != '978') {
324 cb_erreur("monnaie autre que l'euro");
326 $amount = ((float)Env
::i('vads_amount')) / 100;
327 $montant = sprintf("%.02f EUR", $amount);
329 /* on extrait le code de retour */
330 if (Env
::v('vads_result') != '00') {
331 cb_erreur('erreur lors du paiement : ?? (' . Env
::v('vads_result') . ')');
334 /* on fait l'insertion en base de donnees */
335 XDB
::execute('INSERT INTO payment_transactions (id, uid, ref, fullref, amount, pkey, comment)
336 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})',
337 Env
::v('vads_trans_date'), $user->id(), $ref, Env
::v('vads_order_id'), $montant, '', Env
::v('vads_order_info'));
338 echo "Paiement stored.\n";
340 // We check if it is an Xnet payment and then update the related ML.
341 $res = XDB
::query('SELECT eid, asso_id
343 WHERE paiement_id = {?}', $ref);
344 if ($res->numRows() == 1) {
345 list($eid, $asso_id) = $res->fetchOneRow();
346 require_once dirname(__FILE__
) . '/xnetevents/xnetevents.inc.php';
347 $evt = get_event_detail($eid, false
, $asso_id);
348 subscribe_lists_event($user->id(), $evt, 1, $amount, true
);
351 /* on genere le mail de confirmation */
352 $conf_text = str_replace(
353 array('<prenom>', '<nom>', '<promo>', '<montant>', '<salutation>', '<cher>', '<comment>'),
354 array($user->firstName(), $user->lastName(), $user->promo(), $montant,
355 $user->isFemale() ?
'Chère' : 'Cher', $user->isFemale() ?
'Chère' : 'Cher',
356 Env
::v('comment')), $conf_text);
359 $mymail = new PlMailer();
360 $mymail->setFrom($conf_mail);
361 $mymail->addCc($conf_mail);
362 $mymail->setSubject($conf_title);
363 $mymail->setWikiBody($conf_text);
364 $mymail->sendTo($user);
366 /* on envoie les details de la transaction à telepaiement@ */
367 $mymail = new PlMailer();
368 $mymail->setFrom("webmaster@" . $globals->mail
->domain
);
369 $mymail->addTo($globals->money
->email
);
370 $mymail->setSubject($conf_title);
371 $msg = 'utilisateur : ' . $user->login() . ' (' . $user->id() . ')' . "\n" .
372 'mail : ' . $user->forlifeEmail() . "\n\n" .
373 "paiement : $conf_title ($conf_mail)\n".
374 "reference : " . Env
::v('vads_order_id') . "\n".
375 "montant : $montant\n\n".
376 "dump de REQUEST:\n".
377 var_export($_REQUEST,true
);
378 $mymail->setTxtBody($msg);
380 echo "Notifications sent.\n";
384 function handler_paypal_return($page, $uid = null
)
386 $page->changeTpl('payment/retour_paypal.tpl');
388 /* reference banque (numero de transaction) */
389 $no_transaction = Env
::s('tx');
390 /* token a renvoyer pour avoir plus d'information */
391 $clef = Env
::s('sig');
393 $status = Env
::s('st');
395 $reason = ($status == 'Pending') ? Env
::s('pending_reason') : Env
::s('reason_code');
396 /* reference complete de la commande */
397 $fullref = Env
::s('cm');
398 /* montant de la transaction */
399 $montant_nb = Env
::s('amt');
401 $montant_dev = Env
::s('cc');
402 $montant = "$montant_nb $montant_dev";
404 /* on extrait le code de retour */
405 if ($status != "Completed") {
407 paypal_erreur("erreur lors du paiement : $status - $reason");
409 paypal_erreur("Paiement annulé", false
);
413 /* on extrait les informations sur l'utilisateur */
414 $user = User
::get($uid);
416 paypal_erreur("uid invalide");
419 /* on extrait la reference de la commande */
420 if (!ereg('-xorg-([0-9]+)$', $fullref, $matches)) {
421 paypal_erreur("référence de commande invalide");
425 $res = XDB
::query('SELECT mail, text, confirmation
427 WHERE id = {?}', $ref);
428 if (!list($conf_mail, $conf_title, $conf_text) = $res->fetchOneRow()) {
429 paypal_erreur('référence de commande inconnue');
432 /* on fait l'insertion en base de donnees */
433 XDB
::execute("INSERT INTO payment_transactions (id, uid, ref, fullref, amount, pkey, comment)
434 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})",
435 $no_transaction, $user->id(), $ref, $fullref, $montant, $clef, Env
::v('comment'));
437 // We check if it is an Xnet payment and then update the related ML.
438 $res = XDB
::query('SELECT eid
440 WHERE paiement_id = {?}', $ref);
441 if ($eid = $res->fetchOneCell()) {
442 require_once dirname(__FILE__
) . '/xnetevents/xnetevents.inc.php';
443 $evt = get_event_detail($eid);
444 subscribe_lists_event($user->id(), $evt, 1, $montant, true
);
447 /* on genere le mail de confirmation */
448 $conf_text = str_replace(array('<prenom>', '<nom>', '<promo>', '<montant>', '<salutation>', '<cher>'),
449 array($user->firstName(), $user->lastName(), $user->promo(), $montant,
450 $user->isFemale() ?
'Chère' : 'Cher',
451 $user->isFemale() ?
'Chère' : 'Cher'), $conf_text);
454 $mymail = new PlMailer();
455 $mymail->setFrom($conf_mail);
456 $mymail->addCc($conf_mail);
457 $mymail->setSubject($conf_title);
458 $mymail->setWikiBody($conf_text);
459 $mymail->sendTo($user);
461 /* on envoie les details de la transaction à telepaiement@ */
462 $mymail = new PlMailer();
463 $mymail->setFrom("webmaster@" . $globals->mail
->domain
);
464 $mymail->addTo($globals->money
->email
);
465 $mymail->setSubject($conf_title);
466 $msg = 'utilisateur : ' . $user->login() . ' (' . $user->id() . ')' . "\n" .
467 'mail : ' . $user->forlifeEmail() . "\n\n" .
468 "paiement : $conf_title ($conf_mail)\n".
469 "reference : $champ200\n".
470 "montant : $montant\n\n".
471 "dump de REQUEST:\n".
472 var_export($_REQUEST,true
);
473 $mymail->setTxtBody($msg);
476 $page->assign('texte', $conf_text);
477 $page->assign('erreur', $erreur);
480 function handler_xnet_payment($page, $pid = null
)
484 $perms = S
::v('perms');
485 if (!$perms->hasFlag('groupmember')) {
489 $res = XDB
::query("SELECT 1
490 FROM group_events AS e
491 INNER JOIN group_event_participants AS ep ON (ep.eid = e.eid AND e.uid = {?})
492 WHERE e.paiement_id = {?} AND e.asso_id = {?}",
493 S
::i('uid'), $pid, $globals->asso('id'));
494 if ($res->numRows() == 0) {
499 if (!is_null($pid)) {
500 return $this->handler_payment($page, $pid);
502 $page->changeTpl('payment/xnet.tpl');
505 "SELECT id, text, url
507 WHERE asso_id = {?} AND NOT FIND_IN_SET('old', flags)
508 ORDER BY id DESC", $globals->asso('id'));
509 $tit = $res->fetchAllAssoc();
510 $page->assign('titles', $tit);
515 static $orders = array('timestamp' => 'p', 'directory_name' => 'a', 'promo' => 'pd', 'comment' => 'p', 'amount' => 'p');
517 if (Get
::has('order_id') && Get
::has('order') && array_key_exists(Get
::v('order'), $orders)) {
518 $order_id = Get
::i('order_id');
519 $order = Get
::v('order');
520 $ordering = ' ORDER BY ' . $orders[$order] . '.' . $order;
521 if (Get
::has('order_inv') && Get
::i('order_inv') == 1) {
522 $ordering .= ' DESC';
523 $page->assign('order_inv', 0);
525 $page->assign('order_inv', 1);
527 $page->assign('order_id', $order_id);
528 $page->assign('order', $order);
529 $page->assign('anchor', 'legend_' . $order_id);
533 $page->assign('order', false
);
537 $page->assign('order', false
);
539 foreach($tit as $foo) {
542 $res = XDB
::query('SELECT p.uid, IF(p.timestamp = \'0000-00-00\', 0, p.timestamp) AS date, p.comment, p.amount
543 FROM payment_transactions AS p
544 INNER JOIN accounts AS a ON (a.uid = p.uid)
545 LEFT JOIN account_profiles AS ap ON (ap.uid = p.uid AND FIND_IN_SET(\'owner\', ap.perms))
546 LEFT JOIN profile_display AS pd ON (ap.pid = pd.pid)
547 WHERE p.ref = {?}' . (($order_id == $pid) ?
$ordering : ''),
549 $trans[$pid] = User
::getBulkUsersWithUIDs($res->fetchAllAssoc(), 'uid', 'user');
551 foreach ($trans[$pid] as $i => $t) {
552 $sum +
= strtr(substr($t['amount'], 0, strpos($t['amount'], 'EUR')), ',', '.');
553 $trans[$pid][$i]['amount'] = str_replace('EUR', '€', $t['amount']);
555 $trans[$pid][] = array('limit' => true
,
556 'amount' => strtr($sum, '.', ',') . ' €');
558 $res = XDB
::iterRow("SELECT e.eid, e.short_name, e.intitule, ep.nb, ei.montant, ep.paid
559 FROM group_events AS e
560 LEFT JOIN group_event_participants AS ep ON (ep.eid = e.eid AND ep.uid = {?})
561 INNER JOIN group_event_items AS ei ON (ep.eid = ei.eid AND ep.item_id = ei.item_id)
562 WHERE e.paiement_id = {?}",
564 $event[$pid] = array();
565 $event[$pid]['paid'] = 0;
567 $event[$pid]['topay'] = 0;
568 while(list($eid, $shortname, $title, $nb, $montant, $paid) = $res->next()) {
569 $event[$pid]['topay'] +
= ($nb * $montant);
570 $event[$pid]['eid'] = $eid;
571 $event[$pid]['shortname'] = $shortname;
572 $event[$pid]['title'] = $title;
573 $event[$pid]['ins'] = !is_null($nb);
574 $event[$pid]['paid'] = $paid;
577 $res = XDB
::query('SELECT amount
578 FROM payment_transactions
579 WHERE id = {?} AND uid = {?}', $pid, S
::v('uid'));
580 $montants = $res->fetchColumn();
582 foreach ($montants as $m) {
583 $p = strtr(substr($m, 0, strpos($m, 'EUR')), ',', '.');
584 $event[$pid]['paid'] +
= trim($p);
587 $page->register_modifier('decode_comment', 'decode_comment');
588 $page->assign('trans', $trans);
589 $page->assign('event', $event);
592 function handler_admin($page, $action = 'list', $id = null
) {
593 $page->setTitle('Administration - Paiements');
594 $page->assign('title', 'Gestion des télépaiements');
595 $table_editor = new PLTableEditor('admin/payments','payments','id');
596 //$table_editor->add_join_table('payment_transactions','ref',true); => on ne supprime jamais une transaction
597 $table_editor->add_sort_field('flags');
598 $table_editor->add_sort_field('id', true
, true
);
599 $table_editor->on_delete("UPDATE payments SET flags = 'old' WHERE id = {?}", "Le paiement a été archivé");
600 $table_editor->describe('text', 'intitulé', true
);
601 $table_editor->describe('url', 'site web', false
);
602 $table_editor->describe('amount_def', 'montant par défaut', false
);
603 $table_editor->describe('amount_min', 'montant minimum', false
);
604 $table_editor->describe('amount_max', 'montant maximum', false
);
605 $table_editor->describe('mail', 'email contact', true
);
606 $table_editor->describe('confirmation', 'message confirmation', false
);
608 // adds a column with the start date of the linked event if there is one
609 $table_editor->add_option_table('group_events', 'group_events.paiement_id = t.id');
610 $table_editor->add_option_field('group_events.debut', 'related_event', 'évènement', 'timestamp');
612 $table_editor->apply($page, $action, $id);
615 function handler_adm_transactions($page, $payment_id = null
, $action = "list", $id = null
) {
616 // show transactions. FIXME: should not be modifiable
617 $page->setTitle('Administration - Paiements - Transactions');
618 $page->assign('title', "Liste des transactions pour le paiement {$payment_id}");
620 if ($payment_id == null
)
621 $page->trigError("Aucun ID de paiement fourni.");
623 $table_editor = new PLTableEditor("admin/transactions/{$payment_id}",'payment_transactions','id');
624 $table_editor->set_where_clause(XDB
::format('ref = {?}', $payment_id));
625 $table_editor->apply($page, 'list', $id); // only the 'list' action is allowed
626 $page->assign('readonly', 'readonly'); // don't show modification features
629 function handler_adm_bankaccounts($page, $action = "list", $id = null
) {
630 // managment of bank account used for money transfert
631 $page->setTitle('Administration - Paiements - RIBs');
632 $page->assign('title', "Liste des RIBs");
634 $table_editor = new PLTableEditor('admin/payments/bankaccounts', 'payment_bankaccounts', 'id');
635 $table_editor->describe('asso_id', 'ID du groupe', false
);
636 $table_editor->describe('owner', 'titulaire', true
);
637 $table_editor->add_option_table('groups', 'groups.id = t.asso_id');
638 $table_editor->add_option_field('groups.diminutif', 'group_name', 'groupe', 'varchar','account');
641 if ($action == 'update' && Post
::has('account') && !check_rib(Post
::v('account'))) {
642 $page->trigError("Le RIB n'est pas valide");
643 $table_editor->apply($page, 'edit', $id);
647 $table_editor->apply($page, $action, $id);
650 function handler_adm_methods($page, $action = "list", $id = null
) {
651 // show and edit payment methods
652 $page->setTitle('Administration - Paiements - Méthodes');
653 $page->assign('title', 'Méthodes de paiement');
654 $table_editor = new PLTableEditor('admin/payments/methods', 'payment_methods', 'id');
655 $table_editor->apply($page, $action, $id);
658 function handler_adm_reconcile($page, $step = 'list', $param = null
) {
659 // reconciles logs with transactions
660 // FIXME: the admin is considered to be fair => he doesn't hack the $step value, nor other params
661 $page->setTitle('Administration - Paiements - Réconciliations');
662 $page->changeTpl('payment/reconcile.tpl');
663 $page->assign('step', $step);
667 if ($step == 'delete' && $param != null
) {
668 S
::assert_xsrf_token();
669 XDB
::execute('DELETE FROM payment_reconcilations WHERE id = {?}', $param);
670 // FIXME: hardcoding !!!
671 XDB
::execute('UPDATE payment_transactions SET recon_id = NULL,commission = NULL WHERE recon_id = {?} AND method_id = 2', $param);
672 XDB
::execute('UPDATE payment_transactions SET recon_id = NULL WHERE recon_id = {?} AND method_id = 1', $param);
673 $page->trigSuccess("L'entrée " . $param . ' a été supprimée.');
675 } elseif ($step == 'edit') {
676 $page->trigError("L'édition n'est pas implémentée.");
678 } elseif ($step == 'step5') {
679 $page->trigSuccess("La réconciliation est terminée. Il est maintenant nécessaire de générer les virements.");
684 // show list of reconciliations, with a "add" button
685 $page->assign('title', 'Réconciliation - Liste');
686 $page->assign('step', 'list');
690 $res = XDB
::query("SELECT r.id, short_name AS method, period_start, period_end, status,
691 payment_count, sum_amounts, sum_commissions
692 FROM payment_reconcilations AS r
693 LEFT JOIN payment_methods AS m ON (r.method_id = m.id)
694 WHERE recongroup_id IS NULL
695 ORDER BY period_end DESC, period_start DESC");
696 foreach ($res->fetchAllAssoc() as $recon)
697 $recongps[] = array('recons' => array($recon), 'transfers' => array());
699 $res = XDB
::query("SELECT recongroup_id AS id
700 FROM payment_reconcilations
701 GROUP BY recongroup_id
702 ORDER BY MAX(period_end) DESC, MIN(period_start) DESC");
703 foreach ($res->fetchAllAssoc() as $recongp) {
704 $res = XDB
::query("SELECT r.id, short_name AS method, period_start, period_end, status,
705 payment_count, sum_amounts, sum_commissions
706 FROM payment_reconcilations AS r
707 LEFT JOIN payment_methods AS m ON (r.method_id = m.id)
708 WHERE recongroup_id = {?}
709 ORDER BY period_end DESC, period_start DESC",
711 $recongp['recons'] = $res->fetchAllAssoc();
713 $res = XDB
::query('SELECT id, payment_id, amount, account_id, message, date
714 FROM payment_transfers
715 WHERE recongroup_id = {?}',
717 $recongp['transfers'] = $res->fetchAllAssoc();
719 $recongps[] = $recongp;
721 $page->assign_by_ref('recongps', $recongps);
725 function handler_adm_importlogs($page, $step, $param = null
) {
726 $page->setTitle('Administration - Paiements - Réconciliations');
727 $page->changeTpl('payment/reconcile.tpl');
728 $page->assign('step', $step);
730 if (isset($_SESSION['paymentrecon_data'])) {
731 // create temporary table with imported data
732 XDB
::execute('CREATE TEMPORARY TABLE payment_tmp (
733 reference VARCHAR(255) PRIMARY KEY,
736 commission DECIMAL(9,2)
738 foreach ($_SESSION['paymentrecon_data'] as $i)
739 XDB
::execute('INSERT INTO payment_tmp VALUES ({?}, {?}, {?}, {?})',
740 $i['reference'], $i['date'], $i['amount'], $i['commission']);
743 if ($step == 'step1') {
744 $page->assign('title', 'Étape 1');
745 unset($_SESSION['paymentrecon_method']);
746 unset($_SESSION['paymentrecon_data']);
747 unset($_SESSION['paymentrecon_id']);
749 // was a payment method choosen ?
750 if ($param != null
) {
751 $_SESSION['paymentrecon_method'] = (int)$param;
752 pl_redirect('admin/reconcile/importlogs/step2');
755 // ask to choose a payment method
756 $res = XDB
::query('SELECT id, text FROM payment_methods');
757 $page->assign('methods', $res->fetchAllAssoc());
760 } elseif ( $step == 'step2' ) {
761 $page->assign('title', 'Étape 2');
763 // import logs formated in CVS
764 $fields = array('date', 'reference', 'amount', 'commission');
765 $importer = new PaymentLogsImporter();
766 $importer->apply($page, 'admin/reconcile/importlogs/step2', $fields);
768 // if import is finished
769 $result = $importer->get_result();
770 if($result != null
) {
771 $_SESSION['paymentrecon_data'] = $result;
772 pl_redirect('admin/reconcile/importlogs/step3');
775 } elseif ($step == 'step3' ) {
776 $page->assign('title', 'Étape 3');
778 // compute reconcilation summary data
779 $res = XDB
::query('SELECT MIN(date) AS period_start, MAX(date) AS period_end,
780 count(*) AS payment_count, SUM(amount) AS sum_amounts,
781 SUM(commission) AS sum_commissions
783 $recon = $res->fetchOneAssoc();
784 $recon['method_id'] = $_SESSION['paymentrecon_method'];
786 // create reconciliation item in database
787 if(Post
::has('next')) {
788 S
::assert_xsrf_token();
791 $recon['period_start'] = preg_replace('/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/', '\3-\2-\1', Post
::v('period_start'));
792 $recon['period_end'] = preg_replace('/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/', '\3-\2-\1', Post
::v('period_end'));
793 // FIXME: save checks to be done at next step
795 // Create reconcilation item in database
796 // FIXME: check if period doesn't overlap with others for the same method_id
797 XDB
::execute('INSERT INTO payment_reconcilations (method_id, period_start, period_end,
798 payment_count, sum_amounts, sum_commissions)
799 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
800 $recon['method_id'], $recon['period_start'], $recon['period_end'],
801 $recon['payment_count'], $recon['sum_amounts'], $recon['sum_commissions']);
802 $_SESSION['paymentrecon_id'] = XDB
::insertId();
804 // reconcile simple cases (trans.commission n'est modifié que s'il vaut NULL)
805 XDB
::execute("UPDATE payment_transactions AS trans, payment_tmp AS tmp
806 SET trans.recon_id = {?}, trans.commission=tmp.commission
807 WHERE trans.fullref = tmp.reference
808 AND trans.amount = tmp.amount AND DATE(trans.ts_confirmed) = tmp.date
809 AND (trans.commission IS NULL OR trans.commission = tmp.commission)
810 AND method_id = {?} AND recon_id IS NULL AND status = 'confirmed'",
811 $_SESSION['paymentrecon_id'], $recon['method_id']);
813 pl_redirect("admin/reconcile/importlogs/step4");
815 // show summary of the imported data + ask form start/end of reconcilation period
817 $recon['period_start'] = preg_replace('/([0-9]{4})-([0-9]{2})-([0-9]{2})/', '\3/\2/\1', $recon['period_start']);
818 $recon['period_end'] = preg_replace('/([0-9]{4})-([0-9]{2})-([0-9]{2})/', '\3/\2/\1', $recon['period_end']);
819 $page->assign('recon', $recon);
822 } elseif ($step == 'step4' ) {
823 $page->assign('title', 'Étape 4');
825 // get reconcilation summary informations
826 $res = XDB
::query('SELECT * FROM payment_reconcilations WHERE id = {?}', $_SESSION['paymentrecon_id']);
827 $recon = $res->fetchOneAssoc();
828 $page->assign('recon', $recon);
830 if (Post
::has('force')) {
831 S
::assert_xsrf_token();
832 foreach (Post
::v('force') as $id => $value) {
833 XDB
::execute('UPDATE payment_transactions AS trans, payment_tmp AS tmp
834 SET trans.recon_id = {?}, trans.commission = tmp.commission
835 WHERE trans.id = {?} AND trans.fullref = tmp.reference',
836 $_SESSION['paymentrecon_id'], $id);
838 $page->trigSuccess('La réconciliation a été forcée pour ' . count(Post
::v('force')) . ' transaction(s).');
840 } elseif (Post
::has('next')) {
841 if (strlen($recon['comments'])< 3 ) {
842 $page->trigError('Le commentaire doit contenir au moins 3 caractères.');
844 XDB
::execute("UPDATE payment_reconcilations SET status = 'transfering' WHERE id = {?}", $_SESSION['paymentrecon_id']);
845 pl_redirect('admin/reconcile/step5');
848 } elseif (Post
::has('savecomments')) {
849 S
::assert_xsrf_token();
850 $recon['comments'] = Post
::v('comments');
851 $page->assign('recon', $recon);
852 XDB
::execute('UPDATE payment_reconcilations SET comments = {?} WHERE id = {?}', $recon['comments'], $_SESSION['paymentrecon_id']);
853 $page->trigSuccess('Les commentaires ont été enregistrés.');
856 // reconcilation results - ok
857 $res = XDB
::query('SELECT count(*), SUM(amount), SUM(commission)
858 FROM payment_transactions
859 WHERE recon_id = {?}',
861 list($ok_count, $ok_sum_amounts, $ok_sum_coms) = $res->fetchOneRow();
862 $page->assign('ok_count', $ok_count);
864 // reconcilation results - ref exists, but some data differs
865 $res = XDB
::query('SELECT id, fullref, method_id, ts_confirmed, trans.amount, trans.commission, status, recon_id,
866 reference, date, tmp.amount as amount2, tmp.commission as commission2
867 FROM payment_transactions AS trans
868 INNER JOIN payment_tmp AS tmp ON (trans.fullref = tmp.reference)
869 WHERE trans.recon_id IS NULL OR trans.recon_id != {?}',
871 $differs = $res->fetchAllAssoc();
872 $page->assign_by_ref('differs', $differs);
873 $page->assign('differ_count', count($differs));
875 // reconcilation results - ref doesn't exists in database
876 $res = XDB
::query('SELECT tmp.*
877 FROM payment_tmp AS tmp
878 LEFT JOIN payment_transactions AS trans ON (trans.fullref = tmp.reference)
879 WHERE trans.fullref IS NULL');
880 $only_import = $res->fetchAllAssoc();
881 $page->assign_by_ref('only_import', $only_import);
882 $page->assign('onlyim_count', count($only_import));
884 // reconcilation results - exists in database but not in import
885 $res = XDB
::query('SELECT trans.*
886 FROM payment_transactions AS trans
887 LEFT JOIN payment_tmp AS tmp ON (trans.fullref = tmp.reference)
888 WHERE {?} <= DATE(trans.ts_confirmed) AND DATE(trans.ts_confirmed) <= {?}
889 AND tmp.reference IS NULL AND method_id = {?}',
890 $recon['period_start'], $recon['period_end'], $recon['method_id']);
891 $only_database = $res->fetchAllAssoc();
892 $page->assign_by_ref('only_database', $only_database);
893 $page->assign('onlydb_count', count($only_database));
897 function handler_adm_transfers($page, $action = null
, $id = null
) {
898 // list/log all bank transfers and link them to individual transactions
900 if (Post
::has('generate')) {
901 $recon_ids = array_keys(Post
::v('recon_id'));
903 // generate a new reconcilation group ID
904 $res = XDB
::query("SELECT MAX(recongroup_id)+1 FROM payment_reconcilations");
905 $recongp_id = $res->fetchOneCell();
906 if ($recongp_id == null
) $recongp_id = 1;
908 // add reconcilations to group
909 // FIXME: should check if reconcilations are in good status
910 XDB
::execute("UPDATE payment_reconcilations
911 SET recongroup_id = {?}, status = 'closed'
913 $recongp_id, $recon_ids);
916 XDB
::execute('INSERT INTO payment_transfers
917 SELECT NULL, {?}, t.ref, SUM(t.amount+t.commission), NULL, p.text, NULL
918 FROM payment_transactions AS t
919 LEFT JOIN payments AS p ON (t.ref = p.id)
920 LEFT JOIN groups AS g ON (p.asso_id = g.id)
921 WHERE t.recon_id IN {?}
923 $recongp_id, $recon_ids);
925 //$res = XDB::query("SELECT * FROM payment_reconcilations WHERE id IN {?}", $recon_ids);
926 //$recons = $res->fetchAllAssoc();
928 $page->trigSuccess('Les virements ont été générés pour ' . count($recon_ids) . ' réconciliations.');
929 $this->handler_adm_reconcile($page);
931 } elseif ($action == 'delgroup') {
932 S
::assert_xsrf_token();
933 XDB
::execute("UPDATE payment_reconcilations
934 SET status = 'transfering', recongroup_id = NULL
935 WHERE recongroup_id = {?}", $id);
936 XDB
::execute("DELETE FROM payment_transfers
937 WHERE recongroup_id = {?} AND date IS NULL", $id);
939 $page->trigSuccess("Les virements non réalisés ont été supprimé du groupe ".$id.".");
940 $this->handler_adm_reconcile($page);
942 } elseif ($action == "confirm") {
943 S
::assert_xsrf_token();
944 XDB
::execute('UPDATE payment_transfers
946 WHERE id = {?}', $id);
948 $page->trigSuccess('Virement ' . $id . ' confirmé.');
949 $this->handler_adm_reconcile($page);
952 pl_redirect('admin/reconcile');
957 class PaymentLogsImporter
extends CSVImporter
{
960 public function __construct() {
961 parent
::__construct('');
962 $this->registerFunction('systempay_commission', 'Compute BPLC commission', array($this, 'compute_systempay_commission'));
963 $this->registerFunction('payment_id', 'Autocompute payment ID', array($this, 'compute_payment_id'));
964 //$this->forceValue('payment_id','func_payment_id');
967 public function run($action = null
, $insert_relation = null
, $update_relation = null
) {
968 $this->result
= array();
969 foreach ($this->data
as $line) {
970 $a = $this->makeAssoc($line, $insert_relation);
971 $a['date'] = preg_replace('/([0-9]{2})\/([0-9]{2})\/([0-9]{4}).*/', '\3-\2-\1', $a['date']);
972 $a['amount'] = str_replace(',', '.', $a['amount']);
973 $a['commission'] = str_replace(',', '.', $a['commission']);
974 $this->result
[] = $a;
978 public function get_result() {
979 return $this->result
;
982 static public function compute_systempay_commission($line, $key, $relation) {
983 static $EEE_countries = array(
984 'France', 'Allemagne', 'Autriche', 'Belgique', 'Bulgarie', 'Chypre',
985 'Danemark', 'Espagne', 'Estonie', 'Finlande', 'Grèce', 'Hongrie', 'Irlande', 'Islande', 'Italie',
986 'Lettonie', 'Liechtenstein', 'Lituanie', 'Luxembourg', 'Malte', 'Norvège', 'Pays-Bas', 'Pologne',
987 'Portugal', 'Roumanie', 'Royaume-Uni', 'Slovaquie', 'Slovénie', 'Suède', 'République Tchèque'
990 if($key!='commission' ||
!array_key_exists('carte', $line)) {
993 $amount = self
::getValue($line, 'amount', $relation['amount']);
994 if (in_array($line['pays carte'], $EEE_countries)) {
995 return -0.20 - round($amount * 0.005, 2);
997 return -0.20 - round($amount * 0.005, 2) - 0.76;
1001 static public function compute_payment_id($line, $key, $relation) {
1002 if ($key != 'payment_id') {
1005 $reference = self
::getValue($line, 'reference', $relation['reference']);
1006 if (ereg('-([0-9]+)$', $reference, $matches)) {
1014 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: