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