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());
185 $page->assign('donation', $pay->flags
->hasflag('donation'));
188 function handler_cyber2_return($page, $uid = null
)
190 global $globals, $platal;
192 /* on vérifie la signature */
193 $vads_params = array();
194 foreach($_REQUEST as $key => $value)
195 if(substr($key,0,5) == 'vads_') {
196 $vads_params[$key] = $value;
199 $signature = sha1(join('+', $vads_params) . '+' . $globals->money
->cyperplus_key
);
200 //if($signature != Env::v('signature')) {
201 // cb_erreur("signature invalide");
204 /* on extrait les informations sur l'utilisateur */
205 $user = User
::get(Env
::i('vads_cust_id'));
207 cb_erreur("uid invalide");
210 /* on extrait la reference de la commande */
211 if (!ereg('-([0-9]+)$', Env
::v('vads_order_id'), $matches)) {
212 cb_erreur("référence de commande invalide");
216 $res = XDB
::query('SELECT mail, text, confirmation
218 WHERE id={?}', $ref);
219 if ($res->numRows() != 1) {
220 cb_erreur("référence de commande inconnue");
222 list($conf_mail, $conf_title, $conf_text) = $res->fetchOneRow();
224 /* on extrait le montant */
225 if (Env
::v('vads_currency') != '978') {
226 cb_erreur("monnaie autre que l'euro");
228 $amount = ((float)Env
::i('vads_amount')) / 100;
229 $montant = sprintf("%.02f EUR", $amount);
231 /* on extrait le code de retour */
232 if (Env
::v('vads_result') != '00') {
233 cb_erreur('erreur lors du paiement : ?? (' . Env
::v('vads_result') . ')');
236 /* on fait l'insertion en base de donnees */
237 XDB
::execute('INSERT INTO payment_transactions (id, uid, ref, fullref, amount, pkey, comment, display)
238 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
239 Env
::v('vads_trans_date'), $user->id(), $ref, Env
::v('vads_order_id'), $montant, '', Env
::v('vads_order_info'), Env
::i('vads_order_info2'));
240 echo "Paiement stored.\n";
242 // We check if it is an Xnet payment and then update the related ML.
243 $res = XDB
::query('SELECT eid, asso_id
245 WHERE paiement_id = {?}', $ref);
246 if ($res->numRows() == 1) {
247 list($eid, $asso_id) = $res->fetchOneRow();
248 require_once dirname(__FILE__
) . '/xnetevents/xnetevents.inc.php';
249 $evt = get_event_detail($eid, false
, $asso_id);
250 subscribe_lists_event($user->id(), $evt['short_name'], 1, $amount, true
);
253 /* on genere le mail de confirmation */
254 $conf_text = str_replace(
255 array('<prenom>', '<nom>', '<promo>', '<montant>', '<salutation>', '<cher>', '<comment>'),
256 array($user->firstName(), $user->lastName(), $user->promo(), $montant,
257 $user->isFemale() ?
'Chère' : 'Cher', $user->isFemale() ?
'Chère' : 'Cher',
258 Env
::v('vads_order_info')), $conf_text);
261 $mymail = new PlMailer();
262 $mymail->setFrom($conf_mail);
263 $mymail->addCc($conf_mail);
264 $mymail->setSubject($conf_title);
265 $mymail->setWikiBody($conf_text);
266 $mymail->sendTo($user);
268 /* on envoie les details de la transaction à telepaiement@ */
269 $mymail = new PlMailer();
270 $mymail->setFrom("webmaster@" . $globals->mail
->domain
);
271 $mymail->addTo($globals->money
->email
);
272 $mymail->setSubject($conf_title);
273 $msg = 'utilisateur : ' . $user->login() . ' (' . $user->id() . ')' . "\n" .
274 'mail : ' . $user->forlifeEmail() . "\n\n" .
275 "paiement : $conf_title ($conf_mail)\n".
276 "reference : " . Env
::v('vads_order_id') . "\n".
277 "montant : $montant\n\n".
278 "dump de REQUEST:\n".
279 var_export($_REQUEST,true
);
280 $mymail->setTxtBody($msg);
282 echo "Notifications sent.\n";
286 function handler_paypal_return($page, $uid = null
)
288 $page->changeTpl('payment/retour_paypal.tpl');
290 /* reference banque (numero de transaction) */
291 $no_transaction = Env
::s('tx');
292 /* token a renvoyer pour avoir plus d'information */
293 $clef = Env
::s('sig');
295 $status = Env
::s('st');
297 $reason = ($status == 'Pending') ? Env
::s('pending_reason') : Env
::s('reason_code');
298 /* reference complete de la commande */
299 $fullref = Env
::s('cm');
300 /* montant de la transaction */
301 $montant_nb = Env
::s('amt');
303 $montant_dev = Env
::s('cc');
304 $montant = "$montant_nb $montant_dev";
306 /* on extrait le code de retour */
307 if ($status != "Completed") {
309 paypal_erreur("erreur lors du paiement : $status - $reason");
311 paypal_erreur("Paiement annulé", false
);
315 /* on extrait les informations sur l'utilisateur */
316 $user = User
::get($uid);
318 paypal_erreur("uid invalide");
321 /* on extrait la reference de la commande */
322 if (!ereg('-xorg-([0-9]+)$', $fullref, $matches)) {
323 paypal_erreur("référence de commande invalide");
327 $res = XDB
::query('SELECT mail, text, confirmation
329 WHERE id = {?}', $ref);
330 if (!list($conf_mail, $conf_title, $conf_text) = $res->fetchOneRow()) {
331 paypal_erreur('référence de commande inconnue');
334 /* on fait l'insertion en base de donnees */
335 XDB
::execute("INSERT INTO payment_transactions (id, uid, ref, fullref, amount, pkey, comment, display)
336 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, '?})",
337 $no_transaction, $user->id(), $ref, $fullref, $montant, $clef, Env
::v('comment'), Get
::i('display'));
339 // We check if it is an Xnet payment and then update the related ML.
340 $res = XDB
::query('SELECT eid
342 WHERE paiement_id = {?}', $ref);
343 if ($eid = $res->fetchOneCell()) {
344 require_once dirname(__FILE__
) . '/xnetevents/xnetevents.inc.php';
345 $evt = get_event_detail($eid);
346 subscribe_lists_event($user->id(), $evt['short_name'], 1, $montant, true
);
349 /* on genere le mail de confirmation */
350 $conf_text = str_replace(array('<prenom>', '<nom>', '<promo>', '<montant>', '<salutation>', '<cher>', '<comment>'),
351 array($user->firstName(), $user->lastName(), $user->promo(), $montant,
352 $user->isFemale() ?
'Chère' : 'Cher', $user->isFemale() ?
'Chère' : 'Cher',
353 Env
::v('comment')), $conf_text);
356 $mymail = new PlMailer();
357 $mymail->setFrom($conf_mail);
358 $mymail->addCc($conf_mail);
359 $mymail->setSubject($conf_title);
360 $mymail->setWikiBody($conf_text);
361 $mymail->sendTo($user);
363 /* on envoie les details de la transaction à telepaiement@ */
364 $mymail = new PlMailer();
365 $mymail->setFrom("webmaster@" . $globals->mail
->domain
);
366 $mymail->addTo($globals->money
->email
);
367 $mymail->setSubject($conf_title);
368 $msg = 'utilisateur : ' . $user->login() . ' (' . $user->id() . ')' . "\n" .
369 'mail : ' . $user->forlifeEmail() . "\n\n" .
370 "paiement : $conf_title ($conf_mail)\n".
371 "reference : $champ200\n".
372 "montant : $montant\n\n".
373 "dump de REQUEST:\n".
374 var_export($_REQUEST,true
);
375 $mymail->setTxtBody($msg);
378 $page->assign('texte', $conf_text);
379 $page->assign('erreur', $erreur);
382 function handler_xnet_payment($page, $pid = null
)
386 $perms = S
::v('perms');
387 if (!$perms->hasFlag('groupmember')) {
391 $res = XDB
::query("SELECT 1
392 FROM group_events AS e
393 INNER JOIN group_event_participants AS ep ON (ep.eid = e.eid AND e.uid = {?})
394 WHERE e.paiement_id = {?} AND e.asso_id = {?}",
395 S
::i('uid'), $pid, $globals->asso('id'));
396 if ($res->numRows() == 0) {
401 if (!is_null($pid)) {
402 return $this->handler_payment($page, $pid);
404 $page->changeTpl('payment/xnet.tpl');
407 "SELECT id, text, url
409 WHERE asso_id = {?} AND NOT FIND_IN_SET('old', flags)
410 ORDER BY id DESC", $globals->asso('id'));
411 $tit = $res->fetchAllAssoc();
412 $page->assign('titles', $tit);
417 static $orders = array('timestamp' => 'p', 'directory_name' => 'a', 'promo' => 'pd', 'comment' => 'p', 'amount' => 'p');
419 if (Get
::has('order_id') && Get
::has('order') && array_key_exists(Get
::v('order'), $orders)) {
420 $order_id = Get
::i('order_id');
421 $order = Get
::v('order');
422 $ordering = ' ORDER BY ' . $orders[$order] . '.' . $order;
423 if (Get
::has('order_inv') && Get
::i('order_inv') == 1) {
424 $ordering .= ' DESC';
425 $page->assign('order_inv', 0);
427 $page->assign('order_inv', 1);
429 $page->assign('order_id', $order_id);
430 $page->assign('order', $order);
431 $page->assign('anchor', 'legend_' . $order_id);
435 $page->assign('order', false
);
439 $page->assign('order', false
);
441 foreach($tit as $foo) {
444 $res = XDB
::query('SELECT p.uid, IF(p.timestamp = \'0000-00-00\', 0, p.timestamp) AS date, p.comment, p.amount
445 FROM payment_transactions AS p
446 INNER JOIN accounts AS a ON (a.uid = p.uid)
447 LEFT JOIN account_profiles AS ap ON (ap.uid = p.uid AND FIND_IN_SET(\'owner\', ap.perms))
448 LEFT JOIN profile_display AS pd ON (ap.pid = pd.pid)
449 WHERE p.ref = {?}' . (($order_id == $pid) ?
$ordering : ''),
451 $trans[$pid] = User
::getBulkUsersWithUIDs($res->fetchAllAssoc(), 'uid', 'user');
453 foreach ($trans[$pid] as $i => $t) {
454 $sum +
= strtr(substr($t['amount'], 0, strpos($t['amount'], 'EUR')), ',', '.');
455 $trans[$pid][$i]['amount'] = str_replace('EUR', '€', $t['amount']);
457 $trans[$pid][] = array('limit' => true
,
458 'amount' => strtr($sum, '.', ',') . ' €');
460 $res = XDB
::iterRow("SELECT e.eid, e.short_name, e.intitule, ep.nb, ei.montant, ep.paid
461 FROM group_events AS e
462 LEFT JOIN group_event_participants AS ep ON (ep.eid = e.eid AND ep.uid = {?})
463 INNER JOIN group_event_items AS ei ON (ep.eid = ei.eid AND ep.item_id = ei.item_id)
464 WHERE e.paiement_id = {?}",
466 $event[$pid] = array();
467 $event[$pid]['paid'] = 0;
469 $event[$pid]['topay'] = 0;
470 while(list($eid, $shortname, $title, $nb, $montant, $paid) = $res->next()) {
471 $event[$pid]['topay'] +
= ($nb * $montant);
472 $event[$pid]['eid'] = $eid;
473 $event[$pid]['shortname'] = $shortname;
474 $event[$pid]['title'] = $title;
475 $event[$pid]['ins'] = !is_null($nb);
476 $event[$pid]['paid'] = $paid;
479 $res = XDB
::query('SELECT amount
480 FROM payment_transactions
481 WHERE id = {?} AND uid = {?}', $pid, S
::v('uid'));
482 $montants = $res->fetchColumn();
484 foreach ($montants as $m) {
485 $p = strtr(substr($m, 0, strpos($m, 'EUR')), ',', '.');
486 $event[$pid]['paid'] +
= trim($p);
489 $page->register_modifier('decode_comment', 'decode_comment');
490 $page->assign('trans', $trans);
491 $page->assign('event', $event);
494 function handler_payment_csv($page, $pid = null
)
497 pl_redirect('payment');
499 if (substr($pid, -4) == '.vcf') {
500 $pid = substr($pid, 0, strlen($pid) - 4);
503 $res = XDB
::fetchAllAssoc('SELECT uid, IF(timestamp = \'0000-00-00\', 0, timestamp) AS date, comment, amount
504 FROM payment_transactions
509 pl_redirect('payment');
512 $users = User
::getBulkUsersWithUIDs($res, 'uid', 'user');
515 pl_cached_content_headers('text/x-csv', 1);
516 $csv = fopen('php://output', 'w');
517 fputcsv($csv, array('Date', 'Nom', 'Prénom', 'Sexe', 'Promotion', 'Email', 'Commentaire', 'Montant'), ';');
518 foreach ($users as $item) {
519 $user = $item['user'];
520 $sum +
= strtr(substr($item['amount'], 0, strpos($item['amount'], 'EUR')), ',', '.');
521 fputcsv($csv, array(format_datetime($item['date'], '%d/%m/%y'), $user->lastName(), $user->firstName(),
522 ($user->isFemale()) ?
'F' : 'M', $user->promo(), $user->ForlifeEmail(),
523 $item['comment'], str_replace('EUR', '€', $item['amount'])), ';');
525 fputcsv($csv, array(date('d/m/y'), 'Total', '', '', '' , '', '', strtr($sum, '.', ',') . ' €'), ';');
531 function handler_admin($page, $action = 'list', $id = null
) {
532 $page->setTitle('Administration - Paiements');
533 $page->assign('title', 'Gestion des télépaiements');
534 $table_editor = new PLTableEditor('admin/payments','payments','id');
535 //$table_editor->add_join_table('payment_transactions','ref',true); => on ne supprime jamais une transaction
536 $table_editor->add_sort_field('flags');
537 $table_editor->add_sort_field('id', true
, true
);
538 $table_editor->on_delete("UPDATE payments SET flags = 'old' WHERE id = {?}", "Le paiement a été archivé");
539 $table_editor->describe('text', 'intitulé', true
);
540 $table_editor->describe('url', 'site web', false
);
541 $table_editor->describe('amount_def', 'montant par défaut', false
);
542 $table_editor->describe('amount_min', 'montant minimum', false
);
543 $table_editor->describe('amount_max', 'montant maximum', false
);
544 $table_editor->describe('mail', 'email contact', true
);
545 $table_editor->describe('confirmation', 'message confirmation', false
);
547 // adds a column with the start date of the linked event if there is one
548 $table_editor->add_option_table('group_events', 'group_events.paiement_id = t.id');
549 $table_editor->add_option_field('group_events.debut', 'related_event', 'évènement', 'timestamp');
551 $table_editor->apply($page, $action, $id);
554 function handler_adm_transactions($page, $payment_id = null
, $action = "list", $id = null
) {
555 // show transactions. FIXME: should not be modifiable
556 $page->setTitle('Administration - Paiements - Transactions');
557 $page->assign('title', "Liste des transactions pour le paiement {$payment_id}");
559 if ($payment_id == null
)
560 $page->trigError("Aucun ID de paiement fourni.");
562 $table_editor = new PLTableEditor("admin/transactions/{$payment_id}",'payment_transactions','id');
563 $table_editor->set_where_clause(XDB
::format('ref = {?}', $payment_id));
564 $table_editor->apply($page, 'list', $id); // only the 'list' action is allowed
565 $page->assign('readonly', 'readonly'); // don't show modification features
568 function handler_adm_bankaccounts($page, $action = "list", $id = null
) {
569 // managment of bank account used for money transfert
570 $page->setTitle('Administration - Paiements - RIBs');
571 $page->assign('title', "Liste des RIBs");
573 $table_editor = new PLTableEditor('admin/payments/bankaccounts', 'payment_bankaccounts', 'id');
574 $table_editor->describe('asso_id', 'ID du groupe', false
);
575 $table_editor->describe('owner', 'titulaire', true
);
576 $table_editor->add_option_table('groups', 'groups.id = t.asso_id');
577 $table_editor->add_option_field('groups.diminutif', 'group_name', 'groupe', 'varchar','account');
580 if ($action == 'update' && Post
::has('account') && !check_rib(Post
::v('account'))) {
581 $page->trigError("Le RIB n'est pas valide");
582 $table_editor->apply($page, 'edit', $id);
586 $table_editor->apply($page, $action, $id);
589 function handler_adm_methods($page, $action = "list", $id = null
) {
590 // show and edit payment methods
591 $page->setTitle('Administration - Paiements - Méthodes');
592 $page->assign('title', 'Méthodes de paiement');
593 $table_editor = new PLTableEditor('admin/payments/methods', 'payment_methods', 'id');
594 $table_editor->apply($page, $action, $id);
597 function handler_adm_reconcile($page, $step = 'list', $param = null
) {
598 // reconciles logs with transactions
599 // FIXME: the admin is considered to be fair => he doesn't hack the $step value, nor other params
600 $page->setTitle('Administration - Paiements - Réconciliations');
601 $page->changeTpl('payment/reconcile.tpl');
602 $page->assign('step', $step);
606 if ($step == 'delete' && $param != null
) {
607 S
::assert_xsrf_token();
608 XDB
::execute('DELETE FROM payment_reconcilations WHERE id = {?}', $param);
609 // FIXME: hardcoding !!!
610 XDB
::execute('UPDATE payment_transactions SET recon_id = NULL,commission = NULL WHERE recon_id = {?} AND method_id = 2', $param);
611 XDB
::execute('UPDATE payment_transactions SET recon_id = NULL WHERE recon_id = {?} AND method_id = 1', $param);
612 $page->trigSuccess("L'entrée " . $param . ' a été supprimée.');
614 } elseif ($step == 'edit') {
615 $page->trigError("L'édition n'est pas implémentée.");
617 } elseif ($step == 'step5') {
618 $page->trigSuccess("La réconciliation est terminée. Il est maintenant nécessaire de générer les virements.");
623 // show list of reconciliations, with a "add" button
624 $page->assign('title', 'Réconciliation - Liste');
625 $page->assign('step', 'list');
629 $res = XDB
::query("SELECT r.id, short_name AS method, period_start, period_end, status,
630 payment_count, sum_amounts, sum_commissions
631 FROM payment_reconcilations AS r
632 LEFT JOIN payment_methods AS m ON (r.method_id = m.id)
633 WHERE recongroup_id IS NULL
634 ORDER BY period_end DESC, period_start DESC");
635 foreach ($res->fetchAllAssoc() as $recon)
636 $recongps[] = array('recons' => array($recon), 'transfers' => array());
638 $res = XDB
::query("SELECT recongroup_id AS id
639 FROM payment_reconcilations
640 GROUP BY recongroup_id
641 ORDER BY MAX(period_end) DESC, MIN(period_start) DESC");
642 foreach ($res->fetchAllAssoc() as $recongp) {
643 $res = XDB
::query("SELECT r.id, short_name AS method, period_start, period_end, status,
644 payment_count, sum_amounts, sum_commissions
645 FROM payment_reconcilations AS r
646 LEFT JOIN payment_methods AS m ON (r.method_id = m.id)
647 WHERE recongroup_id = {?}
648 ORDER BY period_end DESC, period_start DESC",
650 $recongp['recons'] = $res->fetchAllAssoc();
652 $res = XDB
::query('SELECT id, payment_id, amount, account_id, message, date
653 FROM payment_transfers
654 WHERE recongroup_id = {?}',
656 $recongp['transfers'] = $res->fetchAllAssoc();
658 $recongps[] = $recongp;
660 $page->assign_by_ref('recongps', $recongps);
664 function handler_adm_importlogs($page, $step, $param = null
) {
665 $page->setTitle('Administration - Paiements - Réconciliations');
666 $page->changeTpl('payment/reconcile.tpl');
667 $page->assign('step', $step);
669 if (isset($_SESSION['paymentrecon_data'])) {
670 // create temporary table with imported data
671 XDB
::execute('CREATE TEMPORARY TABLE payment_tmp (
672 reference VARCHAR(255) PRIMARY KEY,
675 commission DECIMAL(9,2)
677 foreach ($_SESSION['paymentrecon_data'] as $i)
678 XDB
::execute('INSERT INTO payment_tmp VALUES ({?}, {?}, {?}, {?})',
679 $i['reference'], $i['date'], $i['amount'], $i['commission']);
682 if ($step == 'step1') {
683 $page->assign('title', 'Étape 1');
684 unset($_SESSION['paymentrecon_method']);
685 unset($_SESSION['paymentrecon_data']);
686 unset($_SESSION['paymentrecon_id']);
688 // was a payment method choosen ?
689 if ($param != null
) {
690 $_SESSION['paymentrecon_method'] = (int)$param;
691 pl_redirect('admin/reconcile/importlogs/step2');
694 // ask to choose a payment method
695 $res = XDB
::query('SELECT id, text FROM payment_methods');
696 $page->assign('methods', $res->fetchAllAssoc());
699 } elseif ( $step == 'step2' ) {
700 $page->assign('title', 'Étape 2');
702 // import logs formated in CVS
703 $fields = array('date', 'reference', 'amount', 'commission');
704 $importer = new PaymentLogsImporter();
705 $importer->apply($page, 'admin/reconcile/importlogs/step2', $fields);
707 // if import is finished
708 $result = $importer->get_result();
709 if($result != null
) {
710 $_SESSION['paymentrecon_data'] = $result;
711 pl_redirect('admin/reconcile/importlogs/step3');
714 } elseif ($step == 'step3' ) {
715 $page->assign('title', 'Étape 3');
717 // compute reconcilation summary data
718 $res = XDB
::query('SELECT MIN(date) AS period_start, MAX(date) AS period_end,
719 count(*) AS payment_count, SUM(amount) AS sum_amounts,
720 SUM(commission) AS sum_commissions
722 $recon = $res->fetchOneAssoc();
723 $recon['method_id'] = $_SESSION['paymentrecon_method'];
725 // create reconciliation item in database
726 if(Post
::has('next')) {
727 S
::assert_xsrf_token();
730 $recon['period_start'] = preg_replace('/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/', '\3-\2-\1', Post
::v('period_start'));
731 $recon['period_end'] = preg_replace('/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/', '\3-\2-\1', Post
::v('period_end'));
732 // FIXME: save checks to be done at next step
734 // Create reconcilation item in database
735 // FIXME: check if period doesn't overlap with others for the same method_id
736 XDB
::execute('INSERT INTO payment_reconcilations (method_id, period_start, period_end,
737 payment_count, sum_amounts, sum_commissions)
738 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
739 $recon['method_id'], $recon['period_start'], $recon['period_end'],
740 $recon['payment_count'], $recon['sum_amounts'], $recon['sum_commissions']);
741 $_SESSION['paymentrecon_id'] = XDB
::insertId();
743 // reconcile simple cases (trans.commission n'est modifié que s'il vaut NULL)
744 XDB
::execute("UPDATE payment_transactions AS trans, payment_tmp AS tmp
745 SET trans.recon_id = {?}, trans.commission=tmp.commission
746 WHERE trans.fullref = tmp.reference
747 AND trans.amount = tmp.amount AND DATE(trans.ts_confirmed) = tmp.date
748 AND (trans.commission IS NULL OR trans.commission = tmp.commission)
749 AND method_id = {?} AND recon_id IS NULL AND status = 'confirmed'",
750 $_SESSION['paymentrecon_id'], $recon['method_id']);
752 pl_redirect("admin/reconcile/importlogs/step4");
754 // show summary of the imported data + ask form start/end of reconcilation period
756 $recon['period_start'] = preg_replace('/([0-9]{4})-([0-9]{2})-([0-9]{2})/', '\3/\2/\1', $recon['period_start']);
757 $recon['period_end'] = preg_replace('/([0-9]{4})-([0-9]{2})-([0-9]{2})/', '\3/\2/\1', $recon['period_end']);
758 $page->assign('recon', $recon);
761 } elseif ($step == 'step4' ) {
762 $page->assign('title', 'Étape 4');
764 // get reconcilation summary informations
765 $res = XDB
::query('SELECT * FROM payment_reconcilations WHERE id = {?}', $_SESSION['paymentrecon_id']);
766 $recon = $res->fetchOneAssoc();
767 $page->assign('recon', $recon);
769 if (Post
::has('force')) {
770 S
::assert_xsrf_token();
771 foreach (Post
::v('force') as $id => $value) {
772 XDB
::execute('UPDATE payment_transactions AS trans, payment_tmp AS tmp
773 SET trans.recon_id = {?}, trans.commission = tmp.commission
774 WHERE trans.id = {?} AND trans.fullref = tmp.reference',
775 $_SESSION['paymentrecon_id'], $id);
777 $page->trigSuccess('La réconciliation a été forcée pour ' . count(Post
::v('force')) . ' transaction(s).');
779 } elseif (Post
::has('next')) {
780 if (strlen($recon['comments'])< 3 ) {
781 $page->trigError('Le commentaire doit contenir au moins 3 caractères.');
783 XDB
::execute("UPDATE payment_reconcilations SET status = 'transfering' WHERE id = {?}", $_SESSION['paymentrecon_id']);
784 pl_redirect('admin/reconcile/step5');
787 } elseif (Post
::has('savecomments')) {
788 S
::assert_xsrf_token();
789 $recon['comments'] = Post
::v('comments');
790 $page->assign('recon', $recon);
791 XDB
::execute('UPDATE payment_reconcilations SET comments = {?} WHERE id = {?}', $recon['comments'], $_SESSION['paymentrecon_id']);
792 $page->trigSuccess('Les commentaires ont été enregistrés.');
795 // reconcilation results - ok
796 $res = XDB
::query('SELECT count(*), SUM(amount), SUM(commission)
797 FROM payment_transactions
798 WHERE recon_id = {?}',
800 list($ok_count, $ok_sum_amounts, $ok_sum_coms) = $res->fetchOneRow();
801 $page->assign('ok_count', $ok_count);
803 // reconcilation results - ref exists, but some data differs
804 $res = XDB
::query('SELECT id, fullref, method_id, ts_confirmed, trans.amount, trans.commission, status, recon_id,
805 reference, date, tmp.amount as amount2, tmp.commission as commission2
806 FROM payment_transactions AS trans
807 INNER JOIN payment_tmp AS tmp ON (trans.fullref = tmp.reference)
808 WHERE trans.recon_id IS NULL OR trans.recon_id != {?}',
810 $differs = $res->fetchAllAssoc();
811 $page->assign_by_ref('differs', $differs);
812 $page->assign('differ_count', count($differs));
814 // reconcilation results - ref doesn't exists in database
815 $res = XDB
::query('SELECT tmp.*
816 FROM payment_tmp AS tmp
817 LEFT JOIN payment_transactions AS trans ON (trans.fullref = tmp.reference)
818 WHERE trans.fullref IS NULL');
819 $only_import = $res->fetchAllAssoc();
820 $page->assign_by_ref('only_import', $only_import);
821 $page->assign('onlyim_count', count($only_import));
823 // reconcilation results - exists in database but not in import
824 $res = XDB
::query('SELECT trans.*
825 FROM payment_transactions AS trans
826 LEFT JOIN payment_tmp AS tmp ON (trans.fullref = tmp.reference)
827 WHERE {?} <= DATE(trans.ts_confirmed) AND DATE(trans.ts_confirmed) <= {?}
828 AND tmp.reference IS NULL AND method_id = {?}',
829 $recon['period_start'], $recon['period_end'], $recon['method_id']);
830 $only_database = $res->fetchAllAssoc();
831 $page->assign_by_ref('only_database', $only_database);
832 $page->assign('onlydb_count', count($only_database));
836 function handler_adm_transfers($page, $action = null
, $id = null
) {
837 // list/log all bank transfers and link them to individual transactions
839 if (Post
::has('generate')) {
840 $recon_ids = array_keys(Post
::v('recon_id'));
842 // generate a new reconcilation group ID
843 $res = XDB
::query("SELECT MAX(recongroup_id)+1 FROM payment_reconcilations");
844 $recongp_id = $res->fetchOneCell();
845 if ($recongp_id == null
) $recongp_id = 1;
847 // add reconcilations to group
848 // FIXME: should check if reconcilations are in good status
849 XDB
::execute("UPDATE payment_reconcilations
850 SET recongroup_id = {?}, status = 'closed'
852 $recongp_id, $recon_ids);
855 XDB
::execute('INSERT INTO payment_transfers
856 SELECT NULL, {?}, t.ref, SUM(t.amount+t.commission), NULL, p.text, NULL
857 FROM payment_transactions AS t
858 LEFT JOIN payments AS p ON (t.ref = p.id)
859 LEFT JOIN groups AS g ON (p.asso_id = g.id)
860 WHERE t.recon_id IN {?}
862 $recongp_id, $recon_ids);
864 //$res = XDB::query("SELECT * FROM payment_reconcilations WHERE id IN {?}", $recon_ids);
865 //$recons = $res->fetchAllAssoc();
867 $page->trigSuccess('Les virements ont été générés pour ' . count($recon_ids) . ' réconciliations.');
868 $this->handler_adm_reconcile($page);
870 } elseif ($action == 'delgroup') {
871 S
::assert_xsrf_token();
872 XDB
::execute("UPDATE payment_reconcilations
873 SET status = 'transfering', recongroup_id = NULL
874 WHERE recongroup_id = {?}", $id);
875 XDB
::execute("DELETE FROM payment_transfers
876 WHERE recongroup_id = {?} AND date IS NULL", $id);
878 $page->trigSuccess("Les virements non réalisés ont été supprimé du groupe ".$id.".");
879 $this->handler_adm_reconcile($page);
881 } elseif ($action == "confirm") {
882 S
::assert_xsrf_token();
883 XDB
::execute('UPDATE payment_transfers
885 WHERE id = {?}', $id);
887 $page->trigSuccess('Virement ' . $id . ' confirmé.');
888 $this->handler_adm_reconcile($page);
891 pl_redirect('admin/reconcile');
896 class PaymentLogsImporter
extends CSVImporter
{
899 public function __construct() {
900 parent
::__construct('');
901 $this->registerFunction('systempay_commission', 'Compute BPLC commission', array($this, 'compute_systempay_commission'));
902 $this->registerFunction('payment_id', 'Autocompute payment ID', array($this, 'compute_payment_id'));
903 //$this->forceValue('payment_id','func_payment_id');
906 public function run($action = null
, $insert_relation = null
, $update_relation = null
) {
907 $this->result
= array();
908 foreach ($this->data
as $line) {
909 $a = $this->makeAssoc($line, $insert_relation);
910 $a['date'] = preg_replace('/([0-9]{2})\/([0-9]{2})\/([0-9]{4}).*/', '\3-\2-\1', $a['date']);
911 $a['amount'] = str_replace(',', '.', $a['amount']);
912 $a['commission'] = str_replace(',', '.', $a['commission']);
913 $this->result
[] = $a;
917 public function get_result() {
918 return $this->result
;
921 static public function compute_systempay_commission($line, $key, $relation) {
922 static $EEE_countries = array(
923 'France', 'Allemagne', 'Autriche', 'Belgique', 'Bulgarie', 'Chypre',
924 'Danemark', 'Espagne', 'Estonie', 'Finlande', 'Grèce', 'Hongrie', 'Irlande', 'Islande', 'Italie',
925 'Lettonie', 'Liechtenstein', 'Lituanie', 'Luxembourg', 'Malte', 'Norvège', 'Pays-Bas', 'Pologne',
926 'Portugal', 'Roumanie', 'Royaume-Uni', 'Slovaquie', 'Slovénie', 'Suède', 'République Tchèque'
929 if($key!='commission' ||
!array_key_exists('carte', $line)) {
932 $amount = self
::getValue($line, 'amount', $relation['amount']);
933 if (in_array($line['pays carte'], $EEE_countries)) {
934 return -0.20 - round($amount * 0.005, 2);
936 return -0.20 - round($amount * 0.005, 2) - 0.76;
940 static public function compute_payment_id($line, $key, $relation) {
941 if ($key != 'payment_id') {
944 $reference = self
::getValue($line, 'reference', $relation['reference']);
945 if (ereg('-([0-9]+)$', $reference, $matches)) {
953 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: