first commit
This commit is contained in:
3
.env.example
Normal file
3
.env.example
Normal file
@@ -0,0 +1,3 @@
|
||||
JWT_SECRET=cambiar-por-un-secreto-largo-y-aleatorio
|
||||
# Puerto API (solo desarrollo local sin Docker)
|
||||
PORT=4000
|
||||
8
.gitignore
vendored
Normal file
8
.gitignore
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
node_modules/
|
||||
dist/
|
||||
backend/data/
|
||||
*.db
|
||||
.env
|
||||
.env.local
|
||||
.DS_Store
|
||||
npm-debug.log*
|
||||
134
README.md
Normal file
134
README.md
Normal file
@@ -0,0 +1,134 @@
|
||||
# Don Marco — Administración Financiera (LAN)
|
||||
|
||||
Aplicación web multiusuario para gestión de **ingresos** (ventas, servicios, alquileres), **egresos** (gastos diarios/fijos), **personal** y **reportes** consolidados. Pensada para operar en la red local de una pequeña empresa con un servidor central.
|
||||
|
||||
## 1. Stack tecnológico recomendado
|
||||
|
||||
| Capa | Tecnología | Motivo |
|
||||
|------|------------|--------|
|
||||
| **Frontend** | React 18 + Vite | UI rápida, componentes reutilizables para planillas dinámicas |
|
||||
| **Backend** | Node.js + Express | API REST ligera, fácil de mantener en LAN |
|
||||
| **Base de datos** | SQLite (`better-sqlite3`) | Almacenamiento local en el servidor, sin instalar MySQL/PostgreSQL |
|
||||
| **Auth** | JWT + bcrypt | Sesiones stateless, contraseñas hasheadas |
|
||||
| **Despliegue** | Docker Compose + Nginx | Un solo comando en el servidor de la red |
|
||||
|
||||
> **Nota:** Aunque mencionaste “almacenamiento local”, para **multiusuario en red** conviene SQLite en el servidor (no `localStorage` del navegador), para que todos vean los mismos datos. El token JWT sí se guarda en `localStorage` del cliente.
|
||||
|
||||
## 2. Estructura del proyecto
|
||||
|
||||
```
|
||||
DonMarcoBackend/
|
||||
├── docker-compose.yml
|
||||
├── README.md
|
||||
├── .env.example
|
||||
├── backend/
|
||||
│ ├── Dockerfile
|
||||
│ ├── package.json
|
||||
│ └── src/
|
||||
│ ├── index.js
|
||||
│ ├── db.js
|
||||
│ ├── seed.js
|
||||
│ ├── middleware/auth.js
|
||||
│ ├── routes/
|
||||
│ │ ├── auth.js
|
||||
│ │ ├── users.js
|
||||
│ │ ├── sheets.js
|
||||
│ │ └── reports.js
|
||||
│ └── utils/calculations.js
|
||||
└── frontend/
|
||||
├── Dockerfile
|
||||
├── nginx.conf
|
||||
├── package.json
|
||||
├── vite.config.js
|
||||
└── src/
|
||||
├── App.jsx
|
||||
├── api/client.js
|
||||
├── context/AuthContext.jsx
|
||||
├── components/
|
||||
│ ├── Layout.jsx
|
||||
│ ├── IngresoSheet.jsx
|
||||
│ ├── GastoSheet.jsx
|
||||
│ └── PersonalSheet.jsx
|
||||
├── pages/
|
||||
│ ├── LoginPage.jsx
|
||||
│ ├── HomePage.jsx
|
||||
│ ├── ReportesPage.jsx
|
||||
│ └── AdminPage.jsx
|
||||
├── utils/calc.js
|
||||
└── styles/global.css
|
||||
```
|
||||
|
||||
## 3. Credenciales por defecto
|
||||
|
||||
| Usuario | Contraseña | Rol |
|
||||
|---------|------------|-----|
|
||||
| `JEFE` | `MACAN` | Superusuario / administrador |
|
||||
|
||||
**Cambie la contraseña del JEFE en producción** desde el panel de administración o actualizando la base de datos.
|
||||
|
||||
## 4. Funcionalidades implementadas
|
||||
|
||||
- Login seguro y menú con pestañas (Ventas, Servicios, Alquileres, Gastos, Personal, Reportes, Salir).
|
||||
- Panel de administración: crear usuarios, contraseñas y permisos **ver/editar** por planilla.
|
||||
- Planillas con filas en blanco al inicio y botón **+** para agregar líneas ilimitadas.
|
||||
- Cálculos automáticos: Precio Total, Utilidad, totales de cierre.
|
||||
- Gastos con clasificación diario / fijo / variable.
|
||||
- Personal: hasta 10 mensualizados y 5 eventuales por registro.
|
||||
- Reportes diario, semanal y mensual con filtro de fechas y selección de planillas.
|
||||
- Cierre semanal de gastos diarios y consolidado mensual en reportes.
|
||||
|
||||
## 5. Ejecución con Docker (recomendado en el servidor LAN)
|
||||
|
||||
```bash
|
||||
cd DonMarcoBackend
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
Acceso desde cualquier PC de la red:
|
||||
|
||||
- **Web:** `http://IP-DEL-SERVIDOR` (puerto 80)
|
||||
- **API directa (opcional):** `http://IP-DEL-SERVIDOR:4000/api/health`
|
||||
|
||||
## 6. Desarrollo local (sin Docker)
|
||||
|
||||
**Terminal 1 — API:**
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
**Terminal 2 — Web:**
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Abrir `http://localhost:3000` (el proxy de Vite redirige `/api` al puerto 4000).
|
||||
|
||||
## 7. Variables de entorno
|
||||
|
||||
Copie `.env.example` a `.env` y defina al menos:
|
||||
|
||||
```env
|
||||
JWT_SECRET=un-secreto-largo-unico
|
||||
```
|
||||
|
||||
En Docker, `JWT_SECRET` se lee desde el entorno del host o del archivo `.env` junto a `docker-compose.yml`.
|
||||
|
||||
## 8. Fórmula de reportes
|
||||
|
||||
Para diario, semanal y mensual (en el rango de fechas seleccionado):
|
||||
|
||||
```
|
||||
Resultado = (Ventas + Alquileres + Servicios) − Total Gastos − Total Personal
|
||||
```
|
||||
|
||||
El sistema indica **UTILIDAD** o **PÉRDIDA** según el signo del resultado neto.
|
||||
|
||||
---
|
||||
|
||||
Desarrollado como base funcional lista para ampliar (exportación PDF, respaldos automáticos, HTTPS con certificado interno, etc.).
|
||||
19
backend/Dockerfile
Normal file
19
backend/Dockerfile
Normal file
@@ -0,0 +1,19 @@
|
||||
FROM node:20-alpine
|
||||
|
||||
RUN apk add --no-cache python3 make g++
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package.json package-lock.json* ./
|
||||
RUN npm install --omit=dev
|
||||
|
||||
COPY src ./src
|
||||
|
||||
RUN mkdir -p /app/data
|
||||
|
||||
ENV PORT=4000
|
||||
ENV DB_PATH=/app/data/donmarco.db
|
||||
|
||||
EXPOSE 4000
|
||||
|
||||
CMD ["node", "src/index.js"]
|
||||
1392
backend/package-lock.json
generated
Normal file
1392
backend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
19
backend/package.json
Normal file
19
backend/package.json
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "donmarco-backend",
|
||||
"version": "1.0.0",
|
||||
"description": "API administración financiera Don Marco",
|
||||
"main": "src/index.js",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "node src/index.js",
|
||||
"dev": "node --watch src/index.js",
|
||||
"seed": "node src/seed.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"bcryptjs": "^2.4.3",
|
||||
"better-sqlite3": "^11.7.0",
|
||||
"cors": "^2.8.5",
|
||||
"express": "^4.21.2",
|
||||
"jsonwebtoken": "^9.0.2"
|
||||
}
|
||||
}
|
||||
56
backend/src/db.js
Normal file
56
backend/src/db.js
Normal file
@@ -0,0 +1,56 @@
|
||||
import Database from 'better-sqlite3';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const dbPath = process.env.DB_PATH || path.join(__dirname, '..', 'data', 'donmarco.db');
|
||||
|
||||
import fs from 'fs';
|
||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||
|
||||
export const db = new Database(dbPath);
|
||||
db.pragma('journal_mode = WAL');
|
||||
|
||||
export const SHEETS = [
|
||||
'ventas',
|
||||
'servicios',
|
||||
'alquileres',
|
||||
'gastos_diarios',
|
||||
'gastos_fijos',
|
||||
'personal',
|
||||
'reportes',
|
||||
];
|
||||
|
||||
export function initDb() {
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT UNIQUE NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
is_admin INTEGER DEFAULT 0,
|
||||
active INTEGER DEFAULT 1,
|
||||
created_at TEXT DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS permissions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
sheet_key TEXT NOT NULL,
|
||||
can_view INTEGER DEFAULT 1,
|
||||
can_edit INTEGER DEFAULT 0,
|
||||
UNIQUE(user_id, sheet_key),
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS registros (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
sheet_type TEXT NOT NULL,
|
||||
data TEXT NOT NULL,
|
||||
created_by INTEGER,
|
||||
updated_at TEXT DEFAULT (datetime('now')),
|
||||
FOREIGN KEY (created_by) REFERENCES users(id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_registros_sheet ON registros(sheet_type);
|
||||
`);
|
||||
}
|
||||
42
backend/src/index.js
Normal file
42
backend/src/index.js
Normal file
@@ -0,0 +1,42 @@
|
||||
import express from 'express';
|
||||
import cors from 'cors';
|
||||
import { initDb } from './db.js';
|
||||
import authRoutes from './routes/auth.js';
|
||||
import userRoutes from './routes/users.js';
|
||||
import sheetRoutes from './routes/sheets.js';
|
||||
import reportRoutes from './routes/reports.js';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { db, SHEETS } from './db.js';
|
||||
|
||||
initDb();
|
||||
|
||||
// Seed automático del superusuario JEFE si no existe
|
||||
const jefe = db.prepare('SELECT id FROM users WHERE username = ?').get('JEFE');
|
||||
if (!jefe) {
|
||||
const hash = bcrypt.hashSync('MACAN', 10);
|
||||
const result = db
|
||||
.prepare('INSERT INTO users (username, password_hash, is_admin, active) VALUES (?, ?, 1, 1)')
|
||||
.run('JEFE', hash);
|
||||
const userId = result.lastInsertRowid;
|
||||
const permStmt = db.prepare(
|
||||
'INSERT INTO permissions (user_id, sheet_key, can_view, can_edit) VALUES (?, ?, 1, 1)'
|
||||
);
|
||||
for (const sheet of SHEETS) permStmt.run(userId, sheet);
|
||||
console.log('Superusuario JEFE creado (contraseña: MACAN)');
|
||||
}
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 4000;
|
||||
|
||||
app.use(cors({ origin: true, credentials: true }));
|
||||
app.use(express.json({ limit: '2mb' }));
|
||||
|
||||
app.get('/api/health', (_req, res) => res.json({ ok: true, service: 'DonMarco API' }));
|
||||
app.use('/api/auth', authRoutes);
|
||||
app.use('/api/users', userRoutes);
|
||||
app.use('/api/sheets', sheetRoutes);
|
||||
app.use('/api/reports', reportRoutes);
|
||||
|
||||
app.listen(PORT, '0.0.0.0', () => {
|
||||
console.log(`Don Marco API escuchando en http://0.0.0.0:${PORT}`);
|
||||
});
|
||||
31
backend/src/middleware/auth.js
Normal file
31
backend/src/middleware/auth.js
Normal file
@@ -0,0 +1,31 @@
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'donmarco-lan-secret-change-in-prod';
|
||||
|
||||
export function signToken(user) {
|
||||
return jwt.sign(
|
||||
{ id: user.id, username: user.username, isAdmin: !!user.is_admin },
|
||||
JWT_SECRET,
|
||||
{ expiresIn: '12h' }
|
||||
);
|
||||
}
|
||||
|
||||
export function authRequired(req, res, next) {
|
||||
const header = req.headers.authorization;
|
||||
if (!header?.startsWith('Bearer ')) {
|
||||
return res.status(401).json({ error: 'No autenticado' });
|
||||
}
|
||||
try {
|
||||
req.user = jwt.verify(header.slice(7), JWT_SECRET);
|
||||
next();
|
||||
} catch {
|
||||
return res.status(401).json({ error: 'Token inválido o expirado' });
|
||||
}
|
||||
}
|
||||
|
||||
export function adminRequired(req, res, next) {
|
||||
if (!req.user?.isAdmin) {
|
||||
return res.status(403).json({ error: 'Solo administrador' });
|
||||
}
|
||||
next();
|
||||
}
|
||||
52
backend/src/routes/auth.js
Normal file
52
backend/src/routes/auth.js
Normal file
@@ -0,0 +1,52 @@
|
||||
import { Router } from 'express';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { db } from '../db.js';
|
||||
import { signToken, authRequired } from '../middleware/auth.js';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.post('/login', (req, res) => {
|
||||
const { username, password } = req.body;
|
||||
if (!username || !password) {
|
||||
return res.status(400).json({ error: 'Usuario y contraseña requeridos' });
|
||||
}
|
||||
const user = db.prepare('SELECT * FROM users WHERE username = ? AND active = 1').get(username);
|
||||
if (!user || !bcrypt.compareSync(password, user.password_hash)) {
|
||||
return res.status(401).json({ error: 'Credenciales inválidas' });
|
||||
}
|
||||
const permissions = db
|
||||
.prepare('SELECT sheet_key, can_view, can_edit FROM permissions WHERE user_id = ?')
|
||||
.all(user.id);
|
||||
const token = signToken(user);
|
||||
res.json({
|
||||
token,
|
||||
user: {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
isAdmin: !!user.is_admin,
|
||||
permissions: permissions.reduce((acc, p) => {
|
||||
acc[p.sheet_key] = { view: !!p.can_view, edit: !!p.can_edit };
|
||||
return acc;
|
||||
}, {}),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
router.get('/me', authRequired, (req, res) => {
|
||||
const user = db.prepare('SELECT id, username, is_admin, active FROM users WHERE id = ?').get(req.user.id);
|
||||
if (!user || !user.active) return res.status(401).json({ error: 'Usuario inactivo' });
|
||||
const permissions = db
|
||||
.prepare('SELECT sheet_key, can_view, can_edit FROM permissions WHERE user_id = ?')
|
||||
.all(user.id);
|
||||
res.json({
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
isAdmin: !!user.is_admin,
|
||||
permissions: permissions.reduce((acc, p) => {
|
||||
acc[p.sheet_key] = { view: !!p.can_view, edit: !!p.can_edit };
|
||||
return acc;
|
||||
}, {}),
|
||||
});
|
||||
});
|
||||
|
||||
export default router;
|
||||
169
backend/src/routes/reports.js
Normal file
169
backend/src/routes/reports.js
Normal file
@@ -0,0 +1,169 @@
|
||||
import { Router } from 'express';
|
||||
import { db } from '../db.js';
|
||||
import { authRequired } from '../middleware/auth.js';
|
||||
import {
|
||||
inRange,
|
||||
sumIngresos,
|
||||
sumGastos,
|
||||
sumPersonal,
|
||||
weekKey,
|
||||
monthKey,
|
||||
parseFecha,
|
||||
} from '../utils/calculations.js';
|
||||
|
||||
const router = Router();
|
||||
router.use(authRequired);
|
||||
|
||||
function loadRows(sheetType) {
|
||||
return db
|
||||
.prepare('SELECT data FROM registros WHERE sheet_type = ?')
|
||||
.all(sheetType)
|
||||
.map((r) => JSON.parse(r.data));
|
||||
}
|
||||
|
||||
function filterByDate(rows, fechaField, desde, hasta) {
|
||||
return rows.filter((r) => inRange(r[fechaField], desde, hasta));
|
||||
}
|
||||
|
||||
function buildReport(desde, hasta, include = {}) {
|
||||
const inc = {
|
||||
ventas: include.ventas !== false,
|
||||
servicios: include.servicios !== false,
|
||||
alquileres: include.alquileres !== false,
|
||||
gastos_diarios: include.gastos_diarios !== false,
|
||||
gastos_fijos: include.gastos_fijos !== false,
|
||||
personal: include.personal !== false,
|
||||
};
|
||||
|
||||
const ventas = inc.ventas ? filterByDate(loadRows('ventas'), 'fecha', desde, hasta) : [];
|
||||
const servicios = inc.servicios ? filterByDate(loadRows('servicios'), 'fecha', desde, hasta) : [];
|
||||
const alquileres = inc.alquileres ? filterByDate(loadRows('alquileres'), 'fecha', desde, hasta) : [];
|
||||
const gastosDiarios = inc.gastos_diarios
|
||||
? filterByDate(loadRows('gastos_diarios'), 'fecha', desde, hasta)
|
||||
: [];
|
||||
const gastosFijos = inc.gastos_fijos
|
||||
? filterByDate(loadRows('gastos_fijos'), 'fecha', desde, hasta)
|
||||
: [];
|
||||
|
||||
const personalRows = inc.personal ? loadRows('personal') : [];
|
||||
const mensualizados = personalRows.filter((r) => r.tipo === 'mensualizado');
|
||||
const eventuales = inc.personal
|
||||
? filterByDate(
|
||||
personalRows.filter((r) => r.tipo === 'eventual'),
|
||||
'fecha',
|
||||
desde,
|
||||
hasta
|
||||
)
|
||||
: [];
|
||||
|
||||
const tVentas = sumIngresos(ventas);
|
||||
const tServicios = sumIngresos(servicios);
|
||||
const tAlquileres = sumIngresos(alquileres);
|
||||
const totalIngresos =
|
||||
tVentas.totalIngresos + tServicios.totalIngresos + tAlquileres.totalIngresos;
|
||||
const totalUtilidad =
|
||||
tVentas.totalUtilidad + tServicios.totalUtilidad + tAlquileres.totalUtilidad;
|
||||
|
||||
const gastosDiariosTotal = sumGastos(gastosDiarios);
|
||||
const gastosFijosTotal = sumGastos(gastosFijos);
|
||||
const gastosVariables = [...gastosDiarios, ...gastosFijos].filter(
|
||||
(g) => g.clasificacion === 'variable'
|
||||
);
|
||||
const gastosVariablesTotal = sumGastos(gastosVariables);
|
||||
const totalGastos = gastosDiariosTotal + gastosFijosTotal;
|
||||
|
||||
const totalPersonal = sumPersonal(mensualizados, eventuales);
|
||||
|
||||
const resultadoNeto = totalIngresos - totalGastos - totalPersonal;
|
||||
|
||||
return {
|
||||
periodo: { desde: desde || null, hasta: hasta || null },
|
||||
desglose: {
|
||||
ventas: tVentas,
|
||||
servicios: tServicios,
|
||||
alquileres: tAlquileres,
|
||||
gastosDiarios: { total: gastosDiariosTotal, filas: gastosDiarios.length },
|
||||
gastosFijos: { total: gastosFijosTotal, filas: gastosFijos.length },
|
||||
gastosVariables: { total: gastosVariablesTotal },
|
||||
personal: { total: totalPersonal, mensualizados: mensualizados.length, eventuales: eventuales.length },
|
||||
},
|
||||
totales: {
|
||||
totalIngresos,
|
||||
totalUtilidad,
|
||||
totalGastos,
|
||||
totalPersonal,
|
||||
resultadoNeto,
|
||||
estado: resultadoNeto >= 0 ? 'utilidad' : 'perdida',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
router.get('/', (req, res) => {
|
||||
const { desde, hasta, tipo = 'mensual', include } = req.query;
|
||||
let d = desde;
|
||||
let h = hasta;
|
||||
|
||||
const today = new Date();
|
||||
if (tipo === 'diario') {
|
||||
const f = (h || d || today.toISOString().slice(0, 10));
|
||||
d = f;
|
||||
h = f;
|
||||
} else if (tipo === 'semanal') {
|
||||
const ref = parseFecha(h || d || today.toISOString().slice(0, 10));
|
||||
const day = ref.getDay();
|
||||
const diff = day === 0 ? -6 : 1 - day;
|
||||
const monday = new Date(ref);
|
||||
monday.setDate(ref.getDate() + diff);
|
||||
const sunday = new Date(monday);
|
||||
sunday.setDate(monday.getDate() + 6);
|
||||
d = monday.toISOString().slice(0, 10);
|
||||
h = sunday.toISOString().slice(0, 10);
|
||||
} else if (tipo === 'mensual' && !d && !h) {
|
||||
d = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-01`;
|
||||
const last = new Date(today.getFullYear(), today.getMonth() + 1, 0);
|
||||
h = last.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
let includeObj = {};
|
||||
if (include) {
|
||||
try {
|
||||
includeObj = typeof include === 'string' ? JSON.parse(include) : include;
|
||||
} catch {
|
||||
includeObj = {};
|
||||
}
|
||||
}
|
||||
|
||||
const report = buildReport(d, h, includeObj);
|
||||
|
||||
if (tipo === 'semanal' || tipo === 'mensual') {
|
||||
const gastosDiariosAll = loadRows('gastos_diarios');
|
||||
const weekly = {};
|
||||
for (const g of gastosDiariosAll) {
|
||||
const wk = weekKey(g.fecha);
|
||||
if (!inRange(g.fecha, d, h)) continue;
|
||||
weekly[wk] = (weekly[wk] || 0) + (Number(g.monto) || 0);
|
||||
}
|
||||
report.cierreSemanal = weekly;
|
||||
report.totalGastosSemanales = Object.values(weekly).reduce((a, b) => a + b, 0);
|
||||
|
||||
if (tipo === 'mensual') {
|
||||
const monthly = {};
|
||||
for (const g of gastosDiariosAll) {
|
||||
const mk = monthKey(g.fecha);
|
||||
if (!inRange(g.fecha, d, h)) continue;
|
||||
monthly[mk] = (monthly[mk] || 0) + (Number(g.monto) || 0);
|
||||
}
|
||||
const fijosAll = filterByDate(loadRows('gastos_fijos'), 'fecha', d, h);
|
||||
report.cierreMensual = {
|
||||
gastosDiariosPorMes: monthly,
|
||||
gastosFijosEnPeriodo: sumGastos(fijosAll),
|
||||
totalGastosMensualesConsolidado:
|
||||
Object.values(monthly).reduce((a, b) => a + b, 0) + sumGastos(fijosAll),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
res.json(report);
|
||||
});
|
||||
|
||||
export default router;
|
||||
95
backend/src/routes/sheets.js
Normal file
95
backend/src/routes/sheets.js
Normal file
@@ -0,0 +1,95 @@
|
||||
import { Router } from 'express';
|
||||
import { db, SHEETS } from '../db.js';
|
||||
import { authRequired } from '../middleware/auth.js';
|
||||
import { sumIngresos, sumGastos, sumPersonal } from '../utils/calculations.js';
|
||||
|
||||
const router = Router();
|
||||
router.use(authRequired);
|
||||
|
||||
const INGRESO_SHEETS = ['ventas', 'servicios', 'alquileres'];
|
||||
const GASTO_SHEETS = ['gastos_diarios', 'gastos_fijos'];
|
||||
|
||||
function checkPermission(req, sheet, needEdit = false) {
|
||||
if (req.user.isAdmin) return true;
|
||||
const row = db
|
||||
.prepare('SELECT can_view, can_edit FROM permissions WHERE user_id = ? AND sheet_key = ?')
|
||||
.get(req.user.id, sheet);
|
||||
if (!row) return false;
|
||||
if (needEdit) return !!row.can_edit;
|
||||
return !!row.can_view;
|
||||
}
|
||||
|
||||
function getSheetPayload(sheetType) {
|
||||
const rows = db
|
||||
.prepare('SELECT id, data, updated_at FROM registros WHERE sheet_type = ? ORDER BY id')
|
||||
.all(sheetType);
|
||||
const parsed = rows.map((r) => ({ id: r.id, ...JSON.parse(r.data), updated_at: r.updated_at }));
|
||||
|
||||
if (INGRESO_SHEETS.includes(sheetType)) {
|
||||
const totals = sumIngresos(parsed);
|
||||
return { rows: parsed, totals };
|
||||
}
|
||||
if (GASTO_SHEETS.includes(sheetType)) {
|
||||
const total = sumGastos(parsed);
|
||||
return { rows: parsed, totals: { totalGastos: total } };
|
||||
}
|
||||
if (sheetType === 'personal') {
|
||||
const mensualizados = parsed.filter((r) => r.tipo === 'mensualizado');
|
||||
const eventuales = parsed.filter((r) => r.tipo === 'eventual');
|
||||
return {
|
||||
mensualizados,
|
||||
eventuales,
|
||||
totals: { totalPersonal: sumPersonal(mensualizados, eventuales) },
|
||||
};
|
||||
}
|
||||
return { rows: parsed };
|
||||
}
|
||||
|
||||
router.get('/:sheetType', (req, res) => {
|
||||
const { sheetType } = req.params;
|
||||
if (!SHEETS.includes(sheetType) || sheetType === 'reportes') {
|
||||
return res.status(400).json({ error: 'Planilla inválida' });
|
||||
}
|
||||
if (!checkPermission(req, sheetType)) {
|
||||
return res.status(403).json({ error: 'Sin permiso para ver esta planilla' });
|
||||
}
|
||||
res.json(getSheetPayload(sheetType));
|
||||
});
|
||||
|
||||
router.put('/:sheetType', (req, res) => {
|
||||
const { sheetType } = req.params;
|
||||
if (!SHEETS.includes(sheetType) || sheetType === 'reportes') {
|
||||
return res.status(400).json({ error: 'Planilla inválida' });
|
||||
}
|
||||
if (!checkPermission(req, sheetType, true)) {
|
||||
return res.status(403).json({ error: 'Sin permiso para editar' });
|
||||
}
|
||||
|
||||
const { rows, mensualizados, eventuales } = req.body;
|
||||
|
||||
db.prepare('DELETE FROM registros WHERE sheet_type = ?').run(sheetType);
|
||||
|
||||
const insert = db.prepare(
|
||||
'INSERT INTO registros (sheet_type, data, created_by) VALUES (?, ?, ?)'
|
||||
);
|
||||
|
||||
if (sheetType === 'personal') {
|
||||
const all = [
|
||||
...(mensualizados || []).map((r) => ({ ...r, tipo: 'mensualizado' })),
|
||||
...(eventuales || []).map((r) => ({ ...r, tipo: 'eventual' })),
|
||||
];
|
||||
for (const row of all) {
|
||||
const { id: _id, updated_at: _u, ...data } = row;
|
||||
insert.run(sheetType, JSON.stringify(data), req.user.id);
|
||||
}
|
||||
} else {
|
||||
for (const row of rows || []) {
|
||||
const { id: _id, updated_at: _u, ...data } = row;
|
||||
insert.run(sheetType, JSON.stringify(data), req.user.id);
|
||||
}
|
||||
}
|
||||
|
||||
res.json(getSheetPayload(sheetType));
|
||||
});
|
||||
|
||||
export default router;
|
||||
96
backend/src/routes/users.js
Normal file
96
backend/src/routes/users.js
Normal file
@@ -0,0 +1,96 @@
|
||||
import { Router } from 'express';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { db, SHEETS } from '../db.js';
|
||||
import { authRequired, adminRequired } from '../middleware/auth.js';
|
||||
|
||||
const router = Router();
|
||||
router.use(authRequired, adminRequired);
|
||||
|
||||
router.get('/', (_req, res) => {
|
||||
const users = db
|
||||
.prepare('SELECT id, username, is_admin, active, created_at FROM users ORDER BY username')
|
||||
.all();
|
||||
const withPerms = users.map((u) => {
|
||||
const permissions = db
|
||||
.prepare('SELECT sheet_key, can_view, can_edit FROM permissions WHERE user_id = ?')
|
||||
.all(u.id);
|
||||
return {
|
||||
...u,
|
||||
isAdmin: !!u.is_admin,
|
||||
active: !!u.active,
|
||||
permissions: permissions.reduce((acc, p) => {
|
||||
acc[p.sheet_key] = { view: !!p.can_view, edit: !!p.can_edit };
|
||||
return acc;
|
||||
}, {}),
|
||||
};
|
||||
});
|
||||
res.json(withPerms);
|
||||
});
|
||||
|
||||
router.post('/', (req, res) => {
|
||||
const { username, password, permissions = {} } = req.body;
|
||||
if (!username || !password) {
|
||||
return res.status(400).json({ error: 'Usuario y contraseña requeridos' });
|
||||
}
|
||||
const hash = bcrypt.hashSync(password, 10);
|
||||
try {
|
||||
const result = db
|
||||
.prepare('INSERT INTO users (username, password_hash, is_admin, active) VALUES (?, ?, 0, 1)')
|
||||
.run(username, hash);
|
||||
const userId = result.lastInsertRowid;
|
||||
const permStmt = db.prepare(
|
||||
'INSERT INTO permissions (user_id, sheet_key, can_view, can_edit) VALUES (?, ?, ?, ?)'
|
||||
);
|
||||
for (const sheet of SHEETS) {
|
||||
if (sheet === 'reportes') continue;
|
||||
const p = permissions[sheet] || { view: false, edit: false };
|
||||
permStmt.run(userId, sheet, p.view ? 1 : 0, p.edit ? 1 : 0);
|
||||
}
|
||||
permStmt.run(userId, 'reportes', 1, 0);
|
||||
res.status(201).json({ id: userId, username });
|
||||
} catch (e) {
|
||||
if (e.code === 'SQLITE_CONSTRAINT_UNIQUE') {
|
||||
return res.status(409).json({ error: 'El usuario ya existe' });
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
|
||||
router.patch('/:id', (req, res) => {
|
||||
const id = Number(req.params.id);
|
||||
const { password, active, permissions } = req.body;
|
||||
const user = db.prepare('SELECT * FROM users WHERE id = ?').get(id);
|
||||
if (!user) return res.status(404).json({ error: 'Usuario no encontrado' });
|
||||
if (user.is_admin && req.user.id !== id && active === 0) {
|
||||
return res.status(400).json({ error: 'No se puede desactivar al administrador principal' });
|
||||
}
|
||||
if (password) {
|
||||
db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run(bcrypt.hashSync(password, 10), id);
|
||||
}
|
||||
if (active !== undefined) {
|
||||
db.prepare('UPDATE users SET active = ? WHERE id = ?').run(active ? 1 : 0, id);
|
||||
}
|
||||
if (permissions) {
|
||||
const upsert = db.prepare(`
|
||||
INSERT INTO permissions (user_id, sheet_key, can_view, can_edit)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(user_id, sheet_key) DO UPDATE SET can_view = excluded.can_view, can_edit = excluded.can_edit
|
||||
`);
|
||||
for (const [sheet, p] of Object.entries(permissions)) {
|
||||
if (!SHEETS.includes(sheet)) continue;
|
||||
upsert.run(id, sheet, p.view ? 1 : 0, p.edit ? 1 : 0);
|
||||
}
|
||||
}
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
router.delete('/:id', (req, res) => {
|
||||
const id = Number(req.params.id);
|
||||
const user = db.prepare('SELECT is_admin FROM users WHERE id = ?').get(id);
|
||||
if (!user) return res.status(404).json({ error: 'Usuario no encontrado' });
|
||||
if (user.is_admin) return res.status(400).json({ error: 'No se puede eliminar al administrador' });
|
||||
db.prepare('DELETE FROM users WHERE id = ?').run(id);
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
export default router;
|
||||
25
backend/src/seed.js
Normal file
25
backend/src/seed.js
Normal file
@@ -0,0 +1,25 @@
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { db, initDb, SHEETS } from './db.js';
|
||||
|
||||
initDb();
|
||||
|
||||
const existing = db.prepare('SELECT id FROM users WHERE username = ?').get('JEFE');
|
||||
if (existing) {
|
||||
console.log('Usuario JEFE ya existe.');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const hash = bcrypt.hashSync('MACAN', 10);
|
||||
const result = db
|
||||
.prepare('INSERT INTO users (username, password_hash, is_admin, active) VALUES (?, ?, 1, 1)')
|
||||
.run('JEFE', hash);
|
||||
|
||||
const userId = result.lastInsertRowid;
|
||||
const permStmt = db.prepare(
|
||||
'INSERT INTO permissions (user_id, sheet_key, can_view, can_edit) VALUES (?, ?, 1, 1)'
|
||||
);
|
||||
for (const sheet of SHEETS) {
|
||||
permStmt.run(userId, sheet);
|
||||
}
|
||||
|
||||
console.log('Superusuario JEFE creado (contraseña: MACAN)');
|
||||
69
backend/src/utils/calculations.js
Normal file
69
backend/src/utils/calculations.js
Normal file
@@ -0,0 +1,69 @@
|
||||
/** Cálculos compartidos para ingresos, egresos y reportes */
|
||||
|
||||
export function calcIngresoRow(row) {
|
||||
const cantidad = Number(row.cantidad) || 0;
|
||||
const precioUnitario = Number(row.precioUnitario) || 0;
|
||||
const costoUnitario = Number(row.costoUnitario) || 0;
|
||||
const precioTotal = cantidad * precioUnitario;
|
||||
const utilidad = precioTotal - cantidad * costoUnitario;
|
||||
return { precioTotal, utilidad };
|
||||
}
|
||||
|
||||
export function sumIngresos(rows) {
|
||||
let totalIngresos = 0;
|
||||
let totalUtilidad = 0;
|
||||
for (const row of rows) {
|
||||
const { precioTotal, utilidad } = calcIngresoRow(row);
|
||||
totalIngresos += precioTotal;
|
||||
totalUtilidad += utilidad;
|
||||
}
|
||||
return { totalIngresos, totalUtilidad };
|
||||
}
|
||||
|
||||
export function sumGastos(rows) {
|
||||
return rows.reduce((acc, r) => acc + (Number(r.monto) || 0), 0);
|
||||
}
|
||||
|
||||
export function sumPersonal(mensualizados = [], eventuales = []) {
|
||||
const mensual = mensualizados.reduce((acc, e) => {
|
||||
const base = Number(e.sueldoBase) || 0;
|
||||
const cargas = Number(e.cargasSociales) || 0;
|
||||
const bonos = Number(e.bonos) || 0;
|
||||
return acc + base + cargas + bonos;
|
||||
}, 0);
|
||||
const event = eventuales.reduce((acc, e) => acc + (Number(e.pagoDiario) || 0), 0);
|
||||
return mensual + event;
|
||||
}
|
||||
|
||||
export function parseFecha(fecha) {
|
||||
if (!fecha) return null;
|
||||
const d = new Date(fecha + 'T12:00:00');
|
||||
return isNaN(d.getTime()) ? null : d;
|
||||
}
|
||||
|
||||
export function inRange(fecha, desde, hasta) {
|
||||
const d = parseFecha(fecha);
|
||||
if (!d) return !desde && !hasta;
|
||||
const ds = desde ? parseFecha(desde) : null;
|
||||
const hs = hasta ? parseFecha(hasta) : null;
|
||||
if (ds && d < ds) return false;
|
||||
if (hs && d > hs) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Lunes de la semana ISO (lunes como inicio) */
|
||||
export function weekKey(fecha) {
|
||||
const d = parseFecha(fecha);
|
||||
if (!d) return 'sin-fecha';
|
||||
const day = d.getDay();
|
||||
const diff = day === 0 ? -6 : 1 - day;
|
||||
const monday = new Date(d);
|
||||
monday.setDate(d.getDate() + diff);
|
||||
return monday.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
export function monthKey(fecha) {
|
||||
const d = parseFecha(fecha);
|
||||
if (!d) return 'sin-fecha';
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
|
||||
}
|
||||
39
docker-compose.yml
Normal file
39
docker-compose.yml
Normal file
@@ -0,0 +1,39 @@
|
||||
services:
|
||||
backend:
|
||||
build:
|
||||
context: ./backend
|
||||
dockerfile: Dockerfile
|
||||
container_name: donmarco-api
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
- PORT=4000
|
||||
- JWT_SECRET=${JWT_SECRET:-cambiar-este-secreto-en-produccion}
|
||||
- DB_PATH=/app/data/donmarco.db
|
||||
volumes:
|
||||
- donmarco_data:/app/data
|
||||
ports:
|
||||
- "4000:4000"
|
||||
networks:
|
||||
- donmarco_net
|
||||
|
||||
frontend:
|
||||
build:
|
||||
context: ./frontend
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
VITE_API_URL: /api
|
||||
container_name: donmarco-web
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "80:80"
|
||||
depends_on:
|
||||
- backend
|
||||
networks:
|
||||
- donmarco_net
|
||||
|
||||
volumes:
|
||||
donmarco_data:
|
||||
|
||||
networks:
|
||||
donmarco_net:
|
||||
driver: bridge
|
||||
15
frontend/Dockerfile
Normal file
15
frontend/Dockerfile
Normal file
@@ -0,0 +1,15 @@
|
||||
FROM node:20-alpine AS build
|
||||
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json* ./
|
||||
RUN npm install
|
||||
COPY . .
|
||||
ARG VITE_API_URL=/api
|
||||
ENV VITE_API_URL=$VITE_API_URL
|
||||
RUN npm run build
|
||||
|
||||
FROM nginx:alpine
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY --from=build /app/dist /usr/share/nginx/html
|
||||
EXPOSE 80
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
14
frontend/index.html
Normal file
14
frontend/index.html
Normal file
@@ -0,0 +1,14 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Don Marco — Administración Financiera</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap" rel="stylesheet" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.jsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
18
frontend/nginx.conf
Normal file
18
frontend/nginx.conf
Normal file
@@ -0,0 +1,18 @@
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://backend:4000/api/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
}
|
||||
1761
frontend/package-lock.json
generated
Normal file
1761
frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
20
frontend/package.json
Normal file
20
frontend/package.json
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "donmarco-frontend",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-router-dom": "^6.28.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"vite": "^5.4.11"
|
||||
}
|
||||
}
|
||||
50
frontend/src/App.jsx
Normal file
50
frontend/src/App.jsx
Normal file
@@ -0,0 +1,50 @@
|
||||
import { Routes, Route, Navigate } from 'react-router-dom';
|
||||
import { useAuth } from './context/AuthContext';
|
||||
import Layout from './components/Layout';
|
||||
import LoginPage from './pages/LoginPage';
|
||||
import HomePage from './pages/HomePage';
|
||||
import ReportesPage from './pages/ReportesPage';
|
||||
import AdminPage from './pages/AdminPage';
|
||||
import IngresoSheet from './components/IngresoSheet';
|
||||
import GastoSheet from './components/GastoSheet';
|
||||
import PersonalSheet from './components/PersonalSheet';
|
||||
|
||||
function PrivateRoute({ children, sheet }) {
|
||||
const { user, loading, canView } = useAuth();
|
||||
if (loading) return <p className="loading">Cargando…</p>;
|
||||
if (!user) return <Navigate to="/login" replace />;
|
||||
if (sheet && !canView(sheet)) return <div className="alert alert-error">Sin acceso a esta planilla</div>;
|
||||
return <Layout>{children}</Layout>;
|
||||
}
|
||||
|
||||
function AdminRoute({ children }) {
|
||||
const { user, loading } = useAuth();
|
||||
if (loading) return <p className="loading">Cargando…</p>;
|
||||
if (!user) return <Navigate to="/login" replace />;
|
||||
if (!user.isAdmin) return <Navigate to="/" replace />;
|
||||
return <Layout>{children}</Layout>;
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const { user, loading } = useAuth();
|
||||
|
||||
if (loading) {
|
||||
return <p className="loading">Iniciando aplicación…</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/login" element={user ? <Navigate to="/" /> : <LoginPage />} />
|
||||
<Route path="/" element={<PrivateRoute><HomePage /></PrivateRoute>} />
|
||||
<Route path="/ventas" element={<PrivateRoute sheet="ventas"><IngresoSheet sheetType="ventas" title="Planilla de Ventas" /></PrivateRoute>} />
|
||||
<Route path="/servicios" element={<PrivateRoute sheet="servicios"><IngresoSheet sheetType="servicios" title="Planilla de Servicios" /></PrivateRoute>} />
|
||||
<Route path="/alquileres" element={<PrivateRoute sheet="alquileres"><IngresoSheet sheetType="alquileres" title="Planilla de Alquileres" /></PrivateRoute>} />
|
||||
<Route path="/gastos-diarios" element={<PrivateRoute sheet="gastos_diarios"><GastoSheet sheetType="gastos_diarios" title="Gastos Diarios" defaultClasificacion="diario" /></PrivateRoute>} />
|
||||
<Route path="/gastos-fijos" element={<PrivateRoute sheet="gastos_fijos"><GastoSheet sheetType="gastos_fijos" title="Gastos Fijos" defaultClasificacion="fijo" /></PrivateRoute>} />
|
||||
<Route path="/personal" element={<PrivateRoute sheet="personal"><PersonalSheet /></PrivateRoute>} />
|
||||
<Route path="/reportes" element={<PrivateRoute sheet="reportes"><ReportesPage /></PrivateRoute>} />
|
||||
<Route path="/admin" element={<AdminRoute><AdminPage /></AdminRoute>} />
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
);
|
||||
}
|
||||
42
frontend/src/api/client.js
Normal file
42
frontend/src/api/client.js
Normal file
@@ -0,0 +1,42 @@
|
||||
const API_BASE = import.meta.env.VITE_API_URL || '/api';
|
||||
|
||||
function getToken() {
|
||||
return localStorage.getItem('donmarco_token');
|
||||
}
|
||||
|
||||
export async function api(path, options = {}) {
|
||||
const headers = { 'Content-Type': 'application/json', ...options.headers };
|
||||
const token = getToken();
|
||||
if (token) headers.Authorization = `Bearer ${token}`;
|
||||
|
||||
const res = await fetch(`${API_BASE}${path}`, { ...options, headers });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Error en la solicitud');
|
||||
return data;
|
||||
}
|
||||
|
||||
export const authApi = {
|
||||
login: (username, password) =>
|
||||
api('/auth/login', { method: 'POST', body: JSON.stringify({ username, password }) }),
|
||||
me: () => api('/auth/me'),
|
||||
};
|
||||
|
||||
export const usersApi = {
|
||||
list: () => api('/users'),
|
||||
create: (body) => api('/users', { method: 'POST', body: JSON.stringify(body) }),
|
||||
update: (id, body) => api(`/users/${id}`, { method: 'PATCH', body: JSON.stringify(body) }),
|
||||
remove: (id) => api(`/users/${id}`, { method: 'DELETE' }),
|
||||
};
|
||||
|
||||
export const sheetsApi = {
|
||||
get: (sheet) => api(`/sheets/${sheet}`),
|
||||
save: (sheet, body) =>
|
||||
api(`/sheets/${sheet}`, { method: 'PUT', body: JSON.stringify(body) }),
|
||||
};
|
||||
|
||||
export const reportsApi = {
|
||||
get: (params) => {
|
||||
const q = new URLSearchParams(params).toString();
|
||||
return api(`/reports?${q}`);
|
||||
},
|
||||
};
|
||||
143
frontend/src/components/GastoSheet.jsx
Normal file
143
frontend/src/components/GastoSheet.jsx
Normal file
@@ -0,0 +1,143 @@
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import { sheetsApi } from '../api/client';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { emptyGastoRow, formatMoney } from '../utils/calc';
|
||||
|
||||
export default function GastoSheet({ sheetType, title, defaultClasificacion }) {
|
||||
const { canEdit } = useAuth();
|
||||
const editable = canEdit(sheetType);
|
||||
const [rows, setRows] = useState([emptyGastoRow()]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [message, setMessage] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
try {
|
||||
const data = await sheetsApi.get(sheetType);
|
||||
const loaded = data.rows?.length ? data.rows : [emptyGastoRow()];
|
||||
setRows(
|
||||
loaded.map((r) => ({
|
||||
...r,
|
||||
clasificacion: r.clasificacion || defaultClasificacion,
|
||||
}))
|
||||
);
|
||||
} catch (e) {
|
||||
setError(e.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
})();
|
||||
}, [sheetType, defaultClasificacion]);
|
||||
|
||||
const total = useMemo(
|
||||
() => rows.reduce((acc, r) => acc + (Number(r.monto) || 0), 0),
|
||||
[rows]
|
||||
);
|
||||
|
||||
const updateRow = (index, field, value) => {
|
||||
setRows((prev) => prev.map((r, i) => (i === index ? { ...r, [field]: value } : r)));
|
||||
};
|
||||
|
||||
const addRow = () =>
|
||||
setRows((prev) => [...prev, { ...emptyGastoRow(), clasificacion: defaultClasificacion }]);
|
||||
const removeRow = (index) => setRows((prev) => (prev.length > 1 ? prev.filter((_, i) => i !== index) : prev));
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!editable) return;
|
||||
setSaving(true);
|
||||
setMessage(null);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await sheetsApi.save(sheetType, { rows });
|
||||
setRows(data.rows?.length ? data.rows : [{ ...emptyGastoRow(), clasificacion: defaultClasificacion }]);
|
||||
setMessage('Planilla guardada correctamente');
|
||||
} catch (e) {
|
||||
setError(e.message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) return <p className="loading">Cargando planilla…</p>;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="page-title">{title}</h1>
|
||||
{error && <div className="alert alert-error">{error}</div>}
|
||||
{message && <div className="alert alert-success">{message}</div>}
|
||||
{!editable && <div className="alert alert-info">Solo lectura</div>}
|
||||
|
||||
<div className="toolbar">
|
||||
{editable && (
|
||||
<>
|
||||
<button type="button" className="btn btn-primary btn-icon" onClick={addRow}>
|
||||
+
|
||||
</button>
|
||||
<button type="button" className="btn btn-primary" onClick={handleSave} disabled={saving}>
|
||||
{saving ? 'Guardando…' : 'Guardar planilla'}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="card sheet-table-wrap">
|
||||
<table className="sheet-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Fecha</th>
|
||||
<th>Detalle</th>
|
||||
<th>Impuestos</th>
|
||||
<th>Nº Factura</th>
|
||||
<th>Monto</th>
|
||||
<th>Clasificación</th>
|
||||
{editable && <th></th>}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row, i) => (
|
||||
<tr key={i}>
|
||||
<td>
|
||||
<input type="date" value={row.fecha || ''} disabled={!editable} onChange={(e) => updateRow(i, 'fecha', e.target.value)} />
|
||||
</td>
|
||||
<td>
|
||||
<input value={row.detalle || ''} disabled={!editable} onChange={(e) => updateRow(i, 'detalle', e.target.value)} />
|
||||
</td>
|
||||
<td>
|
||||
<input type="number" min="0" step="any" value={row.impuestos ?? ''} disabled={!editable} onChange={(e) => updateRow(i, 'impuestos', e.target.value)} />
|
||||
</td>
|
||||
<td>
|
||||
<input value={row.numeroFactura || ''} disabled={!editable} onChange={(e) => updateRow(i, 'numeroFactura', e.target.value)} />
|
||||
</td>
|
||||
<td>
|
||||
<input type="number" min="0" step="any" value={row.monto ?? ''} disabled={!editable} onChange={(e) => updateRow(i, 'monto', e.target.value)} />
|
||||
</td>
|
||||
<td>
|
||||
<select value={row.clasificacion || 'diario'} disabled={!editable} onChange={(e) => updateRow(i, 'clasificacion', e.target.value)}>
|
||||
<option value="diario">Gasto Diario</option>
|
||||
<option value="fijo">Gasto Fijo</option>
|
||||
<option value="variable">Gasto Variable</option>
|
||||
</select>
|
||||
</td>
|
||||
{editable && (
|
||||
<td>
|
||||
<button type="button" className="btn btn-danger btn-icon" onClick={() => removeRow(i)}>
|
||||
×
|
||||
</button>
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div className="totals-bar">
|
||||
<span>
|
||||
Total gastos: <strong>{formatMoney(total)}</strong>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
148
frontend/src/components/IngresoSheet.jsx
Normal file
148
frontend/src/components/IngresoSheet.jsx
Normal file
@@ -0,0 +1,148 @@
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import { sheetsApi } from '../api/client';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { calcIngresoRow, emptyIngresoRow, formatMoney } from '../utils/calc';
|
||||
|
||||
export default function IngresoSheet({ sheetType, title }) {
|
||||
const { canEdit } = useAuth();
|
||||
const editable = canEdit(sheetType);
|
||||
const [rows, setRows] = useState([emptyIngresoRow()]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [message, setMessage] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
try {
|
||||
const data = await sheetsApi.get(sheetType);
|
||||
setRows(data.rows?.length ? data.rows : [emptyIngresoRow()]);
|
||||
} catch (e) {
|
||||
setError(e.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
})();
|
||||
}, [sheetType]);
|
||||
|
||||
const totals = useMemo(() => {
|
||||
let totalIngresos = 0;
|
||||
let totalUtilidad = 0;
|
||||
rows.forEach((row) => {
|
||||
const { precioTotal, utilidad } = calcIngresoRow(row);
|
||||
totalIngresos += precioTotal;
|
||||
totalUtilidad += utilidad;
|
||||
});
|
||||
return { totalIngresos, totalUtilidad };
|
||||
}, [rows]);
|
||||
|
||||
const updateRow = (index, field, value) => {
|
||||
setRows((prev) => prev.map((r, i) => (i === index ? { ...r, [field]: value } : r)));
|
||||
};
|
||||
|
||||
const addRow = () => setRows((prev) => [...prev, emptyIngresoRow()]);
|
||||
const removeRow = (index) => setRows((prev) => (prev.length > 1 ? prev.filter((_, i) => i !== index) : prev));
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!editable) return;
|
||||
setSaving(true);
|
||||
setMessage(null);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await sheetsApi.save(sheetType, { rows });
|
||||
setRows(data.rows?.length ? data.rows : [emptyIngresoRow()]);
|
||||
setMessage('Planilla guardada correctamente');
|
||||
} catch (e) {
|
||||
setError(e.message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) return <p className="loading">Cargando planilla…</p>;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="page-title">{title}</h1>
|
||||
{error && <div className="alert alert-error">{error}</div>}
|
||||
{message && <div className="alert alert-success">{message}</div>}
|
||||
{!editable && <div className="alert alert-info">Solo lectura — sin permiso de edición</div>}
|
||||
|
||||
<div className="toolbar">
|
||||
{editable && (
|
||||
<>
|
||||
<button type="button" className="btn btn-primary btn-icon" onClick={addRow} title="Agregar línea">
|
||||
+
|
||||
</button>
|
||||
<button type="button" className="btn btn-primary" onClick={handleSave} disabled={saving}>
|
||||
{saving ? 'Guardando…' : 'Guardar planilla'}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="card sheet-table-wrap">
|
||||
<table className="sheet-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Fecha</th>
|
||||
<th>Cliente</th>
|
||||
<th>Detalle</th>
|
||||
<th>Cantidad</th>
|
||||
<th>P. Unitario</th>
|
||||
<th>C. Unitario</th>
|
||||
<th>Precio Total</th>
|
||||
<th>Utilidad</th>
|
||||
{editable && <th></th>}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row, i) => {
|
||||
const { precioTotal, utilidad } = calcIngresoRow(row);
|
||||
return (
|
||||
<tr key={i}>
|
||||
<td>
|
||||
<input type="date" value={row.fecha || ''} disabled={!editable} onChange={(e) => updateRow(i, 'fecha', e.target.value)} />
|
||||
</td>
|
||||
<td>
|
||||
<input value={row.cliente || ''} disabled={!editable} onChange={(e) => updateRow(i, 'cliente', e.target.value)} />
|
||||
</td>
|
||||
<td>
|
||||
<input value={row.detalle || ''} disabled={!editable} onChange={(e) => updateRow(i, 'detalle', e.target.value)} />
|
||||
</td>
|
||||
<td>
|
||||
<input type="number" min="0" step="any" value={row.cantidad ?? ''} disabled={!editable} onChange={(e) => updateRow(i, 'cantidad', e.target.value)} />
|
||||
</td>
|
||||
<td>
|
||||
<input type="number" min="0" step="any" value={row.precioUnitario ?? ''} disabled={!editable} onChange={(e) => updateRow(i, 'precioUnitario', e.target.value)} />
|
||||
</td>
|
||||
<td>
|
||||
<input type="number" min="0" step="any" value={row.costoUnitario ?? ''} disabled={!editable} onChange={(e) => updateRow(i, 'costoUnitario', e.target.value)} />
|
||||
</td>
|
||||
<td className="computed">{formatMoney(precioTotal)}</td>
|
||||
<td className="computed">{formatMoney(utilidad)}</td>
|
||||
{editable && (
|
||||
<td>
|
||||
<button type="button" className="btn btn-danger btn-icon" onClick={() => removeRow(i)} title="Quitar fila">
|
||||
×
|
||||
</button>
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div className="totals-bar">
|
||||
<span>
|
||||
Sumatoria ingresos: <strong>{formatMoney(totals.totalIngresos)}</strong>
|
||||
</span>
|
||||
<span>
|
||||
Sumatoria utilidad: <strong>{formatMoney(totals.totalUtilidad)}</strong>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
52
frontend/src/components/Layout.jsx
Normal file
52
frontend/src/components/Layout.jsx
Normal file
@@ -0,0 +1,52 @@
|
||||
import { NavLink, useNavigate } from 'react-router-dom';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
|
||||
const TABS = [
|
||||
{ key: 'ventas', label: 'Planilla de Ventas', path: '/ventas' },
|
||||
{ key: 'servicios', label: 'Planilla de Servicios', path: '/servicios' },
|
||||
{ key: 'alquileres', label: 'Planilla de Alquileres', path: '/alquileres' },
|
||||
{ key: 'gastos_diarios', label: 'Gastos Diarios', path: '/gastos-diarios' },
|
||||
{ key: 'gastos_fijos', label: 'Gastos Fijos', path: '/gastos-fijos' },
|
||||
{ key: 'personal', label: 'Planilla de Personal', path: '/personal' },
|
||||
{ key: 'reportes', label: 'Planilla de Reportes', path: '/reportes' },
|
||||
];
|
||||
|
||||
export default function Layout({ children }) {
|
||||
const { user, logout, canView } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleLogout = () => {
|
||||
logout();
|
||||
navigate('/login');
|
||||
};
|
||||
|
||||
const visibleTabs = TABS.filter((t) => canView(t.key));
|
||||
|
||||
return (
|
||||
<div className="app-shell">
|
||||
<nav className="navbar">
|
||||
<NavLink to="/" className="nav-tab" end>
|
||||
Inicio
|
||||
</NavLink>
|
||||
{visibleTabs.map((tab) => (
|
||||
<NavLink
|
||||
key={tab.path}
|
||||
to={tab.path}
|
||||
className={({ isActive }) => `nav-tab${isActive ? ' active' : ''}`}
|
||||
>
|
||||
{tab.label}
|
||||
</NavLink>
|
||||
))}
|
||||
{user?.isAdmin && (
|
||||
<NavLink to="/admin" className={({ isActive }) => `nav-tab${isActive ? ' active' : ''}`}>
|
||||
Administración
|
||||
</NavLink>
|
||||
)}
|
||||
<button type="button" className="nav-tab logout" onClick={handleLogout}>
|
||||
Salir
|
||||
</button>
|
||||
</nav>
|
||||
<main className="main-content">{children}</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
174
frontend/src/components/PersonalSheet.jsx
Normal file
174
frontend/src/components/PersonalSheet.jsx
Normal file
@@ -0,0 +1,174 @@
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import { sheetsApi } from '../api/client';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { emptyMensualizado, emptyEventual, formatMoney } from '../utils/calc';
|
||||
|
||||
const MAX_MENSUAL = 10;
|
||||
const MAX_EVENTUAL = 5;
|
||||
|
||||
function rowCostMensual(r) {
|
||||
return (Number(r.sueldoBase) || 0) + (Number(r.cargasSociales) || 0) + (Number(r.bonos) || 0);
|
||||
}
|
||||
|
||||
export default function PersonalSheet() {
|
||||
const { canEdit } = useAuth();
|
||||
const editable = canEdit('personal');
|
||||
const [mensualizados, setMensualizados] = useState([emptyMensualizado()]);
|
||||
const [eventuales, setEventuales] = useState([emptyEventual()]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [message, setMessage] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
try {
|
||||
const data = await sheetsApi.get('personal');
|
||||
setMensualizados(
|
||||
data.mensualizados?.length ? data.mensualizados.slice(0, MAX_MENSUAL) : [emptyMensualizado()]
|
||||
);
|
||||
setEventuales(data.eventuales?.length ? data.eventuales : [emptyEventual()]);
|
||||
} catch (e) {
|
||||
setError(e.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
})();
|
||||
}, []);
|
||||
|
||||
const total = useMemo(() => {
|
||||
const m = mensualizados.reduce((a, r) => a + rowCostMensual(r), 0);
|
||||
const e = eventuales.reduce((a, r) => a + (Number(r.pagoDiario) || 0), 0);
|
||||
return m + e;
|
||||
}, [mensualizados, eventuales]);
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!editable) return;
|
||||
setSaving(true);
|
||||
setMessage(null);
|
||||
setError(null);
|
||||
try {
|
||||
await sheetsApi.save('personal', { mensualizados, eventuales });
|
||||
setMessage('Planilla de personal guardada');
|
||||
} catch (e) {
|
||||
setError(e.message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const updateMensual = (i, field, value) =>
|
||||
setMensualizados((p) => p.map((r, idx) => (idx === i ? { ...r, [field]: value } : r)));
|
||||
const updateEventual = (i, field, value) =>
|
||||
setEventuales((p) => p.map((r, idx) => (idx === i ? { ...r, [field]: value } : r)));
|
||||
|
||||
if (loading) return <p className="loading">Cargando planilla…</p>;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="page-title">Planilla de Personal</h1>
|
||||
{error && <div className="alert alert-error">{error}</div>}
|
||||
{message && <div className="alert alert-success">{message}</div>}
|
||||
|
||||
<div className="toolbar">
|
||||
{editable && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-icon"
|
||||
disabled={mensualizados.length >= MAX_MENSUAL}
|
||||
onClick={() => setMensualizados((p) => (p.length < MAX_MENSUAL ? [...p, emptyMensualizado()] : p))}
|
||||
title="Agregar mensualizado"
|
||||
>
|
||||
+ Mensual
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary btn-icon"
|
||||
disabled={eventuales.length >= MAX_EVENTUAL}
|
||||
onClick={() => setEventuales((p) => (p.length < MAX_EVENTUAL ? [...p, emptyEventual()] : p))}
|
||||
title="Agregar eventual"
|
||||
>
|
||||
+ Eventual
|
||||
</button>
|
||||
<button type="button" className="btn btn-primary" onClick={handleSave} disabled={saving}>
|
||||
Guardar
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="card" style={{ marginBottom: '1rem' }}>
|
||||
<h2 style={{ marginTop: 0, fontSize: '1.1rem' }}>Funcionarios mensualizados (máx. {MAX_MENSUAL})</h2>
|
||||
<div className="sheet-table-wrap">
|
||||
<table className="sheet-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Nombre</th>
|
||||
<th>Sueldo base</th>
|
||||
<th>Cargas sociales</th>
|
||||
<th>Bonos</th>
|
||||
<th>Subtotal</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{mensualizados.map((row, i) => (
|
||||
<tr key={i}>
|
||||
<td>
|
||||
<input value={row.nombre || ''} disabled={!editable} onChange={(e) => updateMensual(i, 'nombre', e.target.value)} />
|
||||
</td>
|
||||
<td>
|
||||
<input type="number" value={row.sueldoBase ?? ''} disabled={!editable} onChange={(e) => updateMensual(i, 'sueldoBase', e.target.value)} />
|
||||
</td>
|
||||
<td>
|
||||
<input type="number" value={row.cargasSociales ?? ''} disabled={!editable} onChange={(e) => updateMensual(i, 'cargasSociales', e.target.value)} />
|
||||
</td>
|
||||
<td>
|
||||
<input type="number" value={row.bonos ?? ''} disabled={!editable} onChange={(e) => updateMensual(i, 'bonos', e.target.value)} />
|
||||
</td>
|
||||
<td className="computed">{formatMoney(rowCostMensual(row))}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<h2 style={{ marginTop: 0, fontSize: '1.1rem' }}>Trabajadores eventuales por día (máx. {MAX_EVENTUAL} filas)</h2>
|
||||
<div className="sheet-table-wrap">
|
||||
<table className="sheet-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Fecha</th>
|
||||
<th>Nombre</th>
|
||||
<th>Pago diario</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{eventuales.map((row, i) => (
|
||||
<tr key={i}>
|
||||
<td>
|
||||
<input type="date" value={row.fecha || ''} disabled={!editable} onChange={(e) => updateEventual(i, 'fecha', e.target.value)} />
|
||||
</td>
|
||||
<td>
|
||||
<input value={row.nombre || ''} disabled={!editable} onChange={(e) => updateEventual(i, 'nombre', e.target.value)} />
|
||||
</td>
|
||||
<td>
|
||||
<input type="number" value={row.pagoDiario ?? ''} disabled={!editable} onChange={(e) => updateEventual(i, 'pagoDiario', e.target.value)} />
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="totals-bar" style={{ marginTop: '1rem' }}>
|
||||
<span>
|
||||
Sumatoria total personal: <strong>{formatMoney(total)}</strong>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
57
frontend/src/context/AuthContext.jsx
Normal file
57
frontend/src/context/AuthContext.jsx
Normal file
@@ -0,0 +1,57 @@
|
||||
import { createContext, useContext, useState, useEffect, useCallback } from 'react';
|
||||
import { authApi } from '../api/client';
|
||||
|
||||
const AuthContext = createContext(null);
|
||||
|
||||
export function AuthProvider({ children }) {
|
||||
const [user, setUser] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const loadUser = useCallback(async () => {
|
||||
const token = localStorage.getItem('donmarco_token');
|
||||
if (!token) {
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const me = await authApi.me();
|
||||
setUser(me);
|
||||
} catch {
|
||||
localStorage.removeItem('donmarco_token');
|
||||
setUser(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
loadUser();
|
||||
}, [loadUser]);
|
||||
|
||||
const login = async (username, password) => {
|
||||
const data = await authApi.login(username, password);
|
||||
localStorage.setItem('donmarco_token', data.token);
|
||||
setUser(data.user);
|
||||
return data.user;
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
localStorage.removeItem('donmarco_token');
|
||||
setUser(null);
|
||||
};
|
||||
|
||||
const canView = (sheet) => user?.isAdmin || user?.permissions?.[sheet]?.view;
|
||||
const canEdit = (sheet) => user?.isAdmin || user?.permissions?.[sheet]?.edit;
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, loading, login, logout, canView, canEdit }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const ctx = useContext(AuthContext);
|
||||
if (!ctx) throw new Error('useAuth debe usarse dentro de AuthProvider');
|
||||
return ctx;
|
||||
}
|
||||
16
frontend/src/main.jsx
Normal file
16
frontend/src/main.jsx
Normal file
@@ -0,0 +1,16 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
import App from './App';
|
||||
import { AuthProvider } from './context/AuthContext';
|
||||
import './styles/global.css';
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')).render(
|
||||
<React.StrictMode>
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<App />
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
</React.StrictMode>
|
||||
);
|
||||
191
frontend/src/pages/AdminPage.jsx
Normal file
191
frontend/src/pages/AdminPage.jsx
Normal file
@@ -0,0 +1,191 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { usersApi } from '../api/client';
|
||||
|
||||
const SHEET_LABELS = {
|
||||
ventas: 'Ventas',
|
||||
servicios: 'Servicios',
|
||||
alquileres: 'Alquileres',
|
||||
gastos_diarios: 'Gastos diarios',
|
||||
gastos_fijos: 'Gastos fijos',
|
||||
personal: 'Personal',
|
||||
reportes: 'Reportes',
|
||||
};
|
||||
|
||||
const SHEET_KEYS = Object.keys(SHEET_LABELS);
|
||||
|
||||
function emptyPerms() {
|
||||
return Object.fromEntries(SHEET_KEYS.map((k) => [k, { view: false, edit: false }]));
|
||||
}
|
||||
|
||||
export default function AdminPage() {
|
||||
const [users, setUsers] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [newUser, setNewUser] = useState({ username: '', password: '', permissions: emptyPerms() });
|
||||
|
||||
const load = async () => {
|
||||
try {
|
||||
setUsers(await usersApi.list());
|
||||
} catch (e) {
|
||||
setError(e.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, []);
|
||||
|
||||
const handleCreate = async (e) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
try {
|
||||
await usersApi.create(newUser);
|
||||
setNewUser({ username: '', password: '', permissions: emptyPerms() });
|
||||
await load();
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const updateUserPerms = async (user, sheet, field, value) => {
|
||||
const permissions = { ...user.permissions, [sheet]: { ...user.permissions[sheet], [field]: value } };
|
||||
try {
|
||||
await usersApi.update(user.id, { permissions });
|
||||
await load();
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleActive = async (user) => {
|
||||
if (user.isAdmin) return;
|
||||
try {
|
||||
await usersApi.update(user.id, { active: !user.active });
|
||||
await load();
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) return <p className="loading">Cargando usuarios…</p>;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="page-title">Administración de usuarios</h1>
|
||||
<p style={{ color: 'var(--muted)' }}>
|
||||
El superusuario <strong>JEFE</strong> puede crear usuarios, asignar contraseñas y habilitar acceso por planilla.
|
||||
</p>
|
||||
{error && <div className="alert alert-error">{error}</div>}
|
||||
|
||||
<div className="card admin-grid" style={{ marginBottom: '1.5rem' }}>
|
||||
<h2 style={{ marginTop: 0 }}>Nuevo usuario</h2>
|
||||
<form onSubmit={handleCreate}>
|
||||
<div className="form-group">
|
||||
<label>Usuario</label>
|
||||
<input
|
||||
value={newUser.username}
|
||||
onChange={(e) => setNewUser((p) => ({ ...p, username: e.target.value }))}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>Contraseña</label>
|
||||
<input
|
||||
type="password"
|
||||
value={newUser.password}
|
||||
onChange={(e) => setNewUser((p) => ({ ...p, password: e.target.value }))}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<p style={{ fontSize: '0.85rem' }}>Permisos por planilla:</p>
|
||||
<div className="perm-grid">
|
||||
{SHEET_KEYS.filter((k) => k !== 'reportes').map((key) => (
|
||||
<div key={key} className="perm-item">
|
||||
<strong>{SHEET_LABELS[key]}</strong>
|
||||
<label className="checkbox-row">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={newUser.permissions[key]?.view}
|
||||
onChange={(e) =>
|
||||
setNewUser((p) => ({
|
||||
...p,
|
||||
permissions: {
|
||||
...p.permissions,
|
||||
[key]: { ...p.permissions[key], view: e.target.checked },
|
||||
},
|
||||
}))
|
||||
}
|
||||
/>
|
||||
Ver
|
||||
</label>
|
||||
<label className="checkbox-row">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={newUser.permissions[key]?.edit}
|
||||
onChange={(e) =>
|
||||
setNewUser((p) => ({
|
||||
...p,
|
||||
permissions: {
|
||||
...p.permissions,
|
||||
[key]: { ...p.permissions[key], edit: e.target.checked },
|
||||
},
|
||||
}))
|
||||
}
|
||||
/>
|
||||
Editar
|
||||
</label>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<button type="submit" className="btn btn-primary" style={{ marginTop: '1rem' }}>
|
||||
Crear usuario
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<h2 style={{ marginTop: 0 }}>Usuarios del sistema</h2>
|
||||
{users.map((u) => (
|
||||
<div key={u.id} style={{ borderBottom: '1px solid var(--border)', padding: '1rem 0' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '1rem', flexWrap: 'wrap' }}>
|
||||
<strong>{u.username}</strong>
|
||||
{u.isAdmin && <span style={{ color: 'var(--accent)' }}>Administrador</span>}
|
||||
{!u.isAdmin && (
|
||||
<button type="button" className="btn btn-secondary" onClick={() => toggleActive(u)}>
|
||||
{u.active ? 'Deshabilitar' : 'Habilitar'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{!u.isAdmin && (
|
||||
<div className="perm-grid" style={{ marginTop: '0.75rem' }}>
|
||||
{SHEET_KEYS.map((key) => (
|
||||
<div key={key} className="perm-item">
|
||||
<span>{SHEET_LABELS[key]}</span>
|
||||
<label className="checkbox-row">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={u.permissions?.[key]?.view}
|
||||
onChange={(e) => updateUserPerms(u, key, 'view', e.target.checked)}
|
||||
/>
|
||||
Ver
|
||||
</label>
|
||||
<label className="checkbox-row">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={u.permissions?.[key]?.edit}
|
||||
onChange={(e) => updateUserPerms(u, key, 'edit', e.target.checked)}
|
||||
/>
|
||||
Editar
|
||||
</label>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
23
frontend/src/pages/HomePage.jsx
Normal file
23
frontend/src/pages/HomePage.jsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
|
||||
export default function HomePage() {
|
||||
const { user } = useAuth();
|
||||
|
||||
return (
|
||||
<div className="card">
|
||||
<h1 className="page-title">Menú principal</h1>
|
||||
<p>
|
||||
Bienvenido, <strong>{user?.username}</strong>. Utilice la barra superior para acceder a cada planilla.
|
||||
</p>
|
||||
<ul style={{ color: 'var(--muted)', lineHeight: 1.8 }}>
|
||||
<li>Planillas de ingresos: Ventas, Servicios y Alquileres</li>
|
||||
<li>Planillas de egresos: Gastos Diarios y Gastos Fijos</li>
|
||||
<li>Planilla de Personal y Reportes consolidados</li>
|
||||
{user?.isAdmin && <li>Panel de Administración para gestionar usuarios y permisos</li>}
|
||||
</ul>
|
||||
<p style={{ fontSize: '0.85rem', color: 'var(--muted)', marginTop: '1.5rem' }}>
|
||||
Los datos se almacenan en el servidor de la red local. Use el botón <strong>+</strong> en cada planilla para agregar filas y <strong>Guardar</strong> para persistir.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
62
frontend/src/pages/LoginPage.jsx
Normal file
62
frontend/src/pages/LoginPage.jsx
Normal file
@@ -0,0 +1,62 @@
|
||||
import { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
|
||||
export default function LoginPage() {
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { login } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
try {
|
||||
await login(username.trim(), password);
|
||||
navigate('/');
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="login-page">
|
||||
<div className="card login-card">
|
||||
<h1>Don Marco</h1>
|
||||
<p className="subtitle">Administración financiera — Ingreso con credenciales</p>
|
||||
{error && <div className="alert alert-error">{error}</div>}
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="form-group">
|
||||
<label htmlFor="user">Usuario</label>
|
||||
<input
|
||||
id="user"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
autoComplete="username"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label htmlFor="pass">Contraseña</label>
|
||||
<input
|
||||
id="pass"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<button type="submit" className="btn btn-primary" style={{ width: '100%' }} disabled={loading}>
|
||||
{loading ? 'Ingresando…' : 'Iniciar sesión'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
175
frontend/src/pages/ReportesPage.jsx
Normal file
175
frontend/src/pages/ReportesPage.jsx
Normal file
@@ -0,0 +1,175 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { reportsApi } from '../api/client';
|
||||
import { formatMoney } from '../utils/calc';
|
||||
|
||||
const INCLUDE_OPTS = [
|
||||
{ key: 'ventas', label: 'Ventas' },
|
||||
{ key: 'servicios', label: 'Servicios' },
|
||||
{ key: 'alquileres', label: 'Alquileres' },
|
||||
{ key: 'gastos_diarios', label: 'Gastos diarios' },
|
||||
{ key: 'gastos_fijos', label: 'Gastos fijos' },
|
||||
{ key: 'personal', label: 'Personal' },
|
||||
];
|
||||
|
||||
export default function ReportesPage() {
|
||||
const [tipo, setTipo] = useState('mensual');
|
||||
const [desde, setDesde] = useState('');
|
||||
const [hasta, setHasta] = useState('');
|
||||
const [include, setInclude] = useState(
|
||||
Object.fromEntries(INCLUDE_OPTS.map((o) => [o.key, true]))
|
||||
);
|
||||
const [report, setReport] = useState(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const loadReport = async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await reportsApi.get({
|
||||
tipo,
|
||||
desde: desde || undefined,
|
||||
hasta: hasta || undefined,
|
||||
include: JSON.stringify(include),
|
||||
});
|
||||
setReport(data);
|
||||
} catch (e) {
|
||||
setError(e.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
loadReport();
|
||||
}, []);
|
||||
|
||||
const toggleInclude = (key) => setInclude((p) => ({ ...p, [key]: !p[key] }));
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="page-title">Planilla de Reportes</h1>
|
||||
|
||||
<div className="card" style={{ marginBottom: '1rem' }}>
|
||||
<div className="toolbar" style={{ flexWrap: 'wrap' }}>
|
||||
<label>
|
||||
Tipo de reporte{' '}
|
||||
<select value={tipo} onChange={(e) => setTipo(e.target.value)}>
|
||||
<option value="diario">Diario</option>
|
||||
<option value="semanal">Semanal</option>
|
||||
<option value="mensual">Mensual</option>
|
||||
<option value="custom">Rango personalizado</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Desde <input type="date" value={desde} onChange={(e) => setDesde(e.target.value)} />
|
||||
</label>
|
||||
<label>
|
||||
Hasta <input type="date" value={hasta} onChange={(e) => setHasta(e.target.value)} />
|
||||
</label>
|
||||
<button type="button" className="btn btn-primary" onClick={loadReport} disabled={loading}>
|
||||
{loading ? 'Calculando…' : 'Generar reporte'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p style={{ fontSize: '0.85rem', color: 'var(--muted)' }}>Planillas a incluir en el cálculo:</p>
|
||||
<div className="perm-grid">
|
||||
{INCLUDE_OPTS.map((o) => (
|
||||
<label key={o.key} className="perm-item checkbox-row">
|
||||
<input type="checkbox" checked={!!include[o.key]} onChange={() => toggleInclude(o.key)} />
|
||||
{o.label}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && <div className="alert alert-error">{error}</div>}
|
||||
|
||||
{report && (
|
||||
<>
|
||||
<div className="card">
|
||||
<h2 style={{ marginTop: 0 }}>Desglose por planilla</h2>
|
||||
<table className="sheet-table" style={{ minWidth: 'auto' }}>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>Ventas (ingresos)</td>
|
||||
<td className="computed">{formatMoney(report.desglose.ventas.totalIngresos)}</td>
|
||||
<td>Utilidad: {formatMoney(report.desglose.ventas.totalUtilidad)}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Servicios</td>
|
||||
<td className="computed">{formatMoney(report.desglose.servicios.totalIngresos)}</td>
|
||||
<td>Utilidad: {formatMoney(report.desglose.servicios.totalUtilidad)}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Alquileres</td>
|
||||
<td className="computed">{formatMoney(report.desglose.alquileres.totalIngresos)}</td>
|
||||
<td>Utilidad: {formatMoney(report.desglose.alquileres.totalUtilidad)}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Gastos diarios</td>
|
||||
<td colSpan={2} className="computed">{formatMoney(report.desglose.gastosDiarios.total)}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Gastos fijos</td>
|
||||
<td colSpan={2} className="computed">{formatMoney(report.desglose.gastosFijos.total)}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Gastos variables (clasificados)</td>
|
||||
<td colSpan={2} className="computed">{formatMoney(report.desglose.gastosVariables.total)}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Planilla de personal</td>
|
||||
<td colSpan={2} className="computed">{formatMoney(report.desglose.personal.total)}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div className="totals-bar" style={{ marginTop: '1rem' }}>
|
||||
<span>Total ingresos: {formatMoney(report.totales.totalIngresos)}</span>
|
||||
<span>Total gastos: {formatMoney(report.totales.totalGastos)}</span>
|
||||
<span>Total personal: {formatMoney(report.totales.totalPersonal)}</span>
|
||||
</div>
|
||||
|
||||
{report.cierreSemanal && Object.keys(report.cierreSemanal).length > 0 && (
|
||||
<div className="card" style={{ marginTop: '1rem' }}>
|
||||
<h3>Cierre semanal — gastos diarios por semana</h3>
|
||||
<ul>
|
||||
{Object.entries(report.cierreSemanal).map(([sem, monto]) => (
|
||||
<li key={sem}>
|
||||
Semana desde {sem}: <strong>{formatMoney(monto)}</strong>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p>
|
||||
Total gastos semanales en periodo:{' '}
|
||||
<strong>{formatMoney(report.totalGastosSemanales)}</strong>
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{report.cierreMensual && (
|
||||
<div className="card" style={{ marginTop: '1rem' }}>
|
||||
<h3>Cierre mensual consolidado</h3>
|
||||
<p>Gastos fijos en periodo: {formatMoney(report.cierreMensual.gastosFijosEnPeriodo)}</p>
|
||||
<p>
|
||||
Total gastos mensuales consolidado:{' '}
|
||||
<strong>{formatMoney(report.cierreMensual.totalGastosMensualesConsolidado)}</strong>
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={`report-result ${report.totales.estado}`}>
|
||||
Resultado neto ({tipo}): {formatMoney(report.totales.resultadoNeto)} —{' '}
|
||||
{report.totales.estado === 'utilidad' ? 'UTILIDAD (Ganancia)' : 'PÉRDIDA'}
|
||||
</div>
|
||||
|
||||
<p style={{ fontSize: '0.8rem', color: 'var(--muted)', marginTop: '0.5rem' }}>
|
||||
Fórmula: (Ventas + Alquileres + Servicios) − Total Gastos − Total Personal
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
361
frontend/src/styles/global.css
Normal file
361
frontend/src/styles/global.css
Normal file
@@ -0,0 +1,361 @@
|
||||
:root {
|
||||
--bg: #0f1419;
|
||||
--surface: #1a2332;
|
||||
--surface2: #243044;
|
||||
--border: #2d3f56;
|
||||
--text: #e8edf4;
|
||||
--muted: #8b9cb3;
|
||||
--accent: #3d9cf5;
|
||||
--accent-hover: #5aadff;
|
||||
--success: #34c759;
|
||||
--danger: #ff5c5c;
|
||||
--warning: #ffb020;
|
||||
--radius: 10px;
|
||||
--shadow: 0 4px 24px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: 'DM Sans', system-ui, sans-serif;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
min-height: 100vh;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
#root {
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--accent);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
button {
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
input,
|
||||
select,
|
||||
textarea {
|
||||
font-family: inherit;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.app-shell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.navbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.35rem;
|
||||
padding: 0.75rem 1rem;
|
||||
background: var(--surface);
|
||||
border-bottom: 1px solid var(--border);
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
}
|
||||
|
||||
.nav-tab {
|
||||
padding: 0.5rem 0.85rem;
|
||||
border-radius: var(--radius);
|
||||
border: 1px solid transparent;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
font-size: 0.85rem;
|
||||
font-weight: 500;
|
||||
transition: all 0.15s;
|
||||
}
|
||||
|
||||
.nav-tab:hover {
|
||||
color: var(--text);
|
||||
background: var(--surface2);
|
||||
}
|
||||
|
||||
.nav-tab.active {
|
||||
color: var(--text);
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.nav-tab.logout {
|
||||
margin-left: auto;
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.nav-tab.logout:hover {
|
||||
background: rgba(255, 92, 92, 0.15);
|
||||
}
|
||||
|
||||
.main-content {
|
||||
flex: 1;
|
||||
padding: 1.25rem;
|
||||
max-width: 1400px;
|
||||
margin: 0 auto;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.page-title {
|
||||
margin: 0 0 1rem;
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.card {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 1.25rem;
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.login-page {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 100vh;
|
||||
padding: 1rem;
|
||||
background: radial-gradient(ellipse at top, #1a2a42 0%, var(--bg) 60%);
|
||||
}
|
||||
|
||||
.login-card {
|
||||
width: 100%;
|
||||
max-width: 400px;
|
||||
}
|
||||
|
||||
.login-card h1 {
|
||||
margin: 0 0 0.25rem;
|
||||
font-size: 1.75rem;
|
||||
}
|
||||
|
||||
.login-card .subtitle {
|
||||
color: var(--muted);
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
display: block;
|
||||
margin-bottom: 0.35rem;
|
||||
font-size: 0.85rem;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.form-group input,
|
||||
.form-group select {
|
||||
width: 100%;
|
||||
padding: 0.65rem 0.75rem;
|
||||
border-radius: var(--radius);
|
||||
border: 1px solid var(--border);
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
padding: 0.55rem 1rem;
|
||||
border-radius: var(--radius);
|
||||
border: none;
|
||||
font-weight: 600;
|
||||
font-size: 0.9rem;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background: var(--accent-hover);
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: var(--surface2);
|
||||
color: var(--text);
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
background: transparent;
|
||||
color: var(--danger);
|
||||
border: 1px solid var(--danger);
|
||||
}
|
||||
|
||||
.btn-icon {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
padding: 0;
|
||||
justify-content: center;
|
||||
font-size: 1.25rem;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 1rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.sheet-table-wrap {
|
||||
overflow-x: auto;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.sheet-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.85rem;
|
||||
min-width: 800px;
|
||||
}
|
||||
|
||||
.sheet-table th,
|
||||
.sheet-table td {
|
||||
padding: 0.45rem 0.5rem;
|
||||
border: 1px solid var(--border);
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.sheet-table th {
|
||||
background: var(--surface2);
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sheet-table input,
|
||||
.sheet-table select {
|
||||
width: 100%;
|
||||
min-width: 70px;
|
||||
padding: 0.35rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.sheet-table .computed {
|
||||
color: var(--accent);
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.totals-bar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 1.5rem;
|
||||
padding: 1rem;
|
||||
background: var(--surface2);
|
||||
border-radius: var(--radius);
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.totals-bar strong {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.alert {
|
||||
padding: 0.75rem 1rem;
|
||||
border-radius: var(--radius);
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.alert-error {
|
||||
background: rgba(255, 92, 92, 0.15);
|
||||
border: 1px solid var(--danger);
|
||||
color: #ffb0b0;
|
||||
}
|
||||
|
||||
.alert-success {
|
||||
background: rgba(52, 199, 89, 0.15);
|
||||
border: 1px solid var(--success);
|
||||
}
|
||||
|
||||
.alert-info {
|
||||
background: rgba(61, 156, 245, 0.12);
|
||||
border: 1px solid var(--accent);
|
||||
}
|
||||
|
||||
.report-result {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
padding: 1rem;
|
||||
border-radius: var(--radius);
|
||||
text-align: center;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.report-result.utilidad {
|
||||
background: rgba(52, 199, 89, 0.2);
|
||||
color: var(--success);
|
||||
}
|
||||
|
||||
.report-result.perdida {
|
||||
background: rgba(255, 92, 92, 0.2);
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.admin-grid {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.perm-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
|
||||
gap: 0.5rem;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
.perm-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
font-size: 0.8rem;
|
||||
padding: 0.5rem;
|
||||
background: var(--bg);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.checkbox-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.loading {
|
||||
text-align: center;
|
||||
padding: 3rem;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.navbar {
|
||||
padding: 0.5rem;
|
||||
}
|
||||
.nav-tab {
|
||||
font-size: 0.75rem;
|
||||
padding: 0.4rem 0.6rem;
|
||||
}
|
||||
.main-content {
|
||||
padding: 0.75rem;
|
||||
}
|
||||
}
|
||||
47
frontend/src/utils/calc.js
Normal file
47
frontend/src/utils/calc.js
Normal file
@@ -0,0 +1,47 @@
|
||||
export function calcIngresoRow(row) {
|
||||
const cantidad = Number(row.cantidad) || 0;
|
||||
const precioUnitario = Number(row.precioUnitario) || 0;
|
||||
const costoUnitario = Number(row.costoUnitario) || 0;
|
||||
const precioTotal = cantidad * precioUnitario;
|
||||
const utilidad = precioTotal - cantidad * costoUnitario;
|
||||
return { precioTotal, utilidad };
|
||||
}
|
||||
|
||||
export function formatMoney(n) {
|
||||
return new Intl.NumberFormat('es-AR', {
|
||||
style: 'currency',
|
||||
currency: 'ARS',
|
||||
minimumFractionDigits: 2,
|
||||
}).format(n || 0);
|
||||
}
|
||||
|
||||
export const emptyIngresoRow = () => ({
|
||||
fecha: '',
|
||||
cliente: '',
|
||||
detalle: '',
|
||||
cantidad: '',
|
||||
precioUnitario: '',
|
||||
costoUnitario: '',
|
||||
});
|
||||
|
||||
export const emptyGastoRow = () => ({
|
||||
fecha: '',
|
||||
detalle: '',
|
||||
impuestos: '',
|
||||
numeroFactura: '',
|
||||
monto: '',
|
||||
clasificacion: 'diario',
|
||||
});
|
||||
|
||||
export const emptyMensualizado = () => ({
|
||||
nombre: '',
|
||||
sueldoBase: '',
|
||||
cargasSociales: '',
|
||||
bonos: '',
|
||||
});
|
||||
|
||||
export const emptyEventual = () => ({
|
||||
fecha: '',
|
||||
nombre: '',
|
||||
pagoDiario: '',
|
||||
});
|
||||
16
frontend/vite.config.js
Normal file
16
frontend/vite.config.js
Normal file
@@ -0,0 +1,16 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
host: '0.0.0.0',
|
||||
port: 3000,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: process.env.VITE_API_PROXY || 'http://localhost:4000',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user