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