agente_sync_service.dart 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import 'package:drift/drift.dart';
  2. import 'package:ristoris/database/daos/agenti_dao.dart';
  3. import 'package:ristoris/database/database.dart';
  4. import '../api_service.dart';
  5. class AgenteSyncService {
  6. final ApiService _api;
  7. final AgentiDao _agentiDao;
  8. AgenteSyncService(
  9. this._api,
  10. this._agentiDao,
  11. );
  12. Future<bool> checkAgent(String codAgente) async {
  13. try {
  14. final resp = await _api.get('/rest/agente/esisteNew/$codAgente');
  15. return resp['status'] == 0;
  16. } catch (_) {
  17. return false;
  18. }
  19. }
  20. Future<int> downloadAgenti(
  21. int idAgente,
  22. String codAgente,
  23. String lastUpdate, {
  24. void Function(int current, int total)? onProgress,
  25. }) async {
  26. try {
  27. final data = await _api.getList(
  28. '/rest/agente/updates/$codAgente/$lastUpdate',
  29. );
  30. final db = _agentiDao.db;
  31. final total = data.length;
  32. int count = 0;
  33. await db.transaction(() async {
  34. for (final json in data) {
  35. count++;
  36. onProgress?.call(count, total);
  37. if (codAgente == json['codAgente'] as String) {
  38. await setNuovoIdAgente(codAgente, json['idAgente'] as int? ?? 0);
  39. }
  40. }
  41. await db.batch((batch) {
  42. for (final json in data) {
  43. batch.insert(
  44. db.agenti,
  45. Agente(
  46. idAgente: json['idAgente'] as int? ?? 0,
  47. codAgente: json['codAgente'] as String?,
  48. pwd: json['pwd'] as String?,
  49. ragioneSociale: json['ragioneSociale'] as String?,
  50. attivo: json['attivo'] as int? ?? 0,
  51. cap: json['cap'] as String?,
  52. capoArea: json['capoArea'] as String?,
  53. cellulare: json['cellulare'] as String?,
  54. citta: json['citta'] as String?,
  55. email: json['email'] as String?,
  56. frazione: json['frazione'] as String?,
  57. indirizzo: json['indirizzo'] as String?,
  58. modificaPrezzi: json['modificaPrezzi'] as int? ?? 0,
  59. provincia: json['provincia'] as String?,
  60. telefono: json['telefono'] as String?,
  61. ),
  62. mode: InsertMode.insertOrReplace);
  63. }
  64. });
  65. });
  66. return data.length;
  67. } catch (_) {
  68. return 0;
  69. }
  70. }
  71. Future<void> setNuovoIdAgente(String codAgente, int idAgente) async {
  72. Agente? agente = await _agentiDao.findByCode(codAgente);
  73. if (agente != null && agente.idAgente != idAgente) {
  74. await _agentiDao.updateIdAgente(agente.idAgente, idAgente);
  75. }
  76. }
  77. }