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