|
| 1 | +package com.swiftpos.core.data.sync |
| 2 | + |
| 3 | +import android.content.Context |
| 4 | +import androidx.hilt.work.HiltWorker |
| 5 | +import androidx.work.CoroutineWorker |
| 6 | +import androidx.work.WorkerParameters |
| 7 | +import com.swiftpos.core.data.local.TransactionDao |
| 8 | +import com.swiftpos.core.data.remote.SyncApi |
| 9 | +import com.swiftpos.core.data.repository.toDomain |
| 10 | +import dagger.assisted.Assisted |
| 11 | +import dagger.assisted.AssistedInject |
| 12 | + |
| 13 | +@HiltWorker |
| 14 | +class TransactionSyncWorker @AssistedInject constructor( |
| 15 | + @Assisted context: Context, |
| 16 | + @Assisted workerParams: WorkerParameters, |
| 17 | + private val transactionDao: TransactionDao, |
| 18 | + private val syncApi: SyncApi |
| 19 | +) : CoroutineWorker(context, workerParams) { |
| 20 | + |
| 21 | + override suspend fun doWork(): Result { |
| 22 | + return try { |
| 23 | + val unsyncedEntities = transactionDao.getUnsyncedTransactions() |
| 24 | + |
| 25 | + if (unsyncedEntities.isEmpty()) { |
| 26 | + return Result.success() |
| 27 | + } |
| 28 | + |
| 29 | + // Map entities to domain model |
| 30 | + val transactions = unsyncedEntities.map { it.toDomain() } |
| 31 | + |
| 32 | + // Push to remote API |
| 33 | + syncApi.syncTransactions(transactions) |
| 34 | + |
| 35 | + // Mark as synced locally |
| 36 | + val syncedIds = unsyncedEntities.map { it.id } |
| 37 | + transactionDao.markAsSynced(syncedIds) |
| 38 | + |
| 39 | + Result.success() |
| 40 | + } catch (e: Exception) { |
| 41 | + Result.retry() |
| 42 | + } |
| 43 | + } |
| 44 | +} |
0 commit comments