Fix reply ordering

This commit is contained in:
Matt Low 2024-12-11 15:56:43 +00:00
parent c261fdadf5
commit d2ce8edad8

View File

@ -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