Merge pull request #11050 from eileenmcnaughton/cache
[civicrm-core.git] / CRM / Contribute / Form / UpdateSubscription.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
0f03f337 6 | Copyright CiviCRM LLC (c) 2004-2017 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
6a488035 29 * @package CRM
0f03f337 30 * @copyright CiviCRM LLC (c) 2004-2017
6a488035
TO
31 */
32
33/**
c0f62075 34 * This class generates form components generic to recurring contributions.
6a488035
TO
35 *
36 * It delegates the work to lower level subclasses and integrates the changes
37 * back in. It also uses a lot of functionality with the CRM API's, so any change
38 * made here could potentially affect the API etc. Be careful, be aware, use unit tests.
6a488035
TO
39 */
40class CRM_Contribute_Form_UpdateSubscription extends CRM_Core_Form {
41
42 /**
0c6c47a5 43 * The recurring contribution id, used when editing the recurring contribution.
6a488035
TO
44 *
45 * @var int
46 */
0c6c47a5 47 protected $contributionRecurID = NULL;
6a488035
TO
48
49 protected $_coid = NULL;
50
51 protected $_subscriptionDetails = NULL;
52
53 protected $_selfService = FALSE;
54
55 public $_paymentProcessor = NULL;
56
57 public $_paymentProcessorObj = NULL;
58
0c6c47a5 59 /**
60 * Fields that affect the schedule and are defined as editable by the processor.
61 *
62 * @var array
63 */
64 protected $editableScheduleFields = array();
65
6a488035 66 /**
fe482240 67 * The id of the contact associated with this recurring contribution.
6a488035
TO
68 *
69 * @var int
6a488035 70 */
430ae6dd
TO
71 public $_contactID;
72
c0f62075 73 /**
74 * Pre-processing for the form.
75 *
76 * @throws \Exception
77 */
00be9182 78 public function preProcess() {
6a488035 79
a0d322b1
KW
80 $this->setAction(CRM_Core_Action::UPDATE);
81
0c6c47a5 82 $this->contributionRecurID = CRM_Utils_Request::retrieve('crid', 'Integer', $this, FALSE);
83 if ($this->contributionRecurID) {
b3e340d9 84 try {
cd3ad80e 85 $this->_paymentProcessorObj = CRM_Financial_BAO_PaymentProcessor::getPaymentProcessorForRecurringContribution($this->contributionRecurID);
b3e340d9 86 }
87 catch (CRM_Core_Exception $e) {
0c6c47a5 88 CRM_Core_Error::statusBounce(ts('There is no valid processor for this subscription so it cannot be edited.'));
89 }
0c6c47a5 90 $this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->contributionRecurID);
6a488035
TO
91 }
92
93 $this->_coid = CRM_Utils_Request::retrieve('coid', 'Integer', $this, FALSE);
94 if ($this->_coid) {
95 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'info');
cd3ad80e 96 // @todo test & replace with $this->_paymentProcessorObj = Civi\Payment\System::singleton()->getById($this->_paymentProcessor['id']);
6a488035
TO
97 $this->_paymentProcessorObj = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'obj');
98 $this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_coid, 'contribution');
0c6c47a5 99 $this->contributionRecurID = $this->_subscriptionDetails->recur_id;
6a488035 100 }
0c6c47a5 101 elseif ($this->contributionRecurID) {
102 $this->_coid = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $this->contributionRecurID, 'id', 'contribution_recur_id');
8de2c073 103 }
6a488035 104
1273d77c 105 if (!$this->contributionRecurID || !$this->_subscriptionDetails) {
7bcd892a 106 CRM_Core_Error::statusBounce(ts('Required information missing.'));
6a488035
TO
107 }
108
109 if ($this->_subscriptionDetails->membership_id && $this->_subscriptionDetails->auto_renew) {
7bcd892a 110 CRM_Core_Error::statusBounce(ts('You cannot update the subscription.'));
6a488035
TO
111 }
112
113 if (!CRM_Core_Permission::check('edit contributions')) {
114 $userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this, FALSE);
115 if (!CRM_Contact_BAO_Contact_Utils::validChecksum($this->_subscriptionDetails->contact_id, $userChecksum)) {
7bcd892a 116 CRM_Core_Error::statusBounce(ts('You do not have permission to update subscription.'));
6a488035
TO
117 }
118 $this->_selfService = TRUE;
119 }
120 $this->assign('self_service', $this->_selfService);
121
0c6c47a5 122 $this->editableScheduleFields = $this->_paymentProcessorObj->getEditableRecurringScheduleFields();
123
124 $changeHelpText = $this->_paymentProcessorObj->getRecurringScheduleUpdateHelpText();
125 if (!in_array('amount', $this->editableScheduleFields)) {
126 // Not sure if this is good behaviour - maintaining this existing behaviour for now.
127 CRM_Core_Session::setStatus($changeHelpText, ts('Warning'), 'alert');
128 }
129 else {
130 $this->assign('changeHelpText', $changeHelpText);
131 }
132 $alreadyHardCodedFields = array('amount', 'installments');
133 foreach ($this->editableScheduleFields as $editableScheduleField) {
134 if (!in_array($editableScheduleField, $alreadyHardCodedFields)) {
95d72a5f 135 $this->addField($editableScheduleField, array('entity' => 'ContributionRecur'));
0c6c47a5 136 }
6a488035
TO
137 }
138
0c6c47a5 139 $this->assign('editableScheduleFields', array_diff($this->editableScheduleFields, $alreadyHardCodedFields));
6a488035
TO
140
141 if ($this->_subscriptionDetails->contact_id) {
142 list($this->_donorDisplayName, $this->_donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_subscriptionDetails->contact_id);
143 }
144
145 CRM_Utils_System::setTitle(ts('Update Recurring Contribution'));
146
0c6c47a5 147 // Handle context redirection.
6a488035
TO
148 CRM_Contribute_BAO_ContributionRecur::setSubscriptionContext();
149 }
150
151 /**
347e061b 152 * Set default values for the form.
6a488035 153 *
347e061b 154 * Note that in edit/view mode the default values are retrieved from the database.
6a488035 155 */
00be9182 156 public function setDefaultValues() {
6a488035
TO
157 $this->_defaults = array();
158 $this->_defaults['amount'] = $this->_subscriptionDetails->amount;
159 $this->_defaults['installments'] = $this->_subscriptionDetails->installments;
7083dc2a 160 $this->_defaults['campaign_id'] = $this->_subscriptionDetails->campaign_id;
467fe956 161 $this->_defaults['financial_type_id'] = $this->_subscriptionDetails->financial_type_id;
6a488035 162 $this->_defaults['is_notify'] = 1;
0c6c47a5 163 foreach ($this->editableScheduleFields as $field) {
164 $this->_defaults[$field] = $this->_subscriptionDetails->$field;
165 }
6a488035
TO
166
167 return $this->_defaults;
168 }
169
170 /**
fe482240 171 * Actually build the components of the form.
6a488035
TO
172 */
173 public function buildQuickForm() {
8de2c073 174 // CRM-16398: If current recurring contribution got > 1 lineitems then make amount field readonly
175 $amtAttr = array('size' => 20);
176 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($this->_coid);
177 if (count($lineItems) > 1) {
178 $amtAttr += array('readonly' => TRUE);
179 }
180 $this->addMoney('amount', ts('Recurring Contribution Amount'), TRUE, $amtAttr,
181 TRUE, 'currency', $this->_subscriptionDetails->currency, TRUE
6a488035
TO
182 );
183
467fe956 184 $this->add('text', 'installments', ts('Number of Installments'), array('size' => 20), FALSE);
6a488035
TO
185
186 if ($this->_donorEmail) {
187 $this->add('checkbox', 'is_notify', ts('Notify Contributor?'));
188 }
189
7083dc2a 190 if (CRM_Core_Permission::check('edit contributions')) {
edb227cd 191 CRM_Campaign_BAO_Campaign::addCampaign($this, $this->_subscriptionDetails->campaign_id);
467fe956 192 }
193
0c6c47a5 194 if (CRM_Contribute_BAO_ContributionRecur::supportsFinancialTypeChange($this->contributionRecurID)) {
0d93f90b 195 $this->addEntityRef('financial_type_id', ts('Financial Type'), array('entity' => 'FinancialType'), !$this->_selfService);
7083dc2a 196 }
197
6a488035 198 $type = 'next';
481a74f4 199 if ($this->_selfService) {
6a488035
TO
200 $type = 'submit';
201 }
202
203 // define the buttons
204 $this->addButtons(array(
205 array(
206 'type' => $type,
207 'name' => ts('Save'),
208 'isDefault' => TRUE,
209 ),
210 array(
211 'type' => 'cancel',
212 'name' => ts('Cancel'),
213 ),
214 )
215 );
216 }
217
218 /**
347e061b 219 * Called after the user submits the form.
6a488035
TO
220 */
221 public function postProcess() {
222 // store the submitted values in an array
223 $params = $this->exportValues();
224
225 if ($this->_selfService && $this->_donorEmail) {
226 // for self service force notify
227 $params['is_notify'] = 1;
228 }
229
230 // if this is an update of an existing recurring contribution, pass the ID
231 $params['id'] = $this->_subscriptionDetails->recur_id;
232 $message = '';
233
234 $params['subscriptionId'] = $this->_subscriptionDetails->subscription_id;
4eeb9a5b 235 $updateSubscription = TRUE;
6a488035 236 if ($this->_paymentProcessorObj->isSupported('changeSubscriptionAmount')) {
353ffa53 237 $updateSubscription = $this->_paymentProcessorObj->changeSubscriptionAmount($message, $params);
6a488035
TO
238 }
239 if (is_a($updateSubscription, 'CRM_Core_Error')) {
353ffa53
TO
240 CRM_Core_Error::displaySessionError($updateSubscription);
241 $status = ts('Could not update the Recurring contribution details');
242 $msgTitle = ts('Update Error');
243 $msgType = 'error';
6a488035
TO
244 }
245 elseif ($updateSubscription) {
353ffa53
TO
246 // save the changes
247 $result = CRM_Contribute_BAO_ContributionRecur::add($params);
248 $status = ts('Recurring contribution has been updated to: %1, every %2 %3(s) for %4 installments.',
249 array(
250 1 => CRM_Utils_Money::format($params['amount'], $this->_subscriptionDetails->currency),
251 2 => $this->_subscriptionDetails->frequency_interval,
252 3 => $this->_subscriptionDetails->frequency_unit,
253 4 => $params['installments'],
254 )
255 );
256
257 $msgTitle = ts('Update Success');
258 $msgType = 'success';
c6c91efc 259 $msg = ts('Recurring Contribution Updated');
353ffa53
TO
260 $contactID = $this->_subscriptionDetails->contact_id;
261
262 if ($this->_subscriptionDetails->amount != $params['amount']) {
263 $message .= "<br /> " . ts("Recurring contribution amount has been updated from %1 to %2 for this subscription.",
264 array(
265 1 => CRM_Utils_Money::format($this->_subscriptionDetails->amount, $this->_subscriptionDetails->currency),
266 2 => CRM_Utils_Money::format($params['amount'], $this->_subscriptionDetails->currency),
267 )) . ' ';
c6c91efc 268 if ($this->_subscriptionDetails->amount < $params['amount']) {
269 $msg = ts('Recurring Contribution Updated - increased installment amount');
270 }
271 else {
272 $msg = ts('Recurring Contribution Updated - decreased installment amount');
273 }
353ffa53 274 }
6a488035 275
353ffa53
TO
276 if ($this->_subscriptionDetails->installments != $params['installments']) {
277 $message .= "<br /> " . ts("Recurring contribution installments have been updated from %1 to %2 for this subscription.", array(
278 1 => $this->_subscriptionDetails->installments,
317fceb4 279 2 => $params['installments'],
353ffa53
TO
280 )) . ' ';
281 }
6a488035 282
353ffa53
TO
283 $activityParams = array(
284 'source_contact_id' => $contactID,
12853dec 285 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Update Recurring Contribution'),
c6c91efc 286 'subject' => $msg,
353ffa53
TO
287 'details' => $message,
288 'activity_date_time' => date('YmdHis'),
12853dec 289 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
353ffa53 290 );
12853dec 291
353ffa53
TO
292 $session = CRM_Core_Session::singleton();
293 $cid = $session->get('userID');
6a488035 294
353ffa53
TO
295 if ($cid) {
296 $activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
297 $activityParams['source_contact_id'] = $cid;
298 }
299 CRM_Activity_BAO_Activity::create($activityParams);
300
301 if (!empty($params['is_notify'])) {
302 // send notification
303 if ($this->_subscriptionDetails->contribution_page_id) {
304 CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_ContributionPage', 'id',
305 $this->_subscriptionDetails->contribution_page_id, $value, array(
306 'title',
307 'receipt_from_name',
308 'receipt_from_email',
309 )
6a488035 310 );
353ffa53
TO
311 $receiptFrom = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$this->_subscriptionDetails->contribution_page_id]) . '" <' . $value[$this->_subscriptionDetails->contribution_page_id]['receipt_from_email'] . '>';
312 }
313 else {
314 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
315 $receiptFrom = "$domainValues[0] <$domainValues[1]>";
6a488035 316 }
353ffa53
TO
317
318 list($donorDisplayName, $donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
319
320 $tplParams = array(
321 'recur_frequency_interval' => $this->_subscriptionDetails->frequency_interval,
322 'recur_frequency_unit' => $this->_subscriptionDetails->frequency_unit,
323 'amount' => CRM_Utils_Money::format($params['amount']),
324 'installments' => $params['installments'],
325 );
326
327 $tplParams['contact'] = array('display_name' => $donorDisplayName);
328 $tplParams['receipt_from_email'] = $receiptFrom;
329
330 $sendTemplateParams = array(
331 'groupName' => 'msg_tpl_workflow_contribution',
332 'valueName' => 'contribution_recurring_edit',
333 'contactId' => $contactID,
334 'tplParams' => $tplParams,
335 'isTest' => $this->_subscriptionDetails->is_test,
336 'PDFFilename' => 'receipt.pdf',
337 'from' => $receiptFrom,
338 'toName' => $donorDisplayName,
339 'toEmail' => $donorEmail,
340 );
341 list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
6a488035 342 }
353ffa53 343 }
6a488035
TO
344
345 $session = CRM_Core_Session::singleton();
353ffa53 346 $userID = $session->get('userID');
481a74f4 347 if ($userID && $status) {
6a488035 348 CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
0db6c3e1 349 }
4c9b6178 350 elseif (!$userID) {
317fceb4 351 if ($status) {
6a488035 352 CRM_Utils_System::setUFMessage($status);
317fceb4 353 }
6a488035
TO
354 // keep result as 1, since we not displaying anything on the redirected page anyway
355 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/subscriptionstatus',
353ffa53 356 "reset=1&task=update&result=1"));
6a488035
TO
357 }
358 }
96025800 359
0c6c47a5 360 /**
361 * Explicitly declare the form context.
362 */
363 public function getDefaultContext() {
364 return 'create';
365 }
366
6a488035 367}