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