Add task capture, work reports, daily digests and private contacts
Build and publish container images / images (push) Successful in 16m37s
Build and publish container images / images (push) Successful in 16m37s
This commit is contained in:
1 parent
50b8b0323f
commit
b4792bb175
50 files changed
+2678
-17
No files matched your search
@@ -508,7 +508,7 @@ func publish(stage, target string) error {
|
||||
func verifyReferences(ctx context.Context, database *sql.DB, seen map[string]bool) error {
|
||||
// Only authoritative references, not derived projection/preview caches. Some
|
||||
// installations predate optional modules, hence the explicit table check.
|
||||
for _, ref := range [][2]string{{"revisions", "document_hash"}, {"assets", "head_document_hash"}, {"asset_head_history", "document_hash"}, {"organizer_items", "document_hash"}, {"organizer_revisions", "document_hash"}} {
|
||||
for _, ref := range [][2]string{{"revisions", "document_hash"}, {"assets", "head_document_hash"}, {"asset_head_history", "document_hash"}, {"organizer_items", "document_hash"}, {"organizer_revisions", "document_hash"}, {"organizer_contacts", "hash"}, {"organizer_contact_revisions", "hash"}} {
|
||||
var exists bool
|
||||
if err := database.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name=?)", ref[0]).Scan(&exists); err != nil {
|
||||
return err
|
||||
|
||||
@@ -21,7 +21,8 @@ type Manifest struct {
|
||||
|
||||
func Catalog() []Manifest {
|
||||
return []Manifest{
|
||||
{ID: "organizer.tasks", APIVersion: 1, Version: "0.11.1", Kind: "tasks", Scope: "domain", NameKey: "tasks.title", DescriptionKey: "tasks.help", Capabilities: []string{"tasks.own.read", "tasks.own.write"}, Events: []string{"organizer.task.changed", "organizer.project.changed"}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "foreground+background+index"},
|
||||
{ID: "organizer.contacts", APIVersion: 1, Version: "0.1.0", Kind: "contacts", Scope: "domain", NameKey: "contacts.title", DescriptionKey: "contacts.help", Capabilities: []string{"contacts.own.read", "contacts.own.write"}, Events: []string{}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
|
||||
{ID: "organizer.tasks", APIVersion: 1, Version: "0.12.0", Kind: "tasks", Scope: "domain", NameKey: "tasks.title", DescriptionKey: "tasks.help", Capabilities: []string{"tasks.own.read", "tasks.own.write"}, Events: []string{"organizer.task.changed", "organizer.project.changed", "task.digest.deliver"}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "foreground+background+index"},
|
||||
{ID: "organizer.calendar", APIVersion: 1, Version: "0.2.0", Kind: "calendar", Scope: "domain", NameKey: "calendar.title", DescriptionKey: "calendar.help", Capabilities: []string{"calendar.read", "calendar.write"}, Events: []string{}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
|
||||
{ID: "content.diary", APIVersion: 1, Version: "0.1.0", Kind: "diary", Scope: "domain", NameKey: "periodical.diary", DescriptionKey: "periodical.diary_help", Capabilities: []string{"path.read", "path.write", "domain.extensions.manage"}, Events: []string{"periodical.registered", "periodical.removed"}, SettingsPanel: "diary", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
|
||||
{ID: "content.blog", APIVersion: 1, Version: "0.1.0", Kind: "blog", Scope: "domain", NameKey: "periodical.blog", DescriptionKey: "periodical.blog_help", Capabilities: []string{"path.read", "path.write", "domain.extensions.manage"}, Events: []string{"periodical.registered", "periodical.removed"}, SettingsPanel: "blog", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
|
||||
|
||||
@@ -3,6 +3,7 @@ package server
|
||||
func init() {
|
||||
for lang, entries := range map[string]map[string]string{
|
||||
"en": {
|
||||
"contacts.title": "Private address book", "contacts.help": "Private contacts, vCard import/export and email address lookup.",
|
||||
"contact.title": "Contact details", "contact.phone": "Phone number",
|
||||
"contact.help": "Private by default, independently of your profile. A tap opens the phone app. Leave blank to remove. Use 3–15 digits with an optional leading +, spaces, hyphens or parentheses; extensions and service codes are not supported.",
|
||||
"contact.visibility_help": "The profile audience remains the upper limit. Anonymous access also requires the domain to permit public profiles. Administrators do not automatically see private numbers.",
|
||||
@@ -10,6 +11,7 @@ func init() {
|
||||
"contact.invalid_phone": "Enter a phone number with 3–15 digits and optional leading +; only spaces, hyphens and parentheses may separate digits.",
|
||||
},
|
||||
"ja": {
|
||||
"contacts.title": "個人アドレス帳", "contacts.help": "非公開の連絡先、vCard入出力、メールアドレス検索。",
|
||||
"contact.title": "連絡先", "contact.phone": "電話番号",
|
||||
"contact.help": "プロフィールとは別に、既定で非公開です。タップすると電話アプリを開きます。空欄で削除。3〜15桁の数字と先頭の+、空白・ハイフン・括弧を使用できます。内線やサービスコードは未対応です。",
|
||||
"contact.visibility_help": "プロフィールの公開範囲を上限とします。匿名公開にはドメイン側の許可も必要です。管理者でも非公開の番号は表示されません。",
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/google/uuid"
|
||||
"io"
|
||||
"net/http"
|
||||
"pageswiki/internal/store"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const contactsAPI = "/_/api/v1/extension/organizer.contacts/"
|
||||
|
||||
func contactRoute(p string) bool { return p == "/v/plan/contacts" || strings.HasPrefix(p, contactsAPI) }
|
||||
func (s *Server) handleContacts(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
domain := s.domainUUIDForRequest(r)
|
||||
if !s.systemExtensionEnabled(domain, "organizer.contacts") {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
actor, active := s.calendarActor(r)
|
||||
if actor == "" {
|
||||
s.authRequired(w, r)
|
||||
return
|
||||
}
|
||||
if r.Method != "GET" && r.Method != "HEAD" && !active {
|
||||
taskError(w, store.ErrAccessDenied)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/v/plan/contacts" {
|
||||
if r.Method != "GET" && r.Method != "HEAD" {
|
||||
w.WriteHeader(405)
|
||||
return
|
||||
}
|
||||
if _, _, e := s.store.Contacts(r.Context(), domain, actor, "", ""); e != nil {
|
||||
taskError(w, e)
|
||||
return
|
||||
}
|
||||
s.renderWithContext(w, r, "contacts.gohtml", map[string]any{"Title": "Contacts", "ContactWritable": active, "Path": r.URL.Path})
|
||||
return
|
||||
}
|
||||
key := strings.TrimPrefix(r.URL.Path, contactsAPI)
|
||||
if key == "items" && r.Method == "GET" {
|
||||
items, next, e := s.store.ListContacts(r.Context(), domain, actor, r.URL.Query().Get("q"), r.URL.Query().Get("after"), r.URL.Query().Get("deleted") == "1")
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return
|
||||
}
|
||||
writeEventJSON(w, 200, map[string]any{"items": items, "next": next})
|
||||
return
|
||||
}
|
||||
if key == "import" && r.Method == "POST" {
|
||||
raw, e := io.ReadAll(http.MaxBytesReader(w, r.Body, 65536))
|
||||
if e != nil {
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
return
|
||||
}
|
||||
c, e := s.store.SaveContact(r.Context(), domain, actor, store.Contact{UUID: uuid.NewString(), VCard: string(raw)}, true)
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return
|
||||
}
|
||||
writeEventJSON(w, 201, map[string]any{"item": c})
|
||||
return
|
||||
}
|
||||
id := strings.TrimPrefix(key, "items/")
|
||||
export := strings.HasSuffix(id, ".vcf")
|
||||
if export {
|
||||
id = strings.TrimSuffix(id, ".vcf")
|
||||
}
|
||||
if key != "items" {
|
||||
if u, e := uuid.Parse(id); e != nil || u.String() != id {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
if key != "items" && (r.Method == "GET" || r.Method == "HEAD") {
|
||||
c, e := s.store.Contact(r.Context(), domain, actor, id)
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return
|
||||
}
|
||||
w.Header().Set("ETag", `"`+strconv.FormatInt(c.Version, 10)+`"`)
|
||||
if export {
|
||||
w.Header().Set("Content-Type", "text/vcard; charset=utf-8")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="contact.vcf"`)
|
||||
w.Write([]byte(c.VCard))
|
||||
} else {
|
||||
writeEventJSON(w, 200, map[string]any{"item": c})
|
||||
}
|
||||
return
|
||||
}
|
||||
if !export && (key == "items" && r.Method == "POST" || key != "items" && r.Method == "PUT") {
|
||||
var c store.Contact
|
||||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 128<<10))
|
||||
decoder.DisallowUnknownFields()
|
||||
if decoder.Decode(&c) != nil || decoder.Decode(&struct{}{}) != io.EOF {
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
return
|
||||
}
|
||||
if key == "items" {
|
||||
if c.Version != 0 {
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if c.UUID != id {
|
||||
taskError(w, store.ErrTaskInvalid)
|
||||
return
|
||||
}
|
||||
if r.Header.Get("If-Match") == "" {
|
||||
w.WriteHeader(428)
|
||||
return
|
||||
}
|
||||
if r.Header.Get("If-Match") != `"`+strconv.FormatInt(c.Version, 10)+`"` {
|
||||
taskError(w, store.ErrTaskConflict)
|
||||
return
|
||||
}
|
||||
}
|
||||
c, e := s.store.SaveContact(r.Context(), domain, actor, c, false)
|
||||
if e != nil {
|
||||
taskError(w, e)
|
||||
return
|
||||
}
|
||||
w.Header().Set("ETag", `"`+strconv.FormatInt(c.Version, 10)+`"`)
|
||||
writeEventJSON(w, 200, map[string]any{"item": c})
|
||||
return
|
||||
}
|
||||
w.Header().Set("Allow", "GET, HEAD, POST, PUT")
|
||||
w.WriteHeader(405)
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/google/uuid"
|
||||
"net/http/httptest"
|
||||
"pageswiki/internal/store"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestContactsPreserveImportAndIsolation(t *testing.T) {
|
||||
s, token, domain, actor := taskFixture(t)
|
||||
ctx := context.Background()
|
||||
raw := "BEGIN:VCARD\r\nVERSION:4.0\r\nUID:urn:test:person\r\nFN:田中\r\nEMAIL;TYPE=work:tanaka@example.invalid\r\nTEL;TYPE=cell:1234\r\nX-PRIVATE:keep\\,this\r\nPHOTO:https://example.invalid/do-not-fetch\r\nEND:VCARD\r\n"
|
||||
c, e := s.store.SaveContact(ctx, domain, actor, store.Contact{UUID: uuid.NewString(), VCard: raw}, true)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
repeat, e := s.store.SaveContact(ctx, domain, actor, store.Contact{UUID: uuid.NewString(), VCard: raw}, true)
|
||||
if e != nil || repeat.UUID != c.UUID {
|
||||
t.Fatal("not idempotent", e)
|
||||
}
|
||||
c.Name = "変更"
|
||||
c, e = s.store.SaveContact(ctx, domain, actor, c, false)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for _, preserved := range []string{"EMAIL;TYPE=work:", "TEL;TYPE=cell:", "X-PRIVATE:keep\\,this", "PHOTO:https:"} {
|
||||
if !strings.Contains(c.VCard, preserved) {
|
||||
t.Fatal("lost", preserved)
|
||||
}
|
||||
}
|
||||
old := c
|
||||
old.Version--
|
||||
if _, e = s.store.SaveContact(ctx, domain, actor, old, false); e != store.ErrTaskConflict {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.store.Contact(ctx, domain, uuid.NewString(), c.UUID); e == nil {
|
||||
t.Fatal("other user read")
|
||||
}
|
||||
req := httptest.NewRequest("GET", "http://localhost"+contactsAPI+"items?q=tanaka", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
w := httptest.NewRecorder()
|
||||
s.handleContacts(w, req)
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), "変更") {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
c.Deleted = true
|
||||
if _, e = s.store.SaveContact(ctx, domain, actor, c, false); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
items, _, e := s.store.Contacts(ctx, domain, actor, "", "")
|
||||
if e != nil || len(items) != 0 {
|
||||
t.Fatal(items, e)
|
||||
}
|
||||
if e = s.setSystemExtensionEnabled(domain, "organizer.contacts", false); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.store.Contact(ctx, domain, actor, c.UUID); e != store.ErrAccessDenied {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
func TestContactFormatValidation(t *testing.T) {
|
||||
for _, raw := range []string{"BEGIN:VCARD\nVERSION:2.1\nFN:x\nEND:VCARD\n", "BEGIN:VCARD\nVERSION:4.0\nFN;ENCODING=QUOTED-PRINTABLE:x\nEND:VCARD\n", "BEGIN:VCARD\nVERSION:4.0\nFN:x\nmalformed\nEND:VCARD\n"} {
|
||||
if _, e := store.ParseContact(raw); e == nil {
|
||||
t.Fatal("accepted malformed/legacy")
|
||||
}
|
||||
}
|
||||
raw := "BEGIN:VCARD\r\nVERSION:4.0\r\nFN:" + strings.Repeat("名", 90) + "\r\nNOTE:one\\ntwo\r\nEND:VCARD\r\n"
|
||||
c, e := store.ParseContact(raw)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
again, e := store.ParseContact(c.VCard)
|
||||
if e != nil || again.Name != c.Name || again.Notes != "one\ntwo" {
|
||||
t.Fatal(again, e)
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ func (s *Server) registeredEventHandlers() *dregarnuhr.Registry {
|
||||
s.eventHandlersOnce.Do(func() {
|
||||
registry := &dregarnuhr.Registry{}
|
||||
handlers := map[string]dregarnuhr.Handler{
|
||||
store.TaskDigestEventType: s.deliverTaskDigests,
|
||||
store.NotificationPushEventType: func(ctx context.Context, job *store.EventJob) error {
|
||||
return s.deliverNotificationPushContext(ctx, job)
|
||||
},
|
||||
|
||||
@@ -73,6 +73,9 @@ func (s *Server) startEventScheduler() {
|
||||
if err := s.store.EnsureTaskFocusEvent(); err != nil {
|
||||
log.Printf("focus timer initialization failed: %v", err)
|
||||
}
|
||||
if err := s.store.EnsureTaskDigestEvent(); err != nil {
|
||||
log.Printf("task digest initialization failed: %v", err)
|
||||
}
|
||||
if err := s.store.EnsureNotificationPushEvent(); err != nil {
|
||||
log.Printf("notification push initialization failed: %v", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestProductivityChromium(t *testing.T) {
|
||||
if os.Getenv("PAGESWIKI_BROWSER_TEST") != "1" {
|
||||
t.Skip("opt-in Chromium")
|
||||
}
|
||||
for _, view := range []string{"contacts", "settings", "report", "tasks", "home"} {
|
||||
for _, size := range []string{"desktop", "mobile"} {
|
||||
t.Run(view+"-"+size, func(t *testing.T) {
|
||||
s, token, domain, actor := taskFixture(t)
|
||||
s.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { s.renderSearchHome(w, r, "search") })
|
||||
item := newTaskRecord("task", "Browser work task")
|
||||
item.Status = "done"
|
||||
item.Estimate = 60
|
||||
item.Complexity = 3
|
||||
if _, e := s.store.SaveTask(context.Background(), domain, actor, item, 0); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
repo, e := s.calendars()
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = repo.Create(context.Background(), domain, actor, "Command calendar", "local"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
script, e := os.ReadFile("internal/server/testdata/productivity-browser.js")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
path := map[string]string{"contacts": "/v/plan/contacts", "settings": "/v/plan/tasks/settings", "report": "/v/plan/tasks/report", "tasks": "/v/plan/tasks", "home": "/"}[view]
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
if r.Method == "GET" && r.URL.Path == path {
|
||||
rec := httptest.NewRecorder()
|
||||
s.withAuthorization(s.mux).ServeHTTP(rec, r)
|
||||
for k, v := range rec.Header() {
|
||||
w.Header()[k] = v
|
||||
}
|
||||
w.WriteHeader(rec.Code)
|
||||
// The home template uses nonce CSP. Reuse its already generated nonce
|
||||
// only in this synthetic fixture; production HTML is never rewritten.
|
||||
nonce := ""
|
||||
if csp := rec.Header().Get("Content-Security-Policy"); strings.Contains(csp, "'nonce-") {
|
||||
nonce = strings.SplitN(strings.SplitN(csp, "'nonce-", 2)[1], "'", 2)[0]
|
||||
}
|
||||
w.Write([]byte(strings.Replace(rec.Body.String(), "</body>", "<script nonce=\""+nonce+"\">"+string(script)+"</script></body>", 1)))
|
||||
return
|
||||
}
|
||||
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||
}))
|
||||
defer server.Close()
|
||||
width, height := "1440", "1000"
|
||||
if size == "mobile" {
|
||||
width, height = "390", "844"
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
|
||||
defer cancel()
|
||||
shot := ""
|
||||
if prefix := os.Getenv("PAGESWIKI_PRODUCTIVITY_SCREENSHOT"); prefix != "" {
|
||||
shot = prefix + "-" + view + "-" + size + ".png"
|
||||
}
|
||||
out, e := exec.CommandContext(ctx, "node", "internal/server/testdata/vim-browser-smoke.mjs", strings.Replace(server.URL, "127.0.0.1", "localhost", 1)+path, t.TempDir(), shot, width, height).CombinedOutput()
|
||||
if e != nil {
|
||||
t.Fatalf("%v: %s", e, out)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -84,6 +84,10 @@ func sendMagicLinkSMTPWithTLS(ctx context.Context, config store.AuthProviderConf
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return deliverSMTPMessage(ctx, config, host, sender, addressee, message, tlsOverride)
|
||||
}
|
||||
|
||||
func deliverSMTPMessage(ctx context.Context, config store.AuthProviderConfig, host, sender, addressee string, message []byte, tlsOverride *tls.Config) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, smtpDeliveryTimeout)
|
||||
defer cancel()
|
||||
connection, err := (&net.Dialer{Timeout: 3 * time.Second}).DialContext(ctx, "tcp", config.SMTPAddress)
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/google/uuid"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTaskCalendarCapture(t *testing.T) {
|
||||
s, token, domain, actor := taskFixture(t)
|
||||
repo, e := s.calendars()
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
c, e := repo.Create(context.Background(), domain, actor, "Command calendar", "local")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
input := map[string]any{"request_id": uuid.NewString(), "calendar_uuid": c.ID, "title": "会議", "from": "2026-11-02T09:00", "to": "2026-11-02T10:00"}
|
||||
for range 2 {
|
||||
w := taskRequest(s, token, "POST", "calendar-capture", input, "")
|
||||
if w.Code != 201 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os/exec"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTaskCLIHTTPIntegration(t *testing.T) {
|
||||
if _, e := exec.LookPath("python3"); e != nil {
|
||||
t.Skip("python3 not installed")
|
||||
}
|
||||
s, token, _, _ := taskFixture(t)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r.Host = "localhost"
|
||||
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||
}))
|
||||
defer server.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, "python3", "pages-cli/test_task_integration.py")
|
||||
b, _ := json.Marshal(map[string]string{"origin": server.URL, "token": token, "root": t.TempDir()})
|
||||
cmd.Stdin = bytes.NewReader(b)
|
||||
if out, e := cmd.CombinedOutput(); e != nil {
|
||||
t.Fatalf("CLI task integration %v: %s", e, out)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func sendTaskDigestSMTP(ctx context.Context, config store.AuthProviderConfig, recipient, day, body string) error {
|
||||
// Reuse envelope validation and bounded TLS-aware SMTP transport, without
|
||||
// exposing SMTP credentials, recipient or task content to job logs.
|
||||
host, from, to, _, err := smtpMessage(config, recipient, "https://pages.invalid/")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sender, _ := smtpMailbox(config.SMTPFrom)
|
||||
addressee, _ := smtpMailbox(recipient)
|
||||
if len(body) > 128<<10 || len(day) != 10 || strings.ContainsAny(day, "\r\n\x00") {
|
||||
return store.ErrTaskInvalid
|
||||
}
|
||||
encoded := base64.StdEncoding.EncodeToString([]byte(body))
|
||||
var lines strings.Builder
|
||||
for len(encoded) > 76 {
|
||||
lines.WriteString(encoded[:76] + "\r\n")
|
||||
encoded = encoded[76:]
|
||||
}
|
||||
lines.WriteString(encoded + "\r\n")
|
||||
message := []byte(fmt.Sprintf("To: %s\r\nFrom: %s\r\nSubject: PagesWiki tasks %s\r\nDate: %s\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n%s", addressee.String(), sender.String(), day, time.Now().Format(time.RFC1123Z), lines.String()))
|
||||
return deliverSMTPMessage(ctx, config, host, from, to, message, nil)
|
||||
}
|
||||
|
||||
func (s *Server) deliverTaskDigests(ctx context.Context, job *store.EventJob) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
due, err := s.store.DueTaskDigests(ctx, time.Now())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sent, uncertain := 0, 0
|
||||
for _, candidate := range due {
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
claim, e := s.store.ClaimTaskDigest(ctx, candidate, time.Now())
|
||||
if errors.Is(e, sql.ErrNoRows) {
|
||||
continue
|
||||
}
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
state := "cancelled"
|
||||
if s.systemExtensionEnabled(claim.Domain, "organizer.tasks") {
|
||||
config, e := s.store.AuthProviderConfig(claim.Domain, "smtp")
|
||||
if e == nil && config.Enabled {
|
||||
items, next, e := s.store.ListTasks(ctx, claim.Domain, claim.Owner, store.TaskQuery{Kind: "task", View: "today", Today: claim.Day, Limit: 100})
|
||||
if e == nil {
|
||||
var body strings.Builder
|
||||
host, _ := s.store.GetDomainEffectiveHost(claim.Domain)
|
||||
base := ""
|
||||
if host != "" && !strings.ContainsAny(host, "/\\\r\n\t @") {
|
||||
base = "https://" + host
|
||||
}
|
||||
fmt.Fprintf(&body, "Tasks / やることリスト — %s (%s)\n\n", claim.Day, claim.Timezone)
|
||||
if len(items) == 0 {
|
||||
body.WriteString("No tasks due or planned today. / 今日の対象タスクはありません。\n")
|
||||
}
|
||||
for _, item := range items {
|
||||
fmt.Fprintf(&body, "- %s\n due/期限: %s | planned/予定: %s | estimate/見積: %d min\n %s/v/plan/task/%s\n", item.Title, item.DueOn, item.PlannedOn, item.Estimate, base, item.UUID)
|
||||
}
|
||||
if next != "" {
|
||||
body.WriteString("\nFirst 100 items only. / 最初の100件です。続きはタスク画面で確認してください。\n")
|
||||
}
|
||||
// Check consent and current account email immediately before send.
|
||||
if recipient, e := s.store.TaskDigestRecipient(ctx, claim); e == nil {
|
||||
state = "uncertain"
|
||||
if e = sendTaskDigestSMTP(ctx, config, recipient, claim.Day, body.String()); e == nil {
|
||||
state = "sent"
|
||||
sent++
|
||||
} else {
|
||||
uncertain++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Persist delivery outcome even if the scheduler context was cancelled.
|
||||
finish, stop := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
e = s.store.FinishTaskDigest(finish, claim, state)
|
||||
stop()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
if len(due) > 0 {
|
||||
s.addEventProgressLog(ctx, job, fmt.Sprintf("task digest checked=%d sent=%d uncertain=%d", len(due), sent, uncertain))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
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})
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func TestTaskDigestSMTPContent(t *testing.T) {
|
||||
address, _, done := fakeSMTP(t, "", false)
|
||||
body := "やること\n- 私用タスク\n"
|
||||
if e := sendTaskDigestSMTP(context.Background(), store.AuthProviderConfig{SMTPAddress: address, SMTPFrom: "wiki@example.test"}, "reader@example.test", "2026-11-01", body); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
result := <-done
|
||||
parts := strings.SplitN(strings.ReplaceAll(result.message, "\r\n", "\n"), "\n\n", 2)
|
||||
if len(parts) != 2 {
|
||||
t.Fatal("missing MIME body")
|
||||
}
|
||||
decoded, e := base64.StdEncoding.DecodeString(strings.Join(strings.Fields(parts[1]), ""))
|
||||
if e != nil || string(decoded) != body {
|
||||
t.Fatal("body encoding", e)
|
||||
}
|
||||
if !strings.Contains(parts[0], "Subject: PagesWiki tasks 2026-11-01") || strings.Contains(parts[0], "私用") {
|
||||
t.Fatal("wrong headers")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskCaptureDefaultsReplayAndPermissions(t *testing.T) {
|
||||
s, token, domain, actor := taskFixture(t)
|
||||
ctx := context.Background()
|
||||
days := 2
|
||||
p := store.TaskPreferences{AssigneeUUID: actor, DueDays: &days, Complexity: 3, Estimate: 60, Timezone: "Asia/Tokyo", DigestTime: "09:00"}
|
||||
p, err := s.store.SaveTaskPreferences(ctx, domain, actor, p, time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id := uuid.NewString()
|
||||
input := map[string]any{"request_id": id, "title": "Mail task", "notes": "Subject only"}
|
||||
w := taskRequest(s, token, "POST", "capture", input, "")
|
||||
if w.Code != 201 {
|
||||
t.Fatalf("capture %d %s", w.Code, w.Body)
|
||||
}
|
||||
var response struct {
|
||||
Item store.TaskRecord `json:"item"`
|
||||
}
|
||||
if err = json.Unmarshal(w.Body.Bytes(), &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Item.Complexity != 3 || response.Item.Estimate != 60 || response.Item.AssigneeUUID != actor || response.Item.DueOn == "" {
|
||||
t.Fatalf("defaults missing %+v", response.Item)
|
||||
}
|
||||
p.Estimate = 120
|
||||
if _, err = s.store.SaveTaskPreferences(ctx, domain, actor, p, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 201 {
|
||||
t.Fatalf("retry %d %s", w.Code, w.Body)
|
||||
}
|
||||
loaded, err := s.store.GetTask(ctx, domain, actor, id)
|
||||
if err != nil || loaded.Estimate != 60 || loaded.Version != 1 {
|
||||
t.Fatal(loaded, err)
|
||||
}
|
||||
input["title"] = "Different"
|
||||
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 412 {
|
||||
t.Fatalf("conflicting replay %d", w.Code)
|
||||
}
|
||||
input["request_id"] = uuid.NewString()
|
||||
input["due_on"] = ""
|
||||
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 201 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
if err = json.Unmarshal(w.Body.Bytes(), &response); err != nil || response.Item.DueOn != "" {
|
||||
t.Fatal("explicit clear lost", err)
|
||||
}
|
||||
if w = taskRequest(s, "", "POST", "capture", input, ""); w.Code == 201 {
|
||||
t.Fatal("anonymous capture")
|
||||
}
|
||||
if err = s.store.SetPrincipalState(domain, actor, "readonly"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token, err = s.store.CreateAuthSession(domain, actor)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w = taskRequest(s, token, "POST", "capture", input, ""); w.Code != 403 {
|
||||
t.Fatal("readonly capture", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskWorkReportSplitsMidnightAndCompletion(t *testing.T) {
|
||||
s, _, domain, actor := taskFixture(t)
|
||||
ctx := context.Background()
|
||||
item := newTaskRecord("task", "Tracked task")
|
||||
item.Estimate = 60
|
||||
item.Complexity = 3
|
||||
item, err := s.store.SaveTask(ctx, domain, actor, item, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loc, _ := time.LoadLocation("Asia/Tokyo")
|
||||
start := time.Date(2026, 11, 1, 23, 30, 0, 0, loc)
|
||||
end := start.Add(90 * time.Minute)
|
||||
v, err := s.store.ChangeTaskWork(ctx, domain, actor, "start", store.TaskWork{UUID: uuid.NewString(), TaskUUID: item.UUID}, start)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = s.store.ChangeTaskWork(ctx, domain, actor, "start", store.TaskWork{UUID: uuid.NewString(), TaskUUID: item.UUID}, start); err != store.ErrTaskConflict {
|
||||
t.Fatal("second active timer", err)
|
||||
}
|
||||
v, err = s.store.ChangeTaskWork(ctx, domain, actor, "stop", v, end)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if again, e := s.store.ChangeTaskWork(ctx, domain, actor, "stop", v, end.Add(time.Hour)); e != nil || again.EndMS != v.EndMS {
|
||||
t.Fatal("stop replay changed duration", e)
|
||||
}
|
||||
a := time.Date(2026, 11, 1, 0, 0, 0, 0, loc)
|
||||
report, err := s.store.TaskReport(ctx, domain, actor, a, a.AddDate(0, 0, 2), end)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(report.Tasks) != 1 || report.Tasks[0].WorkMS != 90*60000 || report.Days[0].WorkMS != 30*60000 || report.Days[1].WorkMS != 60*60000 {
|
||||
t.Fatalf("wrong split %+v", report)
|
||||
}
|
||||
item.Status = "done"
|
||||
item, err = s.store.SaveTask(ctx, domain, actor, item, item.Version)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now().In(loc)
|
||||
day := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, loc)
|
||||
report, err = s.store.TaskReport(ctx, domain, actor, day, day.AddDate(0, 0, 1), now)
|
||||
if err != nil || report.Days[0].Points != 7 || report.Days[0].Completed != 1 {
|
||||
t.Fatal("points", report, err)
|
||||
}
|
||||
item.Status = "todo"
|
||||
if _, err = s.store.SaveTask(ctx, domain, actor, item, item.Version); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
report, err = s.store.TaskReport(ctx, domain, actor, day, day.AddDate(0, 0, 1), now)
|
||||
if err != nil || report.Days[0].Points != 0 {
|
||||
t.Fatal("reopen did not retract", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskDigestClaimOnceAndOptOut(t *testing.T) {
|
||||
s, _, domain, actor := taskFixture(t)
|
||||
ctx := context.Background()
|
||||
now := time.Date(2026, 11, 1, 8, 0, 0, 0, time.UTC)
|
||||
p := store.TaskPreferences{Complexity: 1, DigestEnabled: true, DigestTime: "09:00", Timezone: "UTC"}
|
||||
p, err := s.store.SaveTaskPreferences(ctx, domain, actor, p, now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rows, e := s.store.DueTaskDigests(ctx, now); e != nil || len(rows) != 0 {
|
||||
t.Fatal(rows, e)
|
||||
}
|
||||
now = now.Add(2 * time.Hour)
|
||||
due, err := s.store.DueTaskDigests(ctx, now)
|
||||
if err != nil || len(due) != 1 {
|
||||
t.Fatal(due, err)
|
||||
}
|
||||
claim, err := s.store.ClaimTaskDigest(ctx, due[0], now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, e := s.store.ClaimTaskDigest(ctx, due[0], now); e == nil {
|
||||
t.Fatal("double claim")
|
||||
}
|
||||
if err = s.store.FinishTaskDigest(ctx, claim, "sent"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.DigestEnabled = false
|
||||
if _, err = s.store.SaveTaskPreferences(ctx, domain, actor, p, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = s.store.TaskDigestRecipient(ctx, claim); err == nil {
|
||||
t.Fatal("opt-out not enforced")
|
||||
}
|
||||
}
|
||||
@@ -20,10 +20,15 @@ import (
|
||||
const tasksAPI = "/_/api/v1/extension/organizer.tasks/"
|
||||
|
||||
func taskRoute(p string) bool {
|
||||
if contactRoute(p) {
|
||||
return true
|
||||
}
|
||||
return strings.HasPrefix(p, tasksAPI) || p == strings.TrimSuffix(taskDAVRoot, "/") || strings.HasPrefix(p, taskDAVRoot) || p == "/v/plan/today" || p == "/v/plan/tasks" || strings.HasPrefix(p, "/v/plan/tasks/") || p == "/v/plan/projects" || strings.HasPrefix(p, "/v/plan/project/") || strings.HasPrefix(p, "/v/plan/task/")
|
||||
}
|
||||
|
||||
func (s *Server) registerTaskRoutes() {
|
||||
s.mux.HandleFunc(contactsAPI, s.handleContacts)
|
||||
s.mux.HandleFunc("/v/plan/contacts", s.handleContacts)
|
||||
for _, p := range []string{"/v/plan/today", "/v/plan/tasks", "/v/plan/tasks/", "/v/plan/projects", "/v/plan/project/", "/v/plan/task/"} {
|
||||
s.mux.HandleFunc(p, s.handleTaskPage)
|
||||
}
|
||||
@@ -86,6 +91,10 @@ func (s *Server) handleTaskPage(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
domain := s.domainUUIDForRequest(r)
|
||||
if r.URL.Path == "/v/plan/tasks/report" || r.URL.Path == "/v/plan/tasks/settings" {
|
||||
s.handleTaskProductivityPage(w, r, active)
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(r.URL.Path, "/v/plan/tasks/schedule") {
|
||||
s.handleTaskSchedulePage(w, r, actor)
|
||||
return
|
||||
@@ -196,6 +205,10 @@ func (s *Server) handleTasksAPI(w http.ResponseWriter, r *http.Request) {
|
||||
r = r.WithContext(ctx)
|
||||
domain := s.domainUUIDForRequest(r)
|
||||
parts := strings.Split(strings.TrimPrefix(r.URL.Path, tasksAPI), "/")
|
||||
if len(parts) == 1 && (parts[0] == "calendar-capture" || parts[0] == "capture" || parts[0] == "preferences" || parts[0] == "work" || parts[0] == "report") {
|
||||
s.handleTaskProductivity(w, r, actor, active, parts[0])
|
||||
return
|
||||
}
|
||||
if len(parts) == 1 && parts[0] == "schedule" {
|
||||
s.handleTaskScheduleAPI(w, r, actor)
|
||||
return
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
window.addEventListener('load',async()=>{const wait=async(fn)=>{for(let i=0;i<120;i++){if(fn())return;await new Promise(r=>setTimeout(r,100));}throw Error('Timed out: '+fn.toString());};const fill=(n,value)=>{n.value=value;n.dispatchEvent(new Event('input',{bubbles:true}));};try{
|
||||
const path=location.pathname;
|
||||
if(path==='/v/plan/contacts'){
|
||||
await wait(()=>document.querySelector('#contacts-controls button'));document.querySelector('#contacts-controls button').click();fill(document.querySelector('[name=name]'),'ブラウザ連絡先');fill(document.querySelector('[name=emails]'),'browser@example.invalid');fill(document.querySelector('[name=notes]'),'Non-public notes');document.querySelector('#contact-editor form').requestSubmit();await wait(()=>document.querySelector('#contacts-list button')?.textContent.includes('ブラウザ'));const r=await fetch('/_/api/v1/extension/organizer.contacts/items?q=browser').then(r=>r.json());if(r.items.length!==1)throw Error('Contact save missing');
|
||||
}else if(path.endsWith('/settings')){
|
||||
await wait(()=>document.querySelector('[name=due_days]'));fill(document.querySelector('[name=due_days]'),'2');document.querySelector('.productivity-settings').requestSubmit();await wait(()=>document.querySelector('#productivity-status').textContent.includes('保存'));const d=await fetch('/_/api/v1/extension/organizer.tasks/preferences').then(r=>r.json());if(d.preferences.due_days!==2)throw Error('Preferences missing');
|
||||
}else if(path.endsWith('/report')){
|
||||
await wait(()=>document.querySelectorAll('.productivity-day').length>300);if(!document.querySelector('.productivity-day[data-level="2"]'))throw Error('Seven-point completion missing');
|
||||
}else if(path==='/v/plan/tasks'){
|
||||
await wait(()=>document.querySelector('#tasks-quick-title'));fill(document.querySelector('#tasks-quick-title'),'Recording task');document.querySelector('#tasks-capture').requestSubmit();await wait(()=>document.querySelector('[data-action=work]'));document.querySelector('[data-action=work]').click();await wait(()=>document.querySelector('.task-work-bar a').textContent.includes('Recording task'));document.querySelector('.task-work-bar button').click();await wait(()=>document.querySelector('.task-work-bar').hidden);
|
||||
}else{
|
||||
const input=document.querySelector('[data-home-type-search]');fill(input,'add task 検証 cost:2h complexity:3');input.closest('form').requestSubmit();await wait(()=>document.querySelector('.home-command-panel button'));document.querySelector('.home-command-panel button').click();await wait(()=>document.querySelector('.home-command-panel a'));const d=await fetch('/_/api/v1/extension/organizer.tasks/items?q='+encodeURIComponent('検証')).then(r=>r.json());if(d.items[0].estimate_minutes!==120)throw Error('Command cost missing');fill(input,'add cal 会議 from:2026-11-02T09:00 to:2026-11-02T10:00');input.closest('form').requestSubmit();await wait(()=>document.querySelector('.home-command-panel button'));document.querySelector('.home-command-panel button').click();await wait(()=>document.querySelector('.home-command-panel a')?.href.includes('/event/'));
|
||||
}
|
||||
if(document.documentElement.scrollWidth>innerWidth+2)throw Error('Page horizontal overflow');document.body.dataset.vimReady='true';
|
||||
}catch(e){const n=document.createElement('pre');n.id='error';n.textContent=(e.stack||String(e))+'\n'+(document.querySelector('.home-command-panel')?.textContent||'');document.body.append(n);}});
|
||||
@@ -0,0 +1,431 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/mail"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"pageswiki/internal/db"
|
||||
)
|
||||
|
||||
var contactMigrations = []db.SQLMigration{{Version: 1, Name: "private_address_book", Statements: []string{
|
||||
`CREATE TABLE organizer_contacts(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,uuid TEXT NOT NULL,uid TEXT NOT NULL,version INTEGER NOT NULL,name TEXT NOT NULL,search TEXT NOT NULL,data TEXT NOT NULL,hash TEXT NOT NULL,deleted INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(domain_uuid,owner_uuid,uuid),UNIQUE(domain_uuid,owner_uuid,uid))`,
|
||||
`CREATE INDEX organizer_contacts_owner ON organizer_contacts(domain_uuid,owner_uuid,deleted,uuid)`,
|
||||
`CREATE TABLE organizer_contact_revisions(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,uuid TEXT NOT NULL,version INTEGER NOT NULL,hash TEXT NOT NULL,deleted INTEGER NOT NULL,created_ms INTEGER NOT NULL,PRIMARY KEY(domain_uuid,owner_uuid,uuid,version))`,
|
||||
}, Assertions: []string{schemaColumns("organizer_contacts", "domain_uuid,owner_uuid,uuid,uid,version,name,search,data,hash,deleted"), schemaUnique("organizer_contacts", "domain_uuid,owner_uuid,uid")}}}
|
||||
|
||||
type Contact struct {
|
||||
UUID string `json:"uuid"`
|
||||
UID string `json:"uid"`
|
||||
Version int64 `json:"version"`
|
||||
Name string `json:"name"`
|
||||
Emails []string `json:"emails"`
|
||||
Phones []string `json:"phones"`
|
||||
Organization string `json:"organization"`
|
||||
Notes string `json:"notes"`
|
||||
VCard string `json:"vcard,omitempty"`
|
||||
Deleted bool `json:"deleted"`
|
||||
}
|
||||
|
||||
// Preserve every unfolded property, including unsupported fields/parameters.
|
||||
// Encoded legacy v2.1/QP and malformed data are rejected, never silently lost.
|
||||
func cardLines(raw string) ([]string, error) {
|
||||
if len(raw) > 65536 || !utf8.ValidString(raw) || strings.ContainsRune(raw, 0) {
|
||||
return nil, ErrTaskInvalid
|
||||
}
|
||||
for _, c := range raw {
|
||||
if c < 32 && c != '\r' && c != '\n' && c != '\t' || c == 127 {
|
||||
return nil, ErrTaskInvalid
|
||||
}
|
||||
}
|
||||
raw = strings.ReplaceAll(raw, "\r\n", "\n")
|
||||
if strings.ContainsRune(raw, '\r') {
|
||||
return nil, ErrTaskInvalid
|
||||
}
|
||||
var lines []string
|
||||
for _, line := range strings.Split(strings.TrimSuffix(raw, "\n"), "\n") {
|
||||
if strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t") {
|
||||
if len(lines) == 0 {
|
||||
return nil, ErrTaskInvalid
|
||||
}
|
||||
lines[len(lines)-1] += line[1:]
|
||||
} else {
|
||||
lines = append(lines, line)
|
||||
}
|
||||
}
|
||||
if len(lines) < 4 || lines[0] != "BEGIN:VCARD" || lines[len(lines)-1] != "END:VCARD" {
|
||||
return nil, ErrTaskInvalid
|
||||
}
|
||||
return lines, nil
|
||||
}
|
||||
func cardKey(line string) (string, string, error) {
|
||||
quoted := false
|
||||
colon := -1
|
||||
for i, c := range line {
|
||||
if c == '"' {
|
||||
quoted = !quoted
|
||||
}
|
||||
if c == ':' && !quoted {
|
||||
colon = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if colon < 1 {
|
||||
return "", "", ErrTaskInvalid
|
||||
}
|
||||
head := line[:colon]
|
||||
key := strings.SplitN(head, ";", 2)[0]
|
||||
if i := strings.LastIndex(key, "."); i >= 0 {
|
||||
key = key[i+1:]
|
||||
}
|
||||
for _, c := range key {
|
||||
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-') {
|
||||
return "", "", ErrTaskInvalid
|
||||
}
|
||||
}
|
||||
upper := strings.ToUpper(head)
|
||||
if strings.Contains(upper, "ENCODING=") || strings.Contains(upper, "CHARSET=") {
|
||||
return "", "", ErrTaskInvalid
|
||||
}
|
||||
return strings.ToUpper(key), line[colon+1:], nil
|
||||
}
|
||||
func cardText(s string) string {
|
||||
var b strings.Builder
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] == '\\' && i+1 < len(s) {
|
||||
i++
|
||||
if s[i] == 'n' || s[i] == 'N' {
|
||||
b.WriteByte('\n')
|
||||
continue
|
||||
}
|
||||
}
|
||||
b.WriteByte(s[i])
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
func escapeCard(s string) string {
|
||||
return strings.NewReplacer("\\", "\\\\", "\r\n", "\\n", "\n", "\\n", ";", "\\;", ",", "\\,").Replace(s)
|
||||
}
|
||||
func foldCard(lines []string) string {
|
||||
var b strings.Builder
|
||||
for _, line := range lines {
|
||||
first := true
|
||||
for len(line) > 0 {
|
||||
n := 75
|
||||
if !first {
|
||||
b.WriteByte(' ')
|
||||
n = 74
|
||||
}
|
||||
if len(line) < n {
|
||||
n = len(line)
|
||||
}
|
||||
for n > 0 && n < len(line) && !utf8.RuneStart(line[n]) {
|
||||
n--
|
||||
}
|
||||
b.WriteString(line[:n])
|
||||
b.WriteString("\r\n")
|
||||
line = line[n:]
|
||||
first = false
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
func ParseContact(raw string) (Contact, error) {
|
||||
c := Contact{Emails: []string{}, Phones: []string{}}
|
||||
lines, err := cardLines(raw)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
versions, names, uids := 0, 0, 0
|
||||
for _, line := range lines[1 : len(lines)-1] {
|
||||
key, value, e := cardKey(line)
|
||||
if e != nil {
|
||||
return c, e
|
||||
}
|
||||
value = cardText(value)
|
||||
switch key {
|
||||
case "VERSION":
|
||||
versions++
|
||||
if value != "4.0" && value != "3.0" {
|
||||
return c, ErrTaskInvalid
|
||||
}
|
||||
case "BEGIN", "END":
|
||||
return c, ErrTaskInvalid
|
||||
case "UID":
|
||||
uids++
|
||||
c.UID = value
|
||||
case "FN":
|
||||
names++
|
||||
if c.Name == "" {
|
||||
c.Name = value
|
||||
}
|
||||
case "EMAIL":
|
||||
c.Emails = append(c.Emails, value)
|
||||
case "TEL":
|
||||
c.Phones = append(c.Phones, strings.TrimPrefix(value, "tel:"))
|
||||
case "ORG":
|
||||
if c.Organization == "" {
|
||||
c.Organization = value
|
||||
}
|
||||
case "NOTE":
|
||||
if c.Notes == "" {
|
||||
c.Notes = value
|
||||
}
|
||||
}
|
||||
}
|
||||
if versions != 1 || names < 1 || uids > 1 || len(c.Name) > 300 || len(c.UID) > 1024 || strings.TrimSpace(c.Name) == "" || len(c.Emails) > 30 || len(c.Phones) > 30 {
|
||||
return c, ErrTaskInvalid
|
||||
}
|
||||
if lines[1] != "VERSION:4.0" && lines[1] != "VERSION:3.0" {
|
||||
return c, ErrTaskInvalid
|
||||
}
|
||||
for _, value := range append([]string{c.Name, c.UID}, c.Emails...) {
|
||||
if strings.ContainsAny(value, "\r\n\x00") {
|
||||
return c, ErrTaskInvalid
|
||||
}
|
||||
}
|
||||
for _, value := range c.Emails {
|
||||
a, e := mail.ParseAddress(value)
|
||||
if e != nil || a.Address != value {
|
||||
return c, ErrTaskInvalid
|
||||
}
|
||||
}
|
||||
if c.UID == "" {
|
||||
sum := sha256.Sum256([]byte(raw))
|
||||
c.UID = "urn:pageswiki:import:" + hex.EncodeToString(sum[:])
|
||||
lines = append(lines[:len(lines)-1], "UID:"+c.UID, "END:VCARD")
|
||||
}
|
||||
c.VCard = foldCard(lines)
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Editing the visible fields retains other fields verbatim. Even repeated FN,
|
||||
// ORG/NOTE and typed email/phone fields survive when that field is unchanged.
|
||||
func buildContact(old Contact, c Contact) (Contact, error) {
|
||||
if len(c.Name) > 300 || strings.TrimSpace(c.Name) == "" || len(c.Notes) > 16384 || len(c.Organization) > 1000 || len(c.Emails) > 30 || len(c.Phones) > 30 {
|
||||
return c, ErrTaskInvalid
|
||||
}
|
||||
for _, value := range append(append([]string{c.Name, c.Organization}, c.Emails...), c.Phones...) {
|
||||
if strings.ContainsAny(value, "\r\n\x00") {
|
||||
return c, ErrTaskInvalid
|
||||
}
|
||||
}
|
||||
for _, value := range c.Emails {
|
||||
a, e := mail.ParseAddress(value)
|
||||
if e != nil || a.Address != value {
|
||||
return c, ErrTaskInvalid
|
||||
}
|
||||
}
|
||||
lines := []string{"BEGIN:VCARD", "VERSION:4.0", "UID:urn:uuid:" + c.UUID, "END:VCARD"}
|
||||
if old.VCard != "" {
|
||||
var e error
|
||||
lines, e = cardLines(old.VCard)
|
||||
if e != nil {
|
||||
return c, e
|
||||
}
|
||||
}
|
||||
changes := map[string][]string{}
|
||||
if old.VCard == "" || c.Name != old.Name {
|
||||
changes["FN"] = []string{c.Name}
|
||||
}
|
||||
if c.Organization != old.Organization {
|
||||
changes["ORG"] = []string{c.Organization}
|
||||
}
|
||||
if c.Notes != old.Notes {
|
||||
changes["NOTE"] = []string{c.Notes}
|
||||
}
|
||||
if strings.Join(c.Emails, "\x00") != strings.Join(old.Emails, "\x00") {
|
||||
changes["EMAIL"] = c.Emails
|
||||
}
|
||||
if strings.Join(c.Phones, "\x00") != strings.Join(old.Phones, "\x00") {
|
||||
changes["TEL"] = c.Phones
|
||||
}
|
||||
out := []string{}
|
||||
for _, line := range lines[:len(lines)-1] {
|
||||
k, _, _ := cardKey(line)
|
||||
if _, replace := changes[k]; !replace {
|
||||
out = append(out, line)
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"FN", "ORG", "NOTE", "EMAIL", "TEL"} {
|
||||
for _, value := range changes[key] {
|
||||
if value != "" {
|
||||
out = append(out, key+":"+escapeCard(value))
|
||||
}
|
||||
}
|
||||
}
|
||||
out = append(out, "END:VCARD")
|
||||
parsed, e := ParseContact(foldCard(out))
|
||||
parsed.UUID = c.UUID
|
||||
parsed.Version = c.Version
|
||||
parsed.Deleted = c.Deleted
|
||||
return parsed, e
|
||||
}
|
||||
func contactEnabled(ctx context.Context, q interface {
|
||||
QueryRowContext(context.Context, string, ...any) *sql.Row
|
||||
}, domain string) error {
|
||||
var raw string
|
||||
err := q.QueryRowContext(ctx, `SELECT value FROM config WHERE domain_uuid=? AND key='system_extension_states'`, domain).Scan(&raw)
|
||||
if errors.Is(err, sql.ErrNoRows) || err == nil && raw == "" {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
states := map[string]bool{}
|
||||
if json.Unmarshal([]byte(raw), &states) != nil {
|
||||
return ErrAccessDenied
|
||||
}
|
||||
if on, ok := states["organizer.contacts"]; ok && !on {
|
||||
return ErrAccessDenied
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *Store) Contacts(ctx context.Context, domain, actor, query, after string) ([]Contact, string, error) {
|
||||
return s.ListContacts(ctx, domain, actor, query, after, false)
|
||||
}
|
||||
func (s *Store) ListContacts(ctx context.Context, domain, actor, query, after string, deleted bool) ([]Contact, string, error) {
|
||||
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if err := contactEnabled(ctx, s.DB, domain); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if len(query) > 200 {
|
||||
return nil, "", ErrTaskInvalid
|
||||
}
|
||||
rows, err := s.DB.QueryContext(ctx, `SELECT data FROM organizer_contacts WHERE domain_uuid=? AND owner_uuid=? AND deleted=? AND uuid>? AND instr(search,?)>0 ORDER BY uuid LIMIT 101`, domain, actor, deleted, after, strings.ToLower(query))
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []Contact{}
|
||||
next := ""
|
||||
for rows.Next() {
|
||||
var raw string
|
||||
if err = rows.Scan(&raw); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
var c Contact
|
||||
if err = json.Unmarshal([]byte(raw), &c); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if len(out) == 100 {
|
||||
next = out[99].UUID
|
||||
break
|
||||
}
|
||||
c.VCard = ""
|
||||
out = append(out, c)
|
||||
}
|
||||
return out, next, rows.Err()
|
||||
}
|
||||
func (s *Store) Contact(ctx context.Context, domain, actor, id string) (Contact, error) {
|
||||
var c Contact
|
||||
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||
return c, err
|
||||
}
|
||||
if err := contactEnabled(ctx, s.DB, domain); err != nil {
|
||||
return c, err
|
||||
}
|
||||
var raw string
|
||||
err := s.DB.QueryRowContext(ctx, `SELECT data FROM organizer_contacts WHERE domain_uuid=? AND owner_uuid=? AND uuid=?`, domain, actor, id).Scan(&raw)
|
||||
if err == nil {
|
||||
err = json.Unmarshal([]byte(raw), &c)
|
||||
}
|
||||
return c, err
|
||||
}
|
||||
func (s *Store) SaveContact(ctx context.Context, domain, actor string, c Contact, rawImport bool) (Contact, error) {
|
||||
if s.ReadOnly {
|
||||
return c, ErrReadOnly
|
||||
}
|
||||
if id, e := uuid.Parse(c.UUID); e != nil || id.String() != c.UUID || c.Version < 0 {
|
||||
return c, ErrTaskInvalid
|
||||
}
|
||||
tx, err := s.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err = tx.ExecContext(ctx, `UPDATE domain_memberships SET state=state WHERE domain_uuid=? AND principal_uuid=?`, domain, actor); err != nil {
|
||||
return c, err
|
||||
}
|
||||
if err = taskActor(ctx, tx, domain, actor, true); err != nil {
|
||||
return c, err
|
||||
}
|
||||
if err = contactEnabled(ctx, tx, domain); err != nil {
|
||||
return c, err
|
||||
}
|
||||
var old Contact
|
||||
var data string
|
||||
err = tx.QueryRowContext(ctx, `SELECT data FROM organizer_contacts WHERE domain_uuid=? AND owner_uuid=? AND uuid=?`, domain, actor, c.UUID).Scan(&data)
|
||||
if err == nil {
|
||||
if err = json.Unmarshal([]byte(data), &old); err != nil {
|
||||
return c, err
|
||||
}
|
||||
} else if !errors.Is(err, sql.ErrNoRows) {
|
||||
return c, err
|
||||
}
|
||||
if c.Version != old.Version {
|
||||
return c, ErrTaskConflict
|
||||
}
|
||||
if rawImport {
|
||||
if c.Version != 0 {
|
||||
return c, ErrTaskInvalid
|
||||
}
|
||||
parsed, e := ParseContact(c.VCard)
|
||||
if e != nil {
|
||||
return c, e
|
||||
}
|
||||
parsed.UUID = c.UUID
|
||||
c = parsed
|
||||
var existing string
|
||||
err = tx.QueryRowContext(ctx, `SELECT data FROM organizer_contacts WHERE domain_uuid=? AND owner_uuid=? AND uid=?`, domain, actor, c.UID).Scan(&existing)
|
||||
if err == nil {
|
||||
var previous Contact
|
||||
if json.Unmarshal([]byte(existing), &previous) != nil {
|
||||
return c, ErrTaskInvalid
|
||||
}
|
||||
if previous.VCard != c.VCard || previous.Deleted {
|
||||
return c, ErrTaskConflict
|
||||
}
|
||||
return previous, nil
|
||||
}
|
||||
if !errors.Is(err, sql.ErrNoRows) {
|
||||
return c, err
|
||||
}
|
||||
} else {
|
||||
c, err = buildContact(old, c)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
}
|
||||
c.Version++
|
||||
b, err := json.Marshal(c)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
hash := sha256.Sum256([]byte(c.VCard))
|
||||
digest := hex.EncodeToString(hash[:])
|
||||
if err = s.persistDocument(digest, c.VCard); err != nil {
|
||||
return c, err
|
||||
}
|
||||
search := strings.ToLower(c.Name + "\n" + c.Organization + "\n" + strings.Join(c.Emails, "\n") + "\n" + strings.Join(c.Phones, "\n"))
|
||||
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_contacts(domain_uuid,owner_uuid,uuid,uid,version,name,search,data,hash,deleted) VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT(domain_uuid,owner_uuid,uuid) DO UPDATE SET version=excluded.version,name=excluded.name,search=excluded.search,data=excluded.data,hash=excluded.hash,deleted=excluded.deleted`, domain, actor, c.UUID, c.UID, c.Version, c.Name, search, string(b), digest, c.Deleted)
|
||||
if err != nil {
|
||||
return c, fmt.Errorf("save contact: %w", err)
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_contact_revisions VALUES(?,?,?,?,?,?,?)`, domain, actor, c.UUID, c.Version, digest, c.Deleted, time.Now().UnixMilli())
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
return c, tx.Commit()
|
||||
}
|
||||
@@ -12,9 +12,11 @@ import (
|
||||
// Once released, add a new version; never edit an applied definition.
|
||||
// Auth, City, tasks and calendars remain in their existing migration paths.
|
||||
var managedStoreSchemas = map[string][]db.SQLMigration{
|
||||
"cli-auth": cliAuthMigrations,
|
||||
"profile-contacts": profileContactMigrations,
|
||||
"event-jobs": eventJobMigrations,
|
||||
"contacts": contactMigrations,
|
||||
"task-productivity": taskProductivityMigrations,
|
||||
"cli-auth": cliAuthMigrations,
|
||||
"profile-contacts": profileContactMigrations,
|
||||
"event-jobs": eventJobMigrations,
|
||||
"projection-metadata": {{Version: 1, Name: "adopt_projection_metadata", Statements: []string{
|
||||
`CREATE TABLE IF NOT EXISTS projection_metadata (
|
||||
document_hash TEXT NOT NULL,kind TEXT NOT NULL,version INTEGER NOT NULL,
|
||||
|
||||
@@ -15,9 +15,31 @@ func newSchemaTestStore(t *testing.T) *Store {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { database.Close() })
|
||||
// task-productivity follows the legacy task schema at application startup.
|
||||
// Provide its source projection, not the component under test itself.
|
||||
if _, err = database.Exec(`CREATE TABLE organizer_items(domain_uuid TEXT,owner_uuid TEXT,uuid TEXT,kind TEXT,data TEXT)`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &Store{DB: database}
|
||||
}
|
||||
|
||||
func TestTaskProductivityMigrationBackfillsOnce(t *testing.T) {
|
||||
st := newSchemaTestStore(t)
|
||||
if _, e := st.DB.Exec(`INSERT INTO organizer_items VALUES('d','u','t','task','{"completed_at_ms":123,"estimate_minutes":60}')`); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for range 2 {
|
||||
if e := st.ensureSchemaComponent("task-productivity"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
var count, complexity int
|
||||
var completed int64
|
||||
if e := st.DB.QueryRow(`SELECT count(*),completed_ms,complexity FROM organizer_task_metrics`).Scan(&count, &completed, &complexity); e != nil || count != 1 || completed != 123 || complexity != 1 {
|
||||
t.Fatal(count, completed, complexity, e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManagedSchemasFreshRepeatAndReadOnly(t *testing.T) {
|
||||
for component := range managedStoreSchemas {
|
||||
t.Run(component, func(t *testing.T) {
|
||||
|
||||
@@ -108,6 +108,9 @@ func NewWithDocumentRoot(
|
||||
if err := st.EnsureTasksSchema(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if err := st.ensureSchemaComponent("contacts"); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if err := st.EnsureBrowserNavigationSchema(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
const TaskDigestEventType = "task.digest.deliver"
|
||||
|
||||
type TaskDigestDue struct {
|
||||
Domain string
|
||||
Owner string
|
||||
}
|
||||
type TaskDigestClaim struct {
|
||||
TaskDigestDue
|
||||
Day string
|
||||
Version int64
|
||||
Timezone string
|
||||
}
|
||||
|
||||
func (s *Store) EnsureTaskDigestEvent() error {
|
||||
if s.ReadOnly {
|
||||
return ErrReadOnly
|
||||
}
|
||||
now := time.Now().UnixMilli()
|
||||
_, err := s.DB.Exec(`INSERT OR IGNORE INTO event_definitions(uuid,name,event_type,event_key,payload,schedule_kind,interval_seconds,next_run_at_ms,enabled,priority,max_attempts,created_at_ms,updated_at_ms) VALUES('builtin.task.digest','Daily task email',?,'local','{}','interval',60,?,1,-2,1,?,?)`, TaskDigestEventType, now, now, now)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) DueTaskDigests(ctx context.Context, now time.Time) ([]TaskDigestDue, error) {
|
||||
rows, err := s.DB.QueryContext(ctx, `SELECT domain_uuid,owner_uuid FROM organizer_task_preferences WHERE next_digest_ms>0 AND next_digest_ms<=? ORDER BY next_digest_ms,domain_uuid,owner_uuid LIMIT 20`, now.UnixMilli())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []TaskDigestDue{}
|
||||
for rows.Next() {
|
||||
var v TaskDigestDue
|
||||
if err = rows.Scan(&v.Domain, &v.Owner); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Claim before SMTP: an ambiguous delivery is never automatically sent twice.
|
||||
// An interrupted claim stays visible as "sending" for operator review.
|
||||
func (s *Store) ClaimTaskDigest(ctx context.Context, due TaskDigestDue, now time.Time) (TaskDigestClaim, error) {
|
||||
out := TaskDigestClaim{TaskDigestDue: due}
|
||||
if s.ReadOnly {
|
||||
return out, ErrReadOnly
|
||||
}
|
||||
tx, err := s.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
res, err := tx.ExecContext(ctx, `UPDATE organizer_task_preferences SET next_digest_ms=next_digest_ms WHERE domain_uuid=? AND owner_uuid=? AND next_digest_ms>0 AND next_digest_ms<=?`, due.Domain, due.Owner, now.UnixMilli())
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
n, _ := res.RowsAffected()
|
||||
if n != 1 {
|
||||
return out, sql.ErrNoRows
|
||||
}
|
||||
var raw string
|
||||
if err = tx.QueryRowContext(ctx, `SELECT data FROM organizer_task_preferences WHERE domain_uuid=? AND owner_uuid=?`, due.Domain, due.Owner).Scan(&raw); err != nil {
|
||||
return out, err
|
||||
}
|
||||
var p TaskPreferences
|
||||
if err = json.Unmarshal([]byte(raw), &p); err != nil {
|
||||
return out, err
|
||||
}
|
||||
loc, err := time.LoadLocation(p.Timezone)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.Day = now.In(loc).Format("2006-01-02")
|
||||
out.Timezone = p.Timezone
|
||||
out.Version = p.Version
|
||||
allowed := taskActor(ctx, tx, due.Domain, due.Owner, true)
|
||||
on, e := taskReminderExtensionEnabled(ctx, tx, due.Domain)
|
||||
if e != nil {
|
||||
return out, e
|
||||
}
|
||||
if allowed != nil && !errors.Is(allowed, ErrAccessDenied) {
|
||||
return out, allowed
|
||||
}
|
||||
if allowed != nil || !on || !p.DigestEnabled {
|
||||
// An opted-in schedule resumes after a domain or extension is restored.
|
||||
next, e := nextTaskDigest(now, p)
|
||||
if e != nil {
|
||||
return out, e
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, `UPDATE organizer_task_preferences SET next_digest_ms=? WHERE domain_uuid=? AND owner_uuid=?`, next, due.Domain, due.Owner)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
return out, err
|
||||
}
|
||||
return out, sql.ErrNoRows
|
||||
}
|
||||
// Missed days are not replayed. Run once for today's due time; if the
|
||||
// configured hour has not arrived, move the cursor there without sending.
|
||||
clock, _ := time.Parse("15:04", p.DigestTime)
|
||||
local := now.In(loc)
|
||||
today := time.Date(local.Year(), local.Month(), local.Day(), clock.Hour(), clock.Minute(), 0, 0, loc)
|
||||
next, err := nextTaskDigest(now, p)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, `UPDATE organizer_task_preferences SET next_digest_ms=? WHERE domain_uuid=? AND owner_uuid=?`, next, due.Domain, due.Owner)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
if today.After(now) {
|
||||
if err = tx.Commit(); err != nil {
|
||||
return out, err
|
||||
}
|
||||
return out, sql.ErrNoRows
|
||||
}
|
||||
res, err = tx.ExecContext(ctx, `INSERT OR IGNORE INTO organizer_digest_deliveries VALUES(?,?,?,'sending',?)`, due.Domain, due.Owner, out.Day, now.UnixMilli())
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
n, _ = res.RowsAffected()
|
||||
if err = tx.Commit(); err != nil {
|
||||
return out, err
|
||||
}
|
||||
if n != 1 {
|
||||
return out, sql.ErrNoRows
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *Store) TaskDigestRecipient(ctx context.Context, c TaskDigestClaim) (string, error) {
|
||||
if err := taskActor(ctx, s.DB, c.Domain, c.Owner, true); err != nil {
|
||||
return "", err
|
||||
}
|
||||
var raw, email string
|
||||
var version int64
|
||||
err := s.DB.QueryRowContext(ctx, `SELECT f.data,f.version,p.email FROM organizer_task_preferences f JOIN principals p ON p.uuid=f.owner_uuid WHERE f.domain_uuid=? AND f.owner_uuid=?`, c.Domain, c.Owner).Scan(&raw, &version, &email)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var p TaskPreferences
|
||||
if json.Unmarshal([]byte(raw), &p) != nil || !p.DigestEnabled || version != c.Version {
|
||||
return "", ErrAccessDenied
|
||||
}
|
||||
return email, nil
|
||||
}
|
||||
|
||||
func (s *Store) FinishTaskDigest(ctx context.Context, c TaskDigestClaim, state string) error {
|
||||
if state != "sent" && state != "uncertain" && state != "cancelled" {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
_, err := s.DB.ExecContext(ctx, `UPDATE organizer_digest_deliveries SET state=?,updated_ms=? WHERE domain_uuid=? AND owner_uuid=? AND day=? AND state='sending'`, state, time.Now().UnixMilli(), c.Domain, c.Owner, c.Day)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) LastTaskDigest(ctx context.Context, domain, actor string) (map[string]any, error) {
|
||||
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var day, state string
|
||||
var ms int64
|
||||
err := s.DB.QueryRowContext(ctx, `SELECT day,state,updated_ms FROM organizer_digest_deliveries WHERE domain_uuid=? AND owner_uuid=? ORDER BY day DESC LIMIT 1`, domain, actor).Scan(&day, &state, &ms)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"day": day, "state": state, "updated_at_ms": ms}, nil
|
||||
}
|
||||
@@ -0,0 +1,458 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"pageswiki/internal/db"
|
||||
)
|
||||
|
||||
var taskProductivityMigrations = []db.SQLMigration{{Version: 1, Name: "task_capture_work_and_reporting", Statements: []string{
|
||||
`CREATE TABLE organizer_task_preferences(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,version INTEGER NOT NULL,data TEXT NOT NULL,next_digest_ms INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(domain_uuid,owner_uuid))`,
|
||||
`CREATE INDEX organizer_digest_due ON organizer_task_preferences(next_digest_ms) WHERE next_digest_ms>0`,
|
||||
`CREATE TABLE organizer_capture_receipts(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,request_uuid TEXT NOT NULL,request_hash TEXT NOT NULL,item_uuid TEXT NOT NULL,PRIMARY KEY(domain_uuid,owner_uuid,request_uuid))`,
|
||||
`CREATE TABLE organizer_work_sessions(uuid TEXT PRIMARY KEY,domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,task_uuid TEXT NOT NULL,start_ms INTEGER NOT NULL,end_ms INTEGER NOT NULL DEFAULT 0,version INTEGER NOT NULL DEFAULT 1)`,
|
||||
`CREATE UNIQUE INDEX organizer_work_active ON organizer_work_sessions(owner_uuid) WHERE end_ms=0`,
|
||||
`CREATE INDEX organizer_work_period ON organizer_work_sessions(domain_uuid,owner_uuid,start_ms,uuid)`,
|
||||
`CREATE TABLE organizer_task_metrics(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,task_uuid TEXT NOT NULL,completed_ms INTEGER NOT NULL,estimate INTEGER NOT NULL,complexity INTEGER NOT NULL,PRIMARY KEY(domain_uuid,task_uuid))`,
|
||||
`CREATE INDEX organizer_task_completed ON organizer_task_metrics(domain_uuid,owner_uuid,completed_ms)`,
|
||||
`INSERT INTO organizer_task_metrics SELECT domain_uuid,owner_uuid,uuid,COALESCE(json_extract(data,'$.completed_at_ms'),0),COALESCE(json_extract(data,'$.estimate_minutes'),0),max(1,COALESCE(json_extract(data,'$.complexity'),1)) FROM organizer_items WHERE kind='task'`,
|
||||
`CREATE TABLE organizer_digest_deliveries(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,day TEXT NOT NULL,state TEXT NOT NULL,updated_ms INTEGER NOT NULL,PRIMARY KEY(domain_uuid,owner_uuid,day))`,
|
||||
}, Assertions: []string{
|
||||
schemaColumns("organizer_task_preferences", "domain_uuid,owner_uuid,version,data,next_digest_ms"),
|
||||
schemaUnique("organizer_capture_receipts", "domain_uuid,owner_uuid,request_uuid"),
|
||||
schemaIndex("organizer_work_sessions", "organizer_work_period", "domain_uuid,owner_uuid,start_ms,uuid"),
|
||||
}}}
|
||||
|
||||
type TaskPreferences struct {
|
||||
Version int64 `json:"version"`
|
||||
ProjectUUID string `json:"project_uuid"`
|
||||
AssigneeUUID string `json:"assignee_uuid"`
|
||||
DueDays *int `json:"due_days"`
|
||||
StartDays *int `json:"start_days"`
|
||||
PlannedDays *int `json:"planned_days"`
|
||||
ReviewDays *int `json:"review_days"`
|
||||
Estimate int `json:"estimate_minutes"`
|
||||
Complexity int `json:"complexity"`
|
||||
DigestEnabled bool `json:"digest_enabled"`
|
||||
DigestTime string `json:"digest_time"`
|
||||
Timezone string `json:"timezone"`
|
||||
}
|
||||
|
||||
func (s *Store) TaskPreferences(ctx context.Context, domain, actor string) (TaskPreferences, error) {
|
||||
p := TaskPreferences{AssigneeUUID: actor, Complexity: 1, DigestTime: "09:00", Timezone: "UTC"}
|
||||
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||
return p, err
|
||||
}
|
||||
var raw string
|
||||
err := s.DB.QueryRowContext(ctx, `SELECT data FROM organizer_task_preferences WHERE domain_uuid=? AND owner_uuid=?`, domain, actor).Scan(&raw)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return p, nil
|
||||
}
|
||||
if err != nil {
|
||||
return p, err
|
||||
}
|
||||
err = json.Unmarshal([]byte(raw), &p)
|
||||
return p, err
|
||||
}
|
||||
|
||||
func nextTaskDigest(now time.Time, p TaskPreferences) (int64, error) {
|
||||
loc, err := time.LoadLocation(p.Timezone)
|
||||
if err != nil {
|
||||
return 0, ErrTaskInvalid
|
||||
}
|
||||
clock, err := time.Parse("15:04", p.DigestTime)
|
||||
if err != nil || clock.Format("15:04") != p.DigestTime {
|
||||
return 0, ErrTaskInvalid
|
||||
}
|
||||
if !p.DigestEnabled {
|
||||
return 0, nil
|
||||
}
|
||||
t := now.In(loc)
|
||||
candidate := time.Date(t.Year(), t.Month(), t.Day(), clock.Hour(), clock.Minute(), 0, 0, loc)
|
||||
if !candidate.After(now) {
|
||||
candidate = time.Date(t.Year(), t.Month(), t.Day()+1, clock.Hour(), clock.Minute(), 0, 0, loc)
|
||||
}
|
||||
return candidate.UnixMilli(), nil
|
||||
}
|
||||
|
||||
func (s *Store) SaveTaskPreferences(ctx context.Context, domain, actor string, p TaskPreferences, now time.Time) (TaskPreferences, error) {
|
||||
if s.ReadOnly {
|
||||
return p, ErrReadOnly
|
||||
}
|
||||
for _, n := range []*int{p.DueDays, p.StartDays, p.PlannedDays, p.ReviewDays} {
|
||||
if n != nil && (*n < 0 || *n > 3650) {
|
||||
return p, ErrTaskInvalid
|
||||
}
|
||||
}
|
||||
if p.Estimate < 0 || p.Estimate > 10080 || p.Complexity < 1 || p.Complexity > 5 || p.Version < 0 {
|
||||
return p, ErrTaskInvalid
|
||||
}
|
||||
next, err := nextTaskDigest(now, p)
|
||||
if err != nil {
|
||||
return p, err
|
||||
}
|
||||
tx, err := s.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return p, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if err = taskProductivityWriter(ctx, tx, domain, actor); err != nil {
|
||||
return p, err
|
||||
}
|
||||
if err = validateTaskAssignee(ctx, tx, domain, p.AssigneeUUID); err != nil {
|
||||
return p, err
|
||||
}
|
||||
if p.ProjectUUID != "" {
|
||||
var yes bool
|
||||
if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM organizer_items WHERE domain_uuid=? AND owner_uuid=? AND uuid=? AND kind='project' AND archived=0)`, domain, actor, p.ProjectUUID).Scan(&yes); err != nil {
|
||||
return p, err
|
||||
}
|
||||
if !yes {
|
||||
return p, ErrTaskInvalid
|
||||
}
|
||||
}
|
||||
var current int64
|
||||
err = tx.QueryRowContext(ctx, `SELECT version FROM organizer_task_preferences WHERE domain_uuid=? AND owner_uuid=?`, domain, actor).Scan(¤t)
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return p, err
|
||||
}
|
||||
if current != p.Version {
|
||||
return p, ErrTaskConflict
|
||||
}
|
||||
p.Version++
|
||||
raw, _ := json.Marshal(p)
|
||||
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_task_preferences VALUES(?,?,?,?,?) ON CONFLICT(domain_uuid,owner_uuid) DO UPDATE SET version=excluded.version,data=excluded.data,next_digest_ms=excluded.next_digest_ms`, domain, actor, p.Version, string(raw), next)
|
||||
if err != nil {
|
||||
return p, err
|
||||
}
|
||||
return p, tx.Commit()
|
||||
}
|
||||
|
||||
func taskProductivityWriter(ctx context.Context, tx *sql.Tx, domain, actor string) error {
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE domain_memberships SET state=state WHERE domain_uuid=? AND principal_uuid=?`, domain, actor); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := taskActor(ctx, tx, domain, actor, true); err != nil {
|
||||
return err
|
||||
}
|
||||
on, err := taskReminderExtensionEnabled(ctx, tx, domain)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !on {
|
||||
return ErrAccessDenied
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Assignment is a private planning annotation, NOT a grant to read this task.
|
||||
func validateTaskAssignee(ctx context.Context, tx *sql.Tx, domain, assignee string) error {
|
||||
if assignee == "" {
|
||||
return nil
|
||||
}
|
||||
if _, err := uuid.Parse(assignee); err != nil {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
if err := taskActor(ctx, tx, domain, assignee, false); err != nil {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) CapturedTask(ctx context.Context, domain, actor, request, hash string) (TaskRecord, error) {
|
||||
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||
return TaskRecord{}, err
|
||||
}
|
||||
var stored, id string
|
||||
err := s.DB.QueryRowContext(ctx, `SELECT request_hash,item_uuid FROM organizer_capture_receipts WHERE domain_uuid=? AND owner_uuid=? AND request_uuid=?`, domain, actor, request).Scan(&stored, &id)
|
||||
if err != nil {
|
||||
return TaskRecord{}, err
|
||||
}
|
||||
if stored != hash {
|
||||
return TaskRecord{}, ErrTaskConflict
|
||||
}
|
||||
return s.GetTask(ctx, domain, actor, id)
|
||||
}
|
||||
|
||||
func (s *Store) CaptureTask(ctx context.Context, domain, actor, request, hash string, item TaskRecord) (TaskRecord, error) {
|
||||
if _, err := uuid.Parse(request); err != nil {
|
||||
return TaskRecord{}, ErrTaskInvalid
|
||||
}
|
||||
old, err := s.CapturedTask(ctx, domain, actor, request, hash)
|
||||
if err == nil {
|
||||
return old, nil
|
||||
}
|
||||
if !errors.Is(err, sql.ErrNoRows) {
|
||||
return old, err
|
||||
}
|
||||
item.UUID = request
|
||||
out, err := s.saveTask(ctx, domain, actor, item, 0, func(tx *sql.Tx, _ *TaskRecord, _ TaskRecord) error {
|
||||
_, e := tx.ExecContext(ctx, `INSERT INTO organizer_capture_receipts VALUES(?,?,?,?,?)`, domain, actor, request, hash, item.UUID)
|
||||
return e
|
||||
})
|
||||
if err != nil {
|
||||
if old, e := s.CapturedTask(ctx, domain, actor, request, hash); e == nil {
|
||||
return old, nil
|
||||
}
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
|
||||
type TaskWork struct {
|
||||
UUID string `json:"uuid"`
|
||||
TaskUUID string `json:"task_uuid"`
|
||||
StartMS int64 `json:"start_ms"`
|
||||
EndMS int64 `json:"end_ms"`
|
||||
Version int64 `json:"version"`
|
||||
}
|
||||
|
||||
func scanTaskWork(row interface{ Scan(...any) error }) (TaskWork, error) {
|
||||
var v TaskWork
|
||||
err := row.Scan(&v.UUID, &v.TaskUUID, &v.StartMS, &v.EndMS, &v.Version)
|
||||
return v, err
|
||||
}
|
||||
|
||||
const taskWorkColumns = `uuid,task_uuid,start_ms,end_ms,version`
|
||||
|
||||
func (s *Store) ActiveTaskWork(ctx context.Context, domain, actor string) (*TaskWork, error) {
|
||||
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v, err := scanTaskWork(s.DB.QueryRowContext(ctx, `SELECT `+taskWorkColumns+` FROM organizer_work_sessions WHERE domain_uuid=? AND owner_uuid=? AND end_ms=0`, domain, actor))
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
return &v, err
|
||||
}
|
||||
|
||||
func (s *Store) ChangeTaskWork(ctx context.Context, domain, actor, action string, v TaskWork, now time.Time) (TaskWork, error) {
|
||||
if s.ReadOnly {
|
||||
return v, ErrReadOnly
|
||||
}
|
||||
if _, err := uuid.Parse(v.UUID); err != nil {
|
||||
return v, ErrTaskInvalid
|
||||
}
|
||||
tx, err := s.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if err = taskProductivityWriter(ctx, tx, domain, actor); err != nil {
|
||||
return v, err
|
||||
}
|
||||
old, err := scanTaskWork(tx.QueryRowContext(ctx, `SELECT `+taskWorkColumns+` FROM organizer_work_sessions WHERE uuid=? AND domain_uuid=? AND owner_uuid=?`, v.UUID, domain, actor))
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return v, err
|
||||
}
|
||||
switch action {
|
||||
case "start":
|
||||
if v.Version != 0 {
|
||||
return v, ErrTaskInvalid
|
||||
}
|
||||
if err == nil {
|
||||
if old.TaskUUID != v.TaskUUID {
|
||||
return v, ErrTaskConflict
|
||||
}
|
||||
return old, tx.Commit()
|
||||
}
|
||||
var yes bool
|
||||
if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM organizer_items WHERE domain_uuid=? AND owner_uuid=? AND uuid=? AND kind='task' AND archived=0 AND status NOT IN ('done','cancelled'))`, domain, actor, v.TaskUUID).Scan(&yes); err != nil {
|
||||
return v, err
|
||||
}
|
||||
if !yes {
|
||||
return v, sql.ErrNoRows
|
||||
}
|
||||
v.StartMS = now.UnixMilli()
|
||||
v.EndMS = 0
|
||||
v.Version = 1
|
||||
res, e := tx.ExecContext(ctx, `INSERT OR IGNORE INTO organizer_work_sessions(uuid,domain_uuid,owner_uuid,task_uuid,start_ms) VALUES(?,?,?,?,?)`, v.UUID, domain, actor, v.TaskUUID, v.StartMS)
|
||||
if e != nil {
|
||||
return v, e
|
||||
}
|
||||
n, _ := res.RowsAffected()
|
||||
if n != 1 {
|
||||
return v, ErrTaskConflict
|
||||
}
|
||||
case "stop":
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
if old.EndMS > 0 {
|
||||
if v.Version == old.Version || v.Version == old.Version-1 {
|
||||
return old, tx.Commit()
|
||||
}
|
||||
return v, ErrTaskConflict
|
||||
}
|
||||
if old.Version != v.Version {
|
||||
return v, ErrTaskConflict
|
||||
}
|
||||
v = old
|
||||
v.EndMS = max(v.StartMS, now.UnixMilli())
|
||||
v.Version++
|
||||
_, err = tx.ExecContext(ctx, `UPDATE organizer_work_sessions SET end_ms=?,version=? WHERE uuid=?`, v.EndMS, v.Version, v.UUID)
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
default:
|
||||
return v, ErrTaskInvalid
|
||||
}
|
||||
return v, tx.Commit()
|
||||
}
|
||||
|
||||
type TaskReportDay struct {
|
||||
Date string `json:"date"`
|
||||
Completed int `json:"completed"`
|
||||
Points int `json:"points"`
|
||||
Estimate int `json:"estimate_minutes"`
|
||||
WorkMS int64 `json:"work_ms"`
|
||||
FocusMS int64 `json:"focus_ms"`
|
||||
}
|
||||
type TaskReportItem struct {
|
||||
UUID string `json:"uuid"`
|
||||
Title string `json:"title"`
|
||||
ProjectUUID string `json:"project_uuid"`
|
||||
WorkMS int64 `json:"work_ms"`
|
||||
Points int `json:"points"`
|
||||
Completed bool `json:"completed"`
|
||||
}
|
||||
type TaskReport struct {
|
||||
Days []TaskReportDay `json:"days"`
|
||||
Tasks []TaskReportItem `json:"tasks"`
|
||||
Sessions []TaskWork `json:"sessions"`
|
||||
Partial bool `json:"partial"`
|
||||
Timezone string `json:"timezone"`
|
||||
}
|
||||
|
||||
func (s *Store) TaskReport(ctx context.Context, domain, actor string, start, end, now time.Time) (TaskReport, error) {
|
||||
out := TaskReport{Days: []TaskReportDay{}, Tasks: []TaskReportItem{}, Sessions: []TaskWork{}, Timezone: start.Location().String()}
|
||||
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||
return out, err
|
||||
}
|
||||
if !end.After(start) || end.Sub(start) > 367*24*time.Hour {
|
||||
return out, ErrTaskInvalid
|
||||
}
|
||||
days := map[string]int{}
|
||||
for day := start; day.Before(end); day = day.AddDate(0, 0, 1) {
|
||||
days[day.Format("2006-01-02")] = len(out.Days)
|
||||
out.Days = append(out.Days, TaskReportDay{Date: day.Format("2006-01-02")})
|
||||
}
|
||||
byTask := map[string]int{}
|
||||
rows, err := s.DB.QueryContext(ctx, `SELECT m.completed_ms,m.estimate,m.complexity,m.task_uuid,COALESCE(i.title,''),COALESCE(i.project_uuid,'') FROM organizer_task_metrics m LEFT JOIN organizer_items i ON i.domain_uuid=m.domain_uuid AND i.owner_uuid=m.owner_uuid AND i.uuid=m.task_uuid WHERE m.domain_uuid=? AND m.owner_uuid=? AND m.completed_ms>=? AND m.completed_ms<? ORDER BY m.completed_ms,m.task_uuid LIMIT 10001`, domain, actor, start.UnixMilli(), end.UnixMilli())
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
n := 0
|
||||
for rows.Next() {
|
||||
var ms int64
|
||||
var estimate, complexity int
|
||||
var id, title, project string
|
||||
if err = rows.Scan(&ms, &estimate, &complexity, &id, &title, &project); err != nil {
|
||||
rows.Close()
|
||||
return out, err
|
||||
}
|
||||
n++
|
||||
if n > 10000 {
|
||||
out.Partial = true
|
||||
break
|
||||
}
|
||||
if index, ok := days[time.UnixMilli(ms).In(start.Location()).Format("2006-01-02")]; ok {
|
||||
d := &out.Days[index]
|
||||
d.Completed++
|
||||
d.Estimate += estimate
|
||||
d.Points += 1 + ((estimate+29)/30)*max(1, complexity)
|
||||
byTask[id] = len(out.Tasks)
|
||||
out.Tasks = append(out.Tasks, TaskReportItem{UUID: id, Title: title, ProjectUUID: project, Completed: true, Points: 1 + ((estimate+29)/30)*max(1, complexity)})
|
||||
}
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
// Split intervals at local midnight; never assume a day is exactly 24h.
|
||||
addSpan := func(a, b int64, focus bool) int64 {
|
||||
a = max(a, start.UnixMilli())
|
||||
b = min(b, end.UnixMilli(), now.UnixMilli())
|
||||
if b <= a {
|
||||
return 0
|
||||
}
|
||||
total := b - a
|
||||
for a < b {
|
||||
t := time.UnixMilli(a).In(start.Location())
|
||||
next := time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, 0, t.Location()).UnixMilli()
|
||||
stop := min(next, b)
|
||||
if index, ok := days[t.Format("2006-01-02")]; ok {
|
||||
if focus {
|
||||
out.Days[index].FocusMS += stop - a
|
||||
} else {
|
||||
out.Days[index].WorkMS += stop - a
|
||||
}
|
||||
}
|
||||
a = stop
|
||||
}
|
||||
return total
|
||||
}
|
||||
rows, err = s.DB.QueryContext(ctx, `SELECT w.uuid,w.task_uuid,w.start_ms,w.end_ms,w.version,COALESCE(i.title,''),COALESCE(i.project_uuid,'') FROM organizer_work_sessions w LEFT JOIN organizer_items i ON i.domain_uuid=w.domain_uuid AND i.owner_uuid=w.owner_uuid AND i.uuid=w.task_uuid WHERE w.domain_uuid=? AND w.owner_uuid=? AND w.start_ms<? AND (w.end_ms=0 OR w.end_ms>?) ORDER BY w.start_ms DESC,w.uuid LIMIT 10001`, domain, actor, end.UnixMilli(), start.UnixMilli())
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
n = 0
|
||||
for rows.Next() {
|
||||
var v TaskWork
|
||||
var title, project string
|
||||
if err = rows.Scan(&v.UUID, &v.TaskUUID, &v.StartMS, &v.EndMS, &v.Version, &title, &project); err != nil {
|
||||
rows.Close()
|
||||
return out, err
|
||||
}
|
||||
n++
|
||||
if n > 10000 {
|
||||
out.Partial = true
|
||||
break
|
||||
}
|
||||
finish := v.EndMS
|
||||
if finish == 0 {
|
||||
finish = now.UnixMilli()
|
||||
}
|
||||
elapsed := addSpan(v.StartMS, finish, false)
|
||||
if elapsed == 0 {
|
||||
continue
|
||||
}
|
||||
out.Sessions = append(out.Sessions, v)
|
||||
index, ok := byTask[v.TaskUUID]
|
||||
if !ok {
|
||||
index = len(out.Tasks)
|
||||
byTask[v.TaskUUID] = index
|
||||
out.Tasks = append(out.Tasks, TaskReportItem{UUID: v.TaskUUID, Title: title, ProjectUUID: project})
|
||||
}
|
||||
out.Tasks[index].WorkMS += elapsed
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
rows, err = s.DB.QueryContext(ctx, `SELECT start_ms,end_ms FROM organizer_focus_spans WHERE domain_uuid=? AND owner_uuid=? AND start_ms>=? AND start_ms<? AND end_ms>? AND phase='focus' ORDER BY start_ms,session_uuid,version LIMIT 10001`, domain, actor, start.Add(-180*time.Minute).UnixMilli(), end.UnixMilli(), start.UnixMilli())
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
defer rows.Close()
|
||||
n = 0
|
||||
for rows.Next() {
|
||||
var a, b int64
|
||||
if err = rows.Scan(&a, &b); err != nil {
|
||||
return out, err
|
||||
}
|
||||
n++
|
||||
if n > 10000 {
|
||||
out.Partial = true
|
||||
break
|
||||
}
|
||||
addSpan(a, b, true)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
+22
-1
@@ -36,6 +36,8 @@ type TaskRecord struct {
|
||||
DueOn string `json:"due_on"`
|
||||
PlannedOn string `json:"planned_on"`
|
||||
ReviewOn string `json:"review_on"`
|
||||
AssigneeUUID string `json:"assignee_uuid,omitempty"`
|
||||
Complexity int `json:"complexity,omitempty"`
|
||||
PageUUID string `json:"page_uuid"`
|
||||
Archived bool `json:"archived"`
|
||||
Version int64 `json:"version"`
|
||||
@@ -96,7 +98,10 @@ func (s *Store) EnsureTasksSchema() error {
|
||||
if err := s.ensureTaskBlocksSchema(); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.ensureTaskFocusSchema()
|
||||
if err := s.ensureTaskFocusSchema(); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.ensureSchemaComponent("task-productivity")
|
||||
}
|
||||
|
||||
func validTaskDate(v string) bool {
|
||||
@@ -108,6 +113,9 @@ func validTaskDate(v string) bool {
|
||||
}
|
||||
|
||||
func validateTask(item *TaskRecord) error {
|
||||
if item.Complexity < 0 || item.Complexity > 5 {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
if !validTaskNotesSubpath(item.NotesSubpath) || (item.Kind != "project" && item.NotesSubpath != "") {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
@@ -188,6 +196,9 @@ func (s *Store) SaveTask(ctx context.Context, domain, actor string, item TaskRec
|
||||
|
||||
// prepare participates in the same writer transaction as the task head.
|
||||
func (s *Store) saveTask(ctx context.Context, domain, actor string, item TaskRecord, expected int64, prepare func(*sql.Tx, *TaskRecord, TaskRecord) error) (TaskRecord, error) {
|
||||
if s.ReadOnly {
|
||||
return TaskRecord{}, ErrReadOnly
|
||||
}
|
||||
if err := validateTask(&item); err != nil {
|
||||
return TaskRecord{}, err
|
||||
}
|
||||
@@ -266,6 +277,11 @@ func (s *Store) saveTask(ctx context.Context, domain, actor string, item TaskRec
|
||||
if err = s.validateTaskParentTx(ctx, tx, domain, actor, item, old); err != nil {
|
||||
return TaskRecord{}, err
|
||||
}
|
||||
if item.AssigneeUUID != old.AssigneeUUID {
|
||||
if err = validateTaskAssignee(ctx, tx, domain, item.AssigneeUUID); err != nil {
|
||||
return TaskRecord{}, err
|
||||
}
|
||||
}
|
||||
// DAV identity and round-trip metadata are writable only through the DAV
|
||||
// transaction callback, never through a generic JSON/UI update.
|
||||
item.CalDAV = old.CalDAV
|
||||
@@ -330,6 +346,11 @@ func (s *Store) saveTask(ctx context.Context, domain, actor string, item TaskRec
|
||||
if err = s.syncTaskRemindersTx(ctx, tx, domain, actor, item); err != nil {
|
||||
return TaskRecord{}, err
|
||||
}
|
||||
if item.Kind == "task" {
|
||||
if _, err = tx.ExecContext(ctx, `INSERT INTO organizer_task_metrics VALUES(?,?,?,?,?,?) ON CONFLICT(domain_uuid,task_uuid) DO UPDATE SET completed_ms=excluded.completed_ms,estimate=excluded.estimate,complexity=excluded.complexity`, domain, actor, item.UUID, item.CompletedMS, item.Estimate, max(1, item.Complexity)); err != nil {
|
||||
return TaskRecord{}, err
|
||||
}
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
return TaskRecord{}, err
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user