Add shared parent for ContributionRecur forms
[civicrm-core.git] / CRM / Contribute / Form / UpdateBilling.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
6a488035
TO
32 */
33
34/**
347e061b 35 * This class generates form components for processing a contribution.
6a488035 36 */
ca809bb6 37class CRM_Contribute_Form_UpdateBilling extends CRM_Contribute_Form_ContributionRecur {
6a488035
TO
38 protected $_mode = NULL;
39
40 protected $_subscriptionDetails = NULL;
41
42 protected $_selfService = FALSE;
43
44 public $_bltID = NULL;
a6513ad5
EM
45
46 /**
47 * @var array current payment processor including a copy of the object in 'object' key
48 */
49 public $_paymentProcessor = array();
6a488035 50
6a488035 51 /**
fe482240 52 * Set variables up before form is built.
6a488035
TO
53 */
54 public function preProcess() {
55 $this->_mid = CRM_Utils_Request::retrieve('mid', 'Integer', $this, FALSE);
56 $this->_crid = CRM_Utils_Request::retrieve('crid', 'Integer', $this, FALSE);
57 if ($this->_crid) {
58 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_crid, 'recur', 'info');
f1e72c05 59 $this->_paymentProcessor['object'] = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_crid, 'recur', 'obj');
6a488035 60 $this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_crid);
eea16664 61
6a488035
TO
62 // Are we cancelling a recurring contribution that is linked to an auto-renew membership?
63 if ($this->_subscriptionDetails->membership_id) {
64 $this->_mid = $this->_subscriptionDetails->membership_id;
65 }
66 }
67
68 $this->_coid = CRM_Utils_Request::retrieve('coid', 'Integer', $this, FALSE);
69 if ($this->_coid) {
70 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'info');
a6513ad5 71 $this->_paymentProcessor['object'] = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'obj');
6a488035
TO
72 $this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_coid, 'contribution');
73 }
74
75 if ($this->_mid) {
76 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_mid, 'membership', 'info');
a6513ad5 77 $this->_paymentProcessor['object'] = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_mid, 'membership', 'obj');
6a488035
TO
78 $this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_mid, 'membership');
79 $membershipTypes = CRM_Member_PseudoConstant::membershipType();
80 $membershipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_mid, 'membership_type_id');
81 $this->assign('membershipType', CRM_Utils_Array::value($membershipTypeId, $membershipTypes));
82 $this->_mode = 'auto_renew';
83 }
84
1273d77c 85 if ((!$this->_crid && !$this->_coid && !$this->_mid) || (!$this->_subscriptionDetails)) {
6a488035
TO
86 CRM_Core_Error::fatal('Required information missing.');
87 }
88 if (!CRM_Core_Permission::check('edit contributions')) {
a21270c0 89 if ($this->_subscriptionDetails->contact_id != $this->getContactID()) {
7a17438c 90 CRM_Core_Error::statusBounce(ts('You do not have permission to cancel subscription.'));
6a488035
TO
91 }
92 $this->_selfService = TRUE;
93 }
94
b690491e 95 if (!$this->_paymentProcessor['object']->supports('updateSubscriptionBillingInfo')) {
6a488035 96 CRM_Core_Error::fatal(ts("%1 processor doesn't support updating subscription billing details.",
353ffa53
TO
97 array(1 => $this->_paymentProcessor['object']->_processorName)
98 ));
6a488035
TO
99 }
100 $this->assign('paymentProcessor', $this->_paymentProcessor);
101
8345c9d3 102 $this->assignBillingType();
6a488035
TO
103
104 $this->assign('frequency_unit', $this->_subscriptionDetails->frequency_unit);
105 $this->assign('frequency_interval', $this->_subscriptionDetails->frequency_interval);
106 $this->assign('amount', $this->_subscriptionDetails->amount);
107 $this->assign('installments', $this->_subscriptionDetails->installments);
108 $this->assign('mode', $this->_mode);
109
110 // handle context redirection
111 CRM_Contribute_BAO_ContributionRecur::setSubscriptionContext();
112 }
113
186c9c17 114 /**
0c6c47a5 115 * Set the default values of various form elements.
186c9c17 116 *
186c9c17 117 * @return array
0c6c47a5 118 * Default values
186c9c17 119 */
00be9182 120 public function setDefaultValues() {
6a488035
TO
121 $this->_defaults = array();
122
123 if ($this->_subscriptionDetails->contact_id) {
353ffa53
TO
124 $fields = array();
125 $names = array(
126 'first_name',
127 'middle_name',
128 'last_name',
129 "street_address-{$this->_bltID}",
130 "city-{$this->_bltID}",
131 "postal_code-{$this->_bltID}",
132 "country_id-{$this->_bltID}",
133 "state_province_id-{$this->_bltID}",
6a488035
TO
134 );
135 foreach ($names as $name) {
136 $fields[$name] = 1;
137 }
138 $fields["state_province-{$this->_bltID}"] = 1;
139 $fields["country-{$this->_bltID}"] = 1;
140 $fields["email-{$this->_bltID}"] = 1;
141 $fields['email-Primary'] = 1;
142
143 CRM_Core_BAO_UFGroup::setProfileDefaults($this->_subscriptionDetails->contact_id, $fields, $this->_defaults);
144
145 // use primary email address if billing email address is empty
146 if (empty($this->_defaults["email-{$this->_bltID}"]) &&
147 !empty($this->_defaults['email-Primary'])
148 ) {
149 $this->_defaults["email-{$this->_bltID}"] = $this->_defaults['email-Primary'];
150 }
151
152 foreach ($names as $name) {
153 if (!empty($this->_defaults[$name])) {
154 $this->_defaults['billing_' . $name] = $this->_defaults[$name];
155 }
156 }
157 }
158
6a488035
TO
159 $config = CRM_Core_Config::singleton();
160 // set default country from config if no country set
a7488080 161 if (empty($this->_defaults["billing_country_id-{$this->_bltID}"])) {
6a488035
TO
162 $this->_defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
163 }
164
6a488035
TO
165 return $this->_defaults;
166 }
167
168 /**
fe482240 169 * Build the form object.
6a488035
TO
170 */
171 public function buildQuickForm() {
172 $type = 'next';
481a74f4 173 if ($this->_selfService) {
6a488035
TO
174 $type = 'submit';
175 }
176
177 $this->addButtons(array(
178 array(
179 'type' => $type,
180 'name' => ts('Save'),
181 'isDefault' => TRUE,
182 ),
183 array(
184 'type' => 'cancel',
185 'name' => ts('Cancel'),
186 ),
187 )
188 );
189
3c3aac0b 190 CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, TRUE, TRUE);
6a488035
TO
191 $this->addFormRule(array('CRM_Contribute_Form_UpdateBilling', 'formRule'), $this);
192 }
193
194 /**
fe482240 195 * Global form rule.
6a488035 196 *
014c4014
TO
197 * @param array $fields
198 * The input form values.
199 * @param array $files
200 * The uploaded files if any.
0c6c47a5 201 * @param CRM_Core_Form $self
da6b46f4 202 *
6a488035 203 *
72b3a70c
CW
204 * @return bool|array
205 * true if no errors, else array of errors
6a488035 206 */
00be9182 207 public static function formRule($fields, $files, $self) {
7cb3d4f0
CW
208 $errors = array();
209 CRM_Core_Form::validateMandatoryFields($self->_fields, $fields, $errors);
6a488035 210
a479fe60 211 // validate the payment instrument values (e.g. credit card number)
1d1fee72 212 CRM_Core_Payment_Form::validatePaymentInstrument($self->_paymentProcessor['id'], $fields, $errors, NULL);
6a488035 213
6a488035
TO
214 return empty($errors) ? TRUE : $errors;
215 }
216
217 /**
fe482240 218 * Process the form.
6a488035
TO
219 */
220 public function postProcess() {
221 $params = $this->controller->exportValues($this->_name);
222 $status = NULL;
223
224 // now set the values for the billing location.
225 foreach ($this->_fields as $name => $value) {
226 $fields[$name] = 1;
227 }
228 $fields["email-{$this->_bltID}"] = 1;
229
230 $processorParams = array();
231 foreach ($params as $key => $val) {
232 $key = str_replace('billing_', '', $key);
233 list($key) = explode('-', $key);
234 $processorParams[$key] = $val;
235 }
236 $processorParams['state_province'] = CRM_Core_PseudoConstant::stateProvince($params["billing_state_province_id-{$this->_bltID}"], FALSE);
237 $processorParams['country'] = CRM_Core_PseudoConstant::country($params["billing_country_id-{$this->_bltID}"], FALSE);
238 $processorParams['month'] = $processorParams['credit_card_exp_date']['M'];
239 $processorParams['year'] = $processorParams['credit_card_exp_date']['Y'];
240 $processorParams['subscriptionId'] = $this->_subscriptionDetails->subscription_id;
241 $processorParams['amount'] = $this->_subscriptionDetails->amount;
f1e72c05 242 $updateSubscription = $this->_paymentProcessor['object']->updateSubscriptionBillingInfo($message, $processorParams);
6a488035
TO
243 if (is_a($updateSubscription, 'CRM_Core_Error')) {
244 CRM_Core_Error::displaySessionError($updateSubscription);
245 }
246 elseif ($updateSubscription) {
247 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_subscriptionDetails->contact_id, 'contact_type');
248 $contact = &CRM_Contact_BAO_Contact::createProfileContact($params,
249 $fields,
250 $this->_subscriptionDetails->contact_id,
251 NULL,
252 NULL,
253 $ctype
254 );
255
256 // build tpl params
257 if ($this->_subscriptionDetails->membership_id) {
258 $inputParams = array('id' => $this->_subscriptionDetails->membership_id);
259 CRM_Member_BAO_Membership::getValues($inputParams, $tplParams);
260 $tplParams = $tplParams[$this->_subscriptionDetails->membership_id];
261 $tplParams['membership_status'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $tplParams['status_id']);
262 $tplParams['membershipType'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $tplParams['membership_type_id']);
263 $status = ts('Billing details for your automatically renewed %1 membership have been updated.',
264 array(1 => $tplParams['membershipType'])
265 );
266 $msgTitle = ts('Details Updated');
267 $msgType = 'success';
268 }
269 else {
270 $status = ts('Billing details for the recurring contribution of %1, every %2 %3 have been updated.',
271 array(
272 1 => $this->_subscriptionDetails->amount,
273 2 => $this->_subscriptionDetails->frequency_interval,
21dfd5f5 274 3 => $this->_subscriptionDetails->frequency_unit,
6a488035
TO
275 )
276 );
277 $msgTitle = ts('Details Updated');
278 $msgType = 'success';
eea16664 279
6a488035
TO
280 $tplParams = array(
281 'recur_frequency_interval' => $this->_subscriptionDetails->frequency_interval,
282 'recur_frequency_unit' => $this->_subscriptionDetails->frequency_unit,
283 'amount' => $this->_subscriptionDetails->amount,
284 );
285 }
286
287 // format new address for display
288 $addressParts = array("street_address", "city", "postal_code", "state_province", "country");
289 foreach ($addressParts as $part) {
290 $addressParts[$part] = CRM_Utils_Array::value($part, $processorParams);
291 }
292 $tplParams['address'] = CRM_Utils_Address::format($addressParts);
293
294 // format old address to store in activity details
295 $this->_defaults["state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvince($this->_defaults["state_province-{$this->_bltID}"], FALSE);
296 $this->_defaults["country-{$this->_bltID}"] = CRM_Core_PseudoConstant::country($this->_defaults["country-{$this->_bltID}"], FALSE);
297 $addressParts = array("street_address", "city", "postal_code", "state_province", "country");
298 foreach ($addressParts as $part) {
299 $key = "{$part}-{$this->_bltID}";
300 $addressParts[$part] = CRM_Utils_Array::value($key, $this->_defaults);
301 }
302 $this->_defaults['address'] = CRM_Utils_Address::format($addressParts);
303
304 // format new billing name
305 $name = $processorParams['first_name'];
a7488080 306 if (!empty($processorParams['middle_name'])) {
6a488035
TO
307 $name .= " {$processorParams['middle_name']}";
308 }
309 $name .= ' ' . $processorParams['last_name'];
310 $name = trim($name);
311 $tplParams['billingName'] = $name;
312
313 // format old billing name
314 $name = $this->_defaults['first_name'];
a7488080 315 if (!empty($this->_defaults['middle_name'])) {
6a488035
TO
316 $name .= " {$this->_defaults['middle_name']}";
317 }
318 $name .= ' ' . $this->_defaults['last_name'];
319 $name = trim($name);
320 $this->_defaults['billingName'] = $name;
321
322 $message .= "
323<br/><br/>New Billing Name and Address
324<br/>==============================
325<br/>{$tplParams['billingName']}
326<br/>{$tplParams['address']}
327
328<br/><br/>Previous Billing Name and Address
329<br/>==================================
330<br/>{$this->_defaults['billingName']}
331<br/>{$this->_defaults['address']}";
332
333 $activityParams = array(
334 'source_contact_id' => $this->_subscriptionDetails->contact_id,
593dbb07 335 'activity_type_id' => CRM_Core_PseudoConstant::getKey(
336 'CRM_Activity_BAO_Activity',
337 'activity_type_id',
338 'Update Recurring Contribution Billing Details'
6a488035
TO
339 ),
340 'subject' => ts('Recurring Contribution Billing Details Updated'),
341 'details' => $message,
342 'activity_date_time' => date('YmdHis'),
593dbb07 343 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'status_id', 'Completed'),
6a488035
TO
344 );
345 $session = CRM_Core_Session::singleton();
346 $cid = $session->get('userID');
347 if ($cid) {
348 $activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
349 $activityParams['source_contact_id'] = $cid;
350 }
351 CRM_Activity_BAO_Activity::create($activityParams);
352
353 // send notification
354 if ($this->_subscriptionDetails->contribution_page_id) {
355 CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_ContributionPage', 'id',
356 $this->_subscriptionDetails->contribution_page_id, $value, array(
357 'title',
358 'receipt_from_name',
359 'receipt_from_email',
360 )
361 );
362 $receiptFrom = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$this->_subscriptionDetails->contribution_page_id]) . '" <' . $value[$this->_subscriptionDetails->contribution_page_id]['receipt_from_email'] . '>';
363 }
364 else {
365 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
366 $receiptFrom = "$domainValues[0] <$domainValues[1]>";
367 }
368 list($donorDisplayName, $donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_subscriptionDetails->contact_id);
369 $tplParams['contact'] = array('display_name' => $donorDisplayName);
370
371 $date = CRM_Utils_Date::format($processorParams['credit_card_exp_date']);
372 $tplParams['credit_card_exp_date'] = CRM_Utils_Date::mysqlToIso($date);
373 $tplParams['credit_card_number'] = CRM_Utils_System::mungeCreditCard($processorParams['credit_card_number']);
374 $tplParams['credit_card_type'] = $processorParams['credit_card_type'];
375
376 $sendTemplateParams = array(
377 'groupName' => $this->_subscriptionDetails->membership_id ? 'msg_tpl_workflow_membership' : 'msg_tpl_workflow_contribution',
378 'valueName' => $this->_subscriptionDetails->membership_id ? 'membership_autorenew_billing' : 'contribution_recurring_billing',
379 'contactId' => $this->_subscriptionDetails->contact_id,
380 'tplParams' => $tplParams,
381 'isTest' => $this->_subscriptionDetails->is_test,
382 'PDFFilename' => 'receipt.pdf',
383 'from' => $receiptFrom,
384 'toName' => $donorDisplayName,
385 'toEmail' => $donorEmail,
386 );
c6327d7d 387 list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
6a488035
TO
388 }
389 else {
390 $status = ts('There was some problem updating the billing details.');
391 $msgTitle = ts('Update Error');
392 $msgType = 'error';
393 }
394
395 $session = CRM_Core_Session::singleton();
353ffa53 396 $userID = $session->get('userID');
481a74f4 397 if ($userID && $status) {
6a488035 398 $session->setStatus($status, $msgTitle, $msgType);
0db6c3e1 399 }
4c9b6178 400 elseif (!$userID) {
389bcebf 401 if ($status) {
6a488035 402 CRM_Utils_System::setUFMessage($status);
389bcebf 403 }
6a488035 404 $result = (int) ($updateSubscription && isset($ctype));
389bcebf 405 if (isset($tplParams)) {
6a488035 406 $session->set('resultParams', $tplParams);
389bcebf 407 }
eea16664 408 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/subscriptionstatus',
353ffa53 409 "reset=1&task=billing&result={$result}"));
6a488035
TO
410 }
411 }
96025800 412
6a488035 413}