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
{
24 public function __construct() {
25 parent
::__construct();
29 * Add contribution soft credit record.
31 * @param array $params
32 * (reference ) an assoc array of name/value pairs.
35 * soft contribution of object that is added
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);
41 $contributionSoft = new CRM_Contribute_DAO_ContributionSoft();
42 $contributionSoft->copyValues($params);
44 // set currency for CRM-1496
45 if (!isset($contributionSoft->currency
)) {
46 $config = CRM_Core_Config
::singleton();
47 $contributionSoft->currency
= $config->defaultCurrency
;
49 $result = $contributionSoft->save();
50 CRM_Utils_Hook
::post($hook, 'ContributionSoft', $contributionSoft->id
, $contributionSoft);
55 * Process the soft contribution and/or link to personal campaign page.
57 * @param array $params
58 * @param CRM_Contribute_BAO_Contribution $contribution
60 * @throws \CRM_Core_Exception
61 * @throws \CiviCRM_API3_Exception
63 public static function processSoftContribution($params, $contribution) {
64 if (array_key_exists('pcp', $params)) {
65 self
::processPCP($params['pcp'], $contribution);
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)) {
73 $softParam['id'] = $softIDs[$key];
74 unset($softIDs[$key]);
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
;
82 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
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]);
95 * Function used to save pcp / soft credit entry.
97 * This is used by contribution and also event pcps
99 * @param array $params
100 * @param object $form
103 public static function formatSoftCreditParams(&$params, &$form) {
104 $pcp = $softParams = $softIDs = [];
105 if (!empty($params['pcp_made_through_id'])) {
107 'pcp_made_through_id',
108 'pcp_display_in_roll',
112 foreach ($fields as $f) {
113 $pcp[$f] = $params[$f] ??
NULL;
117 if (!empty($form->_values
['honoree_profile_id']) && !empty($params['soft_credit_type_id'])) {
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
126 'onbehalf_contact_id' => 0,
128 $except = array_values(array_intersect_key($params, $exceptKeys));
129 $ids = CRM_Contact_BAO_Contact
::getDuplicateContacts(
131 CRM_Core_BAO_UFGroup
::getContactType($form->_values
['honoree_profile_id']),
137 $honorId = $ids[0] ??
NULL;
141 $honorId = CRM_Contact_BAO_Contact
::createProfileContact(
142 $params['honor'], $null,
144 $form->_values
['honoree_profile_id']
147 'contact_id' => $honorId,
148 'soft_credit_type_id' => $params['soft_credit_type_id'],
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")
157 'honor_id' => $honorId,
158 'honor_profile_id' => $form->_values
['honoree_profile_id'],
159 'honor_profile_values' => $params['honor'],
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];
177 $params['pcp'] = !empty($pcp) ?
$pcp : NULL;
178 $params['soft_credit'] = $softParams;
179 $params['soft_credit_ids'] = $softIDs;
183 * Fetch object based on array of properties.
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.
190 * @return CRM_Contribute_BAO_ContributionSoft
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;
203 * @param int $contact_id
208 public static function getSoftContributionTotals($contact_id, $isTest = 0) {
210 $whereClause = "AND cc.cancel_date IS NULL";
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}
220 1 => [$contact_id, 'Integer'],
221 2 => [$isTest, 'Integer'],
224 $cs = CRM_Core_DAO
::executeQuery($query, $params);
226 $count = $countCancelled = 0;
227 $amount = $average = $cancelAmount = [];
229 while ($cs->fetch()) {
230 if ($cs->amount
> 0) {
232 $amount[] = CRM_Utils_Money
::format($cs->amount
, $cs->currency
);
233 $average[] = CRM_Utils_Money
::format($cs->average
, $cs->currency
);
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) {
244 $cancelAmount[] = CRM_Utils_Money
::format($cancelAmountSQL->amount
, $cancelAmountSQL->currency
);
248 if ($count > 0 ||
$countCancelled > 0) {
252 implode(', ', $amount),
253 implode(', ', $average),
254 implode(', ', $cancelAmount),
261 * Retrieve soft contributions for contribution record.
263 * @param int $contributionID
268 * Array of soft contribution ids, amounts, and associated contact ids
270 public static function getSoftContribution($contributionID, $all = FALSE) {
271 $softContributionFields = self
::getSoftCreditContributionFields([$contributionID], $all);
272 return $softContributionFields[$contributionID] ??
[];
276 * Retrieve soft contributions for an array of contribution records.
278 * @param array $contributionIDs
283 * Array of soft contribution ids, amounts, and associated contact ids
285 public static function getSoftCreditContributionFields($contributionIDs, $all = FALSE) {
289 'pcp_display_in_roll',
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)
300 $queryParams = [1 => [implode(',', $contributionIDs), 'CommaSeparatedIntegers']];
301 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
303 $softContribution = $indexes = [];
304 while ($dao->fetch()) {
307 foreach ($pcpFields as $val) {
308 $softContribution[$dao->contribution_id
][$val] = $dao->$val;
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
;
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
),
329 return $softContribution;
333 * @param int $contributionID
338 public static function getSoftCreditIds($contributionID, $isPCP = FALSE) {
341 FROM civicrm_contribution_soft
342 WHERE contribution_id = %1
346 $query .= " AND pcp_id IS NOT NULL";
349 $query .= " AND pcp_id IS NULL";
351 $params = [1 => [$contributionID, 'Integer']];
353 $dao = CRM_Core_DAO
::executeQuery($query, $params);
356 while ($dao->fetch()) {
366 * Wrapper for ajax soft contribution selector.
368 * @param array $params
369 * Associated array for params.
372 * Associated array of soft contributions
374 public static function getSoftContributionSelector($params) {
376 if (!empty($params['isTest'])) {
377 $isTest = $params['isTest'];
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'];
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']})";
390 $softCreditList = self
::getSoftContributionList($contactId, $filter, $isTest, $params);
392 $softCreditListDT = [];
393 $softCreditListDT['data'] = array_values($softCreditList);
394 $softCreditListDT['recordsTotal'] = $params['total'];
395 $softCreditListDT['recordsFiltered'] = $params['total'];
397 return $softCreditListDT;
401 * Function to retrieve the list of soft contributions for given contact.
403 * @param int $contact_id
405 * @param string $filter
407 * Additional filter criteria, later used in where clause.
408 * @param array $dTParams
412 public static function getSoftContributionList($contact_id, $filter = NULL, $isTest = 0, &$dTParams = NULL) {
413 $config = CRM_Core_Config
::singleton();
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'),
422 $orderBy = 'cc.receive_date DESC';
423 if (!empty($dTParams['sort'])) {
424 $orderBy = $dTParams['sort'];
427 if (!empty($dTParams['rowCount']) && $dTParams['rowCount'] > 0) {
428 $limit = " LIMIT {$dTParams['offset']}, {$dTParams['rowCount']} ";
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');
434 SELECT SQL_CALC_FOUND_ROWS ccs.id, ccs.amount as amount,
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,
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,
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
463 WHERE cc.is_test = %2 AND ccs.contact_id = %1";
468 $query .= "{$where} ORDER BY {$orderBy} {$limit}";
471 1 => [$contact_id, 'Integer'],
472 2 => [$isTest, 'Integer'],
473 3 => [$softOgId, 'Integer'],
474 4 => [$statusOgId, 'Integer'],
476 $cs = CRM_Core_DAO
::executeQuery($query, $params);
478 $dTParams['total'] = CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
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}"
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
;
500 'contributionid' => $cs->contribution_id
,
501 'contactId' => $cs->contributor_id
,
503 $result[$cs->id
]['links'] = CRM_Core_Action
::formLink($links, NULL, $replace);
506 $result[$cs->id
]['contribution_status'] = CRM_Core_TestEntity
::appendTestText($result[$cs->id
]['contribution_status']);
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
517 * @param CRM_Core_Form $form
518 * @param array $params
519 * @param int $honorId
521 public static function formatHonoreeProfileFields($form, $params, $honorId = NULL) {
522 if (empty($form->_values
['honoree_profile_id'])) {
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 = [];
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];
540 //remove name related fields and construct name string with prefix/suffix
541 //which will be later assigned to template
542 switch ($profileContactType) {
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')
548 unset($profileFields['prefix_id']);
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')
557 unset($profileFields['suffix_id']);
562 $honorName = $params['organization_name'];
563 unset($profileFields['organization_name']);
567 $honorName = $params['household_name'];
568 unset($profileFields['household_name']);
573 $honoreeProfileFields['Name'] = $honorName;
574 foreach ($profileFields as $name => $field) {
575 $title = $field['title'];
576 $honoreeProfileFields[$title] = $values[$title];
578 $form->assign('honoreeProfile', $honoreeProfileFields);
581 $form->assign('honorName', $honorName);
586 * Process the pcp associated with a contribution.
589 * @param \CRM_Contribute_BAO_Contribution $contribution
591 * @throws \CRM_Core_Exception
592 * @throws \CiviCRM_API3_Exception
593 * @throws \API_Exception
595 protected static function processPCP($pcp, $contribution) {
596 $pcpId = self
::getSoftCreditIds($contribution->id
, TRUE);
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'
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
)
617 self
::pcpNotifyOwner($contribution->id
, (array) $contributionSoft);
620 //Delete PCP against this contribution and create new on submitted PCP information
622 civicrm_api3('ContributionSoft', 'delete', ['id' => $pcpId]);
627 * Function used to send notification mail to pcp owner.
629 * @param int $contributionID
630 * @param array $contributionSoft
631 * Contribution object.
633 * @throws \API_Exception
634 * @throws \CRM_Core_Exception
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);
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
653 // set email in the template here
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());
659 // get primary location email if no email exist( for billing location).
661 [$donorName, $email] = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contribution['contact_id']);
663 [$ownerName, $ownerEmail] = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contributionSoft['contact_id']);
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'],
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',
685 CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);