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