| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- import 'package:drift/drift.dart';
- import 'package:ristoris/database/daos/agenti_dao.dart';
- import 'package:ristoris/database/database.dart';
- import '../api_service.dart';
- class AgenteSyncService {
- final ApiService _api;
- final AgentiDao _agentiDao;
- AgenteSyncService(
- this._api,
- this._agentiDao,
- );
- Future<bool> checkAgent(String codAgente) async {
- try {
- final resp = await _api.get('/rest/agente/esisteNew/$codAgente');
- return resp['status'] == 0;
- } catch (_) {
- return false;
- }
- }
- Future<int> downloadAgenti(
- int idAgente,
- String codAgente,
- String lastUpdate, {
- void Function(int current, int total)? onProgress,
- }) async {
- try {
- final data = await _api.getList(
- '/rest/agente/updates/$codAgente/$lastUpdate',
- );
- final db = _agentiDao.db;
- final total = data.length;
- int count = 0;
- await db.transaction(() async {
- for (final json in data) {
- count++;
- onProgress?.call(count, total);
- if (codAgente == json['codAgente'] as String) {
- await setNuovoIdAgente(codAgente, json['idAgente'] as int? ?? 0);
- }
- }
- await db.batch((batch) {
- for (final json in data) {
- batch.insert(
- db.agenti,
- Agente(
- idAgente: json['idAgente'] as int? ?? 0,
- codAgente: json['codAgente'] as String?,
- pwd: json['pwd'] as String?,
- ragioneSociale: json['ragioneSociale'] as String?,
- attivo: json['attivo'] as int? ?? 0,
- cap: json['cap'] as String?,
- capoArea: json['capoArea'] as String?,
- cellulare: json['cellulare'] as String?,
- citta: json['citta'] as String?,
- email: json['email'] as String?,
- frazione: json['frazione'] as String?,
- indirizzo: json['indirizzo'] as String?,
- modificaPrezzi: json['modificaPrezzi'] as int? ?? 0,
- provincia: json['provincia'] as String?,
- telefono: json['telefono'] as String?,
- ),
- mode: InsertMode.insertOrReplace);
- }
- });
- });
- return data.length;
- } catch (_) {
- return 0;
- }
- }
- Future<void> setNuovoIdAgente(String codAgente, int idAgente) async {
- Agente? agente = await _agentiDao.findByCode(codAgente);
- if (agente != null && agente.idAgente != idAgente) {
- await _agentiDao.updateIdAgente(agente.idAgente, idAgente);
- }
- }
- }
|