Files
pages/internal/store/task_reminders.go
T
Anya Tokugawa c1175d389f Implement Knowledge City platform, organizer and DAV integration
Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
2026-09-27 14:44:43 +09:00

174 lines
7.7 KiB
Go

package store
import (
"context"
"database/sql"
"encoding/json"
"errors"
"time"
"github.com/google/uuid"
)
const TaskReminderEventType = "task.reminders.deliver"
func (s *Store) ensureTaskReminderSchema() error {
for _, q := range []string{
`CREATE TABLE IF NOT EXISTS organizer_reminders(domain_uuid TEXT NOT NULL,item_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,kind TEXT NOT NULL,source_version INTEGER NOT NULL,fire_at_ms INTEGER NOT NULL,civil_date TEXT NOT NULL,timezone TEXT NOT NULL,notification_key TEXT NOT NULL,state TEXT NOT NULL,PRIMARY KEY(domain_uuid,item_uuid,kind))`,
`CREATE INDEX IF NOT EXISTS organizer_reminders_due ON organizer_reminders(state,fire_at_ms,domain_uuid,item_uuid,kind)`,
`CREATE INDEX IF NOT EXISTS organizer_reminders_notification ON organizer_reminders(domain_uuid,owner_uuid,notification_key)`,
} {
if _, err := s.DB.Exec(q); err != nil {
return err
}
}
return nil
}
// Derived reservations are replaced in the source mutation transaction, not
// asynchronously from an old event: completion/date changes cannot race a
// delayed outbox consumer into resurrecting obsolete reminders.
func (s *Store) syncTaskRemindersTx(ctx context.Context, tx *sql.Tx, domain, actor string, item TaskRecord) error {
for _, kind := range []string{"due", "planned"} {
date, enabled := item.DueOn, item.NotifyDue
if kind == "planned" {
date, enabled = item.PlannedOn, item.NotifyPlanned
}
if item.Kind != "task" || !enabled || item.Archived || item.Status == "done" || item.Status == "cancelled" {
if _, err := tx.ExecContext(ctx, `DELETE FROM organizer_reminders WHERE domain_uuid=? AND item_uuid=? AND kind=?`, domain, item.UUID, kind); err != nil {
return err
}
continue
}
loc, err := time.LoadLocation(item.ReminderTimezone)
if err != nil {
return ErrTaskInvalid
}
stamp := date + " " + item.ReminderTime
fire, err := time.ParseInLocation("2006-01-02 15:04", stamp, loc)
if err != nil || fire.Format("2006-01-02 15:04") != stamp {
return ErrTaskInvalid
}
key := uuid.NewSHA1(uuid.NameSpaceOID, []byte(domain+":"+item.UUID+":"+kind+":"+stamp+":"+item.ReminderTimezone)).String()
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_reminders(domain_uuid,item_uuid,owner_uuid,kind,source_version,fire_at_ms,civil_date,timezone,notification_key,state) VALUES(?,?,?,?,?,?,?,?,?,'pending') ON CONFLICT(domain_uuid,item_uuid,kind) DO UPDATE SET owner_uuid=excluded.owner_uuid,source_version=excluded.source_version,fire_at_ms=excluded.fire_at_ms,civil_date=excluded.civil_date,timezone=excluded.timezone,state=CASE WHEN notification_key=excluded.notification_key AND state='sent' THEN 'sent' ELSE 'pending' END,notification_key=excluded.notification_key`, domain, item.UUID, actor, kind, item.Version, fire.UnixMilli(), date, item.ReminderTimezone, key)
if err != nil {
return err
}
}
return nil
}
func taskReminderExtensionEnabled(ctx context.Context, tx *sql.Tx, domain string) (bool, error) {
var raw string
err := tx.QueryRowContext(ctx, `SELECT value FROM config WHERE domain_uuid=? AND key='system_extension_states'`, domain).Scan(&raw)
if errors.Is(err, sql.ErrNoRows) {
return true, nil
}
if err != nil {
return false, err
}
if raw == "" {
return true, nil
}
states := map[string]bool{}
if json.Unmarshal([]byte(raw), &states) != nil {
return false, nil
}
v, ok := states["organizer.tasks"]
return !ok || v, nil
}
// Notification insertion and reservation acknowledgment share one writer
// transaction. Current membership, source version and extension state are
// rechecked under that lock. No task title/body is copied into the Inbox.
func (s *Store) DeliverTaskReminders(ctx context.Context, now time.Time, limit int) (int, int, error) {
if limit < 1 || limit > 100 {
limit = 100
}
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
tx, err := s.DB.BeginTx(ctx, nil)
if err != nil {
return 0, 0, err
}
defer tx.Rollback()
// Acquire the shared SQLite writer before selecting candidates. Mutations
// and parallel delivery workers cannot change the checked source meanwhile.
if _, err = tx.ExecContext(ctx, `UPDATE organizer_reminders SET state=state WHERE rowid=-1`); err != nil {
return 0, 0, err
}
rows, err := tx.QueryContext(ctx, `SELECT domain_uuid,item_uuid,owner_uuid,kind,source_version,fire_at_ms,civil_date,timezone,notification_key FROM organizer_reminders WHERE state='pending' AND fire_at_ms<=? ORDER BY fire_at_ms,domain_uuid,item_uuid,kind LIMIT ?`, now.UnixMilli(), limit)
if err != nil {
return 0, 0, err
}
type reminder struct {
domain, id, owner, kind, date, timezone, key string
version, fire int64
}
items := []reminder{}
for rows.Next() {
var v reminder
if err = rows.Scan(&v.domain, &v.id, &v.owner, &v.kind, &v.version, &v.fire, &v.date, &v.timezone, &v.key); err != nil {
rows.Close()
return 0, 0, err
}
items = append(items, v)
}
err = rows.Err()
rows.Close()
if err != nil {
return 0, 0, err
}
sent := 0
for _, v := range items {
state := "skipped"
loc, e := time.LoadLocation(v.timezone)
if e != nil {
return 0, 0, e
}
auth := taskActor(ctx, tx, v.domain, v.owner, false)
if auth != nil && !errors.Is(auth, ErrAccessDenied) {
return 0, 0, auth
}
enabled, e := taskReminderExtensionEnabled(ctx, tx, v.domain)
if e != nil {
return 0, 0, e
}
var current bool
if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM organizer_items WHERE domain_uuid=? AND uuid=? AND owner_uuid=? AND version=? AND archived=0 AND status NOT IN ('done','cancelled') AND kind='task')`, v.domain, v.id, v.owner, v.version).Scan(&current); err != nil {
return 0, 0, err
}
if auth == nil && enabled && current && now.In(loc).Format("2006-01-02") == v.date {
_, created, e := s.CreateNotificationTx(tx, Notification{DomainUUID: v.domain, RecipientUUID: v.owner, EventUUID: v.key, Kind: "task." + v.kind, RequestUUID: v.id, Href: "/v/plan/task/" + v.id, Message: "Task reminder", CreatedAtMS: now.UnixMilli()})
if e != nil {
return 0, 0, e
}
if created {
sent++
}
state = "sent"
}
if _, err = tx.ExecContext(ctx, `UPDATE organizer_reminders SET state=? WHERE domain_uuid=? AND item_uuid=? AND kind=?`, state, v.domain, v.id, v.kind); err != nil {
return 0, 0, err
}
}
if err = tx.Commit(); err != nil {
return 0, 0, err
}
return len(items), sent, nil
}
// Resolve a notification using current owner-only metadata; no CAS body fetch
// is necessary. Stale notices remain generic receipts, with no title or link.
func (s *Store) TaskReminderTitle(ctx context.Context, domain, actor, key string) (string, error) {
var title string
err := s.DB.QueryRowContext(ctx, `SELECT i.title FROM organizer_reminders r JOIN organizer_items i ON i.domain_uuid=r.domain_uuid AND i.uuid=r.item_uuid AND i.owner_uuid=r.owner_uuid AND i.version=r.source_version JOIN principals p ON p.uuid=r.owner_uuid AND p.state IN ('active','readonly') JOIN domain_memberships m ON m.principal_uuid=r.owner_uuid AND m.domain_uuid=r.domain_uuid AND m.state='active' JOIN domains d ON d.uuid=r.domain_uuid AND d.enabled=1 AND COALESCE(d.placement,'local')='local' WHERE r.domain_uuid=? AND r.owner_uuid=? AND r.notification_key=? AND r.state='sent' AND i.archived=0 AND i.status NOT IN ('done','cancelled')`, domain, actor, key).Scan(&title)
return title, err
}
func (s *Store) EnsureTaskReminderEvent() error {
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.reminders','Task Inbox reminders',?,'local','{}','interval',60,?,1,-2,3,?,?)`, TaskReminderEventType, now, now, now)
return err
}