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