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