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