This commit is contained in:
lubiana 2025-07-25 16:15:22 +02:00
parent ebd50740f0
commit 1a6d7291c4
Signed by: lubiana
SSH key fingerprint: SHA256:vW1EA0fRR3Fw+dD/sM0K+x3Il2gSry6YRYHqOeQwrfk
6 changed files with 496 additions and 75 deletions

241
main.go
View file

@ -29,13 +29,14 @@ type Checklist struct {
}
type ChecklistItem struct {
ID int `json:"id"`
Content string `json:"content"`
Checked bool `json:"checked"`
ParentID *int `json:"parent_id"`
LockedBy *string `json:"locked_by,omitempty"`
LockUntil *time.Time `json:"lock_until,omitempty"`
Checklist string `json:"checklist_uuid"`
ID int `json:"id"`
Content string `json:"content"`
Checked bool `json:"checked"`
ParentID *int `json:"parent_id"`
LockedBy *string `json:"locked_by,omitempty"`
LockUntil *time.Time `json:"lock_until,omitempty"`
Checklist string `json:"checklist_uuid"`
Dependencies []int `json:"dependencies,omitempty"`
}
type ItemLock struct {
@ -79,6 +80,14 @@ func getChecklistDB(uuid string) (*sql.DB, error) {
parent_id INTEGER,
FOREIGN KEY(parent_id) REFERENCES items(id)
);`,
`CREATE TABLE IF NOT EXISTS dependencies (
item_id INTEGER NOT NULL,
dependency_id INTEGER NOT NULL,
PRIMARY KEY (item_id, dependency_id),
FOREIGN KEY(item_id) REFERENCES items(id) ON DELETE CASCADE,
FOREIGN KEY(dependency_id) REFERENCES items(id) ON DELETE CASCADE,
CHECK(item_id != dependency_id)
);`,
}
for _, q := range queries {
if _, err := db.Exec(q); err != nil {
@ -89,6 +98,25 @@ func getChecklistDB(uuid string) (*sql.DB, error) {
return db, nil
}
func loadItemDependencies(db *sql.DB, itemID int) ([]int, error) {
rows, err := db.Query(`SELECT dependency_id FROM dependencies WHERE item_id = ?`, itemID)
if err != nil {
return nil, err
}
defer rows.Close()
var deps []int
for rows.Next() {
var depID int
err = rows.Scan(&depID)
if err != nil {
return nil, err
}
deps = append(deps, depID)
}
return deps, nil
}
// ensureChecklistExists creates a checklist if it doesn't exist
func ensureChecklistExists(uuid string) error {
db, err := getChecklistDB(uuid)
@ -166,6 +194,13 @@ func loadChecklistItems(uuid string) ([]ChecklistItem, error) {
}
it.Checklist = uuid
// Load dependencies for this item
deps, err := loadItemDependencies(db, it.ID)
if err != nil {
return nil, err
}
it.Dependencies = deps
// Attach lock info if present
itemLocksMutex.Lock()
if lock, ok := itemLocks[it.ID]; ok && lock.Expires.After(time.Now()) {
@ -214,16 +249,72 @@ func addItem(uuid, content string, parentID *int) (ChecklistItem, error) {
}, nil
}
func updateItem(uuid string, id int, content *string, checked *bool, parentID *int) (ChecklistItem, error) {
func updateItem(uuid string, id int, content *string, checked *bool, parentID *int, dependencies *[]int) (ChecklistItem, error) {
log.Printf("updateItem called with uuid: %s, id: %d", uuid, id)
log.Printf("Parameters: content=%v, checked=%v, parentID=%v, dependencies=%v", content, checked, parentID, dependencies)
db, err := getChecklistDB(uuid)
if err != nil {
log.Printf("Failed to get database: %v", err)
return ChecklistItem{}, err
}
defer db.Close()
q := "UPDATE items SET "
args := []interface{}{}
log.Printf("Database connection successful for uuid: %s", uuid)
// If trying to check an item, validate dependencies first
if checked != nil && *checked {
log.Printf("Validating dependencies for item %d", id)
deps, err := loadItemDependencies(db, id)
if err != nil {
log.Printf("Failed to load dependencies: %v", err)
return ChecklistItem{}, err
}
// Check if all dependencies are completed
for _, depID := range deps {
var depChecked int
err = db.QueryRow(`SELECT checked FROM items WHERE id = ?`, depID).Scan(&depChecked)
if err != nil {
log.Printf("Failed to check dependency %d: %v", depID, err)
return ChecklistItem{}, err
}
if depChecked == 0 {
return ChecklistItem{}, fmt.Errorf("cannot complete item: dependency %d is not completed", depID)
}
}
} else {
log.Printf("Skipping dependency validation - checked is %v", checked)
}
log.Printf("About to check dependencies parameter")
// Update dependencies if provided
if dependencies != nil {
log.Printf("Updating dependencies for item %d: %v", id, *dependencies)
// Delete existing dependencies
_, err = db.Exec(`DELETE FROM dependencies WHERE item_id = ?`, id)
if err != nil {
log.Printf("Failed to delete existing dependencies: %v", err)
return ChecklistItem{}, err
}
// Add new dependencies
for _, depID := range *dependencies {
log.Printf("Adding dependency %d for item %d", depID, id)
_, err = db.Exec(`INSERT INTO dependencies (item_id, dependency_id) VALUES (?, ?)`, id, depID)
if err != nil {
log.Printf("Failed to add dependency %d: %v", depID, err)
return ChecklistItem{}, err
}
}
log.Printf("Dependencies updated successfully")
} else {
log.Printf("No dependencies to update")
}
log.Printf("About to build SQL update query")
set := []string{}
args := []interface{}{}
if content != nil {
set = append(set, "content = ?")
args = append(args, *content)
@ -240,24 +331,36 @@ func updateItem(uuid string, id int, content *string, checked *bool, parentID *i
set = append(set, "parent_id = ?")
args = append(args, *parentID)
}
q += strings.Join(set, ", ") + " WHERE id = ?"
args = append(args, id)
_, err = db.Exec(q, args...)
if err != nil {
return ChecklistItem{}, err
if len(set) > 0 {
q := "UPDATE items SET " + strings.Join(set, ", ") + " WHERE id = ?"
args = append(args, id)
log.Printf("SQL query: %s with args: %v", q, args)
_, err = db.Exec(q, args...)
if err != nil {
log.Printf("Failed to execute SQL update: %v", err)
return ChecklistItem{}, err
}
log.Printf("SQL update executed successfully")
} else {
log.Printf("No fields to update in SQL, skipping update query")
}
// Return updated item
log.Printf("Querying updated item %d", id)
rows, err := db.Query(`SELECT id, content, checked, parent_id FROM items WHERE id = ?`, id)
if err != nil {
log.Printf("Failed to query updated item: %v", err)
return ChecklistItem{}, err
}
defer rows.Close()
if rows.Next() {
log.Printf("Found item %d in database", id)
var it ChecklistItem
var checkedInt int
var parentID sql.NullInt64
err = rows.Scan(&it.ID, &it.Content, &checkedInt, &parentID)
if err != nil {
log.Printf("Failed to scan updated item: %v", err)
return ChecklistItem{}, err
}
it.Checked = checkedInt != 0
@ -266,8 +369,19 @@ func updateItem(uuid string, id int, content *string, checked *bool, parentID *i
it.ParentID = &v
}
it.Checklist = uuid
// Load dependencies
deps, err := loadItemDependencies(db, it.ID)
if err != nil {
log.Printf("Failed to load dependencies for return: %v", err)
return ChecklistItem{}, err
}
it.Dependencies = deps
log.Printf("Successfully updated item %d", id)
return it, nil
}
log.Printf("Item %d not found in database", id)
return ChecklistItem{}, fmt.Errorf("not found")
}
@ -278,6 +392,13 @@ func deleteItem(uuid string, id int) error {
}
defer db.Close()
// Delete dependencies that reference this item
_, err = db.Exec(`DELETE FROM dependencies WHERE dependency_id = ?`, id)
if err != nil {
return err
}
// Delete the item itself
_, err = db.Exec(`DELETE FROM items WHERE id = ?`, id)
return err
}
@ -381,7 +502,14 @@ func handleAddItem(w http.ResponseWriter, r *http.Request) {
}
func handleUpdateItem(w http.ResponseWriter, r *http.Request) {
log.Printf("handleUpdateItem called with path: %s", r.URL.Path)
parts := strings.Split(r.URL.Path, "/")
if len(parts) < 6 {
http.Error(w, "Invalid path", 400)
return
}
uuid := parts[3]
id := 0
fmt.Sscanf(parts[5], "%d", &id)
@ -393,18 +521,23 @@ func handleUpdateItem(w http.ResponseWriter, r *http.Request) {
}
type Req struct {
Content *string `json:"content"`
Checked *bool `json:"checked"`
ParentID *int `json:"parent_id"`
Content *string `json:"content"`
Checked *bool `json:"checked"`
ParentID *int `json:"parent_id"`
Dependencies *[]int `json:"dependencies"`
}
var req Req
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Bad body", 400)
return
}
item, err := updateItem(uuid, id, req.Content, req.Checked, req.ParentID)
item, err := updateItem(uuid, id, req.Content, req.Checked, req.ParentID, req.Dependencies)
if err != nil {
http.Error(w, "Not found", 404)
if strings.Contains(err.Error(), "cannot complete item: dependency") {
http.Error(w, err.Error(), 400)
} else {
http.Error(w, "Not found", 404)
}
return
}
broadcast(uuid, map[string]interface{}{"type": "item_updated", "item": item})
@ -587,7 +720,45 @@ func main() {
go lockExpiryDaemon()
// Serve static files from embedded filesystem
// Register API handlers first
http.HandleFunc("/api/checklists", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
handleCreateChecklist(w, r)
} else {
http.NotFound(w, r)
}
})
http.HandleFunc("/api/checklists/", func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
log.Printf("API request: %s %s", r.Method, path)
switch {
case strings.HasSuffix(path, "/items") && r.Method == "GET":
log.Printf("Handling GET items")
handleGetItems(w, r)
case strings.HasSuffix(path, "/items") && r.Method == "POST":
log.Printf("Handling POST items")
handleAddItem(w, r)
case strings.Contains(path, "/items/") && strings.HasSuffix(path, "/lock") && r.Method == "POST":
log.Printf("Handling lock item")
handleLockItem(w, r)
case strings.Contains(path, "/items/") && r.Method == "PATCH":
log.Printf("Handling PATCH item")
handleUpdateItem(w, r)
case strings.Contains(path, "/items/") && r.Method == "DELETE":
log.Printf("Handling DELETE item")
handleDeleteItem(w, r)
case strings.HasSuffix(path, "/sse") && r.Method == "GET":
log.Printf("Handling SSE")
handleSSE(w, r)
default:
log.Printf("No handler found for %s %s", r.Method, path)
http.NotFound(w, r)
}
})
// Serve static files from embedded filesystem (register last)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Check if this is a UUID path (starts with / followed by 36 characters)
isUUIDPath := len(r.URL.Path) == 37 && r.URL.Path[0] == '/' &&
@ -613,34 +784,6 @@ func main() {
}
})
http.HandleFunc("/api/checklists", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
handleCreateChecklist(w, r)
} else {
http.NotFound(w, r)
}
})
http.HandleFunc("/api/checklists/", func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
switch {
case strings.HasSuffix(path, "/items") && r.Method == "GET":
handleGetItems(w, r)
case strings.HasSuffix(path, "/items") && r.Method == "POST":
handleAddItem(w, r)
case strings.Contains(path, "/items/") && strings.HasSuffix(path, "/lock") && r.Method == "POST":
handleLockItem(w, r)
case strings.Contains(path, "/items/") && r.Method == "PATCH":
handleUpdateItem(w, r)
case strings.Contains(path, "/items/") && r.Method == "DELETE":
handleDeleteItem(w, r)
case strings.HasSuffix(path, "/sse") && r.Method == "GET":
handleSSE(w, r)
default:
http.NotFound(w, r)
}
})
port := strings.TrimSpace(os.Getenv("PORT"))
if port == "" {
port = "8080"