From f169571cffeb3ac0404d56ac01ece90c33338113 Mon Sep 17 00:00:00 2001 From: Vidhu Kant Sharma Date: Sun, 3 Dec 2023 20:53:42 +0530 Subject: setting invoice number as 1 if no invoices exist --- invoice/service.go | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) (limited to 'invoice/service.go') diff --git a/invoice/service.go b/invoice/service.go index 3dcc5e2..9408a0d 100644 --- a/invoice/service.go +++ b/invoice/service.go @@ -25,8 +25,28 @@ import ( func getNewInvoiceNumber(userId uint) (uint, error) { var i uint + // check if number of invoices is 0 + var count int64 + err := db.Model(&Invoice{}). + Where("user_id = ?", userId). + Count(&count). + Error + + if err != nil { + return i, err + } + + // if no records exist, then invoice number should be 1 + if count == 0 { + return 1, nil + } + + // if records exist, get max invoice number + // NOTE: if there are gaps in invoice numbers, + // they won't be filled and the series would continue + // from the greatest invoice number. row := db.Model(&Invoice{}).Where("user_id = ?", userId).Select("max(invoice_number)").Row() - err := row.Scan(&i) + err = row.Scan(&i) return i + 1, err } -- cgit v1.2.3