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