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