Commit | Line | Data |
---|---|---|
6a488035 TO |
1 | <?php |
2 | /* | |
3 | +--------------------------------------------------------------------+ | |
bc77d7c0 | 4 | | Copyright CiviCRM LLC. All rights reserved. | |
6a488035 | 5 | | | |
bc77d7c0 TO |
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 | | |
6a488035 TO |
9 | +--------------------------------------------------------------------+ |
10 | */ | |
11 | ||
12 | /** | |
13 | * | |
14 | * @package CRM | |
ca5cec67 | 15 | * @copyright CiviCRM LLC https://civicrm.org/licensing |
6a488035 TO |
16 | */ |
17 | ||
9b161ac5 EM |
18 | use Civi\Api4\Contribution; |
19 | ||
6a488035 | 20 | /** |
ce064e4f | 21 | * This class provides the functionality for batch entry for contributions/memberships. |
6a488035 TO |
22 | */ |
23 | class CRM_Batch_Form_Entry extends CRM_Core_Form { | |
24 | ||
25 | /** | |
eceb18cc | 26 | * Maximum profile fields that will be displayed. |
abd76e0d | 27 | * |
62d3ee27 | 28 | * @var int |
6a488035 TO |
29 | */ |
30 | protected $_rowCount = 1; | |
31 | ||
32 | /** | |
eceb18cc | 33 | * Batch id. |
abd76e0d | 34 | * |
62d3ee27 | 35 | * @var int |
6a488035 TO |
36 | */ |
37 | protected $_batchId; | |
38 | ||
39 | /** | |
eceb18cc | 40 | * Batch information. |
abd76e0d | 41 | * |
62d3ee27 | 42 | * @var array |
6a488035 | 43 | */ |
be2fb01f | 44 | protected $_batchInfo = []; |
6a488035 TO |
45 | |
46 | /** | |
eceb18cc | 47 | * Store the profile id associated with the batch type. |
62d3ee27 | 48 | * @var int |
6a488035 TO |
49 | */ |
50 | protected $_profileId; | |
51 | ||
52 | public $_action; | |
8ef12e64 | 53 | |
6a488035 TO |
54 | public $_mode; |
55 | ||
56 | public $_params; | |
57 | ||
6a488035 | 58 | /** |
fe482240 | 59 | * When not to reset sort_name. |
abd76e0d | 60 | * |
62d3ee27 | 61 | * @var bool |
6a488035 TO |
62 | */ |
63 | protected $_preserveDefault = TRUE; | |
64 | ||
d6dd2bee EM |
65 | /** |
66 | * Renew option for current row. | |
67 | * | |
68 | * This is as set on the form. | |
69 | * | |
70 | * @var int | |
71 | */ | |
72 | protected $currentRowIsRenewOption; | |
73 | ||
6a488035 | 74 | /** |
0880a9d0 | 75 | * Contact fields. |
abd76e0d | 76 | * |
62d3ee27 | 77 | * @var array |
6a488035 | 78 | */ |
be2fb01f | 79 | protected $_contactFields = []; |
6a488035 | 80 | |
afe349ef | 81 | /** |
0880a9d0 | 82 | * Fields array of fields in the batch profile. |
abd76e0d | 83 | * |
afe349ef | 84 | * (based on the uf_field table data) |
85 | * (this can't be protected as it is passed into the CRM_Contact_Form_Task_Batch::parseStreetAddress function | |
86 | * (although a future refactoring might hopefully change that so it uses the api & the function is not | |
87 | * required | |
abd76e0d | 88 | * |
afe349ef | 89 | * @var array |
90 | */ | |
be2fb01f | 91 | public $_fields = []; |
353ffa53 | 92 | |
9b161ac5 EM |
93 | /** |
94 | * @var int | |
95 | */ | |
96 | protected $currentRowContributionID; | |
97 | ||
d6dd2bee EM |
98 | /** |
99 | * Row being processed. | |
100 | * | |
101 | * @var array | |
102 | */ | |
103 | protected $currentRow = []; | |
104 | ||
5e8c8bd6 EM |
105 | /** |
106 | * @var array | |
107 | */ | |
108 | protected $currentRowExistingMembership; | |
109 | ||
9b161ac5 EM |
110 | /** |
111 | * Get the contribution id for the current row. | |
112 | * | |
113 | * @return int | |
114 | * @throws \CRM_Core_Exception | |
115 | */ | |
116 | public function getCurrentRowContributionID(): int { | |
117 | if (!isset($this->currentRowContributionID)) { | |
118 | $this->currentRowContributionID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $this->getCurrentRowMembershipID(), 'contribution_id', 'membership_id'); | |
119 | } | |
120 | return $this->currentRowContributionID; | |
121 | } | |
122 | ||
123 | /** | |
124 | * Set the contribution ID for the current row. | |
125 | * | |
126 | * @param int $currentRowContributionID | |
127 | */ | |
128 | public function setCurrentRowContributionID(int $currentRowContributionID): void { | |
129 | $this->currentRowContributionID = $currentRowContributionID; | |
130 | } | |
131 | ||
132 | /** | |
133 | * @return mixed | |
134 | */ | |
135 | public function getCurrentRowMembershipID() { | |
136 | return $this->currentRowMembershipID; | |
137 | } | |
138 | ||
502822e7 EM |
139 | /** |
140 | * Get the order (contribution) status for the current row. | |
141 | */ | |
142 | protected function getCurrentRowPaymentStatus() { | |
143 | return CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $this->currentRow['contribution_status_id']); | |
144 | } | |
145 | ||
5e8c8bd6 EM |
146 | /** |
147 | * Get the contact ID for the current row. | |
148 | * | |
149 | * @return int | |
150 | */ | |
151 | public function getCurrentRowContactID(): int { | |
152 | return $this->currentRow['contact_id']; | |
153 | } | |
154 | ||
155 | /** | |
156 | * Get the membership type ID for the current row. | |
157 | * | |
158 | * @return int | |
159 | */ | |
160 | public function getCurrentRowMembershipTypeID(): int { | |
161 | return $this->currentRow['membership_type_id']; | |
162 | } | |
163 | ||
9b161ac5 EM |
164 | /** |
165 | * Set the membership id for the current row. | |
166 | * | |
167 | * @param int $currentRowMembershipID | |
168 | */ | |
169 | public function setCurrentRowMembershipID(int $currentRowMembershipID): void { | |
170 | $this->currentRowMembershipID = $currentRowMembershipID; | |
171 | } | |
172 | ||
173 | /** | |
174 | * @var int | |
175 | */ | |
176 | protected $currentRowMembershipID; | |
177 | ||
cdd71d6b | 178 | /** |
179 | * Monetary fields that may be submitted. | |
180 | * | |
181 | * These should get a standardised format in the beginPostProcess function. | |
182 | * | |
183 | * These fields are common to many forms. Some may override this. | |
62d3ee27 | 184 | * @var array |
cdd71d6b | 185 | */ |
186 | protected $submittableMoneyFields = ['total_amount', 'net_amount', 'non_deductible_amount', 'fee_amount']; | |
187 | ||
6a488035 | 188 | /** |
eceb18cc | 189 | * Build all the data structures needed to build the form. |
abd76e0d | 190 | * |
191 | * @throws \CRM_Core_Exception | |
8ef12e64 | 192 | */ |
00be9182 | 193 | public function preProcess() { |
6a488035 TO |
194 | $this->_batchId = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE); |
195 | ||
196 | $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse'); | |
8ef12e64 | 197 | |
6a488035 | 198 | if (empty($this->_batchInfo)) { |
be2fb01f | 199 | $params = ['id' => $this->_batchId]; |
6a488035 TO |
200 | CRM_Batch_BAO_Batch::retrieve($params, $this->_batchInfo); |
201 | ||
57465e2a | 202 | $this->assign('batchTotal', !empty($this->_batchInfo['total']) ? $this->_batchInfo['total'] : NULL); |
6a488035 TO |
203 | $this->assign('batchType', $this->_batchInfo['type_id']); |
204 | ||
205 | // get the profile id associted with this batch type | |
206 | $this->_profileId = CRM_Batch_BAO_Batch::getProfileId($this->_batchInfo['type_id']); | |
207 | } | |
aefb0b79 | 208 | CRM_Core_Resources::singleton() |
353ffa53 | 209 | ->addScriptFile('civicrm', 'templates/CRM/Batch/Form/Entry.js', 1, 'html-header') |
be2fb01f CW |
210 | ->addSetting(['batch' => ['type_id' => $this->_batchInfo['type_id']]]) |
211 | ->addSetting(['setting' => ['monetaryThousandSeparator' => CRM_Core_Config::singleton()->monetaryThousandSeparator]]) | |
212 | ->addSetting(['setting' => ['monetaryDecimalPoint' => CRM_Core_Config::singleton()->monetaryDecimalPoint]]); | |
111f65f4 | 213 | |
a5dfa653 | 214 | $this->assign('defaultCurrencySymbol', CRM_Core_BAO_Country::defaultCurrencySymbol()); |
6a488035 TO |
215 | } |
216 | ||
cbd44e94 | 217 | /** |
bf48aa29 | 218 | * Set Batch ID. |
219 | * | |
220 | * @param int $id | |
cbd44e94 | 221 | */ |
123fe8fe | 222 | public function setBatchID($id) { |
223 | $this->_batchId = $id; | |
224 | } | |
225 | ||
6a488035 | 226 | /** |
eceb18cc | 227 | * Build the form object. |
abd76e0d | 228 | * |
229 | * @throws \CRM_Core_Exception | |
6a488035 | 230 | */ |
00be9182 | 231 | public function buildQuickForm() { |
6a488035 | 232 | if (!$this->_profileId) { |
e22ec653 | 233 | CRM_Core_Error::statusBounce(ts('Profile for bulk data entry is missing.')); |
6a488035 TO |
234 | } |
235 | ||
236 | $this->addElement('hidden', 'batch_id', $this->_batchId); | |
237 | ||
4a413eb6 | 238 | $batchTypes = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate'); |
6a488035 | 239 | // get the profile information |
d556e751 | 240 | if ($this->_batchInfo['type_id'] == $batchTypes['Contribution']) { |
483cfbc4 | 241 | $this->setTitle(ts('Batch Data Entry for Contributions')); |
6a488035 | 242 | } |
691df66d | 243 | elseif ($this->_batchInfo['type_id'] == $batchTypes['Membership']) { |
483cfbc4 | 244 | $this->setTitle(ts('Batch Data Entry for Memberships')); |
6a488035 | 245 | } |
691df66d | 246 | elseif ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) { |
483cfbc4 | 247 | $this->setTitle(ts('Batch Data Entry for Pledge Payments')); |
691df66d | 248 | } |
abd76e0d | 249 | |
6a488035 TO |
250 | $this->_fields = CRM_Core_BAO_UFGroup::getFields($this->_profileId, FALSE, CRM_Core_Action::VIEW); |
251 | ||
252 | // remove file type field and then limit fields | |
253 | $suppressFields = FALSE; | |
6a488035 | 254 | foreach ($this->_fields as $name => $field) { |
6454484c | 255 | if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) && $this->_fields[$name]['html_type'] == 'Autocomplete-Select') { |
6a488035 TO |
256 | $suppressFields = TRUE; |
257 | unset($this->_fields[$name]); | |
258 | } | |
259 | ||
260 | //fix to reduce size as we are using this field in grid | |
261 | if (is_array($field['attributes']) && $this->_fields[$name]['attributes']['size'] > 19) { | |
262 | //shrink class to "form-text-medium" | |
263 | $this->_fields[$name]['attributes']['size'] = 19; | |
264 | } | |
265 | } | |
266 | ||
be2fb01f | 267 | $this->addFormRule(['CRM_Batch_Form_Entry', 'formRule'], $this); |
6a488035 TO |
268 | |
269 | // add the force save button | |
270 | $forceSave = $this->getButtonName('upload', 'force'); | |
271 | ||
cbd83dde | 272 | $this->addElement('xbutton', |
6a488035 | 273 | $forceSave, |
cbd83dde | 274 | ts('Ignore Mismatch & Process the Batch?'), |
f7083334 AH |
275 | [ |
276 | 'type' => 'submit', | |
277 | 'value' => 1, | |
57c59c34 | 278 | 'class' => 'crm-button crm-button_qf_Entry_upload_force-save', |
f7083334 | 279 | ] |
6a488035 TO |
280 | ); |
281 | ||
be2fb01f | 282 | $this->addButtons([ |
5d4fcf54 TO |
283 | [ |
284 | 'type' => 'upload', | |
285 | 'name' => ts('Validate & Process the Batch'), | |
286 | 'isDefault' => TRUE, | |
287 | ], | |
288 | [ | |
289 | 'type' => 'cancel', | |
290 | 'name' => ts('Save & Continue Later'), | |
291 | ], | |
292 | ]); | |
6a488035 TO |
293 | |
294 | $this->assign('rowCount', $this->_batchInfo['item_count'] + 1); | |
295 | ||
be2fb01f | 296 | $preserveDefaultsArray = [ |
353ffa53 TO |
297 | 'first_name', |
298 | 'last_name', | |
299 | 'middle_name', | |
6a488035 TO |
300 | 'organization_name', |
301 | 'household_name', | |
be2fb01f | 302 | ]; |
6a488035 | 303 | |
be2fb01f CW |
304 | $contactTypes = ['Contact', 'Individual', 'Household', 'Organization']; |
305 | $contactReturnProperties = []; | |
5056dc8e | 306 | |
6a488035 | 307 | for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) { |
be2fb01f | 308 | $this->addEntityRef("primary_contact_id[{$rowNumber}]", '', [ |
5d4fcf54 TO |
309 | 'create' => TRUE, |
310 | 'placeholder' => ts('- select -'), | |
311 | ]); | |
6a488035 TO |
312 | |
313 | // special field specific to membership batch udpate | |
314 | if ($this->_batchInfo['type_id'] == 2) { | |
be2fb01f | 315 | $options = [ |
6a488035 TO |
316 | 1 => ts('Add Membership'), |
317 | 2 => ts('Renew Membership'), | |
be2fb01f | 318 | ]; |
6a488035 TO |
319 | $this->add('select', "member_option[$rowNumber]", '', $options); |
320 | } | |
00f6e1a8 | 321 | if ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) { |
be2fb01f CW |
322 | $options = ['' => '-select-']; |
323 | $optionTypes = [ | |
04e6444d | 324 | '1' => ts('Adjust Pledge Payment Schedule?'), |
325 | '2' => ts('Adjust Total Pledge Amount?'), | |
be2fb01f | 326 | ]; |
8e2b1206 | 327 | $this->add('select', "option_type[$rowNumber]", NULL, $optionTypes); |
328 | if (!empty($this->_batchId) && !empty($this->_batchInfo['data']) && !empty($rowNumber)) { | |
329 | $dataValues = json_decode($this->_batchInfo['data'], TRUE); | |
5542b7c2 | 330 | if (!empty($dataValues['values']['primary_contact_id'][$rowNumber])) { |
331 | $pledgeIDs = CRM_Pledge_BAO_Pledge::getContactPledges($dataValues['values']['primary_contact_id'][$rowNumber]); | |
332 | foreach ($pledgeIDs as $pledgeID) { | |
333 | $pledgePayment = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeID); | |
be2fb01f | 334 | $options += [$pledgeID => CRM_Utils_Date::customFormat($pledgePayment['schedule_date'], '%m/%d/%Y') . ', ' . $pledgePayment['amount'] . ' ' . $pledgePayment['currency']]; |
5542b7c2 | 335 | } |
8e2b1206 | 336 | } |
337 | } | |
5056dc8e | 338 | |
b8e805eb | 339 | $this->add('select', "open_pledges[$rowNumber]", '', $options); |
691df66d | 340 | } |
8e2b1206 | 341 | |
6a488035 TO |
342 | foreach ($this->_fields as $name => $field) { |
343 | if (in_array($field['field_type'], $contactTypes)) { | |
57465e2a | 344 | $fld = explode('-', $field['name']); |
5b1666f7 | 345 | $contactReturnProperties[$field['name']] = $fld[0]; |
6a488035 TO |
346 | } |
347 | CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, NULL, FALSE, FALSE, $rowNumber); | |
348 | ||
349 | if (in_array($field['name'], $preserveDefaultsArray)) { | |
350 | $this->_preserveDefault = FALSE; | |
351 | } | |
352 | } | |
353 | } | |
75140351 | 354 | |
3f8a2e90 | 355 | // CRM-19477: Display Error for Batch Sizes Exceeding php.ini max_input_vars |
356 | // Notes: $this->_elementIndex gives an approximate count of the variables being sent | |
75140351 | 357 | // An offset value is set to deal with additional vars that are likely passed. |
3f8a2e90 | 358 | // There may be a more accurate way to do this... |
5d4fcf54 TO |
359 | // set an offset to account for other vars we are not counting |
360 | $offset = 50; | |
75140351 | 361 | if ((count($this->_elementIndex) + $offset) > ini_get("max_input_vars")) { |
6dabf459 | 362 | // Avoiding 'ts' for obscure messages. |
507bc932 | 363 | CRM_Core_Error::statusBounce(ts('Batch size is too large. Increase value of php.ini setting "max_input_vars" (current val = %1)', [1 => ini_get("max_input_vars")])); |
49accad3 | 364 | } |
75140351 | 365 | |
6a488035 | 366 | $this->assign('fields', $this->_fields); |
57465e2a | 367 | CRM_Core_Resources::singleton() |
be2fb01f CW |
368 | ->addSetting([ |
369 | 'contact' => [ | |
353ffa53 TO |
370 | 'return' => implode(',', $contactReturnProperties), |
371 | 'fieldmap' => array_flip($contactReturnProperties), | |
be2fb01f CW |
372 | ], |
373 | ]); | |
6a488035 TO |
374 | |
375 | // don't set the status message when form is submitted. | |
376 | $buttonName = $this->controller->getButtonName('submit'); | |
377 | ||
378 | if ($suppressFields && $buttonName != '_qf_Entry_next') { | |
8f878cd3 | 379 | CRM_Core_Session::setStatus(ts("File type field(s) in the selected profile are not supported for Update multiple records."), ts('Some Fields Excluded'), 'info'); |
6a488035 TO |
380 | } |
381 | } | |
382 | ||
383 | /** | |
eceb18cc | 384 | * Form validations. |
6a488035 | 385 | * |
82d480a5 TO |
386 | * @param array $params |
387 | * Posted values of the form. | |
388 | * @param array $files | |
389 | * List of errors to be posted back to the form. | |
1620f0bc | 390 | * @param \CRM_Batch_Form_Entry $self |
82d480a5 | 391 | * Form object. |
6a488035 | 392 | * |
a6c01b45 CW |
393 | * @return array |
394 | * list of errors to be posted back to the form | |
6a488035 | 395 | */ |
00be9182 | 396 | public static function formRule($params, $files, $self) { |
be2fb01f | 397 | $errors = []; |
4a413eb6 | 398 | $batchTypes = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate'); |
be2fb01f | 399 | $fields = [ |
4db803dd CW |
400 | 'total_amount' => ts('Amount'), |
401 | 'financial_type' => ts('Financial Type'), | |
402 | 'payment_instrument' => ts('Payment Method'), | |
be2fb01f | 403 | ]; |
6a488035 | 404 | |
0576b84b SB |
405 | //CRM-16480 if contact is selected, validate financial type and amount field. |
406 | foreach ($params['field'] as $key => $value) { | |
47087bdc | 407 | if (isset($value['trxn_id'])) { |
be2fb01f | 408 | if (0 < CRM_Core_DAO::singleValueQuery('SELECT id FROM civicrm_contribution WHERE trxn_id = %1', [1 => [$value['trxn_id'], 'String']])) { |
47087bdc | 409 | $errors["field[$key][trxn_id]"] = ts('Transaction ID must be unique within the database'); |
410 | } | |
411 | } | |
61f45887 | 412 | foreach ($fields as $field => $label) { |
dddb4c8c | 413 | if (!empty($params['primary_contact_id'][$key]) && empty($value[$field])) { |
be2fb01f | 414 | $errors["field[$key][$field]"] = ts('%1 is a required field.', [1 => $label]); |
dddb4c8c | 415 | } |
0576b84b SB |
416 | } |
417 | } | |
418 | ||
a7488080 | 419 | if (!empty($params['_qf_Entry_upload_force'])) { |
0576b84b SB |
420 | if (!empty($errors)) { |
421 | return $errors; | |
422 | } | |
6a488035 TO |
423 | return TRUE; |
424 | } | |
425 | ||
426 | $batchTotal = 0; | |
427 | foreach ($params['field'] as $key => $value) { | |
428 | $batchTotal += $value['total_amount']; | |
429 | ||
5ee60152 | 430 | //validate for soft credit fields |
ccec9d6b | 431 | if (!empty($params['soft_credit_contact_id'][$key]) && empty($params['soft_credit_amount'][$key])) { |
d1401e86 | 432 | $errors["soft_credit_amount[$key]"] = ts('Please enter the soft credit amount.'); |
5ee60152 | 433 | } |
8cc574cf | 434 | if (!empty($params['soft_credit_amount']) && !empty($params['soft_credit_amount'][$key]) && CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value($key, $params['soft_credit_amount'])) > CRM_Utils_Rule::cleanMoney($value['total_amount'])) { |
5ee60152 RN |
435 | $errors["soft_credit_amount[$key]"] = ts('Soft credit amount should not be greater than the total amount'); |
436 | } | |
8ef12e64 | 437 | |
6a488035 | 438 | //membership type is required for membership batch entry |
5056dc8e | 439 | if ($self->_batchInfo['type_id'] == $batchTypes['Membership']) { |
a7488080 | 440 | if (empty($value['membership_type'][1])) { |
6a488035 TO |
441 | $errors["field[$key][membership_type]"] = ts('Membership type is a required field.'); |
442 | } | |
443 | } | |
444 | } | |
b8e805eb | 445 | if ($self->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) { |
5056dc8e | 446 | foreach (array_unique($params["open_pledges"]) as $value) { |
42724136 | 447 | if (!empty($value)) { |
448 | $duplicateRows = array_keys($params["open_pledges"], $value); | |
449 | } | |
450 | if (!empty($duplicateRows) && count($duplicateRows) > 1) { | |
5056dc8e | 451 | foreach ($duplicateRows as $key) { |
7f6a92ef | 452 | $errors["open_pledges[$key]"] = ts('You can not record two payments for the same pledge in a single batch.'); |
5056dc8e | 453 | } |
454 | } | |
455 | } | |
456 | } | |
28e8aa1b | 457 | if ((string) $batchTotal != $self->_batchInfo['total']) { |
6a488035 TO |
458 | $self->assign('batchAmountMismatch', TRUE); |
459 | $errors['_qf_defaults'] = ts('Total for amounts entered below does not match the expected batch total.'); | |
460 | } | |
461 | ||
462 | if (!empty($errors)) { | |
463 | return $errors; | |
464 | } | |
465 | ||
466 | $self->assign('batchAmountMismatch', FALSE); | |
467 | return TRUE; | |
468 | } | |
469 | ||
470 | /** | |
eceb18cc | 471 | * Override default cancel action. |
6a488035 | 472 | */ |
00be9182 | 473 | public function cancelAction() { |
6a488035 TO |
474 | // redirect to batch listing |
475 | CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/batch', 'reset=1')); | |
476 | CRM_Utils_System::civiExit(); | |
477 | } | |
478 | ||
479 | /** | |
c490a46a | 480 | * Set default values for the form. |
abd76e0d | 481 | * |
482 | * @throws \CRM_Core_Exception | |
6a488035 | 483 | */ |
00be9182 | 484 | public function setDefaultValues() { |
6a488035 TO |
485 | if (empty($this->_fields)) { |
486 | return; | |
487 | } | |
488 | ||
489 | // for add mode set smart defaults | |
481a74f4 | 490 | if ($this->_action & CRM_Core_Action::ADD) { |
3d927ee7 | 491 | $currentDate = date('Y-m-d H-i-s'); |
6a488035 | 492 | |
363544d7 | 493 | $completeStatus = CRM_Contribute_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'); |
be2fb01f | 494 | $specialFields = [ |
b2c9a0e3 | 495 | 'membership_join_date' => date('Y-m-d'), |
6a488035 | 496 | 'receive_date' => $currentDate, |
21dfd5f5 | 497 | 'contribution_status_id' => $completeStatus, |
be2fb01f | 498 | ]; |
6a488035 TO |
499 | |
500 | for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) { | |
481a74f4 | 501 | foreach ($specialFields as $key => $value) { |
8ef12e64 | 502 | $defaults['field'][$rowNumber][$key] = $value; |
6a488035 | 503 | } |
8ef12e64 | 504 | } |
6a488035 TO |
505 | } |
506 | else { | |
6c97864e | 507 | // get the cached info from data column of civicrm_batch |
508 | $data = CRM_Core_DAO::getFieldValue('CRM_Batch_BAO_Batch', $this->_batchId, 'data'); | |
509 | $defaults = json_decode($data, TRUE); | |
c0d307ec | 510 | $defaults = $defaults['values']; |
6a488035 | 511 | } |
6c97864e | 512 | |
6a488035 TO |
513 | return $defaults; |
514 | } | |
515 | ||
516 | /** | |
eceb18cc | 517 | * Process the form after the input has been submitted and validated. |
abd76e0d | 518 | * |
519 | * @throws \CRM_Core_Exception | |
520 | * @throws \CiviCRM_API3_Exception | |
6a488035 TO |
521 | */ |
522 | public function postProcess() { | |
523 | $params = $this->controller->exportValues($this->_name); | |
6a488035 | 524 | $params['actualBatchTotal'] = 0; |
d556e751 | 525 | |
526 | // get the profile information | |
be2fb01f CW |
527 | $batchTypes = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate'); |
528 | if (in_array($this->_batchInfo['type_id'], [$batchTypes['Pledge Payment'], $batchTypes['Contribution']])) { | |
6a488035 TO |
529 | $this->processContribution($params); |
530 | } | |
d556e751 | 531 | elseif ($this->_batchInfo['type_id'] == $batchTypes['Membership']) { |
818f20f0 | 532 | $params['actualBatchTotal'] = $this->processMembership($params); |
6a488035 | 533 | } |
d556e751 | 534 | |
6a488035 | 535 | // update batch to close status |
be2fb01f | 536 | $paramValues = [ |
6a488035 TO |
537 | 'id' => $this->_batchId, |
538 | // close status | |
1a453756 | 539 | 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Closed'), |
6a488035 | 540 | 'total' => $params['actualBatchTotal'], |
be2fb01f | 541 | ]; |
6a488035 TO |
542 | |
543 | CRM_Batch_BAO_Batch::create($paramValues); | |
544 | ||
6a488035 TO |
545 | // set success status |
546 | CRM_Core_Session::setStatus("", ts("Batch Processed."), "success"); | |
547 | ||
548 | CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/batch', 'reset=1')); | |
549 | } | |
550 | ||
551 | /** | |
eceb18cc | 552 | * Process contribution records. |
6a488035 | 553 | * |
82d480a5 TO |
554 | * @param array $params |
555 | * Associated array of submitted values. | |
6a488035 | 556 | * |
ce064e4f | 557 | * @return bool |
abd76e0d | 558 | * |
559 | * @throws \CRM_Core_Exception | |
560 | * @throws \CiviCRM_API3_Exception | |
6a488035 TO |
561 | */ |
562 | private function processContribution(&$params) { | |
6a488035 | 563 | |
cdd71d6b | 564 | foreach ($this->submittableMoneyFields as $moneyField) { |
565 | foreach ($params['field'] as $index => $fieldValues) { | |
566 | if (isset($fieldValues[$moneyField])) { | |
567 | $params['field'][$index][$moneyField] = CRM_Utils_Rule::cleanMoney($params['field'][$index][$moneyField]); | |
568 | } | |
569 | } | |
570 | } | |
571 | $params['actualBatchTotal'] = CRM_Utils_Rule::cleanMoney($params['actualBatchTotal']); | |
6a488035 | 572 | // get the price set associated with offline contribution record. |
9da8dc8c | 573 | $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name'); |
574 | $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId)); | |
85020e43 EM |
575 | $priceFieldID = CRM_Price_BAO_PriceSet::getOnlyPriceFieldID($this->_priceSet); |
576 | $priceFieldValueID = CRM_Price_BAO_PriceSet::getOnlyPriceFieldValueID($this->_priceSet); | |
6a488035 | 577 | |
6a488035 TO |
578 | if (isset($params['field'])) { |
579 | foreach ($params['field'] as $key => $value) { | |
580 | // if contact is not selected we should skip the row | |
ccec9d6b | 581 | if (empty($params['primary_contact_id'][$key])) { |
6a488035 TO |
582 | continue; |
583 | } | |
584 | ||
9c1bc317 | 585 | $value['contact_id'] = $params['primary_contact_id'][$key] ?? NULL; |
6a488035 TO |
586 | |
587 | // update contact information | |
588 | $this->updateContactInfo($value); | |
589 | ||
5ee60152 | 590 | //build soft credit params |
ccec9d6b CW |
591 | if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) { |
592 | $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key]; | |
0689c15c | 593 | $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]); |
9e1854a1 | 594 | |
595 | //CRM-15350: if soft-credit-type profile field is disabled or removed then | |
596 | //we choose configured SCT default value | |
597 | if (!empty($params['soft_credit_type'][$key])) { | |
598 | $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key]; | |
599 | } | |
600 | else { | |
601 | $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_OptionGroup::getDefaultValue("soft_credit_type"); | |
602 | } | |
6a488035 TO |
603 | } |
604 | ||
b7714c80 AH |
605 | // Build PCP params |
606 | if (!empty($params['pcp_made_through_id'][$key])) { | |
607 | $value['pcp']['pcp_made_through_id'] = $params['pcp_made_through_id'][$key]; | |
608 | $value['pcp']['pcp_display_in_roll'] = !empty($params['pcp_display_in_roll'][$key]); | |
609 | if (!empty($params['pcp_roll_nickname'][$key])) { | |
610 | $value['pcp']['pcp_roll_nickname'] = $params['pcp_roll_nickname'][$key]; | |
611 | } | |
612 | if (!empty($params['pcp_personal_note'][$key])) { | |
613 | $value['pcp']['pcp_personal_note'] = $params['pcp_personal_note'][$key]; | |
614 | } | |
615 | } | |
616 | ||
6a488035 | 617 | $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value, |
df1f662a | 618 | NULL, |
6a488035 TO |
619 | 'Contribution' |
620 | ); | |
621 | ||
a7488080 | 622 | if (!empty($value['send_receipt'])) { |
6a488035 TO |
623 | $value['receipt_date'] = date('Y-m-d His'); |
624 | } | |
2e4a81d5 | 625 | // these translations & date handling are required because we are calling BAO directly rather than the api |
be2fb01f | 626 | $fieldTranslations = [ |
2e4a81d5 EM |
627 | 'financial_type' => 'financial_type_id', |
628 | 'payment_instrument' => 'payment_instrument_id', | |
629 | 'contribution_source' => 'source', | |
630 | 'contribution_note' => 'note', | |
80a67e92 | 631 | 'contribution_check_number' => 'check_number', |
be2fb01f | 632 | ]; |
2e4a81d5 | 633 | foreach ($fieldTranslations as $formField => $baoField) { |
5542b7c2 | 634 | if (isset($value[$formField])) { |
2e4a81d5 EM |
635 | $value[$baoField] = $value[$formField]; |
636 | } | |
637 | unset($value[$formField]); | |
6a488035 TO |
638 | } |
639 | ||
640 | $params['actualBatchTotal'] += $value['total_amount']; | |
6a488035 TO |
641 | $value['batch_id'] = $this->_batchId; |
642 | $value['skipRecentView'] = TRUE; | |
643 | ||
644 | // build line item params | |
691df66d | 645 | $this->_priceSet['fields'][$priceFieldID]['options'][$priceFieldValueID]['amount'] = $value['total_amount']; |
86bfa4f6 | 646 | $value['price_' . $priceFieldID] = 1; |
6a488035 | 647 | |
be2fb01f | 648 | $lineItem = []; |
9da8dc8c | 649 | CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $value, $lineItem[$priceSetId]); |
6a488035 | 650 | |
c039f658 | 651 | // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel |
652 | // function to get correct amount level consistently. Remove setting of the amount level in | |
653 | // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest | |
654 | // to cover all variants. | |
6a488035 TO |
655 | unset($value['amount_level']); |
656 | ||
2e4a81d5 | 657 | //CRM-11529 for back office transactions |
8ef12e64 | 658 | //when financial_type_id is passed in form, update the |
2e4a81d5 | 659 | //line items with the financial type selected in form |
c039f658 | 660 | // @todo - create a price set or price field per financial type & simply choose the appropriate |
661 | // price field rather than working around the fact that each price_field is supposed to have a financial | |
662 | // type & we are allowing that to be overridden. | |
8cc574cf | 663 | if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) { |
6a488035 TO |
664 | foreach ($lineItem[$priceSetId] as &$values) { |
665 | $values['financial_type_id'] = $value['financial_type_id']; | |
666 | } | |
667 | } | |
668 | $value['line_item'] = $lineItem; | |
2f8a402e | 669 | |
6a488035 | 670 | //finally call contribution create for all the magic |
1273d77c | 671 | $contribution = CRM_Contribute_BAO_Contribution::create($value); |
2f8a402e | 672 | // This code to retrieve the contribution has been moved here from the contribution create |
673 | // api. It may not be required. | |
674 | $titleFields = [ | |
675 | 'contact_id', | |
676 | 'total_amount', | |
677 | 'currency', | |
678 | 'financial_type_id', | |
679 | ]; | |
680 | $retrieveRequired = 0; | |
681 | foreach ($titleFields as $titleField) { | |
682 | if (!isset($contribution->$titleField)) { | |
683 | $retrieveRequired = 1; | |
684 | break; | |
685 | } | |
686 | } | |
687 | if ($retrieveRequired == 1) { | |
688 | $contribution->find(TRUE); | |
689 | } | |
4a413eb6 | 690 | $batchTypes = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate'); |
34b568c4 | 691 | if (!empty($this->_batchInfo['type_id']) && ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment'])) { |
04e6444d | 692 | $adjustTotalAmount = FALSE; |
5056dc8e | 693 | if (isset($params['option_type'][$key])) { |
694 | if ($params['option_type'][$key] == 2) { | |
695 | $adjustTotalAmount = TRUE; | |
696 | } | |
04e6444d | 697 | } |
ce70f330 | 698 | $pledgeId = $params['open_pledges'][$key]; |
5056dc8e | 699 | if (is_numeric($pledgeId)) { |
700 | $result = CRM_Pledge_BAO_PledgePayment::getPledgePayments($pledgeId); | |
701 | $pledgePaymentId = 0; | |
481a74f4 | 702 | foreach ($result as $key => $values) { |
5056dc8e | 703 | if ($values['status'] != 'Completed') { |
704 | $pledgePaymentId = $values['id']; | |
705 | break; | |
706 | } | |
04e6444d | 707 | } |
5056dc8e | 708 | CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentId, 'contribution_id', $contribution->id); |
709 | CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, | |
be2fb01f | 710 | [$pledgePaymentId], |
5056dc8e | 711 | $contribution->contribution_status_id, |
712 | NULL, | |
713 | $contribution->total_amount, | |
714 | $adjustTotalAmount | |
715 | ); | |
04e6444d | 716 | } |
04e6444d | 717 | } |
5056dc8e | 718 | |
6a488035 | 719 | //process premiums |
a7488080 | 720 | if (!empty($value['product_name'])) { |
6a488035 | 721 | if ($value['product_name'][0] > 0) { |
818f20f0 | 722 | [$products, $options] = CRM_Contribute_BAO_Premium::getPremiumProductInfo(); |
6a488035 TO |
723 | |
724 | $value['hidden_Premium'] = 1; | |
725 | $value['product_option'] = CRM_Utils_Array::value( | |
726 | $value['product_name'][1], | |
727 | $options[$value['product_name'][0]] | |
728 | ); | |
729 | ||
be2fb01f | 730 | $premiumParams = [ |
6a488035 TO |
731 | 'product_id' => $value['product_name'][0], |
732 | 'contribution_id' => $contribution->id, | |
733 | 'product_option' => $value['product_option'], | |
734 | 'quantity' => 1, | |
be2fb01f | 735 | ]; |
6a488035 TO |
736 | CRM_Contribute_BAO_Contribution::addPremium($premiumParams); |
737 | } | |
738 | } | |
739 | // end of premium | |
740 | ||
741 | //send receipt mail. | |
5056dc8e | 742 | if ($contribution->id && !empty($value['send_receipt'])) { |
ac4760c5 | 743 | $value['from_email_address'] = $this->getFromEmailAddress(); |
691df66d | 744 | $value['contribution_id'] = $contribution->id; |
43f77a2c | 745 | if (!empty($value['soft_credit'])) { |
746 | $value = array_merge($value, CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id)); | |
747 | } | |
481a74f4 | 748 | CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $value); |
6a488035 TO |
749 | } |
750 | } | |
751 | } | |
2e4a81d5 | 752 | return TRUE; |
6a488035 | 753 | } |
6a488035 TO |
754 | |
755 | /** | |
eceb18cc | 756 | * Process membership records. |
6a488035 | 757 | * |
82d480a5 | 758 | * @param array $params |
818f20f0 | 759 | * Array of submitted values. |
6a488035 | 760 | * |
818f20f0 | 761 | * @return float |
762 | * batch total monetary amount. | |
6a488035 | 763 | * |
818f20f0 | 764 | * @throws \CRM_Core_Exception |
765 | * @throws \CiviCRM_API3_Exception | |
77274636 | 766 | * @throws \API_Exception |
6a488035 | 767 | */ |
818f20f0 | 768 | private function processMembership(array $params) { |
769 | $batchTotal = 0; | |
fd4b9293 | 770 | // get the price set associated with offline membership |
9da8dc8c | 771 | $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name'); |
772 | $this->_priceSet = $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId)); | |
6a488035 TO |
773 | |
774 | if (isset($params['field'])) { | |
04b40eab | 775 | // @todo - most of the wrangling in this function is because the api is not being used, especially date stuff. |
6a488035 | 776 | foreach ($params['field'] as $key => $value) { |
9b161ac5 EM |
777 | // if contact is not selected we should skip the row |
778 | if (empty($params['primary_contact_id'][$key])) { | |
779 | continue; | |
780 | } | |
781 | $value['contact_id'] = $params['primary_contact_id'][$key]; | |
d2fc4c00 | 782 | $value = $this->standardiseRow($value); |
d6dd2bee | 783 | $this->currentRow = $value; |
5e8c8bd6 | 784 | $this->currentRowExistingMembership = NULL; |
d6dd2bee | 785 | $this->currentRowIsRenewOption = (int) ($params['member_option'][$key] ?? 1); |
6a488035 TO |
786 | |
787 | // update contact information | |
788 | $this->updateContactInfo($value); | |
789 | ||
6a488035 | 790 | //check for custom data |
502822e7 | 791 | $value['custom'] = CRM_Core_BAO_CustomField::postProcess($this->currentRow, |
6a488035 TO |
792 | $key, |
793 | 'Membership', | |
d2fc4c00 | 794 | $value['membership_type_id'] |
6a488035 TO |
795 | ); |
796 | ||
6a488035 | 797 | // handle soft credit |
9e1854a1 | 798 | if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) { |
ccec9d6b | 799 | $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key]; |
0689c15c | 800 | $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]); |
9e1854a1 | 801 | |
802 | //CRM-15350: if soft-credit-type profile field is disabled or removed then | |
803 | //we choose Gift as default value as per Gift Membership rule | |
804 | if (!empty($params['soft_credit_type'][$key])) { | |
805 | $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key]; | |
806 | } | |
807 | else { | |
1a453756 | 808 | $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', 'Gift'); |
9e1854a1 | 809 | } |
6a488035 | 810 | } |
818f20f0 | 811 | $batchTotal += $value['total_amount']; |
6a488035 TO |
812 | $value['batch_id'] = $this->_batchId; |
813 | $value['skipRecentView'] = TRUE; | |
814 | ||
77274636 EM |
815 | $order = new CRM_Financial_BAO_Order(); |
816 | // We use the override total amount because we are dealing with a | |
817 | // possibly tax_inclusive total, which is assumed for the override total. | |
2df49c85 | 818 | $order->setOverrideTotalAmount((float) $value['total_amount']); |
77274636 EM |
819 | $order->setLineItem([ |
820 | 'membership_type_id' => $value['membership_type_id'], | |
821 | 'financial_type_id' => $value['financial_type_id'], | |
822 | ], $key); | |
502822e7 | 823 | $order->setEntityParameters($this->getCurrentRowMembershipParams(), $key); |
77274636 EM |
824 | |
825 | if (!empty($order->getLineItems())) { | |
826 | $value['lineItems'] = [$order->getPriceSetID() => $order->getPriceFieldIndexedLineItems()]; | |
6a488035 TO |
827 | $value['processPriceSet'] = TRUE; |
828 | } | |
829 | // end of contribution related section | |
d6dd2bee | 830 | if ($this->currentRowIsRenew()) { |
61767a1d | 831 | // The following parameter setting may be obsolete. |
6a488035 | 832 | $this->_params = $params; |
04b40eab | 833 | |
be2fb01f | 834 | $formDates = [ |
6b409353 CW |
835 | 'end_date' => $value['membership_end_date'] ?? NULL, |
836 | 'start_date' => $value['membership_start_date'] ?? NULL, | |
be2fb01f | 837 | ]; |
9cd37b8c EM |
838 | |
839 | $membership = $this->legacyProcessMembership( | |
840 | $value['custom'], $formDates | |
6a488035 TO |
841 | ); |
842 | ||
843 | // make contribution entry | |
be2fb01f | 844 | $contrbutionParams = array_merge($value, ['membership_id' => $membership->id]); |
5471eacc | 845 | $contrbutionParams['skipCleanMoney'] = TRUE; |
3febe800 | 846 | // @todo - calling this from here is pretty hacky since it is called from membership.create anyway |
847 | // This form should set the correct params & not call this fn directly. | |
28cc62fc | 848 | CRM_Member_BAO_Membership::recordMembershipContribution($contrbutionParams); |
9b161ac5 | 849 | $this->setCurrentRowMembershipID($membership->id); |
8ef12e64 | 850 | } |
6a488035 | 851 | else { |
502822e7 EM |
852 | $createdOrder = civicrm_api3('Order', 'create', [ |
853 | 'line_items' => $order->getLineItemForV3OrderApi(), | |
854 | 'receive_date' => $this->currentRow['receive_date'], | |
855 | 'check_number' => $this->currentRow['check_number'] ?? '', | |
856 | 'contact_id' => $this->getCurrentRowContactID(), | |
857 | 'batch_id' => $this->_batchId, | |
858 | 'financial_type_id' => $this->currentRow['financial_type_id'], | |
859 | 'payment_instrument_id' => $this->currentRow['payment_instrument_id'], | |
860 | ]); | |
861 | $this->currentRowContributionID = $createdOrder['id']; | |
862 | ||
863 | $this->setCurrentRowMembershipID($createdOrder['values'][$this->getCurrentRowContributionID()]['line_item'][0]['entity_id']); | |
864 | if ($this->getCurrentRowPaymentStatus() === 'Completed') { | |
865 | civicrm_api3('Payment', 'create', [ | |
866 | 'total_amount' => $order->getTotalAmount() + $order->getTotalTaxAmount(), | |
867 | 'check_number' => $this->currentRow['check_number'] ?? '', | |
868 | 'trxn_date' => $this->currentRow['receive_date'], | |
869 | 'trxn_id' => $this->currentRow['trxn_id'], | |
870 | 'payment_instrument_id' => $this->currentRow['payment_instrument_id'], | |
871 | 'contribution_id' => $this->getCurrentRowContributionID(), | |
872 | 'is_send_contribution_notification' => FALSE, | |
873 | ]); | |
874 | } | |
6a488035 | 875 | |
502822e7 EM |
876 | if (in_array($this->getCurrentRowPaymentStatus(), ['Failed', 'Cancelled'])) { |
877 | Contribution::update() | |
878 | ->addValue('contribution_status_id', $this->currentRow['contribution_status_id']) | |
879 | ->addWhere('id', '=', $this->getCurrentRowContributionID()) | |
880 | ->execute(); | |
881 | } | |
882 | } | |
6a488035 | 883 | //process premiums |
a7488080 | 884 | if (!empty($value['product_name'])) { |
6a488035 | 885 | if ($value['product_name'][0] > 0) { |
7ec3caf3 | 886 | [$products, $options] = CRM_Contribute_BAO_Premium::getPremiumProductInfo(); |
6a488035 TO |
887 | |
888 | $value['hidden_Premium'] = 1; | |
889 | $value['product_option'] = CRM_Utils_Array::value( | |
890 | $value['product_name'][1], | |
891 | $options[$value['product_name'][0]] | |
892 | ); | |
893 | ||
be2fb01f | 894 | $premiumParams = [ |
6a488035 | 895 | 'product_id' => $value['product_name'][0], |
9b161ac5 | 896 | 'contribution_id' => $this->getCurrentRowContributionID(), |
6a488035 TO |
897 | 'product_option' => $value['product_option'], |
898 | 'quantity' => 1, | |
be2fb01f | 899 | ]; |
6a488035 TO |
900 | CRM_Contribute_BAO_Contribution::addPremium($premiumParams); |
901 | } | |
902 | } | |
903 | // end of premium | |
904 | ||
905 | //send receipt mail. | |
502822e7 EM |
906 | if ($this->getCurrentRowMembershipID() && !empty($value['send_receipt'])) { |
907 | $value['membership_id'] = $this->getCurrentRowMembershipID(); | |
908 | $this->emailReceipt($this, $value); | |
6a488035 TO |
909 | } |
910 | } | |
911 | } | |
818f20f0 | 912 | return $batchTotal; |
6a488035 TO |
913 | } |
914 | ||
7ec3caf3 | 915 | /** |
916 | * Send email receipt. | |
917 | * | |
918 | * @param CRM_Core_Form $form | |
919 | * Form object. | |
920 | * @param array $formValues | |
7ec3caf3 | 921 | * |
922 | * @return bool | |
923 | * true if mail was sent successfully | |
ac4760c5 | 924 | * @throws \CRM_Core_Exception|\API_Exception |
7ec3caf3 | 925 | * |
7ec3caf3 | 926 | */ |
502822e7 EM |
927 | protected function emailReceipt($form, &$formValues): bool { |
928 | $membership = new CRM_Member_BAO_Membership(); | |
929 | $membership->id = $this->getCurrentRowMembershipID(); | |
930 | $membership->fetch(); | |
7ec3caf3 | 931 | // @todo figure out how much of the stuff below is genuinely shared with the batch form & a logical shared place. |
932 | if (!empty($formValues['payment_instrument_id'])) { | |
933 | $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument(); | |
934 | $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']]; | |
935 | } | |
936 | ||
937 | $form->assign('module', 'Membership'); | |
938 | $form->assign('contactID', $formValues['contact_id']); | |
939 | ||
940 | $form->assign('membershipID', CRM_Utils_Array::value('membership_id', $form->_params, CRM_Utils_Array::value('membership_id', $form->_defaultValues))); | |
9b161ac5 | 941 | $this->assign('contributionID', $this->getCurrentRowContributionID()); |
7ec3caf3 | 942 | |
943 | if (!empty($formValues['contribution_status_id'])) { | |
944 | $form->assign('contributionStatusID', $formValues['contribution_status_id']); | |
945 | $form->assign('contributionStatus', CRM_Contribute_PseudoConstant::contributionStatus($formValues['contribution_status_id'], 'name')); | |
946 | } | |
947 | ||
d6dd2bee | 948 | $form->assign('receiptType', $this->currentRowIsRenew() ? 'membership renewal' : 'membership signup'); |
7ec3caf3 | 949 | $form->assign('receive_date', CRM_Utils_Array::value('receive_date', $formValues)); |
950 | $form->assign('formValues', $formValues); | |
951 | ||
952 | $form->assign('mem_start_date', CRM_Utils_Date::formatDateOnlyLong($membership->start_date)); | |
953 | if (!CRM_Utils_System::isNull($membership->end_date)) { | |
954 | $form->assign('mem_end_date', CRM_Utils_Date::formatDateOnlyLong($membership->end_date)); | |
955 | } | |
956 | $form->assign('membership_name', CRM_Member_PseudoConstant::membershipType($membership->membership_type_id)); | |
957 | ||
958 | [$form->_contributorDisplayName, $form->_contributorEmail] | |
959 | = CRM_Contact_BAO_Contact_Location::getEmailDetails($formValues['contact_id']); | |
960 | $form->_receiptContactId = $formValues['contact_id']; | |
961 | ||
962 | CRM_Core_BAO_MessageTemplate::sendTemplate( | |
963 | [ | |
964 | 'groupName' => 'msg_tpl_workflow_membership', | |
965 | 'valueName' => 'membership_offline_receipt', | |
966 | 'contactId' => $form->_receiptContactId, | |
ac4760c5 | 967 | 'from' => $this->getFromEmailAddress(), |
7ec3caf3 | 968 | 'toName' => $form->_contributorDisplayName, |
969 | 'toEmail' => $form->_contributorEmail, | |
970 | 'PDFFilename' => ts('receipt') . '.pdf', | |
0fba5cf8 | 971 | 'isEmailPdf' => Civi::settings()->get('invoice_is_email_pdf'), |
9b161ac5 | 972 | 'contributionId' => $this->getCurrentRowContributionID(), |
7ec3caf3 | 973 | 'isTest' => (bool) ($form->_action & CRM_Core_Action::PREVIEW), |
974 | ] | |
975 | ); | |
976 | ||
9b161ac5 EM |
977 | Contribution::update(FALSE) |
978 | ->addWhere('id', '=', $this->getCurrentRowContributionID()) | |
979 | ->setValues(['receipt_date', 'now']) | |
980 | ->execute(); | |
981 | ||
7ec3caf3 | 982 | return TRUE; |
983 | } | |
984 | ||
6a488035 | 985 | /** |
eceb18cc | 986 | * Update contact information. |
6a488035 | 987 | * |
82d480a5 TO |
988 | * @param array $value |
989 | * Associated array of submitted values. | |
6a488035 | 990 | */ |
7ec3caf3 | 991 | private function updateContactInfo(array &$value) { |
6a488035 TO |
992 | $value['preserveDBName'] = $this->_preserveDefault; |
993 | ||
994 | //parse street address, CRM-7768 | |
995 | CRM_Contact_Form_Task_Batch::parseStreetAddress($value, $this); | |
996 | ||
997 | CRM_Contact_BAO_Contact::createProfileContact($value, $this->_fields, | |
998 | $value['contact_id'] | |
999 | ); | |
1000 | } | |
cab024d4 | 1001 | |
afe349ef | 1002 | /** |
ce064e4f | 1003 | * Function exists purely for unit testing purposes. |
1004 | * | |
1005 | * If you feel tempted to use this in live code then it probably means there is some functionality | |
1006 | * that needs to be moved out of the form layer | |
cab024d4 | 1007 | * |
4c16123d | 1008 | * @param array $params |
cab024d4 EM |
1009 | * |
1010 | * @return bool | |
afe349ef | 1011 | */ |
00be9182 | 1012 | public function testProcessMembership($params) { |
afe349ef | 1013 | return $this->processMembership($params); |
1014 | } | |
cab024d4 EM |
1015 | |
1016 | /** | |
ce064e4f | 1017 | * Function exists purely for unit testing purposes. |
1018 | * | |
1019 | * If you feel tempted to use this in live code then it probably means there is some functionality | |
1020 | * that needs to be moved out of the form layer. | |
cab024d4 EM |
1021 | * |
1022 | * @param array $params | |
1023 | * | |
1024 | * @return bool | |
abd76e0d | 1025 | * |
1026 | * @throws \CRM_Core_Exception | |
1027 | * @throws \CiviCRM_API3_Exception | |
cab024d4 | 1028 | */ |
00be9182 | 1029 | public function testProcessContribution($params) { |
cab024d4 EM |
1030 | return $this->processContribution($params); |
1031 | } | |
96025800 | 1032 | |
a1a9cf1f | 1033 | /** |
a1a9cf1f | 1034 | * @param $customFieldsFormatted |
a1a9cf1f | 1035 | * @param array $formDates |
a1a9cf1f | 1036 | * |
c92325a8 EM |
1037 | * @return CRM_Member_BAO_Membership |
1038 | * | |
a1a9cf1f EM |
1039 | * @throws \CRM_Core_Exception |
1040 | * @throws \CiviCRM_API3_Exception | |
1041 | */ | |
9cd37b8c | 1042 | protected function legacyProcessMembership($customFieldsFormatted, $formDates = []): CRM_Member_DAO_Membership { |
c92325a8 | 1043 | $updateStatusId = FALSE; |
ec40ee4a | 1044 | $changeToday = NULL; |
ec40ee4a | 1045 | $numRenewTerms = 1; |
a1a9cf1f | 1046 | $format = '%Y%m%d'; |
a1a9cf1f | 1047 | $ids = []; |
95588dd4 | 1048 | $isPayLater = NULL; |
9cd37b8c | 1049 | $memParams = $this->getCurrentRowMembershipParams(); |
5e8c8bd6 | 1050 | $currentMembership = $this->getCurrentMembership(); |
a1a9cf1f | 1051 | |
bf455864 EM |
1052 | // Now Renew the membership |
1053 | if (!$currentMembership['is_current_member']) { | |
1054 | // membership is not CURRENT | |
a1a9cf1f | 1055 | |
bf455864 EM |
1056 | // CRM-7297 Membership Upsell - calculate dates based on new membership type |
1057 | $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($currentMembership['id'], | |
1058 | $changeToday, | |
1059 | $this->getCurrentRowMembershipTypeID(), | |
1060 | $numRenewTerms | |
1061 | ); | |
a1a9cf1f | 1062 | |
bf455864 EM |
1063 | foreach (['start_date', 'end_date'] as $dateType) { |
1064 | $memParams[$dateType] = $memParams[$dateType] ?: ($dates[$dateType] ?? NULL); | |
a1a9cf1f | 1065 | } |
a1a9cf1f | 1066 | |
bf455864 EM |
1067 | $ids['membership'] = $currentMembership['id']; |
1068 | ||
1069 | //set the log start date. | |
1070 | $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format); | |
1071 | } | |
1072 | else { | |
1073 | ||
1074 | // CURRENT Membership | |
1075 | $membership = new CRM_Member_DAO_Membership(); | |
1076 | $membership->id = $currentMembership['id']; | |
1077 | $membership->find(TRUE); | |
1078 | // CRM-7297 Membership Upsell - calculate dates based on new membership type | |
1079 | $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, | |
1080 | $changeToday, | |
1081 | $this->getCurrentRowMembershipTypeID(), | |
1082 | $numRenewTerms | |
1083 | ); | |
1084 | ||
1085 | // Insert renewed dates for CURRENT membership | |
1086 | $memParams['join_date'] = CRM_Utils_Date::isoToMysql($membership->join_date); | |
1087 | $memParams['start_date'] = $formDates['start_date'] ?? CRM_Utils_Date::isoToMysql($membership->start_date); | |
1088 | $memParams['end_date'] = $formDates['end_date'] ?? NULL; | |
1089 | if (empty($memParams['end_date'])) { | |
1090 | $memParams['end_date'] = $dates['end_date'] ?? NULL; | |
1091 | } | |
a1a9cf1f | 1092 | |
bf455864 EM |
1093 | //set the log start date. |
1094 | $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format); | |
a1a9cf1f | 1095 | |
bf455864 EM |
1096 | if (!empty($currentMembership['id'])) { |
1097 | $ids['membership'] = $currentMembership['id']; | |
a1a9cf1f | 1098 | } |
bf455864 | 1099 | $memParams['membership_activity_status'] = $isPayLater ? 'Scheduled' : 'Completed'; |
a1a9cf1f | 1100 | } |
50002244 | 1101 | |
a1a9cf1f EM |
1102 | //CRM-4555 |
1103 | //if we decided status here and want to skip status | |
1104 | //calculation in create( ); then need to pass 'skipStatusCal'. | |
1105 | if ($updateStatusId) { | |
1106 | $memParams['status_id'] = $updateStatusId; | |
1107 | $memParams['skipStatusCal'] = TRUE; | |
1108 | } | |
1109 | ||
1110 | //since we are renewing, | |
1111 | //make status override false. | |
1112 | $memParams['is_override'] = FALSE; | |
a1a9cf1f EM |
1113 | $memParams['custom'] = $customFieldsFormatted; |
1114 | // Load all line items & process all in membership. Don't do in contribution. | |
1115 | // Relevant tests in api_v3_ContributionPageTest. | |
a1a9cf1f EM |
1116 | // @todo stop passing $ids (membership and userId may be set by this point) |
1117 | $membership = CRM_Member_BAO_Membership::create($memParams, $ids); | |
1118 | ||
1119 | // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010 | |
1120 | // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072 | |
1121 | $membership->find(TRUE); | |
1122 | ||
c92325a8 | 1123 | return $membership; |
a1a9cf1f EM |
1124 | } |
1125 | ||
ac4760c5 EM |
1126 | /** |
1127 | * @return string | |
1128 | * @throws \CRM_Core_Exception | |
1129 | */ | |
1130 | private function getFromEmailAddress(): string { | |
1131 | $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail(); | |
1132 | return "$domainEmail[0] <$domainEmail[1]>"; | |
1133 | } | |
1134 | ||
d2fc4c00 EM |
1135 | /** |
1136 | * Standardise the values in the row from profile-weirdness to civi-standard. | |
1137 | * | |
1138 | * The row uses odd field names such as financial_type rather than financial | |
1139 | * type id. We standardise at this point. | |
1140 | * | |
1141 | * @param array $row | |
1142 | * | |
1143 | * @return array | |
1144 | */ | |
1145 | private function standardiseRow(array $row): array { | |
d6dd2bee EM |
1146 | foreach ($row as $fieldKey => $fieldValue) { |
1147 | if (isset($this->_fields[$fieldKey]) && $this->_fields[$fieldKey]['data_type'] === 'Money') { | |
1148 | $row[$fieldKey] = CRM_Utils_Rule::cleanMoney($fieldValue); | |
1149 | } | |
1150 | } | |
d2fc4c00 EM |
1151 | $renameFieldMapping = [ |
1152 | 'financial_type' => 'financial_type_id', | |
1153 | 'payment_instrument' => 'payment_instrument_id', | |
1154 | 'membership_source' => 'source', | |
1155 | 'membership_status' => 'status_id', | |
1156 | ]; | |
1157 | foreach ($renameFieldMapping as $weirdProfileName => $betterName) { | |
1158 | // Check if isset as some like payment instrument and source are optional. | |
1159 | if (isset($row[$weirdProfileName]) && empty($row[$betterName])) { | |
1160 | $row[$betterName] = $row[$weirdProfileName]; | |
1161 | unset($row[$weirdProfileName]); | |
1162 | } | |
1163 | } | |
1164 | ||
1165 | // The latter format would be normal here - it's unclear if it is sometimes in the former format. | |
1166 | $row['membership_type_id'] = $row['membership_type_id'] ?? $row['membership_type'][1]; | |
1167 | unset($row['membership_type']); | |
1168 | // total_amount is required. | |
1169 | $row['total_amount'] = (float) $row['total_amount']; | |
1170 | return $row; | |
1171 | } | |
1172 | ||
d6dd2bee EM |
1173 | /** |
1174 | * Is the current row a renewal. | |
1175 | * | |
1176 | * @return bool | |
c0f6a1d1 EM |
1177 | * |
1178 | * @throws \CRM_Core_Exception | |
1179 | * @throws \CiviCRM_API3_Exception | |
d6dd2bee EM |
1180 | */ |
1181 | private function currentRowIsRenew(): bool { | |
c0f6a1d1 | 1182 | return $this->currentRowIsRenewOption === 2 && $this->getCurrentMembership(); |
d6dd2bee EM |
1183 | } |
1184 | ||
5e8c8bd6 EM |
1185 | /** |
1186 | * Get any current membership for the current row contact, for the same member organization. | |
1187 | * | |
1188 | * @return array|bool | |
1189 | * | |
1190 | * @throws \CiviCRM_API3_Exception | |
1191 | * @throws \CRM_Core_Exception | |
1192 | */ | |
1193 | protected function getCurrentMembership() { | |
1194 | if (!isset($this->currentRowExistingMembership)) { | |
1195 | // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType | |
1196 | // is the same as the parent org of an existing membership of the contact | |
1197 | $this->currentRowExistingMembership = CRM_Member_BAO_Membership::getContactMembership($this->getCurrentRowContactID(), $this->getCurrentRowMembershipTypeID(), | |
1198 | FALSE, NULL, TRUE | |
1199 | ); | |
502822e7 EM |
1200 | if ($this->currentRowExistingMembership) { |
1201 | // Check and fix the membership if it is STALE | |
1202 | CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($this->currentRowExistingMembership); | |
1203 | } | |
5e8c8bd6 EM |
1204 | } |
1205 | return $this->currentRowExistingMembership; | |
1206 | } | |
1207 | ||
6601aa51 EM |
1208 | /** |
1209 | * Get the params as related to the membership entity. | |
1210 | * | |
1211 | * @return array | |
1212 | */ | |
9cd37b8c | 1213 | private function getCurrentRowMembershipParams(): array { |
502822e7 | 1214 | return array_merge($this->getCurrentRowCustomParams(), [ |
6601aa51 EM |
1215 | 'start_date' => $this->currentRow['membership_start_date'] ?? NULL, |
1216 | 'end_date' => $this->currentRow['membership_end_date'] ?? NULL, | |
1217 | 'join_date' => $this->currentRow['membership_join_date'] ?? NULL, | |
1218 | 'campaign_id' => $this->currentRow['member_campaign_id'] ?? NULL, | |
502822e7 EM |
1219 | 'source' => $this->currentRow['source'] ?? (!$this->currentRowIsRenew() ? ts('Batch entry') : ''), |
1220 | 'membership_type_id' => $this->currentRow['membership_type_id'], | |
1221 | 'contact_id' => $this->getCurrentRowContactID(), | |
1222 | ]); | |
1223 | } | |
1224 | ||
1225 | /** | |
1226 | * Get the custom value parameters from the current row. | |
1227 | * | |
1228 | * @return array | |
1229 | */ | |
1230 | private function getCurrentRowCustomParams(): array { | |
1231 | $return = []; | |
1232 | foreach ($this->currentRow as $field => $value) { | |
1233 | if (strpos($field, 'custom_') === 0) { | |
1234 | $return[$field] = $value; | |
1235 | } | |
1236 | } | |
1237 | return $return; | |
6601aa51 EM |
1238 | } |
1239 | ||
6a488035 | 1240 | } |