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