Files
pages/internal/server/task_productivity.go
T
Anya Tokugawa b4792bb175
Build and publish container images / images (push) Successful in 16m37s
Add task capture, work reports, daily digests and private contacts
2026-11-01 22:28:16 +09:00

269 lines
8.3 KiB
Go

package server
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"net/http"
"strings"
"time"
"github.com/google/uuid"
cal "pageswiki/internal/calendar"
"pageswiki/internal/store"
)
func taskJSON(w http.ResponseWriter, r *http.Request, output any) bool {
d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 32768))
d.DisallowUnknownFields()
if d.Decode(output) != nil || d.Decode(&struct{}{}) != io.EOF {
taskError(w, store.ErrTaskInvalid)
return false
}
return true
}
func defaultTask(p store.TaskPreferences, now time.Time) store.TaskRecord {
item := store.TaskRecord{Kind: "task", Status: "todo", Bucket: "inbox", Priority: 1, ProjectUUID: p.ProjectUUID, AssigneeUUID: p.AssigneeUUID, Estimate: p.Estimate, Complexity: p.Complexity}
for _, date := range []struct {
offset *int
target *string
}{{p.DueDays, &item.DueOn}, {p.StartDays, &item.StartOn}, {p.PlannedDays, &item.PlannedOn}, {p.ReviewDays, &item.ReviewOn}} {
if date.offset != nil {
*date.target = now.AddDate(0, 0, *date.offset).Format("2006-01-02")
}
}
return item
}
type taskCaptureInput struct {
RequestID string `json:"request_id"`
Title string `json:"title"`
Notes string `json:"notes"`
ProjectUUID *string `json:"project_uuid"`
AssigneeUUID *string `json:"assignee_uuid"`
DueOn *string `json:"due_on"`
StartOn *string `json:"start_on"`
PlannedOn *string `json:"planned_on"`
ReviewOn *string `json:"review_on"`
Estimate *int `json:"estimate_minutes"`
Complexity *int `json:"complexity"`
}
func (s *Server) handleTaskProductivity(w http.ResponseWriter, r *http.Request, actor string, active bool, kind string) {
domain := s.domainUUIDForRequest(r)
if r.Method != "GET" && !active {
taskError(w, store.ErrAccessDenied)
return
}
switch kind {
case "calendar-capture":
if r.Method == "POST" {
if !s.systemExtensionEnabled(domain, "organizer.calendar") {
http.NotFound(w, r)
return
}
var input struct {
RequestID string `json:"request_id"`
CalendarUUID string `json:"calendar_uuid"`
Title string `json:"title"`
Start string `json:"from"`
End string `json:"to"`
}
if !taskJSON(w, r, &input) {
return
}
if id, e := uuid.Parse(input.RequestID); e != nil || id.String() != input.RequestID || strings.TrimSpace(input.Title) == "" || len(input.Title) > 300 {
taskError(w, store.ErrTaskInvalid)
return
}
if _, _, e := s.store.ListTasks(r.Context(), domain, actor, store.TaskQuery{Kind: "task", View: "all", Today: time.Now().In(s.getLocation(domain)).Format("2006-01-02"), Limit: 1}); e != nil {
taskError(w, e)
return
}
parse := func(value string) (time.Time, error) {
if strings.HasSuffix(value, "Z") || len(value) > 19 {
return time.Parse(time.RFC3339, value)
}
v, e := time.ParseInLocation("2006-01-02T15:04", value, s.getLocation(domain))
if e == nil && v.Format("2006-01-02T15:04") != value {
e = store.ErrTaskInvalid
}
return v, e
}
start, e1 := parse(input.Start)
end, e2 := parse(input.End)
if e1 != nil || e2 != nil || !end.After(start) || end.Sub(start) > 31*24*time.Hour {
taskError(w, store.ErrTaskInvalid)
return
}
repo, e := s.calendars()
if e != nil {
taskError(w, e)
return
}
event, e := cal.Build("", cal.Event{UID: input.RequestID, Summary: input.Title, Start: start, End: end})
if e != nil {
calendarError(w, e)
return
}
c, event, e := repo.TaskBlock(r.Context(), domain, input.CalendarUUID, actor, input.RequestID, &event)
if e != nil {
calendarError(w, e)
return
}
writeEventJSON(w, 201, map[string]any{"uid": event.UID, "calendar": c.PrettyName})
return
}
case "preferences":
if r.Method == "GET" {
p, err := s.store.TaskPreferences(r.Context(), domain, actor)
if err != nil {
taskError(w, err)
return
}
if p.Version == 0 {
p.Timezone = s.getTimezoneName(domain)
}
last, err := s.store.LastTaskDigest(r.Context(), domain, actor)
if err != nil {
taskError(w, err)
return
}
writeEventJSON(w, 200, map[string]any{"preferences": p, "defaults": defaultTask(p, time.Now().In(s.getLocation(domain))), "timezone": s.getTimezoneName(domain), "last_digest": last})
return
}
if r.Method == "PUT" {
var p store.TaskPreferences
if !taskJSON(w, r, &p) {
return
}
if p.DigestEnabled {
principal, err := s.store.PrincipalForSession(domain, s.authTokenFromRequest(r))
if err != nil {
taskError(w, store.ErrAccessDenied)
return
}
if _, err = smtpMailbox(principal.Email); err != nil {
writeEventJSON(w, 422, map[string]string{"error": "email_required"})
return
}
config, err := s.store.AuthProviderConfig(domain, "smtp")
if err != nil || !config.Enabled {
writeEventJSON(w, 422, map[string]string{"error": "smtp_unavailable"})
return
}
}
p, err := s.store.SaveTaskPreferences(r.Context(), domain, actor, p, time.Now())
if err != nil {
taskError(w, err)
return
}
writeEventJSON(w, 200, map[string]any{"preferences": p})
return
}
case "capture":
if r.Method == "POST" {
var input taskCaptureInput
if !taskJSON(w, r, &input) {
return
}
if id, err := uuid.Parse(input.RequestID); err != nil || id.String() != input.RequestID {
taskError(w, store.ErrTaskInvalid)
return
}
p, err := s.store.TaskPreferences(r.Context(), domain, actor)
if err != nil {
taskError(w, err)
return
}
item := defaultTask(p, time.Now().In(s.getLocation(domain)))
item.Title = input.Title
item.Notes = input.Notes
for _, v := range []struct {
from *string
to *string
}{{input.ProjectUUID, &item.ProjectUUID}, {input.AssigneeUUID, &item.AssigneeUUID}, {input.DueOn, &item.DueOn}, {input.StartOn, &item.StartOn}, {input.PlannedOn, &item.PlannedOn}, {input.ReviewOn, &item.ReviewOn}} {
if v.from != nil {
*v.to = *v.from
}
}
if input.Estimate != nil {
item.Estimate = *input.Estimate
}
if input.Complexity != nil {
item.Complexity = *input.Complexity
}
raw, _ := json.Marshal(input)
hash := sha256.Sum256(raw)
item, err = s.store.CaptureTask(r.Context(), domain, actor, input.RequestID, hex.EncodeToString(hash[:]), item)
if err != nil {
taskError(w, err)
return
}
s.taskResponse(w, r, item, 201)
return
}
case "work":
if r.Method == "GET" {
v, err := s.store.ActiveTaskWork(r.Context(), domain, actor)
if err != nil {
taskError(w, err)
return
}
writeEventJSON(w, 200, map[string]any{"item": v, "server_now_ms": time.Now().UnixMilli()})
return
}
if r.Method == "POST" {
var input struct {
store.TaskWork
Action string `json:"action"`
}
if !taskJSON(w, r, &input) {
return
}
v, err := s.store.ChangeTaskWork(r.Context(), domain, actor, input.Action, input.TaskWork, time.Now())
if err != nil {
taskError(w, err)
return
}
writeEventJSON(w, 200, map[string]any{"item": v, "server_now_ms": time.Now().UnixMilli()})
return
}
case "report":
if r.Method == "GET" {
now := time.Now().In(s.getLocation(domain))
end := time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, now.Location())
start := end.AddDate(-1, 0, 0)
for _, v := range []struct {
key string
target *time.Time
}{{"from", &start}, {"to", &end}} {
if value := r.URL.Query().Get(v.key); value != "" {
parsed, err := time.ParseInLocation("2006-01-02", value, now.Location())
if err != nil || parsed.Format("2006-01-02") != value {
taskError(w, store.ErrTaskInvalid)
return
}
*v.target = parsed
}
}
report, err := s.store.TaskReport(r.Context(), domain, actor, start, end, now)
if err != nil {
taskError(w, err)
return
}
writeEventJSON(w, 200, report)
return
}
}
w.Header().Set("Allow", map[string]string{"calendar-capture": "POST", "capture": "POST", "work": "GET, POST", "report": "GET", "preferences": "GET, PUT"}[kind])
w.WriteHeader(405)
}
func (s *Server) handleTaskProductivityPage(w http.ResponseWriter, r *http.Request, active bool) {
view := strings.TrimPrefix(r.URL.Path, "/v/plan/tasks/")
s.renderWithContext(w, r, "task_productivity.gohtml", map[string]any{"Title": "Tasks", "ProductivityView": view, "TaskWritable": active, "Path": r.URL.Path})
}