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