feat(cc-053): Goals & OKR page

This commit is contained in:
admin-valentin 2026-08-01 10:43:39 +00:00
parent f9ceccdeb3
commit 4c84f090ca

View file

@ -1,215 +1,194 @@
'use client';
import { useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { apiFetch, type Goal, type GoalStatus } from '../../../lib/api';
import { useQuery } from '@tanstack/react-query';
import { apiFetch } from '../../../lib/api';
import type { Goal } from '../../../lib/api';
import { useSession } from '../../../components/session-provider';
const GOAL_STATUS_LABELS: Record<GoalStatus, string> = {
not_started: 'Neînceput',
on_track: 'Pe track',
at_risk: 'La risc',
achieved: 'Atins',
abandoned: 'Abandonat',
};
const STATUS_COLORS: Record<GoalStatus, string> = {
not_started: 'text-ink-faint',
on_track: 'text-signal-ok',
at_risk: 'text-signal-warn',
achieved: 'text-bronze-deep',
abandoned: 'text-ink-line',
};
const createGoalSchema = z.object({
horizon: z.string().min(1, 'Orizontul este obligatoriu').max(500),
metric: z.string().min(1, 'Metrica este obligatorie').max(500),
target: z.string().min(1, 'Ținta este obligatorie').max(1000),
});
type CreateGoalForm = z.infer<typeof createGoalSchema>;
const STATUS_CFG = {
not_started: { label: 'Neînceput', cls: 'bg-paper-sunken text-ink-faint' },
on_track: { label: 'Pe plan', cls: 'bg-signal-ok/10 text-signal-ok' },
at_risk: { label: 'La risc', cls: 'bg-signal-warn/10 text-signal-warn' },
achieved: { label: 'Realizat', cls: 'bg-signal-ok/20 text-signal-ok font-semibold' },
abandoned: { label: 'Abandonat', cls: 'bg-paper-sunken text-ink-line line-through' },
} as const;
export default function GoalsPage() {
const { activeTenant } = useSession();
const tenantId = activeTenant?.tenantId ?? '';
const queryClient = useQueryClient();
const [isFormOpen, setIsFormOpen] = useState(false);
const [statusFilter, setStatusFilter] = useState<GoalStatus | ''>('');
const { data: goals = [], isLoading } = useQuery({
queryKey: ['goals', tenantId, statusFilter],
queryFn: () =>
apiFetch<Goal[]>(
`/v1/goals${statusFilter ? `?status=${statusFilter}` : ''}`,
{ tenantId },
),
const { data: goals = [], isLoading, refetch } = useQuery({
queryKey: ['goals', tenantId],
queryFn: () => apiFetch<Goal[]>('/v1/goals', { tenantId }),
enabled: Boolean(tenantId),
});
const { register, handleSubmit, reset, formState: { errors, isSubmitting } } = useForm<CreateGoalForm>({
resolver: zodResolver(createGoalSchema),
});
const [showForm, setShowForm] = useState(false);
const [form, setForm] = useState({ horizon: '', metric: '', target: '' });
const [saving, setSaving] = useState(false);
const createGoal = useMutation({
mutationFn: (values: CreateGoalForm) =>
apiFetch<Goal>('/v1/goals', { method: 'POST', tenantId, body: values }),
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ['goals', tenantId] });
reset();
setIsFormOpen(false);
},
});
const byStatus = {
at_risk: goals.filter((g) => g.status === 'at_risk'),
on_track: goals.filter((g) => g.status === 'on_track'),
not_started: goals.filter((g) => g.status === 'not_started'),
achieved: goals.filter((g) => g.status === 'achieved'),
abandoned: goals.filter((g) => g.status === 'abandoned'),
};
const updateStatus = useMutation({
mutationFn: ({ id, status }: { id: string; status: GoalStatus }) =>
apiFetch<Goal>(`/v1/goals/${id}`, { method: 'PATCH', tenantId, body: { status } }),
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ['goals', tenantId] });
},
});
async function handleCreate(e: React.FormEvent) {
e.preventDefault();
if (!form.horizon || !form.metric || !form.target) return;
setSaving(true);
await apiFetch('/v1/goals', { tenantId, method: 'POST', body: form });
setForm({ horizon: '', metric: '', target: '' });
setShowForm(false);
setSaving(false);
refetch();
}
const deleteGoal = useMutation({
mutationFn: (id: string) =>
apiFetch<{ deleted: boolean }>(`/v1/goals/${id}`, { method: 'DELETE', tenantId }),
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ['goals', tenantId] });
},
});
async function updateStatus(id: string, status: string) {
await apiFetch(`/v1/goals/${id}`, { tenantId, method: 'PATCH', body: { status } });
refetch();
}
return (
<div className="max-w-3xl">
<div className="mb-6 flex items-center justify-between">
<div className="max-w-5xl space-y-6">
<div className="flex items-start justify-between">
<div>
<h1 className="font-display text-2xl font-semibold text-ink">Obiective</h1>
<p className="text-sm text-ink-faint">Obiectivele strategice urmărite în acest workspace.</p>
<h1 className="font-display text-2xl font-semibold text-ink">Obiective & OKR</h1>
<p className="mt-1 text-sm text-ink-faint">
Urmărire obiective pe orizont de timp: lunar, trimestrial, anual.
</p>
</div>
<button type="button" className="btn-primary" onClick={() => setIsFormOpen((v) => !v)}>
{isFormOpen ? 'Anulează' : 'Obiectiv nou'}
<button
onClick={() => setShowForm((v) => !v)}
className="rounded-lg bg-bronze-deep px-4 py-2 text-sm font-medium text-white hover:bg-bronze-deep/90 transition-colors"
>
+ Obiectiv nou
</button>
</div>
{isFormOpen && (
<form
onSubmit={handleSubmit((values) => createGoal.mutate(values))}
noValidate
className="card mb-6 space-y-4 p-5"
>
<div>
<label className="label" htmlFor="goal-horizon">Orizont</label>
<input
id="goal-horizon"
type="text"
className="field"
placeholder="ex: Q3 2026, 12 luni, Trimestrul II"
{...register('horizon')}
/>
{errors.horizon && <p className="mt-1 text-xs text-signal-danger">{errors.horizon.message}</p>}
{showForm && (
<form onSubmit={handleCreate} className="card p-5 space-y-4">
<h2 className="text-sm font-semibold text-ink">Obiectiv nou</h2>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
<div>
<label className="block text-xs font-medium text-ink-faint mb-1">Orizont *</label>
<input
className="w-full rounded-lg border border-paper-border bg-paper px-3 py-2 text-sm text-ink placeholder:text-ink-line focus:border-bronze-deep focus:outline-none"
placeholder="ex: Q3 2026"
value={form.horizon}
onChange={(e) => setForm((f) => ({ ...f, horizon: e.target.value }))}
required
/>
</div>
<div>
<label className="block text-xs font-medium text-ink-faint mb-1">Metric *</label>
<input
className="w-full rounded-lg border border-paper-border bg-paper px-3 py-2 text-sm text-ink placeholder:text-ink-line focus:border-bronze-deep focus:outline-none"
placeholder="ex: MRR, Clienți noi"
value={form.metric}
onChange={(e) => setForm((f) => ({ ...f, metric: e.target.value }))}
required
/>
</div>
<div>
<label className="block text-xs font-medium text-ink-faint mb-1">Target *</label>
<input
className="w-full rounded-lg border border-paper-border bg-paper px-3 py-2 text-sm text-ink placeholder:text-ink-line focus:border-bronze-deep focus:outline-none"
placeholder="ex: 5000 EUR/lună"
value={form.target}
onChange={(e) => setForm((f) => ({ ...f, target: e.target.value }))}
required
/>
</div>
</div>
<div>
<label className="label" htmlFor="goal-metric">Metrică</label>
<input
id="goal-metric"
type="text"
className="field"
placeholder="ex: Cifra de afaceri, Clienți noi, Uptime"
{...register('metric')}
/>
{errors.metric && <p className="mt-1 text-xs text-signal-danger">{errors.metric.message}</p>}
<div className="flex gap-2">
<button
type="submit"
disabled={saving}
className="rounded-lg bg-bronze-deep px-4 py-2 text-sm font-medium text-white disabled:opacity-50"
>
{saving ? 'Se salvează…' : 'Salvează'}
</button>
<button
type="button"
onClick={() => setShowForm(false)}
className="rounded-lg border border-paper-border px-4 py-2 text-sm text-ink-faint hover:border-ink-faint"
>
Anulare
</button>
</div>
<div>
<label className="label" htmlFor="goal-target">Țintă</label>
<input
id="goal-target"
type="text"
className="field"
placeholder="ex: 500.000 EUR, 50 clienți, 99.9%"
{...register('target')}
/>
{errors.target && <p className="mt-1 text-xs text-signal-danger">{errors.target.message}</p>}
</div>
{createGoal.isError && (
<p className="text-sm text-signal-danger">
{createGoal.error instanceof Error ? createGoal.error.message : 'Eroare la creare'}
</p>
)}
<button type="submit" disabled={isSubmitting || createGoal.isPending} className="btn-primary">
Salvează
</button>
</form>
)}
<div className="mb-4 flex flex-wrap gap-2">
<button
type="button"
onClick={() => setStatusFilter('')}
className={`rounded-full px-3 py-1 text-xs font-medium transition-colors ${
statusFilter === '' ? 'bg-ink text-paper' : 'bg-paper-sunken text-ink-soft hover:text-ink'
}`}
>
Toate
</button>
{(Object.keys(GOAL_STATUS_LABELS) as GoalStatus[]).map((status) => (
<button
key={status}
type="button"
onClick={() => setStatusFilter(status)}
className={`rounded-full px-3 py-1 text-xs font-medium transition-colors ${
statusFilter === status ? 'bg-ink text-paper' : 'bg-paper-sunken text-ink-soft hover:text-ink'
}`}
>
{GOAL_STATUS_LABELS[status]}
</button>
))}
</div>
{isLoading && <p className="text-sm text-ink-faint">Se încarcă</p>}
{!isLoading && goals.length === 0 && (
<p className="card p-6 text-sm text-ink-faint">
{statusFilter
? `Niciun obiectiv cu statusul "${GOAL_STATUS_LABELS[statusFilter]}".`
: 'Niciun obiectiv încă. Adaugă primul mai sus.'}
</p>
)}
<ul className="space-y-3">
{goals.map((goal) => (
<li key={goal.id} className="card p-4">
<div className="flex items-start justify-between gap-4">
<div className="flex-1 min-w-0">
<p className="text-[11px] font-medium uppercase tracking-wider text-ink-faint">{goal.horizon}</p>
<p className="mt-0.5 text-sm font-medium text-ink truncate">{goal.metric}</p>
<p className="mt-0.5 text-sm text-ink-soft">{goal.target}</p>
</div>
<div className="flex items-center gap-2 shrink-0">
<select
aria-label={`Status pentru ${goal.metric}`}
className={`rounded-lg border border-ink-line bg-paper-raised px-2.5 py-1.5 text-xs font-medium
focus:border-bronze focus:outline-none focus:ring-2 focus:ring-bronze/20
${STATUS_COLORS[goal.status]}`}
value={goal.status}
onChange={(e) =>
updateStatus.mutate({ id: goal.id, status: e.target.value as GoalStatus })
}
>
{(Object.entries(GOAL_STATUS_LABELS) as [GoalStatus, string][]).map(([value, label]) => (
<option key={value} value={value}>{label}</option>
))}
</select>
<button
type="button"
onClick={() => deleteGoal.mutate(goal.id)}
disabled={deleteGoal.isPending}
className="text-xs text-signal-danger hover:underline disabled:opacity-50"
>
Șterge
</button>
{isLoading ? (
<p className="text-sm text-ink-faint">Se încarcă</p>
) : goals.length === 0 ? (
<div className="card p-12 text-center">
<p className="font-semibold text-ink">Niciun obiectiv definit</p>
<p className="mt-1 text-sm text-ink-faint">Adaugă primul obiectiv pentru a urmări progresul companiei.</p>
</div>
) : (
<>
{/* Summary stats */}
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
{(Object.keys(STATUS_CFG) as (keyof typeof STATUS_CFG)[]).map((s) => (
<div key={s} className="card p-4">
<p className="text-xs text-ink-faint">{STATUS_CFG[s].label}</p>
<p className="mt-1 font-display text-3xl font-semibold text-ink">{byStatus[s].length}</p>
</div>
))}
<div className="card p-4">
<p className="text-xs text-ink-faint">Total</p>
<p className="mt-1 font-display text-3xl font-semibold text-ink">{goals.length}</p>
</div>
</li>
))}
</ul>
</div>
{/* Goals grouped by status */}
{(['at_risk', 'on_track', 'not_started', 'achieved', 'abandoned'] as const).map((s) => {
const group = byStatus[s];
if (group.length === 0) return null;
return (
<section key={s} className="space-y-2">
<h2 className="text-xs font-semibold uppercase tracking-wider text-ink-faint">
{STATUS_CFG[s].label} ({group.length})
</h2>
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
{group.map((goal) => (
<div key={goal.id} className="card p-5">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
<span className="rounded-full bg-paper-sunken px-2 py-0.5 font-mono text-[11px] text-ink-faint">
{goal.horizon}
</span>
<span className={`rounded-full px-2 py-0.5 text-[11px] font-medium ${STATUS_CFG[goal.status].cls}`}>
{STATUS_CFG[goal.status].label}
</span>
</div>
<p className="mt-2 text-sm font-semibold text-ink">{goal.metric}</p>
<p className="text-sm text-ink-faint">{goal.target}</p>
</div>
<select
value={goal.status}
onChange={(e) => updateStatus(goal.id, e.target.value)}
className="shrink-0 rounded border border-paper-border bg-paper px-2 py-1 text-xs text-ink-faint focus:border-bronze-deep focus:outline-none"
>
{Object.entries(STATUS_CFG).map(([k, v]) => (
<option key={k} value={k}>{v.label}</option>
))}
</select>
</div>
</div>
))}
</div>
</section>
);
})}
</>
)}
</div>
);
}