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