Goes to the payment that was sorted.
[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::v('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 (!list($conf_mail, $conf_title, $conf_text) = $res->fetchOneRow()) {
317 cb_erreur("référence de commande inconnue");
318 }
319
320 /* on extrait le montant */
321 if (Env::v('vads_currency') != '978') {
322 cb_erreur("monnaie autre que l'euro");
323 }
324 $montant = sprintf("%.02f", ((float)Env::v('vads_amount')) / 100) . ' EUR';
325
326 /* on extrait le code de retour */
327 if (Env::v('vads_result') != '00') {
328 cb_erreur('erreur lors du paiement : ?? (' . Env::v('vads_result') . ')');
329 }
330
331 /* on fait l'insertion en base de donnees */
332 XDB::execute('INSERT INTO payment_transactions (id, uid, ref, fullref, amount, pkey, comment)
333 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})',
334 Env::v('vads_trans_date'), $user->id(), $ref, Env::v('vads_order_id'), $montant, '', Env::v('vads_order_info'));
335 echo "Paiement stored.\n";
336
337 // We check if it is an Xnet payment and then update the related ML.
338 $res = XDB::query('SELECT eid
339 FROM group_events
340 WHERE paiement_id = {?}', $ref);
341 if ($eid = $res->fetchOneCell()) {
342 require_once dirname(__FILE__) . '/xnetevents/xnetevents.inc.php';
343 $evt = get_event_detail($eid);
344 subscribe_lists_event($user->id(), $evt, 1, $montant, true);
345 }
346
347 /* on genere le mail de confirmation */
348 $conf_text = str_replace(
349 array('<prenom>', '<nom>', '<promo>', '<montant>', '<salutation>', '<cher>', 'comment>'),
350 array($user->firstName(), $user->lastName(), $user->promo(), $montant,
351 $user->isFemale() ? 'Chère' : 'Cher', $user->isFemale() ? 'Chère' : 'Cher',
352 Env::v('comment')), $conf_text);
353
354 global $globals;
355 $mymail = new PlMailer();
356 $mymail->setFrom($conf_mail);
357 $mymail->addCc($conf_mail);
358 $mymail->setSubject($conf_title);
359 $mymail->setWikiBody($conf_text);
360 $mymail->sendTo($user);
361
362 /* on envoie les details de la transaction à telepaiement@ */
363 $mymail = new PlMailer();
364 $mymail->setFrom("webmaster@" . $globals->mail->domain);
365 $mymail->addTo($globals->money->email);
366 $mymail->setSubject($conf_title);
367 $msg = 'utilisateur : ' . $user->login() . ' (' . $user->id() . ')' . "\n" .
368 'mail : ' . $user->forlifeEmail() . "\n\n" .
369 "paiement : $conf_title ($conf_mail)\n".
370 "reference : " . Env::v('vads_order_id') . "\n".
371 "montant : $montant\n\n".
372 "dump de REQUEST:\n".
373 var_export($_REQUEST,true);
374 $mymail->setTxtBody($msg);
375 $mymail->send();
376 echo "Notifications sent.\n";
377 exit;
378 }
379
380 function handler_paypal_return(&$page, $uid = null)
381 {
382 $page->changeTpl('payment/retour_paypal.tpl');
383
384 /* reference banque (numero de transaction) */
385 $no_transaction = Env::s('tx');
386 /* token a renvoyer pour avoir plus d'information */
387 $clef = Env::s('sig');
388 /* code retour */
389 $status = Env::s('st');
390 /* raison */
391 $reason = ($status == 'Pending') ? Env::s('pending_reason') : Env::s('reason_code');
392 /* reference complete de la commande */
393 $fullref = Env::s('cm');
394 /* montant de la transaction */
395 $montant_nb = Env::s('amt');
396 /* devise */
397 $montant_dev = Env::s('cc');
398 $montant = "$montant_nb $montant_dev";
399
400 /* on extrait le code de retour */
401 if ($status != "Completed") {
402 if ($status) {
403 paypal_erreur("erreur lors du paiement : $status - $reason");
404 } else {
405 paypal_erreur("Paiement annulé", false);
406 }
407 }
408
409 /* on extrait les informations sur l'utilisateur */
410 $user = User::get($uid);
411 if (!$user) {
412 paypal_erreur("uid invalide");
413 }
414
415 /* on extrait la reference de la commande */
416 if (!ereg('-xorg-([0-9]+)$', $fullref, $matches)) {
417 paypal_erreur("référence de commande invalide");
418 }
419
420 $ref = $matches[1];
421 $res = XDB::query('SELECT mail, text, confirmation
422 FROM payments
423 WHERE id = {?}', $ref);
424 if (!list($conf_mail, $conf_title, $conf_text) = $res->fetchOneRow()) {
425 paypal_erreur('référence de commande inconnue');
426 }
427
428 /* on fait l'insertion en base de donnees */
429 XDB::execute("INSERT INTO payment_transactions (id, uid, ref, fullref, amount, pkey, comment)
430 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})",
431 $no_transaction, $user->id(), $ref, $fullref, $montant, $clef, Env::v('comment'));
432
433 // We check if it is an Xnet payment and then update the related ML.
434 $res = XDB::query('SELECT eid
435 FROM group_events
436 WHERE paiement_id = {?}', $ref);
437 if ($eid = $res->fetchOneCell()) {
438 require_once dirname(__FILE__) . '/xnetevents/xnetevents.inc.php';
439 $evt = get_event_detail($eid);
440 subscribe_lists_event($user->id(), $evt, 1, $montant, true);
441 }
442
443 /* on genere le mail de confirmation */
444 $conf_text = str_replace(array('<prenom>', '<nom>', '<promo>', '<montant>', '<salutation>', '<cher>'),
445 array($user->firstName(), $user->lastName(), $user->promo(), $montant,
446 $user->isFemale() ? 'Chère' : 'Cher',
447 $user->isFemale() ? 'Chère' : 'Cher'), $conf_text);
448
449 global $globals;
450 $mymail = new PlMailer();
451 $mymail->setFrom($conf_mail);
452 $mymail->addCc($conf_mail);
453 $mymail->setSubject($conf_title);
454 $mymail->setWikiBody($conf_text);
455 $mymail->sendTo($user);
456
457 /* on envoie les details de la transaction à telepaiement@ */
458 $mymail = new PlMailer();
459 $mymail->setFrom("webmaster@" . $globals->mail->domain);
460 $mymail->addTo($globals->money->email);
461 $mymail->setSubject($conf_title);
462 $msg = 'utilisateur : ' . $user->login() . ' (' . $user->id() . ')' . "\n" .
463 'mail : ' . $user->forlifeEmail() . "\n\n" .
464 "paiement : $conf_title ($conf_mail)\n".
465 "reference : $champ200\n".
466 "montant : $montant\n\n".
467 "dump de REQUEST:\n".
468 var_export($_REQUEST,true);
469 $mymail->setTxtBody($msg);
470 $mymail->send();
471
472 $page->assign('texte', $conf_text);
473 $page->assign('erreur', $erreur);
474 }
475
476 function handler_xnet_payment(&$page, $pid = null)
477 {
478 global $globals;
479
480 $perms = S::v('perms');
481 if (!$perms->hasFlag('groupmember')) {
482 if (is_null($pid)) {
483 return PL_FORBIDDEN;
484 }
485 $res = XDB::query("SELECT 1
486 FROM group_events AS e
487 INNER JOIN group_event_participants AS ep ON (ep.eid = e.eid AND uid = {?})
488 WHERE e.paiement_id = {?} AND e.asso_id = {?}",
489 S::i('uid'), $pid, $globals->asso('id'));
490 if ($res->numRows() == 0) {
491 return PL_FORBIDDEN;
492 }
493 }
494
495 if (!is_null($pid)) {
496 return $this->handler_payment($page, $pid);
497 }
498 $page->changeTpl('payment/xnet.tpl');
499
500 $res = XDB::query(
501 "SELECT id, text, url
502 FROM payments
503 WHERE asso_id = {?} AND NOT FIND_IN_SET('old', flags)
504 ORDER BY id DESC", $globals->asso('id'));
505 $tit = $res->fetchAllAssoc();
506 $page->assign('titles', $tit);
507
508 $trans = array();
509 $event = array();
510 if (may_update()) {
511 static $orders = array('timestamp' => 'p', 'directory_name' => 'a', 'promo' => 'pd', 'comment' => 'p', 'amount' => 'p');
512
513 if (Get::has('order_id') && Get::has('order') && array_key_exists(Get::v('order'), $orders)) {
514 $order_id = Get::i('order_id');
515 $order = Get::v('order');
516 $ordering = ' ORDER BY ' . $orders[$order] . '.' . $order;
517 if (Get::has('order_inv') && Get::i('order_inv') == 1) {
518 $ordering .= ' DESC';
519 $page->assign('order_inv', 0);
520 } else {
521 $page->assign('order_inv', 1);
522 }
523 $page->assign('order_id', $order_id);
524 $page->assign('order', $order);
525 $page->assign('anchor', 'legend_' . $order_id);
526 } else {
527 $order_id = false;
528 $ordering = '';
529 $page->assign('order', false);
530 }
531 } else {
532 $ordering = '';
533 $page->assign('order', false);
534 }
535 foreach($tit as $foo) {
536 $pid = $foo['id'];
537 if (may_update()) {
538 $res = XDB::query('SELECT p.uid, IF(p.timestamp = \'0000-00-00\', 0, p.timestamp) AS date, p.comment, p.amount
539 FROM payment_transactions AS p
540 INNER JOIN accounts AS a ON (a.uid = p.uid)
541 LEFT JOIN account_profiles AS ap ON (ap.uid = p.uid AND FIND_IN_SET(\'owner\', ap.perms))
542 LEFT JOIN profile_display AS pd ON (ap.pid = pd.pid)
543 WHERE p.ref = {?}' . (($order_id == $pid) ? $ordering : ''),
544 $pid);
545 $trans[$pid] = User::getBulkUsersWithUIDs($res->fetchAllAssoc(), 'uid', 'user');
546 $sum = 0;
547 foreach ($trans[$pid] as $i => $t) {
548 $sum += strtr(substr($t['amount'], 0, strpos($t['amount'], 'EUR')), ',', '.');
549 $trans[$pid][$i]['amount'] = str_replace('EUR', '€', $t['amount']);
550 }
551 $trans[$pid][] = array('limit' => true,
552 'amount' => strtr($sum, '.', ',') . ' €');
553 }
554 $res = XDB::iterRow("SELECT e.eid, e.short_name, e.intitule, ep.nb, ei.montant, ep.paid
555 FROM group_events AS e
556 LEFT JOIN group_event_participants AS ep ON (ep.eid = e.eid AND ep.uid = {?})
557 INNER JOIN group_event_items AS ei ON (ep.eid = ei.eid AND ep.item_id = ei.item_id)
558 WHERE e.paiement_id = {?}",
559 S::v('uid'), $pid);
560 $event[$pid] = array();
561 $event[$pid]['paid'] = 0;
562 if ($res->total()) {
563 $event[$pid]['topay'] = 0;
564 while(list($eid, $shortname, $title, $nb, $montant, $paid) = $res->next()) {
565 $event[$pid]['topay'] += ($nb * $montant);
566 $event[$pid]['eid'] = $eid;
567 $event[$pid]['shortname'] = $shortname;
568 $event[$pid]['title'] = $title;
569 $event[$pid]['ins'] = !is_null($nb);
570 $event[$pid]['paid'] = $paid;
571 }
572 }
573 $res = XDB::query('SELECT amount
574 FROM payment_transactions
575 WHERE id = {?} AND uid = {?}', $pid, S::v('uid'));
576 $montants = $res->fetchColumn();
577
578 foreach ($montants as $m) {
579 $p = strtr(substr($m, 0, strpos($m, 'EUR')), ',', '.');
580 $event[$pid]['paid'] += trim($p);
581 }
582 }
583 $page->register_modifier('decode_comment', 'decode_comment');
584 $page->assign('trans', $trans);
585 $page->assign('event', $event);
586 }
587
588 function handler_admin(&$page, $action = 'list', $id = null) {
589 $page->setTitle('Administration - Paiements');
590 $page->assign('title', 'Gestion des télépaiements');
591 $table_editor = new PLTableEditor('admin/payments','payments','id');
592 //$table_editor->add_join_table('payment_transactions','ref',true); => on ne supprime jamais une transaction
593 $table_editor->add_sort_field('flags');
594 $table_editor->add_sort_field('id', true, true);
595 $table_editor->on_delete("UPDATE payments SET flags = 'old' WHERE id = {?}", "Le paiement a été archivé");
596 $table_editor->describe('text', 'intitulé', true);
597 $table_editor->describe('url', 'site web', false);
598 $table_editor->describe('amount_def', 'montant par défaut', false);
599 $table_editor->describe('amount_min', 'montant minimum', false);
600 $table_editor->describe('amount_max', 'montant maximum', false);
601 $table_editor->describe('mail', 'email contact', true);
602 $table_editor->describe('confirmation', 'message confirmation', false);
603
604 // adds a column with the start date of the linked event if there is one
605 $table_editor->add_option_table('group_events', 'group_events.paiement_id = t.id');
606 $table_editor->add_option_field('group_events.debut', 'related_event', 'évènement', 'timestamp');
607
608 $table_editor->apply($page, $action, $id);
609 }
610
611 function handler_adm_transactions(&$page, $payment_id = null, $action = "list", $id = null) {
612 // show transactions. FIXME: should not be modifiable
613 $page->setTitle('Administration - Paiements - Transactions');
614 $page->assign('title', "Liste des transactions pour le paiement {$payment_id}");
615
616 if ($payment_id == null)
617 $page->trigError("Aucun ID de paiement fourni.");
618
619 $table_editor = new PLTableEditor("admin/transactions/{$payment_id}",'payment_transactions','id');
620 $table_editor->set_where_clause(XDB::format('ref = {?}', $payment_id));
621 $table_editor->apply($page, 'list', $id); // only the 'list' action is allowed
622 $page->assign('readonly', 'readonly'); // don't show modification features
623 }
624
625 function handler_adm_bankaccounts(&$page, $action = 'list', $id = null) {
626 // managment of bank account used for money transfert
627 $page->setTitle('Administration - Paiements - RIBs');
628 $page->assign('title', "Liste des RIBs");
629
630 $table_editor = new PLTableEditor('admin/payments/bankaccounts', 'payment_bankaccounts', 'id');
631 $table_editor->describe('asso_id', 'ID du groupe', false);
632 $table_editor->describe('owner', 'titulaire', true);
633 $table_editor->add_option_table('groups', 'groups.id = t.asso_id');
634 $table_editor->add_option_field('groups.diminutif', 'group_name', 'groupe', 'varchar','account');
635
636 // check RIB key
637 if ($action == 'update' && Post::has('account') && !check_rib(Post::v('account'))) {
638 $page->trigError("Le RIB n'est pas valide");
639 $table_editor->apply($page, 'edit', $id);
640 return;
641 }
642
643 $table_editor->apply($page, $action, $id);
644 }
645
646 function handler_adm_methods(&$page, $action = 'list', $id = null) {
647 // show and edit payment methods
648 $page->setTitle('Administration - Paiements - Méthodes');
649 $page->assign('title', 'Méthodes de paiement');
650 $table_editor = new PLTableEditor('admin/payments/methods', 'payment_methods', 'id');
651 $table_editor->apply($page, $action, $id);
652 }
653
654 function handler_adm_reconcile(&$page, $step = 'list', $param = null) {
655 // reconciles logs with transactions
656 // FIXME: the admin is considered to be fair => he doesn't hack the $step value, nor other params
657 $page->setTitle('Administration - Paiements - Réconciliations');
658 $page->changeTpl('payment/reconcile.tpl');
659 $page->assign('step', $step);
660 $list = true;
661
662 // actions
663 if ($step == 'delete' && $param != null) {
664 S::assert_xsrf_token();
665 XDB::execute('DELETE FROM payment_reconcilations WHERE id = {?}', $param);
666 // FIXME: hardcoding !!!
667 XDB::execute('UPDATE payment_transactions SET recon_id = NULL,commission = NULL WHERE recon_id = {?} AND method_id = 2', $param);
668 XDB::execute('UPDATE payment_transactions SET recon_id = NULL WHERE recon_id = {?} AND method_id = 1', $param);
669 $page->trigSuccess("L'entrée " . $param . ' a été supprimée.');
670
671 } elseif ($step == 'edit') {
672 $page->trigError("L'édition n'est pas implémentée.");
673
674 } elseif ($step == 'step5') {
675 $page->trigSuccess("La réconciliation est terminée. Il est maintenant nécessaire de générer les virements.");
676
677 }
678
679 if($list) {
680 // show list of reconciliations, with a "add" button
681 $page->assign('title', 'Réconciliation - Liste');
682 $page->assign('step', 'list');
683
684 $recongps = array();
685
686 $res = XDB::query("SELECT r.id, short_name AS method, period_start, period_end, status,
687 payment_count, sum_amounts, sum_commissions
688 FROM payment_reconcilations AS r
689 LEFT JOIN payment_methods AS m ON (r.method_id = m.id)
690 WHERE recongroup_id IS NULL
691 ORDER BY period_end DESC, period_start DESC");
692 foreach ($res->fetchAllAssoc() as $recon)
693 $recongps[] = array('recons' => array($recon), 'transfers' => array());
694
695 $res = XDB::query("SELECT recongroup_id AS id
696 FROM payment_reconcilations
697 GROUP BY recongroup_id
698 ORDER BY MAX(period_end) DESC, MIN(period_start) DESC");
699 foreach ($res->fetchAllAssoc() as $recongp) {
700 $res = XDB::query("SELECT r.id, short_name AS method, period_start, period_end, status,
701 payment_count, sum_amounts, sum_commissions
702 FROM payment_reconcilations AS r
703 LEFT JOIN payment_methods AS m ON (r.method_id = m.id)
704 WHERE recongroup_id = {?}
705 ORDER BY period_end DESC, period_start DESC",
706 $recongp['id']);
707 $recongp['recons'] = $res->fetchAllAssoc();
708
709 $res = XDB::query('SELECT id, payment_id, amount, account_id, message, date
710 FROM payment_transfers
711 WHERE recongroup_id = {?}',
712 $recongp['id']);
713 $recongp['transfers'] = $res->fetchAllAssoc();
714
715 $recongps[] = $recongp;
716 }
717 $page->assign_by_ref('recongps', $recongps);
718 }
719 }
720
721 function handler_adm_importlogs(&$page, $step, $param = null) {
722 $page->setTitle('Administration - Paiements - Réconciliations');
723 $page->changeTpl('payment/reconcile.tpl');
724 $page->assign('step', $step);
725
726 if (isset($_SESSION['paymentrecon_data'])) {
727 // create temporary table with imported data
728 XDB::execute('CREATE TEMPORARY TABLE payment_tmp (
729 reference VARCHAR(255) PRIMARY KEY,
730 date DATE,
731 amount DECIMAL(9,2),
732 commission DECIMAL(9,2)
733 )');
734 foreach ($_SESSION['paymentrecon_data'] as $i)
735 XDB::execute('INSERT INTO payment_tmp VALUES ({?}, {?}, {?}, {?})',
736 $i['reference'], $i['date'], $i['amount'], $i['commission']);
737 }
738
739 if ($step == 'step1') {
740 $page->assign('title', 'Étape 1');
741 unset($_SESSION['paymentrecon_method']);
742 unset($_SESSION['paymentrecon_data']);
743 unset($_SESSION['paymentrecon_id']);
744
745 // was a payment method choosen ?
746 if ($param != null) {
747 $_SESSION['paymentrecon_method'] = (int)$param;
748 pl_redirect('admin/reconcile/importlogs/step2');
749
750 } else {
751 // ask to choose a payment method
752 $res = XDB::query('SELECT id, text FROM payment_methods');
753 $page->assign('methods', $res->fetchAllAssoc());
754 }
755
756 } elseif ( $step == 'step2' ) {
757 $page->assign('title', 'Étape 2');
758
759 // import logs formated in CVS
760 $fields = array('date', 'reference', 'amount', 'commission');
761 $importer = new PaymentLogsImporter();
762 $importer->apply($page, 'admin/reconcile/importlogs/step2', $fields);
763
764 // if import is finished
765 $result = $importer->get_result();
766 if($result != null) {
767 $_SESSION['paymentrecon_data'] = $result;
768 pl_redirect('admin/reconcile/importlogs/step3');
769 }
770
771 } elseif ($step == 'step3' ) {
772 $page->assign('title', 'Étape 3');
773
774 // compute reconcilation summary data
775 $res = XDB::query('SELECT MIN(date) AS period_start, MAX(date) AS period_end,
776 count(*) AS payment_count, SUM(amount) AS sum_amounts,
777 SUM(commission) AS sum_commissions
778 FROM payment_tmp');
779 $recon = $res->fetchOneAssoc();
780 $recon['method_id'] = $_SESSION['paymentrecon_method'];
781
782 // create reconciliation item in database
783 if(Post::has('next')) {
784 S::assert_xsrf_token();
785
786 // get parameters
787 $recon['period_start'] = preg_replace('/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/', '\3-\2-\1', Post::v('period_start'));
788 $recon['period_end'] = preg_replace('/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/', '\3-\2-\1', Post::v('period_end'));
789 // FIXME: save checks to be done at next step
790
791 // Create reconcilation item in database
792 // FIXME: check if period doesn't overlap with others for the same method_id
793 XDB::execute('INSERT INTO payment_reconcilations (method_id, period_start, period_end,
794 payment_count, sum_amounts, sum_commissions)
795 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
796 $recon['method_id'], $recon['period_start'], $recon['period_end'],
797 $recon['payment_count'], $recon['sum_amounts'], $recon['sum_commissions']);
798 $_SESSION['paymentrecon_id'] = XDB::insertId();
799
800 // reconcile simple cases (trans.commission n'est modifié que s'il vaut NULL)
801 XDB::execute("UPDATE payment_transactions AS trans, payment_tmp AS tmp
802 SET trans.recon_id = {?}, trans.commission=tmp.commission
803 WHERE trans.fullref = tmp.reference
804 AND trans.amount = tmp.amount AND DATE(trans.ts_confirmed) = tmp.date
805 AND (trans.commission IS NULL OR trans.commission = tmp.commission)
806 AND method_id = {?} AND recon_id IS NULL AND status = 'confirmed'",
807 $_SESSION['paymentrecon_id'], $recon['method_id']);
808
809 pl_redirect("admin/reconcile/importlogs/step4");
810
811 // show summary of the imported data + ask form start/end of reconcilation period
812 } else {
813 $recon['period_start'] = preg_replace('/([0-9]{4})-([0-9]{2})-([0-9]{2})/', '\3/\2/\1', $recon['period_start']);
814 $recon['period_end'] = preg_replace('/([0-9]{4})-([0-9]{2})-([0-9]{2})/', '\3/\2/\1', $recon['period_end']);
815 $page->assign('recon', $recon);
816 }
817
818 } elseif ($step == 'step4' ) {
819 $page->assign('title', 'Étape 4');
820
821 // get reconcilation summary informations
822 $res = XDB::query('SELECT * FROM payment_reconcilations WHERE id = {?}', $_SESSION['paymentrecon_id']);
823 $recon = $res->fetchOneAssoc();
824 $page->assign('recon', $recon);
825
826 if (Post::has('force')) {
827 S::assert_xsrf_token();
828 foreach (Post::v('force') as $id => $value) {
829 XDB::execute('UPDATE payment_transactions AS trans, payment_tmp AS tmp
830 SET trans.recon_id = {?}, trans.commission = tmp.commission
831 WHERE trans.id = {?} AND trans.fullref = tmp.reference',
832 $_SESSION['paymentrecon_id'], $id);
833 }
834 $page->trigSuccess('La réconciliation a été forcée pour ' . count(Post::v('force')) . ' transaction(s).');
835
836 } elseif (Post::has('next')) {
837 if (strlen($recon['comments'])< 3 ) {
838 $page->trigError('Le commentaire doit contenir au moins 3 caractères.');
839 } else {
840 XDB::execute("UPDATE payment_reconcilations SET status = 'transfering' WHERE id = {?}", $_SESSION['paymentrecon_id']);
841 pl_redirect('admin/reconcile/step5');
842 }
843
844 } elseif (Post::has('savecomments')) {
845 S::assert_xsrf_token();
846 $recon['comments'] = Post::v('comments');
847 $page->assign('recon', $recon);
848 XDB::execute('UPDATE payment_reconcilations SET comments = {?} WHERE id = {?}', $recon['comments'], $_SESSION['paymentrecon_id']);
849 $page->trigSuccess('Les commentaires ont été enregistrés.');
850 }
851
852 // reconcilation results - ok
853 $res = XDB::query('SELECT count(*), SUM(amount), SUM(commission)
854 FROM payment_transactions
855 WHERE recon_id = {?}',
856 $recon['id']);
857 list($ok_count, $ok_sum_amounts, $ok_sum_coms) = $res->fetchOneRow();
858 $page->assign('ok_count', $ok_count);
859
860 // reconcilation results - ref exists, but some data differs
861 $res = XDB::query('SELECT id, fullref, method_id, ts_confirmed, trans.amount, trans.commission, status, recon_id,
862 reference, date, tmp.amount as amount2, tmp.commission as commission2
863 FROM payment_transactions AS trans
864 INNER JOIN payment_tmp AS tmp ON (trans.fullref = tmp.reference)
865 WHERE trans.recon_id IS NULL OR trans.recon_id != {?}',
866 $recon['id']);
867 $differs = $res->fetchAllAssoc();
868 $page->assign_by_ref('differs', $differs);
869 $page->assign('differ_count', count($differs));
870
871 // reconcilation results - ref doesn't exists in database
872 $res = XDB::query('SELECT tmp.*
873 FROM payment_tmp AS tmp
874 LEFT JOIN payment_transactions AS trans ON (trans.fullref = tmp.reference)
875 WHERE trans.fullref IS NULL');
876 $only_import = $res->fetchAllAssoc();
877 $page->assign_by_ref('only_import', $only_import);
878 $page->assign('onlyim_count', count($only_import));
879
880 // reconcilation results - exists in database but not in import
881 $res = XDB::query('SELECT trans.*
882 FROM payment_transactions AS trans
883 LEFT JOIN payment_tmp AS tmp ON (trans.fullref = tmp.reference)
884 WHERE {?} <= DATE(trans.ts_confirmed) AND DATE(trans.ts_confirmed) <= {?}
885 AND tmp.reference IS NULL AND method_id = {?}',
886 $recon['period_start'], $recon['period_end'], $recon['method_id']);
887 $only_database = $res->fetchAllAssoc();
888 $page->assign_by_ref('only_database', $only_database);
889 $page->assign('onlydb_count', count($only_database));
890 }
891 }
892
893 function handler_adm_transfers(&$page, $action = null, $id = null) {
894 // list/log all bank transfers and link them to individual transactions
895
896 if (Post::has('generate')) {
897 $recon_ids = array_keys(Post::v('recon_id'));
898
899 // generate a new reconcilation group ID
900 $res = XDB::query("SELECT MAX(recongroup_id)+1 FROM payment_reconcilations");
901 $recongp_id = $res->fetchOneCell();
902 if ($recongp_id == null) $recongp_id = 1;
903
904 // add reconcilations to group
905 // FIXME: should check if reconcilations are in good status
906 XDB::execute("UPDATE payment_reconcilations
907 SET recongroup_id = {?}, status = 'closed'
908 WHERE id IN {?}",
909 $recongp_id, $recon_ids);
910
911 // create transfers
912 XDB::execute('INSERT INTO payment_transfers
913 SELECT NULL, {?}, t.ref, SUM(t.amount+t.commission), NULL, p.text, NULL
914 FROM payment_transactions AS t
915 LEFT JOIN payments AS p ON (t.ref = p.id)
916 LEFT JOIN groups AS g ON (p.asso_id = g.id)
917 WHERE t.recon_id IN {?}
918 GROUP BY t.ref',
919 $recongp_id, $recon_ids);
920
921 //$res = XDB::query("SELECT * FROM payment_reconcilations WHERE id IN {?}", $recon_ids);
922 //$recons = $res->fetchAllAssoc();
923
924 $page->trigSuccess('Les virements ont été générés pour ' . count($recon_ids) . ' réconciliations.');
925 $this->handler_adm_reconcile($page);
926
927 } elseif ($action == 'delgroup') {
928 S::assert_xsrf_token();
929 XDB::execute("UPDATE payment_reconcilations
930 SET status = 'transfering', recongroup_id = NULL
931 WHERE recongroup_id = {?}", $id);
932 XDB::execute("DELETE FROM payment_transfers
933 WHERE recongroup_id = {?} AND date IS NULL", $id);
934
935 $page->trigSuccess("Les virements non réalisés ont été supprimé du groupe ".$id.".");
936 $this->handler_adm_reconcile($page);
937
938 } elseif ($action == "confirm") {
939 S::assert_xsrf_token();
940 XDB::execute('UPDATE payment_transfers
941 SET date = NOW()
942 WHERE id = {?}', $id);
943
944 $page->trigSuccess('Virement ' . $id . ' confirmé.');
945 $this->handler_adm_reconcile($page);
946
947 } else {
948 pl_redirect('admin/reconcile');
949 }
950 }
951 }
952
953 class PaymentLogsImporter extends CSVImporter {
954 protected $result;
955
956 public function __construct() {
957 parent::__construct('');
958 $this->registerFunction('systempay_commission', 'Compute BPLC commission', array($this, 'compute_systempay_commission'));
959 $this->registerFunction('payment_id', 'Autocompute payment ID', array($this, 'compute_payment_id'));
960 //$this->forceValue('payment_id','func_payment_id');
961 }
962
963 public function run($action = null, $insert_relation = null, $update_relation = null) {
964 $this->result = array();
965 foreach ($this->data as $line) {
966 $a = $this->makeAssoc($line, $insert_relation);
967 $a['date'] = preg_replace('/([0-9]{2})\/([0-9]{2})\/([0-9]{4}).*/', '\3-\2-\1', $a['date']);
968 $a['amount'] = str_replace(',', '.', $a['amount']);
969 $a['commission'] = str_replace(',', '.', $a['commission']);
970 $this->result[] = $a;
971 }
972 }
973
974 public function get_result() {
975 return $this->result;
976 }
977
978 static public function compute_systempay_commission($line, $key, $relation) {
979 static $EEE_countries = array(
980 'France', 'Allemagne', 'Autriche', 'Belgique', 'Bulgarie', 'Chypre',
981 'Danemark', 'Espagne', 'Estonie', 'Finlande', 'Grèce', 'Hongrie', 'Irlande', 'Islande', 'Italie',
982 'Lettonie', 'Liechtenstein', 'Lituanie', 'Luxembourg', 'Malte', 'Norvège', 'Pays-Bas', 'Pologne',
983 'Portugal', 'Roumanie', 'Royaume-Uni', 'Slovaquie', 'Slovénie', 'Suède', 'République Tchèque'
984 );
985
986 if($key!='commission' || !array_key_exists('carte', $line)) {
987 return null;
988 }
989 $amount = self::getValue($line, 'amount', $relation['amount']);
990 if (in_array($line['pays carte'], $EEE_countries)) {
991 return -0.20 - round($amount * 0.005, 2);
992 } else {
993 return -0.20 - round($amount * 0.005, 2) - 0.76;
994 }
995 }
996
997 static public function compute_payment_id($line, $key, $relation) {
998 if ($key != 'payment_id') {
999 return null;
1000 }
1001 $reference = self::getValue($line, 'reference', $relation['reference']);
1002 if (ereg('-([0-9]+)$', $reference, $matches)) {
1003 return $matches[1];
1004 } else {
1005 return null;
1006 }
1007 }
1008 }
1009
1010 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
1011 ?>