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