Merge pull request #16479 from twomice/1579_avoid_needless_getPayPalPaymentProcessorI...
[civicrm-core.git] / CRM / Contribute / Form / CancelSubscription.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 */
11ec1f96 11use Civi\Payment\PropertyBag;
6a488035
TO
12
13/**
14 *
15 * @package CRM
ca5cec67 16 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
17 */
18
19/**
95cdcc0f 20 * This class provides support for canceling recurring subscriptions.
6a488035 21 */
ca809bb6 22class CRM_Contribute_Form_CancelSubscription extends CRM_Contribute_Form_ContributionRecur {
6a488035
TO
23
24 protected $_userContext = NULL;
25
26 protected $_mode = NULL;
27
f1105edc 28 /**
29 * Should custom data be suppressed on this form.
30 *
31 * We override to suppress custom data because historically it has not been
32 * shown on this form & we don't want to expose it as a by-product of
33 * other change without establishing that it would be good on this form.
34 *
35 * @return bool
36 */
37 protected function isSuppressCustomData() {
38 return TRUE;
39 }
40
6a488035 41 /**
fe482240 42 * Set variables up before form is built.
503699d5 43 *
44 * @throws \CRM_Core_Exception
6a488035
TO
45 */
46 public function preProcess() {
1f17c8ef 47 parent::preProcess();
6a488035 48 if ($this->_crid) {
59545b08
MW
49 $this->assign('frequency_unit', $this->getSubscriptionDetails()->frequency_unit);
50 $this->assign('frequency_interval', $this->getSubscriptionDetails()->frequency_interval);
51 $this->assign('amount', $this->getSubscriptionDetails()->amount);
52 $this->assign('installments', $this->getSubscriptionDetails()->installments);
d947cfb5 53
6a488035 54 // Are we cancelling a recurring contribution that is linked to an auto-renew membership?
59545b08
MW
55 if ($this->getSubscriptionDetails()->membership_id) {
56 $this->_mid = $this->getSubscriptionDetails()->membership_id;
6a488035
TO
57 }
58 }
59
60 if ($this->_mid) {
6a488035 61 $this->_mode = 'auto_renew';
16381e37
J
62 // CRM-18468: crid is more accurate than mid for getting
63 // subscriptionDetails, so don't get them again.
6a488035
TO
64
65 $membershipTypes = CRM_Member_PseudoConstant::membershipType();
66 $membershipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_mid, 'membership_type_id');
67 $this->assign('membershipType', CRM_Utils_Array::value($membershipTypeId, $membershipTypes));
68 }
69
6a488035
TO
70 if ($this->_coid) {
71 if (CRM_Contribute_BAO_Contribution::isSubscriptionCancelled($this->_coid)) {
6a4a50a1 72 CRM_Core_Error::statusBounce(ts('The recurring contribution looks to have been cancelled already.'));
6a488035
TO
73 }
74 $this->_paymentProcessorObj = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'obj');
d947cfb5 75
59545b08
MW
76 $this->assign('frequency_unit', $this->getSubscriptionDetails()->frequency_unit);
77 $this->assign('frequency_interval', $this->getSubscriptionDetails()->frequency_interval);
78 $this->assign('amount', $this->getSubscriptionDetails()->amount);
79 $this->assign('installments', $this->getSubscriptionDetails()->installments);
6a488035
TO
80 }
81
d947cfb5
DL
82 if (
83 (!$this->_crid && !$this->_coid && !$this->_mid) ||
59545b08 84 (!$this->getSubscriptionDetails())
6a488035 85 ) {
f1105edc 86 CRM_Core_Error::statusBounce('Required information missing.');
6a488035
TO
87 }
88
6a488035
TO
89 // handle context redirection
90 CRM_Contribute_BAO_ContributionRecur::setSubscriptionContext();
91
92 CRM_Utils_System::setTitle($this->_mid ? ts('Cancel Auto-renewal') : ts('Cancel Recurring Contribution'));
93 $this->assign('mode', $this->_mode);
94
f1105edc 95 if ($this->isSelfService()) {
96 unset($this->entityFields['send_cancel_request'], $this->entityFields['is_notify']);
97 }
98
59545b08 99 if ($this->getSubscriptionDetails()->contact_id) {
7c550ca0 100 list($this->_donorDisplayName, $this->_donorEmail)
59545b08 101 = CRM_Contact_BAO_Contact::getContactDetails($this->getSubscriptionDetails()->contact_id);
6a488035
TO
102 }
103 }
104
f1105edc 105 /**
106 * Set entity fields for this cancellation.
107 */
108 public function setEntityFields() {
109 $this->entityFields = [
110 'cancel_reason' => ['name' => 'cancel_reason'],
111 ];
112 $this->entityFields['send_cancel_request'] = [
703235f6 113 'title' => ts('Send cancellation request?'),
f1105edc 114 'name' => 'send_cancel_request',
115 'not-auto-addable' => TRUE,
116 ];
117 $this->entityFields['is_notify'] = [
118 'title' => ts('Notify Contributor?'),
119 'name' => 'is_notify',
120 'not-auto-addable' => TRUE,
121 ];
122 }
123
6a488035 124 /**
fe482240 125 * Build the form object.
6a488035
TO
126 */
127 public function buildQuickForm() {
f1105edc 128 $this->buildQuickEntityForm();
6a488035 129 // Determine if we can cancel recurring contribution via API with this processor
1524a007 130 $cancelSupported = $this->_paymentProcessorObj->supports('CancelRecurring');
6a488035 131 if ($cancelSupported) {
be2fb01f 132 $searchRange = [];
6a488035
TO
133 $searchRange[] = $this->createElement('radio', NULL, NULL, ts('Yes'), '1');
134 $searchRange[] = $this->createElement('radio', NULL, NULL, ts('No'), '0');
135
d947cfb5
DL
136 $this->addGroup(
137 $searchRange,
138 'send_cancel_request',
139 ts('Send cancellation request to %1 ?',
be2fb01f 140 [1 => $this->_paymentProcessorObj->_processorName])
d947cfb5 141 );
6a488035
TO
142 }
143 $this->assign('cancelSupported', $cancelSupported);
d947cfb5 144
6a488035
TO
145 if ($this->_donorEmail) {
146 $this->add('checkbox', 'is_notify', ts('Notify Contributor?'));
147 }
148 if ($this->_mid) {
149 $cancelButton = ts('Cancel Automatic Membership Renewal');
150 }
151 else {
152 $cancelButton = ts('Cancel Recurring Contribution');
153 }
154
155 $type = 'next';
f1105edc 156 if ($this->isSelfService()) {
6a488035
TO
157 $type = 'submit';
158 }
159
be2fb01f 160 $this->addButtons([
1330f57a
SL
161 [
162 'type' => $type,
163 'name' => $cancelButton,
164 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
165 'isDefault' => TRUE,
166 ],
167 [
168 'type' => 'cancel',
169 'name' => ts('Not Now'),
170 ],
171 ]);
6a488035
TO
172 }
173
174 /**
1c4a09f4 175 * Set default values for the form.
6a488035 176 *
a6c01b45
CW
177 * @return array
178 * array of default values
6a488035 179 */
00be9182 180 public function setDefaultValues() {
be2fb01f 181 return [
1c4a09f4 182 'is_notify' => 1,
183 'send_cancel_request' => 1,
be2fb01f 184 ];
6a488035
TO
185 }
186
187 /**
fe482240 188 * Process the form submission.
6a488035
TO
189 */
190 public function postProcess() {
11ec1f96 191 $message = NULL;
6a488035 192 $cancelSubscription = TRUE;
353ffa53 193 $params = $this->controller->exportValues($this->_name);
6a488035 194
f1105edc 195 if ($this->isSelfService()) {
6a488035 196 // for self service force sending-request & notify
1524a007 197 if ($this->_paymentProcessorObj->supports('cancelRecurring')) {
6a488035 198 $params['send_cancel_request'] = 1;
d947cfb5
DL
199 }
200
201 if ($this->_donorEmail) {
6a488035 202 $params['is_notify'] = 1;
d947cfb5 203 }
6a488035
TO
204 }
205
206 if (CRM_Utils_Array::value('send_cancel_request', $params) == 1) {
4ae44cc6 207 try {
11ec1f96 208 $propertyBag = new PropertyBag();
157edc4f 209 $propertyBag->setContributionRecurID($this->getSubscriptionDetails()->recur_id);
59545b08 210 $propertyBag->setRecurProcessorID($this->getSubscriptionDetails()->subscription_id);
11ec1f96 211 $message = $this->_paymentProcessorObj->doCancelRecurring($propertyBag)['message'];
4ae44cc6
RLAR
212 }
213 catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
214 CRM_Core_Error::statusBounce($e->getMessage());
215 }
6a488035
TO
216 }
217
11ec1f96 218 if ($cancelSubscription) {
c7d9325a 219 try {
220 civicrm_api3('ContributionRecur', 'cancel', [
59545b08 221 'id' => $this->getSubscriptionDetails()->recur_id,
c7d9325a 222 'membership_id' => $this->_mid,
223 'processor_message' => $message,
f1105edc 224 'cancel_reason' => $params['cancel_reason'],
c7d9325a 225 ]);
d947cfb5 226
be2fb01f 227 $tplParams = [];
6a488035 228 if ($this->_mid) {
be2fb01f 229 $inputParams = ['id' => $this->_mid];
6a488035
TO
230 CRM_Member_BAO_Membership::getValues($inputParams, $tplParams);
231 $tplParams = $tplParams[$this->_mid];
7c550ca0
WA
232 $tplParams['membership_status']
233 = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $tplParams['status_id']);
234 $tplParams['membershipType']
235 = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $tplParams['membership_type_id']);
be2fb01f 236 $status = ts('The automatic renewal of your %1 membership has been cancelled as requested. This does not affect the status of your membership - you will receive a separate notification when your membership is up for renewal.', [1 => $tplParams['membershipType']]);
6a488035
TO
237 $msgTitle = 'Membership Renewal Cancelled';
238 $msgType = 'info';
239 }
240 else {
59545b08
MW
241 $tplParams['recur_frequency_interval'] = $this->getSubscriptionDetails()->frequency_interval;
242 $tplParams['recur_frequency_unit'] = $this->getSubscriptionDetails()->frequency_unit;
243 $tplParams['amount'] = $this->getSubscriptionDetails()->amount;
be2fb01f 244 $tplParams['contact'] = ['display_name' => $this->_donorDisplayName];
6a488035 245 $status = ts('The recurring contribution of %1, every %2 %3 has been cancelled.',
be2fb01f 246 [
59545b08
MW
247 1 => $this->getSubscriptionDetails()->amount,
248 2 => $this->getSubscriptionDetails()->frequency_interval,
249 3 => $this->getSubscriptionDetails()->frequency_unit,
be2fb01f 250 ]
6a488035
TO
251 );
252 $msgTitle = 'Contribution Cancelled';
253 $msgType = 'success';
254 }
255
256 if (CRM_Utils_Array::value('is_notify', $params) == 1) {
59545b08 257 if ($this->getSubscriptionDetails()->contribution_page_id) {
d947cfb5
DL
258 CRM_Core_DAO::commonRetrieveAll(
259 'CRM_Contribute_DAO_ContributionPage',
260 'id',
59545b08 261 $this->getSubscriptionDetails()->contribution_page_id,
d947cfb5 262 $value,
be2fb01f 263 ['title', 'receipt_from_name', 'receipt_from_email']
d947cfb5 264 );
7c550ca0 265 $receiptFrom
59545b08 266 = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$this->getSubscriptionDetails()->contribution_page_id]) .
d947cfb5 267 '" <' .
59545b08 268 $value[$this->getSubscriptionDetails()->contribution_page_id]['receipt_from_email'] .
d947cfb5 269 '>';
6a488035
TO
270 }
271 else {
272 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
273 $receiptFrom = "$domainValues[0] <$domainValues[1]>";
274 }
d947cfb5 275
6a488035 276 // send notification
7c550ca0 277 $sendTemplateParams
be2fb01f 278 = [
353ffa53
TO
279 'groupName' => $this->_mode == 'auto_renew' ? 'msg_tpl_workflow_membership' : 'msg_tpl_workflow_contribution',
280 'valueName' => $this->_mode == 'auto_renew' ? 'membership_autorenew_cancelled' : 'contribution_recurring_cancelled',
59545b08 281 'contactId' => $this->getSubscriptionDetails()->contact_id,
353ffa53
TO
282 'tplParams' => $tplParams,
283 //'isTest' => $isTest, set this from _objects
284 'PDFFilename' => 'receipt.pdf',
285 'from' => $receiptFrom,
286 'toName' => $this->_donorDisplayName,
287 'toEmail' => $this->_donorEmail,
be2fb01f 288 ];
c6327d7d 289 list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
6a488035
TO
290 }
291 }
c7d9325a 292 catch (CiviCRM_API3_Exception $e) {
6a488035
TO
293 $msgType = 'error';
294 $msgTitle = ts('Error');
295 if ($params['send_cancel_request'] == 1) {
296 $status = ts('Recurring contribution was cancelled successfully by the processor, but could not be marked as cancelled in the database.');
297 }
298 else {
299 $status = ts('Recurring contribution could not be cancelled in the database.');
300 }
301 }
302 }
303 else {
304 $status = ts('The recurring contribution could not be cancelled.');
305 $msgTitle = 'Error Cancelling Contribution';
306 $msgType = 'error';
307 }
308
309 $session = CRM_Core_Session::singleton();
353ffa53 310 $userID = $session->get('userID');
481a74f4 311 if ($userID && $status) {
6a488035
TO
312 $session->setStatus($status, $msgTitle, $msgType);
313 }
314 elseif (!$userID) {
7c550ca0 315 if ($status) {
6a488035 316 CRM_Utils_System::setUFMessage($status);
7c550ca0
WA
317 // keep result as 1, since we not displaying anything on the redirected page anyway
318 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/subscriptionstatus',
353ffa53 319 "reset=1&task=cancel&result=1"));
7c550ca0 320 }
6a488035
TO
321 }
322 }
96025800 323
6a488035 324}