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