Merge pull request #15670 from eileenmcnaughton/dupe_locks
[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 // Note the 'subscriptionId' here is the value stored in
207 // civicrm_contribution_recur.processor_id
208 $cancelParams = ['subscriptionId' => $this->_subscriptionDetails->subscription_id];
209 try {
210 $cancelSubscription = $this->_paymentProcessorObj->cancelSubscription($message, $cancelParams);
211 }
212 catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
213 CRM_Core_Error::statusBounce($e->getMessage());
214 }
215 }
216
217 if (is_a($cancelSubscription, 'CRM_Core_Error')) {
218 CRM_Core_Error::displaySessionError($cancelSubscription);
219 }
220 elseif ($cancelSubscription) {
221 try {
222 civicrm_api3('ContributionRecur', 'cancel', [
223 'id' => $this->_subscriptionDetails->recur_id,
224 'membership_id' => $this->_mid,
225 'processor_message' => $message,
226 'cancel_reason' => $params['cancel_reason'],
227 ]);
228
229 $tplParams = [];
230 if ($this->_mid) {
231 $inputParams = ['id' => $this->_mid];
232 CRM_Member_BAO_Membership::getValues($inputParams, $tplParams);
233 $tplParams = $tplParams[$this->_mid];
234 $tplParams['membership_status']
235 = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $tplParams['status_id']);
236 $tplParams['membershipType']
237 = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $tplParams['membership_type_id']);
238 $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']]);
239 $msgTitle = 'Membership Renewal Cancelled';
240 $msgType = 'info';
241 }
242 else {
243 $tplParams['recur_frequency_interval'] = $this->_subscriptionDetails->frequency_interval;
244 $tplParams['recur_frequency_unit'] = $this->_subscriptionDetails->frequency_unit;
245 $tplParams['amount'] = $this->_subscriptionDetails->amount;
246 $tplParams['contact'] = ['display_name' => $this->_donorDisplayName];
247 $status = ts('The recurring contribution of %1, every %2 %3 has been cancelled.',
248 [
249 1 => $this->_subscriptionDetails->amount,
250 2 => $this->_subscriptionDetails->frequency_interval,
251 3 => $this->_subscriptionDetails->frequency_unit,
252 ]
253 );
254 $msgTitle = 'Contribution Cancelled';
255 $msgType = 'success';
256 }
257
258 if (CRM_Utils_Array::value('is_notify', $params) == 1) {
259 if ($this->_subscriptionDetails->contribution_page_id) {
260 CRM_Core_DAO::commonRetrieveAll(
261 'CRM_Contribute_DAO_ContributionPage',
262 'id',
263 $this->_subscriptionDetails->contribution_page_id,
264 $value,
265 ['title', 'receipt_from_name', 'receipt_from_email']
266 );
267 $receiptFrom
268 = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$this->_subscriptionDetails->contribution_page_id]) .
269 '" <' .
270 $value[$this->_subscriptionDetails->contribution_page_id]['receipt_from_email'] .
271 '>';
272 }
273 else {
274 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
275 $receiptFrom = "$domainValues[0] <$domainValues[1]>";
276 }
277
278 // send notification
279 $sendTemplateParams
280 = [
281 'groupName' => $this->_mode == 'auto_renew' ? 'msg_tpl_workflow_membership' : 'msg_tpl_workflow_contribution',
282 'valueName' => $this->_mode == 'auto_renew' ? 'membership_autorenew_cancelled' : 'contribution_recurring_cancelled',
283 'contactId' => $this->_subscriptionDetails->contact_id,
284 'tplParams' => $tplParams,
285 //'isTest' => $isTest, set this from _objects
286 'PDFFilename' => 'receipt.pdf',
287 'from' => $receiptFrom,
288 'toName' => $this->_donorDisplayName,
289 'toEmail' => $this->_donorEmail,
290 ];
291 list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
292 }
293 }
294 catch (CiviCRM_API3_Exception $e) {
295 $msgType = 'error';
296 $msgTitle = ts('Error');
297 if ($params['send_cancel_request'] == 1) {
298 $status = ts('Recurring contribution was cancelled successfully by the processor, but could not be marked as cancelled in the database.');
299 }
300 else {
301 $status = ts('Recurring contribution could not be cancelled in the database.');
302 }
303 }
304 }
305 else {
306 $status = ts('The recurring contribution could not be cancelled.');
307 $msgTitle = 'Error Cancelling Contribution';
308 $msgType = 'error';
309 }
310
311 $session = CRM_Core_Session::singleton();
312 $userID = $session->get('userID');
313 if ($userID && $status) {
314 $session->setStatus($status, $msgTitle, $msgType);
315 }
316 elseif (!$userID) {
317 if ($status) {
318 CRM_Utils_System::setUFMessage($status);
319 // keep result as 1, since we not displaying anything on the redirected page anyway
320 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/subscriptionstatus',
321 "reset=1&task=cancel&result=1"));
322 }
323 }
324 }
325
326 }