Merge remote branch 'origin/xorg/1.0.2/master' into xorg/master
[platal.git] / modules / payment.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2010 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
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. *
10 * *
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. *
15 * *
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 *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22 /* sort en affichant une erreur */
23 function cb_erreur($text) {
24 global $globals;
25 echo "Error.\n";
26 $mymail = new PlMailer();
27 $mymail->addTo($globals->money->email);
28 $mymail->setFrom("webmaster@" . $globals->mail->domain);
29 $mymail->setSubject("erreur lors d'un télépaiement (CyberPaiement)");
30 $mymail->setTxtBody("\n\n".var_export($_REQUEST,true));
31 $mymail->send();
32 echo "Notification sent.\n";
33 exit;
34 }
35
36 /* sort en affichant une erreur */
37 function paypal_erreur($text, $send=true)
38 {
39 global $erreur, $globals;
40 if ($erreur) return;
41 $erreur = $text;
42 if (!$send) return;
43
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));
49 $mymail->send();
50
51 Platal::page()->trigError($text);
52 }
53
54 /* http://fr.wikipedia.org/wiki/Formule_de_Luhn */
55 function luhn($nombre) {
56 $s = strrev($nombre);
57 $sum = 0;
58 for ($i = 0; $i < strlen($s); ++$i) {
59 $dgt = $s{$i};
60 $sum += ($i % 2) ? (2 * $dgt) % 9 : $dgt;
61 }
62 return $sum % 10;
63 }
64
65 /* calcule la clé d'acceptation a partir de 5 champs */
66 function cle_accept($d1, $d2, $d3, $d4, $d5)
67 {
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;
75 }
76
77 /* decode the comment */
78 function comment_decode($comment) {
79 $comment = urldecode($comment);
80 if (is_utf8($comment)) {
81 return $comment;
82 } else {
83 return utf8_encode($comment);
84 }
85 }
86
87 /* check if a RIB account number is valid */
88 function check_rib($rib)
89 {
90 if(strlen($rib) != 23) return false;
91
92 // extract fields
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);
98
99 // check
100 return (0 == fmod(89 * $bank + 15 * $counter + 3 * $account + $key, 97));
101 }
102
103 class PaymentModule extends PLModule
104 {
105 function handlers()
106 {
107 return array(
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'),
124 );
125 }
126
127 function handler_payment(&$page, $ref = -1)
128 {
129 global $globals;
130
131 $this->load('money.inc.php');
132
133 if (!empty($GLOBALS['IS_XNET_SITE'])) {
134 if (!$globals->asso('id')) {
135 return PL_NOT_FOUND;
136 }
137 $res = XDB::query('SELECT asso_id
138 FROM payments
139 WHERE asso_id = {?} AND id = {?}',
140 $globals->asso('id'), $ref);
141 if (!$res->numRows()) {
142 return PL_FORBIDDEN;
143 }
144 }
145 $page->changeTpl('payment/index.tpl');
146 $page->setTitle('Télépaiements');
147
148 // initialisation
149 $op = Env::v('op', 'select');
150 $meth = new PayMethod(Env::i('methode', -1));
151 $pay = new Payment($ref);
152
153 if($pay->flags->hasflag('old')){
154 $page->trigError("La transaction selectionnée est périmée.");
155 $pay = new Payment();
156 }
157 $val = Env::v('montant') != 0 ? Env::v('montant') : $pay->amount_def;
158
159 if (($e = $pay->check($val)) !== true) {
160 $page->trigError($e);
161 }
162
163 if ($op == 'submit') {
164 $pay->init($val, $meth);
165 $pay->prepareform($pay);
166 } else {
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);
172
173 if ($res->total()) {
174 $page->assign('transactions', $res);
175 }
176 }
177
178 $val = floor($val) . '.' . substr(floor(($val - floor($val)) * 100 + 100), 1);
179 $page->assign('montant', $val);
180 $page->assign('comment', Env::v('comment'));
181
182 $page->assign('meth', $meth);
183 $page->assign('pay', $pay);
184 $page->assign('evtlink', $pay->event());
185 }
186
187 function handler_cyber_return(&$page, $uid = null)
188 {
189 /* reference banque (numero de transaction) */
190 $champ901 = Env::s('CHAMP901');
191 /* cle d'acceptation */
192 $champ905 = Env::s('CHAMP905');
193 /* code retour */
194 $champ906 = Env::s('CHAMP906');
195 /* email renvoye par la banque */
196 $champ104 = Env::s('CHAMP104');
197 /* reference complete de la commande */
198 $champ200 = Env::s('CHAMP200');
199 /* montant de la transaction */
200 $champ201 = Env::s('CHAMP201');
201 /* devise */
202 $champ202 = Env::s('CHAMP202');
203 $montant = "$champ201 $champ202";
204
205 /* on extrait les informations sur l'utilisateur */
206 $user = User::get($uid);
207 if (!$user) {
208 cb_erreur("uid invalide");
209 }
210
211
212 /* on extrait la reference de la commande */
213 if (!ereg('-xorg-([0-9]+)$', $champ200, $matches)) {
214 cb_erreur("référence de commande invalide");
215 }
216
217 echo ($ref = $matches[1]);
218 $res = XDB::query('SELECT mail, text, confirmation
219 FROM payments
220 WHERE id = {?}', $ref);
221 if (!list($conf_mail, $conf_title, $conf_text) = $res->fetchOneRow()) {
222 cb_erreur("référence de commande inconnue");
223 }
224
225 /* on extrait le code de retour */
226 if ($champ906 != "0000") {
227 $res = XDB::query('SELECT rcb.text, c.id, c.text
228 FROM payment_codeRCB AS rcb
229 LEFT JOIN payment_codeC AS c ON (rcb.codeC = c.id)
230 WHERE rcb.id = {?}', $champ906);
231 if (list($rcb_text, $c_id, $c_text) = $res->fetchOneRow()) {
232 cb_erreur("erreur lors du paiement : $c_text ($c_id)");
233 } else{
234 cb_erreur("erreur inconnue lors du paiement");
235 }
236 }
237
238 /* on fait l'insertion en base de donnees */
239 XDB::execute('INSERT INTO payment_transactions (id, uid, ref, fullref, amount, pkey, comment)
240 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})',
241 $champ901, $user->id(), $ref, $champ200, $montant, $champ905, Env::v('comment'));
242
243 // We check if it is an Xnet payment and then update the related ML.
244 $res = XDB::query('SELECT eid
245 FROM group_events
246 WHERE paiement_id = {?}', $ref);
247 if ($eid = $res->fetchOneCell()) {
248 require_once dirname(__FILE__) . '/xnetevents/xnetevents.inc.php';
249 $evt = get_event_detail($eid);
250 subscribe_lists_event($uid, $evt, 1, $montant, true);
251 }
252
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('comment')), $conf_text);
259
260 global $globals;
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);
267
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 : $champ200\n".
277 "montant : $montant\n\n".
278 "dump de REQUEST:\n".
279 var_export($_REQUEST,true);
280 $mymail->setTxtBody($msg);
281 $mymail->send();
282 exit;
283 }
284
285 function handler_cyber2_return(&$page, $uid = null)
286 {
287 global $globals, $platal;
288
289 /* on vérifie la signature */
290 $vads_params = array();
291 foreach($_REQUEST as $key => $value)
292 if(substr($key,0,5) == 'vads_') {
293 $vads_params[$key] = $value;
294 }
295 ksort($vads_params);
296 $signature = sha1(join('+', $vads_params) . '+' . $globals->money->cyperplus_key);
297 //if($signature != Env::v('signature')) {
298 // cb_erreur("signature invalide");
299 //}
300
301 /* on extrait les informations sur l'utilisateur */
302 $user = User::get(Env::i('vads_cust_id'));
303 if (!$user) {
304 cb_erreur("uid invalide");
305 }
306
307 /* on extrait la reference de la commande */
308 if (!ereg('-([0-9]+)$', Env::v('vads_order_id'), $matches)) {
309 cb_erreur("référence de commande invalide");
310 }
311
312 $ref = $matches[1];
313 $res = XDB::query('SELECT mail, text, confirmation
314 FROM payments
315 WHERE id={?}", $ref);
316 if ($res->numRows() != 1) {
317 cb_erreur("référence de commande inconnue");
318 }
319 list($conf_mail, $conf_title, $conf_text) = $res->fetchOneRow();
320
321 /* on extrait le montant */
322 if (Env::v('vads_currency') != '978') {
323 cb_erreur("monnaie autre que l'euro");
324 }
325 $amount = ((float)Env::i('vads_amount')) / 100;
326 $montant = sprintf("%.02f EUR", $amount);
327
328 /* on extrait le code de retour */
329 if (Env::v('vads_result') != '00') {
330 cb_erreur('erreur lors du paiement : ?? (' . Env::v('vads_result') . ')');
331 }
332
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 Env::v('vads_trans_date'), $user->id(), $ref, Env::v('vads_order_id'), $montant, '', Env::v('vads_order_info'));
337 echo "Paiement stored.\n";
338
339 // We check if it is an Xnet payment and then update the related ML.
340 $res = XDB::query('SELECT eid, asso_id
341 FROM group_events
342 WHERE paiement_id = {?}', $ref);
343 if ($res->numRows() == 1) {
344 list($eid, $asso_id) = $res->fetchOneRow();
345 require_once dirname(__FILE__) . '/xnetevents/xnetevents.inc.php';
346 $evt = get_event_detail($eid, false, $asso_id);
347 subscribe_lists_event($user->id(), $evt, 1, $amount, true);
348 }
349
350 /* on genere le mail de confirmation */
351 $conf_text = str_replace(
352 array('<prenom>', '<nom>', '<promo>', '<montant>', '<salutation>', '<cher>', '<comment>'),
353 array($user->firstName(), $user->lastName(), $user->promo(), $montant,
354 $user->isFemale() ? 'Chère' : 'Cher', $user->isFemale() ? 'Chère' : 'Cher',
355 Env::v('comment')), $conf_text);
356
357 global $globals;
358 $mymail = new PlMailer();
359 $mymail->setFrom($conf_mail);
360 $mymail->addCc($conf_mail);
361 $mymail->setSubject($conf_title);
362 $mymail->setWikiBody($conf_text);
363 $mymail->sendTo($user);
364
365 /* on envoie les details de la transaction à telepaiement@ */
366 $mymail = new PlMailer();
367 $mymail->setFrom("webmaster@" . $globals->mail->domain);
368 $mymail->addTo($globals->money->email);
369 $mymail->setSubject($conf_title);
370 $msg = 'utilisateur : ' . $user->login() . ' (' . $user->id() . ')' . "\n" .
371 'mail : ' . $user->forlifeEmail() . "\n\n" .
372 "paiement : $conf_title ($conf_mail)\n".
373 "reference : " . Env::v('vads_order_id') . "\n".
374 "montant : $montant\n\n".
375 "dump de REQUEST:\n".
376 var_export($_REQUEST,true);
377 $mymail->setTxtBody($msg);
378 $mymail->send();
379 echo "Notifications sent.\n";
380 exit;
381 }
382
383 function handler_paypal_return(&$page, $uid = null)
384 {
385 $page->changeTpl('payment/retour_paypal.tpl');
386
387 /* reference banque (numero de transaction) */
388 $no_transaction = Env::s('tx');
389 /* token a renvoyer pour avoir plus d'information */
390 $clef = Env::s('sig');
391 /* code retour */
392 $status = Env::s('st');
393 /* raison */
394 $reason = ($status == 'Pending') ? Env::s('pending_reason') : Env::s('reason_code');
395 /* reference complete de la commande */
396 $fullref = Env::s('cm');
397 /* montant de la transaction */
398 $montant_nb = Env::s('amt');
399 /* devise */
400 $montant_dev = Env::s('cc');
401 $montant = "$montant_nb $montant_dev";
402
403 /* on extrait le code de retour */
404 if ($status != "Completed") {
405 if ($status) {
406 paypal_erreur("erreur lors du paiement : $status - $reason");
407 } else {
408 paypal_erreur("Paiement annulé", false);
409 }
410 }
411
412 /* on extrait les informations sur l'utilisateur */
413 $user = User::get($uid);
414 if (!$user) {
415 paypal_erreur("uid invalide");
416 }
417
418 /* on extrait la reference de la commande */
419 if (!ereg('-xorg-([0-9]+)$', $fullref, $matches)) {
420 paypal_erreur("référence de commande invalide");
421 }
422
423 $ref = $matches[1];
424 $res = XDB::query('SELECT mail, text, confirmation
425 FROM payments
426 WHERE id = {?}', $ref);
427 if (!list($conf_mail, $conf_title, $conf_text) = $res->fetchOneRow()) {
428 paypal_erreur('référence de commande inconnue');
429 }
430
431 /* on fait l'insertion en base de donnees */
432 XDB::execute("INSERT INTO payment_transactions (id, uid, ref, fullref, amount, pkey, comment)
433 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})",
434 $no_transaction, $user->id(), $ref, $fullref, $montant, $clef, Env::v('comment'));
435
436 // We check if it is an Xnet payment and then update the related ML.
437 $res = XDB::query('SELECT eid
438 FROM group_events
439 WHERE paiement_id = {?}', $ref);
440 if ($eid = $res->fetchOneCell()) {
441 require_once dirname(__FILE__) . '/xnetevents/xnetevents.inc.php';
442 $evt = get_event_detail($eid);
443 subscribe_lists_event($user->id(), $evt, 1, $montant, true);
444 }
445
446 /* on genere le mail de confirmation */
447 $conf_text = str_replace(array('<prenom>', '<nom>', '<promo>', '<montant>', '<salutation>', '<cher>'),
448 array($user->firstName(), $user->lastName(), $user->promo(), $montant,
449 $user->isFemale() ? 'Chère' : 'Cher',
450 $user->isFemale() ? 'Chère' : 'Cher'), $conf_text);
451
452 global $globals;
453 $mymail = new PlMailer();
454 $mymail->setFrom($conf_mail);
455 $mymail->addCc($conf_mail);
456 $mymail->setSubject($conf_title);
457 $mymail->setWikiBody($conf_text);
458 $mymail->sendTo($user);
459
460 /* on envoie les details de la transaction à telepaiement@ */
461 $mymail = new PlMailer();
462 $mymail->setFrom("webmaster@" . $globals->mail->domain);
463 $mymail->addTo($globals->money->email);
464 $mymail->setSubject($conf_title);
465 $msg = 'utilisateur : ' . $user->login() . ' (' . $user->id() . ')' . "\n" .
466 'mail : ' . $user->forlifeEmail() . "\n\n" .
467 "paiement : $conf_title ($conf_mail)\n".
468 "reference : $champ200\n".
469 "montant : $montant\n\n".
470 "dump de REQUEST:\n".
471 var_export($_REQUEST,true);
472 $mymail->setTxtBody($msg);
473 $mymail->send();
474
475 $page->assign('texte', $conf_text);
476 $page->assign('erreur', $erreur);
477 }
478
479 function handler_xnet_payment(&$page, $pid = null)
480 {
481 global $globals;
482
483 $perms = S::v('perms');
484 if (!$perms->hasFlag('groupmember')) {
485 if (is_null($pid)) {
486 return PL_FORBIDDEN;
487 }
488 $res = XDB::query("SELECT 1
489 FROM group_events AS e
490 INNER JOIN group_event_participants AS ep ON (ep.eid = e.eid AND uid = {?})
491 WHERE e.paiement_id = {?} AND e.asso_id = {?}",
492 S::i('uid'), $pid, $globals->asso('id'));
493 if ($res->numRows() == 0) {
494 return PL_FORBIDDEN;
495 }
496 }
497
498 if (!is_null($pid)) {
499 return $this->handler_payment($page, $pid);
500 }
501 $page->changeTpl('payment/xnet.tpl');
502
503 $res = XDB::query(
504 "SELECT id, text, url
505 FROM payments
506 WHERE asso_id = {?} AND NOT FIND_IN_SET('old', flags)
507 ORDER BY id DESC", $globals->asso('id'));
508 $tit = $res->fetchAllAssoc();
509 $page->assign('titles', $tit);
510
511 $trans = array();
512 $event = array();
513 if (may_update()) {
514 static $orders = array('timestamp' => 'p', 'directory_name' => 'a', 'promo' => 'pd', 'comment' => 'p', 'amount' => 'p');
515
516 if (Get::has('order_id') && Get::has('order') && array_key_exists(Get::v('order'), $orders)) {
517 $order_id = Get::i('order_id');
518 $order = Get::v('order');
519 $ordering = ' ORDER BY ' . $orders[$order] . '.' . $order;
520 if (Get::has('order_inv') && Get::i('order_inv') == 1) {
521 $ordering .= ' DESC';
522 $page->assign('order_inv', 0);
523 } else {
524 $page->assign('order_inv', 1);
525 }
526 $page->assign('order_id', $order_id);
527 $page->assign('order', $order);
528 $page->assign('anchor', 'legend_' . $order_id);
529 } else {
530 $order_id = false;
531 $ordering = '';
532 $page->assign('order', false);
533 }
534 } else {
535 $ordering = '';
536 $page->assign('order', false);
537 }
538 foreach($tit as $foo) {
539 $pid = $foo['id'];
540 if (may_update()) {
541 $res = XDB::query('SELECT p.uid, IF(p.timestamp = \'0000-00-00\', 0, p.timestamp) AS date, p.comment, p.amount
542 FROM payment_transactions AS p
543 INNER JOIN accounts AS a ON (a.uid = p.uid)
544 LEFT JOIN account_profiles AS ap ON (ap.uid = p.uid AND FIND_IN_SET(\'owner\', ap.perms))
545 LEFT JOIN profile_display AS pd ON (ap.pid = pd.pid)
546 WHERE p.ref = {?}' . (($order_id == $pid) ? $ordering : ''),
547 $pid);
548 $trans[$pid] = User::getBulkUsersWithUIDs($res->fetchAllAssoc(), 'uid', 'user');
549 $sum = 0;
550 foreach ($trans[$pid] as $i => $t) {
551 $sum += strtr(substr($t['amount'], 0, strpos($t['amount'], 'EUR')), ',', '.');
552 $trans[$pid][$i]['amount'] = str_replace('EUR', '€', $t['amount']);
553 }
554 $trans[$pid][] = array('limit' => true,
555 'amount' => strtr($sum, '.', ',') . ' €');
556 }
557 $res = XDB::iterRow("SELECT e.eid, e.short_name, e.intitule, ep.nb, ei.montant, ep.paid
558 FROM group_events AS e
559 LEFT JOIN group_event_participants AS ep ON (ep.eid = e.eid AND ep.uid = {?})
560 INNER JOIN group_event_items AS ei ON (ep.eid = ei.eid AND ep.item_id = ei.item_id)
561 WHERE e.paiement_id = {?}",
562 S::v('uid'), $pid);
563 $event[$pid] = array();
564 $event[$pid]['paid'] = 0;
565 if ($res->total()) {
566 $event[$pid]['topay'] = 0;
567 while(list($eid, $shortname, $title, $nb, $montant, $paid) = $res->next()) {
568 $event[$pid]['topay'] += ($nb * $montant);
569 $event[$pid]['eid'] = $eid;
570 $event[$pid]['shortname'] = $shortname;
571 $event[$pid]['title'] = $title;
572 $event[$pid]['ins'] = !is_null($nb);
573 $event[$pid]['paid'] = $paid;
574 }
575 }
576 $res = XDB::query('SELECT amount
577 FROM payment_transactions
578 WHERE id = {?} AND uid = {?}', $pid, S::v('uid'));
579 $montants = $res->fetchColumn();
580
581 foreach ($montants as $m) {
582 $p = strtr(substr($m, 0, strpos($m, 'EUR')), ',', '.');
583 $event[$pid]['paid'] += trim($p);
584 }
585 }
586 $page->register_modifier('decode_comment', 'decode_comment');
587 $page->assign('trans', $trans);
588 $page->assign('event', $event);
589 }
590
591 function handler_admin(&$page, $action = 'list', $id = null) {
592 $page->setTitle('Administration - Paiements');
593 $page->assign('title', 'Gestion des télépaiements');
594 $table_editor = new PLTableEditor('admin/payments','payments','id');
595 //$table_editor->add_join_table('payment_transactions','ref',true); => on ne supprime jamais une transaction
596 $table_editor->add_sort_field('flags');
597 $table_editor->add_sort_field('id', true, true);
598 $table_editor->on_delete("UPDATE payments SET flags = 'old' WHERE id = {?}", "Le paiement a été archivé");
599 $table_editor->describe('text', 'intitulé', true);
600 $table_editor->describe('url', 'site web', false);
601 $table_editor->describe('amount_def', 'montant par défaut', false);
602 $table_editor->describe('amount_min', 'montant minimum', false);
603 $table_editor->describe('amount_max', 'montant maximum', false);
604 $table_editor->describe('mail', 'email contact', true);
605 $table_editor->describe('confirmation', 'message confirmation', false);
606
607 // adds a column with the start date of the linked event if there is one
608 $table_editor->add_option_table('group_events', 'group_events.paiement_id = t.id');
609 $table_editor->add_option_field('group_events.debut', 'related_event', 'évènement', 'timestamp');
610
611 $table_editor->apply($page, $action, $id);
612 }
613
614 function handler_adm_transactions(&$page, $payment_id = null, $action = "list", $id = null) {
615 // show transactions. FIXME: should not be modifiable
616 $page->setTitle('Administration - Paiements - Transactions');
617 $page->assign('title', "Liste des transactions pour le paiement {$payment_id}");
618
619 if ($payment_id == null)
620 $page->trigError("Aucun ID de paiement fourni.");
621
622 $table_editor = new PLTableEditor("admin/transactions/{$payment_id}",'payment_transactions','id');
623 $table_editor->set_where_clause(XDB::format('ref = {?}', $payment_id));
624 $table_editor->apply($page, 'list', $id); // only the 'list' action is allowed
625 $page->assign('readonly', 'readonly'); // don't show modification features
626 }
627
628 function handler_adm_bankaccounts(&$page, $action = 'list', $id = null) {
629 // managment of bank account used for money transfert
630 $page->setTitle('Administration - Paiements - RIBs');
631 $page->assign('title', "Liste des RIBs");
632
633 $table_editor = new PLTableEditor('admin/payments/bankaccounts', 'payment_bankaccounts', 'id');
634 $table_editor->describe('asso_id', 'ID du groupe', false);
635 $table_editor->describe('owner', 'titulaire', true);
636 $table_editor->add_option_table('groups', 'groups.id = t.asso_id');
637 $table_editor->add_option_field('groups.diminutif', 'group_name', 'groupe', 'varchar','account');
638
639 // check RIB key
640 if ($action == 'update' && Post::has('account') && !check_rib(Post::v('account'))) {
641 $page->trigError("Le RIB n'est pas valide");
642 $table_editor->apply($page, 'edit', $id);
643 return;
644 }
645
646 $table_editor->apply($page, $action, $id);
647 }
648
649 function handler_adm_methods(&$page, $action = 'list', $id = null) {
650 // show and edit payment methods
651 $page->setTitle('Administration - Paiements - Méthodes');
652 $page->assign('title', 'Méthodes de paiement');
653 $table_editor = new PLTableEditor('admin/payments/methods', 'payment_methods', 'id');
654 $table_editor->apply($page, $action, $id);
655 }
656
657 function handler_adm_reconcile(&$page, $step = 'list', $param = null) {
658 // reconciles logs with transactions
659 // FIXME: the admin is considered to be fair => he doesn't hack the $step value, nor other params
660 $page->setTitle('Administration - Paiements - Réconciliations');
661 $page->changeTpl('payment/reconcile.tpl');
662 $page->assign('step', $step);
663 $list = true;
664
665 // actions
666 if ($step == 'delete' && $param != null) {
667 S::assert_xsrf_token();
668 XDB::execute('DELETE FROM payment_reconcilations WHERE id = {?}', $param);
669 // FIXME: hardcoding !!!
670 XDB::execute('UPDATE payment_transactions SET recon_id = NULL,commission = NULL WHERE recon_id = {?} AND method_id = 2', $param);
671 XDB::execute('UPDATE payment_transactions SET recon_id = NULL WHERE recon_id = {?} AND method_id = 1', $param);
672 $page->trigSuccess("L'entrée " . $param . ' a été supprimée.');
673
674 } elseif ($step == 'edit') {
675 $page->trigError("L'édition n'est pas implémentée.");
676
677 } elseif ($step == 'step5') {
678 $page->trigSuccess("La réconciliation est terminée. Il est maintenant nécessaire de générer les virements.");
679
680 }
681
682 if($list) {
683 // show list of reconciliations, with a "add" button
684 $page->assign('title', 'Réconciliation - Liste');
685 $page->assign('step', 'list');
686
687 $recongps = array();
688
689 $res = XDB::query("SELECT r.id, short_name AS method, period_start, period_end, status,
690 payment_count, sum_amounts, sum_commissions
691 FROM payment_reconcilations AS r
692 LEFT JOIN payment_methods AS m ON (r.method_id = m.id)
693 WHERE recongroup_id IS NULL
694 ORDER BY period_end DESC, period_start DESC");
695 foreach ($res->fetchAllAssoc() as $recon)
696 $recongps[] = array('recons' => array($recon), 'transfers' => array());
697
698 $res = XDB::query("SELECT recongroup_id AS id
699 FROM payment_reconcilations
700 GROUP BY recongroup_id
701 ORDER BY MAX(period_end) DESC, MIN(period_start) DESC");
702 foreach ($res->fetchAllAssoc() as $recongp) {
703 $res = XDB::query("SELECT r.id, short_name AS method, period_start, period_end, status,
704 payment_count, sum_amounts, sum_commissions
705 FROM payment_reconcilations AS r
706 LEFT JOIN payment_methods AS m ON (r.method_id = m.id)
707 WHERE recongroup_id = {?}
708 ORDER BY period_end DESC, period_start DESC",
709 $recongp['id']);
710 $recongp['recons'] = $res->fetchAllAssoc();
711
712 $res = XDB::query('SELECT id, payment_id, amount, account_id, message, date
713 FROM payment_transfers
714 WHERE recongroup_id = {?}',
715 $recongp['id']);
716 $recongp['transfers'] = $res->fetchAllAssoc();
717
718 $recongps[] = $recongp;
719 }
720 $page->assign_by_ref('recongps', $recongps);
721 }
722 }
723
724 function handler_adm_importlogs(&$page, $step, $param = null) {
725 $page->setTitle('Administration - Paiements - Réconciliations');
726 $page->changeTpl('payment/reconcile.tpl');
727 $page->assign('step', $step);
728
729 if (isset($_SESSION['paymentrecon_data'])) {
730 // create temporary table with imported data
731 XDB::execute('CREATE TEMPORARY TABLE payment_tmp (
732 reference VARCHAR(255) PRIMARY KEY,
733 date DATE,
734 amount DECIMAL(9,2),
735 commission DECIMAL(9,2)
736 )');
737 foreach ($_SESSION['paymentrecon_data'] as $i)
738 XDB::execute('INSERT INTO payment_tmp VALUES ({?}, {?}, {?}, {?})',
739 $i['reference'], $i['date'], $i['amount'], $i['commission']);
740 }
741
742 if ($step == 'step1') {
743 $page->assign('title', 'Étape 1');
744 unset($_SESSION['paymentrecon_method']);
745 unset($_SESSION['paymentrecon_data']);
746 unset($_SESSION['paymentrecon_id']);
747
748 // was a payment method choosen ?
749 if ($param != null) {
750 $_SESSION['paymentrecon_method'] = (int)$param;
751 pl_redirect('admin/reconcile/importlogs/step2');
752
753 } else {
754 // ask to choose a payment method
755 $res = XDB::query('SELECT id, text FROM payment_methods');
756 $page->assign('methods', $res->fetchAllAssoc());
757 }
758
759 } elseif ( $step == 'step2' ) {
760 $page->assign('title', 'Étape 2');
761
762 // import logs formated in CVS
763 $fields = array('date', 'reference', 'amount', 'commission');
764 $importer = new PaymentLogsImporter();
765 $importer->apply($page, 'admin/reconcile/importlogs/step2', $fields);
766
767 // if import is finished
768 $result = $importer->get_result();
769 if($result != null) {
770 $_SESSION['paymentrecon_data'] = $result;
771 pl_redirect('admin/reconcile/importlogs/step3');
772 }
773
774 } elseif ($step == 'step3' ) {
775 $page->assign('title', 'Étape 3');
776
777 // compute reconcilation summary data
778 $res = XDB::query('SELECT MIN(date) AS period_start, MAX(date) AS period_end,
779 count(*) AS payment_count, SUM(amount) AS sum_amounts,
780 SUM(commission) AS sum_commissions
781 FROM payment_tmp');
782 $recon = $res->fetchOneAssoc();
783 $recon['method_id'] = $_SESSION['paymentrecon_method'];
784
785 // create reconciliation item in database
786 if(Post::has('next')) {
787 S::assert_xsrf_token();
788
789 // get parameters
790 $recon['period_start'] = preg_replace('/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/', '\3-\2-\1', Post::v('period_start'));
791 $recon['period_end'] = preg_replace('/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/', '\3-\2-\1', Post::v('period_end'));
792 // FIXME: save checks to be done at next step
793
794 // Create reconcilation item in database
795 // FIXME: check if period doesn't overlap with others for the same method_id
796 XDB::execute('INSERT INTO payment_reconcilations (method_id, period_start, period_end,
797 payment_count, sum_amounts, sum_commissions)
798 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
799 $recon['method_id'], $recon['period_start'], $recon['period_end'],
800 $recon['payment_count'], $recon['sum_amounts'], $recon['sum_commissions']);
801 $_SESSION['paymentrecon_id'] = XDB::insertId();
802
803 // reconcile simple cases (trans.commission n'est modifié que s'il vaut NULL)
804 XDB::execute("UPDATE payment_transactions AS trans, payment_tmp AS tmp
805 SET trans.recon_id = {?}, trans.commission=tmp.commission
806 WHERE trans.fullref = tmp.reference
807 AND trans.amount = tmp.amount AND DATE(trans.ts_confirmed) = tmp.date
808 AND (trans.commission IS NULL OR trans.commission = tmp.commission)
809 AND method_id = {?} AND recon_id IS NULL AND status = 'confirmed'",
810 $_SESSION['paymentrecon_id'], $recon['method_id']);
811
812 pl_redirect("admin/reconcile/importlogs/step4");
813
814 // show summary of the imported data + ask form start/end of reconcilation period
815 } else {
816 $recon['period_start'] = preg_replace('/([0-9]{4})-([0-9]{2})-([0-9]{2})/', '\3/\2/\1', $recon['period_start']);
817 $recon['period_end'] = preg_replace('/([0-9]{4})-([0-9]{2})-([0-9]{2})/', '\3/\2/\1', $recon['period_end']);
818 $page->assign('recon', $recon);
819 }
820
821 } elseif ($step == 'step4' ) {
822 $page->assign('title', 'Étape 4');
823
824 // get reconcilation summary informations
825 $res = XDB::query('SELECT * FROM payment_reconcilations WHERE id = {?}', $_SESSION['paymentrecon_id']);
826 $recon = $res->fetchOneAssoc();
827 $page->assign('recon', $recon);
828
829 if (Post::has('force')) {
830 S::assert_xsrf_token();
831 foreach (Post::v('force') as $id => $value) {
832 XDB::execute('UPDATE payment_transactions AS trans, payment_tmp AS tmp
833 SET trans.recon_id = {?}, trans.commission = tmp.commission
834 WHERE trans.id = {?} AND trans.fullref = tmp.reference',
835 $_SESSION['paymentrecon_id'], $id);
836 }
837 $page->trigSuccess('La réconciliation a été forcée pour ' . count(Post::v('force')) . ' transaction(s).');
838
839 } elseif (Post::has('next')) {
840 if (strlen($recon['comments'])< 3 ) {
841 $page->trigError('Le commentaire doit contenir au moins 3 caractères.');
842 } else {
843 XDB::execute("UPDATE payment_reconcilations SET status = 'transfering' WHERE id = {?}", $_SESSION['paymentrecon_id']);
844 pl_redirect('admin/reconcile/step5');
845 }
846
847 } elseif (Post::has('savecomments')) {
848 S::assert_xsrf_token();
849 $recon['comments'] = Post::v('comments');
850 $page->assign('recon', $recon);
851 XDB::execute('UPDATE payment_reconcilations SET comments = {?} WHERE id = {?}', $recon['comments'], $_SESSION['paymentrecon_id']);
852 $page->trigSuccess('Les commentaires ont été enregistrés.');
853 }
854
855 // reconcilation results - ok
856 $res = XDB::query('SELECT count(*), SUM(amount), SUM(commission)
857 FROM payment_transactions
858 WHERE recon_id = {?}',
859 $recon['id']);
860 list($ok_count, $ok_sum_amounts, $ok_sum_coms) = $res->fetchOneRow();
861 $page->assign('ok_count', $ok_count);
862
863 // reconcilation results - ref exists, but some data differs
864 $res = XDB::query('SELECT id, fullref, method_id, ts_confirmed, trans.amount, trans.commission, status, recon_id,
865 reference, date, tmp.amount as amount2, tmp.commission as commission2
866 FROM payment_transactions AS trans
867 INNER JOIN payment_tmp AS tmp ON (trans.fullref = tmp.reference)
868 WHERE trans.recon_id IS NULL OR trans.recon_id != {?}',
869 $recon['id']);
870 $differs = $res->fetchAllAssoc();
871 $page->assign_by_ref('differs', $differs);
872 $page->assign('differ_count', count($differs));
873
874 // reconcilation results - ref doesn't exists in database
875 $res = XDB::query('SELECT tmp.*
876 FROM payment_tmp AS tmp
877 LEFT JOIN payment_transactions AS trans ON (trans.fullref = tmp.reference)
878 WHERE trans.fullref IS NULL');
879 $only_import = $res->fetchAllAssoc();
880 $page->assign_by_ref('only_import', $only_import);
881 $page->assign('onlyim_count', count($only_import));
882
883 // reconcilation results - exists in database but not in import
884 $res = XDB::query('SELECT trans.*
885 FROM payment_transactions AS trans
886 LEFT JOIN payment_tmp AS tmp ON (trans.fullref = tmp.reference)
887 WHERE {?} <= DATE(trans.ts_confirmed) AND DATE(trans.ts_confirmed) <= {?}
888 AND tmp.reference IS NULL AND method_id = {?}',
889 $recon['period_start'], $recon['period_end'], $recon['method_id']);
890 $only_database = $res->fetchAllAssoc();
891 $page->assign_by_ref('only_database', $only_database);
892 $page->assign('onlydb_count', count($only_database));
893 }
894 }
895
896 function handler_adm_transfers(&$page, $action = null, $id = null) {
897 // list/log all bank transfers and link them to individual transactions
898
899 if (Post::has('generate')) {
900 $recon_ids = array_keys(Post::v('recon_id'));
901
902 // generate a new reconcilation group ID
903 $res = XDB::query("SELECT MAX(recongroup_id)+1 FROM payment_reconcilations");
904 $recongp_id = $res->fetchOneCell();
905 if ($recongp_id == null) $recongp_id = 1;
906
907 // add reconcilations to group
908 // FIXME: should check if reconcilations are in good status
909 XDB::execute("UPDATE payment_reconcilations
910 SET recongroup_id = {?}, status = 'closed'
911 WHERE id IN {?}",
912 $recongp_id, $recon_ids);
913
914 // create transfers
915 XDB::execute('INSERT INTO payment_transfers
916 SELECT NULL, {?}, t.ref, SUM(t.amount+t.commission), NULL, p.text, NULL
917 FROM payment_transactions AS t
918 LEFT JOIN payments AS p ON (t.ref = p.id)
919 LEFT JOIN groups AS g ON (p.asso_id = g.id)
920 WHERE t.recon_id IN {?}
921 GROUP BY t.ref',
922 $recongp_id, $recon_ids);
923
924 //$res = XDB::query("SELECT * FROM payment_reconcilations WHERE id IN {?}", $recon_ids);
925 //$recons = $res->fetchAllAssoc();
926
927 $page->trigSuccess('Les virements ont été générés pour ' . count($recon_ids) . ' réconciliations.');
928 $this->handler_adm_reconcile($page);
929
930 } elseif ($action == 'delgroup') {
931 S::assert_xsrf_token();
932 XDB::execute("UPDATE payment_reconcilations
933 SET status = 'transfering', recongroup_id = NULL
934 WHERE recongroup_id = {?}", $id);
935 XDB::execute("DELETE FROM payment_transfers
936 WHERE recongroup_id = {?} AND date IS NULL", $id);
937
938 $page->trigSuccess("Les virements non réalisés ont été supprimé du groupe ".$id.".");
939 $this->handler_adm_reconcile($page);
940
941 } elseif ($action == "confirm") {
942 S::assert_xsrf_token();
943 XDB::execute('UPDATE payment_transfers
944 SET date = NOW()
945 WHERE id = {?}', $id);
946
947 $page->trigSuccess('Virement ' . $id . ' confirmé.');
948 $this->handler_adm_reconcile($page);
949
950 } else {
951 pl_redirect('admin/reconcile');
952 }
953 }
954 }
955
956 class PaymentLogsImporter extends CSVImporter {
957 protected $result;
958
959 public function __construct() {
960 parent::__construct('');
961 $this->registerFunction('systempay_commission', 'Compute BPLC commission', array($this, 'compute_systempay_commission'));
962 $this->registerFunction('payment_id', 'Autocompute payment ID', array($this, 'compute_payment_id'));
963 //$this->forceValue('payment_id','func_payment_id');
964 }
965
966 public function run($action = null, $insert_relation = null, $update_relation = null) {
967 $this->result = array();
968 foreach ($this->data as $line) {
969 $a = $this->makeAssoc($line, $insert_relation);
970 $a['date'] = preg_replace('/([0-9]{2})\/([0-9]{2})\/([0-9]{4}).*/', '\3-\2-\1', $a['date']);
971 $a['amount'] = str_replace(',', '.', $a['amount']);
972 $a['commission'] = str_replace(',', '.', $a['commission']);
973 $this->result[] = $a;
974 }
975 }
976
977 public function get_result() {
978 return $this->result;
979 }
980
981 static public function compute_systempay_commission($line, $key, $relation) {
982 static $EEE_countries = array(
983 'France', 'Allemagne', 'Autriche', 'Belgique', 'Bulgarie', 'Chypre',
984 'Danemark', 'Espagne', 'Estonie', 'Finlande', 'Grèce', 'Hongrie', 'Irlande', 'Islande', 'Italie',
985 'Lettonie', 'Liechtenstein', 'Lituanie', 'Luxembourg', 'Malte', 'Norvège', 'Pays-Bas', 'Pologne',
986 'Portugal', 'Roumanie', 'Royaume-Uni', 'Slovaquie', 'Slovénie', 'Suède', 'République Tchèque'
987 );
988
989 if($key!='commission' || !array_key_exists('carte', $line)) {
990 return null;
991 }
992 $amount = self::getValue($line, 'amount', $relation['amount']);
993 if (in_array($line['pays carte'], $EEE_countries)) {
994 return -0.20 - round($amount * 0.005, 2);
995 } else {
996 return -0.20 - round($amount * 0.005, 2) - 0.76;
997 }
998 }
999
1000 static public function compute_payment_id($line, $key, $relation) {
1001 if ($key != 'payment_id') {
1002 return null;
1003 }
1004 $reference = self::getValue($line, 'reference', $relation['reference']);
1005 if (ereg('-([0-9]+)$', $reference, $matches)) {
1006 return $matches[1];
1007 } else {
1008 return null;
1009 }
1010 }
1011 }
1012
1013 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
1014 ?>