day3_commit2_vse_slomalos

This commit is contained in:
Terebov_Maksim 2025-02-20 16:41:48 +03:00
parent e83718bce0
commit 0eb8ec5872
5 changed files with 201 additions and 55 deletions

View File

@ -0,0 +1,82 @@
kotlin version: 2.0.21
error message: Daemon compilation failed: null
java.lang.Exception
at org.jetbrains.kotlin.daemon.common.CompileService$CallResult$Error.get(CompileService.kt:69)
at org.jetbrains.kotlin.daemon.common.CompileService$CallResult$Error.get(CompileService.kt:65)
at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.compileWithDaemon(GradleKotlinCompilerWork.kt:240)
at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.compileWithDaemonOrFallbackImpl(GradleKotlinCompilerWork.kt:159)
at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.run(GradleKotlinCompilerWork.kt:111)
at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunnerWithWorkers$GradleKotlinCompilerWorkAction.execute(GradleCompilerRunnerWithWorkers.kt:76)
at org.gradle.workers.internal.DefaultWorkerServer.execute(DefaultWorkerServer.java:63)
at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1.create(NoIsolationWorkerFactory.java:66)
at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1.create(NoIsolationWorkerFactory.java:62)
at org.gradle.internal.classloader.ClassLoaderUtils.executeInClassloader(ClassLoaderUtils.java:100)
at org.gradle.workers.internal.NoIsolationWorkerFactory$1.lambda$execute$0(NoIsolationWorkerFactory.java:62)
at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:44)
at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:41)
at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:209)
at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:204)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:166)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:53)
at org.gradle.workers.internal.AbstractWorker.executeWrappedInBuildOperation(AbstractWorker.java:41)
at org.gradle.workers.internal.NoIsolationWorkerFactory$1.execute(NoIsolationWorkerFactory.java:59)
at org.gradle.workers.internal.DefaultWorkerExecutor.lambda$submitWork$0(DefaultWorkerExecutor.java:174)
at java.base/java.util.concurrent.FutureTask.run(Unknown Source)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runExecution(DefaultConditionalExecutionQueue.java:195)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.access$700(DefaultConditionalExecutionQueue.java:128)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner$1.run(DefaultConditionalExecutionQueue.java:170)
at org.gradle.internal.Factories$1.create(Factories.java:31)
at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:267)
at org.gradle.internal.work.DefaultWorkerLeaseService.runAsWorkerThread(DefaultWorkerLeaseService.java:131)
at org.gradle.internal.work.DefaultWorkerLeaseService.runAsWorkerThread(DefaultWorkerLeaseService.java:136)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runBatch(DefaultConditionalExecutionQueue.java:165)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.run(DefaultConditionalExecutionQueue.java:134)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.base/java.util.concurrent.FutureTask.run(Unknown Source)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
at org.gradle.internal.concurrent.AbstractManagedExecutor$1.run(AbstractManagedExecutor.java:48)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
Caused by: java.nio.file.DirectoryNotEmptyException: C:\Users\User\AppData\Local\Temp\kotlin-backups1146231745401124119
at java.base/sun.nio.fs.WindowsFileSystemProvider.implDelete(Unknown Source)
at java.base/sun.nio.fs.AbstractFileSystemProvider.delete(Unknown Source)
at java.base/java.nio.file.Files.delete(Unknown Source)
at org.jetbrains.kotlin.incremental.RecoverableCompilationTransaction$cleanupStash$2$1$1.invoke(CompilationTransaction.kt:244)
at org.jetbrains.kotlin.incremental.RecoverableCompilationTransaction$cleanupStash$2$1$1.invoke(CompilationTransaction.kt:244)
at org.jetbrains.kotlin.incremental.RecoverableCompilationTransaction.cleanupStash$lambda$11$lambda$10$lambda$9(CompilationTransaction.kt:244)
at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(Unknown Source)
at java.base/java.util.ArrayList.forEach(Unknown Source)
at java.base/java.util.stream.SortedOps$RefSortingSink.end(Unknown Source)
at java.base/java.util.stream.Sink$ChainedReference.end(Unknown Source)
at java.base/java.util.stream.AbstractPipeline.copyInto(Unknown Source)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(Unknown Source)
at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(Unknown Source)
at java.base/java.util.stream.AbstractPipeline.evaluate(Unknown Source)
at java.base/java.util.stream.ReferencePipeline.forEach(Unknown Source)
at org.jetbrains.kotlin.incremental.RecoverableCompilationTransaction.cleanupStash(CompilationTransaction.kt:244)
at org.jetbrains.kotlin.incremental.RecoverableCompilationTransaction.close(CompilationTransaction.kt:254)
at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.tryCompileIncrementally(IncrementalCompilerRunner.kt:747)
at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compile(IncrementalCompilerRunner.kt:120)
at org.jetbrains.kotlin.daemon.CompileServiceImplBase.execIncrementalCompiler(CompileServiceImpl.kt:675)
at org.jetbrains.kotlin.daemon.CompileServiceImplBase.access$execIncrementalCompiler(CompileServiceImpl.kt:92)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:1660)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at java.rmi/sun.rmi.server.UnicastServerRef.dispatch(Unknown Source)
at java.rmi/sun.rmi.transport.Transport$1.run(Unknown Source)
at java.rmi/sun.rmi.transport.Transport$1.run(Unknown Source)
at java.base/java.security.AccessController.doPrivileged(Unknown Source)
at java.rmi/sun.rmi.transport.Transport.serviceCall(Unknown Source)
at java.rmi/sun.rmi.transport.tcp.TCPTransport.handleMessages(Unknown Source)
at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(Unknown Source)
at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(Unknown Source)
at java.base/java.security.AccessController.doPrivileged(Unknown Source)
at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(Unknown Source)
... 3 more

