3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
6 * Galette contributions controller
10 * Copyright © 2020 The Galette Team
12 * This file is part of Galette (http://galette.tuxfamily.org).
14 * Galette is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation, either version 3 of the License, or
17 * (at your option) any later version.
19 * Galette is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License
25 * along with Galette. If not, see <http://www.gnu.org/licenses/>.
27 * @category Controllers
30 * @author Johan Cwiklinski <johan@x-tnd.be>
31 * @copyright 2020 The Galette Team
32 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
34 * @link http://galette.tuxfamily.org
35 * @since Available since 0.9.4dev - 2020-05-08
38 namespace Galette\Controllers\Crud
;
40 use Galette\Controllers\CrudController
;
42 use Slim\Http\Request
;
43 use Slim\Http\Response
;
44 use Galette\Entity\Adherent
;
45 use Galette\Entity\Contribution
;
46 use Galette\Entity\Transaction
;
50 use Galette\Repository\Contributions
;
51 use Galette\Repository\Transactions
;
52 use Galette\Repository\Members
;
53 use Galette\Entity\ContributionsTypes
;
54 use Galette\Core\GaletteMail
;
55 use Galette\Entity\Texts
;
56 use Galette\IO\PdfMembersCards
;
57 use Galette\Repository\PaymentTypes
;
58 use Galette\Core\Links
;
65 * Galette contributions controller
67 * @category Controllers
68 * @name ContributionsController
70 * @author Johan Cwiklinski <johan@x-tnd.be>
71 * @copyright 2020 The Galette Team
72 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
73 * @link http://galette.tuxfamily.org
74 * @since Available since 0.9.4dev - 2020-05-02
77 class ContributionsController
extends CrudController
84 * Only a few things changes in add and edit pages,
85 * boths methods will use this common one.
87 * @param Request $request PSR Request
88 * @param Response $response PSR Response
89 * @param array $args Request arguments
90 * @param Contribution $contrib Contribution instance
94 public function addEditPage(
100 $get = $request->getQueryParams();
102 // contribution types
103 $ct = new ContributionsTypes($this->zdb
);
104 $contributions_types = $ct->getList($args['type'] === 'fee');
108 if (!is_int($contrib->id
)) {
109 // initialiser la structure contribution à vide (nouvelle contribution)
110 $contribution['duree_mois_cotis'] = $this->preferences
->pref_membership_ext
;
113 // template variable declaration
115 if ($args['type'] === 'fee') {
116 $title = _T("Membership fee");
118 $title = _T("Donation");
121 if ($contrib->id
!= '') {
122 $title .= ' (' . _T("modification") . ')';
124 $title .= ' (' . _T("creation") . ')';
129 'id_type_cotis' => 1,
132 'date_debut_cotis' => 1,
133 'date_fin_cotis' => $contrib->isCotis(),
134 'montant_cotis' => $contrib->isCotis() ?
1 : 0
138 'page_title' => $title,
139 'required' => $required,
140 'disabled' => $disabled,
141 'contribution' => $contrib,
142 'adh_selected' => $contrib->member
,
143 'type' => $args['type']
146 // contribution types
147 $params['type_cotis_options'] = $contributions_types;
151 $members = $m->getSelectizedMembers(
153 isset($contrib) && $contrib->member
> 0 ?
$contrib->member
: null
156 $params['members'] = [
157 'filters' => $m->getFilters(),
158 'count' => $m->getCount()
161 if (count($members)) {
162 $params['members']['list'] = $members;
165 $ext_membership = '';
166 if (isset($contrib) && $contrib->isCotis() ||
!isset($contrib) && $args['type'] === 'fee') {
167 $ext_membership = $this->preferences
->pref_membership_ext
;
169 $params['pref_membership_ext'] = $ext_membership;
170 $params['autocomplete'] = true;
175 'ajouter_contribution.tpl',
184 * @param Request $request PSR Request
185 * @param Response $response PSR Response
186 * @param array $args Request arguments
190 public function add(Request
$request, Response
$response, array $args = []) :Response
192 if ($this->session
->contribution
!== null) {
193 $contrib = $this->session
->contribution
;
194 $this->session
->contribution
= null;
196 $get = $request->getQueryParams();
198 $ct = new ContributionsTypes($this->zdb
);
199 $contributions_types = $ct->getList($args['type'] === 'fee');
201 $cparams = ['type' => array_keys($contributions_types)[0]];
204 if (isset($get[Adherent
::PK
]) && $get[Adherent
::PK
] > 0) {
205 $cparams['adh'] = (int)$get[Adherent
::PK
];
210 if (isset($get[Transaction
::PK
]) && $get[Transaction
::PK
] > 0) {
211 $cparams['trans'] = $get[Transaction
::PK
];
214 $contrib = new Contribution(
217 (count($cparams) > 0 ?
$cparams : null)
220 if (isset($cparams['adh'])) {
221 $contrib->member
= $cparams['adh'];
224 if (isset($get['montant_cotis']) && $get['montant_cotis'] > 0) {
225 $contrib->amount
= $get['montant_cotis'];
229 return $this->addEditPage($request, $response, $args, $contrib);
235 * @param Request $request PSR Request
236 * @param Response $response PSR Response
237 * @param array $args Request arguments
241 public function doAdd(Request
$request, Response
$response, array $args = []) :Response
243 $args['action'] = 'add';
244 return $this->store($request, $response, $args);
253 * @param Request $request PSR Request
254 * @param Response $response PSR Response
255 * @param array $args Request arguments
259 public function list(Request
$request, Response
$response, array $args = []) :Response
262 if ($request->isXhr()
263 ||
isset($request->getQueryParams()['ajax'])
264 && $request->getQueryParams()['ajax'] == 'true'
268 $get = $request->getQueryParams();
270 $option = $args['option'] ??
null;
271 $value = $args['value'] ??
null;
274 switch ($args['type']) {
276 $raw_type = 'transactions';
278 case 'contributions':
279 $raw_type = 'contributions';
283 $filter_name = 'filter_' . $raw_type;
285 if (isset($this->session
->$filter_name) && $ajax === false) {
286 $filters = $this->session
->$filter_name;
288 $filter_class = '\\Galette\\Filters\\' . ucwords($raw_type . 'List');
289 $filters = new $filter_class();
293 if (isset($get[Adherent
::PK
]) && $get[Adherent
::PK
] > 0) {
294 $filters->filtre_cotis_adh
= (int)$get[Adherent
::PK
];
298 if (isset($request->getQueryParams()['max_amount'])) {
299 $filters->filtre_transactions
= true;
300 $filters->max_amount
= (int)$request->getQueryParams()['max_amount'];
302 $filters->filtre_transactions
= false;
303 $filters->max_amount
= null;
306 if ($option !== null) {
309 $filters->current_page
= (int)$value;
312 $filters->orderby
= $value;
315 if (($this->login
->isAdmin()
316 ||
$this->login
->isStaff())
318 if ($value == 'all') {
319 $filters->filtre_cotis_adh
= null;
321 $filters->filtre_cotis_adh
= $value;
328 if (!$this->login
->isAdmin() && !$this->login
->isStaff()) {
329 $filters->filtre_cotis_adh
= $this->login
->id
;
332 $class = '\\Galette\\Repository\\' . ucwords($raw_type);
333 $contrib = new $class($this->zdb
, $this->login
, $filters);
334 $contribs_list = $contrib->getList(true);
336 //store filters into session
337 if ($ajax === false) {
338 $this->session
->$filter_name = $filters;
341 //assign pagination variables to the template and add pagination links
342 $filters->setSmartyPagination($this->router
, $this->view
->getSmarty());
345 'page_title' => $raw_type === 'contributions' ?
346 _T("Contributions management") :
347 _T("Transactions management"),
348 'contribs' => $contrib,
349 'list' => $contribs_list,
350 'nb' => $contrib->getCount(),
351 'filters' => $filters,
352 'mode' => ($ajax === true ?
'ajax' : 'std')
355 if ($filters->filtre_cotis_adh
!= null) {
356 $member = new Adherent($this->zdb
);
357 $member->load($filters->filtre_cotis_adh
);
358 $tpl_vars['member'] = $member;
364 'gestion_' . $raw_type . '.tpl',
373 * @param Request $request PSR Request
374 * @param Response $response PSR Response
375 * @param array $args Request arguments
379 public function filter(Request
$request, Response
$response, array $args = []) :Response
382 switch ($args['type']) {
384 $raw_type = 'transactions';
386 case 'contributions':
387 $raw_type = 'contributions';
391 $type = 'filter_' . $raw_type;
392 $post = $request->getParsedBody();
393 $error_detected = [];
395 if ($this->session
->$type !== null) {
396 $filters = $this->session
->$type;
398 $filter_class = '\\Galette\\Filters\\' . ucwords($raw_type) . 'List';
399 $filters = new $filter_class();
402 if (isset($post['clear_filter'])) {
405 if (isset($post['max_amount'])) {
406 $filters->max_amount
= null;
409 if ((isset($post['nbshow']) && is_numeric($post['nbshow']))
411 $filters->show
= $post['nbshow'];
414 if (isset($post['end_date_filter']) ||
isset($post['start_date_filter'])) {
416 if (isset($post['start_date_filter'])) {
417 $field = _T("start date filter");
418 $filters->start_date_filter
= $post['start_date_filter'];
420 if (isset($post['end_date_filter'])) {
421 $field = _T("end date filter");
422 $filters->end_date_filter
= $post['end_date_filter'];
424 } catch (\Exception
$e) {
425 $error_detected[] = $e->getMessage();
429 if (isset($post['payment_type_filter'])) {
430 $ptf = (int)$post['payment_type_filter'];
431 $ptypes = new PaymentTypes(
436 $ptlist = $ptypes->getList();
437 if (isset($ptlist[$ptf])) {
438 $filters->payment_type_filter
= $ptf;
439 } elseif ($ptf == -1) {
440 $filters->payment_type_filter
= null;
442 $error_detected[] = _T("- Unknown payment type!");
447 $this->session
->$type = $filters;
449 if (count($error_detected) > 0) {
451 foreach ($error_detected as $error) {
452 $this->flash
->addMessage(
461 ->withHeader('Location', $this->router
->pathFor('contributions', ['type' => $raw_type]));
470 * @param Request $request PSR Request
471 * @param Response $response PSR Response
472 * @param array $args Request arguments
476 public function edit(Request
$request, Response
$response, array $args = []) :Response
478 if ($this->session
->contribution
!== null) {
479 $contrib = $this->session
->contribution
;
480 $this->session
->contribution
= null;
482 $contrib = new Contribution($this->zdb
, $this->login
, (int)$args['id']);
483 if ($contrib->id
== '') {
484 //not possible to load contribution, exit
485 $this->flash
->addMessage(
490 _T("Unable to load contribution #%id!")
495 ->withHeader('Location', $this->router
->pathFor(
497 ['type' => 'contributions']
502 return $this->addEditPage($request, $response, $args, $contrib);
508 * @param Request $request PSR Request
509 * @param Response $response PSR Response
510 * @param array $args Request arguments
514 public function doEdit(Request
$request, Response
$response, array $args = []) :Response
516 $args['action'] = 'edit';
517 return $this->store($request, $response, $args);
521 * Store contribution (new or existing)
523 * @param Request $request PSR Request
524 * @param Response $response PSR Response
525 * @param array $args Request arguments
529 public function store(Request
$request, Response
$response, array $args = []) :Response
531 $post = $request->getParsedBody();
532 $action = $args['action'];
534 if ($action == 'edit' && isset($post['btnreload'])) {
535 $redirect_url = $this->router
->pathFor($action . 'Contribution', $args);
536 $redirect_url .= '?' . Adherent
::PK
. '=' . $post[Adherent
::PK
] . '&' .
537 ContributionsTypes
::PK
. '=' . $post[ContributionsTypes
::PK
] . '&' .
538 'montant_cotis=' . $post['montant_cotis'];
541 ->withHeader('Location', $redirect_url);
544 $success_detected = [];
545 $error_detected = [];
546 $warning_detected = [];
547 $redirect_url = null;
550 if (isset($args['id'])) {
551 $id_cotis = $args['id'];
554 $id_adh = $post['id_adh'];
556 if ($this->session
->contribution
!== null) {
557 $contrib = $this->session
->contribution
;
558 $this->session
->contribution
= null;
560 if ($id_cotis === null) {
561 $contrib = new Contribution($this->zdb
, $this->login
);
563 $contrib = new Contribution($this->zdb
, $this->login
, (int)$id_cotis);
567 // flagging required fields for first step only
569 'id_type_cotis' => 1,
572 'montant_cotis' => 1, //TODO: not always required, see #196
573 'date_debut_cotis' => 1,
574 'date_fin_cotis' => ($args['type'] === 'fee')
579 $valid = $contrib->check($post, $required, $disabled);
580 if ($valid !== true) {
581 $error_detected = array_merge($error_detected, $valid);
584 if (count($error_detected) == 0) {
585 //all goes well, we can proceed
587 if ($contrib->id
== '') {
591 if (count($error_detected) == 0) {
592 $store = $contrib->store();
593 if ($store === true) {
594 $success_detected[] = _T('Contribution has been successfully stored');
595 //contribution has been stored :)
597 //if an external script has been configured, we call it
598 if ($this->preferences
->pref_new_contrib_script
) {
599 $es = new \Galette\IO\
ExternalScript($this->preferences
);
600 $res = $contrib->executePostScript($es);
603 //send admin an email with all details
604 if ($this->preferences
->pref_mail_method
> GaletteMail
::METHOD_DISABLED
) {
605 $mail = new GaletteMail($this->preferences
);
607 _T("Post contribution script failed")
611 foreach ($this->preferences
->vpref_email_newadh
as $pref_email) {
612 $recipients[$pref_email] = $pref_email;
614 $mail->setRecipients($recipients);
616 $message = _T("The configured post contribution script has failed.");
617 $message .= "\n" . _T("You can find contribution information and script output below.");
621 $mail->setMessage($message);
622 $sent = $mail->send();
625 $txt = _T('Post contribution script has failed.');
626 $this->history
->add($txt, $message);
627 $warning_detected[] = $txt;
628 //Mails are disabled... We log (not safe, but)...
630 'Email to admin has not been sent. Here was the data: ' .
631 "\n" . print_r($res, true),
636 //Mails are disabled... We log (not safe, but)...
638 'Post contribution script has failed. Here was the data: ' .
639 "\n" . print_r($res, true),
647 //something went wrong :'(
648 $error_detected[] = _T("An error occurred while storing the contribution.");
653 if (count($error_detected) == 0) {
654 // Get member information
655 $adh = new Adherent($this->zdb
);
656 $adh->load($contrib->member
);
658 if ($this->preferences
->pref_mail_method
> GaletteMail
::METHOD_DISABLED
) {
663 'name_adh' => custom_html_entity_decode($adh->sname
),
664 'firstname_adh' => custom_html_entity_decode($adh->surname
),
665 'lastname_adh' => custom_html_entity_decode($adh->name
),
666 'mail_adh' => custom_html_entity_decode($adh->getEmail()),
667 'login_adh' => custom_html_entity_decode($adh->login
),
668 'deadline' => custom_html_entity_decode($contrib->end_date
),
669 'contrib_info' => custom_html_entity_decode($contrib->info
),
670 'contrib_amount' => custom_html_entity_decode($contrib->amount
),
671 'contrib_type' => custom_html_entity_decode($contrib->type
->libelle
)
674 if ($new && isset($_POST['mail_confirm'])
675 && $_POST['mail_confirm'] == '1'
677 if (GaletteMail
::isValidEmail($adh->getEmail())) {
679 if (!$contrib->isCotis()) {
682 $mtxt = $texts->getTexts($text, $adh->language
);
684 $mail = new GaletteMail($this->preferences
);
685 $mail->setSubject($texts->getSubject());
686 $mail->setRecipients(
688 $adh->getEmail() => $adh->sname
693 if (strpos($mtxt->tbody
, '{LINK_MEMBERCARD}') !== false) {
694 //member card link is present in mail model, let's add it
695 $links = new Links($this->zdb
);
696 if ($hash = $links->generateNewLink(Links
::TARGET_MEMBERCARD
, $contrib->member
)) {
697 $link_card = $this->preferences
->getURL() .
698 $this->router
->pathFor('directlink', ['hash' => $hash]);
703 if (strpos($mtxt->tbody
, '{LINK_MEMBERCARD}') !== false) {
704 //contribution receipt link is present in mail model, let's add it
705 $links = new Links($this->zdb
);
706 $ltype = $contrib->type
->isExtension() ? Links
::TARGET_INVOICE
: Links
::TARGET_RECEIPT
;
707 if ($hash = $links->generateNewLink($ltype, $contrib->id
)) {
708 $link_pdf = $this->preferences
->getURL() .
709 $this->router
->pathFor('directlink', ['hash' => $hash]);
713 //set replacements, even if empty, to be sure.
714 $texts->setReplaces([
715 'link_membercard' => $link_card,
716 'link_contribpdf' => $link_pdf
719 $mail->setMessage($texts->getBody());
720 $sent = $mail->send();
725 array('/%name/', '/%email/'),
726 array($adh->sname
, $adh->getEmail()),
727 _T("Email sent to user %name (%email)")
732 array('/%name/', '/%email/'),
733 array($adh->sname
, $adh->getEmail()),
734 _T("A problem happened while sending contribution receipt to user %name (%email)")
736 $this->history
->add($txt);
737 $error_detected[] = $txt;
741 array('/%name/', '/%email/'),
742 array($adh->sname
, $adh->getEmail()),
743 _T("Trying to send an email to a member (%name) with an invalid address: %email")
745 $this->history
->add($txt);
746 $warning_detected[] = $txt;
750 // Sent email to admin if pref checked
751 if ($new && $this->preferences
->pref_bool_mailadh
) {
752 // Get email text in database
754 if (!$contrib->isCotis()) {
755 $text = 'newdonation';
757 $mtxt = $texts->getTexts($text, $this->preferences
->pref_lang
);
759 $mail = new GaletteMail($this->preferences
);
760 $mail->setSubject($texts->getSubject());
763 foreach ($this->preferences
->vpref_email_newadh
as $pref_email) {
764 $recipients[$pref_email] = $pref_email;
766 $mail->setRecipients($recipients);
768 $mail->setMessage($texts->getBody());
769 $sent = $mail->send();
774 array('/%name/', '/%email/'),
775 array($adh->sname
, $adh->getEmail()),
776 _T("Email sent to admin for user %name (%email)")
781 array('/%name/', '/%email/'),
782 array($adh->sname
, $adh->getEmail()),
783 _T("A problem happened while sending to admin notification for user %name (%email) contribution")
785 $this->history
->add($txt);
786 $warning_detected[] = $txt;
791 if (count($success_detected) > 0) {
792 foreach ($success_detected as $success) {
793 $this->flash
->addMessage(
801 if (count($warning_detected) > 0) {
802 foreach ($warning_detected as $warning) {
803 $this->flash
->addMessage(
810 if (count($error_detected) == 0) {
811 if ($contrib->isTransactionPart() && $contrib->transaction
->getMissingAmount() > 0) {
813 $redirect_url = $this->router
->pathFor(
816 'type' => $post['contrib_type']
818 ) . '?' . Transaction
::PK
. '=' . $contrib->transaction
->id
.
819 '&' . Adherent
::PK
. '=' . $contrib->member
;
821 //contributions list for member
822 $redirect_url = $this->router
->pathFor(
825 'type' => 'contributions'
827 ) . '?' . Adherent
::PK
. '=' . $contrib->member
;
832 if (count($error_detected) > 0) {
833 //something went wrong.
834 //store entity in session
835 $this->session
->contribution
= $contrib;
836 $redirect_url = $this->router
->pathFor($args['action'] . 'Contribution', $args);
839 foreach ($error_detected as $error) {
840 $this->flash
->addMessage(
846 $this->session
->contribution
= null;
847 if ($redirect_url === null) {
848 $redirect_url = $this->router
->pathFor('contributions', ['type' => $args['type']]);
852 //redirect to calling action
855 ->withHeader('Location', $redirect_url);
862 * Get redirection URI
864 * @param array $args Route arguments
868 public function redirectUri(array $args = [])
870 return $this->router
->pathFor('contributions', ['type' => $args['type']]);
876 * @param array $args Route arguments
880 public function formUri(array $args = [])
882 return $this->router
->pathFor(
883 'doRemoveContribution',
889 * Get confirmation removal page title
891 * @param array $args Route arguments
895 public function confirmRemoveTitle(array $args = [])
899 switch ($args['type']) {
901 $raw_type = 'transactions';
903 case 'contributions':
904 $raw_type = 'contributions';
908 if (isset($args['ids'])) {
910 _T('Remove %1$s %2$s'),
912 ($raw_type === 'contributions') ?
_T('contributions') : _T('transactions')
916 _T('Remove %1$s #%2$s'),
917 ($raw_type === 'contributions') ?
_T('contribution') : _T('transaction'),
926 * @param array $args Route arguments
927 * @param array $post POST values
931 protected function doDelete(array $args, array $post)
934 switch ($args['type']) {
936 $raw_type = 'transactions';
938 case 'contributions':
939 $raw_type = 'contributions';
943 $class = '\\Galette\Repository\\' . ucwords($raw_type);
944 $contribs = new $class($this->zdb
, $this->login
);
945 $rm = $contribs->remove($args['ids'] ??
$args['id'], $this->history
);