From d2ce8edad80476f65c3b29dc1a862ddf8213b907 Mon Sep 17 00:00:00 2001 From: Matt Low Date: Wed, 11 Dec 2024 15:56:43 +0000 Subject: [PATCH] Fix reply ordering --- pkg/conversation/repo.go | 42 +++++++++------------------------------- 1 file changed, 9 insertions(+), 33 deletions(-) diff --git a/pkg/conversation/repo.go b/pkg/conversation/repo.go index f817cc3..4343562 100644 --- a/pkg/conversation/repo.go +++ b/pkg/conversation/repo.go @@ -298,39 +298,36 @@ func (s *repo) CloneBranch(messageToClone Message) (*Message, uint, error) { func fetchMessages(db *gorm.DB) ([]Message, error) { var messages []Message - if err := db.Preload("Conversation").Find(&messages).Error; err != nil { + if err := db.Preload("Conversation").Order("id ASC").Find(&messages).Error; err != nil { return nil, fmt.Errorf("Could not fetch messages: %v", err) } - messageMap := make(map[uint]Message) + messageMap := make(map[uint]*Message) for i, message := range messages { - messageMap[messages[i].ID] = message + messageMap[message.ID] = &messages[i] } // Create a map to store replies by their parent ID repliesMap := make(map[uint][]Message) - for i, message := range messages { - if messages[i].ParentID != nil { - repliesMap[*messages[i].ParentID] = append(repliesMap[*messages[i].ParentID], message) + for _, message := range messages { + if message.ParentID != nil { + repliesMap[*message.ParentID] = append(repliesMap[*message.ParentID], message) } } // Assign replies, parent, and selected reply to each message for i := range messages { if replies, exists := repliesMap[messages[i].ID]; exists { - messages[i].Replies = make([]Message, len(replies)) - for j, m := range replies { - messages[i].Replies[j] = m - } + messages[i].Replies = replies } if messages[i].ParentID != nil { if parent, exists := messageMap[*messages[i].ParentID]; exists { - messages[i].Parent = &parent + messages[i].Parent = parent } } if messages[i].SelectedReplyID != nil { if selectedReply, exists := messageMap[*messages[i].SelectedReplyID]; exists { - messages[i].SelectedReply = &selectedReply + messages[i].SelectedReply = selectedReply } } } @@ -359,27 +356,6 @@ func (s *repo) buildPath(message *Message, getNext func(*Message) *uint) ([]Mess messageMap[messages[i].ID] = &messages[i] } - // Construct Replies - repliesMap := make(map[uint][]*Message, len(messages)) - for _, m := range messageMap { - if m.ParentID == nil { - continue - } - if p, ok := messageMap[*m.ParentID]; ok { - repliesMap[p.ID] = append(repliesMap[p.ID], m) - } - } - - // Add replies to messages - for _, m := range messageMap { - if replies, ok := repliesMap[m.ID]; ok { - m.Replies = make([]Message, len(replies)) - for idx, reply := range replies { - m.Replies[idx] = *reply - } - } - } - // Build the path var path []Message nextID := &message.ID