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