3 require_once 'sequentialcreditnotes.civix.php';
4 use Civi\Api4\Contribution
;
7 * Add a creditnote_id if appropriate.
9 * If the contribution is created with cancelled or refunded status, add credit note id
10 * do the same for chargeback
11 * - creditnotes for chargebacks entered the code 'accidentally' but since it did we maintain it.
13 * @param \CRM_Core_DAO $op
14 * @param string $objectName
16 * @param array $params
18 * @throws \CiviCRM_API3_Exception
19 * @throws \API_Exception
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)) {
26 $existing = Contribution
::get(FALSE)->addWhere('id', '=', (int) $id)->setSelect(['creditnote_id'])->execute()->first();
27 if ($existing['creditnote_id']) {
28 // Since we have it adding it makes is clearer.
29 $params['creditnote_id'] = $existing['creditnote_id'];
33 $params['creditnote_id'] = sequentialcreditnotes_create_credit_note_id();
39 * Generate credit note id with next available number
44 * @throws \CiviCRM_API3_Exception
46 function sequentialcreditnotes_create_credit_note_id() {
48 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution WHERE creditnote_id IS NOT NULL");
53 $creditNoteId = Civi
::settings()->get('credit_notes_prefix') . '' . $creditNoteNum;
54 $result = civicrm_api3('Contribution', 'getcount', [
56 'creditnote_id' => $creditNoteId,
58 } while ($result > 0);