feat: track duration of subtask

This commit is contained in:
Jannik Meier committed 2026-11-06 14:39:46 +01:00
1 parent 9fe73950fd
commit d594207a2c
16 files changed
+714 -810

No files matched your search

+33
View File
@@ -0,0 +1,33 @@
# Kimai Raycast Extension
Raycast-Extension für die Zeiterfassung mit Kimai. UI-Texte auf Deutsch, Code und Kommentare auf Englisch.
## Befehle
```sh
npm run dev # Extension in Raycast laden
npm run build # Build prüfen
npx tsc --noEmit -p . && npx eslint src && npx prettier --check src
```
## Komponenten zentral halten und wiederverwenden
Alle Views sollen sich gleich verhalten. Felder, Auswahlen, Listenzeilen und Aktionen werden deshalb nur einmal in `src/lib/` gebaut und überall wiederverwendet. Die Command-Dateien in `src/*.tsx` bleiben dünn und setzen nur die zentralen Bausteine zusammen.
- `lib/timesheet-form.tsx`: **das eine Formular** für Starten, Stoppen, manuelles Erfassen, Bearbeiten und Erfassen nur mit Dauer (`mode`). Neue Felder oder Validierungsregeln kommen hier rein, nicht in einzelne Views.
- `lib/timesheet-list.tsx`: `TimesheetListItem` (gleiche Zeile überall) und `TimesheetActions` (gleiche Aktionen und Shortcuts überall, nur die ↵-Aktion unterscheidet sich).
- `lib/choice-dropdown.tsx`: Tätigkeitsauswahl (Favoriten, zuletzt verwendet, alle). Kunde und Projekt ergeben sich aus der Tätigkeit, es gibt keine getrennten Dropdowns.
- `lib/note-form.tsx`: Notizen zu laufenden Tätigkeiten.
- `lib/actions.ts`: API-Aktionen mit Toasts (starten, löschen, Favorit).
- `lib/hooks.ts`, `lib/utils.ts`: Daten-Hooks und reine Hilfsfunktionen (Zeit-Parsing, Formatierung).
Vor dem Bauen neuer UI zuerst prüfen, ob es dafür schon einen Baustein gibt, und ihn erweitern statt zu duplizieren. Braucht eine View eine Abweichung, wird sie als Prop des zentralen Bausteins umgesetzt. Taucht Code ein zweites Mal auf, wird er nach `src/lib/` verschoben.
## Einheitliche Regeln
- Zeiten: Feld »Datum« plus »Von«/»Bis« als Textfelder (`8:30`, `0830`). Liegt »Bis« vor »Von«, endet der Eintrag am Folgetag.
- Zeiten sind Wall-Clock-Zeiten des Kimai-Benutzers und werden ohne Zeitzonenumrechnung gesendet (`kimaiDateAt`, `kimaiParts`). Nur »jetzt« wird über `nowParts(timezone)` in die Kimai-Zeitzone umgerechnet.
- Vorbelegung: Starten mit Von = jetzt, Stoppen mit Bis = jetzt (minutengenau), beide änderbar.
- Pause leer = Kimai setzt sie nach seinen Regeln. Eine Änderung der Dauer verschiebt »Bis«.
- Beschreibung ist Pflicht, sobald »Bis« gesetzt ist.
- Tags kommagetrennt. Unbekannte Tags legt `api.ts` vorher an.
+9 -6
View File
@@ -6,16 +6,19 @@ Zeiterfassung mit [Kimai](https://www.kimai.org) direkt aus Raycast.
| Befehl | Funktion |
| --- | --- |
| **Tätigkeit starten** | Formular mit »Von« (vorbelegt mit jetzt) und Tätigkeitsauswahl. Favoriten und zuletzt genutzte Tätigkeiten stehen oben, Kunde und Projekt ergeben sich aus der Tätigkeit. Optional Beschreibung und Tags. |
| **Tätigkeit stoppen** | Listet alle laufenden Tätigkeiten. `↵` öffnet das Stopp-Formular, die Beschreibung ist Pflicht. |
| **Tätigkeit starten** | Timesheet-Formular mit Datum und »Von« (vorbelegt mit jetzt) und Tätigkeitsauswahl. Favoriten und zuletzt genutzte Tätigkeiten stehen oben, Kunde und Projekt ergeben sich aus der Tätigkeit. Optional Beschreibung und Tags. |
| **Tätigkeit stoppen** | Listet alle laufenden Tätigkeiten. `↵` öffnet das Timesheet-Formular mit »Bis« = jetzt (minutengenau, änderbar). Die Beschreibung ist Pflicht. |
| **Notiz hinzufügen** | Stichpunkte zur laufenden Tätigkeit notieren, ohne zu stoppen. Direkt aus der Suche: `Notiz hinzufügen` ⇥ Text ↵ (bei genau einer laufenden Tätigkeit wird sofort angehängt). Ohne Text öffnet sich das Notiz-Formular: ↵ speichert den Stichpunkt und leert das Feld für den nächsten, die gesamte Beschreibung ist darunter editierbar. Auch über die Menüleiste und mit `⌘N` in »Tätigkeit stoppen« und »Timesheets verwalten«. Beim Stoppen ist die Beschreibung mit den Stichpunkten vorbefüllt. |
| **Manuelles Timesheet** | Timesheet nachträglich erfassen: Datum, Von, Bis (z. B. `8:30`, `0830`), Pause, Tätigkeit, Beschreibung (Pflicht) und Tags. Die Tätigkeitsauswahl funktioniert wie bei »Tätigkeit starten« (Suche, Favoriten und zuletzt genutzte oben, Kunde und Projekt ergeben sich daraus). Die Dauer wird live angezeigt. Bleibt die Pause leer, setzt Kimai sie nach seinen Regeln. `⌘⇧↵` speichert und öffnet direkt den nächsten Eintrag (Von = letztes Bis). |
| **Timesheets verwalten** | Alle Timesheets des Monats, nach Tagen gruppiert mit Tagessummen (Monatsauswahl oben rechts). `↵` öffnet das Bearbeiten-Formular mit Von, Bis, Dauer, Pause, Kunde, Projekt, Tätigkeit, Beschreibung und Tags. Weitere Aktionen: stoppen bzw. erneut starten, als Favorit markieren, löschen, in Kimai öffnen. |
| **Kimai Menu Bar** | Menüleisten-Eintrag mit laufender Zeit. »Stoppen…« öffnet das Stopp-Formular mit Pflicht-Beschreibung. Favoriten, zuletzt genutzte und alle Tätigkeiten (nach Kunde) starten. Mehrere Tätigkeiten können parallel laufen. |
| **Manuelles Timesheet** | Timesheet nachträglich erfassen im selben Formular: Datum, Von, Bis, Pause, Dauer, Tätigkeit, Beschreibung (Pflicht) und Tags. `⌘⇧↵` speichert und öffnet direkt den nächsten Eintrag (Von = letztes Bis). |
| **Dauer erfassen** | Erledigte Tätigkeit schnell nachtragen: nur Dauer (z. B. `1:30`, `90m`), Tätigkeit und Beschreibung (Pflicht). Der Eintrag endet jetzt und beginnt um die Dauer früher, ohne Pause. |
| **Timesheets verwalten** | Alle Timesheets des Monats, nach Tagen gruppiert mit Tagessummen (Monatsauswahl oben rechts). `↵` öffnet das Timesheet-Formular zum Bearbeiten. Weitere Aktionen: stoppen bzw. erneut starten, als Favorit markieren, löschen, in Kimai öffnen. |
| **Kimai Menu Bar** | Menüleisten-Eintrag mit laufender Zeit. »Stoppen…« öffnet das Timesheet-Formular wie »Tätigkeit stoppen«. Favoriten, zuletzt genutzte und alle Tätigkeiten (nach Kunde) starten. Mehrere Tätigkeiten können parallel laufen. |
## Hinweise
- **Pausen** werden von Kimai automatisch erzeugt. Die Extension sendet beim Starten und Stoppen keine Pause, im Bearbeiten-Formular kann sie angepasst werden.
- **Ein Formular für alles:** Starten, Stoppen, manuelles Erfassen und Bearbeiten nutzen dieselben Felder und Regeln. Zeiten werden als Datum plus »Von«/»Bis« eingegeben (z. B. `8:30`, `0830`). Liegt »Bis« vor »Von«, endet der Eintrag am Folgetag.
- **Gleiche Aktionen in allen Listen:** `⌘E` bearbeiten, `⌘S` stoppen bzw. erneut starten, `⌘N` Notizen, `⌘F` Favorit, `⌘O` in Kimai öffnen, `⌘R` aktualisieren, `⌃X` löschen.
- **Pausen** setzt Kimai nach seinen Regeln, solange das Feld »Pause« leer bleibt.
- **Dauer** lässt sich über die Kimai-API nicht direkt setzen. Wird sie im Formular geändert, wird »Bis« neu berechnet (Bis = Von + Dauer + Pause). Akzeptiert werden z. B. `1:30`, `90m`, `1,5`, `1h 30m`.
- **Tags** werden kommagetrennt eingegeben. Unbekannte Tags legt die Extension vorher in Kimai an, weil die Timesheet-API sie sonst stillschweigend verwirft.
- **Favoriten** sind die in Kimai markierten Favoriten-Timesheets (`/api/favorites/timesheets`) und können in »Timesheets verwalten« mit `⌘F` gesetzt oder entfernt werden.
+7
View File
@@ -46,6 +46,13 @@
"description": "Timesheet nachträglich mit Datum, Von, Bis und Pause erfassen",
"mode": "view"
},
{
"name": "log-activity",
"title": "Dauer erfassen",
"subtitle": "Kimai",
"description": "Erledigte Tätigkeit nur mit Dauer und Beschreibung nachtragen, endet jetzt",
"mode": "view"
},
{
"name": "manage-timesheets",
"title": "Timesheets verwalten",
+16 -30
View File
@@ -1,19 +1,10 @@
import {
Action,
ActionPanel,
closeMainWindow,
Detail,
Icon,
LaunchProps,
List,
PopToRootType,
showHUD,
} from "@raycast/api";
import { Action, closeMainWindow, Detail, Icon, LaunchProps, List, PopToRootType, showHUD } from "@raycast/api";
import { useEffect, useRef } from "react";
import { Timesheet } from "./lib/api";
import { useActive } from "./lib/hooks";
import { useActive, useNow } from "./lib/hooks";
import { appendNote, NoteForm } from "./lib/note-form";
import { colorIcon, formatTime, showError, timesheetSubtitle, timesheetTitle } from "./lib/utils";
import { TimesheetActions, TimesheetListItem } from "./lib/timesheet-list";
import { showError } from "./lib/utils";
type Props = LaunchProps<{
arguments: Arguments.AddNote;
@@ -32,6 +23,7 @@ async function quickAppend(ts: Timesheet, note: string) {
export default function AddNote({ arguments: args, launchContext }: Props) {
const { data, isLoading, revalidate } = useActive();
const now = useNow();
const active = data ?? [];
const note = args.note?.trim() ?? "";
const done = useRef(false);
@@ -59,27 +51,21 @@ export default function AddNote({ arguments: args, launchContext }: Props) {
<List isLoading={isLoading} navigationTitle="Notiz hinzufügen">
<List.EmptyView icon={Icon.Clock} title="Keine laufenden Tätigkeiten" />
{active.map((ts) => (
<List.Item
<TimesheetListItem
key={ts.id}
icon={colorIcon(ts.activity["color-safe"], Icon.Play)}
title={timesheetTitle(ts)}
subtitle={timesheetSubtitle(ts)}
accessories={[
...(ts.description ? [{ icon: Icon.Text, tooltip: ts.description }] : []),
{ text: `seit ${formatTime(ts.begin)}` },
]}
timesheet={ts}
now={now}
actions={
<ActionPanel>
{note ? (
<TimesheetActions
timesheet={ts}
primary="note"
onChanged={revalidate}
first={
note ? (
<Action title={`»${note}« hinzufügen`} icon={Icon.Plus} onAction={() => quickAppend(ts, note)} />
) : (
<Action.Push
title="Notizen schreiben"
icon={Icon.Pencil}
target={<NoteForm timesheet={ts} onSaved={revalidate} />}
) : undefined
}
/>
)}
</ActionPanel>
}
/>
))}
+2 -193
View File
@@ -1,196 +1,5 @@
import { Action, ActionPanel, Form, Icon, popToRoot, showToast, Toast } from "@raycast/api";
import { useEffect, useMemo, useState } from "react";
import { api } from "./lib/api";
import { ChoiceDropdown, choiceKeyOf, firstChoiceValue } from "./lib/choice-dropdown";
import { useCatalog, useStartOptions } from "./lib/hooks";
import { formatDuration, kimaiDateAt, parseDuration, parseChoiceKey, parseTime, showError } from "./lib/utils";
import { TimesheetForm } from "./lib/timesheet-form";
export default function AddTimesheet() {
const { data: catalog, isLoading: catalogLoading } = useCatalog();
const { favorites, recent, isLoading: optionsLoading } = useStartOptions(catalog);
const all = useMemo(() => catalog?.choices ?? [], [catalog]);
const byKey = useMemo(() => new Map(all.map((c) => [c.key, c])), [all]);
const [date, setDate] = useState<Date | null>(new Date());
const [beginStr, setBeginStr] = useState("");
const [endStr, setEndStr] = useState("");
const [breakStr, setBreakStr] = useState("");
const [choice, setChoice] = useState("");
const [description, setDescription] = useState("");
const [tags, setTags] = useState("");
const [errors, setErrors] = useState<Record<string, string | undefined>>({});
const choiceKey = choiceKeyOf(choice);
const selected = byKey.get(choiceKey ?? "");
// preselect the first favorite (or recent) entry once loaded
useEffect(() => {
if (choice || optionsLoading || catalogLoading) return;
const first = firstChoiceValue(favorites, recent, all);
if (first) setChoice(first);
}, [favorites, recent, all, optionsLoading, catalogLoading]);
const clearError = (field: string) => setErrors((e) => ({ ...e, [field]: undefined }));
const begin = parseTime(beginStr);
const end = parseTime(endStr);
const breakSec = parseDuration(breakStr);
const duration =
begin !== undefined && end !== undefined && end > begin && breakSec !== undefined
? (end - begin) * 60 - breakSec
: undefined;
function onTimeChange(field: "begin" | "end", v: string) {
(field === "begin" ? setBeginStr : setEndStr)(v);
if (v.trim() !== "" && parseTime(v) === undefined) {
setErrors((e) => ({ ...e, [field]: "Format z. B. 8:30" }));
} else {
clearError(field);
}
}
function onBreakChange(v: string) {
setBreakStr(v);
if (parseDuration(v) === undefined) setErrors((e) => ({ ...e, break: "Format z. B. 0:30" }));
else clearError("break");
}
/** returns true when saved */
async function submit(): Promise<boolean> {
const errs: Record<string, string> = {};
if (!date) errs.date = "Pflichtfeld";
if (begin === undefined) errs.begin = beginStr.trim() ? "Format z. B. 8:30" : "Pflichtfeld";
if (end === undefined) errs.end = endStr.trim() ? "Format z. B. 17:00" : "Pflichtfeld";
else if (begin !== undefined && end <= begin) errs.end = "Bis muss nach Von liegen";
if (breakSec === undefined) errs.break = "Format z. B. 0:30";
else if (duration !== undefined && duration <= 0) errs.break = "Pause ist länger als die Arbeitszeit";
if (!choiceKey) errs.choice = "Bitte Tätigkeit wählen";
if (!description.trim()) errs.description = "Beschreibung ist Pflicht";
if (Object.keys(errs).length) {
setErrors(errs);
return false;
}
const toast = await showToast({ style: Toast.Style.Animated, title: "Speichere…" });
try {
// times are entered as wall-clock time of the Kimai user, so no timezone conversion
const ts = await api.create({
begin: kimaiDateAt(date!, begin!),
end: kimaiDateAt(date!, end!),
...parseChoiceKey(choiceKey!),
description,
tags: tags.trim() || undefined,
// without a value Kimai applies its own break rules
...(breakStr.trim() ? { break: formatDuration(breakSec ?? 0) } : {}),
});
toast.style = Toast.Style.Success;
toast.title = `Timesheet erstellt: ${ts.activity.name}`;
toast.message = formatDuration(ts.duration);
return true;
} catch (e) {
toast.hide();
await showError("Speichern fehlgeschlagen", e);
return false;
}
}
async function saveAndClose() {
if (await submit()) await popToRoot();
}
// keep date and assignment, continue where the last entry ended
async function saveAndNext() {
if (!(await submit())) return;
setBeginStr(endStr);
setEndStr("");
setBreakStr("");
setDescription("");
}
return (
<Form
isLoading={catalogLoading || optionsLoading}
navigationTitle="Manuelles Timesheet"
actions={
<ActionPanel>
<Action.SubmitForm title="Speichern" icon={Icon.Check} onSubmit={saveAndClose} />
<Action.SubmitForm
title="Speichern und weiteres erfassen"
icon={Icon.Plus}
shortcut={{ modifiers: ["cmd", "shift"], key: "enter" }}
onSubmit={saveAndNext}
/>
</ActionPanel>
}
>
<Form.DatePicker
id="date"
title="Datum"
type={Form.DatePicker.Type.Date}
value={date}
onChange={(v) => {
setDate(v);
clearError("date");
}}
error={errors.date}
/>
<Form.TextField
id="begin"
title="Von"
placeholder="z. B. 8:30"
value={beginStr}
onChange={(v) => onTimeChange("begin", v)}
error={errors.begin}
/>
<Form.TextField
id="end"
title="Bis"
placeholder="z. B. 17:00"
value={endStr}
onChange={(v) => onTimeChange("end", v)}
error={errors.end}
/>
<Form.TextField
id="break"
title="Pause"
placeholder="automatisch"
value={breakStr}
onChange={onBreakChange}
error={errors.break}
info="Leer lassen, damit Kimai die Pause nach seinen Regeln setzt"
/>
{duration !== undefined && duration > 0 && <Form.Description title="Dauer" text={formatDuration(duration)} />}
<Form.Separator />
<ChoiceDropdown
favorites={favorites}
recent={recent}
all={all}
value={choice}
onChange={(v) => {
setChoice(v);
clearError("choice");
}}
error={errors.choice}
/>
{selected && (
<>
<Form.Description title="Kunde" text={selected.customer?.name ?? "–"} />
<Form.Description title="Projekt" text={selected.project.name} />
</>
)}
<Form.Separator />
<Form.TextArea
id="description"
title="Beschreibung"
value={description}
onChange={(v) => {
setDescription(v);
clearError("description");
}}
error={errors.description}
/>
<Form.TextField id="tags" title="Tags" placeholder="kommagetrennt" value={tags} onChange={setTags} />
</Form>
);
return <TimesheetForm mode="create" isRoot />;
}
+31 -15
View File
@@ -1,16 +1,17 @@
import { showToast, Toast } from "@raycast/api";
import { Alert, confirmAlert, showToast, Toast } from "@raycast/api";
import { api, Timesheet } from "./api";
import { formatDuration, parseChoiceKey, showError, toKimaiDate } from "./utils";
import { formatDay, formatTime, parseChoiceKey, showError, toKimaiDate } from "./utils";
export async function startTimesheet(
choiceKey: string,
options: { begin?: Date; timezone?: string; description?: string; tags?: string } = {},
/** begin as Kimai local datetime, defaults to now */
options: { begin?: string; timezone?: string; description?: string; tags?: string } = {},
) {
const { project, activity } = parseChoiceKey(choiceKey);
const toast = await showToast({ style: Toast.Style.Animated, title: "Starte Tätigkeit…" });
try {
const ts = await api.create({
begin: toKimaiDate(options.begin ?? new Date(), options.timezone),
begin: options.begin ?? toKimaiDate(new Date(), options.timezone),
project,
activity,
description: options.description || undefined,
@@ -27,20 +28,35 @@ export async function startTimesheet(
}
}
/** Stops a running timesheet; a description is mandatory */
export async function stopTimesheet(ts: Timesheet, description: string, tags?: string) {
const toast = await showToast({ style: Toast.Style.Animated, title: `Stoppe ${ts.activity.name}…` });
/** Deletes a timesheet after confirmation; returns true when deleted */
export async function removeTimesheet(ts: Timesheet) {
const ok = await confirmAlert({
title: "Timesheet löschen?",
message: `${ts.activity.name}, ${formatDay(ts.begin)} ${formatTime(ts.begin)}`,
primaryAction: { title: "Löschen", style: Alert.ActionStyle.Destructive },
});
if (!ok) return false;
try {
if (!description.trim()) throw new Error("Beschreibung ist Pflicht");
await api.update(ts.id, { description, ...(tags !== undefined ? { tags } : {}) });
const stopped = await api.stop(ts.id);
toast.style = Toast.Style.Success;
toast.title = `Gestoppt: ${ts.activity.name}`;
toast.message = formatDuration(stopped.duration);
await api.remove(ts.id);
await showToast({ style: Toast.Style.Success, title: "Timesheet gelöscht" });
return true;
} catch (e) {
toast.hide();
await showError("Stoppen fehlgeschlagen", e);
await showError("Löschen fehlgeschlagen", e);
return false;
}
}
export async function toggleFavorite(ts: Timesheet, isFavorite: boolean) {
try {
if (isFavorite) await api.removeFavorite(ts.id);
else await api.addFavorite(ts.id);
await showToast({
style: Toast.Style.Success,
title: isFavorite ? "Aus Favoriten entfernt" : "Zu Favoriten hinzugefügt",
});
return true;
} catch (e) {
await showError("Favorit konnte nicht geändert werden", e);
return false;
}
}
-244
View File
@@ -1,244 +0,0 @@
import { Action, ActionPanel, Form, Icon, showToast, Toast, useNavigation } from "@raycast/api";
import { useMemo, useState } from "react";
import { Activity, api, Customer, Project, Timesheet } from "./api";
import { Catalog } from "./hooks";
import { colorIcon, formatDuration, parseDuration, showError, toKimaiDate } from "./utils";
interface Props {
timesheet: Timesheet;
catalog?: Catalog;
onSaved: () => void;
}
function activitiesFor(project: Project | undefined, activities: Activity[]): Activity[] {
if (!project) return [];
return activities.filter((a) => a.project === project.id || (a.project == null && project.globalActivities));
}
export function TimesheetEditForm({ timesheet, catalog, onSaved }: Props) {
const { pop } = useNavigation();
// make sure the currently assigned (possibly hidden) entries are selectable
const customers = useMemo<Customer[]>(() => {
const list = [...(catalog?.customers ?? [])];
const c = timesheet.project.customer;
if (!list.some((x) => x.id === c.id)) list.push({ id: c.id, name: c.name, visible: false });
return list.sort((a, b) => a.name.localeCompare(b.name, "de"));
}, [catalog, timesheet]);
const projects = useMemo<Project[]>(() => {
const list = [...(catalog?.projects ?? [])];
const p = timesheet.project;
if (!list.some((x) => x.id === p.id))
list.push({ id: p.id, name: p.name, customer: p.customer.id, globalActivities: true, visible: false });
return list.sort((a, b) => a.name.localeCompare(b.name, "de"));
}, [catalog, timesheet]);
const activities = useMemo<Activity[]>(() => {
const list = [...(catalog?.activities ?? [])];
const a = timesheet.activity;
if (!list.some((x) => x.id === a.id)) list.push({ id: a.id, name: a.name, project: a.project, visible: false });
return list.sort((x, y) => x.name.localeCompare(y.name, "de"));
}, [catalog, timesheet]);
const [begin, setBegin] = useState<Date | null>(new Date(timesheet.begin));
const [end, setEnd] = useState<Date | null>(timesheet.end ? new Date(timesheet.end) : null);
const [breakStr, setBreakStr] = useState(formatDuration(timesheet.break ?? 0));
const [durationStr, setDurationStr] = useState(timesheet.end ? formatDuration(timesheet.duration) : "");
const [customerId, setCustomerId] = useState(String(timesheet.project.customer.id));
const [projectId, setProjectId] = useState(String(timesheet.project.id));
const [activityId, setActivityId] = useState(String(timesheet.activity.id));
const [description, setDescription] = useState(timesheet.description ?? "");
const [tags, setTags] = useState(timesheet.tags.join(", "));
const [errors, setErrors] = useState<Record<string, string | undefined>>({});
const customerProjects = projects.filter((p) => String(p.customer) === customerId);
const project = projects.find((p) => String(p.id) === projectId);
const projectActivities = activitiesFor(project, activities);
const clearError = (field: string) => setErrors((e) => ({ ...e, [field]: undefined }));
function recomputeDuration(b: Date | null, e: Date | null, brk: string) {
const breakSec = parseDuration(brk);
if (b && e && breakSec !== undefined) {
setDurationStr(formatDuration((e.getTime() - b.getTime()) / 1000 - breakSec));
} else if (!e) {
setDurationStr("");
}
}
function onBeginChange(v: Date | null) {
setBegin(v);
clearError("begin");
recomputeDuration(v, end, breakStr);
}
function onEndChange(v: Date | null) {
setEnd(v);
clearError("end");
recomputeDuration(begin, v, breakStr);
}
function onBreakChange(v: string) {
setBreakStr(v);
if (parseDuration(v) === undefined) {
setErrors((e) => ({ ...e, break: "Format z. B. 0:30" }));
return;
}
clearError("break");
recomputeDuration(begin, end, v);
}
// changing the duration moves "Bis": end = begin + duration + break
function onDurationChange(v: string) {
setDurationStr(v);
if (v.trim() === "") return clearError("duration");
const dur = parseDuration(v);
const brk = parseDuration(breakStr) ?? 0;
if (dur === undefined) {
setErrors((e) => ({ ...e, duration: "Format z. B. 1:30 oder 90m" }));
return;
}
clearError("duration");
if (begin) setEnd(new Date(begin.getTime() + (dur + brk) * 1000));
}
function selectProject(p: Project | undefined) {
setProjectId(p ? String(p.id) : "");
const acts = activitiesFor(p, activities);
if (!acts.some((a) => String(a.id) === activityId)) setActivityId(acts[0] ? String(acts[0].id) : "");
}
function onCustomerChange(v: string) {
if (v === customerId) return;
setCustomerId(v);
const ps = projects.filter((p) => String(p.customer) === v);
if (!ps.some((p) => String(p.id) === projectId)) selectProject(ps[0]);
}
function onProjectChange(v: string) {
if (v === projectId) return;
selectProject(projects.find((p) => String(p.id) === v));
}
async function submit() {
const errs: Record<string, string> = {};
const breakSec = parseDuration(breakStr);
if (!begin) errs.begin = "Pflichtfeld";
if (breakSec === undefined) errs.break = "Format z. B. 0:30";
if (begin && end && end.getTime() <= begin.getTime()) errs.end = "Bis muss nach Von liegen";
if (!projectId) errs.project = "Bitte Projekt wählen";
if (!activityId) errs.activity = "Bitte Tätigkeit wählen";
// setting "Bis" on a running record stops it, which always requires a description
if (end && !description.trim()) errs.description = "Beschreibung ist Pflicht";
if (Object.keys(errs).length) {
setErrors(errs);
return;
}
const tz = catalog?.timezone;
const toast = await showToast({ style: Toast.Style.Animated, title: "Speichere…" });
try {
await api.update(timesheet.id, {
begin: toKimaiDate(begin!, tz),
...(end ? { end: toKimaiDate(end, tz) } : {}),
project: Number(projectId),
activity: Number(activityId),
description,
tags,
break: formatDuration(breakSec ?? 0),
});
toast.style = Toast.Style.Success;
toast.title = "Timesheet gespeichert";
onSaved();
pop();
} catch (e) {
toast.hide();
await showError("Speichern fehlgeschlagen", e);
}
}
return (
<Form
isLoading={!catalog}
navigationTitle={`Timesheet #${timesheet.id} bearbeiten`}
actions={
<ActionPanel>
<Action.SubmitForm title="Speichern" icon={Icon.Check} onSubmit={submit} />
</ActionPanel>
}
>
<Form.DatePicker
id="begin"
title="Von"
type={Form.DatePicker.Type.DateTime}
value={begin}
onChange={onBeginChange}
error={errors.begin}
/>
<Form.DatePicker
id="end"
title="Bis"
type={Form.DatePicker.Type.DateTime}
value={end}
onChange={onEndChange}
error={errors.end}
info={timesheet.end ? undefined : "Leer lassen, damit die Tätigkeit weiterläuft"}
/>
<Form.TextField
id="duration"
title="Dauer"
placeholder={timesheet.end ? "z. B. 1:30" : "läuft"}
value={durationStr}
onChange={onDurationChange}
error={errors.duration}
info="Änderung der Dauer verschiebt »Bis« (Bis = Von + Dauer + Pause)"
/>
<Form.TextField
id="break"
title="Pause"
placeholder="0:00"
value={breakStr}
onChange={onBreakChange}
error={errors.break}
/>
<Form.Separator />
<Form.Dropdown id="customer" title="Kunde" value={customerId} onChange={onCustomerChange}>
{customers.map((c) => (
<Form.Dropdown.Item key={c.id} value={String(c.id)} title={c.name} icon={colorIcon(c["color-safe"])} />
))}
</Form.Dropdown>
<Form.Dropdown id="project" title="Projekt" value={projectId} onChange={onProjectChange} error={errors.project}>
{customerProjects.map((p) => (
<Form.Dropdown.Item key={p.id} value={String(p.id)} title={p.name} icon={colorIcon(p["color-safe"])} />
))}
</Form.Dropdown>
<Form.Dropdown
id="activity"
title="Tätigkeit"
value={activityId}
onChange={(v) => {
setActivityId(v);
clearError("activity");
}}
error={errors.activity}
>
{projectActivities.map((a) => (
<Form.Dropdown.Item key={a.id} value={String(a.id)} title={a.name} icon={colorIcon(a["color-safe"])} />
))}
</Form.Dropdown>
<Form.Separator />
<Form.TextArea
id="description"
title="Beschreibung"
value={description}
onChange={(v) => {
setDescription(v);
clearError("description");
}}
error={errors.description}
/>
<Form.TextField id="tags" title="Tags" placeholder="kommagetrennt" value={tags} onChange={setTags} />
</Form>
);
}
+11 -1
View File
@@ -1,5 +1,5 @@
import { useCachedPromise } from "@raycast/utils";
import { useMemo } from "react";
import { useEffect, useMemo, useState } from "react";
import { api, Timesheet } from "./api";
import { ActivityChoice, buildChoices, choiceFromTimesheet } from "./utils";
@@ -74,3 +74,13 @@ export function useStartOptions(catalog?: Catalog) {
return { ...options, isLoading, revalidate };
}
/** Current timestamp, refreshed periodically for running durations */
export function useNow(intervalMs = 30_000) {
const [now, setNow] = useState(Date.now());
useEffect(() => {
const t = setInterval(() => setNow(Date.now()), intervalMs);
return () => clearInterval(t);
}, [intervalMs]);
return now;
}
-59
View File
@@ -1,59 +0,0 @@
import { Action, ActionPanel, closeMainWindow, Form, Icon, PopToRootType, useNavigation } from "@raycast/api";
import { useState } from "react";
import { stopTimesheet } from "./actions";
import { Timesheet } from "./api";
import { formatTime, timesheetSubtitle } from "./utils";
interface Props {
timesheet: Timesheet;
onStopped?: () => void;
/** opened directly via launch context (e.g. from the menu bar): close Raycast afterwards instead of popping */
isRoot?: boolean;
}
/** Stopping always requires a description */
export function StopForm({ timesheet, onStopped, isRoot }: Props) {
const { pop } = useNavigation();
const [descriptionError, setDescriptionError] = useState<string>();
async function submit(v: { description: string; tags: string }) {
if (!v.description.trim()) {
setDescriptionError("Beschreibung ist Pflicht");
return false;
}
if (!(await stopTimesheet(timesheet, v.description.trim(), v.tags))) return false;
onStopped?.();
if (isRoot) await closeMainWindow({ popToRootType: PopToRootType.Immediate });
else pop();
}
return (
<Form
navigationTitle={`${timesheet.activity.name} stoppen`}
actions={
<ActionPanel>
<Action.SubmitForm title="Stoppen" icon={Icon.Stop} onSubmit={submit} />
</ActionPanel>
}
>
<Form.Description title="Tätigkeit" text={timesheet.activity.name} />
<Form.Description title="Projekt" text={timesheetSubtitle(timesheet)} />
<Form.Description title="Seit" text={`${formatTime(timesheet.begin)} Uhr`} />
<Form.TextArea
id="description"
title="Beschreibung"
placeholder="Was wurde gemacht?"
defaultValue={timesheet.description ?? ""}
error={descriptionError}
onChange={() => setDescriptionError(undefined)}
autoFocus
/>
<Form.TextField
id="tags"
title="Tags"
placeholder="Optional, kommagetrennt"
defaultValue={timesheet.tags.join(", ")}
/>
</Form>
);
}
+391
View File
@@ -0,0 +1,391 @@
import {
Action,
ActionPanel,
closeMainWindow,
Form,
Icon,
PopToRootType,
showToast,
Toast,
useNavigation,
} from "@raycast/api";
import { useEffect, useMemo, useState } from "react";
import { startTimesheet } from "./actions";
import { api, Timesheet, TimesheetPayload } from "./api";
import { ChoiceDropdown, choiceKeyOf, firstChoiceValue } from "./choice-dropdown";
import { useCatalog, useStartOptions } from "./hooks";
import {
choiceFromTimesheet,
formatClock,
formatDuration,
kimaiDateAt,
kimaiParts,
nowParts,
parseChoiceKey,
parseDuration,
parseTime,
showError,
spanMinutes,
} from "./utils";
/**
* start: new running timesheet (Von = now)
* create: finished timesheet entered afterwards
* stop: finish a running timesheet (Bis = now)
* edit: change any timesheet; on a running one an empty »Bis« keeps it running
* log: finished timesheet from duration only, ending now (no date, times or break)
*/
export type TimesheetFormMode = "start" | "create" | "stop" | "edit" | "log";
interface Props {
mode: TimesheetFormMode;
/** the timesheet to stop or edit */
timesheet?: Timesheet;
onSaved?: () => void;
/** opened as root view (command or launch context): close Raycast afterwards instead of popping */
isRoot?: boolean;
}
type Errors = Partial<Record<"date" | "begin" | "end" | "break" | "duration" | "choice" | "description", string>>;
const NAVIGATION_TITLE: Record<TimesheetFormMode, string> = {
start: "Tätigkeit starten",
create: "Manuelles Timesheet",
stop: "Tätigkeit stoppen",
edit: "Timesheet bearbeiten",
log: "Dauer erfassen",
};
/** The one form for starting, stopping, creating and editing timesheets, so all views share fields and rules */
export function TimesheetForm({ mode, timesheet, onSaved, isRoot }: Props) {
const { pop } = useNavigation();
const { data: catalog, isLoading: catalogLoading } = useCatalog();
const { favorites, recent, isLoading: optionsLoading } = useStartOptions(catalog);
const own = useMemo(() => (timesheet ? choiceFromTimesheet(timesheet) : undefined), [timesheet]);
// the timesheet's own (possibly hidden) assignment must stay selectable
const all = useMemo(() => {
const choices = catalog?.choices ?? [];
return own && !choices.some((c) => c.key === own.key) ? [...choices, own] : choices;
}, [catalog, own]);
const byKey = useMemo(() => new Map(all.map((c) => [c.key, c])), [all]);
// computed once when the form opens
const [initial] = useState(() => {
const now = nowParts(catalog?.timezone);
const begin = timesheet ? kimaiParts(timesheet.begin) : now;
const end = timesheet?.end ? kimaiParts(timesheet.end) : mode === "stop" ? now : undefined;
return {
date: begin.day,
begin: mode === "create" ? "" : formatClock(begin.minutes),
end: end ? formatClock(end.minutes) : "",
break: timesheet?.break ? formatDuration(timesheet.break) : "",
};
});
const [date, setDate] = useState<Date | null>(initial.date);
const [beginStr, setBeginStr] = useState(initial.begin);
const [endStr, setEndStr] = useState(initial.end);
const [breakStr, setBreakStr] = useState(initial.break);
const [durationStr, setDurationStr] = useState(() => durationText(initial.begin, initial.end, initial.break));
const [choice, setChoice] = useState(own ? `all|${own.key}` : "");
const [description, setDescription] = useState(timesheet?.description ?? "");
const [tags, setTags] = useState(timesheet?.tags.join(", ") ?? "");
const [errors, setErrors] = useState<Errors>({});
const selected = byKey.get(choiceKeyOf(choice) ?? "");
const hasEnd = mode !== "start";
// »log« only asks for duration, activity and description
const hasTimes = mode !== "log";
// a running timesheet can be edited without stopping it
const endOptional = mode === "edit" && !timesheet?.end;
// preselect the first favorite (or recent) entry once loaded
useEffect(() => {
if (choice || optionsLoading || catalogLoading) return;
const first = firstChoiceValue(favorites, recent, all);
if (first) setChoice(first);
}, [favorites, recent, all, optionsLoading, catalogLoading]);
const clearError = (field: keyof Errors) => setErrors((e) => ({ ...e, [field]: undefined }));
const setError = (field: keyof Errors, message: string) => setErrors((e) => ({ ...e, [field]: message }));
function onTimeChange(field: "begin" | "end", v: string) {
const b = field === "begin" ? v : beginStr;
const e = field === "end" ? v : endStr;
(field === "begin" ? setBeginStr : setEndStr)(v);
if (v.trim() !== "" && parseTime(v) === undefined) setError(field, "Format z. B. 8:30");
else clearError(field);
setDurationStr(durationText(b, e, breakStr));
}
function onBreakChange(v: string) {
setBreakStr(v);
if (parseDuration(v) === undefined) return setError("break", "Format z. B. 0:30");
clearError("break");
setDurationStr(durationText(beginStr, endStr, v));
}
// changing the duration moves »Bis«: Bis = Von + Dauer + Pause
function onDurationChange(v: string) {
setDurationStr(v);
if (v.trim() === "") return clearError("duration");
const dur = parseDuration(v);
const brk = parseDuration(breakStr) ?? 0;
const begin = parseTime(beginStr);
if (dur === undefined) return setError("duration", "Format z. B. 1:30 oder 90m");
if (dur + brk >= 24 * 3600) return setError("duration", "Höchstens 24 Stunden");
clearError("duration");
if (begin !== undefined) {
setEndStr(formatClock((begin + Math.round((dur + brk) / 60)) % 1440));
clearError("end");
}
}
function validate() {
if (!hasTimes) return validateLog();
const errs: Errors = {};
const begin = parseTime(beginStr);
const end = parseTime(endStr);
const breakSec = parseDuration(breakStr);
if (!date) errs.date = "Pflichtfeld";
if (begin === undefined) errs.begin = beginStr.trim() ? "Format z. B. 8:30" : "Pflichtfeld";
if (hasEnd) {
if (endStr.trim() === "") {
if (!endOptional) errs.end = "Pflichtfeld";
} else if (end === undefined) errs.end = "Format z. B. 17:00";
else if (begin !== undefined && end === begin) errs.end = "Bis muss nach Von liegen";
}
if (breakSec === undefined) errs.break = "Format z. B. 0:30";
else if (begin !== undefined && end !== undefined && spanMinutes(begin, end) * 60 <= breakSec)
errs.break = "Pause ist länger als die Arbeitszeit";
if (!choiceKeyOf(choice)) errs.choice = "Bitte Tätigkeit wählen";
// a finished timesheet always requires a description
if (end !== undefined && !description.trim()) errs.description = "Beschreibung ist Pflicht";
setErrors(errs);
if (Object.keys(errs).length) return undefined;
// times are wall-clock times of the Kimai user, so no timezone conversion
return {
begin: kimaiDateAt(date!, begin!),
end: end !== undefined ? kimaiDateAt(date!, end, end < begin! ? 1 : 0) : undefined,
...parseChoiceKey(choiceKeyOf(choice)!),
description: description.trim(),
tags,
// without a value Kimai applies its own break rules
...(breakStr.trim() ? { break: formatDuration(breakSec ?? 0) } : {}),
} satisfies TimesheetPayload;
}
// the entry ends now (Kimai wall-clock time) and starts »Dauer« earlier, without a break
function validateLog() {
const errs: Errors = {};
const dur = parseDuration(durationStr);
const minutes = dur !== undefined ? Math.round(dur / 60) : 0;
if (durationStr.trim() === "") errs.duration = "Pflichtfeld";
else if (dur === undefined) errs.duration = "Format z. B. 1:30 oder 90m";
else if (minutes < 1) errs.duration = "Mindestens 1 Minute";
else if (minutes >= 1440) errs.duration = "Höchstens 24 Stunden";
if (!choiceKeyOf(choice)) errs.choice = "Bitte Tätigkeit wählen";
if (!description.trim()) errs.description = "Beschreibung ist Pflicht";
setErrors(errs);
if (Object.keys(errs).length) return undefined;
const now = nowParts(catalog?.timezone);
const begin = now.minutes - minutes;
return {
begin: kimaiDateAt(now.day, (begin + 1440) % 1440, begin < 0 ? -1 : 0),
end: kimaiDateAt(now.day, now.minutes),
...parseChoiceKey(choiceKeyOf(choice)!),
description: description.trim(),
break: formatDuration(0),
} satisfies TimesheetPayload;
}
/** returns true when saved */
async function save(): Promise<boolean> {
const payload = validate();
if (!payload) return false;
if (mode === "start") {
const key = choiceKeyOf(choice)!;
return !!(await startTimesheet(key, { begin: payload.begin, description: payload.description, tags }));
}
const toast = await showToast({ style: Toast.Style.Animated, title: "Speichere…" });
try {
// an unchanged begin is not sent, so its seconds are kept
const beginChanged = !timesheet || date?.getTime() !== initial.date.getTime() || beginStr !== initial.begin;
const body: TimesheetPayload = { ...payload, begin: beginChanged ? payload.begin : undefined };
// setting »Bis« on a running timesheet stops it
const ts = timesheet ? await api.update(timesheet.id, body) : await api.create(body);
toast.style = Toast.Style.Success;
toast.title =
mode === "stop"
? `Gestoppt: ${ts.activity.name}`
: mode === "create" || mode === "log"
? `Timesheet erstellt: ${ts.activity.name}`
: "Timesheet gespeichert";
if (ts.end) toast.message = formatDuration(ts.duration);
return true;
} catch (e) {
toast.hide();
await showError("Speichern fehlgeschlagen", e);
return false;
}
}
async function saveAndClose() {
if (!(await save())) return;
onSaved?.();
if (isRoot) await closeMainWindow({ popToRootType: PopToRootType.Immediate });
else pop();
}
// keep date and assignment, continue where the last entry ended
async function saveAndNext() {
if (!(await save())) return;
onSaved?.();
setBeginStr(endStr);
setEndStr("");
setBreakStr("");
setDurationStr("");
setDescription("");
}
const submitTitle = { start: "Starten", create: "Speichern", stop: "Stoppen", edit: "Speichern", log: "Speichern" }[
mode
];
const submitIcon = { start: Icon.Play, create: Icon.Check, stop: Icon.Stop, edit: Icon.Check, log: Icon.Check }[mode];
return (
<Form
isLoading={catalogLoading || optionsLoading}
navigationTitle={mode === "stop" && timesheet ? `${timesheet.activity.name} stoppen` : NAVIGATION_TITLE[mode]}
actions={
<ActionPanel>
<Action.SubmitForm title={submitTitle} icon={submitIcon} onSubmit={saveAndClose} />
{mode === "create" && (
<Action.SubmitForm
title="Speichern und weiteres erfassen"
icon={Icon.Plus}
shortcut={{ modifiers: ["cmd", "shift"], key: "enter" }}
onSubmit={saveAndNext}
/>
)}
</ActionPanel>
}
>
{hasTimes && (
<>
<Form.DatePicker
id="date"
title="Datum"
type={Form.DatePicker.Type.Date}
value={date}
onChange={(v) => {
setDate(v);
clearError("date");
}}
error={errors.date}
/>
<Form.TextField
id="begin"
title="Von"
placeholder="z. B. 8:30"
value={beginStr}
onChange={(v) => onTimeChange("begin", v)}
error={errors.begin}
/>
</>
)}
{hasEnd && (
<>
{hasTimes && (
<>
<Form.TextField
id="end"
title="Bis"
placeholder={endOptional ? "läuft" : "z. B. 17:00"}
value={endStr}
onChange={(v) => onTimeChange("end", v)}
error={errors.end}
info={
(endOptional ? "Leer lassen, damit die Tätigkeit weiterläuft. " : "") +
"Liegt »Bis« vor »Von«, endet der Eintrag am Folgetag"
}
/>
<Form.TextField
id="break"
title="Pause"
placeholder="automatisch"
value={breakStr}
onChange={onBreakChange}
error={errors.break}
info="Leer lassen, damit Kimai die Pause nach seinen Regeln setzt"
/>
</>
)}
<Form.TextField
id="duration"
title="Dauer"
placeholder={endOptional ? "läuft" : "z. B. 1:30"}
value={durationStr}
onChange={onDurationChange}
error={errors.duration}
info={
hasTimes
? "Änderung der Dauer verschiebt »Bis« (Bis = Von + Dauer + Pause)"
: "Der Eintrag endet jetzt und beginnt entsprechend früher, ohne Pause"
}
autoFocus={!hasTimes}
/>
</>
)}
<Form.Separator />
<ChoiceDropdown
favorites={favorites}
recent={recent}
all={all}
value={choice}
onChange={(v) => {
setChoice(v);
clearError("choice");
}}
error={errors.choice}
/>
{selected && (
<>
<Form.Description title="Kunde" text={selected.customer?.name ?? "–"} />
<Form.Description title="Projekt" text={selected.project.name} />
</>
)}
<Form.Separator />
<Form.TextArea
id="description"
title="Beschreibung"
placeholder="Was wurde gemacht?"
value={description}
onChange={(v) => {
setDescription(v);
clearError("description");
}}
error={errors.description}
info={mode === "start" ? undefined : mode === "log" ? "Pflichtfeld" : "Pflicht, sobald »Bis« gesetzt ist"}
autoFocus={mode === "stop"}
/>
{hasTimes && (
<Form.TextField id="tags" title="Tags" placeholder="Optional, kommagetrennt" value={tags} onChange={setTags} />
)}
</Form>
);
}
/** Working time (Bis − Von − Pause) as "H:MM", empty while incomplete */
function durationText(beginStr: string, endStr: string, breakStr: string): string {
const begin = parseTime(beginStr);
const end = parseTime(endStr);
const breakSec = parseDuration(breakStr);
if (begin === undefined || end === undefined || breakSec === undefined || begin === end) return "";
return formatDuration(Math.max(0, spanMinutes(begin, end) * 60 - breakSec));
}
+150
View File
@@ -0,0 +1,150 @@
import { Action, ActionPanel, Color, Icon, List } from "@raycast/api";
import { ReactNode } from "react";
import { removeTimesheet, startTimesheet, toggleFavorite } from "./actions";
import { kimaiUrl, Timesheet } from "./api";
import { NoteForm } from "./note-form";
import { TimesheetForm } from "./timesheet-form";
import {
choiceKey,
colorIcon,
elapsedSeconds,
formatDuration,
formatTime,
timesheetSubtitle,
timesheetTitle,
} from "./utils";
interface ItemProps {
timesheet: Timesheet;
now: number;
/** undefined: favorite state unknown, no star shown */
isFavorite?: boolean;
actions: ReactNode;
}
/** The same list row for a timesheet in every view */
export function TimesheetListItem({ timesheet: ts, now, isFavorite, actions }: ItemProps) {
const running = !ts.end;
return (
<List.Item
icon={colorIcon(ts.activity["color-safe"], running ? Icon.Play : Icon.CircleFilled)}
title={timesheetTitle(ts)}
subtitle={ts.description || timesheetSubtitle(ts)}
keywords={[ts.project.name, ts.project.customer.name, ts.description ?? "", ...ts.tags]}
accessories={[
...(isFavorite ? [{ icon: { source: Icon.Star, tintColor: Color.Yellow }, tooltip: "Favorit" }] : []),
...(ts.description ? [{ text: timesheetSubtitle(ts) }] : []),
...ts.tags.map((t) => ({ tag: t })),
...(ts.break ? [{ icon: Icon.Mug, text: formatDuration(ts.break), tooltip: "Pause" }] : []),
{ text: `${formatTime(ts.begin)}–${ts.end ? formatTime(ts.end) : "läuft"}` },
{ tag: { value: formatDuration(elapsedSeconds(ts, now)), color: running ? Color.Green : undefined } },
]}
actions={actions}
/>
);
}
interface ActionsProps {
timesheet: Timesheet;
/** action on ↵ */
primary: "edit" | "stop" | "note";
onChanged: () => void;
isFavorite?: boolean;
timezone?: string;
/** view-specific action placed before all others (then it runs on ↵) */
first?: ReactNode;
}
/** The same actions and shortcuts for a timesheet in every view; only the action on ↵ differs */
export function TimesheetActions({ timesheet: ts, primary, onChanged, isFavorite, timezone, first }: ActionsProps) {
const running = !ts.end;
const edit = (
<Action.Push
key="edit"
title="Bearbeiten"
icon={Icon.Pencil}
shortcut={{ modifiers: ["cmd"], key: "e" }}
target={<TimesheetForm mode="edit" timesheet={ts} onSaved={onChanged} />}
/>
);
const stopOrRestart = running ? (
<Action.Push
key="stop"
title="Stoppen"
icon={Icon.Stop}
shortcut={{ modifiers: ["cmd"], key: "s" }}
target={<TimesheetForm mode="stop" timesheet={ts} onSaved={onChanged} />}
/>
) : (
<Action
key="stop"
title="Erneut starten"
icon={Icon.Play}
shortcut={{ modifiers: ["cmd"], key: "s" }}
onAction={async () => {
await startTimesheet(choiceKey(ts.project.id, ts.activity.id), {
timezone,
description: ts.description ?? undefined,
tags: ts.tags.join(","),
});
onChanged();
}}
/>
);
const note = running ? (
<Action.Push
key="note"
title="Notizen schreiben"
icon={Icon.Text}
shortcut={{ modifiers: ["cmd"], key: "n" }}
target={<NoteForm timesheet={ts} onSaved={onChanged} />}
/>
) : null;
const ordered = { edit, stop: stopOrRestart, note };
const order = [primary, ...(["stop", "note", "edit"] as const).filter((a) => a !== primary)];
return (
<ActionPanel>
<ActionPanel.Section>
{first}
{order.map((a) => ordered[a])}
</ActionPanel.Section>
<ActionPanel.Section>
{isFavorite !== undefined && (
<Action
title={isFavorite ? "Aus Favoriten entfernen" : "Als Favorit markieren"}
icon={isFavorite ? Icon.StarDisabled : Icon.Star}
shortcut={{ modifiers: ["cmd"], key: "f" }}
onAction={async () => {
if (await toggleFavorite(ts, isFavorite)) onChanged();
}}
/>
)}
<Action.OpenInBrowser
title="In Kimai öffnen"
url={kimaiUrl(`/de/timesheet/${ts.id}/edit`)}
shortcut={{ modifiers: ["cmd"], key: "o" }}
/>
<Action
title="Aktualisieren"
icon={Icon.ArrowClockwise}
shortcut={{ modifiers: ["cmd"], key: "r" }}
onAction={onChanged}
/>
</ActionPanel.Section>
<ActionPanel.Section>
<Action
title="Löschen"
icon={Icon.Trash}
style={Action.Style.Destructive}
shortcut={{ modifiers: ["ctrl"], key: "x" }}
onAction={async () => {
if (await removeTimesheet(ts)) onChanged();
}}
/>
</ActionPanel.Section>
</ActionPanel>
);
}
+34 -5
View File
@@ -52,12 +52,30 @@ export function parseTime(input: string): number | undefined {
return h * 60 + min;
}
/** Kimai local datetime ("YYYY-MM-DDTHH:mm:ss") from a calendar day and minutes since midnight */
export function kimaiDateAt(day: Date, minutes: number): string {
const pad = (n: number) => String(n).padStart(2, "0");
return `${day.getFullYear()}-${pad(day.getMonth() + 1)}-${pad(day.getDate())}T${pad(Math.floor(minutes / 60))}:${pad(minutes % 60)}:00`;
/** Kimai local datetime ("YYYY-MM-DDTHH:mm:ss") from a calendar day (plus offset in days) and minutes since midnight */
export function kimaiDateAt(day: Date, minutes: number, dayOffset = 0): string {
const d = new Date(day.getFullYear(), day.getMonth(), day.getDate() + dayOffset);
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(Math.floor(minutes / 60))}:${pad(minutes % 60)}:00`;
}
/** Calendar day and minutes since midnight of a Kimai datetime, read as wall-clock time without timezone conversion */
export function kimaiParts(value: string): { day: Date; minutes: number } {
const m = value.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/);
if (!m) throw new Error(`Unbekanntes Datumsformat: ${value}`);
return { day: new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3])), minutes: Number(m[4]) * 60 + Number(m[5]) };
}
/** Current day and minute as wall-clock time of the given timezone */
export const nowParts = (timeZone?: string) => kimaiParts(toKimaiDate(new Date(), timeZone));
/** Minutes since midnight -> "HH:MM" */
export const formatClock = (minutes: number) => `${pad(Math.floor(minutes / 60))}:${pad(minutes % 60)}`;
/** Minutes from "Von" to "Bis"; a "Bis" before "Von" lies on the next day */
export const spanMinutes = (begin: number, end: number) => (end - begin + 1440) % 1440;
export function elapsedSeconds(ts: Timesheet, now = Date.now()): number {
if (ts.end) return ts.duration;
return Math.max(0, (now - new Date(ts.begin).getTime()) / 1000 - (ts.break ?? 0));
@@ -130,11 +148,22 @@ export function buildChoices(customers: Customer[], projects: Project[], activit
return choices.sort((a, b) => a.subtitle.localeCompare(b.subtitle, "de") || a.title.localeCompare(b.title, "de"));
}
export function choiceFromTimesheet(ts: Timesheet): Omit<ActivityChoice, "activity" | "project" | "customer"> {
/** The choice of a timesheet, built from its expanded relations (works for hidden entries, too) */
export function choiceFromTimesheet(ts: Timesheet): ActivityChoice {
const customer = { id: ts.project.customer.id, name: ts.project.customer.name, visible: false };
return {
key: choiceKey(ts.project.id, ts.activity.id),
activity: { id: ts.activity.id, name: ts.activity.name, project: ts.activity.project, visible: false },
project: {
id: ts.project.id,
name: ts.project.name,
customer: customer.id,
globalActivities: true,
visible: false,
},
customer,
title: ts.activity.name,
subtitle: `${ts.project.customer.name} › ${ts.project.name}`,
subtitle: timesheetSubtitle(ts),
color: ts.activity["color-safe"] ?? ts.project["color-safe"],
};
}
+5
View File
@@ -0,0 +1,5 @@
import { TimesheetForm } from "./lib/timesheet-form";
export default function LogActivity() {
return <TimesheetForm mode="log" isRoot />;
}
+14 -130
View File
@@ -1,25 +1,10 @@
import { Action, ActionPanel, Alert, Color, confirmAlert, Icon, List, showToast, Toast } from "@raycast/api";
import { Icon, List } from "@raycast/api";
import { useCachedPromise } from "@raycast/utils";
import { useMemo, useState } from "react";
import { startTimesheet } from "./lib/actions";
import { api, kimaiUrl, Timesheet } from "./lib/api";
import { TimesheetEditForm } from "./lib/edit-form";
import { api, Timesheet } from "./lib/api";
import { useCatalog } from "./lib/hooks";
import { NoteForm } from "./lib/note-form";
import { StopForm } from "./lib/stop-form";
import {
choiceKey,
colorIcon,
dayKey,
elapsedSeconds,
formatDay,
formatDuration,
formatTime,
showError,
timesheetSubtitle,
timesheetTitle,
toKimaiDate,
} from "./lib/utils";
import { TimesheetActions, TimesheetListItem } from "./lib/timesheet-list";
import { dayKey, elapsedSeconds, formatDay, formatDuration, toKimaiDate } from "./lib/utils";
const monthFmt = new Intl.DateTimeFormat("de-DE", { month: "long", year: "numeric" });
@@ -66,36 +51,6 @@ export default function ManageTimesheets() {
const monthTotal = timesheets.reduce((sum, ts) => sum + elapsedSeconds(ts, now), 0);
async function remove(ts: Timesheet) {
const ok = await confirmAlert({
title: "Timesheet löschen?",
message: `${ts.activity.name}, ${formatDay(ts.begin)} ${formatTime(ts.begin)}`,
primaryAction: { title: "Löschen", style: Alert.ActionStyle.Destructive },
});
if (!ok) return;
try {
await api.remove(ts.id);
await showToast({ style: Toast.Style.Success, title: "Timesheet gelöscht" });
revalidate();
} catch (e) {
await showError("Löschen fehlgeschlagen", e);
}
}
async function toggleFavorite(ts: Timesheet, isFavorite: boolean) {
try {
if (isFavorite) await api.removeFavorite(ts.id);
else await api.addFavorite(ts.id);
await showToast({
style: Toast.Style.Success,
title: isFavorite ? "Aus Favoriten entfernt" : "Zu Favoriten hinzugefügt",
});
revalidate();
} catch (e) {
await showError("Favorit konnte nicht geändert werden", e);
}
}
return (
<List
isLoading={isLoading}
@@ -115,92 +70,21 @@ export default function ManageTimesheets() {
return (
<List.Section key={key} title={formatDay(entries[0].begin)} subtitle={`${formatDuration(total)} h`}>
{entries.map((ts) => {
const running = !ts.end;
const isFavorite = favoriteIds.includes(ts.id);
return (
<List.Item
<TimesheetListItem
key={ts.id}
icon={colorIcon(ts.activity["color-safe"], running ? Icon.Play : Icon.CircleFilled)}
title={timesheetTitle(ts)}
subtitle={ts.description || timesheetSubtitle(ts)}
keywords={[ts.project.name, ts.project.customer.name, ts.description ?? "", ...ts.tags]}
accessories={[
...(isFavorite
? [{ icon: { source: Icon.Star, tintColor: Color.Yellow }, tooltip: "Favorit" }]
: []),
...(ts.description ? [{ text: timesheetSubtitle(ts) }] : []),
...ts.tags.map((t) => ({ tag: t })),
...(ts.break ? [{ icon: Icon.Mug, text: formatDuration(ts.break), tooltip: "Pause" }] : []),
{ text: `${formatTime(ts.begin)}–${ts.end ? formatTime(ts.end) : "läuft"}` },
{
tag: {
value: formatDuration(elapsedSeconds(ts, now)),
color: running ? Color.Green : undefined,
},
},
]}
timesheet={ts}
now={now}
isFavorite={isFavorite}
actions={
<ActionPanel>
<Action.Push
title="Bearbeiten"
icon={Icon.Pencil}
target={<TimesheetEditForm timesheet={ts} catalog={catalog} onSaved={revalidate} />}
<TimesheetActions
timesheet={ts}
primary="edit"
onChanged={revalidate}
isFavorite={isFavorite}
timezone={catalog?.timezone}
/>
{running && (
<Action.Push
title="Notizen schreiben"
icon={Icon.Text}
shortcut={{ modifiers: ["cmd"], key: "n" }}
target={<NoteForm timesheet={ts} onSaved={revalidate} />}
/>
)}
{running ? (
<Action.Push
title="Stoppen"
icon={Icon.Stop}
shortcut={{ modifiers: ["cmd"], key: "s" }}
target={<StopForm timesheet={ts} onStopped={revalidate} />}
/>
) : (
<Action
title="Erneut starten"
icon={Icon.Play}
shortcut={{ modifiers: ["cmd"], key: "s" }}
onAction={async () => {
await startTimesheet(choiceKey(ts.project.id, ts.activity.id), {
timezone: catalog?.timezone,
description: ts.description ?? undefined,
tags: ts.tags.join(","),
});
revalidate();
}}
/>
)}
<Action
title={isFavorite ? "Aus Favoriten entfernen" : "Als Favorit markieren"}
icon={isFavorite ? Icon.StarDisabled : Icon.Star}
shortcut={{ modifiers: ["cmd"], key: "f" }}
onAction={() => toggleFavorite(ts, isFavorite)}
/>
<Action.OpenInBrowser
title="In Kimai öffnen"
url={kimaiUrl(`/de/timesheet/${ts.id}/edit`)}
shortcut={{ modifiers: ["cmd"], key: "o" }}
/>
<Action
title="Aktualisieren"
icon={Icon.ArrowClockwise}
shortcut={{ modifiers: ["cmd"], key: "r" }}
onAction={revalidate}
/>
<Action
title="Löschen"
icon={Icon.Trash}
style={Action.Style.Destructive}
shortcut={{ modifiers: ["ctrl"], key: "x" }}
onAction={() => remove(ts)}
/>
</ActionPanel>
}
/>
);
+2 -78
View File
@@ -1,81 +1,5 @@
import { Action, ActionPanel, Form, Icon, popToRoot, showToast, Toast } from "@raycast/api";
import { useEffect, useMemo, useState } from "react";
import { startTimesheet } from "./lib/actions";
import { ChoiceDropdown, choiceKeyOf, firstChoiceValue } from "./lib/choice-dropdown";
import { useCatalog, useStartOptions } from "./lib/hooks";
interface Values {
begin: Date | null;
choice: string;
description: string;
tags: string;
}
import { TimesheetForm } from "./lib/timesheet-form";
export default function StartActivity() {
const { data: catalog, isLoading: catalogLoading } = useCatalog();
const { favorites, recent, isLoading: optionsLoading } = useStartOptions(catalog);
const [choice, setChoice] = useState<string>("");
const [beginError, setBeginError] = useState<string>();
const all = useMemo(() => catalog?.choices ?? [], [catalog]);
const byKey = useMemo(() => new Map(all.map((c) => [c.key, c])), [all]);
const selected = byKey.get(choiceKeyOf(choice) ?? "");
// preselect the first favorite (or recent) entry once loaded
useEffect(() => {
if (choice || optionsLoading || catalogLoading) return;
const first = firstChoiceValue(favorites, recent, all);
if (first) setChoice(first);
}, [favorites, recent, all, optionsLoading, catalogLoading]);
async function handleSubmit(values: Values) {
if (!values.begin) {
setBeginError("Bitte Startzeit angeben");
return false;
}
const key = choiceKeyOf(values.choice);
if (!key) {
await showToast({ style: Toast.Style.Failure, title: "Bitte eine Tätigkeit auswählen" });
return false;
}
const ts = await startTimesheet(key, {
begin: values.begin,
timezone: catalog?.timezone,
description: values.description,
tags: values.tags,
});
if (!ts) return false;
await popToRoot();
}
return (
<Form
isLoading={catalogLoading || optionsLoading}
navigationTitle="Tätigkeit starten"
actions={
<ActionPanel>
<Action.SubmitForm title="Starten" icon={Icon.Play} onSubmit={handleSubmit} />
</ActionPanel>
}
>
<Form.DatePicker
id="begin"
title="Von"
type={Form.DatePicker.Type.DateTime}
defaultValue={new Date()}
error={beginError}
onChange={() => setBeginError(undefined)}
/>
<ChoiceDropdown favorites={favorites} recent={recent} all={all} value={choice} onChange={setChoice} />
{selected && (
<>
<Form.Description title="Kunde" text={selected.customer?.name ?? "–"} />
<Form.Description title="Projekt" text={selected.project.name} />
</>
)}
<Form.Separator />
<Form.TextArea id="description" title="Beschreibung" placeholder="Optional" />
<Form.TextField id="tags" title="Tags" placeholder="Optional, kommagetrennt" />
</Form>
);
return <TimesheetForm mode="start" isRoot />;
}
+9 -49
View File
@@ -1,19 +1,7 @@
import { Action, ActionPanel, Detail, Icon, LaunchProps, List } from "@raycast/api";
import { useEffect, useState } from "react";
import { kimaiUrl } from "./lib/api";
import { useActive } from "./lib/hooks";
import { NoteForm } from "./lib/note-form";
import { StopForm } from "./lib/stop-form";
import { colorIcon, elapsedSeconds, formatDuration, formatTime, timesheetSubtitle, timesheetTitle } from "./lib/utils";
function useNow(intervalMs = 30_000) {
const [now, setNow] = useState(Date.now());
useEffect(() => {
const t = setInterval(() => setNow(Date.now()), intervalMs);
return () => clearInterval(t);
}, [intervalMs]);
return now;
}
import { Detail, Icon, LaunchProps, List } from "@raycast/api";
import { useActive, useNow } from "./lib/hooks";
import { TimesheetForm } from "./lib/timesheet-form";
import { TimesheetActions, TimesheetListItem } from "./lib/timesheet-list";
type Props = LaunchProps<{ launchContext?: { timesheetId?: number } }>;
@@ -26,7 +14,7 @@ export default function StopActivity({ launchContext }: Props) {
const targetId = launchContext?.timesheetId;
if (targetId !== undefined) {
const target = active.find((ts) => ts.id === targetId);
if (target) return <StopForm timesheet={target} isRoot />;
if (target) return <TimesheetForm mode="stop" timesheet={target} isRoot />;
if (isLoading) return <Detail isLoading markdown="" />;
}
@@ -34,39 +22,11 @@ export default function StopActivity({ launchContext }: Props) {
<List isLoading={isLoading} navigationTitle="Laufende Tätigkeiten">
<List.EmptyView icon={Icon.Clock} title="Keine laufenden Tätigkeiten" />
{active.map((ts) => (
<List.Item
<TimesheetListItem
key={ts.id}
icon={colorIcon(ts.activity["color-safe"], Icon.Play)}
title={timesheetTitle(ts)}
subtitle={timesheetSubtitle(ts)}
keywords={[ts.project.name, ts.project.customer.name, ts.description ?? ""]}
accessories={[
...(ts.description ? [{ icon: Icon.Text, tooltip: ts.description }] : []),
{ text: `seit ${formatTime(ts.begin)}` },
{ tag: formatDuration(elapsedSeconds(ts, now)), icon: Icon.Clock },
]}
actions={
<ActionPanel>
<Action.Push
title="Stoppen"
icon={Icon.Stop}
target={<StopForm timesheet={ts} onStopped={revalidate} />}
/>
<Action.Push
title="Notizen schreiben"
icon={Icon.Pencil}
shortcut={{ modifiers: ["cmd"], key: "n" }}
target={<NoteForm timesheet={ts} onSaved={revalidate} />}
/>
<Action.OpenInBrowser title="In Kimai öffnen" url={kimaiUrl("/de/timesheet/")} />
<Action
title="Aktualisieren"
icon={Icon.ArrowClockwise}
shortcut={{ modifiers: ["cmd"], key: "r" }}
onAction={revalidate}
/>
</ActionPanel>
}
timesheet={ts}
now={now}
actions={<TimesheetActions timesheet={ts} primary="stop" onChanged={revalidate} />}
/>
))}
</List>