Fixes journentry bug

This commit is contained in:
Victor Broman 2026-02-06 18:49:42 +01:00
parent 3cfa8d7618
commit c51da2a965
4 changed files with 71 additions and 7 deletions

Binary file not shown.

Binary file not shown.

@ -0,0 +1,56 @@
package handlers_test
import (
"net/http/httptest"
"os"
"testing"
"time"
"erp_system/internal/database"
"erp_system/internal/handlers"
"github.com/gorilla/sessions"
)
func TestJournalEntries_List(t *testing.T) {
// Setup temporary DB
dbFile := "test_ledger.db"
db, err := database.Initialize(dbFile)
if err != nil {
t.Fatalf("Failed to initialize DB: %v", err)
}
defer func() {
db.Close()
os.Remove(dbFile)
}()
// Setup Handler
store := sessions.NewCookieStore([]byte("secret"))
h := &handlers.Handler{
DB: db,
Store: store,
}
// Insert a dummy entry so the loop runs
db.Exec("INSERT INTO journal_entries (description) VALUES ('Test')")
// Create a timeout channel to detect freeze
done := make(chan bool)
go func() {
req := httptest.NewRequest("GET", "/ledger/journal", nil)
w := httptest.NewRecorder()
// Execute Handler
h.JournalEntries(w, req)
done <- true
}()
select {
case <-done:
t.Log("Handler completed successfully")
case <-time.After(2 * time.Second):
t.Fatal("Handler timed out - DEADLOCK DETECTED")
}
}

@ -73,7 +73,20 @@ func GLAccountGetByID(db *sql.DB, id int) (*GLAccount, error) {
} }
func JournalEntryGetAll(db *sql.DB) ([]JournalEntry, error) { func JournalEntryGetAll(db *sql.DB) ([]JournalEntry, error) {
rows, err := db.Query("SELECT id, entry_date, description, reference, created_at FROM journal_entries ORDER BY created_at DESC") rows, err := db.Query(`
SELECT
je.id,
je.entry_date,
je.description,
je.reference,
je.created_at,
COALESCE(SUM(jl.debit), 0),
COALESCE(SUM(jl.credit), 0)
FROM journal_entries je
LEFT JOIN journal_lines jl ON je.id = jl.journal_entry_id
GROUP BY je.id
ORDER BY je.created_at DESC
`)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -82,14 +95,9 @@ func JournalEntryGetAll(db *sql.DB) ([]JournalEntry, error) {
var entries []JournalEntry var entries []JournalEntry
for rows.Next() { for rows.Next() {
var je JournalEntry var je JournalEntry
if err := rows.Scan(&je.ID, &je.EntryDate, &je.Description, &je.Reference, &je.CreatedAt); err != nil { if err := rows.Scan(&je.ID, &je.EntryDate, &je.Description, &je.Reference, &je.CreatedAt, &je.TotalDebit, &je.TotalCredit); err != nil {
return nil, err return nil, err
} }
// Get totals
db.QueryRow("SELECT COALESCE(SUM(debit), 0), COALESCE(SUM(credit), 0) FROM journal_lines WHERE journal_entry_id = ?", je.ID).
Scan(&je.TotalDebit, &je.TotalCredit)
entries = append(entries, je) entries = append(entries, je)
} }
return entries, nil return entries, nil