Skip to content

src/complete.ts

30 lines · 1.1 KB · TypeScript
Raw
import { InputError, parseInput } from './lib/validate.ts'
import { byField, idField } from './lib/fields.ts'
import { line, mutateTodo, normalizeId, resolveTimeZone } from './lib/store.ts'

/**
 * Mark a todo/task in the shared todo list as done.
 *
 * @param input - `{ id: string, by: string, note?: string }` — optional note appended to history
 * @returns `{ todo, line }`
 *
 * @example
 * import completeTodo from 'kody:@charlesmatte/todos/complete'
 *
 * await completeTodo({ id: 'T12', by: 'assistant' })
 */
export default async function completeTodo(input: unknown) {
	const p = parseInput<{ id: string; by: string; note?: string }>(
		input,
		{ id: idField, by: byField, note: { type: 'string', maxLength: 1000 } },
		'todos/complete',
	)
	const todo = await mutateTodo(normalizeId(p.id), p.by, 'completed', (t) => {
		if (t.deleted) throw new InputError(`${t.id} is deleted; reopen it first.`)
		if (t.status === 'done') throw new InputError(`${t.id} is already done.`)
		t.status = 'done'
		t.completedAt = new Date().toISOString()
		return p.note ? { note: p.note } : undefined
	})
	return { todo, line: line(todo, await resolveTimeZone()) }
}