agente_sync_service.dart 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. ) async {
  25. try {
  26. final data = await _api.getList(
  27. '/rest/agente/updates/$codAgente/$lastUpdate',
  28. );
  29. final db = _agentiDao.db;
  30. await db.transaction(() async {
  31. for (final json in data) {
  32. if (codAgente == json['codAgente'] as String) {
  33. await setNuovoIdAgente(codAgente, json['idAgente'] as int? ?? 0);
  34. }
  35. }
  36. await db.batch((batch) {
  37. for (final json in data) {
  38. batch.insert(
  39. db.agenti,
  40. Agente(
  41. idAgente: json['idAgente'] as int? ?? 0,
  42. codAgente: json['codAgente'] as String?,
  43. pwd: json['pwd'] as String?,
  44. ragioneSociale: json['ragioneSociale'] as String?,
  45. attivo: json['attivo'] as int? ?? 0,
  46. cap: json['cap'] as String?,
  47. capoArea: json['capoArea'] as String?,
  48. cellulare: json['cellulare'] as String?,
  49. citta: json['citta'] as String?,
  50. email: json['email'] as String?,
  51. frazione: json['frazione'] as String?,
  52. indirizzo: json['indirizzo'] as String?,
  53. modificaPrezzi: json['modificaPrezzi'] as int? ?? 0,
  54. provincia: json['provincia'] as String?,
  55. telefono: json['telefono'] as String?,
  56. ),
  57. mode: InsertMode.insertOrReplace);
  58. }
  59. });
  60. });
  61. return data.length;
  62. } catch (_) {
  63. return 0;
  64. }
  65. }
  66. Future<void> setNuovoIdAgente(String codAgente, int idAgente) async {
  67. Agente? agente = await _agentiDao.findByCode(codAgente);
  68. if (agente != null && agente.idAgente != idAgente) {
  69. await _agentiDao.updateIdAgente(agente.idAgente, idAgente);
  70. }
  71. }
  72. }