CheckPoint: Avances Varios

This commit is contained in:
2025-12-18 13:32:50 -03:00
parent 8f535f3a6e
commit 32663e6324
92 changed files with 12629 additions and 195 deletions

View File

@@ -5,6 +5,9 @@ import ProtectedLayout from './layouts/ProtectedLayout';
import CategoryManager from './pages/Categories/CategoryManager';
import UserManager from './pages/Users/UserManager';
import DiagramPage from './pages/Diagram/DiagramPage';
import PricingManager from './pages/Pricing/PricingManager';
import PromotionsManager from './pages/Pricing/PromotionsManager';
function App() {
return (
@@ -16,6 +19,9 @@ function App() {
<Route path="/" element={<Dashboard />} />
<Route path="/categories" element={<CategoryManager />} />
<Route path="/users" element={<UserManager />} />
<Route path="/diagram" element={<DiagramPage />} />
<Route path="/pricing" element={<PricingManager />} />
<Route path="/promotions" element={<PromotionsManager />} />
</Route>
</Routes>
</BrowserRouter>

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

Before

Width:  |  Height:  |  Size: 4.0 KiB

View File

@@ -1,3 +1,5 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@import "tailwindcss";
@theme {
/* Aquí puedes definir tus variables si las necesitas */
}

View File

@@ -1,6 +1,6 @@
import { Navigate, Outlet } from 'react-router-dom';
import { useAuthStore } from '../store/authStore';
import { LogOut } from 'lucide-react';
import { LogOut, LayoutDashboard, FolderTree, Users, FileText, DollarSign, Percent } from 'lucide-react';
export default function ProtectedLayout() {
const { isAuthenticated, logout } = useAuthStore();
@@ -11,28 +11,58 @@ export default function ProtectedLayout() {
return (
<div className="min-h-screen bg-gray-100 flex">
{/* Sidebar minimalista por ahora */}
<aside className="w-64 bg-gray-900 text-white flex flex-col">
<div className="p-4 text-xl font-bold border-b border-gray-800">
{/* Sidebar */}
<aside className="w-64 bg-gray-900 text-white flex flex-col transition-all duration-300">
<div className="p-4 text-xl font-bold border-b border-gray-800 flex items-center gap-2">
<LayoutDashboard className="text-blue-500" />
SIG-CM
</div>
<nav className="flex-1 p-4">
<ul>
<li className="mb-2">
<a href="/" className="block p-2 hover:bg-gray-800 rounded">Dashboard</a>
<ul className="space-y-1">
<li>
<a href="/" className="flex items-center gap-3 p-3 hover:bg-gray-800 rounded transition-colors text-gray-300 hover:text-white">
<LayoutDashboard size={20} />
<span>Dashboard</span>
</a>
</li>
<li className="mb-2">
<a href="/categories" className="block p-2 hover:bg-gray-800 rounded">Categorías</a>
<li>
<a href="/categories" className="flex items-center gap-3 p-3 hover:bg-gray-800 rounded transition-colors text-gray-300 hover:text-white">
<FolderTree size={20} />
<span>Categorías</span>
</a>
</li>
<li className="mb-2">
<a href="/users" className="block p-2 hover:bg-gray-800 rounded">Usuarios</a>
<li>
<a href="/users" className="flex items-center gap-3 p-3 hover:bg-gray-800 rounded transition-colors text-gray-300 hover:text-white">
<Users size={20} />
<span>Usuarios</span>
</a>
</li>
<li>
<a href="/pricing" className="flex items-center gap-3 p-3 hover:bg-gray-800 rounded transition-colors text-gray-300 hover:text-white">
<DollarSign size={20} />
<span>Tarifas y Reglas</span>
</a>
</li>
<li>
<a href="/promotions" className="flex items-center gap-3 p-3 hover:bg-gray-800 rounded transition-colors text-gray-300 hover:text-white">
<Percent size={20} />
<span>Promociones</span>
</a>
</li>
<li>
<a href="/diagram" className="flex items-center gap-3 p-3 hover:bg-gray-800 rounded transition-colors text-gray-300 hover:text-white">
<FileText size={20} />
<span>Diagramación</span>
</a>
</li>
</ul>
</nav>
<div className="p-4 border-t border-gray-800">
<button
onClick={logout}
className="flex items-center gap-2 text-gray-400 hover:text-white w-full"
className="flex items-center gap-3 text-red-400 hover:text-red-300 w-full p-2 transition-colors"
>
<LogOut size={20} />
<span>Cerrar Sesión</span>
@@ -41,9 +71,9 @@ export default function ProtectedLayout() {
</aside>
{/* Main Content */}
<main className="flex-1 p-8">
<main className="flex-1 p-8 overflow-y-auto">
<Outlet />
</main>
</div>
);
}
}

View File

@@ -1,12 +1,14 @@
import { useState, useEffect } from 'react';
import { Category } from '../../types/Category';
import OperationManager from './OperationManager'; // Import added
import { type Category } from '../../types/Category';
import OperationManager from './OperationManager';
import { categoryService } from '../../services/categoryService';
import { attributeService } from '../../services/attributeService';
import { type AttributeDefinition } from '../../types/AttributeDefinition';
import Modal from '../../components/Modal';
import { Plus, Edit, Trash2, ChevronRight, ChevronDown, Folder, FolderOpen, Settings } from 'lucide-react';
import { Plus, Edit, Trash2, ChevronRight, ChevronDown, Folder, FolderOpen, Settings, LayoutList } from 'lucide-react';
import clsx from 'clsx';
import { operationService } from '../../services/operationService';
import { Operation } from '../../types/Operation';
import { type Operation } from '../../types/Operation';
// Type helper for the tree structure
interface CategoryNode extends Category {
@@ -23,12 +25,21 @@ export default function CategoryManager() {
const [editingCategory, setEditingCategory] = useState<Category | null>(null);
const [formData, setFormData] = useState<Partial<Category>>({ name: '', slug: '', active: true, parentId: null });
// New state for operations matrix
// State for operations matrix
const [selectedCategoryOps, setSelectedCategoryOps] = useState<Operation[]>([]);
const [allOperations, setAllOperations] = useState<Operation[]>([]);
const [configuringCategory, setConfiguringCategory] = useState<Category | null>(null);
const [isOpsModalOpen, setIsOpsModalOpen] = useState(false);
// State for Attributes (ESTO FALTABA)
const [isAttrModalOpen, setIsAttrModalOpen] = useState(false);
const [attributes, setAttributes] = useState<AttributeDefinition[]>([]);
const [newAttrData, setNewAttrData] = useState({
name: '',
dataType: 'text',
required: false
});
useEffect(() => {
loadCategories();
}, []);
@@ -126,7 +137,8 @@ export default function CategoryManager() {
try {
await attributeService.create({
...newAttrData,
categoryId: configuringCategory.id
categoryId: configuringCategory.id,
dataType: newAttrData.dataType as any // Type assertion for simplicity
});
setNewAttrData({ name: '', dataType: 'text', required: false });
loadAttributes(configuringCategory.id);
@@ -357,7 +369,76 @@ export default function CategoryManager() {
</div>
</div>
</Modal>
{/* Attributes Configuration Modal (ESTO FALTABA EN EL JSX) */}
<Modal
isOpen={isAttrModalOpen}
onClose={() => setIsAttrModalOpen(false)}
title={`Atributos de: ${configuringCategory?.name}`}
>
<div className="space-y-6">
{/* List Existing Attributes */}
<div>
<h4 className="font-semibold mb-2 text-sm text-gray-700">Atributos Actuales</h4>
{attributes.length === 0 ? (
<p className="text-sm text-gray-400 italic">No hay atributos definidos.</p>
) : (
<div className="space-y-2">
{attributes.map(attr => (
<div key={attr.id} className="flex items-center justify-between bg-gray-50 p-2 rounded border">
<div className="text-sm">
<span className="font-medium">{attr.name}</span>
<span className="text-gray-500 ml-2 text-xs">({attr.dataType})</span>
{attr.required && <span className="text-red-500 ml-1 text-xs">*Req</span>}
</div>
<button onClick={() => handleDeleteAttribute(attr.id)} className="text-red-500 hover:text-red-700">
<Trash2 size={16} />
</button>
</div>
))}
</div>
)}
</div>
{/* Add New Attribute Form */}
<form onSubmit={handleCreateAttribute} className="border-t pt-4">
<h4 className="font-semibold mb-3 text-sm text-gray-700">Agregar Atributo</h4>
<div className="flex gap-2 mb-2">
<input
type="text"
placeholder="Nombre (ej: Kilometraje)"
className="flex-1 border p-2 rounded text-sm"
value={newAttrData.name}
onChange={e => setNewAttrData({ ...newAttrData, name: e.target.value })}
required
/>
<select
className="border p-2 rounded text-sm"
value={newAttrData.dataType}
onChange={e => setNewAttrData({ ...newAttrData, dataType: e.target.value })}
>
<option value="text">Texto</option>
<option value="number">Número</option>
<option value="boolean">Si/No</option>
<option value="date">Fecha</option>
</select>
</div>
<div className="flex items-center justify-between">
<label className="flex items-center gap-2 text-sm text-gray-600">
<input
type="checkbox"
checked={newAttrData.required}
onChange={e => setNewAttrData({ ...newAttrData, required: e.target.checked })}
/>
Es obligatorio
</label>
<button type="submit" className="bg-green-600 text-white px-3 py-1.5 rounded text-sm hover:bg-green-700 flex items-center gap-1">
<Plus size={16} /> Agregar
</button>
</div>
</form>
</div>
</Modal>
</div>
);
}
}

View File

@@ -1,5 +1,5 @@
import { useState, useEffect } from 'react';
import { type Operation } from '../../types/Operation'; // ID: type-import-fix
import { type Operation } from '../../types/Operation';
import { operationService } from '../../services/operationService';
import { Plus, Trash2 } from 'lucide-react';

View File

@@ -0,0 +1,72 @@
import { useState } from 'react';
import { exportService } from '../../services/exportService';
import { FileText, Download, Calendar } from 'lucide-react';
export default function DiagramPage() {
// Fecha por defecto: Mañana
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
const [date, setDate] = useState(tomorrow.toISOString().split('T')[0]);
const [loading, setLoading] = useState(false);
const handleDownload = async () => {
setLoading(true);
try {
await exportService.downloadDiagram(date);
} catch (error) {
console.error(error);
alert('Error descargando el diagrama');
} finally {
setLoading(false);
}
};
return (
<div className="max-w-4xl mx-auto">
<h2 className="text-2xl font-bold text-gray-800 mb-6 flex items-center gap-2">
<FileText className="text-blue-600" />
Módulo de Diagramación
</h2>
<div className="bg-white rounded-lg shadow-sm border border-gray-200 p-8">
<p className="text-gray-600 mb-6">
Seleccione la fecha de edición para generar el archivo XML de exportación.
Este archivo contiene todos los avisos activos para el día seleccionado, agrupados por rubro.
</p>
<div className="flex items-end gap-4 max-w-md">
<div className="flex-1">
<label className="block text-sm font-medium text-gray-700 mb-1">
Fecha de Edición
</label>
<div className="relative">
<input
type="date"
value={date}
onChange={(e) => setDate(e.target.value)}
className="w-full p-3 pl-10 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none"
/>
<Calendar className="absolute left-3 top-3.5 text-gray-400" size={18} />
</div>
</div>
<button
onClick={handleDownload}
disabled={loading}
className="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 disabled:bg-blue-300 transition flex items-center gap-2 font-medium"
>
{loading ? 'Generando...' : (
<>
<Download size={20} /> Descargar XML
</>
)}
</button>
</div>
<div className="mt-8 p-4 bg-yellow-50 border border-yellow-100 rounded-md text-sm text-yellow-800">
<strong>Nota:</strong> Solo se exportarán los avisos que tengan texto de impresión definido y cuyo rango de fechas cubra el día seleccionado.
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,142 @@
import { useState, useEffect } from 'react';
import api from '../../services/api';
import { Save, DollarSign } from 'lucide-react';
interface PricingConfig {
basePrice: number;
baseWordCount: number;
extraWordPrice: number;
specialChars: string;
specialCharPrice: number;
boldSurcharge: number;
frameSurcharge: number;
}
interface Category { id: number; name: string; }
export default function PricingManager() {
const [categories, setCategories] = useState<Category[]>([]);
const [selectedCat, setSelectedCat] = useState<number | null>(null);
const [config, setConfig] = useState<PricingConfig>({
basePrice: 0, baseWordCount: 15, extraWordPrice: 0,
specialChars: '!', specialCharPrice: 0, boldSurcharge: 0, frameSurcharge: 0
});
const [loading, setLoading] = useState(false);
useEffect(() => {
// Cargar categorías
api.get('/categories').then(res => setCategories(res.data));
}, []);
useEffect(() => {
if (selectedCat) {
// Cargar config existente
api.get(`/pricing/${selectedCat}`).then(res => {
if (res.data) setConfig(res.data);
else setConfig({ // Default si no existe
basePrice: 0, baseWordCount: 15, extraWordPrice: 0,
specialChars: '!', specialCharPrice: 0, boldSurcharge: 0, frameSurcharge: 0
});
});
}
}, [selectedCat]);
const handleSave = async () => {
if (!selectedCat) return;
setLoading(true);
try {
await api.post('/pricing', { ...config, categoryId: selectedCat });
alert('Configuración guardada correctamente.');
} catch (e) {
alert('Error al guardar.');
} finally {
setLoading(false);
}
};
return (
<div className="max-w-4xl mx-auto">
<h2 className="text-2xl font-bold mb-6 flex items-center gap-2">
<DollarSign className="text-green-600" />
Gestor de Tarifas y Reglas
</h2>
<div className="bg-white p-6 rounded shadow mb-6">
<label className="block text-sm font-medium mb-2">Seleccionar Rubro a Configurar</label>
<select
className="w-full border p-2 rounded"
onChange={e => setSelectedCat(Number(e.target.value))}
value={selectedCat || ''}
>
<option value="">-- Seleccione --</option>
{categories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
</select>
</div>
{selectedCat && (
<div className="bg-white p-6 rounded shadow border border-gray-200">
<h3 className="font-bold text-lg mb-4 border-b pb-2">Reglas de Precio</h3>
<div className="grid grid-cols-2 gap-6">
{/* Tarifa Base */}
<div className="space-y-4">
<h4 className="font-semibold text-blue-600">Base</h4>
<div>
<label className="block text-sm text-gray-600">Precio Mínimo ($)</label>
<input type="number" className="border p-2 rounded w-full"
value={config.basePrice} onChange={e => setConfig({ ...config, basePrice: parseFloat(e.target.value) })} />
</div>
<div>
<label className="block text-sm text-gray-600">Palabras Incluidas (Cant.)</label>
<input type="number" className="border p-2 rounded w-full"
value={config.baseWordCount} onChange={e => setConfig({ ...config, baseWordCount: parseInt(e.target.value) })} />
</div>
<div>
<label className="block text-sm text-gray-600">Costo Palabra Extra ($)</label>
<input type="number" className="border p-2 rounded w-full"
value={config.extraWordPrice} onChange={e => setConfig({ ...config, extraWordPrice: parseFloat(e.target.value) })} />
</div>
</div>
{/* Extras y Estilos */}
<div className="space-y-4">
<h4 className="font-semibold text-purple-600">Extras y Recargos</h4>
<div>
<label className="block text-sm text-gray-600">Caracteres Especiales (ej: !$%)</label>
<input type="text" className="border p-2 rounded w-full"
value={config.specialChars} onChange={e => setConfig({ ...config, specialChars: e.target.value })} />
</div>
<div>
<label className="block text-sm text-gray-600">Costo por Caracter Especial ($)</label>
<input type="number" className="border p-2 rounded w-full"
value={config.specialCharPrice} onChange={e => setConfig({ ...config, specialCharPrice: parseFloat(e.target.value) })} />
</div>
<div className="grid grid-cols-2 gap-2">
<div>
<label className="block text-sm text-gray-600">Recargo Negrita ($)</label>
<input type="number" className="border p-2 rounded w-full"
value={config.boldSurcharge} onChange={e => setConfig({ ...config, boldSurcharge: parseFloat(e.target.value) })} />
</div>
<div>
<label className="block text-sm text-gray-600">Recargo Recuadro ($)</label>
<input type="number" className="border p-2 rounded w-full"
value={config.frameSurcharge} onChange={e => setConfig({ ...config, frameSurcharge: parseFloat(e.target.value) })} />
</div>
</div>
</div>
</div>
<div className="mt-8 flex justify-end">
<button
onClick={handleSave}
disabled={loading}
className="bg-blue-600 text-white px-6 py-2 rounded hover:bg-blue-700 flex items-center gap-2"
>
<Save size={18} /> Guardar Configuración
</button>
</div>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,232 @@
import { useState, useEffect } from 'react';
import api from '../../services/api';
import Modal from '../../components/Modal';
import { Percent, Trash2, Plus, Edit, CalendarClock } from 'lucide-react';
interface Promotion {
id: number;
name: string;
categoryId: number | null;
minDays: number;
daysOfWeek: string; // "0,6" (Domingo, Sabado)
discountPercentage: number;
discountFixedAmount: number;
isActive: boolean;
}
interface Category { id: number; name: string; }
export default function PromotionsManager() {
const [promotions, setPromotions] = useState<Promotion[]>([]);
const [categories, setCategories] = useState<Category[]>([]);
const [isModalOpen, setIsModalOpen] = useState(false);
const [editingId, setEditingId] = useState<number | null>(null);
const [formData, setFormData] = useState<Partial<Promotion>>({
name: '', categoryId: null, minDays: 0, daysOfWeek: '',
discountPercentage: 0, discountFixedAmount: 0, isActive: true
});
// Helper para días de la semana
const daysOptions = [
{ val: 1, label: 'Lun' }, { val: 2, label: 'Mar' }, { val: 3, label: 'Mié' },
{ val: 4, label: 'Jue' }, { val: 5, label: 'Vie' }, { val: 6, label: 'Sáb' }, { val: 0, label: 'Dom' }
];
useEffect(() => {
loadData();
}, []);
const loadData = async () => {
const [promosRes, catRes] = await Promise.all([
api.get('/pricing/promotions'),
api.get('/categories')
]);
setPromotions(promosRes.data);
setCategories(catRes.data);
};
const handleEdit = (promo: Promotion) => {
setEditingId(promo.id);
setFormData(promo);
setIsModalOpen(true);
};
const handleCreate = () => {
setEditingId(null);
setFormData({
name: '', categoryId: null, minDays: 0, daysOfWeek: '',
discountPercentage: 0, discountFixedAmount: 0, isActive: true
});
setIsModalOpen(true);
};
const handleDelete = async (id: number) => {
if (!confirm("¿Eliminar promoción?")) return;
await api.delete(`/pricing/promotions/${id}`);
loadData();
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
// Convertir categoryId 0 a null para el backend
const payload = {
...formData,
categoryId: formData.categoryId === 0 ? null : formData.categoryId
};
try {
if (editingId) {
await api.put(`/pricing/promotions/${editingId}`, payload);
} else {
await api.post('/pricing/promotions', payload);
}
setIsModalOpen(false);
loadData();
} catch (e) {
alert("Error al guardar");
}
};
const toggleDay = (dayVal: number) => {
const current = formData.daysOfWeek ? formData.daysOfWeek.split(',').map(Number) : [];
let newDays;
if (current.includes(dayVal)) {
newDays = current.filter(d => d !== dayVal);
} else {
newDays = [...current, dayVal];
}
setFormData({ ...formData, daysOfWeek: newDays.join(',') });
};
return (
<div className="max-w-6xl mx-auto">
<div className="flex justify-between items-center mb-6">
<h2 className="text-2xl font-bold flex items-center gap-2 text-gray-800">
<Percent className="text-orange-500" />
Gestión de Promociones
</h2>
<button onClick={handleCreate} className="bg-blue-600 text-white px-4 py-2 rounded flex items-center gap-2 hover:bg-blue-700">
<Plus size={18} /> Nueva Promo
</button>
</div>
<div className="bg-white rounded shadow overflow-hidden">
<table className="w-full text-left">
<thead className="bg-gray-50 border-b">
<tr>
<th className="p-4">Nombre</th>
<th className="p-4">Rubro</th>
<th className="p-4">Condición Días</th>
<th className="p-4">Descuento</th>
<th className="p-4">Estado</th>
<th className="p-4 text-right">Acciones</th>
</tr>
</thead>
<tbody>
{promotions.map(p => (
<tr key={p.id} className="border-b hover:bg-gray-50">
<td className="p-4 font-medium">{p.name}</td>
<td className="p-4 text-sm text-gray-600">
{p.categoryId ? categories.find(c => c.id === p.categoryId)?.name : 'Todos'}
</td>
<td className="p-4 text-sm">
{p.minDays > 0 ? `Mínimo ${p.minDays} días` : 'Sin mínimo'}
{p.daysOfWeek && (
<div className="text-xs text-gray-500 mt-1 flex gap-1">
<CalendarClock size={12} />
{p.daysOfWeek.split(',').map(d => daysOptions.find(o => o.val === Number(d))?.label).join(', ')}
</div>
)}
</td>
<td className="p-4 font-bold text-green-600">
{p.discountPercentage > 0 ? `-${p.discountPercentage}%` : `-$${p.discountFixedAmount}`}
</td>
<td className="p-4">
<span className={`px-2 py-1 rounded text-xs ${p.isActive ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
{p.isActive ? 'Activa' : 'Inactiva'}
</span>
</td>
<td className="p-4 text-right">
<button onClick={() => handleEdit(p)} className="text-blue-600 p-2"><Edit size={18} /></button>
<button onClick={() => handleDelete(p.id)} className="text-red-600 p-2"><Trash2 size={18} /></button>
</td>
</tr>
))}
</tbody>
</table>
</div>
<Modal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)} title={editingId ? 'Editar Promo' : 'Nueva Promo'}>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-sm font-medium mb-1">Nombre Promoción</label>
<input type="text" required className="w-full border p-2 rounded"
value={formData.name} onChange={e => setFormData({ ...formData, name: e.target.value })} />
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium mb-1">Aplica a Rubro</label>
<select className="w-full border p-2 rounded"
value={formData.categoryId || 0}
onChange={e => setFormData({ ...formData, categoryId: Number(e.target.value) || null })}
>
<option value="0">Todos los Rubros</option>
{categories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
</select>
</div>
<div>
<label className="block text-sm font-medium mb-1">Mínimo de Días</label>
<input type="number" className="w-full border p-2 rounded"
value={formData.minDays} onChange={e => setFormData({ ...formData, minDays: parseInt(e.target.value) })} />
</div>
</div>
<div>
<label className="block text-sm font-medium mb-2">Aplica solo estos días (Opcional)</label>
<div className="flex gap-2 flex-wrap">
{daysOptions.map(day => {
const isSelected = formData.daysOfWeek?.split(',').includes(day.val.toString());
return (
<button
key={day.val} type="button"
onClick={() => toggleDay(day.val)}
className={`px-3 py-1 rounded text-sm border ${isSelected ? 'bg-blue-600 text-white border-blue-600' : 'bg-gray-50 border-gray-300'}`}
>
{day.label}
</button>
)
})}
</div>
</div>
<div className="grid grid-cols-2 gap-4 border-t pt-4">
<div>
<label className="block text-sm font-medium mb-1">Descuento %</label>
<input type="number" className="w-full border p-2 rounded"
value={formData.discountPercentage} onChange={e => setFormData({ ...formData, discountPercentage: parseFloat(e.target.value) })} />
</div>
<div>
<label className="block text-sm font-medium mb-1">Descuento Fijo $</label>
<input type="number" className="w-full border p-2 rounded"
value={formData.discountFixedAmount} onChange={e => setFormData({ ...formData, discountFixedAmount: parseFloat(e.target.value) })} />
</div>
</div>
<div className="flex items-center gap-2 pt-2">
<input type="checkbox" id="active"
checked={formData.isActive} onChange={e => setFormData({ ...formData, isActive: e.target.checked })} />
<label htmlFor="active" className="text-sm">Promoción Activa</label>
</div>
<div className="pt-4 flex justify-end gap-2">
<button type="button" onClick={() => setIsModalOpen(false)} className="px-4 py-2 bg-gray-200 rounded">Cancelar</button>
<button type="submit" className="px-4 py-2 bg-blue-600 text-white rounded">Guardar</button>
</div>
</form>
</Modal>
</div>
);
}

View File

@@ -1,7 +1,7 @@
import { useState, useEffect } from 'react';
// @ts-ignore
import { User } from '../../types/User';
import { userService } from '../../services/userService';
import { type User } from '../../types/User';
import { userService, type CreateUserDto } from '../../services/userService';
import Modal from '../../components/Modal';
import { Plus, Edit, Trash2, Shield, User as UserIcon } from 'lucide-react';
@@ -43,10 +43,9 @@ export default function UserManager() {
// @ts-ignore
const handleEdit = (user: User) => {
setEditingId(user.id);
// Password left empty intentionally
setFormData({
username: user.username,
password: '',
password: '', // Password vacío al editar
role: user.role,
email: user.email || ''
});
@@ -66,15 +65,29 @@ export default function UserManager() {
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
// Validar password obligatorio al crear
if (!editingId && !formData.password) {
alert("La contraseña es obligatoria para nuevos usuarios");
return;
}
const payload: CreateUserDto = {
username: formData.username,
role: formData.role,
email: formData.email,
password: formData.password || undefined // Enviar undefined si está vacío en edit
};
if (editingId) {
await userService.update(editingId, formData);
await userService.update(editingId, payload);
} else {
await userService.create(formData as any);
// En create, password es string (ya validado arriba)
await userService.create(payload as CreateUserDto);
}
setIsModalOpen(false);
loadUsers();
} catch (error) {
alert('Error guardando usuario');
alert('Error procesando usuario');
}
};

View File

@@ -1,7 +1,7 @@
import axios from 'axios';
const api = axios.create({
baseURL: 'https://localhost:7034/api', // Puerto HTTPS obtenido de launchSettings.json
baseURL: import.meta.env.VITE_API_URL, // Usa la variable de entorno
});
api.interceptors.request.use((config) => {
@@ -12,4 +12,4 @@ api.interceptors.request.use((config) => {
return config;
});
export default api;
export default api;

View File

@@ -1,5 +1,5 @@
import api from './api';
import { AttributeDefinition } from '../types/AttributeDefinition';
import { type AttributeDefinition } from '../types/AttributeDefinition';
export const attributeService = {
getByCategoryId: async (categoryId: number): Promise<AttributeDefinition[]> => {

View File

@@ -1,5 +1,5 @@
import api from './api';
import { Category } from '../types/Category';
import { type Category } from '../types/Category';
export const categoryService = {
getAll: async (): Promise<Category[]> => {

View File

@@ -0,0 +1,20 @@
import api from './api';
export const exportService = {
downloadDiagram: async (date: string) => {
// Axios necesita config especial para descargar archivos (blob)
const response = await api.get('/exports/diagram', {
params: { date },
responseType: 'blob'
});
// Truco para forzar la descarga en el navegador
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', `diagrama_${date}.xml`);
document.body.appendChild(link);
link.click();
link.remove();
}
};

View File

@@ -1,5 +1,5 @@
import api from './api';
import { Operation } from '../types/Operation'; // ID: type-import-fix
import { type Operation } from '../types/Operation';
export const operationService = {
getAll: async (): Promise<Operation[]> => {

View File

@@ -1,25 +1,17 @@
import api from './api';
// @ts-ignore
import type { User } from '../types/User';
import { type User } from '../types/User';
interface CreateUserDto {
// DTOs específicos para creación/edición para no usar 'any'
export interface CreateUserDto {
username: string;
password: string;
password?: string; // Opcional en update, requerido en create (validar en UI)
role: string;
email?: string;
}
interface UpdateUserDto {
username: string;
password?: string;
role: string;
email?: string;
email: string;
}
export const userService = {
getAll: async (): Promise<User[]> => {
const response = await api.get<User[]>('/users');
// @ts-ignore
return response.data;
},
@@ -27,11 +19,11 @@ export const userService = {
await api.post('/users', user);
},
update: async (id: number, user: UpdateUserDto): Promise<void> => {
update: async (id: number, user: CreateUserDto): Promise<void> => {
await api.put(`/users/${id}`, user);
},
delete: async (id: number): Promise<void> => {
await api.delete(`/users/${id}`);
}
};
};