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