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