3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
12 use Civi\Api4\Contribution
;
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 class CRM_Contribute_BAO_ContributionSoft
extends CRM_Contribute_DAO_ContributionSoft
{
22 * Add contribution soft credit record.
24 * @param array $params
25 * (reference ) an assoc array of name/value pairs.
28 * soft contribution of object that is added
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);
34 $contributionSoft = new CRM_Contribute_DAO_ContributionSoft();
35 $contributionSoft->copyValues($params);
37 // set currency for CRM-1496
38 if (!isset($contributionSoft->currency
)) {
39 $config = CRM_Core_Config
::singleton();
40 $contributionSoft->currency
= $config->defaultCurrency
;
42 $result = $contributionSoft->save();
43 CRM_Utils_Hook
::post($hook, 'ContributionSoft', $contributionSoft->id
, $contributionSoft);
48 * Process the soft contribution and/or link to personal campaign page.
50 * @param array $params
51 * @param CRM_Contribute_BAO_Contribution $contribution
53 * @throws \CRM_Core_Exception
54 * @throws \CiviCRM_API3_Exception
56 public static function processSoftContribution($params, $contribution) {
57 if (array_key_exists('pcp', $params)) {
58 self
::processPCP($params['pcp'], $contribution);
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)) {
66 $softParam['id'] = $softIDs[$key];
67 unset($softIDs[$key]);
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
;
75 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
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]);
88 * Function used to save pcp / soft credit entry.
90 * This is used by contribution and also event pcps
92 * @param array $params
96 public static function formatSoftCreditParams(&$params, &$form) {
97 $pcp = $softParams = $softIDs = [];
98 if (!empty($params['pcp_made_through_id'])) {
100 'pcp_made_through_id',
101 'pcp_display_in_roll',
105 foreach ($fields as $f) {
106 $pcp[$f] = $params[$f] ??
NULL;
110 if (!empty($form->_values
['honoree_profile_id']) && !empty($params['soft_credit_type_id'])) {
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
119 'onbehalf_contact_id' => 0,
121 $except = array_values(array_intersect_key($params, $exceptKeys));
122 $ids = CRM_Contact_BAO_Contact
::getDuplicateContacts(
124 CRM_Core_BAO_UFGroup
::getContactType($form->_values
['honoree_profile_id']),
130 $honorId = $ids[0] ??
NULL;
134 $honorId = CRM_Contact_BAO_Contact
::createProfileContact(
135 $params['honor'], $null,
137 $form->_values
['honoree_profile_id']
140 'contact_id' => $honorId,
141 'soft_credit_type_id' => $params['soft_credit_type_id'],
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")
150 'honor_id' => $honorId,
151 'honor_profile_id' => $form->_values
['honoree_profile_id'],
152 'honor_profile_values' => $params['honor'],
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];
170 $params['pcp'] = !empty($pcp) ?
$pcp : NULL;
171 $params['soft_credit'] = $softParams;
172 $params['soft_credit_ids'] = $softIDs;
176 * Fetch object based on array of properties.
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.
183 * @return CRM_Contribute_BAO_ContributionSoft
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;
196 * @param int $contact_id
201 public static function getSoftContributionTotals($contact_id, $isTest = 0) {
203 $whereClause = "AND cc.cancel_date IS NULL";
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}
213 1 => [$contact_id, 'Integer'],
214 2 => [$isTest, 'Integer'],
217 $cs = CRM_Core_DAO
::executeQuery($query, $params);
219 $count = $countCancelled = 0;
220 $amount = $average = $cancelAmount = [];
222 while ($cs->fetch()) {
223 if ($cs->amount
> 0) {
225 $amount[] = CRM_Utils_Money
::format($cs->amount
, $cs->currency
);
226 $average[] = CRM_Utils_Money
::format($cs->average
, $cs->currency
);
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) {
237 $cancelAmount[] = CRM_Utils_Money
::format($cancelAmountSQL->amount
, $cancelAmountSQL->currency
);
241 if ($count > 0 ||
$countCancelled > 0) {
245 implode(', ', $amount),
246 implode(', ', $average),
247 implode(', ', $cancelAmount),
254 * Retrieve soft contributions for contribution record.
256 * @param int $contributionID
261 * Array of soft contribution ids, amounts, and associated contact ids
263 public static function getSoftContribution($contributionID, $all = FALSE) {
264 $softContributionFields = self
::getSoftCreditContributionFields([$contributionID], $all);
265 return $softContributionFields[$contributionID] ??
[];
269 * Retrieve soft contributions for an array of contribution records.
271 * @param array $contributionIDs
276 * Array of soft contribution ids, amounts, and associated contact ids
278 public static function getSoftCreditContributionFields($contributionIDs, $all = FALSE) {
282 'pcp_display_in_roll',
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)
293 $queryParams = [1 => [implode(',', $contributionIDs), 'CommaSeparatedIntegers']];
294 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
296 $softContribution = $indexes = [];
297 while ($dao->fetch()) {
300 foreach ($pcpFields as $val) {
301 $softContribution[$dao->contribution_id
][$val] = $dao->$val;
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
;
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
),
322 return $softContribution;
326 * @param int $contributionID
331 public static function getSoftCreditIds($contributionID, $isPCP = FALSE) {
334 FROM civicrm_contribution_soft
335 WHERE contribution_id = %1
339 $query .= " AND pcp_id IS NOT NULL";
342 $query .= " AND pcp_id IS NULL";
344 $params = [1 => [$contributionID, 'Integer']];
346 $dao = CRM_Core_DAO
::executeQuery($query, $params);
349 while ($dao->fetch()) {
359 * Wrapper for ajax soft contribution selector.
361 * @param array $params
362 * Associated array for params.
365 * Associated array of soft contributions
367 public static function getSoftContributionSelector($params) {
369 if (!empty($params['isTest'])) {
370 $isTest = $params['isTest'];
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'];
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']})";
383 $softCreditList = self
::getSoftContributionList($contactId, $filter, $isTest, $params);
385 $softCreditListDT = [];
386 $softCreditListDT['data'] = array_values($softCreditList);
387 $softCreditListDT['recordsTotal'] = $params['total'];
388 $softCreditListDT['recordsFiltered'] = $params['total'];
390 return $softCreditListDT;
394 * Function to retrieve the list of soft contributions for given contact.
396 * @param int $contact_id
398 * @param string $filter
400 * Additional filter criteria, later used in where clause.
401 * @param array $dTParams
405 public static function getSoftContributionList($contact_id, $filter = NULL, $isTest = 0, &$dTParams = NULL) {
406 $config = CRM_Core_Config
::singleton();
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'),
415 $orderBy = 'cc.receive_date DESC';
416 if (!empty($dTParams['sort'])) {
417 $orderBy = $dTParams['sort'];
420 if (!empty($dTParams['rowCount']) && $dTParams['rowCount'] > 0) {
421 $limit = " LIMIT {$dTParams['offset']}, {$dTParams['rowCount']} ";
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');
427 SELECT SQL_CALC_FOUND_ROWS ccs.id, ccs.amount as amount,
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,
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,
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
456 WHERE cc.is_test = %2 AND ccs.contact_id = %1";
461 $query .= "{$where} ORDER BY {$orderBy} {$limit}";
464 1 => [$contact_id, 'Integer'],
465 2 => [$isTest, 'Integer'],
466 3 => [$softOgId, 'Integer'],
467 4 => [$statusOgId, 'Integer'],
469 $cs = CRM_Core_DAO
::executeQuery($query, $params);
471 $dTParams['total'] = CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
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}"
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
;
493 'contributionid' => $cs->contribution_id
,
494 'contactId' => $cs->contributor_id
,
496 $result[$cs->id
]['links'] = CRM_Core_Action
::formLink($links, NULL, $replace);
499 $result[$cs->id
]['contribution_status'] = CRM_Core_TestEntity
::appendTestText($result[$cs->id
]['contribution_status']);
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
510 * @param CRM_Core_Form $form
511 * @param array $params
512 * @param int $honorId
514 public static function formatHonoreeProfileFields($form, $params, $honorId = NULL) {
515 if (empty($form->_values
['honoree_profile_id'])) {
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 = [];
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];
533 //remove name related fields and construct name string with prefix/suffix
534 //which will be later assigned to template
535 switch ($profileContactType) {
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')
541 unset($profileFields['prefix_id']);
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')
550 unset($profileFields['suffix_id']);
555 $honorName = $params['organization_name'];
556 unset($profileFields['organization_name']);
560 $honorName = $params['household_name'];
561 unset($profileFields['household_name']);
566 $honoreeProfileFields['Name'] = $honorName;
567 foreach ($profileFields as $name => $field) {
568 $title = $field['title'];
569 $honoreeProfileFields[$title] = $values[$title];
571 $form->assign('honoreeProfile', $honoreeProfileFields);
574 $form->assign('honorName', $honorName);
579 * Process the pcp associated with a contribution.
582 * @param \CRM_Contribute_BAO_Contribution $contribution
584 * @throws \CRM_Core_Exception
585 * @throws \CiviCRM_API3_Exception
586 * @throws \API_Exception
588 protected static function processPCP($pcp, $contribution) {
589 $pcpId = self
::getSoftCreditIds($contribution->id
, TRUE);
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'
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
)
610 self
::pcpNotifyOwner($contribution->id
, (array) $contributionSoft);
613 //Delete PCP against this contribution and create new on submitted PCP information
615 civicrm_api3('ContributionSoft', 'delete', ['id' => $pcpId]);
620 * Function used to send notification mail to pcp owner.
622 * @param int $contributionID
623 * @param array $contributionSoft
624 * Contribution object.
626 * @throws \API_Exception
627 * @throws \CRM_Core_Exception
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);
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
646 // set email in the template here
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());
652 // get primary location email if no email exist( for billing location).
654 [$donorName, $email] = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contribution['contact_id']);
656 [$ownerName, $ownerEmail] = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contributionSoft['contact_id']);
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'],
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',
678 CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);