Commit | Line | Data |
---|---|---|
38c87aa2 | 1 | <?php |
2 | ||
3 | require_once 'sequentialcreditnotes.civix.php'; | |
4 | use Civi\Api4\Contribution; | |
5 | ||
38c87aa2 | 6 | /** |
7 | * Add a creditnote_id if appropriate. | |
8 | * | |
9 | * If the contribution is created with cancelled or refunded status, add credit note id | |
bb5eaaf0 TO |
10 | * do the same for chargeback |
11 | * - creditnotes for chargebacks entered the code 'accidentally' but since it did we maintain it. | |
38c87aa2 | 12 | * |
13 | * @param \CRM_Core_DAO $op | |
14 | * @param string $objectName | |
15 | * @param int|null $id | |
16 | * @param array $params | |
17 | * | |
18 | * @throws \CiviCRM_API3_Exception | |
19 | * @throws \API_Exception | |
20 | */ | |
21 | function sequentialcreditnotes_civicrm_pre($op, $objectName, $id, &$params) { | |
22 | if ($objectName === 'Contribution' && !empty($params['contribution_status_id'])) { | |
23 | $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded']; | |
24 | if (empty($params['creditnote_id']) && in_array(CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution_status_id']), $reversalStatuses, TRUE)) { | |
25 | if ($id) { | |
fe806431 | 26 | $existing = Contribution::get(FALSE)->addWhere('id', '=', (int) $id)->setSelect(['creditnote_id'])->execute()->first(); |
38c87aa2 | 27 | if ($existing['creditnote_id']) { |
28 | // Since we have it adding it makes is clearer. | |
29 | $params['creditnote_id'] = $existing['creditnote_id']; | |
30 | return; | |
31 | } | |
32 | } | |
33 | $params['creditnote_id'] = sequentialcreditnotes_create_credit_note_id(); | |
34 | } | |
35 | } | |
36 | } | |
37 | ||
38 | /** | |
39 | * Generate credit note id with next available number | |
40 | * | |
41 | * @return string | |
42 | * Credit Note Id. | |
43 | * | |
44 | * @throws \CiviCRM_API3_Exception | |
45 | */ | |
46 | function sequentialcreditnotes_create_credit_note_id() { | |
47 | ||
48 | $creditNoteNum = CRM_Core_DAO::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution WHERE creditnote_id IS NOT NULL"); | |
49 | $creditNoteId = NULL; | |
50 | ||
51 | do { | |
52 | $creditNoteNum++; | |
53 | $creditNoteId = Civi::settings()->get('credit_notes_prefix') . '' . $creditNoteNum; | |
54 | $result = civicrm_api3('Contribution', 'getcount', [ | |
55 | 'sequential' => 1, | |
56 | 'creditnote_id' => $creditNoteId, | |
57 | ]); | |
58 | } while ($result > 0); | |
59 | ||
60 | return $creditNoteId; | |
61 | } |