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, $conf_title="") {
25 echo "Error: ".$text."\n";
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 $content = "raison de l'erreur : " . $text . "\n";
31 if ($conf_title != "") {
32 $content = $content."paiement : ".$conf_title."\n";
34 $content = $content . "dump de REQUEST :\n" . var_export($_REQUEST, true
);
35 $mymail->setTxtBody($content);
37 echo "Notification sent.\n";
41 /* sort en affichant une erreur */
42 function paypal_erreur($text, $send=true
)
44 global $erreur, $globals;
49 $mymail = new PlMailer();
50 $mymail->addTo($globals->money
->email
);
51 $mymail->setFrom("webmaster@" . $globals->mail
->domain
);
52 $mymail->setSubject("erreur lors d'un télépaiement (PayPal)");
53 $mymail->setTxtBody("raison de l'erreur : ".$text."\n".
54 "paiement : $conf_title \n\n".
55 "dump de REQUEST :\n".
56 var_export($_REQUEST,true
));
59 Platal
::page()->trigError($text);
62 /* http://fr.wikipedia.org/wiki/Formule_de_Luhn */
63 function luhn($nombre) {
66 for ($i = 0; $i < strlen($s); ++
$i) {
68 $sum +
= ($i %
2) ?
(2 * $dgt) %
9 : $dgt;
73 /* calcule la clé d'acceptation a partir de 5 champs */
74 function cle_accept($d1, $d2, $d3, $d4, $d5)
76 $m1 = luhn($d1 . $d5);
77 $m2 = luhn($d2 . $d5);
78 $m3 = luhn($d3 . $d5);
79 $m4 = luhn($d4 . $d5);
80 $n = $m1 +
$m2 +
$m3 +
$m4;
81 $alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
82 return $alpha{$n-1} . $m1 . $m2 . $m3 . $m4;
85 /* decode the comment */
86 function comment_decode($comment) {
87 $comment = urldecode($comment);
88 if (is_utf8($comment)) {
91 return utf8_encode($comment);
95 /* check if a RIB account number is valid */
96 function check_rib($rib)
98 if(strlen($rib) != 23) return false
;
101 $rib = strtr(strtoupper($rib),'ABCDEFGHIJKLMNOPQRSTUVWXYZ','12345678912345678923456789');
102 $bank = substr($rib,0,5);
103 $counter = substr($rib,5,5);
104 $account = substr($rib,10,11);
105 $key = substr($rib,21,2);
108 return (0 == fmod(89 * $bank +
15 * $counter +
3 * $account +
$key, 97));
111 class PaymentModule
extends PLModule
116 'payment' => $this->make_hook('payment', AUTH_PUBLIC
, 'user'),
117 'payment/cyber2_return' => $this->make_hook('cyber2_return', AUTH_PUBLIC
, 'user', NO_HTTPS
),
118 'payment/paypal_return' => $this->make_hook('paypal_return', AUTH_PUBLIC
, 'user', NO_HTTPS
),
119 '%grp/paiement' => $this->make_hook('xnet_payment', AUTH_PUBLIC
, 'user'),
120 '%grp/payment' => $this->make_hook('xnet_payment', AUTH_PUBLIC
, 'user'),
121 '%grp/payment/csv' => $this->make_hook('payment_csv', AUTH_PASSWD
, 'groupadmin'),
122 '%grp/payment/cyber2_return' => $this->make_hook('cyber2_return', AUTH_PUBLIC
, 'user', NO_HTTPS
),
123 '%grp/payment/paypal_return' => $this->make_hook('paypal_return', AUTH_PUBLIC
, 'user', NO_HTTPS
),
124 'admin/payments' => $this->make_hook('admin', AUTH_PASSWD
, 'admin'),
125 'admin/payments/methods' => $this->make_hook('adm_methods', AUTH_PASSWD
, 'admin'),
126 'admin/payments/transactions' => $this->make_hook('adm_transactions', AUTH_PASSWD
, 'admin'),
127 'admin/reconcile' => $this->make_hook('adm_reconcile', AUTH_PASSWD
, 'admin'),
128 'admin/reconcile/importlogs' => $this->make_hook('adm_importlogs', AUTH_PASSWD
, 'admin'),
129 'admin/reconcile/transfers' => $this->make_hook('adm_transfers', AUTH_PASSWD
, 'admin'),
130 'admin/reconcile/bankaccounts' => $this->make_hook('adm_bankaccounts', AUTH_PASSWD
, 'admin'),
134 function handler_payment($page, $ref = -1)
136 $page->changeTpl('payment/payment.tpl');
137 $page->setTitle('Télépaiement');
138 $this->load('money.inc.php');
140 $meth = new PayMethod(Env
::i('methode', -1));
141 $pay = new Payment($ref);
143 if (!$pay->flags
->hasflag('public') && (!S
::user() ||
!S
::logged())) {
144 $page->kill("Vous n'avez pas les permissions nécessaires pour accéder à cette page.");
146 $page->assign('public', true
);
149 if ($pay->flags
->hasflag('old')) {
150 $page->kill('La transaction selectionnée est périmée.');
153 if (Env
::has('montant')) {
154 $pay->amount_def
= Env
::v('montant');
156 $val = (Post
::v('amount') != 0) ? Post
::v('amount') : $pay->amount_def
;
158 if (($error = $pay->check($val)) !== true
) {
159 $page->trigError($error);
162 if (Post
::has('op') && Post
::v('op', 'select') == 'submit') {
166 $user = User
::getSilent(Post
::t('login'));
169 if (is_null($user)) {
170 $page->trigError("L'identifiant est erroné.");
171 $page->assign('login_error', true
);
172 $page->assign('login', Post
::t('login'));
174 $pay->init($val, $meth);
175 $pay->prepareform($user);
176 $page->assign('full_name', $user->fullName(true
));
177 $page->assign('sex', $user->isFemale());
179 } elseif (S
::logged()) {
180 $res = XDB
::iterator('SELECT ts_confirmed, amount
181 FROM payment_transactions
182 WHERE uid = {?} AND ref = {?}
183 ORDER BY ts_confirmed DESC',
184 S
::v('uid', -1), $pay->id
);
187 $page->assign('transactions', $res);
190 // Only if $id = -1, meaning only for donation the site's association
192 $biggest_donations = XDB
::fetchAllAssoc('SELECT IF(p.display,
193 IF(ap.pid IS NOT NULL, CONCAT(a.full_name, \' (\', pd.promo, \')\'), a.full_name),
194 \'XXXX\') AS name, p.amount, p.ts_confirmed
195 FROM payment_transactions AS p
196 INNER JOIN accounts AS a ON (a.uid = p.uid)
197 LEFT JOIN account_profiles AS ap ON (a.uid = ap.uid AND FIND_IN_SET(\'owner\', ap.perms))
198 LEFT JOIN profile_display AS pd ON (ap.pid = pd.pid)
200 ORDER BY LENGTH(p.amount) DESC, p.amount DESC, name
204 $donations = XDB
::fetchAllAssoc('(SELECT SUM(amount) AS amount, YEAR(ts_confirmed) AS year, MONTH(ts_confirmed) AS month, ts_confirmed
205 FROM payment_transactions
206 WHERE ref = {?} AND YEAR(ts_confirmed) = YEAR(CURDATE())
209 (SELECT SUM(amount) AS amount, YEAR(ts_confirmed) AS year, 0 AS month, ts_confirmed
210 FROM payment_transactions
211 WHERE ref = {?} AND YEAR(ts_confirmed) < YEAR(CURDATE())
213 ORDER BY year DESC, month DESC',
216 $page->assign('biggest_donations', $biggest_donations);
217 $page->assign('donations', $donations);
218 $page->assign('donation', true
);
222 $val = floor($val * 100) / 100;
223 $page->assign('amount', $val);
224 $page->assign('comment', Env
::v('comment'));
226 $page->assign('meth', $meth);
227 $page->assign('pay', $pay);
228 $page->assign('evtlink', $pay->event());
231 function handler_cyber2_return($page, $uid = null
)
233 global $globals, $platal;
235 /* on vérifie la signature */
236 $vads_params = array();
237 foreach($_REQUEST as $key => $value)
238 if(substr($key,0,5) == 'vads_') {
239 $vads_params[$key] = $value;
242 $signature = sha1(join('+', $vads_params) . '+' . $globals->money
->cyperplus_key
);
243 //if($signature != Env::v('signature')) {
244 // cb_erreur("signature invalide");
247 /* on extrait les informations sur l'utilisateur */
248 $user = User
::get(Env
::i('vads_cust_id'));
250 cb_erreur("uid invalide");
253 /* on extrait la reference de la commande */
254 if (!ereg('-([0-9]+)$', Env
::v('vads_order_id'), $matches)) {
255 cb_erreur("référence de commande invalide");
259 $res = XDB
::query('SELECT mail, text, confirmation
261 WHERE id={?}', $ref);
262 if ($res->numRows() != 1) {
263 cb_erreur("référence de commande inconnue");
265 list($conf_mail, $conf_title, $conf_text) = $res->fetchOneRow();
267 /* on extrait le montant */
268 if (Env
::v('vads_currency') != '978') {
269 cb_erreur("monnaie autre que l'euro");
271 $montant = ((float)Env
::i('vads_amount')) / 100;
273 /* on extrait le code de retour */
274 if (Env
::v('vads_result') != '00') {
275 cb_erreur('erreur lors du paiement : ?? (' . Env
::v('vads_result') . ')', $conf_title);
278 /* on fait l'insertion en base de donnees */
279 XDB
::execute('INSERT INTO payment_transactions (id, method_id, uid, ref, fullref, ts_confirmed, amount, pkey, comment, status, display)
280 VALUES ({?}, 2, {?}, {?}, {?}, NOW(), {?}, {?}, {?}, "confirmed", {?})',
281 Env
::v('vads_trans_date'), $user->id(), $ref, Env
::v('vads_order_id'), $montant, '', Env
::v('vads_order_info'), Env
::i('vads_order_info2'));
282 echo "Payment stored.\n";
284 // We check if it is an Xnet payment and then update the related ML.
285 $res = XDB
::query('SELECT eid, asso_id
287 WHERE paiement_id = {?}', $ref);
288 if ($res->numRows() == 1) {
289 list($eid, $asso_id) = $res->fetchOneRow();
290 require_once dirname(__FILE__
) . '/xnetevents/xnetevents.inc.php';
291 $evt = get_event_detail($eid, false
, $asso_id);
292 subscribe_lists_event($user->id(), $evt['short_name'], 1, $montant, true
);
295 /* on genere le mail de confirmation */
296 $conf_text = str_replace(
297 array('<prenom>', '<nom>', '<promo>', '<montant>', '<salutation>', '<cher>', '<comment>'),
298 array($user->firstName(), $user->lastName(), $user->promo(), $montant,
299 $user->isFemale() ?
'Chère' : 'Cher', $user->isFemale() ?
'Chère' : 'Cher',
300 Env
::v('vads_order_info')), $conf_text);
303 $mymail = new PlMailer();
304 $mymail->setFrom($conf_mail);
305 $mymail->addCc($conf_mail);
306 $mymail->setSubject($conf_title);
307 $mymail->setWikiBody($conf_text);
308 $mymail->sendTo($user);
310 /* on envoie les details de la transaction à telepaiement@ */
311 $mymail = new PlMailer();
312 $mymail->setFrom("webmaster@" . $globals->mail
->domain
);
313 $mymail->addTo($globals->money
->email
);
314 $mymail->setSubject($conf_title);
315 $msg = 'utilisateur : ' . $user->login() . ' (' . $user->id() . ')' . "\n" .
316 'mail : ' . $user->forlifeEmail() . "\n\n" .
317 "paiement : $conf_title ($conf_mail)\n".
318 "reference : " . Env
::v('vads_order_id') . "\n".
319 "montant : $montant\n\n".
320 "dump de REQUEST:\n".
321 var_export($_REQUEST,true
);
322 $mymail->setTxtBody($msg);
324 echo "Notifications sent.\n";
328 function handler_paypal_return($page, $uid = null
)
330 $page->changeTpl('payment/retour_paypal.tpl');
332 /* reference banque (numero de transaction) */
333 $no_transaction = Env
::s('tx');
334 /* token a renvoyer pour avoir plus d'information */
335 $clef = Env
::s('sig');
337 $status = Env
::s('st');
339 $reason = ($status == 'Pending') ? Env
::s('pending_reason') : Env
::s('reason_code');
340 /* reference complete de la commande */
341 $fullref = Env
::s('cm');
342 /* montant de la transaction */
343 $montant = Env
::s('amt');
345 if (Env
::s('cc') != 'EUR') {
346 cb_erreur("monnaie autre que l'euro");
349 /* on extrait le code de retour */
350 if ($status != "Completed") {
352 paypal_erreur("erreur lors du paiement : $status - $reason");
354 paypal_erreur("Paiement annulé", false
);
358 /* on extrait les informations sur l'utilisateur */
359 $user = User
::get($uid);
361 paypal_erreur("uid invalide");
364 /* on extrait la reference de la commande */
365 if (!ereg('-xorg-([0-9]+)$', $fullref, $matches)) {
366 paypal_erreur("référence de commande invalide");
370 $res = XDB
::query('SELECT mail, text, confirmation
372 WHERE id = {?}', $ref);
373 if (!list($conf_mail, $conf_title, $conf_text) = $res->fetchOneRow()) {
374 paypal_erreur('référence de commande inconnue');
377 /* on fait l'insertion en base de donnees */
378 XDB
::execute("INSERT INTO payment_transactions (id, method_id, uid, ref, fullref, ts_confirmed, amount, pkey, comment, status, display)
379 VALUES ({?}, 1, {?}, {?}, {?}, NOW(), {?}, {?}, {?}, 'confirmed', {?})",
380 $no_transaction, $user->id(), $ref, $fullref, $montant, $clef, Env
::v('comment'), Get
::i('display'));
382 // We check if it is an Xnet payment and then update the related ML.
383 $res = XDB
::query('SELECT eid, asso_id
385 WHERE paiement_id = {?}', $ref);
386 if ($res->numRows() == 1) {
387 list($eid, $asso_id) = $res->fetchOneRow();
388 require_once dirname(__FILE__
) . '/xnetevents/xnetevents.inc.php';
389 $evt = get_event_detail($eid, false
, $asso_id);
390 subscribe_lists_event($user->id(), $evt['short_name'], 1, $montant, true
);
393 /* on genere le mail de confirmation */
394 $conf_text = str_replace(array('<prenom>', '<nom>', '<promo>', '<montant>', '<salutation>', '<cher>', '<comment>'),
395 array($user->firstName(), $user->lastName(), $user->promo(), $montant,
396 $user->isFemale() ?
'Chère' : 'Cher', $user->isFemale() ?
'Chère' : 'Cher',
397 Env
::v('comment')), $conf_text);
400 $mymail = new PlMailer();
401 $mymail->setFrom($conf_mail);
402 $mymail->addCc($conf_mail);
403 $mymail->setSubject($conf_title);
404 $mymail->setWikiBody($conf_text);
405 $mymail->sendTo($user);
407 /* on envoie les details de la transaction à telepaiement@ */
408 $mymail = new PlMailer();
409 $mymail->setFrom("webmaster@" . $globals->mail
->domain
);
410 $mymail->addTo($globals->money
->email
);
411 $mymail->setSubject($conf_title);
412 $msg = 'utilisateur : ' . $user->login() . ' (' . $user->id() . ')' . "\n" .
413 'mail : ' . $user->forlifeEmail() . "\n\n" .
414 "paiement : $conf_title ($conf_mail)\n".
415 "reference : $champ200\n".
416 "montant : $montant\n\n".
417 "dump de REQUEST:\n".
418 var_export($_REQUEST,true
);
419 $mymail->setTxtBody($msg);
422 $page->assign('texte', $conf_text);
423 $page->assign('erreur', $erreur);
426 function handler_xnet_payment($page, $pid = null
)
430 $perms = S
::v('perms');
431 if (!(S
::identified() && $perms->hasFlag('groupmember'))) {
435 $res = XDB
::query("SELECT 1
436 FROM group_events AS e
437 INNER JOIN group_event_participants AS ep ON (ep.eid = e.eid AND ep.uid = {?})
438 WHERE e.paiement_id = {?} AND e.asso_id = {?}",
439 S
::i('uid'), $pid, $globals->asso('id'));
440 $public = XDB
::query("SELECT 1
442 INNER JOIN group_events AS g ON (g.paiement_id = p.id)
443 WHERE g.asso_id = {?} AND p.id = {?} AND FIND_IN_SET('public', p.flags)",
444 $globals->asso('id'), $pid);
445 if ($res->numRows() == 0 && $public->numRows() == 0) {
450 if (!is_null($pid)) {
451 return $this->handler_payment($page, $pid);
453 $page->changeTpl('payment/xnet.tpl');
456 "SELECT id, text, url
458 WHERE asso_id = {?} AND NOT FIND_IN_SET('old', flags)
459 ORDER BY id DESC", $globals->asso('id'));
460 $tit = $res->fetchAllAssoc();
461 $page->assign('titles', $tit);
466 static $orders = array('ts_confirmed' => 'p', 'directory_name' => 'a', 'promo' => 'pd', 'comment' => 'p', 'amount' => 'p');
468 if (Get
::has('order_id') && Get
::has('order') && array_key_exists(Get
::v('order'), $orders)) {
469 $order_id = Get
::i('order_id');
470 $order = Get
::v('order');
471 $ordering = ' ORDER BY ' . $orders[$order] . '.' . $order;
472 if (Get
::has('order_inv') && Get
::i('order_inv') == 1) {
473 $ordering .= ' DESC';
474 $page->assign('order_inv', 0);
476 $page->assign('order_inv', 1);
478 $page->assign('order_id', $order_id);
479 $page->assign('order', $order);
480 $page->assign('anchor', 'legend_' . $order_id);
484 $page->assign('order', false
);
488 $page->assign('order', false
);
490 foreach($tit as $foo) {
493 $res = XDB
::query('SELECT p.uid, IF(p.ts_confirmed = \'0000-00-00\', 0, p.ts_confirmed) AS date, p.comment, p.amount
494 FROM payment_transactions AS p
495 INNER JOIN accounts AS a ON (a.uid = p.uid)
496 LEFT JOIN account_profiles AS ap ON (ap.uid = p.uid AND FIND_IN_SET(\'owner\', ap.perms))
497 LEFT JOIN profile_display AS pd ON (ap.pid = pd.pid)
498 WHERE p.ref = {?}' . (($order_id == $pid) ?
$ordering : ''),
500 $trans[$pid] = User
::getBulkUsersWithUIDs($res->fetchAllAssoc(), 'uid', 'user');
502 foreach ($trans[$pid] as $i => $t) {
503 $sum +
= $t['amount'];
504 $trans[$pid][$i]['amount'] = $t['amount'];
506 $trans[$pid][] = array('limit' => true
,
509 $res = XDB
::iterRow("SELECT e.eid, e.short_name, e.intitule, ep.nb, ei.montant, ep.paid
510 FROM group_events AS e
511 LEFT JOIN group_event_participants AS ep ON (ep.eid = e.eid AND ep.uid = {?})
512 INNER JOIN group_event_items AS ei ON (ep.eid = ei.eid AND ep.item_id = ei.item_id)
513 WHERE e.paiement_id = {?}",
515 $event[$pid] = array();
516 $event[$pid]['paid'] = 0;
518 $event[$pid]['topay'] = 0;
519 while(list($eid, $shortname, $title, $nb, $montant, $paid) = $res->next()) {
520 $event[$pid]['topay'] +
= ($nb * $montant);
521 $event[$pid]['eid'] = $eid;
522 $event[$pid]['shortname'] = $shortname;
523 $event[$pid]['title'] = $title;
524 $event[$pid]['ins'] = !is_null($nb);
525 $event[$pid]['paid'] = $paid;
528 $res = XDB
::query('SELECT SUM(amount) AS sum_amount
529 FROM payment_transactions
530 WHERE ref = {?} AND uid = {?}', $pid, S
::v('uid'));
531 $event[$pid]['paid'] = $res->fetchOneCell();
533 $page->register_modifier('decode_comment', 'decode_comment');
534 $page->assign('trans', $trans);
535 $page->assign('event', $event);
538 function handler_payment_csv($page, $pid = null
)
541 pl_redirect('payment');
543 if (substr($pid, -4) == '.vcf') {
544 $pid = substr($pid, 0, strlen($pid) - 4);
547 $res = XDB
::fetchAllAssoc('SELECT uid, IF(ts_confirmed = \'0000-00-00\', 0, ts_confirmed) AS date, comment, amount
548 FROM payment_transactions
550 ORDER BY ts_confirmed',
553 pl_redirect('payment');
556 $users = User
::getBulkUsersWithUIDs($res, 'uid', 'user');
559 pl_cached_content_headers('text/x-csv', 'iso-8859-1', 1);
560 $csv = fopen('php://output', 'w');
561 fputcsv($csv, array('Date', 'Nom', utf8_decode('Prénom'), 'Sexe', 'Promotion', 'Email', 'Commentaire', 'Montant'), ';');
562 foreach ($users as $item) {
563 $user = $item['user'];
564 $sum +
= $item['amount'];
565 fputcsv($csv, array(format_datetime($item['date'], '%d/%m/%y'), utf8_decode($user->lastName()), utf8_decode($user->firstName()),
566 ($user->isFemale()) ?
'F' : 'M', $user->promo(), $user->ForlifeEmail(),
567 utf8_decode($item['comment']), strtr($item['amount'], '.', ',') . ' EUR' ), ';');
569 fputcsv($csv, array(date('d/m/y'), 'Total', '', '', '' , '', '', strtr($sum, '.', ',') . ' EUR'), ';');
575 function handler_admin($page, $action = 'list', $id = null
) {
576 $page->setTitle('Administration - Paiements');
577 $page->assign('title', 'Gestion des télépaiements');
578 $table_editor = new PLTableEditor('admin/payments','payments','id');
579 //$table_editor->add_join_table('payment_transactions','ref',true); => on ne supprime jamais une transaction
580 $table_editor->add_sort_field('flags');
581 $table_editor->add_sort_field('id', true
, true
);
582 $table_editor->on_delete("UPDATE payments SET flags = 'old' WHERE id = {?}", "Le paiement a été archivé");
583 $table_editor->describe('text', 'intitulé', true
);
584 $table_editor->describe('url', 'site web', false
, true
);
585 $table_editor->describe('amount_def', 'montant par défaut', false
, true
);
586 $table_editor->describe('amount_min', 'montant minimum', false
, true
);
587 $table_editor->describe('amount_max', 'montant maximum', false
, true
);
588 $table_editor->describe('mail', 'email contact', true
);
589 $table_editor->describe('confirmation', 'message confirmation', false
, true
);
590 $table_editor->describe('rib_id', 'RIB', false
, true
);
591 // adds a column with the start date of the linked event if there is one
592 $table_editor->add_option_table('group_events', 'group_events.paiement_id = t.id');
593 $table_editor->add_option_field('group_events.archive', 'related_event', 'évènement archivé ?', 'tinyint');
594 // adds a column with the linked rib if there is one
595 $table_editor->add_option_table('payment_bankaccounts', 'payment_bankaccounts.id = t.rib_id');
596 $table_editor->add_option_field('payment_bankaccounts.owner', 'linked_rib_owner', 'rib associé', 'varchar');
598 $table_editor->apply($page, $action, $id);
601 function handler_adm_transactions($page, $payment_id = null
, $action = "list", $id = null
) {
602 // show transactions. FIXME: should not be modifiable
603 $page->setTitle('Administration - Paiements - Transactions');
604 $page->assign('title', "Liste des transactions pour le paiement {$payment_id}");
606 if ($payment_id == null
)
607 $page->trigError("Aucun ID de paiement fourni.");
609 $table_editor = new PLTableEditor("admin/transactions/{$payment_id}",'payment_transactions','id');
610 $table_editor->set_where_clause(XDB
::format('ref = {?}', $payment_id));
611 $table_editor->apply($page, 'list', $id); // only the 'list' action is allowed
612 $page->assign('readonly', 'readonly'); // don't show modification features
615 function handler_adm_bankaccounts($page, $action = "list", $id = null
) {
616 // managment of bank account used for money transfert
617 $page->setTitle('Administration - Paiements - RIBs');
618 $page->assign('title', "Liste des RIBs");
620 $table_editor = new PLTableEditor('admin/payments/bankaccounts', 'payment_bankaccounts', 'id');
621 $table_editor->describe('asso_id', 'ID du groupe', false
, false
);
622 $table_editor->describe('owner', 'titulaire', true
);
623 $table_editor->add_option_table('groups', 'groups.id = t.asso_id');
624 $table_editor->add_option_field('groups.diminutif', 'group_name', 'groupe', 'varchar','account');
627 if ($action == 'update' && Post
::has('account') && !check_rib(Post
::v('account'))) {
628 $page->trigError("Le RIB n'est pas valide");
629 $table_editor->apply($page, 'edit', $id);
633 $table_editor->apply($page, $action, $id);
636 function handler_adm_methods($page, $action = "list", $id = null
) {
637 // show and edit payment methods
638 $page->setTitle('Administration - Paiements - Méthodes');
639 $page->assign('title', 'Méthodes de paiement');
640 $table_editor = new PLTableEditor('admin/payments/methods', 'payment_methods', 'id');
641 $table_editor->apply($page, $action, $id);
644 function handler_adm_reconcile($page, $step = 'list', $param = null
) {
645 // reconciles logs with transactions
646 // FIXME: the admin is considered to be fair => he doesn't hack the $step value, nor other params
647 $page->setTitle('Administration - Paiements - Réconciliations');
648 $page->changeTpl('payment/reconcile.tpl');
649 $page->assign('step', $step);
653 if ($step == 'delete' && $param != null
) {
654 S
::assert_xsrf_token();
655 XDB
::execute('DELETE FROM payment_reconcilations WHERE id = {?}', $param);
656 // FIXME: hardcoding !!!
657 XDB
::execute('UPDATE payment_transactions SET recon_id = NULL,commission = NULL WHERE recon_id = {?} AND method_id = 2', $param);
658 XDB
::execute('UPDATE payment_transactions SET recon_id = NULL WHERE recon_id = {?} AND method_id = 1', $param);
659 $page->trigSuccess("L'entrée " . $param . ' a été supprimée.');
661 } elseif ($step == 'edit') {
662 $page->trigError("L'édition n'est pas implémentée.");
664 } elseif ($step == 'step5') {
665 $page->trigSuccess("La réconciliation est terminée. Il est maintenant nécessaire de générer les virements.");
670 // show list of reconciliations, with a "add" button
671 $page->assign('title', 'Réconciliation - Liste');
672 $page->assign('step', 'list');
676 $res = XDB
::query("SELECT r.id, short_name AS method, period_start, period_end, status,
677 payment_count, sum_amounts, sum_commissions
678 FROM payment_reconcilations AS r
679 LEFT JOIN payment_methods AS m ON (r.method_id = m.id)
680 WHERE recongroup_id IS NULL
681 ORDER BY period_end DESC, period_start DESC");
682 foreach ($res->fetchAllAssoc() as $recon)
683 $recongps[] = array('recons' => array($recon), 'transfers' => array());
685 $res = XDB
::query("SELECT recongroup_id AS id
686 FROM payment_reconcilations
687 GROUP BY recongroup_id
688 ORDER BY MAX(period_end) DESC, MIN(period_start) DESC");
689 foreach ($res->fetchAllAssoc() as $recongp) {
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 = {?}
695 ORDER BY period_end DESC, period_start DESC",
697 $recongp['recons'] = $res->fetchAllAssoc();
699 $res = XDB
::query('SELECT t.id, t.payment_id, t.amount, b.owner, t.message, t.date
700 FROM payment_transfers AS t
701 LEFT JOIN payment_bankaccounts AS b ON (t.account_id=b.id)
702 WHERE recongroup_id = {?}',
704 $recongp['transfers'] = $res->fetchAllAssoc();
706 $recongps[] = $recongp;
708 $page->assign_by_ref('recongps', $recongps);
712 function handler_adm_importlogs($page, $step, $param = null
) {
713 $page->setTitle('Administration - Paiements - Réconciliations');
714 $page->changeTpl('payment/reconcile.tpl');
715 $page->assign('step', $step);
717 if (isset($_SESSION['paymentrecon_data'])) {
718 // create temporary table with imported data
719 XDB
::execute('CREATE TEMPORARY TABLE payment_tmp (
720 reference VARCHAR(255) PRIMARY KEY,
723 commission DECIMAL(9,2)
725 foreach ($_SESSION['paymentrecon_data'] as $i)
726 XDB
::execute('INSERT INTO payment_tmp VALUES ({?}, {?}, {?}, {?})',
727 $i['reference'], $i['date'], $i['amount'], $i['commission']);
730 if ($step == 'step1') {
731 $page->assign('title', 'Étape 1');
732 unset($_SESSION['paymentrecon_method']);
733 unset($_SESSION['paymentrecon_data']);
734 unset($_SESSION['paymentrecon_id']);
736 // was a payment method choosen ?
737 if ($param != null
) {
738 $_SESSION['paymentrecon_method'] = (int)$param;
739 pl_redirect('admin/reconcile/importlogs/step2');
742 // ask to choose a payment method
743 $res = XDB
::query('SELECT id, text FROM payment_methods');
744 $page->assign('methods', $res->fetchAllAssoc());
747 } elseif ( $step == 'step2' ) {
748 $page->assign('title', 'Étape 2');
750 // import logs formated in CVS
751 $fields = array('date', 'reference', 'amount', 'commission');
752 $importer = new PaymentLogsImporter();
753 $importer->apply($page, 'admin/reconcile/importlogs/step2', $fields);
755 // if import is finished
756 $result = $importer->get_result();
757 if($result != null
) {
758 $_SESSION['paymentrecon_data'] = $result;
759 pl_redirect('admin/reconcile/importlogs/step3');
762 } elseif ($step == 'step3' ) {
763 $page->assign('title', 'Étape 3');
765 // compute reconcilation summary data
766 $res = XDB
::query('SELECT MIN(date) AS period_start, MAX(date) AS period_end,
767 count(*) AS payment_count, SUM(amount) AS sum_amounts,
768 SUM(commission) AS sum_commissions
770 $recon = $res->fetchOneAssoc();
771 $recon['method_id'] = $_SESSION['paymentrecon_method'];
773 // create reconciliation item in database
774 if(Post
::has('next')) {
775 S
::assert_xsrf_token();
778 $recon['period_start'] = preg_replace('/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/', '\3-\2-\1', Post
::v('period_start'));
779 $recon['period_end'] = preg_replace('/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/', '\3-\2-\1', Post
::v('period_end'));
780 // FIXME: save checks to be done at next step
782 // Create reconcilation item in database
783 // FIXME: check if period doesn't overlap with others for the same method_id
784 XDB
::execute('INSERT INTO payment_reconcilations (method_id, period_start, period_end,
785 payment_count, sum_amounts, sum_commissions)
786 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
787 $recon['method_id'], $recon['period_start'], $recon['period_end'],
788 $recon['payment_count'], $recon['sum_amounts'], $recon['sum_commissions']);
789 $_SESSION['paymentrecon_id'] = XDB
::insertId();
791 // reconcile simple cases (trans.commission n'est modifié que s'il vaut NULL)
792 XDB
::execute("UPDATE payment_transactions AS trans, payment_tmp AS tmp
793 SET trans.recon_id = {?}, trans.commission=tmp.commission
794 WHERE trans.fullref = tmp.reference
795 AND trans.amount = tmp.amount AND DATE(trans.ts_confirmed) = tmp.date
796 AND (trans.commission IS NULL OR trans.commission = tmp.commission)
797 AND method_id = {?} AND recon_id IS NULL AND status = 'confirmed'",
798 $_SESSION['paymentrecon_id'], $recon['method_id']);
800 pl_redirect("admin/reconcile/importlogs/step4");
802 // show summary of the imported data + ask form start/end of reconcilation period
804 $recon['period_start'] = preg_replace('/([0-9]{4})-([0-9]{2})-([0-9]{2})/', '\3/\2/\1', $recon['period_start']);
805 $recon['period_end'] = preg_replace('/([0-9]{4})-([0-9]{2})-([0-9]{2})/', '\3/\2/\1', $recon['period_end']);
806 $page->assign('recon', $recon);
809 } elseif ($step == 'step4' ) {
810 $page->assign('title', 'Étape 4');
812 // get reconcilation summary informations
813 $res = XDB
::query('SELECT * FROM payment_reconcilations WHERE id = {?}', $_SESSION['paymentrecon_id']);
814 $recon = $res->fetchOneAssoc();
815 $page->assign('recon', $recon);
817 if (Post
::has('force')) {
818 S
::assert_xsrf_token();
819 foreach (Post
::v('force') as $id => $value) {
820 XDB
::execute('UPDATE payment_transactions AS trans, payment_tmp AS tmp
821 SET trans.recon_id = {?}, trans.commission = tmp.commission
822 WHERE trans.id = {?} AND trans.fullref = tmp.reference',
823 $_SESSION['paymentrecon_id'], $id);
825 $page->trigSuccess('La réconciliation a été forcée pour ' . count(Post
::v('force')) . ' transaction(s).');
827 } elseif (Post
::has('next')) {
828 if (strlen($recon['comments'])< 3 ) {
829 $page->trigError('Le commentaire doit contenir au moins 3 caractères.');
831 XDB
::execute("UPDATE payment_reconcilations SET status = 'transfering' WHERE id = {?}", $_SESSION['paymentrecon_id']);
832 pl_redirect('admin/reconcile/step5');
835 } elseif (Post
::has('savecomments')) {
836 S
::assert_xsrf_token();
837 $recon['comments'] = Post
::v('comments');
838 $page->assign('recon', $recon);
839 XDB
::execute('UPDATE payment_reconcilations SET comments = {?} WHERE id = {?}', $recon['comments'], $_SESSION['paymentrecon_id']);
840 $page->trigSuccess('Les commentaires ont été enregistrés.');
843 // reconcilation results - ok
844 $res = XDB
::query('SELECT count(*), SUM(amount), SUM(commission)
845 FROM payment_transactions
846 WHERE recon_id = {?}',
848 list($ok_count, $ok_sum_amounts, $ok_sum_coms) = $res->fetchOneRow();
849 $page->assign('ok_count', $ok_count);
851 // reconcilation results - ref exists, but some data differs
852 $res = XDB
::query('SELECT id, fullref, method_id, ts_confirmed, trans.amount, trans.commission, status, recon_id,
853 reference, date, tmp.amount as amount2, tmp.commission as commission2
854 FROM payment_transactions AS trans
855 INNER JOIN payment_tmp AS tmp ON (trans.fullref = tmp.reference)
856 WHERE trans.recon_id IS NULL OR trans.recon_id != {?}',
858 $differs = $res->fetchAllAssoc();
859 $page->assign_by_ref('differs', $differs);
860 $page->assign('differ_count', count($differs));
862 // reconcilation results - ref doesn't exists in database
863 $res = XDB
::query('SELECT tmp.*
864 FROM payment_tmp AS tmp
865 LEFT JOIN payment_transactions AS trans ON (trans.fullref = tmp.reference)
866 WHERE trans.fullref IS NULL');
867 $only_import = $res->fetchAllAssoc();
868 $page->assign_by_ref('only_import', $only_import);
869 $page->assign('onlyim_count', count($only_import));
871 // reconcilation results - exists in database but not in import
872 $res = XDB
::query('SELECT trans.*
873 FROM payment_transactions AS trans
874 LEFT JOIN payment_tmp AS tmp ON (trans.fullref = tmp.reference)
875 WHERE {?} <= DATE(trans.ts_confirmed) AND DATE(trans.ts_confirmed) <= {?}
876 AND tmp.reference IS NULL AND method_id = {?}',
877 $recon['period_start'], $recon['period_end'], $recon['method_id']);
878 $only_database = $res->fetchAllAssoc();
879 $page->assign_by_ref('only_database', $only_database);
880 $page->assign('onlydb_count', count($only_database));
884 function handler_adm_transfers($page, $action = null
, $id = null
) {
885 // list/log all bank transfers and link them to individual transactions
887 if (Post
::has('generate')) {
888 $recon_ids = array_keys(Post
::v('recon_id'));
890 // generate a new reconcilation group ID
891 $res = XDB
::query("SELECT MAX(recongroup_id)+1 FROM payment_reconcilations");
892 $recongp_id = $res->fetchOneCell();
893 if ($recongp_id == null
) $recongp_id = 1;
895 // add reconcilations to group
896 // FIXME: should check if reconcilations are in good status
897 XDB
::execute("UPDATE payment_reconcilations
898 SET recongroup_id = {?}, status = 'closed'
900 $recongp_id, $recon_ids);
903 XDB
::execute('INSERT INTO payment_transfers
904 SELECT NULL, {?}, t.ref, SUM(t.amount+t.commission), p.rib_id, p.text, NULL
905 FROM payment_transactions AS t
906 LEFT JOIN payments AS p ON (t.ref = p.id)
907 LEFT JOIN groups AS g ON (p.asso_id = g.id)
908 WHERE t.recon_id IN {?}
910 $recongp_id, $recon_ids);
912 //$res = XDB::query("SELECT * FROM payment_reconcilations WHERE id IN {?}", $recon_ids);
913 //$recons = $res->fetchAllAssoc();
915 $page->trigSuccess('Les virements ont été générés pour ' . count($recon_ids) . ' réconciliations.');
916 $this->handler_adm_reconcile($page);
918 } elseif ($action == 'delgroup') {
919 S
::assert_xsrf_token();
920 XDB
::execute("UPDATE payment_reconcilations
921 SET status = 'transfering', recongroup_id = NULL
922 WHERE recongroup_id = {?}", $id);
923 XDB
::execute("DELETE FROM payment_transfers
924 WHERE recongroup_id = {?} AND date IS NULL", $id);
926 $page->trigSuccess("Les virements non réalisés ont été supprimé du groupe ".$id.".");
927 $this->handler_adm_reconcile($page);
929 } elseif ($action == "confirm") {
930 S
::assert_xsrf_token();
931 XDB
::execute('UPDATE payment_transfers
933 WHERE id = {?}', $id);
935 $page->trigSuccess('Virement ' . $id . ' confirmé.');
936 $this->handler_adm_reconcile($page);
939 pl_redirect('admin/reconcile');
944 class PaymentLogsImporter
extends CSVImporter
{
947 public function __construct() {
948 parent
::__construct('');
949 $this->registerFunction('systempay_commission', 'Compute BPLC commission', array($this, 'compute_systempay_commission'));
950 $this->registerFunction('payment_id', 'Autocompute payment ID', array($this, 'compute_payment_id'));
951 //$this->forceValue('payment_id','func_payment_id');
954 public function run($action = null
, $insert_relation = null
, $update_relation = null
) {
955 $this->result
= array();
956 foreach ($this->data
as $line) {
957 $a = $this->makeAssoc($line, $insert_relation);
959 $a['date'] = preg_replace('/([0-9]{2})\/([0-9]{2})\/([0-9]{4}).*/', '\3-\2-\1', $a['date']);
960 $a['date'] = preg_replace('/T.*/','', $a['date']);
963 $a['amount'] = str_replace(',', '.', $a['amount']);
964 $a['commission'] = str_replace(',', '.', $a['commission']);
965 $this->result
[] = $a;
969 public function get_result() {
970 return $this->result
;
973 static public function compute_systempay_commission($line, $key, $relation) {
974 static $EEE_countries = array(
975 'France', 'Allemagne', 'Autriche', 'Belgique', 'Bulgarie', 'Chypre', 'Suisse',
976 'Danemark', 'Espagne', 'Estonie', 'Finlande', 'Grèce', 'Hongrie', 'Irlande', 'Islande', 'Italie',
977 'Lettonie', 'Liechtenstein', 'Lituanie', 'Luxembourg', 'Malte', 'Norvège', 'Pays-Bas', 'Pologne',
978 'Portugal', 'Roumanie', 'Royaume-Uni', 'Slovaquie', 'Slovénie', 'Suède', 'République Tchèque'
981 if($key!='commission' ||
!array_key_exists('carte', $line)) {
984 $amount = self
::getValue($line, 'amount', $relation['amount']);
985 if (in_array($line['pays carte'], $EEE_countries)) {
986 return -0.20 - round($amount * 0.005, 2);
988 return -0.20 - round($amount * 0.005, 2) - 0.76;
992 static public function compute_payment_id($line, $key, $relation) {
993 if ($key != 'payment_id') {
996 $reference = self
::getValue($line, 'reference', $relation['reference']);
997 if (ereg('-([0-9]+)$', $reference, $matches)) {
1005 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: