feat: add audited work records and controlled digest retries
Build and publish container images / images (push) Successful in 12m27s
Build and publish container images / images (push) Successful in 12m27s
This commit is contained in:
1 parent
6e0aecdfb3
commit
e65ca56f92
33 files changed
+2262
-114
No files matched your search
@@ -110,6 +110,88 @@ func TestDashboardUpgradePreservesTaskPreferences(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkHistoryUpgradePreservesLegacySessions(t *testing.T) {
|
||||
st := newSchemaTestStore(t)
|
||||
if err := db.ApplySQLiteMigrations(context.Background(), st.DB, "task-productivity", taskProductivityMigrations[:2]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := st.DB.Exec(`INSERT INTO organizer_work_sessions VALUES('w','d','u','t',100,200,2)`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for range 2 {
|
||||
if err := st.ensureSchemaComponent("task-productivity"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var start, end, version, cancelled int64
|
||||
if err := st.DB.QueryRow(`SELECT start_ms,end_ms,version,cancelled_ms FROM organizer_work_sessions WHERE uuid='w'`).Scan(&start, &end, &version, &cancelled); err != nil || start != 100 || end != 200 || version != 2 || cancelled != 0 {
|
||||
t.Fatal(start, end, version, cancelled, err)
|
||||
}
|
||||
var count int
|
||||
if err := st.DB.QueryRow(`SELECT count(*) FROM organizer_work_revisions`).Scan(&count); err != nil || count != 0 {
|
||||
t.Fatal("invented history", count, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDigestHistoryUpgradePreservesReservations(t *testing.T) {
|
||||
st := newSchemaTestStore(t)
|
||||
ctx := context.Background()
|
||||
if err := db.ApplySQLiteMigrations(ctx, st.DB, "task-productivity", taskProductivityMigrations[:3]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i, state := range []string{"sent", "sending", "uncertain", "cancelled"} {
|
||||
if _, err := st.DB.Exec(`INSERT INTO organizer_digest_deliveries VALUES(?,?,?, ?,?)`, "d", state, "2026-11-01", state, 100+i); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for range 2 {
|
||||
if err := st.ensureSchemaComponent("task-productivity"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var count int
|
||||
if err := st.DB.QueryRow(`SELECT count(*) FROM organizer_digest_deliveries d JOIN organizer_digest_attempts a ON a.uuid=d.attempt_uuid AND a.domain_uuid=d.domain_uuid AND a.owner_uuid=d.owner_uuid AND a.day=d.day AND a.state=d.state AND a.updated_ms=d.updated_ms WHERE a.kind='legacy' AND a.preference_version=0`).Scan(&count); err != nil || count != 4 {
|
||||
t.Fatal("reservation migration", count, err)
|
||||
}
|
||||
var integrity string
|
||||
if err := st.DB.QueryRow(`PRAGMA integrity_check`).Scan(&integrity); err != nil || integrity != "ok" {
|
||||
t.Fatal(integrity, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDigestHistoryMigrationRollback(t *testing.T) {
|
||||
st := newSchemaTestStore(t)
|
||||
ctx := context.Background()
|
||||
if err := db.ApplySQLiteMigrations(ctx, st.DB, "task-productivity", taskProductivityMigrations[:3]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := st.DB.Exec(`INSERT INTO organizer_digest_deliveries VALUES('d','u','2026-11-01','sent',123)`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
steps := append([]db.SQLMigration(nil), taskProductivityMigrations...)
|
||||
steps[3].Statements = append(append([]string(nil), steps[3].Statements...), `INVALID MIGRATION STATEMENT`)
|
||||
if err := db.ApplySQLiteMigrations(ctx, st.DB, "task-productivity", steps); err == nil {
|
||||
t.Fatal("failed migration committed")
|
||||
}
|
||||
var columns, ledger, attempts int
|
||||
if err := st.DB.QueryRow(`SELECT count(*) FROM pragma_table_info('organizer_digest_deliveries')`).Scan(&columns); err != nil || columns != 5 {
|
||||
t.Fatal("DDL not rolled back", columns, err)
|
||||
}
|
||||
if err := st.DB.QueryRow(`SELECT count(*) FROM schema_migration_steps WHERE component='task-productivity'`).Scan(&ledger); err != nil || ledger != 3 {
|
||||
t.Fatal(ledger, err)
|
||||
}
|
||||
if err := st.DB.QueryRow(`SELECT count(*) FROM sqlite_master WHERE name='organizer_digest_attempts'`).Scan(&attempts); err != nil || attempts != 0 {
|
||||
t.Fatal(attempts, err)
|
||||
}
|
||||
var state string
|
||||
if err := st.DB.QueryRow(`SELECT state FROM organizer_digest_deliveries`).Scan(&state); err != nil || state != "sent" {
|
||||
t.Fatal(state, err)
|
||||
}
|
||||
if err := st.ensureSchemaComponent("task-productivity"); err != nil {
|
||||
t.Fatal("retry migration", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManagedSchemasFreshRepeatAndReadOnly(t *testing.T) {
|
||||
for component := range managedStoreSchemas {
|
||||
t.Run(component, func(t *testing.T) {
|
||||
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const TaskDigestEventType = "task.digest.deliver"
|
||||
@@ -16,9 +18,10 @@ type TaskDigestDue struct {
|
||||
}
|
||||
type TaskDigestClaim struct {
|
||||
TaskDigestDue
|
||||
Day string
|
||||
Version int64
|
||||
Timezone string
|
||||
Day string
|
||||
Version int64
|
||||
Timezone string
|
||||
AttemptUUID string
|
||||
}
|
||||
|
||||
func (s *Store) EnsureTaskDigestEvent() error {
|
||||
@@ -124,11 +127,17 @@ func (s *Store) ClaimTaskDigest(ctx context.Context, due TaskDigestDue, now time
|
||||
}
|
||||
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())
|
||||
out.AttemptUUID = uuid.NewString()
|
||||
res, err = tx.ExecContext(ctx, `INSERT OR IGNORE INTO organizer_digest_deliveries(domain_uuid,owner_uuid,day,state,updated_ms,attempt_uuid) VALUES(?,?,?,'sending',?,?)`, due.Domain, due.Owner, out.Day, now.UnixMilli(), out.AttemptUUID)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
n, _ = res.RowsAffected()
|
||||
if n == 1 {
|
||||
if err = insertDigestAttempt(ctx, tx, out, "scheduled", "sending", now); err != nil {
|
||||
return out, err
|
||||
}
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
return out, err
|
||||
}
|
||||
@@ -139,12 +148,20 @@ func (s *Store) ClaimTaskDigest(ctx context.Context, due TaskDigestDue, now time
|
||||
}
|
||||
|
||||
func (s *Store) TaskDigestRecipient(ctx context.Context, c TaskDigestClaim) (string, error) {
|
||||
if err := taskActor(ctx, s.DB, c.Domain, c.Owner, true); err != nil {
|
||||
if s.ReadOnly {
|
||||
return "", ErrReadOnly
|
||||
}
|
||||
tx, err := s.DB.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if err := taskActor(ctx, tx, 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)
|
||||
err = tx.QueryRowContext(ctx, `SELECT f.data,f.version,p.email FROM organizer_task_preferences f JOIN principals p ON p.uuid=f.owner_uuid JOIN organizer_digest_deliveries d ON d.domain_uuid=f.domain_uuid AND d.owner_uuid=f.owner_uuid JOIN organizer_digest_attempts a ON a.uuid=d.attempt_uuid WHERE f.domain_uuid=? AND f.owner_uuid=? AND d.day=? AND d.attempt_uuid=? AND d.state='sending' AND a.state='sending' AND a.updated_ms>?`, c.Domain, c.Owner, c.Day, c.AttemptUUID, time.Now().Add(-2*time.Minute).UnixMilli()).Scan(&raw, &version, &email)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -152,15 +169,22 @@ func (s *Store) TaskDigestRecipient(ctx context.Context, c TaskDigestClaim) (str
|
||||
if json.Unmarshal([]byte(raw), &p) != nil || !p.DigestEnabled || version != c.Version {
|
||||
return "", ErrAccessDenied
|
||||
}
|
||||
return email, nil
|
||||
loc, err := time.LoadLocation(c.Timezone)
|
||||
if err != nil || time.Now().In(loc).Format("2006-01-02") != c.Day {
|
||||
return "", ErrAccessDenied
|
||||
}
|
||||
on, err := taskReminderExtensionEnabled(ctx, tx, c.Domain)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !on {
|
||||
return "", ErrAccessDenied
|
||||
}
|
||||
return email, tx.Commit()
|
||||
}
|
||||
|
||||
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
|
||||
return s.FinishTaskDigestReason(ctx, c, state, "", time.Now())
|
||||
}
|
||||
|
||||
func (s *Store) LastTaskDigest(ctx context.Context, domain, actor string) (map[string]any, error) {
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const TaskDigestRetentionDays = 90
|
||||
|
||||
type TaskDigestAttempt struct {
|
||||
UUID string `json:"uuid"`
|
||||
Day string `json:"day"`
|
||||
Kind string `json:"kind"`
|
||||
State string `json:"state"`
|
||||
Reason string `json:"reason"`
|
||||
Timezone string `json:"timezone"`
|
||||
CreatedMS int64 `json:"created_ms"`
|
||||
UpdatedMS int64 `json:"updated_ms"`
|
||||
}
|
||||
type TaskDigestRetry struct {
|
||||
RequestID string `json:"request_id"`
|
||||
Day string `json:"day"`
|
||||
ExpectedAttempt string `json:"expected_attempt"`
|
||||
DuplicateAcknowledged bool `json:"duplicate_acknowledged"`
|
||||
}
|
||||
type TaskDigestHistory struct {
|
||||
Items []TaskDigestAttempt `json:"items"`
|
||||
Next string `json:"next"`
|
||||
Today string `json:"today"`
|
||||
Current *TaskDigestAttempt `json:"current"`
|
||||
Retries int `json:"retries"`
|
||||
Enabled bool `json:"enabled"`
|
||||
RetentionDays int `json:"retention_days"`
|
||||
}
|
||||
|
||||
const digestAttemptColumns = `uuid,day,kind,state,reason,timezone,created_ms,updated_ms`
|
||||
|
||||
func scanDigestAttempt(row interface{ Scan(...any) error }) (TaskDigestAttempt, error) {
|
||||
var v TaskDigestAttempt
|
||||
err := row.Scan(&v.UUID, &v.Day, &v.Kind, &v.State, &v.Reason, &v.Timezone, &v.CreatedMS, &v.UpdatedMS)
|
||||
return v, err
|
||||
}
|
||||
|
||||
func insertDigestAttempt(ctx context.Context, tx *sql.Tx, c TaskDigestClaim, kind, state string, now time.Time) error {
|
||||
_, err := tx.ExecContext(ctx, `INSERT INTO organizer_digest_attempts(uuid,domain_uuid,owner_uuid,day,kind,state,preference_version,timezone,created_ms,updated_ms) VALUES(?,?,?,?,?,?,?,?,?,?)`, c.AttemptUUID, c.Domain, c.Owner, c.Day, kind, state, c.Version, c.Timezone, now.UnixMilli(), now.UnixMilli())
|
||||
return err
|
||||
}
|
||||
|
||||
// Receipt lookup is read-only. It lets clients confirm an accepted request even
|
||||
// when SMTP is subsequently disabled; it never reactivates a delivery.
|
||||
func (s *Store) TaskDigestRetryReceipt(ctx context.Context, domain, actor string, input TaskDigestRetry) (string, error) {
|
||||
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||
return "", err
|
||||
}
|
||||
id, err := uuid.Parse(input.RequestID)
|
||||
if err != nil || id.String() != input.RequestID {
|
||||
return "", ErrTaskInvalid
|
||||
}
|
||||
var day, expected string
|
||||
var ack bool
|
||||
err = s.DB.QueryRowContext(ctx, `SELECT day,expected_attempt,duplicate_ack FROM organizer_digest_requests WHERE uuid=? AND domain_uuid=? AND owner_uuid=?`, input.RequestID, domain, actor).Scan(&day, &expected, &ack)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if day != input.Day || expected != input.ExpectedAttempt || ack != input.DuplicateAcknowledged {
|
||||
return "", ErrTaskConflict
|
||||
}
|
||||
return input.RequestID, nil
|
||||
}
|
||||
|
||||
// A retry is durable queue admission, never an SMTP send in a browser request.
|
||||
// Keep request receipts and daily reservations even after detail retention.
|
||||
func (s *Store) QueueTaskDigestRetry(ctx context.Context, domain, actor string, input TaskDigestRetry, now time.Time) (string, error) {
|
||||
if s.ReadOnly {
|
||||
return "", ErrReadOnly
|
||||
}
|
||||
id, err := uuid.Parse(input.RequestID)
|
||||
if err != nil || id.String() != input.RequestID {
|
||||
return "", ErrTaskInvalid
|
||||
}
|
||||
tx, err := s.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if err = taskProductivityWriter(ctx, tx, domain, actor); err != nil {
|
||||
return "", err
|
||||
}
|
||||
var oldDomain, oldOwner, oldDay, oldExpected string
|
||||
var oldAck bool
|
||||
err = tx.QueryRowContext(ctx, `SELECT domain_uuid,owner_uuid,day,expected_attempt,duplicate_ack FROM organizer_digest_requests WHERE uuid=?`, input.RequestID).Scan(&oldDomain, &oldOwner, &oldDay, &oldExpected, &oldAck)
|
||||
if err == nil {
|
||||
if oldDomain != domain || oldOwner != actor || oldDay != input.Day || oldExpected != input.ExpectedAttempt || oldAck != input.DuplicateAcknowledged {
|
||||
return "", ErrTaskConflict
|
||||
}
|
||||
return input.RequestID, tx.Commit()
|
||||
}
|
||||
if !errors.Is(err, sql.ErrNoRows) {
|
||||
return "", err
|
||||
}
|
||||
var raw string
|
||||
if err = tx.QueryRowContext(ctx, `SELECT data FROM organizer_task_preferences WHERE domain_uuid=? AND owner_uuid=?`, domain, actor).Scan(&raw); err != nil {
|
||||
return "", err
|
||||
}
|
||||
var p TaskPreferences
|
||||
if err = json.Unmarshal([]byte(raw), &p); err != nil {
|
||||
return "", err
|
||||
}
|
||||
loc, err := time.LoadLocation(p.Timezone)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !p.DigestEnabled {
|
||||
return "", ErrAccessDenied
|
||||
}
|
||||
if input.Day != now.In(loc).Format("2006-01-02") {
|
||||
return "", ErrTaskInvalid
|
||||
}
|
||||
var state, current string
|
||||
if err = tx.QueryRowContext(ctx, `SELECT state,attempt_uuid FROM organizer_digest_deliveries WHERE domain_uuid=? AND owner_uuid=? AND day=?`, domain, actor, input.Day).Scan(&state, ¤t); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if current != input.ExpectedAttempt || state == "queued" || state == "sending" {
|
||||
return "", ErrTaskConflict
|
||||
}
|
||||
if state != "sent" && state != "uncertain" && state != "cancelled" {
|
||||
return "", ErrTaskConflict
|
||||
}
|
||||
if (state == "sent" || state == "uncertain") && !input.DuplicateAcknowledged {
|
||||
return "", ErrTaskInvalid
|
||||
}
|
||||
var count int
|
||||
if err = tx.QueryRowContext(ctx, `SELECT count(*) FROM organizer_digest_requests WHERE domain_uuid=? AND owner_uuid=? AND day=?`, domain, actor, input.Day).Scan(&count); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if count >= 5 {
|
||||
return "", ErrTaskConflict
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_digest_requests VALUES(?,?,?,?,?,?,?)`, input.RequestID, domain, actor, input.Day, input.ExpectedAttempt, input.DuplicateAcknowledged, now.UnixMilli())
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
c := TaskDigestClaim{TaskDigestDue: TaskDigestDue{domain, actor}, Day: input.Day, Version: p.Version, Timezone: p.Timezone, AttemptUUID: input.RequestID}
|
||||
if err = insertDigestAttempt(ctx, tx, c, "manual", "queued", now); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `UPDATE organizer_digest_deliveries SET state='queued',attempt_uuid=?,updated_ms=? WHERE domain_uuid=? AND owner_uuid=? AND day=?`, c.AttemptUUID, now.UnixMilli(), domain, actor, input.Day); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return c.AttemptUUID, tx.Commit()
|
||||
}
|
||||
|
||||
func (s *Store) QueuedTaskDigests(ctx context.Context) ([]TaskDigestClaim, error) {
|
||||
rows, err := s.DB.QueryContext(ctx, `SELECT uuid,domain_uuid,owner_uuid,day,preference_version,timezone FROM organizer_digest_attempts WHERE state='queued' ORDER BY updated_ms,uuid LIMIT 10`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []TaskDigestClaim{}
|
||||
for rows.Next() {
|
||||
var c TaskDigestClaim
|
||||
if err = rows.Scan(&c.AttemptUUID, &c.Domain, &c.Owner, &c.Day, &c.Version, &c.Timezone); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, c)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) ClaimQueuedTaskDigest(ctx context.Context, c TaskDigestClaim, now time.Time) (TaskDigestClaim, error) {
|
||||
if s.ReadOnly {
|
||||
return c, ErrReadOnly
|
||||
}
|
||||
tx, err := s.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
res, err := tx.ExecContext(ctx, `UPDATE organizer_digest_attempts SET state='sending',updated_ms=? WHERE uuid=? AND domain_uuid=? AND owner_uuid=? AND state='queued' AND EXISTS(SELECT 1 FROM organizer_digest_deliveries d WHERE d.domain_uuid=? AND d.owner_uuid=? AND d.day=? AND d.attempt_uuid=? AND d.state='queued')`, now.UnixMilli(), c.AttemptUUID, c.Domain, c.Owner, c.Domain, c.Owner, c.Day, c.AttemptUUID)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
if n != 1 {
|
||||
return c, sql.ErrNoRows
|
||||
}
|
||||
// Reload all claim fields from the queue, not from an earlier enumeration.
|
||||
if err = tx.QueryRowContext(ctx, `SELECT day,preference_version,timezone FROM organizer_digest_attempts WHERE uuid=?`, c.AttemptUUID).Scan(&c.Day, &c.Version, &c.Timezone); err != nil {
|
||||
return c, err
|
||||
}
|
||||
state, reason := "sending", ""
|
||||
allowed := taskActor(ctx, tx, c.Domain, c.Owner, true)
|
||||
if allowed != nil && !errors.Is(allowed, ErrAccessDenied) {
|
||||
return c, allowed
|
||||
}
|
||||
on, err := taskReminderExtensionEnabled(ctx, tx, c.Domain)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
var raw string
|
||||
err = tx.QueryRowContext(ctx, `SELECT data FROM organizer_task_preferences WHERE domain_uuid=? AND owner_uuid=?`, c.Domain, c.Owner).Scan(&raw)
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return c, err
|
||||
}
|
||||
var p TaskPreferences
|
||||
if err == nil {
|
||||
if err = json.Unmarshal([]byte(raw), &p); err != nil {
|
||||
return c, err
|
||||
}
|
||||
}
|
||||
if allowed != nil || !on || !p.DigestEnabled || p.Version != c.Version {
|
||||
state, reason = "cancelled", "consent_changed"
|
||||
}
|
||||
loc, e := time.LoadLocation(c.Timezone)
|
||||
if e != nil || now.In(loc).Format("2006-01-02") != c.Day {
|
||||
state, reason = "cancelled", "day_expired"
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `UPDATE organizer_digest_attempts SET state=?,reason=? WHERE uuid=?`, state, reason, c.AttemptUUID); err != nil {
|
||||
return c, err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `UPDATE organizer_digest_deliveries SET state=?,updated_ms=? WHERE domain_uuid=? AND owner_uuid=? AND day=? AND attempt_uuid=?`, state, now.UnixMilli(), c.Domain, c.Owner, c.Day, c.AttemptUUID); err != nil {
|
||||
return c, err
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
return c, err
|
||||
}
|
||||
if state != "sending" {
|
||||
return c, sql.ErrNoRows
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *Store) FinishTaskDigestReason(ctx context.Context, c TaskDigestClaim, state, reason string, now time.Time) error {
|
||||
if s.ReadOnly {
|
||||
return ErrReadOnly
|
||||
}
|
||||
if state != "sent" && state != "uncertain" && state != "cancelled" {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
switch reason {
|
||||
case "", "smtp_unavailable", "tasks_unavailable", "consent_changed", "transport_uncertain", "extension_disabled":
|
||||
default:
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
tx, err := s.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
res, err := tx.ExecContext(ctx, `UPDATE organizer_digest_deliveries SET state=?,updated_ms=? WHERE domain_uuid=? AND owner_uuid=? AND day=? AND attempt_uuid=? AND state='sending'`, state, now.UnixMilli(), c.Domain, c.Owner, c.Day, c.AttemptUUID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n != 1 {
|
||||
return ErrTaskConflict
|
||||
}
|
||||
res, err = tx.ExecContext(ctx, `UPDATE organizer_digest_attempts SET state=?,reason=?,updated_ms=? WHERE uuid=? AND state='sending'`, state, reason, now.UnixMilli(), c.AttemptUUID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, err = res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n != 1 {
|
||||
return ErrTaskConflict
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (s *Store) TaskDigestHistory(ctx context.Context, domain, actor, after string, limit int, now time.Time) (TaskDigestHistory, error) {
|
||||
out := TaskDigestHistory{Items: []TaskDigestAttempt{}, RetentionDays: TaskDigestRetentionDays}
|
||||
p, err := s.TaskPreferences(ctx, domain, actor)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
loc, err := time.LoadLocation(p.Timezone)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.Today = now.In(loc).Format("2006-01-02")
|
||||
out.Enabled = p.DigestEnabled
|
||||
if limit < 1 || limit > 100 {
|
||||
return out, ErrTaskInvalid
|
||||
}
|
||||
query := `SELECT ` + digestAttemptColumns + ` FROM organizer_digest_attempts WHERE domain_uuid=? AND owner_uuid=?`
|
||||
args := []any{domain, actor}
|
||||
if after != "" {
|
||||
if len(after) > 256 {
|
||||
return out, ErrTaskInvalid
|
||||
}
|
||||
var cursor struct {
|
||||
MS int64
|
||||
ID string
|
||||
}
|
||||
raw, e := base64.RawURLEncoding.DecodeString(after)
|
||||
if e != nil || json.Unmarshal(raw, &cursor) != nil || cursor.MS < 0 || len(cursor.ID) > 80 || cursor.ID == "" {
|
||||
return out, ErrTaskInvalid
|
||||
}
|
||||
query += ` AND (created_ms,uuid)<(?,?)`
|
||||
args = append(args, cursor.MS, cursor.ID)
|
||||
}
|
||||
query += ` ORDER BY created_ms DESC,uuid DESC LIMIT ?`
|
||||
args = append(args, limit+1)
|
||||
rows, err := s.DB.QueryContext(ctx, query, args...)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
for rows.Next() {
|
||||
v, e := scanDigestAttempt(rows)
|
||||
if e != nil {
|
||||
rows.Close()
|
||||
return out, e
|
||||
}
|
||||
out.Items = append(out.Items, v)
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
if len(out.Items) > limit {
|
||||
out.Items = out.Items[:limit]
|
||||
last := out.Items[limit-1]
|
||||
raw, _ := json.Marshal(struct {
|
||||
MS int64
|
||||
ID string
|
||||
}{last.CreatedMS, last.UUID})
|
||||
out.Next = base64.RawURLEncoding.EncodeToString(raw)
|
||||
}
|
||||
current, e := scanDigestAttempt(s.DB.QueryRowContext(ctx, `SELECT `+digestAttemptColumns+` FROM organizer_digest_attempts WHERE uuid=(SELECT attempt_uuid FROM organizer_digest_deliveries WHERE domain_uuid=? AND owner_uuid=? AND day=?)`, domain, actor, out.Today))
|
||||
if e == nil {
|
||||
out.Current = ¤t
|
||||
} else if !errors.Is(e, sql.ErrNoRows) {
|
||||
return out, e
|
||||
}
|
||||
err = s.DB.QueryRowContext(ctx, `SELECT count(*) FROM organizer_digest_requests WHERE domain_uuid=? AND owner_uuid=? AND day=?`, domain, actor, out.Today).Scan(&out.Retries)
|
||||
return out, err
|
||||
}
|
||||
|
||||
// Only detailed terminal attempts expire. Reservations and request receipts are
|
||||
// permanent deduplication state; retention must never delete them.
|
||||
func (s *Store) MaintainTaskDigests(ctx context.Context, now time.Time) (int64, error) {
|
||||
if s.ReadOnly {
|
||||
return 0, ErrReadOnly
|
||||
}
|
||||
tx, err := s.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
_, err = tx.ExecContext(ctx, `UPDATE organizer_digest_attempts SET state='uncertain',reason='worker_interrupted',updated_ms=? WHERE uuid IN (SELECT uuid FROM organizer_digest_attempts WHERE state='sending' AND updated_ms<? ORDER BY updated_ms,uuid LIMIT 100)`, now.UnixMilli(), now.Add(-10*time.Minute).UnixMilli())
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, `UPDATE organizer_digest_deliveries SET state='uncertain',updated_ms=? WHERE state='sending' AND attempt_uuid IN (SELECT uuid FROM organizer_digest_attempts WHERE state='uncertain' AND reason='worker_interrupted' AND updated_ms=?)`, now.UnixMilli(), now.UnixMilli())
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
res, err := tx.ExecContext(ctx, `DELETE FROM organizer_digest_attempts WHERE uuid IN (SELECT uuid FROM organizer_digest_attempts WHERE state IN ('sent','uncertain','cancelled') AND updated_ms<? ORDER BY updated_ms,uuid LIMIT 500)`, now.Add(-TaskDigestRetentionDays*24*time.Hour).UnixMilli())
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return n, tx.Commit()
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -28,7 +29,36 @@ var taskProductivityMigrations = []db.SQLMigration{{Version: 1, Name: "task_capt
|
||||
schemaIndex("organizer_work_sessions", "organizer_work_period", "domain_uuid,owner_uuid,start_ms,uuid"),
|
||||
}}, {Version: 2, Name: "personal_dashboard_layout", Statements: []string{
|
||||
`CREATE TABLE organizer_dashboard_layouts(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,version INTEGER NOT NULL,data TEXT NOT NULL,PRIMARY KEY(domain_uuid,owner_uuid))`,
|
||||
}, Assertions: []string{schemaColumns("organizer_dashboard_layouts", "domain_uuid,owner_uuid,version,data"), schemaUnique("organizer_dashboard_layouts", "domain_uuid,owner_uuid")}}}
|
||||
}, Assertions: []string{schemaColumns("organizer_dashboard_layouts", "domain_uuid,owner_uuid,version,data"), schemaUnique("organizer_dashboard_layouts", "domain_uuid,owner_uuid")}}, {
|
||||
Version: 3, Name: "work_corrections_and_audit",
|
||||
AddColumns: []db.SQLiteColumn{{Table: "organizer_work_sessions", Name: "cancelled_ms", Declaration: "INTEGER NOT NULL DEFAULT 0"}},
|
||||
Statements: []string{`CREATE TABLE organizer_work_revisions(work_uuid TEXT NOT NULL,version INTEGER NOT NULL,domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,action TEXT NOT NULL,reason TEXT NOT NULL,changed_ms INTEGER NOT NULL,data TEXT NOT NULL,PRIMARY KEY(work_uuid,version))`, `CREATE INDEX organizer_work_owner_period ON organizer_work_sessions(owner_uuid,start_ms,uuid)`},
|
||||
Assertions: []string{schemaColumns("organizer_work_sessions", "uuid,domain_uuid,owner_uuid,task_uuid,start_ms,end_ms,version,cancelled_ms"), schemaUnique("organizer_work_revisions", "work_uuid,version"), schemaUnique("organizer_dashboard_layouts", "domain_uuid,owner_uuid")},
|
||||
}, {
|
||||
Version: 4, Name: "digest_attempts_and_retry_receipts",
|
||||
Statements: []string{
|
||||
`ALTER TABLE organizer_digest_deliveries ADD COLUMN attempt_uuid TEXT NOT NULL DEFAULT ''`,
|
||||
`CREATE INDEX organizer_digest_delivery_state ON organizer_digest_deliveries(state,attempt_uuid)`,
|
||||
`CREATE TABLE organizer_digest_attempts(uuid TEXT PRIMARY KEY,domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,day TEXT NOT NULL,kind TEXT NOT NULL,state TEXT NOT NULL,preference_version INTEGER NOT NULL,timezone TEXT NOT NULL,reason TEXT NOT NULL DEFAULT '',created_ms INTEGER NOT NULL,updated_ms INTEGER NOT NULL)`,
|
||||
`CREATE INDEX organizer_digest_history ON organizer_digest_attempts(domain_uuid,owner_uuid,created_ms,uuid)`,
|
||||
`CREATE INDEX organizer_digest_pending ON organizer_digest_attempts(state,updated_ms,uuid)`,
|
||||
`CREATE TABLE organizer_digest_requests(uuid TEXT PRIMARY KEY,domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,day TEXT NOT NULL,expected_attempt TEXT NOT NULL,duplicate_ack INTEGER NOT NULL,created_ms INTEGER NOT NULL)`,
|
||||
`CREATE INDEX organizer_digest_request_day ON organizer_digest_requests(domain_uuid,owner_uuid,day)`,
|
||||
`UPDATE organizer_digest_deliveries SET attempt_uuid='legacy-'||lower(hex(randomblob(16)))`,
|
||||
`INSERT INTO organizer_digest_attempts SELECT attempt_uuid,domain_uuid,owner_uuid,day,'legacy',state,0,'','legacy',updated_ms,updated_ms FROM organizer_digest_deliveries`,
|
||||
}, Assertions: []string{
|
||||
schemaColumns("organizer_work_sessions", "uuid,domain_uuid,owner_uuid,task_uuid,start_ms,end_ms,version,cancelled_ms"),
|
||||
schemaUnique("organizer_work_revisions", "work_uuid,version"),
|
||||
schemaUnique("organizer_dashboard_layouts", "domain_uuid,owner_uuid"),
|
||||
schemaColumns("organizer_digest_deliveries", "domain_uuid,owner_uuid,day,state,updated_ms,attempt_uuid"),
|
||||
schemaUnique("organizer_digest_deliveries", "domain_uuid,owner_uuid,day"),
|
||||
schemaColumns("organizer_digest_attempts", "uuid,domain_uuid,owner_uuid,day,kind,state,preference_version,timezone,reason,created_ms,updated_ms"),
|
||||
schemaUnique("organizer_digest_attempts", "uuid"),
|
||||
schemaIndex("organizer_digest_attempts", "organizer_digest_pending", "state,updated_ms,uuid"),
|
||||
schemaColumns("organizer_digest_requests", "uuid,domain_uuid,owner_uuid,day,expected_attempt,duplicate_ack,created_ms"),
|
||||
schemaUnique("organizer_digest_requests", "uuid"),
|
||||
},
|
||||
}}
|
||||
|
||||
type TaskPreferences struct {
|
||||
Version int64 `json:"version"`
|
||||
@@ -235,20 +265,21 @@ func (s *Store) CaptureTaskWithWiki(ctx context.Context, domain, actor, request,
|
||||
}
|
||||
|
||||
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"`
|
||||
UUID string `json:"uuid"`
|
||||
TaskUUID string `json:"task_uuid"`
|
||||
StartMS int64 `json:"start_ms"`
|
||||
EndMS int64 `json:"end_ms"`
|
||||
Version int64 `json:"version"`
|
||||
CancelledMS int64 `json:"cancelled_ms,omitempty"`
|
||||
}
|
||||
|
||||
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)
|
||||
err := row.Scan(&v.UUID, &v.TaskUUID, &v.StartMS, &v.EndMS, &v.Version, &v.CancelledMS)
|
||||
return v, err
|
||||
}
|
||||
|
||||
const taskWorkColumns = `uuid,task_uuid,start_ms,end_ms,version`
|
||||
const taskWorkColumns = `uuid,task_uuid,start_ms,end_ms,version,cancelled_ms`
|
||||
|
||||
func (s *Store) ActiveTaskWork(ctx context.Context, domain, actor string) (*TaskWork, error) {
|
||||
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||
@@ -261,7 +292,7 @@ func (s *Store) ActiveTaskWork(ctx context.Context, domain, actor string) (*Task
|
||||
return &v, err
|
||||
}
|
||||
|
||||
func (s *Store) ChangeTaskWork(ctx context.Context, domain, actor, action string, v TaskWork, now time.Time) (TaskWork, error) {
|
||||
func (s *Store) ChangeTaskWork(ctx context.Context, domain, actor, action string, v TaskWork, now time.Time, reasons ...string) (TaskWork, error) {
|
||||
if s.ReadOnly {
|
||||
return v, ErrReadOnly
|
||||
}
|
||||
@@ -280,6 +311,16 @@ func (s *Store) ChangeTaskWork(ctx context.Context, domain, actor, action string
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return v, err
|
||||
}
|
||||
if action == "correct" || action == "cancel" {
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
reason := ""
|
||||
if len(reasons) > 0 {
|
||||
reason = reasons[0]
|
||||
}
|
||||
return correctTaskWork(ctx, tx, domain, actor, action, reason, v, old, now)
|
||||
}
|
||||
switch action {
|
||||
case "start":
|
||||
if v.Version != 0 {
|
||||
@@ -300,6 +341,7 @@ func (s *Store) ChangeTaskWork(ctx context.Context, domain, actor, action string
|
||||
}
|
||||
v.StartMS = now.UnixMilli()
|
||||
v.EndMS = 0
|
||||
v.CancelledMS = 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 {
|
||||
@@ -313,6 +355,9 @@ func (s *Store) ChangeTaskWork(ctx context.Context, domain, actor, action string
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
if old.CancelledMS != 0 {
|
||||
return v, ErrTaskConflict
|
||||
}
|
||||
if old.EndMS > 0 {
|
||||
if v.Version == old.Version || v.Version == old.Version-1 {
|
||||
return old, tx.Commit()
|
||||
@@ -332,6 +377,14 @@ func (s *Store) ChangeTaskWork(ctx context.Context, domain, actor, action string
|
||||
default:
|
||||
return v, ErrTaskInvalid
|
||||
}
|
||||
if action == "stop" {
|
||||
if err = auditTaskWork(ctx, tx, domain, actor, "baseline", "", old, now); err != nil {
|
||||
return v, err
|
||||
}
|
||||
}
|
||||
if err = auditTaskWork(ctx, tx, domain, actor, action, "", v, now); err != nil {
|
||||
return v, err
|
||||
}
|
||||
return v, tx.Commit()
|
||||
}
|
||||
|
||||
@@ -344,19 +397,21 @@ type TaskReportDay struct {
|
||||
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"`
|
||||
UUID string `json:"uuid"`
|
||||
Title string `json:"title"`
|
||||
ProjectUUID string `json:"project_uuid"`
|
||||
ProjectTitle string `json:"project_title"`
|
||||
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"`
|
||||
Days []TaskReportDay `json:"days"`
|
||||
Tasks []TaskReportItem `json:"tasks"`
|
||||
Sessions []TaskWork `json:"sessions"`
|
||||
Partial bool `json:"partial"`
|
||||
Timezone string `json:"timezone"`
|
||||
Projects []TaskReportProject `json:"projects"`
|
||||
}
|
||||
|
||||
func (s *Store) TaskReport(ctx context.Context, domain, actor string, start, end, now time.Time) (TaskReport, error) {
|
||||
@@ -373,7 +428,7 @@ func (s *Store) TaskReport(ctx context.Context, domain, actor string, start, end
|
||||
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())
|
||||
rows, err := s.DB.QueryContext(ctx, `SELECT m.completed_ms,m.estimate,m.complexity,m.task_uuid,COALESCE(i.title,''),COALESCE(i.project_uuid,''),COALESCE(p.title,'') 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 LEFT JOIN organizer_items p ON p.uuid=i.project_uuid AND p.domain_uuid=m.domain_uuid AND p.owner_uuid=m.owner_uuid AND p.kind='project' 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
|
||||
}
|
||||
@@ -381,8 +436,8 @@ func (s *Store) TaskReport(ctx context.Context, domain, actor string, start, end
|
||||
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 {
|
||||
var id, title, project, projectTitle string
|
||||
if err = rows.Scan(&ms, &estimate, &complexity, &id, &title, &project, &projectTitle); err != nil {
|
||||
rows.Close()
|
||||
return out, err
|
||||
}
|
||||
@@ -397,7 +452,7 @@ func (s *Store) TaskReport(ctx context.Context, domain, actor string, start, end
|
||||
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)})
|
||||
out.Tasks = append(out.Tasks, TaskReportItem{UUID: id, Title: title, ProjectUUID: project, ProjectTitle: projectTitle, Completed: true, Points: 1 + ((estimate+29)/30)*max(1, complexity)})
|
||||
}
|
||||
}
|
||||
err = rows.Err()
|
||||
@@ -428,15 +483,15 @@ func (s *Store) TaskReport(ctx context.Context, domain, actor string, start, end
|
||||
}
|
||||
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())
|
||||
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,''),COALESCE(p.title,'') 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 LEFT JOIN organizer_items p ON p.uuid=i.project_uuid AND p.domain_uuid=w.domain_uuid AND p.owner_uuid=w.owner_uuid AND p.kind='project' WHERE w.cancelled_ms=0 AND 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 {
|
||||
var title, project, projectTitle string
|
||||
if err = rows.Scan(&v.UUID, &v.TaskUUID, &v.StartMS, &v.EndMS, &v.Version, &title, &project, &projectTitle); err != nil {
|
||||
rows.Close()
|
||||
return out, err
|
||||
}
|
||||
@@ -458,7 +513,7 @@ func (s *Store) TaskReport(ctx context.Context, domain, actor string, start, end
|
||||
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 = append(out.Tasks, TaskReportItem{UUID: v.TaskUUID, Title: title, ProjectUUID: project, ProjectTitle: projectTitle})
|
||||
}
|
||||
out.Tasks[index].WorkMS += elapsed
|
||||
}
|
||||
@@ -485,5 +540,39 @@ func (s *Store) TaskReport(ctx context.Context, domain, actor string, start, end
|
||||
}
|
||||
addSpan(a, b, true)
|
||||
}
|
||||
return out, rows.Err()
|
||||
if err = rows.Err(); err != nil {
|
||||
return out, err
|
||||
}
|
||||
groups := map[string]*TaskReportProject{}
|
||||
for _, task := range out.Tasks {
|
||||
p := groups[task.ProjectUUID]
|
||||
if p == nil {
|
||||
p = &TaskReportProject{UUID: task.ProjectUUID, Title: task.ProjectTitle}
|
||||
groups[task.ProjectUUID] = p
|
||||
}
|
||||
if task.Completed {
|
||||
p.Completed++
|
||||
}
|
||||
p.Points += task.Points
|
||||
p.WorkMS += task.WorkMS
|
||||
}
|
||||
out.Projects = []TaskReportProject{}
|
||||
for _, p := range groups {
|
||||
out.Projects = append(out.Projects, *p)
|
||||
}
|
||||
sort.Slice(out.Projects, func(i, j int) bool {
|
||||
if out.Projects[i].Title != out.Projects[j].Title {
|
||||
return out.Projects[i].Title < out.Projects[j].Title
|
||||
}
|
||||
return out.Projects[i].UUID < out.Projects[j].UUID
|
||||
})
|
||||
return out, nil
|
||||
}
|
||||
|
||||
type TaskReportProject struct {
|
||||
UUID string `json:"uuid"`
|
||||
Title string `json:"title"`
|
||||
Completed int `json:"completed"`
|
||||
Points int `json:"points"`
|
||||
WorkMS int64 `json:"work_ms"`
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type TaskWorkRevision struct {
|
||||
Item TaskWork `json:"item"`
|
||||
Action string `json:"action"`
|
||||
Reason string `json:"reason"`
|
||||
ChangedMS int64 `json:"changed_ms"`
|
||||
}
|
||||
|
||||
func auditTaskWork(ctx context.Context, tx *sql.Tx, domain, actor, action, reason string, v TaskWork, now time.Time) error {
|
||||
raw, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Legacy sessions acquire a baseline lazily. Never rewrite an earlier audit.
|
||||
query := `INSERT INTO organizer_work_revisions(work_uuid,version,domain_uuid,owner_uuid,action,reason,changed_ms,data) VALUES(?,?,?,?,?,?,?,?)`
|
||||
if action == "baseline" {
|
||||
query += ` ON CONFLICT(work_uuid,version) DO NOTHING`
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, query, v.UUID, v.Version, domain, actor, action, reason, now.UnixMilli(), string(raw))
|
||||
return err
|
||||
}
|
||||
|
||||
func correctTaskWork(ctx context.Context, tx *sql.Tx, domain, actor, action, reason string, v, old TaskWork, now time.Time) (TaskWork, error) {
|
||||
reason = strings.TrimSpace(reason)
|
||||
if reason == "" || len(reason) > 500 || !utf8.ValidString(reason) || strings.ContainsAny(reason, "\x00\r\n") {
|
||||
return v, ErrTaskInvalid
|
||||
}
|
||||
if v.Version < 1 || old.EndMS == 0 || old.CancelledMS != 0 {
|
||||
return v, ErrTaskConflict
|
||||
}
|
||||
if old.Version != v.Version {
|
||||
return v, ErrTaskConflict
|
||||
}
|
||||
if v.TaskUUID != "" && v.TaskUUID != old.TaskUUID {
|
||||
return v, ErrTaskInvalid
|
||||
}
|
||||
result := old
|
||||
if action == "correct" {
|
||||
if v.StartMS <= 0 || v.EndMS <= v.StartMS || v.EndMS > now.UnixMilli() || v.EndMS-v.StartMS > int64(31*24*time.Hour/time.Millisecond) {
|
||||
return v, ErrTaskInvalid
|
||||
}
|
||||
// Adjacent spans are valid; double-counted elapsed time is not. Scope across
|
||||
// Domains like the existing one-active-session constraint, without disclosing them.
|
||||
var overlap bool
|
||||
err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM organizer_work_sessions WHERE owner_uuid=? AND uuid<>? AND cancelled_ms=0 AND start_ms<? AND (end_ms=0 OR end_ms>?))`, actor, old.UUID, v.EndMS, v.StartMS).Scan(&overlap)
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
if overlap {
|
||||
return v, ErrTaskConflict
|
||||
}
|
||||
result.StartMS = v.StartMS
|
||||
result.EndMS = v.EndMS
|
||||
} else {
|
||||
result.CancelledMS = now.UnixMilli()
|
||||
}
|
||||
if err := auditTaskWork(ctx, tx, domain, actor, "baseline", "", old, now); err != nil {
|
||||
return v, err
|
||||
}
|
||||
result.Version++
|
||||
updated, err := tx.ExecContext(ctx, `UPDATE organizer_work_sessions SET start_ms=?,end_ms=?,cancelled_ms=?,version=? WHERE uuid=? AND domain_uuid=? AND owner_uuid=? AND version=?`, result.StartMS, result.EndMS, result.CancelledMS, result.Version, old.UUID, domain, actor, old.Version)
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
if count, err := updated.RowsAffected(); err != nil {
|
||||
return v, err
|
||||
} else if count != 1 {
|
||||
return v, ErrTaskConflict
|
||||
}
|
||||
if err := auditTaskWork(ctx, tx, domain, actor, action, reason, result, now); err != nil {
|
||||
return v, err
|
||||
}
|
||||
return result, tx.Commit()
|
||||
}
|
||||
|
||||
type TaskWorkEntry struct {
|
||||
TaskWork
|
||||
Title string `json:"title"`
|
||||
ProjectUUID string `json:"project_uuid"`
|
||||
}
|
||||
type TaskWorkPage struct {
|
||||
Items []TaskWorkEntry `json:"items"`
|
||||
Next string `json:"next"`
|
||||
}
|
||||
type workCursor struct {
|
||||
Start int64 `json:"start"`
|
||||
UUID string `json:"uuid"`
|
||||
}
|
||||
|
||||
func (s *Store) TaskWorkHistory(ctx context.Context, domain, actor string, start, end time.Time, after string, limit int) (TaskWorkPage, error) {
|
||||
out := TaskWorkPage{Items: []TaskWorkEntry{}}
|
||||
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 || limit < 1 || limit > 100 {
|
||||
return out, ErrTaskInvalid
|
||||
}
|
||||
query := `SELECT w.uuid,w.task_uuid,w.start_ms,w.end_ms,w.version,w.cancelled_ms,COALESCE(i.title,''),COALESCE(i.project_uuid,'') FROM organizer_work_sessions w LEFT JOIN organizer_items i ON i.uuid=w.task_uuid AND i.domain_uuid=w.domain_uuid AND i.owner_uuid=w.owner_uuid WHERE w.domain_uuid=? AND w.owner_uuid=? AND w.start_ms<? AND (w.end_ms=0 OR w.end_ms>?)`
|
||||
args := []any{domain, actor, end.UnixMilli(), start.UnixMilli()}
|
||||
if after != "" {
|
||||
if len(after) > 256 {
|
||||
return out, ErrTaskInvalid
|
||||
}
|
||||
raw, err := base64.RawURLEncoding.DecodeString(after)
|
||||
var cursor workCursor
|
||||
if err != nil || json.Unmarshal(raw, &cursor) != nil || cursor.Start <= 0 {
|
||||
return out, ErrTaskInvalid
|
||||
}
|
||||
if id, err := uuid.Parse(cursor.UUID); err != nil || id.String() != cursor.UUID {
|
||||
return out, ErrTaskInvalid
|
||||
}
|
||||
query += ` AND (w.start_ms,w.uuid)<(?,?)`
|
||||
args = append(args, cursor.Start, cursor.UUID)
|
||||
}
|
||||
query += ` ORDER BY w.start_ms DESC,w.uuid DESC LIMIT ?`
|
||||
args = append(args, limit+1)
|
||||
rows, err := s.DB.QueryContext(ctx, query, args...)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var v TaskWorkEntry
|
||||
if err = rows.Scan(&v.UUID, &v.TaskUUID, &v.StartMS, &v.EndMS, &v.Version, &v.CancelledMS, &v.Title, &v.ProjectUUID); err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.Items = append(out.Items, v)
|
||||
}
|
||||
if len(out.Items) > limit {
|
||||
out.Items = out.Items[:limit]
|
||||
last := out.Items[limit-1]
|
||||
raw, _ := json.Marshal(workCursor{Start: last.StartMS, UUID: last.UUID})
|
||||
out.Next = base64.RawURLEncoding.EncodeToString(raw)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) TaskWorkRevisions(ctx context.Context, domain, actor, id string, before int64) ([]TaskWorkRevision, error) {
|
||||
out := []TaskWorkRevision{}
|
||||
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||
return out, err
|
||||
}
|
||||
if before < 0 {
|
||||
return out, ErrTaskInvalid
|
||||
}
|
||||
current, err := scanTaskWork(s.DB.QueryRowContext(ctx, `SELECT `+taskWorkColumns+` FROM organizer_work_sessions WHERE uuid=? AND domain_uuid=? AND owner_uuid=?`, id, domain, actor))
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
if before == 0 {
|
||||
before = current.Version + 1
|
||||
}
|
||||
rows, err := s.DB.QueryContext(ctx, `SELECT action,reason,changed_ms,data FROM organizer_work_revisions WHERE work_uuid=? AND domain_uuid=? AND owner_uuid=? AND version<? ORDER BY version DESC LIMIT 100`, id, domain, actor, before)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var v TaskWorkRevision
|
||||
var raw string
|
||||
if err = rows.Scan(&v.Action, &v.Reason, &v.ChangedMS, &raw); err != nil {
|
||||
return out, err
|
||||
}
|
||||
if err = json.Unmarshal([]byte(raw), &v.Item); err != nil {
|
||||
return out, err
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
if len(out) == 0 && before > current.Version {
|
||||
out = append(out, TaskWorkRevision{Item: current, Action: "baseline"})
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
Reference in new issue
Block a user