Groups filter hack for smaller groups listings
[civicrm-core.git] / CRM / Contribute / Form / CancelSubscription.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035 11
d6ae85ac 12use Civi\Payment\PropertyBag;
32509f69 13use Civi\Payment\Exception\PaymentProcessorException;
6a488035
TO
14
15/**
95cdcc0f 16 * This class provides support for canceling recurring subscriptions.
6a488035 17 */
ca809bb6 18class CRM_Contribute_Form_CancelSubscription extends CRM_Contribute_Form_ContributionRecur {
6a488035 19
32509f69 20 protected $_userContext;
6a488035 21
32509f69 22 protected $_mode;
6a488035 23
d6ae85ac
MW
24 /**
25 * The contributor email
26 *
27 * @var string
28 */
29 protected $_donorEmail = '';
30
f1105edc 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
6a488035 44 /**
fe482240 45 * Set variables up before form is built.
503699d5 46 *
47 * @throws \CRM_Core_Exception
6a488035
TO
48 */
49 public function preProcess() {
1f17c8ef 50 parent::preProcess();
d947cfb5 51
dd793ad1
MW
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,
51c822c6 59 'selfService' => $this->isSelfService(),
dd793ad1
MW
60 ];
61
62 if ($this->_crid) {
6a488035 63 // Are we cancelling a recurring contribution that is linked to an auto-renew membership?
59545b08
MW
64 if ($this->getSubscriptionDetails()->membership_id) {
65 $this->_mid = $this->getSubscriptionDetails()->membership_id;
6a488035
TO
66 }
67 }
68
69 if ($this->_mid) {
6a488035 70 $this->_mode = 'auto_renew';
16381e37
J
71 // CRM-18468: crid is more accurate than mid for getting
72 // subscriptionDetails, so don't get them again.
6a488035
TO
73
74 $membershipTypes = CRM_Member_PseudoConstant::membershipType();
75 $membershipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_mid, 'membership_type_id');
dd793ad1
MW
76 $membershipType = $membershipTypes[$membershipTypeId] ?? '';
77 $this->assign('membershipType', $membershipType);
78 $cancelRecurTextParams['membershipType'] = $membershipType;
6a488035
TO
79 }
80
6a488035
TO
81 if ($this->_coid) {
82 if (CRM_Contribute_BAO_Contribution::isSubscriptionCancelled($this->_coid)) {
6a4a50a1 83 CRM_Core_Error::statusBounce(ts('The recurring contribution looks to have been cancelled already.'));
6a488035
TO
84 }
85 $this->_paymentProcessorObj = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'obj');
6a488035
TO
86 }
87
d947cfb5
DL
88 if (
89 (!$this->_crid && !$this->_coid && !$this->_mid) ||
59545b08 90 (!$this->getSubscriptionDetails())
6a488035 91 ) {
507bc932 92 CRM_Core_Error::statusBounce(ts('Required information missing.'));
6a488035
TO
93 }
94
dd793ad1
MW
95 $this->assign('cancelRecurDetailText', $this->_paymentProcessorObj->getText('cancelRecurDetailText', $cancelRecurTextParams));
96
6a488035
TO
97 // handle context redirection
98 CRM_Contribute_BAO_ContributionRecur::setSubscriptionContext();
99
7e2e2551 100 $this->setTitle($this->_mid ? ts('Cancel Auto-renewal') : ts('Cancel Recurring Contribution'));
6a488035
TO
101 $this->assign('mode', $this->_mode);
102
ca574dc9
EM
103 if ($this->isSelfService() || !$this->_paymentProcessorObj->supports('cancelRecurring')) {
104 // If we are self service (contact is cancelling for themselves via a cancel link)
105 // or the processor does not support cancellation then remove the fields
106 // specifying whether to notify the processor.
107 unset($this->entityFields['send_cancel_request']);
108 }
f1105edc 109 if ($this->isSelfService()) {
ca574dc9
EM
110 // Arguably the is_notify field should be removed in self-service mode.
111 // Historically this has been the case...
112 unset($this->entityFields['is_notify']);
f1105edc 113 }
114
59545b08 115 if ($this->getSubscriptionDetails()->contact_id) {
7c550ca0 116 list($this->_donorDisplayName, $this->_donorEmail)
59545b08 117 = CRM_Contact_BAO_Contact::getContactDetails($this->getSubscriptionDetails()->contact_id);
6a488035
TO
118 }
119 }
120
f1105edc 121 /**
122 * Set entity fields for this cancellation.
123 */
124 public function setEntityFields() {
125 $this->entityFields = [
126 'cancel_reason' => ['name' => 'cancel_reason'],
127 ];
128 $this->entityFields['send_cancel_request'] = [
703235f6 129 'title' => ts('Send cancellation request?'),
f1105edc 130 'name' => 'send_cancel_request',
131 'not-auto-addable' => TRUE,
132 ];
133 $this->entityFields['is_notify'] = [
134 'title' => ts('Notify Contributor?'),
135 'name' => 'is_notify',
136 'not-auto-addable' => TRUE,
137 ];
138 }
139
6a488035 140 /**
fe482240 141 * Build the form object.
6a488035
TO
142 */
143 public function buildQuickForm() {
f1105edc 144 $this->buildQuickEntityForm();
6a488035 145 // Determine if we can cancel recurring contribution via API with this processor
5077b04c 146 if ($this->_paymentProcessorObj->supports('CancelRecurringNotifyOptional')) {
39405208 147 $this->addRadio('send_cancel_request', ts('Send cancellation request to %1 ?', [1 => $this->_paymentProcessorObj->getTitle()]), [ts('No'), ts('Yes')]);
6a488035 148 }
dd793ad1
MW
149 else {
150 $this->assign('cancelRecurNotSupportedText', $this->_paymentProcessorObj->getText('cancelRecurNotSupportedText', []));
151 }
d947cfb5 152
d6ae85ac
MW
153 if (!empty($this->_donorEmail)) {
154 $this->add('checkbox', 'is_notify', ts('Notify Contributor?') . " ({$this->_donorEmail})");
6a488035
TO
155 }
156 if ($this->_mid) {
157 $cancelButton = ts('Cancel Automatic Membership Renewal');
158 }
159 else {
160 $cancelButton = ts('Cancel Recurring Contribution');
161 }
162
163 $type = 'next';
f1105edc 164 if ($this->isSelfService()) {
6a488035
TO
165 $type = 'submit';
166 }
167
be2fb01f 168 $this->addButtons([
1330f57a
SL
169 [
170 'type' => $type,
171 'name' => $cancelButton,
172 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
173 'isDefault' => TRUE,
174 ],
175 [
176 'type' => 'cancel',
177 'name' => ts('Not Now'),
178 ],
179 ]);
6a488035
TO
180 }
181
182 /**
1c4a09f4 183 * Set default values for the form.
6a488035 184 *
a6c01b45
CW
185 * @return array
186 * array of default values
6a488035 187 */
00be9182 188 public function setDefaultValues() {
be2fb01f 189 return [
1c4a09f4 190 'send_cancel_request' => 1,
be2fb01f 191 ];
6a488035
TO
192 }
193
194 /**
fe482240 195 * Process the form submission.
5077b04c 196 *
197 * @throws \CRM_Core_Exception
32509f69 198 * @throws \API_Exception
6a488035
TO
199 */
200 public function postProcess() {
11ec1f96 201 $message = NULL;
353ffa53 202 $params = $this->controller->exportValues($this->_name);
6a488035 203
f1105edc 204 if ($this->isSelfService()) {
6a488035 205 // for self service force sending-request & notify
1524a007 206 if ($this->_paymentProcessorObj->supports('cancelRecurring')) {
6a488035 207 $params['send_cancel_request'] = 1;
d947cfb5
DL
208 }
209
d6ae85ac 210 if (!empty($this->_donorEmail)) {
6a488035 211 $params['is_notify'] = 1;
d947cfb5 212 }
6a488035
TO
213 }
214
5077b04c 215 try {
216 $propertyBag = new PropertyBag();
363b20fa
MW
217 if (isset($params['send_cancel_request'])) {
218 $propertyBag->setIsNotifyProcessorOnCancelRecur(!empty($params['send_cancel_request']));
219 }
5077b04c 220 $propertyBag->setContributionRecurID($this->getSubscriptionDetails()->recur_id);
d0f696ac 221 $propertyBag->setRecurProcessorID($this->getSubscriptionDetails()->processor_id);
5077b04c 222 $message = $this->_paymentProcessorObj->doCancelRecurring($propertyBag)['message'];
223 }
32509f69 224 catch (PaymentProcessorException $e) {
5077b04c 225 CRM_Core_Error::statusBounce($e->getMessage());
6a488035
TO
226 }
227
32509f69 228 try {
229 civicrm_api3('ContributionRecur', 'cancel', [
230 'id' => $this->getSubscriptionDetails()->recur_id,
231 'membership_id' => $this->_mid,
232 'processor_message' => $message,
e73cf7de 233 'cancel_reason' => $this->getSubmittedValue('cancel_reason'),
32509f69 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';
6a488035 248 }
32509f69 249 else {
32509f69 250 $status = ts('The recurring contribution of %1, every %2 %3 has been cancelled.',
251 [
e589a77b
EM
252 1 => CRM_Utils_Money::format($this->getSubscriptionDetails()->amount, $this->getSubscriptionDetails()->currency),
253 2 => $this->getSubscriptionDetails()->frequency_interval,
254 3 => $this->getSubscriptionDetails()->frequency_unit,
32509f69 255 ]
256 );
257 $msgTitle = 'Contribution Cancelled';
258 $msgType = 'success';
259 }
260
261 if (CRM_Utils_Array::value('is_notify', $params) == 1) {
32509f69 262 // send notification
263 $sendTemplateParams
264 = [
265 'groupName' => $this->_mode == 'auto_renew' ? 'msg_tpl_workflow_membership' : 'msg_tpl_workflow_contribution',
266 'valueName' => $this->_mode == 'auto_renew' ? 'membership_autorenew_cancelled' : 'contribution_recurring_cancelled',
267 'contactId' => $this->getSubscriptionDetails()->contact_id,
268 'tplParams' => $tplParams,
e589a77b 269 'tokenContext' => ['contribution_recurId' => $this->getContributionRecurID()],
32509f69 270 //'isTest' => $isTest, set this from _objects
271 'PDFFilename' => 'receipt.pdf',
e73cf7de 272 'from' => CRM_Contribute_BAO_ContributionRecur::getRecurFromAddress($this->getContributionRecurID()),
32509f69 273 'toName' => $this->_donorDisplayName,
274 'toEmail' => $this->_donorEmail,
275 ];
276 list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
6a488035
TO
277 }
278 }
32509f69 279 catch (CiviCRM_API3_Exception $e) {
6a488035 280 $msgType = 'error';
32509f69 281 $msgTitle = ts('Error');
282 if ($params['send_cancel_request'] == 1) {
283 $status = ts('Recurring contribution was cancelled successfully by the processor, but could not be marked as cancelled in the database.');
284 }
285 else {
286 $status = ts('Recurring contribution could not be cancelled in the database.');
287 }
6a488035
TO
288 }
289
32509f69 290 $userID = CRM_Core_Session::getLoggedInContactID();
481a74f4 291 if ($userID && $status) {
32509f69 292 CRM_Core_Session::singleton()->setStatus($status, $msgTitle, $msgType);
6a488035
TO
293 }
294 elseif (!$userID) {
7c550ca0 295 if ($status) {
6a488035 296 CRM_Utils_System::setUFMessage($status);
7c550ca0 297 // keep result as 1, since we not displaying anything on the redirected page anyway
32509f69 298 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/subscriptionstatus',
299 'reset=1&task=cancel&result=1'));
7c550ca0 300 }
6a488035
TO
301 }
302 }
96025800 303
6a488035 304}