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