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'; 'use client';
import { useState } from 'react'; import { useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { zodResolver } from '@hookform/resolvers/zod'; import { apiFetch } from '../../../lib/api';
import { useForm } from 'react-hook-form'; import type { Goal } from '../../../lib/api';
import { z } from 'zod';
import { apiFetch, type Goal, type GoalStatus } from '../../../lib/api';
import { useSession } from '../../../components/session-provider'; import { useSession } from '../../../components/session-provider';
const GOAL_STATUS_LABELS: Record<GoalStatus, string> = { const STATUS_CFG = {
not_started: 'Neînceput', not_started: { label: 'Neînceput', cls: 'bg-paper-sunken text-ink-faint' },
on_track: 'Pe track', on_track: { label: 'Pe plan', cls: 'bg-signal-ok/10 text-signal-ok' },
at_risk: 'La risc', at_risk: { label: 'La risc', cls: 'bg-signal-warn/10 text-signal-warn' },
achieved: 'Atins', achieved: { label: 'Realizat', cls: 'bg-signal-ok/20 text-signal-ok font-semibold' },
abandoned: 'Abandonat', abandoned: { label: 'Abandonat', cls: 'bg-paper-sunken text-ink-line line-through' },
}; } as const;
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>;
export default function GoalsPage() { export default function GoalsPage() {
const { activeTenant } = useSession(); const { activeTenant } = useSession();
const tenantId = activeTenant?.tenantId ?? ''; const tenantId = activeTenant?.tenantId ?? '';
const queryClient = useQueryClient();
const [isFormOpen, setIsFormOpen] = useState(false);
const [statusFilter, setStatusFilter] = useState<GoalStatus | ''>('');
const { data: goals = [], isLoading } = useQuery({ const { data: goals = [], isLoading, refetch } = useQuery({
queryKey: ['goals', tenantId, statusFilter], queryKey: ['goals', tenantId],
queryFn: () => queryFn: () => apiFetch<Goal[]>('/v1/goals', { tenantId }),
apiFetch<Goal[]>(
`/v1/goals${statusFilter ? `?status=${statusFilter}` : ''}`,
{ tenantId },
),
enabled: Boolean(tenantId), enabled: Boolean(tenantId),
}); });
const { register, handleSubmit, reset, formState: { errors, isSubmitting } } = useForm<CreateGoalForm>({ const [showForm, setShowForm] = useState(false);
resolver: zodResolver(createGoalSchema), const [form, setForm] = useState({ horizon: '', metric: '', target: '' });
}); const [saving, setSaving] = useState(false);
const createGoal = useMutation({ const byStatus = {
mutationFn: (values: CreateGoalForm) => at_risk: goals.filter((g) => g.status === 'at_risk'),
apiFetch<Goal>('/v1/goals', { method: 'POST', tenantId, body: values }), on_track: goals.filter((g) => g.status === 'on_track'),
onSuccess: async () => { not_started: goals.filter((g) => g.status === 'not_started'),
await queryClient.invalidateQueries({ queryKey: ['goals', tenantId] }); achieved: goals.filter((g) => g.status === 'achieved'),
reset(); abandoned: goals.filter((g) => g.status === 'abandoned'),
setIsFormOpen(false); };
},
});
const updateStatus = useMutation({ async function handleCreate(e: React.FormEvent) {
mutationFn: ({ id, status }: { id: string; status: GoalStatus }) => e.preventDefault();
apiFetch<Goal>(`/v1/goals/${id}`, { method: 'PATCH', tenantId, body: { status } }), if (!form.horizon || !form.metric || !form.target) return;
onSuccess: async () => { setSaving(true);
await queryClient.invalidateQueries({ queryKey: ['goals', tenantId] }); await apiFetch('/v1/goals', { tenantId, method: 'POST', body: form });
}, setForm({ horizon: '', metric: '', target: '' });
}); setShowForm(false);
setSaving(false);
refetch();
}
const deleteGoal = useMutation({ async function updateStatus(id: string, status: string) {
mutationFn: (id: string) => await apiFetch(`/v1/goals/${id}`, { tenantId, method: 'PATCH', body: { status } });
apiFetch<{ deleted: boolean }>(`/v1/goals/${id}`, { method: 'DELETE', tenantId }), refetch();
onSuccess: async () => { }
await queryClient.invalidateQueries({ queryKey: ['goals', tenantId] });
},
});
return ( return (
<div className="max-w-3xl"> <div className="max-w-5xl space-y-6">
<div className="mb-6 flex items-center justify-between"> <div className="flex items-start justify-between">
<div> <div>
<h1 className="font-display text-2xl font-semibold text-ink">Obiective</h1> <h1 className="font-display text-2xl font-semibold text-ink">Obiective & OKR</h1>
<p className="text-sm text-ink-faint">Obiectivele strategice urmărite în acest workspace.</p> <p className="mt-1 text-sm text-ink-faint">
Urmărire obiective pe orizont de timp: lunar, trimestrial, anual.
</p>
</div> </div>
<button type="button" className="btn-primary" onClick={() => setIsFormOpen((v) => !v)}> <button
{isFormOpen ? 'Anulează' : 'Obiectiv nou'} 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> </button>
</div> </div>
{isFormOpen && ( {showForm && (
<form <form onSubmit={handleCreate} className="card p-5 space-y-4">
onSubmit={handleSubmit((values) => createGoal.mutate(values))} <h2 className="text-sm font-semibold text-ink">Obiectiv nou</h2>
noValidate <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
className="card mb-6 space-y-4 p-5" <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 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"
> >
<div> {saving ? 'Se salvează…' : 'Salvează'}
<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>}
</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>
<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> </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>
</form> </form>
)} )}
<div className="mb-4 flex flex-wrap gap-2"> {isLoading ? (
<button <p className="text-sm text-ink-faint">Se încarcă…</p>
type="button" ) : goals.length === 0 ? (
onClick={() => setStatusFilter('')} <div className="card p-12 text-center">
className={`rounded-full px-3 py-1 text-xs font-medium transition-colors ${ <p className="font-semibold text-ink">Niciun obiectiv definit</p>
statusFilter === '' ? 'bg-ink text-paper' : 'bg-paper-sunken text-ink-soft hover:text-ink' <p className="mt-1 text-sm text-ink-faint">Adaugă primul obiectiv pentru a urmări progresul companiei.</p>
}`} </div>
> ) : (
Toate <>
</button> {/* Summary stats */}
{(Object.keys(GOAL_STATUS_LABELS) as GoalStatus[]).map((status) => ( <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
<button {(Object.keys(STATUS_CFG) as (keyof typeof STATUS_CFG)[]).map((s) => (
key={status} <div key={s} className="card p-4">
type="button" <p className="text-xs text-ink-faint">{STATUS_CFG[s].label}</p>
onClick={() => setStatusFilter(status)} <p className="mt-1 font-display text-3xl font-semibold text-ink">{byStatus[s].length}</p>
className={`rounded-full px-3 py-1 text-xs font-medium transition-colors ${ </div>
statusFilter === status ? 'bg-ink text-paper' : 'bg-paper-sunken text-ink-soft hover:text-ink'
}`}
>
{GOAL_STATUS_LABELS[status]}
</button>
))} ))}
<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>
</div> </div>
{isLoading && <p className="text-sm text-ink-faint">Se încarcă…</p>} {/* Goals grouped by status */}
{!isLoading && goals.length === 0 && ( {(['at_risk', 'on_track', 'not_started', 'achieved', 'abandoned'] as const).map((s) => {
<p className="card p-6 text-sm text-ink-faint"> const group = byStatus[s];
{statusFilter if (group.length === 0) return null;
? `Niciun obiectiv cu statusul "${GOAL_STATUS_LABELS[statusFilter]}".` return (
: 'Niciun obiectiv încă. Adaugă primul mai sus.'} <section key={s} className="space-y-2">
</p> <h2 className="text-xs font-semibold uppercase tracking-wider text-ink-faint">
)} {STATUS_CFG[s].label} ({group.length})
</h2>
<ul className="space-y-3"> <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
{goals.map((goal) => ( {group.map((goal) => (
<li key={goal.id} className="card p-4"> <div key={goal.id} className="card p-5">
<div className="flex items-start justify-between gap-4"> <div className="flex items-start justify-between gap-3">
<div className="flex-1 min-w-0"> <div className="min-w-0 flex-1">
<p className="text-[11px] font-medium uppercase tracking-wider text-ink-faint">{goal.horizon}</p> <div className="flex flex-wrap items-center gap-2">
<p className="mt-0.5 text-sm font-medium text-ink truncate">{goal.metric}</p> <span className="rounded-full bg-paper-sunken px-2 py-0.5 font-mono text-[11px] text-ink-faint">
<p className="mt-0.5 text-sm text-ink-soft">{goal.target}</p> {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> </div>
<div className="flex items-center gap-2 shrink-0">
<select <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} value={goal.status}
onChange={(e) => onChange={(e) => updateStatus(goal.id, e.target.value)}
updateStatus.mutate({ id: goal.id, status: e.target.value as GoalStatus }) 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(GOAL_STATUS_LABELS) as [GoalStatus, string][]).map(([value, label]) => ( {Object.entries(STATUS_CFG).map(([k, v]) => (
<option key={value} value={value}>{label}</option> <option key={k} value={k}>{v.label}</option>
))} ))}
</select> </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>
</div> </div>
</div> </div>
</li>
))} ))}
</ul> </div>
</section>
);
})}
</>
)}
</div> </div>
); );
} }