dev/core#135 Fix first of 2 non numeric issues in CRM_Batch_form_entryTest
[civicrm-core.git] / CRM / Batch / Form / Entry.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
8c9251b3 6 | Copyright CiviCRM LLC (c) 2004-2018 |
6a488035
TO
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
8c9251b3 31 * @copyright CiviCRM LLC (c) 2004-2018
6a488035
TO
32 */
33
34/**
ce064e4f 35 * This class provides the functionality for batch entry for contributions/memberships.
6a488035
TO
36 */
37class CRM_Batch_Form_Entry extends CRM_Core_Form {
38
39 /**
eceb18cc 40 * Maximum profile fields that will be displayed.
6a488035
TO
41 */
42 protected $_rowCount = 1;
43
44 /**
eceb18cc 45 * Batch id.
6a488035
TO
46 */
47 protected $_batchId;
48
49 /**
eceb18cc 50 * Batch information.
6a488035
TO
51 */
52 protected $_batchInfo = array();
53
54 /**
eceb18cc 55 * Store the profile id associated with the batch type.
6a488035
TO
56 */
57 protected $_profileId;
58
59 public $_action;
8ef12e64 60
6a488035
TO
61 public $_mode;
62
63 public $_params;
64
6a488035 65 /**
fe482240 66 * When not to reset sort_name.
6a488035
TO
67 */
68 protected $_preserveDefault = TRUE;
69
70 /**
0880a9d0 71 * Contact fields.
6a488035
TO
72 */
73 protected $_contactFields = array();
74
afe349ef 75 /**
0880a9d0 76 * Fields array of fields in the batch profile.
afe349ef 77 * (based on the uf_field table data)
78 * (this can't be protected as it is passed into the CRM_Contact_Form_Task_Batch::parseStreetAddress function
79 * (although a future refactoring might hopefully change that so it uses the api & the function is not
80 * required
81 * @var array
82 */
83 public $_fields = array();
353ffa53 84
cdd71d6b 85 /**
86 * Monetary fields that may be submitted.
87 *
88 * These should get a standardised format in the beginPostProcess function.
89 *
90 * These fields are common to many forms. Some may override this.
91 */
92 protected $submittableMoneyFields = ['total_amount', 'net_amount', 'non_deductible_amount', 'fee_amount'];
93
6a488035 94 /**
eceb18cc 95 * Build all the data structures needed to build the form.
8ef12e64 96 */
00be9182 97 public function preProcess() {
6a488035
TO
98 $this->_batchId = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
99
100 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
8ef12e64 101
6a488035
TO
102 if (empty($this->_batchInfo)) {
103 $params = array('id' => $this->_batchId);
104 CRM_Batch_BAO_Batch::retrieve($params, $this->_batchInfo);
105
57465e2a 106 $this->assign('batchTotal', !empty($this->_batchInfo['total']) ? $this->_batchInfo['total'] : NULL);
6a488035
TO
107 $this->assign('batchType', $this->_batchInfo['type_id']);
108
109 // get the profile id associted with this batch type
110 $this->_profileId = CRM_Batch_BAO_Batch::getProfileId($this->_batchInfo['type_id']);
111 }
aefb0b79 112 CRM_Core_Resources::singleton()
353ffa53
TO
113 ->addScriptFile('civicrm', 'templates/CRM/Batch/Form/Entry.js', 1, 'html-header')
114 ->addSetting(array('batch' => array('type_id' => $this->_batchInfo['type_id'])))
115 ->addSetting(array('setting' => array('monetaryThousandSeparator' => CRM_Core_Config::singleton()->monetaryThousandSeparator)))
116 ->addSetting(array('setting' => array('monetaryDecimalPoint' => CRM_Core_Config::singleton()->monetaryDecimalPoint)));
111f65f4 117
6a488035
TO
118 }
119
cbd44e94 120 /**
bf48aa29 121 * Set Batch ID.
122 *
123 * @param int $id
cbd44e94 124 */
123fe8fe 125 public function setBatchID($id) {
126 $this->_batchId = $id;
127 }
128
6a488035 129 /**
eceb18cc 130 * Build the form object.
6a488035 131 */
00be9182 132 public function buildQuickForm() {
6a488035
TO
133 if (!$this->_profileId) {
134 CRM_Core_Error::fatal(ts('Profile for bulk data entry is missing.'));
135 }
136
137 $this->addElement('hidden', 'batch_id', $this->_batchId);
138
691df66d 139 $batchTypes = CRM_Core_Pseudoconstant::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate');
6a488035 140 // get the profile information
d556e751 141 if ($this->_batchInfo['type_id'] == $batchTypes['Contribution']) {
6a488035
TO
142 CRM_Utils_System::setTitle(ts('Batch Data Entry for Contributions'));
143 $customFields = CRM_Core_BAO_CustomField::getFields('Contribution');
144 }
691df66d 145 elseif ($this->_batchInfo['type_id'] == $batchTypes['Membership']) {
6a488035 146 CRM_Utils_System::setTitle(ts('Batch Data Entry for Memberships'));
6a488035 147 }
691df66d
TO
148 elseif ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) {
149 CRM_Utils_System::setTitle(ts('Batch Data Entry for Pledge Payments'));
691df66d 150 }
6a488035
TO
151 $this->_fields = array();
152 $this->_fields = CRM_Core_BAO_UFGroup::getFields($this->_profileId, FALSE, CRM_Core_Action::VIEW);
153
154 // remove file type field and then limit fields
155 $suppressFields = FALSE;
6a488035 156 foreach ($this->_fields as $name => $field) {
6454484c 157 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) && $this->_fields[$name]['html_type'] == 'Autocomplete-Select') {
6a488035
TO
158 $suppressFields = TRUE;
159 unset($this->_fields[$name]);
160 }
161
162 //fix to reduce size as we are using this field in grid
163 if (is_array($field['attributes']) && $this->_fields[$name]['attributes']['size'] > 19) {
164 //shrink class to "form-text-medium"
165 $this->_fields[$name]['attributes']['size'] = 19;
166 }
167 }
168
169 $this->addFormRule(array('CRM_Batch_Form_Entry', 'formRule'), $this);
170
171 // add the force save button
172 $forceSave = $this->getButtonName('upload', 'force');
173
174 $this->addElement('submit',
175 $forceSave,
176 ts('Ignore Mismatch & Process the Batch?')
177 );
178
179 $this->addButtons(array(
180 array(
181 'type' => 'upload',
182 'name' => ts('Validate & Process the Batch'),
21dfd5f5 183 'isDefault' => TRUE,
6a488035
TO
184 ),
185 array(
186 'type' => 'cancel',
187 'name' => ts('Save & Continue Later'),
21dfd5f5 188 ),
6a488035
TO
189 )
190 );
191
192 $this->assign('rowCount', $this->_batchInfo['item_count'] + 1);
193
6a488035 194 $preserveDefaultsArray = array(
353ffa53
TO
195 'first_name',
196 'last_name',
197 'middle_name',
6a488035
TO
198 'organization_name',
199 'household_name',
200 );
201
202 $contactTypes = array('Contact', 'Individual', 'Household', 'Organization');
70223980 203 $contactReturnProperties = array();
5056dc8e 204
6a488035 205 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) {
353ffa53
TO
206 $this->addEntityRef("primary_contact_id[{$rowNumber}]", '', array(
207 'create' => TRUE,
acb1052e 208 'placeholder' => ts('- select -'),
353ffa53 209 ));
6a488035
TO
210
211 // special field specific to membership batch udpate
212 if ($this->_batchInfo['type_id'] == 2) {
213 $options = array(
214 1 => ts('Add Membership'),
215 2 => ts('Renew Membership'),
216 );
217 $this->add('select', "member_option[$rowNumber]", '', $options);
218 }
00f6e1a8 219 if ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) {
691df66d 220 $options = array('' => '-select-');
04e6444d 221 $optionTypes = array(
222 '1' => ts('Adjust Pledge Payment Schedule?'),
223 '2' => ts('Adjust Total Pledge Amount?'),
224 );
8e2b1206 225 $this->add('select', "option_type[$rowNumber]", NULL, $optionTypes);
226 if (!empty($this->_batchId) && !empty($this->_batchInfo['data']) && !empty($rowNumber)) {
227 $dataValues = json_decode($this->_batchInfo['data'], TRUE);
5542b7c2 228 if (!empty($dataValues['values']['primary_contact_id'][$rowNumber])) {
229 $pledgeIDs = CRM_Pledge_BAO_Pledge::getContactPledges($dataValues['values']['primary_contact_id'][$rowNumber]);
230 foreach ($pledgeIDs as $pledgeID) {
231 $pledgePayment = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeID);
5056dc8e 232 $options += array($pledgeID => CRM_Utils_Date::customFormat($pledgePayment['schedule_date'], '%m/%d/%Y') . ', ' . $pledgePayment['amount'] . ' ' . $pledgePayment['currency']);
5542b7c2 233 }
8e2b1206 234 }
235 }
5056dc8e 236
b8e805eb 237 $this->add('select', "open_pledges[$rowNumber]", '', $options);
691df66d 238 }
8e2b1206 239
6a488035
TO
240 foreach ($this->_fields as $name => $field) {
241 if (in_array($field['field_type'], $contactTypes)) {
57465e2a 242 $fld = explode('-', $field['name']);
5b1666f7 243 $contactReturnProperties[$field['name']] = $fld[0];
6a488035
TO
244 }
245 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, NULL, FALSE, FALSE, $rowNumber);
246
247 if (in_array($field['name'], $preserveDefaultsArray)) {
248 $this->_preserveDefault = FALSE;
249 }
250 }
251 }
75140351 252
3f8a2e90 253 // CRM-19477: Display Error for Batch Sizes Exceeding php.ini max_input_vars
254 // Notes: $this->_elementIndex gives an approximate count of the variables being sent
75140351 255 // An offset value is set to deal with additional vars that are likely passed.
3f8a2e90 256 // There may be a more accurate way to do this...
49accad3 257 $offset = 50; // set an offset to account for other vars we are not counting
75140351 258 if ((count($this->_elementIndex) + $offset) > ini_get("max_input_vars")) {
259 CRM_Core_Error::fatal(ts('Batch size is too large. Increase value of php.ini setting "max_input_vars" (current val = ' . ini_get("max_input_vars") . ')'));
49accad3 260 }
75140351 261
6a488035 262 $this->assign('fields', $this->_fields);
57465e2a 263 CRM_Core_Resources::singleton()
353ffa53
TO
264 ->addSetting(array(
265 'contact' => array(
266 'return' => implode(',', $contactReturnProperties),
267 'fieldmap' => array_flip($contactReturnProperties),
acb1052e 268 ),
353ffa53 269 ));
6a488035
TO
270
271 // don't set the status message when form is submitted.
272 $buttonName = $this->controller->getButtonName('submit');
273
274 if ($suppressFields && $buttonName != '_qf_Entry_next') {
8f878cd3 275 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
276 }
277 }
278
279 /**
eceb18cc 280 * Form validations.
6a488035 281 *
82d480a5
TO
282 * @param array $params
283 * Posted values of the form.
284 * @param array $files
285 * List of errors to be posted back to the form.
1620f0bc 286 * @param \CRM_Batch_Form_Entry $self
82d480a5 287 * Form object.
6a488035 288 *
a6c01b45
CW
289 * @return array
290 * list of errors to be posted back to the form
6a488035 291 */
00be9182 292 public static function formRule($params, $files, $self) {
6a488035 293 $errors = array();
5056dc8e 294 $batchTypes = CRM_Core_Pseudoconstant::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate');
dddb4c8c 295 $fields = array(
4db803dd
CW
296 'total_amount' => ts('Amount'),
297 'financial_type' => ts('Financial Type'),
298 'payment_instrument' => ts('Payment Method'),
dddb4c8c 299 );
6a488035 300
0576b84b
SB
301 //CRM-16480 if contact is selected, validate financial type and amount field.
302 foreach ($params['field'] as $key => $value) {
47087bdc 303 if (isset($value['trxn_id'])) {
304 if (0 < CRM_Core_DAO::singleValueQuery('SELECT id FROM civicrm_contribution WHERE trxn_id = %1', array(1 => array($value['trxn_id'], 'String')))) {
305 $errors["field[$key][trxn_id]"] = ts('Transaction ID must be unique within the database');
306 }
307 }
61f45887 308 foreach ($fields as $field => $label) {
dddb4c8c 309 if (!empty($params['primary_contact_id'][$key]) && empty($value[$field])) {
ef0c5805 310 $errors["field[$key][$field]"] = ts('%1 is a required field.', array(1 => $label));
dddb4c8c 311 }
0576b84b
SB
312 }
313 }
314
a7488080 315 if (!empty($params['_qf_Entry_upload_force'])) {
0576b84b
SB
316 if (!empty($errors)) {
317 return $errors;
318 }
6a488035
TO
319 return TRUE;
320 }
321
322 $batchTotal = 0;
323 foreach ($params['field'] as $key => $value) {
324 $batchTotal += $value['total_amount'];
325
5ee60152 326 //validate for soft credit fields
ccec9d6b 327 if (!empty($params['soft_credit_contact_id'][$key]) && empty($params['soft_credit_amount'][$key])) {
d1401e86 328 $errors["soft_credit_amount[$key]"] = ts('Please enter the soft credit amount.');
5ee60152 329 }
8cc574cf 330 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
331 $errors["soft_credit_amount[$key]"] = ts('Soft credit amount should not be greater than the total amount');
332 }
8ef12e64 333
6a488035 334 //membership type is required for membership batch entry
5056dc8e 335 if ($self->_batchInfo['type_id'] == $batchTypes['Membership']) {
a7488080 336 if (empty($value['membership_type'][1])) {
6a488035
TO
337 $errors["field[$key][membership_type]"] = ts('Membership type is a required field.');
338 }
339 }
340 }
b8e805eb 341 if ($self->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) {
5056dc8e 342 foreach (array_unique($params["open_pledges"]) as $value) {
42724136 343 if (!empty($value)) {
344 $duplicateRows = array_keys($params["open_pledges"], $value);
345 }
346 if (!empty($duplicateRows) && count($duplicateRows) > 1) {
5056dc8e 347 foreach ($duplicateRows as $key) {
7f6a92ef 348 $errors["open_pledges[$key]"] = ts('You can not record two payments for the same pledge in a single batch.');
5056dc8e 349 }
350 }
351 }
352 }
28e8aa1b 353 if ((string) $batchTotal != $self->_batchInfo['total']) {
6a488035
TO
354 $self->assign('batchAmountMismatch', TRUE);
355 $errors['_qf_defaults'] = ts('Total for amounts entered below does not match the expected batch total.');
356 }
357
358 if (!empty($errors)) {
359 return $errors;
360 }
361
362 $self->assign('batchAmountMismatch', FALSE);
363 return TRUE;
364 }
365
366 /**
eceb18cc 367 * Override default cancel action.
6a488035 368 */
00be9182 369 public function cancelAction() {
6a488035
TO
370 // redirect to batch listing
371 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/batch', 'reset=1'));
372 CRM_Utils_System::civiExit();
373 }
374
375 /**
c490a46a 376 * Set default values for the form.
6a488035 377 */
00be9182 378 public function setDefaultValues() {
6a488035
TO
379 if (empty($this->_fields)) {
380 return;
381 }
382
383 // for add mode set smart defaults
481a74f4 384 if ($this->_action & CRM_Core_Action::ADD) {
3d927ee7 385 $currentDate = date('Y-m-d H-i-s');
6a488035 386
363544d7 387 $completeStatus = CRM_Contribute_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
8ef12e64 388 $specialFields = array(
04b40eab 389 'join_date' => date('Y-m-d'),
6a488035 390 'receive_date' => $currentDate,
21dfd5f5 391 'contribution_status_id' => $completeStatus,
6a488035
TO
392 );
393
394 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) {
481a74f4 395 foreach ($specialFields as $key => $value) {
8ef12e64 396 $defaults['field'][$rowNumber][$key] = $value;
6a488035 397 }
8ef12e64 398 }
6a488035
TO
399 }
400 else {
6c97864e 401 // get the cached info from data column of civicrm_batch
402 $data = CRM_Core_DAO::getFieldValue('CRM_Batch_BAO_Batch', $this->_batchId, 'data');
403 $defaults = json_decode($data, TRUE);
c0d307ec 404 $defaults = $defaults['values'];
6a488035 405 }
6c97864e 406
6a488035
TO
407 return $defaults;
408 }
409
410 /**
eceb18cc 411 * Process the form after the input has been submitted and validated.
6a488035
TO
412 */
413 public function postProcess() {
414 $params = $this->controller->exportValues($this->_name);
6a488035 415 $params['actualBatchTotal'] = 0;
d556e751 416
417 // get the profile information
04b40eab 418 $batchTypes = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate');
00f6e1a8 419 if (in_array($this->_batchInfo['type_id'], array($batchTypes['Pledge Payment'], $batchTypes['Contribution']))) {
6a488035
TO
420 $this->processContribution($params);
421 }
d556e751 422 elseif ($this->_batchInfo['type_id'] == $batchTypes['Membership']) {
6a488035
TO
423 $this->processMembership($params);
424 }
d556e751 425
6a488035
TO
426 // update batch to close status
427 $paramValues = array(
428 'id' => $this->_batchId,
429 // close status
1a453756 430 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Closed'),
6a488035
TO
431 'total' => $params['actualBatchTotal'],
432 );
433
434 CRM_Batch_BAO_Batch::create($paramValues);
435
6a488035
TO
436 // set success status
437 CRM_Core_Session::setStatus("", ts("Batch Processed."), "success");
438
439 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/batch', 'reset=1'));
440 }
441
442 /**
eceb18cc 443 * Process contribution records.
6a488035 444 *
82d480a5
TO
445 * @param array $params
446 * Associated array of submitted values.
6a488035 447 *
ce064e4f 448 * @return bool
6a488035
TO
449 */
450 private function processContribution(&$params) {
6a488035 451
cdd71d6b 452 foreach ($this->submittableMoneyFields as $moneyField) {
453 foreach ($params['field'] as $index => $fieldValues) {
454 if (isset($fieldValues[$moneyField])) {
455 $params['field'][$index][$moneyField] = CRM_Utils_Rule::cleanMoney($params['field'][$index][$moneyField]);
456 }
457 }
458 }
459 $params['actualBatchTotal'] = CRM_Utils_Rule::cleanMoney($params['actualBatchTotal']);
6a488035 460 // get the price set associated with offline contribution record.
9da8dc8c 461 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
462 $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
85020e43
EM
463 $priceFieldID = CRM_Price_BAO_PriceSet::getOnlyPriceFieldID($this->_priceSet);
464 $priceFieldValueID = CRM_Price_BAO_PriceSet::getOnlyPriceFieldValueID($this->_priceSet);
6a488035 465
6a488035
TO
466 if (isset($params['field'])) {
467 foreach ($params['field'] as $key => $value) {
468 // if contact is not selected we should skip the row
ccec9d6b 469 if (empty($params['primary_contact_id'][$key])) {
6a488035
TO
470 continue;
471 }
472
ccec9d6b 473 $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_id']);
6a488035
TO
474
475 // update contact information
476 $this->updateContactInfo($value);
477
5ee60152 478 //build soft credit params
ccec9d6b
CW
479 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
480 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
0689c15c 481 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
9e1854a1 482
483 //CRM-15350: if soft-credit-type profile field is disabled or removed then
484 //we choose configured SCT default value
485 if (!empty($params['soft_credit_type'][$key])) {
486 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
487 }
488 else {
489 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_OptionGroup::getDefaultValue("soft_credit_type");
490 }
6a488035
TO
491 }
492
b7714c80
AH
493 // Build PCP params
494 if (!empty($params['pcp_made_through_id'][$key])) {
495 $value['pcp']['pcp_made_through_id'] = $params['pcp_made_through_id'][$key];
496 $value['pcp']['pcp_display_in_roll'] = !empty($params['pcp_display_in_roll'][$key]);
497 if (!empty($params['pcp_roll_nickname'][$key])) {
498 $value['pcp']['pcp_roll_nickname'] = $params['pcp_roll_nickname'][$key];
499 }
500 if (!empty($params['pcp_personal_note'][$key])) {
501 $value['pcp']['pcp_personal_note'] = $params['pcp_personal_note'][$key];
502 }
503 }
504
6a488035 505 $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value,
df1f662a 506 NULL,
6a488035
TO
507 'Contribution'
508 );
509
a7488080 510 if (!empty($value['send_receipt'])) {
6a488035
TO
511 $value['receipt_date'] = date('Y-m-d His');
512 }
2e4a81d5
EM
513 // these translations & date handling are required because we are calling BAO directly rather than the api
514 $fieldTranslations = array(
515 'financial_type' => 'financial_type_id',
516 'payment_instrument' => 'payment_instrument_id',
517 'contribution_source' => 'source',
518 'contribution_note' => 'note',
6a488035 519
2e4a81d5
EM
520 );
521 foreach ($fieldTranslations as $formField => $baoField) {
5542b7c2 522 if (isset($value[$formField])) {
2e4a81d5
EM
523 $value[$baoField] = $value[$formField];
524 }
525 unset($value[$formField]);
6a488035
TO
526 }
527
528 $params['actualBatchTotal'] += $value['total_amount'];
6a488035
TO
529 $value['batch_id'] = $this->_batchId;
530 $value['skipRecentView'] = TRUE;
531
532 // build line item params
691df66d 533 $this->_priceSet['fields'][$priceFieldID]['options'][$priceFieldValueID]['amount'] = $value['total_amount'];
86bfa4f6 534 $value['price_' . $priceFieldID] = 1;
6a488035
TO
535
536 $lineItem = array();
9da8dc8c 537 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $value, $lineItem[$priceSetId]);
6a488035 538
c039f658 539 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
540 // function to get correct amount level consistently. Remove setting of the amount level in
541 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
542 // to cover all variants.
6a488035
TO
543 unset($value['amount_level']);
544
2e4a81d5 545 //CRM-11529 for back office transactions
8ef12e64 546 //when financial_type_id is passed in form, update the
2e4a81d5 547 //line items with the financial type selected in form
c039f658 548 // @todo - create a price set or price field per financial type & simply choose the appropriate
549 // price field rather than working around the fact that each price_field is supposed to have a financial
550 // type & we are allowing that to be overridden.
8cc574cf 551 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
6a488035
TO
552 foreach ($lineItem[$priceSetId] as &$values) {
553 $values['financial_type_id'] = $value['financial_type_id'];
554 }
555 }
556 $value['line_item'] = $lineItem;
cdd71d6b 557 $value['skipCleanMoney'] = TRUE;
6a488035 558 //finally call contribution create for all the magic
1273d77c 559 $contribution = CRM_Contribute_BAO_Contribution::create($value);
d556e751 560 $batchTypes = CRM_Core_Pseudoconstant::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate');
34b568c4 561 if (!empty($this->_batchInfo['type_id']) && ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment'])) {
04e6444d 562 $adjustTotalAmount = FALSE;
5056dc8e 563 if (isset($params['option_type'][$key])) {
564 if ($params['option_type'][$key] == 2) {
565 $adjustTotalAmount = TRUE;
566 }
04e6444d 567 }
ce70f330 568 $pledgeId = $params['open_pledges'][$key];
5056dc8e 569 if (is_numeric($pledgeId)) {
570 $result = CRM_Pledge_BAO_PledgePayment::getPledgePayments($pledgeId);
571 $pledgePaymentId = 0;
481a74f4 572 foreach ($result as $key => $values) {
5056dc8e 573 if ($values['status'] != 'Completed') {
574 $pledgePaymentId = $values['id'];
575 break;
576 }
04e6444d 577 }
5056dc8e 578 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentId, 'contribution_id', $contribution->id);
579 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId,
580 array($pledgePaymentId),
581 $contribution->contribution_status_id,
582 NULL,
583 $contribution->total_amount,
584 $adjustTotalAmount
585 );
04e6444d 586 }
04e6444d 587 }
5056dc8e 588
6a488035 589 //process premiums
a7488080 590 if (!empty($value['product_name'])) {
6a488035
TO
591 if ($value['product_name'][0] > 0) {
592 list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
593
594 $value['hidden_Premium'] = 1;
595 $value['product_option'] = CRM_Utils_Array::value(
596 $value['product_name'][1],
597 $options[$value['product_name'][0]]
598 );
599
600 $premiumParams = array(
601 'product_id' => $value['product_name'][0],
602 'contribution_id' => $contribution->id,
603 'product_option' => $value['product_option'],
604 'quantity' => 1,
605 );
606 CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
607 }
608 }
609 // end of premium
610
611 //send receipt mail.
5056dc8e 612 if ($contribution->id && !empty($value['send_receipt'])) {
691df66d
TO
613 // add the domain email id
614 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
615 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
616 $value['from_email_address'] = $domainEmail;
617 $value['contribution_id'] = $contribution->id;
43f77a2c 618 if (!empty($value['soft_credit'])) {
619 $value = array_merge($value, CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id));
620 }
481a74f4 621 CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $value);
6a488035
TO
622 }
623 }
624 }
2e4a81d5 625 return TRUE;
6a488035 626 }
6a488035
TO
627
628 /**
eceb18cc 629 * Process membership records.
6a488035 630 *
82d480a5
TO
631 * @param array $params
632 * Associated array of submitted values.
6a488035 633 *
6a488035 634 *
2e4a81d5 635 * @return bool
6a488035
TO
636 */
637 private function processMembership(&$params) {
6a488035 638
fd4b9293 639 // get the price set associated with offline membership
9da8dc8c 640 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
641 $this->_priceSet = $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
6a488035
TO
642
643 if (isset($params['field'])) {
04b40eab 644 // @todo - most of the wrangling in this function is because the api is not being used, especially date stuff.
6a488035
TO
645 $customFields = array();
646 foreach ($params['field'] as $key => $value) {
5471eacc 647 foreach ($value as $fieldKey => $fieldValue) {
648 if (isset($this->_fields[$fieldKey]) && $this->_fields[$fieldKey]['data_type'] === 'Money') {
649 $value[$fieldKey] = CRM_Utils_Rule::cleanMoney($fieldValue);
650 }
651 }
6a488035 652 // if contact is not selected we should skip the row
ccec9d6b 653 if (empty($params['primary_contact_id'][$key])) {
6a488035
TO
654 continue;
655 }
656
ccec9d6b 657 $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_id']);
6a488035
TO
658
659 // update contact information
660 $this->updateContactInfo($value);
661
662 $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
663
a7488080 664 if (!empty($value['send_receipt'])) {
6a488035
TO
665 $value['receipt_date'] = date('Y-m-d His');
666 }
667
a7488080 668 if (!empty($value['membership_source'])) {
6a488035
TO
669 $value['source'] = $value['membership_source'];
670 }
671
672 unset($value['membership_source']);
673
674 //Get the membership status
a7488080 675 if (!empty($value['membership_status'])) {
6a488035
TO
676 $value['status_id'] = $value['membership_status'];
677 unset($value['membership_status']);
678 }
679
680 if (empty($customFields)) {
681 // membership type custom data
682 $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $membershipTypeId);
683
684 $customFields = CRM_Utils_Array::crmArrayMerge($customFields,
685 CRM_Core_BAO_CustomField::getFields('Membership',
686 FALSE, FALSE, NULL, NULL, TRUE
687 )
688 );
689 }
690
691 //check for custom data
692 $value['custom'] = CRM_Core_BAO_CustomField::postProcess($params['field'][$key],
6a488035
TO
693 $key,
694 'Membership',
695 $membershipTypeId
696 );
697
a7488080 698 if (!empty($value['financial_type'])) {
6a488035
TO
699 $value['financial_type_id'] = $value['financial_type'];
700 }
701
a7488080 702 if (!empty($value['payment_instrument'])) {
6a488035
TO
703 $value['payment_instrument_id'] = $value['payment_instrument'];
704 }
705
706 // handle soft credit
9e1854a1 707 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
ccec9d6b 708 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
0689c15c 709 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
9e1854a1 710
711 //CRM-15350: if soft-credit-type profile field is disabled or removed then
712 //we choose Gift as default value as per Gift Membership rule
713 if (!empty($params['soft_credit_type'][$key])) {
714 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
715 }
716 else {
1a453756 717 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', 'Gift');
9e1854a1 718 }
6a488035
TO
719 }
720
5c6f56b5 721 $params['actualBatchTotal'] += (float) $value['total_amount'];
6a488035
TO
722
723 unset($value['financial_type']);
724 unset($value['payment_instrument']);
725
726 $value['batch_id'] = $this->_batchId;
727 $value['skipRecentView'] = TRUE;
728
729 // make entry in line item for contribution
8ef12e64 730
6a488035
TO
731 $editedFieldParams = array(
732 'price_set_id' => $priceSetId,
21dfd5f5 733 'name' => $value['membership_type'][0],
6a488035
TO
734 );
735
736 $editedResults = array();
9da8dc8c 737 CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
6a488035
TO
738
739 if (!empty($editedResults)) {
740 unset($this->_priceSet['fields']);
741 $this->_priceSet['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
742 unset($this->_priceSet['fields'][$editedResults['id']]['options']);
743 $fid = $editedResults['id'];
744 $editedFieldParams = array(
745 'price_field_id' => $editedResults['id'],
21dfd5f5 746 'membership_type_id' => $value['membership_type_id'],
6a488035
TO
747 );
748
749 $editedResults = array();
9da8dc8c 750 CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $editedResults);
6a488035 751 $this->_priceSet['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
a7488080 752 if (!empty($value['total_amount'])) {
6a488035
TO
753 $this->_priceSet['fields'][$fid]['options'][$editedResults['id']]['amount'] = $value['total_amount'];
754 }
755
756 $fieldID = key($this->_priceSet['fields']);
757 $value['price_' . $fieldID] = $editedResults['id'];
758
8ef12e64 759 $lineItem = array();
9da8dc8c 760 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
6a488035
TO
761 $value, $lineItem[$priceSetId]
762 );
763
8ef12e64 764 //CRM-11529 for backoffice transactions
765 //when financial_type_id is passed in form, update the
6a488035 766 //lineitems with the financial type selected in form
8cc574cf 767 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
6a488035
TO
768 foreach ($lineItem[$priceSetId] as &$values) {
769 $values['financial_type_id'] = $value['financial_type_id'];
770 }
771 }
8ef12e64 772
6a488035
TO
773 $value['lineItems'] = $lineItem;
774 $value['processPriceSet'] = TRUE;
775 }
776 // end of contribution related section
777
778 unset($value['membership_type']);
8ef12e64 779
691df66d 780 $value['is_renew'] = FALSE;
481a74f4 781 if (!empty($params['member_option']) && CRM_Utils_Array::value($key, $params['member_option']) == 2) {
61767a1d
EM
782
783 // The following parameter setting may be obsolete.
6a488035 784 $this->_params = $params;
691df66d 785 $value['is_renew'] = TRUE;
61767a1d
EM
786 $isPayLater = CRM_Utils_Array::value('is_pay_later', $params);
787 $campaignId = NULL;
788 if (isset($this->_values) && is_array($this->_values) && !empty($this->_values)) {
789 $campaignId = CRM_Utils_Array::value('campaign_id', $this->_params);
790 if (!array_key_exists('campaign_id', $this->_params)) {
791 $campaignId = CRM_Utils_Array::value('campaign_id', $this->_values);
792 }
793 }
04b40eab 794
795 $formDates = array(
796 'end_date' => CRM_Utils_Array::value('membership_end_date', $value),
797 'start_date' => CRM_Utils_Array::value('membership_start_date', $value),
798 );
620ce374 799 $membershipSource = CRM_Utils_Array::value('source', $value);
356bfcaf 800 list($membership) = CRM_Member_BAO_Membership::processMembership(
61767a1d 801 $value['contact_id'], $value['membership_type_id'], FALSE,
55d094e7 802 //$numTerms should be default to 1.
803 NULL, NULL, $value['custom'], 1, NULL, FALSE,
620ce374 804 NULL, $membershipSource, $isPayLater, $campaignId, $formDates
6a488035
TO
805 );
806
807 // make contribution entry
28cc62fc 808 $contrbutionParams = array_merge($value, array('membership_id' => $membership->id));
5471eacc 809 $contrbutionParams['skipCleanMoney'] = TRUE;
3febe800 810 // @todo - calling this from here is pretty hacky since it is called from membership.create anyway
811 // This form should set the correct params & not call this fn directly.
28cc62fc 812 CRM_Member_BAO_Membership::recordMembershipContribution($contrbutionParams);
8ef12e64 813 }
6a488035 814 else {
04b40eab 815 $dateTypes = array(
816 'join_date' => 'joinDate',
817 'membership_start_date' => 'startDate',
818 'membership_end_date' => 'endDate',
819 );
820
821 $dates = array(
822 'join_date',
823 'start_date',
824 'end_date',
825 'reminder_date',
826 );
827 foreach ($dateTypes as $dateField => $dateVariable) {
828 $$dateVariable = CRM_Utils_Date::processDate($value[$dateField]);
829 $fDate[$dateField] = CRM_Utils_Array::value($dateField, $value);
830 }
831
832 $calcDates = array();
833 $calcDates[$membershipTypeId] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeId,
834 $joinDate, $startDate, $endDate
835 );
836
837 foreach ($calcDates as $memType => $calcDate) {
838 foreach ($dates as $d) {
839 //first give priority to form values then calDates.
840 $date = CRM_Utils_Array::value($d, $value);
841 if (!$date) {
842 $date = CRM_Utils_Array::value($d, $calcDate);
843 }
844
845 $value[$d] = CRM_Utils_Date::processDate($date);
846 }
847 }
848
849 unset($value['membership_start_date']);
850 unset($value['membership_end_date']);
851 $ids = array();
852 $membership = CRM_Member_BAO_Membership::create($value, $ids);
6a488035
TO
853 }
854
855 //process premiums
a7488080 856 if (!empty($value['product_name'])) {
6a488035
TO
857 if ($value['product_name'][0] > 0) {
858 list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
859
860 $value['hidden_Premium'] = 1;
861 $value['product_option'] = CRM_Utils_Array::value(
862 $value['product_name'][1],
863 $options[$value['product_name'][0]]
864 );
865
866 $premiumParams = array(
867 'product_id' => $value['product_name'][0],
5056dc8e 868 'contribution_id' => CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id, 'contribution_id', 'membership_id'),
6a488035
TO
869 'product_option' => $value['product_option'],
870 'quantity' => 1,
871 );
872 CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
873 }
874 }
875 // end of premium
876
877 //send receipt mail.
481a74f4 878 if ($membership->id && !empty($value['send_receipt'])) {
6a488035 879
691df66d
TO
880 // add the domain email id
881 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
882 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
6a488035 883
691df66d 884 $value['from_email_address'] = $domainEmail;
353ffa53 885 $value['membership_id'] = $membership->id;
691df66d 886 $value['contribution_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id, 'contribution_id', 'membership_id');
481a74f4 887 CRM_Member_Form_Membership::emailReceipt($this, $value, $membership);
6a488035
TO
888 }
889 }
890 }
afe349ef 891 return TRUE;
6a488035
TO
892 }
893
894 /**
eceb18cc 895 * Update contact information.
6a488035 896 *
82d480a5
TO
897 * @param array $value
898 * Associated array of submitted values.
6a488035
TO
899 */
900 private function updateContactInfo(&$value) {
901 $value['preserveDBName'] = $this->_preserveDefault;
902
903 //parse street address, CRM-7768
904 CRM_Contact_Form_Task_Batch::parseStreetAddress($value, $this);
905
906 CRM_Contact_BAO_Contact::createProfileContact($value, $this->_fields,
907 $value['contact_id']
908 );
909 }
cab024d4 910
afe349ef 911 /**
ce064e4f 912 * Function exists purely for unit testing purposes.
913 *
914 * If you feel tempted to use this in live code then it probably means there is some functionality
915 * that needs to be moved out of the form layer
cab024d4 916 *
4c16123d 917 * @param array $params
cab024d4
EM
918 *
919 * @return bool
afe349ef 920 */
00be9182 921 public function testProcessMembership($params) {
afe349ef 922 return $this->processMembership($params);
923 }
cab024d4
EM
924
925 /**
ce064e4f 926 * Function exists purely for unit testing purposes.
927 *
928 * If you feel tempted to use this in live code then it probably means there is some functionality
929 * that needs to be moved out of the form layer.
cab024d4
EM
930 *
931 * @param array $params
932 *
933 * @return bool
934 */
00be9182 935 public function testProcessContribution($params) {
cab024d4
EM
936 return $this->processContribution($params);
937 }
96025800 938
6a488035 939}