Merge pull request #11986 from eileenmcnaughton/test
[civicrm-core.git] / CRM / Contribute / Form / UpdateSubscription.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 * @package CRM
30 * @copyright CiviCRM LLC (c) 2004-2018
31 */
32
33 /**
34 * This class generates form components generic to recurring contributions.
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.
39 */
40 class CRM_Contribute_Form_UpdateSubscription extends CRM_Core_Form {
41
42 /**
43 * The recurring contribution id, used when editing the recurring contribution.
44 *
45 * @var int
46 */
47 protected $contributionRecurID = NULL;
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
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
66 /**
67 * The id of the contact associated with this recurring contribution.
68 *
69 * @var int
70 */
71 public $_contactID;
72
73 /**
74 * Pre-processing for the form.
75 *
76 * @throws \Exception
77 */
78 public function preProcess() {
79
80 $this->setAction(CRM_Core_Action::UPDATE);
81
82 $this->contributionRecurID = CRM_Utils_Request::retrieve('crid', 'Integer', $this, FALSE);
83 if ($this->contributionRecurID) {
84 try {
85 $this->_paymentProcessorObj = CRM_Financial_BAO_PaymentProcessor::getPaymentProcessorForRecurringContribution($this->contributionRecurID);
86 }
87 catch (CRM_Core_Exception $e) {
88 CRM_Core_Error::statusBounce(ts('There is no valid processor for this subscription so it cannot be edited.'));
89 }
90 $this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->contributionRecurID);
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');
96 // @todo test & replace with $this->_paymentProcessorObj = Civi\Payment\System::singleton()->getById($this->_paymentProcessor['id']);
97 $this->_paymentProcessorObj = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'obj');
98 $this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_coid, 'contribution');
99 $this->contributionRecurID = $this->_subscriptionDetails->recur_id;
100 }
101 elseif ($this->contributionRecurID) {
102 $this->_coid = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $this->contributionRecurID, 'id', 'contribution_recur_id');
103 }
104
105 if (!$this->contributionRecurID || !$this->_subscriptionDetails) {
106 CRM_Core_Error::statusBounce(ts('Required information missing.'));
107 }
108
109 if ($this->_subscriptionDetails->membership_id && $this->_subscriptionDetails->auto_renew) {
110 // Add Membership details to form
111 $membership = civicrm_api3('Membership', 'get', array(
112 'contribution_recur_id' => $this->contributionRecurID,
113 ));
114 if (!empty($membership['count'])) {
115 $membershipDetails = reset($membership['values']);
116 $values['membership_id'] = $membershipDetails['id'];
117 $values['membership_name'] = $membershipDetails['membership_name'];
118 }
119 $this->assign('recurMembership', $values);
120 $this->assign('contactId', $this->_subscriptionDetails->contact_id);
121 }
122
123 if (!CRM_Core_Permission::check('edit contributions')) {
124 $userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this, FALSE);
125 if (!CRM_Contact_BAO_Contact_Utils::validChecksum($this->_subscriptionDetails->contact_id, $userChecksum)) {
126 CRM_Core_Error::statusBounce(ts('You do not have permission to update subscription.'));
127 }
128 $this->_selfService = TRUE;
129 }
130 $this->assign('self_service', $this->_selfService);
131
132 $this->editableScheduleFields = $this->_paymentProcessorObj->getEditableRecurringScheduleFields();
133
134 $changeHelpText = $this->_paymentProcessorObj->getRecurringScheduleUpdateHelpText();
135 if (!in_array('amount', $this->editableScheduleFields)) {
136 // Not sure if this is good behaviour - maintaining this existing behaviour for now.
137 CRM_Core_Session::setStatus($changeHelpText, ts('Warning'), 'alert');
138 }
139 else {
140 $this->assign('changeHelpText', $changeHelpText);
141 }
142 $alreadyHardCodedFields = array('amount', 'installments');
143 foreach ($this->editableScheduleFields as $editableScheduleField) {
144 if (!in_array($editableScheduleField, $alreadyHardCodedFields)) {
145 $this->addField($editableScheduleField, array('entity' => 'ContributionRecur'));
146 }
147 }
148
149 // when custom data is included in this page
150 if (!empty($_POST['hidden_custom'])) {
151 CRM_Custom_Form_CustomData::preProcess($this, NULL, NULL, 1, 'ContributionRecur', $this->contributionRecurID);
152 CRM_Custom_Form_CustomData::buildQuickForm($this);
153 CRM_Custom_Form_CustomData::setDefaultValues($this);
154 }
155
156 $this->assign('editableScheduleFields', array_diff($this->editableScheduleFields, $alreadyHardCodedFields));
157
158 if ($this->_subscriptionDetails->contact_id) {
159 list($this->_donorDisplayName, $this->_donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_subscriptionDetails->contact_id);
160 }
161
162 CRM_Utils_System::setTitle(ts('Update Recurring Contribution'));
163
164 // Handle context redirection.
165 CRM_Contribute_BAO_ContributionRecur::setSubscriptionContext();
166 }
167
168 /**
169 * Set default values for the form.
170 *
171 * Note that in edit/view mode the default values are retrieved from the database.
172 */
173 public function setDefaultValues() {
174 $this->_defaults = array();
175 $this->_defaults['amount'] = $this->_subscriptionDetails->amount;
176 $this->_defaults['installments'] = $this->_subscriptionDetails->installments;
177 $this->_defaults['campaign_id'] = $this->_subscriptionDetails->campaign_id;
178 $this->_defaults['financial_type_id'] = $this->_subscriptionDetails->financial_type_id;
179 $this->_defaults['is_notify'] = 1;
180 foreach ($this->editableScheduleFields as $field) {
181 $this->_defaults[$field] = isset($this->_subscriptionDetails->$field) ? $this->_subscriptionDetails->$field : NULL;
182 }
183
184 return $this->_defaults;
185 }
186
187 /**
188 * Actually build the components of the form.
189 */
190 public function buildQuickForm() {
191 // CRM-16398: If current recurring contribution got > 1 lineitems then make amount field readonly
192 $amtAttr = array('size' => 20);
193 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($this->_coid);
194 if (count($lineItems) > 1) {
195 $amtAttr += array('readonly' => TRUE);
196 }
197 $this->addMoney('amount', ts('Recurring Contribution Amount'), TRUE, $amtAttr,
198 TRUE, 'currency', $this->_subscriptionDetails->currency, TRUE
199 );
200
201 $this->add('text', 'installments', ts('Number of Installments'), array('size' => 20), FALSE);
202
203 if ($this->_donorEmail) {
204 $this->add('checkbox', 'is_notify', ts('Notify Contributor?'));
205 }
206
207 if (CRM_Core_Permission::check('edit contributions')) {
208 CRM_Campaign_BAO_Campaign::addCampaign($this, $this->_subscriptionDetails->campaign_id);
209 }
210
211 if (CRM_Contribute_BAO_ContributionRecur::supportsFinancialTypeChange($this->contributionRecurID)) {
212 $this->addEntityRef('financial_type_id', ts('Financial Type'), array('entity' => 'FinancialType'), !$this->_selfService);
213 }
214
215 // Add custom data
216 $this->assign('customDataType', 'ContributionRecur');
217 $this->assign('entityID', $this->contributionRecurID);
218
219 $type = 'next';
220 if ($this->_selfService) {
221 $type = 'submit';
222 }
223
224 // define the buttons
225 $this->addButtons(array(
226 array(
227 'type' => $type,
228 'name' => ts('Save'),
229 'isDefault' => TRUE,
230 ),
231 array(
232 'type' => 'cancel',
233 'name' => ts('Cancel'),
234 ),
235 )
236 );
237 }
238
239 /**
240 * Called after the user submits the form.
241 */
242 public function postProcess() {
243 // store the submitted values in an array
244 $params = $this->exportValues();
245
246 if ($this->_selfService && $this->_donorEmail) {
247 // for self service force notify
248 $params['is_notify'] = 1;
249 }
250
251 // if this is an update of an existing recurring contribution, pass the ID
252 $params['id'] = $this->_subscriptionDetails->recur_id;
253 $message = '';
254
255 $params['subscriptionId'] = $this->_subscriptionDetails->subscription_id;
256 $updateSubscription = TRUE;
257 if ($this->_paymentProcessorObj->isSupported('changeSubscriptionAmount')) {
258 $updateSubscription = $this->_paymentProcessorObj->changeSubscriptionAmount($message, $params);
259 }
260 if (is_a($updateSubscription, 'CRM_Core_Error')) {
261 CRM_Core_Error::displaySessionError($updateSubscription);
262 $status = ts('Could not update the Recurring contribution details');
263 $msgTitle = ts('Update Error');
264 $msgType = 'error';
265 }
266 elseif ($updateSubscription) {
267 // Handle custom data
268 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->contributionRecurID, 'ContributionRecur');
269 // save the changes
270 CRM_Contribute_BAO_ContributionRecur::add($params);
271 $status = ts('Recurring contribution has been updated to: %1, every %2 %3(s) for %4 installments.',
272 array(
273 1 => CRM_Utils_Money::format($params['amount'], $this->_subscriptionDetails->currency),
274 2 => $this->_subscriptionDetails->frequency_interval,
275 3 => $this->_subscriptionDetails->frequency_unit,
276 4 => $params['installments'],
277 )
278 );
279
280 $msgTitle = ts('Update Success');
281 $msgType = 'success';
282 $msg = ts('Recurring Contribution Updated');
283 $contactID = $this->_subscriptionDetails->contact_id;
284
285 if ($this->_subscriptionDetails->amount != $params['amount']) {
286 $message .= "<br /> " . ts("Recurring contribution amount has been updated from %1 to %2 for this subscription.",
287 array(
288 1 => CRM_Utils_Money::format($this->_subscriptionDetails->amount, $this->_subscriptionDetails->currency),
289 2 => CRM_Utils_Money::format($params['amount'], $this->_subscriptionDetails->currency),
290 )) . ' ';
291 if ($this->_subscriptionDetails->amount < $params['amount']) {
292 $msg = ts('Recurring Contribution Updated - increased installment amount');
293 }
294 else {
295 $msg = ts('Recurring Contribution Updated - decreased installment amount');
296 }
297 }
298
299 if ($this->_subscriptionDetails->installments != $params['installments']) {
300 $message .= "<br /> " . ts("Recurring contribution installments have been updated from %1 to %2 for this subscription.", array(
301 1 => $this->_subscriptionDetails->installments,
302 2 => $params['installments'],
303 )) . ' ';
304 }
305
306 $activityParams = array(
307 'source_contact_id' => $contactID,
308 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Update Recurring Contribution'),
309 'subject' => $msg,
310 'details' => $message,
311 'activity_date_time' => date('YmdHis'),
312 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
313 );
314
315 $session = CRM_Core_Session::singleton();
316 $cid = $session->get('userID');
317
318 if ($cid) {
319 $activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
320 $activityParams['source_contact_id'] = $cid;
321 }
322 CRM_Activity_BAO_Activity::create($activityParams);
323
324 if (!empty($params['is_notify'])) {
325 // send notification
326 if ($this->_subscriptionDetails->contribution_page_id) {
327 CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_ContributionPage', 'id',
328 $this->_subscriptionDetails->contribution_page_id, $value, array(
329 'title',
330 'receipt_from_name',
331 'receipt_from_email',
332 )
333 );
334 $receiptFrom = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$this->_subscriptionDetails->contribution_page_id]) . '" <' . $value[$this->_subscriptionDetails->contribution_page_id]['receipt_from_email'] . '>';
335 }
336 else {
337 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
338 $receiptFrom = "$domainValues[0] <$domainValues[1]>";
339 }
340
341 list($donorDisplayName, $donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
342
343 $tplParams = array(
344 'recur_frequency_interval' => $this->_subscriptionDetails->frequency_interval,
345 'recur_frequency_unit' => $this->_subscriptionDetails->frequency_unit,
346 'amount' => CRM_Utils_Money::format($params['amount']),
347 'installments' => $params['installments'],
348 );
349
350 $tplParams['contact'] = array('display_name' => $donorDisplayName);
351 $tplParams['receipt_from_email'] = $receiptFrom;
352
353 $sendTemplateParams = array(
354 'groupName' => 'msg_tpl_workflow_contribution',
355 'valueName' => 'contribution_recurring_edit',
356 'contactId' => $contactID,
357 'tplParams' => $tplParams,
358 'isTest' => $this->_subscriptionDetails->is_test,
359 'PDFFilename' => 'receipt.pdf',
360 'from' => $receiptFrom,
361 'toName' => $donorDisplayName,
362 'toEmail' => $donorEmail,
363 );
364 list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
365 }
366 }
367
368 $session = CRM_Core_Session::singleton();
369 $userID = $session->get('userID');
370 if ($userID && $status) {
371 CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
372 }
373 elseif (!$userID) {
374 if ($status) {
375 CRM_Utils_System::setUFMessage($status);
376 }
377 // keep result as 1, since we not displaying anything on the redirected page anyway
378 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/subscriptionstatus',
379 "reset=1&task=update&result=1"));
380 }
381 }
382
383 /**
384 * Explicitly declare the form context.
385 */
386 public function getDefaultContext() {
387 return 'create';
388 }
389
390 }