Merge pull request #22475 from eileenmcnaughton/ipn
[civicrm-core.git] / CRM / Contribute / Form / ContributionView.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 use Civi\Api4\Contribution;
13
14 /**
15 *
16 * @package CRM
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
18 */
19
20 /**
21 * This class generates form components for Payment-Instrument.
22 */
23 class CRM_Contribute_Form_ContributionView extends CRM_Core_Form {
24
25 /**
26 * Set variables up before form is built.
27 *
28 * @throws \CRM_Core_Exception
29 * @throws \API_Exception
30 */
31 public function preProcess() {
32 $id = $this->getID();
33
34 $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
35 $this->assign('context', $context);
36
37 // Note than this get could be restricted by ACLs in an extension
38 $contribution = Contribution::get(TRUE)->addWhere('id', '=', $id)->addSelect('*')->execute()->first();
39 if (empty($contribution)) {
40 CRM_Core_Error::statusBounce(ts('Access to contribution not permitted'));
41 }
42 // We just cast here because it was traditionally an array called values - would be better
43 // just to use 'contribution'.
44 $values = (array) $contribution;
45 $contributionStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
46
47 // @todo - it might have been better to create a new form that extends this
48 // for template contributions rather than overloading this form.
49 $force_create_template = CRM_Utils_Request::retrieve('force_create_template', 'Boolean', $this, FALSE, FALSE);
50 if ($force_create_template && !empty($values['contribution_recur_id']) && empty($values['is_template'])) {
51 // Create a template contribution.
52 $templateContributionId = CRM_Contribute_BAO_ContributionRecur::ensureTemplateContributionExists($values['contribution_recur_id']);
53 if (!empty($templateContributionId)) {
54 $id = $templateContributionId;
55 $params = ['id' => $id];
56 $values = CRM_Contribute_BAO_Contribution::getValuesWithMappings($params);
57 }
58 }
59 $this->assign('is_template', $values['is_template']);
60
61 CRM_Contribute_BAO_Contribution::resolveDefaults($values);
62
63 if (!empty($values['contribution_page_id'])) {
64 $contribPages = CRM_Contribute_PseudoConstant::contributionPage(NULL, TRUE);
65 $values['contribution_page_title'] = CRM_Utils_Array::value(CRM_Utils_Array::value('contribution_page_id', $values), $contribPages);
66 }
67
68 // get received into i.e to_financial_account_id from last trxn
69 $financialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($this->getID(), 'DESC');
70 $values['to_financial_account'] = '';
71 if (!empty($financialTrxnId['financialTrxnId'])) {
72 $values['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $financialTrxnId['financialTrxnId'], 'to_financial_account_id');
73 if ($values['to_financial_account_id']) {
74 $values['to_financial_account'] = CRM_Contribute_PseudoConstant::financialAccount($values['to_financial_account_id']);
75 }
76 $values['payment_processor_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $financialTrxnId['financialTrxnId'], 'payment_processor_id');
77 if ($values['payment_processor_id']) {
78 $values['payment_processor_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessor', $values['payment_processor_id'], 'name');
79 }
80 }
81
82 if (!empty($values['contribution_recur_id'])) {
83 $sql = "SELECT installments, frequency_interval, frequency_unit FROM civicrm_contribution_recur WHERE id = %1";
84 $params = [1 => [$values['contribution_recur_id'], 'Integer']];
85 $dao = CRM_Core_DAO::executeQuery($sql, $params);
86 if ($dao->fetch()) {
87 $values['recur_installments'] = $dao->installments;
88 $values['recur_frequency_unit'] = $dao->frequency_unit;
89 $values['recur_frequency_interval'] = $dao->frequency_interval;
90 }
91 }
92
93 $groupTree = CRM_Core_BAO_CustomGroup::getTree('Contribution', NULL, $id, 0, $values['financial_type_id'] ?? NULL,
94 NULL, TRUE, NULL, FALSE, CRM_Core_Permission::VIEW);
95 CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree, FALSE, NULL, NULL, NULL, $id);
96
97 $premiumId = NULL;
98 $dao = new CRM_Contribute_DAO_ContributionProduct();
99 $dao->contribution_id = $id;
100 if ($dao->find(TRUE)) {
101 $premiumId = $dao->id;
102 $productID = $dao->product_id;
103 }
104
105 if ($premiumId) {
106 $productDAO = new CRM_Contribute_DAO_Product();
107 $productDAO->id = $productID;
108 $productDAO->find(TRUE);
109
110 $this->assign('premium', $productDAO->name);
111 $this->assign('option', $dao->product_option);
112 $this->assign('fulfilled', $dao->fulfilled_date);
113 }
114
115 // Get Note
116 $noteValue = CRM_Core_BAO_Note::getNote(CRM_Utils_Array::value('id', $values), 'civicrm_contribution');
117 $values['note'] = array_values($noteValue);
118
119 // show billing address location details, if exists
120 if (!empty($values['address_id'])) {
121 $addressParams = ['id' => $values['address_id']];
122 $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id');
123 $addressDetails = array_values($addressDetails);
124 $values['billing_address'] = $addressDetails[0]['display'];
125 }
126
127 //assign soft credit record if exists.
128 $SCRecords = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->getID(), TRUE);
129 if (!empty($SCRecords['soft_credit'])) {
130 $this->assign('softContributions', $SCRecords['soft_credit']);
131 unset($SCRecords['soft_credit']);
132 }
133
134 //assign pcp record if exists
135 foreach ($SCRecords as $name => $value) {
136 $this->assign($name, $value);
137 }
138
139 $lineItems = [CRM_Price_BAO_LineItem::getLineItemsByContributionID(($id))];
140 $this->assign('lineItem', $lineItems);
141 $values['totalAmount'] = $values['total_amount'];
142 $this->assign('displayLineItemFinancialType', TRUE);
143
144 //do check for campaigns
145 if ($campaignId = CRM_Utils_Array::value('campaign_id', $values)) {
146 $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
147 $values['campaign'] = $campaigns[$campaignId];
148 }
149 if ($contributionStatus === 'Refunded') {
150 $this->assign('refund_trxn_id', CRM_Core_BAO_FinancialTrxn::getRefundTransactionTrxnID($id));
151 }
152
153 // assign values to the template
154 $this->assignVariables($values, array_keys($values));
155 $invoicing = CRM_Invoicing_Utils::isInvoicingEnabled();
156 $this->assign('invoicing', $invoicing);
157 $this->assign('isDeferred', Civi::settings()->get('deferred_revenue_enabled'));
158 if ($invoicing && isset($values['tax_amount'])) {
159 $this->assign('totalTaxAmount', $values['tax_amount']);
160 }
161
162 // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container
163 $displayName = CRM_Contact_BAO_Contact::displayName($values['contact_id']);
164 $this->assign('displayName', $displayName);
165 // Check if this is default domain contact CRM-10482
166 if (CRM_Contact_BAO_Contact::checkDomainContact($values['contact_id'])) {
167 $displayName .= ' (' . ts('default organization') . ')';
168 }
169
170 if (empty($values['is_template'])) {
171 $this->setTitle(ts('View Contribution from') . ' ' . $displayName);
172 }
173 else {
174 $this->setTitle(ts('View Template Contribution from') . ' ' . $displayName);
175 }
176
177 // add viewed contribution to recent items list
178 $url = CRM_Utils_System::url('civicrm/contact/view/contribution',
179 "action=view&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"
180 );
181
182 $title = $displayName . ' - (' . CRM_Utils_Money::format($values['total_amount'], $values['currency']) . ' ' . ' - ' . $values['financial_type'] . ')';
183
184 $recentOther = [];
185 if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) {
186 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
187 "action=update&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"
188 );
189 }
190 if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) {
191 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
192 "action=delete&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"
193 );
194 }
195 CRM_Utils_Recent::add($title,
196 $url,
197 $values['id'],
198 'Contribution',
199 $values['contact_id'],
200 NULL,
201 $recentOther
202 );
203 $statusOptionValueNames = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
204 $contributionStatus = $statusOptionValueNames[$values['contribution_status_id']];
205 $this->assign('addRecordPayment', in_array($contributionStatus, ['Partially paid', 'Pending refund', 'Pending']));
206 $this->assignPaymentInfoBlock($id);
207
208 $searchKey = NULL;
209 if ($this->controller->_key) {
210 $searchKey = $this->controller->_key;
211 }
212
213 if ($this->isHasAccess('update')) {
214 $urlParams = "reset=1&id={$id}&cid={$values['contact_id']}&action=update&context={$context}";
215 if (($context === 'fulltext' || $context === 'search') && $searchKey) {
216 $urlParams = "reset=1&id={$id}&cid={$values['contact_id']}&action=update&context={$context}&key={$searchKey}";
217 }
218 if (!$contribution['is_template']) {
219 foreach (CRM_Contribute_BAO_Contribution::getContributionPaymentLinks($this->getID(), $contributionStatus) as $paymentButton) {
220 $paymentButton['icon'] = 'fa-plus-circle';
221 $linkButtons[] = $paymentButton;
222 }
223 }
224 $linkButtons[] = [
225 'title' => ts('Edit'),
226 'url' => 'civicrm/contact/view/contribution',
227 'qs' => $urlParams,
228 'icon' => 'fa-pencil',
229 'accesskey' => 'e',
230 ];
231 }
232
233 if ($this->isHasAccess('delete')) {
234 $urlParams = "reset=1&id={$id}&cid={$values['contact_id']}&action=delete&context={$context}";
235 if (($context === 'fulltext' || $context === 'search') && $searchKey) {
236 $urlParams = "reset=1&id={$id}&cid={$values['contact_id']}&action=delete&context={$context}&key={$searchKey}";
237 }
238 $linkButtons[] = [
239 'title' => ts('Delete'),
240 'url' => 'civicrm/contact/view/contribution',
241 'qs' => $urlParams,
242 'icon' => 'fa-trash',
243 ];
244 }
245
246 $pdfUrlParams = "reset=1&id={$id}&cid={$values['contact_id']}";
247 $emailUrlParams = "reset=1&id={$id}&cid={$values['contact_id']}&select=email";
248 if (Civi::settings()->get('invoicing') && !$contribution['is_template']) {
249 if (($values['contribution_status'] !== 'Refunded') && ($values['contribution_status'] !== 'Cancelled')) {
250 $invoiceButtonText = ts('Download Invoice');
251 }
252 else {
253 $invoiceButtonText = ts('Download Invoice and Credit Note');
254 }
255 $linkButtons[] = [
256 'title' => $invoiceButtonText,
257 'url' => 'civicrm/contribute/invoice',
258 'qs' => $pdfUrlParams,
259 'icon' => 'fa-download',
260 ];
261 $linkButtons[] = [
262 'title' => ts('Email Invoice'),
263 'url' => 'civicrm/contribute/invoice/email',
264 'qs' => $emailUrlParams,
265 'icon' => 'fa-paper-plane',
266 ];
267 }
268 $this->assign('linkButtons', $linkButtons ?? []);
269 // These next 3 parameters are used to construct a url in PaymentInfo.tpl
270 $this->assign('contactId', $values['contact_id']);
271 $this->assign('componentId', $id);
272 $this->assign('component', 'contribution');
273 $this->assignPaymentInfoBlock($id);
274 }
275
276 /**
277 * Build the form object.
278 */
279 public function buildQuickForm() {
280 $this->addButtons([
281 [
282 'type' => 'cancel',
283 'name' => ts('Done'),
284 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
285 'isDefault' => TRUE,
286 ],
287 ]);
288 }
289
290 /**
291 * Assign the values to build the payment info block.
292 *
293 * @todo - this is a bit too much copy & paste from AbstractEditPayment
294 * (justifying on the basis it's 'pretty short' and in a different inheritance
295 * tree. I feel like traits are probably the longer term answer).
296 *
297 * @param int $id
298 *
299 * @return string
300 * Block title.
301 */
302 protected function assignPaymentInfoBlock($id) {
303 // component is used in getPaymentInfo primarily to retrieve the contribution id, we
304 // already have that.
305 $paymentInfo = CRM_Contribute_BAO_Contribution::getPaymentInfo($id, 'contribution', TRUE);
306 $title = ts('View Payment');
307 $this->assign('transaction', TRUE);
308 $this->assign('payments', $paymentInfo['transaction']);
309 $this->assign('paymentLinks', $paymentInfo['payment_links']);
310 return $title;
311 }
312
313 /**
314 * @param string $action
315 *
316 * @return bool
317 */
318 private function isHasAccess(string $action): bool {
319 try {
320 return Contribution::checkAccess()
321 ->setAction($action)
322 ->addValue('id', $this->getID())
323 ->execute()->first()['access'];
324 }
325 catch (API_Exception $e) {
326 return FALSE;
327 }
328 }
329
330 /**
331 * Get the contribution ID.
332 *
333 * @return int
334 */
335 private function getID(): int {
336 $id = $this->get('id');
337 if (empty($id)) {
338 CRM_Core_Error::statusBounce('Contribution ID is required');
339 }
340 return $id;
341 }
342
343 }