This commit is contained in:
Sergio De la torre 2023-07-12 12:40:16 +02:00
parent 66b9250a35
commit 9818b545c2
13 changed files with 157 additions and 86 deletions

View File

@ -42,10 +42,13 @@ class MobileApplication : Application() {
salix = restClient.salixClient
}
fun getPrefs(): SharedPreferences.Editor {
fun getPrefsEditor(): SharedPreferences.Editor {
val prefs: SharedPreferences = getSharedPreferences(PREFS_USER, 0)
return prefs.edit()
}
fun getPrefsShared(): SharedPreferences {
return getSharedPreferences(PREFS_USER, 0)
}
fun playSoundIsOK(bool: Boolean) {
if (bool) mpok!!.start() else mperror!!.start()

View File

@ -11,6 +11,7 @@ import es.verdnatura.presentation.view.feature.collection.listSaleSalix
import es.verdnatura.presentation.view.feature.historicoshelvinglog.model.ShelvingLogSalix
import es.verdnatura.presentation.view.feature.login.model.LoginSalixVO
import es.verdnatura.presentation.view.feature.login.model.OperatorSalix
import es.verdnatura.presentation.view.feature.login.model.RenewToken
import es.verdnatura.presentation.view.feature.login.model.SalixGrupo
import es.verdnatura.presentation.view.feature.login.model.accessConfigSalix
import es.verdnatura.presentation.view.feature.packaging.model.EntrySalix
@ -217,7 +218,7 @@ interface SalixService {
@POST("vnusers/renewToken")
fun renewToken(
):
Call<LoginSalixVO>
Call<RenewToken>
@PATCH("ItemShelvings/{id}")
fun itemShelvingUpdate(

View File

@ -1,12 +1,15 @@
package es.verdnatura.domain
import android.app.Activity
import android.content.Context
import es.verdnatura.R
import android.content.Intent
import es.verdnatura.presentation.base.nameofFunction
import es.verdnatura.presentation.view.feature.login.activity.LoginActivity
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.system.exitProcess
//Se crea interceptor para así generalizar las respuestas y llamadas,
@ -31,6 +34,11 @@ abstract class SilexCallback<T>(val context: Context) : Callback<T> {
if (response.code() == 555) {
var message = JSONObject(response.message()).getString("Message")
onError(Error(message))
} else if (response.code() == 401) {
val intent = Intent(context, LoginActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
exitProcess(0)
} else {
onError(Error(response.message().toString()))
}

View File

@ -30,8 +30,9 @@ class SilexInterceptor : Interceptor {
val newRequest = request.newBuilder()
.addHeader("aplicacion", "json")
.addHeader("version", "1")
.addHeader("user",(context as MobileApplication).userName)
.addHeader("pass", (context as MobileApplication).userPassword)
// Tarea 5613 comentar user y pass cuando en Silex está subido
//.addHeader("user",(context as MobileApplication).userName)
//.addHeader("pass", (context as MobileApplication).userPassword)
.addHeader("Authorization", prefs.getString("token", ""))
.addHeader("Content-Type", "application/json")
.build()

View File

@ -1,10 +1,7 @@
package es.verdnatura.presentation.base
import android.Manifest
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.view.LayoutInflater
@ -45,6 +42,7 @@ abstract class BaseFragment<T : ViewDataBinding, V : BaseViewModel>(viewModelCla
protected val USER = "user"
protected val PASSWORD = "password"
protected val TOKEN = "token"
protected val TTL = "ttl"
protected val TOKENCREATED = "tokenCreated"
protected val SECTORDESCRIP = "sectordescrip"
protected val SECTORFK = "sectorFk"
@ -286,13 +284,6 @@ abstract class BaseFragment<T : ViewDataBinding, V : BaseViewModel>(viewModelCla
tool.backButton.visibility = View.INVISIBLE
}
/* fun cancelSpeech() {
if (mSpeechRecognizer != null) {
mSpeechRecognizer!!.destroy()
mSpeechRecognizer = null
}
}*/
private fun getDefaults(key: String?, context: Context?): String? {
val preferences = PreferenceManager.getDefaultSharedPreferences(context)
return preferences.getString(key, null)
@ -558,9 +549,18 @@ abstract class BaseFragment<T : ViewDataBinding, V : BaseViewModel>(viewModelCla
name -> editor.putInt(name, value)
ANDROID_ID -> editor.putInt(name, value)
}
editor.apply()
}
fun saveDataLong(name: String, value: Long) {
val prefs: SharedPreferences = requireActivity().getSharedPreferences(PREFS_USER, 0)
val editor = prefs.edit()
when (name) {
name -> editor.putLong(name, value)
}
editor.apply()
}

View File

@ -1,6 +1,5 @@
package es.verdnatura.presentation.view.feature.login.fragment
import android.app.Application
import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
@ -22,12 +21,14 @@ import es.verdnatura.presentation.view.feature.login.model.LoginDevice
import es.verdnatura.presentation.view.feature.login.model.LoginSalixVO
import es.verdnatura.presentation.view.feature.login.model.OperatorList
import es.verdnatura.presentation.view.feature.login.model.OperatorSalix
import es.verdnatura.presentation.view.feature.login.model.RenewToken
import es.verdnatura.presentation.view.feature.login.model.accessConfigSalix
import es.verdnatura.presentation.view.feature.login.model.accessConfigSalixList
import es.verdnatura.presentation.view.feature.login.model.versionApp
import es.verdnatura.presentation.view.feature.login.model.workerId
import es.verdnatura.presentation.view.feature.paletizador.model.itemsExpeditionDynamics
import retrofit2.Response
import java.util.Date
class LoginViewModel(val context: Context) : BaseViewModel(context) {
private val _loginsalixitem by lazy { MutableLiveData<LoginSalixVO>() }
@ -73,6 +74,10 @@ class LoginViewModel(val context: Context) : BaseViewModel(context) {
private val _workerOperatorList by lazy { MutableLiveData<OperatorList>() }
private val _accessConfigSalixList by lazy { MutableLiveData<accessConfigSalixList>() }
private val _renewTokenResponse by lazy { MutableLiveData<RenewToken>() }
val renewTokenResponse: LiveData<RenewToken>
get() = _renewTokenResponse
val loadWorkerPrintList = Transformations.map(_workerPrintList) { Event(it) }
val loadOperatorList = Transformations.map(_workerOperatorList) { Event(it) }
val loadAccessConfigSalixList = Transformations.map(_accessConfigSalixList) { Event(it) }
@ -90,6 +95,7 @@ class LoginViewModel(val context: Context) : BaseViewModel(context) {
password,
it.token,
it.created,
it.ttl,
isError = false,
errorMessage = ""
)
@ -174,11 +180,10 @@ class LoginViewModel(val context: Context) : BaseViewModel(context) {
fun worker_getId() {
silex.worker_getId().enqueue(object : SilexCallback<Int>(context) {
override fun onSuccess(response: Response<Int>) {
val prefs = app.getPrefs()
val prefs = app.getPrefsEditor()
response.body()?.let { prefs.putInt("userFk", it) }
prefs.commit()
// operator_getDataSalix("{\"where\": {\"workerFk\":${response.body()?.let {it}}}}")
app.userId = response.body()?.let { it }
}
})
@ -517,30 +522,28 @@ class LoginViewModel(val context: Context) : BaseViewModel(context) {
}
fun renewToken(
) {
println("Renovando loginsalix")
salix.renewToken()
.enqueue(object : SilexCallback<LoginSalixVO>(context) {
.enqueue(object : SilexCallback<RenewToken>(context) {
override fun onSuccess(response: Response<LoginSalixVO>) {
override fun onSuccess(response: Response<RenewToken>) {
var loginSalixVO = response.body()
val prefs = app.getPrefs()
prefs.putString("TOKEN",loginSalixVO!!.token)
prefs.putString("TOKENCREATED",loginSalixVO!!.created)
var RenewToken = response.body()
val prefs = app.getPrefsEditor()
prefs.putString("token", RenewToken!!.id)
prefs.putLong("ttl", RenewToken!!.ttl)
prefs.putLong("tokenCreated", Date().time)
_renewTokenResponse.value = RenewToken
}
override fun onError(t: Throwable) {
val listError: ArrayList<accessConfigSalix> = ArrayList()
listError.add(
accessConfigSalix(
isError = true,
errorMessage = getMessageFromAllResponse(
_renewTokenResponse.value = RenewToken(
"", 0, true, getMessageFromAllResponse(
nameofFunction(this),
t.message!!
)
)
)
_accessConfigSalixList.value = accessConfigSalixList(listError)
}

View File

@ -5,6 +5,13 @@ class LoginSalixVO(
val password: String = "",
val token: String = "",
val created: String = "",
val ttl: Long = 0,
var isError: Boolean = false,
var errorMessage: String = ""
)
class RenewToken(
val id:String,
val ttl: Long = 0,
var isError: Boolean = false,
var errorMessage: String = ""
)

View File

@ -14,6 +14,7 @@ import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.MutableLiveData
import com.google.android.material.bottomnavigation.LabelVisibilityMode.LABEL_VISIBILITY_UNLABELED
import es.verdnatura.MobileApplication
import es.verdnatura.R
@ -52,6 +53,7 @@ import es.verdnatura.presentation.view.feature.historicovehiculo.fragment.Histor
import es.verdnatura.presentation.view.feature.inventario.fragment.InventaryFragment
import es.verdnatura.presentation.view.feature.inventario.fragment.InventaryParkingFragment
import es.verdnatura.presentation.view.feature.login.fragment.LoginViewModel
import es.verdnatura.presentation.view.feature.login.model.RenewToken
import es.verdnatura.presentation.view.feature.main.model.ItemMenuVO
import es.verdnatura.presentation.view.feature.packaging.fragment.ObservFragment
import es.verdnatura.presentation.view.feature.packaging.fragment.PackagingCountFragment
@ -83,10 +85,10 @@ import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.time.Duration
import java.time.Instant
import java.util.Date
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
@ -101,12 +103,27 @@ class MainActivity : BaseActivity<ActivityMainBinding>(), OnPasillerosItemClickL
var mperror: MediaPlayer? = null
var mpok: MediaPlayer? = null
var mpErrorRepeat: MediaPlayer? = null
private var scheduledFuture: ScheduledFuture<*>? = null
private var scheduledExecutor: ScheduledExecutorService? = null
private val _renewTokenResponse = MutableLiveData<RenewToken>()
//Tarea #4815
// var miTime: Long = System.currentTimeMillis() / 1000 / 60 / 60
private var comeFromDelivery: Boolean? = null
override fun getLayoutId(): Int = R.layout.activity_main
override fun onPause() {
super.onPause()
scheduledFuture?.cancel(false)
}
@RequiresApi(Build.VERSION_CODES.O)
override fun onResume() {
super.onResume()
if (scheduledFuture?.isCancelled == true) {
startRepeatingTask((application as MobileApplication).renewInterval)
}
}
@RequiresApi(Build.VERSION_CODES.O)
override fun init() {
@ -117,8 +134,7 @@ class MainActivity : BaseActivity<ActivityMainBinding>(), OnPasillerosItemClickL
customDialog = CustomDialogMainActivity(this)
setFragments()
setBottomMenuFragment()
//Tarea 5613
//startRepeatingTask((application as MobileApplication).renewInterval)
}
@ -126,7 +142,7 @@ class MainActivity : BaseActivity<ActivityMainBinding>(), OnPasillerosItemClickL
private fun startRepeatingTask(myInterval: Long) {
scheduledExecutor = Executors.newSingleThreadScheduledExecutor()
scheduledExecutor?.scheduleAtFixedRate(
scheduledFuture = scheduledExecutor?.scheduleAtFixedRate(
{
runOnUiThread {
checkTokenRenew()
@ -138,6 +154,14 @@ class MainActivity : BaseActivity<ActivityMainBinding>(), OnPasillerosItemClickL
)
}
@RequiresApi(Build.VERSION_CODES.O)
override fun onDestroy() {
super.onDestroy()
scheduledExecutor?.shutdown()
}
@RequiresApi(Build.VERSION_CODES.O)
private fun setFragments() {
try {
val extras = intent.extras
@ -147,17 +171,22 @@ class MainActivity : BaseActivity<ActivityMainBinding>(), OnPasillerosItemClickL
comeFromDelivery = true
val option = extras.getString("menu")
//Tarea 5613 borrar que se guarde
saveDataInt("USERFK", extras.getString("userfk")!!.toInt())
/* saveDataInt("USERFK", extras.getString("userfk")!!.toInt())
saveUserAccesPref(
extras.getString("user").toString(),
extras.getString("password").toString()
)
)*/
// A borrar toda esta parte cuando está oficialmente delivery en picking
var app = application as MobileApplication
app.userName = extras.getString("user").toString()
app.userId = extras.getString("userfk").toString().toInt()
app.userPassword = extras.getString("password").toString()
val prefs: SharedPreferences = getSharedPreferences("es.verdnatura.user.prefs", 0)
val editor = prefs.edit()
editor.putString("token", extras.getString("token").toString())
editor.commit()
when (option) {
"log" -> onPasillerosItemClickListener(
@ -221,20 +250,10 @@ class MainActivity : BaseActivity<ActivityMainBinding>(), OnPasillerosItemClickL
} else {
if (haveSector() && havePrinter()) addFragment(
PasilleroFragment.newInstance(getString(R.string.main), true),
R.id.main_frame_layout,
PasilleroFragment.TAG,
false
//Tarea 5613
startRepeatingTask(
(application as MobileApplication).getPrefsShared().getLong("renewInterval", 0)
)
else addFragment(
AjustesFragment.newInstance(),
R.id.main_frame_layout,
AjustesFragment.TAG,
false
)
if (uriImage != null && uriImage is Uri) {
onPasillerosItemClickListener(
PasillerosItemVO(
@ -248,7 +267,22 @@ class MainActivity : BaseActivity<ActivityMainBinding>(), OnPasillerosItemClickL
), uriImage.toString()
)
} else {
if (haveSector() && havePrinter()) addFragment(
PasilleroFragment.newInstance(getString(R.string.main), true),
R.id.main_frame_layout,
PasilleroFragment.TAG,
false
)
else addFragment(
AjustesFragment.newInstance(),
R.id.main_frame_layout,
AjustesFragment.TAG,
false
)
}
}
} catch (exception: Exception) {
@ -864,6 +898,10 @@ class MainActivity : BaseActivity<ActivityMainBinding>(), OnPasillerosItemClickL
.setDescription(getString(R.string.sureCloseSession))
.setOkButton(getString(R.string.exit)) {
customDialog.dismiss()
//Borrar Token
var getPrefs = (application as MobileApplication).getPrefsEditor()
getPrefs.putString("token", "")
getPrefs.commit()
finish()
}.setKoButton(getString(R.string.cancel)) {
@ -1056,28 +1094,34 @@ class MainActivity : BaseActivity<ActivityMainBinding>(), OnPasillerosItemClickL
@RequiresApi(Build.VERSION_CODES.O)
//Tarea 5613
fun checkTokenRenew() {
// runBlocking {
val prefs = (application as MobileApplication).getPrefsShared()
val renewPeriod = (application as MobileApplication).renewPeriod
val prefs: SharedPreferences = getSharedPreferences("es.verdnatura.user.prefs", 0)
val createdSaved = prefs.getString("tokenCreated", "")
val renewPeriod = (application as MobileApplication).renewInterval
val dateTokenCreated = Instant.parse(createdSaved)
val dateToday = Instant.now()
val duracion = Duration.between(dateTokenCreated, dateToday)
val secondsDifference = duracion.seconds
println("Renovar: Segundos diferencia entre creado y actual" + secondsDifference)
if (secondsDifference < renewPeriod) {
println("REnovar si")
var min = minOf(prefs.getLong("ttl", 0), renewPeriod) * 1000
/* println("Renovar: ****************************")
println("Renovar: el min es " + min)
println("Renovar: el ttl es " + prefs.getLong("ttl", 0))
println("Renovar: el renewPeriod será $renewPeriod")
println("Renovar segundos :" + (min + Date().time) / 1000)
println("Renovar token created :" + prefs.getLong("tokenCreated", 0))
println("Renovar fecha vida:" + (min + prefs.getLong("ttl", 0)))
println("Renovar fecha hui:" + Date().time)
println("Renovar: ****************************")
*/
if (Date().time < (min + prefs.getLong("tokenCreated", 0))) {
val loginViewModel = LoginViewModel(application as MobileApplication)
loginViewModel.renewToken()
} else {
println("Renovar no")
/* val loginViewModel = LoginViewModel(application as MobileApplication)
//val loginViewModel = ViewModelProvider(this).get(LoginViewModel::class.java)
loginViewModel.renewToken()*/
loginViewModel.renewTokenResponse.observe(this) { renewToken ->
if (!renewToken.isError) {
val prefsEditor = (application as MobileApplication).getPrefsEditor()
prefsEditor.putString("token", renewToken.id)
prefsEditor.putLong("ttl", renewToken.ttl)
prefsEditor.putLong("tokenCreated", Date().time)
prefsEditor.apply()
}
}
}
}

View File

@ -122,7 +122,7 @@
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="@dimen/default_layout_margin"
android:text="@string/Recordarusuarioycontraseña"
android:text="@string/saveSesion"
android:textColor="@android:color/white"
android:textSize="@dimen/body2"
android:textStyle="bold"

View File

@ -611,5 +611,6 @@
<string name="scanItemForChecking">Escanea artículo a verificar</string>
<string name="itemNotFoundScanAgain">Artículo no encontrado. Escanea de nuevo el carro</string>
<string name="scanShelvingAgain">Escanea matrícula de nuevo</string>
<string name="saveSesion">Recordar sesión</string>
</resources>

View File

@ -611,5 +611,6 @@
<string name="scanItemForChecking">Escanea artículo a verificar</string>
<string name="itemNotFoundScanAgain">Artículo no encontrado. Escanea de nuevo el carro</string>
<string name="scanShelvingAgain">Escanea matrícula de nuevo</string>
<string name="saveSesion">Recordar sesión</string>
</resources>

View File

@ -611,5 +611,6 @@
<string name="scanItemForChecking">Escanea artículo a verificar</string>
<string name="itemNotFoundScanAgain">Artículo no encontrado. Escanea de nuevo el carro</string>
<string name="scanShelvingAgain">Escanea matrícula de nuevo</string>
<string name="saveSesion">Recordar sesión</string>
</resources>

View File

@ -29,6 +29,7 @@
<string name="Borrardatosdeacceso">Clear access data</string>
<string name="Bienvenido">Welcome</string>
<string name="Recordarusuarioycontraseña">Remember username and password</string>
<string name="saveSesion">Remember sesion data</string>
<string name="titleFaults">Foults</string>
<string name="Versión">Version</string>
<string name="name">Company</string>