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