3 require_once 'sequentialcreditnotes.civix.php';
4 use Civi\Api4\Contribution
;
7 * Implements hook_civicrm_alterSettingsFolders().
9 * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_alterSettingsFolders
11 function sequentialcreditnotes_civicrm_alterSettingsFolders(&$metaDataFolders = NULL) {
12 _sequentialcreditnotes_civix_civicrm_alterSettingsFolders($metaDataFolders);
16 * Add a creditnote_id if appropriate.
18 * If the contribution is created with cancelled or refunded status, add credit note id
19 * do the same for chargeback
20 * - creditnotes for chargebacks entered the code 'accidentally' but since it did we maintain it.
22 * @param \CRM_Core_DAO $op
23 * @param string $objectName
25 * @param array $params
27 * @throws \CiviCRM_API3_Exception
28 * @throws \API_Exception
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)) {
35 $existing = Contribution
::get(FALSE)->addWhere('id', '=', (int) $id)->setSelect(['creditnote_id'])->execute()->first();
36 if ($existing['creditnote_id']) {
37 // Since we have it adding it makes is clearer.
38 $params['creditnote_id'] = $existing['creditnote_id'];
42 $params['creditnote_id'] = sequentialcreditnotes_create_credit_note_id();
48 * Generate credit note id with next available number
53 * @throws \CiviCRM_API3_Exception
55 function sequentialcreditnotes_create_credit_note_id() {
57 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution WHERE creditnote_id IS NOT NULL");
62 $creditNoteId = Civi
::settings()->get('credit_notes_prefix') . '' . $creditNoteNum;
63 $result = civicrm_api3('Contribution', 'getcount', [
65 'creditnote_id' => $creditNoteId,
67 } while ($result > 0);