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