-
Notifications
You must be signed in to change notification settings - Fork 60
/
ticket_db.go
68 lines (56 loc) · 1.79 KB
/
ticket_db.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package db
import (
"errors"
"fmt"
"time"
"github.com/google/uuid"
"gorm.io/gorm"
)
func (db database) GetTicket(uuid string) (Tickets, error) {
var ticket Tickets
result := db.db.Where("uuid = ?", uuid).First(&ticket)
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return Tickets{}, errors.New("ticket not found")
}
return ticket, result.Error
}
func (db database) UpdateTicket(ticket Tickets) (Tickets, error) {
if ticket.UUID == uuid.Nil {
return Tickets{}, errors.New("ticket UUID is required")
}
if ticket.FeatureUUID == "" || ticket.PhaseUUID == "" || ticket.Name == "" {
return Tickets{}, errors.New("feature_uuid, phase_uuid, and name are required")
}
var existingTicket Tickets
result := db.db.Where("uuid = ?", ticket.UUID).First(&existingTicket)
now := time.Now()
ticket.UpdatedAt = now
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
ticket.CreatedAt = now
if err := db.db.Create(&ticket).Error; err != nil {
return Tickets{}, fmt.Errorf("failed to create ticket: %w", err)
}
return ticket, nil
}
return Tickets{}, fmt.Errorf("database error: %w", result.Error)
}
if err := db.db.Model(&existingTicket).Updates(ticket).Error; err != nil {
return Tickets{}, fmt.Errorf("failed to update ticket: %w", err)
}
var updatedTicket Tickets
if err := db.db.Where("uuid = ?", ticket.UUID).First(&updatedTicket).Error; err != nil {
return Tickets{}, fmt.Errorf("failed to fetch updated ticket: %w", err)
}
return updatedTicket, nil
}
func (db database) DeleteTicket(uuid string) error {
result := db.db.Where("uuid = ?", uuid).Delete(&Tickets{})
if result.Error != nil {
return fmt.Errorf("failed to delete ticket: %w", result.Error)
}
if result.RowsAffected == 0 {
return errors.New("ticket not found")
}
return nil
}