summaryrefslogtreecommitdiff
path: root/internal/store/chains.go
blob: f3bd0d7e1393518835e843a5064e46f3849b49f2 (plain)
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
package store

import (
	"database/sql"
	"fmt"
	"time"

	"task-dashboard/internal/config"
	"task-dashboard/internal/models"
)

// defaultChainProjectColor is used for the project a chain auto-creates for
// itself, since the chain-creation API takes no color -- unlike
// HandleWidgetProjectsCreate, where the client always supplies one.
const defaultChainProjectColor = "#8B5CF6"

// CreateChain creates a backing project (per the design's "a chain is
// effectively a project with strict sequential unlocking"), a task_chains
// row, and one native_tasks row per entry in tasks. Position 0 is created
// unlocked with due_date = now; the rest are locked with no due date. All
// in one transaction so a partial chain never exists.
func (s *Store) CreateChain(name string, tasks []models.ChainTaskInput) (*models.Chain, error) {
	if len(tasks) == 0 {
		return nil, fmt.Errorf("chain must have at least one task")
	}

	project, err := s.CreateProject(name, defaultChainProjectColor)
	if err != nil {
		return nil, err
	}

	chainID := newTaskID()
	now := config.Now()

	tx, err := s.db.Begin()
	if err != nil {
		return nil, err
	}
	defer func() { _ = tx.Rollback() }()

	if _, err := tx.Exec(`
		INSERT INTO task_chains (id, project_id, status, created_at) VALUES (?, ?, 'active', ?)
	`, chainID, project.ID, now); err != nil {
		return nil, err
	}

	for i, t := range tasks {
		unlocked := i == 0
		var dueDate *time.Time
		if unlocked {
			dueDate = &now
		}
		priority := t.Priority
		if priority == 0 {
			priority = 1
		}
		if _, err := tx.Exec(`
			INSERT INTO native_tasks (id, content, description, project_name, project_id, priority, due_date, chain_id, chain_position, chain_unlocked, created_at, updated_at)
			VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
		`, newTaskID(), t.Content, t.Description, project.Name, project.ID, priority, dueDate, chainID, i, unlocked, now, now); err != nil {
			return nil, err
		}
	}

	if err := tx.Commit(); err != nil {
		return nil, err
	}

	return &models.Chain{ID: chainID, ProjectID: project.ID, Status: "active", CreatedAt: now}, nil
}

// GetChain returns a single chain by id, or ErrNativeTaskNotFound.
func (s *Store) GetChain(id string) (*models.Chain, error) {
	var c models.Chain
	err := s.db.QueryRow(`
		SELECT id, project_id, status, created_at FROM task_chains WHERE id = ?
	`, id).Scan(&c.ID, &c.ProjectID, &c.Status, &c.CreatedAt)
	if err == sql.ErrNoRows {
		return nil, ErrNativeTaskNotFound
	}
	if err != nil {
		return nil, err
	}
	return &c, nil
}

// GetChainTasks returns every task in the chain, locked and unlocked both,
// ordered by chain_position -- the full checklist view.
func (s *Store) GetChainTasks(chainID string) ([]models.Task, error) {
	rows, err := s.db.Query(`
		SELECT id, content, description, project_name, project_id, due_date, priority, completed, labels, created_at,
		       recurrence_freq, recurrence_interval, recurrence_weekdays, recurrence_series_id, next_occurrence_override, estimated_minutes,
		       chain_id, chain_position, chain_unlocked,
		       bucket_id, bucket_state, bucket_last_active_at
		FROM native_tasks
		WHERE chain_id = ?
		ORDER BY chain_position ASC
	`, chainID)
	if err != nil {
		return nil, err
	}
	defer func() { _ = rows.Close() }()
	return scanNativeTasks(rows)
}

// SetChainStatus updates a chain's status (active/paused/abandoned/completed).
// Returns ErrNativeTaskNotFound if id doesn't match any row.
func (s *Store) SetChainStatus(id, status string) error {
	result, err := s.db.Exec(`UPDATE task_chains SET status = ? WHERE id = ?`, status, id)
	if err != nil {
		return err
	}
	return checkRowsAffected(result)
}

// advanceChain is called from CompleteNativeTask when the just-completed
// task has a chain_id set. Per the design, a paused chain does not
// auto-advance -- it must be explicitly resumed first. Completing the last
// position marks the chain completed instead of advancing.
func (s *Store) advanceChain(chainID string, completedPosition int) error {
	chain, err := s.GetChain(chainID)
	if err != nil {
		return err
	}
	if chain.Status == "paused" {
		return nil
	}

	now := config.Now()
	result, err := s.db.Exec(`
		UPDATE native_tasks SET chain_unlocked = 1, due_date = ?, updated_at = ?
		WHERE chain_id = ? AND chain_position = ?
	`, now, now, chainID, completedPosition+1)
	if err != nil {
		return err
	}
	affected, err := result.RowsAffected()
	if err != nil {
		return err
	}
	if affected == 0 {
		// No next position -- the completed task was the last in the chain.
		return s.SetChainStatus(chainID, "completed")
	}
	return nil
}