Fix payment instrument bug by using correct payment instrument
[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;
6a488035
TO
13
14/**
95cdcc0f 15 * This class provides support for canceling recurring subscriptions.
6a488035 16 */
ca809bb6 17class CRM_Contribute_Form_CancelSubscription extends CRM_Contribute_Form_ContributionRecur {
6a488035
TO
18
19 protected $_userContext = NULL;
20
21 protected $_mode = NULL;
22
d6ae85ac
MW
23 /**
24 * The contributor email
25 *
26 * @var string
27 */
28 protected $_donorEmail = '';
29
f1105edc 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
6a488035 43 /**
fe482240 44 * Set variables up before form is built.
503699d5 45 *
46 * @throws \CRM_Core_Exception
6a488035
TO
47 */
48 public function preProcess() {
1f17c8ef 49 parent::preProcess();
d947cfb5 50
dd793ad1
MW
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) {
6a488035 61 // Are we cancelling a recurring contribution that is linked to an auto-renew membership?
59545b08
MW
62 if ($this->getSubscriptionDetails()->membership_id) {
63 $this->_mid = $this->getSubscriptionDetails()->membership_id;
6a488035
TO
64 }
65 }
66
67 if ($this->_mid) {
6a488035 68 $this->_mode = 'auto_renew';
16381e37
J
69 // CRM-18468: crid is more accurate than mid for getting
70 // subscriptionDetails, so don't get them again.
6a488035
TO
71
72 $membershipTypes = CRM_Member_PseudoConstant::membershipType();
73 $membershipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_mid, 'membership_type_id');
dd793ad1
MW
74 $membershipType = $membershipTypes[$membershipTypeId] ?? '';
75 $this->assign('membershipType', $membershipType);
76 $cancelRecurTextParams['membershipType'] = $membershipType;
6a488035
TO
77 }
78
6a488035
TO
79 if ($this->_coid) {
80 if (CRM_Contribute_BAO_Contribution::isSubscriptionCancelled($this->_coid)) {
6a4a50a1 81 CRM_Core_Error::statusBounce(ts('The recurring contribution looks to have been cancelled already.'));
6a488035
TO
82 }
83 $this->_paymentProcessorObj = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'obj');
6a488035
TO
84 }
85
d947cfb5
DL
86 if (
87 (!$this->_crid && !$this->_coid && !$this->_mid) ||
59545b08 88 (!$this->getSubscriptionDetails())
6a488035 89 ) {
f1105edc 90 CRM_Core_Error::statusBounce('Required information missing.');
6a488035
TO
91 }
92
dd793ad1
MW
93 $this->assign('cancelRecurDetailText', $this->_paymentProcessorObj->getText('cancelRecurDetailText', $cancelRecurTextParams));
94
6a488035
TO
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
f1105edc 101 if ($this->isSelfService()) {
102 unset($this->entityFields['send_cancel_request'], $this->entityFields['is_notify']);
103 }
104
59545b08 105 if ($this->getSubscriptionDetails()->contact_id) {
7c550ca0 106 list($this->_donorDisplayName, $this->_donorEmail)
59545b08 107 = CRM_Contact_BAO_Contact::getContactDetails($this->getSubscriptionDetails()->contact_id);
6a488035
TO
108 }
109 }
110
f1105edc 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'] = [
703235f6 119 'title' => ts('Send cancellation request?'),
f1105edc 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
6a488035 130 /**
fe482240 131 * Build the form object.
6a488035
TO
132 */
133 public function buildQuickForm() {
f1105edc 134 $this->buildQuickEntityForm();
6a488035 135 // Determine if we can cancel recurring contribution via API with this processor
5077b04c 136 if ($this->_paymentProcessorObj->supports('CancelRecurringNotifyOptional')) {
be2fb01f 137 $searchRange = [];
6a488035
TO
138 $searchRange[] = $this->createElement('radio', NULL, NULL, ts('Yes'), '1');
139 $searchRange[] = $this->createElement('radio', NULL, NULL, ts('No'), '0');
140
d947cfb5
DL
141 $this->addGroup(
142 $searchRange,
143 'send_cancel_request',
144 ts('Send cancellation request to %1 ?',
4e0ebeee 145 [1 => $this->_paymentProcessorObj->getTitle()])
d947cfb5 146 );
6a488035 147 }
dd793ad1
MW
148 else {
149 $this->assign('cancelRecurNotSupportedText', $this->_paymentProcessorObj->getText('cancelRecurNotSupportedText', []));
150 }
d947cfb5 151
d6ae85ac
MW
152 if (!empty($this->_donorEmail)) {
153 $this->add('checkbox', 'is_notify', ts('Notify Contributor?') . " ({$this->_donorEmail})");
6a488035
TO
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';
f1105edc 163 if ($this->isSelfService()) {
6a488035
TO
164 $type = 'submit';
165 }
166
be2fb01f 167 $this->addButtons([
1330f57a
SL
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 ]);
6a488035
TO
179 }
180
181 /**
1c4a09f4 182 * Set default values for the form.
6a488035 183 *
a6c01b45
CW
184 * @return array
185 * array of default values
6a488035 186 */
00be9182 187 public function setDefaultValues() {
be2fb01f 188 return [
1c4a09f4 189 'is_notify' => 1,
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
6a488035
TO
198 */
199 public function postProcess() {
11ec1f96 200 $message = NULL;
6a488035 201 $cancelSubscription = TRUE;
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 }
224 catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
225 CRM_Core_Error::statusBounce($e->getMessage());
6a488035
TO
226 }
227
11ec1f96 228 if ($cancelSubscription) {
c7d9325a 229 try {
230 civicrm_api3('ContributionRecur', 'cancel', [
59545b08 231 'id' => $this->getSubscriptionDetails()->recur_id,
c7d9325a 232 'membership_id' => $this->_mid,
233 'processor_message' => $message,
f1105edc 234 'cancel_reason' => $params['cancel_reason'],
c7d9325a 235 ]);
d947cfb5 236
be2fb01f 237 $tplParams = [];
6a488035 238 if ($this->_mid) {
be2fb01f 239 $inputParams = ['id' => $this->_mid];
6a488035
TO
240 CRM_Member_BAO_Membership::getValues($inputParams, $tplParams);
241 $tplParams = $tplParams[$this->_mid];
7c550ca0
WA
242 $tplParams['membership_status']
243 = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $tplParams['status_id']);
244 $tplParams['membershipType']
245 = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $tplParams['membership_type_id']);
be2fb01f 246 $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']]);
6a488035
TO
247 $msgTitle = 'Membership Renewal Cancelled';
248 $msgType = 'info';
249 }
250 else {
59545b08
MW
251 $tplParams['recur_frequency_interval'] = $this->getSubscriptionDetails()->frequency_interval;
252 $tplParams['recur_frequency_unit'] = $this->getSubscriptionDetails()->frequency_unit;
dd793ad1 253 $tplParams['amount'] = CRM_Utils_Money::format($this->getSubscriptionDetails()->amount, $this->getSubscriptionDetails()->currency);
be2fb01f 254 $tplParams['contact'] = ['display_name' => $this->_donorDisplayName];
6a488035 255 $status = ts('The recurring contribution of %1, every %2 %3 has been cancelled.',
be2fb01f 256 [
dd793ad1
MW
257 1 => $tplParams['amount'],
258 2 => $tplParams['recur_frequency_interval'],
259 3 => $tplParams['recur_frequency_unit'],
be2fb01f 260 ]
6a488035
TO
261 );
262 $msgTitle = 'Contribution Cancelled';
263 $msgType = 'success';
264 }
265
266 if (CRM_Utils_Array::value('is_notify', $params) == 1) {
59545b08 267 if ($this->getSubscriptionDetails()->contribution_page_id) {
d947cfb5
DL
268 CRM_Core_DAO::commonRetrieveAll(
269 'CRM_Contribute_DAO_ContributionPage',
270 'id',
59545b08 271 $this->getSubscriptionDetails()->contribution_page_id,
d947cfb5 272 $value,
be2fb01f 273 ['title', 'receipt_from_name', 'receipt_from_email']
d947cfb5 274 );
7c550ca0 275 $receiptFrom
59545b08 276 = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$this->getSubscriptionDetails()->contribution_page_id]) .
d947cfb5 277 '" <' .
59545b08 278 $value[$this->getSubscriptionDetails()->contribution_page_id]['receipt_from_email'] .
d947cfb5 279 '>';
6a488035
TO
280 }
281 else {
282 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
283 $receiptFrom = "$domainValues[0] <$domainValues[1]>";
284 }
d947cfb5 285
6a488035 286 // send notification
7c550ca0 287 $sendTemplateParams
be2fb01f 288 = [
353ffa53
TO
289 'groupName' => $this->_mode == 'auto_renew' ? 'msg_tpl_workflow_membership' : 'msg_tpl_workflow_contribution',
290 'valueName' => $this->_mode == 'auto_renew' ? 'membership_autorenew_cancelled' : 'contribution_recurring_cancelled',
59545b08 291 'contactId' => $this->getSubscriptionDetails()->contact_id,
353ffa53
TO
292 'tplParams' => $tplParams,
293 //'isTest' => $isTest, set this from _objects
294 'PDFFilename' => 'receipt.pdf',
295 'from' => $receiptFrom,
296 'toName' => $this->_donorDisplayName,
297 'toEmail' => $this->_donorEmail,
be2fb01f 298 ];
c6327d7d 299 list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
6a488035
TO
300 }
301 }
c7d9325a 302 catch (CiviCRM_API3_Exception $e) {
6a488035
TO
303 $msgType = 'error';
304 $msgTitle = ts('Error');
305 if ($params['send_cancel_request'] == 1) {
306 $status = ts('Recurring contribution was cancelled successfully by the processor, but could not be marked as cancelled in the database.');
307 }
308 else {
309 $status = ts('Recurring contribution could not be cancelled in the database.');
310 }
311 }
312 }
313 else {
314 $status = ts('The recurring contribution could not be cancelled.');
315 $msgTitle = 'Error Cancelling Contribution';
316 $msgType = 'error';
317 }
318
319 $session = CRM_Core_Session::singleton();
353ffa53 320 $userID = $session->get('userID');
481a74f4 321 if ($userID && $status) {
6a488035
TO
322 $session->setStatus($status, $msgTitle, $msgType);
323 }
324 elseif (!$userID) {
7c550ca0 325 if ($status) {
6a488035 326 CRM_Utils_System::setUFMessage($status);
7c550ca0
WA
327 // keep result as 1, since we not displaying anything on the redirected page anyway
328 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/subscriptionstatus',
353ffa53 329 "reset=1&task=cancel&result=1"));
7c550ca0 330 }
6a488035
TO
331 }
332 }
96025800 333
6a488035 334}