From f97b92e47eb8f2f101a6fc5540ca9664b5d84004 Mon Sep 17 00:00:00 2001
From: Guanhuan Chen <oooomic@gmail.com>
Date: Tue, 29 Sep 2015 16:59:41 +0100
Subject: [PATCH] Fix credit note sequence issue

---
 CRM/Contribute/Form/Task/Invoice.php | 14 ++++++++++----
 1 file changed, 10 insertions(+), 4 deletions(-)

diff --git a/CRM/Contribute/Form/Task/Invoice.php b/CRM/Contribute/Form/Task/Invoice.php
index a93a3c3bff..27959383ae 100644
--- a/CRM/Contribute/Form/Task/Invoice.php
+++ b/CRM/Contribute/Form/Task/Invoice.php
@@ -312,7 +312,16 @@ class CRM_Contribute_Form_Task_Invoice extends CRM_Contribute_Form_Task {
       }
 
       if ($contribution->contribution_status_id == $refundedStatusId || $contribution->contribution_status_id == $cancelledStatusId) {
-        $creditNoteId = CRM_Utils_Array::value('credit_notes_prefix', $prefixValue) . "" . $contribution->id;
+        if (is_null($contribution->creditnote_id)) {
+          $query = "select count(creditnote_id) as creditnote_number from civicrm_contribution";
+          $dao = CRM_Core_DAO::executeQuery($query);
+          $dao->fetch();
+          $creditNoteId = CRM_Utils_Array::value('credit_notes_prefix', $prefixValue) . "" . ($dao->creditnote_number + 1);
+          CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'creditnote_id', $creditNoteId);
+        }
+        else {
+          $creditNoteId = $contribution->creditnote_id;
+        }
       }
       $invoiceId = CRM_Utils_Array::value('invoice_prefix', $prefixValue) . "" . $contribution->id;
 
@@ -544,9 +553,6 @@ class CRM_Contribute_Form_Task_Invoice extends CRM_Contribute_Form_Task {
       }
 
       CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'invoice_id', $invoiceId);
-      if ($contribution->contribution_status_id == $refundedStatusId || $contribution->contribution_status_id == $cancelledStatusId) {
-        CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'creditnote_id', $creditNoteId);
-      }
       $invoiceTemplate->clearTemplateVars();
     }
 
-- 
2.25.1