View File

@ -1,6 +1,5 @@
package ru.myitschool.work.api
import okhttp3.ResponseBody
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.GET
@ -28,7 +27,10 @@ interface ApiService {
suspend fun getEmployeeInfo(@Path("login") login: String): Response<EmployeeData>
@PATCH("/api/open") // Открыть дверь
suspend fun openDoor(@Body request: OpenDoorRequest): Response<Unit> // Измените Response<String> на Response<Unit>
suspend fun openDoor(
@Header("Authorization") authHeader: String,
@Body request: OpenDoorRequest
): Response<Unit> // Измените Response<String> на Response<Unit>
@POST("/api/employee/toggleAccess") // Метод для блокировки/разблокировки доступа
suspend fun toggleAccess(@Body request: ToggleAccessRequest): Response<Unit>
@ -41,7 +43,8 @@ interface ApiService {
data class EmployeeData(
val name: String,
val position: String,
val lastVisit: String
val lastVisit: String,
val avatarUrl: String? // Добавьте это поле
)
// Модель данных для запроса блокировки/разблокировки доступа
@ -52,6 +55,5 @@ data class ToggleAccessRequest(
// Модель данных для запроса открытия двери
data class OpenDoorRequest(
val login: String, // Логин сотрудника
val value: Long // Код для открытия двери
)

View File

@ -1,12 +1,14 @@
package ru.myitschool.work.ui.main
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.setFragmentResultListener
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.squareup.picasso.Picasso
import kotlinx.coroutines.launch
import ru.myitschool.work.R
import ru.myitschool.work.api.ApiService
@ -44,6 +46,83 @@ class MainFragment : Fragment(R.layout.fragment_main) {
checkQrResult()
}
private fun setupUI() {
binding.refresh.setOnClickListener {
fetchUserInfo()
}
binding.scanQrCode?.setOnClickListener {
// Переход к экрану сканирования QR-кода
findNavController().navigate(R.id.qrScanFragment) // Убедитесь, что у вас есть правильный ID для навигации
}
// Проверяем роль пользователя и показываем кнопку AdminPanel, если роль admin
if (SessionManager.userRole == "admin") {
binding.adminPanelButton?.visibility = View.VISIBLE
binding.adminPanelButton?.setOnClickListener {
findNavController().navigate(R.id.adminFragment) // Переход к экрану администратора
}
} else {
binding.adminPanelButton?.visibility = View.GONE // Скрываем кнопку, если не admin
}
}
private fun fetchUserInfo() {
lifecycleScope.launch {
val login = SessionManager.userLogin ?: run {
binding.error.text = "Пользователь не авторизован"
binding.error.visibility = View.VISIBLE
return@launch
}
val authHeader = SessionManager.getAuthHeader() ?: run {
binding.error.text = "Ошибка авторизации"
binding.error.visibility = View.VISIBLE
return@launch
}
try {
val response = apiService.getUserInfo(login, authHeader)
// Логируем код ответа
Log.d("MainFragment", "Response code: ${response.code()}")
if (response.isSuccessful) {
val employeeData = response.body()
employeeData?.let {
binding.fullname.text = it.name
binding.position.text = it.position
binding.lastEntry.text = it.lastVisit
// Логируем URL аватара
Log.d("MainFragment", "Avatar URL: ${it.avatarUrl}")
// Загрузка аватара с помощью Picasso
if (it.avatarUrl != null) {
Picasso.get()
.load(it.avatarUrl)
.placeholder(R.drawable.ic_refresh) // Замените на ваш ресурс-заполнитель
.error(R.drawable.ic_close) // Замените на ваш ресурс ошибки
.into(binding.photo)
binding.photo.visibility = View.VISIBLE
} else {
binding.photo.visibility = View.GONE // Скрыть, если URL нет
}
// Показываем кнопку "Сканировать QR-код" после успешного получения данных
binding.scanQrCode?.visibility = View.VISIBLE
}
} else {
binding.error.text = "Ошибка получения данных: ${response.message()}"
binding.error.visibility = View.VISIBLE
}
} catch (e: Exception) {
Log.e("MainFragment", "Error fetching user info", e)
binding.error.text = "Ошибка сети: ${e.message}"
binding.error.visibility = View.VISIBLE
}
}
}
private fun checkQrResult() {
// Слушаем результат QR сканирования
setFragmentResultListener(QrScanDestination.REQUEST_KEY) { _, bundle ->
@ -58,44 +137,6 @@ class MainFragment : Fragment(R.layout.fragment_main) {
}
}
private fun setupUI() {
binding.refresh.setOnClickListener {
fetchUserInfo()
}
binding.scanQrCode?.setOnClickListener {
// Переход к экрану сканирования QR-кода
findNavController().navigate(R.id.qrScanFragment) // Убедитесь, что у вас есть правильный ID для навигации
}
}
private fun fetchUserInfo() {
lifecycleScope.launch {
val login = SessionManager.userLogin ?: return@launch
val authHeader = SessionManager.getAuthHeader()
val response = apiService.getUserInfo(login, authHeader)
if (response.isSuccessful) {
val employeeData = response.body()
employeeData?.let {
binding.fullname.text = it.name
binding.position.text = it.position
binding.lastEntry.text = it.lastVisit
binding.photo.visibility = View.VISIBLE
binding.fullname.visibility = View.VISIBLE
binding.position.visibility = View.VISIBLE
binding.lastEntry.visibility = View.VISIBLE
// Показываем кнопку "Сканировать QR-код" после успешного получения данных
binding.scanQrCode?.visibility = View.VISIBLE
}
} else {
binding.error.text = "Ошибка получения данных"
binding.error.visibility = View.VISIBLE
}
}
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()

View File

@ -8,6 +8,7 @@ import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.util.Base64
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
@ -62,25 +63,37 @@ class QrResult : Fragment(R.layout.fragment_qr_scan_result) {
private fun sendRequestToServer(qrData: String) {
lifecycleScope.launch {
try {
val login = SessionManager.userLogin
if (login != null) {
val openDoorRequest = OpenDoorRequest(login, qrData.toLong()) // Преобразуем qrData в Long
val response = apiService.openDoor(openDoorRequest)
if (response.isSuccessful) {
binding.result.text = "Успешно/Success"
} else {
binding.result.text = "Что-то пошло не так/Something went wrong: ${response.message()}"
}
val qrValue = qrData.toLong() // Преобразуем данные QR-кода в Long
val login = SessionManager.userLogin ?: "default_login" // Замените на ваш логин
val password = "your_password" // Замените на ваш пароль
val authHeader = "Basic " + Base64.encodeToString("$login:$password".toByteArray(), Base64.NO_WRAP)
// Логируем данные перед отправкой
Log.d("QrResult", "Sending request with QR value: $qrValue and authHeader: $authHeader")
// Создаем объект запроса
val request = OpenDoorRequest(qrValue)
// Вызываем метод openDoor с правильными параметрами
val response = apiService.openDoor(authHeader, request)
// Логируем код ответа и тело ответа
Log.d("QrResult", "Response code: ${response.code()}")
Log.d("QrResult", "Response body: ${response.body()}")
if (response.isSuccessful) {
binding.result.text = "Door Opened" // Сообщение о том, что дверь открыта
} else {
binding.result.text = "Пользователь не авторизован/Unauthorized user"
binding.result.text = "Door Closed" // Сообщение о том, что дверь закрыта
}
} catch (e: NumberFormatException) {
binding.result.text = "Некорректные данные QR-кода"
} catch (e: Exception) {
binding.result.text = "Что-то пошло не так/Something went wrong: ${e.message}"
Log.e("QrResult", "Error sending request to server", e)
binding.result.text = "Что-то пошло не так: ${e.message}"
Log.e("QrResult", "Error: ${e.message}", e) // Логируем ошибку
}
}
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()

View File

@ -54,4 +54,12 @@
android:layout_height="wrap_content"
android:text="Сканировать QR-код"
android:visibility="gone" />
<Button
android:id="@+id/adminPanelButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Admin Panel"
android:visibility="gone" />
</LinearLayout>