Merge pull request #12918 from davejenx/job_process_memberships_tests
[civicrm-core.git] / CRM / Member / Form / Membership.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
8c9251b3 6 | Copyright CiviCRM LLC (c) 2004-2018 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
8c9251b3 31 * @copyright CiviCRM LLC (c) 2004-2018
6a488035
TO
32 */
33
34/**
5e56c7a5 35 * This class generates form components for offline membership form.
6a488035
TO
36 */
37class CRM_Member_Form_Membership extends CRM_Member_Form {
38
39 protected $_memType = NULL;
40
41 protected $_onlinePendingContributionId;
42
43 public $_mode;
44
45 public $_contributeMode = 'direct';
46
47 protected $_recurMembershipTypes;
48
49 protected $_memTypeSelected;
50
d424ffde 51 /**
fe482240 52 * Display name of the member.
d424ffde
CW
53 *
54 * @var string
6a488035 55 */
b11c92be 56 protected $_memberDisplayName = NULL;
6a488035 57
d424ffde
CW
58 /**
59 * email of the person paying for the membership (used for receipts)
60 */
b11c92be 61 protected $_memberEmail = NULL;
6a488035 62
d424ffde 63 /**
fe482240 64 * Contact ID of the member.
d424ffde
CW
65 *
66 * @var int
67 */
cc984198 68 public $_contactID = NULL;
6a488035 69
d424ffde
CW
70 /**
71 * Display name of the person paying for the membership (used for receipts)
72 *
73 * @var string
74 */
b11c92be 75 protected $_contributorDisplayName = NULL;
6a488035 76
d424ffde 77 /**
b11c92be 78 * email of the person paying for the membership (used for receipts)
79 */
80 protected $_contributorEmail = NULL;
6a488035 81
d424ffde
CW
82 /**
83 * email of the person paying for the membership (used for receipts)
84 *
85 * @var int
86 */
b11c92be 87 protected $_contributorContactID = NULL;
6a488035 88
d424ffde 89 /**
fe482240 90 * ID of the person the receipt is to go to.
d424ffde
CW
91 *
92 * @var int
b11c92be 93 */
94 protected $_receiptContactId = NULL;
6a488035 95
d424ffde 96 /**
4aa7d844 97 * Keep a class variable for ALL membership IDs so
6a488035 98 * postProcess hook function can do something with it
d424ffde
CW
99 *
100 * @var array
6a488035 101 */
b11c92be 102 protected $_membershipIDs = array();
6a488035 103
5d86176b 104 /**
4aa7d844 105 * An array to hold a list of date fields on the form
5d86176b 106 * so that they can be converted to ISO in a consistent manner
107 *
108 * @var array
109 */
110 protected $_dateFields = array(
111 'receive_date' => array('default' => 'now'),
112 );
113
e4f5c851 114 /**
59c798c9 115 * Set entity fields to be assigned to the form.
116 */
117 protected function setEntityFields() {
118 $this->entityFields = [
119 'join_date' => [
120 'name' => 'join_date',
121 'description' => ts('Member Since'),
122 ],
123 'start_date' => [
124 'name' => 'start_date',
125 'description' => ts('Start Date'),
126 ],
127 'end_date' => [
128 'name' => 'end_date',
129 'description' => ts('End Date'),
130 ],
131 ];
132 }
133
134 /**
135 * Set the delete message.
e4f5c851 136 *
59c798c9 137 * We do this from the constructor in order to do a translation.
e4f5c851 138 */
59c798c9 139 public function setDeleteMessage() {
140 $this->deleteMessage = '<span class="font-red bold">'
141 . ts("WARNING: Deleting this membership will also delete any related payment (contribution) records." . ts("This action cannot be undone.")
142 . '</span><p>'
143 . ts("Consider modifying the membership status instead if you want to maintain an audit trail and avoid losing payment data. You can set the status to Cancelled by editing the membership and clicking the Status Override checkbox.")
144 . '</p><p>'
145 . ts("Click 'Delete' if you want to continue.") . '</p>');
e4f5c851 146 }
147
59c798c9 148 /**
149 * Overriding this entity trait function as not yet tested.
150 *
151 * We continue to rely on legacy handling.
152 */
153 public function addCustomDataToForm() {}
154
155
156 /**
157 * Overriding this entity trait function as not yet tested.
158 *
159 * We continue to rely on legacy handling.
160 */
161 public function addFormButtons() {}
162
18aa3e1e 163 /**
4efc56ef
EM
164 * Get selected membership type from the form values.
165 *
e4a6290d 166 * @param array $priceSet
4efc56ef
EM
167 * @param array $params
168 *
169 * @return array
18aa3e1e 170 */
e4a6290d 171 public static function getSelectedMemberships($priceSet, $params) {
18aa3e1e 172 $memTypeSelected = array();
e4a6290d 173 $priceFieldIDS = self::getPriceFieldIDs($params, $priceSet);
ccb02c2d 174 if (isset($params['membership_type_id']) && !empty($params['membership_type_id'][1])) {
175 $memTypeSelected = array($params['membership_type_id'][1] => $params['membership_type_id'][1]);
176 }
177 else {
18aa3e1e
EM
178 foreach ($priceFieldIDS as $priceFieldId) {
179 if ($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
180 $memTypeSelected[$id] = $id;
181 }
182 }
183 }
18aa3e1e
EM
184 return $memTypeSelected;
185 }
186
187 /**
188 * Extract price set fields and values from $params.
189 *
5e56c7a5 190 * @param array $params
e4a6290d 191 * @param array $priceSet
5e56c7a5 192 *
18aa3e1e
EM
193 * @return array
194 */
e4a6290d 195 public static function getPriceFieldIDs($params, $priceSet) {
15724d0a 196 $priceFieldIDS = array();
e4a6290d 197 if (isset($priceSet['fields']) && is_array($priceSet['fields'])) {
15724d0a 198 foreach ($priceSet['fields'] as $fieldId => $field) {
e4a6290d 199 if (!empty($params['price_' . $fieldId])) {
200 if (is_array($params['price_' . $fieldId])) {
201 foreach ($params['price_' . $fieldId] as $priceFldVal => $isSet) {
202 if ($isSet) {
203 $priceFieldIDS[] = $priceFldVal;
204 }
18aa3e1e
EM
205 }
206 }
15724d0a 207 elseif (!$field['is_enter_qty']) {
e4a6290d 208 $priceFieldIDS[] = $params['price_' . $fieldId];
209 }
18aa3e1e
EM
210 }
211 }
212 }
213 return $priceFieldIDS;
214 }
215
5e56c7a5 216 /**
217 * Form preProcess function.
218 *
219 * @throws \Exception
220 */
6a488035 221 public function preProcess() {
186a737c
EM
222 // This string makes up part of the class names, differentiating them (not sure why) from the membership fields.
223 $this->assign('formClass', 'membership');
a6513ad5 224 parent::preProcess();
59c798c9 225 if ($this->isUpdateToExistingRecurringMembership()) {
226 $this->entityFields['end_date']['is_freeze'] = TRUE;
227 }
6a488035
TO
228 // get price set id.
229 $this->_priceSetId = CRM_Utils_Array::value('priceSetId', $_GET);
230 $this->set('priceSetId', $this->_priceSetId);
231 $this->assign('priceSetId', $this->_priceSetId);
232
6a488035
TO
233 if ($this->_action & CRM_Core_Action::DELETE) {
234 $contributionID = CRM_Member_BAO_Membership::getMembershipContributionId($this->_id);
235 // check delete permission for contribution
236 if ($this->_id && $contributionID && !CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
96ca8376 237 CRM_Core_Error::fatal(ts("This Membership is linked to a contribution. You must have 'delete in CiviContribute' permission in order to delete this record."));
6a488035
TO
238 }
239 }
240
6a488035 241 if ($this->_action & CRM_Core_Action::ADD) {
6a488035
TO
242 if ($this->_contactID) {
243 //check whether contact has a current membership so we can alert user that they may want to do a renewal instead
4256ea25
AH
244 $contactMemberships = array();
245 $memParams = array('contact_id' => $this->_contactID);
246 CRM_Member_BAO_Membership::getValues($memParams, $contactMemberships, TRUE);
247 $cMemTypes = array();
248 foreach ($contactMemberships as $mem) {
249 $cMemTypes[] = $mem['membership_type_id'];
250 }
251 if (count($cMemTypes) > 0) {
252 $memberorgs = CRM_Member_BAO_MembershipType::getMemberOfContactByMemTypes($cMemTypes);
253 $mems_by_org = array();
2e8b13d1 254 foreach ($contactMemberships as $mem) {
4256ea25 255 $mem['member_of_contact_id'] = CRM_Utils_Array::value($mem['membership_type_id'], $memberorgs);
a7488080 256 if (!empty($mem['membership_end_date'])) {
4256ea25
AH
257 $mem['membership_end_date'] = CRM_Utils_Date::customformat($mem['membership_end_date']);
258 }
259 $mem['membership_type'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
260 $mem['membership_type_id'],
261 'name', 'id'
6a488035 262 );
4256ea25
AH
263 $mem['membership_status'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus',
264 $mem['status_id'],
265 'label', 'id'
6a488035 266 );
74dd0d90
CW
267 $mem['renewUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership',
268 "reset=1&action=renew&cid={$this->_contactID}&id={$mem['id']}&context=membership&selectedChild=member"
269 . ($this->_mode ? '&mode=live' : '')
270 );
4256ea25
AH
271 $mem['membershipTab'] = CRM_Utils_System::url('civicrm/contact/view',
272 "reset=1&force=1&cid={$this->_contactID}&selectedChild=member"
273 );
274 $mems_by_org[$mem['member_of_contact_id']] = $mem;
6a488035 275 }
74dd0d90 276 $this->assign('existingContactMemberships', $mems_by_org);
6a488035
TO
277 }
278 }
1001e556 279 else {
74dd0d90 280 // In standalone mode we don't have a contact id yet so lookup will be done client-side with this script:
d292601b
AH
281 $resources = CRM_Core_Resources::singleton();
282 $resources->addScriptFile('civicrm', 'templates/CRM/Member/Form/MembershipStandalone.js');
d292601b
AH
283 $passthru = array(
284 'typeorgs' => CRM_Member_BAO_MembershipType::getMembershipTypeOrganization(),
74dd0d90
CW
285 'memtypes' => CRM_Core_PseudoConstant::get('CRM_Member_BAO_Membership', 'membership_type_id'),
286 'statuses' => CRM_Core_PseudoConstant::get('CRM_Member_BAO_Membership', 'status_id'),
d292601b
AH
287 );
288 $resources->addSetting(array('existingMems' => $passthru));
289 }
6a488035
TO
290 }
291
97ae4877 292 if (!$this->_memType) {
293 $params = CRM_Utils_Request::exportValues();
06470609 294 if (!empty($params['membership_type_id'][1])) {
71098424 295 $this->_memType = $params['membership_type_id'][1];
296 }
97ae4877 297 }
6452294d
MW
298
299 // Add custom data to form
300 CRM_Custom_Form_CustomData::addToForm($this, $this->_memType);
6a488035
TO
301
302 // CRM-4395, get the online pending contribution id.
303 $this->_onlinePendingContributionId = NULL;
304 if (!$this->_mode && $this->_id && ($this->_action & CRM_Core_Action::UPDATE)) {
305 $this->_onlinePendingContributionId = CRM_Contribute_BAO_Contribution::checkOnlinePendingContribution($this->_id,
306 'Membership'
307 );
308 }
309 $this->assign('onlinePendingContributionId', $this->_onlinePendingContributionId);
6a488035 310
e2046b33 311 $this->setPageTitle(ts('Membership'));
6a488035
TO
312 }
313
314 /**
5e56c7a5 315 * Set default values for the form.
6a488035
TO
316 */
317 public function setDefaultValues() {
6a488035
TO
318
319 if ($this->_priceSetId) {
9da8dc8c 320 return CRM_Price_BAO_PriceSet::setDefaultPriceSet($this, $defaults);
6a488035
TO
321 }
322
323 $defaults = parent::setDefaultValues();
324
325 //setting default join date and receive date
569fe706 326 list($now, $currentTime) = CRM_Utils_Date::setDateDefaults();
6a488035
TO
327 if ($this->_action == CRM_Core_Action::ADD) {
328 $defaults['receive_date'] = $now;
569fe706 329 $defaults['receive_date_time'] = $currentTime;
6a488035
TO
330 }
331
6a488035
TO
332 $defaults['num_terms'] = 1;
333
a7488080 334 if (!empty($defaults['id'])) {
6a488035
TO
335 if ($this->_onlinePendingContributionId) {
336 $defaults['record_contribution'] = $this->_onlinePendingContributionId;
337 }
338 else {
339 $contributionId = CRM_Core_DAO::singleValueQuery("
340 SELECT contribution_id
341 FROM civicrm_membership_payment
342 WHERE membership_id = $this->_id
343 ORDER BY contribution_id
344 DESC limit 1");
345
346 if ($contributionId) {
347 $defaults['record_contribution'] = $contributionId;
348 }
349 }
350 }
133e2c99 351
374a4dd6 352 //set Soft Credit Type to Gift by default
353 $scTypes = CRM_Core_OptionGroup::values("soft_credit_type");
354 $defaults['soft_credit_type_id'] = CRM_Utils_Array::value(ts('Gift'), array_flip($scTypes));
355
a7488080 356 if (!empty($defaults['record_contribution']) && !$this->_mode) {
6a488035
TO
357 $contributionParams = array('id' => $defaults['record_contribution']);
358 $contributionIds = array();
359
360 //keep main object campaign in hand.
361 $memberCampaignId = CRM_Utils_Array::value('campaign_id', $defaults);
362
363 CRM_Contribute_BAO_Contribution::getValues($contributionParams, $defaults, $contributionIds);
364
365 //get back original object campaign id.
366 $defaults['campaign_id'] = $memberCampaignId;
367
a7488080 368 if (!empty($defaults['receive_date'])) {
6a488035
TO
369 list($defaults['receive_date']) = CRM_Utils_Date::setDateDefaults($defaults['receive_date']);
370 }
371
372 // Contribution::getValues() over-writes the membership record's source field value - so we need to restore it.
a7488080 373 if (!empty($defaults['membership_source'])) {
6a488035
TO
374 $defaults['source'] = $defaults['membership_source'];
375 }
376 }
d96cf288 377 //CRM-13420
a7488080 378 if (empty($defaults['payment_instrument_id'])) {
d96cf288
DG
379 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
380 }
6a488035
TO
381
382 // User must explicitly choose to send a receipt in both add and update mode.
383 $defaults['send_receipt'] = 0;
384
385 if ($this->_action & CRM_Core_Action::UPDATE) {
386 // in this mode by default uncheck this checkbox
387 unset($defaults['record_contribution']);
388 }
389
2e8b13d1 390 $subscriptionCancelled = FALSE;
a7488080 391 if (!empty($defaults['id'])) {
6a488035
TO
392 $subscriptionCancelled = CRM_Member_BAO_Membership::isSubscriptionCancelled($this->_id);
393 }
394
395 $alreadyAutoRenew = FALSE;
a7488080 396 if (!empty($defaults['contribution_recur_id']) && !$subscriptionCancelled) {
6a488035
TO
397 $defaults['auto_renew'] = 1;
398 $alreadyAutoRenew = TRUE;
399 }
400 $this->assign('alreadyAutoRenew', $alreadyAutoRenew);
401
402 $this->assign('member_is_test', CRM_Utils_Array::value('member_is_test', $defaults));
403
404 $this->assign('membership_status_id', CRM_Utils_Array::value('status_id', $defaults));
405
a7488080 406 if (!empty($defaults['is_pay_later'])) {
6a488035
TO
407 $this->assign('is_pay_later', TRUE);
408 }
409 if ($this->_mode) {
3b8e6c3f 410 $defaults = $this->getBillingDefaults($defaults);
5e56c7a5 411 // hack to simplify credit card entry for testing
412 // $defaults['credit_card_type'] = 'Visa';
413 // $defaults['credit_card_number'] = '4807731747657838';
414 // $defaults['cvv2'] = '000';
415 // $defaults['credit_card_exp_date'] = array( 'Y' => '2012', 'M' => '05' );
6a488035
TO
416 }
417
6a488035 418 //setting default join date if there is no join date
a7488080 419 if (empty($defaults['join_date'])) {
59c798c9 420 $defaults['join_date'] = date('Y-m-d H:i:s');
6a488035
TO
421 }
422
a7488080 423 if (!empty($defaults['membership_end_date'])) {
6a488035
TO
424 $this->assign('endDate', $defaults['membership_end_date']);
425 }
426
427 return $defaults;
428 }
429
430 /**
fe482240 431 * Build the form object.
6a488035
TO
432 */
433 public function buildQuickForm() {
6a488035 434
59c798c9 435 $this->buildQuickEntityForm();
579e1e0e 436 $this->assign('currency', CRM_Core_Config::singleton()->defaultCurrencySymbol);
53d0a906 437 $isUpdateToExistingRecurringMembership = $this->isUpdateToExistingRecurringMembership();
6a488035
TO
438 // build price set form.
439 $buildPriceSet = FALSE;
8cc574cf 440 if ($this->_priceSetId || !empty($_POST['price_set_id'])) {
a7488080 441 if (!empty($_POST['price_set_id'])) {
6a488035
TO
442 $buildPriceSet = TRUE;
443 }
444 $getOnlyPriceSetElements = TRUE;
445 if (!$this->_priceSetId) {
446 $this->_priceSetId = $_POST['price_set_id'];
447 $getOnlyPriceSetElements = FALSE;
448 }
449
450 $this->set('priceSetId', $this->_priceSetId);
9da8dc8c 451 CRM_Price_BAO_PriceSet::buildPriceSet($this);
6a488035
TO
452
453 $optionsMembershipTypes = array();
454 foreach ($this->_priceSet['fields'] as $pField) {
455 if (empty($pField['options'])) {
456 continue;
457 }
458 foreach ($pField['options'] as $opId => $opValues) {
459 $optionsMembershipTypes[$opId] = CRM_Utils_Array::value('membership_type_id', $opValues, 0);
460 }
461 }
462
9da8dc8c 463 $this->assign('autoRenewOption', CRM_Price_BAO_PriceSet::checkAutoRenewForPriceSet($this->_priceSetId));
6a488035
TO
464
465 $this->assign('optionsMembershipTypes', $optionsMembershipTypes);
5a9c4d4a 466 $this->assign('contributionType', CRM_Utils_Array::value('financial_type_id', $this->_priceSet));
6a488035
TO
467
468 // get only price set form elements.
469 if ($getOnlyPriceSetElements) {
470 return;
471 }
472 }
473
474 // use to build form during form rule.
475 $this->assign('buildPriceSet', $buildPriceSet);
476
477 if ($this->_action & CRM_Core_Action::ADD) {
478 $buildPriceSet = FALSE;
9da8dc8c 479 $priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviMember');
6a488035
TO
480 if (!empty($priceSets)) {
481 $buildPriceSet = TRUE;
482 }
483
484 if ($buildPriceSet) {
485 $this->add('select', 'price_set_id', ts('Choose price set'),
486 array(
21dfd5f5 487 '' => ts('Choose price set'),
b11c92be 488 ) + $priceSets,
6a488035
TO
489 NULL, array('onchange' => "buildAmount( this.value );")
490 );
491 }
492 $this->assign('hasPriceSets', $buildPriceSet);
493 }
494
6a488035
TO
495 if ($this->_action & CRM_Core_Action::DELETE) {
496 $this->addButtons(array(
c5c263ca
AH
497 array(
498 'type' => 'next',
499 'name' => ts('Delete'),
500 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
501 'isDefault' => TRUE,
502 ),
503 array(
504 'type' => 'cancel',
505 'name' => ts('Cancel'),
506 ),
507 ));
6a488035
TO
508 return;
509 }
510
511 if ($this->_context == 'standalone') {
353ffa53 512 $this->addEntityRef('contact_id', ts('Contact'), array(
c5c263ca
AH
513 'create' => TRUE,
514 'api' => array('extra' => array('email')),
515 ), TRUE);
6a488035
TO
516 }
517
518 $selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
519
c60d2e2c 520 // Throw status bounce when no Membership type or priceset is present
7284a1a4
PN
521 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
522 && empty($this->allMembershipTypeDetails) && empty($priceSets)
523 ) {
c60d2e2c
PN
524 CRM_Core_Error::statusBounce(ts('You do not have all the permissions needed for this page.'));
525 }
6a488035 526 // retrieve all memberships
ab30e033
EM
527 $allMembershipInfo = array();
528 foreach ($this->allMembershipTypeDetails as $key => $values) {
529 if ($this->_mode && empty($values['minimum_fee'])) {
530 continue;
531 }
532 else {
533 $memberOfContactId = CRM_Utils_Array::value('member_of_contact_id', $values);
534 if (empty($selMemTypeOrg[$memberOfContactId])) {
535 $selMemTypeOrg[$memberOfContactId] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
536 $memberOfContactId,
537 'display_name',
538 'id'
539 );
6a488035 540
ab30e033 541 $selOrgMemType[$memberOfContactId][0] = ts('- select -');
6a488035 542 }
ab30e033
EM
543 if (empty($selOrgMemType[$memberOfContactId][$key])) {
544 $selOrgMemType[$memberOfContactId][$key] = CRM_Utils_Array::value('name', $values);
6a488035 545 }
6a488035 546 }
decbd3d0 547 $totalAmount = CRM_Utils_Array::value('minimum_fee', $values);
548 //CRM-18827 - override the default value if total_amount is submitted
549 if (!empty($this->_submitValues['total_amount'])) {
550 $totalAmount = $this->_submitValues['total_amount'];
551 }
ab30e033
EM
552 // build membership info array, which is used when membership type is selected to:
553 // - set the payment information block
554 // - set the max related block
555 $allMembershipInfo[$key] = array(
556 'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $values),
decbd3d0 557 'total_amount' => CRM_Utils_Money::format($totalAmount, NULL, '%a'),
558 'total_amount_numeric' => $totalAmount,
ab30e033
EM
559 'auto_renew' => CRM_Utils_Array::value('auto_renew', $values),
560 'has_related' => isset($values['relationship_type_id']),
561 'max_related' => CRM_Utils_Array::value('max_related', $values),
562 );
6a488035
TO
563 }
564
565 $this->assign('allMembershipInfo', json_encode($allMembershipInfo));
566
567 // show organization by default, if only one organization in
568 // the list
569 if (count($selMemTypeOrg) == 2) {
570 unset($selMemTypeOrg[0], $selOrgMemType[0][0]);
571 }
572 //sort membership organization and type, CRM-6099
573 natcasesort($selMemTypeOrg);
574 foreach ($selOrgMemType as $index => $orgMembershipType) {
575 natcasesort($orgMembershipType);
576 $selOrgMemType[$index] = $orgMembershipType;
577 }
578
ab30e033
EM
579 $memTypeJs = array(
580 'onChange' => "buildMaxRelated(this.value,true); CRM.buildCustomData('Membership', this.value);",
581 );
8deb20a3 582
ab30e033 583 if (!empty($this->_recurPaymentProcessors)) {
8c80f3f9 584 $memTypeJs['onChange'] = "" . $memTypeJs['onChange'] . "buildAutoRenew(this.value, null, '{$this->_mode}');";
ab30e033 585 }
6a488035 586
6a488035
TO
587 $this->add('text', 'max_related', ts('Max related'),
588 CRM_Core_DAO::getAttribute('CRM_Member_DAO_Membership', 'max_related')
589 );
590
353ffa53 591 $sel = &$this->addElement('hierselect',
6a488035
TO
592 'membership_type_id',
593 ts('Membership Organization and Type'),
594 $memTypeJs
595 );
596
597 $sel->setOptions(array($selMemTypeOrg, $selOrgMemType));
53d0a906 598 if ($isUpdateToExistingRecurringMembership) {
599 $sel->freeze();
6a488035
TO
600 }
601
6a488035
TO
602 if ($this->_action & CRM_Core_Action::ADD) {
603 $this->add('text', 'num_terms', ts('Number of Terms'), array('size' => 6));
604 }
605
6a488035
TO
606 $this->add('text', 'source', ts('Source'),
607 CRM_Core_DAO::getAttribute('CRM_Member_DAO_Membership', 'source')
608 );
609
610 //CRM-7362 --add campaigns.
611 $campaignId = NULL;
612 if ($this->_id) {
613 $campaignId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'campaign_id');
614 }
615 CRM_Campaign_BAO_Campaign::addCampaign($this, $campaignId);
616
617 if (!$this->_mode) {
618 $this->add('select', 'status_id', ts('Membership Status'),
619 array('' => ts('- select -')) + CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label')
620 );
e136f704
O
621
622 $statusOverride = $this->addElement('select', 'is_override', ts('Status Override?'),
623 CRM_Member_StatusOverrideTypes::getSelectOptions()
6a488035 624 );
53d0a906 625 if ($statusOverride && $isUpdateToExistingRecurringMembership) {
626 $statusOverride->freeze();
6a488035
TO
627 }
628
e136f704
O
629 $this->add('datepicker', 'status_override_end_date', ts('Status Override End Date'), '', FALSE, array('minDate' => time(), 'time' => FALSE));
630
6a488035
TO
631 $this->addElement('checkbox', 'record_contribution', ts('Record Membership Payment?'));
632
6a488035
TO
633 $this->add('text', 'total_amount', ts('Amount'));
634 $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
635
5d86176b 636 $this->addDate('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
6a488035
TO
637
638 $this->add('select', 'payment_instrument_id',
4db803dd 639 ts('Payment Method'),
6a488035
TO
640 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
641 FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
642 );
643 $this->add('text', 'trxn_id', ts('Transaction ID'));
644 $this->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
5e56c7a5 645 'objectExists', array(
646 'CRM_Contribute_DAO_Contribution',
647 $this->_id,
648 'trxn_id',
649 )
6a488035
TO
650 );
651
6a488035 652 $this->add('select', 'contribution_status_id',
7fe7b63d 653 ts('Payment Status'), CRM_Contribute_BAO_Contribution_Utils::getContributionStatuses('membership')
6a488035
TO
654 );
655 $this->add('text', 'check_number', ts('Check Number'),
656 CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
657 );
658 }
659 else {
660 //add field for amount to allow an amount to be entered that differs from minimum
661 $this->add('text', 'total_amount', ts('Amount'));
662 }
5a9c4d4a
PN
663 $this->add('select', 'financial_type_id',
664 ts('Financial Type'),
573fd305 665 array('' => ts('- select -')) + CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $this->_action)
5a9c4d4a 666 );
d80dbc14 667
d80dbc14 668 $this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different Contact?'));
186a737c 669
d80dbc14 670 $this->addSelect('soft_credit_type_id', array('entity' => 'contribution_soft'));
671 $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), array('create' => TRUE));
672
6a488035
TO
673 $this->addElement('checkbox',
674 'send_receipt',
675 ts('Send Confirmation and Receipt?'), NULL,
8c80f3f9 676 array('onclick' => "showEmailOptions()")
6a488035
TO
677 );
678
679 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
680
186a737c 681 $this->add('textarea', 'receipt_text', ts('Receipt Message'));
6a488035
TO
682
683 // Retrieve the name and email of the contact - this will be the TO for receipt email
684 if ($this->_contactID) {
685 list($this->_memberDisplayName,
686 $this->_memberEmail
b11c92be 687 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
6a488035
TO
688
689 $this->assign('emailExists', $this->_memberEmail);
690 $this->assign('displayName', $this->_memberDisplayName);
691 }
692
50b85bf9 693 if ($isUpdateToExistingRecurringMembership && CRM_Member_BAO_Membership::isCancelSubscriptionSupported($this->_id)) {
694 $this->assign('cancelAutoRenew',
695 CRM_Utils_System::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}")
696 );
697 }
53d0a906 698
50b85bf9 699 $this->assign('isRecur', $isUpdateToExistingRecurringMembership);
6a488035
TO
700
701 $this->addFormRule(array('CRM_Member_Form_Membership', 'formRule'), $this);
8c80f3f9 702 $mailingInfo = Civi::settings()->get('mailing_backend');
703 $this->assign('isEmailEnabledForSite', ($mailingInfo['outBound_option'] != 2));
6a488035
TO
704
705 parent::buildQuickForm();
706 }
707
708 /**
fe482240 709 * Validation.
6a488035 710 *
b2363ea8
TO
711 * @param array $params
712 * (ref.) an assoc array of name/value pairs.
6a488035 713 *
5e56c7a5 714 * @param array $files
715 * @param CRM_Member_Form_Membership $self
2a6da8d7
EM
716 *
717 * @throws CiviCRM_API3_Exception
72b3a70c
CW
718 * @return bool|array
719 * mixed true or array of errors
6a488035 720 */
00be9182 721 public static function formRule($params, $files, $self) {
6a488035
TO
722 $errors = array();
723
ccb02c2d 724 $priceSetId = self::getPriceSetID($params);
725 $priceSetDetails = self::getPriceSetDetails($params);
6a488035 726
e4a6290d 727 $selectedMemberships = self::getSelectedMemberships($priceSetDetails[$priceSetId], $params);
ccb02c2d 728
729 if (!empty($params['price_set_id'])) {
9da8dc8c 730 CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $params, $errors);
6a488035 731
15724d0a 732 $priceFieldIDS = self::getPriceFieldIDs($params, $priceSetDetails[$priceSetId]);
6a488035
TO
733
734 if (!empty($priceFieldIDS)) {
735 $ids = implode(',', $priceFieldIDS);
736
9da8dc8c 737 $count = CRM_Price_BAO_PriceSet::getMembershipCount($ids);
2e8b13d1 738 foreach ($count as $occurrence) {
b44e3f84 739 if ($occurrence > 1) {
6a488035
TO
740 $errors['_qf_default'] = ts('Select at most one option associated with the same membership type.');
741 }
742 }
6a488035 743 }
867047cd 744 // Return error if empty $self->_memTypeSelected
745 if (empty($errors) && empty($selectedMemberships)) {
746 $errors['_qf_default'] = ts('Select at least one membership option.');
747 }
748 if (!$self->_mode && empty($params['record_contribution'])) {
749 $errors['record_contribution'] = ts('Record Membership Payment is required when you use a price set.');
750 }
6a488035 751 }
867047cd 752 else {
753 if (empty($params['membership_type_id'][1])) {
754 $errors['membership_type_id'] = ts('Please select a membership type.');
755 }
6a488035
TO
756 $numterms = CRM_Utils_Array::value('num_terms', $params);
757 if ($numterms && intval($numterms) != $numterms) {
758 $errors['num_terms'] = ts('Please enter an integer for the number of terms.');
759 }
6a488035 760
356b5786 761 if (($self->_mode || isset($params['record_contribution'])) && empty($params['financial_type_id'])) {
867047cd 762 $errors['financial_type_id'] = ts('Please enter the financial Type.');
763 }
6a488035
TO
764 }
765
18aa3e1e
EM
766 if (!empty($errors) && (count($selectedMemberships) > 1)) {
767 $memberOfContacts = CRM_Member_BAO_MembershipType::getMemberOfContactByMemTypes($selectedMemberships);
6a488035
TO
768 $duplicateMemberOfContacts = array_count_values($memberOfContacts);
769 foreach ($duplicateMemberOfContacts as $countDuplicate) {
770 if ($countDuplicate > 1) {
771 $errors['_qf_default'] = ts('Please do not select more than one membership associated with the same organization.');
772 }
773 }
774 }
775
6a488035
TO
776 if (!empty($errors)) {
777 return $errors;
778 }
779
8cc574cf 780 if (!empty($params['record_contribution']) && empty($params['payment_instrument_id'])) {
4db803dd 781 $errors['payment_instrument_id'] = ts('Payment Method is a required field.');
d96cf288 782 }
6a488035 783
a7488080
CW
784 if (!empty($params['is_different_contribution_contact'])) {
785 if (empty($params['soft_credit_type_id'])) {
133e2c99 786 $errors['soft_credit_type_id'] = ts('Please Select a Soft Credit Type');
787 }
d80dbc14 788 if (empty($params['soft_credit_contact_id'])) {
789 $errors['soft_credit_contact_id'] = ts('Please select a contact');
133e2c99 790 }
791 }
792
a7488080 793 if (!empty($params['payment_processor_id'])) {
a479fe60 794 // validate payment instrument (e.g. credit card number)
f48e6cf7 795 CRM_Core_Payment_Form::validatePaymentInstrument($params['payment_processor_id'], $params, $errors, NULL);
6a488035
TO
796 }
797
798 $joinDate = NULL;
a7488080 799 if (!empty($params['join_date'])) {
6a488035
TO
800
801 $joinDate = CRM_Utils_Date::processDate($params['join_date']);
802
18aa3e1e 803 foreach ($selectedMemberships as $memType) {
6a488035 804 $startDate = NULL;
a7488080 805 if (!empty($params['start_date'])) {
6a488035
TO
806 $startDate = CRM_Utils_Date::processDate($params['start_date']);
807 }
808
809 // if end date is set, ensure that start date is also set
810 // and that end date is later than start date
6a488035 811 $endDate = NULL;
a7488080 812 if (!empty($params['end_date'])) {
6a488035
TO
813 $endDate = CRM_Utils_Date::processDate($params['end_date']);
814 }
815
816 $membershipDetails = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($memType);
817
818 if ($startDate && CRM_Utils_Array::value('period_type', $membershipDetails) == 'rolling') {
819 if ($startDate < $joinDate) {
820 $errors['start_date'] = ts('Start date must be the same or later than Member since.');
821 }
822 }
823
824 if ($endDate) {
825 if ($membershipDetails['duration_unit'] == 'lifetime') {
f476dde8 826 // Check if status is NOT cancelled or similar. For lifetime memberships, there is no automated
ae3d69ec
SG
827 // process to update status based on end-date. The user must change the status now.
828 $result = civicrm_api3('MembershipStatus', 'get', array(
829 'sequential' => 1,
830 'is_current_member' => 0,
831 ));
f476dde8 832 $tmp_statuses = $result['values'];
8efea814 833 $status_ids = array();
22e263ad 834 foreach ($tmp_statuses as $cur_stat) {
8efea814 835 $status_ids[] = $cur_stat['id'];
f476dde8 836 }
e136f704 837
481a74f4 838 if (empty($params['status_id']) || in_array($params['status_id'], $status_ids) == FALSE) {
f476dde8 839 $errors['status_id'] = ts('Please enter a status that does NOT represent a current membership status.');
e136f704
O
840 }
841
842 if (!empty($params['is_override']) && !CRM_Member_StatusOverrideTypes::isPermanent($params['is_override'])) {
843 $errors['is_override'] = ts('Because you set an End Date for a lifetime membership, This must be set to "Override Permanently"');
f476dde8 844 }
6a488035
TO
845 }
846 else {
847 if (!$startDate) {
848 $errors['start_date'] = ts('Start date must be set if end date is set.');
849 }
850 if ($endDate < $startDate) {
851 $errors['end_date'] = ts('End date must be the same or later than start date.');
852 }
853 }
854 }
855
5e56c7a5 856 // Default values for start and end dates if not supplied on the form.
6a488035
TO
857 $defaultDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType,
858 $joinDate,
859 $startDate,
860 $endDate
861 );
862
863 if (!$startDate) {
864 $startDate = CRM_Utils_Array::value('start_date',
865 $defaultDates
866 );
867 }
868 if (!$endDate) {
869 $endDate = CRM_Utils_Array::value('end_date',
870 $defaultDates
871 );
872 }
873
874 //CRM-3724, check for availability of valid membership status.
e136f704 875 if ((empty($params['is_override']) || CRM_Member_StatusOverrideTypes::isNo($params['is_override'])) && !isset($errors['_qf_default'])) {
6a488035
TO
876 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate,
877 $endDate,
878 $joinDate,
879 'today',
5f11bbcc
EM
880 TRUE,
881 $memType,
882 $params
6a488035
TO
883 );
884 if (empty($calcStatus)) {
885 $url = CRM_Utils_System::url('civicrm/admin/member/membershipStatus', 'reset=1&action=browse');
886 $errors['_qf_default'] = ts('There is no valid Membership Status available for selected membership dates.');
887 $status = ts('Oops, it looks like there is no valid membership status available for the given membership dates. You can <a href="%1">Configure Membership Status Rules</a>.', array(1 => $url));
888 if (!$self->_mode) {
e136f704 889 $status .= ' ' . ts('OR You can sign up by setting Status Override? to something other than "NO".');
6a488035
TO
890 }
891 CRM_Core_Session::setStatus($status, ts('Membership Status Error'), 'error');
892 }
893 }
894 }
895 }
896 else {
897 $errors['join_date'] = ts('Please enter the Member Since.');
898 }
899
e136f704
O
900 if (!empty($params['is_override']) && CRM_Member_StatusOverrideTypes::isOverridden($params['is_override']) && empty($params['status_id'])) {
901 $errors['status_id'] = ts('Please enter the Membership status.');
902 }
903
904 if (!empty($params['is_override']) && CRM_Member_StatusOverrideTypes::isUntilDate($params['is_override'])) {
905 if (empty($params['status_override_end_date'])) {
906 $errors['status_override_end_date'] = ts('Please enter the Membership override end date.');
907 }
6a488035
TO
908 }
909
910 //total amount condition arise when membership type having no
911 //minimum fee
912 if (isset($params['record_contribution'])) {
6a488035
TO
913 if (CRM_Utils_System::isNull($params['total_amount'])) {
914 $errors['total_amount'] = ts('Please enter the contribution.');
915 }
916 }
917
918 // validate contribution status for 'Failed'.
8cc574cf 919 if ($self->_onlinePendingContributionId && !empty($params['record_contribution']) &&
6a488035
TO
920 (CRM_Utils_Array::value('contribution_status_id', $params) ==
921 array_search('Failed', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))
922 )
923 ) {
924 $errors['contribution_status_id'] = ts('Please select a valid payment status before updating.');
925 }
926
927 return empty($errors) ? TRUE : $errors;
928 }
929
930 /**
fe482240 931 * Process the form submission.
6a488035
TO
932 */
933 public function postProcess() {
934 if ($this->_action & CRM_Core_Action::DELETE) {
3506b6cd 935 CRM_Member_BAO_Membership::del($this->_id);
6a488035
TO
936 return;
937 }
7865d848
EM
938 // get the submitted form values.
939 $this->_params = $this->controller->exportValues($this->_name);
e9fe9519 940 $this->prepareStatusOverrideValues();
6a488035 941
09108d7d 942 $this->submit();
7865d848
EM
943
944 $this->setUserContext();
945 }
946
e9fe9519
O
947 /**
948 * Prepares the values related to status override.
949 */
950 private function prepareStatusOverrideValues() {
951 $this->setOverrideDateValue();
952 $this->convertIsOverrideValue();
953 }
954
955 /**
956 * Sets status override end date to empty value if
957 * the selected override option is not 'until date'.
958 */
959 private function setOverrideDateValue() {
393f1657 960 if (!CRM_Member_StatusOverrideTypes::isUntilDate(CRM_Utils_Array::value('is_override', $this->_params))) {
e9fe9519
O
961 $this->_params['status_override_end_date'] = '';
962 }
963 }
964
e136f704
O
965 /**
966 * Convert the value of selected (status override?)
967 * option to TRUE if it indicate an overridden status
968 * or FALSE otherwise.
969 */
970 private function convertIsOverrideValue() {
971 $this->_params['is_override'] = CRM_Member_StatusOverrideTypes::isOverridden($this->_params['is_override']);
972 }
973
7865d848
EM
974 /**
975 * Send email receipt.
976 *
977 * @param CRM_Core_Form $form
978 * Form object.
979 * @param array $formValues
980 * @param object $membership
981 * Object.
982 *
983 * @return bool
984 * true if mail was sent successfully
985 */
986 public static function emailReceipt(&$form, &$formValues, &$membership) {
987 // retrieve 'from email id' for acknowledgement
beac1417 988 $receiptFrom = CRM_Utils_Array::value('from_email_address', $formValues);
7865d848
EM
989
990 if (!empty($formValues['payment_instrument_id'])) {
991 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
992 $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
993 }
994
995 // retrieve custom data
996 $customFields = $customValues = array();
997 if (property_exists($form, '_groupTree')
998 && !empty($form->_groupTree)
999 ) {
1000 foreach ($form->_groupTree as $groupID => $group) {
1001 if ($groupID == 'info') {
1002 continue;
1003 }
1004 foreach ($group['fields'] as $k => $field) {
1005 $field['title'] = $field['label'];
1006 $customFields["custom_{$k}"] = $field;
1007 }
1008 }
1009 }
1010
1011 $members = array(array('member_id', '=', $membership->id, 0, 0));
1012 // check whether its a test drive
1013 if ($form->_mode == 'test') {
1014 $members[] = array('member_test', '=', 1, 0, 0);
1015 }
1016
1017 CRM_Core_BAO_UFGroup::getValues($formValues['contact_id'], $customFields, $customValues, FALSE, $members);
0816949d 1018 $form->assign('customValues', $customValues);
7865d848
EM
1019
1020 if ($form->_mode) {
5103bd18 1021 $form->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
0b50eca0 1022 $form->_params,
1023 $form->_bltID
1024 ));
7d193e45 1025
7865d848
EM
1026 $date = CRM_Utils_Date::format($form->_params['credit_card_exp_date']);
1027 $date = CRM_Utils_Date::mysqlToIso($date);
1028 $form->assign('credit_card_exp_date', $date);
1029 $form->assign('credit_card_number',
1030 CRM_Utils_System::mungeCreditCard($form->_params['credit_card_number'])
1031 );
1032 $form->assign('credit_card_type', $form->_params['credit_card_type']);
1033 $form->assign('contributeMode', 'direct');
1034 $form->assign('isAmountzero', 0);
1035 $form->assign('is_pay_later', 0);
1036 $form->assign('isPrimary', 1);
1037 }
1038
1039 $form->assign('module', 'Membership');
1040 $form->assign('contactID', $formValues['contact_id']);
1041
1042 $form->assign('membershipID', CRM_Utils_Array::value('membership_id', $form->_params, CRM_Utils_Array::value('membership_id', $form->_defaultValues)));
1043
1044 if (!empty($formValues['contribution_id'])) {
1045 $form->assign('contributionID', $formValues['contribution_id']);
1046 }
1047 elseif (isset($form->_onlinePendingContributionId)) {
1048 $form->assign('contributionID', $form->_onlinePendingContributionId);
1049 }
1050
1051 if (!empty($formValues['contribution_status_id'])) {
1052 $form->assign('contributionStatusID', $formValues['contribution_status_id']);
1053 $form->assign('contributionStatus', CRM_Contribute_PseudoConstant::contributionStatus($formValues['contribution_status_id'], 'name'));
1054 }
1055
1056 if (!empty($formValues['is_renew'])) {
1057 $form->assign('receiptType', 'membership renewal');
1058 }
1059 else {
1060 $form->assign('receiptType', 'membership signup');
1061 }
1062 $form->assign('receive_date', CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $formValues)));
1063 $form->assign('formValues', $formValues);
1064
1065 if (empty($lineItem)) {
1066 $form->assign('mem_start_date', CRM_Utils_Date::customFormat($membership->start_date, '%B %E%f, %Y'));
1067 if (!CRM_Utils_System::isNull($membership->end_date)) {
1068 $form->assign('mem_end_date', CRM_Utils_Date::customFormat($membership->end_date, '%B %E%f, %Y'));
1069 }
1070 $form->assign('membership_name', CRM_Member_PseudoConstant::membershipType($membership->membership_type_id));
1071 }
1072
7865d848
EM
1073 $isBatchProcess = is_a($form, 'CRM_Batch_Form_Entry');
1074 if ((empty($form->_contributorDisplayName) || empty($form->_contributorEmail)) || $isBatchProcess) {
1075 // in this case the form is being called statically from the batch editing screen
1076 // having one class in the form layer call another statically is not greate
1077 // & we should aim to move this function to the BAO layer in future.
1078 // however, we can assume that the contact_id passed in by the batch
1079 // function will be the recipient
1080 list($form->_contributorDisplayName, $form->_contributorEmail)
1081 = CRM_Contact_BAO_Contact_Location::getEmailDetails($formValues['contact_id']);
1082 if (empty($form->_receiptContactId) || $isBatchProcess) {
1083 $form->_receiptContactId = $formValues['contact_id'];
1084 }
1085 }
1086 $template = CRM_Core_Smarty::singleton();
1087 $taxAmt = $template->get_template_vars('dataArray');
1088 $eventTaxAmt = $template->get_template_vars('totalTaxAmount');
aaffa79f 1089 $prefixValue = Civi::settings()->get('contribution_invoice_settings');
7865d848
EM
1090 $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
1091 if ((!empty($taxAmt) || isset($eventTaxAmt)) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
1092 $isEmailPdf = TRUE;
1093 }
1094 else {
1095 $isEmailPdf = FALSE;
1096 }
1097
1098 list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
1099 array(
1100 'groupName' => 'msg_tpl_workflow_membership',
1101 'valueName' => 'membership_offline_receipt',
1102 'contactId' => $form->_receiptContactId,
1103 'from' => $receiptFrom,
1104 'toName' => $form->_contributorDisplayName,
1105 'toEmail' => $form->_contributorEmail,
1106 'PDFFilename' => ts('receipt') . '.pdf',
1107 'isEmailPdf' => $isEmailPdf,
1108 'contributionId' => $formValues['contribution_id'],
1109 'isTest' => (bool) ($form->_action & CRM_Core_Action::PREVIEW),
1110 )
1111 );
1112
1113 return TRUE;
1114 }
1115
1116 /**
5e56c7a5 1117 * Submit function.
1118 *
1119 * This is also accessed by unit tests.
1120 *
7865d848
EM
1121 * @return array
1122 */
09108d7d 1123 public function submit() {
4bd318e0 1124 $isTest = ($this->_mode == 'test') ? 1 : 0;
09108d7d 1125 $this->storeContactFields($this->_params);
ba2f3f65 1126 $this->beginPostProcess();
09108d7d 1127 $formValues = $this->_params;
7865d848
EM
1128 $joinDate = $startDate = $endDate = NULL;
1129 $membershipTypes = $membership = $calcDate = array();
41709813 1130 $membershipType = NULL;
18135422 1131 $paymentInstrumentID = $this->_paymentProcessor['object']->getPaymentInstrumentID();
7865d848 1132
41709813 1133 $mailSend = FALSE;
ccb02c2d 1134 $formValues = $this->setPriceSetParameters($formValues);
7865d848
EM
1135 $params = $softParams = $ids = array();
1136
09108d7d 1137 $this->processBillingAddress();
7865d848 1138
08fd4b45
EM
1139 if ($this->_id) {
1140 $ids['membership'] = $params['id'] = $this->_id;
1141 }
1142 $ids['userId'] = CRM_Core_Session::singleton()->get('userID');
1143
7865d848
EM
1144 // Set variables that we normally get from context.
1145 // In form mode these are set in preProcess.
1146 //TODO: set memberships, fixme
1147 $this->setContextVariables($formValues);
ccb02c2d 1148
e4a6290d 1149 $this->_memTypeSelected = self::getSelectedMemberships(
ccb02c2d 1150 $this->_priceSet,
e4a6290d 1151 $formValues
1152 );
867047cd 1153 if (empty($formValues['financial_type_id'])) {
ccb02c2d 1154 $formValues['financial_type_id'] = $this->_priceSet['financial_type_id'];
867047cd 1155 }
7865d848 1156
6a488035 1157 $config = CRM_Core_Config::singleton();
6a488035 1158
18135422 1159 // @todo this is no longer required if we convert some date fields.
7865d848 1160 $this->convertDateFieldsToMySQL($formValues);
6a488035
TO
1161
1162 $membershipTypeValues = array();
1163 foreach ($this->_memTypeSelected as $memType) {
1164 $membershipTypeValues[$memType]['membership_type_id'] = $memType;
1165 }
1166
1167 //take the required membership recur values.
7865d848 1168 if ($this->_mode && !empty($formValues['auto_renew'])) {
ccb02c2d 1169 $params['is_recur'] = $formValues['is_recur'] = TRUE;
6a488035
TO
1170 $mapping = array(
1171 'frequency_interval' => 'duration_interval',
1172 'frequency_unit' => 'duration_unit',
1173 );
1174
1175 $count = 0;
1176 foreach ($this->_memTypeSelected as $memType) {
1177 $recurMembershipTypeValues = CRM_Utils_Array::value($memType,
1178 $this->_recurMembershipTypes, array()
1179 );
1180 foreach ($mapping as $mapVal => $mapParam) {
1181 $membershipTypeValues[$memType][$mapVal] = CRM_Utils_Array::value($mapParam,
1182 $recurMembershipTypeValues
1183 );
1184 if (!$count) {
ccb02c2d 1185 $formValues[$mapVal] = CRM_Utils_Array::value($mapParam,
6a488035
TO
1186 $recurMembershipTypeValues
1187 );
1188 }
1189 }
1190 $count++;
1191 }
6a488035
TO
1192 }
1193
ccb02c2d 1194 $isQuickConfig = $this->_priceSet['is_quick_config'];
1195
6a488035 1196 $termsByType = array();
9f1bc5dc 1197
ccb02c2d 1198 $lineItem = array($this->_priceSetId => array());
1199
08fd4b45 1200 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
1a1a2f4f 1201 $formValues, $lineItem[$this->_priceSetId], NULL, $this->_priceSetId);
ccb02c2d 1202
1203 if (CRM_Utils_Array::value('tax_amount', $formValues)) {
1204 $params['tax_amount'] = $formValues['tax_amount'];
08fd4b45 1205 }
ccb02c2d 1206 $params['total_amount'] = CRM_Utils_Array::value('amount', $formValues);
ccb02c2d 1207 if (!empty($lineItem[$this->_priceSetId])) {
1208 foreach ($lineItem[$this->_priceSetId] as &$li) {
08fd4b45
EM
1209 if (!empty($li['membership_type_id'])) {
1210 if (!empty($li['membership_num_terms'])) {
1211 $termsByType[$li['membership_type_id']] = $li['membership_num_terms'];
6a488035 1212 }
08fd4b45 1213 }
6a488035 1214
08fd4b45
EM
1215 ///CRM-11529 for quick config backoffice transactions
1216 //when financial_type_id is passed in form, update the
1217 //lineitems with the financial type selected in form
c26225d2 1218 $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $formValues);
08fd4b45
EM
1219 if ($isQuickConfig && $submittedFinancialType) {
1220 $li['financial_type_id'] = $submittedFinancialType;
6a488035
TO
1221 }
1222 }
1223 }
1224
6a488035
TO
1225 $params['contact_id'] = $this->_contactID;
1226
1227 $fields = array(
1228 'status_id',
1229 'source',
1230 'is_override',
e136f704 1231 'status_override_end_date',
6a488035
TO
1232 'campaign_id',
1233 );
1234
1235 foreach ($fields as $f) {
1236 $params[$f] = CRM_Utils_Array::value($f, $formValues);
1237 }
1238
1239 // fix for CRM-3724
1240 // when is_override false ignore is_admin statuses during membership
1241 // status calculation. similarly we did fix for import in CRM-3570.
a7488080 1242 if (empty($params['is_override'])) {
6a488035
TO
1243 $params['exclude_is_admin'] = TRUE;
1244 }
1245
1246 // process date params to mysql date format.
1247 $dateTypes = array(
1248 'join_date' => 'joinDate',
1249 'start_date' => 'startDate',
1250 'end_date' => 'endDate',
1251 );
1252 foreach ($dateTypes as $dateField => $dateVariable) {
1253 $$dateVariable = CRM_Utils_Date::processDate($formValues[$dateField]);
1254 }
1255
b09fe5ed 1256 $memTypeNumTerms = empty($termsByType) ? CRM_Utils_Array::value('num_terms', $formValues) : NULL;
6a488035
TO
1257
1258 $calcDates = array();
1259 foreach ($this->_memTypeSelected as $memType) {
1693f081 1260 if (empty($memTypeNumTerms)) {
1261 $memTypeNumTerms = CRM_Utils_Array::value($memType, $termsByType, 1);
1262 }
6a488035
TO
1263 $calcDates[$memType] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType,
1264 $joinDate, $startDate, $endDate, $memTypeNumTerms
1265 );
1266 }
1267
1268 foreach ($calcDates as $memType => $calcDate) {
5d86176b 1269 foreach (array_keys($dateTypes) as $d) {
6a488035
TO
1270 //first give priority to form values then calDates.
1271 $date = CRM_Utils_Array::value($d, $formValues);
1272 if (!$date) {
1273 $date = CRM_Utils_Array::value($d, $calcDate);
1274 }
1275
1276 $membershipTypeValues[$memType][$d] = CRM_Utils_Date::processDate($date);
6a488035
TO
1277 }
1278 }
1279
6a488035
TO
1280 foreach ($this->_memTypeSelected as $memType) {
1281 if (array_key_exists('max_related', $formValues)) {
c26225d2 1282 // max related memberships - take from form or inherit from membership type
6a488035
TO
1283 $membershipTypeValues[$memType]['max_related'] = CRM_Utils_Array::value('max_related', $formValues);
1284 }
6a488035 1285 $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField::postProcess($formValues,
6a488035
TO
1286 $this->_id,
1287 'Membership'
1288 );
6a488035
TO
1289 $membershipTypes[$memType] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
1290 $memType
1291 );
1292 }
1293
1294 $membershipType = implode(', ', $membershipTypes);
1295
1296 // Retrieve the name and email of the current user - this will be the FROM for the receipt email
ab30e033 1297 list($userName) = CRM_Contact_BAO_Contact_Location::getEmailDetails($ids['userId']);
6a488035 1298
d80dbc14 1299 //CRM-13981, allow different person as a soft-contributor of chosen type
b11c92be 1300 if ($this->_contributorContactID != $this->_contactID) {
91ef9be0 1301 $params['contribution_contact_id'] = $this->_contributorContactID;
ccb02c2d 1302 if (!empty($formValues['soft_credit_type_id'])) {
1303 $softParams['soft_credit_type_id'] = $formValues['soft_credit_type_id'];
91ef9be0 1304 $softParams['contact_id'] = $this->_contactID;
6a488035
TO
1305 }
1306 }
c26225d2
MWMC
1307
1308 $pendingMembershipStatusId = CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending');
1309
a7488080 1310 if (!empty($formValues['record_contribution'])) {
6a488035 1311 $recordContribution = array(
b11c92be 1312 'total_amount',
b11c92be 1313 'financial_type_id',
1314 'payment_instrument_id',
1315 'trxn_id',
1316 'contribution_status_id',
1317 'check_number',
1318 'campaign_id',
1319 'receive_date',
a55e39e9 1320 'card_type_id',
1321 'pan_truncation',
6a488035
TO
1322 );
1323
1324 foreach ($recordContribution as $f) {
1325 $params[$f] = CRM_Utils_Array::value($f, $formValues);
1326 }
1327
1328 if (!$this->_onlinePendingContributionId) {
2286d173 1329 if (empty($formValues['source'])) {
353ffa53 1330 $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', array(
7865d848
EM
1331 1 => $membershipType,
1332 2 => $userName,
1333 ));
2286d173
PD
1334 }
1335 else {
0e81467c 1336 $params['contribution_source'] = $formValues['source'];
2286d173 1337 }
0e81467c 1338 }
6a488035 1339
c26225d2 1340 $completedContributionStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
a7488080 1341 if (empty($params['is_override']) &&
c26225d2 1342 CRM_Utils_Array::value('contribution_status_id', $params) != $completedContributionStatusId
6a488035 1343 ) {
c26225d2 1344 $params['status_id'] = $pendingMembershipStatusId;
6a488035
TO
1345 $params['skipStatusCal'] = TRUE;
1346 $params['is_pay_later'] = 1;
1347 $this->assign('is_pay_later', 1);
1348 }
1349
a7488080 1350 if (!empty($formValues['send_receipt'])) {
5d86176b 1351 $params['receipt_date'] = CRM_Utils_Array::value('receive_date', $formValues);
6a488035
TO
1352 }
1353
1354 //insert financial type name in receipt.
1355 $formValues['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
1356 $formValues['financial_type_id']
1357 );
1358 }
1359
1360 // process line items, until no previous line items.
1361 if (!empty($lineItem)) {
1362 $params['lineItems'] = $lineItem;
1363 $params['processPriceSet'] = TRUE;
1364 }
1365 $createdMemberships = array();
1366 if ($this->_mode) {
ccb02c2d 1367 $params['total_amount'] = CRM_Utils_Array::value('total_amount', $formValues, 0);
a7f2d5fd 1368
1369 //CRM-20264 : Store CC type and number (last 4 digit) during backoffice or online payment
1370 $params['card_type_id'] = CRM_Utils_Array::value('card_type_id', $this->_params);
1371 $params['pan_truncation'] = CRM_Utils_Array::value('pan_truncation', $this->_params);
a8d4ff25 1372
ccb02c2d 1373 if (!$isQuickConfig) {
b11c92be 1374 $params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet',
ccb02c2d 1375 $this->_priceSetId,
6a488035
TO
1376 'financial_type_id'
1377 );
1378 }
1379 else {
5a9c4d4a 1380 $params['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $formValues);
6a488035
TO
1381 }
1382
ba2f3f65 1383 //get the payment processor id as per mode. Try removing in favour of beginPostProcess.
ccb02c2d 1384 $params['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor['id'];
09108d7d 1385 $params['register_date'] = date('YmdHis');
6a488035 1386
a1a94e61 1387 // add all the additional payment params we need
ba2f3f65 1388 // @todo the country & state values should be set by the call to $this->assignBillingAddress.
ccb02c2d 1389 $formValues["state_province-{$this->_bltID}"] = $formValues["billing_state_province-{$this->_bltID}"]
a271822c 1390 = CRM_Core_PseudoConstant::stateProvinceAbbreviation($formValues["billing_state_province_id-{$this->_bltID}"]);
ccb02c2d 1391 $formValues["country-{$this->_bltID}"] = $formValues["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($formValues["billing_country_id-{$this->_bltID}"]);
6a488035 1392
ccb02c2d 1393 $formValues['amount'] = $params['total_amount'];
ba2f3f65 1394 // @todo this is a candidate for beginPostProcessFunction.
ccb02c2d 1395 $formValues['currencyID'] = $config->defaultCurrency;
1396 $formValues['description'] = ts("Contribution submitted by a staff person using member's credit card for signup");
1397 $formValues['invoiceID'] = md5(uniqid(rand(), TRUE));
1398 $formValues['financial_type_id'] = $params['financial_type_id'];
6a488035
TO
1399
1400 // at this point we've created a contact and stored its address etc
1401 // all the payment processors expect the name and address to be in the
1402 // so we copy stuff over to first_name etc.
ccb02c2d 1403 $paymentParams = $formValues;
6a488035
TO
1404 $paymentParams['contactID'] = $this->_contributorContactID;
1405 //CRM-10377 if payment is by an alternate contact then we need to set that person
1406 // as the contact in the payment params
b11c92be 1407 if ($this->_contributorContactID != $this->_contactID) {
ccb02c2d 1408 if (!empty($formValues['soft_credit_type_id'])) {
133e2c99 1409 $softParams['contact_id'] = $params['contact_id'];
ccb02c2d 1410 $softParams['soft_credit_type_id'] = $formValues['soft_credit_type_id'];
6a488035
TO
1411 }
1412 }
ccb02c2d 1413 if (!empty($formValues['send_receipt'])) {
6a488035
TO
1414 $paymentParams['email'] = $this->_contributorEmail;
1415 }
1416
ba2f3f65 1417 // This is a candidate for shared beginPostProcess function.
ccb02c2d 1418 CRM_Core_Payment_Form::mapParams($this->_bltID, $formValues, $paymentParams, TRUE);
6a488035 1419 // CRM-7137 -for recurring membership,
b44e3f84 1420 // we do need contribution and recurring records.
6a488035 1421 $result = NULL;
a7488080 1422 if (!empty($paymentParams['is_recur'])) {
8a7b41d1
EM
1423 $financialType = new CRM_Financial_DAO_FinancialType();
1424 $financialType->id = $params['financial_type_id'];
1425 $financialType->find(TRUE);
ccb02c2d 1426 $this->_params = $formValues;
18135422 1427
ba013eea 1428 $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($this,
6a488035 1429 $paymentParams,
3febe800 1430 NULL,
f6261e9d 1431 array(
1432 'contact_id' => $this->_contributorContactID,
9b581f1d 1433 'line_item' => $lineItem,
f6261e9d 1434 'is_test' => $isTest,
1435 'campaign_id' => CRM_Utils_Array::value('campaign_id', $paymentParams),
ccb02c2d 1436 'contribution_page_id' => CRM_Utils_Array::value('contribution_page_id', $formValues),
3febe800 1437 'source' => CRM_Utils_Array::value('source', $paymentParams, CRM_Utils_Array::value('description', $paymentParams)),
1438 'thankyou_date' => CRM_Utils_Array::value('thankyou_date', $paymentParams),
18135422 1439 'payment_instrument_id' => $paymentInstrumentID,
f6261e9d 1440 ),
8a7b41d1 1441 $financialType,
4bd318e0 1442 FALSE,
449f4c90 1443 $this->_bltID,
1444 TRUE
6a488035 1445 );
133e2c99 1446
1447 //create new soft-credit record, CRM-13981
00c1cd97
CW
1448 if ($softParams) {
1449 $softParams['contribution_id'] = $contribution->id;
1450 $softParams['currency'] = $contribution->currency;
1451 $softParams['amount'] = $contribution->total_amount;
1452 CRM_Contribute_BAO_ContributionSoft::add($softParams);
1453 }
133e2c99 1454
a22bd791 1455 $paymentParams['contactID'] = $this->_contactID;
6a488035 1456 $paymentParams['contributionID'] = $contribution->id;
b11c92be 1457 $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
6a488035
TO
1458 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
1459 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
1460 $ids['contribution'] = $contribution->id;
1461 $params['contribution_recur_id'] = $paymentParams['contributionRecurID'];
6a488035 1462 }
c26225d2 1463 $paymentStatus = NULL;
6a488035
TO
1464
1465 if ($params['total_amount'] > 0.0) {
ab30e033 1466 $payment = $this->_paymentProcessor['object'];
06d062ce
EM
1467 try {
1468 $result = $payment->doPayment($paymentParams);
ccb02c2d 1469 $formValues = array_merge($formValues, $result);
c26225d2 1470 $paymentStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $formValues['payment_status_id']);
ab30e033
EM
1471 // Assign amount to template if payment was successful.
1472 $this->assign('amount', $params['total_amount']);
6a488035 1473 }
31176a73 1474 catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
06d062ce 1475 if (!empty($paymentParams['contributionID'])) {
ab30e033
EM
1476 CRM_Contribute_BAO_Contribution::failPayment($paymentParams['contributionID'], $this->_contactID,
1477 $e->getMessage());
06d062ce
EM
1478 }
1479 if (!empty($paymentParams['contributionRecurID'])) {
1480 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
1481 }
1482
63dd64f2 1483 CRM_Core_Session::singleton()->setStatus($e->getMessage());
06d062ce 1484 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership',
31176a73 1485 "reset=1&action=add&cid={$this->_contactID}&context=membership&mode={$this->_mode}"
06d062ce 1486 ));
6a488035 1487
06d062ce 1488 }
6a488035
TO
1489 }
1490
c26225d2
MWMC
1491 if ($paymentStatus !== 'Completed') {
1492 $params['status_id'] = $pendingMembershipStatusId;
7d193e45
LS
1493 $params['skipStatusCal'] = TRUE;
1494 // unset send-receipt option, since receipt will be sent when ipn is received.
ccb02c2d 1495 unset($formValues['send_receipt'], $formValues['send_receipt']);
7d193e45
LS
1496 //as membership is pending set dates to null.
1497 $memberDates = array(
1498 'join_date' => 'joinDate',
1499 'start_date' => 'startDate',
1500 'end_date' => 'endDate',
1501 );
2e8b13d1 1502 foreach ($memberDates as $dv) {
7d193e45
LS
1503 $$dv = NULL;
1504 foreach ($this->_memTypeSelected as $memType) {
1505 $membershipTypeValues[$memType][$dv] = NULL;
1506 }
1507 }
1508 }
09108d7d 1509 $now = date('YmdHis');
c26225d2 1510 $params['receive_date'] = date('YmdHis');
ccb02c2d 1511 $params['invoice_id'] = $formValues['invoiceID'];
6a488035
TO
1512 $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)',
1513 array(1 => $membershipType, 2 => $userName)
1514 );
1515 $params['source'] = $formValues['source'] ? $formValues['source'] : $params['contribution_source'];
1516 $params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
6a488035 1517 $params['is_test'] = ($this->_mode == 'live') ? 0 : 1;
ccb02c2d 1518 if (!empty($formValues['send_receipt'])) {
6a488035
TO
1519 $params['receipt_date'] = $now;
1520 }
1521 else {
1522 $params['receipt_date'] = NULL;
1523 }
1524
ccb02c2d 1525 $this->set('params', $formValues);
6a488035
TO
1526 $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
1527 $this->assign('receive_date',
1528 CRM_Utils_Date::mysqlToIso($params['receive_date'])
1529 );
1530
1531 // required for creating membership for related contacts
1532 $params['action'] = $this->_action;
1533
1534 //create membership record.
1535 $count = 0;
1536 foreach ($this->_memTypeSelected as $memType) {
1537 if ($count &&
1538 ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))
1539 ) {
1540 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1541 }
1542
1543 $membershipParams = array_merge($membershipTypeValues[$memType], $params);
87d0f881 1544 //CRM-15366
396e62d8 1545 if (!empty($softParams) && empty($paymentParams['is_recur'])) {
1546 $membershipParams['soft_credit'] = $softParams;
1547 }
77623a96 1548 if (isset($result['fee_amount'])) {
1549 $membershipParams['fee_amount'] = $result['fee_amount'];
1550 }
8a7b41d1
EM
1551 // This is required to trigger the recording of the membership contribution in the
1552 // CRM_Member_BAO_Membership::Create function.
1553 // @todo stop setting this & 'teach' the create function to respond to something
1554 // appropriate as part of our 2-step always create the pending contribution & then finally add the payment
1555 // process -
1556 // @see http://wiki.civicrm.org/confluence/pages/viewpage.action?pageId=261062657#Payments&AccountsRoadmap-Movetowardsalwaysusinga2-steppaymentprocess
1557 $membershipParams['contribution_status_id'] = CRM_Utils_Array::value('payment_status_id', $result);
ccb02c2d 1558 if (!empty($paymentParams['is_recur'])) {
1559 // The earlier process created the line items (although we want to get rid of the earlier one in favour
1560 // of a single path!
1561 unset($membershipParams['lineItems']);
1562 }
18135422 1563 $membershipParams['payment_instrument_id'] = $paymentInstrumentID;
6a488035 1564 $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
3e228d81
PN
1565 $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams);
1566 unset($params['lineItems']);
6a488035
TO
1567 $this->_membershipIDs[] = $membership->id;
1568 $createdMemberships[$memType] = $membership;
1569 $count++;
1570 }
1571
6a488035
TO
1572 }
1573 else {
1574 $params['action'] = $this->_action;
8cc574cf 1575 if ($this->_onlinePendingContributionId && !empty($formValues['record_contribution'])) {
6a488035
TO
1576
1577 // update membership as well as contribution object, CRM-4395
1578 $params['contribution_id'] = $this->_onlinePendingContributionId;
1579 $params['componentId'] = $params['id'];
1580 $params['componentName'] = 'contribute';
1581 $result = CRM_Contribute_BAO_Contribution::transitionComponents($params, TRUE);
8cc574cf 1582 if (!empty($result) && !empty($params['contribution_id'])) {
6a488035 1583 $lineItem = array();
77dbdcbc 1584 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($params['contribution_id']);
b11c92be 1585 $itemId = key($lineItems);
1586 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
4aa7d844 1587
6a488035
TO
1588 $lineItems[$itemId]['unit_price'] = $params['total_amount'];
1589 $lineItems[$itemId]['line_total'] = $params['total_amount'];
1590 $lineItems[$itemId]['id'] = $itemId;
1591 $lineItem[$priceSetId] = $lineItems;
8aa7457a
EM
1592 $contributionBAO = new CRM_Contribute_BAO_Contribution();
1593 $contributionBAO->id = $params['contribution_id'];
7524682e 1594 $contributionBAO->contact_id = $params['contact_id'];
8aa7457a
EM
1595 $contributionBAO->find();
1596 CRM_Price_BAO_LineItem::processPriceSet($params['contribution_id'], $lineItem, $contributionBAO, 'civicrm_membership');
133e2c99 1597
1598 //create new soft-credit record, CRM-13981
00c1cd97
CW
1599 if ($softParams) {
1600 $softParams['contribution_id'] = $params['contribution_id'];
1601 while ($contributionBAO->fetch()) {
1602 $softParams['currency'] = $contributionBAO->currency;
1603 $softParams['amount'] = $contributionBAO->total_amount;
1604 }
1605 CRM_Contribute_BAO_ContributionSoft::add($softParams);
133e2c99 1606 }
6a488035
TO
1607 }
1608
1609 //carry updated membership object.
1610 $membership = new CRM_Member_DAO_Membership();
1611 $membership->id = $this->_id;
1612 $membership->find(TRUE);
1613
1614 $cancelled = TRUE;
1615 if ($membership->end_date) {
1616 //display end date w/ status message.
1617 $endDate = $membership->end_date;
1618
b11c92be 1619 if (!in_array($membership->status_id, array(
7ff60806
PN
1620 // CRM-15475
1621 array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1622 array_search('Expired', CRM_Member_PseudoConstant::membershipStatus()),
b11c92be 1623 ))
1624 ) {
6a488035
TO
1625 $cancelled = FALSE;
1626 }
1627 }
1628 // suppress form values in template.
1629 $this->assign('cancelled', $cancelled);
1630
6a488035
TO
1631 $createdMemberships[] = $membership;
1632 }
1633 else {
1634 $count = 0;
1635 foreach ($this->_memTypeSelected as $memType) {
8cc574cf 1636 if ($count && !empty($formValues['record_contribution']) &&
6a488035
TO
1637 ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))
1638 ) {
1639 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1640 }
1641
1642 $membershipParams = array_merge($params, $membershipTypeValues[$memType]);
a7488080 1643 if (!empty($formValues['int_amount'])) {
6a488035 1644 $init_amount = array();
b11c92be 1645 foreach ($formValues as $key => $value) {
1646 if (strstr($key, 'txt-price')) {
6a488035
TO
1647 $init_amount[$key] = $value;
1648 }
1649 }
1650 $membershipParams['init_amount'] = $init_amount;
1651 }
d80dbc14 1652
1653 if (!empty($softParams)) {
1654 $membershipParams['soft_credit'] = $softParams;
1655 }
1656
6a488035 1657 $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
3e228d81 1658 $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams);
d5b95619 1659 unset($params['lineItems']);
fd706baa
PN
1660 // skip line item creation for next interation since line item(s) are already created.
1661 $params['skipLineItem'] = TRUE;
6a488035
TO
1662
1663 $this->_membershipIDs[] = $membership->id;
1664 $createdMemberships[$memType] = $membership;
1665 $count++;
1666 }
1667 }
1668 }
1669
ccb02c2d 1670 if (!empty($lineItem[$this->_priceSetId])) {
aaffa79f 1671 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
03b412ae 1672 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
01604562 1673 $taxAmount = FALSE;
79d001a2 1674 $totalTaxAmount = 0;
ccb02c2d 1675 foreach ($lineItem[$this->_priceSetId] as & $priceFieldOp) {
a7488080 1676 if (!empty($priceFieldOp['membership_type_id'])) {
3b85fc04
PN
1677 $priceFieldOp['start_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'], '%B %E%f, %Y') : '-';
1678 $priceFieldOp['end_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'], '%B %E%f, %Y') : '-';
6a488035
TO
1679 }
1680 else {
1681 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1682 }
03b412ae 1683 if ($invoicing && isset($priceFieldOp['tax_amount'])) {
01604562 1684 $taxAmount = TRUE;
79d001a2
PB
1685 $totalTaxAmount += $priceFieldOp['tax_amount'];
1686 }
1687 }
03b412ae
PB
1688 if ($invoicing) {
1689 $dataArray = array();
ccb02c2d 1690 foreach ($lineItem[$this->_priceSetId] as $key => $value) {
03b412ae
PB
1691 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
1692 if (isset($dataArray[$value['tax_rate']])) {
1693 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
0db6c3e1
TO
1694 }
1695 else {
03b412ae
PB
1696 $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
1697 }
0e81467c 1698 }
03b412ae 1699 }
01604562
PB
1700 if ($taxAmount) {
1701 $this->assign('totalTaxAmount', $totalTaxAmount);
a6e29c95 1702 // Not sure why would need this on Submit.... unless it's being used when sending mails in which case this is the wrong place
1703 $this->assign('taxTerm', $this->getSalesTaxTerm());
01604562 1704 }
03b412ae 1705 $this->assign('dataArray', $dataArray);
6a488035
TO
1706 }
1707 }
1708 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
1709
1710 $receiptSend = FALSE;
7d193e45
LS
1711 $contributionId = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id);
1712 $membershipIds = $this->_membershipIDs;
1713 if ($contributionId && !empty($membershipIds)) {
1714 $contributionDetails = CRM_Contribute_BAO_Contribution::getContributionDetails(
1715 CRM_Export_Form_Select::MEMBER_EXPORT, $this->_membershipIDs);
1716 if ($contributionDetails[$membership->id]['contribution_status'] == 'Completed') {
aadd21c2 1717 $receiptSend = TRUE;
7d193e45
LS
1718 }
1719 }
6a488035 1720
7e0c2ccd 1721 $receiptSent = FALSE;
7d193e45 1722 if (!empty($formValues['send_receipt']) && $receiptSend) {
b11c92be 1723 $formValues['contact_id'] = $this->_contactID;
7d193e45 1724 $formValues['contribution_id'] = $contributionId;
186a737c
EM
1725 // We really don't need a distinct receipt_text_signup vs receipt_text_renewal as they are
1726 // handled in the receipt. But by setting one we avoid breaking templates for now
1727 // although at some point we should switch in the templates.
1728 $formValues['receipt_text_signup'] = $formValues['receipt_text'];
6a488035 1729 // send email receipt
09108d7d 1730 $this->assignBillingName();
b11c92be 1731 $mailSend = self::emailReceipt($this, $formValues, $membership);
7e0c2ccd 1732 $receiptSent = TRUE;
6a488035 1733 }
6a488035 1734
7865d848
EM
1735 // finally set membership id if already not set
1736 if (!$this->_id) {
1737 $this->_id = $membership->id;
6a488035 1738 }
6a488035 1739
5b217d3f 1740 $isRecur = CRM_Utils_Array::value('is_recur', $params);
268a84f2 1741 $this->updateContributionOnMembershipTypeChange($params, $membership);
9dea4584 1742 $this->setStatusMessage($membership, $endDate, $receiptSent, $membershipTypes, $createdMemberships, $isRecur, $calcDates, $mailSend);
7865d848
EM
1743 return $createdMemberships;
1744 }
1745
268a84f2 1746 /**
1747 * Update related contribution of a membership if update_contribution_on_membership_type_change
1748 * contribution setting is enabled and type is changed on edit
1749 *
1750 * @param array $inputParams
1751 * submitted form values
1752 * @param CRM_Member_DAO_Membership $membership
1753 * Updated membership object
1754 *
1755 */
1756 protected function updateContributionOnMembershipTypeChange($inputParams, $membership) {
1757 if (Civi::settings()->get('update_contribution_on_membership_type_change') &&
1758 ($this->_action & CRM_Core_Action::UPDATE) && // on update
1759 $this->_id && // if ID is present
1760 !in_array($this->_memType, $this->_memTypeSelected) // if selected membership doesn't match with earlier membership
1761 ) {
1762 if (CRM_Utils_Array::value('is_recur', $inputParams)) {
1763 CRM_Core_Session::setStatus(ts('Associated recurring contribution cannot be updated on membership type change.', ts('Error'), 'error'));
1764 return;
1765 }
1766
1767 // fetch lineitems by updated membership ID
1768 $lineItems = CRM_Price_BAO_LineItem::getLineItems($membership->id, 'membership');
1769 // retrieve the related contribution ID
1770 $contributionID = CRM_Core_DAO::getFieldValue(
1771 'CRM_Member_DAO_MembershipPayment',
1772 $membership->id,
1773 'contribution_id',
1774 'membership_id'
1775 );
1776 // get price fields of chosen price-set
1777 $priceSetDetails = CRM_Utils_Array::value(
1778 $this->_priceSetId,
1779 CRM_Price_BAO_PriceSet::getSetDetail(
1780 $this->_priceSetId,
1781 TRUE,
1782 TRUE
1783 )
1784 );
1785
1786 // add price field information in $inputParams
1787 self::addPriceFieldByMembershipType($inputParams, $priceSetDetails['fields'], $membership->membership_type_id);
6dde7f04 1788
268a84f2 1789 // update related contribution and financial records
1790 CRM_Price_BAO_LineItem::changeFeeSelections(
1791 $inputParams,
1792 $membership->id,
1793 'membership',
1794 $contributionID,
1795 $priceSetDetails['fields'],
6dde7f04 1796 $lineItems
268a84f2 1797 );
1798 CRM_Core_Session::setStatus(ts('Associated contribution is updated on membership type change.'), ts('Success'), 'success');
1799 }
1800 }
1801
1802 /**
1803 * Add selected price field information in $formValues
1804 *
1805 * @param array $formValues
1806 * submitted form values
1807 * @param array $priceFields
1808 * Price fields of selected Priceset ID
1809 * @param int $membershipTypeID
1810 * Selected membership type ID
1811 *
1812 */
1813 public static function addPriceFieldByMembershipType(&$formValues, $priceFields, $membershipTypeID) {
1814 foreach ($priceFields as $priceFieldID => $priceField) {
1815 if (isset($priceField['options']) && count($priceField['options'])) {
1816 foreach ($priceField['options'] as $option) {
1817 if ($option['membership_type_id'] == $membershipTypeID) {
1818 $formValues["price_{$priceFieldID}"] = $option['id'];
1819 break;
1820 }
1821 }
1822 }
1823 }
1824 }
5e56c7a5 1825 /**
1826 * Set context in session.
1827 */
7865d848 1828 protected function setUserContext() {
6a488035 1829 $buttonName = $this->controller->getButtonName();
7865d848
EM
1830 $session = CRM_Core_Session::singleton();
1831
6a488035
TO
1832 if ($this->_context == 'standalone') {
1833 if ($buttonName == $this->getButtonName('upload', 'new')) {
1834 $session->replaceUserContext(CRM_Utils_System::url('civicrm/member/add',
b11c92be 1835 'reset=1&action=add&context=standalone'
1836 ));
6a488035
TO
1837 }
1838 else {
1839 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
b11c92be 1840 "reset=1&cid={$this->_contactID}&selectedChild=member"
1841 ));
6a488035
TO
1842 }
1843 }
1844 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1845 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/membership',
b11c92be 1846 "reset=1&action=add&context=membership&cid={$this->_contactID}"
1847 ));
6a488035
TO
1848 }
1849 }
1850
1851 /**
5e56c7a5 1852 * Get status message for updating membership.
1853 *
1854 * @param CRM_Member_BAO_Membership $membership
1855 * @param string $endDate
5e56c7a5 1856 *
7865d848 1857 * @return string
6a488035 1858 */
6d5b9c63 1859 protected function getStatusMessageForUpdate($membership, $endDate) {
5e56c7a5 1860 // End date can be modified by hooks, so if end date is set then use it.
7865d848 1861 $endDate = ($membership->end_date) ? $membership->end_date : $endDate;
6a488035 1862
7865d848
EM
1863 $statusMsg = ts('Membership for %1 has been updated.', array(1 => $this->_memberDisplayName));
1864 if ($endDate && $endDate !== 'null') {
1865 $endDate = CRM_Utils_Date::customFormat($endDate);
1866 $statusMsg .= ' ' . ts('The membership End Date is %1.', array(1 => $endDate));
6a488035 1867 }
7865d848
EM
1868 return $statusMsg;
1869 }
6a488035 1870
7865d848 1871 /**
5e56c7a5 1872 * Get status message for create action.
1873 *
1874 * @param string $endDate
5e56c7a5 1875 * @param array $membershipTypes
1876 * @param array $createdMemberships
5b217d3f 1877 * @param bool $isRecur
5e56c7a5 1878 * @param array $calcDates
5e56c7a5 1879 *
7865d848
EM
1880 * @return array|string
1881 */
6d5b9c63 1882 protected function getStatusMessageForCreate($endDate, $membershipTypes, $createdMemberships,
1883 $isRecur, $calcDates) {
7865d848
EM
1884 // FIX ME: fix status messages
1885
1886 $statusMsg = array();
1887 foreach ($membershipTypes as $memType => $membershipType) {
1888 $statusMsg[$memType] = ts('%1 membership for %2 has been added.', array(
1889 1 => $membershipType,
1890 2 => $this->_memberDisplayName,
1891 ));
6a488035 1892
7865d848
EM
1893 $membership = $createdMemberships[$memType];
1894 $memEndDate = ($membership->end_date) ? $membership->end_date : $endDate;
6a488035 1895
7865d848 1896 //get the end date from calculated dates.
5b217d3f 1897 if (!$memEndDate && !$isRecur) {
7865d848 1898 $memEndDate = CRM_Utils_Array::value('end_date', $calcDates[$memType]);
35fa23f8 1899 }
6a488035 1900
7865d848
EM
1901 if ($memEndDate && $memEndDate !== 'null') {
1902 $memEndDate = CRM_Utils_Date::customFormat($memEndDate);
1903 $statusMsg[$memType] .= ' ' . ts('The new membership End Date is %1.', array(1 => $memEndDate));
b11c92be 1904 }
6a488035 1905 }
7865d848 1906 $statusMsg = implode('<br/>', $statusMsg);
7865d848 1907 return $statusMsg;
6a488035 1908 }
96025800 1909
5b217d3f 1910 /**
1911 * @param $membership
1912 * @param $endDate
1913 * @param $receiptSend
1914 * @param $membershipTypes
1915 * @param $createdMemberships
1916 * @param $isRecur
1917 * @param $calcDates
6d5b9c63 1918 * @param $mailSent
5b217d3f 1919 */
6d5b9c63 1920 protected function setStatusMessage($membership, $endDate, $receiptSend, $membershipTypes, $createdMemberships, $isRecur, $calcDates, $mailSent) {
5b217d3f 1921 if (($this->_action & CRM_Core_Action::UPDATE)) {
6d5b9c63 1922 $this->addStatusMessage($this->getStatusMessageForUpdate($membership, $endDate));
5b217d3f 1923 }
1924 elseif (($this->_action & CRM_Core_Action::ADD)) {
6d5b9c63 1925 $this->addStatusMessage($this->getStatusMessageForCreate($endDate, $membershipTypes, $createdMemberships,
1926 $isRecur, $calcDates));
1927 }
1928 if ($receiptSend && $mailSent) {
1929 $this->addStatusMessage(ts('A membership confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail)));
5b217d3f 1930 }
1931
6d5b9c63 1932 CRM_Core_Session::setStatus($this->getStatusMessage(), ts('Complete'), 'success');
5b217d3f 1933 //CRM-15187
1934 // display message when membership type is changed
1935 if (($this->_action & CRM_Core_Action::UPDATE) && $this->_id && !in_array($this->_memType, $this->_memTypeSelected)) {
0fedbc88
PN
1936 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'membership');
1937 $maxID = max(array_keys($lineItem));
1938 $lineItem = $lineItem[$maxID];
1939 $membershipTypeDetails = $this->allMembershipTypeDetails[$membership->membership_type_id];
1940 if ($membershipTypeDetails['financial_type_id'] != $lineItem['financial_type_id']) {
1941 CRM_Core_Session::setStatus(
1942 ts('The financial types associated with the old and new membership types are different. You may want to edit the contribution associated with this membership to adjust its financial type.'),
1943 ts('Warning')
1944 );
1945 }
1946 if ($membershipTypeDetails['minimum_fee'] != $lineItem['line_total']) {
1947 CRM_Core_Session::setStatus(
1948 ts('The cost of the old and new membership types are different. You may want to edit the contribution associated with this membership to adjust its amount.'),
1949 ts('Warning')
1950 );
1951 }
5b217d3f 1952 }
1953 }
1954
50b85bf9 1955 /**
1956 * @return bool
1957 */
1958 protected function isUpdateToExistingRecurringMembership() {
1959 $isRecur = FALSE;
1960 if ($this->_action & CRM_Core_Action::UPDATE
59c798c9 1961 && CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->getEntityId(),
50b85bf9 1962 'contribution_recur_id')
59c798c9 1963 && !CRM_Member_BAO_Membership::isSubscriptionCancelled($this->getEntityId())) {
50b85bf9 1964
1965 $isRecur = TRUE;
1966 }
1967 return $isRecur;
1968 }
1969
6a488035 1970}