Merge pull request #14667 from hoegrammer/master
[civicrm-core.git] / CRM / Contribute / Form / UpdateSubscription.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 /**
13 * @package CRM
14 * @copyright CiviCRM LLC https://civicrm.org/licensing
15 */
16
17
18 /**
19 * This class generates form components generic to recurring contributions.
20 *
21 * It delegates the work to lower level subclasses and integrates the changes
22 * back in. It also uses a lot of functionality with the CRM API's, so any change
23 * made here could potentially affect the API etc. Be careful, be aware, use unit tests.
24 */
25 class CRM_Contribute_Form_UpdateSubscription extends CRM_Contribute_Form_ContributionRecur {
26
27 protected $_subscriptionDetails = NULL;
28
29 public $_paymentProcessor = NULL;
30
31 public $_paymentProcessorObj = NULL;
32
33 /**
34 * Fields that affect the schedule and are defined as editable by the processor.
35 *
36 * @var array
37 */
38 protected $editableScheduleFields = [];
39
40 /**
41 * The id of the contact associated with this recurring contribution.
42 *
43 * @var int
44 */
45 public $_contactID;
46
47 /**
48 * Pre-processing for the form.
49 *
50 * @throws \Exception
51 */
52 public function preProcess() {
53
54 parent::preProcess();
55 $this->setAction(CRM_Core_Action::UPDATE);
56
57 if ($this->_coid) {
58 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'info');
59 // @todo test & replace with $this->_paymentProcessorObj = Civi\Payment\System::singleton()->getById($this->_paymentProcessor['id']);
60 $this->_paymentProcessorObj = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'obj');
61 $this->contributionRecurID = $this->_subscriptionDetails->recur_id;
62 }
63 elseif ($this->contributionRecurID) {
64 $this->_coid = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $this->contributionRecurID, 'id', 'contribution_recur_id');
65 }
66
67 if (!$this->contributionRecurID || !$this->_subscriptionDetails) {
68 CRM_Core_Error::statusBounce(ts('Required information missing.'));
69 }
70
71 if ($this->_subscriptionDetails->membership_id && $this->_subscriptionDetails->auto_renew) {
72 // Add Membership details to form
73 $membership = civicrm_api3('Membership', 'get', [
74 'contribution_recur_id' => $this->contributionRecurID,
75 ]);
76 if (!empty($membership['count'])) {
77 $membershipDetails = reset($membership['values']);
78 $values['membership_id'] = $membershipDetails['id'];
79 $values['membership_name'] = $membershipDetails['membership_name'];
80 }
81 $this->assign('recurMembership', $values);
82 $this->assign('contactId', $this->_subscriptionDetails->contact_id);
83 }
84
85 $this->assign('self_service', $this->isSelfService());
86
87 $this->editableScheduleFields = $this->_paymentProcessorObj->getEditableRecurringScheduleFields();
88
89 $changeHelpText = $this->_paymentProcessorObj->getRecurringScheduleUpdateHelpText();
90 if (!in_array('amount', $this->editableScheduleFields)) {
91 // Not sure if this is good behaviour - maintaining this existing behaviour for now.
92 CRM_Core_Session::setStatus($changeHelpText, ts('Warning'), 'alert');
93 }
94 else {
95 $this->assign('changeHelpText', $changeHelpText);
96 }
97 $alreadyHardCodedFields = ['amount', 'installments'];
98 foreach ($this->editableScheduleFields as $editableScheduleField) {
99 if (!in_array($editableScheduleField, $alreadyHardCodedFields)) {
100 $this->addField($editableScheduleField, ['entity' => 'ContributionRecur'], FALSE, FALSE);
101 }
102 }
103
104 // when custom data is included in this page
105 if (!empty($_POST['hidden_custom']) && !$this->isSelfService()) {
106 CRM_Custom_Form_CustomData::preProcess($this, NULL, NULL, 1, 'ContributionRecur', $this->contributionRecurID);
107 CRM_Custom_Form_CustomData::buildQuickForm($this);
108 CRM_Custom_Form_CustomData::setDefaultValues($this);
109 }
110
111 $this->assign('editableScheduleFields', array_diff($this->editableScheduleFields, $alreadyHardCodedFields));
112
113 if ($this->_subscriptionDetails->contact_id) {
114 list($this->_donorDisplayName, $this->_donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_subscriptionDetails->contact_id);
115 }
116
117 CRM_Utils_System::setTitle(ts('Update Recurring Contribution'));
118
119 // Handle context redirection.
120 CRM_Contribute_BAO_ContributionRecur::setSubscriptionContext();
121 }
122
123 /**
124 * Set default values for the form.
125 *
126 * Note that in edit/view mode the default values are retrieved from the database.
127 */
128 public function setDefaultValues() {
129 $this->_defaults = [];
130 $this->_defaults['amount'] = $this->_subscriptionDetails->amount;
131 $this->_defaults['installments'] = $this->_subscriptionDetails->installments;
132 $this->_defaults['campaign_id'] = $this->_subscriptionDetails->campaign_id;
133 $this->_defaults['financial_type_id'] = $this->_subscriptionDetails->financial_type_id;
134 $this->_defaults['is_notify'] = 1;
135 foreach ($this->editableScheduleFields as $field) {
136 $this->_defaults[$field] = isset($this->_subscriptionDetails->$field) ? $this->_subscriptionDetails->$field : NULL;
137 }
138
139 return $this->_defaults;
140 }
141
142 /**
143 * Actually build the components of the form.
144 */
145 public function buildQuickForm() {
146 // CRM-16398: If current recurring contribution got > 1 lineitems then make amount field readonly
147 $amtAttr = ['size' => 20];
148 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($this->_coid);
149 if (count($lineItems) > 1) {
150 $amtAttr += ['readonly' => TRUE];
151 }
152 $this->addMoney('amount', ts('Recurring Contribution Amount'), TRUE, $amtAttr,
153 TRUE, 'currency', $this->_subscriptionDetails->currency, TRUE
154 );
155
156 $this->add('text', 'installments', ts('Number of Installments'), ['size' => 20], FALSE);
157
158 if ($this->_donorEmail) {
159 $this->add('checkbox', 'is_notify', ts('Notify Contributor?'));
160 }
161
162 if (CRM_Core_Permission::check('edit contributions')) {
163 CRM_Campaign_BAO_Campaign::addCampaign($this, $this->_subscriptionDetails->campaign_id);
164 }
165
166 if (CRM_Contribute_BAO_ContributionRecur::supportsFinancialTypeChange($this->contributionRecurID)) {
167 $this->addEntityRef('financial_type_id', ts('Financial Type'), ['entity' => 'FinancialType'], !$this->isSelfService());
168 }
169
170 // Add custom data
171 $this->assign('customDataType', 'ContributionRecur');
172 $this->assign('entityID', $this->contributionRecurID);
173
174 $type = 'next';
175 if ($this->isSelfService()) {
176 $type = 'submit';
177 }
178
179 // define the buttons
180 $this->addButtons([
181 [
182 'type' => $type,
183 'name' => ts('Save'),
184 'isDefault' => TRUE,
185 ],
186 [
187 'type' => 'cancel',
188 'name' => ts('Cancel'),
189 ],
190 ]);
191 }
192
193 /**
194 * Called after the user submits the form.
195 */
196 public function postProcess() {
197 // store the submitted values in an array
198 $params = $this->exportValues();
199
200 if ($this->isSelfService() && $this->_donorEmail) {
201 // for self service force notify
202 $params['is_notify'] = 1;
203 }
204
205 // if this is an update of an existing recurring contribution, pass the ID
206 $params['id'] = $this->_subscriptionDetails->recur_id;
207 $message = '';
208
209 $params['subscriptionId'] = $this->_subscriptionDetails->subscription_id;
210 $updateSubscription = TRUE;
211 if ($this->_paymentProcessorObj->supports('changeSubscriptionAmount')) {
212 try {
213 $updateSubscription = $this->_paymentProcessorObj->changeSubscriptionAmount($message, $params);
214 }
215 catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
216 CRM_Core_Error::statusBounce($e->getMessage());
217 }
218 }
219 if (is_a($updateSubscription, 'CRM_Core_Error')) {
220 CRM_Core_Error::displaySessionError($updateSubscription);
221 $status = ts('Could not update the Recurring contribution details');
222 $msgTitle = ts('Update Error');
223 $msgType = 'error';
224 }
225 elseif ($updateSubscription) {
226 // Handle custom data
227 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->contributionRecurID, 'ContributionRecur');
228 // save the changes
229 CRM_Contribute_BAO_ContributionRecur::add($params);
230 $status = ts('Recurring contribution has been updated to: %1, every %2 %3(s) for %4 installments.',
231 [
232 1 => CRM_Utils_Money::format($params['amount'], $this->_subscriptionDetails->currency),
233 2 => $this->_subscriptionDetails->frequency_interval,
234 3 => $this->_subscriptionDetails->frequency_unit,
235 4 => $params['installments'],
236 ]
237 );
238
239 $msgTitle = ts('Update Success');
240 $msgType = 'success';
241 $msg = ts('Recurring Contribution Updated');
242 $contactID = $this->_subscriptionDetails->contact_id;
243
244 if ($this->_subscriptionDetails->amount != $params['amount']) {
245 $message .= "<br /> " . ts("Recurring contribution amount has been updated from %1 to %2 for this subscription.",
246 [
247 1 => CRM_Utils_Money::format($this->_subscriptionDetails->amount, $this->_subscriptionDetails->currency),
248 2 => CRM_Utils_Money::format($params['amount'], $this->_subscriptionDetails->currency),
249 ]) . ' ';
250 if ($this->_subscriptionDetails->amount < $params['amount']) {
251 $msg = ts('Recurring Contribution Updated - increased installment amount');
252 }
253 else {
254 $msg = ts('Recurring Contribution Updated - decreased installment amount');
255 }
256 }
257
258 if ($this->_subscriptionDetails->installments != $params['installments']) {
259 $message .= "<br /> " . ts("Recurring contribution installments have been updated from %1 to %2 for this subscription.", [
260 1 => $this->_subscriptionDetails->installments,
261 2 => $params['installments'],
262 ]) . ' ';
263 }
264
265 $activityParams = [
266 'source_contact_id' => $contactID,
267 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Update Recurring Contribution'),
268 'subject' => $msg,
269 'details' => $message,
270 'activity_date_time' => date('YmdHis'),
271 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
272 ];
273
274 $session = CRM_Core_Session::singleton();
275 $cid = $session->get('userID');
276
277 if ($cid) {
278 $activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
279 $activityParams['source_contact_id'] = $cid;
280 }
281 CRM_Activity_BAO_Activity::create($activityParams);
282
283 if (!empty($params['is_notify'])) {
284 // send notification
285 if ($this->_subscriptionDetails->contribution_page_id) {
286 CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_ContributionPage', 'id',
287 $this->_subscriptionDetails->contribution_page_id, $value, [
288 'title',
289 'receipt_from_name',
290 'receipt_from_email',
291 ]
292 );
293 $receiptFrom = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$this->_subscriptionDetails->contribution_page_id]) . '" <' . $value[$this->_subscriptionDetails->contribution_page_id]['receipt_from_email'] . '>';
294 }
295 else {
296 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
297 $receiptFrom = "$domainValues[0] <$domainValues[1]>";
298 }
299
300 list($donorDisplayName, $donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
301
302 $tplParams = [
303 'recur_frequency_interval' => $this->_subscriptionDetails->frequency_interval,
304 'recur_frequency_unit' => $this->_subscriptionDetails->frequency_unit,
305 'amount' => CRM_Utils_Money::format($params['amount']),
306 'installments' => $params['installments'],
307 ];
308
309 $tplParams['contact'] = ['display_name' => $donorDisplayName];
310 $tplParams['receipt_from_email'] = $receiptFrom;
311
312 $sendTemplateParams = [
313 'groupName' => 'msg_tpl_workflow_contribution',
314 'valueName' => 'contribution_recurring_edit',
315 'contactId' => $contactID,
316 'tplParams' => $tplParams,
317 'isTest' => $this->_subscriptionDetails->is_test,
318 'PDFFilename' => 'receipt.pdf',
319 'from' => $receiptFrom,
320 'toName' => $donorDisplayName,
321 'toEmail' => $donorEmail,
322 ];
323 list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
324 }
325 }
326
327 $session = CRM_Core_Session::singleton();
328 $userID = $session->get('userID');
329 if ($userID && $status) {
330 CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
331 }
332 elseif (!$userID) {
333 if ($status) {
334 CRM_Utils_System::setUFMessage($status);
335 }
336 // keep result as 1, since we not displaying anything on the redirected page anyway
337 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/subscriptionstatus',
338 "reset=1&task=update&result=1"));
339 }
340 }
341
342 }