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