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/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
),
113 '%grp/payment/csv' => $this->make_hook('payment_csv', AUTH_MDP
, 'groupadmin'),
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'),
126 function handler_payment($page, $ref = -1)
130 $this->load('money.inc.php');
132 if (!empty($GLOBALS['IS_XNET_SITE'])) {
133 if (!$globals->asso('id')) {
136 $res = XDB
::query('SELECT asso_id
138 WHERE asso_id = {?} AND id = {?}',
139 $globals->asso('id'), $ref);
140 if (!$res->numRows()) {
144 $page->changeTpl('payment/index.tpl');
145 $page->setTitle('Télépaiements');
148 $op = Env
::v('op', 'select');
149 $meth = new PayMethod(Env
::i('methode', -1));
150 $pay = new Payment($ref);
152 if($pay->flags
->hasflag('old')){
153 $page->trigError("La transaction selectionnée est périmée.");
154 $pay = new Payment();
156 $val = Env
::v('montant') != 0 ? Env
::v('montant') : $pay->amount_def
;
158 if (($e = $pay->check($val)) !== true
) {
159 $page->trigError($e);
162 if ($op == 'submit') {
163 $pay->init($val, $meth);
164 $pay->prepareform($pay);
166 $res = XDB
::iterator('SELECT timestamp, amount
167 FROM payment_transactions
168 WHERE uid = {?} AND ref = {?}
169 ORDER BY timestamp DESC',
170 S
::v('uid', -1), $ref);
173 $page->assign('transactions', $res);
177 $val = floor($val) . '.' . substr(floor(($val - floor($val)) * 100 +
100), 1);
178 $page->assign('montant', $val);
179 $page->assign('comment', Env
::v('comment'));
181 $page->assign('meth', $meth);
182 $page->assign('pay', $pay);
183 $page->assign('evtlink', $pay->event());
184 $page->assign('sex', S
::user()->isFemale());
187 function handler_cyber2_return($page, $uid = null
)
189 global $globals, $platal;
191 /* on vérifie la signature */
192 $vads_params = array();
193 foreach($_REQUEST as $key => $value)
194 if(substr($key,0,5) == 'vads_') {
195 $vads_params[$key] = $value;
198 $signature = sha1(join('+', $vads_params) . '+' . $globals->money
->cyperplus_key
);
199 //if($signature != Env::v('signature')) {
200 // cb_erreur("signature invalide");
203 /* on extrait les informations sur l'utilisateur */
204 $user = User
::get(Env
::i('vads_cust_id'));
206 cb_erreur("uid invalide");
209 /* on extrait la reference de la commande */
210 if (!ereg('-([0-9]+)$', Env
::v('vads_order_id'), $matches)) {
211 cb_erreur("référence de commande invalide");
215 $res = XDB
::query('SELECT mail, text, confirmation
217 WHERE id={?}', $ref);
218 if ($res->numRows() != 1) {
219 cb_erreur("référence de commande inconnue");
221 list($conf_mail, $conf_title, $conf_text) = $res->fetchOneRow();
223 /* on extrait le montant */
224 if (Env
::v('vads_currency') != '978') {
225 cb_erreur("monnaie autre que l'euro");
227 $amount = ((float)Env
::i('vads_amount')) / 100;
228 $montant = sprintf("%.02f EUR", $amount);
230 /* on extrait le code de retour */
231 if (Env
::v('vads_result') != '00') {
232 cb_erreur('erreur lors du paiement : ?? (' . Env
::v('vads_result') . ')');
235 /* on fait l'insertion en base de donnees */
236 XDB
::execute('INSERT INTO payment_transactions (id, uid, ref, fullref, amount, pkey, comment)
237 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})',
238 Env
::v('vads_trans_date'), $user->id(), $ref, Env
::v('vads_order_id'), $montant, '', Env
::v('vads_order_info'));
239 echo "Paiement stored.\n";
241 // We check if it is an Xnet payment and then update the related ML.
242 $res = XDB
::query('SELECT eid, asso_id
244 WHERE paiement_id = {?}', $ref);
245 if ($res->numRows() == 1) {
246 list($eid, $asso_id) = $res->fetchOneRow();
247 require_once dirname(__FILE__
) . '/xnetevents/xnetevents.inc.php';
248 $evt = get_event_detail($eid, false
, $asso_id);
249 subscribe_lists_event($user->id(), $evt['short_name'], 1, $amount, true
);
252 /* on genere le mail de confirmation */
253 $conf_text = str_replace(
254 array('<prenom>', '<nom>', '<promo>', '<montant>', '<salutation>', '<cher>', '<comment>'),
255 array($user->firstName(), $user->lastName(), $user->promo(), $montant,
256 $user->isFemale() ?
'Chère' : 'Cher', $user->isFemale() ?
'Chère' : 'Cher',
257 Env
::v('vads_order_info')), $conf_text);
260 $mymail = new PlMailer();
261 $mymail->setFrom($conf_mail);
262 $mymail->addCc($conf_mail);
263 $mymail->setSubject($conf_title);
264 $mymail->setWikiBody($conf_text);
265 $mymail->sendTo($user);
267 /* on envoie les details de la transaction à telepaiement@ */
268 $mymail = new PlMailer();
269 $mymail->setFrom("webmaster@" . $globals->mail
->domain
);
270 $mymail->addTo($globals->money
->email
);
271 $mymail->setSubject($conf_title);
272 $msg = 'utilisateur : ' . $user->login() . ' (' . $user->id() . ')' . "\n" .
273 'mail : ' . $user->forlifeEmail() . "\n\n" .
274 "paiement : $conf_title ($conf_mail)\n".
275 "reference : " . Env
::v('vads_order_id') . "\n".
276 "montant : $montant\n\n".
277 "dump de REQUEST:\n".
278 var_export($_REQUEST,true
);
279 $mymail->setTxtBody($msg);
281 echo "Notifications sent.\n";
285 function handler_paypal_return($page, $uid = null
)
287 $page->changeTpl('payment/retour_paypal.tpl');
289 /* reference banque (numero de transaction) */
290 $no_transaction = Env
::s('tx');
291 /* token a renvoyer pour avoir plus d'information */
292 $clef = Env
::s('sig');
294 $status = Env
::s('st');
296 $reason = ($status == 'Pending') ? Env
::s('pending_reason') : Env
::s('reason_code');
297 /* reference complete de la commande */
298 $fullref = Env
::s('cm');
299 /* montant de la transaction */
300 $montant_nb = Env
::s('amt');
302 $montant_dev = Env
::s('cc');
303 $montant = "$montant_nb $montant_dev";
305 /* on extrait le code de retour */
306 if ($status != "Completed") {
308 paypal_erreur("erreur lors du paiement : $status - $reason");
310 paypal_erreur("Paiement annulé", false
);
314 /* on extrait les informations sur l'utilisateur */
315 $user = User
::get($uid);
317 paypal_erreur("uid invalide");
320 /* on extrait la reference de la commande */
321 if (!ereg('-xorg-([0-9]+)$', $fullref, $matches)) {
322 paypal_erreur("référence de commande invalide");
326 $res = XDB
::query('SELECT mail, text, confirmation
328 WHERE id = {?}', $ref);
329 if (!list($conf_mail, $conf_title, $conf_text) = $res->fetchOneRow()) {
330 paypal_erreur('référence de commande inconnue');
333 /* on fait l'insertion en base de donnees */
334 XDB
::execute("INSERT INTO payment_transactions (id, uid, ref, fullref, amount, pkey, comment)
335 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})",
336 $no_transaction, $user->id(), $ref, $fullref, $montant, $clef, Env
::v('comment'));
338 // We check if it is an Xnet payment and then update the related ML.
339 $res = XDB
::query('SELECT eid
341 WHERE paiement_id = {?}', $ref);
342 if ($eid = $res->fetchOneCell()) {
343 require_once dirname(__FILE__
) . '/xnetevents/xnetevents.inc.php';
344 $evt = get_event_detail($eid);
345 subscribe_lists_event($user->id(), $evt['short_name'], 1, $montant, true
);
348 /* on genere le mail de confirmation */
349 $conf_text = str_replace(array('<prenom>', '<nom>', '<promo>', '<montant>', '<salutation>', '<cher>', '<comment>'),
350 array($user->firstName(), $user->lastName(), $user->promo(), $montant,
351 $user->isFemale() ?
'Chère' : 'Cher', $user->isFemale() ?
'Chère' : 'Cher',
352 Env
::v('comment')), $conf_text);
355 $mymail = new PlMailer();
356 $mymail->setFrom($conf_mail);
357 $mymail->addCc($conf_mail);
358 $mymail->setSubject($conf_title);
359 $mymail->setWikiBody($conf_text);
360 $mymail->sendTo($user);
362 /* on envoie les details de la transaction à telepaiement@ */
363 $mymail = new PlMailer();
364 $mymail->setFrom("webmaster@" . $globals->mail
->domain
);
365 $mymail->addTo($globals->money
->email
);
366 $mymail->setSubject($conf_title);
367 $msg = 'utilisateur : ' . $user->login() . ' (' . $user->id() . ')' . "\n" .
368 'mail : ' . $user->forlifeEmail() . "\n\n" .
369 "paiement : $conf_title ($conf_mail)\n".
370 "reference : $champ200\n".
371 "montant : $montant\n\n".
372 "dump de REQUEST:\n".
373 var_export($_REQUEST,true
);
374 $mymail->setTxtBody($msg);
377 $page->assign('texte', $conf_text);
378 $page->assign('erreur', $erreur);
381 function handler_xnet_payment($page, $pid = null
)
385 $perms = S
::v('perms');
386 if (!$perms->hasFlag('groupmember')) {
390 $res = XDB
::query("SELECT 1
391 FROM group_events AS e
392 INNER JOIN group_event_participants AS ep ON (ep.eid = e.eid AND e.uid = {?})
393 WHERE e.paiement_id = {?} AND e.asso_id = {?}",
394 S
::i('uid'), $pid, $globals->asso('id'));
395 if ($res->numRows() == 0) {
400 if (!is_null($pid)) {
401 return $this->handler_payment($page, $pid);
403 $page->changeTpl('payment/xnet.tpl');
406 "SELECT id, text, url
408 WHERE asso_id = {?} AND NOT FIND_IN_SET('old', flags)
409 ORDER BY id DESC", $globals->asso('id'));
410 $tit = $res->fetchAllAssoc();
411 $page->assign('titles', $tit);
416 static $orders = array('timestamp' => 'p', 'directory_name' => 'a', 'promo' => 'pd', 'comment' => 'p', 'amount' => 'p');
418 if (Get
::has('order_id') && Get
::has('order') && array_key_exists(Get
::v('order'), $orders)) {
419 $order_id = Get
::i('order_id');
420 $order = Get
::v('order');
421 $ordering = ' ORDER BY ' . $orders[$order] . '.' . $order;
422 if (Get
::has('order_inv') && Get
::i('order_inv') == 1) {
423 $ordering .= ' DESC';
424 $page->assign('order_inv', 0);
426 $page->assign('order_inv', 1);
428 $page->assign('order_id', $order_id);
429 $page->assign('order', $order);
430 $page->assign('anchor', 'legend_' . $order_id);
434 $page->assign('order', false
);
438 $page->assign('order', false
);
440 foreach($tit as $foo) {
443 $res = XDB
::query('SELECT p.uid, IF(p.timestamp = \'0000-00-00\', 0, p.timestamp) AS date, p.comment, p.amount
444 FROM payment_transactions AS p
445 INNER JOIN accounts AS a ON (a.uid = p.uid)
446 LEFT JOIN account_profiles AS ap ON (ap.uid = p.uid AND FIND_IN_SET(\'owner\', ap.perms))
447 LEFT JOIN profile_display AS pd ON (ap.pid = pd.pid)
448 WHERE p.ref = {?}' . (($order_id == $pid) ?
$ordering : ''),
450 $trans[$pid] = User
::getBulkUsersWithUIDs($res->fetchAllAssoc(), 'uid', 'user');
452 foreach ($trans[$pid] as $i => $t) {
453 $sum +
= strtr(substr($t['amount'], 0, strpos($t['amount'], 'EUR')), ',', '.');
454 $trans[$pid][$i]['amount'] = str_replace('EUR', '€', $t['amount']);
456 $trans[$pid][] = array('limit' => true
,
457 'amount' => strtr($sum, '.', ',') . ' €');
459 $res = XDB
::iterRow("SELECT e.eid, e.short_name, e.intitule, ep.nb, ei.montant, ep.paid
460 FROM group_events AS e
461 LEFT JOIN group_event_participants AS ep ON (ep.eid = e.eid AND ep.uid = {?})
462 INNER JOIN group_event_items AS ei ON (ep.eid = ei.eid AND ep.item_id = ei.item_id)
463 WHERE e.paiement_id = {?}",
465 $event[$pid] = array();
466 $event[$pid]['paid'] = 0;
468 $event[$pid]['topay'] = 0;
469 while(list($eid, $shortname, $title, $nb, $montant, $paid) = $res->next()) {
470 $event[$pid]['topay'] +
= ($nb * $montant);
471 $event[$pid]['eid'] = $eid;
472 $event[$pid]['shortname'] = $shortname;
473 $event[$pid]['title'] = $title;
474 $event[$pid]['ins'] = !is_null($nb);
475 $event[$pid]['paid'] = $paid;
478 $res = XDB
::query('SELECT amount
479 FROM payment_transactions
480 WHERE id = {?} AND uid = {?}', $pid, S
::v('uid'));
481 $montants = $res->fetchColumn();
483 foreach ($montants as $m) {
484 $p = strtr(substr($m, 0, strpos($m, 'EUR')), ',', '.');
485 $event[$pid]['paid'] +
= trim($p);
488 $page->register_modifier('decode_comment', 'decode_comment');
489 $page->assign('trans', $trans);
490 $page->assign('event', $event);
493 function handler_payment_csv($page, $pid = null
)
496 pl_redirect('payment');
498 if (substr($pid, -4) == '.vcf') {
499 $pid = substr($pid, 0, strlen($pid) - 4);
502 $res = XDB
::fetchAllAssoc('SELECT uid, IF(timestamp = \'0000-00-00\', 0, timestamp) AS date, comment, amount
503 FROM payment_transactions
508 pl_redirect('payment');
511 $users = User
::getBulkUsersWithUIDs($res, 'uid', 'user');
514 pl_cached_content_headers('text/x-csv', 1);
515 $csv = fopen('php://output', 'w');
516 fputcsv($csv, array('Date', 'Nom', 'Prénom', 'Sexe', 'Promotion', 'Email', 'Commentaire', 'Montant'), ';');
517 foreach ($users as $item) {
518 $user = $item['user'];
519 $sum +
= strtr(substr($item['amount'], 0, strpos($item['amount'], 'EUR')), ',', '.');
520 fputcsv($csv, array(format_datetime($item['date'], '%d/%m/%y'), $user->lastName(), $user->firstName(),
521 ($user->isFemale()) ?
'F' : 'M', $user->promo(), $user->ForlifeEmail(),
522 $item['comment'], str_replace('EUR', '€', $item['amount'])), ';');
524 fputcsv($csv, array(date('d/m/y'), 'Total', '', '', '' , '', '', strtr($sum, '.', ',') . ' €'), ';');
530 function handler_admin($page, $action = 'list', $id = null
) {
531 $page->setTitle('Administration - Paiements');
532 $page->assign('title', 'Gestion des télépaiements');
533 $table_editor = new PLTableEditor('admin/payments','payments','id');
534 //$table_editor->add_join_table('payment_transactions','ref',true); => on ne supprime jamais une transaction
535 $table_editor->add_sort_field('flags');
536 $table_editor->add_sort_field('id', true
, true
);
537 $table_editor->on_delete("UPDATE payments SET flags = 'old' WHERE id = {?}", "Le paiement a été archivé");
538 $table_editor->describe('text', 'intitulé', true
);
539 $table_editor->describe('url', 'site web', false
);
540 $table_editor->describe('amount_def', 'montant par défaut', false
);
541 $table_editor->describe('amount_min', 'montant minimum', false
);
542 $table_editor->describe('amount_max', 'montant maximum', false
);
543 $table_editor->describe('mail', 'email contact', true
);
544 $table_editor->describe('confirmation', 'message confirmation', false
);
546 // adds a column with the start date of the linked event if there is one
547 $table_editor->add_option_table('group_events', 'group_events.paiement_id = t.id');
548 $table_editor->add_option_field('group_events.debut', 'related_event', 'évènement', 'timestamp');
550 $table_editor->apply($page, $action, $id);
553 function handler_adm_transactions($page, $payment_id = null
, $action = "list", $id = null
) {
554 // show transactions. FIXME: should not be modifiable
555 $page->setTitle('Administration - Paiements - Transactions');
556 $page->assign('title', "Liste des transactions pour le paiement {$payment_id}");
558 if ($payment_id == null
)
559 $page->trigError("Aucun ID de paiement fourni.");
561 $table_editor = new PLTableEditor("admin/transactions/{$payment_id}",'payment_transactions','id');
562 $table_editor->set_where_clause(XDB
::format('ref = {?}', $payment_id));
563 $table_editor->apply($page, 'list', $id); // only the 'list' action is allowed
564 $page->assign('readonly', 'readonly'); // don't show modification features
567 function handler_adm_bankaccounts($page, $action = "list", $id = null
) {
568 // managment of bank account used for money transfert
569 $page->setTitle('Administration - Paiements - RIBs');
570 $page->assign('title', "Liste des RIBs");
572 $table_editor = new PLTableEditor('admin/payments/bankaccounts', 'payment_bankaccounts', 'id');
573 $table_editor->describe('asso_id', 'ID du groupe', false
);
574 $table_editor->describe('owner', 'titulaire', true
);
575 $table_editor->add_option_table('groups', 'groups.id = t.asso_id');
576 $table_editor->add_option_field('groups.diminutif', 'group_name', 'groupe', 'varchar','account');
579 if ($action == 'update' && Post
::has('account') && !check_rib(Post
::v('account'))) {
580 $page->trigError("Le RIB n'est pas valide");
581 $table_editor->apply($page, 'edit', $id);
585 $table_editor->apply($page, $action, $id);
588 function handler_adm_methods($page, $action = "list", $id = null
) {
589 // show and edit payment methods
590 $page->setTitle('Administration - Paiements - Méthodes');
591 $page->assign('title', 'Méthodes de paiement');
592 $table_editor = new PLTableEditor('admin/payments/methods', 'payment_methods', 'id');
593 $table_editor->apply($page, $action, $id);
596 function handler_adm_reconcile($page, $step = 'list', $param = null
) {
597 // reconciles logs with transactions
598 // FIXME: the admin is considered to be fair => he doesn't hack the $step value, nor other params
599 $page->setTitle('Administration - Paiements - Réconciliations');
600 $page->changeTpl('payment/reconcile.tpl');
601 $page->assign('step', $step);
605 if ($step == 'delete' && $param != null
) {
606 S
::assert_xsrf_token();
607 XDB
::execute('DELETE FROM payment_reconcilations WHERE id = {?}', $param);
608 // FIXME: hardcoding !!!
609 XDB
::execute('UPDATE payment_transactions SET recon_id = NULL,commission = NULL WHERE recon_id = {?} AND method_id = 2', $param);
610 XDB
::execute('UPDATE payment_transactions SET recon_id = NULL WHERE recon_id = {?} AND method_id = 1', $param);
611 $page->trigSuccess("L'entrée " . $param . ' a été supprimée.');
613 } elseif ($step == 'edit') {
614 $page->trigError("L'édition n'est pas implémentée.");
616 } elseif ($step == 'step5') {
617 $page->trigSuccess("La réconciliation est terminée. Il est maintenant nécessaire de générer les virements.");
622 // show list of reconciliations, with a "add" button
623 $page->assign('title', 'Réconciliation - Liste');
624 $page->assign('step', 'list');
628 $res = XDB
::query("SELECT r.id, short_name AS method, period_start, period_end, status,
629 payment_count, sum_amounts, sum_commissions
630 FROM payment_reconcilations AS r
631 LEFT JOIN payment_methods AS m ON (r.method_id = m.id)
632 WHERE recongroup_id IS NULL
633 ORDER BY period_end DESC, period_start DESC");
634 foreach ($res->fetchAllAssoc() as $recon)
635 $recongps[] = array('recons' => array($recon), 'transfers' => array());
637 $res = XDB
::query("SELECT recongroup_id AS id
638 FROM payment_reconcilations
639 GROUP BY recongroup_id
640 ORDER BY MAX(period_end) DESC, MIN(period_start) DESC");
641 foreach ($res->fetchAllAssoc() as $recongp) {
642 $res = XDB
::query("SELECT r.id, short_name AS method, period_start, period_end, status,
643 payment_count, sum_amounts, sum_commissions
644 FROM payment_reconcilations AS r
645 LEFT JOIN payment_methods AS m ON (r.method_id = m.id)
646 WHERE recongroup_id = {?}
647 ORDER BY period_end DESC, period_start DESC",
649 $recongp['recons'] = $res->fetchAllAssoc();
651 $res = XDB
::query('SELECT id, payment_id, amount, account_id, message, date
652 FROM payment_transfers
653 WHERE recongroup_id = {?}',
655 $recongp['transfers'] = $res->fetchAllAssoc();
657 $recongps[] = $recongp;
659 $page->assign_by_ref('recongps', $recongps);
663 function handler_adm_importlogs($page, $step, $param = null
) {
664 $page->setTitle('Administration - Paiements - Réconciliations');
665 $page->changeTpl('payment/reconcile.tpl');
666 $page->assign('step', $step);
668 if (isset($_SESSION['paymentrecon_data'])) {
669 // create temporary table with imported data
670 XDB
::execute('CREATE TEMPORARY TABLE payment_tmp (
671 reference VARCHAR(255) PRIMARY KEY,
674 commission DECIMAL(9,2)
676 foreach ($_SESSION['paymentrecon_data'] as $i)
677 XDB
::execute('INSERT INTO payment_tmp VALUES ({?}, {?}, {?}, {?})',
678 $i['reference'], $i['date'], $i['amount'], $i['commission']);
681 if ($step == 'step1') {
682 $page->assign('title', 'Étape 1');
683 unset($_SESSION['paymentrecon_method']);
684 unset($_SESSION['paymentrecon_data']);
685 unset($_SESSION['paymentrecon_id']);
687 // was a payment method choosen ?
688 if ($param != null
) {
689 $_SESSION['paymentrecon_method'] = (int)$param;
690 pl_redirect('admin/reconcile/importlogs/step2');
693 // ask to choose a payment method
694 $res = XDB
::query('SELECT id, text FROM payment_methods');
695 $page->assign('methods', $res->fetchAllAssoc());
698 } elseif ( $step == 'step2' ) {
699 $page->assign('title', 'Étape 2');
701 // import logs formated in CVS
702 $fields = array('date', 'reference', 'amount', 'commission');
703 $importer = new PaymentLogsImporter();
704 $importer->apply($page, 'admin/reconcile/importlogs/step2', $fields);
706 // if import is finished
707 $result = $importer->get_result();
708 if($result != null
) {
709 $_SESSION['paymentrecon_data'] = $result;
710 pl_redirect('admin/reconcile/importlogs/step3');
713 } elseif ($step == 'step3' ) {
714 $page->assign('title', 'Étape 3');
716 // compute reconcilation summary data
717 $res = XDB
::query('SELECT MIN(date) AS period_start, MAX(date) AS period_end,
718 count(*) AS payment_count, SUM(amount) AS sum_amounts,
719 SUM(commission) AS sum_commissions
721 $recon = $res->fetchOneAssoc();
722 $recon['method_id'] = $_SESSION['paymentrecon_method'];
724 // create reconciliation item in database
725 if(Post
::has('next')) {
726 S
::assert_xsrf_token();
729 $recon['period_start'] = preg_replace('/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/', '\3-\2-\1', Post
::v('period_start'));
730 $recon['period_end'] = preg_replace('/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/', '\3-\2-\1', Post
::v('period_end'));
731 // FIXME: save checks to be done at next step
733 // Create reconcilation item in database
734 // FIXME: check if period doesn't overlap with others for the same method_id
735 XDB
::execute('INSERT INTO payment_reconcilations (method_id, period_start, period_end,
736 payment_count, sum_amounts, sum_commissions)
737 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
738 $recon['method_id'], $recon['period_start'], $recon['period_end'],
739 $recon['payment_count'], $recon['sum_amounts'], $recon['sum_commissions']);
740 $_SESSION['paymentrecon_id'] = XDB
::insertId();
742 // reconcile simple cases (trans.commission n'est modifié que s'il vaut NULL)
743 XDB
::execute("UPDATE payment_transactions AS trans, payment_tmp AS tmp
744 SET trans.recon_id = {?}, trans.commission=tmp.commission
745 WHERE trans.fullref = tmp.reference
746 AND trans.amount = tmp.amount AND DATE(trans.ts_confirmed) = tmp.date
747 AND (trans.commission IS NULL OR trans.commission = tmp.commission)
748 AND method_id = {?} AND recon_id IS NULL AND status = 'confirmed'",
749 $_SESSION['paymentrecon_id'], $recon['method_id']);
751 pl_redirect("admin/reconcile/importlogs/step4");
753 // show summary of the imported data + ask form start/end of reconcilation period
755 $recon['period_start'] = preg_replace('/([0-9]{4})-([0-9]{2})-([0-9]{2})/', '\3/\2/\1', $recon['period_start']);
756 $recon['period_end'] = preg_replace('/([0-9]{4})-([0-9]{2})-([0-9]{2})/', '\3/\2/\1', $recon['period_end']);
757 $page->assign('recon', $recon);
760 } elseif ($step == 'step4' ) {
761 $page->assign('title', 'Étape 4');
763 // get reconcilation summary informations
764 $res = XDB
::query('SELECT * FROM payment_reconcilations WHERE id = {?}', $_SESSION['paymentrecon_id']);
765 $recon = $res->fetchOneAssoc();
766 $page->assign('recon', $recon);
768 if (Post
::has('force')) {
769 S
::assert_xsrf_token();
770 foreach (Post
::v('force') as $id => $value) {
771 XDB
::execute('UPDATE payment_transactions AS trans, payment_tmp AS tmp
772 SET trans.recon_id = {?}, trans.commission = tmp.commission
773 WHERE trans.id = {?} AND trans.fullref = tmp.reference',
774 $_SESSION['paymentrecon_id'], $id);
776 $page->trigSuccess('La réconciliation a été forcée pour ' . count(Post
::v('force')) . ' transaction(s).');
778 } elseif (Post
::has('next')) {
779 if (strlen($recon['comments'])< 3 ) {
780 $page->trigError('Le commentaire doit contenir au moins 3 caractères.');
782 XDB
::execute("UPDATE payment_reconcilations SET status = 'transfering' WHERE id = {?}", $_SESSION['paymentrecon_id']);
783 pl_redirect('admin/reconcile/step5');
786 } elseif (Post
::has('savecomments')) {
787 S
::assert_xsrf_token();
788 $recon['comments'] = Post
::v('comments');
789 $page->assign('recon', $recon);
790 XDB
::execute('UPDATE payment_reconcilations SET comments = {?} WHERE id = {?}', $recon['comments'], $_SESSION['paymentrecon_id']);
791 $page->trigSuccess('Les commentaires ont été enregistrés.');
794 // reconcilation results - ok
795 $res = XDB
::query('SELECT count(*), SUM(amount), SUM(commission)
796 FROM payment_transactions
797 WHERE recon_id = {?}',
799 list($ok_count, $ok_sum_amounts, $ok_sum_coms) = $res->fetchOneRow();
800 $page->assign('ok_count', $ok_count);
802 // reconcilation results - ref exists, but some data differs
803 $res = XDB
::query('SELECT id, fullref, method_id, ts_confirmed, trans.amount, trans.commission, status, recon_id,
804 reference, date, tmp.amount as amount2, tmp.commission as commission2
805 FROM payment_transactions AS trans
806 INNER JOIN payment_tmp AS tmp ON (trans.fullref = tmp.reference)
807 WHERE trans.recon_id IS NULL OR trans.recon_id != {?}',
809 $differs = $res->fetchAllAssoc();
810 $page->assign_by_ref('differs', $differs);
811 $page->assign('differ_count', count($differs));
813 // reconcilation results - ref doesn't exists in database
814 $res = XDB
::query('SELECT tmp.*
815 FROM payment_tmp AS tmp
816 LEFT JOIN payment_transactions AS trans ON (trans.fullref = tmp.reference)
817 WHERE trans.fullref IS NULL');
818 $only_import = $res->fetchAllAssoc();
819 $page->assign_by_ref('only_import', $only_import);
820 $page->assign('onlyim_count', count($only_import));
822 // reconcilation results - exists in database but not in import
823 $res = XDB
::query('SELECT trans.*
824 FROM payment_transactions AS trans
825 LEFT JOIN payment_tmp AS tmp ON (trans.fullref = tmp.reference)
826 WHERE {?} <= DATE(trans.ts_confirmed) AND DATE(trans.ts_confirmed) <= {?}
827 AND tmp.reference IS NULL AND method_id = {?}',
828 $recon['period_start'], $recon['period_end'], $recon['method_id']);
829 $only_database = $res->fetchAllAssoc();
830 $page->assign_by_ref('only_database', $only_database);
831 $page->assign('onlydb_count', count($only_database));
835 function handler_adm_transfers($page, $action = null
, $id = null
) {
836 // list/log all bank transfers and link them to individual transactions
838 if (Post
::has('generate')) {
839 $recon_ids = array_keys(Post
::v('recon_id'));
841 // generate a new reconcilation group ID
842 $res = XDB
::query("SELECT MAX(recongroup_id)+1 FROM payment_reconcilations");
843 $recongp_id = $res->fetchOneCell();
844 if ($recongp_id == null
) $recongp_id = 1;
846 // add reconcilations to group
847 // FIXME: should check if reconcilations are in good status
848 XDB
::execute("UPDATE payment_reconcilations
849 SET recongroup_id = {?}, status = 'closed'
851 $recongp_id, $recon_ids);
854 XDB
::execute('INSERT INTO payment_transfers
855 SELECT NULL, {?}, t.ref, SUM(t.amount+t.commission), NULL, p.text, NULL
856 FROM payment_transactions AS t
857 LEFT JOIN payments AS p ON (t.ref = p.id)
858 LEFT JOIN groups AS g ON (p.asso_id = g.id)
859 WHERE t.recon_id IN {?}
861 $recongp_id, $recon_ids);
863 //$res = XDB::query("SELECT * FROM payment_reconcilations WHERE id IN {?}", $recon_ids);
864 //$recons = $res->fetchAllAssoc();
866 $page->trigSuccess('Les virements ont été générés pour ' . count($recon_ids) . ' réconciliations.');
867 $this->handler_adm_reconcile($page);
869 } elseif ($action == 'delgroup') {
870 S
::assert_xsrf_token();
871 XDB
::execute("UPDATE payment_reconcilations
872 SET status = 'transfering', recongroup_id = NULL
873 WHERE recongroup_id = {?}", $id);
874 XDB
::execute("DELETE FROM payment_transfers
875 WHERE recongroup_id = {?} AND date IS NULL", $id);
877 $page->trigSuccess("Les virements non réalisés ont été supprimé du groupe ".$id.".");
878 $this->handler_adm_reconcile($page);
880 } elseif ($action == "confirm") {
881 S
::assert_xsrf_token();
882 XDB
::execute('UPDATE payment_transfers
884 WHERE id = {?}', $id);
886 $page->trigSuccess('Virement ' . $id . ' confirmé.');
887 $this->handler_adm_reconcile($page);
890 pl_redirect('admin/reconcile');
895 class PaymentLogsImporter
extends CSVImporter
{
898 public function __construct() {
899 parent
::__construct('');
900 $this->registerFunction('systempay_commission', 'Compute BPLC commission', array($this, 'compute_systempay_commission'));
901 $this->registerFunction('payment_id', 'Autocompute payment ID', array($this, 'compute_payment_id'));
902 //$this->forceValue('payment_id','func_payment_id');
905 public function run($action = null
, $insert_relation = null
, $update_relation = null
) {
906 $this->result
= array();
907 foreach ($this->data
as $line) {
908 $a = $this->makeAssoc($line, $insert_relation);
909 $a['date'] = preg_replace('/([0-9]{2})\/([0-9]{2})\/([0-9]{4}).*/', '\3-\2-\1', $a['date']);
910 $a['amount'] = str_replace(',', '.', $a['amount']);
911 $a['commission'] = str_replace(',', '.', $a['commission']);
912 $this->result
[] = $a;
916 public function get_result() {
917 return $this->result
;
920 static public function compute_systempay_commission($line, $key, $relation) {
921 static $EEE_countries = array(
922 'France', 'Allemagne', 'Autriche', 'Belgique', 'Bulgarie', 'Chypre',
923 'Danemark', 'Espagne', 'Estonie', 'Finlande', 'Grèce', 'Hongrie', 'Irlande', 'Islande', 'Italie',
924 'Lettonie', 'Liechtenstein', 'Lituanie', 'Luxembourg', 'Malte', 'Norvège', 'Pays-Bas', 'Pologne',
925 'Portugal', 'Roumanie', 'Royaume-Uni', 'Slovaquie', 'Slovénie', 'Suède', 'République Tchèque'
928 if($key!='commission' ||
!array_key_exists('carte', $line)) {
931 $amount = self
::getValue($line, 'amount', $relation['amount']);
932 if (in_array($line['pays carte'], $EEE_countries)) {
933 return -0.20 - round($amount * 0.005, 2);
935 return -0.20 - round($amount * 0.005, 2) - 0.76;
939 static public function compute_payment_id($line, $key, $relation) {
940 if ($key != 'payment_id') {
943 $reference = self
::getValue($line, 'reference', $relation['reference']);
944 if (ereg('-([0-9]+)$', $reference, $matches)) {
952 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: