forked from civicrm/civicrm-core
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathContribution.php
5449 lines (4969 loc) · 208 KB
/
Contribution.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
use Civi\Api4\Activity;
use Civi\Api4\ActivityContact;
use Civi\Api4\Contribution;
use Civi\Api4\ContributionRecur;
use Civi\Api4\PaymentProcessor;
use Civi\Api4\PledgePayment;
/**
*
* @package CRM
* @copyright CiviCRM LLC https://civicrm.org/licensing
*/
class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution {
/**
* Static field for all the contribution information that we can potentially import
*
* @var array
*/
public static $_importableFields = NULL;
/**
* Static field for all the contribution information that we can potentially export
*
* @var array
*/
public static $_exportableFields = NULL;
/**
* Static field to hold financial trxn id's.
*
* @var array
*/
public static $_trxnIDs = NULL;
/**
* Field for all the objects related to this contribution.
*
* This is used from
* 1) deprecated function transitionComponents
* 2) function to send contribution receipts _assignMessageVariablesToTemplate
* 3) some invoice code that is copied from 2
* 4) odds & sods that need to be investigated and fixed.
*
* However, it is no longer used by completeOrder.
*
* @var \CRM_Member_BAO_Membership|\CRM_Event_BAO_Participant[]
*
* @deprecated
*/
public $_relatedObjects = [];
/**
* Field for the component - either 'event' (participant) or 'contribute'
* (any item related to a contribution page e.g. membership, pledge, contribution)
* This is used for composing messages because they have dependency on the
* contribution_page or event page - although over time we may eliminate that
*
* @var string
* "contribution"\"event"
*/
public $_component = NULL;
/**
* Possibly obsolete variable.
*
* If you use it please explain why it is set in the create function here.
*
* @var string
*/
public $trxn_result_code;
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
}
/**
* Takes an associative array and creates a contribution object.
*
* the function extract all the params it needs to initialize the create a
* contribution object. the params array could contain additional unused name/value
* pairs
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*
* @return \CRM_Contribute_BAO_Contribution
* @throws \CRM_Core_Exception
* @throws \CiviCRM_API3_Exception
*/
public static function add(&$params) {
if (empty($params)) {
return NULL;
}
$contributionID = $params['id'] ?? NULL;
$action = $contributionID ? 'edit' : 'create';
$duplicates = [];
if (self::checkDuplicate($params, $duplicates, $contributionID)) {
$message = ts("Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: %1", [1 => implode(', ', $duplicates)]);
throw new CRM_Core_Exception($message);
}
//set defaults in create mode
if (!$contributionID) {
CRM_Core_DAO::setCreateDefaults($params, self::getDefaults());
if (empty($params['invoice_number']) && CRM_Invoicing_Utils::isInvoicingEnabled()) {
$nextContributionID = CRM_Core_DAO::singleValueQuery("SELECT COALESCE(MAX(id) + 1, 1) FROM civicrm_contribution");
$params['invoice_number'] = self::getInvoiceNumber($nextContributionID);
}
}
$contributionStatusID = $params['contribution_status_id'] ?? NULL;
if (CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $contributionStatusID) === 'Partially paid' && empty($params['is_post_payment_create'])) {
CRM_Core_Error::deprecatedFunctionWarning('Setting status to partially paid other than by using Payment.create is deprecated and unreliable');
}
if (!$contributionStatusID) {
// Since the fee amount is expecting this (later on) ensure it is always set.
// It would only not be set for an update where it is unchanged.
$params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', [
'id' => $contributionID,
'return' => 'contribution_status_id',
]);
}
$contributionStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['contribution_status_id']);
if (!$contributionID
&& !empty($params['membership_id'])
&& Civi::settings()->get('deferred_revenue_enabled')
) {
$memberStartDate = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
if ($memberStartDate) {
$params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
}
}
self::calculateMissingAmountParams($params, $contributionID);
if (!empty($params['payment_instrument_id'])) {
$paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument('name');
if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
$params['check_number'] = 'null';
}
}
$setPrevContribution = TRUE;
if ($contributionID && $setPrevContribution) {
$params['prevContribution'] = self::getOriginalContribution($contributionID);
}
$previousContributionStatus = ($contributionID && !empty($params['prevContribution'])) ? CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['prevContribution']->contribution_status_id) : NULL;
if ($contributionID && !empty($params['revenue_recognition_date'])
&& !($previousContributionStatus === 'Pending')
&& !self::allowUpdateRevenueRecognitionDate($contributionID)
) {
unset($params['revenue_recognition_date']);
}
// Get Line Items if we don't have them already.
if (empty($params['line_item'])) {
if (isset($params['id'])) {
CRM_Price_BAO_LineItem::getLineItemArray($params, [$params['id']]);
}
else {
CRM_Price_BAO_LineItem::getLineItemArray($params);
}
}
if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
isset($params['financial_type_id']))) {
$params = CRM_Contribute_BAO_Contribution::checkTaxAmount($params);
}
CRM_Utils_Hook::pre($action, 'Contribution', $contributionID, $params);
$contribution = new CRM_Contribute_BAO_Contribution();
$contribution->copyValues($params);
$contribution->id = $contributionID;
if (empty($contribution->id)) {
// (only) on 'create', make sure that a valid currency is set (CRM-16845)
if (!CRM_Utils_Rule::currencyCode($contribution->currency)) {
$contribution->currency = CRM_Core_Config::singleton()->defaultCurrency;
}
}
$result = $contribution->save();
// Add financial_trxn details as part of fix for CRM-4724
$contribution->trxn_result_code = $params['trxn_result_code'] ?? NULL;
$contribution->payment_processor = $params['payment_processor'] ?? NULL;
//add Account details
$params['contribution'] = $contribution;
if (empty($params['is_post_payment_create'])) {
// If this is being called from the Payment.create api/ BAO then that Entity
// takes responsibility for the financial transactions. In fact calling Payment.create
// to add payments & having it call completetransaction and / or contribution.create
// to update related entities is the preferred flow.
// Note that leveraging this parameter for any other code flow is not supported and
// is likely to break in future and / or cause serious problems in your data.
// https://github.com/civicrm/civicrm-core/pull/14673
self::recordFinancialAccounts($params);
}
if (self::isUpdateToRecurringContribution($params)) {
CRM_Contribute_BAO_ContributionRecur::updateOnNewPayment(
(!empty($params['contribution_recur_id']) ? $params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id),
$contributionStatus,
$params['receive_date'] ?? 'now'
);
}
$params['contribution_id'] = $contribution->id;
if (!empty($params['custom']) &&
is_array($params['custom'])
) {
CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id, $action);
}
CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
CRM_Utils_Hook::post($action, 'Contribution', $contribution->id, $contribution);
return $result;
}
/**
* Is this contribution updating an existing recurring contribution.
*
* We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
* pending payment is being confirmed (or failing).
*
* @param array $params
*
* @return bool
*/
public static function isUpdateToRecurringContribution($params) {
if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
return TRUE;
}
if (empty($params['prevContribution']) || empty($params['contribution_status_id'])) {
return FALSE;
}
if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id)) {
return FALSE;
}
$contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
if ($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)) {
return TRUE;
}
return FALSE;
}
/**
* Get defaults for new entity.
*
* @return array
*/
public static function getDefaults() {
return [
'payment_instrument_id' => key(CRM_Core_OptionGroup::values('payment_instrument',
FALSE, FALSE, FALSE, 'AND is_default = 1')
),
'contribution_status_id' => CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
'receive_date' => date('Y-m-d H:i:s'),
];
}
/**
* Fetch the object and store the values in the values array.
*
* @param array $params
* Input parameters to find object.
* @param array $values
* Output values of the object.
* @param array $ids
* The array that holds all the db ids.
*
* @return CRM_Contribute_BAO_Contribution|null
* The found object or null
*/
public static function getValues($params, &$values = [], &$ids = []) {
if (empty($params)) {
return NULL;
}
$contribution = new CRM_Contribute_BAO_Contribution();
$contribution->copyValues($params);
if ($contribution->find(TRUE)) {
$ids['contribution'] = $contribution->id;
CRM_Core_DAO::storeValues($contribution, $values);
return $contribution;
}
// return by reference
$null = NULL;
return $null;
}
/**
* Get the values and resolve the most common mappings.
*
* Since contribution status is resolved in almost every function that calls getValues it makes
* sense to have an extra function to resolve it rather than repeat the code.
*
* Think carefully before adding more mappings to be resolved as there could be performance implications
* if this function starts to be called from more iterative functions.
*
* @param array $params
* Input parameters to find object.
*
* @return array
* Array of the found contribution.
* @throws CRM_Core_Exception
*/
public static function getValuesWithMappings($params) {
$values = $ids = [];
$contribution = self::getValues($params, $values, $ids);
if (is_null($contribution)) {
throw new CRM_Core_Exception('No contribution found');
}
$values['contribution_status'] = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
return $values;
}
/**
* Calculate net_amount & fee_amount if they are not set.
*
* Net amount should be total - fee.
* This should only be called for new contributions.
*
* @param array $params
* Params for a new contribution before they are saved.
* @param int|null $contributionID
* Contribution ID if we are dealing with an update.
*
* @throws \CiviCRM_API3_Exception
*/
public static function calculateMissingAmountParams(&$params, $contributionID) {
if (!$contributionID && (!isset($params['fee_amount']) || $params['fee_amount'] === '')) {
if (isset($params['total_amount']) && isset($params['net_amount'])) {
$params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
}
else {
$params['fee_amount'] = 0;
}
}
if (!isset($params['net_amount'])) {
if (!$contributionID) {
$params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
}
else {
if (isset($params['fee_amount']) || isset($params['total_amount'])) {
// We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
// net_amount may need adjusting.
$contribution = civicrm_api3('Contribution', 'getsingle', [
'id' => $contributionID,
'return' => ['total_amount', 'net_amount', 'fee_amount'],
]);
$totalAmount = (isset($params['total_amount']) ? (float) $params['total_amount'] : (float) CRM_Utils_Array::value('total_amount', $contribution));
$feeAmount = (isset($params['fee_amount']) ? (float) $params['fee_amount'] : (float) CRM_Utils_Array::value('fee_amount', $contribution));
$params['net_amount'] = $totalAmount - $feeAmount;
}
}
}
}
/**
* @param $params
* @param $billingLocationTypeID
*
* @return array
*/
protected static function getBillingAddressParams($params, $billingLocationTypeID) {
$hasBillingField = FALSE;
$billingFields = [
'street_address',
'city',
'state_province_id',
'postal_code',
'country_id',
];
//build address array
$addressParams = [];
$addressParams['location_type_id'] = $billingLocationTypeID;
$addressParams['is_billing'] = 1;
$billingFirstName = $params['billing_first_name'] ?? NULL;
$billingMiddleName = $params['billing_middle_name'] ?? NULL;
$billingLastName = $params['billing_last_name'] ?? NULL;
$addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingMiddleName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingLastName}";
foreach ($billingFields as $value) {
$addressParams[$value] = $params["billing_{$value}-{$billingLocationTypeID}"] ?? NULL;
if (!empty($addressParams[$value])) {
$hasBillingField = TRUE;
}
}
return [$hasBillingField, $addressParams];
}
/**
* Get address params ready to be passed to the payment processor.
*
* We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
* To create an address we need state_province_id.
*
* @param array $params
* @param int $billingLocationTypeID
*
* @return array
*/
public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
[$hasBillingField, $addressParams] = self::getBillingAddressParams($params, $billingLocationTypeID);
foreach ($addressParams as $name => $field) {
if (substr($name, 0, 8) == 'billing_') {
$addressParams[substr($name, 9)] = $addressParams[$field];
}
}
return [$hasBillingField, $addressParams];
}
/**
* Get the number of terms for this contribution for a given membership type
* based on querying the line item table and relevant price field values
* Note that any one contribution should only be able to have one line item relating to a particular membership
* type
*
* @param int $membershipTypeID
*
* @param int $contributionID
*
* @return int
*/
public static function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
$numTerms = CRM_Core_DAO::singleValueQuery("
SELECT membership_num_terms FROM civicrm_line_item li
LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
WHERE contribution_id = %1 AND membership_type_id = %2",
[1 => [$contributionID, 'Integer'], 2 => [$membershipTypeID, 'Integer']]
);
// default of 1 is precautionary
return empty($numTerms) ? 1 : $numTerms;
}
/**
* Takes an associative array and creates a contribution object.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*
* @return CRM_Contribute_BAO_Contribution
*
* @throws \API_Exception
* @throws \CRM_Core_Exception
* @throws \CiviCRM_API3_Exception
*/
public static function create(&$params) {
$transaction = new CRM_Core_Transaction();
try {
$contribution = self::add($params);
}
catch (CRM_Core_Exception $e) {
$transaction->rollback();
throw $e;
}
$params['contribution_id'] = $contribution->id;
$session = CRM_Core_Session::singleton();
if (!empty($params['note'])) {
$noteParams = [
'entity_table' => 'civicrm_contribution',
'note' => $params['note'],
'entity_id' => $contribution->id,
'contact_id' => $session->get('userID'),
];
if (!$noteParams['contact_id']) {
$noteParams['contact_id'] = $params['contact_id'];
}
CRM_Core_BAO_Note::add($noteParams);
}
CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution);
if (!empty($params['id']) && !empty($params['contribution_status_id'])
) {
self::disconnectPledgePaymentsIfCancelled((int) $params['id'], CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution_status_id']));
}
$transaction->commit();
if (empty($contribution->contact_id)) {
$contribution->find(TRUE);
}
$isCompleted = ('Completed' === CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id));
if (!empty($params['on_behalf'])
|| $isCompleted
) {
$existingActivity = Activity::get(FALSE)->setWhere([
['source_record_id', '=', $contribution->id],
['activity_type_id:name', '=', 'Contribution'],
])->execute()->first();
$campaignParams = isset($params['campaign_id']) ? ['campaign_id' => ($params['campaign_id'] ?? NULL)] : [];
$activityParams = array_merge([
'activity_type_id:name' => 'Contribution',
'source_record_id' => $contribution->id,
'activity_date_time' => $contribution->receive_date,
'is_test' => (bool) $contribution->is_test,
'status_id:name' => $isCompleted ? 'Completed' : 'Scheduled',
'skipRecentView' => TRUE,
'subject' => CRM_Activity_BAO_Activity::getActivitySubject($contribution),
'id' => $existingActivity['id'] ?? NULL,
], $campaignParams);
if (!$activityParams['id']) {
$activityParams['source_contact_id'] = (int) ($params['source_contact_id'] ?? (CRM_Core_Session::getLoggedInContactID() ?: $contribution->contact_id));
$activityParams['target_contact_id'] = ($activityParams['source_contact_id'] === (int) $contribution->contact_id) ? [] : [$contribution->contact_id];
}
else {
list($sourceContactId, $targetContactId) = self::getActivitySourceAndTarget($activityParams['id']);
if (empty($targetContactId) && $sourceContactId != $contribution->contact_id) {
// If no target contact exists and the source contact is not equal to
// the contribution contact, update the source contact
$activityParams['source_contact_id'] = $contribution->contact_id;
}
elseif (isset($targetContactId) && $targetContactId != $contribution->contact_id) {
// If a target contact exists and it is not equal to the contribution
// contact, update the target contact
$activityParams['target_contact_id'] = [$contribution->contact_id];
}
}
Activity::save(FALSE)->addRecord($activityParams)->execute();
}
// do not add to recent items for import, CRM-4399
if (empty($params['skipRecentView'])) {
$url = CRM_Utils_System::url('civicrm/contact/view/contribution',
"action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
);
// in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
$titleFields = [
'contact_id',
'total_amount',
'currency',
'financial_type_id',
];
$retrieveRequired = 0;
foreach ($titleFields as $titleField) {
if (!isset($contribution->$titleField)) {
$retrieveRequired = 1;
break;
}
}
if ($retrieveRequired == 1) {
$contribution->find(TRUE);
}
$financialType = CRM_Contribute_PseudoConstant::financialType($contribution->financial_type_id);
$title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $financialType . ')';
$recentOther = [];
if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) {
$recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
"action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
);
}
if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) {
$recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
"action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
);
}
// add the recently created Contribution
CRM_Utils_Recent::add($title,
$url,
$contribution->id,
'Contribution',
$contribution->contact_id,
NULL,
$recentOther
);
}
return $contribution;
}
/**
* Get the values for pseudoconstants for name->value and reverse.
*
* @param array $defaults
* (reference) the default values, some of which need to be resolved.
* @param bool $reverse
* True if we want to resolve the values in the reverse direction (value -> name).
*/
public static function resolveDefaults(&$defaults, $reverse = FALSE) {
self::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant::financialType(), $reverse);
self::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant::paymentInstrument(), $reverse);
self::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'label'), $reverse);
self::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant::pcPage(), $reverse);
}
/**
* Convert associative array names to values and vice-versa.
*
* This function is used by both the web form layer and the api. Note that
* the api needs the name => value conversion, also the view layer typically
* requires value => name conversion
*
* @param array $defaults
* @param string $property
* @param array $lookup
* @param bool $reverse
*
* @return bool
*/
public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
$id = $property . '_id';
$src = $reverse ? $property : $id;
$dst = $reverse ? $id : $property;
if (!array_key_exists($src, $defaults)) {
return FALSE;
}
$look = $reverse ? array_flip($lookup) : $lookup;
if (is_array($look)) {
if (!array_key_exists($defaults[$src], $look)) {
return FALSE;
}
}
$defaults[$dst] = $look[$defaults[$src]];
return TRUE;
}
/**
* Retrieve DB object based on input parameters.
*
* It also stores all the retrieved values in the default array.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the name / value pairs.
* in a hierarchical manner
* @param array $ids
* (reference) the array that holds all the db ids.
*
* @return CRM_Contribute_BAO_Contribution
*/
public static function retrieve(&$params, &$defaults = [], &$ids = []) {
$contribution = CRM_Contribute_BAO_Contribution::getValues($params, $defaults, $ids);
return $contribution;
}
/**
* Combine all the importable fields from the lower levels object.
*
* The ordering is important, since currently we do not have a weight
* scheme. Adding weight is super important and should be done in the
* next week or so, before this can be called complete.
*
* @param string $contactType
* @param bool $status
*
* @return array
* array of importable Fields
*/
public static function &importableFields($contactType = 'Individual', $status = TRUE) {
if (!self::$_importableFields) {
if (!self::$_importableFields) {
self::$_importableFields = [];
}
if (!$status) {
$fields = ['' => ['title' => ts('- do not import -')]];
}
else {
$fields = ['' => ['title' => ts('- Contribution Fields -')]];
}
$note = CRM_Core_DAO_Note::import();
$tmpFields = CRM_Contribute_DAO_Contribution::import();
unset($tmpFields['option_value']);
$optionFields = CRM_Core_OptionValue::getFields($mode = 'contribute');
$contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
// Using new Dedupe rule.
$ruleParams = [
'contact_type' => $contactType,
'used' => 'Unsupervised',
];
$fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
$tmpContactField = [];
if (is_array($fieldsArray)) {
foreach ($fieldsArray as $value) {
//skip if there is no dupe rule
if ($value == 'none') {
continue;
}
$customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
$value,
'id',
'column_name'
);
$value = $customFieldId ? 'custom_' . $customFieldId : $value;
$tmpContactField[trim($value)] = $contactFields[trim($value)];
if (!$status) {
$title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
}
else {
$title = $tmpContactField[trim($value)]['title'];
}
$tmpContactField[trim($value)]['title'] = $title;
}
}
$tmpContactField['external_identifier'] = $contactFields['external_identifier'];
$tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
$tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
$fields = array_merge($fields, $tmpContactField);
$fields = array_merge($fields, $tmpFields);
$fields = array_merge($fields, $note);
$fields = array_merge($fields, $optionFields);
$fields = array_merge($fields, CRM_Financial_DAO_FinancialType::export());
$fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
self::$_importableFields = $fields;
}
return self::$_importableFields;
}
/**
* Combine all the exportable fields from the lower level objects.
*
* @param bool $checkPermission
*
* @return array
* array of exportable Fields
*/
public static function &exportableFields($checkPermission = TRUE) {
if (!self::$_exportableFields) {
if (!self::$_exportableFields) {
self::$_exportableFields = [];
}
$fields = CRM_Contribute_DAO_Contribution::export();
if (CRM_Contribute_BAO_Query::isSiteHasProducts()) {
$fields = array_merge(
$fields,
CRM_Contribute_DAO_Product::export(),
CRM_Contribute_DAO_ContributionProduct::export(),
// CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
[
'contribution_product_id' => [
'title' => ts('Premium'),
'name' => 'contribution_product_id',
'where' => 'civicrm_product.id',
'data_type' => CRM_Utils_Type::T_INT,
],
]
);
}
$financialAccount = CRM_Financial_DAO_FinancialAccount::export();
$contributionPage = [
'contribution_page' => [
'title' => ts('Contribution Page'),
'name' => 'contribution_page',
'where' => 'civicrm_contribution_page.title',
'data_type' => CRM_Utils_Type::T_STRING,
],
];
$contributionNote = [
'contribution_note' => [
'title' => ts('Contribution Note'),
'name' => 'contribution_note',
'data_type' => CRM_Utils_Type::T_TEXT,
],
];
$extraFields = [
'contribution_batch' => [
'title' => ts('Batch Name'),
],
];
// CRM-17787
$campaignTitle = [
'contribution_campaign_title' => [
'title' => ts('Campaign Title'),
'name' => 'campaign_title',
'where' => 'civicrm_campaign.title',
'data_type' => CRM_Utils_Type::T_STRING,
],
];
$softCreditFields = [
'contribution_soft_credit_name' => [
'name' => 'contribution_soft_credit_name',
'title' => ts('Soft Credit For'),
'where' => 'civicrm_contact_d.display_name',
'data_type' => CRM_Utils_Type::T_STRING,
],
'contribution_soft_credit_amount' => [
'name' => 'contribution_soft_credit_amount',
'title' => ts('Soft Credit Amount'),
'where' => 'civicrm_contribution_soft.amount',
'data_type' => CRM_Utils_Type::T_MONEY,
],
'contribution_soft_credit_type' => [
'name' => 'contribution_soft_credit_type',
'title' => ts('Soft Credit Type'),
'where' => 'contribution_softcredit_type.label',
'data_type' => CRM_Utils_Type::T_STRING,
],
'contribution_soft_credit_contribution_id' => [
'name' => 'contribution_soft_credit_contribution_id',
'title' => ts('Soft Credit For Contribution ID'),
'where' => 'civicrm_contribution_soft.contribution_id',
'data_type' => CRM_Utils_Type::T_INT,
],
'contribution_soft_credit_contact_id' => [
'name' => 'contribution_soft_credit_contact_id',
'title' => ts('Soft Credit For Contact ID'),
'where' => 'civicrm_contact_d.id',
'data_type' => CRM_Utils_Type::T_INT,
],
];
$fields = array_merge($fields, $contributionPage,
$contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle,
CRM_Core_BAO_CustomField::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
);
self::$_exportableFields = $fields;
}
return self::$_exportableFields;
}
/**
* Record an activity when a payment is received.
*
* @todo this is intended to be moved to payment BAO class as a protected function
* on that class. Currently being cleaned up. The addActivityForPayment doesn't really
* merit it's own function as it makes the code less rather than more readable.
*
* @param int $contributionId
* @param int $participantId
* @param string $totalAmount
* @param string $currency
* @param string $trxnDate
*
* @throws \CRM_Core_Exception
* @throws \CiviCRM_API3_Exception
*/
public static function recordPaymentActivity($contributionId, $participantId, $totalAmount, $currency, $trxnDate) {
$activityType = ($totalAmount < 0) ? 'Refund' : 'Payment';
if ($participantId) {
$inputParams['id'] = $participantId;
$values = [];
$ids = [];
$entityObj = CRM_Event_BAO_Participant::getValues($inputParams, $values, $ids);
$entityObj = $entityObj[$participantId];
$title = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id, 'title');
}
else {
$entityObj = new CRM_Contribute_BAO_Contribution();
$entityObj->id = $contributionId;
$entityObj->find(TRUE);
$title = ts('Contribution');
}
// @todo per block above this is not a logical splitting off of functionality.
self::addActivityForPayment($entityObj->contact_id, $activityType, $title, $contributionId, $totalAmount, $currency, $trxnDate);
}
/**
* Get the value for the To Financial Account.
*
* @param $contribution
* @param $params
*
* @return int
*/
public static function getToFinancialAccount($contribution, $params) {
if (!empty($params['payment_processor_id'])) {
return CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($params['payment_processor_id'], NULL, 'civicrm_payment_processor');
}
if (!empty($params['payment_instrument_id'])) {
return CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
}
else {
$relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
$queryParams = [1 => [$relationTypeId, 'Integer']];
return CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
}
}
/**
* Get memberships related to the contribution.
*
* @param int $contributionID
*
* @return array
*/
protected static function getRelatedMemberships($contributionID) {
$membershipPayments = civicrm_api3('MembershipPayment', 'get', [
'return' => 'membership_id',
'contribution_id' => (int) $contributionID,
])['values'];
$membershipIDs = [];
foreach ($membershipPayments as $membershipPayment) {
$membershipIDs[] = $membershipPayment['membership_id'];
}
if (empty($membershipIDs)) {
return [];
}
// We could combine this with the MembershipPayment.get - we'd
// need to re-wrangle the params (here or in the calling function)
// as they would then me membership.contact_id, membership.is_test etc
return civicrm_api3('Membership', 'get', [
'id' => ['IN' => $membershipIDs],
'return' => ['id', 'contact_id', 'membership_type_id', 'is_test', 'status_id', 'end_date'],
])['values'];
}
/**
* Do any accounting updates required as a result of a contribution status change.
*
* Currently we have a bit of a roundabout where adding a payment results in this being called &
* this may attempt to add a payment. We need to resolve that....
*
* The 'right' way to add payments or refunds is through the Payment.create api. That api
* then updates the contribution but this process should not also record another financial trxn.
* Currently we have weak detection fot that scenario & where it is detected the first returned
* value is FALSE - meaning 'do not continue'.
*
* We should also look at the fact that the calling function - updateFinancialAccounts
* bunches together some disparate processes rather than having separate appropriate
* functions.
*
* @param array $params
*
* @return bool
* Return indicates whether the updateFinancialAccounts function should continue.
*/
private static function updateFinancialAccountsOnContributionStatusChange(&$params) {
$previousContributionStatus = CRM_Contribute_PseudoConstant::contributionStatus($params['prevContribution']->contribution_status_id, 'name');
$currentContributionStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id);
if ((($previousContributionStatus == 'Partially paid' && $currentContributionStatus == 'Completed')
|| ($previousContributionStatus == 'Pending refund' && $currentContributionStatus == 'Completed')
// This concept of pay_later as different to any other sort of pending is deprecated & it's unclear
// why it is here or where it is handled instead.
|| ($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later == TRUE
&& $currentContributionStatus == 'Partially paid'))
) {
return FALSE;
}
if (self::isContributionUpdateARefund($params['prevContribution']->contribution_status_id, $params['contribution']->contribution_status_id)) {
// @todo we should stop passing $params by reference - splitting this out would be a step towards that.
$params['trxnParams']['total_amount'] = -$params['total_amount'];
}
elseif (($previousContributionStatus == 'Pending'
&& $params['prevContribution']->is_pay_later) || $previousContributionStatus == 'In Progress'
) {
$financialTypeID = !empty($params['financial_type_id']) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id;
$arAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
if ($currentContributionStatus == 'Cancelled') {
// @todo we should stop passing $params by reference - splitting this out would be a step towards that.
$params['trxnParams']['to_financial_account_id'] = $arAccountId;
$params['trxnParams']['total_amount'] = -$params['total_amount'];
}