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