garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /web/src/lib/focus.ts

raw

import {post} from '@/lib/api'
import {local} from '@/lib/reactive'

/**
 * Focus (focus.rs): how much deciding the person does, against limits they
 * set themselves — a daily cap of points and of sessions at work, decision
 * blocks, quiet hours — and the rules the autopilot may decide by.
 */

export interface FocusSettings {
    cap_points: number | null
    cap_sessions: number | null
    /** Times of day ("15:00") when held questions are announced at once. */
    blocks: string[]
    /** Hold what can wait between blocks: no push for it. */
    hold: boolean
    quiet_from: string | null
    quiet_until: string | null
    tz_min: number
    /** The person's rules apply in sessions without the autopilot too. */
    rules_everywhere: boolean
    /** How long an answer of the autopilot's can be taken back from the digest, in minutes. */
    undo_min: number
}

export interface FocusDay {
    points: number
    decisions: number
    switches: number
    interruptions: number
    own_words: number
    late: number
    landings: number
    /** The most sessions at work at once, as the decisions saw it. */
    peak: number
    near_cap?: boolean
    at_cap?: boolean
    date?: string
    checkin?: number | null
}

/** An answer the autopilot gave for the person. */
export interface PilotAnswer {
    at: number
    session: string
    n: number
    kind: 'question' | 'permission' | 'message'
    question: string
    answer: unknown
    why?: string | null
    basis?: 'rule' | 'precedent' | 'judgement' | null
    rule?: string | null
    sure?: boolean | null
    saved: number
    undone: boolean
    undo_until: number
}

export interface Rule {
    id: string
    text: string
    state: 'approved' | 'suggested' | 'rejected'
    by: string
    at: number
    uses: number
    last_used?: number
    evidence?: string
    session?: string | null
}

export interface Focus {
    person: string
    now: number
    settings: FocusSettings
    today: FocusDay
    /** The block open now ("15:00"), and the next one's start. */
    block: string | null
    next_block: number | null
    quiet: boolean
    /** What can wait is held now: no push for it. */
    holding: boolean
    /** How many things wait that can wait. */
    held: number
    at_work: number
    pilot: PilotAnswer[]
    saved: number
    week: FocusDay[]
    rules: Rule[]
    checkin: number | null
    suggested_cap: {cap: number; fresh: number; fried: number; fresh_days: number; fried_days: number} | null
}

/** Minutes east of UTC, as the hub counts the person's day. */
export const tzMin = () => -new Date().getTimezoneOffset()

export const focus = local({data: null as Focus | null, error: '', loading: false, at: 0})

/** Fetch it again, unless it was fetched in the last `fresh_ms`. */
export async function loadFocus(fresh_ms = 0): Promise<void> {
    if (focus.loading || (fresh_ms && Date.now() - focus.at < fresh_ms)) return
    focus.loading = true
    try {
        const r = await fetch(`/v1/focus?tz=${tzMin()}`)
        if (!r.ok) throw new Error(`${r.status}`)
        focus.data = (await r.json()) as Focus
        focus.error = ''
        focus.at = Date.now()
    } catch (e) {
        focus.error = (e as Error).message
    } finally {
        focus.loading = false
    }
}

export const focusApi = {
    settings: (s: Partial<FocusSettings>) => post('/v1/focus/settings', {...s, tz_min: tzMin()}) as Promise<FocusSettings>,
    rule: (op: 'add' | 'approve' | 'reject' | 'edit' | 'remove', fields: {id?: string; text?: string; session?: string}) =>
        post('/v1/focus/rules', {op, ...fields}) as Promise<{rules: Rule[]}>,
    checkin: (rating: number) => post('/v1/focus/checkin', {rating}),
    undo: (session: string, n: number) => post('/v1/focus/undo', {session, n}),
}

/** Where today stands against the cap: its share (0…1+), or null without a cap. */
export function capShare(f: Focus): number | null {
    return f.settings.cap_points ? f.today.points / f.settings.cap_points : null
}

/** "HH:MM, HH:MM" from what the person typed: times kept, the rest dropped. */
export function parseBlocks(text: string): string[] {
    return text
        .split(/[,\s]+/)
        .map((t) => t.trim())
        .filter((t) => /^\d{1,2}:\d{2}$/.test(t))
}

/** A rule from a question the person just answered: in their words, editable later. */
export function ruleFromQuestion(question: string): string {
    const q = question.replace(/\s+/g, ' ').trim()
    const short = q.length > 160 ? `${q.slice(0, 157)}…` : q
    return `When a session asks “${short}”, take the recommended option if it fits what I asked.`
}

/** An answer as words: a pick, several, or the form's fields. */
export function answerWords(a: unknown): string {
    if (typeof a === 'string') return a
    if (Array.isArray(a)) return a.join(', ')
    if (a && typeof a === 'object') {
        const vals = Object.entries(a as Record<string, unknown>)
            .filter(([, v]) => v !== '' && v != null)
            .map(([, v]) => (Array.isArray(v) ? v.join(', ') : String(v)))
        return vals.join('; ')
    }
    return ''
}