feat: version 3.2.0 -- Integracion IA: configuracion y plan de actividades

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Milton Gonzalez
2026-10-23 15:55:54 -05:00
parent c64a16064f
commit 89dec6da7e
25 changed files with 538 additions and 10 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "project-linkedcorp-frontend",
"private": true,
"version": "3.1.2",
"version": "3.2.0",
"type": "module",
"scripts": {
"dev": "vite",
+4 -1
View File
@@ -2,7 +2,9 @@ import { useState } from 'react';
import { Eye, EyeOff } from 'lucide-react';
import { useUi } from '../context/ui-context.jsx';
export function PasswordInput({ value, onChange, required, autoFocus, placeholder, id }) {
// autoComplete="new-password" en claves de terceros (SMTP, IA): evita que el gestor de contraseñas
// del navegador rellene la clave de login al hacer clic y deje el formulario "con cambios".
export function PasswordInput({ value, onChange, required, autoFocus, placeholder, id, autoComplete }) {
const { t } = useUi();
const [visible, setVisible] = useState(false);
return (
@@ -16,6 +18,7 @@ export function PasswordInput({ value, onChange, required, autoFocus, placeholde
required={required}
autoFocus={autoFocus}
placeholder={placeholder}
autoComplete={autoComplete}
/>
<button
type="button"
+48
View File
@@ -6,6 +6,30 @@ export const messages = {
user_modules_hint: 'Marca los módulos que este usuario puede usar. Lo que no esté marcado no aparece en su menú y el sistema le niega el acceso.',
user_modules_saved: 'Módulos actualizados. El usuario verá el cambio al recargar.',
dashboard_no_projects_module: 'Bienvenido. Usa el menú de la izquierda para ir a los módulos que tienes habilitados.',
config_ai: 'Inteligencia artificial (IA)',
ai_not_configured: 'La IA no está configurada: carga una clave de API de Anthropic para habilitar las funciones con IA.',
ai_hint: 'La clave se guarda cifrada y nunca sale del servidor. Haiku es el modelo más económico; Sonnet da mejores resultados con mayor costo.',
ai_api_key: 'Clave de API (Anthropic)',
ai_key_configured_hint: 'Hay una clave guardada. Déjalo vacío para conservarla.',
ai_model: 'Modelo',
ai_model_haiku: 'Claude Haiku 5.5 (económico)',
ai_model_sonnet: 'Claude Sonnet 5.5 (mejor calidad)',
ai_test: 'Probar conexión',
ai_testing: 'Probando...',
ai_test_success: 'Conexión correcta con la IA',
ai_plan_button: 'Plan con IA',
ai_plan_title: 'Plan de actividades con IA',
ai_plan_hint: 'La IA propone actividades y tareas a partir del nombre, descripción y objetivo del proyecto. Puedes agregar indicaciones. Revisarás la propuesta antes de crear nada.',
ai_plan_description: 'Indicaciones (opcional)',
ai_plan_placeholder: 'Ej.: migrar 40 buzones a Microsoft 365 en 6 semanas, con capacitación a usuarios',
ai_plan_generate: 'Generar propuesta',
ai_plan_generating: 'Generando...',
ai_plan_review: 'Desmarca lo que no quieras. Las actividades se crean encadenadas desde hoy, con prioridad media; luego puedes editarlas.',
ai_plan_days: 'días',
ai_plan_apply: 'Crear seleccionadas',
ai_plan_creating: 'Creando...',
ai_plan_back: 'Volver',
ai_plan_created: 'Actividades creadas',
nav_projects: 'Proyectos',
nav_organization: 'Organizacion',
nav_config: 'Configuracion',
@@ -529,6 +553,30 @@ export const messages = {
user_modules_hint: 'Check the modules this user can use. Unchecked modules are hidden from their menu and access is denied.',
user_modules_saved: 'Modules updated. The user will see the change after reloading.',
dashboard_no_projects_module: 'Welcome. Use the menu on the left to open the modules enabled for you.',
config_ai: 'Artificial intelligence (AI)',
ai_not_configured: 'AI is not configured: add an Anthropic API key to enable AI features.',
ai_hint: 'The key is stored encrypted and never leaves the server. Haiku is the cheapest model; Sonnet gives better results at a higher cost.',
ai_api_key: 'API key (Anthropic)',
ai_key_configured_hint: 'A key is saved. Leave empty to keep it.',
ai_model: 'Model',
ai_model_haiku: 'Claude Haiku 5.5 (low cost)',
ai_model_sonnet: 'Claude Sonnet 5.5 (best quality)',
ai_test: 'Test connection',
ai_testing: 'Testing...',
ai_test_success: 'AI connection OK',
ai_plan_button: 'AI plan',
ai_plan_title: 'AI activity plan',
ai_plan_hint: 'AI proposes activities and tasks from the project name, description and objective. You can add instructions. You will review the proposal before anything is created.',
ai_plan_description: 'Instructions (optional)',
ai_plan_placeholder: 'E.g.: migrate 40 mailboxes to Microsoft 365 in 6 weeks, with user training',
ai_plan_generate: 'Generate proposal',
ai_plan_generating: 'Generating...',
ai_plan_review: 'Uncheck what you do not want. Activities are created back to back from today with medium priority; you can edit them later.',
ai_plan_days: 'days',
ai_plan_apply: 'Create selected',
ai_plan_creating: 'Creating...',
ai_plan_back: 'Back',
ai_plan_created: 'Activities created',
nav_projects: 'Projects',
nav_organization: 'Organization',
nav_config: 'Settings',
@@ -0,0 +1,78 @@
import { useState } from 'react';
import { Save, Send } from 'lucide-react';
import { useUi } from '../../context/ui-context.jsx';
import { useAsync, useAction } from '../../hooks/useAsync.js';
import { getAiConfig, updateAiConfig, testAiConfig } from '../../services/settings.js';
import { Field, FieldRow } from '../../components/Field.jsx';
import { Button } from '../../components/Button.jsx';
import { InfoBar } from '../../components/InfoBar.jsx';
import { PasswordInput } from '../../components/PasswordInput.jsx';
import { DraftNotice } from '../../components/DraftNotice.jsx';
import { useDraftForm } from '../../hooks/useDraftForm.js';
const MODEL_LABEL_KEYS = { 'claude-haiku-5-5': 'ai_model_haiku', 'claude-sonnet-5-5': 'ai_model_sonnet' };
export default function AiSettingsPanel() {
const { t, pushToast } = useUi();
const runAction = useAction();
const { data: config, reload } = useAsync(getAiConfig, []);
// La clave (apiKey) nunca se guarda como borrador.
const draft = useDraftForm({
formId: 'ai-config', entityId: 'system',
initial: config ? { model: config.model, apiKey: '', editVersion: config.edit_version } : { model: '', apiKey: '' },
label: t('config_ai'), enabled: !!config, exclude: ['apiKey'],
});
const form = draft.values;
const setForm = draft.setValues;
const [testing, setTesting] = useState(false);
const [testResult, setTestResult] = useState(null);
async function save() {
await draft.guardSave(() => runAction(async () => {
await updateAiConfig(form);
draft.clear();
await reload();
pushToast({ tone: 'success', message: t('common_saved') });
}), { fetchCurrent: async () => { const c = await getAiConfig(); return { model: c.model, apiKey: '', editVersion: c.edit_version }; } });
}
async function runTest() {
setTestResult(null);
setTesting(true);
try {
const r = await testAiConfig({ apiKey: form.apiKey, model: form.model });
setTestResult({ ok: true, message: `${t('ai_test_success')} (${r.model})` });
} catch (err) {
setTestResult({ ok: false, message: err.message });
} finally {
setTesting(false);
}
}
if (!config) return <div className="text-muted">{t('common_loading')}</div>;
return (
<div>
{!config.configured && <InfoBar tone="warning" dismissible={false}>{t('ai_not_configured')}</InfoBar>}
<div className="text-muted" style={{ fontSize: '.76rem', marginBottom: 10 }}>{t('ai_hint')}</div>
<DraftNotice draft={draft} />
<FieldRow>
<Field label={t('ai_api_key')} dirty={draft.isFieldDirty('apiKey')} hint={config.configured ? t('ai_key_configured_hint') : undefined}>
<PasswordInput value={form.apiKey} onChange={(e) => setForm((f) => ({ ...f, apiKey: e.target.value }))} placeholder="sk-ant-..." autoComplete="new-password" />
</Field>
<Field label={t('ai_model')} dirty={draft.isFieldDirty('model')}>
<select className="input" value={form.model} onChange={(e) => setForm((f) => ({ ...f, model: e.target.value }))}>
{config.models.map((m) => <option key={m} value={m}>{t(MODEL_LABEL_KEYS[m] || m)}</option>)}
</select>
</Field>
</FieldRow>
{testResult && <InfoBar tone={testResult.ok ? 'success' : 'error'}>{testResult.message}</InfoBar>}
<div style={{ display: 'flex', gap: 8 }}>
<Button variant="accent" icon={Save} onClick={save}>{t('common_save')}</Button>
<Button variant="standard" icon={Send} onClick={runTest} disabled={testing || (!form.apiKey && !config.configured)}>
{testing ? t('ai_testing') : t('ai_test')}
</Button>
</div>
</div>
);
}
@@ -1,6 +1,6 @@
import { useEffect } from 'react';
import { Navigate, useSearchParams } from 'react-router-dom';
import { Palette, ListChecks, Flag, FolderKanban, Layers, Mail, Building2, RefreshCw, Bug } from 'lucide-react';
import { Palette, ListChecks, Flag, FolderKanban, Layers, Mail, Building2, RefreshCw, Bug, Sparkles } from 'lucide-react';
import { useUi } from '../../context/ui-context.jsx';
import { useAuth } from '../../context/auth-context.jsx';
import { Expander } from '../../components/Expander.jsx';
@@ -8,6 +8,7 @@ import { Field, FieldRow } from '../../components/Field.jsx';
import { ComboBox } from '../../components/ComboBox.jsx';
import { CatalogEditor } from './CatalogEditor.jsx';
import SmtpSettingsPanel from './SmtpSettingsPanel.jsx';
import AiSettingsPanel from './AiSettingsPanel.jsx';
import CompanySettingsPanel from './CompanySettingsPanel.jsx';
import UpdaterPanel from './UpdaterPanel.jsx';
import ErrorLogsPanel from './ErrorLogsPanel.jsx';
@@ -119,6 +120,10 @@ export default function ConfiguracionPage() {
<SmtpSettingsPanel />
</Expander>
<Expander icon={Sparkles} title={t('config_ai')} draftForms={['ai-config']}>
<AiSettingsPanel />
</Expander>
<div id="updates-panel">
<Expander icon={RefreshCw} title={t('config_updater')} defaultOpen={openUpdates}>
<UpdaterPanel />
@@ -73,7 +73,7 @@ export default function SmtpSettingsPanel() {
</Field>
</FieldRow>
<Field label={t('smtp_pass')} dirty={draft.isFieldDirty('pass')} hint={config.configured ? t('smtp_pass_configured_hint') : undefined}>
<PasswordInput value={form.pass} onChange={(e) => setForm((f) => ({ ...f, pass: e.target.value }))} />
<PasswordInput value={form.pass} onChange={(e) => setForm((f) => ({ ...f, pass: e.target.value }))} autoComplete="new-password" />
</Field>
<Button variant="accent" icon={Save} onClick={save}>{t('common_save')}</Button>
@@ -0,0 +1,97 @@
import { useState } from 'react';
import { Sparkles, Check } from 'lucide-react';
import { DetailPopup } from '../../components/DetailPopup.jsx';
import { Button } from '../../components/Button.jsx';
import { Field } from '../../components/Field.jsx';
import { InfoBar } from '../../components/InfoBar.jsx';
import { useUi } from '../../context/ui-context.jsx';
import { generateProjectPlan, applyProjectPlan } from '../../services/ai.js';
// Plan de actividades sugerido por IA: el usuario describe, revisa la propuesta, desmarca lo que
// no quiere y recien ahi se crean (la IA solo sugiere, nunca guarda sola).
export function AiPlanDialog({ open, projectId, onClose, onCreated }) {
const { t, lang, pushToast } = useUi();
const [description, setDescription] = useState('');
const [plan, setPlan] = useState(null);
const [selected, setSelected] = useState([]);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
function close() {
setPlan(null); setSelected([]); setError(''); setDescription('');
onClose();
}
async function generate() {
setBusy(true); setError('');
try {
const r = await generateProjectPlan(projectId, { description, lang });
setPlan(r.activities);
setSelected(r.activities.map((_, i) => i));
} catch (err) {
setError(err.message);
} finally {
setBusy(false);
}
}
async function apply() {
setBusy(true); setError('');
try {
const r = await applyProjectPlan(projectId, plan.filter((_, i) => selected.includes(i)));
pushToast({ tone: 'success', message: `${t('ai_plan_created')}: ${r.created}` });
onCreated();
close();
} catch (err) {
setError(err.message);
} finally {
setBusy(false);
}
}
const toggle = (i) => setSelected((s) => (s.includes(i) ? s.filter((x) => x !== i) : [...s, i]));
return (
<DetailPopup open={open} title={t('ai_plan_title')} onClose={busy ? () => {} : close} width={720} height={620}>
{error && <InfoBar tone="error">{error}</InfoBar>}
{!plan ? (
<>
<p className="text-muted" style={{ marginTop: 0 }}>{t('ai_plan_hint')}</p>
<Field label={t('ai_plan_description')}>
<textarea className="input" rows={5} value={description} onChange={(e) => setDescription(e.target.value)} placeholder={t('ai_plan_placeholder')} />
</Field>
<div style={{ display: 'flex', gap: 8 }}>
<Button variant="accent" icon={Sparkles} onClick={generate} disabled={busy}>{busy ? t('ai_plan_generating') : t('ai_plan_generate')}</Button>
<Button variant="standard" onClick={close} disabled={busy}>{t('common_cancel')}</Button>
</div>
</>
) : (
<>
<p className="text-muted" style={{ marginTop: 0 }}>{t('ai_plan_review')}</p>
<div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 16 }}>
{plan.map((a, i) => (
<label key={i} className="panel-card" style={{ display: 'flex', gap: 10, alignItems: 'flex-start', margin: 0 }}>
<input type="checkbox" checked={selected.includes(i)} onChange={() => toggle(i)} style={{ marginTop: 4 }} />
<div>
<strong>{a.name}</strong> <span className="text-muted">· {a.durationDays} {t('ai_plan_days')}</span>
{a.description && <div className="text-muted" style={{ fontSize: '.8rem' }}>{a.description}</div>}
{a.tasks.length > 0 && (
<ul style={{ margin: '4px 0 0', paddingLeft: 18, fontSize: '.82rem' }}>
{a.tasks.map((task, j) => <li key={j}>{task}</li>)}
</ul>
)}
</div>
</label>
))}
</div>
<div style={{ display: 'flex', gap: 8 }}>
<Button variant="accent" icon={Check} onClick={apply} disabled={busy || !selected.length}>
{busy ? t('ai_plan_creating') : `${t('ai_plan_apply')} (${selected.length})`}
</Button>
<Button variant="standard" onClick={() => setPlan(null)} disabled={busy}>{t('ai_plan_back')}</Button>
</div>
</>
)}
</DetailPopup>
);
}
@@ -1,6 +1,6 @@
import { useEffect, useRef, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Plus, Save, Trash2, ArrowRightLeft, FolderUp, Archive, RotateCcw } from 'lucide-react';
import { Plus, Save, Trash2, ArrowRightLeft, FolderUp, Archive, RotateCcw, Sparkles } from 'lucide-react';
import { useUi } from '../../context/ui-context.jsx';
import { useAuth } from '../../context/auth-context.jsx';
import { useAsync, useAction } from '../../hooks/useAsync.js';
@@ -20,6 +20,8 @@ import { StatusBadge, ProgressBar, DueBadge } from '../../components/StatusBadge
import { dueStatus } from '../../utils/dueStatus.js';
import { DetailPopup } from '../../components/DetailPopup.jsx';
import ActivityDetailPanel from './ActivityDetailPanel.jsx';
import { AiPlanDialog } from './AiPlanDialog.jsx';
import { getAiStatus } from '../../services/ai.js';
import { DraftNotice } from '../../components/DraftNotice.jsx';
import { DraftMark, useGuardedClose } from '../../components/NavigationGuard.jsx';
import { useDraftForm, useUserDrafts, hasDraftFor } from '../../hooks/useDraftForm.js';
@@ -32,6 +34,9 @@ export default function ProjectActivitiesTab({ project, projectId }) {
const navigate = useNavigate();
const runAction = useAction();
const { data: activities, reload } = useAsync(() => listActivitiesByProject(projectId), [projectId]);
// Boton de IA solo si el superadmin configuro la clave; el backend valida permisos al usarlo.
const { data: aiStatus } = useAsync(() => getAiStatus().catch(() => ({ enabled: false })), []);
const [aiPlanOpen, setAiPlanOpen] = useState(false);
const [trashOpen, setTrashOpen] = useState(false);
const { data: trashed, reload: reloadTrash } = useAsync(
() => (trashOpen ? listActivitiesTrash(projectId) : Promise.resolve([])),
@@ -272,9 +277,14 @@ export default function ProjectActivitiesTab({ project, projectId }) {
{project?.isOwner && (
<Button variant="standard" icon={Archive} onClick={() => setTrashOpen(true)}>{t('activities_trash')}</Button>
)}
{aiStatus?.enabled && (
<Button variant="standard" icon={Sparkles} onClick={() => setAiPlanOpen(true)}>{t('ai_plan_button')}</Button>
)}
<Button variant="accent" icon={Plus} onClick={() => setCreating(true)}>{t('activity_new')}{pendingNew && !creating && <DraftMark />}</Button>
</div>
<AiPlanDialog open={aiPlanOpen} projectId={projectId} onClose={() => setAiPlanOpen(false)} onCreated={reload} />
<DetailPopup open={trashOpen} title={t('activities_trash')} onClose={() => setTrashOpen(false)} width={480} height={420}>
{(trashed || []).length === 0 && <div className="text-muted" style={{ fontSize: '.82rem' }}>{t('activities_trash_empty')}</div>}
{(trashed || []).map((a) => (
+5
View File
@@ -0,0 +1,5 @@
import { api } from './api.js';
export const getAiStatus = () => api.get('/ai/status');
export const generateProjectPlan = (projectId, data) => api.post(`/ai/projects/${projectId}/plan`, data);
export const applyProjectPlan = (projectId, activities) => api.post(`/ai/projects/${projectId}/plan/apply`, { activities });
+3
View File
@@ -3,3 +3,6 @@ import { api } from './api.js';
export const getSmtpConfig = () => api.get('/settings/smtp');
export const updateSmtpConfig = (data) => api.put('/settings/smtp', data);
export const testSmtpConfig = (data) => api.post('/settings/smtp/test', data);
export const getAiConfig = () => api.get('/settings/ai');
export const updateAiConfig = (data) => api.put('/settings/ai', data);
export const testAiConfig = (data) => api.post('/settings/ai/test', data);