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