Merge pull request #23080 from eileenmcnaughton/isset
[civicrm-core.git] / CRM / Contribute / Form / UpdateBilling.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/**
347e061b 19 * This class generates form components for processing a contribution.
6a488035 20 */
ca809bb6 21class CRM_Contribute_Form_UpdateBilling extends CRM_Contribute_Form_ContributionRecur {
6a488035
TO
22 protected $_mode = NULL;
23
24 protected $_subscriptionDetails = NULL;
25
6a488035 26 public $_bltID = NULL;
a6513ad5 27
6a488035 28 /**
fe482240 29 * Set variables up before form is built.
503699d5 30 *
31 * @throws \CRM_Core_Exception
6a488035
TO
32 */
33 public function preProcess() {
1f17c8ef 34 parent::preProcess();
6a488035 35 if ($this->_crid) {
6a488035 36 // Are we cancelling a recurring contribution that is linked to an auto-renew membership?
cc929f4e
MW
37 if ($this->getSubscriptionDetails()->membership_id) {
38 $this->_mid = $this->getSubscriptionDetails()->membership_id;
6a488035
TO
39 }
40 }
41
6a488035
TO
42 if ($this->_coid) {
43 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'info');
a6513ad5 44 $this->_paymentProcessor['object'] = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'obj');
6a488035
TO
45 }
46
47 if ($this->_mid) {
48 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_mid, 'membership', 'info');
a6513ad5 49 $this->_paymentProcessor['object'] = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_mid, 'membership', 'obj');
6a488035
TO
50 $membershipTypes = CRM_Member_PseudoConstant::membershipType();
51 $membershipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_mid, 'membership_type_id');
52 $this->assign('membershipType', CRM_Utils_Array::value($membershipTypeId, $membershipTypes));
53 $this->_mode = 'auto_renew';
54 }
55
cc929f4e 56 if ((!$this->_crid && !$this->_coid && !$this->_mid) || (!$this->getSubscriptionDetails())) {
32519aca 57 throw new CRM_Core_Exception('Required information missing.');
6a488035 58 }
6a488035 59
b690491e 60 if (!$this->_paymentProcessor['object']->supports('updateSubscriptionBillingInfo')) {
32519aca 61 throw new CRM_Core_Exception(ts("%1 processor doesn't support updating subscription billing details.",
62 [1 => $this->_paymentProcessor['title']]
353ffa53 63 ));
6a488035
TO
64 }
65 $this->assign('paymentProcessor', $this->_paymentProcessor);
66
8345c9d3 67 $this->assignBillingType();
6a488035 68
50750f66
SL
69 $this->assign('recur_frequency_unit', $this->getSubscriptionDetails()->frequency_unit);
70 $this->assign('recur_frequency_interval', $this->getSubscriptionDetails()->frequency_interval);
cc929f4e
MW
71 $this->assign('amount', $this->getSubscriptionDetails()->amount);
72 $this->assign('installments', $this->getSubscriptionDetails()->installments);
6a488035
TO
73 $this->assign('mode', $this->_mode);
74
75 // handle context redirection
76 CRM_Contribute_BAO_ContributionRecur::setSubscriptionContext();
77 }
78
186c9c17 79 /**
0c6c47a5 80 * Set the default values of various form elements.
186c9c17 81 *
186c9c17 82 * @return array
0c6c47a5 83 * Default values
186c9c17 84 */
00be9182 85 public function setDefaultValues() {
affcc9d2 86 $this->_defaults = [];
6a488035 87
cc929f4e 88 if ($this->getSubscriptionDetails()->contact_id) {
affcc9d2 89 $fields = [];
353ffa53
TO
90 $names = array(
91 'first_name',
92 'middle_name',
93 'last_name',
94 "street_address-{$this->_bltID}",
95 "city-{$this->_bltID}",
96 "postal_code-{$this->_bltID}",
97 "country_id-{$this->_bltID}",
98 "state_province_id-{$this->_bltID}",
6a488035
TO
99 );
100 foreach ($names as $name) {
101 $fields[$name] = 1;
102 }
103 $fields["state_province-{$this->_bltID}"] = 1;
104 $fields["country-{$this->_bltID}"] = 1;
105 $fields["email-{$this->_bltID}"] = 1;
106 $fields['email-Primary'] = 1;
107
cc929f4e 108 CRM_Core_BAO_UFGroup::setProfileDefaults($this->getSubscriptionDetails()->contact_id, $fields, $this->_defaults);
6a488035
TO
109
110 // use primary email address if billing email address is empty
111 if (empty($this->_defaults["email-{$this->_bltID}"]) &&
112 !empty($this->_defaults['email-Primary'])
113 ) {
114 $this->_defaults["email-{$this->_bltID}"] = $this->_defaults['email-Primary'];
115 }
116
117 foreach ($names as $name) {
118 if (!empty($this->_defaults[$name])) {
119 $this->_defaults['billing_' . $name] = $this->_defaults[$name];
120 }
121 }
122 }
123
6a488035
TO
124 $config = CRM_Core_Config::singleton();
125 // set default country from config if no country set
a7488080 126 if (empty($this->_defaults["billing_country_id-{$this->_bltID}"])) {
6a488035
TO
127 $this->_defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
128 }
129
6a488035
TO
130 return $this->_defaults;
131 }
132
133 /**
fe482240 134 * Build the form object.
6a488035
TO
135 */
136 public function buildQuickForm() {
137 $type = 'next';
d5c59a00 138 if ($this->isSelfService()) {
6a488035
TO
139 $type = 'submit';
140 }
141
142 $this->addButtons(array(
1330f57a
SL
143 array(
144 'type' => $type,
145 'name' => ts('Save'),
146 'isDefault' => TRUE,
147 ),
148 array(
149 'type' => 'cancel',
150 'name' => ts('Cancel'),
151 ),
152 ));
6a488035 153
3c3aac0b 154 CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, TRUE, TRUE);
6a488035
TO
155 $this->addFormRule(array('CRM_Contribute_Form_UpdateBilling', 'formRule'), $this);
156 }
157
158 /**
fe482240 159 * Global form rule.
6a488035 160 *
014c4014
TO
161 * @param array $fields
162 * The input form values.
163 * @param array $files
164 * The uploaded files if any.
0c6c47a5 165 * @param CRM_Core_Form $self
da6b46f4 166 *
6a488035 167 *
72b3a70c
CW
168 * @return bool|array
169 * true if no errors, else array of errors
6a488035 170 */
00be9182 171 public static function formRule($fields, $files, $self) {
affcc9d2 172 $errors = [];
7cb3d4f0 173 CRM_Core_Form::validateMandatoryFields($self->_fields, $fields, $errors);
6a488035 174
a479fe60 175 // validate the payment instrument values (e.g. credit card number)
1d1fee72 176 CRM_Core_Payment_Form::validatePaymentInstrument($self->_paymentProcessor['id'], $fields, $errors, NULL);
6a488035 177
6a488035
TO
178 return empty($errors) ? TRUE : $errors;
179 }
180
181 /**
fe482240 182 * Process the form.
6a488035
TO
183 */
184 public function postProcess() {
185 $params = $this->controller->exportValues($this->_name);
186 $status = NULL;
187
188 // now set the values for the billing location.
189 foreach ($this->_fields as $name => $value) {
190 $fields[$name] = 1;
191 }
192 $fields["email-{$this->_bltID}"] = 1;
193
affcc9d2 194 $processorParams = [];
6a488035
TO
195 foreach ($params as $key => $val) {
196 $key = str_replace('billing_', '', $key);
197 list($key) = explode('-', $key);
198 $processorParams[$key] = $val;
199 }
7a75d70b
MW
200 $processorParams['billingStateProvince'] = $processorParams['state_province'] = CRM_Core_PseudoConstant::stateProvince($params["billing_state_province_id-{$this->_bltID}"], FALSE);
201 $processorParams['billingCountry'] = $processorParams['country'] = CRM_Core_PseudoConstant::country($params["billing_country_id-{$this->_bltID}"], FALSE);
2e09448c
MW
202 $processorParams['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($processorParams);
203 $processorParams['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($processorParams);
cc929f4e
MW
204 $processorParams['recurProcessorID'] = $processorParams['subscriptionId'] = $this->getSubscriptionDetails()->processor_id;
205 $processorParams['amount'] = $this->getSubscriptionDetails()->amount;
206 $processorParams['contributionRecurID'] = $this->getContributionRecurID();
27c1277b 207 $message = '';
208 $updateSubscription = $this->_paymentProcessor['object']->updateSubscriptionBillingInfo($message, $processorParams);
6a488035
TO
209 if (is_a($updateSubscription, 'CRM_Core_Error')) {
210 CRM_Core_Error::displaySessionError($updateSubscription);
211 }
212 elseif ($updateSubscription) {
cc929f4e 213 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->getSubscriptionDetails()->contact_id, 'contact_type');
2b69dd84 214 CRM_Contact_BAO_Contact::createProfileContact($params,
6a488035 215 $fields,
cc929f4e 216 $this->getSubscriptionDetails()->contact_id,
6a488035
TO
217 NULL,
218 NULL,
219 $ctype
220 );
221
222 // build tpl params
cc929f4e
MW
223 if ($this->getSubscriptionDetails()->membership_id) {
224 $inputParams = array('id' => $this->getSubscriptionDetails()->membership_id);
6a488035 225 CRM_Member_BAO_Membership::getValues($inputParams, $tplParams);
cc929f4e 226 $tplParams = $tplParams[$this->getSubscriptionDetails()->membership_id];
6a488035
TO
227 $tplParams['membership_status'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $tplParams['status_id']);
228 $tplParams['membershipType'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $tplParams['membership_type_id']);
229 $status = ts('Billing details for your automatically renewed %1 membership have been updated.',
2b69dd84 230 [1 => $tplParams['membershipType']]
6a488035
TO
231 );
232 $msgTitle = ts('Details Updated');
233 $msgType = 'success';
234 }
235 else {
236 $status = ts('Billing details for the recurring contribution of %1, every %2 %3 have been updated.',
237 array(
cc929f4e
MW
238 1 => $this->getSubscriptionDetails()->amount,
239 2 => $this->getSubscriptionDetails()->frequency_interval,
240 3 => $this->getSubscriptionDetails()->frequency_unit,
6a488035
TO
241 )
242 );
243 $msgTitle = ts('Details Updated');
244 $msgType = 'success';
eea16664 245
6a488035 246 $tplParams = array(
cc929f4e
MW
247 'recur_frequency_interval' => $this->getSubscriptionDetails()->frequency_interval,
248 'recur_frequency_unit' => $this->getSubscriptionDetails()->frequency_unit,
249 'amount' => $this->getSubscriptionDetails()->amount,
6a488035
TO
250 );
251 }
252
253 // format new address for display
254 $addressParts = array("street_address", "city", "postal_code", "state_province", "country");
255 foreach ($addressParts as $part) {
9c1bc317 256 $addressParts[$part] = $processorParams[$part] ?? NULL;
6a488035
TO
257 }
258 $tplParams['address'] = CRM_Utils_Address::format($addressParts);
259
260 // format old address to store in activity details
261 $this->_defaults["state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvince($this->_defaults["state_province-{$this->_bltID}"], FALSE);
262 $this->_defaults["country-{$this->_bltID}"] = CRM_Core_PseudoConstant::country($this->_defaults["country-{$this->_bltID}"], FALSE);
263 $addressParts = array("street_address", "city", "postal_code", "state_province", "country");
264 foreach ($addressParts as $part) {
265 $key = "{$part}-{$this->_bltID}";
9c1bc317 266 $addressParts[$part] = $this->_defaults[$key] ?? NULL;
6a488035
TO
267 }
268 $this->_defaults['address'] = CRM_Utils_Address::format($addressParts);
269
270 // format new billing name
271 $name = $processorParams['first_name'];
a7488080 272 if (!empty($processorParams['middle_name'])) {
6a488035
TO
273 $name .= " {$processorParams['middle_name']}";
274 }
275 $name .= ' ' . $processorParams['last_name'];
276 $name = trim($name);
277 $tplParams['billingName'] = $name;
278
279 // format old billing name
280 $name = $this->_defaults['first_name'];
a7488080 281 if (!empty($this->_defaults['middle_name'])) {
6a488035
TO
282 $name .= " {$this->_defaults['middle_name']}";
283 }
284 $name .= ' ' . $this->_defaults['last_name'];
285 $name = trim($name);
286 $this->_defaults['billingName'] = $name;
287
288 $message .= "
289<br/><br/>New Billing Name and Address
290<br/>==============================
291<br/>{$tplParams['billingName']}
292<br/>{$tplParams['address']}
293
294<br/><br/>Previous Billing Name and Address
295<br/>==================================
296<br/>{$this->_defaults['billingName']}
297<br/>{$this->_defaults['address']}";
298
299 $activityParams = array(
cc929f4e 300 'source_contact_id' => $this->getSubscriptionDetails()->contact_id,
593dbb07 301 'activity_type_id' => CRM_Core_PseudoConstant::getKey(
302 'CRM_Activity_BAO_Activity',
303 'activity_type_id',
304 'Update Recurring Contribution Billing Details'
6a488035
TO
305 ),
306 'subject' => ts('Recurring Contribution Billing Details Updated'),
307 'details' => $message,
308 'activity_date_time' => date('YmdHis'),
593dbb07 309 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
6a488035
TO
310 );
311 $session = CRM_Core_Session::singleton();
312 $cid = $session->get('userID');
313 if ($cid) {
314 $activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
315 $activityParams['source_contact_id'] = $cid;
316 }
317 CRM_Activity_BAO_Activity::create($activityParams);
318
cc929f4e 319 list($donorDisplayName, $donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->getSubscriptionDetails()->contact_id);
6a488035
TO
320 $tplParams['contact'] = array('display_name' => $donorDisplayName);
321
2e09448c 322 $tplParams = array_merge($tplParams, CRM_Contribute_Form_AbstractEditPayment::formatCreditCardDetails($processorParams));
6a488035
TO
323
324 $sendTemplateParams = array(
cc929f4e
MW
325 'groupName' => $this->getSubscriptionDetails()->membership_id ? 'msg_tpl_workflow_membership' : 'msg_tpl_workflow_contribution',
326 'valueName' => $this->getSubscriptionDetails()->membership_id ? 'membership_autorenew_billing' : 'contribution_recurring_billing',
327 'contactId' => $this->getSubscriptionDetails()->contact_id,
6a488035 328 'tplParams' => $tplParams,
cc929f4e 329 'isTest' => $this->getSubscriptionDetails()->is_test,
6a488035 330 'PDFFilename' => 'receipt.pdf',
ae06bba6 331 'from' => CRM_Contribute_BAO_ContributionRecur::getRecurFromAddress($this->getContributionRecurID()),
6a488035
TO
332 'toName' => $donorDisplayName,
333 'toEmail' => $donorEmail,
334 );
c6327d7d 335 list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
6a488035
TO
336 }
337 else {
338 $status = ts('There was some problem updating the billing details.');
339 $msgTitle = ts('Update Error');
340 $msgType = 'error';
341 }
342
343 $session = CRM_Core_Session::singleton();
353ffa53 344 $userID = $session->get('userID');
481a74f4 345 if ($userID && $status) {
6a488035 346 $session->setStatus($status, $msgTitle, $msgType);
0db6c3e1 347 }
4c9b6178 348 elseif (!$userID) {
389bcebf 349 if ($status) {
6a488035 350 CRM_Utils_System::setUFMessage($status);
389bcebf 351 }
6a488035 352 $result = (int) ($updateSubscription && isset($ctype));
389bcebf 353 if (isset($tplParams)) {
6a488035 354 $session->set('resultParams', $tplParams);
389bcebf 355 }
eea16664 356 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/subscriptionstatus',
353ffa53 357 "reset=1&task=billing&result={$result}"));
6a488035
TO
358 }
359 }
96025800 360
6a488035 361}