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