Enable QueueRunner for membership import
[civicrm-core.git] / CRM / Member / Form.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/**
19 * Base class for offline membership / membership type / membership renewal and membership status forms
20 *
21 */
cc984198 22class CRM_Member_Form extends CRM_Contribute_Form_AbstractEditPayment {
6a488035 23
59c798c9 24 use CRM_Core_Form_EntityFormTrait;
6a488035 25
a6513ad5
EM
26 /**
27 * Membership Type ID
971e129b 28 * @var int
a6513ad5
EM
29 */
30 protected $_memType;
31
32 /**
33 * Array of from email ids
34 * @var array
35 */
be2fb01f 36 protected $_fromEmails = [];
a6513ad5 37
ab30e033
EM
38 /**
39 * Details of all enabled membership types.
40 *
41 * @var array
42 */
be2fb01f 43 protected $allMembershipTypeDetails = [];
ab30e033
EM
44
45 /**
46 * Array of membership type IDs and whether they permit autorenewal.
47 *
48 * @var array
49 */
be2fb01f 50 protected $membershipTypeRenewalStatus = [];
ab30e033 51
e4a6290d 52 /**
53 * Price set ID configured for the form.
54 *
55 * @var int
56 */
57 public $_priceSetId;
58
59 /**
60 * Price set details as an array.
61 *
62 * @var array
63 */
64 public $_priceSet;
65
a817ccdd 66 /**
67 * The order being processed.
68 *
69 * @var \CRM_Financial_BAO_Order
70 */
71 protected $order;
72
20df462f 73 /**
74 * This string is the used for passing to the buildAmount hook.
75 *
76 * @var string
77 */
78 protected $formContext = 'membership';
79
80 /**
81 * @return string
82 */
83 public function getFormContext(): string {
84 return $this->formContext;
85 }
86
6452294d
MW
87 /**
88 * Explicitly declare the entity api name.
89 */
90 public function getDefaultEntity() {
91 return 'Membership';
92 }
93
6d5b9c63 94 /**
95 * @var array
96 */
97 protected $statusMessage = [];
98
99 /**
100 * Add to the status message.
101 *
fa3fdebc 102 * @param string $message
6d5b9c63 103 */
104 protected function addStatusMessage($message) {
105 $this->statusMessage[] = $message;
106 }
107
108 /**
109 * Get the status message.
110 *
111 * @return string
112 */
113 protected function getStatusMessage() {
114 return implode(' ', $this->statusMessage);
115 }
116
09108d7d 117 /**
118 * Values submitted to the form, processed along the way.
119 *
120 * @var array
121 */
be2fb01f 122 protected $_params = [];
09108d7d 123
59c798c9 124 /**
125 * Fields for the entity to be assigned to the template.
126 *
127 * Fields may have keys
128 * - name (required to show in tpl from the array)
129 * - description (optional, will appear below the field)
130 * - not-auto-addable - this class will not attempt to add the field using addField.
131 * (this will be automatically set if the field does not have html in it's metadata
132 * or is not a core field on the form's entity).
133 * - help (option) add help to the field - e.g ['id' => 'id-source', 'file' => 'CRM/Contact/Form/Contact']]
134 * - template - use a field specific template to render this field
135 * - required
136 * - is_freeze (field should be frozen).
137 *
138 * @var array
139 */
140 protected $entityFields = [];
141
00be9182 142 public function preProcess() {
42e8b05c
EM
143 // Check for edit permission.
144 if (!CRM_Core_Permission::checkActionPermission('CiviMember', $this->_action)) {
beb414cc 145 CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
42e8b05c 146 }
6a38708b 147 if (!CRM_Member_BAO_Membership::statusAvailabilty()) {
148 // all possible statuses are disabled - redirect back to contact form
149 CRM_Core_Error::statusBounce(ts('There are no configured membership statuses. You cannot add this membership until your membership statuses are correctly configured'));
150 }
151
42e8b05c 152 parent::preProcess();
be2fb01f 153 $params = [];
edc80cda 154 $params['context'] = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this, FALSE, 'membership');
7865d848 155 $params['id'] = CRM_Utils_Request::retrieve('id', 'Positive', $this);
19046166 156 $params['mode'] = CRM_Utils_Request::retrieve('mode', 'Alphanumeric', $this);
7865d848
EM
157
158 $this->setContextVariables($params);
a6513ad5
EM
159
160 $this->assign('context', $this->_context);
161 $this->assign('membershipMode', $this->_mode);
871a8674 162 $this->assign('newCredit', CRM_Core_Config::isEnabledBackOfficeCreditCardPayments());
be2fb01f 163 $this->allMembershipTypeDetails = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, [], TRUE);
ab30e033
EM
164 foreach ($this->allMembershipTypeDetails as $index => $membershipType) {
165 if ($membershipType['auto_renew']) {
166 $this->_recurMembershipTypes[$index] = $membershipType;
167 $this->membershipTypeRenewalStatus[$index] = $membershipType['auto_renew'];
168 }
169 }
6a488035
TO
170 }
171
172 /**
c490a46a 173 * Set default values for the form. MobileProvider that in edit/view mode
6a488035
TO
174 * the default values are retrieved from the database
175 *
6a488035 176 *
a6c01b45
CW
177 * @return array
178 * defaults
6a488035 179 */
00be9182 180 public function setDefaultValues() {
be2fb01f 181 $defaults = [];
a6513ad5 182 if (isset($this->_id)) {
be2fb01f 183 $params = ['id' => $this->_id];
a6513ad5 184 CRM_Member_BAO_Membership::retrieve($params, $defaults);
42e8b05c 185 if (isset($defaults['minimum_fee'])) {
48845185 186 $defaults['minimum_fee'] = CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency($defaults['minimum_fee']);
42e8b05c 187 }
6a488035 188
42e8b05c
EM
189 if (isset($defaults['status'])) {
190 $this->assign('membershipStatus', $defaults['status']);
191 }
e136f704
O
192
193 if (!empty($defaults['is_override'])) {
194 $defaults['is_override'] = CRM_Member_StatusOverrideTypes::PERMANENT;
195 }
196 if (!empty($defaults['status_override_end_date'])) {
197 $defaults['is_override'] = CRM_Member_StatusOverrideTypes::UNTIL_DATE;
198 }
6a488035
TO
199 }
200
201 if ($this->_action & CRM_Core_Action::ADD) {
202 $defaults['is_active'] = 1;
203 }
204
205 if (isset($defaults['member_of_contact_id']) &&
206 $defaults['member_of_contact_id']
207 ) {
208 $defaults['member_org'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
209 $defaults['member_of_contact_id'], 'display_name'
210 );
211 }
f525ec1f 212 if (!empty($defaults['membership_type_id'])) {
213 $this->_memType = $defaults['membership_type_id'];
214 }
215 if (is_numeric($this->_memType)) {
be2fb01f 216 $defaults['membership_type_id'] = [];
f525ec1f 217 $defaults['membership_type_id'][0] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
218 $this->_memType,
219 'member_of_contact_id',
220 'id'
221 );
222 $defaults['membership_type_id'][1] = $this->_memType;
223 }
224 else {
225 $defaults['membership_type_id'] = $this->_memType;
226 }
6a488035
TO
227 return $defaults;
228 }
229
230 /**
fe482240 231 * Build the form object.
6a488035
TO
232 */
233 public function buildQuickForm() {
a6e29c95 234 $this->assignSalesTaxMetadataToTemplate();
4aa7d844 235
b15c60e1 236 $this->addPaymentProcessorSelect(TRUE, FALSE, TRUE);
0dc4ef42 237 CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE, TRUE, $this->getDefaultPaymentInstrumentId());
38f6574d 238 $this->assign('recurProcessor', json_encode($this->_recurPaymentProcessors));
4aa7d844
EM
239 // Build the form for auto renew. This is displayed when in credit card mode or update mode.
240 // The reason for showing it in update mode is not that clear.
871a8674 241 $this->assign('allowAutoRenew', $this->_mode && !empty($this->_recurPaymentProcessors));
4aa7d844 242 if ($this->_mode || ($this->_action & CRM_Core_Action::UPDATE)) {
4aa7d844 243
ab30e033 244 $autoRenewElement = $this->addElement('checkbox', 'auto_renew', ts('Membership renewed automatically'),
be2fb01f 245 NULL, ['onclick' => "showHideByValue('auto_renew','','send-receipt','table-row','radio',true); showHideNotice( );"]
ab30e033
EM
246 );
247 if ($this->_action & CRM_Core_Action::UPDATE) {
248 $autoRenewElement->freeze();
249 }
4aa7d844 250
4aa7d844
EM
251 $this->addElement('checkbox',
252 'auto_renew',
8c80f3f9 253 ts('Membership renewed automatically')
4aa7d844
EM
254 );
255
4aa7d844 256 }
ab30e033 257 $this->assign('autoRenewOptions', json_encode($this->membershipTypeRenewalStatus));
4aa7d844 258
6a488035 259 if ($this->_action & CRM_Core_Action::RENEW) {
be2fb01f
CW
260 $this->addButtons([
261 [
c5c263ca
AH
262 'type' => 'upload',
263 'name' => ts('Renew'),
264 'isDefault' => TRUE,
be2fb01f
CW
265 ],
266 [
c5c263ca
AH
267 'type' => 'cancel',
268 'name' => ts('Cancel'),
be2fb01f
CW
269 ],
270 ]);
6a488035
TO
271 }
272 elseif ($this->_action & CRM_Core_Action::DELETE) {
be2fb01f
CW
273 $this->addButtons([
274 [
c5c263ca
AH
275 'type' => 'next',
276 'name' => ts('Delete'),
277 'isDefault' => TRUE,
be2fb01f
CW
278 ],
279 [
c5c263ca
AH
280 'type' => 'cancel',
281 'name' => ts('Cancel'),
be2fb01f
CW
282 ],
283 ]);
6a488035
TO
284 }
285 else {
be2fb01f
CW
286 $this->addButtons([
287 [
c5c263ca
AH
288 'type' => 'upload',
289 'name' => ts('Save'),
290 'isDefault' => TRUE,
be2fb01f
CW
291 ],
292 [
c5c263ca
AH
293 'type' => 'upload',
294 'name' => ts('Save and New'),
295 'subName' => 'new',
be2fb01f
CW
296 ],
297 [
c5c263ca
AH
298 'type' => 'cancel',
299 'name' => ts('Cancel'),
be2fb01f
CW
300 ],
301 ]);
6a488035
TO
302 }
303 }
304
fb3082b2 305 /**
100fef9d 306 * Extract values from the contact create boxes on the form and assign appropriately to
6a488035
TO
307 *
308 * - $this->_contributorEmail,
309 * - $this->_memberEmail &
fb3082b2 310 * - $this->_contributionName
6a488035
TO
311 * - $this->_memberName
312 * - $this->_contactID (effectively memberContactId but changing might have spin-off effects)
313 * - $this->_contributorContactId - id of the contributor
314 * - $this->_receiptContactId
315 *
316 * If the member & contributor are the same then the values will be the same. But if different people paid
317 * then they weill differ
318 *
5a4f6742
CW
319 * @param array $formValues
320 * values from form. The important values we are looking for are.
4c7aa1f7
CW
321 * - contact_id
322 * - soft_credit_contact_id
6a488035 323 */
9b873358 324 public function storeContactFields($formValues) {
6a488035 325 // in a 'standalone form' (contact id not in the url) the contact will be in the form values
4c7aa1f7
CW
326 if (!empty($formValues['contact_id'])) {
327 $this->_contactID = $formValues['contact_id'];
6a488035
TO
328 }
329
a817ccdd 330 [$this->_memberDisplayName, $this->_memberEmail] = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
23f0a3fd 331 $this->_contributorContactID = $this->getContributionContactID();
6a488035
TO
332 //CRM-10375 Where the payer differs to the member the payer should get the email.
333 // here we store details in order to do that
4c7aa1f7 334 if (!empty($formValues['soft_credit_contact_id'])) {
23f0a3fd 335 $this->_receiptContactId = $formValues['soft_credit_contact_id'];
a817ccdd 336 [$this->_contributorDisplayName, $this->_contributorEmail] = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contributorContactID);
6a488035
TO
337 }
338 else {
23f0a3fd 339 $this->_receiptContactId = $this->_contactID;
6a488035
TO
340 $this->_contributorDisplayName = $this->_memberDisplayName;
341 $this->_contributorEmail = $this->_memberEmail;
342 }
343 }
96025800 344
23f0a3fd 345 /**
346 * Get the contact id for the contribution.
347 *
348 * @return int
349 */
350 protected function getContributionContactID(): int {
351 return (int) ($this->getSubmittedValue('soft_credit_contact_id') ?: $this->getSubmittedValue('contact_id'));
352 }
353
45a6ec43 354 /**
355 * Get the contact id for the contribution.
356 *
357 * @return int
358 */
359 protected function getMembershipContactID(): int {
360 // It's not clear that $this->_contactID *could* be set outside
361 // tests when contact_id is not submitted - so this fallback
362 // is precautionary in order to be similar to past behaviour.
363 return (int) ($this->getSubmittedValue('contact_id') ?: $this->_contactID);
364 }
365
0271af37 366 /**
367 * Set variables in a way that can be accessed from different places.
368 *
369 * This is part of refactoring for unit testability on the submit function.
370 *
371 * @param array $params
372 */
7865d848 373 protected function setContextVariables($params) {
be2fb01f 374 $variables = [
7865d848
EM
375 'action' => '_action',
376 'context' => '_context',
377 'id' => '_id',
378 'cid' => '_contactID',
379 'mode' => '_mode',
be2fb01f 380 ];
7865d848
EM
381 foreach ($variables as $paramKey => $classVar) {
382 if (isset($params[$paramKey]) && !isset($this->$classVar)) {
383 $this->$classVar = $params[$paramKey];
384 }
385 }
386
7865d848
EM
387 if ($this->_id) {
388 $this->_memType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_id, 'membership_type_id');
389 $this->_membershipIDs[] = $this->_id;
390 }
391 $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
392 }
393
a70418a7
EM
394 /**
395 * Create a recurring contribution record.
396 *
c9696db9 397 * @param array $contributionRecurParams
a70418a7 398 *
97dda7c0 399 * @param int $membershipTypeID
a70418a7
EM
400 *
401 * @return array
402 * @throws \CiviCRM_API3_Exception
403 */
97dda7c0 404 protected function processRecurringContribution($contributionRecurParams, $membershipTypeID) {
a70418a7 405
be2fb01f 406 $mapping = [
a70418a7
EM
407 'frequency_interval' => 'duration_interval',
408 'frequency_unit' => 'duration_unit',
be2fb01f
CW
409 ];
410 $membershipType = civicrm_api3('MembershipType', 'getsingle', [
97dda7c0 411 'id' => $membershipTypeID,
a70418a7 412 'return' => $mapping,
be2fb01f 413 ]);
a70418a7 414
be2fb01f 415 $returnParams = ['is_recur' => TRUE];
a70418a7
EM
416 foreach ($mapping as $recurringFieldName => $membershipTypeFieldName) {
417 $contributionRecurParams[$recurringFieldName] = $membershipType[$membershipTypeFieldName];
14065266 418 $returnParams[$recurringFieldName] = $membershipType[$membershipTypeFieldName];
a70418a7
EM
419 }
420
421 $contributionRecur = civicrm_api3('ContributionRecur', 'create', $contributionRecurParams);
14065266 422 $returnParams['contributionRecurID'] = $contributionRecur['id'];
a70418a7
EM
423 return $returnParams;
424 }
425
ccb02c2d 426 /**
427 * Ensure price parameters are set.
428 *
429 * If they are not set it means a quick config option has been chosen so we
430 * fill them in here to make the two flows the same. They look like 'price_2' => 2 etc.
431 *
432 * @param array $formValues
433 */
434 protected function ensurePriceParamsAreSet(&$formValues) {
435 foreach ($formValues as $key => $value) {
ea09031a 436 if ((substr($key, 0, 6) == 'price_') && is_numeric(substr($key, 6))) {
ccb02c2d 437 return;
438 }
439 }
440 $priceFields = CRM_Member_BAO_Membership::setQuickConfigMembershipParameters(
441 $formValues['membership_type_id'][0],
442 $formValues['membership_type_id'][1],
430f2faf 443 CRM_Utils_Array::value('total_amount', $formValues),
ccb02c2d 444 $this->_priceSetId
445 );
446 $formValues = array_merge($formValues, $priceFields['price_fields']);
447 }
448
449 /**
450 * Get the details for the selected price set.
451 *
452 * @param array $params
453 * Parameters submitted to the form.
454 *
455 * @return array
456 */
cd595bef 457 protected function getPriceSetDetails(array $params): ?array {
9c1bc317 458 $priceSetID = $params['price_set_id'] ?? NULL;
ccb02c2d 459 if ($priceSetID) {
460 return CRM_Price_BAO_PriceSet::getSetDetail($priceSetID);
461 }
462 else {
463 $priceSet = CRM_Price_BAO_PriceSet::getDefaultPriceSet('membership');
464 $priceSet = reset($priceSet);
465 return CRM_Price_BAO_PriceSet::getSetDetail($priceSet['setID']);
466 }
467 }
468
469 /**
470 * Get the selected price set id.
471 *
472 * @param array $params
473 * Parameters submitted to the form.
474 *
475 * @return int
476 */
cd595bef 477 protected function getPriceSetID(array $params): int {
9c1bc317 478 $priceSetID = $params['price_set_id'] ?? NULL;
ccb02c2d 479 if (!$priceSetID) {
cd595bef 480 $priceSetDetails = $this->getPriceSetDetails($params);
7aa78908 481 return (int) key($priceSetDetails);
ccb02c2d 482 }
7aa78908 483 return (int) $priceSetID;
ccb02c2d 484 }
485
486 /**
487 * Store parameters relating to price sets.
488 *
489 * @param array $formValues
490 *
491 * @return array
812b2c0c 492 * @throws \API_Exception
ccb02c2d 493 */
cd595bef 494 protected function setPriceSetParameters(array $formValues): array {
a817ccdd 495 // process price set and get total amount and line items.
cd595bef 496 $this->_priceSetId = $this->getPriceSetID($formValues);
a817ccdd 497 $this->ensurePriceParamsAreSet($formValues);
cd595bef 498 $priceSetDetails = $this->getPriceSetDetails($formValues);
ccb02c2d 499 $this->_priceSet = $priceSetDetails[$this->_priceSetId];
a817ccdd 500 $this->order = new CRM_Financial_BAO_Order();
20df462f 501 $this->order->setForm($this);
812b2c0c
EM
502 $this->order->setPriceSelectionFromUnfilteredInput($formValues);
503 if (isset($formValues['total_amount'])) {
fc690477 504 $this->order->setOverrideTotalAmount((float) $formValues['total_amount']);
a817ccdd 505 }
506 $this->order->setOverrideFinancialTypeID((int) $formValues['financial_type_id']);
ccb02c2d 507 return $formValues;
508 }
509
09108d7d 510 /**
511 * Wrapper function for unit tests.
512 *
513 * @param array $formValues
514 */
23f0a3fd 515 public function testSubmit(array $formValues = []): void {
516 if (empty($formValues)) {
517 // If getForm is used these will be set - this is now
518 // preferred.
519 $formValues = $this->controller->exportValues($this->_name);
520 }
6aef1389 521 $this->exportedValues = $formValues;
18135422 522 $this->setContextVariables($formValues);
26e40b3e 523 $this->_memType = !empty($formValues['membership_type_id']) ? $formValues['membership_type_id'][1] : NULL;
09108d7d 524 $this->_params = $formValues;
525 $this->submit();
526 }
527
df04742c 528 /**
529 * Get order related params.
530 *
531 * In practice these are contribution params but later they cann be used with the Order api.
532 *
533 * @return array
534 *
535 * @throws \CiviCRM_API3_Exception
536 */
537 protected function getOrderParams(): array {
df04742c 538 return [
a817ccdd 539 'lineItems' => [$this->_priceSetId => $this->order->getLineItems()],
df04742c 540 // This is one of those weird & wonderful legacy params we aim to get rid of.
541 'processPriceSet' => TRUE,
a817ccdd 542 'tax_amount' => $this->order->getTotalTaxAmount(),
df04742c 543 ];
544 }
545
cd98958c 546 /**
547 * Get the currency in use.
548 *
549 * This just defaults to getting the default currency
550 * as other currencies are not supported on the membership
551 * forms at the moment.
552 *
553 * @param array $submittedValues
554 *
555 * @return string
556 */
557 public function getCurrency($submittedValues = []): string {
558 return CRM_Core_Config::singleton()->defaultCurrency;
559 }
560
c2b07971 561 /**
562 * Get the relevant payment instrument id.
563 *
564 * @return int
565 */
566 protected function getPaymentInstrumentID(): int {
567 return (int) $this->getSubmittedValue('payment_instrument_id') ?: $this->_paymentProcessor['object']->getPaymentInstrumentID();
568 }
569
83708bb1
EM
570 /**
571 * Get the last 4 numbers of the card.
572 *
573 * @return int|null
574 */
575 protected function getPanTruncation(): ?int {
576 $card = $this->getSubmittedValue('credit_card_number');
577 return $card ? (int) substr($card, -4) : NULL;
578 }
579
580 /**
581 * Get the card_type_id.
582 *
583 * This value is the integer representing the option value for
584 * the credit card type (visa, mastercard). It is stored as part of the
585 * payment record in civicrm_financial_trxn.
586 *
587 * @return int|null
588 */
589 protected function getCardTypeID(): ?int {
590 return CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $this->getSubmittedValue('credit_card_type'));
591 }
592
6a488035 593}