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
@@ -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);}});
|
||||
Reference in new issue
Block a user