Explicitly specify params so we can find problems with comparing translated labels
[civicrm-core.git] / CRM / Contribute / Form / Task / Status.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33
34 /**
35 * This class provides the functionality to email a group of contacts.
36 */
37 class CRM_Contribute_Form_Task_Status extends CRM_Contribute_Form_Task {
38
39 /**
40 * Are we operating in "single mode", i.e. updating the task of only
41 * one specific contribution?
42 *
43 * @var bool
44 */
45 public $_single = FALSE;
46
47 protected $_rows;
48
49 /**
50 * Build all the data structures needed to build the form.
51 */
52 public function preProcess() {
53 $id = CRM_Utils_Request::retrieve('id', 'Positive',
54 $this, FALSE
55 );
56
57 if ($id) {
58 $this->_contributionIds = [$id];
59 $this->_componentClause = " civicrm_contribution.id IN ( $id ) ";
60 $this->_single = TRUE;
61 $this->assign('totalSelectedContributions', 1);
62 }
63 else {
64 parent::preProcess();
65 }
66
67 // check that all the contribution ids have pending status
68 $query = "
69 SELECT count(*)
70 FROM civicrm_contribution
71 WHERE contribution_status_id != 2
72 AND {$this->_componentClause}";
73 $count = CRM_Core_DAO::singleValueQuery($query);
74 if ($count != 0) {
75 CRM_Core_Error::statusBounce(ts('Please select only online contributions with Pending status.'));
76 }
77
78 // we have all the contribution ids, so now we get the contact ids
79 parent::setContactIDs();
80 $this->assign('single', $this->_single);
81 }
82
83 /**
84 * Build the form object.
85 */
86 public function buildQuickForm() {
87 $status = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'label');
88 unset($status[2]);
89 unset($status[5]);
90 unset($status[6]);
91 $this->add('select', 'contribution_status_id',
92 ts('Contribution Status'),
93 $status,
94 TRUE
95 );
96
97 $contribIDs = implode(',', $this->_contributionIds);
98 $query = "
99 SELECT c.id as contact_id,
100 co.id as contribution_id,
101 c.display_name as display_name,
102 co.total_amount as amount,
103 co.receive_date as receive_date,
104 co.source as source,
105 co.payment_instrument_id as paid_by,
106 co.check_number as check_no
107 FROM civicrm_contact c,
108 civicrm_contribution co
109 WHERE co.contact_id = c.id
110 AND co.id IN ( $contribIDs )";
111 $dao = CRM_Core_DAO::executeQuery($query);
112
113 // build a row for each contribution id
114 $this->_rows = [];
115 $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution');
116 $defaults = [];
117 $now = date("Y-m-d");
118 $paidByOptions = ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::paymentInstrument();
119
120 while ($dao->fetch()) {
121 $row['contact_id'] = $dao->contact_id;
122 $row['contribution_id'] = $dao->contribution_id;
123 $row['display_name'] = $dao->display_name;
124 $row['amount'] = $dao->amount;
125 $row['source'] = $dao->source;
126 $row['trxn_id'] = &$this->addElement('text', "trxn_id_{$row['contribution_id']}", ts('Transaction ID'));
127 $this->addRule("trxn_id_{$row['contribution_id']}",
128 ts('This Transaction ID already exists in the database. Include the account number for checks.'),
129 'objectExists',
130 ['CRM_Contribute_DAO_Contribution', $dao->contribution_id, 'trxn_id']
131 );
132
133 $row['fee_amount'] = &$this->add('text', "fee_amount_{$row['contribution_id']}", ts('Fee Amount'),
134 $attributes['fee_amount']
135 );
136 $this->addRule("fee_amount_{$row['contribution_id']}", ts('Please enter a valid amount.'), 'money');
137 $defaults["fee_amount_{$row['contribution_id']}"] = 0.0;
138
139 $row['trxn_date'] = $this->add('datepicker', "trxn_date_{$row['contribution_id']}", ts('Transaction Date'), [], FALSE, ['time' => FALSE]);
140 $defaults["trxn_date_{$row['contribution_id']}"] = $now;
141
142 $this->add("text", "check_number_{$row['contribution_id']}", ts('Check Number'));
143 $defaults["check_number_{$row['contribution_id']}"] = $dao->check_no;
144
145 $this->add("select", "payment_instrument_id_{$row['contribution_id']}", ts('Payment Method'), $paidByOptions);
146 $defaults["payment_instrument_id_{$row['contribution_id']}"] = $dao->paid_by;
147
148 $this->_rows[] = $row;
149 }
150
151 $this->assign_by_ref('rows', $this->_rows);
152 $this->setDefaults($defaults);
153 $this->addButtons([
154 [
155 'type' => 'next',
156 'name' => ts('Update Pending Status'),
157 'isDefault' => TRUE,
158 ],
159 [
160 'type' => 'back',
161 'name' => ts('Cancel'),
162 ],
163 ]);
164
165 $this->addFormRule(['CRM_Contribute_Form_Task_Status', 'formRule']);
166 }
167
168 /**
169 * Global validation rules for the form.
170 *
171 * @param array $fields
172 * Posted values of the form.
173 *
174 * @return array
175 * list of errors to be posted back to the form
176 */
177 public static function formRule($fields) {
178 $seen = $errors = [];
179 foreach ($fields as $name => $value) {
180 if (strpos($name, 'trxn_id_') !== FALSE) {
181 if ($fields[$name]) {
182 if (array_key_exists($value, $seen)) {
183 $errors[$name] = ts('Transaction ID\'s must be unique. Include the account number for checks.');
184 }
185 $seen[$value] = 1;
186 }
187 }
188
189 if ((strpos($name, 'check_number_') !== FALSE) && $value) {
190 $contribID = substr($name, 13);
191
192 if ($fields["payment_instrument_id_{$contribID}"] != CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', 'Check')) {
193 $errors["payment_instrument_id_{$contribID}"] = ts("Payment Method should be Check when a check number is entered for a contribution.");
194 }
195 }
196 }
197 return empty($errors) ? TRUE : $errors;
198 }
199
200 /**
201 * Process the form after the input has been submitted and validated.
202 */
203 public function postProcess() {
204 $params = $this->controller->exportValues($this->_name);
205
206 // submit the form with values.
207 self::processForm($this, $params);
208
209 CRM_Core_Session::setStatus(ts('Contribution status has been updated for selected record(s).'), ts('Status Updated'), 'success');
210 }
211
212 /**
213 * Process the form with submitted params.
214 *
215 * Also supports unit test.
216 *
217 * @param CRM_Core_Form $form
218 * @param array $params
219 *
220 * @throws \Exception
221 */
222 public static function processForm($form, $params) {
223 $statusID = CRM_Utils_Array::value('contribution_status_id', $params);
224 $baseIPN = new CRM_Core_Payment_BaseIPN();
225
226 $transaction = new CRM_Core_Transaction();
227
228 // get the missing pieces for each contribution
229 $contribIDs = implode(',', $form->_contributionIds);
230 $details = self::getDetails($contribIDs);
231 $template = CRM_Core_Smarty::singleton();
232
233 // for each contribution id, we just call the baseIPN stuff
234 foreach ($form->_rows as $row) {
235 $input = $ids = $objects = [];
236 $input['component'] = $details[$row['contribution_id']]['component'];
237
238 $ids['contact'] = $row['contact_id'];
239 $ids['contribution'] = $row['contribution_id'];
240 $ids['contributionRecur'] = NULL;
241 $ids['contributionPage'] = NULL;
242 $ids['membership'] = CRM_Utils_Array::value('membership', $details[$row['contribution_id']]);
243 $ids['participant'] = CRM_Utils_Array::value('participant', $details[$row['contribution_id']]);
244 $ids['event'] = CRM_Utils_Array::value('event', $details[$row['contribution_id']]);
245
246 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
247 CRM_Core_Error::fatal();
248 }
249
250 $contribution = &$objects['contribution'];
251
252 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL,
253 'name'
254 );
255
256 if ($statusID == array_search('Cancelled', $contributionStatuses)) {
257 $baseIPN->cancelled($objects, $transaction);
258 $transaction->commit();
259 continue;
260 }
261 elseif ($statusID == array_search('Failed', $contributionStatuses)) {
262 $baseIPN->failed($objects, $transaction);
263 $transaction->commit();
264 continue;
265 }
266
267 // status is not pending
268 if ($contribution->contribution_status_id != array_search('Pending',
269 $contributionStatuses
270 )
271 ) {
272 $transaction->commit();
273 continue;
274 }
275
276 // set some fake input values so we can reuse IPN code
277 $input['amount'] = $contribution->total_amount;
278 $input['is_test'] = $contribution->is_test;
279 $input['fee_amount'] = $params["fee_amount_{$row['contribution_id']}"];
280 $input['check_number'] = $params["check_number_{$row['contribution_id']}"];
281 $input['payment_instrument_id'] = $params["payment_instrument_id_{$row['contribution_id']}"];
282 $input['net_amount'] = $contribution->total_amount - $input['fee_amount'];
283
284 if (!empty($params["trxn_id_{$row['contribution_id']}"])) {
285 $input['trxn_id'] = trim($params["trxn_id_{$row['contribution_id']}"]);
286 }
287 else {
288 $input['trxn_id'] = $contribution->invoice_id;
289 }
290 $input['trxn_date'] = $params["trxn_date_{$row['contribution_id']}"] . ' ' . date('H:i:s');
291
292 // @todo calling baseIPN like this is a pattern in it's last gasps. Call contribute.completetransaction api.
293 $baseIPN->completeTransaction($input, $ids, $objects, $transaction, FALSE);
294
295 // reset template values before processing next transactions
296 $template->clearTemplateVars();
297 }
298 }
299
300 /**
301 * @param string $contributionIDs
302 *
303 * @return array
304 */
305 public static function &getDetails($contributionIDs) {
306 if (empty($contributionIDs)) {
307 return [];
308 }
309 $query = "
310 SELECT c.id as contribution_id,
311 c.contact_id as contact_id ,
312 mp.membership_id as membership_id ,
313 pp.participant_id as participant_id ,
314 p.event_id as event_id
315 FROM civicrm_contribution c
316 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
317 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
318 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
319 WHERE c.id IN ( $contributionIDs )";
320
321 $rows = [];
322 $dao = CRM_Core_DAO::executeQuery($query);
323
324 while ($dao->fetch()) {
325 $rows[$dao->contribution_id]['component'] = $dao->participant_id ? 'event' : 'contribute';
326 $rows[$dao->contribution_id]['contact'] = $dao->contact_id;
327 if ($dao->membership_id) {
328 if (!array_key_exists('membership', $rows[$dao->contribution_id])) {
329 $rows[$dao->contribution_id]['membership'] = [];
330 }
331 $rows[$dao->contribution_id]['membership'][] = $dao->membership_id;
332 }
333 if ($dao->participant_id) {
334 $rows[$dao->contribution_id]['participant'] = $dao->participant_id;
335 }
336 if ($dao->event_id) {
337 $rows[$dao->contribution_id]['event'] = $dao->event_id;
338 }
339 }
340 return $rows;
341 }
342
343 }