content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package ru.netology.nework.viewmodel import android.app.Application import android.net.Uri import androidx.core.net.toFile import androidx.core.net.toUri import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.asLiveData import androidx.lifecycle.switchMap import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import ru.netology.nework.auth.AppAuth import ru.netology.nework.auxiliary.ConstantValues.emptyPost import ru.netology.nework.auxiliary.ConstantValues.noPhoto import ru.netology.nework.model.FeedModel import ru.netology.nework.model.FeedModelState import ru.netology.nework.repository.Repository import ru.netology.nework.auxiliary.SingleLiveEvent import ru.netology.nework.dto.Attachment import ru.netology.nework.dto.AttachmentType import ru.netology.nework.dto.MediaUpload import ru.netology.nework.dto.Post import ru.netology.nework.model.MediaModel import java.io.File import javax.inject.Inject @HiltViewModel class PostViewModel @Inject constructor( application: Application, private val repository: Repository, private val appAuth: AppAuth ) : AndroidViewModel(application) { @OptIn(ExperimentalCoroutinesApi::class) val data: LiveData<FeedModel> get() = appAuth .authStateFlow .flatMapLatest { (myId, _) -> repository.data .map { posts -> FeedModel( posts.map { it.copy(ownedByMe = it.authorId == myId) }, posts.isEmpty() ) } }.asLiveData(Dispatchers.Default) private val _dataState = MutableLiveData<FeedModelState>(FeedModelState.Idle) val dataState: LiveData<FeedModelState> get() = _dataState private val edited = MutableLiveData(emptyPost) private val _postCreated = SingleLiveEvent<Unit>() val postCreated: LiveData<Unit> get() = _postCreated private val _media = MutableLiveData( MediaModel( edited.value?.attachment?.url?.toUri(), edited.value?.attachment?.url?.toUri()?.toFile(), edited.value?.attachment?.type ) ) val media: LiveData<MediaModel> get() = _media val newerCount: LiveData<Int> = data.switchMap { repository.getNewerCount(it.posts.firstOrNull()?.id ?: 0L) .catch { e -> e.printStackTrace() } .asLiveData(Dispatchers.Default) } fun changeMedia(uri: Uri?, file: File?, attachmentType: AttachmentType?) { _media.value = MediaModel(uri, file, attachmentType) } init { loadPosts() } fun viewNewPosts() = viewModelScope.launch { try { repository.showNewPosts() _dataState.value = FeedModelState.ShadowIdle } catch (e: Exception) { _dataState.value = FeedModelState.Error } } fun loadPosts() = viewModelScope.launch { try { _dataState.value = FeedModelState.Loading repository.getAllAsync() _dataState.value = FeedModelState.ShadowIdle } catch (e: Exception) { _dataState.value = FeedModelState.Error } } fun refreshPosts() = viewModelScope.launch { try { _dataState.value = FeedModelState.Refresh repository.getAllAsync() _dataState.value = FeedModelState.ShadowIdle } catch (e: Exception) { _dataState.value = FeedModelState.Error } } fun likeById(post: Post) { viewModelScope.launch { try { repository.likeByIdAsync(post) } catch (e: Exception) { _dataState.value = FeedModelState.Error } } } fun removeById(id: Long) { viewModelScope.launch { try { repository.removeByIdAsync(id) _dataState.value = FeedModelState.Idle } catch (e: Exception) { _dataState.value = FeedModelState.Error } } } fun edit(post: Post) { edited.value = post } fun getEditedId(): Long { return edited.value?.id ?: 0 } fun getEditedPostAttachment(): Attachment? { return edited.value?.attachment } fun changeContent(content: String, link: String?, mentionsIds:List<Long>) { val text = content.trim() if (edited.value?.content == text && edited.value?.link == link && edited.value?.mentionIds == mentionsIds) return edited.value = edited.value?.copy(content = text, link = link, mentionIds = mentionsIds) } fun deleteAttachment() { edited.value = edited.value?.copy(attachment = null) } fun save() { edited.value?.let { savingPost -> _postCreated.value = Unit viewModelScope.launch { try { when (_media.value) { noPhoto -> repository.saveAsync(savingPost) else -> _media.value?.file?.let { file -> repository.saveWithAttachment(savingPost, MediaUpload(file), _media.value!!.attachmentType!!) } } _dataState.value = FeedModelState.Idle } catch (e: Exception) { _dataState.value = FeedModelState.Error } } } edited.value = emptyPost _media.value = noPhoto } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/viewmodel/PostViewModel.kt
1046824149
package ru.netology.nework.viewmodel import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.flow import kotlinx.coroutines.launch import ru.netology.nework.auth.AppAuth import ru.netology.nework.auxiliary.ConstantValues import ru.netology.nework.dto.* import ru.netology.nework.repository.Repository import javax.inject.Inject @HiltViewModel class JobViewModel @Inject constructor( application: Application, private val repository: Repository, private val appAuth: AppAuth ) : AndroidViewModel(application) { val data: Flow<List<Job>> get() = flow { while (true) { loadAllJobs() emit(_data) delay(1_000) } } private var _data: List<Job> = listOf() private val edited = MutableLiveData(ConstantValues.emptyJob) init { loadMyJobs() } private fun loadAllJobs() = viewModelScope.launch { repository.dataJobs.collectLatest { _data = it } } fun loadMyJobs() = viewModelScope.launch { try { repository.getMyJobs(appAuth.authStateFlow.value.id) } catch (_: Exception) { } repository.dataJobs.collectLatest { listAllJob -> _data = listAllJob.filter { job -> job.ownerId == appAuth.authStateFlow.value.id } } } fun loadUserJobs(id: Long) = viewModelScope.launch { try { repository.getJobs(id) } catch (_: Exception) { } repository.dataJobs.collectLatest { listAllJob -> _data = listAllJob.filter { job -> job.ownerId == id } } } fun removeById(id: Long) = viewModelScope.launch { try { repository.removeJobById(id) } catch (_: Exception) { } } fun edit(job: Job) { edited.value = job } fun getEditedId(): Long { return edited.value?.id ?: 0 } fun changeContent( name: String, position: String, start: String, finish: String?, link: String? ) { if (edited.value?.name == name && edited.value?.position == position && edited.value?.start == start && edited.value?.finish == finish && edited.value?.link == link ) return edited.value = edited.value?.copy( name = name, position = position, start = start, finish = finish, link = link ) } fun save() { viewModelScope.launch { try { edited.value?.let { repository.saveJob(it) } } catch (_: Exception) { } } edited.value = ConstantValues.emptyJob } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/viewmodel/JobViewModel.kt
3623725999
package ru.netology.nework.viewmodel import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.delay import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.flow import kotlinx.coroutines.launch import ru.netology.nework.dto.User import ru.netology.nework.repository.Repository import javax.inject.Inject @HiltViewModel class UsersViewModel @Inject constructor( application: Application, private val repository: Repository, ) : AndroidViewModel(application) { val dataUsersList get() = flow { while (true) { getData() emit(_dataUsersList) delay(1_000) } } private var _dataUsersList: List<User> = listOf() private fun getData() = viewModelScope.launch { try { repository.getUsers() } catch (_: Exception) { } repository.dataUsers.collectLatest { _dataUsersList = it } } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/viewmodel/UsersViewModel.kt
2925122720
package ru.netology.nework.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import com.bumptech.glide.Glide import dagger.hilt.android.AndroidEntryPoint import ru.netology.nework.R import ru.netology.nework.auxiliary.Companion.Companion.textArg import ru.netology.nework.databinding.FragmentAttachmentImageViewBinding @AndroidEntryPoint class ViewImageAttach : Fragment() { private lateinit var binding: FragmentAttachmentImageViewBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentAttachmentImageViewBinding.inflate(layoutInflater) val url = arguments?.textArg ?: "" Glide.with(binding.image) .load(url) .placeholder(R.drawable.not_image_500) .timeout(10_000) .into(binding.image) binding.fabCancel.setOnClickListener { findNavController().navigateUp() } return binding.root } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/ui/ViewImageAttach.kt
2309463195
package ru.netology.nework.ui import android.annotation.SuppressLint import android.app.Activity import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.core.net.toFile import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import com.github.dhaval2404.imagepicker.ImagePicker import com.google.android.material.snackbar.Snackbar import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.* import ru.netology.nework.R import ru.netology.nework.auxiliary.Companion.Companion.textArg import ru.netology.nework.databinding.FragmentAuthBinding import ru.netology.nework.dto.MediaUpload import ru.netology.nework.viewmodel.AuthViewModel import kotlin.coroutines.EmptyCoroutineContext @AndroidEntryPoint class AuthFragment : Fragment() { private val binding by lazy { FragmentAuthBinding.inflate(layoutInflater) } private val viewModel: AuthViewModel by viewModels() private var fragmentBinding: FragmentAuthBinding? = null @SuppressLint("SetTextI18n") override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { fragmentBinding = binding binding.authBlock.isVisible = true val isSignIn = arguments?.textArg == getString(R.string.sign_in) if (isSignIn) { binding.signUpGroup.visibility = View.GONE binding.enterInSystem.setText(R.string.sign_in) } else { binding.signUpGroup.visibility = View.VISIBLE binding.enterInSystem.setText(R.string.sign_up) } val pickPhotoLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { when (it.resultCode) { ImagePicker.RESULT_ERROR -> { Snackbar.make( binding.root, ImagePicker.getError(it.data), Snackbar.LENGTH_LONG ).show() } Activity.RESULT_OK -> { val uri: Uri? = it.data?.data viewModel.changePhoto(uri, uri?.toFile()) } } } binding.uploadAvatar.setOnClickListener { ImagePicker.with(this) .cropSquare() .compress(512) .galleryMimeTypes( arrayOf( "image/png", "image/jpeg", ) ) .createIntent(pickPhotoLauncher::launch) } viewModel.photo.observe(viewLifecycleOwner) { if (it.uri == null) { binding.uploadAvatar.visibility = View.VISIBLE binding.photoContainer.visibility = View.GONE return@observe } binding.uploadAvatar.visibility = View.GONE binding.photoContainer.visibility = View.VISIBLE binding.photo.setImageURI(it.uri) } viewModel.dataState.observe(viewLifecycleOwner) { when (it) { 0 -> findNavController().navigateUp() -1 -> { binding.errorMessage.visibility = View.GONE } 1 -> { binding.errorMessage.visibility = View.VISIBLE binding.errorMessage.setText(R.string.not_pass_enter) } else -> { binding.errorMessage.visibility = View.VISIBLE binding.errorMessage.text = getString(R.string.eror_code) + ": $it" } } } with(binding) { removePhoto.setOnClickListener { viewModel.changePhoto(null, null) } enterInSystem.setOnClickListener { binding.errorMessage.visibility = View.GONE val scope = CoroutineScope(EmptyCoroutineContext) if (isSignIn) { inputEditPasswordConfirm.text = inputEditPassword.text val login = binding.inputEditLogin.text.toString() val pass = binding.inputEditPassword.text.toString() scope.launch { viewModel.login(login, pass) } } else { if (inputEditPasswordConfirm.text.toString() != inputEditPassword.text.toString()) { Toast.makeText( requireContext(), R.string.error_password_not_ident, Toast.LENGTH_SHORT ).show() return@setOnClickListener } else { val login = binding.inputEditLogin.text.toString() val pass = binding.inputEditPassword.text.toString() val name = binding.inputEditName.text.toString() val photo = viewModel.photo.value?.file?.let { file -> MediaUpload(file) } scope.launch { viewModel.registerWithPhoto(login, pass, name, photo) } } } } return root } } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/ui/AuthFragment.kt
1315951180
package ru.netology.nework.ui import android.os.Bundle import android.view.LayoutInflater import androidx.navigation.fragment.findNavController import android.view.View import android.view.ViewGroup import androidx.fragment.app.activityViewModels import androidx.lifecycle.lifecycleScope import ru.netology.nework.R import ru.netology.nework.adapters.OnInteractionListenerUsers import com.google.android.material.bottomsheet.BottomSheetDialogFragment import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collectLatest import ru.netology.nework.adapters.UsersAdapter import ru.netology.nework.auxiliary.Companion.Companion.eventId import ru.netology.nework.auxiliary.Companion.Companion.eventRequestType import ru.netology.nework.auxiliary.Companion.Companion.userId import ru.netology.nework.dto.User import ru.netology.nework.databinding.FragmentBottomSheetBinding import ru.netology.nework.viewmodel.EventViewModel import ru.netology.nework.viewmodel.UsersViewModel @AndroidEntryPoint class BottomSheetFragment : BottomSheetDialogFragment() { private val usersViewModel: UsersViewModel by activityViewModels() val viewModel: EventViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val binding = FragmentBottomSheetBinding.inflate(inflater, container, false) val adapter = UsersAdapter(object : OnInteractionListenerUsers { override fun onTap(user: User) { findNavController().navigate( R.id.action_bottomSheetFragment_to_profileFragment, Bundle().apply { userId = user.id } ) } }) var filteredList: List<Long> = emptyList() binding.list.adapter = adapter lifecycleScope.launchWhenCreated { viewModel.data.collectLatest { when (arguments?.eventRequestType) { "speakers" -> filteredList = it.find { event -> event.id == arguments?.eventId }?.speakerIds ?: emptyList() "party" -> filteredList = it.find { event -> event.id == arguments?.eventId }?.participantsIds ?: emptyList() else -> emptyList<Long>() } } } lifecycleScope.launchWhenCreated { usersViewModel.dataUsersList.collectLatest { adapter.submitList(it.filter { user -> filteredList.contains(user.id) }) } } return binding.root } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/ui/BottomSheetFragment.kt
555235748
package ru.netology.nework.ui import android.app.AlertDialog import ru.netology.nework.adapters.OnInteractionListenerUsers import ru.netology.nework.auxiliary.Companion.Companion.userId import ru.netology.nework.dto.User import android.os.Bundle import android.view.* import androidx.core.view.MenuProvider import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import ru.netology.nework.R import androidx.navigation.fragment.findNavController import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collectLatest import ru.netology.nework.adapters.UsersAdapter import ru.netology.nework.auth.AppAuth import ru.netology.nework.auxiliary.Companion.Companion.textArg import ru.netology.nework.auxiliary.FloatingValue.currentFragment import ru.netology.nework.databinding.FragmentUsersBinding import ru.netology.nework.viewmodel.AuthViewModel import ru.netology.nework.viewmodel.UsersViewModel import javax.inject.Inject @AndroidEntryPoint class UsersFragment : Fragment() { @Inject lateinit var appAuth: AppAuth override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val binding = FragmentUsersBinding.inflate(layoutInflater) val viewModel: UsersViewModel by activityViewModels() val authViewModel: AuthViewModel by viewModels() var menuProvider: MenuProvider? = null val adapter = UsersAdapter( object : OnInteractionListenerUsers { override fun onTap(user: User) { findNavController().navigate( R.id.action_usersFragment_to_profileFragment, Bundle().apply { userId = user.id } ) } } ) authViewModel.data.observe(viewLifecycleOwner) { menuProvider?.let(requireActivity()::removeMenuProvider) requireActivity().addMenuProvider(object : MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { menuInflater.inflate(R.menu.menu_main, menu) menu.setGroupVisible(R.id.unauthenticated, !authViewModel.authenticated) menu.setGroupVisible(R.id.authenticated, authViewModel.authenticated) } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { return when (menuItem.itemId) { R.id.signin -> { findNavController().navigate( R.id.action_usersFragment_to_authFragment, Bundle().apply { textArg = getString(R.string.sign_in) } ) true } R.id.signup -> { findNavController().navigate( R.id.action_usersFragment_to_authFragment, Bundle().apply { textArg = getString(R.string.sign_up) } ) true } R.id.signout -> { AlertDialog.Builder(requireActivity()) .setTitle(R.string.are_you_suare) .setPositiveButton(R.string.yes) { _, _ -> appAuth.removeAuth() } .setCancelable(true) .setNegativeButton(R.string.no, null) .create() .show() true } else -> false } } }.apply { menuProvider = this }, viewLifecycleOwner) } binding.mainNavView.setOnItemSelectedListener{ menuItem -> when (menuItem.itemId) { R.id.navigation_posts -> { findNavController().navigate(R.id.action_usersFragment_to_feedFragment) true } R.id.navigation_events -> { findNavController().navigate(R.id.action_usersFragment_to_eventsFragment) true } R.id.navigation_users -> { true } R.id.navigation_profile -> { findNavController().navigate(R.id.action_usersFragment_to_profileFragment) true } else -> false } } binding.mainNavView.selectedItemId = R.id.navigation_users binding.listUsers.adapter = adapter lifecycleScope.launchWhenCreated { viewModel.dataUsersList.collectLatest { adapter.submitList(it) } } return binding.root } override fun onStart() { currentFragment = javaClass.simpleName super.onStart() } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/ui/UsersFragment.kt
1031359548
package ru.netology.nework.ui import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.view.* import androidx.activity.result.contract.ActivityResultContracts import androidx.core.net.toFile import androidx.core.view.MenuProvider import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import com.bumptech.glide.Glide import com.github.dhaval2404.imagepicker.ImagePicker import com.github.dhaval2404.imagepicker.constant.ImageProvider import com.google.android.material.snackbar.Snackbar import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collectLatest import ru.netology.nework.R import ru.netology.nework.adapters.OnInteractionListenerUsers import ru.netology.nework.adapters.UsersAdapter import ru.netology.nework.auxiliary.AndroidUtils.hideKeyboard import ru.netology.nework.auxiliary.Companion.Companion.textArg import ru.netology.nework.auxiliary.ConstantValues.emptyEvent import ru.netology.nework.auxiliary.FloatingValue.currentFragment import ru.netology.nework.auxiliary.FloatingValue.getExtensionFromUri import ru.netology.nework.auxiliary.FloatingValue.textNewPost import ru.netology.nework.databinding.FragmentNewEventBinding import ru.netology.nework.dto.Attachment import ru.netology.nework.dto.AttachmentType import ru.netology.nework.dto.EventType import ru.netology.nework.dto.User import ru.netology.nework.viewmodel.EventViewModel import ru.netology.nework.viewmodel.UsersViewModel import java.io.File import java.io.FileOutputStream @AndroidEntryPoint class NewEventFragment : Fragment() { private val binding by lazy { FragmentNewEventBinding.inflate(layoutInflater) } private val viewModel: EventViewModel by activityViewModels() private val userViewModel: UsersViewModel by viewModels() private var event = emptyEvent private var fragmentBinding: FragmentNewEventBinding? = null private var type: AttachmentType? = null private var attachRes: Attachment? = null private var speakersIds:MutableList<Long> = mutableListOf() private var typeEvent:EventType = EventType.ONLINE private var adapter = UsersAdapter(object : OnInteractionListenerUsers { override fun onTap(user: User) { speakersIds.add(user.id) binding.countMentions.text = speakersIds.size.toString() } }) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { fragmentBinding = binding lifecycleScope.launchWhenCreated { viewModel.data.collectLatest { list -> event = list.find { event -> event.id == viewModel.getEditedId() } ?: emptyEvent } } with(binding) { if (event != emptyEvent) { edit.setText(event.content) inputLink.setText(event.link) countMentions.text = event.speakerIds.size.toString() dateEventInput.setText(event.datetime.take(10)) timeEventInput.setText(event.datetime.subSequence(11,16)) } if (edit.text.isNullOrBlank()) { edit.setText(textNewPost) } edit.requestFocus() attachRes = viewModel.getEditedEventAttachment() Glide.with(photo) .load(attachRes?.url) .placeholder( when (attachRes?.type) { AttachmentType.AUDIO -> { R.drawable.ic_baseline_audio_file_500 } AttachmentType.VIDEO -> { R.drawable.ic_baseline_video_library_500 } else -> { R.drawable.not_image_500 } } ) .timeout(10_000) .into(photo) if (!attachRes?.url.isNullOrBlank() && arguments?.textArg != null) { binding.photoContainer.visibility = View.VISIBLE } viewModel.media.observe(viewLifecycleOwner) { if (it.uri == null && attachRes?.url.isNullOrBlank()) { binding.photoContainer.visibility = View.GONE return@observe } else { binding.photoContainer.visibility = View.VISIBLE if (it.attachmentType == AttachmentType.IMAGE) { binding.photo.setImageURI(it.uri) } } } requireActivity().addMenuProvider(object : MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { menuInflater.inflate(R.menu.menu_new_post, menu) } override fun onMenuItemSelected(menuItem: MenuItem): Boolean = when (menuItem.itemId) { R.id.save -> { fragmentBinding?.let { viewModel.changeContent( it.edit.text.toString(), it.inputLink.text.toString().ifEmpty { null }, "${it.dateEventInput.text.toString()} ${it.timeEventInput.text.toString()}", typeEvent, speakersIds ) viewModel.save() hideKeyboard(requireView()) } true } else -> false } }, viewLifecycleOwner) binding.listUsers.adapter = adapter clickListeners() return root } } override fun onStart() { currentFragment = javaClass.simpleName super.onStart() } @SuppressLint("IntentReset") private fun clickListeners() { binding.typeOnline.isClickable = false binding.typeOnline.setOnCheckedChangeListener { _, checked -> if (checked) { binding.typeOffline.toggle() binding.typeOffline.isClickable = true binding.typeOnline.isClickable = false typeEvent = EventType.ONLINE } } binding.typeOffline.setOnCheckedChangeListener { _, checked -> if (checked) { binding.typeOnline.toggle() binding.typeOnline.isClickable = true binding.typeOffline.isClickable = false typeEvent = EventType.OFFLINE } } binding.countMentions.setOnLongClickListener { speakersIds = mutableListOf() binding.countMentions.text = speakersIds.size.toString() true } val pickPhotoLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { when (it.resultCode) { ImagePicker.RESULT_ERROR -> { Snackbar.make( binding.root, ImagePicker.getError(it.data), Snackbar.LENGTH_LONG ).show() } Activity.RESULT_OK -> { val uri: Uri? = it.data?.data viewModel.changeMedia(uri, uri?.toFile(), AttachmentType.IMAGE) } } } binding.pickPhoto.setOnClickListener { ImagePicker.with(this) .crop() .compress(2048) .provider(ImageProvider.GALLERY) .galleryMimeTypes( arrayOf( "image/png", "image/jpeg", ) ) .createIntent(pickPhotoLauncher::launch) } binding.takePhoto.setOnClickListener { ImagePicker.with(this) .crop() .compress(2048) .provider(ImageProvider.CAMERA) .createIntent(pickPhotoLauncher::launch) } val pickMediaLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { when (it.resultCode) { Activity.RESULT_OK -> { val uri: Uri? = it.data?.data val contentResolver = context?.contentResolver val inputStream = uri?.let { it1 -> contentResolver?.openInputStream(it1) } val audioBytes = inputStream?.readBytes() if (uri != null && contentResolver != null) { val extension = getExtensionFromUri(uri, contentResolver) val file = File(context?.getExternalFilesDir(null), "input.$extension") FileOutputStream(file).use { outputStream -> outputStream.write(audioBytes) outputStream.flush() } viewModel.changeMedia(uri, file, type) } } else -> { Snackbar.make( binding.root, getString(R.string.error_upload), Snackbar.LENGTH_LONG ).show() } } } binding.uploadAudio.setOnClickListener { val intent = Intent(Intent.ACTION_PICK, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI) intent.type = "audio/*" type = AttachmentType.AUDIO attachRes = attachRes?.copy(type = type!!) pickMediaLauncher.launch(intent) } binding.uploadVideo.setOnClickListener { val intent = Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI) intent.type = "video/*" type = AttachmentType.VIDEO attachRes = attachRes?.copy(type = type!!) pickMediaLauncher.launch(intent) } binding.removePhoto.setOnClickListener { viewModel.deleteAttachment() attachRes = null viewModel.changeMedia(null, null, null) } binding.addMentions.setOnClickListener { binding.listUsers.isVisible = !binding.listUsers.isVisible lifecycleScope.launchWhenCreated { userViewModel.dataUsersList.collectLatest { adapter.submitList(it) } } } with(binding) { viewModel.eventCreated.observe(viewLifecycleOwner) { viewModel.loadEvents() findNavController().navigateUp() } fabCancel.setOnClickListener { if (viewModel.getEditedId() == 0L) { textNewPost = edit.text.toString() } else { edit.text?.clear() viewModel.save() } hideKeyboard(root) findNavController().navigateUp() } } } override fun onDestroyView() { fragmentBinding = null super.onDestroyView() } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/ui/NewEventFragment.kt
1884090227
package ru.netology.nework.ui import android.app.AlertDialog import android.content.Intent import android.media.MediaPlayer import android.net.Uri import ru.netology.nework.auxiliary.Companion.Companion.userId import android.os.Bundle import android.view.* import android.widget.MediaController import android.widget.Toast import android.widget.VideoView import androidx.core.view.MenuProvider import androidx.core.view.isVisible import androidx.fragment.app.* import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collectLatest import ru.netology.nework.R import ru.netology.nework.adapters.EventAdapter import ru.netology.nework.adapters.OnInteractionListenerEvent import ru.netology.nework.auth.AppAuth import ru.netology.nework.auxiliary.Companion.Companion.eventId import ru.netology.nework.auxiliary.Companion.Companion.eventRequestType import ru.netology.nework.auxiliary.Companion.Companion.textArg import ru.netology.nework.auxiliary.FloatingValue.currentFragment import ru.netology.nework.databinding.FragmentEventsBinding import ru.netology.nework.dto.AttachmentType import ru.netology.nework.dto.EventResponse import ru.netology.nework.viewmodel.AuthViewModel import ru.netology.nework.viewmodel.EventViewModel import javax.inject.Inject @AndroidEntryPoint class EventsFragment : Fragment() { val viewModel: EventViewModel by activityViewModels() val authViewModel: AuthViewModel by viewModels() @Inject lateinit var appAuth: AppAuth val mediaPlayer = MediaPlayer() private val interactionListener = object : OnInteractionListenerEvent { override fun onTapAvatar(event: EventResponse) { findNavController().navigate( R.id.action_eventsFragment_to_profileFragment, Bundle().apply { userId = event.authorId } ) } override fun onLike(event: EventResponse) { if (authViewModel.authenticated) { viewModel.likeById(event) } else { AlertDialog.Builder(context) .setMessage(R.string.action_not_allowed) .setPositiveButton(R.string.sign_up) { _, _ -> findNavController().navigate( R.id.action_eventsFragment_to_authFragment, Bundle().apply { textArg = getString(R.string.sign_up) } ) } .setNeutralButton(R.string.sign_in) { _, _ -> findNavController().navigate( R.id.action_eventsFragment_to_authFragment, Bundle().apply { textArg = getString(R.string.sign_in) } ) } .setNegativeButton(R.string.no, null) .setCancelable(true) .create() .show() } } override fun onShare(event: EventResponse) { val intent = Intent().apply { action = Intent.ACTION_SEND type = "text/plain" putExtra(Intent.EXTRA_TEXT, event.content) } val shareIntent = Intent.createChooser(intent, getString(R.string.chooser_share_post)) startActivity(shareIntent) } override fun onRemove(event: EventResponse) { viewModel.removeById(event.id) } override fun onEdit(event: EventResponse) { viewModel.edit(event) findNavController().navigate(R.id.action_eventsFragment_to_newEventFragment) } override fun onPlayPost(event: EventResponse, videoView: VideoView?) { if (event.attachment?.type == AttachmentType.VIDEO) { videoView?.isVisible = true val uri = Uri.parse(event.attachment.url) videoView?.apply { setMediaController(MediaController(requireContext())) setVideoURI(uri) setOnPreparedListener { videoView.layoutParams?.height = (resources.displayMetrics.widthPixels * (it.videoHeight.toDouble() / it.videoWidth)).toInt() start() } setOnCompletionListener { if (videoView.layoutParams?.width != null) { videoView.layoutParams?.width = resources.displayMetrics.widthPixels videoView.layoutParams?.height = (videoView.layoutParams?.width!! * 0.5625).toInt() } stopPlayback() } } } if (event.attachment?.type == AttachmentType.AUDIO) { if (mediaPlayer.isPlaying) { mediaPlayer.stop() } else { mediaPlayer.reset() mediaPlayer.setDataSource(event.attachment.url) mediaPlayer.prepare() mediaPlayer.start() } } } override fun onLink(event: EventResponse) { val intent = if (event.link?.contains("https://") == true || event.link?.contains("http://") == true) { Intent(Intent.ACTION_VIEW, Uri.parse(event.link)) } else { Intent(Intent.ACTION_VIEW, Uri.parse("http://${event.link}")) } startActivity(intent) } override fun onPreviewAttachment(event: EventResponse) { findNavController().navigate( R.id.action_eventsFragment_to_viewImageAttach, Bundle().apply { textArg = event.attachment?.url }) } override fun onSpeakersAction(event: EventResponse) { if (event.speakerIds.isNotEmpty()) { findNavController().navigate( R.id.action_eventsFragment_to_bottomSheetFragment, Bundle().apply { eventId = event.id eventRequestType = "speakers" } ) } else { Toast.makeText(requireContext(), R.string.not_value_event, Toast.LENGTH_SHORT) .show() } } override fun onPartyAction(event: EventResponse) { if (event.participantsIds.isNotEmpty()) { findNavController().navigate( R.id.action_eventsFragment_to_bottomSheetFragment, Bundle().apply { eventId = event.id eventRequestType = "party" } ) } else { Toast.makeText(requireContext(), R.string.not_value_event, Toast.LENGTH_SHORT) .show() } } override fun onJoinAction(event: EventResponse) { viewModel.joinById(event) } } private lateinit var binding: FragmentEventsBinding private lateinit var adapter: EventAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentEventsBinding.inflate(layoutInflater) adapter = EventAdapter(interactionListener) binding.list.adapter = adapter lifecycleScope.launchWhenCreated { viewModel.data.collectLatest { adapter.submitList(it) } } var menuProvider: MenuProvider? = null authViewModel.data.observe(viewLifecycleOwner) { menuProvider?.let(requireActivity()::removeMenuProvider) requireActivity().addMenuProvider(object : MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { menuInflater.inflate(R.menu.menu_main, menu) menu.setGroupVisible(R.id.unauthenticated, !authViewModel.authenticated) menu.setGroupVisible(R.id.authenticated, authViewModel.authenticated) } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { return when (menuItem.itemId) { R.id.signin -> { findNavController().navigate( R.id.action_feedFragment_to_authFragment, Bundle().apply { textArg = getString(R.string.sign_in) } ) true } R.id.signup -> { findNavController().navigate( R.id.action_feedFragment_to_authFragment, Bundle().apply { textArg = getString(R.string.sign_up) } ) true } R.id.signout -> { AlertDialog.Builder(requireActivity()) .setTitle(R.string.are_you_suare) .setPositiveButton(R.string.yes) { _, _ -> appAuth.removeAuth() } .setCancelable(true) .setNegativeButton(R.string.no, null) .create() .show() true } else -> false } } }.apply { menuProvider = this }, viewLifecycleOwner) } binding.mainNavView.setOnItemSelectedListener { menuItem -> when (menuItem.itemId) { R.id.navigation_posts -> { findNavController().navigate(R.id.action_eventsFragment_to_feedFragment) true } R.id.navigation_events -> { true } R.id.navigation_users -> { findNavController().navigate(R.id.action_eventsFragment_to_usersFragment) true } R.id.navigation_profile -> { findNavController().navigate(R.id.action_eventsFragment_to_profileFragment) true } else -> false } } binding.mainNavView.selectedItemId = R.id.navigation_events binding.fab.setOnClickListener { if (authViewModel.authenticated) { findNavController().navigate(R.id.action_eventsFragment_to_newEventFragment) } else { AlertDialog.Builder(context) .setMessage(R.string.action_not_allowed) .setPositiveButton(R.string.sign_up) { _, _ -> findNavController().navigate( R.id.action_eventsFragment_to_authFragment, Bundle().apply { textArg = getString(R.string.sign_up) } ) } .setNeutralButton(R.string.sign_in) { _, _ -> findNavController().navigate( R.id.action_eventsFragment_to_authFragment, Bundle().apply { textArg = getString(R.string.sign_in) } ) } .setNegativeButton(R.string.no, null) .setCancelable(true) .create() .show() } } binding.swipe.setOnRefreshListener { viewModel.loadEvents() binding.swipe.isRefreshing = false } return binding.root } override fun onDestroyView() { mediaPlayer.release() super.onDestroyView() } override fun onResume() { currentFragment = javaClass.simpleName super.onResume() } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/ui/EventsFragment.kt
2964795185
package ru.netology.nework.ui import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.view.* import androidx.activity.result.contract.ActivityResultContracts import androidx.core.net.toFile import androidx.core.view.MenuProvider import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import com.bumptech.glide.Glide import com.github.dhaval2404.imagepicker.ImagePicker import com.github.dhaval2404.imagepicker.constant.ImageProvider import com.google.android.material.snackbar.Snackbar import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collectLatest import ru.netology.nework.R import ru.netology.nework.adapters.OnInteractionListenerUsers import ru.netology.nework.adapters.UsersAdapter import ru.netology.nework.auxiliary.AndroidUtils.hideKeyboard import ru.netology.nework.auxiliary.Companion.Companion.linkArg import ru.netology.nework.auxiliary.Companion.Companion.mentionsCountArg import ru.netology.nework.auxiliary.Companion.Companion.textArg import ru.netology.nework.auxiliary.FloatingValue.currentFragment import ru.netology.nework.auxiliary.FloatingValue.getExtensionFromUri import ru.netology.nework.auxiliary.FloatingValue.textNewPost import ru.netology.nework.databinding.FragmentNewPostBinding import ru.netology.nework.dto.Attachment import ru.netology.nework.dto.AttachmentType import ru.netology.nework.dto.User import ru.netology.nework.viewmodel.PostViewModel import ru.netology.nework.viewmodel.UsersViewModel import java.io.File import java.io.FileOutputStream @AndroidEntryPoint class NewPostFragment : Fragment() { private val binding by lazy { FragmentNewPostBinding.inflate(layoutInflater) } private val viewModel: PostViewModel by activityViewModels() private val userViewModel: UsersViewModel by viewModels() private var fragmentBinding: FragmentNewPostBinding? = null private var type: AttachmentType? = null private var attachRes: Attachment? = null private var mentionsIds:MutableList<Long> = mutableListOf() private var adapter = UsersAdapter(object : OnInteractionListenerUsers { override fun onTap(user: User) { mentionsIds.add(user.id) binding.countMentions.text = mentionsIds.size.toString() } }) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { fragmentBinding = binding with(binding) { arguments?.textArg?.let { edit.setText(it) } arguments?.linkArg?.let { inputLink.setText(it) } arguments?.mentionsCountArg?.let { countMentions.text = it.toString() } if (edit.text.isNullOrBlank()) { edit.setText(textNewPost) } edit.requestFocus() attachRes = viewModel.getEditedPostAttachment() Glide.with(photo) .load(attachRes?.url) .placeholder( when (attachRes?.type) { AttachmentType.AUDIO -> { R.drawable.ic_baseline_audio_file_500 } AttachmentType.VIDEO -> { R.drawable.ic_baseline_video_library_500 } else -> { R.drawable.not_image_500 } } ) .timeout(10_000) .into(photo) if (!attachRes?.url.isNullOrBlank() && arguments?.textArg != null) { binding.photoContainer.visibility = View.VISIBLE } viewModel.media.observe(viewLifecycleOwner) { if (it.uri == null && attachRes?.url.isNullOrBlank()) { binding.photoContainer.visibility = View.GONE return@observe } else { binding.photoContainer.visibility = View.VISIBLE if (it.attachmentType == AttachmentType.IMAGE) { binding.photo.setImageURI(it.uri) } } } requireActivity().addMenuProvider(object : MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { menuInflater.inflate(R.menu.menu_new_post, menu) } override fun onMenuItemSelected(menuItem: MenuItem): Boolean = when (menuItem.itemId) { R.id.save -> { fragmentBinding?.let { viewModel.changeContent( it.edit.text.toString(), it.inputLink.text.toString().ifEmpty { null }, mentionsIds ) viewModel.save() hideKeyboard(requireView()) } true } else -> false } }, viewLifecycleOwner) binding.listUsers.adapter = adapter clickListeners() return root } } override fun onStart() { currentFragment = javaClass.simpleName super.onStart() } @SuppressLint("IntentReset") private fun clickListeners() { binding.countMentions.setOnLongClickListener { mentionsIds = mutableListOf() binding.countMentions.text = mentionsIds.size.toString() true } val pickPhotoLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { when (it.resultCode) { ImagePicker.RESULT_ERROR -> { Snackbar.make( binding.root, ImagePicker.getError(it.data), Snackbar.LENGTH_LONG ).show() } Activity.RESULT_OK -> { val uri: Uri? = it.data?.data viewModel.changeMedia(uri, uri?.toFile(), AttachmentType.IMAGE) } } } binding.pickPhoto.setOnClickListener { ImagePicker.with(this) .crop() .compress(2048) .provider(ImageProvider.GALLERY) .galleryMimeTypes( arrayOf( "image/png", "image/jpeg", ) ) .createIntent(pickPhotoLauncher::launch) } binding.takePhoto.setOnClickListener { ImagePicker.with(this) .crop() .compress(2048) .provider(ImageProvider.CAMERA) .createIntent(pickPhotoLauncher::launch) } val pickMediaLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { when (it.resultCode) { Activity.RESULT_OK -> { val uri: Uri? = it.data?.data val contentResolver = context?.contentResolver val inputStream = uri?.let { it1 -> contentResolver?.openInputStream(it1) } val audioBytes = inputStream?.readBytes() if (uri != null && contentResolver != null) { val extension = getExtensionFromUri(uri, contentResolver) val file = File(context?.getExternalFilesDir(null), "input.$extension") FileOutputStream(file).use { outputStream -> outputStream.write(audioBytes) outputStream.flush() } viewModel.changeMedia(uri, file, type) } } else -> { Snackbar.make( binding.root, getString(R.string.error_upload), Snackbar.LENGTH_LONG ).show() } } } binding.uploadAudio.setOnClickListener { val intent = Intent(Intent.ACTION_PICK, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI) intent.type = "audio/*" type = AttachmentType.AUDIO attachRes = attachRes?.copy(type = type!!) pickMediaLauncher.launch(intent) } binding.uploadVideo.setOnClickListener { val intent = Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI) intent.type = "video/*" type = AttachmentType.VIDEO attachRes = attachRes?.copy(type = type!!) pickMediaLauncher.launch(intent) } binding.removePhoto.setOnClickListener { viewModel.deleteAttachment() attachRes = null viewModel.changeMedia(null, null, null) } binding.addMentions.setOnClickListener { binding.listUsers.isVisible = !binding.listUsers.isVisible lifecycleScope.launchWhenCreated { userViewModel.dataUsersList.collectLatest { adapter.submitList(it) } } } with(binding) { viewModel.postCreated.observe(viewLifecycleOwner) { viewModel.loadPosts() findNavController().navigateUp() } fabCancel.setOnClickListener { if (viewModel.getEditedId() == 0L) { textNewPost = edit.text.toString() } else { edit.text?.clear() viewModel.save() } hideKeyboard(root) findNavController().navigateUp() } } } override fun onDestroyView() { fragmentBinding = null super.onDestroyView() } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/ui/NewPostFragment.kt
431479193
package ru.netology.nework.ui import android.os.Bundle import android.widget.Toast import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import com.google.android.gms.common.ConnectionResult import com.google.android.gms.common.GoogleApiAvailability import com.google.android.material.floatingactionbutton.FloatingActionButton import dagger.hilt.android.AndroidEntryPoint import ru.netology.nework.R import ru.netology.nework.auxiliary.FloatingValue.currentFragment import ru.netology.nework.auxiliary.FloatingValue.textNewPost import ru.netology.nework.viewmodel.AuthViewModel @AndroidEntryPoint class AppActivity : AppCompatActivity(R.layout.activity_app) { private val viewModel: AuthViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel.data.observe(this) { invalidateOptionsMenu() } checkGoogleApiAvailability() } private fun checkGoogleApiAvailability() { with(GoogleApiAvailability.getInstance()) { val code = isGooglePlayServicesAvailable(this@AppActivity) if (code == ConnectionResult.SUCCESS) { return@with } if (isUserResolvableError(code)) { getErrorDialog(this@AppActivity, code, 9000)?.show() return } Toast.makeText(this@AppActivity, "Google Api Unavailable", Toast.LENGTH_LONG).show() } } @Deprecated("Deprecated in Java") override fun onBackPressed() { if (currentFragment == "NewPostFragment") { findViewById<FloatingActionButton>(R.id.fab_cancel).callOnClick() return } super.onBackPressed() } override fun onStop() { currentFragment = "" textNewPost = "" super.onStop() } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/ui/AppActivity.kt
2007458503
package ru.netology.nework.ui import android.app.AlertDialog import android.media.MediaPlayer import ru.netology.nework.auxiliary.Companion.Companion.userId import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.* import android.widget.MediaController import ru.netology.nework.viewmodel.UsersViewModel import android.widget.Toast import android.widget.VideoView import androidx.core.view.MenuProvider import androidx.core.view.isVisible import androidx.fragment.app.* import androidx.navigation.fragment.findNavController import com.google.android.material.snackbar.Snackbar import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import ru.netology.nework.R import ru.netology.nework.adapters.OnInteractionListener import ru.netology.nework.adapters.PostAdapter import ru.netology.nework.auth.AppAuth import ru.netology.nework.auxiliary.Companion.Companion.linkArg import ru.netology.nework.auxiliary.Companion.Companion.mentionsCountArg import ru.netology.nework.auxiliary.Companion.Companion.textArg import ru.netology.nework.auxiliary.FloatingValue.currentFragment import ru.netology.nework.databinding.FragmentFeedBinding import ru.netology.nework.dto.AttachmentType import ru.netology.nework.dto.Post import ru.netology.nework.model.FeedModelState import ru.netology.nework.viewmodel.AuthViewModel import ru.netology.nework.viewmodel.PostViewModel import javax.inject.Inject import kotlin.coroutines.EmptyCoroutineContext @AndroidEntryPoint class FeedFragment : Fragment() { val viewModel: PostViewModel by activityViewModels() val authViewModel: AuthViewModel by viewModels() private val usersViewModel: UsersViewModel by activityViewModels() @Inject lateinit var appAuth: AppAuth private val mediaPlayer = MediaPlayer() private val interactionListener = object : OnInteractionListener { override fun onTapAvatar(post: Post) { findNavController().navigate( R.id.action_feedFragment_to_profileFragment, Bundle().apply { userId = post.authorId } ) } override fun onLike(post: Post) { if (authViewModel.authenticated) { viewModel.likeById(post) } else { AlertDialog.Builder(context) .setMessage(R.string.action_not_allowed) .setPositiveButton(R.string.sign_up) { _, _ -> findNavController().navigate( R.id.action_feedFragment_to_authFragment, Bundle().apply { textArg = getString(R.string.sign_up) } ) } .setNeutralButton(R.string.sign_in) { _, _ -> findNavController().navigate( R.id.action_feedFragment_to_authFragment, Bundle().apply { textArg = getString(R.string.sign_in) } ) } .setNegativeButton(R.string.no, null) .setCancelable(true) .create() .show() } } override fun onShare(post: Post) { val intent = Intent().apply { action = Intent.ACTION_SEND type = "text/plain" putExtra(Intent.EXTRA_TEXT, post.content) } val shareIntent = Intent.createChooser(intent, getString(R.string.chooser_share_post)) startActivity(shareIntent) } override fun onRemove(post: Post) { viewModel.removeById(post.id) } override fun onEdit(post: Post) { viewModel.edit(post) findNavController().navigate( R.id.action_feedFragment_to_newPostFragment, Bundle().apply { textArg = post.content linkArg = post.link mentionsCountArg = post.mentionIds?.size?.toLong() ?: 0L }) } override fun onPlayPost(post: Post, videoView: VideoView?) { if (post.attachment?.type == AttachmentType.VIDEO) { videoView?.isVisible = true val uri = Uri.parse(post.attachment.url) videoView?.apply { setMediaController(MediaController(requireContext())) setVideoURI(uri) setOnPreparedListener { videoView.layoutParams?.height = (resources.displayMetrics.widthPixels * (it.videoHeight.toDouble() / it.videoWidth)).toInt() start() } setOnCompletionListener { if (videoView.layoutParams?.width != null) { videoView.layoutParams?.width = resources.displayMetrics.widthPixels videoView.layoutParams?.height = (videoView.layoutParams?.width!! * 0.5625).toInt() } stopPlayback() } } } if (post.attachment?.type == AttachmentType.AUDIO) { if (mediaPlayer.isPlaying) { mediaPlayer.pause() } else { mediaPlayer.reset() mediaPlayer.setDataSource(post.attachment.url) mediaPlayer.prepare() mediaPlayer.start() } } } override fun onLink(post: Post) { val intent = if (post.link?.contains("https://") == true || post.link?.contains("http://") == true) { Intent(Intent.ACTION_VIEW, Uri.parse(post.link)) } else { Intent(Intent.ACTION_VIEW, Uri.parse("http://${post.link}")) } startActivity(intent) } override fun onPreviewAttachment(post: Post) { findNavController().navigate( R.id.action_feedFragment_to_viewImageAttach, Bundle().apply { textArg = post.attachment?.url }) } } private lateinit var binding: FragmentFeedBinding private lateinit var adapter: PostAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentFeedBinding.inflate(layoutInflater) adapter = PostAdapter(interactionListener) binding.list.adapter = adapter usersViewModel.dataUsersList viewModel.data.observe(viewLifecycleOwner) { adapter.submitList(it.posts) binding.emptyText.isVisible = it.empty } viewModel.dataState.observe(viewLifecycleOwner) { binding.progress.isVisible = it is FeedModelState.Loading binding.swipe.isRefreshing = it is FeedModelState.Refresh if (it is FeedModelState.Error) { Snackbar.make(binding.root, R.string.error_loading, Snackbar.LENGTH_LONG) .setAction(R.string.retry_loading) { viewModel.loadPosts() } .show() } if (it is FeedModelState.Idle) { Toast.makeText(context, R.string.on_success, Toast.LENGTH_SHORT).show() } } var menuProvider: MenuProvider? = null authViewModel.data.observe(viewLifecycleOwner) { menuProvider?.let(requireActivity()::removeMenuProvider) requireActivity().addMenuProvider(object : MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { menuInflater.inflate(R.menu.menu_main, menu) menu.setGroupVisible(R.id.unauthenticated, !authViewModel.authenticated) menu.setGroupVisible(R.id.authenticated, authViewModel.authenticated) } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { return when (menuItem.itemId) { R.id.signin -> { findNavController().navigate( R.id.action_feedFragment_to_authFragment, Bundle().apply { textArg = getString(R.string.sign_in) } ) true } R.id.signup -> { findNavController().navigate( R.id.action_feedFragment_to_authFragment, Bundle().apply { textArg = getString(R.string.sign_up) } ) true } R.id.signout -> { AlertDialog.Builder(requireActivity()) .setTitle(R.string.are_you_suare) .setPositiveButton(R.string.yes) { _, _ -> appAuth.removeAuth() } .setCancelable(true) .setNegativeButton(R.string.no, null) .create() .show() true } else -> false } } }.apply { menuProvider = this }, viewLifecycleOwner) } binding.mainNavView.setOnItemSelectedListener { menuItem -> when (menuItem.itemId) { R.id.navigation_posts -> { true } R.id.navigation_events -> { findNavController().navigate(R.id.action_feedFragment_to_eventsFragment) true } R.id.navigation_users -> { findNavController().navigate(R.id.action_feedFragment_to_usersFragment) true } R.id.navigation_profile -> { findNavController().navigate(R.id.action_feedFragment_to_profileFragment) true } else -> false } } binding.mainNavView.selectedItemId = R.id.navigation_posts binding.fab.setOnClickListener { if (authViewModel.authenticated) { findNavController().navigate(R.id.action_feedFragment_to_newPostFragment) } else { AlertDialog.Builder(context) .setMessage(R.string.action_not_allowed) .setPositiveButton(R.string.sign_up) { _, _ -> findNavController().navigate( R.id.action_feedFragment_to_authFragment, Bundle().apply { textArg = getString(R.string.sign_up) } ) } .setNeutralButton(R.string.sign_in) { _, _ -> findNavController().navigate( R.id.action_feedFragment_to_authFragment, Bundle().apply { textArg = getString(R.string.sign_in) } ) } .setNegativeButton(R.string.no, null) .setCancelable(true) .create() .show() } } binding.retryButton.setOnClickListener { viewModel.loadPosts() } binding.swipe.setOnRefreshListener { viewModel.refreshPosts() } binding.newerCount.setOnClickListener { binding.newerCount.isVisible = false CoroutineScope(EmptyCoroutineContext).launch { launch { viewModel.viewNewPosts() delay(25) // без delay прокручивает раньше, не смотря на join }.join() binding.list.smoothScrollToPosition(0) } } viewModel.newerCount.observe(viewLifecycleOwner) { state -> binding.newerCount.isVisible = state > 0 } return binding.root } override fun onDestroyView() { mediaPlayer.release() super.onDestroyView() } override fun onResume() { currentFragment = javaClass.simpleName super.onResume() } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/ui/FeedFragment.kt
2515519176
package ru.netology.nework.ui import android.os.Bundle import android.view.* import androidx.core.view.MenuProvider import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collectLatest import ru.netology.nework.R import ru.netology.nework.auxiliary.AndroidUtils.hideKeyboard import ru.netology.nework.auxiliary.ConstantValues.emptyJob import ru.netology.nework.auxiliary.FloatingValue.currentFragment import ru.netology.nework.databinding.FragmentNewJobBinding import ru.netology.nework.viewmodel.JobViewModel @AndroidEntryPoint class NewJobFragment : Fragment() { private val binding by lazy { FragmentNewJobBinding.inflate(layoutInflater) } private val viewModel: JobViewModel by activityViewModels() private var job = emptyJob private var fragmentBinding: FragmentNewJobBinding? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { fragmentBinding = binding lifecycleScope.launchWhenCreated { viewModel.data.collectLatest { list -> job = list.find { job -> job.id == viewModel.getEditedId() } ?: emptyJob } } with(binding) { if (job != emptyJob) { jobOrganizationInput.setText(job.name) jobPositionInput.setText(job.position) dateStartWorkingInput.setText(job.start) dateEndWorkingInput.setText(job.finish) inputLink.setText(job.link) } requireActivity().addMenuProvider(object : MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { menuInflater.inflate(R.menu.menu_new_post, menu) } override fun onMenuItemSelected(menuItem: MenuItem): Boolean = when (menuItem.itemId) { R.id.save -> { fragmentBinding?.let { viewModel.changeContent( it.jobOrganizationInput.text.toString(), it.jobPositionInput.text.toString(), it.dateStartWorkingInput.text.toString(), it.dateEndWorkingInput.text.toString().ifEmpty { null }, it.inputLink.text.toString().ifEmpty { null }, ) viewModel.save() hideKeyboard(requireView()) findNavController().navigate(R.id.action_newJobFragment_to_profileFragment) } true } else -> false } }, viewLifecycleOwner) return root } } override fun onStart() { currentFragment = javaClass.simpleName super.onStart() } override fun onDestroyView() { fragmentBinding = null super.onDestroyView() } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/ui/NewJobFragment.kt
3280125731
package ru.netology.nework.ui import android.app.AlertDialog import android.content.Intent import android.media.MediaPlayer import android.net.Uri import android.os.Bundle import android.view.* import android.widget.MediaController import android.widget.Toast import android.widget.VideoView import androidx.core.view.MenuProvider import androidx.core.view.isVisible import androidx.fragment.app.* import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import com.bumptech.glide.Glide import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collectLatest import ru.netology.nework.R import ru.netology.nework.adapters.* import ru.netology.nework.auth.AppAuth import ru.netology.nework.auxiliary.Companion.Companion.eventId import ru.netology.nework.auxiliary.Companion.Companion.eventRequestType import ru.netology.nework.auxiliary.Companion.Companion.linkArg import ru.netology.nework.auxiliary.Companion.Companion.mentionsCountArg import ru.netology.nework.auxiliary.Companion.Companion.textArg import ru.netology.nework.auxiliary.Companion.Companion.userId import ru.netology.nework.auxiliary.ConstantValues.emptyUser import ru.netology.nework.auxiliary.FloatingValue.currentFragment import ru.netology.nework.databinding.FragmentProfileBinding import ru.netology.nework.dto.* import ru.netology.nework.viewmodel.* import javax.inject.Inject @AndroidEntryPoint class ProfileFragment : Fragment() { val postViewModel: PostViewModel by activityViewModels() val eventViewModel: EventViewModel by activityViewModels() val jobViewModel: JobViewModel by activityViewModels() private val usersViewModel: UsersViewModel by activityViewModels() val authViewModel: AuthViewModel by viewModels() @Inject lateinit var appAuth: AppAuth val mediaPlayer = MediaPlayer() private val interactionListenerEvent = object : OnInteractionListenerEvent { override fun onLike(event: EventResponse) { if (authViewModel.authenticated) { eventViewModel.likeById(event) } else { AlertDialog.Builder(context) .setMessage(R.string.action_not_allowed) .setPositiveButton(R.string.sign_up) { _, _ -> findNavController().navigate( R.id.action_profileFragment_to_authFragment, Bundle().apply { textArg = getString(R.string.sign_up) } ) } .setNeutralButton(R.string.sign_in) { _, _ -> findNavController().navigate( R.id.action_profileFragment_to_authFragment, Bundle().apply { textArg = getString(R.string.sign_in) } ) } .setNegativeButton(R.string.no, null) .setCancelable(true) .create() .show() } } override fun onShare(event: EventResponse) { val intent = Intent().apply { action = Intent.ACTION_SEND type = "text/plain" putExtra(Intent.EXTRA_TEXT, event.content) } val shareIntent = Intent.createChooser(intent, getString(R.string.chooser_share_post)) startActivity(shareIntent) } override fun onRemove(event: EventResponse) { eventViewModel.removeById(event.id) } override fun onEdit(event: EventResponse) { eventViewModel.edit(event) findNavController().navigate(R.id.action_profileFragment_to_newEventFragment) } override fun onPlayPost(event: EventResponse, videoView: VideoView?) { if (event.attachment?.type == AttachmentType.VIDEO) { videoView?.isVisible = true val uri = Uri.parse(event.attachment.url) videoView?.apply { setMediaController(MediaController(requireContext())) setVideoURI(uri) setOnPreparedListener { videoView.layoutParams?.height = (resources.displayMetrics.widthPixels * (it.videoHeight.toDouble() / it.videoWidth)).toInt() start() } setOnCompletionListener { if (videoView.layoutParams?.width != null) { videoView.layoutParams?.width = resources.displayMetrics.widthPixels videoView.layoutParams?.height = (videoView.layoutParams?.width!! * 0.5625).toInt() } stopPlayback() } } } if (event.attachment?.type == AttachmentType.AUDIO) { if (mediaPlayer.isPlaying) { mediaPlayer.stop() } else { mediaPlayer.reset() mediaPlayer.setDataSource(event.attachment.url) mediaPlayer.prepare() mediaPlayer.start() } } } override fun onLink(event: EventResponse) { val intent = if (event.link?.contains("https://") == true || event.link?.contains("http://") == true) { Intent(Intent.ACTION_VIEW, Uri.parse(event.link)) } else { Intent(Intent.ACTION_VIEW, Uri.parse("http://${event.link}")) } startActivity(intent) } override fun onPreviewAttachment(event: EventResponse) { findNavController().navigate( R.id.action_profileFragment_to_viewImageAttach, Bundle().apply { textArg = event.attachment?.url }) } override fun onSpeakersAction(event: EventResponse) { if (event.speakerIds.isNotEmpty()) { findNavController().navigate( R.id.action_profileFragment_to_bottomSheetFragment, Bundle().apply { eventId = event.id eventRequestType = "speakers" } ) } else { Toast.makeText(requireContext(), R.string.not_value_event, Toast.LENGTH_SHORT) .show() } } override fun onPartyAction(event: EventResponse) { if (event.participantsIds.isNotEmpty()) { findNavController().navigate( R.id.action_profileFragment_to_bottomSheetFragment, Bundle().apply { eventId = event.id eventRequestType = "party" } ) } else { Toast.makeText(requireContext(), R.string.not_value_event, Toast.LENGTH_SHORT) .show() } } override fun onJoinAction(event: EventResponse) { eventViewModel.joinById(event) } } private val interactionListenerPost = object : OnInteractionListener { override fun onLike(post: Post) { if (authViewModel.authenticated) { postViewModel.likeById(post) } else { AlertDialog.Builder(context) .setMessage(R.string.action_not_allowed) .setPositiveButton(R.string.sign_up) { _, _ -> findNavController().navigate( R.id.action_profileFragment_to_authFragment, Bundle().apply { textArg = getString(R.string.sign_up) } ) } .setNeutralButton(R.string.sign_in) { _, _ -> findNavController().navigate( R.id.action_profileFragment_to_authFragment, Bundle().apply { textArg = getString(R.string.sign_in) } ) } .setNegativeButton(R.string.no, null) .setCancelable(true) .create() .show() } } override fun onShare(post: Post) { val intent = Intent().apply { action = Intent.ACTION_SEND type = "text/plain" putExtra(Intent.EXTRA_TEXT, post.content) } val shareIntent = Intent.createChooser(intent, getString(R.string.chooser_share_post)) startActivity(shareIntent) } override fun onRemove(post: Post) { postViewModel.removeById(post.id) } override fun onEdit(post: Post) { postViewModel.edit(post) findNavController().navigate( R.id.action_profileFragment_to_newPostFragment, Bundle().apply { textArg = post.content linkArg = post.link mentionsCountArg = post.mentionIds?.size?.toLong() ?: 0L }) } override fun onPlayPost(post: Post, videoView: VideoView?) { if (post.attachment?.type == AttachmentType.VIDEO) { videoView?.isVisible = true val uri = Uri.parse(post.attachment.url) videoView?.apply { setMediaController(MediaController(requireContext())) setVideoURI(uri) setOnPreparedListener { videoView.layoutParams?.height = (resources.displayMetrics.widthPixels * (it.videoHeight.toDouble() / it.videoWidth)).toInt() start() } setOnCompletionListener { if (videoView.layoutParams?.width != null) { videoView.layoutParams?.width = resources.displayMetrics.widthPixels videoView.layoutParams?.height = (videoView.layoutParams?.width!! * 0.5625).toInt() } stopPlayback() } } } if (post.attachment?.type == AttachmentType.AUDIO) { mediaPlayer.reset() if (mediaPlayer.isPlaying) { mediaPlayer.stop() } else { mediaPlayer.setDataSource(post.attachment.url) mediaPlayer.prepare() mediaPlayer.start() } } } override fun onLink(post: Post) { val intent = if (post.link?.contains("https://") == true || post.link?.contains("http://") == true) { Intent(Intent.ACTION_VIEW, Uri.parse(post.link)) } else { Intent(Intent.ACTION_VIEW, Uri.parse("http://${post.link}")) } startActivity(intent) } override fun onPreviewAttachment(post: Post) { findNavController().navigate( R.id.action_profileFragment_to_viewImageAttach, Bundle().apply { textArg = post.attachment?.url }) } } private val interactionListenerJob = object : OnInteractionListenerJob { override fun onRemove(job: Job) { jobViewModel.removeById(job.id) } override fun onEdit(job: Job) { jobViewModel.edit(job) findNavController().navigate(R.id.action_profileFragment_to_newJobFragment) } override fun onLink(job: Job) { val intent = if (job.link?.contains("https://") == true || job.link?.contains("http://") == true) { Intent(Intent.ACTION_VIEW, Uri.parse(job.link)) } else { Intent(Intent.ACTION_VIEW, Uri.parse("http://${job.link}")) } startActivity(intent) } override fun myOrNo(job: Job): Boolean { return job.ownerId == appAuth.authStateFlow.value.id } } private lateinit var binding: FragmentProfileBinding private lateinit var adapterJob: JobAdapter private lateinit var adapterEvent: EventAdapter private lateinit var adapterPost: PostAdapter private lateinit var user: User override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentProfileBinding.inflate(layoutInflater) adapterJob = JobAdapter(interactionListenerJob) adapterEvent = EventAdapter(interactionListenerEvent) adapterPost = PostAdapter(interactionListenerPost) binding.listJob.adapter = adapterJob binding.listEvent.adapter = adapterEvent binding.listPosts.adapter = adapterPost lifecycleScope.launchWhenCreated { usersViewModel.dataUsersList.collectLatest { listUsers -> user = listUsers.find { it.id == (arguments?.userId ?: appAuth.authStateFlow.value.id) } ?: emptyUser Glide.with(binding.avatar) .load(user.avatar) .placeholder(R.drawable.ic_image_not_supported_24) .error(R.drawable.ic_not_avatars_24) .circleCrop() .timeout(10_000) .into(binding.avatar) binding.idUser.text = user.id.toString() binding.nameUser.text = user.name binding.loginUser.text = user.login } } if (arguments?.userId != null) { jobViewModel.loadUserJobs(arguments?.userId!!) } else { jobViewModel.loadMyJobs() } lifecycleScope.launchWhenCreated { jobViewModel.data.collectLatest { adapterJob.submitList(it.filter { job -> job.ownerId == (arguments?.userId ?: appAuth.authStateFlow.value.id) }) } binding.jobTitle.text = if (adapterJob.itemCount == 0) { getString(R.string.no_jobs) } else { getString(R.string.job_description) } } lifecycleScope.launchWhenCreated { eventViewModel.data.collectLatest { adapterEvent.submitList(it.filter { event -> event.speakerIds.contains((arguments?.userId ?: appAuth.authStateFlow.value.id)) || event.participantsIds.contains( (arguments?.userId ?: appAuth.authStateFlow.value.id) ) }) binding.eventTitle.text = if (adapterEvent.itemCount == 0) { getString(R.string.no_events) } else { getString(R.string.event_description) } } } postViewModel.data.observe(viewLifecycleOwner) { adapterPost.submitList(it.posts.filter { post -> post.mentionIds?.contains( (arguments?.userId ?: appAuth.authStateFlow.value.id) ) ?: false || post.authorId == (arguments?.userId ?: appAuth.authStateFlow.value.id) }) binding.postTitle.text = if (adapterPost.itemCount == 0) { getString(R.string.no_posts) } else { getString(R.string.post_description) } } binding.addJob.isVisible = (arguments?.userId == appAuth.authStateFlow.value.id || arguments?.userId == null) binding.mainNavView.selectedItemId = R.id.navigation_profile var menuProvider: MenuProvider? = null authViewModel.data.observe(viewLifecycleOwner) { menuProvider?.let(requireActivity()::removeMenuProvider) requireActivity().addMenuProvider(object : MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { menuInflater.inflate(R.menu.menu_main, menu) menu.setGroupVisible(R.id.unauthenticated, !authViewModel.authenticated) menu.setGroupVisible(R.id.authenticated, authViewModel.authenticated) } override fun onMenuItemSelected(menuItem: MenuItem): Boolean { return when (menuItem.itemId) { R.id.signin -> { findNavController().navigate( R.id.action_feedFragment_to_authFragment, Bundle().apply { textArg = getString(R.string.sign_in) } ) true } R.id.signup -> { findNavController().navigate( R.id.action_feedFragment_to_authFragment, Bundle().apply { textArg = getString(R.string.sign_up) } ) true } R.id.signout -> { AlertDialog.Builder(requireActivity()) .setTitle(R.string.are_you_suare) .setPositiveButton(R.string.yes) { _, _ -> appAuth.removeAuth() } .setCancelable(true) .setNegativeButton(R.string.no, null) .create() .show() true } else -> false } } }.apply { menuProvider = this }, viewLifecycleOwner) } binding.mainNavView.setOnItemSelectedListener { menuItem -> when (menuItem.itemId) { R.id.navigation_posts -> { findNavController().navigate(R.id.action_profileFragment_to_feedFragment) true } R.id.navigation_events -> { findNavController().navigate(R.id.action_profileFragment_to_feedFragment) findNavController().navigate(R.id.action_feedFragment_to_eventsFragment) true } R.id.navigation_users -> { findNavController().navigate(R.id.action_profileFragment_to_feedFragment) findNavController().navigate(R.id.action_feedFragment_to_usersFragment) true } R.id.navigation_profile -> { arguments?.userId?.let { findNavController().navigate(R.id.action_profileFragment_self) } true } else -> false } } binding.addJob.setOnClickListener { findNavController().navigate(R.id.action_profileFragment_to_newJobFragment) } return binding.root } override fun onResume() { currentFragment = javaClass.simpleName super.onResume() } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/ui/ProfileFragment.kt
2990260459
package ru.netology.nework.database import android.content.Context import androidx.room.Room import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import ru.netology.nework.dao.PostDaoRoom import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module class DbModule { @Singleton @Provides fun provideDb( @ApplicationContext context: Context ): AppDbRoom = Room.databaseBuilder(context, AppDbRoom::class.java, "app.db") .fallbackToDestructiveMigration() .build() @Provides fun providePostDao( appDb: AppDbRoom ):PostDaoRoom = appDb.postDaoRoom() }
NeWork_Diplom/app/src/main/java/ru/netology/nework/database/DbModule.kt
540437311
package ru.netology.nework.database import androidx.room.Database import androidx.room.RoomDatabase import ru.netology.nework.dao.* @Database(entities = [PostEntity::class, UserEntity::class, EventsEntity::class,JobEntity::class], version = 1) abstract class AppDbRoom : RoomDatabase() { abstract fun postDaoRoom(): PostDaoRoom }
NeWork_Diplom/app/src/main/java/ru/netology/nework/database/AppDbRoom.kt
3840155352
package ru.netology.nework.repository import kotlinx.coroutines.flow.Flow import ru.netology.nework.dto.* interface Repository { val data: Flow<List<Post>> val dataUsers: Flow<List<User>> val dataEvents: Flow<List<EventResponse>> val dataJobs: Flow<List<Job>> fun getNewerCount(id: Long): Flow<Int> suspend fun showNewPosts() suspend fun edit(post: Post) suspend fun getAllAsync() suspend fun removeByIdAsync(id: Long) suspend fun saveAsync(post: Post) suspend fun saveWithAttachment(post: Post, upload: MediaUpload, attachmentType: AttachmentType) suspend fun likeByIdAsync(post: Post) suspend fun upload(upload: MediaUpload): MediaResponse suspend fun getUsers() suspend fun getUserBuId(id: Long) suspend fun getAllEvents() suspend fun saveEvents(event: EventResponse) suspend fun saveEventsWithAttachment( event: EventResponse, upload: MediaUpload, attachmentType: AttachmentType ) suspend fun removeEventsById(id: Long) suspend fun likeByIdEvents(event: EventResponse) suspend fun joinByIdEvents(event: EventResponse) suspend fun getJobs(id: Long) suspend fun getMyJobs(id: Long) suspend fun saveJob(job: Job) suspend fun removeJobById(id: Long) }
NeWork_Diplom/app/src/main/java/ru/netology/nework/repository/Repository.kt
3098862944
package ru.netology.nework.repository import androidx.lifecycle.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import okhttp3.MultipartBody import okhttp3.RequestBody.Companion.asRequestBody import okio.IOException import ru.netology.nework.api.* import ru.netology.nework.dao.* import ru.netology.nework.dto.* import ru.netology.nework.error.ApiError import ru.netology.nework.error.AppError import ru.netology.nework.error.NetworkError import ru.netology.nework.error.UnknownError import javax.inject.Inject class RepositoryImpl @Inject constructor( private val dao: PostDaoRoom, private val apiService: ApiService, ) : Repository { private val newerPostsId = mutableListOf<Long>() override val data = dao.getAll() .map(List<PostEntity>::toDto) .flowOn(Dispatchers.Default) override val dataUsers = dao.getUsers() .map(List<UserEntity>::toDto) .flowOn(Dispatchers.Default) override val dataEvents: Flow<List<EventResponse>> = dao.getAllEvents() .map(List<EventsEntity>::toDto) .flowOn(Dispatchers.Default) override val dataJobs: Flow<List<Job>> = dao.getJobs() .map(List<JobEntity>::toDto) .flowOn(Dispatchers.Default) override fun getNewerCount(id: Long): Flow<Int> = flow { while (true) { delay(10_000L) val response = apiService.getNewer(id) if (!response.isSuccessful) { throw ApiError(response.message()) } val body = response.body() ?: throw ApiError(response.message()) dao.insert(body.toEntity(isNew = true)) body.forEach { newerPostsId.add(it.id) } emit(body.size) } } override suspend fun showNewPosts() { dao.showNewPosts() } override suspend fun getAllAsync() { try { val response = apiService.getAll() if (!response.isSuccessful) { throw ApiError(response.message()) } val body = response.body() ?: throw ApiError(response.message()) dao.insert(body.toEntity()) } catch (e: IOException) { throw NetworkError } catch (e: Exception) { throw UnknownError } } override suspend fun removeByIdAsync(id: Long) { try { val response = apiService.removeById(id) if (!response.isSuccessful) { throw ApiError(response.message()) } dao.removeById(id) } catch (e: IOException) { throw NetworkError } catch (e: Exception) { throw UnknownError } } override suspend fun saveAsync(post: Post) { try { val postRequest = PostCreateRequest( post.id, post.content, post.coords, post.link, post.attachment, post.mentionIds ) val response = apiService.save(postRequest) if (!response.isSuccessful) { throw ApiError(response.message()) } val postResponse = response.body() ?: throw ApiError(response.message()) val postDaoSaved = Post( id = postResponse.id, authorId = postResponse.authorId, author = postResponse.author, authorAvatar = postResponse.authorAvatar, content = postResponse.content, published = postResponse.published, likedByMe = postResponse.likedByMe, likeOwnerIds = postResponse.likeOwnerIds, attachment = postResponse.attachment, ownedByMe = postResponse.ownedByMe ) dao.save(PostEntity.fromDto(postDaoSaved)) } catch (e: IOException) { throw NetworkError } catch (e: Exception) { throw UnknownError } } override suspend fun saveWithAttachment( post: Post, upload: MediaUpload, attachmentType: AttachmentType ) { try { val media = upload(upload) val postWithAttachment = post.copy( attachment = Attachment( url = media.url, type = attachmentType, ) ) saveAsync(postWithAttachment) } catch (e: AppError) { throw e } catch (e: IOException) { throw NetworkError } catch (e: Exception) { throw UnknownError } } override suspend fun upload(upload: MediaUpload): MediaResponse { try { val media = MultipartBody.Part.createFormData( "file", upload.file.name, upload.file.asRequestBody() ) val response = apiService.upload(media) if (!response.isSuccessful) { throw ApiError(response.message()) } return response.body() ?: throw ApiError(response.message()) } catch (e: IOException) { throw NetworkError } catch (e: Exception) { throw UnknownError } } override suspend fun getUsers() { try { val response = apiService.getUsers() if (!response.isSuccessful) { throw ApiError(response.message()) } val userResponseList = response.body() ?: throw ApiError(response.message()) val usersDaoSaved = userResponseList.map { userResponse -> User( id = userResponse.id, login = userResponse.login, name = userResponse.name, avatar = userResponse.avatar ) } dao.insertUsers(usersDaoSaved.toEntity()) } catch (e: IOException) { throw NetworkError } catch (e: Exception) { throw UnknownError } } override suspend fun getUserBuId(id: Long) { try { val response = apiService.getUserById(id) if (!response.isSuccessful) { throw ApiError(response.message()) } val userResponse = response.body() ?: throw ApiError(response.message()) val userDaoSaved = User( id = userResponse.id, login = userResponse.login, name = userResponse.name, avatar = userResponse.avatar, ) dao.insert(UserEntity.fromDto(userDaoSaved)) } catch (e: IOException) { throw NetworkError } catch (e: Exception) { throw UnknownError } } override suspend fun getAllEvents() { try { val response = apiService.getAllEvents() if (!response.isSuccessful) { throw ApiError(response.message()) } val body = response.body() ?: throw ApiError(response.message()) dao.insertEvents(body.toEntity()) } catch (e: IOException) { throw NetworkError } catch (e: Exception) { throw UnknownError } } override suspend fun saveEvents(event: EventResponse) { try { val eventRequest = EventCreateRequest( event.id, event.content, event.datetime, null, event.type, event.attachment, event.link, event.speakerIds ) val response = apiService.saveEvents(eventRequest) if (!response.isSuccessful) { throw ApiError(response.message()) } val eventResponse = response.body() ?: throw ApiError(response.message()) dao.saveEvent(EventsEntity.fromDto(eventResponse)) } catch (e: IOException) { throw NetworkError } catch (e: Exception) { throw UnknownError } } override suspend fun saveEventsWithAttachment( event: EventResponse, upload: MediaUpload, attachmentType: AttachmentType ) { try { val media = upload(upload) val eventWithAttachment = event.copy( attachment = Attachment( url = media.url, type = attachmentType, ) ) saveEvents(eventWithAttachment) } catch (e: AppError) { throw e } catch (e: IOException) { throw NetworkError } catch (e: Exception) { throw UnknownError } } override suspend fun removeEventsById(id: Long) { try { val response = apiService.removeByIdEvent(id) if (!response.isSuccessful) { throw ApiError(response.message()) } dao.removeByIdEvent(id) } catch (e: IOException) { throw NetworkError } catch (e: Exception) { throw UnknownError } } override suspend fun likeByIdEvents(event: EventResponse) { dao.likeByIdEvent(event.id) try { val response = if (event.likedByMe) { apiService.dislikeByIdEvent(event.id) } else { apiService.likeByIdEvent(event.id) } if (!response.isSuccessful) { throw ApiError(response.message()) } val body = response.body() ?: throw ApiError(response.message()) dao.insertEvents(EventsEntity.fromDto(body)) } catch (e: IOException) { throw NetworkError } catch (e: Exception) { throw UnknownError } } override suspend fun joinByIdEvents(event: EventResponse) { dao.joinByIdEvent(event.id) try { val response = if (event.participatedByMe) { apiService.unJoinByIdEvent(event.id) } else { apiService.joinByIdEvent(event.id) } if (!response.isSuccessful) { throw ApiError(response.message()) } val body = response.body() ?: throw ApiError(response.message()) dao.insertEvents(EventsEntity.fromDto(body)) } catch (e: IOException) { throw NetworkError } catch (e: Exception) { throw UnknownError } } override suspend fun getJobs(id: Long) { try { val response = apiService.getUserJobs(id) if (!response.isSuccessful) { throw ApiError(response.message()) } val body = response.body() ?: throw ApiError(response.message()) dao.insertJobs(body.toEntity(id)) } catch (e: IOException) { throw NetworkError } catch (e: Exception) { throw UnknownError } } override suspend fun getMyJobs(id: Long) { try { val response = apiService.getMyJobs() if (!response.isSuccessful) { throw ApiError(response.message()) } val body = response.body() ?: throw ApiError(response.message()) dao.insertJobs(body.toEntity(id)) } catch (e: IOException) { throw NetworkError } catch (e: Exception) { throw UnknownError } } override suspend fun saveJob(job: Job) { try { val response = apiService.saveJob(job) if (!response.isSuccessful) { throw ApiError(response.message()) } val jobResponse = response.body() ?: throw ApiError(response.message()) dao.insertJob(JobEntity.fromDto(jobResponse)) } catch (e: IOException) { throw NetworkError } catch (e: Exception) { throw UnknownError } } override suspend fun removeJobById(id: Long) { dao.removeByIdJob(id) try { val response = apiService.removeJobById(id) if (!response.isSuccessful) { throw ApiError(response.message()) } dao.removeByIdJob(id) } catch (e: IOException) { throw NetworkError } catch (e: Exception) { throw UnknownError } } override suspend fun likeByIdAsync(post: Post) { dao.likeById(post.id) try { val response = if (post.likedByMe) { apiService.dislikeById(post.id) } else { apiService.likeById(post.id) } if (!response.isSuccessful) { throw ApiError(response.message()) } val body = response.body() ?: throw ApiError(response.message()) dao.insert(PostEntity.fromDto(body)) } catch (e: IOException) { throw NetworkError } catch (e: Exception) { throw UnknownError } } override suspend fun edit(post: Post) { saveAsync(post) } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/repository/RepositoryImpl.kt
1674880813
package ru.netology.nework.repository import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module interface RepositoryModule { @Singleton @Binds fun bindsPostRepository(impl: RepositoryImpl): Repository }
NeWork_Diplom/app/src/main/java/ru/netology/nework/repository/RepositoryModule.kt
809681781
package ru.netology.nework.auth import android.content.Context import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import javax.inject.Inject import javax.inject.Singleton @Singleton class AppAuth @Inject constructor( @ApplicationContext private val context: Context, ) { private val prefs = context.getSharedPreferences("auth", Context.MODE_PRIVATE) private val idKey = "id" private val tokenKey = "token" private val nameKey = "name" private val _authStateFlow: MutableStateFlow<AuthState> init { val id = prefs.getLong(idKey, 0) val token = prefs.getString(tokenKey, null) val name = prefs.getString(nameKey, null) if (id == 0L || token == null) { _authStateFlow = MutableStateFlow(AuthState()) with(prefs.edit()) { clear() apply() } } else { _authStateFlow = MutableStateFlow(AuthState(id, token, name)) } } val authStateFlow: StateFlow<AuthState> = _authStateFlow.asStateFlow() @Synchronized fun setAuth(id: Long, token: String?, name: String?) { _authStateFlow.value = AuthState(id, token, name) with(prefs.edit()) { putLong(idKey, id) putString(tokenKey, token) putString(nameKey, token) apply() } } @Synchronized fun removeAuth() { _authStateFlow.value = AuthState() with(prefs.edit()) { clear() commit() } } } data class AuthState(val id: Long = 0, val token: String? = null, val name: String? = null)
NeWork_Diplom/app/src/main/java/ru/netology/nework/auth/AppAuth.kt
271262264
package ru.netology.nework.dao import androidx.room.* import ru.netology.nework.auxiliary.Converters import ru.netology.nework.dto.Post @Entity data class PostEntity( @PrimaryKey(autoGenerate = true) val id: Long, val authorId: Long, val author: String, val authorAvatar: String? = null, val content: String, val published: String, val likedByMe: Boolean = false, val likeOwnerIds: String?, @Embedded val coords: CoordEmbeddable?, val link:String? = null, val sharedByMe: Boolean = false, val countShared: Int = 999, val mentionIds: String?, val mentionedMe:Boolean = false, @Embedded var attachment: AttachmentEmbeddable?, val isNew: Boolean = false, var likes: Int = 0, ) { init { likes = Converters.toListDto(likeOwnerIds).size } fun toDto() = Post( id, authorId, author, authorAvatar, content, published, likedByMe, Converters.toListDto(likeOwnerIds), coords?.toDto(), link, sharedByMe, countShared, Converters.toListDto(mentionIds), mentionedMe, attachment?.toDto() ) companion object { fun fromDto(dto: Post) = PostEntity( dto.id, dto.authorId, dto.author, dto.authorAvatar, dto.content, dto.published, dto.likedByMe, Converters.fromListDto(dto.likeOwnerIds), CoordEmbeddable.fromDto(dto.coords), dto.link, dto.sharedByMe, dto.countShared, Converters.fromListDto(dto.mentionIds), dto.mentionedMe, AttachmentEmbeddable.fromDto(dto.attachment) ) } } fun List<PostEntity>.toDto(): List<Post> = map(PostEntity::toDto) fun List<Post>.toEntity(isNew: Boolean = false): List<PostEntity> = map(PostEntity::fromDto) .map { it.copy(isNew = isNew) }
NeWork_Diplom/app/src/main/java/ru/netology/nework/dao/PostEntity.kt
3861197141
package ru.netology.nework.dao import ru.netology.nework.dto.Attachment import ru.netology.nework.dto.AttachmentType data class AttachmentEmbeddable( var url: String, var type: AttachmentType, ) { fun toDto() = Attachment(url, type) companion object { fun fromDto(dto: Attachment?) = dto?.let { AttachmentEmbeddable(it.url, it.type) } } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/dao/AttachmentEmbeddable.kt
1171159073
package ru.netology.nework.dao import androidx.room.Entity import androidx.room.PrimaryKey import ru.netology.nework.dto.Job @Entity data class JobEntity( @PrimaryKey val id: Long, val name: String, val position: String, val start: String, val finish: String?, val link: String?, val ownerId:Long = -1 ) { fun toDto() = Job( id, name, position, start, finish, link, ownerId ) companion object { fun fromDto(dto: Job) = JobEntity( dto.id, dto.name, dto.position, dto.start, dto.finish, dto.link, dto.ownerId ) } } fun List<JobEntity>.toDto(): List<Job> = map(JobEntity::toDto) fun List<Job>.toEntity(id: Long): List<JobEntity> = map(JobEntity::fromDto).map { it.copy(ownerId = id) }
NeWork_Diplom/app/src/main/java/ru/netology/nework/dao/JobEntity.kt
184803895
package ru.netology.nework.dao import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import kotlinx.coroutines.flow.Flow @Dao interface PostDaoRoom { @Query("SELECT * FROM PostEntity WHERE isNew = 0 ORDER BY id DESC") fun getAll(): Flow<List<PostEntity>> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(post: PostEntity) @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(posts: List<PostEntity>) @Query("UPDATE PostEntity SET content = :content WHERE id = :id") suspend fun updateContentById(id: Long, content: String) suspend fun save(post: PostEntity) = if (post.id == 0L) insert(post) else updateContentById(post.id, post.content) @Query( """ UPDATE PostEntity SET likes = likes + CASE WHEN likedByMe THEN -1 ELSE 1 END, likedByMe = CASE WHEN likedByMe THEN 0 ELSE 1 END WHERE id = :id """ ) suspend fun likeById(id: Long) @Query("DELETE FROM PostEntity WHERE id = :id") suspend fun removeById(id: Long) @Query( """ UPDATE PostEntity SET isNew = 0 WHERE isNew = 1 """ ) suspend fun showNewPosts() @Query("SELECT * FROM UserEntity ORDER BY id DESC") fun getUsers(): Flow<List<UserEntity>> @Query("SELECT * FROM UserEntity ORDER BY id DESC") fun getUserById(): Flow<List<UserEntity>> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(user: UserEntity) @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertUsers(users: List<UserEntity>) @Query("SELECT * FROM EventsEntity ORDER BY id DESC") fun getAllEvents(): Flow<List<EventsEntity>> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertEvents(event: EventsEntity) @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertEvents(event: List<EventsEntity>) @Query("UPDATE EventsEntity SET content = :content WHERE id = :id") suspend fun updateContentEventsById(id: Long, content: String) suspend fun saveEvent(event: EventsEntity) = if (event.id == 0L) insertEvents(event) else updateContentById(event.id, event.content) @Query( """ UPDATE EventsEntity SET likedByMe = CASE WHEN likedByMe THEN 0 ELSE 1 END WHERE id = :id """ ) suspend fun likeByIdEvent(id: Long) @Query( """ UPDATE EventsEntity SET participatedByMe = CASE WHEN participatedByMe THEN 0 ELSE 1 END WHERE id = :id """ ) suspend fun joinByIdEvent(id: Long) @Query("DELETE FROM EventsEntity WHERE id = :id") suspend fun removeByIdEvent(id: Long) @Query("DELETE FROM JobEntity WHERE id = :id") suspend fun removeByIdJob(id: Long) @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertJob(job: JobEntity) @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertJobs(jobs: List<JobEntity>) @Query("SELECT * FROM JobEntity") fun getJobs(): Flow<List<JobEntity>> }
NeWork_Diplom/app/src/main/java/ru/netology/nework/dao/PostDaoRoom.kt
3427653236
package ru.netology.nework.dao import androidx.room.Entity import androidx.room.PrimaryKey import ru.netology.nework.dto.User @Entity data class UserEntity( @PrimaryKey val id: Long, val login: String, val name: String, val avatar: String?, ) { fun toDto() = User( id, login, name, avatar ) companion object { fun fromDto(dto: User) = UserEntity( dto.id, dto.login, dto.name, dto.avatar ) } } fun List<UserEntity>.toDto(): List<User> = map(UserEntity::toDto) fun List<User>.toEntity(): List<UserEntity> = map(UserEntity::fromDto)
NeWork_Diplom/app/src/main/java/ru/netology/nework/dao/UserEntity.kt
1960274790
package ru.netology.nework.dao import androidx.room.Embedded import androidx.room.Entity import androidx.room.PrimaryKey import ru.netology.nework.auxiliary.Converters import ru.netology.nework.dto.* @Entity class EventsEntity( @PrimaryKey val id:Long, val authorId:Long, val author:String, val authorAvatar:String? = null, val authorJob:String? = null, val content:String, val datetime:String, val published:String, val typeEvent: EventType, val likeOwnerIds: String?, val likedByMe:Boolean = false, val speakerIds: String?, val participantsIds: String?, val participatedByMe:Boolean = false, @Embedded val attachment: AttachmentEmbeddable? = null, val link:String? = null, val ownedByMe:Boolean = false, ) { fun toDto() = EventResponse( id, authorId, author, authorAvatar, authorJob, content, datetime, published, null, typeEvent, Converters.toListDto(likeOwnerIds), likedByMe, Converters.toListDto(speakerIds), Converters.toListDto(participantsIds), participatedByMe, attachment?.toDto(), link, ownedByMe, null ) companion object { fun fromDto(dto: EventResponse) = EventsEntity( dto.id, dto.authorId, dto.author, dto.authorAvatar, dto.authorJob, dto.content, dto.datetime, dto.published, dto.type, Converters.fromListDto(dto.likeOwnerIds), dto.likedByMe, Converters.fromListDto(dto.speakerIds), Converters.fromListDto(dto.participantsIds), dto.participatedByMe, AttachmentEmbeddable.fromDto(dto.attachment), dto.link, dto.ownedByMe ) } } fun List<EventsEntity>.toDto(): List<EventResponse> = map(EventsEntity::toDto) fun List<EventResponse>.toEntity(): List<EventsEntity> = map(EventsEntity::fromDto)
NeWork_Diplom/app/src/main/java/ru/netology/nework/dao/EventsEntity.kt
3713514689
package ru.netology.nework.dao import ru.netology.nework.dto.Coordinates data class CoordEmbeddable( val latitude : String?, val longitude : String?, ) { fun toDto() = Coordinates(latitude, longitude) companion object { fun fromDto(dto: Coordinates?) = dto?.let { CoordEmbeddable(it.lat, it.long) } } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/dao/CoordEmbeddable.kt
1347626548
package ru.netology.nework.adapters import android.content.res.Resources import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import ru.netology.nework.databinding.FragmentCardPostBinding import ru.netology.nework.dto.Post import android.view.View import android.widget.PopupMenu import android.widget.VideoView import androidx.core.view.isVisible import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import ru.netology.nework.R import ru.netology.nework.auxiliary.FloatingValue.convertDatePublished import ru.netology.nework.auxiliary.NumberTranslator import ru.netology.nework.dto.AttachmentType import kotlin.coroutines.EmptyCoroutineContext interface OnInteractionListener { fun onLike(post: Post) {} fun onShare(post: Post) {} fun onEdit(post: Post) {} fun onRemove(post: Post) {} fun onPlayPost(post: Post, videoView: VideoView? = null) {} fun onLink(post: Post) {} fun onPreviewAttachment(post: Post) {} fun onTapAvatar(post: Post) {} } class PostAdapter( private val onInteractionListener: OnInteractionListener ) : ListAdapter<Post,PostViewHolder>(PostDiffCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostViewHolder { val binding = FragmentCardPostBinding.inflate(LayoutInflater.from(parent.context), parent, false) return PostViewHolder(binding, onInteractionListener) } override fun onBindViewHolder(holder: PostViewHolder, position: Int) { val post = getItem(position) holder.renderingPostStructure(post) } override fun onViewRecycled(holder: PostViewHolder) { super.onViewRecycled(holder) holder.binding.videoAttachment.stopPlayback() holder.binding.videoAttachment.setVideoURI(null) } } class PostDiffCallback : DiffUtil.ItemCallback<Post>() { override fun areItemsTheSame(oldItem: Post, newItem: Post): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: Post, newItem: Post): Boolean { return oldItem == newItem } } class PostViewHolder( val binding: FragmentCardPostBinding, private val onInteractionListener: OnInteractionListener, ) : RecyclerView.ViewHolder(binding.root) { fun renderingPostStructure(post: Post) { with(binding) { title.text = post.author datePublished.text = convertDatePublished(post.published) content.text = post.content like.text = NumberTranslator.translateNumber(post.likeOwnerIds?.size ?: 0) like.isChecked = post.likedByMe share.isChecked = post.sharedByMe mentions.text = NumberTranslator.translateNumber(post.mentionIds?.size ?: 0) mentions.isCheckable = true mentions.isClickable = false mentions.isChecked = post.mentionedMe links.isVisible = (post.link != null) if (post.link != null) { links.text = post.link } Glide.with(avatar) .load(post.authorAvatar) .placeholder(R.drawable.ic_image_not_supported_24) .error(R.drawable.ic_not_avatars_24) .circleCrop() .timeout(10_000) .into(avatar) moreVert.visibility = if (post.ownedByMe) View.VISIBLE else View.INVISIBLE if (post.attachment != null) { attachmentContent.isVisible = true if(post.attachment.type == AttachmentType.IMAGE) { Glide.with(imageAttachment) .load(post.attachment.url) .placeholder(R.drawable.ic_image_not_supported_24) .apply( RequestOptions.overrideOf( Resources.getSystem().displayMetrics.widthPixels ) ) .timeout(10_000) .into(imageAttachment) } videoAttachment.isVisible = (post.attachment.type == AttachmentType.VIDEO) playButtonPost.isVisible = (post.attachment.type == AttachmentType.VIDEO) playButtonPostAudio.isVisible = (post.attachment.type == AttachmentType.AUDIO) imageAttachment.isVisible = (post.attachment.type == AttachmentType.IMAGE) descriptionAttachment.isVisible = (post.attachment.type == AttachmentType.AUDIO) } else { attachmentContent.visibility = View.GONE } postListeners(post) } } private fun postListeners(post: Post) { with(binding) { like.setOnClickListener { like.isChecked = !like.isChecked //Инвертируем нажатие onInteractionListener.onLike(post) } share.setOnClickListener { onInteractionListener.onShare(post) } playButtonPostAudio.setOnClickListener { CoroutineScope(EmptyCoroutineContext).launch { onInteractionListener.onPlayPost(post) } } playButtonPost.setOnClickListener { onInteractionListener.onPlayPost(post, binding.videoAttachment) } imageAttachment.setOnClickListener { onInteractionListener.onPreviewAttachment(post) } links.setOnClickListener { onInteractionListener.onLink(post) } avatar.setOnClickListener { onInteractionListener.onTapAvatar(post) } moreVert.setOnClickListener { val popupMenu = PopupMenu(it.context, it) popupMenu.apply { inflate(R.menu.options_post) setOnMenuItemClickListener { item -> when (item.itemId) { R.id.remove -> { moreVert.isChecked = false onInteractionListener.onRemove(post) true } R.id.edit -> { moreVert.isChecked = false onInteractionListener.onEdit(post) true } else -> false } } }.show() popupMenu.setOnDismissListener { moreVert.isChecked = false } } } } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/adapters/PostAdapter.kt
1160797614
package ru.netology.nework.adapters import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import ru.netology.nework.R import ru.netology.nework.databinding.FragmentCardUsersBinding import ru.netology.nework.dto.User interface OnInteractionListenerUsers { fun onTap(user: User) {} } class UsersAdapter( private val onInteractionListener: OnInteractionListenerUsers = object : OnInteractionListenerUsers {} ) : ListAdapter<User, UserViewHolder>(UserDiffCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder { val binding = FragmentCardUsersBinding.inflate(LayoutInflater.from(parent.context), parent, false) return UserViewHolder(binding, onInteractionListener) } override fun onBindViewHolder(holder: UserViewHolder, position: Int) { val user = getItem(position) holder.renderingPostStructure(user) } } class UserDiffCallback : DiffUtil.ItemCallback<User>() { override fun areItemsTheSame(oldItem: User, newItem: User): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: User, newItem: User): Boolean { return oldItem == newItem } } class UserViewHolder( private val binding: FragmentCardUsersBinding, private val onInteractionListener: OnInteractionListenerUsers ) : RecyclerView.ViewHolder(binding.root) { @SuppressLint("SetTextI18n") fun renderingPostStructure(user: User) { with(binding) { idUser.text = "[id: ${user.id}]" loginUser.text = user.login nameUser.text = "(${user.name})" Glide.with(avatar) .load(user.avatar) .placeholder(R.drawable.ic_image_not_supported_24) .error(R.drawable.ic_not_avatars_24) .circleCrop() .timeout(10_000) .into(avatar) userListeners(user) } } private fun userListeners(user: User) { binding.userCard.setOnClickListener { onInteractionListener.onTap(user) } } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/adapters/UsersAdapter.kt
1703487320
package ru.netology.nework.adapters import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.core.view.isVisible import androidx.recyclerview.widget.RecyclerView import ru.netology.nework.databinding.FragmentCardJobBinding import ru.netology.nework.dto.Job interface OnInteractionListenerJob { fun onEdit(job: Job) {} fun onRemove(job: Job) {} fun onLink(job: Job) {} fun myOrNo(job: Job):Boolean {return true} } class JobAdapter( private val onInteractionListener: OnInteractionListenerJob ) : ListAdapter<Job,JobViewHolder>(JobDiffCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): JobViewHolder { val binding = FragmentCardJobBinding.inflate(LayoutInflater.from(parent.context), parent, false) return JobViewHolder(binding, onInteractionListener) } override fun onBindViewHolder(holder: JobViewHolder, position: Int) { val job = getItem(position) holder.renderingPostStructure(job) } } class JobDiffCallback : DiffUtil.ItemCallback<Job>() { override fun areItemsTheSame(oldItem: Job, newItem: Job): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: Job, newItem: Job): Boolean { return oldItem == newItem } } class JobViewHolder( private val binding: FragmentCardJobBinding, private val onInteractionListener: OnInteractionListenerJob, ) : RecyclerView.ViewHolder(binding.root) { fun renderingPostStructure(job: Job) { with(binding) { jobOrganization.text = job.name jobPosition.text = job.position val workingPeriod = "${job.start.take(10)}\n${job.finish?.take(10) ?: "..."}" jobWorking.text = workingPeriod jobLink.isVisible = (job.link != null) if (job.link != null) { jobLink.text = job.link } jobEdit.isVisible = onInteractionListener.myOrNo(job) jobRemove.isVisible = onInteractionListener.myOrNo(job) postListeners(job) } } private fun postListeners(job: Job) { with(binding) { jobLink.setOnClickListener { onInteractionListener.onLink(job) } jobEdit.setOnClickListener{ onInteractionListener.onEdit(job) } jobRemove.setOnClickListener{ onInteractionListener.onRemove(job) } } } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/adapters/JobAdapter.kt
4221419899
package ru.netology.nework.adapters import android.content.res.Resources import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import android.view.View import android.widget.PopupMenu import android.widget.VideoView import androidx.core.view.isVisible import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import ru.netology.nework.R import ru.netology.nework.auxiliary.FloatingValue.convertDatePublished import ru.netology.nework.auxiliary.NumberTranslator import ru.netology.nework.databinding.FragmentCardEventBinding import ru.netology.nework.dto.AttachmentType import ru.netology.nework.dto.EventResponse import kotlin.coroutines.EmptyCoroutineContext interface OnInteractionListenerEvent { fun onLike(event: EventResponse) {} fun onShare(event: EventResponse) {} fun onEdit(event: EventResponse) {} fun onRemove(event: EventResponse) {} fun onPlayPost(event: EventResponse, videoView: VideoView? = null) {} fun onLink(event: EventResponse) {} fun onPreviewAttachment(event: EventResponse) {} fun onSpeakersAction(event: EventResponse) {} fun onPartyAction(event: EventResponse) {} fun onJoinAction(event: EventResponse) {} fun onTapAvatar(event: EventResponse) {} } class EventAdapter( private val onInteractionListener: OnInteractionListenerEvent ) : ListAdapter<EventResponse,EventViewHolder>(EventDiffCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EventViewHolder { val binding = FragmentCardEventBinding.inflate(LayoutInflater.from(parent.context), parent, false) return EventViewHolder(binding, onInteractionListener) } override fun onBindViewHolder(holder: EventViewHolder, position: Int) { val post = getItem(position) holder.renderingPostStructure(post) } override fun onViewRecycled(holder: EventViewHolder) { super.onViewRecycled(holder) holder.binding.videoAttachment.stopPlayback() holder.binding.videoAttachment.setVideoURI(null) } } class EventDiffCallback : DiffUtil.ItemCallback<EventResponse>() { override fun areItemsTheSame(oldItem: EventResponse, newItem: EventResponse): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: EventResponse, newItem: EventResponse): Boolean { return oldItem == newItem } } class EventViewHolder( val binding: FragmentCardEventBinding, private val onInteractionListener: OnInteractionListenerEvent, ) : RecyclerView.ViewHolder(binding.root) { fun renderingPostStructure(event: EventResponse) { with(binding) { title.text = event.author datePublished.text = convertDatePublished(event.published) content.text = event.content like.text = NumberTranslator.translateNumber(event.likeOwnerIds.size) like.isChecked = event.likedByMe eventDateValue.text = convertDatePublished(event.datetime).dropLast(3) eventFormatValue.text = event.type.name joinButton.isChecked = event.participatedByMe joinButton.text = if (joinButton.isChecked) { binding.root.context.getString(R.string.un_join) } else { binding.root.context.getString(R.string.join) } links.isVisible = (event.link != null) if (event.link != null) { links.text = event.link } Glide.with(avatar) .load(event.authorAvatar) .placeholder(R.drawable.ic_image_not_supported_24) .error(R.drawable.ic_not_avatars_24) .circleCrop() .timeout(10_000) .into(avatar) moreVert.visibility = if (event.ownedByMe) View.VISIBLE else View.INVISIBLE if (event.attachment != null) { attachmentContent.isVisible = true if(event.attachment.type == AttachmentType.IMAGE) { Glide.with(imageAttachment) .load(event.attachment.url) .placeholder(R.drawable.ic_image_not_supported_24) .apply( RequestOptions.overrideOf( Resources.getSystem().displayMetrics.widthPixels ) ) .timeout(10_000) .into(imageAttachment) } videoAttachment.isVisible = (event.attachment.type == AttachmentType.VIDEO) playButtonPost.isVisible = (event.attachment.type == AttachmentType.VIDEO) playButtonPostAudio.isVisible = (event.attachment.type == AttachmentType.AUDIO) imageAttachment.isVisible = (event.attachment.type == AttachmentType.IMAGE) descriptionAttachment.isVisible = (event.attachment.type == AttachmentType.AUDIO) } else { attachmentContent.visibility = View.GONE } postListeners(event) } } private fun postListeners(event: EventResponse) { with(binding) { like.setOnClickListener { like.isChecked = !like.isChecked //Инвертация нажатия onInteractionListener.onLike(event) } share.setOnClickListener { onInteractionListener.onShare(event) } playButtonPostAudio.setOnClickListener { CoroutineScope(EmptyCoroutineContext).launch { onInteractionListener.onPlayPost(event) } } playButtonPost.setOnClickListener { onInteractionListener.onPlayPost(event, binding.videoAttachment) } imageAttachment.setOnClickListener { onInteractionListener.onPreviewAttachment(event) } links.setOnClickListener { onInteractionListener.onLink(event) } partyButton.setOnClickListener{ onInteractionListener.onPartyAction(event) } joinButton.setOnClickListener{ onInteractionListener.onJoinAction(event) } speakersButton.setOnClickListener{ onInteractionListener.onSpeakersAction(event) } avatar.setOnClickListener { onInteractionListener.onTapAvatar(event) } moreVert.setOnClickListener { val popupMenu = PopupMenu(it.context, it) popupMenu.apply { inflate(R.menu.options_post) setOnMenuItemClickListener { item -> when (item.itemId) { R.id.remove -> { moreVert.isChecked = false onInteractionListener.onRemove(event) true } R.id.edit -> { moreVert.isChecked = false onInteractionListener.onEdit(event) true } else -> false } } }.show() popupMenu.setOnDismissListener { moreVert.isChecked = false } } } } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/adapters/EventAdapter.kt
998068998
package ru.netology.nework.model import ru.netology.nework.dto.Post data class FeedModel( val posts: List<Post> = emptyList(), val empty: Boolean = false, ) sealed interface FeedModelState { object Loading : FeedModelState object Error : FeedModelState object Refresh : FeedModelState object Idle : FeedModelState object ShadowIdle : FeedModelState }
NeWork_Diplom/app/src/main/java/ru/netology/nework/model/FeedModel.kt
2408702145
package ru.netology.nework.model import android.net.Uri import ru.netology.nework.dto.AttachmentType import java.io.File data class MediaModel(val uri: Uri? = null, val file: File? = null, val attachmentType: AttachmentType? = null)
NeWork_Diplom/app/src/main/java/ru/netology/nework/model/MediaModel.kt
3863301666
package ru.netology.nework.api import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.create import ru.netology.nework.BuildConfig import ru.netology.nework.auth.AppAuth import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module class ApiModule { companion object { private const val BASE_URL = "${BuildConfig.BASE_URL}/api/" } @Provides @Singleton fun provideLogging(): HttpLoggingInterceptor = HttpLoggingInterceptor().apply { if (BuildConfig.DEBUG) { level = HttpLoggingInterceptor.Level.BODY } } @Provides @Singleton fun provideOkHttp( logging: HttpLoggingInterceptor, appAuth: AppAuth ):OkHttpClient = OkHttpClient.Builder() .addInterceptor(logging) .addInterceptor { chain -> appAuth.authStateFlow.value.token?.let { token -> val newRequest = chain.request().newBuilder() .addHeader("Authorization", token) .build() return@addInterceptor chain.proceed(newRequest) } chain.proceed(chain.request()) } .build() @Provides @Singleton fun provideRetrofit( okHttpClient: OkHttpClient ): Retrofit = Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .baseUrl(BASE_URL) .client(okHttpClient) .build() @Provides @Singleton fun provideApiService( retrofit: Retrofit ): ApiService = retrofit.create() }
NeWork_Diplom/app/src/main/java/ru/netology/nework/api/ApiModule.kt
269447782
package ru.netology.nework.api import okhttp3.MultipartBody import okhttp3.RequestBody import retrofit2.Response import retrofit2.http.* import ru.netology.nework.dto.* interface ApiService { @GET("posts") suspend fun getAll(): Response<List<Post>> @GET("posts/{id}/newer") suspend fun getNewer(@Path("id") id: Long): Response<List<Post>> @POST("posts") suspend fun save(@Body post: PostCreateRequest): Response<PostResponse> @DELETE("posts/{id}") suspend fun removeById(@Path("id") id: Long): Response<Unit> @POST("posts/{id}/likes") suspend fun likeById(@Path("id") id: Long): Response<Post> @DELETE("posts/{id}/likes") suspend fun dislikeById(@Path("id") id: Long): Response<Post> @Multipart @POST("media") suspend fun upload(@Part media: MultipartBody.Part): Response<MediaResponse> @FormUrlEncoded @POST("users/authentication") suspend fun login(@Field("login") login: String, @Field("password") pass: String): Response<Token> @FormUrlEncoded @POST("users/registration") suspend fun register( @Field("login") login: String, @Field("password") pass: String, @Field("name") name: String ): Response<Token> @Multipart @POST("users/registration") suspend fun registerWithPhoto( @Part("login") login: RequestBody, @Part("password") pass: RequestBody, @Part("name") name: RequestBody, @Part media: MultipartBody.Part, ): Response<Token> @GET("users") suspend fun getUsers(): Response<List<UserResponse>> @GET("users/{id}") suspend fun getUserById(@Path("id") id: Long): Response<UserResponse> @GET("events") suspend fun getAllEvents(): Response<List<EventResponse>> @POST("events") suspend fun saveEvents(@Body event: EventCreateRequest): Response<EventResponse> @DELETE("events/{id}") suspend fun removeByIdEvent(@Path("id") id: Long): Response<Unit> @POST("events/{id}/likes") suspend fun likeByIdEvent(@Path("id") id: Long): Response<EventResponse> @DELETE("events/{id}/likes") suspend fun dislikeByIdEvent(@Path("id") id: Long): Response<EventResponse> @POST("events/{id}/participants") suspend fun joinByIdEvent(@Path("id") id: Long): Response<EventResponse> @DELETE("events/{id}/participants") suspend fun unJoinByIdEvent(@Path("id") id: Long): Response<EventResponse> @GET("my/jobs") suspend fun getMyJobs(): Response<List<Job>> @POST("my/jobs") suspend fun saveJob(@Body job: Job): Response<Job> @DELETE("my/jobs/{id}") suspend fun removeJobById(@Path("id") id: Long): Response<Unit> @GET("{id}/jobs") suspend fun getUserJobs(@Path("id") id: Long): Response<List<Job>> }
NeWork_Diplom/app/src/main/java/ru/netology/nework/api/ApiService.kt
27382808
package ru.netology.nework.application import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class NeWorkApplication : Application()
NeWork_Diplom/app/src/main/java/ru/netology/nework/application/NeWorkApplication.kt
483760987
package ru.netology.nework.error sealed class AppError(var code: String): RuntimeException() class ApiError(code: String): AppError(code) object NetworkError : AppError("error_network") object UnknownError: AppError("error_unknown")
NeWork_Diplom/app/src/main/java/ru/netology/nework/error/AppError.kt
1017337776
package ru.netology.nework.auxiliary import android.content.Context import android.view.View import android.view.inputmethod.InputMethodManager object AndroidUtils { fun hideKeyboard(view: View) { val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(view.windowToken, 0) } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/auxiliary/AndroidUtils.kt
3924824916
package ru.netology.nework.auxiliary import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer class SingleLiveEvent<T> : MutableLiveData<T>() { private var pending = false override fun observe(owner: LifecycleOwner, observer: Observer<in T?>) { require (!hasActiveObservers()) { error("Multiple observers registered but only one will be notified of changes.") } super.observe(owner) { if (pending) { pending = false observer.onChanged(it) } } } override fun setValue(t: T?) { pending = true super.setValue(t) } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/auxiliary/SingleLiveEvent.kt
4009445706
package ru.netology.nework.auxiliary object Converters { fun fromListDto(list: List<Long>?): String { if (list == null) return "" return list.toString() } fun toListDto(data: String?): List<Long> { return if (data == "[]") emptyList() else { val substr = data?.substring(1, data.length - 1) substr?.split(", ")?.map { it.toLong() } ?: emptyList() } } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/auxiliary/Converters.kt
1390758527
package ru.netology.nework.auxiliary import android.os.Bundle import ru.netology.nework.auxiliary.ConstantValues.EVENT_ID import ru.netology.nework.auxiliary.ConstantValues.EVENT_REQUEST_TYPE import ru.netology.nework.auxiliary.ConstantValues.POST_CONTENT import ru.netology.nework.auxiliary.ConstantValues.POST_LINK import ru.netology.nework.auxiliary.ConstantValues.POST_MENTIONS_COUNT import ru.netology.nework.auxiliary.ConstantValues.USER_ID class Companion { companion object { var Bundle.textArg: String? set(value) = putString(POST_CONTENT, value) get() = getString(POST_CONTENT) var Bundle.linkArg: String? set(value) = putString(POST_LINK, value) get() = getString(POST_LINK) var Bundle.mentionsCountArg: Long set(value) = putLong(POST_MENTIONS_COUNT, value) get() = getLong(POST_MENTIONS_COUNT) var Bundle.eventId: Long set(value) = putLong(EVENT_ID, value) get() = getLong(EVENT_ID) var Bundle.eventRequestType: String? set(value) = putString(EVENT_REQUEST_TYPE, value) get() = getString(EVENT_REQUEST_TYPE) var Bundle.userId: Long set(value) = putLong(USER_ID, value) get() = getLong(USER_ID) } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/auxiliary/Companion.kt
2168850798
package ru.netology.nework.auxiliary import android.content.ContentResolver import android.net.Uri import android.webkit.MimeTypeMap object FloatingValue { var textNewPost = "" var currentFragment = "" fun convertDatePublished(dateString: String): String { val date = dateString.substring(0..9) val time = dateString.substring(11..18) return "$date $time" } fun getExtensionFromUri(uri: Uri, contentResolver: ContentResolver): String? { val mimeType = contentResolver.getType(uri) ?: return null return MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType) } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/auxiliary/FloatingValue.kt
3032976423
package ru.netology.nework.auxiliary import ru.netology.nework.dto.* import ru.netology.nework.model.MediaModel object ConstantValues { const val POST_CONTENT = "content" const val POST_LINK = "link" const val POST_MENTIONS_COUNT = "count mentions in post" const val EVENT_ID = "event id" const val EVENT_REQUEST_TYPE = "party or speakers" const val USER_ID = "user id" val emptyUser = User( id = -1, login = "", name = "", avatar = null ) val emptyJob = Job( id = 0, name = "", position = "", start = "", finish = "", link = "", ownerId = -1L, ) val emptyPost = Post( id = 0, authorId = 0, content = "", author = "", likeOwnerIds = emptyList(), countShared = 0, mentionIds = emptyList(), published = "" ) val emptyEvent = EventResponse( id = 0, authorId = 0, content = "", author = "", likeOwnerIds = emptyList(), datetime = "", type = EventType.OFFLINE, published = "", ) val noPhoto = MediaModel() }
NeWork_Diplom/app/src/main/java/ru/netology/nework/auxiliary/ConstantValues.kt
698559866
package ru.netology.nework.auxiliary object NumberTranslator { fun translateNumber(count: Int) = when (count) { in 1..999 -> "$count" in 1_000..9_999 -> "${count / 1000}.${count % 1000 / 100}K" in 10_000..999_000 -> "${count / 1000}K" in 1_000_000..9_999_999 -> "${count / 1_000_000}.${count % 1_000_000 / 100_000}M" in 10_000_000..Int.MAX_VALUE -> "${count / 1_000_000}M" else -> "0" } }
NeWork_Diplom/app/src/main/java/ru/netology/nework/auxiliary/NumberTranslator.kt
3510632593
package com.nitc.projectsgc import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.nitc.projectsgc", appContext.packageName) } }
nitc_sgc_mvvm/app/src/androidTest/java/com/nitc/projectsgc/ExampleInstrumentedTest.kt
2871311844
package com.nitc.projectsgc import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
nitc_sgc_mvvm/app/src/test/java/com/nitc/projectsgc/ExampleUnitTest.kt
3006855756
package com.nitc.projectsgc import android.app.Application import android.util.Log import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class MyApplication:Application() { }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/MyApplication.kt
3156920304
package com.nitc.projectsgc import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.Logout import androidx.compose.material.icons.filled.Home import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.filled.Notifications import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Scaffold import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarColors import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.colorResource import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.nitc.projectsgc.composable.admin.viewmodels.AdminViewModel import com.nitc.projectsgc.composable.admin.viewmodels.MentorListViewModel import com.nitc.projectsgc.composable.admin.viewmodels.StudentListViewModel import com.nitc.projectsgc.composable.components.HeadingText import com.nitc.projectsgc.composable.components.SimpleSnackBar import com.nitc.projectsgc.composable.components.SimpleToast import com.nitc.projectsgc.composable.components.SubHeadingText import com.nitc.projectsgc.composable.login.LoginCredential import com.nitc.projectsgc.composable.login.LoginScreen import com.nitc.projectsgc.composable.util.storage.StorageManagerImpl import com.nitc.projectsgc.composable.login.LoginViewModel import com.nitc.projectsgc.composable.mentor.MentorViewModel import com.nitc.projectsgc.composable.navigation.NavigationScreen import com.nitc.projectsgc.composable.navigation.graphs.adminGraph import com.nitc.projectsgc.composable.navigation.graphs.mentorGraph import com.nitc.projectsgc.composable.navigation.graphs.newsGraph import com.nitc.projectsgc.composable.navigation.graphs.studentGraph import com.nitc.projectsgc.composable.news.NewsViewModel import com.nitc.projectsgc.composable.student.viewmodels.BookingViewModel import com.nitc.projectsgc.composable.student.viewmodels.StudentViewModel import com.nitc.projectsgc.composable.util.UserRole import com.nitc.projectsgc.composable.util.storage.StorageViewModel import com.nitc.projectsgc.databinding.ActivityMainBinding import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : ComponentActivity() { lateinit var binding: ActivityMainBinding val sharedViewModel: SharedViewModel by viewModels() private val adminViewModel: AdminViewModel by viewModels() private val studentListViewModel: StudentListViewModel by viewModels() private val mentorListViewModel: MentorListViewModel by viewModels() private val loginViewModel: LoginViewModel by viewModels() private val mentorViewModel: MentorViewModel by viewModels() private val studentViewModel: StudentViewModel by viewModels() private val bookingViewModel: BookingViewModel by viewModels() private val storageViewModel: StorageViewModel by viewModels() private val newsViewModel: NewsViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { // val titleStateHolder = TitleStateHolder(initialTitle = "Login") AllContent() } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun AllContent() { val titleState = remember { mutableStateOf("SGC NITC") } val topBarState = remember { mutableStateOf(false) } val dropDownState = remember { mutableStateOf(false) } val dashboardState = remember { mutableStateOf(false) } val logoutState = remember { mutableStateOf(false) } val newsState = remember { mutableStateOf(false) } Scaffold( topBar = { if (topBarState.value) { TopAppBar( title = { HeadingText( text = titleState.value, fontColor = Color.Black, modifier = Modifier ) }, colors = TopAppBarColors( containerColor = colorResource(id = R.color.lavender), titleContentColor = Color.White, actionIconContentColor = Color.White, scrolledContainerColor = Color.Yellow, navigationIconContentColor = Color.Black ), actions = { IconButton(onClick = { newsState.value = true }) { Icon( imageVector = Icons.Filled.Notifications, tint = Color.Black, contentDescription = "News" ) } Box(modifier = Modifier) { IconButton(onClick = { dropDownState.value = true }) { Icon( imageVector = Icons.Filled.MoreVert, tint = Color.Black, contentDescription = "More Options" ) } DropdownMenu( modifier = Modifier.align(Alignment.BottomEnd), expanded = dropDownState.value, onDismissRequest = { dropDownState.value = false }) { DropdownMenuItem( text = { SubHeadingText( text = "Dashboard", fontColor = Color.Black, modifier = Modifier ) }, leadingIcon = { Icon( imageVector = Icons.Filled.Home, contentDescription = "Dashboard Icon" ) }, onClick = { dashboardState.value = true dropDownState.value = false }) DropdownMenuItem( text = { SubHeadingText( text = "Logout", fontColor = Color.Black, modifier = Modifier ) }, leadingIcon = { Icon( imageVector = Icons.AutoMirrored.Filled.Logout, contentDescription = "Logout Icon" ) }, onClick = { logout() dropDownState.value = false logoutState.value = true }) } } }, ) } }, content = { paddingValues -> Column( modifier = Modifier .fillMaxSize() .padding(paddingValues) ) { AllNavigation(titleState, topBarState, dashboardState, newsState,logoutState) } } ) } @Composable fun AllNavigation( titleState: MutableState<String>, topBarState: MutableState<Boolean>, dashboardState: MutableState<Boolean>, newsState:MutableState<Boolean>, logoutState: MutableState<Boolean> ) { Log.d("inLogin", "Herehreheh") val navController = rememberNavController() var loginCredential = storageViewModel.getUserInfo() LaunchedEffect(key1 = logoutState.value) { if (logoutState.value) { navController.popBackStack() navController.navigate(NavigationScreen.LoginScreen.route) } } LaunchedEffect(key1 = dashboardState.value) { if (dashboardState.value) { dashboardState.value = false navController.popBackStack(NavigationScreen.FlashScreen.route, true) when (storageViewModel.getUserType()) { UserRole.Admin -> navController.popBackStack("admin",inclusive = true) UserRole.Student-> navController.popBackStack("student/${loginCredential.username}",inclusive = true) UserRole.Mentor -> navController.popBackStack("mentor/${loginCredential.username}",inclusive = true) else -> navController.popBackStack(NavigationScreen.LoginScreen.route,inclusive = true) } when (storageViewModel.getUserType()) { UserRole.Admin -> navController.navigate("admin") UserRole.Student-> navController.navigate("student/${loginCredential.username}") UserRole.Mentor -> navController.navigate("mentor/${loginCredential.username}") else -> navController.navigate(NavigationScreen.LoginScreen.route) } } } LaunchedEffect(key1 = newsState.value) { if(newsState.value){ newsState.value = false navController.popBackStack("news/${loginCredential.userType.toString()}/${loginCredential.username}",inclusive = true) navController.navigate("news/${loginCredential.userType.toString()}/${loginCredential.username}") } } NavHost( navController = navController, startDestination = NavigationScreen.FlashScreen.route ) { composable(route = NavigationScreen.FlashScreen.route) { loginCredential = storageViewModel.getUserInfo() topBarState.value = false Log.d("userType", "User type is ${loginCredential.userType}") FlashScreen { navController.popBackStack(NavigationScreen.FlashScreen.route, true) when (loginCredential.userType) { UserRole.Admin -> navController.navigate("admin") UserRole.Student-> navController.navigate("student/${loginCredential.username}") UserRole.Mentor -> navController.navigate("mentor/${loginCredential.username}") else -> navController.navigate(NavigationScreen.LoginScreen.route) } } } composable(route = NavigationScreen.LoginScreen.route) { topBarState.value = false // logoutState.value = false LoginScreen( navController = navController, loginViewModel = loginViewModel, storageViewModel = storageViewModel ) { userTypeSelected -> Log.d("loginSuccess", "Login successful") sharedViewModel.userType = userTypeSelected sharedViewModel.loginCredential = loginViewModel.loginCredential.value navController.popBackStack(NavigationScreen.LoginScreen.route, true) Log.d("userType", "User type is $userTypeSelected") when (userTypeSelected) { UserRole.Admin -> { Log.d("userType", "in 0") navController.navigate("admin") } UserRole.Student-> { Log.d("loginSuccess","Passed username : ${loginViewModel.loginCredential.value.username}") navController.navigate("student/${loginViewModel.loginCredential.value.username}") } UserRole.Mentor -> { navController.navigate("mentor/${loginViewModel.loginCredential.value.username}") } else -> navController.navigate(NavigationScreen.LoginScreen.route) } } } studentGraph( titleState, topBarState, navController, studentViewModel, bookingViewModel ) adminGraph( titleState, topBarState, navController, adminViewModel, studentListViewModel, mentorListViewModel ) mentorGraph( topBarState, navController, mentorViewModel, titleState ) newsGraph( topBarState, navController, titleState, newsViewModel ) } } private fun logout() { storageViewModel.deleteData() } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/MainActivity.kt
1804385727
package com.nitc.projectsgc import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import com.nitc.projectsgc.composable.components.HeadingText import kotlinx.coroutines.delay @Composable fun FlashScreen(onTimeout:()->Unit) { LaunchedEffect(Unit) { delay(300) // Delay for 5 seconds onTimeout() } Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Image( painter = painterResource(id = R.drawable.sgc_logo_blue_1), contentDescription = "SGC Logo", modifier = Modifier.fillMaxSize(0.6F) ) HeadingText(text = stringResource(id = R.string.app_name), fontColor = Color.Black, modifier = Modifier) } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/FlashScreen.kt
2894500223
package com.nitc.projectsgc.composable.util import android.os.Build import android.util.Log import androidx.annotation.RequiresApi import java.text.SimpleDateFormat import java.time.Instant import java.time.LocalDate import java.time.ZoneId import java.time.format.DateTimeFormatter import java.util.Locale class DateUtils { fun convertMillisToLocalDate(millis: Long) : LocalDate { return Instant .ofEpochMilli(millis) .atZone(ZoneId.systemDefault()) .toLocalDate() } private fun convertMillisToLocalDateWithFormatter(date: LocalDate, dateTimeFormatter: DateTimeFormatter) : LocalDate { //Convert the date to a long in millis using a dateformmater val dateInMillis = LocalDate.parse(date.format(dateTimeFormatter), dateTimeFormatter) .atStartOfDay(ZoneId.systemDefault()) .toInstant() .toEpochMilli() //Convert the millis to a localDate object return Instant .ofEpochMilli(dateInMillis) .atZone(ZoneId.systemDefault()) .toLocalDate() } fun reverseDateString(inputDate:String):String{ var numbers = inputDate.split('-') numbers = numbers.reversed() return numbers.joinToString('-'.toString()) } fun dateToString(millis:Long): String { val localDate = convertMillisToLocalDate(millis) val dateFormatter = DateTimeFormatter.ofPattern("EEEE, dd MMMM, yyyy", Locale.getDefault()) val dateInMillis = convertMillisToLocalDateWithFormatter(localDate, dateFormatter) Log.d("dateToString",dateInMillis.toString()) // return SimpleDateFormat("dd-MM-yyyy",Locale.getDefault()).format(SimpleDateFormat("yyyy-MM-dd",Locale.getDefault()).format(dateInMillis)) val gotDate = reverseDateString(dateInMillis.toString()) Log.d("dateToString","gotdate : $gotDate") return gotDate } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/util/DateUtils.kt
982501998
package com.nitc.projectsgc.composable.util.storage import androidx.lifecycle.ViewModel import com.nitc.projectsgc.composable.login.LoginCredential import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class StorageViewModel @Inject constructor( private val storageManager: StorageManager ) : ViewModel(){ fun storeUserData(userType: Int, username: String,password:String) { storageManager.saveUsername(userType, username,password) } fun deleteData():Boolean{ return storageManager.deleteData() } fun getUserInfo():LoginCredential{ return storageManager.getUserInfo() } fun getUserType():Int{ return storageManager.getUserType() } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/util/storage/StorageViewModel.kt
3921216926
package com.nitc.projectsgc.composable.util.storage import android.content.Context import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ViewModelComponent import dagger.hilt.android.scopes.ViewModelScoped @Module @InstallIn(ViewModelComponent::class) object StorageModule { @Provides @ViewModelScoped fun provideStorageManager(context: Context): StorageManager { return StorageManagerImpl(context) } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/util/storage/StorageModule.kt
849307596
package com.nitc.projectsgc.composable.util.storage import com.nitc.projectsgc.composable.login.LoginCredential interface StorageManager { fun getUserType():Int fun saveUsername( userType: Int, username: String, password: String, ):Boolean fun deleteData():Boolean fun getUserInfo(): LoginCredential }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/util/storage/StorageManager.kt
905236752
package com.nitc.projectsgc.composable.util.storage import android.content.Context import com.nitc.projectsgc.composable.login.LoginCredential import javax.inject.Inject class StorageManagerImpl @Inject constructor( private val context: Context ) : StorageManager { override fun getUserType():Int{ var sharedPreferences = context.getSharedPreferences( "sgcLogin", Context.MODE_PRIVATE ) if(sharedPreferences != null){ val userType = sharedPreferences.getInt("userType",-1) return userType }else return -1 } override fun saveUsername( userType: Int, username: String, password: String, ):Boolean{ var saved = false var sharedPreferences = context.getSharedPreferences( "sgcLogin", Context.MODE_PRIVATE ) val editor = sharedPreferences?.edit() if (editor != null) { editor.putString("password", password) editor.putInt("userType", userType) editor.putString("username", username) editor.apply() saved = true } return saved } override fun getUserInfo(): LoginCredential { var sharedPreferences = context.getSharedPreferences( "sgcLogin", Context.MODE_PRIVATE ) if(sharedPreferences != null){ val userType = sharedPreferences.getInt("userType",-1) val username = sharedPreferences.getString("username","") val password = sharedPreferences.getString("password","") return LoginCredential(userType,username!!,password!!) }else return LoginCredential() } override fun deleteData(): Boolean { val sharedPreferences = context.getSharedPreferences( "sgcLogin", Context.MODE_PRIVATE ) val editor = sharedPreferences.edit() return if(editor != null){ editor.remove("password") editor.remove("userType") editor.remove("username") editor.apply() true }else false } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/util/storage/StorageManagerImpl.kt
2418561869
package com.nitc.projectsgc.composable.util object UserRole { val Admin = 0 val Student = 1 val Mentor = 2 }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/util/UserRole.kt
725030940
package com.nitc.projectsgc.composable.util import arrow.core.Either object PathUtils { fun getMentorType(username: String): Either<Exception, String> { val underscoreIndex = username.indexOfFirst { it == '_' } if (underscoreIndex == -1) { return Either.Left(Exception("Username format invalid: Missing underscore")) } val lastUnderscoreIndex = username.indexOfLast { it == '_' } if (lastUnderscoreIndex == -1) { return Either.Left(Exception("Username format invalid: Missing ending underscore")) } return Either.Right(username.substring(underscoreIndex + 1, lastUnderscoreIndex)) } fun getUsernameFromEmailSure(userType:Int,input: String): String { val atRateIndex = input.indexOfFirst { it == '@' } val underscoreIndex = input.indexOfFirst { it == '_' } if(userType == 2){ return input.substring(0,atRateIndex) }else{ return input.substring(underscoreIndex+1,atRateIndex) } } fun getUsernameFromEmail(userType:Int,input: String): Either<Exception, String> { val atRateIndex = input.indexOfFirst { it == '@' } if (atRateIndex == -1) { return Either.Left(Exception("Email not valid")) } if(userType == 2){ return Either.Right(input.substring(0,atRateIndex)) }else{ val underscoreIndex = input.indexOfFirst { it == '_' } if(underscoreIndex == -1){ return Either.Left(Exception("Username not valid")) } return Either.Right(input.substring(underscoreIndex+1,atRateIndex)) } } fun isValidStudentEmail(email: String): Boolean { val regex = Regex("""^[a-zA-Z]+_[a-zA-Z][0-9]{6}[a-zA-Z]{2}@nitc\.ac\.in$""") return regex.matches(email) } fun isValidMentorUsername(username: String): Either<Exception,Boolean> { if (!username.contains("_") || !username.endsWith("@nitc.ac.in")) { Either.Left(Exception("Username must contain '_' and end with '@nitc.ac.in'")) } val parts = username.split("_") if (parts.size != 3) { Either.Left(Exception("Username must have two underscores separating three parts")) } val name1 = parts[0] val specialty = parts[1] val optionalNumber = parts[2] if (!name1.matches("[a-zA-Z]+".toRegex())) { Either.Left(Exception("First name part must contain only letters")) } if (!specialty.matches("[a-zA-Z]+".toRegex())) { Either.Left(Exception("Specialty part must contain only letters")) } val optionalNumberRegex = "[0-9]*".toRegex() // Matches zero or more digits if (!optionalNumber.matches(optionalNumberRegex)) { Either.Left(Exception("Optional number part must be digits or empty")) } return Either.Right(true) } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/util/PathUtils.kt
2753879562
package com.nitc.projectsgc.composable import android.app.Application import android.content.Context import com.nitc.projectsgc.MyApplication import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object ApplicationModule { @Provides @Singleton fun provideContext(application:Application):Context{ return application.applicationContext } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/ApplicationModule.kt
2348265435
package com.nitc.projectsgc.composable.student.viewmodels import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import arrow.core.Either import com.nitc.projectsgc.composable.student.repo.BookingRepo import com.nitc.projectsgc.composable.student.repo.StudentRepo import com.nitc.projectsgc.models.Appointment import com.nitc.projectsgc.models.Student import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject @HiltViewModel class StudentViewModel @Inject constructor( private val studentRepo: StudentRepo, private val bookingRepo: BookingRepo ):ViewModel() { private val _profile = MutableStateFlow<Either<String, Student>?>(null) val profile:StateFlow<Either<String,Student>?> = _profile.asStateFlow() private val _appointments = MutableStateFlow<Either<String,List<Appointment>>?>(null) val appointments: StateFlow<Either<String, List<Appointment>>?> = _appointments.asStateFlow() fun getProfile(rollNo:String){ viewModelScope.launch { _profile.value = studentRepo.getStudent(rollNo) } } suspend fun cancelAppointment(appointment: Appointment):Boolean{ return withContext(Dispatchers.Main){ bookingRepo.cancelAppointment(appointment) } } suspend fun updateProfile(student: Student, oldPassword: String): Boolean { val updateSuccess = withContext(Dispatchers.Main) { Log.d("updateProfile", "In adminViewmodel") if (studentRepo.updateProfile(student, oldPassword)) { Log.d("updateProfile", "Old password = $oldPassword") Log.d("updateProfile", "New password = ${student.password}") _profile.value = Either.Right(student) true } else false } return updateSuccess } fun deleteProfileValue(){ _profile.value = null } fun deleteAppointmentsValue(){ _appointments.value = null } fun getAppointments(rollNo:String){ viewModelScope.launch { // deleteAppointmentsValue() _appointments.value = bookingRepo.getAppointments(rollNo) } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/student/viewmodels/StudentViewModel.kt
3733983271
package com.nitc.projectsgc.composable.student.viewmodels import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import arrow.core.Either import com.nitc.projectsgc.composable.student.repo.BookingRepo import com.nitc.projectsgc.models.Appointment import com.nitc.projectsgc.models.Mentor import com.nitc.projectsgc.models.Student import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject @HiltViewModel class BookingViewModel @Inject constructor( private val bookingRepo: BookingRepo ) : ViewModel() { private val _mentorTypes = MutableStateFlow<Either<String, List<String>>?>(null) val mentorTypes: StateFlow<Either<String, List<String>>?> = _mentorTypes.asStateFlow() fun getMentorTypes() { viewModelScope.launch { _mentorTypes.value = bookingRepo.getMentorTypes() } } private val _mentors = MutableStateFlow<Either<String, List<Mentor>>?>(null) val mentors: StateFlow<Either<String, List<Mentor>>?> = _mentors.asStateFlow() fun getMentors(mentorType: String) { viewModelScope.launch { // _mentors.value = null _mentors.value = bookingRepo.getMentorNames(mentorType) } } private val _availableTimeSlots = MutableStateFlow<Either<String, List<String>>?>(null) val availableTimeSlots: StateFlow<Either<String, List<String>>?> = _availableTimeSlots.asStateFlow() fun getAvailableTimeSlots( mentorType: String, mentorID: String, dateChosen: String ) { viewModelScope.launch { _availableTimeSlots.value = bookingRepo.getAvailableTimeSlots( mentorType, mentorID, dateChosen ) } } suspend fun bookAppointment(appointment: Appointment): Boolean { val booked = withContext(Dispatchers.Main) { bookingRepo.bookAppointment(appointment) } return booked } suspend fun rescheduleAppointment(oldAppointment: Appointment,appointment: Appointment): Boolean { val rescheduled = withContext(Dispatchers.Main) { bookingRepo.rescheduleAppointment(oldAppointment,appointment) } return rescheduled } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/student/viewmodels/BookingViewModel.kt
3055389215
package com.nitc.projectsgc.composable.student import com.nitc.projectsgc.composable.student.repo.BookingRepo import com.nitc.projectsgc.composable.student.repo.StudentRepo import com.nitc.projectsgc.composable.student.viewmodels.StudentViewModel import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ViewModelComponent import dagger.hilt.android.scopes.ViewModelScoped @Module @InstallIn(ViewModelComponent::class) object StudentModule { @Provides @ViewModelScoped fun provideStudentRepo():StudentRepo{ return StudentRepo() } @Provides @ViewModelScoped fun provideBookingRepo(): BookingRepo { return BookingRepo() } @Provides @ViewModelScoped fun provideStudentViewModel(studentRepo: StudentRepo,bookingRepo: BookingRepo): StudentViewModel { return StudentViewModel(studentRepo,bookingRepo) } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/student/StudentModule.kt
2873213377
package com.nitc.projectsgc.composable.student.screens import android.content.Context import android.widget.Toast import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.colorResource import androidx.compose.ui.unit.dp import arrow.core.Either import com.nitc.projectsgc.R import com.nitc.projectsgc.composable.components.BasicSubHeadingButton import com.nitc.projectsgc.composable.components.CardInputFieldWithValue import com.nitc.projectsgc.composable.components.DateDialog import com.nitc.projectsgc.composable.components.SubHeadingText import com.nitc.projectsgc.composable.student.viewmodels.BookingViewModel import com.nitc.projectsgc.models.Appointment import com.nitc.projectsgc.models.Mentor @Composable fun BookingScreen( rollNo: String, bookingViewModel: BookingViewModel, bookCallback: () -> Unit ) { val appointmentState = remember { mutableStateOf(Appointment(studentID = rollNo)) } val bookingContext = LocalContext.current val mentorTypesDropdownState = remember { mutableStateOf(false) } val mentorTypesState = remember { mutableStateOf<List<String>?>(null) } LaunchedEffect(Unit) { bookingViewModel.getMentorTypes() bookingViewModel.mentorTypes.collect { mentorTypesEither -> when (mentorTypesEither) { is Either.Left -> { showToast(mentorTypesEither.value, bookingContext) } is Either.Right -> { mentorTypesState.value = mentorTypesEither.value if (mentorTypesState.value.isNullOrEmpty()) { showToast("No mentor types found", bookingContext) } } null -> { // showToast("Error in getting mentor types",bookingContext) } } } } val mentorsState = remember { mutableStateOf<List<Mentor>?>(null) } val mentorsDropdownState = remember { mutableStateOf(false) } val dateState = remember { mutableStateOf(false) } val timeSlotsDropdownState = remember { mutableStateOf(false) } val timeSlotsState = remember { mutableStateOf(emptyList<String>()) } val bookAppointmentState = remember { mutableStateOf(false) } LaunchedEffect(bookAppointmentState.value) { if (bookAppointmentState.value) { val booked = bookingViewModel.bookAppointment(appointmentState.value) if (booked) { showToast("Booked your appointment", bookingContext) bookCallback() } else { showToast("Error in booking your appointment", bookingContext) } } } // val mentorsEitherState by bookingViewModel.mentors.collectAsState() val getMentorState = remember { mutableStateOf(false) } val getTimeSlotsState = remember { mutableStateOf(false) } val mentorsEitherState by bookingViewModel.mentors.collectAsState() LaunchedEffect(getMentorState.value) { if (getMentorState.value) { bookingViewModel.getMentors(appointmentState.value.mentorType) } } LaunchedEffect(key1 = mentorsEitherState) { // bookingViewModel.mentors.collect { mentorsEither -> if (getMentorState.value) { getMentorState.value = false when (val mentorsEither = mentorsEitherState) { // Log.d("getMentorNames", "In launched effect") // if (appointment.value.mentorType.isNotEmpty()) { // when (mentorsEither) { is Either.Left -> { Toast.makeText(bookingContext, mentorsEither.value, Toast.LENGTH_LONG) .show() } is Either.Right -> { mentorsState.value = mentorsEither.value mentorsDropdownState.value = true } null -> { Toast.makeText( bookingContext, "Error in getting mentors", Toast.LENGTH_LONG ) .show() } } } } val timeSlotsEitherState by bookingViewModel.availableTimeSlots.collectAsState() LaunchedEffect(getTimeSlotsState.value) { if (getTimeSlotsState.value) { bookingViewModel.getAvailableTimeSlots( appointmentState.value.mentorType, appointmentState.value.mentorID, appointmentState.value.date ) } } LaunchedEffect(key1 = timeSlotsEitherState) { if (getTimeSlotsState.value) { getTimeSlotsState.value = false when (val timeSlotsEither = timeSlotsEitherState) { is Either.Right -> { timeSlotsState.value = timeSlotsEither.value timeSlotsDropdownState.value = true } is Either.Left -> { showToast( timeSlotsEither.value, bookingContext ) } null -> { showToast( "Error in getting time slots", bookingContext, ) } } } } LazyColumn( modifier = Modifier .fillMaxSize(), verticalArrangement = Arrangement.spacedBy(30.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { item { Box { BasicSubHeadingButton( text = appointmentState.value.mentorType.ifEmpty { "Select Mentor Type" }, tc = Color.White, colors = ButtonDefaults.buttonColors( containerColor = colorResource(id = R.color.navy_blue) ), clickCallback = { mentorTypesDropdownState.value = true }, modifier = Modifier ) DropdownMenu(expanded = mentorTypesDropdownState.value, onDismissRequest = { mentorTypesDropdownState.value = false }) { if (!mentorTypesState.value.isNullOrEmpty()) { mentorTypesState.value!!.forEachIndexed { index, mentorType -> DropdownMenuItem(text = { Text(text = mentorType, color = Color.Black) }, onClick = { appointmentState.value = appointmentState.value.copy(mentorType = mentorType) mentorTypesDropdownState.value = false }) } } } } } item { Box { BasicSubHeadingButton( clickCallback = { if (appointmentState.value.mentorType.isNotEmpty()) { getMentorState.value = true // bookingViewModel.getMentors( // appointment.value.mentorType // ) mentorsDropdownState.value = true } else showToast("Choose a mentorship type first", bookingContext) }, text = appointmentState.value.mentorName.ifEmpty { "Select Mentor" }, modifier = Modifier, tc = Color.Black, colors = ButtonDefaults.buttonColors(containerColor = colorResource(id = R.color.light_gray)) ) // if(!mentorsState.value.isNullOrEmpty()) { DropdownMenu(expanded = mentorsDropdownState.value, onDismissRequest = { mentorsDropdownState.value = false }) { if (!getMentorState.value && !mentorsState.value.isNullOrEmpty()) { mentorsState.value!!.forEachIndexed { index, mentor -> DropdownMenuItem(text = { Text(text = mentor.name, color = Color.Black) }, onClick = { appointmentState.value = appointmentState.value.copy( mentorID = mentor.userName, mentorName = mentor.name ) mentorsDropdownState.value = false }) } } // } } } } item { Box { BasicSubHeadingButton( text = appointmentState.value.date.ifEmpty { "Select Date" }, colors = ButtonDefaults.buttonColors(), tc = Color.White, modifier = Modifier ) { dateState.value = true } if (dateState.value) { DateDialog( heading = "Book for date", isVisible = dateState.value ) { dateChosen -> appointmentState.value = appointmentState.value.copy(date = dateChosen) dateState.value = false } } } } item { Box(modifier = Modifier) { BasicSubHeadingButton( text = appointmentState.value.timeSlot.ifEmpty { "Select Time Slot" }, colors = ButtonDefaults.buttonColors(), tc = Color.White, modifier = Modifier ) { if (appointmentState.value.mentorID.isNotEmpty() && appointmentState.value.date.isNotEmpty() && appointmentState.value.mentorType.isNotEmpty()) { getTimeSlotsState.value = true timeSlotsDropdownState.value = true } else { showToast("Choose mentorship type and mentor first", bookingContext) } } if (!getTimeSlotsState.value && timeSlotsState.value.isNotEmpty()) { DropdownMenu(expanded = timeSlotsDropdownState.value, onDismissRequest = { timeSlotsDropdownState.value = false }) { if (timeSlotsState.value.isNotEmpty()) { timeSlotsState.value.forEachIndexed { index, timeSlot -> DropdownMenuItem(text = { SubHeadingText( text = timeSlot, fontColor = Color.Black, modifier = Modifier ) }, onClick = { appointmentState.value = appointmentState.value.copy(timeSlot = timeSlot) timeSlotsDropdownState.value = false }) } } else showToast( "No Time slots available for the given date", bookingContext ) } } } } item { CardInputFieldWithValue( hint = "Problem Description", text = "", isPassword = false, modifier = Modifier.fillMaxWidth(0.7F) ) { problemDesc -> appointmentState.value = appointmentState.value.copy(problemDescription = problemDesc) } } item { BasicSubHeadingButton( text = "Submit", colors = ButtonDefaults.buttonColors( containerColor = colorResource(id = R.color.navy_blue) ), tc = Color.White, modifier = Modifier ) { if (appointmentState.value.problemDescription.isEmpty()) { Toast.makeText( bookingContext, "Write your problem description", Toast.LENGTH_LONG ) .show() } else { appointmentState.value = appointmentState.value.copy(status = "Booked") bookAppointmentState.value = true } } Spacer(modifier = Modifier.size(100.dp)) } } } fun showToast(message: String, context: Context) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show() }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/student/screens/BookingScreen.kt
1663157497
package com.nitc.projectsgc.composable.student.screens import android.util.Log import android.widget.Toast import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.navigation.NavController import arrow.core.Either import com.nitc.projectsgc.composable.components.TabLayout import com.nitc.projectsgc.composable.login.LoginViewModel import com.nitc.projectsgc.composable.student.viewmodels.BookingViewModel import com.nitc.projectsgc.composable.student.viewmodels.StudentViewModel import com.nitc.projectsgc.models.Student import kotlinx.coroutines.launch @Composable fun StudentDashboardScreen( rollNo: String, studentViewModel: StudentViewModel, bookingViewModel:BookingViewModel, goToBooking:()->Unit ) { Column( modifier = Modifier.fillMaxSize() ) { val selectedTabIndex = remember { mutableIntStateOf(0) } TabLayout( tabs = listOf("Appointments", "Profile"), fontColor = Color.Black, bg = Color.White, ) { pageIndex -> when (pageIndex) { 0 -> { StudentAppointmentsScreen( rollNo = rollNo, studentViewModel = studentViewModel, bookingViewModel = bookingViewModel, bookCallback = { goToBooking() } ) } 1 -> { GetProfile(rollNo, studentViewModel) } } } } } @Composable fun GetProfile(rollNo: String, studentViewModel: StudentViewModel) { Log.d("studentDashboard", "rollNo is : $rollNo") studentViewModel.getProfile(rollNo) val screenContext = LocalContext.current val updatingState = remember { mutableStateOf(false) } val studentState = remember { mutableStateOf<Student?>(null) } val studentEither = studentViewModel.profile.collectAsState().value var oldPassword = "" val coroutineScope = rememberCoroutineScope() when (studentEither) { is Either.Left -> { Toast.makeText( LocalContext.current, "Error in getting student : ${studentEither.value}", Toast.LENGTH_LONG ).show() } is Either.Right -> { Log.d("viewStudent", "no error message") studentState.value = studentEither.value oldPassword = studentEither.value.password UpdateStudentScreen(studentEither.value) { updatedStudent -> Log.d("updateStudent", "these are new values ; $updatedStudent") coroutineScope.launch { Log.d("updateStudent", "Now updated : $updatedStudent") val updateSuccess = studentViewModel.updateProfile(updatedStudent, oldPassword) if (updateSuccess) { studentState.value = updatedStudent Toast.makeText(screenContext, "Updated", Toast.LENGTH_LONG).show() } else { Toast.makeText( screenContext, "Error in updating student", Toast.LENGTH_LONG ).show() } updatingState.value = false } } } null -> { Log.d("viewStudent", "Student either is null") } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/student/screens/StudentDashboardScreen.kt
817231401
package com.nitc.projectsgc.composable.student.screens import android.util.Log import android.widget.Toast import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.DateRange import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.colorResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import arrow.core.Either import com.nitc.projectsgc.R import com.nitc.projectsgc.composable.components.RescheduleDialog import com.nitc.projectsgc.composable.student.components.BookedAppointmentCard import com.nitc.projectsgc.composable.student.viewmodels.BookingViewModel import com.nitc.projectsgc.composable.student.viewmodels.StudentViewModel import com.nitc.projectsgc.models.Appointment @Composable fun StudentAppointmentsScreen( rollNo: String, studentViewModel: StudentViewModel, bookingViewModel: BookingViewModel, bookCallback: () -> Unit ) { val myContext = LocalContext.current val isLoading = remember { mutableStateOf(true) } LaunchedEffect(Unit) { studentViewModel.getAppointments(rollNo) } val reschedulingState = remember { mutableStateOf<Appointment?>(null) } val coroutineScope = rememberCoroutineScope() val appointmentsEitherState by studentViewModel.appointments.collectAsState() val appointmentsState = remember { mutableStateOf(listOf<Appointment>()) } val cancelState = remember { mutableStateOf<Appointment?>(null) } LaunchedEffect(cancelState.value) { if (cancelState.value != null) { val cancelled = studentViewModel.cancelAppointment(cancelState.value!!) if (cancelled) { showToast("Cancelled appointment", myContext) } else { showToast("Could not cancel the appointment", myContext) } cancelState.value = null studentViewModel.getAppointments(rollNo) } } LaunchedEffect(appointmentsEitherState) { Log.d("studentDashboard", "apointments changed") when (val appointmentsEither = appointmentsEitherState) { is Either.Right -> { Log.d("studentDashboard", "apointments state something") if (appointmentsEither.value.isEmpty()) { Toast.makeText( myContext, "No appointments found", Toast.LENGTH_SHORT ).show() } else { appointmentsState.value = appointmentsEither.value Log.d("studentDashboard", "Appointments got") } isLoading.value = false } is Either.Left -> { Toast.makeText( myContext, (appointmentsEither.value), Toast.LENGTH_SHORT ).show() isLoading.value = false } null -> { isLoading.value = false // Toast.makeText( // myContext, // "Error in accessing appointments", // Toast.LENGTH_SHORT // ).show() } } } if (reschedulingState.value != null) { RescheduleDialog( oldAppointment = reschedulingState.value!!, onDismiss = { reschedulingState.value = null studentViewModel.getAppointments(rollNo) }, bookingViewModel = bookingViewModel ) } else { Box(modifier = Modifier.fillMaxSize()) { if (isLoading.value) CircularProgressIndicator( Modifier .fillMaxSize(0.6F) .align(Alignment.Center) ) LazyColumn( modifier = Modifier.fillMaxSize() ) { items( count = appointmentsState.value.size, itemContent = { index -> BookedAppointmentCard( appointment = appointmentsState.value[index], rescheduleCallback = { reschedulingState.value = appointmentsState.value[index] }, cancelCallback = { cancelState.value = appointmentsState.value[index] }) }) } FloatingActionButton( onClick = { bookCallback() }, shape = RoundedCornerShape(25), containerColor = colorResource(id = R.color.navy_blue), modifier = Modifier .align(Alignment.BottomEnd) .padding(10.dp) .clip(RoundedCornerShape(25)) .background(colorResource(id = R.color.navy_blue)) ) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .background(Color.Transparent) .padding(7.dp), verticalArrangement = Arrangement.SpaceBetween ) { Icon(Icons.Filled.DateRange, "Book Appointment", tint = Color.White) Spacer(modifier = Modifier.size(10.dp)) Text( text = "Book\nAppointment", textAlign = TextAlign.Center, color = Color.White, modifier = Modifier.padding(horizontal = 7.dp) ) } } } } } @Preview @Composable fun StudentAppointmentsPreview() { }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/student/screens/StudentAppointmentsScreen.kt
3050228512
package com.nitc.projectsgc.composable.student.screens import android.util.Log import android.widget.Toast import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.ButtonDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.colorResource import androidx.compose.ui.unit.dp import arrow.core.Either import com.nitc.projectsgc.R import com.nitc.projectsgc.composable.admin.viewmodels.AdminViewModel import com.nitc.projectsgc.composable.components.BasicButton import com.nitc.projectsgc.composable.components.BasicSubHeadingButton import com.nitc.projectsgc.composable.components.CardInputFieldWithValue import com.nitc.projectsgc.composable.components.DateDialog import com.nitc.projectsgc.composable.components.SimpleToast import com.nitc.projectsgc.composable.components.SubHeadingText import com.nitc.projectsgc.composable.util.PathUtils import com.nitc.projectsgc.models.Student import kotlinx.coroutines.launch import java.text.SimpleDateFormat import java.util.Date import java.util.Locale @Composable fun ViewStudentScreen( rollNo: String, adminViewModel: AdminViewModel ) { val studentState = remember { mutableStateOf<Student?>(null) } if (rollNo != "no") { adminViewModel.getStudent(rollNo) } else { adminViewModel.deleteStudentValue() studentState.value = Student() } val screenContext = LocalContext.current val updatingState = remember { mutableStateOf(false) } val studentEither = adminViewModel.student.collectAsState().value var oldPassword = "" val coroutineScope = rememberCoroutineScope() when (studentEither) { is Either.Left -> { Toast.makeText( LocalContext.current, "Error in getting student : ${studentEither.value}", Toast.LENGTH_LONG ).show() } is Either.Right -> { Log.d("viewStudent", "no error message") studentState.value = studentEither.value oldPassword = studentEither.value.password UpdateStudentScreen(studentEither.value) { updatedStudent -> Log.d("updateStudent", "these are new values ; $updatedStudent") coroutineScope.launch { Log.d("updateStudent", "Now updated : $updatedStudent") val updateSuccess = adminViewModel.updateStudent(updatedStudent, oldPassword) if (updateSuccess) { studentState.value = updatedStudent Toast.makeText(screenContext, "Updated Student", Toast.LENGTH_LONG).show() } else { Toast.makeText( screenContext, "Error in updating student", Toast.LENGTH_LONG ).show() } updatingState.value = false } } } null -> { Log.d("viewStudent", "Student either is null") UpdateStudentScreen( Student( dateOfBirth = SimpleDateFormat( "dd-MM-yyyy", Locale.getDefault() ).format(Date()) ) ) { newStudent -> coroutineScope.launch { val addedSuccessEither = adminViewModel.addStudent(newStudent) when (addedSuccessEither) { is Either.Left -> { Toast.makeText( screenContext, addedSuccessEither.value, Toast.LENGTH_LONG ).show() } is Either.Right -> { Toast.makeText(screenContext, "Added Student", Toast.LENGTH_LONG) .show() studentState.value = newStudent } } updatingState.value = false } } } } // } @Composable fun UpdateStudentScreen(studentFound: Student, onUpdate: (student: Student) -> Unit) { val studentState = remember { mutableStateOf(studentFound) } val dobDialogState = remember { mutableStateOf(false) } val screenContext = LocalContext.current // val updateSuccess by adminViewModel.updateSuccess.collectAsState() val oldPassword = studentState.value.password // Log.d("updateStudent","Old password = $oldPassword") if (dobDialogState.value) { DateDialog(heading = "Date of Birth", isVisible = dobDialogState.value) { dateChosen -> studentState.value = studentState.value.copy(dateOfBirth = dateChosen) dobDialogState.value = false } } LazyColumn( modifier = Modifier .fillMaxSize() .padding(top = 30.dp), reverseLayout = false, horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(20.dp) ) { items(1) { index -> CardInputFieldWithValue( hint = "Name", text = studentState.value!!.name, isPassword = false, modifier = Modifier.fillMaxWidth(0.75F) ) { newName -> studentState.value = studentState.value.copy(name = newName) } Spacer(modifier = Modifier.size(20.dp)) BasicSubHeadingButton( text = studentState.value.dateOfBirth, colors = ButtonDefaults.buttonColors( containerColor = colorResource(id = R.color.light_gray) ), tc = Color.Black, modifier = Modifier ) { dobDialogState.value = true } Spacer(modifier = Modifier.size(20.dp)) CardInputFieldWithValue( hint = "Email", text = studentState.value!!.emailId, isPassword = false, modifier = Modifier.fillMaxWidth(0.75F) ) { emailInput -> studentState.value = studentState.value!!.copy(emailId = emailInput) } Spacer(modifier = Modifier.size(20.dp)) CardInputFieldWithValue( hint = "Gender", text = studentState.value!!.gender, isPassword = false, modifier = Modifier.fillMaxWidth(0.75F) ) { newGender -> studentState.value = studentState.value!!.copy(gender = newGender) } Spacer(modifier = Modifier.size(20.dp)) CardInputFieldWithValue( hint = "Phone Number", text = studentState.value!!.phoneNumber, isPassword = false, modifier = Modifier.fillMaxWidth(0.75F) ) { newPhone -> studentState.value = studentState.value!!.copy(phoneNumber = newPhone) } Spacer(modifier = Modifier.size(20.dp)) CardInputFieldWithValue( hint = "Password", text = studentState.value!!.password, isPassword = false, modifier = Modifier.fillMaxWidth(0.75F) ) { newPassword -> studentState.value = studentState.value!!.copy(password = newPassword) Log.d("updateStudent", "student value now is ${studentState.value.toString()}") } Spacer(modifier = Modifier.size(40.dp)) BasicButton( text = if (studentFound.name.isEmpty()) "Add" else "Update", colors = ButtonDefaults.buttonColors(containerColor = colorResource(id = R.color.navy_blue)), modifier = Modifier.padding(20.dp), tc = Color.White ) { Log.d("updateStudent", "Now updated : ${studentState.value}") // updatingState.value = true when (val rollNoEither = PathUtils.getUsernameFromEmail(1, studentState.value.emailId)) { is Either.Right -> { studentState.value = studentState.value.copy(rollNo = rollNoEither.value) onUpdate(studentState.value) } is Either.Left -> { Toast.makeText(screenContext, "Enter valid Email", Toast.LENGTH_LONG).show() } } } } } } // //@Preview(showSystemUi = true, showBackground = true) //@Composable //fun ViewStudentPreview() { // ViewStudentScreen(rollNo = "m210704ca") //}
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/student/screens/ViewStudentScreen.kt
3242542277
package com.nitc.projectsgc.composable.student.components import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.nitc.projectsgc.R import com.nitc.projectsgc.composable.components.CardFieldWithValue import com.nitc.projectsgc.composable.components.CardInputFieldWithValue import com.nitc.projectsgc.composable.components.ClickableCard import com.nitc.projectsgc.composable.components.HeadingText import com.nitc.projectsgc.composable.components.NormalText import com.nitc.projectsgc.composable.components.SubHeadingText import com.nitc.projectsgc.models.Appointment @Preview @Composable fun BookedAppointmentCardPreview() { BookedAppointmentCard( appointment = Appointment( date = "24/11/2111", mentorID = "sakshi_health_2", mentorName = "Sakshi", studentID = "prashant_m210704ca", studentName = "Prashant", status = "Booked", remarks = "ahsdfl haskldfh lkashdfl ahskldfhasl hdflkahsd lfkjhasaskhfd lksahdflk ahsl", rescheduled = false, timeSlot = "4-5", mentorType = "Success" ), {}, {} ) } @OptIn(ExperimentalFoundationApi::class) @Composable fun BookedAppointmentCard( appointment: Appointment, rescheduleCallback: () -> Unit, cancelCallback: () -> Unit ) { val optionsMenuState = remember { mutableStateOf(false) } // Surface( // modifier = Modifier // .fillMaxWidth() // .padding(7.dp) // .clip( // RoundedCornerShape(15) // ) Card( modifier = Modifier .padding(5.dp) .combinedClickable( onClick = { }, onLongClick = { optionsMenuState.value = true } ) .fillMaxWidth(), shape = RoundedCornerShape(10), colors = CardDefaults.cardColors( containerColor = colorResource(id = R.color.lavender) ) ) { Box( modifier = Modifier .fillMaxWidth() .padding(5.dp) .clip( RoundedCornerShape(15) ) .background(colorResource(id = R.color.lavender)) ) { Column( modifier = Modifier .background(colorResource(id = R.color.lavender)), horizontalAlignment = Alignment.CenterHorizontally ) { Row( modifier = Modifier .fillMaxWidth() .height(130.dp) .padding(top = 5.dp) .background(Color.Transparent), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceEvenly ) { Image( modifier = Modifier .fillMaxHeight(0.65F) .clip(RoundedCornerShape(50)), painter = painterResource(id = R.drawable.boy_face), contentDescription = "Mentor image" ) Spacer(modifier = Modifier.size(15.dp)) Column( modifier = Modifier.fillMaxHeight(), verticalArrangement = Arrangement.SpaceEvenly, ) { // Spacer(modifier = Modifier.size(10.dp)) NormalText( text = appointment.mentorName, fontColor = Color.Black, modifier = Modifier ) // Spacer(modifier = Modifier.size(15.dp)) Row( verticalAlignment = Alignment.CenterVertically ) { NormalText( text = "Time : ", fontColor = Color.Black, modifier = Modifier ) Spacer(modifier = Modifier.size(5.dp)) NormalText( text = appointment.timeSlot, fontColor = Color.Black, modifier = Modifier ) } } Spacer(modifier = Modifier.size(15.dp)) Column( modifier = Modifier.fillMaxHeight(), verticalArrangement = Arrangement.SpaceEvenly, horizontalAlignment = Alignment.CenterHorizontally ) { // Spacer(modifier = Modifier.size(10.dp)) Text( text = appointment.date, color = Color.Black, modifier = Modifier ) // Spacer(modifier = Modifier.size(15.dp)) Row( verticalAlignment = Alignment.CenterVertically ) { NormalText( text = "Type : ", fontColor = Color.Black, modifier = Modifier ) Spacer(modifier = Modifier.size(5.dp)) Text( text = appointment.mentorType, color = Color.Black, modifier = Modifier ) } } } Card( modifier = Modifier.padding(5.dp), colors = CardDefaults.cardColors( containerColor = colorResource(id = R.color.ivory) ), elevation = CardDefaults.cardElevation(2.dp), shape = RoundedCornerShape(40), ) { NormalText( text = appointment.status, fontColor = Color.Black, modifier = Modifier .padding(20.dp) .align(Alignment.CenterHorizontally) ) } if (appointment.completed) { CardFieldWithValue( hint = "Remarks", text = appointment.remarks, modifier = Modifier .padding(horizontal = 10.dp) .fillMaxWidth(0.85F) ) } } if (!appointment.completed && !appointment.cancelled) { DropdownMenu( modifier = Modifier .align(Alignment.TopCenter) .background(Color.White), expanded = optionsMenuState.value, onDismissRequest = { optionsMenuState.value = false }) { DropdownMenuItem(text = { NormalText( text = "Reschedule", fontColor = Color.Black, modifier = Modifier ) }, onClick = { rescheduleCallback() optionsMenuState.value = false } ) DropdownMenuItem(text = { NormalText(text = "Cancel", fontColor = Color.Black, modifier = Modifier) }, onClick = { cancelCallback() optionsMenuState.value = false } ) } } } } // .height(intrinsicSize = IntrinsicSize.Min) // .background(colorResource(id = R.color.lavender)) // ) { }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/student/components/BookedAppointmentCard.kt
3170536188
package com.nitc.projectsgc.composable.student.repo import android.app.AlertDialog import android.util.Log import androidx.compose.ui.res.stringArrayResource import androidx.core.content.ContextCompat import androidx.lifecycle.MutableLiveData import arrow.core.Either import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import com.nitc.projectsgc.R import com.nitc.projectsgc.models.Appointment import com.nitc.projectsgc.models.Mentor import java.time.LocalDate import java.time.format.DateTimeFormatter import javax.inject.Inject import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine class BookingRepo @Inject constructor() { suspend fun getAppointments(rollNo: String): Either<String, List<Appointment>>? { return suspendCoroutine { continuation -> var isResumed = false var appointments = arrayListOf<Appointment>() var database = FirebaseDatabase.getInstance() var reference = database.reference.child("students") Log.d("studentDashboard", "outside snapshot") reference.child("$rollNo") .addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { Log.d("studentDashboard", "In snapshot") if (snapshot.hasChild("appointments")) { for (ds in snapshot.child("appointments").children) { try { val appointment = ds.getValue(Appointment::class.java) appointments.add(appointment!!) } catch (excCasting: Exception) { Log.d( "getAppointments", "Error in casting appointment : $excCasting" ) continue } } if (!isResumed) { isResumed = true continuation.resume(Either.Right(appointments)) } } else { Log.d("studentDashboard", "No appointment found here") if (!isResumed) { isResumed = true continuation.resume(Either.Right(appointments)) } } } override fun onCancelled(error: DatabaseError) { if (!isResumed) { isResumed = true Log.d("getAppointments", "Error in database : $error") continuation.resume(Either.Left("Error in database : $error")) } } }) } } suspend fun getCompletedAppointments(rollNo: String): ArrayList<Appointment>? { return suspendCoroutine { continuation -> var completedLive = MutableLiveData<ArrayList<Appointment>>(null) var appointments = arrayListOf<Appointment>() var database = FirebaseDatabase.getInstance() var studentReference = database.reference.child("students") studentReference.child(rollNo) .addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { for (ds in snapshot.child("appointments").children) { var appointment = ds.getValue(Appointment::class.java) if (appointment != null) { if (appointment.completed) appointments.add(appointment) } } val formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy") val sortedAppointments = appointments.sortedBy { LocalDate.parse(it.date, formatter) } .toCollection(ArrayList<Appointment>()) continuation.resume(sortedAppointments) } override fun onCancelled(error: DatabaseError) { continuation.resume(null) } }) } } suspend fun cancelAppointment(appointment: Appointment): Boolean { return suspendCoroutine { continuation -> appointment.cancelled = true appointment.status = "Cancelled by Student" var isResumed = false var database = FirebaseDatabase.getInstance() var studentReference = database.reference .child("students") var typeReference = database.reference .child("types") studentReference.child(appointment.studentID + "/appointments") .child(appointment.id.toString()).setValue(appointment) .addOnCompleteListener { studentTask -> if (studentTask.isSuccessful) { typeReference.child(appointment.mentorType.toString() + "/${appointment.mentorID}/appointments/${appointment.date}/${appointment.timeSlot}") .setValue(appointment).addOnCompleteListener { mentorTask -> if (mentorTask.isSuccessful) if (!isResumed) continuation.resume( true ) else if (!isResumed) continuation.resume(false) } } else { if (!isResumed) continuation.resume(false) } } } } suspend fun getMentorNames(mentorType: String): Either<String, List<Mentor>>? { return suspendCoroutine { continuation -> var isResumed = false var mentors = arrayListOf<Mentor>() var database: FirebaseDatabase = FirebaseDatabase.getInstance() var reference: DatabaseReference = database.reference.child("types") reference.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { var mentorsSnapshot = snapshot.child(mentorType).children for (mentor in mentorsSnapshot) { try { mentors.add(mentor.getValue(Mentor::class.java)!!) } catch (excCasting: Exception) { Log.d("getMentorNames", "Error in casting mentor : $excCasting") continue } } Log.d("getMentorNames", "Mentor names found : $mentors") if (!isResumed) { continuation.resume(Either.Right(mentors)) isResumed = true } } override fun onCancelled(error: DatabaseError) { if (!isResumed) { continuation.resume(Either.Left("Error in getting mentors : $error")) isResumed = true } } }) } } suspend fun getMentorTypes(): Either<String, ArrayList<String>>? { return suspendCoroutine { continuation -> // var mentorTypeLive = MutableLiveData<ArrayList<String>>(null) var isResumed = false val database: FirebaseDatabase = FirebaseDatabase.getInstance() val reference: DatabaseReference = database.reference.child("types") var mentorTypes = arrayListOf<String>() reference.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { for (typeChild in snapshot.children) { mentorTypes.add(typeChild.key.toString()) } if (!isResumed) { continuation.resume(Either.Right(mentorTypes)) isResumed = true } } override fun onCancelled(error: DatabaseError) { if (!isResumed) { continuation.resume(Either.Left("Error in getting mentor types : $error")) isResumed = true } } }) } } suspend fun bookAppointment(appointment: Appointment): Boolean { return suspendCoroutine { continuation -> var isResumed = false val database: FirebaseDatabase = FirebaseDatabase.getInstance() var reference: DatabaseReference = database.reference var mentorReference = reference.child("types/${appointment.mentorType}/${appointment.mentorID}/appointments/${appointment.date}/${appointment.timeSlot}") var appointmentID = mentorReference.push().key.toString() appointment.id = appointmentID mentorReference.setValue(appointment).addOnCompleteListener { mentorTask -> if (mentorTask.isSuccessful) { reference.child("students/${appointment.studentID}/appointments/$appointmentID") .setValue(appointment).addOnCompleteListener { studentTask -> if (studentTask.isSuccessful) { if (!isResumed) continuation.resume(true) } else { mentorReference.child(appointment.timeSlot.toString()) .removeValue() if (!isResumed) continuation.resume(false) } } } else if (!isResumed) continuation.resume(false) } } } suspend fun getAvailableTimeSlots( mentorTypeSelected: String, mentorID: String, selectedDate: String ): Either<String, List<String>>? { return suspendCoroutine { continuation -> var isResumed = false var totalTimeSlots = arrayListOf<String>("9-10", "10-11", "11-12", "1-2", "2-3", "3-4", "4-5") var mentorTimeSlots = arrayListOf<String>() val reference = FirebaseDatabase.getInstance().reference.child("types") reference.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { var dateRef = "$mentorTypeSelected/$mentorID/appointments/$selectedDate" if (snapshot.hasChild(dateRef)) { Log.d("getSlots", "dateref : $dateRef") for (timeSlots in snapshot.child(dateRef).children) { mentorTimeSlots.add(timeSlots.key.toString()) totalTimeSlots.removeIf { it == timeSlots.key.toString() } Log.d("getSlots", timeSlots.key.toString()) } // for (timeslot in totalTimeSlots) { // if (!mentorTimeSlots.contains(timeslot)) { // availableTimeSlots.add(timeslot) // } // } } if (!isResumed) { isResumed = true continuation.resume(Either.Right(totalTimeSlots)) } } override fun onCancelled(error: DatabaseError) { Log.d("getAvailableTimeSlots", "Error in database : $error") if (!isResumed) { isResumed = true continuation.resume(Either.Left("Error in database : $error")) } } }) } } suspend fun rescheduleAppointment( oldAppointment: Appointment, appointment: Appointment ): Boolean { return suspendCoroutine { continuation -> var isResumed = false oldAppointment.status = "Rescheduled to " + appointment.date + " " + appointment.timeSlot oldAppointment.rescheduled = true val database: FirebaseDatabase = FirebaseDatabase.getInstance() var reference: DatabaseReference = database.reference var mentorNewReference = reference.child("types/${appointment.mentorType}/${appointment.mentorID}/appointments/${appointment.date}/${appointment.timeSlot}") var appointmentID = mentorNewReference.push().key.toString() appointment.id = appointmentID var mentorOldReference = reference.child("types/${oldAppointment.mentorType}/${oldAppointment.mentorID}/appointments/${oldAppointment.date}/${oldAppointment.timeSlot}") mentorOldReference.removeValue().addOnCompleteListener { oldMentorTask -> if (oldMentorTask.isSuccessful) { reference.child("students/${oldAppointment.studentID}/appointments/${oldAppointment.id}") .removeValue().addOnCompleteListener { oldStudentTask -> if (oldStudentTask.isSuccessful) { mentorNewReference.setValue(appointment) .addOnCompleteListener { mentorTask -> if (mentorTask.isSuccessful) { reference.child("students/${appointment.studentID}/appointments/$appointmentID") .setValue(appointment) .addOnCompleteListener { studentTask -> if (studentTask.isSuccessful) { if (!isResumed) continuation.resume(true) } else { mentorNewReference.child(appointment.timeSlot.toString()) .removeValue() if (!isResumed) continuation.resume( false ) } } } else if (!isResumed) continuation.resume(false) } } else if (!isResumed) continuation.resume(false) } } else if (!isResumed) continuation.resume(false) }.addOnFailureListener { errOldDeletion -> Log.d("reschedule", "Error in deleting old booking : $errOldDeletion") if (!isResumed) continuation.resume(false) } } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/student/repo/BookingRepo.kt
3914841169
package com.nitc.projectsgc.composable.student.repo import android.util.Log import android.widget.Toast import arrow.core.Either import arrow.core.right import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.MutableData import com.google.firebase.database.Transaction import com.google.firebase.database.ValueEventListener import com.nitc.projectsgc.models.Appointment import com.nitc.projectsgc.models.Student import javax.inject.Inject import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine class StudentRepo @Inject constructor() { suspend fun getStudent(studentID: String): Either<String, Student> { return suspendCoroutine { continuation -> var isResumed = false val database: FirebaseDatabase = FirebaseDatabase.getInstance() val reference: DatabaseReference = database.reference .child("students") reference.addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { try { var student = snapshot.child(studentID).getValue(Student::class.java) if (student != null) { if (!isResumed) { isResumed = true continuation.resume(Either.Right(student)) } } else { if (!isResumed) { isResumed = true continuation.resume(Either.Left("Could not resolve student")) } } } catch (exc: Exception) { if (!isResumed) { isResumed = true continuation.resume(Either.Left("Error in getting student : $exc")) } } } override fun onCancelled(error: DatabaseError) { if (!isResumed) { isResumed = true continuation.resume(Either.Left("Error : $error")) } } }) } } suspend fun updateProfile( student: Student, oldPassword: String ): Boolean { return suspendCoroutine { continuation -> Log.d("updateStudent", "In repo") var isResumed = false val database: FirebaseDatabase = FirebaseDatabase.getInstance() val reference: DatabaseReference = database.reference.child("students") val auth: FirebaseAuth = FirebaseAuth.getInstance() reference.child(student.rollNo).runTransaction(object : Transaction.Handler { override fun doTransaction(currentData: MutableData): Transaction.Result { try{ // if(!currentData.hasChild("appointments")) currentData.child("appointments").value = student.appointments // if(currentData.hasChild("appointments")){ // val appointments = currentData.child("appointments") // } // val studentFound = currentData.getValue(Student::class.java) // student.appointments = studentFound!!.appointments currentData.child("name").value = student.name currentData.child("userName").value = student.userName // currentData.child("appointments").value = student.appointments currentData.child("rollNo").value = student.rollNo currentData.child("emailId").value = student.emailId currentData.child("phoneNumber").value = student.phoneNumber currentData.child("password").value = student.password currentData.child("gender").value = student.gender currentData.child("dateOfBirth").value = student.dateOfBirth return Transaction.success(currentData) }catch(excCasting:Exception){ if(!isResumed){ isResumed = true continuation.resume(false) } return Transaction.abort() } } override fun onComplete( errorDatabase: DatabaseError?, committed: Boolean, currentData: DataSnapshot? ) { if(errorDatabase != null){ Log.d("updateStudent","Error in updating student : $errorDatabase") if (!isResumed) { isResumed = true continuation.resume(false) } }else if(committed){ if (student.password != oldPassword) { Log.d("updateStudent", "old password is not same") auth.signInWithEmailAndPassword(student.emailId, oldPassword) .addOnSuccessListener { loggedIn -> if (loggedIn != null) { val currentUser = FirebaseAuth.getInstance().currentUser if (currentUser != null) { currentUser.updatePassword(student.password) .addOnCompleteListener { task -> if (task.isSuccessful) { // Show success message to the user auth.signOut() Log.d("updateStudent", "Updated student") if (!isResumed) { isResumed = true continuation.resume(true) } } else { // Password update failed, show error message to the user Log.d( "updateStudent", "Error in updating password of current user" ) if (!isResumed) { isResumed = true continuation.resume(false) } } } .addOnFailureListener { excUpdating -> Log.d( "updateStudent", "Error in updating student : $excUpdating" ) if (!isResumed) { isResumed = true continuation.resume(false) } } } else { Log.d( "updateStudent", "current user is null after logging in with old password" ) if (!isResumed) { isResumed = true continuation.resume(false) } } } else { Log.d("updateStudent", "Error in logging in with old password") if (!isResumed) { isResumed = true continuation.resume(false) } } } .addOnFailureListener { excLogin -> Log.d( "updateStudent", "Error in logging in with old password : $excLogin" ) if (!isResumed) { isResumed = true continuation.resume(false) } } } else { if (!isResumed) { isResumed = true continuation.resume(true) } } }else{ Log.d("updateStudent","Transaction not committed") if (!isResumed) { isResumed = true continuation.resume(false) } } } }) } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/student/repo/StudentRepo.kt
2769579884
package com.nitc.projectsgc.composable.admin.viewmodels import android.content.Context import android.util.Log import android.widget.Toast import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.nitc.projectsgc.composable.admin.repo.MentorsRepo import com.nitc.projectsgc.models.Mentor import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class MentorListViewModel @Inject constructor( private val mentorsRepo: MentorsRepo ):ViewModel() { private val _mentorList = MutableStateFlow(emptyList<Mentor>()) val mentorList: StateFlow<List<Mentor>> = _mentorList fun getMentors(context: Context){ try{ viewModelScope.launch { val mentors = mentorsRepo.getMentors() if(mentors != null) _mentorList.value = mentors } }catch(exc:Exception){ Toast.makeText(context,"Error in getting mentors : $exc", Toast.LENGTH_LONG).show() Log.d("getStudents","Error in getting mentors : $exc") } } fun deleteMentor(context: Context,username:String) { try{ viewModelScope.launch { val deleted = mentorsRepo.deleteMentor(username) if(deleted){ val mentorList = _mentorList.value.filter{ it.userName != username } _mentorList.value = mentorList } } }catch(exc:Exception) { Toast.makeText(context, "Error in deleting mentor : $exc", Toast.LENGTH_LONG).show() Log.d("getStudents", "Error in deleting mentor : $exc") } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/admin/viewmodels/MentorListViewModel.kt
1741174432
package com.nitc.projectsgc.composable.admin.viewmodels import android.content.Context import android.util.Log import android.widget.Toast import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import arrow.core.Either import com.nitc.projectsgc.composable.admin.repo.MentorsRepo import com.nitc.projectsgc.composable.admin.repo.StudentsRepo import com.nitc.projectsgc.models.Mentor import com.nitc.projectsgc.models.Student import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject import kotlin.coroutines.suspendCoroutine @HiltViewModel class AdminViewModel @Inject constructor( val studentsRepo: StudentsRepo, val mentorsRepo: MentorsRepo ) : ViewModel() { // val studentsRepo = StudentsRepo() // val mentorsRepo = MentorsRepo() private val _student = MutableStateFlow<Either<String, Student>?>(null) val student: StateFlow<Either<String, Student>?> = _student.asStateFlow() private val _mentor = MutableStateFlow<Either<String, Mentor>?>(null) val mentor: StateFlow<Either<String, Mentor>?> = _mentor.asStateFlow() fun deleteStudentValue(){ _student.value = null } fun deleteMentorValue(){ _mentor.value = null } fun getStudent(rollNo: String) { viewModelScope.launch { _student.value = studentsRepo.getStudent(rollNo) } } suspend fun updateStudent(student: Student, oldPassword: String): Boolean { val updateSuccess = withContext(Dispatchers.Main) { Log.d("updateStudent", "In adminViewmodel") if (studentsRepo.updateStudent(student, oldPassword)) { Log.d("updateStudent", "Old password = $oldPassword") Log.d("updateStudent", "New password = ${student.password}") _student.value = Either.Right(student) true } else false } return updateSuccess } suspend fun addMentor(mentor: Mentor): Either<String,Boolean> { val updateSuccess = withContext(Dispatchers.Main) { Log.d("updateMentor", "In adminViewmodel") mentorsRepo.addMentor(mentor) } return updateSuccess } suspend fun updateMentor(mentor: Mentor, oldPassword: String): Boolean { val updateSuccess = withContext(Dispatchers.Main) { Log.d("updateMentor", "In adminViewmodel") if (mentorsRepo.updateMentor(mentor, oldPassword)) { Log.d("updateMentor", "Old password = $oldPassword") Log.d("updateMentor", "New password = ${mentor.password}") _mentor.value = Either.Right(mentor) true } else false } return updateSuccess } fun getMentor(username: String) { viewModelScope.launch { _mentor.value = mentorsRepo.getMentor(username) } } suspend fun addStudent(newStudent: Student): Either<String,Boolean> { val addSuccess = withContext(Dispatchers.Main) { Log.d("addStudent", "In adminViewmodel") studentsRepo.addStudent(newStudent) } return addSuccess } // // private val _mentor = MutableStateFlow<Either<String, Mentor>?>(null) // val mentor:StateFlow<Either<String, Mentor>?> = _mentor.asStateFlow() // //// private val _updateSuccess = MutableStateFlow<Boolean>(false) //// val updateSuccess: StateFlow<Boolean> = _updateSuccess.asStateFlow() // fun getMentor(username:String){ // viewModelScope.launch { // _mentor.value = mentorsRepo.getMentor("health",username) // } // } // fun updateMentor(mentor: Mentor,oldPassword:String){ // viewModelScope.launch { // if(mentorsRepo.updateMentor(mentor,oldPassword)){ // _mentor.value = Either.Right(mentor) // _updateSuccess.value = true // }else{ // _updateSuccess.value = false // } // } // } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/admin/viewmodels/AdminViewModel.kt
391581668
package com.nitc.projectsgc.composable.admin.viewmodels import android.content.Context import android.util.Log import android.widget.Toast import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.navigation.compose.rememberNavController import arrow.core.Either import com.nitc.projectsgc.composable.admin.repo.MentorsRepo import com.nitc.projectsgc.composable.admin.repo.StudentsRepo import com.nitc.projectsgc.models.Appointment import com.nitc.projectsgc.models.Mentor import com.nitc.projectsgc.models.Student import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class StudentListViewModel @Inject constructor( private val studentsRepo: StudentsRepo ):ViewModel() { private val _studentList = MutableStateFlow(emptyList<Student>()) val studentList: StateFlow<List<Student>> = _studentList // private val _studentAppointments = MutableStateFlow<Either<String, List<Appointment>>?>(null) // val studentAppointments : StateFlow<Either<String,List<Appointment>>?> = _studentAppointments.asStateFlow() fun getStudents(context:Context){ try{ viewModelScope.launch { val students = studentsRepo.getStudents() if(students != null) _studentList.value = students } }catch(exc:Exception){ Toast.makeText(context,"Error in getting students : $exc",Toast.LENGTH_LONG).show() Log.d("getStudents","Error in getting students : $exc") } } // fun deleteStudentAppointments(){ // _studentAppointments.value = null // } // fun getStudentAppointments(rollNo: String){ // viewModelScope.launch { // _studentAppointments.value = studentsRepo.getAppointments(rollNo) // } // } fun deleteStudent(context: Context,rollNo:String) { try{ viewModelScope.launch { val deleted = studentsRepo.deleteStudent(rollNo) if(deleted){ val studentList = _studentList.value.filter{ it.rollNo != rollNo } _studentList.value = studentList } } }catch(exc:Exception) { Toast.makeText(context, "Error in deleting mentor : $exc", Toast.LENGTH_LONG).show() Log.d("getStudents", "Error in deleting mentor : $exc") } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/admin/viewmodels/StudentListViewModel.kt
791048158
package com.nitc.projectsgc.composable.admin import com.nitc.projectsgc.composable.admin.repo.MentorsRepo import com.nitc.projectsgc.composable.admin.repo.StudentsRepo import com.nitc.projectsgc.composable.admin.viewmodels.AdminViewModel import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ViewModelComponent import dagger.hilt.android.scopes.ViewModelScoped @Module @InstallIn(ViewModelComponent::class) object AdminModule { @Provides @ViewModelScoped fun provideStudentsRepo(): StudentsRepo { return StudentsRepo() } @Provides @ViewModelScoped fun provideMentorsRepo(): MentorsRepo { return MentorsRepo() } @Provides @ViewModelScoped fun provideAdminViewModel(studentsRepo: StudentsRepo,mentorsRepo: MentorsRepo): AdminViewModel { return AdminViewModel(studentsRepo,mentorsRepo) } // // @Provides // @ViewModelScoped // fun provideStudentListViewModel(studentsRepo: StudentsRepo): StudentListViewModel { // return StudentListViewModel(studentsRepo) // } // // // @Provides // @ViewModelScoped // fun provideMentorListViewModel(mentorsRepo: MentorsRepo): MentorListViewModel { // return MentorListViewModel(mentorsRepo) // } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/admin/AdminModule.kt
1048040298
package com.nitc.projectsgc.composable.admin import android.util.Log import androidx.activity.compose.BackHandler import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.navigation.NavController import com.nitc.projectsgc.composable.admin.viewmodels.AdminViewModel import com.nitc.projectsgc.composable.admin.viewmodels.MentorListViewModel import com.nitc.projectsgc.composable.admin.viewmodels.StudentListViewModel import com.nitc.projectsgc.composable.components.MentorCard import com.nitc.projectsgc.composable.components.StudentCard import com.nitc.projectsgc.composable.components.TabLayout @Composable fun AdminDashboardScreen( adminViewModel: AdminViewModel, navController: NavController, mentorListViewModel: MentorListViewModel, studentListViewModel: StudentListViewModel, viewStudentCallback: (rollNo: String) -> Unit, viewMentorCallback: (username: String) -> Unit, addStudentCallback: () -> Unit, addMentorCallback: () -> Unit ) { Log.d("adminDashboard","Inside the admin dashboard screen") Column( modifier = Modifier.fillMaxSize() ) { val selectedTabIndex = remember { mutableIntStateOf(0) } TabLayout( tabs = listOf("Students", "Mentors"), fontColor = Color.Black, bg = Color.White, ) { pageIndex -> when (pageIndex) { 0 -> { GetStudents( studentListViewModel = studentListViewModel, viewStudentCallback = { viewStudentCallback(it) }, backCallback = { navController.popBackStack() }, addStudentCallback = { addStudentCallback() } ) } 1 -> { GetMentors(mentorListViewModel, viewMentorCallback = { Log.d("viewMentor","Getting username : $it") viewMentorCallback(it) }, backCallback = { navController.popBackStack() }, addMentorCallback = { addMentorCallback() } ) } } } } } @Composable fun GetStudents( studentListViewModel: StudentListViewModel, viewStudentCallback: (rollNo: String) -> Unit, backCallback: () -> Unit, addStudentCallback: () -> Unit ) { val myContext = LocalContext.current studentListViewModel.getStudents(myContext) val students = studentListViewModel.studentList.collectAsState() BackHandler(enabled = true) { backCallback() } Box(modifier = Modifier.fillMaxSize()) { LazyColumn( modifier = Modifier.fillMaxSize() ) { items( count = students.value.size, itemContent = { index: Int -> val student = students.value[index] StudentCard( student = student, deleteCallback = { studentListViewModel.deleteStudent(myContext, student.rollNo) }, clickCallback = { viewStudentCallback(student.rollNo) }, ) } ) } FloatingActionButton( onClick = { addStudentCallback() }, modifier = Modifier .align(Alignment.BottomEnd) .padding(10.dp) ) { Icon(Icons.Filled.Add, "Add Student") } } } @Composable fun GetMentors( mentorListViewModel: MentorListViewModel, viewMentorCallback: (username: String) -> Unit, backCallback: () -> Unit, addMentorCallback: () -> Unit ) { BackHandler(enabled = true) { backCallback() } val myContext = LocalContext.current mentorListViewModel.getMentors(myContext) val mentors = mentorListViewModel.mentorList.collectAsState() Box(modifier = Modifier.fillMaxSize()) { LazyColumn( modifier = Modifier .align(Alignment.Center) .fillMaxSize() ) { items( count = mentors.value.size, itemContent = { index: Int -> val mentor = mentors.value[index] MentorCard(mentor = mentor, deleteCallback = { mentorListViewModel.deleteMentor(myContext, mentor.userName) }, clickCallback = { viewMentorCallback(mentor.userName) }, ) } ) } FloatingActionButton( onClick = { addMentorCallback() }, modifier = Modifier .align(Alignment.BottomEnd) .padding(10.dp) ) { Icon(Icons.Filled.Add, "Add Mentor") } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/admin/AdminDashboardScreen.kt
3263636142
package com.nitc.projectsgc.composable.admin.repo import android.util.Log import arrow.core.Either import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.MutableData import com.google.firebase.database.Transaction import com.google.firebase.database.ValueEventListener import com.nitc.projectsgc.composable.util.PathUtils import com.nitc.projectsgc.models.Appointment import com.nitc.projectsgc.models.Mentor import com.nitc.projectsgc.models.Student import javax.inject.Inject import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine class MentorsRepo @Inject constructor() { suspend fun getMentors(): ArrayList<Mentor>? { return suspendCoroutine { continuation -> var database: FirebaseDatabase = FirebaseDatabase.getInstance() var reference: DatabaseReference = database.reference.child("types") reference.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { var typeList = arrayListOf<String>() var mentorList = arrayListOf<Mentor>() for (typeOfMentor in snapshot.children) { typeList.add(typeOfMentor.key.toString()) } for (typeOfMentor in typeList) { for (mentor in snapshot.child(typeOfMentor).children) { Log.d("mentorCheck", mentor.toString()) var thisMentor = mentor.getValue(Mentor::class.java) if (thisMentor != null) { mentorList.add(thisMentor) } } } continuation.resume(mentorList) } override fun onCancelled(error: DatabaseError) { continuation.resume(null) } }) } } suspend fun addMentor( mentor: Mentor ): Either<String, Boolean> { return suspendCoroutine { continuation -> var isResumed = false val database: FirebaseDatabase = FirebaseDatabase.getInstance() val reference: DatabaseReference = database.reference.child("types").child(mentor.type) val auth: FirebaseAuth = FirebaseAuth.getInstance() reference.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { if (!snapshot.hasChild(mentor.userName)) { reference.child(mentor.userName) .setValue(mentor).addOnSuccessListener { task -> Log.d("addMentor", "here in addMentor access") // continuation.resume(true) auth.createUserWithEmailAndPassword( mentor.email, mentor.password ).addOnSuccessListener { authTask -> if (authTask != null) { Log.d("addMentor", "auth task is successful") if (!isResumed) { isResumed = true continuation.resume(Either.Right(true)) } } else { Log.d("addMentor", "auth task is not successful") reference.child(mentor.userName).removeValue() if (!isResumed) { isResumed = true continuation.resume(Either.Left("Error in adding mentor")) } } }.addOnFailureListener { errAuth -> Log.d("addMentor", "Error in adding auth mentor : $errAuth") if (!isResumed) { isResumed = true continuation.resume(Either.Left("Error in adding mentor : $errAuth")) } } } .addOnFailureListener { errAdd -> Log.d("addMentor", "Error in adding mentor : $errAdd") if (!isResumed) { isResumed = true continuation.resume(Either.Left("Error in adding mentor : $errAdd")) } } } else { if (!isResumed) { isResumed = true continuation.resume(Either.Left("Mentor already exists with given username")) } } } override fun onCancelled(error: DatabaseError) { Log.d("addMentor", "Database error : $error") if (!isResumed) { isResumed = true continuation.resume(Either.Left("Error in adding mentor : $error")) } } }) } } suspend fun getMentor(username: String): Either<String, Mentor> { return suspendCoroutine { continuation -> var isResumed = false var database: FirebaseDatabase = FirebaseDatabase.getInstance() val mentorTypeEither = PathUtils.getMentorType(username) when (mentorTypeEither) { is Either.Left -> { if (!isResumed) { isResumed = true continuation.resume(Either.Left(mentorTypeEither.value.message!!)) } } is Either.Right -> { var reference: DatabaseReference = database.reference.child("types/${mentorTypeEither.value}/${username}") reference.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { try { val mentor = snapshot.getValue(Mentor::class.java) if (!isResumed) { isResumed = true continuation.resume(Either.Right(mentor!!)) } } catch (exc: Exception) { Log.d("getMentor", "Error in getting mentor : $exc") if (!isResumed) { isResumed = true continuation.resume(Either.Left("Error in getting mentor : $exc")) } } } override fun onCancelled(error: DatabaseError) { Log.d("getMentor", "Database Error : $error") if (!isResumed) { continuation.resume(Either.Left("Database error ; $error")) isResumed = true } } }) } } } } suspend fun getMentorNames(mentorType: String): ArrayList<Mentor>? { return suspendCoroutine { continuation -> var isResumed = false var mentors = arrayListOf<Mentor>() var database: FirebaseDatabase = FirebaseDatabase.getInstance() var reference: DatabaseReference = database.reference.child("types") reference.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { var mentorsSnapshot = snapshot.child(mentorType).children for (mentor in mentorsSnapshot) { mentors.add(mentor.getValue(Mentor::class.java)!!) } if (!isResumed) { continuation.resume(mentors) isResumed = true } } override fun onCancelled(error: DatabaseError) { if (!isResumed) { continuation.resume(null) isResumed = true } } }) } } suspend fun getMentorTypes(): ArrayList<String>? { return suspendCoroutine { continuation -> // var mentorTypeLive = MutableLiveData<ArrayList<String>>(null) var isResumed = false val database: FirebaseDatabase = FirebaseDatabase.getInstance() val reference: DatabaseReference = database.reference.child("types") var mentorTypes = arrayListOf<String>() reference.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { for (typeChild in snapshot.children) { mentorTypes.add(typeChild.key.toString()) } if (!isResumed) { continuation.resume(mentorTypes) isResumed = true } } override fun onCancelled(error: DatabaseError) { if (!isResumed) { continuation.resume(null) isResumed = true } } }) } } suspend fun deleteMentor(userName: String): Boolean { return suspendCoroutine { continuation -> var database: FirebaseDatabase = FirebaseDatabase.getInstance() var typeReference: DatabaseReference = database.reference.child("types") var isResumed = false val mentorTypeEither = PathUtils.getMentorType(userName) when (mentorTypeEither) { is Either.Left -> { if (!isResumed) { isResumed = true continuation.resume(false) } } is Either.Right -> { var mentorPath = "$mentorTypeEither.value/$userName" Log.d("deleteMentor", mentorPath) typeReference.child(mentorPath) .addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { for (ds in snapshot.child("appointments").children) { for (timeSlot in ds.children) { var appointment = timeSlot.getValue(Appointment::class.java)!! var studentReference = "students/${appointment.studentID}/appointments/${appointment.id}" Log.d("deleteMentor", studentReference) database.reference.child(studentReference).removeValue() .addOnSuccessListener { }.addOnFailureListener { if (!isResumed) { isResumed = true continuation.resume(false) } } } } } override fun onCancelled(error: DatabaseError) { if (!isResumed) { isResumed = true continuation.resume(false) } } }) typeReference.child(mentorPath).removeValue() .addOnSuccessListener { deletedMentor -> if (!isResumed) { isResumed = true continuation.resume(true) } } .addOnFailureListener { error -> if (!isResumed) { isResumed = true continuation.resume(false) } } } } } } suspend fun updateMentor( mentor: Mentor, oldPassword: String ): Boolean { return suspendCoroutine { continuation -> Log.d("updateMentor", "In repo") var isResumed = false val database: FirebaseDatabase = FirebaseDatabase.getInstance() val reference: DatabaseReference = database.reference.child("types") when (val mentorTypeEither = PathUtils.getMentorType(mentor.userName)) { is Either.Left -> { if (!isResumed) { isResumed = true continuation.resume(false) } } is Either.Right -> { val mentorPath = "${mentorTypeEither.value}/${mentor.userName}" val auth: FirebaseAuth = FirebaseAuth.getInstance() reference.child(mentorPath).runTransaction(object : Transaction.Handler { override fun doTransaction(currentData: MutableData): Transaction.Result { return try { currentData.child("name").value = mentor.name currentData.child("userName").value = mentor.userName currentData.child("type").value = mentor.type currentData.child("email").value = mentor.email currentData.child("phone").value = mentor.phone currentData.child("password").value = mentor.password Transaction.success(currentData) } catch (excCasting: Exception) { if (!isResumed) { isResumed = true continuation.resume(false) } Transaction.abort() } } override fun onComplete( errorDatabase: DatabaseError?, committed: Boolean, currentData: DataSnapshot? ) { if (errorDatabase != null) { Log.d("updateStudent", "Error in updating student : $errorDatabase") if (!isResumed) { isResumed = true continuation.resume(false) } } else if (committed) { Log.d("updateMentor", "in add on success") if (mentor.password != oldPassword) { Log.d("updateMentor", "old password is not same") auth.signInWithEmailAndPassword(mentor.email, oldPassword) .addOnSuccessListener { loggedIn -> if (loggedIn != null) { val currentUser = FirebaseAuth.getInstance().currentUser if (currentUser != null) { currentUser.updatePassword(mentor.password) .addOnCompleteListener { task -> if (task.isSuccessful) { // Show success message to the user auth.signOut() Log.d( "updateMentor", "Updated mentor" ) if (!isResumed) { isResumed = true continuation.resume(true) } } else { // Password update failed, show error message to the user Log.d( "updateMentor", "Error in updating password of current user" ) if (!isResumed) { isResumed = true continuation.resume(false) } } } .addOnFailureListener { excUpdating -> Log.d( "updateMentor", "Error in updating mentor : $excUpdating" ) if (!isResumed) { isResumed = true continuation.resume(false) } } } else { Log.d( "updateMentor", "current user is null after logging in with old password" ) if (!isResumed) { isResumed = true continuation.resume(false) } } } else { Log.d( "updateMentor", "Error in logging in with old password" ) if (!isResumed) { isResumed = true continuation.resume(false) } } } .addOnFailureListener { excLogin -> Log.d( "updateMentor", "Error in logging in with old password : $excLogin" ) if (!isResumed) { isResumed = true continuation.resume(false) } } } else { if (!isResumed) { isResumed = true continuation.resume(true) } } } else { Log.d("updateMentor", "Transaction not committed") if (!isResumed) { isResumed = true continuation.resume(false) } } } }) } } } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/admin/repo/MentorsRepo.kt
3298398988
package com.nitc.projectsgc.composable.admin.repo import android.content.Context import android.util.Log import android.widget.Toast import arrow.core.Either import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.MutableData import com.google.firebase.database.Transaction import com.google.firebase.database.ValueEventListener import com.nitc.projectsgc.models.Appointment import com.nitc.projectsgc.models.Student import javax.inject.Inject import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine class StudentsRepo @Inject constructor() { suspend fun getStudent(studentID: String): Either<String, Student> { return suspendCoroutine { continuation -> var isResumed = false val database: FirebaseDatabase = FirebaseDatabase.getInstance() val reference: DatabaseReference = database.reference .child("students") reference.addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { try { var student = snapshot.child(studentID).getValue(Student::class.java) if (student != null) { if (!isResumed) { isResumed = true continuation.resume(Either.Right(student)) } } else { if (!isResumed) { isResumed = true continuation.resume(Either.Left("Could not resolve student")) } } } catch (exc: Exception) { if (!isResumed) { isResumed = true continuation.resume(Either.Left("Error in getting student : $exc")) } } } override fun onCancelled(error: DatabaseError) { if (!isResumed) { isResumed = true continuation.resume(Either.Left("Error : $error")) } } }) } } suspend fun updateStudent( student: Student, oldPassword: String ): Boolean { return suspendCoroutine { continuation -> Log.d("updateStudent", "In repo") var isResumed = false val database: FirebaseDatabase = FirebaseDatabase.getInstance() val reference: DatabaseReference = database.reference.child("students") val auth: FirebaseAuth = FirebaseAuth.getInstance() reference.child(student.rollNo).runTransaction(object : Transaction.Handler { override fun doTransaction(currentData: MutableData): Transaction.Result { try{ // if(!currentData.hasChild("appointments")) currentData.child("appointments").value = student.appointments // if(currentData.hasChild("appointments")){ // val appointments = currentData.child("appointments") // } // val studentFound = currentData.getValue(Student::class.java) // student.appointments = studentFound!!.appointments currentData.child("name").value = student.name currentData.child("userName").value = student.userName // currentData.child("appointments").value = student.appointments currentData.child("rollNo").value = student.rollNo currentData.child("emailId").value = student.emailId currentData.child("phoneNumber").value = student.phoneNumber currentData.child("password").value = student.password currentData.child("gender").value = student.gender currentData.child("dateOfBirth").value = student.dateOfBirth return Transaction.success(currentData) }catch(excCasting:Exception){ if(!isResumed){ isResumed = true continuation.resume(false) } return Transaction.abort() } } override fun onComplete( errorDatabase: DatabaseError?, committed: Boolean, currentData: DataSnapshot? ) { if(errorDatabase != null){ Log.d("updateStudent","Error in updating student : $errorDatabase") if (!isResumed) { isResumed = true continuation.resume(false) } }else if(committed){ if (student.password != oldPassword) { Log.d("updateStudent", "old password is not same") auth.signInWithEmailAndPassword(student.emailId, oldPassword) .addOnSuccessListener { loggedIn -> if (loggedIn != null) { val currentUser = FirebaseAuth.getInstance().currentUser if (currentUser != null) { currentUser.updatePassword(student.password) .addOnCompleteListener { task -> if (task.isSuccessful) { // Show success message to the user auth.signOut() Log.d("updateStudent", "Updated student") if (!isResumed) { isResumed = true continuation.resume(true) } } else { // Password update failed, show error message to the user Log.d( "updateStudent", "Error in updating password of current user" ) if (!isResumed) { isResumed = true continuation.resume(false) } } } .addOnFailureListener { excUpdating -> Log.d( "updateStudent", "Error in updating student : $excUpdating" ) if (!isResumed) { isResumed = true continuation.resume(false) } } } else { Log.d( "updateStudent", "current user is null after logging in with old password" ) if (!isResumed) { isResumed = true continuation.resume(false) } } } else { Log.d("updateStudent", "Error in logging in with old password") if (!isResumed) { isResumed = true continuation.resume(false) } } } .addOnFailureListener { excLogin -> Log.d( "updateStudent", "Error in logging in with old password : $excLogin" ) if (!isResumed) { isResumed = true continuation.resume(false) } } } else { if (!isResumed) { isResumed = true continuation.resume(true) } } }else{ Log.d("updateStudent","Transaction not committed") if (!isResumed) { isResumed = true continuation.resume(false) } } } }) } } suspend fun getStudents(): ArrayList<Student>? { return suspendCoroutine { continuation -> var database: FirebaseDatabase = FirebaseDatabase.getInstance() var reference: DatabaseReference = database.reference.child("students") reference.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { var studentList = arrayListOf<Student>() for (student in snapshot.children) { var thisStudent = student.getValue(Student::class.java) if (thisStudent != null) { studentList.add(thisStudent) } } continuation.resume(studentList) } override fun onCancelled(error: DatabaseError) { continuation.resume(null) } }) } } suspend fun deleteStudent(rollNo: String): Boolean { return suspendCoroutine { continuation -> var isResumed = false var database: FirebaseDatabase = FirebaseDatabase.getInstance() var typeReference = database.reference.child("types") var studentReference: DatabaseReference = database.reference.child("students") // Log.d("child",reference.child(rollNo).toString()) studentReference.child(rollNo) .addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(studentSnapshot: DataSnapshot) { if (studentSnapshot.hasChild("appointments")) { for (appointment in studentSnapshot.child("appointments").children) { var studentAppointment = appointment.getValue(Appointment::class.java)!! var mentorAppointmentPath = "${studentAppointment.mentorType}/${studentAppointment.mentorID}/${studentAppointment.date}/${studentAppointment.timeSlot}" studentAppointment.status = "Student deleted" studentAppointment.cancelled = true typeReference.child(mentorAppointmentPath) .setValue(studentAppointment) .addOnCompleteListener { mentorDeleted -> if (mentorDeleted.isSuccessful) { if (!isResumed) continuation.resume(true) } else { if (!isResumed) continuation.resume(false) } } } } } override fun onCancelled(error: DatabaseError) { if (!isResumed) continuation.resume(false) } }) studentReference.child(rollNo).removeValue().addOnSuccessListener { continuation.resume(true) } .addOnFailureListener { error -> if (!isResumed) continuation.resume(false) } } } suspend fun addStudent( student: Student ): Either<String, Boolean> { return suspendCoroutine { continuation -> Log.d("addStudent", "In repo") var isResumed = false val database: FirebaseDatabase = FirebaseDatabase.getInstance() val reference: DatabaseReference = database.reference.child("students") Log.d("addStudent","adding student : $student") val auth: FirebaseAuth = FirebaseAuth.getInstance() reference.child(student.rollNo).setValue(student).addOnSuccessListener { task -> Log.d("addStudent", "in add on success") Log.d("addStudent", "old password is not same") auth.createUserWithEmailAndPassword(student.emailId, student.password) .addOnSuccessListener { loggedIn -> if (loggedIn != null) { Log.d("addStudent", "Updated student") if (!isResumed) { isResumed = true continuation.resume(Either.Right(true)) } } else { // Password add failed, show error message to the user Log.d( "addStudent", "Error in adding password of current user" ) if(!isResumed){ isResumed = true continuation.resume(Either.Left("Error in adding student")) } } } .addOnFailureListener { excAdding -> Log.d( "addStudent", "Error in adding student : $excAdding" ) if(!isResumed){ isResumed = true continuation.resume(Either.Left("Error in adding student : $excAdding")) } } }.addOnFailureListener { excAdd -> Log.d("addStudent", "Error in adding in firebase : $excAdd") if(!isResumed){ isResumed = true continuation.resume(Either.Left("Error in adding student : $excAdd")) } } } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/admin/repo/StudentsRepo.kt
3673226543
package com.nitc.projectsgc.composable.navigation import androidx.annotation.StringRes import com.nitc.projectsgc.R sealed class NavigationScreen(val route:String, @StringRes val resID:Int){ data object FlashScreen:NavigationScreen("flashScreen", R.string.app_name) data object LoginScreen:NavigationScreen("loginScreen", R.string.login_screen) data object AdminDashboard:NavigationScreen("adminDashboard", R.string.admin_dashboard) data object MentorDashboard:NavigationScreen("mentorDashboard", R.string.mentor_dashboard) data object StudentDashboard:NavigationScreen("studentDashboard", R.string.student_dashboard) data object BookingScreen:NavigationScreen("bookingScreen", R.string.booking_screen) data object RescheduleScreen:NavigationScreen("rescheduleScreen", R.string.reschedule_screen) data object NewsScreen:NavigationScreen("newsScreen", R.string.news_screen) data object ViewStudent:NavigationScreen("viewStudent", R.string.view_student) data object ViewStudentAppointments:NavigationScreen("viewStudentAppointments", R.string.view_student_appointments) data object ViewMentor:NavigationScreen("viewMentor", R.string.view_mentor) data object ViewMentorAppointments:NavigationScreen("viewMentorAppointments", R.string.view_mentor_appointments) }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/navigation/NavigationScreen.kt
393496693
package com.nitc.projectsgc.composable.navigation.graphs import android.util.Log import androidx.compose.runtime.MutableState import androidx.compose.ui.res.stringResource import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.NavType import androidx.navigation.compose.composable import androidx.navigation.navArgument import androidx.navigation.navigation import com.nitc.projectsgc.composable.navigation.NavigationScreen import com.nitc.projectsgc.composable.student.screens.BookingScreen import com.nitc.projectsgc.composable.student.screens.StudentAppointmentsScreen import com.nitc.projectsgc.composable.student.viewmodels.StudentViewModel import com.nitc.projectsgc.composable.student.screens.StudentDashboardScreen import com.nitc.projectsgc.composable.student.viewmodels.BookingViewModel import com.nitc.projectsgc.models.Appointment fun NavGraphBuilder.studentGraph( titleState: MutableState<String>, topBarState: MutableState<Boolean>, navController: NavController, studentViewModel: StudentViewModel, bookingViewModel: BookingViewModel ) { navigation( startDestination = "${NavigationScreen.StudentDashboard.route}/{rollNo}", route = "student/{rollNo}" ) { composable( route = "${NavigationScreen.StudentDashboard.route}/{rollNo}", arguments = listOf( navArgument("rollNo") { type = NavType.StringType } ) ) { navEntry -> titleState.value = stringResource(NavigationScreen.StudentDashboard.resID) topBarState.value = true val roll = navEntry.arguments?.getString("rollNo") ?: "" Log.d("studentDashboard", "Roll no found : $roll") StudentDashboardScreen( roll, studentViewModel, bookingViewModel, goToBooking = { navController.navigate(NavigationScreen.BookingScreen.route + "/${roll}") } ) } // composable( // route = "${NavigationScreen.RescheduleScreen.route}/{rollNo}", // arguments = listOf( // navArgument("rollNo") { type = NavType.StringType } // ) // ) { navEntry -> // navEntry.arguments?.getString("rollNo").let {roll-> // StudentDashboardScreen(roll) // } // } composable( route = "${NavigationScreen.BookingScreen.route}/{rollNo}", arguments = listOf( navArgument("rollNo") { type = NavType.StringType }, ) ) { navEntry -> titleState.value = stringResource(NavigationScreen.BookingScreen.resID) val roll = navEntry.arguments?.getString("rollNo") ?: "" BookingScreen( rollNo = roll, bookingViewModel = bookingViewModel, bookCallback = { navController.popBackStack(NavigationScreen.BookingScreen.route, true) navController.navigate("${NavigationScreen.StudentDashboard.route}/${roll}") }) } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/navigation/graphs/StudentGraph.kt
2917122296
package com.nitc.projectsgc.composable.navigation.graphs import android.util.Log import androidx.compose.runtime.MutableState import androidx.compose.ui.res.stringResource import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.NavType import androidx.navigation.compose.composable import androidx.navigation.navArgument import androidx.navigation.navigation import com.nitc.projectsgc.composable.admin.AdminDashboardScreen import com.nitc.projectsgc.composable.admin.viewmodels.AdminViewModel import com.nitc.projectsgc.composable.admin.viewmodels.MentorListViewModel import com.nitc.projectsgc.composable.admin.viewmodels.StudentListViewModel import com.nitc.projectsgc.composable.mentor.screens.ViewMentorScreen import com.nitc.projectsgc.composable.navigation.NavigationScreen import com.nitc.projectsgc.composable.student.screens.StudentAppointmentsScreen import com.nitc.projectsgc.composable.student.screens.ViewStudentScreen fun NavGraphBuilder.adminGraph( titleState: MutableState<String>, topBarState: MutableState<Boolean>, navController: NavController, adminViewModel: AdminViewModel, studentListViewModel: StudentListViewModel, mentorListViewModel: MentorListViewModel ) { navigation(startDestination = NavigationScreen.AdminDashboard.route, route = "admin") { Log.d("adminDashboard", "In the navigation of admin") composable(route = NavigationScreen.AdminDashboard.route) { Log.d("adminDashboard", "In admin dashboard composabled") topBarState.value = true // navController.popBackStack( // inclusive = false, // route = NavigationScreen.AdminDashboard.route // ) titleState.value = stringResource(id = NavigationScreen.AdminDashboard.resID) AdminDashboardScreen( adminViewModel = adminViewModel, navController = navController, mentorListViewModel = mentorListViewModel, studentListViewModel = studentListViewModel, viewStudentCallback = { rollNo -> navController.navigate(NavigationScreen.ViewStudent.route + "/" + rollNo) }, viewMentorCallback = { username -> navController.navigate("${NavigationScreen.ViewMentor.route}/${username}") }, addMentorCallback = { navController.navigate(NavigationScreen.ViewMentor.route + "/no") }, addStudentCallback = { navController.navigate(NavigationScreen.ViewStudent.route + "/no") } ) } composable(route = "${NavigationScreen.ViewMentor.route}/{username}", arguments = listOf( navArgument("username") { type = NavType.StringType } )) { navBackStackEntry -> topBarState.value = true titleState.value = stringResource(id = NavigationScreen.ViewMentor.resID) val usernameString = navBackStackEntry.arguments?.getString("username") ?: "no" ViewMentorScreen( username = usernameString, adminViewModel = adminViewModel ) } composable(route = "${NavigationScreen.ViewStudent.route}/{rollNo}", arguments = listOf( navArgument("rollNo") { type = NavType.StringType } )) { navBackStackEntry -> topBarState.value = true titleState.value = stringResource(id = NavigationScreen.ViewStudent.resID) val rollNoString = navBackStackEntry.arguments?.getString("rollNo") ?: "no" ViewStudentScreen(rollNoString, adminViewModel) } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/navigation/graphs/AdminGraph.kt
4216022988
package com.nitc.projectsgc.composable.navigation.graphs import androidx.compose.runtime.MutableState import androidx.compose.ui.res.stringResource import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.NavType import androidx.navigation.compose.composable import androidx.navigation.navArgument import androidx.navigation.navigation import com.nitc.projectsgc.composable.mentor.MentorViewModel import com.nitc.projectsgc.composable.mentor.screens.MentorAppointmentsScreen import com.nitc.projectsgc.composable.mentor.screens.MentorDashboardScreen import com.nitc.projectsgc.composable.mentor.screens.PastRecordScreen import com.nitc.projectsgc.composable.navigation.NavigationScreen import com.nitc.projectsgc.composable.student.screens.StudentAppointmentsScreen fun NavGraphBuilder.mentorGraph( topBarState: MutableState<Boolean>, navController: NavController, mentorViewModel: MentorViewModel, titleState: MutableState<String> ) { navigation( startDestination = "${NavigationScreen.MentorDashboard.route}/{username}", route = "mentor/{username}" ) { composable(route = "${NavigationScreen.MentorDashboard.route}/{username}", arguments = listOf( navArgument("username") { type = NavType.StringType } )) { navBackStackEntry -> topBarState.value = true titleState.value = stringResource(id = NavigationScreen.MentorDashboard.resID) navBackStackEntry.arguments?.getString("username") ?.let { usernameString -> MentorDashboardScreen( username = usernameString, mentorViewModel = mentorViewModel, pastRecordCallback = { rollNo -> navController.navigate("${NavigationScreen.ViewStudentAppointments.route}/${usernameString}/${rollNo}") } ) } } composable(route = "${NavigationScreen.ViewStudentAppointments.route}/{username}/{rollNo}", arguments = listOf( navArgument("rollNo") { type = NavType.StringType } )) { navBackStackEntry -> topBarState.value = true titleState.value = stringResource(id = NavigationScreen.ViewStudentAppointments.resID) val rollNo = navBackStackEntry.arguments?.getString("rollNo") ?: "" val username = navBackStackEntry.arguments?.getString("username") ?: "" PastRecordScreen( username = username, mentorViewModel = mentorViewModel, rollNo = rollNo ) } // // composable(route = "${NavigationScreen.ViewMentorAppointments.route}/{username}", // arguments = listOf( // navArgument("username") { type = NavType.StringType } // )) { navBackStackEntry -> // titleState.value = stringResource(id = NavigationScreen.ViewMentorAppointments.resID) // navBackStackEntry.arguments?.getString("username") // ?.let { usernameString -> // MentorAppointmentsScreen( // username = usernameString, // mentorViewModel = mentorViewModel, // // ) // } // } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/navigation/graphs/MentorGraph.kt
2500039395
package com.nitc.projectsgc.composable.navigation.graphs import androidx.compose.runtime.MutableState import androidx.compose.ui.res.stringResource import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.NavType import androidx.navigation.compose.composable import androidx.navigation.navArgument import androidx.navigation.navigation import com.nitc.projectsgc.composable.navigation.NavigationScreen import com.nitc.projectsgc.composable.news.NewsViewModel import com.nitc.projectsgc.composable.news.screens.NewsScreen import com.nitc.projectsgc.composable.util.UserRole fun NavGraphBuilder.newsGraph( topBarState: MutableState<Boolean>, navController: NavController, titleState: MutableState<String>, newsViewModel: NewsViewModel ) { navigation( startDestination = "${NavigationScreen.NewsScreen.route}/{userType}/{username}", route = "news/{userType}/{username}" ) { composable(route = "${NavigationScreen.NewsScreen.route}/{userType}/{username}", arguments = listOf( navArgument("username") { type = NavType.StringType }, navArgument("userType") { type = NavType.StringType }, )) { navBackStackEntry -> topBarState.value = true titleState.value = stringResource(id = NavigationScreen.NewsScreen.resID) navBackStackEntry.arguments?.let { args -> val username = args.getString("username") ?: "" val userType = (args.getString("userType")?:"${UserRole.Student}").toInt() NewsScreen( newsViewModel = newsViewModel, userType = userType, username = username ) } } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/navigation/graphs/NewsGraph.kt
2647568635
package com.nitc.projectsgc.composable.mentor.screens import android.util.Log import android.widget.Toast import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import arrow.core.Either import com.nitc.projectsgc.composable.admin.viewmodels.AdminViewModel import com.nitc.projectsgc.models.Mentor import kotlinx.coroutines.launch @Composable fun ViewMentorScreen( username: String, adminViewModel: AdminViewModel ) { val mentorState = remember { mutableStateOf<Mentor?>(if (username != "no") null else Mentor()) } if (username != "no") { adminViewModel.getMentor(username) } else { adminViewModel.deleteMentorValue() mentorState.value = Mentor() } val screenContext = LocalContext.current val updatingState = remember { mutableStateOf(false) } val mentorEither = adminViewModel.mentor.collectAsState().value var oldPassword = "" val coroutineScope = rememberCoroutineScope() when (mentorEither) { is Either.Left -> { Toast.makeText( LocalContext.current, "Error in getting mentor : ${mentorEither.value}", Toast.LENGTH_LONG ).show() } is Either.Right -> { Log.d("viewMentor", "no error message") mentorState.value = mentorEither.value oldPassword = mentorEither.value.password UpdateMentorScreen(mentorEither.value) { updatedMentor -> Log.d("updateMentor", "these are new values ; $updatedMentor") coroutineScope.launch { Log.d("updateMentor", "Now updated : $updatedMentor") val updateSuccess = adminViewModel.updateMentor(updatedMentor, oldPassword) if (updateSuccess) { mentorState.value = updatedMentor Toast.makeText(screenContext, "Updated Mentor", Toast.LENGTH_LONG).show() } else { Toast.makeText( screenContext, "Error in updating mentor", Toast.LENGTH_LONG ).show() } updatingState.value = false } } } null -> { Log.d("viewMentor", "Mentor either is null") UpdateMentorScreen(Mentor()) { newMentor -> coroutineScope.launch { val addedSuccessEither = adminViewModel.addMentor(newMentor) when (addedSuccessEither) { is Either.Left -> { Toast.makeText( screenContext, addedSuccessEither.value, Toast.LENGTH_LONG ).show() } is Either.Right -> { Toast.makeText(screenContext, "Added Mentor", Toast.LENGTH_LONG) .show() mentorState.value = newMentor } } updatingState.value = false } } } } // } @Preview @Composable fun ViewMentorPreview() { }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/mentor/screens/ViewMentorScreen.kt
2654531635
package com.nitc.projectsgc.composable.mentor.screens import android.util.Log import android.widget.Toast import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.navigation.NavController import arrow.core.Either import com.nitc.projectsgc.composable.components.TabLayout import com.nitc.projectsgc.composable.mentor.MentorViewModel import com.nitc.projectsgc.models.Mentor import kotlinx.coroutines.launch @Composable fun MentorDashboardScreen( username: String, mentorViewModel: MentorViewModel, pastRecordCallback: (rollNo: String) -> Unit ) { Column( modifier = Modifier.fillMaxSize() ) { val selectedTabIndex = remember { mutableIntStateOf(0) } TabLayout( tabs = listOf("Appointments", "Profile"), fontColor = Color.Black, bg = Color.White, ) { pageIndex -> when (pageIndex) { 0 -> { MentorAppointmentsScreen( username = username, mentorViewModel = mentorViewModel, recordCallback = { studentRoll -> pastRecordCallback(studentRoll) } ) } 1 -> { GetProfile(username = username, mentorViewModel = mentorViewModel) } } } } } @Composable fun GetProfile(username: String, mentorViewModel: MentorViewModel) { val mentorState = remember { mutableStateOf<Mentor?>(if (username != "no") null else Mentor()) } Log.d("mentorDashboard","username is : $username") mentorViewModel.getProfile(username) val screenContext = LocalContext.current val updatingState = remember { mutableStateOf(false) } val mentorEither = mentorViewModel.mentor.collectAsState().value var oldPassword = "" val coroutineScope = rememberCoroutineScope() when (mentorEither) { is Either.Left -> { Toast.makeText( LocalContext.current, "Error in getting mentor : ${mentorEither.value}", Toast.LENGTH_LONG ).show() } is Either.Right -> { Log.d("viewMentor", "no error message") mentorState.value = mentorEither.value oldPassword = mentorEither.value.password UpdateMentorScreen(mentorEither.value) { updatedMentor -> Log.d("updateMentor", "these are new values ; $updatedMentor") coroutineScope.launch { Log.d("updateMentor", "Now updated : $updatedMentor") val updateSuccess = mentorViewModel.updateProfile(updatedMentor, oldPassword) if (updateSuccess) { mentorState.value = updatedMentor Toast.makeText(screenContext, "Updated Mentor", Toast.LENGTH_LONG).show() } else { Toast.makeText( screenContext, "Error in updating mentor", Toast.LENGTH_LONG ).show() } updatingState.value = false } } } null -> { Log.d("viewMentor", "Mentor either is null") } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/mentor/screens/MentorDashboardScreen.kt
1924238821
package com.nitc.projectsgc.composable.mentor.screens import android.util.Log import android.widget.Toast import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.ButtonDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import arrow.core.Either import com.nitc.projectsgc.composable.components.BasicButton import com.nitc.projectsgc.composable.components.CardInputFieldWithOptions import com.nitc.projectsgc.composable.components.CardInputFieldWithValue import com.nitc.projectsgc.composable.components.SimpleToast import com.nitc.projectsgc.composable.util.PathUtils import com.nitc.projectsgc.models.Mentor @Composable fun UpdateMentorScreen(mentorFound: Mentor, onUpdate: (mentor: Mentor) -> Unit) { val mentorState = remember { mutableStateOf(mentorFound) } val screenContext = LocalContext.current LazyColumn( verticalArrangement = Arrangement.spacedBy(20.dp), modifier = Modifier .fillMaxSize() .padding(top = 20.dp), horizontalAlignment = Alignment.CenterHorizontally ) { item { CardInputFieldWithValue( hint = "Name", text = mentorState.value!!.name, isPassword = false, modifier = Modifier.fillMaxWidth(0.75F) ) { newName -> mentorState.value = mentorState.value.copy(name = newName) } } item { CardInputFieldWithValue( hint = "Email", text = mentorState.value!!.email, isPassword = false, modifier = Modifier.fillMaxWidth(0.75F) ) { newEmail -> mentorState.value = mentorState.value!!.copy(email = newEmail) } } item { CardInputFieldWithValue( hint = "Username", text = mentorState.value!!.userName, isPassword = false, modifier = Modifier.fillMaxWidth(0.75F) ) { newUsername -> mentorState.value = mentorState.value!!.copy(userName = newUsername) } } item { CardInputFieldWithOptions( hint = "Phone Number", text = mentorState.value!!.phone, isPassword = false, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Phone ), modifier = Modifier.fillMaxWidth(0.75F) ) { newPhone -> mentorState.value = mentorState.value!!.copy(phone = newPhone) } } item { CardInputFieldWithValue( hint = "Password", text = mentorState.value!!.password, isPassword = false, modifier = Modifier.fillMaxWidth(0.75F) ) { newPassword -> mentorState.value = mentorState.value!!.copy(password = newPassword) Log.d("updateMentor", "mentor value now is ${mentorState.value.toString()}") } } item { Spacer(modifier = Modifier.size(20.dp)) BasicButton( text = if (mentorFound.name.isEmpty()) "Add" else "Update", colors = ButtonDefaults.buttonColors(), modifier = Modifier.padding(20.dp), tc = Color.White ) { Log.d("updateMentor", "Now updated : ${mentorState.value}") // updatingState.value = true val username = mentorState.value.userName when (val mentorTypeEither = PathUtils.getMentorType(username)) { is Either.Left -> { Toast.makeText( screenContext, mentorTypeEither.value.message!!, Toast.LENGTH_LONG ).show() } is Either.Right -> { mentorState.value = mentorState.value.copy( type = mentorTypeEither.value ) onUpdate(mentorState.value) } } // if(mentorFound.name.isEmpty()){ // } } } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/mentor/screens/UpdateMentorScreen.kt
1496628891
package com.nitc.projectsgc.composable.mentor.screens import android.util.Log import android.widget.Toast import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.DateRange import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.colorResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import arrow.core.Either import com.nitc.projectsgc.R import com.nitc.projectsgc.composable.components.DateDialog import com.nitc.projectsgc.composable.components.RemarkDialog import com.nitc.projectsgc.composable.mentor.MentorViewModel import com.nitc.projectsgc.composable.mentor.components.MentorAppointmentCard import com.nitc.projectsgc.composable.news.screens.showToast import com.nitc.projectsgc.models.Appointment import java.text.SimpleDateFormat import java.util.Date import java.util.Locale @Composable fun MentorAppointmentsScreen( username: String, mentorViewModel: MentorViewModel, recordCallback: (rollNo: String) -> Unit ) { val myContext = LocalContext.current val dateState = remember { mutableStateOf( SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(Date()).toString() ) } val isLoading = remember { mutableStateOf(true) } val dateDialogState = remember { mutableStateOf(false) } LaunchedEffect(dateState.value) { mentorViewModel.getMentorAppointments( username, dateState.value ) } val coroutineScope = rememberCoroutineScope() val appointmentsEither = mentorViewModel.appointments.collectAsState() val appointmentsState = remember { mutableStateOf(listOf<Appointment>()) } val completeAppointmentState = remember { mutableStateOf<Appointment?>(null) } val completeState = remember { mutableStateOf(false) } val cancelAppointmentState = remember { mutableIntStateOf(-1) } LaunchedEffect(key1 = cancelAppointmentState.intValue) { if (cancelAppointmentState.intValue != -1) { val cancelled = mentorViewModel.cancelAppointment(appointmentsState.value[cancelAppointmentState.intValue]) if (cancelled) { showToast("Cancelled appointment", myContext) } else { showToast("Could not cancel the appointment", myContext) } cancelAppointmentState.intValue = -1 mentorViewModel.getMentorAppointments(username, dateState.value) } } LaunchedEffect(key1 = completeState.value) { Log.d("completeAppointment","Calling method with value ${completeAppointmentState.value}") if (completeState.value && completeAppointmentState.value != null) { val completed = mentorViewModel.completeAppointment(completeAppointmentState.value!!) if (completed) { showToast("Completed appointment", myContext) } else { showToast("Error in completing this appointment", myContext) } completeState.value = false completeAppointmentState.value = null mentorViewModel.getMentorAppointments(username, dateState.value) } } LaunchedEffect(appointmentsEither.value) { Log.d("mentorDashboard", "apointments changed") when (val appointmentsEitherState = appointmentsEither.value) { is Either.Right -> { if (appointmentsEitherState.value.isEmpty()) { Toast.makeText( myContext, "No appointments found for given date", Toast.LENGTH_SHORT ).show() } else { appointmentsState.value = appointmentsEitherState.value Log.d("mentorDashboard", "Appointments got") isLoading.value = false } } is Either.Left -> { Toast.makeText( myContext, (appointmentsEitherState.value), Toast.LENGTH_SHORT ).show() isLoading.value = false } null -> { isLoading.value = false // Toast.makeText( // myContext, // "Error in accessing appointments", // Toast.LENGTH_SHORT // ).show() } } } Box(modifier = Modifier.fillMaxSize()) { if (isLoading.value) CircularProgressIndicator(Modifier.fillMaxSize()) LazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp) ) { items(count = appointmentsState.value.size, itemContent = { index -> MentorAppointmentCard( appointment = appointmentsState.value[index], mentorViewModel = mentorViewModel, completeCallback = { completeAppointmentState.value = appointmentsState.value[index] }, viewPastRecordCallback = { recordCallback(appointmentsState.value[index].studentID) }, cancelCallback = { cancelAppointmentState.intValue = index }) }) } FloatingActionButton( onClick = { dateDialogState.value = true }, shape = RoundedCornerShape(25), containerColor = colorResource(id = R.color.navy_blue), modifier = Modifier .align(Alignment.BottomEnd) .padding(10.dp) .clip(RoundedCornerShape(25)) .background(colorResource(id = R.color.navy_blue)) ) { if (dateDialogState.value) { DateDialog( heading = "Choose Date", isVisible = dateDialogState.value ) { dateChosen -> dateState.value = dateChosen Log.d("dateChosen", "Date chosen value + ${dateState.value}") dateDialogState.value = false } } Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.background(Color.Transparent) ) { Icon(Icons.Filled.DateRange, "Choose Date", tint = Color.White) Text( text = dateState.value, color = Color.White, modifier = Modifier.padding(horizontal = 7.dp) ) } } } if (completeAppointmentState.value != null && !completeState.value) { RemarkDialog(value = "", closeDialog = { completeAppointmentState.value = null }) { remark -> completeAppointmentState.value = completeAppointmentState.value!!.copy(remarks = remark) completeState.value = true Log.d("completeAppointment","Setting it to true") } } } @Preview @Composable fun MentorAppointmentsPreview() { }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/mentor/screens/MentorAppointmentsScreen.kt
2489593746
package com.nitc.projectsgc.composable.mentor.screens import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import arrow.core.Either import com.nitc.projectsgc.composable.mentor.MentorViewModel import com.nitc.projectsgc.composable.mentor.components.PastRecordCard import com.nitc.projectsgc.composable.news.screens.showToast import com.nitc.projectsgc.composable.student.components.BookedAppointmentCard import com.nitc.projectsgc.models.Appointment @Composable fun PastRecordScreen( mentorViewModel: MentorViewModel, rollNo: String, username: String ) { val myContext = LocalContext.current val isLoading = remember { mutableStateOf(true) } LaunchedEffect(Unit) { mentorViewModel.getStudentPastRecord(username, rollNo) } val pastRecordEitherState by mentorViewModel.pastRecord.collectAsState() val pastRecordState = remember { mutableStateOf(listOf<Appointment>()) } when (val pastRecordEither = pastRecordEitherState) { is Either.Left -> { showToast(pastRecordEither.value, myContext) } is Either.Right -> { pastRecordState.value = pastRecordEither.value } null -> { } } LazyColumn( modifier = Modifier.fillMaxSize() ) { items( count = pastRecordState.value.size, itemContent = { index -> PastRecordCard( appointment = pastRecordState.value[index] ) }) } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/mentor/screens/PastRecordScreen.kt
1372818521
package com.nitc.projectsgc.composable.mentor.components import android.util.Log import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import arrow.core.Either import com.nitc.projectsgc.R import com.nitc.projectsgc.composable.components.NormalText import com.nitc.projectsgc.composable.components.SubHeadingText import com.nitc.projectsgc.composable.mentor.MentorViewModel import com.nitc.projectsgc.models.Appointment import com.nitc.projectsgc.models.Student //@Preview //@Composable //fun MentorAppointmentCardPreview() { // MentorAppointmentCard( // appointment = Appointment( // date = "24/11/2111", // mentorID = "sakshi_health_2", // mentorName = "Sakshi", // studentID = "prashant_m210704ca", // status = "Booked", // remarks = "", // problemDescription = "This is the problem hsdfhs dfhsdf h", // rescheduled = false, // timeSlot = "4-5", // mentorType = "Success" // ), // studentRoll = "m210704ca", // {}, // {}, // {}, // ) //} @OptIn(ExperimentalFoundationApi::class) @Composable fun MentorAppointmentCard( appointment: Appointment, mentorViewModel: MentorViewModel, completeCallback: () -> Unit, viewPastRecordCallback: () -> Unit, cancelCallback: () -> Unit, ) { Log.d("getStudent", "in the mentor appointment card") LaunchedEffect(Unit) { mentorViewModel.getStudent(appointment.studentID) } val studentEitherState by mentorViewModel.student.collectAsState() val studentState = remember { mutableStateOf(Student()) } when (val studentEither = studentEitherState) { is Either.Left -> { Log.d("getStudent", studentEither.value) } is Either.Right -> { Log.d("getStudent", "Student either value = ${studentEither.value}") studentState.value = studentEither.value ShowMentorAppointmentCard( appointment, studentState.value, completeCallback, viewPastRecordCallback, cancelCallback ) } null -> { } } // Surface( // modifier = Modifier // .fillMaxWidth() // .padding(7.dp) // .clip( // RoundedCornerShape(15) // ) // .height(intrinsicSize = IntrinsicSize.Min) // .background(colorResource(id = R.color.lavender)) // ) { } @OptIn(ExperimentalFoundationApi::class, ExperimentalComposeUiApi::class) @Composable fun ShowMentorAppointmentCard( appointment: Appointment, student: Student, completeCallback: () -> Unit, viewPastRecordCallback: () -> Unit, cancelCallback: () -> Unit ) { val optionsMenuState = remember { mutableStateOf(false) } // var pointerOffset = Offset.Zero // // // val cardHeight = remember { // mutableStateOf(0) // } // val cardWidth = remember { // mutableStateOf(0) // } Card( modifier = Modifier // .onSizeChanged {size-> // cardHeight.value = size.height // cardWidth.value = size.width // } .combinedClickable( onClick = { }, onLongClick = { optionsMenuState.value = true } ) // .pointerInteropFilter { // pointerOffset = Offset(it.x, it.y) //// Log.d("pointerOffset","x = ${it.x} and y = ${it.y}") // false // } .fillMaxWidth(), colors = CardDefaults.cardColors(containerColor = colorResource(id = R.color.lavender)), shape = RoundedCornerShape(10) ) { Box( contentAlignment = Alignment.TopStart, modifier = Modifier .fillMaxWidth() .padding(5.dp) .background(colorResource(id = R.color.lavender)) ) { Column( modifier = Modifier .background(colorResource(id = R.color.lavender)), horizontalAlignment = Alignment.CenterHorizontally ) { Row( modifier = Modifier .fillMaxWidth() .padding(top = 15.dp) .background(Color.Transparent), verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.SpaceEvenly ) { Image( modifier = Modifier .height(70.dp) .clip(RoundedCornerShape(50)), painter = painterResource(id = R.drawable.boy_face), contentDescription = "Mentor image" ) Spacer(modifier = Modifier.size(5.dp)) Column( verticalArrangement = Arrangement.Top, ) { Spacer(modifier = Modifier.size(5.dp)) SubHeadingText( text = student.name, fontColor = Color.Black, modifier = Modifier ) Spacer(modifier = Modifier.size(5.dp)) Text( text = student.rollNo, color = Color.Black, modifier = Modifier, fontSize = 17.sp ) Spacer(modifier = Modifier.size(5.dp)) Text(text = student.phoneNumber, color = Color.Black, fontSize = 16.sp) } Spacer(modifier = Modifier.size(15.dp)) Column( verticalArrangement = Arrangement.SpaceBetween, horizontalAlignment = Alignment.CenterHorizontally ) { Spacer(modifier = Modifier.size(5.dp)) Row { NormalText( text = "DOB : ", fontColor = Color.Black, modifier = Modifier ) NormalText( text = student.dateOfBirth, fontColor = Color.Black, modifier = Modifier ) } Spacer(modifier = Modifier.size(15.dp)) Row( verticalAlignment = Alignment.CenterVertically ) { SubHeadingText( text = "Time : ", fontColor = Color.Black, modifier = Modifier ) Spacer(modifier = Modifier.size(5.dp)) Text(text = appointment.timeSlot, color = Color.Black, fontSize = 16.sp) } } } Card( modifier = Modifier .padding(5.dp) .fillMaxWidth(0.8F), colors = CardDefaults.cardColors( containerColor = colorResource(id = R.color.light_gray) ) ) { SubHeadingText( text = appointment.problemDescription, fontColor = Color.Black, modifier = Modifier.padding(15.dp) ) } Card( modifier = Modifier.padding(5.dp), colors = CardDefaults.cardColors( containerColor = colorResource(id = R.color.ivory) ), elevation = CardDefaults.cardElevation(1.dp), shape = RoundedCornerShape(40), ) { SubHeadingText( text = appointment.status, fontColor = Color.Black, modifier = Modifier .padding(20.dp) .align(Alignment.CenterHorizontally) ) } } DropdownMenu( modifier = Modifier.background(Color.White), // offset = DpOffset((pointerOffset.x % cardWidth.value).dp, (pointerOffset.y % cardHeight.value).dp), expanded = optionsMenuState.value, onDismissRequest = { optionsMenuState.value = false }) { DropdownMenuItem(text = { SubHeadingText( text = "View Past Record", fontColor = Color.Black, modifier = Modifier ) }, onClick = { viewPastRecordCallback() optionsMenuState.value = false }) if (!appointment.cancelled && !appointment.completed) { DropdownMenuItem(text = { SubHeadingText( text = "Complete", fontColor = Color.Black, modifier = Modifier ) }, onClick = { completeCallback() optionsMenuState.value = false }) DropdownMenuItem(text = { SubHeadingText( text = "Cancel", fontColor = Color.Black, modifier = Modifier ) }, onClick = { cancelCallback() optionsMenuState.value = false }) } } } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/mentor/components/MentorAppointmentCard.kt
711806714
package com.nitc.projectsgc.composable.mentor.components import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import com.nitc.projectsgc.R import com.nitc.projectsgc.composable.components.CardFieldWithValue import com.nitc.projectsgc.composable.components.NormalText import com.nitc.projectsgc.models.Appointment @Composable fun PastRecordCard( appointment: Appointment ) { Box( modifier = Modifier .fillMaxWidth() .padding(5.dp) .clip( RoundedCornerShape(15) ) .background(colorResource(id = R.color.lavender)) ) { Card( modifier = Modifier .background(colorResource(id = R.color.lavender)) .padding(5.dp) .align(Alignment.TopCenter) .fillMaxWidth() ) { Column( modifier = Modifier .background(colorResource(id = R.color.lavender)), horizontalAlignment = Alignment.CenterHorizontally ) { Row( modifier = Modifier .fillMaxWidth() .height(130.dp) .padding(top = 5.dp) .background(Color.Transparent), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceEvenly ) { Image( modifier = Modifier .fillMaxHeight(0.65F) .clip(RoundedCornerShape(50)), painter = painterResource(id = R.drawable.boy_face), contentDescription = "Mentor image" ) Spacer(modifier = Modifier.size(15.dp)) Column( modifier = Modifier.fillMaxHeight(), verticalArrangement = Arrangement.SpaceEvenly, ) { // Spacer(modifier = Modifier.size(10.dp)) NormalText( text = appointment.mentorName, fontColor = Color.Black, modifier = Modifier ) // Spacer(modifier = Modifier.size(15.dp)) Row( verticalAlignment = Alignment.CenterVertically ) { NormalText( text = "Time : ", fontColor = Color.Black, modifier = Modifier ) Spacer(modifier = Modifier.size(5.dp)) NormalText( text = appointment.timeSlot, fontColor = Color.Black, modifier = Modifier ) } } Spacer(modifier = Modifier.size(15.dp)) Column( modifier = Modifier.fillMaxHeight(), verticalArrangement = Arrangement.SpaceEvenly, horizontalAlignment = Alignment.CenterHorizontally ) { // Spacer(modifier = Modifier.size(10.dp)) Text( text = appointment.date, color = Color.Black, modifier = Modifier ) // Spacer(modifier = Modifier.size(15.dp)) Row( verticalAlignment = Alignment.CenterVertically ) { NormalText( text = "Type : ", fontColor = Color.Black, modifier = Modifier ) Spacer(modifier = Modifier.size(5.dp)) Text( text = appointment.mentorType, color = Color.Black, modifier = Modifier ) } } } Card( modifier = Modifier.padding(5.dp), colors = CardDefaults.cardColors( containerColor = colorResource(id = R.color.ivory) ), elevation = CardDefaults.cardElevation(2.dp), shape = RoundedCornerShape(40), ) { NormalText( text = appointment.status, fontColor = Color.Black, modifier = Modifier .padding(20.dp) .align(Alignment.CenterHorizontally) ) } if (appointment.completed) { CardFieldWithValue( hint = "Remarks", text = appointment.remarks, modifier = Modifier.padding(horizontal = 10.dp).fillMaxWidth(0.85F) ) } } } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/mentor/components/PastRecordCard.kt
1847293376
package com.nitc.projectsgc.composable.mentor import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import arrow.core.Either import com.nitc.projectsgc.composable.mentor.repo.MentorRepo import com.nitc.projectsgc.models.Appointment import com.nitc.projectsgc.models.Mentor import com.nitc.projectsgc.models.Student import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject @HiltViewModel class MentorViewModel @Inject constructor( private val mentorRepo: MentorRepo, ) :ViewModel() { private val _appointments = MutableStateFlow<Either<String,List<Appointment>>?>(Either.Right( emptyList() )) val appointments: StateFlow<Either<String, List<Appointment>>?> = _appointments.asStateFlow() private val _mentor = MutableStateFlow<Either<String, Mentor>?>(null) val mentor: StateFlow<Either<String, Mentor>?> = _mentor.asStateFlow() private val _student = MutableStateFlow<Either<String, Student>?>(null) val student: StateFlow<Either<String, Student>?> = _student.asStateFlow() fun deleteMentorValue(){ _mentor.value = null } fun deleteStudentValue(){ _student.value = null } fun getStudent(rollNo:String){ viewModelScope.launch { _student.value = mentorRepo.getStudent(rollNo) } } fun getProfile(username: String) { viewModelScope.launch { _mentor.value = mentorRepo.getProfile(username) } } suspend fun cancelAppointment(appointment: Appointment):Boolean{ val cancelled = withContext(Dispatchers.Main){ mentorRepo.cancelAppointment(appointment) } return cancelled } suspend fun completeAppointment(appointment: Appointment):Boolean{ val completed = withContext(Dispatchers.Main){ mentorRepo.giveRemarks(appointment) } return completed } suspend fun updateProfile(mentor: Mentor, oldPassword: String): Boolean { val updateSuccess = withContext(Dispatchers.Main) { Log.d("updateMentor", "In adminViewmodel") if (mentorRepo.updateProfile(mentor, oldPassword)) { Log.d("updateMentor", "Old password = $oldPassword") Log.d("updateMentor", "New password = ${mentor.password}") _mentor.value = Either.Right(mentor) true } else false } return updateSuccess } fun deleteMentorAppointments(){ _appointments.value = null } fun getMentorAppointments(username:String,today: String){ viewModelScope.launch { deleteMentorAppointments() _appointments.value = mentorRepo.getTodayAppointments(username, today) } } private val _pastRecord = MutableStateFlow<Either<String,List<Appointment>>?>(Either.Right( emptyList() )) val pastRecord: StateFlow<Either<String, List<Appointment>>?> = _pastRecord.asStateFlow() fun deleteStudentPastRecordValue(){ _pastRecord.value = null } fun getStudentPastRecord(username:String,rollNo: String){ viewModelScope.launch { _pastRecord.value = mentorRepo.getStudentRecord(username, rollNo) } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/mentor/MentorViewModel.kt
3169407625
package com.nitc.projectsgc.composable.mentor import com.nitc.projectsgc.composable.admin.repo.StudentsRepo import com.nitc.projectsgc.composable.mentor.repo.MentorRepo import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ViewModelComponent import dagger.hilt.android.scopes.ViewModelScoped @Module @InstallIn(ViewModelComponent::class) object MentorModule { @Provides @ViewModelScoped fun provideMentorRepo(): MentorRepo { return MentorRepo() } @Provides @ViewModelScoped fun provideMentorViewModel(mentorRepo: MentorRepo): MentorViewModel { return MentorViewModel(mentorRepo) } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/mentor/MentorModule.kt
361783747
package com.nitc.projectsgc.composable.mentor.repo import android.util.Log import arrow.core.Either import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.MutableData import com.google.firebase.database.Transaction import com.google.firebase.database.ValueEventListener import com.nitc.projectsgc.composable.util.PathUtils import com.nitc.projectsgc.models.Appointment import com.nitc.projectsgc.models.Mentor import com.nitc.projectsgc.models.Student import java.time.LocalDate import java.time.format.DateTimeFormatter import javax.inject.Inject import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine class MentorRepo @Inject constructor() { suspend fun getStudent(studentID: String): Either<String, Student> { return suspendCoroutine { continuation -> var isResumed = false val database: FirebaseDatabase = FirebaseDatabase.getInstance() val reference: DatabaseReference = database.reference .child("students") Log.d("getStudent", "in getting studnet for mentor") reference.addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { try { var student = snapshot.child(studentID).getValue(Student::class.java) if (student != null) { if (!isResumed) { isResumed = true Log.d("getStudent", "got student : $student") continuation.resume(Either.Right(student)) } } else { if (!isResumed) { isResumed = true continuation.resume(Either.Left("Could not resolve student")) } } } catch (exc: Exception) { if (!isResumed) { isResumed = true continuation.resume(Either.Left("Error in getting student : $exc")) } } } override fun onCancelled(error: DatabaseError) { if (!isResumed) { isResumed = true continuation.resume(Either.Left("Error : $error")) } } }) } } suspend fun getProfile(username: String): Either<String, Mentor> { return suspendCoroutine { continuation -> var isResumed = false var database: FirebaseDatabase = FirebaseDatabase.getInstance() val mentorTypeEither = PathUtils.getMentorType(username) when (mentorTypeEither) { is Either.Left -> { if (!isResumed) { isResumed = true continuation.resume(Either.Left(mentorTypeEither.value.message!!)) } } is Either.Right -> { var reference: DatabaseReference = database.reference.child("types/${mentorTypeEither.value}/${username}") reference.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { try { val mentor = snapshot.getValue(Mentor::class.java) if (!isResumed) { isResumed = true continuation.resume(Either.Right(mentor!!)) } } catch (exc: Exception) { Log.d("getMentor", "Error in getting mentor : $exc") if (!isResumed) { isResumed = true continuation.resume(Either.Left("Error in getting mentor : $exc")) } } } override fun onCancelled(error: DatabaseError) { Log.d("getMentor", "Database Error : $error") if (!isResumed) { continuation.resume(Either.Left("Database error ; $error")) isResumed = true } } }) } } } } suspend fun updateProfile( mentor: Mentor, oldPassword: String ): Boolean { return suspendCoroutine { continuation -> Log.d("updateMentor", "In repo") var isResumed = false val database: FirebaseDatabase = FirebaseDatabase.getInstance() val reference: DatabaseReference = database.reference.child("types") when (val mentorTypeEither = PathUtils.getMentorType(mentor.userName)) { is Either.Left -> { if (!isResumed) { isResumed = true continuation.resume(false) } } is Either.Right -> { val mentorPath = "${mentorTypeEither.value}/${mentor.userName}" val auth: FirebaseAuth = FirebaseAuth.getInstance() reference.child(mentorPath).runTransaction(object : Transaction.Handler { override fun doTransaction(currentData: MutableData): Transaction.Result { return try { currentData.child("name").value = mentor.name currentData.child("userName").value = mentor.userName currentData.child("type").value = mentor.type currentData.child("email").value = mentor.email currentData.child("phone").value = mentor.phone currentData.child("password").value = mentor.password Transaction.success(currentData) } catch (excCasting: Exception) { if (!isResumed) { isResumed = true continuation.resume(false) } Transaction.abort() } } override fun onComplete( errorDatabase: DatabaseError?, committed: Boolean, currentData: DataSnapshot? ) { if (errorDatabase != null) { Log.d("updateStudent", "Error in updating student : $errorDatabase") if (!isResumed) { isResumed = true continuation.resume(false) } } else if (committed) { Log.d("updateMentor", "in add on success") if (mentor.password != oldPassword) { Log.d("updateMentor", "old password is not same") auth.signInWithEmailAndPassword(mentor.email, oldPassword) .addOnSuccessListener { loggedIn -> if (loggedIn != null) { val currentUser = FirebaseAuth.getInstance().currentUser if (currentUser != null) { currentUser.updatePassword(mentor.password) .addOnCompleteListener { task -> if (task.isSuccessful) { // Show success message to the user auth.signOut() Log.d( "updateMentor", "Updated mentor" ) if (!isResumed) { isResumed = true continuation.resume(true) } } else { // Password update failed, show error message to the user Log.d( "updateMentor", "Error in updating password of current user" ) if (!isResumed) { isResumed = true continuation.resume(false) } } } .addOnFailureListener { excUpdating -> Log.d( "updateMentor", "Error in updating mentor : $excUpdating" ) if (!isResumed) { isResumed = true continuation.resume(false) } } } else { Log.d( "updateMentor", "current user is null after logging in with old password" ) if (!isResumed) { isResumed = true continuation.resume(false) } } } else { Log.d( "updateMentor", "Error in logging in with old password" ) if (!isResumed) { isResumed = true continuation.resume(false) } } } .addOnFailureListener { excLogin -> Log.d( "updateMentor", "Error in logging in with old password : $excLogin" ) if (!isResumed) { isResumed = true continuation.resume(false) } } } else { if (!isResumed) { isResumed = true continuation.resume(true) } } } else { Log.d("updateMentor", "Transaction not committed") if (!isResumed) { isResumed = true continuation.resume(false) } } } }) } } } } suspend fun getTodayAppointments( username: String, today: String ): Either<String, ArrayList<Appointment>>? { return suspendCoroutine { continuation -> var database = FirebaseDatabase.getInstance() var isResumed = false when (val mentorTypeEither = PathUtils.getMentorType(username)) { is Either.Left -> { if (!isResumed) { isResumed = true continuation.resume(Either.Left(mentorTypeEither.value.message!!)) } } is Either.Right -> { var refString = "types/${mentorTypeEither.value}/${username}/appointments/${today}" Log.d("refString", refString) var reference = database.reference.child(refString) reference.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { var appointments = arrayListOf<Appointment>() for (timeSlot in snapshot.children) { Log.d("refString", timeSlot.key.toString()) try { appointments.add(timeSlot.getValue(Appointment::class.java)!!) } catch (excCasting: Exception) { Log.d("getAppointments", "Error in casting : $excCasting") continue } } val formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy") Log.d("appointmentsSize", appointments.size.toString()) val sortedAppointments = appointments.sortedBy { LocalDate.parse(it.date, formatter) } .toCollection(ArrayList<Appointment>()) Log.d("getAppointments", "Size : ${appointments.size}") if (!isResumed) { isResumed = true Log.d( "getAppointments", "Appointments : ${sortedAppointments.size}" ) continuation.resume(Either.Right(sortedAppointments)) } } override fun onCancelled(error: DatabaseError) { Log.d("getAppointments", "Error in database ; $error") if (!isResumed) { isResumed = true continuation.resume(Either.Left("Error in database ; $error")) } } }) } } } } suspend fun cancelAppointment(appointment: Appointment): Boolean { return suspendCoroutine { continuation -> appointment.cancelled = true appointment.status = "Cancelled by Mentor" var database = FirebaseDatabase.getInstance() var refString = "types/${appointment.mentorType}/${appointment.mentorID}/appointments/${appointment.date}/${appointment.timeSlot}" Log.d("refString", refString) var isResumed = false var mentorReference = database.reference .child(refString) var reference = database.reference mentorReference.setValue(appointment).addOnCompleteListener { cancelTask -> if (cancelTask.isSuccessful) { var studentRefString = "students/${appointment.studentID}/appointments/${appointment.id}" reference.child(studentRefString).setValue(appointment) .addOnCompleteListener { studentTask -> if (studentTask.isSuccessful) if (!isResumed) continuation.resume(true) else { if (!isResumed) { isResumed = true continuation.resume(false) } } } } else { if (!isResumed) { isResumed = true continuation.resume(false) } } }.addOnFailureListener { errCanceling -> Log.d("cancelAppointment", "Error in cancelling appointment : $errCanceling") if (!isResumed) { isResumed = true continuation.resume(false) } } } } suspend fun getStudentRecord( mentorUsername: String, studentID: String ): Either<String, ArrayList<Appointment>>? { return suspendCoroutine { continuation -> var isResumed = false var appointments = arrayListOf<Appointment>() var database = FirebaseDatabase.getInstance() var refString = "students/${studentID}/appointments" var mentorReference = database.reference .child(refString) mentorReference.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { for (ds in snapshot.children) { try { val appointment = ds.getValue(Appointment::class.java) if (appointment!!.mentorID != mentorUsername) { appointments.add(appointment) } }catch(excCasting:Exception){ Log.d("getStudentRecord","Error in casting appointment") continue } } val formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy") val sortedAppointments = appointments.sortedBy { LocalDate.parse(it.date, formatter) } .toCollection(ArrayList<Appointment>()) if (!isResumed){ isResumed = true continuation.resume(Either.Right(sortedAppointments)) } } override fun onCancelled(error: DatabaseError) { if (!isResumed){ isResumed = true continuation.resume(Either.Left("Error in database : $error")) } } }) } } suspend fun giveRemarks(appointment: Appointment): Boolean { return suspendCoroutine { continuation -> appointment.status = "Completed" appointment.completed = true var isResumed = false var database = FirebaseDatabase.getInstance() var refString = "students/${appointment.studentID}/appointments" var studentReference = database.reference .child(refString) studentReference.child(appointment.id.toString()).setValue(appointment) .addOnCompleteListener { task -> if (task.isSuccessful) { var mentorRefString = "types/${appointment.mentorType}/${appointment.mentorID}/appointments/${appointment.date}/${appointment.timeSlot}" var mentorReference = database.reference .child(mentorRefString) mentorReference.setValue(appointment).addOnCompleteListener { mentorTask -> if (mentorTask.isSuccessful) { if (!isResumed) { isResumed = true continuation.resume(true) } } else { if (!isResumed) { isResumed = true continuation.resume(false) } } } } else { if (!isResumed) { isResumed = true continuation.resume(false) } } }.addOnFailureListener { errGiveRemarks -> Log.d("giveRemarks", "Error in giving remarks : $errGiveRemarks") if (!isResumed) { isResumed = true continuation.resume(false) } } } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/mentor/repo/MentorRepo.kt
3114655263
package com.nitc.projectsgc.composable.components import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonColors import androidx.compose.material3.ButtonDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp @Composable fun BasicButton( text: String, colors: ButtonColors, tc: Color, modifier: Modifier, clickCallback: () -> Unit ) { Button( onClick = { clickCallback() }, shape = RoundedCornerShape(15.dp), colors = colors, modifier = modifier ) { HeadingText(text, tc, modifier = Modifier) } } @Composable fun BasicButtonWithState( text: String, colors: ButtonColors, tc: Color, enableState: MutableState<Boolean>, modifier: Modifier, clickCallback: () -> Unit ) { Button( enabled = enableState.value, onClick = { clickCallback() }, shape = RoundedCornerShape(15.dp), colors = colors, modifier = modifier ) { HeadingText(text, tc, modifier = Modifier) } } @Composable fun BasicButtonWithEnabled( text: String, colors: ButtonColors, tc: Color, enabled: Boolean, modifier: Modifier, clickCallback: () -> Unit ) { Button( enabled = enabled, onClick = { clickCallback() }, shape = RoundedCornerShape(15.dp), colors = colors, modifier = modifier ) { HeadingText(text, tc, modifier = Modifier) } } @Composable fun BasicSubHeadingButton( text: String, colors: ButtonColors, tc: Color, modifier: Modifier, clickCallback: () -> Unit ) { Button( onClick = { clickCallback() }, shape = RoundedCornerShape(15.dp), colors = colors, modifier = modifier ) { SubHeadingText(text, tc, modifier = Modifier) } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/components/Buttons.kt
2737996763
package com.nitc.projectsgc.composable.components import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.nitc.projectsgc.R import com.nitc.projectsgc.models.Mentor @Preview @Composable fun loadMentorCard() { // NewsCard( // date = "today", // mentorName = "Alex", // body = "htihsiodhf ohsodfho shfoshfd ohsiofd psh " // ) MentorCard( mentor = Mentor( "Name", "Phone", "email sdfsf", "Career", "password", "username" ), deleteCallback = {}, ) { } } @OptIn(ExperimentalFoundationApi::class) @Composable fun MentorCard( mentor: Mentor, deleteCallback: () -> Unit, clickCallback: () -> Unit ) { val deleteMenuState = remember { mutableStateOf(false) } Surface( modifier = Modifier .background(colorResource(id = R.color.white)) .padding(5.dp) .clip( RoundedCornerShape(15) ) .combinedClickable( onClick = { clickCallback() }, onLongClick = { deleteMenuState.value = true } ) .height(intrinsicSize = IntrinsicSize.Min) ) { Box( modifier = Modifier .background(colorResource(id = R.color.lavender)) .padding(5.dp), ) { Card( // padding = 10, // clickCallback = { //// clickCallback() // }, // optionsCallback = { //// deleteMenuState.value = true // } ) { Box( modifier = Modifier .fillMaxSize() .background(colorResource(id = R.color.lavender)) ) { Row( modifier = Modifier.align(Alignment.CenterStart) ) { Image( modifier = Modifier .size(70.dp) .clip(RoundedCornerShape(50)), painter = painterResource(id = R.drawable.boy_face), contentDescription = "Mentor Photo" ) Spacer(modifier = Modifier.size(20.dp)) Column( modifier = Modifier .fillMaxHeight() .background(Color.Transparent) ) { Spacer(modifier = Modifier.size(5.dp)) SubHeadingText( text = mentor.name, fontColor = Color.Black, modifier = Modifier ) Spacer(modifier = Modifier.size(5.dp)) Text(text = mentor.email, color = Color.Black) Spacer(modifier = Modifier.size(5.dp)) Text( text = mentor.phone, color = Color.Black, modifier = Modifier ) } } SubHeadingText( text = mentor.type, fontColor = Color.Black, modifier = Modifier.align( Alignment.TopEnd ) ) } } DropdownMenu( modifier = Modifier.align(Alignment.BottomEnd).background(Color.White), expanded = deleteMenuState.value, onDismissRequest = { deleteMenuState.value = false }) { // DropdownMenuItem(text = { // SubHeadingText( // text = "Appointments", // fontColor = Color.Black, // modifier = Modifier // ) // }, onClick = { // }) DropdownMenuItem(text = { SubHeadingText(text = "Delete", fontColor = Color.Black, modifier = Modifier) }, onClick = { deleteMenuState.value = false deleteCallback() }) } } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/components/MentorCard.kt
3332453425
package com.nitc.projectsgc.composable.components import androidx.compose.foundation.background import androidx.compose.foundation.layout.padding import androidx.compose.material3.Card import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @Composable fun HeadingText(text: String, fontColor: Color,modifier: Modifier) { Text( text = text, fontSize = 21.sp, fontWeight = FontWeight.Medium, color = fontColor, modifier = modifier ) } @Composable fun SubHeadingText(text: String, fontColor: Color,modifier: Modifier) { Text( text = text, fontSize = 18.sp, fontWeight = FontWeight.Medium, color = fontColor, modifier = modifier ) } @Composable fun NormalText(text: String, fontColor: Color,modifier: Modifier) { Text( text = text, fontSize = 16.sp, fontWeight = FontWeight.Medium, color = fontColor, modifier = modifier ) } @Composable fun HeadingCard(text: String, bg: Color, fontColor: Color) { Card( modifier = Modifier.background(bg).padding(10.dp) ) { HeadingText(text = text, fontColor = fontColor,modifier = Modifier) } } @Preview @Composable fun PreviewHeading() { HeadingCard(text = "Text", bg = Color.White, fontColor = Color.Black) }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/components/Heading.kt
1907678439
package com.nitc.projectsgc.composable.components import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.colorResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.nitc.projectsgc.R import com.nitc.projectsgc.models.Mentor @Preview @Composable fun loadNewsCard() { // NewsCard( // date = "today", // mentorName = "Alex", // body = "htihsiodhf ohsodfho shfoshfd ohsiofd psh " // ) NewsCard("date", "Mentor name", "Body of the news"){} } @Composable fun NewsCard( date: String, mentorName: String, body: String, clickCallback: () -> Unit ) { val dropDownState = remember { mutableStateOf(false) } Card( onClick = { dropDownState.value = true }, elevation = CardDefaults.cardElevation(2.dp), border = BorderStroke(1.dp, color = Color.Black), shape = RoundedCornerShape(10), modifier = Modifier.padding(5.dp), colors = CardDefaults.cardColors( containerColor = Color.White, contentColor = Color.White, disabledContainerColor = Color.White, disabledContentColor = Color.White ) ) { Box { Column( modifier = Modifier .fillMaxWidth() .padding(10.dp) .background(Color.White) ) { Box( modifier = Modifier .fillMaxWidth() .background(Color.White), ) { SubHeadingText( text = date, fontColor = Color.Black, modifier = Modifier.align( Alignment.CenterStart ) ) Row( modifier = Modifier.align(Alignment.CenterEnd), verticalAlignment = Alignment.CenterVertically ) { SubHeadingText(text = "By", fontColor = Color.Black, modifier = Modifier) Spacer(modifier = Modifier.size(10.dp)) Text( text = mentorName, color = Color.Black, fontSize = 15.sp ) } } Spacer(modifier = Modifier.size(35.dp)) Card( modifier = Modifier.align(Alignment.CenterHorizontally), colors = CardDefaults.cardColors( containerColor = colorResource(id = R.color.light_gray) ), elevation = CardDefaults.cardElevation(2.dp) ) { Text( text = body, color = Color.Black, modifier = Modifier.padding(10.dp), fontSize = 15.sp ) } Spacer(modifier = Modifier.size(15.dp)) } DropdownMenu( modifier = Modifier.background(Color.White), expanded = dropDownState.value, onDismissRequest = { dropDownState.value = false }) { DropdownMenuItem(text = { SubHeadingText( text = "Delete", fontColor = Color.Black, modifier = Modifier ) }, onClick = { clickCallback() dropDownState.value = false }) } } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/components/NewsCard.kt
3718680069
package com.nitc.projectsgc.composable.components import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Cancel import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.DatePicker import androidx.compose.material3.DatePickerDialog import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.rememberDatePickerState import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.colorResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.window.Dialog import arrow.core.Either import com.nitc.projectsgc.R import com.nitc.projectsgc.composable.student.screens.showToast import com.nitc.projectsgc.composable.student.viewmodels.BookingViewModel import com.nitc.projectsgc.composable.util.DateUtils import com.nitc.projectsgc.models.Appointment @Composable fun RemarkDialog(value: String, closeDialog: () -> Unit, giveRemark: (String) -> Unit) { val txtFieldError = remember { mutableStateOf("") } val txtField = remember { mutableStateOf(value) } val dialogContext = LocalContext.current Dialog(onDismissRequest = { closeDialog() }) { Surface( shape = RoundedCornerShape(16.dp), color = Color.White, shadowElevation = 0.dp ) { Box( contentAlignment = Alignment.Center ) { Column( modifier = Modifier.padding(20.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Text( text = "Complete Appointment", style = TextStyle( fontSize = 21.sp, fontFamily = FontFamily.Default, fontWeight = FontWeight.Bold ) ) Icon( imageVector = Icons.Filled.Cancel, contentDescription = "", modifier = Modifier .width(30.dp) .height(30.dp) .clickable { closeDialog() } ) } Spacer(modifier = Modifier.height(20.dp)) CardInputFieldWithValue( modifier = Modifier .fillMaxWidth(), hint = "Remarks", isPassword = false, text = "", onValueChanged = {remarkInput-> txtField.value = remarkInput } ) Spacer(modifier = Modifier.height(20.dp)) // Box(modifier = Modifier.padding(40.dp, 0.dp, 40.dp, 0.dp)) { BasicButton( clickCallback = { if (txtField.value.isEmpty()) { txtFieldError.value = "Field can not be empty" showToast("Give some remark", dialogContext) } else { giveRemark(txtField.value) } }, tc = Color.White, colors = ButtonDefaults.buttonColors( containerColor = colorResource(id = R.color.navy_blue) ), modifier = Modifier, text = "Done" ) // } } } } } } // //@Preview //@Composable //fun RemarkDialogPreview(){ // RemarkDialog(value = "Remarks", setShowDialog = {}) { // // } //} //@Preview //@Composable //fun DateDialogPreview(){ // DateDialog("Reschedule",true) { // // } //} @OptIn(ExperimentalMaterial3Api::class) @Composable fun DateDialog( heading: String, isVisible: Boolean, dateSelected: (String) -> Unit ) { val datePickerState = rememberDatePickerState() val dateState = remember { mutableStateOf("") } val dateDialogState = remember { mutableStateOf(isVisible) } if (dateDialogState.value) { DatePickerDialog( modifier = Modifier.fillMaxSize(1F), shape = RoundedCornerShape(5), onDismissRequest = { dateDialogState.value = false }, confirmButton = { if (datePickerState.selectedDateMillis != null) { dateState.value = DateUtils().dateToString(datePickerState.selectedDateMillis!!) dateDialogState.value = false dateSelected(dateState.value) } else { // Toast.makeText(LocalContext.current,"Select date first",Toast.LENGTH_LONG).show() } }) { DatePicker( state = datePickerState, modifier = Modifier.fillMaxSize().padding(10.dp), title = { HeadingText(text = heading, fontColor = Color.Black, modifier = Modifier) }, headline = { Text(dateState.value) }, showModeToggle = true ) } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun RescheduleDialog( oldAppointment: Appointment, onDismiss: () -> Unit, bookingViewModel: BookingViewModel ) { val appointmentState = remember { mutableStateOf(oldAppointment) } val dateState = remember { mutableStateOf(false) } val timeSlotsDropdownState = remember { mutableStateOf(false) } val timeSlotsState = remember { mutableStateOf(emptyList<String>()) } val rescheduleAppointmentState = remember { mutableStateOf(false) } val getTimeSlotsState = remember { mutableStateOf(false) } val bookingContext = LocalContext.current val timeSlotsEitherState by bookingViewModel.availableTimeSlots.collectAsState() LaunchedEffect(getTimeSlotsState.value) { if (getTimeSlotsState.value) { bookingViewModel.getAvailableTimeSlots( appointmentState.value.mentorType, appointmentState.value.mentorID, appointmentState.value.date ) } } LaunchedEffect(key1 = timeSlotsEitherState) { if (getTimeSlotsState.value) { getTimeSlotsState.value = false when (val timeSlotsEither = timeSlotsEitherState) { is Either.Right -> { timeSlotsState.value = timeSlotsEither.value timeSlotsDropdownState.value = true } is Either.Left -> { showToast( timeSlotsEither.value, bookingContext ) } null -> { showToast( "Error in getting time slots", bookingContext, ) } } } } LaunchedEffect(key1 = rescheduleAppointmentState.value) { if(rescheduleAppointmentState.value){ val rescheduled = bookingViewModel.rescheduleAppointment(oldAppointment,appointmentState.value) if (rescheduled) { showToast("Rescheduled your appointment", bookingContext) onDismiss() } else { showToast("Error in rescheduling your appointment", bookingContext) } } } ModalBottomSheet( modifier = Modifier .fillMaxSize(), onDismissRequest = { onDismiss() }, sheetState = rememberModalBottomSheetState(false), ) { Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally ) { HeadingText( text = "Reschedule Appointment", fontColor = Color.Black, modifier = Modifier ) Spacer(modifier = Modifier.size(15.dp)) Row( modifier = Modifier.fillMaxWidth(0.8F), horizontalArrangement = Arrangement.SpaceEvenly ) { BasicSubHeadingButton( text = appointmentState.value.mentorType, tc = Color.White, colors = ButtonDefaults.buttonColors( containerColor = colorResource(id = R.color.navy_blue) ), clickCallback = { }, modifier = Modifier ) BasicSubHeadingButton( clickCallback = { }, text = appointmentState.value.mentorName, modifier = Modifier, tc = Color.Black, colors = ButtonDefaults.buttonColors(containerColor = colorResource(id = R.color.light_gray)) ) } Spacer(modifier = Modifier.size(15.dp)) BasicSubHeadingButton( text = appointmentState.value.date.ifEmpty { "Select Date" }, colors = ButtonDefaults.buttonColors(), tc = Color.White, modifier = Modifier ) { dateState.value = true } if (dateState.value) { DateDialog( heading = "Book for date", isVisible = dateState.value ) { dateChosen -> appointmentState.value = appointmentState.value.copy(date = dateChosen) dateState.value = false } } Spacer(modifier = Modifier.size(15.dp)) Box(modifier = Modifier) { BasicSubHeadingButton( text = appointmentState.value.timeSlot.ifEmpty { "Select Time Slot" }, colors = ButtonDefaults.buttonColors(), tc = Color.White, modifier = Modifier ) { if (appointmentState.value.mentorID.isNotEmpty() && appointmentState.value.date.isNotEmpty() && appointmentState.value.mentorType.isNotEmpty()) { getTimeSlotsState.value = true timeSlotsDropdownState.value = true } else { showToast("Choose mentorship type and mentor first", bookingContext) } } if (!getTimeSlotsState.value && timeSlotsState.value.isNotEmpty()) { DropdownMenu(expanded = timeSlotsDropdownState.value, onDismissRequest = { timeSlotsDropdownState.value = false }) { if (timeSlotsState.value.isNotEmpty()) { timeSlotsState.value.forEachIndexed { index, timeSlot -> DropdownMenuItem(text = { SubHeadingText( text = timeSlot, fontColor = Color.Black, modifier = Modifier ) }, onClick = { appointmentState.value = appointmentState.value.copy(timeSlot = timeSlot) timeSlotsDropdownState.value = false }) } } else showToast( "No Time slots available for the given date", bookingContext ) } } } Spacer(modifier = Modifier.size(15.dp)) BasicSubHeadingButton( text = "Reschedule", colors = ButtonDefaults.buttonColors( containerColor = colorResource(id = R.color.navy_blue) ), tc = Color.White, modifier = Modifier ) { appointmentState.value = appointmentState.value.copy(status = "Rescheduled") rescheduleAppointmentState.value = true } } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/components/Dialogs.kt
2178050968
package com.nitc.projectsgc.composable.components import android.util.Log import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Divider import androidx.compose.material3.DividerDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ScrollableTabRow import androidx.compose.material3.Tab import androidx.compose.material3.TabRow import androidx.compose.material3.TabRowDefaults import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp @OptIn(ExperimentalFoundationApi::class) @Composable fun TabLayout( tabs: List<String>, fontColor: Color, bg: Color, pageChanged: @Composable (Int) -> Unit ) { var selectedTabIndex by remember { mutableStateOf(0) } val pagerState = rememberPagerState(initialPage = selectedTabIndex) { tabs.size } LaunchedEffect(pagerState.currentPage,pagerState.isScrollInProgress) { // if(!pagerState.isScrollInProgress) selectedTabIndex = pagerState.currentPage } LaunchedEffect(selectedTabIndex) { // Log.d("tabIndex","Tab index changed to ${selectedTabIndex}") pagerState.scrollToPage(selectedTabIndex) } Column(modifier = Modifier.fillMaxSize()) { TabRow( contentColor = Color.Black, containerColor = bg, selectedTabIndex = selectedTabIndex, modifier = Modifier.fillMaxWidth(), divider = { }, ) { tabs.forEachIndexed { index, tab -> Tab( selected = index == selectedTabIndex, onClick = { // Log.d("tabIndex","Clicked is $index") selectedTabIndex = index }, modifier = Modifier ) { SubHeadingText( text = tab, fontColor = fontColor, modifier = Modifier.padding(14.dp) ) } } } HorizontalPager( state = pagerState, modifier = Modifier.fillMaxSize(), verticalAlignment = Alignment.Top ) { pageIndex -> Box(modifier = Modifier.fillMaxSize()){ pageChanged(pageIndex) } } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/components/Tabs.kt
1922054786
package com.nitc.projectsgc.composable.components import android.widget.Toast import androidx.compose.foundation.layout.padding import androidx.compose.material3.Scaffold import androidx.compose.material3.Snackbar import androidx.compose.material3.SnackbarDuration import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp @Composable fun SimpleToast(message: String) { val context = LocalContext.current LaunchedEffect(true) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show() } } @Composable fun SimpleSnackBar( snackbarHostState: SnackbarHostState = remember { SnackbarHostState() }, text: String ) { val snackBarHostState = remember { SnackbarHostState() } SnackbarHost(hostState = snackBarHostState, modifier = Modifier.padding(5.dp)){ Snackbar( content = { Text(text = text) } ) } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/components/Alerts.kt
1119836043
package com.nitc.projectsgc.composable.components import androidx.compose.foundation.background import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.CardColors import androidx.compose.material3.CardDefaults import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.TextFieldColors import androidx.compose.material3.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp @Preview @Composable fun EmailInputField() { val emailValue = remember { mutableStateOf("") } BasicCard(15, 3, 1, 4, CardDefaults.cardColors()) { TextField( modifier = Modifier .background(Color.White) .padding(5.dp), value = emailValue.value, shape = RoundedCornerShape(25.dp), onValueChange = { emailValue.value = it }, label = { HeadingText(text = "Email", fontColor = Color.Black, modifier = Modifier) }, colors = TextFieldDefaults.colors( focusedTextColor = Color.Black, unfocusedTextColor = Color.DarkGray, focusedLabelColor = Color.Black, unfocusedLabelColor = Color.DarkGray, unfocusedContainerColor = Color.White ) ) } } @Composable fun CardInputFieldWithOptions( hint: String, text:String, isPassword: Boolean, modifier: Modifier, keyboardOptions: KeyboardOptions, onValueChanged: (String) -> Unit ) { val inputValue = remember { mutableStateOf(text) } BasicCard(15, 3, 0, 4,CardDefaults.cardColors( containerColor = Color.White, contentColor = Color.White )) { TextField( modifier = modifier, value = inputValue.value, shape = RoundedCornerShape(25.dp), onValueChange = { inputValue.value = it onValueChanged(it) }, label = { Text(text = hint, modifier = Modifier) }, visualTransformation = if (isPassword) PasswordVisualTransformation() else VisualTransformation.None, colors = TextFieldDefaults.colors( focusedContainerColor = Color.White, unfocusedContainerColor = Color.White, disabledContainerColor = Color.White ), keyboardOptions = keyboardOptions ) } } @Composable fun CardInputFieldWithValue( hint: String, text:String, isPassword: Boolean, modifier: Modifier, onValueChanged: (String) -> Unit ) { val inputValue = remember { mutableStateOf(text) } BasicCard(15, 3, 0, 7,CardDefaults.cardColors( containerColor = Color.White, contentColor = Color.White )) { TextField( modifier = modifier, value = inputValue.value, shape = RoundedCornerShape(25.dp), onValueChange = { inputValue.value = it onValueChanged(it) }, label = { Text(text = hint, modifier = Modifier) }, visualTransformation = if (isPassword) PasswordVisualTransformation() else VisualTransformation.None, colors = TextFieldDefaults.colors( focusedContainerColor = Color.White, unfocusedContainerColor = Color.White, disabledContainerColor = Color.White ) ) } } @Composable fun CardFieldWithValue( hint: String, text:String, modifier: Modifier, ) { BasicCard(15, 3, 0, 7,CardDefaults.cardColors( containerColor = Color.White, contentColor = Color.White )) { TextField( modifier = modifier, value = text, shape = RoundedCornerShape(25.dp), enabled = false, onValueChange = { }, label = { Text(text = hint, modifier = Modifier, color = Color.Black) }, colors = TextFieldDefaults.colors( focusedContainerColor = Color.White, unfocusedContainerColor = Color.White, disabledContainerColor = Color.White, unfocusedTextColor = Color.Black, focusedTextColor = Color.Black, unfocusedLabelColor = Color.Black, focusedLabelColor = Color.Black, disabledTextColor = Color.Black ) ) } } @Composable fun BasicInputFieldWithColors( hint: String, isPassword: Boolean, cardColors: CardColors, textFieldColors: TextFieldColors, onValueChanged: (String) -> Unit ) { val inputValue = remember { mutableStateOf("") } BasicCard(15, 3, 1, 4, cardColors) { TextField( modifier = Modifier .background(Color.White) .padding(5.dp), value = inputValue.value, shape = RoundedCornerShape(25.dp), onValueChange = { inputValue.value = it onValueChanged(it) }, label = { HeadingText(text = hint, fontColor = Color.Black, modifier = Modifier) }, visualTransformation = if (isPassword) PasswordVisualTransformation() else VisualTransformation.None, colors = textFieldColors ) } } @Composable fun BasicInputField(hint: String, isPassword: Boolean, onValueChanged: (String) -> Unit) { val passwordValue = remember { mutableStateOf("") } BasicCard(15, 3, 1, 4, CardDefaults.cardColors()) { TextField( modifier = Modifier .background(Color.White) .padding(5.dp), value = passwordValue.value, shape = RoundedCornerShape(25.dp), onValueChange = { passwordValue.value = it onValueChanged(it) }, label = { HeadingText(text = hint, fontColor = Color.Black, modifier = Modifier) }, visualTransformation = if (isPassword) PasswordVisualTransformation() else VisualTransformation.None, colors = TextFieldDefaults.colors( focusedTextColor = Color.Black, unfocusedTextColor = Color.Gray, focusedLabelColor = Color.Black, unfocusedLabelColor = Color.Gray, unfocusedContainerColor = Color.White ) ) } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/components/InputFields.kt
286971913
package com.nitc.projectsgc.composable.components import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.CardElevation import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.nitc.projectsgc.R import com.nitc.projectsgc.models.Mentor import com.nitc.projectsgc.models.Student @Preview @Composable fun loadStudentCard() { // NewsCard( // date = "today", // mentorName = "Alex", // body = "htihsiodhf ohsodfho shfoshfd ohsiofd psh " // ) StudentCard(student = Student( "Phone", "Name", "Career", "24/11/2311", "email sdfsf", "Male", "password", "248545345234" ), deleteCallback = {}, clickCallback = {}) } @OptIn(ExperimentalFoundationApi::class) @Composable fun StudentCard( student: Student, deleteCallback: () -> Unit, clickCallback: () -> Unit, ) { val deleteMenuState = remember { mutableStateOf(false) } Surface( modifier = Modifier .fillMaxWidth() .padding(5.dp) .height(intrinsicSize = IntrinsicSize.Min) .clip( RoundedCornerShape(15) ) .combinedClickable( onClick = { clickCallback() }, onLongClick = { deleteMenuState.value = true } ) .background(Color.Transparent) ) { Box( modifier = Modifier ) { Card( modifier = Modifier .background(colorResource(id = R.color.lavender)) .padding(10.dp) ) { Row( modifier = Modifier .fillMaxSize() .background(colorResource(id = R.color.lavender)), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Row( modifier = Modifier.background(Color.Transparent) ) { Image( modifier = Modifier .size(70.dp) .clip(RoundedCornerShape(50)), painter = if (student.gender == "Male") painterResource(id = R.drawable.boy_face) else painterResource( id = R.drawable.girl_face ), contentDescription = "Mentor Photo" ) Spacer(modifier = Modifier.size(20.dp)) Column( modifier = Modifier .fillMaxHeight() .background(Color.Transparent) ) { Spacer(modifier = Modifier.size(5.dp)) SubHeadingText( text = student.name, fontColor = Color.Black, modifier = Modifier ) Spacer(modifier = Modifier.size(5.dp)) Text(text = student.rollNo, color = Color.Black) Spacer(modifier = Modifier.size(5.dp)) Text( text = student.phoneNumber, color = Color.Black, modifier = Modifier ) // Spacer(modifier = Modifier.size(15.dp)) // Button( // onClick = { }, // shape = RoundedCornerShape(15.dp), // colors = ButtonDefaults.buttonColors( // containerColor = colorResource(id = R.color.purple_700) // ), // elevation = ButtonDefaults.buttonElevation(5.dp) // ) { // Text(text = "View Appointments", color = Color.White) // } } } Text( text = student.dateOfBirth, color = Color.Black, fontSize = 15.sp, modifier = Modifier.align(Alignment.Top) ) } } DropdownMenu(expanded = deleteMenuState.value, onDismissRequest = { deleteMenuState.value = false }) { DropdownMenuItem(text = { SubHeadingText(text = "Delete", fontColor = Color.Black, modifier = Modifier) }, onClick = { deleteMenuState.value = false deleteCallback() }) } } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/components/StudentCard.kt
1682917047
package com.nitc.projectsgc.composable.components import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Card import androidx.compose.material3.CardColors import androidx.compose.material3.CardDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @Preview @Composable fun loadLogin() { LoginCard { } } @OptIn(ExperimentalFoundationApi::class) @Composable fun ClickableCard( padding: Int, clickCallback: () -> Unit, optionsCallback: () -> Unit, content: @Composable () -> Unit ) { Card(modifier = Modifier .background(Color.Transparent) .fillMaxSize() .height(IntrinsicSize.Min) .padding(padding.dp) .combinedClickable( onClick = { clickCallback() }, onLongClick = { optionsCallback() } ) ) { content() } } @Composable fun LoginCard(userTypeCallback: (Int) -> Unit) { val userType = remember { mutableIntStateOf(0) } val unselectedTC = Color.Black val unselectedBG = Color.White val selectedTC = Color.White val selectedBG = Color.Black val userTypes = arrayOf( "Admin", "Student", "Mentor" ) BasicCustomCard( 50, 2, 1, CardDefaults.cardColors(), modifier = Modifier.height(50.dp).padding(horizontal = 25.dp) ) { Row( modifier = Modifier .background(Color.White) .padding(0.dp) .fillMaxHeight(), horizontalArrangement = Arrangement.spacedBy(10.dp) ) { userTypes.forEachIndexed { index, type -> Card( onClick = { userType.intValue = index userTypeCallback(userType.intValue) }, modifier = Modifier .padding(0.dp) .fillMaxHeight() .weight(1F), shape = RoundedCornerShape(50), colors = CardDefaults.cardColors( containerColor = if (userType.intValue == index) selectedBG else unselectedBG, ) ) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, modifier = Modifier .fillMaxHeight() .fillMaxWidth() ) { Text( text = type, fontSize = 18.sp, textAlign = TextAlign.Center, color = if (userType.intValue == index) selectedTC else unselectedTC, modifier = Modifier .align(Alignment.CenterVertically) ) } } } } } } @Composable fun BasicCustomCard( cr: Int, elevation: Int, stroke: Int, cardColors: CardColors, modifier: Modifier, content: @Composable () -> Unit ) { Card( modifier = modifier, border = BorderStroke(stroke.dp, Color.Black), shape = RoundedCornerShape(cr), elevation = CardDefaults.cardElevation(elevation.dp), colors = cardColors ) { content() } } @Composable fun BasicCard( cr: Int, elevation: Int, stroke: Int, padding: Int, cardColors: CardColors, content: @Composable () -> Unit ) { Card( modifier = Modifier .padding(padding.dp), border = BorderStroke(stroke.dp, Color.Black), shape = RoundedCornerShape(cr.dp), elevation = CardDefaults.cardElevation(elevation.dp), colors = cardColors ) { content() } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/components/Cards.kt
4147876279
package com.nitc.projectsgc.composable.news import android.util.Log import arrow.core.Either import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import com.nitc.projectsgc.composable.util.UserRole import com.nitc.projectsgc.models.News import javax.inject.Inject import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine class NewsRepo @Inject constructor(){ suspend fun addNews(userType:Int,news: News):Boolean{ return suspendCoroutine {continuation -> if(userType == UserRole.Admin || userType == UserRole.Mentor) { var database = FirebaseDatabase.getInstance() var reference = database.reference.child("news") var newsID = reference.push().key.toString() news.newsID = newsID reference.child(newsID).setValue(news).addOnCompleteListener { task -> if (task.isSuccessful) { continuation.resume(true) } else { continuation.resume(false) } } }else continuation.resume(false) } } suspend fun deleteNews(userType:Int,newsID:String):Boolean{ return suspendCoroutine {continuation -> if(userType == UserRole.Admin || userType == UserRole.Mentor) { var database = FirebaseDatabase.getInstance() var reference = database.reference.child("news") reference.child(newsID).removeValue().addOnCompleteListener { task -> if (task.isSuccessful) { continuation.resume(true) } else { continuation.resume(false) } } }else continuation.resume(false) } } suspend fun getNews(): Either<String,ArrayList<News>>{ return suspendCoroutine { continuation -> var database = FirebaseDatabase.getInstance() var reference = database.reference.child("news") var isResumed = false var newsArray = arrayListOf<News>() reference.addListenerForSingleValueEvent(object: ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { for ( ds in snapshot.children){ try{ val news = ds.getValue(News::class.java) newsArray.add(news!!) }catch(excCasting:Exception){ Log.d("getNews","Error in casting news : $excCasting") continue } } if(!isResumed){ isResumed = true continuation.resume(Either.Right(newsArray)) } } override fun onCancelled(error: DatabaseError) { if(!isResumed){ isResumed = true continuation.resume(Either.Left("Error in database : $error")) } } }) } } }
nitc_sgc_mvvm/app/src/main/java/com/nitc/projectsgc/composable/news/NewsRepo.kt
3637296330