Initial commit
This commit is contained in:
193
lib/database/database_helper.dart
Normal file
193
lib/database/database_helper.dart
Normal file
@@ -0,0 +1,193 @@
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
import 'package:path/path.dart';
|
||||
import '../models/servicio.dart';
|
||||
import '../models/factura.dart';
|
||||
import '../models/configuracion.dart';
|
||||
|
||||
class DatabaseHelper {
|
||||
static final DatabaseHelper instance = DatabaseHelper._init();
|
||||
static Database? _database;
|
||||
|
||||
DatabaseHelper._init();
|
||||
|
||||
Future<Database> get database async {
|
||||
if (_database != null) return _database!;
|
||||
_database = await _initDB('hogarcontrol.db');
|
||||
return _database!;
|
||||
}
|
||||
|
||||
Future<Database> _initDB(String filePath) async {
|
||||
final dbPath = await getDatabasesPath();
|
||||
final path = join(dbPath, filePath);
|
||||
return await openDatabase(path, version: 1, onCreate: _createDB, onConfigure: _onConfigure);
|
||||
}
|
||||
|
||||
Future _onConfigure(Database db) async {
|
||||
await db.execute('PRAGMA foreign_keys = ON');
|
||||
}
|
||||
|
||||
Future _createDB(Database db, int version) async {
|
||||
await db.execute('''
|
||||
CREATE TABLE servicios (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
nombre TEXT NOT NULL,
|
||||
icono TEXT NOT NULL,
|
||||
color INTEGER NOT NULL,
|
||||
dia_vencimiento INTEGER NOT NULL,
|
||||
fecha_creacion TEXT NOT NULL
|
||||
)
|
||||
''');
|
||||
await db.execute('''
|
||||
CREATE TABLE facturas (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
servicio_id INTEGER NOT NULL,
|
||||
monto REAL NOT NULL,
|
||||
fecha_emision TEXT NOT NULL,
|
||||
fecha_vencimiento TEXT NOT NULL,
|
||||
estado TEXT NOT NULL DEFAULT 'Pendiente',
|
||||
nota TEXT,
|
||||
fecha_pago TEXT,
|
||||
FOREIGN KEY (servicio_id) REFERENCES servicios(id) ON DELETE CASCADE
|
||||
)
|
||||
''');
|
||||
await db.execute('''
|
||||
CREATE TABLE configuracion (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
dias_recordatorio TEXT NOT NULL DEFAULT '7,3,1,0',
|
||||
tema TEXT NOT NULL DEFAULT 'claro',
|
||||
moneda TEXT NOT NULL DEFAULT 'USD'
|
||||
)
|
||||
''');
|
||||
}
|
||||
|
||||
Future<int> insertServicio(Servicio servicio) async {
|
||||
final db = await database;
|
||||
return await db.insert('servicios', servicio.toMap()..remove('id'));
|
||||
}
|
||||
|
||||
Future<List<Servicio>> getServicios() async {
|
||||
final db = await database;
|
||||
final maps = await db.query('servicios', orderBy: 'nombre ASC');
|
||||
return maps.map((map) => Servicio.fromMap(map)).toList();
|
||||
}
|
||||
|
||||
Future<int> updateServicio(Servicio servicio) async {
|
||||
final db = await database;
|
||||
return await db.update('servicios', servicio.toMap(), where: 'id = ?', whereArgs: [servicio.id]);
|
||||
}
|
||||
|
||||
Future<int> deleteServicio(int id) async {
|
||||
final db = await database;
|
||||
return await db.delete('servicios', where: 'id = ?', whereArgs: [id]);
|
||||
}
|
||||
|
||||
Future<int> insertFactura(Factura factura) async {
|
||||
final db = await database;
|
||||
return await db.insert('facturas', factura.toMap()..remove('id'));
|
||||
}
|
||||
|
||||
Future<List<Factura>> getFacturas({String? estado, int? servicioId}) async {
|
||||
final db = await database;
|
||||
String? where;
|
||||
List<dynamic>? whereArgs;
|
||||
if (estado != null && servicioId != null) {
|
||||
where = 'estado = ? AND servicio_id = ?';
|
||||
whereArgs = [estado, servicioId];
|
||||
} else if (estado != null) {
|
||||
where = 'estado = ?';
|
||||
whereArgs = [estado];
|
||||
} else if (servicioId != null) {
|
||||
where = 'servicio_id = ?';
|
||||
whereArgs = [servicioId];
|
||||
}
|
||||
final maps = await db.query('facturas', where: where, whereArgs: whereArgs, orderBy: 'fecha_vencimiento DESC');
|
||||
return maps.map((map) => Factura.fromMap(map)).toList();
|
||||
}
|
||||
|
||||
Future<List<Factura>> getFacturasVencidas() async {
|
||||
final db = await database;
|
||||
final hoy = DateTime.now().toIso8601String().split('T')[0];
|
||||
final maps = await db.query('facturas',
|
||||
where: 'estado = ? AND fecha_vencimiento < ?', whereArgs: ['Pendiente', hoy], orderBy: 'fecha_vencimiento ASC');
|
||||
return maps.map((map) => Factura.fromMap(map)).toList();
|
||||
}
|
||||
|
||||
Future<List<Factura>> getFacturasPorMes(int year, int month) async {
|
||||
final db = await database;
|
||||
final mes = month.toString().padLeft(2, '0');
|
||||
final maps = await db.query('facturas',
|
||||
where: "fecha_vencimiento LIKE ?", whereArgs: ['$year-$mes%'], orderBy: 'fecha_vencimiento ASC');
|
||||
return maps.map((map) => Factura.fromMap(map)).toList();
|
||||
}
|
||||
|
||||
Future<List<Factura>> getFacturasPorRango(String inicio, String fin) async {
|
||||
final db = await database;
|
||||
final maps = await db.query('facturas',
|
||||
where: 'fecha_vencimiento BETWEEN ? AND ?', whereArgs: [inicio, fin], orderBy: 'fecha_vencimiento ASC');
|
||||
return maps.map((map) => Factura.fromMap(map)).toList();
|
||||
}
|
||||
|
||||
Future<double> getTotalGastadoMes(int year, int month) async {
|
||||
final db = await database;
|
||||
final mes = month.toString().padLeft(2, '0');
|
||||
final result = await db.rawQuery(
|
||||
"SELECT COALESCE(SUM(monto), 0) as total FROM facturas WHERE estado = 'Pagada' AND fecha_pago LIKE ?",
|
||||
['$year-$mes%']);
|
||||
return (result.first['total'] as num).toDouble();
|
||||
}
|
||||
|
||||
Future<Map<String, double>> getGastosPorServicio(int year, int month) async {
|
||||
final db = await database;
|
||||
final mes = month.toString().padLeft(2, '0');
|
||||
final result = await db.rawQuery('''
|
||||
SELECT s.nombre, COALESCE(SUM(f.monto), 0) as total
|
||||
FROM facturas f
|
||||
JOIN servicios s ON f.servicio_id = s.id
|
||||
WHERE f.estado = 'Pagada' AND f.fecha_pago LIKE ?
|
||||
GROUP BY s.nombre
|
||||
''', ['$year-$mes%']);
|
||||
final map = <String, double>{};
|
||||
for (final row in result) {
|
||||
map[row['nombre'] as String] = (row['total'] as num).toDouble();
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
Future<List<Map<String, dynamic>>> getGastoMensual(int year) async {
|
||||
final db = await database;
|
||||
return await db.rawQuery('''
|
||||
SELECT strftime('%m', fecha_pago) as mes, COALESCE(SUM(monto), 0) as total
|
||||
FROM facturas
|
||||
WHERE estado = 'Pagada' AND fecha_pago LIKE ?
|
||||
GROUP BY mes
|
||||
ORDER BY mes
|
||||
''', ['$year-%']);
|
||||
}
|
||||
|
||||
Future<int> updateFactura(Factura factura) async {
|
||||
final db = await database;
|
||||
return await db.update('facturas', factura.toMap(), where: 'id = ?', whereArgs: [factura.id]);
|
||||
}
|
||||
|
||||
Future<int> deleteFactura(int id) async {
|
||||
final db = await database;
|
||||
return await db.delete('facturas', where: 'id = ?', whereArgs: [id]);
|
||||
}
|
||||
|
||||
Future<Configuracion?> getConfiguracion() async {
|
||||
final db = await database;
|
||||
final maps = await db.query('configuracion', limit: 1);
|
||||
if (maps.isEmpty) return null;
|
||||
return Configuracion.fromMap(maps.first);
|
||||
}
|
||||
|
||||
Future<int> saveConfiguracion(Configuracion config) async {
|
||||
final db = await database;
|
||||
final existing = await getConfiguracion();
|
||||
if (existing != null) {
|
||||
return await db.update('configuracion', config.toMap()..remove('id'),
|
||||
where: 'id = ?', whereArgs: [existing.id]);
|
||||
}
|
||||
return await db.insert('configuracion', config.toMap()..remove('id'));
|
||||
}
|
||||
}
|
||||
38
lib/main.dart
Normal file
38
lib/main.dart
Normal file
@@ -0,0 +1,38 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'providers/servicio_provider.dart';
|
||||
import 'providers/factura_provider.dart';
|
||||
import 'providers/configuracion_provider.dart';
|
||||
import 'screens/splash_screen.dart';
|
||||
|
||||
void main() {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
runApp(
|
||||
MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider(create: (_) => ServicioProvider()),
|
||||
ChangeNotifierProvider(create: (_) => FacturaProvider()),
|
||||
ChangeNotifierProvider(create: (_) => ConfiguracionProvider()),
|
||||
],
|
||||
child: const HogarControlApp(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class HogarControlApp extends StatelessWidget {
|
||||
const HogarControlApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
title: 'HogarControl',
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: ThemeData(
|
||||
colorSchemeSeed: Colors.teal,
|
||||
useMaterial3: true,
|
||||
brightness: Brightness.light,
|
||||
),
|
||||
home: const SplashScreen(),
|
||||
);
|
||||
}
|
||||
}
|
||||
27
lib/models/configuracion.dart
Normal file
27
lib/models/configuracion.dart
Normal file
@@ -0,0 +1,27 @@
|
||||
class Configuracion {
|
||||
final int? id;
|
||||
final String diasRecordatorio;
|
||||
final String tema;
|
||||
final String moneda;
|
||||
|
||||
Configuracion({
|
||||
this.id,
|
||||
required this.diasRecordatorio,
|
||||
this.tema = 'claro',
|
||||
this.moneda = 'USD',
|
||||
});
|
||||
|
||||
Map<String, dynamic> toMap() => {
|
||||
'id': id,
|
||||
'dias_recordatorio': diasRecordatorio,
|
||||
'tema': tema,
|
||||
'moneda': moneda,
|
||||
};
|
||||
|
||||
factory Configuracion.fromMap(Map<String, dynamic> map) => Configuracion(
|
||||
id: map['id'] as int?,
|
||||
diasRecordatorio: map['dias_recordatorio'] as String,
|
||||
tema: map['tema'] as String? ?? 'claro',
|
||||
moneda: map['moneda'] as String? ?? 'USD',
|
||||
);
|
||||
}
|
||||
64
lib/models/factura.dart
Normal file
64
lib/models/factura.dart
Normal file
@@ -0,0 +1,64 @@
|
||||
class Factura {
|
||||
final int? id;
|
||||
final int servicioId;
|
||||
final double monto;
|
||||
final String fechaEmision;
|
||||
final String fechaVencimiento;
|
||||
final String estado;
|
||||
final String? nota;
|
||||
final String? fechaPago;
|
||||
|
||||
Factura({
|
||||
this.id,
|
||||
required this.servicioId,
|
||||
required this.monto,
|
||||
required this.fechaEmision,
|
||||
required this.fechaVencimiento,
|
||||
this.estado = 'Pendiente',
|
||||
this.nota,
|
||||
this.fechaPago,
|
||||
});
|
||||
|
||||
Factura copyWith({
|
||||
int? id,
|
||||
int? servicioId,
|
||||
double? monto,
|
||||
String? fechaEmision,
|
||||
String? fechaVencimiento,
|
||||
String? estado,
|
||||
String? nota,
|
||||
String? fechaPago,
|
||||
}) =>
|
||||
Factura(
|
||||
id: id ?? this.id,
|
||||
servicioId: servicioId ?? this.servicioId,
|
||||
monto: monto ?? this.monto,
|
||||
fechaEmision: fechaEmision ?? this.fechaEmision,
|
||||
fechaVencimiento: fechaVencimiento ?? this.fechaVencimiento,
|
||||
estado: estado ?? this.estado,
|
||||
nota: nota ?? this.nota,
|
||||
fechaPago: fechaPago ?? this.fechaPago,
|
||||
);
|
||||
|
||||
Map<String, dynamic> toMap() => {
|
||||
'id': id,
|
||||
'servicio_id': servicioId,
|
||||
'monto': monto,
|
||||
'fecha_emision': fechaEmision,
|
||||
'fecha_vencimiento': fechaVencimiento,
|
||||
'estado': estado,
|
||||
'nota': nota,
|
||||
'fecha_pago': fechaPago,
|
||||
};
|
||||
|
||||
factory Factura.fromMap(Map<String, dynamic> map) => Factura(
|
||||
id: map['id'] as int?,
|
||||
servicioId: map['servicio_id'] as int,
|
||||
monto: (map['monto'] as num).toDouble(),
|
||||
fechaEmision: map['fecha_emision'] as String,
|
||||
fechaVencimiento: map['fecha_vencimiento'] as String,
|
||||
estado: map['estado'] as String? ?? 'Pendiente',
|
||||
nota: map['nota'] as String?,
|
||||
fechaPago: map['fecha_pago'] as String?,
|
||||
);
|
||||
}
|
||||
35
lib/models/servicio.dart
Normal file
35
lib/models/servicio.dart
Normal file
@@ -0,0 +1,35 @@
|
||||
class Servicio {
|
||||
final int? id;
|
||||
final String nombre;
|
||||
final String icono;
|
||||
final int color;
|
||||
final int diaVencimiento;
|
||||
final String fechaCreacion;
|
||||
|
||||
Servicio({
|
||||
this.id,
|
||||
required this.nombre,
|
||||
required this.icono,
|
||||
required this.color,
|
||||
required this.diaVencimiento,
|
||||
required this.fechaCreacion,
|
||||
});
|
||||
|
||||
Map<String, dynamic> toMap() => {
|
||||
'id': id,
|
||||
'nombre': nombre,
|
||||
'icono': icono,
|
||||
'color': color,
|
||||
'dia_vencimiento': diaVencimiento,
|
||||
'fecha_creacion': fechaCreacion,
|
||||
};
|
||||
|
||||
factory Servicio.fromMap(Map<String, dynamic> map) => Servicio(
|
||||
id: map['id'] as int?,
|
||||
nombre: map['nombre'] as String,
|
||||
icono: map['icono'] as String,
|
||||
color: map['color'] as int,
|
||||
diaVencimiento: map['dia_vencimiento'] as int,
|
||||
fechaCreacion: map['fecha_creacion'] as String,
|
||||
);
|
||||
}
|
||||
40
lib/providers/configuracion_provider.dart
Normal file
40
lib/providers/configuracion_provider.dart
Normal file
@@ -0,0 +1,40 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../database/database_helper.dart';
|
||||
import '../models/configuracion.dart';
|
||||
import '../services/notification_service.dart';
|
||||
|
||||
class ConfiguracionProvider extends ChangeNotifier {
|
||||
final DatabaseHelper _db = DatabaseHelper.instance;
|
||||
Configuracion? _config;
|
||||
bool _cargando = false;
|
||||
|
||||
Configuracion? get config => _config;
|
||||
bool get cargando => _cargando;
|
||||
|
||||
Future<void> cargarConfiguracion() async {
|
||||
_cargando = true;
|
||||
notifyListeners();
|
||||
_config = await _db.getConfiguracion();
|
||||
if (_config == null) {
|
||||
_config = Configuracion(diasRecordatorio: '7,3,1,0');
|
||||
await _db.saveConfiguracion(_config!);
|
||||
}
|
||||
_cargando = false;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> guardarConfiguracion(Configuracion config) async {
|
||||
await _db.saveConfiguracion(config);
|
||||
_config = config;
|
||||
await NotificationService.instance.scheduleRecordatorios();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
List<int> get diasRecordatorioList {
|
||||
if (_config == null) return [7, 3, 1, 0];
|
||||
return _config!.diasRecordatorio
|
||||
.split(',')
|
||||
.map((e) => int.tryParse(e.trim()) ?? 0)
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
61
lib/providers/factura_provider.dart
Normal file
61
lib/providers/factura_provider.dart
Normal file
@@ -0,0 +1,61 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../database/database_helper.dart';
|
||||
import '../models/factura.dart';
|
||||
|
||||
class FacturaProvider extends ChangeNotifier {
|
||||
final DatabaseHelper _db = DatabaseHelper.instance;
|
||||
List<Factura> _facturas = [];
|
||||
List<Factura> _facturasVencidas = [];
|
||||
bool _cargando = false;
|
||||
|
||||
List<Factura> get facturas => _facturas;
|
||||
List<Factura> get facturasVencidas => _facturasVencidas;
|
||||
bool get cargando => _cargando;
|
||||
|
||||
Future<void> cargarFacturas({String? estado, int? servicioId}) async {
|
||||
_cargando = true;
|
||||
notifyListeners();
|
||||
_facturas = await _db.getFacturas(estado: estado, servicioId: servicioId);
|
||||
_facturasVencidas = await _db.getFacturasVencidas();
|
||||
_cargando = false;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> agregarFactura(Factura factura) async {
|
||||
await _db.insertFactura(factura);
|
||||
await cargarFacturas();
|
||||
}
|
||||
|
||||
Future<void> marcarPagada(int id) async {
|
||||
final factura = _facturas.firstWhere((f) => f.id == id);
|
||||
final hoy = DateTime.now().toIso8601String().split('T')[0];
|
||||
final actualizada = factura.copyWith(estado: 'Pagada', fechaPago: hoy);
|
||||
await _db.updateFactura(actualizada);
|
||||
await cargarFacturas();
|
||||
}
|
||||
|
||||
Future<void> eliminarFactura(int id) async {
|
||||
await _db.deleteFactura(id);
|
||||
await cargarFacturas();
|
||||
}
|
||||
|
||||
Future<double> totalGastadoMes(int year, int month) async {
|
||||
return await _db.getTotalGastadoMes(year, month);
|
||||
}
|
||||
|
||||
Future<Map<String, double>> gastosPorServicio(int year, int month) async {
|
||||
return await _db.getGastosPorServicio(year, month);
|
||||
}
|
||||
|
||||
Future<List<Map<String, dynamic>>> gastoMensual(int year) async {
|
||||
return await _db.getGastoMensual(year);
|
||||
}
|
||||
|
||||
Future<List<Factura>> facturasPorMes(int year, int month) async {
|
||||
return await _db.getFacturasPorMes(year, month);
|
||||
}
|
||||
|
||||
Future<List<Factura>> facturasPorRango(String inicio, String fin) async {
|
||||
return await _db.getFacturasPorRango(inicio, fin);
|
||||
}
|
||||
}
|
||||
35
lib/providers/servicio_provider.dart
Normal file
35
lib/providers/servicio_provider.dart
Normal file
@@ -0,0 +1,35 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../database/database_helper.dart';
|
||||
import '../models/servicio.dart';
|
||||
|
||||
class ServicioProvider extends ChangeNotifier {
|
||||
final DatabaseHelper _db = DatabaseHelper.instance;
|
||||
List<Servicio> _servicios = [];
|
||||
bool _cargando = false;
|
||||
|
||||
List<Servicio> get servicios => _servicios;
|
||||
bool get cargando => _cargando;
|
||||
|
||||
Future<void> cargarServicios() async {
|
||||
_cargando = true;
|
||||
notifyListeners();
|
||||
_servicios = await _db.getServicios();
|
||||
_cargando = false;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> agregarServicio(Servicio servicio) async {
|
||||
await _db.insertServicio(servicio);
|
||||
await cargarServicios();
|
||||
}
|
||||
|
||||
Future<void> actualizarServicio(Servicio servicio) async {
|
||||
await _db.updateServicio(servicio);
|
||||
await cargarServicios();
|
||||
}
|
||||
|
||||
Future<void> eliminarServicio(int id) async {
|
||||
await _db.deleteServicio(id);
|
||||
await cargarServicios();
|
||||
}
|
||||
}
|
||||
123
lib/screens/calendario_screen.dart
Normal file
123
lib/screens/calendario_screen.dart
Normal file
@@ -0,0 +1,123 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:table_calendar/table_calendar.dart';
|
||||
import '../providers/factura_provider.dart';
|
||||
import '../providers/servicio_provider.dart';
|
||||
import '../providers/configuracion_provider.dart';
|
||||
|
||||
class CalendarioScreen extends StatefulWidget {
|
||||
const CalendarioScreen({super.key});
|
||||
|
||||
@override
|
||||
State<CalendarioScreen> createState() => _CalendarioScreenState();
|
||||
}
|
||||
|
||||
class _CalendarioScreenState extends State<CalendarioScreen> {
|
||||
DateTime _focusedDay = DateTime.now();
|
||||
DateTime? _selectedDay;
|
||||
Map<DateTime, List<Map<String, dynamic>>> _eventos = {};
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_cargarEventos();
|
||||
}
|
||||
|
||||
void _cargarEventos() {
|
||||
final facturaProv = context.read<FacturaProvider>();
|
||||
final servicioProv = context.read<ServicioProvider>();
|
||||
facturaProv.cargarFacturas().then((_) {
|
||||
_construirEventos(facturaProv, servicioProv);
|
||||
});
|
||||
}
|
||||
|
||||
void _construirEventos(FacturaProvider facturaProv, ServicioProvider servicioProv) {
|
||||
final eventos = <DateTime, List<Map<String, dynamic>>>{};
|
||||
for (final f in facturaProv.facturas) {
|
||||
final fecha = DateTime.tryParse(f.fechaVencimiento);
|
||||
if (fecha == null) continue;
|
||||
final servicio = servicioProv.servicios.where((s) => s.id == f.servicioId).firstOrNull;
|
||||
final day = DateTime(fecha.year, fecha.month, fecha.day);
|
||||
eventos.putIfAbsent(day, () => []).add({
|
||||
'servicio': servicio?.nombre ?? 'Desconocido',
|
||||
'monto': f.monto,
|
||||
'estado': f.estado,
|
||||
'color': Color(servicio?.color ?? 0xFF6200EE),
|
||||
});
|
||||
}
|
||||
setState(() => _eventos = eventos);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
context.watch<FacturaProvider>();
|
||||
context.watch<ServicioProvider>();
|
||||
final configProv = context.watch<ConfiguracionProvider>();
|
||||
final symbol = configProv.config?.moneda == 'USD' ? '\$' : configProv.config?.moneda == 'EUR' ? '€' : 'MX\$';
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Calendario de pagos')),
|
||||
body: Column(
|
||||
children: [
|
||||
TableCalendar(
|
||||
firstDay: DateTime(2024),
|
||||
lastDay: DateTime(2035),
|
||||
focusedDay: _focusedDay,
|
||||
selectedDayPredicate: (day) => isSameDay(_selectedDay, day),
|
||||
eventLoader: (day) {
|
||||
final d = DateTime(day.year, day.month, day.day);
|
||||
return _eventos[d] ?? [];
|
||||
},
|
||||
calendarStyle: CalendarStyle(
|
||||
todayDecoration: BoxDecoration(color: Theme.of(context).colorScheme.primary.withValues(alpha: 0.5), shape: BoxShape.circle),
|
||||
selectedDecoration: BoxDecoration(color: Theme.of(context).colorScheme.primary, shape: BoxShape.circle),
|
||||
markerDecoration: BoxDecoration(color: Theme.of(context).colorScheme.secondary, shape: BoxShape.circle),
|
||||
),
|
||||
headerStyle: const HeaderStyle(formatButtonVisible: false, titleCentered: true),
|
||||
onDaySelected: (selected, focused) {
|
||||
setState(() {
|
||||
_selectedDay = selected;
|
||||
_focusedDay = focused;
|
||||
});
|
||||
},
|
||||
onPageChanged: (focused) => _focusedDay = focused,
|
||||
calendarBuilders: CalendarBuilders(
|
||||
markerBuilder: (context, date, events) {
|
||||
if (events.isEmpty) return null;
|
||||
final pendientes = events.where((e) => (e as Map)['estado'] == 'Pendiente').length;
|
||||
final pagadas = events.where((e) => (e as Map)['estado'] == 'Pagada').length;
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (pendientes > 0)
|
||||
Container(margin: const EdgeInsets.only(right: 2), width: 6, height: 6, decoration: BoxDecoration(color: Colors.red, shape: BoxShape.circle)),
|
||||
if (pagadas > 0)
|
||||
Container(width: 6, height: 6, decoration: BoxDecoration(color: Colors.green, shape: BoxShape.circle)),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
const Divider(),
|
||||
Expanded(
|
||||
child: _selectedDay == null || (_eventos[DateTime(_selectedDay!.year, _selectedDay!.month, _selectedDay!.day)]?.isEmpty ?? true)
|
||||
? Center(child: Text('Sin facturas en esta fecha', style: Theme.of(context).textTheme.bodyLarge))
|
||||
: ListView(
|
||||
children: (_eventos[DateTime(_selectedDay!.year, _selectedDay!.month, _selectedDay!.day)] ?? []).map((e) {
|
||||
return Card(
|
||||
child: ListTile(
|
||||
leading: CircleAvatar(backgroundColor: e['color'] as Color, child: Text((e['servicio'] as String).substring(0, 2).toUpperCase(), style: const TextStyle(color: Colors.white, fontSize: 12))),
|
||||
title: Text(e['servicio'] as String),
|
||||
subtitle: Text('$symbol${NumberFormat('#,##0.00').format(e['monto'])}'),
|
||||
trailing: Chip(label: Text(e['estado'] as String, style: TextStyle(fontSize: 12, color: e['estado'] == 'Pagada' ? Colors.green : Colors.orange))),
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
93
lib/screens/configuracion_screen.dart
Normal file
93
lib/screens/configuracion_screen.dart
Normal file
@@ -0,0 +1,93 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../models/configuracion.dart';
|
||||
import '../providers/configuracion_provider.dart';
|
||||
|
||||
class ConfiguracionScreen extends StatefulWidget {
|
||||
const ConfiguracionScreen({super.key});
|
||||
|
||||
@override
|
||||
State<ConfiguracionScreen> createState() => _ConfiguracionScreenState();
|
||||
}
|
||||
|
||||
class _ConfiguracionScreenState extends State<ConfiguracionScreen> {
|
||||
late List<bool> _diasSeleccionados;
|
||||
late String _moneda;
|
||||
|
||||
final List<Map<String, dynamic>> _opcionesDias = [
|
||||
{'label': '7 días antes', 'value': 7},
|
||||
{'label': '3 días antes', 'value': 3},
|
||||
{'label': '1 día antes', 'value': 1},
|
||||
{'label': 'Día de vencimiento', 'value': 0},
|
||||
];
|
||||
|
||||
final List<String> _monedas = ['USD', 'EUR', 'MXN', 'COP', 'ARS', 'PEN', 'CLP', 'BRL'];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final config = context.read<ConfiguracionProvider>().config;
|
||||
final dias = config?.diasRecordatorio ?? '7,3,1,0';
|
||||
final lista = dias.split(',').map((e) => int.tryParse(e.trim()) ?? 0).toList();
|
||||
_diasSeleccionados = _opcionesDias.map((o) => lista.contains(o['value'])).toList();
|
||||
_moneda = config?.moneda ?? 'USD';
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final provider = context.read<ConfiguracionProvider>();
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Configuración')),
|
||||
body: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
Text('Recordatorios', style: Theme.of(context).textTheme.titleMedium),
|
||||
const SizedBox(height: 8),
|
||||
...List.generate(_opcionesDias.length, (i) {
|
||||
return CheckboxListTile(
|
||||
title: Text(_opcionesDias[i]['label'] as String),
|
||||
value: _diasSeleccionados[i],
|
||||
onChanged: (v) {
|
||||
setState(() => _diasSeleccionados[i] = v ?? false);
|
||||
},
|
||||
);
|
||||
}),
|
||||
const SizedBox(height: 20),
|
||||
Text('Moneda', style: Theme.of(context).textTheme.titleMedium),
|
||||
const SizedBox(height: 8),
|
||||
DropdownButtonFormField<String>(
|
||||
value: _moneda,
|
||||
decoration: const InputDecoration(border: OutlineInputBorder()),
|
||||
items: _monedas.map((m) => DropdownMenuItem(value: m, child: Text(m))).toList(),
|
||||
onChanged: (v) => setState(() => _moneda = v!),
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
FilledButton(
|
||||
onPressed: () async {
|
||||
final diasStr = _opcionesDias
|
||||
.asMap()
|
||||
.entries
|
||||
.where((e) => _diasSeleccionados[e.key])
|
||||
.map((e) => e.value['value'].toString())
|
||||
.join(',');
|
||||
final config = Configuracion(
|
||||
id: provider.config?.id,
|
||||
diasRecordatorio: diasStr.isEmpty ? '0' : diasStr,
|
||||
tema: provider.config?.tema ?? 'claro',
|
||||
moneda: _moneda,
|
||||
);
|
||||
await provider.guardarConfiguracion(config);
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Configuración guardada')),
|
||||
);
|
||||
}
|
||||
},
|
||||
child: const Text('Guardar configuración'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
126
lib/screens/crear_factura_screen.dart
Normal file
126
lib/screens/crear_factura_screen.dart
Normal file
@@ -0,0 +1,126 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import '../models/factura.dart';
|
||||
import '../providers/factura_provider.dart';
|
||||
import '../providers/servicio_provider.dart';
|
||||
|
||||
class CrearFacturaScreen extends StatefulWidget {
|
||||
const CrearFacturaScreen({super.key});
|
||||
|
||||
@override
|
||||
State<CrearFacturaScreen> createState() => _CrearFacturaScreenState();
|
||||
}
|
||||
|
||||
class _CrearFacturaScreenState extends State<CrearFacturaScreen> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
late TextEditingController _montoCtrl;
|
||||
late TextEditingController _notaCtrl;
|
||||
int? _servicioId;
|
||||
DateTime _fechaEmision = DateTime.now();
|
||||
DateTime _fechaVencimiento = DateTime.now().add(const Duration(days: 30));
|
||||
String _estado = 'Pendiente';
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_montoCtrl = TextEditingController();
|
||||
_notaCtrl = TextEditingController();
|
||||
context.read<ServicioProvider>().cargarServicios();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_montoCtrl.dispose();
|
||||
_notaCtrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final servicioProv = context.watch<ServicioProvider>();
|
||||
final facturaProv = context.read<FacturaProvider>();
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Nueva factura')),
|
||||
body: Form(
|
||||
key: _formKey,
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
DropdownButtonFormField<int>(
|
||||
value: _servicioId,
|
||||
decoration: const InputDecoration(labelText: 'Servicio', border: OutlineInputBorder()),
|
||||
items: servicioProv.servicios.map((s) => DropdownMenuItem(value: s.id, child: Text(s.nombre))).toList(),
|
||||
onChanged: (v) => setState(() => _servicioId = v),
|
||||
validator: (v) => v == null ? 'Selecciona un servicio' : null,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _montoCtrl,
|
||||
decoration: const InputDecoration(labelText: 'Monto', border: OutlineInputBorder(), prefixText: '\$ '),
|
||||
keyboardType: TextInputType.numberWithOptions(decimal: true),
|
||||
validator: (v) {
|
||||
if (v == null || v.isEmpty) return 'Ingresa el monto';
|
||||
if (double.tryParse(v) == null) return 'Monto inválido';
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
ListTile(
|
||||
title: const Text('Fecha de emisión'),
|
||||
subtitle: Text(DateFormat('yyyy-MM-dd').format(_fechaEmision)),
|
||||
trailing: const Icon(Icons.calendar_today),
|
||||
onTap: () async {
|
||||
final date = await showDatePicker(context: context, firstDate: DateTime(2020), lastDate: DateTime(2035), initialDate: _fechaEmision);
|
||||
if (date != null) setState(() => _fechaEmision = date);
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
title: const Text('Fecha de vencimiento'),
|
||||
subtitle: Text(DateFormat('yyyy-MM-dd').format(_fechaVencimiento)),
|
||||
trailing: const Icon(Icons.calendar_today),
|
||||
onTap: () async {
|
||||
final date = await showDatePicker(context: context, firstDate: DateTime(2020), lastDate: DateTime(2035), initialDate: _fechaVencimiento);
|
||||
if (date != null) setState(() => _fechaVencimiento = date);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _notaCtrl,
|
||||
decoration: const InputDecoration(labelText: 'Nota (opcional)', border: OutlineInputBorder()),
|
||||
maxLines: 2,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
SegmentedButton<String>(
|
||||
segments: const [
|
||||
ButtonSegment(value: 'Pendiente', label: Text('Pendiente')),
|
||||
ButtonSegment(value: 'Pagada', label: Text('Pagada')),
|
||||
],
|
||||
selected: {_estado},
|
||||
onSelectionChanged: (v) => setState(() => _estado = v.first),
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
FilledButton(
|
||||
onPressed: () async {
|
||||
if (!_formKey.currentState!.validate()) return;
|
||||
final factura = Factura(
|
||||
servicioId: _servicioId!,
|
||||
monto: double.parse(_montoCtrl.text),
|
||||
fechaEmision: DateFormat('yyyy-MM-dd').format(_fechaEmision),
|
||||
fechaVencimiento: DateFormat('yyyy-MM-dd').format(_fechaVencimiento),
|
||||
estado: _estado,
|
||||
nota: _notaCtrl.text.isEmpty ? null : _notaCtrl.text,
|
||||
fechaPago: _estado == 'Pagada' ? DateFormat('yyyy-MM-dd').format(DateTime.now()) : null,
|
||||
);
|
||||
await facturaProv.agregarFactura(factura);
|
||||
if (context.mounted) Navigator.pop(context);
|
||||
},
|
||||
child: const Text('Guardar factura'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
149
lib/screens/crear_servicio_screen.dart
Normal file
149
lib/screens/crear_servicio_screen.dart
Normal file
@@ -0,0 +1,149 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import '../models/servicio.dart';
|
||||
import '../providers/servicio_provider.dart';
|
||||
|
||||
class CrearServicioScreen extends StatefulWidget {
|
||||
final Servicio? servicio;
|
||||
const CrearServicioScreen({super.key, this.servicio});
|
||||
|
||||
@override
|
||||
State<CrearServicioScreen> createState() => _CrearServicioScreenState();
|
||||
}
|
||||
|
||||
class _CrearServicioScreenState extends State<CrearServicioScreen> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
late TextEditingController _nombreCtrl;
|
||||
String _iconoSeleccionado = 'recibo';
|
||||
Color _colorSeleccionado = Colors.purple;
|
||||
int _diaVencimiento = 15;
|
||||
|
||||
final List<Map<String, dynamic>> _iconos = [
|
||||
{'key': 'electricidad', 'icon': Icons.bolt, 'label': 'Electricidad'},
|
||||
{'key': 'agua', 'icon': Icons.water_drop, 'label': 'Agua'},
|
||||
{'key': 'internet', 'icon': Icons.wifi, 'label': 'Internet'},
|
||||
{'key': 'cable', 'icon': Icons.tv, 'label': 'Cable'},
|
||||
{'key': 'telefono', 'icon': Icons.phone, 'label': 'Teléfono'},
|
||||
{'key': 'gas', 'icon': Icons.local_fire_department, 'label': 'Gas'},
|
||||
{'key': 'alquiler', 'icon': Icons.home, 'label': 'Alquiler'},
|
||||
{'key': 'recibo', 'icon': Icons.receipt, 'label': 'Otros'},
|
||||
];
|
||||
|
||||
final List<Color> _colores = [
|
||||
Colors.red, Colors.pink, Colors.purple, Colors.deepPurple,
|
||||
Colors.indigo, Colors.blue, Colors.lightBlue, Colors.cyan,
|
||||
Colors.teal, Colors.green, Colors.lightGreen, Colors.lime,
|
||||
Colors.yellow, Colors.amber, Colors.orange, Colors.deepOrange,
|
||||
Colors.brown, Colors.grey, Colors.blueGrey,
|
||||
];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_nombreCtrl = TextEditingController(text: widget.servicio?.nombre ?? '');
|
||||
if (widget.servicio != null) {
|
||||
_iconoSeleccionado = widget.servicio!.icono;
|
||||
_colorSeleccionado = Color(widget.servicio!.color);
|
||||
_diaVencimiento = widget.servicio!.diaVencimiento;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_nombreCtrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final provider = context.read<ServicioProvider>();
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: Text(widget.servicio != null ? 'Editar servicio' : 'Nuevo servicio')),
|
||||
body: Form(
|
||||
key: _formKey,
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
TextFormField(
|
||||
controller: _nombreCtrl,
|
||||
decoration: const InputDecoration(labelText: 'Nombre del servicio', border: OutlineInputBorder()),
|
||||
validator: (v) => v == null || v.trim().isEmpty ? 'Ingresa el nombre' : null,
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Text('Icono', style: Theme.of(context).textTheme.titleSmall),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: _iconos.map((item) {
|
||||
final selected = _iconoSeleccionado == item['key'];
|
||||
return ChoiceChip(
|
||||
selected: selected,
|
||||
avatar: Icon(item['icon'] as IconData, size: 20),
|
||||
label: Text(item['label'] as String, style: const TextStyle(fontSize: 12)),
|
||||
onSelected: (_) => setState(() => _iconoSeleccionado = item['key'] as String),
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Text('Color', style: Theme.of(context).textTheme.titleSmall),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 6,
|
||||
runSpacing: 6,
|
||||
children: _colores.map((c) {
|
||||
final selected = _colorSeleccionado == c;
|
||||
return GestureDetector(
|
||||
onTap: () => setState(() => _colorSeleccionado = c),
|
||||
child: Container(
|
||||
width: 36,
|
||||
height: 36,
|
||||
decoration: BoxDecoration(
|
||||
color: c,
|
||||
shape: BoxShape.circle,
|
||||
border: selected ? Border.all(color: Colors.white, width: 3) : null,
|
||||
boxShadow: selected ? [BoxShadow(color: c.withValues(alpha: 0.5), blurRadius: 8)] : null,
|
||||
),
|
||||
child: selected ? const Icon(Icons.check, color: Colors.white, size: 18) : null,
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Text('Día de vencimiento', style: Theme.of(context).textTheme.titleSmall),
|
||||
const SizedBox(height: 8),
|
||||
DropdownButtonFormField<int>(
|
||||
value: _diaVencimiento,
|
||||
decoration: const InputDecoration(border: OutlineInputBorder()),
|
||||
items: List.generate(28, (i) => DropdownMenuItem(value: i + 1, child: Text('${i + 1}'))),
|
||||
onChanged: (v) => setState(() => _diaVencimiento = v!),
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
FilledButton(
|
||||
onPressed: () async {
|
||||
if (!_formKey.currentState!.validate()) return;
|
||||
final servicio = Servicio(
|
||||
id: widget.servicio?.id,
|
||||
nombre: _nombreCtrl.text.trim(),
|
||||
icono: _iconoSeleccionado,
|
||||
color: _colorSeleccionado.value,
|
||||
diaVencimiento: _diaVencimiento,
|
||||
fechaCreacion: widget.servicio?.fechaCreacion ?? DateFormat('yyyy-MM-dd').format(DateTime.now()),
|
||||
);
|
||||
if (widget.servicio != null) {
|
||||
await provider.actualizarServicio(servicio);
|
||||
} else {
|
||||
await provider.agregarServicio(servicio);
|
||||
}
|
||||
if (context.mounted) Navigator.pop(context);
|
||||
},
|
||||
child: Text(widget.servicio != null ? 'Guardar cambios' : 'Crear servicio'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
142
lib/screens/dashboard_screen.dart
Normal file
142
lib/screens/dashboard_screen.dart
Normal file
@@ -0,0 +1,142 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import '../providers/servicio_provider.dart';
|
||||
import '../providers/factura_provider.dart';
|
||||
import '../providers/configuracion_provider.dart';
|
||||
import '../widgets/stat_card.dart';
|
||||
import 'servicios_screen.dart';
|
||||
import 'facturas_screen.dart';
|
||||
import 'calendario_screen.dart';
|
||||
import 'estadisticas_screen.dart';
|
||||
import 'configuracion_screen.dart';
|
||||
import 'crear_factura_screen.dart';
|
||||
|
||||
class DashboardScreen extends StatefulWidget {
|
||||
const DashboardScreen({super.key});
|
||||
|
||||
@override
|
||||
State<DashboardScreen> createState() => _DashboardScreenState();
|
||||
}
|
||||
|
||||
class _DashboardScreenState extends State<DashboardScreen> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_cargarDatos();
|
||||
}
|
||||
|
||||
void _cargarDatos() {
|
||||
context.read<ServicioProvider>().cargarServicios();
|
||||
context.read<FacturaProvider>().cargarFacturas();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final facturaProv = context.watch<FacturaProvider>();
|
||||
final servicioProv = context.watch<ServicioProvider>();
|
||||
final configProv = context.watch<ConfiguracionProvider>();
|
||||
final moneda = configProv.config?.moneda ?? 'USD';
|
||||
final symbol = moneda == 'USD' ? '\$' : moneda == 'EUR' ? '€' : moneda == 'MXN' ? 'MX\$' : '\$';
|
||||
|
||||
final pendientes = facturaProv.facturas.where((f) => f.estado == 'Pendiente').length;
|
||||
final vencidas = facturaProv.facturasVencidas.length;
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('HogarControl'), centerTitle: true, actions: [
|
||||
IconButton(icon: const Icon(Icons.settings), onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (_) => const ConfiguracionScreen()))),
|
||||
]),
|
||||
body: RefreshIndicator(
|
||||
onRefresh: () async => _cargarDatos(),
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(child: StatCard(
|
||||
title: 'Pendientes',
|
||||
value: '$pendientes',
|
||||
icon: Icons.pending_actions,
|
||||
color: Colors.orange,
|
||||
)),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: StatCard(
|
||||
title: 'Vencidas',
|
||||
value: '$vencidas',
|
||||
icon: Icons.warning_rounded,
|
||||
color: Colors.red,
|
||||
)),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(child: StatCard(
|
||||
title: 'Pagadas este mes',
|
||||
value: facturaProv.facturas.where((f) => f.estado == 'Pagada').length.toString(),
|
||||
icon: Icons.check_circle,
|
||||
color: Colors.green,
|
||||
)),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: StatCard(
|
||||
title: 'Total gastado',
|
||||
value: '$symbol${NumberFormat('#,##0.00').format(facturaProv.facturas.where((f) => f.estado == 'Pagada').fold(0.0, (sum, f) => sum + f.monto))}',
|
||||
icon: Icons.attach_money,
|
||||
color: Colors.blue,
|
||||
)),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Text('Próximos vencimientos', style: Theme.of(context).textTheme.titleMedium),
|
||||
const SizedBox(height: 8),
|
||||
...facturaProv.facturas
|
||||
.where((f) => f.estado == 'Pendiente')
|
||||
.take(5)
|
||||
.map((f) {
|
||||
final servicio = servicioProv.servicios.where((s) => s.id == f.servicioId).firstOrNull;
|
||||
return Card(
|
||||
child: ListTile(
|
||||
leading: CircleAvatar(
|
||||
backgroundColor: Color(servicio?.color ?? 0xFF6200EE),
|
||||
child: Text(servicio?.nombre.substring(0, 2).toUpperCase() ?? '??',
|
||||
style: const TextStyle(color: Colors.white, fontSize: 12)),
|
||||
),
|
||||
title: Text(servicio?.nombre ?? 'Desconocido'),
|
||||
subtitle: Text('Ven: ${f.fechaVencimiento} $symbol${NumberFormat('#,##0.00').format(f.monto)}'),
|
||||
trailing: TextButton(
|
||||
onPressed: () => facturaProv.marcarPagada(f.id!),
|
||||
child: const Text('Pagar'),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
],
|
||||
),
|
||||
),
|
||||
floatingActionButton: FloatingActionButton.extended(
|
||||
onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (_) => const CrearFacturaScreen())).then((_) => _cargarDatos()),
|
||||
icon: const Icon(Icons.add),
|
||||
label: const Text('Nueva factura'),
|
||||
),
|
||||
bottomNavigationBar: NavigationBar(
|
||||
selectedIndex: 0,
|
||||
onDestinationSelected: (i) {
|
||||
switch (i) {
|
||||
case 0: break;
|
||||
case 1: Navigator.push(context, MaterialPageRoute(builder: (_) => const ServiciosScreen()));
|
||||
case 2: Navigator.push(context, MaterialPageRoute(builder: (_) => const FacturasScreen()));
|
||||
case 3: Navigator.push(context, MaterialPageRoute(builder: (_) => const CalendarioScreen()));
|
||||
case 4: Navigator.push(context, MaterialPageRoute(builder: (_) => const EstadisticasScreen()));
|
||||
}
|
||||
},
|
||||
destinations: const [
|
||||
NavigationDestination(icon: Icon(Icons.dashboard), label: 'Dashboard'),
|
||||
NavigationDestination(icon: Icon(Icons.electrical_services), label: 'Servicios'),
|
||||
NavigationDestination(icon: Icon(Icons.receipt_long), label: 'Facturas'),
|
||||
NavigationDestination(icon: Icon(Icons.calendar_month), label: 'Calendario'),
|
||||
NavigationDestination(icon: Icon(Icons.bar_chart), label: 'Stats'),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
145
lib/screens/estadisticas_screen.dart
Normal file
145
lib/screens/estadisticas_screen.dart
Normal file
@@ -0,0 +1,145 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:fl_chart/fl_chart.dart';
|
||||
import '../providers/factura_provider.dart';
|
||||
import '../providers/configuracion_provider.dart';
|
||||
|
||||
class EstadisticasScreen extends StatefulWidget {
|
||||
const EstadisticasScreen({super.key});
|
||||
|
||||
@override
|
||||
State<EstadisticasScreen> createState() => _EstadisticasScreenState();
|
||||
}
|
||||
|
||||
class _EstadisticasScreenState extends State<EstadisticasScreen> {
|
||||
late int _year;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_year = DateTime.now().year;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final facturaProv = context.watch<FacturaProvider>();
|
||||
final configProv = context.watch<ConfiguracionProvider>();
|
||||
final moneda = configProv.config?.moneda ?? 'USD';
|
||||
final symbol = moneda == 'USD' ? '\$' : moneda == 'EUR' ? '€' : moneda == 'MXN' ? 'MX\$' : '\$';
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Estadísticas')),
|
||||
body: FutureBuilder(
|
||||
future: Future.wait([
|
||||
facturaProv.gastoMensual(_year),
|
||||
facturaProv.gastosPorServicio(_year, DateTime.now().month),
|
||||
facturaProv.totalGastadoMes(_year, DateTime.now().month),
|
||||
]),
|
||||
builder: (context, AsyncSnapshot<List<dynamic>> snapshot) {
|
||||
if (!snapshot.hasData) return const Center(child: CircularProgressIndicator());
|
||||
|
||||
final gastoMensual = snapshot.data![0] as List<Map<String, dynamic>>;
|
||||
final gastoPorServicio = snapshot.data![1] as Map<String, double>;
|
||||
final totalMes = snapshot.data![2] as double;
|
||||
|
||||
return ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
Text('Resumen $_year', style: Theme.of(context).textTheme.titleLarge),
|
||||
const SizedBox(height: 8),
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Gasto mensual actual', style: Theme.of(context).textTheme.titleSmall),
|
||||
Text('$symbol${NumberFormat('#,##0.00').format(totalMes)}',
|
||||
style: Theme.of(context).textTheme.headlineMedium),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Text('Gasto mensual ($_year)', style: Theme.of(context).textTheme.titleMedium),
|
||||
const SizedBox(height: 8),
|
||||
SizedBox(
|
||||
height: 200,
|
||||
child: BarChart(
|
||||
BarChartData(
|
||||
alignment: BarChartAlignment.spaceAround,
|
||||
maxY: (gastoMensual.isEmpty ? 1000 : gastoMensual.map((e) => (e['total'] as num).toDouble()).reduce((a, b) => a > b ? a : b)) * 1.2,
|
||||
barGroups: List.generate(12, (i) {
|
||||
final mes = (i + 1).toString().padLeft(2, '0');
|
||||
final data = gastoMensual.where((e) => e['mes'] == mes).firstOrNull;
|
||||
return BarChartGroupData(
|
||||
x: i,
|
||||
barRods: [
|
||||
BarChartRodData(
|
||||
toY: data != null ? (data['total'] as num).toDouble() : 0,
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
width: 16,
|
||||
borderRadius: const BorderRadius.vertical(top: Radius.circular(4)),
|
||||
),
|
||||
],
|
||||
);
|
||||
}),
|
||||
titlesData: FlTitlesData(
|
||||
leftTitles: AxisTitles(sideTitles: SideTitles(showTitles: true, reservedSize: 40, getTitlesWidget: (v, _) => Text('$symbol${v.toInt()}', style: const TextStyle(fontSize: 10)))),
|
||||
bottomTitles: AxisTitles(sideTitles: SideTitles(showTitles: true, getTitlesWidget: (v, _) {
|
||||
const meses = ['E', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'];
|
||||
return Text(meses[v.toInt()], style: const TextStyle(fontSize: 10));
|
||||
})),
|
||||
rightTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)),
|
||||
topTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)),
|
||||
),
|
||||
gridData: FlGridData(show: true, drawVerticalLine: false, horizontalInterval: (gastoMensual.isEmpty ? 1000 : gastoMensual.map((e) => (e['total'] as num).toDouble()).reduce((a, b) => a > b ? a : b)) / 4),
|
||||
borderData: FlBorderData(show: false),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Text('Distribución por servicio', style: Theme.of(context).textTheme.titleMedium),
|
||||
const SizedBox(height: 8),
|
||||
if (gastoPorServicio.isEmpty)
|
||||
Card(child: Padding(padding: const EdgeInsets.all(16), child: Text('Sin datos este mes')))
|
||||
else
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
children: gastoPorServicio.entries.map((e) {
|
||||
final total = gastoPorServicio.values.fold(0.0, (a, b) => a + b);
|
||||
final pct = total > 0 ? e.value / total * 100 : 0.0;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: Row(
|
||||
children: [
|
||||
SizedBox(width: 100, child: Text(e.key, style: const TextStyle(fontSize: 13))),
|
||||
Expanded(
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
child: LinearProgressIndicator(
|
||||
value: pct / 100,
|
||||
backgroundColor: Colors.grey[200],
|
||||
minHeight: 12,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
SizedBox(width: 70, child: Text('$symbol${NumberFormat('#,##0.00').format(e.value)}', style: const TextStyle(fontSize: 12), textAlign: TextAlign.right)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
110
lib/screens/facturas_screen.dart
Normal file
110
lib/screens/facturas_screen.dart
Normal file
@@ -0,0 +1,110 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import '../providers/factura_provider.dart';
|
||||
import '../providers/servicio_provider.dart';
|
||||
import '../providers/configuracion_provider.dart';
|
||||
|
||||
class FacturasScreen extends StatefulWidget {
|
||||
const FacturasScreen({super.key});
|
||||
|
||||
@override
|
||||
State<FacturasScreen> createState() => _FacturasScreenState();
|
||||
}
|
||||
|
||||
class _FacturasScreenState extends State<FacturasScreen> {
|
||||
String? _filtroEstado;
|
||||
int? _filtroServicio;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
context.read<FacturaProvider>().cargarFacturas();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final facturaProv = context.watch<FacturaProvider>();
|
||||
final servicioProv = context.watch<ServicioProvider>();
|
||||
final configProv = context.watch<ConfiguracionProvider>();
|
||||
final moneda = configProv.config?.moneda ?? 'USD';
|
||||
final symbol = moneda == 'USD' ? '\$' : moneda == 'EUR' ? '€' : moneda == 'MXN' ? 'MX\$' : '\$';
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Facturas')),
|
||||
body: Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: Row(
|
||||
children: [
|
||||
FilterChip(label: const Text('Todas'), selected: _filtroEstado == null && _filtroServicio == null, onSelected: (_) => setState(() { _filtroEstado = null; _filtroServicio = null; facturaProv.cargarFacturas(); })),
|
||||
const SizedBox(width: 8),
|
||||
FilterChip(label: const Text('Pendientes'), selected: _filtroEstado == 'Pendiente', onSelected: (_) => setState(() { _filtroEstado = 'Pendiente'; _filtroServicio = null; facturaProv.cargarFacturas(estado: 'Pendiente'); })),
|
||||
const SizedBox(width: 8),
|
||||
FilterChip(label: const Text('Pagadas'), selected: _filtroEstado == 'Pagada', onSelected: (_) => setState(() { _filtroEstado = 'Pagada'; _filtroServicio = null; facturaProv.cargarFacturas(estado: 'Pagada'); })),
|
||||
const SizedBox(width: 8),
|
||||
FilterChip(label: const Text('Vencidas'), selected: _filtroEstado == 'vencidas', onSelected: (_) => setState(() { _filtroEstado = 'vencidas'; _filtroServicio = null; facturaProv.facturasVencidas; })),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: facturaProv.cargando
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: ListView.builder(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
itemCount: facturaProv.facturas.length + (facturaProv.facturas.isEmpty ? 1 : 0),
|
||||
itemBuilder: (_, i) {
|
||||
if (facturaProv.facturas.isEmpty) {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(48),
|
||||
child: Column(
|
||||
children: [
|
||||
Icon(Icons.receipt_long, size: 64, color: Colors.grey[400]),
|
||||
const SizedBox(height: 16),
|
||||
Text('No hay facturas', style: Theme.of(context).textTheme.bodyLarge),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
final f = facturaProv.facturas[i];
|
||||
final servicio = servicioProv.servicios.where((s) => s.id == f.servicioId).firstOrNull;
|
||||
final vencida = f.estado == 'Pendiente' && DateTime.tryParse(f.fechaVencimiento)?.isBefore(DateTime.now()) == true;
|
||||
return Card(
|
||||
child: ListTile(
|
||||
leading: CircleAvatar(
|
||||
backgroundColor: Color(servicio?.color ?? 0xFF6200EE),
|
||||
child: Text(servicio?.nombre.substring(0, 2).toUpperCase() ?? '??',
|
||||
style: const TextStyle(color: Colors.white, fontSize: 12)),
|
||||
),
|
||||
title: Text('${servicio?.nombre ?? 'Desconocido'} - $symbol${NumberFormat('#,##0.00').format(f.monto)}'),
|
||||
subtitle: Text('Vence: ${f.fechaVencimiento}${f.estado == 'Pagada' ? ' Pagada: ${f.fechaPago ?? ''}' : ''}'),
|
||||
trailing: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (f.estado == 'Pendiente')
|
||||
IconButton(
|
||||
icon: Icon(Icons.check_circle, color: vencida ? Colors.red : Colors.green),
|
||||
onPressed: () => facturaProv.marcarPagada(f.id!),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.delete_outline, color: Colors.red),
|
||||
onPressed: () => facturaProv.eliminarFactura(f.id!),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
87
lib/screens/servicios_screen.dart
Normal file
87
lib/screens/servicios_screen.dart
Normal file
@@ -0,0 +1,87 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../providers/servicio_provider.dart';
|
||||
import 'crear_servicio_screen.dart';
|
||||
|
||||
class ServiciosScreen extends StatelessWidget {
|
||||
const ServiciosScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final provider = context.watch<ServicioProvider>();
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Servicios')),
|
||||
body: provider.cargando
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: provider.servicios.isEmpty
|
||||
? Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.electrical_services, size: 64, color: Colors.grey[400]),
|
||||
const SizedBox(height: 16),
|
||||
Text('No hay servicios registrados', style: Theme.of(context).textTheme.bodyLarge),
|
||||
const SizedBox(height: 8),
|
||||
Text('Agrega tu primer servicio', style: Theme.of(context).textTheme.bodyMedium),
|
||||
],
|
||||
),
|
||||
)
|
||||
: ListView.builder(
|
||||
padding: const EdgeInsets.all(16),
|
||||
itemCount: provider.servicios.length,
|
||||
itemBuilder: (_, i) {
|
||||
final s = provider.servicios[i];
|
||||
return Card(
|
||||
child: ListTile(
|
||||
leading: CircleAvatar(
|
||||
backgroundColor: Color(s.color),
|
||||
child: Icon(_getIcon(s.icono), color: Colors.white),
|
||||
),
|
||||
title: Text(s.nombre),
|
||||
subtitle: Text('Vence día ${s.diaVencimiento}'),
|
||||
trailing: IconButton(
|
||||
icon: const Icon(Icons.delete_outline, color: Colors.red),
|
||||
onPressed: () async {
|
||||
final ok = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (_) => AlertDialog(
|
||||
title: const Text('Eliminar servicio'),
|
||||
content: Text('¿Eliminar ${s.nombre}? Se eliminarán sus facturas.'),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('Cancelar')),
|
||||
TextButton(onPressed: () => Navigator.pop(context, true), child: const Text('Eliminar')),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (ok == true) provider.eliminarServicio(s.id!);
|
||||
},
|
||||
),
|
||||
onTap: () => Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(builder: (_) => CrearServicioScreen(servicio: s)),
|
||||
).then((_) => provider.cargarServicios()),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
floatingActionButton: FloatingActionButton(
|
||||
onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (_) => const CrearServicioScreen())).then((_) => provider.cargarServicios()),
|
||||
child: const Icon(Icons.add),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
IconData _getIcon(String name) {
|
||||
switch (name) {
|
||||
case 'electricidad': return Icons.bolt;
|
||||
case 'agua': return Icons.water_drop;
|
||||
case 'internet': return Icons.wifi;
|
||||
case 'cable': return Icons.tv;
|
||||
case 'telefono': return Icons.phone;
|
||||
case 'gas': return Icons.local_fire_department;
|
||||
case 'alquiler': return Icons.home;
|
||||
default: return Icons.receipt;
|
||||
}
|
||||
}
|
||||
}
|
||||
51
lib/screens/splash_screen.dart
Normal file
51
lib/screens/splash_screen.dart
Normal file
@@ -0,0 +1,51 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../providers/configuracion_provider.dart';
|
||||
import '../services/notification_service.dart';
|
||||
import 'dashboard_screen.dart';
|
||||
|
||||
class SplashScreen extends StatefulWidget {
|
||||
const SplashScreen({super.key});
|
||||
|
||||
@override
|
||||
State<SplashScreen> createState() => _SplashScreenState();
|
||||
}
|
||||
|
||||
class _SplashScreenState extends State<SplashScreen> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_init();
|
||||
}
|
||||
|
||||
Future<void> _init() async {
|
||||
await NotificationService.instance.init();
|
||||
await context.read<ConfiguracionProvider>().cargarConfiguracion();
|
||||
await NotificationService.instance.scheduleRecordatorios();
|
||||
if (mounted) {
|
||||
Navigator.of(context).pushReplacement(
|
||||
MaterialPageRoute(builder: (_) => const DashboardScreen()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: Theme.of(context).colorScheme.primary,
|
||||
body: Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.home_rounded, size: 80, color: Theme.of(context).colorScheme.onPrimary),
|
||||
const SizedBox(height: 16),
|
||||
Text('HogarControl',
|
||||
style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold, color: Theme.of(context).colorScheme.onPrimary)),
|
||||
const SizedBox(height: 24),
|
||||
CircularProgressIndicator(color: Theme.of(context).colorScheme.onPrimary),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
74
lib/services/notification_service.dart
Normal file
74
lib/services/notification_service.dart
Normal file
@@ -0,0 +1,74 @@
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'package:timezone/timezone.dart' as tz;
|
||||
import 'package:timezone/data/latest.dart' as tz_data;
|
||||
import '../database/database_helper.dart';
|
||||
|
||||
class NotificationService {
|
||||
static final NotificationService instance = NotificationService._init();
|
||||
final FlutterLocalNotificationsPlugin _plugin = FlutterLocalNotificationsPlugin();
|
||||
bool _initialized = false;
|
||||
|
||||
NotificationService._init();
|
||||
|
||||
Future<void> init() async {
|
||||
if (_initialized) return;
|
||||
tz_data.initializeTimeZones();
|
||||
const androidSettings = AndroidInitializationSettings('@mipmap/ic_launcher');
|
||||
const settings = InitializationSettings(android: androidSettings);
|
||||
await _plugin.initialize(settings);
|
||||
_initialized = true;
|
||||
}
|
||||
|
||||
Future<void> scheduleRecordatorios() async {
|
||||
await _plugin.cancelAll();
|
||||
final db = DatabaseHelper.instance;
|
||||
final facturas = await db.getFacturas(estado: 'Pendiente');
|
||||
final config = await db.getConfiguracion();
|
||||
final diasStr = config?.diasRecordatorio ?? '7,3,1,0';
|
||||
final dias = diasStr.split(',').map((e) => int.tryParse(e.trim()) ?? 0).toList();
|
||||
|
||||
for (final factura in facturas) {
|
||||
final vencimiento = DateTime.tryParse(factura.fechaVencimiento);
|
||||
if (vencimiento == null) continue;
|
||||
for (final dia in dias) {
|
||||
final notifDate = vencimiento.subtract(Duration(days: dia));
|
||||
final now = DateTime.now();
|
||||
if (notifDate.isAfter(now) || notifDate.day == now.day) {
|
||||
await _scheduleNotification(
|
||||
id: factura.id! * 10 + dia,
|
||||
title: dia == 0 ? 'Factura vence hoy' : 'Recordatorio de factura',
|
||||
body: 'La factura vence en $dia día(s)',
|
||||
scheduledDate: notifDate,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _scheduleNotification({
|
||||
required int id,
|
||||
required String title,
|
||||
required String body,
|
||||
required DateTime scheduledDate,
|
||||
}) async {
|
||||
const androidDetails = AndroidNotificationDetails(
|
||||
'hogarcontrol_recordatorios',
|
||||
'Recordatorios de facturas',
|
||||
channelDescription: 'Notificaciones de recordatorio de pago',
|
||||
importance: Importance.high,
|
||||
priority: Priority.high,
|
||||
);
|
||||
const details = NotificationDetails(android: androidDetails);
|
||||
final tzDate = tz.TZDateTime.from(scheduledDate, tz.local);
|
||||
await _plugin.zonedSchedule(
|
||||
id,
|
||||
title,
|
||||
body,
|
||||
tzDate,
|
||||
details,
|
||||
androidScheduleMode: AndroidScheduleMode.inexactAllowWhileIdle,
|
||||
matchDateTimeComponents: DateTimeComponents.dayOfMonthAndTime,
|
||||
uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.absoluteTime,
|
||||
);
|
||||
}
|
||||
}
|
||||
39
lib/widgets/stat_card.dart
Normal file
39
lib/widgets/stat_card.dart
Normal file
@@ -0,0 +1,39 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class StatCard extends StatelessWidget {
|
||||
final String title;
|
||||
final String value;
|
||||
final IconData icon;
|
||||
final Color color;
|
||||
|
||||
const StatCard({
|
||||
super.key,
|
||||
required this.title,
|
||||
required this.value,
|
||||
required this.icon,
|
||||
required this.color,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(icon, color: color, size: 20),
|
||||
const SizedBox(width: 8),
|
||||
Text(title, style: Theme.of(context).textTheme.bodySmall),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(value, style: Theme.of(context).textTheme.headlineSmall?.copyWith(fontWeight: FontWeight.bold)),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user