2 /***************************************************************************
3 * Copyright (C) 2003-2010 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)
72 $n = $m1 +
$m2 +
$m3 +
$m4;
73 $alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
74 return $alpha{$n-1}.$m1.$m2.$m3.$m4;
77 /* decode the comment */
78 function comment_decode($comment) {
79 $comment = urldecode($comment);
80 if (is_utf8($comment)) {
83 return utf8_encode($comment);
87 /* check if a RIB account number is valid */
88 function check_rib($rib)
90 if(strlen($rib) != 23) return false
;
93 $rib = strtr(strtoupper($rib),'ABCDEFGHIJKLMNOPQRSTUVWXYZ','12345678912345678923456789');
94 $bank = substr($rib,0,5);
95 $counter = substr($rib,5,5);
96 $account = substr($rib,10,11);
97 $key = substr($rib,21,2);
100 return 0 == fmod(89 * $bank +
15 * $counter +
3 * $account +
$key, 97);
103 class PaymentModule
extends PLModule
108 'payment' => $this->make_hook('payment', AUTH_MDP
, 'payment'),
109 'payment/cyber_return' => $this->make_hook('cyber_return', AUTH_PUBLIC
, 'user', NO_HTTPS
),
110 'payment/cyber2_return' => $this->make_hook('cyber2_return', AUTH_PUBLIC
, 'user', NO_HTTPS
),
111 'payment/paypal_return' => $this->make_hook('paypal_return', AUTH_PUBLIC
, 'user', NO_HTTPS
),
112 '%grp/paiement' => $this->make_hook('xnet_payment', AUTH_MDP
),
113 '%grp/payment' => $this->make_hook('xnet_payment', AUTH_MDP
),
114 '%grp/payment/cyber_return' => $this->make_hook('cyber_return', AUTH_PUBLIC
, 'user', NO_HTTPS
),
115 '%grp/payment/cyber2_return' => $this->make_hook('cyber2_return', AUTH_PUBLIC
, 'user', NO_HTTPS
),
116 '%grp/payment/paypal_return' => $this->make_hook('paypal_return', AUTH_PUBLIC
, 'user', NO_HTTPS
),
117 'admin/payments' => $this->make_hook('admin', AUTH_MDP
, 'admin'),
118 'admin/payments/methods' => $this->make_hook('adm_methods', AUTH_MDP
, 'admin'),
119 'admin/payments/transactions'=> $this->make_hook('adm_transactions', AUTH_MDP
, 'admin'),
120 'admin/reconcile' => $this->make_hook('adm_reconcile', AUTH_MDP
, 'admin'),
121 'admin/reconcile/importlogs' => $this->make_hook('adm_importlogs', AUTH_MDP
, 'admin'),
122 'admin/reconcile/transfers' => $this->make_hook('adm_transfers', AUTH_MDP
, 'admin'),
123 'admin/reconcile/bankaccounts'=> $this->make_hook('adm_bankaccounts', AUTH_MDP
, 'admin'),
127 function handler_payment(&$page, $ref = -1)
131 $this->load('money.inc.php');
133 if (!empty($GLOBALS['IS_XNET_SITE'])) {
134 if (!$globals->asso('id')) {
137 $res = XDB
::query("SELECT asso_id
139 WHERE asso_id = {?} AND id = {?}",
140 $globals->asso('id'), $ref);
141 if (!$res->numRows()) {
145 $page->changeTpl('payment/index.tpl');
146 $page->setTitle('Télépaiements');
149 $op = Env
::v('op', 'select');
150 $meth = new PayMethod(Env
::i('methode', -1));
151 $pay = new Payment($ref);
153 if($pay->flags
->hasflag('old')){
154 $page->trigError("La transaction selectionnée est périmée.");
155 $pay = new Payment();
157 $val = Env
::v('montant') != 0 ? Env
::v('montant') : $pay->amount_def
;
159 if (($e = $pay->check($val)) !== true
) {
160 $page->trigError($e);
164 $pay->init($val, $meth);
165 $pay->prepareform($pay);
167 $res = XDB
::iterator("SELECT timestamp, amount
168 FROM payment_transactions
169 WHERE uid = {?} AND ref = {?}
170 ORDER BY timestamp DESC",
171 S
::v('uid', -1), $ref);
173 if ($res->total()) $page->assign('transactions', $res);
176 $val = floor($val).".".substr(floor(($val - floor($val))*100+
100),1);
177 $page->assign('montant',$val);
178 $page->assign('comment',Env
::v('comment'));
180 $page->assign('meth', $meth);
181 $page->assign('pay', $pay);
182 $page->assign('evtlink', $pay->event());
185 function handler_cyber_return(&$page, $uid = null
)
187 /* reference banque (numero de transaction) */
188 $champ901 = Env
::s('CHAMP901');
189 /* cle d'acceptation */
190 $champ905 = Env
::s('CHAMP905');
192 $champ906 = Env
::s('CHAMP906');
193 /* email renvoye par la banque */
194 $champ104 = Env
::s('CHAMP104');
195 /* reference complete de la commande */
196 $champ200 = Env
::s('CHAMP200');
197 /* montant de la transaction */
198 $champ201 = Env
::s('CHAMP201');
200 $champ202 = Env
::s('CHAMP202');
201 $montant = "$champ201 $champ202";
203 /* on extrait les informations sur l'utilisateur */
204 $user = User
::get($uid);
206 cb_erreur("uid invalide");
210 /* on extrait la reference de la commande */
211 if (!ereg('-xorg-([0-9]+)$', $champ200, $matches)) {
212 cb_erreur("référence de commande invalide");
215 echo ($ref = $matches[1]);
216 $res = XDB
::query("SELECT mail, text, confirmation
218 WHERE id={?}", $ref);
219 if (!list($conf_mail, $conf_title, $conf_text) = $res->fetchOneRow()) {
220 cb_erreur("référence de commande inconnue");
223 /* on extrait le code de retour */
224 if ($champ906 != "0000") {
225 $res = XDB
::query('SELECT rcb.text, c.id, c.text
226 FROM payment_codeRCB AS rcb
227 LEFT JOIN payment_codeC AS c ON (rcb.codeC = c.id)
228 WHERE rcb.id = {?}', $champ906);
229 if (list($rcb_text, $c_id, $c_text) = $res->fetchOneRow()) {
230 cb_erreur("erreur lors du paiement : $c_text ($c_id)");
232 cb_erreur("erreur inconnue lors du paiement");
236 /* on fait l'insertion en base de donnees */
237 XDB
::execute("INSERT INTO payment_transactions (id, uid, ref, fullref, amount, pkey, comment)
238 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})",
239 $champ901, $user->id(), $ref, $champ200, $montant, $champ905, Env
::v('comment'));
241 // We check if it is an Xnet payment and then update the related ML.
242 $res = XDB
::query('SELECT eid
244 WHERE paiement_id = {?}', $ref);
245 if ($eid = $res->fetchOneCell()) {
246 require_once dirname(__FILE__
) . '/xnetevents/xnetevents.inc.php';
247 $evt = get_event_detail($eid);
248 subscribe_lists_event($uid, $evt, 1, $montant, true
);
251 /* on genere le mail de confirmation */
252 $conf_text = str_replace(
253 array('<prenom>', '<nom>', '<promo>', '<montant>', '<salutation>', '<cher>', 'comment>'),
254 array($user->firstName(), $user->lastName(), $user->promo(), $montant,
255 $user->isFemale() ?
'Chère' : 'Cher', $user->isFemale() ?
'Chère' : 'Cher',
256 Env
::v('comment')), $conf_text);
259 $mymail = new PlMailer();
260 $mymail->setFrom($conf_mail);
261 $mymail->addCc($conf_mail);
262 $mymail->setSubject($conf_title);
263 $mymail->setWikiBody($conf_text);
264 $mymail->sendTo($user);
266 /* on envoie les details de la transaction à telepaiement@ */
267 $mymail = new PlMailer();
268 $mymail->setFrom("webmaster@" . $globals->mail
->domain
);
269 $mymail->addTo($globals->money
->email
);
270 $mymail->setSubject($conf_title);
271 $msg = 'utilisateur : ' . $user->login() . ' (' . $user->id() . ')' . "\n" .
272 'mail : ' . $user->forlifeEmail() . "\n\n" .
273 "paiement : $conf_title ($conf_mail)\n".
274 "reference : $champ200\n".
275 "montant : $montant\n\n".
276 "dump de REQUEST:\n".
277 var_export($_REQUEST,true
);
278 $mymail->setTxtBody($msg);
283 function handler_cyber2_return(&$page, $uid = null
)
285 global $globals, $platal;
287 /* on vérifie la signature */
288 $vads_params = array();
289 foreach($_REQUEST as $key => $value)
290 if(substr($key,0,5) == "vads_")
291 $vads_params[$key] = $value;
293 $signature = sha1(join('+',$vads_params).'+'.$globals->money
->cyperplus_key
);
294 //if($signature != Env::v('signature')) {
295 // cb_erreur("signature invalide");
298 /* on extrait les informations sur l'utilisateur */
299 $user = User
::get(Env
::v('vads_cust_id'));
301 cb_erreur("uid invalide");
304 /* on extrait la reference de la commande */
305 if (!ereg('-([0-9]+)$', Env
::v('vads_order_id'), $matches)) {
306 cb_erreur("référence de commande invalide");
310 $res = XDB
::query("SELECT mail, text, confirmation
312 WHERE id={?}", $ref);
313 if (!list($conf_mail, $conf_title, $conf_text) = $res->fetchOneRow()) {
314 cb_erreur("référence de commande inconnue");
317 /* on extrait le montant */
318 if (Env
::v('vads_currency') != "978") {
319 cb_erreur("monnaie autre que l'euro");
321 $montant = sprintf("%.02f", ((float)Env
::v('vads_amount'))/100) . " EUR";
323 /* on extrait le code de retour */
324 if (Env
::v('vads_result') != "00") {
325 cb_erreur("erreur lors du paiement : ?? (".Env
::v('vads_result').")");
328 /* on fait l'insertion en base de donnees */
329 XDB
::execute("INSERT INTO payment_transactions (id, uid, ref, fullref, amount, pkey, comment)
330 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})",
331 Env
::v('vads_trans_date'), $user->id(), $ref, Env
::v('vads_order_id'), $montant, "", Env
::v('vads_order_info'));
332 echo "Paiement stored.\n";
334 // We check if it is an Xnet payment and then update the related ML.
335 $res = XDB
::query('SELECT eid
337 WHERE paiement_id = {?}', $ref);
338 if ($eid = $res->fetchOneCell()) {
339 require_once dirname(__FILE__
) . '/xnetevents/xnetevents.inc.php';
340 $evt = get_event_detail($eid);
341 subscribe_lists_event($user->id(), $evt, 1, $montant, true
);
344 /* on genere le mail de confirmation */
345 $conf_text = str_replace(
346 array('<prenom>', '<nom>', '<promo>', '<montant>', '<salutation>', '<cher>', 'comment>'),
347 array($user->firstName(), $user->lastName(), $user->promo(), $montant,
348 $user->isFemale() ?
'Chère' : 'Cher', $user->isFemale() ?
'Chère' : 'Cher',
349 Env
::v('comment')), $conf_text);
352 $mymail = new PlMailer();
353 $mymail->setFrom($conf_mail);
354 $mymail->addCc($conf_mail);
355 $mymail->setSubject($conf_title);
356 $mymail->setWikiBody($conf_text);
357 $mymail->sendTo($user);
359 /* on envoie les details de la transaction à telepaiement@ */
360 $mymail = new PlMailer();
361 $mymail->setFrom("webmaster@" . $globals->mail
->domain
);
362 $mymail->addTo($globals->money
->email
);
363 $mymail->setSubject($conf_title);
364 $msg = 'utilisateur : ' . $user->login() . ' (' . $user->id() . ')' . "\n" .
365 'mail : ' . $user->forlifeEmail() . "\n\n" .
366 "paiement : $conf_title ($conf_mail)\n".
367 "reference : " . Env
::v('vads_order_id') . "\n".
368 "montant : $montant\n\n".
369 "dump de REQUEST:\n".
370 var_export($_REQUEST,true
);
371 $mymail->setTxtBody($msg);
373 echo "Notifications sent.\n";
377 function handler_paypal_return(&$page, $uid = null
)
379 $page->changeTpl('payment/retour_paypal.tpl');
381 /* reference banque (numero de transaction) */
382 $no_transaction = Env
::s('tx');
383 /* token a renvoyer pour avoir plus d'information */
384 $clef = Env
::s('sig');
386 $status = Env
::s('st');
388 $reason = ($status == 'Pending')? Env
::s('pending_reason'): Env
::s('reason_code');
389 /* reference complete de la commande */
390 $fullref = Env
::s('cm');
391 /* montant de la transaction */
392 $montant_nb = Env
::s('amt');
394 $montant_dev = Env
::s('cc');
395 $montant = "$montant_nb $montant_dev";
397 /* on extrait le code de retour */
398 if ($status != "Completed") {
400 paypal_erreur("erreur lors du paiement : $status - $reason");
402 paypal_erreur("Paiement annulé", false
);
405 /* on extrait les informations sur l'utilisateur */
406 $user = User
::get($uid);
408 paypal_erreur("uid invalide");
411 /* on extrait la reference de la commande */
412 if (!ereg('-xorg-([0-9]+)$', $fullref, $matches)) {
413 paypal_erreur("référence de commande invalide");
417 $res = XDB
::query("SELECT mail, text, confirmation
419 WHERE id = {?}", $ref);
420 if (!list($conf_mail,$conf_title,$conf_text) = $res->fetchOneRow()) {
421 paypal_erreur("référence de commande inconnue");
424 /* on fait l'insertion en base de donnees */
425 XDB
::execute("INSERT INTO payment_transactions (id, uid, ref, fullref, amount, pkey, comment)
426 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})",
427 $no_transaction, $user->id(), $ref, $fullref, $montant, $clef, Env
::v('comment'));
429 // We check if it is an Xnet payment and then update the related ML.
430 $res = XDB
::query('SELECT eid
432 WHERE paiement_id = {?}', $ref);
433 if ($eid = $res->fetchOneCell()) {
434 require_once dirname(__FILE__
) . '/xnetevents/xnetevents.inc.php';
435 $evt = get_event_detail($eid);
436 subscribe_lists_event($user->id(), $evt, 1, $montant, true
);
439 /* on genere le mail de confirmation */
440 $conf_text = str_replace(array('<prenom>', '<nom>', '<promo>', '<montant>', '<salutation>', '<cher>'),
441 array($user->firstName(), $user->lastName(), $user->promo(), $montant,
442 $user->isFemale() ?
'Chère' : 'Cher',
443 $user->isFemale() ?
'Chère' : 'Cher'), $conf_text);
446 $mymail = new PlMailer();
447 $mymail->setFrom($conf_mail);
448 $mymail->addCc($conf_mail);
449 $mymail->setSubject($conf_title);
450 $mymail->setWikiBody($conf_text);
451 $mymail->sendTo($user);
453 /* on envoie les details de la transaction à telepaiement@ */
454 $mymail = new PlMailer();
455 $mymail->setFrom("webmaster@" . $globals->mail
->domain
);
456 $mymail->addTo($globals->money
->email
);
457 $mymail->setSubject($conf_title);
458 $msg = 'utilisateur : ' . $user->login() . ' (' . $user->id() . ')' . "\n" .
459 'mail : ' . $user->forlifeEmail() . "\n\n" .
460 "paiement : $conf_title ($conf_mail)\n".
461 "reference : $champ200\n".
462 "montant : $montant\n\n".
463 "dump de REQUEST:\n".
464 var_export($_REQUEST,true
);
465 $mymail->setTxtBody($msg);
468 $page->assign('texte', $conf_text);
469 $page->assign('erreur', $erreur);
472 function handler_xnet_payment(&$page, $pid = null
)
476 $perms = S
::v('perms');
477 if (!$perms->hasFlag('groupmember')) {
481 $res = XDB
::query("SELECT 1
482 FROM group_events AS e
483 INNER JOIN group_event_participants AS ep ON (ep.eid = e.eid AND uid = {?})
484 WHERE e.paiement_id = {?} AND e.asso_id = {?}",
485 S
::i('uid'), $pid, $globals->asso('id'));
486 if ($res->numRows() == 0) {
491 if (!is_null($pid)) {
492 return $this->handler_payment($page, $pid);
494 $page->changeTpl('payment/xnet.tpl');
497 "SELECT id, text, url
499 WHERE asso_id = {?} AND NOT FIND_IN_SET('old', flags)
500 ORDER BY id DESC", $globals->asso('id'));
501 $tit = $res->fetchAllAssoc();
502 $page->assign('titres', $tit);
505 // TODO: replug sort.
508 foreach($tit as $foo) {
511 $res = XDB
::query('SELECT t.uid, timestamp AS `date`, t.comment, amount
512 FROM payment_transactions AS t
513 WHERE t.ref = {?}', $pid);
514 $trans[$pid] = User
::getBulkUsersWithUIDs($res->fetchAllAssoc(), 'uid', 'user');
516 foreach ($trans[$pid] as $i => $t) {
517 $sum +
= strtr(substr($t['amount'], 0, strpos($t['amount'], 'EUR')), ',', '.');
518 $trans[$pid][$i]['amount'] = str_replace('EUR', '€', $t['amount']);
520 $trans[$pid][] = array('nom' => 'somme totale',
521 'amount' => strtr($sum, '.', ',').' €');
523 $res = XDB
::iterRow("SELECT e.eid, e.short_name, e.intitule, ep.nb, ei.montant, ep.paid
524 FROM group_events AS e
525 LEFT JOIN group_event_participants AS ep ON (ep.eid = e.eid AND uid = {?})
526 INNER JOIN group_event_items AS ei ON (ep.eid = ei.eid AND ep.item_id = ei.item_id)
527 WHERE e.paiement_id = {?}",
529 $event[$pid] = array();
530 $event[$pid]['paid'] = 0;
532 $event[$pid]['topay'] = 0;
533 while(list($eid, $shortname, $title, $nb, $montant, $paid) = $res->next()) {
534 $event[$pid]['topay'] +
= ($nb * $montant);
535 $event[$pid]['eid'] = $eid;
536 $event[$pid]['shortname'] = $shortname;
537 $event[$pid]['title'] = $title;
538 $event[$pid]['ins'] = !is_null($nb);
539 $event[$pid]['paid'] = $paid;
542 $res = XDB
::query("SELECT amount
543 FROM payment_transactions AS t
544 WHERE ref = {?} AND uid = {?}", $pid, S
::v('uid'));
545 $montants = $res->fetchColumn();
547 foreach ($montants as $m) {
548 $p = strtr(substr($m, 0, strpos($m, 'EUR')), ',', '.');
549 $event[$pid]['paid'] +
= trim($p);
552 $page->register_modifier('decode_comment', 'decode_comment');
553 $page->assign('trans', $trans);
554 $page->assign('event', $event);
557 function handler_admin(&$page, $action = 'list', $id = null
) {
558 $page->setTitle('Administration - Paiements');
559 $page->assign('title', 'Gestion des télépaiements');
560 $table_editor = new PLTableEditor('admin/payments','payments','id');
561 //$table_editor->add_join_table('payment_transactions','ref',true); => on ne supprime jamais une transaction
562 $table_editor->add_sort_field('flags');
563 $table_editor->add_sort_field('id', true
, true
);
564 $table_editor->on_delete("UPDATE payments SET flags = 'old' WHERE id = {?}", "Le paiement a été archivé");
565 $table_editor->describe('text','intitulé',true
);
566 $table_editor->describe('url','site web',false
);
567 $table_editor->describe('amount_def','montant par défaut',false
);
568 $table_editor->describe('amount_min','montant minimum',false
);
569 $table_editor->describe('amount_max','montant maximum',false
);
570 $table_editor->describe('mail','email contact',true
);
571 $table_editor->describe('confirmation','message confirmation',false
);
573 // adds a column with the start date of the linked event if there is one
574 $table_editor->add_option_table('group_events','group_events.paiement_id = t.id');
575 $table_editor->add_option_field('group_events.debut', 'related_event', 'évènement', 'timestamp');
577 $table_editor->apply($page, $action, $id);
580 function handler_adm_transactions(&$page, $payment_id = null
, $action = "list", $id = null
) {
581 // show transactions. FIXME: should not be modifiable
582 $page->setTitle('Administration - Paiements - Transactions');
583 $page->assign('title', "Liste des transactions pour le paiement {$payment_id}");
585 if ($payment_id == null
)
586 $page->trigError("Aucun ID de paiement fourni.");
588 $table_editor = new PLTableEditor("admin/transactions/{$payment_id}",'payment_transactions','id');
589 $table_editor->set_where_clause(XDB
::format('ref = {?}', $payment_id));
590 $table_editor->apply($page, 'list', $id); // only the 'list' action is allowed
591 $page->assign("readonly","readonly"); // don't show modification features
594 function handler_adm_bankaccounts(&$page, $action = "list", $id = null
) {
595 // managment of bank account used for money transfert
596 $page->setTitle('Administration - Paiements - RIBs');
597 $page->assign('title', "Liste des RIBs");
599 $table_editor = new PLTableEditor("admin/payments/bankaccounts",'payment_bankaccounts','id');
600 $table_editor->describe('asso_id','ID du groupe',false
);
601 $table_editor->describe('owner','titulaire',true
);
602 $table_editor->add_option_table('groups','groups.id = t.asso_id');
603 $table_editor->add_option_field('groups.diminutif', 'group_name', 'groupe', 'varchar','account');
606 if ($action == "update" && Post
::has("account") && !check_rib(Post
::v("account"))) {
607 $page->trigError("Le RIB n'est pas valide");
608 $table_editor->apply($page, "edit", $id);
612 $table_editor->apply($page, $action, $id);
615 function handler_adm_methods(&$page, $action = "list", $id = null
) {
616 // show and edit payment methods
617 $page->setTitle('Administration - Paiements - Méthodes');
618 $page->assign('title', "Méthodes de paiement");
619 $table_editor = new PLTableEditor("admin/payments/methods",'payment_methods','id');
620 $table_editor->apply($page, $action, $id);
623 function handler_adm_reconcile(&$page, $step = 'list', $param = null
) {
624 // reconciles logs with transactions
625 // FIXME: the admin is considered to be fair => he doesn't hack the $step value, nor other params
626 $page->setTitle('Administration - Paiements - Réconciliations');
627 $page->changeTpl('payment/reconcile.tpl');
628 $page->assign('step', $step);
632 if ($step == 'delete' && $param != null
) {
633 S
::assert_xsrf_token();
634 XDB
::execute("DELETE FROM payment_reconcilations WHERE id={?}", $param);
635 // FIXME: hardcoding !!!
636 XDB
::execute("UPDATE payment_transactions SET recon_id=NULL,commission=NULL WHERE recon_id={?} AND method_id=2", $param);
637 XDB
::execute("UPDATE payment_transactions SET recon_id=NULL WHERE recon_id={?} AND method_id=1", $param);
638 $page->trigSuccess("L'entrée ".$param." a été supprimée.");
640 } elseif ($step == 'edit') {
641 $page->trigError("L'édition n'est pas implémentée.");
643 } elseif ($step == 'step5') {
644 $page->trigSuccess("La réconciliation est terminée. Il est maintenant nécessaire de générer les virements.");
649 // show list of reconciliations, with a "add" button
650 $page->assign('title', "Réconciliation - Liste");
651 $page->assign('step', 'list');
655 $res = XDB
::query("SELECT r.id, short_name AS method, period_start, period_end, status,
656 payment_count, sum_amounts, sum_commissions
657 FROM payment_reconcilations AS r
658 LEFT JOIN payment_methods AS m ON r.method_id=m.id
659 WHERE recongroup_id IS NULL
660 ORDER BY period_end DESC, period_start DESC");
661 foreach ($res->fetchAllAssoc() as $recon)
662 $recongps[] = array('recons' => array($recon), 'transfers' => array());
664 $res = XDB
::query("SELECT recongroup_id AS id
665 FROM payment_reconcilations
666 GROUP BY recongroup_id
667 ORDER BY MAX(period_end) DESC, MIN(period_start) DESC");
668 foreach ($res->fetchAllAssoc() as $recongp) {
669 $res = XDB
::query("SELECT r.id, short_name AS method, period_start, period_end, status,
670 payment_count, sum_amounts, sum_commissions
671 FROM payment_reconcilations AS r
672 LEFT JOIN payment_methods AS m ON r.method_id=m.id
673 WHERE recongroup_id={?}
674 ORDER BY period_end DESC, period_start DESC",
676 $recongp['recons'] = $res->fetchAllAssoc();
678 $res = XDB
::query("SELECT id, payment_id, amount, account_id, message, date
679 FROM payment_transfers
680 WHERE recongroup_id={?}",
682 $recongp['transfers'] = $res->fetchAllAssoc();
684 $recongps[] = $recongp;
686 $page->assign_by_ref('recongps', $recongps);
690 function handler_adm_importlogs(&$page, $step, $param = null
) {
691 $page->setTitle('Administration - Paiements - Réconciliations');
692 $page->changeTpl('payment/reconcile.tpl');
693 $page->assign('step', $step);
695 if (isset($_SESSION['paymentrecon_data'])) {
696 // create temporary table with imported data
697 XDB
::execute("CREATE TEMPORARY TABLE payment_tmp (
698 reference VARCHAR(255) PRIMARY KEY,
701 commission DECIMAL(9,2)
703 foreach ($_SESSION['paymentrecon_data'] as $i)
704 XDB
::execute("INSERT INTO payment_tmp VALUES ({?},{?},{?},{?})",
705 $i['reference'], $i['date'], $i['amount'], $i['commission']);
708 if ($step == 'step1') {
709 $page->assign('title', "Étape 1");
710 unset($_SESSION['paymentrecon_method']);
711 unset($_SESSION['paymentrecon_data']);
712 unset($_SESSION['paymentrecon_id']);
714 // was a payment method choosen ?
715 if ($param != null
) {
716 $_SESSION['paymentrecon_method'] = (int)$param;
717 pl_redirect("admin/reconcile/importlogs/step2");
720 // ask to choose a payment method
721 $res = XDB
::query("SELECT id, text FROM payment_methods");
722 $page->assign('methods', $res->fetchAllAssoc());
725 } elseif ( $step == 'step2' ) {
726 $page->assign('title', "Étape 2");
728 // import logs formated in CVS
729 $fields = array('date','reference','amount','commission');
730 $importer = new PaymentLogsImporter();
731 $importer->apply($page, 'admin/reconcile/importlogs/step2', $fields);
733 // if import is finished
734 $result = $importer->get_result();
735 if($result != null
) {
736 $_SESSION['paymentrecon_data'] = $result;
737 pl_redirect("admin/reconcile/importlogs/step3");
740 } elseif ($step == 'step3' ) {
741 $page->assign('title', "Étape 3");
743 // compute reconcilation summary data
744 $res = XDB
::query("SELECT MIN(date) AS period_start, MAX(date) AS period_end,
745 count(*) AS payment_count, SUM(amount) AS sum_amounts,
746 SUM(commission) AS sum_commissions
748 $recon = $res->fetchOneAssoc();
749 $recon['method_id'] = $_SESSION['paymentrecon_method'];
751 // create reconciliation item in database
752 if(Post
::has('next')) {
753 S
::assert_xsrf_token();
756 $recon['period_start'] = preg_replace('/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/','\3-\2-\1',Post
::v('period_start'));
757 $recon['period_end'] = preg_replace('/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/','\3-\2-\1',Post
::v('period_end'));
758 // FIXME: save checks to be done at next step
760 // Create reconcilation item in database
761 // FIXME: check if period doesn't overlap with others for the same method_id
762 XDB
::execute("INSERT INTO payment_reconcilations (method_id, period_start, period_end,
763 payment_count, sum_amounts, sum_commissions)
764 VALUES ({?}, {?}, {?}, {?}, {?}, {?})",
765 $recon['method_id'], $recon['period_start'], $recon['period_end'],
766 $recon['payment_count'], $recon['sum_amounts'], $recon['sum_commissions']);
767 $_SESSION['paymentrecon_id'] = XDB
::insertId();
769 // reconcile simple cases (trans.commission n'est modifié que s'il vaut NULL)
770 XDB
::execute("UPDATE payment_transactions AS trans, payment_tmp AS tmp
771 SET trans.recon_id={?}, trans.commission=tmp.commission
772 WHERE trans.fullref=tmp.reference
773 AND trans.amount=tmp.amount AND DATE(trans.ts_confirmed)=tmp.date
774 AND (trans.commission IS NULL OR trans.commission=tmp.commission)
775 AND method_id={?} AND recon_id IS NULL AND status='confirmed'",
776 $_SESSION['paymentrecon_id'], $recon['method_id']);
778 pl_redirect("admin/reconcile/importlogs/step4");
780 // show summary of the imported data + ask form start/end of reconcilation period
782 $recon['period_start'] = preg_replace('/([0-9]{4})-([0-9]{2})-([0-9]{2})/', '\3/\2/\1', $recon['period_start']);
783 $recon['period_end'] = preg_replace('/([0-9]{4})-([0-9]{2})-([0-9]{2})/', '\3/\2/\1', $recon['period_end']);
784 $page->assign('recon', $recon);
787 } elseif ($step == 'step4' ) {
788 $page->assign('title', "Étape 4");
790 // get reconcilation summary informations
791 $res = XDB
::query("SELECT * FROM payment_reconcilations WHERE id={?}", $_SESSION['paymentrecon_id']);
792 $recon = $res->fetchOneAssoc();
793 $page->assign('recon', $recon);
795 if (Post
::has('force')) {
796 S
::assert_xsrf_token();
797 foreach (Post
::v('force') as $id => $value) {
798 XDB
::execute("UPDATE payment_transactions AS trans, payment_tmp AS tmp
799 SET trans.recon_id={?}, trans.commission=tmp.commission
800 WHERE trans.id={?} AND trans.fullref=tmp.reference",
801 $_SESSION['paymentrecon_id'], $id);
803 $page->trigSuccess('La réconciliation a été forcée pour '.count(Post
::v('force')).' transaction(s).');
805 } elseif (Post
::has('next')) {
806 if (strlen($recon['comments'])<3) {
807 $page->trigError("Le commentaire doit contenir au moins 3 caractères.");
809 XDB
::execute("UPDATE payment_reconcilations SET status='transfering' WHERE id={?}", $_SESSION['paymentrecon_id']);
810 pl_redirect('admin/reconcile/step5');
813 } elseif (Post
::has('savecomments')) {
814 S
::assert_xsrf_token();
815 $recon['comments'] = Post
::v('comments');
816 $page->assign('recon', $recon);
817 XDB
::execute("UPDATE payment_reconcilations SET comments={?} WHERE id={?}", $recon['comments'], $_SESSION['paymentrecon_id']);
818 $page->trigSuccess('Les commentaires ont été enregistrés.');
821 // reconcilation results - ok
822 $res = XDB
::query("SELECT count(*),SUM(amount),SUM(commission)
823 FROM payment_transactions WHERE recon_id={?}",
825 list($ok_count,$ok_sum_amounts,$ok_sum_coms) = $res->fetchOneRow();
826 $page->assign('ok_count', $ok_count);
828 // reconcilation results - ref exists, but some data differs
829 $res = XDB
::query("SELECT id, fullref, method_id, ts_confirmed, trans.amount, trans.commission, status, recon_id,
830 reference, date, tmp.amount as amount2, tmp.commission as commission2
831 FROM payment_transactions AS trans
832 INNER JOIN payment_tmp AS tmp ON trans.fullref=tmp.reference
833 WHERE trans.recon_id IS NULL OR trans.recon_id != {?}",
835 $differs = $res->fetchAllAssoc();
836 $page->assign_by_ref('differs', $differs);
837 $page->assign('differ_count', count($differs));
839 // reconcilation results - ref doesn't exists in database
840 $res = XDB
::query("SELECT tmp.*
841 FROM payment_tmp AS tmp
842 LEFT JOIN payment_transactions AS trans ON trans.fullref=tmp.reference
843 WHERE trans.fullref IS NULL");
844 $only_import = $res->fetchAllAssoc();
845 $page->assign_by_ref('only_import', $only_import);
846 $page->assign('onlyim_count', count($only_import));
848 // reconcilation results - exists in database but not in import
849 $res = XDB
::query("SELECT trans.*
850 FROM payment_transactions AS trans
851 LEFT JOIN payment_tmp AS tmp ON trans.fullref=tmp.reference
852 WHERE {?}<=DATE(trans.ts_confirmed) AND DATE(trans.ts_confirmed)<={?}
853 AND tmp.reference IS NULL AND method_id={?}",
854 $recon['period_start'], $recon['period_end'], $recon['method_id']);
855 $only_database = $res->fetchAllAssoc();
856 $page->assign_by_ref('only_database', $only_database);
857 $page->assign('onlydb_count', count($only_database));
861 function handler_adm_transfers(&$page, $action = null
, $id = null
) {
862 // list/log all bank transfers and link them to individual transactions
864 if (Post
::has('generate')) {
865 $recon_ids = array_keys(Post
::v('recon_id'));
867 // generate a new reconcilation group ID
868 $res = XDB
::query("SELECT MAX(recongroup_id)+1 FROM payment_reconcilations");
869 $recongp_id = $res->fetchOneCell();
870 if ($recongp_id == null
) $recongp_id = 1;
872 // add reconcilations to group
873 // FIXME: should check if reconcilations are in good status
874 XDB
::execute("UPDATE payment_reconcilations SET recongroup_id={?}, status='closed'
876 $recongp_id, $recon_ids);
879 XDB
::execute("INSERT INTO payment_transfers
880 SELECT NULL, {?}, t.ref, SUM(t.amount+t.commission), NULL, p.text, NULL
881 FROM payment_transactions AS t
882 LEFT JOIN payments AS p ON t.ref = p.id
883 LEFT JOIN groups AS g ON p.asso_id = g.id
884 WHERE t.recon_id IN {?}
886 $recongp_id, $recon_ids);
888 //$res = XDB::query("SELECT * FROM payment_reconcilations WHERE id IN {?}", $recon_ids);
889 //$recons = $res->fetchAllAssoc();
891 $page->trigSuccess("Les virements ont été générés pour ".count($recon_ids)." réconciliations.");
892 $this->handler_adm_reconcile($page);
894 } elseif ($action == "delgroup") {
895 S
::assert_xsrf_token();
896 XDB
::execute("UPDATE payment_reconcilations SET status='transfering', recongroup_id=NULL WHERE recongroup_id={?}", $id);
897 XDB
::execute("DELETE FROM payment_transfers WHERE recongroup_id={?} AND date IS NULL", $id);
899 $page->trigSuccess("Les virements non réalisés ont été supprimé du groupe ".$id.".");
900 $this->handler_adm_reconcile($page);
903 pl_redirect("admin/reconcile");
908 class PaymentLogsImporter
extends CSVImporter
{
911 public function __construct() {
912 parent
::__construct('');
913 $this->registerFunction('systempay_commission', 'Compute BPLC commission', array($this,"compute_systempay_commission"));
914 $this->registerFunction('payment_id', 'Autocompute payment ID', array($this,"compute_payment_id"));
915 //$this->forceValue('payment_id','func_payment_id');
918 public function run($action = null
, $insert_relation = null
, $update_relation = null
) {
919 $this->result
= array();
920 foreach ($this->data
as $line) {
921 $a = $this->makeAssoc($line, $insert_relation);
922 $a['date'] = preg_replace('/([0-9]{2})\/([0-9]{2})\/([0-9]{4}).*/','\3-\2-\1', $a['date']);
923 $a['amount'] = str_replace(',','.',$a['amount']);
924 $a['commission'] = str_replace(',','.',$a['commission']);
925 $this->result
[] = $a;
929 public function get_result() {
930 return $this->result
;
933 static public function compute_systempay_commission($line, $key, $relation) {
934 static $EEE_countries = array('France','Allemagne','Autriche','Belgique','Bulgarie','Chypre',
935 'Danemark','Espagne','Estonie','Finlande','Grèce','Hongrie','Irlande','Islande','Italie',
936 'Lettonie','Liechtenstein','Lituanie','Luxembourg','Malte','Norvège','Pays-Bas','Pologne',
937 'Portugal','Roumanie','Royaume-Uni','Slovaquie','Slovénie','Suède','République Tchèque');
939 if($key!='commission' ||
!array_key_exists('carte',$line)) return null
;
940 $amount = self
::getValue($line, 'amount', $relation['amount']);
941 if (in_array($line['pays carte'],$EEE_countries))
942 return -0.20 - round($amount*0.005, 2);
944 return -0.20 - round($amount*0.005, 2) - 0.76;
947 static public function compute_payment_id($line, $key, $relation) {
948 if ($key != 'payment_id') return null
;
949 $reference = self
::getValue($line, 'reference', $relation['reference']);
950 if (ereg('-([0-9]+)$', $reference, $matches))
957 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: