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