usuarios_view_model.dart 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import 'dart:convert';
  2. import 'package:flutter/material.dart';
  3. import 'package:sqflite/sqflite.dart';
  4. import '../data/api_response.dart';
  5. import '../models/models.dart';
  6. import '../services/base_service.dart';
  7. import '../services/repo_service.dart';
  8. class UsuarioViewModel extends ChangeNotifier {
  9. List<Usuario> _usuarios = [];
  10. bool _isLoading = false;
  11. List<Usuario> get usuarios => _usuarios;
  12. bool get isLoading => _isLoading;
  13. int _currentPage = 1;
  14. int _totalProducts = 0;
  15. int _limit = 10;
  16. int get currentPage => _currentPage;
  17. int get totalProducts => _totalProducts;
  18. int get totalPages => (_totalProducts / _limit).ceil();
  19. Future<void> fetchLocalAll({int page = 1}) async {
  20. _currentPage = page;
  21. var db = await RepoService().db;
  22. int? count = Sqflite.firstIntValue(
  23. await db!.rawQuery('SELECT COUNT(*) FROM Usuario'));
  24. _totalProducts = count ?? 0;
  25. int offset = (_limit * (page - 1));
  26. var query = await db.query('Usuario',
  27. where: 'eliminado IS NULL',
  28. orderBy: 'id asc',
  29. limit: _limit,
  30. offset: offset);
  31. _usuarios = query.map((element) => Usuario.fromJson(element)).toList();
  32. notifyListeners();
  33. }
  34. Future<bool> sincronizarUsuarios() async {
  35. try {
  36. Map<String, String> parametros = {"expand": 'permisos'};
  37. final response = ApiResponse(
  38. await BaseService().get('/pos/usuario', queryParameters: parametros));
  39. if (response.isOk && response.resultados != null) {
  40. List<Usuario> usuariosApi =
  41. response.resultados!.map((json) => Usuario.fromApi(json)).toList();
  42. if (usuariosApi.isNotEmpty) {
  43. await RepoService().sincronizarUsuarios(usuariosApi);
  44. notifyListeners();
  45. return true;
  46. }
  47. }
  48. return false;
  49. } catch (e) {
  50. print('Error al sincronizar usuarios: $e');
  51. return false;
  52. }
  53. }
  54. }