init
This commit is contained in:
commit
913e5a87d2
18 files changed
+5139
No files matched your search
@@ -0,0 +1,4 @@
|
||||
node_modules
|
||||
/dist
|
||||
raycast-env.d.ts
|
||||
.DS_Store
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"printWidth": 120,
|
||||
"singleQuote": false
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
# Kimai für Raycast
|
||||
|
||||
Zeiterfassung mit [Kimai](https://www.kimai.org) direkt aus Raycast.
|
||||
|
||||
## Befehle
|
||||
|
||||
| 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. |
|
||||
| **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. |
|
||||
|
||||
## Hinweise
|
||||
|
||||
- **Pausen** werden von Kimai automatisch erzeugt. Die Extension sendet beim Starten und Stoppen keine Pause, im Bearbeiten-Formular kann sie angepasst werden.
|
||||
- **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.
|
||||
- Zeiten werden in der Zeitzone des Kimai-Benutzers übertragen.
|
||||
|
||||
## Einrichtung
|
||||
|
||||
```sh
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Beim ersten Start fragt Raycast nach der Kimai-URL (Standard: `https://timetracking.wentocon.de`) und dem API-Token (Kimai: Profil › API-Zugang).
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
@@ -0,0 +1,4 @@
|
||||
const { defineConfig } = require("eslint/config");
|
||||
const raycastConfig = require("@raycast/eslint-config");
|
||||
|
||||
module.exports = defineConfig([...raycastConfig]);
|
||||
Generated
+3707
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,76 @@
|
||||
{
|
||||
"$schema": "https://www.raycast.com/schemas/extension.json",
|
||||
"name": "kimai",
|
||||
"title": "Kimai",
|
||||
"description": "Zeiterfassung mit Kimai: Tätigkeiten starten, stoppen und Timesheets verwalten",
|
||||
"icon": "icon.png",
|
||||
"author": "meirjann",
|
||||
"categories": ["Productivity"],
|
||||
"license": "MIT",
|
||||
"commands": [
|
||||
{
|
||||
"name": "start-activity",
|
||||
"title": "Tätigkeit starten",
|
||||
"subtitle": "Kimai",
|
||||
"description": "Startet eine neue Zeiterfassung, Favoriten zuerst",
|
||||
"mode": "view"
|
||||
},
|
||||
{
|
||||
"name": "stop-activity",
|
||||
"title": "Tätigkeit stoppen",
|
||||
"subtitle": "Kimai",
|
||||
"description": "Zeigt alle laufenden Tätigkeiten und stoppt sie mit Beschreibung",
|
||||
"mode": "view"
|
||||
},
|
||||
{
|
||||
"name": "manage-timesheets",
|
||||
"title": "Timesheets verwalten",
|
||||
"subtitle": "Kimai",
|
||||
"description": "Übersicht und Bearbeitung der Timesheets des aktuellen Monats",
|
||||
"mode": "view"
|
||||
},
|
||||
{
|
||||
"name": "menu-bar",
|
||||
"title": "Kimai Menu Bar",
|
||||
"subtitle": "Kimai",
|
||||
"description": "Laufende Tätigkeiten in der Menüleiste starten und stoppen",
|
||||
"mode": "menu-bar",
|
||||
"interval": "1m"
|
||||
}
|
||||
],
|
||||
"preferences": [
|
||||
{
|
||||
"name": "baseUrl",
|
||||
"title": "Kimai URL",
|
||||
"description": "Basis-URL der Kimai-Instanz",
|
||||
"type": "textfield",
|
||||
"required": true,
|
||||
"default": "https://timetracking.wentocon.de"
|
||||
},
|
||||
{
|
||||
"name": "apiToken",
|
||||
"title": "API Token",
|
||||
"description": "Kimai API Token (Profil > API-Zugang)",
|
||||
"type": "password",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"dependencies": {
|
||||
"@raycast/api": "^2.11.1",
|
||||
"@raycast/utils": "^2.3.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@raycast/eslint-config": "^2.2.0",
|
||||
"@types/node": "26.6.5",
|
||||
"@types/react": "19.3.0",
|
||||
"eslint": "^9.22.0",
|
||||
"prettier": "^3.5.3",
|
||||
"typescript": "^5.8.2"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "ray build",
|
||||
"dev": "ray develop",
|
||||
"fix-lint": "ray lint --fix",
|
||||
"lint": "ray lint"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { showToast, Toast } from "@raycast/api";
|
||||
import { api, Timesheet } from "./api";
|
||||
import { formatDuration, parseChoiceKey, showError, toKimaiDate } from "./utils";
|
||||
|
||||
export async function startTimesheet(
|
||||
choiceKey: string,
|
||||
options: { begin?: Date; 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),
|
||||
project,
|
||||
activity,
|
||||
description: options.description || undefined,
|
||||
tags: options.tags || undefined,
|
||||
});
|
||||
toast.style = Toast.Style.Success;
|
||||
toast.title = `Gestartet: ${ts.activity.name}`;
|
||||
toast.message = `${ts.project.customer.name} › ${ts.project.name}`;
|
||||
return ts;
|
||||
} catch (e) {
|
||||
toast.hide();
|
||||
await showError("Start fehlgeschlagen", e);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** 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}…` });
|
||||
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);
|
||||
return true;
|
||||
} catch (e) {
|
||||
toast.hide();
|
||||
await showError("Stoppen fehlgeschlagen", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
import { getPreferenceValues } from "@raycast/api";
|
||||
|
||||
export interface Customer {
|
||||
id: number;
|
||||
name: string;
|
||||
color?: string | null;
|
||||
"color-safe"?: string;
|
||||
visible: boolean;
|
||||
}
|
||||
|
||||
export interface Project {
|
||||
id: number;
|
||||
name: string;
|
||||
customer: number;
|
||||
parentTitle?: string;
|
||||
globalActivities: boolean;
|
||||
color?: string | null;
|
||||
"color-safe"?: string;
|
||||
visible: boolean;
|
||||
}
|
||||
|
||||
export interface Activity {
|
||||
id: number;
|
||||
name: string;
|
||||
project: number | null;
|
||||
parentTitle?: string | null;
|
||||
color?: string | null;
|
||||
"color-safe"?: string;
|
||||
visible: boolean;
|
||||
}
|
||||
|
||||
/** Timesheet as returned with `full=true` (expanded relations) */
|
||||
export interface Timesheet {
|
||||
id: number;
|
||||
begin: string;
|
||||
end: string | null;
|
||||
duration: number;
|
||||
break?: number;
|
||||
description: string | null;
|
||||
tags: string[];
|
||||
activity: { id: number; name: string; project: number | null; "color-safe"?: string };
|
||||
project: {
|
||||
id: number;
|
||||
name: string;
|
||||
"color-safe"?: string;
|
||||
customer: { id: number; name: string; "color-safe"?: string };
|
||||
};
|
||||
}
|
||||
|
||||
export interface Tag {
|
||||
id: number;
|
||||
name: string;
|
||||
color?: string | null;
|
||||
}
|
||||
|
||||
export interface Me {
|
||||
id: number;
|
||||
username: string;
|
||||
alias?: string | null;
|
||||
timezone: string;
|
||||
}
|
||||
|
||||
export interface TimesheetConfig {
|
||||
trackingMode: string;
|
||||
defaultBeginTime: string;
|
||||
activeEntriesHardLimit: number;
|
||||
isAllowFutureTimes: boolean;
|
||||
isAllowOverlapping: boolean;
|
||||
}
|
||||
|
||||
export interface TimesheetPayload {
|
||||
begin?: string;
|
||||
end?: string | null;
|
||||
project?: number;
|
||||
activity?: number;
|
||||
description?: string;
|
||||
tags?: string;
|
||||
break?: string;
|
||||
}
|
||||
|
||||
export class KimaiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public status?: number,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
function prefs() {
|
||||
const p = getPreferenceValues<Preferences>();
|
||||
return { baseUrl: p.baseUrl.replace(/\/+$/, ""), token: p.apiToken.trim() };
|
||||
}
|
||||
|
||||
export function kimaiUrl(path = ""): string {
|
||||
return `${prefs().baseUrl}${path}`;
|
||||
}
|
||||
|
||||
/** Kimai form errors are nested: { errors: { children: { field: { errors: [...] } } } } */
|
||||
function collectFormErrors(node: unknown, path: string[] = []): string[] {
|
||||
if (!node || typeof node !== "object") return [];
|
||||
const obj = node as Record<string, unknown>;
|
||||
const out: string[] = [];
|
||||
if (Array.isArray(obj.errors)) {
|
||||
for (const e of obj.errors) {
|
||||
if (typeof e === "string") out.push(path.length ? `${path.join(".")}: ${e}` : e);
|
||||
}
|
||||
} else if (obj.errors && typeof obj.errors === "object") {
|
||||
out.push(...collectFormErrors(obj.errors, path));
|
||||
}
|
||||
if (obj.children && typeof obj.children === "object") {
|
||||
for (const [key, child] of Object.entries(obj.children as Record<string, unknown>)) {
|
||||
out.push(...collectFormErrors(child, [...path, key]));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function request<T>(method: string, path: string, body?: unknown): Promise<T> {
|
||||
const { baseUrl, token } = prefs();
|
||||
const res = await fetch(`${baseUrl}/api${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
Accept: "application/json",
|
||||
...(body !== undefined ? { "Content-Type": "application/json" } : {}),
|
||||
},
|
||||
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
|
||||
const text = await res.text();
|
||||
let data: unknown = undefined;
|
||||
if (text) {
|
||||
try {
|
||||
data = JSON.parse(text);
|
||||
} catch {
|
||||
if (!res.ok) throw new KimaiError(`HTTP ${res.status}`, res.status);
|
||||
throw new KimaiError("Ungültige Antwort von Kimai (kein JSON). Stimmt die URL?", res.status);
|
||||
}
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const msg = (data as { message?: string } | undefined)?.message ?? `HTTP ${res.status}`;
|
||||
const details = collectFormErrors(data);
|
||||
throw new KimaiError(details.length ? `${msg}: ${details.join("; ")}` : msg, res.status);
|
||||
}
|
||||
|
||||
// Validation errors are returned with status 400 normally, but be defensive
|
||||
if (data && typeof data === "object" && "errors" in data && !("id" in data)) {
|
||||
const details = collectFormErrors(data);
|
||||
if (details.length) throw new KimaiError(details.join("; "));
|
||||
}
|
||||
|
||||
return data as T;
|
||||
}
|
||||
|
||||
export const api = {
|
||||
me: () => request<Me>("GET", "/users/me"),
|
||||
timesheetConfig: () => request<TimesheetConfig>("GET", "/config/timesheet"),
|
||||
customers: () => request<Customer[]>("GET", "/customers?visible=1"),
|
||||
projects: () => request<Project[]>("GET", "/projects?visible=1"),
|
||||
activities: () => request<Activity[]>("GET", "/activities?visible=1"),
|
||||
/** names of all existing tags */
|
||||
tagNames: () => request<string[]>("GET", "/tags"),
|
||||
createTag: (name: string) => request<Tag>("POST", "/tags", { name, visible: true }),
|
||||
|
||||
active: () => request<Timesheet[]>("GET", "/timesheets/active"),
|
||||
favorites: () => request<Timesheet[]>("GET", "/favorites/timesheets"),
|
||||
recent: () => request<Timesheet[]>("GET", "/timesheets/recent?size=10"),
|
||||
timesheets: (begin: string, end: string) =>
|
||||
request<Timesheet[]>(
|
||||
"GET",
|
||||
`/timesheets?full=true&size=1000&order=DESC&orderBy=begin&begin=${encodeURIComponent(begin)}&end=${encodeURIComponent(end)}`,
|
||||
),
|
||||
|
||||
create: async (payload: TimesheetPayload) =>
|
||||
request<Timesheet>("POST", "/timesheets?full=true", await withEnsuredTags(payload)),
|
||||
update: async (id: number, payload: TimesheetPayload) =>
|
||||
request<Timesheet>("PATCH", `/timesheets/${id}`, await withEnsuredTags(payload)),
|
||||
stop: (id: number) => request<Timesheet>("PATCH", `/timesheets/${id}/stop`),
|
||||
remove: (id: number) => request<void>("DELETE", `/timesheets/${id}`),
|
||||
addFavorite: (id: number) => request<void>("POST", `/favorites/timesheets/${id}`),
|
||||
removeFavorite: (id: number) => request<void>("DELETE", `/favorites/timesheets/${id}`),
|
||||
};
|
||||
|
||||
/**
|
||||
* The timesheet API silently drops unknown tags, so missing tags are created upfront.
|
||||
* Returns the payload with tags normalized to the spelling of existing tags.
|
||||
*/
|
||||
async function withEnsuredTags(payload: TimesheetPayload): Promise<TimesheetPayload> {
|
||||
if (payload.tags === undefined) return payload;
|
||||
const wanted = [
|
||||
...new Set(
|
||||
payload.tags
|
||||
.split(",")
|
||||
.map((t) => t.trim())
|
||||
.filter(Boolean),
|
||||
),
|
||||
];
|
||||
if (wanted.length === 0) return { ...payload, tags: "" };
|
||||
|
||||
const existing = new Map((await api.tagNames()).map((n) => [n.toLowerCase(), n]));
|
||||
const names: string[] = [];
|
||||
for (const tag of wanted) {
|
||||
let name = existing.get(tag.toLowerCase());
|
||||
if (!name) {
|
||||
try {
|
||||
name = (await api.createTag(tag)).name;
|
||||
} catch (e) {
|
||||
// the tag exists but is hidden: Kimai still resolves it by name
|
||||
if (!(e instanceof KimaiError && e.status === 400)) throw e;
|
||||
name = tag;
|
||||
}
|
||||
existing.set(name.toLowerCase(), name);
|
||||
}
|
||||
names.push(name);
|
||||
}
|
||||
return { ...payload, tags: names.join(",") };
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { useCachedPromise } from "@raycast/utils";
|
||||
import { useMemo } from "react";
|
||||
import { api, Timesheet } from "./api";
|
||||
import { ActivityChoice, buildChoices, choiceFromTimesheet } from "./utils";
|
||||
|
||||
export interface Catalog {
|
||||
timezone?: string;
|
||||
choices: ActivityChoice[];
|
||||
customers: Awaited<ReturnType<typeof api.customers>>;
|
||||
projects: Awaited<ReturnType<typeof api.projects>>;
|
||||
activities: Awaited<ReturnType<typeof api.activities>>;
|
||||
}
|
||||
|
||||
async function loadCatalog(): Promise<Catalog> {
|
||||
const [me, customers, projects, activities] = await Promise.all([
|
||||
api.me(),
|
||||
api.customers(),
|
||||
api.projects(),
|
||||
api.activities(),
|
||||
]);
|
||||
return {
|
||||
timezone: me.timezone,
|
||||
customers,
|
||||
projects,
|
||||
activities,
|
||||
choices: buildChoices(customers, projects, activities),
|
||||
};
|
||||
}
|
||||
|
||||
export function useCatalog() {
|
||||
return useCachedPromise(loadCatalog, [], { keepPreviousData: true });
|
||||
}
|
||||
|
||||
export function useActive() {
|
||||
return useCachedPromise(api.active, [], { keepPreviousData: true });
|
||||
}
|
||||
|
||||
export interface StartOptions {
|
||||
favorites: ActivityChoice[];
|
||||
recent: ActivityChoice[];
|
||||
/** template timesheet per choice key (favorite or recent) to prefill description/tags */
|
||||
templates: Map<string, Timesheet>;
|
||||
}
|
||||
|
||||
async function loadStartOptions(): Promise<Timesheet[][]> {
|
||||
return Promise.all([api.favorites(), api.recent()]);
|
||||
}
|
||||
|
||||
/** Favorites and recently used activities, resolved against the catalog and de-duplicated */
|
||||
export function useStartOptions(catalog?: Catalog) {
|
||||
const { data, isLoading, revalidate } = useCachedPromise(loadStartOptions, [], { keepPreviousData: true });
|
||||
|
||||
const options = useMemo<StartOptions>(() => {
|
||||
const templates = new Map<string, Timesheet>();
|
||||
const byKey = new Map((catalog?.choices ?? []).map((c) => [c.key, c]));
|
||||
const resolve = (list: Timesheet[], seen: Set<string>) => {
|
||||
const out: ActivityChoice[] = [];
|
||||
for (const ts of list) {
|
||||
const base = choiceFromTimesheet(ts);
|
||||
if (seen.has(base.key)) continue;
|
||||
const choice = byKey.get(base.key);
|
||||
// only offer combinations which are still visible / startable
|
||||
if (!choice) continue;
|
||||
seen.add(base.key);
|
||||
if (!templates.has(base.key)) templates.set(base.key, ts);
|
||||
out.push(choice);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
const seen = new Set<string>();
|
||||
const [favorites = [], recent = []] = data ?? [];
|
||||
return { favorites: resolve(favorites, seen), recent: resolve(recent, seen), templates };
|
||||
}, [data, catalog]);
|
||||
|
||||
return { ...options, isLoading, revalidate };
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { Color, Icon, Image, showToast, Toast } from "@raycast/api";
|
||||
import { Activity, Customer, Project, Timesheet } from "./api";
|
||||
|
||||
/** Formats a Date as Kimai's HTML5 local datetime ("YYYY-MM-DDTHH:mm:ss") in the given timezone */
|
||||
export function toKimaiDate(date: Date, timeZone?: string): string {
|
||||
const parts = new Intl.DateTimeFormat("sv-SE", {
|
||||
timeZone,
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
second: "2-digit",
|
||||
hourCycle: "h23",
|
||||
}).format(date);
|
||||
return parts.replace(" ", "T");
|
||||
}
|
||||
|
||||
/** Seconds -> "H:MM" (Kimai duration format) */
|
||||
export function formatDuration(seconds: number): string {
|
||||
const s = Math.max(0, Math.round(seconds));
|
||||
const h = Math.floor(s / 3600);
|
||||
const m = Math.floor((s % 3600) / 60);
|
||||
return `${h}:${String(m).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses durations like "1:30", "1h 30m", "90m", "1,5", "1.5h", "45" (minutes) into seconds.
|
||||
* Returns undefined for invalid input.
|
||||
*/
|
||||
export function parseDuration(input: string): number | undefined {
|
||||
const v = input.trim().toLowerCase();
|
||||
if (v === "") return 0;
|
||||
let m = v.match(/^(\d+):(\d{1,2})(?::(\d{1,2}))?$/);
|
||||
if (m) return Number(m[1]) * 3600 + Number(m[2]) * 60 + Number(m[3] ?? 0);
|
||||
m = v.match(/^(?:(\d+(?:[.,]\d+)?)\s*h)?\s*(?:(\d+)\s*m(?:in)?)?$/);
|
||||
if (m && (m[1] || m[2])) return Math.round(Number((m[1] ?? "0").replace(",", ".")) * 3600) + Number(m[2] ?? 0) * 60;
|
||||
m = v.match(/^(\d+[.,]\d+)$/);
|
||||
if (m) return Math.round(Number(m[1].replace(",", ".")) * 3600);
|
||||
m = v.match(/^(\d+)$/);
|
||||
if (m) return Number(m[1]) * 60;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
const timeFmt = new Intl.DateTimeFormat("de-DE", { hour: "2-digit", minute: "2-digit" });
|
||||
const dayFmt = new Intl.DateTimeFormat("de-DE", { weekday: "long", day: "2-digit", month: "2-digit", year: "numeric" });
|
||||
|
||||
export const formatTime = (iso: string) => timeFmt.format(new Date(iso));
|
||||
export const formatDay = (iso: string) => dayFmt.format(new Date(iso));
|
||||
|
||||
export function dayKey(iso: string): string {
|
||||
const d = new Date(iso);
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export function colorIcon(color?: string | null, source: Image.Source = Icon.CircleFilled): Image.ImageLike {
|
||||
return { source, tintColor: color ?? Color.SecondaryText };
|
||||
}
|
||||
|
||||
/** A startable combination of customer / project / activity */
|
||||
export interface ActivityChoice {
|
||||
key: string;
|
||||
activity: Activity;
|
||||
project: Project;
|
||||
customer?: Customer;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
color?: string;
|
||||
}
|
||||
|
||||
export const choiceKey = (projectId: number, activityId: number) => `${projectId}:${activityId}`;
|
||||
|
||||
export function parseChoiceKey(key: string): { project: number; activity: number } {
|
||||
const [project, activity] = key.split(":").map(Number);
|
||||
return { project, activity };
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds all startable activity choices. Project-specific activities map to exactly one project;
|
||||
* global activities (project = null) are offered for every project that allows global activities.
|
||||
*/
|
||||
export function buildChoices(customers: Customer[], projects: Project[], activities: Activity[]): ActivityChoice[] {
|
||||
const customerById = new Map(customers.map((c) => [c.id, c]));
|
||||
const projectById = new Map(projects.map((p) => [p.id, p]));
|
||||
const choices: ActivityChoice[] = [];
|
||||
|
||||
const add = (activity: Activity, project: Project) => {
|
||||
const customer = customerById.get(project.customer);
|
||||
choices.push({
|
||||
key: choiceKey(project.id, activity.id),
|
||||
activity,
|
||||
project,
|
||||
customer,
|
||||
title: activity.name,
|
||||
subtitle: `${customer?.name ?? project.parentTitle ?? "?"} › ${project.name}`,
|
||||
color: activity["color-safe"] ?? project["color-safe"],
|
||||
});
|
||||
};
|
||||
|
||||
for (const activity of activities) {
|
||||
if (activity.project != null) {
|
||||
const project = projectById.get(activity.project);
|
||||
if (project) add(activity, project);
|
||||
} else {
|
||||
for (const project of projects) if (project.globalActivities) add(activity, project);
|
||||
}
|
||||
}
|
||||
|
||||
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"> {
|
||||
return {
|
||||
key: choiceKey(ts.project.id, ts.activity.id),
|
||||
title: ts.activity.name,
|
||||
subtitle: `${ts.project.customer.name} › ${ts.project.name}`,
|
||||
color: ts.activity["color-safe"] ?? ts.project["color-safe"],
|
||||
};
|
||||
}
|
||||
|
||||
export function timesheetTitle(ts: Timesheet): string {
|
||||
return ts.activity.name;
|
||||
}
|
||||
|
||||
export function timesheetSubtitle(ts: Timesheet): string {
|
||||
return `${ts.project.customer.name} › ${ts.project.name}`;
|
||||
}
|
||||
|
||||
export function errorMessage(e: unknown): string {
|
||||
return e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
|
||||
export async function showError(title: string, e: unknown) {
|
||||
await showToast({ style: Toast.Style.Failure, title, message: errorMessage(e) });
|
||||
}
|
||||
|
||||
export function parseTags(input: string): string[] {
|
||||
return input
|
||||
.split(",")
|
||||
.map((t) => t.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
import { Action, ActionPanel, Alert, Color, confirmAlert, Icon, List, showToast, Toast } 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 { useCatalog } from "./lib/hooks";
|
||||
import { StopForm } from "./lib/stop-form";
|
||||
import {
|
||||
choiceKey,
|
||||
colorIcon,
|
||||
dayKey,
|
||||
elapsedSeconds,
|
||||
formatDay,
|
||||
formatDuration,
|
||||
formatTime,
|
||||
showError,
|
||||
timesheetSubtitle,
|
||||
timesheetTitle,
|
||||
toKimaiDate,
|
||||
} from "./lib/utils";
|
||||
|
||||
const monthFmt = new Intl.DateTimeFormat("de-DE", { month: "long", year: "numeric" });
|
||||
|
||||
/** The current month plus the 11 months before, as "YYYY-MM" */
|
||||
function monthOptions(): { value: string; title: string }[] {
|
||||
const now = new Date();
|
||||
return Array.from({ length: 12 }, (_, i) => {
|
||||
const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
|
||||
return {
|
||||
value: `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`,
|
||||
title: monthFmt.format(d),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function loadMonth(month: string, timezone: string | undefined): Promise<[Timesheet[], number[]]> {
|
||||
const [y, m] = month.split("-").map(Number);
|
||||
const begin = toKimaiDate(new Date(y, m - 1, 1, 0, 0, 0), timezone);
|
||||
const end = toKimaiDate(new Date(y, m, 0, 23, 59, 59), timezone);
|
||||
const [timesheets, favorites] = await Promise.all([api.timesheets(begin, end), api.favorites()]);
|
||||
return [timesheets, favorites.map((f) => f.id)];
|
||||
}
|
||||
|
||||
export default function ManageTimesheets() {
|
||||
const months = useMemo(monthOptions, []);
|
||||
const [month, setMonth] = useState(months[0].value);
|
||||
const { data: catalog } = useCatalog();
|
||||
const { data, isLoading, revalidate } = useCachedPromise(loadMonth, [month, catalog?.timezone], {
|
||||
keepPreviousData: true,
|
||||
execute: catalog !== undefined,
|
||||
});
|
||||
|
||||
const [timesheets = [], favoriteIds = []] = data ?? [];
|
||||
const now = Date.now();
|
||||
|
||||
const days = useMemo(() => {
|
||||
const groups = new Map<string, Timesheet[]>();
|
||||
for (const ts of timesheets) {
|
||||
const key = dayKey(ts.begin);
|
||||
groups.set(key, [...(groups.get(key) ?? []), ts]);
|
||||
}
|
||||
return [...groups.entries()].sort(([a], [b]) => b.localeCompare(a));
|
||||
}, [timesheets]);
|
||||
|
||||
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}
|
||||
navigationTitle={`Timesheets · ${formatDuration(monthTotal)} h`}
|
||||
searchBarPlaceholder="Timesheets durchsuchen"
|
||||
searchBarAccessory={
|
||||
<List.Dropdown tooltip="Monat" value={month} onChange={setMonth}>
|
||||
{months.map((m) => (
|
||||
<List.Dropdown.Item key={m.value} value={m.value} title={m.title} />
|
||||
))}
|
||||
</List.Dropdown>
|
||||
}
|
||||
>
|
||||
<List.EmptyView icon={Icon.Calendar} title="Keine Timesheets in diesem Monat" />
|
||||
{days.map(([key, entries]) => {
|
||||
const total = entries.reduce((sum, ts) => sum + elapsedSeconds(ts, now), 0);
|
||||
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
|
||||
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,
|
||||
},
|
||||
},
|
||||
]}
|
||||
actions={
|
||||
<ActionPanel>
|
||||
<Action.Push
|
||||
title="Bearbeiten"
|
||||
icon={Icon.Pencil}
|
||||
target={<TimesheetEditForm timesheet={ts} catalog={catalog} 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>
|
||||
}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</List.Section>
|
||||
);
|
||||
})}
|
||||
</List>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { Color, Icon, launchCommand, LaunchType, MenuBarExtra, open } from "@raycast/api";
|
||||
import { useMemo } from "react";
|
||||
import { startTimesheet } from "./lib/actions";
|
||||
import { kimaiUrl } from "./lib/api";
|
||||
import { useActive, useCatalog, useStartOptions } from "./lib/hooks";
|
||||
import { ActivityChoice, colorIcon, elapsedSeconds, formatDuration, formatTime, timesheetSubtitle } from "./lib/utils";
|
||||
|
||||
function truncate(s: string, max = 28) {
|
||||
return s.length > max ? `${s.slice(0, max - 1)}…` : s;
|
||||
}
|
||||
|
||||
export default function MenuBar() {
|
||||
const { data: catalog, isLoading: catalogLoading } = useCatalog();
|
||||
const { data: active, isLoading: activeLoading, revalidate: revalidateActive } = useActive();
|
||||
const { favorites, recent, isLoading: optionsLoading, revalidate: revalidateOptions } = useStartOptions(catalog);
|
||||
|
||||
const running = active ?? [];
|
||||
const now = Date.now();
|
||||
const total = running.reduce((sum, ts) => sum + elapsedSeconds(ts, now), 0);
|
||||
|
||||
const title =
|
||||
running.length === 0
|
||||
? undefined
|
||||
: running.length === 1
|
||||
? `${truncate(running[0].activity.name, 18)} ${formatDuration(total)}`
|
||||
: `${running.length}× ${formatDuration(total)}`;
|
||||
|
||||
// all activities grouped by customer, for the "Alle Tätigkeiten" submenu
|
||||
const byCustomer = useMemo(() => {
|
||||
const groups = new Map<string, ActivityChoice[]>();
|
||||
for (const c of catalog?.choices ?? []) {
|
||||
const name = c.customer?.name ?? "Ohne Kunde";
|
||||
groups.set(name, [...(groups.get(name) ?? []), c]);
|
||||
}
|
||||
return [...groups.entries()].sort(([a], [b]) => a.localeCompare(b, "de"));
|
||||
}, [catalog]);
|
||||
|
||||
async function start(choice: ActivityChoice) {
|
||||
await startTimesheet(choice.key, { timezone: catalog?.timezone });
|
||||
revalidateActive();
|
||||
revalidateOptions();
|
||||
}
|
||||
|
||||
const isRunning = (choice: ActivityChoice) =>
|
||||
running.some((ts) => ts.project.id === choice.project.id && ts.activity.id === choice.activity.id);
|
||||
|
||||
const startItem = (choice: ActivityChoice, prefix: string, title = choice.title) => (
|
||||
<MenuBarExtra.Item
|
||||
key={`${prefix}-${choice.key}`}
|
||||
icon={colorIcon(choice.color, isRunning(choice) ? Icon.Play : Icon.CircleFilled)}
|
||||
title={title}
|
||||
subtitle={prefix === "all" ? undefined : choice.subtitle}
|
||||
tooltip={`${choice.subtitle} › ${choice.title} starten`}
|
||||
onAction={() => start(choice)}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<MenuBarExtra
|
||||
icon={{ source: Icon.Clock, tintColor: running.length ? Color.Green : undefined }}
|
||||
title={title}
|
||||
tooltip="Kimai"
|
||||
isLoading={catalogLoading || activeLoading || optionsLoading}
|
||||
>
|
||||
<MenuBarExtra.Section
|
||||
title={running.length ? `Laufend (${formatDuration(total)} h)` : "Keine laufende Tätigkeit"}
|
||||
>
|
||||
{running.map((ts) => (
|
||||
<MenuBarExtra.Submenu
|
||||
key={ts.id}
|
||||
icon={colorIcon(ts.activity["color-safe"], Icon.Play)}
|
||||
title={`${ts.activity.name} ${formatDuration(elapsedSeconds(ts, now))}`}
|
||||
>
|
||||
<MenuBarExtra.Item title={timesheetSubtitle(ts)} subtitle={`seit ${formatTime(ts.begin)}`} />
|
||||
{ts.description ? <MenuBarExtra.Item title={truncate(ts.description, 60)} icon={Icon.Text} /> : null}
|
||||
<MenuBarExtra.Separator />
|
||||
<MenuBarExtra.Item
|
||||
title="Stoppen…"
|
||||
icon={Icon.Stop}
|
||||
onAction={() =>
|
||||
launchCommand({
|
||||
name: "stop-activity",
|
||||
type: LaunchType.UserInitiated,
|
||||
context: { timesheetId: ts.id },
|
||||
})
|
||||
}
|
||||
/>
|
||||
</MenuBarExtra.Submenu>
|
||||
))}
|
||||
</MenuBarExtra.Section>
|
||||
|
||||
{favorites.length > 0 && (
|
||||
<MenuBarExtra.Section title="Favoriten starten">
|
||||
{favorites.map((c) => startItem(c, "fav"))}
|
||||
</MenuBarExtra.Section>
|
||||
)}
|
||||
{recent.length > 0 && (
|
||||
<MenuBarExtra.Section title="Zuletzt verwendet">{recent.map((c) => startItem(c, "rec"))}</MenuBarExtra.Section>
|
||||
)}
|
||||
|
||||
<MenuBarExtra.Section>
|
||||
<MenuBarExtra.Submenu title="Alle Tätigkeiten" icon={Icon.List}>
|
||||
{byCustomer.map(([customer, choices]) => (
|
||||
<MenuBarExtra.Submenu key={customer} title={customer} icon={Icon.Building}>
|
||||
{choices.map((c) => startItem(c, "all", `${c.project.name} › ${c.title}`))}
|
||||
</MenuBarExtra.Submenu>
|
||||
))}
|
||||
</MenuBarExtra.Submenu>
|
||||
<MenuBarExtra.Item
|
||||
title="Tätigkeit starten…"
|
||||
icon={Icon.Play}
|
||||
onAction={() => launchCommand({ name: "start-activity", type: LaunchType.UserInitiated })}
|
||||
/>
|
||||
<MenuBarExtra.Item
|
||||
title="Timesheets verwalten…"
|
||||
icon={Icon.Calendar}
|
||||
onAction={() => launchCommand({ name: "manage-timesheets", type: LaunchType.UserInitiated })}
|
||||
/>
|
||||
<MenuBarExtra.Item title="Kimai öffnen" icon={Icon.Globe} onAction={() => open(kimaiUrl("/"))} />
|
||||
</MenuBarExtra.Section>
|
||||
</MenuBarExtra>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { Action, ActionPanel, Form, Icon, popToRoot, showToast, Toast } from "@raycast/api";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { startTimesheet } from "./lib/actions";
|
||||
import { useCatalog, useStartOptions } from "./lib/hooks";
|
||||
import { ActivityChoice, colorIcon } from "./lib/utils";
|
||||
|
||||
interface Values {
|
||||
begin: Date | null;
|
||||
choice: string;
|
||||
description: string;
|
||||
tags: string;
|
||||
}
|
||||
|
||||
function ChoiceItem({ choice, prefix }: { choice: ActivityChoice; prefix: string }) {
|
||||
return (
|
||||
<Form.Dropdown.Item
|
||||
value={`${prefix}|${choice.key}`}
|
||||
title={`${choice.title} · ${choice.subtitle}`}
|
||||
keywords={[choice.title, choice.project.name, choice.customer?.name ?? ""]}
|
||||
icon={colorIcon(choice.color)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
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 = choice ? byKey.get(choice.split("|")[1]) : undefined;
|
||||
|
||||
// preselect the first favorite (or recent) entry once loaded
|
||||
useEffect(() => {
|
||||
if (choice || optionsLoading || catalogLoading) return;
|
||||
const first = favorites[0] ? `fav|${favorites[0].key}` : recent[0] ? `rec|${recent[0].key}` : undefined;
|
||||
if (first) setChoice(first);
|
||||
else if (all[0]) setChoice(`all|${all[0].key}`);
|
||||
}, [favorites, recent, all, optionsLoading, catalogLoading]);
|
||||
|
||||
async function handleSubmit(values: Values) {
|
||||
if (!values.begin) {
|
||||
setBeginError("Bitte Startzeit angeben");
|
||||
return false;
|
||||
}
|
||||
const key = values.choice.split("|")[1];
|
||||
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)}
|
||||
/>
|
||||
<Form.Dropdown id="choice" title="Tätigkeit" value={choice} onChange={setChoice}>
|
||||
{favorites.length > 0 && (
|
||||
<Form.Dropdown.Section title="⭐ Favoriten">
|
||||
{favorites.map((c) => (
|
||||
<ChoiceItem key={`fav-${c.key}`} choice={c} prefix="fav" />
|
||||
))}
|
||||
</Form.Dropdown.Section>
|
||||
)}
|
||||
{recent.length > 0 && (
|
||||
<Form.Dropdown.Section title="Zuletzt verwendet">
|
||||
{recent.map((c) => (
|
||||
<ChoiceItem key={`rec-${c.key}`} choice={c} prefix="rec" />
|
||||
))}
|
||||
</Form.Dropdown.Section>
|
||||
)}
|
||||
<Form.Dropdown.Section title="Alle Tätigkeiten">
|
||||
{all.map((c) => (
|
||||
<ChoiceItem key={`all-${c.key}`} choice={c} prefix="all" />
|
||||
))}
|
||||
</Form.Dropdown.Section>
|
||||
</Form.Dropdown>
|
||||
{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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
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 { 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;
|
||||
}
|
||||
|
||||
type Props = LaunchProps<{ launchContext?: { timesheetId?: number } }>;
|
||||
|
||||
export default function StopActivity({ launchContext }: Props) {
|
||||
const { data, isLoading, revalidate } = useActive();
|
||||
const now = useNow();
|
||||
const active = data ?? [];
|
||||
|
||||
// launched from the menu bar for a specific timesheet: show its stop form directly
|
||||
const targetId = launchContext?.timesheetId;
|
||||
if (targetId !== undefined) {
|
||||
const target = active.find((ts) => ts.id === targetId);
|
||||
if (target) return <StopForm timesheet={target} isRoot />;
|
||||
if (isLoading) return <Detail isLoading markdown="" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<List isLoading={isLoading} navigationTitle="Laufende Tätigkeiten">
|
||||
<List.EmptyView icon={Icon.Clock} title="Keine laufenden Tätigkeiten" />
|
||||
{active.map((ts) => (
|
||||
<List.Item
|
||||
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.OpenInBrowser title="In Kimai öffnen" url={kimaiUrl("/de/timesheet/")} />
|
||||
<Action
|
||||
title="Aktualisieren"
|
||||
icon={Icon.ArrowClockwise}
|
||||
shortcut={{ modifiers: ["cmd"], key: "r" }}
|
||||
onAction={revalidate}
|
||||
/>
|
||||
</ActionPanel>
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</List>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/tsconfig",
|
||||
"display": "Node 22",
|
||||
"include": ["src/**/*", "raycast-env.d.ts"],
|
||||
"compilerOptions": {
|
||||
"lib": ["ES2023"],
|
||||
"module": "commonjs",
|
||||
"target": "ES2023",
|
||||
"strict": true,
|
||||
"isolatedModules": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"jsx": "react-jsx",
|
||||
"resolveJsonModule": true
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user