Merge pull request #21873 from mariav0/patch-11
[civicrm-core.git] / CRM / Contribute / BAO / ContributionSoft.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 class CRM_Contribute_BAO_ContributionSoft extends CRM_Contribute_DAO_ContributionSoft {
20
21 /**
22 * Construct method.
23 */
24 public function __construct() {
25 parent::__construct();
26 }
27
28 /**
29 * Add contribution soft credit record.
30 *
31 * @param array $params
32 * (reference ) an assoc array of name/value pairs.
33 *
34 * @return object
35 * soft contribution of object that is added
36 */
37 public static function add(&$params) {
38 $hook = empty($params['id']) ? 'create' : 'edit';
39 CRM_Utils_Hook::pre($hook, 'ContributionSoft', CRM_Utils_Array::value('id', $params), $params);
40
41 $contributionSoft = new CRM_Contribute_DAO_ContributionSoft();
42 $contributionSoft->copyValues($params);
43
44 // set currency for CRM-1496
45 if (!isset($contributionSoft->currency)) {
46 $config = CRM_Core_Config::singleton();
47 $contributionSoft->currency = $config->defaultCurrency;
48 }
49 $result = $contributionSoft->save();
50 CRM_Utils_Hook::post($hook, 'ContributionSoft', $contributionSoft->id, $contributionSoft);
51 return $result;
52 }
53
54 /**
55 * Process the soft contribution and/or link to personal campaign page.
56 *
57 * @param array $params
58 * @param CRM_Contribute_BAO_Contribution $contribution
59 *
60 * @throws \CRM_Core_Exception
61 * @throws \CiviCRM_API3_Exception
62 */
63 public static function processSoftContribution($params, $contribution) {
64 if (array_key_exists('pcp', $params)) {
65 self::processPCP($params['pcp'], $contribution);
66 }
67 if (isset($params['soft_credit'])) {
68 $softIDs = self::getSoftCreditIds($contribution->id);
69 $softParams = $params['soft_credit'];
70 foreach ($softParams as $softParam) {
71 if (!empty($softIDs)) {
72 $key = key($softIDs);
73 $softParam['id'] = $softIDs[$key];
74 unset($softIDs[$key]);
75 }
76 $softParam['contribution_id'] = $contribution->id;
77 $softParam['currency'] = $contribution->currency;
78 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
79 if (empty($softParam['amount'])) {
80 $softParam['amount'] = $contribution->total_amount;
81 }
82 CRM_Contribute_BAO_ContributionSoft::add($softParam);
83 }
84
85 // delete any extra soft-credit while updating back-office contribution
86 foreach ((array) $softIDs as $softID) {
87 if (!in_array($softID, $params['soft_credit_ids'])) {
88 civicrm_api3('ContributionSoft', 'delete', ['id' => $softID]);
89 }
90 }
91 }
92 }
93
94 /**
95 * Function used to save pcp / soft credit entry.
96 *
97 * This is used by contribution and also event pcps
98 *
99 * @param array $params
100 * @param object $form
101 * Form object.
102 */
103 public static function formatSoftCreditParams(&$params, &$form) {
104 $pcp = $softParams = $softIDs = [];
105 if (!empty($params['pcp_made_through_id'])) {
106 $fields = [
107 'pcp_made_through_id',
108 'pcp_display_in_roll',
109 'pcp_roll_nickname',
110 'pcp_personal_note',
111 ];
112 foreach ($fields as $f) {
113 $pcp[$f] = $params[$f] ?? NULL;
114 }
115 }
116
117 if (!empty($form->_values['honoree_profile_id']) && !empty($params['soft_credit_type_id'])) {
118 $honorId = NULL;
119
120 // @todo fix use of deprecated function.
121 $contributionSoftParams['soft_credit_type_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', 'pcp');
122 //check if there is any duplicate contact
123 // honoree should never be the donor
124 $exceptKeys = [
125 'contactID' => 0,
126 'onbehalf_contact_id' => 0,
127 ];
128 $except = array_values(array_intersect_key($params, $exceptKeys));
129 $ids = CRM_Contact_BAO_Contact::getDuplicateContacts(
130 $params['honor'],
131 CRM_Core_BAO_UFGroup::getContactType($form->_values['honoree_profile_id']),
132 'Unsupervised',
133 $except,
134 FALSE
135 );
136 if (count($ids)) {
137 $honorId = $ids[0] ?? NULL;
138 }
139
140 $null = [];
141 $honorId = CRM_Contact_BAO_Contact::createProfileContact(
142 $params['honor'], $null,
143 $honorId, NULL,
144 $form->_values['honoree_profile_id']
145 );
146 $softParams[] = [
147 'contact_id' => $honorId,
148 'soft_credit_type_id' => $params['soft_credit_type_id'],
149 ];
150
151 if (!empty($form->_values['is_email_receipt'])) {
152 $form->_values['honor'] = [
153 'soft_credit_type' => CRM_Utils_Array::value(
154 $params['soft_credit_type_id'],
155 CRM_Core_OptionGroup::values("soft_credit_type")
156 ),
157 'honor_id' => $honorId,
158 'honor_profile_id' => $form->_values['honoree_profile_id'],
159 'honor_profile_values' => $params['honor'],
160 ];
161 }
162 }
163 elseif (!empty($params['soft_credit_contact_id'])) {
164 //build soft credit params
165 foreach ($params['soft_credit_contact_id'] as $key => $val) {
166 if ($val && $params['soft_credit_amount'][$key]) {
167 $softParams[$key]['contact_id'] = $val;
168 $softParams[$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
169 $softParams[$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
170 if (!empty($params['soft_credit_id'][$key])) {
171 $softIDs[] = $softParams[$key]['id'] = $params['soft_credit_id'][$key];
172 }
173 }
174 }
175 }
176
177 $params['pcp'] = !empty($pcp) ? $pcp : NULL;
178 $params['soft_credit'] = $softParams;
179 $params['soft_credit_ids'] = $softIDs;
180 }
181
182 /**
183 * Fetch object based on array of properties.
184 *
185 * @param array $params
186 * (reference ) an assoc array of name/value pairs.
187 * @param array $defaults
188 * (reference ) an assoc array to hold the flattened values.
189 *
190 * @return CRM_Contribute_BAO_ContributionSoft
191 */
192 public static function retrieve(&$params, &$defaults) {
193 $contributionSoft = new CRM_Contribute_DAO_ContributionSoft();
194 $contributionSoft->copyValues($params);
195 if ($contributionSoft->find(TRUE)) {
196 CRM_Core_DAO::storeValues($contributionSoft, $defaults);
197 return $contributionSoft;
198 }
199 return NULL;
200 }
201
202 /**
203 * @param int $contact_id
204 * @param int $isTest
205 *
206 * @return array
207 */
208 public static function getSoftContributionTotals($contact_id, $isTest = 0) {
209
210 $whereClause = "AND cc.cancel_date IS NULL";
211
212 $query = "
213 SELECT SUM(amount) as amount, AVG(total_amount) as average, cc.currency
214 FROM civicrm_contribution_soft ccs
215 LEFT JOIN civicrm_contribution cc ON ccs.contribution_id = cc.id
216 WHERE cc.is_test = %2 AND ccs.contact_id = %1 {$whereClause}
217 GROUP BY currency";
218
219 $params = [
220 1 => [$contact_id, 'Integer'],
221 2 => [$isTest, 'Integer'],
222 ];
223
224 $cs = CRM_Core_DAO::executeQuery($query, $params);
225
226 $count = $countCancelled = 0;
227 $amount = $average = $cancelAmount = [];
228
229 while ($cs->fetch()) {
230 if ($cs->amount > 0) {
231 $count++;
232 $amount[] = CRM_Utils_Money::format($cs->amount, $cs->currency);
233 $average[] = CRM_Utils_Money::format($cs->average, $cs->currency);
234 }
235 }
236
237 //to get cancel amount
238 $cancelAmountWhereClause = "AND cc.cancel_date IS NOT NULL";
239 $query = str_replace($whereClause, $cancelAmountWhereClause, $query);
240 $cancelAmountSQL = CRM_Core_DAO::executeQuery($query, $params);
241 while ($cancelAmountSQL->fetch()) {
242 if ($cancelAmountSQL->amount > 0) {
243 $countCancelled++;
244 $cancelAmount[] = CRM_Utils_Money::format($cancelAmountSQL->amount, $cancelAmountSQL->currency);
245 }
246 }
247
248 if ($count > 0 || $countCancelled > 0) {
249 return [
250 $count,
251 $countCancelled,
252 implode(',&nbsp;', $amount),
253 implode(',&nbsp;', $average),
254 implode(',&nbsp;', $cancelAmount),
255 ];
256 }
257 return [0, 0];
258 }
259
260 /**
261 * Retrieve soft contributions for contribution record.
262 *
263 * @param int $contributionID
264 * @param bool $all
265 * Include PCP data.
266 *
267 * @return array
268 * Array of soft contribution ids, amounts, and associated contact ids
269 */
270 public static function getSoftContribution($contributionID, $all = FALSE) {
271 $softContributionFields = self::getSoftCreditContributionFields([$contributionID], $all);
272 return $softContributionFields[$contributionID] ?? [];
273 }
274
275 /**
276 * Retrieve soft contributions for an array of contribution records.
277 *
278 * @param array $contributionIDs
279 * @param bool $all
280 * Include PCP data.
281 *
282 * @return array
283 * Array of soft contribution ids, amounts, and associated contact ids
284 */
285 public static function getSoftCreditContributionFields($contributionIDs, $all = FALSE) {
286 $pcpFields = [
287 'pcp_id',
288 'pcp_title',
289 'pcp_display_in_roll',
290 'pcp_roll_nickname',
291 'pcp_personal_note',
292 ];
293
294 $query = "
295 SELECT ccs.id, pcp_id, ccs.contribution_id as contribution_id, cpcp.title as pcp_title, pcp_display_in_roll, pcp_roll_nickname, pcp_personal_note, ccs.currency as currency, amount, ccs.contact_id as contact_id, c.display_name, ccs.soft_credit_type_id
296 FROM civicrm_contribution_soft ccs INNER JOIN civicrm_contact c on c.id = ccs.contact_id
297 LEFT JOIN civicrm_pcp cpcp ON ccs.pcp_id = cpcp.id
298 WHERE contribution_id IN (%1)
299 ";
300 $queryParams = [1 => [implode(',', $contributionIDs), 'CommaSeparatedIntegers']];
301 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
302
303 $softContribution = $indexes = [];
304 while ($dao->fetch()) {
305 if ($dao->pcp_id) {
306 if ($all) {
307 foreach ($pcpFields as $val) {
308 $softContribution[$dao->contribution_id][$val] = $dao->$val;
309 }
310 $softContribution[$dao->contribution_id]['pcp_soft_credit_to_name'] = $dao->display_name;
311 $softContribution[$dao->contribution_id]['pcp_soft_credit_to_id'] = $dao->contact_id;
312 }
313 }
314 else {
315 // Use a 1-based array because that's what this function returned before refactoring in https://github.com/civicrm/civicrm-core/pull/14747
316 $indexes[$dao->contribution_id] = isset($indexes[$dao->contribution_id]) ? $indexes[$dao->contribution_id] + 1 : 1;
317 $softContribution[$dao->contribution_id]['soft_credit'][$indexes[$dao->contribution_id]] = [
318 'contact_id' => $dao->contact_id,
319 'soft_credit_id' => $dao->id,
320 'currency' => $dao->currency,
321 'amount' => $dao->amount,
322 'contact_name' => $dao->display_name,
323 'soft_credit_type' => $dao->soft_credit_type_id,
324 'soft_credit_type_label' => CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $dao->soft_credit_type_id),
325 ];
326 }
327 }
328
329 return $softContribution;
330 }
331
332 /**
333 * @param int $contributionID
334 * @param bool $isPCP
335 *
336 * @return array
337 */
338 public static function getSoftCreditIds($contributionID, $isPCP = FALSE) {
339 $query = "
340 SELECT id
341 FROM civicrm_contribution_soft
342 WHERE contribution_id = %1
343 ";
344
345 if ($isPCP) {
346 $query .= " AND pcp_id IS NOT NULL";
347 }
348 else {
349 $query .= " AND pcp_id IS NULL";
350 }
351 $params = [1 => [$contributionID, 'Integer']];
352
353 $dao = CRM_Core_DAO::executeQuery($query, $params);
354 $id = [];
355 $type = '';
356 while ($dao->fetch()) {
357 if ($isPCP) {
358 return $dao->id;
359 }
360 $id[] = $dao->id;
361 }
362 return $id;
363 }
364
365 /**
366 * Wrapper for ajax soft contribution selector.
367 *
368 * @param array $params
369 * Associated array for params.
370 *
371 * @return array
372 * Associated array of soft contributions
373 */
374 public static function getSoftContributionSelector($params) {
375 $isTest = 0;
376 if (!empty($params['isTest'])) {
377 $isTest = $params['isTest'];
378 }
379 // Format the params.
380 $params['offset'] = ($params['page'] - 1) * $params['rp'];
381 $params['rowCount'] = $params['rp'];
382 $params['sort'] = $params['sortBy'] ?? NULL;
383 $contactId = $params['cid'];
384
385 $filter = NULL;
386 if ($params['context'] == 'membership' && !empty($params['entityID']) && $contactId) {
387 $filter = " AND cc.id IN (SELECT contribution_id FROM civicrm_membership_payment WHERE membership_id = {$params['entityID']})";
388 }
389
390 $softCreditList = self::getSoftContributionList($contactId, $filter, $isTest, $params);
391
392 $softCreditListDT = [];
393 $softCreditListDT['data'] = array_values($softCreditList);
394 $softCreditListDT['recordsTotal'] = $params['total'];
395 $softCreditListDT['recordsFiltered'] = $params['total'];
396
397 return $softCreditListDT;
398 }
399
400 /**
401 * Function to retrieve the list of soft contributions for given contact.
402 *
403 * @param int $contact_id
404 * Contact id.
405 * @param string $filter
406 * @param int $isTest
407 * Additional filter criteria, later used in where clause.
408 * @param array $dTParams
409 *
410 * @return array
411 */
412 public static function getSoftContributionList($contact_id, $filter = NULL, $isTest = 0, &$dTParams = NULL) {
413 $config = CRM_Core_Config::singleton();
414 $links = [
415 CRM_Core_Action::VIEW => [
416 'name' => ts('View'),
417 'url' => 'civicrm/contact/view/contribution',
418 'qs' => 'reset=1&id=%%contributionid%%&cid=%%contactId%%&action=view&context=contribution&selectedChild=contribute',
419 'title' => ts('View related contribution'),
420 ],
421 ];
422 $orderBy = 'cc.receive_date DESC';
423 if (!empty($dTParams['sort'])) {
424 $orderBy = $dTParams['sort'];
425 }
426 $limit = '';
427 if (!empty($dTParams['rowCount']) && $dTParams['rowCount'] > 0) {
428 $limit = " LIMIT {$dTParams['offset']}, {$dTParams['rowCount']} ";
429 }
430 $softOgId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'soft_credit_type', 'id', 'name');
431 $statusOgId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'contribution_status', 'id', 'name');
432
433 $query = '
434 SELECT SQL_CALC_FOUND_ROWS ccs.id, ccs.amount as amount,
435 ccs.contribution_id,
436 ccs.pcp_id,
437 ccs.pcp_display_in_roll,
438 ccs.pcp_roll_nickname,
439 ccs.pcp_personal_note,
440 ccs.soft_credit_type_id,
441 sov.label as sct_label,
442 cc.receive_date,
443 cc.contact_id as contributor_id,
444 cc.contribution_status_id as contribution_status_id,
445 cov.label as contribution_status,
446 cp.title as pcp_title,
447 cc.currency,
448 contact.display_name as contributor_name,
449 cct.name as financial_type
450 FROM civicrm_contribution_soft ccs
451 LEFT JOIN civicrm_contribution cc
452 ON ccs.contribution_id = cc.id
453 LEFT JOIN civicrm_pcp cp
454 ON ccs.pcp_id = cp.id
455 LEFT JOIN civicrm_contact contact ON
456 ccs.contribution_id = cc.id AND cc.contact_id = contact.id
457 LEFT JOIN civicrm_financial_type cct ON cc.financial_type_id = cct.id
458 LEFT JOIN civicrm_option_value sov ON sov.option_group_id = %3 AND ccs.soft_credit_type_id = sov.value
459 LEFT JOIN civicrm_option_value cov ON cov.option_group_id = %4 AND cc.contribution_status_id = cov.value
460 ';
461
462 $where = "
463 WHERE cc.is_test = %2 AND ccs.contact_id = %1";
464 if ($filter) {
465 $where .= $filter;
466 }
467
468 $query .= "{$where} ORDER BY {$orderBy} {$limit}";
469
470 $params = [
471 1 => [$contact_id, 'Integer'],
472 2 => [$isTest, 'Integer'],
473 3 => [$softOgId, 'Integer'],
474 4 => [$statusOgId, 'Integer'],
475 ];
476 $cs = CRM_Core_DAO::executeQuery($query, $params);
477
478 $dTParams['total'] = CRM_Core_DAO::singleValueQuery('SELECT FOUND_ROWS()');
479 $result = [];
480 while ($cs->fetch()) {
481 $result[$cs->id]['amount'] = CRM_Utils_Money::format($cs->amount, $cs->currency);
482 $result[$cs->id]['currency'] = $cs->currency;
483 $result[$cs->id]['contributor_id'] = $cs->contributor_id;
484 $result[$cs->id]['contribution_id'] = $cs->contribution_id;
485 $result[$cs->id]['contributor_name'] = CRM_Utils_System::href(
486 $cs->contributor_name,
487 'civicrm/contact/view',
488 "reset=1&cid={$cs->contributor_id}"
489 );
490 $result[$cs->id]['financial_type'] = $cs->financial_type;
491 $result[$cs->id]['receive_date'] = CRM_Utils_Date::customFormat($cs->receive_date, $config->dateformatDatetime);
492 $result[$cs->id]['pcp_id'] = $cs->pcp_id;
493 $result[$cs->id]['pcp_title'] = ($cs->pcp_title) ? $cs->pcp_title : 'n/a';
494 $result[$cs->id]['pcp_display_in_roll'] = $cs->pcp_display_in_roll;
495 $result[$cs->id]['pcp_roll_nickname'] = $cs->pcp_roll_nickname;
496 $result[$cs->id]['pcp_personal_note'] = $cs->pcp_personal_note;
497 $result[$cs->id]['contribution_status'] = $cs->contribution_status;
498 $result[$cs->id]['sct_label'] = $cs->sct_label;
499 $replace = [
500 'contributionid' => $cs->contribution_id,
501 'contactId' => $cs->contributor_id,
502 ];
503 $result[$cs->id]['links'] = CRM_Core_Action::formLink($links, NULL, $replace);
504
505 if ($isTest) {
506 $result[$cs->id]['contribution_status'] = CRM_Core_TestEntity::appendTestText($result[$cs->id]['contribution_status']);
507 }
508 }
509 return $result;
510 }
511
512 /**
513 * Function to assign honor profile fields to template/form, if $honorId (as soft-credit's contact_id)
514 * is passed then whole honoreeprofile fields with title/value assoc array assigned or only honoreeName
515 * is assigned
516 *
517 * @param CRM_Core_Form $form
518 * @param array $params
519 * @param int $honorId
520 */
521 public static function formatHonoreeProfileFields($form, $params, $honorId = NULL) {
522 if (empty($form->_values['honoree_profile_id'])) {
523 return;
524 }
525 $profileContactType = CRM_Core_BAO_UFGroup::getContactType($form->_values['honoree_profile_id']);
526 $profileFields = CRM_Core_BAO_UFGroup::getFields($form->_values['honoree_profile_id']);
527 $honoreeProfileFields = $values = [];
528 $honorName = NULL;
529
530 if ($honorId) {
531 CRM_Core_BAO_UFGroup::getValues($honorId, $profileFields, $values, FALSE, $params);
532 if (empty($params)) {
533 foreach ($profileFields as $name => $field) {
534 $title = $field['title'];
535 $params[$field['name']] = $values[$title];
536 }
537 }
538 }
539
540 //remove name related fields and construct name string with prefix/suffix
541 //which will be later assigned to template
542 switch ($profileContactType) {
543 case 'Individual':
544 if (array_key_exists('prefix_id', $params)) {
545 $honorName = CRM_Utils_Array::value($params['prefix_id'],
546 CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id')
547 );
548 unset($profileFields['prefix_id']);
549 }
550 $honorName .= ' ' . $params['first_name'] . ' ' . $params['last_name'];
551 unset($profileFields['first_name']);
552 unset($profileFields['last_name']);
553 if (array_key_exists('suffix_id', $params)) {
554 $honorName .= ' ' . CRM_Utils_Array::value($params['suffix_id'],
555 CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id')
556 );
557 unset($profileFields['suffix_id']);
558 }
559 break;
560
561 case 'Organization':
562 $honorName = $params['organization_name'];
563 unset($profileFields['organization_name']);
564 break;
565
566 case 'Household':
567 $honorName = $params['household_name'];
568 unset($profileFields['household_name']);
569 break;
570 }
571
572 if ($honorId) {
573 $honoreeProfileFields['Name'] = $honorName;
574 foreach ($profileFields as $name => $field) {
575 $title = $field['title'];
576 $honoreeProfileFields[$title] = $values[$title];
577 }
578 $form->assign('honoreeProfile', $honoreeProfileFields);
579 }
580 else {
581 $form->assign('honorName', $honorName);
582 }
583 }
584
585 /**
586 * Process the pcp associated with a contribution.
587 *
588 * @param array $pcp
589 * @param \CRM_Contribute_BAO_Contribution $contribution
590 *
591 * @throws \CRM_Core_Exception
592 * @throws \CiviCRM_API3_Exception
593 * @throws \API_Exception
594 */
595 protected static function processPCP($pcp, $contribution) {
596 $pcpId = self::getSoftCreditIds($contribution->id, TRUE);
597
598 if ($pcp) {
599 $softParams = [];
600 $softParams['id'] = $pcpId ?: NULL;
601 $softParams['contribution_id'] = $contribution->id;
602 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
603 $softParams['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP',
604 $pcp['pcp_made_through_id'], 'contact_id'
605 );
606 $softParams['currency'] = $contribution->currency;
607 $softParams['amount'] = $contribution->total_amount;
608 $softParams['pcp_display_in_roll'] = $pcp['pcp_display_in_roll'] ?? NULL;
609 $softParams['pcp_roll_nickname'] = $pcp['pcp_roll_nickname'] ?? NULL;
610 $softParams['pcp_personal_note'] = $pcp['pcp_personal_note'] ?? NULL;
611 $softParams['soft_credit_type_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', 'pcp');
612 $contributionSoft = self::add($softParams);
613 //Send notification to owner for PCP if the contribution is already completed.
614 if ($contributionSoft->pcp_id && empty($pcpId)
615 && 'Completed' === CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id)
616 ) {
617 self::pcpNotifyOwner($contribution->id, (array) $contributionSoft);
618 }
619 }
620 //Delete PCP against this contribution and create new on submitted PCP information
621 elseif ($pcpId) {
622 civicrm_api3('ContributionSoft', 'delete', ['id' => $pcpId]);
623 }
624 }
625
626 /**
627 * Function used to send notification mail to pcp owner.
628 *
629 * @param int $contributionID
630 * @param array $contributionSoft
631 * Contribution object.
632 *
633 * @throws \API_Exception
634 * @throws \CRM_Core_Exception
635 */
636 public static function pcpNotifyOwner(int $contributionID, array $contributionSoft): void {
637 $params = ['id' => $contributionSoft['pcp_id']];
638 $contribution = Contribution::get(FALSE)
639 ->addWhere('id', '=', $contributionID)
640 ->addSelect('receive_date', 'contact_id')->execute()->first();
641 CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
642 $ownerNotifyID = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCPBlock', $pcpInfo['pcp_block_id'], 'owner_notify_id');
643 $ownerNotifyOption = CRM_Core_PseudoConstant::getName('CRM_PCP_DAO_PCPBlock', 'owner_notify_id', $ownerNotifyID);
644
645 if ($ownerNotifyOption !== 'no_notifications' &&
646 (($ownerNotifyOption === 'owner_chooses' &&
647 CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $contributionSoft['pcp_id'], 'is_notify')) ||
648 $ownerNotifyOption === 'all_owners')) {
649 $pcpInfoURL = CRM_Utils_System::url('civicrm/pcp/info',
650 "reset=1&id={$contributionSoft['pcp_id']}",
651 TRUE, NULL, FALSE, TRUE
652 );
653 // set email in the template here
654
655 if (CRM_Core_BAO_LocationType::getBilling()) {
656 [$donorName, $email] = CRM_Contact_BAO_Contact_Location::getEmailDetails($contribution['contact_id'],
657 FALSE, CRM_Core_BAO_LocationType::getBilling());
658 }
659 // get primary location email if no email exist( for billing location).
660 if (!$email) {
661 [$donorName, $email] = CRM_Contact_BAO_Contact_Location::getEmailDetails($contribution['contact_id']);
662 }
663 [$ownerName, $ownerEmail] = CRM_Contact_BAO_Contact_Location::getEmailDetails($contributionSoft['contact_id']);
664 $tplParams = [
665 'page_title' => $pcpInfo['title'],
666 'receive_date' => $contribution['receive_date'],
667 'total_amount' => $contributionSoft['amount'],
668 'donors_display_name' => $donorName,
669 'donors_email' => $email,
670 'pcpInfoURL' => $pcpInfoURL,
671 'is_honor_roll_enabled' => $contributionSoft['pcp_display_in_roll'],
672 'currency' => $contributionSoft['currency'],
673 ];
674 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
675 $sendTemplateParams = [
676 'groupName' => 'msg_tpl_workflow_contribution',
677 'valueName' => 'pcp_owner_notify',
678 'contactId' => $contributionSoft['contact_id'],
679 'toEmail' => $ownerEmail,
680 'toName' => $ownerName,
681 'from' => "$domainValues[0] <$domainValues[1]>",
682 'tplParams' => $tplParams,
683 'PDFFilename' => 'receipt.pdf',
684 ];
685 CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
686 }
687 }
688
689 }