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