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