[REF] Refactor to use the standard CRM_Core_Form::addRadio function for a number...
[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 use Civi\Payment\Exception\PaymentProcessorException;
14
15 /**
16 * This class provides support for canceling recurring subscriptions.
17 */
18 class CRM_Contribute_Form_CancelSubscription extends CRM_Contribute_Form_ContributionRecur {
19
20 protected $_userContext;
21
22 protected $_mode;
23
24 /**
25 * The contributor email
26 *
27 * @var string
28 */
29 protected $_donorEmail = '';
30
31 /**
32 * Should custom data be suppressed on this form.
33 *
34 * We override to suppress custom data because historically it has not been
35 * shown on this form & we don't want to expose it as a by-product of
36 * other change without establishing that it would be good on this form.
37 *
38 * @return bool
39 */
40 protected function isSuppressCustomData() {
41 return TRUE;
42 }
43
44 /**
45 * Set variables up before form is built.
46 *
47 * @throws \CRM_Core_Exception
48 */
49 public function preProcess() {
50 parent::preProcess();
51
52 $cancelRecurTextParams = [
53 'mode' => $this->_mode,
54 'amount' => $this->getSubscriptionDetails()->amount,
55 'currency' => $this->getSubscriptionDetails()->currency,
56 'frequency_interval' => $this->getSubscriptionDetails()->frequency_interval,
57 'frequency_unit' => $this->getSubscriptionDetails()->frequency_unit,
58 'installments' => $this->getSubscriptionDetails()->installments,
59 'selfService' => $this->isSelfService(),
60 ];
61
62 if ($this->_crid) {
63 // Are we cancelling a recurring contribution that is linked to an auto-renew membership?
64 if ($this->getSubscriptionDetails()->membership_id) {
65 $this->_mid = $this->getSubscriptionDetails()->membership_id;
66 }
67 }
68
69 if ($this->_mid) {
70 $this->_mode = 'auto_renew';
71 // CRM-18468: crid is more accurate than mid for getting
72 // subscriptionDetails, so don't get them again.
73
74 $membershipTypes = CRM_Member_PseudoConstant::membershipType();
75 $membershipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_mid, 'membership_type_id');
76 $membershipType = $membershipTypes[$membershipTypeId] ?? '';
77 $this->assign('membershipType', $membershipType);
78 $cancelRecurTextParams['membershipType'] = $membershipType;
79 }
80
81 if ($this->_coid) {
82 if (CRM_Contribute_BAO_Contribution::isSubscriptionCancelled($this->_coid)) {
83 CRM_Core_Error::statusBounce(ts('The recurring contribution looks to have been cancelled already.'));
84 }
85 $this->_paymentProcessorObj = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'obj');
86 }
87
88 if (
89 (!$this->_crid && !$this->_coid && !$this->_mid) ||
90 (!$this->getSubscriptionDetails())
91 ) {
92 CRM_Core_Error::statusBounce('Required information missing.');
93 }
94
95 $this->assign('cancelRecurDetailText', $this->_paymentProcessorObj->getText('cancelRecurDetailText', $cancelRecurTextParams));
96
97 // handle context redirection
98 CRM_Contribute_BAO_ContributionRecur::setSubscriptionContext();
99
100 CRM_Utils_System::setTitle($this->_mid ? ts('Cancel Auto-renewal') : ts('Cancel Recurring Contribution'));
101 $this->assign('mode', $this->_mode);
102
103 if ($this->isSelfService()) {
104 unset($this->entityFields['send_cancel_request'], $this->entityFields['is_notify']);
105 }
106
107 if ($this->getSubscriptionDetails()->contact_id) {
108 list($this->_donorDisplayName, $this->_donorEmail)
109 = CRM_Contact_BAO_Contact::getContactDetails($this->getSubscriptionDetails()->contact_id);
110 }
111 }
112
113 /**
114 * Set entity fields for this cancellation.
115 */
116 public function setEntityFields() {
117 $this->entityFields = [
118 'cancel_reason' => ['name' => 'cancel_reason'],
119 ];
120 $this->entityFields['send_cancel_request'] = [
121 'title' => ts('Send cancellation request?'),
122 'name' => 'send_cancel_request',
123 'not-auto-addable' => TRUE,
124 ];
125 $this->entityFields['is_notify'] = [
126 'title' => ts('Notify Contributor?'),
127 'name' => 'is_notify',
128 'not-auto-addable' => TRUE,
129 ];
130 }
131
132 /**
133 * Build the form object.
134 */
135 public function buildQuickForm() {
136 $this->buildQuickEntityForm();
137 // Determine if we can cancel recurring contribution via API with this processor
138 if ($this->_paymentProcessorObj->supports('CancelRecurringNotifyOptional')) {
139 $this->addRadio('send_cancel_request', ts('Send cancellation request to %1 ?', [1 => $this->_paymentProcessorObj->getTitle()]), [ts('No'), ts('Yes')]);
140 }
141 else {
142 $this->assign('cancelRecurNotSupportedText', $this->_paymentProcessorObj->getText('cancelRecurNotSupportedText', []));
143 }
144
145 if (!empty($this->_donorEmail)) {
146 $this->add('checkbox', 'is_notify', ts('Notify Contributor?') . " ({$this->_donorEmail})");
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';
156 if ($this->isSelfService()) {
157 $type = 'submit';
158 }
159
160 $this->addButtons([
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 ]);
172 }
173
174 /**
175 * Set default values for the form.
176 *
177 * @return array
178 * array of default values
179 */
180 public function setDefaultValues() {
181 return [
182 'is_notify' => 1,
183 'send_cancel_request' => 1,
184 ];
185 }
186
187 /**
188 * Process the form submission.
189 *
190 * @throws \CRM_Core_Exception
191 * @throws \API_Exception
192 */
193 public function postProcess() {
194 $message = NULL;
195 $params = $this->controller->exportValues($this->_name);
196
197 if ($this->isSelfService()) {
198 // for self service force sending-request & notify
199 if ($this->_paymentProcessorObj->supports('cancelRecurring')) {
200 $params['send_cancel_request'] = 1;
201 }
202
203 if (!empty($this->_donorEmail)) {
204 $params['is_notify'] = 1;
205 }
206 }
207
208 try {
209 $propertyBag = new PropertyBag();
210 if (isset($params['send_cancel_request'])) {
211 $propertyBag->setIsNotifyProcessorOnCancelRecur(!empty($params['send_cancel_request']));
212 }
213 $propertyBag->setContributionRecurID($this->getSubscriptionDetails()->recur_id);
214 $propertyBag->setRecurProcessorID($this->getSubscriptionDetails()->processor_id);
215 $message = $this->_paymentProcessorObj->doCancelRecurring($propertyBag)['message'];
216 }
217 catch (PaymentProcessorException $e) {
218 CRM_Core_Error::statusBounce($e->getMessage());
219 }
220
221 try {
222 civicrm_api3('ContributionRecur', 'cancel', [
223 'id' => $this->getSubscriptionDetails()->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->getSubscriptionDetails()->frequency_interval;
244 $tplParams['recur_frequency_unit'] = $this->getSubscriptionDetails()->frequency_unit;
245 $tplParams['amount'] = CRM_Utils_Money::format($this->getSubscriptionDetails()->amount, $this->getSubscriptionDetails()->currency);
246 $tplParams['contact'] = ['display_name' => $this->_donorDisplayName];
247 $status = ts('The recurring contribution of %1, every %2 %3 has been cancelled.',
248 [
249 1 => $tplParams['amount'],
250 2 => $tplParams['recur_frequency_interval'],
251 3 => $tplParams['recur_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->getSubscriptionDetails()->contribution_page_id) {
260 CRM_Core_DAO::commonRetrieveAll(
261 'CRM_Contribute_DAO_ContributionPage',
262 'id',
263 $this->getSubscriptionDetails()->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->getSubscriptionDetails()->contribution_page_id]) .
269 '" <' .
270 $value[$this->getSubscriptionDetails()->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->getSubscriptionDetails()->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 $userID = CRM_Core_Session::getLoggedInContactID();
306 if ($userID && $status) {
307 CRM_Core_Session::singleton()->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 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/subscriptionstatus',
314 'reset=1&task=cancel&result=1'));
315 }
316 }
317 }
318
319 }